@useorgx/openclaw-plugin 0.7.6 → 0.7.11
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/{CnitK1MX.js → AqVoI3SF.js} +1 -1
- package/dashboard/dist/assets/AqVoI3SF.js.br +0 -0
- package/dashboard/dist/assets/AqVoI3SF.js.gz +0 -0
- package/dashboard/dist/assets/BC4WvnHJ.js +1 -0
- package/dashboard/dist/assets/BC4WvnHJ.js.br +0 -0
- package/dashboard/dist/assets/BC4WvnHJ.js.gz +0 -0
- package/dashboard/dist/assets/{DOFL9l8s.js → BG5mwTkg.js} +1 -1
- package/dashboard/dist/assets/BG5mwTkg.js.br +0 -0
- package/dashboard/dist/assets/BG5mwTkg.js.gz +0 -0
- package/dashboard/dist/assets/BNh-XYPV.js +1 -0
- package/dashboard/dist/assets/BNh-XYPV.js.br +0 -0
- package/dashboard/dist/assets/BNh-XYPV.js.gz +0 -0
- package/dashboard/dist/assets/{CFwPph5U.js → BepW_590.js} +1 -1
- package/dashboard/dist/assets/BepW_590.js.br +0 -0
- package/dashboard/dist/assets/BepW_590.js.gz +0 -0
- package/dashboard/dist/assets/BerAfzjq.js +1 -0
- package/dashboard/dist/assets/BerAfzjq.js.br +0 -0
- package/dashboard/dist/assets/BerAfzjq.js.gz +0 -0
- package/dashboard/dist/assets/Bp3N-QL5.js +212 -0
- package/dashboard/dist/assets/Bp3N-QL5.js.br +0 -0
- package/dashboard/dist/assets/Bp3N-QL5.js.gz +0 -0
- package/dashboard/dist/assets/C3dZRz9P.css +1 -0
- package/dashboard/dist/assets/C3dZRz9P.css.br +0 -0
- package/dashboard/dist/assets/C3dZRz9P.css.gz +0 -0
- package/dashboard/dist/assets/CD-q5mdP.js +1 -0
- package/dashboard/dist/assets/CD-q5mdP.js.br +0 -0
- package/dashboard/dist/assets/CD-q5mdP.js.gz +0 -0
- package/dashboard/dist/assets/{BgcAY5rE.js → CdvjC9G9.js} +1 -1
- package/dashboard/dist/assets/CdvjC9G9.js.br +0 -0
- package/dashboard/dist/assets/CdvjC9G9.js.gz +0 -0
- package/dashboard/dist/assets/Ck2agw-s.js +1 -0
- package/dashboard/dist/assets/Ck2agw-s.js.br +0 -0
- package/dashboard/dist/assets/Ck2agw-s.js.gz +0 -0
- package/dashboard/dist/assets/{D7DHFX0D.js → D2CH1H6k.js} +1 -1
- package/dashboard/dist/assets/D2CH1H6k.js.br +0 -0
- package/dashboard/dist/assets/D2CH1H6k.js.gz +0 -0
- package/dashboard/dist/assets/D9esz7jd.js +1 -0
- package/dashboard/dist/assets/D9esz7jd.js.br +0 -0
- package/dashboard/dist/assets/D9esz7jd.js.gz +0 -0
- package/dashboard/dist/assets/{77gGFBt6.js → DCP-C7fn.js} +1 -1
- package/dashboard/dist/assets/DCP-C7fn.js.br +0 -0
- package/dashboard/dist/assets/DCP-C7fn.js.gz +0 -0
- package/dashboard/dist/assets/{CSr2ZnTV.js → DJASCd69.js} +1 -1
- package/dashboard/dist/assets/DJASCd69.js.br +0 -0
- package/dashboard/dist/assets/DJASCd69.js.gz +0 -0
- package/dashboard/dist/assets/Dm9AybAp.js +1 -0
- package/dashboard/dist/assets/Dm9AybAp.js.br +0 -0
- package/dashboard/dist/assets/Dm9AybAp.js.gz +0 -0
- package/dashboard/dist/assets/{DxKG5zy8.js → Du1wfrXa.js} +1 -1
- package/dashboard/dist/assets/Du1wfrXa.js.br +0 -0
- package/dashboard/dist/assets/Du1wfrXa.js.gz +0 -0
- package/dashboard/dist/assets/{DpuQm1oF.js → beHYBbh6.js} +1 -1
- package/dashboard/dist/assets/beHYBbh6.js.br +0 -0
- package/dashboard/dist/assets/beHYBbh6.js.gz +0 -0
- package/dashboard/dist/index.html +2 -2
- package/dashboard/dist/index.html.br +0 -0
- package/dashboard/dist/index.html.gz +0 -0
- package/dist/hash-utils.js +2 -1
- package/dist/http/helpers/auto-continue-engine.d.ts +36 -0
- package/dist/http/helpers/auto-continue-engine.js +83 -17
- package/dist/http/helpers/autopilot-runtime.d.ts +1 -0
- package/dist/http/helpers/autopilot-runtime.js +31 -3
- package/dist/http/helpers/autopilot-slice-utils.d.ts +10 -0
- package/dist/http/helpers/autopilot-slice-utils.js +58 -0
- package/dist/http/helpers/humanize-slice-failure.d.ts +35 -0
- package/dist/http/helpers/humanize-slice-failure.js +137 -0
- package/dist/http/helpers/mission-control.d.ts +1 -0
- package/dist/http/helpers/mission-control.js +72 -5
- package/dist/http/index.js +65 -3
- package/dist/http/routes/live-misc.js +12 -4
- package/dist/http/routes/live-snapshot.js +10 -4
- package/dist/http/routes/mission-control-actions.js +5 -0
- package/dist/http/routes/mission-control-read.d.ts +1 -0
- package/dist/http/routes/mission-control-read.js +65 -4
- package/dist/index.d.ts +8 -1
- package/dist/index.js +21 -1
- package/dist/mcp-http-handler.js +6 -0
- package/dist/openclaw.plugin.json +1 -1
- package/dist/tools/core-tools.d.ts +27 -0
- package/dist/tools/core-tools.js +89 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/dashboard/dist/assets/77gGFBt6.js.br +0 -0
- package/dashboard/dist/assets/77gGFBt6.js.gz +0 -0
- package/dashboard/dist/assets/BBpTN_SR.js +0 -1
- package/dashboard/dist/assets/BBpTN_SR.js.br +0 -0
- package/dashboard/dist/assets/BBpTN_SR.js.gz +0 -0
- package/dashboard/dist/assets/BVShoyjA.js +0 -1
- package/dashboard/dist/assets/BVShoyjA.js.br +0 -0
- package/dashboard/dist/assets/BVShoyjA.js.gz +0 -0
- package/dashboard/dist/assets/BgcAY5rE.js.br +0 -0
- package/dashboard/dist/assets/BgcAY5rE.js.gz +0 -0
- package/dashboard/dist/assets/C-PAoJF-.js +0 -1
- package/dashboard/dist/assets/C-PAoJF-.js.br +0 -0
- package/dashboard/dist/assets/C-PAoJF-.js.gz +0 -0
- package/dashboard/dist/assets/C0nA-iUG.js +0 -1
- package/dashboard/dist/assets/C0nA-iUG.js.br +0 -0
- package/dashboard/dist/assets/C0nA-iUG.js.gz +0 -0
- package/dashboard/dist/assets/C6GO-FKy.js +0 -1
- package/dashboard/dist/assets/C6GO-FKy.js.br +0 -0
- package/dashboard/dist/assets/C6GO-FKy.js.gz +0 -0
- package/dashboard/dist/assets/CFwPph5U.js.br +0 -0
- package/dashboard/dist/assets/CFwPph5U.js.gz +0 -0
- package/dashboard/dist/assets/CPjsbbgZ.js +0 -212
- package/dashboard/dist/assets/CPjsbbgZ.js.br +0 -0
- package/dashboard/dist/assets/CPjsbbgZ.js.gz +0 -0
- package/dashboard/dist/assets/CSr2ZnTV.js.br +0 -0
- package/dashboard/dist/assets/CSr2ZnTV.js.gz +0 -0
- package/dashboard/dist/assets/CgQDT6yL.js +0 -1
- package/dashboard/dist/assets/CgQDT6yL.js.br +0 -0
- package/dashboard/dist/assets/CgQDT6yL.js.gz +0 -0
- package/dashboard/dist/assets/CnitK1MX.js.br +0 -0
- package/dashboard/dist/assets/CnitK1MX.js.gz +0 -0
- package/dashboard/dist/assets/D7DHFX0D.js.br +0 -0
- package/dashboard/dist/assets/D7DHFX0D.js.gz +0 -0
- package/dashboard/dist/assets/DEip7uko.js +0 -1
- package/dashboard/dist/assets/DEip7uko.js.br +0 -0
- package/dashboard/dist/assets/DEip7uko.js.gz +0 -0
- package/dashboard/dist/assets/DHUSLc01.css +0 -1
- package/dashboard/dist/assets/DHUSLc01.css.br +0 -0
- package/dashboard/dist/assets/DHUSLc01.css.gz +0 -0
- package/dashboard/dist/assets/DOFL9l8s.js.br +0 -0
- package/dashboard/dist/assets/DOFL9l8s.js.gz +0 -0
- package/dashboard/dist/assets/DpuQm1oF.js.br +0 -0
- package/dashboard/dist/assets/DpuQm1oF.js.gz +0 -0
- package/dashboard/dist/assets/DxKG5zy8.js.br +0 -0
- package/dashboard/dist/assets/DxKG5zy8.js.gz +0 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/D9esz7jd.js","assets/cNrhgGc1.js","assets/C-KIc3Wc.js","assets/BJgZIVUQ.js","assets/qm8xLgv-.css","assets/Ck2agw-s.js","assets/DCP-C7fn.js","assets/CxQ08qFN.js","assets/tcEHYcbW.js","assets/CD-q5mdP.js","assets/BC4WvnHJ.js","assets/DJASCd69.js","assets/AqVoI3SF.js","assets/Dm9AybAp.js","assets/CL_wXqR7.js","assets/BTAEErUY.js","assets/BerAfzjq.js","assets/Du1wfrXa.js","assets/BG5mwTkg.js","assets/D2CH1H6k.js","assets/beHYBbh6.js","assets/BepW_590.js","assets/BNh-XYPV.js","assets/CdvjC9G9.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Jl=Object.defineProperty;var Yl=(e,t,s)=>t in e?Jl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Bn=(e,t,s)=>Yl(e,typeof t!="symbol"?t+"":t,s);import{r as o,u as ga,a as ps,b as yn,j as n,c as Zl,d as ec,D as Da,e as tc,Q as nc}from"./cNrhgGc1.js";import{b as sc}from"./C-KIc3Wc.js";import{m as he,A as yt,u as Yn}from"./CxQ08qFN.js";import{F as rc,T as ic}from"./BJgZIVUQ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const 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 ac="modulepreload",oc=function(e){return"/orgx/live/"+e},$a={},Ut=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=oc(u),u in $a)return;$a[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":ac,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)})},Fa=()=>{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()}}},ki="all";function Qn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function lc(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return Qn(e.get("workspace_id"))??Qn(e.get("workspaceId"))??Qn(e.get("command_center_id"))??Qn(e.get("commandCenterId"))??Qn(e.get("center"))??Qn(e.get("project_id"))??Qn(e.get("projectId"))}catch{return null}}function fs(e,t,s){const r=Qn(t);if(!r){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",ki),e.set("command_center_id",ki),e.set("center",ki));return}e.set("workspace_id",r),e.set("command_center_id",r),e.set("center",r)}function cc(e){const t=Qn(e);return t?{"x-orgx-workspace-id":t}:{}}function At(e){const t={};e.contentTypeJson&&(t["Content-Type"]="application/json"),e.embedMode&&(t["X-Orgx-Embed"]="true"),e.authToken&&(t.Authorization=`Bearer ${e.authToken}`);const s=e.workspaceId??lc();return Object.assign(t,cc(s)),t}const dc=[[/opus/i,"Opus"],[/sonnet/i,"Sonnet"],[/haiku/i,"Haiku"],[/kimi/i,"Kimi"],[/gemini/i,"Gemini"],[/gpt-4o/i,"GPT-4o"],[/gpt-4/i,"GPT-4"],[/qwen/i,"Qwen"],[/deepseek/i,"DeepSeek"],[/llama/i,"Llama"]];function wr(e){if(!e)return"";for(const[s,r]of dc)if(s.test(e))return r;const t=e.split("/");return t[t.length-1]??e}const il=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,al=/^[0-9a-f]{20,}$/i;function cs(e){return il.test(e)?`#${e.slice(0,4)}`:al.test(e)?`#${e.slice(0,4)}`:e}function zn(e){return il.test(e)||al.test(e)}function _s(e,t=4){let s=e.replace(/^\/Users\/[^/]+\//,"~/").replace(/^~\/Code\//,"").replace(/^~\//,"");const r=s.split("/");return r.length>t&&(s=r.slice(-t).join("/")),s}function dt(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=>wr(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>_s(s)),t}function qt(e){let t=e;return t=t.replace(/\[?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\]?/gi,""),t=t.replace(/\[workstream\s*\]/gi,""),t=t.replace(/\[workstream\b[^\]]*\]/gi,""),t=t.replace(/\/var\/folders\/[^\s"']*/g,"(local file)"),t=t.replace(/\/tmp\/[^\s"']*/g,"(temp file)"),t=t.replace(/\/Users\/[^\s"']*/g,s=>_s(s)),t=t.replace(/telegram:\d+/g,"Telegram session"),t=t.replace(/discord:\d+/g,"Discord session"),t=t.replace(/\s{2,}/g," ").trim(),t||"Untitled session"}function xr(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 Pa(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function nr(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,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 Oa(e){const t=Pa(e);if(!t)return null;const s=Pa(t.error),r=s??t,i=nr(r,["message","detail","error_description"])??(s?null:nr(t,["error"])),a=nr(r,["code","error_code","type"]),l=uc(r,["status","httpStatusCode"]),c=nr(r,["requestId","request_id"]),d=nr(r,["docsUrl","docs_url"]);return!i&&!a&&l==null&&!c&&!d?null:{code:a,message:i,status:l,requestId:c,docsUrl:d}}function mc(e){var d,u;const t=e.trim();if(!t)return null;const s=(()=>{try{return JSON.parse(t)}catch{return null}})(),r=Oa(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=Oa(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 Ba(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 Rt(e){var c;const t=mc(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=Ba(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.":qt(dt(a))}function pc(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 fc(e){const t=e.metadata??{},s=Fs(t,"task_title")??Fs(t,"workstream_title"),r=s?qt(String(s)):e.title?qt(e.title):null,i=Fs(t,"user_summary")??Fs(t,"summary"),a=i?qt(String(i)):e.summary?qt(e.summary):e.description?qt(e.description):null,l=Fs(t,"next_step")??Fs(t,"nextStep"),c=l?qt(String(l)):null;return{taskDescription:r,outcomeDescription:a&&a===r?null:a,nextStep:c&&(c===r||c===a)?null:c}}function Fs(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const hc={auto_continue_stopped:"Autopilot paused",budget_exhausted:"Token budget reached",error:"Encountered an error",blocked:"Waiting for input",stopped:"Manually stopped",rate_limited:"Rate limited — retrying shortly",timeout:"Timed out",timed_out:"Timed out",cancelled:"Cancelled",completed:"Completed"};function sr(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return hc[t]??e.replace(/_/g," ")}const gc={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function $h(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return gc[t]??e.replace(/_/g," ")}function Fh(e,t){return e.toLowerCase().includes("path")?_s(t):zn(t)?cs(t):t.includes(",")?t.split(",").map(r=>{const i=r.trim();return zn(i)?cs(i):i}).join(", "):qt(t)}function xc(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 Ph(e){const t=xc(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function ni(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function _t(e){const s=(e instanceof Date?e:new Date(e)).getTime()-Date.now();if(Number.isNaN(s))return"unknown";const r=Math.floor(Math.abs(s)/1e3),i=s<0?"past":"future";if(r<10)return i==="past"?"just now":"soon";if(r<60)return i==="past"?`${r}s ago`:`in ${r}s`;const a=Math.floor(r/60);if(a<60)return i==="past"?`${a}m ago`:`in ${a}m`;const 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 yc=8e3,bc=320,wc=300,vc=80,kc=80,jc=120,qa=6e4,Nc=1200,Ic=90,Ac=3,Sc=24,za=24,rr=new WeakMap,xa={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},Mr={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Ms={threads:[],total:0,updatedAt:null},Wa={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},ol=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),Tr=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 Cc(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=>Rt(a)).filter(a=>a.length>0).join(" ")}function Mc(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 Rt(s.length>0?s:e.trim())}function Tc(e){const t=e.map(s=>Mc(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function ut(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function si(e,t){const s=Wa[e.status]??99,r=Wa[t.status]??99;if(s!==r)return s-r;const i=ut(e.updatedAt??e.lastEventAt??e.startedAt),a=ut(t.updatedAt??t.lastEventAt??t.startedAt);return i!==a?a-i:e.id.localeCompare(t.id)}function Ec(e){return(e??"").trim().toLowerCase()}function Ua(e){return ol.has(Ec(e.status))}function ji(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function Ha(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const h=Date.now(),v=e.nodes.filter(w=>{const k=ut(w.updatedAt??w.lastEventAt??w.startedAt);if(Ua(w))return!0;const _=["completed","archived","failed"].includes((w.status??"").toLowerCase())?Tr/3:Tr;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(si),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 ji(h))s.add(v);const i=Date.now(),a=[];for(const h of e.nodes){if(ji(h).some(m=>s.has(m)))continue;const y=ut(h.updatedAt??h.lastEventAt??h.startedAt),w=["completed","archived","failed"].includes((h.status??"").toLowerCase())?Tr/3:Tr,k=i-y<=w;if(Ua(h)||k){a.push(h),r.push(h);for(const m of ji(h))s.add(m)}}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(si),edges:b,groups:u}}function ir(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(si).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 Va(e,t){return e.length<=t?e:[...e].sort((s,r)=>ut(r.updatedAt)-ut(s.updatedAt)).slice(0,t)}function Rc(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()-ut(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 ll(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 Ka(e,t){if(e.nodes.length!==t.nodes.length||e.edges.length!==t.edges.length||e.groups.length!==t.groups.length)return!1;for(let s=0;s<e.nodes.length;s+=1){const r=e.nodes[s],i=t.nodes[s];if(r.id!==i.id||r.status!==i.status||r.title!==i.title||r.progress!==i.progress||r.updatedAt!==i.updatedAt||r.lastEventAt!==i.lastEventAt)return!1}for(let s=0;s<e.edges.length;s+=1){const r=e.edges[s],i=t.edges[s];if(r.parentId!==i.parentId||r.childId!==i.childId)return!1}for(let s=0;s<e.groups.length;s+=1){const r=e.groups[s],i=t.groups[s];if(r.id!==i.id||r.label!==i.label||r.status!==i.status)return!1}return!0}function Ga(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].updatedAt!==t[s].updatedAt||e[s].status!==t[s].status||e[s].title!==t[s].title)return!1;return!0}function Xa(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s].id!==t[s].id||e[s].status!==t[s].status||e[s].updatedAt!==t[s].updatedAt||e[s].waitingMinutes!==t[s].waitingMinutes)return!1;return!0}function cl(e){if(!e||typeof e!="object")return xa;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 Lc(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 ri(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=rr.get(r);if(i)return i;if(t>=Ac){const x=Array.isArray(e)?"[…]":"{…}";return rr.set(r,x),x}if(rr.set(r,Array.isArray(e)?"[]":"{}"),Array.isArray(e)){const x=e.slice(0,za).map(v=>ri(v,t+1)).join(","),b=e.length>za?",…":"",h=`[${x}${b}]`;return rr.set(r,h),h}const a=e,l=Object.keys(a).sort(),c=l.slice(0,Sc),d=c.map(x=>`${x}:${ri(a[x],t+1)}`).join("|"),u=l.length>c.length?"|…":"",g=`{${d}${u}}`;return rr.set(r,g),g}function Dc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function js(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}const $c=new Set(["autopilot_slice_result","auto_continue_started","auto_continue_stopped","next_up_manual_dispatch_started","autopilot_slice_mcp_handshake_failed","autopilot_slice_timeout","autopilot_slice_log_stall","auto_continue_spawn_guard_blocked","auto_continue_spawn_guard_rate_limited","autopilot_autofix_scheduled","autopilot_autofix_executed","autopilot_autofix_skipped"]);function Fc(e){const t=Dc(e.metadata),s=t==null?void 0:t.event,r=typeof s=="string"?s.trim().toLowerCase():"";if(!r||!$c.has(r))return null;const i=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??js(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=js(t,["correlation_id","correlationId"]),l=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??js(t,["initiative_id","initiativeId"]),c=js(t,["workstream_id","workstreamId"]),d=js(t,["task_id","taskId"]),u=js(t,["stop_reason","stopReason"]),g=js(t,["parsed_status","parsedStatus"]),x=(e.title??"").trim().toLowerCase();return!i&&!a&&!c&&!d?null:[r,l??"",c??"",d??"",i??"",a??"",u??"",g??"",x].join("|")}function dl(e,t){const s=new Set,r=new Set,i=[];for(const a of e){if(s.has(a.id))continue;s.add(a.id);const l=Fc(a);if(!(l&&r.has(l))&&(l&&r.add(l),i.push(a),i.length>=t))break}return i}function Pc(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,ri(d.metadata));let a=!1;for(const d of t){const u=r.get(d.id),g=ri(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=ut(u.timestamp)-ut(d.timestamp);return g!==0?g:u.id.localeCompare(d.id)}),c=dl(l,s);return ll(e,c)?e:c}function Ni(e,t){const s=[...e].sort((r,i)=>{const a=ut(i.timestamp)-ut(r.timestamp);return a!==0?a:i.id.localeCompare(r.id)});return dl(s,t)}function Qa(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(Rc).sort((a,l)=>a.waitingMinutes!==l.waitingMinutes?l.waitingMinutes-a.waitingMinutes:ut(l.requestedAt??l.updatedAt)-ut(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 Ja(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 Oc(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 Bc(e,t){return!!(ol.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function Er(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function Ii(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 qc(e,t,s){const r=new Map,i=[...e].sort((c,d)=>ut(d.timestamp)-ut(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:Ja(c.type),progress:null,initiativeId:x,workstreamId:null,groupId:x??"unscoped",groupLabel:Er(x),startedAt:g,updatedAt:g,lastEventAt:g,lastEventSummary:c.title,blockers:c.type==="blocker_created"&&c.description?[c.description]:[]});continue}(!u.startedAt||ut(g)<ut(u.startedAt))&&(u.startedAt=g),ut(g)>=ut(u.updatedAt??u.lastEventAt)&&(u.updatedAt=g,u.lastEventAt=g,u.lastEventSummary=c.title,u.status=Ja(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=Er(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=Oc(c.status),x=new Date().toISOString(),b=Bc(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:Er(v),startedAt:h,updatedAt:h,lastEventAt:h,lastEventSummary:c.currentTask,blockers:Ii(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),Ii(c.blockers).length>0&&(u.blockers=Ii(c.blockers)),v&&!u.initiativeId&&(u.initiativeId=v,u.groupId=v,u.groupLabel=Er(v))}const a=Array.from(r.values()).sort(si).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 zc(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 Wc(e,t,s,r,i=[],a=xa,l=null,c=1,d=[],u=Ms,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=ut(x)>=ut(b)?x:b;return{connection:"connected",lastActivity:h?_t(h):null,lastSnapshotAt:l,snapshotVersion:c,sessions:e,activity:t,handoffs:s,decisions:r,sliceRuns:i,outbox:cl(a),chat:Gr(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 Ya(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)=>ut(r.lastEventAt??r.lastHeartbeatAt)-ut(s.lastEventAt??s.lastHeartbeatAt))}function Za(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 Uc(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)=>ut(r.lastActivityAt??r.updatedAt)-ut(s.lastActivityAt??s.updatedAt))}function Gr(e){if(!e||typeof e!="object")return Ms;const t=Uc(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 Hc(e,t){const s=e??Ms,r=t??Ms;if(s.total!==r.total||s.updatedAt!==r.updatedAt||s.threads.length!==r.threads.length)return!1;for(let i=0;i<s.threads.length;i+=1){const a=s.threads[i],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 Xr(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)=>ut(i.updatedAt??i.lastEventAt)-ut(r.updatedAt??r.lastEventAt))}function Rr(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)=>ut(r.updatedAt??r.completedAt??r.failedAt)-ut(s.updatedAt??s.completedAt??s.failedAt))}function Ai(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)=>ut(r.occurredAt)-ut(s.occurredAt))}function Si(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 eo(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 Xr(t)}function Vc(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 Kc(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 Gc(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 Xc(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 Qc(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 Jc(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 Yc(e={}){const{enabled:t=!0,pollInterval:s=yc,useMock:r=!1,enableDecisions:i=!0,initiativeId:a=null,projectId:l=null,maxSessions:c=bc,maxActivityItems:d=wc,maxHandoffs:u=vc,maxDecisions:g=kc,batchWindowMs:x=jc}=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(Fa()),[j,w]=o.useState(Mr),[k,m]=o.useState(!r),[_,H]=o.useState(null),oe=o.useRef(),K=o.useRef(null),be=o.useRef(null),[V,Y]=o.useState(!1),ce=o.useRef(0),ye=o.useRef(!1),we=o.useRef(`${b??"__all__"}::${h??"__all__"}`),W=o.useRef(!1),Ie=o.useRef(null),Ee=o.useCallback((P,J)=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null),w(P),J!=null&&J.autoResetMs&&J.autoResetMs>0&&(Ie.current=setTimeout(()=>{Ie.current=null,w(Mr)},J.autoResetMs))},[]);o.useEffect(()=>()=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null)},[]),o.useEffect(()=>{const P=`${b??"__all__"}::${h??"__all__"}`;we.current!==P&&(we.current=P,W.current=!0,Ee(Mr),y(J=>({...J,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Ms,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(J.snapshotVersion??0)+1})),m(!0),H(null))},[b,h,Ee]);const fe=o.useCallback((P,J,ie,ve=null,ke=null,ee=null,Te=null,pe=null,C=null,O=null)=>{ce.current=Date.now(),ye.current=!1,y(U=>{const se=W.current;se&&(W.current=!1);const Le=J===null?se?[]:U.activity:Ni(J,d),qe=ie===null?se?[]:U.handoffs:Va(ie,u),Me=ir(P===null?se?{nodes:[],edges:[],groups:[]}:U.sessions:se?ir(P,c):Ha(U.sessions,ir(P,c)),c),T=ve===null?se?[]:U.decisions:Qa(ve,g),q=ke===null?se?[]:U.sliceRuns:Xr(ke),re=ee===null?se?xa:U.outbox:cl(ee),ue=pe===null?se?[]:U.runtimeInstances??[]:Ya(pe),Ce=C===null?se?Ms:U.chat??Ms:Gr(C),Ye=(O==null?void 0:O.workSliceProjections)==null?se?[]:U.workSliceProjections??[]:Rr(O.workSliceProjections),Je=(O==null?void 0:O.timelineNarrative)==null?se?[]:U.timelineNarrative??[]:Ai(O.timelineNarrative),Fe=(O==null?void 0:O.nextUpByInitiative)==null?se?[]:U.nextUpByInitiative??[]:Si(O.nextUpByInitiative),Xe=typeof(O==null?void 0:O.runningWorkSlices)=="number"&&Number.isFinite(O.runningWorkSlices)?Math.max(0,Math.floor(O.runningWorkSlices)):U.runningWorkSlices??0,He=typeof(O==null?void 0:O.needsInputTotal)=="number"&&Number.isFinite(O.needsInputTotal)?Math.max(0,Math.floor(O.needsInputTotal)):U.needsInputTotal??0,mt=typeof(O==null?void 0:O.failedActionableTotal)=="number"&&Number.isFinite(O.failedActionableTotal)?Math.max(0,Math.floor(O.failedActionableTotal)):U.failedActionableTotal??0,ot=typeof(O==null?void 0:O.completedTodayTotal)=="number"&&Number.isFinite(O.completedTodayTotal)?Math.max(0,Math.floor(O.completedTodayTotal)):U.completedTodayTotal??0,lt=(O==null?void 0:O.consistencyFlags)==null?U.consistencyFlags??[]:O.consistencyFlags.filter(Ae=>typeof Ae=="string"),ge=(O==null?void 0:O.dataHealth)===void 0||(O==null?void 0:O.dataHealth)===null?U.dataHealth:O.dataHealth,Ke=(U.snapshotVersion??0)+1;return Ka(U.sessions,Me)&&ll(U.activity,Le)&&Ga(U.handoffs,qe)&&Xa(U.decisions,T)&&Vc(U.sliceRuns,q)&&Lc(U.outbox,re)&&Hc(U.chat,Ce)&&Za(U.runtimeInstances,ue)&&Kc(U.workSliceProjections??[],Ye)&&Gc(U.timelineNarrative??[],Je)&&Xc(U.nextUpByInitiative??[],Fe)&&(U.runningWorkSlices??0)===Xe&&(U.needsInputTotal??0)===He&&(U.failedActionableTotal??0)===mt&&(U.completedTodayTotal??0)===ot&&Qc(U.consistencyFlags??[],lt)&&Jc(U.dataHealth,ge)&&U.lastSnapshotAt===Te&&U.connection==="connected"?U:Wc(Me,Le,qe,T,q,re,Te,Ke,ue,Ce,{workSliceProjections:Ye,timelineNarrative:Je,nextUpByInitiative:Fe,runningWorkSlices:Xe,needsInputTotal:He,failedActionableTotal:mt,completedTodayTotal:ot,consistencyFlags:lt,dataHealth:ge})}),m(!1)},[d,g,u,c]),Z=o.useCallback(async()=>{if(!t){y(ie=>ie.connection==="disconnected"?ie:{...ie,connection:"disconnected"}),m(!1),H(null);return}const P=`${b??"__all__"}::${h??"__all__"}`;if(K.current&&be.current===P)return K.current;if(r){y(Fa()),m(!1);return}const J=(async()=>{try{const ie=new URLSearchParams({sessionsLimit:String(c),activityLimit:String(d),decisionsLimit:String(g),include_idle:"true"});h&&fs(ie,h),b&&ie.set("initiative",b);const ve=[{label:"live/snapshot-v2",url:`/orgx/api/live/snapshot-v2?${ie.toString()}`},{label:"dashboard-bundle",url:`/orgx/api/dashboard-bundle?${ie.toString()}`},{label:"live/snapshot",url:`/orgx/api/live/snapshot?${ie.toString()}`}],ke=[];let ee=null,Te=!1;for(let Q=0;Q<ve.length;Q+=1){const Ne=ve[Q];Q>0&&await new Promise($e=>{setTimeout($e,Ic)});const De=await zc(Ne.url,{headers:At({workspaceId:h})},{timeoutMs:Nc});if(De.ok&&De.data){ee=De.data;break}(De.status===401||De.status===403)&&(Te=!0),ke.push(`${Ne.label}: ${De.error??"unavailable"}`)}if(!ee){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(Cc(ke))}if(we.current!==P)return;const pe=Array.isArray(ee.degraded)?ee.degraded.filter(Q=>typeof Q=="string"):[],C=pe.map(Q=>Q.toLowerCase()),O=(...Q)=>C.some(Ne=>Q.some(De=>Ne.includes(De))),U=Array.isArray(ee.activity)?ee.activity:[],se=Array.isArray(ee.handoffs)?ee.handoffs:[],Le=Array.isArray(ee.decisions)?ee.decisions:[],qe=U.length===0&&O("activity unavailable","activity local fallback failed"),Me=O("sessions unavailable","sessions local fallback failed"),T=se.length===0&&O("handoffs unavailable"),q=Le.length===0&&O("decisions unavailable"),re=Rr(Array.isArray(ee.projections)?ee.projections:[]),ue=Gr(ee.chat??null),Ce=Ai(Array.isArray(ee.timelineNarrative)?ee.timelineNarrative:[]),Ye=Si(Array.isArray(ee.nextUpByInitiative)?ee.nextUpByInitiative:[]),Je=re.length>0?eo(re):Xr(Array.isArray(ee.sliceRuns)?ee.sliceRuns:[]),Fe=ee.sessions&&Array.isArray(ee.sessions.nodes)&&Array.isArray(ee.sessions.edges)&&Array.isArray(ee.sessions.groups)?ee.sessions:qc(U,ee.agents,c),Xe=Je.length===0&&re.length===0&&O("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),He=Ye.length===0&&O("next-up unavailable","next-up queue"),mt=qe?null:U,ot=T?null:se,lt=q?null:Le,ge=Me&&Fe.nodes.length===0?null:Fe,Ke=Xe?null:re,Ae=Xe?null:Ce,B=Xe?null:Je,Pe=He?null:Ye;fe(ge,mt,ot,lt,B,ee.outbox??null,ee.generatedAt??null,ee.runtimeInstances??null,ue,{workSliceProjections:Ke,timelineNarrative:Ae,nextUpByInitiative:Pe,runningWorkSlices:Xe?null:ee.runningWorkSlices??null,needsInputTotal:Xe?null:ee.needsInput??null,failedActionableTotal:Xe?null:ee.failedActionable??null,completedTodayTotal:Xe?null:ee.completedToday??null,consistencyFlags:Array.isArray(ee.consistencyFlags)?ee.consistencyFlags:null,dataHealth:ee.dataHealth??null});const z=pe.length>0?Tc(pe):[];z.length>0?(H(`Partial live data: ${z.join("; ")}`),y(Q=>Q.connection==="connected"?Q:{...Q,connection:"connected"}),Y(!1)):(H(null),y(Q=>Q.connection==="connected"?Q:{...Q,connection:"connected"}))}catch(ie){if(we.current!==P)return;const ve=ie instanceof Error?ie.message:"Unknown error",ke=!!(ie&&typeof ie=="object"&&"code"in ie&&ie.code==="ORGX_AUTH");ke&&(ye.current=!0);const ee=ce.current>0&&Date.now()-ce.current>qa;H(ve),y(Te=>{const pe=ke||ee?"disconnected":"reconnecting";return Te.connection===pe?Te:{...Te,connection:pe}}),Y(!ke),m(!1)}finally{be.current===P&&(K.current=null,be.current=null)}})();return K.current=J,be.current=P,J},[fe,t,i,d,g,u,c,h,b,r]),de=o.useCallback(async(P,J,ie)=>{var C,O,U;if(!i)throw new Error("OrgX decisions are unavailable while disconnected.");const ve=Array.from(new Set(P.filter(Boolean)));if(ve.length===0)return{updated:0,failed:0};const ke=((C=ie==null?void 0:ie.note)==null?void 0:C.trim())||void 0,ee=((O=ie==null?void 0:ie.optionId)==null?void 0:O.trim())||void 0;if(r){const se=new Set(ve);return y(Le=>{const qe=Le.decisions.filter(re=>se.has(re.id));if(qe.length===0)return Le;const Me=new Date().toISOString(),T=qe.map(re=>({id:`decision:${J}:${re.id}:${Date.now()}`,type:"decision_resolved",title:J==="approve"?`Approved: ${re.title}`:`Rejected: ${re.title}`,description:re.context,agentId:null,agentName:re.agentName,requesterAgentId:null,requesterAgentName:re.agentName??null,executorAgentId:null,executorAgentName:re.agentName??null,runId:null,initiativeId:null,timestamp:Me,metadata:{decisionId:re.id,action:J}})),q=Ni(T.concat(Le.activity),d);return{...Le,decisions:Le.decisions.filter(re=>!se.has(re.id)),activity:q,lastActivity:_t(Me)}}),{updated:se.size,failed:0,firstError:void 0}}const Te=new Date().toISOString(),pe=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:At({contentTypeJson:!0,workspaceId:h}),body:JSON.stringify({ids:ve,action:J,...ke?{note:ke}:{},...ee?{option_id:ee}:{}})});try{const se=await pe.json().catch(()=>null),Le=Array.isArray(se==null?void 0:se.results)?se.results:[],qe=new Set(Le.filter(ue=>ue.ok).map(ue=>ue.id)),T=((U=Le.filter(ue=>!ue.ok).find(ue=>typeof ue.error=="string"&&ue.error.trim().length>0))==null?void 0:U.error)??(typeof(se==null?void 0:se.error)=="string"&&se.error.trim().length>0?se.error:void 0);if(!pe.ok&&pe.status!==207){const ue=T??`Decision action failed (${pe.status})`;throw new Error(ue)}if(qe.size===0&&pe.ok&&((se==null?void 0:se.failed)??0)===0)for(const ue of ve)qe.add(ue);qe.size>0?y(ue=>{const Ce=ue.decisions.filter(He=>qe.has(He.id));if(Ce.length===0)return ue;const Ye=new Date().toISOString(),Je=Ce.map(He=>({id:`decision:${J}:${He.id}:${Date.now()}`,type:"decision_resolved",title:J==="approve"?`Approved: ${He.title}`:`Rejected: ${He.title}`,description:He.context,agentId:null,agentName:He.agentName,requesterAgentId:null,requesterAgentName:He.agentName??null,executorAgentId:null,executorAgentName:He.agentName??null,runId:null,initiativeId:null,timestamp:Ye,metadata:{decisionId:He.id,action:J}})),Fe=Ni(Je.concat(ue.activity),d);return{...ue,decisions:ue.decisions.filter(He=>!qe.has(He.id)),activity:Fe,lastActivity:_t(Ye)}}):pe.ok&&ve.length>0&&y(ue=>({...ue,decisions:ue.decisions.filter(Ce=>!ve.includes(Ce.id))})),Z();const q=(se==null?void 0:se.updated)??qe.size,re=(se==null?void 0:se.failed)??Math.max(0,ve.length-qe.size);return Ee({phase:re>0?"error":"success",action:J,targetCount:ve.length,message:re>0?`${J==="approve"?"Approve":"Reject"} completed with ${re} failure${re===1?"":"s"}.`:J==="approve"?`Approved ${q} decision${q===1?"":"s"}.`:`Rejected ${q} decision${q===1?"":"s"}.`,startedAt:Te,completedAt:new Date().toISOString()},{autoResetMs:re>0?8e3:4e3}),{updated:q,failed:re,firstError:T}}catch(se){throw Ee({phase:"error",action:J,targetCount:ve.length,message:se instanceof Error?se.message:"Decision update failed.",startedAt:Te,completedAt:new Date().toISOString()}),se}},[i,Z,d,h,Ee,r]),Re=o.useCallback(async(P,J)=>de([P],"approve",J),[de]),ne=o.useCallback(async(P,J)=>de([P],"reject",J),[de]),$=o.useCallback(async()=>{let P=[];return y(J=>(P=J.decisions.map(ie=>ie.id),J)),P.length===0?{updated:0,failed:0}:de(P,"approve")},[de]),X=o.useCallback(async(P,J,ie)=>de(P,J,ie?{note:ie}:void 0),[de]);return o.useEffect(()=>{i||Ee(Mr)},[i,Ee]),o.useEffect(()=>{if(!t){Y(!1),m(!1),H(null);return}if(r){Z();return}if(Z(),h){Y(!0);return}const P=new URLSearchParams;h&&fs(P,h),b&&P.set("initiative",b);const J=P.toString()?`/orgx/api/live/stream?${P.toString()}`:"/orgx/api/live/stream",ie=new EventSource(J),ve=new EventSource("/orgx/api/hooks/runtime/stream");let ke=null,ee=null,Te=null,pe=null,C=[],O=null,U;const se=()=>{if(U=void 0,ke){ce.current=Date.now(),ye.current=!1;const Me=ke;ke=null,Te=null,pe=null,C=[],O=null,ee=null,fe(Me.sessions,Me.activity,Me.handoffs,Me.decisions,Me.sliceRuns,Me.outbox,Me.generatedAt,Me.runtimeInstances,Me.chat,Me.v2);return}!Te&&!pe&&!O&&!ee&&C.length===0||(ce.current=Date.now(),ye.current=!1,y(Me=>{var q;let T=Me;if(Te){const re=ir(Te,c),ue=ir(Ha(T.sessions,re),c);Te=null,Ka(T.sessions,ue)||(T={...T,sessions:ue})}if(pe){const re=Va(pe,u);pe=null,Ga(T.handoffs,re)||(T={...T,handoffs:re})}if(O){const re=Qa(O,g);O=null,Xa(T.decisions,re)||(T={...T,decisions:re})}if(ee){const re=Ya(ee);ee=null,Za(T.runtimeInstances,re)||(T={...T,runtimeInstances:re})}if(C.length>0){const re=Pc(T.activity,C,d);C=[],re!==T.activity&&(T={...T,activity:re,lastActivity:(q=re[0])!=null&&q.timestamp?_t(re[0].timestamp):T.lastActivity})}return T===Me?Me:T.connection==="connected"?T:{...T,connection:"connected"}}),H(null),m(!1))},Le=()=>{U||(U=setTimeout(se,x))};ie.onopen=()=>{ce.current=Date.now(),ye.current=!1,Y(!1),y(Me=>Me.connection==="connected"?Me:{...Me,connection:"connected"}),H(null)},ie.onerror=()=>{if(ye.current){y(T=>T.connection==="disconnected"?T:{...T,connection:"disconnected"}),Y(!1);return}const Me=ce.current>0&&Date.now()-ce.current>qa;y(T=>T.connection===(Me?"disconnected":"reconnecting")?T:{...T,connection:Me?"disconnected":"reconnecting"}),Y(!0)},ie.addEventListener("snapshot",Me=>{try{const T=JSON.parse(Me.data),q=typeof T.generatedAt=="string"&&T.generatedAt.length>0?T.generatedAt:new Date().toISOString();ke={sessions:T.sessions,activity:T.activity??[],handoffs:T.handoffs??[],decisions:T.decisions??null,sliceRuns:Array.isArray(T.sliceRuns)?Xr(T.sliceRuns):Array.isArray(T.projections)?eo(Rr(T.projections)):null,outbox:T.outbox??null,generatedAt:q,runtimeInstances:Array.isArray(T.runtimeInstances)?T.runtimeInstances:null,chat:Gr(T.chat??null),v2:{workSliceProjections:Array.isArray(T.projections)?Rr(T.projections):null,timelineNarrative:Array.isArray(T.timelineNarrative)?Ai(T.timelineNarrative):null,nextUpByInitiative:Array.isArray(T.nextUpByInitiative)?Si(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}},Le()}catch(T){H(T instanceof Error?T.message:"Invalid snapshot")}}),ie.addEventListener("activity.appended",Me=>{try{const T=JSON.parse(Me.data);if(T.length===0)return;C=C.concat(T),Le()}catch{}}),ie.addEventListener("session.updated",Me=>{try{Te=JSON.parse(Me.data),Le()}catch{}});const qe=Me=>{try{const T=JSON.parse(Me.data);ee=Array.isArray(T)?T:[T],Le()}catch{}};return ie.addEventListener("runtime.updated",qe),ve.addEventListener("runtime.updated",qe),ie.addEventListener("handoff.updated",Me=>{try{pe=JSON.parse(Me.data),Le()}catch{}}),ie.addEventListener("decision.updated",Me=>{try{O=JSON.parse(Me.data),Le()}catch{}}),()=>{U&&clearTimeout(U),ie.close(),ve.close()}},[fe,x,t,i,Z,d,g,u,c,b,h,r]),o.useEffect(()=>{if(!(!t||r||(oe.current&&clearInterval(oe.current),!V&&!!!h)))return oe.current=setInterval(Z,s),()=>{oe.current&&clearInterval(oe.current)}},[t,Z,h,s,V,r]),{data:v,isLoading:k,error:_,refetch:Z,approveDecision:Re,rejectDecision:ne,approveAllDecisions:$,bulkDecisionAction:X,decisionMutation:j}}const vr=[{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 ul(e){return vr.find(t=>t.id===e)??vr[0]}function jr(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=vr.find(r=>r.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function Zc(e,t=Date.now()){const s=jr(e,t);return s?new Date(s).toISOString():null}const ed=new Set(["ungrouped","unscoped","unknown"]),td="orgx.demo_mode",nd="orgx.show_synthetic_entities";function Es(e){const t=(e??"").trim().toLowerCase();return!!(!t||ed.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(td)==="1"}catch{return!1}}function sd(){if(typeof window>"u")return!1;if(Ft())return!0;try{return window.localStorage.getItem(nd)==="1"}catch{return!1}}function rd(e){return Ft()?!0:!Es(e)}function ia(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ml(e,t){const s=ia(t.timestamp)-ia(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function id(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ad(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 pl(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=id(e.metadata);return ad(s,["initiative_id","initiativeId"])}function _i(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function aa(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(!aa(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]||!aa(s[c],r[c]))return!1}return!0}const od=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function zs(e,...t){}function ld(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&&pl(g)!==r){d++;continue}const x=ia(g.timestamp);if(x){if(a!==null&&x<a){u++;continue}if(l!==null&&x>l){u++;continue}i.set(g.id,g)}}return zs("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(ml)}function to(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||!aa(c.metadata??null,l.metadata??null))&&(s.set(l.id,l),a=!0,i++)}return zs("mergeById",{currentCount:e.length,incomingCount:t.length,added:r,updated:i,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(ml):e}function cd(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(()=>_i(a),[a]),x=o.useMemo(()=>_i(l),[l]),b=o.useMemo(()=>_i(c),[c]),h=o.useMemo(()=>jr(s),[s]),v=o.useMemo(()=>Zc(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]),m=o.useMemo(()=>ld(t,{sinceEpoch:w,untilEpoch:k},g,x),[t,w,k,g,x]),_=u?null:"",[H,oe]=o.useState(m),[K,be]=o.useState(()=>_),[V,Y]=o.useState(!1),[ce,ye]=o.useState(null),[we,W]=o.useState(null),Ie=o.useRef(null),Ee=o.useRef(!1),fe=o.useRef(m);fe.current=m;const Z=o.useMemo(()=>`${g??""}|${x??""}|${s}|${y??""}|${j??""}|${b??""}|${u?"demo":"live"}`,[g,x,s,y,j,b,u]),de=o.useRef(Z);o.useEffect(()=>{de.current!==Z&&(de.current=Z,zs("RESET",{reason:"filter/run change",runId:g,initiativeId:x,projectId:b,timeFilterId:s,sinceIso:y,untilIso:j,seedCount:fe.current.length}),oe(fe.current),be(_),ye(null),W(null),Ee.current=!1)},[Z,_,g,x,b,s,y,j]),o.useEffect(()=>{oe($=>{const X=to($,m);return X!==$&&zs("SSE_MERGE",{prevCount:$.length,seedCount:m.length,nextCount:X.length,delta:X.length-$.length}),X})},[m]);const Re=o.useCallback(async()=>{if(u){be(null),ye(null);return}if(K===null)return;if(Ie.current)return Ie.current;Y(!0);const $=(async()=>{try{const X=new URLSearchParams;X.set("limit",String(Math.max(1,Math.min(500,d)))),K.trim().length>0&&X.set("cursor",K),y&&X.set("since",y),j&&X.set("until",j),g&&X.set("run",g),x&&X.set("initiative",x),b&&fs(X,b);const P=await fetch(`/orgx/api/live/activity/page?${X.toString()}`,{headers:At({workspaceId:b})}),J=await P.json().catch(()=>null);if(!P.ok||!J){const ke=typeof(J==null?void 0:J.error)=="string"&&J.error.trim()||typeof(J==null?void 0:J.message)=="string"&&J.message.trim()||`Activity paging failed (${P.status})`;throw new Error(ke)}const ie=Array.isArray(J.activities)?J.activities:[],ve=ie.filter(ke=>!x||pl(ke)===x);zs("PAGE_FETCH",{cursor:K,rawCount:ie.length,afterFilter:ve.length,filteredOut:ie.length-ve.length,initiativeId:x,runId:g,nextCursor:J.nextCursor??null}),oe(ke=>{const ee=to(ke,ve);return zs("PAGE_MERGE",{prevCount:ke.length,pageCount:ve.length,nextCount:ee.length,added:ee.length-ke.length}),ee}),be(J.nextCursor??null),W(J.storeUpdatedAt??null),ye(null)}catch(X){const P=X instanceof Error?X.message:"";ye(P?Rt(P):"Activity paging failed"),be(J=>J===""?null:J)}finally{Y(!1),Ie.current=null}})();return Ie.current=$,$},[K,u,x,d,b,g,y,j]);return o.useEffect(()=>{K===""&&(Ee.current||(Ee.current=!0,Re()))},[K,Re]),{items:H,hasMore:K!==null,isLoadingMore:V,error:ce,storeUpdatedAt:we,loadMore:Re,cutoffEpoch:w,sinceIso:y,untilIso:j}}const dd="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",ud="".trim().toLowerCase()==="true"||"".trim()==="1",md="".trim().toLowerCase()==="true"||"".trim()==="1",pd={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let Ci=null,no=!1,so=!1,ya=!1;function fd(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function fi(){return ya||!ud?!1:md?!0:!fd()}function hd(){return fi()?(Ci||(Ci=Ut(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(ya=!0,null))),Ci):Promise.resolve(null)}function gd(e){if(no)return!0;try{return e.init(dd,pd),no=!0,!0}catch{return ya=!0,!1}}async function ba(){const e=await hd();return!e||!gd(e)?null:e}function xd(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 yd(){!fi()||typeof window>"u"||so||(so=!0,xd(()=>{ba()}))}function bd(e){if(!fi())return;const t=e.trim();t&&ba().then(s=>{if(s)try{s.identify(t)}catch{}})}function os(e,t){fi()&&e.trim()&&ba().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const wd="https://orgx.mintlify.site/guides/openclaw-plugin-setup",vd=1500,Mi="orgx.onboarding.skip",kd=680,jd=`<!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>`,Qr={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:wd,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function Ps(){return{...Qr,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function Ti(e){if(typeof e=="string")return Rt(e);if(e&&typeof e=="object"){const t=e;if(typeof t.error=="string")return Rt(t.error);if(typeof t.message=="string")return Rt(t.message)}}async function ar(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:Ti(s==null?void 0:s.error)??Ti(s==null?void 0:s.message)??Ti(s)??Rt(`Request failed (${t.status})`)}}function Lr(e){if(e)try{bd(e)}catch{}}function Nd(){const[e,t]=o.useState(()=>Ft()?Ps():Qr),[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(Mi)==="1"),x=o.useCallback(async()=>{if(Ft()){const m=Ps();return t(m),m}const k=await ar(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!k.ok||!k.data){const m=k.error??"Failed to load onboarding state",_={...Qr,status:"error",lastError:m,nextAction:"retry"};return t(_),_}return Lr(k.data.installationId??null),t(k.data),k.data},[]);o.useEffect(()=>{if(Ft()){t(Ps()),r(!1);return}let k=!1;return(async()=>{r(!0);const m=await x();k||(t(m),r(!1))})(),()=>{k=!0}},[x]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const m=Math.max(900,e.pollIntervalMs??vd),_=window.setInterval(async()=>{const H=await ar(fetch("/orgx/api/onboarding/status",{method:"GET"}));H.ok&&H.data&&(Lr(H.data.installationId??null),t(H.data))},m);return()=>{window.clearInterval(_)}},[e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(u){window.localStorage.setItem(Mi,"1");return}window.localStorage.removeItem(Mi)}},[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(jd),k.document.close(),k):null}catch{return null}},[]),h=o.useCallback(async()=>{if(Ft()){const m=Ps();t(m);return}const k=b();d.current=k,a(!0);try{const m=await ar(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),_=m.data;if(!m.ok||!(_!=null&&_.state)){k&&!k.closed&&k.close();const oe=m.error??"Could not start pairing";t(K=>({...K,status:"error",lastError:oe,nextAction:"enter_manual_key"}));return}t(_.state);const H=_.connectUrl;if(H){const oe=d.current;let K=!1;if(oe&&!oe.closed)try{window.setTimeout(()=>{if(!oe.closed)try{oe.location.href=H}catch{}},kd),K=!0}catch{K=!1}K||(K=!!window.open(H,"_blank","noopener,noreferrer")),K||t(be=>({...be,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 m=Ps();return t(m),m}c(!0);try{const m=k.trim(),_=m.replace(/^[a-z]+_/i,""),H=Array.from(new Set([m,_?`oxk_${_}`:"",_?`orgx_${_}`:""].map(K=>K.trim()).filter(K=>K.length>0)));let oe="Manual key validation failed";for(const K of H){const be={"Content-Type":"application/json","X-OrgX-Api-Key":K,Authorization:`Bearer ${K}`},V=await ar(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:be,body:JSON.stringify({apiKey:K})}));if(V.ok&&V.data)return Lr(V.data.installationId??null),t(V.data),V.data;oe=V.error??oe}throw t(K=>({...K,status:"manual_key",lastError:oe,nextAction:"enter_manual_key"})),new Error(oe)}finally{c(!1)}},[]),y=o.useCallback(async()=>{if(Ft()){const _=Ps();return t(_),_}const k=await ar(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(k.ok&&k.data)return Lr(k.data.installationId??null),t(k.data),k.data;const m={...Qr,status:"idle"};return t(m),m},[]),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 Jn={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 Id extends Error{constructor(s,r){super(s);Bn(this,"code","upgrade_required");Bn(this,"currentPlan");Bn(this,"requiredPlan");Bn(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 Ad(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 Id(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 Oh(e){const t=(e??"").trim().toLowerCase();return t?t==="free"?"Free":t==="starter"?"Starter":t==="team"?"Team":t==="enterprise"?"Enterprise":t[0].toUpperCase()+t.slice(1):"Unknown"}class fl extends Error{constructor(s){super(s.message);Bn(this,"status");Bn(this,"code");Bn(this,"errorLocation");Bn(this,"retryable");Bn(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 Sd(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function kr(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 _d(e,t){if(e.status!==404)return!1;const s=kr(t,["error"])??"",r=kr(t,["message"])??"";return/unknown api endpoint/i.test(`${s} ${r}`)}function Cd(e,t,s){if(_d(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=kr(t,["error","message"])??`${s} (${e.status})`;return Rt(r)}function Ei(e,t,s){const r=Sd(t),i=Cd(e,r,s),a=kr(r,["code"]),l=kr(r,["error_location","errorLocation"]),c=r==null?void 0:r.retryable,d=typeof c=="boolean"?c:!1;return new fl({message:i,status:e.status,code:a,errorLocation:l,retryable:d,details:r})}function Bh(e){return e instanceof fl}const Md=750;async function or(e){return await e.json().catch(()=>null)}function Td(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 Ed(e,t,s){if(Td(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 Rt(r)}function Rd(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?Rt(s):t}function Ld(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 Jr({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 Dd(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 $d(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;return!(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")}function wa(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 va(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 hl(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=wa(typeof l.id=="string"?l.id:null),d=va(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 Fd(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function Pd(e){const t=wa(e.runnerAgentId),s=va(e.runnerAgentName,t),r=hl(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=Fd(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:$d(e),autoRuntimeState:Dd(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 Jr(e){const t=e.items.map(u=>Pd(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 Od(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 Bd(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 qd(e){var x,b,h,v,y,j,w,k,m,_,H,oe,K,be,V,Y;const t=((b=(x=e.lineage)==null?void 0:x.initiativeIds)==null?void 0:b.filter(ce=>typeof ce=="string"&&ce.trim().length>0))??[],s=((v=(h=e.lineage)==null?void 0:h.workstreamIds)==null?void 0:v.filter(ce=>typeof ce=="string"&&ce.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(ce=>typeof ce=="string"&&ce.trim().length>0))==null?void 0:k.trim())||s[0]||null;if(!r||!i)return null;const a=((_=(m=e.lineage)==null?void 0:m.taskIds)==null?void 0:_.filter(ce=>typeof ce=="string"&&ce.trim().length>0))??[],l=e.level==="workstream"||e.level==="milestone"||e.level==="task"?e.level:null,c=wa(e.runnerAgentId??null),d=va(e.runnerAgentName??null,c),u=hl(e.runnerAgents??null,c,d),g=u[0]??null;return{initiativeId:r,initiativeTitle:((H=e.initiativeTitle)==null?void 0:H.trim())||t[0]||r,initiativeStatus:"active",initiativePriority:null,initiativePriorityNum:null,workstreamId:i,workstreamTitle:((oe=e.workstreamTitle)==null?void 0:oe.trim())||((K=e.title)==null?void 0:K.trim())||((be=e.milestoneTitle)==null?void 0:be.trim())||((V=e.taskTitle)==null?void 0:V.trim())||Bd(i),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((Y=e.taskTitle)==null?void 0:Y.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:Od(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 zd(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 Wd(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 Ud({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 ce,ye,we,W,Ie,Ee,fe,Z,de,Re;const u=ga(),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(()=>Jn.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:Jn.liveData({authToken:i,embedMode:a,projectId:t})})},Md)},w=async({includeGraph:ne=!0,includeLiveData:$=!0}={})=>{const X=[u.invalidateQueries({queryKey:v}),u.invalidateQueries({queryKey:Jn.autoContinueStatus({initiativeId:e,authToken:i,embedMode:a})})];ne&&X.push(u.invalidateQueries({queryKey:Jn.missionControlGraph({initiativeId:e,authToken:i,embedMode:a})})),await Promise.all(X),$&&j()},k=async(ne,$)=>{if(g)return Ld(e);const X=new URLSearchParams;e&&X.set("initiative_id",e),fs(X,t,{allTokenWhenMissing:!0}),X.set("offset",String(ne)),X.set("limit",String($));let P;try{P=await fetch(`/orgx/api/mission-control/next-up?${X.toString()}`,{headers:At({authToken:i,embedMode:a})})}catch(Te){throw new Error(Rd(Te,"Failed to load next up queue"))}const J=await or(P);if(!P.ok){const Te=Ed(P,J,"Failed to load next up queue");throw new Error(Te)}const ie=J??null;if(!ie||ie.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:ne,limit:$,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(sd())return Jr(ie);const ve=ie.items.filter(Te=>!Es(Te.initiativeId));let ke=Jr({...ie,items:ve});if(ke.items.length>0)return ke;const ee=new URLSearchParams;e&&ee.set("initiative_id",e),fs(ee,t,{allTokenWhenMissing:!0}),ee.set("level","workstream"),ee.set("include_completed","0"),ee.set("offset",String(ne)),ee.set("limit",String(Math.max($,24)));try{const Te=await fetch(`/orgx/api/mission-control/slices?${ee.toString()}`,{headers:At({authToken:i,embedMode:a})}),pe=await or(Te);if(Te.ok&&(pe!=null&&pe.ok)&&Array.isArray(pe.items)){const C=pe.items.map(O=>qd(O)).filter(O=>!!O).filter(O=>!Es(O.initiativeId));C.length>0&&(ke=Jr({ok:!0,generatedAt:new Date().toISOString(),total:typeof pe.total=="number"&&Number.isFinite(pe.total)?Math.max(pe.total,C.length):C.length,items:C,pagination:pe.pagination&&typeof pe.pagination=="object"?{offset:typeof pe.pagination.offset=="number"?Math.max(0,Math.floor(pe.pagination.offset)):ne,limit:typeof pe.pagination.limit=="number"?Math.max(1,Math.floor(pe.pagination.limit)):Math.max($,24),total:typeof pe.pagination.total=="number"?Math.max(0,Math.floor(pe.pagination.total)):C.length,nextCursor:typeof pe.pagination.nextCursor=="string"?pe.pagination.nextCursor:null,hasMore:typeof pe.pagination.hasMore=="boolean"?pe.pagination.hasMore:!1}:void 0,degraded:Array.from(new Set([...ie.degraded??[],"Queue derived from slices while live queue stabilizes."]))}))}}catch{}return ke},m=ps({queryKey:v,enabled:l,queryFn:async()=>k(x,b),refetchInterval:ne=>{const $=ne.state.data;return!$||!Array.isArray($.items)||$.items.length===0?1e4:$.items.some(P=>P.queueState==="running")?2500:8e3}}),_=o.useRef(null);o.useEffect(()=>{var X;const ne=(X=m.data)==null?void 0:X.pagination;if(!l||!(ne!=null&&ne.hasMore)||!ne.nextCursor||_.current===ne.nextCursor)return;const $=Number.parseInt(ne.nextCursor,10);Number.isFinite($)&&(_.current=ne.nextCursor,u.prefetchQuery({queryKey:Jn.nextUpQueue({initiativeId:e,projectId:t,offset:$,limit:b,authToken:i,embedMode:a}),queryFn:()=>k($,b),staleTime:15e3}))},[l,(ye=(ce=m.data)==null?void 0:ce.pagination)==null?void 0:ye.hasMore,(W=(we=m.data)==null?void 0:we.pagination)==null?void 0:W.nextCursor,e,t,b,i,a,u]);const H=yn({mutationFn:async ne=>{if(g)return{ok:!0,initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,dispatchMode:"slice",sessionId:null};const $=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:At({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,agentId:ne.agentId??void 0,scope:ne.scope??void 0,maxParallelSlices:typeof ne.maxParallelSlices=="number"&&Number.isFinite(ne.maxParallelSlices)?Math.max(1,Math.floor(ne.maxParallelSlices)):void 0,parallelMode:ne.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),X=await or($);if(!$.ok)throw Ei($,X,"Failed to dispatch queued workstream");return X},onMutate:async ne=>{await u.cancelQueries({queryKey:v});const $=u.getQueryData(v);return $?(u.setQueryData(v,{...$,items:$.items.map(X=>X.initiativeId===ne.initiativeId&&X.workstreamId===ne.workstreamId?{...X,queueState:"running",playbackState:"running"}:X.queueState==="running"?{...X,queueState:"idle",playbackState:"idle"}:X)}),{previous:$}):{previous:$}},onError:(ne,$,X)=>{X!=null&&X.previous&&u.setQueryData(v,X.previous)},onSuccess:()=>{w({includeGraph:!1})}}),oe=yn({mutationFn:async ne=>{if(g)return;const $={initiativeId:ne.initiativeId,agentId:ne.agentId??void 0,tokenBudgetTokens:ne.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};ne.scope==="workstream"&&ne.workstreamId&&($.workstreamIds=[ne.workstreamId]),typeof ne.maxParallelSlices=="number"&&Number.isFinite(ne.maxParallelSlices)&&($.maxParallelSlices=ne.maxParallelSlices),ne.parallelMode==="iwmt"&&($.parallelMode=ne.parallelMode);const X=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:At({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify($)}),P=await or(X);if(!X.ok){const J=Ad(P);throw J||Ei(X,P,"Failed to start auto-continue")}},onSuccess:()=>{w({includeGraph:!1})}}),K=yn({mutationFn:async ne=>{if(g)return;const $=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:At({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:ne.initiativeId})}),X=await or($);if(!$.ok)throw Ei($,X,"Failed to stop auto-continue")},onSuccess:()=>{w({includeGraph:!1})}}),be=((Ie=m.data)==null?void 0:Ie.items)??[],V=o.useMemo(()=>d==="initiative"?zd(be):[],[be,d]),Y=o.useMemo(()=>d==="milestone"?Wd(be):[],[be,d]);return{items:be,total:((Ee=m.data)==null?void 0:Ee.total)??0,pagination:((fe=m.data)==null?void 0:fe.pagination)??null,generatedAt:((Z=m.data)==null?void 0:Z.generatedAt)??null,degraded:((de=m.data)==null?void 0:de.degraded)??[],isLoading:m.isLoading,isFetching:m.isFetching,error:((Re=m.error)==null?void 0:Re.message)??null,refetch:m.refetch,playWorkstream:H.mutateAsync,startWorkstreamAutoContinue:oe.mutateAsync,stopInitiativeAutoContinue:K.mutateAsync,isPlaying:H.isPending,isStartingAutoContinue:oe.isPending,isStoppingAutoContinue:K.isPending,zoomLevel:d,initiativeGroups:V,milestoneGroups:Y}}const Hd=750;async function rn(e){return await e.json().catch(()=>null)}function qs(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 an(e,t,s){if(qs(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 Rt(r)}function Vd(e){const t=e.authToken??null,s=e.embedMode??!1,r=Ft(),i=ga(),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"]})},Hd)},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 m=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await rn(m);if(m.ok)return _;if(!qs(m,_))throw new Error(an(m,_,"Failed to move Next Up item"));const H=await fetch("/orgx/api/mission-control/next-up",{headers:At({authToken:t,embedMode:s})}),oe=await rn(H);if(!H.ok)throw new Error(an(H,oe,"Failed to read queue for move fallback"));const be=(Array.isArray(oe==null?void 0:oe.items)?oe.items:[]).map(we=>{const W=typeof(we==null?void 0:we.initiativeId)=="string"?we.initiativeId:null,Ie=typeof(we==null?void 0:we.workstreamId)=="string"?we.workstreamId:null;return!W||!Ie?null:{initiativeId:W,workstreamId:Ie}}).filter(we=>!!we);if(be.length===0)throw new Error("Queue placement controls require a newer plugin runtime. Refresh to latest main and retry.");const V=be.findIndex(we=>we.initiativeId===k.initiativeId&&we.workstreamId===k.workstreamId);if(V===-1)return{ok:!0,fallback:"reorder-move-skip"};const[Y]=be.splice(V,1);(k.placement??"top")==="bottom"?be.push(Y):be.unshift(Y);const ce=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:be})}),ye=await rn(ce);if(!ce.ok)throw new Error(an(ce,ye,"Failed to move Next Up item with reorder fallback"));return ye??{ok:!0,fallback:"reorder-move"}},u=async k=>{if(r)return{ok:!0,demo:!0,initiativeId:k.initiativeId,workstreamId:k.workstreamId};const m=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await rn(m);if(m.ok)return _;if(qs(m,_)){const H=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),oe=await rn(H);if(!H.ok)throw new Error(an(H,oe,"Failed to remove item from queue with legacy fallback"));return oe??{ok:!0,fallback:"next-up-unpin"}}throw new Error(an(m,_,"Failed to remove item from queue"))},g=yn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0};const m=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await rn(m);if(!m.ok)throw new Error(an(m,_,"Failed to pin Next Up item"))},onSuccess:()=>{c()}}),x=yn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0};const m=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await rn(m);if(!m.ok)throw new Error(an(m,_,"Failed to unpin Next Up item"))},onSuccess:()=>{c()}}),b=yn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0,updated:k.order.length};const m=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await rn(m);if(!m.ok)throw new Error(an(m,_,"Failed to reorder Next Up queue"))},onSuccess:()=>{c()}}),h=yn({mutationFn:d,onSuccess:()=>{c()}}),v=yn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0,initiativeId:k.initiativeId,workstreamId:k.workstreamId};const m=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await rn(m);if(!m.ok){if(qs(m,_)){const H=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:k.initiativeId})}),oe=await rn(H);if(!H.ok)throw new Error(an(H,oe,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(an(m,_,"Failed to stop triage"))}return _},onSuccess:()=>{c()}}),y=yn({mutationFn:u,onSuccess:()=>{c()}}),j=yn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0,cleared:!0};const m=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await rn(m);if(!m.ok){if(qs(m,_)&&k.initiativeId){const H=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:k.initiativeId})}),oe=await rn(H);if(!H.ok)throw new Error(an(H,oe,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(an(m,_,"Failed to clear Next Up lifecycle state"))}return _},onSuccess:()=>{c()}}),w=yn({mutationFn:async k=>{if(r)return{ok:!0,demo:!0,updated:k.items.length,failed:0,errors:[],fallback:"demo"};const m=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:At({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(k)}),_=await rn(m);if(!m.ok){if(!qs(m,_))throw new Error(an(m,_,"Failed to apply bulk queue action"));const H=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(Y){return{ok:!1,error:Y instanceof Error?Y.message:"Queue action failed"}}})),oe=H.filter(V=>V.ok).length,K=H.length-oe,be=H.filter(V=>!V.ok&&V.error).map(V=>V.error);return{ok:K===0,updated:oe,failed:K,errors:be,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 gl(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function Kd(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:gl(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(Rt(String(d)))}return l.json()}async function Gd(e,t,s,r){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,l=await fetch(a,{method:"POST",headers:gl(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(Rt(String(d)))}return l.json()}function Xd(e={}){const{enabled:t=!0,workspaceId:s=null,status:r="open",authToken:i=null,embedMode:a=!1}=e,l=ga(),c=Jn.triageQueue({workspaceId:s,status:r,authToken:i,embedMode:a}),d=ps({queryKey:c,queryFn:()=>Kd(s,r,i,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=yn({mutationFn:async({itemId:h,payload:v})=>Gd(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 le(...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"},qh={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)"}},Qd={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},Jd={Pace:"Engineering",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"};function Yd(e){return Qd[e]??"rgba(255, 255, 255, 0.4)"}function xl(e){return Jd[e]??null}function Zd(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function zt(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}},zh={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}}},Dr={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}})},Wh={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},hi="/orgx/live/assets/Fm0FhtnV.png";function yl({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 bn({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(yl,{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 eu=[{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"}],Yr=[{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."}],tu=[{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."}],ro="openclaw plugins install @useorgx/openclaw-plugin",io="orgx.demo_mode",nu=6500;function su(e){switch(e){case"config":return"Plugin config";case"environment":return"Environment variable";case"persisted":return"Saved local credential";case"openclaw-config-file":return"OpenClaw config file";case"legacy-dev":return"Local development key";default:return"Not detected"}}const ru={hidden:{},visible:{transition:{staggerChildren:.07}}},ls={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},iu={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 Ri(e){const t=Yr.length;return(e+t)%t}function au({state:e,isStarting:t,onConnect:s,onUseManualKey:r,onContinueWithoutOrgX:i}){const a=!!e.lastError,l=e.lastError?Rt(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=Yr[x];o.useEffect(()=>{if(c==="idle")return;const m=window.setTimeout(()=>d("idle"),2e3);return()=>window.clearTimeout(m)},[c]),o.useEffect(()=>{if(u==="idle")return;const m=window.setTimeout(()=>g("idle"),2e3);return()=>window.clearTimeout(m)},[u]),o.useEffect(()=>{if(h)return;const m=window.setInterval(()=>{b(_=>Ri(_+1))},nu);return()=>window.clearInterval(m)},[h]);const w=async()=>{try{await navigator.clipboard.writeText(ro),d("ok")}catch{d("error")}},k=async()=>{try{const m={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(m,null,2)),g("ok")}catch{g("error")}};return n.jsxs(he.section,{variants:ru,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(he.div,{variants:ls,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:hi,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(he.h2,{variants:ls,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(bn,{type:"workstream",size:19,className:"opacity-95"}),"Connect your workspace"]}),n.jsx(he.p,{variants:ls,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(he.div,{variants:ls,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(bn,{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,"/",Yr.length]})]}),n.jsx(yt,{initial:!1,mode:"wait",children:n.jsxs(he.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(m=>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(bn,{type:m.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:m.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:m.detail})]},`${j.id}-${m.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:Yr.map((m,_)=>{const H=_===x;return n.jsx("button",{type:"button",onClick:()=>b(_),"aria-label":`View slide ${_+1}`,className:`h-1.5 rounded-full transition-all ${H?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},m.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>b(m=>Ri(m-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(m=>Ri(m+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:eu.map(m=>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 ${iu[m.iconType]}`,children:n.jsx(bn,{type:m.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:m.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:m.desc})]},m.label))}),n.jsxs(he.div,{variants:ls,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(he.div,{variants:ls,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(bn,{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(bn,{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:ro}),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: ",su(e.keySource)]})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"What Unlocks After Connect"}),n.jsx("div",{className:"mt-2 space-y-1.5",children:tu.map(m=>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(bn,{type:m.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:m.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:m.detail})]},m.label))})]})]})]}),n.jsx(he.div,{variants:ls,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(he.div,{variants:ls,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(io,"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(io)}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 ou={hidden:{},visible:{transition:{staggerChildren:.06}}},Ns={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function lu({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(Rt(h))}},u=a!==null;return n.jsxs(he.section,{variants:ou,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(he.div,{variants:Ns,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:hi,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(he.h3,{variants:Ns,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(he.p,{variants:Ns,className:"mt-1.5 text-heading leading-relaxed text-secondary",children:["Paste a key from your ",n.jsx("span",{className:"text-secondary",children:"useorgx.com"})," dashboard. Browser pairing is recommended."]}),n.jsxs(he.p,{variants:Ns,className:"mt-1 text-body text-muted",children:["Paste full key or only the part after ",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_"}),"."]}),n.jsx(he.div,{variants:Ns,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(he.div,{variants:Ns,className:"mt-6 space-y-4 px-6 sm:px-8",children:[n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1.5 block text-caption font-medium uppercase tracking-[0.14em] text-muted",children:"API key"}),n.jsxs("div",{className:`flex items-stretch overflow-hidden rounded-xl border transition-colors focus-within:border-[#BFFF00]/40 ${u?"border-red-500/30":"border-white/[0.08]"}`,children:[n.jsx("span",{className:"flex items-center border-r border-subtle bg-white/[0.03] px-3 font-mono text-body text-faint select-none",children:"oxk_"}),n.jsx("input",{value:r,onChange:g=>{i(g.target.value),a&&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(he.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(he.div,{variants:Ns,className:"mt-6 flex flex-wrap items-center gap-3 px-6 sm:px-8",children:[n.jsx("button",{type:"button",onClick:()=>{d()},disabled:e,className:"inline-flex items-center gap-2 rounded-full bg-[#BFFF00] px-5 py-2.5 text-body font-semibold text-black shadow-[0_0_24px_rgba(191,255,0,0.12)] transition-all hover:bg-[#d3ff42] hover:shadow-[0_0_32px_rgba(191,255,0,0.22)] disabled:cursor-not-allowed disabled:opacity-50",children:e?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"h-3.5 w-3.5 animate-spin",viewBox:"0 0 16 16",fill:"none",children:[n.jsx("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),n.jsx("path",{d:"M14 8a6 6 0 00-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),"Validating..."]}):"Validate & Connect"}),n.jsx("button",{type:"button",onClick:s,className:"rounded-full border border-white/[0.1] px-4 py-2 text-body text-secondary transition hover:border-white/[0.18] hover:text-bright",children:"Back to pairing"})]}),n.jsx("div",{className:"mt-6 border-t border-subtle px-6 py-4 sm:px-8",children:n.jsx("p",{className:"text-body text-faint",children:"Keys are stored locally and never leave your device."})})]})}const ao="orgx.user.display-name",oo="orgx.user.avatar-seed-suffix";function lo(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function co(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function cu(){const[e,t]=o.useState(()=>lo(ao)),[s,r]=o.useState(()=>lo(oo)),i=(e||"orgx-user")+s,a=o.useCallback(c=>{const d=c.trim();co(ao,d),t(d)},[]),l=o.useCallback(()=>{const c=String(Date.now());co(oo,c),r(c)},[]);return{displayName:e,avatarSeed:i,updateName:a,regenerateAvatar:l}}function du(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function uu(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 uo=[D.lime,D.teal,D.iris,D.cyan];function mu(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),m=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} ${m}`,"Z"].join(" ")}function pu(e){const t=uu(du(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=uo[Math.floor(t()*uo.length)],j=.25+t()*.55;r.push({d:mu(i,a,c,d,h,v),fill:y,opacity:j})}}return r}function fu({seed:e,size:t,className:s,animate:r=!0}){const i=o.useMemo(()=>pu(e),[e]);return n.jsxs(he.svg,{viewBox:"0 0 100 100",width:t,height:t,className:le("flex-shrink-0",s),initial:r?{opacity:0,scale:.85,rotate:-30}:!1,animate:{opacity:1,scale:1,rotate:0},transition:{duration:.5,ease: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(he.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 hu({onComplete:e}){const{displayName:t,updateName:s}=cu(),[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(he.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(fu,{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 gu=[{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 xu({className:e,compact:t=!1}){return n.jsxs("div",{className:le("flex flex-wrap items-center gap-x-3 gap-y-1 text-muted",t?"text-micro":"text-caption",e),children:[n.jsxs("span",{className:"text-faint",children:["© ",new Date().getFullYear()," OrgX"]}),gu.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 mo="orgx.user.name-asked";function yu(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 bu(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 wu(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const po={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},Li="orgx.onboarding.mc_hint.dismissed",Di={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 vu({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(Li)==="1"),[b,h]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(mo)!=="1"),v=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(mo,"1"),h(!1)},[]);o.useEffect(()=>{typeof window>"u"||(g?window.localStorage.setItem(Li,"1"):window.localStorage.removeItem(Li))},[g]);const y=e.status==="manual_key",j=e.status==="awaiting_browser_auth"||e.status==="pairing",w=wu(e.status),k=w==="active"&&e.status!=="connected",m=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(he.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(he.div,{...Di,children:n.jsx(hu,{onComplete:v})},"welcome-name"):y?n.jsx(he.div,{...Di,children:n.jsx(lu,{isSubmitting:r,onSubmit:l,onBack:c})},"manual"):n.jsx(he.div,{...Di,children:n.jsx(au,{state:e,isStarting:s,onConnect:()=>{a()},onUseManualKey:d,onContinueWithoutOrgX:u})},"explainer")}),!t&&(j||e.status==="connected")&&n.jsxs(he.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 ${po[w]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${po[w]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:yu(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:bu(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"})]})]}),m&&n.jsxs(he.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(xu,{compact:!0})})]})})}function ku({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 gi({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],m=document.activeElement;!v.shiftKey&&m===k?(v.preventDefault(),w.focus()):v.shiftKey&&m===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(he.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(he.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:Zl.createPortal(g,document.body)}const ju=[{id:"agents",label:"Agents",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]})},{id:"activity",label:"Activity",icon:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})})},{id:"decisions",label:"Decisions",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"}),n.jsx("path",{d:"m9 12 2 2 4-4"})]})},{id:"initiatives",label:"Next Up",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"}),n.jsx("line",{x1:"4",x2:"4",y1:"22",y2:"15"})]})}];function Nu({activeTab:e,onTabChange:t,pendingDecisionCount:s=0}){return n.jsx("nav",{className:"pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3 lg:hidden",style:{bottom:"max(10px, env(safe-area-inset-bottom))"},"aria-label":"Mobile sections",children:n.jsx("div",{className:"pointer-events-auto relative flex items-stretch gap-1 rounded-[24px] border border-strong bg-[#090d16]/90 p-1.5 shadow-[0_20px_50px_rgba(0,0,0,0.52)] backdrop-blur-xl",children:ju.map(r=>{const i=e===r.id;return n.jsxs("button",{type:"button",onClick:()=>t(r.id),"aria-current":i?"page":void 0,className:le("relative flex min-w-[76px] flex-1 flex-col items-center gap-1 overflow-hidden rounded-[18px] px-2 pb-1.5 pt-2.5 transition-colors",i?"text-lime":"text-secondary hover:text-white/72"),children:[i&&n.jsxs(n.Fragment,{children:[n.jsx(he.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(he.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:le("relative inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors",i?"border-[#BFFF00]/35 bg-[#BFFF00]/[0.12] text-[#D8FFA1]":"border-white/[0.1] bg-white/[0.03]"),children:[n.jsx("span",{className:"relative z-[1]",children:r.icon}),r.id==="decisions"&&s>0&&n.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-3.5 min-w-[14px] items-center justify-center rounded-full border border-black/35 px-1 text-[8px] font-bold text-black shadow-[0_2px_8px_rgba(0,0,0,0.35)]",style:{backgroundColor:D.amber},children:s>99?"99+":s})]}),n.jsx("span",{className:le("relative z-[1] text-micro font-medium",i?"text-[#D8FFA1]":"text-secondary"),children:r.label})]},r.id)})})})}function Us({children:e,className:t="",surface:s=!0}){return n.jsx("section",{className:le("relative overflow-hidden rounded-2xl",s?"surface-tier-1":"",t),children:e})}const Iu={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"},Au="/orgx/live/",on=e=>`${Au.replace(/\/+$/,"/")}${e}`,Su={pace:on("brand/product-orchestrator.png"),eli:on("brand/engineering-autopilot.png"),mark:on("brand/launch-captain.png"),sage:on("brand/pipeline-intelligence.png"),orion:on("brand/control-tower.png"),dana:on("brand/design-codex.png"),xandy:on("brand/xandy-orchestrator.png"),nova:on("brand/xandy-orchestrator.png"),openclaw:on("brand/openclaw-mark.svg"),codex:on("brand/openai-mark.svg"),openai:on("brand/openai-mark.svg"),anthropic:on("brand/anthropic-mark.svg"),orgx:on("brand/orgx-logo.png")},_u=[{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 Cu(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of _u)if(s.test.test(t))return Su[s.key];return null}function Bt({name:e,size:t="xs",hint:s,src:r}){const i=Yd(e),[a,l]=o.useState(!1),c=o.useMemo(()=>r&&r.trim()?r:Cu(e,s),[s,e,r]),d=!!(c&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${Iu[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"}):Zd(e)})}Bt.displayName="AgentAvatar";const Mu={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 Cn({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:le("inline-flex h-7 items-center rounded-full border text-caption font-medium leading-none whitespace-nowrap",i?"gap-1.5 pl-[3px] pr-2.5 [&>[data-agent-avatar]]:h-5 [&>[data-agent-avatar]]:w-5":"gap-1.5 px-2.5",Mu[t],s),...r,children:e})}function Tu(e){var s,r;const t=[];if(e.initiativeId){const i={id:e.initiativeId,label:e.initiativeTitle||Cs(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=bl(e.status),l={id:e.workstreamId,label:e.workstreamTitle||Cs(e.workstreamId,"Workstream"),type:"workstream",status:a,progress:e.scopeProgress?{done:e.scopeProgress.completedTasks,total:e.scopeProgress.totalTasks}:void 0,agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]};if((s=e.scopeProgress)!=null&&s.milestones&&e.scopeProgress.milestones.length>0)for(const c of e.scopeProgress.milestones){const d=c.done>=c.total?"done":c.done>0?"active":"pending",u={id:c.id,label:c.title||Cs(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:Cs(d,"Task"),type:"task",status:u<c?"done":"pending"}))}i.children.push(l)}t.push(i)}return t}function Uh(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||Cs(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,r=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||Cs(e.workstreamId,"Workstream"),type:"workstream",status:bl(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,i=e.taskId?{id:e.taskId,label:e.taskTitle||Cs(e.taskId,"Task"),type:"task",highlight:!0}:null;return r&&i&&(r.children=[i]),s&&r?(s.children=[r],t.push(s)):r?t.push(r):s&&t.push(s),t}function Cs(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function bl(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 wl(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 Eu(e){const t=wl(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const Ru=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(he.div,{className:"h-full rounded-full",style:{backgroundColor:r},initial:{width:0},animate:{width:`${i}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),Lu=16,Du=14,fo=8,$u=8,Fu=28,Pu=24,Ou=24,Bu=20,$i="rgba(255,255,255,0.07)";function qu(e){const t=e?Du:Lu,s=t+$u+4;return{iconSz:t,colW:s,rowH:e?Ou:Fu,rowHTask:e?Bu:Pu}}function vl({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}=qu(i),j=x?y:v,w=e.children??[],k=w.filter(V=>V.type==="task"),m=w.filter(V=>V.type!=="task"),_=k.length>l&&!c,H=_?k.slice(0,l):k,oe=k.length-H.length,K=[...m,...H],be=K.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:$i,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:$i,left:(t-1)*h+h/2,top:j/2,width:h}})]}),n.jsxs(he.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:{...Eu(e.status),width:fo,height:fo}}):n.jsx(bn,{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(Ru,{done:e.progress.done,total:e.progress.total,color:wl(e.status)})})]})]}),be&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:$i,left:t*h+h/2,top:j/2,height:j/2}}),be&&n.jsxs("div",{children:[K.map((V,Y)=>n.jsx(vl,{node:V,depth:t+1,isLast:Y===K.length-1&&!_,activeId:r,compact:i,index:a+Y+1,taskLimit:l,expanded:c,onToggleExpand:d},V.id)),_&&n.jsxs(he.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{delay:(a+K.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:["+",oe," more · see all"]}),n.jsx(yt,{children:c&&k.length>l&&n.jsx(he.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 zu=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(vl,{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))})}),oa={engineering:{domain:"engineering",displayName:"Engineering",gradient:["#22c55e","#14b8a6"],accentColor:"#22c55e",glowColor:"#22c55e33",icon:"hammer",progressStyle:"linear",verb:"Building"},design:{domain:"design",displayName:"Design",gradient:["#a78bfa","#ec4899"],accentColor:"#a78bfa",glowColor:"#a78bfa33",icon:"palette",progressStyle:"wave",verb:"Designing"},product:{domain:"product",displayName:"Product",gradient:["#3b82f6","#6366f1"],accentColor:"#3b82f6",glowColor:"#3b82f633",icon:"compass",progressStyle:"stepped",verb:"Specifying"},marketing:{domain:"marketing",displayName:"Marketing",gradient:["#f59e0b","#ef4444"],accentColor:"#f59e0b",glowColor:"#f59e0b33",icon:"megaphone",progressStyle:"wave",verb:"Crafting"},sales:{domain:"sales",displayName:"Sales",gradient:["#06b6d4","#3b82f6"],accentColor:"#06b6d4",glowColor:"#06b6d433",icon:"handshake",progressStyle:"linear",verb:"Preparing"},operations:{domain:"operations",displayName:"Operations",gradient:["#64748b","#475569"],accentColor:"#64748b",glowColor:"#64748b33",icon:"shield",progressStyle:"stepped",verb:"Securing"},orchestrator:{domain:"orchestrator",displayName:"Orchestrator",gradient:["#8b5cf6","#6366f1"],accentColor:"#8b5cf6",glowColor:"#8b5cf633",icon:"workflow",progressStyle:"linear",verb:"Coordinating"}},Wu=Object.keys(oa);function ho(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of Wu)if(t.includes(s))return s;return"engineering"}function go(e){return oa[e]??oa.engineering}const Os={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},lr={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},xo={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},yo={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 kl(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=yo[r];if(i){const a=lr[i]??"";return{name:i,domain:a,color:Os[i]??s.color,displayLabel:a?`${i} (${a})`:i}}for(const[a,l]of Object.entries(xo))if(r.includes(a)){const c=lr[l]??"";return{name:l,domain:c,color:Os[l]??s.color,displayLabel:c?`${l} (${c})`:l}}}if(t){const r=t.trim();if(Os[r]){const l=lr[r]??"";return{name:r,domain:l,color:Os[r],displayLabel:l?`${r} (${l})`:r}}const i=r.toLowerCase(),a=yo[i];if(a){const l=lr[a]??"";return{name:a,domain:l,color:Os[a]??s.color,displayLabel:l?`${a} (${l})`:a}}for(const[l,c]of Object.entries(xo))if(i.includes(l)){const d=lr[c]??"";return{name:c,domain:d,color:Os[c]??s.color,displayLabel:d?`${c} (${d})`:c}}}return s}function Hh({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(Bt,{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 Uu=new Set(["running","active","in_progress","working","planning","dispatching"]),Hu=new Set(["running","dispatching"]),Vu=3*6e4;function Ku(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=Vu:!1}function Gu(e){const t=zt(e.status??""),s=zt(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:Uu.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?Ku(e.lastHeartbeatAt):!1}function jl(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function Xu(e){const t=zt(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"border-teal-300/28 bg-teal-400/[0.10] text-teal-100":t==="blocked"||t==="failed"||t==="error"?"border-red-400/26 bg-red-500/[0.10] text-red-100":t==="paused"||t==="pending"||t==="queued"?"border-amber-300/28 bg-amber-300/[0.10] text-amber-100":"border-[#BFFF00]/24 bg-[#BFFF00]/[0.10] text-[#E8FFD0]"}function Qu(e){const t=zt(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"from-teal-300/0 via-teal-300/65 to-teal-300/0":t==="blocked"||t==="failed"||t==="error"?"from-red-300/0 via-red-300/65 to-red-300/0":t==="paused"||t==="pending"||t==="queued"?"from-amber-300/0 via-amber-300/65 to-amber-300/0":"from-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function Nl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function $r(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Is(e,t){const s=[],r=i=>{if(typeof i!="string")return;const a=i.trim();a&&(s.some(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 ii(e,t){if(!e)return t;const s=e.trim();return s?zn(s)?`${t} ${cs(s)}`:s:t}const Ju=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),Yu=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function Zu(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?Ju.has(t)||t.startsWith("telegram:"):!1}function em(e){if(!e)return!1;const t=e.trim();return t?Yu.some(s=>s.test(t)):!1}function Il({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())??"",m=((h=w.workstreamId)==null?void 0:h.trim())??"";if(!k||!m)continue;const _=`${k}:${m}`;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(!Hu.has(w.status))continue;const k=(w.runId??w.sliceRunId??"").trim();if(!k)continue;const m=Is(w.initiativeIds,w.initiativeId),_=Is(w.workstreamIds,w.workstreamId),H=m[0]??null,oe=_[0]??null,K=[];for(const ye of m)for(const we of _)!ye||!we||K.push(`${ye}:${we}`);if(!(l.has(k)||K.some(ye=>a.has(ye))))continue;const V=i.get(k)??(K.length>0?K.map(ye=>a.get(ye)??null).find(ye=>!!ye)??null:null),Y=H?r.get(H)??H:null,ce=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:zt(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:ce??(V==null?void 0:V.progress)??null,initiativeId:H,initiativeIds:m,initiativeTitle:Y,workstreamId:oe,workstreamIds:_,iwmtId:w.iwmtId??null,iwmtIds:Is(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)=>$r(k.updatedAt)-$r(w.updatedAt)),c.length>0){const w=[],k=new Set;for(const m of c){const _=m.initiativeId??((j=m.initiativeIds)==null?void 0:j[0])??"none",oe=(m.workstreamId?`scope:${_}:${m.workstreamId}`:null)??(m.runId?`run:${m.runId}`:m.key);k.has(oe)||(k.add(oe),w.push(m))}return w}const d=e.filter(w=>{if(!Gu(w))return!1;const k=(w.initiativeId??"").trim(),m=(w.workstreamId??"").trim();return k.length>0&&m.length>0});d.sort((w,k)=>{const m=$r(w.updatedAt??w.lastEventAt??w.startedAt);return $r(k.updatedAt??k.lastEventAt??k.startedAt)-m});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:zt(w.status??""),title:w.title,subtitle:(k=w.lastEventSummary)!=null&&k.trim()?w.lastEventSummary.trim():null,progress:w.progress,initiativeId:w.initiativeId,initiativeIds:Is(void 0,w.initiativeId),initiativeTitle:w.initiativeId?r.get(w.initiativeId)??w.groupLabel??null:w.groupLabel??null,workstreamId:w.workstreamId,workstreamIds:Is(void 0,w.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:w.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:w.updatedAt??w.lastEventAt??w.startedAt??null}})}const tm=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,m]=o.useState(null),[_,H]=o.useState(null),[oe,K]=o.useState(null),[be,V]=o.useState(null),Y=o.useMemo(()=>{const Z=new Map;if(!Array.isArray(s))return Z;for(const de of s){const Re=Is(de.initiativeIds,de.initiativeId),ne=Is(de.workstreamIds,de.workstreamId);for(const X of Re)for(const P of ne){if(!X||!P)continue;const J=`${X}:${P}`;Z.has(J)||Z.set(J,de)}const $=(de.runId??de.sliceRunId??"").trim();$&&!Z.has(`run:${$}`)&&Z.set(`run:${$}`,de)}return Z},[s]),ce=o.useMemo(()=>Il({sessions:t,sliceRuns:s,initiatives:r}),[r,t,s]),ye=o.useMemo(()=>{const Z=new Map;for(const de of ce){const Re=zt(de.status);Z.set(Re,(Z.get(Re)??0)+1)}return Array.from(Z.entries()).sort((de,Re)=>Re[1]-de[1]).map(([de,Re])=>({status:de,count:Re}))},[ce]),we=o.useMemo(()=>k?ce.filter(Z=>zt(Z.status)===k):ce,[k,ce]),W=o.useMemo(()=>{var ne,$;const Z=new Map,de=[];for(const X of we){const P=(((ne=X.initiativeIds)==null?void 0:ne[0])??X.initiativeId??"").trim(),J=((($=X.workstreamIds)==null?void 0:$[0])??X.workstreamId??"").trim();if(!P){de.push(X);continue}let ie=Z.get(P);ie||(ie={title:X.initiativeTitle??P,wsMap:new Map},Z.set(P,ie));const ve=J||"__none__";let ke=ie.wsMap.get(ve);ke||(ke={title:X.workstreamTitle??(J||"Unassigned"),rows:[],completedCount:0,lastActivity:null},ie.wsMap.set(ve,ke));const ee=zt(X.status);if(ee==="completed"||ee==="done"?ke.completedCount+=1:ke.rows.push(X),X.updatedAt){const Te=Date.parse(X.updatedAt),pe=ke.lastActivity?Date.parse(ke.lastActivity):0;Number.isFinite(Te)&&Te>pe&&(ke.lastActivity=X.updatedAt)}}const Re=[];for(const[X,P]of Z){const J=[];for(const[ie,ve]of P.wsMap)J.push({workstreamId:ie,workstreamTitle:ve.title,rows:ve.rows,completedCount:ve.completedCount,lastActivityAt:ve.lastActivity});J.sort((ie,ve)=>{const ke=ie.lastActivityAt?Date.parse(ie.lastActivityAt):0;return(ve.lastActivityAt?Date.parse(ve.lastActivityAt):0)-ke}),Re.push({initiativeId:X,initiativeTitle:P.title,workstreams:J})}return Re.sort((X,P)=>{const J=Math.max(0,...X.workstreams.map(ve=>ve.lastActivityAt?Date.parse(ve.lastActivityAt):0));return Math.max(0,...P.workstreams.map(ve=>ve.lastActivityAt?Date.parse(ve.lastActivityAt):0))-J}),{groups:Re,ungrouped:de}},[we]),[Ie,Ee]=o.useState(new Set),fe=async(Z,de,Re)=>{if(Z.session){V(null),H(Z.session.id);try{await de(Z.session),V(Re)}catch(ne){const $=ne instanceof Error?ne.message:"";V($?Rt($):"Workstream action failed")}finally{H(null)}}};return n.jsxs(Us,{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:ce.length})]})}):null,ye.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:()=>m(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:ce.length})]}),ye.map(({status:Z,count:de})=>n.jsxs("button",{type:"button",onClick:()=>m(Re=>Re===Z?null:Z),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${k===Z?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[jl(Z),n.jsx("span",{className:"tabular-nums opacity-70",children:de})]},Z))]}),be&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:be}),we.length===0?ce.length===0&&d>0&&u?n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 px-6 py-10 text-center",children:[n.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.03]",children:n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:"h-5 w-5 text-secondary","aria-hidden":!0,children:n.jsx("path",{d:"M10 6v4m0 4h.01M3 10a7 7 0 1114 0 7 7 0 01-14 0z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-medium text-primary",children:"All clear"}),n.jsxs("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:["No active runs right now."," ",n.jsx("span",{className:"tabular-nums font-semibold text-[#F5B700]/90",children:d})," ",d===1?"item needs":"items need"," your attention."]})]}),n.jsxs("button",{type:"button",onClick:u,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-[#F5B700]/25 bg-[#F5B700]/[0.08] px-4 text-caption font-semibold text-[#FFE7A8] transition-colors hover:border-[#F5B700]/40 hover:bg-[#F5B700]/[0.14]",children:[n.jsx("span",{children:"Review needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:d})]})]}):n.jsx("div",{className:"flex flex-1 items-center justify-center px-4 py-10",children:n.jsx("p",{className:"text-body text-secondary",children:ce.length===0?"No runs in progress.":"No runs match this filter."})}):n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-2",children:n.jsxs(he.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[W.groups.map(Z=>n.jsxs("div",{children:[n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:qt(Z.initiativeTitle&&!zn(Z.initiativeTitle)?Z.initiativeTitle:ii(Z.initiativeId,"Initiative"))}),Z.workstreams.map(de=>{var ee,Te;const Re=`${Z.initiativeId}:${de.workstreamId}`,ne=Ie.has(Re),$=de.rows[0]??null,X=$?kl((ee=$.session)==null?void 0:ee.agentId,(Te=$.session)==null?void 0:Te.agentName):null,P=$!=null&&$.milestoneProgress?$.milestoneProgress.reduce((pe,C)=>pe+C.total,0):null,J=$!=null&&$.milestoneProgress?$.milestoneProgress.reduce((pe,C)=>pe+C.done,0):null,ie=P&&P>0?`Task ${(J??0)+1} of ${P}`:null,ve=P&&P>0?Math.round((J??0)/P*100):($==null?void 0:$.progress)!=null?Nl($.progress):null,ke=qt($!=null&&$.workstreamTitle&&!zn($.workstreamTitle)?$.workstreamTitle:ii(de.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:[X&&n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${X.color}20`,color:X.color},children:X.name.charAt(0).toUpperCase()}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-[13px] font-semibold text-white/88",title:ke,children:ke}),X?n.jsx("p",{className:"truncate text-[11px] font-medium",style:{color:X.color},title:X.displayLabel,children:X.displayLabel}):null]})]}),ie&&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:ie}),n.jsx("div",{className:"h-1 rounded-full bg-white/10 w-24",children:n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,ve??0)}%`,backgroundColor:(X==null?void 0:X.color)??"#14B8A6"}})})]})]}),n.jsx("div",{className:"space-y-2",children:de.rows.map((pe,C)=>n.jsx(bo,{row:pe,index:C,sliceRunByScope:Y,busySessionId:_,expandedRowKey:oe,setExpandedRowKey:K,onOpenSession:g,onFocusRunId:x,onPauseWorkstream:h,onResumeWorkstream:v,onRestartSession:y,onPlayWorkstream:b,onIntervene:j,onOpenSliceDetail:w,runWorkstreamAction:fe,showInitiativeLabel:!1},pe.key))}),de.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>Ee(pe=>{const C=new Set(pe);return C.has(Re)?C.delete(Re):C.add(Re),C}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:ne?`Hide ${de.completedCount} completed`:`${de.completedCount} completed`})})]},de.workstreamId)})]},Z.initiativeId)),W.ungrouped.length>0&&n.jsxs("div",{children:[W.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:W.ungrouped.map((Z,de)=>n.jsx(bo,{row:Z,index:de,sliceRunByScope:Y,busySessionId:_,expandedRowKey:oe,setExpandedRowKey:K,onOpenSession:g,onFocusRunId:x,onPauseWorkstream:h,onResumeWorkstream:v,onRestartSession:y,onPlayWorkstream:b,onIntervene:j,onOpenSliceDetail:w,runWorkstreamAction:fe,showInitiativeLabel:!0},Z.key))})]})]})})]})});function bo({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 de,Re,ne,$,X,P,J,ie,ve,ke;const j=zt(e.status??""),w=e.updatedAt,k=e.subtitle?e.subtitle:w?`Updated ${_t(w)}`:null,m=y&&(e.initiativeTitle||e.initiativeId)?qt(e.initiativeTitle&&!zn(e.initiativeTitle)?e.initiativeTitle:ii(e.initiativeId,"Initiative")):null,_=(de=e.title)!=null&&de.trim()?e.title:"",H=Zu(_)&&((Re=e.workstreamTitle)!=null&&Re.trim())?e.workstreamTitle:_||e.workstreamTitle||"",oe=ii(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),K=qt(H&&!zn(H)?H:oe),be=k&&!em(k)?qt(k):null,V=Nl(e.progress),Y=["running","active","in_progress","working","planning","dispatching"].includes(j),ce=["paused","blocked","queued","pending"].includes(j),ye=g??x,we=V===null&&["running","active","in_progress","working","planning","dispatching"].includes(j),W=e.session?r===e.session.id:!1,Ie=i===e.key,Ee=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),fe=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),Z=kl((ne=e.session)==null?void 0:ne.agentId,($=e.session)==null?void 0:$.agentName);return n.jsxs(he.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,fe),role:"button",tabIndex:0,onKeyDown:ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),h==null||h(e,fe))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${Qu(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":Z.color}:void 0,children:n.jsx(Bt,{name:((X=e.session)==null?void 0:X.agentName)??"OrgX",hint:((P=e.session)==null?void 0:P.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[m?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:m}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(bn,{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:K,children:K})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[e.scope&&e.scope!=="task"&&n.jsx(Cn,{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] ${Xu(j)}`,children:jl(j)}),w&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:rc(new Date(w),{addSuffix:!0})})]}),be?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:be,children:be}):null,null,(V!==null||we)&&n.jsxs("div",{className:"mt-2",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro",children:[n.jsx("span",{className:"text-secondary",children:"Progress"}),n.jsx("span",{className:"font-semibold text-primary tabular-nums",children: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, ${go(ho((J=e.session)==null?void 0:J.agentId)).gradient[0]}, ${go(ho((ie=e.session)==null?void 0:ie.agentId)).gradient[1]})`}})})]}),e.milestoneProgress&&e.milestoneProgress.length>0&&n.jsx("div",{className:"mt-2",children:n.jsx(zu,{nodes:Tu({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((ee,Te)=>ee+Te.total,0),completedTasks:e.milestoneProgress.reduce((ee,Te)=>ee+Te.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((ve=e.session)==null?void 0:ve.agentName)??null,agentId:((ke=e.session)==null?void 0:ke.agentId)??null}),activeId:e.workstreamId,compact:!0})}),Ee?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:ee=>{ee.stopPropagation(),a(Te=>Te===e.key?null:e.key)},className:"inline-flex h-6 items-center gap-1 rounded-md px-1 text-micro font-semibold text-secondary transition-colors hover:text-white",children:Ie?"Hide details":"Slice details"}),Ie?n.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-white/[0.08] bg-black/[0.18] px-2.5 py-2",children:[e.workstreamTitle?n.jsxs("p",{className:"text-caption text-secondary",children:["Workstream: ",n.jsx("span",{className:"text-white/90",children:e.workstreamTitle})]}):null,n.jsxs("div",{className:"flex flex-wrap gap-1.5 text-micro",children:[n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Tasks ",e.taskIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Milestones ",e.milestoneIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Artifacts ",e.artifactCount]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Needs input ",e.decisionCount]})]})]}):null]}):null,n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 border-t border-white/[0.07] pt-2",onClick:ee=>ee.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&&Y&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:W,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&&ce&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:W,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&&ye&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:W,onClick:()=>void v(e,ye,`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:W,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 nm={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 xi({icon:e="inbox",headline:t,description:s,primaryAction:r,secondaryAction:i,className:a}){return n.jsxs(he.div,{className:le("flex flex-col items-center justify-center py-12 px-6 text-center max-w-md mx-auto",a),initial:"hidden",animate:"visible",variants:{visible:{transition:{staggerChildren:.04}}},children:[n.jsx(he.div,{className:"flex h-12 w-12 items-center justify-center rounded-xl border border-white/[0.08] bg-white/[0.04]",variants:Dr,custom:0,children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",className:"text-secondary",children:nm[e]})}),n.jsx(he.h4,{className:"mt-5 text-heading font-semibold text-white",variants:Dr,custom:1,children:t}),n.jsx(he.p,{className:"mt-2 text-body text-secondary leading-relaxed",variants:Dr,custom:2,children:s}),(r||i)&&n.jsxs(he.div,{className:"mt-5 flex items-center gap-2",variants:Dr,custom:3,children:[r&&n.jsx("button",{type:"button",onClick:r.onClick,className:"control-pill px-4 text-[12px] font-medium",style:{borderColor:"rgba(191, 255, 0, 0.24)",background:"rgba(191, 255, 0, 0.09)",color:"#d8ffa1"},children:r.label}),i&&n.jsx("button",{type:"button",onClick:i.onClick,className:"control-pill px-4 text-[12px] font-medium",children:i.label})]})]})}const sm=new Set(["awaiting_input","needs_review","failed"]);function wo(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function rm(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 Al(e){const t=e.filter(r=>sm.has(r.status)).sort((r,i)=>wo(i.updatedAt??i.lastEventAt??"")-wo(r.updatedAt??r.lastEventAt??"")),s=new Map;for(const r of t){const i=rm(r),a=s.get(i);if(!a){s.set(i,{item:r,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function im(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 am(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function om(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 lm(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 cm(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 la(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return zn(s)?`${t} ${cs(s)}`:s}function dm(e){if(!e)return null;const t=qt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function um(e,t,s){const r=(t==null?void 0:t.trim())??"";if(r&&!zn(r)){const a=qt(r);if(a!=="Untitled session")return a}const i=dm(e.statusExplainer);return i||(s?la(s,"Workstream"):la(e.sliceRunId,"Slice"))}const mm=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(()=>Al(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(Us,{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(xi,{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 we;const k=(Array.isArray(y.initiativeIds)&&y.initiativeIds.length>0?y.initiativeIds[0]:y.initiativeId)??null,m=(Array.isArray(y.workstreamIds)&&y.workstreamIds.length>0?y.workstreamIds[0]:y.workstreamId)??null,_=(k?b.get(k):null)??la(k,"Initiative"),H=y.workstreamTitle??(m?h.get(m)??null:null),oe=um(y,H,m),K=(we=y.statusExplainer)!=null&&we.trim().length?y.statusExplainer:"Review this slice to continue execution.",be=qt(cm(y)),V=qt(K),Y=qt(_),ce=y.scope?y.scope.replace(/_/g," "):null,ye=y.updatedAt??y.lastEventAt??null;return n.jsxs(he.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:W=>{(W.key==="Enter"||W.key===" ")&&(W.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 ${om(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(bn,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:Y})]}),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:oe,children:[n.jsx(bn,{type:"workstream",size:12,className:"mt-[3px] flex-shrink-0 opacity-90"}),n.jsx("span",{className:"line-clamp-2",children:oe})]}),n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:be,children:be}),V!==be&&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] ${im(y.status)}`,children:am(y.status)}),ce?n.jsx("span",{className:"chip text-micro capitalize",children:ce}):null]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[j>1&&n.jsxs("span",{className:"chip text-micro",children:[j," similar updates"]}),typeof 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"]}),ye&&n.jsxs("span",{children:["Updated ",_t(ye)]})]}),y.decisionOptions&&y.decisionOptions.length>0&&y.decisionOptions.length<=3&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",onClick:W=>W.stopPropagation(),children:y.decisionOptions.slice(0,3).map(W=>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:W.description??W.label,children:W.label},W.id))}),n.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-white/[0.07] pt-2",onClick:W=>W.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:lm(y)})]})]},y.sliceRunId)})})]})});function pm(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function fm(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 hm(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function gm(e){return{id:e.id,name:e.title,status:pm(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:fm(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 vo=150,xm=12;function ko(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function ym(){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 Sl(e,t=null){return ps({queryKey:Jn.entities({type:"initiative",projectId:t}),queryFn:async()=>{var c;if(Ft())return ym();const s=[],r=(t==null?void 0:t.trim())??"";let i=0;for(let d=0;d<xm;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(vo),offset:String(i)});r&&fs(u,r);const g=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:At({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+=vo}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}ko(d.updated_at??d.created_at)>ko(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=>hm(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(gm)},enabled:e,staleTime:6e4})}const Fr=50,jo=8;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){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function vm(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function km(e){const t=vm(e.sequence);return{id:e.id,name:e.title,status:bm(e.status),rawStatus:e.status??null,priority:e.priority??null,category:void 0,health:Math.max(0,Math.min(100,Math.round(e.progress??0))),daysRemaining:0,targetDate:e.targetDate??e.dueDate??e.etaEndAt??null,createdAt:e.createdAt??null,updatedAt:e.updatedAt??null,sequenceIndex:t,hierarchyLabel:typeof t=="number"?`I${t+1}`:void 0,activeAgents:e.activeAgents??0,totalAgents:e.totalAgents??0,description:void 0}}function jm(e,t=null){return ps({queryKey:Jn.liveInitiatives({limit:Fr*jo,projectId:t}),queryFn:async()=>{var l;if(Ft())return[];const s=[];let r=0;for(let c=0;c<jo;c+=1){const d=new URLSearchParams({limit:String(Fr),offset:String(r)});t&&t.trim().length>0&&fs(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:At({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===Fr)||x.length===0)break;r+=Fr}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=>wm(c.status)).map(km)},enabled:e,staleTime:3e4})}const _l=o.createContext(null);function Nm({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(_l.Provider,{value:{state:t,open:r,close:i},children:e})}function Cl(){const e=o.useContext(_l);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function Im(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 No(e){const{className:t}=e,{key:s,segments:r}=Im(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(he.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 Vh={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"},Am={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"},Kh=e=>Am[zt(e)]??"text-white/60 bg-white/5 border-white/10",Gh=e=>{const t=zt(e);return t==="active"||t==="in_progress"?"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20":t==="blocked"?"text-[#FF6B88] bg-[#FF6B88]/10 border-[#FF6B88]/20":t==="completed"||t==="done"?"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20":"text-white/60 bg-white/5 border-white/10"},Xh=e=>{const t=zt(e);return t==="done"||t==="completed"?"text-[#14B8A6] bg-[#14B8A6]/10 border-[#14B8A6]/20":t==="active"||t==="in_progress"?"text-[#BFFF00] bg-[#BFFF00]/10 border-[#BFFF00]/20":"text-white/60 bg-white/5 border-white/10"},Qh=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Jh=e=>{const t=zt(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},As=e=>{const t=zt(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)"},ai={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)"}},Sm=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Zr(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)Zr(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"?(Sm.some(c=>l.includes(c))||l.startsWith("meta")||l.endsWith("id"))&&Zr(a,t,s+1,r):typeof a=="object"&&a!==null&&Zr(a,t,s+1,r)}}}}function _m(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 ds(...e){const t=[],s=new Set;for(const r of e)Zr(r,t,0,s);for(const r of t){const i=_m(r);if(i)return ai[i]}return ai.unknown}function Cm(e){return ai[e]??ai.unknown}const Mm={xs:18,sm:24,md:30};function Tm({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:hi,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 Hs({provider:e,size:t="sm",className:s,showRing:r=!0}){const i=Cm(e),a=Mm[t];return n.jsx("span",{className:le("inline-flex items-center justify-center rounded-md",s),style:{width:a,height:a,color:i.accent,backgroundColor:i.tint,border:r?`1px solid ${i.accent}55`:"none"},title:i.label,"aria-label":i.label,children:n.jsx("span",{style:{width:Math.round(a*.66),height:Math.round(a*.66),display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(Tm,{provider:e})})})}function Em({running:e,blocked:t,paused:s,size:r=36,children:i}){const a=Yn(),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(he.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 Pr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function ka(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function ja(e,t){if(typeof t=="number")return`${e}${t+1}`}const Rm=(e,t)=>{const s=ka(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:ja("W",s)}},Lm=(e,t)=>{const s=ka(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:ja("M",s)}},Dm=(e,t)=>{const s=ka(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:ja("T",s)}};function Fi(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 $m(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 Fm({initiativeId:e,authToken:t=null,embedMode:s=!1,enabled:r=!0}){var c;const i=rd(e),a=o.useMemo(()=>Jn.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),l=ps({queryKey:a,enabled:r&&!!e&&i,queryFn:async()=>{if(!e)return Pr;if(Ft())return $m(e);if(!i)return{...Pr,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"}),m=await fetch(`/orgx/api/entities?${k.toString()}`,{headers:u});return m.ok?await m.json():{data:[]}}catch{return{data:[]}}},[x,b,h]=await Promise.all([g("workstream"),g("milestone"),g("task")]),v=Array.isArray(x.data)?Fi(x.data.map(w=>Rm(w,e))):[],y=Array.isArray(b.data)?Fi(b.data.map(w=>Lm(w,e))):[],j=Array.isArray(h.data)?Fi(h.data.map(w=>Dm(w,e))):[];return{initiativeId:e,workstreams:v,milestones:y,tasks:j}}});return{details:(i?l.data:null)??(e?{...Pr,initiativeId:e}:Pr),isLoading:i?l.isLoading:!1,error:i?((c=l.error)==null?void 0:c.message)??null:null,refetch:l.refetch}}function Pm(){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 Na({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return ps({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Ft())return Pm();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 cr(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 Om(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function Bm(e,t){return[...t?e.tasks.filter(r=>r.workstreamId===t):e.tasks].sort((r,i)=>r.title.localeCompare(i.title))}function qm({open:e,onClose:t,onLaunched:s}){var ie,ve,ke,ee,Te,pe;const r=Na({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:i}=Sl(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),[m,_]=o.useState(null),[H,oe]=o.useState("starter"),[K,be]=o.useState(!1),[V,Y]=o.useState(1),ce=Ft(),ye=o.useMemo(()=>{const C=c.trim();return C?(i==null?void 0:i.find(O=>O.id===C))??null:null},[i,c]),{details:we}=Fm({initiativeId:ye?ye.id:null,enabled:e&&!!ye}),W=o.useMemo(()=>Om(we),[we]),Ie=o.useMemo(()=>Bm(we,u||null),[we,u]),Ee=((ie=r.data)==null?void 0:ie.agents)??[],fe=o.useMemo(()=>{const C=a.trim();return C?Ee.find(O=>O.id===C)??null:null},[Ee,a]);o.useEffect(()=>{var O,U;if(!e)return;const C=((O=Ee.find(se=>se.isDefault))==null?void 0:O.id)??((U=Ee[0])==null?void 0:U.id)??"";!a&&C&&l(C)},[Ee,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=(fe==null?void 0:fe.model)??"",O=C.includes("openrouter")?"openrouter":C.includes("anthropic")?"anthropic":C.includes("openai")?"openai":"auto";v(O)},[e,fe==null?void 0:fe.model,a]),o.useEffect(()=>{e&&(k(null),_(null),oe("starter"),Y(1))},[e]),o.useEffect(()=>{g(""),b("")},[c]),o.useEffect(()=>{b("")},[u]),o.useEffect(()=>{e&&(y.trim().length>0||ye&&j(`Kick off: ${ye.name}`))},[y,e,ye]);const Z=!!a.trim()&&!!c.trim(),de=V===1?!!a.trim():V===2?!!c.trim():Z,Re=async()=>{var qe;const C=(m==null?void 0:m.checkout)??"/orgx/api/billing/checkout",O=H&&H.trim().length>0?H.trim():"starter",se=await(await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:O,billingCycle:"monthly"})})).json().catch(()=>null),Le=((qe=se==null?void 0:se.data)==null?void 0:qe.url)??(se==null?void 0:se.url)??null;if(!Le)throw new Error((se==null?void 0:se.error)??"Checkout unavailable");window.open(Le,"_blank","noopener,noreferrer")},ne=async()=>{var Le;const C=(m==null?void 0:m.portal)??"/orgx/api/billing/portal",U=await(await fetch(C,{method:"POST"})).json().catch(()=>null),se=((Le=U==null?void 0:U.data)==null?void 0:Le.url)??(U==null?void 0:U.url)??null;if(!se)throw new Error((U==null?void 0:U.error)??"Billing portal unavailable");window.open(se,"_blank","noopener,noreferrer")},$=async()=>{if(!(!Z||K)){if(ce){t(),s==null||s();return}k(null),_(null),be(!0);try{const C={agentId:a.trim(),message:y.trim()?y.trim():void 0,initiativeId:c.trim(),initiativeTitle:(ye==null?void 0:ye.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 U=await fetch(`/orgx/api/agents/launch?${O.toString()}`,{method:"POST"}),se=await U.json().catch(()=>null);if(!U.ok||!(se!=null&&se.ok))throw(se==null?void 0:se.code)==="upgrade_required"&&(_(se.actions??null),oe(se.requiredPlan??"starter")),new Error((se==null?void 0:se.error)??`Launch failed (${U.status})`);t(),s==null||s()}catch(C){k(C instanceof Error?C.message:"Launch failed")}finally{be(!1)}}},X=!!((ve=fe==null?void 0:fe.run)!=null&&ve.runId)&&!!((ke=fe==null?void 0:fe.run)!=null&&ke.pid),P=async()=>{var C;if(!(!((C=fe==null?void 0:fe.run)!=null&&C.runId)||!X||K)&&!ce){k(null),be(!0);try{const O=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(fe.run.runId)}`,{method:"POST"}),U=await O.json().catch(()=>null);if(!O.ok||!(U!=null&&U.ok))throw new Error((U==null?void 0:U.error)??`Stop failed (${O.status})`);await r.refetch()}catch(O){k(O instanceof Error?O.message:"Stop failed")}finally{be(!1)}}},J=async()=>{var C;if(!(!((C=fe==null?void 0:fe.run)!=null&&C.runId)||K)){if(ce){t(),s==null||s();return}k(null),be(!0);try{const O=new URLSearchParams;O.set("runId",fe.run.runId),y.trim()&&O.set("message",y.trim()),h&&h!=="auto"&&O.set("provider",h);const U=await fetch(`/orgx/api/agents/restart?${O.toString()}`,{method:"POST"}),se=await U.json().catch(()=>null);if(!U.ok||!(se!=null&&se.ok))throw new Error((se==null?void 0:se.error)??`Restart failed (${U.status})`);t(),s==null||s()}catch(O){k(O instanceof Error?O.message:"Restart failed")}finally{be(!1)}}};return e?n.jsx(gi,{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:()=>Y(C),className:le("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(he.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:Ee.map(C=>{const O=cr(C.status);return n.jsxs("option",{value:C.id,children:[C.name," (",C.id,") · ",O.label]},C.id)})})]}),fe&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] p-3 text-body text-secondary",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"font-medium text-primary",children:fe.name}),n.jsx("span",{className:"rounded-full border px-2 py-0.5 text-micro uppercase tracking-[0.12em]",style:{borderColor:`${cr(fe.status).color}55`,color:cr(fe.status).color,backgroundColor:cr(fe.status).bg},children:cr(fe.status).label})]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Model:"})," ",fe.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",fe.workspace??"unknown"]}),((ee=fe.context)==null?void 0:ee.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",fe.context.initiativeTitle??fe.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value: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."})]}),fe.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",fe.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",fe.run.status,")"]})]}),fe.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:P,disabled:!X||K,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:J,disabled:K,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:!ye,className:le("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!ye&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any workstream"}),W.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:!ye,className:le("mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",!ye&&"opacity-50"),children:[n.jsx("option",{value:"",children:"Any task"}),Ie.slice(0,80).map(C=>n.jsx("option",{value:C.id,children:C.title},C.id))]}),Ie.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),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:((fe==null?void 0:fe.name)??a.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Initiative"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:((ye==null?void 0:ye.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=W.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()?((pe=Ie.find(C=>C.id===x))==null?void 0:pe.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}),m&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void Re().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 ne().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"}),m.pricing&&n.jsx("a",{href:m.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).":Z?"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:()=>Y(C=>C>1?C-1:C),disabled:K,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:()=>Y(C=>C<3?C+1:C),disabled:!de||K,className:le("rounded-xl px-4 py-2 text-body font-semibold transition-colors",de&&!K?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:de&&!K?{backgroundColor:D.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:$,disabled:!Z||K,className:le("rounded-xl px-4 py-2 text-body font-semibold transition-colors",Z&&!K?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:Z&&!K?{backgroundColor:D.lime}:void 0,children:K?"Launching…":"Launch"})]})]})]})}):null}const Pi=10,zm=20;function Wm(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?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}function Hm({open:e,onClose:t,agentName:s,catalogAgent:r,sessions:i,activity:a,onSelectSession:l,onRefresh:c}){var be,V,Y,ce,ye,we;const[d,u]=o.useState(!1),[g,x]=o.useState(!1),[b,h]=o.useState(null),v=xl(s),y=Wm((r==null?void 0:r.status)??null),j=o.useMemo(()=>{let W=0,Ie=0,Ee=0,fe=0;for(const Z of i)Z.status==="running"||Z.status==="queued"||Z.status==="pending"?W++:Z.status==="blocked"?Ie++:Z.status==="failed"||Z.status==="cancelled"?Ee++:(Z.status==="completed"||Z.status==="archived")&&fe++;return{running:W,blocked:Ie,failed:Ee,completed:fe}},[i]),w=o.useMemo(()=>[...i].sort((W,Ie)=>Date.parse(Ie.updatedAt??Ie.lastEventAt??Ie.startedAt??"")-Date.parse(W.updatedAt??W.lastEventAt??W.startedAt??"")),[i]),k=d?w:w.slice(0,Pi),m=w.length>Pi,_=o.useMemo(()=>[...a].sort((W,Ie)=>Date.parse(Ie.timestamp)-Date.parse(W.timestamp)).slice(0,zm),[a]),H=!!((be=r==null?void 0:r.run)!=null&&be.runId)&&!!((V=r==null?void 0:r.run)!=null&&V.pid),oe=async()=>{var W;if(!(!((W=r==null?void 0:r.run)!=null&&W.runId)||!H||g)){h(null),x(!0);try{const Ie=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(r.run.runId)}`,{method:"POST"}),Ee=await Ie.json().catch(()=>null);if(!Ie.ok||!(Ee!=null&&Ee.ok))throw new Error((Ee==null?void 0:Ee.error)??`Stop failed (${Ie.status})`);c==null||c()}catch(Ie){h(Ie instanceof Error?Ie.message:"Stop failed")}finally{x(!1)}}},K=async()=>{var W;if(!(!((W=r==null?void 0:r.run)!=null&&W.runId)||g)){h(null),x(!0);try{const Ie=new URLSearchParams;Ie.set("runId",r.run.runId);const Ee=await fetch(`/orgx/api/agents/restart?${Ie.toString()}`,{method:"POST"}),fe=await Ee.json().catch(()=>null);if(!Ee.ok||!(fe!=null&&fe.ok))throw new Error((fe==null?void 0:fe.error)??`Restart failed (${Ee.status})`);c==null||c()}catch(Ie){h(Ie instanceof Error?Ie.message:"Restart failed")}finally{x(!1)}}};return e?n.jsx(gi,{open:e,onClose:t,maxWidth:"max-w-3xl",children:n.jsxs("div",{className:"flex h-full min-h-0 w-full flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 px-8 pt-6 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0 text-[13px] text-secondary",children:[n.jsx("span",{children:"Agents"}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",className:"flex-shrink-0 opacity-40",children:n.jsx("path",{d:"m9 18 6-6-6-6"})}),n.jsx("span",{className:"truncate text-white font-medium",children:s})]}),n.jsx("button",{type:"button",onClick:t,"aria-label":"Close detail",className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full text-muted transition-colors hover:bg-white/[0.06] hover:text-white focus:outline-none",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-8 py-6 space-y-8",children:[n.jsxs("div",{className:"flex items-start gap-5",children:[n.jsx(Bt,{name:s,size:"lg",hint:s}),n.jsxs("div",{className:"min-w-0 flex-1 pt-1",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("h3",{className:"text-[28px] font-medium leading-none text-white truncate",children:s}),n.jsx("span",{className:"rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-widest",style:{color:y.color,backgroundColor:y.bg},children:y.label})]}),v&&n.jsx("p",{className:"text-[15px] text-secondary mt-2",children:v})]})]}),n.jsx("div",{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",children:[{label:"Running",value:j.running,color:D.lime},{label:"Blocked",value:j.blocked,color:D.red},{label:"Failed",value:j.failed,color:D.amber},{label:"Completed",value:j.completed,color:D.teal}].map(W=>n.jsxs("div",{children:[n.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted",children:W.label}),n.jsx("p",{className:"mt-1 text-2xl font-light",style:{color:W.value>0?W.color:"rgba(255,255,255,0.2)",fontVariantNumeric:"tabular-nums"},children:W.value})]},W.label))}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-12 pt-4",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-6",children:"Sessions"}),i.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No sessions recorded."}):n.jsxs("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-6",children:[k.map(W=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[29px] top-1.5 h-2 w-2 rounded-full border border-black ring-4 ring-black",style:{backgroundColor:As(W.status)}}),n.jsxs("button",{onClick:()=>{l(W.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:W.title}),n.jsx("span",{className:"flex-shrink-0 text-[12px] text-muted tabular-nums",children:_t(W.updatedAt??W.lastEventAt??W.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:W.status}),W.progress!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-white/[0.15]",children:"·"}),n.jsxs("span",{children:[Math.round(W.progress),"%"]})]})]})]})]},W.id)),m&&n.jsx("button",{type:"button",onClick:()=>u(W=>!W),className:"text-[12px] font-medium text-secondary hover:text-white transition-colors focus:outline-none",children:d?"Collapse timeline":`View ${w.length-Pi} older sessions`})]})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-6",children:"Live Activity"}),_.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No recent activity."}):n.jsx("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-5",children:_.map((W,Ie)=>n.jsxs("div",{className:"relative group",children:[n.jsx("div",{className:"absolute -left-[27px] top-1.5 h-1.5 w-1.5 rounded-full ring-4 ring-black",style:{backgroundColor:Um(W.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:W.title??W.summary??W.description??"Activity"}),n.jsx("span",{className:"flex-shrink-0 text-[11px] text-muted tabular-nums mt-0.5",children:_t(W.timestamp)})]})]},W.id??Ie))})]})]}),(r==null?void 0:r.run)&&n.jsxs("div",{className:"pt-4 border-t border-white/[0.04]",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-4",children:"Controls"}),n.jsxs("div",{className:"flex flex-wrap items-center gap-6",children:[n.jsxs("p",{className:"text-[13px] text-secondary",children:[n.jsx("span",{className:"text-muted mr-2",children:"Tracked run:"}),r.run.runId.slice(0,8),"…",n.jsxs("span",{className:"text-muted ml-2",children:["(",r.run.status,")"]})]}),n.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[n.jsx("button",{type:"button",onClick:oe,disabled:!H||g,className:"rounded-lg px-4 py-2 text-[13px] font-medium text-rose-400 transition-colors hover:text-rose-300 hover:bg-rose-400/10 disabled:opacity-40 focus:outline-none",children:g?"Stopping…":"Stop Run"}),n.jsx("button",{type:"button",onClick:K,disabled:g,className:"rounded-lg px-4 py-2 text-[13px] font-medium text-white bg-white/[0.06] transition-colors hover:bg-white/[0.12] disabled:opacity-40 focus:outline-none",children:g?"Restarting…":"Restart"})]}),b&&n.jsx("p",{className:"w-full text-caption text-rose-400",children:b})]})]}),r&&n.jsxs("div",{className:"pt-4 border-t border-white/[0.04]",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-4",children:"Settings"}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-y-4 gap-x-8",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Provider"}),n.jsx("p",{className:"text-[14px] text-primary",children:(Y=r.model)!=null&&Y.includes("openrouter")?"OpenRouter":(ce=r.model)!=null&&ce.includes("anthropic")?"Anthropic":(ye=r.model)!=null&&ye.includes("openai")?"OpenAI":"Auto"})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Model"}),n.jsx("p",{className:le("text-[14px] truncate",r.model?"text-primary":"text-muted"),children:r.model??"Not configured"})]}),r.workspace&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Workspace"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:r.workspace})]}),((we=r.context)==null?void 0:we.initiativeTitle)&&n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Initiative"}),n.jsx("p",{className:"text-[14px] text-primary truncate",children:r.context.initiativeTitle})]})]})]})]})]})}):null}const Or=120,Io=10,Vm=24,Ao=520,Km=58,Gm=56,Xm=20,Qm=8,Ia=new Set(["running","active","in_progress","working","planning","handoff","review"]),Jm=new Set(["blocked","failed"]),Ym=10,Zm=[{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"}],ep=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ca=[{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 at(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function xn(e,t){const s=at(e),r=at(t);if(!s&&!r)return null;const i=[s,r].filter(Boolean).join(" ");if(!i)return null;for(const a of ca)if(a.aliases.some(l=>l.test(i)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function tp(e){const t=xn(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=xn(null,r);if(i)return i}return null}function np(e){const t=at(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 Ml(e){const t=tp(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=at(e.agentId),r=at(e.agentName);if(s||r)return{agentId:e.agentId??null,agentName:e.agentName??null};const i=np(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 sp(e){const t=Ml(e),s=at(t.agentId);if(s)return`id:${s}`;const r=at(t.agentName);return r?`name:${r}`:"unassigned"}function rp(e){const t=e.trim();return t?ep.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function oi(e){const t=(e??"").trim();return t?Es(t):!1}function ip(e){var t,s;return!!(oi((t=e.context)==null?void 0:t.initiativeId)||oi(((s=e.run)==null?void 0:s.initiativeId)??null))}function Oi(e){if(xn(e.agentId,e.agentName))return!0;const s=at(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function ln(e){const t=at(e.status)??"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=at(e.phase);if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const r=at(e.state);return r==="error"?"failed":r==="stopped"?"paused":r==="stale"?"queued":Ia.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function da(e){const t=at(e);return t?Ia.has(t)||Jm.has(t):!1}function So(e){const t=at(e);return t?Ia.has(t):!1}function Br(e){return e?!!(da(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function ap(e){return e?e.state==="active":!1}function op(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function Mn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Bi(e,t){return Mn(t.updatedAt??t.lastEventAt??t.startedAt)-Mn(e.updatedAt??e.lastEventAt??e.startedAt)}function lp({status:e,nodes:t,onSelectSession:s,selectedSessionId:r}){const[i,a]=o.useState(!1),l=As(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(he.span,{animate:{rotate:i?90:0},transition:{duration:.15},className:"text-micro text-muted",children:"▸"})]}),n.jsx(yt,{children:i&&n.jsx(he.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=ds(d.agentName,d.title,d.lastEventSummary,d);return n.jsx(he.button,{onClick:()=>s(d.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.12,delay:Math.min(u*.02,.1)},className:le("w-full rounded-lg px-2.5 py-1.5 text-left transition-colors",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(Hs,{provider:x.id,size:"xs"}),n.jsx("p",{className:"min-w-0 flex-1 truncate text-body text-bright",title:d.title,children:d.title}),n.jsx("span",{className:"text-micro text-muted",children:_t(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const cp=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),[m,_]=o.useState(0),[H,oe]=o.useState(null),K=Na({enabled:!0}),be=((T=K.data)==null?void 0:T.agents)??[],V=o.useMemo(()=>jr(a),[a]),Y=o.useMemo(()=>V===null?s:s.filter(q=>Mn(q.timestamp)>=V),[s,V]);o.useMemo(()=>{var ue,Ce,Ye;const q=new Map,re=[...Y].sort((Je,Fe)=>Mn(Fe.timestamp)-Mn(Je.timestamp));for(const Je of re){const Fe=Je.runId;if(!Fe||q.has(Fe))continue;const Xe=((ue=Je.summary)==null?void 0:ue.trim())??((Ce=Je.description)==null?void 0:Ce.trim())??((Ye=Je.title)==null?void 0:Ye.trim())??"";Xe.length>0&&q.set(Fe,Xe)}return q},[Y]);const{agents:ce,hiddenGroupCount:ye,filteredOutGroupsByDate:we,filteredOutSessionsByDate:W,visibleSessionCount:Ie,archivedGroups:Ee,sessionCountInScope:fe}=o.useMemo(()=>{var Pe;const q=b?t.nodes:t.nodes.filter(z=>!oi(z.initiativeId)),re=b?be:be.filter(z=>!ip(z)),ue=b?x:x.filter(z=>!oi(z.initiativeId)),Ce=new Map,Ye=new Map,Je=[...ue].sort((z,Q)=>Mn(Q.lastEventAt??Q.lastHeartbeatAt)-Mn(z.lastEventAt??z.lastHeartbeatAt));for(const z of Je){z.runId&&!Ce.has(z.runId)&&Ce.set(z.runId,z);const Q=xn(z.agentId,z.agentName??z.displayName),Ne=at((Q==null?void 0:Q.agentId)??z.agentId);if(Ne){const De=Ye.get(Ne)??[];De.push(z),Ye.set(Ne,De)}}const Fe=new Map;for(const z of q){const Q=Ml(z),Ne=sp(z),De=at(Q.agentId),$e=at(Q.agentName);let Oe=Fe.get(Ne)??null;if(!Oe&&De&&$e){const Se=`name:${$e}`,Ge=Fe.get(Se);Ge&&(Fe.delete(Se),Ge.groupKey=Ne,Fe.set(Ne,Ge),Oe=Ge)}if(!Oe&&$e){const Se=Array.from(Fe.values()).find(Ge=>at(Ge.agentName)===$e);Se&&(Oe=Se)}Oe?(Oe.nodes.push(z),!Oe.agentId&&Q.agentId&&(Oe.agentId=Q.agentId),(Oe.agentName==="OrgX"||!Oe.agentName)&&Q.agentName&&(Oe.agentName=Q.agentName)):Fe.set(Ne,{groupKey:Ne,agentId:Q.agentId,agentName:Q.agentName??Q.agentId??"OrgX",nodes:[z],latest:z,runtime:null,runtimeActiveCount:0})}for(const z of re){const Q=xn(z.id,z.name),Ne=(Q==null?void 0:Q.agentId)??z.id,De=(Q==null?void 0:Q.agentName)??z.name,$e=at(Ne),Oe=at(De),Se=$e?`id:${$e}`:null,Ge=Oe?`name:${Oe}`:null;let rt=null;if(Se&&Fe.has(Se))rt=Se;else if(Ge&&Fe.has(Ge))rt=Ge;else{const ze=Array.from(Fe.entries()).find(([,Ct])=>$e&&at(Ct.agentId)===$e||Oe&&at(Ct.agentName)===Oe);rt=(ze==null?void 0:ze[0])??null}if(rt){const ze=Fe.get(rt);ze.catalogAgent=z,!ze.agentId&&Ne&&(ze.agentId=Ne),(ze.agentName==="OrgX"||!ze.agentName)&&De&&(ze.agentName=De),Se&&ze.groupKey!==Se&&!Fe.has(Se)&&(Fe.delete(ze.groupKey),ze.groupKey=Se,Fe.set(Se,ze))}else{const ze=Se??Ge??`catalog:${De.toLowerCase()}`;Fe.set(ze,{groupKey:ze,agentId:Ne,agentName:De,nodes:[],latest:null,catalogAgent:z,runtime:null,runtimeActiveCount:0})}}for(const z of ca){const Q=`orgx:${z.id}`,Ne=`id:${Q}`;let De=Fe.get(Ne)??null;if(!De){const $e=Array.from(Fe.entries()).find(([,Oe])=>{const Se=xn(Oe.agentId,Oe.agentName);return at(Se==null?void 0:Se.agentId)===at(Q)});$e&&(Fe.delete($e[0]),De=$e[1],De.groupKey=Ne,Fe.set(Ne,De))}if(De||(De={groupKey:Ne,agentId:Q,agentName:z.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},Fe.set(Ne,De)),De.agentId=Q,De.agentName=z.name,!De.catalogAgent){const $e=re.find(Oe=>{const Se=xn(Oe.id,Oe.name);return at(Se==null?void 0:Se.agentId)===at(Q)});$e&&(De.catalogAgent=$e)}}const Xe=new Map(ca.map((z,Q)=>[at(`orgx:${z.id}`),Q]));for(const z of Fe.values()){z.nodes.length>0&&(z.nodes.sort(Bi),z.latest=z.nodes[0]);const Q=[],Ne=new Set;if((Pe=z.latest)!=null&&Pe.runId){const $e=Ce.get(z.latest.runId);$e&&!Ne.has($e.id)&&(Q.push($e),Ne.add($e.id))}for(const $e of z.nodes){if(!$e.runId)continue;const Oe=Ce.get($e.runId);Oe&&!Ne.has(Oe.id)&&(Q.push(Oe),Ne.add(Oe.id))}const De=at(z.agentId);if(De)for(const $e of Ye.get(De)??[])Ne.has($e.id)||(Q.push($e),Ne.add($e.id));Q.sort(($e,Oe)=>Mn(Oe.lastEventAt??Oe.lastHeartbeatAt)-Mn($e.lastEventAt??$e.lastHeartbeatAt)),z.runtime=Q[0]??null,z.runtimeActiveCount=Q.filter($e=>ap($e)).length}const He=Array.from(Fe.values()).sort((z,Q)=>{const Ne=Oi(z),De=Oi(Q);if(Ne!==De)return Ne?-1:1;if(Ne&&De){const $e=xn(z.agentId,z.agentName),Oe=xn(Q.agentId,Q.agentName),Se=Xe.get(at(($e==null?void 0:$e.agentId)??z.agentId))??999,Ge=Xe.get(at((Oe==null?void 0:Oe.agentId)??Q.agentId))??999;if(Se!==Ge)return Se-Ge}return z.latest&&Q.latest?Bi(z.latest,Q.latest):z.latest&&!Q.latest?-1:!z.latest&&Q.latest?1:z.agentName.localeCompare(Q.agentName)}),mt=ul(a),ot=mt.id==="live",lt=mt.minutes===null||ot?null:Date.now()-mt.minutes*6e4,ge=[],Ke=[];let Ae=0,B=0;for(const z of He){const Q=(z.runtimeActiveCount??0)>0,Ne=Oi(z);if(z.nodes.length===0){const Se=Br(z.catalogAgent);(Ne||ot&&(Se||Q))&&ge.push(z);continue}if(ot){const Se=z.nodes.filter(ze=>da(ln(ze))),Ge=z.nodes.filter(ze=>!da(ln(ze))),rt=Br(z.catalogAgent);if(Se.length===0){Ne||rt||Q?ge.push({...z,nodes:[],latest:null}):(Ae+=1,B+=z.nodes.length,Ke.push(z));continue}B+=Ge.length,Ge.length>0&&Ke.push({...z,nodes:Ge,latest:Ge[0]??null}),ge.push({...z,nodes:Se,latest:Se[0]??null});continue}if(lt===null){ge.push(z);continue}const De=z.nodes.filter(Se=>So(ln(Se))?!0:Mn(Se.updatedAt??Se.lastEventAt??Se.startedAt)>=lt),$e=Br(z.catalogAgent);if(De.length===0){Ne||$e||Q?ge.push({...z,nodes:[],latest:null}):(Ae+=1,B+=z.nodes.length,Ke.push(z));continue}const Oe=z.nodes.filter(Se=>So(ln(Se))?!1:Mn(Se.updatedAt??Se.lastEventAt??Se.startedAt)<lt);B+=Oe.length,Oe.length>0&&Ke.push({...z,nodes:Oe,latest:Oe[0]}),ge.push({...z,nodes:De,latest:De[0]})}return{agents:ge.slice(0,Or),hiddenGroupCount:Math.max(0,ge.length-Or),filteredOutGroupsByDate:Ae,filteredOutSessionsByDate:B,visibleSessionCount:ge.slice(0,Or).reduce((z,Q)=>z+Q.nodes.length,0),archivedGroups:Ke,sessionCountInScope:q.length}},[a,t.nodes,be,x,b]);o.useEffect(()=>{k(!1),_(0)},[a]);const Z=o.useMemo(()=>Ee.reduce((q,re)=>q+re.nodes.length,0),[Ee]),de=o.useMemo(()=>ce.filter(q=>q.nodes.length>0).map(q=>q.groupKey),[ce]),Re=o.useMemo(()=>{if(de.length===0)return{allCollapsed:!1,allExpanded:!0};let q=0;for(const re of de)h.has(re)&&(q+=1);return{allCollapsed:q===de.length,allExpanded:q===0}},[h,de]),ne=o.useMemo(()=>{const q=[];for(const re of Ee)for(const ue of re.nodes)q.push({node:ue,agentName:re.agentName});return q.sort((re,ue)=>Bi(re.node,ue.node)),q.slice(0,(m+1)*Ym)},[Ee,m]),$=q=>{v(re=>{const ue=new Set(re);return ue.has(q)?ue.delete(q):ue.add(q),ue})},X=()=>{v(()=>Re.allCollapsed?new Set:new Set(de))},P=o.useMemo(()=>H?ce.find(q=>q.groupKey===H)??null:null,[ce,H]),J=o.useMemo(()=>(P==null?void 0:P.nodes)??[],[P]),ie=o.useMemo(()=>{if(!P)return[];const q=at(P.agentName),re=at(P.agentId),ue=xn(P.agentId,P.agentName);return Y.filter(Ce=>{const Ye=at(Ce.agentName),Je=at(Ce.agentId),Fe=xn(Ce.agentId,Ce.agentName);return q!==null&&Ye===q||re!==null&&Je===re||ue!==null&&Fe!==null&&at(ue.agentId)===at(Fe.agentId)})},[Y,P]),ve=fe===0,ke=be.length>0,ee=o.useRef(null),[Te,pe]=o.useState(0),[C,O]=o.useState(0),U=o.useCallback(q=>{const re=q.currentTarget.scrollTop;pe(ue=>Math.abs(ue-re)<1?ue:re)},[]);o.useEffect(()=>{const q=ee.current;if(!q)return;const re=()=>{const ue=q.clientHeight,Ce=q.scrollTop;O(Ye=>Ye===ue?Ye:ue),pe(Ye=>Math.abs(Ye-Ce)<1?Ye:Ce)};if(re(),typeof ResizeObserver<"u"){const ue=new ResizeObserver(()=>re());return ue.observe(q),()=>ue.disconnect()}return window.addEventListener("resize",re),()=>window.removeEventListener("resize",re)},[ce.length]);const{visibleAgentGroups:se,topVirtualSpacerPx:Le,bottomVirtualSpacerPx:qe,virtualizationEnabled:Me}=o.useMemo(()=>{if(!(ce.length>Vm&&C>0))return{visibleAgentGroups:ce,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const re=ce.map(He=>{const ot=h.has(He.groupKey)?0:Math.min(He.nodes.length,Io);let lt=Km;return ot>0&&(lt+=Xm+ot*Gm,He.nodes.length>ot&&(lt+=20)),lt+Qm}),ue=new Array(re.length+1).fill(0);for(let He=0;He<re.length;He+=1)ue[He+1]=ue[He]+re[He];const Ce=ue[ue.length-1],Ye=Math.max(0,Te-Ao),Je=Te+C+Ao;let Fe=0;for(;Fe<ce.length&&ue[Fe+1]<Ye;)Fe+=1;let Xe=Fe;for(;Xe<ce.length&&ue[Xe]<Je;)Xe+=1;return Xe<=Fe&&(Xe=Math.min(ce.length,Fe+1)),{visibleAgentGroups:ce.slice(Fe,Xe),topVirtualSpacerPx:ue[Fe],bottomVirtualSpacerPx:Math.max(0,Ce-ue[Xe]),virtualizationEnabled:!0}},[ce,h,Te,C]);return n.jsxs(Us,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(qm,{open:y,onClose:()=>j(!1),onLaunched:()=>{K.refetch(),u==null||u()}}),n.jsx(Hm,{open:H!==null,onClose:()=>oe(null),agentName:(P==null?void 0:P.agentName)??"",catalogAgent:(P==null?void 0:P.catalogAgent)??null,sessions:J,activity:ie,onSelectSession:i,onRefresh:()=>K.refetch()}),n.jsx("div",{className:"border-b border-subtle px-4 py-3.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"min-w-0 truncate text-heading font-semibold text-white",children:"Agents"}),n.jsxs("span",{className:"chip flex-shrink-0 text-caption tabular-nums",children:[Ie," of ",fe]})]}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:X,disabled:de.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:Re.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:Re.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:ee,onScroll:U,className:"flex-1 space-y-2 overflow-y-auto p-3",children:[ce.length===0&&!ve&&n.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-xl border border-subtle bg-white/[0.02] px-3 py-6 text-center",children:[n.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-faint",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx("p",{className:"text-body text-secondary",children:"No sessions match the selected activity window."})]}),ce.length===0&&ve&&!d&&n.jsx(xi,{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&&Le>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Le}}),se.map(q=>{var Se;const re=q.groupKey,ue=h.has(re),Ce=q.latest,Ye=Ce?ln(Ce):null,Je=q.nodes.length>0,Fe=q.nodes.length===1,Xe=Br(q.catalogAgent),He=q.runtime??null,mt=(q.runtimeActiveCount??0)>0,ot=!Je&&mt&&He!==null,lt=Je||ot,ge=Ce?r===Ce.id:!1,Ke=q.agentName||((Se=q.catalogAgent)==null?void 0:Se.name)||q.agentId||"OrgX",Ae=xn(q.agentId,Ke),B=(Ae==null?void 0:Ae.agentName)??rp(Ke),Pe=(Ae==null?void 0:Ae.role)??xl(B),z=ds(q.agentId,B,He==null?void 0:He.displayName,Ce==null?void 0:Ce.runtimeProvider,Ce==null?void 0:Ce.runtimeClient),Q=Ae===null&&(z.id==="codex"||z.id==="openai"||z.id==="anthropic"||z.id==="openclaw"),Ne=Pe?`${Ke} — ${Pe}`:Ke,De=ue?[]:Je?q.nodes.slice(0,Io):[],$e=Math.max(0,Je?q.nodes.length-De.length:0),Oe=at(c)===at(B)||at(c)===at(Ne);return n.jsxs(he.div,{layout:!0,transition:{type:"spring",stiffness:260,damping:30,mass:.75},className:le("overflow-hidden rounded-xl border border-subtle bg-white/[0.02] transition-all",ge&&"border-white/20 bg-white/[0.05]",Oe&&"border-[#0AD4C4]/30",!Je&&!Xe&&!mt&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{Fe?i(q.nodes[0].id):ot?$(re):!Je&&Xe?oe(re):l?l(Oe?null:B):Ce&&i(Ce.id)},className:"flex flex-1 items-start gap-2.5 rounded-lg px-1 py-0.5 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsxs("div",{className:"relative flex-shrink-0",children:[Q?n.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-strong bg-white/[0.03]",children:n.jsx(Hs,{provider:z.id,size:"sm",showRing:!1})}):n.jsx(Em,{running:q.nodes.filter(Ge=>{const rt=ln(Ge);return rt==="running"||rt==="handoff"||rt==="review"}).length,blocked:q.nodes.filter(Ge=>{const rt=ln(Ge);return rt==="blocked"||rt==="failed"}).length,paused:q.nodes.filter(Ge=>{const rt=ln(Ge);return rt==="paused"||rt==="cancelled"}).length,size:36,children:n.jsx(Bt,{name:B,size:"sm",hint:`${q.agentId??""} ${B}`})}),Ae&&n.jsx("span",{className:"absolute -bottom-1 -left-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-[#08090D] bg-[#08090D]",children:n.jsx("img",{src:"/orgx/live/brand/orgx-logo.png",alt:"","aria-hidden":"true",className:"h-3 w-3 rounded-full object-contain",loading:"lazy"})}),Ce&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:As(Ye??Ce.status),borderColor:D.cardBg}}),!Ce&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Xe?As("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:Pe?`${Ke} — ${Pe}`:Ke,children:n.jsxs("span",{className:"truncate text-body font-semibold text-white",children:[B,Pe&&n.jsxs("span",{className:"ml-1.5 font-normal text-muted",children:["— ",Pe]})]})}),n.jsx("div",{className:"flex items-center gap-1.5",children:Je?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const Ge={};for(const rt of q.nodes){const ze=ln(rt);Ge[ze]=(Ge[ze]??0)+1}return Object.entries(Ge).map(([rt,ze])=>`${ze} ${rt}`).join(" · ")})(),children:(()=>{const Ge={};for(const ze of q.nodes){const Ct=ln(ze);Ge[Ct]=(Ge[Ct]??0)+1}const rt=q.nodes.length;return Object.entries(Ge).map(([ze,Ct])=>n.jsx("span",{style:{width:`${Ct/rt*100}%`,backgroundColor:As(ze)}},ze))})()}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:q.nodes.length})]}):Xe||mt?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("span",{className:"h-1.5 w-full",style:{backgroundColor:As("running")}})}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:Math.max(1,q.runtimeActiveCount??0)})]}):n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]"}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-muted",style:{fontVariantNumeric:"tabular-nums"},children:"0"})]})})]})]}),n.jsx("button",{type:"button",onClick:()=>oe(re),"aria-label":`View ${B} details`,className:"flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-white/[0.05] hover:text-primary",children:n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 16v-4"}),n.jsx("path",{d:"M12 8h.01"})]})}),n.jsx("button",{type:"button",onClick:()=>{lt&&$(re)},disabled:!lt,"aria-label":lt?ue?"Expand sessions":"Collapse sessions":"No sessions to expand",className:le("flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted transition-colors",lt?"hover:bg-white/[0.05] hover:text-primary":"cursor-default opacity-35"),children:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:le("transition-transform",lt&&!ue?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(yt,{initial:!1,children:lt&&!ue&&n.jsx(he.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 Ge=new Map,rt=[];for(const Ze of De){const jt=ln(Ze);if(jt==="blocked"||jt==="paused"||jt==="failed"){const Jt=`${jt}:${Ze.blockerReason??""}`,Gt=Ge.get(Jt)??[];Gt.push(Ze),Ge.set(Jt,Gt)}else rt.push(Ze)}const ze=[];for(const[Ze,jt]of Ge)jt.length>3?ze.push({status:Ze.split(":")[0],nodes:jt}):rt.push(...jt);const Ct=(Ze,jt)=>{const Jt=r===Ze.id,Gt=ln(Ze),dn=ds(Ze.agentName,Ze.title,Ze.lastEventSummary,Ze);return n.jsx(he.button,{onClick:()=>i(Ze.id),initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.16,delay:Math.min(jt*.015,.12)},className:le("w-full rounded-lg px-2.5 py-2 text-left transition-colors",Jt?"bg-white/[0.09]":"bg-white/[0.02] hover:bg-white/[0.05]"),children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Hs,{provider:dn.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate text-body text-bright",title:Ze.title,children:Ze.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:dn.accent},children:dn.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:Gt}),n.jsx("span",{title:ni(Ze.updatedAt??Ze.lastEventAt??Ze.startedAt??Date.now()),children:_t(Ze.updatedAt??Ze.lastEventAt??Ze.startedAt??Date.now())})]}),Ze.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(Ze.progress)}%`,background:`linear-gradient(90deg, ${D.lime}, ${D.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:As(Gt)},"aria-label":Gt,title:Gt})]})},Ze.id)};return n.jsxs(n.Fragment,{children:[rt.map((Ze,jt)=>Ct(Ze,jt)),ze.map(Ze=>n.jsx(lp,{status:Ze.status,nodes:Ze.nodes,onSelectSession:i,selectedSessionId:r},`cg-${Ze.status}-${Ze.nodes.length}`))]})})(),$e>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",$e," older sessions hidden"]})]})})})]},re)}),Me&&qe>0&&n.jsx("div",{"aria-hidden":"true",style:{height:qe}})]}),ye>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] px-3 py-2 text-caption text-secondary",children:["Showing ",Or," most recent agent groups (",ye," older groups omitted)."]}),d&&g!=="connected"&&!ke&&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:Zm.map(q=>n.jsxs("div",{className:"flex items-center gap-2.5 rounded-lg px-2 py-1.5 opacity-55",children:[n.jsx("div",{className:"flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md border border-white/[0.08] bg-white/[0.03]",children:n.jsx("span",{className:"text-micro font-semibold text-secondary",children:q.name.charAt(0)})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-caption font-medium text-secondary",children:q.name}),n.jsx("p",{className:"text-micro text-muted",children:q.role})]}),n.jsx("button",{onClick:d,className:"rounded-md border border-lime/25 bg-lime/10 px-2 py-0.5 text-micro font-semibold text-lime transition-colors hover:bg-lime/20",children:"Connect"})]},q.id))})]}),W>0&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsxs("button",{onClick:()=>{k(q=>!q),w&&_(0)},className:"flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:le("transition-transform",w?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[Z," archived session",Z===1?"":"s",we>0?` across ${we} agent${we===1?"":"s"}`:""]})]}),n.jsx(yt,{initial:!1,children:w&&n.jsx(he.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsxs("div",{className:"space-y-1.5 border-t border-subtle p-2",children:[ne.map(({node:q,agentName:re})=>{const ue=ln(q),Ce=q.runtimeProvider?{id:op(q.runtimeProvider)}:ds(q.agentName,q.title,q.lastEventSummary,q);return n.jsxs("button",{onClick:()=>i(q.id),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left opacity-60 transition-colors hover:bg-white/[0.05] hover:opacity-80",children:[n.jsx(Hs,{provider:Ce.id,size:"xs"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"truncate text-caption font-medium text-primary",children:re}),n.jsx("span",{className:"text-micro text-muted",title:ni(q.updatedAt??q.lastEventAt??q.startedAt??Date.now()),children:_t(q.updatedAt??q.lastEventAt??q.startedAt??Date.now())})]}),n.jsx("p",{className:"truncate text-micro text-secondary",children:q.title}),n.jsx("span",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:ue})]})]},q.id)}),ne.length<Z&&n.jsxs("button",{onClick:()=>_(q=>q+1),className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-1.5 text-micro text-secondary transition-colors hover:bg-white/[0.05]",children:["Load more (",Z-ne.length," remaining)"]})]})})})]})]})]})}),dp=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),up=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),mp=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),pp=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),fp=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function Bs(e){return e?zt(e):""}function qi(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function hp(e){return e.some(t=>dp.has(t))}function gp(e){return e.some(t=>up.has(t))}function xp(e){return e.some(t=>mp.has(t))}function yp(e){return e.some(t=>pp.has(t))}function bp(e){return e.some(t=>fp.has(t))}function Gn(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 wp(e){const t=Bs(e.sessionStatus),s=Bs(e.sessionPhase),r=Bs(e.sessionState),i=Bs(e.sliceStatus),a=Bs(e.activityStatus),l=Bs(e.stopReason),c=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,r,i,a,l].filter(_=>_.length>0),u=qi(e.blockingDecisionCount),g=qi(e.nonBlockingDecisionCount),x=qi(e.blockerCount),b=c==="run_failed",h=c==="run_completed"||c==="milestone_completed"||c==="decision_resolved",v=b||hp(d),y=gp(d)||c==="decision_requested"||u>0||e.decisionRequired===!0,j=xp(d)||x>0,w=h||yp(d),k=bp(d)||c==="run_started";if(v)return Gn("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(w&&!y&&!v&&x===0&&!e.blockerReason)return g>0?Gn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Gn("completed","Execution completed successfully.",{tone:"positive"});if(y||j)return u>0||e.decisionRequired===!0||c==="decision_requested"?Gn("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):Gn("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:j?"critical":"warning"});if(w)return g>0?Gn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Gn("completed","Execution completed successfully.",{tone:"positive"});if(k){const _=g>0?`Running with ${g} optional decision${g===1?"":"s"} available.`:"Running.";return Gn("in_progress",_,{tone:"neutral"})}return Gn("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const zi=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function vp(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ss(e,t){const s=[];let r=0,i=0;zi.lastIndex=0;for(let a=zi.exec(e);a;a=zi.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&&vp(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 kp(e,t){const s=e.split(`
|
|
204
|
+
`),r=[];return s.forEach((i,a)=>{r.push(...Ss(i,`${t}-line-${a}`)),a<s.length-1&&r.push(n.jsx("br",{},`${t}-br-${a}`))}),r}function ei(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function jp(e){const t=ei(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function Np(e){const t=e.trim(),s=t.startsWith(":"),r=t.endsWith(":");return s&&r?"center":r?"right":"left"}function Ip(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("|")&&jp(c)){const b=ei(i),v=ei(c).map(j=>Np(j));r+=2;const y=[];for(;r<t.length;){const j=t[r]??"";if(!j.trim()||!j.includes("|"))break;y.push(ei(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:Ss(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,m)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:v[m]??"left"},children:Ss(j[m]??"",`tbl-r-${r}-${w}-${m}`)},`tbl-r-${w}-c-${m}`))},`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:le("tracking-[-0.01em] text-white",v),children:Ss(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:Ss(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:Ss(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:kp(x.join(`
|
|
208
|
+
`),`p-${r}`)},`p-${r}`))}return s}function li({text:e,mode:t="inline",className:s}){const r=e.replace(/\r\n/g,`
|
|
209
|
+
`);return r.trim()?t==="inline"?n.jsx("span",{className:s,children:Ss(r,"inline")}):n.jsx("div",{className:le("space-y-2",s),children:Ip(r)}):null}function Tl(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function Ap(e){if(!e)return;const t=Tl(e.metadata);return t?{...e,...t}:e}const El={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 qn(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 ua(e){return e?e.toLowerCase():""}function Sp(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,qn(t,["source","event","eventType","artifact_type","action","kind"]),qn(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function _p(e,t){const s=ua(qn(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}:El.artifact_created}function Cp(e){const t=Ap(Tl(e.metadata)),s=Sp(e,t),r=ua(qn(t,["source"])),i=ua(qn(t,["action"])),a=qn(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"&&qn(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:D.teal};if(a==="auto_continue_stopped"){const c=qn(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=qn(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=qn(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 El[e.type]??{icon:"message",label:"Activity",color:D.textMuted}}function Mp({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(yl,{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 ci(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function ma(e){if(!e)return;const t=ci(e.metadata);return t?{...e,...t}:e}function Tp(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function Ep(e){let t=0;for(const s of e){const r=ma(ci(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 Rp=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(()=>Ep(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 m of d){const _=ma(ci(m.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:dt(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(Bt,{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:dt(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?`${dt(x.provider)} · `:"",x.model?wr(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: ",dt(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 K;const y=Cp(h),j=y.color,w=(K=ma(ci(h.metadata)))==null?void 0:K.model,k=typeof w=="string"?wr(w):null,m=dt(h.title??""),_=h.type==="run_failed",H=h.type==="artifact_created",oe=h.type==="decision_requested"||h.type==="decision_resolved";return n.jsxs(he.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(Mp,{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":oe?"text-amber-300":H?"text-cyan-300":"text-bright"}`,children:m}),h.summary&&h.summary!==m&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:dt(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:ni(h.timestamp),children:Tp(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:ni(d[d.length-1].timestamp),children:_t(d[d.length-1].timestamp)})]})]})]})});function Lp({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(he.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 Dp={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}};function $p({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(Bt,{name:a,hint:a,size:"xs"})}),n.jsxs("div",{className:"relative min-w-0 flex-1 pl-3",children:[n.jsx("span",{className:le("absolute inset-y-0 left-0 w-[2px] rounded-full",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(li,{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(he.button,{type:"button",variants:Dp,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:le(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 Fp({open:e,onClose:t,children:s}){return n.jsx(gi,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function Pp(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 Op={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 Bp({item:e,className:t}){const s=o.useMemo(()=>fc(e),[e]),r=Pp(e),i=Op[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(Wi,{label:"Task",value:s.taskDescription,styles:i}),s.outcomeDescription&&n.jsx(Wi,{label:"Outcome",value:s.outcomeDescription,styles:i}),s.nextStep&&n.jsx(Wi,{label:"Next step",value:s.nextStep,styles:i})]})}function Wi({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 _o=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),qp=[{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"}],dr=[{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"}],Co={type:"spring",stiffness:400,damping:25},Mo={scale:.985};function Qt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function zp(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 ur(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?qt(Rt(e??"Request failed.")):t==="send"?"Message send failed. Draft is preserved.":t==="launch"?"Launch request failed. Thread remains saved.":"Request failed."}function Wp(e){return[e.title,e.summary??"",e.lastSnippet??"",e.assigneeName??"",e.initiativeTitle??"",...e.watcherNames??[]].join(" ").toLowerCase()}function Up(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 di(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function Vs(e){return e==="running"?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":e==="completed"?"border-teal/30 bg-teal/[0.12] text-teal-100":e==="blocked"||e==="failed"?"border-rose-400/30 bg-rose-400/[0.12] text-rose-100":e==="queued"?"border-white/[0.18] bg-white/[0.08] text-primary":"border-white/[0.12] bg-white/[0.04] text-secondary"}function Rl(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function Hp(e){return e==="agent"?"assistant":e}function Vp(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function Kp(e,t){return t.map(s=>({id:s.id,role:Hp(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function Ll(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function Ks(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ti(e){const t=Ks(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const r=Ks(t.latestMessage),i=Ks(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 Gp(e){const t=Ks(e);if(!t)return null;const s=ti({...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=>Ks(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=>Ks(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)=>Qt(a.createdAt)-Qt(l.createdAt)),launches:i.sort((a,l)=>Qt(l.requestedAt)-Qt(a.requestedAt))}}function Xp(e,t,s){const r=Qt(e.lastActivityAt);if(!r)return!1;if(t==="custom"){const a=Qt(s.startIso),l=Qt(s.endIso);return!(a&&r<a||l&&r>l)}const i=jr(t,Date.now());return i?r>=i:!0}async function mr(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 Ui(e,t){const s=new Map;for(const r of e)s.set(r.id,r);return s.set(t.id,t),Array.from(s.values()).sort((r,i)=>Qt(i.lastActivityAt??i.updatedAt)-Qt(r.lastActivityAt??r.updatedAt))}function Qp(e,t){const s=new Map;for(const r of e)s.set(r.id,r);for(const r of t)s.set(r.id,r);return Array.from(s.values()).sort((r,i)=>Qt(i.lastActivityAt??i.updatedAt)-Qt(r.lastActivityAt??r.updatedAt))}const Dl=o.createContext(null),$l=o.createContext(null);function Aa(){const e=o.useContext(Dl);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function Sa(){const e=o.useContext($l);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function Jp({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),[m,_]=o.useState(null),[H,oe]=o.useState("resting"),[K,be]=o.useState(""),[V,Y]=o.useState(!1),[ce,ye]=o.useState(!1),[we,W]=o.useState(null),[Ie,Ee]=o.useState(null),[fe,Z]=o.useState([]),[de,Re]=o.useState(""),[ne,$]=o.useState([]),[X,P]=o.useState(""),[J,ie]=o.useState(null),[ve,ke]=o.useState(""),[ee,Te]=o.useState(!1),[pe,C]=o.useState(""),[O,U]=o.useState([]),[se,Le]=o.useState(!1),[qe,Me]=o.useState("auto"),[T,q]=o.useState(!1),[re,ue]=o.useState(!1),[Ce,Ye]=o.useState(!1),Je=o.useRef(null),Fe=o.useRef(null),Xe=o.useRef(null),He=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&b(R=>Qp(R,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{h&&b(R=>R.sort((me,ae)=>Qt(ae.lastActivityAt)-Qt(me.lastActivityAt)))},[h]);const{data:mt}=Na({enabled:!0,refetchInterval:8e3}),ot=o.useMemo(()=>{var me,ae;const R=new Map;for(const je of qp)R.set(je.id,{id:je.id,name:je.name,handle:je.handle,domain:je.domain,domainLabel:je.domainLabel,role:je.role,status:"idle",currentTask:null,isSystem:!1});if(mt!=null&&mt.agents)for(const je of mt.agents){const ft=R.get(je.id);ft?(ft.status=je.status==="running"?"running":(me=je.blockers)!=null&&me.length?"blocked":"idle",ft.currentTask=je.currentTask??null):R.set(je.id,{id:je.id,name:je.name,handle:je.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:je.status==="running"?"running":(ae=je.blockers)!=null&&ae.length?"blocked":"idle",currentTask:je.currentTask??null,isSystem:_o.has(je.id)})}for(const je of t){const ft=(je.agentId??"").trim(),Qe=(je.agentName??"").trim();!ft||!Qe||R.has(ft)||R.set(ft,{id:ft,name:Qe,handle:ft,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:_o.has(ft)})}return Array.from(R.values()).filter(je=>!je.isSystem).sort((je,ft)=>je.name.localeCompare(ft.name))},[mt,t]),lt=o.useMemo(()=>s.map(R=>({id:R.id,name:R.name})).sort((R,me)=>R.name.localeCompare(me.name)),[s]),ge=o.useMemo(()=>ot.find(R=>R.id===de)??null,[ot,de]),Ke=o.useMemo(()=>{const R=new Set(ne);return ot.filter(me=>R.has(me.id))},[ot,ne]),Ae=o.useMemo(()=>lt.find(R=>R.id===X)??null,[lt,X]);o.useEffect(()=>{de&&$(R=>R.filter(me=>me!==de))},[de]);const B=o.useMemo(()=>ot.slice(0,8),[ot]),Pe=o.useMemo(()=>{const R=ve.trim().toLowerCase();return R?ot.filter(me=>me.name.toLowerCase().includes(R)||me.handle.toLowerCase().includes(R)||me.domain.toLowerCase().includes(R)||me.role.toLowerCase().includes(R)):ot},[ot,ve]),z=o.useMemo(()=>{const R=pe.trim().toLowerCase();return R?lt.filter(me=>me.name.toLowerCase().includes(R)):lt},[lt,pe]),Q=o.useMemo(()=>{const R=i.trim().toLowerCase(),me=x.filter(ae=>!Up(ae,a)||!Xp(ae,c,d)?!1:R.length===0?!0:Wp(ae).includes(R));return me.sort((ae,je)=>{const ft=Qt(je.lastActivityAt)-Qt(ae.lastActivityAt);return l==="newest"?ft:-ft}),me},[d,i,l,a,x,c]),Ne=o.useMemo(()=>{if(!h||Q.some(me=>me.id===h))return Q;const R=x.find(me=>me.id===h);return R?[R,...Q]:Q},[h,Q,x]),De=o.useMemo(()=>x.find(R=>R.id===h)??null,[h,x]),$e=o.useMemo(()=>fe.filter(R=>R.status!=="ready").length,[fe]),Se=K.trim().length>0&&!V,Ge=o.useMemo(()=>$e>0?`${$e} attachment(s) still processing.`:"Press Enter to send.",[$e]),rt=o.useMemo(()=>V?"Sending…":ce?"Launching…":"Send",[ce,V]),ze=o.useMemo(()=>new ic({api:"/orgx/api/chat/usechat"}),[]),{messages:Ct,setMessages:Ze,sendMessage:jt,status:Jt,error:Gt,clearError:dn}=ec({id:`orgx-chat-guidance-${r??"global"}`,transport:ze,onError:R=>{W(ur((R==null?void 0:R.message)??null,"send"))}});o.useEffect(()=>{if(!y){Ze([]);return}Ze(Kp(y.id,y.messages))},[y,Ze]);const En=o.useMemo(()=>{const R=[...Ct].reverse().find(ae=>ae.role==="assistant");if(!R)return null;const me=Vp(R);return me.length>0?me:null},[Ct]),hs=o.useRef(null);o.useEffect(()=>{if(Jt!=="ready"&&Jt!=="error"||!En)return;const R=[...Ct].reverse().find(me=>me.role==="assistant");!R||R.id===hs.current||(hs.current=R.id,U(me=>[...me,{id:`guidance_${R.id}`,role:"agent",body:En,timestamp:new Date().toISOString()}]))},[Jt,En,Ct]);const pt=o.useCallback(()=>{be(""),Z([]),ue(!1),Ye(!1),W(null),Ee(null)},[]),Ht=o.useCallback(R=>{U(me=>[...me,{...R,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),wn=o.useCallback(()=>U([]),[]),Lt=o.useCallback(()=>Le(R=>!R),[]),Nt=o.useMemo(()=>dr.find(R=>R.id===qe)??dr[0],[qe]),Wt=o.useCallback(()=>{Me(R=>{const me=dr.findIndex(ae=>ae.id===R);return dr[(me+1)%dr.length].id})},[]),Vt=o.useCallback(async()=>{typeof g=="function"&&await g()},[g]),Ot=o.useCallback(async R=>{var je;k(!0),_(null);const me=await mr(`/orgx/api/chat/threads/${encodeURIComponent(R)}`);if(!me.ok||!((je=me.data)!=null&&je.thread))return k(!1),_(ur(me.error,"load")),null;const ae=Gp(me.data.thread);return ae?(j(ae),k(!1),ae):(k(!1),_("Thread detail payload was invalid."),null)},[]),un=o.useCallback(async(R,me)=>{me&&(Xe.current=me),v(R),await Ot(R),requestAnimationFrame(()=>{var ae;return(ae=Fe.current)==null?void 0:ae.focus()})},[Ot]),Zn=o.useCallback(()=>{var R;v(null),j(null),_(null),k(!1),(R=Xe.current)==null||R.focus()},[]),mn=o.useCallback(R=>{window.setTimeout(()=>{Z(me=>me.map(ae=>ae.id===R?{...ae,status:"indexing",updatedAt:new Date().toISOString()}:ae))},80),window.setTimeout(()=>{Z(me=>me.map(ae=>{var Qe;if(ae.id!==R)return ae;const je=((Qe=ae.mimeType)==null?void 0:Qe.toLowerCase())==="application/x-msdownload"||ae.name.toLowerCase().endsWith(".exe"),ft=(ae.sizeBytes??0)>25*1024*1024;return je?{...ae,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:ft?{...ae,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...ae,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Rn=o.useCallback(R=>{if(!R||R.length===0)return;const me=new Date().toISOString(),ae=Array.from(R).map(je=>({id:`draft_att_${crypto.randomUUID()}`,name:je.name,mimeType:je.type||null,sizeBytes:Number.isFinite(je.size)?je.size:null,status:"preparing",error:null,masked:!1,createdAt:me,updatedAt:me}));Z(je=>je.concat(ae)),ae.forEach(je=>mn(je.id)),os("chat_attachment_state_changed",{count:ae.length,state:"preparing"})},[mn]),gs=o.useCallback(R=>{Z(me=>me.map(ae=>ae.id===R?{...ae,status:"preparing",error:null,updatedAt:new Date().toISOString()}:ae)),mn(R),os("chat_attachment_state_changed",{state:"retry"})},[mn]),vn=o.useCallback(R=>{Re(me=>me===R?"":R),$(me=>me.filter(ae=>ae!==R)),ie(null),ke("")},[]),en=o.useCallback(R=>{$(me=>me.includes(R)?me.filter(ae=>ae!==R):me.concat(R))},[]),Kt=o.useCallback(()=>{Te(!1),C(""),ie(R=>R==="assignee"?null:"assignee"),ke("")},[]),es=o.useCallback(()=>{Te(!1),C(""),ie(R=>R==="watcher"?null:"watcher"),ke("")},[]),kn=o.useCallback(()=>{ie(null),ke(""),Te(R=>!R),C("")},[]),ts=o.useCallback(async(R,me)=>{var Qe;q(!0);const ae=lt.find(et=>et.id===me)??null,je=await mr("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:R,project_id:r??void 0,initiativeId:(ae==null?void 0:ae.id)??null,initiativeTitle:(ae==null?void 0:ae.name)??null,relinked:!0})});if(q(!1),!je.ok||!((Qe=je.data)!=null&&Qe.thread)){_(je.error??"Scope link failed.");return}const ft=ti(je.data.thread);ft&&b(et=>Ui(et,ft)),await Ot(R),await Vt(),os("chat_thread_linked_initiative",{threadId:R,initiativeId:(ae==null?void 0:ae.id)??null})},[lt,Ot,Vt,r]),ns=o.useCallback(async R=>{dn(),await jt({text:R.prompt},{body:{threadId:R.thread.id,project_id:r??void 0,initiativeId:R.thread.initiativeId??(Ae==null?void 0:Ae.id)??void 0,initiativeTitle:R.thread.initiativeTitle??(Ae==null?void 0:Ae.name)??void 0,assigneeId:(ge==null?void 0:ge.id)??R.thread.assigneeId??void 0,assigneeName:(ge==null?void 0:ge.name)??R.thread.assigneeName??void 0,watcherIds:Ke.map(me=>me.id),watcherNames:Ke.map(me=>me.name)}}),await Vt(),await Ot(R.thread.id)},[dn,Ot,Vt,ge==null?void 0:ge.id,ge==null?void 0:ge.name,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,Ke,jt,r]),tn=o.useCallback(async()=>{var ft,Qe;const R=K.trim();if(!R)return W("Write a message before sending."),{thread:null,messageId:null};W(null),Ee(null),Y(!0);const me=await mr("/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:(ge==null?void 0:ge.id)??(y==null?void 0:y.assigneeId)??void 0,assigneeName:(ge==null?void 0:ge.name)??(y==null?void 0:y.assigneeName)??void 0,watcherIds:Ke.map(et=>et.id),watcherNames:Ke.map(et=>et.name),body:R,attachments:fe.map(et=>({id:et.id,name:et.name,mimeType:et.mimeType,sizeBytes:et.sizeBytes,status:et.status,error:et.error,masked:et.masked}))})});if(Y(!1),!me.ok||!((ft=me.data)!=null&&ft.thread))return W(ur(me.error,"send")),os("chat_message_send_failed",{reason:me.error??"unknown"}),{thread:null,messageId:null};const ae=ti(me.data.thread);if(!ae)return W("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};b(et=>Ui(et,ae)),Ht({role:"user",body:R}),qe!=="auto"&&ge&&Ht({role:"system",body:`Routing to ${ge.name} via ${Nt.label}`}),os("chat_message_sent",{threadId:ae.id,watcherCount:ae.watcherIds.length}),await Vt();const je=me.data.message&&typeof me.data.message.id=="string"?me.data.message.id:((Qe=ae.latestMessage)==null?void 0:Qe.id)??null;return v(ae.id),await Ot(ae.id),ns({thread:ae,prompt:R}).catch(et=>{Ht({role:"error",body:ur(et instanceof Error?et.message:String(et??""),"send")})}),pt(),oe("reviewing"),{thread:ae,messageId:je}},[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,K,fe,Ot,Vt,pt,ns,ge==null?void 0:ge.id,ge==null?void 0:ge.name,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,qe,Nt,Ke,r]),Ln=o.useCallback(async(R,me)=>{var bt,fn,Wn,ys,Nn,bs,Un;if(!me){Ht({role:"error",body:"Send a message first to launch."});return}if(!ge){Ht({role:"error",body:"Pick an agent with @ before launching."});return}if($e>0&&!Ce){ue(!0),Ht({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}ye(!0),W(null),Ee(null);const ae=await mr("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:ge.id,message:K.trim().length>0?K.trim():R.lastSnippet??R.title,initiativeId:R.initiativeId??(Ae==null?void 0:Ae.id)??void 0,initiativeTitle:R.initiativeTitle??(Ae==null?void 0:Ae.name)??void 0,workstreamId:R.workstreamId??void 0,taskId:R.taskId??void 0,provider:qe!=="auto"?qe:void 0})}),je=((bt=ae.data)==null?void 0:bt.sessionId)??((fn=ae.data)==null?void 0:fn.runId)??null,ft=ae.ok&&je?"running":ae.ok?"queued":"blocked",Qe=ae.ok?null:ae.error??"Launch request failed before queueing.",et=await mr("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:R.id,messageId:me,assigneeId:ge.id,assigneeName:ge.name,watcherIds:Ke.map(St=>St.id),watcherNames:Ke.map(St=>St.name),executionMode:"local_queue",provider:((Wn=ae.data)==null?void 0:Wn.provider)??(qe!=="auto"?qe:"openclaw"),runId:je??void 0,status:ft,blockedReason:Qe??void 0,warnings:$e>0?[`${$e} attachment(s) were not ready at launch.`]:[]})});if(ye(!1),Ye(!1),ue(!1),!et.ok||!((ys=et.data)!=null&&ys.thread)){W(et.error?ur(et.error,"launch"):Qe??"Launch state could not be persisted. Message remained saved."),os("chat_launch_failed",{threadId:R.id,reason:et.error??Qe??"unknown"});return}const xs=ti(et.data.thread);if(xs&&b(St=>Ui(St,xs)),await Ot(R.id),await Vt(),!ae.ok){W(`Launch blocked: ${Qe??"Set assignee and retry."}`),os("chat_launch_blocked",{threadId:R.id,reason:Qe??"unknown"});return}const ht=((Nn=ae.data)==null?void 0:Nn.provider)==="anthropic"?"Claude Code":((bs=ae.data)==null?void 0:bs.provider)==="openai"?"Codex":Nt.shortLabel,rs=(Un=ae.data)!=null&&Un.model?` (${ae.data.model})`:"";Ee(je?`Launch started via ${ht}${rs}. Thread timeline now tracks execution state.`:`Launch queued locally via ${ht}. Run starts when a worker is available.`),os(je?"chat_launch_started":"chat_launch_queued",{threadId:R.id,runId:je,assigneeId:ge.id})},[K,Ce,Ot,Vt,ge,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,qe,Nt,Ke,$e]),Dt=o.useCallback(async()=>{var me;const R=await tn();(me=R.thread)!=null&&me.id&&await un(R.thread.id)},[un,tn]),ss=o.useCallback(async()=>{const R=await tn();R.thread&&(await Ln(R.thread,R.messageId),await un(R.thread.id))},[Ln,un,tn]),nn=o.useCallback(async()=>{if(Se){if(ge){await ss();return}await Dt()}},[Se,ss,Dt,ge]),pn=o.useMemo(()=>({threads:x,activeThreadId:h,activeThread:y,activeThreadSummary:De,displayedThreads:Ne,composerMode:H,draft:K,draftAttachments:fe,sending:V,launching:ce,composerError:we,composerNotice:Ie,selectedAssigneeId:de,selectedAssignee:ge,selectedWatcherIds:ne,selectedWatchers:Ke,selectedInitiativeId:X,selectedInitiative:Ae,agentOptions:ot,quickAssigneeOptions:B,initiativeOptions:lt,agentPickerMode:J,agentPickerQuery:ve,filteredAgentOptions:Pe,scopePickerOpen:ee,scopePickerQuery:pe,filteredInitiativeOptions:z,panelLoading:w,panelError:m,scopeSaving:T,launchWarningOpen:re,launchWarningAccepted:Ce,unresolvedAttachmentCount:$e,canSend:Se,composerGuidance:Ge,primaryActionLabel:rt,guidanceStatus:Jt,guidancePreview:En,guidanceError:Gt??null,inlineMessages:O,threadSidebarOpen:se,workspaceId:r,selectedProvider:qe,selectedProviderDef:Nt}),[x,h,y,De,Ne,H,K,fe,V,ce,we,Ie,de,ge,ne,Ke,X,Ae,ot,B,lt,J,ve,Pe,ee,pe,z,w,m,T,re,Ce,$e,Se,Ge,rt,Jt,En,Gt,O,se,r,qe,Nt]),jn=o.useMemo(()=>({setDraft:be,setComposerMode:oe,setDraftAttachments:Z,selectAssignee:vn,toggleWatcher:en,setSelectedInitiativeId:P,toggleAssigneePicker:Kt,toggleWatcherPicker:es,toggleScopePicker:kn,setAgentPickerQuery:ke,setScopePickerQuery:C,setAgentPickerMode:ie,setScopePickerOpen:Te,handlePrimaryAction:nn,handleFilesAdded:Rn,handleRetryAttachment:gs,openThreadPanel:un,closeThreadPanel:Zn,loadThreadDetail:Ot,applyScopeLink:ts,resetComposer:pt,setComposerError:W,setComposerNotice:Ee,setLaunchWarningAccepted:Ye,pushInlineMessage:Ht,clearInlineMessages:wn,toggleThreadSidebar:Lt,setSelectedProvider:Me,cycleProvider:Wt,fileInputRef:Je,panelHeadingRef:Fe,composerShellRef:He}),[vn,en,Kt,es,kn,nn,Rn,gs,un,Zn,Ot,ts,pt,Ht,wn,Lt,Wt]);return n.jsx(Dl.Provider,{value:pn,children:n.jsx($l.Provider,{value:jn,children:e})})}const Yp={type:"spring",stiffness:500,damping:35,mass:.5};function Zp({messages:e,isStreaming:t,collapsed:s,onClick:r}){var c;const i=Yn(),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(he.div,{initial:i?!1:{opacity:0,height:0},animate:i?{}:{opacity:1,height:"auto"},exit:i?{}:{opacity:0,height:0},transition:i?void 0:{duration:.25,ease:[.22,1,.36,1]},className:"overflow-hidden",children:n.jsx("div",{ref:a,onClick:r,role:r?"button":void 0,tabIndex:r?0:void 0,className:le("max-h-[200px] space-y-1.5 overflow-y-auto px-1 pb-2 pt-1","scroll-smooth",r&&"cursor-pointer"),children:n.jsx(yt,{initial:!1,children:l.map(d=>n.jsx(he.div,{initial:i?!1:{opacity:0,y:8,scale:.97},animate:i?{}:{opacity:1,y:0,scale:1},transition:i?void 0:Yp,className:le("flex",d.role==="user"?"justify-end":"justify-start",d.role==="system"&&"justify-center"),children:d.role==="system"?n.jsx("p",{className:"text-micro italic text-muted",children:d.body}):n.jsxs("div",{className:le("max-w-[85%] rounded-2xl px-3 py-2",d.role==="user"&&"bg-lime/[0.1]",d.role==="agent"&&"bg-white/[0.05]",d.role==="error"&&"bg-rose-400/[0.1]"),children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:le("text-micro font-medium",d.role==="user"&&"text-[#E1FFB2]/80",d.role==="agent"&&"text-secondary",d.role==="error"&&"text-rose-200"),children:d.role==="user"?"You":d.role==="error"?"Error":"Agent"}),n.jsx("time",{className:"text-[10px] text-muted/60",dateTime:d.timestamp,children:_t(d.timestamp)})]}),n.jsxs("p",{className:le("mt-0.5 whitespace-pre-wrap text-caption leading-relaxed",d.role==="user"&&"text-primary",d.role==="agent"&&"text-primary",d.role==="error"&&"text-rose-100"),children:[d.body,t&&d===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 To({open:e,onClose:t}){const s=Yn(),{displayedThreads:r,activeThreadId:i,activeThread:a,activeThreadSummary:l,panelLoading:c,panelError:d,scopeSaving:u,initiativeOptions:g}=Aa(),{openThreadPanel:x,closeThreadPanel:b,loadThreadDetail:h,applyScopeLink:v,panelHeadingRef:y}=Sa(),j=(a==null?void 0:a.id)??(l==null?void 0:l.id)??null,w=o.useCallback((m,_)=>{x(m,_)},[x]),k=o.useCallback(()=>{b(),t()},[b,t]);return n.jsx(yt,{children:e&&n.jsxs(n.Fragment,{children:[n.jsx(he.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(he.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:le("grid min-h-0 flex-1 overflow-hidden",i&&"lg:grid-cols-[minmax(260px,0.8fr)_minmax(0,1.2fr)]"),children:[n.jsx("div",{className:"min-h-0 overflow-y-auto px-3 pb-3",children:r.length===0?n.jsx(xi,{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(m=>n.jsxs("button",{type:"button",onClick:_=>w(m.id,_.currentTarget),className:le("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",i===m.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:m.lastSnippet?`"${m.lastSnippet.length>40?m.lastSnippet.slice(0,40)+"...":m.lastSnippet}"`:m.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:m.lastActivityAt,children:_t(m.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[m.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",m.assigneeName]}),n.jsx("span",{children:m.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Vs(m.status)),children:di(m.status)})]})]},m.id))})}),n.jsx(yt,{initial:!1,children:i&&n.jsxs(he.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:le("rounded-full border px-2 py-0.5 text-micro font-semibold",Vs((l==null?void 0:l.status)??"message_only")),children:di((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(m=>n.jsx("article",{className:le("flex",m.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:le("max-w-[90%] rounded-xl border px-2.5 py-1.5",m.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":m.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:m.senderName??Rl(m.role)}),n.jsx("time",{dateTime:m.createdAt,children:_t(m.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:m.body})]})},m.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(m=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Vs(Ll(m.status))),children:m.status}),n.jsx("span",{children:m.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:m.requestedAt,children:_t(m.requestedAt)})]},m.id))]})]})})]})]})]})})}function Eo(){const e=Yn(),{displayedThreads:t,activeThreadId:s,activeThread:r,activeThreadSummary:i,panelLoading:a,panelError:l,scopeSaving:c,initiativeOptions:d,threadSidebarOpen:u}=Aa(),{openThreadPanel:g,closeThreadPanel:x,loadThreadDetail:b,applyScopeLink:h,setComposerMode:v,toggleThreadSidebar:y,panelHeadingRef:j}=Sa(),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(he.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(he.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(he.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:Mo,transition:Co,onClick:()=>{k(),v("focused"),requestAnimationFrame(()=>{const m=document.getElementById("chat-dock-input");m instanceof HTMLTextAreaElement&&m.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((m,_)=>n.jsxs(he.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:Co,delay:e?0:Math.min(_*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:Mo,onClick:H=>void g(m.id,H.currentTarget),className:le("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===m.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:m.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:m.lastActivityAt,children:_t(m.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:m.lastSnippet??m.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[m.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Bt,{name:m.assigneeName,hint:m.assigneeName,size:"xs"}),n.jsx("span",{children:m.assigneeName})]}),n.jsx("span",{children:m.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Vs(m.status)),children:di(m.status)})]})]},m.id))})}),n.jsx(yt,{initial:!1,children:s&&n.jsxs(he.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:le("rounded-full border px-2 py-0.5 text-micro font-semibold",Vs((i==null?void 0:i.status)??"message_only")),children:di((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(m=>n.jsx("article",{className:le("flex",m.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:le("max-w-[90%] rounded-xl border px-2.5 py-1.5",m.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":m.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:m.senderName??Rl(m.role)}),n.jsx("time",{dateTime:m.createdAt,children:_t(m.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:m.body})]})},m.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(m=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Vs(Ll(m.status))),children:m.status}),n.jsx("span",{children:m.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:m.requestedAt,children:_t(m.requestedAt)})]},m.id))]})]})})]},"sidebar-panel")]})}):null}const ef={type:"spring",stiffness:500,damping:30,mass:.5};function tf({open:e,agents:t,query:s,activeIndex:r,onSelect:i}){const a=Yn(),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(he.div,{initial:a?!1:{opacity:0,y:8,scale:.96},animate:a?{}:{opacity:1,y:0,scale:1},exit:a?{}:{opacity:0,y:8,scale:.96},transition:a?void 0:ef,className:le("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Agent suggestions",children:n.jsx("div",{ref: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:le("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",x?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Bt,{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 nf={type:"spring",stiffness:500,damping:30,mass:.5};function sf({open:e,initiatives:t,query:s,activeIndex:r,onSelect:i}){const a=Yn(),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(he.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:nf,className:le("absolute bottom-[calc(100%+6px)] left-0 z-30 w-[280px]","rounded-2xl border border-white/[0.1] bg-[#0D1117]/98 p-1","shadow-[0_16px_48px_rgba(0,0,0,0.5),0_0_0_1px_rgba(255,255,255,0.04)] backdrop-blur-2xl"),role:"listbox","aria-label":"Initiative scope suggestions",children:n.jsxs("div",{ref: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:le("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",r===0?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:"Unscoped"}),d.map((u,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:le("flex w-full items-center gap-2 rounded-xl px-2.5 py-2 text-left text-caption","transition-colors duration-[60ms]",x?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:n.jsx("span",{className:"truncate",children:u.name})},u.id)})]})})})}function rf({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=Yn();return n.jsx(yt,{children:e&&n.jsxs(he.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:le("rounded-full px-2 py-0.5 text-micro",t==="assignee"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Assignee"}),n.jsx("button",{type:"button",onClick:()=>x("watcher"),className:le("rounded-full px-2 py-0.5 text-micro",t==="watcher"?"bg-white/[0.1] text-primary":"text-secondary hover:text-primary"),children:"Watchers"})]}),n.jsx("button",{type:"button",onClick: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:le("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",y?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":y,"aria-label":`Select ${v.name} as assignee`,children:n.jsx(Bt,{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:le("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",y?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":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(Bt,{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 Ro=24,Lo=200;function Do(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 af(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 $o({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 pa="orgx-chat-dock-collapsed";function of(){try{return localStorage.getItem(pa)==="1"}catch{return!1}}function lf(){const e=Aa(),t=Sa(),s=Yn(),r=o.useRef(null),i=o.useRef(null),[a,l]=o.useState(of),c=o.useCallback(()=>{l(B=>{const Pe=!B;try{localStorage.setItem(pa,Pe?"1":"0")}catch{}return Pe})},[]),[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),[m,_]=o.useState(-1),[H,oe]=o.useState(!1),[K,be]=o.useState(""),[V,Y]=o.useState(0),[ce,ye]=o.useState(-1),{composerMode:we,draft:W,draftAttachments:Ie,sending:Ee,launching:fe,selectedAssigneeId:Z,selectedAssignee:de,selectedWatcherIds:Re,selectedInitiative:ne,agentOptions:$,quickAssigneeOptions:X,agentPickerMode:P,agentPickerQuery:J,filteredAgentOptions:ie,initiativeOptions:ve,canSend:ke,activeThreadId:ee,guidanceStatus:Te,inlineMessages:pe,displayedThreads:C,launchWarningOpen:O,launchWarningAccepted:U,selectedProvider:se,selectedProviderDef:Le}=e,qe=W.trim(),Me=pe.length>0;qe.length>0;const T=o.useCallback(()=>{const B=r.current;if(!B)return;B.style.height="0";const Pe=Math.min(Math.max(B.scrollHeight,Ro),Lo);B.style.height=`${Pe}px`},[]);o.useLayoutEffect(()=>{T()},[W,T]);const q=o.useMemo(()=>{if(!h)return $;const B=y.toLowerCase();return B?$.filter(Pe=>Pe.name.toLowerCase().includes(B)||Pe.handle.toLowerCase().includes(B)||Pe.domain.toLowerCase().includes(B)||Pe.role.toLowerCase().includes(B)):$},[$,h,y]),re=o.useMemo(()=>{if(!H)return ve;const B=K.toLowerCase();return B?ve.filter(Pe=>Pe.name.toLowerCase().includes(B)):ve},[ve,H,K]);o.useEffect(()=>{if(b.current&&clearTimeout(b.current),pe.length<=2){x(!1);return}return x(!1),b.current=window.setTimeout(()=>{x(!0)},5e3),()=>{b.current&&clearTimeout(b.current)}},[pe.length]),o.useEffect(()=>{const B=Pe=>{if((Pe.metaKey||Pe.ctrlKey)&&Pe.key==="k"){if(Pe.preventDefault(),a){l(!1);try{localStorage.setItem(pa,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var z;return(z=r.current)==null?void 0:z.focus()})}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[t,a]);const ue=o.useCallback(()=>{we==="resting"&&t.setComposerMode("focused")},[we,t]),Ce=o.useCallback(()=>{window.setTimeout(()=>{qe.length===0&&!Me&&!h&&!H&&Ie.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),v(!1),oe(!1))},100)},[qe,Me,h,H,Ie.length,t]),Ye=o.useCallback(B=>{const Pe=B.target.value,z=B.target.selectionStart??Pe.length;t.setDraft(Pe),(we==="resting"||we==="focused")&&t.setComposerMode("composing");const Q=Pe.slice(0,z),Ne=Q.match(/@(\w*)$/);if(Ne){v(!0),j(Ne[1]),k(0),_(z-Ne[0].length),oe(!1);return}const De=Q.match(/#(\w*)$/);if(De){oe(!0),be(De[1]),Y(0),ye(z-De[0].length),v(!1);return}h&&v(!1),H&&oe(!1)},[we,t,h,H]),Je=o.useCallback(B=>{var Ne;const Pe=W.slice(0,m),z=W.slice(((Ne=r.current)==null?void 0:Ne.selectionStart)??W.length),Q=`${Pe}@${B.name} ${z}`;t.setDraft(Q),t.selectAssignee(B.id),v(!1),j(""),requestAnimationFrame(()=>{if(r.current){const De=Pe.length+B.name.length+2;r.current.setSelectionRange(De,De),r.current.focus()}})},[W,m,t]),Fe=o.useCallback(B=>{var Q;const Pe=W.slice(0,ce),z=W.slice(((Q=r.current)==null?void 0:Q.selectionStart)??W.length);if(B){const Ne=`${Pe}#${B.name} ${z}`;t.setDraft(Ne),t.setSelectedInitiativeId(B.id),requestAnimationFrame(()=>{if(r.current){const De=Pe.length+B.name.length+2;r.current.setSelectionRange(De,De),r.current.focus()}})}else{const Ne=`${Pe}${z}`;t.setDraft(Ne),t.setSelectedInitiativeId(""),requestAnimationFrame(()=>{r.current&&(r.current.setSelectionRange(Pe.length,Pe.length),r.current.focus())})}oe(!1),be("")},[W,ce,t]),Xe=o.useCallback(B=>{if(h&&q.length>0){if(B.key==="ArrowDown"){B.preventDefault(),k(Pe=>(Pe+1)%q.length);return}if(B.key==="ArrowUp"){B.preventDefault(),k(Pe=>(Pe-1+q.length)%q.length);return}if(B.key==="Enter"||B.key==="Tab"){B.preventDefault(),Je(q[w]);return}if(B.key==="Escape"){B.preventDefault(),v(!1);return}}if(H){const Pe=re.length+1;if(B.key==="ArrowDown"){B.preventDefault(),Y(z=>(z+1)%Pe);return}if(B.key==="ArrowUp"){B.preventDefault(),Y(z=>(z-1+Pe)%Pe);return}if(B.key==="Enter"||B.key==="Tab"){B.preventDefault(),Fe(V===0?null:re[V-1]);return}if(B.key==="Escape"){B.preventDefault(),oe(!1);return}}if(B.key==="Enter"&&!B.shiftKey){B.preventDefault(),t.handlePrimaryAction();return}B.key==="Escape"&&(B.preventDefault(),P?t.setAgentPickerMode(null):Me?t.clearInlineMessages():(t.setComposerMode("resting"),B.target.blur()))},[t,P,Me,h,q,w,Je,H,re,V,Fe]),He=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),mt=Ee||fe?n.jsx("svg",{className:"h-4 w-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"52",strokeDashoffset:"16",strokeLinecap:"round"})}):n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),n.jsx("polyline",{points:"5 12 12 5 19 12"})]}),ot=(we==="reviewing"||Me)&&pe.length>0,lt=Te==="submitted"||Te==="streaming",ge=o.useRef(pe.length),[Ke,Ae]=o.useState(0);return o.useEffect(()=>{if(!a){ge.current=pe.length,Ae(0);return}const B=pe.length-ge.current;B>0&&Ae(B)},[a,pe.length]),a?n.jsxs(n.Fragment,{children:[n.jsx(To,{open:d,onClose:()=>u(!1)}),n.jsx(Eo,{}),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(he.button,{type:"button",onClick:()=>{c(),requestAnimationFrame(()=>{var B;return(B=r.current)==null?void 0:B.focus()})},initial:s?!1:{scale:.8,opacity:0},animate:s?{}:{scale:1,opacity:1},whileHover:s?void 0:{scale:1.08},whileTap:s?void 0:{scale:.92},transition:{type:"spring",stiffness:500,damping:28},className:le("relative inline-flex h-12 w-12 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16]/90 text-primary backdrop-blur-xl","shadow-[0_8px_32px_rgba(0,0,0,0.4),inset_0_1px_0_rgba(255,255,255,0.05)]","hover:border-white/[0.22] hover:bg-[#0A0E16]"),"aria-label":"Open chat",children:[n.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),n.jsx(yt,{children:Ke>0&&n.jsx(he.span,{initial:{scale:0},animate:{scale:1},exit:{scale:0},transition:{type:"spring",stiffness:500,damping:20},className:le("absolute -right-1 -top-1 flex h-5 min-w-[20px] items-center justify-center rounded-full","bg-lime px-1 text-[10px] font-bold text-[#0A0E16]"),children:Ke>9?"9+":Ke},"unread")}),ee&&Ke===0&&n.jsx("span",{className:"absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full border-2 border-[#0A0E16] bg-lime"})]})})]}):n.jsxs(n.Fragment,{children:[n.jsx(To,{open:d,onClose:()=>u(!1)}),n.jsx(Eo,{}),n.jsxs("div",{ref:B=>{t.composerShellRef.current=B},className:"sticky bottom-0 z-20 px-4 pb-4 pt-2",style:{paddingBottom:"max(16px, env(safe-area-inset-bottom))"},children:[n.jsx(yt,{children:O&&n.jsxs(he.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:U,onChange:B=>t.setLaunchWarningAccepted(B.target.checked)}),n.jsx("span",{children:"I understand unresolved attachment extraction may reduce context quality."})]})]},"launch-warning")}),n.jsx("div",{className:"relative",children:n.jsx(rf,{open:P!==null,mode:P??"assignee",agents:ie,quickAgents:X,query:J,selectedAssigneeId:Z,selectedWatcherIds:Re,onQueryChange:t.setAgentPickerQuery,onSelectAssignee:t.selectAssignee,onToggleWatcher:t.toggleWatcher,onClose:()=>t.setAgentPickerMode(null),onSwitchMode:t.setAgentPickerMode,anchorRef:i})}),n.jsxs(he.section,{"data-testid":"chat-dock","data-state":we,initial:s?!1:{opacity:0,y:20},animate:s?{}:{opacity:1,y:0},transition:s?void 0:{duration:Pt.durationEntrance/1e3,ease:Pt.easingEntrance},className:le("group/dock relative rounded-[22px] border border-white/[0.12] bg-[#0A0E16]/80 px-3 py-2.5 backdrop-blur-xl","shadow-[inset_0_1px_0_rgba(255,255,255,0.035),0_14px_34px_rgba(0,0,0,0.36)]","transition-[border-color] duration-200",we!=="resting"&&"border-white/[0.16]"),children:[n.jsx("button",{type:"button",onClick:c,className:le("absolute -right-1 -top-1 z-10 flex h-6 w-6 items-center justify-center rounded-full","border border-white/[0.14] bg-[#0A0E16] text-secondary","opacity-0 transition-opacity duration-200","hover:bg-white/[0.08] hover:text-primary","group-hover/dock:opacity-100"),"aria-label":"Minimize chat",title:"Minimize to icon",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}),n.jsx("input",{ref:B=>{t.fileInputRef.current=B},type:"file",multiple:!0,className:"hidden",onChange:B=>{t.handleFilesAdded(B.target.files),B.currentTarget.value=""}}),n.jsx(yt,{children:ot&&n.jsx(Zp,{messages:pe,isStreaming:lt,collapsed:g,onClick:He})}),n.jsxs("div",{className:"relative",children:[n.jsx(tf,{open:h,agents:q,query:y,activeIndex:w,anchorRect:null,onSelect:Je,onClose:()=>v(!1)}),n.jsx(sf,{open:H,initiatives:re,query:K,activeIndex:V,onSelect:Fe,onClose:()=>oe(!1)})]}),n.jsx(yt,{initial:!1,children:Ie.length>0&&n.jsx(he.div,{initial:s?!1:{opacity:0,height:0},animate:s?{}:{opacity:1,height:"auto"},exit:s?{}:{opacity:0,height:0},transition:{duration:.2,ease:[.22,1,.36,1]},className:"mb-2 overflow-hidden",children:n.jsx("div",{className:"flex flex-wrap items-start gap-2","aria-live":"polite",children:Ie.map(B=>n.jsxs("div",{className:le("group relative flex items-center gap-2.5 rounded-xl border px-3 py-2","transition-colors duration-150",B.status==="failed"?"border-rose-400/30 bg-rose-400/[0.08]":"border-white/[0.1] bg-white/[0.04]"),children:[n.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:`${Do(B.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:Do(B.mimeType),strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n.jsx("polyline",{points:"14 2 14 8 20 8"})]})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"max-w-[180px] truncate text-caption font-medium text-primary",children:B.name}),n.jsxs("p",{className:"text-micro text-muted",children:[af(B.mimeType,B.name),B.sizeBytes?` · ${zp(B.sizeBytes)}`:""]})]}),n.jsx("button",{type:"button",onClick:()=>t.setDraftAttachments(Pe=>Pe.filter(z=>z.id!==B.id)),className:le("absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full","border border-white/[0.16] bg-[#0A0E16] text-[10px] text-secondary","opacity-0 transition-opacity duration-150 group-hover:opacity-100","hover:bg-white/[0.1] hover:text-primary"),"aria-label":`Remove ${B.name}`,children:"×"}),B.status!=="ready"&&B.status!=="failed"&&n.jsx("div",{className:"absolute bottom-0.5 left-3 right-3 h-0.5 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("div",{className:"h-full w-1/2 animate-pulse rounded-full bg-white/[0.2]"})}),B.status==="failed"&&n.jsx("button",{type:"button",onClick:()=>t.handleRetryAttachment(B.id),className:"ml-1 rounded-md border border-rose-300/20 bg-rose-400/[0.12] px-1.5 py-0.5 text-micro text-rose-200 hover:bg-rose-400/[0.2]",children:"Retry"})]},B.id))})})}),n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("button",{type:"button",onClick:()=>{var B;return(B=t.fileInputRef.current)==null?void 0:B.click()},className:le("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","border border-white/[0.12] bg-transparent text-secondary","transition-colors duration-150","hover:bg-white/[0.06] hover:text-primary"),"aria-label":"Add files and more",children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),n.jsxs(he.button,{type:"button",onClick:t.cycleProvider,whileTap:s?void 0:{scale:.93},transition:{duration:.1},className:le("mb-0.5 inline-flex h-7 flex-shrink-0 items-center gap-1.5 rounded-full px-2","border text-micro font-medium","transition-all duration-200",se==="anthropic"?"border-[#F5B700]/30 bg-[#F5B700]/[0.08] text-[#F5B700]":se==="openai"?"border-emerald-400/30 bg-emerald-400/[0.08] text-emerald-300":"border-white/[0.12] bg-white/[0.04] text-muted"),title:`Provider: ${Le.label}. Click to switch.`,"aria-label":`Current provider: ${Le.label}. Click to cycle.`,children:[n.jsx($o,{icon:Le.icon}),n.jsx("span",{children:Le.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:W,onFocus:ue,onBlur:Ce,onChange:Ye,onKeyDown:Xe,placeholder:"Ask anything",rows:1,className:le("w-full resize-none border-none bg-transparent py-1 text-[13px] leading-[22px] text-primary","placeholder:text-muted/60 focus:outline-none"),style:{minHeight:Ro,maxHeight:Lo,overflowY:"auto"},"aria-expanded":we!=="resting"})]}),C.length>0&&n.jsxs("button",{type:"button",onClick:()=>{window.innerWidth>=768?t.toggleThreadSidebar():u(!0)},className:le("mb-0.5 inline-flex h-7 min-w-[28px] flex-shrink-0 items-center justify-center gap-1 rounded-full px-1.5","text-micro text-muted transition-colors duration-150","hover:bg-white/[0.06] hover:text-secondary"),"aria-label":`${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(he.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!ke,"data-action":"chat-send-primary",whileTap:s?void 0:{scale:.92},transition:{duration:.1},className:le("mb-0.5 inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full","transition-all duration-200",ke?"bg-lime text-[#0A0E16] shadow-[0_0_12px_rgba(191,255,0,0.25)]":"bg-white/[0.08] text-muted"),title:de?`Send to ${de.name} via ${Le.shortLabel}`:`Send via ${Le.shortLabel}`,"aria-label":de?`Send to ${de.name} via ${Le.shortLabel}`:`Send message via ${Le.shortLabel}`,children:mt})]}),n.jsx(yt,{children:(de||ne)&&we!=="resting"&&n.jsxs(he.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:[de&&n.jsxs("button",{ref:B=>{i.current=B},type:"button",onClick:t.toggleWatcherPicker,className:le("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-micro","text-[#E1FFB2]/80 transition-colors duration-150 hover:bg-lime/[0.08]"),children:[n.jsx(Bt,{name:de.name,hint:de.name,size:"xs"}),n.jsxs("span",{className:"max-w-[100px] truncate",children:["@",de.name]}),de.status==="running"&&n.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-lime"})]}),ne&&n.jsxs("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-micro text-cyan-100/70",children:["#",ne.name]}),se!=="auto"&&n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-micro",style:{color:Le.accent},children:[n.jsx($o,{icon:Le.icon}),Le.shortLabel]})]})})]})]})]})}const Hi=50,cf=50,pr=20,Fo=3600,Po=12e3,qr={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"},Oo=["live","24h","7d","all"];function Bo(e){if(e==="custom"||e==="all")return null;const t=Oo.indexOf(e);return t<0?null:Oo[t+1]??null}function df(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function qo(e){return e==="codex"||e==="openai"||e==="anthropic"||e==="openclaw"}function us(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function zr(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Wr(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Vi(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function zo(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Ts(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function _a(e){if(!e)return;let t={...e},s=Ts(t.metadata),r=0;for(;s&&r<4;)t={...t,...s},s=Ts(s.metadata),r+=1;return t}function wt(e){const t=Ts(e==null?void 0:e.metadata);return _a(t)}function uf(e){const t=_a(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 fa(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 yr(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 Wo(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const mf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,pf=/^[0-9a-f]{20,}$/i,Fl=/^\d+$/,Pl=/^(user|usr|clerk)_[a-z0-9]+$/i;function Zt(e){if(!e)return null;const t=e.trim();return!t||mf.test(t)||pf.test(t)||Fl.test(t)||Pl.test(t)?null:t}const ff=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function hf(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return ff.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function Uo(e,t,s){if(!e)return null;let r=null;for(const a of t){const l=Zt(Wo(e[a]));if(l){r=l;break}}let i=null;for(const a of s){const l=Zt(Wo(e[a]));if(l){i=l;break}}return!r&&!i?null:{id:r,name:i,label:i??r??"OrgX"}}function gf(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 Ho(e){const t=wt(e),s=yr(e),r=pi(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)??Uo(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)??Uo(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?gf(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 Ki(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}function fr(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 Gi(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 Vo=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 Ur(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function xf(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 Ws(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 yf(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 bf(e){const t=wt(e),s=Ur(e.kind)??Ur(t==null?void 0:t.activity_bucket)??Ur(t==null?void 0:t.activityBucket)??Ur(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=yf(t),i=e.decisionRequired===!0||xf(t,["decision_required","decisionRequired"])===!0,a=Ws(t,["artifacts","artifact_count","artifactCount"])??0,l=Ws(t,["decisions","decision_count","decisionCount"])??0,c=Ws(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Ws(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=Tn(st(t,["stop_reason","stopReason"])??"");if(g==="blocked"||g==="error")return"decision"}return r&&Vo.has(r)?Vo.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 ui(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 wf(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 vf(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 Xi(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function Qi(e){return e==="completed"?D.lime:e==="needs_input"?D.amber:e==="issue"?D.red:D.teal}function kf(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 Ko(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function ms(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 Xn(e){const t=ms(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=ms(s.count??s.total??s.size);if(r!==null)return Math.max(0,Math.round(r))}return null}function jf(e){const t=ms(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 Nf(e,t){for(const s of t){const r=jf(e[s]);if(r!==null)return r}return null}function Hr(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 Ol(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=Hr(e,["blocking_decision_ids","blockingDecisionIds"]),s=Hr(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),r=Hr(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=Hr(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 Bl(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=yr(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(U=>typeof U=="string"&&U.trim().length>0):[],x=Mf(g),b=t.task_ids??t.taskIds,h=Array.isArray(b)?b.filter(U=>typeof U=="string"&&U.trim().length>0):[],v=t.milestone_ids??t.milestoneIds,y=Array.isArray(v)?v.filter(U=>typeof U=="string"&&U.trim().length>0):[],j=st(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),w=st(t,["initiative_title","initiativeTitle"]),k=st(t,["initiative_status","initiativeStatus"]),m=fr(e),_=st(t,["workstream_title","workstreamTitle"]),H=st(t,["workstream_status","workstreamStatus"]),oe=st(t,["task_title","taskTitle"]),K=st(t,["milestone_title","milestoneTitle"]),be=st(t,["domain"]),V=st(t,["phase","slice_phase","slicePhase"]),Y=st(t,["next_step","nextStep"]),ce=Nf(t,["progress_pct","progressPct","progress_percent","progressPercent","completion_pct","completionPct","slice_progress_pct","sliceProgressPct"]),ye=typeof t.parsed_status=="string"?t.parsed_status:typeof t.parsedStatus=="string"?t.parsedStatus:null,we=typeof t.has_output=="boolean"?t.has_output:typeof t.hasOutput=="boolean"?t.hasOutput:null,W=typeof t.log_path=="string"?t.log_path:typeof t.logPath=="string"?t.logPath:null,Ie=typeof t.output_path=="string"?t.output_path:typeof t.outputPath=="string"?t.outputPath:null,Ee=typeof t.error=="string"?t.error:null,fe=Xn(t.artifacts??t.artifact_count??t.artifactCount),Z=Xn(t.decisions??t.decision_count??t.decisionCount),de=Ol(t),Re=t.decisions_needed??t.decisionsNeeded;let ne=Xn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),$=Xn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((ne===null||$===null)&&Array.isArray(Re)){let U=0,se=0;for(const Le of Re){if(!Le||typeof Le!="object"||Array.isArray(Le))continue;Le.blocking===!1?se+=1:U+=1}ne===null&&(ne=U),$===null&&($=se)}ne===null&&Z!==null&&e.decisionRequired===!0&&(ne=Z>0?Z:1),$===null&&Z!==null&&ne!==null&&($=Math.max(0,Z-ne)),ne===null&&Z!==null&&$!==null&&(ne=Math.max(0,Z-$));const X=Xn(t.status_updates_applied??t.statusUpdatesApplied),P=Xn(t.task_updates??t.taskUpdates),J=Xn(t.milestone_updates??t.milestoneUpdates),ie=X??(P!==null||J!==null?(P??0)+(J??0):null),ve=Xn(t.status_updates_buffered??t.statusUpdatesBuffered),ke=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,ee=ms(t.token_budget??t.tokenBudget),Te=ms(t.tokens_used??t.tokensUsed),pe=a.agentId??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null),C=a.agentName??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??x,O=x&&!a.agentName?null:pe;return{event:s,agentId:O,agentName:C,requesterAgentId:l,requesterAgentName:c,dispatcherClient:d,initiativeId:j,domain:be,phase:V,progressPct:ce,nextStep:Y,requiredSkills:g,initiativeStatus:k,initiativeTitle:w,workstreamId:m,workstreamStatus:H,workstreamTitle:_,taskTitle:oe,milestoneTitle:K,taskIds:h,milestoneIds:y,parsedStatus:ye,hasOutput:we,artifacts:fe,decisions:Z,blockingDecisions:ne,nonBlockingDecisions:$,decisionIds:de.decisionIds,blockingDecisionIds:de.blockingDecisionIds,nonBlockingDecisionIds:de.nonBlockingDecisionIds,statusUpdatesApplied:ie,statusUpdatesBuffered:ve,stopReason:ke,tokenBudget:ee,tokensUsed:Te,logPath:W,outputPath:Ie,error:Ee}}function Ji(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function If(e){const t=_a(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 ql(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 Af(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=ql(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 Sf(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 zl(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||!Sf(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 st(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 hr(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||zn(s)?null:s}function Vr(e){for(const t of e){const s=hr(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 Cf(e,t){if(!e)return null;const s=wt(e);if(!s)return null;const r=st(s,["event","event_name","eventName"]),i=Ts(s.spawn_guard),a=Ts(i==null?void 0:i.checks),l=Ts((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),c=st(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=_f(c),u=ms(l==null?void 0:l.current)??d.domainCurrent,g=ms(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:st(s,["domain"])??st(i,["domain","task_domain"]),modelTier:st(s,["spawn_guard_model_tier","model_tier"])??st(i,["modelTier","model_tier"]),domainCurrent:u,domainMax:g,totalCurrent:x,totalMax:b,retryAt:st(s,["next_retry_at","nextRetryAt"]),retryInMs:ms(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:v}}function Mf(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 ${dt(i)}`}return null}function Tf(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 Yi(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&&Tf(r)?a:r??a;if(l)return xr(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"?xr(i):gr.test(i)||Ef.test(i)||Fl.test(i)||Pl.test(i)?"OrgX":xr(i)}const gr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ef=/^[0-9a-f]{20,}$/i,Rf=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function mi(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(Rf)??[]){const c=l.trim().toLowerCase();gr.test(c)&&t.add(c)}typeof e.runId=="string"&&gr.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();gr.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();gr.test(d)&&t.add(d)}}return t}function Lf(e){if(!e)return[];const t=wt(e);return Ol(t).decisionIds}function Df(e,t,s){if(!e)return[];const r=wt(e),i=st(r,["workstream_id","workstreamId"]),a=st(r,["initiative_id","initiativeId"]),l=mi(e);if(!i&&!a&&l.size===0)return[];const c=us(e.timestamp),d=[];for(const b of t){if(b.id===e.id)continue;const h=wt(b);if(!h)continue;const v=st(h,["workstream_id","workstreamId"]),y=st(h,["initiative_id","initiativeId"]),j=mi(b),w=l.size>0&&Array.from(l).some(K=>j.has(K)),k=!!i&&!!v&&i===v;if(!w&&!k&&!(!!a&&!!y&&a===y))continue;const _=zl(b).filter(K=>!s.has(K.path));if(_.length===0)continue;const H=Math.abs(us(b.timestamp)-c);if(!w&&H>7200*1e3)continue;const oe=w?0:k?1:2;!w&&H>1200*1e3||d.push({priority:oe,delta:H,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 $f(e,t){if(!e)return null;const s=wt(e),r=st(s,["workstream_id","workstreamId"]),i=st(s,["initiative_id","initiativeId"]),a=mi(e);if(!r&&!i&&a.size===0)return null;const l=us(e.timestamp),c=[];for(const u of t){if(u.id===e.id)continue;const g=Bl(u);if(!g)continue;const x=wt(u);if(!x)continue;const b=st(x,["workstream_id","workstreamId"]),h=st(x,["initiative_id","initiativeId"]),v=mi(u),y=a.size>0&&Array.from(a).some(H=>v.has(H)),j=!!r&&!!b&&r===b;if(!y&&!j&&!(!!i&&!!h&&i===h))continue;const k=Math.abs(us(u.timestamp)-l);if(!y&&k>1200*1e3)continue;const m=y?"shared_id":j?"workstream":"initiative",_=m==="shared_id"?0:m==="workstream"?1:2;c.push({priority:_,delta:k,relation:m,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 Tn(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function yi(e){const t=Tn(e);return["done","complete","completed","stopped","success"].includes(t)}function Ff(e){const t=Tn(e.parsedStatus),s=Tn(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":yi(t)||e.stopReason==="completed"?"positive":"neutral"}function Pf(e){if(yi(e.parsedStatus)||e.stopReason==="completed")return 100;const t=Tn(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 Wl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function Of(e,t){if(!e&&t===null)return null;const s=e?Ff(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=Wl(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=Pf(e);if(a===null)return null;const l=r(a);return{pct:a,source:"lifecycle",label:l?i:"Progress",tone:s,terminalStop:l}}function Bf(e,t,s,r=null){var w;const i=wt(e),a=Tn(st(i,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),l=Tn(e.state??e.phase??e.kind??e.type),c=Tn((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??l),d=Tn((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=st(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"||yi(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:Et(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:Et(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:Et(e.title)??"Autopilot stopped because the current dispatch scope is complete.",hint:null,tone:"positive"};if(d==="stopped")return{label:"Stopped",summary:Et(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:Et(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:Et(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)??""),m=String((i==null?void 0:i.new_state)??""),_=String((i==null?void 0:i.reason)??"");return m==="running"?{label:"Autopilot activated",summary:`State changed from ${k} to running.`,hint:"Autopilot will dispatch work from the Next Up queue.",tone:"positive"}:m==="blocked"||m==="error"?{label:m==="error"?"Autopilot error":"Autopilot blocked",summary:`State changed from ${k} to ${m}${_?`: ${_}`:""}.`,hint:"Review the triage queue for actionable items.",tone:"critical"}:{label:"Autopilot state change",summary:`${k} → ${m}${_?` (${_})`:""}.`,hint:null,tone:"neutral"}}if(y)return{label:"Rate limited",summary:u?Et(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?Et(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?Et(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?Et(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 Ul(e){if(typeof e=="string")return n.jsx(li,{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:Ul(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:dt(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 Et(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=wr(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:dt(t)}const qf=[/^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 zf(e){return qf.some(t=>t.test(e))}function pi(e){const t=e.title??"";return zf(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:dt(t)||dt(ui(e.type)),isSystem:!1}}const Wf=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 br(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&&Wf.has(s)||l||c&&(d||u)||d&&(u||i.includes("outbox")||i.includes("replay"))||i.includes("outbox_replay")&&u)}function Go(e){var d;if(!e||!br(e))return null;const t=wt(e),s=Xn((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=st(t,["entity_type","entityType"])??i??(e.type==="milestone_completed"?"milestone":null),l=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",c=a?` for ${dt(a).toLowerCase()}`:"";return`${l}${c} were synced from local replay.`}function Zi(e){if(!br(e))return null;const t=wt(e);if(!t)return null;const s=st(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const r=st(t,["event","event_name","eventName"])??"",i=st(t,["changeset_id","changesetId"])??"",a=st(t,["entity_type","entityType"])??"",l=st(t,["entity_id","entityId"])??"",c=fa(e)??"",d=pi(e).title.trim().toLowerCase();return`fallback:${r.toLowerCase()}:${i.toLowerCase()}:${a.toLowerCase()}:${l.toLowerCase()}:${c.toLowerCase()}:${d}`}function Uf(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 Xo(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 Qo(e,t){const r=(Et(t??e.summary)??Et(e.description)??dt(e.title||ui(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=>Xo(l).trim()).filter(l=>l.length>0&&!/^\|?[:\-| ]+\|?$/.test(l));let a=i[0]??Xo(r);return a.length<24&&i.length>1&&(a=`${a} ${i[1]}`.trim()),a.length>108?`${a.slice(0,107).trimEnd()}…`:a}const Hf=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:m,onClearAgentFilter:_,onFocusRunId:H,onOpenDecision:oe,requestedActivityItemId:K=null,onActivityItemRequestHandled:be,onPlayNextUp:V,onStartAutopilot:Y,onPauseWorkstream:ce,onCreateInitiative:ye,onOpenMissionControl:we,onOpenSettings:W,workspaceId:Ie=null,chatSnapshot:Ee,onRefreshData:fe,isLoading:Z=!1,onOpenNextUp:de}){var Ma;const Re=Yn(),{open:ne}=Cl(),[$,X]=o.useState("all"),[P,J]=o.useState(!1),[ie,ve]=o.useState(!1),[ke,ee]=o.useState(""),[Te,pe]=o.useState(new Set),[C,O]=o.useState({}),[U,se]=o.useState("newest"),[Le,qe]=o.useState(!1),[Me,T]=o.useState(!1),[q,re]=o.useState(Hi),[ue,Ce]=o.useState(null),[Ye,Je]=o.useState(null),[Fe,Xe]=o.useState(!1),[He,mt]=o.useState(1),[ot,lt]=o.useState("structured"),[ge,Ke]=o.useState(null),[Ae,B]=o.useState("feed"),[Pe,z]=o.useState(null),[Q,Ne]=o.useState(null),[De,$e]=o.useState(!1),[Oe,Se]=o.useState(null),[Ge,rt]=o.useState(null),[ze,Ct]=o.useState(!1),[Ze,jt]=o.useState(null),[Jt,Gt]=o.useState(!1),dn=o.useRef(Date.now()),En=o.useRef(null),hs=o.useRef(null),pt=o.useRef(null),Ht=o.useRef(null),wn=o.useRef(null),[Lt,Nt]=o.useState(()=>zr(h.startIso)),[Wt,Vt]=o.useState(()=>zr(h.endIso)),[Ot,un]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),Zn=o.useMemo(()=>ul(x),[x]),mn=o.useMemo(()=>zr(h.startIso),[h.startIso]),Rn=o.useMemo(()=>zr(h.endIso),[h.endIso]),gs=o.useMemo(()=>!Lt||!Wt?!1:Wt.getTime()>=Lt.getTime(),[Wt,Lt]),vn=o.useMemo(()=>x!=="custom"?Zn.label:mn&&Rn?`${Wr(mn)} - ${Wr(Rn)}`:"Custom range",[Rn,mn,x,Zn.label]);o.useEffect(()=>{Nt(mn),Vt(Rn)},[Rn,mn]),o.useEffect(()=>{if(typeof window>"u")return;const f=()=>un(window.innerWidth<=640);return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[]),o.useEffect(()=>{const N=()=>{dn.current=Date.now()};window.addEventListener("pointerdown",N),window.addEventListener("keydown",N);const I=setInterval(()=>{Date.now()-dn.current>3e5&&Gt(!0)},3e4);return()=>{window.removeEventListener("pointerdown",N),window.removeEventListener("keydown",N),clearInterval(I)}},[]);const en=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 xe;return M.type==="decision_requested"&&((xe=M.metadata)==null?void 0:xe.status)==="pending"}).length;return{completed:f,blocked:N,decisions:I}},[s,t]),Kt=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]),es=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]),kn=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 f},[s]),ts=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:us(N.updatedAt??N.lastEventAt??N.startedAt??null)},M=[N.runId,N.sliceRunId].filter(xe=>typeof xe=="string"&&xe.trim().length>0).map(xe=>xe.trim());for(const xe of M){const Ve=f.get(xe);(!Ve||I.updatedEpoch>=Ve.updatedEpoch)&&f.set(xe,I)}}return f},[r]),ns=o.useMemo(()=>{const f=new Map;for(const N of s){const I=Wl(N.progress);I!==null&&(f.set(N.runId,I),f.set(N.id,I))}return f},[s]),tn=o.useMemo(()=>{const f=new Map;for(const N of s)!N.agentId||!N.agentName||f.set(N.agentId,N.agentName);return f},[s]),Ln=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]),Dt=o.useMemo(()=>{const f=new Map;for(const N of r){const I=N.workstreamId??null,M=hr(N.workstreamTitle,I);if(!M)continue;const xe=[N.runId,N.sliceRunId].filter(Ve=>typeof Ve=="string"&&Ve.trim().length>0).map(Ve=>Ve.trim());for(const Ve of xe)f.set(Ve,M)}return f},[r]),ss=o.useMemo(()=>{const f=new Map;for(const N of i){const I=hr(N.name,N.id);I&&f.set(N.id,I)}return f},[i]),nn=o.useMemo(()=>{const f=new Map;for(const N of i)for(const I of N.workstreams??[]){const M=hr(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=hr(N.workstreamTitle,I);M&&f.set(I,M)}return f},[i,r]);o.useMemo(()=>{const f=[...s];return f.sort((N,I)=>{const M=us(N.updatedAt??N.lastEventAt??N.startedAt??null);return us(I.updatedAt??I.lastEventAt??I.startedAt??null)-M}),f},[s]);const pn=o.useMemo(()=>t.map(f=>{const N=fa(f),I=bf(f),M=wt(f),xe=N?kn.get(N)??null:null,Ve=N?ts.get(N)??null:null,it=wp({sessionStatus:(xe==null?void 0:xe.status)??(N?es.get(N)??null:null),sessionPhase:(xe==null?void 0:xe.phase)??null,sessionState:(xe==null?void 0:xe.state)??null,sliceStatus:(Ve==null?void 0:Ve.status)??null,activityType:f.type,activityStatus:st(M,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:st(M,["stop_reason","stopReason"]),decisionRequired:f.decisionRequired??!1,blockingDecisionCount:Ws(M,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Ve==null?void 0:Ve.blockingDecisions)??0,nonBlockingDecisionCount:Ws(M,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Ve==null?void 0:Ve.nonBlockingDecisions)??0,blockerCount:(xe==null?void 0:xe.blockerCount)??0,blockerReason:(xe==null?void 0:xe.blockerReason)??null}),vt=kf(I,it),gn=[f.title,f.description,f.summary,f.agentName,uf(M)].filter(On=>typeof On=="string"&&On.length>0).join(" ").toLowerCase(),kt=N?(Kt.get(N)??N).toLowerCase():"",xt=M==null?void 0:M.scope,Xt=xt==="milestone"||xt==="workstream"?xt:void 0;return{item:f,bucket:I,userState:vt.state,userStateWhy:vt.why,canonicalProjection:it,runId:N,timestampEpoch:us(f.timestamp),searchText:gn,runLabelSearch:kt,scopeGroupId:Xt?N??null:null,scope:Xt}}),[t,Kt,kn,es,ts]),jn=o.useMemo(()=>{const f=[...pn];return f.sort((N,I)=>{const M=I.timestampEpoch-N.timestampEpoch;return M!==0?M:I.item.id.localeCompare(N.item.id)}),f},[pn]),R=o.useMemo(()=>[...jn].reverse(),[jn]),me=o.useMemo(()=>{let f=0;for(const N of pn)f=Math.max(f,N.timestampEpoch);return f<=0?!1:Date.now()-f<6e4},[pn]),ae=o.useMemo(()=>new Set(l.filter(f=>f&&f.trim().length>0)),[l]),je=ae.size>0,ft=o.useMemo(()=>vr.filter(f=>["live","24h","7d","all"].includes(f.id)),[]),Qe=o.useMemo(()=>{if(!je)return null;for(const f of ae){const N=s.find(I=>I.runId===f||I.id===f);if(N)return N}return null},[je,ae,s]),et=o.useMemo(()=>je?Qe!=null&&Qe.runtimeProvider?{id:df(Qe.runtimeProvider)}:ds(Qe==null?void 0:Qe.agentId,Qe==null?void 0:Qe.agentName,Qe==null?void 0:Qe.title,Qe==null?void 0:Qe.lastEventSummary,Qe==null?void 0:Qe.runtimeClient,c):ds(),[Qe,je,c]),xs=o.useMemo(()=>g?ds(g):ds(),[g]),{filtered:ht,filteredTotal:rs,hiddenCount:bt,hiddenSyncCount:fn}=o.useMemo(()=>{const f=U==="newest"?jn:R,N=[];let I=0,M=0;const xe=new Set,Ve=ke.trim().toLowerCase();for(const kt of f){const xt=kt.runId;if(je&&(!xt||!ae.has(xt)))continue;if(d){const _n=fr(kt.item),er=xt?Ln.get(xt)??null:null;if((_n??er)!==d)continue}const Xt=yr(kt.item);if(g&&Xt.agentName!==g)continue;const On=Zi(kt.item);if(On){if(xe.has(On)){M+=1;continue}if(xe.add(On),!P){M+=1;continue}}else if(!P&&br(kt.item)){M+=1;continue}$==="completed"&&kt.userState!=="completed"||$==="needs_attention"&&kt.userState!=="needs_input"&&kt.userState!=="issue"||$==="in_progress"&&kt.userState!=="in_progress"||Ve.length>0&&!`${kt.searchText} ${kt.runLabelSearch}`.includes(Ve)||(N.length<Po?N.push(kt):I+=1)}const it=Math.min(Math.max(1,Math.min(Fo,q)),N.length),vt=N.slice(0,it),gn=N.length+I;return{filtered:vt,filteredTotal:gn,hiddenCount:Math.max(0,gn-vt.length),hiddenSyncCount:M}},[$,g,jn,R,je,ke,q,d,ae,Ln,P,U]),Wn=o.useMemo(()=>{const f=new Map;for(const I of ht){const M=wf(I.item.timestamp),xe=f.get(M);xe?xe.push(I):f.set(M,[I])}return Array.from(f.keys()).sort((I,M)=>{const xe=Number(M)-Number(I);return U==="newest"?xe:-xe}).map(I=>({key:I,label:vf(I),items:f.get(I)??[]}))},[ht,U]),ys=o.useMemo(()=>Wn.map(f=>{const N=new Map;for(const I of f.items){const M=pi(I.item).title.trim().toLowerCase(),xe=Zi(I.item),Ve=xe?`${I.item.type}::sync::${xe}`:`${I.item.type}::${M}`,it=N.get(Ve);it?(it.count+=1,it.firstTimestamp=Math.min(it.firstTimestamp,I.timestampEpoch),it.allItems.push(I),I.timestampEpoch>it.representative.timestampEpoch&&(it.representative=I)):N.set(Ve,{key:Ve,representative:I,count:1,firstTimestamp:I.timestampEpoch,allItems:[I]})}return{...f,clusters:Array.from(N.values())}}),[Wn]),Nn=o.useCallback(f=>{pe(N=>{const I=new Set(N);return I.has(f)?I.delete(f):I.add(f),I}),O(N=>{if(Object.prototype.hasOwnProperty.call(N,f)){const I={...N};return delete I[f],I}return{...N,[f]:pr}})},[]),bs=o.useCallback((f,N)=>{O(I=>{const M=I[f]??pr,xe=Math.min(N,M+pr);return xe===M?I:{...I,[f]:xe}})},[]),Un=o.useCallback(()=>{!v||!b||!Lt||!Wt||Wt.getTime()<Lt.getTime()||(v({startIso:Lt.toISOString(),endIso:Wt.toISOString()}),b("custom"),T(!1))},[Wt,Lt,v,b]),St=o.useCallback(()=>{Nt(null),Vt(null),v==null||v({startIso:null,endIso:null}),x==="custom"&&(b==null||b("live"))},[v,b,x]),In=o.useMemo(()=>Math.min(Fo,Math.min(Po,rs)),[rs]);o.useEffect(()=>{re(Hi),pe(new Set),O({})},[$,g,je,ke,d,P,U,x]),o.useEffect(()=>{if(!Le)return;const f=I=>{var xe;const M=I.target;M instanceof Node&&((xe=En.current)!=null&&xe.contains(M)||qe(!1))},N=I=>{I.key==="Escape"&&qe(!1)};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",N),()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",N)}},[Le]),o.useEffect(()=>{if(!Me)return;const f=I=>{var xe;const M=I.target;M instanceof Node&&((xe=hs.current)!=null&&xe.contains(M)||T(!1))},N=I=>{I.key==="Escape"&&T(!1)};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",N),()=>{window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",N)}},[Me]);const An=o.useRef(w);An.current=w;const ws=o.useRef(y);ws.current=y;const Dn=o.useRef(j);Dn.current=j;const[Sn,vs]=o.useState(!1),Rs=o.useRef(null),Nr=o.useRef(x),Ir=o.useRef(Date.now()),Gs=o.useRef(!1);o.useEffect(()=>{Nr.current!==x&&(Nr.current=x,Rs.current=null,Ir.current=Date.now(),Gs.current=!1)},[x]),o.useEffect(()=>{const f=pt.current,N=Ht.current;if(!f||!N)return;const I=new IntersectionObserver(xe=>{const Ve=xe.some(it=>it.isIntersecting);vs(Ve)},{root:f,rootMargin:"0px 0px 600px 0px"});I.observe(N);const M=()=>{Gs.current=!0};return f.addEventListener("scroll",M,{passive:!0}),()=>{I.disconnect(),f.removeEventListener("scroll",M)}},[]),o.useEffect(()=>{var f;if(Sn){if(ht.length<In){re(N=>Math.min(In,Math.max(N,Hi)+cf));return}if(ws.current&&!Dn.current){(f=An.current)==null||f.call(An);return}}},[ht.length,In,Sn]),o.useEffect(()=>{if(!Sn||y||j||!b)return;const f=pt.current,N=f?f.scrollHeight<=f.clientHeight+4:!1;if(!Gs.current&&!N||Date.now()-Ir.current<3e3)return;const M=Bo(x);M&&Rs.current!==M&&(Rs.current=M,b(M))},[ht.length,y,j,b,Sn,x]);const Mt=o.useMemo(()=>ue?ht.findIndex(f=>f.item.id===ue):-1,[ue,ht]),E=Mt>=0?ht[Mt]:null,Ar=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]),Hn=o.useMemo(()=>{if(!E)return null;const f=E.runId??fa(E.item);return f?Ar.get(f)??null:null},[E,Ar]),Vn=o.useMemo(()=>ql((E==null?void 0:E.item)??null),[E]),hn=o.useMemo(()=>Gi((E==null?void 0:E.item)??null),[E]),$n=o.useMemo(()=>Bl((E==null?void 0:E.item)??null),[E]),Ls=o.useMemo(()=>$n?null:$f((E==null?void 0:E.item)??null,t),[$n,E,t]),We=o.useMemo(()=>E?Ho(E.item):null,[E]),Fn=o.useMemo(()=>We?We.executor??We.requester:null,[We]),te=$n??(Ls==null?void 0:Ls.detail)??null,Xs=o.useMemo(()=>{var f,N;return Yi((te==null?void 0:te.requesterAgentName)??((f=We==null?void 0:We.requester)==null?void 0:f.name)??null,(te==null?void 0:te.requesterAgentId)??((N=We==null?void 0:We.requester)==null?void 0:N.id)??null,tn)},[te,We,tn]),is=o.useMemo(()=>hf(Xs),[Xs]),Qs=o.useMemo(()=>{var N,I;const f=Yi((te==null?void 0:te.agentName)??((N=We==null?void 0:We.executor)==null?void 0:N.name)??null,(te==null?void 0:te.agentId)??((I=We==null?void 0:We.executor)==null?void 0:I.id)??null,tn);return f==="—"?(We==null?void 0:We.primaryLabel)??"Codex":f},[te,We,tn]),Yt=o.useMemo(()=>E!=null&&E.runId?ns.get(E.runId)??null:null,[E,ns]),$t=o.useMemo(()=>Of(te,Yt),[te,Yt]),L=o.useMemo(()=>{const f=te;if(!f)return null;const N=f.initiativeId??(E==null?void 0:E.item.initiativeId)??null,I=N?i.find(_n=>_n.id===N)??null:null,M=f.initiativeTitle??(I==null?void 0:I.name)??null,xe=f.initiativeStatus??(I==null?void 0:I.status)??null,Ve=(I==null?void 0:I.workstreams)??[],it=Ve.length>0?Ve.length:null,vt=it!==null?Ve.filter(_n=>yi(_n.status)).length:null,gn=it&&vt!==null?Math.round(vt/it*100):null,kt=f.workstreamId??null,xt=kt&&Ve.length>0?Ve.find(_n=>_n.id===kt)??null:null,Xt=f.workstreamTitle??(xt==null?void 0:xt.name)??(kt?nn.get(kt)??null:null),On=f.workstreamStatus??(xt==null?void 0:xt.status)??null;return{initiativeId:N,initiativeTitle:M,initiativeStatus:xe,totalInitiativeWorkstreams:it,doneInitiativeWorkstreams:vt,initiativeWorkstreamPct:gn,workstreamId:kt,workstreamTitle:Xt,workstreamStatus:On,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}},[te,E,i,nn]),Tt=o.useMemo(()=>E?Bf(E.item,te,L?{decisions:L.decisions,blockingDecisions:L.blockingDecisions,nonBlockingDecisions:L.nonBlockingDecisions,stopReason:L.stopReason,parsedStatus:L.parsedStatus}:null,E.canonicalProjection??null):null,[te,E,L]),Sr=o.useMemo(()=>{if(!L)return[];const f=[];Tt&&f.push({label:"Status",value:Tt.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:sr(L.stopReason)??dt(L.stopReason)});const M=pc(L.tokensUsed,L.tokenBudget);return M&&f.push({label:"Token usage",value:M}),f},[L,Tt]),Ds=o.useMemo(()=>{const f=new Set;for(const N of Lf((E==null?void 0:E.item)??null))f.add(N);for(const N of(te==null?void 0:te.decisionIds)??[])f.add(N);for(const N of(te==null?void 0:te.blockingDecisionIds)??[])f.add(N);for(const N of(te==null?void 0:te.nonBlockingDecisionIds)??[])f.add(N);return Array.from(f)},[te,E]),bi=o.useMemo(()=>oe?Ds.length>0||(E==null?void 0:E.item.decisionRequired)===!0||((L==null?void 0:L.blockingDecisions)??0)>0?!0:(Tt==null?void 0:Tt.label)==="Needs decision":!1,[Ds,E,L,Tt,oe]),Js=o.useMemo(()=>$t?$t.tone==="positive"?D.lime:$t.tone==="warning"?D.amber:$t.tone==="critical"?D.red:D.teal:D.teal,[$t]),ks=($t==null?void 0:$t.terminalStop)===!0,tt=o.useMemo(()=>If(wt((E==null?void 0:E.item)??null)),[E]),Ys=o.useMemo(()=>wt((E==null?void 0:E.item)??null),[E]),gt=o.useMemo(()=>Cf((E==null?void 0:E.item)??null,te),[te,E]),Kn=o.useMemo(()=>{if(!(gt!=null&>.retryAt))return null;const f=new Date(gt.retryAt);if(!Number.isFinite(f.getTime()))return null;const N=f.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),I=_t(gt.retryAt);return I?`${N} (${I})`:N},[gt]),Zs=o.useMemo(()=>E?yr(E.item):{agentId:null,agentName:null},[E]),p=o.useMemo(()=>Ko(Ts(E==null?void 0:E.item.metadata)??void 0),[E]);o.useMemo(()=>Ko(Ys),[Ys]);const A=o.useMemo(()=>{const f=zl((E==null?void 0:E.item)??null);return f.length>0?f:Df((E==null?void 0:E.item)??null,t,new Set)},[E,t]),F=o.useMemo(()=>A.filter((f,N,I)=>I.findIndex(M=>M.path===f.path)===N),[A]),S=o.useMemo(()=>F.slice(0,4),[F]),G=o.useMemo(()=>F.slice(4),[F]),_e=o.useMemo(()=>{if(F.length===0)return null;const f=F[0];return f?Ji(f.path):null},[F]),nt=o.useMemo(()=>{const f=Et(ge);if(f)return f;const N=Go((E==null?void 0:E.item)??null);return N||(Et(E==null?void 0:E.item.summary)??Et(E==null?void 0:E.item.description))},[ge,E]),Ue=o.useMemo(()=>E?br(E.item):!1,[E]),Be=o.useMemo(()=>{if(!te||!E)return null;const f=te.initiativeId??E.item.initiativeId??null,N=te.workstreamId??fr(E.item);if(!f||!N)return null;const I=Tn((L==null?void 0:L.parsedStatus)??te.parsedStatus),M=Tn((L==null?void 0:L.stopReason)??te.stopReason),xe=Math.max(0,(L==null?void 0:L.blockingDecisions)??te.blockingDecisions??(E.item.decisionRequired?1:0)),Ve=Math.max(0,(L==null?void 0:L.nonBlockingDecisions)??te.nonBlockingDecisions??0),it=I==="blocked"||I==="error"||I==="failed"||M==="blocked"||M==="error"||E.item.type==="blocker_created",vt=!it&&xe===0&&Ve>0&&(I==="needs_decision"||I==="completed"||M==="completed");return!it&&!vt?null:{initiativeId:f,workstreamId:N,runId:E.runId??null,event:te.event,requestedByAgentId:te.requesterAgentId??E.item.requesterAgentId??null,requestedByAgentName:te.requesterAgentName??E.item.requesterAgentName??null,actionLabel:it?"Auto-fix in 10s":"Auto-continue in 10s",helperText:it?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:it}},[te,E,L]),ct=o.useCallback(()=>{Ce(null)},[]),It=o.useCallback(async(f,N)=>{if(N){rt(null),Se(f);try{await N()}catch(I){rt(I instanceof Error?I.message:"Action failed")}finally{Se(I=>I===f?null:I)}}},[]),_r=o.useCallback(async()=>{var f;if(!(!Be||ze)){Ct(!0),jt(null);try{const N=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:Be.initiativeId,workstreamId:Be.workstreamId,runId:Be.runId,event:Be.event,requestedByAgentId:Be.requestedByAgentId,requestedByAgentName:Be.requestedByAgentName,graceMs:1e4})}),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,xe=M&&Number.isFinite(M.getTime())?M.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;jt(xe?`Scheduled. Auto action starts by ${xe} 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";jt(Rt(I)||I)}finally{Ct(!1)}}},[Be,ze]);o.useEffect(()=>{if(!Ye)return;const f=window.setTimeout(()=>Je(null),2e3);return()=>window.clearTimeout(f)},[Ye]),o.useEffect(()=>{rt(null)},[$,ke,x]),o.useEffect(()=>{if(!K){wn.current=null;return}const f=K.trim();!f||wn.current===f||!t.some(I=>I.id===f)||(wn.current=f,ve(!1),X("all"),ee(""),mt(1),Ce(f),be==null||be(f))},[t,be,K]);const sn=o.useCallback(async(f,N)=>{if(N)try{await navigator.clipboard.writeText(N),Je(`${f} copied`)}catch{Je("Copy failed")}},[]);o.useEffect(()=>{lt("structured"),Xe(!1),Ct(!1),jt(null)},[ue]),o.useEffect(()=>{Ke(null),B("feed");const f=Uf((E==null?void 0:E.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 Ve;return M.ok?((Ve=(await M.json()).detail)==null?void 0:Ve.summary)??null:(M.status===404&&B("missing"),null)}).then(M=>{typeof M=="string"&&M.trim().length>0?(Ke(M),B("local")):B("missing")}).catch(M=>{M instanceof DOMException&&M.name==="AbortError"||B("missing")}),()=>I.abort()},[E]),o.useEffect(()=>{z(null),Ne(null);const f=E==null?void 0:E.item;if(!f||De)return;const N=(ge??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)&&$e(!0),null)).then(M=>{const xe=M==null?void 0:M.headline;typeof xe=="string"&&xe.trim().length>0&&($e(!1),z(xe.trim()),Ne((M==null?void 0:M.source)??null))}).catch(M=>{M instanceof DOMException&&M.name}),()=>I.abort()},[E,ge,De]);const Pn=o.useCallback(f=>{var M;if(ht.length===0)return;const I=((Mt>=0?Mt:0)+f+ht.length)%ht.length;mt(f),Ce(((M=ht[I])==null?void 0:M.item.id)??null)},[Mt,ht]);o.useEffect(()=>{ue&&(Mt>=0||Ce(null))},[Mt,ue]),o.useEffect(()=>{if(!ue)return;const f=N=>{N.key==="ArrowRight"||N.key.toLowerCase()==="l"?(N.preventDefault(),Pn(1)):(N.key==="ArrowLeft"||N.key.toLowerCase()==="h")&&(N.preventDefault(),Pn(-1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[ue,Pn]);const as=ae.size===1,wi=as?[...ae][0]:null,Hl=wi?s.find(f=>f.runId===wi||f.id===wi)??null:null,vi=o.useMemo(()=>{if(!as)return[];const f=[],N=new Set;for(const I of pn){if(!I.runId||!ae.has(I.runId))continue;const M=Zi(I.item);if(M){if(N.has(M)||(N.add(M),!P))continue}else if(!P&&br(I.item))continue;f.push(I.item)}return f},[as,pn,ae,P]),Ca=!Re&&ht.length<=160,$s=(f,N,I)=>{const M=f.item,xe=I??M.id,Ve=yr(M),it=Ho(M),vt=it.executor??it.requester,gn=Yi(Zt((vt==null?void 0:vt.name)??it.primaryLabel??M.agentName??Ve.agentName??null),Zt((vt==null?void 0:vt.id)??M.agentId??Ve.agentId??null),tn)||"OrgX",kt=Qi(f.userState),xt=U==="newest"&&N<2,Xt=f.runId,On=Go(M),{title:_n}=pi(M),er=On??Et(M.summary),Cr=Et(M.description),Ta=Qo(M,er??Cr??null),Ea=wt(M),Ra=Vr([{value:st(Ea,["initiative_title","initiativeTitle"]),idHint:M.initiativeId},{value:M.initiativeId?ss.get(M.initiativeId)??null:null,idHint:M.initiativeId}]),tr=fr(M)??(Xt?Ln.get(Xt)??null:null),La=Vr([{value:st(Ea,["workstream_title","workstreamTitle"]),idHint:tr},{value:tr?nn.get(tr)??null:null,idHint:tr},{value:Xt?Dt.get(Xt)??null:null,idHint:tr}]),Vl=[Ra,La].filter(Boolean).join(" > ")||Ra||La||dt(M.type),Kl=Xi(f.userState),Gl=new Date(M.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),Xl=_t(M.timestamp),Ql=f.bucket==="artifact"?Af(M):null;return n.jsx($p,{renderKey:xe,displayTitle:_n,headline:Ta,contextLabel:Vl,detailText:(er??Cr)!==Ta?er??Cr:null,displayAgentName:gn,railColor:kt,userStateLabel:Kl,userStateWhy:f.userStateWhy,relativeTime:Xl,timeLabel:Gl,isRecent:xt,enableMotion:Ca,onOpen:()=>{mt(1),Ce(M.id)},ariaLabel:`Open activity details for ${_n||ui(M.type)}`,artifactSnippet:Ql},xe)};return n.jsx(Jp,{sessions:s,initiatives:i??[],workspaceId:Ie??null,query:ke,statusFilter:$,sortOrder:U,timeFilterId:x,customTimeRange:h,snapshot:Ee,onRequestRefresh:fe,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[as&&vi.length>0?n.jsx(Rp,{items:vi,session:Hl,agentName:((Ma=vi[0])==null?void 0:Ma.agentName)??null,onBack:k,onOpenItem:f=>{mt(1),Ce(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:rs}),bt>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:["+",bt," hidden"]}),fn>0&&!P&&n.jsxs("button",{type:"button",onClick:()=>J(!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:[fn," sync hidden"]}),P&&n.jsx("button",{type:"button",onClick:()=>J(!1),className:"hidden flex-shrink-0 rounded-full border border-lime/30 bg-lime/[0.10] px-2 py-0.5 text-micro text-[#E1FFB2] transition-colors hover:bg-lime/[0.16] sm:inline-flex",title:"Hide low-signal sync replay events",children:"Sync visible"}),n.jsx("span",{className:le("h-1.5 w-1.5 flex-shrink-0 rounded-full",me&&"pulse-soft"),style:{backgroundColor:D.lime},"aria-label":"Live",title:me?"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:ke,onChange:f=>ee(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:hs,children:[n.jsxs("button",{type:"button",onClick:()=>{T(f=>!f),qe(!1)},"aria-haspopup":"menu","aria-expanded":Me,className:le("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",Me?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsx("span",{className:"max-w-[120px] truncate",children:vn}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:le("transition-transform duration-200",Me&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(yt,{children:Me&&n.jsx(he.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:vr.filter(f=>f.id!=="custom").map(f=>{const N=x===f.id;return n.jsx("button",{type:"button",onClick:()=>{b==null||b(f.id),T(!1)},className:le("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"}),Ot?n.jsx("input",{type:"datetime-local",step:300,value:Vi(Lt),onChange:f=>Nt(zo(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(Da,{selected:Lt,onChange:f=>Nt(f instanceof Date?f:null),selectsStart:!0,startDate:Lt,endDate:Wt,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"}),Ot?n.jsx("input",{type:"datetime-local",step:300,min:Vi(Lt),value:Vi(Wt),onChange:f=>Vt(zo(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(Da,{selected:Wt,onChange:f=>Vt(f instanceof Date?f:null),selectsEnd:!0,minDate:Lt??void 0,startDate:Lt,endDate:Wt,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:gs?`${Wr(Lt)} - ${Wr(Wt)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:St,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:Un,disabled:!gs,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:[(je||d||g)&&n.jsxs(n.Fragment,{children:[je&&n.jsxs("button",{onClick:k,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[qo(et.id)?n.jsx(Hs,{provider:et.id,size:"xs"}):n.jsx(Bt,{name:(Qe==null?void 0:Qe.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:m,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:[qo(xs.id)?n.jsx(Hs,{provider:xs.id,size:"xs"}):n.jsx(Bt,{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(qr).map(f=>{const N=$===f;return n.jsx("button",{type:"button",onClick:()=>X(f),"aria-pressed":N,className:le("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:qr[f]},f)})}),n.jsx("button",{type:"button",onClick:()=>ve(f=>!f),className:le("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",ie?"border-lime/30 text-lime":"border-white/[0.1]"),"aria-pressed":ie,"aria-label":ie?"Expand activity density":"Compact activity density",title:ie?"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:ie?"M4 12h16":"M4 12h10"}),n.jsx("path",{d:"M4 17h16"})]})}),n.jsxs("div",{className:"relative flex-shrink-0",ref:En,children:[n.jsxs("button",{type:"button",onClick:()=>{qe(f=>!f),T(!1)},"aria-haspopup":"menu","aria-expanded":Le,"aria-label":"Activity filters",title:"Activity filters",className:le("inline-flex h-8 items-center gap-1.5 rounded-full border px-2.5 text-caption font-semibold transition-colors",Le?"border-lime/30 bg-lime/[0.10] text-[#E1FFB2]":"border-white/[0.1] bg-white/[0.03] text-primary hover:bg-white/[0.08]"),children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 6h16"}),n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"M10 18h4"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Filters"}),n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:le("transition-transform duration-200",Le&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(yt,{children:Le&&n.jsx(he.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:()=>{se(f.id),qe(!1)},className:le("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",U===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(qr).map(f=>{const N=$===f;return n.jsx("button",{type:"button",onClick:()=>{X(f),qe(!1)},className:le("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:qr[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:()=>{J(f=>!f)},className:le("w-full rounded-lg border px-2.5 py-2 text-left text-caption transition-colors",P?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:P?"Hide 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:pt,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[ht.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(xi,{icon:"activity",headline:Z?"Syncing activity feed...":je?"No activity yet for this session":d?"No activity yet for this workstream":"No matching activity right now.",description:Z?"Live updates usually appear within a few seconds after dispatch.":`Try widening the time window (${vn}), 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:ft.map(f=>{const N=x===f.id;return n.jsx("button",{type:"button",onClick:()=>b==null?void 0:b(f.id),className:le("rounded-full border px-2.5 py-1 text-caption font-semibold transition-colors",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:[(je||d||g)&&n.jsx("button",{type:"button",onClick:()=>{je&&k(),d&&(m==null||m()),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 It("play",V),disabled:Oe!==null,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18 disabled:opacity-45",children:Oe==="play"?"Starting...":"Start next session"}),!V&&we&&n.jsx("button",{type:"button",onClick:we,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18",children:"Browse initiatives"})]}),Ge&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:Ge})]})}),n.jsx(Lp,{completedCount:en.completed,decisionsCount:en.decisions,blockerCount:en.blocked,visible:Jt,onDismiss:()=>{Gt(!1),dn.current=Date.now()}}),ht.length>0&&n.jsxs("div",{className:"space-y-4",children:[ys.map(f=>{const N=ie?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}),Ca?n.jsx(yt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:N.map((I,M)=>{const xe=Te.has(I.key),Ve=I.allItems.slice(1),it=Ve.length,vt=Math.min(it,C[I.key]??pr),gn=Ve.slice(0,vt);if(I.count===1)return $s(I.representative,M);const kt=`cluster:${I.key}`;return n.jsxs("div",{children:[$s(I.representative,M,kt),n.jsxs("button",{type:"button",onClick:xt=>{xt.stopPropagation(),Nn(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:xe?"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:le("transition-transform",xe?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),xe&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[gn.map((xt,Xt)=>$s(xt,M+Xt+1)),vt<it&&n.jsxs("button",{type:"button",onClick:xt=>{xt.stopPropagation(),bs(I.key,it)},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 (",it-vt," remaining)"]})]})]},I.key)})})}):n.jsx("div",{className:"space-y-2",children:N.map((I,M)=>{const xe=Te.has(I.key),Ve=I.allItems.slice(1),it=Ve.length,vt=Math.min(it,C[I.key]??pr),gn=Ve.slice(0,vt);if(I.count===1)return $s(I.representative,M);const kt=`cluster:${I.key}`;return n.jsxs("div",{children:[$s(I.representative,M,kt),n.jsxs("button",{type:"button",onClick:xt=>{xt.stopPropagation(),Nn(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:xe?"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:le("transition-transform",xe?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),xe&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[gn.map((xt,Xt)=>$s(xt,M+Xt+1)),vt<it&&n.jsxs("button",{type:"button",onClick:xt=>{xt.stopPropagation(),bs(I.key,it)},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 (",it-vt," remaining)"]})]})]},I.key)})}),ie&&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:Ht,className:"pointer-events-none h-px","aria-hidden":!0}),n.jsx("div",{className:le("flex items-center justify-center py-6 transition-opacity duration-500 ease-out",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&&ht.length>0&&!Bo(x)&&n.jsx("p",{className:"pb-4 text-center text-micro tracking-wide text-muted/50",children:bt>0?`${ht.length} of ${rs} events`:"You’ve reached the beginning"})]})]})]}),n.jsx(lf,{}),n.jsx(Fp,{open:E!==null,onClose:ct,children:E&&n.jsxs("div",{className:"relative flex h-[100dvh] w-full min-h-0 flex-col sm:h-[86vh] sm:max-h-[86vh]",children:[n.jsx("div",{className:"absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-lime/10 via-cyan/5 to-transparent"}),n.jsxs("div",{className:"relative z-10 flex items-center justify-between border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:{backgroundColor:Qi(E.userState),boxShadow:`0 0 12px ${Qi(E.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Xi(E.userState)," · ",Mt+1,"/",ht.length," sessions"]}),Ye&&n.jsx(Cn,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:Ye})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[E.runId&&H&&n.jsx("button",{type:"button",onClick:()=>{H(E.runId),ct()},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:()=>Pn(-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:()=>Pn(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:()=>Xe(f=>!f),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"More actions",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[n.jsx("circle",{cx:"12",cy:"5",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"19",r:"1.5"})]})}),Fe&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>Xe(!1)}),n.jsxs("div",{className:"absolute right-0 top-full z-40 mt-1 min-w-[160px] rounded-lg border border-strong bg-[#0d0f16] py-1 shadow-xl",children:[E.runId&&n.jsx("button",{type:"button",onClick:()=>{sn("Run id",E.runId??""),Xe(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-caption text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:"Copy run ID"}),Zs.agentId&&n.jsx("button",{type:"button",onClick:()=>{sn("Agent id",Zs.agentId??""),Xe(!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:()=>{sn("Event id",E.item.id),Xe(!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:ct,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:He,children:n.jsx(he.section,{custom:He,initial:{opacity:0,x:He*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:He*-32,scale:.985},transition:{duration:.28,ease:[.16,1,.3,1]},className:"min-h-full w-full overscroll-contain",children:n.jsxs("div",{className:"space-y-6 pb-1",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-title font-semibold tracking-[-0.02em] text-white whitespace-pre-wrap break-words",children:Pe||Qo(E.item,ge)||dt(E.item.title||ui(E.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(E.item.timestamp).toLocaleString()," · ",_t(E.item.timestamp),Q==="llm"&&n.jsx("span",{className:"text-muted",children:"· AI title"})]}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-caption",children:[(()=>{const f=wt(E.item),N=(te==null?void 0:te.workstreamId)??fr(E.item)??(E.runId?Ln.get(E.runId)??null:null),I=Vr([{value:(te==null?void 0:te.workstreamTitle)??null,idHint:N},{value:st(f,["workstream_title","workstreamTitle"]),idHint:N},{value:N?nn.get(N)??null:null,idHint:N},{value:E.runId?Dt.get(E.runId)??null:null,idHint:N}]),xe=[Vr([{value:(te==null?void 0:te.initiativeTitle)??null,idHint:E.item.initiativeId},{value:st(f,["initiative_title","initiativeTitle"]),idHint:E.item.initiativeId},{value:E.item.initiativeId?ss.get(E.item.initiativeId)??null:null,idHint:E.item.initiativeId}]),I].filter(Boolean).join(" > ");return xe?n.jsx(Cn,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:xe})}):null})(),n.jsx(Cn,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:Xi(E.userState)}),n.jsxs(Cn,{tone:"muted",children:[n.jsx(Bt,{name:(Fn==null?void 0:Fn.label)??(We==null?void 0:We.primaryLabel)??"OrgX",hint:Fn?Ki(Fn):(We==null?void 0:We.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(Fn==null?void 0:Fn.label)??(We==null?void 0:We.primaryLabel)??"OrgX"})]}),Ue&&n.jsx(Cn,{tone:"lime",children:"Sync replay"})]})]}),n.jsx(Bp,{item:E.item}),Vn&&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:Vn.source==="metadata"?"Artifact":dt(Vn.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:()=>lt("structured"),"aria-pressed":ot==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${ot==="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:()=>lt("json"),"aria-pressed":ot==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${ot==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),hn&&n.jsx("button",{type:"button",onClick:()=>ne(hn),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:ot==="structured"?Ul(Vn.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(Vn.value,null,2)})})})]}),Tt&&n.jsxs("div",{className:le("rounded-xl border px-3.5 py-3",Tt.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",Tt.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",Tt.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",Tt.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:Tt.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:Tt.summary}),Tt.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:Tt.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[E.runId&&H&&n.jsx("button",{type:"button",onClick:()=>{H(E.runId),ct()},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"}),bi&&n.jsx("button",{type:"button",onClick:()=>{oe==null||oe(Ds[0]??null),ct()},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:Ds.length>0?"Resolve decision":"Resolve decisions"}),hn&&!Vn&&n.jsx("button",{type:"button",onClick:()=>ne(hn),className:"rounded-full border border-cyan-300/25 bg-cyan-500/[0.1] px-3 py-1 text-caption font-semibold text-cyan-100 transition hover:bg-cyan-500/[0.16]",children:"Open artifact"}),_e&&n.jsx("a",{href:_e,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-semibold text-primary transition hover:bg-white/[0.1]",children:"Review evidence"}),Be&&n.jsx("button",{type:"button",onClick:()=>void _r(),disabled:ze,className:le("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",Be.isBlockedFlow?"border-amber-300/30 bg-amber-500/[0.12] text-amber-100 hover:bg-amber-500/[0.18]":"border-lime/30 bg-lime/[0.12] text-[#D8FFA1] hover:bg-lime/[0.18]"),children:ze?"Scheduling...":Be.actionLabel})]}),Be&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:Ze??Be.helperText})]}),gt&&n.jsxs("div",{className:"mt-3 rounded-xl border border-amber-300/26 bg-amber-500/[0.08] px-3.5 py-3",children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-amber-100/85",children:"Spawn guard"}),n.jsx(Cn,{tone:gt.isRateLimited?"muted":"red",children:gt.isRateLimited?"Rate limited":"Blocked"})]}),n.jsx("p",{className:"mt-1 text-caption text-amber-100/80",children:"Dispatch was stopped before launch. Adjust limits or retry after the window resets."}),n.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Domain window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:gt.domainCurrent!==null&>.domainMax!==null?`${gt.domainCurrent}/${gt.domainMax} per hour`:"Not provided"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:"Global window"}),n.jsx("div",{className:"mt-1 text-body font-semibold tabular-nums text-primary",children:gt.totalCurrent!==null&>.totalMax!==null?`${gt.totalCurrent}/${gt.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[gt.domain&&n.jsxs(Cn,{tone:"muted",children:["Domain: ",dt(gt.domain)]}),gt.modelTier&&n.jsxs(Cn,{tone:"muted",children:["Tier: ",dt(gt.modelTier)]}),Kn&&n.jsxs(Cn,{tone:"muted",children:["Retry: ",Kn]}),!Kn&>.retryInMs!==null&&n.jsxs(Cn,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(gt.retryInMs/1e3)),"s"]})]}),gt.blockedReason&&n.jsx("p",{className:"mt-2 rounded-lg border border-white/[0.10] bg-black/20 px-3 py-2 text-caption text-primary",children:Et(gt.blockedReason)??gt.blockedReason}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[W&&n.jsx("button",{type:"button",onClick:W,className:"rounded-full border border-amber-300/32 bg-amber-500/[0.14] px-3 py-1 text-caption font-semibold text-amber-100 transition hover:bg-amber-500/[0.2]",children:"Edit limits"}),Be&&n.jsx("button",{type:"button",onClick:()=>void _r(),disabled:ze,className:"rounded-full border border-lime/30 bg-lime/[0.12] px-3 py-1 text-caption font-semibold text-[#D8FFA1] transition hover:bg-lime/[0.18] disabled:opacity-50",children:ze?"Scheduling...":"Retry now"})]})]}),Sr.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:Sr.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))})]}),We&&!te&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Delegation"}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-body text-secondary",children:[n.jsx("span",{className:"flex items-center gap-1.5",children:We.requester?n.jsxs(n.Fragment,{children:[n.jsx(Bt,{name:We.requester.label,hint:Ki(We.requester),size:"xs"}),n.jsx("span",{className:"text-primary",children:We.requester.label})]}):n.jsx("span",{children:xr("System / unknown")})}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"text-primary",children:We.mode==="handoff"?"Delegated handoff":We.mode==="requested"?"Dispatch requested":We.mode==="single"?"Direct execution":"System event"}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"flex items-center gap-1.5",children:We.executor?n.jsxs(n.Fragment,{children:[n.jsx(Bt,{name:We.executor.label,hint:Ki(We.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:We.executor.label})]}):n.jsx("span",{children:xr("Not assigned")})})]}),We.subtitle&&n.jsx("p",{className:"mt-1 text-caption text-muted",children:We.subtitle})]}),te&&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:sr(te.event)??dt(te.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:ks?"Terminal state":"Progress"}),n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:Js},children:ks?(Tt==null?void 0:Tt.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:Js}})}),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(Bt,{name:is.primary,hint:is.secondary??is.primary,size:"xs"}),n.jsx("span",{children:is.primary})]}),is.secondary&&n.jsxs("p",{className:"mt-0.5 text-micro text-muted",children:["via ",is.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(Bt,{name:Qs,hint:Qs,size:"xs"}),n.jsx("span",{children:Qs})]})]}),te.dispatcherClient&&te.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:dt(te.dispatcherClient)})]}),(te.domain||te.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:[te.domain??"",te.requiredSkills.length>0?`${te.domain?" · ":""}${te.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?cs(L.initiativeId):"—")})]}),L.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:dt(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??cs(L.workstreamId)})]}),L.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:dt(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:sr(L.phase)??dt(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:sr(L.parsedStatus)??dt(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:sr(L.stopReason)??dt(L.stopReason)})]})]})]}),te.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:te.error})]}),nt&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Summary"}),Ae==="missing"&&!Ue&&n.jsx("p",{className:"mb-1 text-caption text-amber-200/75",children:"Full local turn transcript was unavailable; showing the event summary payload."}),n.jsx(li,{mode:"block",text:nt,className:"text-body leading-relaxed text-primary"})]}),Et(E.item.description)&&Et(E.item.description)!==nt&&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(li,{mode:"block",text:Et(E.item.description)??"",className:"text-body leading-relaxed text-secondary"})]}),Hn&&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:Hn.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:Hn.dispatch})]}),Hn.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:Hn.highlights.slice(0,3).map((f,N)=>n.jsx("li",{children:f},`${Hn.sliceRunId}:highlight:${N}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:Hn.outcome.summary})]})]})]}),F.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:[F.length," ",F.length===1?"file":"files"," captured for this run."]}),n.jsxs("div",{className:"space-y-2",children:[S.map((f,N)=>{const I=Ji(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:dt(f.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:_s(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 sn(`${dt(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}`)}),G.length>0&&n.jsxs("details",{className:"group rounded-lg border border-white/[0.08] bg-black/15 px-2.5 py-2",children:[n.jsxs("summary",{className:"cursor-pointer list-none text-caption font-semibold text-secondary",children:["View ",G.length," additional evidence file",G.length===1?"":"s"]}),n.jsx("div",{className:"mt-2 space-y-2",children:G.map((f,N)=>{const I=Ji(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:dt(f.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:_s(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 sn(`${dt(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}`)})})]})]})]}),E&&Gi(E.item)&&!Vn&&n.jsxs("button",{type:"button",onClick:()=>{const f=Gi(E.item);f&&ne(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"})]}),(tt||(te==null?void 0:te.logPath)||p)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),(tt||(te==null?void 0:te.logPath)||(te==null?void 0:te.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:[tt&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[tt.domain&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Domain"}),n.jsx("div",{className:"mt-0.5 text-primary",children:dt(tt.domain)})]}),(tt.provider||tt.model)&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model"}),n.jsxs("div",{className:"mt-0.5 text-primary",children:[tt.provider?`${dt(tt.provider)} · `:"",tt.model?wr(tt.model):"—"]})]}),tt.modelTier&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model tier"}),n.jsx("div",{className:"mt-0.5 text-primary",children:dt(tt.modelTier)})]}),tt.pluginVersion&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Plugin"}),n.jsxs("div",{className:"mt-0.5 text-primary",children:["v",tt.pluginVersion]})]})]}),(tt==null?void 0:tt.skillPack)&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-1",children:[n.jsx("span",{className:"text-micro text-muted",children:"Skill pack"}),n.jsxs("span",{className:"text-primary",children:[tt.skillPack.name??"—",tt.skillPack.version?`@${tt.skillPack.version}`:"",tt.skillPack.source?` · ${tt.skillPack.source}`:""]}),tt.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var f;return void sn("Skill pack checksum",((f=tt.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 ",tt.skillPack.checksum.slice(0,12)]})]}),tt&&tt.requiredSkills.length>0&&n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-1",children:[n.jsx("span",{className:"text-micro text-muted",children:"Skills"}),tt.requiredSkills.map(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))]}),(tt==null?void 0:tt.kickoffContextHash)&&n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-micro text-muted",children:"Kickoff context"})," ",n.jsxs("span",{className:"font-mono text-muted",children:[tt.kickoffContextSource?`${tt.kickoffContextSource} · `:"",tt.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void sn("Kickoff context hash",tt.kickoffContextHash??""),className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),((te==null?void 0:te.logPath)||(te==null?void 0:te.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(te==null?void 0:te.logPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["log: ",_s(te.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void sn("Log path",(te==null?void 0:te.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"})]}),(te==null?void 0:te.outputPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["output: ",_s(te.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void sn("Output path",(te==null?void 0:te.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: ",cs(L.initiativeId)]}),(L==null?void 0:L.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",cs(L.workstreamId)]})]})]})]}),p&&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:p})]})]})},E.item.id)})}),n.jsx("div",{className:"border-t border-subtle px-5 py-2.5 text-caption text-muted sm:px-6",children:"Keyboard: ← previous · → next · Esc close"})]})})]})})}),Vf=o.lazy(async()=>({default:(await Ut(()=>import("./D9esz7jd.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]))).MissionControlView})),Kf=o.lazy(async()=>({default:(await Ut(()=>import("./DJASCd69.js"),__vite__mapDeps([11,1,2,3,4,12,7]))).SessionInspector})),Gf=o.lazy(async()=>({default:(await Ut(()=>import("./Dm9AybAp.js"),__vite__mapDeps([13,1,2,3,4,9,7,12]))).DecisionQueue})),Xf=o.lazy(()=>Ut(()=>import("./CL_wXqR7.js"),__vite__mapDeps([14,1,2,3,4,7])).then(e=>({default:e.TriageQueue}))),Qf=o.lazy(()=>Ut(()=>import("./BTAEErUY.js"),__vite__mapDeps([15,1,2,3,4,7])).then(e=>({default:e.TriageDetailModal}))),Jf=o.lazy(async()=>({default:(await Ut(()=>import("./Ck2agw-s.js").then(t=>t.a),__vite__mapDeps([5,1,2,3,4,6,7]))).NextUpPanel})),Yf=o.lazy(async()=>({default:(await Ut(()=>import("./BerAfzjq.js"),__vite__mapDeps([16,1,2,3,4,7,10]))).SettingsModal})),Zf=o.lazy(async()=>({default:(await Ut(()=>import("./Du1wfrXa.js"),__vite__mapDeps([17,1,2,3,4,7]))).BulkSessionsModal})),eh=o.lazy(async()=>({default:(await Ut(()=>import("./BG5mwTkg.js"),__vite__mapDeps([18,1,2,3,4,13,9,7,12]))).BulkDecisionsModal})),th=o.lazy(async()=>({default:(await Ut(()=>import("./D2CH1H6k.js"),__vite__mapDeps([19,1,2,3,4,7]))).BulkOutboxModal})),nh=o.lazy(async()=>({default:(await Ut(()=>import("./beHYBbh6.js"),__vite__mapDeps([20,1,2,3,4,7]))).BulkHandoffsModal})),sh=o.lazy(async()=>({default:(await Ut(()=>import("./BepW_590.js"),__vite__mapDeps([21,1,2,3,4,6,7]))).ArtifactViewerModal})),rh=o.lazy(async()=>({default:(await Ut(()=>import("./BNh-XYPV.js"),__vite__mapDeps([22,1,2,3,4,9,7,8]))).SliceDetailModal})),ih=o.lazy(async()=>({default:(await Ut(()=>import("./CdvjC9G9.js"),__vite__mapDeps([23,1,2,3,4,7]))).RealtimeOrchestratorModal})),Jo={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},ah={connected:D.lime,reconnecting:D.amber,disconnected:D.red},ea="orgx.demo_mode",ta="orgx.dev_mode",na="orgx.show_synthetic_entities",ha="orgx.selected_workspace_id",Yo={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},Zo=new Set(["running","active","queued","pending","in_progress","working","planning"]),oh=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function cn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function lh(e){const t=cn(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function ch(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 dh(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=Rt(e);return{title:"Live stream degraded",message:ch(s),action:"settings"}}function sa(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 uh(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 el(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function tl(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 ra(e,t){const s=Yo[e.status]??99,r=Yo[t.status]??99;return s!==r?s-r:cn(e.updatedAt??e.lastEventAt??e.startedAt)-cn(t.updatedAt??t.lastEventAt??t.startedAt)}function nl(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 mh(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 ph(e){if(Es(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function fh(e){if(Es(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function hh(e){const t=e.metadata;return t!=null&&typeof t=="object"&&t.mock===!0}function gh(e){return oh.test(e)}function Kr(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 xh(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function yh(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function bh(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 wh(e,t){fs(e,t)}function vh(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 kh(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=bh(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(ha);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function jh(){const e=Nd();return e.showGate?n.jsx(vu,{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(Nm,{children:n.jsx(_h,{onboarding:e})})}function Nh(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 Ih(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 sl(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 rl(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Ah(){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:hi,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function Sh(){const{state:e}=Cl();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(sh,{})}):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(ea)==="1"}catch{return!1}}),[r,i]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(na)==="1"}catch{return!1}}),[a,l]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(ta)==="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(()=>kh()),x=o.useCallback(p=>{d(p);try{localStorage.setItem("orgx-dashboard-view",p)}catch{}},[]),{data:b=[]}=ps({queryKey:["workspace-options",t?"demo":"live"],queryFn:async()=>{if(t)return[];const p=await fetch("/orgx/api/entities?type=command_center&limit=50");if(!p.ok)return[];const A=await p.json().catch(()=>null),F=Array.isArray(A==null?void 0:A.data)?A.data:[],S=[];for(const G of F){if(!G||typeof G!="object"||Array.isArray(G))continue;const _e=Kr(G,["id"]);if(!_e)continue;const nt=Kr(G,["status","priority"]);if(!xh(nt))continue;const Ue=Kr(G,["title","name"])??(_e.length>10?`${_e.slice(0,8)}…`:_e),Be=G.is_default===!0,ct=yh({title:Ue,isDefault:Be}),It=Kr(G,["created_at"]);S.push({id:_e,title:ct,status:nt,isDefault:Be,createdAt:It})}return S.sort((G,_e)=>{if(G.isDefault!==_e.isDefault)return G.isDefault?-1:1;const nt=cn(G.createdAt)-cn(_e.createdAt);return nt!==0?nt:G.title.localeCompare(_e.title)}),S},staleTime:6e4}),h=o.useMemo(()=>{var p;return u?((p=b.find(A=>A.id===u))==null?void 0:p.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,b]),v=o.useMemo(()=>!u||b.some(p=>p.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(p=>p.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:m,approveDecision:_,rejectDecision:H,approveAllDecisions:oe,bulkDecisionAction:K,decisionMutation:be}=Yc({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...y}),V=t||r,Y=o.useMemo(()=>V?j.sessions.nodes:j.sessions.nodes.filter(p=>!ph(p)),[j.sessions.nodes,V]),ce=o.useMemo(()=>j.activity.filter(p=>!(!V&&fh(p)||!a&&hh(p))),[j.activity,V,a]),ye=j.connection==="connected"||j.decisions.length>0,[we,W]=o.useState(null),[Ie,Ee]=o.useState(!1),[fe,Z]=o.useState(null),[de,Re]=o.useState(null),[ne,$]=o.useState(null),[X,P]=o.useState(null),[J,ie]=o.useState("live"),[ve,ke]=o.useState({startIso:null,endIso:null}),ee=o.useRef(new Set),[Te,pe]=o.useState(null),[C,O]=o.useState(null),[U,se]=o.useState(null),[Le,qe]=o.useState(null),Me=o.useRef(null),T=o.useCallback(p=>{Me.current&&clearTimeout(Me.current),qe(p),Me.current=setTimeout(()=>qe(null),4e3)},[]),[q,re]=o.useState(!1),[ue,Ce]=o.useState(!1),[Ye,Je]=o.useState([]),Fe=o.useRef(null),Xe=o.useRef(null),[He,mt]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[ot,lt]=o.useState(!1),[ge,Ke]=o.useState(null),[Ae,B]=o.useState("agents"),[Pe,z]=o.useState("initiatives"),[Q,Ne]=o.useState("next_up"),De=o.useCallback(p=>{if(B(p),p==="initiatives"){z("initiatives"),Ne("next_up");return}p==="decisions"&&(z("initiatives"),Ne("in_progress"),Oe("needs_attention"))},[]),[$e,Oe]=o.useState("all"),Se=o.useMemo(()=>Array.isArray(j.sliceRuns)?j.sliceRuns:[],[j.sliceRuns]),rt=o.useMemo(()=>Il({sessions:Y,sliceRuns:Se}),[Se,Y]).length,ze=o.useMemo(()=>Al(Se),[Se]),Ct=ze.length+(ye?j.decisions.length:0),[Ze,jt]=o.useState(null),Jt=o.useCallback(p=>{const A=Se.find(F=>F.initiativeId===p.initiativeId&&F.workstreamId===p.workstreamId)??null;jt({source:"queue",item:p,linkedSliceRun:A})},[Se]),Gt=o.useCallback((p,A)=>{jt({source:"in_progress",row:p,sliceRun:A})},[]),dn=o.useCallback(p=>{jt({source:"needs_input",sliceRun:p})},[]),En=o.useCallback(async(p,A)=>{T("Slice accepted and marked complete."),m()},[m,T]),hs=o.useCallback(async(p,A)=>{T("Changes requested — feedback posted.")},[T]),pt=Ud({projectId:u,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:j.snapshotVersion}),Ht=Vd({authToken:null,embedMode:!1}),{model:wn,actions:Lt}=Xd({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),Nt=o.useMemo(()=>wn.items.filter(p=>p.kind==="failure_diagnostic"),[wn.items]),Wt=o.useMemo(()=>({...wn,items:Nt,total:Nt.length}),[Nt,wn]),[Vt,Ot]=o.useState(null),[un,Zn]=o.useState(0),mn=o.useCallback(p=>{Ot(p);const A=Nt.findIndex(F=>F.id===p.id);Zn(A>=0?A:0)},[Nt]),Rn=o.useCallback(p=>{if(Nt.length===0)return;const A=(un+p+Nt.length)%Nt.length;Zn(A),Ot(Nt[A]??null)},[un,Nt]),gs=pt,vn=o.useMemo(()=>pt.items.find(p=>p.autoIntentEnabled===!0&&(p.autoRuntimeState==="running"||p.autoRuntimeState==="stopping"))??null,[pt.items]),en=!!vn;o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(ea,"1"):window.localStorage.removeItem(ea)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{r?window.localStorage.setItem(na,"1"):window.localStorage.removeItem(na)}catch{}},[r]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(ta,"1"):window.localStorage.removeItem(ta)}catch{}},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(ha,u):window.localStorage.removeItem(ha)}catch{}try{const p=new URL(window.location.href);u?wh(p.searchParams,u):vh(p.searchParams),p.searchParams.delete("initiative"),p.searchParams.delete("initiative_id"),p.searchParams.delete("project"),window.history.replaceState(null,"",`${p.pathname}${p.search}${p.hash}`)}catch{}}},[u]);const Kt=o.useCallback((p,A)=>{mt(F=>({open:!0,tab:p??F.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),es=o.useCallback(p=>{if(s(p),!(typeof window>"u"))try{const A=new URL(window.location.href);p?A.searchParams.set("demo","1"):A.searchParams.delete("demo"),window.history.replaceState(null,"",`${A.pathname}${A.search}${A.hash}`)}catch{}},[]),kn=o.useCallback(()=>{Kt("orgx")},[Kt]),ts=o.useCallback(()=>{Ut(()=>import("./D9esz7jd.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]))},[]),{data:ns}=Sl(c==="mission-control",u),{data:tn}=jm(c==="mission-control",u),{data:Ln=[]}=ps({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[Dt,ss]=o.useState(null),[nn,pn]=o.useState(""),[jn,R]=o.useState(!1),me=o.useCallback((p,A)=>{ss({type:p,initiativeId:A}),pn(""),R(!1)},[]),ae=o.useCallback(()=>{ss(null),pn(""),R(!1)},[]),je=o.useCallback(()=>{Re(null)},[]),ft=o.useCallback(()=>{$(null),P(null)},[]),Qe=o.useCallback(()=>{se(null)},[]);o.useEffect(()=>{var F;const p=((F=Y[0])==null?void 0:F.id)??null;if(!p){we!==null&&W(null);return}if(we===null){W(p);return}Y.some(S=>S.id===we)||W(p)},[Y,we]),o.useEffect(()=>{if(!de)return;Y.some(A=>A.id===de)||Re(null)},[de,Y]);const et=o.useCallback(p=>{Ut(()=>import("./DJASCd69.js"),__vite__mapDeps([11,1,2,3,4,12,7])),W(p),Ee(!0),Z(null),Re(p),$(null),P(null)},[]),xs=o.useCallback(p=>{Ut(()=>import("./DJASCd69.js"),__vite__mapDeps([11,1,2,3,4,12,7])),W(p.id),Ee(!0),Re(p.id),$(p.workstreamId??null),P(p.title),Z({workstreamId:p.workstreamId??null,text:`Intervention requested for "${p.title}". `}),T(`Opened intervention composer for ${p.title}.`)},[]),ht=o.useCallback(p=>{const A=p.trim();if(!A)return;const F=Y.find(S=>S.runId===A||S.id===A)??null;F&&(et(F.id),T(`Focused session: ${F.title}`))},[Y,et]),rs=o.useCallback(p=>{var S;const A=(S=p.id)==null?void 0:S.trim();if(!A)return;const F=sa(p);if(F){const G=Y.find(_e=>_e.runId===F||_e.id===F)??null;G&&(W(G.id),Re(G.id))}x("activity"),B("activity"),Ee(!1),pe(A),T("Opened activity detail from session timeline.")},[Y,x]),bt=o.useMemo(()=>Y.find(p=>p.id===de)??null,[de,Y]),fn=o.useMemo(()=>{var F,S;const p=((F=bt==null?void 0:bt.runId)==null?void 0:F.trim())??"",A=((S=bt==null?void 0:bt.id)==null?void 0:S.trim())??"";return!p||!A?[]:p===A?[p]:[p,A]},[bt==null?void 0:bt.id,bt==null?void 0:bt.runId]),Wn=o.useMemo(()=>{const p=new Set;for(const A of fn){const F=A.trim();F.length>0&&p.add(F)}return p},[fn]),ys=o.useMemo(()=>{const p=new Map;for(const A of Y){const F=A.workstreamId??null;A.runId&&p.set(A.runId,F),A.id&&p.set(A.id,F)}return p},[Y]),Nn=o.useMemo(()=>{const p=fn.length>0?fn.join("|"):"*",A=(ne==null?void 0:ne.trim())||"*",F=(U==null?void 0:U.trim())||"*";return`${p}::${A}::${F}`},[ne,U,fn]),bs=o.useCallback(p=>{ee.current.add(Nn),ie(p)},[Nn]);o.useEffect(()=>{if(ee.current.has(Nn)||w)return;const p=Date.now(),A=ce.filter(G=>{const _e=sa(G);if(Wn.size>0&&(!_e||!Wn.has(_e)))return!1;if(ne){const nt=el(G);if((tl(nt,["workstreamId","workstream_id"])??(_e?ys.get(_e)??null:null))!==ne)return!1}if(U){const nt=el(G);if((tl(nt,["agentName","agent_name"])??G.agentName)!==U)return!1}return!0});if(A.length===0)return;const S=["live","24h","7d","all"].find(G=>{const _e=jr(G,p);return A.some(nt=>{const Ue=cn(nt.timestamp);return Ue?_e===null||Ue>=_e:!1})})??"all";ee.current.add(Nn),S!==J&&ie(S)},[ne,ce,Nn,J,ys,U,w,Wn]);const Un=cd({seed:ce,timeFilterId:J,customSinceIso:J==="custom"?ve.startIso:null,customUntilIso:J==="custom"?ve.endIso:null,runId:(bt==null?void 0:bt.runId)??null,projectId:u,pageSize:50,demoMode:t}),St=o.useMemo(()=>Y.find(p=>p.id===we)??null,[Y,we]),In=o.useMemo(()=>Y.filter(p=>Zo.has(p.status)).length,[Y]),An=o.useMemo(()=>Se.length>0?ze.length:Y.filter(p=>{const A=zt(p.status),F=zt(p.phase??""),S=zt(p.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||F==="blocked"||S==="error"?!0:Zo.has(A)||A==="handoff"||A==="review"?!1:p.blockers.length>0}).length,[Se.length,ze.length,Y]);o.useMemo(()=>Y.filter(p=>p.status==="failed").length,[Y]);const ws=o.useMemo(()=>Y.filter(p=>p.status==="completed").length,[Y]);o.useMemo(()=>{const p=(ye?j.decisions.length:0)+An;return[{id:"active",label:"Running",value:In,color:In>0?D.lime:D.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:p,color:p>0?D.amber:D.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:ws,color:D.teal,icon:"session"}]},[In,An,ws,j.decisions.length,Y,ye]),o.useMemo(()=>j.decisions.length>0?Math.max(0,...j.decisions.map(p=>p.waitingMinutes)):0,[j.decisions]);const Dn=o.useMemo(()=>k?dh(k):null,[k]),Sn=o.useMemo(()=>{const p=[];if(Dn){const A=Dn.action==="refresh"&&typeof m=="function";p.push({id:`stream-error:${k}`,kind:"error",icon:"notification",title:Dn.title,message:Dn.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void m():()=>Kt("orgx")})}return j.connection!=="connected"&&p.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:kn}),Le&&p.push({id:`ops:${Le}`,kind:"info",icon:/decision/i.test(Le)?"decision":"workstream",title:"Update",message:Le}),p},[j.connection,j.outbox.lastReplayError,j.outbox.pendingTotal,j.outbox.replayStatus,k,Dn,kn,m,Kt,Le]);o.useEffect(()=>{const p=new Set(Sn.map(A=>A.id));Je(A=>A.filter(F=>p.has(F)))},[Sn]);const vs=o.useMemo(()=>Sn.filter(p=>!Ye.includes(p.id)),[Ye,Sn]),Rs=ye?j.decisions.length:0,Nr=In+An+Rs,Ir=o.useCallback(p=>{Je(A=>A.includes(p)?A:A.concat(p))},[]),Gs=o.useCallback(()=>{Je(Sn.map(p=>p.id))},[Sn]);o.useEffect(()=>{if(!ue)return;const p=F=>{var G,_e;const S=F.target;S&&((G=Xe.current)!=null&&G.contains(S)||(_e=Fe.current)!=null&&_e.contains(S)||Ce(!1))},A=F=>{F.key==="Escape"&&Ce(!1)};return document.addEventListener("mousedown",p),document.addEventListener("touchstart",p),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",p),document.removeEventListener("touchstart",p),document.removeEventListener("keydown",A)}},[ue]);const Mt=o.useMemo(()=>{var F;const p=new Map;for(const S of Y){const G=S.initiativeId??S.groupId??"unscoped",_e=S.groupLabel&&S.groupLabel.trim().length>0?S.groupLabel:S.initiativeId??"Unscoped Initiative",nt=Nh(_e),Ue=p.get(G)??{id:G,name:_e,category:nt,progressTotal:0,progressCount:0,statusCounts:{},activeAgents:new Set,allAgents:new Set,workstreams:new Map,latestEpoch:0};if(S.progress!==null&&(Ue.progressTotal+=S.progress,Ue.progressCount+=1),Ue.statusCounts[S.status]=(Ue.statusCounts[S.status]??0)+1,S.agentName&&(Ue.allAgents.add(S.agentName),["running","queued","pending","blocked"].includes(S.status)&&Ue.activeAgents.add(S.agentName)),S.workstreamId){const Be=j.sessions.groups.find(It=>It.id===S.workstreamId),ct=((F=Be==null?void 0:Be.label)==null?void 0:F.trim())||S.workstreamId;Ue.workstreams.set(S.workstreamId,ct)}Ue.latestEpoch=Math.max(Ue.latestEpoch,cn(S.updatedAt??S.lastEventAt??S.startedAt)),p.set(G,Ue)}const A=[];for(const S of p.values()){const G=S.progressCount>0?Math.round(S.progressTotal/S.progressCount):S.statusCounts.completed?100:S.statusCounts.running?55:0,_e=S.category,nt=Ih(_e),Ue=Math.round(Math.max(0,Math.min(100,G))/100*(nt.length-1)),Be=(S.statusCounts.blocked??0)>0,ct=(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,It=!ct&&!Be&&(S.statusCounts.paused??0)>0&&(S.statusCounts.running??0)===0&&(S.statusCounts.queued??0)===0&&(S.statusCounts.pending??0)===0,_r=nt.map((sn,Pn)=>{let as="upcoming";return(ct||Pn<Ue)&&(as="completed"),Pn===Ue&&!ct&&(as=Be?"warning":"current"),{name:sn,status:as}});A.push({id:S.id,name:S.name,status:ct?"completed":Be?"blocked":It?"paused":"active",rawStatus:ct?"completed":Be?"blocked":It?"paused":"active",category:_e,health:Math.max(0,Math.min(100,G)),phases:_r,currentPhase:ct?nt.length-1:Ue,daysRemaining:0,targetDate:null,createdAt:S.latestEpoch>0?new Date(S.latestEpoch).toISOString():null,updatedAt:S.latestEpoch>0?new Date(S.latestEpoch).toISOString():null,activeAgents:S.activeAgents.size,totalAgents:S.allAgents.size,avatars:Array.from(S.activeAgents).slice(0,3),description:`${S.workstreams.size} workstreams are active right now.`,workstreams:Array.from(S.workstreams.entries()).map(([sn,Pn])=>({id:sn,name:Pn,status:"active"}))})}return A.sort((S,G)=>{const _e=S.status==="blocked"?0:S.status==="active"?1:2,nt=G.status==="blocked"?0:G.status==="active"?1:2;return _e!==nt?_e-nt:G.health-S.health})},[Y,j.sessions.groups]),E=o.useMemo(()=>{const p=(S,G)=>{var _e,nt;return{...S,...G,health:G.health>0?G.health:S.health,activeAgents:Math.max(S.activeAgents,G.activeAgents),totalAgents:Math.max(S.totalAgents,G.totalAgents),avatars:(_e=S.avatars)!=null&&_e.length?S.avatars:G.avatars,workstreams:(nt=S.workstreams)!=null&&nt.length?S.workstreams:G.workstreams,description:S.description??G.description,rawStatus:G.rawStatus??S.rawStatus??null,targetDate:G.targetDate??S.targetDate??null,createdAt:G.createdAt??S.createdAt??null,updatedAt:G.updatedAt??S.updatedAt??null}},A=new Map;for(const S of Mt)A.set(S.id,S);for(const S of[...tn??[],...ns??[]]){if(!V&&Es(S.id)){A.delete(S.id);continue}const G=S.rawStatus??S.status;if(!rl(G)){A.delete(S.id);continue}const _e=A.get(S.id);A.set(S.id,_e?p(_e,S):S)}const F=new Set(Ln);return Array.from(A.values()).filter(S=>!F.has(S.id)).filter(S=>rl(S.rawStatus??S.status)).sort((S,G)=>{const _e=It=>It==="blocked"?0:It==="active"?1:It==="paused"?2:3,nt=_e(S.status)-_e(G.status);if(nt!==0)return nt;const Ue=sl(S.priority)-sl(G.priority);if(Ue!==0)return Ue;const Be=cn(G.updatedAt)-cn(S.updatedAt);if(Be!==0)return Be;const ct=G.health-S.health;return ct!==0?ct:S.name.localeCompare(G.name)})},[Mt,ns,V,tn,Ln]),Ar=o.useMemo(()=>{if(!bt)return null;const p=bt.agentName,A=bt.title;if(p){const F=ce.find(S=>{var G;return S.runId===bt.runId&&((G=S.summary)==null?void 0:G.trim())});if(F!=null&&F.summary){const S=F.summary.trim().length>40?F.summary.trim().slice(0,40)+"…":F.summary.trim();return`${p}: ${S}`}return p}if(A){const F=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(F.length>0)return F}return A??null},[ce,bt]),Hn=o.useMemo(()=>{const p=new Map;for(const A of Y){const F=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,S=(A.agentName??"").trim()||(A.agentId??"").trim();if(!S)continue;const G=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),_e=cn(G),nt=_e?Math.max(0,Math.floor((Date.now()-_e)/6e4)):0,Ue=p.get(F),Be={id:F,name:S,role:"Agent",status:mh(A.status),task:A.title??null,progress:A.progress??null,lastActive:G,lastActiveMinutes:nt};(!Ue||cn(Be.lastActive)>cn(Ue.lastActive))&&p.set(F,Be)}return Array.from(p.values())},[Y]),Vn=o.useCallback(async()=>{if(Y.length===0){T("No sessions available to continue.");return}const p=[...Y].sort(ra)[0];if(W(p.id),Re(p.id),$(null),P(null),["blocked","pending","queued"].includes(p.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})})}catch{}T(`Focused highest priority session: ${p.title}`),await m()},[Y,m]),hn=o.useCallback(async(p,A)=>{const F=await p.json().catch(()=>null),S=typeof(F==null?void 0:F.error)=="string"&&F.error.trim()||typeof(F==null?void 0:F.message)=="string"&&F.message.trim()||`${A} (${p.status})`;return/unknown api endpoint/i.test(S)?`${A}. This route is unavailable in the running plugin build.`:Rt(S)},[]),$n=o.useCallback((p,A)=>!p||p.trim().length===0?A:Rt(p.trim())||A,[]),Ls=o.useCallback(async()=>{const p=nl(pt.items);if(!p){T("No startable Next Up workstream is available."),x("mission-control");return}await pt.playWorkstream({initiativeId:p.initiativeId,workstreamId:p.workstreamId,agentId:p.runnerAgentId}),Re(null),$(p.workstreamId),P(p.workstreamTitle),se(null),T(`Dispatched Next Up: ${p.workstreamTitle}`),await Promise.all([pt.refetch(),m()])},[m,pt,x]),We=o.useCallback(async()=>{const p=nl(pt.items);if(!p){T("No startable initiative is ready for Autopilot yet."),x("mission-control");return}await Ht.move({initiativeId:p.initiativeId,workstreamId:p.workstreamId,placement:"top"}),await pt.startWorkstreamAutoContinue({initiativeId:p.initiativeId,workstreamId:p.workstreamId,agentId:p.runnerAgentId,scope:"initiative"}),Re(null),$(p.workstreamId),P(p.workstreamTitle),se(null),T(`Autopilot started for ${p.initiativeTitle}; queued from ${p.workstreamTitle}.`),await Promise.all([pt.refetch(),m()])},[m,Ht,pt,x]),Fn=o.useCallback(async()=>{re(!0);try{if(!vn){await We();return}await pt.stopInitiativeAutoContinue({initiativeId:vn.initiativeId}),T(`Autopilot stopped for ${vn.initiativeTitle}.`),await Promise.all([pt.refetch(),m()])}finally{re(!1)}},[vn,m,pt,We]),te=o.useCallback(async p=>{const A=(p.initiativeId??"").trim(),F=(p.workstreamId??"").trim();if(!A||!F)throw new Error("Missing initiative/workstream metadata for this session.");const S=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:F,agentId:p.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok)throw new Error(await hn(S,"Failed to dispatch workstream from In Progress"));Re(null),$(F),P(p.title),T(`Dispatched ${p.title}.`),await Promise.all([pt.refetch(),m()])},[hn,m,pt]),Xs=o.useCallback(async p=>{const A=(p.initiativeId??"").trim(),F=(p.workstreamId??"").trim();if(!A||!F)throw new Error("Missing initiative/workstream metadata for this session.");const S=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:F,placement:"bottom",resetToTodo:!1})});if(!S.ok){const G=await hn(S,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(G))throw new Error(G);const _e=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!_e.ok)throw new Error(await hn(_e,"Failed to pause workstream using legacy fallback"))}T(`Paused ${p.title} and sent it to the bottom of queue.`),await Promise.all([pt.refetch(),m()])},[hn,m,pt]),is=o.useCallback(async p=>{const A=(p.workstreamId??"").trim();if(!A)throw new Error("This session is missing a workstream id for intervention notes.");const F=p.text.trim();if(gh(F)){Kt("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:F,commentType:"intervention",severity:"info",tags:["intervention","in_progress"]})});if(!S.ok)throw new Error(await hn(S,"Failed to submit intervention"));T(`Intervention sent for ${p.session.title}.`),await m()},[Kt,hn,m]),Qs=o.useCallback(async p=>{if(W(p.id),Re(p.id),$(null),P(null),!["running","completed","archived"].includes(p.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})})}catch{}T(`Dispatch requested: ${p.title}`),await m()},[m]),Yt=o.useCallback(async(p,A,F={})=>{const S=await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!S.ok){const G=await S.json().catch(()=>null);throw new Error((G==null?void 0:G.error)??`${A} failed (${S.status})`)}},[]),$t=o.useCallback(async p=>{var G;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!A.ok){const _e=await A.json().catch(()=>null);throw new Error((_e==null?void 0:_e.error)??`Checkpoint creation failed (${A.status})`)}const F=await A.json().catch(()=>null),S=F&&"data"in F&&((G=F.data)==null?void 0:G.id)||F&&"id"in F&&F.id||null;T(S?`Checkpoint created: ${S.slice(0,8)}`:"Checkpoint created."),await m()},[m]),L=o.useCallback(async p=>{await Yt(p,"pause",{reason:"pause_from_dashboard"}),T(`Pause requested: ${p.title}`),await m()},[m,Yt]),Tt=o.useCallback(async p=>{await Yt(p,"resume",{reason:"resume_from_dashboard"}),T(`Resume requested: ${p.title}`),await m()},[m,Yt]),Sr=o.useCallback(async p=>{await Yt(p,"cancel",{reason:"restart_from_in_progress"}),await te(p),T(`Restarted ${p.title}.`),await m()},[te,m,Yt]),Ds=o.useCallback(async p=>{await Yt(p,"cancel",{reason:"cancel_from_dashboard"}),T(`Cancel requested: ${p.title}`),await m()},[m,Yt]),bi=o.useCallback(async p=>{var nt;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(p.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const Ue=await A.json().catch(()=>null);throw new Error((Ue==null?void 0:Ue.error)??`Checkpoint list failed (${A.status})`)}const F=await A.json().catch(()=>null),_e=(nt=(Array.isArray(F)?F:Array.isArray(F==null?void 0:F.data)?F.data:[]).map(Ue=>({id:typeof Ue.id=="string"?Ue.id:"",createdAt:typeof Ue.createdAt=="string"?Ue.createdAt:typeof Ue.created_at=="string"?Ue.created_at:""})).filter(Ue=>Ue.id.length>0).sort((Ue,Be)=>Date.parse(Be.createdAt)-Date.parse(Ue.createdAt))[0])==null?void 0:nt.id;if(!_e)throw new Error("No checkpoint available for rollback.");await Yt(p,"rollback",{checkpointId:_e,reason:"rollback_from_dashboard"}),T(`Rollback requested for ${p.title}.`),await m()},[m,Yt]),Js=o.useCallback(async()=>{var F;if(!Dt||nn.trim().length===0||jn)return;R(!0);const p=Dt.type,A=nn.trim();try{const S={type:p,title:A,status:"active"};if(p==="workstream"){const _e=Dt.initiativeId??(St==null?void 0:St.initiativeId)??((F=Mt[0])==null?void 0:F.id)??null;if(!_e){T("Select an initiative first to start a workstream."),R(!1);return}S.initiative_id=_e,S.parentId=_e}const G=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!G.ok){const _e=await G.json().catch(()=>null);throw new Error((_e==null?void 0:_e.error)??`Failed to create ${p}.`)}T(`Created ${p}: ${A}`),ae(),await m()}catch(S){T($n(S instanceof Error?S.message:"",`Failed to create ${p}.`)),R(!1)}},[ae,jn,Dt,nn,Mt,m,St==null?void 0:St.initiativeId]),ks=o.useCallback(()=>{me("initiative")},[me]),tt=o.useCallback(p=>{me("workstream",p)},[me]);o.useCallback(()=>{var p;return tt((St==null?void 0:St.initiativeId)??((p=Mt[0])==null?void 0:p.id)??null)},[Mt,St==null?void 0:St.initiativeId,tt]);const Ys=o.useCallback(p=>{const A=[...Y].filter(F=>(F.initiativeId??F.groupId)===p.id).sort(ra)[0];A&&(W(A.id),Re(A.id),$(null),P(null),T(`Focused initiative: ${p.name}`))},[Y]),gt=o.useCallback(p=>{const A=Mt.find(F=>F.id===p)??E.find(F=>F.id===p)??null;A&&Ys(A)},[Ys,Mt,E]),Kn=o.useCallback(p=>{const A=(p??"").trim();x("activity"),z("initiatives"),B("initiatives"),Ne("in_progress"),Oe("needs_attention"),O(A.length>0?A:null),T(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[x]),Zs=o.useCallback(p=>{const A=new Set,F=(p.runId??"").trim();F.length>0&&A.add(F),A.add(p.sliceRunId);const S=new Map;for(const Be of ce){const ct=sa(Be),It=uh(Be);(ct&&A.has(ct)||It&&It===p.sliceRunId)&&S.set(Be.id,Be)}const G=Array.from(S.values()),_e=Be=>{const ct=Be.type.trim().toLowerCase();let It=0;return(ct==="decision_requested"||ct==="blocker_created")&&(It+=80),(ct==="run_failed"||ct==="autopilot_stopped")&&(It+=70),(ct.includes("slice_completed")||ct.includes("completed"))&&(It+=60),ct.includes("artifact")&&(It+=55),(ct.includes("progress")||ct.includes("update"))&&(It+=35),It+=Math.floor(cn(Be.timestamp)/1e3),It};G.sort((Be,ct)=>_e(ct)-_e(Be));const nt=G[0]??null;x("activity"),B("activity"),z("initiatives");const Ue=(F?Y.find(Be=>Be.runId===F||Be.id===F)??null:null)??(p.initiativeId&&p.workstreamId?Y.find(Be=>Be.initiativeId===p.initiativeId&&Be.workstreamId===p.workstreamId)??null:null);if(Ue?(W(Ue.id),Re(Ue.id),$(null),P(null)):p.workstreamId&&(Re(null),$(p.workstreamId),P(p.workstreamTitle??"Work slice")),nt!=null&&nt.id){pe(nt.id),T(`Reviewing activity for ${p.workstreamTitle??"work slice"}.`);return}if(p.primaryAction==="resolve_decision"){Kn();return}if(F.length>0){ht(F),T("Opened the related work session. Timeline details were unavailable.");return}T("No activity details were found for this slice yet.")},[ce,ht,Kn,Y,x]);return o.useCallback(p=>{const A=new Set(p),F=[...Y].filter(S=>A.has(S.status)).sort(ra)[0];if(!F){T("No matching sessions for that metric right now.");return}et(F.id),B("activity")},[Y,et]),o.useCallback(p=>{c==="activity"&&(p==="sessions"||p==="active"||p==="blocked"||p==="failed"||p==="decisions"||p==="outbox"||p==="handoffs")&&Ke(p)},[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((p,A)=>n.jsx("div",{className:"shimmer-skeleton h-7 w-24 rounded-full"},A))})]}),n.jsxs("div",{className:"grid flex-1 grid-cols-1 gap-4 p-4 sm:p-5 lg:grid-cols-12",children:[n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-3"}),n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-6"}),n.jsxs("div",{className:"flex flex-col gap-4 lg:col-span-3",children:[n.jsx("div",{className:"shimmer-skeleton h-40 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton h-48 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton flex-1 rounded-2xl",style:{minHeight:160}})]})]})]}):n.jsxs("div",{className:"relative flex min-h-screen flex-col pb-[92px] lg:h-screen lg:min-h-0 lg:overflow-hidden lg:pb-0",style:{backgroundColor: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(Ah,{}),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(ku,{color:ah[j.connection],pulse:j.connection==="connected",title:[`Status: ${Jo[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: ${lh(j.lastSnapshotAt)}`,Dn?`Details: ${Dn.message}`:null].filter(Boolean).join(`
|
|
212
|
+
`),children:Jo[j.connection]??"Unknown"}),(In>0||An>0)&&n.jsx(No,{className:"hidden md:flex",running:In,blocked:An,decisionsCount:ye?j.decisions.length:0,completedToday:ws,onDecisionsClick:()=>{x("activity"),z("initiatives"),B("initiatives"),Ne("in_progress"),Oe("needs_attention")},onBlockedClick:()=>{Se.length>0?(x("mission-control"),Ne("in_progress"),Oe("needs_attention")):Ke("blocked")},onNewInitiative:ks})]}),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:ts,onFocus:ts,"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:p=>{const A=p.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(p=>n.jsx("option",{value:p.id,children:p.title},p.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),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:()=>{es(!1),kn()},className:"hidden rounded-full border border-amber-200/25 bg-amber-200/10 px-3 py-1.5 text-caption font-semibold text-amber-100 transition-colors hover:bg-amber-200/15 sm:inline",title:"Exit demo mode",children:"Exit demo"}),n.jsxs("button",{type:"button",ref:Fe,onClick:()=>Ce(p=>!p),title:"Notifications","aria-haspopup":"dialog","aria-expanded":ue,"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"})]}),vs.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:vs.length})]}),n.jsx("button",{type:"button",onClick:()=>lt(!0),title:"Realtime orchestrator",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 18a2.5 2.5 0 0 0 2.5-2.5v-7a2.5 2.5 0 1 0-5 0v7A2.5 2.5 0 0 0 12 18z"}),n.jsx("path",{d:"M6 12.5v2a6 6 0 0 0 12 0v-2"}),n.jsx("path",{d:"M12 20.5v2"})]})}),n.jsx("button",{type:"button",onClick:()=>Kt("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:m,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"})]}),ue&&n.jsxs("div",{id:"header-notifications-panel",ref:Xe,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:[vs.length>0&&n.jsx("button",{type:"button",onClick:Gs,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>Ce(!1),className:"rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary","aria-label":"Close notifications",children:"Close"})]})]}),n.jsx("div",{className:"mb-1.5 px-1.5",children:n.jsx(No,{className:"max-w-full overflow-hidden",running:In,blocked:An,decisionsCount:Rs,completedToday:ws,onDecisionsClick:()=>{x("activity"),B("initiatives"),z("initiatives"),Ne("in_progress"),Oe("needs_attention"),Ce(!1)},onBlockedClick:()=>{Se.length>0?(x("mission-control"),Ne("in_progress"),Oe("needs_attention")):Ke("blocked"),Ce(!1)}})}),vs.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:Nr>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:vs.map(p=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:p.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:p.kind==="error"?"rgba(239,68,68,0.08)":"rgba(255,255,255,0.02)"},children:n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex items-center gap-1.5 text-body font-semibold",style:{color:p.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(bn,{type:p.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:p.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:p.message}),p.onAction&&n.jsx("button",{type:"button",onClick:()=>{var A;(A=p.onAction)==null||A.call(p),Ce(!1)},className:"mt-1.5 rounded-md border border-strong bg-white/[0.05] px-2.5 py-1 text-caption font-medium text-primary transition-colors hover:bg-white/[0.1] hover:text-white",children:p.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>Ir(p.id),className:"shrink-0 rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary",title:"Dismiss",children:"Dismiss"})]})},p.id))})]})]})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-center gap-2 lg:hidden",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"workspace-switcher-mobile",className:"sr-only",children:"Workspace scope"}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{id:"workspace-switcher-mobile",value:u??"__all__",onChange:p=>{const A=p.target.value;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(p=>n.jsx("option",{value:p.id,children:p.title},p.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})]}),n.jsxs("div",{className:"flex w-full max-w-[248px] rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>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(Vf,{initiatives:E,activities:ce,agents:Hn,runtimeInstances:j.runtimeInstances??[],workspaceInitiativeId:u,isLoading:w,authToken:null,embedMode:!1,connection:j.connection,lastSnapshotAt:j.lastSnapshotAt,error:k,hasApiKey:e.state.hasApiKey,onOpenSettings:()=>Kt("orgx"),onRefresh:m,onCreateInitiative:ks,onPlayNextUp:Ls,onStartAutopilot:We,nextUpQueueModel:pt,nextUpActionsModel:Ht,snapshotVersion:j.snapshotVersion,nextUpActiveElsewhereCount:rt})})}):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(cp,{sessions:j.sessions,activity:ce,runtimeInstances:j.runtimeInstances??[],showSyntheticEntities:t||r,selectedSessionId:we,onSelectSession:et,onAgentFilter:se,agentFilter:U,timeFilterId:J,onReconnect:kn,onLaunched:m,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(Hf,{activity:Un.items,sessions:Y,sliceRuns:Se,initiatives:Mt,timelineNarrative:j.timelineNarrative??[],workspaceId:u,chatSnapshot:j.chat,selectedRunIds:fn,selectedSessionLabel:Ar,selectedWorkstreamId:ne,selectedWorkstreamLabel:X,agentFilter:U,timeFilterId:J,onTimeFilterChange:bs,customTimeRange:ve,onCustomTimeRangeChange:ke,hasMore:Un.hasMore,isLoadingMore:Un.isLoadingMore,onLoadMore:Un.loadMore,onClearSelection:je,onClearWorkstreamFilter:ft,onClearAgentFilter:Qe,onFocusRunId:ht,onOpenDecision:Kn,requestedActivityItemId:Te,onActivityItemRequestHandled:()=>pe(null),onPlayNextUp:Ls,onStartAutopilot:We,onPauseWorkstream:Xs,onCreateInitiative:ks,onOpenMissionControl:()=>x("mission-control"),onOpenNextUp:()=>x("mission-control"),onOpenSettings:()=>Kt("orgx"),onRefreshData:m,isLoading:w})}),n.jsx("section",{className:`flex min-h-0 flex-col gap-3 lg:col-span-3 lg:gap-3 ${Ae!=="decisions"&&Ae!=="initiatives"?"hidden lg:flex":""}`,children:n.jsx("div",{className:`min-h-0 ${Pe==="initiatives"?"flex-1":"flex-shrink-0"} `,children:Pe==="initiatives"?n.jsxs(Us,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 pt-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-4 overflow-x-auto",children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":Q==="in_progress",onClick:p=>{p.stopPropagation(),Ne("in_progress")},className:le("relative inline-flex items-center gap-1.5 pb-2 text-caption font-semibold transition-colors",Q==="in_progress"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"In Progress"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:rt}),n.jsx("span",{className:le("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:p=>{p.stopPropagation(),Ne("next_up")},className:le("relative inline-flex items-center gap-1.5 pb-2 text-caption font-semibold transition-colors",Q==="next_up"?"text-white":"text-secondary hover:text-bright"),children:[n.jsx("span",{children:"Next Up"}),n.jsx("span",{className:"text-micro tabular-nums text-muted",children:gs.total}),n.jsx("span",{className:le("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:()=>{Fn().catch(p=>{T($n(p instanceof Error?p.message:"","Autopilot action failed."))})},disabled:q,className:"control-pill inline-flex h-8 items-center gap-1.5 px-2.5 text-caption font-semibold disabled:opacity-45","data-tone":"teal","data-state":en?"active":"idle",title:en?"Stop autopilot":"Start autopilot","aria-label":en?"Stop autopilot":"Start autopilot",children:[n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:le("h-3.5 w-3.5",en?"animate-pulse":""),"aria-hidden":!0,children:n.jsx("path",{d:"M6.1 13.25C4.25 13.25 2.8 11.8 2.8 10s1.45-3.25 3.3-3.25c3.15 0 4.35 6.5 8.05 6.5 1.85 0 3.3-1.45 3.3-3.25s-1.45-3.25-3.3-3.25c-3.7 0-4.9 6.5-8.05 6.5Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),n.jsx("span",{className:"text-micro uppercase tracking-[0.12em]",children:"Auto"}),n.jsx("span",{className:le("rounded-full px-1.5 py-0.5 text-[10px] font-semibold",en?"bg-[#BFFF00]/18 text-[#E3FFAE]":"bg-white/[0.08] text-secondary"),children:en?"On":"Off"})]})]}),Q==="in_progress"?n.jsxs("div",{className:"flex items-center gap-1.5 border-b border-subtle px-4 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>Oe("all"),className:le("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",$e==="all"?"bg-white/[0.09] text-primary":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"All active"}),n.jsx("span",{className:"tabular-nums opacity-75",children:rt})]}),n.jsxs("button",{type:"button",onClick:()=>Oe("needs_attention"),className:le("inline-flex h-6 items-center gap-1 rounded-full px-2.5 text-micro font-semibold transition-colors",$e==="needs_attention"?"bg-[#F5B700]/14 text-[#FFE7A8]":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"Needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:Ct})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:Q==="in_progress"?$e==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[Wt.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(Xf,{model:Wt,actions:Lt,onOpenDetail:mn})})}),ye?n.jsxs("section",{className:le("overflow-hidden rounded-xl border border-subtle bg-white/[0.02]",ze.length===0?"flex-1 min-h-[220px]":"min-h-[220px] max-h-[50%]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Decision queue"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:j.decisions.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:"Resolve blockers and approvals to keep dispatch moving."})]}),n.jsx("div",{className:"min-h-0 p-2",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"h-full min-h-[160px] rounded-lg border border-subtle bg-white/[0.02] p-4 text-body text-secondary",children:"Loading decisions…"}),children:n.jsx(Gf,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:j.decisions,focusDecisionId:C,onFocusDecisionHandled:()=>O(null),onApproveDecision:_,onRejectDecision:H,onApproveAll:oe,onBulkDecisionAction:K,mutationState:be})})})]}):n.jsx(Us,{className:"border border-subtle bg-white/[0.02] px-4 py-3 text-body text-secondary",children:"OrgX is not connected. Decision actions are hidden until connectivity returns."}),n.jsxs("section",{className:le("flex min-h-[180px] flex-1 flex-col overflow-hidden rounded-xl border border-subtle bg-white/[0.02]"),children:[n.jsxs("div",{className:"border-b border-subtle px-3 py-2.5",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45",children:ye?"Blocked & review-required slices":"Needs attention"}),n.jsx("span",{className:"rounded-full bg-white/[0.08] px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-white/55",children:ze.length})]}),n.jsx("p",{className:"mt-1 text-caption text-white/35",children:"Retry, approve, or manually intervene on execution slices."})]}),n.jsx("div",{className:"min-h-0 flex-1 p-2",children:n.jsx(mm,{className:le("h-full min-h-0"),title:ye?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:Se,initiatives:Mt,onOpenDecisions:()=>Kn(),onFocusRunId:ht,onReviewActivity:Zs,onOpenSliceDetail:dn})})]})]}):n.jsx(tm,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:Y,sliceRuns:Se,initiatives:Mt,needsAttentionCount:Ct,onSwitchToNeedsAttention:()=>Oe("needs_attention"),onOpenSession:et,onFocusRunId:ht,onPlayWorkstream:te,onPauseWorkstream:Xs,onResumeWorkstream:te,onRestartSession:Sr,onIntervene:xs,onOpenSliceDetail:Gt}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(Jf,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:pt,queueActions:Ht,snapshotVersion:j.snapshotVersion,activeElsewhereCount:rt,excludeRunning:!0,onOpenInitiative:gt,onOpenSliceDetail:Jt})})},`${Q}:${$e}`)]}):n.jsx(Us,{className:"card-enter",children:n.jsxs("button",{onClick:()=>z("initiatives"),className:"flex w-full items-center justify-between px-4 py-3 text-left transition-colors hover:bg-white/[0.03]",children:[n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("h2",{className:"text-heading font-semibold text-white",children:"Initiatives"})}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"-rotate-90 text-muted",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})})})})]}),n.jsx(yt,{children:Ie&&St&&n.jsxs(n.Fragment,{children:[n.jsx(he.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed bottom-0 left-0 right-0 top-[64px] z-[240] hidden bg-black/40 backdrop-blur-sm lg:block",onClick:()=>Ee(!1)},"session-drawer-backdrop"),n.jsxs(he.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:400,damping:35},className:"fixed bottom-0 right-0 top-[64px] z-[250] hidden w-[480px] flex-col lg:flex",style:{backgroundColor:D.cardBg},children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-subtle px-4 py-3",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Session Detail"}),n.jsx("button",{type:"button",onClick:()=>Ee(!1),"aria-label":"Close session inspector",className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08] hover:text-white",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),n.jsx("div",{className:"flex-1 min-h-0",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading session detail…"}),children:n.jsx(Kf,{session:St,activity:ce,initiatives:Mt,sliceRuns:Se,initialInterventionDraft:fe,onSubmitIntervention:is,onOpenActivityItem:rs,onContinueHighestPriority:Vn,onDispatchSession:Qs,onPauseSession:L,onResumeSession:Tt,onCancelSession:Ds,onCreateCheckpoint:$t,onRollbackSession:bi,onStartInitiative:ks,onStartWorkstream:tt})})})]},"session-drawer-panel")]})}),c==="activity"?n.jsx(Nu,{activeTab:Ae,onTabChange:De,pendingDecisionCount:ye?j.decisions.length:0}):null,n.jsx(gi,{open:Dt!==null,onClose:ae,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:nn,onChange:p=>pn(p.target.value),onKeyDown:p=>{p.key==="Enter"&&Js()},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:ae,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:Js,disabled:nn.trim().length===0||jn,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:jn?"Creating…":"Create"})]})]})}),He.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Yf,{open:He.open,onClose:()=>mt(p=>({...p,open:!1,focusAgentDomain:null})),activeTab:He.tab,onChangeTab:p=>mt(A=>({...A,tab:p})),agentBehaviorInitialDomain:He.focusAgentDomain,demoMode:t,onToggleDemoMode:p=>{es(p),p||kn()},devMode:a,onToggleDevMode:l,showSyntheticEntities:r,onToggleShowSyntheticEntities:i,workspaceOptions:v,selectedWorkspaceId:u,onSelectWorkspace:g,onboarding:e,authToken:null,embedMode:!1})}),ot&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(ih,{open:ot,selectedWorkspaceId:u,onClose:()=>lt(!1)})}),(ge==="sessions"||ge==="active"||ge==="blocked"||ge==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Zf,{open:ge==="sessions"||ge==="active"||ge==="blocked"||ge==="failed",onClose:()=>Ke(null),mode:ge==="active"||ge==="blocked"||ge==="failed"?ge:"sessions",sessions:Y,onOpenSession:p=>{et(p.id),Ke(null)},onRunAction:async(p,A)=>{await Yt(p,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>m(),onSetNotice:p=>T(p)})}),ge==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(eh,{open:ge==="decisions",onClose:()=>Ke(null),decisions:ye?j.decisions:[],onApproveDecision:_,onRejectDecision:H,onApproveAll:oe,onBulkDecisionAction:K})}),ge==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(th,{open:ge==="outbox",onClose:()=>Ke(null),outbox:j.outbox,onOpenSettings:()=>{Ke(null),Kt("orgx")},onRefresh:()=>{m()}})}),ge==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(nh,{open:ge==="handoffs",onClose:()=>Ke(null),handoffs:j.handoffs})}),n.jsx(Sh,{}),Vt&&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(Qf,{item:Vt,actions:Lt,onClose:()=>Ot(null),onNavigate:Rn,currentIndex:un,totalCount:Nt.length,decisions:ye?j.decisions:void 0,onApproveDecision:_,onRejectDecision:H})})})}),Ze&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(rh,{target:Ze,onClose:()=>jt(null),onPlayWorkstream:async(p,A,F)=>{const S=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,workstreamId:A,agentId:F??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const G=await S.json().catch(()=>null);T($n((G==null?void 0:G.error)??(G==null?void 0:G.message)??null,`Failed to dispatch workstream (${S.status})`));return}T("Dispatched workstream."),m()},onStartAutoContinue:async(p,A,F)=>{await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,workstreamId:A,placement:"top"})});const S=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,agentId:F??void 0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const G=await S.json().catch(()=>null);T($n((G==null?void 0:G.error)??(G==null?void 0:G.message)??null,`Failed to start auto-continue (${S.status})`));return}T("Auto-continue started."),m()},onMoveWorkstream:async(p,A,F)=>{const S=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,workstreamId:A,placement:F})});if(!S.ok){const G=await S.json().catch(()=>null);T($n((G==null?void 0:G.error)??(G==null?void 0:G.message)??null,`Move failed (${S.status})`));return}T(`Moved workstream to ${F}.`),m()},onRemoveFromQueue:async(p,A)=>{const F=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:p,workstreamId:A})});if(!F.ok){const S=await F.json().catch(()=>null);T($n((S==null?void 0:S.error)??(S==null?void 0:S.message)??null,`Remove failed (${F.status})`));return}T("Removed workstream from queue."),m()},onOpenSession:et,onFocusRunId:ht,onOpenInitiative:gt,onReviewActivity:Zs,onOpenDecisions:()=>Kn(),onAcceptSlice:En,onRejectSlice:hs})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});yd();const Ch=new sc({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});tc.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(nc,{client:Ch,children:n.jsx(jh,{})})}));export{Ph as $,Bt as A,le as B,qt as C,zn as D,bn as E,cs as F,Ud as G,Oh as H,Hh as I,Bh as J,zh as K,os as L,li as M,ds as N,wp as O,Us as P,Fh as Q,_s as R,Hs as S,xi as T,Id as U,lu as V,cu as W,fu as X,xu as Y,Wh as Z,xc as _,Ad as a,zu as a0,Uh as a1,Cn as a2,Dr as a3,Tu as a4,$h as a5,sr as a6,ni as a7,At as b,hm as c,rd as d,D as e,Qh as f,Fm as g,Rt as h,Ft as i,As as j,Vh as k,Cl as l,Pt as m,zt as n,Gh as o,Ei as p,Jn as q,_t as r,Jh as s,gm as t,Vd as u,Xh as v,Kh as w,qh as x,gi as y,fs as z};
|