@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
|
@@ -1,212 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DEip7uko.js","assets/cNrhgGc1.js","assets/C-KIc3Wc.js","assets/BJgZIVUQ.js","assets/qm8xLgv-.css","assets/BVShoyjA.js","assets/77gGFBt6.js","assets/CxQ08qFN.js","assets/tcEHYcbW.js","assets/CgQDT6yL.js","assets/BBpTN_SR.js","assets/CSr2ZnTV.js","assets/CnitK1MX.js","assets/C-PAoJF-.js","assets/CL_wXqR7.js","assets/BTAEErUY.js","assets/C0nA-iUG.js","assets/DxKG5zy8.js","assets/DOFL9l8s.js","assets/D7DHFX0D.js","assets/DpuQm1oF.js","assets/CFwPph5U.js","assets/C6GO-FKy.js","assets/BgcAY5rE.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Dl=Object.defineProperty;var $l=(e,t,s)=>t in e?Dl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var tr=(e,t,s)=>$l(e,typeof t!="symbol"?t+"":t,s);import{r as o,u as oa,a as cs,b as yn,j as n,c as Fl,d as Pl,D as Ia,e as Ol,Q as Bl}from"./cNrhgGc1.js";import{b as ql}from"./C-KIc3Wc.js";import{m as he,A as yt,u as Hn}from"./CxQ08qFN.js";import{F as zl,T as Wl}from"./BJgZIVUQ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function s(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=s(i);fetch(i.href,a)}})();const Ul="modulepreload",Hl=function(e){return"/orgx/live/"+e},Aa={},qt=function(t,s,r){let i=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(g=>Promise.resolve(g).then(y=>({status:"fulfilled",value:y}),y=>({status:"rejected",reason:y}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),d=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=c(s.map(u=>{if(u=Hl(u),u in Aa)return;Aa[u]=!0;const g=u.endsWith(".css"),y=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${y}`))return;const w=document.createElement("link");if(w.rel=g?"stylesheet":Ul,g||(w.as="script"),w.crossOrigin="",w.href=u,d&&w.setAttribute("nonce",d),document.head.appendChild(w),g)return new Promise((f,k)=>{w.addEventListener("load",f),w.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return i.then(c=>{for(const l of c||[])l.status==="rejected"&&a(l.reason);return t().catch(a)})},Sa=()=>{const e=new Date,t=s=>new Date(e.getTime()-s*60*1e3).toISOString();return{connection:"connected",lastActivity:"2m ago",lastSnapshotAt:e.toISOString(),snapshotVersion:1,sessions:{groups:[{id:"init-1",label:"Q4 Feature Ship",status:"active"},{id:"init-2",label:"Black Friday Email",status:"active"}],edges:[{parentId:"run-1",childId:"run-2"},{parentId:"run-1",childId:"run-3"}],nodes:[{id:"run-1",parentId:null,runId:"run-1",title:"Q4 Feature Ship – Planning",agentId:"eli",agentName:"Eli",status:"running",progress:45,initiativeId:"init-1",workstreamId:null,groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(120),updatedAt:t(2),lastEventAt:t(2),lastEventSummary:"Delegated work to design and data agents.",blockers:[]},{id:"run-2",parentId:"run-1",runId:"run-2",title:"Dashboard UI pass",agentId:"dana",agentName:"Dana",status:"running",progress:70,initiativeId:"init-1",workstreamId:"ws-4",groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(80),updatedAt:t(5),lastEventAt:t(5),lastEventSummary:"Drafted handoff for approval.",blockers:["Approval pending"]},{id:"run-3",parentId:"run-1",runId:"run-3",title:"Usage tracking instrumentation",agentId:"pace",agentName:"Pace",status:"queued",progress:0,initiativeId:"init-1",workstreamId:"ws-5",groupId:"init-1",groupLabel:"Q4 Feature Ship",startedAt:t(30),updatedAt:t(12),lastEventAt:t(12),lastEventSummary:"Waiting for data pipeline access.",blockers:["Access to events table"]},{id:"run-4",parentId:null,runId:"run-4",title:"Black Friday Email Campaign",agentId:"mark",agentName:"Mark",status:"running",progress:55,initiativeId:"init-2",workstreamId:null,groupId:"init-2",groupLabel:"Black Friday Email",startedAt:t(90),updatedAt:t(8),lastEventAt:t(8),lastEventSummary:"Drafted subject line variants.",blockers:[]}]},activity:[{id:"activity-1",type:"decision_requested",title:"Decision requested",description:"Approve dashboard UI layout for Q4 Feature Ship.",agentId:"dana",agentName:"Dana",requesterAgentId:"dana",requesterAgentName:"Dana",executorAgentId:"dana",executorAgentName:"Dana",runId:"run-2",initiativeId:"init-1",timestamp:t(2)},{id:"activity-2",type:"artifact_created",title:"Artifact created: Subject line variants",description:"Drafted 3 subject line variants for approval.",agentId:"mark",agentName:"Mark",requesterAgentId:"mark",requesterAgentName:"Mark",executorAgentId:"mark",executorAgentName:"Mark",runId:"run-4",initiativeId:"init-2",timestamp:t(8)},{id:"activity-3",type:"delegation",title:"Task delegated",description:"Spin up data agent for instrumentation plan.",agentId:"eli",agentName:"Eli",requesterAgentId:"eli",requesterAgentName:"Eli",executorAgentId:"eli",executorAgentName:"Eli",runId:"run-1",initiativeId:"init-1",timestamp:t(18)}],handoffs:[{id:"handoff-1",title:"Dashboard UI approval",status:"created",priority:"high",summary:"Need approval on dashboard UI layout and component hierarchy.",currentActorType:"user",currentActorId:"me",createdAt:t(12),updatedAt:t(2),events:[{id:"handoff-event-1",handoffId:"handoff-1",eventType:"created",actorType:"agent",actorId:"dana",payload:{summary:"Draft layout ready for review."},createdAt:t(12)}]}],decisions:[{id:"decision-1",title:"Approve dashboard copy update",context:"Marketing requested a copy refresh before final launch. Confirm wording changes.",status:"pending",agentName:"Mark",requestedAt:t(22),updatedAt:t(2),waitingMinutes:22}],sliceRuns:[{id:"slice-run-1",sliceRunId:"slice-run-1",runId:"run-2",initiativeId:"init-1",workstreamId:"ws-4",workstreamTitle:"Dashboard UI pass",taskIds:["task-1"],milestoneIds:[],status:"awaiting_input",statusExplainer:"Needs your decision to proceed with this slice.",primaryAction:"resolve_decision",hasArtifact:!1,artifactCount:0,artifacts:[],decisionCount:1,blockingDecisionCount:1,decisionOptions:[{id:"approve-layout",label:"Approve layout",description:"Proceed with the current dashboard layout.",impliedStatus:"approved",requiresNote:!1}],sourceClient:"codex",runtimeState:"active",startedAt:t(80),updatedAt:t(2),completedAt:null,failedAt:null,archivedAt:null,lastEventAt:t(2),lastEventSummary:"Waiting on approval before implementation continues.",correlationId:"run-2",confidence:"high"},{id:"slice-run-2",sliceRunId:"slice-run-2",runId:"run-4",initiativeId:"init-2",workstreamId:"ws-9",workstreamTitle:"Email campaign generation",taskIds:["task-2"],milestoneIds:[],status:"completed",statusExplainer:"Completed with verified output artifacts.",primaryAction:"open_artifact",hasArtifact:!0,artifactCount:1,artifacts:[{id:"artifact-1",type:"document",title:"Subject line variants",url:null,createdAt:t(8)}],decisionCount:0,blockingDecisionCount:0,decisionOptions:[],sourceClient:"openclaw",runtimeState:"stopped",startedAt:t(90),updatedAt:t(8),completedAt:t(8),failedAt:null,archivedAt:null,lastEventAt:t(8),lastEventSummary:"Produced subject line variants and attached artifact.",correlationId:"run-4",confidence:"high"}],outbox:{pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},chat:{threads:[],total:0,updatedAt:e.toISOString()}}},hi="all";function zn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Vl(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);return zn(e.get("workspace_id"))??zn(e.get("workspaceId"))??zn(e.get("command_center_id"))??zn(e.get("commandCenterId"))??zn(e.get("center"))??zn(e.get("project_id"))??zn(e.get("projectId"))}catch{return null}}function ds(e,t,s){const r=zn(t);if(!r){s!=null&&s.allTokenWhenMissing&&(e.set("workspace_id",hi),e.set("command_center_id",hi),e.set("center",hi));return}e.set("workspace_id",r),e.set("command_center_id",r),e.set("center",r)}function Kl(e){const t=zn(e);return t?{"x-orgx-workspace-id":t}:{}}function St(e){const t={};e.contentTypeJson&&(t["Content-Type"]="application/json"),e.embedMode&&(t["X-Orgx-Embed"]="true"),e.authToken&&(t.Authorization=`Bearer ${e.authToken}`);const s=e.workspaceId??Vl();return Object.assign(t,Kl(s)),t}const Gl=[[/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 xr(e){if(!e)return"";for(const[s,r]of Gl)if(s.test(e))return r;const t=e.split("/");return t[t.length-1]??e}const Ho=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Vo=/^[0-9a-f]{20,}$/i;function is(e){return Ho.test(e)?`#${e.slice(0,4)}`:Vo.test(e)?`#${e.slice(0,4)}`:e}function Un(e){return Ho.test(e)||Vo.test(e)}function Is(e,t=4){let s=e.replace(/^\/Users\/[^/]+\//,"~/").replace(/^~\/Code\//,"").replace(/^~\//,"");const r=s.split("/");return r.length>t&&(s=r.slice(-t).join("/")),s}function lt(e){let t=e;return t=t.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,s=>`#${s.slice(0,4)}`),t=t.replace(/(?:anthropic|openrouter|openai)\/[a-z0-9._/-]+/gi,s=>xr(s)),t=t.replace(/\/Users\/[a-zA-Z0-9_-]+\/[^\s"']+/g,s=>Is(s)),t}function Pt(e){let t=e;return t=t.replace(/\[?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\]?/gi,""),t=t.replace(/\[workstream\s*\]/gi,""),t=t.replace(/\[workstream\b[^\]]*\]/gi,""),t=t.replace(/\/var\/folders\/[^\s"']*/g,"(local file)"),t=t.replace(/\/tmp\/[^\s"']*/g,"(temp file)"),t=t.replace(/\/Users\/[^\s"']*/g,s=>Is(s)),t=t.replace(/telegram:\d+/g,"Telegram session"),t=t.replace(/discord:\d+/g,"Discord session"),t=t.replace(/\s{2,}/g," ").trim(),t||"Untitled session"}function fr(e){const t=e.toLowerCase().trim();return t==="main"?"You":t==="system"||t==="system / unknown"||t==="openclaw"||t==="local_openclaw"?"OrgX":t==="not assigned"||t==="unassigned"?"Pending":e}function Cn(e){return/agent catalog unavailable|listagents/i.test(e)?"Agent details are still loading.":/timed out|timeout|request cancelled|signal is aborted/i.test(e)?"Live sync is taking longer than expected. Data will refresh automatically.":/budget.*exhaust/i.test(e)?"Token budget reached":/unknown api endpoint|route is unavailable|missing required live routes/i.test(e)?"This plugin build is missing required routes. Update and restart the plugin.":/unauthorized|forbidden|authentication|api key/i.test(e)?"Authentication needs attention. Reconnect OrgX in Settings.":/worker exited without structured output|worker close|signal=null/i.test(e)?"An agent run ended before returning a structured result.":/mcp handshake failed/i.test(e)?"The agent connection handshake failed. Retry after reconnecting.":/run not found/i.test(e)?"This session is no longer available.":/500|internal server error/i.test(e)?"Something went wrong on the server. Retrying automatically.":/ECONNREFUSED|network error|fetch failed/i.test(e)?"Connection issue. Retrying automatically.":/40[13]/.test(e)?"Access issue. You may need to reconnect your workspace.":/blocked without an explicit reason/i.test(e)?"This item was paused without a specific reason.":Pt(lt(e))}function Xl(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 Ql(e){const t=e.metadata??{},s=Bs(t,"task_title")??Bs(t,"workstream_title"),r=s?Pt(String(s)):e.title?Pt(e.title):null,i=Bs(t,"user_summary")??Bs(t,"summary"),a=i?Pt(String(i)):e.summary?Pt(e.summary):e.description?Pt(e.description):null,c=Bs(t,"next_step")??Bs(t,"nextStep"),l=c?Pt(String(c)):null;return{taskDescription:r,outcomeDescription:a&&a===r?null:a,nextStep:l&&(l===r||l===a)?null:l}}function Bs(e,t){const s=e[t];return typeof s=="string"&&s.trim().length>0?s.trim():null}const Jl={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 nr(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Jl[t]??e.replace(/_/g," ")}const Yl={running:"Active",waiting_for_capacity:"Waiting for capacity",rate_limited:"Rate limited",idle:"Idle",blocked:"Blocked",queued:"Queued"};function ph(e){if(!e)return null;const t=e.trim().toLowerCase().replace(/[\s-]+/g,"_");return Yl[t]??e.replace(/_/g," ")}function fh(e,t){return e.toLowerCase().includes("path")?Is(t):Un(t)?is(t):t.includes(",")?t.split(",").map(r=>{const i=r.trim();return Un(i)?is(i):i}).join(", "):Pt(t)}function Zl(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 hh(e){const t=Zl(e);return!Number.isFinite(e)||e<60?{text:t,tone:"normal"}:e<1440?{text:t,tone:"attention"}:{text:t,tone:"urgent"}}function Jr(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString()}function _t(e){const s=(e instanceof Date?e:new Date(e)).getTime()-Date.now();if(Number.isNaN(s))return"unknown";const r=Math.floor(Math.abs(s)/1e3),i=s<0?"past":"future";if(r<10)return i==="past"?"just now":"soon";if(r<60)return i==="past"?`${r}s ago`:`in ${r}s`;const a=Math.floor(r/60);if(a<60)return i==="past"?`${a}m ago`:`in ${a}m`;const c=Math.floor(a/60);if(c<24)return i==="past"?`${c}h ago`:`in ${c}h`;const l=Math.floor(c/24);return i==="past"?`${l}d ago`:`in ${l}d`}const ec=8e3,tc=320,nc=300,sc=80,rc=80,ic=120,_a=6e4,ac=3500,oc=180,la={pendingTotal:0,pendingByQueue:{},oldestEventAt:null,newestEventAt:null,replayStatus:"idle",lastReplayAttemptAt:null,lastReplaySuccessAt:null,lastReplayFailureAt:null,lastReplayError:null},Ir={phase:"idle",action:null,targetCount:0,message:null,startedAt:null,completedAt:null},Ss={threads:[],total:0,updatedAt:null},Ca={running:0,active:0,queued:1,in_progress:1,working:1,planning:1,handoff:1,review:2,pending:2,blocked:3,failed:4,cancelled:5,paused:6,completed:6,archived:7},Ko=new Set(["running","active","queued","in_progress","working","planning","handoff","review","pending","blocked"]),Ar=10*6e4;function lc(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 c=a.replace(/^[^:]+:\s*/,"").trim();return c.length>0?c:a}))).slice(0,2).map(a=>Cn(a)).filter(a=>a.length>0).join(" ")}function dc(e){const t=e.trim().toLowerCase();if(!t)return"";if(t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("request canceled")||t.includes("signal is aborted"))return"Live sync is slower than expected. Some panels may refresh a few seconds late.";if(t.includes("unauthorized")||t.includes("forbidden"))return"OrgX authorization needs attention. Reconnect your API key in Settings.";if(t.includes("unknown api endpoint")||t.includes("route is unavailable"))return"This plugin runtime is missing required live routes. Restart the plugin after updating.";const s=e.replace(/^[^:]+:\s*/,"").replace(/\s+/g," ").trim();return Cn(s.length>0?s:e.trim())}function uc(e){const t=e.map(s=>dc(s)).filter(s=>s.length>0);return Array.from(new Set(t)).slice(0,2)}function ft(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Yr(e,t){const s=Ca[e.status]??99,r=Ca[t.status]??99;if(s!==r)return s-r;const i=ft(e.updatedAt??e.lastEventAt??e.startedAt),a=ft(t.updatedAt??t.lastEventAt??t.startedAt);return i!==a?a-i:e.id.localeCompare(t.id)}function mc(e){return(e??"").trim().toLowerCase()}function Ma(e){return Ko.has(mc(e.status))}function gi(e){const t=[];return e.id&&t.push(`id:${e.id}`),e.runId&&t.push(`run:${e.runId}`),t}function Ta(e,t){if(!e.nodes.length)return t;if(!t.nodes.length){const f=Date.now(),k=e.nodes.filter(v=>{const b=ft(v.updatedAt??v.lastEventAt??v.startedAt);if(Ma(v))return!0;const _=["completed","archived","failed"].includes((v.status??"").toLowerCase())?Ar/3:Ar;return f-b<=_});if(!k.length)return t;const x=new Set(k.map(v=>v.id)),j=new Set(k.map(v=>v.groupId));return{nodes:k.sort(Yr),edges:e.edges.filter(v=>x.has(v.parentId)&&x.has(v.childId)),groups:e.groups.filter(v=>j.has(v.id))}}const s=new Set,r=[...t.nodes];for(const f of t.nodes)for(const k of gi(f))s.add(k);const i=Date.now(),a=[];for(const f of e.nodes){if(gi(f).some(h=>s.has(h)))continue;const x=ft(f.updatedAt??f.lastEventAt??f.startedAt),v=["completed","archived","failed"].includes((f.status??"").toLowerCase())?Ar/3:Ar,b=i-x<=v;if(Ma(f)||b){a.push(f),r.push(f);for(const h of gi(f))s.add(h)}}if(!a.length)return t;const c=new Set(r.map(f=>f.id)),l=new Map(e.groups.map(f=>[f.id,f])),d=new Map(t.groups.map(f=>[f.id,f])),u=[...t.groups];for(const f of a){if(d.has(f.groupId))continue;const k=l.get(f.groupId)??{id:f.groupId,label:f.groupLabel||f.agentName||"Ungrouped",status:null};d.set(f.groupId,k),u.push(k)}const g=f=>`${f.parentId}->${f.childId}`,y=new Set,w=[];for(const f of t.edges){if(!c.has(f.parentId)||!c.has(f.childId))continue;const k=g(f);y.has(k)||(y.add(k),w.push(f))}for(const f of e.edges){if(!c.has(f.parentId)||!c.has(f.childId))continue;const k=g(f);y.has(k)||(y.add(k),w.push(f))}return{nodes:r.sort(Yr),edges:w,groups:u}}function sr(e,t){if(e.nodes.length<=t)return e;const s=[...e.nodes].sort(Yr).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 Ea(e,t){return e.length<=t?e:[...e].sort((s,r)=>ft(r.updatedAt)-ft(s.updatedAt)).slice(0,t)}function pc(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()-ft(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 Go(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 Ra(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 La(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 Da(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 Xo(e){if(!e||typeof e!="object")return la;const t=e.pendingByQueue&&typeof e.pendingByQueue=="object"?Object.fromEntries(Object.entries(e.pendingByQueue).filter(([r])=>typeof r=="string"&&r.length>0).map(([r,i])=>[r,Number.isFinite(Number(i))?Math.max(0,Math.floor(Number(i))):0])):{},s=e.replayStatus==="running"||e.replayStatus==="success"||e.replayStatus==="error"?e.replayStatus:"idle";return{pendingTotal:Number.isFinite(e.pendingTotal)?Math.max(0,Math.floor(e.pendingTotal)):Object.values(t).reduce((r,i)=>r+i,0),pendingByQueue:t,oldestEventAt:e.oldestEventAt??null,newestEventAt:e.newestEventAt??null,replayStatus:s,lastReplayAttemptAt:e.lastReplayAttemptAt??null,lastReplaySuccessAt:e.lastReplaySuccessAt??null,lastReplayFailureAt:e.lastReplayFailureAt??null,lastReplayError:e.lastReplayError??null}}function fc(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 hc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ws(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r!="string")continue;const i=r.trim();if(i.length>0)return i}return null}const gc=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 xc(e){const t=hc(e.metadata),s=t==null?void 0:t.event,r=typeof s=="string"?s.trim().toLowerCase():"";if(!r||!gc.has(r))return null;const i=(typeof e.runId=="string"&&e.runId.trim().length>0?e.runId.trim():null)??ws(t,["run_id","runId","slice_run_id","sliceRunId","active_run_id","activeRunId","last_run_id","lastRunId"]),a=ws(t,["correlation_id","correlationId"]),c=(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null)??ws(t,["initiative_id","initiativeId"]),l=ws(t,["workstream_id","workstreamId"]),d=ws(t,["task_id","taskId"]),u=ws(t,["stop_reason","stopReason"]),g=ws(t,["parsed_status","parsedStatus"]),y=(e.title??"").trim().toLowerCase();return!i&&!a&&!l&&!d?null:[r,c??"",l??"",d??"",i??"",a??"",u??"",g??"",y].join("|")}function Qo(e,t){const s=new Set,r=new Set,i=[];for(const a of e){if(s.has(a.id))continue;s.add(a.id);const c=xc(a);if(!(c&&r.has(c))&&(c&&r.add(c),i.push(a),i.length>=t))break}return i}function yc(e,t,s){if(t.length===0)return e;const r=new Map;for(const l of e)r.set(l.id,l);let i=!1;for(const l of t){const d=r.get(l.id);if(!d){r.set(l.id,l),i=!0;continue}(d.timestamp!==l.timestamp||d.type!==l.type||d.title!==l.title||d.description!==l.description||d.summary!==l.summary||d.kind!==l.kind||d.agentId!==l.agentId||d.agentName!==l.agentName||d.requesterAgentId!==l.requesterAgentId||d.requesterAgentName!==l.requesterAgentName||d.executorAgentId!==l.executorAgentId||d.executorAgentName!==l.executorAgentName||d.runId!==l.runId||d.initiativeId!==l.initiativeId||d.decisionRequired!==l.decisionRequired||JSON.stringify(d.metadata??null)!==JSON.stringify(l.metadata??null))&&(r.set(l.id,l),i=!0)}if(!i)return e;const a=Array.from(r.values()).sort((l,d)=>{const u=ft(d.timestamp)-ft(l.timestamp);return u!==0?u:d.id.localeCompare(l.id)}),c=Qo(a,s);return Go(e,c)?e:c}function xi(e,t){const s=[...e].sort((r,i)=>{const a=ft(i.timestamp)-ft(r.timestamp);return a!==0?a:i.id.localeCompare(r.id)});return Qo(s,t)}function $a(e,t){const s=e.filter(a=>!!a&&typeof a.id=="string"&&a.id.length>0).map(pc).sort((a,c)=>a.waitingMinutes!==c.waitingMinutes?c.waitingMinutes-a.waitingMinutes:ft(c.requestedAt??c.updatedAt)-ft(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 Fa(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 bc(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 wc(e,t){return!!(Ko.has(t)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0)}function Sr(e){return e?`Initiative ${e.length>16?`${e.slice(0,8)}…`:e}`:"Unscoped"}function yi(e){if(!Array.isArray(e))return[];const t=[];for(const s of e)typeof s=="string"&&s.trim().length>0&&t.push(s.trim());return t}function vc(e,t,s){const r=new Map,i=[...e].sort((l,d)=>ft(d.timestamp)-ft(l.timestamp));for(const l of i){if(!l.runId)continue;const d=l.runId,u=r.get(d),g=l.timestamp;if(!u){const y=l.initiativeId??null;r.set(d,{id:d,parentId:null,runId:d,title:l.title,agentId:l.agentId??null,agentName:l.agentName??null,status:Fa(l.type),progress:null,initiativeId:y,workstreamId:null,groupId:y??"unscoped",groupLabel:Sr(y),startedAt:g,updatedAt:g,lastEventAt:g,lastEventSummary:l.title,blockers:l.type==="blocker_created"&&l.description?[l.description]:[]});continue}(!u.startedAt||ft(g)<ft(u.startedAt))&&(u.startedAt=g),ft(g)>=ft(u.updatedAt??u.lastEventAt)&&(u.updatedAt=g,u.lastEventAt=g,u.lastEventSummary=l.title,u.status=Fa(l.type),l.agentName&&(u.agentName=l.agentName),l.agentId&&(u.agentId=l.agentId),l.initiativeId&&(u.initiativeId=l.initiativeId,u.groupId=l.initiativeId,u.groupLabel=Sr(l.initiativeId)),(!u.title||u.title.length<4)&&(u.title=l.title)),l.type==="blocker_created"&&l.description&&(u.blockers.includes(l.description)||u.blockers.push(l.description))}for(const l of t??[]){const d=l.runId??`agent:${l.id}`,u=r.get(d),g=bc(l.status),y=new Date().toISOString(),w=wc(l,g),f=l.startedAt??(w?y:null),k=l.initiativeId??null,x=l.currentTask&&l.currentTask.trim().length>0?l.currentTask.trim():`${l.name??l.id} ${g==="archived"?"idle":g}`;if(!u){r.set(d,{id:d,parentId:null,runId:d,title:x,agentId:l.id,agentName:l.name??l.id,status:g,progress:null,initiativeId:k,workstreamId:null,groupId:k??"unscoped",groupLabel:Sr(k),startedAt:f,updatedAt:f,lastEventAt:f,lastEventSummary:l.currentTask,blockers:yi(l.blockers)});continue}!u.agentName&&l.name&&(u.agentName=l.name),u.agentId||(u.agentId=l.id),(!u.title||u.title===u.runId)&&(u.title=x),w&&(u.updatedAt=f??u.updatedAt??y,u.lastEventAt=f??u.lastEventAt??y),u.status==="archived"&&g!=="archived"&&(u.status=g),yi(l.blockers).length>0&&(u.blockers=yi(l.blockers)),k&&!u.initiativeId&&(u.initiativeId=k,u.groupId=k,u.groupLabel=Sr(k))}const a=Array.from(r.values()).sort(Yr).slice(0,s),c=new Map;for(const l of a)c.has(l.groupId)||c.set(l.groupId,{id:l.groupId,label:l.groupLabel,status:l.status});return{nodes:a,edges:[],groups:Array.from(c.values())}}async function kc(e,t,s){var g;const r=Number.isFinite(s.timeoutMs)?Math.max(100,Math.floor(s.timeoutMs)):0,i=r>0?new AbortController:null,a=t==null?void 0:t.signal,c=(i==null?void 0:i.signal)??a,l=c?{...t??{},signal:c}:t??{};let d=null,u=null;if(i){if(a!=null&&a.aborted)i.abort();else if(a){const y=()=>i.abort();a.addEventListener("abort",y,{once:!0}),u=()=>a.removeEventListener("abort",y)}d=setTimeout(()=>i.abort(),r)}try{const y=await fetch(e,l),f=(((g=y.headers.get("content-type"))==null?void 0:g.toLowerCase())??"").includes("application/json");if(!y.ok){let k=`${y.status} ${y.statusText}`;if(f){const x=await y.json().catch(()=>null);x!=null&&x.error&&(k=`${y.status} ${x.error}`)}else{const x=(await y.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);x.length>0&&(k=`${y.status} ${x}`)}return{ok:!1,status:y.status,data:null,error:k}}if(!f){const k=(await y.text().catch(()=>"")).replace(/\s+/g," ").slice(0,80);return{ok:!1,status:y.status,data:null,error:`Unexpected content type for ${e}${k?`: ${k}`:""}`}}return{ok:!0,status:y.status,data:await y.json(),error:null}}catch(y){const w=y instanceof Error?y.message:"Network error",f=!!(i!=null&&i.signal.aborted)&&!(a!=null&&a.aborted);return y instanceof DOMException&&y.name==="AbortError"||lc(w)?{ok:!1,status:0,data:null,error:f&&r>0?`request timed out after ${r}ms`:"request cancelled"}:{ok:!1,status:0,data:null,error:w}}finally{d&&clearTimeout(d),u&&u()}}function jc(e,t,s,r,i=[],a=la,c=null,l=1,d=[],u=Ss,g){var k,x,j;const y=((k=t[0])==null?void 0:k.timestamp)??null,w=((x=r[0])==null?void 0:x.requestedAt)??((j=r[0])==null?void 0:j.updatedAt)??null,f=ft(y)>=ft(w)?y:w;return{connection:"connected",lastActivity:f?_t(f):null,lastSnapshotAt:c,snapshotVersion:l,sessions:e,activity:t,handoffs:s,decisions:r,sliceRuns:i,outbox:Xo(a),chat:Wr(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 Pa(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)=>ft(r.lastEventAt??r.lastHeartbeatAt)-ft(s.lastEventAt??s.lastHeartbeatAt))}function Oa(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 Nc(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)=>ft(r.lastActivityAt??r.updatedAt)-ft(s.lastActivityAt??s.updatedAt))}function Wr(e){if(!e||typeof e!="object")return Ss;const t=Nc(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 Ic(e,t){const s=e??Ss,r=t??Ss;if(s.total!==r.total||s.updatedAt!==r.updatedAt||s.threads.length!==r.threads.length)return!1;for(let i=0;i<s.threads.length;i+=1){const a=s.threads[i],c=r.threads[i];if(a.id!==c.id||a.status!==c.status||a.lastActivityAt!==c.lastActivityAt||a.lastSnippet!==c.lastSnippet||a.assigneeId!==c.assigneeId||a.launchCount!==c.launchCount||a.messageCount!==c.messageCount)return!1}return!0}function Ur(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map,s=(r,i)=>{const a=[],c=l=>{if(typeof l!="string")return;const d=l.trim();d&&(a.some(u=>u.toLowerCase()===d.toLowerCase())||a.push(d))};if(Array.isArray(r))for(const l of r)c(l);else if(typeof r=="string")for(const l of r.split(/[\n,;]+/g))c(l);return i&&c(i),a};for(const r of e){if(!r||typeof r!="object")continue;const i=typeof r.sliceRunId=="string"&&r.sliceRunId.trim().length>0?r.sliceRunId.trim():typeof r.id=="string"&&r.id.trim().length>0?r.id.trim():null;if(!i)continue;const a=s(r.initiativeIds,r.initiativeId??null),c=s(r.workstreamIds,r.workstreamId??null),l=s(r.iwmtIds,r.iwmtId??null),d=typeof r.initiativeId=="string"&&r.initiativeId.trim().length>0?r.initiativeId.trim():a[0]??null,u=typeof r.workstreamId=="string"&&r.workstreamId.trim().length>0?r.workstreamId.trim():c[0]??null,g=typeof r.iwmtId=="string"&&r.iwmtId.trim().length>0?r.iwmtId.trim():l[0]??null;t.set(i,{...r,id:i,sliceRunId:i,initiativeId:d,initiativeIds:a,workstreamId:u,workstreamIds:c,iwmtId:g,iwmtIds:l,artifacts:Array.isArray(r.artifacts)?r.artifacts:[],decisionOptions:Array.isArray(r.decisionOptions)?r.decisionOptions:[],taskIds:Array.isArray(r.taskIds)?r.taskIds:[],milestoneIds:Array.isArray(r.milestoneIds)?r.milestoneIds:[]})}return Array.from(t.values()).sort((r,i)=>ft(i.updatedAt??i.lastEventAt)-ft(r.updatedAt??r.lastEventAt))}function _r(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;if(!r)continue;const i=s.lineage&&typeof s.lineage=="object"?s.lineage:null;t.set(r,{...s,sliceRunId:r,consistencyFlags:Array.isArray(s.consistencyFlags)?s.consistencyFlags:[],lineage:{initiativeIds:Array.isArray(i==null?void 0:i.initiativeIds)?i.initiativeIds:[],initiativeTitles:Array.isArray(i==null?void 0:i.initiativeTitles)?i.initiativeTitles:[],workstreamIds:Array.isArray(i==null?void 0:i.workstreamIds)?i.workstreamIds:[],workstreamTitles:Array.isArray(i==null?void 0:i.workstreamTitles)?i.workstreamTitles:[],taskIds:Array.isArray(i==null?void 0:i.taskIds)?i.taskIds:[],milestoneIds:Array.isArray(i==null?void 0:i.milestoneIds)?i.milestoneIds:[],iwmtIds:Array.isArray(i==null?void 0:i.iwmtIds)?i.iwmtIds:[],sliceRunId:r,sessionId:typeof(i==null?void 0:i.sessionId)=="string"?i.sessionId:null},artifacts:Array.isArray(s.artifacts)?s.artifacts:[]})}return Array.from(t.values()).sort((s,r)=>ft(r.updatedAt??r.completedAt??r.failedAt)-ft(s.updatedAt??s.completedAt??s.failedAt))}function bi(e){if(!Array.isArray(e)||e.length===0)return[];const t=new Map;for(const s of e){if(!s||typeof s!="object")continue;const r=typeof s.sliceRunId=="string"&&s.sliceRunId.trim().length>0?s.sliceRunId.trim():null;r&&t.set(r,{...s,sliceRunId:r,highlights:Array.isArray(s.highlights)?s.highlights:[],technicalTrace:s.technicalTrace??{eventCount:0,eventIds:[]}})}return Array.from(t.values()).sort((s,r)=>ft(r.occurredAt)-ft(s.occurredAt))}function wi(e){return!Array.isArray(e)||e.length===0?[]:e.filter(t=>t&&typeof t=="object").map(t=>({initiativeId:typeof t.initiativeId=="string"&&t.initiativeId.trim().length>0?t.initiativeId.trim():null,initiativeTitle:typeof t.initiativeTitle=="string"&&t.initiativeTitle.trim().length>0?t.initiativeTitle.trim():"Unscoped initiative",pendingCount:typeof t.pendingCount=="number"&&Number.isFinite(t.pendingCount)?Math.max(0,Math.floor(t.pendingCount)):0,queue:Array.isArray(t.queue)?t.queue:[]})).sort((t,s)=>s.pendingCount-t.pendingCount)}function Ba(e){var s;if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const r of e){if(r.sliceKind!=="work_slice")continue;const i=r.lineage.initiativeIds[0]??null,a=r.lineage.workstreamIds[0]??null,c=r.lineage.workstreamTitles[0]??r.lineage.workstreamIds[0]??null,l=r.lifecycleState==="completed"&&r.outcomeState==="succeeded_without_artifacts"?"needs_review":r.lifecycleState,d=((s=r.actionContract)==null?void 0:s.actionType)??null,u=d==="open_artifact"||d==="open_logs"||d==="open_session"||d==="open_run"||d==="open_workstream"||d==="open_task"||d==="open_initiative"||d==="open_pr"||d==="open_diff"||d==="open_branch"?"open_artifact":d==="approve"||d==="reject"||d==="provide_context"||d==="request_info"||d==="confirm_scope"||d==="connect_provider"||d==="refresh_credentials"||d==="reassign"||d==="escalate"?"resolve_decision":d==="retry"||d==="resume"||d==="start"||d==="auto_fix"?"retry_slice":r.outcomeState==="succeeded_without_artifacts"?"review_output":"none";t.push({id:r.sliceRunId,sliceRunId:r.sliceRunId,runId:r.runId,initiativeId:i,initiativeIds:r.lineage.initiativeIds,workstreamId:a,workstreamIds:r.lineage.workstreamIds,iwmtId:r.lineage.iwmtIds[0]??null,iwmtIds:r.lineage.iwmtIds,workstreamTitle:c,taskIds:r.lineage.taskIds,milestoneIds:r.lineage.milestoneIds,status:l,statusExplainer:r.statusExplainer,primaryAction:u,hasArtifact:r.hasArtifact,artifactCount:r.artifactCount,artifacts:r.artifacts.map(g=>({id:g.artifactId,type:g.type,title:g.title,url:g.url,createdAt:g.producedAt})),decisionCount:r.outcomeState==="needs_input"?1:0,blockingDecisionCount:r.outcomeState==="needs_input"?1:0,decisionOptions:[],sourceClient:r.sourceClient,runtimeState:r.runtimeState,startedAt:null,updatedAt:r.updatedAt,completedAt:r.completedAt,failedAt:r.failedAt,archivedAt:r.archivedAt,lastEventAt:r.updatedAt,lastEventSummary:r.statusExplainer,correlationId:r.sliceRunId,confidence:r.confidence})}return Ur(t)}function Ac(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 Sc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.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 _c(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.sliceRunId!==i.sliceRunId||r.occurredAt!==i.occurredAt||r.outcome.state!==i.outcome.state||r.outcome.artifactCount!==i.outcome.artifactCount)return!1}return!0}function Cc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1){const r=e[s],i=t[s];if(r.initiativeId!==i.initiativeId||r.pendingCount!==i.pendingCount||r.queue.length!==i.queue.length)return!1}return!0}function Mc(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 Tc(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 Ec(e={}){const{enabled:t=!0,pollInterval:s=ec,useMock:r=!1,enableDecisions:i=!0,initiativeId:a=null,projectId:c=null,maxSessions:l=tc,maxActivityItems:d=nc,maxHandoffs:u=sc,maxDecisions:g=rc,batchWindowMs:y=ic}=e,w=typeof a=="string"&&a.trim().length>0?a.trim():null,f=typeof c=="string"&&c.trim().length>0?c.trim():null,[k,x]=o.useState(Sa()),[j,v]=o.useState(Ir),[b,h]=o.useState(!r),[_,V]=o.useState(null),oe=o.useRef(),K=o.useRef(null),be=o.useRef(null),[H,Z]=o.useState(!1),ce=o.useRef(0),ye=o.useRef(!1),we=o.useRef(`${w??"__all__"}::${f??"__all__"}`),W=o.useRef(!1),Ie=o.useRef(null),Te=o.useCallback((P,Y)=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null),v(P),Y!=null&&Y.autoResetMs&&Y.autoResetMs>0&&(Ie.current=setTimeout(()=>{Ie.current=null,v(Ir)},Y.autoResetMs))},[]);o.useEffect(()=>()=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null)},[]),o.useEffect(()=>{const P=`${w??"__all__"}::${f??"__all__"}`;we.current!==P&&(we.current=P,W.current=!0,Te(Ir),x(Y=>({...Y,sessions:{nodes:[],edges:[],groups:[]},activity:[],handoffs:[],decisions:[],sliceRuns:[],chat:Ss,runtimeInstances:[],workSliceProjections:[],timelineNarrative:[],nextUpByInitiative:[],runningWorkSlices:0,needsInputTotal:0,failedActionableTotal:0,completedTodayTotal:0,consistencyFlags:[],lastActivity:null,lastSnapshotAt:null,snapshotVersion:(Y.snapshotVersion??0)+1})),h(!0),V(null))},[w,f,Te]);const fe=o.useCallback((P,Y,ie,ve=null,je=null,te=null,Me=null,pe=null,M=null,O=null)=>{ce.current=Date.now(),ye.current=!1,x(U=>{const se=W.current;se&&(W.current=!1);const Re=Y===null?se?[]:U.activity:xi(Y,d),qe=ie===null?se?[]:U.handoffs:Ea(ie,u),Ce=sr(P===null?se?{nodes:[],edges:[],groups:[]}:U.sessions:se?sr(P,l):Ta(U.sessions,sr(P,l)),l),T=ve===null?se?[]:U.decisions:$a(ve,g),q=je===null?se?[]:U.sliceRuns:Ur(je),re=te===null?se?la:U.outbox:Xo(te),ue=pe===null?se?[]:U.runtimeInstances??[]:Pa(pe),_e=M===null?se?Ss:U.chat??Ss:Wr(M),Ye=(O==null?void 0:O.workSliceProjections)==null?se?[]:U.workSliceProjections??[]:_r(O.workSliceProjections),Ge=(O==null?void 0:O.timelineNarrative)==null?se?[]:U.timelineNarrative??[]:bi(O.timelineNarrative),$e=(O==null?void 0:O.nextUpByInitiative)==null?se?[]:U.nextUpByInitiative??[]:wi(O.nextUpByInitiative),Ke=typeof(O==null?void 0:O.runningWorkSlices)=="number"&&Number.isFinite(O.runningWorkSlices)?Math.max(0,Math.floor(O.runningWorkSlices)):U.runningWorkSlices??0,We=typeof(O==null?void 0:O.needsInputTotal)=="number"&&Number.isFinite(O.needsInputTotal)?Math.max(0,Math.floor(O.needsInputTotal)):U.needsInputTotal??0,ht=typeof(O==null?void 0:O.failedActionableTotal)=="number"&&Number.isFinite(O.failedActionableTotal)?Math.max(0,Math.floor(O.failedActionableTotal)):U.failedActionableTotal??0,st=typeof(O==null?void 0:O.completedTodayTotal)=="number"&&Number.isFinite(O.completedTodayTotal)?Math.max(0,Math.floor(O.completedTodayTotal)):U.completedTodayTotal??0,rt=(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,He=(U.snapshotVersion??0)+1;return Ra(U.sessions,Ce)&&Go(U.activity,Re)&&La(U.handoffs,qe)&&Da(U.decisions,T)&&Ac(U.sliceRuns,q)&&fc(U.outbox,re)&&Ic(U.chat,_e)&&Oa(U.runtimeInstances,ue)&&Sc(U.workSliceProjections??[],Ye)&&_c(U.timelineNarrative??[],Ge)&&Cc(U.nextUpByInitiative??[],$e)&&(U.runningWorkSlices??0)===Ke&&(U.needsInputTotal??0)===We&&(U.failedActionableTotal??0)===ht&&(U.completedTodayTotal??0)===st&&Mc(U.consistencyFlags??[],rt)&&Tc(U.dataHealth,ge)&&U.lastSnapshotAt===Me&&U.connection==="connected"?U:jc(Ce,Re,qe,T,q,re,Me,He,ue,_e,{workSliceProjections:Ye,timelineNarrative:Ge,nextUpByInitiative:$e,runningWorkSlices:Ke,needsInputTotal:We,failedActionableTotal:ht,completedTodayTotal:st,consistencyFlags:rt,dataHealth:ge})}),h(!1)},[d,g,u,l]),ee=o.useCallback(async()=>{if(!t){x(ie=>ie.connection==="disconnected"?ie:{...ie,connection:"disconnected"}),h(!1),V(null);return}const P=`${w??"__all__"}::${f??"__all__"}`;if(K.current&&be.current===P)return K.current;if(r){x(Sa()),h(!1);return}const Y=(async()=>{try{const ie=new URLSearchParams({sessionsLimit:String(l),activityLimit:String(d),decisionsLimit:String(g),include_idle:"true"});f&&ds(ie,f),w&&ie.set("initiative",w);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()}`}],je=[];let te=null,Me=!1;for(let Q=0;Q<ve.length;Q+=1){const Ne=ve[Q];Q>0&&await new Promise(De=>{setTimeout(De,oc)});const Le=await kc(Ne.url,{headers:St({workspaceId:f})},{timeoutMs:ac});if(Le.ok&&Le.data){te=Le.data;break}(Le.status===401||Le.status===403)&&(Me=!0),je.push(`${Ne.label}: ${Le.error??"unavailable"}`)}if(!te){if(Me){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(je))}if(we.current!==P)return;const pe=Array.isArray(te.degraded)?te.degraded.filter(Q=>typeof Q=="string"):[],M=pe.map(Q=>Q.toLowerCase()),O=(...Q)=>M.some(Ne=>Q.some(Le=>Ne.includes(Le))),U=Array.isArray(te.activity)?te.activity:[],se=Array.isArray(te.handoffs)?te.handoffs:[],Re=Array.isArray(te.decisions)?te.decisions:[],qe=U.length===0&&O("activity unavailable","activity local fallback failed"),Ce=O("sessions unavailable","sessions local fallback failed"),T=se.length===0&&O("handoffs unavailable"),q=Re.length===0&&O("decisions unavailable"),re=_r(Array.isArray(te.projections)?te.projections:[]),ue=Wr(te.chat??null),_e=bi(Array.isArray(te.timelineNarrative)?te.timelineNarrative:[]),Ye=wi(Array.isArray(te.nextUpByInitiative)?te.nextUpByInitiative:[]),Ge=re.length>0?Ba(re):Ur(Array.isArray(te.sliceRuns)?te.sliceRuns:[]),$e=te.sessions&&Array.isArray(te.sessions.nodes)&&Array.isArray(te.sessions.edges)&&Array.isArray(te.sessions.groups)?te.sessions:vc(U,te.agents,l),Ke=Ge.length===0&&re.length===0&&O("activity unavailable","sessions unavailable","decisions unavailable","next-up unavailable","next-up queue"),We=Ye.length===0&&O("next-up unavailable","next-up queue"),ht=qe?null:U,st=T?null:se,rt=q?null:Re,ge=Ce&&$e.nodes.length===0?null:$e,He=Ke?null:re,Ae=Ke?null:_e,B=Ke?null:Ge,Pe=We?null:Ye;fe(ge,ht,st,rt,B,te.outbox??null,te.generatedAt??null,te.runtimeInstances??null,ue,{workSliceProjections:He,timelineNarrative:Ae,nextUpByInitiative:Pe,runningWorkSlices:Ke?null:te.runningWorkSlices??null,needsInputTotal:Ke?null:te.needsInput??null,failedActionableTotal:Ke?null:te.failedActionable??null,completedTodayTotal:Ke?null:te.completedToday??null,consistencyFlags:Array.isArray(te.consistencyFlags)?te.consistencyFlags:null,dataHealth:te.dataHealth??null});const z=pe.length>0?uc(pe):[];z.length>0?(V(`Partial live data: ${z.join("; ")}`),x(Q=>Q.connection==="connected"?Q:{...Q,connection:"connected"}),Z(!1)):(V(null),x(Q=>Q.connection==="connected"?Q:{...Q,connection:"connected"}))}catch(ie){if(we.current!==P)return;const ve=ie instanceof Error?ie.message:"Unknown error",je=!!(ie&&typeof ie=="object"&&"code"in ie&&ie.code==="ORGX_AUTH");je&&(ye.current=!0);const te=ce.current>0&&Date.now()-ce.current>_a;V(ve),x(Me=>{const pe=je||te?"disconnected":"reconnecting";return Me.connection===pe?Me:{...Me,connection:pe}}),Z(!je),h(!1)}finally{be.current===P&&(K.current=null,be.current=null)}})();return K.current=Y,be.current=P,Y},[fe,t,i,d,g,u,l,f,w,r]),de=o.useCallback(async(P,Y,ie)=>{var M,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 je=((M=ie==null?void 0:ie.note)==null?void 0:M.trim())||void 0,te=((O=ie==null?void 0:ie.optionId)==null?void 0:O.trim())||void 0;if(r){const se=new Set(ve);return x(Re=>{const qe=Re.decisions.filter(re=>se.has(re.id));if(qe.length===0)return Re;const Ce=new Date().toISOString(),T=qe.map(re=>({id:`decision:${Y}:${re.id}:${Date.now()}`,type:"decision_resolved",title:Y==="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:Ce,metadata:{decisionId:re.id,action:Y}})),q=xi(T.concat(Re.activity),d);return{...Re,decisions:Re.decisions.filter(re=>!se.has(re.id)),activity:q,lastActivity:_t(Ce)}}),{updated:se.size,failed:0,firstError:void 0}}const Me=new Date().toISOString(),pe=await fetch("/orgx/api/live/decisions/approve",{method:"POST",headers:St({contentTypeJson:!0,workspaceId:f}),body:JSON.stringify({ids:ve,action:Y,...je?{note:je}:{},...te?{option_id:te}:{}})});try{const se=await pe.json().catch(()=>null),Re=Array.isArray(se==null?void 0:se.results)?se.results:[],qe=new Set(Re.filter(ue=>ue.ok).map(ue=>ue.id)),T=((U=Re.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?x(ue=>{const _e=ue.decisions.filter(We=>qe.has(We.id));if(_e.length===0)return ue;const Ye=new Date().toISOString(),Ge=_e.map(We=>({id:`decision:${Y}:${We.id}:${Date.now()}`,type:"decision_resolved",title:Y==="approve"?`Approved: ${We.title}`:`Rejected: ${We.title}`,description:We.context,agentId:null,agentName:We.agentName,requesterAgentId:null,requesterAgentName:We.agentName??null,executorAgentId:null,executorAgentName:We.agentName??null,runId:null,initiativeId:null,timestamp:Ye,metadata:{decisionId:We.id,action:Y}})),$e=xi(Ge.concat(ue.activity),d);return{...ue,decisions:ue.decisions.filter(We=>!qe.has(We.id)),activity:$e,lastActivity:_t(Ye)}}):pe.ok&&ve.length>0&&x(ue=>({...ue,decisions:ue.decisions.filter(_e=>!ve.includes(_e.id))})),ee();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 Te({phase:re>0?"error":"success",action:Y,targetCount:ve.length,message:re>0?`${Y==="approve"?"Approve":"Reject"} completed with ${re} failure${re===1?"":"s"}.`:Y==="approve"?`Approved ${q} decision${q===1?"":"s"}.`:`Rejected ${q} decision${q===1?"":"s"}.`,startedAt:Me,completedAt:new Date().toISOString()},{autoResetMs:re>0?8e3:4e3}),{updated:q,failed:re,firstError:T}}catch(se){throw Te({phase:"error",action:Y,targetCount:ve.length,message:se instanceof Error?se.message:"Decision update failed.",startedAt:Me,completedAt:new Date().toISOString()}),se}},[i,ee,d,f,Te,r]),Ee=o.useCallback(async(P,Y)=>de([P],"approve",Y),[de]),ne=o.useCallback(async(P,Y)=>de([P],"reject",Y),[de]),R=o.useCallback(async()=>{let P=[];return x(Y=>(P=Y.decisions.map(ie=>ie.id),Y)),P.length===0?{updated:0,failed:0}:de(P,"approve")},[de]),J=o.useCallback(async(P,Y,ie)=>de(P,Y,ie?{note:ie}:void 0),[de]);return o.useEffect(()=>{i||Te(Ir)},[i,Te]),o.useEffect(()=>{if(!t){Z(!1),h(!1),V(null);return}if(r){ee();return}if(ee(),f){Z(!0);return}const P=new URLSearchParams;f&&ds(P,f),w&&P.set("initiative",w);const Y=P.toString()?`/orgx/api/live/stream?${P.toString()}`:"/orgx/api/live/stream",ie=new EventSource(Y),ve=new EventSource("/orgx/api/hooks/runtime/stream");let je=null,te=null,Me=null,pe=null,M=[],O=null,U;const se=()=>{if(U=void 0,je){ce.current=Date.now(),ye.current=!1;const Ce=je;je=null,Me=null,pe=null,M=[],O=null,te=null,fe(Ce.sessions,Ce.activity,Ce.handoffs,Ce.decisions,Ce.sliceRuns,Ce.outbox,Ce.generatedAt,Ce.runtimeInstances,Ce.chat,Ce.v2);return}!Me&&!pe&&!O&&!te&&M.length===0||(ce.current=Date.now(),ye.current=!1,x(Ce=>{var q;let T=Ce;if(Me){const re=sr(Me,l),ue=sr(Ta(T.sessions,re),l);Me=null,Ra(T.sessions,ue)||(T={...T,sessions:ue})}if(pe){const re=Ea(pe,u);pe=null,La(T.handoffs,re)||(T={...T,handoffs:re})}if(O){const re=$a(O,g);O=null,Da(T.decisions,re)||(T={...T,decisions:re})}if(te){const re=Pa(te);te=null,Oa(T.runtimeInstances,re)||(T={...T,runtimeInstances:re})}if(M.length>0){const re=yc(T.activity,M,d);M=[],re!==T.activity&&(T={...T,activity:re,lastActivity:(q=re[0])!=null&&q.timestamp?_t(re[0].timestamp):T.lastActivity})}return T===Ce?Ce:T.connection==="connected"?T:{...T,connection:"connected"}}),V(null),h(!1))},Re=()=>{U||(U=setTimeout(se,y))};ie.onopen=()=>{ce.current=Date.now(),ye.current=!1,Z(!1),x(Ce=>Ce.connection==="connected"?Ce:{...Ce,connection:"connected"}),V(null)},ie.onerror=()=>{if(ye.current){x(T=>T.connection==="disconnected"?T:{...T,connection:"disconnected"}),Z(!1);return}const Ce=ce.current>0&&Date.now()-ce.current>_a;x(T=>T.connection===(Ce?"disconnected":"reconnecting")?T:{...T,connection:Ce?"disconnected":"reconnecting"}),Z(!0)},ie.addEventListener("snapshot",Ce=>{try{const T=JSON.parse(Ce.data),q=typeof T.generatedAt=="string"&&T.generatedAt.length>0?T.generatedAt:new Date().toISOString();je={sessions:T.sessions,activity:T.activity??[],handoffs:T.handoffs??[],decisions:T.decisions??null,sliceRuns:Array.isArray(T.sliceRuns)?Ur(T.sliceRuns):Array.isArray(T.projections)?Ba(_r(T.projections)):null,outbox:T.outbox??null,generatedAt:q,runtimeInstances:Array.isArray(T.runtimeInstances)?T.runtimeInstances:null,chat:Wr(T.chat??null),v2:{workSliceProjections:Array.isArray(T.projections)?_r(T.projections):null,timelineNarrative:Array.isArray(T.timelineNarrative)?bi(T.timelineNarrative):null,nextUpByInitiative:Array.isArray(T.nextUpByInitiative)?wi(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}},Re()}catch(T){V(T instanceof Error?T.message:"Invalid snapshot")}}),ie.addEventListener("activity.appended",Ce=>{try{const T=JSON.parse(Ce.data);if(T.length===0)return;M=M.concat(T),Re()}catch{}}),ie.addEventListener("session.updated",Ce=>{try{Me=JSON.parse(Ce.data),Re()}catch{}});const qe=Ce=>{try{const T=JSON.parse(Ce.data);te=Array.isArray(T)?T:[T],Re()}catch{}};return ie.addEventListener("runtime.updated",qe),ve.addEventListener("runtime.updated",qe),ie.addEventListener("handoff.updated",Ce=>{try{pe=JSON.parse(Ce.data),Re()}catch{}}),ie.addEventListener("decision.updated",Ce=>{try{O=JSON.parse(Ce.data),Re()}catch{}}),()=>{U&&clearTimeout(U),ie.close(),ve.close()}},[fe,y,t,i,ee,d,g,u,l,w,f,r]),o.useEffect(()=>{if(!(!t||r||(oe.current&&clearInterval(oe.current),!H&&!!!f)))return oe.current=setInterval(ee,s),()=>{oe.current&&clearInterval(oe.current)}},[t,ee,f,s,H,r]),{data:k,isLoading:b,error:_,refetch:ee,approveDecision:Ee,rejectDecision:ne,approveAllDecisions:R,bulkDecisionAction:J,decisionMutation:j}}const yr=[{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 Jo(e){return yr.find(t=>t.id===e)??yr[0]}function br(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=yr.find(r=>r.id===e);return!s||s.minutes===null?null:t-s.minutes*6e4}function Rc(e,t=Date.now()){const s=br(e,t);return s?new Date(s).toISOString():null}const Lc=new Set(["ungrouped","unscoped","unknown"]),Dc="orgx.demo_mode",$c="orgx.show_synthetic_entities";function Cs(e){const t=(e??"").trim().toLowerCase();return!!(!t||Lc.has(t)||/^init-\d+$/.test(t)||t.startsWith("mock-"))}function Lt(){if(typeof window>"u")return!1;try{if(new URLSearchParams(window.location.search).get("demo")==="1")return!0}catch{}try{return window.localStorage.getItem(Dc)==="1"}catch{return!1}}function Fc(){if(typeof window>"u")return!1;if(Lt())return!0;try{return window.localStorage.getItem($c)==="1"}catch{return!1}}function Pc(e){return Lt()?!0:!Cs(e)}function Qi(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Yo(e,t){const s=Qi(t.timestamp)-Qi(e.timestamp);return s!==0?s:String(t.id).localeCompare(String(e.id))}function Oc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Bc(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 Zo(e){const t=typeof e.initiativeId=="string"?e.initiativeId.trim():"";if(t.length>0)return t;const s=Oc(e.metadata);return Bc(s,["initiative_id","initiativeId"])}function vi(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ji(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(e===null||t===null)return e===t;if(typeof e!="object")return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let c=0;c<e.length;c+=1)if(!Ji(e[c],t[c]))return!1;return!0}const s=e,r=t,i=Object.keys(s).sort(),a=Object.keys(r).sort();if(i.length!==a.length)return!1;for(let c=0;c<i.length;c+=1){const l=i[c];if(l!==a[c]||!Ji(s[l],r[l]))return!1}return!0}const qc=typeof window<"u"&&/[?&]debug_feed/.test(window.location.search);function Hs(e,...t){}function zc(e,t,s,r){const i=new Map,a=t.sinceEpoch,c=t.untilEpoch;let l=0,d=0,u=0;for(const g of e??[]){if(!g||typeof g.id!="string")continue;if(s&&g.runId!==s){l++;continue}if(r&&Zo(g)!==r){d++;continue}const y=Qi(g.timestamp);if(y){if(a!==null&&y<a){u++;continue}if(c!==null&&y>c){u++;continue}i.set(g.id,g)}}return Hs("normalizeSeed",{inputCount:(e==null?void 0:e.length)??0,outputCount:i.size,runId:s,initiativeId:r,skippedRun:l,skippedInitiative:d,skippedTime:u,sinceEpoch:a?new Date(a).toISOString():null,untilEpoch:c?new Date(c).toISOString():null}),Array.from(i.values()).sort(Yo)}function qa(e,t){if(t.length===0)return e;const s=new Map;for(const c of e)s.set(c.id,c);let r=0,i=0,a=!1;for(const c of t){const l=s.get(c.id);if(!l){s.set(c.id,c),a=!0,r++;continue}(l.timestamp!==c.timestamp||l.type!==c.type||l.title!==c.title||l.description!==c.description||l.summary!==c.summary||!Ji(l.metadata??null,c.metadata??null))&&(s.set(c.id,c),a=!0,i++)}return Hs("mergeById",{currentCount:e.length,incomingCount:t.length,added:r,updated:i,changed:a,resultCount:s.size}),a?Array.from(s.values()).sort(Yo):e}function Wc(e){const{seed:t,timeFilterId:s,customSinceIso:r=null,customUntilIso:i=null,runId:a=null,initiativeId:c=null,projectId:l=null,pageSize:d=50,demoMode:u=Lt()}=e,g=o.useMemo(()=>vi(a),[a]),y=o.useMemo(()=>vi(c),[c]),w=o.useMemo(()=>vi(l),[l]),f=o.useMemo(()=>br(s),[s]),k=o.useMemo(()=>Rc(s),[s]),x=o.useMemo(()=>{if(s==="custom"){const R=(r==null?void 0:r.trim())??"";return R.length>0?R:null}return k},[r,k,s]),j=o.useMemo(()=>{if(s!=="custom")return null;const R=(i==null?void 0:i.trim())??"";return R.length>0?R:null},[i,s]),v=o.useMemo(()=>{if(x){const R=Date.parse(x);if(Number.isFinite(R))return R}return f},[f,x]),b=o.useMemo(()=>{if(!j)return null;const R=Date.parse(j);return Number.isFinite(R)?R:null},[j]),h=o.useMemo(()=>zc(t,{sinceEpoch:v,untilEpoch:b},g,y),[t,v,b,g,y]),_=u?null:"",[V,oe]=o.useState(h),[K,be]=o.useState(()=>_),[H,Z]=o.useState(!1),[ce,ye]=o.useState(null),[we,W]=o.useState(null),Ie=o.useRef(null),Te=o.useRef(!1),fe=o.useRef(h);fe.current=h;const ee=o.useMemo(()=>`${g??""}|${y??""}|${s}|${x??""}|${j??""}|${w??""}|${u?"demo":"live"}`,[g,y,s,x,j,w,u]),de=o.useRef(ee);o.useEffect(()=>{de.current!==ee&&(de.current=ee,Hs("RESET",{reason:"filter/run change",runId:g,initiativeId:y,projectId:w,timeFilterId:s,sinceIso:x,untilIso:j,seedCount:fe.current.length}),oe(fe.current),be(_),ye(null),W(null),Te.current=!1)},[ee,_,g,y,w,s,x,j]),o.useEffect(()=>{oe(R=>{const J=qa(R,h);return J!==R&&Hs("SSE_MERGE",{prevCount:R.length,seedCount:h.length,nextCount:J.length,delta:J.length-R.length}),J})},[h]);const Ee=o.useCallback(async()=>{if(u){be(null),ye(null);return}if(K===null)return;if(Ie.current)return Ie.current;Z(!0);const R=(async()=>{try{const J=new URLSearchParams;J.set("limit",String(Math.max(1,Math.min(500,d)))),K.trim().length>0&&J.set("cursor",K),x&&J.set("since",x),j&&J.set("until",j),g&&J.set("run",g),y&&J.set("initiative",y),w&&ds(J,w);const P=await fetch(`/orgx/api/live/activity/page?${J.toString()}`,{headers:St({workspaceId:w})}),Y=await P.json().catch(()=>null);if(!P.ok||!Y){const je=typeof(Y==null?void 0:Y.error)=="string"&&Y.error.trim()||typeof(Y==null?void 0:Y.message)=="string"&&Y.message.trim()||`Activity paging failed (${P.status})`;throw new Error(je)}const ie=Array.isArray(Y.activities)?Y.activities:[],ve=ie.filter(je=>!y||Zo(je)===y);Hs("PAGE_FETCH",{cursor:K,rawCount:ie.length,afterFilter:ve.length,filteredOut:ie.length-ve.length,initiativeId:y,runId:g,nextCursor:Y.nextCursor??null}),oe(je=>{const te=qa(je,ve);return Hs("PAGE_MERGE",{prevCount:je.length,pageCount:ve.length,nextCount:te.length,added:te.length-je.length}),te}),be(Y.nextCursor??null),W(Y.storeUpdatedAt??null),ye(null)}catch(J){const P=J instanceof Error?J.message:"";ye(P?Cn(P):"Activity paging failed"),be(Y=>Y===""?null:Y)}finally{Z(!1),Ie.current=null}})();return Ie.current=R,R},[K,u,y,d,w,g,x,j]);return o.useEffect(()=>{K===""&&(Te.current||(Te.current=!0,Ee()))},[K,Ee]),{items:V,hasMore:K!==null,isLoadingMore:H,error:ce,storeUpdatedAt:we,loadMore:Ee,cutoffEpoch:v,sinceIso:x,untilIso:j}}const Uc="phc_s4KPgkYEFZgvkMYw4zXG41H5FN6haVwbEWPYHfNjxOc",Hc="".trim().toLowerCase()==="true"||"".trim()==="1",Vc="".trim().toLowerCase()==="true"||"".trim()==="1",Kc={api_host:"https://us.i.posthog.com",defaults:"2026-01-30",person_profiles:"identified_only"};let ki=null,za=!1,Wa=!1,ca=!1;function Gc(){if(typeof window>"u")return!1;const e=window.location.hostname.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function li(){return ca||!Hc?!1:Vc?!0:!Gc()}function Xc(){return li()?(ki||(ki=qt(()=>import("./BgOYB78t.js"),[]).then(e=>e.default).catch(()=>(ca=!0,null))),ki):Promise.resolve(null)}function Qc(e){if(za)return!0;try{return e.init(Uc,Kc),za=!0,!0}catch{return ca=!0,!1}}async function da(){const e=await Xc();return!e||!Qc(e)?null:e}function Jc(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 Yc(){!li()||typeof window>"u"||Wa||(Wa=!0,Jc(()=>{da()}))}function Zc(e){if(!li())return;const t=e.trim();t&&da().then(s=>{if(s)try{s.identify(t)}catch{}})}function ss(e,t){li()&&e.trim()&&da().then(s=>{if(s)try{s.capture(e,t)}catch{}})}const ed="https://orgx.mintlify.site/guides/openclaw-plugin-setup",td=1500,ji="orgx.onboarding.skip",nd=680,sd=`<!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>`,Hr={status:"idle",hasApiKey:!1,connectionVerified:!1,workspaceName:null,lastError:null,nextAction:"connect",docsUrl:ed,keySource:"none",installationId:null,connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null};function qs(){return{...Hr,status:"connected",hasApiKey:!0,connectionVerified:!0,workspaceName:"Demo Workspace",nextAction:"open_dashboard",keySource:"legacy-dev",lastError:null}}function rd(e){if(typeof e=="string")return e;if(e&&typeof e=="object")return JSON.stringify(e)}async function rr(e){const t=await e,s=await t.json().catch(()=>null);return t.ok?s??{}:{ok:!1,error:rd(s==null?void 0:s.error)??`Request failed (${t.status})`}}function Cr(e){if(e)try{Zc(e)}catch{}}function id(){const[e,t]=o.useState(()=>Lt()?qs():Hr),[s,r]=o.useState(()=>!Lt()),[i,a]=o.useState(!1),[c,l]=o.useState(!1),d=o.useRef(null),[u,g]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(ji)==="1"),y=o.useCallback(async()=>{if(Lt()){const h=qs();return t(h),h}const b=await rr(fetch("/orgx/api/onboarding/status",{method:"GET"}));if(!b.ok||!b.data){const h=b.error??"Failed to load onboarding state",_={...Hr,status:"error",lastError:h,nextAction:"retry"};return t(_),_}return Cr(b.data.installationId??null),t(b.data),b.data},[]);o.useEffect(()=>{if(Lt()){t(qs()),r(!1);return}let b=!1;return(async()=>{r(!0);const h=await y();b||(t(h),r(!1))})(),()=>{b=!0}},[y]),o.useEffect(()=>{if(!(e.status==="awaiting_browser_auth"||e.status==="pairing"))return;const h=Math.max(900,e.pollIntervalMs??td),_=window.setInterval(async()=>{const V=await rr(fetch("/orgx/api/onboarding/status",{method:"GET"}));V.ok&&V.data&&(Cr(V.data.installationId??null),t(V.data))},h);return()=>{window.clearInterval(_)}},[e.pollIntervalMs,e.status]),o.useEffect(()=>{if(!(typeof window>"u")){if(u){window.localStorage.setItem(ji,"1");return}window.localStorage.removeItem(ji)}},[u]);const w=o.useCallback(()=>{if(typeof window>"u")return null;try{const b=window.open("","_blank");return b?(b.opener=null,b.document.title="Connecting to OrgX…",b.document.open(),b.document.write(sd),b.document.close(),b):null}catch{return null}},[]),f=o.useCallback(async()=>{if(Lt()){const h=qs();t(h);return}const b=w();d.current=b,a(!0);try{const h=await rr(fetch("/orgx/api/onboarding/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({deviceName:navigator.platform||"OpenClaw Device",platform:navigator.platform})})),_=h.data;if(!h.ok||!(_!=null&&_.state)){b&&!b.closed&&b.close();const oe=h.error??"Could not start pairing";t(K=>({...K,status:"error",lastError:oe,nextAction:"enter_manual_key"}));return}t(_.state);const V=_.connectUrl;if(V){const oe=d.current;let K=!1;if(oe&&!oe.closed)try{window.setTimeout(()=>{if(!oe.closed)try{oe.location.href=V}catch{}},nd),K=!0}catch{K=!1}K||(K=!!window.open(V,"_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)}},[w]),k=o.useCallback(async b=>{if(Lt()){const h=qs();return t(h),h}l(!0);try{const h=b.trim(),_=h.replace(/^[a-z]+_/i,""),V=Array.from(new Set([h,_?`oxk_${_}`:"",_?`orgx_${_}`:""].map(K=>K.trim()).filter(K=>K.length>0)));let oe="Manual key validation failed";for(const K of V){const be={"Content-Type":"application/json","X-OrgX-Api-Key":K,Authorization:`Bearer ${K}`},H=await rr(fetch("/orgx/api/onboarding/manual-key",{method:"POST",headers:be,body:JSON.stringify({apiKey:K})}));if(H.ok&&H.data)return Cr(H.data.installationId??null),t(H.data),H.data;oe=H.error??oe}throw t(K=>({...K,status:"manual_key",lastError:oe,nextAction:"enter_manual_key"})),new Error(oe)}finally{l(!1)}},[]),x=o.useCallback(async()=>{if(Lt()){const _=qs();return t(_),_}const b=await rr(fetch("/orgx/api/onboarding/disconnect",{method:"POST"}));if(b.ok&&b.data)return Cr(b.data.installationId??null),t(b.data),b.data;const h={...Hr,status:"idle"};return t(h),h},[]),j=o.useCallback(()=>{t(b=>({...b,status:"idle",lastError:null,nextAction:"connect",connectUrl:null,pairingId:null,expiresAt:null,pollIntervalMs:null}))},[]),v=o.useMemo(()=>Lt()||u?!1:!(e.hasApiKey&&e.connectionVerified&&e.status==="connected"),[u,e.connectionVerified,e.hasApiKey,e.status]);return{state:e,showGate:v,isLoading:s,isStarting:i,isSubmittingManual:c,refreshStatus:y,startPairing:f,submitManualKey:k,disconnect:x,skipGate:()=>g(!0),resumeGate:()=>g(!1),backToPairing:j,setManualMode:()=>t(b=>({...b,status:"manual_key",nextAction:"enter_manual_key"}))}}const Wn={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 ad extends Error{constructor(s,r){super(s);tr(this,"code","upgrade_required");tr(this,"currentPlan");tr(this,"requiredPlan");tr(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 od(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 ad(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 gh(e){const t=(e??"").trim().toLowerCase();return t?t==="free"?"Free":t==="starter"?"Starter":t==="team"?"Team":t==="enterprise"?"Enterprise":t[0].toUpperCase()+t.slice(1):"Unknown"}const ld=750;async function ir(e){return await e.json().catch(()=>null)}function cd(e,t){if(e.status!==404)return!1;const s=typeof(t==null?void 0:t.error)=="string"?t.error:"",r=typeof(t==null?void 0:t.message)=="string"?t.message:"";return/unknown api endpoint/i.test(`${s} ${r}`)}function Mr(e,t,s){if(cd(e,t))return`${s}. This queue route is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable.`;const r=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||s;return Cn(r)}function dd(e,t){const s=e instanceof Error?e.message:"",r=s.trim().toLowerCase();return r.includes("timed out")||r.includes("timeout")||r.includes("request cancelled")||r.includes("signal is aborted")?`${t}. Request timed out while waiting for queue data.`:r.includes("failed to fetch")||r.includes("network")?`${t}. Unable to reach the queue service right now.`:s?Cn(s):t}function ud(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 Vr({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 md(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 pd(e){if(!e.autoContinue)return!1;const t=e.autoContinue.status;if(t!=="running"&&t!=="stopping"||e.autoContinue.stopReason==="error")return!1;if(e.queueState==="running"||e.queueState==="blocked")return!0;const s=!!(e.autoContinue.activeRunId||e.autoContinue.activeTaskId),r=!!(Array.isArray(e.autoContinue.activeRunIds)&&e.autoContinue.activeRunIds.length>0);if(s||r)return!0;const i=Date.parse(e.autoContinue.updatedAt??"");return Number.isFinite(i)?Date.now()-i<=45e3:!1}function ua(e){const t=typeof e=="string"?e.trim():"";if(!t)return"unassigned";const s=t.toLowerCase();return s==="undefined"||s==="null"||s==="main"?"unassigned":t}function ma(e,t){const s=typeof e=="string"?e.trim():"";if(!s)return t==="unassigned"?"Unassigned":t;const r=s.toLowerCase();return r==="undefined"||r==="null"||r==="main"&&t==="unassigned"?t==="unassigned"?"Unassigned":t:s}function el(e,t,s){if(!Array.isArray(e))return t==="unassigned"?[]:[{id:t,name:s}];const r=[],i=new Set;for(const a of e){if(!a||typeof a!="object"||Array.isArray(a))continue;const c=a,l=ua(typeof c.id=="string"?c.id:null),d=ma(typeof c.name=="string"?c.name:null,l);if(l==="unassigned"&&d==="Unassigned")continue;const u=l.toLowerCase();i.has(u)||(i.add(u),r.push({id:l,name:d}))}return r.length===0&&t!=="unassigned"?[{id:t,name:s}]:r}function fd(e,t){return e==="assigned"||e==="inferred"||e==="fallback"?e:t==="unassigned"?"fallback":"inferred"}function hd(e){const t=ua(e.runnerAgentId),s=ma(e.runnerAgentName,t),r=el(e.runnerAgents,t,s),i=r[0]??null,a=(i==null?void 0:i.id)??t,c=(i==null?void 0:i.name)??s,l=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:c,runnerAgents:r,runnerSource:l,playbackState:e.queueState,autoIntentEnabled:pd(e),autoRuntimeState:md(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 Vr(e){const t=e.items.map(u=>hd(u)),s=typeof e.total=="number"&&Number.isFinite(e.total)?Math.max(e.total,t.length):t.length,r=e.pagination&&typeof e.pagination=="object"?e.pagination:null,i=r&&Number.isFinite(r.offset)?Math.max(0,Math.floor(r.offset)):0,a=r&&Number.isFinite(r.limit)?Math.max(1,Math.floor(r.limit)):Math.max(1,t.length),c=i+a<s,l=r&&typeof r.hasMore=="boolean"?r.hasMore:c,d=r&&typeof r.nextCursor=="string"?r.nextCursor:l?String(i+a):null;return{...e,items:t,total:s,pagination:{offset:i,limit:a,total:s,nextCursor:d,hasMore:l}}}function gd(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 xd(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 yd(e){var y,w,f,k,x,j,v,b,h,_,V,oe,K,be,H,Z;const t=((w=(y=e.lineage)==null?void 0:y.initiativeIds)==null?void 0:w.filter(ce=>typeof ce=="string"&&ce.trim().length>0))??[],s=((k=(f=e.lineage)==null?void 0:f.workstreamIds)==null?void 0:k.filter(ce=>typeof ce=="string"&&ce.trim().length>0))??[],r=((x=e.initiativeId)==null?void 0:x.trim())||t[0]||null,i=((j=e.workstreamId)==null?void 0:j.trim())||((b=(v=e.sourceWorkstreamIds)==null?void 0:v.find(ce=>typeof ce=="string"&&ce.trim().length>0))==null?void 0:b.trim())||s[0]||null;if(!r||!i)return null;const a=((_=(h=e.lineage)==null?void 0:h.taskIds)==null?void 0:_.filter(ce=>typeof ce=="string"&&ce.trim().length>0))??[],c=e.level==="workstream"||e.level==="milestone"||e.level==="task"?e.level:null,l=ua(e.runnerAgentId??null),d=ma(e.runnerAgentName??null,l),u=el(e.runnerAgents??null,l,d),g=u[0]??null;return{initiativeId:r,initiativeTitle:((V=e.initiativeTitle)==null?void 0:V.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())||((H=e.taskTitle)==null?void 0:H.trim())||xd(i),workstreamStatus:e.status,nextTaskId:e.taskId,nextTaskTitle:((Z=e.taskTitle)==null?void 0:Z.trim())||null,nextTaskPriority:typeof e.priorityNum=="number"?e.priorityNum:null,nextTaskDueAt:e.dueAt,runnerAgentId:(g==null?void 0:g.id)??l,runnerAgentName:(g==null?void 0:g.name)??d,runnerAgents:u,runnerSource:e.runnerSource??(g?"inferred":"fallback"),queueState:gd(e),blockReason:e.blockReason??null,queueOrigin:"system",sliceScope:c,sliceTaskIds:a.length>0?a:e.taskId?[e.taskId]:[],sliceTaskCount:a.length>0?a.length:e.taskId?1:0,sliceMilestoneId:e.milestoneId,executionPolicy:null,autoContinue:null}}function bd(e){const t=new Map;for(const s of e){const r=t.get(s.initiativeId);if(r){r.workstreamCount+=1,r.workstreamIds.push(s.workstreamId),r.items.push(s);for(const a of s.runnerAgents??[])r.runnerAgents.some(c=>c.id===a.id)||r.runnerAgents.push(a);const i=a=>a==="running"?3:a==="blocked"?2:a==="queued"?1:0;i(s.queueState)>i(r.queueState)&&(r.queueState=s.queueState)}else t.set(s.initiativeId,{initiativeId:s.initiativeId,initiativeTitle:s.initiativeTitle??s.initiativeId,initiativeStatus:s.initiativeStatus??"active",initiativePriority:typeof s.initiativePriority=="string"?s.initiativePriority:null,initiativePriorityNum:typeof s.initiativePriorityNum=="number"?s.initiativePriorityNum:null,workstreamCount:1,workstreamIds:[s.workstreamId],runnerAgents:[...s.runnerAgents??[]],queueState:s.queueState,items:[s]})}return Array.from(t.values())}function 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 vd({initiativeId:e=null,projectId:t=null,offset:s=0,limit:r=20,authToken:i=null,embedMode:a=!1,enabled:c=!0,snapshotVersion:l=null,zoomLevel:d="workstream"}){var ce,ye,we,W,Ie,Te,fe,ee,de,Ee;const u=oa(),g=Lt(),y=Math.max(0,s),w=Math.max(1,Math.min(300,r)),f=o.useRef(null);o.useEffect(()=>()=>{f.current&&(clearTimeout(f.current),f.current=null)},[]);const k=o.useMemo(()=>Wn.nextUpQueue({initiativeId:e,projectId:t,offset:y,limit:w,authToken:i,embedMode:a}),[e,t,y,w,i,a]),x=o.useRef(l);o.useEffect(()=>{l!==null&&x.current!==null&&l!==x.current&&u.invalidateQueries({queryKey:k}),x.current=l},[l,u,k]);const j=()=>{f.current&&(clearTimeout(f.current),f.current=null),f.current=setTimeout(()=>{f.current=null,u.invalidateQueries({queryKey:Wn.liveData({authToken:i,embedMode:a,projectId:t})})},ld)},v=async()=>{await Promise.all([u.invalidateQueries({queryKey:k}),u.invalidateQueries({queryKey:Wn.autoContinueStatus({initiativeId:e,authToken:i,embedMode:a})}),u.invalidateQueries({queryKey:Wn.missionControlGraph({initiativeId:e,authToken:i,embedMode:a})})]),j()},b=async(ne,R)=>{if(g)return ud(e);const J=new URLSearchParams;e&&J.set("initiative_id",e),ds(J,t,{allTokenWhenMissing:!0}),J.set("offset",String(ne)),J.set("limit",String(R));let P;try{P=await fetch(`/orgx/api/mission-control/next-up?${J.toString()}`,{headers:St({authToken:i,embedMode:a})})}catch(Me){throw new Error(dd(Me,"Failed to load next up queue"))}const Y=await ir(P);if(!P.ok){const Me=Mr(P,Y,"Failed to load next up queue");throw new Error(Me)}const ie=Y??null;if(!ie||ie.ok!==!0)return{ok:!0,generatedAt:new Date().toISOString(),total:0,items:[],pagination:{offset:ne,limit:R,total:0,nextCursor:null,hasMore:!1},degraded:["next-up queue response missing expected payload"]};if(Fc())return Vr(ie);const ve=ie.items.filter(Me=>!Cs(Me.initiativeId));let je=Vr({...ie,items:ve});if(je.items.length>0)return je;const te=new URLSearchParams;e&&te.set("initiative_id",e),ds(te,t,{allTokenWhenMissing:!0}),te.set("level","workstream"),te.set("include_completed","0"),te.set("offset",String(ne)),te.set("limit",String(Math.max(R,24)));try{const Me=await fetch(`/orgx/api/mission-control/slices?${te.toString()}`,{headers:St({authToken:i,embedMode:a})}),pe=await ir(Me);if(Me.ok&&(pe!=null&&pe.ok)&&Array.isArray(pe.items)){const M=pe.items.map(O=>yd(O)).filter(O=>!!O).filter(O=>!Cs(O.initiativeId));M.length>0&&(je=Vr({ok:!0,generatedAt:new Date().toISOString(),total:typeof pe.total=="number"&&Number.isFinite(pe.total)?Math.max(pe.total,M.length):M.length,items:M,pagination:pe.pagination&&typeof pe.pagination=="object"?{offset:typeof pe.pagination.offset=="number"?Math.max(0,Math.floor(pe.pagination.offset)):ne,limit:typeof pe.pagination.limit=="number"?Math.max(1,Math.floor(pe.pagination.limit)):Math.max(R,24),total:typeof pe.pagination.total=="number"?Math.max(0,Math.floor(pe.pagination.total)):M.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 je},h=cs({queryKey:k,enabled:c,queryFn:async()=>b(y,w),refetchInterval:ne=>{const R=ne.state.data;return!R||!Array.isArray(R.items)||R.items.length===0?1e4:R.items.some(P=>P.queueState==="running")?2500:8e3}}),_=o.useRef(null);o.useEffect(()=>{var J;const ne=(J=h.data)==null?void 0:J.pagination;if(!c||!(ne!=null&&ne.hasMore)||!ne.nextCursor||_.current===ne.nextCursor)return;const R=Number.parseInt(ne.nextCursor,10);Number.isFinite(R)&&(_.current=ne.nextCursor,u.prefetchQuery({queryKey:Wn.nextUpQueue({initiativeId:e,projectId:t,offset:R,limit:w,authToken:i,embedMode:a}),queryFn:()=>b(R,w),staleTime:15e3}))},[c,(ye=(ce=h.data)==null?void 0:ce.pagination)==null?void 0:ye.hasMore,(W=(we=h.data)==null?void 0:we.pagination)==null?void 0:W.nextCursor,e,t,w,i,a,u]);const V=yn({mutationFn:async ne=>{if(g)return{ok:!0,initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,dispatchMode:"slice",sessionId:null};const R=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:St({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:ne.initiativeId,workstreamId:ne.workstreamId,agentId:ne.agentId??void 0,scope:ne.scope??void 0,maxParallelSlices:typeof ne.maxParallelSlices=="number"&&Number.isFinite(ne.maxParallelSlices)?Math.max(1,Math.floor(ne.maxParallelSlices)):void 0,parallelMode:ne.parallelMode==="iwmt"?"iwmt":void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})}),J=await ir(R);if(!R.ok)throw new Error(Mr(R,J,"Failed to dispatch queued workstream"));return J},onMutate:async ne=>{await u.cancelQueries({queryKey:k});const R=u.getQueryData(k);return R?(u.setQueryData(k,{...R,items:R.items.map(J=>J.initiativeId===ne.initiativeId&&J.workstreamId===ne.workstreamId?{...J,queueState:"running",playbackState:"running"}:J.queueState==="running"?{...J,queueState:"idle",playbackState:"idle"}:J)}),{previous:R}):{previous:R}},onError:(ne,R,J)=>{J!=null&&J.previous&&u.setQueryData(k,J.previous)},onSuccess:()=>{v()}}),oe=yn({mutationFn:async ne=>{if(g)return;const R={initiativeId:ne.initiativeId,agentId:ne.agentId??void 0,tokenBudgetTokens:ne.tokenBudgetTokens,ignoreSpawnGuardRateLimit:!0};ne.scope==="workstream"&&ne.workstreamId&&(R.workstreamIds=[ne.workstreamId]),typeof ne.maxParallelSlices=="number"&&Number.isFinite(ne.maxParallelSlices)&&(R.maxParallelSlices=ne.maxParallelSlices),ne.parallelMode==="iwmt"&&(R.parallelMode=ne.parallelMode);const J=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:St({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify(R)}),P=await ir(J);if(!J.ok){const Y=od(P);throw Y||new Error(Mr(J,P,"Failed to start auto-continue"))}},onSuccess:()=>{v()}}),K=yn({mutationFn:async ne=>{if(g)return;const R=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:St({authToken:i,embedMode:a,contentTypeJson:!0}),body:JSON.stringify({initiativeId:ne.initiativeId})}),J=await ir(R);if(!R.ok)throw new Error(Mr(R,J,"Failed to stop auto-continue"))},onSuccess:()=>{v()}}),be=((Ie=h.data)==null?void 0:Ie.items)??[],H=o.useMemo(()=>d==="initiative"?bd(be):[],[be,d]),Z=o.useMemo(()=>d==="milestone"?wd(be):[],[be,d]);return{items:be,total:((Te=h.data)==null?void 0:Te.total)??0,pagination:((fe=h.data)==null?void 0:fe.pagination)??null,generatedAt:((ee=h.data)==null?void 0:ee.generatedAt)??null,degraded:((de=h.data)==null?void 0:de.degraded)??[],isLoading:h.isLoading,isFetching:h.isFetching,error:((Ee=h.error)==null?void 0:Ee.message)??null,refetch:h.refetch,playWorkstream:V.mutateAsync,startWorkstreamAutoContinue:oe.mutateAsync,stopInitiativeAutoContinue:K.mutateAsync,isPlaying:V.isPending,isStartingAutoContinue:oe.isPending,isStoppingAutoContinue:K.isPending,zoomLevel:d,initiativeGroups:H,milestoneGroups:Z}}const kd=750;async function sn(e){return await e.json().catch(()=>null)}function Us(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 rn(e,t,s){if(Us(e,t))return`${s}. This queue control is unavailable in the running plugin build.`;if(e.status===401||e.status===403)return`${s}. Reconnect OrgX authentication in Settings.`;if(e.status>=500)return`${s}. OrgX is temporarily unavailable. Try again in a moment.`;const r=typeof(t==null?void 0:t.error)=="string"&&t.error.trim()||typeof(t==null?void 0:t.message)=="string"&&t.message.trim()||`${s}.`;return Cn(r)}function jd(e){const t=e.authToken??null,s=e.embedMode??!1,r=Lt(),i=oa(),a=o.useRef(null);o.useEffect(()=>()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]);const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),a.current=setTimeout(()=>{a.current=null,i.invalidateQueries({queryKey:["live-data"]})},kd)},l=async()=>{await Promise.all([i.invalidateQueries({queryKey:["mission-control-next-up"]}),i.invalidateQueries({queryKey:["mission-control-graph"]}),i.invalidateQueries({queryKey:["mission-control-slices"]})]),c()},d=async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId,placement:b.placement??"top"};const h=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await sn(h);if(h.ok)return _;if(!Us(h,_))throw new Error(rn(h,_,"Failed to move Next Up item"));const V=await fetch("/orgx/api/mission-control/next-up",{headers:St({authToken:t,embedMode:s})}),oe=await sn(V);if(!V.ok)throw new Error(rn(V,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 H=be.findIndex(we=>we.initiativeId===b.initiativeId&&we.workstreamId===b.workstreamId);if(H===-1)return{ok:!0,fallback:"reorder-move-skip"};const[Z]=be.splice(H,1);(b.placement??"top")==="bottom"?be.push(Z):be.unshift(Z);const ce=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({order:be})}),ye=await sn(ce);if(!ce.ok)throw new Error(rn(ce,ye,"Failed to move Next Up item with reorder fallback"));return ye??{ok:!0,fallback:"reorder-move"}},u=async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId};const h=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await sn(h);if(h.ok)return _;if(Us(h,_)){const V=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),oe=await sn(V);if(!V.ok)throw new Error(rn(V,oe,"Failed to remove item from queue with legacy fallback"));return oe??{ok:!0,fallback:"next-up-unpin"}}throw new Error(rn(h,_,"Failed to remove item from queue"))},g=yn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0};const h=await fetch("/orgx/api/mission-control/next-up/pin",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await sn(h);if(!h.ok)throw new Error(rn(h,_,"Failed to pin Next Up item"))},onSuccess:()=>{l()}}),y=yn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0};const h=await fetch("/orgx/api/mission-control/next-up/unpin",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await sn(h);if(!h.ok)throw new Error(rn(h,_,"Failed to unpin Next Up item"))},onSuccess:()=>{l()}}),w=yn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,updated:b.order.length};const h=await fetch("/orgx/api/mission-control/next-up/reorder",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await sn(h);if(!h.ok)throw new Error(rn(h,_,"Failed to reorder Next Up queue"))},onSuccess:()=>{l()}}),f=yn({mutationFn:d,onSuccess:()=>{l()}}),k=yn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,initiativeId:b.initiativeId,workstreamId:b.workstreamId};const h=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await sn(h);if(!h.ok){if(Us(h,_)){const V=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:b.initiativeId})}),oe=await sn(V);if(!V.ok)throw new Error(rn(V,oe,"Failed to pause triage with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(rn(h,_,"Failed to stop triage"))}return _},onSuccess:()=>{l()}}),x=yn({mutationFn:u,onSuccess:()=>{l()}}),j=yn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,cleared:!0};const h=await fetch("/orgx/api/mission-control/next-up/clear",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await sn(h);if(!h.ok){if(Us(h,_)&&b.initiativeId){const V=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify({initiativeId:b.initiativeId})}),oe=await sn(V);if(!V.ok)throw new Error(rn(V,oe,"Failed to clear lifecycle state with legacy fallback"));return{ok:!0,fallback:"auto-continue-stop"}}throw new Error(rn(h,_,"Failed to clear Next Up lifecycle state"))}return _},onSuccess:()=>{l()}}),v=yn({mutationFn:async b=>{if(r)return{ok:!0,demo:!0,updated:b.items.length,failed:0,errors:[],fallback:"demo"};const h=await fetch("/orgx/api/mission-control/next-up/bulk",{method:"POST",headers:St({authToken:t,embedMode:s,contentTypeJson:!0}),body:JSON.stringify(b)}),_=await sn(h);if(!h.ok){if(!Us(h,_))throw new Error(rn(h,_,"Failed to apply bulk queue action"));const V=await Promise.all(b.items.map(async H=>{try{return b.action==="remove"?await u(H):await d({initiativeId:H.initiativeId,workstreamId:H.workstreamId,placement:b.action==="move_top"?"top":"bottom"}),{ok:!0,error:null}}catch(Z){return{ok:!1,error:Z instanceof Error?Z.message:"Queue action failed"}}})),oe=V.filter(H=>H.ok).length,K=V.length-oe,be=V.filter(H=>!H.ok&&H.error).map(H=>H.error);return{ok:K===0,updated:oe,failed:K,errors:be,fallback:"sequential"}}return _},onSuccess:()=>{l()}});return{pin:g.mutateAsync,unpin:y.mutateAsync,reorder:w.mutateAsync,move:f.mutateAsync,remove:x.mutateAsync,stopTriage:k.mutateAsync,clear:j.mutateAsync,bulk:v.mutateAsync,isPinning:g.isPending,isUnpinning:y.isPending,isReordering:w.isPending,isMoving:f.isPending,isRemoving:x.isPending,isStoppingTriage:k.isPending,isClearing:j.isPending,isBulking:v.isPending}}function tl(e,t){const s={"Content-Type":"application/json"};return e&&(s.Authorization=`Bearer ${e}`),t&&(s["X-OrgX-Embed"]="1"),s}async function Nd(e,t,s,r){const i=new URLSearchParams;e&&i.set("workspace_id",e),t&&i.set("status",t),i.set("limit","100");const a=`/orgx/api/live/triage?${i.toString()}`,c=await fetch(a,{headers:tl(s,r)});if(!c.ok)throw new Error(`Triage fetch failed: ${c.status}`);return c.json()}async function Id(e,t,s,r){const a=`/orgx/api/live/triage/action?${new URLSearchParams({id:e}).toString()}`,c=await fetch(a,{method:"POST",headers:tl(s,r),body:JSON.stringify(t)});if(!c.ok){const l=await c.json().catch(()=>({}));throw new Error(l.error??`Action failed: ${c.status}`)}return c.json()}function Ad(e={}){const{enabled:t=!0,workspaceId:s=null,status:r="open",authToken:i=null,embedMode:a=!1}=e,c=oa(),l=Wn.triageQueue({workspaceId:s,status:r,authToken:i,embedMode:a}),d=cs({queryKey:l,queryFn:()=>Nd(s,r,i,a),enabled:t,refetchInterval:8e3,staleTime:4e3}),u=yn({mutationFn:async({itemId:f,payload:k})=>Id(f,k,i,a),onSuccess:()=>{c.invalidateQueries({queryKey:l})}}),g=o.useCallback(async(f,k,x)=>u.mutateAsync({itemId:f,payload:{action:k,note:x==null?void 0:x.note,optionId:x==null?void 0:x.optionId,snoozeDurationMinutes:x==null?void 0:x.snoozeDurationMinutes}}),[u]),y=o.useMemo(()=>{var f,k,x;return{items:((f=d.data)==null?void 0:f.items)??[],total:((k=d.data)==null?void 0:k.total)??0,isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,degraded:((x=d.data)==null?void 0:x.degraded)??[],refetch:d.refetch}},[d]),w=o.useMemo(()=>({performAction:g,isActing:u.isPending,lastActionError:u.error?u.error.message:null}),[g,u.isPending,u.error]);return{model:y,actions:w}}function le(...e){return e.filter(Boolean).join(" ")}const E={lime:"#BFFF00",teal:"#14B8A6",cyan:"#0AD4C4",iris:"#7C7CFF",amber:"#F5B700",red:"#FF6B88",background:"#02040A",cardBg:"#08090D",cardBgElevated:"#0C0E14",cardBorderStrong:"rgba(255, 255, 255, 0.12)",textMuted:"#8F9AB7"},xh={active:{text:"rgba(223, 255, 156, 0.9)"},done:{text:"rgba(135, 255, 233, 0.9)"},blocked:{text:"rgba(255, 195, 208, 0.9)"},planned:{text:"rgba(236, 241, 255, 0.74)"}},Sd={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",System:"#14B8A6",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},_d={Pace:"Engineering",Eli:"Engineering",Dana:"Product Design",Mark:"Marketing",System:"System",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"};function Cd(e){return Sd[e]??"rgba(255, 255, 255, 0.4)"}function nl(e){return _d[e]??null}function Md(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}function Ot(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_")}const Dt={durationFast:150,durationStandard:220,durationEntrance:360,easingStandard:[.22,1,.36,1],easingEntrance:[.16,1,.3,1],easingBounce:{type:"spring",stiffness:320,damping:28,mass:.7}},yh={surfaceSwitch:{duration:Dt.durationStandard/1e3,ease:Dt.easingStandard},contentCrossFade:{initial:{opacity:0,y:3},animate:{opacity:1,y:0},exit:{opacity:0,y:-3},transition:{duration:Dt.durationFast/1e3,ease:Dt.easingStandard}},railMorphSpring:{type:"spring",stiffness:340,damping:38,mass:.72},listStaggerStep:.016,listStaggerMaxItems:6,segmentedTap:{whileTap:{scale:.985},transition:{duration:.09}}},Tr={hidden:{opacity:0,y:8},visible:e=>({opacity:1,y:0,transition:{delay:Math.min(e,8)*.04,duration:Dt.durationStandard/1e3,ease:Dt.easingStandard}})},bh={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15}},ci="/orgx/live/assets/Fm0FhtnV.png";function sl({size:e=14,className:t="",stroke:s="currentColor",strokeWidth:r=1.8,withBackground:i=!1,backgroundColor:a="transparent"}){return n.jsxs("svg",{className:t,width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:s,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:r,children:[i?n.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"6",fill:a,stroke:"none"}):null,n.jsx("path",{d:"M6 6c3 0 5 6 8 6"}),n.jsx("path",{d:"M6 18c3 0 5-6 8-6"}),n.jsx("path",{d:"M6 12h12"}),n.jsx("path",{d:"m14 8 4 4-4 4"}),n.jsx("circle",{cx:"6",cy:"6",r:"1.5",fill:s,stroke:"none"}),n.jsx("circle",{cx:"6",cy:"12",r:"1.5",fill:s,stroke:"none"}),n.jsx("circle",{cx:"6",cy:"18",r:"1.5",fill:s,stroke:"none"})]})}function 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 c=r??E.iris;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${c}1A`}),n.jsx("circle",{cx:"12",cy:"12",r:"5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:c,stroke:"none"})]})}if(e==="workstream"){const c=r??E.lime;return n.jsx(sl,{size:s,className:t,stroke:c,strokeWidth:i.strokeWidth,withBackground:!0,backgroundColor:`${c}1A`})}if(e==="milestone"){const c=r??E.teal;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1z",fill:`${c}1A`})]})}if(e==="task")return n.jsxs("svg",{...i,stroke:"rgba(255,255,255,0.76)",children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"4",fill:"rgba(255,255,255,0.12)"}),n.jsx("path",{d:"M9 12.2 11 14.2 15.2 10"})]});if(e==="decision"){const c=r??E.amber;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("path",{d:"M12 3 5.2 6.1v5.7c0 4.8 3.2 7.5 6.8 9 3.6-1.5 6.8-4.2 6.8-9V6.1z",fill:`${c}1A`}),n.jsx("path",{d:"m9.3 12.1 1.8 1.9 3.6-3.6"})]})}if(e==="session"){const c=r??E.teal;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"4",fill:`${c}14`}),n.jsx("path",{d:"M8 9h8"}),n.jsx("path",{d:"M8 13h5"}),n.jsx("path",{d:"M8 17h3"})]})}if(e==="active"){const c=r??E.lime;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${c}12`}),n.jsx("path",{d:"M7 13h2l1.6-6 3.1 12 1.6-6H17"})]})}if(e==="blocked"){const c=r??E.red;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"6",fill:`${c}12`}),n.jsx("rect",{x:"7.5",y:"11",width:"9",height:"7",rx:"2",fill:"rgba(255,255,255,0.03)"}),n.jsx("path",{d:"M9 11V9.2a3 3 0 0 1 6 0V11"})]})}if(e==="failed"){const c=r??E.red;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9",fill:`${c}12`}),n.jsx("path",{d:"M9 9l6 6"}),n.jsx("path",{d:"M15 9l-6 6"})]})}if(e==="handoff"){const c=r??E.iris;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("path",{d:"M7 12h10"}),n.jsx("path",{d:"m13 8 4 4-4 4"}),n.jsx("path",{d:"M7 8v8",opacity:"0.55"})]})}if(e==="outbox"){const c=r??E.amber;return n.jsxs("svg",{...i,stroke:c,children:[n.jsx("path",{d:"M4 12h16"}),n.jsx("path",{d:"M6 7h12l2 5v7a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-7z",fill:`${c}12`}),n.jsx("path",{d:"M9 14h6"})]})}const a=r??E.cyan;return n.jsxs("svg",{...i,stroke:a,children:[n.jsx("path",{d:"M12 3a6 6 0 0 0-6 6v2.9c0 .7-.3 1.4-.8 1.9L4 15.2h16l-1.2-1.4a2.8 2.8 0 0 1-.8-1.9V9a6 6 0 0 0-6-6z",fill:`${a}1A`}),n.jsx("path",{d:"M9.2 18a2.8 2.8 0 0 0 5.6 0"})]})}const Td=[{label:"Model Routing",desc:"Right model, right cost, every prompt",iconType:"initiative"},{label:"Live Operations",desc:"Decisions, handoffs, sessions in real time",iconType:"workstream"},{label:"Quality Gates",desc:"Automated checkpoints before shipping",iconType:"milestone"}],Kr=[{id:"hierarchy",kicker:"Mission Control",title:"Map the full execution ladder in one place",description:"Trace initiatives through workstreams, milestones, and tasks with sticky context, dependency mapping, and inline edits.",highlights:[{type:"initiative",label:"Initiative",detail:"Top-level outcomes with owner and status."},{type:"workstream",label:"Workstream",detail:"Operational lanes and runner context."},{type:"milestone",label:"Milestone",detail:"Checkpoints that gate readiness."},{type:"task",label:"Task",detail:"Priority, ETA, budget, and dependencies."}],footnote:"Use the hierarchy filters to isolate open, blocked, or done work instantly."},{id:"activity",kicker:"Activity + Decisions",title:"Stay in flow while execution evolves",description:"Track agent output as it happens, review decision payloads, and keep operational context attached from plan to completion.",highlights:[{type:"notification",label:"Live feed",detail:"Messages, failures, and progress in one stream."},{type:"decision",label:"Decision queue",detail:"Approve or reject with full execution context."},{type:"workstream",label:"Handoffs",detail:"Runner transitions across domains and tasks."},{type:"task",label:"Artifacts",detail:"Completion evidence attached where it belongs."}],footnote:"Focus a session to pin a run while the rest of the org remains visible."},{id:"dispatch",kicker:"Autopilot + Next Up",title:"Dispatch work confidently with clear guardrails",description:"Queue the next workstream, open the owning initiative instantly, and escalate from manual play to controlled auto-continue.",highlights:[{type:"workstream",label:"Next Up",detail:"Queued workstreams with resolved runner and next task."},{type:"initiative",label:"Open target",detail:"Jump to the owning initiative and sticky hierarchy."},{type:"milestone",label:"Guardrails",detail:"Blocked states are surfaced before dispatch."},{type:"notification",label:"System notices",detail:"Inline success and failure feedback loops."}],footnote:"Start with Play, then enable auto-continue when queue health is stable."}],Ed=[{type:"initiative",label:"Live Initiative Sync",detail:"Initiatives and ownership stay aligned with OpenClaw execution."},{type:"decision",label:"Decision Control",detail:"Review approvals in-app without losing mission context."},{type:"workstream",label:"Queue Visibility",detail:"Understand what runs next, who runs it, and why."}],Ua="openclaw plugins install @useorgx/openclaw-plugin",Ha="orgx.demo_mode",Rd=6500;function Ld(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 Dd={hidden:{},visible:{transition:{staggerChildren:.07}}},rs={hidden:{opacity:0,y:14},visible:{opacity:1,y:0,transition:{duration:.45,ease:[.16,1,.3,1]}}},$d={initiative:"text-[#A8A0FF]",workstream:"text-[#BFFF00]",milestone:"text-[#43E7D8]",task:"text-primary",session:"text-[#43E7D8]",active:"text-[#BFFF00]",blocked:"text-[#FF6B88]",failed:"text-[#FF6B88]",handoff:"text-[#A8A0FF]",outbox:"text-[#F5D37A]",decision:"text-[#F5D37A]",notification:"text-[#7EEDE1]"};function Ni(e){const t=Kr.length;return(e+t)%t}function Fd({state:e,isStarting:t,onConnect:s,onUseManualKey:r,onContinueWithoutOrgX:i}){const a=!!e.lastError,[c,l]=o.useState("idle"),[d,u]=o.useState("idle"),[g,y]=o.useState(0),[w,f]=o.useState(!1),k=e.hasApiKey&&e.keySource&&e.keySource!=="none",x=Kr[g];o.useEffect(()=>{if(c==="idle")return;const b=window.setTimeout(()=>l("idle"),2e3);return()=>window.clearTimeout(b)},[c]),o.useEffect(()=>{if(d==="idle")return;const b=window.setTimeout(()=>u("idle"),2e3);return()=>window.clearTimeout(b)},[d]),o.useEffect(()=>{if(w)return;const b=window.setInterval(()=>{y(h=>Ni(h+1))},Rd);return()=>window.clearInterval(b)},[w]);const j=async()=>{try{await navigator.clipboard.writeText(Ua),l("ok")}catch{l("error")}},v=async()=>{try{const b={at:new Date().toISOString(),onboarding:{status:e.status,nextAction:e.nextAction,hasApiKey:e.hasApiKey,keySource:e.keySource,installationId:e.installationId,lastError:e.lastError},page:typeof window<"u"?window.location.href:null,userAgent:typeof navigator<"u"?navigator.userAgent:null};await navigator.clipboard.writeText(JSON.stringify(b,null,2)),u("ok")}catch{u("error")}};return n.jsxs(he.section,{variants:Dd,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:rs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:ci,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsxs(he.h2,{variants:rs,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:rs,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:rs,className:"space-y-2.5",children:[n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] p-3.5",onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(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:[g+1,"/",Kr.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:x.kicker}),n.jsx("h3",{className:"text-title font-semibold leading-snug text-white/94",children:x.title}),n.jsx("p",{className:"text-body leading-relaxed text-secondary",children:x.description}),n.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:x.highlights.map(b=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(bn,{type:b.type,size:12,className:"flex-shrink-0 opacity-92"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:b.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:b.detail})]},`${x.id}-${b.label}`))}),n.jsx("p",{className:"text-micro leading-relaxed text-muted",children:x.footnote})]},x.id)}),n.jsxs("div",{className:"mt-1.5 flex items-center justify-between",children:[n.jsx("div",{className:"flex items-center gap-1.5",children:Kr.map((b,h)=>{const _=h===g;return n.jsx("button",{type:"button",onClick:()=>y(h),"aria-label":`View slide ${h+1}`,className:`h-1.5 rounded-full transition-all ${_?"w-6 bg-[#BFFF00]":"w-2 bg-white/24 hover:bg-white/38"}`},b.id)})}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:()=>y(b=>Ni(b-1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Prev"}),n.jsx("button",{type:"button",onClick:()=>y(b=>Ni(b+1)),className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Next"})]})]})]}),n.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-3",children:Td.map(b=>n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.025] px-3 py-2.5",children:[n.jsx("div",{className:`mb-1.5 ${$d[b.iconType]}`,children:n.jsx(bn,{type:b.iconType,size:15})}),n.jsx("p",{className:"text-caption font-semibold text-white",children:b.label}),n.jsx("p",{className:"mt-0.5 text-micro leading-snug text-white/44",children:b.desc})]},b.label))}),n.jsxs(he.div,{variants:rs,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:rs,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:Ua}),n.jsx("button",{type:"button",onClick:()=>{j()},className:"rounded-full border border-strong px-3 py-1 text-caption text-secondary transition hover:border-white/[0.2] hover:text-bright",children:c==="ok"?"Copied":c==="error"?"Copy failed":"Copy command"})]}),k&&n.jsxs("p",{className:"mt-2 text-caption text-secondary",children:["API key source detected: ",Ld(e.keySource)]})]}),n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3",children:[n.jsx("p",{className:"text-caption uppercase tracking-[0.08em] text-muted",children:"What Unlocks After Connect"}),n.jsx("div",{className:"mt-2 space-y-1.5",children:Ed.map(b=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(bn,{type:b.type,size:12,className:"flex-shrink-0 opacity-90"}),n.jsx("p",{className:"text-caption font-semibold text-bright",children:b.label})]}),n.jsx("p",{className:"mt-0.5 text-micro leading-relaxed text-secondary",children:b.detail})]},b.label))})]})]})]}),n.jsx(he.div,{variants:rs,className:"mx-6 mt-2 sm:mx-8",children:a?n.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-red-500/15 bg-red-500/[0.04] px-4 py-3",children:[n.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500/15",children:n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:n.jsx("path",{d:"M5 2.5v3M5 7.5h.004",stroke:"#FF6B88",strokeWidth:"1.4",strokeLinecap:"round"})})}),n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx("p",{className:"text-body text-red-300/80",children:e.lastError})}),n.jsxs("div",{className:"flex flex-shrink-0 items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void v(),className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",title:"Copy debug details for support",children:d==="ok"?"Copied":d==="error"?"Copy failed":"Copy debug"}),n.jsx("button",{type:"button",onClick:r,className:"rounded-full border border-strong bg-white/[0.04] px-3 py-1 text-caption font-medium text-primary transition hover:bg-white/[0.08] hover:text-white",children:"Use API key"}),n.jsx("button",{type:"button",onClick:s,disabled:t,className:"rounded-full border border-red-500/20 bg-red-500/[0.06] px-3 py-1 text-caption font-semibold text-red-200/85 transition hover:bg-red-500/[0.09] hover:text-red-100 disabled:opacity-50",children:"Retry"})]})]}):n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-subtle bg-white/[0.02] px-3.5 py-2",children:[n.jsx("span",{className:"relative flex h-1.5 w-1.5",children:n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-white/40"})}),n.jsx("span",{className:"text-body text-muted",children:"Ready to connect"})]})}),n.jsxs(he.div,{variants:rs,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(Ha,"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(Ha)}catch{}i()},className:"text-left text-caption text-faint transition hover:text-secondary",children:"Continue offline"})]}),n.jsxs("a",{href:e.docsUrl,target:"_blank",rel:"noopener noreferrer",className:"group inline-flex items-center gap-1 text-caption text-muted transition hover:text-secondary",children:["Setup guide",n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:"transition-transform group-hover:translate-x-0.5",children:n.jsx("path",{d:"M3.5 2.5l3 2.5-3 2.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})]})}const Pd={hidden:{},visible:{transition:{staggerChildren:.06}}},vs={hidden:{opacity:0,y:10},visible:{opacity:1,y:0,transition:{duration:.35,ease:[.16,1,.3,1]}}};function Od({isSubmitting:e,onSubmit:t,onBack:s}){const[r,i]=o.useState(""),[a,c]=o.useState(null),l="https://www.useorgx.com/settings#security",d=async()=>{c(null);const g=r.trim();if(!g){c("API key is required.");return}const y=/^[a-z]+_/i.test(g)?g:`oxk_${g}`;try{await t(y),i("")}catch(w){c(w instanceof Error?w.message:"Failed to validate API key.")}},u=a!==null;return n.jsxs(he.section,{variants:Pd,initial:"hidden",animate:"visible",className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] soft-shadow rounded-2xl",children:[n.jsxs("div",{className:"px-6 pt-6 sm:px-8 sm:pt-8",children:[n.jsxs(he.div,{variants:vs,className:"flex items-center gap-2.5",children:[n.jsx("img",{src:ci,alt:"OrgX",className:"h-7 w-7 rounded-lg object-contain"}),n.jsx("span",{className:"text-body font-semibold text-primary",children:"OrgX"})]}),n.jsx(he.h3,{variants:vs,className:"mt-5 text-[22px] font-semibold tracking-[-0.02em] text-white",children:"Manual API key"}),n.jsxs(he.p,{variants:vs,className:"mt-1.5 text-heading leading-relaxed text-secondary",children:["Paste a key from your ",n.jsx("span",{className:"text-secondary",children:"useorgx.com"})," dashboard. Browser pairing is recommended."]}),n.jsxs(he.p,{variants:vs,className:"mt-1 text-body text-muted",children:["Paste full key or only the part after ",n.jsx("span",{className:"font-mono text-secondary",children:"oxk_"}),"."]}),n.jsx(he.div,{variants:vs,className:"mt-3",children:n.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 rounded-full border border-white/[0.10] bg-white/[0.03] px-3 py-1.5 text-body font-semibold text-secondary transition hover:bg-white/[0.06] hover:text-primary",title:"Open OrgX settings to generate an API key",children:["Generate an API key",n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",children:[n.jsx("path",{d:"M4.5 2.5h5v5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M9.5 2.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"}),n.jsx("path",{d:"M2.75 3.5H2.5c-.55 0-1 .45-1 1v5c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})]})]})})]}),n.jsxs(he.div,{variants:vs,className:"mt-6 space-y-4 px-6 sm:px-8",children:[n.jsxs("label",{className:"block",children:[n.jsx("span",{className:"mb-1.5 block text-caption font-medium uppercase tracking-[0.14em] text-muted",children:"API key"}),n.jsxs("div",{className:`flex items-stretch overflow-hidden rounded-xl border transition-colors focus-within:border-[#BFFF00]/40 ${u?"border-red-500/30":"border-white/[0.08]"}`,children:[n.jsx("span",{className:"flex items-center border-r border-subtle bg-white/[0.03] px-3 font-mono text-body text-faint select-none",children:"oxk_"}),n.jsx("input",{value:r,onChange:g=>{i(g.target.value),a&&c(null)},placeholder:"paste your key",className:"w-full bg-transparent px-3 py-2.5 font-mono text-body text-white outline-none placeholder:text-faint"})]}),u&&n.jsx(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:vs,className:"mt-6 flex flex-wrap items-center gap-3 px-6 sm:px-8",children:[n.jsx("button",{type:"button",onClick:()=>{d()},disabled:e,className:"inline-flex items-center gap-2 rounded-full bg-[#BFFF00] px-5 py-2.5 text-body font-semibold text-black shadow-[0_0_24px_rgba(191,255,0,0.12)] transition-all hover:bg-[#d3ff42] hover:shadow-[0_0_32px_rgba(191,255,0,0.22)] disabled:cursor-not-allowed disabled:opacity-50",children:e?n.jsxs(n.Fragment,{children:[n.jsxs("svg",{className:"h-3.5 w-3.5 animate-spin",viewBox:"0 0 16 16",fill:"none",children:[n.jsx("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",opacity:"0.2"}),n.jsx("path",{d:"M14 8a6 6 0 00-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),"Validating..."]}):"Validate & Connect"}),n.jsx("button",{type:"button",onClick:s,className:"rounded-full border border-white/[0.1] px-4 py-2 text-body text-secondary transition hover:border-white/[0.18] hover:text-bright",children:"Back to pairing"})]}),n.jsx("div",{className:"mt-6 border-t border-subtle px-6 py-4 sm:px-8",children:n.jsx("p",{className:"text-body text-faint",children:"Keys are stored locally and never leave your device."})})]})}const Va="orgx.user.display-name",Ka="orgx.user.avatar-seed-suffix";function Ga(e){return typeof window>"u"?"":window.localStorage.getItem(e)??""}function Xa(e,t){typeof window>"u"||(t?window.localStorage.setItem(e,t):window.localStorage.removeItem(e))}function Bd(){const[e,t]=o.useState(()=>Ga(Va)),[s,r]=o.useState(()=>Ga(Ka)),i=(e||"orgx-user")+s,a=o.useCallback(l=>{const d=l.trim();Xa(Va,d),t(d)},[]),c=o.useCallback(()=>{const l=String(Date.now());Xa(Ka,l),r(l)},[]);return{displayName:e,avatarSeed:i,updateName:a,regenerateAvatar:c}}function qd(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)>>>0;return t}function zd(e){let t=e|0;return()=>{t=t+1831565813|0;let s=Math.imul(t^t>>>15,1|t);return s=s+Math.imul(s^s>>>7,61|s)^s,((s^s>>>14)>>>0)/4294967296}}const Qa=[E.lime,E.teal,E.iris,E.cyan];function Wd(e,t,s,r,i,a){const c=_=>_*Math.PI/180,l=Math.cos,d=Math.sin,u=c(i),g=c(a),y=a-i>180?1:0,w=e+r*l(u),f=t+r*d(u),k=e+r*l(g),x=t+r*d(g),j=e+s*l(g),v=t+s*d(g),b=e+s*l(u),h=t+s*d(u);return[`M ${w} ${f}`,`A ${r} ${r} 0 ${y} 1 ${k} ${x}`,`L ${j} ${v}`,`A ${s} ${s} 0 ${y} 0 ${b} ${h}`,"Z"].join(" ")}function Ud(e){const t=zd(qd(e)),s=3+Math.floor(t()*2),r=[],i=50,a=50;for(let c=0;c<s;c++){const l=8+c*10,d=l+9,u=6+Math.floor(t()*6),g=360/u,y=1.5+t()*2;for(let w=0;w<u;w++){if(t()<.15)continue;const f=w*g+y/2,k=(w+1)*g-y/2,x=Qa[Math.floor(t()*Qa.length)],j=.25+t()*.55;r.push({d:Wd(i,a,l,d,f,k),fill:x,opacity:j})}}return r}function Hd({seed:e,size:t,className:s,animate:r=!0}){const i=o.useMemo(()=>Ud(e),[e]);return n.jsxs(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:Dt.easingEntrance},children:[n.jsxs("defs",{children:[n.jsx("clipPath",{id:`avatar-clip-${e}`,children:n.jsx("circle",{cx:"50",cy:"50",r:"48"})}),n.jsxs("radialGradient",{id:`avatar-glow-${e}`,cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:E.lime,stopOpacity:"0.08"}),n.jsx("stop",{offset:"100%",stopColor:E.lime,stopOpacity:"0"})]})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:E.cardBg}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#avatar-glow-${e})`}),n.jsx("g",{clipPath:`url(#avatar-clip-${e})`,children:i.map((a,c)=>n.jsx(he.path,{d:a.d,fill:a.fill,initial:r?{opacity:0,scale:.85}:!1,animate:{opacity:a.opacity,scale:1},transition:{delay:c*.012,duration:.35,ease:Dt.easingEntrance},style:{transformOrigin:"50px 50px"}},c))}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:"1"})]},e)}function Vd({onComplete:e}){const{displayName:t,updateName:s}=Bd(),[r,i]=o.useState(t),a=o.useCallback(()=>{s(r),e()},[r,s,e]),c=o.useCallback(()=>{e()},[e]),l=o.useCallback(u=>{u.key==="Enter"&&a()},[a]),d=(r.trim()||"orgx-user")+"";return n.jsx(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:Dt.easingEntrance},className:"flex items-center justify-center",children:n.jsx("div",{className:"w-full max-w-md rounded-2xl border border-white/[0.08] bg-[--orgx-surface-elevated] p-6 sm:p-8",children:n.jsxs("div",{className:"flex flex-col items-center text-center",children:[n.jsx(Hd,{seed:d,size:96}),n.jsx("h2",{className:"mt-5 text-title font-medium text-white",children:"Welcome to OrgX"}),n.jsx("p",{className:"mt-2 text-body leading-relaxed text-secondary",children:"What should we call you? This appears in your settings and is stored locally."}),n.jsx("input",{type:"text",value:r,onChange:u=>i(u.target.value),onKeyDown:l,maxLength:64,autoFocus:!0,placeholder:"Your name",className:"mt-5 h-10 w-full max-w-xs rounded-xl border border-white/[0.12] bg-white/[0.04] px-4 text-center text-body text-white placeholder:text-muted focus:border-lime/30 focus:outline-none"}),n.jsx("button",{type:"button",onClick:a,className:"mt-5 rounded-full bg-lime px-6 py-2.5 text-body font-medium text-black transition hover:brightness-110",children:r.trim()?"Continue":"Continue without name"}),r.trim()&&n.jsx("button",{type:"button",onClick:c,className:"mt-3 text-caption text-secondary transition hover:text-white",children:"Skip"})]})})})}const Kd=[{label:"Terms",href:"https://www.useorgx.com/terms"},{label:"Privacy",href:"https://www.useorgx.com/privacy"},{label:"IP notice",href:"https://www.useorgx.com/legal"}];function Gd({className:e,compact:t=!1}){return n.jsxs("div",{className: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"]}),Kd.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 Ja="orgx.user.name-asked";function Xd(e){switch(e){case"starting":return"Starting secure session...";case"awaiting_browser_auth":return"Waiting for browser approval...";case"pairing":return"Confirming connection...";case"manual_key":return"Manual key entry";case"connected":return"Connected";case"error":return"Connection issue";default:return"Ready to connect"}}function Qd(e){switch(e){case"config":return"Config key";case"environment":return"Env key";case"persisted":return"Saved key";case"openclaw-config-file":return"OpenClaw key";case"legacy-dev":return"Local dev key";default:return"No key"}}function Jd(e){return e==="awaiting_browser_auth"||e==="pairing"||e==="starting"?"active":e==="error"?"error":e==="connected"?"active":"idle"}const Ya={idle:"bg-white/40",active:"bg-[#BFFF00]",error:"bg-red-400"},Ii="orgx.onboarding.mc_hint.dismissed",Ai={initial:{opacity:0,y:14,scale:.985},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.985},transition:{duration:.32,ease:[.16,1,.3,1]}};function Yd({state:e,isLoading:t,isStarting:s,isSubmittingManual:r,onRefresh:i,onStartPairing:a,onSubmitManualKey:c,onBackToPairing:l,onUseManualKey:d,onSkip:u}){const[g,y]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Ii)==="1"),[w,f]=o.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Ja)!=="1"),k=o.useCallback(()=>{typeof window<"u"&&window.localStorage.setItem(Ja,"1"),f(!1)},[]);o.useEffect(()=>{typeof window>"u"||(g?window.localStorage.setItem(Ii,"1"):window.localStorage.removeItem(Ii))},[g]);const x=e.status==="manual_key",j=e.status==="awaiting_browser_auth"||e.status==="pairing",v=Jd(e.status),b=v==="active"&&e.status!=="connected",h=e.status==="connected"&&!g;return n.jsx("div",{className:"relative flex min-h-screen items-start justify-center px-4 pb-6 pt-0 sm:pt-2",style:{backgroundColor:"#02040A"},children:n.jsxs(he.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.45},className:`relative z-10 w-full ${x?"max-w-lg":"max-w-[1120px]"}`,children:[t?n.jsxs("div",{className:"bg-[--orgx-surface-elevated] border border-[--orgx-border] rounded-2xl p-6 sm:p-8",children:[n.jsx("div",{className:"shimmer-skeleton h-7 w-28 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-5 h-8 w-3/4 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton mt-3 h-4 w-2/3 rounded-lg"}),n.jsxs("div",{className:"mt-7 grid grid-cols-3 gap-2.5",children:[n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"}),n.jsx("div",{className:"shimmer-skeleton h-24 rounded-xl"})]}),n.jsx("div",{className:"shimmer-skeleton mt-7 h-10 w-36 rounded-full"})]}):n.jsx(yt,{mode:"wait",children:e.status==="connected"&&w?n.jsx(he.div,{...Ai,children:n.jsx(Vd,{onComplete:k})},"welcome-name"):x?n.jsx(he.div,{...Ai,children:n.jsx(Od,{isSubmitting:r,onSubmit:c,onBack:l})},"manual"):n.jsx(he.div,{...Ai,children:n.jsx(Fd,{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:[b&&n.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${Ya[v]} opacity-40`}),n.jsx("span",{className:`relative inline-flex h-2 w-2 rounded-full ${Ya[v]}`})]}),n.jsx("span",{className:"text-body text-secondary",children:Xd(e.status)}),e.workspaceName&&n.jsxs("span",{className:"chip",children:["Account: ",e.workspaceName]}),e.keySource&&e.keySource!=="none"&&n.jsx("span",{className:"chip",children:Qd(e.keySource)})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[e.expiresAt&&n.jsx("span",{className:"text-caption text-muted",children:new Date(e.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),e.connectUrl&&j&&n.jsx("a",{href:e.connectUrl,target:"_blank",rel:"noopener noreferrer",className:"rounded-full border border-[#BFFF00]/25 bg-[#BFFF00]/[0.05] px-3 py-1 text-caption font-medium text-[#D8FFA1] transition hover:bg-[#BFFF00]/[0.1]",children:"Approve in browser"}),n.jsx("button",{type:"button",onClick:()=>{i()},className:"rounded-full border border-white/[0.08] px-2.5 py-1 text-caption text-muted transition hover:bg-white/[0.04] hover:text-secondary",children:"Refresh"})]})]}),h&&n.jsxs(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:()=>y(!0),className:"text-caption text-secondary underline underline-offset-2",children:"Dismiss"})]})]}),!t&&n.jsx("div",{className:"mt-3 flex justify-center",children:n.jsx(Gd,{compact:!0})})]})})}function Zd({children:e,color:t,pulse:s,title:r}){const i=t??E.lime;return n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-micro font-semibold uppercase tracking-[0.14em]",title:r,style:{backgroundColor:`${i}22`,border:`1px solid ${i}5a`,color:i},children:[n.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[s&&n.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full opacity-75",style:{backgroundColor:i}}),n.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full",style:{backgroundColor:i}})]}),e]})}function di({open:e,onClose:t,children:s,maxWidth:r="max-w-2xl",fitContent:i=!1,closeOnBackdropClick:a=!0,closeOnEscape:c=!0,closeOnEscapeWhenTyping:l=!0}){const d=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{if(!e)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(()=>{const k=d.current;if(!k)return;const x=k.querySelector('[data-modal-autofocus="true"]');if(x){x.focus();return}const j=k.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');j.length>0?j[0].focus():k.focus()})();const w=k=>{if(k.key==="Escape"){if(!c)return;if(!l){const _=k.target;if(_&&(_.tagName==="INPUT"||_.tagName==="TEXTAREA"||_.tagName==="SELECT"||_.isContentEditable))return}k.preventDefault(),t();return}if(k.key!=="Tab")return;const x=d.current;if(!x)return;const j=x.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(j.length===0){k.preventDefault(),x.focus();return}const v=j[0],b=j[j.length-1],h=document.activeElement;!k.shiftKey&&h===b?(k.preventDefault(),v.focus()):k.shiftKey&&h===v&&(k.preventDefault(),b.focus())},f=document.body.style.overflow;return document.body.style.overflow="hidden",document.addEventListener("keydown",w),()=>{var k;document.body.style.overflow=f,document.removeEventListener("keydown",w),(k=u.current)==null||k.focus()}},[e,t,c,l]);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:E.cardBgElevated,borderColor:E.cardBorderStrong},onClick:y=>y.stopPropagation(),role:"dialog","aria-modal":"true",tabIndex:-1,ref:d,children:[n.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-white/50 to-transparent"}),s]})]})});return typeof document>"u"?g:Fl.createPortal(g,document.body)}const eu=[{id:"agents",label:"Agents",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),n.jsx("circle",{cx:"12",cy:"7",r:"4"})]})},{id:"activity",label:"Activity",icon:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})})},{id:"decisions",label:"Decisions",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"}),n.jsx("path",{d:"m9 12 2 2 4-4"})]})},{id:"initiatives",label:"Next Up",icon:n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"}),n.jsx("line",{x1:"4",x2:"4",y1:"22",y2:"15"})]})}];function tu({activeTab:e,onTabChange:t,pendingDecisionCount:s=0}){return n.jsx("nav",{className:"pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3 lg:hidden",style:{bottom:"max(10px, env(safe-area-inset-bottom))"},"aria-label":"Mobile sections",children:n.jsx("div",{className:"pointer-events-auto relative flex items-stretch gap-1 rounded-[24px] border border-strong bg-[#090d16]/90 p-1.5 shadow-[0_20px_50px_rgba(0,0,0,0.52)] backdrop-blur-xl",children:eu.map(r=>{const i=e===r.id;return n.jsxs("button",{type:"button",onClick:()=>t(r.id),"aria-current":i?"page":void 0,className: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:E.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:E.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 Ks({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 nu={xs:"w-6 h-6 text-micro",sm:"w-8 h-8 text-micro",md:"w-10 h-10 text-body",lg:"w-16 h-16 text-title"},su="/orgx/live/",an=e=>`${su.replace(/\/+$/,"/")}${e}`,ru={pace:an("brand/product-orchestrator.png"),eli:an("brand/engineering-autopilot.png"),mark:an("brand/launch-captain.png"),sage:an("brand/pipeline-intelligence.png"),orion:an("brand/control-tower.png"),dana:an("brand/design-codex.png"),xandy:an("brand/xandy-orchestrator.png"),nova:an("brand/xandy-orchestrator.png"),openclaw:an("brand/openclaw-mark.svg"),codex:an("brand/openai-mark.svg"),openai:an("brand/openai-mark.svg"),anthropic:an("brand/anthropic-mark.svg"),orgx:an("brand/orgx-logo.png")},iu=[{test:/\bpace\b|product|nova|strategist/i,key:"pace"},{test:/\beli\b|engineering|dev-delivery|executor/i,key:"eli"},{test:/\bmark\b|marketing|launch-captain/i,key:"mark"},{test:/\bsage\b|sales|pipeline-intelligence|sales-sage/i,key:"sage"},{test:/\borion\b|operations|ops-orbit|control-tower/i,key:"orion"},{test:/\bdana\b|design/i,key:"dana"},{test:/\bxandy\b|orchestrator|router-all-agents/i,key:"xandy"},{test:/\bholt\b|openclaw/i,key:"openclaw"},{test:/openai|gpt|o[1345]-|codex/i,key:"codex"},{test:/anthropic|claude/i,key:"anthropic"},{test:/\borgx\b/i,key:"orgx"}];function au(...e){const t=e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).join(" ").toLowerCase();if(!t)return null;for(const s of iu)if(s.test.test(t))return ru[s.key];return null}function Ft({name:e,size:t="xs",hint:s,src:r}){const i=Cd(e),[a,c]=o.useState(!1),l=o.useMemo(()=>r&&r.trim()?r:au(e,s),[s,e,r]),d=!!(l&&!a);return n.jsx("div",{"data-agent-avatar":"true",className:`${nu[t]} overflow-hidden rounded-full flex items-center justify-center font-semibold flex-shrink-0`,style:{backgroundColor:`${i}20`,color:i,border:`1px solid ${i}30`},children:d?n.jsx("img",{src:l??void 0,alt:e,className:"h-full w-full rounded-full object-cover",onError:()=>c(!0),loading:"lazy"}):Md(e)})}Ft.displayName="AgentAvatar";const ou={neutral:"border-strong bg-white/[0.04] text-primary",muted:"border-strong bg-white/[0.03] text-secondary",lime:"border-lime/28 bg-lime/[0.12] text-[#D8FFA1]",cyan:"border-cyan-300/28 bg-cyan-500/[0.12] text-cyan-100",red:"border-red-300/28 bg-red-500/[0.12] text-red-100"};function An({children:e,tone:t="muted",className:s,...r}){const i=o.Children.toArray(e).some(a=>{if(!o.isValidElement(a))return!1;const c=a.type;return c.displayName==="AgentAvatar"||c.name==="AgentAvatar"});return n.jsx("span",{className: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",ou[t],s),...r,children:e})}function lu(e){var s,r;const t=[];if(e.initiativeId){const i={id:e.initiativeId,label:e.initiativeTitle||As(e.initiativeId,"Initiative"),type:"initiative",children:[]};if(e.workstreamId){const a=rl(e.status),c={id:e.workstreamId,label:e.workstreamTitle||As(e.workstreamId,"Workstream"),type:"workstream",status:a,progress:e.scopeProgress?{done:e.scopeProgress.completedTasks,total:e.scopeProgress.totalTasks}:void 0,agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]};if((s=e.scopeProgress)!=null&&s.milestones&&e.scopeProgress.milestones.length>0)for(const l of e.scopeProgress.milestones){const d=l.done>=l.total?"done":l.done>0?"active":"pending",u={id:l.id,label:l.title||As(l.id,"Milestone"),type:"milestone",status:d,progress:{done:l.done,total:l.total}};l.total>0&&(u.children=Array.from({length:l.total},(g,y)=>({id:`${l.id}-task-${y}`,label:`Task ${y+1}`,type:"task",status:y<l.done?"done":"pending"}))),c.children.push(u)}else if(e.taskIds&&e.taskIds.length>0){const l=((r=e.scopeProgress)==null?void 0:r.completedTasks)??0;c.children=e.taskIds.map((d,u)=>({id:d,label:As(d,"Task"),type:"task",status:u<l?"done":"pending"}))}i.children.push(c)}t.push(i)}return t}function wh(e){const t=[];if(!e.initiativeId&&!e.workstreamId)return t;const s=e.initiativeId?{id:e.initiativeId,label:e.initiativeTitle||As(e.initiativeId,"Initiative"),type:"initiative",children:[]}:null,r=e.workstreamId?{id:e.workstreamId,label:e.workstreamTitle||As(e.workstreamId,"Workstream"),type:"workstream",status:rl(e.status),agent:e.agentName?{name:e.agentName,id:e.agentId}:null,children:[]}:null,i=e.taskId?{id:e.taskId,label:e.taskTitle||As(e.taskId,"Task"),type:"task",highlight:!0}:null;return r&&i&&(r.children=[i]),s&&r?(s.children=[r],t.push(s)):r?t.push(r):s&&t.push(s),t}function As(e,t){return!e||e.length<8?t:`${t} ${e.slice(0,6)}`}function rl(e){return e?e==="completed"||e==="done"?"done":e==="running"||e==="in_progress"||e==="needs_review"?"active":e==="failed"?"failed":e==="blocked"||e==="awaiting_input"?"blocked":"pending":"pending"}function il(e){switch(e){case"done":return E.lime;case"active":return E.teal;case"blocked":return E.amber;case"failed":return E.red;default:return"rgba(255,255,255,0.15)"}}function cu(e){const t=il(e);return{backgroundColor:e==="pending"?"transparent":t,borderColor:t,borderWidth:1.5,borderStyle:"solid"}}const du=o.memo(function({done:t,total:s,color:r}){const i=s>0?Math.max(2,Math.round(t/s*100)):0;return n.jsx("div",{className:"h-[3px] w-full overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx(he.div,{className:"h-full rounded-full",style:{backgroundColor:r},initial:{width:0},animate:{width:`${i}%`},transition:{duration:.5,ease:[.22,1,.36,1]}})})}),uu=16,mu=14,Za=8,pu=8,fu=28,hu=24,gu=24,xu=20,Si="rgba(255,255,255,0.07)";function yu(e){const t=e?mu:uu,s=t+pu+4;return{iconSz:t,colW:s,rowH:e?gu:fu,rowHTask:e?xu:hu}}function al({node:e,depth:t,isLast:s,activeId:r,compact:i,index:a,taskLimit:c,expanded:l,onToggleExpand:d}){const u=r===e.id||e.highlight,g=e.progress&&e.progress.total>0,y=e.type==="task",{iconSz:w,colW:f,rowH:k,rowHTask:x}=yu(i),j=y?x:k,v=e.children??[],b=v.filter(H=>H.type==="task"),h=v.filter(H=>H.type!=="task"),_=b.length>c&&!l,V=_?b.slice(0,c):b,oe=b.length-V.length,K=[...h,...V],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:Si,left:(t-1)*f+f/2,top:0,bottom:s?void 0:0,height:s?j/2:void 0}}),n.jsx("div",{className:"absolute h-px",style:{backgroundColor:Si,left:(t-1)*f+f/2,top:j/2,width:f}})]}),n.jsxs(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*f},children:[n.jsx("div",{className:"flex flex-shrink-0 items-center justify-center",style:{width:f,height:j},children:y?n.jsx("span",{className:"inline-block rounded-full",style:{...cu(e.status),width:Za,height:Za}}):n.jsx(bn,{type:e.type,size:w,accent:u?E.lime:void 0})}),n.jsxs("div",{className:"min-w-0 flex-1 pr-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:`min-w-0 truncate ${y?`text-[12px] leading-none ${e.status==="done"?"text-white/40 line-through decoration-white/10":"text-white/35"}`:e.type==="milestone"?"text-[13px] font-medium leading-none text-white/55":t===0?"text-[13px] font-medium leading-none text-white/80":"text-[13px] font-medium leading-none text-white/70"} ${u?"!text-white/90 !no-underline":""}`,children:e.label}),g&&n.jsxs("span",{className:"flex-shrink-0 text-[10px] tabular-nums leading-none text-white/20",children:[e.progress.done,"/",e.progress.total]}),e.agent&&n.jsx("span",{className:"ml-auto flex-shrink-0 rounded-full bg-white/[0.05] px-1.5 py-px text-[9px] font-medium leading-none text-white/25",children:e.agent.name})]}),g&&!y&&n.jsx("div",{className:"mt-1.5 max-w-[160px]",children:n.jsx(du,{done:e.progress.done,total:e.progress.total,color:il(e.status)})})]})]}),be&&n.jsx("div",{className:"absolute w-px",style:{backgroundColor:Si,left:t*f+f/2,top:j/2,height:j/2}}),be&&n.jsxs("div",{children:[K.map((H,Z)=>n.jsx(al,{node:H,depth:t+1,isLast:Z===K.length-1&&!_,activeId:r,compact:i,index:a+Z+1,taskLimit:c,expanded:l,onToggleExpand:d},H.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:x,paddingLeft:(t+1)*f+f},children:["+",oe," more · see all"]}),n.jsx(yt,{children:l&&b.length>c&&n.jsx(he.button,{type:"button",initial:{opacity:0,height:0},animate:{opacity:1,height:x},exit:{opacity:0,height:0},onClick:d,className:"flex items-center text-[10px] font-medium text-white/25 transition-colors hover:text-white/45",style:{paddingLeft:(t+1)*f+f},children:"show less"})})]})]})}const bu=o.memo(function({nodes:t,className:s,activeId:r,compact:i,taskLimit:a=4}){const[c,l]=o.useState(!1);return t.length===0?null:n.jsx("div",{className:s,children:t.map((d,u)=>n.jsx(al,{node:d,depth:0,isLast:u===t.length-1,activeId:r,compact:i,index:u,taskLimit:a,expanded:c,onToggleExpand:()=>l(g=>!g)},d.id))})}),Yi={engineering:{domain:"engineering",displayName:"Engineering",gradient:["#22c55e","#14b8a6"],accentColor:"#22c55e",glowColor:"#22c55e33",icon:"hammer",progressStyle:"linear",verb:"Building"},design:{domain:"design",displayName:"Design",gradient:["#a78bfa","#ec4899"],accentColor:"#a78bfa",glowColor:"#a78bfa33",icon:"palette",progressStyle:"wave",verb:"Designing"},product:{domain:"product",displayName:"Product",gradient:["#3b82f6","#6366f1"],accentColor:"#3b82f6",glowColor:"#3b82f633",icon:"compass",progressStyle:"stepped",verb:"Specifying"},marketing:{domain:"marketing",displayName:"Marketing",gradient:["#f59e0b","#ef4444"],accentColor:"#f59e0b",glowColor:"#f59e0b33",icon:"megaphone",progressStyle:"wave",verb:"Crafting"},sales:{domain:"sales",displayName:"Sales",gradient:["#06b6d4","#3b82f6"],accentColor:"#06b6d4",glowColor:"#06b6d433",icon:"handshake",progressStyle:"linear",verb:"Preparing"},operations:{domain:"operations",displayName:"Operations",gradient:["#64748b","#475569"],accentColor:"#64748b",glowColor:"#64748b33",icon:"shield",progressStyle:"stepped",verb:"Securing"},orchestrator:{domain:"orchestrator",displayName:"Orchestrator",gradient:["#8b5cf6","#6366f1"],accentColor:"#8b5cf6",glowColor:"#8b5cf633",icon:"workflow",progressStyle:"linear",verb:"Coordinating"}},wu=Object.keys(Yi);function eo(e){if(!e)return"engineering";const t=e.trim().toLowerCase();for(const s of wu)if(t.includes(s))return s;return"engineering"}function to(e){return Yi[e]??Yi.engineering}const zs={Pace:"#7C7CFF",Eli:"#BFFF00",Dana:"#FF00D4",Mark:"#F5B700",Sage:"#0AD4C4",Orion:"#14B8A6",Xandy:"#FF6B88",Nova:"#A78BFA"},ar={Eli:"Engineering",Pace:"Product",Dana:"Design",Mark:"Marketing",Sage:"Strategy",Orion:"Operations",Xandy:"Orchestrator",Nova:"Research"},no={engineering:"Eli",product:"Pace",design:"Dana",marketing:"Mark",strategy:"Strategy",sales:"Sage",operations:"Orion",orchestrator:"Xandy",research:"Nova"},so={eli:"Eli",pace:"Pace",dana:"Dana",mark:"Mark",sage:"Sage",orion:"Orion",xandy:"Xandy",nova:"Nova","engineering-agent":"Eli","product-agent":"Pace","design-agent":"Dana","marketing-agent":"Mark","strategy-agent":"Sage","sales-agent":"Sage","operations-agent":"Orion","orchestrator-agent":"Xandy","research-agent":"Nova","engineering-bot":"Eli","product-bot":"Pace","design-bot":"Dana","marketing-bot":"Mark","dev-delivery":"Eli","launch-captain":"Mark","pipeline-intelligence":"Sage","control-tower":"Orion","design-codex":"Dana","router-all-agents":"Xandy","ops-orbit":"Orion","sales-sage":"Sage"};function ol(e,t){const s={name:(t==null?void 0:t.trim())||"OrgX",domain:"",color:"rgba(255,255,255,0.4)",displayLabel:(t==null?void 0:t.trim())||"OrgX"};if(e){const r=e.trim().toLowerCase(),i=so[r];if(i){const a=ar[i]??"";return{name:i,domain:a,color:zs[i]??s.color,displayLabel:a?`${i} (${a})`:i}}for(const[a,c]of Object.entries(no))if(r.includes(a)){const l=ar[c]??"";return{name:c,domain:l,color:zs[c]??s.color,displayLabel:l?`${c} (${l})`:c}}}if(t){const r=t.trim();if(zs[r]){const c=ar[r]??"";return{name:r,domain:c,color:zs[r],displayLabel:c?`${r} (${c})`:r}}const i=r.toLowerCase(),a=so[i];if(a){const c=ar[a]??"";return{name:a,domain:c,color:zs[a]??s.color,displayLabel:c?`${a} (${c})`:a}}for(const[c,l]of Object.entries(no))if(i.includes(c)){const d=ar[l]??"";return{name:l,domain:d,color:zs[l]??s.color,displayLabel:d?`${l} (${d})`:l}}}return s}function vh({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(Ft,{name:i.name,size:"xs"})},i.id)),r>0&&n.jsxs("span",{className:"ml-1 flex-shrink-0 text-micro text-muted",children:["+",r]})]})}const vu=new Set(["running","active","in_progress","working","planning","dispatching"]),ku=new Set(["running","dispatching"]),ju=3*6e4;function Nu(e){if(!e)return!1;const t=Date.parse(e);return Number.isFinite(t)?Date.now()-t<=ju:!1}function Iu(e){const t=Ot(e.status??""),s=Ot(e.state??"");return s==="stale"||t==="stale"||s==="stopped"&&t!=="blocked"?!1:vu.has(t)?!0:t==="queued"||t==="pending"||t==="paused"||t==="completed"?!1:e.lastHeartbeatAt?Nu(e.lastHeartbeatAt):!1}function ll(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function Au(e){const t=Ot(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"border-teal-300/28 bg-teal-400/[0.10] text-teal-100":t==="blocked"||t==="failed"||t==="error"?"border-red-400/26 bg-red-500/[0.10] text-red-100":t==="paused"||t==="pending"||t==="queued"?"border-amber-300/28 bg-amber-300/[0.10] text-amber-100":"border-[#BFFF00]/24 bg-[#BFFF00]/[0.10] text-[#E8FFD0]"}function Su(e){const t=Ot(e);return t==="running"||t==="active"||t==="in_progress"||t==="working"||t==="dispatching"?"from-teal-300/0 via-teal-300/65 to-teal-300/0":t==="blocked"||t==="failed"||t==="error"?"from-red-300/0 via-red-300/65 to-red-300/0":t==="paused"||t==="pending"||t==="queued"?"from-amber-300/0 via-amber-300/65 to-amber-300/0":"from-[#BFFF00]/0 via-[#BFFF00]/70 to-[#BFFF00]/0"}function cl(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function Er(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function ks(e,t){const s=[],r=i=>{if(typeof i!="string")return;const a=i.trim();a&&(s.some(c=>c.toLowerCase()===a.toLowerCase())||s.push(a))};if(Array.isArray(e))for(const i of e)r(i);return r(t??null),s}function Zr(e,t){if(!e)return t;const s=e.trim();return s?Un(s)?`${t} ${is(s)}`:s:t}const _u=new Set(["telegram session","codex session","claude session","claude code session","openclaw session","reporting session"]),Cu=[/^session sent an update\.?$/i,/^session updated\.?$/i,/^status update\.?$/i];function Mu(e){if(!e)return!1;const t=e.trim().toLowerCase();return t?_u.has(t)||t.startsWith("telegram:"):!1}function Tu(e){if(!e)return!1;const t=e.trim();return t?Cu.some(s=>s.test(t)):!1}function dl({sessions:e,sliceRuns:t=[],initiatives:s=[]}){var y,w,f,k,x,j;const r=new Map;for(const v of s)v.id&&r.set(v.id,v.name??v.id);const i=new Map;for(const v of e){const b=(y=v.runId)==null?void 0:y.trim();!b||i.has(b)||i.set(b,v)}const a=new Map;for(const v of e){const b=((w=v.initiativeId)==null?void 0:w.trim())??"",h=((f=v.workstreamId)==null?void 0:f.trim())??"";if(!b||!h)continue;const _=`${b}:${h}`;a.has(_)||a.set(_,v)}const c=new Set;for(const v of e){const b=(k=v.runId)==null?void 0:k.trim();b&&c.add(b)}const l=[];for(const v of t){if(!ku.has(v.status))continue;const b=(v.runId??v.sliceRunId??"").trim();if(!b)continue;const h=ks(v.initiativeIds,v.initiativeId),_=ks(v.workstreamIds,v.workstreamId),V=h[0]??null,oe=_[0]??null,K=[];for(const ye of h)for(const we of _)!ye||!we||K.push(`${ye}:${we}`);if(!(c.has(b)||K.some(ye=>a.has(ye))))continue;const H=i.get(b)??(K.length>0?K.map(ye=>a.get(ye)??null).find(ye=>!!ye)??null:null),Z=V?r.get(V)??V:null,ce=v.scopeProgress&&typeof v.scopeProgress.totalTasks=="number"&&v.scopeProgress.totalTasks>0?Math.round(v.scopeProgress.completedTasks/v.scopeProgress.totalTasks*100):null;l.push({key:`slice:${v.sliceRunId}`,source:"slice",session:H??null,runId:b,status:Ot(v.status),title:v.workstreamTitle??(H==null?void 0:H.title)??`Work slice ${v.sliceRunId.slice(0,8)}`,subtitle:v.statusExplainer??v.lastEventSummary??(H==null?void 0:H.lastEventSummary)??null,progress:ce??(H==null?void 0:H.progress)??null,initiativeId:V,initiativeIds:h,initiativeTitle:Z,workstreamId:oe,workstreamIds:_,iwmtId:v.iwmtId??null,iwmtIds:ks(v.iwmtIds,v.iwmtId),workstreamTitle:v.workstreamTitle??(H==null?void 0:H.title)??null,taskIds:Array.isArray(v.taskIds)?v.taskIds:[],milestoneIds:Array.isArray(v.milestoneIds)?v.milestoneIds:[],artifactCount:v.artifactCount??0,decisionCount:v.blockingDecisionCount??v.decisionCount??0,updatedAt:v.updatedAt??v.lastEventAt??(H==null?void 0:H.updatedAt)??null,scope:v.scope,milestoneProgress:(x=v.scopeProgress)==null?void 0:x.milestones})}if(l.sort((v,b)=>Er(b.updatedAt)-Er(v.updatedAt)),l.length>0){const v=[],b=new Set;for(const h of l){const _=h.initiativeId??((j=h.initiativeIds)==null?void 0:j[0])??"none",oe=(h.workstreamId?`scope:${_}:${h.workstreamId}`:null)??(h.runId?`run:${h.runId}`:h.key);b.has(oe)||(b.add(oe),v.push(h))}return v}const d=e.filter(Iu);d.sort((v,b)=>{const h=Er(v.updatedAt??v.lastEventAt??v.startedAt);return Er(b.updatedAt??b.lastEventAt??b.startedAt)-h});const u=[],g=new Set;for(const v of d){const b=v.workstreamId&&v.workstreamId.trim().length>0?`${v.initiativeId??"none"}:${v.workstreamId}`:v.runId;g.has(b)||(g.add(b),u.push(v))}return u.map(v=>{var b;return{key:`session:${v.id}`,source:"session",session:v,runId:v.runId,status:Ot(v.status??""),title:v.title,subtitle:(b=v.lastEventSummary)!=null&&b.trim()?v.lastEventSummary.trim():null,progress:v.progress,initiativeId:v.initiativeId,initiativeIds:ks(void 0,v.initiativeId),initiativeTitle:v.initiativeId?r.get(v.initiativeId)??v.groupLabel??null:v.groupLabel??null,workstreamId:v.workstreamId,workstreamIds:ks(void 0,v.workstreamId),iwmtId:null,iwmtIds:[],workstreamTitle:v.title,taskIds:[],milestoneIds:[],artifactCount:0,decisionCount:0,updatedAt:v.updatedAt??v.lastEventAt??v.startedAt??null}})}const Eu=o.memo(function({sessions:t,sliceRuns:s=[],initiatives:r=[],title:i="In Progress",className:a,showHeader:c=!0,panelStyle:l="card",needsAttentionCount:d=0,onSwitchToNeedsAttention:u,onOpenSession:g,onFocusRunId:y,onPlayWorkstream:w,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:x,onIntervene:j,onOpenSliceDetail:v}){const[b,h]=o.useState(null),[_,V]=o.useState(null),[oe,K]=o.useState(null),[be,H]=o.useState(null),Z=o.useMemo(()=>{const ee=new Map;if(!Array.isArray(s))return ee;for(const de of s){const Ee=ks(de.initiativeIds,de.initiativeId),ne=ks(de.workstreamIds,de.workstreamId);for(const J of Ee)for(const P of ne){if(!J||!P)continue;const Y=`${J}:${P}`;ee.has(Y)||ee.set(Y,de)}const R=(de.runId??de.sliceRunId??"").trim();R&&!ee.has(`run:${R}`)&&ee.set(`run:${R}`,de)}return ee},[s]),ce=o.useMemo(()=>dl({sessions:t,sliceRuns:s,initiatives:r}),[r,t,s]),ye=o.useMemo(()=>{const ee=new Map;for(const de of ce){const Ee=Ot(de.status);ee.set(Ee,(ee.get(Ee)??0)+1)}return Array.from(ee.entries()).sort((de,Ee)=>Ee[1]-de[1]).map(([de,Ee])=>({status:de,count:Ee}))},[ce]),we=o.useMemo(()=>b?ce.filter(ee=>Ot(ee.status)===b):ce,[b,ce]),W=o.useMemo(()=>{var ne,R;const ee=new Map,de=[];for(const J of we){const P=(((ne=J.initiativeIds)==null?void 0:ne[0])??J.initiativeId??"").trim(),Y=(((R=J.workstreamIds)==null?void 0:R[0])??J.workstreamId??"").trim();if(!P){de.push(J);continue}let ie=ee.get(P);ie||(ie={title:J.initiativeTitle??P,wsMap:new Map},ee.set(P,ie));const ve=Y||"__none__";let je=ie.wsMap.get(ve);je||(je={title:J.workstreamTitle??(Y||"Unassigned"),rows:[],completedCount:0,lastActivity:null},ie.wsMap.set(ve,je));const te=Ot(J.status);if(te==="completed"||te==="done"?je.completedCount+=1:je.rows.push(J),J.updatedAt){const Me=Date.parse(J.updatedAt),pe=je.lastActivity?Date.parse(je.lastActivity):0;Number.isFinite(Me)&&Me>pe&&(je.lastActivity=J.updatedAt)}}const Ee=[];for(const[J,P]of ee){const Y=[];for(const[ie,ve]of P.wsMap)Y.push({workstreamId:ie,workstreamTitle:ve.title,rows:ve.rows,completedCount:ve.completedCount,lastActivityAt:ve.lastActivity});Y.sort((ie,ve)=>{const je=ie.lastActivityAt?Date.parse(ie.lastActivityAt):0;return(ve.lastActivityAt?Date.parse(ve.lastActivityAt):0)-je}),Ee.push({initiativeId:J,initiativeTitle:P.title,workstreams:Y})}return Ee.sort((J,P)=>{const Y=Math.max(0,...J.workstreams.map(ve=>ve.lastActivityAt?Date.parse(ve.lastActivityAt):0));return Math.max(0,...P.workstreams.map(ve=>ve.lastActivityAt?Date.parse(ve.lastActivityAt):0))-Y}),{groups:Ee,ungrouped:de}},[we]),[Ie,Te]=o.useState(new Set),fe=async(ee,de,Ee)=>{if(ee.session){H(null),V(ee.session.id);try{await de(ee.session),H(Ee)}catch(ne){const R=ne instanceof Error?ne.message:"";H(R?Cn(R):"Workstream action failed")}finally{V(null)}}};return n.jsxs(Ks,{surface:l==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${l==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${a??""}`,children:[c?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:i}),n.jsx("span",{className:"chip text-micro",children:ce.length})]})}):null,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:()=>h(null),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold transition-colors ${b===null?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:["All",n.jsx("span",{className:"tabular-nums opacity-70",children:ce.length})]}),ye.map(({status:ee,count:de})=>n.jsxs("button",{type:"button",onClick:()=>h(Ee=>Ee===ee?null:ee),className:`inline-flex h-6 items-center gap-1 rounded-full border px-2 text-micro font-semibold capitalize transition-colors ${b===ee?"border-[#BFFF00]/30 bg-[#BFFF00]/12 text-[#E1FFB2]":"border-strong bg-white/[0.04] text-secondary hover:bg-white/[0.08]"}`,children:[ll(ee),n.jsx("span",{className:"tabular-nums opacity-70",children:de})]},ee))]}),be&&n.jsx("div",{className:"border-b border-subtle px-3 py-2 text-caption text-secondary",children:be}),we.length===0?ce.length===0&&d>0&&u?n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 px-6 py-10 text-center",children:[n.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.03]",children:n.jsx("svg",{viewBox:"0 0 20 20",fill:"none",className:"h-5 w-5 text-secondary","aria-hidden":!0,children:n.jsx("path",{d:"M10 6v4m0 4h.01M3 10a7 7 0 1114 0 7 7 0 01-14 0z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsxs("div",{children:[n.jsx("p",{className:"text-body font-medium text-primary",children:"All clear"}),n.jsxs("p",{className:"mt-1 text-caption leading-relaxed text-secondary",children:["No active runs right now."," ",n.jsx("span",{className:"tabular-nums font-semibold text-[#F5B700]/90",children:d})," ",d===1?"item needs":"items need"," your attention."]})]}),n.jsxs("button",{type:"button",onClick:u,className:"inline-flex h-8 items-center gap-1.5 rounded-full border border-[#F5B700]/25 bg-[#F5B700]/[0.08] px-4 text-caption font-semibold text-[#FFE7A8] transition-colors hover:border-[#F5B700]/40 hover:bg-[#F5B700]/[0.14]",children:[n.jsx("span",{children:"Review needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:d})]})]}):n.jsx("div",{className:"flex flex-1 items-center justify-center px-4 py-10",children:n.jsx("p",{className:"text-body text-secondary",children:ce.length===0?"No runs in progress.":"No runs match this filter."})}):n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-2",children:n.jsxs(he.div,{className:"space-y-4",initial:"hidden",animate:"show",variants:{show:{transition:{staggerChildren:.04}}},children:[W.groups.map(ee=>n.jsxs("div",{children:[n.jsx("h3",{className:"text-[15px] font-semibold text-white/90 mb-2",children:Pt(ee.initiativeTitle&&!Un(ee.initiativeTitle)?ee.initiativeTitle:Zr(ee.initiativeId,"Initiative"))}),ee.workstreams.map(de=>{var te,Me;const Ee=`${ee.initiativeId}:${de.workstreamId}`,ne=Ie.has(Ee),R=de.rows[0]??null,J=R?ol((te=R.session)==null?void 0:te.agentId,(Me=R.session)==null?void 0:Me.agentName):null,P=R!=null&&R.milestoneProgress?R.milestoneProgress.reduce((pe,M)=>pe+M.total,0):null,Y=R!=null&&R.milestoneProgress?R.milestoneProgress.reduce((pe,M)=>pe+M.done,0):null,ie=P&&P>0?`Task ${(Y??0)+1} of ${P}`:null,ve=P&&P>0?Math.round((Y??0)/P*100):(R==null?void 0:R.progress)!=null?cl(R.progress):null,je=Pt(R!=null&&R.workstreamTitle&&!Un(R.workstreamTitle)?R.workstreamTitle:Zr(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:[J&&n.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0",style:{backgroundColor:`${J.color}20`,color:J.color},children:J.name.charAt(0).toUpperCase()}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-[13px] font-semibold text-white/88",title:je,children:je}),J?n.jsx("p",{className:"truncate text-[11px] font-medium",style:{color:J.color},title:J.displayLabel,children:J.displayLabel}):null]})]}),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:(J==null?void 0:J.color)??"#14B8A6"}})})]})]}),n.jsx("div",{className:"space-y-2",children:de.rows.map((pe,M)=>n.jsx(ro,{row:pe,index:M,sliceRunByScope:Z,busySessionId:_,expandedRowKey:oe,setExpandedRowKey:K,onOpenSession:g,onFocusRunId:y,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:x,onPlayWorkstream:w,onIntervene:j,onOpenSliceDetail:v,runWorkstreamAction:fe,showInitiativeLabel:!1},pe.key))}),de.completedCount>0&&n.jsx("div",{className:"mt-1.5",children:n.jsx("button",{type:"button",onClick:()=>Te(pe=>{const M=new Set(pe);return M.has(Ee)?M.delete(Ee):M.add(Ee),M}),className:"text-[11px] text-[#14B8A6] cursor-pointer hover:underline",children:ne?`Hide ${de.completedCount} completed`:`${de.completedCount} completed`})})]},de.workstreamId)})]},ee.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((ee,de)=>n.jsx(ro,{row:ee,index:de,sliceRunByScope:Z,busySessionId:_,expandedRowKey:oe,setExpandedRowKey:K,onOpenSession:g,onFocusRunId:y,onPauseWorkstream:f,onResumeWorkstream:k,onRestartSession:x,onPlayWorkstream:w,onIntervene:j,onOpenSliceDetail:v,runWorkstreamAction:fe,showInitiativeLabel:!0},ee.key))})]})]})})]})});function ro({row:e,index:t,sliceRunByScope:s,busySessionId:r,expandedRowKey:i,setExpandedRowKey:a,onOpenSession:c,onFocusRunId:l,onPauseWorkstream:d,onResumeWorkstream:u,onRestartSession:g,onPlayWorkstream:y,onIntervene:w,onOpenSliceDetail:f,runWorkstreamAction:k,showInitiativeLabel:x=!0}){var de,Ee,ne,R,J,P,Y,ie,ve,je;const j=Ot(e.status??""),v=e.updatedAt,b=e.subtitle?e.subtitle:v?`Updated ${_t(v)}`:null,h=x&&(e.initiativeTitle||e.initiativeId)?Pt(e.initiativeTitle&&!Un(e.initiativeTitle)?e.initiativeTitle:Zr(e.initiativeId,"Initiative")):null,_=(de=e.title)!=null&&de.trim()?e.title:"",V=Mu(_)&&((Ee=e.workstreamTitle)!=null&&Ee.trim())?e.workstreamTitle:_||e.workstreamTitle||"",oe=Zr(e.workstreamId??e.runId,e.scope==="milestone"?"Milestone":e.scope==="task"?"Task":"Workstream"),K=Pt(V&&!Un(V)?V:oe),be=b&&!Tu(b)?Pt(b):null,H=cl(e.progress),Z=["running","active","in_progress","working","planning","dispatching"].includes(j),ce=["paused","blocked","queued","pending"].includes(j),ye=g??y,we=H===null&&["running","active","in_progress","working","planning","dispatching"].includes(j),W=e.session?r===e.session.id:!1,Ie=i===e.key,Te=e.source==="slice"&&(e.taskIds.length>0||e.milestoneIds.length>0||e.artifactCount>0||e.decisionCount>0),fe=(e.initiativeId&&e.workstreamId?s.get(`${e.initiativeId}:${e.workstreamId}`)??null:null)??(e.runId?s.get(`run:${e.runId}`)??null:null),ee=ol((ne=e.session)==null?void 0:ne.agentId,(R=e.session)==null?void 0:R.agentName);return n.jsxs(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:()=>f==null?void 0:f(e,fe),role:"button",tabIndex:0,onKeyDown:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),f==null||f(e,fe))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${Su(j)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex min-w-0 items-start gap-2.5",children:[n.jsx("div",{className:e.status==="running"?"agent-glow-ring rounded-full":"",style:e.status==="running"?{"--agent-glow-color":ee.color}:void 0,children:n.jsx(Ft,{name:((J=e.session)==null?void 0:J.agentName)??"OrgX",hint:((P=e.session)==null?void 0:P.agentId)??e.runId,size:"sm"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[h?n.jsx("p",{className:"text-micro uppercase tracking-[0.08em] text-muted",children:h}):null,n.jsxs("div",{className:"flex min-w-0 items-start gap-1.5",children:[n.jsx(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(An,{tone:e.scope==="milestone"?"cyan":"lime",children:e.scope}),n.jsx("span",{className:`inline-flex rounded-full border px-2 py-[1px] text-micro font-semibold uppercase tracking-[0.08em] ${Au(j)}`,children:ll(j)}),v&&n.jsx("span",{className:"font-mono tabular-nums text-[11px] text-white/40 ml-auto",children:zl(new Date(v),{addSuffix:!0})})]}),be?n.jsx("p",{className:"mt-1 line-clamp-2 text-caption leading-snug text-secondary",title:be,children:be}):null,null,(H!==null||we)&&n.jsxs("div",{className:"mt-2",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro",children:[n.jsx("span",{className:"text-secondary",children:"Progress"}),n.jsx("span",{className:"font-semibold text-primary tabular-nums",children:H===null?"Live":`${H}%`})]}),n.jsx("div",{className:`h-1.5 overflow-hidden rounded-full bg-white/[0.09]${H===100?" shimmer-on-complete":""}`,children:H===null?n.jsx("div",{className:"h-full w-1/3 animate-pulse rounded-full bg-[#7dd3c0]/70"}):n.jsx("div",{className:"h-full rounded-full transition-[width] duration-500",style:{width:`${Math.max(3,H)}%`,background:`linear-gradient(90deg, ${to(eo((Y=e.session)==null?void 0:Y.agentId)).gradient[0]}, ${to(eo((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(bu,{nodes:lu({initiativeId:e.initiativeId,initiativeTitle:e.initiativeTitle,workstreamId:e.workstreamId,workstreamTitle:e.workstreamTitle,taskIds:e.taskIds,milestoneIds:e.milestoneIds,scopeProgress:e.milestoneProgress?{totalTasks:e.milestoneProgress.reduce((te,Me)=>te+Me.total,0),completedTasks:e.milestoneProgress.reduce((te,Me)=>te+Me.done,0),milestones:e.milestoneProgress}:null,status:e.status,agentName:((ve=e.session)==null?void 0:ve.agentName)??null,agentId:((je=e.session)==null?void 0:je.agentId)??null}),activeId:e.workstreamId,compact:!0})}),Te?n.jsxs("div",{className:"mt-2",children:[n.jsx("button",{type:"button",onClick:te=>{te.stopPropagation(),a(Me=>Me===e.key?null:e.key)},className:"inline-flex h-6 items-center gap-1 rounded-md px-1 text-micro font-semibold text-secondary transition-colors hover:text-white",children:Ie?"Hide details":"Slice details"}),Ie?n.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-white/[0.08] bg-black/[0.18] px-2.5 py-2",children:[e.workstreamTitle?n.jsxs("p",{className:"text-caption text-secondary",children:["Workstream: ",n.jsx("span",{className:"text-white/90",children:e.workstreamTitle})]}):null,n.jsxs("div",{className:"flex flex-wrap gap-1.5 text-micro",children:[n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Tasks ",e.taskIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Milestones ",e.milestoneIds.length]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Artifacts ",e.artifactCount]}),n.jsxs("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.03] px-2 py-0.5 text-secondary",children:["Needs input ",e.decisionCount]})]})]}):null]}):null,n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 border-t border-white/[0.07] pt-2",onClick:te=>te.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>{if(e.session){c==null||c(e.session.id);return}l==null||l(e.runId)},className:"control-pill h-7 px-2.5 text-micro font-semibold",title:e.session?"Open session detail":"Focus in Activity",children:e.session?"Open":"Focus"}),e.session&&Z&&d&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:W,onClick:()=>void k(e,d,`Paused ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Pause and return this workstream to queue",children:"Pause"}),e.session&&ce&&u&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:W,onClick:()=>void k(e,u,`Resumed ${e.title}.`),className:"control-pill h-7 px-2.5 text-micro font-semibold disabled:opacity-45",title:"Resume this workstream",children:"Resume"}),e.session&&ye&&e.session.initiativeId&&e.session.workstreamId&&n.jsx("button",{type:"button",disabled:W,onClick:()=>void k(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&&w&&n.jsx("button",{type:"button",disabled:W,onClick:()=>void k(e,w,`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 Ru={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 ui({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:Tr,custom:0,children:n.jsx("svg",{width:"22",height:"22",viewBox:"0 0 24 24",className:"text-secondary",children:Ru[e]})}),n.jsx(he.h4,{className:"mt-5 text-heading font-semibold text-white",variants:Tr,custom:1,children:t}),n.jsx(he.p,{className:"mt-2 text-body text-secondary leading-relaxed",variants:Tr,custom:2,children:s}),(r||i)&&n.jsxs(he.div,{className:"mt-5 flex items-center gap-2",variants:Tr,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 Lu=new Set(["awaiting_input","needs_review","failed"]);function io(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Du(e){var i,a;const t=e.initiativeId??((i=e.initiativeIds)==null?void 0:i[0])??"none",s=e.workstreamId??((a=e.workstreamIds)==null?void 0:a[0])??"none",r=(e.statusExplainer??"").trim().toLowerCase();return[t,s,e.status,e.primaryAction,r].join("|")}function ul(e){const t=e.filter(r=>Lu.has(r.status)).sort((r,i)=>io(i.updatedAt??i.lastEventAt??"")-io(r.updatedAt??r.lastEventAt??"")),s=new Map;for(const r of t){const i=Du(r),a=s.get(i);if(!a){s.set(i,{item:r,duplicateCount:1});continue}a.duplicateCount+=1}return Array.from(s.values())}function $u(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 Fu(e){return e==="awaiting_input"?"Needs input":e==="needs_review"?"Needs review":e==="failed"?"Failed":e.replace(/_/g," ")}function Pu(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 Ou(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 Bu(e){if(e.artifactCount>0)return`${e.artifactCount} artifact${e.artifactCount===1?"":"s"} ready to review.`;if(e.blockingDecisionCount>0||e.decisionCount>0){const t=Math.max(e.blockingDecisionCount,e.decisionCount);return`${t} decision${t===1?"":"s"} need${t===1?"s":""} your input.`}return e.status==="failed"?"Execution stopped before finishing.":e.status==="needs_review"?"Output is available and needs a quick review.":"This work needs your attention to continue."}function Zi(e,t){if(!e||e.trim().length===0)return t;const s=e.trim();return Un(s)?`${t} ${is(s)}`:s}function qu(e){if(!e)return null;const t=Pt(e);return t.length<12?null:t.length>96?`${t.slice(0,93)}…`:t}function zu(e,t,s){const r=(t==null?void 0:t.trim())??"";if(r&&!Un(r)){const a=Pt(r);if(a!=="Untitled session")return a}const i=qu(e.statusExplainer);return i||(s?Zi(s,"Workstream"):Zi(e.sliceRunId,"Slice"))}const Wu=o.memo(function({sliceRuns:t,initiatives:s=[],title:r="Needs Input",className:i,showHeader:a=!0,panelStyle:c="card",onOpenDecisions:l,onFocusRunId:d,onReviewActivity:u,onOpenSliceDetail:g}){const y=o.useMemo(()=>ul(t),[t]),w=o.useMemo(()=>{const x=new Map;for(const j of s)j.id&&x.set(j.id,j.name??j.id);return x},[s]),f=o.useMemo(()=>{const x=new Map;for(const j of s)for(const v of j.workstreams??[])v.id&&(x.has(v.id)||x.set(v.id,v.name??v.id));return x},[s]),k=x=>{var j;if(x.primaryAction==="resolve_decision"){l==null||l();return}if(x.primaryAction==="review_output"||x.primaryAction==="retry_slice"){u==null||u(x);return}if(x.primaryAction==="open_artifact"){const v=(j=x.artifacts.find(b=>b.url))==null?void 0:j.url;if(v&&typeof window<"u"){window.open(v,"_blank","noopener,noreferrer");return}u==null||u(x);return}if(x.runId){d==null||d(x.runId);return}x.sliceRunId&&(d==null||d(x.sliceRunId))};return n.jsxs(Ks,{surface:c==="card",className:`flex h-full min-h-0 flex-col overflow-hidden ${c==="flat"?"!rounded-none !border-none !bg-transparent !shadow-none":""} ${i??""}`,children:[a?n.jsx("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 py-3",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[n.jsx("h2",{className:"truncate text-heading font-semibold text-white",children:r}),n.jsx("span",{className:"chip text-micro",children:y.length})]})}):null,y.length===0?n.jsx(ui,{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:y.map(({item:x,duplicateCount:j},v)=>{var we;const b=(Array.isArray(x.initiativeIds)&&x.initiativeIds.length>0?x.initiativeIds[0]:x.initiativeId)??null,h=(Array.isArray(x.workstreamIds)&&x.workstreamIds.length>0?x.workstreamIds[0]:x.workstreamId)??null,_=(b?w.get(b):null)??Zi(b,"Initiative"),V=x.workstreamTitle??(h?f.get(h)??null:null),oe=zu(x,V,h),K=(we=x.statusExplainer)!=null&&we.trim().length?x.statusExplainer:"Review this slice to continue execution.",be=Pt(Bu(x)),H=Pt(K),Z=Pt(_),ce=x.scope?x.scope.replace(/_/g," "):null,ye=x.updatedAt??x.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(v,7)*.022,ease:[.22,1,.36,1]},className:`group hover-lift relative overflow-visible rounded-2xl border bg-white/[0.02] px-3 py-2.5 transition-colors hover:border-white/[0.14] ${x.status==="failed"?"border-red-400/20":x.blockingDecisionCount>0?"border-amber-400/20":"border-white/[0.08]"}`,role:"button",tabIndex:0,onClick:()=>g==null?void 0:g(x),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),g==null||g(x))},children:[n.jsx("div",{className:`pointer-events-none absolute inset-x-3 top-0 h-px bg-gradient-to-r ${Pu(x.status)}`,"aria-hidden":!0}),n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex min-w-0 items-center gap-1 text-micro uppercase tracking-[0.08em] text-muted",children:[n.jsx(bn,{type:"initiative",size:10,className:"flex-shrink-0 opacity-80"}),n.jsx("span",{className:"truncate",children:Z})]}),n.jsxs("p",{className:"mt-0.5 inline-flex min-w-0 items-start gap-1.5 text-body font-semibold leading-snug text-white",title: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}),H!==be&&n.jsx("p",{className:"mt-1 line-clamp-2 text-micro leading-snug text-muted",title:H,children:H})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-1.5",children:[n.jsx("span",{className:`inline-flex h-6 items-center rounded-full border px-2 text-micro font-semibold uppercase tracking-[0.08em] ${$u(x.status)}`,children:Fu(x.status)}),ce?n.jsx("span",{className:"chip text-micro capitalize",children:ce}):null]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro text-secondary",children:[j>1&&n.jsxs("span",{className:"chip text-micro",children:[j," similar updates"]}),typeof x.blockingDecisionCount=="number"&&x.blockingDecisionCount>0&&n.jsxs("span",{className:"chip text-micro border-red-400/30 bg-red-500/[0.1] text-red-200/90",children:["Blocks ",x.blockingDecisionCount," task",x.blockingDecisionCount===1?"":"s"]}),typeof x.decisionCount=="number"&&x.decisionCount>0&&n.jsxs("span",{className:"chip text-micro",children:[x.decisionCount," decision",x.decisionCount===1?"":"s"]}),typeof x.artifactCount=="number"&&x.artifactCount>0&&n.jsxs("span",{className:"chip text-micro",children:[x.artifactCount," artifact",x.artifactCount===1?"":"s"]}),ye&&n.jsxs("span",{children:["Updated ",_t(ye)]})]}),x.decisionOptions&&x.decisionOptions.length>0&&x.decisionOptions.length<=3&&n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",onClick:W=>W.stopPropagation(),children:x.decisionOptions.slice(0,3).map(W=>n.jsx("button",{type:"button",onClick:()=>g==null?void 0:g(x),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(x),className:"control-pill h-7 px-2.5 text-micro font-semibold",children:"Details"}),n.jsx("button",{type:"button",onClick:()=>k(x),className:"control-pill h-7 px-2.5 text-micro font-semibold","data-tone":x.status==="failed"?"teal":void 0,children:Ou(x)})]})]},x.sliceRunId)})})]})});function Uu(e){const t=e.toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Hu(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 Vu(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Ku(e){return{id:e.id,name:e.title,status:Uu(e.status),rawStatus:e.status??null,priority:e.priority??null,health:e.progress_pct??0,daysRemaining:Hu(e.target_date),targetDate:e.target_date??null,createdAt:e.created_at??null,updatedAt:e.updated_at??e.created_at??null,activeAgents:0,totalAgents:0,description:e.summary??void 0}}const ao=150,Gu=12;function oo(e){const t=Date.parse(e??"");return Number.isFinite(t)?t:0}function Xu(){const e=new Date,t=864e5;return[{id:"init-1",name:"Q4 Feature Ship",status:"active",rawStatus:"active",priority:"high",health:38,daysRemaining:16,targetDate:new Date(e.getTime()+16*t).toISOString(),createdAt:new Date(e.getTime()-18*t).toISOString(),updatedAt:new Date(e.getTime()-5*6e4).toISOString(),activeAgents:2,totalAgents:3,description:"Finalize launch readiness for the Q4 initiative."},{id:"init-2",name:"Black Friday Email",status:"active",rawStatus:"active",priority:"medium",health:55,daysRemaining:10,targetDate:new Date(e.getTime()+10*t).toISOString(),createdAt:new Date(e.getTime()-22*t).toISOString(),updatedAt:new Date(e.getTime()-15*6e4).toISOString(),activeAgents:1,totalAgents:2,description:"Generate and validate campaign assets for holiday launch."}]}function ml(e,t=null){return cs({queryKey:Wn.entities({type:"initiative",projectId:t}),queryFn:async()=>{var l;if(Lt())return Xu();const s=[],r=(t==null?void 0:t.trim())??"";let i=0;for(let d=0;d<Gu;d+=1){const u=new URLSearchParams({type:"initiative",limit:String(ao),offset:String(i)});r&&ds(u,r);const g=await fetch(`/orgx/api/entities?${u.toString()}`,{headers:St({workspaceId:r})});if(!g.ok)break;const y=await g.json(),w=y.data??[];if(s.push(...w),!!!((l=y.pagination)!=null&&l.has_more)||w.length===0)break;i+=ao}const a=r.length>0&&s.some(d=>(d.command_center_id??d.commandCenterId??"").trim().length>0),c=new Map;for(const d of s){const u=c.get(d.id);if(!u){c.set(d.id,d);continue}oo(d.updated_at??d.created_at)>oo(u.updated_at??u.created_at)&&c.set(d.id,d)}return Array.from(c.values()).filter(d=>!r||!a?!0:(d.command_center_id??d.commandCenterId??"").trim()===r).filter(d=>Vu(d.status)).sort((d,u)=>{const g=Date.parse(d.updated_at??d.created_at??"")||0;return(Date.parse(u.updated_at??u.created_at??"")||0)-g}).map(Ku)},enabled:e,staleTime:6e4})}const Rr=50,lo=8;function Qu(e){const t=(e??"").toLowerCase();return t==="completed"||t==="done"?"completed":t==="blocked"||t==="at_risk"?"blocked":t==="paused"||t==="hold"?"paused":"active"}function Ju(e){const t=(e??"").toLowerCase();return!["deleted","archived","cancelled"].includes(t)}function Yu(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function Zu(e){const t=Yu(e.sequence);return{id:e.id,name:e.title,status:Qu(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 em(e,t=null){return cs({queryKey:Wn.liveInitiatives({limit:Rr*lo,projectId:t}),queryFn:async()=>{var c;if(Lt())return[];const s=[];let r=0;for(let l=0;l<lo;l+=1){const d=new URLSearchParams({limit:String(Rr),offset:String(r)});t&&t.trim().length>0&&ds(d,t);const u=await fetch(`/orgx/api/live/initiatives?${d.toString()}`,{headers:St({workspaceId:t})});if(!u.ok)break;const g=await u.json(),y=g.initiatives??[];s.push(...y);const w=typeof g.total=="number"?g.total:null,f=(c=g.pagination)==null?void 0:c.has_more;if(!(typeof f=="boolean"?f:w!==null?r+y.length<w:y.length===Rr)||y.length===0)break;r+=Rr}const i=(t==null?void 0:t.trim())??"",a=i.length>0&&s.some(l=>(l.command_center_id??l.commandCenterId??"").trim().length>0);return s.filter(l=>!i||!a?!0:(l.command_center_id??l.commandCenterId??"").trim()===i).filter(l=>Ju(l.status)).map(Zu)},enabled:e,staleTime:3e4})}const pl=o.createContext(null);function tm({children:e}){const[t,s]=o.useState({artifactId:null}),r=o.useCallback((a,c)=>{s({artifactId:a,context:c})},[]),i=o.useCallback(()=>{s({artifactId:null})},[]);return n.jsx(pl.Provider,{value:{state:t,open:r,close:i},children:e})}function fl(){const e=o.useContext(pl);if(!e)throw new Error("useArtifactViewer must be used within ArtifactViewerProvider");return e}function nm(e){const{running:t,blocked:s,decisionsCount:r,completedToday:i,onDecisionsClick:a,onBlockedClick:c,onNewInitiative:l}=e,d=r+s;return t===0&&d===0&&i===0?{key:"idle-empty",segments:[{text:"All caught up. "},l?{text:"Start something new?",color:E.lime,clickable:!0,onClick:l}:{text:"Nothing running."}]}:t===0&&d===0?{key:"idle-done",segments:[{text:`${i} done today`,color:E.teal},{text:" · all caught up"}]}:s>0&&r>0?{key:`blocked-decisions-${s}-${r}-${t}`,segments:[...t>0?[{text:`${t} running · `}]:[],{text:`${s} blocked`,color:E.red,clickable:!0,onClick:c},{text:" · "},{text:`${r} need your input`,color:E.amber,clickable:!0,onClick:a}]}:s>0?{key:`blocked-${s}-${t}`,segments:[{text:`${s} blocked`,color:E.red,clickable:!0,onClick:c},...t>0?[{text:` · ${t} running`}]:[]]}:r>0?{key:`decisions-${r}-${t}`,segments:[...t>0?[{text:`${t} running`,color:E.lime},{text:" · "}]:[],{text:`${r} need your input`,color:E.amber,clickable:!0,onClick:a}]}:{key:`running-${t}`,segments:[{text:`${t} running`,color:E.lime},{text:" · all systems go"}]}}function co(e){const{className:t}=e,{key:s,segments:r}=nm(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 kh={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"},sm={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"},jh=e=>sm[Ot(e)]??"text-white/60 bg-white/5 border-white/10",Nh=e=>{const t=Ot(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"},Ih=e=>{const t=Ot(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"},Ah=e=>e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase()),Sh=e=>{const t=Ot(e);return t==="blocked"?0:t==="in_progress"||t==="active"?1:t==="todo"||t==="planned"?2:t==="done"||t==="completed"?3:4},js=e=>{const t=Ot(e);return t==="blocked"||t==="failed"||t==="cancelled"?E.red:t==="active"||t==="in_progress"||t==="running"?E.lime:t==="handoff"||t==="review"||t==="done"||t==="completed"?E.teal:t==="paused"||t==="queued"||t==="pending"||t==="working"||t==="planning"?E.amber:t==="archived"||t==="draft"?"rgba(255,255,255,0.5)":"rgba(255,255,255,0.35)"},ei={codex:{id:"codex",label:"Codex",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},openai:{id:"openai",label:"OpenAI",accent:"#10B981",tint:"rgba(16, 185, 129, 0.18)"},anthropic:{id:"anthropic",label:"Anthropic",accent:"#F5B700",tint:"rgba(245, 183, 0, 0.18)"},openclaw:{id:"openclaw",label:"OpenClaw",accent:"#FF4D4D",tint:"rgba(255, 77, 77, 0.18)"},orgx:{id:"orgx",label:"OrgX",accent:E.lime,tint:"rgba(191, 255, 0, 0.18)"},unknown:{id:"unknown",label:"Agent",accent:E.teal,tint:"rgba(20, 184, 166, 0.18)"}},rm=["provider","vendor","model","runtime","engine","agent","name","title","label","summary","description","source"];function Gr(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)Gr(i,t,s+1,r);return}if(typeof e=="object"){if(r.has(e))return;r.add(e);for(const[i,a]of Object.entries(e)){const c=i.toLowerCase();typeof a=="string"?(rm.some(l=>c.includes(l))||c.startsWith("meta")||c.endsWith("id"))&&Gr(a,t,s+1,r):typeof a=="object"&&a!==null&&Gr(a,t,s+1,r)}}}}function im(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 as(...e){const t=[],s=new Set;for(const r of e)Gr(r,t,0,s);for(const r of t){const i=im(r);if(i)return ei[i]}return ei.unknown}function am(e){return ei[e]??ei.unknown}const om={xs:18,sm:24,md:30};function lm({provider:e}){switch(e){case"openai":case"codex":return n.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:n.jsx("path",{fill:"currentColor",d:"M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z"})});case"anthropic":return n.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:n.jsx("path",{fill:"currentColor",d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z"})});case"openclaw":return n.jsxs("svg",{viewBox:"0 0 120 120","aria-hidden":"true",children:[n.jsx("path",{d:"M60 10C30 10 15 35 15 55C15 75 30 95 45 100V110H55V100C55 100 60 102 65 100V110H75V100C90 95 105 75 105 55C105 35 90 10 60 10Z",fill:"currentColor"}),n.jsx("path",{d:"M20 45C5 40 0 50 5 60C10 70 20 65 25 55C28 48 25 45 20 45Z",fill:"currentColor"}),n.jsx("path",{d:"M100 45C115 40 120 50 115 60C110 70 100 65 95 55C92 48 95 45 100 45Z",fill:"currentColor"}),n.jsx("circle",{cx:"45",cy:"35",r:"6",fill:"rgba(2,4,10,0.92)"}),n.jsx("circle",{cx:"75",cy:"35",r:"6",fill:"rgba(2,4,10,0.92)"})]});case"orgx":return n.jsx("img",{src:ci,alt:"","aria-hidden":"true",className:"h-full w-full rounded-[4px] object-contain"});default:return n.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[n.jsx("circle",{cx:"12",cy:"12",r:"8",stroke:"currentColor",strokeWidth:"1.8",fill:"none"}),n.jsx("path",{d:"m12 6-2 7h3l-1 5 4-8h-3l1-4Z",fill:"currentColor"})]})}}function Gs({provider:e,size:t="sm",className:s,showRing:r=!0}){const i=am(e),a=om[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(lm,{provider:e})})})}function cm({running:e,blocked:t,paused:s,size:r=36,children:i}){const a=Hn(),c=e+t+s,l=o.useMemo(()=>{if(c===0)return[];const f=[];return e>0&&f.push({color:E.lime,fraction:e/c}),t>0&&f.push({color:E.red,fraction:t/c}),s>0&&f.push({color:E.amber,fraction:s/c}),f},[e,t,s,c]),d=2.5,u=(r-d)/2,g=2*Math.PI*u,y=r/2;if(c===0)return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:r,height:r},children:[n.jsx("svg",{width:r,height:r,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:n.jsx("circle",{cx:y,cy:y,r:u,fill:"none",stroke:"rgba(255,255,255,0.08)",strokeWidth:d})}),n.jsx("div",{className:"relative z-10",children:i})]});let w=0;return n.jsxs("div",{className:"relative inline-flex items-center justify-center",style:{width:r,height:r},children:[n.jsxs("svg",{width:r,height:r,className:"absolute inset-0",style:{transform:"rotate(-90deg)"},children:[n.jsx("circle",{cx:y,cy:y,r:u,fill:"none",stroke:"rgba(255,255,255,0.06)",strokeWidth:d}),l.map((f,k)=>{const x=f.fraction*g,j=-w;return w+=x,n.jsx(he.circle,{cx:y,cy:y,r:u,fill:"none",stroke:f.color,strokeWidth:d,strokeLinecap:"round",strokeDasharray:`${x} ${g-x}`,strokeDashoffset:j,initial:a?!1:{strokeDasharray:`0 ${g}`},animate:{strokeDasharray:`${x} ${g-x}`},transition:{duration:.5,delay:k*.08,ease:[.22,1,.36,1]},style:{opacity:.85}},k)})]}),n.jsx("div",{className:"relative z-10",children:i})]})}const Lr={initiativeId:"",workstreams:[],milestones:[],tasks:[]};function pa(e){if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.max(0,Math.trunc(e));return t>0?t-1:t}function fa(e,t){if(typeof t=="number")return`${e}${t+1}`}const dm=(e,t)=>{const s=pa(e.sequence??e.order);return{id:e.id,name:e.name??"Untitled workstream",summary:e.summary??null,status:e.status??"planned",progress:typeof e.progress=="number"&&!Number.isNaN(e.progress)?Math.max(0,Math.min(100,e.progress<=1?e.progress*100:e.progress)):null,initiativeId:e.initiative_id??t,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fa("W",s)}},um=(e,t)=>{const s=pa(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled milestone",description:e.description??null,status:e.status??"planned",dueDate:e.due_date??null,initiativeId:e.initiative_id??t,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fa("M",s)}},mm=(e,t)=>{const s=pa(e.sequence??e.order);return{id:e.id,title:e.title??"Untitled task",description:e.description??null,status:e.status??"todo",priority:e.priority??null,dueDate:e.due_date??null,initiativeId:e.initiative_id??t,milestoneId:e.milestone_id??null,workstreamId:e.workstream_id??null,createdAt:e.created_at??null,sequenceIndex:s,hierarchyLabel:fa("T",s)}};function _i(e){return[...e].sort((t,s)=>{const r=typeof t.sequenceIndex=="number"?t.sequenceIndex:Number.POSITIVE_INFINITY,i=typeof s.sequenceIndex=="number"?s.sequenceIndex:Number.POSITIVE_INFINITY;if(r!==i)return r-i;const a=t.createdAt?Date.parse(t.createdAt):0,c=s.createdAt?Date.parse(s.createdAt):0;return a!==c?a-c:0})}function pm(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 l;const i=Pc(e),a=o.useMemo(()=>Wn.initiativeDetails({initiativeId:e,authToken:t,embedMode:s}),[e,t,s]),c=cs({queryKey:a,enabled:r&&!!e&&i,queryFn:async()=>{if(!e)return Lr;if(Lt())return pm(e);if(!i)return{...Lr,initiativeId:e};const d={};s&&(d["X-Orgx-Embed"]="true"),t&&(d.Authorization=`Bearer ${t}`);const u=Object.keys(d).length?d:void 0,g=async v=>{try{const b=new URLSearchParams({type:v,initiative_id:e,limit:"100"}),h=await fetch(`/orgx/api/entities?${b.toString()}`,{headers:u});return h.ok?await h.json():{data:[]}}catch{return{data:[]}}},[y,w,f]=await Promise.all([g("workstream"),g("milestone"),g("task")]),k=Array.isArray(y.data)?_i(y.data.map(v=>dm(v,e))):[],x=Array.isArray(w.data)?_i(w.data.map(v=>um(v,e))):[],j=Array.isArray(f.data)?_i(f.data.map(v=>mm(v,e))):[];return{initiativeId:e,workstreams:k,milestones:x,tasks:j}}});return{details:(i?c.data:null)??(e?{...Lr,initiativeId:e}:Lr),isLoading:i?c.isLoading:!1,error:i?((l=c.error)==null?void 0:l.message)??null:null,refetch:c.refetch}}function hm(){const e=new Date().toISOString();return{generatedAt:e,agents:[{id:"eli",name:"Eli",workspace:"Q4 Feature Ship",model:"gpt-5",isDefault:!0,status:"running",currentTask:"Planning",runId:"run-1",startedAt:e,blockers:[],context:null},{id:"dana",name:"Dana",workspace:"Q4 Feature Ship",model:"claude-sonnet-4.5",isDefault:!1,status:"running",currentTask:"Dashboard UI pass",runId:"run-2",startedAt:e,blockers:["Approval pending"],context:null},{id:"mark",name:"Mark",workspace:"Black Friday Email",model:"gpt-5-mini",isDefault:!1,status:"running",currentTask:"Campaign variants",runId:"run-4",startedAt:e,blockers:[],context:null}]}}function ha({enabled:e=!0,staleTime:t=5e3,refetchInterval:s}={}){return cs({queryKey:["openclaw-agent-catalog"],queryFn:async()=>{if(Lt())return hm();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 or(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:E.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:E.iris,bg:"rgba(124,124,255,0.10)"}}function gm(e){return[...e.workstreams].sort((t,s)=>t.name.localeCompare(s.name))}function xm(e,t){return[...t?e.tasks.filter(r=>r.workstreamId===t):e.tasks].sort((r,i)=>r.title.localeCompare(i.title))}function ym({open:e,onClose:t,onLaunched:s}){var ie,ve,je,te,Me,pe;const r=ha({enabled:e,staleTime:2e3,refetchInterval:e?3e3:!1}),{data:i}=ml(e),[a,c]=o.useState(""),[l,d]=o.useState(""),[u,g]=o.useState(""),[y,w]=o.useState(""),[f,k]=o.useState("auto"),[x,j]=o.useState(""),[v,b]=o.useState(null),[h,_]=o.useState(null),[V,oe]=o.useState("starter"),[K,be]=o.useState(!1),[H,Z]=o.useState(1),ce=Lt(),ye=o.useMemo(()=>{const M=l.trim();return M?(i==null?void 0:i.find(O=>O.id===M))??null:null},[i,l]),{details:we}=fm({initiativeId:ye?ye.id:null,enabled:e&&!!ye}),W=o.useMemo(()=>gm(we),[we]),Ie=o.useMemo(()=>xm(we,u||null),[we,u]),Te=((ie=r.data)==null?void 0:ie.agents)??[],fe=o.useMemo(()=>{const M=a.trim();return M?Te.find(O=>O.id===M)??null:null},[Te,a]);o.useEffect(()=>{var O,U;if(!e)return;const M=((O=Te.find(se=>se.isDefault))==null?void 0:O.id)??((U=Te[0])==null?void 0:U.id)??"";!a&&M&&c(M)},[Te,e,a]),o.useEffect(()=>{if(!e||l.trim())return;const M=i??[],O=M.length===1?M[0]:null;O&&d(O.id)},[i,e,l]),o.useEffect(()=>{if(!e)return;const M=(fe==null?void 0:fe.model)??"",O=M.includes("openrouter")?"openrouter":M.includes("anthropic")?"anthropic":M.includes("openai")?"openai":"auto";k(O)},[e,fe==null?void 0:fe.model,a]),o.useEffect(()=>{e&&(b(null),_(null),oe("starter"),Z(1))},[e]),o.useEffect(()=>{g(""),w("")},[l]),o.useEffect(()=>{w("")},[u]),o.useEffect(()=>{e&&(x.trim().length>0||ye&&j(`Kick off: ${ye.name}`))},[x,e,ye]);const ee=!!a.trim()&&!!l.trim(),de=H===1?!!a.trim():H===2?!!l.trim():ee,Ee=async()=>{var qe;const M=(h==null?void 0:h.checkout)??"/orgx/api/billing/checkout",O=V&&V.trim().length>0?V.trim():"starter",se=await(await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:O,billingCycle:"monthly"})})).json().catch(()=>null),Re=((qe=se==null?void 0:se.data)==null?void 0:qe.url)??(se==null?void 0:se.url)??null;if(!Re)throw new Error((se==null?void 0:se.error)??"Checkout unavailable");window.open(Re,"_blank","noopener,noreferrer")},ne=async()=>{var Re;const M=(h==null?void 0:h.portal)??"/orgx/api/billing/portal",U=await(await fetch(M,{method:"POST"})).json().catch(()=>null),se=((Re=U==null?void 0:U.data)==null?void 0:Re.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")},R=async()=>{if(!(!ee||K)){if(ce){t(),s==null||s();return}b(null),_(null),be(!0);try{const M={agentId:a.trim(),message:x.trim()?x.trim():void 0,initiativeId:l.trim(),initiativeTitle:(ye==null?void 0:ye.name)??null,workstreamId:u.trim()?u.trim():null,taskId:y.trim()?y.trim():null,provider:f!=="auto"?f:null},O=new URLSearchParams;O.set("agentId",M.agentId),O.set("initiativeId",M.initiativeId),M.initiativeTitle&&O.set("initiativeTitle",M.initiativeTitle),M.workstreamId&&O.set("workstreamId",M.workstreamId),M.taskId&&O.set("taskId",M.taskId),M.message&&O.set("message",M.message),M.provider&&O.set("provider",M.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(M){b(M instanceof Error?M.message:"Launch failed")}finally{be(!1)}}},J=!!((ve=fe==null?void 0:fe.run)!=null&&ve.runId)&&!!((je=fe==null?void 0:fe.run)!=null&&je.pid),P=async()=>{var M;if(!(!((M=fe==null?void 0:fe.run)!=null&&M.runId)||!J||K)&&!ce){b(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){b(O instanceof Error?O.message:"Stop failed")}finally{be(!1)}}},Y=async()=>{var M;if(!(!((M=fe==null?void 0:fe.run)!=null&&M.runId)||K)){if(ce){t(),s==null||s();return}b(null),be(!0);try{const O=new URLSearchParams;O.set("runId",fe.run.runId),x.trim()&&O.set("message",x.trim()),f&&f!=="auto"&&O.set("provider",f);const 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){b(O instanceof Error?O.message:"Restart failed")}finally{be(!1)}}};return e?n.jsx(di,{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(([M,O])=>n.jsxs("button",{type:"button",onClick:()=>Z(M),className:le("rounded-full px-3 py-1 transition-colors",H===M?"bg-white/[0.12] text-white":"hover:bg-white/[0.06]"),children:[M,". ",O]},M))})]}),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:[H===1&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Agent"}),n.jsx("select",{value:a,onChange:M=>c(M.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:Te.map(M=>{const O=or(M.status);return n.jsxs("option",{value:M.id,children:[M.name," (",M.id,") · ",O.label]},M.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:`${or(fe.status).color}55`,color:or(fe.status).color,backgroundColor:or(fe.status).bg},children:or(fe.status).label})]}),n.jsxs("div",{className:"mt-2 space-y-2",children:[n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Model:"})," ",fe.model??"unknown"]}),n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Workspace:"})," ",fe.workspace??"unknown"]}),((te=fe.context)==null?void 0:te.initiativeId)&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Scoped:"})," ",fe.context.initiativeTitle??fe.context.initiativeId]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Provider"}),n.jsxs("select",{value:f,onChange:M=>k(M.target.value),className:"mt-1 w-full rounded-xl border border-white/[0.1] bg-black/30 px-3 py-2 text-body text-primary focus:outline-none focus:ring-1 focus:ring-[#BFFF00]/30",children:[n.jsx("option",{value:"auto",children:"Auto (keep agent model)"}),n.jsx("option",{value:"anthropic",children:"Anthropic"}),n.jsx("option",{value:"openrouter",children:"OpenRouter"}),n.jsx("option",{value:"openai",children:"OpenAI"})]}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Selecting a provider updates the agent's default model before launch."})]}),fe.run&&n.jsxs("p",{className:"truncate",children:[n.jsx("span",{className:"text-muted",children:"Tracked run:"})," ",fe.run.runId.slice(0,8),"…"," ",n.jsxs("span",{className:"text-muted",children:["(",fe.run.status,")"]})]}),fe.run&&n.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[n.jsx("button",{type:"button",onClick:P,disabled:!J||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:Y,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"})]})]})]})]}),H===2&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Initiative Scope"}),n.jsxs("select",{value:l,onChange:M=>d(M.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(M=>n.jsx("option",{value:M.id,children:M.name},M.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:M=>g(M.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(M=>n.jsx("option",{value:M.id,children:M.name},M.id))]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task (optional)"}),n.jsxs("select",{value:y,onChange:M=>w(M.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(M=>n.jsx("option",{value:M.id,children:M.title},M.id))]}),Ie.length>80&&n.jsx("p",{className:"mt-1 text-micro text-muted",children:"Showing first 80 tasks to keep the menu usable."})]})]})]}),H===3&&n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-caption uppercase tracking-[0.1em] text-muted",children:"Kickoff Message"}),n.jsx("textarea",{value:x,onChange:M=>j(M.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)??l.trim())||"—"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Workstream"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:u.trim()?((Me=W.find(M=>M.id===u))==null?void 0:Me.name)??u:"Any"})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-black/20 px-3 py-2",children:[n.jsx("div",{className:"text-micro uppercase tracking-[0.12em] text-muted",children:"Task"}),n.jsx("div",{className:"mt-0.5 truncate text-body text-primary",children:y.trim()?((pe=Ie.find(M=>M.id===y))==null?void 0:pe.title)??y:"Any"})]})]})]})]})]},H)}),v&&n.jsx("div",{className:"mt-3 rounded-xl border border-rose-300/20 bg-rose-400/10 px-3 py-2 text-body text-rose-100",children:n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("div",{children:v}),h&&n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void Ee().catch(M=>b(M instanceof Error?M.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(M=>b(M instanceof Error?M.message:"Portal failed")),className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition-colors hover:bg-white/[0.08]",children:"Billing portal"}),h.pricing&&n.jsx("a",{href:h.pricing,target:"_blank",rel:"noopener noreferrer",className:"text-caption text-secondary underline decoration-white/20 hover:text-primary",children:"View pricing"})]})]})})]}),n.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-subtle px-5 py-3.5 sm:px-6",children:[n.jsx("div",{className:"text-caption text-secondary",children:H===1?"Pick an agent to configure.":H===2?"Select an initiative scope (required).":ee?"Launch will update sessions/activity under the selected initiative.":"Select an agent and initiative to launch."}),n.jsxs("div",{className:"flex items-center gap-2",children:[H>1&&n.jsx("button",{type:"button",onClick:()=>Z(M=>M>1?M-1:M),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"}),H<3?n.jsx("button",{type:"button",onClick:()=>Z(M=>M<3?M+1:M),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:E.lime}:void 0,children:"Next"}):n.jsx("button",{type:"button",onClick:R,disabled:!ee||K,className:le("rounded-xl px-4 py-2 text-body font-semibold transition-colors",ee&&!K?"text-black":"cursor-not-allowed border border-strong bg-white/[0.05] text-muted"),style:ee&&!K?{backgroundColor:E.lime}:void 0,children:K?"Launching…":"Launch"})]})]})]})}):null}const Ci=10,bm=20;function wm(e){const t=(e??"").toLowerCase();return t==="active"?{label:"Active",color:E.lime,bg:"rgba(191,255,0,0.12)"}:t==="blocked"?{label:"Blocked",color:"#fb7185",bg:"rgba(244, 63, 94, 0.12)"}:t==="idle"?{label:"Idle",color:"rgba(255,255,255,0.55)",bg:"rgba(255,255,255,0.06)"}:{label:e||"Unknown",color:E.iris,bg:"rgba(124,124,255,0.10)"}}function vm(e){return e?e.includes("error")||e.includes("fail")?E.red:e.includes("decision")||e.includes("block")?E.amber:e.includes("complete")||e.includes("success")?E.teal:e.includes("start")||e.includes("launch")?E.lime:E.iris:E.iris}function km({open:e,onClose:t,agentName:s,catalogAgent:r,sessions:i,activity:a,onSelectSession:c,onRefresh:l}){var be,H,Z,ce,ye,we;const[d,u]=o.useState(!1),[g,y]=o.useState(!1),[w,f]=o.useState(null),k=nl(s),x=wm((r==null?void 0:r.status)??null),j=o.useMemo(()=>{let W=0,Ie=0,Te=0,fe=0;for(const ee of i)ee.status==="running"||ee.status==="queued"||ee.status==="pending"?W++:ee.status==="blocked"?Ie++:ee.status==="failed"||ee.status==="cancelled"?Te++:(ee.status==="completed"||ee.status==="archived")&&fe++;return{running:W,blocked:Ie,failed:Te,completed:fe}},[i]),v=o.useMemo(()=>[...i].sort((W,Ie)=>Date.parse(Ie.updatedAt??Ie.lastEventAt??Ie.startedAt??"")-Date.parse(W.updatedAt??W.lastEventAt??W.startedAt??"")),[i]),b=d?v:v.slice(0,Ci),h=v.length>Ci,_=o.useMemo(()=>[...a].sort((W,Ie)=>Date.parse(Ie.timestamp)-Date.parse(W.timestamp)).slice(0,bm),[a]),V=!!((be=r==null?void 0:r.run)!=null&&be.runId)&&!!((H=r==null?void 0:r.run)!=null&&H.pid),oe=async()=>{var W;if(!(!((W=r==null?void 0:r.run)!=null&&W.runId)||!V||g)){f(null),y(!0);try{const Ie=await fetch(`/orgx/api/agents/stop?runId=${encodeURIComponent(r.run.runId)}`,{method:"POST"}),Te=await Ie.json().catch(()=>null);if(!Ie.ok||!(Te!=null&&Te.ok))throw new Error((Te==null?void 0:Te.error)??`Stop failed (${Ie.status})`);l==null||l()}catch(Ie){f(Ie instanceof Error?Ie.message:"Stop failed")}finally{y(!1)}}},K=async()=>{var W;if(!(!((W=r==null?void 0:r.run)!=null&&W.runId)||g)){f(null),y(!0);try{const Ie=new URLSearchParams;Ie.set("runId",r.run.runId);const Te=await fetch(`/orgx/api/agents/restart?${Ie.toString()}`,{method:"POST"}),fe=await Te.json().catch(()=>null);if(!Te.ok||!(fe!=null&&fe.ok))throw new Error((fe==null?void 0:fe.error)??`Restart failed (${Te.status})`);l==null||l()}catch(Ie){f(Ie instanceof Error?Ie.message:"Restart failed")}finally{y(!1)}}};return e?n.jsx(di,{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(Ft,{name:s,size:"lg",hint:s}),n.jsxs("div",{className:"min-w-0 flex-1 pt-1",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("h3",{className:"text-[28px] font-medium leading-none text-white truncate",children:s}),n.jsx("span",{className:"rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-widest",style:{color:x.color,backgroundColor:x.bg},children:x.label})]}),k&&n.jsx("p",{className:"text-[15px] text-secondary mt-2",children:k})]})]}),n.jsx("div",{className:"flex items-center gap-12 pt-2 pb-6 border-b border-white/[0.04]",children:[{label:"Running",value:j.running,color:E.lime},{label:"Blocked",value:j.blocked,color:E.red},{label:"Failed",value:j.failed,color:E.amber},{label:"Completed",value:j.completed,color:E.teal}].map(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:[b.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:js(W.status)}}),n.jsxs("button",{onClick:()=>{c(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)),h&&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 ${v.length-Ci} older sessions`})]})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-6",children:"Live Activity"}),_.length===0?n.jsx("p",{className:"text-body text-muted italic",children:"No recent activity."}):n.jsx("div",{className:"relative border-l border-white/[0.06] pl-6 ml-2 space-y-5",children:_.map((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:vm(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:!V||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"})]}),w&&n.jsx("p",{className:"w-full text-caption text-rose-400",children:w})]})]}),r&&n.jsxs("div",{className:"pt-4 border-t border-white/[0.04]",children:[n.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-widest text-muted mb-4",children:"Settings"}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-y-4 gap-x-8",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-[11px] text-muted mb-1",children:"Provider"}),n.jsx("p",{className:"text-[14px] text-primary",children:(Z=r.model)!=null&&Z.includes("openrouter")?"OpenRouter":(ce=r.model)!=null&&ce.includes("anthropic")?"Anthropic":(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 Dr=120,uo=10,jm=24,mo=520,Nm=58,Im=56,Am=20,Sm=8,ga=new Set(["running","active","in_progress","working","planning","handoff","review"]),_m=new Set(["blocked","failed"]),Cm=10,Mm=[{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"}],Tm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ea=[{id:"eli",name:"Eli",role:"Engineering",aliases:[/\beli\b/i,/\borgx[\s_-]*engineering\b/i,/^\s*engineering\s*$/i]},{id:"dana",name:"Dana",role:"Product Design",aliases:[/\bdana\b/i,/\borgx[\s_-]*design\b/i,/\borgx[\s_-]*product\b/i,/\bproduct[\s_-]*design\b/i]},{id:"mark",name:"Mark",role:"Marketing",aliases:[/\bmark\b/i,/\borgx[\s_-]*marketing\b/i,/^\s*marketing\s*$/i]},{id:"sage",name:"Sage",role:"Sales",aliases:[/\bsage\b/i,/\borgx[\s_-]*sales\b/i,/^\s*sales\s*$/i]},{id:"orion",name:"Orion",role:"Operations",aliases:[/\borion\b/i,/\borgx[\s_-]*operations\b/i,/^\s*operations\s*$/i]},{id:"xandy",name:"Xandy",role:"Orchestrator",aliases:[/\bxandy\b/i,/\borgx[\s_-]*orchestrator\b/i,/^\s*orchestrator\s*$/i]},{id:"pace",name:"Pace",role:"Engineering",aliases:[/\bpace\b/i,/\borgx[\s_-]*pace\b/i]}];function nt(e){const t=e==null?void 0:e.trim().toLowerCase();return t&&t.length>0?t:null}function xn(e,t){const s=nt(e),r=nt(t);if(!s&&!r)return null;const i=[s,r].filter(Boolean).join(" ");if(!i)return null;for(const a of ea)if(a.aliases.some(c=>c.test(i)))return{agentId:`orgx:${a.id}`,agentName:a.name,role:a.role};return null}function Em(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 Rm(e){const t=nt(e.runtimeClient);if(t==="codex")return"codex";if(t==="claude-code")return"claude-code";if(t==="openclaw")return"openclaw";if(t==="api")return"api";const s=[e.title,e.lastEventSummary,e.runtimeLabel,e.runtimeProvider,e.groupLabel].filter(r=>typeof r=="string"&&r.trim().length>0).join(" ").toLowerCase();return s.includes("claude-code")||s.includes("anthropic")||s.includes("claude")?"claude-code":s.includes("openclaw")?"openclaw":s.includes("codex")||s.includes("openai")?"codex":s.includes("orgx api")||s.includes("source_client=api")?"api":null}function hl(e){const t=Em(e);if(t)return{agentId:t.agentId,agentName:t.agentName};const s=nt(e.agentId),r=nt(e.agentName);if(s||r)return{agentId:e.agentId??null,agentName:e.agentName??null};const i=Rm(e);return i==="codex"?{agentId:"runtime:codex",agentName:"Codex"}:i==="claude-code"?{agentId:"runtime:claude-code",agentName:"Claude Code"}:i==="openclaw"?{agentId:"runtime:openclaw",agentName:"OpenClaw"}:i==="api"?{agentId:"runtime:api",agentName:"OrgX API"}:{agentId:null,agentName:null}}function Lm(e){const t=hl(e),s=nt(t.agentId);if(s)return`id:${s}`;const r=nt(t.agentName);return r?`name:${r}`:"unassigned"}function Dm(e){const t=e.trim();return t?Tm.test(t)?`${t.slice(0,8)}…${t.slice(-4)}`:!t.includes(" ")&&t.length>64?`${t.slice(0,48)}…`:t:"OrgX"}function ti(e){const t=(e??"").trim();return t?Cs(t):!1}function $m(e){var t,s;return!!(ti((t=e.context)==null?void 0:t.initiativeId)||ti(((s=e.run)==null?void 0:s.initiativeId)??null))}function Mi(e){if(xn(e.agentId,e.agentName))return!0;const s=nt(e.agentId);return!!(s!=null&&s.startsWith("orgx"))}function on(e){const t=nt(e.status)??"archived";if(t==="blocked"||t==="failed"||t==="completed"||t==="cancelled")return t;const s=nt(e.phase);if(s==="blocked")return"blocked";if(s==="handoff")return"handoff";if(s==="completed")return"completed";if(s==="review")return"review";const r=nt(e.state);return r==="error"?"failed":r==="stopped"?"paused":r==="stale"?"queued":ga.has(t)?t:Array.isArray(e.blockers)&&e.blockers.length>0?"blocked":t}function ta(e){const t=nt(e);return t?ga.has(t)||_m.has(t):!1}function po(e){const t=nt(e);return t?ga.has(t):!1}function $r(e){return e?!!(ta(e.status)||e.runId&&e.runId.trim().length>0||e.currentTask&&e.currentTask.trim().length>0):!1}function Fm(e){return e?e.state==="active":!1}function Pm(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function Sn(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ti(e,t){return Sn(t.updatedAt??t.lastEventAt??t.startedAt)-Sn(e.updatedAt??e.lastEventAt??e.startedAt)}function Om({status:e,nodes:t,onSelectSession:s,selectedSessionId:r}){const[i,a]=o.useState(!1),c=js(e),l=e==="blocked"?"blocked":e==="failed"?"failed":"paused";return n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>a(d=>!d),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-white/[0.05]",children:[n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:c}}),n.jsxs("span",{className:"flex-1 text-body text-secondary",children:[t.length," ",l," sessions"]}),n.jsx(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,y=as(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(Gs,{provider:y.id,size:"xs"}),n.jsx("p",{className:"min-w-0 flex-1 truncate text-body text-bright",title:d.title,children:d.title}),n.jsx("span",{className:"text-micro text-muted",children:_t(d.updatedAt??d.lastEventAt??d.startedAt??Date.now())})]})},d.id)})})})]})}const Bm=o.memo(function({sessions:t,activity:s,selectedSessionId:r,onSelectSession:i,timeFilterId:a,onAgentFilter:c,agentFilter:l,onReconnect:d,onLaunched:u,connectionStatus:g,runtimeInstances:y=[],showSyntheticEntities:w=!1}){var T;const[f,k]=o.useState(new Set),[x,j]=o.useState(!1),[v,b]=o.useState(!1),[h,_]=o.useState(0),[V,oe]=o.useState(null),K=ha({enabled:!0}),be=((T=K.data)==null?void 0:T.agents)??[],H=o.useMemo(()=>br(a),[a]),Z=o.useMemo(()=>H===null?s:s.filter(q=>Sn(q.timestamp)>=H),[s,H]);o.useMemo(()=>{var ue,_e,Ye;const q=new Map,re=[...Z].sort((Ge,$e)=>Sn($e.timestamp)-Sn(Ge.timestamp));for(const Ge of re){const $e=Ge.runId;if(!$e||q.has($e))continue;const Ke=((ue=Ge.summary)==null?void 0:ue.trim())??((_e=Ge.description)==null?void 0:_e.trim())??((Ye=Ge.title)==null?void 0:Ye.trim())??"";Ke.length>0&&q.set($e,Ke)}return q},[Z]);const{agents:ce,hiddenGroupCount:ye,filteredOutGroupsByDate:we,filteredOutSessionsByDate:W,visibleSessionCount:Ie,archivedGroups:Te,sessionCountInScope:fe}=o.useMemo(()=>{var Pe;const q=w?t.nodes:t.nodes.filter(z=>!ti(z.initiativeId)),re=w?be:be.filter(z=>!$m(z)),ue=w?y:y.filter(z=>!ti(z.initiativeId)),_e=new Map,Ye=new Map,Ge=[...ue].sort((z,Q)=>Sn(Q.lastEventAt??Q.lastHeartbeatAt)-Sn(z.lastEventAt??z.lastHeartbeatAt));for(const z of Ge){z.runId&&!_e.has(z.runId)&&_e.set(z.runId,z);const Q=xn(z.agentId,z.agentName??z.displayName),Ne=nt((Q==null?void 0:Q.agentId)??z.agentId);if(Ne){const Le=Ye.get(Ne)??[];Le.push(z),Ye.set(Ne,Le)}}const $e=new Map;for(const z of q){const Q=hl(z),Ne=Lm(z),Le=nt(Q.agentId),De=nt(Q.agentName);let Oe=$e.get(Ne)??null;if(!Oe&&Le&&De){const Se=`name:${De}`,Ve=$e.get(Se);Ve&&($e.delete(Se),Ve.groupKey=Ne,$e.set(Ne,Ve),Oe=Ve)}if(!Oe&&De){const Se=Array.from($e.values()).find(Ve=>nt(Ve.agentName)===De);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)):$e.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,Le=(Q==null?void 0:Q.agentName)??z.name,De=nt(Ne),Oe=nt(Le),Se=De?`id:${De}`:null,Ve=Oe?`name:${Oe}`:null;let ct=null;if(Se&&$e.has(Se))ct=Se;else if(Ve&&$e.has(Ve))ct=Ve;else{const ze=Array.from($e.entries()).find(([,Ct])=>De&&nt(Ct.agentId)===De||Oe&&nt(Ct.agentName)===Oe);ct=(ze==null?void 0:ze[0])??null}if(ct){const ze=$e.get(ct);ze.catalogAgent=z,!ze.agentId&&Ne&&(ze.agentId=Ne),(ze.agentName==="OrgX"||!ze.agentName)&&Le&&(ze.agentName=Le),Se&&ze.groupKey!==Se&&!$e.has(Se)&&($e.delete(ze.groupKey),ze.groupKey=Se,$e.set(Se,ze))}else{const ze=Se??Ve??`catalog:${Le.toLowerCase()}`;$e.set(ze,{groupKey:ze,agentId:Ne,agentName:Le,nodes:[],latest:null,catalogAgent:z,runtime:null,runtimeActiveCount:0})}}for(const z of ea){const Q=`orgx:${z.id}`,Ne=`id:${Q}`;let Le=$e.get(Ne)??null;if(!Le){const De=Array.from($e.entries()).find(([,Oe])=>{const Se=xn(Oe.agentId,Oe.agentName);return nt(Se==null?void 0:Se.agentId)===nt(Q)});De&&($e.delete(De[0]),Le=De[1],Le.groupKey=Ne,$e.set(Ne,Le))}if(Le||(Le={groupKey:Ne,agentId:Q,agentName:z.name,nodes:[],latest:null,runtime:null,runtimeActiveCount:0},$e.set(Ne,Le)),Le.agentId=Q,Le.agentName=z.name,!Le.catalogAgent){const De=re.find(Oe=>{const Se=xn(Oe.id,Oe.name);return nt(Se==null?void 0:Se.agentId)===nt(Q)});De&&(Le.catalogAgent=De)}}const Ke=new Map(ea.map((z,Q)=>[nt(`orgx:${z.id}`),Q]));for(const z of $e.values()){z.nodes.length>0&&(z.nodes.sort(Ti),z.latest=z.nodes[0]);const Q=[],Ne=new Set;if((Pe=z.latest)!=null&&Pe.runId){const De=_e.get(z.latest.runId);De&&!Ne.has(De.id)&&(Q.push(De),Ne.add(De.id))}for(const De of z.nodes){if(!De.runId)continue;const Oe=_e.get(De.runId);Oe&&!Ne.has(Oe.id)&&(Q.push(Oe),Ne.add(Oe.id))}const Le=nt(z.agentId);if(Le)for(const De of Ye.get(Le)??[])Ne.has(De.id)||(Q.push(De),Ne.add(De.id));Q.sort((De,Oe)=>Sn(Oe.lastEventAt??Oe.lastHeartbeatAt)-Sn(De.lastEventAt??De.lastHeartbeatAt)),z.runtime=Q[0]??null,z.runtimeActiveCount=Q.filter(De=>Fm(De)).length}const We=Array.from($e.values()).sort((z,Q)=>{const Ne=Mi(z),Le=Mi(Q);if(Ne!==Le)return Ne?-1:1;if(Ne&&Le){const De=xn(z.agentId,z.agentName),Oe=xn(Q.agentId,Q.agentName),Se=Ke.get(nt((De==null?void 0:De.agentId)??z.agentId))??999,Ve=Ke.get(nt((Oe==null?void 0:Oe.agentId)??Q.agentId))??999;if(Se!==Ve)return Se-Ve}return z.latest&&Q.latest?Ti(z.latest,Q.latest):z.latest&&!Q.latest?-1:!z.latest&&Q.latest?1:z.agentName.localeCompare(Q.agentName)}),ht=Jo(a),st=ht.id==="live",rt=ht.minutes===null||st?null:Date.now()-ht.minutes*6e4,ge=[],He=[];let Ae=0,B=0;for(const z of We){const Q=(z.runtimeActiveCount??0)>0,Ne=Mi(z);if(z.nodes.length===0){const Se=$r(z.catalogAgent);(Ne||st&&(Se||Q))&&ge.push(z);continue}if(st){const Se=z.nodes.filter(ze=>ta(on(ze))),Ve=z.nodes.filter(ze=>!ta(on(ze))),ct=$r(z.catalogAgent);if(Se.length===0){Ne||ct||Q?ge.push({...z,nodes:[],latest:null}):(Ae+=1,B+=z.nodes.length,He.push(z));continue}B+=Ve.length,Ve.length>0&&He.push({...z,nodes:Ve,latest:Ve[0]??null}),ge.push({...z,nodes:Se,latest:Se[0]??null});continue}if(rt===null){ge.push(z);continue}const Le=z.nodes.filter(Se=>po(on(Se))?!0:Sn(Se.updatedAt??Se.lastEventAt??Se.startedAt)>=rt),De=$r(z.catalogAgent);if(Le.length===0){Ne||De||Q?ge.push({...z,nodes:[],latest:null}):(Ae+=1,B+=z.nodes.length,He.push(z));continue}const Oe=z.nodes.filter(Se=>po(on(Se))?!1:Sn(Se.updatedAt??Se.lastEventAt??Se.startedAt)<rt);B+=Oe.length,Oe.length>0&&He.push({...z,nodes:Oe,latest:Oe[0]}),ge.push({...z,nodes:Le,latest:Le[0]})}return{agents:ge.slice(0,Dr),hiddenGroupCount:Math.max(0,ge.length-Dr),filteredOutGroupsByDate:Ae,filteredOutSessionsByDate:B,visibleSessionCount:ge.slice(0,Dr).reduce((z,Q)=>z+Q.nodes.length,0),archivedGroups:He,sessionCountInScope:q.length}},[a,t.nodes,be,y,w]);o.useEffect(()=>{b(!1),_(0)},[a]);const ee=o.useMemo(()=>Te.reduce((q,re)=>q+re.nodes.length,0),[Te]),de=o.useMemo(()=>ce.filter(q=>q.nodes.length>0).map(q=>q.groupKey),[ce]),Ee=o.useMemo(()=>{if(de.length===0)return{allCollapsed:!1,allExpanded:!0};let q=0;for(const re of de)f.has(re)&&(q+=1);return{allCollapsed:q===de.length,allExpanded:q===0}},[f,de]),ne=o.useMemo(()=>{const q=[];for(const re of Te)for(const ue of re.nodes)q.push({node:ue,agentName:re.agentName});return q.sort((re,ue)=>Ti(re.node,ue.node)),q.slice(0,(h+1)*Cm)},[Te,h]),R=q=>{k(re=>{const ue=new Set(re);return ue.has(q)?ue.delete(q):ue.add(q),ue})},J=()=>{k(()=>Ee.allCollapsed?new Set:new Set(de))},P=o.useMemo(()=>V?ce.find(q=>q.groupKey===V)??null:null,[ce,V]),Y=o.useMemo(()=>(P==null?void 0:P.nodes)??[],[P]),ie=o.useMemo(()=>{if(!P)return[];const q=nt(P.agentName),re=nt(P.agentId),ue=xn(P.agentId,P.agentName);return Z.filter(_e=>{const Ye=nt(_e.agentName),Ge=nt(_e.agentId),$e=xn(_e.agentId,_e.agentName);return q!==null&&Ye===q||re!==null&&Ge===re||ue!==null&&$e!==null&&nt(ue.agentId)===nt($e.agentId)})},[Z,P]),ve=fe===0,je=be.length>0,te=o.useRef(null),[Me,pe]=o.useState(0),[M,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=te.current;if(!q)return;const re=()=>{const ue=q.clientHeight,_e=q.scrollTop;O(Ye=>Ye===ue?Ye:ue),pe(Ye=>Math.abs(Ye-_e)<1?Ye:_e)};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:Re,bottomVirtualSpacerPx:qe,virtualizationEnabled:Ce}=o.useMemo(()=>{if(!(ce.length>jm&&M>0))return{visibleAgentGroups:ce,topVirtualSpacerPx:0,bottomVirtualSpacerPx:0,virtualizationEnabled:!1};const re=ce.map(We=>{const st=f.has(We.groupKey)?0:Math.min(We.nodes.length,uo);let rt=Nm;return st>0&&(rt+=Am+st*Im,We.nodes.length>st&&(rt+=20)),rt+Sm}),ue=new Array(re.length+1).fill(0);for(let We=0;We<re.length;We+=1)ue[We+1]=ue[We]+re[We];const _e=ue[ue.length-1],Ye=Math.max(0,Me-mo),Ge=Me+M+mo;let $e=0;for(;$e<ce.length&&ue[$e+1]<Ye;)$e+=1;let Ke=$e;for(;Ke<ce.length&&ue[Ke]<Ge;)Ke+=1;return Ke<=$e&&(Ke=Math.min(ce.length,$e+1)),{visibleAgentGroups:ce.slice($e,Ke),topVirtualSpacerPx:ue[$e],bottomVirtualSpacerPx:Math.max(0,_e-ue[Ke]),virtualizationEnabled:!0}},[ce,f,Me,M]);return n.jsxs(Ks,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsx(ym,{open:x,onClose:()=>j(!1),onLaunched:()=>{K.refetch(),u==null||u()}}),n.jsx(km,{open:V!==null,onClose:()=>oe(null),agentName:(P==null?void 0:P.agentName)??"",catalogAgent:(P==null?void 0:P.catalogAgent)??null,sessions:Y,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:J,disabled:de.length===0,className:"control-pill hidden flex-shrink-0 px-3 text-caption font-semibold sm:inline-flex",title:Ee.allCollapsed?"Expand all agent groups":"Collapse all agent groups",children:Ee.allCollapsed?"Expand":"Collapse"}),n.jsx("button",{type:"button",onClick:()=>j(!0),className:"control-pill flex-shrink-0 px-3 text-caption font-semibold",children:"Launch"})]})]})}),n.jsxs("div",{ref:te,onScroll: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(ui,{icon:"agents",headline:"No active sessions yet",description:"Start a session to see agent conversations here."}),l&&c&&n.jsxs("div",{className:"flex items-center justify-between rounded-lg bg-[#0AD4C4]/[0.08] px-3 py-1.5 text-caption text-[#0AD4C4]",children:[n.jsxs("span",{children:["Filtered: ",l]}),n.jsx("button",{type:"button",onClick:()=>c(null),className:"text-micro underline underline-offset-2",children:"Clear"})]}),n.jsxs("div",{className:"space-y-1.5",children:[Ce&&Re>0&&n.jsx("div",{"aria-hidden":"true",style:{height:Re}}),se.map(q=>{var Se;const re=q.groupKey,ue=f.has(re),_e=q.latest,Ye=_e?on(_e):null,Ge=q.nodes.length>0,$e=q.nodes.length===1,Ke=$r(q.catalogAgent),We=q.runtime??null,ht=(q.runtimeActiveCount??0)>0,st=!Ge&&ht&&We!==null,rt=Ge||st,ge=_e?r===_e.id:!1,He=q.agentName||((Se=q.catalogAgent)==null?void 0:Se.name)||q.agentId||"OrgX",Ae=xn(q.agentId,He),B=(Ae==null?void 0:Ae.agentName)??Dm(He),Pe=(Ae==null?void 0:Ae.role)??nl(B),z=as(q.agentId,B,We==null?void 0:We.displayName,_e==null?void 0:_e.runtimeProvider,_e==null?void 0:_e.runtimeClient),Q=Ae===null&&(z.id==="codex"||z.id==="openai"||z.id==="anthropic"||z.id==="openclaw"),Ne=Pe?`${He} — ${Pe}`:He,Le=ue?[]:Ge?q.nodes.slice(0,uo):[],De=Math.max(0,Ge?q.nodes.length-Le.length:0),Oe=nt(l)===nt(B)||nt(l)===nt(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",!Ge&&!Ke&&!ht&&"opacity-55"),children:[n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2",children:[n.jsxs("button",{type:"button",onClick:()=>{$e?i(q.nodes[0].id):st?R(re):!Ge&&Ke?oe(re):c?c(Oe?null:B):_e&&i(_e.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(Gs,{provider:z.id,size:"sm",showRing:!1})}):n.jsx(cm,{running:q.nodes.filter(Ve=>{const ct=on(Ve);return ct==="running"||ct==="handoff"||ct==="review"}).length,blocked:q.nodes.filter(Ve=>{const ct=on(Ve);return ct==="blocked"||ct==="failed"}).length,paused:q.nodes.filter(Ve=>{const ct=on(Ve);return ct==="paused"||ct==="cancelled"}).length,size:36,children:n.jsx(Ft,{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"})}),_e&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:js(Ye??_e.status),borderColor:E.cardBg}}),!_e&&n.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2",style:{backgroundColor:Ke?js("running"):"rgba(255,255,255,0.2)",borderColor:E.cardBg}})]}),n.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[n.jsx("div",{className:"flex min-w-0 items-baseline",title:Pe?`${He} — ${Pe}`:He,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:Ge?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full",title:(()=>{const Ve={};for(const ct of q.nodes){const ze=on(ct);Ve[ze]=(Ve[ze]??0)+1}return Object.entries(Ve).map(([ct,ze])=>`${ze} ${ct}`).join(" · ")})(),children:(()=>{const Ve={};for(const ze of q.nodes){const Ct=on(ze);Ve[Ct]=(Ve[Ct]??0)+1}const ct=q.nodes.length;return Object.entries(Ve).map(([ze,Ct])=>n.jsx("span",{style:{width:`${Ct/ct*100}%`,backgroundColor:js(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})]}):Ke||ht?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"flex h-1.5 flex-1 overflow-hidden rounded-full bg-white/[0.06]",children:n.jsx("span",{className:"h-1.5 w-full",style:{backgroundColor:js("running")}})}),n.jsx("span",{className:"w-6 flex-shrink-0 text-right text-micro text-secondary",style:{fontVariantNumeric:"tabular-nums"},children:Math.max(1,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:()=>{rt&&R(re)},disabled:!rt,"aria-label":rt?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",rt?"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",rt&&!ue?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})})]}),n.jsx(yt,{initial:!1,children:rt&&!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 Ve=new Map,ct=[];for(const Ze of Le){const kt=on(Ze);if(kt==="blocked"||kt==="paused"||kt==="failed"){const Jt=`${kt}:${Ze.blockerReason??""}`,Kt=Ve.get(Jt)??[];Kt.push(Ze),Ve.set(Jt,Kt)}else ct.push(Ze)}const ze=[];for(const[Ze,kt]of Ve)kt.length>3?ze.push({status:Ze.split(":")[0],nodes:kt}):ct.push(...kt);const Ct=(Ze,kt)=>{const Jt=r===Ze.id,Kt=on(Ze),cn=as(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(kt*.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(Gs,{provider:cn.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:cn.accent},children:cn.label}),n.jsx("span",{className:"uppercase tracking-[0.08em]",children:Kt}),n.jsx("span",{title:Jr(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, ${E.lime}, ${E.teal})`}})})]}),n.jsx("span",{className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:js(Kt)},"aria-label":Kt,title:Kt})]})},Ze.id)};return n.jsxs(n.Fragment,{children:[ct.map((Ze,kt)=>Ct(Ze,kt)),ze.map(Ze=>n.jsx(Om,{status:Ze.status,nodes:Ze.nodes,onSelectSession:i,selectedSessionId:r},`cg-${Ze.status}-${Ze.nodes.length}`))]})})(),De>0&&n.jsxs("p",{className:"px-1 text-micro text-muted",children:["+",De," older sessions hidden"]})]})})})]},re)}),Ce&&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 ",Dr," most recent agent groups (",ye," older groups omitted)."]}),d&&g!=="connected"&&!je&&n.jsxs("div",{className:"rounded-xl border border-subtle bg-white/[0.02] text-caption text-secondary",children:[n.jsx("p",{className:"px-3 pt-2 pb-1.5 text-micro uppercase tracking-[0.1em] text-muted",children:"OrgX Agent Roster"}),n.jsx("div",{className:"space-y-1 px-2 pb-2",children:Mm.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:()=>{b(q=>!q),v&&_(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",v?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),n.jsxs("span",{children:[ee," archived session",ee===1?"":"s",we>0?` across ${we} agent${we===1?"":"s"}`:""]})]}),n.jsx(yt,{initial:!1,children:v&&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=on(q),_e=q.runtimeProvider?{id:Pm(q.runtimeProvider)}:as(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(Gs,{provider:_e.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:Jr(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<ee&&n.jsxs("button",{onClick:()=>_(q=>q+1),className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.02] px-3 py-1.5 text-micro text-secondary transition-colors hover:bg-white/[0.05]",children:["Load more (",ee-ne.length," remaining)"]})]})})})]})]})]})}),qm=new Set(["failed","error","timed_out","timeout","aborted","crashed","fatal"]),zm=new Set(["awaiting_input","needs_review","needs_decision","review_required"]),Wm=new Set(["blocked","paused","rate_limited","waiting_dependency","stopping"]),Um=new Set(["completed","complete","done","resolved","success","succeeded","archived","cancelled","stopped"]),Hm=new Set(["running","active","in_progress","working","planning","dispatching","queued","pending","resumed","handoff"]);function Ws(e){return e?Ot(e):""}function Ei(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.round(e))}function Vm(e){return e.some(t=>qm.has(t))}function Km(e){return e.some(t=>zm.has(t))}function Gm(e){return e.some(t=>Wm.has(t))}function Xm(e){return e.some(t=>Um.has(t))}function Qm(e){return e.some(t=>Hm.has(t))}function Bn(e,t,s){const r=e==="in_progress"?"In progress":e==="needs_attention"?"Needs attention":e==="completed"?"Completed":e==="failed"?"Failed":"Update",i=(s==null?void 0:s.tone)??(e==="completed"?"positive":e==="failed"?"critical":e==="needs_attention"?"warning":"neutral"),a=e==="completed"||e==="failed",c=e==="needs_attention"||e==="failed";return{status:e,label:r,sentence:t,nextAction:(s==null?void 0:s.nextAction)??null,tone:i,isTerminal:a,isActionRequired:c}}function Jm(e){const t=Ws(e.sessionStatus),s=Ws(e.sessionPhase),r=Ws(e.sessionState),i=Ws(e.sliceStatus),a=Ws(e.activityStatus),c=Ws(e.stopReason),l=(e.activityType??"").toString().trim().toLowerCase(),d=[t,s,r,i,a,c].filter(_=>_.length>0),u=Ei(e.blockingDecisionCount),g=Ei(e.nonBlockingDecisionCount),y=Ei(e.blockerCount),w=l==="run_failed",f=l==="run_completed"||l==="milestone_completed"||l==="decision_resolved",k=w||Vm(d),x=Km(d)||l==="decision_requested"||u>0||e.decisionRequired===!0,j=Gm(d)||y>0,v=f||Xm(d),b=Qm(d)||l==="run_started";if(k)return Bn("failed","Execution failed and needs intervention.",{nextAction:"Review evidence",tone:"critical"});if(v&&!x&&!k&&y===0&&!e.blockerReason)return g>0?Bn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Bn("completed","Execution completed successfully.",{tone:"positive"});if(x||j)return u>0||e.decisionRequired===!0||l==="decision_requested"?Bn("needs_attention","Execution is waiting for a decision.",{nextAction:"Resolve decision",tone:"warning"}):Bn("needs_attention","Execution is blocked and needs intervention.",{nextAction:"Review blocker",tone:j?"critical":"warning"});if(v)return g>0?Bn("completed","Execution completed with optional follow-up decisions.",{nextAction:"Review optional follow-up",tone:"positive"}):Bn("completed","Execution completed successfully.",{tone:"positive"});if(b){const _=g>0?`Running with ${g} optional decision${g===1?"":"s"} available.`:"Running.";return Bn("in_progress",_,{tone:"neutral"})}return Bn("unknown","Status is available but not fully classified yet.",{tone:"neutral"})}const Ri=/\[([^\]]+)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*\n]+)\*|_([^_\n]+)_/g;function Ym(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ns(e,t){const s=[];let r=0,i=0;Ri.lastIndex=0;for(let a=Ri.exec(e);a;a=Ri.exec(e)){const[c]=a,l=a.index;l>r&&s.push(e.slice(r,l));const d=`${t}-${i++}`,u=a[1],g=a[2],y=a[3],w=a[4],f=a[5],k=a[6],x=a[7];u&&g&&Ym(g)?s.push(n.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:"text-[#D8FFA1] underline decoration-white/35 underline-offset-2 transition hover:text-[#ECFFC6]",children:u},d)):y?s.push(n.jsx("code",{className:"rounded bg-white/[0.08] px-1 py-0.5 font-mono text-[0.93em] text-bright",children:y},d)):w||f?s.push(n.jsx("strong",{className:"font-semibold text-white",children:w??f},d)):k||x?s.push(n.jsx("em",{className:"italic text-bright",children:k??x},d)):s.push(c),r=l+c.length}return r<e.length&&s.push(e.slice(r)),s}function Zm(e,t){const s=e.split(`
|
|
204
|
-
`),r=[];return s.forEach((i,a)=>{r.push(...Ns(i,`${t}-line-${a}`)),a<s.length-1&&r.push(n.jsx("br",{},`${t}-br-${a}`))}),r}function Xr(e){return e.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function ep(e){const t=Xr(e);return t.length===0?!1:t.every(s=>/^:?-{3,}:?$/.test(s))}function tp(e){const t=e.trim(),s=t.startsWith(":"),r=t.endsWith(":");return s&&r?"center":r?"right":"left"}function np(e){const t=e.replace(/\r\n/g,`
|
|
205
|
-
`).split(`
|
|
206
|
-
`),s=[];let r=0;for(;r<t.length;){const i=t[r]??"",a=i.trim();if(!a){r+=1;continue}const c=i.includes("|"),l=t[r+1]??"";if(c&&l.includes("|")&&ep(l)){const w=Xr(i),k=Xr(l).map(j=>tp(j));r+=2;const x=[];for(;r<t.length;){const j=t[r]??"";if(!j.trim()||!j.includes("|"))break;x.push(Xr(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:w.map((j,v)=>n.jsx("th",{className:"px-3 py-2 text-caption font-semibold uppercase tracking-[0.08em] text-primary",style:{textAlign:k[v]??"left"},children:Ns(j,`tbl-h-${r}-${v}`)},`tbl-h-${v}`))})}),n.jsx("tbody",{children:x.map((j,v)=>n.jsx("tr",{className:v<x.length-1?"border-b border-subtle":void 0,children:w.map((b,h)=>n.jsx("td",{className:"px-3 py-2 text-body leading-relaxed text-primary align-top",style:{textAlign:k[h]??"left"},children:Ns(j[h]??"",`tbl-r-${r}-${v}-${h}`)},`tbl-r-${v}-c-${h}`))},`tbl-r-${v}`))})]})},`tbl-${r}`));continue}if(a.startsWith("```")){const w=a.slice(3).trim(),f=[];for(r+=1;r<t.length&&!(t[r]??"").trim().startsWith("```");)f.push(t[r]??""),r+=1;r<t.length&&(r+=1),s.push(n.jsxs("div",{className:"rounded-xl border border-white/[0.1] bg-black/40 p-3",children:[w&&n.jsx("p",{className:"mb-1 text-micro uppercase tracking-[0.12em] text-muted",children:w}),n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:n.jsx("code",{children:f.join(`
|
|
207
|
-
`)})})]},`code-${r}`));continue}const d=a.match(/^(#{1,3})\s+(.+)$/);if(d){const w=d[1].length,f=d[2],k=w===1?"text-title font-semibold":w===2?"text-heading font-semibold":"text-body font-medium";s.push(n.jsx("p",{className:le("tracking-[-0.01em] text-white",k),children:Ns(f,`h-${r}`)},`h-${r}`)),r+=1;continue}if(i.match(/^\s*[-*]\s+(.+)$/)){const w=[];for(;r<t.length;){const k=(t[r]??"").match(/^\s*[-*]\s+(.+)$/);if(!k)break;w.push(k[1]),r+=1}s.push(n.jsx("ul",{className:"space-y-1.5 pl-4",children:w.map((f,k)=>n.jsx("li",{className:"list-disc text-body leading-relaxed text-primary",children:Ns(f,`ul-${r}-${k}`)},`ul-${r}-${k}`))},`ul-${r}`));continue}if(i.match(/^\s*\d+\.\s+(.+)$/)){const w=[];for(;r<t.length;){const k=(t[r]??"").match(/^\s*\d+\.\s+(.+)$/);if(!k)break;w.push(k[1]),r+=1}s.push(n.jsx("ol",{className:"space-y-1.5 pl-4",children:w.map((f,k)=>n.jsx("li",{className:"list-decimal text-body leading-relaxed text-primary",children:Ns(f,`ol-${r}-${k}`)},`ol-${r}-${k}`))},`ol-${r}`));continue}const y=[];for(;r<t.length;){const w=t[r]??"",f=w.trim();if(!f||/^(#{1,3})\s+/.test(f)||/^\s*[-*]\s+/.test(w)||/^\s*\d+\.\s+/.test(w)||f.startsWith("```"))break;y.push(w),r+=1}s.push(n.jsx("p",{className:"text-body leading-relaxed text-primary",children:Zm(y.join(`
|
|
208
|
-
`),`p-${r}`)},`p-${r}`))}return s}function ni({text:e,mode:t="inline",className:s}){const r=e.replace(/\r\n/g,`
|
|
209
|
-
`);return r.trim()?t==="inline"?n.jsx("span",{className:s,children:Ns(r,"inline")}):n.jsx("div",{className:le("space-y-2",s),children:np(r)}):null}function gl(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function sp(e){if(!e)return;const t=gl(e.metadata);return t?{...e,...t}:e}const xl={run_started:{icon:"play",label:"Run started",color:E.teal},run_completed:{icon:"check_circle",label:"Run completed",color:E.lime},run_failed:{icon:"alert_triangle",label:"Run failed",color:E.red},artifact_created:{icon:"file",label:"Artifact",color:E.cyan},decision_requested:{icon:"shield",label:"Decision requested",color:E.amber},decision_resolved:{icon:"shield_check",label:"Decision resolved",color:E.lime},handoff_requested:{icon:"handoff",label:"Handoff requested",color:E.iris},handoff_claimed:{icon:"handoff_claimed",label:"Handoff claimed",color:E.teal},handoff_fulfilled:{icon:"sparkles",label:"Handoff fulfilled",color:E.lime},blocker_created:{icon:"octagon_x",label:"Blocker",color:E.red},milestone_completed:{icon:"flag",label:"Milestone",color:E.cyan},delegation:{icon:"workflow",label:"Delegation",color:E.iris}};function Fn(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function na(e){return e?e.toLowerCase():""}function rp(e,t){return[e.type,e.kind,e.phase,e.state,e.title,e.summary,e.description,Fn(t,["source","event","eventType","artifact_type","action","kind"]),Fn(t,["task","taskName","workstream","milestone","status"])].filter(s=>typeof s=="string"&&s.trim().length>0).join(" ").toLowerCase()}function ip(e,t){const s=na(Fn(e,["artifact_type","artifactType"]));return s.includes("pr")||/pull request|merge request/.test(t)?{icon:"file_code",label:"Pull request",color:E.cyan}:s.includes("commit")||/commit|diff|patch/.test(t)?{icon:"git_commit",label:"Commit",color:E.cyan}:s.includes("config")?{icon:"checkpoint",label:"Config",color:E.cyan}:s.includes("design")?{icon:"compass",label:"Design output",color:E.cyan}:s.includes("report")||s.includes("document")||/memo|doc/.test(t)?{icon:"file",label:"Document",color:E.cyan}:xl.artifact_created}function ap(e){const t=sp(gl(e.metadata)),s=rp(e,t),r=na(Fn(t,["source"])),i=na(Fn(t,["action"])),a=Fn(t,["event","event_name","eventName"]);if(a==="auto_continue_started"||a==="auto_continue_stopped"||a==="autopilot_transition"||a==="autopilot_slice_result"||a==="autopilot_slice_finished"){if(a==="auto_continue_started"||a==="autopilot_transition"&&Fn(t,["new_state"])==="running")return{icon:"infinity",label:"Autopilot started",color:E.teal};if(a==="auto_continue_stopped"){const l=Fn(t,["stop_reason"]);return l==="error"||l==="blocked"?{icon:"infinity",label:"Autopilot blocked",color:E.red}:l==="budget_exhausted"?{icon:"infinity",label:"Budget exhausted",color:E.amber}:{icon:"infinity",label:"Autopilot stopped",color:E.amber}}if(a==="autopilot_transition"){const l=Fn(t,["new_state"]);return l==="blocked"||l==="error"?{icon:"infinity",label:"Autopilot blocked",color:E.red}:{icon:"infinity",label:"Autopilot transition",color:E.teal}}const c=Fn(t,["parsed_status","status"]);return c==="completed"||c==="success"?{icon:"check_circle",label:"Slice completed",color:E.lime}:{icon:"infinity",label:"Autopilot slice",color:E.teal}}if(/heartbeat|heart beat|alive signal/.test(s))return{icon:"heartbeat",label:"Heartbeat",color:E.teal};if(/soul/.test(s))return{icon:"compass",label:"Soul state",color:E.iris};if(/memory sync|sync memory|workspace state|sync completed|memory file/.test(s))return{icon:"memory_sync",label:"Memory sync",color:E.teal};if(/checkpoint|rollback|restore point/.test(s))return{icon:"checkpoint",label:"Save point",color:E.amber};if(/quality gate|quality score|quality check/.test(s))return{icon:"quality_gate",label:"Quality gate",color:E.lime};if(/model routing|routed model|model tier/.test(s))return{icon:"route",label:"Model routing",color:E.iris};if(r==="local_openclaw")return{icon:"terminal",label:"Local",color:E.teal};if(e.type==="artifact_created")return ip(t,s);if(e.type==="decision_resolved")return i==="reject"||/rejected|declined/.test(s)?{icon:"shield_x",label:"Decision rejected",color:E.red}:{icon:"shield_check",label:"Decision approved",color:E.lime};if(e.type==="delegation"){if(/dispatch|spawn|launched|kickoff|started/.test(s))return{icon:"workflow",label:"Dispatch",color:E.iris};if(/message|chat|reply|summary/.test(s))return{icon:"message",label:"Message",color:E.teal}}return xl[e.type]??{icon:"message",label:"Activity",color:E.textMuted}}function op({icon:e,size:t=14,className:s}){const r={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",className:s};switch(e){case"play":return n.jsx("svg",{...r,children:n.jsx("path",{d:"m8 6 10 6-10 6z"})});case"check_circle":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m8.5 12 2.5 2.5 4.5-5"})]});case"alert_triangle":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"m12 3 9 16H3z"}),n.jsx("path",{d:"M12 9v4"}),n.jsx("path",{d:"M12 17h.01"})]});case"file":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),n.jsx("path",{d:"M14 2v5h5"})]});case"file_code":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),n.jsx("path",{d:"M14 2v5h5"}),n.jsx("path",{d:"m10 13-2 2 2 2"}),n.jsx("path",{d:"m14 13 2 2-2 2"})]});case"git_commit":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M3 12h6M15 12h6"})]});case"shield":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"M12 9v4"}),n.jsx("path",{d:"M12 16h.01"})]});case"shield_check":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"shield_x":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m10 10 4 4M14 10l-4 4"})]});case"handoff":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M7 8h6a3 3 0 1 1 0 6H8"}),n.jsx("path",{d:"m10 14-3 3-3-3"}),n.jsx("path",{d:"M17 10h-4"})]});case"handoff_claimed":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M8.5 12.5 12 9l3.5 3.5"}),n.jsx("path",{d:"M6 14h12"}),n.jsx("path",{d:"M7 18h10"})]});case"sparkles":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"m12 3 1.5 3.5L17 8l-3.5 1.5L12 13l-1.5-3.5L7 8l3.5-1.5z"}),n.jsx("path",{d:"m5 14 .8 1.8L8 16.6l-2.2.8L5 19l-.8-1.6L2 16.6l2.2-.8z"}),n.jsx("path",{d:"m19 14 .8 1.8 2.2.8-2.2.8L19 19l-.8-1.6-2.2-.8 2.2-.8z"})]});case"octagon_x":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"m10.2 3-5.8 3.3v11.4L10.2 21h3.6l5.8-3.3V6.3L13.8 3z"}),n.jsx("path",{d:"m9 9 6 6M15 9l-6 6"})]});case"flag":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M5 3v18"}),n.jsx("path",{d:"m5 4 12 1-2 4 2 4-12-1"})]});case"workflow":return n.jsx(sl,{size:t,className:s,strokeWidth:1.8});case"memory_sync":return n.jsxs("svg",{...r,children:[n.jsx("ellipse",{cx:"12",cy:"5.5",rx:"6.5",ry:"2.5"}),n.jsx("path",{d:"M5.5 5.5v6c0 1.4 2.9 2.5 6.5 2.5s6.5-1.1 6.5-2.5v-6"}),n.jsx("path",{d:"m8 17-2 2 2 2"}),n.jsx("path",{d:"M16 17l2 2-2 2"})]});case"heartbeat":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M3 12h4l2-4 3 8 2-4h7"})});case"checkpoint":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3v6"}),n.jsx("path",{d:"M8 5h8"}),n.jsx("path",{d:"M7 11h10v10H7z"}),n.jsx("path",{d:"M9 14h6"})]});case"quality_gate":return n.jsxs("svg",{...r,children:[n.jsx("path",{d:"M12 3 5 6v6c0 5 3.3 7.8 7 9 3.7-1.2 7-4 7-9V6z"}),n.jsx("path",{d:"m9 12.5 2 2 4-4"})]});case"route":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"6",cy:"6",r:"2"}),n.jsx("circle",{cx:"18",cy:"18",r:"2"}),n.jsx("path",{d:"M8 6h4a4 4 0 0 1 4 4v6"}),n.jsx("path",{d:"M16 6h2"})]});case"terminal":return n.jsxs("svg",{...r,children:[n.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),n.jsx("path",{d:"m7 9 3 3-3 3"}),n.jsx("path",{d:"M13 15h4"})]});case"compass":return n.jsxs("svg",{...r,children:[n.jsx("circle",{cx:"12",cy:"12",r:"9"}),n.jsx("path",{d:"m10 10 6-2-2 6-6 2z"})]});case"infinity":return n.jsx("svg",{...r,children:n.jsx("path",{d:"M18.178 8c5.096 0 5.096 8 0 8-5.095 0-7.133-8-12.739-8-4.585 0-4.585 8 0 8 5.606 0 7.644-8 12.74-8z"})});case"message":default:return n.jsx("svg",{...r,children:n.jsx("path",{d:"M21 12a8 8 0 0 1-8 8H7l-4 2 1.5-4A8 8 0 1 1 21 12z"})})}}function si(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function sa(e){if(!e)return;const t=si(e.metadata);return t?{...e,...t}:e}function lp(e){try{return new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}catch{return""}}function cp(e){let t=0;for(const s of e){const r=sa(si(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 dp=o.memo(function({items:t,session:s,agentName:r,onBack:i,onOpenItem:a}){const[c,l]=o.useState(!1),d=o.useMemo(()=>[...t].sort((f,k)=>Date.parse(f.timestamp)-Date.parse(k.timestamp)),[t]),u=o.useMemo(()=>cp(d),[d]),g=o.useMemo(()=>{if(d.length<2)return null;const f=Date.parse(d[0].timestamp),x=Date.parse(d[d.length-1].timestamp)-f;return x<6e4?`${Math.round(x/1e3)}s`:x<36e5?`${Math.round(x/6e4)}m`:`${(x/36e5).toFixed(1)}h`},[d]),y=o.useMemo(()=>{let f=null,k=null,x=null,j=null,v=null;for(const h of d){const _=sa(si(h.metadata));if(_&&(!f&&typeof _.domain=="string"&&(f=_.domain),!k&&typeof _.provider=="string"&&(k=_.provider),!x&&typeof _.model=="string"&&(x=_.model),!j&&typeof _.spawn_guard_model_tier=="string"&&(j=_.spawn_guard_model_tier),!v&&typeof _.kickoff_context_hash=="string"&&(v=_.kickoff_context_hash),f&&(k||x)&&j&&v))break}return!(f||k||x||j||v)?null:{domain:f,provider:k,model:x,modelTier:j,kickoffContextHash:v}},[d]),w=(s==null?void 0:s.title)??r??"Session";return n.jsxs("div",{className:"flex h-full flex-col",children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-3",children:[n.jsxs("button",{onClick:i,className:"mb-2 flex items-center gap-1.5 text-caption text-secondary transition-colors hover:text-primary",children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})}),"Back to timeline"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:E.lime,boxShadow:`0 0 12px ${E.lime}55`}}),n.jsx("h3",{className:"text-heading font-semibold text-white",children:lt(w)})]}),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(Ft,{name:r,hint:(s==null?void 0:s.id)??(s==null?void 0:s.runId)??null,size:"xs"}),n.jsx("span",{children:r})]}),n.jsxs("span",{children:[d.length," turn",d.length!==1?"s":""]}),g&&n.jsx("span",{children:g}),u&&n.jsx("span",{className:"text-muted",children:u}),(y==null?void 0:y.domain)&&n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:lt(y.domain)}),(s==null?void 0:s.status)&&n.jsx("span",{className:"rounded-full px-1.5 py-0.5 text-micro uppercase tracking-wider",style:{backgroundColor:s.status==="running"?`${E.lime}20`:s.status==="failed"?`${E.red}20`:`${E.teal}20`,color:s.status==="running"?E.lime:s.status==="failed"?E.red:E.teal},children:s.status}),y&&(y.provider||y.model||y.modelTier||y.kickoffContextHash)&&n.jsxs("button",{type:"button",onClick:()=>l(f=>!f),className:"inline-flex items-center gap-1 text-micro text-muted transition-colors hover:text-secondary",children:[n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:`transition-transform duration-150 ${c?"rotate-180":""}`,children:n.jsx("path",{d:"m6 9 6 6 6-6"})}),"Info"]})]}),c&&y&&n.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5 text-micro",children:[(y.provider||y.model)&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:[y.provider?`${lt(y.provider)} · `:"",y.model?xr(y.model):"—"]}),y.modelTier&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",children:["tier: ",lt(y.modelTier)]}),y.kickoffContextHash&&n.jsxs("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 font-mono text-secondary",children:["kickoff ",y.kickoffContextHash.slice(0,8),"…"]})]})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:[n.jsx(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:`${E.iris}25`}}),n.jsx("div",{className:"space-y-1",children:d.map((f,k)=>{var K;const x=ap(f),j=x.color,v=(K=sa(si(f.metadata)))==null?void 0:K.model,b=typeof v=="string"?xr(v):null,h=lt(f.title??""),_=f.type==="run_failed",V=f.type==="artifact_created",oe=f.type==="decision_requested"||f.type==="decision_resolved";return n.jsxs(he.button,{type:"button",initial:{opacity:0,x:-8},animate:{opacity:1,x:0},transition:{duration:.2,delay:k*.02},onClick:()=>a==null?void 0:a(f),className:"group relative flex w-full items-start gap-2.5 rounded-lg py-1.5 pl-0 pr-2 text-left transition-colors hover:bg-white/[0.02] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/35 focus-visible:ring-offset-1 focus-visible:ring-offset-[#02040A]",children:[n.jsx("span",{className:"relative z-10 mt-1.5 flex h-[15px] w-[15px] flex-shrink-0 items-center justify-center rounded-full text-[8px]",style:{backgroundColor:`${j}20`,color:j,border:`1px solid ${j}40`},children:n.jsx(op,{icon:x.icon,size:8,className:"opacity-95"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:`text-body leading-snug ${_?"text-red-400":oe?"text-amber-300":V?"text-cyan-300":"text-bright"}`,children:h}),f.summary&&f.summary!==h&&n.jsx("p",{className:"mt-0.5 text-caption leading-relaxed text-muted",children:lt(f.summary)})]}),n.jsxs("div",{className:"flex flex-shrink-0 flex-col items-end gap-0.5 pt-0.5",children:[n.jsx("span",{className:"text-micro text-muted",title:Jr(f.timestamp),children:lp(f.timestamp)}),b&&n.jsx("span",{className:"text-micro text-faint",children:b})]})]},f.id)})})]})}),d.length===0&&n.jsxs("div",{className:"flex flex-col items-center gap-2 py-8 text-center",children:[n.jsx("p",{className:"text-body text-secondary",children:"No activity in this session yet."}),n.jsx("p",{className:"text-caption text-muted animate-pulse",children:"Activity may take a moment to appear."})]}),d.length>0&&n.jsxs("div",{className:"mt-4 rounded-lg border border-subtle bg-white/[0.02] px-3 py-2 text-micro text-muted",children:[d.length," turn",d.length!==1?"s":"",g?` over ${g}`:"",u?` · ${u}`:""," · ",n.jsx("span",{title:Jr(d[d.length-1].timestamp),children:_t(d[d.length-1].timestamp)})]})]})]})});function up({completedCount:e,decisionsCount:t,blockerCount:s,visible:r,onDismiss:i}){if(!(e>0||t>0||s>0))return null;const c=[];return e>0&&c.push(`${e} task${e===1?"":"s"} completed`),t>0&&c.push(`${t} need${t===1?"s":""} decisions`),s>0&&c.push(`${s} new blocker${s===1?"":"s"}`),n.jsx(yt,{children:r&&n.jsx(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:`${E.teal}08`,border:`1px solid ${E.teal}20`},children:n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-caption font-semibold text-white",children:"While you were away"}),n.jsx("p",{className:"mt-1 text-body text-secondary",children:c.join(" · ")})]}),n.jsx("button",{onClick:i,className:"flex-shrink-0 rounded-md px-2.5 py-1 text-caption font-medium text-secondary transition-colors hover:bg-white/[0.06] hover:text-white",children:"Got it"})]})})})})}const mp={initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-4,scale:.98}};function pp({renderKey:e,displayTitle:t,headline:s,contextLabel:r,detailText:i,displayAgentName:a,railColor:c,userStateLabel:l,userStateWhy:d,relativeTime:u,timeLabel:g,isRecent:y,enableMotion:w,onOpen:f,ariaLabel:k,artifactSnippet:x}){const j="group w-full rounded-xl border border-white/[0.08] bg-white/[0.02] px-3.5 py-3 text-left transition-colors hover:border-strong hover:bg-white/[0.05] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#BFFF00]/45 cv-auto",v=n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(Ft,{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",y&&"pulse-soft"),style:{backgroundColor:c,boxShadow:`0 0 14px ${c}66`}}),n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate text-caption text-secondary",title:r,children:r}),n.jsx("p",{className:"mt-0.5 line-clamp-1 break-words text-body font-semibold leading-snug text-bright",children:s||t})]}),n.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[n.jsx("span",{className:"text-caption text-secondary",children:g}),n.jsx("span",{className:"text-micro text-muted",children:u})]})]}),x?n.jsxs("div",{className:"mt-2 flex items-center gap-2 rounded-lg border border-cyan-400/20 bg-cyan-500/[0.06] px-2.5 py-1.5",children:[n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#67e8f9",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsxs("span",{className:"min-w-0 flex-1 truncate text-caption text-cyan-200/90",children:[n.jsx("span",{className:"font-semibold",children:x.label}),x.preview&&n.jsx("span",{className:"ml-1.5 text-cyan-200/60",children:x.preview})]}),n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#67e8f9",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0 opacity-50",children:n.jsx("path",{d:"m9 18 6-6-6-6"})})]}):i?n.jsx("div",{className:"mt-1.5 line-clamp-2 text-caption leading-relaxed text-secondary",children:n.jsx(ni,{mode:"inline",text:i})}):null,n.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5 text-micro",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border px-2 py-0.5 font-semibold tracking-[0.01em]",style:{borderColor:`${c}55`,backgroundColor:`${c}1A`,color:c},title:d,children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:c}}),l]}),n.jsx("span",{className:"inline-flex max-w-[220px] items-center gap-1 rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-secondary",title:a,children:n.jsx("span",{className:"truncate",children:a})})]})]})]});return w?n.jsx(he.button,{type:"button",variants:mp,initial:"initial",animate:"animate",exit:"exit",transition:{duration:.25,ease:[.4,0,.2,1]},whileHover:{y:-1.5},whileTap:{scale:.995},onClick:f,className:j,"aria-label":k,children:v},e):n.jsx("button",{type:"button",onClick:f,className:le(j,"transform-gpu transition-[transform,background-color,border-color,color] hover:-translate-y-[1px] active:scale-[0.995]"),"aria-label":k,children:v},e)}function fp({open:e,onClose:t,children:s}){return n.jsx(di,{open:e,onClose:t,maxWidth:"max-w-3xl",closeOnEscape:!1,children:s})}function hp(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 gp={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 xp({item:e,className:t}){const s=o.useMemo(()=>Ql(e),[e]),r=hp(e),i=gp[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(Li,{label:"Task",value:s.taskDescription,styles:i}),s.outcomeDescription&&n.jsx(Li,{label:"Outcome",value:s.outcomeDescription,styles:i}),s.nextStep&&n.jsx(Li,{label:"Next step",value:s.nextStep,styles:i})]})}function Li({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 fo=new Set(["orgx-orchestrator","xandy","dispatcher","router-all-agents"]),yp=[{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"}],lr=[{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"}],ho={type:"spring",stiffness:400,damping:25},go={scale:.985};function Qt(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function bp(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 cr(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?Pt(Cn(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 vp(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 ri(e){return e==="message_only"?"Message sent":e==="queued"?"Queued":e==="running"?"Running":e==="blocked"?"Blocked":e==="completed"?"Completed":e==="failed"?"Failed":e}function Xs(e){return e==="running"?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":e==="completed"?"border-teal/30 bg-teal/[0.12] text-teal-100":e==="blocked"||e==="failed"?"border-rose-400/30 bg-rose-400/[0.12] text-rose-100":e==="queued"?"border-white/[0.18] bg-white/[0.08] text-primary":"border-white/[0.12] bg-white/[0.04] text-secondary"}function yl(e){return e==="user"?"You":e==="agent"?"Agent":"System"}function kp(e){return e==="agent"?"assistant":e}function jp(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join("").trim()}function Np(e,t){return t.map(s=>({id:s.id,role:kp(s.role),metadata:{threadId:e,messageId:s.id,source:"thread-store"},parts:[{type:"text",text:s.body,state:"done"}]}))}function bl(e){return e==="queued"?"queued":e==="running"?"running":e==="blocked"?"blocked":e==="completed"?"completed":e==="failed"?"failed":"message_only"}function Qs(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Qr(e){const t=Qs(e);if(!t)return null;const s=typeof t.id=="string"?t.id.trim():"";if(!s)return null;const r=Qs(t.latestMessage),i=Qs(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 Ip(e){const t=Qs(e);if(!t)return null;const s=Qr({...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=>Qs(a)).filter(a=>!!a).map(a=>{const c=a.role==="agent"||a.role==="system"?a.role:"user";return{id:typeof a.id=="string"?a.id:`msg_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,role:c,body:typeof a.body=="string"?a.body:"",senderId:typeof a.senderId=="string"?a.senderId:null,senderName:typeof a.senderName=="string"?a.senderName:null,createdAt:typeof a.createdAt=="string"?a.createdAt:s.createdAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,attachments:Array.isArray(a.attachments)?a.attachments.filter(l=>!!l&&typeof l=="object"):[],metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[],i=Array.isArray(t.launches)?t.launches.map(a=>Qs(a)).filter(a=>!!a).map(a=>{const c=a.executionMode==="cloud"||a.executionMode==="hybrid"?a.executionMode:"local_queue",l=a.status==="queued"||a.status==="running"||a.status==="blocked"||a.status==="completed"||a.status==="failed"||a.status==="requested"?a.status:"requested";return{id:typeof a.id=="string"?a.id:`launch_${s.id}`,threadId:typeof a.threadId=="string"?a.threadId:s.id,messageId:typeof a.messageId=="string"?a.messageId:"",assigneeId:typeof a.assigneeId=="string"?a.assigneeId:null,assigneeName:typeof a.assigneeName=="string"?a.assigneeName:null,watcherIds:Array.isArray(a.watcherIds)?a.watcherIds.filter(d=>typeof d=="string"):[],watcherNames:Array.isArray(a.watcherNames)?a.watcherNames.filter(d=>typeof d=="string"):[],executionMode:c,provider:typeof a.provider=="string"?a.provider:null,runId:typeof a.runId=="string"?a.runId:null,status:l,blockedReason:typeof a.blockedReason=="string"?a.blockedReason:null,warnings:Array.isArray(a.warnings)?a.warnings.filter(d=>typeof d=="string"):[],requestedAt:typeof a.requestedAt=="string"?a.requestedAt:s.updatedAt,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:s.updatedAt,metadata:a.metadata&&typeof a.metadata=="object"?a.metadata:{}}}):[];return{...s,messages:r.sort((a,c)=>Qt(a.createdAt)-Qt(c.createdAt)),launches:i.sort((a,c)=>Qt(c.requestedAt)-Qt(a.requestedAt))}}function Ap(e,t,s){const r=Qt(e.lastActivityAt);if(!r)return!1;if(t==="custom"){const a=Qt(s.startIso),c=Qt(s.endIso);return!(a&&r<a||c&&r>c)}const i=br(t,Date.now());return i?r>=i:!0}async function dr(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 Di(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 Sp(e,t){const s=new Map;for(const r of e)s.set(r.id,r);for(const r of t)s.set(r.id,r);return Array.from(s.values()).sort((r,i)=>Qt(i.lastActivityAt??i.updatedAt)-Qt(r.lastActivityAt??r.updatedAt))}const wl=o.createContext(null),vl=o.createContext(null);function xa(){const e=o.useContext(wl);if(!e)throw new Error("useChatDockState must be used within ChatDockProvider");return e}function ya(){const e=o.useContext(vl);if(!e)throw new Error("useChatDockDispatch must be used within ChatDockProvider");return e}function _p({children:e,sessions:t,initiatives:s,workspaceId:r,query:i,statusFilter:a,sortOrder:c,timeFilterId:l,customTimeRange:d,snapshot:u,onRequestRefresh:g}){const[y,w]=o.useState((u==null?void 0:u.threads)??[]),[f,k]=o.useState(null),[x,j]=o.useState(null),[v,b]=o.useState(!1),[h,_]=o.useState(null),[V,oe]=o.useState("resting"),[K,be]=o.useState(""),[H,Z]=o.useState(!1),[ce,ye]=o.useState(!1),[we,W]=o.useState(null),[Ie,Te]=o.useState(null),[fe,ee]=o.useState([]),[de,Ee]=o.useState(""),[ne,R]=o.useState([]),[J,P]=o.useState(""),[Y,ie]=o.useState(null),[ve,je]=o.useState(""),[te,Me]=o.useState(!1),[pe,M]=o.useState(""),[O,U]=o.useState([]),[se,Re]=o.useState(!1),[qe,Ce]=o.useState("auto"),[T,q]=o.useState(!1),[re,ue]=o.useState(!1),[_e,Ye]=o.useState(!1),Ge=o.useRef(null),$e=o.useRef(null),Ke=o.useRef(null),We=o.useRef(null);o.useEffect(()=>{u!=null&&u.threads&&w(C=>Sp(C,u.threads))},[u==null?void 0:u.threads,u==null?void 0:u.updatedAt]),o.useEffect(()=>{f&&w(C=>C.sort((me,G)=>Qt(G.lastActivityAt)-Qt(me.lastActivityAt)))},[f]);const{data:ht}=ha({enabled:!0,refetchInterval:8e3}),st=o.useMemo(()=>{var me,G;const C=new Map;for(const Fe of yp)C.set(Fe.id,{id:Fe.id,name:Fe.name,handle:Fe.handle,domain:Fe.domain,domainLabel:Fe.domainLabel,role:Fe.role,status:"idle",currentTask:null,isSystem:!1});if(ht!=null&&ht.agents)for(const Fe of ht.agents){const gt=C.get(Fe.id);gt?(gt.status=Fe.status==="running"?"running":(me=Fe.blockers)!=null&&me.length?"blocked":"idle",gt.currentTask=Fe.currentTask??null):C.set(Fe.id,{id:Fe.id,name:Fe.name,handle:Fe.id,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:Fe.status==="running"?"running":(G=Fe.blockers)!=null&&G.length?"blocked":"idle",currentTask:Fe.currentTask??null,isSystem:fo.has(Fe.id)})}for(const Fe of t){const gt=(Fe.agentId??"").trim(),it=(Fe.agentName??"").trim();!gt||!it||C.has(gt)||C.set(gt,{id:gt,name:it,handle:gt,domain:"custom",domainLabel:"Custom Agent",role:"Custom",status:"idle",currentTask:null,isSystem:fo.has(gt)})}return Array.from(C.values()).filter(Fe=>!Fe.isSystem).sort((Fe,gt)=>Fe.name.localeCompare(gt.name))},[ht,t]),rt=o.useMemo(()=>s.map(C=>({id:C.id,name:C.name})).sort((C,me)=>C.name.localeCompare(me.name)),[s]),ge=o.useMemo(()=>st.find(C=>C.id===de)??null,[st,de]),He=o.useMemo(()=>{const C=new Set(ne);return st.filter(me=>C.has(me.id))},[st,ne]),Ae=o.useMemo(()=>rt.find(C=>C.id===J)??null,[rt,J]);o.useEffect(()=>{de&&R(C=>C.filter(me=>me!==de))},[de]);const B=o.useMemo(()=>st.slice(0,8),[st]),Pe=o.useMemo(()=>{const C=ve.trim().toLowerCase();return C?st.filter(me=>me.name.toLowerCase().includes(C)||me.handle.toLowerCase().includes(C)||me.domain.toLowerCase().includes(C)||me.role.toLowerCase().includes(C)):st},[st,ve]),z=o.useMemo(()=>{const C=pe.trim().toLowerCase();return C?rt.filter(me=>me.name.toLowerCase().includes(C)):rt},[rt,pe]),Q=o.useMemo(()=>{const C=i.trim().toLowerCase(),me=y.filter(G=>!vp(G,a)||!Ap(G,l,d)?!1:C.length===0?!0:wp(G).includes(C));return me.sort((G,Fe)=>{const gt=Qt(Fe.lastActivityAt)-Qt(G.lastActivityAt);return c==="newest"?gt:-gt}),me},[d,i,c,a,y,l]),Ne=o.useMemo(()=>{if(!f||Q.some(me=>me.id===f))return Q;const C=y.find(me=>me.id===f);return C?[C,...Q]:Q},[f,Q,y]),Le=o.useMemo(()=>y.find(C=>C.id===f)??null,[f,y]),De=o.useMemo(()=>fe.filter(C=>C.status!=="ready").length,[fe]),Se=K.trim().length>0&&!H,Ve=o.useMemo(()=>De>0?`${De} attachment(s) still processing.`:"Press Enter to send.",[De]),ct=o.useMemo(()=>H?"Sending…":ce?"Launching…":"Send",[ce,H]),ze=o.useMemo(()=>new Wl({api:"/orgx/api/chat/usechat"}),[]),{messages:Ct,setMessages:Ze,sendMessage:kt,status:Jt,error:Kt,clearError:cn}=Pl({id:`orgx-chat-guidance-${r??"global"}`,transport:ze,onError:C=>{W(cr((C==null?void 0:C.message)??null,"send"))}});o.useEffect(()=>{if(!x){Ze([]);return}Ze(Np(x.id,x.messages))},[x,Ze]);const Mn=o.useMemo(()=>{const C=[...Ct].reverse().find(G=>G.role==="assistant");if(!C)return null;const me=jp(C);return me.length>0?me:null},[Ct]),us=o.useRef(null);o.useEffect(()=>{if(Jt!=="ready"&&Jt!=="error"||!Mn)return;const C=[...Ct].reverse().find(me=>me.role==="assistant");!C||C.id===us.current||(us.current=C.id,U(me=>[...me,{id:`guidance_${C.id}`,role:"agent",body:Mn,timestamp:new Date().toISOString()}]))},[Jt,Mn,Ct]);const bt=o.useCallback(()=>{be(""),ee([]),ue(!1),Ye(!1),W(null),Te(null)},[]),zt=o.useCallback(C=>{U(me=>[...me,{...C,id:`inline_${crypto.randomUUID()}`,timestamp:new Date().toISOString()}])},[]),wn=o.useCallback(()=>U([]),[]),Tt=o.useCallback(()=>Re(C=>!C),[]),It=o.useMemo(()=>lr.find(C=>C.id===qe)??lr[0],[qe]),Bt=o.useCallback(()=>{Ce(C=>{const me=lr.findIndex(G=>G.id===C);return lr[(me+1)%lr.length].id})},[]),Wt=o.useCallback(async()=>{typeof g=="function"&&await g()},[g]),$t=o.useCallback(async C=>{var Fe;b(!0),_(null);const me=await dr(`/orgx/api/chat/threads/${encodeURIComponent(C)}`);if(!me.ok||!((Fe=me.data)!=null&&Fe.thread))return b(!1),_(cr(me.error,"load")),null;const G=Ip(me.data.thread);return G?(j(G),b(!1),G):(b(!1),_("Thread detail payload was invalid."),null)},[]),dn=o.useCallback(async(C,me)=>{me&&(Ke.current=me),k(C),await $t(C),requestAnimationFrame(()=>{var G;return(G=$e.current)==null?void 0:G.focus()})},[$t]),Vn=o.useCallback(()=>{var C;k(null),j(null),_(null),b(!1),(C=Ke.current)==null||C.focus()},[]),un=o.useCallback(C=>{window.setTimeout(()=>{ee(me=>me.map(G=>G.id===C?{...G,status:"indexing",updatedAt:new Date().toISOString()}:G))},80),window.setTimeout(()=>{ee(me=>me.map(G=>{var it;if(G.id!==C)return G;const Fe=((it=G.mimeType)==null?void 0:it.toLowerCase())==="application/x-msdownload"||G.name.toLowerCase().endsWith(".exe"),gt=(G.sizeBytes??0)>25*1024*1024;return Fe?{...G,status:"failed",error:"Unsupported file type.",updatedAt:new Date().toISOString()}:gt?{...G,status:"failed",error:"File exceeds 25 MB extraction limit.",updatedAt:new Date().toISOString()}:{...G,status:"ready",error:null,updatedAt:new Date().toISOString()}}))},420)},[]),Tn=o.useCallback(C=>{if(!C||C.length===0)return;const me=new Date().toISOString(),G=Array.from(C).map(Fe=>({id:`draft_att_${crypto.randomUUID()}`,name:Fe.name,mimeType:Fe.type||null,sizeBytes:Number.isFinite(Fe.size)?Fe.size:null,status:"preparing",error:null,masked:!1,createdAt:me,updatedAt:me}));ee(Fe=>Fe.concat(G)),G.forEach(Fe=>un(Fe.id)),ss("chat_attachment_state_changed",{count:G.length,state:"preparing"})},[un]),ms=o.useCallback(C=>{ee(me=>me.map(G=>G.id===C?{...G,status:"preparing",error:null,updatedAt:new Date().toISOString()}:G)),un(C),ss("chat_attachment_state_changed",{state:"retry"})},[un]),vn=o.useCallback(C=>{Ee(me=>me===C?"":C),R(me=>me.filter(G=>G!==C)),ie(null),je("")},[]),en=o.useCallback(C=>{R(me=>me.includes(C)?me.filter(G=>G!==C):me.concat(C))},[]),Ut=o.useCallback(()=>{Me(!1),M(""),ie(C=>C==="assignee"?null:"assignee"),je("")},[]),Kn=o.useCallback(()=>{Me(!1),M(""),ie(C=>C==="watcher"?null:"watcher"),je("")},[]),kn=o.useCallback(()=>{ie(null),je(""),Me(C=>!C),M("")},[]),Gn=o.useCallback(async(C,me)=>{var it;q(!0);const G=rt.find(Xe=>Xe.id===me)??null,Fe=await dr("/orgx/api/chat/link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:C,project_id:r??void 0,initiativeId:(G==null?void 0:G.id)??null,initiativeTitle:(G==null?void 0:G.name)??null,relinked:!0})});if(q(!1),!Fe.ok||!((it=Fe.data)!=null&&it.thread)){_(Fe.error??"Scope link failed.");return}const gt=Qr(Fe.data.thread);gt&&w(Xe=>Di(Xe,gt)),await $t(C),await Wt(),ss("chat_thread_linked_initiative",{threadId:C,initiativeId:(G==null?void 0:G.id)??null})},[rt,$t,Wt,r]),Xn=o.useCallback(async C=>{cn(),await kt({text:C.prompt},{body:{threadId:C.thread.id,project_id:r??void 0,initiativeId:C.thread.initiativeId??(Ae==null?void 0:Ae.id)??void 0,initiativeTitle:C.thread.initiativeTitle??(Ae==null?void 0:Ae.name)??void 0,assigneeId:(ge==null?void 0:ge.id)??C.thread.assigneeId??void 0,assigneeName:(ge==null?void 0:ge.name)??C.thread.assigneeName??void 0,watcherIds:He.map(me=>me.id),watcherNames:He.map(me=>me.name)}}),await Wt(),await $t(C.thread.id)},[cn,$t,Wt,ge==null?void 0:ge.id,ge==null?void 0:ge.name,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,He,kt,r]),tn=o.useCallback(async()=>{var gt,it;const C=K.trim();if(!C)return W("Write a message before sending."),{thread:null,messageId:null};W(null),Te(null),Z(!0);const me=await dr("/orgx/api/chat/messages",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:f??void 0,project_id:r??void 0,initiativeId:(Ae==null?void 0:Ae.id)??(x==null?void 0:x.initiativeId)??void 0,initiativeTitle:(Ae==null?void 0:Ae.name)??(x==null?void 0:x.initiativeTitle)??void 0,assigneeId:(ge==null?void 0:ge.id)??(x==null?void 0:x.assigneeId)??void 0,assigneeName:(ge==null?void 0:ge.name)??(x==null?void 0:x.assigneeName)??void 0,watcherIds:He.map(Xe=>Xe.id),watcherNames:He.map(Xe=>Xe.name),body:C,attachments:fe.map(Xe=>({id:Xe.id,name:Xe.name,mimeType:Xe.mimeType,sizeBytes:Xe.sizeBytes,status:Xe.status,error:Xe.error,masked:Xe.masked}))})});if(Z(!1),!me.ok||!((gt=me.data)!=null&>.thread))return W(cr(me.error,"send")),ss("chat_message_send_failed",{reason:me.error??"unknown"}),{thread:null,messageId:null};const G=Qr(me.data.thread);if(!G)return W("Send succeeded but thread payload was invalid."),{thread:null,messageId:null};w(Xe=>Di(Xe,G)),zt({role:"user",body:C}),qe!=="auto"&&ge&&zt({role:"system",body:`Routing to ${ge.name} via ${It.label}`}),ss("chat_message_sent",{threadId:G.id,watcherCount:G.watcherIds.length}),await Wt();const Fe=me.data.message&&typeof me.data.message.id=="string"?me.data.message.id:((it=G.latestMessage)==null?void 0:it.id)??null;return k(G.id),await $t(G.id),Xn({thread:G,prompt:C}).catch(Xe=>{zt({role:"error",body:cr(Xe instanceof Error?Xe.message:String(Xe??""),"send")})}),bt(),oe("reviewing"),{thread:G,messageId:Fe}},[x==null?void 0:x.assigneeId,x==null?void 0:x.assigneeName,x==null?void 0:x.initiativeId,x==null?void 0:x.initiativeTitle,f,K,fe,$t,Wt,bt,Xn,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,It,He,r]),En=o.useCallback(async(C,me)=>{var jt,pn,Pn,ps,Ln,Yn,fn;if(!me){zt({role:"error",body:"Send a message first to launch."});return}if(!ge){zt({role:"error",body:"Pick an agent with @ before launching."});return}if(De>0&&!_e){ue(!0),zt({role:"error",body:"Some attachments are still processing. Confirm to continue."});return}ye(!0),W(null),Te(null);const G=await dr("/orgx/api/agents/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:ge.id,message:K.trim().length>0?K.trim():C.lastSnippet??C.title,initiativeId:C.initiativeId??(Ae==null?void 0:Ae.id)??void 0,initiativeTitle:C.initiativeTitle??(Ae==null?void 0:Ae.name)??void 0,workstreamId:C.workstreamId??void 0,taskId:C.taskId??void 0,provider:qe!=="auto"?qe:void 0})}),Fe=((jt=G.data)==null?void 0:jt.sessionId)??((pn=G.data)==null?void 0:pn.runId)??null,gt=G.ok&&Fe?"running":G.ok?"queued":"blocked",it=G.ok?null:G.error??"Launch request failed before queueing.",Xe=await dr("/orgx/api/chat/launch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({threadId:C.id,messageId:me,assigneeId:ge.id,assigneeName:ge.name,watcherIds:He.map(At=>At.id),watcherNames:He.map(At=>At.name),executionMode:"local_queue",provider:((Pn=G.data)==null?void 0:Pn.provider)??(qe!=="auto"?qe:"openclaw"),runId:Fe??void 0,status:gt,blockedReason:it??void 0,warnings:De>0?[`${De} attachment(s) were not ready at launch.`]:[]})});if(ye(!1),Ye(!1),ue(!1),!Xe.ok||!((ps=Xe.data)!=null&&ps.thread)){W(Xe.error?cr(Xe.error,"launch"):it??"Launch state could not be persisted. Message remained saved."),ss("chat_launch_failed",{threadId:C.id,reason:Xe.error??it??"unknown"});return}const Jn=Qr(Xe.data.thread);if(Jn&&w(At=>Di(At,Jn)),await $t(C.id),await Wt(),!G.ok){W(`Launch blocked: ${it??"Set assignee and retry."}`),ss("chat_launch_blocked",{threadId:C.id,reason:it??"unknown"});return}const mn=((Ln=G.data)==null?void 0:Ln.provider)==="anthropic"?"Claude Code":((Yn=G.data)==null?void 0:Yn.provider)==="openai"?"Codex":It.shortLabel,Ms=(fn=G.data)!=null&&fn.model?` (${G.data.model})`:"";Te(Fe?`Launch started via ${mn}${Ms}. Thread timeline now tracks execution state.`:`Launch queued locally via ${mn}. Run starts when a worker is available.`),ss(Fe?"chat_launch_started":"chat_launch_queued",{threadId:C.id,runId:Fe,assigneeId:ge.id})},[K,_e,$t,Wt,ge,Ae==null?void 0:Ae.id,Ae==null?void 0:Ae.name,qe,It,He,De]),Et=o.useCallback(async()=>{var me;const C=await tn();(me=C.thread)!=null&&me.id&&await dn(C.thread.id)},[dn,tn]),Rn=o.useCallback(async()=>{const C=await tn();C.thread&&(await En(C.thread,C.messageId),await dn(C.thread.id))},[En,dn,tn]),Gt=o.useCallback(async()=>{if(Se){if(ge){await Rn();return}await Et()}},[Se,Rn,Et,ge]),Qn=o.useMemo(()=>({threads:y,activeThreadId:f,activeThread:x,activeThreadSummary:Le,displayedThreads:Ne,composerMode:V,draft:K,draftAttachments:fe,sending:H,launching:ce,composerError:we,composerNotice:Ie,selectedAssigneeId:de,selectedAssignee:ge,selectedWatcherIds:ne,selectedWatchers:He,selectedInitiativeId:J,selectedInitiative:Ae,agentOptions:st,quickAssigneeOptions:B,initiativeOptions:rt,agentPickerMode:Y,agentPickerQuery:ve,filteredAgentOptions:Pe,scopePickerOpen:te,scopePickerQuery:pe,filteredInitiativeOptions:z,panelLoading:v,panelError:h,scopeSaving:T,launchWarningOpen:re,launchWarningAccepted:_e,unresolvedAttachmentCount:De,canSend:Se,composerGuidance:Ve,primaryActionLabel:ct,guidanceStatus:Jt,guidancePreview:Mn,guidanceError:Kt??null,inlineMessages:O,threadSidebarOpen:se,workspaceId:r,selectedProvider:qe,selectedProviderDef:It}),[y,f,x,Le,Ne,V,K,fe,H,ce,we,Ie,de,ge,ne,He,J,Ae,st,B,rt,Y,ve,Pe,te,pe,z,v,h,T,re,_e,De,Se,Ve,ct,Jt,Mn,Kt,O,se,r,qe,It]),Ht=o.useMemo(()=>({setDraft:be,setComposerMode:oe,setDraftAttachments:ee,selectAssignee:vn,toggleWatcher:en,setSelectedInitiativeId:P,toggleAssigneePicker:Ut,toggleWatcherPicker:Kn,toggleScopePicker:kn,setAgentPickerQuery:je,setScopePickerQuery:M,setAgentPickerMode:ie,setScopePickerOpen:Me,handlePrimaryAction:Gt,handleFilesAdded:Tn,handleRetryAttachment:ms,openThreadPanel:dn,closeThreadPanel:Vn,loadThreadDetail:$t,applyScopeLink:Gn,resetComposer:bt,setComposerError:W,setComposerNotice:Te,setLaunchWarningAccepted:Ye,pushInlineMessage:zt,clearInlineMessages:wn,toggleThreadSidebar:Tt,setSelectedProvider:Ce,cycleProvider:Bt,fileInputRef:Ge,panelHeadingRef:$e,composerShellRef:We}),[vn,en,Ut,Kn,kn,Gt,Tn,ms,dn,Vn,$t,Gn,bt,zt,wn,Tt,Bt]);return n.jsx(wl.Provider,{value:Qn,children:n.jsx(vl.Provider,{value:Ht,children:e})})}const Cp={type:"spring",stiffness:500,damping:35,mass:.5};function Mp({messages:e,isStreaming:t,collapsed:s,onClick:r}){var l;const i=Hn(),a=o.useRef(null);o.useEffect(()=>{const d=a.current;d&&d.scrollTo({top:d.scrollHeight,behavior:"smooth"})},[e.length,(l=e[e.length-1])==null?void 0:l.body]);const c=s?e.slice(-2):e;return c.length===0?null:n.jsx(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:c.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:Cp,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===c[c.length-1]&&d.role==="agent"&&n.jsx("span",{className:"ml-0.5 inline-block h-[14px] w-[2px] translate-y-[2px] rounded-full bg-white/50",style:{animation:"pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite"}})]})]})},d.id))})})})}function xo({open:e,onClose:t}){const s=Hn(),{displayedThreads:r,activeThreadId:i,activeThread:a,activeThreadSummary:c,panelLoading:l,panelError:d,scopeSaving:u,initiativeOptions:g}=xa(),{openThreadPanel:y,closeThreadPanel:w,loadThreadDetail:f,applyScopeLink:k,panelHeadingRef:x}=ya(),j=(a==null?void 0:a.id)??(c==null?void 0:c.id)??null,v=o.useCallback((h,_)=>{y(h,_)},[y]),b=o.useCallback(()=>{w(),t()},[w,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:b,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:Dt.durationEntrance/1e3,ease:Dt.easingEntrance},"aria-label":"Thread history","data-testid":"thread-drawer",className:"fixed bottom-0 left-0 right-0 z-25 flex max-h-[min(60vh,480px)] flex-col rounded-t-[22px] border-t border-white/[0.14] bg-[#0A0E16]/95 shadow-[0_-12px_40px_rgba(0,0,0,0.4)] backdrop-blur-xl",style:{paddingBottom:"max(12px, env(safe-area-inset-bottom))"},children:[n.jsx("div",{className:"flex justify-center py-2",children:n.jsx("div",{className:"h-1 w-10 rounded-full bg-white/[0.16]"})}),n.jsxs("header",{className:"flex items-center justify-between gap-2 px-4 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Threads"}),n.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:r.length})]}),n.jsx("button",{type:"button",onClick:b,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread drawer",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsxs("div",{className: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(ui,{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(h=>n.jsxs("button",{type:"button",onClick:_=>v(h.id,_.currentTarget),className:le("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",i===h.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:h.lastSnippet?`"${h.lastSnippet.length>40?h.lastSnippet.slice(0,40)+"...":h.lastSnippet}"`:h.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:h.lastActivityAt,children:_t(h.lastActivityAt)})]}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[h.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx("span",{className:"text-secondary",children:"@"})," ",h.assigneeName]}),n.jsx("span",{children:h.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Xs(h.status)),children:ri(h.status)})]})]},h.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:Dt.durationStandard/1e3,ease:Dt.easingStandard},className:"hidden min-h-0 flex-col overflow-hidden border-l border-white/[0.08] lg:flex",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-white/[0.06] px-4 py-2",children:[n.jsx("h4",{ref:x,tabIndex:-1,className:"truncate text-caption font-semibold text-primary outline-none",children:(a==null?void 0:a.title)??(c==null?void 0:c.title)??"Thread"}),n.jsx("span",{className:le("rounded-full border px-2 py-0.5 text-micro font-semibold",Xs((c==null?void 0:c.status)??"message_only")),children:ri((c==null?void 0:c.status)??"message_only")})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:l?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):d?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:d}),j&&n.jsx("button",{type:"button",onClick:()=>void f(j),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):a&&a.messages.length>0?n.jsx("div",{className:"space-y-2",children:a.messages.map(h=>n.jsx("article",{className:le("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:le("max-w-[90%] rounded-xl border px-2.5 py-1.5",h.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":h.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:h.senderName??yl(h.role)}),n.jsx("time",{dateTime:h.createdAt,children:_t(h.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:h.body})]})},h.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),a&&a.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[a.launches.length," launch",a.launches.length===1?"":"es"]}),a.launches.slice(0,2).map(h=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Xs(bl(h.status))),children:h.status}),n.jsx("span",{children:h.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:h.requestedAt,children:_t(h.requestedAt)})]},h.id))]})]})})]})]})]})})}function yo(){const e=Hn(),{displayedThreads:t,activeThreadId:s,activeThread:r,activeThreadSummary:i,panelLoading:a,panelError:c,scopeSaving:l,initiativeOptions:d,threadSidebarOpen:u}=xa(),{openThreadPanel:g,closeThreadPanel:y,loadThreadDetail:w,applyScopeLink:f,setComposerMode:k,toggleThreadSidebar:x,panelHeadingRef:j}=ya(),v=(r==null?void 0:r.id)??(i==null?void 0:i.id)??null,b=o.useCallback(()=>{x()},[x]);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:b,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:Dt.durationEntrance/1e3,ease:Dt.easingEntrance},"aria-label":"Thread sidebar","data-testid":"thread-sidebar",className:"fixed inset-y-0 left-0 z-25 flex w-[380px] max-w-[85vw] flex-col border-r border-white/[0.14] bg-[#0A0E16]/95 shadow-[12px_0_40px_rgba(0,0,0,0.4)] backdrop-blur-xl",children:[n.jsxs("header",{className:"flex items-center justify-between gap-2 border-b border-white/[0.08] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Threads"}),n.jsx("span",{className:"rounded-full border border-white/[0.12] bg-white/[0.04] px-2 py-0.5 text-micro text-secondary",children:t.length})]}),n.jsx("button",{type:"button",onClick:b,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread sidebar",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-3 py-3",children:t.length===0?n.jsxs("div",{className:"rounded-xl border border-white/[0.08] bg-white/[0.02] px-3 py-3 text-caption text-secondary",children:[n.jsx("p",{className:"text-primary",children:"No threads yet."}),n.jsx("p",{className:"mt-0.5",children:"Send a message to start one."}),n.jsx(he.button,{type:"button",whileHover:e?void 0:{y:-1},whileTap:e?void 0:go,transition:ho,onClick:()=>{b(),k("focused"),requestAnimationFrame(()=>{const h=document.getElementById("chat-dock-input");h instanceof HTMLTextAreaElement&&h.focus()})},className:"mt-2 inline-flex min-h-[34px] items-center rounded-full border border-lime/30 bg-lime/[0.12] px-2.5 text-micro font-semibold text-[#E1FFB2] hover:bg-lime/[0.18]",children:"Start thread"})]}):n.jsx("div",{className:"space-y-1.5",children:t.map((h,_)=>n.jsxs(he.button,{type:"button",initial:e?!1:{opacity:0,x:-8},animate:e?{}:{opacity:1,x:0},transition:{...e?{}:ho,delay:e?0:Math.min(_*.02,.16)},whileHover:e?void 0:{x:2},whileTap:e?void 0:go,onClick:V=>void g(h.id,V.currentTarget),className:le("w-full rounded-xl border px-3 py-2 text-left transition-colors duration-150",s===h.id?"border-lime/35 bg-lime/[0.08]":"border-white/[0.08] bg-white/[0.02] hover:border-white/[0.16] hover:bg-white/[0.05]"),children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsx("p",{className:"min-w-0 truncate text-caption font-semibold text-primary",children:h.title}),n.jsx("time",{className:"flex-shrink-0 text-micro text-muted",dateTime:h.lastActivityAt,children:_t(h.lastActivityAt)})]}),n.jsx("p",{className:"mt-0.5 line-clamp-1 text-micro text-secondary",children:h.lastSnippet??h.summary??"No message yet."}),n.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-micro text-muted",children:[h.assigneeName&&n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Ft,{name:h.assigneeName,hint:h.assigneeName,size:"xs"}),n.jsx("span",{children:h.assigneeName})]}),n.jsx("span",{children:h.initiativeTitle??"Unscoped"}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Xs(h.status)),children:ri(h.status)})]})]},h.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:Dt.durationStandard/1e3,ease:Dt.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",Xs((i==null?void 0:i.status)??"message_only")),children:ri((i==null?void 0:i.status)??"message_only")}),n.jsx("button",{type:"button",onClick:y,className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-white/[0.14] bg-white/[0.03] text-micro text-secondary hover:bg-white/[0.08] hover:text-primary","aria-label":"Close thread detail",children:"×"})]})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-2",children:a?n.jsxs("div",{className:"space-y-2","aria-label":"Loading thread",children:[n.jsx("div",{className:"h-10 w-[78%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"}),n.jsx("div",{className:"ml-auto h-10 w-[68%] animate-pulse rounded-xl border border-white/[0.08] bg-white/[0.04]"})]}):c?n.jsxs("div",{className:"rounded-md border border-rose-400/30 bg-rose-400/[0.12] px-2.5 py-2 text-caption text-rose-100",children:[n.jsx("p",{children:c}),v&&n.jsx("button",{type:"button",onClick:()=>void w(v),className:"mt-1.5 inline-flex min-h-[28px] items-center rounded-full border border-rose-200/30 bg-rose-400/[0.12] px-2 text-micro text-rose-100 hover:bg-rose-400/[0.2]",children:"Retry"})]}):r&&r.messages.length>0?n.jsx("div",{className:"space-y-2",children:r.messages.map(h=>n.jsx("article",{className:le("flex",h.role==="user"?"justify-end":"justify-start"),children:n.jsxs("div",{className:le("max-w-[90%] rounded-xl border px-2.5 py-1.5",h.role==="system"?"border-white/[0.12] bg-white/[0.03] text-secondary":h.role==="agent"?"border-teal/25 bg-teal/[0.1] text-primary":"border-lime/25 bg-lime/[0.1] text-primary"),children:[n.jsxs("div",{className:"mb-0.5 flex items-center justify-between gap-2 text-micro text-muted",children:[n.jsx("span",{children:h.senderName??yl(h.role)}),n.jsx("time",{dateTime:h.createdAt,children:_t(h.createdAt)})]}),n.jsx("p",{className:"whitespace-pre-wrap text-caption",children:h.body})]})},h.id))}):n.jsx("p",{className:"text-caption text-secondary",children:"No messages yet."})}),r&&r.launches.length>0&&n.jsxs("div",{className:"border-t border-white/[0.06] px-4 py-2",children:[n.jsxs("p",{className:"text-micro font-semibold text-muted",children:[r.launches.length," launch",r.launches.length===1?"":"es"]}),r.launches.slice(0,2).map(h=>n.jsxs("div",{className:"mt-1 flex items-center gap-2 text-micro text-secondary",children:[n.jsx("span",{className:le("rounded-full border px-1.5 py-0 text-[10px] font-semibold",Xs(bl(h.status))),children:h.status}),n.jsx("span",{children:h.assigneeName??"Unset"}),n.jsx("time",{className:"text-muted",dateTime:h.requestedAt,children:_t(h.requestedAt)})]},h.id))]})]})})]},"sidebar-panel")]})}):null}const Tp={type:"spring",stiffness:500,damping:30,mass:.5};function Ep({open:e,agents:t,query:s,activeIndex:r,onSelect:i}){const a=Hn(),c=o.useRef(null);o.useEffect(()=>{if(!e||!c.current)return;const u=c.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[r,e]);const l=s.length>0?t.filter(u=>{const g=s.toLowerCase();return u.name.toLowerCase().includes(g)||u.handle.toLowerCase().includes(g)||u.domain.toLowerCase().includes(g)||u.role.toLowerCase().includes(g)}):t;if(!e||l.length===0)return null;const d=l.slice(0,6);return n.jsx(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:Tp,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:c,className:"space-y-px",children:d.map((u,g)=>{const y=g===r;return n.jsxs("button",{type:"button",role:"option","aria-selected":y,"data-active":y,onClick:()=>i(u),onMouseDown:w=>w.preventDefault(),className:le("flex w-full items-center gap-2.5 rounded-xl px-2.5 py-2 text-left","transition-colors duration-[60ms]",y?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:[n.jsx(Ft,{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 Rp={type:"spring",stiffness:500,damping:30,mass:.5};function Lp({open:e,initiatives:t,query:s,activeIndex:r,onSelect:i}){const a=Hn(),c=o.useRef(null);o.useEffect(()=>{if(!e||!c.current)return;const u=c.current.querySelector('[data-active="true"]');u&&u.scrollIntoView({block:"nearest"})},[r,e]);const l=s.length>0?t.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())):t;if(!e)return null;const d=l.slice(0,6);return n.jsx(yt,{children:n.jsx(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:Rp,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:c,className:"space-y-px",children:[n.jsx("button",{type:"button",role:"option","aria-selected":r===0,"data-active":r===0,onClick:()=>i(null),onMouseDown:u=>u.preventDefault(),className: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 y=g+1===r;return n.jsx("button",{type:"button",role:"option","aria-selected":y,"data-active":y,onClick:()=>i(u),onMouseDown:w=>w.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]",y?"bg-white/[0.08] text-primary":"text-secondary hover:bg-white/[0.05] hover:text-primary"),children:n.jsx("span",{className:"truncate",children:u.name})},u.id)})]})})})}function Dp({open:e,mode:t,agents:s,quickAgents:r,query:i,selectedAssigneeId:a,selectedWatcherIds:c,onQueryChange:l,onSelectAssignee:d,onToggleWatcher:u,onClose:g,onSwitchMode:y,anchorRef:w}){const f=Hn();return n.jsx(yt,{children:e&&n.jsxs(he.div,{initial:f?!1:{opacity:0,scale:.95,y:8},animate:f?{}:{opacity:1,scale:1,y:0},exit:f?{}:{opacity:0,scale:.95,y:8},transition:f?void 0:Dt.easingBounce,className:"absolute bottom-[calc(100%+8px)] left-0 z-30 w-[320px] rounded-xl border border-white/[0.14] bg-[#0A0E16]/98 p-2.5 shadow-[0_20px_44px_rgba(0,0,0,0.45)] backdrop-blur-xl",children:[n.jsx("div",{className:"absolute -bottom-[6px] left-4 h-0 w-0 border-l-[6px] border-r-[6px] border-t-[6px] border-l-transparent border-r-transparent border-t-white/[0.14]","aria-hidden":!0}),n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsxs("div",{className:"flex gap-1",children:[n.jsx("button",{type:"button",onClick:()=>y("assignee"),className: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:()=>y("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(k=>{const x=a===k.id;return n.jsx("button",{type:"button",onClick:()=>d(k.id),title:k.name,className:le("flex-shrink-0 rounded-full p-0.5 transition-all duration-[120ms]",x?"ring-2 ring-lime/60 ring-offset-1 ring-offset-[#0A0E16]":"ring-1 ring-white/[0.12] hover:ring-white/[0.24]"),"aria-pressed":x,"aria-label":`Select ${k.name} as assignee`,children:n.jsx(Ft,{name:k.name,hint:k.name,size:"xs"})},k.id)})}),n.jsx("input",{value:i,onChange:k=>l(k.target.value),placeholder:"Search agents...",className:"mb-2 h-9 w-full rounded-lg border border-white/[0.12] bg-black/35 px-2.5 text-caption text-primary outline-none focus:border-lime/35",autoFocus:!0}),n.jsx("div",{className:"max-h-[240px] space-y-1 overflow-y-auto",children:s.map(k=>{const x=a===k.id,j=c.includes(k.id);return n.jsxs("button",{type:"button",onClick:()=>{if(t==="assignee"){d(k.id);return}x||u(k.id)},className:le("flex min-h-[38px] w-full items-center justify-between rounded-lg border px-2 py-1.5 text-left text-caption",x?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":j?"border-teal/30 bg-teal/[0.12] text-teal-100":"border-white/[0.1] bg-white/[0.02] text-secondary hover:bg-white/[0.08] hover:text-primary"),children:[n.jsxs("span",{className:"inline-flex items-center gap-2",children:[n.jsx(Ft,{name:k.name,hint:k.name,size:"xs"}),n.jsx("span",{children:k.name})]}),n.jsx("span",{className:"text-micro",children:x?"Assignee":j?"Watcher":"Select"})]},k.id)})})]})})}const bo=24,wo=200;function vo(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 $p(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 ko({icon:e,className:t}){return e==="anthropic"?n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",className:t,children:n.jsx("path",{d:"M16.5 2.3L12 21.7l-1.7-6.5L3.8 13l6.5-1.7L12 4.8l1.7 6.5 6.5 1.7-6.5 1.7L12 21.7"})}):e==="openai"?n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[n.jsx("path",{d:"M12 2a7 7 0 0 1 7 7c0 2.38-1.19 4.47-3 5.74V17a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2.26C6.19 13.47 5 11.38 5 9a7 7 0 0 1 7-7z"}),n.jsx("line",{x1:"10",y1:"21",x2:"14",y2:"21"})]}):n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:n.jsx("path",{d:"M12 2l2.4 7.2L22 12l-7.6 2.8L12 22l-2.4-7.2L2 12l7.6-2.8z"})})}const ra="orgx-chat-dock-collapsed";function Fp(){try{return localStorage.getItem(ra)==="1"}catch{return!1}}function Pp(){const e=xa(),t=ya(),s=Hn(),r=o.useRef(null),i=o.useRef(null),[a,c]=o.useState(Fp),l=o.useCallback(()=>{c(B=>{const Pe=!B;try{localStorage.setItem(ra,Pe?"1":"0")}catch{}return Pe})},[]),[d,u]=o.useState(!1),[g,y]=o.useState(!1),w=o.useRef(null),[f,k]=o.useState(!1),[x,j]=o.useState(""),[v,b]=o.useState(0),[h,_]=o.useState(-1),[V,oe]=o.useState(!1),[K,be]=o.useState(""),[H,Z]=o.useState(0),[ce,ye]=o.useState(-1),{composerMode:we,draft:W,draftAttachments:Ie,sending:Te,launching:fe,selectedAssigneeId:ee,selectedAssignee:de,selectedWatcherIds:Ee,selectedInitiative:ne,agentOptions:R,quickAssigneeOptions:J,agentPickerMode:P,agentPickerQuery:Y,filteredAgentOptions:ie,initiativeOptions:ve,canSend:je,activeThreadId:te,guidanceStatus:Me,inlineMessages:pe,displayedThreads:M,launchWarningOpen:O,launchWarningAccepted:U,selectedProvider:se,selectedProviderDef:Re}=e,qe=W.trim(),Ce=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,bo),wo);B.style.height=`${Pe}px`},[]);o.useLayoutEffect(()=>{T()},[W,T]);const q=o.useMemo(()=>{if(!f)return R;const B=x.toLowerCase();return B?R.filter(Pe=>Pe.name.toLowerCase().includes(B)||Pe.handle.toLowerCase().includes(B)||Pe.domain.toLowerCase().includes(B)||Pe.role.toLowerCase().includes(B)):R},[R,f,x]),re=o.useMemo(()=>{if(!V)return ve;const B=K.toLowerCase();return B?ve.filter(Pe=>Pe.name.toLowerCase().includes(B)):ve},[ve,V,K]);o.useEffect(()=>{if(w.current&&clearTimeout(w.current),pe.length<=2){y(!1);return}return y(!1),w.current=window.setTimeout(()=>{y(!0)},5e3),()=>{w.current&&clearTimeout(w.current)}},[pe.length]),o.useEffect(()=>{const B=Pe=>{if((Pe.metaKey||Pe.ctrlKey)&&Pe.key==="k"){if(Pe.preventDefault(),a){c(!1);try{localStorage.setItem(ra,"0")}catch{}}t.setComposerMode("focused"),requestAnimationFrame(()=>{var z;return(z=r.current)==null?void 0:z.focus()})}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[t,a]);const ue=o.useCallback(()=>{we==="resting"&&t.setComposerMode("focused")},[we,t]),_e=o.useCallback(()=>{window.setTimeout(()=>{qe.length===0&&!Ce&&!f&&!V&&Ie.length===0&&t.composerShellRef.current&&!t.composerShellRef.current.contains(document.activeElement)&&(t.setComposerMode("resting"),t.setAgentPickerMode(null),k(!1),oe(!1))},100)},[qe,Ce,f,V,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){k(!0),j(Ne[1]),b(0),_(z-Ne[0].length),oe(!1);return}const Le=Q.match(/#(\w*)$/);if(Le){oe(!0),be(Le[1]),Z(0),ye(z-Le[0].length),k(!1);return}f&&k(!1),V&&oe(!1)},[we,t,f,V]),Ge=o.useCallback(B=>{var Ne;const Pe=W.slice(0,h),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),k(!1),j(""),requestAnimationFrame(()=>{if(r.current){const Le=Pe.length+B.name.length+2;r.current.setSelectionRange(Le,Le),r.current.focus()}})},[W,h,t]),$e=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 Le=Pe.length+B.name.length+2;r.current.setSelectionRange(Le,Le),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]),Ke=o.useCallback(B=>{if(f&&q.length>0){if(B.key==="ArrowDown"){B.preventDefault(),b(Pe=>(Pe+1)%q.length);return}if(B.key==="ArrowUp"){B.preventDefault(),b(Pe=>(Pe-1+q.length)%q.length);return}if(B.key==="Enter"||B.key==="Tab"){B.preventDefault(),Ge(q[v]);return}if(B.key==="Escape"){B.preventDefault(),k(!1);return}}if(V){const Pe=re.length+1;if(B.key==="ArrowDown"){B.preventDefault(),Z(z=>(z+1)%Pe);return}if(B.key==="ArrowUp"){B.preventDefault(),Z(z=>(z-1+Pe)%Pe);return}if(B.key==="Enter"||B.key==="Tab"){B.preventDefault(),$e(H===0?null:re[H-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):Ce?t.clearInlineMessages():(t.setComposerMode("resting"),B.target.blur()))},[t,P,Ce,f,q,v,Ge,V,re,H,$e]),We=o.useCallback(()=>{t.toggleThreadSidebar()},[t]),ht=Te||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"})]}),st=(we==="reviewing"||Ce)&&pe.length>0,rt=Me==="submitted"||Me==="streaming",ge=o.useRef(pe.length),[He,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(xo,{open:d,onClose:()=>u(!1)}),n.jsx(yo,{}),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:()=>{l(),requestAnimationFrame(()=>{var B;return(B=r.current)==null?void 0:B.focus()})},initial:s?!1:{scale:.8,opacity:0},animate:s?{}:{scale:1,opacity:1},whileHover:s?void 0:{scale:1.08},whileTap:s?void 0:{scale:.92},transition:{type:"spring",stiffness:500,damping:28},className: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:He>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:He>9?"9+":He},"unread")}),te&&He===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(xo,{open:d,onClose:()=>u(!1)}),n.jsx(yo,{}),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(Dp,{open:P!==null,mode:P??"assignee",agents:ie,quickAgents:J,query:Y,selectedAssigneeId:ee,selectedWatcherIds:Ee,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:Dt.durationEntrance/1e3,ease:Dt.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:l,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:st&&n.jsx(Mp,{messages:pe,isStreaming:rt,collapsed:g,onClick:We})}),n.jsxs("div",{className:"relative",children:[n.jsx(Ep,{open:f,agents:q,query:x,activeIndex:v,anchorRect:null,onSelect:Ge,onClose:()=>k(!1)}),n.jsx(Lp,{open:V,initiatives:re,query:K,activeIndex:H,onSelect:$e,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:`${vo(B.mimeType)}20`},children:n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:vo(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:[$p(B.mimeType,B.name),B.sizeBytes?` · ${bp(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: ${Re.label}. Click to switch.`,"aria-label":`Current provider: ${Re.label}. Click to cycle.`,children:[n.jsx(ko,{icon:Re.icon}),n.jsx("span",{children:Re.shortLabel})]}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"chat-dock-input",className:"sr-only",children:"Chat composer"}),n.jsx("textarea",{ref:r,id:"chat-dock-input",value:W,onFocus:ue,onBlur:_e,onChange:Ye,onKeyDown:Ke,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:bo,maxHeight:wo,overflowY:"auto"},"aria-expanded":we!=="resting"})]}),M.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":`${M.length} thread${M.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"})}),M.length]}),n.jsx(he.button,{type:"button",onClick:()=>void t.handlePrimaryAction(),disabled:!je,"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",je?"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 ${Re.shortLabel}`:`Send via ${Re.shortLabel}`,"aria-label":de?`Send to ${de.name} via ${Re.shortLabel}`:`Send message via ${Re.shortLabel}`,children:ht})]}),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(Ft,{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:Re.accent},children:[n.jsx(ko,{icon:Re.icon}),Re.shortLabel]})]})})]})]})]})}const $i=50,Op=50,ur=20,jo=3600,No=12e3,Fr={all:"All",completed:"Completed",needs_attention:"Needs attention",in_progress:"In progress"},Io=["live","24h","7d","all"];function Ao(e){if(e==="custom"||e==="all")return null;const t=Io.indexOf(e);return t<0?null:Io[t+1]??null}function Bp(e){return e==="codex"?"codex":e==="openai"?"openai":e==="anthropic"?"anthropic":e==="openclaw"?"openclaw":e==="orgx"?"orgx":"unknown"}function So(e){return e==="codex"||e==="openai"||e==="anthropic"||e==="openclaw"}function os(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Pr(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function Or(e){return e?e.toLocaleString([],{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}):"—"}function Fi(e){return e?new Date(e.getTime()-e.getTimezoneOffset()*6e4).toISOString().slice(0,16):""}function _o(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?new Date(t):null}function _s(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return e}function ba(e){if(!e)return;let t={...e},s=_s(t.metadata),r=0;for(;s&&r<4;)t={...t,...s},s=_s(s.metadata),r+=1;return t}function Nt(e){const t=_s(e==null?void 0:e.metadata);return ba(t)}function qp(e){const t=ba(e);if(!t)return"";const s=[];for(const[r,i]of Object.entries(t))typeof i=="string"&&(r.toLowerCase().includes("type")||r.toLowerCase().includes("kind")||r.toLowerCase().includes("summary")||r.toLowerCase().includes("message")||r.toLowerCase().includes("artifact")||r.toLowerCase().includes("decision")||r.toLowerCase().includes("run")||r.toLowerCase().includes("title")||r.toLowerCase().includes("task")||r.toLowerCase().includes("workstream")||r.toLowerCase().includes("milestone"))&&s.push(i);return s.join(" ")}function ia(e){if(e.runId)return e.runId;const t=Nt(e);if(!t)return null;const s=["runId","run_id","sliceRunId","slice_run_id","sessionId","session_id","agentRunId"];for(const r of s){const i=t[r];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function hr(e){const t=Nt(e);if(!t)return{agentId:null,agentName:null};const s=(typeof t.agent_id=="string"&&t.agent_id.trim().length>0?t.agent_id.trim():null)??(typeof t.agentId=="string"&&t.agentId.trim().length>0?t.agentId.trim():null)??(typeof e.agentId=="string"&&e.agentId.trim().length>0?e.agentId.trim():null),r=(typeof t.agent_name=="string"&&t.agent_name.trim().length>0?t.agent_name.trim():null)??(typeof t.agentName=="string"&&t.agentName.trim().length>0?t.agentName.trim():null)??(typeof e.agentName=="string"&&e.agentName.trim().length>0?e.agentName.trim():null);return{agentId:s,agentName:r}}function Co(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const zp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Wp=/^[0-9a-f]{20,}$/i,kl=/^\d+$/,jl=/^(user|usr|clerk)_[a-z0-9]+$/i;function Zt(e){if(!e)return null;const t=e.trim();return!t||zp.test(t)||Wp.test(t)||kl.test(t)||jl.test(t)?null:t}const Up=new Set(["main","system","local","cli","openclaw","runtime","unknown"]);function Hp(e){if(!e||e.trim().length===0||e.trim()==="—")return{primary:"OrgX",secondary:null};const t=e.trim(),s=t.toLowerCase();return Up.has(s)?{primary:"You",secondary:t}:{primary:t,secondary:null}}function Mo(e,t,s){if(!e)return null;let r=null;for(const a of t){const c=Zt(Co(e[a]));if(c){r=c;break}}let i=null;for(const a of s){const c=Zt(Co(e[a]));if(c){i=c;break}}return!r&&!i?null:{id:r,name:i,label:i??r??"OrgX"}}function Vp(e,t){var s,r;if(!e||!t)return!1;if(e.id&&t.id){const i=e.id.trim().toLowerCase(),a=t.id.trim().toLowerCase();if(i===a){const c=((s=e.name)==null?void 0:s.trim().toLowerCase())??null,l=((r=t.name)==null?void 0:r.trim().toLowerCase())??null;return c&&l&&c!==l?!1:["unknown","system","agent","none","null","undefined"].includes(i)?!!(c&&l&&c===l):!0}}return!e.name||!t.name?!1:e.name.trim().toLowerCase()===t.name.trim().toLowerCase()}function To(e){const t=Nt(e),s=hr(e),r=oi(e),i=Zt(s.agentId),a=Zt(s.agentName),c=Zt(e.requesterAgentId??null),l=Zt(e.requesterAgentName??null),u=(c||l?{id:c,name:l,label:l??c??"OrgX"}:null)??Mo(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),y=Zt(e.executorAgentName??null),f=(g||y?{id:g,name:y,label:y??g??"Agent"}:null)??Mo(t,["executed_by_agent_id","executedByAgentId","executor_agent_id","executorAgentId","delegated_to_agent_id","delegatedToAgentId","handoff_to_agent_id","handoffToAgentId","agent_id","agentId"],["executed_by_agent_name","executedByAgentName","executor_agent_name","executorAgentName","delegated_to_agent_name","delegatedToAgentName","handoff_to_agent_name","handoffToAgentName","agent_name","agentName"])??(i||a?{id:i,name:a,label:a??i??"Agent"}:null);return u&&f?Vp(u,f)?{requester:u,executor:f,mode:"single",primaryLabel:f.label,subtitle:f.label}:{requester:u,executor:f,mode:"handoff",primaryLabel:f.label,subtitle:`${u.label} handed off to ${f.label}`}:u&&!f?{requester:u,executor:null,mode:"requested",primaryLabel:u.label,subtitle:`${u.label} requested a run`}:!u&&f?{requester:null,executor:f,mode:"single",primaryLabel:f.label,subtitle:f.label}:r.isSystem?{requester:null,executor:null,mode:"system",primaryLabel:"OrgX",subtitle:"OrgX"}:{requester:null,executor:null,mode:"system",primaryLabel:Zt(e.agentName??null)??Zt(e.agentId??null)??"OrgX",subtitle:Zt(e.agentName??null)??Zt(e.agentId??null)??"OrgX"}}function Pi(e){return e?[e.id,e.name,e.label].filter(Boolean).join(" "):""}function mr(e){const t=Nt(e);if(!t)return null;const s=["workstreamId","workstream_id"];for(const i of s){const a=t[i];if(typeof a=="string"&&a.trim().length>0)return a.trim()}const r=t.orgx_context;if(r&&typeof r=="object"&&!Array.isArray(r)){const i=r,a=i.workstreamId??i.workstream_id;if(typeof a=="string"&&a.trim().length>0)return a.trim()}return null}function Oi(e){const t=Nt(e);if(!t)return null;const s=["artifact_id","artifactId","work_artifact_id"];for(const r of s){const i=t[r];if(typeof i=="string"&&i.length>0)return i}return null}const Eo=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 Br(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="artifact"?"artifact":t==="decision"?"decision":t==="message"?"message":null}function Kp(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="boolean")return r;if(typeof r=="string"){const i=r.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}}return null}function Vs(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 Gp(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 Xp(e){const t=Nt(e),s=Br(e.kind)??Br(t==null?void 0:t.activity_bucket)??Br(t==null?void 0:t.activityBucket)??Br(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=Gp(t),i=e.decisionRequired===!0||Kp(t,["decision_required","decisionRequired"])===!0,a=Vs(t,["artifacts","artifact_count","artifactCount"])??0,c=Vs(t,["decisions","decision_count","decisionCount"])??0,l=Vs(t,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??0,d=Vs(t,["non_blocking_decisions","nonBlockingDecisions","non_blocking_decision_count","nonBlockingDecisionCount"])??0;if(r==="autopilot_slice_result")return i||l>0?"decision":a>0?"artifact":c>0||d>0?"decision":"message";if(r==="auto_continue_stopped"){const g=_n(dt(t,["stop_reason","stopReason"])??"");if(g==="blocked"||g==="error")return"decision"}return r&&Eo.has(r)?Eo.get(r):typeof(t==null?void 0:t.artifact_id)=="string"||typeof(t==null?void 0:t.artifactId)=="string"||typeof(t==null?void 0:t.work_artifact_id)=="string"||a>0?"artifact":i||c>0||l>0||d>0?"decision":"message"}function ii(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 Qp(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 Jp(e){const t=Number(e);if(!Number.isFinite(t))return"Unknown day";const s=new Date(t),r=new Date,i=new Date(r.getFullYear(),r.getMonth(),r.getDate()),a=new Date(i);return a.setDate(i.getDate()-1),s.getTime()===i.getTime()?"Today":s.getTime()===a.getTime()?"Yesterday":s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:s.getFullYear()===r.getFullYear()?void 0:"numeric"})}function Bi(e){return e==="completed"?"Completed":e==="needs_input"?"Needs attention":e==="issue"?"Issue":e==="in_progress"?"In progress":"Update"}function qi(e){return e==="completed"?E.lime:e==="needs_input"?E.amber:e==="issue"?E.red:E.teal}function Yp(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 Ro(e){if(!e||Object.keys(e).length===0)return null;try{return JSON.stringify(e,null,2)}catch{return null}}function ls(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 qn(e){const t=ls(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=ls(s.count??s.total??s.size);if(r!==null)return Math.max(0,Math.round(r))}return null}function Zp(e){const t=ls(e);if(t===null)return null;const s=t>0&&t<=1?t*100:t;return Math.max(0,Math.min(100,Math.round(s)))}function ef(e,t){for(const s of t){const r=Zp(e[s]);if(r!==null)return r}return null}function qr(e,t){const s=[],r=new Set,i=a=>{if(typeof a!="string")return;const c=a.trim();!c||r.has(c)||(r.add(c),s.push(c))};for(const a of t){const c=e[a];if(Array.isArray(c)){for(const l of c)i(l);continue}i(c)}return s}function Nl(e){if(!e)return{decisionIds:[],blockingDecisionIds:[],nonBlockingDecisionIds:[]};const t=qr(e,["blocking_decision_ids","blockingDecisionIds"]),s=qr(e,["non_blocking_decision_ids","nonBlockingDecisionIds"]),r=qr(e,["decision_id","decisionId","decision_ids","decisionIds"]),i=new Set([...r,...t,...s]),a=e.decisions_needed??e.decisionsNeeded;if(Array.isArray(a))for(const c of a){if(!c||typeof c!="object"||Array.isArray(c))continue;const l=c,d=qr(l,["id","decision_id","decisionId"]),u=l.blocking!==!1;for(const g of d)i.add(g),u?t.includes(g)||t.push(g):s.includes(g)||s.push(g)}return{decisionIds:Array.from(i),blockingDecisionIds:t,nonBlockingDecisionIds:s}}function Il(e){if(!e)return null;const t=Nt(e);if(!t)return null;const s=typeof t.event=="string"&&t.event.trim().length>0?t.event.trim():null,r=s??"",i=r.startsWith("autopilot_slice")&&!r.includes("artifact")||r.startsWith("autopilot_autofix");if(!s||!i&&s!=="auto_continue_started"&&s!=="auto_continue_stopped"&&s!=="next_up_manual_dispatch_started")return null;const a=hr(e),c=(typeof t.requested_by_agent_id=="string"&&t.requested_by_agent_id.trim().length>0?t.requested_by_agent_id.trim():null)??(typeof t.requestedByAgentId=="string"&&t.requestedByAgentId.trim().length>0?t.requestedByAgentId.trim():null)??(typeof t.runner_agent_id=="string"&&t.runner_agent_id.trim().length>0?t.runner_agent_id.trim():null)??(typeof t.runnerAgentId=="string"&&t.runnerAgentId.trim().length>0?t.runnerAgentId.trim():null)??a.agentId,l=(typeof t.requested_by_agent_name=="string"&&t.requested_by_agent_name.trim().length>0?t.requested_by_agent_name.trim():null)??(typeof t.requestedByAgentName=="string"&&t.requestedByAgentName.trim().length>0?t.requestedByAgentName.trim():null)??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??a.agentName,d=(typeof t.source_client=="string"&&t.source_client.trim().length>0?t.source_client.trim():null)??(typeof t.sourceClient=="string"&&t.sourceClient.trim().length>0?t.sourceClient.trim():null)??(typeof e.runtimeClient=="string"&&e.runtimeClient.trim().length>0?e.runtimeClient.trim():null),u=t.required_skills??t.requiredSkills,g=Array.isArray(u)?u.filter(U=>typeof U=="string"&&U.trim().length>0):[],y=of(g),w=t.task_ids??t.taskIds,f=Array.isArray(w)?w.filter(U=>typeof U=="string"&&U.trim().length>0):[],k=t.milestone_ids??t.milestoneIds,x=Array.isArray(k)?k.filter(U=>typeof U=="string"&&U.trim().length>0):[],j=dt(t,["initiative_id","initiativeId"])??(typeof e.initiativeId=="string"&&e.initiativeId.trim().length>0?e.initiativeId.trim():null),v=dt(t,["initiative_title","initiativeTitle"]),b=dt(t,["initiative_status","initiativeStatus"]),h=mr(e),_=dt(t,["workstream_title","workstreamTitle"]),V=dt(t,["workstream_status","workstreamStatus"]),oe=dt(t,["task_title","taskTitle"]),K=dt(t,["milestone_title","milestoneTitle"]),be=dt(t,["domain"]),H=dt(t,["phase","slice_phase","slicePhase"]),Z=dt(t,["next_step","nextStep"]),ce=ef(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,Te=typeof t.error=="string"?t.error:null,fe=qn(t.artifacts??t.artifact_count??t.artifactCount),ee=qn(t.decisions??t.decision_count??t.decisionCount),de=Nl(t),Ee=t.decisions_needed??t.decisionsNeeded;let ne=qn(t.blocking_decisions??t.blockingDecisions??t.blocking_decision_count??t.blockingDecisionCount),R=qn(t.non_blocking_decisions??t.nonBlockingDecisions??t.non_blocking_decision_count??t.nonBlockingDecisionCount);if((ne===null||R===null)&&Array.isArray(Ee)){let U=0,se=0;for(const Re of Ee){if(!Re||typeof Re!="object"||Array.isArray(Re))continue;Re.blocking===!1?se+=1:U+=1}ne===null&&(ne=U),R===null&&(R=se)}ne===null&&ee!==null&&e.decisionRequired===!0&&(ne=ee>0?ee:1),R===null&&ee!==null&&ne!==null&&(R=Math.max(0,ee-ne)),ne===null&&ee!==null&&R!==null&&(ne=Math.max(0,ee-R));const J=qn(t.status_updates_applied??t.statusUpdatesApplied),P=qn(t.task_updates??t.taskUpdates),Y=qn(t.milestone_updates??t.milestoneUpdates),ie=J??(P!==null||Y!==null?(P??0)+(Y??0):null),ve=qn(t.status_updates_buffered??t.statusUpdatesBuffered),je=typeof t.stop_reason=="string"?t.stop_reason:typeof t.stopReason=="string"?t.stopReason:null,te=ls(t.token_budget??t.tokenBudget),Me=ls(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),M=a.agentName??(typeof t.runner_agent_name=="string"&&t.runner_agent_name.trim().length>0?t.runner_agent_name.trim():null)??(typeof t.runnerAgentName=="string"&&t.runnerAgentName.trim().length>0?t.runnerAgentName.trim():null)??y,O=y&&!a.agentName?null:pe;return{event:s,agentId:O,agentName:M,requesterAgentId:c,requesterAgentName:l,dispatcherClient:d,initiativeId:j,domain:be,phase:H,progressPct:ce,nextStep:Z,requiredSkills:g,initiativeStatus:b,initiativeTitle:v,workstreamId:h,workstreamStatus:V,workstreamTitle:_,taskTitle:oe,milestoneTitle:K,taskIds:f,milestoneIds:x,parsedStatus:ye,hasOutput:we,artifacts:fe,decisions:ee,blockingDecisions:ne,nonBlockingDecisions:R,decisionIds:de.decisionIds,blockingDecisionIds:de.blockingDecisionIds,nonBlockingDecisionIds:de.nonBlockingDecisionIds,statusUpdatesApplied:ie,statusUpdatesBuffered:ve,stopReason:je,tokenBudget:te,tokensUsed:Me,logPath:W,outputPath:Ie,error:Te}}function zi(e){const t=e.trim();return t?/^https?:\/\//i.test(t)?t:`/orgx/api/live/filesystem/open?path=${encodeURIComponent(t)}`:""}function tf(e){const t=ba(e);if(!t)return null;const s=t,r=s.orgx_provenance,i=r&&typeof r=="object"&&!Array.isArray(r)?r:null,a=i!=null&&i.skill_pack&&typeof i.skill_pack=="object"&&!Array.isArray(i.skill_pack)?i.skill_pack:null,c=(typeof s.orgx_plugin_version=="string"?s.orgx_plugin_version:null)??(typeof(i==null?void 0:i.plugin_version)=="string"?i.plugin_version:null),l=(typeof s.skill_pack_name=="string"?s.skill_pack_name:null)??(typeof(a==null?void 0:a.name)=="string"?a.name:null),d=(typeof s.skill_pack_version=="string"?s.skill_pack_version:null)??(typeof(a==null?void 0:a.version)=="string"?a.version:null),u=(typeof s.skill_pack_checksum=="string"?s.skill_pack_checksum:null)??(typeof(a==null?void 0:a.checksum)=="string"?a.checksum:null),g=(typeof s.skill_pack_source=="string"?s.skill_pack_source:null)??(typeof(a==null?void 0:a.source)=="string"?a.source:null),y=typeof s.kickoff_context_hash=="string"?s.kickoff_context_hash:null,w=typeof s.kickoff_context_source=="string"?s.kickoff_context_source:null,f=typeof s.spawn_guard_model_tier=="string"?s.spawn_guard_model_tier:null,k=typeof s.provider=="string"?s.provider:null,x=typeof s.model=="string"?s.model:null,j=typeof s.domain=="string"?s.domain:null,v=s.required_skills??s.requiredSkills,b=Array.isArray(v)?v.filter(_=>typeof _=="string"&&_.trim().length>0):[];return!!c||!!(l||d||u)||!!y||!!(f||k||x||j)||b.length>0?{pluginVersion:c,skillPack:l||d||u||g?{name:l,version:d,checksum:u,source:g}:null,kickoffContextHash:y,kickoffContextSource:w,modelTier:f,provider:k,model:x,domain:j,requiredSkills:b}:null}function Al(e){if(!e)return null;const t=Nt(e);if(!t||typeof t!="object")return null;const s=["artifact","artifacts","output","outputs","result","results","payload","toolOutput","toolOutputs","toolResult","toolResults"];for(const r of s){const i=t[r];if(i!=null)return{source:r,value:i}}return e.type==="artifact_created"?{source:"metadata",value:t}:null}function nf(e){const t=Nt(e),s=!!(t&&typeof t.artifact_id=="string"||t&&typeof t.artifactId=="string"||t&&typeof t.work_artifact_id=="string"),r=Al(e);if(!r&&!s)return null;let i="Artifact";e.type==="artifact_created"?i="Created artifact":(r==null?void 0:r.source)==="toolOutput"||(r==null?void 0:r.source)==="toolOutputs"?i="Tool output":(r==null?void 0:r.source)==="toolResult"||(r==null?void 0:r.source)==="toolResults"?i="Result":(r==null?void 0:r.source)==="output"||(r==null?void 0:r.source)==="outputs"?i="Output":s&&(i="Registered artifact");let a="";if(r){const c=r.value;if(typeof c=="string")a=c.length>80?c.slice(0,80)+"…":c;else if(Array.isArray(c))a=`${c.length} item${c.length===1?"":"s"}`;else if(c&&typeof c=="object"){const l=Object.keys(c);a=l.length<=4?l.join(", "):`${l.length} fields`}}return{label:i,preview:a,hasRegisteredId:s}}function 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 Sl(e){const t=Nt(e);if(!t)return[];const s=[],r=new Set,i=(c,l)=>{if(typeof l!="string")return;const d=l.trim();if(!d||!sf(d))return;const u=`${c}:${d}`;r.has(u)||(r.add(u),s.push({key:c,path:d}))},a=(c,l="",d=0)=>{if(!(d>2))for(const[u,g]of Object.entries(c)){const y=l?`${l}.${u}`:u,w=u.toLowerCase();if(w.includes("path")||w==="url"||w==="uri"||w.endsWith("url")||w.endsWith("_file")||w.endsWith("file")||w.includes("artifact"))if(Array.isArray(g))for(const k of g)i(y,k);else i(y,g);g&&typeof g=="object"&&!Array.isArray(g)&&a(g,y,d+1)}};return a(t),s}function dt(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 rf(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 af(e,t){if(!e)return null;const s=Nt(e);if(!s)return null;const r=dt(s,["event","event_name","eventName"]),i=_s(s.spawn_guard),a=_s(i==null?void 0:i.checks),c=_s((a==null?void 0:a.rateLimit)??(a==null?void 0:a.rate_limit)),l=dt(s,["blocked_reason","blockedReason","last_error","lastError"])??(t==null?void 0:t.error)??null,d=rf(l),u=ls(c==null?void 0:c.current)??d.domainCurrent,g=ls(c==null?void 0:c.max)??d.domainMax,y=d.totalCurrent,w=d.totalMax,f=typeof(c==null?void 0:c.passed)=="boolean"?c.passed:null,k=((r==null?void 0:r.includes("rate_limited"))??!1)||!!(l&&/rate limit/i.test(l))||f===!1;return!((r==null?void 0:r.includes("spawn_guard"))??!1)&&!k&&!i&&!l?null:{event:r,blockedReason:l,domain:dt(s,["domain"])??dt(i,["domain","task_domain"]),modelTier:dt(s,["spawn_guard_model_tier","model_tier"])??dt(i,["modelTier","model_tier"]),domainCurrent:u,domainMax:g,totalCurrent:y,totalMax:w,retryAt:dt(s,["next_retry_at","nextRetryAt"]),retryInMs:ls(s.next_retry_in_ms??s.nextRetryInMs),isRateLimited:k}}function of(e){var r;if(e.length!==1)return null;const t=(r=e[0])==null?void 0:r.trim();if(!t)return null;const s={"orgx-marketing-agent":"OrgX Marketing","orgx-engineering-agent":"OrgX Engineering","orgx-design-agent":"OrgX Design","orgx-product-agent":"OrgX Product","orgx-sales-agent":"OrgX Sales","orgx-operations-agent":"OrgX Operations","orgx-orchestrator-agent":"OrgX Orchestrator"};if(s[t])return s[t];if(t.endsWith("-agent")){const i=t.replace(/^orgx-/,"").replace(/-agent$/,"").trim();return i.length===0?null:`OrgX ${lt(i)}`}return null}function lf(e){if(!e)return!1;const t=e.trim().toLowerCase();return t.startsWith("orgx ")?t==="orgx engineering"||t==="orgx product"||t==="orgx marketing"||t==="orgx sales"||t==="orgx operations"||t==="orgx design"||t==="orgx orchestrator":!1}function Wi(e,t,s){const r=typeof e=="string"&&e.trim().length>0?e.trim():null,i=typeof t=="string"&&t.trim().length>0?t.trim():null,a=i?(s==null?void 0:s.get(i))??null:null,c=r&&a&&lf(r)?a:r??a;if(c)return fr(c);if(!i)return"OrgX";const l=i.toLowerCase();return l==="main"||l==="system"||l==="unknown"||l==="runtime"||l==="orgx"||l==="openclaw"||l==="null"||l==="undefined"?fr(i):pr.test(i)||cf.test(i)||kl.test(i)||jl.test(i)?"OrgX":fr(i)}const pr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,cf=/^[0-9a-f]{20,}$/i,df=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;function ai(e){const t=new Set;if(!e)return t;for(const a of[e.title,e.summary,e.description])if(typeof a=="string")for(const c of a.match(df)??[]){const l=c.trim().toLowerCase();pr.test(l)&&t.add(l)}typeof e.runId=="string"&&pr.test(e.runId.trim())&&t.add(e.runId.trim().toLowerCase());const s=Nt(e);if(!s)return t;const r=["run_id","runId","last_run_id","lastRunId","active_run_id","activeRunId","slice_id","sliceId","worker_run_id","workerRunId","correlation_id","correlationId","initiative_id","initiativeId","workstream_id","workstreamId","task_id","taskId","milestone_id","milestoneId","decision_id","decisionId","outbox_event_id","outboxEventId"],i=["task_ids","taskIds","milestone_ids","milestoneIds","decision_ids","decisionIds","blocking_decision_ids","blockingDecisionIds","non_blocking_decision_ids","nonBlockingDecisionIds","allowed_workstream_ids","allowedWorkstreamIds"];for(const a of r){const c=s[a];if(typeof c=="string"){const l=c.trim().toLowerCase();pr.test(l)&&t.add(l)}}for(const a of i){const c=s[a];if(Array.isArray(c))for(const l of c){if(typeof l!="string")continue;const d=l.trim().toLowerCase();pr.test(d)&&t.add(d)}}return t}function uf(e){if(!e)return[];const t=Nt(e);return Nl(t).decisionIds}function mf(e,t,s){if(!e)return[];const r=Nt(e),i=dt(r,["workstream_id","workstreamId"]),a=dt(r,["initiative_id","initiativeId"]),c=ai(e);if(!i&&!a&&c.size===0)return[];const l=os(e.timestamp),d=[];for(const w of t){if(w.id===e.id)continue;const f=Nt(w);if(!f)continue;const k=dt(f,["workstream_id","workstreamId"]),x=dt(f,["initiative_id","initiativeId"]),j=ai(w),v=c.size>0&&Array.from(c).some(K=>j.has(K)),b=!!i&&!!k&&i===k;if(!v&&!b&&!(!!a&&!!x&&a===x))continue;const _=Sl(w).filter(K=>!s.has(K.path));if(_.length===0)continue;const V=Math.abs(os(w.timestamp)-l);if(!v&&V>7200*1e3)continue;const oe=v?0:b?1:2;!v&&V>1200*1e3||d.push({priority:oe,delta:V,evidence:_})}if(d.length===0)return[];d.sort((w,f)=>w.priority!==f.priority?w.priority-f.priority:w.delta-f.delta);const u=[],g=new Set(s),y=d[0].priority;for(const w of d){if(w.priority!==y)break;for(const f of w.evidence)if(!g.has(f.path)&&(g.add(f.path),u.push({key:`related.${f.key}`,path:f.path}),u.length>=8))return u}return u}function pf(e,t){if(!e)return null;const s=Nt(e),r=dt(s,["workstream_id","workstreamId"]),i=dt(s,["initiative_id","initiativeId"]),a=ai(e);if(!r&&!i&&a.size===0)return null;const c=os(e.timestamp),l=[];for(const u of t){if(u.id===e.id)continue;const g=Il(u);if(!g)continue;const y=Nt(u);if(!y)continue;const w=dt(y,["workstream_id","workstreamId"]),f=dt(y,["initiative_id","initiativeId"]),k=ai(u),x=a.size>0&&Array.from(a).some(V=>k.has(V)),j=!!r&&!!w&&r===w;if(!x&&!j&&!(!!i&&!!f&&i===f))continue;const b=Math.abs(os(u.timestamp)-c);if(!x&&b>1200*1e3)continue;const h=x?"shared_id":j?"workstream":"initiative",_=h==="shared_id"?0:h==="workstream"?1:2;l.push({priority:_,delta:b,relation:h,detail:g})}if(l.length===0)return null;l.sort((u,g)=>u.priority!==g.priority?u.priority-g.priority:u.delta-g.delta);const d=l[0];return{detail:d.detail,relation:d.relation}}function _n(e){return e?e.trim().toLowerCase().replace(/[\s-]+/g,"_"):""}function mi(e){const t=_n(e);return["done","complete","completed","stopped","success"].includes(t)}function ff(e){const t=_n(e.parsedStatus),s=_n(e.event);return t==="failed"||t==="error"||t==="timed_out"||t==="timeout"||t==="aborted"||s.includes("error")||s.includes("timeout")?"critical":t==="blocked"||e.stopReason==="blocked"?"warning":mi(t)||e.stopReason==="completed"?"positive":"neutral"}function hf(e){if(mi(e.parsedStatus)||e.stopReason==="completed")return 100;const t=_n(e.parsedStatus);if(t==="blocked"||t==="error"||t==="failed")return 100;const s=e.event;return s==="auto_continue_started"?3:s==="next_up_manual_dispatch_started"?8:s==="autopilot_slice_dispatched"?14:s==="autopilot_slice_status_updates_buffered"?72:s==="autopilot_slice_result"?92:s==="autopilot_autofix_scheduled"?6:s==="autopilot_autofix_executed"?18:s==="autopilot_autofix_skipped"||s==="auto_continue_stopped"?100:s.startsWith("autopilot_slice")?56:null}function _l(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e)))}function gf(e,t){if(!e&&t===null)return null;const s=e?ff(e):"neutral",r=l=>l>=100&&(s==="warning"||s==="critical"),i="Reached a terminal blocked state. Resolve blockers to continue.";if((e==null?void 0:e.progressPct)!==null&&(e==null?void 0:e.progressPct)!==void 0){const l=_l(e.progressPct)??0,d=r(l);return{pct:l,source:"metadata",label:d?i:"Reported by slice metadata",tone:s,terminalStop:d}}if(t!==null){const l=r(t);return{pct:t,source:"session",label:l?i:"Derived from runtime session",tone:s,terminalStop:l}}if(!e)return null;const a=hf(e);if(a===null)return null;const c=r(a);return{pct:a,source:"lifecycle",label:c?i:"Estimated from dispatch lifecycle",tone:s,terminalStop:c}}function xf(e,t,s,r=null){var v;const i=Nt(e),a=_n(dt(i,["event","event_name","eventName"])??(t==null?void 0:t.event)??""),c=_n(e.state??e.phase??e.kind??e.type),l=_n((s==null?void 0:s.parsedStatus)??(t==null?void 0:t.parsedStatus)??c),d=_n((s==null?void 0:s.stopReason)??(t==null?void 0:t.stopReason)),u=dt(i,["blocked_reason","blockedReason","error","message"])??(t==null?void 0:t.error)??e.description??null,g=Math.max(0,(s==null?void 0:s.decisions)??(t==null?void 0:t.decisions)??0),y=Math.max(0,(s==null?void 0:s.blockingDecisions)??(t==null?void 0:t.blockingDecisions)??(e.decisionRequired===!0?Math.max(1,g):0)),w=Math.max(0,(s==null?void 0:s.nonBlockingDecisions)??(t==null?void 0:t.nonBlockingDecisions)??Math.max(0,g-y)),f=e.decisionRequired===!0||e.type==="decision_requested"||y>0||l==="needs_decision"&&w===0,k=e.type==="run_completed"||e.type==="milestone_completed"||mi(l)||d==="completed",x=a.includes("spawn_guard_rate_limited")||!!(u&&/rate limit/i.test(u)),j=a.includes("spawn_guard_blocked");if(a==="auto_continue_started")return{label:"Autopilot on",summary:Mt(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:Mt(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:Mt(e.title)??"Autopilot stopped because the current dispatch scope is complete.",hint:null,tone:"positive"};if(d==="stopped")return{label:"Stopped",summary:Mt(e.title)??"Autopilot was stopped by request.",hint:"Start again to resume continuous dispatch.",tone:"neutral"};if(d==="blocked")return{label:f?"Needs decision":"Blocked",summary:Mt(e.title)??(f?"Autopilot is paused pending a decision.":"Autopilot is blocked and needs intervention."),hint:f?"Open the Decisions panel and approve the pending item to continue.":"Resolve the blocker, then restart autopilot.",tone:f?"warning":"critical"};if(d==="error")return{label:"Error",summary:Mt(e.title)??u??"Autopilot stopped because of an error.",hint:"Open evidence and logs, then retry or pause the workstream.",tone:"critical"}}if(a==="autopilot_transition"){const b=String((i==null?void 0:i.old_state)??""),h=String((i==null?void 0:i.new_state)??""),_=String((i==null?void 0:i.reason)??"");return h==="running"?{label:"Autopilot activated",summary:`State changed from ${b} to running.`,hint:"Autopilot will dispatch work from the Next Up queue.",tone:"positive"}:h==="blocked"||h==="error"?{label:h==="error"?"Autopilot error":"Autopilot blocked",summary:`State changed from ${b} to ${h}${_?`: ${_}`:""}.`,hint:"Review the triage queue for actionable items.",tone:"critical"}:{label:"Autopilot state change",summary:`${b} → ${h}${_?` (${_})`:""}.`,hint:null,tone:"neutral"}}if(x)return{label:"Rate limited",summary:u?Mt(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?Mt(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:w>0?"Completed + follow-up":"Completed",summary:w>0?`Execution completed. ${w} non-blocking decision${w===1?"":"s"} were logged for optional follow-up.`:r.sentence,hint:r.nextAction,tone:"positive"};if(r.status==="failed")return{label:"Failed",summary:u?Mt(u)??r.sentence:r.sentence,hint:r.nextAction,tone:"critical"};if(r.status==="needs_attention"){const b=f||(((v=r.nextAction)==null?void 0:v.toLowerCase().includes("decision"))??!1);return{label:b?"Needs decision":"Needs attention",summary:r.sentence,hint:r.nextAction??(b?"Review the Decisions panel and resolve the pending item.":"Review blocker details and resume when resolved."),tone:b?"warning":"critical"}}if(r.status==="in_progress")return{label:"In progress",summary:r.sentence,hint:null,tone:"neutral"}}return e.type==="run_failed"||e.type==="blocker_created"||l==="blocked"||l==="failed"||l==="error"||d==="blocked"||d==="error"?{label:"Blocked",summary:u?Mt(u)??"Execution is blocked.":"Execution is blocked and needs intervention.",hint:f?"Resolve the pending decision, then resume the session.":"Open the session and retry after fixing the blocker.",tone:"critical"}:f?{label:"Needs decision",summary:"Execution paused pending approval or a human choice.",hint:"Review the Decisions panel and approve the pending item to continue.",tone:"warning"}:k&&w>0?{label:"Completed + follow-up",summary:`Execution completed. ${w} non-blocking decision${w===1?"":"s"} were logged for optional follow-up.`,hint:"Review the decision for optimization, but no approval is required to mark this slice complete.",tone:"positive"}:e.type==="decision_resolved"?{label:"Decision resolved",summary:"A pending decision was completed.",hint:null,tone:"positive"}:k?{label:"Completed",summary:"Execution completed successfully.",hint:null,tone:"positive"}:e.type==="run_started"||c==="running"||c==="in_progress"?{label:"In progress",summary:"Execution is actively running.",hint:null,tone:"neutral"}:null}function Cl(e){if(typeof e=="string")return n.jsx(ni,{mode:"block",text:e,className:"text-body leading-relaxed text-primary"});if(typeof e=="number"||typeof e=="boolean")return n.jsx("p",{className:"text-body text-primary",children:String(e)});if(Array.isArray(e))return n.jsx("div",{className:"space-y-1.5",children:e.map((t,s)=>n.jsx("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:Cl(t)},`artifact-list-${s}`))});if(e&&typeof e=="object"){const t=Object.entries(e);return n.jsx("dl",{className:"space-y-1.5",children:t.map(([s,r])=>n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("dt",{className:"text-micro font-semibold tracking-[0.02em] text-secondary",children:lt(s)}),n.jsx("dd",{className:"mt-1 text-body text-primary",children:typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):Array.isArray(r)?`${r.length} item${r.length===1?"":"s"}`:r&&typeof r=="object"?`${Object.keys(r).length} field${Object.keys(r).length===1?"":"s"}`:"—"})]},s))})}return n.jsx("p",{className:"text-body text-secondary",children:"No artifact payload."})}function Mt(e){if(!e)return null;const t=e.trim();if(!t)return null;const s=xr(t);return s&&s!==t&&/^[a-z0-9._/-]+$/i.test(t)?s:lt(t)}const yf=[/^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 bf(e){return yf.some(t=>t.test(e))}function oi(e){const t=e.title??"";return bf(t)?/Exec failed|SIGKILL|SIGTERM|Error: /i.test(t)?{title:"Execution failed",isSystem:!0}:/outbox replay|changeset replayed/i.test(t)?{title:"Changes synced",isSystem:!0}:/execution policy/i.test(t)?{title:"System directive",isSystem:!0}:{title:"System event",isSystem:!0}:{title:lt(t)||lt(ii(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 gr(e){const t=Nt(e);if(!t)return!1;const s=(typeof t.event=="string"&&t.event.trim().length>0?t.event.trim().toLowerCase():null)??(typeof t.event_name=="string"&&t.event_name.trim().length>0?t.event_name.trim().toLowerCase():null)??(typeof t.eventName=="string"&&t.eventName.trim().length>0?t.eventName.trim().toLowerCase():null),r=(typeof t.source_client=="string"?t.source_client:null)??(typeof t.sourceClient=="string"?t.sourceClient:null),i=(r==null?void 0:r.toLowerCase())??"",a=(typeof e.kind=="string"&&e.kind.trim().length>0?e.kind.trim().toLowerCase():null)??(typeof t.kind=="string"&&t.kind.trim().length>0?t.kind.trim().toLowerCase():null)??(typeof t.event_kind=="string"&&t.event_kind.trim().length>0?t.event_kind.trim().toLowerCase():null)??(typeof t.eventKind=="string"&&t.eventKind.trim().length>0?t.eventKind.trim().toLowerCase():null)??"",c=/(changeset[\._ ]?(applied|replayed)|sync[\._ ]?applied|sentinel[\._ ]?(changeset|decision)[\._ ]?applied)/i.test(a),l=t.replayed===!0,d=typeof t.changeset_id=="string"&&t.changeset_id.trim().length>0||typeof t.changesetId=="string"&&t.changesetId.trim().length>0,u=/changes synced|changeset replayed|changeset applied|outbox replay/i.test(`${e.title??""} ${e.summary??""} ${e.description??""}`);return!!(s&&wf.has(s)||c||l&&(d||u)||d&&(u||i.includes("outbox")||i.includes("replay"))||i.includes("outbox_replay")&&u)}function Lo(e){var d;if(!e||!gr(e))return null;const t=Nt(e),s=qn((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=dt(t,["entity_type","entityType"])??i??(e.type==="milestone_completed"?"milestone":null),c=s!==null?`${s} change${s===1?"":"s"}`:"Queued changes",l=a?` for ${lt(a).toLowerCase()}`:"";return`${c}${l} were synced from local replay.`}function Ui(e){if(!gr(e))return null;const t=Nt(e);if(!t)return null;const s=dt(t,["idempotency_key","idempotencyKey"]);if(s)return`idem:${s.toLowerCase()}`;const r=dt(t,["event","event_name","eventName"])??"",i=dt(t,["changeset_id","changesetId"])??"",a=dt(t,["entity_type","entityType"])??"",c=dt(t,["entity_id","entityId"])??"",l=ia(e)??"",d=oi(e).title.trim().toLowerCase();return`fallback:${r.toLowerCase()}:${i.toLowerCase()}:${a.toLowerCase()}:${c.toLowerCase()}:${l.toLowerCase()}:${d}`}function vf(e){if(!e)return null;const t=Nt(e);if(!t||typeof t!="object")return null;const s=typeof t.source=="string"?t.source.trim():"",r=typeof t.turnId=="string"?t.turnId.trim():"";if(s!=="local_openclaw"||!r)return null;const i=typeof t.sessionKey=="string"&&t.sessionKey.trim().length>0?t.sessionKey.trim():null;return{turnId:r,sessionKey:i,runId:e.runId??null}}function Do(e){return e.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/_([^_\n]+)_/g,"$1")}function $o(e,t){const r=(Mt(t??e.summary)??Mt(e.description)??lt(e.title||ii(e.type))).replace(/\r\n/g,`
|
|
210
|
-
`).replace(/```[\s\S]*?```/g," ").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s*[-*]\s+/gm,"").replace(/\s+/g," ").trim(),i=r.split(`
|
|
211
|
-
`).map(c=>Do(c).trim()).filter(c=>c.length>0&&!/^\|?[:\-| ]+\|?$/.test(c));let a=i[0]??Do(r);return a.length<24&&i.length>1&&(a=`${a} ${i[1]}`.trim()),a.length>108?`${a.slice(0,107).trimEnd()}…`:a}const kf=o.memo(function({activity:t,sessions:s,sliceRuns:r=[],initiatives:i=[],timelineNarrative:a=[],selectedRunIds:c,selectedSessionLabel:l=null,selectedWorkstreamId:d=null,selectedWorkstreamLabel:u=null,agentFilter:g=null,timeFilterId:y="live",onTimeFilterChange:w,customTimeRange:f={startIso:null,endIso:null},onCustomTimeRangeChange:k,hasMore:x=!1,isLoadingMore:j=!1,onLoadMore:v,onClearSelection:b,onClearWorkstreamFilter:h,onClearAgentFilter:_,onFocusRunId:V,onOpenDecision:oe,requestedActivityItemId:K=null,onActivityItemRequestHandled:be,onPlayNextUp:H,onStartAutopilot:Z,onPauseWorkstream:ce,onCreateInitiative:ye,onOpenMissionControl:we,onOpenSettings:W,workspaceId:Ie=null,chatSnapshot:Te,onRefreshData:fe,isLoading:ee=!1,onOpenNextUp:de}){var va;const Ee=Hn(),{open:ne}=fl(),[R,J]=o.useState("all"),[P,Y]=o.useState(!1),[ie,ve]=o.useState(!1),[je,te]=o.useState(""),[Me,pe]=o.useState(new Set),[M,O]=o.useState({}),[U,se]=o.useState("newest"),[Re,qe]=o.useState(!1),[Ce,T]=o.useState(!1),[q,re]=o.useState($i),[ue,_e]=o.useState(null),[Ye,Ge]=o.useState(null),[$e,Ke]=o.useState(!1),[We,ht]=o.useState(1),[st,rt]=o.useState("structured"),[ge,He]=o.useState(null),[Ae,B]=o.useState("feed"),[Pe,z]=o.useState(null),[Q,Ne]=o.useState(null),[Le,De]=o.useState(!1),[Oe,Se]=o.useState(null),[Ve,ct]=o.useState(null),[ze,Ct]=o.useState(!1),[Ze,kt]=o.useState(null),[Jt,Kt]=o.useState(!1),cn=o.useRef(Date.now()),Mn=o.useRef(null),us=o.useRef(null),bt=o.useRef(null),zt=o.useRef(null),wn=o.useRef(null),[Tt,It]=o.useState(()=>Pr(f.startIso)),[Bt,Wt]=o.useState(()=>Pr(f.endIso)),[$t,dn]=o.useState(()=>typeof window>"u"?!1:window.innerWidth<=640),Vn=o.useMemo(()=>Jo(y),[y]),un=o.useMemo(()=>Pr(f.startIso),[f.startIso]),Tn=o.useMemo(()=>Pr(f.endIso),[f.endIso]),ms=o.useMemo(()=>!Tt||!Bt?!1:Bt.getTime()>=Tt.getTime(),[Bt,Tt]),vn=o.useMemo(()=>y!=="custom"?Vn.label:un&&Tn?`${Or(un)} - ${Or(Tn)}`:"Custom range",[Tn,un,y,Vn.label]);o.useEffect(()=>{It(un),Wt(Tn)},[Tn,un]),o.useEffect(()=>{if(typeof window>"u")return;const p=()=>dn(window.innerWidth<=640);return p(),window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[]),o.useEffect(()=>{const N=()=>{cn.current=Date.now()};window.addEventListener("pointerdown",N),window.addEventListener("keydown",N);const I=setInterval(()=>{Date.now()-cn.current>3e5&&Kt(!0)},3e4);return()=>{window.removeEventListener("pointerdown",N),window.removeEventListener("keydown",N),clearInterval(I)}},[]);const en=o.useMemo(()=>{const p=s.filter($=>$.status==="completed").length,N=s.filter($=>$.status==="blocked"||$.status==="failed").length,I=t.filter($=>{var ke;return $.type==="decision_requested"&&((ke=$.metadata)==null?void 0:ke.status)==="pending"}).length;return{completed:p,blocked:N,decisions:I}},[s,t]),Ut=o.useMemo(()=>{const p=new Map;for(const N of s)p.set(N.runId,N.title),p.set(N.id,N.title);return p},[s]),Kn=o.useMemo(()=>{const p=new Map;for(const N of s)N.status&&(p.set(N.runId,N.status),p.set(N.id,N.status));return p},[s]),kn=o.useMemo(()=>{var N;const p=new Map;for(const I of s){const $={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};p.set(I.runId,$),p.set(I.id,$)}return p},[s]),Gn=o.useMemo(()=>{const p=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:os(N.updatedAt??N.lastEventAt??N.startedAt??null)},$=[N.runId,N.sliceRunId].filter(ke=>typeof ke=="string"&&ke.trim().length>0).map(ke=>ke.trim());for(const ke of $){const Je=p.get(ke);(!Je||I.updatedEpoch>=Je.updatedEpoch)&&p.set(ke,I)}}return p},[r]),Xn=o.useMemo(()=>{const p=new Map;for(const N of s){const I=_l(N.progress);I!==null&&(p.set(N.runId,I),p.set(N.id,I))}return p},[s]),tn=o.useMemo(()=>{const p=new Map;for(const N of s)!N.agentId||!N.agentName||p.set(N.agentId,N.agentName);return p},[s]),En=o.useMemo(()=>{const p=new Map;for(const N of s){const I=N.workstreamId??null;p.set(N.runId,I),p.set(N.id,I)}return p},[s]),Et=o.useMemo(()=>{const p=new Map;for(const N of i)p.set(N.id,N.name);return p},[i]),Rn=o.useMemo(()=>{const p=new Map;for(const N of i)for(const I of N.workstreams??[])p.set(I.id,I.name);return p},[i]);o.useMemo(()=>{const p=[...s];return p.sort((N,I)=>{const $=os(N.updatedAt??N.lastEventAt??N.startedAt??null);return os(I.updatedAt??I.lastEventAt??I.startedAt??null)-$}),p},[s]);const Gt=o.useMemo(()=>t.map(p=>{const N=ia(p),I=Xp(p),$=Nt(p),ke=N?kn.get(N)??null:null,Je=N?Gn.get(N)??null:null,tt=Jm({sessionStatus:(ke==null?void 0:ke.status)??(N?Kn.get(N)??null:null),sessionPhase:(ke==null?void 0:ke.phase)??null,sessionState:(ke==null?void 0:ke.state)??null,sliceStatus:(Je==null?void 0:Je.status)??null,activityType:p.type,activityStatus:dt($,["status","state","phase","lifecycle_state","lifecycleState","parsed_status","parsedStatus","run_status","runStatus"]),stopReason:dt($,["stop_reason","stopReason"]),decisionRequired:p.decisionRequired??!1,blockingDecisionCount:Vs($,["blocking_decisions","blockingDecisions","blocking_decision_count","blockingDecisionCount"])??(Je==null?void 0:Je.blockingDecisions)??0,nonBlockingDecisionCount:Vs($,["non_blocking_decisions","nonBlockingDecisions","decision_count","decisionCount","decisions"])??(Je==null?void 0:Je.nonBlockingDecisions)??0,blockerCount:(ke==null?void 0:ke.blockerCount)??0,blockerReason:(ke==null?void 0:ke.blockerReason)??null}),vt=Yp(I,tt),hn=[p.title,p.description,p.summary,p.agentName,qp($)].filter(Vt=>typeof Vt=="string"&&Vt.length>0).join(" ").toLowerCase(),xt=$==null?void 0:$.scope,ut=xt==="milestone"||xt==="workstream"?xt:void 0;return{item:p,bucket:I,userState:vt.state,userStateWhy:vt.why,canonicalProjection:tt,runId:N,timestampEpoch:os(p.timestamp),searchText:hn,scopeGroupId:ut?N??null:null,scope:ut}}),[t,kn,Kn,Gn]),Qn=o.useMemo(()=>{let p=0;for(const N of Gt)p=Math.max(p,N.timestampEpoch);return p<=0?!1:Date.now()-p<6e4},[Gt]),Ht=o.useMemo(()=>new Set(c.filter(p=>p&&p.trim().length>0)),[c]),C=Ht.size>0,me=o.useMemo(()=>yr.filter(p=>["live","24h","7d","all"].includes(p.id)),[]),G=o.useMemo(()=>{if(!C)return null;for(const p of Ht){const N=s.find(I=>I.runId===p||I.id===p);if(N)return N}return null},[C,Ht,s]),Fe=o.useMemo(()=>C?G!=null&&G.runtimeProvider?{id:Bp(G.runtimeProvider)}:as(G==null?void 0:G.agentId,G==null?void 0:G.agentName,G==null?void 0:G.title,G==null?void 0:G.lastEventSummary,G==null?void 0:G.runtimeClient,l):as(),[G,C,l]),gt=o.useMemo(()=>g?as(g):as(),[g]),{filtered:it,filteredTotal:Xe,hiddenCount:Jn,hiddenSyncCount:mn}=o.useMemo(()=>{const p=[];let N=0,I=0;const $=new Set,ke=je.trim().toLowerCase();for(const xt of Gt){const ut=xt.runId;if(C&&(!ut||!Ht.has(ut)))continue;if(d){const gn=mr(xt.item),Os=ut?En.get(ut)??null:null;if((gn??Os)!==d)continue}const Vt=hr(xt.item);if(g&&Vt.agentName!==g)continue;const bs=Ui(xt.item);if(bs){if($.has(bs)){I+=1;continue}if($.add(bs),!P){I+=1;continue}}else if(!P&&gr(xt.item)){I+=1;continue}if(!(R==="completed"&&xt.userState!=="completed")&&!(R==="needs_attention"&&xt.userState!=="needs_input"&&xt.userState!=="issue")&&!(R==="in_progress"&&xt.userState!=="in_progress")){if(ke.length>0){const gn=ut?Ut.get(ut)??ut:"";if(!`${xt.searchText} ${gn.toLowerCase()}`.includes(ke))continue}p.length<No?p.push(xt):N+=1}}const Je=[...p].sort((xt,ut)=>{const Vt=ut.timestampEpoch-xt.timestampEpoch;return U==="newest"?Vt:-Vt}),tt=Math.min(Math.max(1,Math.min(jo,q)),Je.length),vt=Je.slice(0,tt),hn=Je.length+N;return{filtered:vt,filteredTotal:hn,hiddenCount:Math.max(0,hn-vt.length),hiddenSyncCount:I}},[R,g,Gt,C,je,Ut,q,d,Ht,En,P,U]),Ms=o.useMemo(()=>{const p=new Map;for(const I of it){const $=Qp(I.item.timestamp),ke=p.get($);ke?ke.push(I):p.set($,[I])}return Array.from(p.keys()).sort((I,$)=>{const ke=Number($)-Number(I);return U==="newest"?ke:-ke}).map(I=>({key:I,label:Jp(I),items:p.get(I)??[]}))},[it,U]),jt=o.useMemo(()=>Ms.map(p=>{const N=new Map;for(const I of p.items){const $=oi(I.item).title.trim().toLowerCase(),ke=Ui(I.item),Je=ke?`${I.item.type}::sync::${ke}`:`${I.item.type}::${$}`,tt=N.get(Je);tt?(tt.count+=1,tt.firstTimestamp=Math.min(tt.firstTimestamp,I.timestampEpoch),tt.allItems.push(I),I.timestampEpoch>tt.representative.timestampEpoch&&(tt.representative=I)):N.set(Je,{key:Je,representative:I,count:1,firstTimestamp:I.timestampEpoch,allItems:[I]})}return{...p,clusters:Array.from(N.values())}}),[Ms]),pn=o.useCallback(p=>{pe(N=>{const I=new Set(N);return I.has(p)?I.delete(p):I.add(p),I}),O(N=>{if(Object.prototype.hasOwnProperty.call(N,p)){const I={...N};return delete I[p],I}return{...N,[p]:ur}})},[]),Pn=o.useCallback((p,N)=>{O(I=>{const $=I[p]??ur,ke=Math.min(N,$+ur);return ke===$?I:{...I,[p]:ke}})},[]),ps=o.useCallback(()=>{!k||!w||!Tt||!Bt||Bt.getTime()<Tt.getTime()||(k({startIso:Tt.toISOString(),endIso:Bt.toISOString()}),w("custom"),T(!1))},[Bt,Tt,k,w]),Ln=o.useCallback(()=>{It(null),Wt(null),k==null||k({startIso:null,endIso:null}),y==="custom"&&(w==null||w("live"))},[k,w,y]),Yn=o.useMemo(()=>Math.min(jo,Math.min(No,Xe)),[Xe]);o.useEffect(()=>{re($i),pe(new Set),O({})},[R,g,C,je,d,P,U,y]),o.useEffect(()=>{if(!Re)return;const p=I=>{var ke;const $=I.target;$ instanceof Node&&((ke=Mn.current)!=null&&ke.contains($)||qe(!1))},N=I=>{I.key==="Escape"&&qe(!1)};return window.addEventListener("pointerdown",p),window.addEventListener("keydown",N),()=>{window.removeEventListener("pointerdown",p),window.removeEventListener("keydown",N)}},[Re]),o.useEffect(()=>{if(!Ce)return;const p=I=>{var ke;const $=I.target;$ instanceof Node&&((ke=us.current)!=null&&ke.contains($)||T(!1))},N=I=>{I.key==="Escape"&&T(!1)};return window.addEventListener("pointerdown",p),window.addEventListener("keydown",N),()=>{window.removeEventListener("pointerdown",p),window.removeEventListener("keydown",N)}},[Ce]);const fn=o.useRef(v);fn.current=v;const At=o.useRef(x);At.current=x;const Dn=o.useRef(j);Dn.current=j;const[jn,Ts]=o.useState(!1),Nn=o.useRef(null),On=o.useRef(y),Zn=o.useRef(Date.now()),Es=o.useRef(!1);o.useEffect(()=>{On.current!==y&&(On.current=y,Nn.current=null,Zn.current=Date.now(),Es.current=!1)},[y]),o.useEffect(()=>{const p=bt.current,N=zt.current;if(!p||!N)return;const I=new IntersectionObserver(ke=>{const Je=ke.some(tt=>tt.isIntersecting);Ts(Je)},{root:p,rootMargin:"0px 0px 600px 0px"});I.observe(N);const $=()=>{Es.current=!0};return p.addEventListener("scroll",$,{passive:!0}),()=>{I.disconnect(),p.removeEventListener("scroll",$)}},[]),o.useEffect(()=>{var p;if(jn){if(it.length<Yn){re(N=>Math.min(Yn,Math.max(N,$i)+Op));return}if(At.current&&!Dn.current){(p=fn.current)==null||p.call(fn);return}}},[it.length,Yn,jn]),o.useEffect(()=>{if(!jn||x||j||!w||!Es.current||Date.now()-Zn.current<3e3)return;const N=Ao(y);N&&Nn.current!==N&&(Nn.current=N,w(N))},[x,j,w,jn,y]);const $n=o.useMemo(()=>ue?it.findIndex(p=>p.item.id===ue):-1,[ue,it]),D=$n>=0?it[$n]:null,wr=o.useMemo(()=>{var N;const p=new Map;for(const I of a){const $=(N=I==null?void 0:I.sliceRunId)==null?void 0:N.trim();!$||p.has($)||p.set($,I)}return p},[a]),Rt=o.useMemo(()=>{if(!D)return null;const p=D.runId??ia(D.item);return p?wr.get(p)??null:null},[D,wr]),In=o.useMemo(()=>Al((D==null?void 0:D.item)??null),[D]),Rs=o.useMemo(()=>Oi((D==null?void 0:D.item)??null),[D]),Js=o.useMemo(()=>Il((D==null?void 0:D.item)??null),[D]),fs=o.useMemo(()=>Js?null:pf((D==null?void 0:D.item)??null,t),[Js,D,t]),Be=o.useMemo(()=>D?To(D.item):null,[D]),Xt=o.useMemo(()=>Be?Be.executor??Be.requester:null,[Be]),ae=Js??(fs==null?void 0:fs.detail)??null,hs=o.useMemo(()=>{var p,N;return Wi((ae==null?void 0:ae.requesterAgentName)??((p=Be==null?void 0:Be.requester)==null?void 0:p.name)??null,(ae==null?void 0:ae.requesterAgentId)??((N=Be==null?void 0:Be.requester)==null?void 0:N.id)??null,tn)},[ae,Be,tn]),es=o.useMemo(()=>Hp(hs),[hs]),ts=o.useMemo(()=>{var N,I;const p=Wi((ae==null?void 0:ae.agentName)??((N=Be==null?void 0:Be.executor)==null?void 0:N.name)??null,(ae==null?void 0:ae.agentId)??((I=Be==null?void 0:Be.executor)==null?void 0:I.id)??null,tn);return p==="—"?(Be==null?void 0:Be.primaryLabel)??"Codex":p},[ae,Be,tn]),Ys=o.useMemo(()=>D!=null&&D.runId?Xn.get(D.runId)??null:null,[D,Xn]),Yt=o.useMemo(()=>gf(ae,Ys),[ae,Ys]),L=o.useMemo(()=>{const p=ae;if(!p)return null;const N=p.initiativeId??(D==null?void 0:D.item.initiativeId)??null,I=N?i.find(gn=>gn.id===N)??null:null,$=p.initiativeTitle??(I==null?void 0:I.name)??null,ke=p.initiativeStatus??(I==null?void 0:I.status)??null,Je=(I==null?void 0:I.workstreams)??[],tt=Je.length>0?Je.length:null,vt=tt!==null?Je.filter(gn=>mi(gn.status)).length:null,hn=tt&&vt!==null?Math.round(vt/tt*100):null,xt=p.workstreamId??null,ut=xt&&Je.length>0?Je.find(gn=>gn.id===xt)??null:null,Vt=p.workstreamTitle??(ut==null?void 0:ut.name)??(xt?Rn.get(xt)??null:null),bs=p.workstreamStatus??(ut==null?void 0:ut.status)??null;return{initiativeId:N,initiativeTitle:$,initiativeStatus:ke,totalInitiativeWorkstreams:tt,doneInitiativeWorkstreams:vt,initiativeWorkstreamPct:hn,workstreamId:xt,workstreamTitle:Vt,workstreamStatus:bs,taskTitle:p.taskTitle,milestoneTitle:p.milestoneTitle,scopedTaskCount:p.taskIds.length,scopedMilestoneCount:p.milestoneIds.length,statusUpdatesApplied:p.statusUpdatesApplied,statusUpdatesBuffered:p.statusUpdatesBuffered,artifacts:p.artifacts,decisions:p.decisions,blockingDecisions:p.blockingDecisions,nonBlockingDecisions:p.nonBlockingDecisions,tokensUsed:p.tokensUsed,tokenBudget:p.tokenBudget,nextStep:p.nextStep,phase:p.phase,stopReason:p.stopReason,parsedStatus:p.parsedStatus}},[ae,D,i,Rn]),mt=o.useMemo(()=>D?xf(D.item,ae,L?{decisions:L.decisions,blockingDecisions:L.blockingDecisions,nonBlockingDecisions:L.nonBlockingDecisions,stopReason:L.stopReason,parsedStatus:L.parsedStatus}:null,D.canonicalProjection??null):null,[ae,D,L]),vr=o.useMemo(()=>{if(!L)return[];const p=[];mt&&p.push({label:"Status",value:mt.label}),L.scopedTaskCount>0&&p.push({label:"Tasks",value:L.scopedTaskCount}),L.scopedMilestoneCount>0&&p.push({label:"Milestones",value:L.scopedMilestoneCount});const N=L.artifacts??0;N>0&&p.push({label:"Artifacts",value:N});const I=L.decisions??0;I>0&&p.push({label:"Decisions",value:I}),L.blockingDecisions&&L.blockingDecisions>0&&p.push({label:"Blocking",value:L.blockingDecisions,tone:"critical"}),L.stopReason&&p.push({label:"Stop reason",value:nr(L.stopReason)??lt(L.stopReason)});const $=Xl(L.tokensUsed,L.tokenBudget);return $&&p.push({label:"Token usage",value:$}),p},[L,mt]),Ls=o.useMemo(()=>{const p=new Set;for(const N of uf((D==null?void 0:D.item)??null))p.add(N);for(const N of(ae==null?void 0:ae.decisionIds)??[])p.add(N);for(const N of(ae==null?void 0:ae.blockingDecisionIds)??[])p.add(N);for(const N of(ae==null?void 0:ae.nonBlockingDecisionIds)??[])p.add(N);return Array.from(p)},[ae,D]),pi=o.useMemo(()=>oe?Ls.length>0||(D==null?void 0:D.item.decisionRequired)===!0||((L==null?void 0:L.blockingDecisions)??0)>0?!0:(mt==null?void 0:mt.label)==="Needs decision":!1,[Ls,D,L,mt,oe]),kr=o.useMemo(()=>Yt?Yt.tone==="positive"?E.lime:Yt.tone==="warning"?E.amber:Yt.tone==="critical"?E.red:E.teal:E.teal,[Yt]),jr=(Yt==null?void 0:Yt.terminalStop)===!0,at=o.useMemo(()=>tf(Nt((D==null?void 0:D.item)??null)),[D]),Zs=o.useMemo(()=>Nt((D==null?void 0:D.item)??null),[D]),pt=o.useMemo(()=>af((D==null?void 0:D.item)??null,ae),[ae,D]),gs=o.useMemo(()=>{if(!(pt!=null&&pt.retryAt))return null;const p=new Date(pt.retryAt);if(!Number.isFinite(p.getTime()))return null;const N=p.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),I=_t(pt.retryAt);return I?`${N} (${I})`:N},[pt]),er=o.useMemo(()=>D?hr(D.item):{agentId:null,agentName:null},[D]),Ds=o.useMemo(()=>Ro(_s(D==null?void 0:D.item.metadata)??void 0),[D]);o.useMemo(()=>Ro(Zs),[Zs]);const ns=o.useMemo(()=>{const p=Sl((D==null?void 0:D.item)??null);return p.length>0?p:mf((D==null?void 0:D.item)??null,t,new Set)},[D,t]),nn=o.useMemo(()=>ns.filter((p,N,I)=>I.findIndex($=>$.path===p.path)===N),[ns]),m=o.useMemo(()=>nn.slice(0,4),[nn]),A=o.useMemo(()=>nn.slice(4),[nn]),F=o.useMemo(()=>{if(nn.length===0)return null;const p=nn[0];return p?zi(p.path):null},[nn]),S=o.useMemo(()=>{const p=Mt(ge);if(p)return p;const N=Lo((D==null?void 0:D.item)??null);return N||(Mt(D==null?void 0:D.item.summary)??Mt(D==null?void 0:D.item.description))},[ge,D]),X=o.useMemo(()=>D?gr(D.item):!1,[D]),xe=o.useMemo(()=>{if(!ae||!D)return null;const p=ae.initiativeId??D.item.initiativeId??null,N=ae.workstreamId??mr(D.item);if(!p||!N)return null;const I=_n((L==null?void 0:L.parsedStatus)??ae.parsedStatus),$=_n((L==null?void 0:L.stopReason)??ae.stopReason),ke=Math.max(0,(L==null?void 0:L.blockingDecisions)??ae.blockingDecisions??(D.item.decisionRequired?1:0)),Je=Math.max(0,(L==null?void 0:L.nonBlockingDecisions)??ae.nonBlockingDecisions??0),tt=I==="blocked"||I==="error"||I==="failed"||$==="blocked"||$==="error"||D.item.type==="blocker_created",vt=!tt&&ke===0&&Je>0&&(I==="needs_decision"||I==="completed"||$==="completed");return!tt&&!vt?null:{initiativeId:p,workstreamId:N,runId:D.runId??null,event:ae.event,requestedByAgentId:ae.requesterAgentId??D.item.requesterAgentId??null,requestedByAgentName:ae.requesterAgentName??D.item.requesterAgentName??null,actionLabel:tt?"Auto-fix in 10s":"Auto-continue in 10s",helperText:tt?"Pause this workstream within 10 seconds to cancel the auto-fix.":"Optional decision captured. Slice will continue automatically after the grace window.",isBlockedFlow:tt}},[ae,D,L]),Qe=o.useCallback(()=>{_e(null)},[]),Ue=o.useCallback(async(p,N)=>{if(N){ct(null),Se(p);try{await N()}catch(I){ct(I instanceof Error?I.message:"Action failed")}finally{Se(I=>I===p?null:I)}}},[]),et=o.useCallback(async()=>{var p;if(!(!xe||ze)){Ct(!0),kt(null);try{const N=await fetch("/orgx/api/mission-control/activity/auto-fix",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({initiativeId:xe.initiativeId,workstreamId:xe.workstreamId,runId:xe.runId,event:xe.event,requestedByAgentId:xe.requestedByAgentId,requestedByAgentName:xe.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 $=(p=I==null?void 0:I.scheduled)!=null&&p.dueAt?new Date(I.scheduled.dueAt):null,ke=$&&Number.isFinite($.getTime())?$.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):null;kt(ke?`Scheduled. Auto action starts by ${ke} unless you pause first.`:"Scheduled. Auto action starts in 10s unless you pause first.")}catch(N){const I=N instanceof Error?N.message:"Failed to schedule auto-fix";kt(Cn(I)||I)}finally{Ct(!1)}}},[xe,ze]);o.useEffect(()=>{if(!Ye)return;const p=window.setTimeout(()=>Ge(null),2e3);return()=>window.clearTimeout(p)},[Ye]),o.useEffect(()=>{ct(null)},[R,je,y]),o.useEffect(()=>{if(!K){wn.current=null;return}const p=K.trim();!p||wn.current===p||!t.some(I=>I.id===p)||(wn.current=p,ve(!1),J("all"),te(""),ht(1),_e(p),be==null||be(p))},[t,be,K]);const ot=o.useCallback(async(p,N)=>{if(N)try{await navigator.clipboard.writeText(N),Ge(`${p} copied`)}catch{Ge("Copy failed")}},[]);o.useEffect(()=>{rt("structured"),Ke(!1),Ct(!1),kt(null)},[ue]),o.useEffect(()=>{He(null),B("feed");const p=vf((D==null?void 0:D.item)??null);if(!p||Lt())return;const N=new URLSearchParams({turnId:p.turnId});p.sessionKey&&N.set("sessionKey",p.sessionKey),p.runId&&N.set("run",p.runId);const I=new AbortController;return fetch(`/orgx/api/live/activity/detail?${N.toString()}`,{method:"GET",signal:I.signal}).then(async $=>{var Je;return $.ok?((Je=(await $.json()).detail)==null?void 0:Je.summary)??null:($.status===404&&B("missing"),null)}).then($=>{typeof $=="string"&&$.trim().length>0?(He($),B("local")):B("missing")}).catch($=>{$ instanceof DOMException&&$.name==="AbortError"||B("missing")}),()=>I.abort()},[D]),o.useEffect(()=>{z(null),Ne(null);const p=D==null?void 0:D.item;if(!p||Le)return;const N=(ge??p.summary??p.description??p.title??"").trim();if(!N||Lt())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:p.title??null,type:p.type})}).then(async $=>$.ok?await $.json():(($.status===404||$.status===405)&&De(!0),null)).then($=>{const ke=$==null?void 0:$.headline;typeof ke=="string"&&ke.trim().length>0&&(De(!1),z(ke.trim()),Ne(($==null?void 0:$.source)??null))}).catch($=>{$ instanceof DOMException&&$.name}),()=>I.abort()},[D,ge,Le]);const wt=o.useCallback(p=>{var $;if(it.length===0)return;const I=(($n>=0?$n:0)+p+it.length)%it.length;ht(p),_e((($=it[I])==null?void 0:$.item.id)??null)},[$n,it]);o.useEffect(()=>{ue&&($n>=0||_e(null))},[$n,ue]),o.useEffect(()=>{if(!ue)return;const p=N=>{N.key==="ArrowRight"||N.key.toLowerCase()==="l"?(N.preventDefault(),wt(1)):(N.key==="ArrowLeft"||N.key.toLowerCase()==="h")&&(N.preventDefault(),wt(-1))};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[ue,wt]);const $s=Ht.size===1,xs=$s?[...Ht][0]:null,Fs=xs?s.find(p=>p.runId===xs||p.id===xs)??null:null,ys=o.useMemo(()=>{if(!$s)return[];const p=[],N=new Set;for(const I of Gt){if(!I.runId||!Ht.has(I.runId))continue;const $=Ui(I.item);if($){if(N.has($)||(N.add($),!P))continue}else if(!P&&gr(I.item))continue;p.push(I.item)}return p},[$s,Gt,Ht,P]),wa=!Ee&&it.length<=160,Ps=(p,N,I)=>{const $=p.item,ke=I??$.id,Je=hr($),tt=To($),vt=tt.executor??tt.requester,hn=Wi(Zt((vt==null?void 0:vt.name)??tt.primaryLabel??$.agentName??Je.agentName??null),Zt((vt==null?void 0:vt.id)??$.agentId??Je.agentId??null),tn)||"OrgX",xt=qi(p.userState),ut=U==="newest"&&N<2,Vt=p.runId,bs=Lo($),{title:gn}=oi($),Os=bs??Mt($.summary),Nr=Mt($.description),ka=$o($,Os??Nr??null),ja=$.initiativeId?Et.get($.initiativeId)??lt($.initiativeId):null,fi=mr($)??(Vt?En.get(Vt)??null:null),Na=fi?Rn.get(fi)??lt(fi):null,Ml=[ja,Na].filter(Boolean).join(" > ")||ja||Na||lt($.type),Tl=Bi(p.userState),El=new Date($.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),Rl=_t($.timestamp),Ll=p.bucket==="artifact"?nf($):null;return n.jsx(pp,{renderKey:ke,displayTitle:gn,headline:ka,contextLabel:Ml,detailText:(Os??Nr)!==ka?Os??Nr:null,displayAgentName:hn,railColor:xt,userStateLabel:Tl,userStateWhy:p.userStateWhy,relativeTime:Rl,timeLabel:El,isRecent:ut,enableMotion:wa,onOpen:()=>{ht(1),_e($.id)},ariaLabel:`Open activity details for ${gn||ii($.type)}`,artifactSnippet:Ll},ke)};return n.jsx(_p,{sessions:s,initiatives:i??[],workspaceId:Ie??null,query:je,statusFilter:R,sortOrder:U,timeFilterId:y,customTimeRange:f,snapshot:Te,onRequestRefresh:fe,children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[$s&&ys.length>0?n.jsx(dp,{items:ys,session:Fs,agentName:((va=ys[0])==null?void 0:va.agentName)??null,onBack:b,onOpenItem:p=>{ht(1),_e(p.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:Xe}),Jn>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:["+",Jn," hidden"]}),mn>0&&!P&&n.jsxs("button",{type:"button",onClick:()=>Y(!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:[mn," sync hidden"]}),P&&n.jsx("button",{type:"button",onClick:()=>Y(!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",Qn&&"pulse-soft"),style:{backgroundColor:E.lime},"aria-label":"Live",title:Qn?"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:je,onChange:p=>te(p.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:us,children:[n.jsxs("button",{type:"button",onClick:()=>{T(p=>!p),qe(!1)},"aria-haspopup":"menu","aria-expanded":Ce,className:le("inline-flex h-7 items-center gap-1 rounded-full border px-2.5 text-micro font-semibold transition-colors",Ce?"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",Ce&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(yt,{children:Ce&&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:yr.filter(p=>p.id!=="custom").map(p=>{const N=y===p.id;return n.jsx("button",{type:"button",onClick:()=>{w==null||w(p.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:p.label},p.id)})})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] p-2.5",children:[n.jsx("p",{className:"mb-2 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Custom range"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("label",{className:"block text-micro uppercase tracking-[0.06em] text-secondary",children:"Start"}),$t?n.jsx("input",{type:"datetime-local",step:300,value:Fi(Tt),onChange:p=>It(_o(p.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(Ia,{selected:Tt,onChange:p=>It(p instanceof Date?p:null),selectsStart:!0,startDate:Tt,endDate:Bt,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"}),$t?n.jsx("input",{type:"datetime-local",step:300,min:Fi(Tt),value:Fi(Bt),onChange:p=>Wt(_o(p.target.value)),className:"orgx-datepicker-input w-full rounded-lg border border-white/[0.12] bg-black/30 px-2.5 py-1.5 text-caption text-primary outline-none transition-colors focus:border-lime/35"}):n.jsx(Ia,{selected:Bt,onChange:p=>Wt(p instanceof Date?p:null),selectsEnd:!0,minDate:Tt??void 0,startDate:Tt,endDate:Bt,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:ms?`${Or(Tt)} - ${Or(Bt)}`:"Pick start and end to apply"}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{type:"button",onClick:Ln,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:ps,disabled:!ms,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:[(C||d||g)&&n.jsxs(n.Fragment,{children:[C&&n.jsxs("button",{onClick:b,className:"chip chip-avatar inline-flex min-w-0 items-center","aria-label":"Clear session filter",children:[So(Fe.id)?n.jsx(Gs,{provider:Fe.id,size:"xs"}):n.jsx(Ft,{name:(G==null?void 0:G.agentName)??"OrgX",hint:l??null,size:"xs"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Session",l?`: ${l}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),d&&n.jsxs("button",{onClick:h,className:"chip inline-flex min-w-0 items-center gap-2",style:{borderColor:"rgba(191,255,0,0.28)",color:"#D8FFA1"},"aria-label":"Clear workstream filter",children:[n.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro",children:"↳"}),n.jsxs("span",{className:"min-w-0 truncate",children:["Workstream",u?`: ${u}`:""]}),n.jsx("span",{className:"ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-micro text-secondary",children:"×"})]}),g&&n.jsxs("button",{onClick:_,className:"chip chip-avatar inline-flex min-w-0 items-center",style:{borderColor:"rgba(10,212,196,0.3)",color:"#0AD4C4"},"aria-label":"Clear agent filter",children:[So(gt.id)?n.jsx(Gs,{provider:gt.id,size:"xs"}):n.jsx(Ft,{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(Fr).map(p=>{const N=R===p;return n.jsx("button",{type:"button",onClick:()=>J(p),"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:Fr[p]},p)})}),n.jsx("button",{type:"button",onClick:()=>ve(p=>!p),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:Mn,children:[n.jsxs("button",{type:"button",onClick:()=>{qe(p=>!p),T(!1)},"aria-haspopup":"menu","aria-expanded":Re,"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",Re?"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",Re&&"rotate-180"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n.jsx(yt,{children:Re&&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(p=>n.jsx("button",{type:"button",onClick:()=>{se(p.id),qe(!1)},className:le("rounded-lg border px-2 py-1.5 text-caption font-medium transition-colors",U===p.id?"border-lime/30 bg-lime/[0.12] text-[#E1FFB2]":"border-white/[0.08] bg-white/[0.02] text-secondary hover:bg-white/[0.06] hover:text-primary"),children:p.label},p.id))})]}),n.jsxs("div",{className:"rounded-lg border border-white/[0.08] bg-white/[0.02] px-2.5 py-2",children:[n.jsx("p",{className:"text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Time window"}),n.jsx("p",{className:"mt-1 text-caption text-secondary",children:"Use the time dropdown beside Activity count for presets and custom date/time ranges."})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Status"}),n.jsx("div",{className:"grid grid-cols-2 gap-1",children:Object.keys(Fr).map(p=>{const N=R===p;return n.jsx("button",{type:"button",onClick:()=>{J(p),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:Fr[p]},p)})})]}),n.jsxs("div",{children:[n.jsx("p",{className:"mb-1 text-micro font-semibold uppercase tracking-[0.08em] text-muted",children:"Signal"}),n.jsx("button",{type:"button",onClick:()=>{Y(p=>!p)},className: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:bt,className:"flex-1 overflow-y-auto overscroll-y-contain scroll-smooth px-4 py-3 pb-24",children:[it.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(ui,{icon:"activity",headline:ee?"Syncing activity feed...":C?"No activity yet for this session":d?"No activity yet for this workstream":"No matching activity right now.",description:ee?"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:me.map(p=>{const N=y===p.id;return n.jsx("button",{type:"button",onClick:()=>w==null?void 0:w(p.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:p.label},`empty-time-${p.id}`)})}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(C||d||g)&&n.jsx("button",{type:"button",onClick:()=>{C&&b(),d&&(h==null||h()),g&&(_==null||_())},className:"rounded-full border border-strong bg-white/[0.03] px-3 py-1.5 text-caption font-semibold text-primary transition hover:bg-white/[0.08]",children:"Clear filters"}),H&&n.jsx("button",{type:"button",onClick:()=>void Ue("play",H),disabled:Oe!==null,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18 disabled:opacity-45",children:Oe==="play"?"Starting...":"Start next session"}),!H&&we&&n.jsx("button",{type:"button",onClick:we,className:"rounded-full border border-[#BFFF00]/28 bg-[#BFFF00]/12 px-3 py-1.5 text-caption font-semibold text-[#D8FFA1] transition hover:bg-[#BFFF00]/18",children:"Browse initiatives"})]}),Ve&&n.jsx("p",{className:"mt-2 text-caption text-amber-200/80",children:Ve})]})}),n.jsx(up,{completedCount:en.completed,decisionsCount:en.decisions,blockerCount:en.blocked,visible:Jt,onDismiss:()=>{Kt(!1),cn.current=Date.now()}}),it.length>0&&n.jsxs("div",{className:"space-y-4",children:[jt.map(p=>{const N=ie?p.clusters.slice(0,4):p.clusters;return n.jsxs("section",{children:[n.jsx("h3",{className:"mb-2.5 border-b border-subtle pb-1.5 text-caption font-semibold tracking-[0.01em] text-muted",children:p.label}),wa?n.jsx(yt,{mode:"popLayout",children:n.jsx("div",{className:"space-y-2",children:N.map((I,$)=>{const ke=Me.has(I.key),Je=I.allItems.slice(1),tt=Je.length,vt=Math.min(tt,M[I.key]??ur),hn=Je.slice(0,vt);if(I.count===1)return Ps(I.representative,$);const xt=`cluster:${I.key}`;return n.jsxs("div",{children:[Ps(I.representative,$,xt),n.jsxs("button",{type:"button",onClick:ut=>{ut.stopPropagation(),pn(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:ke?"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",ke?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ke&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[hn.map((ut,Vt)=>Ps(ut,$+Vt+1)),vt<tt&&n.jsxs("button",{type:"button",onClick:ut=>{ut.stopPropagation(),Pn(I.key,tt)},className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:["Load more (",tt-vt," remaining)"]})]})]},I.key)})})}):n.jsx("div",{className:"space-y-2",children:N.map((I,$)=>{const ke=Me.has(I.key),Je=I.allItems.slice(1),tt=Je.length,vt=Math.min(tt,M[I.key]??ur),hn=Je.slice(0,vt);if(I.count===1)return Ps(I.representative,$);const xt=`cluster:${I.key}`;return n.jsxs("div",{children:[Ps(I.representative,$,xt),n.jsxs("button",{type:"button",onClick:ut=>{ut.stopPropagation(),pn(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:ke?"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",ke?"rotate-0":"-rotate-90"),children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),ke&&n.jsxs("div",{className:"ml-8 mt-1 space-y-1.5 border-l border-subtle pl-3",children:[hn.map((ut,Vt)=>Ps(ut,$+Vt+1)),vt<tt&&n.jsxs("button",{type:"button",onClick:ut=>{ut.stopPropagation(),Pn(I.key,tt)},className:"rounded-full border border-strong bg-white/[0.03] px-2.5 py-1 text-micro text-secondary transition-colors hover:bg-white/[0.06] hover:text-primary",children:["Load more (",tt-vt," remaining)"]})]})]},I.key)})}),ie&&p.clusters.length>N.length&&n.jsxs("p",{className:"mt-1.5 text-caption text-muted",children:["+",p.clusters.length-N.length," more"]})]},p.key)}),n.jsx("div",{ref:zt,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":x?"opacity-0":"opacity-0 pointer-events-none"),children:n.jsx("div",{className:"flex items-center gap-2.5",children:n.jsxs("div",{className:"flex gap-1","aria-label":"Loading older events",children:[n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/70 animate-[pulse_1.4s_ease-in-out_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/50 animate-[pulse_1.4s_ease-in-out_0.2s_infinite]"}),n.jsx("span",{className:"h-1 w-1 rounded-full bg-[#BFFF00]/30 animate-[pulse_1.4s_ease-in-out_0.4s_infinite]"})]})})}),!x&&!j&&it.length>0&&!Ao(y)&&n.jsx("p",{className:"pb-4 text-center text-micro tracking-wide text-muted/50",children:Jn>0?`${it.length} of ${Xe} events`:"You’ve reached the beginning"})]})]})]}),n.jsx(Pp,{}),n.jsx(fp,{open:D!==null,onClose:Qe,children:D&&n.jsxs("div",{className:"relative flex h-[100dvh] w-full min-h-0 flex-col sm:h-[86vh] sm:max-h-[86vh]",children:[n.jsx("div",{className:"absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-lime/10 via-cyan/5 to-transparent"}),n.jsxs("div",{className:"relative z-10 flex items-center justify-between border-b border-subtle px-5 py-3 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"h-2.5 w-2.5 flex-shrink-0 rounded-full",style:{backgroundColor:qi(D.userState),boxShadow:`0 0 12px ${qi(D.userState)}55`}}),n.jsxs("span",{className:"text-caption text-secondary",children:[Bi(D.userState)," · ",$n+1,"/",it.length]}),Ye&&n.jsx(An,{tone:"neutral",className:"text-micro font-semibold tracking-[0.02em]",children:Ye})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[D.runId&&V&&n.jsx("button",{type:"button",onClick:()=>{V(D.runId),Qe()},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:()=>wt(-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:()=>wt(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:()=>Ke(p=>!p),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.04] text-secondary transition hover:bg-white/[0.1] hover:text-primary","aria-label":"More actions",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[n.jsx("circle",{cx:"12",cy:"5",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"12",r:"1.5"}),n.jsx("circle",{cx:"12",cy:"19",r:"1.5"})]})}),$e&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30",onClick:()=>Ke(!1)}),n.jsxs("div",{className:"absolute right-0 top-full z-40 mt-1 min-w-[160px] rounded-lg border border-strong bg-[#0d0f16] py-1 shadow-xl",children:[D.runId&&n.jsx("button",{type:"button",onClick:()=>{ot("Run id",D.runId??""),Ke(!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"}),er.agentId&&n.jsx("button",{type:"button",onClick:()=>{ot("Agent id",er.agentId??""),Ke(!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:()=>{ot("Event id",D.item.id),Ke(!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:Qe,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:We,children:n.jsx(he.section,{custom:We,initial:{opacity:0,x:We*44,scale:.985},animate:{opacity:1,x:0,scale:1},exit:{opacity:0,x:We*-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||$o(D.item,ge)||lt(D.item.title||ii(D.item.type))}),n.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 text-body text-secondary",children:[new Date(D.item.timestamp).toLocaleString()," · ",_t(D.item.timestamp),Q==="llm"&&n.jsx("span",{className:"text-muted",children:"· AI title"})]}),n.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-caption",children:[(()=>{const p=(ae==null?void 0:ae.workstreamId)??mr(D.item)??(D.runId?En.get(D.runId)??null:null),N=p?Rn.get(p)??lt(p):null,$=[(ae==null?void 0:ae.initiativeTitle)??(D.item.initiativeId?Et.get(D.item.initiativeId)??null:null),N].filter(Boolean).join(" > ");return $?n.jsx(An,{tone:"muted",className:"max-w-full",children:n.jsx("span",{className:"truncate",children:$})}):null})(),n.jsx(An,{tone:"neutral",className:"font-semibold tracking-[0.02em]",children:Bi(D.userState)}),n.jsxs(An,{tone:"muted",children:[n.jsx(Ft,{name:(Xt==null?void 0:Xt.label)??(Be==null?void 0:Be.primaryLabel)??"OrgX",hint:Xt?Pi(Xt):(Be==null?void 0:Be.primaryLabel)??"OrgX",size:"xs"}),n.jsx("span",{children:(Xt==null?void 0:Xt.label)??(Be==null?void 0:Be.primaryLabel)??"OrgX"})]}),X&&n.jsx(An,{tone:"lime",children:"Sync replay"})]})]}),n.jsx(xp,{item:D.item}),In&&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:In.source==="metadata"?"Artifact":lt(In.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:()=>rt("structured"),"aria-pressed":st==="structured",className:`rounded-full px-2.5 py-0.5 transition-colors ${st==="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:()=>rt("json"),"aria-pressed":st==="json",className:`rounded-full px-2.5 py-0.5 transition-colors ${st==="json"?"bg-cyan-500/[0.25] text-cyan-100":"text-cyan-300/50 hover:text-cyan-200"}`,children:"JSON"})]}),Rs&&n.jsx("button",{type:"button",onClick:()=>ne(Rs),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:st==="structured"?Cl(In.value):n.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap font-mono text-caption leading-relaxed text-primary",children:JSON.stringify(In.value,null,2)})})})]}),mt&&n.jsxs("div",{className:le("rounded-xl border px-3.5 py-3",mt.tone==="critical"&&"border-red-400/28 bg-red-500/[0.09]",mt.tone==="warning"&&"border-amber-400/28 bg-amber-500/[0.09]",mt.tone==="positive"&&"border-lime/28 bg-lime/[0.08]",mt.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:mt.label}),n.jsx("p",{className:"mt-1 text-body text-primary",children:mt.summary}),mt.hint&&n.jsx("p",{className:"mt-1 text-caption text-secondary",children:mt.hint}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[D.runId&&V&&n.jsx("button",{type:"button",onClick:()=>{V(D.runId),Qe()},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"}),pi&&n.jsx("button",{type:"button",onClick:()=>{oe==null||oe(Ls[0]??null),Qe()},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:Ls.length>0?"Resolve decision":"Resolve decisions"}),Rs&&!In&&n.jsx("button",{type:"button",onClick:()=>ne(Rs),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"}),F&&n.jsx("a",{href:F,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"}),xe&&n.jsx("button",{type:"button",onClick:()=>void et(),disabled:ze,className:le("rounded-full border px-3 py-1 text-caption font-semibold transition disabled:opacity-50",xe.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...":xe.actionLabel})]}),xe&&n.jsx("p",{className:"mt-2 text-caption text-secondary",children:Ze??xe.helperText})]}),pt&&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(An,{tone:pt.isRateLimited?"muted":"red",children:pt.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:pt.domainCurrent!==null&&pt.domainMax!==null?`${pt.domainCurrent}/${pt.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:pt.totalCurrent!==null&&pt.totalMax!==null?`${pt.totalCurrent}/${pt.totalMax} per hour`:"Not provided"})]})]}),n.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-caption text-secondary",children:[pt.domain&&n.jsxs(An,{tone:"muted",children:["Domain: ",lt(pt.domain)]}),pt.modelTier&&n.jsxs(An,{tone:"muted",children:["Tier: ",lt(pt.modelTier)]}),gs&&n.jsxs(An,{tone:"muted",children:["Retry: ",gs]}),!gs&&pt.retryInMs!==null&&n.jsxs(An,{tone:"muted",children:["Retry in ~",Math.max(1,Math.round(pt.retryInMs/1e3)),"s"]})]}),pt.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:Mt(pt.blockedReason)??pt.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"}),xe&&n.jsx("button",{type:"button",onClick:()=>void et(),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"})]})]}),vr.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:vr.map(p=>n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:p.label}),n.jsx("div",{className:`mt-0.5 break-words tabular-nums ${p.tone==="critical"?"text-red-300":"text-primary"}`,children:p.value})]},p.label))})]}),Be&&!ae&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Delegation"}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-body text-secondary",children:[n.jsx("span",{className:"flex items-center gap-1.5",children:Be.requester?n.jsxs(n.Fragment,{children:[n.jsx(Ft,{name:Be.requester.label,hint:Pi(Be.requester),size:"xs"}),n.jsx("span",{className:"text-primary",children:Be.requester.label})]}):n.jsx("span",{children:fr("System / unknown")})}),n.jsx("span",{className:"text-white/[0.15]",children:"→"}),n.jsx("span",{className:"text-primary",children:Be.mode==="handoff"?"Delegated handoff":Be.mode==="requested"?"Dispatch requested":Be.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:Be.executor?n.jsxs(n.Fragment,{children:[n.jsx(Ft,{name:Be.executor.label,hint:Pi(Be.executor),size:"xs"}),n.jsx("span",{className:"text-primary",children:Be.executor.label})]}):n.jsx("span",{children:fr("Not assigned")})})]}),Be.subtitle&&n.jsx("p",{className:"mt-1 text-caption text-muted",children:Be.subtitle})]}),ae&&n.jsxs("div",{className:"space-y-5",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("p",{className:"px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Session"}),n.jsx("span",{className:"rounded-full border border-lime/30 bg-lime/[0.08] px-2 py-0.5 text-micro font-semibold text-lime/85",children:nr(ae.event)??lt(ae.event)})]}),fs&&n.jsxs("p",{className:"mt-1 px-1 text-caption text-muted",children:["Based on related activity (",lt(fs.relation),")."]})]}),Yt&&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:jr?"Terminal state":"Progress"}),n.jsx("p",{className:"text-body font-semibold tabular-nums",style:{color:kr},children:jr?(mt==null?void 0:mt.label)??"Stopped":`${Yt.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,Yt.pct)}%`,backgroundColor:kr}})}),n.jsx("p",{className:"mt-1 text-micro text-muted",children:Yt.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(Ft,{name:es.primary,hint:es.secondary??es.primary,size:"xs"}),n.jsx("span",{children:es.primary})]}),es.secondary&&n.jsxs("p",{className:"mt-0.5 text-micro text-muted",children:["via ",es.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(Ft,{name:ts,hint:ts,size:"xs"}),n.jsx("span",{children:ts})]})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Dispatcher"}),n.jsx("div",{className:"mt-0.5 text-body text-primary",children:ae.dispatcherClient?lt(ae.dispatcherClient):"OrgX"})]}),(ae.domain||ae.requiredSkills.length>0)&&n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Policy"}),n.jsxs("div",{className:"mt-0.5 text-body text-primary",children:[ae.domain??"",ae.requiredSkills.length>0?`${ae.domain?" · ":""}${ae.requiredSkills.join(", ")}`:""]})]})]})]}),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?is(L.initiativeId):"—")})]}),L.initiativeStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:lt(L.initiativeStatus)})]}),n.jsxs("div",{className:"flex items-center justify-between gap-2 py-1",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-micro text-muted",children:"Workstream"}),n.jsx("p",{className:"mt-0.5 text-body text-primary",children:L.workstreamTitle??(L.workstreamId?is(L.workstreamId):"—")})]}),L.workstreamStatus&&n.jsx("span",{className:"flex-shrink-0 text-micro text-muted",children:lt(L.workstreamStatus)})]})]}),L.initiativeWorkstreamPct!==null&&n.jsxs("div",{className:"mt-3",children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between text-micro text-muted",children:[n.jsx("span",{children:"Workstreams complete"}),n.jsxs("span",{className:"tabular-nums",children:[L.doneInitiativeWorkstreams??0,"/",L.totalInitiativeWorkstreams??0]})]}),n.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-white/[0.10]",children:n.jsx("div",{className:"h-full rounded-full bg-[#BFFF00]/80",style:{width:`${Math.max(4,L.initiativeWorkstreamPct)}%`}})})]})]}),((L==null?void 0:L.taskTitle)||(L==null?void 0:L.milestoneTitle)||(L==null?void 0:L.phase)||(L==null?void 0:L.nextStep)||(L==null?void 0:L.parsedStatus)||(L==null?void 0:L.stopReason))&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Current step"}),n.jsxs("div",{className:"space-y-1 text-caption",children:[(L==null?void 0:L.taskTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Task"})," ",n.jsx("span",{className:"text-primary",children:L.taskTitle})]}),(L==null?void 0:L.milestoneTitle)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Milestone"})," ",n.jsx("span",{className:"text-primary",children:L.milestoneTitle})]}),(L==null?void 0:L.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Phase"})," ",n.jsx("span",{className:"text-primary",children:nr(L.phase)??lt(L.phase)})]}),(L==null?void 0:L.nextStep)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Next step"})," ",n.jsx("span",{className:"text-primary",children:L.nextStep})]}),(L==null?void 0:L.parsedStatus)&&L.parsedStatus!==(L==null?void 0:L.phase)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Status"})," ",n.jsx("span",{className:"text-primary",children:nr(L.parsedStatus)??lt(L.parsedStatus)})]}),(L==null?void 0:L.stopReason)&&L.stopReason!==(L==null?void 0:L.phase)&&L.stopReason!==(L==null?void 0:L.parsedStatus)&&n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Stop reason"})," ",n.jsx("span",{className:"text-primary",children:nr(L.stopReason)??lt(L.stopReason)})]})]})]}),ae.error&&n.jsx("div",{className:"rounded-lg border border-red-400/20 bg-red-500/10 px-4 py-3 text-body text-red-100/80",children:ae.error})]}),S&&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"&&!X&&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(ni,{mode:"block",text:S,className:"text-body leading-relaxed text-primary"})]}),Mt(D.item.description)&&Mt(D.item.description)!==S&&n.jsxs("div",{children:[n.jsx("p",{className:"mb-2 px-1 text-micro font-semibold uppercase tracking-wider text-muted",children:"Details"}),n.jsx(ni,{mode:"block",text:Mt(D.item.description)??"",className:"text-body leading-relaxed text-secondary"})]}),Rt&&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:Rt.intent})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Dispatch"})," ",n.jsx("span",{className:"text-primary",children:Rt.dispatch})]}),Rt.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:Rt.highlights.slice(0,3).map((p,N)=>n.jsx("li",{children:p},`${Rt.sliceRunId}:highlight:${N}`))})]}),n.jsxs("p",{children:[n.jsx("span",{className:"text-muted",children:"Outcome"})," ",n.jsx("span",{className:"text-primary",children:Rt.outcome.summary})]})]})]}),nn.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:[nn.length," ",nn.length===1?"file":"files"," captured for this run."]}),n.jsxs("div",{className:"space-y-2",children:[m.map((p,N)=>{const I=zi(p.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:lt(p.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Is(p.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 ot(`${lt(p.key)} path`,p.path),className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Copy"})]})]},`${p.key}:${p.path}:${N}`)}),A.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 ",A.length," additional evidence file",A.length===1?"":"s"]}),n.jsx("div",{className:"mt-2 space-y-2",children:A.map((p,N)=>{const I=zi(p.path);return n.jsxs("div",{className:"flex items-center justify-between gap-3 py-1",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-micro text-muted",children:lt(p.key)}),n.jsx("p",{className:"mt-0.5 truncate font-mono text-caption text-primary",children:Is(p.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 ot(`${lt(p.key)} path`,p.path),className:"rounded-full border border-strong bg-white/[0.04] px-2.5 py-1 text-caption text-primary transition hover:bg-white/[0.1]",children:"Copy"})]})]},`${p.key}:${p.path}:overflow:${N}`)})})]})]})]}),D&&Oi(D.item)&&!In&&n.jsxs("button",{type:"button",onClick:()=>{const p=Oi(D.item);p&&ne(p)},className:"flex w-full items-center gap-2.5 rounded-xl border border-cyan-400/25 bg-cyan-500/[0.08] px-3.5 py-2.5 text-left transition-colors hover:bg-cyan-500/[0.14]",children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:E.cyan,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"flex-shrink-0",children:[n.jsx("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),n.jsx("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),n.jsx("span",{className:"text-body font-medium",style:{color:E.cyan},children:"View registered artifact"})]}),(at||(ae==null?void 0:ae.logPath)||Ds)&&n.jsx("div",{className:"border-t border-white/[0.06]"}),(at||(ae==null?void 0:ae.logPath)||(ae==null?void 0:ae.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:[at&&n.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 sm:grid-cols-3",children:[at.domain&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Domain"}),n.jsx("div",{className:"mt-0.5 text-primary",children:lt(at.domain)})]}),(at.provider||at.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:[at.provider?`${lt(at.provider)} · `:"",at.model?xr(at.model):"—"]})]}),at.modelTier&&n.jsxs("div",{className:"py-1",children:[n.jsx("div",{className:"text-micro text-muted",children:"Model tier"}),n.jsx("div",{className:"mt-0.5 text-primary",children:lt(at.modelTier)})]}),at.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",at.pluginVersion]})]})]}),(at==null?void 0:at.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:[at.skillPack.name??"—",at.skillPack.version?`@${at.skillPack.version}`:"",at.skillPack.source?` · ${at.skillPack.source}`:""]}),at.skillPack.checksum&&n.jsxs("button",{type:"button",onClick:()=>{var p;return void ot("Skill pack checksum",((p=at.skillPack)==null?void 0:p.checksum)??"")},className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:["sha ",at.skillPack.checksum.slice(0,12)]})]}),at&&at.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"}),at.requiredSkills.map(p=>n.jsx("span",{className:"rounded-full border border-strong bg-white/[0.03] px-2 py-0.5 text-micro text-secondary",children:p},p))]}),(at==null?void 0:at.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:[at.kickoffContextSource?`${at.kickoffContextSource} · `:"",at.kickoffContextHash.slice(0,16)]})]}),n.jsx("button",{type:"button",onClick:()=>void ot("Kickoff context hash",at.kickoffContextHash??""),className:"rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),((ae==null?void 0:ae.logPath)||(ae==null?void 0:ae.outputPath))&&n.jsxs("div",{className:"space-y-1 border-t border-white/[0.06] pt-3",children:[(ae==null?void 0:ae.logPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["log: ",Is(ae.logPath)]}),n.jsx("button",{type:"button",onClick:()=>void ot("Log path",(ae==null?void 0:ae.logPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]}),(ae==null?void 0:ae.outputPath)&&n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsxs("p",{className:"min-w-0 truncate font-mono text-muted",children:["output: ",Is(ae.outputPath)]}),n.jsx("button",{type:"button",onClick:()=>void ot("Output path",(ae==null?void 0:ae.outputPath)??""),className:"flex-shrink-0 rounded-full border border-strong bg-white/[0.04] px-2 py-0.5 text-micro text-muted transition hover:bg-white/[0.1] hover:text-primary",children:"Copy"})]})]}),((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: ",is(L.initiativeId)]}),(L==null?void 0:L.workstreamId)&&n.jsxs("p",{className:"break-all font-mono text-muted",children:["workstream: ",is(L.workstreamId)]})]})]})]}),Ds&&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:Ds})]})]})},D.item.id)})}),n.jsx("div",{className:"border-t border-subtle px-5 py-2.5 text-caption text-muted sm:px-6",children:"Keyboard: ← previous · → next · Esc close"})]})})]})})}),jf=o.lazy(async()=>({default:(await qt(()=>import("./DEip7uko.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]))).MissionControlView})),Nf=o.lazy(async()=>({default:(await qt(()=>import("./CSr2ZnTV.js"),__vite__mapDeps([11,1,2,3,4,12,7]))).SessionInspector})),If=o.lazy(async()=>({default:(await qt(()=>import("./C-PAoJF-.js"),__vite__mapDeps([13,1,2,3,4,9,7,12]))).DecisionQueue})),Af=o.lazy(()=>qt(()=>import("./CL_wXqR7.js"),__vite__mapDeps([14,1,2,3,4,7])).then(e=>({default:e.TriageQueue}))),Sf=o.lazy(()=>qt(()=>import("./BTAEErUY.js"),__vite__mapDeps([15,1,2,3,4,7])).then(e=>({default:e.TriageDetailModal}))),_f=o.lazy(async()=>({default:(await qt(()=>import("./BVShoyjA.js").then(t=>t.a),__vite__mapDeps([5,1,2,3,4,6,7]))).NextUpPanel})),Cf=o.lazy(async()=>({default:(await qt(()=>import("./C0nA-iUG.js"),__vite__mapDeps([16,1,2,3,4,7,10]))).SettingsModal})),Mf=o.lazy(async()=>({default:(await qt(()=>import("./DxKG5zy8.js"),__vite__mapDeps([17,1,2,3,4,7]))).BulkSessionsModal})),Tf=o.lazy(async()=>({default:(await qt(()=>import("./DOFL9l8s.js"),__vite__mapDeps([18,1,2,3,4,13,9,7,12]))).BulkDecisionsModal})),Ef=o.lazy(async()=>({default:(await qt(()=>import("./D7DHFX0D.js"),__vite__mapDeps([19,1,2,3,4,7]))).BulkOutboxModal})),Rf=o.lazy(async()=>({default:(await qt(()=>import("./DpuQm1oF.js"),__vite__mapDeps([20,1,2,3,4,7]))).BulkHandoffsModal})),Lf=o.lazy(async()=>({default:(await qt(()=>import("./CFwPph5U.js"),__vite__mapDeps([21,1,2,3,4,6,7]))).ArtifactViewerModal})),Df=o.lazy(async()=>({default:(await qt(()=>import("./C6GO-FKy.js"),__vite__mapDeps([22,1,2,3,4,9,7,8]))).SliceDetailModal})),$f=o.lazy(async()=>({default:(await qt(()=>import("./BgcAY5rE.js"),__vite__mapDeps([23,1,2,3,4,7]))).RealtimeOrchestratorModal})),Fo={connected:"Live",reconnecting:"Reconnecting",disconnected:"Offline"},Ff={connected:E.lime,reconnecting:E.amber,disconnected:E.red},Hi="orgx.demo_mode",Vi="orgx.dev_mode",Ki="orgx.show_synthetic_entities",aa="orgx.selected_workspace_id",Po={blocked:0,pending:1,queued:2,running:3,failed:4,cancelled:5,completed:6,archived:7},Oo=new Set(["running","active","queued","pending","in_progress","working","planning"]),Pf=/^\s*configure\s+engineering\s+agent(?:\s*[.!?])?\s*$/i;function ln(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Of(e){const t=ln(e);if(!t)return"unknown";try{return new Date(t).toLocaleString()}catch{return"unknown"}}function Bf(e,t=220){const s=e.split("|").map(a=>a.trim()).filter(Boolean).map(a=>a.replace(/^[^:]+:\s*/,"").trim()),i=Array.from(new Set(s.length>0?s:[e.trim()])).slice(0,2).join(" ");return i.length<=t?i:`${i.slice(0,t-1).trimEnd()}…`}function qf(e){const t=e.trim().toLowerCase();return t.includes("timed out")||t.includes("timeout")||t.includes("request cancelled")||t.includes("signal is aborted")?{title:"Live sync delayed",message:"OrgX Live is responding slowly. Initiatives and Next Up may look empty until sync recovers.",action:"refresh"}:t.includes("unauthorized")||t.includes("forbidden")||t.includes("api key")||t.includes("auth")?{title:"OrgX auth required",message:"Reconnect your OrgX API key in Settings to restore live initiatives, activity, and Next Up.",action:"settings"}:t.includes("unknown api endpoint")||t.includes("missing required live routes")||t.includes("runtime is missing required live routes")?{title:"Plugin update required",message:"This runtime is missing required live routes. Restart the plugin and update to the latest build.",action:"settings"}:{title:"Live stream degraded",message:Bf(e),action:"settings"}}function Gi(e){if(e.runId&&e.runId.trim().length>0)return e.runId.trim();if(!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata))return null;const t=e.metadata,s=["runId","run_id","sessionId","session_id","agentRunId"];for(const r of s){const i=t[r];if(typeof i=="string"&&i.trim().length>0)return i.trim()}return null}function zf(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 Bo(e){return!e.metadata||typeof e.metadata!="object"||Array.isArray(e.metadata)?null:e.metadata}function qo(e,t){if(!e)return null;for(const s of t){const r=e[s];if(typeof r=="string"&&r.trim().length>0)return r.trim()}return null}function Xi(e,t){const s=Po[e.status]??99,r=Po[t.status]??99;return s!==r?s-r:ln(e.updatedAt??e.lastEventAt??e.startedAt)-ln(t.updatedAt??t.lastEventAt??t.startedAt)}function zo(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 Wf(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 Uf(e){if(Cs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Hf(e){if(Cs(e.initiativeId))return!0;const t=(e.runId??"").trim().toLowerCase();return!!(/^run-\d+$/.test(t)||t.startsWith("mock-"))}function Vf(e){const t=e.metadata;return t!=null&&typeof t=="object"&&t.mock===!0}function Kf(e){return Pf.test(e)}function zr(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 Gf(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function Xf(e){const t=e.title.trim();return t.length>0?t:e.isDefault?"Default workspace":"Untitled workspace"}function Qf(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 Jf(e,t){ds(e,t)}function Yf(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 Zf(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search),t=Qf(e);if(t)return t}catch{}try{const e=window.localStorage.getItem(aa);if(e&&e.trim().length>0)return e.trim()}catch{}return null}function eh(){const e=id();return e.showGate?n.jsx(Yd,{state:e.state,isLoading:e.isLoading,isStarting:e.isStarting,isSubmittingManual:e.isSubmittingManual,onRefresh:e.refreshStatus,onStartPairing:e.startPairing,onSubmitManualKey:e.submitManualKey,onBackToPairing:e.backToPairing,onUseManualKey:e.setManualMode,onSkip:e.skipGate}):n.jsx(tm,{children:n.jsx(ih,{onboarding:e})})}function th(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 nh(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 Wo(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 Uo(e){const t=(e??"").trim().toLowerCase();return t?!["deleted","archived","cancelled"].includes(t):!0}function sh(){return n.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center rounded-lg border border-strong bg-white/[0.04] p-0.5",children:n.jsx("img",{src:ci,alt:"OrgX",className:"h-full w-full rounded-md object-contain"})})}function rh(){const{state:e}=fl();return e.artifactId?n.jsx(o.Suspense,{fallback:null,children:n.jsx(Lf,{})}):null}function ih({onboarding:e}){const[t,s]=o.useState(()=>{if(typeof window>"u")return!1;if(new URLSearchParams(window.location.search).get("demo")==="1")return!0;try{return window.localStorage.getItem(Hi)==="1"}catch{return!1}}),[r,i]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ki)==="1"}catch{return!1}}),[a,c]=o.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(Vi)==="1"}catch{return!1}}),[l,d]=o.useState(()=>{if(new URLSearchParams(window.location.search).get("view")==="mission-control")return"mission-control";try{if(localStorage.getItem("orgx-dashboard-view")==="mission-control")return"mission-control"}catch{}return"activity"}),[u,g]=o.useState(()=>Zf()),y=o.useCallback(m=>{d(m);try{localStorage.setItem("orgx-dashboard-view",m)}catch{}},[]),{data:w=[]}=cs({queryKey:["workspace-options",t?"demo":"live"],queryFn:async()=>{if(t)return[];const m=await fetch("/orgx/api/entities?type=command_center&limit=50");if(!m.ok)return[];const A=await m.json().catch(()=>null),F=Array.isArray(A==null?void 0:A.data)?A.data:[],S=[];for(const X of F){if(!X||typeof X!="object"||Array.isArray(X))continue;const xe=zr(X,["id"]);if(!xe)continue;const Qe=zr(X,["status","priority"]);if(!Gf(Qe))continue;const Ue=zr(X,["title","name"])??(xe.length>10?`${xe.slice(0,8)}…`:xe),et=X.is_default===!0,ot=Xf({title:Ue,isDefault:et}),wt=zr(X,["created_at"]);S.push({id:xe,title:ot,status:Qe,isDefault:et,createdAt:wt})}return S.sort((X,xe)=>{if(X.isDefault!==xe.isDefault)return X.isDefault?-1:1;const Qe=ln(X.createdAt)-ln(xe.createdAt);return Qe!==0?Qe:X.title.localeCompare(xe.title)}),S},staleTime:6e4}),f=o.useMemo(()=>{var m;return u?((m=w.find(A=>A.id===u))==null?void 0:m.title)??`Workspace ${u.slice(0,8)}`:"All workspaces"},[u,w]),k=o.useMemo(()=>!u||w.some(m=>m.id===u)?w:[{id:u,title:f,status:null,isDefault:!1,createdAt:null},...w],[u,f,w]);o.useEffect(()=>{u&&w.length!==0&&(w.some(m=>m.id===u)||g(null))},[u,w]),t||e.state.hasApiKey&&e.state.connectionVerified;const x=o.useMemo(()=>l==="mission-control"?{maxSessions:240,maxActivityItems:120,maxHandoffs:60,maxDecisions:80,batchWindowMs:140}:{maxSessions:320,maxActivityItems:80,maxHandoffs:80,maxDecisions:80,batchWindowMs:120},[l]),{data:j,isLoading:v,error:b,refetch:h,approveDecision:_,rejectDecision:V,approveAllDecisions:oe,bulkDecisionAction:K,decisionMutation:be}=Ec({useMock:t,enabled:!0,enableDecisions:!0,projectId:u,...x}),H=t||r,Z=o.useMemo(()=>H?j.sessions.nodes:j.sessions.nodes.filter(m=>!Uf(m)),[j.sessions.nodes,H]),ce=o.useMemo(()=>j.activity.filter(m=>!(!H&&Hf(m)||!a&&Vf(m))),[j.activity,H,a]),ye=j.connection==="connected"||j.decisions.length>0,[we,W]=o.useState(null),[Ie,Te]=o.useState(!1),[fe,ee]=o.useState(null),[de,Ee]=o.useState(null),[ne,R]=o.useState(null),[J,P]=o.useState(null),[Y,ie]=o.useState("live"),[ve,je]=o.useState({startIso:null,endIso:null}),te=o.useRef(new Set),[Me,pe]=o.useState(null),[M,O]=o.useState(null),[U,se]=o.useState(null),[Re,qe]=o.useState(null),Ce=o.useRef(null),T=o.useCallback(m=>{Ce.current&&clearTimeout(Ce.current),qe(m),Ce.current=setTimeout(()=>qe(null),4e3)},[]),[q,re]=o.useState(!1),[ue,_e]=o.useState(!1),[Ye,Ge]=o.useState([]),$e=o.useRef(null),Ke=o.useRef(null),[We,ht]=o.useState({open:!1,tab:"orgx",focusAgentDomain:null}),[st,rt]=o.useState(!1),[ge,He]=o.useState(null),[Ae,B]=o.useState("agents"),[Pe,z]=o.useState("initiatives"),[Q,Ne]=o.useState("next_up"),Le=o.useCallback(m=>{if(B(m),m==="initiatives"){z("initiatives"),Ne("next_up");return}m==="decisions"&&(z("initiatives"),Ne("in_progress"),Oe("needs_attention"))},[]),[De,Oe]=o.useState("all"),Se=o.useMemo(()=>Array.isArray(j.sliceRuns)?j.sliceRuns:[],[j.sliceRuns]),ct=o.useMemo(()=>dl({sessions:Z,sliceRuns:Se}),[Se,Z]).length,ze=o.useMemo(()=>ul(Se),[Se]),Ct=ze.length+(ye?j.decisions.length:0),[Ze,kt]=o.useState(null),Jt=o.useCallback(m=>{const A=Se.find(F=>F.initiativeId===m.initiativeId&&F.workstreamId===m.workstreamId)??null;kt({source:"queue",item:m,linkedSliceRun:A})},[Se]),Kt=o.useCallback((m,A)=>{kt({source:"in_progress",row:m,sliceRun:A})},[]),cn=o.useCallback(m=>{kt({source:"needs_input",sliceRun:m})},[]),Mn=o.useCallback(async(m,A)=>{T("Slice accepted and marked complete."),h()},[h,T]),us=o.useCallback(async(m,A)=>{T("Changes requested — feedback posted.")},[T]),bt=vd({projectId:u,authToken:null,embedMode:!1,enabled:!0,snapshotVersion:j.snapshotVersion}),zt=jd({authToken:null,embedMode:!1}),{model:wn,actions:Tt}=Ad({enabled:!0,workspaceId:u,authToken:null,embedMode:!1}),It=o.useMemo(()=>wn.items.filter(m=>m.kind==="failure_diagnostic"),[wn.items]),Bt=o.useMemo(()=>({...wn,items:It,total:It.length}),[It,wn]),[Wt,$t]=o.useState(null),[dn,Vn]=o.useState(0),un=o.useCallback(m=>{$t(m);const A=It.findIndex(F=>F.id===m.id);Vn(A>=0?A:0)},[It]),Tn=o.useCallback(m=>{if(It.length===0)return;const A=(dn+m+It.length)%It.length;Vn(A),$t(It[A]??null)},[dn,It]),ms=bt,vn=o.useMemo(()=>bt.items.find(m=>m.autoIntentEnabled===!0&&(m.autoRuntimeState==="running"||m.autoRuntimeState==="stopping"))??null,[bt.items]),en=!!vn;o.useEffect(()=>{if(!(typeof window>"u"))try{t?window.localStorage.setItem(Hi,"1"):window.localStorage.removeItem(Hi)}catch{}},[t]),o.useEffect(()=>{if(!(typeof window>"u"))try{r?window.localStorage.setItem(Ki,"1"):window.localStorage.removeItem(Ki)}catch{}},[r]),o.useEffect(()=>{if(!(typeof window>"u"))try{a?window.localStorage.setItem(Vi,"1"):window.localStorage.removeItem(Vi)}catch{}},[a]),o.useEffect(()=>{if(!(typeof window>"u")){try{u?window.localStorage.setItem(aa,u):window.localStorage.removeItem(aa)}catch{}try{const m=new URL(window.location.href);u?Jf(m.searchParams,u):Yf(m.searchParams),m.searchParams.delete("initiative"),m.searchParams.delete("initiative_id"),m.searchParams.delete("project"),window.history.replaceState(null,"",`${m.pathname}${m.search}${m.hash}`)}catch{}}},[u]);const Ut=o.useCallback((m,A)=>{ht(F=>({open:!0,tab:m??F.tab,focusAgentDomain:(A==null?void 0:A.focusAgentDomain)??null}))},[]),Kn=o.useCallback(m=>{if(s(m),!(typeof window>"u"))try{const A=new URL(window.location.href);m?A.searchParams.set("demo","1"):A.searchParams.delete("demo"),window.history.replaceState(null,"",`${A.pathname}${A.search}${A.hash}`)}catch{}},[]),kn=o.useCallback(()=>{Ut("orgx")},[Ut]),Gn=o.useCallback(()=>{qt(()=>import("./DEip7uko.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]))},[]),{data:Xn}=ml(l==="mission-control",u),{data:tn}=em(l==="mission-control",u),{data:En=[]}=cs({queryKey:["initiative-tombstones"],queryFn:async()=>[],initialData:[],staleTime:Number.POSITIVE_INFINITY}),[Et,Rn]=o.useState(null),[Gt,Qn]=o.useState(""),[Ht,C]=o.useState(!1),me=o.useCallback((m,A)=>{Rn({type:m,initiativeId:A}),Qn(""),C(!1)},[]),G=o.useCallback(()=>{Rn(null),Qn(""),C(!1)},[]),Fe=o.useCallback(()=>{Ee(null)},[]),gt=o.useCallback(()=>{R(null),P(null)},[]),it=o.useCallback(()=>{se(null)},[]);o.useEffect(()=>{var F;const m=((F=Z[0])==null?void 0:F.id)??null;if(!m){we!==null&&W(null);return}if(we===null){W(m);return}Z.some(S=>S.id===we)||W(m)},[Z,we]),o.useEffect(()=>{if(!de)return;Z.some(A=>A.id===de)||Ee(null)},[de,Z]);const Xe=o.useCallback(m=>{qt(()=>import("./CSr2ZnTV.js"),__vite__mapDeps([11,1,2,3,4,12,7])),W(m),Te(!0),ee(null),Ee(m),R(null),P(null)},[]),Jn=o.useCallback(m=>{qt(()=>import("./CSr2ZnTV.js"),__vite__mapDeps([11,1,2,3,4,12,7])),W(m.id),Te(!0),Ee(m.id),R(m.workstreamId??null),P(m.title),ee({workstreamId:m.workstreamId??null,text:`Intervention requested for "${m.title}". `}),T(`Opened intervention composer for ${m.title}.`)},[]),mn=o.useCallback(m=>{const A=m.trim();if(!A)return;const F=Z.find(S=>S.runId===A||S.id===A)??null;F&&(Xe(F.id),T(`Focused session: ${F.title}`))},[Z,Xe]),Ms=o.useCallback(m=>{var S;const A=(S=m.id)==null?void 0:S.trim();if(!A)return;const F=Gi(m);if(F){const X=Z.find(xe=>xe.runId===F||xe.id===F)??null;X&&(W(X.id),Ee(X.id))}y("activity"),B("activity"),Te(!1),pe(A),T("Opened activity detail from session timeline.")},[Z,y]),jt=o.useMemo(()=>Z.find(m=>m.id===de)??null,[de,Z]),pn=o.useMemo(()=>{var F,S;const m=((F=jt==null?void 0:jt.runId)==null?void 0:F.trim())??"",A=((S=jt==null?void 0:jt.id)==null?void 0:S.trim())??"";return!m||!A?[]:m===A?[m]:[m,A]},[jt==null?void 0:jt.id,jt==null?void 0:jt.runId]),Pn=o.useMemo(()=>{const m=new Set;for(const A of pn){const F=A.trim();F.length>0&&m.add(F)}return m},[pn]),ps=o.useMemo(()=>{const m=new Map;for(const A of Z){const F=A.workstreamId??null;A.runId&&m.set(A.runId,F),A.id&&m.set(A.id,F)}return m},[Z]),Ln=o.useMemo(()=>{const m=pn.length>0?pn.join("|"):"*",A=(ne==null?void 0:ne.trim())||"*",F=(U==null?void 0:U.trim())||"*";return`${m}::${A}::${F}`},[ne,U,pn]),Yn=o.useCallback(m=>{te.current.add(Ln),ie(m)},[Ln]);o.useEffect(()=>{if(te.current.has(Ln)||v)return;const m=Date.now(),A=ce.filter(X=>{const xe=Gi(X);if(Pn.size>0&&(!xe||!Pn.has(xe)))return!1;if(ne){const Qe=Bo(X);if((qo(Qe,["workstreamId","workstream_id"])??(xe?ps.get(xe)??null:null))!==ne)return!1}if(U){const Qe=Bo(X);if((qo(Qe,["agentName","agent_name"])??X.agentName)!==U)return!1}return!0});if(A.length===0)return;const S=["live","24h","7d","all"].find(X=>{const xe=br(X,m);return A.some(Qe=>{const Ue=ln(Qe.timestamp);return Ue?xe===null||Ue>=xe:!1})})??"all";te.current.add(Ln),S!==Y&&ie(S)},[ne,ce,Ln,Y,ps,U,v,Pn]);const fn=Wc({seed:ce,timeFilterId:Y,customSinceIso:Y==="custom"?ve.startIso:null,customUntilIso:Y==="custom"?ve.endIso:null,runId:(jt==null?void 0:jt.runId)??null,projectId:u,pageSize:50,demoMode:t}),At=o.useMemo(()=>Z.find(m=>m.id===we)??null,[Z,we]),Dn=o.useMemo(()=>Z.filter(m=>Oo.has(m.status)).length,[Z]),jn=o.useMemo(()=>Se.length>0?ze.length:Z.filter(m=>{const A=Ot(m.status),F=Ot(m.phase??""),S=Ot(m.state??"");return A==="completed"||A==="cancelled"||A==="archived"?!1:A==="blocked"||A==="failed"||F==="blocked"||S==="error"?!0:Oo.has(A)||A==="handoff"||A==="review"?!1:m.blockers.length>0}).length,[Se.length,ze.length,Z]);o.useMemo(()=>Z.filter(m=>m.status==="failed").length,[Z]);const Ts=o.useMemo(()=>Z.filter(m=>m.status==="completed").length,[Z]);o.useMemo(()=>{const m=(ye?j.decisions.length:0)+jn;return[{id:"active",label:"Running",value:Dn,color:Dn>0?E.lime:E.textMuted,icon:"active"},{id:"attention",label:"Needs attention",value:m,color:m>0?E.amber:E.textMuted,icon:"decision"},{id:"completed",label:"Done today",value:Ts,color:E.teal,icon:"session"}]},[Dn,jn,Ts,j.decisions.length,Z,ye]),o.useMemo(()=>j.decisions.length>0?Math.max(0,...j.decisions.map(m=>m.waitingMinutes)):0,[j.decisions]);const Nn=o.useMemo(()=>b?qf(b):null,[b]),On=o.useMemo(()=>{const m=[];if(Nn){const A=Nn.action==="refresh"&&typeof h=="function";m.push({id:`stream-error:${b}`,kind:"error",icon:"notification",title:Nn.title,message:Nn.message,actionLabel:A?"Refresh":"Settings",onAction:A?()=>void h():()=>Ut("orgx")})}return j.connection!=="connected"&&m.push({id:`connection:${j.connection}`,kind:j.connection==="disconnected"?"error":"info",icon:"notification",title:j.connection==="disconnected"?"Connection lost":"Reconnecting",message:j.connection==="disconnected"?"Live connection is offline. Initiatives and Next Up may stay stale until reconnect.":"Live connection is recovering. Fresh updates will resume automatically.",actionLabel:"Reconnect",onAction:kn}),Re&&m.push({id:`ops:${Re}`,kind:"info",icon:/decision/i.test(Re)?"decision":"workstream",title:"Update",message:Re}),m},[j.connection,j.outbox.lastReplayError,j.outbox.pendingTotal,j.outbox.replayStatus,b,Nn,kn,h,Ut,Re]);o.useEffect(()=>{const m=new Set(On.map(A=>A.id));Ge(A=>A.filter(F=>m.has(F)))},[On]);const Zn=o.useMemo(()=>On.filter(m=>!Ye.includes(m.id)),[Ye,On]),Es=ye?j.decisions.length:0,$n=Dn+jn+Es,D=o.useCallback(m=>{Ge(A=>A.includes(m)?A:A.concat(m))},[]),wr=o.useCallback(()=>{Ge(On.map(m=>m.id))},[On]);o.useEffect(()=>{if(!ue)return;const m=F=>{var X,xe;const S=F.target;S&&((X=Ke.current)!=null&&X.contains(S)||(xe=$e.current)!=null&&xe.contains(S)||_e(!1))},A=F=>{F.key==="Escape"&&_e(!1)};return document.addEventListener("mousedown",m),document.addEventListener("touchstart",m),document.addEventListener("keydown",A),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("touchstart",m),document.removeEventListener("keydown",A)}},[ue]);const Rt=o.useMemo(()=>{var F;const m=new Map;for(const S of Z){const X=S.initiativeId??S.groupId??"unscoped",xe=S.groupLabel&&S.groupLabel.trim().length>0?S.groupLabel:S.initiativeId??"Unscoped Initiative",Qe=th(xe),Ue=m.get(X)??{id:X,name:xe,category:Qe,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 et=j.sessions.groups.find(wt=>wt.id===S.workstreamId),ot=((F=et==null?void 0:et.label)==null?void 0:F.trim())||S.workstreamId;Ue.workstreams.set(S.workstreamId,ot)}Ue.latestEpoch=Math.max(Ue.latestEpoch,ln(S.updatedAt??S.lastEventAt??S.startedAt)),m.set(X,Ue)}const A=[];for(const S of m.values()){const X=S.progressCount>0?Math.round(S.progressTotal/S.progressCount):S.statusCounts.completed?100:S.statusCounts.running?55:0,xe=S.category,Qe=nh(xe),Ue=Math.round(Math.max(0,Math.min(100,X))/100*(Qe.length-1)),et=(S.statusCounts.blocked??0)>0,ot=(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,wt=!ot&&!et&&(S.statusCounts.paused??0)>0&&(S.statusCounts.running??0)===0&&(S.statusCounts.queued??0)===0&&(S.statusCounts.pending??0)===0,$s=Qe.map((xs,Fs)=>{let ys="upcoming";return(ot||Fs<Ue)&&(ys="completed"),Fs===Ue&&!ot&&(ys=et?"warning":"current"),{name:xs,status:ys}});A.push({id:S.id,name:S.name,status:ot?"completed":et?"blocked":wt?"paused":"active",rawStatus:ot?"completed":et?"blocked":wt?"paused":"active",category:xe,health:Math.max(0,Math.min(100,X)),phases:$s,currentPhase:ot?Qe.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(([xs,Fs])=>({id:xs,name:Fs,status:"active"}))})}return A.sort((S,X)=>{const xe=S.status==="blocked"?0:S.status==="active"?1:2,Qe=X.status==="blocked"?0:X.status==="active"?1:2;return xe!==Qe?xe-Qe:X.health-S.health})},[Z,j.sessions.groups]),In=o.useMemo(()=>{const m=(S,X)=>{var xe,Qe;return{...S,...X,health:X.health>0?X.health:S.health,activeAgents:Math.max(S.activeAgents,X.activeAgents),totalAgents:Math.max(S.totalAgents,X.totalAgents),avatars:(xe=S.avatars)!=null&&xe.length?S.avatars:X.avatars,workstreams:(Qe=S.workstreams)!=null&&Qe.length?S.workstreams:X.workstreams,description:S.description??X.description,rawStatus:X.rawStatus??S.rawStatus??null,targetDate:X.targetDate??S.targetDate??null,createdAt:X.createdAt??S.createdAt??null,updatedAt:X.updatedAt??S.updatedAt??null}},A=new Map;for(const S of Rt)A.set(S.id,S);for(const S of[...tn??[],...Xn??[]]){if(!H&&Cs(S.id)){A.delete(S.id);continue}const X=S.rawStatus??S.status;if(!Uo(X)){A.delete(S.id);continue}const xe=A.get(S.id);A.set(S.id,xe?m(xe,S):S)}const F=new Set(En);return Array.from(A.values()).filter(S=>!F.has(S.id)).filter(S=>Uo(S.rawStatus??S.status)).sort((S,X)=>{const xe=wt=>wt==="blocked"?0:wt==="active"?1:wt==="paused"?2:3,Qe=xe(S.status)-xe(X.status);if(Qe!==0)return Qe;const Ue=Wo(S.priority)-Wo(X.priority);if(Ue!==0)return Ue;const et=ln(X.updatedAt)-ln(S.updatedAt);if(et!==0)return et;const ot=X.health-S.health;return ot!==0?ot:S.name.localeCompare(X.name)})},[Rt,Xn,H,tn,En]),Rs=o.useMemo(()=>{if(!jt)return null;const m=jt.agentName,A=jt.title;if(m){const F=ce.find(S=>{var X;return S.runId===jt.runId&&((X=S.summary)==null?void 0:X.trim())});if(F!=null&&F.summary){const S=F.summary.trim().length>40?F.summary.trim().slice(0,40)+"…":F.summary.trim();return`${m}: ${S}`}return m}if(A){const F=A.replace(/^(telegram|slack|discord|whatsapp|email|sms):/,"").trim();if(F.length>0)return F}return A??null},[ce,jt]),Js=o.useMemo(()=>{const m=new Map;for(const A of Z){const F=(A.agentId??"").trim()||`name:${(A.agentName??"").trim()}`,S=(A.agentName??"").trim()||(A.agentId??"").trim();if(!S)continue;const X=A.updatedAt??A.lastEventAt??A.startedAt??new Date().toISOString(),xe=ln(X),Qe=xe?Math.max(0,Math.floor((Date.now()-xe)/6e4)):0,Ue=m.get(F),et={id:F,name:S,role:"Agent",status:Wf(A.status),task:A.title??null,progress:A.progress??null,lastActive:X,lastActiveMinutes:Qe};(!Ue||ln(et.lastActive)>ln(Ue.lastActive))&&m.set(F,et)}return Array.from(m.values())},[Z]),fs=o.useCallback(async()=>{if(Z.length===0){T("No sessions available to continue.");return}const m=[...Z].sort(Xi)[0];if(W(m.id),Ee(m.id),R(null),P(null),["blocked","pending","queued"].includes(m.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"continue_from_dashboard"})})}catch{}T(`Focused highest priority session: ${m.title}`),await h()},[Z,h]),Be=o.useCallback(async(m,A)=>{const F=await m.json().catch(()=>null),S=typeof(F==null?void 0:F.error)=="string"&&F.error.trim()||typeof(F==null?void 0:F.message)=="string"&&F.message.trim()||`${A} (${m.status})`;return/unknown api endpoint/i.test(S)?`${A}. This route is unavailable in the running plugin build.`:Cn(S)},[]),Xt=o.useCallback((m,A)=>!m||m.trim().length===0?A:Cn(m.trim())||A,[]),ae=o.useCallback(async()=>{const m=zo(bt.items);if(!m){T("No startable Next Up workstream is available."),y("mission-control");return}await bt.playWorkstream({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId}),Ee(null),R(m.workstreamId),P(m.workstreamTitle),se(null),T(`Dispatched Next Up: ${m.workstreamTitle}`),await Promise.all([bt.refetch(),h()])},[h,bt,y]),hs=o.useCallback(async()=>{const m=zo(bt.items);if(!m){T("No startable initiative is ready for Autopilot yet."),y("mission-control");return}await zt.move({initiativeId:m.initiativeId,workstreamId:m.workstreamId,placement:"top"}),await bt.startWorkstreamAutoContinue({initiativeId:m.initiativeId,workstreamId:m.workstreamId,agentId:m.runnerAgentId,scope:"initiative"}),Ee(null),R(m.workstreamId),P(m.workstreamTitle),se(null),T(`Autopilot started for ${m.initiativeTitle}; queued from ${m.workstreamTitle}.`),await Promise.all([bt.refetch(),h()])},[h,zt,bt,y]),es=o.useCallback(async()=>{re(!0);try{if(!vn){await hs();return}await bt.stopInitiativeAutoContinue({initiativeId:vn.initiativeId}),T(`Autopilot stopped for ${vn.initiativeTitle}.`),await Promise.all([bt.refetch(),h()])}finally{re(!1)}},[vn,h,bt,hs]),ts=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),F=(m.workstreamId??"").trim();if(!A||!F)throw new Error("Missing initiative/workstream metadata for this session.");const S=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:F,agentId:m.agentId??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok)throw new Error(await Be(S,"Failed to dispatch workstream from In Progress"));Ee(null),R(F),P(m.title),T(`Dispatched ${m.title}.`),await Promise.all([bt.refetch(),h()])},[Be,h,bt]),Ys=o.useCallback(async m=>{const A=(m.initiativeId??"").trim(),F=(m.workstreamId??"").trim();if(!A||!F)throw new Error("Missing initiative/workstream metadata for this session.");const S=await fetch("/orgx/api/mission-control/next-up/triage/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A,workstreamId:F,placement:"bottom",resetToTodo:!1})});if(!S.ok){const X=await Be(S,"Failed to pause workstream from In Progress");if(!/running plugin build/i.test(X))throw new Error(X);const xe=await fetch("/orgx/api/mission-control/auto-continue/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:A})});if(!xe.ok)throw new Error(await Be(xe,"Failed to pause workstream using legacy fallback"))}T(`Paused ${m.title} and sent it to the bottom of queue.`),await Promise.all([bt.refetch(),h()])},[Be,h,bt]),Yt=o.useCallback(async m=>{const A=(m.workstreamId??"").trim();if(!A)throw new Error("This session is missing a workstream id for intervention notes.");const F=m.text.trim();if(Kf(F)){Ut("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 Be(S,"Failed to submit intervention"));T(`Intervention sent for ${m.session.title}.`),await h()},[Ut,Be,h]),L=o.useCallback(async m=>{if(W(m.id),Ee(m.id),R(null),P(null),!["running","completed","archived"].includes(m.status))try{await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/resume`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dispatch_from_dashboard"})})}catch{}T(`Dispatch requested: ${m.title}`),await h()},[h]),mt=o.useCallback(async(m,A,F={})=>{const S=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/actions/${A}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!S.ok){const X=await S.json().catch(()=>null);throw new Error((X==null?void 0:X.error)??`${A} failed (${S.status})`)}},[]),vr=o.useCallback(async m=>{var X;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:"dashboard_manual_checkpoint"})});if(!A.ok){const xe=await A.json().catch(()=>null);throw new Error((xe==null?void 0:xe.error)??`Checkpoint creation failed (${A.status})`)}const F=await A.json().catch(()=>null),S=F&&"data"in F&&((X=F.data)==null?void 0:X.id)||F&&"id"in F&&F.id||null;T(S?`Checkpoint created: ${S.slice(0,8)}`:"Checkpoint created."),await h()},[h]),Ls=o.useCallback(async m=>{await mt(m,"pause",{reason:"pause_from_dashboard"}),T(`Pause requested: ${m.title}`),await h()},[h,mt]),pi=o.useCallback(async m=>{await mt(m,"resume",{reason:"resume_from_dashboard"}),T(`Resume requested: ${m.title}`),await h()},[h,mt]),kr=o.useCallback(async m=>{await mt(m,"cancel",{reason:"restart_from_in_progress"}),await ts(m),T(`Restarted ${m.title}.`),await h()},[ts,h,mt]),jr=o.useCallback(async m=>{await mt(m,"cancel",{reason:"cancel_from_dashboard"}),T(`Cancel requested: ${m.title}`),await h()},[h,mt]),at=o.useCallback(async m=>{var Qe;const A=await fetch(`/orgx/api/runs/${encodeURIComponent(m.runId)}/checkpoints`,{method:"GET"});if(!A.ok){const Ue=await A.json().catch(()=>null);throw new Error((Ue==null?void 0:Ue.error)??`Checkpoint list failed (${A.status})`)}const F=await A.json().catch(()=>null),xe=(Qe=(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,et)=>Date.parse(et.createdAt)-Date.parse(Ue.createdAt))[0])==null?void 0:Qe.id;if(!xe)throw new Error("No checkpoint available for rollback.");await mt(m,"rollback",{checkpointId:xe,reason:"rollback_from_dashboard"}),T(`Rollback requested for ${m.title}.`),await h()},[h,mt]),Zs=o.useCallback(async()=>{var F;if(!Et||Gt.trim().length===0||Ht)return;C(!0);const m=Et.type,A=Gt.trim();try{const S={type:m,title:A,status:"active"};if(m==="workstream"){const xe=Et.initiativeId??(At==null?void 0:At.initiativeId)??((F=Rt[0])==null?void 0:F.id)??null;if(!xe){T("Select an initiative first to start a workstream."),C(!1);return}S.initiative_id=xe,S.parentId=xe}const X=await fetch("/orgx/api/entities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!X.ok){const xe=await X.json().catch(()=>null);throw new Error((xe==null?void 0:xe.error)??`Failed to create ${m}.`)}T(`Created ${m}: ${A}`),G(),await h()}catch(S){T(Xt(S instanceof Error?S.message:"",`Failed to create ${m}.`)),C(!1)}},[G,Ht,Et,Gt,Rt,h,At==null?void 0:At.initiativeId]),pt=o.useCallback(()=>{me("initiative")},[me]),gs=o.useCallback(m=>{me("workstream",m)},[me]);o.useCallback(()=>{var m;return gs((At==null?void 0:At.initiativeId)??((m=Rt[0])==null?void 0:m.id)??null)},[Rt,At==null?void 0:At.initiativeId,gs]);const er=o.useCallback(m=>{const A=[...Z].filter(F=>(F.initiativeId??F.groupId)===m.id).sort(Xi)[0];A&&(W(A.id),Ee(A.id),R(null),P(null),T(`Focused initiative: ${m.name}`))},[Z]),Ds=o.useCallback(m=>{const A=Rt.find(F=>F.id===m)??In.find(F=>F.id===m)??null;A&&er(A)},[er,Rt,In]),ns=o.useCallback(m=>{const A=(m??"").trim();y("activity"),z("initiatives"),B("initiatives"),Ne("in_progress"),Oe("needs_attention"),O(A.length>0?A:null),T(A.length>0?"Reviewing pending decision.":"Review needs attention.")},[y]),nn=o.useCallback(m=>{const A=new Set,F=(m.runId??"").trim();F.length>0&&A.add(F),A.add(m.sliceRunId);const S=new Map;for(const et of ce){const ot=Gi(et),wt=zf(et);(ot&&A.has(ot)||wt&&wt===m.sliceRunId)&&S.set(et.id,et)}const X=Array.from(S.values()),xe=et=>{const ot=et.type.trim().toLowerCase();let wt=0;return(ot==="decision_requested"||ot==="blocker_created")&&(wt+=80),(ot==="run_failed"||ot==="autopilot_stopped")&&(wt+=70),(ot.includes("slice_completed")||ot.includes("completed"))&&(wt+=60),ot.includes("artifact")&&(wt+=55),(ot.includes("progress")||ot.includes("update"))&&(wt+=35),wt+=Math.floor(ln(et.timestamp)/1e3),wt};X.sort((et,ot)=>xe(ot)-xe(et));const Qe=X[0]??null;y("activity"),B("activity"),z("initiatives");const Ue=(F?Z.find(et=>et.runId===F||et.id===F)??null:null)??(m.initiativeId&&m.workstreamId?Z.find(et=>et.initiativeId===m.initiativeId&&et.workstreamId===m.workstreamId)??null:null);if(Ue?(W(Ue.id),Ee(Ue.id),R(null),P(null)):m.workstreamId&&(Ee(null),R(m.workstreamId),P(m.workstreamTitle??"Work slice")),Qe!=null&&Qe.id){pe(Qe.id),T(`Reviewing activity for ${m.workstreamTitle??"work slice"}.`);return}if(m.primaryAction==="resolve_decision"){ns();return}if(F.length>0){mn(F),T("Opened the related work session. Timeline details were unavailable.");return}T("No activity details were found for this slice yet.")},[ce,mn,ns,Z,y]);return o.useCallback(m=>{const A=new Set(m),F=[...Z].filter(S=>A.has(S.status)).sort(Xi)[0];if(!F){T("No matching sessions for that metric right now.");return}Xe(F.id),B("activity")},[Z,Xe]),o.useCallback(m=>{l==="activity"&&(m==="sessions"||m==="active"||m==="blocked"||m==="failed"||m==="decisions"||m==="outbox"||m==="handoffs")&&He(m)},[l]),v?n.jsxs("div",{className:"flex min-h-screen flex-col lg:h-screen",style:{backgroundColor:E.background},children:[n.jsxs("div",{className:"border-b border-subtle px-4 py-2.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"shimmer-skeleton h-6 w-6 rounded-lg"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-28 rounded-md"}),n.jsx("div",{className:"shimmer-skeleton h-5 w-14 rounded-full"})]}),n.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Array.from({length:4}).map((m,A)=>n.jsx("div",{className:"shimmer-skeleton h-7 w-24 rounded-full"},A))})]}),n.jsxs("div",{className:"grid flex-1 grid-cols-1 gap-4 p-4 sm:p-5 lg:grid-cols-12",children:[n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-3"}),n.jsx("div",{className:"shimmer-skeleton min-h-[240px] rounded-2xl lg:col-span-6"}),n.jsxs("div",{className:"flex flex-col gap-4 lg:col-span-3",children:[n.jsx("div",{className:"shimmer-skeleton h-40 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton h-48 rounded-2xl"}),n.jsx("div",{className:"shimmer-skeleton flex-1 rounded-2xl",style:{minHeight:160}})]})]})]}):n.jsxs("div",{className:"relative flex min-h-screen flex-col pb-[92px] lg:h-screen lg:min-h-0 lg:overflow-hidden lg:pb-0",style:{backgroundColor:E.background},children:[typeof window<"u"&&window.location.port==="5173"&&n.jsx("div",{className:"absolute left-1/2 top-4 z-30 -translate-x-1/2",children:n.jsxs("div",{className:"rounded-full border border-strong bg-white/[0.06] px-4 py-2 text-caption text-primary shadow-[0_10px_30px_rgba(0,0,0,0.35)] backdrop-blur",children:["Dev preview on 5173. Installed plugin runs on OpenClaw port"," ",n.jsx("a",{href:"http://127.0.0.1:18789/orgx/live/",className:"text-white underline underline-offset-4 hover:text-secondary",children:"18789"}),"."]})}),n.jsxs("header",{className:"relative z-[180] border-b border-subtle px-4 py-1.5 sm:px-6",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2.5 lg:grid lg:grid-cols-[1fr_auto_1fr]",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[n.jsx(sh,{}),n.jsxs("h1",{className:"text-title font-semibold tracking-tight text-white sm:text-[17px]",children:["OrgX",n.jsx("span",{className:"ml-1.5 text-secondary",children:"Live"})]}),n.jsx(Zd,{color:Ff[j.connection],pulse:j.connection==="connected",title:[`Status: ${Fo[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: ${Of(j.lastSnapshotAt)}`,Nn?`Details: ${Nn.message}`:null].filter(Boolean).join(`
|
|
212
|
-
`),children:Fo[j.connection]??"Unknown"}),(Dn>0||jn>0)&&n.jsx(co,{className:"hidden md:flex",running:Dn,blocked:jn,decisionsCount:ye?j.decisions.length:0,completedToday:Ts,onDecisionsClick:()=>{y("activity"),z("initiatives"),B("initiatives"),Ne("in_progress"),Oe("needs_attention")},onBlockedClick:()=>{Se.length>0?(y("mission-control"),Ne("in_progress"),Oe("needs_attention")):He("blocked")},onNewInitiative:pt})]}),n.jsx("div",{className:"hidden items-center justify-center lg:flex",children:n.jsxs("div",{className:"flex rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>y("activity"),"aria-pressed":l==="activity",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${l==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>y("mission-control"),onMouseEnter:Gn,onFocus:Gn,"aria-pressed":l==="mission-control",className:`rounded-full px-3 py-1 text-body font-medium transition-all ${l==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})}),n.jsxs("div",{className:"relative isolate flex items-center justify-end gap-1.5 sm:gap-2",children:[n.jsxs("div",{className:"relative hidden md:block",children:[n.jsx("label",{htmlFor:"workspace-switcher",className:"sr-only",children:"Workspace scope"}),n.jsxs("select",{id:"workspace-switcher",value:u??"__all__",onChange:m=>{const A=m.target.value;g(A==="__all__"?null:A)},className:"control-pill h-8 min-w-[170px] appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${f}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),k.map(m=>n.jsx("option",{value:m.id,children:m.title},m.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),j.lastActivity&&n.jsxs("span",{className:"hidden text-body text-secondary xl:inline",children:["Last activity: ",j.lastActivity]}),t&&n.jsx("button",{type:"button",onClick:()=>{Kn(!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:$e,onClick:()=>_e(m=>!m),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"})]}),Zn.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:Zn.length})]}),n.jsx("button",{type:"button",onClick:()=>rt(!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:()=>Ut("orgx"),title:"Settings",className:"relative inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08]",children:n.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z"}),n.jsx("path",{d:"M19.4 15a1.8 1.8 0 0 0 .36 2l.05.05a2.2 2.2 0 0 1-1.56 3.76 2.2 2.2 0 0 1-1.56-.64l-.05-.05a1.8 1.8 0 0 0-2-.36 1.8 1.8 0 0 0-1.1 1.63V22a2.2 2.2 0 0 1-4.4 0v-.07a1.8 1.8 0 0 0-1.1-1.63 1.8 1.8 0 0 0-2 .36l-.05.05a2.2 2.2 0 1 1-3.12-3.12l.05-.05a1.8 1.8 0 0 0 .36-2 1.8 1.8 0 0 0-1.63-1.1H2a2.2 2.2 0 0 1 0-4.4h.07a1.8 1.8 0 0 0 1.63-1.1 1.8 1.8 0 0 0-.36-2l-.05-.05a2.2 2.2 0 1 1 3.12-3.12l.05.05a1.8 1.8 0 0 0 2 .36 1.8 1.8 0 0 0 1.1-1.63V2a2.2 2.2 0 0 1 4.4 0v.07a1.8 1.8 0 0 0 1.1 1.63 1.8 1.8 0 0 0 2-.36l.05-.05a2.2 2.2 0 0 1 3.12 3.12l-.05.05a1.8 1.8 0 0 0-.36 2 1.8 1.8 0 0 0 1.63 1.1H22a2.2 2.2 0 0 1 0 4.4h-.07a1.8 1.8 0 0 0-1.63 1.1z"})]})}),n.jsxs("button",{type:"button",onClick:h,className:"group inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.1] bg-white/[0.03] text-body text-primary transition-colors hover:bg-white/[0.08] sm:w-auto sm:gap-1.5 sm:px-3",title:"Refresh data",children:[n.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"transition-transform group-hover:rotate-45",children:[n.jsx("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),n.jsx("path",{d:"M21 3v5h-5"})]}),n.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]}),ue&&n.jsxs("div",{id:"header-notifications-panel",ref:Ke,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:[Zn.length>0&&n.jsx("button",{type:"button",onClick:wr,className:"text-caption text-secondary transition-colors hover:text-primary",children:"Dismiss all"}),n.jsx("button",{type:"button",onClick:()=>_e(!1),className:"rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary","aria-label":"Close notifications",children:"Close"})]})]}),n.jsx("div",{className:"mb-1.5 px-1.5",children:n.jsx(co,{className:"max-w-full overflow-hidden",running:Dn,blocked:jn,decisionsCount:Es,completedToday:Ts,onDecisionsClick:()=>{y("activity"),B("initiatives"),z("initiatives"),Ne("in_progress"),Oe("needs_attention"),_e(!1)},onBlockedClick:()=>{Se.length>0?(y("mission-control"),Ne("in_progress"),Oe("needs_attention")):He("blocked"),_e(!1)}})}),Zn.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:$n>0?"No new notification banners. Active work is summarized above.":"Everything looks clear."}):n.jsx("div",{className:"space-y-1.5",children:Zn.map(m=>n.jsx("div",{className:"rounded-xl border px-3 py-2",style:{borderColor:m.kind==="error"?"rgba(239,68,68,0.35)":"rgba(255,255,255,0.1)",backgroundColor:m.kind==="error"?"rgba(239,68,68,0.08)":"rgba(255,255,255,0.02)"},children:n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("p",{className:"inline-flex items-center gap-1.5 text-body font-semibold",style:{color:m.kind==="error"?"#fecaca":"#e2e8f0"},children:[n.jsx(bn,{type:m.icon,size:12,className:"opacity-90"}),n.jsx("span",{className:"truncate",children:m.title})]}),n.jsx("p",{className:"mt-0.5 text-body leading-snug text-secondary",children:m.message}),m.onAction&&n.jsx("button",{type:"button",onClick:()=>{var A;(A=m.onAction)==null||A.call(m),_e(!1)},className:"mt-1.5 rounded-md border border-strong bg-white/[0.05] px-2.5 py-1 text-caption font-medium text-primary transition-colors hover:bg-white/[0.1] hover:text-white",children:m.actionLabel??"View"})]}),n.jsx("button",{type:"button",onClick:()=>D(m.id),className:"shrink-0 rounded-md px-1.5 py-0.5 text-caption text-secondary transition-colors hover:bg-white/[0.08] hover:text-primary",title:"Dismiss",children:"Dismiss"})]})},m.id))})]})]})]}),n.jsxs("div",{className:"mt-2 flex items-center justify-center gap-2 lg:hidden",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("label",{htmlFor:"workspace-switcher-mobile",className:"sr-only",children:"Workspace scope"}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{id:"workspace-switcher-mobile",value:u??"__all__",onChange:m=>{const A=m.target.value;g(A==="__all__"?null:A)},className:"control-pill h-8 w-full appearance-none justify-start bg-white/[0.03] pl-3 pr-8 text-caption font-semibold text-primary",title:`Workspace scope: ${f}`,children:[n.jsx("option",{value:"__all__",children:"All workspaces"}),k.map(m=>n.jsx("option",{value:m.id,children:m.title},m.id))]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 text-secondary",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]})]}),n.jsxs("div",{className:"flex w-full max-w-[248px] rounded-full border border-white/[0.1] bg-white/[0.03] p-0.5",role:"group","aria-label":"Dashboard view",children:[n.jsx("button",{type:"button",onClick:()=>y("activity"),"aria-pressed":l==="activity",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${l==="activity"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Activity"}),n.jsx("button",{type:"button",onClick:()=>y("mission-control"),"aria-pressed":l==="mission-control",className:`flex-1 rounded-full px-3 py-1.5 text-body font-medium transition-all ${l==="mission-control"?"bg-white/[0.1] text-white":"text-secondary hover:text-bright"}`,children:"Mission Control"})]})]})]}),l==="mission-control"?n.jsx("div",{className:"relative z-0 flex-1 min-h-0 flex flex-col overflow-hidden",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"flex flex-1 items-center justify-center text-body text-secondary",children:"Loading Mission Control…"}),children:n.jsx(jf,{initiatives:In,activities:ce,agents:Js,runtimeInstances:j.runtimeInstances??[],workspaceInitiativeId:u,isLoading:v,authToken:null,embedMode:!1,connection:j.connection,lastSnapshotAt:j.lastSnapshotAt,error:b,hasApiKey:e.state.hasApiKey,onOpenSettings:()=>Ut("orgx"),onRefresh:h,onCreateInitiative:pt,onPlayNextUp:ae,onStartAutopilot:hs,nextUpQueueModel:bt,nextUpActionsModel:zt,snapshotVersion:j.snapshotVersion})})}):n.jsxs("main",{className:"relative z-0 grid min-h-0 flex-1 grid-cols-1 gap-4 overflow-y-auto p-4 pb-20 sm:p-5 sm:pb-20 lg:grid-cols-12 lg:overflow-hidden lg:pb-5",children:[n.jsx("section",{className:`min-h-0 lg:col-span-3 lg:flex lg:flex-col lg:[&>section]:h-full ${Ae!=="agents"?"hidden lg:flex":""}`,children:n.jsx(Bm,{sessions:j.sessions,activity:ce,runtimeInstances:j.runtimeInstances??[],showSyntheticEntities:t||r,selectedSessionId:we,onSelectSession:Xe,onAgentFilter:se,agentFilter:U,timeFilterId:Y,onReconnect:kn,onLaunched:h,connectionStatus:j.connection})}),n.jsx("section",{className:`min-h-0 lg:col-span-6 lg:flex lg:flex-col lg:[&>section]:h-full ${Ae!=="activity"?"hidden lg:flex":""}`,children:n.jsx(kf,{activity:fn.items,sessions:Z,sliceRuns:Se,initiatives:Rt,timelineNarrative:j.timelineNarrative??[],workspaceId:u,chatSnapshot:j.chat,selectedRunIds:pn,selectedSessionLabel:Rs,selectedWorkstreamId:ne,selectedWorkstreamLabel:J,agentFilter:U,timeFilterId:Y,onTimeFilterChange:Yn,customTimeRange:ve,onCustomTimeRangeChange:je,hasMore:fn.hasMore,isLoadingMore:fn.isLoadingMore,onLoadMore:fn.loadMore,onClearSelection:Fe,onClearWorkstreamFilter:gt,onClearAgentFilter:it,onFocusRunId:mn,onOpenDecision:ns,requestedActivityItemId:Me,onActivityItemRequestHandled:()=>pe(null),onPlayNextUp:ae,onStartAutopilot:hs,onPauseWorkstream:Ys,onCreateInitiative:pt,onOpenMissionControl:()=>y("mission-control"),onOpenNextUp:()=>y("mission-control"),onOpenSettings:()=>Ut("orgx"),onRefreshData:h,isLoading:v})}),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(Ks,{className:"flex h-full min-h-0 flex-col card-enter",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-subtle px-4 pt-3",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-4 overflow-x-auto",children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":Q==="in_progress",onClick:m=>{m.stopPropagation(),Ne("in_progress")},className: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:ct}),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:m=>{m.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:ms.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:()=>{es().catch(m=>{T(Xt(m instanceof Error?m.message:"","Autopilot action failed."))})},disabled:q,className:"control-pill inline-flex h-8 items-center gap-1.5 px-2.5 text-caption font-semibold disabled:opacity-45","data-tone":"teal","data-state":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",De==="all"?"bg-white/[0.09] text-primary":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"All active"}),n.jsx("span",{className:"tabular-nums opacity-75",children:ct})]}),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",De==="needs_attention"?"bg-[#F5B700]/14 text-[#FFE7A8]":"text-secondary hover:bg-white/[0.06] hover:text-bright"),children:[n.jsx("span",{children:"Needs attention"}),n.jsx("span",{className:"tabular-nums opacity-80",children:Ct})]})]}):null,n.jsx("div",{className:"min-h-0 flex-1",children:Q==="in_progress"?De==="needs_attention"?n.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-y-auto p-2",children:[Bt.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(Af,{model:Bt,actions:Tt,onOpenDetail:un})})}),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(If,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",decisions:j.decisions,focusDecisionId:M,onFocusDecisionHandled:()=>O(null),onApproveDecision:_,onRejectDecision:V,onApproveAll:oe,onBulkDecisionAction:K,mutationState:be})})})]}):n.jsx(Ks,{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(Wu,{className:le("h-full min-h-0"),title:ye?"Blocked & review-required slices":"Needs attention",showHeader:!1,panelStyle:"flat",sliceRuns:Se,initiatives:Rt,onOpenDecisions:()=>ns(),onFocusRunId:mn,onReviewActivity:nn,onOpenSliceDetail:cn})})]})]}):n.jsx(Eu,{className:"h-full min-h-0",showHeader:!1,panelStyle:"flat",sessions:Z,sliceRuns:Se,initiatives:Rt,needsAttentionCount:Ct,onSwitchToNeedsAttention:()=>Oe("needs_attention"),onOpenSession:Xe,onFocusRunId:mn,onPlayWorkstream:ts,onPauseWorkstream:Ys,onResumeWorkstream:ts,onRestartSession:kr,onIntervene:Jn,onOpenSliceDetail:Kt}):n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading queue…"}),children:n.jsx(_f,{projectId:u,title:"Next Up",showHeader:!1,panelStyle:"flat",className:"h-full",compact:!1,selectionEnabled:!0,showQueueSettings:!0,queueModel:bt,queueActions:zt,snapshotVersion:j.snapshotVersion,onOpenInitiative:Ds,onOpenSliceDetail:Jt})})},`${Q}:${De}`)]}):n.jsx(Ks,{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&&At&&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:()=>Te(!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:E.cardBg},children:[n.jsxs("div",{className:"flex items-center justify-between border-b border-subtle px-4 py-3",children:[n.jsx("h3",{className:"text-body font-semibold text-primary",children:"Session Detail"}),n.jsx("button",{type:"button",onClick:()=>Te(!1),"aria-label":"Close session inspector",className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-strong bg-white/[0.03] text-primary transition-colors hover:bg-white/[0.08] hover:text-white",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})})]}),n.jsx("div",{className:"flex-1 min-h-0",children:n.jsx(o.Suspense,{fallback:n.jsx("div",{className:"p-4 text-body text-secondary",children:"Loading session detail…"}),children:n.jsx(Nf,{session:At,activity:ce,initiatives:Rt,sliceRuns:Se,initialInterventionDraft:fe,onSubmitIntervention:Yt,onOpenActivityItem:Ms,onContinueHighestPriority:fs,onDispatchSession:L,onPauseSession:Ls,onResumeSession:pi,onCancelSession:jr,onCreateCheckpoint:vr,onRollbackSession:at,onStartInitiative:pt,onStartWorkstream:gs})})})]},"session-drawer-panel")]})}),l==="activity"?n.jsx(tu,{activeTab:Ae,onTabChange:Le,pendingDecisionCount:ye?j.decisions.length:0}):null,n.jsx(di,{open:Et!==null,onClose:G,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:(Et==null?void 0:Et.type)==="workstream"?"New Workstream":"New Initiative"}),n.jsx("p",{className:"mt-1 text-body leading-relaxed text-secondary",children:(Et==null?void 0:Et.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:Gt,onChange:m=>Qn(m.target.value),onKeyDown:m=>{m.key==="Enter"&&Zs()},autoFocus:!0,"data-modal-autofocus":"true",placeholder:(Et==null?void 0:Et.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:G,className:"rounded-md px-3 py-1.5 text-body text-secondary transition-colors hover:text-white",children:"Cancel"}),n.jsx("button",{onClick:Zs,disabled:Gt.trim().length===0||Ht,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:Ht?"Creating…":"Create"})]})]})}),We.open&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Cf,{open:We.open,onClose:()=>ht(m=>({...m,open:!1,focusAgentDomain:null})),activeTab:We.tab,onChangeTab:m=>ht(A=>({...A,tab:m})),agentBehaviorInitialDomain:We.focusAgentDomain,demoMode:t,onToggleDemoMode:m=>{Kn(m),m||kn()},devMode:a,onToggleDevMode:c,showSyntheticEntities:r,onToggleShowSyntheticEntities:i,workspaceOptions:k,selectedWorkspaceId:u,onSelectWorkspace:g,onboarding:e,authToken:null,embedMode:!1})}),st&&n.jsx(o.Suspense,{fallback:null,children:n.jsx($f,{open:st,selectedWorkspaceId:u,onClose:()=>rt(!1)})}),(ge==="sessions"||ge==="active"||ge==="blocked"||ge==="failed")&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Mf,{open:ge==="sessions"||ge==="active"||ge==="blocked"||ge==="failed",onClose:()=>He(null),mode:ge==="active"||ge==="blocked"||ge==="failed"?ge:"sessions",sessions:Z,onOpenSession:m=>{Xe(m.id),He(null)},onRunAction:async(m,A)=>{await mt(m,A,{reason:`bulk_${A}_from_header`})},onRefetch:async()=>h(),onSetNotice:m=>T(m)})}),ge==="decisions"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Tf,{open:ge==="decisions",onClose:()=>He(null),decisions:ye?j.decisions:[],onApproveDecision:_,onRejectDecision:V,onApproveAll:oe,onBulkDecisionAction:K})}),ge==="outbox"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Ef,{open:ge==="outbox",onClose:()=>He(null),outbox:j.outbox,onOpenSettings:()=>{He(null),Ut("orgx")},onRefresh:()=>{h()}})}),ge==="handoffs"&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Rf,{open:ge==="handoffs",onClose:()=>He(null),handoffs:j.handoffs})}),n.jsx(rh,{}),Wt&&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(Sf,{item:Wt,actions:Tt,onClose:()=>$t(null),onNavigate:Tn,currentIndex:dn,totalCount:It.length,decisions:ye?j.decisions:void 0,onApproveDecision:_,onRejectDecision:V})})})}),Ze&&n.jsx(o.Suspense,{fallback:null,children:n.jsx(Df,{target:Ze,onClose:()=>kt(null),onPlayWorkstream:async(m,A,F)=>{const S=await fetch("/orgx/api/mission-control/next-up/play",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,agentId:F??void 0,fastAck:!0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const X=await S.json().catch(()=>null);T(Xt((X==null?void 0:X.error)??(X==null?void 0:X.message)??null,`Failed to dispatch workstream (${S.status})`));return}T("Dispatched workstream."),h()},onStartAutoContinue:async(m,A,F)=>{await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:"top"})});const S=await fetch("/orgx/api/mission-control/auto-continue/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,agentId:F??void 0,ignoreSpawnGuardRateLimit:!0})});if(!S.ok){const X=await S.json().catch(()=>null);T(Xt((X==null?void 0:X.error)??(X==null?void 0:X.message)??null,`Failed to start auto-continue (${S.status})`));return}T("Auto-continue started."),h()},onMoveWorkstream:async(m,A,F)=>{const S=await fetch("/orgx/api/mission-control/next-up/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A,placement:F})});if(!S.ok){const X=await S.json().catch(()=>null);T(Xt((X==null?void 0:X.error)??(X==null?void 0:X.message)??null,`Move failed (${S.status})`));return}T(`Moved workstream to ${F}.`),h()},onRemoveFromQueue:async(m,A)=>{const F=await fetch("/orgx/api/mission-control/next-up/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({initiativeId:m,workstreamId:A})});if(!F.ok){const S=await F.json().catch(()=>null);T(Xt((S==null?void 0:S.error)??(S==null?void 0:S.message)??null,`Remove failed (${F.status})`));return}T("Removed workstream from queue."),h()},onOpenSession:Xe,onFocusRunId:mn,onOpenInitiative:Ds,onReviewActivity:nn,onOpenDecisions:()=>ns(),onAcceptSlice:Mn,onRejectSlice:us})})]})}typeof window<"u"&&window.addEventListener("vite:preloadError",e=>{e.preventDefault(),window.location.reload()});Yc();const ah=new ql({defaultOptions:{queries:{staleTime:3e4,retry:1,refetchOnWindowFocus:!1,refetchOnReconnect:!0}}});Ol.createRoot(document.getElementById("root")).render(n.jsx(o.StrictMode,{children:n.jsx(Bl,{client:ah,children:n.jsx(eh,{})})}));export{wh as $,Ft as A,Un as B,is as C,vd as D,bn as E,gh as F,yh as G,ss as H,vh as I,as as J,Jm as K,fh as L,ni as M,Is as N,Gs as O,Ks as P,od as Q,ui as R,Od as S,Bd as T,ad as U,Hd as V,Gd as W,bh as X,Zl as Y,hh as Z,bu as _,Vu as a,An as a0,Tr as a1,lu as a2,ph as a3,nr as a4,Jr as a5,St as b,Pc as c,E as d,fm as e,Ah as f,js as g,Cn as h,Lt as i,kh as j,fl as k,Nh as l,Dt as m,Ot as n,_t as o,Ih as p,Wn as q,jh as r,Sh as s,Ku as t,jd as u,xh as v,di as w,ds as x,le as y,Pt as z};
|