@wrongstack/webui-hq 0.291.2 → 0.292.1

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.
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/cockpit-CZa8Ik0r.js","assets/rolldown-runtime-QTnfLwEv.js","assets/icons-BlGYTg3M.js","assets/markdown-Dm2qU66U.js","assets/fleet-map-VOzbj36e.js","assets/vendor-BoaR8QxN.js","assets/fleet-topology-CHOsHZc9.js","assets/live-console-CGxRZ15o.js","assets/mailbox-B3ZDFEyg.js","assets/use-backfilled-events-BnFvycsd.js","assets/cost-C4nlUQAz.js","assets/brain-B4Tdewfy.js","assets/worktree-BXf7yQRK.js","assets/trends-C6j-auPf.js","assets/alerts-Coy0VQOD.js","assets/control-BRj__LMC.js","assets/settings-BncyJ7aj.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{A as t,At as n,Et as r,G as i,L as a,M as o,Mt as s,Nt as c,Ot as l,S as u,T as d,_ as ee,a as te,c as f,ft as p,g as m,i as ne,k as h,o as re,p as ie,q as g,tt as _,u as ae,vt as v,w as oe,x as y}from"./icons-BlGYTg3M.js";import{t as b}from"./vendor-BoaR8QxN.js";import{i as x}from"./markdown-Dm2qU66U.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var S=e(c(),1),C=b(),w=e=>Symbol.iterator in e,T=e=>`entries`in e,E=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},se=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function ce(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:w(e)&&w(t)?T(e)&&T(t)?E(e,t):se(e,t):E({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function le(e){let t=S.useRef(void 0);return n=>{let r=e(n);return ce(t.current,r)?t.current:t.current=r}}var D=`wrongstack.hq.token.v1`;function ue(){if(typeof window>`u`)return null;try{let e=new URLSearchParams(window.location.search).get(`token`);return e!==null&&e.length>0?e:null}catch{return null}}function O(){if(typeof window>`u`)return null;try{return window.sessionStorage??null}catch{return null}}function de(){try{let e=O()?.getItem(D)??null;return e!==null&&e.length>0?e:null}catch{return null}}function k(e){try{O()?.setItem(D,e)}catch{}}function A(){try{O()?.removeItem(D)}catch{}}function j(){let e=ue();return e===null?de():(k(e),e)}function fe(){if(typeof window>`u`)return;let e=ue();if(e!==null&&(k(e),de()===e))try{let e=new URL(window.location.href);e.searchParams.delete(`token`),window.history.replaceState(null,``,`${e.pathname}${e.search}${e.hash}`)}catch{}}function pe(){let e=j();return e===null?{}:{Authorization:`Bearer ${e}`}}function M(e,t){let n={...t?.headers??{},...pe()};return fetch(e,{...t,headers:n})}var N=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},me=(e=>e?N(e):N),he=e=>e;function ge(e,t=he){let n=S.useSyncExternalStore(e.subscribe,S.useCallback(()=>t(e.getState()),[e,t]),S.useCallback(()=>t(e.getInitialState()),[e,t]));return S.useDebugValue(n),n}var P=e=>{let t=me(e),n=e=>ge(t,e);return Object.assign(n,t),n},_e=(e=>e?P(e):P);function F(e,t){let n=t.liveSessions??[],r=e.selectedSessionId===null?void 0:n.find(t=>t.sessionId===e.selectedSessionId),i=e.selectedAgentId===null||r?.agents.some(t=>t.id===e.selectedAgentId)===!0,a=e.selectedClientId===null||t.clients.some(t=>t.clientId===e.selectedClientId);return{snapshot:t,...e.selectedSessionId!==null&&r===void 0?{selectedSessionId:null,selectedAgentId:null}:i?{}:{selectedAgentId:null},...a?{}:{selectedClientId:null}}}function ve(e,t){return e.timestamp===t.timestamp&&e.severity===t.severity&&e.message===t.message}var I=_e()(e=>({snapshot:null,events:[],alerts:[],commandStatuses:[],activeView:`cockpit`,selectedSessionId:null,selectedAgentId:null,selectedClientId:null,connected:!1,authRequired:!1,setActiveView:t=>e({activeView:t}),selectSession:(t,n=null)=>e({selectedSessionId:t,selectedAgentId:n}),selectAgent:(t,n)=>e({selectedSessionId:t,selectedAgentId:n}),selectClient:t=>e({selectedClientId:t}),markAuthRequired:()=>e(e=>e.authRequired?{}:{authRequired:!0}),_hydrateSnapshot:t=>e(e=>e.snapshot===null?F(e,t):{}),_onSnapshot:t=>e(e=>({...F(e,t),connected:!0})),_onEvent:t=>e(e=>e.events.some(e=>e.id===t.id)?{}:{events:[...e.events,t].slice(-500)}),_onAlert:t=>e(e=>e.alerts.some(e=>ve(e,t))?{}:{alerts:[...e.alerts,t].slice(-100)}),_onCommandStatus:t=>e(e=>{let n=e.commandStatuses.findIndex(e=>e.commandId===t.commandId);if(n<0)return{commandStatuses:[...e.commandStatuses,t].slice(-200)};let r=[...e.commandStatuses];return r[n]=t,{commandStatuses:r}}),_setConnected:t=>e({connected:t})}));async function L(e){let t;try{t=await M(e)}catch{throw Error(`Network error fetching ${e}`)}if(t.status===401)throw I.getState().markAuthRequired(),Error(`401 Unauthorized fetching ${e} — browser token required`);if(!t.ok)throw Error(`${t.status} ${t.statusText}`);try{return await t.json()}catch{throw Error(`Invalid JSON response from ${e}: ${t.status}`)}}async function ye(e){let t;try{t=await M(`/api/mailbox-send`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})}catch{throw Error(`Network error sending mailbox message`)}if(t.status===401)throw I.getState().markAuthRequired(),Error(`401 Unauthorized — browser token required`);if(!t.ok){let e=await t.json().catch(()=>null),n=typeof e?.error==`string`?e.error:t.statusText||`HTTP ${t.status}`;throw Error(n)}try{return await t.json()}catch{throw Error(`Invalid JSON response from mailbox-send API`)}}async function be(e,t,n){let r;try{r=await M(`/api/command`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({clientId:e,type:t,payload:n})})}catch{throw Error(`Network error sending command`)}if(r.status===401)throw I.getState().markAuthRequired(),Error(`401 Unauthorized — browser token required`);if(!r.ok){let e=(await r.json().catch(()=>null))?.error??(r.statusText||`HTTP ${r.status}`);throw Error(e)}try{return await r.json()}catch{throw Error(`Invalid JSON response from command API`)}}var R=`wrongstack.hq.local-prefs.v1`,z={appearance:{theme:`dark`},fleet:{scope:`all`,layout:`map`,machineId:``,projectId:``},console:{delivery:`steer`,subject:``,body:``},control:{cmdType:`steer`,abortTarget:`leader`,spawnRole:`bug-hunter`,spawnTask:``,steerTo:`leader`,steerSubject:``,steerBody:``,broadcastSubject:``,broadcastBody:``},mailbox:{query:``,types:[],priorities:[],includeCompleted:!0}},B=null,V=new Set;function H(){for(let e of V)e()}function U(e){return typeof structuredClone==`function`?structuredClone(e):JSON.parse(JSON.stringify(e))}function W(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xe(){if(typeof window>`u`||window.localStorage===void 0)return U(z);try{let e=window.localStorage.getItem(R);return e===null?U(z):Se(JSON.parse(e))}catch{return U(z)}}function Se(e){if(!W(e))return U(z);let t=W(e.appearance)?e.appearance:{},n=W(e.fleet)?e.fleet:{},r=W(e.console)?e.console:{},i=W(e.control)?e.control:{},a=W(e.mailbox)?e.mailbox:{};return{appearance:{theme:t.theme===`light`?`light`:`dark`},fleet:{scope:n.scope===`machine`||n.scope===`project`?n.scope:`all`,layout:n.layout===`compact`?`compact`:`map`,machineId:typeof n.machineId==`string`?n.machineId:``,projectId:typeof n.projectId==`string`?n.projectId:``},console:{delivery:r.delivery===`btw`||r.delivery===`queue`?r.delivery:`steer`,subject:typeof r.subject==`string`?r.subject:``,body:typeof r.body==`string`?r.body:``},control:{cmdType:i.cmdType===`btw`||i.cmdType===`queue`||i.cmdType===`abort`||i.cmdType===`spawn`||i.cmdType===`broadcast`||i.cmdType===`run-command`?i.cmdType:z.control.cmdType,abortTarget:i.abortTarget===`fleet`?`fleet`:`leader`,spawnRole:typeof i.spawnRole==`string`&&i.spawnRole.length>0?i.spawnRole:z.control.spawnRole,spawnTask:typeof i.spawnTask==`string`?i.spawnTask:z.control.spawnTask,steerTo:typeof i.steerTo==`string`?i.steerTo:z.control.steerTo,steerSubject:typeof i.steerSubject==`string`?i.steerSubject:z.control.steerSubject,steerBody:typeof i.steerBody==`string`?i.steerBody:z.control.steerBody,broadcastSubject:typeof i.broadcastSubject==`string`?i.broadcastSubject:z.control.broadcastSubject,broadcastBody:typeof i.broadcastBody==`string`?i.broadcastBody:z.control.broadcastBody},mailbox:{query:typeof a.query==`string`?a.query:z.mailbox.query,types:Array.isArray(a.types)?a.types.filter(e=>typeof e==`string`):[],priorities:Array.isArray(a.priorities)?a.priorities.filter(e=>typeof e==`string`):[],includeCompleted:typeof a.includeCompleted!=`boolean`||a.includeCompleted}}}function G(){return B===null&&(B=xe()),B}function K(e){if(!(typeof window>`u`||window.localStorage===void 0))try{window.localStorage.setItem(R,JSON.stringify(e))}catch{}}function Ce(e){return V.add(e),()=>V.delete(e)}function we(){return G()}function Te(){return z}function q(){return(0,S.useSyncExternalStore)(Ce,we,Te)}function Ee(e){let t=G();B={...t,control:{...t.control,...e}},K(B),H()}function De(e){let t=G();B={...t,appearance:{...t.appearance,...e}},K(B),H()}function Oe(e){let t=G();B={...t,fleet:{...t.fleet,...e}},K(B),H()}function ke(e){let t=G();B={...t,console:{...t.console,...e}},K(B),H()}function Ae(e){let t=G();B={...t,mailbox:{...t.mailbox,...e}},K(B),H()}var J=x();function je({hadToken:e}){let[t,n]=(0,S.useState)(null),[r,i]=(0,S.useState)(null);(0,S.useEffect)(()=>{fetch(`/api/auth/status`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return await e.json()}).then(n).catch(()=>i(`Could not load HQ auth status.`))},[]);let a=t?.tokenMode??!0,o=t?.passwordMode??!1,[s,c]=(0,S.useState)(`token`);return(0,S.useEffect)(()=>{t&&c(t.passwordMode?`password`:`token`)},[t]),r?(0,J.jsx)(`div`,{className:`hq-token-gate`,children:(0,J.jsxs)(`div`,{className:`hq-token-card`,children:[(0,J.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),(0,J.jsx)(`div`,{className:`hq-token-title`,children:`Auth status unavailable`}),(0,J.jsx)(`p`,{className:`hq-token-text`,children:r})]})}):t?(0,J.jsx)(`div`,{className:`hq-token-gate`,children:(0,J.jsxs)(`div`,{className:`hq-token-card`,children:[(0,J.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),a&&o?(0,J.jsxs)(`div`,{className:`hq-token-tabs`,children:[(0,J.jsx)(`button`,{type:`button`,className:`hq-token-tab`+(s===`token`?` active`:``),onClick:()=>c(`token`),children:`Browser token`}),(0,J.jsx)(`button`,{type:`button`,className:`hq-token-tab`+(s===`password`?` active`:``),onClick:()=>c(`password`),children:`Password`})]}):null,s===`token`||!o?(0,J.jsx)(Me,{hadToken:e}):(0,J.jsx)(Ne,{})]})}):(0,J.jsx)(`div`,{className:`hq-token-gate`,children:(0,J.jsxs)(`div`,{className:`hq-token-card`,children:[(0,J.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),(0,J.jsx)(`div`,{className:`hq-token-title`,children:`Checking auth mode…`})]})})}function Me({hadToken:e}){let[t,n]=(0,S.useState)(``),r=()=>{let e=t.trim();e.length!==0&&(k(e),window.location.reload())};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`hq-token-title`,children:`Browser token required`}),(0,J.jsx)(`p`,{className:`hq-token-text`,children:e?`The saved token was rejected — it may have been revoked or the server was reset. Paste a current browser token.`:`This HQ server runs in token mode. Paste the browser token printed at startup (the ?token= value in the URL wstack --hq shows).`}),(0,J.jsx)(`input`,{className:`hq-token-input`,type:`password`,placeholder:`browser token`,autoComplete:`off`,value:t,onChange:e=>n(e.target.value),onKeyDown:e=>{e.key===`Enter`&&r()}}),(0,J.jsx)(`button`,{type:`button`,className:`hq-token-submit`,onClick:r,disabled:t.trim().length===0,children:`Connect`}),(0,J.jsxs)(`p`,{className:`hq-token-hint`,children:[`Manage tokens with `,(0,J.jsx)(`code`,{children:`wstack hq token list`}),` / `,(0,J.jsx)(`code`,{children:`wstack hq token create`}),` — they live in `,(0,J.jsx)(`code`,{children:`~/.wrongstack/hq/auth.json`}),`.`]})]})}function Ne(){let[e,t]=(0,S.useState)(``),[n,r]=(0,S.useState)(null),[i,a]=(0,S.useState)(!1),o=async()=>{let t=e;if(t.length!==0){a(!0),r(null);try{let e=await fetch(`/api/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({password:t})});if(!e.ok){let t=`Login failed.`;try{let n=(await e.json()).error;typeof n==`string`?t=n:typeof n?.message==`string`&&(t=n.message)}catch{}r(t),a(!1);return}A(),window.location.reload()}catch{r(`Network error. Is the HQ server running?`),a(!1)}}};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`hq-token-title`,children:`Password required`}),(0,J.jsx)(`p`,{className:`hq-token-text`,children:`This HQ server is protected by a password. Enter it to open the dashboard.`}),n?(0,J.jsx)(`p`,{className:`hq-token-error`,children:n}):null,(0,J.jsx)(`input`,{className:`hq-token-input`,type:`password`,placeholder:`password`,autoComplete:`current-password`,value:e,onChange:e=>t(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()}}),(0,J.jsx)(`button`,{type:`button`,className:`hq-token-submit`,onClick:()=>void o(),disabled:e.length===0||i,children:i?`Logging in…`:`Log in`}),(0,J.jsxs)(`p`,{className:`hq-token-hint`,children:[`Set or change the password with `,(0,J.jsx)(`code`,{children:`wstack --hq --password <secret>`}),`.`]})]})}var Pe=`modulepreload`,Fe=function(e){return`/`+e},Ie={},Y=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Fe(t,n),t=s(t),t in Ie)return;Ie[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Pe,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Le=360*60*1e3,X=[{id:`cockpit`,label:`Cockpit`,eyebrow:`Fleet overview`,description:`Health, active work, alerts, cost and command shortcuts.`,group:`Operations`,icon:i,shortcut:1},{id:`fleet`,label:`Fleet Map`,eyebrow:`Topology`,description:`Machines, projects, terminals and agents in one live graph.`,group:`Operations`,icon:h,shortcut:2},{id:`console`,label:`Live Console`,eyebrow:`Transcripts`,description:`Stream and inspect session or agent conversations.`,group:`Operations`,icon:o,shortcut:3},{id:`mailbox`,label:`Mailbox`,eyebrow:`Coordination`,description:`Cross-project messages, unread work and direct delivery.`,group:`Operations`,icon:g,shortcut:4},{id:`alerts`,label:`Alerts`,eyebrow:`Attention`,description:`Active fleet warnings and alert transition history.`,group:`Intelligence`,icon:n,shortcut:5},{id:`cost`,label:`Cost`,eyebrow:`Economics`,description:`Project, provider and model spending distribution.`,group:`Intelligence`,icon:v,shortcut:6},{id:`trends`,label:`Trends`,eyebrow:`Telemetry`,description:`Cost, token and tool activity over time.`,group:`Intelligence`,icon:r,shortcut:7},{id:`brain`,label:`Brain`,eyebrow:`Decisions`,description:`Autonomous decisions, escalations and interventions.`,group:`Intelligence`,icon:l,shortcut:8},{id:`worktree`,label:`Worktrees`,eyebrow:`Workspace`,description:`Distributed branches, worktrees and ownership state.`,group:`System`,icon:_,shortcut:9},{id:`control`,label:`Control`,eyebrow:`Command plane`,description:`Steer, queue, broadcast and audit remote commands.`,group:`System`,icon:u,shortcut:0},{id:`settings`,label:`Security`,eyebrow:`Access control`,description:`Manage the HQ browser password, authentication and active credentials.`,group:`System`,icon:m}],Re=[`Operations`,`Intelligence`,`System`],ze={cockpit:(0,S.lazy)(()=>Y(()=>import(`./cockpit-CZa8Ik0r.js`).then(e=>({default:e.CockpitView})),__vite__mapDeps([0,1,2,3]))),fleet:(0,S.lazy)(()=>Y(()=>import(`./fleet-map-VOzbj36e.js`).then(e=>({default:e.FleetMapView})),__vite__mapDeps([4,1,2,5,3,6]))),console:(0,S.lazy)(()=>Y(()=>import(`./live-console-CGxRZ15o.js`).then(e=>({default:e.LiveConsoleView})),__vite__mapDeps([7,1,2,3,6,5]))),mailbox:(0,S.lazy)(()=>Y(()=>import(`./mailbox-B3ZDFEyg.js`).then(e=>({default:e.MailboxView})),__vite__mapDeps([8,1,2,3,9]))),cost:(0,S.lazy)(()=>Y(()=>import(`./cost-C4nlUQAz.js`).then(e=>({default:e.CostView})),__vite__mapDeps([10,1,2,3]))),brain:(0,S.lazy)(()=>Y(()=>import(`./brain-B4Tdewfy.js`).then(e=>({default:e.BrainView})),__vite__mapDeps([11,2,1,3,9]))),worktree:(0,S.lazy)(()=>Y(()=>import(`./worktree-BXf7yQRK.js`).then(e=>({default:e.WorktreeView})),__vite__mapDeps([12,1,2,3,9]))),trends:(0,S.lazy)(()=>Y(()=>import(`./trends-C6j-auPf.js`).then(e=>({default:e.TrendsView})),__vite__mapDeps([13,1,2,3]))),alerts:(0,S.lazy)(()=>Y(()=>import(`./alerts-Coy0VQOD.js`).then(e=>({default:e.AlertsView})),__vite__mapDeps([14,1,2,3]))),control:(0,S.lazy)(()=>Y(()=>import(`./control-BRj__LMC.js`).then(e=>({default:e.ControlView})),__vite__mapDeps([15,1,2,3]))),settings:(0,S.lazy)(()=>Y(()=>import(`./settings-BncyJ7aj.js`).then(e=>({default:e.SettingsView})),__vite__mapDeps([16,1,2,3])))};function Be(e){return X.find(t=>t.id===e)??X[0]}var Ve=class extends S.Component{state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e.message:String(e)}}componentDidUpdate(e){e.view!==this.props.view&&this.state.error!==null&&this.setState({error:null})}render(){return this.state.error===null?this.props.children:(0,J.jsxs)(`div`,{className:`hq-view-error`,role:`alert`,children:[(0,J.jsx)(ie,{size:22}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:`This HQ surface stopped safely.`}),(0,J.jsx)(`p`,{children:this.state.error})]}),(0,J.jsxs)(`button`,{type:`button`,className:`hq-btn secondary`,onClick:()=>this.setState({error:null}),children:[(0,J.jsx)(y,{size:13}),`Retry view`]})]})}};function He(){let{snapshot:e,alerts:n,activeView:r,authRequired:i,connected:o}=I(le(e=>({snapshot:e.snapshot,alerts:e.alerts,activeView:e.activeView,authRequired:e.authRequired,connected:e.connected}))),[c,l]=(0,S.useState)(()=>typeof window>`u`||window.innerWidth>=1180),[u,f]=(0,S.useState)(null),[p,m]=(0,S.useState)(null),[h,ie]=(0,S.useState)(!1),{theme:g}=q().appearance;if((0,S.useEffect)(()=>(document.documentElement.dataset.hqTheme=g,()=>{delete document.documentElement.dataset.hqTheme}),[g]),(0,S.useEffect)(()=>{let e=!1;return L(`/api/snapshot`).then(t=>{e||I.getState()._hydrateSnapshot(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,S.useEffect)(()=>{let e=!1;return L(`/api/auth/status`).then(t=>{e||m(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,S.useEffect)(()=>{let e=!1,t=()=>{L(`/api/system/update`).then(t=>{e||f(t)}).catch(()=>{})};t();let n=window.setInterval(t,Le);return()=>{e=!0,window.clearInterval(n)}},[]),(0,S.useEffect)(()=>{let e=e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),l(e=>!e);return}if(e.altKey&&/^\d$/.test(e.key)){let t=Number(e.key),n=X.find(e=>e.shortcut===t);n&&(e.preventDefault(),I.getState().setActiveView(n.id));return}e.key===`Escape`&&c&&window.innerWidth<900&&l(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]),i)return(0,J.jsx)(je,{hadToken:j()!==null});let _=e?.totals,y=_?.unreadMailboxMessages??0,b=n.filter(e=>e.severity!==`info`).length,x=Be(r),C=x.icon,w=ze[r],T=e=>{I.getState().setActiveView(e),window.innerWidth<900&&l(!1)},E=async()=>{ie(!0);try{await M(`/api/logout`,{method:`POST`})}finally{A(),window.location.reload()}};return(0,J.jsxs)(`div`,{className:`hq-app`,"data-theme":g,"data-testid":`hq-workbench`,children:[(0,J.jsx)(`button`,{type:`button`,className:`hq-sidebar-scrim`,"data-open":c,"aria-label":`Close HQ navigation`,onClick:()=>l(!1)}),(0,J.jsxs)(`aside`,{className:`hq-secondary-nav`,"data-open":c,"aria-label":`HQ navigation`,children:[(0,J.jsxs)(`div`,{className:`hq-secondary-header`,children:[(0,J.jsxs)(`div`,{className:`hq-secondary-brand`,children:[(0,J.jsx)(`img`,{src:`/wrongstack.svg`,alt:``,"aria-hidden":`true`,draggable:!1}),(0,J.jsxs)(`div`,{className:`hq-secondary-copy`,children:[(0,J.jsx)(`span`,{className:`hq-secondary-eyebrow`,children:`Command center`}),(0,J.jsx)(`strong`,{children:`WrongStack HQ`})]})]}),(0,J.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-secondary-close`,"aria-label":`Collapse HQ navigation`,title:`Collapse navigation (Ctrl+B)`,onClick:()=>l(!1),children:(0,J.jsx)(d,{size:16})})]}),(0,J.jsx)(`div`,{className:`hq-secondary-scroll`,children:Re.map(e=>(0,J.jsxs)(`section`,{className:`hq-nav-group`,children:[(0,J.jsx)(`div`,{className:`hq-nav-group-label`,children:e}),X.filter(t=>t.group===e).map(e=>{let t=e.icon,n=e.id===`mailbox`?y:e.id===`alerts`?b:0;return(0,J.jsxs)(`button`,{type:`button`,className:`hq-nav-item`,"data-active":r===e.id,"aria-current":r===e.id?`page`:void 0,onClick:()=>T(e.id),children:[(0,J.jsx)(t,{size:15}),(0,J.jsx)(`span`,{children:e.label}),e.shortcut===void 0?null:(0,J.jsxs)(`kbd`,{children:[`Alt+`,e.shortcut]}),n>0?(0,J.jsx)(`span`,{className:`hq-nav-badge`,children:n}):null]},e.id)})]},e))}),(0,J.jsxs)(`div`,{className:`hq-secondary-footer`,children:[(0,J.jsxs)(`div`,{className:`hq-link-state`,"data-live":o,children:[(0,J.jsx)(`span`,{className:`hq-link-dot`}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o?`Connected`:`Reconnecting`}),(0,J.jsxs)(`span`,{children:[_?.activeMachines??0,` machines · `,_?.activeClients??0,` clients`]})]})]}),(0,J.jsx)(`span`,{className:`hq-build-label`,children:`@wrongstack/webui-hq`})]})]}),(0,J.jsxs)(`section`,{className:`hq-workbench`,"data-update-available":u?.outdated===!0,children:[(0,J.jsxs)(`header`,{className:`hq-header`,children:[(0,J.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-sidebar-toggle`,"aria-label":c?`Collapse HQ navigation`:`Expand HQ navigation`,"aria-expanded":c,title:`Toggle navigation (Ctrl+B)`,onClick:()=>l(e=>!e),children:c?(0,J.jsx)(d,{size:17}):(0,J.jsx)(oe,{size:17})}),(0,J.jsx)(`div`,{className:`hq-view-icon`,"aria-hidden":`true`,children:(0,J.jsx)(C,{size:18})}),(0,J.jsxs)(`div`,{className:`hq-view-identity`,children:[(0,J.jsx)(`span`,{children:x.eyebrow}),(0,J.jsx)(`h1`,{children:x.label}),(0,J.jsx)(`p`,{children:x.description})]}),(0,J.jsxs)(`div`,{className:`hq-top-metrics`,children:[(0,J.jsx)(Z,{icon:ee,label:`Machines`,value:_?.activeMachines??0}),(0,J.jsx)(Z,{icon:re,label:`Agents`,value:_?.activeAgents??0}),(0,J.jsx)(Z,{icon:s,label:`Sessions`,value:_?.activeSessions??0}),(0,J.jsx)(Z,{icon:v,label:`Cost`,value:`$${(_?.totalCostUsd??0).toFixed(2)}`,accent:!0})]}),(0,J.jsxs)(`div`,{className:`hq-connection-pill`,"data-live":o,children:[o?(0,J.jsx)(ne,{size:13}):(0,J.jsx)(te,{size:13}),o?`Live`:`Reconnecting`]}),(0,J.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-theme-toggle`,"aria-label":`Switch to ${g===`dark`?`light`:`dark`} mode`,title:`Switch to ${g===`dark`?`light`:`dark`} mode`,onClick:()=>De({theme:g===`dark`?`light`:`dark`}),children:g===`dark`?(0,J.jsx)(ae,{size:16}):(0,J.jsx)(t,{size:16})}),p?.tokenMode||p?.passwordMode?(0,J.jsx)(`button`,{type:`button`,className:`hq-icon-button`,"aria-label":`Log out of HQ`,title:`Log out and clear this tab's HQ credentials`,disabled:h,onClick:()=>void E(),children:(0,J.jsx)(a,{size:16})}):null]}),u?.outdated?(0,J.jsx)(Ue,{status:u}):null,(0,J.jsx)(`main`,{className:`hq-main`,id:`hq-main`,tabIndex:-1,children:(0,J.jsx)(Ve,{view:r,children:(0,J.jsx)(S.Suspense,{fallback:(0,J.jsx)(We,{label:x.label}),children:(0,J.jsx)(w,{})})})})]})]})}function Ue({status:e}){let[t,n]=(0,S.useState)(!1),r=async()=>{try{await navigator.clipboard.writeText(e.command),n(!0),window.setTimeout(()=>n(!1),1500)}catch{n(!1)}};return(0,J.jsxs)(`aside`,{className:`hq-update-notice`,role:`status`,"aria-live":`polite`,children:[(0,J.jsx)(f,{size:16,"aria-hidden":`true`}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:`WrongStack update available`}),(0,J.jsxs)(`span`,{children:[`v`,e.current,` → v`,e.latest,`. Run `,(0,J.jsx)(`code`,{children:e.command}),` in your terminal, then restart HQ.`]})]}),(0,J.jsxs)(`button`,{type:`button`,onClick:()=>void r(),title:`Copy update command`,children:[(0,J.jsx)(p,{size:13,"aria-hidden":`true`}),t?`Copied`:`Copy command`]})]})}function Z({icon:e,label:t,value:n,accent:r=!1}){return(0,J.jsxs)(`div`,{className:`hq-top-metric`,"data-accent":r,children:[(0,J.jsx)(e,{size:12}),(0,J.jsx)(`span`,{children:t}),(0,J.jsx)(`strong`,{children:n})]})}function We({label:e}){return(0,J.jsxs)(`div`,{className:`hq-view-loading`,role:`status`,children:[(0,J.jsx)(u,{size:18}),(0,J.jsxs)(`span`,{children:[`Loading `,e,`…`]})]})}var Ge=25e3,Ke=1e4,qe=3e4,Je=class{ws=null;handlers=new Set;stateHandlers=new Set;reconnectAttempt=0;reconnectTimer=null;heartbeatTimer=null;lastMessageAt=0;stopped=!1;_state=`disconnected`;url;maxRetries;heartbeatIntervalMs;heartbeatTimeoutMs;maxBackoffMs;constructor(e){if(this.maxRetries=e?.maxRetries??1/0,this.heartbeatIntervalMs=e?.heartbeatIntervalMs??Ge,this.heartbeatTimeoutMs=e?.heartbeatTimeoutMs??Ke,this.maxBackoffMs=e?.maxBackoffMs??qe,e?.url)this.url=e.url;else{let e=typeof window<`u`?window.location:{host:`127.0.0.1:3499`,protocol:`http:`},t=e.protocol===`https:`?`wss:`:`ws:`,n=j(),r=`${t}//${e.host}/ws/browser`;this.url=n===null?r:`${r}?token=${encodeURIComponent(n)}`}}get state(){return this._state}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}connect(){if(this.stopped||this.ws!==null)return;this.emitState(`connecting`);let e;try{e=new WebSocket(this.url)}catch{this.scheduleReconnect();return}this.ws=e,e.onopen=()=>{this.reconnectAttempt=0,this.lastMessageAt=Date.now(),this.emitState(`connected`),this.startHeartbeat()},e.onmessage=e=>{this.lastMessageAt=Date.now();try{let t=JSON.parse(typeof e.data==`string`?e.data:``);for(let e of this.handlers)try{e(t)}catch{}}catch{}},e.onclose=()=>this.handleClose(`close`),e.onerror=()=>this.handleClose(`error`)}close(){this.stopped=!0,this.stopHeartbeat(),this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws?.close(1e3,`client closed`),this.ws=null,this.emitState(`disconnected`)}on(e){return this.handlers.add(e),()=>this.handlers.delete(e)}onStateChange(e){return this.stateHandlers.add(e),e(this._state),()=>this.stateHandlers.delete(e)}handleClose(e){this.ws!==null&&(this.ws=null,this.stopHeartbeat(),this.scheduleReconnect())}scheduleReconnect(){if(this.stopped||this.reconnectTimer!==null)return;if(this.reconnectAttempt>=this.maxRetries){this.emitState(`disconnected`);return}let e=1e3*2**Math.min(this.reconnectAttempt,4)*(.5+Math.random()*.5),t=Math.min(e,this.maxBackoffMs);this.reconnectAttempt++,this.emitState(`reconnecting`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t)}get isHeartbeatTimedOut(){return this.ws===null||Date.now()-this.lastMessageAt>this.heartbeatIntervalMs+this.heartbeatTimeoutMs}startHeartbeat(){this.stopHeartbeat(),this.lastMessageAt=Date.now(),this.heartbeatTimer=setInterval(()=>{this.isHeartbeatTimedOut&&this.ws!==null&&(this.ws.close(4e3,`heartbeat timeout`),this.ws=null,this.scheduleReconnect())},this.heartbeatIntervalMs)}stopHeartbeat(){this.heartbeatTimer!==null&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}emitState(e){this._state=e;for(let t of this.stateHandlers)try{t(e)}catch{}}},Q=null;function Ye(){return Q===null&&(Q=new Je,Q.connect()),Q}var $=document.getElementById(`root`);if($!==null){fe();let e=Ye();e.onStateChange(e=>{I.getState()._setConnected(e===`connected`)}),e.on(e=>{e.type===`hq.snapshot`?I.getState()._onSnapshot(e.snapshot):e.type===`hq.event`?I.getState()._onEvent(e.event):e.type===`hq.alert`?I.getState()._onAlert(e):e.type===`hq.command_status`&&I.getState()._onCommandStatus(e.command)}),(0,C.createRoot)($).render((0,J.jsx)(S.StrictMode,{children:(0,J.jsx)(He,{})}))}export{q as a,ye as c,A as d,le as f,Ae as i,I as l,Ee as n,L as o,Oe as r,be as s,ke as t,M as u};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/cockpit-DP0tuuzs.js","assets/rolldown-runtime-QTnfLwEv.js","assets/icons-BlGYTg3M.js","assets/markdown-Dm2qU66U.js","assets/fleet-map-BtYC_Ydf.js","assets/vendor-BoaR8QxN.js","assets/fleet-topology-C_gii-RC.js","assets/live-console-BlqOehGt.js","assets/mailbox-BCg0PskE.js","assets/use-backfilled-events-DMTqAxHb.js","assets/cost-D2BIAuKs.js","assets/brain-DU8mix0V.js","assets/worktree-C_TC9kKj.js","assets/trends-DWnLrGaS.js","assets/alerts-CWaseVj8.js","assets/control-CynJZLcm.js","assets/settings-DdncdaZK.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{A as t,At as n,Et as r,G as i,L as a,M as o,Mt as s,Nt as c,Ot as l,S as u,T as d,_ as ee,a as te,c as f,ft as p,g as m,i as ne,k as h,o as re,p as ie,q as g,tt as _,u as ae,vt as v,w as oe,x as y}from"./icons-BlGYTg3M.js";import{t as b}from"./vendor-BoaR8QxN.js";import{i as x}from"./markdown-Dm2qU66U.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var S=e(c(),1),C=b(),w=e=>Symbol.iterator in e,T=e=>`entries`in e,E=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},se=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function ce(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:w(e)&&w(t)?T(e)&&T(t)?E(e,t):se(e,t):E({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function le(e){let t=S.useRef(void 0);return n=>{let r=e(n);return ce(t.current,r)?t.current:t.current=r}}var D=`wrongstack.hq.token.v1`;function ue(){if(typeof window>`u`)return null;try{let e=new URLSearchParams(window.location.search).get(`token`);return e!==null&&e.length>0?e:null}catch{return null}}function O(){if(typeof window>`u`)return null;try{return window.sessionStorage??null}catch{return null}}function de(){try{let e=O()?.getItem(D)??null;return e!==null&&e.length>0?e:null}catch{return null}}function k(e){try{O()?.setItem(D,e)}catch{}}function A(){try{O()?.removeItem(D)}catch{}}function j(){let e=ue();return e===null?de():(k(e),e)}function fe(){if(typeof window>`u`)return;let e=ue();if(e!==null&&(k(e),de()===e))try{let e=new URL(window.location.href);e.searchParams.delete(`token`),window.history.replaceState(null,``,`${e.pathname}${e.search}${e.hash}`)}catch{}}function pe(){let e=j();return e===null?{}:{Authorization:`Bearer ${e}`}}function M(e,t){let n={...t?.headers??{},...pe()};return fetch(e,{...t,headers:n})}var N=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},me=(e=>e?N(e):N),he=e=>e;function ge(e,t=he){let n=S.useSyncExternalStore(e.subscribe,S.useCallback(()=>t(e.getState()),[e,t]),S.useCallback(()=>t(e.getInitialState()),[e,t]));return S.useDebugValue(n),n}var P=e=>{let t=me(e),n=e=>ge(t,e);return Object.assign(n,t),n},_e=(e=>e?P(e):P);function F(e,t){let n=t.liveSessions??[],r=e.selectedSessionId===null?void 0:n.find(t=>t.sessionId===e.selectedSessionId),i=e.selectedAgentId===null||r?.agents.some(t=>t.id===e.selectedAgentId)===!0,a=e.selectedClientId===null||t.clients.some(t=>t.clientId===e.selectedClientId);return{snapshot:t,...e.selectedSessionId!==null&&r===void 0?{selectedSessionId:null,selectedAgentId:null}:i?{}:{selectedAgentId:null},...a?{}:{selectedClientId:null}}}function ve(e,t){return e.timestamp===t.timestamp&&e.severity===t.severity&&e.message===t.message}var I=_e()(e=>({snapshot:null,events:[],alerts:[],commandStatuses:[],activeView:`cockpit`,selectedSessionId:null,selectedAgentId:null,selectedClientId:null,connected:!1,authRequired:!1,setActiveView:t=>e({activeView:t}),selectSession:(t,n=null)=>e({selectedSessionId:t,selectedAgentId:n}),selectAgent:(t,n)=>e({selectedSessionId:t,selectedAgentId:n}),selectClient:t=>e({selectedClientId:t}),markAuthRequired:()=>e(e=>e.authRequired?{}:{authRequired:!0}),_hydrateSnapshot:t=>e(e=>e.snapshot===null?F(e,t):{}),_onSnapshot:t=>e(e=>({...F(e,t),connected:!0})),_onEvent:t=>e(e=>e.events.some(e=>e.id===t.id)?{}:{events:[...e.events,t].slice(-500)}),_onAlert:t=>e(e=>e.alerts.some(e=>ve(e,t))?{}:{alerts:[...e.alerts,t].slice(-100)}),_onCommandStatus:t=>e(e=>{let n=e.commandStatuses.findIndex(e=>e.commandId===t.commandId);if(n<0)return{commandStatuses:[...e.commandStatuses,t].slice(-200)};let r=[...e.commandStatuses];return r[n]=t,{commandStatuses:r}}),_setConnected:t=>e({connected:t})}));async function L(e){let t;try{t=await M(e)}catch{throw Error(`Network error fetching ${e}`)}if(t.status===401)throw I.getState().markAuthRequired(),Error(`401 Unauthorized fetching ${e} — browser token required`);if(!t.ok)throw Error(`${t.status} ${t.statusText}`);try{return await t.json()}catch{throw Error(`Invalid JSON response from ${e}: ${t.status}`)}}async function ye(e){let t;try{t=await M(`/api/mailbox-send`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)})}catch{throw Error(`Network error sending mailbox message`)}if(t.status===401)throw I.getState().markAuthRequired(),Error(`401 Unauthorized — browser token required`);if(!t.ok){let e=await t.json().catch(()=>null),n=typeof e?.error==`string`?e.error:t.statusText||`HTTP ${t.status}`;throw Error(n)}try{return await t.json()}catch{throw Error(`Invalid JSON response from mailbox-send API`)}}async function be(e,t,n){let r;try{r=await M(`/api/command`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({clientId:e,type:t,payload:n})})}catch{throw Error(`Network error sending command`)}if(r.status===401)throw I.getState().markAuthRequired(),Error(`401 Unauthorized — browser token required`);if(!r.ok){let e=(await r.json().catch(()=>null))?.error??(r.statusText||`HTTP ${r.status}`);throw Error(e)}try{return await r.json()}catch{throw Error(`Invalid JSON response from command API`)}}var R=`wrongstack.hq.local-prefs.v1`,z={appearance:{theme:`dark`},fleet:{scope:`all`,layout:`map`,machineId:``,projectId:``},console:{delivery:`steer`,subject:``,body:``},control:{cmdType:`steer`,abortTarget:`leader`,spawnRole:`bug-hunter`,spawnTask:``,steerTo:`leader`,steerSubject:``,steerBody:``,broadcastSubject:``,broadcastBody:``},mailbox:{query:``,types:[],priorities:[],includeCompleted:!0}},B=null,V=new Set;function H(){for(let e of V)e()}function U(e){return typeof structuredClone==`function`?structuredClone(e):JSON.parse(JSON.stringify(e))}function W(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xe(){if(typeof window>`u`||window.localStorage===void 0)return U(z);try{let e=window.localStorage.getItem(R);return e===null?U(z):Se(JSON.parse(e))}catch{return U(z)}}function Se(e){if(!W(e))return U(z);let t=W(e.appearance)?e.appearance:{},n=W(e.fleet)?e.fleet:{},r=W(e.console)?e.console:{},i=W(e.control)?e.control:{},a=W(e.mailbox)?e.mailbox:{};return{appearance:{theme:t.theme===`light`?`light`:`dark`},fleet:{scope:n.scope===`machine`||n.scope===`project`?n.scope:`all`,layout:n.layout===`compact`?`compact`:`map`,machineId:typeof n.machineId==`string`?n.machineId:``,projectId:typeof n.projectId==`string`?n.projectId:``},console:{delivery:r.delivery===`btw`||r.delivery===`queue`?r.delivery:`steer`,subject:typeof r.subject==`string`?r.subject:``,body:typeof r.body==`string`?r.body:``},control:{cmdType:i.cmdType===`btw`||i.cmdType===`queue`||i.cmdType===`abort`||i.cmdType===`spawn`||i.cmdType===`broadcast`||i.cmdType===`run-command`?i.cmdType:z.control.cmdType,abortTarget:i.abortTarget===`fleet`?`fleet`:`leader`,spawnRole:typeof i.spawnRole==`string`&&i.spawnRole.length>0?i.spawnRole:z.control.spawnRole,spawnTask:typeof i.spawnTask==`string`?i.spawnTask:z.control.spawnTask,steerTo:typeof i.steerTo==`string`?i.steerTo:z.control.steerTo,steerSubject:typeof i.steerSubject==`string`?i.steerSubject:z.control.steerSubject,steerBody:typeof i.steerBody==`string`?i.steerBody:z.control.steerBody,broadcastSubject:typeof i.broadcastSubject==`string`?i.broadcastSubject:z.control.broadcastSubject,broadcastBody:typeof i.broadcastBody==`string`?i.broadcastBody:z.control.broadcastBody},mailbox:{query:typeof a.query==`string`?a.query:z.mailbox.query,types:Array.isArray(a.types)?a.types.filter(e=>typeof e==`string`):[],priorities:Array.isArray(a.priorities)?a.priorities.filter(e=>typeof e==`string`):[],includeCompleted:typeof a.includeCompleted!=`boolean`||a.includeCompleted}}}function G(){return B===null&&(B=xe()),B}function K(e){if(!(typeof window>`u`||window.localStorage===void 0))try{window.localStorage.setItem(R,JSON.stringify(e))}catch{}}function Ce(e){return V.add(e),()=>V.delete(e)}function we(){return G()}function Te(){return z}function q(){return(0,S.useSyncExternalStore)(Ce,we,Te)}function Ee(e){let t=G();B={...t,control:{...t.control,...e}},K(B),H()}function De(e){let t=G();B={...t,appearance:{...t.appearance,...e}},K(B),H()}function Oe(e){let t=G();B={...t,fleet:{...t.fleet,...e}},K(B),H()}function ke(e){let t=G();B={...t,console:{...t.console,...e}},K(B),H()}function Ae(e){let t=G();B={...t,mailbox:{...t.mailbox,...e}},K(B),H()}var J=x();function je({hadToken:e}){let[t,n]=(0,S.useState)(null),[r,i]=(0,S.useState)(null);(0,S.useEffect)(()=>{fetch(`/api/auth/status`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return await e.json()}).then(n).catch(()=>i(`Could not load HQ auth status.`))},[]);let a=t?.tokenMode??!0,o=t?.passwordMode??!1,[s,c]=(0,S.useState)(`token`);return(0,S.useEffect)(()=>{t&&c(t.passwordMode?`password`:`token`)},[t]),r?(0,J.jsx)(`div`,{className:`hq-token-gate`,children:(0,J.jsxs)(`div`,{className:`hq-token-card`,children:[(0,J.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),(0,J.jsx)(`div`,{className:`hq-token-title`,children:`Auth status unavailable`}),(0,J.jsx)(`p`,{className:`hq-token-text`,children:r})]})}):t?(0,J.jsx)(`div`,{className:`hq-token-gate`,children:(0,J.jsxs)(`div`,{className:`hq-token-card`,children:[(0,J.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),a&&o?(0,J.jsxs)(`div`,{className:`hq-token-tabs`,children:[(0,J.jsx)(`button`,{type:`button`,className:`hq-token-tab`+(s===`token`?` active`:``),onClick:()=>c(`token`),children:`Browser token`}),(0,J.jsx)(`button`,{type:`button`,className:`hq-token-tab`+(s===`password`?` active`:``),onClick:()=>c(`password`),children:`Password`})]}):null,s===`token`||!o?(0,J.jsx)(Me,{hadToken:e}):(0,J.jsx)(Ne,{})]})}):(0,J.jsx)(`div`,{className:`hq-token-gate`,children:(0,J.jsxs)(`div`,{className:`hq-token-card`,children:[(0,J.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),(0,J.jsx)(`div`,{className:`hq-token-title`,children:`Checking auth mode…`})]})})}function Me({hadToken:e}){let[t,n]=(0,S.useState)(``),r=()=>{let e=t.trim();e.length!==0&&(k(e),window.location.reload())};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`hq-token-title`,children:`Browser token required`}),(0,J.jsx)(`p`,{className:`hq-token-text`,children:e?`The saved token was rejected — it may have been revoked or the server was reset. Paste a current browser token.`:`This HQ server runs in token mode. Paste the browser token printed at startup (the ?token= value in the URL wstack --hq shows).`}),(0,J.jsx)(`input`,{className:`hq-token-input`,type:`password`,placeholder:`browser token`,autoComplete:`off`,value:t,onChange:e=>n(e.target.value),onKeyDown:e=>{e.key===`Enter`&&r()}}),(0,J.jsx)(`button`,{type:`button`,className:`hq-token-submit`,onClick:r,disabled:t.trim().length===0,children:`Connect`}),(0,J.jsxs)(`p`,{className:`hq-token-hint`,children:[`Manage tokens with `,(0,J.jsx)(`code`,{children:`wstack hq token list`}),` / `,(0,J.jsx)(`code`,{children:`wstack hq token create`}),` — they live in `,(0,J.jsx)(`code`,{children:`~/.wrongstack/hq/auth.json`}),`.`]})]})}function Ne(){let[e,t]=(0,S.useState)(``),[n,r]=(0,S.useState)(null),[i,a]=(0,S.useState)(!1),o=async()=>{let t=e;if(t.length!==0){a(!0),r(null);try{let e=await fetch(`/api/login`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({password:t})});if(!e.ok){let t=`Login failed.`;try{let n=(await e.json()).error;typeof n==`string`?t=n:typeof n?.message==`string`&&(t=n.message)}catch{}r(t),a(!1);return}A(),window.location.reload()}catch{r(`Network error. Is the HQ server running?`),a(!1)}}};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`hq-token-title`,children:`Password required`}),(0,J.jsx)(`p`,{className:`hq-token-text`,children:`This HQ server is protected by a password. Enter it to open the dashboard.`}),n?(0,J.jsx)(`p`,{className:`hq-token-error`,children:n}):null,(0,J.jsx)(`input`,{className:`hq-token-input`,type:`password`,placeholder:`password`,autoComplete:`current-password`,value:e,onChange:e=>t(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()}}),(0,J.jsx)(`button`,{type:`button`,className:`hq-token-submit`,onClick:()=>void o(),disabled:e.length===0||i,children:i?`Logging in…`:`Log in`}),(0,J.jsxs)(`p`,{className:`hq-token-hint`,children:[`Set or change the password with `,(0,J.jsx)(`code`,{children:`wstack --hq --password <secret>`}),`.`]})]})}var Pe=`modulepreload`,Fe=function(e){return`/`+e},Ie={},Y=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Fe(t,n),t=s(t),t in Ie)return;Ie[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Pe,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Le=360*60*1e3,X=[{id:`cockpit`,label:`Cockpit`,eyebrow:`Fleet overview`,description:`Health, active work, alerts, cost and command shortcuts.`,group:`Operations`,icon:i,shortcut:1},{id:`fleet`,label:`Fleet Map`,eyebrow:`Topology`,description:`Machines, projects, terminals and agents in one live graph.`,group:`Operations`,icon:h,shortcut:2},{id:`console`,label:`Live Console`,eyebrow:`Transcripts`,description:`Stream and inspect session or agent conversations.`,group:`Operations`,icon:o,shortcut:3},{id:`mailbox`,label:`Mailbox`,eyebrow:`Coordination`,description:`Cross-project messages, unread work and direct delivery.`,group:`Operations`,icon:g,shortcut:4},{id:`alerts`,label:`Alerts`,eyebrow:`Attention`,description:`Active fleet warnings and alert transition history.`,group:`Intelligence`,icon:n,shortcut:5},{id:`cost`,label:`Cost`,eyebrow:`Economics`,description:`Project, provider and model spending distribution.`,group:`Intelligence`,icon:v,shortcut:6},{id:`trends`,label:`Trends`,eyebrow:`Telemetry`,description:`Cost, token and tool activity over time.`,group:`Intelligence`,icon:r,shortcut:7},{id:`brain`,label:`Brain`,eyebrow:`Decisions`,description:`Autonomous decisions, escalations and interventions.`,group:`Intelligence`,icon:l,shortcut:8},{id:`worktree`,label:`Worktrees`,eyebrow:`Workspace`,description:`Distributed branches, worktrees and ownership state.`,group:`System`,icon:_,shortcut:9},{id:`control`,label:`Control`,eyebrow:`Command plane`,description:`Steer, queue, broadcast and audit remote commands.`,group:`System`,icon:u,shortcut:0},{id:`settings`,label:`Security`,eyebrow:`Access control`,description:`Manage the HQ browser password, authentication and active credentials.`,group:`System`,icon:m}],Re=[`Operations`,`Intelligence`,`System`],ze={cockpit:(0,S.lazy)(()=>Y(()=>import(`./cockpit-DP0tuuzs.js`).then(e=>({default:e.CockpitView})),__vite__mapDeps([0,1,2,3]))),fleet:(0,S.lazy)(()=>Y(()=>import(`./fleet-map-BtYC_Ydf.js`).then(e=>({default:e.FleetMapView})),__vite__mapDeps([4,1,2,5,3,6]))),console:(0,S.lazy)(()=>Y(()=>import(`./live-console-BlqOehGt.js`).then(e=>({default:e.LiveConsoleView})),__vite__mapDeps([7,1,2,3,6,5]))),mailbox:(0,S.lazy)(()=>Y(()=>import(`./mailbox-BCg0PskE.js`).then(e=>({default:e.MailboxView})),__vite__mapDeps([8,1,2,3,9]))),cost:(0,S.lazy)(()=>Y(()=>import(`./cost-D2BIAuKs.js`).then(e=>({default:e.CostView})),__vite__mapDeps([10,1,2,3]))),brain:(0,S.lazy)(()=>Y(()=>import(`./brain-DU8mix0V.js`).then(e=>({default:e.BrainView})),__vite__mapDeps([11,2,1,3,9]))),worktree:(0,S.lazy)(()=>Y(()=>import(`./worktree-C_TC9kKj.js`).then(e=>({default:e.WorktreeView})),__vite__mapDeps([12,1,2,3,9]))),trends:(0,S.lazy)(()=>Y(()=>import(`./trends-DWnLrGaS.js`).then(e=>({default:e.TrendsView})),__vite__mapDeps([13,1,2,3]))),alerts:(0,S.lazy)(()=>Y(()=>import(`./alerts-CWaseVj8.js`).then(e=>({default:e.AlertsView})),__vite__mapDeps([14,1,2,3]))),control:(0,S.lazy)(()=>Y(()=>import(`./control-CynJZLcm.js`).then(e=>({default:e.ControlView})),__vite__mapDeps([15,1,2,3]))),settings:(0,S.lazy)(()=>Y(()=>import(`./settings-DdncdaZK.js`).then(e=>({default:e.SettingsView})),__vite__mapDeps([16,1,2,3])))};function Be(e){return X.find(t=>t.id===e)??X[0]}var Ve=class extends S.Component{state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e.message:String(e)}}componentDidUpdate(e){e.view!==this.props.view&&this.state.error!==null&&this.setState({error:null})}render(){return this.state.error===null?this.props.children:(0,J.jsxs)(`div`,{className:`hq-view-error`,role:`alert`,children:[(0,J.jsx)(ie,{size:22}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:`This HQ surface stopped safely.`}),(0,J.jsx)(`p`,{children:this.state.error})]}),(0,J.jsxs)(`button`,{type:`button`,className:`hq-btn secondary`,onClick:()=>this.setState({error:null}),children:[(0,J.jsx)(y,{size:13}),`Retry view`]})]})}};function He(){let{snapshot:e,alerts:n,activeView:r,authRequired:i,connected:o}=I(le(e=>({snapshot:e.snapshot,alerts:e.alerts,activeView:e.activeView,authRequired:e.authRequired,connected:e.connected}))),[c,l]=(0,S.useState)(()=>typeof window>`u`||window.innerWidth>=1180),[u,f]=(0,S.useState)(null),[p,m]=(0,S.useState)(null),[h,ie]=(0,S.useState)(!1),{theme:g}=q().appearance;if((0,S.useEffect)(()=>(document.documentElement.dataset.hqTheme=g,()=>{delete document.documentElement.dataset.hqTheme}),[g]),(0,S.useEffect)(()=>{let e=!1;return L(`/api/snapshot`).then(t=>{e||I.getState()._hydrateSnapshot(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,S.useEffect)(()=>{let e=!1;return L(`/api/auth/status`).then(t=>{e||m(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,S.useEffect)(()=>{let e=!1,t=()=>{L(`/api/system/update`).then(t=>{e||f(t)}).catch(()=>{})};t();let n=window.setInterval(t,Le);return()=>{e=!0,window.clearInterval(n)}},[]),(0,S.useEffect)(()=>{let e=e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),l(e=>!e);return}if(e.altKey&&/^\d$/.test(e.key)){let t=Number(e.key),n=X.find(e=>e.shortcut===t);n&&(e.preventDefault(),I.getState().setActiveView(n.id));return}e.key===`Escape`&&c&&window.innerWidth<900&&l(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[c]),i)return(0,J.jsx)(je,{hadToken:j()!==null});let _=e?.totals,y=_?.unreadMailboxMessages??0,b=n.filter(e=>e.severity!==`info`).length,x=Be(r),C=x.icon,w=ze[r],T=e=>{I.getState().setActiveView(e),window.innerWidth<900&&l(!1)},E=async()=>{ie(!0);try{await M(`/api/logout`,{method:`POST`})}finally{A(),window.location.reload()}};return(0,J.jsxs)(`div`,{className:`hq-app`,"data-theme":g,"data-testid":`hq-workbench`,children:[(0,J.jsx)(`button`,{type:`button`,className:`hq-sidebar-scrim`,"data-open":c,"aria-label":`Close HQ navigation`,onClick:()=>l(!1)}),(0,J.jsxs)(`aside`,{className:`hq-secondary-nav`,"data-open":c,"aria-label":`HQ navigation`,children:[(0,J.jsxs)(`div`,{className:`hq-secondary-header`,children:[(0,J.jsxs)(`div`,{className:`hq-secondary-brand`,children:[(0,J.jsx)(`img`,{src:`/wrongstack.svg`,alt:``,"aria-hidden":`true`,draggable:!1}),(0,J.jsxs)(`div`,{className:`hq-secondary-copy`,children:[(0,J.jsx)(`span`,{className:`hq-secondary-eyebrow`,children:`Command center`}),(0,J.jsx)(`strong`,{children:`WrongStack HQ`})]})]}),(0,J.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-secondary-close`,"aria-label":`Collapse HQ navigation`,title:`Collapse navigation (Ctrl+B)`,onClick:()=>l(!1),children:(0,J.jsx)(d,{size:16})})]}),(0,J.jsx)(`div`,{className:`hq-secondary-scroll`,children:Re.map(e=>(0,J.jsxs)(`section`,{className:`hq-nav-group`,children:[(0,J.jsx)(`div`,{className:`hq-nav-group-label`,children:e}),X.filter(t=>t.group===e).map(e=>{let t=e.icon,n=e.id===`mailbox`?y:e.id===`alerts`?b:0;return(0,J.jsxs)(`button`,{type:`button`,className:`hq-nav-item`,"data-active":r===e.id,"aria-current":r===e.id?`page`:void 0,onClick:()=>T(e.id),children:[(0,J.jsx)(t,{size:15}),(0,J.jsx)(`span`,{children:e.label}),e.shortcut===void 0?null:(0,J.jsxs)(`kbd`,{children:[`Alt+`,e.shortcut]}),n>0?(0,J.jsx)(`span`,{className:`hq-nav-badge`,children:n}):null]},e.id)})]},e))}),(0,J.jsxs)(`div`,{className:`hq-secondary-footer`,children:[(0,J.jsxs)(`div`,{className:`hq-link-state`,"data-live":o,children:[(0,J.jsx)(`span`,{className:`hq-link-dot`}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o?`Connected`:`Reconnecting`}),(0,J.jsxs)(`span`,{children:[_?.activeMachines??0,` machines · `,_?.activeClients??0,` clients`]})]})]}),(0,J.jsx)(`span`,{className:`hq-build-label`,children:`@wrongstack/webui-hq`})]})]}),(0,J.jsxs)(`section`,{className:`hq-workbench`,"data-update-available":u?.outdated===!0,children:[(0,J.jsxs)(`header`,{className:`hq-header`,children:[(0,J.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-sidebar-toggle`,"aria-label":c?`Collapse HQ navigation`:`Expand HQ navigation`,"aria-expanded":c,title:`Toggle navigation (Ctrl+B)`,onClick:()=>l(e=>!e),children:c?(0,J.jsx)(d,{size:17}):(0,J.jsx)(oe,{size:17})}),(0,J.jsx)(`div`,{className:`hq-view-icon`,"aria-hidden":`true`,children:(0,J.jsx)(C,{size:18})}),(0,J.jsxs)(`div`,{className:`hq-view-identity`,children:[(0,J.jsx)(`span`,{children:x.eyebrow}),(0,J.jsx)(`h1`,{children:x.label}),(0,J.jsx)(`p`,{children:x.description})]}),(0,J.jsxs)(`div`,{className:`hq-top-metrics`,children:[(0,J.jsx)(Z,{icon:ee,label:`Machines`,value:_?.activeMachines??0}),(0,J.jsx)(Z,{icon:re,label:`Agents`,value:_?.activeAgents??0}),(0,J.jsx)(Z,{icon:s,label:`Sessions`,value:_?.activeSessions??0}),(0,J.jsx)(Z,{icon:v,label:`Cost`,value:`$${(_?.totalCostUsd??0).toFixed(2)}`,accent:!0})]}),(0,J.jsxs)(`div`,{className:`hq-connection-pill`,"data-live":o,children:[o?(0,J.jsx)(ne,{size:13}):(0,J.jsx)(te,{size:13}),o?`Live`:`Reconnecting`]}),(0,J.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-theme-toggle`,"aria-label":`Switch to ${g===`dark`?`light`:`dark`} mode`,title:`Switch to ${g===`dark`?`light`:`dark`} mode`,onClick:()=>De({theme:g===`dark`?`light`:`dark`}),children:g===`dark`?(0,J.jsx)(ae,{size:16}):(0,J.jsx)(t,{size:16})}),p?.tokenMode||p?.passwordMode?(0,J.jsx)(`button`,{type:`button`,className:`hq-icon-button`,"aria-label":`Log out of HQ`,title:`Log out and clear this tab's HQ credentials`,disabled:h,onClick:()=>void E(),children:(0,J.jsx)(a,{size:16})}):null]}),u?.outdated?(0,J.jsx)(Ue,{status:u}):null,(0,J.jsx)(`main`,{className:`hq-main`,id:`hq-main`,tabIndex:-1,children:(0,J.jsx)(Ve,{view:r,children:(0,J.jsx)(S.Suspense,{fallback:(0,J.jsx)(We,{label:x.label}),children:(0,J.jsx)(w,{})})})})]})]})}function Ue({status:e}){let[t,n]=(0,S.useState)(!1),r=async()=>{try{await navigator.clipboard.writeText(e.command),n(!0),window.setTimeout(()=>n(!1),1500)}catch{n(!1)}};return(0,J.jsxs)(`aside`,{className:`hq-update-notice`,role:`status`,"aria-live":`polite`,children:[(0,J.jsx)(f,{size:16,"aria-hidden":`true`}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:`WrongStack update available`}),(0,J.jsxs)(`span`,{children:[`v`,e.current,` → v`,e.latest,`. Run `,(0,J.jsx)(`code`,{children:e.command}),` in your terminal, then restart HQ.`]})]}),(0,J.jsxs)(`button`,{type:`button`,onClick:()=>void r(),title:`Copy update command`,children:[(0,J.jsx)(p,{size:13,"aria-hidden":`true`}),t?`Copied`:`Copy command`]})]})}function Z({icon:e,label:t,value:n,accent:r=!1}){return(0,J.jsxs)(`div`,{className:`hq-top-metric`,"data-accent":r,children:[(0,J.jsx)(e,{size:12}),(0,J.jsx)(`span`,{children:t}),(0,J.jsx)(`strong`,{children:n})]})}function We({label:e}){return(0,J.jsxs)(`div`,{className:`hq-view-loading`,role:`status`,children:[(0,J.jsx)(u,{size:18}),(0,J.jsxs)(`span`,{children:[`Loading `,e,`…`]})]})}var Ge=25e3,Ke=1e4,qe=3e4,Je=class{ws=null;handlers=new Set;stateHandlers=new Set;reconnectAttempt=0;reconnectTimer=null;heartbeatTimer=null;lastMessageAt=0;stopped=!1;_state=`disconnected`;url;maxRetries;heartbeatIntervalMs;heartbeatTimeoutMs;maxBackoffMs;constructor(e){if(this.maxRetries=e?.maxRetries??1/0,this.heartbeatIntervalMs=e?.heartbeatIntervalMs??Ge,this.heartbeatTimeoutMs=e?.heartbeatTimeoutMs??Ke,this.maxBackoffMs=e?.maxBackoffMs??qe,e?.url)this.url=e.url;else{let e=typeof window<`u`?window.location:{host:`127.0.0.1:3499`,protocol:`http:`},t=e.protocol===`https:`?`wss:`:`ws:`,n=j(),r=`${t}//${e.host}/ws/browser`;this.url=n===null?r:`${r}?token=${encodeURIComponent(n)}`}}get state(){return this._state}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}connect(){if(this.stopped||this.ws!==null)return;this.emitState(`connecting`);let e;try{e=new WebSocket(this.url)}catch{this.scheduleReconnect();return}this.ws=e,e.onopen=()=>{this.reconnectAttempt=0,this.lastMessageAt=Date.now(),this.emitState(`connected`),this.startHeartbeat()},e.onmessage=e=>{this.lastMessageAt=Date.now();try{let t=JSON.parse(typeof e.data==`string`?e.data:``);for(let e of this.handlers)try{e(t)}catch{}}catch{}},e.onclose=()=>this.handleClose(`close`),e.onerror=()=>this.handleClose(`error`)}close(){this.stopped=!0,this.stopHeartbeat(),this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws?.close(1e3,`client closed`),this.ws=null,this.emitState(`disconnected`)}on(e){return this.handlers.add(e),()=>this.handlers.delete(e)}onStateChange(e){return this.stateHandlers.add(e),e(this._state),()=>this.stateHandlers.delete(e)}handleClose(e){this.ws!==null&&(this.ws=null,this.stopHeartbeat(),this.scheduleReconnect())}scheduleReconnect(){if(this.stopped||this.reconnectTimer!==null)return;if(this.reconnectAttempt>=this.maxRetries){this.emitState(`disconnected`);return}let e=1e3*2**Math.min(this.reconnectAttempt,4)*(.5+Math.random()*.5),t=Math.min(e,this.maxBackoffMs);this.reconnectAttempt++,this.emitState(`reconnecting`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t)}get isHeartbeatTimedOut(){return this.ws===null||Date.now()-this.lastMessageAt>this.heartbeatIntervalMs+this.heartbeatTimeoutMs}startHeartbeat(){this.stopHeartbeat(),this.lastMessageAt=Date.now(),this.heartbeatTimer=setInterval(()=>{this.isHeartbeatTimedOut&&this.ws!==null&&(this.ws.close(4e3,`heartbeat timeout`),this.ws=null,this.scheduleReconnect())},this.heartbeatIntervalMs)}stopHeartbeat(){this.heartbeatTimer!==null&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}emitState(e){this._state=e;for(let t of this.stateHandlers)try{t(e)}catch{}}},Q=null;function Ye(){return Q===null&&(Q=new Je,Q.connect()),Q}var $=document.getElementById(`root`);if($!==null){fe();let e=Ye();e.onStateChange(e=>{I.getState()._setConnected(e===`connected`)}),e.on(e=>{e.type===`hq.snapshot`?I.getState()._onSnapshot(e.snapshot):e.type===`hq.event`?I.getState()._onEvent(e.event):e.type===`hq.alert`?I.getState()._onAlert(e):e.type===`hq.command_status`&&I.getState()._onCommandStatus(e.command)}),(0,C.createRoot)($).render((0,J.jsx)(S.StrictMode,{children:(0,J.jsx)(He,{})}))}export{q as a,ye as c,A as d,le as f,Ae as i,I as l,Ee as n,L as o,Oe as r,be as s,ke as t,M as u};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Ct as t,D as n,J as r,M as i,Nt as a,S as o,at as s,d as c,j as l,jt as u,kt as d,v as f}from"./icons-BlGYTg3M.js";import{i as p}from"./markdown-Dm2qU66U.js";import{a as m,f as h,l as g,s as _,t as v}from"./index-Ckam6WOR.js";import{c as y,l as ee,s as b,t as x,u as S}from"./fleet-topology-CHOsHZc9.js";var C=e(a(),1);function w(e,t,n){if(e===null||t===null)return null;let r=(e.liveSessions??[]).find(e=>e.sessionId===t);if(r===void 0)return null;let i=e.sessions.find(e=>e.sessionId===t)?.clientId,a=r.clientId??i,o=e.clients.find(e=>e.connected&&e.clientId===a),s=e.clients.filter(e=>e.connected&&e.machineId===r.machineId&&e.projectId===r.projectId&&(r.pid===void 0||e.pid===r.pid)),c=(o?.capabilities.includes(`control.receive`)===!0?o:void 0)??s.find(e=>e.kind===r.clientKind&&e.capabilities.includes(`control.receive`))??s.find(e=>e.capabilities.includes(`control.receive`))??o??s[0],l=n===null?null:r.agents.find(e=>e.id===n)??null,u=n===null||n===`leader`?`leader`:n,d=e.clients.some(e=>e.connected&&e.projectId===r.projectId&&e.capabilities.includes(`mailbox.serve`));return{session:r,client:c??null,agent:l,recipient:u,controllable:c?.capabilities.includes(`control.receive`)===!0,mailboxServeActive:d}}var T=p();function E(e){let t=x(e),n=[],r=new Map,i=new Map,a=new Map,o=e=>`machine:${e.machineId}`,s=e=>`project:${e.machineId}:${e.projectId}`;for(let e of t.nodes){if(e.kind!==`machine`)continue;let t={id:e.id,label:e.label,sub:e.sub,projects:[]};r.set(e.id,t),n.push(t)}for(let e of t.nodes){if(e.kind!==`project`)continue;let t=r.get(o(e));if(t===void 0)continue;let n={id:e.id,label:e.label,clients:[]};i.set(e.id,n),t.projects.push(n)}for(let e of t.nodes){if(e.kind!==`terminal`||e.sessionId===void 0||e.serviceMode!==void 0)continue;let t=i.get(s(e));if(t===void 0)continue;let n={clientId:e.clientId,sessionId:e.sessionId,label:e.label,clientKind:e.clientKind,status:e.status,synthetic:e.isSyntheticSession===!0,agents:[]};a.set(e.sessionId,n),t.clients.push(n)}for(let e of t.nodes){if(e.kind!==`agent`||e.sessionId===void 0||e.agentId===void 0)continue;let t=a.get(e.sessionId);t!==void 0&&t.agents.push({id:e.agentId,label:e.label,status:e.status})}return n.map(e=>({...e,projects:e.projects.filter(e=>e.clients.length>0)})).filter(e=>e.projects.length>0)}function D(e){return e===`active`||e===`running`||e===`streaming`?`active`:e===`waiting_user`?`warn`:e===`error`||e===`stale`||e===`closing`?`error`:`idle`}function te({snapshot:e,selectedSessionId:n,selectedAgentId:r}){let i=(0,C.useMemo)(()=>E(e),[e]),[a,o]=(0,C.useState)(new Set),u=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return i.length===0?(0,T.jsx)(`div`,{className:`hq-fleetnav`,children:(0,T.jsx)(`div`,{className:`hq-empty hq-pad-md`,children:`No live sessions. Open a WrongStack CLI/TUI/WebUI connected to HQ.`})}):(0,T.jsx)(`div`,{className:`hq-fleetnav`,role:`tree`,"aria-label":`Fleet navigator`,children:i.map(e=>{let i=!a.has(e.id);return(0,T.jsxs)(`div`,{className:`hq-nav-machine`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row machine`,onClick:()=>u(e.id),"aria-expanded":i,children:[(0,T.jsx)(t,{size:12,className:`hq-nav-caret`+(i?` open`:``)}),(0,T.jsx)(l,{size:13}),(0,T.jsx)(`span`,{className:`hq-nav-label`,title:e.sub??e.label,children:e.label})]}),i&&e.projects.map(e=>{let i=!a.has(e.id);return(0,T.jsxs)(`div`,{className:`hq-nav-project`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row project`,onClick:()=>u(e.id),"aria-expanded":i,children:[(0,T.jsx)(t,{size:12,className:`hq-nav-caret`+(i?` open`:``)}),(0,T.jsx)(s,{size:13}),(0,T.jsx)(`span`,{className:`hq-nav-label`,title:e.label,children:e.label})]}),i&&e.clients.map(e=>{let i=!a.has(e.sessionId),o=n===e.sessionId&&r===null;return(0,T.jsxs)(`div`,{className:`hq-nav-client`,children:[(0,T.jsxs)(`div`,{className:`hq-nav-clientrow`,children:[e.agents.length>0?(0,T.jsx)(`button`,{type:`button`,className:`hq-nav-caretbtn`,onClick:()=>u(e.sessionId),"aria-label":i?`Collapse`:`Expand`,children:(0,T.jsx)(t,{size:12,className:`hq-nav-caret`+(i?` open`:``)})}):(0,T.jsx)(`span`,{className:`hq-nav-caretbtn`}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row client`+(o?` selected`:``),disabled:e.synthetic,onClick:()=>{e.synthetic||(g.getState().selectSession(e.sessionId),e.clientId!==void 0&&g.getState().selectClient(e.clientId))},title:e.synthetic?`waiting for session telemetry`:e.label,children:[(0,T.jsx)(`span`,{className:`hq-nav-dot `+D(e.status)}),(0,T.jsx)(c,{size:12}),(0,T.jsx)(`span`,{className:`hq-nav-label`,children:e.label}),e.agents.length>0&&(0,T.jsx)(`span`,{className:`hq-nav-count`,children:e.agents.length})]})]}),i&&e.agents.map(t=>(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row agent`+(n===e.sessionId&&r===t.id?` selected`:``),onClick:()=>{g.getState().selectAgent(e.sessionId,t.id),e.clientId!==void 0&&g.getState().selectClient(e.clientId)},title:t.label,children:[(0,T.jsx)(`span`,{className:`hq-nav-dot `+D(t.status)}),(0,T.jsx)(d,{size:12}),(0,T.jsx)(`span`,{className:`hq-nav-label`,children:t.label})]},t.id))]},e.sessionId)})]},e.id)})]},e.id)})})}function O(e){return e===`completed`?`active`:e===`failed`||e===`rejected`?`error`:e===`delivered`||e===`accepted`?`info`:`warn`}function k({receipt:e,lifecycle:t}){let r=new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}),i=(0,T.jsx)(`span`,{className:`hq-pill ${O(t)}`,"aria-label":`Command ${t}`,children:t});return e.type===`abort`?(0,T.jsx)(`div`,{className:`hq-chat-turn system hq-command-turn`,"data-command-id":e.commandId,children:(0,T.jsxs)(`span`,{className:`hq-chat-system-line`,children:[(0,T.jsx)(n,{size:12}),` `,e.preview,` `,i,(0,T.jsx)(`span`,{className:`hq-chat-clock`,children:r})]})}):(0,T.jsx)(`div`,{className:`hq-chat-turn user hq-command-turn`,"data-command-id":e.commandId,children:(0,T.jsxs)(`div`,{className:`hq-chat-bubble user`,children:[(0,T.jsxs)(`div`,{className:`hq-chat-role`,children:[`you → `,e.target,` · `,e.type,` `,i,(0,T.jsx)(`span`,{className:`hq-chat-clock`,children:r})]}),(0,T.jsx)(`div`,{className:`hq-chat-prose`,children:e.preview})]})})}function A(){let{selectedSessionId:e,selectedAgentId:t,snapshot:a,commandStatuses:s}=g(h(e=>({selectedSessionId:e.selectedSessionId,selectedAgentId:e.selectedAgentId,snapshot:e.snapshot,commandStatuses:e.commandStatuses}))),c=e,l=t,p=l!==null,x=m().console,[E,D]=(0,C.useState)(x.delivery),[O,A]=(0,C.useState)(x.subject),[j,M]=(0,C.useState)(x.body),[N,P]=(0,C.useState)(!1),[F,I]=(0,C.useState)(null),[L,R]=(0,C.useState)(!1),[z,B]=(0,C.useState)(!1),[V,H]=(0,C.useState)([]),U=ee(c,l),{entries:W,meta:G,stats:K}=U,q=(0,C.useMemo)(()=>V.filter(e=>{if(e.type===`abort`)return!0;let t=Date.parse(e.createdAt);return!W.some(n=>n.role===`user`&&n.text.trim()===e.preview&&Math.abs(Date.parse(n.ts)-t)<12e4)}),[W,V]);(0,C.useEffect)(()=>{if(!U.pinned||q.length===0)return;let e=window.requestAnimationFrame(()=>{U.listRef.current?.scrollToIndex(W.length+q.length-1,{align:`end`})});return()=>window.cancelAnimationFrame(e)},[U.listRef,U.pinned,W.length,q.length]);let J=()=>{U.jumpToLatest(),window.requestAnimationFrame(()=>{U.listRef.current?.scrollToIndex(W.length+q.length-1,{align:`end`})})},Y=(0,C.useMemo)(()=>w(a,c,l),[l,c,a]),X=Y?.agent??null,Z=Y?.recipient===`leader`,Q=X?.name??(Z?`Leader agent`:Y?.recipient??`agent`);(0,C.useEffect)(()=>{let e=Y?.client?.clientId;e!==void 0&&g.getState().selectClient(e),I(null),R(!1),B(!1),H([])},[Y?.client?.clientId,c,l]);let $=async()=>{if(Y?.client===null||Y?.client===void 0||!Y.controllable||j.trim().length===0)return;P(!0),I(null);let e=j.trim();try{let t=await _(Y.client.clientId,E,{to:Y.recipient,subject:O.trim()||`HQ ${E}`,body:e,priority:E===`steer`?`high`:`normal`});M(``),v({body:``}),H(n=>[...n,{commandId:t.commandId,type:E,target:Q,preview:e,createdAt:new Date().toISOString()}].slice(-8)),I({tone:`ok`,text:`${E} queued for ${Q} · ${t.commandId}`})}catch(e){I({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{P(!1)}},ne=async()=>{if(!(Y?.client===null||Y?.client===void 0)){P(!0),I(null);try{let e=await _(Y.client.clientId,`abort`,{target:Y.recipient});if(H(t=>[...t,{commandId:e.commandId,type:`abort`,target:Q,preview:`Interrupt ${Q}`,createdAt:new Date().toISOString()}].slice(-8)),Z&&z){let e=await _(Y.client.clientId,`abort`,{target:`fleet`});H(t=>[...t,{commandId:e.commandId,type:`abort`,target:`all subagents`,preview:`Interrupt every subagent on this client`,createdAt:new Date().toISOString()}].slice(-8))}I({tone:`ok`,text:Z&&z?`Leader interrupt queued; all subagents will be interrupted too.`:`${Q} interrupt queued.`}),R(!1)}catch(e){I({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{P(!1)}}};return(0,T.jsxs)(`div`,{className:`hq-console-shell`,children:[(0,T.jsx)(te,{snapshot:a??null,selectedSessionId:c,selectedAgentId:l}),(0,T.jsxs)(`div`,{className:`hq-console`,children:[(0,T.jsxs)(`div`,{className:`hq-chat-header`,children:[(0,T.jsx)(i,{size:15,className:`hq-chat-header-icon`}),(0,T.jsx)(`span`,{className:`hq-card-title hq-title-inline`,children:`Console`}),p&&(0,T.jsxs)(`span`,{className:`hq-pill active`,children:[(0,T.jsx)(d,{size:12}),` `,X?.name??l]}),G.projectName!==void 0&&!p&&(0,T.jsx)(`span`,{className:`hq-pill`,children:G.projectName}),Y!==null&&(0,T.jsxs)(`span`,{className:`hq-pill info`,title:Y.client?.clientId,children:[Y.session.hostname??Y.session.machineId,` ·`,` `,Y.session.clientKind.toUpperCase()]}),Y?.mailboxServeActive===!0&&(0,T.jsx)(`span`,{className:`hq-pill active`,children:`mailbox serve`}),G.source!==void 0&&(0,T.jsx)(`span`,{className:`hq-pill`,title:G.source===`disk`?`disk = full history replayed from this machine`:`stream = live ring only (remote or not yet persisted)`,children:G.source===`disk`?`full history`:`live ring`}),(0,T.jsxs)(`span`,{className:`hq-chat-counts`,children:[(0,T.jsxs)(`span`,{className:`hq-pill`,children:[K.turns+q.length,` turns`]}),(0,T.jsxs)(`span`,{className:`hq-pill`,children:[K.tools,` tools`]}),K.running>0&&(0,T.jsxs)(`span`,{className:`hq-pill running`,children:[K.running,` running`]}),K.errors>0&&(0,T.jsxs)(`span`,{className:`hq-pill error`,children:[K.errors,` err`]}),!p&&!U.full&&G.total>W.length&&(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn secondary hq-chat-fullbtn`,onClick:()=>U.setFull(!0),title:`History is truncated — load all ${G.total} turns`,children:[(0,T.jsx)(r,{size:12}),` load all `,G.total]})]})]}),c===null?(0,T.jsx)(`div`,{className:`hq-empty`,children:`Pick a client or agent from the tree on the left.`}):U.loading&&W.length===0&&q.length===0?(0,T.jsx)(`div`,{className:`hq-empty`,children:p?`Loading agent history…`:`Loading transcript…`}):U.error===null?(0,T.jsxs)(`div`,{className:`hq-chat-scroll`,children:[W.length===0&&q.length===0?(0,T.jsx)(`div`,{className:`hq-empty`,children:p?`No messages from ${X?.name??l??`this agent`} yet.`:`No transcript entries yet.`}):(0,T.jsxs)(S,{ref:U.listRef,onScroll:U.onScroll,className:`hq-chat-vlist`,children:[W.map((e,t)=>(0,T.jsx)(`div`,{className:`hq-chat-rowpad`,children:(0,T.jsx)(b,{entry:e,running:U.isRunningAt(e,t)})},y(e,t))),q.map(e=>{let t=s.find(t=>t.commandId===e.commandId);return(0,T.jsx)(`div`,{className:`hq-chat-rowpad`,"aria-live":`polite`,children:(0,T.jsx)(k,{receipt:e,lifecycle:t?.ackStatus??t?.status??`queued`})},`receipt:${e.commandId}`)})]}),!U.pinned&&(W.length>0||q.length>0)&&(0,T.jsx)(`button`,{type:`button`,className:`hq-chat-jump`,onClick:J,title:`Jump to latest`,children:(0,T.jsx)(u,{size:14})})]}):(0,T.jsxs)(`div`,{className:`hq-empty`,children:[`Error: `,U.error]}),c!==null&&(0,T.jsxs)(`div`,{className:`hq-console-composer`,children:[(0,T.jsxs)(`div`,{className:`hq-console-composer-head`,children:[(0,T.jsxs)(`span`,{children:[(0,T.jsx)(o,{size:13}),` Send to `,(0,T.jsx)(`strong`,{children:Q})]}),(0,T.jsx)(`span`,{className:`hq-pill ${Y?.controllable===!0?`active`:`error`}`,children:Y?.controllable===!0?`control live`:`read-only client`})]}),(0,T.jsxs)(`div`,{className:`hq-console-compose-row`,children:[(0,T.jsxs)(`select`,{className:`hq-select hq-console-delivery`,"aria-label":`Message delivery mode`,value:E,onChange:e=>{let t=e.target.value;D(t),v({delivery:t})},children:[(0,T.jsx)(`option`,{value:`steer`,children:`Steer now`}),(0,T.jsx)(`option`,{value:`btw`,children:`BTW / FYI`}),(0,T.jsx)(`option`,{value:`queue`,children:`Queue next`})]}),(0,T.jsx)(`input`,{className:`hq-input hq-console-subject`,"aria-label":`Message subject`,placeholder:`HQ ${E} (optional subject)`,value:O,onChange:e=>{A(e.target.value),v({subject:e.target.value})}}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn danger hq-console-interrupt`,disabled:N||Y?.controllable!==!0,onClick:()=>{B(!1),R(!0)},children:[(0,T.jsx)(n,{size:13}),` Interrupt`]})]}),(0,T.jsxs)(`div`,{className:`hq-console-compose-row hq-console-message-row`,children:[(0,T.jsx)(`textarea`,{className:`hq-textarea hq-console-message`,"aria-label":`Message ${Q}`,placeholder:`Message ${Q}…`,rows:2,value:j,onChange:e=>{M(e.target.value),v({body:e.target.value})},onKeyDown:e=>{e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),$())}}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn primary hq-console-send`,disabled:N||j.trim().length===0||Y?.controllable!==!0,onClick:()=>void $(),children:[(0,T.jsx)(f,{size:13}),` `,N?`Queueing…`:`Send`]})]}),(0,T.jsxs)(`div`,{className:`hq-console-compose-foot`,children:[(0,T.jsx)(`span`,{children:`Ctrl+Enter sends · steer interrupts at the next safe turn`}),F!==null&&(0,T.jsx)(`span`,{className:`hq-console-status ${F.tone}`,children:F.text})]})]})]}),L&&Y!==null&&(0,T.jsxs)(`div`,{className:`hq-confirm-layer`,role:`presentation`,children:[(0,T.jsx)(`button`,{type:`button`,className:`hq-confirm-scrim`,"aria-label":`Cancel interrupt`,onClick:()=>R(!1)}),(0,T.jsxs)(`section`,{className:`hq-confirm-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`hq-interrupt-title`,children:[(0,T.jsx)(n,{size:22,className:`hq-confirm-danger`}),(0,T.jsxs)(`div`,{children:[(0,T.jsxs)(`h2`,{id:`hq-interrupt-title`,children:[`Interrupt `,Q,`?`]}),(0,T.jsx)(`p`,{children:`The current run will stop at its cancellation boundary.`})]}),Z&&(0,T.jsxs)(`label`,{className:`hq-confirm-check`,children:[(0,T.jsx)(`input`,{type:`checkbox`,checked:z,onChange:e=>B(e.target.checked)}),`Also interrupt every subagent on this client`]}),(0,T.jsxs)(`div`,{className:`hq-confirm-actions`,children:[(0,T.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,onClick:()=>R(!1),children:`Cancel`}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn danger`,disabled:N,onClick:()=>void ne(),children:[(0,T.jsx)(n,{size:13}),` Confirm interrupt`]})]})]})]})]})}export{A as LiveConsoleView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Ct as t,D as n,J as r,M as i,Nt as a,S as o,at as s,d as c,j as l,jt as u,kt as d,v as f}from"./icons-BlGYTg3M.js";import{i as p}from"./markdown-Dm2qU66U.js";import{a as m,f as h,l as g,s as _,t as v}from"./index-DzLBc00n.js";import{c as y,l as ee,s as b,t as x,u as S}from"./fleet-topology-C_gii-RC.js";var C=e(a(),1);function w(e,t,n){if(e===null||t===null)return null;let r=(e.liveSessions??[]).find(e=>e.sessionId===t);if(r===void 0)return null;let i=e.sessions.find(e=>e.sessionId===t)?.clientId,a=r.clientId??i,o=e.clients.find(e=>e.connected&&e.clientId===a),s=e.clients.filter(e=>e.connected&&e.machineId===r.machineId&&e.projectId===r.projectId&&(r.pid===void 0||e.pid===r.pid)),c=(o?.capabilities.includes(`control.receive`)===!0?o:void 0)??s.find(e=>e.kind===r.clientKind&&e.capabilities.includes(`control.receive`))??s.find(e=>e.capabilities.includes(`control.receive`))??o??s[0],l=n===null?null:r.agents.find(e=>e.id===n)??null,u=n===null||n===`leader`?`leader`:n,d=e.clients.some(e=>e.connected&&e.projectId===r.projectId&&e.capabilities.includes(`mailbox.serve`));return{session:r,client:c??null,agent:l,recipient:u,controllable:c?.capabilities.includes(`control.receive`)===!0,mailboxServeActive:d}}var T=p();function E(e){let t=x(e),n=[],r=new Map,i=new Map,a=new Map,o=e=>`machine:${e.machineId}`,s=e=>`project:${e.machineId}:${e.projectId}`;for(let e of t.nodes){if(e.kind!==`machine`)continue;let t={id:e.id,label:e.label,sub:e.sub,projects:[]};r.set(e.id,t),n.push(t)}for(let e of t.nodes){if(e.kind!==`project`)continue;let t=r.get(o(e));if(t===void 0)continue;let n={id:e.id,label:e.label,clients:[]};i.set(e.id,n),t.projects.push(n)}for(let e of t.nodes){if(e.kind!==`terminal`||e.sessionId===void 0||e.serviceMode!==void 0)continue;let t=i.get(s(e));if(t===void 0)continue;let n={clientId:e.clientId,sessionId:e.sessionId,label:e.label,clientKind:e.clientKind,status:e.status,synthetic:e.isSyntheticSession===!0,agents:[]};a.set(e.sessionId,n),t.clients.push(n)}for(let e of t.nodes){if(e.kind!==`agent`||e.sessionId===void 0||e.agentId===void 0)continue;let t=a.get(e.sessionId);t!==void 0&&t.agents.push({id:e.agentId,label:e.label,status:e.status})}return n.map(e=>({...e,projects:e.projects.filter(e=>e.clients.length>0)})).filter(e=>e.projects.length>0)}function D(e){return e===`active`||e===`running`||e===`streaming`?`active`:e===`waiting_user`?`warn`:e===`error`||e===`stale`||e===`closing`?`error`:`idle`}function te({snapshot:e,selectedSessionId:n,selectedAgentId:r}){let i=(0,C.useMemo)(()=>E(e),[e]),[a,o]=(0,C.useState)(new Set),u=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return i.length===0?(0,T.jsx)(`div`,{className:`hq-fleetnav`,children:(0,T.jsx)(`div`,{className:`hq-empty hq-pad-md`,children:`No live sessions. Open a WrongStack CLI/TUI/WebUI connected to HQ.`})}):(0,T.jsx)(`div`,{className:`hq-fleetnav`,role:`tree`,"aria-label":`Fleet navigator`,children:i.map(e=>{let i=!a.has(e.id);return(0,T.jsxs)(`div`,{className:`hq-nav-machine`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row machine`,onClick:()=>u(e.id),"aria-expanded":i,children:[(0,T.jsx)(t,{size:12,className:`hq-nav-caret`+(i?` open`:``)}),(0,T.jsx)(l,{size:13}),(0,T.jsx)(`span`,{className:`hq-nav-label`,title:e.sub??e.label,children:e.label})]}),i&&e.projects.map(e=>{let i=!a.has(e.id);return(0,T.jsxs)(`div`,{className:`hq-nav-project`,children:[(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row project`,onClick:()=>u(e.id),"aria-expanded":i,children:[(0,T.jsx)(t,{size:12,className:`hq-nav-caret`+(i?` open`:``)}),(0,T.jsx)(s,{size:13}),(0,T.jsx)(`span`,{className:`hq-nav-label`,title:e.label,children:e.label})]}),i&&e.clients.map(e=>{let i=!a.has(e.sessionId),o=n===e.sessionId&&r===null;return(0,T.jsxs)(`div`,{className:`hq-nav-client`,children:[(0,T.jsxs)(`div`,{className:`hq-nav-clientrow`,children:[e.agents.length>0?(0,T.jsx)(`button`,{type:`button`,className:`hq-nav-caretbtn`,onClick:()=>u(e.sessionId),"aria-label":i?`Collapse`:`Expand`,children:(0,T.jsx)(t,{size:12,className:`hq-nav-caret`+(i?` open`:``)})}):(0,T.jsx)(`span`,{className:`hq-nav-caretbtn`}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row client`+(o?` selected`:``),disabled:e.synthetic,onClick:()=>{e.synthetic||(g.getState().selectSession(e.sessionId),e.clientId!==void 0&&g.getState().selectClient(e.clientId))},title:e.synthetic?`waiting for session telemetry`:e.label,children:[(0,T.jsx)(`span`,{className:`hq-nav-dot `+D(e.status)}),(0,T.jsx)(c,{size:12}),(0,T.jsx)(`span`,{className:`hq-nav-label`,children:e.label}),e.agents.length>0&&(0,T.jsx)(`span`,{className:`hq-nav-count`,children:e.agents.length})]})]}),i&&e.agents.map(t=>(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row agent`+(n===e.sessionId&&r===t.id?` selected`:``),onClick:()=>{g.getState().selectAgent(e.sessionId,t.id),e.clientId!==void 0&&g.getState().selectClient(e.clientId)},title:t.label,children:[(0,T.jsx)(`span`,{className:`hq-nav-dot `+D(t.status)}),(0,T.jsx)(d,{size:12}),(0,T.jsx)(`span`,{className:`hq-nav-label`,children:t.label})]},t.id))]},e.sessionId)})]},e.id)})]},e.id)})})}function O(e){return e===`completed`?`active`:e===`failed`||e===`rejected`?`error`:e===`delivered`||e===`accepted`?`info`:`warn`}function k({receipt:e,lifecycle:t}){let r=new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}),i=(0,T.jsx)(`span`,{className:`hq-pill ${O(t)}`,"aria-label":`Command ${t}`,children:t});return e.type===`abort`?(0,T.jsx)(`div`,{className:`hq-chat-turn system hq-command-turn`,"data-command-id":e.commandId,children:(0,T.jsxs)(`span`,{className:`hq-chat-system-line`,children:[(0,T.jsx)(n,{size:12}),` `,e.preview,` `,i,(0,T.jsx)(`span`,{className:`hq-chat-clock`,children:r})]})}):(0,T.jsx)(`div`,{className:`hq-chat-turn user hq-command-turn`,"data-command-id":e.commandId,children:(0,T.jsxs)(`div`,{className:`hq-chat-bubble user`,children:[(0,T.jsxs)(`div`,{className:`hq-chat-role`,children:[`you → `,e.target,` · `,e.type,` `,i,(0,T.jsx)(`span`,{className:`hq-chat-clock`,children:r})]}),(0,T.jsx)(`div`,{className:`hq-chat-prose`,children:e.preview})]})})}function A(){let{selectedSessionId:e,selectedAgentId:t,snapshot:a,commandStatuses:s}=g(h(e=>({selectedSessionId:e.selectedSessionId,selectedAgentId:e.selectedAgentId,snapshot:e.snapshot,commandStatuses:e.commandStatuses}))),c=e,l=t,p=l!==null,x=m().console,[E,D]=(0,C.useState)(x.delivery),[O,A]=(0,C.useState)(x.subject),[j,M]=(0,C.useState)(x.body),[N,P]=(0,C.useState)(!1),[F,I]=(0,C.useState)(null),[L,R]=(0,C.useState)(!1),[z,B]=(0,C.useState)(!1),[V,H]=(0,C.useState)([]),U=ee(c,l),{entries:W,meta:G,stats:K}=U,q=(0,C.useMemo)(()=>V.filter(e=>{if(e.type===`abort`)return!0;let t=Date.parse(e.createdAt);return!W.some(n=>n.role===`user`&&n.text.trim()===e.preview&&Math.abs(Date.parse(n.ts)-t)<12e4)}),[W,V]);(0,C.useEffect)(()=>{if(!U.pinned||q.length===0)return;let e=window.requestAnimationFrame(()=>{U.listRef.current?.scrollToIndex(W.length+q.length-1,{align:`end`})});return()=>window.cancelAnimationFrame(e)},[U.listRef,U.pinned,W.length,q.length]);let J=()=>{U.jumpToLatest(),window.requestAnimationFrame(()=>{U.listRef.current?.scrollToIndex(W.length+q.length-1,{align:`end`})})},Y=(0,C.useMemo)(()=>w(a,c,l),[l,c,a]),X=Y?.agent??null,Z=Y?.recipient===`leader`,Q=X?.name??(Z?`Leader agent`:Y?.recipient??`agent`);(0,C.useEffect)(()=>{let e=Y?.client?.clientId;e!==void 0&&g.getState().selectClient(e),I(null),R(!1),B(!1),H([])},[Y?.client?.clientId,c,l]);let $=async()=>{if(Y?.client===null||Y?.client===void 0||!Y.controllable||j.trim().length===0)return;P(!0),I(null);let e=j.trim();try{let t=await _(Y.client.clientId,E,{to:Y.recipient,subject:O.trim()||`HQ ${E}`,body:e,priority:E===`steer`?`high`:`normal`});M(``),v({body:``}),H(n=>[...n,{commandId:t.commandId,type:E,target:Q,preview:e,createdAt:new Date().toISOString()}].slice(-8)),I({tone:`ok`,text:`${E} queued for ${Q} · ${t.commandId}`})}catch(e){I({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{P(!1)}},ne=async()=>{if(!(Y?.client===null||Y?.client===void 0)){P(!0),I(null);try{let e=await _(Y.client.clientId,`abort`,{target:Y.recipient});if(H(t=>[...t,{commandId:e.commandId,type:`abort`,target:Q,preview:`Interrupt ${Q}`,createdAt:new Date().toISOString()}].slice(-8)),Z&&z){let e=await _(Y.client.clientId,`abort`,{target:`fleet`});H(t=>[...t,{commandId:e.commandId,type:`abort`,target:`all subagents`,preview:`Interrupt every subagent on this client`,createdAt:new Date().toISOString()}].slice(-8))}I({tone:`ok`,text:Z&&z?`Leader interrupt queued; all subagents will be interrupted too.`:`${Q} interrupt queued.`}),R(!1)}catch(e){I({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{P(!1)}}};return(0,T.jsxs)(`div`,{className:`hq-console-shell`,children:[(0,T.jsx)(te,{snapshot:a??null,selectedSessionId:c,selectedAgentId:l}),(0,T.jsxs)(`div`,{className:`hq-console`,children:[(0,T.jsxs)(`div`,{className:`hq-chat-header`,children:[(0,T.jsx)(i,{size:15,className:`hq-chat-header-icon`}),(0,T.jsx)(`span`,{className:`hq-card-title hq-title-inline`,children:`Console`}),p&&(0,T.jsxs)(`span`,{className:`hq-pill active`,children:[(0,T.jsx)(d,{size:12}),` `,X?.name??l]}),G.projectName!==void 0&&!p&&(0,T.jsx)(`span`,{className:`hq-pill`,children:G.projectName}),Y!==null&&(0,T.jsxs)(`span`,{className:`hq-pill info`,title:Y.client?.clientId,children:[Y.session.hostname??Y.session.machineId,` ·`,` `,Y.session.clientKind.toUpperCase()]}),Y?.mailboxServeActive===!0&&(0,T.jsx)(`span`,{className:`hq-pill active`,children:`mailbox serve`}),G.source!==void 0&&(0,T.jsx)(`span`,{className:`hq-pill`,title:G.source===`disk`?`disk = full history replayed from this machine`:`stream = live ring only (remote or not yet persisted)`,children:G.source===`disk`?`full history`:`live ring`}),(0,T.jsxs)(`span`,{className:`hq-chat-counts`,children:[(0,T.jsxs)(`span`,{className:`hq-pill`,children:[K.turns+q.length,` turns`]}),(0,T.jsxs)(`span`,{className:`hq-pill`,children:[K.tools,` tools`]}),K.running>0&&(0,T.jsxs)(`span`,{className:`hq-pill running`,children:[K.running,` running`]}),K.errors>0&&(0,T.jsxs)(`span`,{className:`hq-pill error`,children:[K.errors,` err`]}),!p&&!U.full&&G.total>W.length&&(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn secondary hq-chat-fullbtn`,onClick:()=>U.setFull(!0),title:`History is truncated — load all ${G.total} turns`,children:[(0,T.jsx)(r,{size:12}),` load all `,G.total]})]})]}),c===null?(0,T.jsx)(`div`,{className:`hq-empty`,children:`Pick a client or agent from the tree on the left.`}):U.loading&&W.length===0&&q.length===0?(0,T.jsx)(`div`,{className:`hq-empty`,children:p?`Loading agent history…`:`Loading transcript…`}):U.error===null?(0,T.jsxs)(`div`,{className:`hq-chat-scroll`,children:[W.length===0&&q.length===0?(0,T.jsx)(`div`,{className:`hq-empty`,children:p?`No messages from ${X?.name??l??`this agent`} yet.`:`No transcript entries yet.`}):(0,T.jsxs)(S,{ref:U.listRef,onScroll:U.onScroll,className:`hq-chat-vlist`,children:[W.map((e,t)=>(0,T.jsx)(`div`,{className:`hq-chat-rowpad`,children:(0,T.jsx)(b,{entry:e,running:U.isRunningAt(e,t)})},y(e,t))),q.map(e=>{let t=s.find(t=>t.commandId===e.commandId);return(0,T.jsx)(`div`,{className:`hq-chat-rowpad`,"aria-live":`polite`,children:(0,T.jsx)(k,{receipt:e,lifecycle:t?.ackStatus??t?.status??`queued`})},`receipt:${e.commandId}`)})]}),!U.pinned&&(W.length>0||q.length>0)&&(0,T.jsx)(`button`,{type:`button`,className:`hq-chat-jump`,onClick:J,title:`Jump to latest`,children:(0,T.jsx)(u,{size:14})})]}):(0,T.jsxs)(`div`,{className:`hq-empty`,children:[`Error: `,U.error]}),c!==null&&(0,T.jsxs)(`div`,{className:`hq-console-composer`,children:[(0,T.jsxs)(`div`,{className:`hq-console-composer-head`,children:[(0,T.jsxs)(`span`,{children:[(0,T.jsx)(o,{size:13}),` Send to `,(0,T.jsx)(`strong`,{children:Q})]}),(0,T.jsx)(`span`,{className:`hq-pill ${Y?.controllable===!0?`active`:`error`}`,children:Y?.controllable===!0?`control live`:`read-only client`})]}),(0,T.jsxs)(`div`,{className:`hq-console-compose-row`,children:[(0,T.jsxs)(`select`,{className:`hq-select hq-console-delivery`,"aria-label":`Message delivery mode`,value:E,onChange:e=>{let t=e.target.value;D(t),v({delivery:t})},children:[(0,T.jsx)(`option`,{value:`steer`,children:`Steer now`}),(0,T.jsx)(`option`,{value:`btw`,children:`BTW / FYI`}),(0,T.jsx)(`option`,{value:`queue`,children:`Queue next`})]}),(0,T.jsx)(`input`,{className:`hq-input hq-console-subject`,"aria-label":`Message subject`,placeholder:`HQ ${E} (optional subject)`,value:O,onChange:e=>{A(e.target.value),v({subject:e.target.value})}}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn danger hq-console-interrupt`,disabled:N||Y?.controllable!==!0,onClick:()=>{B(!1),R(!0)},children:[(0,T.jsx)(n,{size:13}),` Interrupt`]})]}),(0,T.jsxs)(`div`,{className:`hq-console-compose-row hq-console-message-row`,children:[(0,T.jsx)(`textarea`,{className:`hq-textarea hq-console-message`,"aria-label":`Message ${Q}`,placeholder:`Message ${Q}…`,rows:2,value:j,onChange:e=>{M(e.target.value),v({body:e.target.value})},onKeyDown:e=>{e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),$())}}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn primary hq-console-send`,disabled:N||j.trim().length===0||Y?.controllable!==!0,onClick:()=>void $(),children:[(0,T.jsx)(f,{size:13}),` `,N?`Queueing…`:`Send`]})]}),(0,T.jsxs)(`div`,{className:`hq-console-compose-foot`,children:[(0,T.jsx)(`span`,{children:`Ctrl+Enter sends · steer interrupts at the next safe turn`}),F!==null&&(0,T.jsx)(`span`,{className:`hq-console-status ${F.tone}`,children:F.text})]})]})]}),L&&Y!==null&&(0,T.jsxs)(`div`,{className:`hq-confirm-layer`,role:`presentation`,children:[(0,T.jsx)(`button`,{type:`button`,className:`hq-confirm-scrim`,"aria-label":`Cancel interrupt`,onClick:()=>R(!1)}),(0,T.jsxs)(`section`,{className:`hq-confirm-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`hq-interrupt-title`,children:[(0,T.jsx)(n,{size:22,className:`hq-confirm-danger`}),(0,T.jsxs)(`div`,{children:[(0,T.jsxs)(`h2`,{id:`hq-interrupt-title`,children:[`Interrupt `,Q,`?`]}),(0,T.jsx)(`p`,{children:`The current run will stop at its cancellation boundary.`})]}),Z&&(0,T.jsxs)(`label`,{className:`hq-confirm-check`,children:[(0,T.jsx)(`input`,{type:`checkbox`,checked:z,onChange:e=>B(e.target.checked)}),`Also interrupt every subagent on this client`]}),(0,T.jsxs)(`div`,{className:`hq-confirm-actions`,children:[(0,T.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,onClick:()=>R(!1),children:`Cancel`}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn danger`,disabled:N,onClick:()=>void ne(),children:[(0,T.jsx)(n,{size:13}),` Confirm interrupt`]})]})]})]})]})}export{A as LiveConsoleView};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{C as t,F as n,I as r,N as i,Nt as a,O as o,P as s,U as c,bt as l,h as u,nt as d,y as f}from"./icons-BlGYTg3M.js";import{i as p}from"./markdown-Dm2qU66U.js";import{a as m,c as h,f as g,i as _,l as v,u as y}from"./index-Ckam6WOR.js";import{t as b}from"./use-backfilled-events-BnFvycsd.js";var x=e(a(),1),S=p(),C=[{value:`steer`,label:`steer — redirect the current work`},{value:`btw`,label:`btw — FYI, no action required`},{value:`queue`,label:`queue — note for the next agent`},{value:`broadcast`,label:`broadcast — all agents in the project`}];function w({projects:e,sender:t}){let n=t??h,[i,a]=(0,x.useState)(!1),[o,s]=(0,x.useState)(``),[c,l]=(0,x.useState)(`steer`),[u,d]=(0,x.useState)(`leader`),[f,p]=(0,x.useState)(`normal`),[m,g]=(0,x.useState)(``),[_,v]=(0,x.useState)(``),[y,b]=(0,x.useState)({phase:`idle`}),w=o||e[0]?.projectId||``,T=y.phase!==`sending`&&_.trim().length>0&&w.length>0,E=async()=>{if(T){b({phase:`sending`});try{let e=await n({projectId:w,type:c,...c===`broadcast`?{}:{to:u.trim()||`leader`},subject:m.trim()||`HQ prompt`,body:_.trim(),priority:f});b({phase:`sent`,messageId:e.messageId}),v(``)}catch(e){b({phase:`error`,message:e instanceof Error?e.message:String(e)})}}};return i?(0,S.jsxs)(`div`,{className:`hq-card hq-composer`,children:[(0,S.jsxs)(`div`,{className:`hq-row hq-row-baseline`,children:[(0,S.jsx)(`span`,{className:`hq-card-title hq-title-inline`,children:`Send to project mailbox`}),(0,S.jsx)(`span`,{className:`hq-composer-hint`,children:`lands in the mailbox file — picked up by the next agent, no live client needed`}),(0,S.jsx)(`button`,{type:`button`,className:`hq-toggle hq-ml-auto`,"aria-label":`Collapse composer`,onClick:()=>a(!1),children:`▾`})]}),(0,S.jsxs)(`div`,{className:`hq-composer-grid`,children:[(0,S.jsxs)(`label`,{className:`hq-composer-field`,children:[(0,S.jsx)(`span`,{children:`project`}),(0,S.jsx)(`select`,{className:`hq-select`,value:w,onChange:e=>s(e.target.value),children:e.map(e=>(0,S.jsx)(`option`,{value:e.projectId,children:e.label??e.projectId},e.projectId))})]}),(0,S.jsxs)(`label`,{className:`hq-composer-field`,children:[(0,S.jsx)(`span`,{children:`type`}),(0,S.jsx)(`select`,{className:`hq-select`,value:c,onChange:e=>l(e.target.value),children:C.map(e=>(0,S.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),c!==`broadcast`&&(0,S.jsxs)(`label`,{className:`hq-composer-field`,children:[(0,S.jsx)(`span`,{children:`to`}),(0,S.jsx)(`input`,{className:`hq-input`,value:u,placeholder:`leader`,onChange:e=>d(e.target.value)})]}),(0,S.jsxs)(`label`,{className:`hq-composer-field`,children:[(0,S.jsx)(`span`,{children:`priority`}),(0,S.jsxs)(`select`,{className:`hq-select`,value:f,onChange:e=>p(e.target.value),children:[(0,S.jsx)(`option`,{value:`high`,children:`high`}),(0,S.jsx)(`option`,{value:`normal`,children:`normal`}),(0,S.jsx)(`option`,{value:`low`,children:`low`})]})]})]}),(0,S.jsx)(`input`,{className:`hq-input`,value:m,placeholder:`subject (optional)`,onChange:e=>g(e.target.value)}),(0,S.jsx)(`textarea`,{className:`hq-input hq-composer-body`,value:_,rows:3,placeholder:`Message body — e.g. “after the current task, run the full test suite”`,onChange:e=>v(e.target.value)}),(0,S.jsxs)(`div`,{className:`hq-row`,children:[(0,S.jsx)(`button`,{type:`button`,className:`hq-btn`,disabled:!T,onClick:()=>void E(),children:y.phase===`sending`?`Sending…`:`Send`}),y.phase===`sent`&&(0,S.jsxs)(`span`,{className:`hq-composer-status ok`,children:[`delivered`,y.messageId===void 0?``:` · ${y.messageId.slice(0,8)}`]}),y.phase===`error`&&(0,S.jsx)(`span`,{className:`hq-composer-status err`,title:y.message,children:y.message})]})]}):(0,S.jsxs)(`div`,{className:`hq-composer-bar`,children:[(0,S.jsxs)(`button`,{type:`button`,className:`hq-btn`,disabled:e.length===0,title:e.length===0?`No projects reported yet — connect a client first`:`Write a message into a project mailbox (works with zero connected agents)`,onClick:()=>a(!0),children:[(0,S.jsx)(r,{size:13}),` Compose`]}),y.phase===`sent`&&(0,S.jsxs)(`span`,{className:`hq-composer-status ok`,children:[`delivered`,y.messageId===void 0?``:` · ${y.messageId.slice(0,8)}`]})]})}function T(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.mailboxId==`string`&&(t.scope===`project`||t.scope===`global`)&&Array.isArray(t.messages)&&Array.isArray(t.agents)&&typeof t.totals==`object`&&t.totals!==null}function E(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.mailboxId==`string`&&typeof t.action==`string`&&(t.message===void 0||typeof t.message==`object`)}function D(e,t){let n=e.get(t);return n===void 0&&(n={projectId:t,messages:[],countersFromSnapshot:!1,onlineAgentCount:0,highPriorityCount:0,unreadCount:0,incompleteCount:0},e.set(t,n)),n}function O(e){let t=0,n=0,r=0;for(let i of e){let e=i.message;e.priority===`high`&&(t+=1),e.completed||(r+=1,(e.readCount??0)===0&&(n+=1))}return{highPriorityCount:t,unreadCount:n,incompleteCount:r}}function k(e){let t=new Map;for(let n of e)(t.get(n.message.mailId)===void 0||n.source===`event`)&&t.set(n.message.mailId,n);return Array.from(t.values()).sort((e,t)=>t.message.timestamp.localeCompare(e.message.timestamp))}function A(e,t){let n=new Map;if(e!==null)for(let t of e.mailboxes){let e=D(n,t.projectId);e.mailboxId=t.mailboxId,e.scope=t.scope,e.onlineAgentCount=t.onlineAgentCount,e.highPriorityCount=t.highPriorityCount,e.unreadCount=t.unreadCount,e.incompleteCount=t.incompleteCount,e.countersFromSnapshot=!0}for(let e of t){if(e.type!==`mailbox.snapshot`||!T(e.payload))continue;let t=e.payload,r=D(n,e.projectId);r.mailboxId=t.mailboxId,r.scope=t.scope;for(let n of t.messages)r.messages.push({message:n,source:`snapshot`,key:`s:${e.id}:${n.messageId}`,projectId:e.projectId})}let r=new Map;for(let e of t){if(e.type!==`mailbox.event`||!E(e.payload))continue;let t=e.payload,i=D(n,e.projectId);i.mailboxId=t.mailboxId,i.scope=i.scope??`project`,t.message!==void 0&&!r.has(t.message.mailId)&&(r.set(t.message.mailId,i),i.messages.push({message:t.message,source:`event`,key:`e:${t.message.mailId}:${e.seq}`,projectId:e.projectId})),t.agent?.online&&(i.onlineAgentCount+=1)}for(let e of n.values())if(e.messages=k(e.messages),!e.countersFromSnapshot){let t=O(e.messages);e.highPriorityCount=t.highPriorityCount,e.unreadCount=t.unreadCount,e.incompleteCount=t.incompleteCount}let i=Array.from(n.values()).sort((e,t)=>{let n=e.messages[0]?.message.timestamp??``;return(t.messages[0]?.message.timestamp??``).localeCompare(n)});return{projects:i,hasAnyActivity:i.some(e=>e.messages.length>0)}}var j=Object.freeze({types:new Set,priorities:new Set,projectIds:new Set,includeCompleted:!0,query:``});function M(e,t){switch(t.type){case`toggle-type`:{let n=new Set(e.types);return n.has(t.value)?n.delete(t.value):n.add(t.value),{...e,types:n}}case`toggle-priority`:{let n=new Set(e.priorities);return n.has(t.value)?n.delete(t.value):n.add(t.value),{...e,priorities:n}}case`toggle-project`:{let n=new Set(e.projectIds);return n.has(t.value)?n.delete(t.value):n.add(t.value),{...e,projectIds:n}}case`set-query`:return{...e,query:t.value};case`set-include-completed`:return{...e,includeCompleted:t.value};case`clear-all`:return j;default:return e}}function N(e,t={}){let n=t.includeCompleted??!0,r=t.types&&t.types.length>0?new Set(t.types):null,i=t.priorities&&t.priorities.length>0?new Set(t.priorities):null,a=t.projectIds&&t.projectIds.length>0?new Set(t.projectIds):null,o=t.query?.trim().toLowerCase()??``,s=t.limit??500,c=[];for(let t of e){let e=t.message;!n&&e.completed||r&&!r.has(e.type)||i&&!i.has(e.priority)||a||o.length>0&&!`${e.subject}\n${e.from}\n${e.to}\n${e.bodyPreview??``}`.toLowerCase().includes(o)||c.push({key:t.key,flat:t})}c.sort((e,t)=>{let n=t.flat.message.timestamp.localeCompare(e.flat.message.timestamp);return n===0?e.flat.message.mailId.localeCompare(t.flat.message.mailId):n});let l=c.length,u=l>s,d=u?c.slice(0,s):c;return{totalMatched:l,returned:d.length,truncated:u,entries:d}}function P(e,t,n={}){let{projectIds:r,...i}=n,a=A(e,t),o=[],s=r!==void 0&&r.length>0?new Set(r):null;for(let e of a.projects)s&&!s.has(e.projectId)||(o=o.concat(e.messages));return N(o,i)}function F(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.error==`string`)return!0;if(typeof t.error!=`object`||t.error===null)return!1;let n=t.error;return typeof n.code==`string`&&typeof n.message==`string`}async function I(e){let t=await y(`/api/mailbox/messages/${encodeURIComponent(e.mailId)}/action`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(t.status===401&&v.getState().markAuthRequired(),!t.ok){let e=`${t.status} ${t.statusText}`;try{let n=await t.json();F(n)&&(e=typeof n.error==`string`?n.error:`${n.error.code}: ${n.error.message}`)}catch{}throw Error(`mailbox action failed — ${e}`)}return await t.json()}var L={markRead:e=>I({...e,action:`mark-read`}),acknowledge:e=>I({...e,action:`acknowledge`}),reopen:e=>I({...e,action:`reopen`}),softDelete:e=>I({...e,action:`soft-delete`}),restore:e=>I({...e,action:`restore`})};function R({mailId:e,actorId:t,projectId:n,isDeleted:r=!1,onAction:i,disabled:a=!1}){let[o,s]=(0,x.useState)(null),[c,l]=(0,x.useState)(null),u=async(t,n)=>{if(!(a||o!==null)){s(t),l(null);try{await n(),i?.(e,t)}catch(e){l(e instanceof Error?e.message:String(e))}finally{s(null)}}},d={mailId:e,readerId:t,projectId:n};return(0,S.jsxs)(`div`,{className:`hq-msg-actions`,children:[!r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:a||o!==null,onClick:()=>u(`mark-read`,()=>L.markRead(d)),children:o===`mark-read`?`…`:`Mark read`}),!r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn`,disabled:a||o!==null,onClick:()=>u(`acknowledge`,()=>L.acknowledge(d)),children:o===`acknowledge`?`…`:`Acknowledge`}),!r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:a||o!==null,onClick:()=>u(`reopen`,()=>L.reopen(d)),children:o===`reopen`?`…`:`Reopen`}),!r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn danger`,disabled:a||o!==null,onClick:()=>u(`soft-delete`,()=>L.softDelete(d)),children:o===`soft-delete`?`…`:`Delete`}),r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:a||o!==null,onClick:()=>u(`restore`,()=>L.restore(d)),children:o===`restore`?`…`:`Restore`}),c!==null&&(0,S.jsx)(`span`,{className:`hq-msg-action-error`,title:c,children:c})]})}function z(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function B(e){return e.length<=14?e:`${e.slice(0,8)}…${e.slice(-4)}`}var V={note:{icon:o,tone:`info`},ask:{icon:c,tone:`warn`},assign:{icon:t,tone:`warn`},steer:{icon:c,tone:`warn`},btw:{icon:i,tone:`info`},broadcast:{icon:s,tone:`info`},status:{icon:d,tone:`idle`},result:{icon:l,tone:`running`},review:{icon:f,tone:`info`},control:{icon:u,tone:`error`}};Object.keys(V);var H=`hq-operator`;function U({flat:e,defaultExpanded:t}){let[r,i]=(0,x.useState)(!!t),a=e.message,o=a.hasBody||a.bodyPreview!==void 0&&a.bodyPreview.length>0,s=V[a.type]??{icon:n,tone:`info`},c=s.icon,l=`${a.from} → ${a.to}`;return(0,S.jsxs)(`div`,{className:`hq-msg`+(a.completed?` done`:``),children:[(0,S.jsxs)(`div`,{className:`hq-msg-head`,children:[(0,S.jsx)(`span`,{className:`hq-msg-icon`,title:a.type,children:(0,S.jsx)(c,{size:13})}),(0,S.jsx)(`span`,{className:`hq-pill `+s.tone,children:a.type}),a.priority===`high`&&(0,S.jsx)(`span`,{className:`hq-pill error`,children:`high`}),a.priority===`low`&&(0,S.jsx)(`span`,{className:`hq-pill idle`,children:`low`}),(0,S.jsx)(`span`,{className:`hq-msg-subject`,title:a.subject,children:a.subject||`(no subject)`}),(0,S.jsx)(`span`,{className:`hq-mono hq-msg-route`,children:l}),(0,S.jsx)(`span`,{className:`hq-mono hq-msg-time`,title:a.timestamp,children:z(a.timestamp)}),(0,S.jsx)(`span`,{className:`hq-mono hq-msg-id`,children:B(a.messageId)}),(0,S.jsx)(`span`,{className:`hq-msg-flag `+(a.completed?`done`:`open`),children:a.completed?`completed${a.completedBy===void 0?``:` by ${a.completedBy}`}`:`open`}),o&&(0,S.jsx)(`button`,{type:`button`,className:`hq-toggle hq-msg-toggle`,onClick:()=>i(e=>!e),"aria-expanded":r,"aria-label":r?`Collapse body`:`Expand body`,children:r?`▾`:`▸`})]}),r&&(0,S.jsxs)(`div`,{className:`hq-msg-body`,children:[a.bodyPreview!==void 0&&a.bodyPreview.length>0?(0,S.jsx)(`pre`,{className:`hq-msg-pre`,children:a.bodyPreview}):(0,S.jsx)(`div`,{className:`hq-empty hq-pad-sm`,children:`(empty body)`}),a.outcomePreview!==void 0&&a.outcomePreview.length>0&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`hq-msg-sublabel`,children:`outcome`}),(0,S.jsx)(`pre`,{className:`hq-msg-pre`,children:a.outcomePreview})]}),(0,S.jsxs)(`div`,{className:`hq-msg-meta`,children:[(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`source:`}),` `,e.source]}),a.replyTo!==void 0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`reply to:`}),` `,B(a.replyTo)]}),a.senderSessionId!==void 0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`sender session:`}),` `,B(a.senderSessionId)]}),(a.readCount??0)>0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`reads:`}),` `,a.readCount]}),a.unreadCount!==void 0&&a.unreadCount>0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`unread:`}),` `,a.unreadCount]}),a.task!==void 0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`task:`}),` `,a.task.taskId??`—`,a.task.agentName===void 0?``:` · ${a.task.agentName}`,a.task.status===void 0?``:` (${a.task.status})`]})]}),e.projectId!==void 0&&(0,S.jsx)(R,{mailId:a.mailId,actorId:H,projectId:e.projectId})]})]})}var W=[`ask`,`assign`,`steer`,`review`,`result`,`status`,`broadcast`,`note`,`btw`,`control`],G=[`high`,`normal`,`low`];function K({snapshot:e,events:t}={}){let n=v(e=>e.snapshot),r=e===void 0?n:e,i=t===void 0?v.getState().events:t,a=m(),[o,s]=(0,x.useReducer)(M,(0,x.useMemo)(()=>{let e=a.mailbox;return{types:new Set(e.types),priorities:new Set(e.priorities),projectIds:new Set,includeCompleted:e.includeCompleted,query:e.query}},[a.mailbox]));(0,x.useEffect)(()=>{_({query:o.query,types:Array.from(o.types),priorities:Array.from(o.priorities),includeCompleted:o.includeCompleted})},[o.query,o.types,o.priorities,o.includeCompleted]);let c=(0,x.useMemo)(()=>A(r??null,i).projects.map(e=>({projectId:e.projectId,count:e.messages.length})),[r,i]),l=(0,x.useMemo)(()=>P(r??null,i,{types:Array.from(o.types),priorities:Array.from(o.priorities),projectIds:Array.from(o.projectIds),includeCompleted:o.includeCompleted,query:o.query||void 0,limit:500}),[r,i,o]),u=o.types.size+o.priorities.size+o.projectIds.size+ +!o.includeCompleted+ +(o.query.trim().length>0);return(0,S.jsxs)(`div`,{children:[(0,S.jsxs)(`div`,{className:`hq-card-title`,children:[`Live mailbox feed · `,l.returned,` of `,l.totalMatched,` message`,l.totalMatched===1?``:`s`,l.truncated?` · refined to fit`:``]}),(0,S.jsxs)(`div`,{className:`hq-card hq-mailbox-filterbar`,children:[(0,S.jsx)(`label`,{className:`hq-label`,htmlFor:`mailbox-live-query`,children:`Search`}),(0,S.jsx)(`input`,{id:`mailbox-live-query`,className:`hq-input`,value:o.query,onChange:e=>s({type:`set-query`,value:e.target.value}),placeholder:`subject / sender / recipient / body…`}),(0,S.jsx)(q,{title:`Types`,children:W.map(e=>(0,S.jsx)(J,{selected:o.types.has(e),label:e,onClick:()=>s({type:`toggle-type`,value:e})},e))}),(0,S.jsx)(q,{title:`Priority`,children:G.map(e=>(0,S.jsx)(J,{selected:o.priorities.has(e),label:e,tone:e===`high`?`error`:e===`low`?`idle`:`info`,onClick:()=>s({type:`toggle-priority`,value:e})},e))}),c.length>0&&(0,S.jsx)(q,{title:`Projects`,children:c.map(e=>(0,S.jsx)(J,{selected:o.projectIds.has(e.projectId),label:`${e.projectId} (${e.count})`,onClick:()=>s({type:`toggle-project`,value:e.projectId})},e.projectId))}),(0,S.jsxs)(`div`,{className:`hq-row hq-mailbox-filter-actions`,children:[(0,S.jsxs)(`label`,{className:`hq-check`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:o.includeCompleted,onChange:e=>s({type:`set-include-completed`,value:e.target.checked})}),`include completed`]}),(0,S.jsxs)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:u===0,onClick:()=>s({type:`clear-all`}),children:[`Clear filters`,u>0?` (${u})`:``]})]})]}),l.entries.length===0?(0,S.jsx)(`div`,{className:`hq-empty`,children:`No mailbox activity matches the current filters.`}):(0,S.jsx)(`div`,{className:`hq-msg-list hq-live-feed`,children:l.entries.map((e,t)=>(0,S.jsx)(U,{flat:e.flat,defaultExpanded:t===0&&o.query.trim().length>0},e.key))})]})}function q({title:e,children:t}){return(0,S.jsxs)(`div`,{className:`hq-filter-section`,children:[(0,S.jsx)(`div`,{className:`hq-msg-sublabel`,children:e}),(0,S.jsx)(`div`,{className:`hq-filter-chip-row`,children:t})]})}function J({selected:e,label:t,onClick:n,tone:r=`info`}){return(0,S.jsx)(`button`,{type:`button`,className:`hq-filter-chip hq-pill ${r}${e?` selected`:``}`,"aria-pressed":e,onClick:n,children:t})}function Y(){let{snapshot:e,events:t}=v(g(e=>({snapshot:e.snapshot,events:e.events}))),[n,r]=(0,x.useState)(`live`),{events:i}=b(`mailbox.event`,300),a=(0,x.useMemo)(()=>[...i,...t.filter(e=>e.type!==`mailbox.event`)],[i,t]),{projects:o,hasAnyActivity:s}=(0,x.useMemo)(()=>A(e,a),[e,a]),c=e?.totals.unreadMailboxMessages??0,l=e?.totals.incompleteMailboxMessages??0,u=(0,x.useMemo)(()=>{let t=new Map;for(let n of e?.projects??[])t.set(n.projectId,{projectId:n.projectId,label:n.projectName});for(let e of o)t.has(e.projectId)||t.set(e.projectId,{projectId:e.projectId});return Array.from(t.values())},[e,o]);return o.length===0&&u.length===0?(0,S.jsx)(`div`,{className:`hq-empty`,children:`No mailbox activity reported by connected clients.`}):(0,S.jsxs)(`div`,{children:[(0,S.jsxs)(`div`,{className:`hq-card-title`,children:[`Mailbox Activity — `,o.length,` project`,o.length===1?``:`s`,` ·`,` `,c,` unread · `,l,` incomplete`,s?` · showing detailed messages`:``]}),(0,S.jsx)(w,{projects:u}),(0,S.jsxs)(`div`,{className:`hq-mailbox-modebar`,role:`tablist`,"aria-label":`Mailbox view mode`,children:[(0,S.jsx)(`button`,{type:`button`,role:`tab`,className:`hq-btn secondary`+(n===`live`?` hq-btn-selected`:``),"aria-selected":n===`live`,onClick:()=>r(`live`),children:`Live feed`}),(0,S.jsx)(`button`,{type:`button`,role:`tab`,className:`hq-btn secondary`+(n===`grouped`?` hq-btn-selected`:``),"aria-selected":n===`grouped`,onClick:()=>r(`grouped`),children:`Grouped by project`})]}),n===`live`?(0,S.jsx)(K,{snapshot:e,events:a}):o.map(e=>(0,S.jsx)(X,{group:e},e.projectId))]})}function X({group:e}){let[t,n]=(0,x.useState)(!0);return(0,S.jsxs)(`div`,{className:`hq-card`,children:[(0,S.jsxs)(`div`,{className:`hq-row hq-row-baseline`,children:[(0,S.jsx)(`button`,{type:`button`,className:`hq-toggle`,onClick:()=>n(e=>!e),"aria-label":t?`Collapse project messages`:`Expand project messages`,children:t?`▾`:`▸`}),(0,S.jsx)(`span`,{className:`hq-text-bright`,children:e.projectId}),e.scope!==void 0&&(0,S.jsx)(`span`,{className:`hq-pill info`,children:e.scope}),e.mailboxId!==void 0&&(0,S.jsx)(`span`,{className:`hq-mono hq-text-dim`,children:e.mailboxId}),(0,S.jsxs)(`span`,{className:`hq-mono hq-text-dim hq-ml-auto`,children:[e.messages.length,` message`,e.messages.length===1?``:`s`]})]}),(0,S.jsxs)(`div`,{className:`hq-grid hq-mt-8`,style:{gridTemplateColumns:`repeat(5,1fr)`},children:[(0,S.jsx)(Z,{label:`messages`,value:e.messages.length}),(0,S.jsx)(Z,{label:`unread`,value:e.unreadCount,accent:e.unreadCount>0?`amber`:void 0}),(0,S.jsx)(Z,{label:`incomplete`,value:e.incompleteCount,accent:e.incompleteCount>0?`red`:void 0}),(0,S.jsx)(Z,{label:`high-priority`,value:e.highPriorityCount,accent:e.highPriorityCount>0?`red`:void 0}),(0,S.jsx)(Z,{label:`online agents`,value:e.onlineAgentCount,accent:e.onlineAgentCount>0?`green`:void 0})]}),t&&e.messages.length>0&&(0,S.jsx)(`div`,{className:`hq-msg-list hq-mt-12`,children:e.messages.map(e=>(0,S.jsx)(U,{flat:e},e.key))}),t&&e.messages.length===0&&(0,S.jsx)(`div`,{className:`hq-empty hq-cockpit-empty`,children:`Snapshot counters reported for this project, but no detailed mailbox events have streamed yet.`})]})}function Z({label:e,value:t,accent:n}){return(0,S.jsxs)(`div`,{className:`hq-text-center`,children:[(0,S.jsx)(`div`,{className:`hq-stat-num`,style:{color:n===`amber`?`var(--amber)`:n===`red`?`var(--red)`:n===`green`?`var(--green)`:`var(--text)`},children:t}),(0,S.jsx)(`div`,{className:`hq-stat-label`,children:e})]})}export{Y as MailboxView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{C as t,F as n,I as r,N as i,Nt as a,O as o,P as s,U as c,bt as l,h as u,nt as d,y as f}from"./icons-BlGYTg3M.js";import{i as p}from"./markdown-Dm2qU66U.js";import{a as m,c as h,f as g,i as _,l as v,u as y}from"./index-DzLBc00n.js";import{t as b}from"./use-backfilled-events-DMTqAxHb.js";var x=e(a(),1),S=p(),C=[{value:`steer`,label:`steer — redirect the current work`},{value:`btw`,label:`btw — FYI, no action required`},{value:`queue`,label:`queue — note for the next agent`},{value:`broadcast`,label:`broadcast — all agents in the project`}];function w({projects:e,sender:t}){let n=t??h,[i,a]=(0,x.useState)(!1),[o,s]=(0,x.useState)(``),[c,l]=(0,x.useState)(`steer`),[u,d]=(0,x.useState)(`leader`),[f,p]=(0,x.useState)(`normal`),[m,g]=(0,x.useState)(``),[_,v]=(0,x.useState)(``),[y,b]=(0,x.useState)({phase:`idle`}),w=o||e[0]?.projectId||``,T=y.phase!==`sending`&&_.trim().length>0&&w.length>0,E=async()=>{if(T){b({phase:`sending`});try{let e=await n({projectId:w,type:c,...c===`broadcast`?{}:{to:u.trim()||`leader`},subject:m.trim()||`HQ prompt`,body:_.trim(),priority:f});b({phase:`sent`,messageId:e.messageId}),v(``)}catch(e){b({phase:`error`,message:e instanceof Error?e.message:String(e)})}}};return i?(0,S.jsxs)(`div`,{className:`hq-card hq-composer`,children:[(0,S.jsxs)(`div`,{className:`hq-row hq-row-baseline`,children:[(0,S.jsx)(`span`,{className:`hq-card-title hq-title-inline`,children:`Send to project mailbox`}),(0,S.jsx)(`span`,{className:`hq-composer-hint`,children:`lands in the mailbox file — picked up by the next agent, no live client needed`}),(0,S.jsx)(`button`,{type:`button`,className:`hq-toggle hq-ml-auto`,"aria-label":`Collapse composer`,onClick:()=>a(!1),children:`▾`})]}),(0,S.jsxs)(`div`,{className:`hq-composer-grid`,children:[(0,S.jsxs)(`label`,{className:`hq-composer-field`,children:[(0,S.jsx)(`span`,{children:`project`}),(0,S.jsx)(`select`,{className:`hq-select`,value:w,onChange:e=>s(e.target.value),children:e.map(e=>(0,S.jsx)(`option`,{value:e.projectId,children:e.label??e.projectId},e.projectId))})]}),(0,S.jsxs)(`label`,{className:`hq-composer-field`,children:[(0,S.jsx)(`span`,{children:`type`}),(0,S.jsx)(`select`,{className:`hq-select`,value:c,onChange:e=>l(e.target.value),children:C.map(e=>(0,S.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),c!==`broadcast`&&(0,S.jsxs)(`label`,{className:`hq-composer-field`,children:[(0,S.jsx)(`span`,{children:`to`}),(0,S.jsx)(`input`,{className:`hq-input`,value:u,placeholder:`leader`,onChange:e=>d(e.target.value)})]}),(0,S.jsxs)(`label`,{className:`hq-composer-field`,children:[(0,S.jsx)(`span`,{children:`priority`}),(0,S.jsxs)(`select`,{className:`hq-select`,value:f,onChange:e=>p(e.target.value),children:[(0,S.jsx)(`option`,{value:`high`,children:`high`}),(0,S.jsx)(`option`,{value:`normal`,children:`normal`}),(0,S.jsx)(`option`,{value:`low`,children:`low`})]})]})]}),(0,S.jsx)(`input`,{className:`hq-input`,value:m,placeholder:`subject (optional)`,onChange:e=>g(e.target.value)}),(0,S.jsx)(`textarea`,{className:`hq-input hq-composer-body`,value:_,rows:3,placeholder:`Message body — e.g. “after the current task, run the full test suite”`,onChange:e=>v(e.target.value)}),(0,S.jsxs)(`div`,{className:`hq-row`,children:[(0,S.jsx)(`button`,{type:`button`,className:`hq-btn`,disabled:!T,onClick:()=>void E(),children:y.phase===`sending`?`Sending…`:`Send`}),y.phase===`sent`&&(0,S.jsxs)(`span`,{className:`hq-composer-status ok`,children:[`delivered`,y.messageId===void 0?``:` · ${y.messageId.slice(0,8)}`]}),y.phase===`error`&&(0,S.jsx)(`span`,{className:`hq-composer-status err`,title:y.message,children:y.message})]})]}):(0,S.jsxs)(`div`,{className:`hq-composer-bar`,children:[(0,S.jsxs)(`button`,{type:`button`,className:`hq-btn`,disabled:e.length===0,title:e.length===0?`No projects reported yet — connect a client first`:`Write a message into a project mailbox (works with zero connected agents)`,onClick:()=>a(!0),children:[(0,S.jsx)(r,{size:13}),` Compose`]}),y.phase===`sent`&&(0,S.jsxs)(`span`,{className:`hq-composer-status ok`,children:[`delivered`,y.messageId===void 0?``:` · ${y.messageId.slice(0,8)}`]})]})}function T(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.mailboxId==`string`&&(t.scope===`project`||t.scope===`global`)&&Array.isArray(t.messages)&&Array.isArray(t.agents)&&typeof t.totals==`object`&&t.totals!==null}function E(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.mailboxId==`string`&&typeof t.action==`string`&&(t.message===void 0||typeof t.message==`object`)}function D(e,t){let n=e.get(t);return n===void 0&&(n={projectId:t,messages:[],countersFromSnapshot:!1,onlineAgentCount:0,highPriorityCount:0,unreadCount:0,incompleteCount:0},e.set(t,n)),n}function O(e){let t=0,n=0,r=0;for(let i of e){let e=i.message;e.priority===`high`&&(t+=1),e.completed||(r+=1,(e.readCount??0)===0&&(n+=1))}return{highPriorityCount:t,unreadCount:n,incompleteCount:r}}function k(e){let t=new Map;for(let n of e)(t.get(n.message.mailId)===void 0||n.source===`event`)&&t.set(n.message.mailId,n);return Array.from(t.values()).sort((e,t)=>t.message.timestamp.localeCompare(e.message.timestamp))}function A(e,t){let n=new Map;if(e!==null)for(let t of e.mailboxes){let e=D(n,t.projectId);e.mailboxId=t.mailboxId,e.scope=t.scope,e.onlineAgentCount=t.onlineAgentCount,e.highPriorityCount=t.highPriorityCount,e.unreadCount=t.unreadCount,e.incompleteCount=t.incompleteCount,e.countersFromSnapshot=!0}for(let e of t){if(e.type!==`mailbox.snapshot`||!T(e.payload))continue;let t=e.payload,r=D(n,e.projectId);r.mailboxId=t.mailboxId,r.scope=t.scope;for(let n of t.messages)r.messages.push({message:n,source:`snapshot`,key:`s:${e.id}:${n.messageId}`,projectId:e.projectId})}let r=new Map;for(let e of t){if(e.type!==`mailbox.event`||!E(e.payload))continue;let t=e.payload,i=D(n,e.projectId);i.mailboxId=t.mailboxId,i.scope=i.scope??`project`,t.message!==void 0&&!r.has(t.message.mailId)&&(r.set(t.message.mailId,i),i.messages.push({message:t.message,source:`event`,key:`e:${t.message.mailId}:${e.seq}`,projectId:e.projectId})),t.agent?.online&&(i.onlineAgentCount+=1)}for(let e of n.values())if(e.messages=k(e.messages),!e.countersFromSnapshot){let t=O(e.messages);e.highPriorityCount=t.highPriorityCount,e.unreadCount=t.unreadCount,e.incompleteCount=t.incompleteCount}let i=Array.from(n.values()).sort((e,t)=>{let n=e.messages[0]?.message.timestamp??``;return(t.messages[0]?.message.timestamp??``).localeCompare(n)});return{projects:i,hasAnyActivity:i.some(e=>e.messages.length>0)}}var j=Object.freeze({types:new Set,priorities:new Set,projectIds:new Set,includeCompleted:!0,query:``});function M(e,t){switch(t.type){case`toggle-type`:{let n=new Set(e.types);return n.has(t.value)?n.delete(t.value):n.add(t.value),{...e,types:n}}case`toggle-priority`:{let n=new Set(e.priorities);return n.has(t.value)?n.delete(t.value):n.add(t.value),{...e,priorities:n}}case`toggle-project`:{let n=new Set(e.projectIds);return n.has(t.value)?n.delete(t.value):n.add(t.value),{...e,projectIds:n}}case`set-query`:return{...e,query:t.value};case`set-include-completed`:return{...e,includeCompleted:t.value};case`clear-all`:return j;default:return e}}function N(e,t={}){let n=t.includeCompleted??!0,r=t.types&&t.types.length>0?new Set(t.types):null,i=t.priorities&&t.priorities.length>0?new Set(t.priorities):null,a=t.projectIds&&t.projectIds.length>0?new Set(t.projectIds):null,o=t.query?.trim().toLowerCase()??``,s=t.limit??500,c=[];for(let t of e){let e=t.message;!n&&e.completed||r&&!r.has(e.type)||i&&!i.has(e.priority)||a||o.length>0&&!`${e.subject}\n${e.from}\n${e.to}\n${e.bodyPreview??``}`.toLowerCase().includes(o)||c.push({key:t.key,flat:t})}c.sort((e,t)=>{let n=t.flat.message.timestamp.localeCompare(e.flat.message.timestamp);return n===0?e.flat.message.mailId.localeCompare(t.flat.message.mailId):n});let l=c.length,u=l>s,d=u?c.slice(0,s):c;return{totalMatched:l,returned:d.length,truncated:u,entries:d}}function P(e,t,n={}){let{projectIds:r,...i}=n,a=A(e,t),o=[],s=r!==void 0&&r.length>0?new Set(r):null;for(let e of a.projects)s&&!s.has(e.projectId)||(o=o.concat(e.messages));return N(o,i)}function F(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.error==`string`)return!0;if(typeof t.error!=`object`||t.error===null)return!1;let n=t.error;return typeof n.code==`string`&&typeof n.message==`string`}async function I(e){let t=await y(`/api/mailbox/messages/${encodeURIComponent(e.mailId)}/action`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(t.status===401&&v.getState().markAuthRequired(),!t.ok){let e=`${t.status} ${t.statusText}`;try{let n=await t.json();F(n)&&(e=typeof n.error==`string`?n.error:`${n.error.code}: ${n.error.message}`)}catch{}throw Error(`mailbox action failed — ${e}`)}return await t.json()}var L={markRead:e=>I({...e,action:`mark-read`}),acknowledge:e=>I({...e,action:`acknowledge`}),reopen:e=>I({...e,action:`reopen`}),softDelete:e=>I({...e,action:`soft-delete`}),restore:e=>I({...e,action:`restore`})};function R({mailId:e,actorId:t,projectId:n,isDeleted:r=!1,onAction:i,disabled:a=!1}){let[o,s]=(0,x.useState)(null),[c,l]=(0,x.useState)(null),u=async(t,n)=>{if(!(a||o!==null)){s(t),l(null);try{await n(),i?.(e,t)}catch(e){l(e instanceof Error?e.message:String(e))}finally{s(null)}}},d={mailId:e,readerId:t,projectId:n};return(0,S.jsxs)(`div`,{className:`hq-msg-actions`,children:[!r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:a||o!==null,onClick:()=>u(`mark-read`,()=>L.markRead(d)),children:o===`mark-read`?`…`:`Mark read`}),!r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn`,disabled:a||o!==null,onClick:()=>u(`acknowledge`,()=>L.acknowledge(d)),children:o===`acknowledge`?`…`:`Acknowledge`}),!r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:a||o!==null,onClick:()=>u(`reopen`,()=>L.reopen(d)),children:o===`reopen`?`…`:`Reopen`}),!r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn danger`,disabled:a||o!==null,onClick:()=>u(`soft-delete`,()=>L.softDelete(d)),children:o===`soft-delete`?`…`:`Delete`}),r&&(0,S.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:a||o!==null,onClick:()=>u(`restore`,()=>L.restore(d)),children:o===`restore`?`…`:`Restore`}),c!==null&&(0,S.jsx)(`span`,{className:`hq-msg-action-error`,title:c,children:c})]})}function z(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function B(e){return e.length<=14?e:`${e.slice(0,8)}…${e.slice(-4)}`}var V={note:{icon:o,tone:`info`},ask:{icon:c,tone:`warn`},assign:{icon:t,tone:`warn`},steer:{icon:c,tone:`warn`},btw:{icon:i,tone:`info`},broadcast:{icon:s,tone:`info`},status:{icon:d,tone:`idle`},result:{icon:l,tone:`running`},review:{icon:f,tone:`info`},control:{icon:u,tone:`error`}};Object.keys(V);var H=`hq-operator`;function U({flat:e,defaultExpanded:t}){let[r,i]=(0,x.useState)(!!t),a=e.message,o=a.hasBody||a.bodyPreview!==void 0&&a.bodyPreview.length>0,s=V[a.type]??{icon:n,tone:`info`},c=s.icon,l=`${a.from} → ${a.to}`;return(0,S.jsxs)(`div`,{className:`hq-msg`+(a.completed?` done`:``),children:[(0,S.jsxs)(`div`,{className:`hq-msg-head`,children:[(0,S.jsx)(`span`,{className:`hq-msg-icon`,title:a.type,children:(0,S.jsx)(c,{size:13})}),(0,S.jsx)(`span`,{className:`hq-pill `+s.tone,children:a.type}),a.priority===`high`&&(0,S.jsx)(`span`,{className:`hq-pill error`,children:`high`}),a.priority===`low`&&(0,S.jsx)(`span`,{className:`hq-pill idle`,children:`low`}),(0,S.jsx)(`span`,{className:`hq-msg-subject`,title:a.subject,children:a.subject||`(no subject)`}),(0,S.jsx)(`span`,{className:`hq-mono hq-msg-route`,children:l}),(0,S.jsx)(`span`,{className:`hq-mono hq-msg-time`,title:a.timestamp,children:z(a.timestamp)}),(0,S.jsx)(`span`,{className:`hq-mono hq-msg-id`,children:B(a.messageId)}),(0,S.jsx)(`span`,{className:`hq-msg-flag `+(a.completed?`done`:`open`),children:a.completed?`completed${a.completedBy===void 0?``:` by ${a.completedBy}`}`:`open`}),o&&(0,S.jsx)(`button`,{type:`button`,className:`hq-toggle hq-msg-toggle`,onClick:()=>i(e=>!e),"aria-expanded":r,"aria-label":r?`Collapse body`:`Expand body`,children:r?`▾`:`▸`})]}),r&&(0,S.jsxs)(`div`,{className:`hq-msg-body`,children:[a.bodyPreview!==void 0&&a.bodyPreview.length>0?(0,S.jsx)(`pre`,{className:`hq-msg-pre`,children:a.bodyPreview}):(0,S.jsx)(`div`,{className:`hq-empty hq-pad-sm`,children:`(empty body)`}),a.outcomePreview!==void 0&&a.outcomePreview.length>0&&(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(`div`,{className:`hq-msg-sublabel`,children:`outcome`}),(0,S.jsx)(`pre`,{className:`hq-msg-pre`,children:a.outcomePreview})]}),(0,S.jsxs)(`div`,{className:`hq-msg-meta`,children:[(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`source:`}),` `,e.source]}),a.replyTo!==void 0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`reply to:`}),` `,B(a.replyTo)]}),a.senderSessionId!==void 0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`sender session:`}),` `,B(a.senderSessionId)]}),(a.readCount??0)>0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`reads:`}),` `,a.readCount]}),a.unreadCount!==void 0&&a.unreadCount>0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`unread:`}),` `,a.unreadCount]}),a.task!==void 0&&(0,S.jsxs)(`span`,{children:[(0,S.jsx)(`strong`,{children:`task:`}),` `,a.task.taskId??`—`,a.task.agentName===void 0?``:` · ${a.task.agentName}`,a.task.status===void 0?``:` (${a.task.status})`]})]}),e.projectId!==void 0&&(0,S.jsx)(R,{mailId:a.mailId,actorId:H,projectId:e.projectId})]})]})}var W=[`ask`,`assign`,`steer`,`review`,`result`,`status`,`broadcast`,`note`,`btw`,`control`],G=[`high`,`normal`,`low`];function K({snapshot:e,events:t}={}){let n=v(e=>e.snapshot),r=e===void 0?n:e,i=t===void 0?v.getState().events:t,a=m(),[o,s]=(0,x.useReducer)(M,(0,x.useMemo)(()=>{let e=a.mailbox;return{types:new Set(e.types),priorities:new Set(e.priorities),projectIds:new Set,includeCompleted:e.includeCompleted,query:e.query}},[a.mailbox]));(0,x.useEffect)(()=>{_({query:o.query,types:Array.from(o.types),priorities:Array.from(o.priorities),includeCompleted:o.includeCompleted})},[o.query,o.types,o.priorities,o.includeCompleted]);let c=(0,x.useMemo)(()=>A(r??null,i).projects.map(e=>({projectId:e.projectId,count:e.messages.length})),[r,i]),l=(0,x.useMemo)(()=>P(r??null,i,{types:Array.from(o.types),priorities:Array.from(o.priorities),projectIds:Array.from(o.projectIds),includeCompleted:o.includeCompleted,query:o.query||void 0,limit:500}),[r,i,o]),u=o.types.size+o.priorities.size+o.projectIds.size+ +!o.includeCompleted+ +(o.query.trim().length>0);return(0,S.jsxs)(`div`,{children:[(0,S.jsxs)(`div`,{className:`hq-card-title`,children:[`Live mailbox feed · `,l.returned,` of `,l.totalMatched,` message`,l.totalMatched===1?``:`s`,l.truncated?` · refined to fit`:``]}),(0,S.jsxs)(`div`,{className:`hq-card hq-mailbox-filterbar`,children:[(0,S.jsx)(`label`,{className:`hq-label`,htmlFor:`mailbox-live-query`,children:`Search`}),(0,S.jsx)(`input`,{id:`mailbox-live-query`,className:`hq-input`,value:o.query,onChange:e=>s({type:`set-query`,value:e.target.value}),placeholder:`subject / sender / recipient / body…`}),(0,S.jsx)(q,{title:`Types`,children:W.map(e=>(0,S.jsx)(J,{selected:o.types.has(e),label:e,onClick:()=>s({type:`toggle-type`,value:e})},e))}),(0,S.jsx)(q,{title:`Priority`,children:G.map(e=>(0,S.jsx)(J,{selected:o.priorities.has(e),label:e,tone:e===`high`?`error`:e===`low`?`idle`:`info`,onClick:()=>s({type:`toggle-priority`,value:e})},e))}),c.length>0&&(0,S.jsx)(q,{title:`Projects`,children:c.map(e=>(0,S.jsx)(J,{selected:o.projectIds.has(e.projectId),label:`${e.projectId} (${e.count})`,onClick:()=>s({type:`toggle-project`,value:e.projectId})},e.projectId))}),(0,S.jsxs)(`div`,{className:`hq-row hq-mailbox-filter-actions`,children:[(0,S.jsxs)(`label`,{className:`hq-check`,children:[(0,S.jsx)(`input`,{type:`checkbox`,checked:o.includeCompleted,onChange:e=>s({type:`set-include-completed`,value:e.target.checked})}),`include completed`]}),(0,S.jsxs)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:u===0,onClick:()=>s({type:`clear-all`}),children:[`Clear filters`,u>0?` (${u})`:``]})]})]}),l.entries.length===0?(0,S.jsx)(`div`,{className:`hq-empty`,children:`No mailbox activity matches the current filters.`}):(0,S.jsx)(`div`,{className:`hq-msg-list hq-live-feed`,children:l.entries.map((e,t)=>(0,S.jsx)(U,{flat:e.flat,defaultExpanded:t===0&&o.query.trim().length>0},e.key))})]})}function q({title:e,children:t}){return(0,S.jsxs)(`div`,{className:`hq-filter-section`,children:[(0,S.jsx)(`div`,{className:`hq-msg-sublabel`,children:e}),(0,S.jsx)(`div`,{className:`hq-filter-chip-row`,children:t})]})}function J({selected:e,label:t,onClick:n,tone:r=`info`}){return(0,S.jsx)(`button`,{type:`button`,className:`hq-filter-chip hq-pill ${r}${e?` selected`:``}`,"aria-pressed":e,onClick:n,children:t})}function Y(){let{snapshot:e,events:t}=v(g(e=>({snapshot:e.snapshot,events:e.events}))),[n,r]=(0,x.useState)(`live`),{events:i}=b(`mailbox.event`,300),a=(0,x.useMemo)(()=>[...i,...t.filter(e=>e.type!==`mailbox.event`)],[i,t]),{projects:o,hasAnyActivity:s}=(0,x.useMemo)(()=>A(e,a),[e,a]),c=e?.totals.unreadMailboxMessages??0,l=e?.totals.incompleteMailboxMessages??0,u=(0,x.useMemo)(()=>{let t=new Map;for(let n of e?.projects??[])t.set(n.projectId,{projectId:n.projectId,label:n.projectName});for(let e of o)t.has(e.projectId)||t.set(e.projectId,{projectId:e.projectId});return Array.from(t.values())},[e,o]);return o.length===0&&u.length===0?(0,S.jsx)(`div`,{className:`hq-empty`,children:`No mailbox activity reported by connected clients.`}):(0,S.jsxs)(`div`,{children:[(0,S.jsxs)(`div`,{className:`hq-card-title`,children:[`Mailbox Activity — `,o.length,` project`,o.length===1?``:`s`,` ·`,` `,c,` unread · `,l,` incomplete`,s?` · showing detailed messages`:``]}),(0,S.jsx)(w,{projects:u}),(0,S.jsxs)(`div`,{className:`hq-mailbox-modebar`,role:`tablist`,"aria-label":`Mailbox view mode`,children:[(0,S.jsx)(`button`,{type:`button`,role:`tab`,className:`hq-btn secondary`+(n===`live`?` hq-btn-selected`:``),"aria-selected":n===`live`,onClick:()=>r(`live`),children:`Live feed`}),(0,S.jsx)(`button`,{type:`button`,role:`tab`,className:`hq-btn secondary`+(n===`grouped`?` hq-btn-selected`:``),"aria-selected":n===`grouped`,onClick:()=>r(`grouped`),children:`Grouped by project`})]}),n===`live`?(0,S.jsx)(K,{snapshot:e,events:a}):o.map(e=>(0,S.jsx)(X,{group:e},e.projectId))]})}function X({group:e}){let[t,n]=(0,x.useState)(!0);return(0,S.jsxs)(`div`,{className:`hq-card`,children:[(0,S.jsxs)(`div`,{className:`hq-row hq-row-baseline`,children:[(0,S.jsx)(`button`,{type:`button`,className:`hq-toggle`,onClick:()=>n(e=>!e),"aria-label":t?`Collapse project messages`:`Expand project messages`,children:t?`▾`:`▸`}),(0,S.jsx)(`span`,{className:`hq-text-bright`,children:e.projectId}),e.scope!==void 0&&(0,S.jsx)(`span`,{className:`hq-pill info`,children:e.scope}),e.mailboxId!==void 0&&(0,S.jsx)(`span`,{className:`hq-mono hq-text-dim`,children:e.mailboxId}),(0,S.jsxs)(`span`,{className:`hq-mono hq-text-dim hq-ml-auto`,children:[e.messages.length,` message`,e.messages.length===1?``:`s`]})]}),(0,S.jsxs)(`div`,{className:`hq-grid hq-mt-8`,style:{gridTemplateColumns:`repeat(5,1fr)`},children:[(0,S.jsx)(Z,{label:`messages`,value:e.messages.length}),(0,S.jsx)(Z,{label:`unread`,value:e.unreadCount,accent:e.unreadCount>0?`amber`:void 0}),(0,S.jsx)(Z,{label:`incomplete`,value:e.incompleteCount,accent:e.incompleteCount>0?`red`:void 0}),(0,S.jsx)(Z,{label:`high-priority`,value:e.highPriorityCount,accent:e.highPriorityCount>0?`red`:void 0}),(0,S.jsx)(Z,{label:`online agents`,value:e.onlineAgentCount,accent:e.onlineAgentCount>0?`green`:void 0})]}),t&&e.messages.length>0&&(0,S.jsx)(`div`,{className:`hq-msg-list hq-mt-12`,children:e.messages.map(e=>(0,S.jsx)(U,{flat:e},e.key))}),t&&e.messages.length===0&&(0,S.jsx)(`div`,{className:`hq-empty hq-cockpit-empty`,children:`Snapshot counters reported for this project, but no detailed mailbox events have streamed yet.`})]})}function Z({label:e,value:t,accent:n}){return(0,S.jsxs)(`div`,{className:`hq-text-center`,children:[(0,S.jsx)(`div`,{className:`hq-stat-num`,style:{color:n===`amber`?`var(--amber)`:n===`red`?`var(--red)`:n===`green`?`var(--green)`:`var(--text)`},children:t}),(0,S.jsx)(`div`,{className:`hq-stat-label`,children:e})]})}export{Y as MailboxView};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{K as t,L as n,Nt as r,R as i,S as a,f as o,ft as s,p as c}from"./icons-BlGYTg3M.js";import{i as l}from"./markdown-Dm2qU66U.js";import{d as u,u as d}from"./index-Ckam6WOR.js";var f=e(r(),1),p=l();async function m(e){let t=e.statusText||`HTTP ${e.status}`;try{let n=await e.json();return typeof n.error==`string`?n.error:n.error?.message??t}catch{return t}}function h(){let[e,r]=(0,f.useState)(null),[l,h]=(0,f.useState)(``),[g,_]=(0,f.useState)(``),[v,y]=(0,f.useState)(``),[b,x]=(0,f.useState)(!1),[S,C]=(0,f.useState)(null),[w,T]=(0,f.useState)(!1),E=async()=>{let e=await d(`/api/auth/status`);if(!e.ok)throw Error(await m(e));r(await e.json())};(0,f.useEffect)(()=>{E().catch(e=>{C({tone:`error`,text:e instanceof Error?e.message:String(e)})})},[]);let D=e?.passwordMode===!0&&e.authKind===`password`,O=g.length>=8&&g.length<=1024,k=g===v,A=O&&k&&(!D||l.length>0)&&!b,j=async()=>{if(A){x(!0),C(null);try{let t=await d(`/api/auth/password`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...D?{currentPassword:l}:{},newPassword:g})});if(!t.ok)throw Error(await m(t));r(await t.json()),h(``),_(``),y(``),C({tone:`ok`,text:e?.passwordMode?`Password changed.`:`Password enabled.`})}catch(e){C({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{x(!1)}}},M=async()=>{x(!0),C(null);try{let e=await d(`/api/auth/password`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...D?{currentPassword:l}:{}})});if(!e.ok)throw Error(await m(e));r(await e.json()),h(``),T(!1),C({tone:`ok`,text:`Password protection removed.`})}catch(e){C({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{x(!1)}},N=async()=>{x(!0);try{await d(`/api/logout`,{method:`POST`})}finally{u(),window.location.reload()}},P=async()=>{if(!(!e?.publicOrigin||!e.passwordMode))try{await navigator.clipboard.writeText(e.publicOrigin),C({tone:`ok`,text:`Public tunnel URL copied.`})}catch{C({tone:`error`,text:`Could not copy the public tunnel URL.`})}};return(0,p.jsxs)(`div`,{className:`hq-security-page`,children:[(0,p.jsxs)(`section`,{className:`hq-security-summary`,"aria-label":`Authentication status`,children:[(0,p.jsxs)(`div`,{className:`hq-security-card`,children:[(0,p.jsx)(c,{size:18}),(0,p.jsx)(`span`,{children:`Browser access`}),(0,p.jsx)(`strong`,{children:e?.loggedIn?`Authenticated`:`Checking…`})]}),(0,p.jsxs)(`div`,{className:`hq-security-card`,children:[(0,p.jsx)(t,{size:18}),(0,p.jsx)(`span`,{children:`Browser tokens`}),(0,p.jsx)(`strong`,{children:e?.tokenMode?`Enabled`:`Disabled`})]}),(0,p.jsxs)(`div`,{className:`hq-security-card`,children:[(0,p.jsx)(i,{size:18}),(0,p.jsx)(`span`,{children:`Password login`}),(0,p.jsx)(`strong`,{children:e?.passwordMode?`Enabled`:`Disabled`})]}),(0,p.jsxs)(`div`,{className:`hq-security-card`,children:[(0,p.jsx)(a,{size:18}),(0,p.jsx)(`span`,{children:`Public tunnel`}),(0,p.jsx)(`strong`,{children:e?.publicRelay?`Active`:`Disabled`}),e?.publicOrigin&&e.passwordMode?(0,p.jsxs)(`button`,{type:`button`,className:`hq-security-copy`,"aria-label":`Copy public tunnel URL`,title:e.publicOrigin,onClick:()=>void P(),children:[(0,p.jsx)(s,{size:12}),`Copy URL`]}):null]})]}),(0,p.jsxs)(`section`,{className:`hq-security-panel`,children:[(0,p.jsxs)(`div`,{className:`hq-security-panel-head`,children:[(0,p.jsxs)(`div`,{children:[(0,p.jsx)(`span`,{children:`Browser credential`}),(0,p.jsx)(`h2`,{children:e?.passwordMode?`Change HQ password`:`Enable HQ password`}),(0,p.jsx)(`p`,{children:`Passwords are stored as salted scrypt hashes. Changing the password invalidates older password sessions.`})]}),(0,p.jsx)(i,{size:22})]}),S?(0,p.jsx)(`div`,{className:`hq-security-message`,"data-tone":S.tone,role:`status`,children:S.text}):null,(0,p.jsxs)(`div`,{className:`hq-security-form`,children:[D?(0,p.jsxs)(`label`,{children:[(0,p.jsx)(`span`,{children:`Current password`}),(0,p.jsx)(`input`,{type:`password`,autoComplete:`current-password`,value:l,onChange:e=>h(e.target.value)})]}):null,(0,p.jsxs)(`label`,{children:[(0,p.jsx)(`span`,{children:`New password`}),(0,p.jsx)(`input`,{type:`password`,autoComplete:`new-password`,minLength:8,maxLength:1024,value:g,onChange:e=>_(e.target.value)}),(0,p.jsx)(`small`,{children:`Minimum 8 characters.`})]}),(0,p.jsxs)(`label`,{children:[(0,p.jsx)(`span`,{children:`Confirm new password`}),(0,p.jsx)(`input`,{type:`password`,autoComplete:`new-password`,minLength:8,maxLength:1024,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&j()}}),v&&!k?(0,p.jsx)(`small`,{"data-error":!0,children:`Passwords do not match.`}):null]}),(0,p.jsx)(`div`,{className:`hq-security-actions`,children:(0,p.jsxs)(`button`,{type:`button`,className:`hq-btn`,disabled:!A,onClick:()=>void j(),children:[(0,p.jsx)(c,{size:14}),b?`Saving…`:e?.passwordMode?`Change password`:`Enable password`]})})]})]}),(0,p.jsxs)(`section`,{className:`hq-security-panel danger-zone`,children:[(0,p.jsxs)(`div`,{className:`hq-security-panel-head`,children:[(0,p.jsxs)(`div`,{children:[(0,p.jsx)(`span`,{children:`Session and recovery`}),(0,p.jsx)(`h2`,{children:`Access controls`}),(0,p.jsx)(`p`,{children:`Browser tokens remain available as a recovery path. Public tunnel mode will refuse to remove the last browser authentication method.`})]}),(0,p.jsx)(o,{size:22})]}),(0,p.jsxs)(`div`,{className:`hq-security-actions split`,children:[(0,p.jsxs)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:b,onClick:()=>void N(),children:[(0,p.jsx)(n,{size:14}),`Log out this browser`]}),e?.passwordMode?w?(0,p.jsxs)(`div`,{className:`hq-security-confirm-remove`,children:[(0,p.jsx)(`span`,{children:`Remove password protection?`}),(0,p.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:b,onClick:()=>T(!1),children:`Cancel`}),(0,p.jsx)(`button`,{type:`button`,className:`hq-btn danger`,disabled:b||D&&!l,onClick:()=>void M(),children:`Remove password`})]}):(0,p.jsxs)(`button`,{type:`button`,className:`hq-btn danger`,disabled:b,onClick:()=>T(!0),children:[(0,p.jsx)(o,{size:14}),`Remove password`]}):null]})]})]})}export{h as SettingsView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{K as t,L as n,Nt as r,R as i,S as a,f as o,ft as s,p as c}from"./icons-BlGYTg3M.js";import{i as l}from"./markdown-Dm2qU66U.js";import{d as u,u as d}from"./index-DzLBc00n.js";var f=e(r(),1),p=l();async function m(e){let t=e.statusText||`HTTP ${e.status}`;try{let n=await e.json();return typeof n.error==`string`?n.error:n.error?.message??t}catch{return t}}function h(){let[e,r]=(0,f.useState)(null),[l,h]=(0,f.useState)(``),[g,_]=(0,f.useState)(``),[v,y]=(0,f.useState)(``),[b,x]=(0,f.useState)(!1),[S,C]=(0,f.useState)(null),[w,T]=(0,f.useState)(!1),E=async()=>{let e=await d(`/api/auth/status`);if(!e.ok)throw Error(await m(e));r(await e.json())};(0,f.useEffect)(()=>{E().catch(e=>{C({tone:`error`,text:e instanceof Error?e.message:String(e)})})},[]);let D=e?.passwordMode===!0&&e.authKind===`password`,O=g.length>=8&&g.length<=1024,k=g===v,A=O&&k&&(!D||l.length>0)&&!b,j=async()=>{if(A){x(!0),C(null);try{let t=await d(`/api/auth/password`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...D?{currentPassword:l}:{},newPassword:g})});if(!t.ok)throw Error(await m(t));r(await t.json()),h(``),_(``),y(``),C({tone:`ok`,text:e?.passwordMode?`Password changed.`:`Password enabled.`})}catch(e){C({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{x(!1)}}},M=async()=>{x(!0),C(null);try{let e=await d(`/api/auth/password`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...D?{currentPassword:l}:{}})});if(!e.ok)throw Error(await m(e));r(await e.json()),h(``),T(!1),C({tone:`ok`,text:`Password protection removed.`})}catch(e){C({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{x(!1)}},N=async()=>{x(!0);try{await d(`/api/logout`,{method:`POST`})}finally{u(),window.location.reload()}},P=async()=>{if(!(!e?.publicOrigin||!e.passwordMode))try{await navigator.clipboard.writeText(e.publicOrigin),C({tone:`ok`,text:`Public tunnel URL copied.`})}catch{C({tone:`error`,text:`Could not copy the public tunnel URL.`})}};return(0,p.jsxs)(`div`,{className:`hq-security-page`,children:[(0,p.jsxs)(`section`,{className:`hq-security-summary`,"aria-label":`Authentication status`,children:[(0,p.jsxs)(`div`,{className:`hq-security-card`,children:[(0,p.jsx)(c,{size:18}),(0,p.jsx)(`span`,{children:`Browser access`}),(0,p.jsx)(`strong`,{children:e?.loggedIn?`Authenticated`:`Checking…`})]}),(0,p.jsxs)(`div`,{className:`hq-security-card`,children:[(0,p.jsx)(t,{size:18}),(0,p.jsx)(`span`,{children:`Browser tokens`}),(0,p.jsx)(`strong`,{children:e?.tokenMode?`Enabled`:`Disabled`})]}),(0,p.jsxs)(`div`,{className:`hq-security-card`,children:[(0,p.jsx)(i,{size:18}),(0,p.jsx)(`span`,{children:`Password login`}),(0,p.jsx)(`strong`,{children:e?.passwordMode?`Enabled`:`Disabled`})]}),(0,p.jsxs)(`div`,{className:`hq-security-card`,children:[(0,p.jsx)(a,{size:18}),(0,p.jsx)(`span`,{children:`Public tunnel`}),(0,p.jsx)(`strong`,{children:e?.publicRelay?`Active`:`Disabled`}),e?.publicOrigin&&e.passwordMode?(0,p.jsxs)(`button`,{type:`button`,className:`hq-security-copy`,"aria-label":`Copy public tunnel URL`,title:e.publicOrigin,onClick:()=>void P(),children:[(0,p.jsx)(s,{size:12}),`Copy URL`]}):null]})]}),(0,p.jsxs)(`section`,{className:`hq-security-panel`,children:[(0,p.jsxs)(`div`,{className:`hq-security-panel-head`,children:[(0,p.jsxs)(`div`,{children:[(0,p.jsx)(`span`,{children:`Browser credential`}),(0,p.jsx)(`h2`,{children:e?.passwordMode?`Change HQ password`:`Enable HQ password`}),(0,p.jsx)(`p`,{children:`Passwords are stored as salted scrypt hashes. Changing the password invalidates older password sessions.`})]}),(0,p.jsx)(i,{size:22})]}),S?(0,p.jsx)(`div`,{className:`hq-security-message`,"data-tone":S.tone,role:`status`,children:S.text}):null,(0,p.jsxs)(`div`,{className:`hq-security-form`,children:[D?(0,p.jsxs)(`label`,{children:[(0,p.jsx)(`span`,{children:`Current password`}),(0,p.jsx)(`input`,{type:`password`,autoComplete:`current-password`,value:l,onChange:e=>h(e.target.value)})]}):null,(0,p.jsxs)(`label`,{children:[(0,p.jsx)(`span`,{children:`New password`}),(0,p.jsx)(`input`,{type:`password`,autoComplete:`new-password`,minLength:8,maxLength:1024,value:g,onChange:e=>_(e.target.value)}),(0,p.jsx)(`small`,{children:`Minimum 8 characters.`})]}),(0,p.jsxs)(`label`,{children:[(0,p.jsx)(`span`,{children:`Confirm new password`}),(0,p.jsx)(`input`,{type:`password`,autoComplete:`new-password`,minLength:8,maxLength:1024,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&j()}}),v&&!k?(0,p.jsx)(`small`,{"data-error":!0,children:`Passwords do not match.`}):null]}),(0,p.jsx)(`div`,{className:`hq-security-actions`,children:(0,p.jsxs)(`button`,{type:`button`,className:`hq-btn`,disabled:!A,onClick:()=>void j(),children:[(0,p.jsx)(c,{size:14}),b?`Saving…`:e?.passwordMode?`Change password`:`Enable password`]})})]})]}),(0,p.jsxs)(`section`,{className:`hq-security-panel danger-zone`,children:[(0,p.jsxs)(`div`,{className:`hq-security-panel-head`,children:[(0,p.jsxs)(`div`,{children:[(0,p.jsx)(`span`,{children:`Session and recovery`}),(0,p.jsx)(`h2`,{children:`Access controls`}),(0,p.jsx)(`p`,{children:`Browser tokens remain available as a recovery path. Public tunnel mode will refuse to remove the last browser authentication method.`})]}),(0,p.jsx)(o,{size:22})]}),(0,p.jsxs)(`div`,{className:`hq-security-actions split`,children:[(0,p.jsxs)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:b,onClick:()=>void N(),children:[(0,p.jsx)(n,{size:14}),`Log out this browser`]}),e?.passwordMode?w?(0,p.jsxs)(`div`,{className:`hq-security-confirm-remove`,children:[(0,p.jsx)(`span`,{children:`Remove password protection?`}),(0,p.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:b,onClick:()=>T(!1),children:`Cancel`}),(0,p.jsx)(`button`,{type:`button`,className:`hq-btn danger`,disabled:b||D&&!l,onClick:()=>void M(),children:`Remove password`})]}):(0,p.jsxs)(`button`,{type:`button`,className:`hq-btn danger`,disabled:b,onClick:()=>T(!0),children:[(0,p.jsx)(o,{size:14}),`Remove password`]}):null]})]})]})}export{h as SettingsView};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Nt as t}from"./icons-BlGYTg3M.js";import{i as n}from"./markdown-Dm2qU66U.js";import{o as r}from"./index-Ckam6WOR.js";var i=e(t(),1),a=n();function o({points:e,color:t,height:n=140,format:r,emptyLabel:o=`no data`}){let[s,c]=(0,i.useState)(null),l=(0,i.useId)(),u=n,d=u-10-22,f=(0,i.useMemo)(()=>Math.max(...e.map(e=>e.value),0),[e]);if(e.length===0||f<=0)return(0,a.jsx)(`div`,{className:`hq-chart-empty`,children:o});let p=e.length,m=666/p,h=Math.max(2,Math.min(18,m-2)),g=e=>10+d*(1-e/f),_=[f*.25,f*.5,f*.75,f],v=Math.max(1,Math.round(p/5)),y=e=>new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),b=s===null?void 0:e[s];return(0,a.jsxs)(`div`,{className:`hq-chart`,children:[(0,a.jsxs)(`svg`,{viewBox:`0 0 720 ${u}`,className:`hq-chart-svg`,role:`img`,"aria-label":`Time series chart with ${e.length} data points`,onMouseLeave:()=>c(null),onMouseMove:t=>{let n=t.currentTarget.getBoundingClientRect(),r=(t.clientX-n.left)/n.width*720,i=Math.floor((r-46)/m);c(i>=0&&i<e.length?i:null)},children:[(0,a.jsx)(`clipPath`,{id:l,children:(0,a.jsx)(`rect`,{x:46,y:10,width:666,height:d})}),_.map((e,t)=>(0,a.jsxs)(`g`,{children:[(0,a.jsx)(`line`,{x1:46,x2:712,y1:g(e),y2:g(e),className:`hq-chart-grid`}),(0,a.jsx)(`text`,{x:40,y:g(e)+3,className:`hq-chart-ytick`,textAnchor:`end`,children:r(e)})]},t)),(0,a.jsx)(`line`,{x1:46,x2:712,y1:10+d,y2:10+d,className:`hq-chart-axis`}),(0,a.jsx)(`g`,{clipPath:`url(#${l})`,children:e.map((e,n)=>{let r=46+n*m+(m-h)/2,i=g(e.value),o=10+d-i;return o<=0?null:(0,a.jsx)(`rect`,{x:r,y:i,width:h,height:o,rx:Math.min(3,h/2),fill:t,opacity:s===null||s===n?1:.45},n)})}),e.map((e,t)=>t%v===0?(0,a.jsx)(`text`,{x:46+t*m+m/2,y:u-6,className:`hq-chart-xtick`,textAnchor:`middle`,children:y(e.ts)},t):null),(0,a.jsx)(`rect`,{x:46,y:10,width:666,height:d,fill:`transparent`})]}),b!==void 0&&(0,a.jsxs)(`div`,{className:`hq-chart-tooltip`,children:[(0,a.jsx)(`span`,{className:`hq-chart-tooltip-swatch`,style:{background:t}}),(0,a.jsx)(`span`,{className:`hq-chart-tooltip-value`,children:r(b.value)}),(0,a.jsx)(`span`,{className:`hq-chart-tooltip-time`,children:y(b.ts)})]})]})}var s=[{label:`1h`,ms:3600*1e3},{label:`6h`,ms:360*60*1e3},{label:`24h`,ms:1440*60*1e3},{label:`7d`,ms:10080*60*1e3}];function c(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(Math.round(e))}function l(e,t){let n=new Map;for(let r of e){let e=r[t];if(e!==void 0)for(let[t,r]of Object.entries(e)){let e=n.get(t);e===void 0?n.set(t,{...r}):(e.costUsd+=r.costUsd,e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cacheRead=(e.cacheRead??0)+(r.cacheRead??0),e.cacheWrite=(e.cacheWrite??0)+(r.cacheWrite??0))}}return[...n.entries()].map(([e,t])=>({key:e,entry:t})).sort((e,t)=>t.entry.costUsd-e.entry.costUsd)}function u(){let[e,t]=(0,i.useState)([]),[n,u]=(0,i.useState)(null),[d,f]=(0,i.useState)(s[2].ms);(0,i.useEffect)(()=>{let e=!1,n=()=>{r(`/api/trends/cost`).then(n=>{e||(t(n.samples),u(null))}).catch(t=>{e||u(t.message)})};n();let i=setInterval(n,3e4);return()=>{e=!0,clearInterval(i)}},[]);let{shown:p,totalCost:m,totalTokens:h,totalTools:g,byModel:_,byProvider:v,totalCacheRead:y,totalCacheWrite:b}=(0,i.useMemo)(()=>{let t=Date.now()-d,n=e.filter(e=>e.ts>=t),r=n.length>0?n:e.slice(-24),i=r.reduce((e,t)=>e+t.costUsd,0),a=r.reduce((e,t)=>e+t.inputTokens+t.outputTokens,0),o=r.reduce((e,t)=>e+t.toolCalls,0),s=l(r,`byModel`);return{shown:r,totalCost:i,totalTokens:a,totalTools:o,byModel:s,byProvider:l(r,`byProvider`),totalCacheRead:s.reduce((e,t)=>e+(t.entry.cacheRead??0),0),totalCacheWrite:s.reduce((e,t)=>e+(t.entry.cacheWrite??0),0)}},[e,d]);if(n!==null)return(0,a.jsxs)(`div`,{className:`hq-empty`,children:[`Error loading trends: `,n]});if(e.length===0)return(0,a.jsx)(`div`,{className:`hq-empty`,children:`No trend data yet. Trends accumulate as cost signals arrive.`});let x=_.length>0,S=y+b>0?y/(y+b)*100:null;return(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`div`,{className:`hq-filter-row`,children:[s.map(e=>(0,a.jsx)(`button`,{type:`button`,className:`hq-pill hq-filter-chip${d===e.ms?` selected`:``}`,onClick:()=>f(e.ms),children:e.label},e.label)),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle hq-ml-auto`,children:[p.length,` × 5-min buckets`]})]}),(0,a.jsxs)(`div`,{className:`hq-stat-row`,children:[(0,a.jsxs)(`div`,{className:`hq-stat-block`,children:[(0,a.jsxs)(`span`,{className:`hq-stat-block-value accent-cost`,children:[`$`,m.toFixed(4)]}),(0,a.jsx)(`span`,{className:`hq-stat-block-label`,children:`cost`})]}),(0,a.jsxs)(`div`,{className:`hq-stat-block`,children:[(0,a.jsx)(`span`,{className:`hq-stat-block-value accent-tokens`,children:c(h)}),(0,a.jsx)(`span`,{className:`hq-stat-block-label`,children:`tokens`})]}),(0,a.jsxs)(`div`,{className:`hq-stat-block`,children:[(0,a.jsx)(`span`,{className:`hq-stat-block-value accent-tools`,children:g.toLocaleString()}),(0,a.jsx)(`span`,{className:`hq-stat-block-label`,children:`tool calls`})]}),S!==null&&(0,a.jsxs)(`div`,{className:`hq-stat-block`,children:[(0,a.jsxs)(`span`,{className:`hq-stat-block-value`,children:[S.toFixed(0),`%`]}),(0,a.jsx)(`span`,{className:`hq-stat-block-label`,children:`cache hit`}),(0,a.jsxs)(`span`,{className:`hq-stat-block-sub`,children:[c(y),` read · `,c(b),` write`]})]})]}),(0,a.jsxs)(`div`,{className:`hq-card`,children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`Cost (USD)`}),(0,a.jsx)(o,{points:p.map(e=>({ts:e.ts,value:e.costUsd})),color:`var(--chart-1)`,format:e=>`$${e>=1?e.toFixed(2):e.toFixed(4)}`})]}),(0,a.jsxs)(`div`,{className:`hq-card`,children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`Tokens (in + out)`}),(0,a.jsx)(o,{points:p.map(e=>({ts:e.ts,value:e.inputTokens+e.outputTokens})),color:`var(--chart-2)`,format:c})]}),(0,a.jsxs)(`div`,{className:`hq-card`,children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`Tool calls`}),(0,a.jsx)(o,{points:p.map(e=>({ts:e.ts,value:e.toolCalls})),color:`var(--chart-3)`,format:e=>String(Math.round(e))})]}),x&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`By Model`}),(0,a.jsx)(`div`,{className:`hq-card`,children:_.map(({key:e,entry:t})=>{let n=m>0?t.costUsd/m*100:0;return(0,a.jsxs)(`div`,{className:`hq-row`,children:[(0,a.jsx)(`span`,{className:`hq-text-bright`,children:e}),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle`,children:[c(t.inputTokens),`→`,c(t.outputTokens),t.cacheRead!==void 0||t.cacheWrite!==void 0?` · cache ${c((t.cacheRead??0)+(t.cacheWrite??0))}`:``]}),(0,a.jsxs)(`span`,{className:`hq-cost-amount hq-ml-auto`,children:[`$`,t.costUsd.toFixed(4)]}),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle`,children:[n.toFixed(1),`%`]})]},e)})}),v.length>1&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`By Provider`}),(0,a.jsx)(`div`,{className:`hq-card`,children:v.map(({key:e,entry:t})=>{let n=m>0?t.costUsd/m*100:0;return(0,a.jsxs)(`div`,{className:`hq-row`,children:[(0,a.jsx)(`span`,{className:`hq-text-bright`,children:e}),(0,a.jsxs)(`span`,{className:`hq-cost-amount hq-ml-auto`,children:[`$`,t.costUsd.toFixed(4)]}),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle`,children:[n.toFixed(1),`%`]})]},e)})})]})]})]})}export{u as TrendsView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Nt as t}from"./icons-BlGYTg3M.js";import{i as n}from"./markdown-Dm2qU66U.js";import{o as r}from"./index-DzLBc00n.js";var i=e(t(),1),a=n();function o({points:e,color:t,height:n=140,format:r,emptyLabel:o=`no data`}){let[s,c]=(0,i.useState)(null),l=(0,i.useId)(),u=n,d=u-10-22,f=(0,i.useMemo)(()=>Math.max(...e.map(e=>e.value),0),[e]);if(e.length===0||f<=0)return(0,a.jsx)(`div`,{className:`hq-chart-empty`,children:o});let p=e.length,m=666/p,h=Math.max(2,Math.min(18,m-2)),g=e=>10+d*(1-e/f),_=[f*.25,f*.5,f*.75,f],v=Math.max(1,Math.round(p/5)),y=e=>new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),b=s===null?void 0:e[s];return(0,a.jsxs)(`div`,{className:`hq-chart`,children:[(0,a.jsxs)(`svg`,{viewBox:`0 0 720 ${u}`,className:`hq-chart-svg`,role:`img`,"aria-label":`Time series chart with ${e.length} data points`,onMouseLeave:()=>c(null),onMouseMove:t=>{let n=t.currentTarget.getBoundingClientRect(),r=(t.clientX-n.left)/n.width*720,i=Math.floor((r-46)/m);c(i>=0&&i<e.length?i:null)},children:[(0,a.jsx)(`clipPath`,{id:l,children:(0,a.jsx)(`rect`,{x:46,y:10,width:666,height:d})}),_.map((e,t)=>(0,a.jsxs)(`g`,{children:[(0,a.jsx)(`line`,{x1:46,x2:712,y1:g(e),y2:g(e),className:`hq-chart-grid`}),(0,a.jsx)(`text`,{x:40,y:g(e)+3,className:`hq-chart-ytick`,textAnchor:`end`,children:r(e)})]},t)),(0,a.jsx)(`line`,{x1:46,x2:712,y1:10+d,y2:10+d,className:`hq-chart-axis`}),(0,a.jsx)(`g`,{clipPath:`url(#${l})`,children:e.map((e,n)=>{let r=46+n*m+(m-h)/2,i=g(e.value),o=10+d-i;return o<=0?null:(0,a.jsx)(`rect`,{x:r,y:i,width:h,height:o,rx:Math.min(3,h/2),fill:t,opacity:s===null||s===n?1:.45},n)})}),e.map((e,t)=>t%v===0?(0,a.jsx)(`text`,{x:46+t*m+m/2,y:u-6,className:`hq-chart-xtick`,textAnchor:`middle`,children:y(e.ts)},t):null),(0,a.jsx)(`rect`,{x:46,y:10,width:666,height:d,fill:`transparent`})]}),b!==void 0&&(0,a.jsxs)(`div`,{className:`hq-chart-tooltip`,children:[(0,a.jsx)(`span`,{className:`hq-chart-tooltip-swatch`,style:{background:t}}),(0,a.jsx)(`span`,{className:`hq-chart-tooltip-value`,children:r(b.value)}),(0,a.jsx)(`span`,{className:`hq-chart-tooltip-time`,children:y(b.ts)})]})]})}var s=[{label:`1h`,ms:3600*1e3},{label:`6h`,ms:360*60*1e3},{label:`24h`,ms:1440*60*1e3},{label:`7d`,ms:10080*60*1e3}];function c(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(Math.round(e))}function l(e,t){let n=new Map;for(let r of e){let e=r[t];if(e!==void 0)for(let[t,r]of Object.entries(e)){let e=n.get(t);e===void 0?n.set(t,{...r}):(e.costUsd+=r.costUsd,e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cacheRead=(e.cacheRead??0)+(r.cacheRead??0),e.cacheWrite=(e.cacheWrite??0)+(r.cacheWrite??0))}}return[...n.entries()].map(([e,t])=>({key:e,entry:t})).sort((e,t)=>t.entry.costUsd-e.entry.costUsd)}function u(){let[e,t]=(0,i.useState)([]),[n,u]=(0,i.useState)(null),[d,f]=(0,i.useState)(s[2].ms);(0,i.useEffect)(()=>{let e=!1,n=()=>{r(`/api/trends/cost`).then(n=>{e||(t(n.samples),u(null))}).catch(t=>{e||u(t.message)})};n();let i=setInterval(n,3e4);return()=>{e=!0,clearInterval(i)}},[]);let{shown:p,totalCost:m,totalTokens:h,totalTools:g,byModel:_,byProvider:v,totalCacheRead:y,totalCacheWrite:b}=(0,i.useMemo)(()=>{let t=Date.now()-d,n=e.filter(e=>e.ts>=t),r=n.length>0?n:e.slice(-24),i=r.reduce((e,t)=>e+t.costUsd,0),a=r.reduce((e,t)=>e+t.inputTokens+t.outputTokens,0),o=r.reduce((e,t)=>e+t.toolCalls,0),s=l(r,`byModel`);return{shown:r,totalCost:i,totalTokens:a,totalTools:o,byModel:s,byProvider:l(r,`byProvider`),totalCacheRead:s.reduce((e,t)=>e+(t.entry.cacheRead??0),0),totalCacheWrite:s.reduce((e,t)=>e+(t.entry.cacheWrite??0),0)}},[e,d]);if(n!==null)return(0,a.jsxs)(`div`,{className:`hq-empty`,children:[`Error loading trends: `,n]});if(e.length===0)return(0,a.jsx)(`div`,{className:`hq-empty`,children:`No trend data yet. Trends accumulate as cost signals arrive.`});let x=_.length>0,S=y+b>0?y/(y+b)*100:null;return(0,a.jsxs)(`div`,{children:[(0,a.jsxs)(`div`,{className:`hq-filter-row`,children:[s.map(e=>(0,a.jsx)(`button`,{type:`button`,className:`hq-pill hq-filter-chip${d===e.ms?` selected`:``}`,onClick:()=>f(e.ms),children:e.label},e.label)),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle hq-ml-auto`,children:[p.length,` × 5-min buckets`]})]}),(0,a.jsxs)(`div`,{className:`hq-stat-row`,children:[(0,a.jsxs)(`div`,{className:`hq-stat-block`,children:[(0,a.jsxs)(`span`,{className:`hq-stat-block-value accent-cost`,children:[`$`,m.toFixed(4)]}),(0,a.jsx)(`span`,{className:`hq-stat-block-label`,children:`cost`})]}),(0,a.jsxs)(`div`,{className:`hq-stat-block`,children:[(0,a.jsx)(`span`,{className:`hq-stat-block-value accent-tokens`,children:c(h)}),(0,a.jsx)(`span`,{className:`hq-stat-block-label`,children:`tokens`})]}),(0,a.jsxs)(`div`,{className:`hq-stat-block`,children:[(0,a.jsx)(`span`,{className:`hq-stat-block-value accent-tools`,children:g.toLocaleString()}),(0,a.jsx)(`span`,{className:`hq-stat-block-label`,children:`tool calls`})]}),S!==null&&(0,a.jsxs)(`div`,{className:`hq-stat-block`,children:[(0,a.jsxs)(`span`,{className:`hq-stat-block-value`,children:[S.toFixed(0),`%`]}),(0,a.jsx)(`span`,{className:`hq-stat-block-label`,children:`cache hit`}),(0,a.jsxs)(`span`,{className:`hq-stat-block-sub`,children:[c(y),` read · `,c(b),` write`]})]})]}),(0,a.jsxs)(`div`,{className:`hq-card`,children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`Cost (USD)`}),(0,a.jsx)(o,{points:p.map(e=>({ts:e.ts,value:e.costUsd})),color:`var(--chart-1)`,format:e=>`$${e>=1?e.toFixed(2):e.toFixed(4)}`})]}),(0,a.jsxs)(`div`,{className:`hq-card`,children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`Tokens (in + out)`}),(0,a.jsx)(o,{points:p.map(e=>({ts:e.ts,value:e.inputTokens+e.outputTokens})),color:`var(--chart-2)`,format:c})]}),(0,a.jsxs)(`div`,{className:`hq-card`,children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`Tool calls`}),(0,a.jsx)(o,{points:p.map(e=>({ts:e.ts,value:e.toolCalls})),color:`var(--chart-3)`,format:e=>String(Math.round(e))})]}),x&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`By Model`}),(0,a.jsx)(`div`,{className:`hq-card`,children:_.map(({key:e,entry:t})=>{let n=m>0?t.costUsd/m*100:0;return(0,a.jsxs)(`div`,{className:`hq-row`,children:[(0,a.jsx)(`span`,{className:`hq-text-bright`,children:e}),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle`,children:[c(t.inputTokens),`→`,c(t.outputTokens),t.cacheRead!==void 0||t.cacheWrite!==void 0?` · cache ${c((t.cacheRead??0)+(t.cacheWrite??0))}`:``]}),(0,a.jsxs)(`span`,{className:`hq-cost-amount hq-ml-auto`,children:[`$`,t.costUsd.toFixed(4)]}),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle`,children:[n.toFixed(1),`%`]})]},e)})}),v.length>1&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(`div`,{className:`hq-card-title`,children:`By Provider`}),(0,a.jsx)(`div`,{className:`hq-card`,children:v.map(({key:e,entry:t})=>{let n=m>0?t.costUsd/m*100:0;return(0,a.jsxs)(`div`,{className:`hq-row`,children:[(0,a.jsx)(`span`,{className:`hq-text-bright`,children:e}),(0,a.jsxs)(`span`,{className:`hq-cost-amount hq-ml-auto`,children:[`$`,t.costUsd.toFixed(4)]}),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle`,children:[n.toFixed(1),`%`]})]},e)})})]})]})]})}export{u as TrendsView};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Nt as t}from"./icons-BlGYTg3M.js";import{l as n,o as r}from"./index-Ckam6WOR.js";var i=e(t(),1);function a(e,t=200){let a=n(e=>e.events),[o,s]=(0,i.useState)([]),[c,l]=(0,i.useState)(!0);return(0,i.useEffect)(()=>{let n=!1;return r(`/api/events?type=${encodeURIComponent(e)}&limit=${t}`).then(e=>{n||(s([...e.events??[]].reverse()),l(!1))}).catch(()=>{n||l(!1)}),()=>{n=!0}},[e,t]),{events:(0,i.useMemo)(()=>{let t=new Set,n=[];for(let r of o)r.type!==e||t.has(r.id)||(t.add(r.id),n.push(r));for(let r of a)r.type!==e||t.has(r.id)||(t.add(r.id),n.push(r));return n},[o,a,e]),loading:c}}export{a as t};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Nt as t}from"./icons-BlGYTg3M.js";import{l as n,o as r}from"./index-DzLBc00n.js";var i=e(t(),1);function a(e,t=200){let a=n(e=>e.events),[o,s]=(0,i.useState)([]),[c,l]=(0,i.useState)(!0);return(0,i.useEffect)(()=>{let n=!1;return r(`/api/events?type=${encodeURIComponent(e)}&limit=${t}`).then(e=>{n||(s([...e.events??[]].reverse()),l(!1))}).catch(()=>{n||l(!1)}),()=>{n=!0}},[e,t]),{events:(0,i.useMemo)(()=>{let t=new Set,n=[];for(let r of o)r.type!==e||t.has(r.id)||(t.add(r.id),n.push(r));for(let r of a)r.type!==e||t.has(r.id)||(t.add(r.id),n.push(r));return n},[o,a,e]),loading:c}}export{a as t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{$ as t,E as n,Nt as r,Tt as i,c as a,ht as o,l as s}from"./icons-BlGYTg3M.js";import{i as c}from"./markdown-Dm2qU66U.js";import{t as l}from"./use-backfilled-events-BnFvycsd.js";var u=e(r(),1),d=c(),f={allocated:{Icon:n,cls:`info`},committed:{Icon:i,cls:`active`},merged:{Icon:t,cls:`active`},conflict:{Icon:a,cls:`warn`},released:{Icon:s,cls:`idle`},failed:{Icon:o,cls:`error`}};function p({e}){let t=e.payload,r=f[t.kind]??{Icon:n,cls:`info`};return(0,d.jsxs)(`div`,{className:`hq-row`,children:[(0,d.jsx)(r.Icon,{size:14,className:`hq-kind-icon ${r.cls}`}),(0,d.jsx)(`span`,{className:`hq-text-bright`,children:t.kind}),t.branch!==void 0&&(0,d.jsx)(`span`,{className:`hq-pill info`,children:t.branch}),t.kind===`committed`&&(0,d.jsxs)(`span`,{className:`hq-mono hq-diffstat`,children:[(0,d.jsxs)(`span`,{className:`hq-diff-add-count`,children:[`+`,t.insertions??0]}),` `,(0,d.jsxs)(`span`,{className:`hq-diff-del-count`,children:[`−`,t.deletions??0]}),` in `,t.files??0,` file(s)`,` `,t.sha===void 0?``:`(${t.sha.slice(0,7)})`]}),t.kind===`conflict`&&t.conflictFiles!==void 0&&(0,d.jsxs)(`span`,{className:`hq-mono hq-row-error`,children:[`conflicts: `,t.conflictFiles.join(`, `)]}),t.kind===`failed`&&(0,d.jsx)(`span`,{className:`hq-mono hq-row-error`,children:t.error}),(0,d.jsx)(`span`,{className:`hq-mono hq-row-time`,children:new Date(e.timestamp).toLocaleTimeString()})]})}function m(){let{events:e,loading:t}=l(`worktree.event`,300),r=(0,u.useMemo)(()=>{let t=new Map;for(let n of e){let e=n.payload.ownerId??`(unknown)`,r=t.get(e)??[];r.push(n),t.set(e,r)}return Array.from(t.entries()).reverse()},[e]);return r.length===0?(0,d.jsx)(`div`,{className:`hq-empty`,children:t?`Loading worktree history…`:`No worktree events yet. These appear when Goal allocates/merges git worktrees for parallel phases.`}):(0,d.jsxs)(`div`,{children:[(0,d.jsxs)(`div`,{className:`hq-card-title`,children:[`Worktree Lifecycle (`,r.length,` worktree`,r.length===1?``:`s`,`)`]}),r.map(([e,t])=>{let r=t[t.length-1].payload,i=f[r.kind]??{Icon:n,cls:`info`};return(0,d.jsxs)(`div`,{className:`hq-card`,children:[(0,d.jsxs)(`div`,{className:`hq-row hq-lane-head`,children:[(0,d.jsx)(`span`,{className:`hq-mono hq-text-bright`,children:e}),(0,d.jsx)(`span`,{className:`hq-pill ${i.cls}`,children:r.kind}),(0,d.jsxs)(`span`,{className:`hq-mono hq-row-time`,children:[t.length,` events`]})]}),t.map(e=>(0,d.jsx)(p,{e},e.id))]},e)})]})}export{m as WorktreeView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{$ as t,E as n,Nt as r,Tt as i,c as a,ht as o,l as s}from"./icons-BlGYTg3M.js";import{i as c}from"./markdown-Dm2qU66U.js";import{t as l}from"./use-backfilled-events-DMTqAxHb.js";var u=e(r(),1),d=c(),f={allocated:{Icon:n,cls:`info`},committed:{Icon:i,cls:`active`},merged:{Icon:t,cls:`active`},conflict:{Icon:a,cls:`warn`},released:{Icon:s,cls:`idle`},failed:{Icon:o,cls:`error`}};function p({e}){let t=e.payload,r=f[t.kind]??{Icon:n,cls:`info`};return(0,d.jsxs)(`div`,{className:`hq-row`,children:[(0,d.jsx)(r.Icon,{size:14,className:`hq-kind-icon ${r.cls}`}),(0,d.jsx)(`span`,{className:`hq-text-bright`,children:t.kind}),t.branch!==void 0&&(0,d.jsx)(`span`,{className:`hq-pill info`,children:t.branch}),t.kind===`committed`&&(0,d.jsxs)(`span`,{className:`hq-mono hq-diffstat`,children:[(0,d.jsxs)(`span`,{className:`hq-diff-add-count`,children:[`+`,t.insertions??0]}),` `,(0,d.jsxs)(`span`,{className:`hq-diff-del-count`,children:[`−`,t.deletions??0]}),` in `,t.files??0,` file(s)`,` `,t.sha===void 0?``:`(${t.sha.slice(0,7)})`]}),t.kind===`conflict`&&t.conflictFiles!==void 0&&(0,d.jsxs)(`span`,{className:`hq-mono hq-row-error`,children:[`conflicts: `,t.conflictFiles.join(`, `)]}),t.kind===`failed`&&(0,d.jsx)(`span`,{className:`hq-mono hq-row-error`,children:t.error}),(0,d.jsx)(`span`,{className:`hq-mono hq-row-time`,children:new Date(e.timestamp).toLocaleTimeString()})]})}function m(){let{events:e,loading:t}=l(`worktree.event`,300),r=(0,u.useMemo)(()=>{let t=new Map;for(let n of e){let e=n.payload.ownerId??`(unknown)`,r=t.get(e)??[];r.push(n),t.set(e,r)}return Array.from(t.entries()).reverse()},[e]);return r.length===0?(0,d.jsx)(`div`,{className:`hq-empty`,children:t?`Loading worktree history…`:`No worktree events yet. These appear when Goal allocates/merges git worktrees for parallel phases.`}):(0,d.jsxs)(`div`,{children:[(0,d.jsxs)(`div`,{className:`hq-card-title`,children:[`Worktree Lifecycle (`,r.length,` worktree`,r.length===1?``:`s`,`)`]}),r.map(([e,t])=>{let r=t[t.length-1].payload,i=f[r.kind]??{Icon:n,cls:`info`};return(0,d.jsxs)(`div`,{className:`hq-card`,children:[(0,d.jsxs)(`div`,{className:`hq-row hq-lane-head`,children:[(0,d.jsx)(`span`,{className:`hq-mono hq-text-bright`,children:e}),(0,d.jsx)(`span`,{className:`hq-pill ${i.cls}`,children:r.kind}),(0,d.jsxs)(`span`,{className:`hq-mono hq-row-time`,children:[t.length,` events`]})]}),t.map(e=>(0,d.jsx)(p,{e},e.id))]},e)})]})}export{m as WorktreeView};
package/dist/index.html CHANGED
@@ -5,7 +5,7 @@
5
5
  <link rel="icon" type="image/svg+xml" href="/wrongstack.svg" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>WrongStack HQ</title>
8
- <script type="module" crossorigin src="/assets/index-Ckam6WOR.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-DzLBc00n.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-QTnfLwEv.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/icons-BlGYTg3M.js">
11
11
  <link rel="modulepreload" crossorigin href="/assets/vendor-BoaR8QxN.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wrongstack/webui-hq",
3
- "version": "0.291.2",
3
+ "version": "0.292.1",
4
4
  "license": "MIT",
5
5
  "description": "HQ Command Center dashboard — offline React app for the cross-machine coordination surface (port 3499).",
6
6
  "type": "module",
@@ -21,8 +21,8 @@
21
21
  "remark-gfm": "^4.0.1",
22
22
  "virtua": "^0.49.3",
23
23
  "zustand": "5.0.14",
24
- "@wrongstack/core": "0.291.2",
25
- "@wrongstack/tools": "0.291.2"
24
+ "@wrongstack/core": "0.292.1",
25
+ "@wrongstack/tools": "0.292.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/react": "^19.2.17",
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Nt as t}from"./icons-BlGYTg3M.js";import{i as n}from"./markdown-Dm2qU66U.js";import{f as r,l as i,o as a,s as o}from"./index-Ckam6WOR.js";var s=e(t(),1),c=n();function l(){let{snapshot:e,alerts:t,selectedClientId:n,connected:l}=i(r(e=>({snapshot:e.snapshot,alerts:e.alerts,selectedClientId:e.selectedClientId,connected:e.connected}))),m=e,h=m?.totals,g=m?.machines??[],_=m?.projects??[],v=m?.clients??[],y=m?.liveSessions??[],b=v.filter(e=>e.capabilities.includes(`control.receive`)),x=n??b[0]?.clientId??null,S=b.find(e=>e.clientId===x)??b[0]??null,[C,w]=(0,s.useState)([]),[T,E]=(0,s.useState)([]),[D,O]=(0,s.useState)(null),[k,A]=(0,s.useState)(null),[j,M]=(0,s.useState)(null),[N,P]=(0,s.useState)(null);(0,s.useEffect)(()=>{let e=!1,t=()=>{a(`/api/alerts`).then(t=>{e||(w(t.active),E(t.history),O(null))}).catch(t=>{e||O(t instanceof Error?t.message:String(t))})};t();let n=setInterval(t,15e3);return()=>{e=!0,clearInterval(n)}},[]);let F=(0,s.useMemo)(()=>{let e=t.slice(-30).reverse().map(e=>({severity:typeof e.severity==`string`?e.severity:`info`,ruleId:`live`,message:`Live alert envelope received.`,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()})),n=[...C,...T].slice(-30).reverse().map(e=>({severity:typeof e.severity==`string`?e.severity:`info`,ruleId:typeof e.ruleId==`string`?e.ruleId:`alert`,message:typeof e.message==`string`?e.message:``,timestamp:typeof e.lastFiredAt==`string`?e.lastFiredAt:typeof e.firstFiredAt==`string`?e.firstFiredAt:new Date().toISOString()})),r=[...e,...n],i=new Set,a=[];for(let e of r){let t=`${e.ruleId}|${e.message}|${e.timestamp}`;if(!i.has(t)&&(i.add(t),a.push(e),a.length>=12))break}return a},[t,C,T]),I=(0,s.useMemo)(()=>{let e=0,t=0,n=0,r=0,i=0;for(let a of y){a.status===`active`&&(i+=1);for(let i of a.agents??[])e+=1,i.status===`running`||i.status===`streaming`?t+=1:i.status===`waiting_user`?n+=1:i.status===`error`&&(r+=1)}return{total:e,busy:t,waiting:n,errored:r,activeSessions:i}},[y]),L=(0,s.useMemo)(()=>[..._].sort((e,t)=>t.totalCostUsd-e.totalCostUsd).slice(0,4),[_]);async function R(e){if(S!==null){A(e),M(null),P(null);try{let t=e===`pause-noisy`?{subject:`HQ quick action: pause noisy agents`,body:`HQ operator requests: pause non-critical/noisy agent work, reduce chatter, and keep only essential status updates until resumed.`,priority:`high`}:{subject:`HQ quick action: status request`,body:`HQ operator requests a concise status broadcast from active agents: current task, blocker if any, and next expected action.`,priority:`normal`},n=await o(S.clientId,`broadcast`,t);M(`queued ${n.commandId}`)}catch(e){P(e instanceof Error?e.message:String(e))}finally{A(null)}}}let z=[{title:`Fleet`,view:`fleet`,cta:`open fleet`,body:(0,c.jsxs)(`div`,{className:`hq-cockpit-grid`,children:[(0,c.jsx)(u,{label:`machines`,value:g.length}),(0,c.jsx)(u,{label:`clients`,value:v.length}),(0,c.jsx)(u,{label:`sessions`,value:I.activeSessions,accent:I.activeSessions>0?`green`:void 0}),(0,c.jsx)(u,{label:`agents`,value:I.total}),(0,c.jsx)(u,{label:`busy`,value:I.busy,accent:I.busy>0?`green`:void 0}),(0,c.jsx)(u,{label:`waiting`,value:I.waiting,accent:I.waiting>0?`warn`:void 0}),(0,c.jsx)(u,{label:`errored`,value:I.errored,accent:I.errored>0?`error`:void 0}),(0,c.jsx)(u,{label:`cost $`,value:(h?.totalCostUsd??0).toFixed(2),accent:`green`})]})}],B={title:`Alerts`,view:`alerts`,cta:`open alerts`,body:F.length===0?(0,c.jsx)(`div`,{className:`hq-empty hq-cockpit-empty`,children:`No alerts in the last few minutes.`}):(0,c.jsx)(`div`,{className:`hq-cockpit-alert-list`,children:F.map((e,t)=>(0,c.jsxs)(`div`,{className:`hq-cockpit-alert-row`,children:[(0,c.jsx)(`span`,{className:`hq-pill `+p(e.severity),children:e.severity}),(0,c.jsx)(`span`,{className:`hq-mono`,children:e.ruleId}),(0,c.jsx)(`span`,{className:`hq-cockpit-alert-msg`,children:e.message}),(0,c.jsx)(`span`,{className:`hq-mono hq-text-dim hq-ml-auto`,children:f(e.timestamp)})]},`${e.ruleId}-${e.timestamp}-${t}`))})},V={title:`Cost`,view:`cost`,cta:`open cost`,body:L.length===0?(0,c.jsx)(`div`,{className:`hq-empty hq-cockpit-empty`,children:`No cost data yet — connect some clients.`}):(0,c.jsx)(`div`,{className:`hq-cockpit-cost-list`,children:L.map(e=>{let t=(h?.totalCostUsd??0)>0?e.totalCostUsd/h.totalCostUsd*100:0;return(0,c.jsxs)(`div`,{className:`hq-cockpit-cost-row`,children:[(0,c.jsxs)(`div`,{className:`hq-cockpit-cost-line`,children:[(0,c.jsx)(`span`,{className:`hq-cockpit-cost-name`,children:e.projectName}),(0,c.jsx)(`span`,{className:`hq-mono hq-text-dim`,children:e.projectId}),(0,c.jsxs)(`span`,{className:`hq-mono hq-cockpit-cost-amount hq-ml-auto`,children:[`$`,e.totalCostUsd.toFixed(4)]}),(0,c.jsxs)(`span`,{className:`hq-mono hq-text-dim`,children:[t.toFixed(1),`%`]})]}),(0,c.jsx)(`div`,{className:`hq-cockpit-cost-bar`,role:`progressbar`,"aria-label":`${e.projectName} share of fleet cost`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Number(t.toFixed(1)),children:(0,c.jsx)(`span`,{style:{width:`${Math.max(2,t)}%`}})}),(0,c.jsxs)(`div`,{className:`hq-cockpit-cost-meta`,children:[(0,c.jsxs)(`span`,{children:[e.activeSessions,` sessions`]}),(0,c.jsxs)(`span`,{children:[e.activeSubagents,` subagents`]}),(0,c.jsxs)(`span`,{children:[e.activeClients,` clients`]})]})]},e.projectId)})})};return(0,c.jsxs)(`div`,{children:[(0,c.jsx)(`div`,{className:`hq-card-title`,children:`Cockpit`}),(0,c.jsxs)(`div`,{className:`hq-card hq-cockpit-summary`,children:[(0,c.jsxs)(`div`,{className:`hq-row`,children:[(0,c.jsx)(`span`,{className:`hq-pill info`,children:l?`connected`:`reconnecting`}),(0,c.jsxs)(`span`,{className:`hq-pill`,children:[h?.activeMachines??0,` machines`]}),(0,c.jsxs)(`span`,{className:`hq-pill`,children:[h?.activeSessions??0,` sessions`]}),(0,c.jsxs)(`span`,{className:`hq-pill`,children:[h?.activeAgents??0,` agents`]}),(0,c.jsxs)(`span`,{className:`hq-pill green`,children:[`$`,(h?.totalCostUsd??0).toFixed(2)]}),C.length>0&&(0,c.jsxs)(`span`,{className:`hq-pill error`,children:[C.length,` active alerts`]}),D!==null&&(0,c.jsx)(`span`,{className:`hq-pill error`,children:D}),(0,c.jsx)(`button`,{type:`button`,className:`hq-btn secondary hq-ml-auto`,onClick:()=>i.getState().setActiveView(`fleet`),children:`Open Fleet`})]}),(0,c.jsxs)(`section`,{className:`hq-cockpit-actions`,"aria-label":`Cockpit quick actions`,children:[(0,c.jsxs)(`div`,{className:`hq-cockpit-actions-copy`,children:[(0,c.jsx)(`span`,{className:`hq-cockpit-section-title`,children:`Quick Actions`}),(0,c.jsx)(`span`,{className:`hq-mono`,children:S===null?`no controllable client connected`:`target ${d(S.clientId)}`})]}),(0,c.jsxs)(`div`,{className:`hq-cockpit-actions-buttons`,children:[(0,c.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:S===null||k!==null,onClick:()=>void R(`pause-noisy`),children:k===`pause-noisy`?`Queuing…`:`Pause noisy agents`}),(0,c.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,disabled:S===null||k!==null,onClick:()=>void R(`status-request`),children:k===`status-request`?`Queuing…`:`Broadcast status request`}),(0,c.jsx)(`button`,{type:`button`,className:`hq-btn secondary`,onClick:()=>i.getState().setActiveView(`control`),children:`Open Control`})]}),j!==null&&(0,c.jsx)(`span`,{className:`hq-pill info`,children:j}),N!==null&&(0,c.jsx)(`span`,{className:`hq-pill error`,children:N})]})]}),[...z,B,V].map(e=>(0,c.jsxs)(`div`,{className:`hq-card hq-cockpit-section`,children:[(0,c.jsxs)(`div`,{className:`hq-row`,children:[(0,c.jsx)(`span`,{className:`hq-cockpit-section-title`,children:e.title}),(0,c.jsx)(`button`,{type:`button`,className:`hq-btn secondary hq-ml-auto`,onClick:()=>i.getState().setActiveView(e.view),children:e.cta})]}),e.body]},e.title))]})}function u({label:e,value:t,accent:n}){return(0,c.jsxs)(`div`,{className:`hq-stat`+(n?` ${n}`:``),children:[(0,c.jsx)(`span`,{className:`hq-stat-num`,children:t}),(0,c.jsx)(`span`,{className:`hq-stat-label`,children:e})]})}function d(e){return e.length<=18?e:`${e.slice(0,9)}…${e.slice(-6)}`}function f(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString()}function p(e){return e===`critical`||e===`error`||e===`high`?`error`:e===`warn`||e===`warning`||e===`medium`?`warn`:e===`info`||e===`low`?`info`:`idle`}export{l as CockpitView};