@useorgx/openclaw-plugin 0.7.15 → 0.7.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dashboard/dist/assets/8pbG6uLK.js +1 -0
- package/dashboard/dist/assets/8pbG6uLK.js.br +0 -0
- package/dashboard/dist/assets/8pbG6uLK.js.gz +0 -0
- package/dashboard/dist/assets/B1LENRC8.js +212 -0
- package/dashboard/dist/assets/B1LENRC8.js.br +0 -0
- package/dashboard/dist/assets/B1LENRC8.js.gz +0 -0
- package/dashboard/dist/assets/{gZr_xKlA.js → BM75sh1f.js} +1 -1
- package/dashboard/dist/assets/BM75sh1f.js.br +0 -0
- package/dashboard/dist/assets/BM75sh1f.js.gz +0 -0
- package/dashboard/dist/assets/{CJjEAGFN.js → BYVYH9CH.js} +1 -1
- package/dashboard/dist/assets/BYVYH9CH.js.br +0 -0
- package/dashboard/dist/assets/BYVYH9CH.js.gz +0 -0
- package/dashboard/dist/assets/BkMrrjAv.js +1 -0
- package/dashboard/dist/assets/BkMrrjAv.js.br +0 -0
- package/dashboard/dist/assets/BkMrrjAv.js.gz +0 -0
- package/dashboard/dist/assets/BpF7v1Dk.js +1 -0
- package/dashboard/dist/assets/BpF7v1Dk.js.br +0 -0
- package/dashboard/dist/assets/BpF7v1Dk.js.gz +0 -0
- package/dashboard/dist/assets/{C9fvfXmS.js → Bv_86bUY.js} +1 -1
- package/dashboard/dist/assets/Bv_86bUY.js.br +0 -0
- package/dashboard/dist/assets/Bv_86bUY.js.gz +0 -0
- package/dashboard/dist/assets/{CFZ4Swr5.js → C3PrI8L7.js} +1 -1
- package/dashboard/dist/assets/C3PrI8L7.js.br +0 -0
- package/dashboard/dist/assets/C3PrI8L7.js.gz +0 -0
- package/dashboard/dist/assets/{C91KLKit.js → C6AqbA9J.js} +1 -1
- package/dashboard/dist/assets/C6AqbA9J.js.br +0 -0
- package/dashboard/dist/assets/C6AqbA9J.js.gz +0 -0
- package/dashboard/dist/assets/{7DhYqBrM.js → CUXb_4F3.js} +1 -1
- package/dashboard/dist/assets/CUXb_4F3.js.br +0 -0
- package/dashboard/dist/assets/CUXb_4F3.js.gz +0 -0
- package/dashboard/dist/assets/{3TtV4moZ.js → Cn8sRTkO.js} +1 -1
- package/dashboard/dist/assets/Cn8sRTkO.js.br +0 -0
- package/dashboard/dist/assets/Cn8sRTkO.js.gz +0 -0
- package/dashboard/dist/assets/{CnPC783_.js → D5IgXoTj.js} +1 -1
- package/dashboard/dist/assets/D5IgXoTj.js.br +0 -0
- package/dashboard/dist/assets/D5IgXoTj.js.gz +0 -0
- package/dashboard/dist/assets/DMKyYAtD.js +1 -0
- package/dashboard/dist/assets/DMKyYAtD.js.br +0 -0
- package/dashboard/dist/assets/DMKyYAtD.js.gz +0 -0
- package/dashboard/dist/assets/{CGj8kRhg.js → DXzpQUC0.js} +1 -1
- package/dashboard/dist/assets/DXzpQUC0.js.br +0 -0
- package/dashboard/dist/assets/DXzpQUC0.js.gz +0 -0
- package/dashboard/dist/assets/JDPvhd68.js +1 -0
- package/dashboard/dist/assets/JDPvhd68.js.br +0 -0
- package/dashboard/dist/assets/JDPvhd68.js.gz +0 -0
- package/dashboard/dist/assets/{3VwNyxUf.js → R6N_VVqm.js} +1 -1
- package/dashboard/dist/assets/R6N_VVqm.js.br +0 -0
- package/dashboard/dist/assets/R6N_VVqm.js.gz +0 -0
- package/dashboard/dist/assets/{CKrH5fYO.js → cEP7N1dn.js} +1 -1
- package/dashboard/dist/assets/cEP7N1dn.js.br +0 -0
- package/dashboard/dist/assets/cEP7N1dn.js.gz +0 -0
- package/dashboard/dist/assets/iLnvdWmW.css +1 -0
- package/dashboard/dist/assets/iLnvdWmW.css.br +0 -0
- package/dashboard/dist/assets/iLnvdWmW.css.gz +0 -0
- package/dashboard/dist/assets/{Ctw95IkC.js → konqMbVI.js} +1 -1
- package/dashboard/dist/assets/konqMbVI.js.br +0 -0
- package/dashboard/dist/assets/konqMbVI.js.gz +0 -0
- package/dashboard/dist/assets/{T2NFtzAv.js → wc6cgXzV.js} +1 -1
- package/dashboard/dist/assets/wc6cgXzV.js.br +0 -0
- package/dashboard/dist/assets/wc6cgXzV.js.gz +0 -0
- package/dashboard/dist/index.html +3 -3
- package/dashboard/dist/index.html.br +0 -0
- package/dashboard/dist/index.html.gz +0 -0
- package/dist/http/helpers/auto-continue-engine.d.ts +15 -0
- package/dist/http/helpers/auto-continue-engine.js +165 -0
- package/dist/http/helpers/mission-control.d.ts +3 -0
- package/dist/http/helpers/mission-control.js +38 -7
- package/dist/http/helpers/value-utils.d.ts +1 -1
- package/dist/http/helpers/value-utils.js +5 -2
- package/dist/http/index.js +3 -1
- package/dist/http/routes/chat.d.ts +1 -1
- package/dist/http/routes/chat.js +2 -2
- package/dist/http/routes/entities.js +60 -2
- package/dist/http/routes/entity-dynamic.js +49 -9
- package/dist/http/routes/live-snapshot.d.ts +10 -1
- package/dist/http/routes/live-snapshot.js +11 -3
- package/dist/http/routes/mission-control-actions.d.ts +6 -0
- package/dist/http/routes/mission-control-actions.js +33 -0
- package/package.json +1 -1
- package/dashboard/dist/assets/0RUEVzJa.js +0 -1
- package/dashboard/dist/assets/0RUEVzJa.js.br +0 -0
- package/dashboard/dist/assets/0RUEVzJa.js.gz +0 -0
- package/dashboard/dist/assets/3TtV4moZ.js.br +0 -0
- package/dashboard/dist/assets/3TtV4moZ.js.gz +0 -0
- package/dashboard/dist/assets/3VwNyxUf.js.br +0 -0
- package/dashboard/dist/assets/3VwNyxUf.js.gz +0 -0
- package/dashboard/dist/assets/7DhYqBrM.js.br +0 -0
- package/dashboard/dist/assets/7DhYqBrM.js.gz +0 -0
- package/dashboard/dist/assets/BVvffj0x.js +0 -1
- package/dashboard/dist/assets/BVvffj0x.js.br +0 -0
- package/dashboard/dist/assets/BVvffj0x.js.gz +0 -0
- package/dashboard/dist/assets/BiOgVMED.js +0 -1
- package/dashboard/dist/assets/BiOgVMED.js.br +0 -0
- package/dashboard/dist/assets/BiOgVMED.js.gz +0 -0
- package/dashboard/dist/assets/C91KLKit.js.br +0 -0
- package/dashboard/dist/assets/C91KLKit.js.gz +0 -0
- package/dashboard/dist/assets/C9fvfXmS.js.br +0 -0
- package/dashboard/dist/assets/C9fvfXmS.js.gz +0 -0
- package/dashboard/dist/assets/CFZ4Swr5.js.br +0 -0
- package/dashboard/dist/assets/CFZ4Swr5.js.gz +0 -0
- package/dashboard/dist/assets/CGj8kRhg.js.br +0 -0
- package/dashboard/dist/assets/CGj8kRhg.js.gz +0 -0
- package/dashboard/dist/assets/CJjEAGFN.js.br +0 -0
- package/dashboard/dist/assets/CJjEAGFN.js.gz +0 -0
- package/dashboard/dist/assets/CKrH5fYO.js.br +0 -0
- package/dashboard/dist/assets/CKrH5fYO.js.gz +0 -0
- package/dashboard/dist/assets/CMTTPXch.js +0 -1
- package/dashboard/dist/assets/CMTTPXch.js.br +0 -0
- package/dashboard/dist/assets/CMTTPXch.js.gz +0 -0
- package/dashboard/dist/assets/CnPC783_.js.br +0 -0
- package/dashboard/dist/assets/CnPC783_.js.gz +0 -0
- package/dashboard/dist/assets/Ctw95IkC.js.br +0 -0
- package/dashboard/dist/assets/Ctw95IkC.js.gz +0 -0
- package/dashboard/dist/assets/DHz-aQPw.js +0 -1
- package/dashboard/dist/assets/DHz-aQPw.js.br +0 -0
- package/dashboard/dist/assets/DHz-aQPw.js.gz +0 -0
- package/dashboard/dist/assets/DNX2foSJ.css +0 -1
- package/dashboard/dist/assets/DNX2foSJ.css.br +0 -0
- package/dashboard/dist/assets/DNX2foSJ.css.gz +0 -0
- package/dashboard/dist/assets/DxUw4FMR.js +0 -212
- package/dashboard/dist/assets/DxUw4FMR.js.br +0 -0
- package/dashboard/dist/assets/DxUw4FMR.js.gz +0 -0
- package/dashboard/dist/assets/T2NFtzAv.js.br +0 -0
- package/dashboard/dist/assets/T2NFtzAv.js.gz +0 -0
- package/dashboard/dist/assets/gZr_xKlA.js.br +0 -0
- package/dashboard/dist/assets/gZr_xKlA.js.gz +0 -0
|
@@ -1,212 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/0RUEVzJa.js","assets/Dj2k1r16.js","assets/BiOgVMED.js","assets/BVvffj0x.js","assets/CGj8kRhg.js","assets/eeHXe_OQ.js","assets/3VwNyxUf.js","assets/BCudUvwg.js","assets/C91KLKit.js","assets/CKrH5fYO.js","assets/cX2e-TLi.js","assets/BjK42gtU.js","assets/qm8xLgv-.css","assets/BV0BcV1u.js","assets/3TtV4moZ.js","assets/C9fvfXmS.js","assets/DHz-aQPw.js","assets/CSlBSRyv.js","assets/C-MOJWHs.js","assets/T2NFtzAv.js","assets/gZr_xKlA.js","assets/CFZ4Swr5.js","assets/CnPC783_.js","assets/7DhYqBrM.js","assets/CJjEAGFN.js","assets/CMTTPXch.js","assets/Ctw95IkC.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
var ic=Object.defineProperty;var ac=(e,t,s)=>t in e?ic(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Fn=(e,t,s)=>ac(e,typeof t!="symbol"?t+"":t,s);import{r as o,j as n,a as oc,d as lc}from"./Dj2k1r16.js";import{u as va,a as hs,b as mn,Q as cc,c as dc}from"./BiOgVMED.js";import{m as pe,A as yt,u as es}from"./eeHXe_OQ.js";import{a7 as uc}from"./cX2e-TLi.js";import{D as Ba}from"./BjK42gtU.js";import{T as mc,u as pc}from"./BV0BcV1u.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).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 fc="modulepreload",hc=function(e){return"/orgx/live/"+e},qa={},zt=function(t,s,r){let i=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(g=>Promise.resolve(g).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));i=l(s.map(u=>{if(u=hc(u),u in qa)return;qa[u]=!0;const g=u.endsWith(".css"),x=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${x}`))return;const b=document.createElement("link");if(b.rel=g?"stylesheet":fc,g||(b.as="script"),b.crossOrigin="",b.href=u,d&&b.setAttribute("nonce",d),document.head.appendChild(b),g)return new Promise((h,v)=>{b.addEventListener("load",h),b.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return i.then(l=>{for(const c of l||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})},za=()=>{const e=new Date,t=s=>new Date(e.getTime()-s*60*1e3).toISOString();return{connection:"connected",lastActivity:"2m ago",lastSnapshotAt:e.toISOString(),snapshotVersion:1,sessions:{groups:[{id:"init-1",label:"Q4 Feature Ship",status:"active"},{id:"init-2",label:"Black Friday Email",status:"active"}],edges:[{parentId:"run-1",childId:"run-2"},{parentId:"run-1",childId:"run-3"}],nodes:[{id:"run-1",parentId:null,runId:"run-1",title:"Q4 Feature Ship – Planning",agentId:"eli",agentName:"Eli",status:"running",progress:45,initiativeId:"init-1",workstreamId:null,groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(120),updatedAt:t(2),lastEventAt:t(2),lastEventSummary:"Delegated work to design and data agents.",blockers:[]},{id:"run-2",parentId:"run-1",runId:"run-2",title:"Dashboard UI pass",agentId:"dana",agentName:"Dana",status:"running",progress:70,initiativeId:"init-1",workstreamId:"ws-4",groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(80),updatedAt:t(5),lastEventAt:t(5),lastEventSummary:"Drafted handoff for approval.",blockers:["Approval pending"]},{id:"run-3",parentId:"run-1",runId:"run-3",title:"Usage tracking instrumentation",agentId:"pace",agentName:"Pace",status:"queued",progress:0,initiativeId:"init-1",workstreamId:"ws-5",groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(30),updatedAt:t(12),lastEventAt:t(12),lastEventSummary:"Waiting for data pipeline access.",blockers:["Access to events table"]},{id:"run-4",parentId:null,runId:"run-4",title:"Black Friday Email Campaign",agentId:"mark",agentName:"Mark",status:"running",progress:55,initiativeId:"init-2",workstreamId:null,groupId:"init-2",groupLabel:"Black Friday Email",startedAt:t(90),updatedAt:t(8),lastEventAt:t(8),lastEventSummary:"Drafted subject line variants.",blockers:[]}]},activity:[{id:"activity-1",type:"decision_requested",title:"Decision requested",description:"Approve dashboard UI layout for Q4 Feature Ship.",agentId:"dana",agentName:"Dana",requesterAgentId:"dana",requesterAgentName:"Dana",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-2",initiativeId:"init-1",timestamp:t(2)},{id:"activity-2",type:"artifact_created",title:"Artifact created: Subject line variants",description:"Drafted 3 subject line variants for approval.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-4",initiativeId:"init-2",timestamp:t(8)},{id:"activity-3",type:"delegation",title:"Task delegated",description:"Spin up data agent for instrumentation plan.",agentId:"eli",agentName:"Eli",requesterAgentId:"eli",requesterAgentName:"Eli",executorAgentId:"eli",executorAgentName:"Eli",runId:"run-1",initiativeId:"init-1",timestamp:t(18)}],handoffs:[{id:"handoff-1",title:"Dashboard UI approval",status:"created",priority:"high",summary:"Need approval on dashboard UI layout and component hierarchy.",currentActorType:"user",currentActorId:"me",createdAt:t(12),updatedAt:t(2),events:[{id:"handoff-event-1",handoffId:"handoff-1",eventType:"created",actorType:"agent",actorId:"dana",payload:{summary:"Draft layout ready for review."},createdAt:t(12)}]}],decisions:[{id:"decision-1",title:"Approve dashboard copy update",context:"Marketing requested a copy refresh before final launch. Confirm wording changes.",status:"pending",agentName:"Mark",requestedAt:t(22),updatedAt:t(2),waitingMinutes:22}],sliceRuns:[{id:"slice-run-1",sliceRunId:"slice-run-1",runId:"run-2",initiativeId:"init-1",workstreamId:"ws-4",workstreamTitle:"Dashboard UI pass",taskIds:["task-1"],milestoneIds:[],status:"awaiting_input",statusExplainer:"Needs your decision to proceed with this slice.",primaryAction:"resolve_decision",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"approve-layout",label:"Approve layout",description:"Proceed with the current dashboard layout.",impliedStatus:"approved",requiresNote:!1}],sourceClient:"codex",runtimeState:"active",startedAt:t(80),updatedAt:t(2),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(2),lastEventSummary:"Waiting on approval before implementation continues.",correlationId:"run-2",confidence:"high"},{id:"slice-run-2",sliceRunId:"slice-run-2",runId:"run-4",initiativeId:"init-2",workstreamId:"ws-9",workstreamTitle:"Email campaign generation",taskIds:["task-2"],milestoneIds:[],status:"completed",statusExplainer:"Completed with verified output artifacts.",primaryAction:"open_artifact",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-1",type:"document",title:"Subject line variants",url:null,createdAt:t(8)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"stopped",startedAt:t(90),updatedAt:t(8),completedAt:t(8),failedAt:null,archivedAt:null,lastEventAt:t(8),lastEventSummary:"Produced subject line variants and attached artifact.",correlationId:"run-4",confidence:"high"}],outbox:{pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},chat:{threads:[],total:0,updatedAt:e.toISOString()}}},Si="all";function Yn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function gc(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return Yn(e.get("workspace_id"))??Yn(e.get("workspaceId"))??Yn(e.get("command_center_id"))??Yn(e.get("commandCenterId"))??Yn(e.get("center"))??Yn(e.get("project_id"))??Yn(e.get("projectId"))}catch{return null}}function gs(e,t,s){const r=Yn(t);if(!r){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",Si),e.set("command_center_id",Si),e.set("center",Si));return}e.set("workspace_id",r),e.set("command_center_id",r),e.set("center",r)}function xc(e){const t=Yn(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??gc();return Object.assign(t,xc(s)),t}const yc=[[/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 Ar(e){if(!e)return"";for(const[s,r]of yc)if(s.test(e))return r;const t=e.split("/");return t[t.length-1]??e}const ul=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ml=/^[0-9a-f]{20,}$/i;function us(e){return ul.test(e)?`#${e.slice(0,4)}`:ml.test(e)?`#${e.slice(0,4)}`:e}function On(e){return ul.test(e)||ml.test(e)}function Is(e,t=4){let s=e.replace(/^\/Users\/[^/]+\//,"~/").replace(/^~\/Code\//,"").replace(/^~\//,"");const r=s.split("/");return r.length>t&&(s=r.slice(-t).join("/")),s}function lt(e){let t=e;return t=t.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,s=>`#${s.slice(0,4)}`),t=t.replace(/(?:anthropic|openrouter|openai)\/[a-z0-9._/-]+/gi,s=>Ar(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>Is(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=>Is(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 jr(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 Wa(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function lr(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 bc(e,t){if(!e)return null;for(const s of t){const r=e[s];if(!(typeof r!="number"||!Number.isFinite(r)))return r}return null}function Ua(e){const t=Wa(e);if(!t)return null;const s=Wa(t.error),r=s??t,i=lr(r,["message","detail","error_description"])??(s?null:lr(t,["error"])),a=lr(r,["code","error_code","type"]),l=bc(r,["status","httpStatusCode"]),c=lr(r,["requestId","request_id"]),d=lr(r,["docsUrl","docs_url"]);return!i&&!a&&l==null&&!c&&!d?null:{code:a,message:i,status:l,requestId:c,docsUrl:d}}function wc(e){var d,u;const t=e.trim();if(!t)return null;const s=(()=>{try{return JSON.parse(t)}catch{return null}})(),r=Ua(s);if(r)return r;const i=t.indexOf("{"),a=t.lastIndexOf("}");if(i>=0&&a>i){const g=t.slice(i,a+1);try{const x=JSON.parse(g),b=Ua(x);if(b)return b}catch{}}const l=t.match(/"message"\s*:\s*"([^"]+)"/i),c=t.match(/"code"\s*:\s*"([^"]+)"/i);return!l&&!c?null:{code:((d=c==null?void 0:c[1])==null?void 0:d.trim())||null,message:((u=l==null?void 0:l[1])==null?void 0:u.trim())||null,status:null,requestId:null,docsUrl:null}}function Ha(e){return e.replace(/"requestId"\s*:\s*"[^"]*"/gi,"").replace(/"timestamp"\s*:\s*"[^"]*"/gi,"").replace(/"docsUrl"\s*:\s*"[^"]*"/gi,"").replace(/\brequest[_\s-]?id[:=]\s*[\w-]+/gi,"").replace(/\bdocsUrl[:=]\s*\S+/gi,"").replace(/\btimestamp[:=]\s*\S+/gi,"").replace(/[{}]/g," ").replace(/\s{2,}/g," ").trim()}function Lt(e){var c;const t=wc(e),s=((c=t==null?void 0:t.code)==null?void 0:c.toLowerCase())??"",r=(t==null?void 0:t.message)??null,i=(r==null?void 0:r.toLowerCase())??"";if(s==="internal_error"||i.includes("internal server error"))return/list decision|load decision|decision/i.test(i)?"Decisions are temporarily unavailable. Try refreshing in a moment.":"OrgX hit a temporary server issue. We will retry automatically.";if(s==="unauthorized"||s==="forbidden"||i.includes("unauthorized")||i.includes("forbidden"))return"Authentication needs attention. Reconnect OrgX in Settings.";const a=Ha(r||e),l=a.toLowerCase();return/agent catalog unavailable|listagents/i.test(e)?"Agent details are still loading.":/timed out|timeout|request cancelled|signal is aborted/i.test(l)?"Live sync is taking longer than expected. Data will refresh automatically.":/budget.*exhaust/i.test(l)?"Token budget reached":/unknown api endpoint|route is unavailable|missing required live routes/i.test(l)?"This plugin build is missing required routes. Update and restart the plugin.":/unauthorized|forbidden|authentication|api key/i.test(l)?"Authentication needs attention. Reconnect OrgX in Settings.":/worker exited without structured output|worker close|signal=null/i.test(l)?"An agent run ended before returning a structured result.":/mcp handshake failed/i.test(l)?"The agent connection handshake failed. Retry after reconnecting.":/run not found/i.test(l)?"This session is no longer available.":/500|internal_error|internal server error/i.test(l)?"Something went wrong on the server. Retrying automatically.":/econnrefused|network error|fetch failed/i.test(l)?"Connection issue. Retrying automatically.":/40[13]/.test(l)?"Access issue. You may need to reconnect your workspace.":/blocked without an explicit reason/i.test(l)?"This item was paused without a specific reason.":Bt(lt(a))}function vc(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 kc(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,l=Ps(t,"next_step")??Ps(t,"nextStep"),c=l?Bt(String(l)):null;return{taskDescription:r,outcomeDescription:a&&a===r?null:a,nextStep:c&&(c===r||c===a)?null:c}}function Ps(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const jc={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 cr(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return jc[t]??e.replace(/_/g," ")}const Nc={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function Vh(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Nc[t]??e.replace(/_/g," ")}function Kh(e,t){return e.toLowerCase().includes("path")?Is(t):On(t)?us(t):t.includes(",")?t.split(",").map(r=>{const i=r.trim();return On(i)?us(i):i}).join(", "):Bt(t)}function Ic(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 Gh(e){const t=Ic(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function oi(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 l=Math.floor(a/60);if(l<24)return i==="past"?`${l}h ago`:`in ${l}h`;const c=Math.floor(l/24);return i==="past"?`${c}d ago`:`in ${c}d`}const Ac=8e3,Sc=320,_c=300,Cc=80,Mc=80,Tc=120,Va=6e4,Ec=1200,Rc=90,Lc=3,Dc=24,Ka=24,dr=new WeakMap,ka={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},Rr={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Ss={threads:[],total:0,updatedAt:null},Ga={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},pl=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),Lr=10*6e4;function $c(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 Fc(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 l=a.replace(/^[^:]+:\s*/,"").trim();return l.length>0?l:a}))).slice(0,2).map(a=>Lt(a)).filter(a=>a.length>0).join(" ")}function Pc(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 Lt(s.length>0?s:e.trim())}function Oc(e){const t=e.map(s=>Pc(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function mt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function li(e,t){const s=Ga[e.status]??99,r=Ga[t.status]??99;if(s!==r)return s-r;const i=mt(e.updatedAt??e.lastEventAt??e.startedAt),a=mt(t.updatedAt??t.lastEventAt??t.startedAt);return i!==a?a-i:e.id.localeCompare(t.id)}function Bc(e){return(e??"").trim().toLowerCase()}function Xa(e){return pl.has(Bc(e.status))}function _i(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function Qa(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const h=Date.now(),v=e.nodes.filter(w=>{const k=mt(w.updatedAt??w.lastEventAt??w.startedAt);if(Xa(w))return!0;const _=["completed","archived","failed"].includes((w.status??"").toLowerCase())?Lr/3:Lr;return h-k<=_});if(!v.length)return t;const y=new Set(v.map(w=>w.id)),j=new Set(v.map(w=>w.groupId));return{nodes:v.sort(li),edges:e.edges.filter(w=>y.has(w.parentId)&&y.has(w.childId)),groups:e.groups.filter(w=>j.has(w.id))}}const s=new Set,r=[...t.nodes];for(const h of t.nodes)for(const v of _i(h))s.add(v);const i=Date.now(),a=[];for(const h of e.nodes){if(_i(h).some(p=>s.has(p)))continue;const y=mt(h.updatedAt??h.lastEventAt??h.startedAt),w=["completed","archived","failed"].includes((h.status??"").toLowerCase())?Lr/3:Lr,k=i-y<=w;if(Xa(h)||k){a.push(h),r.push(h);for(const p of _i(h))s.add(p)}}if(!a.length)return t;const l=new Set(r.map(h=>h.id)),c=new Map(e.groups.map(h=>[h.id,h])),d=new Map(t.groups.map(h=>[h.id,h])),u=[...t.groups];for(const h of a){if(d.has(h.groupId))continue;const v=c.get(h.groupId)??{id:h.groupId,label:h.groupLabel||h.agentName||"Ungrouped",status:null};d.set(h.groupId,v),u.push(v)}const g=h=>`${h.parentId}->${h.childId}`,x=new Set,b=[];for(const h of t.edges){if(!l.has(h.parentId)||!l.has(h.childId))continue;const v=g(h);x.has(v)||(x.add(v),b.push(h))}for(const h of e.edges){if(!l.has(h.parentId)||!l.has(h.childId))continue;const v=g(h);x.has(v)||(x.add(v),b.push(h))}return{nodes:r.sort(li),edges:b,groups:u}}function ur(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(li).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 Ja(e,t){return e.length<=t?e:[...e].sort((s,r)=>mt(r.updatedAt)-mt(s.updatedAt)).slice(0,t)}function qc(e){const t=e.requestedAt??e.updatedAt??null,s=e.updatedAt??t,r=Number.isFinite(e.waitingMinutes)?Math.max(0,Math.floor(e.waitingMinutes)):t?Math.max(0,Math.floor((Date.now()-mt(t))/6e4)):0;return{id:e.id,title:e.title,context:e.context??null,status:e.status??"pending",agentName:e.agentName??null,requestedAt:t,updatedAt:s,waitingMinutes:r,metadata:e.metadata}}function fl(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 Ya(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 Za(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 eo(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 hl(e){if(!e||typeof e!="object")return ka;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 zc(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 ci(e,t=0){if(e==null)return"null";const s=typeof e;if(s==="string")return`s:${e}`;if(s==="number")return`n:${Number.isFinite(e)?String(e):"nan"}`;if(s==="boolean")return`b:${e?"1":"0"}`;if(s==="bigint")return`i:${String(e)}`;if(s!=="object")return`${s}:${String(e)}`;const r=e,i=dr.get(r);if(i)return i;if(t>=Lc){const x=Array.isArray(e)?"[…]":"{…}";return dr.set(r,x),x}if(dr.set(r,Array.isArray(e)?"[]":"{}"),Array.isArray(e)){const x=e.slice(0,Ka).map(v=>ci(v,t+1)).join(","),b=e.length>Ka?",…":"",h=`[${x}${b}]`;return dr.set(r,h),h}const a=e,l=Object.keys(a).sort(),c=l.slice(0,Dc),d=c.map(x=>`${x}:${ci(a[x],t+1)}`).join("|"),u=l.length>c.length?"|…":"",g=`{${d}${u}}`;return dr.set(r,g),g}function Wc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ws(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 Uc(e){const t=Wc(e.metadata),s=t==null?void 0:t.event,r=typeof s=="string"?s.trim().toLowerCase():"",i=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??ws(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=ws(t,["correlation_id","correlationId"]),l=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??ws(t,["initiative_id","initiativeId"]),c=ws(t,["workstream_id","workstreamId"]),d=ws(t,["task_id","taskId"]),u=ws(t,["stop_reason","stopReason"]),g=ws(t,["parsed_status","parsedStatus"]),x=(e.title??"").trim().toLowerCase();return!r&&!i&&!a||!i&&!a&&!c&&!d?null:[r,l??"",c??"",d??"",i??"",a??"",u??"",g??"",x].join("|")}function Dr(e){let t=0;const s=e.metadata;return s&&(t+=Object.keys(s).length),e.summary&&(t+=2),e.description&&(t+=2),e.agentName&&(t+=1),e.runtimeLabel&&(t+=1),e.runtimeProvider&&(t+=1),e.phase&&(t+=1),e.state&&(t+=1),t}function gl(e,t){const s=new Set,r=new Set,i=new Map,a=[];for(const l of e){if(s.has(l.id)){const d=a.findIndex(u=>u.id===l.id);d>=0&&Dr(l)>Dr(a[d])&&(a[d]=l);continue}s.add(l.id);const c=Uc(l);if(c&&r.has(c)){const d=i.get(c);Dr(l)>Dr(a[d])&&(a[d]=l);continue}if(c&&(r.add(c),i.set(c,a.length)),a.push(l),a.length>=t)break}return a}function Hc(e,t,s){if(t.length===0)return e;const r=new Map,i=new Map;for(const d of e)r.set(d.id,d),i.set(d.id,ci(d.metadata));let a=!1;for(const d of t){const u=r.get(d.id),g=ci(d.metadata);if(!u){r.set(d.id,d),i.set(d.id,g),a=!0;continue}(u.timestamp!==d.timestamp||u.type!==d.type||u.title!==d.title||u.description!==d.description||u.summary!==d.summary||u.kind!==d.kind||u.agentId!==d.agentId||u.agentName!==d.agentName||u.requesterAgentId!==d.requesterAgentId||u.requesterAgentName!==d.requesterAgentName||u.executorAgentId!==d.executorAgentId||u.executorAgentName!==d.executorAgentName||u.runId!==d.runId||u.initiativeId!==d.initiativeId||u.decisionRequired!==d.decisionRequired||i.get(d.id)!==g)&&(r.set(d.id,d),i.set(d.id,g),a=!0)}if(!a)return e;const l=Array.from(r.values()).sort((d,u)=>{const g=mt(u.timestamp)-mt(d.timestamp);return g!==0?g:u.id.localeCompare(d.id)}),c=gl(l,s);return fl(e,c)?e:c}function Ci(e,t){const s=[...e].sort((r,i)=>{const a=mt(i.timestamp)-mt(r.timestamp);return a!==0?a:i.id.localeCompare(r.id)});return gl(s,t)}function to(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(qc).sort((a,l)=>a.waitingMinutes!==l.waitingMinutes?l.waitingMinutes-a.waitingMinutes:mt(l.requestedAt??l.updatedAt)-mt(a.requestedAt??a.updatedAt)).slice(0,t),r=new Set,i=[];for(const a of s)r.has(a.id)||(r.add(a.id),i.push(a));return i}function no(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 Vc(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 Kc(e,t){return!!(pl.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function $r(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function Mi(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 Gc(e,t,s){const r=new Map,i=[...e].sort((c,d)=>mt(d.timestamp)-mt(c.timestamp));for(const c of i){if(!c.runId)continue;const d=c.runId,u=r.get(d),g=c.timestamp;if(!u){const x=c.initiativeId??null;r.set(d,{id:d,parentId:null,runId:d,title:c.title,agentId:c.agentId??null,agentName:c.agentName??null,status:no(c.type),progress:null,initiativeId:x,workstreamId:null,groupId:x??"unscoped",groupLabel:$r(x),startedAt:g,updatedAt:g,lastEventAt:g,lastEventSummary:c.title,blockers:c.type==="blocker_created"&&c.description?[c.description]:[]});continue}(!u.startedAt||mt(g)<mt(u.startedAt))&&(u.startedAt=g),mt(g)>=mt(u.updatedAt??u.lastEventAt)&&(u.updatedAt=g,u.lastEventAt=g,u.lastEventSummary=c.title,u.status=no(c.type),c.agentName&&(u.agentName=c.agentName),c.agentId&&(u.agentId=c.agentId),c.initiativeId&&(u.initiativeId=c.initiativeId,u.groupId=c.initiativeId,u.groupLabel=$r(c.initiativeId)),(!u.title||u.title.length<4)&&(u.title=c.title)),c.type==="blocker_created"&&c.description&&(u.blockers.includes(c.description)||u.blockers.push(c.description))}for(const c of t??[]){const d=c.runId??`agent:${c.id}`,u=r.get(d),g=Vc(c.status),x=new Date().toISOString(),b=Kc(c,g),h=c.startedAt??(b?x:null),v=c.initiativeId??null,y=c.currentTask&&c.currentTask.trim().length>0?c.currentTask.trim():`${c.name??c.id} ${g==="archived"?"idle":g}`;if(!u){r.set(d,{id:d,parentId:null,runId:d,title:y,agentId:c.id,agentName:c.name??c.id,status:g,progress:null,initiativeId:v,workstreamId:null,groupId:v??"unscoped",groupLabel:$r(v),startedAt:h,updatedAt:h,lastEventAt:h,lastEventSummary:c.currentTask,blockers:Mi(c.blockers)});continue}!u.agentName&&c.name&&(u.agentName=c.name),u.agentId||(u.agentId=c.id),(!u.title||u.title===u.runId)&&(u.title=y),b&&(u.updatedAt=h??u.updatedAt??x,u.lastEventAt=h??u.lastEventAt??x),u.status==="archived"&&g!=="archived"&&(u.status=g),Mi(c.blockers).length>0&&(u.blockers=Mi(c.blockers)),v&&!u.initiativeId&&(u.initiativeId=v,u.groupId=v,u.groupLabel=$r(v))}const a=Array.from(r.values()).sort(li).slice(0,s),l=new Map;for(const c of a)l.has(c.groupId)||l.set(c.groupId,{id:c.groupId,label:c.groupLabel,status:c.status});return{nodes:a,edges:[],groups:Array.from(l.values())}}async function Xc(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,l=(i==null?void 0:i.signal)??a,c=l?{...t??{},signal:l}:t??{};let d=null,u=null;if(i){if(a!=null&&a.aborted)i.abort();else if(a){const x=()=>i.abort();a.addEventListener("abort",x,{once:!0}),u=()=>a.removeEventListener("abort",x)}d=setTimeout(()=>i.abort(),r)}try{const x=await fetch(e,c),h=(((g=x.headers.get("content-type"))==null?void 0:g.toLowerCase())??"").includes("application/json");if(!x.ok){let v=`${x.status} ${x.statusText}`;if(h){const y=await x.json().catch(()=>null);y!=null&&y.error&&(v=`${x.status} ${y.error}`)}else{const y=(await x.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);y.length>0&&(v=`${x.status} ${y}`)}return{ok:!1,status:x.status,data:null,error:v}}if(!h){const v=(await x.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:x.status,data:null,error:`Unexpected content type for ${e}${v?`: ${v}`:""}`}}return{ok:!0,status:x.status,data:await x.json(),error:null}}catch(x){const b=x instanceof Error?x.message:"Network error",h=!!(i!=null&&i.signal.aborted)&&!(a!=null&&a.aborted);return x instanceof DOMException&&x.name==="AbortError"||$c(b)?{ok:!1,status:0,data:null,error:h&&r>0?`request timed out after ${r}ms`:"request cancelled"}:{ok:!1,status:0,data:null,error:b}}finally{d&&clearTimeout(d),u&&u()}}function Qc(e,t,s,r,i=[],a=ka,l=null,c=1,d=[],u=Ss,g){var v,y,j;const x=((v=t[0])==null?void 0:v.timestamp)??null,b=((y=r[0])==null?void 0:y.requestedAt)??((j=r[0])==null?void 0:j.updatedAt)??null,h=mt(x)>=mt(b)?x:b;return{connection:"connected",lastActivity:h?Mt(h):null,lastSnapshotAt:l,snapshotVersion:c,sessions:e,activity:t,handoffs:s,decisions:r,sliceRuns:i,outbox:hl(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 so(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object"||typeof s.id!="string")continue;const r=s.id.trim();r&&t.set(r,s)}return Array.from(t.values()).sort((s,r)=>mt(r.lastEventAt??r.lastHeartbeatAt)-mt(s.lastEventAt??s.lastHeartbeatAt))}function ro(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 Jc(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object"||typeof s.id!="string")continue;const r=s.id.trim();r&&t.set(r,{...s,id:r,watcherIds:Array.isArray(s.watcherIds)?s.watcherIds.filter(Boolean):[],watcherNames:Array.isArray(s.watcherNames)?s.watcherNames.filter(Boolean):[],latestLaunch:s.latestLaunch&&typeof s.latestLaunch=="object"?{...s.latestLaunch,watcherIds:Array.isArray(s.latestLaunch.watcherIds)?s.latestLaunch.watcherIds.filter(Boolean):[],watcherNames:Array.isArray(s.latestLaunch.watcherNames)?s.latestLaunch.watcherNames.filter(Boolean):[],warnings:Array.isArray(s.latestLaunch.warnings)?s.latestLaunch.warnings.filter(Boolean):[]}:null})}return Array.from(t.values()).sort((s,r)=>mt(r.lastActivityAt??r.updatedAt)-mt(s.lastActivityAt??s.updatedAt))}function Zr(e){if(!e||typeof e!="object")return Ss;const t=Jc(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 Yc(e,t){const s=e??Ss,r=t??Ss;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],l=r.threads[i];if(a.id!==l.id||a.status!==l.status||a.lastActivityAt!==l.lastActivityAt||a.lastSnippet!==l.lastSnippet||a.assigneeId!==l.assigneeId||a.launchCount!==l.launchCount||a.messageCount!==l.messageCount)return!1}return!0}function ei(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map,s=(r,i)=>{const a=[],l=c=>{if(typeof c!="string")return;const d=c.trim();d&&(a.some(u=>u.toLowerCase()===d.toLowerCase())||a.push(d))};if(Array.isArray(r))for(const c of r)l(c);else if(typeof r=="string")for(const c of r.split(/[\n,;]+/g))l(c);return i&&l(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),l=s(r.workstreamIds,r.workstreamId??null),c=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():l[0]??null,g=typeof r.iwmtId=="string"&&r.iwmtId.trim().length>0?r.iwmtId.trim():c[0]??null;t.set(i,{...r,id:i,sliceRunId:i,initiativeId:d,initiativeIds:a,workstreamId:u,workstreamIds:l,iwmtId:g,iwmtIds:c,artifacts:Array.isArray(r.artifacts)?r.artifacts:[],decisionOptions:Array.isArray(r.decisionOptions)?r.decisionOptions:[],taskIds:Array.isArray(r.taskIds)?r.taskIds:[],milestoneIds:Array.isArray(r.milestoneIds)?r.milestoneIds:[]})}return Array.from(t.values()).sort((r,i)=>mt(i.updatedAt??i.lastEventAt)-mt(r.updatedAt??r.lastEventAt))}function Fr(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;if(!r)continue;const i=s.lineage&&typeof s.lineage=="object"?s.lineage:null;t.set(r,{...s,sliceRunId:r,consistencyFlags:Array.isArray(s.consistencyFlags)?s.consistencyFlags:[],lineage:{initiativeIds:Array.isArray(i==null?void 0:i.initiativeIds)?i.initiativeIds:[],initiativeTitles:Array.isArray(i==null?void 0:i.initiativeTitles)?i.initiativeTitles:[],workstreamIds:Array.isArray(i==null?void 0:i.workstreamIds)?i.workstreamIds:[],workstreamTitles:Array.isArray(i==null?void 0:i.workstreamTitles)?i.workstreamTitles:[],taskIds:Array.isArray(i==null?void 0:i.taskIds)?i.taskIds:[],milestoneIds:Array.isArray(i==null?void 0:i.milestoneIds)?i.milestoneIds:[],iwmtIds:Array.isArray(i==null?void 0:i.iwmtIds)?i.iwmtIds:[],sliceRunId:r,sessionId:typeof(i==null?void 0:i.sessionId)=="string"?i.sessionId:null},artifacts:Array.isArray(s.artifacts)?s.artifacts:[]})}return Array.from(t.values()).sort((s,r)=>mt(r.updatedAt??r.completedAt??r.failedAt)-mt(s.updatedAt??s.completedAt??s.failedAt))}function Ti(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;r&&t.set(r,{...s,sliceRunId:r,highlights:Array.isArray(s.highlights)?s.highlights:[],technicalTrace:s.technicalTrace??{eventCount:0,eventIds:[]}})}return Array.from(t.values()).sort((s,r)=>mt(r.occurredAt)-mt(s.occurredAt))}function Ei(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 io(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,l=r.lineage.workstreamTitles[0]??r.lineage.workstreamIds[0]??null,c=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:l,taskIds:r.lineage.taskIds,milestoneIds:r.lineage.milestoneIds,status:c,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 ei(t)}function Zc(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 ed(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 td(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.occurredAt!==i.occurredAt||r.outcome.state!==i.outcome.state||r.outcome.artifactCount!==i.outcome.artifactCount)return!1}return!0}function nd(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.initiativeId!==i.initiativeId||r.pendingCount!==i.pendingCount||r.queue.length!==i.queue.length)return!1}return!0}function sd(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 rd(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 id(e={}){const{enabled:t=!0,pollInterval:s=Ac,useMock:r=!1,enableDecisions:i=!0,initiativeId:a=null,projectId:l=null,maxSessions:c=Sc,maxActivityItems:d=_c,maxHandoffs:u=Cc,maxDecisions:g=Mc,batchWindowMs:x=Tc}=e,b=typeof a=="string"&&a.trim().length>0?a.trim():null,h=typeof l=="string"&&l.trim().length>0?l.trim():null,[v,y]=o.useState(za()),[j,w]=o.useState(Rr),[k,p]=o.useState(!r),[_,U]=o.useState(null),ae=o.useRef(),G=o.useRef(null),ve=o.useRef(null),[V,ee]=o.useState(!1),de=o.useRef(0),we=o.useRef(!1),je=o.useRef(`${b??"__all__"}::${h??"__all__"}`),ge=o.useRef(!1),He=o.useRef(null),ue=o.useCallback((z,K)=>{He.current&&(clearTimeout(He.current),He.current=null),w(z),K!=null&&K.autoResetMs&&K.autoResetMs>0&&(He.current=setTimeout(()=>{He.current=null,w(Rr)},K.autoResetMs))},[]);o.useEffect(()=>()=>{He.current&&(clearTimeout(He.current),He.current=null)},[]),o.useEffect(()=>{const z=`${b??"__all__"}::${h??"__all__"}`;je.current!==z&&(je.current=z,ge.current=!0,ue(Rr),y(K=>({...K,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Ss,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(K.snapshotVersion??0)+1})),p(!0),U(null))},[b,h,ue]);const ne=o.useCallback((z,K,le,xe=null,Se=null,Y=null,Te=null,fe=null,C=null,O=null)=>{de.current=Date.now(),we.current=!1,y(W=>{const Z=ge.current;Z&&(ge.current=!1);const Fe=K===null?Z?[]:W.activity:Ci(K,d),Oe=le===null?Z?[]:W.handoffs:Ja(le,u),Me=ur(z===null?Z?{nodes:[],edges:[],groups:[]}:W.sessions:Z?ur(z,c):Qa(W.sessions,ur(z,c)),c),T=xe===null?Z?[]:W.decisions:to(xe,g),F=Se===null?Z?[]:W.sliceRuns:ei(Se),ie=Y===null?Z?ka:W.outbox:hl(Y),he=fe===null?Z?[]:W.runtimeInstances??[]:so(fe),Ie=C===null?Z?Ss:W.chat??Ss:Zr(C),Xe=(O==null?void 0:O.workSliceProjections)==null?Z?[]:W.workSliceProjections??[]:Fr(O.workSliceProjections),Qe=(O==null?void 0:O.timelineNarrative)==null?Z?[]:W.timelineNarrative??[]:Ti(O.timelineNarrative),Ee=(O==null?void 0:O.nextUpByInitiative)==null?Z?[]:W.nextUpByInitiative??[]:Ei(O.nextUpByInitiative),et=typeof(O==null?void 0:O.runningWorkSlices)=="number"&&Number.isFinite(O.runningWorkSlices)?Math.max(0,Math.floor(O.runningWorkSlices)):W.runningWorkSlices??0,qe=typeof(O==null?void 0:O.needsInputTotal)=="number"&&Number.isFinite(O.needsInputTotal)?Math.max(0,Math.floor(O.needsInputTotal)):W.needsInputTotal??0,pt=typeof(O==null?void 0:O.failedActionableTotal)=="number"&&Number.isFinite(O.failedActionableTotal)?Math.max(0,Math.floor(O.failedActionableTotal)):W.failedActionableTotal??0,at=typeof(O==null?void 0:O.completedTodayTotal)=="number"&&Number.isFinite(O.completedTodayTotal)?Math.max(0,Math.floor(O.completedTodayTotal)):W.completedTodayTotal??0,Ze=(O==null?void 0:O.consistencyFlags)==null?W.consistencyFlags??[]:O.consistencyFlags.filter(Ae=>typeof Ae=="string"),ye=(O==null?void 0:O.dataHealth)===void 0||(O==null?void 0:O.dataHealth)===null?W.dataHealth:O.dataHealth,We=(W.snapshotVersion??0)+1;return Ya(W.sessions,Me)&&fl(W.activity,Fe)&&Za(W.handoffs,Oe)&&eo(W.decisions,T)&&Zc(W.sliceRuns,F)&&zc(W.outbox,ie)&&Yc(W.chat,Ie)&&ro(W.runtimeInstances,he)&&ed(W.workSliceProjections??[],Xe)&&td(W.timelineNarrative??[],Qe)&&nd(W.nextUpByInitiative??[],Ee)&&(W.runningWorkSlices??0)===et&&(W.needsInputTotal??0)===qe&&(W.failedActionableTotal??0)===pt&&(W.completedTodayTotal??0)===at&&sd(W.consistencyFlags??[],Ze)&&rd(W.dataHealth,ye)&&W.lastSnapshotAt===Te&&W.connection==="connected"?W:Qc(Me,Fe,Oe,T,F,ie,Te,We,he,Ie,{workSliceProjections:Xe,timelineNarrative:Qe,nextUpByInitiative:Ee,runningWorkSlices:et,needsInputTotal:qe,failedActionableTotal:pt,completedTodayTotal:at,consistencyFlags:Ze,dataHealth:ye})}),p(!1)},[d,g,u,c]),X=o.useCallback(async()=>{if(!t){y(le=>le.connection==="disconnected"?le:{...le,connection:"disconnected"}),p(!1),U(null);return}const z=`${b??"__all__"}::${h??"__all__"}`;if(G.current&&ve.current===z)return G.current;if(r){y(za()),p(!1);return}const K=(async()=>{try{const le=new URLSearchParams({sessionsLimit:String(c),activityLimit:String(d),decisionsLimit:String(g),include_idle:"true"});h&&gs(le,h),b&&le.set("initiative",b);const xe=[{label:"live/snapshot-v2",url:`/orgx/api/live/snapshot-v2?${le.toString()}`},{label:"dashboard-bundle",url:`/orgx/api/dashboard-bundle?${le.toString()}`},{label:"live/snapshot",url:`/orgx/api/live/snapshot?${le.toString()}`}],Se=[];let Y=null,Te=!1;for(let Q=0;Q<xe.length;Q+=1){const _e=xe[Q];Q>0&&await new Promise(De=>{setTimeout(De,Rc)});const Le=await Xc(_e.url,{headers:_t({workspaceId:h})},{timeoutMs:Ec});if(Le.ok&&Le.data){Y=Le.data;break}(Le.status===401||Le.status===403)&&(Te=!0),Se.push(`${_e.label}: ${Le.error??"unavailable"}`)}if(!Y){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(Fc(Se))}if(je.current!==z)return;const fe=Array.isArray(Y.degraded)?Y.degraded.filter(Q=>typeof Q=="string"):[],C=fe.map(Q=>Q.toLowerCase()),O=(...Q)=>C.some(_e=>Q.some(Le=>_e.includes(Le))),W=Array.isArray(Y.activity)?Y.activity:[],Z=Array.isArray(Y.handoffs)?Y.handoffs:[],Fe=Array.isArray(Y.decisions)?Y.decisions:[],Oe=W.length===0&&O("activity unavailable","activity local fallback failed"),Me=O("sessions unavailable","sessions local fallback failed"),T=Z.length===0&&O("handoffs unavailable"),F=Fe.length===0&&O("decisions unavailable"),ie=Fr(Array.isArray(Y.projections)?Y.projections:[]),he=Zr(Y.chat??null),Ie=Ti(Array.isArray(Y.timelineNarrative)?Y.timelineNarrative:[]),Xe=Ei(Array.isArray(Y.nextUpByInitiative)?Y.nextUpByInitiative:[]),Qe=ie.length>0?io(ie):ei(Array.isArray(Y.sliceRuns)?Y.sliceRuns:[]),Ee=Y.sessions&&Array.isArray(Y.sessions.nodes)&&Array.isArray(Y.sessions.edges)&&Array.isArray(Y.sessions.groups)?Y.sessions:Gc(W,Y.agents,c),et=Qe.length===0&&ie.length===0&&O("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),qe=Xe.length===0&&O("next-up unavailable","next-up queue"),pt=Oe?null:W,at=T?null:Z,Ze=F?null:Fe,ye=Me&&Ee.nodes.length===0?null:Ee,We=et?null:ie,Ae=et?null:Ie,q=et?null:Qe,Re=qe?null:Xe;ne(ye,pt,at,Ze,q,Y.outbox??null,Y.generatedAt??null,Y.runtimeInstances??null,he,{workSliceProjections:We,timelineNarrative:Ae,nextUpByInitiative:Re,runningWorkSlices:et?null:Y.runningWorkSlices??null,needsInputTotal:et?null:Y.needsInput??null,failedActionableTotal:et?null:Y.failedActionable??null,completedTodayTotal:et?null:Y.completedToday??null,consistencyFlags:Array.isArray(Y.consistencyFlags)?Y.consistencyFlags:null,dataHealth:Y.dataHealth??null});const B=fe.length>0?Oc(fe):[];B.length>0?(U(`Partial live data: ${B.join("; ")}`),y(Q=>Q.connection==="connected"?Q:{...Q,connection:"connected"}),ee(!1)):(U(null),y(Q=>Q.connection==="connected"?Q:{...Q,connection:"connected"}))}catch(le){if(je.current!==z)return;const xe=le instanceof Error?le.message:"Unknown error",Se=!!(le&&typeof le=="object"&&"code"in le&&le.code==="ORGX_AUTH");Se&&(we.current=!0);const Y=de.current>0&&Date.now()-de.current>Va;U(xe),y(Te=>{const fe=Se||Y?"disconnected":"reconnecting";return Te.connection===fe?Te:{...Te,connection:fe}}),ee(!Se),p(!1)}finally{ve.current===z&&(G.current=null,ve.current=null)}})();return G.current=K,ve.current=z,K},[ne,t,i,d,g,u,c,h,b,r]),te=o.useCallback(async(z,K,le)=>{var C,O,W;if(!i)throw new Error("OrgX decisions are unavailable while disconnected.");const xe=Array.from(new Set(z.filter(Boolean)));if(xe.length===0)return{updated:0,failed:0};const Se=((C=le==null?void 0:le.note)==null?void 0:C.trim())||void 0,Y=((O=le==null?void 0:le.optionId)==null?void 0:O.trim())||void 0;if(r){const Z=new Set(xe);return y(Fe=>{const Oe=Fe.decisions.filter(ie=>Z.has(ie.id));if(Oe.length===0)return Fe;const Me=new Date().toISOString(),T=Oe.map(ie=>({id:`decision:${K}:${ie.id}:${Date.now()}`,type:"decision_resolved",title:K==="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:K}})),F=Ci(T.concat(Fe.activity),d);return{...Fe,decisions:Fe.decisions.filter(ie=>!Z.has(ie.id)),activity:F,lastActivity:Mt(Me)}}),{updated:Z.size,failed:0,firstError:void 0}}const Te=new Date().toISOString(),fe=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:_t({contentTypeJson:!0,workspaceId:h}),body:JSON.stringify({ids:xe,action:K,...Se?{note:Se}:{},...Y?{option_id:Y}:{}})});try{const Z=await fe.json().catch(()=>null),Fe=Array.isArray(Z==null?void 0:Z.results)?Z.results:[],Oe=new Set(Fe.filter(he=>he.ok).map(he=>he.id)),T=((W=Fe.filter(he=>!he.ok).find(he=>typeof he.error=="string"&&he.error.trim().length>0))==null?void 0:W.error)??(typeof(Z==null?void 0:Z.error)=="string"&&Z.error.trim().length>0?Z.error:void 0);if(!fe.ok&&fe.status!==207){const he=T??`Decision action failed (${fe.status})`;throw new Error(he)}if(Oe.size===0&&fe.ok&&((Z==null?void 0:Z.failed)??0)===0)for(const he of xe)Oe.add(he);Oe.size>0?y(he=>{const Ie=he.decisions.filter(qe=>Oe.has(qe.id));if(Ie.length===0)return he;const Xe=new Date().toISOString(),Qe=Ie.map(qe=>({id:`decision:${K}:${qe.id}:${Date.now()}`,type:"decision_resolved",title:K==="approve"?`Approved: ${qe.title}`:`Rejected: ${qe.title}`,description:qe.context,agentId:null,agentName:qe.agentName,requesterAgentId:null,requesterAgentName:qe.agentName??null,executorAgentId:null,executorAgentName:qe.agentName??null,runId:null,initiativeId:null,timestamp:Xe,metadata:{decisionId:qe.id,action:K}})),Ee=Ci(Qe.concat(he.activity),d);return{...he,decisions:he.decisions.filter(qe=>!Oe.has(qe.id)),activity:Ee,lastActivity:Mt(Xe)}}):fe.ok&&xe.length>0&&y(he=>({...he,decisions:he.decisions.filter(Ie=>!xe.includes(Ie.id))})),X();const F=(Z==null?void 0:Z.updated)??Oe.size,ie=(Z==null?void 0:Z.failed)??Math.max(0,xe.length-Oe.size);return ue({phase:ie>0?"error":"success",action:K,targetCount:xe.length,message:ie>0?`${K==="approve"?"Approve":"Reject"} completed with ${ie} failure${ie===1?"":"s"}.`:K==="approve"?`Approved ${F} decision${F===1?"":"s"}.`:`Rejected ${F} decision${F===1?"":"s"}.`,startedAt:Te,completedAt:new Date().toISOString()},{autoResetMs:ie>0?8e3:4e3}),{updated:F,failed:ie,firstError:T}}catch(Z){throw ue({phase:"error",action:K,targetCount:xe.length,message:Z instanceof Error?Z.message:"Decision update failed.",startedAt:Te,completedAt:new Date().toISOString()}),Z}},[i,X,d,h,ue,r]),Ne=o.useCallback(async(z,K)=>te([z],"approve",K),[te]),se=o.useCallback(async(z,K)=>te([z],"reject",K),[te]),$=o.useCallback(async()=>{let z=[];return y(K=>(z=K.decisions.map(le=>le.id),K)),z.length===0?{updated:0,failed:0}:te(z,"approve")},[te]),H=o.useCallback(async(z,K,le)=>te(z,K,le?{note:le}:void 0),[te]);return o.useEffect(()=>{i||ue(Rr)},[i,ue]),o.useEffect(()=>{if(!t){ee(!1),p(!1),U(null);return}if(r){X();return}if(X(),h){ee(!0);return}const z=new URLSearchParams;h&&gs(z,h),b&&z.set("initiative",b);const K=z.toString()?`/orgx/api/live/stream?${z.toString()}`:"/orgx/api/live/stream",le=new EventSource(K),xe=new EventSource("/orgx/api/hooks/runtime/stream");let Se=null,Y=null,Te=null,fe=null,C=[],O=null,W;const Z=()=>{if(W=void 0,Se){de.current=Date.now(),we.current=!1;const Me=Se;Se=null,Te=null,fe=null,C=[],O=null,Y=null,ne(Me.sessions,Me.activity,Me.handoffs,Me.decisions,Me.sliceRuns,Me.outbox,Me.generatedAt,Me.runtimeInstances,Me.chat,Me.v2);return}!Te&&!fe&&!O&&!Y&&C.length===0||(de.current=Date.now(),we.current=!1,y(Me=>{var F;let T=Me;if(Te){const ie=ur(Te,c),he=ur(Qa(T.sessions,ie),c);Te=null,Ya(T.sessions,he)||(T={...T,sessions:he})}if(fe){const ie=Ja(fe,u);fe=null,Za(T.handoffs,ie)||(T={...T,handoffs:ie})}if(O){const ie=to(O,g);O=null,eo(T.decisions,ie)||(T={...T,decisions:ie})}if(Y){const ie=so(Y);Y=null,ro(T.runtimeInstances,ie)||(T={...T,runtimeInstances:ie})}if(C.length>0){const ie=Hc(T.activity,C,d);C=[],ie!==T.activity&&(T={...T,activity:ie,lastActivity:(F=ie[0])!=null&&F.timestamp?Mt(ie[0].timestamp):T.lastActivity})}return T===Me?Me:T.connection==="connected"?T:{...T,connection:"connected"}}),U(null),p(!1))},Fe=()=>{W||(W=setTimeout(Z,x))};le.onopen=()=>{de.current=Date.now(),we.current=!1,ee(!1),y(Me=>Me.connection==="connected"?Me:{...Me,connection:"connected"}),U(null)},le.onerror=()=>{if(we.current){y(T=>T.connection==="disconnected"?T:{...T,connection:"disconnected"}),ee(!1);return}const Me=de.current>0&&Date.now()-de.current>Va;y(T=>T.connection===(Me?"disconnected":"reconnecting")?T:{...T,connection:Me?"disconnected":"reconnecting"}),ee(!0)},le.addEventListener("snapshot",Me=>{try{const T=JSON.parse(Me.data),F=typeof T.generatedAt=="string"&&T.generatedAt.length>0?T.generatedAt:new Date().toISOString();Se={sessions:T.sessions,activity:T.activity??[],handoffs:T.handoffs??[],decisions:T.decisions??null,sliceRuns:Array.isArray(T.sliceRuns)?ei(T.sliceRuns):Array.isArray(T.projections)?io(Fr(T.projections)):null,outbox:T.outbox??null,generatedAt:F,runtimeInstances:Array.isArray(T.runtimeInstances)?T.runtimeInstances:null,chat:Zr(T.chat??null),v2:{workSliceProjections:Array.isArray(T.projections)?Fr(T.projections):null,timelineNarrative:Array.isArray(T.timelineNarrative)?Ti(T.timelineNarrative):null,nextUpByInitiative:Array.isArray(T.nextUpByInitiative)?Ei(T.nextUpByInitiative):null,runningWorkSlices:typeof T.runningWorkSlices=="number"?T.runningWorkSlices:null,needsInputTotal:typeof T.needsInput=="number"?T.needsInput:null,failedActionableTotal:typeof T.failedActionable=="number"?T.failedActionable:null,completedTodayTotal:typeof T.completedToday=="number"?T.completedToday:null,consistencyFlags:Array.isArray(T.consistencyFlags)?T.consistencyFlags:null,dataHealth:T.dataHealth??null}},Fe()}catch(T){U(T instanceof Error?T.message:"Invalid snapshot")}}),le.addEventListener("activity.appended",Me=>{try{const T=JSON.parse(Me.data);if(T.length===0)return;C=C.concat(T),Fe()}catch{}}),le.addEventListener("session.updated",Me=>{try{Te=JSON.parse(Me.data),Fe()}catch{}});const Oe=Me=>{try{const T=JSON.parse(Me.data);Y=Array.isArray(T)?T:[T],Fe()}catch{}};return le.addEventListener("runtime.updated",Oe),xe.addEventListener("runtime.updated",Oe),le.addEventListener("handoff.updated",Me=>{try{fe=JSON.parse(Me.data),Fe()}catch{}}),le.addEventListener("decision.updated",Me=>{try{O=JSON.parse(Me.data),Fe()}catch{}}),()=>{W&&clearTimeout(W),le.close(),xe.close()}},[ne,x,t,i,X,d,g,u,c,b,h,r]),o.useEffect(()=>{if(!(!t||r||(ae.current&&clearInterval(ae.current),!V&&!!!h)))return ae.current=setInterval(X,s),()=>{ae.current&&clearInterval(ae.current)}},[t,X,h,s,V,r]),{data:v,isLoading:k,error:_,refetch:X,approveDecision:Ne,rejectDecision:se,approveAllDecisions:$,bulkDecisionAction:H,decisionMutation:j}}const Sr=[{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 xl(e){return Sr.find(t=>t.id===e)??Sr[0]}function Cr(e,t=Date.now()){if(e==="all")return null;if(e==="live")return t-60*6e4;if(e==="24h"){const r=new Date(t);return r.setHours(0,0,0,0),r.getTime()}if(e==="custom")return null;const s=Sr.find(r=>r.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function ad(e,t=Date.now()){const s=Cr(e,t);return s?new Date(s).toISOString():null}const od=new Set(["ungrouped","unscoped","unknown"]),ld="orgx.demo_mode",cd="orgx.show_synthetic_entities";function Cs(e){const t=(e??"").trim().toLowerCase();return!!(!t||od.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Ft(){if(typeof window>"u")return!1;try{if(new URLSearchParams(window.location.search).get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(ld)==="1"}catch{return!1}}function dd(){if(typeof window>"u")return!1;if(Ft())return!0;try{return window.localStorage.getItem(cd)==="1"}catch{return!1}}function ud(e){return Ft()?!0:!Cs(e)}function da(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function yl(e,t){const s=da(t.timestamp)-da(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function md(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function pd(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 bl(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=md(e.metadata);return pd(s,["initiative_id","initiativeId"])}function Ri(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ua(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(e===null||t===null)return e===t;if(typeof e!="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let l=0;l<e.length;l+=1)if(!ua(e[l],t[l]))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 l=0;l<i.length;l+=1){const c=i[l];if(c!==a[l]||!ua(s[c],r[c]))return!1}return!0}const fd=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function Ws(e,...t){}function hd(e,t,s,r){const i=new Map,a=t.sinceEpoch,l=t.untilEpoch;let c=0,d=0,u=0;for(const g of e??[]){if(!g||typeof g.id!="string")continue;if(s&&g.runId!==s){c++;continue}if(r&&bl(g)!==r){d++;continue}const x=da(g.timestamp);if(x){if(a!==null&&x<a){u++;continue}if(l!==null&&x>l){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:c,skippedInitiative:d,skippedTime:u,sinceEpoch:a?new Date(a).toISOString():null,untilEpoch:l?new Date(l).toISOString():null}),Array.from(i.values()).sort(yl)}function ao(e,t){if(t.length===0)return e;const s=new Map;for(const l of e)s.set(l.id,l);let r=0,i=0,a=!1;for(const l of t){const c=s.get(l.id);if(!c){s.set(l.id,l),a=!0,r++;continue}(c.timestamp!==l.timestamp||c.type!==l.type||c.title!==l.title||c.description!==l.description||c.summary!==l.summary||!ua(c.metadata??null,l.metadata??null))&&(s.set(l.id,l),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(yl):e}function gd(e){const{seed:t,timeFilterId:s,customSinceIso:r=null,customUntilIso:i=null,runId:a=null,initiativeId:l=null,projectId:c=null,pageSize:d=50,demoMode:u=Ft()}=e,g=o.useMemo(()=>Ri(a),[a]),x=o.useMemo(()=>Ri(l),[l]),b=o.useMemo(()=>Ri(c),[c]),h=o.useMemo(()=>Cr(s),[s]),v=o.useMemo(()=>ad(s),[s]),y=o.useMemo(()=>{if(s==="custom"){const $=(r==null?void 0:r.trim())??"";return $.length>0?$:null}return v},[r,v,s]),j=o.useMemo(()=>{if(s!=="custom")return null;const $=(i==null?void 0:i.trim())??"";return $.length>0?$:null},[i,s]),w=o.useMemo(()=>{if(y){const $=Date.parse(y);if(Number.isFinite($))return $}return h},[h,y]),k=o.useMemo(()=>{if(!j)return null;const $=Date.parse(j);return Number.isFinite($)?$:null},[j]),p=o.useMemo(()=>hd(t,{sinceEpoch:w,untilEpoch:k},g,x),[t,w,k,g,x]),_=u?null:"",[U,ae]=o.useState(p),[G,ve]=o.useState(()=>_),[V,ee]=o.useState(!1),[de,we]=o.useState(null),[je,ge]=o.useState(null),He=o.useRef(null),ue=o.useRef(!1),ne=o.useRef(p);ne.current=p;const X=o.useMemo(()=>`${g??""}|${x??""}|${s}|${y??""}|${j??""}|${b??""}|${u?"demo":"live"}`,[g,x,s,y,j,b,u]),te=o.useRef(X);o.useEffect(()=>{te.current!==X&&(te.current=X,Ws("RESET",{reason:"filter/run change",runId:g,initiativeId:x,projectId:b,timeFilterId:s,sinceIso:y,untilIso:j,seedCount:ne.current.length}),ae(ne.current),ve(_),we(null),ge(null),ue.current=!1)},[X,_,g,x,b,s,y,j]),o.useEffect(()=>{ae($=>{const H=ao($,p);return H!==$&&Ws("SSE_MERGE",{prevCount:$.length,seedCount:p.length,nextCount:H.length,delta:H.length-$.length}),H})},[p]);const Ne=o.useCallback(async()=>{if(u){ve(null),we(null);return}if(G===null)return;if(He.current)return He.current;ee(!0);const $=(async()=>{try{const H=new URLSearchParams;H.set("limit",String(Math.max(1,Math.min(500,d)))),G.trim().length>0&&H.set("cursor",G),y&&H.set("since",y),j&&H.set("until",j),g&&H.set("run",g),x&&H.set("initiative",x),b&&gs(H,b);const z=await fetch(`/orgx/api/live/activity/page?${H.toString()}`,{headers:_t({workspaceId:b})}),K=await z.json().catch(()=>null);if(!z.ok||!K){const Se=typeof(K==null?void 0:K.error)=="string"&&K.error.trim()||typeof(K==null?void 0:K.message)=="string"&&K.message.trim()||`Activity paging failed (${z.status})`;throw new Error(Se)}const le=Array.isArray(K.activities)?K.activities:[],xe=le.filter(Se=>!x||bl(Se)===x);Ws("PAGE_FETCH",{cursor:G,rawCount:le.length,afterFilter:xe.length,filteredOut:le.length-xe.length,initiativeId:x,runId:g,nextCursor:K.nextCursor??null}),ae(Se=>{const Y=ao(Se,xe);return Ws("PAGE_MERGE",{prevCount:Se.length,pageCount:xe.length,nextCount:Y.length,added:Y.length-Se.length}),Y}),ve(K.nextCursor??null),ge(K.storeUpdatedAt??null),we(null)}catch(H){const z=H instanceof Error?H.message:"";we(z?Lt(z):"Activity paging failed"),ve(K=>K===""?null:K)}finally{ee(!1),He.current=null}})();return He.current=$,$},[G,u,x,d,b,g,y,j]);return o.useEffect(()=>{G===""&&(ue.current||(ue.current=!0,Ne()))},[G,Ne]),{items:U,hasMore:G!==null,isLoadingMore:V,error:de,storeUpdatedAt:je,loadMore:Ne,cutoffEpoch:w,sinceIso:y,untilIso:j}}const xd="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",yd="".trim().toLowerCase()==="true"||"".trim()==="1",bd="".trim().toLowerCase()==="true"||"".trim()==="1",wd={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let Li=null,oo=!1,lo=!1,ja=!1;function vd(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function bi(){return ja||!yd?!1:bd?!0:!vd()}function kd(){return bi()?(Li||(Li=zt(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(ja=!0,null))),Li):Promise.resolve(null)}function jd(e){if(oo)return!0;try{return e.init(xd,wd),oo=!0,!0}catch{return ja=!0,!1}}async function Na(){const e=await kd();return!e||!jd(e)?null:e}function Nd(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 Id(){!bi()||typeof window>"u"||lo||(lo=!0,Nd(()=>{Na()}))}function Ad(e){if(!bi())return;const t=e.trim();t&&Na().then(s=>{if(s)try{s.identify(t)}catch{}})}function cs(e,t){bi()&&e.trim()&&Na().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const Sd="https://orgx.mintlify.site/guides/openclaw-plugin-setup",_d=1500,Di="orgx.onboarding.skip",Cd=680,Md=`<!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>`,ti={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:Sd,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function Os(){return{...ti,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function $i(e){if(typeof e=="string")return Lt(e);if(e&&typeof e=="object"){const t=e;if(typeof t.error=="string")return Lt(t.error);if(typeof t.message=="string")return Lt(t.message)}}async function mr(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:$i(s==null?void 0:s.error)??$i(s==null?void 0:s.message)??$i(s)??Lt(`Request failed (${t.status})`)}}function Pr(e){if(e)try{Ad(e)}catch{}}function Td(){const[e,t]=o.useState(()=>Ft()?Os():ti),[s,r]=o.useState(()=>!Ft()),[i,a]=o.useState(!1),[l,c]=o.useState(!1),d=o.useRef(null),[u,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Di)==="1"),x=o.useCallback(async()=>{if(Ft()){const p=Os();return t(p),p}const k=await mr(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!k.ok||!k.data){const p=k.error??"Failed to load onboarding state",_={...ti,status:"error",lastError:p,nextAction:"retry"};return t(_),_}return Pr(k.data.installationId??null),t(k.data),k.data},[]);o.useEffect(()=>{if(Ft()){t(Os()),r(!1);return}let k=!1;return(async()=>{r(!0);const p=await x();k||(t(p),r(!1))})(),()=>{k=!0}},[x]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const p=Math.max(900,e.pollIntervalMs??_d),_=window.setInterval(async()=>{const U=await mr(fetch("/orgx/api/onboarding/status",{method:"GET"}));U.ok&&U.data&&(Pr(U.data.installationId??null),t(U.data))},p);return()=>{window.clearInterval(_)}},[e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(u){window.localStorage.setItem(Di,"1");return}window.localStorage.removeItem(Di)}},[u]);const b=o.useCallback(()=>{if(typeof window>"u")return null;try{const k=window.open("","_blank");return k?(k.opener=null,k.document.title="Connecting to OrgX…",k.document.open(),k.document.write(Md),k.document.close(),k):null}catch{return null}},[]),h=o.useCallback(async()=>{if(Ft()){const p=Os();t(p);return}const k=b();d.current=k,a(!0);try{const p=await mr(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),_=p.data;if(!p.ok||!(_!=null&&_.state)){k&&!k.closed&&k.close();const ae=p.error??"Could not start pairing";t(G=>({...G,status:"error",lastError:ae,nextAction:"enter_manual_key"}));return}t(_.state);const U=_.connectUrl;if(U){const ae=d.current;let G=!1;if(ae&&!ae.closed)try{window.setTimeout(()=>{if(!ae.closed)try{ae.location.href=U}catch{}},Cd),G=!0}catch{G=!1}G||(G=!!window.open(U,"_blank","noopener,noreferrer")),G||t(ve=>({...ve,lastError:'Popup was blocked. Use "Approve in browser" below.',nextAction:"open_browser"}))}}finally{d.current=null,a(!1)}},[b]),v=o.useCallback(async k=>{if(Ft()){const p=Os();return t(p),p}c(!0);try{const p=k.trim(),_=p.replace(/^[a-z]+_/i,""),U=Array.from(new Set([p,_?`oxk_${_}`:"",_?`orgx_${_}`:""].map(G=>G.trim()).filter(G=>G.length>0)));let ae="Manual key validation failed";for(const G of U){const ve={"Content-Type":"application/json","X-OrgX-Api-Key":G,Authorization:`Bearer ${G}`},V=await mr(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:ve,body:JSON.stringify({apiKey:G})}));if(V.ok&&V.data)return Pr(V.data.installationId??null),t(V.data),V.data;ae=V.error??ae}throw t(G=>({...G,status:"manual_key",lastError:ae,nextAction:"enter_manual_key"})),new Error(ae)}finally{c(!1)}},[]),y=o.useCallback(async()=>{if(Ft()){const _=Os();return t(_),_}const k=await mr(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(k.ok&&k.data)return Pr(k.data.installationId??null),t(k.data),k.data;const p={...ti,status:"idle"};return t(p),p},[]),j=o.useCallback(()=>{t(k=>({...k,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),w=o.useMemo(()=>Ft()||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:l,refreshStatus:x,startPairing:h,submitManualKey:v,disconnect:y,skipGate:()=>g(!0),resumeGate:()=>g(!1),backToPairing:j,setManualMode:()=>t(k=>({...k,status:"manual_key",nextAction:"enter_manual_key"}))}}const Zn={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 Ed extends Error{constructor(s,r){super(s);Fn(this,"code","upgrade_required");Fn(this,"currentPlan");Fn(this,"requiredPlan");Fn(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 Rd(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 Ed(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 Xh(e){const t=(e??"").trim().toLowerCase();return t?t==="free"?"Free":t==="starter"?"Starter":t==="team"?"Team":t==="enterprise"?"Enterprise":t[0].toUpperCase()+t.slice(1):"Unknown"}class wl extends Error{constructor(s){super(s.message);Fn(this,"status");Fn(this,"code");Fn(this,"errorLocation");Fn(this,"retryable");Fn(this,"details");this.name="MissionControlApiError",this.status=s.status,this.code=s.code??null,this.errorLocation=s.errorLocation??null,this.retryable=s.retryable??!1,this.details=s.details??null}}function Ld(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function _r(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function Dd(e,t){if(e.status!==404)return!1;const s=_r(t,["error"])??"",r=_r(t,["message"])??"";return/unknown api endpoint/i.test(`${s} ${r}`)}function $d(e,t,s){if(Dd(e,t))return`${s}. This queue control is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable.`;const r=_r(t,["error","message"])??`${s} (${e.status})`;return Lt(r)}function Fi(e,t,s){const r=Ld(t),i=$d(e,r,s),a=_r(r,["code"]),l=_r(r,["error_location","errorLocation"]),c=r==null?void 0:r.retryable,d=typeof c=="boolean"?c:!1;return new wl({message:i,status:e.status,code:a,errorLocation:l,retryable:d,details:r})}function Qh(e){return e instanceof wl}const Fd=750;async function pr(e){return await e.json().catch(()=>null)}function Pd(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 Od(e,t,s){if(Pd(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 Lt(r)}function Bd(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?Lt(s):t}function qd(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 ni({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 zd(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 Wd(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;return!(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")}function Ia(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 Aa(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 vl(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 l=a,c=Ia(typeof l.id=="string"?l.id:null),d=Aa(typeof l.name=="string"?l.name:null,c);if(c==="unassigned"&&d==="Unassigned")continue;const u=c.toLowerCase();i.has(u)||(i.add(u),r.push({id:c,name:d}))}return r.length===0&&t!=="unassigned"?[{id:t,name:s}]:r}function Ud(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function Hd(e){const t=Ia(e.runnerAgentId),s=Aa(e.runnerAgentName,t),r=vl(e.runnerAgents,t,s),i=r[0]??null,a=(i==null?void 0:i.id)??t,l=(i==null?void 0:i.name)??s,c=Ud(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:l,runnerAgents:r,runnerSource:c,playbackState:e.queueState,autoIntentEnabled:Wd(e),autoRuntimeState:zd(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 ni(e){const t=e.items.map(u=>Hd(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),l=i+a<s,c=r&&typeof r.hasMore=="boolean"?r.hasMore:l,d=r&&typeof r.nextCursor=="string"?r.nextCursor:c?String(i+a):null;return{...e,items:t,total:s,pagination:{offset:i,limit:a,total:s,nextCursor:d,hasMore:c}}}function Vd(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 Kd(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 Gd(e){var x,b,h,v,y,j,w,k,p,_,U,ae,G,ve,V,ee;const t=((b=(x=e.lineage)==null?void 0:x.initiativeIds)==null?void 0:b.filter(de=>typeof de=="string"&&de.trim().length>0))??[],s=((v=(h=e.lineage)==null?void 0:h.workstreamIds)==null?void 0:v.filter(de=>typeof de=="string"&&de.trim().length>0))??[],r=((y=e.initiativeId)==null?void 0:y.trim())||t[0]||null,i=((j=e.workstreamId)==null?void 0:j.trim())||((k=(w=e.sourceWorkstreamIds)==null?void 0:w.find(de=>typeof de=="string"&&de.trim().length>0))==null?void 0:k.trim())||s[0]||null;if(!r||!i)return null;const a=((_=(p=e.lineage)==null?void 0:p.taskIds)==null?void 0:_.filter(de=>typeof de=="string"&&de.trim().length>0))??[],l=e.level==="workstream"||e.level==="milestone"||e.level==="task"?e.level:null,c=Ia(e.runnerAgentId??null),d=Aa(e.runnerAgentName??null,c),u=vl(e.runnerAgents??null,c,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:((ae=e.workstreamTitle)==null?void 0:ae.trim())||((G=e.title)==null?void 0:G.trim())||((ve=e.milestoneTitle)==null?void 0:ve.trim())||((V=e.taskTitle)==null?void 0:V.trim())||Kd(i),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((ee=e.taskTitle)==null?void 0:ee.trim())||null,nextTaskPriority:typeof e.priorityNum=="number"?e.priorityNum:null,nextTaskDueAt:e.dueAt,runnerAgentId:(g==null?void 0:g.id)??c,runnerAgentName:(g==null?void 0:g.name)??d,runnerAgents:u,runnerSource:e.runnerSource??(g?"inferred":"fallback"),queueState:Vd(e),blockReason:e.blockReason??null,queueOrigin:"system",sliceScope:l,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 Xd(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(l=>l.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 Qd(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 Jd({initiativeId:e=null,projectId:t=null,offset:s=0,limit:r=20,authToken:i=null,embedMode:a=!1,enabled:l=!0,snapshotVersion:c=null,zoomLevel:d="workstream"}){var de,we,je,ge,He,ue,ne,X,te,Ne;const u=va(),g=Ft(),x=Math.max(0,s),b=Math.max(1,Math.min(300,r)),h=o.useRef(null);o.useEffect(()=>()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]);const v=o.useMemo(()=>Zn.nextUpQueue({initiativeId:e,projectId:t,offset:x,limit:b,authToken:i,embedMode:a}),[e,t,x,b,i,a]),y=o.useRef(c);o.useEffect(()=>{c!==null&&y.current!==null&&c!==y.current&&u.invalidateQueries({queryKey:v}),y.current=c},[c,u,v]);const j=()=>{h.current&&(clearTimeout(h.current),h.current=null),h.current=setTimeout(()=>{h.current=null,u.invalidateQueries({queryKey:Zn.liveData({authToken:i,embedMode:a,projectId:t})})},Fd)},w=async({includeGraph:se=!0,includeLiveData:$=!0}={})=>{const H=[u.invalidateQueries({queryKey:v}),u.invalidateQueries({queryKey:Zn.autoContinueStatus({initiativeId:e,authToken:i,embedMode:a})})];se&&H.push(u.invalidateQueries({queryKey:Zn.missionControlGraph({initiativeId:e,authToken:i,embedMode:a})})),await Promise.all(H),$&&j()},k=async(se,$)=>{if(g)return qd(e);const H=new URLSearchParams;e&&H.set("initiative_id",e),gs(H,t,{allTokenWhenMissing:!0}),H.set("offset",String(se)),H.set("limit",String($));let z;try{z=await fetch(`/orgx/api/mission-control/next-up?${H.toString()}`,{headers:_t({authToken:i,embedMode:a})})}catch(Te){throw new Error(Bd(Te,"Failed to load next up queue"))}const K=await pr(z);if(!z.ok){const Te=Od(z,K,"Failed to load next up queue");throw new Error(Te)}const le=K??null;if(!le||le.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:se,limit:$,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(dd())return ni(le);const xe=le.items.filter(Te=>!Cs(Te.initiativeId));let Se=ni({...le,items:xe});if(Se.items.length>0)return Se;const Y=new URLSearchParams;e&&Y.set("initiative_id",e),gs(Y,t,{allTokenWhenMissing:!0}),Y.set("level","workstream"),Y.set("include_completed","0"),Y.set("offset",String(se)),Y.set("limit",String(Math.max($,24)));try{const Te=await fetch(`/orgx/api/mission-control/slices?${Y.toString()}`,{headers:_t({authToken:i,embedMode:a})}),fe=await pr(Te);if(Te.ok&&(fe!=null&&fe.ok)&&Array.isArray(fe.items)){const C=fe.items.map(O=>Gd(O)).filter(O=>!!O).filter(O=>!Cs(O.initiativeId));C.length>0&&(Se=ni({ok:!0,generatedAt:new Date().toISOString(),total:typeof fe.total=="number"&&Number.isFinite(fe.total)?Math.max(fe.total,C.length):C.length,items:C,pagination:fe.pagination&&typeof fe.pagination=="object"?{offset:typeof fe.pagination.offset=="number"?Math.max(0,Math.floor(fe.pagination.offset)):se,limit:typeof fe.pagination.limit=="number"?Math.max(1,Math.floor(fe.pagination.limit)):Math.max($,24),total:typeof fe.pagination.total=="number"?Math.max(0,Math.floor(fe.pagination.total)):C.length,nextCursor:typeof fe.pagination.nextCursor=="string"?fe.pagination.nextCursor:null,hasMore:typeof fe.pagination.hasMore=="boolean"?fe.pagination.hasMore:!1}:void 0,degraded:Array.from(new Set([...le.degraded??[],"Queue derived from slices while live queue stabilizes."]))}))}}catch{}return Se},p=hs({queryKey:v,enabled:l,queryFn:async()=>k(x,b),refetchInterval:se=>{const $=se.state.data;return!$||!Array.isArray($.items)||$.items.length===0?1e4:$.items.some(z=>z.queueState==="running")?2500:8e3}}),_=o.useRef(null);o.useEffect(()=>{var H;const se=(H=p.data)==null?void 0:H.pagination;if(!l||!(se!=null&&se.hasMore)||!se.nextCursor||_.current===se.nextCursor)return;const $=Number.parseInt(se.nextCursor,10);Number.isFinite($)&&(_.current=se.nextCursor,u.prefetchQuery({queryKey:Zn.nextUpQueue({initiativeId:e,projectId:t,offset:$,limit:b,authToken:i,embedMode:a}),queryFn:()=>k($,b),staleTime:15e3}))},[l,(we=(de=p.data)==null?void 0:de.pagination)==null?void 0:we.hasMore,(ge=(je=p.data)==null?void 0:je.pagination)==null?void 0:ge.nextCursor,e,t,b,i,a,u]);const U=mn({mutationFn:async se=>{if(g)return{ok:!0,initiativeId:se.initiativeId,workstreamId:se.workstreamId,dispatchMode:"slice",sessionId:null};const $=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:se.initiativeId,workstreamId:se.workstreamId,agentId:se.agentId??void 0,scope:se.scope??void 0,maxParallelSlices:typeof se.maxParallelSlices=="number"&&Number.isFinite(se.maxParallelSlices)?Math.max(1,Math.floor(se.maxParallelSlices)):void 0,parallelMode:se.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),H=await pr($);if(!$.ok)throw Fi($,H,"Failed to dispatch queued workstream");return H},onMutate:async se=>{await u.cancelQueries({queryKey:v});const $=u.getQueryData(v);return $?(u.setQueryData(v,{...$,items:$.items.map(H=>H.initiativeId===se.initiativeId&&H.workstreamId===se.workstreamId?{...H,queueState:"running",playbackState:"running"}:H.queueState==="running"?{...H,queueState:"idle",playbackState:"idle"}:H)}),{previous:$}):{previous:$}},onError:(se,$,H)=>{H!=null&&H.previous&&u.setQueryData(v,H.previous)},onSuccess:()=>{w({includeGraph:!1})}}),ae=mn({mutationFn:async se=>{if(g)return;const $={initiativeId:se.initiativeId,agentId:se.agentId??void 0,tokenBudgetTokens:se.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};se.scope==="workstream"&&se.workstreamId&&($.workstreamIds=[se.workstreamId]),typeof se.maxParallelSlices=="number"&&Number.isFinite(se.maxParallelSlices)&&($.maxParallelSlices=se.maxParallelSlices),se.parallelMode==="iwmt"&&($.parallelMode=se.parallelMode);const H=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify($)}),z=await pr(H);if(!H.ok){const K=Rd(z);throw K||Fi(H,z,"Failed to start auto-continue")}},onSuccess:()=>{w({includeGraph:!1})}}),G=mn({mutationFn:async se=>{if(g)return;const $=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:_t({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:se.initiativeId})}),H=await pr($);if(!$.ok)throw Fi($,H,"Failed to stop auto-continue")},onSuccess:()=>{w({includeGraph:!1})}}),ve=((He=p.data)==null?void 0:He.items)??[],V=o.useMemo(()=>d==="initiative"?Xd(ve):[],[ve,d]),ee=o.useMemo(()=>d==="milestone"?Qd(ve):[],[ve,d]);return{items:ve,total:((ue=p.data)==null?void 0:ue.total)??0,pagination:((ne=p.data)==null?void 0:ne.pagination)??null,generatedAt:((X=p.data)==null?void 0:X.generatedAt)??null,degraded:((te=p.data)==null?void 0:te.degraded)??[],isLoading:p.isLoading,isFetching:p.isFetching,error:((Ne=p.error)==null?void 0:Ne.message)??null,refetch:p.refetch,playWorkstream:U.mutateAsync,startWorkstreamAutoContinue:ae.mutateAsync,stopInitiativeAutoContinue:G.mutateAsync,isPlaying:U.isPending,isStartingAutoContinue:ae.isPending,isStoppingAutoContinue:G.isPending,zoomLevel:d,initiativeGroups:V,milestoneGroups:ee}}const Yd=750;async function nn(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 sn(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 Lt(r)}function Zd(e){const t=e.authToken??null,s=e.embedMode??!1,r=Ft(),i=va(),a=o.useRef(null);o.useEffect(()=>()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]);const l=()=>{a.current&&(clearTimeout(a.current),a.current=null),a.current=setTimeout(()=>{a.current=null,i.invalidateQueries({queryKey:["live-data"]})},Yd)},c=async()=>{await Promise.all([i.invalidateQueries({queryKey:["mission-control-next-up"]}),i.invalidateQueries({queryKey:["mission-control-graph"]}),i.invalidateQueries({queryKey:["mission-control-slices"]})]),l()},d=async k=>{if(r)return{ok:!0,demo:!0,initiativeId:k.initiativeId,workstreamId:k.workstreamId,placement:k.placement??"top"};const p=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await nn(p);if(p.ok)return _;if(!zs(p,_))throw new Error(sn(p,_,"Failed to move Next Up item"));const U=await fetch("/orgx/api/mission-control/next-up",{headers:_t({authToken:t,embedMode:s})}),ae=await nn(U);if(!U.ok)throw new Error(sn(U,ae,"Failed to read queue for move fallback"));const ve=(Array.isArray(ae==null?void 0:ae.items)?ae.items:[]).map(je=>{const ge=typeof(je==null?void 0:je.initiativeId)=="string"?je.initiativeId:null,He=typeof(je==null?void 0:je.workstreamId)=="string"?je.workstreamId:null;return!ge||!He?null:{initiativeId:ge,workstreamId:He}}).filter(je=>!!je);if(ve.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const V=ve.findIndex(je=>je.initiativeId===k.initiativeId&&je.workstreamId===k.workstreamId);if(V===-1)return{ok:!0,fallback:"reorder-move-skip"};const[ee]=ve.splice(V,1);(k.placement??"top")==="bottom"?ve.push(ee):ve.unshift(ee);const de=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:ve})}),we=await nn(de);if(!de.ok)throw new Error(sn(de,we,"Failed to move Next Up item with reorder fallback"));return we??{ok:!0,fallback:"reorder-move"}},u=async k=>{if(r)return{ok:!0,demo:!0,initiativeId:k.initiativeId,workstreamId:k.workstreamId};const p=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await nn(p);if(p.ok)return _;if(zs(p,_)){const U=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),ae=await nn(U);if(!U.ok)throw new Error(sn(U,ae,"Failed to remove item from queue with legacy fallback"));return ae??{ok:!0,fallback:"next-up-unpin"}}throw new Error(sn(p,_,"Failed to remove item from queue"))},g=mn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0};const p=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await nn(p);if(!p.ok)throw new Error(sn(p,_,"Failed to pin Next Up item"))},onSuccess:()=>{c()}}),x=mn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0};const p=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await nn(p);if(!p.ok)throw new Error(sn(p,_,"Failed to unpin Next Up item"))},onSuccess:()=>{c()}}),b=mn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0,updated:k.order.length};const p=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await nn(p);if(!p.ok)throw new Error(sn(p,_,"Failed to reorder Next Up queue"))},onSuccess:()=>{c()}}),h=mn({mutationFn:d,onSuccess:()=>{c()}}),v=mn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0,initiativeId:k.initiativeId,workstreamId:k.workstreamId};const p=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await nn(p);if(!p.ok){if(zs(p,_)){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:k.initiativeId})}),ae=await nn(U);if(!U.ok)throw new Error(sn(U,ae,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(sn(p,_,"Failed to stop triage"))}return _},onSuccess:()=>{c()}}),y=mn({mutationFn:u,onSuccess:()=>{c()}}),j=mn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0,cleared:!0};const p=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await nn(p);if(!p.ok){if(zs(p,_)&&k.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:k.initiativeId})}),ae=await nn(U);if(!U.ok)throw new Error(sn(U,ae,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(sn(p,_,"Failed to clear Next Up lifecycle state"))}return _},onSuccess:()=>{c()}}),w=mn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0,updated:k.items.length,failed:0,errors:[],fallback:"demo"};const p=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:_t({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await nn(p);if(!p.ok){if(!zs(p,_))throw new Error(sn(p,_,"Failed to apply bulk queue action"));const U=await Promise.all(k.items.map(async V=>{try{return k.action==="remove"?await u(V):await d({initiativeId:V.initiativeId,workstreamId:V.workstreamId,placement:k.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(ee){return{ok:!1,error:ee instanceof Error?ee.message:"Queue action failed"}}})),ae=U.filter(V=>V.ok).length,G=U.length-ae,ve=U.filter(V=>!V.ok&&V.error).map(V=>V.error);return{ok:G===0,updated:ae,failed:G,errors:ve,fallback:"sequential"}}return _},onSuccess:()=>{c()}});return{pin:g.mutateAsync,unpin:x.mutateAsync,reorder:b.mutateAsync,move:h.mutateAsync,remove:y.mutateAsync,stopTriage:v.mutateAsync,clear:j.mutateAsync,bulk:w.mutateAsync,isPinning:g.isPending,isUnpinning:x.isPending,isReordering:b.isPending,isMoving:h.isPending,isRemoving:y.isPending,isStoppingTriage:v.isPending,isClearing:j.isPending,isBulking:w.isPending}}function kl(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function eu(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()}`,l=await fetch(a,{headers:kl(s,r)});if(!l.ok){const c=await l.json().catch(()=>null),d=(c&&typeof c=="object"&&"error"in c&&typeof c.error=="string"?c.error:null)??(c&&typeof c=="object"&&"message"in c&&typeof c.message=="string"?c.message:null)??`Triage fetch failed (${l.status})`;throw new Error(Lt(String(d)))}return l.json()}async function tu(e,t,s,r){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,l=await fetch(a,{method:"POST",headers:kl(s,r),body:JSON.stringify(t)});if(!l.ok){const c=await l.json().catch(()=>({})),d=c.error??c.message??`Action failed (${l.status})`;throw new Error(Lt(String(d)))}return l.json()}function nu(e={}){const{enabled:t=!0,workspaceId:s=null,status:r="open",authToken:i=null,embedMode:a=!1}=e,l=va(),c=Zn.triageQueue({workspaceId:s,status:r,authToken:i,embedMode:a}),d=hs({queryKey:c,queryFn:()=>eu(s,r,i,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=mn({mutationFn:async({itemId:h,payload:v})=>tu(h,v,i,a),onSuccess:()=>{l.invalidateQueries({queryKey:c})}}),g=o.useCallback(async(h,v,y)=>u.mutateAsync({itemId:h,payload:{action:v,note:y==null?void 0:y.note,optionId:y==null?void 0:y.optionId,snoozeDurationMinutes:y==null?void 0:y.snoozeDurationMinutes}}),[u]),x=o.useMemo(()=>{var h,v,y;return{items:((h=d.data)==null?void 0:h.items)??[],total:((v=d.data)==null?void 0:v.total)??0,isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,degraded:((y=d.data)==null?void 0:y.degraded)??[],refetch:d.refetch}},[d]),b=o.useMemo(()=>({performAction:g,isActing:u.isPending,lastActionError:u.error?u.error.message:null}),[g,u.isPending,u.error]);return{model:x,actions:b}}function ce(...e){return e.filter(Boolean).join(" ")}const D={lime:"#BFFF00",teal:"#14B8A6",cyan:"#0AD4C4",iris:"#7C7CFF",amber:"#F5B700",red:"#FF6B88",background:"#02040A",cardBg:"#08090D",cardBgElevated:"#0C0E14",cardBorderStrong:"rgba(255, 255, 255, 0.12)",textMuted:"#8F9AB7"},Jh={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)"}},su={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},ru={Pace:"Engineering",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"};function jl(e){return su[e]??"rgba(255, 255, 255, 0.4)"}function Nl(e){return ru[e]??null}function iu(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function qt(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const Pt={durationFast:150,durationStandard:220,durationEntrance:360,easingStandard:[.22,1,.36,1],easingEntrance:[.16,1,.3,1],easingBounce:{type:"spring",stiffness:320,damping:28,mass:.7}},Yh={surfaceSwitch:{duration:Pt.durationStandard/1e3,ease:Pt.easingStandard},contentCrossFade:{initial:{opacity:0,y:3},animate:{opacity:1,y:0},exit:{opacity:0,y:-3},transition:{duration:Pt.durationFast/1e3,ease:Pt.easingStandard}},railMorphSpring:{type:"spring",stiffness:340,damping:38,mass:.72},listStaggerStep:.016,listStaggerMaxItems:6,segmentedTap:{whileTap:{scale:.985},transition:{duration:.09}}},Or={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{delay:Math.min(e,8)*.04,duration:Pt.durationStandard/1e3,ease:Pt.easingStandard}})},Zh={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},wi="/orgx/live/assets/Fm0FhtnV.png";function Il({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 ln({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 l=r??D.iris;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${l}1A`}),n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:l,stroke:"none"})]})}if(e==="workstream"){const l=r??D.lime;return n.jsx(Il,{size:s,className:t,stroke:l,strokeWidth:i.strokeWidth,withBackground:!0,backgroundColor:`${l}1A`})}if(e==="milestone"){const l=r??D.teal;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1z",fill:`${l}1A`})]})}if(e==="task")return n.jsxs("svg",{...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 l=r??D.amber;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("path",{d:"M12 3 5.2 6.1v5.7c0 4.8 3.2 7.5 6.8 9 3.6-1.5 6.8-4.2 6.8-9V6.1z",fill:`${l}1A`}),n.jsx("path",{d:"m9.3 12.1 1.8 1.9 3.6-3.6"})]})}if(e==="session"){const l=r??D.teal;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"4",fill:`${l}14`}),n.jsx("path",{d:"M8 9h8"}),n.jsx("path",{d:"M8 13h5"}),n.jsx("path",{d:"M8 17h3"})]})}if(e==="active"){const l=r??D.lime;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${l}12`}),n.jsx("path",{d:"M7 13h2l1.6-6 3.1 12 1.6-6H17"})]})}if(e==="blocked"){const l=r??D.red;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${l}12`}),n.jsx("rect",{x:"7.5",y:"11",width:"9",height:"7",rx:"2",fill:"rgba(255,255,255,0.03)"}),n.jsx("path",{d:"M9 11V9.2a3 3 0 0 1 6 0V11"})]})}if(e==="failed"){const l=r??D.red;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${l}12`}),n.jsx("path",{d:"M9 9l6 6"}),n.jsx("path",{d:"M15 9l-6 6"})]})}if(e==="handoff"){const l=r??D.iris;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"m13 8 4 4-4 4"}),n.jsx("path",{d:"M7 8v8",opacity:"0.55"})]})}if(e==="outbox"){const l=r??D.amber;return n.jsxs("svg",{...i,stroke:l,children:[n.jsx("path",{d:"M4 12h16"}),n.jsx("path",{d:"M6 7h12l2 5v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7z",fill:`${l}12`}),n.jsx("path",{d:"M9 14h6"})]})}const a=r??D.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 au=[{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"}],si=[{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."}],ou=[{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."}],co="openclaw plugins install @useorgx/openclaw-plugin",uo="orgx.demo_mode",lu=6500;function cu(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 du={hidden:{},visible:{transition:{staggerChildren:.07}}},ds={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},uu={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 Pi(e){const t=si.length;return(e+t)%t}function mu({state:e,isStarting:t,onConnect:s,onUseManualKey:r,onContinueWithoutOrgX:i}){const a=!!e.lastError,l=e.lastError?Lt(e.lastError):null,[c,d]=o.useState("idle"),[u,g]=o.useState("idle"),[x,b]=o.useState(0),[h,v]=o.useState(!1),y=e.hasApiKey&&e.keySource&&e.keySource!=="none",j=si[x];o.useEffect(()=>{if(c==="idle")return;const p=window.setTimeout(()=>d("idle"),2e3);return()=>window.clearTimeout(p)},[c]),o.useEffect(()=>{if(u==="idle")return;const p=window.setTimeout(()=>g("idle"),2e3);return()=>window.clearTimeout(p)},[u]),o.useEffect(()=>{if(h)return;const p=window.setInterval(()=>{b(_=>Pi(_+1))},lu);return()=>window.clearInterval(p)},[h]);const w=async()=>{try{await navigator.clipboard.writeText(co),d("ok")}catch{d("error")}},k=async()=>{try{const p={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(p,null,2)),g("ok")}catch{g("error")}};return n.jsxs(pe.section,{variants:du,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(pe.div,{variants:ds,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:wi,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(pe.h2,{variants:ds,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(ln,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(pe.p,{variants:ds,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(pe.div,{variants:ds,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:()=>v(!0),onMouseLeave:()=>v(!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(ln,{type:"workstream",size:14,className:"text-[#BFFF00]"}),n.jsx("p",{className:"text-micro uppercase tracking-[0.1em] text-secondary",children:"Guided Tour"})]}),n.jsxs("span",{className:"chip text-micro",children:[x+1,"/",si.length]})]}),n.jsx(yt,{initial:!1,mode:"wait",children:n.jsxs(pe.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:j.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:j.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:j.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:j.highlights.map(p=>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(ln,{type:p.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:p.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:p.detail})]},`${j.id}-${p.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:j.footnote})]},j.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:si.map((p,_)=>{const U=_===x;return n.jsx("button",{type:"button",onClick:()=>b(_),"aria-label":`View slide ${_+1}`,className:`h-1.5 rounded-full transition-all ${U?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},p.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>b(p=>Pi(p-1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Prev"}),n.jsx("button",{type:"button",onClick:()=>b(p=>Pi(p+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:au.map(p=>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 ${uu[p.iconType]}`,children:n.jsx(ln,{type:p.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:p.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:p.desc})]},p.label))}),n.jsxs(pe.div,{variants:ds,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(pe.div,{variants:ds,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(ln,{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(ln,{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:co}),n.jsx("button",{type:"button",onClick:()=>{w()},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"})]}),y&&n.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["API key source detected: ",cu(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:ou.map(p=>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(ln,{type:p.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:p.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:p.detail})]},p.label))})]})]})]}),n.jsx(pe.div,{variants:ds,className:"mx-6 mt-2 sm:mx-8",children:a?n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-red-500/15 bg-red-500/[0.04] px-4 py-3",children:[n.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500/15",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:n.jsx("path",{d:"M5 2.5v3M5 7.5h.004",stroke:"#FF6B88",strokeWidth:"1.4",strokeLinecap:"round"})})}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx("p",{className:"text-body text-red-300/80",children:l})}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void k(),className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",title:"Copy debug details for support",children:u==="ok"?"Copied":u==="error"?"Copy failed":"Copy debug"}),n.jsx("button",{type:"button",onClick:r,className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Use API key"}),n.jsx("button",{type:"button",onClick:s,disabled:t,className:"rounded-full border border-red-500/20 bg-red-500/[0.06] px-3 py-1 text-caption font-semibold text-red-200/85 transition hover:bg-red-500/[0.09] hover:text-red-100 disabled:opacity-50",children:"Retry"})]})]}):n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-subtle bg-white/[0.02] px-3.5 py-2",children:[n.jsx("span",{className:"relative flex h-1.5 w-1.5",children:n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-white/40"})}),n.jsx("span",{className:"text-body text-muted",children:"Ready to connect"})]})}),n.jsxs(pe.div,{variants:ds,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(uo,"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(uo)}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 pu={hidden:{},visible:{transition:{staggerChildren:.06}}},vs={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function fu({isSubmitting:e,onSubmit:t,onBack:s}){const[r,i]=o.useState(""),[a,l]=o.useState(null),c="https://www.useorgx.com/settings#security",d=async()=>{l(null);const g=r.trim();if(!g){l("API key is required.");return}const x=/^[a-z]+_/i.test(g)?g:`oxk_${g}`;try{await t(x),i("")}catch(b){const h=b instanceof Error?b.message:"Failed to validate API key.";l(Lt(h))}},u=a!==null;return n.jsxs(pe.section,{variants:pu,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(pe.div,{variants:vs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:wi,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(pe.h3,{variants:vs,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(pe.p,{variants:vs,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(pe.p,{variants:vs,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(pe.div,{variants:vs,className:"mt-3",children:n.jsxs("a",{href:c,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 rounded-full border border-white/[0.10] bg-white/[0.03] px-3 py-1.5 text-body font-semibold text-secondary transition hover:bg-white/[0.06] hover:text-primary",title:"Open OrgX settings to generate an API key",children:["Generate an API key",n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",children:[n.jsx("path",{d:"M4.5 2.5h5v5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M9.5 2.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M2.75 3.5H2.5c-.55 0-1 .45-1 1v5c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]})]})})]}),n.jsxs(pe.div,{variants:vs,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&&l(null)},placeholder:"paste your key",className:"w-full bg-transparent px-3 py-2.5 font-mono text-body text-white outline-none placeholder:text-faint"})]}),u&&n.jsx(pe.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(pe.div,{variants:vs,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 mo="orgx.user.display-name",po="orgx.user.avatar-seed-suffix";function fo(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function ho(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function hu(){const[e,t]=o.useState(()=>fo(mo)),[s,r]=o.useState(()=>fo(po)),i=(e||"orgx-user")+s,a=o.useCallback(c=>{const d=c.trim();ho(mo,d),t(d)},[]),l=o.useCallback(()=>{const c=String(Date.now());ho(po,c),r(c)},[]);return{displayName:e,avatarSeed:i,updateName:a,regenerateAvatar:l}}function gu(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function xu(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 go=[D.lime,D.teal,D.iris,D.cyan];function yu(e,t,s,r,i,a){const l=_=>_*Math.PI/180,c=Math.cos,d=Math.sin,u=l(i),g=l(a),x=a-i>180?1:0,b=e+r*c(u),h=t+r*d(u),v=e+r*c(g),y=t+r*d(g),j=e+s*c(g),w=t+s*d(g),k=e+s*c(u),p=t+s*d(u);return[`M ${b} ${h}`,`A ${r} ${r} 0 ${x} 1 ${v} ${y}`,`L ${j} ${w}`,`A ${s} ${s} 0 ${x} 0 ${k} ${p}`,"Z"].join(" ")}function bu(e){const t=xu(gu(e)),s=3+Math.floor(t()*2),r=[],i=50,a=50;for(let l=0;l<s;l++){const c=8+l*10,d=c+9,u=6+Math.floor(t()*6),g=360/u,x=1.5+t()*2;for(let b=0;b<u;b++){if(t()<.15)continue;const h=b*g+x/2,v=(b+1)*g-x/2,y=go[Math.floor(t()*go.length)],j=.25+t()*.55;r.push({d:yu(i,a,c,d,h,v),fill:y,opacity:j})}}return r}function wu({seed:e,size:t,className:s,animate:r=!0}){const i=o.useMemo(()=>bu(e),[e]);return n.jsxs(pe.svg,{viewBox:"0 0 100 100",width:t,height:t,className:ce("flex-shrink-0",s),initial:r?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease:Pt.easingEntrance},children:[n.jsxs("defs",{children:[n.jsx("clipPath",{id:`avatar-clip-${e}`,children:n.jsx("circle",{cx:"50",cy:"50",r:"48"})}),n.jsxs("radialGradient",{id:`avatar-glow-${e}`,cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:D.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:D.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:D.cardBg}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#avatar-glow-${e})`}),n.jsx("g",{clipPath:`url(#avatar-clip-${e})`,children:i.map((a,l)=>n.jsx(pe.path,{d:a.d,fill:a.fill,initial:r?{opacity:0,scale:.85}:!1,animate:{opacity:a.opacity,scale:1},transition:{delay:l*.012,duration:.35,ease:Pt.easingEntrance},style:{transformOrigin:"50px 50px"}},l))}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"1"})]},e)}function vu({onComplete:e}){const{displayName:t,updateName:s}=hu(),[r,i]=o.useState(t),a=o.useCallback(()=>{s(r),e()},[r,s,e]),l=o.useCallback(()=>{e()},[e]),c=o.useCallback(u=>{u.key==="Enter"&&a()},[a]),d=(r.trim()||"orgx-user")+"";return n.jsx(pe.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:Pt.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(wu,{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:c,maxLength:64,autoFocus:!0,placeholder:"Your name",className:"mt-5 h-10 w-full max-w-xs rounded-xl border border-white/[0.12] bg-white/[0.04] px-4 text-center text-body text-white placeholder:text-muted focus:border-lime/30 focus:outline-none"}),n.jsx("button",{type:"button",onClick:a,className:"mt-5 rounded-full bg-lime px-6 py-2.5 text-body font-medium text-black transition hover:brightness-110",children:r.trim()?"Continue":"Continue without name"}),r.trim()&&n.jsx("button",{type:"button",onClick:l,className:"mt-3 text-caption text-secondary transition hover:text-white",children:"Skip"})]})})})}const ku=[{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 ju({className:e,compact:t=!1}){return n.jsxs("div",{className:ce("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"]}),ku.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 xo="orgx.user.name-asked";function Nu(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 Iu(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 Au(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const yo={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},Oi="orgx.onboarding.mc_hint.dismissed",Bi={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 Su({state:e,isLoading:t,isStarting:s,isSubmittingManual:r,onRefresh:i,onStartPairing:a,onSubmitManualKey:l,onBackToPairing:c,onUseManualKey:d,onSkip:u}){const[g,x]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Oi)==="1"),[b,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(xo)!=="1"),v=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(xo,"1"),h(!1)},[]);o.useEffect(()=>{typeof window>"u"||(g?window.localStorage.setItem(Oi,"1"):window.localStorage.removeItem(Oi))},[g]);const y=e.status==="manual_key",j=e.status==="awaiting_browser_auth"||e.status==="pairing",w=Au(e.status),k=w==="active"&&e.status!=="connected",p=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(pe.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.45},className:`relative z-10 w-full ${y?"max-w-lg":"max-w-[1120px]"}`,children:[t?n.jsxs("div",{className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] rounded-2xl p-6 sm:p-8",children:[n.jsx("div",{className:"shimmer-skeleton h-7 w-28 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-5 h-8 w-3/4 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-3 h-4 w-2/3 rounded-lg"}),n.jsxs("div",{className:"mt-7 grid grid-cols-3 gap-2.5",children:[n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"})]}),n.jsx("div",{className:"shimmer-skeleton mt-7 h-10 w-36 rounded-full"})]}):n.jsx(yt,{mode:"wait",children:e.status==="connected"&&b?n.jsx(pe.div,{...Bi,children:n.jsx(vu,{onComplete:v})},"welcome-name"):y?n.jsx(pe.div,{...Bi,children:n.jsx(fu,{isSubmitting:r,onSubmit:l,onBack:c})},"manual"):n.jsx(pe.div,{...Bi,children:n.jsx(mu,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(j||e.status==="connected")&&n.jsxs(pe.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:[k&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${yo[w]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${yo[w]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:Nu(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:Iu(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"})]})]}),p&&n.jsxs(pe.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:.2,duration:.3},className:"mt-3 rounded-xl border border-[#7C7CFF]/25 bg-[#7C7CFF]/10 px-4 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-[#CFCBFF]",children:"Mission Control Tip"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-[#E6E4FF]",children:"Open Mission Control to see initiative → workstream → milestone → task flow with dependencies and recent todos in one expandable view."}),n.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[n.jsx("a",{href:"/orgx/live?view=mission-control",className:"rounded-full border border-[#BFFF00]/30 bg-[#BFFF00]/15 px-3 py-1 text-caption font-medium text-[#D8FFA1]",children:"Open Mission Control"}),n.jsx("button",{type:"button",onClick:()=>x(!0),className:"text-caption text-secondary underline underline-offset-2",children:"Dismiss"})]})]}),!t&&n.jsx("div",{className:"mt-3 flex justify-center",children:n.jsx(ju,{compact:!0})})]})})}function _u({children:e,color:t,pulse:s,title:r}){const i=t??D.lime;return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-micro font-semibold uppercase tracking-[0.14em]",title: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 vi({open:e,onClose:t,children:s,maxWidth:r="max-w-2xl",fitContent:i=!1,closeOnBackdropClick:a=!0,closeOnEscape:l=!0,closeOnEscapeWhenTyping:c=!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 v=d.current;if(!v)return;const y=v.querySelector('[data-modal-autofocus="true"]');if(y){y.focus();return}const j=v.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():v.focus()})();const b=v=>{if(v.key==="Escape"){if(!l)return;if(!c){const _=v.target;if(_&&(_.tagName==="INPUT"||_.tagName==="TEXTAREA"||_.tagName==="SELECT"||_.isContentEditable))return}v.preventDefault(),t();return}if(v.key!=="Tab")return;const y=d.current;if(!y)return;const j=y.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(j.length===0){v.preventDefault(),y.focus();return}const w=j[0],k=j[j.length-1],p=document.activeElement;!v.shiftKey&&p===k?(v.preventDefault(),w.focus()):v.shiftKey&&p===w&&(v.preventDefault(),k.focus())},h=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",b),()=>{var v;document.body.style.overflow=h,document.removeEventListener("keydown",b),(v=u.current)==null||v.focus()}},[e,t,l,c]);const g=n.jsx(yt,{children:e&&n.jsxs(pe.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(pe.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:D.cardBgElevated,borderColor:D.cardBorderStrong},onClick:x=>x.stopPropagation(),role:"dialog","aria-modal":"true",tabIndex:-1,ref:d,children:[n.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-white/50 to-transparent"}),s]})]})});return typeof document>"u"?g:oc.createPortal(g,document.body)}const Cu=[{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 Mu({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:Cu.map(r=>{const i=e===r.id;return n.jsxs("button",{type:"button",onClick:()=>t(r.id),"aria-current":i?"page":void 0,className:ce("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(pe.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(pe.span,{layoutId:"mobile-tab-active-line",className:"absolute inset-x-3 top-0.5 h-[2px] rounded-full",style:{backgroundColor:D.lime},transition:{type:"spring",stiffness:440,damping:36,mass:.75}})]}),n.jsxs("span",{className:ce("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:D.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:ce("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:ce("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const Tu={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"},Eu="/orgx/live/",rn=e=>`${Eu.replace(/\/+$/,"/")}${e}`,Ru={pace:rn("brand/product-orchestrator.png"),eli:rn("brand/engineering-autopilot.png"),mark:rn("brand/launch-captain.png"),sage:rn("brand/pipeline-intelligence.png"),orion:rn("brand/control-tower.png"),dana:rn("brand/design-codex.png"),xandy:rn("brand/xandy-orchestrator.png"),nova:rn("brand/xandy-orchestrator.png"),openclaw:rn("brand/openclaw-mark.svg"),codex:rn("brand/openai-mark.svg"),openai:rn("brand/openai-mark.svg"),anthropic:rn("brand/anthropic-mark.svg"),orgx:rn("brand/orgx-logo.png")},Lu=[{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 Du(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of Lu)if(s.test.test(t))return Ru[s.key];return null}function Ot({name:e,size:t="xs",hint:s,src:r}){const i=jl(e),[a,l]=o.useState(!1),c=o.useMemo(()=>r&&r.trim()?r:Du(e,s),[s,e,r]),d=!!(c&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${Tu[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:c??void 0,alt:e,className:"h-full w-full rounded-full object-cover",onError:()=>l(!0),loading:"lazy"}):iu(e)})}Ot.displayName="AgentAvatar";const $u={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 Nn({children:e,tone:t="muted",className:s,...r}){const i=o.Children.toArray(e).some(a=>{if(!o.isValidElement(a))return!1;const l=a.type;return l.displayName==="AgentAvatar"||l.name==="AgentAvatar"});return n.jsx("span",{className:ce("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",$u[t],s),...r,children:e})}function Fu(e){var s,r;const t=[];if(e.initiativeId){const i={id:e.initiativeId,label:e.initiativeTitle||As(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=Al(e.status),l={id:e.workstreamId,label:e.workstreamTitle||As(e.workstreamId,"Workstream"),type:"workstream",status:a,progress:e.scopeProgress?{done:e.scopeProgress.completedTasks,total:e.scopeProgress.totalTasks}:void 0,agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]};if((s=e.scopeProgress)!=null&&s.milestones&&e.scopeProgress.milestones.length>0)for(const c of e.scopeProgress.milestones){const d=c.done>=c.total?"done":c.done>0?"active":"pending",u={id:c.id,label:c.title||As(c.id,"Milestone"),type:"milestone",status:d,progress:{done:c.done,total:c.total}};c.total>0&&(u.children=Array.from({length:c.total},(g,x)=>({id:`${c.id}-task-${x}`,label:`Task ${x+1}`,type:"task",status:x<c.done?"done":"pending"}))),l.children.push(u)}else if(e.taskIds&&e.taskIds.length>0){const c=((r=e.scopeProgress)==null?void 0:r.completedTasks)??0;l.children=e.taskIds.map((d,u)=>({id:d,label:As(d,"Task"),type:"task",status:u<c?"done":"pending"}))}i.children.push(l)}t.push(i)}return t}function eg(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||As(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,r=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||As(e.workstreamId,"Workstream"),type:"workstream",status:Al(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,i=e.taskId?{id:e.taskId,label:e.taskTitle||As(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 As(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function Al(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 Sl(e){switch(e){case"done":return D.lime;case"active":return D.teal;case"blocked":return D.amber;case"failed":return D.red;default:return"rgba(255,255,255,0.15)"}}function Pu(e){const t=Sl(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const Ou=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(pe.div,{className:"h-full rounded-full",style:{backgroundColor:r},initial:{width:0},animate:{width:`${i}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),Bu=16,qu=14,bo=8,zu=8,Wu=28,Uu=24,Hu=24,Vu=20,qi="rgba(255,255,255,0.07)";function Ku(e){const t=e?qu:Bu,s=t+zu+4;return{iconSz:t,colW:s,rowH:e?Hu:Wu,rowHTask:e?Vu:Uu}}function _l({node:e,depth:t,isLast:s,activeId:r,compact:i,index:a,taskLimit:l,expanded:c,onToggleExpand:d}){const u=r===e.id||e.highlight,g=e.progress&&e.progress.total>0,x=e.type==="task",{iconSz:b,colW:h,rowH:v,rowHTask:y}=Ku(i),j=x?y:v,w=e.children??[],k=w.filter(V=>V.type==="task"),p=w.filter(V=>V.type!=="task"),_=k.length>l&&!c,U=_?k.slice(0,l):k,ae=k.length-U.length,G=[...p,...U],ve=G.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:qi,left:(t-1)*h+h/2,top:0,bottom:s?void 0:0,height:s?j/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:qi,left:(t-1)*h+h/2,top:j/2,width:h}})]}),n.jsxs(pe.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*h},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:h,height:j},children:x?n.jsx("span",{className:"inline-block rounded-full",style:{...Pu(e.status),width:bo,height:bo}}):n.jsx(ln,{type:e.type,size:b,accent:u?D.lime:void 0})}),n.jsxs("div",{className:"min-w-0 flex-1 pr-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:`min-w-0 truncate ${x?`text-[12px] leading-none ${e.status==="done"?"text-white/40 line-through decoration-white/10":"text-white/35"}`:e.type==="milestone"?"text-[13px] font-medium leading-none text-white/55":t===0?"text-[13px] font-medium leading-none text-white/80":"text-[13px] font-medium leading-none text-white/70"} ${u?"!text-white/90 !no-underline":""}`,children:e.label}),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&&!x&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(Ou,{done:e.progress.done,total:e.progress.total,color:Sl(e.status)})})]})]}),ve&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:qi,left:t*h+h/2,top:j/2,height:j/2}}),ve&&n.jsxs("div",{children:[G.map((V,ee)=>n.jsx(_l,{node:V,depth:t+1,isLast:ee===G.length-1&&!_,activeId:r,compact:i,index:a+ee+1,taskLimit:l,expanded:c,onToggleExpand:d},V.id)),_&&n.jsxs(pe.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+G.length+1)*.02},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{height:y,paddingLeft:(t+1)*h+h},children:["+",ae," more · see all"]}),n.jsx(yt,{children:c&&k.length>l&&n.jsx(pe.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:y},exit:{opacity:0,height:0},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{paddingLeft:(t+1)*h+h},children:"show less"})})]})]})}const Gu=o.memo(function({nodes:t,className:s,activeId:r,compact:i,taskLimit:a=4}){const[l,c]=o.useState(!1);return t.length===0?null:n.jsx("div",{className:s,children:t.map((d,u)=>n.jsx(_l,{node:d,depth:0,isLast:u===t.length-1,activeId:r,compact:i,index:u,taskLimit:a,expanded:l,onToggleExpand:()=>c(g=>!g)},d.id))})}),ma={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"}},Xu=Object.keys(ma);function wo(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of Xu)if(t.includes(s))return s;return"engineering"}function vo(e){return ma[e]??ma.engineering}const Bs={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},fr={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},ko={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},jo={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 Cl(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=jo[r];if(i){const a=fr[i]??"";return{name:i,domain:a,color:Bs[i]??s.color,displayLabel:a?`${i} (${a})`:i}}for(const[a,l]of Object.entries(ko))if(r.includes(a)){const c=fr[l]??"";return{name:l,domain:c,color:Bs[l]??s.color,displayLabel:c?`${l} (${c})`:l}}}if(t){const r=t.trim();if(Bs[r]){const l=fr[r]??"";return{name:r,domain:l,color:Bs[r],displayLabel:l?`${r} (${l})`:r}}const i=r.toLowerCase(),a=jo[i];if(a){const l=fr[a]??"";return{name:a,domain:l,color:Bs[a]??s.color,displayLabel:l?`${a} (${l})`:a}}for(const[l,c]of Object.entries(ko))if(i.includes(l)){const d=fr[c]??"";return{name:c,domain:d,color:Bs[c]??s.color,displayLabel:d?`${c} (${d})`:c}}}return s}function tg({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(Ot,{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 Qu=new Set(["running","active","in_progress","working","planning","dispatching"]),Ju=new Set(["running","dispatching"]),Yu=3*6e4;function Zu(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=Yu:!1}function em(e){const t=qt(e.status??""),s=qt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:Qu.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?Zu(e.lastHeartbeatAt):!1}function Ml(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function tm(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 nm(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 Tl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function Br(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ks(e,t){const s=[],r=i=>{if(typeof i!="string")return;const a=i.trim();a&&(s.some(l=>l.toLowerCase()===a.toLowerCase())||s.push(a))};if(Array.isArray(e))for(const i of e)r(i);return r(t??null),s}function di(e,t){if(!e)return t;const s=e.trim();return s?On(s)?`${t} ${us(s)}`:s:t}const sm=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),rm=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function im(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?sm.has(t)||t.startsWith("telegram:"):!1}function am(e){if(!e)return!1;const t=e.trim();return t?rm.some(s=>s.test(t)):!1}function El({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var x,b,h,v,y,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 k=(x=w.runId)==null?void 0:x.trim();!k||i.has(k)||i.set(k,w)}const a=new Map;for(const w of e){const k=((b=w.initiativeId)==null?void 0:b.trim())??"",p=((h=w.workstreamId)==null?void 0:h.trim())??"";if(!k||!p)continue;const _=`${k}:${p}`;a.has(_)||a.set(_,w)}const l=new Set;for(const w of e){const k=(v=w.runId)==null?void 0:v.trim();k&&l.add(k)}const c=[];for(const w of t){if(!Ju.has(w.status))continue;const k=(w.runId??w.sliceRunId??"").trim();if(!k)continue;const p=ks(w.initiativeIds,w.initiativeId),_=ks(w.workstreamIds,w.workstreamId),U=p[0]??null,ae=_[0]??null,G=[];for(const we of p)for(const je of _)!we||!je||G.push(`${we}:${je}`);if(!(l.has(k)||G.some(we=>a.has(we))))continue;const V=i.get(k)??(G.length>0?G.map(we=>a.get(we)??null).find(we=>!!we)??null:null),ee=U?r.get(U)??U:null,de=w.scopeProgress&&typeof w.scopeProgress.totalTasks=="number"&&w.scopeProgress.totalTasks>0?Math.round(w.scopeProgress.completedTasks/w.scopeProgress.totalTasks*100):null;c.push({key:`slice:${w.sliceRunId}`,source:"slice",session:V??null,runId:k,status:qt(w.status),title:w.workstreamTitle??(V==null?void 0:V.title)??`Work slice ${w.sliceRunId.slice(0,8)}`,subtitle:w.statusExplainer??w.lastEventSummary??(V==null?void 0:V.lastEventSummary)??null,progress:de??(V==null?void 0:V.progress)??null,initiativeId:U,initiativeIds:p,initiativeTitle:ee,workstreamId:ae,workstreamIds:_,iwmtId:w.iwmtId??null,iwmtIds:ks(w.iwmtIds,w.iwmtId),workstreamTitle:w.workstreamTitle??(V==null?void 0:V.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??(V==null?void 0:V.updatedAt)??null,scope:w.scope,milestoneProgress:(y=w.scopeProgress)==null?void 0:y.milestones})}if(c.sort((w,k)=>Br(k.updatedAt)-Br(w.updatedAt)),c.length>0){const w=[],k=new Set;for(const p of c){const _=p.initiativeId??((j=p.initiativeIds)==null?void 0:j[0])??"none",ae=(p.workstreamId?`scope:${_}:${p.workstreamId}`:null)??(p.runId?`run:${p.runId}`:p.key);k.has(ae)||(k.add(ae),w.push(p))}return w}const d=e.filter(w=>{if(!em(w))return!1;const k=(w.initiativeId??"").trim(),p=(w.workstreamId??"").trim();return k.length>0&&p.length>0});d.sort((w,k)=>{const p=Br(w.updatedAt??w.lastEventAt??w.startedAt);return Br(k.updatedAt??k.lastEventAt??k.startedAt)-p});const u=[],g=new Set;for(const w of d){const k=w.workstreamId&&w.workstreamId.trim().length>0?`${w.initiativeId??"none"}:${w.workstreamId}`:w.runId;g.has(k)||(g.add(k),u.push(w))}return u.map(w=>{var k;return{key:`session:${w.id}`,source:"session",session:w,runId:w.runId,status:qt(w.status??""),title:w.title,subtitle:(k=w.lastEventSummary)!=null&&k.trim()?w.lastEventSummary.trim():null,progress:w.progress,initiativeId:w.initiativeId,initiativeIds:ks(void 0,w.initiativeId),initiativeTitle:w.initiativeId?r.get(w.initiativeId)??w.groupLabel??null:w.groupLabel??null,workstreamId:w.workstreamId,workstreamIds:ks(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 om=o.memo(function({sessions:t,sliceRuns:s=[],initiatives:r=[],title:i="In Progress",className:a,showHeader:l=!0,panelStyle:c="card",needsAttentionCount:d=0,onSwitchToNeedsAttention:u,onOpenSession:g,onFocusRunId:x,onPlayWorkstream:b,onPauseWorkstream:h,onResumeWorkstream:v,onRestartSession:y,onIntervene:j,onOpenSliceDetail:w}){const[k,p]=o.useState(null),[_,U]=o.useState(null),[ae,G]=o.useState(null),[ve,V]=o.useState(null),ee=o.useMemo(()=>{const X=new Map;if(!Array.isArray(s))return X;for(const te of s){const Ne=ks(te.initiativeIds,te.initiativeId),se=ks(te.workstreamIds,te.workstreamId);for(const H of Ne)for(const z of se){if(!H||!z)continue;const K=`${H}:${z}`;X.has(K)||X.set(K,te)}const $=(te.runId??te.sliceRunId??"").trim();$&&!X.has(`run:${$}`)&&X.set(`run:${$}`,te)}return X},[s]),de=o.useMemo(()=>El({sessions:t,sliceRuns:s,initiatives:r}),[r,t,s]),we=o.useMemo(()=>{const X=new Map;for(const te of de){const Ne=qt(te.status);X.set(Ne,(X.get(Ne)??0)+1)}return Array.from(X.entries()).sort((te,Ne)=>Ne[1]-te[1]).map(([te,Ne])=>({status:te,count:Ne}))},[de]),je=o.useMemo(()=>k?de.filter(X=>qt(X.status)===k):de,[k,de]),ge=o.useMemo(()=>{var se,$;const X=new Map,te=[];for(const H of je){const z=(((se=H.initiativeIds)==null?void 0:se[0])??H.initiativeId??"").trim(),K=((($=H.workstreamIds)==null?void 0:$[0])??H.workstreamId??"").trim();if(!z){te.push(H);continue}let le=X.get(z);le||(le={title:H.initiativeTitle??z,wsMap:new Map},X.set(z,le));const xe=K||"__none__";let Se=le.wsMap.get(xe);Se||(Se={title:H.workstreamTitle??(K||"Unassigned"),rows:[],completedCount:0,lastActivity:null},le.wsMap.set(xe,Se));const Y=qt(H.status);if(Y==="completed"||Y==="done"?Se.completedCount+=1:Se.rows.push(H),H.updatedAt){const Te=Date.parse(H.updatedAt),fe=Se.lastActivity?Date.parse(Se.lastActivity):0;Number.isFinite(Te)&&Te>fe&&(Se.lastActivity=H.updatedAt)}}const Ne=[];for(const[H,z]of X){const K=[];for(const[le,xe]of z.wsMap)K.push({workstreamId:le,workstreamTitle:xe.title,rows:xe.rows,completedCount:xe.completedCount,lastActivityAt:xe.lastActivity});K.sort((le,xe)=>{const Se=le.lastActivityAt?Date.parse(le.lastActivityAt):0;return(xe.lastActivityAt?Date.parse(xe.lastActivityAt):0)-Se}),Ne.push({initiativeId:H,initiativeTitle:z.title,workstreams:K})}return Ne.sort((H,z)=>{const K=Math.max(0,...H.workstreams.map(xe=>xe.lastActivityAt?Date.parse(xe.lastActivityAt):0));return Math.max(0,...z.workstreams.map(xe=>xe.lastActivityAt?Date.parse(xe.lastActivityAt):0))-K}),{groups:Ne,ungrouped:te}},[je]),[He,ue]=o.useState(new Set),ne=async(X,te,Ne)=>{if(X.session){V(null),U(X.session.id);try{await te(X.session),V(Ne)}catch(se){const $=se instanceof Error?se.message:"";V($?Lt($):"Workstream action failed")}finally{U(null)}}};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":""} ${a??""}`,children:[l?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:i}),n.jsx("span",{className:"chip text-micro",children:de.length})]})}):null,we.length>1&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 border-b border-subtle px-3 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>p(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${k===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:de.length})]}),we.map(({status:X,count:te})=>n.jsxs("button",{type:"button",onClick:()=>p(Ne=>Ne===X?null:X),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${k===X?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[Ml(X),n.jsx("span",{className:"tabular-nums opacity-70",children:te})]},X))]}),ve&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:ve}),je.length===0?de.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:de.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(pe.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[ge.groups.map(X=>n.jsxs("div",{children:[n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:Bt(X.initiativeTitle&&!On(X.initiativeTitle)?X.initiativeTitle:di(X.initiativeId,"Initiative"))}),X.workstreams.map(te=>{var Y,Te;const Ne=`${X.initiativeId}:${te.workstreamId}`,se=He.has(Ne),$=te.rows[0]??null,H=$?Cl((Y=$.session)==null?void 0:Y.agentId,(Te=$.session)==null?void 0:Te.agentName):null,z=$!=null&&$.milestoneProgress?$.milestoneProgress.reduce((fe,C)=>fe+C.total,0):null,K=$!=null&&$.milestoneProgress?$.milestoneProgress.reduce((fe,C)=>fe+C.done,0):null,le=z&&z>0?`Task ${(K??0)+1} of ${z}`:null,xe=z&&z>0?Math.round((K??0)/z*100):($==null?void 0:$.progress)!=null?Tl($.progress):null,Se=Bt($!=null&&$.workstreamTitle&&!On($.workstreamTitle)?$.workstreamTitle:di(te.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:[H&&n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${H.color}20`,color:H.color},children:H.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:Se,children:Se}),H?n.jsx("p",{className:"truncate text-[11px] font-medium",style:{color:H.color},title:H.displayLabel,children:H.displayLabel}):null]})]}),le&&n.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/50",children:le}),n.jsx("div",{className:"h-1 rounded-full bg-white/10 w-24",children:n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,xe??0)}%`,backgroundColor:(H==null?void 0:H.color)??"#14B8A6"}})})]})]}),n.jsx("div",{className:"space-y-2",children:te.rows.map((fe,C)=>n.jsx(No,{row:fe,index:C,sliceRunByScope:ee,busySessionId:_,expandedRowKey:ae,setExpandedRowKey:G,onOpenSession:g,onFocusRunId:x,onPauseWorkstream:h,onResumeWorkstream:v,onRestartSession:y,onPlayWorkstream:b,onIntervene:j,onOpenSliceDetail:w,runWorkstreamAction:ne,showInitiativeLabel:!1},fe.key))}),te.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>ue(fe=>{const C=new Set(fe);return C.has(Ne)?C.delete(Ne):C.add(Ne),C}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:se?`Hide ${te.completedCount} completed`:`${te.completedCount} completed`})})]},te.workstreamId)})]},X.initiativeId)),ge.ungrouped.length>0&&n.jsxs("div",{children:[ge.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:ge.ungrouped.map((X,te)=>n.jsx(No,{row:X,index:te,sliceRunByScope:ee,busySessionId:_,expandedRowKey:ae,setExpandedRowKey:G,onOpenSession:g,onFocusRunId:x,onPauseWorkstream:h,onResumeWorkstream:v,onRestartSession:y,onPlayWorkstream:b,onIntervene:j,onOpenSliceDetail:w,runWorkstreamAction:ne,showInitiativeLabel:!0},X.key))})]})]})})]})});function No({row:e,index:t,sliceRunByScope:s,busySessionId:r,expandedRowKey:i,setExpandedRowKey:a,onOpenSession:l,onFocusRunId:c,onPauseWorkstream:d,onResumeWorkstream:u,onRestartSession:g,onPlayWorkstream:x,onIntervene:b,onOpenSliceDetail:h,runWorkstreamAction:v,showInitiativeLabel:y=!0}){var te,Ne,se,$,H,z,K,le,xe,Se;const j=qt(e.status??""),w=e.updatedAt,k=e.subtitle?e.subtitle:w?`Updated ${Mt(w)}`:null,p=y&&(e.initiativeTitle||e.initiativeId)?Bt(e.initiativeTitle&&!On(e.initiativeTitle)?e.initiativeTitle:di(e.initiativeId,"Initiative")):null,_=(te=e.title)!=null&&te.trim()?e.title:"",U=im(_)&&((Ne=e.workstreamTitle)!=null&&Ne.trim())?e.workstreamTitle:_||e.workstreamTitle||"",ae=di(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),G=Bt(U&&!On(U)?U:ae),ve=k&&!am(k)?Bt(k):null,V=Tl(e.progress),ee=["running","active","in_progress","working","planning","dispatching"].includes(j),de=["paused","blocked","queued","pending"].includes(j),we=g??x,je=V===null&&["running","active","in_progress","working","planning","dispatching"].includes(j),ge=e.session?r===e.session.id:!1,He=i===e.key,ue=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),ne=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),X=Cl((se=e.session)==null?void 0:se.agentId,($=e.session)==null?void 0:$.agentName);return n.jsxs(pe.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:()=>h==null?void 0:h(e,ne),role:"button",tabIndex:0,onKeyDown:Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),h==null||h(e,ne))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${nm(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":X.color}:void 0,children:n.jsx(Ot,{name:((H=e.session)==null?void 0:H.agentName)??"OrgX",hint:((z=e.session)==null?void 0:z.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[p?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:p}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(ln,{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:G,children:G})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(Nn,{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] ${tm(j)}`,children:Ml(j)}),w&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:uc(new Date(w),{addSuffix:!0})})]}),ve?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:ve,children:ve}):null,null,(V!==null||je)&&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:V===null?"Live":`${V}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${V===100?" shimmer-on-complete":""}`,children:V===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,V)}%`,background:`linear-gradient(90deg, ${vo(wo((K=e.session)==null?void 0:K.agentId)).gradient[0]}, ${vo(wo((le=e.session)==null?void 0:le.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(Gu,{nodes:Fu({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((Y,Te)=>Y+Te.total,0),completedTasks:e.milestoneProgress.reduce((Y,Te)=>Y+Te.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((xe=e.session)==null?void 0:xe.agentName)??null,agentId:((Se=e.session)==null?void 0:Se.agentId)??null}),activeId:e.workstreamId,compact:!0})}),ue?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:Y=>{Y.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:He?"Hide details":"Slice details"}),He?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:Y=>Y.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>{if(e.session){l==null||l(e.session.id);return}c==null||c(e.runId)},className:"control-pill h-7 px-2.5 text-micro font-semibold",title:e.session?"Open session detail":"Focus in Activity",children:e.session?"Open":"Focus"}),e.session&&ee&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ge,onClick:()=>void v(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&&de&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ge,onClick:()=>void v(e,u,`Resumed ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Resume this workstream",children:"Resume"}),e.session&&we&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:ge,onClick:()=>void v(e,we,`Restarted ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Restart this workstream",children:"Restart"}),e.session&&b&&n.jsx("button",{type:"button",disabled:ge,onClick:()=>void v(e,b,`Opened intervention for ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Intervene with context and guidance",children:"Intervene"})]})]})]})]},e.key)}const lm={inbox:n.jsx("path",{d:"M22 12h-6l-2 3H10l-2-3H2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),search:n.jsxs(n.Fragment,{children:[n.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"m21 21-4.3-4.3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),activity:n.jsx("path",{d:"M22 12h-4l-3 9L9 3l-3 9H2",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),agents:n.jsx(n.Fragment,{children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",stroke:"currentColor",strokeWidth:"1.5",fill:"none"})}),initiative:n.jsx("path",{d:"M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),queue:n.jsxs(n.Fragment,{children:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"M8 12h8M12 8v8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),error:n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),n.jsx("path",{d:"M12 9v4M12 17h.01",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})};function ki({icon:e="inbox",headline:t,description:s,primaryAction:r,secondaryAction:i,className:a}){return n.jsxs(pe.div,{className:ce("flex flex-col items-center justify-center py-12 px-6 text-center max-w-md mx-auto",a),initial:"hidden",animate:"visible",variants:{visible:{transition:{staggerChildren:.04}}},children:[n.jsx(pe.div,{className:"flex h-12 w-12 items-center justify-center rounded-xl border border-white/[0.08] bg-white/[0.04]",variants:Or,custom:0,children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",className:"text-secondary",children:lm[e]})}),n.jsx(pe.h4,{className:"mt-5 text-heading font-semibold text-white",variants:Or,custom:1,children:t}),n.jsx(pe.p,{className:"mt-2 text-body text-secondary leading-relaxed",variants:Or,custom:2,children:s}),(r||i)&&n.jsxs(pe.div,{className:"mt-5 flex items-center gap-2",variants:Or,custom:3,children:[r&&n.jsx("button",{type:"button",onClick:r.onClick,className:"control-pill px-4 text-[12px] font-medium",style:{borderColor:"rgba(191, 255, 0, 0.24)",background:"rgba(191, 255, 0, 0.09)",color:"#d8ffa1"},children:r.label}),i&&n.jsx("button",{type:"button",onClick:i.onClick,className:"control-pill px-4 text-[12px] font-medium",children:i.label})]})]})}const cm=new Set(["awaiting_input","needs_review","failed"]);function Io(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function dm(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 Rl(e){const t=e.filter(r=>cm.has(r.status)).sort((r,i)=>Io(i.updatedAt??i.lastEventAt??"")-Io(r.updatedAt??r.lastEventAt??"")),s=new Map;for(const r of t){const i=dm(r),a=s.get(i);if(!a){s.set(i,{item:r,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function um(e){return e==="failed"?"border-red-400/30 bg-red-500/[0.10] text-red-100":e==="needs_review"?"border-amber-300/30 bg-amber-300/[0.10] text-amber-100":"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]"}function mm(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function pm(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 fm(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 hm(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 pa(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return On(s)?`${t} ${us(s)}`:s}function gm(e){if(!e)return null;const t=Bt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function xm(e,t,s){const r=(t==null?void 0:t.trim())??"";if(r&&!On(r)){const a=Bt(r);if(a!=="Untitled session")return a}const i=gm(e.statusExplainer);return i||(s?pa(s,"Workstream"):pa(e.sliceRunId,"Slice"))}const ym=o.memo(function({sliceRuns:t,initiatives:s=[],title:r="Needs Input",className:i,showHeader:a=!0,panelStyle:l="card",onOpenDecisions:c,onFocusRunId:d,onReviewActivity:u,onOpenSliceDetail:g}){const x=o.useMemo(()=>Rl(t),[t]),b=o.useMemo(()=>{const y=new Map;for(const j of s)j.id&&y.set(j.id,j.name??j.id);return y},[s]),h=o.useMemo(()=>{const y=new Map;for(const j of s)for(const w of j.workstreams??[])w.id&&(y.has(w.id)||y.set(w.id,w.name??w.id));return y},[s]),v=y=>{var j;if(y.primaryAction==="resolve_decision"){c==null||c();return}if(y.primaryAction==="review_output"||y.primaryAction==="retry_slice"){u==null||u(y);return}if(y.primaryAction==="open_artifact"){const w=(j=y.artifacts.find(k=>k.url))==null?void 0:j.url;if(w&&typeof window<"u"){window.open(w,"_blank","noopener,noreferrer");return}u==null||u(y);return}if(y.runId){d==null||d(y.runId);return}y.sliceRunId&&(d==null||d(y.sliceRunId))};return n.jsxs(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":""} ${i??""}`,children:[a?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:r}),n.jsx("span",{className:"chip text-micro",children:x.length})]})}):null,x.length===0?n.jsx(ki,{icon:"inbox",headline:"No slices need attention",description:"All workstreams are running smoothly. Decisions will appear here when agents need your input."}):n.jsx("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto px-3 py-2",children:x.map(({item:y,duplicateCount:j},w)=>{var je;const k=(Array.isArray(y.initiativeIds)&&y.initiativeIds.length>0?y.initiativeIds[0]:y.initiativeId)??null,p=(Array.isArray(y.workstreamIds)&&y.workstreamIds.length>0?y.workstreamIds[0]:y.workstreamId)??null,_=(k?b.get(k):null)??pa(k,"Initiative"),U=y.workstreamTitle??(p?h.get(p)??null:null),ae=xm(y,U,p),G=(je=y.statusExplainer)!=null&&je.trim().length?y.statusExplainer:"Review this slice to continue execution.",ve=Bt(hm(y)),V=Bt(G),ee=Bt(_),de=y.scope?y.scope.replace(/_/g," "):null,we=y.updatedAt??y.lastEventAt??null;return n.jsxs(pe.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] ${y.status==="failed"?"border-red-400/20":y.blockingDecisionCount>0?"border-amber-400/20":"border-white/[0.08]"}`,role:"button",tabIndex:0,onClick:()=>g==null?void 0:g(y),onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&(ge.preventDefault(),g==null||g(y))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${pm(y.status)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex min-w-0 items-center gap-1 text-micro uppercase tracking-[0.08em] text-muted",children:[n.jsx(ln,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:ee})]}),n.jsxs("p",{className:"mt-0.5 inline-flex min-w-0 items-start gap-1.5 text-body font-semibold leading-snug text-white",title:ae,children:[n.jsx(ln,{type:"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:ae})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:ve,children:ve}),V!==ve&&n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:V,children:V})]}),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] ${um(y.status)}`,children:mm(y.status)}),de?n.jsx("span",{className:"chip text-micro capitalize",children:de}):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 y.blockingDecisionCount=="number"&&y.blockingDecisionCount>0&&n.jsxs("span",{className:"chip text-micro border-red-400/30 bg-red-500/[0.1] text-red-200/90",children:["Blocks ",y.blockingDecisionCount," task",y.blockingDecisionCount===1?"":"s"]}),typeof y.decisionCount=="number"&&y.decisionCount>0&&n.jsxs("span",{className:"chip text-micro",children:[y.decisionCount," decision",y.decisionCount===1?"":"s"]}),typeof y.artifactCount=="number"&&y.artifactCount>0&&n.jsxs("span",{className:"chip text-micro",children:[y.artifactCount," artifact",y.artifactCount===1?"":"s"]}),we&&n.jsxs("span",{children:["Updated ",Mt(we)]})]}),y.decisionOptions&&y.decisionOptions.length>0&&y.decisionOptions.length<=3&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",onClick:ge=>ge.stopPropagation(),children:y.decisionOptions.slice(0,3).map(ge=>n.jsx("button",{type:"button",onClick:()=>g==null?void 0:g(y),className:"chip text-micro font-medium hover:bg-white/[0.08] transition-colors cursor-pointer",title:ge.description??ge.label,children:ge.label},ge.id))}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:ge=>ge.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>g==null?void 0:g(y),className:"control-pill h-7 px-2.5 text-micro font-semibold",children:"Details"}),n.jsx("button",{type:"button",onClick:()=>v(y),className:"control-pill h-7 px-2.5 text-micro font-semibold","data-tone":y.status==="failed"?"teal":void 0,children:fm(y)})]})]},y.sliceRunId)})})]})});function bm(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function wm(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 vm(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function km(e){return{id:e.id,name:e.title,status:bm(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:wm(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 Ao=150,jm=12;function So(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function Nm(){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 Ll(e,t=null){return hs({queryKey:Zn.entities({type:"initiative",projectId:t}),queryFn:async()=>{var c;if(Ft())return Nm();const s=[],r=(t==null?void 0:t.trim())??"";let i=0;for(let d=0;d<jm;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(Ao),offset:String(i)});r&&gs(u,r);const g=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:_t({workspaceId:r})});if(!g.ok)break;const x=await g.json(),b=x.data??[];if(s.push(...b),!!!((c=x.pagination)!=null&&c.has_more)||b.length===0)break;i+=Ao}const a=r.length>0&&s.some(d=>(d.command_center_id??d.commandCenterId??"").trim().length>0),l=new Map;for(const d of s){const u=l.get(d.id);if(!u){l.set(d.id,d);continue}So(d.updated_at??d.created_at)>So(u.updated_at??u.created_at)&&l.set(d.id,d)}return Array.from(l.values()).filter(d=>!r||!a?!0:(d.command_center_id??d.commandCenterId??"").trim()===r).filter(d=>vm(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(km)},enabled:e,staleTime:6e4})}const qr=50,_o=8;function Im(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Am(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Sm(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function _m(e){const t=Sm(e.sequence);return{id:e.id,name:e.title,status:Im(e.status),rawStatus:e.status??null,priority:e.priority??null,category:void 0,health:Math.max(0,Math.min(100,Math.round(e.progress??0))),daysRemaining:0,targetDate:e.targetDate??e.dueDate??e.etaEndAt??null,createdAt:e.createdAt??null,updatedAt:e.updatedAt??null,sequenceIndex:t,hierarchyLabel:typeof t=="number"?`I${t+1}`:void 0,activeAgents:e.activeAgents??0,totalAgents:e.totalAgents??0,description:void 0}}function Cm(e,t=null){return hs({queryKey:Zn.liveInitiatives({limit:qr*_o,projectId:t}),queryFn:async()=>{var l;if(Ft())return[];const s=[];let r=0;for(let c=0;c<_o;c+=1){const d=new URLSearchParams({limit:String(qr),offset:String(r)});t&&t.trim().length>0&&gs(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(),x=g.initiatives??[];s.push(...x);const b=typeof g.total=="number"?g.total:null,h=(l=g.pagination)==null?void 0:l.has_more;if(!(typeof h=="boolean"?h:b!==null?r+x.length<b:x.length===qr)||x.length===0)break;r+=qr}const i=(t==null?void 0:t.trim())??"",a=i.length>0&&s.some(c=>(c.command_center_id??c.commandCenterId??"").trim().length>0);return s.filter(c=>!i||!a?!0:(c.command_center_id??c.commandCenterId??"").trim()===i).filter(c=>Am(c.status)).map(_m)},enabled:e,staleTime:3e4})}const Dl=o.createContext(null);function Mm({children:e}){const[t,s]=o.useState({artifactId:null}),r=o.useCallback((a,l)=>{s({artifactId:a,context:l})},[]),i=o.useCallback(()=>{s({artifactId:null})},[]);return n.jsx(Dl.Provider,{value:{state:t,open:r,close:i},children:e})}function $l(){const e=o.useContext(Dl);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:l,onNewInitiative:c}=e,d=r+s;return t===0&&d===0&&i===0?{key:"idle-empty",segments:[{text:"All caught up. "},c?{text:"Start something new?",color:D.lime,clickable:!0,onClick:c}:{text:"Nothing running."}]}:t===0&&d===0?{key:"idle-done",segments:[{text:`${i} done today`,color:D.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:D.red,clickable:!0,onClick:l},{text:" · "},{text:`${r} need your input`,color:D.amber,clickable:!0,onClick:a}]}:s>0?{key:`blocked-${s}-${t}`,segments:[{text:`${s} blocked`,color:D.red,clickable:!0,onClick:l},...t>0?[{text:` · ${t} running`}]:[]]}:r>0?{key:`decisions-${r}-${t}`,segments:[...t>0?[{text:`${t} running`,color:D.lime},{text:" · "}]:[],{text:`${r} need your input`,color:D.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:D.lime},{text:" · all systems go"}]}}function Co(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(yt,{mode:"wait",children:n.jsx(pe.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 ng={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"},Em={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"},sg=e=>Em[qt(e)]??"text-white/60 bg-white/5 border-white/10",rg=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"},ig=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"},ag=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),og=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},js=e=>{const t=qt(e);return t==="blocked"||t==="failed"||t==="cancelled"?D.red:t==="active"||t==="in_progress"||t==="running"?D.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?D.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?D.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},ui={codex:{id:"codex",label:"Codex",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},openai:{id:"openai",label:"OpenAI",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},anthropic:{id:"anthropic",label:"Anthropic",accent:"#F5B700",tint:"rgba(245, 183, 0, 0.18)"},openclaw:{id:"openclaw",label:"OpenClaw",accent:"#FF4D4D",tint:"rgba(255, 77, 77, 0.18)"},orgx:{id:"orgx",label:"OrgX",accent:D.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:D.teal,tint:"rgba(20, 184, 166, 0.18)"}},Rm=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function ri(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)ri(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 l=i.toLowerCase();typeof a=="string"?(Rm.some(c=>l.includes(c))||l.startsWith("meta")||l.endsWith("id"))&&ri(a,t,s+1,r):typeof a=="object"&&a!==null&&ri(a,t,s+1,r)}}}}function Lm(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 ms(...e){const t=[],s=new Set;for(const r of e)ri(r,t,0,s);for(const r of t){const i=Lm(r);if(i)return ui[i]}return ui.unknown}function Dm(e){return ui[e]??ui.unknown}const $m={xs:18,sm:24,md:30};function Fm({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:wi,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 Vs({provider:e,size:t="sm",className:s,showRing:r=!0}){const i=Dm(e),a=$m[t];return n.jsx("span",{className:ce("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(Fm,{provider:e})})})}function Fl({running:e,blocked:t,paused:s,size:r=36,children:i}){const a=es(),l=e+t+s,c=o.useMemo(()=>{if(l===0)return[];const h=[];return e>0&&h.push({color:D.lime,fraction:e/l}),t>0&&h.push({color:D.red,fraction:t/l}),s>0&&h.push({color:D.amber,fraction:s/l}),h},[e,t,s,l]),d=2.5,u=(r-d)/2,g=2*Math.PI*u,x=r/2;if(l===0)return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:r,height:r},children:[n.jsx("svg",{width:r,height:r,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:n.jsx("circle",{cx:x,cy:x,r:u,fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:d})}),n.jsx("div",{className:"relative z-10",children:i})]});let b=0;return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:r,height:r},children:[n.jsxs("svg",{width:r,height:r,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:[n.jsx("circle",{cx:x,cy:x,r:u,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),c.map((h,v)=>{const y=h.fraction*g,j=-b;return b+=y,n.jsx(pe.circle,{cx:x,cy:x,r:u,fill:"none",stroke:h.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${y} ${g-y}`,strokeDashoffset:j,initial:a?!1:{strokeDasharray:`0 ${g}`},animate:{strokeDasharray:`${y} ${g-y}`},transition:{duration:.5,delay:v*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},v)})]}),n.jsx("div",{className:"relative z-10",children:i})]})}const zr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function Sa(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function _a(e,t){if(typeof t=="number")return`${e}${t+1}`}const Pm=(e,t)=>{const s=Sa(e.sequence??e.order);return{id:e.id,name:e.name??"Untitled workstream",summary:e.summary??null,status:e.status??"planned",progress:typeof e.progress=="number"&&!Number.isNaN(e.progress)?Math.max(0,Math.min(100,e.progress<=1?e.progress*100:e.progress)):null,initiativeId:e.initiative_id??t,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:_a("W",s)}},Om=(e,t)=>{const s=Sa(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled milestone",description:e.description??null,status:e.status??"planned",dueDate:e.due_date??null,initiativeId:e.initiative_id??t,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:_a("M",s)}},Bm=(e,t)=>{const s=Sa(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled task",description:e.description??null,status:e.status??"todo",priority:e.priority??null,dueDate:e.due_date??null,initiativeId:e.initiative_id??t,milestoneId:e.milestone_id??null,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:_a("T",s)}};function zi(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,l=s.createdAt?Date.parse(s.createdAt):0;return a!==l?a-l:0})}function qm(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 zm({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:r=!0}){var c;const i=ud(e),a=o.useMemo(()=>Zn.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),l=hs({queryKey:a,enabled:r&&!!e&&i,queryFn:async()=>{if(!e)return zr;if(Ft())return qm(e);if(!i)return{...zr,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 k=new URLSearchParams({type:w,initiative_id:e,limit:"100"}),p=await fetch(`/orgx/api/entities?${k.toString()}`,{headers:u});return p.ok?await p.json():{data:[]}}catch{return{data:[]}}},[x,b,h]=await Promise.all([g("workstream"),g("milestone"),g("task")]),v=Array.isArray(x.data)?zi(x.data.map(w=>Pm(w,e))):[],y=Array.isArray(b.data)?zi(b.data.map(w=>Om(w,e))):[],j=Array.isArray(h.data)?zi(h.data.map(w=>Bm(w,e))):[];return{initiativeId:e,workstreams:v,milestones:y,tasks:j}}});return{details:(i?l.data:null)??(e?{...zr,initiativeId:e}:zr),isLoading:i?l.isLoading:!1,error:i?((c=l.error)==null?void 0:c.message)??null:null,refetch:l.refetch}}function Wm(){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 Ca({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return hs({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Ft())return Wm();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 hr(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:D.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:D.iris,bg:"rgba(124,124,255,0.10)"}}function Um(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function Hm(e,t){return[...t?e.tasks.filter(r=>r.workstreamId===t):e.tasks].sort((r,i)=>r.title.localeCompare(i.title))}function Vm({open:e,onClose:t,onLaunched:s}){var le,xe,Se,Y,Te,fe;const r=Ca({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:i}=Ll(e),[a,l]=o.useState(""),[c,d]=o.useState(""),[u,g]=o.useState(""),[x,b]=o.useState(""),[h,v]=o.useState("auto"),[y,j]=o.useState(""),[w,k]=o.useState(null),[p,_]=o.useState(null),[U,ae]=o.useState("starter"),[G,ve]=o.useState(!1),[V,ee]=o.useState(1),de=Ft(),we=o.useMemo(()=>{const C=c.trim();return C?(i==null?void 0:i.find(O=>O.id===C))??null:null},[i,c]),{details:je}=zm({initiativeId:we?we.id:null,enabled:e&&!!we}),ge=o.useMemo(()=>Um(je),[je]),He=o.useMemo(()=>Hm(je,u||null),[je,u]),ue=((le=r.data)==null?void 0:le.agents)??[],ne=o.useMemo(()=>{const C=a.trim();return C?ue.find(O=>O.id===C)??null:null},[ue,a]);o.useEffect(()=>{var O,W;if(!e)return;const C=((O=ue.find(Z=>Z.isDefault))==null?void 0:O.id)??((W=ue[0])==null?void 0:W.id)??"";!a&&C&&l(C)},[ue,e,a]),o.useEffect(()=>{if(!e||c.trim())return;const C=i??[],O=C.length===1?C[0]:null;O&&d(O.id)},[i,e,c]),o.useEffect(()=>{if(!e)return;const C=(ne==null?void 0:ne.model)??"",O=C.includes("openrouter")?"openrouter":C.includes("anthropic")?"anthropic":C.includes("openai")?"openai":"auto";v(O)},[e,ne==null?void 0:ne.model,a]),o.useEffect(()=>{e&&(k(null),_(null),ae("starter"),ee(1))},[e]),o.useEffect(()=>{g(""),b("")},[c]),o.useEffect(()=>{b("")},[u]),o.useEffect(()=>{e&&(y.trim().length>0||we&&j(`Kick off: ${we.name}`))},[y,e,we]);const X=!!a.trim()&&!!c.trim(),te=V===1?!!a.trim():V===2?!!c.trim():X,Ne=async()=>{var Oe;const C=(p==null?void 0:p.checkout)??"/orgx/api/billing/checkout",O=U&&U.trim().length>0?U.trim():"starter",Z=await(await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:O,billingCycle:"monthly"})})).json().catch(()=>null),Fe=((Oe=Z==null?void 0:Z.data)==null?void 0:Oe.url)??(Z==null?void 0:Z.url)??null;if(!Fe)throw new Error((Z==null?void 0:Z.error)??"Checkout unavailable");window.open(Fe,"_blank","noopener,noreferrer")},se=async()=>{var Fe;const C=(p==null?void 0:p.portal)??"/orgx/api/billing/portal",W=await(await fetch(C,{method:"POST"})).json().catch(()=>null),Z=((Fe=W==null?void 0:W.data)==null?void 0:Fe.url)??(W==null?void 0:W.url)??null;if(!Z)throw new Error((W==null?void 0:W.error)??"Billing portal unavailable");window.open(Z,"_blank","noopener,noreferrer")},$=async()=>{if(!(!X||G)){if(de){t(),s==null||s();return}k(null),_(null),ve(!0);try{const C={agentId:a.trim(),message:y.trim()?y.trim():void 0,initiativeId:c.trim(),initiativeTitle:(we==null?void 0:we.name)??null,workstreamId:u.trim()?u.trim():null,taskId:x.trim()?x.trim():null,provider:h!=="auto"?h: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"}),Z=await W.json().catch(()=>null);if(!W.ok||!(Z!=null&&Z.ok))throw(Z==null?void 0:Z.code)==="upgrade_required"&&(_(Z.actions??null),ae(Z.requiredPlan??"starter")),new Error((Z==null?void 0:Z.error)??`Launch failed (${W.status})`);t(),s==null||s()}catch(C){k(C instanceof Error?C.message:"Launch failed")}finally{ve(!1)}}},H=!!((xe=ne==null?void 0:ne.run)!=null&&xe.runId)&&!!((Se=ne==null?void 0:ne.run)!=null&&Se.pid),z=async()=>{var C;if(!(!((C=ne==null?void 0:ne.run)!=null&&C.runId)||!H||G)&&!de){k(null),ve(!0);try{const O=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(ne.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){k(O instanceof Error?O.message:"Stop failed")}finally{ve(!1)}}},K=async()=>{var C;if(!(!((C=ne==null?void 0:ne.run)!=null&&C.runId)||G)){if(de){t(),s==null||s();return}k(null),ve(!0);try{const O=new URLSearchParams;O.set("runId",ne.run.runId),y.trim()&&O.set("message",y.trim()),h&&h!=="auto"&&O.set("provider",h);const W=await fetch(`/orgx/api/agents/restart?${O.toString()}`,{method:"POST"}),Z=await W.json().catch(()=>null);if(!W.ok||!(Z!=null&&Z.ok))throw new Error((Z==null?void 0:Z.error)??`Restart failed (${W.status})`);t(),s==null||s()}catch(O){k(O instanceof Error?O.message:"Restart failed")}finally{ve(!1)}}};return e?n.jsx(vi,{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:()=>ee(C),className:ce("rounded-full px-3 py-1 transition-colors",V===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(yt,{mode:"wait",children:n.jsxs(pe.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:[V===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=>l(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:ue.map(C=>{const O=hr(C.status);return n.jsxs("option",{value:C.id,children:[C.name," (",C.id,") · ",O.label]},C.id)})})]}),ne&&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:ne.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${hr(ne.status).color}55`,color:hr(ne.status).color,backgroundColor:hr(ne.status).bg},children:hr(ne.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:"})," ",ne.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",ne.workspace??"unknown"]}),((Y=ne.context)==null?void 0:Y.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",ne.context.initiativeTitle??ne.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value:h,onChange:C=>v(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."})]}),ne.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",ne.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",ne.run.status,")"]})]}),ne.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:z,disabled:!H||G,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:K,disabled:G,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"})]})]})]})]}),V===2&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Initiative Scope"}),n.jsxs("select",{value:c,onChange: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:!we,className:ce("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!we&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),ge.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:x,onChange:C=>b(C.target.value),disabled:!we,className:ce("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!we&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),He.slice(0,80).map(C=>n.jsx("option",{value:C.id,children:C.title},C.id))]}),He.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),V===3&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Kickoff Message"}),n.jsx("textarea",{value:y,onChange: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:((ne==null?void 0:ne.name)??a.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Initiative"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((we==null?void 0:we.name)??c.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:u.trim()?((Te=ge.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:x.trim()?((fe=He.find(C=>C.id===x))==null?void 0:fe.title)??x:"Any"})]})]})]})]})]},V)}),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}),p&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void Ne().catch(C=>k(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 se().catch(C=>k(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"}),p.pricing&&n.jsx("a",{href:p.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:V===1?"Pick an agent to configure.":V===2?"Select an initiative scope (required).":X?"Launch will update sessions/activity under the selected initiative.":"Select an agent and initiative to launch."}),n.jsxs("div",{className:"flex items-center gap-2",children:[V>1&&n.jsx("button",{type:"button",onClick:()=>ee(C=>C>1?C-1:C),disabled:G,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"}),V<3?n.jsx("button",{type:"button",onClick:()=>ee(C=>C<3?C+1:C),disabled:!te||G,className:ce("rounded-xl px-4 py-2 text-body font-semibold transition-colors",te&&!G?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:te&&!G?{backgroundColor:D.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:$,disabled:!X||G,className:ce("rounded-xl px-4 py-2 text-body font-semibold transition-colors",X&&!G?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:X&&!G?{backgroundColor:D.lime}:void 0,children:G?"Launching…":"Launch"})]})]})]})}):null}function Km({breadcrumbs:e,typeBadge:t,onClose:s,footer:r,children:i}){return n.jsxs("div",{className:"flex h-full w-full min-h-0 flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 text-body text-secondary",children:[e.map((a,l)=>n.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[l>0&&n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"flex-shrink-0 text-faint",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),a.onClick?n.jsx("button",{type:"button",onClick:a.onClick,className:`truncate transition-colors hover:text-primary ${l===e.length-1?"text-primary font-medium":""}`,children:a.label}):n.jsx("span",{className:`truncate ${l===e.length-1?"text-primary font-medium":""}`,children:a.label})]},l)),t&&n.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 rounded-full border border-white/[0.1] bg-white/[0.04] px-2 py-0.5 text-micro uppercase tracking-[0.06em] text-secondary",children:[t.icon&&n.jsx(ln,{type:t.icon,size:11,className:"opacity-90"}),t.label]})]}),n.jsx("button",{type:"button",onClick:s,"aria-label":"Close detail",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full border border-strong bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08] hover:text-white",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:i}),r&&n.jsx("div",{className:"flex-shrink-0 border-t border-subtle px-5 py-3 sm:px-6",children:r})]})}const Wi=10,Gm=20;function Xm(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:D.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:D.iris,bg:"rgba(124,124,255,0.10)"}}function Qm(e){return e?e.includes("error")||e.includes("fail")?D.red:e.includes("decision")||e.includes("block")?D.amber:e.includes("complete")||e.includes("success")?D.teal:e.includes("start")||e.includes("launch")?D.lime:D.iris:D.iris}const Jm={hidden:{opacity:0,y:-4},visible:e=>({opacity:1,y:0,transition:{duration:.28,delay:e*.04,ease:[.16,1,.3,1]}})},Wr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{duration:.22,delay:e*.04,ease:[.22,1,.36,1]}})};function Ym(){return n.jsx("div",{className:"h-px bg-gradient-to-r from-transparent via-white/[0.06] to-transparent"})}function Zm({open:e,onClose:t,agentName:s,catalogAgent:r,sessions:i,activity:a,onSelectSession:l,onRefresh:c}){var ee,de,we,je,ge,He;const[d,u]=o.useState(!1),[g,x]=o.useState(!1),[b,h]=o.useState(null),v=Nl(s),y=Xm((r==null?void 0:r.status)??null),j=jl(s),w=o.useMemo(()=>{let ue=0,ne=0,X=0,te=0;for(const Ne of i)Ne.status==="running"||Ne.status==="queued"||Ne.status==="pending"?ue++:Ne.status==="blocked"?ne++:Ne.status==="failed"||Ne.status==="cancelled"?X++:(Ne.status==="completed"||Ne.status==="archived")&&te++;return{running:ue,blocked:ne,failed:X,completed:te}},[i]),k=o.useMemo(()=>[...i].sort((ue,ne)=>Date.parse(ne.updatedAt??ne.lastEventAt??ne.startedAt??"")-Date.parse(ue.updatedAt??ue.lastEventAt??ue.startedAt??"")),[i]),p=d?k:k.slice(0,Wi),_=k.length>Wi,U=o.useMemo(()=>[...a].sort((ue,ne)=>Date.parse(ne.timestamp)-Date.parse(ue.timestamp)).slice(0,Gm),[a]),ae=!!((ee=r==null?void 0:r.run)!=null&&ee.runId)&&!!((de=r==null?void 0:r.run)!=null&&de.pid),G=async()=>{var ue;if(!(!((ue=r==null?void 0:r.run)!=null&&ue.runId)||!ae||g)){h(null),x(!0);try{const ne=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(r.run.runId)}`,{method:"POST"}),X=await ne.json().catch(()=>null);if(!ne.ok||!(X!=null&&X.ok))throw new Error((X==null?void 0:X.error)??`Stop failed (${ne.status})`);c==null||c()}catch(ne){h(ne instanceof Error?ne.message:"Stop failed")}finally{x(!1)}}},ve=async()=>{var ue;if(!(!((ue=r==null?void 0:r.run)!=null&&ue.runId)||g)){h(null),x(!0);try{const ne=new URLSearchParams;ne.set("runId",r.run.runId);const X=await fetch(`/orgx/api/agents/restart?${ne.toString()}`,{method:"POST"}),te=await X.json().catch(()=>null);if(!X.ok||!(te!=null&&te.ok))throw new Error((te==null?void 0:te.error)??`Restart failed (${X.status})`);c==null||c()}catch(ne){h(ne instanceof Error?ne.message:"Restart failed")}finally{x(!1)}}};if(!e)return null;const V=r!=null&&r.run?n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("p",{className:"text-caption text-secondary",children:["Run ",r.run.runId.slice(0,8),"…",n.jsxs("span",{className:"text-muted ml-1",children:["(",r.run.status,")"]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:G,disabled:!ae||g,className:"rounded-md px-2.5 py-1.5 text-caption font-medium text-red-400/70 hover:bg-red-500/[0.08] hover:text-red-300 disabled:opacity-40 transition-colors",children:g?"Stopping…":"Stop"}),n.jsx("button",{type:"button",onClick:ve,disabled:g,className:"h-8 rounded-lg border border-lime/25 bg-lime/10 px-4 text-caption font-semibold text-lime transition-colors hover:bg-lime/20 disabled:opacity-40",children:g?"Restarting…":"Restart"})]})]}):void 0;return n.jsxs(vi,{open:e,onClose:t,maxWidth:"max-w-3xl",children:[n.jsx("div",{className:"h-[2px] rounded-t-xl",style:{background:`linear-gradient(90deg, ${j}, transparent)`}}),n.jsx(Km,{breadcrumbs:[{label:"Agents"},{label:s}],onClose:t,footer:V,children:n.jsxs("div",{className:"px-8 py-6 space-y-8",children:[n.jsxs(pe.div,{className:"flex items-start gap-5",variants:Jm,initial:"hidden",animate:"visible",custom:0,children:[n.jsx(Fl,{running:w.running,blocked:w.blocked+w.failed,paused:0,size:72,children:n.jsx(Ot,{name:s,size:"lg",hint:s})}),n.jsxs("div",{className:"min-w-0 flex-1 pt-1",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("h3",{className:"text-[28px] font-medium leading-none text-white truncate",children:s}),n.jsx("span",{className:"status-pill",style:{color:y.color,backgroundColor:y.bg,borderColor:`${y.color}30`},children:y.label})]}),v&&n.jsx("p",{className:"text-micro uppercase tracking-[0.12em] text-muted mt-2",children:v})]})]}),n.jsx(pe.div,{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",variants:Wr,initial:"hidden",animate:"visible",custom:1,children:[{label:"Running",value:w.running,color:D.lime},{label:"Blocked",value:w.blocked,color:D.red},{label:"Failed",value:w.failed,color:D.amber},{label:"Completed",value:w.completed,color:D.teal}].map(ue=>n.jsxs("div",{children:[n.jsx("p",{className:"section-kicker",children:ue.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:ue.value>0?ue.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:ue.value})]},ue.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs(pe.div,{variants:Wr,initial:"hidden",animate:"visible",custom:2,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Sessions"}),i.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No sessions recorded."}):n.jsxs("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-6",children:[p.map(ue=>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:js(ue.status)}}),n.jsxs("button",{onClick:()=>{l(ue.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:ue.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:Mt(ue.updatedAt??ue.lastEventAt??ue.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:ue.status}),ue.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(ue.progress),"%"]})]})]})]})]},ue.id)),_&&n.jsx("button",{type:"button",onClick:()=>u(ue=>!ue),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${k.length-Wi} older sessions`})]})]}),n.jsxs(pe.div,{variants:Wr,initial:"hidden",animate:"visible",custom:3,children:[n.jsx("p",{className:"section-kicker mb-6",children:"Live Activity"}),U.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:U.map((ue,ne)=>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:Qm(ue.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:ue.title??ue.summary??ue.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:Mt(ue.timestamp)})]})]},ue.id??ne))})]})]}),n.jsx(Ym,{}),r&&n.jsxs(pe.div,{variants:Wr,initial:"hidden",animate:"visible",custom:4,children:[n.jsx("p",{className:"section-kicker mb-4",children:"Configuration"}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-y-4 gap-x-8",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Provider"}),n.jsx("p",{className:"text-[14px] text-primary",children:(we=r.model)!=null&&we.includes("openrouter")?"OpenRouter":(je=r.model)!=null&&je.includes("anthropic")?"Anthropic":(ge=r.model)!=null&&ge.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Model"}),n.jsx("p",{className:ce("text-[14px] truncate",r.model?"text-primary":"text-muted"),children:r.model??"Not configured"})]}),r.workspace&&n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Workspace"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:r.workspace})]}),((He=r.context)==null?void 0:He.initiativeTitle)&&n.jsxs("div",{children:[n.jsx("p",{className:"text-micro text-muted mb-1",children:"Initiative"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:r.context.initiativeTitle})]})]})]}),b&&n.jsx("p",{className:"rounded-md border border-red-400/30 bg-red-500/10 px-3 py-2 text-caption text-red-200",children:b})]})})]})}const Ur=120,Mo=10,ep=24,To=520,tp=58,np=56,sp=20,rp=8,Ma=new Set(["running","active","in_progress","working","planning","handoff","review"]),ip=new Set(["blocked","failed"]),ap=10,op=[{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"}],lp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,fa=[{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 un(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 fa)if(a.aliases.some(l=>l.test(i)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function cp(e){const t=un(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=un(null,r);if(i)return i}return null}function dp(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 Pl(e){const t=cp(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=dp(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 up(e){const t=Pl(e),s=rt(t.agentId);if(s)return`id:${s}`;const r=rt(t.agentName);return r?`name:${r}`:"unassigned"}function mp(e){const t=e.trim();return t?lp.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function mi(e){const t=(e??"").trim();return t?Cs(t):!1}function pp(e){var t,s;return!!(mi((t=e.context)==null?void 0:t.initiativeId)||mi(((s=e.run)==null?void 0:s.initiativeId)??null))}function Ui(e){if(un(e.agentId,e.agentName))return!0;const s=rt(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function an(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":Ma.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function ha(e){const t=rt(e);return t?Ma.has(t)||ip.has(t):!1}function Eo(e){const t=rt(e);return t?Ma.has(t):!1}function Hr(e){return e?!!(ha(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function fp(e){return e?e.state==="active":!1}function hp(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function In(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Hi(e,t){return In(t.updatedAt??t.lastEventAt??t.startedAt)-In(e.updatedAt??e.lastEventAt??e.startedAt)}function gp({status:e,nodes:t,onSelectSession:s,selectedSessionId:r}){const[i,a]=o.useState(!1),l=js(e),c=e==="blocked"?"blocked":e==="failed"?"failed":"paused";return n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>a(d=>!d),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-white/[0.05]",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:l}}),n.jsxs("span",{className:"flex-1 text-body text-secondary",children:[t.length," ",c," sessions"]}),n.jsx(pe.span,{animate:{rotate:i?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(yt,{children:i&&n.jsx(pe.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,x=ms(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(pe.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:ce("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(Vs,{provider:x.id,size:"xs"}),n.jsx("p",{className:"min-w-0 flex-1 truncate text-body text-bright",title:d.title,children:d.title}),n.jsx("span",{className:"text-micro text-muted",children:Mt(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const xp=o.memo(function({sessions:t,activity:s,selectedSessionId:r,onSelectSession:i,timeFilterId:a,onAgentFilter:l,agentFilter:c,onReconnect:d,onLaunched:u,connectionStatus:g,runtimeInstances:x=[],showSyntheticEntities:b=!1}){var T;const[h,v]=o.useState(new Set),[y,j]=o.useState(!1),[w,k]=o.useState(!1),[p,_]=o.useState(0),[U,ae]=o.useState(null),G=Ca({enabled:!0}),ve=((T=G.data)==null?void 0:T.agents)??[],V=o.useMemo(()=>Cr(a),[a]),ee=o.useMemo(()=>V===null?s:s.filter(F=>In(F.timestamp)>=V),[s,V]);o.useMemo(()=>{var he,Ie,Xe;const F=new Map,ie=[...ee].sort((Qe,Ee)=>In(Ee.timestamp)-In(Qe.timestamp));for(const Qe of ie){const Ee=Qe.runId;if(!Ee||F.has(Ee))continue;const et=((he=Qe.summary)==null?void 0:he.trim())??((Ie=Qe.description)==null?void 0:Ie.trim())??((Xe=Qe.title)==null?void 0:Xe.trim())??"";et.length>0&&F.set(Ee,et)}return F},[ee]);const{agents:de,hiddenGroupCount:we,filteredOutGroupsByDate:je,filteredOutSessionsByDate:ge,visibleSessionCount:He,archivedGroups:ue,sessionCountInScope:ne}=o.useMemo(()=>{var Re;const F=b?t.nodes:t.nodes.filter(B=>!mi(B.initiativeId)),ie=b?ve:ve.filter(B=>!pp(B)),he=b?x:x.filter(B=>!mi(B.initiativeId)),Ie=new Map,Xe=new Map,Qe=[...he].sort((B,Q)=>In(Q.lastEventAt??Q.lastHeartbeatAt)-In(B.lastEventAt??B.lastHeartbeatAt));for(const B of Qe){B.runId&&!Ie.has(B.runId)&&Ie.set(B.runId,B);const Q=un(B.agentId,B.agentName??B.displayName),_e=rt((Q==null?void 0:Q.agentId)??B.agentId);if(_e){const Le=Xe.get(_e)??[];Le.push(B),Xe.set(_e,Le)}}const Ee=new Map;for(const B of F){const Q=Pl(B),_e=up(B),Le=rt(Q.agentId),De=rt(Q.agentName);let Pe=Ee.get(_e)??null;if(!Pe&&Le&&De){const Ce=`name:${De}`,Ke=Ee.get(Ce);Ke&&(Ee.delete(Ce),Ke.groupKey=_e,Ee.set(_e,Ke),Pe=Ke)}if(!Pe&&De){const Ce=Array.from(Ee.values()).find(Ke=>rt(Ke.agentName)===De);Ce&&(Pe=Ce)}Pe?(Pe.nodes.push(B),!Pe.agentId&&Q.agentId&&(Pe.agentId=Q.agentId),(Pe.agentName==="OrgX"||!Pe.agentName)&&Q.agentName&&(Pe.agentName=Q.agentName)):Ee.set(_e,{groupKey:_e,agentId:Q.agentId,agentName:Q.agentName??Q.agentId??"OrgX",nodes:[B],latest:B,runtime:null,runtimeActiveCount:0})}for(const B of ie){const Q=un(B.id,B.name),_e=(Q==null?void 0:Q.agentId)??B.id,Le=(Q==null?void 0:Q.agentName)??B.name,De=rt(_e),Pe=rt(Le),Ce=De?`id:${De}`:null,Ke=Pe?`name:${Pe}`:null;let ot=null;if(Ce&&Ee.has(Ce))ot=Ce;else if(Ke&&Ee.has(Ke))ot=Ke;else{const Ge=Array.from(Ee.entries()).find(([,Nt])=>De&&rt(Nt.agentId)===De||Pe&&rt(Nt.agentName)===Pe);ot=(Ge==null?void 0:Ge[0])??null}if(ot){const Ge=Ee.get(ot);Ge.catalogAgent=B,!Ge.agentId&&_e&&(Ge.agentId=_e),(Ge.agentName==="OrgX"||!Ge.agentName)&&Le&&(Ge.agentName=Le),Ce&&Ge.groupKey!==Ce&&!Ee.has(Ce)&&(Ee.delete(Ge.groupKey),Ge.groupKey=Ce,Ee.set(Ce,Ge))}else{const Ge=Ce??Ke??`catalog:${Le.toLowerCase()}`;Ee.set(Ge,{groupKey:Ge,agentId:_e,agentName:Le,nodes:[],latest:null,catalogAgent:B,runtime:null,runtimeActiveCount:0})}}for(const B of fa){const Q=`orgx:${B.id}`,_e=`id:${Q}`;let Le=Ee.get(_e)??null;if(!Le){const De=Array.from(Ee.entries()).find(([,Pe])=>{const Ce=un(Pe.agentId,Pe.agentName);return rt(Ce==null?void 0:Ce.agentId)===rt(Q)});De&&(Ee.delete(De[0]),Le=De[1],Le.groupKey=_e,Ee.set(_e,Le))}if(Le||(Le={groupKey:_e,agentId:Q,agentName:B.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},Ee.set(_e,Le)),Le.agentId=Q,Le.agentName=B.name,!Le.catalogAgent){const De=ie.find(Pe=>{const Ce=un(Pe.id,Pe.name);return rt(Ce==null?void 0:Ce.agentId)===rt(Q)});De&&(Le.catalogAgent=De)}}const et=new Map(fa.map((B,Q)=>[rt(`orgx:${B.id}`),Q]));for(const B of Ee.values()){B.nodes.length>0&&(B.nodes.sort(Hi),B.latest=B.nodes[0]);const Q=[],_e=new Set;if((Re=B.latest)!=null&&Re.runId){const De=Ie.get(B.latest.runId);De&&!_e.has(De.id)&&(Q.push(De),_e.add(De.id))}for(const De of B.nodes){if(!De.runId)continue;const Pe=Ie.get(De.runId);Pe&&!_e.has(Pe.id)&&(Q.push(Pe),_e.add(Pe.id))}const Le=rt(B.agentId);if(Le)for(const De of Xe.get(Le)??[])_e.has(De.id)||(Q.push(De),_e.add(De.id));Q.sort((De,Pe)=>In(Pe.lastEventAt??Pe.lastHeartbeatAt)-In(De.lastEventAt??De.lastHeartbeatAt)),B.runtime=Q[0]??null,B.runtimeActiveCount=Q.filter(De=>fp(De)).length}const qe=Array.from(Ee.values()).sort((B,Q)=>{const _e=Ui(B),Le=Ui(Q);if(_e!==Le)return _e?-1:1;if(_e&&Le){const De=un(B.agentId,B.agentName),Pe=un(Q.agentId,Q.agentName),Ce=et.get(rt((De==null?void 0:De.agentId)??B.agentId))??999,Ke=et.get(rt((Pe==null?void 0:Pe.agentId)??Q.agentId))??999;if(Ce!==Ke)return Ce-Ke}return B.latest&&Q.latest?Hi(B.latest,Q.latest):B.latest&&!Q.latest?-1:!B.latest&&Q.latest?1:B.agentName.localeCompare(Q.agentName)}),pt=xl(a),at=pt.id==="live",Ze=pt.minutes===null||at?null:Date.now()-pt.minutes*6e4,ye=[],We=[];let Ae=0,q=0;for(const B of qe){const Q=(B.runtimeActiveCount??0)>0,_e=Ui(B);if(B.nodes.length===0){const Ce=Hr(B.catalogAgent);(_e||at&&(Ce||Q))&&ye.push(B);continue}if(at){const Ce=B.nodes.filter(Ge=>ha(an(Ge))),Ke=B.nodes.filter(Ge=>!ha(an(Ge))),ot=Hr(B.catalogAgent);if(Ce.length===0){_e||ot||Q?ye.push({...B,nodes:[],latest:null}):(Ae+=1,q+=B.nodes.length,We.push(B));continue}q+=Ke.length,Ke.length>0&&We.push({...B,nodes:Ke,latest:Ke[0]??null}),ye.push({...B,nodes:Ce,latest:Ce[0]??null});continue}if(Ze===null){ye.push(B);continue}const Le=B.nodes.filter(Ce=>Eo(an(Ce))?!0:In(Ce.updatedAt??Ce.lastEventAt??Ce.startedAt)>=Ze),De=Hr(B.catalogAgent);if(Le.length===0){_e||De||Q?ye.push({...B,nodes:[],latest:null}):(Ae+=1,q+=B.nodes.length,We.push(B));continue}const Pe=B.nodes.filter(Ce=>Eo(an(Ce))?!1:In(Ce.updatedAt??Ce.lastEventAt??Ce.startedAt)<Ze);q+=Pe.length,Pe.length>0&&We.push({...B,nodes:Pe,latest:Pe[0]}),ye.push({...B,nodes:Le,latest:Le[0]})}return{agents:ye.slice(0,Ur),hiddenGroupCount:Math.max(0,ye.length-Ur),filteredOutGroupsByDate:Ae,filteredOutSessionsByDate:q,visibleSessionCount:ye.slice(0,Ur).reduce((B,Q)=>B+Q.nodes.length,0),archivedGroups:We,sessionCountInScope:F.length}},[a,t.nodes,ve,x,b]);o.useEffect(()=>{k(!1),_(0)},[a]);const X=o.useMemo(()=>ue.reduce((F,ie)=>F+ie.nodes.length,0),[ue]),te=o.useMemo(()=>de.filter(F=>F.nodes.length>0).map(F=>F.groupKey),[de]),Ne=o.useMemo(()=>{if(te.length===0)return{allCollapsed:!1,allExpanded:!0};let F=0;for(const ie of te)h.has(ie)&&(F+=1);return{allCollapsed:F===te.length,allExpanded:F===0}},[h,te]),se=o.useMemo(()=>{const F=[];for(const ie of ue)for(const he of ie.nodes)F.push({node:he,agentName:ie.agentName});return F.sort((ie,he)=>Hi(ie.node,he.node)),F.slice(0,(p+1)*ap)},[ue,p]),$=F=>{v(ie=>{const he=new Set(ie);return he.has(F)?he.delete(F):he.add(F),he})},H=()=>{v(()=>Ne.allCollapsed?new Set:new Set(te))},z=o.useMemo(()=>U?de.find(F=>F.groupKey===U)??null:null,[de,U]),K=o.useMemo(()=>(z==null?void 0:z.nodes)??[],[z]),le=o.useMemo(()=>{if(!z)return[];const F=rt(z.agentName),ie=rt(z.agentId),he=un(z.agentId,z.agentName);return ee.filter(Ie=>{const Xe=rt(Ie.agentName),Qe=rt(Ie.agentId),Ee=un(Ie.agentId,Ie.agentName);return F!==null&&Xe===F||ie!==null&&Qe===ie||he!==null&&Ee!==null&&rt(he.agentId)===rt(Ee.agentId)})},[ee,z]),xe=ne===0,Se=ve.length>0,Y=o.useRef(null),[Te,fe]=o.useState(0),[C,O]=o.useState(0),W=o.useCallback(F=>{const ie=F.currentTarget.scrollTop;fe(he=>Math.abs(he-ie)<1?he:ie)},[]);o.useEffect(()=>{const F=Y.current;if(!F)return;const ie=()=>{const he=F.clientHeight,Ie=F.scrollTop;O(Xe=>Xe===he?Xe:he),fe(Xe=>Math.abs(Xe-Ie)<1?Xe:Ie)};if(ie(),typeof ResizeObserver<"u"){const he=new ResizeObserver(()=>ie());return he.observe(F),()=>he.disconnect()}return window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[de.length]);const{visibleAgentGroups:Z,topVirtualSpacerPx:Fe,bottomVirtualSpacerPx:Oe,virtualizationEnabled:Me}=o.useMemo(()=>{if(!(de.length>ep&&C>0))return{visibleAgentGroups:de,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const ie=de.map(qe=>{const at=h.has(qe.groupKey)?0:Math.min(qe.nodes.length,Mo);let Ze=tp;return at>0&&(Ze+=sp+at*np,qe.nodes.length>at&&(Ze+=20)),Ze+rp}),he=new Array(ie.length+1).fill(0);for(let qe=0;qe<ie.length;qe+=1)he[qe+1]=he[qe]+ie[qe];const Ie=he[he.length-1],Xe=Math.max(0,Te-To),Qe=Te+C+To;let Ee=0;for(;Ee<de.length&&he[Ee+1]<Xe;)Ee+=1;let et=Ee;for(;et<de.length&&he[et]<Qe;)et+=1;return et<=Ee&&(et=Math.min(de.length,Ee+1)),{visibleAgentGroups:de.slice(Ee,et),topVirtualSpacerPx:he[Ee],bottomVirtualSpacerPx:Math.max(0,Ie-he[et]),virtualizationEnabled:!0}},[de,h,Te,C]);return n.jsxs(Hs,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(Vm,{open:y,onClose:()=>j(!1),onLaunched:()=>{G.refetch(),u==null||u()}}),n.jsx(Zm,{open:U!==null,onClose:()=>ae(null),agentName:(z==null?void 0:z.agentName)??"",catalogAgent:(z==null?void 0:z.catalogAgent)??null,sessions:K,activity:le,onSelectSession:i,onRefresh:()=>G.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:[He," of ",ne]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:H,disabled:te.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:Ne.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:Ne.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:Y,onScroll:W,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[de.length===0&&!xe&&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."})]}),de.length===0&&xe&&!d&&n.jsx(ki,{icon:"agents",headline:"No active sessions yet",description:"Start a session to see agent conversations here."}),c&&l&&n.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-[#0AD4C4]/[0.08] px-3 py-1.5 text-caption text-[#0AD4C4]",children:[n.jsxs("span",{children:["Filtered: ",c]}),n.jsx("button",{type:"button",onClick:()=>l(null),className:"text-micro underline underline-offset-2",children:"Clear"})]}),n.jsxs("div",{className:"space-y-1.5",children:[Me&&Fe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Fe}}),Z.map(F=>{var Ce;const ie=F.groupKey,he=h.has(ie),Ie=F.latest,Xe=Ie?an(Ie):null,Qe=F.nodes.length>0,Ee=F.nodes.length===1,et=Hr(F.catalogAgent),qe=F.runtime??null,pt=(F.runtimeActiveCount??0)>0,at=!Qe&&pt&&qe!==null,Ze=Qe||at,ye=Ie?r===Ie.id:!1,We=F.agentName||((Ce=F.catalogAgent)==null?void 0:Ce.name)||F.agentId||"OrgX",Ae=un(F.agentId,We),q=(Ae==null?void 0:Ae.agentName)??mp(We),Re=(Ae==null?void 0:Ae.role)??Nl(q),B=ms(F.agentId,q,qe==null?void 0:qe.displayName,Ie==null?void 0:Ie.runtimeProvider,Ie==null?void 0:Ie.runtimeClient),Q=Ae===null&&(B.id==="codex"||B.id==="openai"||B.id==="anthropic"||B.id==="openclaw"),_e=Re?`${We} — ${Re}`:We,Le=he?[]:Qe?F.nodes.slice(0,Mo):[],De=Math.max(0,Qe?F.nodes.length-Le.length:0),Pe=rt(c)===rt(q)||rt(c)===rt(_e);return n.jsxs(pe.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:ce("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",ye&&"border-white/20 bg-white/[0.05]",Pe&&"border-[#0AD4C4]/30",!Qe&&!et&&!pt&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{Ee?i(F.nodes[0].id):at?$(ie):!Qe&&et?ae(ie):l?l(Pe?null:q):Ie&&i(Ie.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(Vs,{provider:B.id,size:"sm",showRing:!1})}):n.jsx(Fl,{running:F.nodes.filter(Ke=>{const ot=an(Ke);return ot==="running"||ot==="handoff"||ot==="review"}).length,blocked:F.nodes.filter(Ke=>{const ot=an(Ke);return ot==="blocked"||ot==="failed"}).length,paused:F.nodes.filter(Ke=>{const ot=an(Ke);return ot==="paused"||ot==="cancelled"}).length,size:36,children:n.jsx(Ot,{name:q,size:"sm",hint:`${F.agentId??""} ${q}`})}),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"})}),Ie&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:js(Xe??Ie.status),borderColor:D.cardBg}}),!Ie&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:et?js("running"):"rgba(255,255,255,0.2)",borderColor:D.cardBg}})]}),n.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[n.jsx("div",{className:"flex min-w-0 items-baseline",title:Re?`${We} — ${Re}`:We,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[q,Re&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Re]})]})}),n.jsx("div",{className:"flex items-center gap-1.5",children:Qe?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const Ke={};for(const ot of F.nodes){const Ge=an(ot);Ke[Ge]=(Ke[Ge]??0)+1}return Object.entries(Ke).map(([ot,Ge])=>`${Ge} ${ot}`).join(" · ")})(),children:(()=>{const Ke={};for(const Ge of F.nodes){const Nt=an(Ge);Ke[Nt]=(Ke[Nt]??0)+1}const ot=F.nodes.length;return Object.entries(Ke).map(([Ge,Nt])=>n.jsx("span",{style:{width:`${Nt/ot*100}%`,backgroundColor:js(Ge)}},Ge))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:F.nodes.length})]}):et||pt?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:js("running")}})}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:Math.max(1,F.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:()=>ae(ie),"aria-label":`View ${q} 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:()=>{Ze&&$(ie)},disabled:!Ze,"aria-label":Ze?he?"Expand sessions":"Collapse sessions":"No sessions to expand",className:ce("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",Ze?"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:ce("transition-transform",Ze&&!he?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(yt,{initial:!1,children:Ze&&!he&&n.jsx(pe.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 Ke=new Map,ot=[];for(const Je of Le){const Ct=an(Je);if(Ct==="blocked"||Ct==="paused"||Ct==="failed"){const Wt=`${Ct}:${Je.blockerReason??""}`,Qt=Ke.get(Wt)??[];Qt.push(Je),Ke.set(Wt,Qt)}else ot.push(Je)}const Ge=[];for(const[Je,Ct]of Ke)Ct.length>3?Ge.push({status:Je.split(":")[0],nodes:Ct}):ot.push(...Ct);const Nt=(Je,Ct)=>{const Wt=r===Je.id,Qt=an(Je),pn=ms(Je.agentName,Je.title,Je.lastEventSummary,Je);return n.jsx(pe.button,{onClick:()=>i(Je.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(Ct*.015,.12)},className:ce("w-full rounded-lg px-2.5 py-2 text-left transition-colors",Wt?"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(Vs,{provider:pn.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:Je.title,children:Je.title}),n.jsxs("div",{className:"flex items-center gap-1.5 text-micro text-secondary",children:[n.jsx("span",{className:"font-semibold uppercase tracking-[0.08em]",style:{color:pn.accent},children:pn.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:Qt}),n.jsx("span",{title:oi(Je.updatedAt??Je.lastEventAt??Je.startedAt??Date.now()),children:Mt(Je.updatedAt??Je.lastEventAt??Je.startedAt??Date.now())})]}),Je.progress!==null&&n.jsx("div",{className:"mt-1 h-0.5 rounded-full bg-white/[0.08]",children:n.jsx("div",{className:"h-0.5 rounded-full",style:{width:`${Math.round(Je.progress)}%`,background:`linear-gradient(90deg, ${D.lime}, ${D.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:js(Qt)},"aria-label":Qt,title:Qt})]})},Je.id)};return n.jsxs(n.Fragment,{children:[ot.map((Je,Ct)=>Nt(Je,Ct)),Ge.map(Je=>n.jsx(gp,{status:Je.status,nodes:Je.nodes,onSelectSession:i,selectedSessionId:r},`cg-${Je.status}-${Je.nodes.length}`))]})})(),De>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",De," older sessions hidden"]})]})})})]},ie)}),Me&&Oe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Oe}})]}),we>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",Ur," most recent agent groups (",we," older groups omitted)."]}),d&&g!=="connected"&&!Se&&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:op.map(F=>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:F.name.charAt(0)})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-caption font-medium text-secondary",children:F.name}),n.jsx("p",{className:"text-micro text-muted",children:F.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"})]},F.id))})]}),ge>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{k(F=>!F),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:ce("transition-transform",w?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[X," archived session",X===1?"":"s",je>0?` across ${je} agent${je===1?"":"s"}`:""]})]}),n.jsx(yt,{initial:!1,children:w&&n.jsx(pe.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:[se.map(({node:F,agentName:ie})=>{const he=an(F),Ie=F.runtimeProvider?{id:hp(F.runtimeProvider)}:ms(F.agentName,F.title,F.lastEventSummary,F);return n.jsxs("button",{onClick:()=>i(F.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(Vs,{provider:Ie.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:oi(F.updatedAt??F.lastEventAt??F.startedAt??Date.now()),children:Mt(F.updatedAt??F.lastEventAt??F.startedAt??Date.now())})]}),n.jsx("p",{className:"truncate text-micro text-secondary",children:F.title}),n.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:he})]})]},F.id)}),se.length<X&&n.jsxs("button",{onClick:()=>_(F=>F+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 (",X-se.length," remaining)"]})]})})})]})]})]})}),yp=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),bp=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),wp=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),vp=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),kp=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function qs(e){return e?qt(e):""}function Vi(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function jp(e){return e.some(t=>yp.has(t))}function Np(e){return e.some(t=>bp.has(t))}function Ip(e){return e.some(t=>wp.has(t))}function Ap(e){return e.some(t=>vp.has(t))}function Sp(e){return e.some(t=>kp.has(t))}function Qn(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",l=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:l}}function _p(e){const t=qs(e.sessionStatus),s=qs(e.sessionPhase),r=qs(e.sessionState),i=qs(e.sliceStatus),a=qs(e.activityStatus),l=qs(e.stopReason),c=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,r,i,a,l].filter(_=>_.length>0),u=Vi(e.blockingDecisionCount),g=Vi(e.nonBlockingDecisionCount),x=Vi(e.blockerCount),b=c==="run_failed",h=c==="run_completed"||c==="milestone_completed"||c==="decision_resolved",v=b||jp(d),y=Np(d)||c==="decision_requested"||u>0||e.decisionRequired===!0,j=Ip(d)||x>0,w=h||Ap(d),k=Sp(d)||c==="run_started";if(v)return Qn("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(w&&!y&&!v&&x===0&&!e.blockerReason)return g>0?Qn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Qn("completed","Execution completed successfully.",{tone:"positive"});if(y||j)return u>0||e.decisionRequired===!0||c==="decision_requested"?Qn("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):Qn("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:j?"critical":"warning"});if(w)return g>0?Qn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Qn("completed","Execution completed successfully.",{tone:"positive"});if(k){const _=g>0?`Running with ${g} optional decision${g===1?"":"s"} available.`:"Running.";return Qn("in_progress",_,{tone:"neutral"})}return Qn("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const Ki=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Cp(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ns(e,t){const s=[];let r=0,i=0;Ki.lastIndex=0;for(let a=Ki.exec(e);a;a=Ki.exec(e)){const[l]=a,c=a.index;c>r&&s.push(e.slice(r,c));const d=`${t}-${i++}`,u=a[1],g=a[2],x=a[3],b=a[4],h=a[5],v=a[6],y=a[7];u&&g&&Cp(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)):x?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:x},d)):b||h?s.push(n.jsx("strong",{className:"font-semibold text-white",children:b??h},d)):v||y?s.push(n.jsx("em",{className:"italic text-bright",children:v??y},d)):s.push(l),r=c+l.length}return r<e.length&&s.push(e.slice(r)),s}function Mp(e,t){const s=e.split(`
|
|
204
|
-
`),r=[];return s.forEach((i,a)=>{r.push(...Ns(i,`${t}-line-${a}`)),a<s.length-1&&r.push(n.jsx("br",{},`${t}-br-${a}`))}),r}function ii(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Tp(e){const t=ii(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 Rp(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 l=i.includes("|"),c=t[r+1]??"";if(l&&c.includes("|")&&Tp(c)){const b=ii(i),v=ii(c).map(j=>Ep(j));r+=2;const y=[];for(;r<t.length;){const j=t[r]??"";if(!j.trim()||!j.includes("|"))break;y.push(ii(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:b.map((j,w)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:v[w]??"left"},children:Ns(j,`tbl-h-${r}-${w}`)},`tbl-h-${w}`))})}),n.jsx("tbody",{children:y.map((j,w)=>n.jsx("tr",{className:w<y.length-1?"border-b border-subtle":void 0,children:b.map((k,p)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:v[p]??"left"},children:Ns(j[p]??"",`tbl-r-${r}-${w}-${p}`)},`tbl-r-${w}-c-${p}`))},`tbl-r-${w}`))})]})},`tbl-${r}`));continue}if(a.startsWith("```")){const b=a.slice(3).trim(),h=[];for(r+=1;r<t.length&&!(t[r]??"").trim().startsWith("```");)h.push(t[r]??""),r+=1;r<t.length&&(r+=1),s.push(n.jsxs("div",{className:"rounded-xl border border-white/[0.1] bg-black/40 p-3",children:[b&&n.jsx("p",{className:"mb-1 text-micro uppercase tracking-[0.12em] text-muted",children:b}),n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:n.jsx("code",{children:h.join(`
|
|
207
|
-
`)})})]},`code-${r}`));continue}const d=a.match(/^(#{1,3})\s+(.+)$/);if(d){const b=d[1].length,h=d[2],v=b===1?"text-title font-semibold":b===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:ce("tracking-[-0.01em] text-white",v),children:Ns(h,`h-${r}`)},`h-${r}`)),r+=1;continue}if(i.match(/^\s*[-*]\s+(.+)$/)){const b=[];for(;r<t.length;){const v=(t[r]??"").match(/^\s*[-*]\s+(.+)$/);if(!v)break;b.push(v[1]),r+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:b.map((h,v)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:Ns(h,`ul-${r}-${v}`)},`ul-${r}-${v}`))},`ul-${r}`));continue}if(i.match(/^\s*\d+\.\s+(.+)$/)){const b=[];for(;r<t.length;){const v=(t[r]??"").match(/^\s*\d+\.\s+(.+)$/);if(!v)break;b.push(v[1]),r+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:b.map((h,v)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:Ns(h,`ol-${r}-${v}`)},`ol-${r}-${v}`))},`ol-${r}`));continue}const x=[];for(;r<t.length;){const b=t[r]??"",h=b.trim();if(!h||/^(#{1,3})\s+/.test(h)||/^\s*[-*]\s+/.test(b)||/^\s*\d+\.\s+/.test(b)||h.startsWith("```"))break;x.push(b),r+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Mp(x.join(`
|
|
208
|
-
`),`p-${r}`)},`p-${r}`))}return s}function pi({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:Ns(r,"inline")}):n.jsx("div",{className:ce("space-y-2",s),children:Rp(r)}):null}function Ol(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Lp(e){if(!e)return;const t=Ol(e.metadata);return t?{...e,...t}:e}const Bl={run_started:{icon:"play",label:"Run started",color:D.teal},run_completed:{icon:"check_circle",label:"Run completed",color:D.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:D.red},artifact_created:{icon:"file",label:"Artifact",color:D.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:D.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:D.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:D.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:D.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:D.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:D.red},milestone_completed:{icon:"flag",label:"Milestone",color:D.cyan},delegation:{icon:"workflow",label:"Delegation",color:D.iris}};function Pn(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 ga(e){return e?e.toLowerCase():""}function Dp(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,Pn(t,["source","event","eventType","artifact_type","action","kind"]),Pn(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function $p(e,t){const s=ga(Pn(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:D.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:D.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:D.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:D.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:D.cyan}:Bl.artifact_created}function Fp(e){const t=Lp(Ol(e.metadata)),s=Dp(e,t),r=ga(Pn(t,["source"])),i=ga(Pn(t,["action"])),a=Pn(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"&&Pn(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:D.teal};if(a==="auto_continue_stopped"){const c=Pn(t,["stop_reason"]);return c==="error"||c==="blocked"?{icon:"infinity",label:"Autopilot blocked",color:D.red}:c==="budget_exhausted"?{icon:"infinity",label:"Budget exhausted",color:D.amber}:{icon:"infinity",label:"Autopilot stopped",color:D.amber}}if(a==="autopilot_transition"){const c=Pn(t,["new_state"]);return c==="blocked"||c==="error"?{icon:"infinity",label:"Autopilot blocked",color:D.red}:{icon:"infinity",label:"Autopilot transition",color:D.teal}}const l=Pn(t,["parsed_status","status"]);return l==="completed"||l==="success"?{icon:"check_circle",label:"Slice completed",color:D.lime}:{icon:"infinity",label:"Autopilot slice",color:D.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:D.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:D.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:D.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:D.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:D.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:D.iris};if(r==="local_openclaw")return{icon:"terminal",label:"Local",color:D.teal};if(e.type==="artifact_created")return $p(t,s);if(e.type==="decision_resolved")return i==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:D.red}:{icon:"shield_check",label:"Decision approved",color:D.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Dispatch",color:D.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:D.teal}}return Bl[e.type]??{icon:"message",label:"Activity",color:D.textMuted}}function Pp({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(Il,{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 fi(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function xa(e){if(!e)return;const t=fi(e.metadata);return t?{...e,...t}:e}function Op(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function Bp(e){let t=0;for(const s of e){const r=xa(fi(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 qp=o.memo(function({items:t,session:s,agentName:r,onBack:i,onOpenItem:a}){const[l,c]=o.useState(!1),d=o.useMemo(()=>[...t].sort((h,v)=>Date.parse(h.timestamp)-Date.parse(v.timestamp)),[t]),u=o.useMemo(()=>Bp(d),[d]),g=o.useMemo(()=>{if(d.length<2)return null;const h=Date.parse(d[0].timestamp),y=Date.parse(d[d.length-1].timestamp)-h;return y<6e4?`${Math.round(y/1e3)}s`:y<36e5?`${Math.round(y/6e4)}m`:`${(y/36e5).toFixed(1)}h`},[d]),x=o.useMemo(()=>{let h=null,v=null,y=null,j=null,w=null;for(const p of d){const _=xa(fi(p.metadata));if(_&&(!h&&typeof _.domain=="string"&&(h=_.domain),!v&&typeof _.provider=="string"&&(v=_.provider),!y&&typeof _.model=="string"&&(y=_.model),!j&&typeof _.spawn_guard_model_tier=="string"&&(j=_.spawn_guard_model_tier),!w&&typeof _.kickoff_context_hash=="string"&&(w=_.kickoff_context_hash),h&&(v||y)&&j&&w))break}return!(h||v||y||j||w)?null:{domain:h,provider:v,model:y,modelTier:j,kickoffContextHash:w}},[d]),b=(s==null?void 0:s.title)??r??"Session";return n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-3",children:[n.jsxs("button",{onClick:i,className:"mb-2 flex items-center gap-1.5 text-caption text-secondary transition-colors hover:text-primary",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})}),"Back to timeline"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:D.lime,boxShadow:`0 0 12px ${D.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:lt(b)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-micro text-secondary",children:[r&&n.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-subtle px-1 py-0.5",children:[n.jsx(Ot,{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}),(x==null?void 0:x.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:lt(x.domain)}),(s==null?void 0:s.status)&&n.jsx("span",{className:"rounded-full px-1.5 py-0.5 text-micro uppercase tracking-wider",style:{backgroundColor:s.status==="running"?`${D.lime}20`:s.status==="failed"?`${D.red}20`:`${D.teal}20`,color:s.status==="running"?D.lime:s.status==="failed"?D.red:D.teal},children:s.status}),x&&(x.provider||x.model||x.modelTier||x.kickoffContextHash)&&n.jsxs("button",{type:"button",onClick:()=>c(h=>!h),className:"inline-flex items-center gap-1 text-micro text-muted transition-colors hover:text-secondary",children:[n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:`transition-transform duration-150 ${l?"rotate-180":""}`,children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),"Info"]})]}),l&&x&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(x.provider||x.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[x.provider?`${lt(x.provider)} · `:"",x.model?Ar(x.model):"—"]}),x.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",lt(x.modelTier)]}),x.kickoffContextHash&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 font-mono text-secondary",children:["kickoff ",x.kickoffContextHash.slice(0,8),"…"]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:[n.jsx(yt,{mode:"popLayout",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"absolute left-[7px] top-3 bottom-3 w-px",style:{backgroundColor:`${D.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((h,v)=>{var G;const y=Fp(h),j=y.color,w=(G=xa(fi(h.metadata)))==null?void 0:G.model,k=typeof w=="string"?Ar(w):null,p=lt(h.title??""),_=h.type==="run_failed",U=h.type==="artifact_created",ae=h.type==="decision_requested"||h.type==="decision_resolved";return n.jsxs(pe.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:v*.02},onClick:()=>a==null?void 0:a(h),className:"group relative flex w-full items-start gap-2.5 rounded-lg py-1.5 pl-0 pr-2 text-left transition-colors hover:bg-white/[0.02] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#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(Pp,{icon:y.icon,size:8,className:"opacity-95"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:`text-body leading-snug ${_?"text-red-400":ae?"text-amber-300":U?"text-cyan-300":"text-bright"}`,children:p}),h.summary&&h.summary!==p&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:lt(h.summary)})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-0.5 pt-0.5",children:[n.jsx("span",{className:"text-micro text-muted",title:oi(h.timestamp),children:Op(h.timestamp)}),k&&n.jsx("span",{className:"text-micro text-faint",children:k})]})]},h.id)})})]})}),d.length===0&&n.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-center",children:[n.jsx("p",{className:"text-body text-secondary",children:"No activity in this session yet."}),n.jsx("p",{className:"text-caption text-muted animate-pulse",children:"Activity may take a moment to appear."})]}),d.length>0&&n.jsxs("div",{className:"mt-4 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2 text-micro text-muted",children:[d.length," turn",d.length!==1?"s":"",g?` over ${g}`:"",u?` · ${u}`:""," · ",n.jsx("span",{title:oi(d[d.length-1].timestamp),children:Mt(d[d.length-1].timestamp)})]})]})]})});function zp({completedCount:e,decisionsCount:t,blockerCount:s,visible:r,onDismiss:i}){if(!(e>0||t>0||s>0))return null;const l=[];return e>0&&l.push(`${e} task${e===1?"":"s"} completed`),t>0&&l.push(`${t} need${t===1?"s":""} decisions`),s>0&&l.push(`${s} new blocker${s===1?"":"s"}`),n.jsx(yt,{children:r&&n.jsx(pe.div,{initial:{opacity:0,height:0,marginBottom:0},animate:{opacity:1,height:"auto",marginBottom:12},exit:{opacity:0,height:0,marginBottom:0},transition:{duration:.3,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{className:"rounded-xl px-4 py-3",style:{backgroundColor:`${D.teal}08`,border:`1px solid ${D.teal}20`},children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"While you were away"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:l.join(" · ")})]}),n.jsx("button",{onClick: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 Wp={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}};function Up({renderKey:e,displayTitle:t,headline:s,contextLabel:r,detailText:i,displayAgentName:a,railColor:l,userStateLabel:c,userStateWhy:d,relativeTime:u,timeLabel:g,isRecent:x,enableMotion:b,onOpen:h,ariaLabel:v,artifactSnippet:y}){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(Ot,{name:a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:ce("absolute inset-y-0 left-0 w-[2px] rounded-full",x&&"pulse-soft"),style:{backgroundColor:l,boxShadow:`0 0 14px ${l}66`}}),n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"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})]})]}),y?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:y.label}),y.preview&&n.jsx("span",{className:"ml-1.5 text-cyan-200/60",children:y.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(pi,{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:`${l}55`,backgroundColor:`${l}1A`,color:l},title:d,children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:l}}),c]}),n.jsx("span",{className:"inline-flex max-w-[220px] items-center gap-1 rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",title:a,children:n.jsx("span",{className:"truncate",children:a})})]})]})]});return b?n.jsx(pe.button,{type:"button",variants:Wp,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:h,className:j,"aria-label":v,children:w},e):n.jsx("button",{type:"button",onClick:h,className:ce(j,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":v,children:w},e)}function Hp({open:e,onClose:t,children:s}){return n.jsx(vi,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function Vp(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 Kp={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(()=>kc(e),[e]),r=Vp(e),i=Kp[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(Gi,{label:"Task",value:s.taskDescription,styles:i}),s.outcomeDescription&&n.jsx(Gi,{label:"Outcome",value:s.outcomeDescription,styles:i}),s.nextStep&&n.jsx(Gi,{label:"Next step",value:s.nextStep,styles:i})]})}function Gi({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 Ro=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"}],gr=[{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"}],Lo={type:"spring",stiffness:400,damping:25},Do={scale:.985};function Xt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Qp(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 xr(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(Lt(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function Jp(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function Yp(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 hi(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function Ks(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 ql(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function Zp(e){return e==="agent"?"assistant":e}function ef(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function tf(e,t){return t.map(s=>({id:s.id,role:Zp(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function zl(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 ai(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 nf(e){const t=Gs(e);if(!t)return null;const s=ai({...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 l=a.role==="agent"||a.role==="system"?a.role:"user";return{id:typeof a.id=="string"?a.id:`msg_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,role:l,body:typeof a.body=="string"?a.body:"",senderId:typeof a.senderId=="string"?a.senderId:null,senderName:typeof a.senderName=="string"?a.senderName:null,createdAt:typeof a.createdAt=="string"?a.createdAt:s.createdAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,attachments:Array.isArray(a.attachments)?a.attachments.filter(c=>!!c&&typeof c=="object"):[],metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[],i=Array.isArray(t.launches)?t.launches.map(a=>Gs(a)).filter(a=>!!a).map(a=>{const l=a.executionMode==="cloud"||a.executionMode==="hybrid"?a.executionMode:"local_queue",c=a.status==="queued"||a.status==="running"||a.status==="blocked"||a.status==="completed"||a.status==="failed"||a.status==="requested"?a.status:"requested";return{id:typeof a.id=="string"?a.id:`launch_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,messageId:typeof a.messageId=="string"?a.messageId:"",assigneeId:typeof a.assigneeId=="string"?a.assigneeId:null,assigneeName:typeof a.assigneeName=="string"?a.assigneeName:null,watcherIds:Array.isArray(a.watcherIds)?a.watcherIds.filter(d=>typeof d=="string"):[],watcherNames:Array.isArray(a.watcherNames)?a.watcherNames.filter(d=>typeof d=="string"):[],executionMode:l,provider:typeof a.provider=="string"?a.provider:null,runId:typeof a.runId=="string"?a.runId:null,status:c,blockedReason:typeof a.blockedReason=="string"?a.blockedReason:null,warnings:Array.isArray(a.warnings)?a.warnings.filter(d=>typeof d=="string"):[],requestedAt:typeof a.requestedAt=="string"?a.requestedAt:s.updatedAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[];return{...s,messages:r.sort((a,l)=>Xt(a.createdAt)-Xt(l.createdAt)),launches:i.sort((a,l)=>Xt(l.requestedAt)-Xt(a.requestedAt))}}function sf(e,t,s){const r=Xt(e.lastActivityAt);if(!r)return!1;if(t==="custom"){const a=Xt(s.startIso),l=Xt(s.endIso);return!(a&&r<a||l&&r>l)}const i=Cr(t,Date.now());return i?r>=i:!0}async function yr(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 Xi(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)=>Xt(i.lastActivityAt??i.updatedAt)-Xt(r.lastActivityAt??r.updatedAt))}function rf(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)=>Xt(i.lastActivityAt??i.updatedAt)-Xt(r.lastActivityAt??r.updatedAt))}const Wl=o.createContext(null),Ul=o.createContext(null);function Ta(){const e=o.useContext(Wl);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function Ea(){const e=o.useContext(Ul);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function af({children:e,sessions:t,initiatives:s,workspaceId:r,query:i,statusFilter:a,sortOrder:l,timeFilterId:c,customTimeRange:d,snapshot:u,onRequestRefresh:g}){const[x,b]=o.useState((u==null?void 0:u.threads)??[]),[h,v]=o.useState(null),[y,j]=o.useState(null),[w,k]=o.useState(!1),[p,_]=o.useState(null),[U,ae]=o.useState("resting"),[G,ve]=o.useState(""),[V,ee]=o.useState(!1),[de,we]=o.useState(!1),[je,ge]=o.useState(null),[He,ue]=o.useState(null),[ne,X]=o.useState([]),[te,Ne]=o.useState(""),[se,$]=o.useState([]),[H,z]=o.useState(""),[K,le]=o.useState(null),[xe,Se]=o.useState(""),[Y,Te]=o.useState(!1),[fe,C]=o.useState(""),[O,W]=o.useState([]),[Z,Fe]=o.useState(!1),[Oe,Me]=o.useState("auto"),[T,F]=o.useState(!1),[ie,he]=o.useState(!1),[Ie,Xe]=o.useState(!1),Qe=o.useRef(null),Ee=o.useRef(null),et=o.useRef(null),qe=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&b(E=>rf(E,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{h&&b(E=>E.sort((oe,me)=>Xt(me.lastActivityAt)-Xt(oe.lastActivityAt)))},[h]);const{data:pt}=Ca({enabled:!0,refetchInterval:8e3}),at=o.useMemo(()=>{var oe,me;const E=new Map;for(const $e of Xp)E.set($e.id,{id:$e.id,name:$e.name,handle:$e.handle,domain:$e.domain,domainLabel:$e.domainLabel,role:$e.role,status:"idle",currentTask:null,isSystem:!1});if(pt!=null&&pt.agents)for(const $e of pt.agents){const ft=E.get($e.id);ft?(ft.status=$e.status==="running"?"running":(oe=$e.blockers)!=null&&oe.length?"blocked":"idle",ft.currentTask=$e.currentTask??null):E.set($e.id,{id:$e.id,name:$e.name,handle:$e.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:$e.status==="running"?"running":(me=$e.blockers)!=null&&me.length?"blocked":"idle",currentTask:$e.currentTask??null,isSystem:Ro.has($e.id)})}for(const $e of t){const ft=($e.agentId??"").trim(),ht=($e.agentName??"").trim();!ft||!ht||E.has(ft)||E.set(ft,{id:ft,name:ht,handle:ft,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:Ro.has(ft)})}return Array.from(E.values()).filter($e=>!$e.isSystem).sort(($e,ft)=>$e.name.localeCompare(ft.name))},[pt,t]),Ze=o.useMemo(()=>s.map(E=>({id:E.id,name:E.name})).sort((E,oe)=>E.name.localeCompare(oe.name)),[s]),ye=o.useMemo(()=>at.find(E=>E.id===te)??null,[at,te]),We=o.useMemo(()=>{const E=new Set(se);return at.filter(oe=>E.has(oe.id))},[at,se]),Ae=o.useMemo(()=>Ze.find(E=>E.id===H)??null,[Ze,H]);o.useEffect(()=>{te&&$(E=>E.filter(oe=>oe!==te))},[te]);const q=o.useMemo(()=>at.slice(0,8),[at]),Re=o.useMemo(()=>{const E=xe.trim().toLowerCase();return E?at.filter(oe=>oe.name.toLowerCase().includes(E)||oe.handle.toLowerCase().includes(E)||oe.domain.toLowerCase().includes(E)||oe.role.toLowerCase().includes(E)):at},[at,xe]),B=o.useMemo(()=>{const E=fe.trim().toLowerCase();return E?Ze.filter(oe=>oe.name.toLowerCase().includes(E)):Ze},[Ze,fe]),Q=o.useMemo(()=>{const E=i.trim().toLowerCase(),oe=x.filter(me=>!Yp(me,a)||!sf(me,c,d)?!1:E.length===0?!0:Jp(me).includes(E));return oe.sort((me,$e)=>{const ft=Xt($e.lastActivityAt)-Xt(me.lastActivityAt);return l==="newest"?ft:-ft}),oe},[d,i,l,a,x,c]),_e=o.useMemo(()=>{if(!h||Q.some(oe=>oe.id===h))return Q;const E=x.find(oe=>oe.id===h);return E?[E,...Q]:Q},[h,Q,x]),Le=o.useMemo(()=>x.find(E=>E.id===h)??null,[h,x]),De=o.useMemo(()=>ne.filter(E=>E.status!=="ready").length,[ne]),Ce=G.trim().length>0&&!V,Ke=o.useMemo(()=>De>0?`${De} attachment(s) still processing.`:"Press Enter to send.",[De]),ot=o.useMemo(()=>V?"Sending…":de?"Launching…":"Send",[de,V]),Ge=o.useMemo(()=>new mc({api:"/orgx/api/chat/usechat"}),[]),{messages:Nt,setMessages:Je,sendMessage:Ct,status:Wt,error:Qt,clearError:pn}=pc({id:`orgx-chat-guidance-${r??"global"}`,transport:Ge,onError:E=>{ge(xr((E==null?void 0:E.message)??null,"send"))}});o.useEffect(()=>{if(!y){Je([]);return}Je(tf(y.id,y.messages))},[y,Je]);const fn=o.useMemo(()=>{const E=[...Nt].reverse().find(me=>me.role==="assistant");if(!E)return null;const oe=ef(E);return oe.length>0?oe:null},[Nt]),xs=o.useRef(null);o.useEffect(()=>{if(Wt!=="ready"&&Wt!=="error"||!fn)return;const E=[...Nt].reverse().find(oe=>oe.role==="assistant");!E||E.id===xs.current||(xs.current=E.id,W(oe=>[...oe,{id:`guidance_${E.id}`,role:"agent",body:fn,timestamp:new Date().toISOString()}]))},[Wt,fn,Nt]);const bt=o.useCallback(()=>{ve(""),X([]),he(!1),Xe(!1),ge(null),ue(null)},[]),Ut=o.useCallback(E=>{W(oe=>[...oe,{...E,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),Sn=o.useCallback(()=>W([]),[]),Bn=o.useCallback(()=>Fe(E=>!E),[]),ct=o.useMemo(()=>gr.find(E=>E.id===Oe)??gr[0],[Oe]),_n=o.useCallback(()=>{Me(E=>{const oe=gr.findIndex(me=>me.id===E);return gr[(oe+1)%gr.length].id})},[]),It=o.useCallback(async()=>{typeof g=="function"&&await g()},[g]),Tt=o.useCallback(async E=>{var $e;k(!0),_(null);const oe=await yr(`/orgx/api/chat/threads/${encodeURIComponent(E)}`);if(!oe.ok||!(($e=oe.data)!=null&&$e.thread))return k(!1),_(xr(oe.error,"load")),null;const me=nf(oe.data.thread);return me?(j(me),k(!1),me):(k(!1),_("Thread detail payload was invalid."),null)},[]),en=o.useCallback(async(E,oe)=>{oe&&(et.current=oe),v(E),await Tt(E),requestAnimationFrame(()=>{var me;return(me=Ee.current)==null?void 0:me.focus()})},[Tt]),ys=o.useCallback(()=>{var E;v(null),j(null),_(null),k(!1),(E=et.current)==null||E.focus()},[]),qn=o.useCallback(E=>{window.setTimeout(()=>{X(oe=>oe.map(me=>me.id===E?{...me,status:"indexing",updatedAt:new Date().toISOString()}:me))},80),window.setTimeout(()=>{X(oe=>oe.map(me=>{var ht;if(me.id!==E)return me;const $e=((ht=me.mimeType)==null?void 0:ht.toLowerCase())==="application/x-msdownload"||me.name.toLowerCase().endsWith(".exe"),ft=(me.sizeBytes??0)>25*1024*1024;return $e?{...me,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:ft?{...me,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...me,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Cn=o.useCallback(E=>{if(!E||E.length===0)return;const oe=new Date().toISOString(),me=Array.from(E).map($e=>({id:`draft_att_${crypto.randomUUID()}`,name:$e.name,mimeType:$e.type||null,sizeBytes:Number.isFinite($e.size)?$e.size:null,status:"preparing",error:null,masked:!1,createdAt:oe,updatedAt:oe}));X($e=>$e.concat(me)),me.forEach($e=>qn($e.id)),cs("chat_attachment_state_changed",{count:me.length,state:"preparing"})},[qn]),Mn=o.useCallback(E=>{X(oe=>oe.map(me=>me.id===E?{...me,status:"preparing",error:null,updatedAt:new Date().toISOString()}:me)),qn(E),cs("chat_attachment_state_changed",{state:"retry"})},[qn]),hn=o.useCallback(E=>{Ne(oe=>oe===E?"":E),$(oe=>oe.filter(me=>me!==E)),le(null),Se("")},[]),cn=o.useCallback(E=>{$(oe=>oe.includes(E)?oe.filter(me=>me!==E):oe.concat(E))},[]),Ht=o.useCallback(()=>{Te(!1),C(""),le(E=>E==="assignee"?null:"assignee"),Se("")},[]),ts=o.useCallback(()=>{Te(!1),C(""),le(E=>E==="watcher"?null:"watcher"),Se("")},[]),gn=o.useCallback(()=>{le(null),Se(""),Te(E=>!E),C("")},[]),zn=o.useCallback(async(E,oe)=>{var ht;F(!0);const me=Ze.find(ze=>ze.id===oe)??null,$e=await yr("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:E,project_id:r??void 0,initiativeId:(me==null?void 0:me.id)??null,initiativeTitle:(me==null?void 0:me.name)??null,relinked:!0})});if(F(!1),!$e.ok||!((ht=$e.data)!=null&&ht.thread)){_($e.error??"Scope link failed.");return}const ft=ai($e.data.thread);ft&&b(ze=>Xi(ze,ft)),await Tt(E),await It(),cs("chat_thread_linked_initiative",{threadId:E,initiativeId:(me==null?void 0:me.id)??null})},[Ze,Tt,It,r]),ns=o.useCallback(async E=>{pn(),await Ct({text:E.prompt},{body:{threadId:E.thread.id,project_id:r??void 0,initiativeId:E.thread.initiativeId??(Ae==null?void 0:Ae.id)??void 0,initiativeTitle:E.thread.initiativeTitle??(Ae==null?void 0:Ae.name)??void 0,assigneeId:(ye==null?void 0:ye.id)??E.thread.assigneeId??void 0,assigneeName:(ye==null?void 0:ye.name)??E.thread.assigneeName??void 0,watcherIds:We.map(oe=>oe.id),watcherNames:We.map(oe=>oe.name)}}),await It(),await Tt(E.thread.id)},[pn,Tt,It,ye==null?void 0:ye.id,ye==null?void 0:ye.name,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,We,Ct,r]),xn=o.useCallback(async()=>{var ft,ht;const E=G.trim();if(!E)return ge("Write a message before sending."),{thread:null,messageId:null};ge(null),ue(null),ee(!0);const oe=await yr("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:h??void 0,project_id:r??void 0,initiativeId:(Ae==null?void 0:Ae.id)??(y==null?void 0:y.initiativeId)??void 0,initiativeTitle:(Ae==null?void 0:Ae.name)??(y==null?void 0:y.initiativeTitle)??void 0,assigneeId:(ye==null?void 0:ye.id)??(y==null?void 0:y.assigneeId)??void 0,assigneeName:(ye==null?void 0:ye.name)??(y==null?void 0:y.assigneeName)??void 0,watcherIds:We.map(ze=>ze.id),watcherNames:We.map(ze=>ze.name),body:E,attachments:ne.map(ze=>({id:ze.id,name:ze.name,mimeType:ze.mimeType,sizeBytes:ze.sizeBytes,status:ze.status,error:ze.error,masked:ze.masked}))})});if(ee(!1),!oe.ok||!((ft=oe.data)!=null&&ft.thread))return ge(xr(oe.error,"send")),cs("chat_message_send_failed",{reason:oe.error??"unknown"}),{thread:null,messageId:null};const me=ai(oe.data.thread);if(!me)return ge("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};b(ze=>Xi(ze,me)),Ut({role:"user",body:E}),Oe!=="auto"&&ye&&Ut({role:"system",body:`Routing to ${ye.name} via ${ct.label}`}),cs("chat_message_sent",{threadId:me.id,watcherCount:me.watcherIds.length}),await It();const $e=oe.data.message&&typeof oe.data.message.id=="string"?oe.data.message.id:((ht=me.latestMessage)==null?void 0:ht.id)??null;return v(me.id),await Tt(me.id),ns({thread:me,prompt:E}).catch(ze=>{Ut({role:"error",body:xr(ze instanceof Error?ze.message:String(ze??""),"send")})}),bt(),ae("reviewing"),{thread:me,messageId:$e}},[y==null?void 0:y.assigneeId,y==null?void 0:y.assigneeName,y==null?void 0:y.initiativeId,y==null?void 0:y.initiativeTitle,h,G,ne,Tt,It,bt,ns,ye==null?void 0:ye.id,ye==null?void 0:ye.name,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,Oe,ct,We,r]),ss=o.useCallback(async(E,oe)=>{var vt,gt,bn,Un,wn,bs,Hn;if(!oe){Ut({role:"error",body:"Send a message first to launch."});return}if(!ye){Ut({role:"error",body:"Pick an agent with @ before launching."});return}if(De>0&&!Ie){he(!0),Ut({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}we(!0),ge(null),ue(null);const me=await yr("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:ye.id,message:G.trim().length>0?G.trim():E.lastSnippet??E.title,initiativeId:E.initiativeId??(Ae==null?void 0:Ae.id)??void 0,initiativeTitle:E.initiativeTitle??(Ae==null?void 0:Ae.name)??void 0,workstreamId:E.workstreamId??void 0,taskId:E.taskId??void 0,provider:Oe!=="auto"?Oe:void 0})}),$e=((vt=me.data)==null?void 0:vt.sessionId)??((gt=me.data)==null?void 0:gt.runId)??null,ft=me.ok&&$e?"running":me.ok?"queued":"blocked",ht=me.ok?null:me.error??"Launch request failed before queueing.",ze=await yr("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:E.id,messageId:oe,assigneeId:ye.id,assigneeName:ye.name,watcherIds:We.map(St=>St.id),watcherNames:We.map(St=>St.name),executionMode:"local_queue",provider:((bn=me.data)==null?void 0:bn.provider)??(Oe!=="auto"?Oe:"openclaw"),runId:$e??void 0,status:ft,blockedReason:ht??void 0,warnings:De>0?[`${De} attachment(s) were not ready at launch.`]:[]})});if(we(!1),Xe(!1),he(!1),!ze.ok||!((Un=ze.data)!=null&&Un.thread)){ge(ze.error?xr(ze.error,"launch"):ht??"Launch state could not be persisted. Message remained saved."),cs("chat_launch_failed",{threadId:E.id,reason:ze.error??ht??"unknown"});return}const Ms=ai(ze.data.thread);if(Ms&&b(St=>Xi(St,Ms)),await Tt(E.id),await It(),!me.ok){ge(`Launch blocked: ${ht??"Set assignee and retry."}`),cs("chat_launch_blocked",{threadId:E.id,reason:ht??"unknown"});return}const dt=((wn=me.data)==null?void 0:wn.provider)==="anthropic"?"Claude Code":((bs=me.data)==null?void 0:bs.provider)==="openai"?"Codex":ct.shortLabel,Ts=(Hn=me.data)!=null&&Hn.model?` (${me.data.model})`:"";ue($e?`Launch started via ${dt}${Ts}. Thread timeline now tracks execution state.`:`Launch queued locally via ${dt}. Run starts when a worker is available.`),cs($e?"chat_launch_started":"chat_launch_queued",{threadId:E.id,runId:$e,assigneeId:ye.id})},[G,Ie,Tt,It,ye,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,Oe,ct,We,De]),Dt=o.useCallback(async()=>{var oe;const E=await xn();(oe=E.thread)!=null&&oe.id&&await en(E.thread.id)},[en,xn]),yn=o.useCallback(async()=>{const E=await xn();E.thread&&(await ss(E.thread,E.messageId),await en(E.thread.id))},[ss,en,xn]),tn=o.useCallback(async()=>{if(Ce){if(ye){await yn();return}await Dt()}},[Ce,yn,Dt,ye]),rs=o.useMemo(()=>({threads:x,activeThreadId:h,activeThread:y,activeThreadSummary:Le,displayedThreads:_e,composerMode:U,draft:G,draftAttachments:ne,sending:V,launching:de,composerError:je,composerNotice:He,selectedAssigneeId:te,selectedAssignee:ye,selectedWatcherIds:se,selectedWatchers:We,selectedInitiativeId:H,selectedInitiative:Ae,agentOptions:at,quickAssigneeOptions:q,initiativeOptions:Ze,agentPickerMode:K,agentPickerQuery:xe,filteredAgentOptions:Re,scopePickerOpen:Y,scopePickerQuery:fe,filteredInitiativeOptions:B,panelLoading:w,panelError:p,scopeSaving:T,launchWarningOpen:ie,launchWarningAccepted:Ie,unresolvedAttachmentCount:De,canSend:Ce,composerGuidance:Ke,primaryActionLabel:ot,guidanceStatus:Wt,guidancePreview:fn,guidanceError:Qt??null,inlineMessages:O,threadSidebarOpen:Z,workspaceId:r,selectedProvider:Oe,selectedProviderDef:ct}),[x,h,y,Le,_e,U,G,ne,V,de,je,He,te,ye,se,We,H,Ae,at,q,Ze,K,xe,Re,Y,fe,B,w,p,T,ie,Ie,De,Ce,Ke,ot,Wt,fn,Qt,O,Z,r,Oe,ct]),Wn=o.useMemo(()=>({setDraft:ve,setComposerMode:ae,setDraftAttachments:X,selectAssignee:hn,toggleWatcher:cn,setSelectedInitiativeId:z,toggleAssigneePicker:Ht,toggleWatcherPicker:ts,toggleScopePicker:gn,setAgentPickerQuery:Se,setScopePickerQuery:C,setAgentPickerMode:le,setScopePickerOpen:Te,handlePrimaryAction:tn,handleFilesAdded:Cn,handleRetryAttachment:Mn,openThreadPanel:en,closeThreadPanel:ys,loadThreadDetail:Tt,applyScopeLink:zn,resetComposer:bt,setComposerError:ge,setComposerNotice:ue,setLaunchWarningAccepted:Xe,pushInlineMessage:Ut,clearInlineMessages:Sn,toggleThreadSidebar:Bn,setSelectedProvider:Me,cycleProvider:_n,fileInputRef:Qe,panelHeadingRef:Ee,composerShellRef:qe}),[hn,cn,Ht,ts,gn,tn,Cn,Mn,en,ys,Tt,zn,bt,Ut,Sn,Bn,_n]);return n.jsx(Wl.Provider,{value:rs,children:n.jsx(Ul.Provider,{value:Wn,children:e})})}const of={type:"spring",stiffness:500,damping:35,mass:.5};function lf({messages:e,isStreaming:t,collapsed:s,onClick:r}){var c;const i=es(),a=o.useRef(null);o.useEffect(()=>{const d=a.current;d&&d.scrollTo({top:d.scrollHeight,behavior:"smooth"})},[e.length,(c=e[e.length-1])==null?void 0:c.body]);const l=s?e.slice(-2):e;return l.length===0?null:n.jsx(pe.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:ce("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",r&&"cursor-pointer"),children:n.jsx(yt,{initial:!1,children:l.map(d=>n.jsx(pe.div,{initial:i?!1:{opacity:0,y:8,scale:.97},animate:i?{}:{opacity:1,y:0,scale:1},transition:i?void 0:of,className:ce("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:ce("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:ce("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:ce("mt-0.5 whitespace-pre-wrap text-caption leading-relaxed",d.role==="user"&&"text-primary",d.role==="agent"&&"text-primary",d.role==="error"&&"text-rose-100"),children:[d.body,t&&d===l[l.length-1]&&d.role==="agent"&&n.jsx("span",{className:"ml-0.5 inline-block h-[14px] w-[2px] translate-y-[2px] rounded-full bg-white/50",style:{animation:"pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite"}})]})]})},d.id))})})})}function $o({open:e,onClose:t}){const s=es(),{displayedThreads:r,activeThreadId:i,activeThread:a,activeThreadSummary:l,panelLoading:c,panelError:d,scopeSaving:u,initiativeOptions:g}=Ta(),{openThreadPanel:x,closeThreadPanel:b,loadThreadDetail:h,applyScopeLink:v,panelHeadingRef:y}=Ea(),j=(a==null?void 0:a.id)??(l==null?void 0:l.id)??null,w=o.useCallback((p,_)=>{x(p,_)},[x]),k=o.useCallback(()=>{b(),t()},[b,t]);return n.jsx(yt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(pe.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:k,className:"fixed inset-0 z-[24] bg-black/30"}),n.jsxs(pe.section,{initial:s?!1:{y:"100%"},animate:s?{}:{y:0},exit:s?{}:{y:"100%"},transition:s?void 0:{duration:Pt.durationEntrance/1e3,ease:Pt.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:k,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:ce("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(ki,{icon:"inbox",headline:"No threads yet",description:"Send a message to start a conversation thread.",className:"py-6"}):n.jsx("div",{className:"space-y-1.5",children:r.map(p=>n.jsxs("button",{type:"button",onClick:_=>w(p.id,_.currentTarget),className:ce("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",i===p.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:p.lastSnippet?`"${p.lastSnippet.length>40?p.lastSnippet.slice(0,40)+"...":p.lastSnippet}"`:p.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:p.lastActivityAt,children:Mt(p.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[p.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",p.assigneeName]}),n.jsx("span",{children:p.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:ce("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Ks(p.status)),children:hi(p.status)})]})]},p.id))})}),n.jsx(yt,{initial:!1,children:i&&n.jsxs(pe.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:Pt.durationStandard/1e3,ease:Pt.easingStandard},className:"hidden min-h-0 flex-col overflow-hidden border-l border-white/[0.08] lg:flex",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2",children:[n.jsx("h4",{ref:y,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(a==null?void 0:a.title)??(l==null?void 0:l.title)??"Thread"}),n.jsx("span",{className:ce("rounded-full border px-2 py-0.5 text-micro font-semibold",Ks((l==null?void 0:l.status)??"message_only")),children:hi((l==null?void 0:l.status)??"message_only")})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:c?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):d?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:d}),j&&n.jsx("button",{type:"button",onClick:()=>void h(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(p=>n.jsx("article",{className:ce("flex",p.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:ce("max-w-[90%] rounded-xl border px-2.5 py-1.5",p.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":p.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:p.senderName??ql(p.role)}),n.jsx("time",{dateTime:p.createdAt,children:Mt(p.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:p.body})]})},p.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(p=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:ce("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Ks(zl(p.status))),children:p.status}),n.jsx("span",{children:p.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:p.requestedAt,children:Mt(p.requestedAt)})]},p.id))]})]})})]})]})]})})}function Fo(){const e=es(),{displayedThreads:t,activeThreadId:s,activeThread:r,activeThreadSummary:i,panelLoading:a,panelError:l,scopeSaving:c,initiativeOptions:d,threadSidebarOpen:u}=Ta(),{openThreadPanel:g,closeThreadPanel:x,loadThreadDetail:b,applyScopeLink:h,setComposerMode:v,toggleThreadSidebar:y,panelHeadingRef:j}=Ea(),w=(r==null?void 0:r.id)??(i==null?void 0:i.id)??null,k=o.useCallback(()=>{y()},[y]);return u?n.jsx(yt,{children:u&&n.jsxs(n.Fragment,{children:[n.jsx(pe.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15},onClick:k,className:"fixed inset-0 z-[24] bg-black/30"},"sidebar-backdrop"),n.jsxs(pe.section,{initial:e?!1:{x:"-100%"},animate:e?{}:{x:0},exit:e?{}:{x:"-100%"},transition:e?void 0:{duration:Pt.durationEntrance/1e3,ease:Pt.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:k,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(pe.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:Do,transition:Lo,onClick:()=>{k(),v("focused"),requestAnimationFrame(()=>{const p=document.getElementById("chat-dock-input");p instanceof HTMLTextAreaElement&&p.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((p,_)=>n.jsxs(pe.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:Lo,delay:e?0:Math.min(_*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:Do,onClick:U=>void g(p.id,U.currentTarget),className:ce("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===p.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:p.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:p.lastActivityAt,children:Mt(p.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:p.lastSnippet??p.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[p.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Ot,{name:p.assigneeName,hint:p.assigneeName,size:"xs"}),n.jsx("span",{children:p.assigneeName})]}),n.jsx("span",{children:p.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:ce("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Ks(p.status)),children:hi(p.status)})]})]},p.id))})}),n.jsx(yt,{initial:!1,children:s&&n.jsxs(pe.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:Pt.durationStandard/1e3,ease:Pt.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:ce("rounded-full border px-2 py-0.5 text-micro font-semibold",Ks((i==null?void 0:i.status)??"message_only")),children:hi((i==null?void 0:i.status)??"message_only")}),n.jsx("button",{type:"button",onClick:x,className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-micro text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread detail",children:"×"})]})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:a?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):l?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:l}),w&&n.jsx("button",{type:"button",onClick:()=>void b(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(p=>n.jsx("article",{className:ce("flex",p.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:ce("max-w-[90%] rounded-xl border px-2.5 py-1.5",p.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":p.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:p.senderName??ql(p.role)}),n.jsx("time",{dateTime:p.createdAt,children:Mt(p.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:p.body})]})},p.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(p=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:ce("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Ks(zl(p.status))),children:p.status}),n.jsx("span",{children:p.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:p.requestedAt,children:Mt(p.requestedAt)})]},p.id))]})]})})]},"sidebar-panel")]})}):null}const cf={type:"spring",stiffness:500,damping:30,mass:.5};function df({open:e,agents:t,query:s,activeIndex:r,onSelect:i}){const a=es(),l=o.useRef(null);o.useEffect(()=>{if(!e||!l.current)return;const u=l.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[r,e]);const c=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||c.length===0)return null;const d=c.slice(0,6);return n.jsx(yt,{children:n.jsx(pe.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:cf,className:ce("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Agent suggestions",children:n.jsx("div",{ref:l,className:"space-y-px",children:d.map((u,g)=>{const x=g===r;return n.jsxs("button",{type:"button",role:"option","aria-selected":x,"data-active":x,onClick:()=>i(u),onMouseDown:b=>b.preventDefault(),className:ce("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",x?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Ot,{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 uf={type:"spring",stiffness:500,damping:30,mass:.5};function mf({open:e,initiatives:t,query:s,activeIndex:r,onSelect:i}){const a=es(),l=o.useRef(null);o.useEffect(()=>{if(!e||!l.current)return;const u=l.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[r,e]);const c=s.length>0?t.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())):t;if(!e)return null;const d=c.slice(0,6);return n.jsx(yt,{children:n.jsx(pe.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:uf,className:ce("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Initiative scope suggestions",children:n.jsxs("div",{ref:l,className:"space-y-px",children:[n.jsx("button",{type:"button",role:"option","aria-selected":r===0,"data-active":r===0,onClick:()=>i(null),onMouseDown:u=>u.preventDefault(),className:ce("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 x=g+1===r;return n.jsx("button",{type:"button",role:"option","aria-selected":x,"data-active":x,onClick:()=>i(u),onMouseDown:b=>b.preventDefault(),className:ce("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",x?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:n.jsx("span",{className:"truncate",children:u.name})},u.id)})]})})})}function pf({open:e,mode:t,agents:s,quickAgents:r,query:i,selectedAssigneeId:a,selectedWatcherIds:l,onQueryChange:c,onSelectAssignee:d,onToggleWatcher:u,onClose:g,onSwitchMode:x,anchorRef:b}){const h=es();return n.jsx(yt,{children:e&&n.jsxs(pe.div,{initial:h?!1:{opacity:0,scale:.95,y:8},animate:h?{}:{opacity:1,scale:1,y:0},exit:h?{}:{opacity:0,scale:.95,y:8},transition:h?void 0:Pt.easingBounce,className:"absolute bottom-[calc(100%+8px)] left-0 z-30 w-[320px] rounded-xl border border-white/[0.14] bg-[#0A0E16]/98 p-2.5 shadow-[0_20px_44px_rgba(0,0,0,0.45)] backdrop-blur-xl",children:[n.jsx("div",{className:"absolute -bottom-[6px] left-4 h-0 w-0 border-l-[6px] border-r-[6px] border-t-[6px] border-l-transparent border-r-transparent border-t-white/[0.14]","aria-hidden":!0}),n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsxs("div",{className:"flex gap-1",children:[n.jsx("button",{type:"button",onClick:()=>x("assignee"),className:ce("rounded-full px-2 py-0.5 text-micro",t==="assignee"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Assignee"}),n.jsx("button",{type:"button",onClick:()=>x("watcher"),className:ce("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(v=>{const y=a===v.id;return n.jsx("button",{type:"button",onClick:()=>d(v.id),title:v.name,className:ce("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",y?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":y,"aria-label":`Select ${v.name} as assignee`,children:n.jsx(Ot,{name:v.name,hint:v.name,size:"xs"})},v.id)})}),n.jsx("input",{value:i,onChange:v=>c(v.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(v=>{const y=a===v.id,j=l.includes(v.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(v.id);return}y||u(v.id)},className:ce("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",y?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":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(Ot,{name:v.name,hint:v.name,size:"xs"}),n.jsx("span",{children:v.name})]}),n.jsx("span",{className:"text-micro",children:y?"Assignee":j?"Watcher":"Select"})]},v.id)})})]})})}const Po=24,Oo=200;function Bo(e){return e?e.startsWith("application/pdf")?"#EF4444":e.startsWith("image/")?"#A78BFA":e.includes("spreadsheet")||e.includes("csv")?"#22C55E":e.includes("presentation")?"#F97316":"#8F9AB7":"#8F9AB7"}function ff(e,t){var r;if(e!=null&&e.startsWith("application/pdf"))return"PDF";if(e!=null&&e.startsWith("image/"))return"Image";if(e!=null&&e.includes("spreadsheet")||e!=null&&e.includes("csv"))return"Sheet";if(e!=null&&e.includes("presentation"))return"Slides";const s=(r=t.split(".").pop())==null?void 0:r.toUpperCase();return s&&s.length<=5?s:"File"}function qo({icon:e,className:t}){return e==="anthropic"?n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",className:t,children:n.jsx("path",{d:"M16.5 2.3L12 21.7l-1.7-6.5L3.8 13l6.5-1.7L12 4.8l1.7 6.5 6.5 1.7-6.5 1.7L12 21.7"})}):e==="openai"?n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M12 2a7 7 0 0 1 7 7c0 2.38-1.19 4.47-3 5.74V17a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2.26C6.19 13.47 5 11.38 5 9a7 7 0 0 1 7-7z"}),n.jsx("line",{x1:"10",y1:"21",x2:"14",y2:"21"})]}):n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M12 2l2.4 7.2L22 12l-7.6 2.8L12 22l-2.4-7.2L2 12l7.6-2.8z"})})}const ya="orgx-chat-dock-collapsed";function hf(){try{return localStorage.getItem(ya)==="1"}catch{return!1}}function gf(){const e=Ta(),t=Ea(),s=es(),r=o.useRef(null),i=o.useRef(null),[a,l]=o.useState(hf),c=o.useCallback(()=>{l(q=>{const Re=!q;try{localStorage.setItem(ya,Re?"1":"0")}catch{}return Re})},[]),[d,u]=o.useState(!1),[g,x]=o.useState(!1),b=o.useRef(null),[h,v]=o.useState(!1),[y,j]=o.useState(""),[w,k]=o.useState(0),[p,_]=o.useState(-1),[U,ae]=o.useState(!1),[G,ve]=o.useState(""),[V,ee]=o.useState(0),[de,we]=o.useState(-1),{composerMode:je,draft:ge,draftAttachments:He,sending:ue,launching:ne,selectedAssigneeId:X,selectedAssignee:te,selectedWatcherIds:Ne,selectedInitiative:se,agentOptions:$,quickAssigneeOptions:H,agentPickerMode:z,agentPickerQuery:K,filteredAgentOptions:le,initiativeOptions:xe,canSend:Se,activeThreadId:Y,guidanceStatus:Te,inlineMessages:fe,displayedThreads:C,launchWarningOpen:O,launchWarningAccepted:W,selectedProvider:Z,selectedProviderDef:Fe}=e,Oe=ge.trim(),Me=fe.length>0;Oe.length>0;const T=o.useCallback(()=>{const q=r.current;if(!q)return;q.style.height="0";const Re=Math.min(Math.max(q.scrollHeight,Po),Oo);q.style.height=`${Re}px`},[]);o.useLayoutEffect(()=>{T()},[ge,T]);const F=o.useMemo(()=>{if(!h)return $;const q=y.toLowerCase();return q?$.filter(Re=>Re.name.toLowerCase().includes(q)||Re.handle.toLowerCase().includes(q)||Re.domain.toLowerCase().includes(q)||Re.role.toLowerCase().includes(q)):$},[$,h,y]),ie=o.useMemo(()=>{if(!U)return xe;const q=G.toLowerCase();return q?xe.filter(Re=>Re.name.toLowerCase().includes(q)):xe},[xe,U,G]);o.useEffect(()=>{if(b.current&&clearTimeout(b.current),fe.length<=2){x(!1);return}return x(!1),b.current=window.setTimeout(()=>{x(!0)},5e3),()=>{b.current&&clearTimeout(b.current)}},[fe.length]),o.useEffect(()=>{const q=Re=>{if((Re.metaKey||Re.ctrlKey)&&Re.key==="k"){if(Re.preventDefault(),a){l(!1);try{localStorage.setItem(ya,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var B;return(B=r.current)==null?void 0:B.focus()})}};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[t,a]);const he=o.useCallback(()=>{je==="resting"&&t.setComposerMode("focused")},[je,t]),Ie=o.useCallback(()=>{window.setTimeout(()=>{Oe.length===0&&!Me&&!h&&!U&&He.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),v(!1),ae(!1))},100)},[Oe,Me,h,U,He.length,t]),Xe=o.useCallback(q=>{const Re=q.target.value,B=q.target.selectionStart??Re.length;t.setDraft(Re),(je==="resting"||je==="focused")&&t.setComposerMode("composing");const Q=Re.slice(0,B),_e=Q.match(/@(\w*)$/);if(_e){v(!0),j(_e[1]),k(0),_(B-_e[0].length),ae(!1);return}const Le=Q.match(/#(\w*)$/);if(Le){ae(!0),ve(Le[1]),ee(0),we(B-Le[0].length),v(!1);return}h&&v(!1),U&&ae(!1)},[je,t,h,U]),Qe=o.useCallback(q=>{var _e;const Re=ge.slice(0,p),B=ge.slice(((_e=r.current)==null?void 0:_e.selectionStart)??ge.length),Q=`${Re}@${q.name} ${B}`;t.setDraft(Q),t.selectAssignee(q.id),v(!1),j(""),requestAnimationFrame(()=>{if(r.current){const Le=Re.length+q.name.length+2;r.current.setSelectionRange(Le,Le),r.current.focus()}})},[ge,p,t]),Ee=o.useCallback(q=>{var Q;const Re=ge.slice(0,de),B=ge.slice(((Q=r.current)==null?void 0:Q.selectionStart)??ge.length);if(q){const _e=`${Re}#${q.name} ${B}`;t.setDraft(_e),t.setSelectedInitiativeId(q.id),requestAnimationFrame(()=>{if(r.current){const Le=Re.length+q.name.length+2;r.current.setSelectionRange(Le,Le),r.current.focus()}})}else{const _e=`${Re}${B}`;t.setDraft(_e),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{r.current&&(r.current.setSelectionRange(Re.length,Re.length),r.current.focus())})}ae(!1),ve("")},[ge,de,t]),et=o.useCallback(q=>{if(h&&F.length>0){if(q.key==="ArrowDown"){q.preventDefault(),k(Re=>(Re+1)%F.length);return}if(q.key==="ArrowUp"){q.preventDefault(),k(Re=>(Re-1+F.length)%F.length);return}if(q.key==="Enter"||q.key==="Tab"){q.preventDefault(),Qe(F[w]);return}if(q.key==="Escape"){q.preventDefault(),v(!1);return}}if(U){const Re=ie.length+1;if(q.key==="ArrowDown"){q.preventDefault(),ee(B=>(B+1)%Re);return}if(q.key==="ArrowUp"){q.preventDefault(),ee(B=>(B-1+Re)%Re);return}if(q.key==="Enter"||q.key==="Tab"){q.preventDefault(),Ee(V===0?null:ie[V-1]);return}if(q.key==="Escape"){q.preventDefault(),ae(!1);return}}if(q.key==="Enter"&&!q.shiftKey){q.preventDefault(),t.handlePrimaryAction();return}q.key==="Escape"&&(q.preventDefault(),z?t.setAgentPickerMode(null):Me?t.clearInlineMessages():(t.setComposerMode("resting"),q.target.blur()))},[t,z,Me,h,F,w,Qe,U,ie,V,Ee]),qe=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),pt=ue||ne?n.jsx("svg",{className:"h-4 w-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"52",strokeDashoffset:"16",strokeLinecap:"round"})}):n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),n.jsx("polyline",{points:"5 12 12 5 19 12"})]}),at=(je==="reviewing"||Me)&&fe.length>0,Ze=Te==="submitted"||Te==="streaming",ye=o.useRef(fe.length),[We,Ae]=o.useState(0);return o.useEffect(()=>{if(!a){ye.current=fe.length,Ae(0);return}const q=fe.length-ye.current;q>0&&Ae(q)},[a,fe.length]),a?n.jsxs(n.Fragment,{children:[n.jsx($o,{open:d,onClose:()=>u(!1)}),n.jsx(Fo,{}),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(pe.button,{type:"button",onClick:()=>{c(),requestAnimationFrame(()=>{var q;return(q=r.current)==null?void 0:q.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:ce("relative inline-flex h-12 w-12 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16]/90 text-primary backdrop-blur-xl","shadow-[0_8px_32px_rgba(0,0,0,0.4),inset_0_1px_0_rgba(255,255,255,0.05)]","hover:border-white/[0.22] hover:bg-[#0A0E16]"),"aria-label":"Open chat",children:[n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx(yt,{children:We>0&&n.jsx(pe.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:ce("absolute -right-1 -top-1 flex h-5 min-w-[20px] items-center justify-center rounded-full","bg-lime px-1 text-[10px] font-bold text-[#0A0E16]"),children:We>9?"9+":We},"unread")}),Y&&We===0&&n.jsx("span",{className:"absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full border-2 border-[#0A0E16] bg-lime"})]})})]}):n.jsxs(n.Fragment,{children:[n.jsx($o,{open:d,onClose:()=>u(!1)}),n.jsx(Fo,{}),n.jsxs("div",{ref:q=>{t.composerShellRef.current=q},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(yt,{children:O&&n.jsxs(pe.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:q=>t.setLaunchWarningAccepted(q.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(pf,{open:z!==null,mode:z??"assignee",agents:le,quickAgents:H,query:K,selectedAssigneeId:X,selectedWatcherIds:Ne,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:i})}),n.jsxs(pe.section,{"data-testid":"chat-dock","data-state":je,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:Pt.durationEntrance/1e3,ease:Pt.easingEntrance},className:ce("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",je!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:c,className:ce("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:q=>{t.fileInputRef.current=q},type:"file",multiple:!0,className:"hidden",onChange:q=>{t.handleFilesAdded(q.target.files),q.currentTarget.value=""}}),n.jsx(yt,{children:at&&n.jsx(lf,{messages:fe,isStreaming:Ze,collapsed:g,onClick:qe})}),n.jsxs("div",{className:"relative",children:[n.jsx(df,{open:h,agents:F,query:y,activeIndex:w,anchorRect:null,onSelect:Qe,onClose:()=>v(!1)}),n.jsx(mf,{open:U,initiatives:ie,query:G,activeIndex:V,onSelect:Ee,onClose:()=>ae(!1)})]}),n.jsx(yt,{initial:!1,children:He.length>0&&n.jsx(pe.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:He.map(q=>n.jsxs("div",{className:ce("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",q.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:`${Bo(q.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:Bo(q.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:q.name}),n.jsxs("p",{className:"text-micro text-muted",children:[ff(q.mimeType,q.name),q.sizeBytes?` · ${Qp(q.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments(Re=>Re.filter(B=>B.id!==q.id)),className:ce("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 ${q.name}`,children:"×"}),q.status!=="ready"&&q.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]"})}),q.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(q.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"})]},q.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var q;return(q=t.fileInputRef.current)==null?void 0:q.click()},className:ce("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(pe.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:ce("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",Z==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":Z==="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: ${Fe.label}. Click to switch.`,"aria-label":`Current provider: ${Fe.label}. Click to cycle.`,children:[n.jsx(qo,{icon:Fe.icon}),n.jsx("span",{children:Fe.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:ge,onFocus:he,onBlur:Ie,onChange:Xe,onKeyDown:et,placeholder:"Ask anything",rows:1,className:ce("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:Po,maxHeight:Oo,overflowY:"auto"},"aria-expanded":je!=="resting"})]}),C.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:ce("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(pe.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!Se,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:ce("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",Se?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:te?`Send to ${te.name} via ${Fe.shortLabel}`:`Send via ${Fe.shortLabel}`,"aria-label":te?`Send to ${te.name} via ${Fe.shortLabel}`:`Send message via ${Fe.shortLabel}`,children:pt})]}),n.jsx(yt,{children:(te||se)&&je!=="resting"&&n.jsxs(pe.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:[te&&n.jsxs("button",{ref:q=>{i.current=q},type:"button",onClick:t.toggleWatcherPicker,className:ce("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(Ot,{name:te.name,hint:te.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",te.name]}),te.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),se&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",se.name]}),Z!=="auto"&&n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro",style:{color:Fe.accent},children:[n.jsx(qo,{icon:Fe.icon}),Fe.shortLabel]})]})})]})]})]})}const Qi=50,xf=50,br=20,zo=3600,Wo=12e3,Vr={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"},Uo=["live","24h","7d","all"];function Ho(e){if(e==="custom"||e==="all")return null;const t=Uo.indexOf(e);return t<0?null:Uo[t+1]??null}function Vo(e,t){if(e.size!==t.size)return!1;for(const[s,r]of e){const i=t.get(s);if(!i)return!1;for(const a of Object.keys(r))if(r[a]!==i[a])return!1}return!0}function yf(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function Ko(e){return e==="codex"||e==="openai"||e==="anthropic"||e==="openclaw"}function ps(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Kr(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Gr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Ji(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function Go(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function _s(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ra(e){if(!e)return;let t={...e},s=_s(t.metadata),r=0;for(;s&&r<4;)t={...t,...s},s=_s(s.metadata),r+=1;return t}function wt(e){const t=_s(e==null?void 0:e.metadata);return Ra(t)}function bf(e){const t=Ra(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 ba(e){if(e.runId)return e.runId;const t=wt(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 Nr(e){const t=wt(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 Xo(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const wf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vf=/^[0-9a-f]{20,}$/i,Hl=/^\d+$/,Vl=/^(user|usr|clerk)_[a-z0-9]+$/i;function Zt(e){if(!e)return null;const t=e.trim();return!t||wf.test(t)||vf.test(t)||Hl.test(t)||Vl.test(t)?null:t}const kf=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function jf(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return kf.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function Qo(e,t,s){if(!e)return null;let r=null;for(const a of t){const l=Zt(Xo(e[a]));if(l){r=l;break}}let i=null;for(const a of s){const l=Zt(Xo(e[a]));if(l){i=l;break}}return!r&&!i?null:{id:r,name:i,label:i??r??"OrgX"}}function Nf(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 l=((s=e.name)==null?void 0:s.trim().toLowerCase())??null,c=((r=t.name)==null?void 0:r.trim().toLowerCase())??null;return l&&c&&l!==c?!1:["unknown","system","agent","none","null","undefined"].includes(i)?!!(l&&c&&l===c):!0}}return!e.name||!t.name?!1:e.name.trim().toLowerCase()===t.name.trim().toLowerCase()}function Jo(e){const t=wt(e),s=Nr(e),r=yi(e),i=Zt(s.agentId),a=Zt(s.agentName),l=Zt(e.requesterAgentId??null),c=Zt(e.requesterAgentName??null),u=(l||c?{id:l,name:c,label:c??l??"OrgX"}:null)??Qo(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=Zt(e.executorAgentId??null),x=Zt(e.executorAgentName??null),h=(g||x?{id:g,name:x,label:x??g??"Agent"}:null)??Qo(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&&h?Nf(u,h)?{requester:u,executor:h,mode:"single",primaryLabel:h.label,subtitle:h.label}:{requester:u,executor:h,mode:"handoff",primaryLabel:h.label,subtitle:`${u.label} handed off to ${h.label}`}:u&&!h?{requester:u,executor:null,mode:"requested",primaryLabel:u.label,subtitle:`${u.label} requested a run`}:!u&&h?{requester:null,executor:h,mode:"single",primaryLabel:h.label,subtitle:h.label}:r.isSystem?{requester:null,executor:null,mode:"system",primaryLabel:"OrgX",subtitle:"OrgX"}:{requester:null,executor:null,mode:"system",primaryLabel:Zt(e.agentName??null)??Zt(e.agentId??null)??"OrgX",subtitle:Zt(e.agentName??null)??Zt(e.agentId??null)??"OrgX"}}function Yi(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}function wr(e){const t=wt(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 Zi(e){const t=wt(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 Yo=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 Xr(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function If(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 Af(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 Sf(e){const t=wt(e),s=Xr(e.kind)??Xr(t==null?void 0:t.activity_bucket)??Xr(t==null?void 0:t.activityBucket)??Xr(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=Af(t),i=e.decisionRequired===!0||If(t,["decision_required","decisionRequired"])===!0,a=Us(t,["artifacts","artifact_count","artifactCount"])??0,l=Us(t,["decisions","decision_count","decisionCount"])??0,c=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||c>0?"decision":a>0?"artifact":l>0||d>0?"decision":"message";if(r==="auto_continue_stopped"){const g=An(nt(t,["stop_reason","stopReason"])??"");if(g==="blocked"||g==="error")return"decision"}return r&&Yo.has(r)?Yo.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||l>0||c>0||d>0?"decision":"message"}function gi(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 _f(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 Cf(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 ea(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function ta(e){return e==="completed"?D.lime:e==="needs_input"?D.amber:e==="issue"?D.red:D.teal}function Mf(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 Zo(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function fs(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 Jn(e){const t=fs(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=fs(s.count??s.total??s.size);if(r!==null)return Math.max(0,Math.round(r))}return null}function Tf(e){const t=fs(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 Ef(e,t){for(const s of t){const r=Tf(e[s]);if(r!==null)return r}return null}function Qr(e,t){const s=[],r=new Set,i=a=>{if(typeof a!="string")return;const l=a.trim();!l||r.has(l)||(r.add(l),s.push(l))};for(const a of t){const l=e[a];if(Array.isArray(l)){for(const c of l)i(c);continue}i(l)}return s}function Kl(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=Qr(e,["blocking_decision_ids","blockingDecisionIds"]),s=Qr(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),r=Qr(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 l of a){if(!l||typeof l!="object"||Array.isArray(l))continue;const c=l,d=Qr(c,["id","decision_id","decisionId"]),u=c.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 Gl(e){if(!e)return null;const t=wt(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=Nr(e),l=(typeof t.requested_by_agent_id=="string"&&t.requested_by_agent_id.trim().length>0?t.requested_by_agent_id.trim():null)??(typeof t.requestedByAgentId=="string"&&t.requestedByAgentId.trim().length>0?t.requestedByAgentId.trim():null)??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null)??a.agentId,c=(typeof t.requested_by_agent_name=="string"&&t.requested_by_agent_name.trim().length>0?t.requested_by_agent_name.trim():null)??(typeof t.requestedByAgentName=="string"&&t.requestedByAgentName.trim().length>0?t.requestedByAgentName.trim():null)??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??a.agentName,d=(typeof t.source_client=="string"&&t.source_client.trim().length>0?t.source_client.trim():null)??(typeof t.sourceClient=="string"&&t.sourceClient.trim().length>0?t.sourceClient.trim():null)??(typeof e.runtimeClient=="string"&&e.runtimeClient.trim().length>0?e.runtimeClient.trim():null),u=t.required_skills??t.requiredSkills,g=Array.isArray(u)?u.filter(W=>typeof W=="string"&&W.trim().length>0):[],x=Pf(g),b=t.task_ids??t.taskIds,h=Array.isArray(b)?b.filter(W=>typeof W=="string"&&W.trim().length>0):[],v=t.milestone_ids??t.milestoneIds,y=Array.isArray(v)?v.filter(W=>typeof W=="string"&&W.trim().length>0):[],j=nt(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),w=nt(t,["initiative_title","initiativeTitle"]),k=nt(t,["initiative_status","initiativeStatus"]),p=wr(e),_=nt(t,["workstream_title","workstreamTitle"]),U=nt(t,["workstream_status","workstreamStatus"]),ae=nt(t,["task_title","taskTitle"]),G=nt(t,["milestone_title","milestoneTitle"]),ve=nt(t,["domain"]),V=nt(t,["phase","slice_phase","slicePhase"]),ee=nt(t,["next_step","nextStep"]),de=Ef(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),we=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,je=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,ge=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,He=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,ue=typeof t.error=="string"?t.error:null,ne=Jn(t.artifacts??t.artifact_count??t.artifactCount),X=Jn(t.decisions??t.decision_count??t.decisionCount),te=Kl(t),Ne=t.decisions_needed??t.decisionsNeeded;let se=Jn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),$=Jn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((se===null||$===null)&&Array.isArray(Ne)){let W=0,Z=0;for(const Fe of Ne){if(!Fe||typeof Fe!="object"||Array.isArray(Fe))continue;Fe.blocking===!1?Z+=1:W+=1}se===null&&(se=W),$===null&&($=Z)}se===null&&X!==null&&e.decisionRequired===!0&&(se=X>0?X:1),$===null&&X!==null&&se!==null&&($=Math.max(0,X-se)),se===null&&X!==null&&$!==null&&(se=Math.max(0,X-$));const H=Jn(t.status_updates_applied??t.statusUpdatesApplied),z=Jn(t.task_updates??t.taskUpdates),K=Jn(t.milestone_updates??t.milestoneUpdates),le=H??(z!==null||K!==null?(z??0)+(K??0):null),xe=Jn(t.status_updates_buffered??t.statusUpdatesBuffered),Se=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,Y=fs(t.token_budget??t.tokenBudget),Te=fs(t.tokens_used??t.tokensUsed),fe=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)??x,O=x&&!a.agentName?null:fe;return{event:s,agentId:O,agentName:C,requesterAgentId:l,requesterAgentName:c,dispatcherClient:d,initiativeId:j,domain:ve,phase:V,progressPct:de,nextStep:ee,requiredSkills:g,initiativeStatus:k,initiativeTitle:w,workstreamId:p,workstreamStatus:U,workstreamTitle:_,taskTitle:ae,milestoneTitle:G,taskIds:h,milestoneIds:y,parsedStatus:we,hasOutput:je,artifacts:ne,decisions:X,blockingDecisions:se,nonBlockingDecisions:$,decisionIds:te.decisionIds,blockingDecisionIds:te.blockingDecisionIds,nonBlockingDecisionIds:te.nonBlockingDecisionIds,statusUpdatesApplied:le,statusUpdatesBuffered:xe,stopReason:Se,tokenBudget:Y,tokensUsed:Te,logPath:ge,outputPath:He,error:ue}}function na(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function Rf(e){const t=Ra(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,l=(typeof s.orgx_plugin_version=="string"?s.orgx_plugin_version:null)??(typeof(i==null?void 0:i.plugin_version)=="string"?i.plugin_version:null),c=(typeof s.skill_pack_name=="string"?s.skill_pack_name:null)??(typeof(a==null?void 0:a.name)=="string"?a.name:null),d=(typeof s.skill_pack_version=="string"?s.skill_pack_version:null)??(typeof(a==null?void 0:a.version)=="string"?a.version:null),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),x=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,b=typeof s.kickoff_context_source=="string"?s.kickoff_context_source:null,h=typeof s.spawn_guard_model_tier=="string"?s.spawn_guard_model_tier:null,v=typeof s.provider=="string"?s.provider:null,y=typeof s.model=="string"?s.model:null,j=typeof s.domain=="string"?s.domain:null,w=s.required_skills??s.requiredSkills,k=Array.isArray(w)?w.filter(_=>typeof _=="string"&&_.trim().length>0):[];return!!l||!!(c||d||u)||!!x||!!(h||v||y||j)||k.length>0?{pluginVersion:l,skillPack:c||d||u||g?{name:c,version:d,checksum:u,source:g}:null,kickoffContextHash:x,kickoffContextSource:b,modelTier:h,provider:v,model:y,domain:j,requiredSkills:k}:null}function Xl(e){if(!e)return null;const t=wt(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 Lf(e){const t=wt(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),r=Xl(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 l=r.value;if(typeof l=="string")a=l.length>80?l.slice(0,80)+"…":l;else if(Array.isArray(l))a=`${l.length} item${l.length===1?"":"s"}`;else if(l&&typeof l=="object"){const c=Object.keys(l);a=c.length<=4?c.join(", "):`${c.length} fields`}}return{label:i,preview:a,hasRegisteredId:s}}function Df(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 Ql(e){const t=wt(e);if(!t)return[];const s=[],r=new Set,i=(l,c)=>{if(typeof c!="string")return;const d=c.trim();if(!d||!Df(d))return;const u=`${l}:${d}`;r.has(u)||(r.add(u),s.push({key:l,path:d}))},a=(l,c="",d=0)=>{if(!(d>2))for(const[u,g]of Object.entries(l)){const x=c?`${c}.${u}`:u,b=u.toLowerCase();if(b.includes("path")||b==="url"||b==="uri"||b.endsWith("url")||b.endsWith("_file")||b.endsWith("file")||b.includes("artifact"))if(Array.isArray(g))for(const v of g)i(x,v);else i(x,g);g&&typeof g=="object"&&!Array.isArray(g)&&a(g,x,d+1)}};return a(t),s}function nt(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 vr(e,t){if(typeof e!="string")return null;const s=e.trim();if(!s)return null;const r=typeof t=="string"?t.trim().toLowerCase():"";return r&&s.toLowerCase()===r||On(s)?null:s}function Jr(e){for(const t of e){const s=vr(t.value,t.idHint);if(s)return s}return null}function $f(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 Ff(e,t){if(!e)return null;const s=wt(e);if(!s)return null;const r=nt(s,["event","event_name","eventName"]),i=_s(s.spawn_guard),a=_s(i==null?void 0:i.checks),l=_s((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),c=nt(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=$f(c),u=fs(l==null?void 0:l.current)??d.domainCurrent,g=fs(l==null?void 0:l.max)??d.domainMax,x=d.totalCurrent,b=d.totalMax,h=typeof(l==null?void 0:l.passed)=="boolean"?l.passed:null,v=((r==null?void 0:r.includes("rate_limited"))??!1)||!!(c&&/rate limit/i.test(c))||h===!1;return!((r==null?void 0:r.includes("spawn_guard"))??!1)&&!v&&!i&&!c?null:{event:r,blockedReason:c,domain:nt(s,["domain"])??nt(i,["domain","task_domain"]),modelTier:nt(s,["spawn_guard_model_tier","model_tier"])??nt(i,["modelTier","model_tier"]),domainCurrent:u,domainMax:g,totalCurrent:x,totalMax:b,retryAt:nt(s,["next_retry_at","nextRetryAt"]),retryInMs:fs(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:v}}function Pf(e){var r;if(e.length!==1)return null;const t=(r=e[0])==null?void 0:r.trim();if(!t)return null;const s={"orgx-marketing-agent":"OrgX Marketing","orgx-engineering-agent":"OrgX Engineering","orgx-design-agent":"OrgX Design","orgx-product-agent":"OrgX Product","orgx-sales-agent":"OrgX Sales","orgx-operations-agent":"OrgX Operations","orgx-orchestrator-agent":"OrgX Orchestrator"};if(s[t])return s[t];if(t.endsWith("-agent")){const i=t.replace(/^orgx-/,"").replace(/-agent$/,"").trim();return i.length===0?null:`OrgX ${lt(i)}`}return null}function 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 sa(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,l=r&&a&&Of(r)?a:r??a;if(l)return jr(l);if(!i)return"OrgX";const c=i.toLowerCase();return c==="main"||c==="system"||c==="unknown"||c==="runtime"||c==="orgx"||c==="openclaw"||c==="null"||c==="undefined"?jr(i):kr.test(i)||Bf.test(i)||Hl.test(i)||Vl.test(i)?"OrgX":jr(i)}const kr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bf=/^[0-9a-f]{20,}$/i,qf=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function xi(e){const t=new Set;if(!e)return t;for(const a of[e.title,e.summary,e.description])if(typeof a=="string")for(const l of a.match(qf)??[]){const c=l.trim().toLowerCase();kr.test(c)&&t.add(c)}typeof e.runId=="string"&&kr.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=wt(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 l=s[a];if(typeof l=="string"){const c=l.trim().toLowerCase();kr.test(c)&&t.add(c)}}for(const a of i){const l=s[a];if(Array.isArray(l))for(const c of l){if(typeof c!="string")continue;const d=c.trim().toLowerCase();kr.test(d)&&t.add(d)}}return t}function zf(e){if(!e)return[];const t=wt(e);return Kl(t).decisionIds}function Wf(e,t,s){if(!e)return[];const r=wt(e),i=nt(r,["workstream_id","workstreamId"]),a=nt(r,["initiative_id","initiativeId"]),l=xi(e);if(!i&&!a&&l.size===0)return[];const c=ps(e.timestamp),d=[];for(const b of t){if(b.id===e.id)continue;const h=wt(b);if(!h)continue;const v=nt(h,["workstream_id","workstreamId"]),y=nt(h,["initiative_id","initiativeId"]),j=xi(b),w=l.size>0&&Array.from(l).some(G=>j.has(G)),k=!!i&&!!v&&i===v;if(!w&&!k&&!(!!a&&!!y&&a===y))continue;const _=Ql(b).filter(G=>!s.has(G.path));if(_.length===0)continue;const U=Math.abs(ps(b.timestamp)-c);if(!w&&U>7200*1e3)continue;const ae=w?0:k?1:2;!w&&U>1200*1e3||d.push({priority:ae,delta:U,evidence:_})}if(d.length===0)return[];d.sort((b,h)=>b.priority!==h.priority?b.priority-h.priority:b.delta-h.delta);const u=[],g=new Set(s),x=d[0].priority;for(const b of d){if(b.priority!==x)break;for(const h of b.evidence)if(!g.has(h.path)&&(g.add(h.path),u.push({key:`related.${h.key}`,path:h.path}),u.length>=8))return u}return u}function Uf(e,t){if(!e)return null;const s=wt(e),r=nt(s,["workstream_id","workstreamId"]),i=nt(s,["initiative_id","initiativeId"]),a=xi(e);if(!r&&!i&&a.size===0)return null;const l=ps(e.timestamp),c=[];for(const u of t){if(u.id===e.id)continue;const g=Gl(u);if(!g)continue;const x=wt(u);if(!x)continue;const b=nt(x,["workstream_id","workstreamId"]),h=nt(x,["initiative_id","initiativeId"]),v=xi(u),y=a.size>0&&Array.from(a).some(U=>v.has(U)),j=!!r&&!!b&&r===b;if(!y&&!j&&!(!!i&&!!h&&i===h))continue;const k=Math.abs(ps(u.timestamp)-l);if(!y&&k>1200*1e3)continue;const p=y?"shared_id":j?"workstream":"initiative",_=p==="shared_id"?0:p==="workstream"?1:2;c.push({priority:_,delta:k,relation:p,detail:g})}if(c.length===0)return null;c.sort((u,g)=>u.priority!==g.priority?u.priority-g.priority:u.delta-g.delta);const d=c[0];return{detail:d.detail,relation:d.relation}}function An(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function ji(e){const t=An(e);return["done","complete","completed","stopped","success"].includes(t)}function Hf(e){const t=An(e.parsedStatus),s=An(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":ji(t)||e.stopReason==="completed"?"positive":"neutral"}function Vf(e){if(ji(e.parsedStatus)||e.stopReason==="completed")return 100;const t=An(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 Jl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function Kf(e,t){if(!e&&t===null)return null;const s=e?Hf(e):"neutral",r=c=>c>=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 c=Jl(e.progressPct)??0,d=r(c);return{pct:c,source:"metadata",label:d?i:"Progress",tone:s,terminalStop:d}}if(t!==null){const c=r(t);return{pct:t,source:"session",label:c?i:"Progress",tone:s,terminalStop:c}}if(!e)return null;const a=Vf(e);if(a===null)return null;const l=r(a);return{pct:a,source:"lifecycle",label:l?i:"Progress",tone:s,terminalStop:l}}function Gf(e,t,s,r=null){var w;const i=wt(e),a=An(nt(i,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),l=An(e.state??e.phase??e.kind??e.type),c=An((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??l),d=An((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=nt(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),x=Math.max(0,(s==null?void 0:s.blockingDecisions)??(t==null?void 0:t.blockingDecisions)??(e.decisionRequired===!0?Math.max(1,g):0)),b=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,g-x)),h=e.decisionRequired===!0||e.type==="decision_requested"||x>0||c==="needs_decision"&&b===0,v=e.type==="run_completed"||e.type==="milestone_completed"||ji(c)||d==="completed",y=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:h?"Needs decision":"Blocked",summary:Rt(e.title)??(h?"Autopilot is paused pending a decision.":"Autopilot is blocked and needs intervention."),hint:h?"Open the Decisions panel and approve the pending item to continue.":"Resolve the blocker, then restart autopilot.",tone:h?"warning":"critical"};if(d==="error")return{label:"Error",summary: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 k=String((i==null?void 0:i.old_state)??""),p=String((i==null?void 0:i.new_state)??""),_=String((i==null?void 0:i.reason)??"");return p==="running"?{label:"Autopilot activated",summary:`State changed from ${k} to running.`,hint:"Autopilot will dispatch work from the Next Up queue.",tone:"positive"}:p==="blocked"||p==="error"?{label:p==="error"?"Autopilot error":"Autopilot blocked",summary:`State changed from ${k} to ${p}${_?`: ${_}`:""}.`,hint:"Review the triage queue for actionable items.",tone:"critical"}:{label:"Autopilot state change",summary:`${k} → ${p}${_?` (${_})`:""}.`,hint:null,tone:"neutral"}}if(y)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:b>0?"Completed + follow-up":"Completed",summary:b>0?`Execution completed. ${b} non-blocking decision${b===1?"":"s"} were logged for optional follow-up.`:r.sentence,hint:r.nextAction,tone:"positive"};if(r.status==="failed")return{label:"Failed",summary:u?Rt(u)??r.sentence:r.sentence,hint:r.nextAction,tone:"critical"};if(r.status==="needs_attention"){const k=h||(((w=r.nextAction)==null?void 0:w.toLowerCase().includes("decision"))??!1);return{label:k?"Needs decision":"Needs attention",summary:r.sentence,hint:r.nextAction??(k?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:k?"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"||c==="blocked"||c==="failed"||c==="error"||d==="blocked"||d==="error"?{label:"Blocked",summary:u?Rt(u)??"Execution is blocked.":"Execution is blocked and needs intervention.",hint:h?"Resolve the pending decision, then resume the session.":"Open the session and retry after fixing the blocker.",tone:"critical"}:h?{label:"Needs decision",summary:"Execution paused pending approval or a human choice.",hint:"Review the Decisions panel and approve the pending item to continue.",tone:"warning"}:v&&b>0?{label:"Completed + follow-up",summary:`Execution completed. ${b} non-blocking decision${b===1?"":"s"} were logged for optional follow-up.`,hint:"Review the decision for optimization, but no approval is required to mark this slice complete.",tone:"positive"}:e.type==="decision_resolved"?{label:"Decision resolved",summary:"A pending decision was completed.",hint:null,tone:"positive"}:v?{label:"Completed",summary:"Execution completed successfully.",hint:null,tone:"positive"}:e.type==="run_started"||l==="running"||l==="in_progress"?{label:"In progress",summary:"Execution is actively running.",hint:null,tone:"neutral"}:null}function Yl(e){if(typeof e=="string")return n.jsx(pi,{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:Yl(t)},`artifact-list-${s}`))});if(e&&typeof e=="object"){const t=Object.entries(e);return n.jsx("dl",{className:"space-y-1.5",children:t.map(([s,r])=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("dt",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:lt(s)}),n.jsx("dd",{className:"mt-1 text-body text-primary",children:typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`${r.length} item${r.length===1?"":"s"}`:r&&typeof r=="object"?`${Object.keys(r).length} field${Object.keys(r).length===1?"":"s"}`:"—"})]},s))})}return n.jsx("p",{className:"text-body text-secondary",children:"No artifact payload."})}function Rt(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=Ar(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:lt(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 Qf(e){return Xf.some(t=>t.test(e))}function yi(e){const t=e.title??"";return Qf(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:lt(t)||lt(gi(e.type)),isSystem:!1}}const Jf=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 Ir(e){const t=wt(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)??"",l=/(changeset[\._ ]?(applied|replayed)|sync[\._ ]?applied|sentinel[\._ ]?(changeset|decision)[\._ ]?applied)/i.test(a),c=t.replayed===!0,d=typeof t.changeset_id=="string"&&t.changeset_id.trim().length>0||typeof t.changesetId=="string"&&t.changesetId.trim().length>0,u=/changes synced|changeset replayed|changeset applied|outbox replay/i.test(`${e.title??""} ${e.summary??""} ${e.description??""}`);return!!(s&&Jf.has(s)||l||c&&(d||u)||d&&(u||i.includes("outbox")||i.includes("replay"))||i.includes("outbox_replay")&&u)}function el(e){var d;if(!e||!Ir(e))return null;const t=wt(e),s=Jn((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=nt(t,["entity_type","entityType"])??i??(e.type==="milestone_completed"?"milestone":null),l=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",c=a?` for ${lt(a).toLowerCase()}`:"";return`${l}${c} were synced from local replay.`}function ra(e){if(!Ir(e))return null;const t=wt(e);if(!t)return null;const s=nt(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const r=nt(t,["event","event_name","eventName"])??"",i=nt(t,["changeset_id","changesetId"])??"",a=nt(t,["entity_type","entityType"])??"",l=nt(t,["entity_id","entityId"])??"",c=ba(e)??"",d=yi(e).title.trim().toLowerCase();return`fallback:${r.toLowerCase()}:${i.toLowerCase()}:${a.toLowerCase()}:${l.toLowerCase()}:${c.toLowerCase()}:${d}`}function Yf(e){if(!e)return null;const t=wt(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 tl(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 nl(e,t){const r=(Rt(t??e.summary)??Rt(e.description)??lt(e.title||gi(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(l=>tl(l).trim()).filter(l=>l.length>0&&!/^\|?[:\-| ]+\|?$/.test(l));let a=i[0]??tl(r);return a.length<24&&i.length>1&&(a=`${a} ${i[1]}`.trim()),a.length>108?`${a.slice(0,107).trimEnd()}…`:a}const Zf=o.memo(function({activity:t,sessions:s,sliceRuns:r=[],initiatives:i=[],timelineNarrative:a=[],selectedRunIds:l,selectedSessionLabel:c=null,selectedWorkstreamId:d=null,selectedWorkstreamLabel:u=null,agentFilter:g=null,timeFilterId:x="live",onTimeFilterChange:b,customTimeRange:h={startIso:null,endIso:null},onCustomTimeRangeChange:v,hasMore:y=!1,isLoadingMore:j=!1,onLoadMore:w,onClearSelection:k,onClearWorkstreamFilter:p,onClearAgentFilter:_,onFocusRunId:U,onOpenDecision:ae,requestedActivityItemId:G=null,onActivityItemRequestHandled:ve,onPlayNextUp:V,onStartAutopilot:ee,onPauseWorkstream:de,onCreateInitiative:we,onOpenMissionControl:je,onOpenSettings:ge,workspaceId:He=null,chatSnapshot:ue,onRefreshData:ne,isLoading:X=!1,onOpenNextUp:te,devMode:Ne=!1}){var Da;const se=es(),{open:$}=$l(),[H,z]=o.useState("all"),[K,le]=o.useState(!1),[xe,Se]=o.useState(!1),[Y,Te]=o.useState(""),[fe,C]=o.useState(new Set),[O,W]=o.useState({}),[Z,Fe]=o.useState("newest"),[Oe,Me]=o.useState(!1),[T,F]=o.useState(!1),[ie,he]=o.useState(Qi),[Ie,Xe]=o.useState(null),[Qe,Ee]=o.useState(null),[et,qe]=o.useState(!1),[pt,at]=o.useState(1),[Ze,ye]=o.useState("structured"),[We,Ae]=o.useState(null),[q,Re]=o.useState("feed"),[B,Q]=o.useState(null),[_e,Le]=o.useState(null),[De,Pe]=o.useState(!1),[Ce,Ke]=o.useState(null),[ot,Ge]=o.useState(null),[Nt,Je]=o.useState(!1),[Ct,Wt]=o.useState(null),[Qt,pn]=o.useState(!1),fn=o.useRef(Date.now()),xs=o.useRef(null),bt=o.useRef(null),Ut=o.useRef(null),Sn=o.useRef(null),Bn=o.useRef(null),[ct,_n]=o.useState(()=>Kr(h.startIso)),[It,Tt]=o.useState(()=>Kr(h.endIso)),[en,ys]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),qn=o.useMemo(()=>xl(x),[x]),Cn=o.useMemo(()=>Kr(h.startIso),[h.startIso]),Mn=o.useMemo(()=>Kr(h.endIso),[h.endIso]),hn=o.useMemo(()=>!ct||!It?!1:It.getTime()>=ct.getTime(),[It,ct]),cn=o.useMemo(()=>x!=="custom"?qn.label:Cn&&Mn?`${Gr(Cn)} - ${Gr(Mn)}`:"Custom range",[Mn,Cn,x,qn.label]);o.useEffect(()=>{_n(Cn),Tt(Mn)},[Mn,Cn]),o.useEffect(()=>{if(typeof window>"u")return;const f=()=>ys(window.innerWidth<=640);return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[]),o.useEffect(()=>{const N=()=>{fn.current=Date.now()};window.addEventListener("pointerdown",N),window.addEventListener("keydown",N);const I=setInterval(()=>{Date.now()-fn.current>3e5&&pn(!0)},3e4);return()=>{window.removeEventListener("pointerdown",N),window.removeEventListener("keydown",N),clearInterval(I)}},[]);const Ht=o.useMemo(()=>{const f=s.filter(M=>M.status==="completed").length,N=s.filter(M=>M.status==="blocked"||M.status==="failed").length,I=t.filter(M=>{var be;return M.type==="decision_requested"&&((be=M.metadata)==null?void 0:be.status)==="pending"}).length;return{completed:f,blocked:N,decisions:I}},[s,t]),ts=o.useMemo(()=>{const f=new Map;for(const N of s)f.set(N.runId,N.title),f.set(N.id,N.title);return f},[s]),gn=o.useMemo(()=>{const f=new Map;for(const N of s)N.status&&(f.set(N.runId,N.status),f.set(N.id,N.status));return f},[s]),zn=o.useRef(new Map),ns=o.useMemo(()=>{var N;const f=new Map;for(const I of s){const M={status:I.status??null,phase:I.phase??null,state:I.state??null,blockerCount:Array.isArray(I.blockers)?I.blockers.length:0,blockerReason:I.blockerReason??((N=I.blockerDiagnostics)==null?void 0:N.reason)??null};f.set(I.runId,M),f.set(I.id,M)}return Vo(zn.current,f)?zn.current:(zn.current=f,f)},[s]),xn=o.useRef(new Map),ss=o.useMemo(()=>{const f=new Map;for(const N of r){const I={status:N.status??null,blockingDecisions:Math.max(0,N.blockingDecisionCount??0),nonBlockingDecisions:Math.max(0,(N.decisionCount??0)-(N.blockingDecisionCount??0)),updatedEpoch:ps(N.updatedAt??N.lastEventAt??N.startedAt??null)},M=[N.runId,N.sliceRunId].filter(be=>typeof be=="string"&&be.trim().length>0).map(be=>be.trim());for(const be of M){const Ue=f.get(be);(!Ue||I.updatedEpoch>=Ue.updatedEpoch)&&f.set(be,I)}}return Vo(xn.current,f)?xn.current:(xn.current=f,f)},[r]),Dt=o.useMemo(()=>{const f=new Map;for(const N of s){const I=Jl(N.progress);I!==null&&(f.set(N.runId,I),f.set(N.id,I))}return f},[s]),yn=o.useMemo(()=>{const f=new Map;for(const N of s)!N.agentId||!N.agentName||f.set(N.agentId,N.agentName);return f},[s]),tn=o.useMemo(()=>{const f=new Map;for(const N of s){const I=N.workstreamId??null;f.set(N.runId,I),f.set(N.id,I)}return f},[s]),rs=o.useMemo(()=>{const f=new Map;for(const N of r){const I=N.workstreamId??null,M=vr(N.workstreamTitle,I);if(!M)continue;const be=[N.runId,N.sliceRunId].filter(Ue=>typeof Ue=="string"&&Ue.trim().length>0).map(Ue=>Ue.trim());for(const Ue of be)f.set(Ue,M)}return f},[r]),Wn=o.useMemo(()=>{const f=new Map;for(const N of i){const I=vr(N.name,N.id);I&&f.set(N.id,I)}return f},[i]),E=o.useMemo(()=>{const f=new Map;for(const N of i)for(const I of N.workstreams??[]){const M=vr(I.name,I.id);M&&f.set(I.id,M)}for(const N of r){const I=N.workstreamId??null;if(!I||f.has(I))continue;const M=vr(N.workstreamTitle,I);M&&f.set(I,M)}return f},[i,r]);o.useMemo(()=>{const f=[...s];return f.sort((N,I)=>{const M=ps(N.updatedAt??N.lastEventAt??N.startedAt??null);return ps(I.updatedAt??I.lastEventAt??I.startedAt??null)-M}),f},[s]);const oe=o.useMemo(()=>t.map(f=>{const N=ba(f),I=Sf(f),M=wt(f),be=N?ns.get(N)??null:null,Ue=N?ss.get(N)??null:null,st=_p({sessionStatus:(be==null?void 0:be.status)??(N?gn.get(N)??null:null),sessionPhase:(be==null?void 0:be.phase)??null,sessionState:(be==null?void 0:be.state)??null,sliceStatus:(Ue==null?void 0:Ue.status)??null,activityType:f.type,activityStatus:nt(M,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:nt(M,["stop_reason","stopReason"]),decisionRequired:f.decisionRequired??!1,blockingDecisionCount:Us(M,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Ue==null?void 0:Ue.blockingDecisions)??0,nonBlockingDecisionCount:Us(M,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Ue==null?void 0:Ue.nonBlockingDecisions)??0,blockerCount:(be==null?void 0:be.blockerCount)??0,blockerReason:(be==null?void 0:be.blockerReason)??null}),kt=Mf(I,st),dn=[f.title,f.description,f.summary,f.agentName,bf(M)].filter($n=>typeof $n=="string"&&$n.length>0).join(" ").toLowerCase(),jt=N?(ts.get(N)??N).toLowerCase():"",xt=M==null?void 0:M.scope,Gt=xt==="milestone"||xt==="workstream"?xt:void 0;return{item:f,bucket:I,userState:kt.state,userStateWhy:kt.why,canonicalProjection:st,runId:N,timestampEpoch:ps(f.timestamp),searchText:dn,runLabelSearch:jt,scopeGroupId:Gt?N??null:null,scope:Gt}}),[t,ts,ns,gn,ss]),me=o.useMemo(()=>{const f=[...oe];return f.sort((N,I)=>{const M=I.timestampEpoch-N.timestampEpoch;return M!==0?M:I.item.id.localeCompare(N.item.id)}),f},[oe]),$e=o.useMemo(()=>[...me].reverse(),[me]),ft=o.useMemo(()=>{let f=0;for(const N of oe)f=Math.max(f,N.timestampEpoch);return f<=0?!1:Date.now()-f<6e4},[oe]),ht=o.useMemo(()=>new Set(l.filter(f=>f&&f.trim().length>0)),[l]),ze=ht.size>0,Ms=o.useMemo(()=>Sr.filter(f=>["live","24h","7d","all"].includes(f.id)),[]),dt=o.useMemo(()=>{if(!ze)return null;for(const f of ht){const N=s.find(I=>I.runId===f||I.id===f);if(N)return N}return null},[ze,ht,s]),Ts=o.useMemo(()=>ze?dt!=null&&dt.runtimeProvider?{id:yf(dt.runtimeProvider)}:ms(dt==null?void 0:dt.agentId,dt==null?void 0:dt.agentName,dt==null?void 0:dt.title,dt==null?void 0:dt.lastEventSummary,dt==null?void 0:dt.runtimeClient,c):ms(),[dt,ze,c]),vt=o.useMemo(()=>g?ms(g):ms(),[g]),{filtered:gt,filteredTotal:bn,hiddenCount:Un,hiddenSyncCount:wn}=o.useMemo(()=>{const f=Z==="newest"?me:$e,N=[];let I=0,M=0;const be=new Set,Ue=Y.trim().toLowerCase();for(const jt of f){const xt=jt.runId;if(ze&&(!xt||!ht.has(xt)))continue;if(d){const jn=wr(jt.item),ar=xt?tn.get(xt)??null:null;if((jn??ar)!==d)continue}const Gt=Nr(jt.item);if(g&&Gt.agentName!==g)continue;const $n=ra(jt.item);if($n){if(be.has($n)){M+=1;continue}if(be.add($n),!K){M+=1;continue}}else if(!K&&Ir(jt.item)){M+=1;continue}H==="completed"&&jt.userState!=="completed"||H==="needs_attention"&&jt.userState!=="needs_input"&&jt.userState!=="issue"||H==="in_progress"&&jt.userState!=="in_progress"||Ue.length>0&&!`${jt.searchText} ${jt.runLabelSearch}`.includes(Ue)||(N.length<Wo?N.push(jt):I+=1)}const st=Math.min(Math.max(1,Math.min(zo,ie)),N.length),kt=N.slice(0,st),dn=N.length+I;return{filtered:kt,filteredTotal:dn,hiddenCount:Math.max(0,dn-kt.length),hiddenSyncCount:M}},[H,g,me,$e,ze,Y,ie,d,ht,tn,K,Z]),bs=o.useMemo(()=>{const f=new Map;for(const I of gt){const M=_f(I.item.timestamp),be=f.get(M);be?be.push(I):f.set(M,[I])}return Array.from(f.keys()).sort((I,M)=>{const be=Number(M)-Number(I);return Z==="newest"?be:-be}).map(I=>({key:I,label:Cf(I),items:f.get(I)??[]}))},[gt,Z]),Hn=o.useMemo(()=>bs.map(f=>{const N=new Map;for(const I of f.items){const M=yi(I.item).title.trim().toLowerCase(),be=ra(I.item),Ue=be?`${I.item.type}::sync::${be}`:`${I.item.type}::${M}`,st=N.get(Ue);st?(st.count+=1,st.firstTimestamp=Math.min(st.firstTimestamp,I.timestampEpoch),st.allItems.push(I),I.timestampEpoch>st.representative.timestampEpoch&&(st.representative=I)):N.set(Ue,{key:Ue,representative:I,count:1,firstTimestamp:I.timestampEpoch,allItems:[I]})}return{...f,clusters:Array.from(N.values())}}),[bs]),St=o.useCallback(f=>{C(N=>{const I=new Set(N);return I.has(f)?I.delete(f):I.add(f),I}),W(N=>{if(Object.prototype.hasOwnProperty.call(N,f)){const I={...N};return delete I[f],I}return{...N,[f]:br}})},[]),Tn=o.useCallback((f,N)=>{W(I=>{const M=I[f]??br,be=Math.min(N,M+br);return be===M?I:{...I,[f]:be}})},[]),is=o.useCallback(()=>{!v||!b||!ct||!It||It.getTime()<ct.getTime()||(v({startIso:ct.toISOString(),endIso:It.toISOString()}),b("custom"),F(!1))},[It,ct,v,b]),Es=o.useCallback(()=>{_n(null),Tt(null),v==null||v({startIso:null,endIso:null}),x==="custom"&&(b==null||b("live"))},[v,b,x]),vn=o.useMemo(()=>Math.min(zo,Math.min(Wo,bn)),[bn]);o.useEffect(()=>{he(Qi),C(new Set),W({})},[H,g,ze,Y,d,K,Z,x]),o.useEffect(()=>{if(!Oe)return;const f=I=>{var be;const M=I.target;M instanceof Node&&((be=xs.current)!=null&&be.contains(M)||Me(!1))},N=I=>{I.key==="Escape"&&Me(!1)};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",N),()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",N)}},[Oe]),o.useEffect(()=>{if(!T)return;const f=I=>{var be;const M=I.target;M instanceof Node&&((be=bt.current)!=null&&be.contains(M)||F(!1))},N=I=>{I.key==="Escape"&&F(!1)};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",N),()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",N)}},[T]);const kn=o.useRef(w);kn.current=w;const as=o.useRef(y);as.current=y;const Xs=o.useRef(j);Xs.current=j;const[Rs,Ni]=o.useState(!1),Qs=o.useRef(null),Vt=o.useRef(x),Ls=o.useRef(Date.now()),Js=o.useRef(!1);o.useEffect(()=>{Vt.current!==x&&(Vt.current=x,Qs.current=null,Ls.current=Date.now(),Js.current=!1)},[x]),o.useEffect(()=>{const f=Ut.current,N=Sn.current;if(!f||!N)return;const I=new IntersectionObserver(be=>{const Ue=be.some(st=>st.isIntersecting);Ni(Ue)},{root:f,rootMargin:"0px 0px 600px 0px"});I.observe(N);const M=()=>{Js.current=!0};return f.addEventListener("scroll",M,{passive:!0}),()=>{I.disconnect(),f.removeEventListener("scroll",M)}},[]),o.useEffect(()=>{var f;if(Rs){if(gt.length<vn){he(N=>Math.min(vn,Math.max(N,Qi)+xf));return}if(as.current&&!Xs.current){(f=kn.current)==null||f.call(kn);return}}},[gt.length,vn,Rs]),o.useEffect(()=>{if(!Rs||y||j||!b)return;const f=Ut.current,N=f?f.scrollHeight<=f.clientHeight+4:!1;if(!Js.current&&!N||Date.now()-Ls.current<3e3)return;const M=Ho(x);M&&Qs.current!==M&&(Qs.current=M,b(M))},[gt.length,y,j,b,Rs,x]);const En=o.useMemo(()=>Ie?gt.findIndex(f=>f.item.id===Ie):-1,[Ie,gt]),R=En>=0?gt[En]:null,Rn=o.useMemo(()=>{var N;const f=new Map;for(const I of a){const M=(N=I==null?void 0:I.sliceRunId)==null?void 0:N.trim();!M||f.has(M)||f.set(M,I)}return f},[a]),Jt=o.useMemo(()=>{if(!R)return null;const f=R.runId??ba(R.item);return f?Rn.get(f)??null:null},[R,Rn]),Ln=o.useMemo(()=>Xl((R==null?void 0:R.item)??null),[R]),Vn=o.useMemo(()=>Zi((R==null?void 0:R.item)??null),[R]),Ys=o.useMemo(()=>Gl((R==null?void 0:R.item)??null),[R]),os=o.useMemo(()=>Ys?null:Uf((R==null?void 0:R.item)??null,t),[Ys,R,t]),Ve=o.useMemo(()=>R?Jo(R.item):null,[R]),Dn=o.useMemo(()=>Ve?Ve.executor??Ve.requester:null,[Ve]),re=Ys??(os==null?void 0:os.detail)??null,Yt=o.useMemo(()=>{var f,N;return sa((re==null?void 0:re.requesterAgentName)??((f=Ve==null?void 0:Ve.requester)==null?void 0:f.name)??null,(re==null?void 0:re.requesterAgentId)??((N=Ve==null?void 0:Ve.requester)==null?void 0:N.id)??null,yn)},[re,Ve,yn]),ls=o.useMemo(()=>jf(Yt),[Yt]),Zs=o.useMemo(()=>{var N,I;const f=sa((re==null?void 0:re.agentName)??((N=Ve==null?void 0:Ve.executor)==null?void 0:N.name)??null,(re==null?void 0:re.agentId)??((I=Ve==null?void 0:Ve.executor)==null?void 0:I.id)??null,yn);return f==="—"?(Ve==null?void 0:Ve.primaryLabel)??"Codex":f},[re,Ve,yn]),Mr=o.useMemo(()=>R!=null&&R.runId?Dt.get(R.runId)??null:null,[R,Dt]),$t=o.useMemo(()=>Kf(re,Mr),[re,Mr]),L=o.useMemo(()=>{const f=re;if(!f)return null;const N=f.initiativeId??(R==null?void 0:R.item.initiativeId)??null,I=N?i.find(jn=>jn.id===N)??null:null,M=f.initiativeTitle??(I==null?void 0:I.name)??null,be=f.initiativeStatus??(I==null?void 0:I.status)??null,Ue=(I==null?void 0:I.workstreams)??[],st=Ue.length>0?Ue.length:null,kt=st!==null?Ue.filter(jn=>ji(jn.status)).length:null,dn=st&&kt!==null?Math.round(kt/st*100):null,jt=f.workstreamId??null,xt=jt&&Ue.length>0?Ue.find(jn=>jn.id===jt)??null:null,Gt=f.workstreamTitle??(xt==null?void 0:xt.name)??(jt?E.get(jt)??null:null),$n=f.workstreamStatus??(xt==null?void 0:xt.status)??null;return{initiativeId:N,initiativeTitle:M,initiativeStatus:be,totalInitiativeWorkstreams:st,doneInitiativeWorkstreams:kt,initiativeWorkstreamPct:dn,workstreamId:jt,workstreamTitle:Gt,workstreamStatus:$n,taskTitle:f.taskTitle,milestoneTitle:f.milestoneTitle,scopedTaskCount:f.taskIds.length,scopedMilestoneCount:f.milestoneIds.length,statusUpdatesApplied:f.statusUpdatesApplied,statusUpdatesBuffered:f.statusUpdatesBuffered,artifacts:f.artifacts,decisions:f.decisions,blockingDecisions:f.blockingDecisions,nonBlockingDecisions:f.nonBlockingDecisions,tokensUsed:f.tokensUsed,tokenBudget:f.tokenBudget,nextStep:f.nextStep,phase:f.phase,stopReason:f.stopReason,parsedStatus:f.parsedStatus}},[re,R,i,E]),Et=o.useMemo(()=>R?Gf(R.item,re,L?{decisions:L.decisions,blockingDecisions:L.blockingDecisions,nonBlockingDecisions:L.nonBlockingDecisions,stopReason:L.stopReason,parsedStatus:L.parsedStatus}:null,R.canonicalProjection??null):null,[re,R,L]),er=o.useMemo(()=>{if(!L)return[];const f=[];Et&&f.push({label:"Status",value:Et.label}),L.scopedTaskCount>0&&f.push({label:"Tasks",value:L.scopedTaskCount}),L.scopedMilestoneCount>0&&f.push({label:"Milestones",value:L.scopedMilestoneCount});const N=L.artifacts??0;N>0&&f.push({label:"Artifacts",value:N});const I=L.decisions??0;I>0&&f.push({label:"Decisions",value:I}),L.blockingDecisions&&L.blockingDecisions>0&&f.push({label:"Blocking",value:L.blockingDecisions,tone:"critical"}),L.stopReason&&f.push({label:"Stop reason",value:cr(L.stopReason)??lt(L.stopReason)});const M=vc(L.tokensUsed,L.tokenBudget);return M&&f.push({label:"Token usage",value:M}),f},[L,Et]),Kn=o.useMemo(()=>{const f=new Set;for(const N of zf((R==null?void 0:R.item)??null))f.add(N);for(const N of(re==null?void 0:re.decisionIds)??[])f.add(N);for(const N of(re==null?void 0:re.blockingDecisionIds)??[])f.add(N);for(const N of(re==null?void 0:re.nonBlockingDecisionIds)??[])f.add(N);return Array.from(f)},[re,R]),tr=o.useMemo(()=>ae?Kn.length>0||(R==null?void 0:R.item.decisionRequired)===!0||((L==null?void 0:L.blockingDecisions)??0)>0?!0:(Et==null?void 0:Et.label)==="Needs decision":!1,[Kn,R,L,Et,ae]),nr=o.useMemo(()=>$t?$t.tone==="positive"?D.lime:$t.tone==="warning"?D.amber:$t.tone==="critical"?D.red:D.teal:D.teal,[$t]),sr=($t==null?void 0:$t.terminalStop)===!0,Ye=o.useMemo(()=>Rf(wt((R==null?void 0:R.item)??null)),[R]),rr=o.useMemo(()=>wt((R==null?void 0:R.item)??null),[R]),m=o.useMemo(()=>Ff((R==null?void 0:R.item)??null,re),[re,R]),A=o.useMemo(()=>{if(!(m!=null&&m.retryAt))return null;const f=new Date(m.retryAt);if(!Number.isFinite(f.getTime()))return null;const N=f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),I=Mt(m.retryAt);return I?`${N} (${I})`:N},[m]),P=o.useMemo(()=>R?Nr(R.item):{agentId:null,agentName:null},[R]),S=o.useMemo(()=>Zo(_s(R==null?void 0:R.item.metadata)??void 0),[R]);o.useMemo(()=>Zo(rr),[rr]);const J=o.useMemo(()=>{const f=Ql((R==null?void 0:R.item)??null);return f.length>0?f:Wf((R==null?void 0:R.item)??null,t,new Set)},[R,t]),ke=o.useMemo(()=>J.filter((f,N,I)=>I.findIndex(M=>M.path===f.path)===N),[J]),it=o.useMemo(()=>ke.slice(0,4),[ke]),Be=o.useMemo(()=>ke.slice(4),[ke]),tt=o.useMemo(()=>{if(ke.length===0)return null;const f=ke[0];return f?na(f.path):null},[ke]),ut=o.useMemo(()=>{const f=Rt(We);if(f)return f;const N=el((R==null?void 0:R.item)??null);return N||(Rt(R==null?void 0:R.item.summary)??Rt(R==null?void 0:R.item.description))},[We,R]),At=o.useMemo(()=>R?Ir(R.item):!1,[R]),Kt=o.useMemo(()=>{if(!re||!R)return null;const f=re.initiativeId??R.item.initiativeId??null,N=re.workstreamId??wr(R.item);if(!f||!N)return null;const I=An((L==null?void 0:L.parsedStatus)??re.parsedStatus),M=An((L==null?void 0:L.stopReason)??re.stopReason),be=Math.max(0,(L==null?void 0:L.blockingDecisions)??re.blockingDecisions??(R.item.decisionRequired?1:0)),Ue=Math.max(0,(L==null?void 0:L.nonBlockingDecisions)??re.nonBlockingDecisions??0),st=I==="blocked"||I==="error"||I==="failed"||M==="blocked"||M==="error"||R.item.type==="blocker_created",kt=!st&&be===0&&Ue>0&&(I==="needs_decision"||I==="completed"||M==="completed");return!st&&!kt?null:{initiativeId:f,workstreamId:N,runId:R.runId??null,event:re.event,requestedByAgentId:re.requesterAgentId??R.item.requesterAgentId??null,requestedByAgentName:re.requesterAgentName??R.item.requesterAgentName??null,actionLabel:st?"Auto-fix in 10s":"Auto-continue in 10s",helperText:st?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:st}},[re,R,L]),Gn=o.useCallback(()=>{Xe(null)},[]),Ds=o.useCallback(async(f,N)=>{if(N){Ge(null),Ke(f);try{await N()}catch(I){Ge(I instanceof Error?I.message:"Action failed")}finally{Ke(I=>I===f?null:I)}}},[]),$s=o.useCallback(async()=>{var f;if(!(!Kt||Nt)){Je(!0),Wt(null);try{const N=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:Kt.initiativeId,workstreamId:Kt.workstreamId,runId:Kt.runId,event:Kt.event,requestedByAgentId:Kt.requestedByAgentId,requestedByAgentName:Kt.requestedByAgentName,graceMs:1e4})}),I=await N.json().catch(()=>null);if(!N.ok||(I==null?void 0:I.ok)!==!0)throw new Error((I==null?void 0:I.error)||`Request failed (${N.status})`);const M=(f=I==null?void 0:I.scheduled)!=null&&f.dueAt?new Date(I.scheduled.dueAt):null,be=M&&Number.isFinite(M.getTime())?M.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;Wt(be?`Scheduled. Auto action starts by ${be} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(N){const I=N instanceof Error?N.message:"Failed to schedule auto-fix";Wt(Lt(I)||I)}finally{Je(!1)}}},[Kt,Nt]);o.useEffect(()=>{if(!Qe)return;const f=window.setTimeout(()=>Ee(null),2e3);return()=>window.clearTimeout(f)},[Qe]),o.useEffect(()=>{Ge(null)},[H,Y,x]),o.useEffect(()=>{if(!G){Bn.current=null;return}const f=G.trim();!f||Bn.current===f||!t.some(I=>I.id===f)||(Bn.current=f,Se(!1),z("all"),Te(""),at(1),Xe(f),ve==null||ve(f))},[t,ve,G]);const Xn=o.useCallback(async(f,N)=>{if(N)try{await navigator.clipboard.writeText(N),Ee(`${f} copied`)}catch{Ee("Copy failed")}},[]);o.useEffect(()=>{ye("structured"),qe(!1),Je(!1),Wt(null)},[Ie]),o.useEffect(()=>{Ae(null),Re("feed");const f=Yf((R==null?void 0:R.item)??null);if(!f||Ft())return;const N=new URLSearchParams({turnId:f.turnId});f.sessionKey&&N.set("sessionKey",f.sessionKey),f.runId&&N.set("run",f.runId);const I=new AbortController;return fetch(`/orgx/api/live/activity/detail?${N.toString()}`,{method:"GET",signal:I.signal}).then(async M=>{var Ue;return M.ok?((Ue=(await M.json()).detail)==null?void 0:Ue.summary)??null:(M.status===404&&Re("missing"),null)}).then(M=>{typeof M=="string"&&M.trim().length>0?(Ae(M),Re("local")):Re("missing")}).catch(M=>{M instanceof DOMException&&M.name==="AbortError"||Re("missing")}),()=>I.abort()},[R]),o.useEffect(()=>{Q(null),Le(null);const f=R==null?void 0:R.item;if(!f||De)return;const N=(We??f.summary??f.description??f.title??"").trim();if(!N||Ft())return;const I=new AbortController;return fetch("/orgx/api/live/activity/headline",{method:"POST",headers:{"Content-Type":"application/json"},signal:I.signal,body:JSON.stringify({text:N,title:f.title??null,type:f.type})}).then(async M=>M.ok?await M.json():((M.status===404||M.status===405)&&Pe(!0),null)).then(M=>{const be=M==null?void 0:M.headline;typeof be=="string"&&be.trim().length>0&&(Pe(!1),Q(be.trim()),Le((M==null?void 0:M.source)??null))}).catch(M=>{M instanceof DOMException&&M.name}),()=>I.abort()},[R,We,De]);const ir=o.useCallback(f=>{var M;if(gt.length===0)return;const I=((En>=0?En:0)+f+gt.length)%gt.length;at(f),Xe(((M=gt[I])==null?void 0:M.item.id)??null)},[En,gt]);o.useEffect(()=>{Ie&&(En>=0||Xe(null))},[En,Ie]),o.useEffect(()=>{if(!Ie)return;const f=N=>{N.key==="ArrowRight"||N.key.toLowerCase()==="l"?(N.preventDefault(),ir(1)):(N.key==="ArrowLeft"||N.key.toLowerCase()==="h")&&(N.preventDefault(),ir(-1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[Ie,ir]);const Tr=ht.size===1,Ii=Tr?[...ht][0]:null,Zl=Ii?s.find(f=>f.runId===Ii||f.id===Ii)??null:null,Ai=o.useMemo(()=>{if(!Tr)return[];const f=[],N=new Set;for(const I of oe){if(!I.runId||!ht.has(I.runId))continue;const M=ra(I.item);if(M){if(N.has(M)||(N.add(M),!K))continue}else if(!K&&Ir(I.item))continue;f.push(I.item)}return f},[Tr,oe,ht,K]),La=!se&>.length<=160,Fs=(f,N,I)=>{const M=f.item,be=I??M.id,Ue=Nr(M),st=Jo(M),kt=st.executor??st.requester,dn=sa(Zt((kt==null?void 0:kt.name)??st.primaryLabel??M.agentName??Ue.agentName??null),Zt((kt==null?void 0:kt.id)??M.agentId??Ue.agentId??null),yn)||"OrgX",jt=ta(f.userState),xt=Z==="newest"&&N<2,Gt=f.runId,$n=el(M),{title:jn}=yi(M),ar=$n??Rt(M.summary),Er=Rt(M.description),$a=nl(M,ar??Er??null),Fa=wt(M),Pa=Jr([{value:nt(Fa,["initiative_title","initiativeTitle"]),idHint:M.initiativeId},{value:M.initiativeId?Wn.get(M.initiativeId)??null:null,idHint:M.initiativeId}]),or=wr(M)??(Gt?tn.get(Gt)??null:null),Oa=Jr([{value:nt(Fa,["workstream_title","workstreamTitle"]),idHint:or},{value:or?E.get(or)??null:null,idHint:or},{value:Gt?rs.get(Gt)??null:null,idHint:or}]),ec=[Pa,Oa].filter(Boolean).join(" > ")||Pa||Oa||lt(M.type),tc=ea(f.userState),nc=new Date(M.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),sc=Mt(M.timestamp),rc=f.bucket==="artifact"?Lf(M):null;return n.jsx(Up,{renderKey:be,displayTitle:jn,headline:$a,contextLabel:ec,detailText:(ar??Er)!==$a?ar??Er:null,displayAgentName:dn,railColor:jt,userStateLabel:tc,userStateWhy:f.userStateWhy,relativeTime:sc,timeLabel:nc,isRecent:xt,enableMotion:La,onOpen:()=>{at(1),Xe(M.id)},ariaLabel:`Open activity details for ${jn||gi(M.type)}`,artifactSnippet:rc},be)};return n.jsx(af,{sessions:s,initiatives:i??[],workspaceId:He??null,query:Y,statusFilter:H,sortOrder:Z,timeFilterId:x,customTimeRange:h,snapshot:ue,onRequestRefresh:ne,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[Tr&&Ai.length>0?n.jsx(qp,{items:Ai,session:Zl,agentName:((Da=Ai[0])==null?void 0:Da.agentName)??null,onBack:k,onOpenItem:f=>{at(1),Xe(f.id)}}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h2",{className:"flex-shrink-0 text-heading font-semibold text-white",children:"Activity"}),n.jsx("span",{className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.05] px-2 py-0.5 text-micro text-primary tabular-nums",children:bn}),Un>0&&n.jsxs("span",{className:"hidden flex-shrink-0 rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums sm:inline-flex",children:["+",Un," hidden"]}),wn>0&&!K&&n.jsxs("button",{type:"button",onClick:()=>le(!0),className:"hidden flex-shrink-0 rounded-full border border-white/[0.14] bg-white/[0.03] px-2 py-0.5 text-micro text-secondary tabular-nums transition-colors hover:bg-white/[0.08] hover:text-primary sm:inline-flex",title:"Show low-signal sync replay events",children:[wn," sync hidden"]}),K&&n.jsx("button",{type:"button",onClick:()=>le(!1),className:"hidden flex-shrink-0 rounded-full border border-lime/30 bg-lime/[0.10] px-2 py-0.5 text-micro text-[#E1FFB2] transition-colors hover:bg-lime/[0.16] sm:inline-flex",title:"Hide low-signal sync replay events",children:"Sync visible"}),n.jsx("span",{className:ce("h-1.5 w-1.5 flex-shrink-0 rounded-full",ft&&"pulse-soft"),style:{backgroundColor:D.lime},"aria-label":"Live",title:ft?"New activity within the last minute":"Live activity feed"}),n.jsx("div",{className:"ml-auto w-[180px] flex-shrink-0 sm:w-[220px]",children:n.jsxs("div",{className:"relative",children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-muted",children:[n.jsx("circle",{cx:"11",cy:"11",r:"7"}),n.jsx("path",{d:"m20 20-3.5-3.5"})]}),n.jsx("input",{value:Y,onChange:f=>Te(f.target.value),placeholder:"Search...",className:"h-7 w-full rounded-full border border-white/[0.08] bg-white/[0.03] pl-7 pr-2 text-micro text-primary placeholder:text-muted transition-colors focus:border-[#BFFF00]/30 focus:outline-none","aria-label":"Search activity"})]})})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n.jsxs("div",{className:"relative",ref:bt,children:[n.jsxs("button",{type:"button",onClick:()=>{F(f=>!f),Me(!1)},"aria-haspopup":"menu","aria-expanded":T,className:ce("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",T?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsx("span",{className:"max-w-[120px] truncate",children:cn}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:ce("transition-transform duration-200",T&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(yt,{children:T&&n.jsx(pe.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:Sr.filter(f=>f.id!=="custom").map(f=>{const N=x===f.id;return n.jsx("button",{type:"button",onClick:()=>{b==null||b(f.id),F(!1)},className:ce("rounded-full border px-2.5 py-1 text-micro font-semibold transition-colors",N?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:f.label},f.id)})})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] p-2.5",children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Custom range"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"Start"}),en?n.jsx("input",{type:"datetime-local",step:300,value:Ji(ct),onChange:f=>_n(Go(f.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(Ba,{selected:ct,onChange:f=>_n(f instanceof Date?f:null),selectsStart:!0,startDate:ct,endDate:It,showTimeSelect:!0,timeIntervals:5,dateFormat:"MMM d, yyyy h:mm aa",className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35",calendarClassName:"orgx-datepicker",popperClassName:"orgx-datepicker-popper",popperPlacement:"bottom-start",showPopperArrow:!1}),n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"End"}),en?n.jsx("input",{type:"datetime-local",step:300,min:Ji(ct),value:Ji(It),onChange:f=>Tt(Go(f.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(Ba,{selected:It,onChange:f=>Tt(f instanceof Date?f:null),selectsEnd:!0,minDate:ct??void 0,startDate:ct,endDate:It,showTimeSelect:!0,timeIntervals:5,dateFormat:"MMM d, yyyy h:mm aa",className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35",calendarClassName:"orgx-datepicker",popperClassName:"orgx-datepicker-popper",popperPlacement:"bottom-start",showPopperArrow:!1})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-micro text-secondary",children:hn?`${Gr(ct)} - ${Gr(It)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:Es,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:is,disabled:!hn,className:"rounded-full border border-lime/30 bg-lime/[0.14] px-2.5 py-1 text-micro font-semibold text-[#E1FFB2] transition-colors hover:bg-lime/[0.2] disabled:opacity-45",children:"Apply"})]})]})]})]})})})]}),n.jsx("div",{className:"mx-0.5 h-3.5 w-px flex-shrink-0 bg-white/[0.08]"}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[(ze||d||g)&&n.jsxs(n.Fragment,{children:[ze&&n.jsxs("button",{onClick:k,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[Ko(Ts.id)?n.jsx(Vs,{provider:Ts.id,size:"xs"}):n.jsx(Ot,{name:(dt==null?void 0:dt.agentName)??"OrgX",hint:c??null,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Session",c?`: ${c}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),d&&n.jsxs("button",{onClick:p,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:[Ko(vt.id)?n.jsx(Vs,{provider:vt.id,size:"xs"}):n.jsx(Ot,{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(Vr).map(f=>{const N=H===f;return n.jsx("button",{type:"button",onClick:()=>z(f),"aria-pressed":N,className:ce("rounded-full px-3 py-1.5 text-micro font-semibold transition-colors",N?"border border-lime/25 bg-lime/[0.10] text-[#E1FFB2]":"border border-transparent text-secondary hover:bg-white/[0.08] hover:text-bright"),children:Vr[f]},f)})}),n.jsx("button",{type:"button",onClick:()=>Se(f=>!f),className:ce("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",xe?"border-lime/30 text-lime":"border-white/[0.1]"),"aria-pressed":xe,"aria-label":xe?"Expand activity density":"Compact activity density",title:xe?"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:xe?"M4 12h16":"M4 12h10"}),n.jsx("path",{d:"M4 17h16"})]})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:xs,children:[n.jsxs("button",{type:"button",onClick:()=>{Me(f=>!f),F(!1)},"aria-haspopup":"menu","aria-expanded":Oe,"aria-label":"Activity filters",title:"Activity filters",className:ce("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",Oe?"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:ce("transition-transform duration-200",Oe&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(yt,{children:Oe&&n.jsx(pe.div,{initial:{opacity:0,y:-6,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98},transition:{duration:.18,ease:[.22,1,.36,1]},className:"absolute right-0 z-20 mt-2 w-[290px] rounded-xl border border-white/[0.12] bg-[#0A0D14]/95 p-3 shadow-[0_12px_40px_rgba(0,0,0,0.45)] backdrop-blur-xl",role:"menu","aria-label":"Activity view controls",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Sort"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:[{id:"newest",label:"Newest"},{id:"oldest",label:"Oldest"}].map(f=>n.jsx("button",{type:"button",onClick:()=>{Fe(f.id),Me(!1)},className:ce("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",Z===f.id?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:f.label},f.id))})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Time window"}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Use the time dropdown beside Activity count for presets and custom date/time ranges."})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:Object.keys(Vr).map(f=>{const N=H===f;return n.jsx("button",{type:"button",onClick:()=>{z(f),Me(!1)},className:ce("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",N?"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:Vr[f]},f)})})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Signal"}),n.jsx("button",{type:"button",onClick:()=>{le(f=>!f)},className:ce("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",K?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:K?"Hide background sync events":"Show background sync events"}),n.jsx("p",{className:"mt-1 text-micro leading-relaxed text-muted",children:"Background sync events are routine system operations that most users can safely ignore."})]})]})})})]})]})]})]})}),n.jsxs("div",{ref:Ut,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[gt.length===0&&n.jsx("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-4 py-5",children:n.jsxs("div",{className:"mx-auto max-w-2xl",children:[n.jsx(ki,{icon:"activity",headline:X?"Syncing activity feed...":ze?"No activity yet for this session":d?"No activity yet for this workstream":"No matching activity right now.",description:X?"Live updates usually appear within a few seconds after dispatch.":`Try widening the time window (${cn}), changing filters, or launch the next workstream.`,className:"py-6"}),n.jsx("div",{className:"mt-3 flex flex-wrap items-center gap-1.5",children:Ms.map(f=>{const N=x===f.id;return n.jsx("button",{type:"button",onClick:()=>b==null?void 0:b(f.id),className:ce("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",N?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.1] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:f.label},`empty-time-${f.id}`)})}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(ze||d||g)&&n.jsx("button",{type:"button",onClick:()=>{ze&&k(),d&&(p==null||p()),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"}),V&&n.jsx("button",{type:"button",onClick:()=>void Ds("play",V),disabled:Ce!==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:Ce==="play"?"Starting...":"Start next session"}),!V&&je&&n.jsx("button",{type:"button",onClick:je,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"})]}),ot&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:ot})]})}),n.jsx(zp,{completedCount:Ht.completed,decisionsCount:Ht.decisions,blockerCount:Ht.blocked,visible:Qt,onDismiss:()=>{pn(!1),fn.current=Date.now()}}),gt.length>0&&n.jsxs("div",{className:"space-y-4",children:[Hn.map(f=>{const N=xe?f.clusters.slice(0,4):f.clusters;return n.jsxs("section",{children:[n.jsx("h3",{className:"mb-2.5 border-b border-subtle pb-1.5 text-caption font-semibold tracking-[0.01em] text-muted",children:f.label}),La?n.jsx(yt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:N.map((I,M)=>{const be=fe.has(I.key),Ue=I.allItems.slice(1),st=Ue.length,kt=Math.min(st,O[I.key]??br),dn=Ue.slice(0,kt);if(I.count===1)return Fs(I.representative,M);const jt=`cluster:${I.key}`;return n.jsxs("div",{children:[Fs(I.representative,M,jt),n.jsxs("button",{type:"button",onClick:xt=>{xt.stopPropagation(),St(I.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:["×",I.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:be?"hide":`and ${I.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ce("transition-transform",be?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),be&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[dn.map((xt,Gt)=>Fs(xt,M+Gt+1)),kt<st&&n.jsxs("button",{type:"button",onClick:xt=>{xt.stopPropagation(),Tn(I.key,st)},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 (",st-kt," remaining)"]})]})]},I.key)})})}):n.jsx("div",{className:"space-y-2",children:N.map((I,M)=>{const be=fe.has(I.key),Ue=I.allItems.slice(1),st=Ue.length,kt=Math.min(st,O[I.key]??br),dn=Ue.slice(0,kt);if(I.count===1)return Fs(I.representative,M);const jt=`cluster:${I.key}`;return n.jsxs("div",{children:[Fs(I.representative,M,jt),n.jsxs("button",{type:"button",onClick:xt=>{xt.stopPropagation(),St(I.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:["×",I.count]}),n.jsx("span",{className:"text-muted",children:"·"}),n.jsx("span",{children:be?"hide":`and ${I.count-1} similar`}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:ce("transition-transform",be?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),be&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[dn.map((xt,Gt)=>Fs(xt,M+Gt+1)),kt<st&&n.jsxs("button",{type:"button",onClick:xt=>{xt.stopPropagation(),Tn(I.key,st)},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 (",st-kt," remaining)"]})]})]},I.key)})}),xe&&f.clusters.length>N.length&&n.jsxs("p",{className:"mt-1.5 text-caption text-muted",children:["+",f.clusters.length-N.length," more"]})]},f.key)}),n.jsx("div",{ref:Sn,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:ce("flex items-center justify-center py-6 transition-opacity duration-500 ease-out",j?"opacity-100":y?"opacity-0":"opacity-0 pointer-events-none"),children:n.jsx("div",{className:"flex items-center gap-2.5",children:n.jsxs("div",{className:"flex gap-1","aria-label":"Loading older events",children:[n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/70 animate-[pulse_1.4s_ease-in-out_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/50 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/30 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]"})]})})}),!y&&!j&>.length>0&&!Ho(x)&&n.jsx("p",{className:"pb-4 text-center text-micro tracking-wide text-muted/50",children:Un>0?`${gt.length} of ${bn} events`:"You’ve reached the beginning"})]})]})]}),Ne?n.jsx(gf,{}):null,n.jsx(Hp,{open:R!==null,onClose:Gn,children:R&&n.jsxs("div",{className:"relative flex h-[100dvh] w-full min-h-0 flex-col sm:h-[86vh] sm:max-h-[86vh]",children:[n.jsx("div",{className:"absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-lime/10 via-cyan/5 to-transparent"}),n.jsxs("div",{className:"relative z-10 flex items-center justify-between border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:{backgroundColor:ta(R.userState),boxShadow:`0 0 12px ${ta(R.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[ea(R.userState)," · ",En+1,"/",gt.length," sessions"]}),Qe&&n.jsx(Nn,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:Qe})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[R.runId&&U&&n.jsx("button",{type:"button",onClick:()=>{U(R.runId),Gn()},className:"rounded-full border border-lime/25 bg-lime/10 px-3 py-1 text-caption font-semibold text-lime transition hover:bg-lime/20",children:"Focus session"}),n.jsx("button",{type:"button",onClick:()=>ir(-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:()=>ir(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:()=>qe(f=>!f),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"More actions",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[n.jsx("circle",{cx:"12",cy:"5",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"19",r:"1.5"})]})}),et&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>qe(!1)}),n.jsxs("div",{className:"absolute right-0 top-full z-40 mt-1 min-w-[160px] rounded-lg border border-strong bg-[#0d0f16] py-1 shadow-xl",children:[R.runId&&n.jsx("button",{type:"button",onClick:()=>{Xn("Run id",R.runId??""),qe(!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"}),P.agentId&&n.jsx("button",{type:"button",onClick:()=>{Xn("Agent id",P.agentId??""),qe(!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:()=>{Xn("Event id",R.item.id),qe(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy event ID"})]})]})]}),n.jsx("button",{type:"button",onClick:Gn,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"Close activity detail",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]})]}),n.jsx("div",{className:"relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto px-5 pb-5 pt-4 sm:px-6",children:n.jsx(yt,{mode:"wait",custom:pt,children:n.jsx(pe.section,{custom:pt,initial:{opacity:0,x:pt*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:pt*-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:B||nl(R.item,We)||lt(R.item.title||gi(R.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(R.item.timestamp).toLocaleString()," · ",Mt(R.item.timestamp),_e==="llm"&&n.jsx("span",{className:"text-muted",children:"· AI title"})]}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-caption",children:[(()=>{const f=wt(R.item),N=(re==null?void 0:re.workstreamId)??wr(R.item)??(R.runId?tn.get(R.runId)??null:null),I=Jr([{value:(re==null?void 0:re.workstreamTitle)??null,idHint:N},{value:nt(f,["workstream_title","workstreamTitle"]),idHint:N},{value:N?E.get(N)??null:null,idHint:N},{value:R.runId?rs.get(R.runId)??null:null,idHint:N}]),be=[Jr([{value:(re==null?void 0:re.initiativeTitle)??null,idHint:R.item.initiativeId},{value:nt(f,["initiative_title","initiativeTitle"]),idHint:R.item.initiativeId},{value:R.item.initiativeId?Wn.get(R.item.initiativeId)??null:null,idHint:R.item.initiativeId}]),I].filter(Boolean).join(" > ");return be?n.jsx(Nn,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:be})}):null})(),n.jsx(Nn,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:ea(R.userState)}),n.jsxs(Nn,{tone:"muted",children:[n.jsx(Ot,{name:(Dn==null?void 0:Dn.label)??(Ve==null?void 0:Ve.primaryLabel)??"OrgX",hint:Dn?Yi(Dn):(Ve==null?void 0:Ve.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(Dn==null?void 0:Dn.label)??(Ve==null?void 0:Ve.primaryLabel)??"OrgX"})]}),At&&n.jsx(Nn,{tone:"lime",children:"Sync replay"})]})]}),n.jsx(Gp,{item:R.item}),Ln&&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:Ln.source==="metadata"?"Artifact":lt(Ln.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:()=>ye("structured"),"aria-pressed":Ze==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${Ze==="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:()=>ye("json"),"aria-pressed":Ze==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${Ze==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),Vn&&n.jsx("button",{type:"button",onClick:()=>$(Vn),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:Ze==="structured"?Yl(Ln.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(Ln.value,null,2)})})})]}),Et&&n.jsxs("div",{className:ce("rounded-xl border px-3.5 py-3",Et.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",Et.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",Et.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",Et.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:Et.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:Et.summary}),Et.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:Et.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[R.runId&&U&&n.jsx("button",{type:"button",onClick:()=>{U(R.runId),Gn()},className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Open work session"}),tr&&n.jsx("button",{type:"button",onClick:()=>{ae==null||ae(Kn[0]??null),Gn()},className:"rounded-full border border-amber-300/30 bg-amber-400/[0.10] px-3 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-400/[0.16]",children:Kn.length>0?"Resolve decision":"Resolve decisions"}),Vn&&!Ln&&n.jsx("button",{type:"button",onClick:()=>$(Vn),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"}),tt&&n.jsx("a",{href:tt,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"}),Kt&&n.jsx("button",{type:"button",onClick:()=>void $s(),disabled:Nt,className:ce("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",Kt.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:Nt?"Scheduling...":Kt.actionLabel})]}),Kt&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:Ct??Kt.helperText})]}),m&&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(Nn,{tone:m.isRateLimited?"muted":"red",children:m.isRateLimited?"Rate limited":"Blocked"})]}),n.jsx("p",{className:"mt-1 text-caption text-amber-100/80",children:"Dispatch was stopped before launch. Adjust limits or retry after the window resets."}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Domain window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:m.domainCurrent!==null&&m.domainMax!==null?`${m.domainCurrent}/${m.domainMax} per hour`:"Not provided"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Global window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:m.totalCurrent!==null&&m.totalMax!==null?`${m.totalCurrent}/${m.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[m.domain&&n.jsxs(Nn,{tone:"muted",children:["Domain: ",lt(m.domain)]}),m.modelTier&&n.jsxs(Nn,{tone:"muted",children:["Tier: ",lt(m.modelTier)]}),A&&n.jsxs(Nn,{tone:"muted",children:["Retry: ",A]}),!A&&m.retryInMs!==null&&n.jsxs(Nn,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(m.retryInMs/1e3)),"s"]})]}),m.blockedReason&&n.jsx("p",{className:"mt-2 rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2 text-caption text-primary",children:Rt(m.blockedReason)??m.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[ge&&n.jsx("button",{type:"button",onClick:ge,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"}),Kt&&n.jsx("button",{type:"button",onClick:()=>void $s(),disabled:Nt,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:Nt?"Scheduling...":"Retry now"})]})]}),er.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:er.map(f=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:f.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${f.tone==="critical"?"text-red-300":"text-primary"}`,children:f.value})]},f.label))})]}),Ve&&!re&&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:Ve.requester?n.jsxs(n.Fragment,{children:[n.jsx(Ot,{name:Ve.requester.label,hint:Yi(Ve.requester),size:"xs"}),n.jsx("span",{className:"text-primary",children:Ve.requester.label})]}):n.jsx("span",{children:jr("System / unknown")})}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"text-primary",children:Ve.mode==="handoff"?"Delegated handoff":Ve.mode==="requested"?"Dispatch requested":Ve.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:Ve.executor?n.jsxs(n.Fragment,{children:[n.jsx(Ot,{name:Ve.executor.label,hint:Yi(Ve.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:Ve.executor.label})]}):n.jsx("span",{children:jr("Not assigned")})})]}),Ve.subtitle&&n.jsx("p",{className:"mt-1 text-caption text-muted",children:Ve.subtitle})]}),re&&n.jsxs("div",{className:"space-y-5",children:[(L==null?void 0:L.nextStep)&&(($t==null?void 0:$t.tone)==="critical"||($t==null?void 0:$t.tone)==="warning")&&n.jsxs("div",{className:"rounded-xl border border-red-400/25 bg-red-500/[0.08] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-red-400"}),n.jsx("p",{className:"text-micro font-semibold uppercase tracking-wider text-red-200",children:"Action needed"})]}),n.jsx("p",{className:"text-body text-primary leading-relaxed",children:L.nextStep})]}),n.jsx("div",{children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("p",{className:"px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Session"}),n.jsx("span",{className:"rounded-full border border-lime/30 bg-lime/[0.08] px-2 py-0.5 text-micro font-semibold text-lime/85",children:cr(re.event)??lt(re.event)})]})}),$t&&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:sr?"Terminal state":"Progress"}),n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:nr},children:sr?(Et==null?void 0:Et.label)??"Stopped":`${$t.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,$t.pct)}%`,backgroundColor:nr}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:$t.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(Ot,{name:ls.primary,hint:ls.secondary??ls.primary,size:"xs"}),n.jsx("span",{children:ls.primary})]}),ls.secondary&&n.jsxs("p",{className:"mt-0.5 text-micro text-muted",children:["via ",ls.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(Ot,{name:Zs,hint:Zs,size:"xs"}),n.jsx("span",{children:Zs})]})]}),re.dispatcherClient&&re.dispatcherClient!=="unknown"&&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:lt(re.dispatcherClient)})]}),(re.domain||re.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:[re.domain??"",re.requiredSkills.length>0?`${re.domain?" · ":""}${re.requiredSkills.join(", ")}`:""]})]})]})]}),L&&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:L.initiativeTitle??(L.initiativeId?us(L.initiativeId):"—")})]}),L.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:lt(L.initiativeStatus)})]}),(L.workstreamTitle||L.workstreamId)&&n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Workstream"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:L.workstreamTitle??us(L.workstreamId)})]}),L.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:lt(L.workstreamStatus)})]})]}),L.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:[L.doneInitiativeWorkstreams??0,"/",L.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,L.initiativeWorkstreamPct)}%`}})})]})]}),((L==null?void 0:L.taskTitle)||(L==null?void 0:L.milestoneTitle)||(L==null?void 0:L.phase)||(L==null?void 0:L.nextStep)||(L==null?void 0:L.parsedStatus)||(L==null?void 0:L.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:[(L==null?void 0:L.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:L.taskTitle})]}),(L==null?void 0:L.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:L.milestoneTitle})]}),(L==null?void 0:L.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:cr(L.phase)??lt(L.phase)})]}),(L==null?void 0:L.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:L.nextStep})]}),(L==null?void 0:L.parsedStatus)&&L.parsedStatus!==(L==null?void 0:L.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:cr(L.parsedStatus)??lt(L.parsedStatus)})]}),(L==null?void 0:L.stopReason)&&L.stopReason!==(L==null?void 0:L.phase)&&L.stopReason!==(L==null?void 0:L.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:cr(L.stopReason)??lt(L.stopReason)})]})]})]}),re.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:re.error})]}),ut&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),q==="missing"&&!At&&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(pi,{mode:"block",text:ut,className:"text-body leading-relaxed text-primary"})]}),Rt(R.item.description)&&Rt(R.item.description)!==ut&&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(pi,{mode:"block",text:Rt(R.item.description)??"",className:"text-body leading-relaxed text-secondary"})]}),Jt&&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:Jt.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:Jt.dispatch})]}),Jt.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:Jt.highlights.slice(0,3).map((f,N)=>n.jsx("li",{children:f},`${Jt.sliceRunId}:highlight:${N}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:Jt.outcome.summary})]})]})]}),ke.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:[ke.length," ",ke.length===1?"file":"files"," captured for this run."]}),n.jsxs("div",{className:"space-y-2",children:[it.map((f,N)=>{const I=na(f.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:lt(f.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Is(f.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[I&&n.jsx("a",{href:I,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 Xn(`${lt(f.key)} path`,f.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"})]})]},`${f.key}:${f.path}:${N}`)}),Be.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 ",Be.length," additional evidence file",Be.length===1?"":"s"]}),n.jsx("div",{className:"mt-2 space-y-2",children:Be.map((f,N)=>{const I=na(f.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:lt(f.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Is(f.path)})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:[I&&n.jsx("a",{href:I,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 Xn(`${lt(f.key)} path`,f.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"})]})]},`${f.key}:${f.path}:overflow:${N}`)})})]})]})]}),R&&Zi(R.item)&&!Ln&&n.jsxs("button",{type:"button",onClick:()=>{const f=Zi(R.item);f&&$(f)},className:"flex w-full items-center gap-2.5 rounded-xl border border-cyan-400/25 bg-cyan-500/[0.08] px-3.5 py-2.5 text-left transition-colors hover:bg-cyan-500/[0.14]",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:D.cyan,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsx("span",{className:"text-body font-medium",style:{color:D.cyan},children:"View registered artifact"})]}),(Ye||(re==null?void 0:re.logPath)||S)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),(Ye||(re==null?void 0:re.logPath)||(re==null?void 0:re.outputPath)||(L==null?void 0:L.initiativeId)||(L==null?void 0:L.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:[Ye&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[Ye.domain&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Domain"}),n.jsx("div",{className:"mt-0.5 text-primary",children:lt(Ye.domain)})]}),(Ye.provider||Ye.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:[Ye.provider?`${lt(Ye.provider)} · `:"",Ye.model?Ar(Ye.model):"—"]})]}),Ye.modelTier&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model tier"}),n.jsx("div",{className:"mt-0.5 text-primary",children:lt(Ye.modelTier)})]}),Ye.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",Ye.pluginVersion]})]})]}),(Ye==null?void 0:Ye.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:[Ye.skillPack.name??"—",Ye.skillPack.version?`@${Ye.skillPack.version}`:"",Ye.skillPack.source?` · ${Ye.skillPack.source}`:""]}),Ye.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var f;return void Xn("Skill pack checksum",((f=Ye.skillPack)==null?void 0:f.checksum)??"")},className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:["sha ",Ye.skillPack.checksum.slice(0,12)]})]}),Ye&&Ye.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"}),Ye.requiredSkills.map(f=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:f},f))]}),(Ye==null?void 0:Ye.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:[Ye.kickoffContextSource?`${Ye.kickoffContextSource} · `:"",Ye.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void Xn("Kickoff context hash",Ye.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"})]}),((re==null?void 0:re.logPath)||(re==null?void 0:re.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(re==null?void 0:re.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: ",Is(re.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void Xn("Log path",(re==null?void 0:re.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"})]}),(re==null?void 0:re.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: ",Is(re.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void Xn("Output path",(re==null?void 0:re.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"})]})]}),((L==null?void 0:L.initiativeId)||(L==null?void 0:L.workstreamId))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(L==null?void 0:L.initiativeId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["initiative: ",us(L.initiativeId)]}),(L==null?void 0:L.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",us(L.workstreamId)]})]})]})]}),S&&n.jsxs("details",{className:"group",children:[n.jsxs("summary",{className:"flex cursor-pointer items-center gap-1.5 px-1 text-micro font-semibold uppercase tracking-wider text-muted select-none",children:[n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"transition-transform group-open:rotate-90",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),"Raw metadata"]}),n.jsx("pre",{className:"mt-2 overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-muted",children:S})]})]})},R.item.id)})}),n.jsx("div",{className:"border-t border-subtle px-5 py-2.5 text-caption text-muted sm:px-6",children:"Keyboard: ← previous · → next · Esc close"})]})})]})})}),eh=o.lazy(async()=>({default:(await zt(()=>import("./0RUEVzJa.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))).MissionControlView})),th=o.lazy(async()=>({default:(await zt(()=>import("./3TtV4moZ.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13]))).SessionInspector})),nh=o.lazy(async()=>({default:(await zt(()=>import("./DHz-aQPw.js"),__vite__mapDeps([16,1,8,5,15,2,10,11,12,13]))).DecisionQueue})),sh=o.lazy(()=>zt(()=>import("./CSlBSRyv.js"),__vite__mapDeps([17,1,5])).then(e=>({default:e.TriageQueue}))),rh=o.lazy(()=>zt(()=>import("./C-MOJWHs.js"),__vite__mapDeps([18,1,5])).then(e=>({default:e.TriageDetailModal}))),ih=o.lazy(async()=>({default:(await zt(()=>import("./BVvffj0x.js").then(t=>t.a),__vite__mapDeps([3,1,4,5,6]))).NextUpPanel})),ah=o.lazy(async()=>({default:(await zt(()=>import("./T2NFtzAv.js"),__vite__mapDeps([19,1,2,5,9,10,11,12,13]))).SettingsModal})),oh=o.lazy(async()=>({default:(await zt(()=>import("./gZr_xKlA.js"),__vite__mapDeps([20,1,2,5,10,11,12,13]))).BulkSessionsModal})),lh=o.lazy(async()=>({default:(await zt(()=>import("./CFZ4Swr5.js"),__vite__mapDeps([21,1,16,8,5,15,2,10,11,12,13]))).BulkDecisionsModal})),ch=o.lazy(async()=>({default:(await zt(()=>import("./CnPC783_.js"),__vite__mapDeps([22,1,2,5,10,11,12,13]))).BulkOutboxModal})),dh=o.lazy(async()=>({default:(await zt(()=>import("./7DhYqBrM.js"),__vite__mapDeps([23,1,2,5,10,11,12,13]))).BulkHandoffsModal})),uh=o.lazy(async()=>({default:(await zt(()=>import("./CJjEAGFN.js"),__vite__mapDeps([24,1,2,4,5,10,11,12,13]))).ArtifactViewerModal})),mh=o.lazy(async()=>({default:(await zt(()=>import("./CMTTPXch.js"),__vite__mapDeps([25,1,8,5,7,6,2,10,11,12,13]))).SliceDetailModal})),ph=o.lazy(async()=>({default:(await zt(()=>import("./Ctw95IkC.js"),__vite__mapDeps([26,1,2,5,10,11,12,13]))).RealtimeOrchestratorModal})),sl={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},fh={connected:D.lime,reconnecting:D.amber,disconnected:D.red},ia="orgx.demo_mode",aa="orgx.dev_mode",oa="orgx.show_synthetic_entities",wa="orgx.selected_workspace_id",rl={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},il=new Set(["running","active","queued","pending","in_progress","working","planning"]),hh=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function on(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function gh(e){const t=on(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function xh(e,t=220){const s=e.split("|").map(a=>a.trim()).filter(Boolean).map(a=>a.replace(/^[^:]+:\s*/,"").trim()),i=Array.from(new Set(s.length>0?s:[e.trim()])).slice(0,2).join(" ");return i.length<=t?i:`${i.slice(0,t-1).trimEnd()}…`}function yh(e){const t=e.trim().toLowerCase();if(t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("signal is aborted"))return{title:"Live sync delayed",message:"OrgX Live is responding slowly. Initiatives and Next Up may look empty until sync recovers.",action:"refresh"};if(t.includes("unauthorized")||t.includes("forbidden")||t.includes("api key")||t.includes("auth"))return{title:"OrgX auth required",message:"Reconnect your OrgX API key in Settings to restore live initiatives, activity, and Next Up.",action:"settings"};if(t.includes("unknown api endpoint")||t.includes("missing required live routes")||t.includes("runtime is missing required live routes"))return{title:"Plugin update required",message:"This runtime is missing required live routes. Restart the plugin and update to the latest build.",action:"settings"};const s=Lt(e);return{title:"Live stream degraded",message:xh(s),action:"settings"}}function la(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 bh(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 al(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function ol(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 ca(e,t){const s=rl[e.status]??99,r=rl[t.status]??99;return s!==r?s-r:on(e.updatedAt??e.lastEventAt??e.startedAt)-on(t.updatedAt??t.lastEventAt??t.startedAt)}function ll(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 wh(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 vh(e){if(Cs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function kh(e){if(Cs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function jh(e){const t=e.metadata;return t!=null&&typeof t=="object"&&t.mock===!0}function Nh(e){return hh.test(e)}function Yr(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 Ih(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Ah(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function Sh(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 _h(e,t){gs(e,t)}function Ch(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 Mh(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=Sh(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(wa);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function Th(){const e=Td();return e.showGate?n.jsx(Su,{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(Mm,{children:n.jsx($h,{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 Rh(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 cl(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 dl(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Lh(){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:wi,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function Dh(){const{state:e}=$l();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(uh,{})}):null}function $h({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(ia)==="1"}catch{return!1}}),[r,i]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(oa)==="1"}catch{return!1}}),[a,l]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(aa)==="1"}catch{return!1}}),[c,d]=o.useState(()=>{if(new URLSearchParams(window.location.search).get("view")==="mission-control")return"mission-control";try{if(localStorage.getItem("orgx-dashboard-view")==="mission-control")return"mission-control"}catch{}return"activity"}),[u,g]=o.useState(()=>Mh()),x=o.useCallback(m=>{d(m);try{localStorage.setItem("orgx-dashboard-view",m)}catch{}},[]),{data:b=[]}=hs({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),P=Array.isArray(A==null?void 0:A.data)?A.data:[],S=[];for(const J of P){if(!J||typeof J!="object"||Array.isArray(J))continue;const ke=Yr(J,["id"]);if(!ke)continue;const it=Yr(J,["status","priority"]);if(!Ih(it))continue;const Be=Yr(J,["title","name"])??(ke.length>10?`${ke.slice(0,8)}…`:ke),tt=J.is_default===!0,ut=Ah({title:Be,isDefault:tt}),At=Yr(J,["created_at"]);S.push({id:ke,title:ut,status:it,isDefault:tt,createdAt:At})}return S.sort((J,ke)=>{if(J.isDefault!==ke.isDefault)return J.isDefault?-1:1;const it=on(J.createdAt)-on(ke.createdAt);return it!==0?it:J.title.localeCompare(ke.title)}),S},staleTime:6e4}),h=o.useMemo(()=>{var m;return u?((m=b.find(A=>A.id===u))==null?void 0:m.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,b]),v=o.useMemo(()=>!u||b.some(m=>m.id===u)?b:[{id:u,title:h,status:null,isDefault:!1,createdAt:null},...b],[u,h,b]);o.useEffect(()=>{u&&b.length!==0&&(b.some(m=>m.id===u)||g(null))},[u,b]),t||e.state.hasApiKey&&e.state.connectionVerified;const y=o.useMemo(()=>c==="mission-control"?{maxSessions:240,maxActivityItems:120,maxHandoffs:60,maxDecisions:80,batchWindowMs:140}:{maxSessions:320,maxActivityItems:80,maxHandoffs:80,maxDecisions:80,batchWindowMs:120},[c]),{data:j,isLoading:w,error:k,refetch:p,approveDecision:_,rejectDecision:U,approveAllDecisions:ae,bulkDecisionAction:G,decisionMutation:ve}=id({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...y}),V=t||r,ee=o.useMemo(()=>V?j.sessions.nodes:j.sessions.nodes.filter(m=>!vh(m)),[j.sessions.nodes,V]),de=o.useMemo(()=>j.activity.filter(m=>!(!V&&kh(m)||!a&&jh(m))),[j.activity,V,a]),we=j.connection==="connected"||j.decisions.length>0,[je,ge]=o.useState(null),[He,ue]=o.useState(!1),[ne,X]=o.useState(null),[te,Ne]=o.useState(null),[se,$]=o.useState(null),[H,z]=o.useState(null),[K,le]=o.useState("live"),[xe,Se]=o.useState({startIso:null,endIso:null}),Y=o.useRef(new Set),[Te,fe]=o.useState(null),[C,O]=o.useState(null),[W,Z]=o.useState(null),[Fe,Oe]=o.useState(null),Me=o.useRef(null),T=o.useCallback(m=>{Me.current&&clearTimeout(Me.current),Oe(m),Me.current=setTimeout(()=>Oe(null),4e3)},[]),[F,ie]=o.useState(!1),[he,Ie]=o.useState(!1),[Xe,Qe]=o.useState([]),Ee=o.useRef(null),et=o.useRef(null),[qe,pt]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[at,Ze]=o.useState(!1),[ye,We]=o.useState(null),[Ae,q]=o.useState("agents"),[Re,B]=o.useState("initiatives"),[Q,_e]=o.useState("next_up"),Le=o.useCallback(m=>{if(q(m),m==="initiatives"){B("initiatives"),_e("next_up");return}m==="decisions"&&(B("initiatives"),_e("in_progress"),Pe("needs_attention"))},[]),[De,Pe]=o.useState("all"),Ce=o.useMemo(()=>Array.isArray(j.sliceRuns)?j.sliceRuns:[],[j.sliceRuns]),ot=o.useMemo(()=>El({sessions:ee,sliceRuns:Ce}),[Ce,ee]).length,Ge=o.useMemo(()=>Rl(Ce),[Ce]),Nt=Ge.length+(we?j.decisions.length:0),[Je,Ct]=o.useState(null),Wt=o.useCallback(m=>{const A=Ce.find(P=>P.initiativeId===m.initiativeId&&P.workstreamId===m.workstreamId)??null;Ct({source:"queue",item:m,linkedSliceRun:A})},[Ce]),Qt=o.useCallback((m,A)=>{Ct({source:"in_progress",row:m,sliceRun:A})},[]),pn=o.useCallback(m=>{Ct({source:"needs_input",sliceRun:m})},[]),fn=o.useCallback(async(m,A)=>{T("Slice accepted and marked complete."),p()},[p,T]),xs=o.useCallback(async(m,A)=>{T("Changes requested — feedback posted.")},[T]),bt=Jd({projectId:u,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:j.snapshotVersion}),Ut=Zd({authToken:null,embedMode:!1}),{model:Sn,actions:Bn}=nu({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),ct=o.useMemo(()=>Sn.items.filter(m=>m.kind==="failure_diagnostic"),[Sn.items]),_n=o.useMemo(()=>({...Sn,items:ct,total:ct.length}),[ct,Sn]),[It,Tt]=o.useState(null),[en,ys]=o.useState(0),qn=o.useCallback(m=>{Tt(m);const A=ct.findIndex(P=>P.id===m.id);ys(A>=0?A:0)},[ct]),Cn=o.useCallback(m=>{if(ct.length===0)return;const A=(en+m+ct.length)%ct.length;ys(A),Tt(ct[A]??null)},[en,ct]),Mn=bt,hn=o.useMemo(()=>bt.items.find(m=>m.autoIntentEnabled===!0&&(m.autoRuntimeState==="running"||m.autoRuntimeState==="stopping"))??null,[bt.items]),cn=!!hn;o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(ia,"1"):window.localStorage.removeItem(ia)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{r?window.localStorage.setItem(oa,"1"):window.localStorage.removeItem(oa)}catch{}},[r]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(aa,"1"):window.localStorage.removeItem(aa)}catch{}},[a]),o.useEffect(()=>{a||Ze(!1)},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(wa,u):window.localStorage.removeItem(wa)}catch{}try{const m=new URL(window.location.href);u?_h(m.searchParams,u):Ch(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)=>{pt(P=>({open:!0,tab:m??P.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),ts=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{}},[]),gn=o.useCallback(()=>{Ht("orgx")},[Ht]),zn=o.useCallback(()=>{zt(()=>import("./0RUEVzJa.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]))},[]),{data:ns}=Ll(c==="mission-control",u),{data:xn}=Cm(c==="mission-control",u),{data:ss=[]}=hs({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[Dt,yn]=o.useState(null),[tn,rs]=o.useState(""),[Wn,E]=o.useState(!1),oe=o.useCallback((m,A)=>{yn({type:m,initiativeId:A}),rs(""),E(!1)},[]),me=o.useCallback(()=>{yn(null),rs(""),E(!1)},[]),$e=o.useCallback(()=>{Ne(null)},[]),ft=o.useCallback(()=>{$(null),z(null)},[]),ht=o.useCallback(()=>{Z(null)},[]);o.useEffect(()=>{var P;const m=((P=ee[0])==null?void 0:P.id)??null;if(!m){je!==null&&ge(null);return}if(je===null){ge(m);return}ee.some(S=>S.id===je)||ge(m)},[ee,je]),o.useEffect(()=>{if(!te)return;ee.some(A=>A.id===te)||Ne(null)},[te,ee]);const ze=o.useCallback(m=>{zt(()=>import("./3TtV4moZ.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),ge(m),ue(!0),X(null),Ne(m),$(null),z(null)},[]),Ms=o.useCallback(m=>{zt(()=>import("./3TtV4moZ.js"),__vite__mapDeps([14,1,15,5,2,10,11,12,13])),ge(m.id),ue(!0),Ne(m.id),$(m.workstreamId??null),z(m.title),X({workstreamId:m.workstreamId??null,text:`Intervention requested for "${m.title}". `}),T(`Opened intervention composer for ${m.title}.`)},[]),dt=o.useCallback(m=>{const A=m.trim();if(!A)return;const P=ee.find(S=>S.runId===A||S.id===A)??null;P&&(ze(P.id),T(`Focused session: ${P.title}`))},[ee,ze]),Ts=o.useCallback(m=>{var S;const A=(S=m.id)==null?void 0:S.trim();if(!A)return;const P=la(m);if(P){const J=ee.find(ke=>ke.runId===P||ke.id===P)??null;J&&(ge(J.id),Ne(J.id))}x("activity"),q("activity"),ue(!1),fe(A),T("Opened activity detail from session timeline.")},[ee,x]),vt=o.useMemo(()=>ee.find(m=>m.id===te)??null,[te,ee]),gt=o.useMemo(()=>{var P,S;const m=((P=vt==null?void 0:vt.runId)==null?void 0:P.trim())??"",A=((S=vt==null?void 0:vt.id)==null?void 0:S.trim())??"";return!m||!A?[]:m===A?[m]:[m,A]},[vt==null?void 0:vt.id,vt==null?void 0:vt.runId]),bn=o.useMemo(()=>{const m=new Set;for(const A of gt){const P=A.trim();P.length>0&&m.add(P)}return m},[gt]),Un=o.useMemo(()=>{const m=new Map;for(const A of ee){const P=A.workstreamId??null;A.runId&&m.set(A.runId,P),A.id&&m.set(A.id,P)}return m},[ee]),wn=o.useMemo(()=>{const m=gt.length>0?gt.join("|"):"*",A=(se==null?void 0:se.trim())||"*",P=(W==null?void 0:W.trim())||"*";return`${m}::${A}::${P}`},[se,W,gt]),bs=o.useCallback(m=>{Y.current.add(wn),le(m)},[wn]);o.useEffect(()=>{if(Y.current.has(wn)||w)return;const m=Date.now(),A=de.filter(J=>{const ke=la(J);if(bn.size>0&&(!ke||!bn.has(ke)))return!1;if(se){const it=al(J);if((ol(it,["workstreamId","workstream_id"])??(ke?Un.get(ke)??null:null))!==se)return!1}if(W){const it=al(J);if((ol(it,["agentName","agent_name"])??J.agentName)!==W)return!1}return!0});if(A.length===0)return;const S=["live","24h","7d","all"].find(J=>{const ke=Cr(J,m);return A.some(it=>{const Be=on(it.timestamp);return Be?ke===null||Be>=ke:!1})})??"all";Y.current.add(wn),S!==K&&le(S)},[se,de,wn,K,Un,W,w,bn]);const Hn=gd({seed:de,timeFilterId:K,customSinceIso:K==="custom"?xe.startIso:null,customUntilIso:K==="custom"?xe.endIso:null,runId:(vt==null?void 0:vt.runId)??null,projectId:u,pageSize:50,demoMode:t}),St=o.useMemo(()=>ee.find(m=>m.id===je)??null,[ee,je]),Tn=o.useMemo(()=>ee.filter(m=>il.has(m.status)).length,[ee]),is=o.useMemo(()=>Ce.length>0?Ge.length:ee.filter(m=>{const A=qt(m.status),P=qt(m.phase??""),S=qt(m.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||P==="blocked"||S==="error"?!0:il.has(A)||A==="handoff"||A==="review"?!1:m.blockers.length>0}).length,[Ce.length,Ge.length,ee]);o.useMemo(()=>ee.filter(m=>m.status==="failed").length,[ee]);const Es=o.useMemo(()=>ee.filter(m=>m.status==="completed").length,[ee]);o.useMemo(()=>{const m=(we?j.decisions.length:0)+is;return[{id:"active",label:"Running",value:Tn,color:Tn>0?D.lime:D.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:m,color:m>0?D.amber:D.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:Es,color:D.teal,icon:"session"}]},[Tn,is,Es,j.decisions.length,ee,we]),o.useMemo(()=>j.decisions.length>0?Math.max(0,...j.decisions.map(m=>m.waitingMinutes)):0,[j.decisions]);const vn=o.useMemo(()=>k?yh(k):null,[k]),kn=o.useMemo(()=>{const m=[];if(vn){const A=vn.action==="refresh"&&typeof p=="function";m.push({id:`stream-error:${k}`,kind:"error",icon:"notification",title:vn.title,message:vn.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void p():()=>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:gn}),Fe&&m.push({id:`ops:${Fe}`,kind:"info",icon:/decision/i.test(Fe)?"decision":"workstream",title:"Update",message:Fe}),m},[j.connection,j.outbox.lastReplayError,j.outbox.pendingTotal,j.outbox.replayStatus,k,vn,gn,p,Ht,Fe]);o.useEffect(()=>{const m=new Set(kn.map(A=>A.id));Qe(A=>A.filter(P=>m.has(P)))},[kn]);const as=o.useMemo(()=>kn.filter(m=>!Xe.includes(m.id)),[Xe,kn]),Xs=we?j.decisions.length:0,Rs=Tn+is+Xs,Ni=o.useCallback(m=>{Qe(A=>A.includes(m)?A:A.concat(m))},[]),Qs=o.useCallback(()=>{Qe(kn.map(m=>m.id))},[kn]);o.useEffect(()=>{if(!he)return;const m=P=>{var J,ke;const S=P.target;S&&((J=et.current)!=null&&J.contains(S)||(ke=Ee.current)!=null&&ke.contains(S)||Ie(!1))},A=P=>{P.key==="Escape"&&Ie(!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)}},[he]);const Vt=o.useMemo(()=>{var P;const m=new Map;for(const S of ee){const J=S.initiativeId??S.groupId??"unscoped",ke=S.groupLabel&&S.groupLabel.trim().length>0?S.groupLabel:S.initiativeId??"Unscoped Initiative",it=Eh(ke),Be=m.get(J)??{id:J,name:ke,category:it,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(S.progress!==null&&(Be.progressTotal+=S.progress,Be.progressCount+=1),Be.statusCounts[S.status]=(Be.statusCounts[S.status]??0)+1,S.agentName&&(Be.allAgents.add(S.agentName),["running","queued","pending","blocked"].includes(S.status)&&Be.activeAgents.add(S.agentName)),S.workstreamId){const tt=j.sessions.groups.find(At=>At.id===S.workstreamId),ut=((P=tt==null?void 0:tt.label)==null?void 0:P.trim())||S.workstreamId;Be.workstreams.set(S.workstreamId,ut)}Be.latestEpoch=Math.max(Be.latestEpoch,on(S.updatedAt??S.lastEventAt??S.startedAt)),m.set(J,Be)}const A=[];for(const S of m.values()){const J=S.progressCount>0?Math.round(S.progressTotal/S.progressCount):S.statusCounts.completed?100:S.statusCounts.running?55:0,ke=S.category,it=Rh(ke),Be=Math.round(Math.max(0,Math.min(100,J))/100*(it.length-1)),tt=(S.statusCounts.blocked??0)>0,ut=(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,At=!ut&&!tt&&(S.statusCounts.paused??0)>0&&(S.statusCounts.running??0)===0&&(S.statusCounts.queued??0)===0&&(S.statusCounts.pending??0)===0,Kt=it.map((Gn,Ds)=>{let $s="upcoming";return(ut||Ds<Be)&&($s="completed"),Ds===Be&&!ut&&($s=tt?"warning":"current"),{name:Gn,status:$s}});A.push({id:S.id,name:S.name,status:ut?"completed":tt?"blocked":At?"paused":"active",rawStatus:ut?"completed":tt?"blocked":At?"paused":"active",category:ke,health:Math.max(0,Math.min(100,J)),phases:Kt,currentPhase:ut?it.length-1:Be,daysRemaining:0,targetDate:null,createdAt:S.latestEpoch>0?new Date(S.latestEpoch).toISOString():null,updatedAt:S.latestEpoch>0?new Date(S.latestEpoch).toISOString():null,activeAgents:S.activeAgents.size,totalAgents:S.allAgents.size,avatars:Array.from(S.activeAgents).slice(0,3),description:`${S.workstreams.size} workstreams are active right now.`,workstreams:Array.from(S.workstreams.entries()).map(([Gn,Ds])=>({id:Gn,name:Ds,status:"active"}))})}return A.sort((S,J)=>{const ke=S.status==="blocked"?0:S.status==="active"?1:2,it=J.status==="blocked"?0:J.status==="active"?1:2;return ke!==it?ke-it:J.health-S.health})},[ee,j.sessions.groups]),Ls=o.useMemo(()=>{const m=(S,J)=>{var ke,it;return{...S,...J,health:J.health>0?J.health:S.health,activeAgents:Math.max(S.activeAgents,J.activeAgents),totalAgents:Math.max(S.totalAgents,J.totalAgents),avatars:(ke=S.avatars)!=null&&ke.length?S.avatars:J.avatars,workstreams:(it=S.workstreams)!=null&&it.length?S.workstreams:J.workstreams,description:S.description??J.description,rawStatus:J.rawStatus??S.rawStatus??null,targetDate:J.targetDate??S.targetDate??null,createdAt:J.createdAt??S.createdAt??null,updatedAt:J.updatedAt??S.updatedAt??null}},A=new Map;for(const S of Vt)A.set(S.id,S);for(const S of[...xn??[],...ns??[]]){if(!V&&Cs(S.id)){A.delete(S.id);continue}const J=S.rawStatus??S.status;if(!dl(J)){A.delete(S.id);continue}const ke=A.get(S.id);A.set(S.id,ke?m(ke,S):S)}const P=new Set(ss);return Array.from(A.values()).filter(S=>!P.has(S.id)).filter(S=>dl(S.rawStatus??S.status)).sort((S,J)=>{const ke=At=>At==="blocked"?0:At==="active"?1:At==="paused"?2:3,it=ke(S.status)-ke(J.status);if(it!==0)return it;const Be=cl(S.priority)-cl(J.priority);if(Be!==0)return Be;const tt=on(J.updatedAt)-on(S.updatedAt);if(tt!==0)return tt;const ut=J.health-S.health;return ut!==0?ut:S.name.localeCompare(J.name)})},[Vt,ns,V,xn,ss]),Js=o.useMemo(()=>{if(!vt)return null;const m=vt.agentName,A=vt.title;if(m){const P=de.find(S=>{var J;return S.runId===vt.runId&&((J=S.summary)==null?void 0:J.trim())});if(P!=null&&P.summary){const S=P.summary.trim().length>40?P.summary.trim().slice(0,40)+"…":P.summary.trim();return`${m}: ${S}`}return m}if(A){const P=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(P.length>0)return P}return A??null},[de,vt]),En=o.useMemo(()=>{const m=new Map;for(const A of ee){const P=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,S=(A.agentName??"").trim()||(A.agentId??"").trim();if(!S)continue;const J=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),ke=on(J),it=ke?Math.max(0,Math.floor((Date.now()-ke)/6e4)):0,Be=m.get(P),tt={id:P,name:S,role:"Agent",status:wh(A.status),task:A.title??null,progress:A.progress??null,lastActive:J,lastActiveMinutes:it};(!Be||on(tt.lastActive)>on(Be.lastActive))&&m.set(P,tt)}return Array.from(m.values())},[ee]),R=o.useCallback(async()=>{if(ee.length===0){T("No sessions available to continue.");return}const m=[...ee].sort(ca)[0];if(ge(m.id),Ne(m.id),$(null),z(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{}T(`Focused highest priority session: ${m.title}`),await p()},[ee,p]),Rn=o.useCallback(async(m,A)=>{const P=await m.json().catch(()=>null),S=typeof(P==null?void 0:P.error)=="string"&&P.error.trim()||typeof(P==null?void 0:P.message)=="string"&&P.message.trim()||`${A} (${m.status})`;return/unknown api endpoint/i.test(S)?`${A}. This route is unavailable in the running plugin build.`:Lt(S)},[]),Jt=o.useCallback((m,A)=>!m||m.trim().length===0?A:Lt(m.trim())||A,[]),Ln=o.useCallback(async()=>{const m=ll(bt.items);if(!m){T("No startable Next Up workstream is available."),x("mission-control");return}await bt.playWorkstream({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId}),Ne(null),$(m.workstreamId),z(m.workstreamTitle),Z(null),T(`Dispatched Next Up: ${m.workstreamTitle}`),await Promise.all([bt.refetch(),p()])},[p,bt,x]),Vn=o.useCallback(async()=>{const m=ll(bt.items);if(!m){T("No startable initiative is ready for Autopilot yet."),x("mission-control");return}await Ut.move({initiativeId:m.initiativeId,workstreamId:m.workstreamId,placement:"top"}),await bt.startWorkstreamAutoContinue({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId,scope:"initiative"}),Ne(null),$(m.workstreamId),z(m.workstreamTitle),Z(null),T(`Autopilot started for ${m.initiativeTitle}; queued from ${m.workstreamTitle}.`),await Promise.all([bt.refetch(),p()])},[p,Ut,bt,x]),Ys=o.useCallback(async()=>{ie(!0);try{if(!hn){await Vn();return}await bt.stopInitiativeAutoContinue({initiativeId:hn.initiativeId}),T(`Autopilot stopped for ${hn.initiativeTitle}.`),await Promise.all([bt.refetch(),p()])}finally{ie(!1)}},[hn,p,bt,Vn]),os=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),P=(m.workstreamId??"").trim();if(!A||!P)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:P,agentId:m.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok)throw new Error(await Rn(S,"Failed to dispatch workstream from In Progress"));Ne(null),$(P),z(m.title),T(`Dispatched ${m.title}.`),await Promise.all([bt.refetch(),p()])},[Rn,p,bt]),Ve=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),P=(m.workstreamId??"").trim();if(!A||!P)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:P,placement:"bottom",resetToTodo:!1})});if(!S.ok){const J=await Rn(S,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(J))throw new Error(J);const ke=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!ke.ok)throw new Error(await Rn(ke,"Failed to pause workstream using legacy fallback"))}T(`Paused ${m.title} and sent it to the bottom of queue.`),await Promise.all([bt.refetch(),p()])},[Rn,p,bt]),Dn=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 P=m.text.trim();if(Nh(P)){Ht("agents",{focusAgentDomain:"engineering"}),T("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:P,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!S.ok)throw new Error(await Rn(S,"Failed to submit intervention"));T(`Intervention sent for ${m.session.title}.`),await p()},[Ht,Rn,p]),re=o.useCallback(async m=>{if(ge(m.id),Ne(m.id),$(null),z(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{}T(`Dispatch requested: ${m.title}`),await p()},[p]),Yt=o.useCallback(async(m,A,P={})=>{const S=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!S.ok){const J=await S.json().catch(()=>null);throw new Error((J==null?void 0:J.error)??`${A} failed (${S.status})`)}},[]),ls=o.useCallback(async m=>{var J;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 ke=await A.json().catch(()=>null);throw new Error((ke==null?void 0:ke.error)??`Checkpoint creation failed (${A.status})`)}const P=await A.json().catch(()=>null),S=P&&"data"in P&&((J=P.data)==null?void 0:J.id)||P&&"id"in P&&P.id||null;T(S?`Checkpoint created: ${S.slice(0,8)}`:"Checkpoint created."),await p()},[p]),Zs=o.useCallback(async m=>{await Yt(m,"pause",{reason:"pause_from_dashboard"}),T(`Pause requested: ${m.title}`),await p()},[p,Yt]),Mr=o.useCallback(async m=>{await Yt(m,"resume",{reason:"resume_from_dashboard"}),T(`Resume requested: ${m.title}`),await p()},[p,Yt]),$t=o.useCallback(async m=>{await Yt(m,"cancel",{reason:"restart_from_in_progress"}),await os(m),T(`Restarted ${m.title}.`),await p()},[os,p,Yt]),L=o.useCallback(async m=>{await Yt(m,"cancel",{reason:"cancel_from_dashboard"}),T(`Cancel requested: ${m.title}`),await p()},[p,Yt]),Et=o.useCallback(async m=>{var it;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const Be=await A.json().catch(()=>null);throw new Error((Be==null?void 0:Be.error)??`Checkpoint list failed (${A.status})`)}const P=await A.json().catch(()=>null),ke=(it=(Array.isArray(P)?P:Array.isArray(P==null?void 0:P.data)?P.data:[]).map(Be=>({id:typeof Be.id=="string"?Be.id:"",createdAt:typeof Be.createdAt=="string"?Be.createdAt:typeof Be.created_at=="string"?Be.created_at:""})).filter(Be=>Be.id.length>0).sort((Be,tt)=>Date.parse(tt.createdAt)-Date.parse(Be.createdAt))[0])==null?void 0:it.id;if(!ke)throw new Error("No checkpoint available for rollback.");await Yt(m,"rollback",{checkpointId:ke,reason:"rollback_from_dashboard"}),T(`Rollback requested for ${m.title}.`),await p()},[p,Yt]),er=o.useCallback(async()=>{var P;if(!Dt||tn.trim().length===0||Wn)return;E(!0);const m=Dt.type,A=tn.trim();try{const S={type:m,title:A,status:"active"};if(m==="workstream"){const ke=Dt.initiativeId??(St==null?void 0:St.initiativeId)??((P=Vt[0])==null?void 0:P.id)??null;if(!ke){T("Select an initiative first to start a workstream."),E(!1);return}S.initiative_id=ke,S.parentId=ke}const J=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!J.ok){const ke=await J.json().catch(()=>null);throw new Error((ke==null?void 0:ke.error)??`Failed to create ${m}.`)}T(`Created ${m}: ${A}`),me(),await p()}catch(S){T(Jt(S instanceof Error?S.message:"",`Failed to create ${m}.`)),E(!1)}},[me,Wn,Dt,tn,Vt,p,St==null?void 0:St.initiativeId]),Kn=o.useCallback(()=>{oe("initiative")},[oe]),tr=o.useCallback(m=>{oe("workstream",m)},[oe]);o.useCallback(()=>{var m;return tr((St==null?void 0:St.initiativeId)??((m=Vt[0])==null?void 0:m.id)??null)},[Vt,St==null?void 0:St.initiativeId,tr]);const nr=o.useCallback(m=>{const A=[...ee].filter(P=>(P.initiativeId??P.groupId)===m.id).sort(ca)[0];A&&(ge(A.id),Ne(A.id),$(null),z(null),T(`Focused initiative: ${m.name}`))},[ee]),sr=o.useCallback(m=>{const A=Vt.find(P=>P.id===m)??Ls.find(P=>P.id===m)??null;A&&nr(A)},[nr,Vt,Ls]),Ye=o.useCallback(m=>{const A=(m??"").trim();x("activity"),B("initiatives"),q("initiatives"),_e("in_progress"),Pe("needs_attention"),O(A.length>0?A:null),T(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[x]),rr=o.useCallback(m=>{const A=new Set,P=(m.runId??"").trim();P.length>0&&A.add(P),A.add(m.sliceRunId);const S=new Map;for(const tt of de){const ut=la(tt),At=bh(tt);(ut&&A.has(ut)||At&&At===m.sliceRunId)&&S.set(tt.id,tt)}const J=Array.from(S.values()),ke=tt=>{const ut=tt.type.trim().toLowerCase();let At=0;return(ut==="decision_requested"||ut==="blocker_created")&&(At+=80),(ut==="run_failed"||ut==="autopilot_stopped")&&(At+=70),(ut.includes("slice_completed")||ut.includes("completed"))&&(At+=60),ut.includes("artifact")&&(At+=55),(ut.includes("progress")||ut.includes("update"))&&(At+=35),At+=Math.floor(on(tt.timestamp)/1e3),At};J.sort((tt,ut)=>ke(ut)-ke(tt));const it=J[0]??null;x("activity"),q("activity"),B("initiatives");const Be=(P?ee.find(tt=>tt.runId===P||tt.id===P)??null:null)??(m.initiativeId&&m.workstreamId?ee.find(tt=>tt.initiativeId===m.initiativeId&&tt.workstreamId===m.workstreamId)??null:null);if(Be?(ge(Be.id),Ne(Be.id),$(null),z(null)):m.workstreamId&&(Ne(null),$(m.workstreamId),z(m.workstreamTitle??"Work slice")),it!=null&&it.id){fe(it.id),T(`Reviewing activity for ${m.workstreamTitle??"work slice"}.`);return}if(m.primaryAction==="resolve_decision"){Ye();return}if(P.length>0){dt(P),T("Opened the related work session. Timeline details were unavailable.");return}T("No activity details were found for this slice yet.")},[de,dt,Ye,ee,x]);return o.useCallback(m=>{const A=new Set(m),P=[...ee].filter(S=>A.has(S.status)).sort(ca)[0];if(!P){T("No matching sessions for that metric right now.");return}ze(P.id),q("activity")},[ee,ze]),o.useCallback(m=>{c==="activity"&&(m==="sessions"||m==="active"||m==="blocked"||m==="failed"||m==="decisions"||m==="outbox"||m==="handoffs")&&We(m)},[c]),w?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:D.background},children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-2.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"shimmer-skeleton h-6 w-6 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-28 rounded-md"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-14 rounded-full"})]}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Array.from({length:4}).map((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:D.background},children:[typeof window<"u"&&window.location.port==="5173"&&n.jsx("div",{className:"absolute left-1/2 top-4 z-30 -translate-x-1/2",children:n.jsxs("div",{className:"rounded-full border border-strong bg-white/[0.06] px-4 py-2 text-caption text-primary shadow-[0_10px_30px_rgba(0,0,0,0.35)] backdrop-blur",children:["Dev preview on 5173. Installed plugin runs on OpenClaw port"," ",n.jsx("a",{href:"http://127.0.0.1:18789/orgx/live/",className:"text-white underline underline-offset-4 hover:text-secondary",children:"18789"}),"."]})}),n.jsxs("header",{className:"relative z-[180] border-b border-subtle px-4 py-1.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2.5 lg:grid lg:grid-cols-[1fr_auto_1fr]",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[n.jsx(Lh,{}),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(_u,{color:fh[j.connection],pulse:j.connection==="connected",title:[`Status: ${sl[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: ${gh(j.lastSnapshotAt)}`,vn?`Details: ${vn.message}`:null].filter(Boolean).join(`
|
|
212
|
-
`),children:sl[j.connection]??"Unknown"}),(Tn>0||is>0)&&n.jsx(Co,{className:"hidden md:flex",running:Tn,blocked:is,decisionsCount:we?j.decisions.length:0,completedToday:Es,onDecisionsClick:()=>{x("activity"),B("initiatives"),q("initiatives"),_e("in_progress"),Pe("needs_attention")},onBlockedClick:()=>{Ce.length>0?(x("mission-control"),_e("in_progress"),Pe("needs_attention")):We("blocked")},onNewInitiative:Kn})]}),n.jsx("div",{className:"hidden items-center justify-center lg:flex",children:n.jsxs("div",{className:"flex rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>x("activity"),"aria-pressed":c==="activity",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${c==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>x("mission-control"),onMouseEnter:zn,onFocus:zn,"aria-pressed":c==="mission-control",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${c==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})}),n.jsxs("div",{className:"relative isolate flex items-center justify-end gap-1.5 sm:gap-2",children:[n.jsxs("div",{className:"relative hidden md:block",children:[n.jsx("label",{htmlFor:"workspace-switcher",className:"sr-only",children:"Workspace scope"}),n.jsxs("select",{id:"workspace-switcher",value: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: ${h}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),v.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:()=>{ts(!1),gn()},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:Ee,onClick:()=>Ie(m=>!m),title:"Notifications","aria-haspopup":"dialog","aria-expanded":he,"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"})]}),as.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:as.length})]}),a?n.jsx("button",{type:"button",onClick:()=>Ze(!0),title:"Realtime orchestrator",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 18a2.5 2.5 0 0 0 2.5-2.5v-7a2.5 2.5 0 1 0-5 0v7A2.5 2.5 0 0 0 12 18z"}),n.jsx("path",{d:"M6 12.5v2a6 6 0 0 0 12 0v-2"}),n.jsx("path",{d:"M12 20.5v2"})]})}):null,n.jsx("button",{type:"button",onClick:()=>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:p,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"})]}),he&&n.jsxs("div",{id:"header-notifications-panel",ref:et,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:[as.length>0&&n.jsx("button",{type:"button",onClick:Qs,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>Ie(!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(Co,{className:"max-w-full overflow-hidden",running:Tn,blocked:is,decisionsCount:Xs,completedToday:Es,onDecisionsClick:()=>{x("activity"),q("initiatives"),B("initiatives"),_e("in_progress"),Pe("needs_attention"),Ie(!1)},onBlockedClick:()=>{Ce.length>0?(x("mission-control"),_e("in_progress"),Pe("needs_attention")):We("blocked"),Ie(!1)}})}),as.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:Rs>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:as.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(ln,{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),Ie(!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:()=>Ni(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: ${h}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),v.map(m=>n.jsx("option",{value:m.id,children:m.title},m.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})]}),n.jsxs("div",{className:"flex w-full max-w-[248px] rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>x("activity"),"aria-pressed":c==="activity",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${c==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>x("mission-control"),"aria-pressed":c==="mission-control",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${c==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})]})]}),c==="mission-control"?n.jsx("div",{className:"relative z-0 flex-1 min-h-0 flex flex-col overflow-hidden",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"flex flex-1 items-center justify-center text-body text-secondary",children:"Loading Mission Control…"}),children:n.jsx(eh,{initiatives:Ls,activities:de,agents:En,runtimeInstances:j.runtimeInstances??[],workspaceInitiativeId:u,isLoading:w,authToken:null,embedMode:!1,connection:j.connection,lastSnapshotAt:j.lastSnapshotAt,error:k,hasApiKey:e.state.hasApiKey,devMode:a,onOpenSettings:()=>Ht("orgx"),onRefresh:p,onCreateInitiative:Kn,onPlayNextUp:Ln,onStartAutopilot:Vn,nextUpQueueModel:bt,nextUpActionsModel:Ut,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(xp,{sessions:j.sessions,activity:de,runtimeInstances:j.runtimeInstances??[],showSyntheticEntities:t||r,selectedSessionId:je,onSelectSession:ze,onAgentFilter:Z,agentFilter:W,timeFilterId:K,onReconnect:gn,onLaunched:p,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(Zf,{activity:Hn.items,sessions:ee,sliceRuns:Ce,initiatives:Vt,timelineNarrative:j.timelineNarrative??[],workspaceId:u,chatSnapshot:j.chat,devMode:a,selectedRunIds:gt,selectedSessionLabel:Js,selectedWorkstreamId:se,selectedWorkstreamLabel:H,agentFilter:W,timeFilterId:K,onTimeFilterChange:bs,customTimeRange:xe,onCustomTimeRangeChange:Se,hasMore:Hn.hasMore,isLoadingMore:Hn.isLoadingMore,onLoadMore:Hn.loadMore,onClearSelection:$e,onClearWorkstreamFilter:ft,onClearAgentFilter:ht,onFocusRunId:dt,onOpenDecision:Ye,requestedActivityItemId:Te,onActivityItemRequestHandled:()=>fe(null),onPlayNextUp:Ln,onStartAutopilot:Vn,onPauseWorkstream:Ve,onCreateInitiative:Kn,onOpenMissionControl:()=>x("mission-control"),onOpenNextUp:()=>x("mission-control"),onOpenSettings:()=>Ht("orgx"),onRefreshData:p,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 ${Re==="initiatives"?"flex-1":"flex-shrink-0"} `,children:Re==="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 py-2.5",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-3 overflow-x-auto",children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":Q==="in_progress",onClick:m=>{m.stopPropagation(),_e("in_progress")},className:ce("relative inline-flex h-8 items-center gap-1.5 px-0.5 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:ot}),n.jsx("span",{className:ce("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(),_e("next_up")},className:ce("relative inline-flex h-8 items-center gap-1.5 px-0.5 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:Mn.total}),n.jsx("span",{className:ce("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:()=>{Ys().catch(m=>{T(Jt(m instanceof Error?m.message:"","Autopilot action failed."))})},disabled:F,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":cn?"active":"idle",title:cn?"Stop autopilot":"Start autopilot","aria-label":cn?"Stop autopilot":"Start autopilot",children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:ce("h-3.5 w-3.5",cn?"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:ce("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",cn?"bg-[#BFFF00]/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:cn?"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:()=>Pe("all"),className:ce("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",De==="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:ot})]}),n.jsxs("button",{type:"button",onClick:()=>Pe("needs_attention"),className:ce("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",De==="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:Nt})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:Q==="in_progress"?De==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[_n.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(sh,{model:_n,actions:Bn,onOpenDetail:qn})})}),we?n.jsxs("section",{className:ce("overflow-hidden rounded-xl border border-subtle bg-white/[0.02]",Ge.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(nh,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:j.decisions,focusDecisionId:C,onFocusDecisionHandled:()=>O(null),onApproveDecision:_,onRejectDecision:U,onApproveAll:ae,onBulkDecisionAction:G,mutationState:ve})})})]}):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:ce("flex min-h-[180px] flex-1 flex-col overflow-hidden rounded-xl border border-subtle bg-white/[0.02]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:we?"Blocked & review-required slices":"Needs attention"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:Ge.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(ym,{className:ce("h-full min-h-0"),title:we?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:Ce,initiatives:Vt,onOpenDecisions:()=>Ye(),onFocusRunId:dt,onReviewActivity:rr,onOpenSliceDetail:pn})})]})]}):n.jsx(om,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:ee,sliceRuns:Ce,initiatives:Vt,needsAttentionCount:Nt,onSwitchToNeedsAttention:()=>Pe("needs_attention"),onOpenSession:ze,onFocusRunId:dt,onPlayWorkstream:os,onPauseWorkstream:Ve,onResumeWorkstream:os,onRestartSession:$t,onIntervene:Ms,onOpenSliceDetail:Qt}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(ih,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:bt,queueActions:Ut,snapshotVersion:j.snapshotVersion,excludeRunning:!0,onOpenInitiative:sr,onOpenSliceDetail:Wt})})},`${Q}:${De}`)]}):n.jsx(Hs,{className:"card-enter",children:n.jsxs("button",{onClick:()=>B("initiatives"),className:"flex w-full items-center justify-between px-4 py-3 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("h2",{className:"text-heading font-semibold text-white",children:"Initiatives"})}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"-rotate-90 text-muted",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})})})})]}),n.jsx(yt,{children:He&&St&&n.jsxs(n.Fragment,{children:[n.jsx(pe.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:()=>ue(!1)},"session-drawer-backdrop"),n.jsx(pe.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:400,damping:35},className:"glass-panel soft-shadow fixed bottom-0 right-0 top-[64px] z-[250] hidden w-[480px] flex-col lg:flex",style:{backgroundColor:D.cardBg,borderLeft:"1px solid rgba(255,255,255,0.08)"},children:n.jsx("div",{className:"flex-1 min-h-0",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading session detail…"}),children:n.jsx(th,{session:St,activity:de,initiatives:Vt,sliceRuns:Ce,initialInterventionDraft:ne,onSubmitIntervention:Dn,onOpenActivityItem:Ts,onContinueHighestPriority:R,onDispatchSession:re,onPauseSession:Zs,onResumeSession:Mr,onCancelSession:L,onCreateCheckpoint:ls,onRollbackSession:Et,onStartInitiative:Kn,onStartWorkstream:tr,onClose:()=>ue(!1)})})})},"session-drawer-panel")]})}),c==="activity"?n.jsx(Mu,{activeTab:Ae,onTabChange:Le,pendingDecisionCount:we?j.decisions.length:0}):null,n.jsx(vi,{open:Dt!==null,onClose:me,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:(Dt==null?void 0:Dt.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(Dt==null?void 0:Dt.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:tn,onChange:m=>rs(m.target.value),onKeyDown:m=>{m.key==="Enter"&&er()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(Dt==null?void 0:Dt.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:me,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:er,disabled:tn.trim().length===0||Wn,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:Wn?"Creating…":"Create"})]})]})}),qe.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(ah,{open:qe.open,onClose:()=>pt(m=>({...m,open:!1,focusAgentDomain:null})),activeTab:qe.tab,onChangeTab:m=>pt(A=>({...A,tab:m})),agentBehaviorInitialDomain:qe.focusAgentDomain,demoMode:t,onToggleDemoMode:m=>{ts(m),m||gn()},devMode:a,onToggleDevMode:l,showSyntheticEntities:r,onToggleShowSyntheticEntities:i,workspaceOptions:v,selectedWorkspaceId:u,onSelectWorkspace:g,onboarding:e,authToken:null,embedMode:!1})}),a&&at&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(ph,{open:at,selectedWorkspaceId:u,onClose:()=>Ze(!1)})}),(ye==="sessions"||ye==="active"||ye==="blocked"||ye==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(oh,{open:ye==="sessions"||ye==="active"||ye==="blocked"||ye==="failed",onClose:()=>We(null),mode:ye==="active"||ye==="blocked"||ye==="failed"?ye:"sessions",sessions:ee,onOpenSession:m=>{ze(m.id),We(null)},onRunAction:async(m,A)=>{await Yt(m,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>p(),onSetNotice:m=>T(m)})}),ye==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(lh,{open:ye==="decisions",onClose:()=>We(null),decisions:we?j.decisions:[],onApproveDecision:_,onRejectDecision:U,onApproveAll:ae,onBulkDecisionAction:G})}),ye==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(ch,{open:ye==="outbox",onClose:()=>We(null),outbox:j.outbox,onOpenSettings:()=>{We(null),Ht("orgx")},onRefresh:()=>{p()}})}),ye==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(dh,{open:ye==="handoffs",onClose:()=>We(null),handoffs:j.handoffs})}),n.jsx(Dh,{}),It&&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(rh,{item:It,actions:Bn,onClose:()=>Tt(null),onNavigate:Cn,currentIndex:en,totalCount:ct.length,decisions:we?j.decisions:void 0,onApproveDecision:_,onRejectDecision:U})})})}),Je&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(mh,{target:Je,initiatives:Vt,onClose:()=>Ct(null),onPlayWorkstream:async(m,A,P)=>{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:P??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const J=await S.json().catch(()=>null);T(Jt((J==null?void 0:J.error)??(J==null?void 0:J.message)??null,`Failed to dispatch workstream (${S.status})`));return}T("Dispatched workstream."),p()},onStartAutoContinue:async(m,A,P)=>{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:P??void 0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const J=await S.json().catch(()=>null);T(Jt((J==null?void 0:J.error)??(J==null?void 0:J.message)??null,`Failed to start auto-continue (${S.status})`));return}T("Auto-continue started."),p()},onMoveWorkstream:async(m,A,P)=>{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:P})});if(!S.ok){const J=await S.json().catch(()=>null);T(Jt((J==null?void 0:J.error)??(J==null?void 0:J.message)??null,`Move failed (${S.status})`));return}T(`Moved workstream to ${P}.`),p()},onRemoveFromQueue:async(m,A)=>{const P=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A})});if(!P.ok){const S=await P.json().catch(()=>null);T(Jt((S==null?void 0:S.error)??(S==null?void 0:S.message)??null,`Remove failed (${P.status})`));return}T("Removed workstream from queue."),p()},onOpenSession:ze,onFocusRunId:dt,onOpenInitiative:sr,onReviewActivity:rr,onOpenDecisions:()=>Ye(),onAcceptSlice:fn,onRejectSlice:xs})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});Id();const Fh=new cc({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});lc.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(dc,{client:Fh,children:n.jsx(Th,{})})}));export{Gh as $,Ot as A,ce as B,Bt as C,On as D,ln as E,us as F,Jd as G,Xh as H,tg as I,Qh as J,Yh as K,cs as L,pi as M,ms as N,_p as O,Hs as P,Kh as Q,Is as R,Nn as S,ki as T,Ed as U,fu as V,hu as W,wu as X,ju as Y,Zh as Z,Ic as _,Rd as a,Gu as a0,eg as a1,Or as a2,Fu as a3,Km as a4,Vh as a5,cr as a6,oi as a7,_t as b,vm as c,ud as d,D as e,ag as f,zm as g,Lt as h,Ft as i,js as j,ng as k,$l as l,Pt as m,qt as n,rg as o,Fi as p,Zn as q,Mt as r,og as s,km as t,Zd as u,ig as v,sg as w,Jh as x,vi as y,gs as z};
|