@wrongstack/webui-hq 0.296.2 → 0.296.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/cockpit-DvD1_FDz.js","assets/rolldown-runtime-QTnfLwEv.js","assets/icons-BV2PcvP1.js","assets/markdown-HUVrfVaI.js","assets/fleet-map-CPD0vSE4.js","assets/vendor-DT5_U5Rx.js","assets/fleet-topology-BA3kpTuc.js","assets/live-console-BqDIM7Cs.js","assets/mailbox-E7puE59T.js","assets/use-backfilled-events-B_7YE0rb.js","assets/kanban-C9jQWM2T.js","assets/cost-CE_P6ujW.js","assets/brain-D5R8R8BY.js","assets/worktree-D0pa1IH5.js","assets/trends-DqAtNjBm.js","assets/alerts-B_wJljmR.js","assets/control-DGfNRSfd.js","assets/settings-DMQf2eO5.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{A as t,At as n,C as r,Ct as i,E as a,It as o,J as s,K as c,Lt as l,Mt as u,N as d,Pt as f,R as ee,St as p,T as te,Y as ne,_ as re,a as ie,c as m,g as h,ht as g,i as ae,j as oe,mt as _,n as v,o as se,p as ce,rt as le,u as ue,x as y,yt as de}from"./icons-BV2PcvP1.js";import{t as fe}from"./vendor-DT5_U5Rx.js";import{i as pe}from"./markdown-HUVrfVaI.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 b={maxReconnectAttempts:10,initialBackoffMs:1e3,maxBackoffMs:3e4,backoffMultiplier:2,jitterRatio:0,queueLimit:1e3,heartbeatIntervalMs:0,heartbeatTimeoutMs:0};function me(){return{phase:`idle`,reconnectAttempt:0,lastActivityAt:null,stopped:!1}}function he(e){return e.stopped?e:{...e,phase:`connecting`}}function ge(e,t=Date.now()){return{...e,phase:`open`,reconnectAttempt:0,lastActivityAt:t,stopped:!1}}function _e(e,t=Date.now()){return{...e,lastActivityAt:t}}function ve(e){return{...e,phase:`closed`,stopped:!0}}function ye(e,t,n=Date.now(),r=Math.random){if(e.stopped||e.reconnectAttempt>=t.maxReconnectAttempts)return{state:{...e,phase:`closed`},plan:null};let i=e.reconnectAttempt+1,a=Math.min(t.initialBackoffMs*t.backoffMultiplier**(i-1),t.maxBackoffMs),o=(r()*2-1)*t.jitterRatio,s=Math.max(0,Math.round(a*(1+o)));return{state:{...e,phase:`reconnecting`,reconnectAttempt:i},plan:{attempt:i,delayMs:s,retryAt:n+s}}}function be(e,t,n=Date.now()){return e.phase!==`open`||e.lastActivityAt===null||t.heartbeatIntervalMs<=0?!1:n-e.lastActivityAt>t.heartbeatIntervalMs+t.heartbeatTimeoutMs}var xe=`abort,ping,user_message,tool.confirm_result,completion.request,model.switch,model.refine,autonomy.switch,context.clear,context.compact,context.debug,context.editor.open,context.editor.validate,context.editor.apply,context.mode.create,context.mode.delete,context.mode.switch,context.mode.update,context.modes.list,context.repair,mode.switch,modes.list,session.checkpoints,session.delete,session.new,session.rename,session.resume,session.rewind,session.save,sessions.list,side_effects.list,stats.get,todo.update,todos.clear,todos.get,todos.remove`.split(`,`),Se=[`collab.join`,`collab.leave`,`collab.annotate`,`collab.resolve`,`collab.request_pause`,`collab.resume`,`collab.grant_control`,`collab.inject_tool`,`mailbox.agents`,`mailbox.clear`,`mailbox.compact`,`mailbox.messages`,`mailbox.purge`,`mailbox.send`],Ce=`brain.ask,brain.config.get,brain.config.set,brain.risk,brain.status,chronicle.facet,chronicle.facets,chronicle.graph,chronicle.metrics,chronicle.query,chronicle.status,config.doctor,design.list,design.materialize,design.set,design.state,design.swap,design.tune,design.use,design.verify,memory.list,memory.sage.backfillRecoverable,memory.sage.candidateResolve,memory.sage.delete,memory.sage.forFile,memory.sage.get,memory.sage.graph,memory.sage.list,memory.sage.listPage,memory.sage.recover,memory.sage.remember,memory.sage.update`.split(`,`),we=`auth.oauth.cancel,auth.oauth.code,auth.oauth.start,mcp.add,mcp.disable,mcp.discover,mcp.enable,mcp.list,mcp.prompt.get,mcp.prompts,mcp.remove,mcp.resource.read,mcp.resources,mcp.restart,mcp.sleep,mcp.update,mcp.wake,prompts.content,prompts.create,prompts.favorite,prompts.list,prompts.recent,prompts.search,prompts.used,skills.content,skills.create,skills.edit,skills.export,skills.install,skills.list,skills.uninstall,skills.update`.split(`,`),Te=`goal-state.get,goal.addTask,goal.assess,goal.assignTask,goal.clear,goal.get,goal.list,goal.load,goal.moveTask,goal.pause,goal.resume,goal.retryTask,goal.revert,goal.runTask,goal.save,goal.selectPhase,goal.start,goal.state,goal.status,goal.stop,goal.taskStatus,goal.toggleAutonomous,plan.get,plan.item.update,plan.template_use,task.update,tasks.get`.split(`,`),Ee=`sdd.board.cancel_task,sdd.board.cleanup_worktrees,sdd.board.delete_task,sdd.board.destroy,sdd.board.get,sdd.board.list,sdd.board.pause,sdd.board.reassign,sdd.board.resume,sdd.board.retry,sdd.board.retry_all_failed,sdd.board.rollback,sdd.board.set_task_fallbacks,sdd.board.set_task_model,sdd.board.set_task_verification,sdd.board.split_task,sdd.board.stop,sdd.run.from_graph,sdd.run.from_spec,sdd.run.start,sdd.spec.approve,sdd.spec.discard,sdd.spec.get,sdd.spec.message,sdd.spec.start,specs.get,specs.list,specs.taskStatus`.split(`,`),De=[`files.list`,`files.read`,`files.tree`,`files.write`,`git.changes`,`git.diff`,`git.info`,`projects.add`,`projects.list`,`projects.select`,`working_dir.set`,`worktree.cleanup`,`worktree.diff`,`worktree.merge`,`worktree.remove`,`worktree.scan`,`shell.open`,`process.kill`,`process.killAll`,`process.list`,`terminal.close`,`terminal.create`,`terminal.input`,`terminal.resize`],Oe=`codebase.index.server.shutdown,connections.health,connections.service_action,diag.get,key.add,key.delete,key.set_active,key.update,prefs.get,prefs.update,provider.add,provider.clear_models,provider.models,provider.models.search,provider.probe,provider.remove,provider.status.clear,provider.status.get,provider.status.retry,provider.undo_clear,provider.update,providers.list,providers.saved,tool.disable,tool.enable,tools.list,webui.shutdown`.split(`,`),ke=`error,log,pong,side_effects,agent.status_changed,agent.timeline.message,client.status_update,compaction.failed,completion.result,context.compacted,context.debug,context.editor.snapshot,context.editor.validation,context.editor.applied,context.mode.changed,context.modes.list,context.repaired,ctx.max_context,ctx.pct,delegate.completed,delegate.started,iteration.completed,iteration.limit_reached,iteration.started,model.refine_result,modes.list,provider.active_blocked,provider.error,provider.fallback,provider.response,provider.retry,provider.status_changed,provider.stream_error,provider.text_delta,provider.thinking_delta,run.result,session.checkpoints,session.damaged,session.end,session.rewound,session.start,session.stats,sessions.list,sessions.status_update,stats.get,token.cost_estimate_unavailable,token.threshold,tool.confirm_needed,tool.disabled,tool.enabled,tool.executed,tool.loop_detected,tool.progress,tool.started,tools.list,trust.persisted`.split(`,`),Ae=[`collab.annotation.added`,`collab.annotation.resolved`,`collab.event`,`collab.injection.granted`,`collab.participant.joined`,`collab.participant.left`,`collab.pause.granted`,`collab.pause.released`,`collab.state`,`mailbox.agent_registered`,`mailbox.agents`,`mailbox.cleared`,`mailbox.compacted`,`mailbox.event`,`mailbox.messages`,`mailbox.sent`,`mailbox.purged`,`mailbox.received`,`subagent.budget_extended`,`subagent.event`],je=`brain.answer,brain.config,brain.event,brain.status,chronicle.error,chronicle.facet_result,chronicle.facets_result,chronicle.graph_result,chronicle.metrics_result,chronicle.query_result,chronicle.status_result,config.doctor.result,design.list,design.materialize,design.set,design.state,design.swap,design.tune,design.use,design.verify,memory.event,memory.list,memory.sage.backfillRecoverable,memory.sage.candidateResolve,memory.sage.delete,memory.sage.forFile,memory.sage.get,memory.sage.graph,memory.sage.list,memory.sage.listPage,memory.sage.recover,memory.sage.remember,memory.sage.update`.split(`,`),Me=`mcp.content.error,mcp.content.selected,mcp.list,mcp.operation_result,mcp.prompts,mcp.resources,mcp.server.added,mcp.server.connected,mcp.server.disconnected,mcp.server.discovered,mcp.server.error,mcp.server.reconnected,mcp.server.removed,mcp.server.sleeping,mcp.server.updated,mcp.server.waking,prompts.content,prompts.created,prompts.favorite,prompts.list,prompts.recent,prompts.search,prompts.used,skills.content,skills.created,skills.edited,skills.exported,skills.installed,skills.list,skills.uninstalled,skills.updated`.split(`,`),Ne=`budget.decision,budget.threshold_reached,coordinator.stats,coordinator.status,eternal.iteration,fleet.concurrency_update,goal-state.updated,goal.assess.result,goal.list,goal.paused,goal.resumed,goal.saved,goal.error,goal.stopped,goal.failed,goal.completed,goal.cleared,goal.reverted,goal.progress,goal.state,in_flight.ended,in_flight.started,plan.updated,task.completed,task.failed,task.pending,task.started,tasks.updated,todos.cleared,todos.updated`.split(`,`),Pe=[`kanban.task.activity`,`sdd.board.lifecycle_result`,`sdd.board.list`,`sdd.board.snapshot`,`sdd.run.started`,`sdd.spec.agent_text`,`sdd.spec.error`,`sdd.spec.snapshot`,`specs.detail`,`specs.list`],Fe=[`consensus.vote_cast`,`consensus.vote_initiated`,`consensus.vote_resolved`,`cron.job_fired`,`cron.snapshot`,`techstack.job.cancelled`,`techstack.job.failed`,`techstack.job.progress`,`techstack.job.started`,`techstack.report.delivered`,`techstack.report.ready`,`techstack.snapshot.updated`,`techstack.workspace.completed`],Ie=`checkpoint.written,codemap.file_event,codemap.index_updated,codemap.tool_executed,codemap.tool_started,file.saved,files.list,files.read,files.tree,files.written,git.changes,git.diff,git.info,process.list,projects.added,projects.list,projects.selected,terminal.exit,terminal.output,working_dir.changed,worktree.cleanup_result,worktree.diff_result,worktree.event,worktree.merge_result,worktree.orphans,worktree.state`.split(`,`),Le=[`auth.oauth.status`,`codebase.index.server.shutdown_result`,`connections.health_error`,`connections.health_result`,`connections.service_action_result`,`diag.get`,`key.operation_result`,`model.switch_result`,`prefs.updated`,`provider.catalog`,`provider.models`,`provider.models.search_result`,`provider.probe`,`provider.status.snapshot`,`providers.saved`],Re=[...xe,...Se,...De,...Oe,...Te,...Ee,...Ce,...we],ze=[...ke,...Ae,...Ie,...Le,...Ne,...Pe,...Fe,...je,...Me];new Set(Re),new Set(ze);function x(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function S(e,t=0){return typeof e==`number`&&Number.isFinite(e)?e:t}function C(e){return e===void 0||Array.isArray(e)}function Be(e){return S(e.activeProjects)===e.activeProjects&&S(e.activeClients)===e.activeClients&&S(e.activeSessions)===e.activeSessions&&S(e.activeSubagents)===e.activeSubagents&&S(e.unreadMailboxMessages)===e.unreadMailboxMessages&&S(e.incompleteMailboxMessages)===e.incompleteMailboxMessages&&S(e.totalCostUsd)===e.totalCostUsd}function Ve(e){if(e.type!==`hq.snapshot`)return null;let t=x(e.snapshot),n=t?x(t.totals):null;return!t||typeof t.generatedAt!=`string`||!Array.isArray(t.clients)||!Array.isArray(t.projects)||!Array.isArray(t.sessions)||!Array.isArray(t.fleets)||!Array.isArray(t.mailboxes)||!n||!Be(n)||!C(t.machines)||!C(t.liveSessions)||!C(t.mcpServers)?null:{kind:`hq-snapshot`,snapshot:t}}function He(e){if(e.type!==`hq.event`)return null;let t=x(e.event);return!t||typeof t.id!=`string`||typeof t.type!=`string`||typeof t.timestamp!=`string`||typeof t.clientId!=`string`||typeof t.projectId!=`string`||typeof t.seq!=`number`?null:{kind:`hq-event`,event:t}}function Ue(e){return e.type!==`hq.alert`||typeof e.severity!=`string`||![`info`,`warn`,`error`].includes(e.severity)||typeof e.message!=`string`||typeof e.timestamp!=`string`?null:{kind:`hq-alert`,alert:e}}function We(e){if(e.type!==`hq.command_status`)return null;let t=x(e.command);return!t||typeof t.commandId!=`string`||typeof t.type!=`string`||typeof t.clientId!=`string`||typeof t.enqueuedBy!=`string`||typeof t.enqueuedAt!=`string`||typeof t.status!=`string`||![`queued`,`delivered`,`acked`].includes(t.status)?null:{kind:`hq-command-status`,command:t}}var w=e(l(),1),Ge=fe(),T=e=>Symbol.iterator in e,E=e=>`entries`in e,D=(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},Ke=(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 qe(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:T(e)&&T(t)?E(e)&&E(t)?D(e,t):Ke(e,t):D({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function O(e){let t=w.useRef(void 0);return n=>{let r=e(n);return qe(t.current,r)?t.current:t.current=r}}var k=`wrongstack.hq.token.v1`;function A(){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 j(){if(typeof window>`u`)return null;try{return window.sessionStorage??null}catch{return null}}function Je(){try{let e=j()?.getItem(k)??null;return e!==null&&e.length>0?e:null}catch{return null}}function M(e){try{j()?.setItem(k,e)}catch{}}function N(){try{j()?.removeItem(k)}catch{}}function P(){let e=A();return e===null?Je():(M(e),e)}function Ye(){if(typeof window>`u`)return;let e=A();if(e!==null&&(M(e),Je()===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 Xe(){let e=P();return e===null?{}:{Authorization:`Bearer ${e}`}}function F(e,t){let n={...t?.headers??{},...Xe()};return fetch(e,{...t,headers:n})}function Ze(){if(typeof window>`u`)return null;try{let e=window.location.hash;if(!e.startsWith(`#bootstrap=`))return null;let t=e.slice(11);return t.length>0?t:null}catch{return null}}function Qe(){if(!(typeof window>`u`))try{let e=new URL(window.location.href);e.hash.startsWith(`#bootstrap=`)&&(e.hash=``,window.history.replaceState(null,``,`${e.pathname}${e.search}`))}catch{}}async function $e(){let e=Ze();if(e===null)return!1;try{return(await fetch(`/api/auth/bootstrap`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({code:e}),credentials:`same-origin`,signal:AbortSignal.timeout(1e4)})).ok?(Qe(),N(),!0):!1}catch{return!1}}var I=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},et=(e=>e?I(e):I),tt=e=>e;function nt(e,t=tt){let n=w.useSyncExternalStore(e.subscribe,w.useCallback(()=>t(e.getState()),[e,t]),w.useCallback(()=>t(e.getInitialState()),[e,t]));return w.useDebugValue(n),n}var rt=e=>{let t=et(e),n=e=>nt(t,e);return Object.assign(n,t),n},it=(e=>e?rt(e):rt),at=6e3,ot=0,L=it()(e=>({toasts:[],addToast:(t,n=`info`,r=at,i)=>{let a=`toast-${++ot}-${Date.now()}`,o={id:a,message:t,severity:n,createdAt:Date.now(),ttlMs:r,action:i};e(e=>({toasts:[...e.toasts.slice(-4),o]})),r>0&&setTimeout(()=>{e(e=>({toasts:e.toasts.filter(e=>e.id!==a)}))},r)},removeToast:t=>e(e=>({toasts:e.toasts.filter(e=>e.id!==t)})),clearToasts:()=>e({toasts:[]})})),R=pe(),st={error:(0,R.jsx)(de,{size:16,"aria-hidden":`true`}),warning:(0,R.jsx)(m,{size:16,"aria-hidden":`true`}),info:(0,R.jsx)(s,{size:16,"aria-hidden":`true`}),success:(0,R.jsx)(i,{size:16,"aria-hidden":`true`})};function ct(){let{toasts:e,removeToast:t}=L(O(e=>({toasts:e.toasts,removeToast:e.removeToast})));return e.length===0?null:(0,R.jsx)(`div`,{className:`hq-toast-container`,role:`status`,"aria-live":`polite`,"aria-label":`Notifications`,children:e.map(e=>(0,R.jsxs)(`div`,{className:`hq-toast hq-toast--${e.severity}`,"data-severity":e.severity,children:[(0,R.jsx)(`span`,{className:`hq-toast-icon`,children:st[e.severity]}),(0,R.jsx)(`span`,{className:`hq-toast-message`,children:e.message}),e.action?(0,R.jsx)(`span`,{className:`hq-toast-action`,children:e.action}):null,(0,R.jsx)(`button`,{type:`button`,className:`hq-toast-close`,"aria-label":`Dismiss notification`,onClick:()=>t(e.id),children:(0,R.jsx)(v,{size:12})})]},e.id))})}function lt(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 ut(e,t){return e.timestamp===t.timestamp&&e.severity===t.severity&&e.message===t.message}var z=it()(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?lt(e,t):{}),_onSnapshot:t=>e(e=>({...lt(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=>ut(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 B(e){let t;try{t=await F(e)}catch{throw Error(`Network error fetching ${e}`)}if(t.status===401)throw z.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 dt(e){let t;try{t=await F(`/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 z.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 ft(e,t,n){let r;try{r=await F(`/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 z.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 pt=`wrongstack.hq.local-prefs.v1`,V={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}},H=null,U=new Set;function W(){for(let e of U)e()}function G(e){return typeof structuredClone==`function`?structuredClone(e):JSON.parse(JSON.stringify(e))}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mt(){if(typeof window>`u`||window.localStorage===void 0)return G(V);try{let e=window.localStorage.getItem(pt);return e===null?G(V):ht(JSON.parse(e))}catch{return G(V)}}function ht(e){if(!K(e))return G(V);let t=K(e.appearance)?e.appearance:{},n=K(e.fleet)?e.fleet:{},r=K(e.console)?e.console:{},i=K(e.control)?e.control:{},a=K(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:V.control.cmdType,abortTarget:i.abortTarget===`fleet`?`fleet`:`leader`,spawnRole:typeof i.spawnRole==`string`&&i.spawnRole.length>0?i.spawnRole:V.control.spawnRole,spawnTask:typeof i.spawnTask==`string`?i.spawnTask:V.control.spawnTask,steerTo:typeof i.steerTo==`string`?i.steerTo:V.control.steerTo,steerSubject:typeof i.steerSubject==`string`?i.steerSubject:V.control.steerSubject,steerBody:typeof i.steerBody==`string`?i.steerBody:V.control.steerBody,broadcastSubject:typeof i.broadcastSubject==`string`?i.broadcastSubject:V.control.broadcastSubject,broadcastBody:typeof i.broadcastBody==`string`?i.broadcastBody:V.control.broadcastBody},mailbox:{query:typeof a.query==`string`?a.query:V.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 q(){return H===null&&(H=mt()),H}function J(e){if(!(typeof window>`u`||window.localStorage===void 0))try{window.localStorage.setItem(pt,JSON.stringify(e))}catch{}}function gt(e){return U.add(e),()=>U.delete(e)}function _t(){return q()}function vt(){return V}function yt(){return(0,w.useSyncExternalStore)(gt,_t,vt)}function bt(e){let t=q();H={...t,control:{...t.control,...e}},J(H),W()}function xt(e){let t=q();H={...t,appearance:{...t.appearance,...e}},J(H),W()}function St(e){let t=q();H={...t,fleet:{...t.fleet,...e}},J(H),W()}function Ct(e){let t=q();H={...t,console:{...t.console,...e}},J(H),W()}function wt(e){let t=q();H={...t,mailbox:{...t.mailbox,...e}},J(H),W()}function Tt({hadToken:e}){let[t,n]=(0,w.useState)(null),[r,i]=(0,w.useState)(null);(0,w.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,w.useState)(`token`);return(0,w.useEffect)(()=>{t&&c(t.passwordMode?`password`:`token`)},[t]),r?(0,R.jsx)(`div`,{className:`hq-token-gate`,children:(0,R.jsxs)(`div`,{className:`hq-token-card`,children:[(0,R.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),(0,R.jsx)(`div`,{className:`hq-token-title`,children:`Auth status unavailable`}),(0,R.jsx)(`p`,{className:`hq-token-text`,children:r})]})}):t?(0,R.jsx)(`div`,{className:`hq-token-gate`,children:(0,R.jsxs)(`div`,{className:`hq-token-card`,children:[(0,R.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),a&&o?(0,R.jsxs)(`div`,{className:`hq-token-tabs`,children:[(0,R.jsx)(`button`,{type:`button`,className:`hq-token-tab`+(s===`token`?` active`:``),onClick:()=>c(`token`),children:`Browser token`}),(0,R.jsx)(`button`,{type:`button`,className:`hq-token-tab`+(s===`password`?` active`:``),onClick:()=>c(`password`),children:`Password`})]}):null,s===`token`||!o?(0,R.jsx)(Et,{hadToken:e}):(0,R.jsx)(Dt,{})]})}):(0,R.jsx)(`div`,{className:`hq-token-gate`,children:(0,R.jsxs)(`div`,{className:`hq-token-card`,children:[(0,R.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),(0,R.jsx)(`div`,{className:`hq-token-title`,children:`Checking auth mode…`})]})})}function Et({hadToken:e}){let[t,n]=(0,w.useState)(``),r=()=>{let e=t.trim();e.length!==0&&(M(e),window.location.reload())};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`hq-token-title`,children:`Browser token required`}),(0,R.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,R.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,R.jsx)(`button`,{type:`button`,className:`hq-token-submit`,onClick:r,disabled:t.trim().length===0,children:`Connect`}),(0,R.jsxs)(`p`,{className:`hq-token-hint`,children:[`Manage tokens with `,(0,R.jsx)(`code`,{children:`wstack hq token list`}),` / `,(0,R.jsx)(`code`,{children:`wstack hq token create`}),` — they live in `,(0,R.jsx)(`code`,{children:`~/.wrongstack/hq/auth.json`}),`.`]})]})}function Dt(){let[e,t]=(0,w.useState)(``),[n,r]=(0,w.useState)(null),[i,a]=(0,w.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}N(),window.location.reload()}catch{r(`Network error. Is the HQ server running?`),a(!1)}}};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`hq-token-title`,children:`Password required`}),(0,R.jsx)(`p`,{className:`hq-token-text`,children:`This HQ server is protected by a password. Enter it to open the dashboard.`}),n?(0,R.jsx)(`p`,{className:`hq-token-error`,children:n}):null,(0,R.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,R.jsx)(`button`,{type:`button`,className:`hq-token-submit`,onClick:()=>void o(),disabled:e.length===0||i,children:i?`Logging in…`:`Log in`}),(0,R.jsxs)(`p`,{className:`hq-token-hint`,children:[`Set or change the password with `,(0,R.jsx)(`code`,{children:`wstack --hq --password <secret>`}),`.`]})]})}var Ot=`modulepreload`,kt=function(e){return`/`+e},At={},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=kt(t,n),t=s(t),t in At)return;At[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`:Ot,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)})},jt=360*60*1e3,X=[{id:`cockpit`,label:`Cockpit`,eyebrow:`Fleet overview`,description:`Health, active work, alerts, cost and command shortcuts.`,group:`Operations`,icon:c,shortcut:1},{id:`fleet`,label:`Fleet Map`,eyebrow:`Topology`,description:`Machines, projects, terminals and agents in one live graph.`,group:`Operations`,icon:t,shortcut:2},{id:`console`,label:`Live Console`,eyebrow:`Transcripts`,description:`Stream and inspect session or agent conversations.`,group:`Operations`,icon:d,shortcut:3},{id:`mailbox`,label:`Mailbox`,eyebrow:`Coordination`,description:`Cross-project messages, unread work and direct delivery.`,group:`Operations`,icon:ne,shortcut:4},{id:`kanban`,label:`Kanban`,eyebrow:`Project work`,description:`Read-only project boards synchronized across clones and machines.`,group:`Operations`,icon:g},{id:`alerts`,label:`Alerts`,eyebrow:`Attention`,description:`Active fleet warnings and alert transition history.`,group:`Intelligence`,icon:f,shortcut:5},{id:`cost`,label:`Cost`,eyebrow:`Economics`,description:`Project, provider and model spending distribution.`,group:`Intelligence`,icon:p,shortcut:6},{id:`trends`,label:`Trends`,eyebrow:`Telemetry`,description:`Cost, token and tool activity over time.`,group:`Intelligence`,icon:n,shortcut:7},{id:`brain`,label:`Brain`,eyebrow:`Decisions`,description:`Autonomous decisions, escalations and interventions.`,group:`Intelligence`,icon:u,shortcut:8},{id:`worktree`,label:`Worktrees`,eyebrow:`Workspace`,description:`Distributed branches, worktrees and ownership state.`,group:`System`,icon:le,shortcut:9},{id:`control`,label:`Control`,eyebrow:`Command plane`,description:`Steer, queue, broadcast and audit remote commands.`,group:`System`,icon:r,shortcut:0},{id:`settings`,label:`Security`,eyebrow:`Access control`,description:`Manage the HQ browser password, authentication and active credentials.`,group:`System`,icon:h}],Mt=[`Operations`,`Intelligence`,`System`],Nt={cockpit:(0,w.lazy)(()=>Y(()=>import(`./cockpit-DvD1_FDz.js`).then(e=>({default:e.CockpitView})),__vite__mapDeps([0,1,2,3]))),fleet:(0,w.lazy)(()=>Y(()=>import(`./fleet-map-CPD0vSE4.js`).then(e=>({default:e.FleetMapView})),__vite__mapDeps([4,1,2,5,3,6]))),console:(0,w.lazy)(()=>Y(()=>import(`./live-console-BqDIM7Cs.js`).then(e=>({default:e.LiveConsoleView})),__vite__mapDeps([7,1,2,3,6,5]))),mailbox:(0,w.lazy)(()=>Y(()=>import(`./mailbox-E7puE59T.js`).then(e=>({default:e.MailboxView})),__vite__mapDeps([8,1,2,3,9]))),kanban:(0,w.lazy)(()=>Y(()=>import(`./kanban-C9jQWM2T.js`).then(e=>({default:e.KanbanView})),__vite__mapDeps([10,1,2,3]))),cost:(0,w.lazy)(()=>Y(()=>import(`./cost-CE_P6ujW.js`).then(e=>({default:e.CostView})),__vite__mapDeps([11,1,2,3]))),brain:(0,w.lazy)(()=>Y(()=>import(`./brain-D5R8R8BY.js`).then(e=>({default:e.BrainView})),__vite__mapDeps([12,1,2,3,9]))),worktree:(0,w.lazy)(()=>Y(()=>import(`./worktree-D0pa1IH5.js`).then(e=>({default:e.WorktreeView})),__vite__mapDeps([13,1,2,3,9]))),trends:(0,w.lazy)(()=>Y(()=>import(`./trends-DqAtNjBm.js`).then(e=>({default:e.TrendsView})),__vite__mapDeps([14,1,2,3]))),alerts:(0,w.lazy)(()=>Y(()=>import(`./alerts-B_wJljmR.js`).then(e=>({default:e.AlertsView})),__vite__mapDeps([15,1,2,3]))),control:(0,w.lazy)(()=>Y(()=>import(`./control-DGfNRSfd.js`).then(e=>({default:e.ControlView})),__vite__mapDeps([16,1,2,3]))),settings:(0,w.lazy)(()=>Y(()=>import(`./settings-DMQf2eO5.js`).then(e=>({default:e.SettingsView})),__vite__mapDeps([17,1,2,3])))};function Pt(e){return X.find(t=>t.id===e)??X[0]}var Ft=class extends w.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,R.jsxs)(`div`,{className:`hq-view-error`,role:`alert`,children:[(0,R.jsx)(ce,{size:22}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:`This HQ surface stopped safely.`}),(0,R.jsx)(`p`,{children:this.state.error})]}),(0,R.jsxs)(`button`,{type:`button`,className:`hq-btn secondary`,onClick:()=>this.setState({error:null}),children:[(0,R.jsx)(y,{size:13}),`Retry view`]})]})}};function It(){let{snapshot:e,alerts:t,activeView:n,authRequired:r,connected:i}=z(O(e=>({snapshot:e.snapshot,alerts:e.alerts,activeView:e.activeView,authRequired:e.authRequired,connected:e.connected}))),[s,c]=(0,w.useState)(()=>typeof window>`u`||window.innerWidth>=1180),[l,u]=(0,w.useState)(null),[d,f]=(0,w.useState)(null),[ne,m]=(0,w.useState)(!1),{theme:h}=yt().appearance,g=(0,w.useRef)(!1),_=(0,w.useRef)(!1);if((0,w.useEffect)(()=>{_.current&&i===!1?L.getState().addToast(`Connection lost — reconnecting with backoff…`,`warning`,4e3):_.current&&g.current===!1&&i===!0&&L.getState().addToast(`Reconnected to HQ server`,`success`,3e3),i&&(_.current=!0),g.current=i},[i]),(0,w.useEffect)(()=>(document.documentElement.dataset.hqTheme=h,()=>{delete document.documentElement.dataset.hqTheme}),[h]),(0,w.useEffect)(()=>{let e=!1;return B(`/api/snapshot`).then(t=>{e||z.getState()._hydrateSnapshot(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,w.useEffect)(()=>{let e=!1;return B(`/api/auth/status`).then(t=>{e||f(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,w.useEffect)(()=>{let e=!1,t=()=>{B(`/api/system/update`).then(t=>{e||u(t)}).catch(()=>{})};t();let n=window.setInterval(t,jt);return()=>{e=!0,window.clearInterval(n)}},[]),(0,w.useEffect)(()=>{let e=e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),c(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(),z.getState().setActiveView(n.id));return}e.key===`Escape`&&s&&window.innerWidth<900&&c(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),r)return(0,R.jsx)(Tt,{hadToken:P()!==null});let v=e?.totals,ce=v?.unreadMailboxMessages??0,le=t.filter(e=>e.severity!==`info`).length,y=Pt(n),de=y.icon,fe=Nt[n],pe=e=>{z.getState().setActiveView(e),window.innerWidth<900&&c(!1)},b=async()=>{m(!0);try{await F(`/api/logout`,{method:`POST`})}finally{N(),window.location.reload()}};return(0,R.jsxs)(`div`,{className:`hq-app`,"data-theme":h,"data-testid":`hq-workbench`,children:[(0,R.jsx)(`button`,{type:`button`,className:`hq-sidebar-scrim`,"data-open":s,"aria-label":`Close HQ navigation`,onClick:()=>c(!1)}),(0,R.jsxs)(`aside`,{className:`hq-secondary-nav`,"data-open":s,"aria-label":`HQ navigation`,children:[(0,R.jsxs)(`div`,{className:`hq-secondary-header`,children:[(0,R.jsxs)(`div`,{className:`hq-secondary-brand`,children:[(0,R.jsx)(`img`,{src:`/wrongstack.svg`,alt:``,"aria-hidden":`true`,draggable:!1}),(0,R.jsxs)(`div`,{className:`hq-secondary-copy`,children:[(0,R.jsx)(`span`,{className:`hq-secondary-eyebrow`,children:`Command center`}),(0,R.jsx)(`strong`,{children:`WrongStack HQ`})]})]}),(0,R.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-secondary-close`,"aria-label":`Collapse HQ navigation`,title:`Collapse navigation (Ctrl+B)`,onClick:()=>c(!1),children:(0,R.jsx)(a,{size:16})})]}),(0,R.jsx)(`div`,{className:`hq-secondary-scroll`,children:Mt.map(e=>(0,R.jsxs)(`section`,{className:`hq-nav-group`,children:[(0,R.jsx)(`div`,{className:`hq-nav-group-label`,children:e}),X.filter(t=>t.group===e).map(e=>{let t=e.icon,r=e.id===`mailbox`?ce:e.id===`alerts`?le:0;return(0,R.jsxs)(`button`,{type:`button`,className:`hq-nav-item`,"data-active":n===e.id,"aria-current":n===e.id?`page`:void 0,onClick:()=>pe(e.id),children:[(0,R.jsx)(t,{size:15}),(0,R.jsx)(`span`,{children:e.label}),e.shortcut===void 0?null:(0,R.jsxs)(`kbd`,{children:[`Alt+`,e.shortcut]}),r>0?(0,R.jsx)(`span`,{className:`hq-nav-badge`,children:r}):null]},e.id)})]},e))}),(0,R.jsxs)(`div`,{className:`hq-secondary-footer`,children:[(0,R.jsxs)(`div`,{className:`hq-link-state`,"data-live":i,children:[(0,R.jsx)(`span`,{className:`hq-link-dot`}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:i?`Connected`:`Reconnecting`}),(0,R.jsxs)(`span`,{children:[v?.activeMachines??0,` machines · `,v?.activeClients??0,` clients`]})]})]}),(0,R.jsx)(`span`,{className:`hq-build-label`,children:`@wrongstack/webui-hq`})]})]}),(0,R.jsxs)(`section`,{className:`hq-workbench`,"data-update-available":l?.outdated===!0,children:[(0,R.jsxs)(`header`,{className:`hq-header`,children:[(0,R.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-sidebar-toggle`,"aria-label":s?`Collapse HQ navigation`:`Expand HQ navigation`,"aria-expanded":s,title:`Toggle navigation (Ctrl+B)`,onClick:()=>c(e=>!e),children:s?(0,R.jsx)(a,{size:17}):(0,R.jsx)(te,{size:17})}),(0,R.jsx)(`div`,{className:`hq-view-icon`,"aria-hidden":`true`,children:(0,R.jsx)(de,{size:18})}),(0,R.jsxs)(`div`,{className:`hq-view-identity`,children:[(0,R.jsx)(`span`,{children:y.eyebrow}),(0,R.jsx)(`h1`,{children:y.label}),(0,R.jsx)(`p`,{children:y.description})]}),(0,R.jsxs)(`div`,{className:`hq-top-metrics`,children:[(0,R.jsx)(Z,{icon:re,label:`Machines`,value:v?.activeMachines??0}),(0,R.jsx)(Z,{icon:se,label:`Agents`,value:v?.activeAgents??0}),(0,R.jsx)(Z,{icon:o,label:`Sessions`,value:v?.activeSessions??0}),(0,R.jsx)(Z,{icon:p,label:`Cost`,value:`$${(v?.totalCostUsd??0).toFixed(2)}`,accent:!0})]}),(0,R.jsxs)(`div`,{className:`hq-connection-pill`,"data-live":i,children:[i?(0,R.jsx)(ae,{size:13}):(0,R.jsx)(ie,{size:13}),i?`Live`:`Reconnecting`]}),(0,R.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-theme-toggle`,"aria-label":`Switch to ${h===`dark`?`light`:`dark`} mode`,title:`Switch to ${h===`dark`?`light`:`dark`} mode`,onClick:()=>xt({theme:h===`dark`?`light`:`dark`}),children:h===`dark`?(0,R.jsx)(ue,{size:16}):(0,R.jsx)(oe,{size:16})}),d?.tokenMode||d?.passwordMode?(0,R.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:ne,onClick:()=>void b(),children:(0,R.jsx)(ee,{size:16})}):null]}),l?.outdated?(0,R.jsx)(Lt,{status:l}):null,(0,R.jsx)(`main`,{className:`hq-main`,id:`hq-main`,tabIndex:-1,children:(0,R.jsx)(Ft,{view:n,children:(0,R.jsx)(w.Suspense,{fallback:(0,R.jsx)(Rt,{label:y.label}),children:(0,R.jsx)(fe,{})})})})]}),(0,R.jsx)(ct,{})]})}function Lt({status:e}){let[t,n]=(0,w.useState)(!1),r=async()=>{try{await navigator.clipboard.writeText(e.command),n(!0),window.setTimeout(()=>n(!1),1500)}catch{n(!1)}};return(0,R.jsxs)(`aside`,{className:`hq-update-notice`,role:`status`,"aria-live":`polite`,children:[(0,R.jsx)(m,{size:16,"aria-hidden":`true`}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:`WrongStack update available`}),(0,R.jsxs)(`span`,{children:[`v`,e.current,` → v`,e.latest,`. Run `,(0,R.jsx)(`code`,{children:e.command}),` in your terminal, then restart HQ.`]})]}),(0,R.jsxs)(`button`,{type:`button`,onClick:()=>void r(),title:`Copy update command`,children:[(0,R.jsx)(_,{size:13,"aria-hidden":`true`}),t?`Copied`:`Copy command`]})]})}function Z({icon:e,label:t,value:n,accent:r=!1}){return(0,R.jsxs)(`div`,{className:`hq-top-metric`,"data-accent":r,children:[(0,R.jsx)(e,{size:12}),(0,R.jsx)(`span`,{children:t}),(0,R.jsx)(`strong`,{children:n})]})}function Rt({label:e}){return(0,R.jsxs)(`div`,{className:`hq-view-loading`,role:`status`,children:[(0,R.jsx)(r,{size:18}),(0,R.jsxs)(`span`,{children:[`Loading `,e,`…`]})]})}var zt=25e3,Bt=1e4,Vt=3e4,Ht=class{ws=null;handlers=new Set;stateHandlers=new Set;reconnectAttempt=0;connectionState=me();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??zt,this.heartbeatTimeoutMs=e?.heartbeatTimeoutMs??Bt,this.maxBackoffMs=e?.maxBackoffMs??Vt,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=P(),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.connectionState=he(this.connectionState),this.emitState(`connecting`);let e;try{e=new WebSocket(this.url)}catch{this.scheduleReconnect();return}this.ws=e,e.onopen=()=>{this.reconnectAttempt=0,this.connectionState=ge(this.connectionState),this.lastMessageAt=Date.now(),this.connectionState=_e(this.connectionState,this.lastMessageAt),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.connectionState=ve(this.connectionState),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;let e=ye(this.connectionState,{...b,maxReconnectAttempts:this.maxRetries,maxBackoffMs:this.maxBackoffMs,heartbeatIntervalMs:this.heartbeatIntervalMs,heartbeatTimeoutMs:this.heartbeatTimeoutMs,jitterRatio:.5});if(this.connectionState=e.state,this.reconnectAttempt=e.state.reconnectAttempt,!e.plan){this.emitState(`disconnected`);return}this.emitState(`reconnecting`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e.plan.delayMs)}get isHeartbeatTimedOut(){return this.ws===null||be(this.connectionState,{...b,heartbeatIntervalMs:this.heartbeatIntervalMs,heartbeatTimeoutMs: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 Ut(){return Q===null&&(Q=new Ht,Q.connect()),Q}var $=document.getElementById(`root`);$!==null&&$e().finally(()=>{Ye();let e=Ut();e.onStateChange(e=>{z.getState()._setConnected(e===`connected`)}),e.on(e=>{if(e.type===`hq.snapshot`){let t=Ve(e);t&&z.getState()._onSnapshot(t.snapshot)}else if(e.type===`hq.event`){let t=He(e);t&&z.getState()._onEvent(t.event)}else if(e.type===`hq.alert`){let t=Ue(e);t&&z.getState()._onAlert(t.alert)}else if(e.type===`hq.command_status`){let t=We(e);t&&z.getState()._onCommandStatus(t.command)}}),(0,Ge.createRoot)($).render((0,R.jsx)(w.StrictMode,{children:(0,R.jsx)(It,{})}))});export{yt as a,dt as c,N as d,O as f,wt as i,z as l,bt as n,B as o,St as r,ft as s,Ct as t,F as u};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Ct as t,Lt as n,S as r,_t as i,c as a,rt as o,s}from"./icons-BV2PcvP1.js";import{i as c}from"./markdown-HUVrfVaI.js";import{l,o as u}from"./index-JtwIxe7S.js";var d=e(n(),1),f=new Set([`low`,`medium`,`high`,`critical`]),p=new Set([`pending`,`ready`,`in_progress`,`review`,`completed`,`blocked`,`failed`,`archived`]);function m(e){return`/api/projects/${encodeURIComponent(e)}/kanban`}function h(e){return e.boards.map(e=>g(e)).filter(e=>e!==null).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}function g(e){let t=e.board;if(t.id!==e.boardId)return null;let n=y(t.columns).map(_).filter(e=>e!==null),r=y(t.tasks).map(v).filter(e=>e!==null),i=new Set(n.map(e=>e.id)),a=new Set(r.map(e=>e.columnId).filter(e=>!i.has(e)));for(let e of a)n.push({id:e,title:e.length>0?e:`Unmapped`,order:2**53-1});let o=n.sort((e,t)=>e.order-t.order||e.title.localeCompare(t.title)).map(e=>({...e,tasks:r.filter(t=>t.columnId===e.id).sort((e,t)=>e.order-t.order||e.title.localeCompare(t.title))}));return{id:e.boardId,title:S(t.title)??e.boardId,description:S(t.description),tags:x(t.tags),revision:e.revision,updatedAt:e.updatedAt,activePresence:y(t.presence).filter(e=>e.active===!0).length,taskCount:r.length,completedTaskCount:r.filter(e=>e.status===`completed`).length,activeTaskCount:r.filter(e=>e.status===`in_progress`||e.status===`review`).length,blockedTaskCount:r.filter(e=>e.status===`blocked`||e.status===`failed`).length,columns:o}}function _(e){let t=S(e.id),n=S(e.title);return!t||!n?null:{id:t,title:n,color:S(e.color),order:C(e.order)??0,wipLimit:C(e.wipLimit)}}function v(e){let t=S(e.id),n=S(e.title),r=S(e.columnId);if(!t||!n||r===void 0)return null;let i=b(e.assignment);return{id:t,title:n,description:S(e.description),columnId:r,order:C(e.order)??0,priority:w(e.priority,f)??`medium`,status:w(e.status,p)??`pending`,assignee:S(e.assignee)??S(e.assignedAgent)??S(i?.name)??S(i?.agentId),assignmentStatus:S(i?.status),labels:x(e.labels),dependsOn:x(e.dependsOn),dueDate:S(e.dueDate)}}function y(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e)):[]}function b(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function x(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function S(e){return typeof e==`string`?e:void 0}function C(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function w(e,t){return typeof e==`string`&&t.has(e)?e:void 0}var T=c(),E=1e4,D=[];function O(){let e=l(e=>e.snapshot?.projects??D),t=l(e=>{for(let t=e.events.length-1;t>=0;t--){let n=e.events[t];if(n?.type===`kanban.snapshot`)return n.id}return null}),[n,i]=(0,d.useState)(``),[o,s]=(0,d.useState)(``),[c,f]=(0,d.useState)(null),[p,g]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1),[y,b]=(0,d.useState)(null),x=(0,d.useRef)(0),S=(0,d.useRef)(t);(0,d.useEffect)(()=>{if(e.length===0){i(``),f(null);return}e.some(e=>e.projectId===n)||i(e[0].projectId)},[n,e]);let C=(0,d.useCallback)(async(e=!1)=>{if(!n)return;let t=++x.current;e?g(!0):v(!0);try{let e=await u(m(n));if(t!==x.current)return;f(e),b(null)}catch(e){if(t!==x.current)return;b(e instanceof Error?e.message:String(e))}finally{t===x.current&&(g(!1),v(!1))}},[n]);(0,d.useEffect)(()=>{x.current++,f(null),s(``),b(null)},[n]),(0,d.useEffect)(()=>{if(!n)return;C(!0);let e=window.setInterval(()=>void C(!1),E);return()=>{x.current++,window.clearInterval(e)}},[C,n]),(0,d.useEffect)(()=>{t===null||t===S.current||(S.current=t,n&&C(!1))},[t,C,n]);let w=(0,d.useMemo)(()=>c?h(c):[],[c]);(0,d.useEffect)(()=>{w.length===0?s(``):w.some(e=>e.id===o)||s(w[0].id)},[o,w]);let O=w.find(e=>e.id===o)??null,j=e.find(e=>e.projectId===n)??null;return e.length===0?(0,T.jsx)(`div`,{className:`hq-empty`,children:`No HQ projects are available. Connect a WrongStack client to publish its project identity and Kanban snapshot.`}):(0,T.jsxs)(`div`,{className:`hq-kanban-view`,children:[(0,T.jsx)(k,{projects:e,projectId:n,onProjectChange:e=>i(e),boards:w,boardId:o,onBoardChange:s,generatedAt:c?.generatedAt,refreshing:_,onRefresh:()=>void C(!1)}),y?(0,T.jsxs)(`div`,{className:`hq-kanban-error`,role:`alert`,children:[(0,T.jsx)(a,{size:15}),(0,T.jsx)(`span`,{children:y}),(0,T.jsx)(`button`,{type:`button`,onClick:()=>void C(!0),children:`Retry`})]}):null,p&&c===null?(0,T.jsxs)(`div`,{className:`hq-view-loading`,role:`status`,children:[(0,T.jsx)(r,{size:18}),(0,T.jsx)(`span`,{children:`Loading project boards…`})]}):O?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(A,{project:j,board:O,boardCount:w.length}),(0,T.jsx)(M,{board:O})]}):(0,T.jsxs)(`div`,{className:`hq-empty`,children:[`This project has not published a Kanban board yet. Create one with `,(0,T.jsx)(`code`,{children:`/kanban`}),` `,`from any connected clone.`]})]})}function k({projects:e,projectId:t,onProjectChange:n,boards:i,boardId:a,onBoardChange:o,generatedAt:s,refreshing:c,onRefresh:l}){return(0,T.jsxs)(`div`,{className:`hq-kanban-toolbar`,children:[(0,T.jsxs)(`label`,{children:[(0,T.jsx)(`span`,{children:`Project`}),(0,T.jsx)(`select`,{className:`hq-select`,"aria-label":`Kanban project`,value:t,onChange:e=>n(e.target.value),children:e.map(e=>(0,T.jsx)(`option`,{value:e.projectId,children:e.projectName},e.projectId))})]}),(0,T.jsxs)(`label`,{children:[(0,T.jsx)(`span`,{children:`Board`}),(0,T.jsxs)(`select`,{className:`hq-select`,"aria-label":`Kanban board`,value:a,disabled:i.length===0,onChange:e=>o(e.target.value),children:[i.length===0?(0,T.jsx)(`option`,{value:``,children:`No boards`}):null,i.map(e=>(0,T.jsx)(`option`,{value:e.id,children:e.title},e.id))]})]}),(0,T.jsxs)(`div`,{className:`hq-kanban-sync`,children:[(0,T.jsx)(`span`,{children:s?`Synced ${F(s)}`:`Waiting for snapshot`}),(0,T.jsxs)(`button`,{type:`button`,onClick:l,disabled:c,"aria-label":`Refresh Kanban`,children:[(0,T.jsx)(r,{size:14,className:c?`is-spinning`:void 0}),`Refresh`]})]})]})}function A({project:e,board:t,boardCount:n}){return(0,T.jsxs)(`section`,{className:`hq-kanban-summary`,children:[(0,T.jsxs)(`div`,{className:`hq-kanban-heading`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsxs)(`span`,{children:[e?.projectName??`Project`,` · Kanban`]}),(0,T.jsx)(`h2`,{children:t.title}),t.description?(0,T.jsx)(`p`,{children:t.description}):null]}),(0,T.jsxs)(`div`,{className:`hq-kanban-board-meta`,children:[(0,T.jsxs)(`span`,{className:`hq-mono`,children:[`rev `,t.revision]}),(0,T.jsx)(`span`,{children:F(t.updatedAt)}),t.activePresence>0?(0,T.jsxs)(`span`,{className:`hq-pill active`,children:[t.activePresence,` active`]}):null]})]}),t.tags.length>0?(0,T.jsx)(`div`,{className:`hq-kanban-tags`,children:t.tags.map(e=>(0,T.jsx)(`span`,{className:`hq-pill info`,children:e},e))}):null,(0,T.jsxs)(`div`,{className:`hq-kanban-stats`,children:[(0,T.jsx)(j,{label:`Boards`,value:n}),(0,T.jsx)(j,{label:`Tasks`,value:t.taskCount}),(0,T.jsx)(j,{label:`Active`,value:t.activeTaskCount,tone:`active`}),(0,T.jsx)(j,{label:`Blocked`,value:t.blockedTaskCount,tone:`blocked`}),(0,T.jsx)(j,{label:`Done`,value:t.completedTaskCount,tone:`done`})]})]})}function j({label:e,value:t,tone:n}){return(0,T.jsxs)(`div`,{className:`hq-kanban-stat`,"data-tone":n,children:[(0,T.jsx)(`strong`,{children:t}),(0,T.jsx)(`span`,{children:e})]})}function M({board:e}){return e.columns.length===0?(0,T.jsx)(`div`,{className:`hq-empty`,children:`This board does not have any columns yet.`}):(0,T.jsx)(`section`,{className:`hq-kanban-board`,"aria-label":`${e.title} Kanban board`,style:{"--hq-kanban-columns":Math.max(1,e.columns.length)},children:e.columns.map(e=>(0,T.jsxs)(`div`,{className:`hq-kanban-column`,"data-over-limit":e.wipLimit!==void 0&&e.tasks.filter(e=>e.status!==`completed`).length>e.wipLimit,children:[(0,T.jsxs)(`header`,{style:e.color?{borderTopColor:e.color}:void 0,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`strong`,{children:e.title}),e.wipLimit===void 0?null:(0,T.jsxs)(`span`,{children:[`WIP `,e.tasks.length,`/`,e.wipLimit]})]}),(0,T.jsx)(`span`,{className:`hq-kanban-column-count`,children:e.tasks.length})]}),(0,T.jsx)(`div`,{className:`hq-kanban-column-body`,children:e.tasks.length===0?(0,T.jsx)(`div`,{className:`hq-kanban-column-empty`,children:`No cards`}):e.tasks.map(e=>(0,T.jsx)(N,{task:e},e.id))})]},e.id))})}function N({task:e}){return(0,T.jsxs)(`article`,{className:`hq-kanban-task`,"data-priority":e.priority,children:[(0,T.jsxs)(`div`,{className:`hq-kanban-task-topline`,children:[(0,T.jsx)(`span`,{className:`hq-pill ${e.status}`,children:e.status.replaceAll(`_`,` `)}),(0,T.jsx)(`span`,{className:`hq-kanban-priority ${e.priority}`,children:e.priority})]}),(0,T.jsx)(`h3`,{children:e.title}),e.description?(0,T.jsx)(`p`,{children:e.description}):null,e.labels.length>0?(0,T.jsx)(`div`,{className:`hq-kanban-task-labels`,children:e.labels.slice(0,4).map(e=>(0,T.jsx)(`span`,{children:e},e))}):null,(0,T.jsxs)(`footer`,{children:[e.assignee?(0,T.jsxs)(`span`,{title:e.assignmentStatus??`assigned`,children:[(0,T.jsx)(s,{size:12}),e.assignee]}):null,e.dependsOn.length>0?(0,T.jsxs)(`span`,{title:`${e.dependsOn.length} dependencies`,children:[(0,T.jsx)(o,{size:12}),e.dependsOn.length]}):null,e.dueDate?(0,T.jsxs)(`span`,{title:`Due ${new Date(e.dueDate).toLocaleString()}`,children:[(0,T.jsx)(i,{size:12}),P(e.dueDate)]}):null,e.status===`completed`?(0,T.jsx)(t,{size:13,className:`is-done`}):null]})]})}function P(e){let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`}):e}function F(e){let t=Date.parse(e);if(!Number.isFinite(t))return e;let n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<10)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}export{O as KanbanView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Ct as t,Lt as n,S as r,_t as i,c as a,rt as o,s}from"./icons-BV2PcvP1.js";import{i as c}from"./markdown-HUVrfVaI.js";import{l,o as u}from"./index-04jymFDH.js";var d=e(n(),1),f=new Set([`low`,`medium`,`high`,`critical`]),p=new Set([`pending`,`ready`,`in_progress`,`review`,`completed`,`blocked`,`failed`,`archived`]);function m(e){return`/api/projects/${encodeURIComponent(e)}/kanban`}function h(e){return e.boards.map(e=>g(e)).filter(e=>e!==null).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}function g(e){let t=e.board;if(t.id!==e.boardId)return null;let n=y(t.columns).map(_).filter(e=>e!==null),r=y(t.tasks).map(v).filter(e=>e!==null),i=new Set(n.map(e=>e.id)),a=new Set(r.map(e=>e.columnId).filter(e=>!i.has(e)));for(let e of a)n.push({id:e,title:e.length>0?e:`Unmapped`,order:2**53-1});let o=n.sort((e,t)=>e.order-t.order||e.title.localeCompare(t.title)).map(e=>({...e,tasks:r.filter(t=>t.columnId===e.id).sort((e,t)=>e.order-t.order||e.title.localeCompare(t.title))}));return{id:e.boardId,title:S(t.title)??e.boardId,description:S(t.description),tags:x(t.tags),revision:e.revision,updatedAt:e.updatedAt,activePresence:y(t.presence).filter(e=>e.active===!0).length,taskCount:r.length,completedTaskCount:r.filter(e=>e.status===`completed`).length,activeTaskCount:r.filter(e=>e.status===`in_progress`||e.status===`review`).length,blockedTaskCount:r.filter(e=>e.status===`blocked`||e.status===`failed`).length,columns:o}}function _(e){let t=S(e.id),n=S(e.title);return!t||!n?null:{id:t,title:n,color:S(e.color),order:C(e.order)??0,wipLimit:C(e.wipLimit)}}function v(e){let t=S(e.id),n=S(e.title),r=S(e.columnId);if(!t||!n||r===void 0)return null;let i=b(e.assignment);return{id:t,title:n,description:S(e.description),columnId:r,order:C(e.order)??0,priority:w(e.priority,f)??`medium`,status:w(e.status,p)??`pending`,assignee:S(e.assignee)??S(e.assignedAgent)??S(i?.name)??S(i?.agentId),assignmentStatus:S(i?.status),labels:x(e.labels),dependsOn:x(e.dependsOn),dueDate:S(e.dueDate)}}function y(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&!Array.isArray(e)):[]}function b(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function x(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function S(e){return typeof e==`string`?e:void 0}function C(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function w(e,t){return typeof e==`string`&&t.has(e)?e:void 0}var T=c(),E=1e4,D=[];function O(){let e=l(e=>e.snapshot?.projects??D),t=l(e=>{for(let t=e.events.length-1;t>=0;t--){let n=e.events[t];if(n?.type===`kanban.snapshot`)return n.id}return null}),[n,i]=(0,d.useState)(``),[o,s]=(0,d.useState)(``),[c,f]=(0,d.useState)(null),[p,g]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1),[y,b]=(0,d.useState)(null),x=(0,d.useRef)(0),S=(0,d.useRef)(t);(0,d.useEffect)(()=>{if(e.length===0){i(``),f(null);return}e.some(e=>e.projectId===n)||i(e[0].projectId)},[n,e]);let C=(0,d.useCallback)(async(e=!1)=>{if(!n)return;let t=++x.current;e?g(!0):v(!0);try{let e=await u(m(n));if(t!==x.current)return;f(e),b(null)}catch(e){if(t!==x.current)return;b(e instanceof Error?e.message:String(e))}finally{t===x.current&&(g(!1),v(!1))}},[n]);(0,d.useEffect)(()=>{x.current++,f(null),s(``),b(null)},[n]),(0,d.useEffect)(()=>{if(!n)return;C(!0);let e=window.setInterval(()=>void C(!1),E);return()=>{x.current++,window.clearInterval(e)}},[C,n]),(0,d.useEffect)(()=>{t===null||t===S.current||(S.current=t,n&&C(!1))},[t,C,n]);let w=(0,d.useMemo)(()=>c?h(c):[],[c]);(0,d.useEffect)(()=>{w.length===0?s(``):w.some(e=>e.id===o)||s(w[0].id)},[o,w]);let O=w.find(e=>e.id===o)??null,j=e.find(e=>e.projectId===n)??null;return e.length===0?(0,T.jsx)(`div`,{className:`hq-empty`,children:`No HQ projects are available. Connect a WrongStack client to publish its project identity and Kanban snapshot.`}):(0,T.jsxs)(`div`,{className:`hq-kanban-view`,children:[(0,T.jsx)(k,{projects:e,projectId:n,onProjectChange:e=>i(e),boards:w,boardId:o,onBoardChange:s,generatedAt:c?.generatedAt,refreshing:_,onRefresh:()=>void C(!1)}),y?(0,T.jsxs)(`div`,{className:`hq-kanban-error`,role:`alert`,children:[(0,T.jsx)(a,{size:15}),(0,T.jsx)(`span`,{children:y}),(0,T.jsx)(`button`,{type:`button`,onClick:()=>void C(!0),children:`Retry`})]}):null,p&&c===null?(0,T.jsxs)(`div`,{className:`hq-view-loading`,role:`status`,children:[(0,T.jsx)(r,{size:18}),(0,T.jsx)(`span`,{children:`Loading project boards…`})]}):O?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(A,{project:j,board:O,boardCount:w.length}),(0,T.jsx)(M,{board:O})]}):(0,T.jsxs)(`div`,{className:`hq-empty`,children:[`This project has not published a Kanban board yet. Create one with `,(0,T.jsx)(`code`,{children:`/kanban`}),` `,`from any connected clone.`]})]})}function k({projects:e,projectId:t,onProjectChange:n,boards:i,boardId:a,onBoardChange:o,generatedAt:s,refreshing:c,onRefresh:l}){return(0,T.jsxs)(`div`,{className:`hq-kanban-toolbar`,children:[(0,T.jsxs)(`label`,{children:[(0,T.jsx)(`span`,{children:`Project`}),(0,T.jsx)(`select`,{className:`hq-select`,"aria-label":`Kanban project`,value:t,onChange:e=>n(e.target.value),children:e.map(e=>(0,T.jsx)(`option`,{value:e.projectId,children:e.projectName},e.projectId))})]}),(0,T.jsxs)(`label`,{children:[(0,T.jsx)(`span`,{children:`Board`}),(0,T.jsxs)(`select`,{className:`hq-select`,"aria-label":`Kanban board`,value:a,disabled:i.length===0,onChange:e=>o(e.target.value),children:[i.length===0?(0,T.jsx)(`option`,{value:``,children:`No boards`}):null,i.map(e=>(0,T.jsx)(`option`,{value:e.id,children:e.title},e.id))]})]}),(0,T.jsxs)(`div`,{className:`hq-kanban-sync`,children:[(0,T.jsx)(`span`,{children:s?`Synced ${F(s)}`:`Waiting for snapshot`}),(0,T.jsxs)(`button`,{type:`button`,onClick:l,disabled:c,"aria-label":`Refresh Kanban`,children:[(0,T.jsx)(r,{size:14,className:c?`is-spinning`:void 0}),`Refresh`]})]})]})}function A({project:e,board:t,boardCount:n}){return(0,T.jsxs)(`section`,{className:`hq-kanban-summary`,children:[(0,T.jsxs)(`div`,{className:`hq-kanban-heading`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsxs)(`span`,{children:[e?.projectName??`Project`,` · Kanban`]}),(0,T.jsx)(`h2`,{children:t.title}),t.description?(0,T.jsx)(`p`,{children:t.description}):null]}),(0,T.jsxs)(`div`,{className:`hq-kanban-board-meta`,children:[(0,T.jsxs)(`span`,{className:`hq-mono`,children:[`rev `,t.revision]}),(0,T.jsx)(`span`,{children:F(t.updatedAt)}),t.activePresence>0?(0,T.jsxs)(`span`,{className:`hq-pill active`,children:[t.activePresence,` active`]}):null]})]}),t.tags.length>0?(0,T.jsx)(`div`,{className:`hq-kanban-tags`,children:t.tags.map(e=>(0,T.jsx)(`span`,{className:`hq-pill info`,children:e},e))}):null,(0,T.jsxs)(`div`,{className:`hq-kanban-stats`,children:[(0,T.jsx)(j,{label:`Boards`,value:n}),(0,T.jsx)(j,{label:`Tasks`,value:t.taskCount}),(0,T.jsx)(j,{label:`Active`,value:t.activeTaskCount,tone:`active`}),(0,T.jsx)(j,{label:`Blocked`,value:t.blockedTaskCount,tone:`blocked`}),(0,T.jsx)(j,{label:`Done`,value:t.completedTaskCount,tone:`done`})]})]})}function j({label:e,value:t,tone:n}){return(0,T.jsxs)(`div`,{className:`hq-kanban-stat`,"data-tone":n,children:[(0,T.jsx)(`strong`,{children:t}),(0,T.jsx)(`span`,{children:e})]})}function M({board:e}){return e.columns.length===0?(0,T.jsx)(`div`,{className:`hq-empty`,children:`This board does not have any columns yet.`}):(0,T.jsx)(`section`,{className:`hq-kanban-board`,"aria-label":`${e.title} Kanban board`,style:{"--hq-kanban-columns":Math.max(1,e.columns.length)},children:e.columns.map(e=>(0,T.jsxs)(`div`,{className:`hq-kanban-column`,"data-over-limit":e.wipLimit!==void 0&&e.tasks.filter(e=>e.status!==`completed`).length>e.wipLimit,children:[(0,T.jsxs)(`header`,{style:e.color?{borderTopColor:e.color}:void 0,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`strong`,{children:e.title}),e.wipLimit===void 0?null:(0,T.jsxs)(`span`,{children:[`WIP `,e.tasks.length,`/`,e.wipLimit]})]}),(0,T.jsx)(`span`,{className:`hq-kanban-column-count`,children:e.tasks.length})]}),(0,T.jsx)(`div`,{className:`hq-kanban-column-body`,children:e.tasks.length===0?(0,T.jsx)(`div`,{className:`hq-kanban-column-empty`,children:`No cards`}):e.tasks.map(e=>(0,T.jsx)(N,{task:e},e.id))})]},e.id))})}function N({task:e}){return(0,T.jsxs)(`article`,{className:`hq-kanban-task`,"data-priority":e.priority,children:[(0,T.jsxs)(`div`,{className:`hq-kanban-task-topline`,children:[(0,T.jsx)(`span`,{className:`hq-pill ${e.status}`,children:e.status.replaceAll(`_`,` `)}),(0,T.jsx)(`span`,{className:`hq-kanban-priority ${e.priority}`,children:e.priority})]}),(0,T.jsx)(`h3`,{children:e.title}),e.description?(0,T.jsx)(`p`,{children:e.description}):null,e.labels.length>0?(0,T.jsx)(`div`,{className:`hq-kanban-task-labels`,children:e.labels.slice(0,4).map(e=>(0,T.jsx)(`span`,{children:e},e))}):null,(0,T.jsxs)(`footer`,{children:[e.assignee?(0,T.jsxs)(`span`,{title:e.assignmentStatus??`assigned`,children:[(0,T.jsx)(s,{size:12}),e.assignee]}):null,e.dependsOn.length>0?(0,T.jsxs)(`span`,{title:`${e.dependsOn.length} dependencies`,children:[(0,T.jsx)(o,{size:12}),e.dependsOn.length]}):null,e.dueDate?(0,T.jsxs)(`span`,{title:`Due ${new Date(e.dueDate).toLocaleString()}`,children:[(0,T.jsx)(i,{size:12}),P(e.dueDate)]}):null,e.status===`completed`?(0,T.jsx)(t,{size:13,className:`is-done`}):null]})]})}function P(e){let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`}):e}function F(e){let t=Date.parse(e);if(!Number.isFinite(t))return e;let n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<10)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}export{O as KanbanView};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{C as t,Dt as n,Ft as r,Lt as i,M as a,N as o,Nt as s,O as c,X as l,d as u,st as d,v as f}from"./icons-BV2PcvP1.js";import{i as p}from"./markdown-HUVrfVaI.js";import{a as m,f as h,l as g,s as _,t as v}from"./index-JtwIxe7S.js";import{c as y,l as b,s as ee,t as x,u as S}from"./fleet-topology-D59v7Ec7.js";var C=e(i(),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 O({snapshot:e,selectedSessionId:t,selectedAgentId:r}){let i=(0,C.useMemo)(()=>E(e),[e]),[o,c]=(0,C.useState)(new Set),l=e=>c(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=!o.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:()=>l(e.id),"aria-expanded":i,children:[(0,T.jsx)(n,{size:12,className:`hq-nav-caret`+(i?` open`:``)}),(0,T.jsx)(a,{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=!o.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:()=>l(e.id),"aria-expanded":i,children:[(0,T.jsx)(n,{size:12,className:`hq-nav-caret`+(i?` open`:``)}),(0,T.jsx)(d,{size:13}),(0,T.jsx)(`span`,{className:`hq-nav-label`,title:e.label,children:e.label})]}),i&&e.clients.map(e=>{let i=!o.has(e.sessionId),a=t===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:()=>l(e.sessionId),"aria-label":i?`Collapse`:`Expand`,children:(0,T.jsx)(n,{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`+(a?` 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)(u,{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(n=>(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row agent`+(t===e.sessionId&&r===n.id?` selected`:``),onClick:()=>{g.getState().selectAgent(e.sessionId,n.id),e.clientId!==void 0&&g.getState().selectClient(e.clientId)},title:n.label,children:[(0,T.jsx)(`span`,{className:`hq-nav-dot `+D(n.status)}),(0,T.jsx)(s,{size:12}),(0,T.jsx)(`span`,{className:`hq-nav-label`,children:n.label})]},n.id))]},e.sessionId)})]},e.id)})]},e.id)})})}function k(e){return e===`completed`?`active`:e===`failed`||e===`rejected`?`error`:e===`delivered`||e===`accepted`?`info`:`warn`}function A({receipt:e,lifecycle:t}){let n=new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}),r=(0,T.jsx)(`span`,{className:`hq-pill ${k(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)(c,{size:12}),` `,e.preview,` `,r,(0,T.jsx)(`span`,{className:`hq-chat-clock`,children:n})]})}):(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,` `,r,(0,T.jsx)(`span`,{className:`hq-chat-clock`,children:n})]}),(0,T.jsx)(`div`,{className:`hq-chat-prose`,children:e.preview})]})})}function j(){let{selectedSessionId:e,selectedAgentId:n,snapshot:i,commandStatuses:a}=g(h(e=>({selectedSessionId:e.selectedSessionId,selectedAgentId:e.selectedAgentId,snapshot:e.snapshot,commandStatuses:e.commandStatuses}))),u=e,d=n,p=d!==null,x=m().console,[E,D]=(0,C.useState)(x.delivery),[k,j]=(0,C.useState)(x.subject),[M,N]=(0,C.useState)(x.body),[P,F]=(0,C.useState)(!1),[I,L]=(0,C.useState)(null),[te,R]=(0,C.useState)(!1),[z,B]=(0,C.useState)(!1),[V,H]=(0,C.useState)([]),U=b(u,d),{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(i,u,d),[d,u,i]),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),L(null),R(!1),B(!1),H([])},[Y?.client?.clientId,u,d]);let $=async()=>{if(Y?.client===null||Y?.client===void 0||!Y.controllable||M.trim().length===0)return;F(!0),L(null);let e=M.trim();try{let t=await _(Y.client.clientId,E,{to:Y.recipient,subject:k.trim()||`HQ ${E}`,body:e,priority:E===`steer`?`high`:`normal`});N(``),v({body:``}),H(n=>[...n,{commandId:t.commandId,type:E,target:Q,preview:e,createdAt:new Date().toISOString()}].slice(-8)),L({tone:`ok`,text:`${E} queued for ${Q} · ${t.commandId}`})}catch(e){L({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{F(!1)}},ne=async()=>{if(!(Y?.client===null||Y?.client===void 0)){F(!0),L(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))}L({tone:`ok`,text:Z&&z?`Leader interrupt queued; all subagents will be interrupted too.`:`${Q} interrupt queued.`}),R(!1)}catch(e){L({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{F(!1)}}};return(0,T.jsxs)(`div`,{className:`hq-console-shell`,children:[(0,T.jsx)(O,{snapshot:i??null,selectedSessionId:u,selectedAgentId:d}),(0,T.jsxs)(`div`,{className:`hq-console`,children:[(0,T.jsxs)(`div`,{className:`hq-chat-header`,children:[(0,T.jsx)(o,{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)(s,{size:12}),` `,X?.name??d]}),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)(l,{size:12}),` load all `,G.total]})]})]}),u===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??d??`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)(ee,{entry:e,running:U.isRunningAt(e,t)})},y(e,t))),q.map(e=>{let t=a.find(t=>t.commandId===e.commandId);return(0,T.jsx)(`div`,{className:`hq-chat-rowpad`,"aria-live":`polite`,children:(0,T.jsx)(A,{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)(r,{size:14})})]}):(0,T.jsxs)(`div`,{className:`hq-empty`,children:[`Error: `,U.error]}),u!==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)(t,{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:k,onChange:e=>{j(e.target.value),v({subject:e.target.value})}}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn danger hq-console-interrupt`,disabled:P||Y?.controllable!==!0,onClick:()=>{B(!1),R(!0)},children:[(0,T.jsx)(c,{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:M,onChange:e=>{N(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:P||M.trim().length===0||Y?.controllable!==!0,onClick:()=>void $(),children:[(0,T.jsx)(f,{size:13}),` `,P?`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`}),I!==null&&(0,T.jsx)(`span`,{className:`hq-console-status ${I.tone}`,children:I.text})]})]})]}),te&&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)(c,{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:P,onClick:()=>void ne(),children:[(0,T.jsx)(c,{size:13}),` Confirm interrupt`]})]})]})]})]})}export{j as LiveConsoleView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{C as t,Dt as n,Ft as r,Lt as i,M as a,N as o,Nt as s,O as c,X as l,d as u,st as d,v as f}from"./icons-BV2PcvP1.js";import{i as p}from"./markdown-HUVrfVaI.js";import{a as m,f as h,l as g,s as _,t as v}from"./index-04jymFDH.js";import{c as y,l as b,s as ee,t as x,u as S}from"./fleet-topology-BA3kpTuc.js";var C=e(i(),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 O({snapshot:e,selectedSessionId:t,selectedAgentId:r}){let i=(0,C.useMemo)(()=>E(e),[e]),[o,c]=(0,C.useState)(new Set),l=e=>c(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=!o.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:()=>l(e.id),"aria-expanded":i,children:[(0,T.jsx)(n,{size:12,className:`hq-nav-caret`+(i?` open`:``)}),(0,T.jsx)(a,{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=!o.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:()=>l(e.id),"aria-expanded":i,children:[(0,T.jsx)(n,{size:12,className:`hq-nav-caret`+(i?` open`:``)}),(0,T.jsx)(d,{size:13}),(0,T.jsx)(`span`,{className:`hq-nav-label`,title:e.label,children:e.label})]}),i&&e.clients.map(e=>{let i=!o.has(e.sessionId),a=t===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:()=>l(e.sessionId),"aria-label":i?`Collapse`:`Expand`,children:(0,T.jsx)(n,{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`+(a?` 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)(u,{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(n=>(0,T.jsxs)(`button`,{type:`button`,className:`hq-nav-row agent`+(t===e.sessionId&&r===n.id?` selected`:``),onClick:()=>{g.getState().selectAgent(e.sessionId,n.id),e.clientId!==void 0&&g.getState().selectClient(e.clientId)},title:n.label,children:[(0,T.jsx)(`span`,{className:`hq-nav-dot `+D(n.status)}),(0,T.jsx)(s,{size:12}),(0,T.jsx)(`span`,{className:`hq-nav-label`,children:n.label})]},n.id))]},e.sessionId)})]},e.id)})]},e.id)})})}function k(e){return e===`completed`?`active`:e===`failed`||e===`rejected`?`error`:e===`delivered`||e===`accepted`?`info`:`warn`}function A({receipt:e,lifecycle:t}){let n=new Date(e.createdAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}),r=(0,T.jsx)(`span`,{className:`hq-pill ${k(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)(c,{size:12}),` `,e.preview,` `,r,(0,T.jsx)(`span`,{className:`hq-chat-clock`,children:n})]})}):(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,` `,r,(0,T.jsx)(`span`,{className:`hq-chat-clock`,children:n})]}),(0,T.jsx)(`div`,{className:`hq-chat-prose`,children:e.preview})]})})}function j(){let{selectedSessionId:e,selectedAgentId:n,snapshot:i,commandStatuses:a}=g(h(e=>({selectedSessionId:e.selectedSessionId,selectedAgentId:e.selectedAgentId,snapshot:e.snapshot,commandStatuses:e.commandStatuses}))),u=e,d=n,p=d!==null,x=m().console,[E,D]=(0,C.useState)(x.delivery),[k,j]=(0,C.useState)(x.subject),[M,N]=(0,C.useState)(x.body),[P,F]=(0,C.useState)(!1),[I,L]=(0,C.useState)(null),[te,R]=(0,C.useState)(!1),[z,B]=(0,C.useState)(!1),[V,H]=(0,C.useState)([]),U=b(u,d),{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(i,u,d),[d,u,i]),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),L(null),R(!1),B(!1),H([])},[Y?.client?.clientId,u,d]);let $=async()=>{if(Y?.client===null||Y?.client===void 0||!Y.controllable||M.trim().length===0)return;F(!0),L(null);let e=M.trim();try{let t=await _(Y.client.clientId,E,{to:Y.recipient,subject:k.trim()||`HQ ${E}`,body:e,priority:E===`steer`?`high`:`normal`});N(``),v({body:``}),H(n=>[...n,{commandId:t.commandId,type:E,target:Q,preview:e,createdAt:new Date().toISOString()}].slice(-8)),L({tone:`ok`,text:`${E} queued for ${Q} · ${t.commandId}`})}catch(e){L({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{F(!1)}},ne=async()=>{if(!(Y?.client===null||Y?.client===void 0)){F(!0),L(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))}L({tone:`ok`,text:Z&&z?`Leader interrupt queued; all subagents will be interrupted too.`:`${Q} interrupt queued.`}),R(!1)}catch(e){L({tone:`error`,text:e instanceof Error?e.message:String(e)})}finally{F(!1)}}};return(0,T.jsxs)(`div`,{className:`hq-console-shell`,children:[(0,T.jsx)(O,{snapshot:i??null,selectedSessionId:u,selectedAgentId:d}),(0,T.jsxs)(`div`,{className:`hq-console`,children:[(0,T.jsxs)(`div`,{className:`hq-chat-header`,children:[(0,T.jsx)(o,{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)(s,{size:12}),` `,X?.name??d]}),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)(l,{size:12}),` load all `,G.total]})]})]}),u===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??d??`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)(ee,{entry:e,running:U.isRunningAt(e,t)})},y(e,t))),q.map(e=>{let t=a.find(t=>t.commandId===e.commandId);return(0,T.jsx)(`div`,{className:`hq-chat-rowpad`,"aria-live":`polite`,children:(0,T.jsx)(A,{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)(r,{size:14})})]}):(0,T.jsxs)(`div`,{className:`hq-empty`,children:[`Error: `,U.error]}),u!==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)(t,{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:k,onChange:e=>{j(e.target.value),v({subject:e.target.value})}}),(0,T.jsxs)(`button`,{type:`button`,className:`hq-btn danger hq-console-interrupt`,disabled:P||Y?.controllable!==!0,onClick:()=>{B(!1),R(!0)},children:[(0,T.jsx)(c,{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:M,onChange:e=>{N(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:P||M.trim().length===0||Y?.controllable!==!0,onClick:()=>void $(),children:[(0,T.jsx)(f,{size:13}),` `,P?`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`}),I!==null&&(0,T.jsx)(`span`,{className:`hq-console-status ${I.tone}`,children:I.text})]})]})]}),te&&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)(c,{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:P,onClick:()=>void ne(),children:[(0,T.jsx)(c,{size:13}),` Confirm interrupt`]})]})]})]})]})}export{j as LiveConsoleView};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{F as t,I as n,L as r,Lt as i,P as a,W as o,h as s,it as c,k as l,w as u,wt as d,y as f}from"./icons-BV2PcvP1.js";import{i as p}from"./markdown-HUVrfVaI.js";import{a as m,c as h,f as g,i as _,l as v,u as y}from"./index-JtwIxe7S.js";import{t as b}from"./use-backfilled-events-XgbaW3ZO.js";var x=e(i(),1),S=p(),C=[{value:`note`,label:`note — general information`},{value:`ask`,label:`ask — reply required`},{value:`assign`,label:`assign — work ownership`},{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`},{value:`status`,label:`status — meaningful checkpoint`},{value:`result`,label:`result — completed output/evidence`},{value:`review`,label:`review — passive inspection request`}];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)(!1),[_,v]=(0,x.useState)(``),[y,b]=(0,x.useState)(``),[w,T]=(0,x.useState)({phase:`idle`}),E=o||e[0]?.projectId||``,D=w.phase!==`sending`&&y.trim().length>0&&E.length>0,O=async()=>{if(D){T({phase:`sending`});try{let e=await n({projectId:E,type:c,...c===`broadcast`?{}:{to:u.trim()||`leader`},subject:_.trim()||`HQ prompt`,body:y.trim(),priority:f,audience:m?`leaders`:`all`});T({phase:`sent`,messageId:e.messageId}),b(``)}catch(e){T({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:E,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:`audience`}),(0,S.jsxs)(`select`,{className:`hq-select`,value:m?`leaders`:`all`,onChange:e=>g(e.target.value===`leaders`),children:[(0,S.jsx)(`option`,{value:`all`,children:`all agents`}),(0,S.jsx)(`option`,{value:`leaders`,children:`leaders only — subagents cannot consume`})]})]}),(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:_,placeholder:`subject (optional)`,onChange:e=>v(e.target.value)}),(0,S.jsx)(`textarea`,{className:`hq-input hq-composer-body`,value:y,rows:3,placeholder:`Message body — e.g. “after the current task, run the full test suite”`,onChange:e=>b(e.target.value)}),(0,S.jsxs)(`div`,{className:`hq-row`,children:[(0,S.jsx)(`button`,{type:`button`,className:`hq-btn`,disabled:!D,onClick:()=>void O(),children:w.phase===`sending`?`Sending…`:`Send`}),w.phase===`sent`&&(0,S.jsxs)(`span`,{className:`hq-composer-status ok`,children:[`delivered`,w.messageId===void 0?``:` · ${w.messageId.slice(0,8)}`]}),w.phase===`error`&&(0,S.jsx)(`span`,{className:`hq-composer-status err`,title:w.message,children:w.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`]}),w.phase===`sent`&&(0,S.jsxs)(`span`,{className:`hq-composer-status ok`,children:[`delivered`,w.messageId===void 0?``:` · ${w.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:l,tone:`info`},ask:{icon:o,tone:`warn`},assign:{icon:u,tone:`warn`},steer:{icon:o,tone:`warn`},btw:{icon:a,tone:`info`},broadcast:{icon:t,tone:`info`},status:{icon:c,tone:`idle`},result:{icon:d,tone:`running`},review:{icon:f,tone:`info`},control:{icon:s,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.audience===`leaders`&&(0,S.jsx)(`span`,{className:`hq-pill info`,children:`leaders only`}),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{F as t,I as n,L as r,Lt as i,P as a,W as o,h as s,it as c,k as l,w as u,wt as d,y as f}from"./icons-BV2PcvP1.js";import{i as p}from"./markdown-HUVrfVaI.js";import{a as m,c as h,f as g,i as _,l as v,u as y}from"./index-04jymFDH.js";import{t as b}from"./use-backfilled-events-B_7YE0rb.js";var x=e(i(),1),S=p(),C=[{value:`note`,label:`note — general information`},{value:`ask`,label:`ask — reply required`},{value:`assign`,label:`assign — work ownership`},{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`},{value:`status`,label:`status — meaningful checkpoint`},{value:`result`,label:`result — completed output/evidence`},{value:`review`,label:`review — passive inspection request`}];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)(!1),[_,v]=(0,x.useState)(``),[y,b]=(0,x.useState)(``),[w,T]=(0,x.useState)({phase:`idle`}),E=o||e[0]?.projectId||``,D=w.phase!==`sending`&&y.trim().length>0&&E.length>0,O=async()=>{if(D){T({phase:`sending`});try{let e=await n({projectId:E,type:c,...c===`broadcast`?{}:{to:u.trim()||`leader`},subject:_.trim()||`HQ prompt`,body:y.trim(),priority:f,audience:m?`leaders`:`all`});T({phase:`sent`,messageId:e.messageId}),b(``)}catch(e){T({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:E,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:`audience`}),(0,S.jsxs)(`select`,{className:`hq-select`,value:m?`leaders`:`all`,onChange:e=>g(e.target.value===`leaders`),children:[(0,S.jsx)(`option`,{value:`all`,children:`all agents`}),(0,S.jsx)(`option`,{value:`leaders`,children:`leaders only — subagents cannot consume`})]})]}),(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:_,placeholder:`subject (optional)`,onChange:e=>v(e.target.value)}),(0,S.jsx)(`textarea`,{className:`hq-input hq-composer-body`,value:y,rows:3,placeholder:`Message body — e.g. “after the current task, run the full test suite”`,onChange:e=>b(e.target.value)}),(0,S.jsxs)(`div`,{className:`hq-row`,children:[(0,S.jsx)(`button`,{type:`button`,className:`hq-btn`,disabled:!D,onClick:()=>void O(),children:w.phase===`sending`?`Sending…`:`Send`}),w.phase===`sent`&&(0,S.jsxs)(`span`,{className:`hq-composer-status ok`,children:[`delivered`,w.messageId===void 0?``:` · ${w.messageId.slice(0,8)}`]}),w.phase===`error`&&(0,S.jsx)(`span`,{className:`hq-composer-status err`,title:w.message,children:w.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`]}),w.phase===`sent`&&(0,S.jsxs)(`span`,{className:`hq-composer-status ok`,children:[`delivered`,w.messageId===void 0?``:` · ${w.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:l,tone:`info`},ask:{icon:o,tone:`warn`},assign:{icon:u,tone:`warn`},steer:{icon:o,tone:`warn`},btw:{icon:a,tone:`info`},broadcast:{icon:t,tone:`info`},status:{icon:c,tone:`idle`},result:{icon:d,tone:`running`},review:{icon:f,tone:`info`},control:{icon:s,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.audience===`leaders`&&(0,S.jsx)(`span`,{className:`hq-pill info`,children:`leaders only`}),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{C as t,Lt as n,R as r,f as i,mt as a,p as o,q as s,z as c}from"./icons-BV2PcvP1.js";import{i as l}from"./markdown-HUVrfVaI.js";import{d as u,u as d}from"./index-JtwIxe7S.js";var f=e(n(),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,n]=(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));n(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));n(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));n(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)(o,{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)(s,{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)(c,{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)(t,{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)(a,{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)(c,{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)(o,{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)(i,{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)(r,{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)(i,{size:14}),`Remove password`]}):null]})]})]})}export{h as SettingsView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{C as t,Lt as n,R as r,f as i,mt as a,p as o,q as s,z as c}from"./icons-BV2PcvP1.js";import{i as l}from"./markdown-HUVrfVaI.js";import{d as u,u as d}from"./index-04jymFDH.js";var f=e(n(),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,n]=(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));n(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));n(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));n(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)(o,{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)(s,{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)(c,{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)(t,{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)(a,{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)(c,{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)(o,{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)(i,{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)(r,{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)(i,{size:14}),`Remove password`]}):null]})]})]})}export{h as SettingsView};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Lt as t}from"./icons-BV2PcvP1.js";import{i as n}from"./markdown-HUVrfVaI.js";import{o as r}from"./index-JtwIxe7S.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),[f,p]=(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:m,totalCost:h,totalTokens:g,totalTools:_,byModel:v,byProvider:y,totalCacheRead:b,totalCacheWrite:x}=(0,i.useMemo)(()=>{let t=Date.now()-f,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,f]);if(n!==null)return(0,a.jsxs)(`div`,{className:`hq-empty hq-empty-ornate`,children:[`Error loading trends: `,n]});if(e.length===0)return(0,a.jsx)(`div`,{className:`hq-empty hq-empty-ornate`,children:`No trend data yet. Trends accumulate as cost signals arrive.`});let S=v.length>0,C=b+x>0?b/(b+x)*100:null,w=s.find(e=>e.ms===f)?.label??`custom`;return(0,a.jsxs)(`div`,{className:`hq-screen hq-trends-screen`,children:[(0,a.jsxs)(`section`,{className:`hq-screen-hero hq-trends-hero`,"aria-label":`Telemetry trend summary`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Telemetry runway`}),(0,a.jsxs)(`h2`,{children:[w,` signal window`]}),(0,a.jsx)(`p`,{children:`Cost, tokens and tool activity are split into single-purpose charts so spikes stay attributable without dual-axis ambiguity.`})]}),(0,a.jsxs)(`div`,{className:`hq-hero-metrics`,children:[(0,a.jsx)(d,{label:`cost`,value:`$${h.toFixed(4)}`}),(0,a.jsx)(d,{label:`tokens`,value:c(g),tone:`warn`}),(0,a.jsx)(d,{label:`tool calls`,value:_.toLocaleString(),tone:`ok`}),C===null?null:(0,a.jsx)(d,{label:`cache hit`,value:`${C.toFixed(0)}%`})]})]}),(0,a.jsxs)(`div`,{className:`hq-filter-row hq-trends-filter-row`,children:[s.map(e=>(0,a.jsx)(`button`,{type:`button`,className:`hq-pill hq-filter-chip${f===e.ms?` selected`:``}`,onClick:()=>p(e.ms),children:e.label},e.label)),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle hq-ml-auto`,children:[m.length,` × 5-min buckets`]})]}),(0,a.jsxs)(`section`,{className:`hq-chart-gallery`,"aria-label":`Trend charts`,children:[(0,a.jsxs)(`div`,{className:`hq-card hq-chart-card primary`,children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Spend`}),(0,a.jsx)(`h3`,{children:`Cost (USD)`})]})}),(0,a.jsx)(o,{points:m.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 hq-chart-card`,children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Volume`}),(0,a.jsx)(`h3`,{children:`Tokens (in + out)`})]})}),(0,a.jsx)(o,{points:m.map(e=>({ts:e.ts,value:e.inputTokens+e.outputTokens})),color:`var(--chart-2)`,format:c})]}),(0,a.jsxs)(`div`,{className:`hq-card hq-chart-card`,children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Activity`}),(0,a.jsx)(`h3`,{children:`Tool calls`})]})}),(0,a.jsx)(o,{points:m.map(e=>({ts:e.ts,value:e.toolCalls})),color:`var(--chart-3)`,format:e=>String(Math.round(e))})]})]}),S&&(0,a.jsxs)(`section`,{className:`hq-two-column hq-trends-breakdowns`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Model economics`}),(0,a.jsx)(`h3`,{children:`By Model`})]})}),(0,a.jsx)(`div`,{className:`hq-card hq-breakdown-card`,children:v.map(({key:e,entry:t})=>{let n=h>0?t.costUsd/h*100:0;return(0,a.jsxs)(`div`,{className:`hq-row hq-breakdown-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)})})]}),y.length>1&&(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Provider split`}),(0,a.jsx)(`h3`,{children:`By Provider`})]})}),(0,a.jsx)(`div`,{className:`hq-card hq-breakdown-card`,children:y.map(({key:e,entry:t})=>{let n=h>0?t.costUsd/h*100:0;return(0,a.jsxs)(`div`,{className:`hq-row hq-breakdown-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)})})]})]})]})}function d({label:e,value:t,tone:n}){return(0,a.jsxs)(`div`,{className:`hq-hero-metric`,"data-tone":n,children:[(0,a.jsx)(`strong`,{children:t}),(0,a.jsx)(`span`,{children:e})]})}export{u as TrendsView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Lt as t}from"./icons-BV2PcvP1.js";import{i as n}from"./markdown-HUVrfVaI.js";import{o as r}from"./index-04jymFDH.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),[f,p]=(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:m,totalCost:h,totalTokens:g,totalTools:_,byModel:v,byProvider:y,totalCacheRead:b,totalCacheWrite:x}=(0,i.useMemo)(()=>{let t=Date.now()-f,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,f]);if(n!==null)return(0,a.jsxs)(`div`,{className:`hq-empty hq-empty-ornate`,children:[`Error loading trends: `,n]});if(e.length===0)return(0,a.jsx)(`div`,{className:`hq-empty hq-empty-ornate`,children:`No trend data yet. Trends accumulate as cost signals arrive.`});let S=v.length>0,C=b+x>0?b/(b+x)*100:null,w=s.find(e=>e.ms===f)?.label??`custom`;return(0,a.jsxs)(`div`,{className:`hq-screen hq-trends-screen`,children:[(0,a.jsxs)(`section`,{className:`hq-screen-hero hq-trends-hero`,"aria-label":`Telemetry trend summary`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Telemetry runway`}),(0,a.jsxs)(`h2`,{children:[w,` signal window`]}),(0,a.jsx)(`p`,{children:`Cost, tokens and tool activity are split into single-purpose charts so spikes stay attributable without dual-axis ambiguity.`})]}),(0,a.jsxs)(`div`,{className:`hq-hero-metrics`,children:[(0,a.jsx)(d,{label:`cost`,value:`$${h.toFixed(4)}`}),(0,a.jsx)(d,{label:`tokens`,value:c(g),tone:`warn`}),(0,a.jsx)(d,{label:`tool calls`,value:_.toLocaleString(),tone:`ok`}),C===null?null:(0,a.jsx)(d,{label:`cache hit`,value:`${C.toFixed(0)}%`})]})]}),(0,a.jsxs)(`div`,{className:`hq-filter-row hq-trends-filter-row`,children:[s.map(e=>(0,a.jsx)(`button`,{type:`button`,className:`hq-pill hq-filter-chip${f===e.ms?` selected`:``}`,onClick:()=>p(e.ms),children:e.label},e.label)),(0,a.jsxs)(`span`,{className:`hq-mono hq-row-subtle hq-ml-auto`,children:[m.length,` × 5-min buckets`]})]}),(0,a.jsxs)(`section`,{className:`hq-chart-gallery`,"aria-label":`Trend charts`,children:[(0,a.jsxs)(`div`,{className:`hq-card hq-chart-card primary`,children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Spend`}),(0,a.jsx)(`h3`,{children:`Cost (USD)`})]})}),(0,a.jsx)(o,{points:m.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 hq-chart-card`,children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Volume`}),(0,a.jsx)(`h3`,{children:`Tokens (in + out)`})]})}),(0,a.jsx)(o,{points:m.map(e=>({ts:e.ts,value:e.inputTokens+e.outputTokens})),color:`var(--chart-2)`,format:c})]}),(0,a.jsxs)(`div`,{className:`hq-card hq-chart-card`,children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Activity`}),(0,a.jsx)(`h3`,{children:`Tool calls`})]})}),(0,a.jsx)(o,{points:m.map(e=>({ts:e.ts,value:e.toolCalls})),color:`var(--chart-3)`,format:e=>String(Math.round(e))})]})]}),S&&(0,a.jsxs)(`section`,{className:`hq-two-column hq-trends-breakdowns`,children:[(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Model economics`}),(0,a.jsx)(`h3`,{children:`By Model`})]})}),(0,a.jsx)(`div`,{className:`hq-card hq-breakdown-card`,children:v.map(({key:e,entry:t})=>{let n=h>0?t.costUsd/h*100:0;return(0,a.jsxs)(`div`,{className:`hq-row hq-breakdown-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)})})]}),y.length>1&&(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`div`,{className:`hq-section-head compact`,children:(0,a.jsxs)(`div`,{children:[(0,a.jsx)(`span`,{className:`hq-section-kicker`,children:`Provider split`}),(0,a.jsx)(`h3`,{children:`By Provider`})]})}),(0,a.jsx)(`div`,{className:`hq-card hq-breakdown-card`,children:y.map(({key:e,entry:t})=>{let n=h>0?t.costUsd/h*100:0;return(0,a.jsxs)(`div`,{className:`hq-row hq-breakdown-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)})})]})]})]})}function d({label:e,value:t,tone:n}){return(0,a.jsxs)(`div`,{className:`hq-hero-metric`,"data-tone":n,children:[(0,a.jsx)(`strong`,{children:t}),(0,a.jsx)(`span`,{children:e})]})}export{u as TrendsView};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{Lt as t}from"./icons-BV2PcvP1.js";import{l as n,o as r}from"./index-JtwIxe7S.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{Lt as t}from"./icons-BV2PcvP1.js";import{l as n,o as r}from"./index-04jymFDH.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{D as t,Lt as n,c as r,kt as i,l as a,tt as o,yt as s}from"./icons-BV2PcvP1.js";import{i as c}from"./markdown-HUVrfVaI.js";import{t as l}from"./use-backfilled-events-XgbaW3ZO.js";var u=e(n(),1),d=c(),f={allocated:{Icon:t,cls:`info`},committed:{Icon:i,cls:`active`},merged:{Icon:o,cls:`active`},conflict:{Icon:r,cls:`warn`},released:{Icon:a,cls:`idle`},failed:{Icon:s,cls:`error`}};function p({e}){let n=e.payload,r=f[n.kind]??{Icon:t,cls:`info`};return(0,d.jsxs)(`div`,{className:`hq-row hq-worktree-event-line`,children:[(0,d.jsx)(r.Icon,{size:14,className:`hq-kind-icon ${r.cls}`}),(0,d.jsx)(`span`,{className:`hq-text-bright`,children:n.kind}),n.branch!==void 0&&(0,d.jsx)(`span`,{className:`hq-pill info`,children:n.branch}),n.kind===`committed`&&(0,d.jsxs)(`span`,{className:`hq-mono hq-diffstat`,children:[(0,d.jsxs)(`span`,{className:`hq-diff-add-count`,children:[`+`,n.insertions??0]}),` `,(0,d.jsxs)(`span`,{className:`hq-diff-del-count`,children:[`−`,n.deletions??0]}),` in `,n.files??0,` file(s)`,` `,n.sha===void 0?``:`(${n.sha.slice(0,7)})`]}),n.kind===`conflict`&&n.conflictFiles!==void 0&&(0,d.jsxs)(`span`,{className:`hq-mono hq-row-error`,children:[`conflicts: `,n.conflictFiles.join(`, `)]}),n.kind===`failed`&&(0,d.jsx)(`span`,{className:`hq-mono hq-row-error`,children:n.error}),(0,d.jsx)(`span`,{className:`hq-mono hq-row-time`,children:new Date(e.timestamp).toLocaleTimeString()})]})}function m(){let{events:e,loading:n}=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]),i=(0,u.useMemo)(()=>{let e=0,t=0,n=0,i=0;for(let[,a]of r){let r=a.at(-1)?.payload;r?.kind===`merged`||r?.kind===`released`?t+=1:e+=1,a.some(e=>e.payload.kind===`conflict`)&&(n+=1),a.some(e=>e.payload.kind===`failed`)&&(i+=1)}return{open:e,merged:t,conflicts:n,failed:i}},[r]);return r.length===0?(0,d.jsx)(`div`,{className:`hq-empty hq-empty-ornate`,children:n?`Loading worktree history…`:`No worktree events yet. These appear when Goal allocates or merges git worktrees for parallel phases.`}):(0,d.jsxs)(`div`,{className:`hq-screen hq-worktree-screen`,children:[(0,d.jsxs)(`section`,{className:`hq-screen-hero hq-worktree-hero`,"aria-label":`Worktree lifecycle summary`,children:[(0,d.jsxs)(`div`,{children:[(0,d.jsx)(`span`,{className:`hq-section-kicker`,children:`Workspace lanes`}),(0,d.jsx)(`h2`,{children:`Parallel branch lifecycle`}),(0,d.jsx)(`p`,{children:`Each owner gets a lane so allocation, commits, conflicts, merges and release events read as an ordered build path.`})]}),(0,d.jsxs)(`div`,{className:`hq-hero-metrics`,children:[(0,d.jsx)(h,{label:`lanes`,value:r.length}),(0,d.jsx)(h,{label:`open`,value:i.open,tone:i.open>0?`warn`:`ok`}),(0,d.jsx)(h,{label:`merged/released`,value:i.merged,tone:`ok`}),(0,d.jsx)(h,{label:`conflicts`,value:i.conflicts+i.failed,tone:i.conflicts+i.failed>0?`error`:`ok`})]})]}),(0,d.jsx)(`div`,{className:`hq-worktree-lanes`,children:r.map(([e,n])=>{let r=n[n.length-1].payload,i=f[r.kind]??{Icon:t,cls:`info`};return(0,d.jsxs)(`article`,{className:`hq-card hq-worktree-lane`,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:[n.length,` events`]})]}),(0,d.jsx)(`div`,{className:`hq-worktree-event-list`,children:n.map(e=>(0,d.jsx)(p,{e},e.id))})]},e)})})]})}function h({label:e,value:t,tone:n}){return(0,d.jsxs)(`div`,{className:`hq-hero-metric`,"data-tone":n,children:[(0,d.jsx)(`strong`,{children:t}),(0,d.jsx)(`span`,{children:e})]})}export{m as WorktreeView};
1
+ import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{D as t,Lt as n,c as r,kt as i,l as a,tt as o,yt as s}from"./icons-BV2PcvP1.js";import{i as c}from"./markdown-HUVrfVaI.js";import{t as l}from"./use-backfilled-events-B_7YE0rb.js";var u=e(n(),1),d=c(),f={allocated:{Icon:t,cls:`info`},committed:{Icon:i,cls:`active`},merged:{Icon:o,cls:`active`},conflict:{Icon:r,cls:`warn`},released:{Icon:a,cls:`idle`},failed:{Icon:s,cls:`error`}};function p({e}){let n=e.payload,r=f[n.kind]??{Icon:t,cls:`info`};return(0,d.jsxs)(`div`,{className:`hq-row hq-worktree-event-line`,children:[(0,d.jsx)(r.Icon,{size:14,className:`hq-kind-icon ${r.cls}`}),(0,d.jsx)(`span`,{className:`hq-text-bright`,children:n.kind}),n.branch!==void 0&&(0,d.jsx)(`span`,{className:`hq-pill info`,children:n.branch}),n.kind===`committed`&&(0,d.jsxs)(`span`,{className:`hq-mono hq-diffstat`,children:[(0,d.jsxs)(`span`,{className:`hq-diff-add-count`,children:[`+`,n.insertions??0]}),` `,(0,d.jsxs)(`span`,{className:`hq-diff-del-count`,children:[`−`,n.deletions??0]}),` in `,n.files??0,` file(s)`,` `,n.sha===void 0?``:`(${n.sha.slice(0,7)})`]}),n.kind===`conflict`&&n.conflictFiles!==void 0&&(0,d.jsxs)(`span`,{className:`hq-mono hq-row-error`,children:[`conflicts: `,n.conflictFiles.join(`, `)]}),n.kind===`failed`&&(0,d.jsx)(`span`,{className:`hq-mono hq-row-error`,children:n.error}),(0,d.jsx)(`span`,{className:`hq-mono hq-row-time`,children:new Date(e.timestamp).toLocaleTimeString()})]})}function m(){let{events:e,loading:n}=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]),i=(0,u.useMemo)(()=>{let e=0,t=0,n=0,i=0;for(let[,a]of r){let r=a.at(-1)?.payload;r?.kind===`merged`||r?.kind===`released`?t+=1:e+=1,a.some(e=>e.payload.kind===`conflict`)&&(n+=1),a.some(e=>e.payload.kind===`failed`)&&(i+=1)}return{open:e,merged:t,conflicts:n,failed:i}},[r]);return r.length===0?(0,d.jsx)(`div`,{className:`hq-empty hq-empty-ornate`,children:n?`Loading worktree history…`:`No worktree events yet. These appear when Goal allocates or merges git worktrees for parallel phases.`}):(0,d.jsxs)(`div`,{className:`hq-screen hq-worktree-screen`,children:[(0,d.jsxs)(`section`,{className:`hq-screen-hero hq-worktree-hero`,"aria-label":`Worktree lifecycle summary`,children:[(0,d.jsxs)(`div`,{children:[(0,d.jsx)(`span`,{className:`hq-section-kicker`,children:`Workspace lanes`}),(0,d.jsx)(`h2`,{children:`Parallel branch lifecycle`}),(0,d.jsx)(`p`,{children:`Each owner gets a lane so allocation, commits, conflicts, merges and release events read as an ordered build path.`})]}),(0,d.jsxs)(`div`,{className:`hq-hero-metrics`,children:[(0,d.jsx)(h,{label:`lanes`,value:r.length}),(0,d.jsx)(h,{label:`open`,value:i.open,tone:i.open>0?`warn`:`ok`}),(0,d.jsx)(h,{label:`merged/released`,value:i.merged,tone:`ok`}),(0,d.jsx)(h,{label:`conflicts`,value:i.conflicts+i.failed,tone:i.conflicts+i.failed>0?`error`:`ok`})]})]}),(0,d.jsx)(`div`,{className:`hq-worktree-lanes`,children:r.map(([e,n])=>{let r=n[n.length-1].payload,i=f[r.kind]??{Icon:t,cls:`info`};return(0,d.jsxs)(`article`,{className:`hq-card hq-worktree-lane`,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:[n.length,` events`]})]}),(0,d.jsx)(`div`,{className:`hq-worktree-event-list`,children:n.map(e=>(0,d.jsx)(p,{e},e.id))})]},e)})})]})}function h({label:e,value:t,tone:n}){return(0,d.jsxs)(`div`,{className:`hq-hero-metric`,"data-tone":n,children:[(0,d.jsx)(`strong`,{children:t}),(0,d.jsx)(`span`,{children: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-JtwIxe7S.js"></script>
8
+ <script type="module" crossorigin src="/assets/index-04jymFDH.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-QTnfLwEv.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/icons-BV2PcvP1.js">
11
11
  <link rel="modulepreload" crossorigin href="/assets/vendor-DT5_U5Rx.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wrongstack/webui-hq",
3
- "version": "0.296.2",
3
+ "version": "0.296.4",
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,9 +21,9 @@
21
21
  "remark-gfm": "^4.0.1",
22
22
  "virtua": "^0.49.3",
23
23
  "zustand": "5.0.14",
24
- "@wrongstack/core": "0.296.2",
25
- "@wrongstack/webui-server": "0.296.2",
26
- "@wrongstack/tools": "0.296.2"
24
+ "@wrongstack/core": "0.296.4",
25
+ "@wrongstack/webui-server": "0.296.4",
26
+ "@wrongstack/tools": "0.296.4"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/react": "^19.2.17",
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/cockpit-TAQtONc4.js","assets/rolldown-runtime-QTnfLwEv.js","assets/icons-BV2PcvP1.js","assets/markdown-HUVrfVaI.js","assets/fleet-map-NYSgfhOv.js","assets/vendor-DT5_U5Rx.js","assets/fleet-topology-D59v7Ec7.js","assets/live-console-UTUFGuNq.js","assets/mailbox-CfZc7ihG.js","assets/use-backfilled-events-XgbaW3ZO.js","assets/kanban-DafBjWVp.js","assets/cost-BdYMgqJF.js","assets/brain-rtqqgiFJ.js","assets/worktree-CJgUsABP.js","assets/trends-D8ophSBn.js","assets/alerts-BjEpUt0S.js","assets/control-RGqCysT8.js","assets/settings-7QqKSgKT.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{A as t,At as n,C as r,Ct as i,E as a,It as o,J as s,K as c,Lt as l,Mt as u,N as d,Pt as f,R as ee,St as p,T as te,Y as ne,_ as re,a as ie,c as m,g as h,ht as g,i as ae,j as oe,mt as _,n as v,o as se,p as ce,rt as le,u as ue,x as y,yt as de}from"./icons-BV2PcvP1.js";import{t as fe}from"./vendor-DT5_U5Rx.js";import{i as pe}from"./markdown-HUVrfVaI.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 b={maxReconnectAttempts:10,initialBackoffMs:1e3,maxBackoffMs:3e4,backoffMultiplier:2,jitterRatio:0,queueLimit:1e3,heartbeatIntervalMs:0,heartbeatTimeoutMs:0};function me(){return{phase:`idle`,reconnectAttempt:0,lastActivityAt:null,stopped:!1}}function he(e){return e.stopped?e:{...e,phase:`connecting`}}function ge(e,t=Date.now()){return{...e,phase:`open`,reconnectAttempt:0,lastActivityAt:t,stopped:!1}}function _e(e,t=Date.now()){return{...e,lastActivityAt:t}}function ve(e){return{...e,phase:`closed`,stopped:!0}}function ye(e,t,n=Date.now(),r=Math.random){if(e.stopped||e.reconnectAttempt>=t.maxReconnectAttempts)return{state:{...e,phase:`closed`},plan:null};let i=e.reconnectAttempt+1,a=Math.min(t.initialBackoffMs*t.backoffMultiplier**(i-1),t.maxBackoffMs),o=(r()*2-1)*t.jitterRatio,s=Math.max(0,Math.round(a*(1+o)));return{state:{...e,phase:`reconnecting`,reconnectAttempt:i},plan:{attempt:i,delayMs:s,retryAt:n+s}}}function be(e,t,n=Date.now()){return e.phase!==`open`||e.lastActivityAt===null||t.heartbeatIntervalMs<=0?!1:n-e.lastActivityAt>t.heartbeatIntervalMs+t.heartbeatTimeoutMs}var xe=`abort,ping,user_message,tool.confirm_result,completion.request,model.switch,model.refine,autonomy.switch,context.clear,context.compact,context.debug,context.editor.open,context.editor.validate,context.editor.apply,context.mode.create,context.mode.delete,context.mode.switch,context.mode.update,context.modes.list,context.repair,mode.switch,modes.list,session.checkpoints,session.delete,session.new,session.rename,session.resume,session.rewind,session.save,sessions.list,side_effects.list,stats.get,todo.update,todos.clear,todos.get,todos.remove`.split(`,`),Se=[`collab.join`,`collab.leave`,`collab.annotate`,`collab.resolve`,`collab.request_pause`,`collab.resume`,`collab.grant_control`,`collab.inject_tool`,`mailbox.agents`,`mailbox.clear`,`mailbox.compact`,`mailbox.messages`,`mailbox.purge`,`mailbox.send`],Ce=`brain.ask,brain.config.get,brain.config.set,brain.risk,brain.status,chronicle.facet,chronicle.facets,chronicle.graph,chronicle.metrics,chronicle.query,chronicle.status,config.doctor,design.list,design.materialize,design.set,design.state,design.swap,design.tune,design.use,design.verify,memory.list,memory.sage.backfillRecoverable,memory.sage.candidateResolve,memory.sage.delete,memory.sage.forFile,memory.sage.get,memory.sage.graph,memory.sage.list,memory.sage.listPage,memory.sage.recover,memory.sage.remember,memory.sage.update`.split(`,`),we=`auth.oauth.cancel,auth.oauth.code,auth.oauth.start,mcp.add,mcp.disable,mcp.discover,mcp.enable,mcp.list,mcp.prompt.get,mcp.prompts,mcp.remove,mcp.resource.read,mcp.resources,mcp.restart,mcp.sleep,mcp.update,mcp.wake,prompts.content,prompts.create,prompts.favorite,prompts.list,prompts.recent,prompts.search,prompts.used,skills.content,skills.create,skills.edit,skills.export,skills.install,skills.list,skills.uninstall,skills.update`.split(`,`),Te=`goal-state.get,goal.addTask,goal.assess,goal.assignTask,goal.clear,goal.get,goal.list,goal.load,goal.moveTask,goal.pause,goal.resume,goal.retryTask,goal.revert,goal.runTask,goal.save,goal.selectPhase,goal.start,goal.state,goal.status,goal.stop,goal.taskStatus,goal.toggleAutonomous,plan.get,plan.item.update,plan.template_use,task.update,tasks.get`.split(`,`),Ee=`sdd.board.cancel_task,sdd.board.cleanup_worktrees,sdd.board.delete_task,sdd.board.destroy,sdd.board.get,sdd.board.list,sdd.board.pause,sdd.board.reassign,sdd.board.resume,sdd.board.retry,sdd.board.retry_all_failed,sdd.board.rollback,sdd.board.set_task_fallbacks,sdd.board.set_task_model,sdd.board.set_task_verification,sdd.board.split_task,sdd.board.stop,sdd.run.from_graph,sdd.run.from_spec,sdd.run.start,sdd.spec.approve,sdd.spec.discard,sdd.spec.get,sdd.spec.message,sdd.spec.start,specs.get,specs.list,specs.taskStatus`.split(`,`),De=[`files.list`,`files.read`,`files.tree`,`files.write`,`git.changes`,`git.diff`,`git.info`,`projects.add`,`projects.list`,`projects.select`,`working_dir.set`,`worktree.cleanup`,`worktree.diff`,`worktree.merge`,`worktree.remove`,`worktree.scan`,`shell.open`,`process.kill`,`process.killAll`,`process.list`,`terminal.close`,`terminal.create`,`terminal.input`,`terminal.resize`],Oe=`codebase.index.server.shutdown,connections.health,diag.get,key.add,key.delete,key.set_active,key.update,prefs.get,prefs.update,provider.add,provider.clear_models,provider.models,provider.models.search,provider.probe,provider.remove,provider.status.clear,provider.status.get,provider.status.retry,provider.undo_clear,provider.update,providers.list,providers.saved,tool.disable,tool.enable,tools.list,webui.shutdown`.split(`,`),ke=`error,log,pong,side_effects,agent.status_changed,agent.timeline.message,client.status_update,compaction.failed,completion.result,context.compacted,context.debug,context.editor.snapshot,context.editor.validation,context.editor.applied,context.mode.changed,context.modes.list,context.repaired,ctx.max_context,ctx.pct,delegate.completed,delegate.started,iteration.completed,iteration.limit_reached,iteration.started,model.refine_result,modes.list,provider.active_blocked,provider.error,provider.fallback,provider.response,provider.retry,provider.status_changed,provider.stream_error,provider.text_delta,provider.thinking_delta,run.result,session.checkpoints,session.damaged,session.end,session.rewound,session.start,session.stats,sessions.list,sessions.status_update,stats.get,token.cost_estimate_unavailable,token.threshold,tool.confirm_needed,tool.disabled,tool.enabled,tool.executed,tool.loop_detected,tool.progress,tool.started,tools.list,trust.persisted`.split(`,`),Ae=[`collab.annotation.added`,`collab.annotation.resolved`,`collab.event`,`collab.injection.granted`,`collab.participant.joined`,`collab.participant.left`,`collab.pause.granted`,`collab.pause.released`,`collab.state`,`mailbox.agent_registered`,`mailbox.agents`,`mailbox.cleared`,`mailbox.compacted`,`mailbox.event`,`mailbox.messages`,`mailbox.sent`,`mailbox.purged`,`mailbox.received`,`subagent.budget_extended`,`subagent.event`],je=`brain.answer,brain.config,brain.event,brain.status,chronicle.error,chronicle.facet_result,chronicle.facets_result,chronicle.graph_result,chronicle.metrics_result,chronicle.query_result,chronicle.status_result,config.doctor.result,design.list,design.materialize,design.set,design.state,design.swap,design.tune,design.use,design.verify,memory.event,memory.list,memory.sage.backfillRecoverable,memory.sage.candidateResolve,memory.sage.delete,memory.sage.forFile,memory.sage.get,memory.sage.graph,memory.sage.list,memory.sage.listPage,memory.sage.recover,memory.sage.remember,memory.sage.update`.split(`,`),Me=`mcp.content.error,mcp.content.selected,mcp.list,mcp.operation_result,mcp.prompts,mcp.resources,mcp.server.added,mcp.server.connected,mcp.server.disconnected,mcp.server.discovered,mcp.server.error,mcp.server.reconnected,mcp.server.removed,mcp.server.sleeping,mcp.server.updated,mcp.server.waking,prompts.content,prompts.created,prompts.favorite,prompts.list,prompts.recent,prompts.search,prompts.used,skills.content,skills.created,skills.edited,skills.exported,skills.installed,skills.list,skills.uninstalled,skills.updated`.split(`,`),Ne=`budget.decision,budget.threshold_reached,coordinator.stats,coordinator.status,eternal.iteration,fleet.concurrency_update,goal-state.updated,goal.assess.result,goal.list,goal.paused,goal.resumed,goal.saved,goal.error,goal.stopped,goal.failed,goal.completed,goal.cleared,goal.reverted,goal.progress,goal.state,in_flight.ended,in_flight.started,plan.updated,task.completed,task.failed,task.pending,task.started,tasks.updated,todos.cleared,todos.updated`.split(`,`),Pe=[`kanban.task.activity`,`sdd.board.lifecycle_result`,`sdd.board.list`,`sdd.board.snapshot`,`sdd.run.started`,`sdd.spec.agent_text`,`sdd.spec.error`,`sdd.spec.snapshot`,`specs.detail`,`specs.list`],Fe=[`consensus.vote_cast`,`consensus.vote_initiated`,`consensus.vote_resolved`,`cron.job_fired`,`cron.snapshot`,`techstack.job.cancelled`,`techstack.job.failed`,`techstack.job.progress`,`techstack.job.started`,`techstack.report.delivered`,`techstack.report.ready`,`techstack.snapshot.updated`,`techstack.workspace.completed`],Ie=`checkpoint.written,codemap.file_event,codemap.index_updated,codemap.tool_executed,codemap.tool_started,file.saved,files.list,files.read,files.tree,files.written,git.changes,git.diff,git.info,process.list,projects.added,projects.list,projects.selected,terminal.exit,terminal.output,working_dir.changed,worktree.cleanup_result,worktree.diff_result,worktree.event,worktree.merge_result,worktree.orphans,worktree.state`.split(`,`),Le=[`auth.oauth.status`,`codebase.index.server.shutdown_result`,`connections.health_error`,`connections.health_result`,`diag.get`,`key.operation_result`,`model.switch_result`,`prefs.updated`,`provider.catalog`,`provider.models`,`provider.models.search_result`,`provider.probe`,`provider.status.snapshot`,`providers.saved`],Re=[...xe,...Se,...De,...Oe,...Te,...Ee,...Ce,...we],ze=[...ke,...Ae,...Ie,...Le,...Ne,...Pe,...Fe,...je,...Me];new Set(Re),new Set(ze);function x(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function S(e,t=0){return typeof e==`number`&&Number.isFinite(e)?e:t}function C(e){return e===void 0||Array.isArray(e)}function Be(e){return S(e.activeProjects)===e.activeProjects&&S(e.activeClients)===e.activeClients&&S(e.activeSessions)===e.activeSessions&&S(e.activeSubagents)===e.activeSubagents&&S(e.unreadMailboxMessages)===e.unreadMailboxMessages&&S(e.incompleteMailboxMessages)===e.incompleteMailboxMessages&&S(e.totalCostUsd)===e.totalCostUsd}function Ve(e){if(e.type!==`hq.snapshot`)return null;let t=x(e.snapshot),n=t?x(t.totals):null;return!t||typeof t.generatedAt!=`string`||!Array.isArray(t.clients)||!Array.isArray(t.projects)||!Array.isArray(t.sessions)||!Array.isArray(t.fleets)||!Array.isArray(t.mailboxes)||!n||!Be(n)||!C(t.machines)||!C(t.liveSessions)||!C(t.mcpServers)?null:{kind:`hq-snapshot`,snapshot:t}}function He(e){if(e.type!==`hq.event`)return null;let t=x(e.event);return!t||typeof t.id!=`string`||typeof t.type!=`string`||typeof t.timestamp!=`string`||typeof t.clientId!=`string`||typeof t.projectId!=`string`||typeof t.seq!=`number`?null:{kind:`hq-event`,event:t}}function Ue(e){return e.type!==`hq.alert`||typeof e.severity!=`string`||![`info`,`warn`,`error`].includes(e.severity)||typeof e.message!=`string`||typeof e.timestamp!=`string`?null:{kind:`hq-alert`,alert:e}}function We(e){if(e.type!==`hq.command_status`)return null;let t=x(e.command);return!t||typeof t.commandId!=`string`||typeof t.type!=`string`||typeof t.clientId!=`string`||typeof t.enqueuedBy!=`string`||typeof t.enqueuedAt!=`string`||typeof t.status!=`string`||![`queued`,`delivered`,`acked`].includes(t.status)?null:{kind:`hq-command-status`,command:t}}var w=e(l(),1),Ge=fe(),T=e=>Symbol.iterator in e,E=e=>`entries`in e,D=(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},Ke=(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 qe(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:T(e)&&T(t)?E(e)&&E(t)?D(e,t):Ke(e,t):D({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function O(e){let t=w.useRef(void 0);return n=>{let r=e(n);return qe(t.current,r)?t.current:t.current=r}}var k=`wrongstack.hq.token.v1`;function A(){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 j(){if(typeof window>`u`)return null;try{return window.sessionStorage??null}catch{return null}}function M(){try{let e=j()?.getItem(k)??null;return e!==null&&e.length>0?e:null}catch{return null}}function N(e){try{j()?.setItem(k,e)}catch{}}function P(){try{j()?.removeItem(k)}catch{}}function F(){let e=A();return e===null?M():(N(e),e)}function Je(){if(typeof window>`u`)return;let e=A();if(e!==null&&(N(e),M()===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 Ye(){let e=F();return e===null?{}:{Authorization:`Bearer ${e}`}}function I(e,t){let n={...t?.headers??{},...Ye()};return fetch(e,{...t,headers:n})}var Xe=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},Ze=(e=>e?Xe(e):Xe),Qe=e=>e;function $e(e,t=Qe){let n=w.useSyncExternalStore(e.subscribe,w.useCallback(()=>t(e.getState()),[e,t]),w.useCallback(()=>t(e.getInitialState()),[e,t]));return w.useDebugValue(n),n}var et=e=>{let t=Ze(e),n=e=>$e(t,e);return Object.assign(n,t),n},tt=(e=>e?et(e):et),nt=6e3,rt=0,L=tt()(e=>({toasts:[],addToast:(t,n=`info`,r=nt,i)=>{let a=`toast-${++rt}-${Date.now()}`,o={id:a,message:t,severity:n,createdAt:Date.now(),ttlMs:r,action:i};e(e=>({toasts:[...e.toasts.slice(-4),o]})),r>0&&setTimeout(()=>{e(e=>({toasts:e.toasts.filter(e=>e.id!==a)}))},r)},removeToast:t=>e(e=>({toasts:e.toasts.filter(e=>e.id!==t)})),clearToasts:()=>e({toasts:[]})})),R=pe(),it={error:(0,R.jsx)(de,{size:16,"aria-hidden":`true`}),warning:(0,R.jsx)(m,{size:16,"aria-hidden":`true`}),info:(0,R.jsx)(s,{size:16,"aria-hidden":`true`}),success:(0,R.jsx)(i,{size:16,"aria-hidden":`true`})};function at(){let{toasts:e,removeToast:t}=L(O(e=>({toasts:e.toasts,removeToast:e.removeToast})));return e.length===0?null:(0,R.jsx)(`div`,{className:`hq-toast-container`,role:`status`,"aria-live":`polite`,"aria-label":`Notifications`,children:e.map(e=>(0,R.jsxs)(`div`,{className:`hq-toast hq-toast--${e.severity}`,"data-severity":e.severity,children:[(0,R.jsx)(`span`,{className:`hq-toast-icon`,children:it[e.severity]}),(0,R.jsx)(`span`,{className:`hq-toast-message`,children:e.message}),e.action?(0,R.jsx)(`span`,{className:`hq-toast-action`,children:e.action}):null,(0,R.jsx)(`button`,{type:`button`,className:`hq-toast-close`,"aria-label":`Dismiss notification`,onClick:()=>t(e.id),children:(0,R.jsx)(v,{size:12})})]},e.id))})}function ot(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 st(e,t){return e.timestamp===t.timestamp&&e.severity===t.severity&&e.message===t.message}var z=tt()(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?ot(e,t):{}),_onSnapshot:t=>e(e=>({...ot(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=>st(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 B(e){let t;try{t=await I(e)}catch{throw Error(`Network error fetching ${e}`)}if(t.status===401)throw z.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 ct(e){let t;try{t=await I(`/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 z.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 lt(e,t,n){let r;try{r=await I(`/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 z.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 ut=`wrongstack.hq.local-prefs.v1`,V={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}},H=null,U=new Set;function W(){for(let e of U)e()}function G(e){return typeof structuredClone==`function`?structuredClone(e):JSON.parse(JSON.stringify(e))}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dt(){if(typeof window>`u`||window.localStorage===void 0)return G(V);try{let e=window.localStorage.getItem(ut);return e===null?G(V):ft(JSON.parse(e))}catch{return G(V)}}function ft(e){if(!K(e))return G(V);let t=K(e.appearance)?e.appearance:{},n=K(e.fleet)?e.fleet:{},r=K(e.console)?e.console:{},i=K(e.control)?e.control:{},a=K(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:V.control.cmdType,abortTarget:i.abortTarget===`fleet`?`fleet`:`leader`,spawnRole:typeof i.spawnRole==`string`&&i.spawnRole.length>0?i.spawnRole:V.control.spawnRole,spawnTask:typeof i.spawnTask==`string`?i.spawnTask:V.control.spawnTask,steerTo:typeof i.steerTo==`string`?i.steerTo:V.control.steerTo,steerSubject:typeof i.steerSubject==`string`?i.steerSubject:V.control.steerSubject,steerBody:typeof i.steerBody==`string`?i.steerBody:V.control.steerBody,broadcastSubject:typeof i.broadcastSubject==`string`?i.broadcastSubject:V.control.broadcastSubject,broadcastBody:typeof i.broadcastBody==`string`?i.broadcastBody:V.control.broadcastBody},mailbox:{query:typeof a.query==`string`?a.query:V.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 q(){return H===null&&(H=dt()),H}function J(e){if(!(typeof window>`u`||window.localStorage===void 0))try{window.localStorage.setItem(ut,JSON.stringify(e))}catch{}}function pt(e){return U.add(e),()=>U.delete(e)}function mt(){return q()}function ht(){return V}function gt(){return(0,w.useSyncExternalStore)(pt,mt,ht)}function _t(e){let t=q();H={...t,control:{...t.control,...e}},J(H),W()}function vt(e){let t=q();H={...t,appearance:{...t.appearance,...e}},J(H),W()}function yt(e){let t=q();H={...t,fleet:{...t.fleet,...e}},J(H),W()}function bt(e){let t=q();H={...t,console:{...t.console,...e}},J(H),W()}function xt(e){let t=q();H={...t,mailbox:{...t.mailbox,...e}},J(H),W()}function St({hadToken:e}){let[t,n]=(0,w.useState)(null),[r,i]=(0,w.useState)(null);(0,w.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,w.useState)(`token`);return(0,w.useEffect)(()=>{t&&c(t.passwordMode?`password`:`token`)},[t]),r?(0,R.jsx)(`div`,{className:`hq-token-gate`,children:(0,R.jsxs)(`div`,{className:`hq-token-card`,children:[(0,R.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),(0,R.jsx)(`div`,{className:`hq-token-title`,children:`Auth status unavailable`}),(0,R.jsx)(`p`,{className:`hq-token-text`,children:r})]})}):t?(0,R.jsx)(`div`,{className:`hq-token-gate`,children:(0,R.jsxs)(`div`,{className:`hq-token-card`,children:[(0,R.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),a&&o?(0,R.jsxs)(`div`,{className:`hq-token-tabs`,children:[(0,R.jsx)(`button`,{type:`button`,className:`hq-token-tab`+(s===`token`?` active`:``),onClick:()=>c(`token`),children:`Browser token`}),(0,R.jsx)(`button`,{type:`button`,className:`hq-token-tab`+(s===`password`?` active`:``),onClick:()=>c(`password`),children:`Password`})]}):null,s===`token`||!o?(0,R.jsx)(Ct,{hadToken:e}):(0,R.jsx)(wt,{})]})}):(0,R.jsx)(`div`,{className:`hq-token-gate`,children:(0,R.jsxs)(`div`,{className:`hq-token-card`,children:[(0,R.jsx)(`div`,{className:`hq-brand`,children:`WrongStack HQ`}),(0,R.jsx)(`div`,{className:`hq-token-title`,children:`Checking auth mode…`})]})})}function Ct({hadToken:e}){let[t,n]=(0,w.useState)(``),r=()=>{let e=t.trim();e.length!==0&&(N(e),window.location.reload())};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`hq-token-title`,children:`Browser token required`}),(0,R.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,R.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,R.jsx)(`button`,{type:`button`,className:`hq-token-submit`,onClick:r,disabled:t.trim().length===0,children:`Connect`}),(0,R.jsxs)(`p`,{className:`hq-token-hint`,children:[`Manage tokens with `,(0,R.jsx)(`code`,{children:`wstack hq token list`}),` / `,(0,R.jsx)(`code`,{children:`wstack hq token create`}),` — they live in `,(0,R.jsx)(`code`,{children:`~/.wrongstack/hq/auth.json`}),`.`]})]})}function wt(){let[e,t]=(0,w.useState)(``),[n,r]=(0,w.useState)(null),[i,a]=(0,w.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}P(),window.location.reload()}catch{r(`Network error. Is the HQ server running?`),a(!1)}}};return(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(`div`,{className:`hq-token-title`,children:`Password required`}),(0,R.jsx)(`p`,{className:`hq-token-text`,children:`This HQ server is protected by a password. Enter it to open the dashboard.`}),n?(0,R.jsx)(`p`,{className:`hq-token-error`,children:n}):null,(0,R.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,R.jsx)(`button`,{type:`button`,className:`hq-token-submit`,onClick:()=>void o(),disabled:e.length===0||i,children:i?`Logging in…`:`Log in`}),(0,R.jsxs)(`p`,{className:`hq-token-hint`,children:[`Set or change the password with `,(0,R.jsx)(`code`,{children:`wstack --hq --password <secret>`}),`.`]})]})}var Tt=`modulepreload`,Et=function(e){return`/`+e},Dt={},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=Et(t,n),t=s(t),t in Dt)return;Dt[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`:Tt,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)})},Ot=360*60*1e3,X=[{id:`cockpit`,label:`Cockpit`,eyebrow:`Fleet overview`,description:`Health, active work, alerts, cost and command shortcuts.`,group:`Operations`,icon:c,shortcut:1},{id:`fleet`,label:`Fleet Map`,eyebrow:`Topology`,description:`Machines, projects, terminals and agents in one live graph.`,group:`Operations`,icon:t,shortcut:2},{id:`console`,label:`Live Console`,eyebrow:`Transcripts`,description:`Stream and inspect session or agent conversations.`,group:`Operations`,icon:d,shortcut:3},{id:`mailbox`,label:`Mailbox`,eyebrow:`Coordination`,description:`Cross-project messages, unread work and direct delivery.`,group:`Operations`,icon:ne,shortcut:4},{id:`kanban`,label:`Kanban`,eyebrow:`Project work`,description:`Read-only project boards synchronized across clones and machines.`,group:`Operations`,icon:g},{id:`alerts`,label:`Alerts`,eyebrow:`Attention`,description:`Active fleet warnings and alert transition history.`,group:`Intelligence`,icon:f,shortcut:5},{id:`cost`,label:`Cost`,eyebrow:`Economics`,description:`Project, provider and model spending distribution.`,group:`Intelligence`,icon:p,shortcut:6},{id:`trends`,label:`Trends`,eyebrow:`Telemetry`,description:`Cost, token and tool activity over time.`,group:`Intelligence`,icon:n,shortcut:7},{id:`brain`,label:`Brain`,eyebrow:`Decisions`,description:`Autonomous decisions, escalations and interventions.`,group:`Intelligence`,icon:u,shortcut:8},{id:`worktree`,label:`Worktrees`,eyebrow:`Workspace`,description:`Distributed branches, worktrees and ownership state.`,group:`System`,icon:le,shortcut:9},{id:`control`,label:`Control`,eyebrow:`Command plane`,description:`Steer, queue, broadcast and audit remote commands.`,group:`System`,icon:r,shortcut:0},{id:`settings`,label:`Security`,eyebrow:`Access control`,description:`Manage the HQ browser password, authentication and active credentials.`,group:`System`,icon:h}],kt=[`Operations`,`Intelligence`,`System`],At={cockpit:(0,w.lazy)(()=>Y(()=>import(`./cockpit-TAQtONc4.js`).then(e=>({default:e.CockpitView})),__vite__mapDeps([0,1,2,3]))),fleet:(0,w.lazy)(()=>Y(()=>import(`./fleet-map-NYSgfhOv.js`).then(e=>({default:e.FleetMapView})),__vite__mapDeps([4,1,2,5,3,6]))),console:(0,w.lazy)(()=>Y(()=>import(`./live-console-UTUFGuNq.js`).then(e=>({default:e.LiveConsoleView})),__vite__mapDeps([7,1,2,3,6,5]))),mailbox:(0,w.lazy)(()=>Y(()=>import(`./mailbox-CfZc7ihG.js`).then(e=>({default:e.MailboxView})),__vite__mapDeps([8,1,2,3,9]))),kanban:(0,w.lazy)(()=>Y(()=>import(`./kanban-DafBjWVp.js`).then(e=>({default:e.KanbanView})),__vite__mapDeps([10,1,2,3]))),cost:(0,w.lazy)(()=>Y(()=>import(`./cost-BdYMgqJF.js`).then(e=>({default:e.CostView})),__vite__mapDeps([11,1,2,3]))),brain:(0,w.lazy)(()=>Y(()=>import(`./brain-rtqqgiFJ.js`).then(e=>({default:e.BrainView})),__vite__mapDeps([12,1,2,3,9]))),worktree:(0,w.lazy)(()=>Y(()=>import(`./worktree-CJgUsABP.js`).then(e=>({default:e.WorktreeView})),__vite__mapDeps([13,1,2,3,9]))),trends:(0,w.lazy)(()=>Y(()=>import(`./trends-D8ophSBn.js`).then(e=>({default:e.TrendsView})),__vite__mapDeps([14,1,2,3]))),alerts:(0,w.lazy)(()=>Y(()=>import(`./alerts-BjEpUt0S.js`).then(e=>({default:e.AlertsView})),__vite__mapDeps([15,1,2,3]))),control:(0,w.lazy)(()=>Y(()=>import(`./control-RGqCysT8.js`).then(e=>({default:e.ControlView})),__vite__mapDeps([16,1,2,3]))),settings:(0,w.lazy)(()=>Y(()=>import(`./settings-7QqKSgKT.js`).then(e=>({default:e.SettingsView})),__vite__mapDeps([17,1,2,3])))};function jt(e){return X.find(t=>t.id===e)??X[0]}var Mt=class extends w.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,R.jsxs)(`div`,{className:`hq-view-error`,role:`alert`,children:[(0,R.jsx)(ce,{size:22}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:`This HQ surface stopped safely.`}),(0,R.jsx)(`p`,{children:this.state.error})]}),(0,R.jsxs)(`button`,{type:`button`,className:`hq-btn secondary`,onClick:()=>this.setState({error:null}),children:[(0,R.jsx)(y,{size:13}),`Retry view`]})]})}};function Nt(){let{snapshot:e,alerts:t,activeView:n,authRequired:r,connected:i}=z(O(e=>({snapshot:e.snapshot,alerts:e.alerts,activeView:e.activeView,authRequired:e.authRequired,connected:e.connected}))),[s,c]=(0,w.useState)(()=>typeof window>`u`||window.innerWidth>=1180),[l,u]=(0,w.useState)(null),[d,f]=(0,w.useState)(null),[ne,m]=(0,w.useState)(!1),{theme:h}=gt().appearance,g=(0,w.useRef)(!1),_=(0,w.useRef)(!1);if((0,w.useEffect)(()=>{_.current&&i===!1?L.getState().addToast(`Connection lost — reconnecting with backoff…`,`warning`,4e3):_.current&&g.current===!1&&i===!0&&L.getState().addToast(`Reconnected to HQ server`,`success`,3e3),i&&(_.current=!0),g.current=i},[i]),(0,w.useEffect)(()=>(document.documentElement.dataset.hqTheme=h,()=>{delete document.documentElement.dataset.hqTheme}),[h]),(0,w.useEffect)(()=>{let e=!1;return B(`/api/snapshot`).then(t=>{e||z.getState()._hydrateSnapshot(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,w.useEffect)(()=>{let e=!1;return B(`/api/auth/status`).then(t=>{e||f(t)}).catch(()=>{}),()=>{e=!0}},[]),(0,w.useEffect)(()=>{let e=!1,t=()=>{B(`/api/system/update`).then(t=>{e||u(t)}).catch(()=>{})};t();let n=window.setInterval(t,Ot);return()=>{e=!0,window.clearInterval(n)}},[]),(0,w.useEffect)(()=>{let e=e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),c(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(),z.getState().setActiveView(n.id));return}e.key===`Escape`&&s&&window.innerWidth<900&&c(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),r)return(0,R.jsx)(St,{hadToken:F()!==null});let v=e?.totals,ce=v?.unreadMailboxMessages??0,le=t.filter(e=>e.severity!==`info`).length,y=jt(n),de=y.icon,fe=At[n],pe=e=>{z.getState().setActiveView(e),window.innerWidth<900&&c(!1)},b=async()=>{m(!0);try{await I(`/api/logout`,{method:`POST`})}finally{P(),window.location.reload()}};return(0,R.jsxs)(`div`,{className:`hq-app`,"data-theme":h,"data-testid":`hq-workbench`,children:[(0,R.jsx)(`button`,{type:`button`,className:`hq-sidebar-scrim`,"data-open":s,"aria-label":`Close HQ navigation`,onClick:()=>c(!1)}),(0,R.jsxs)(`aside`,{className:`hq-secondary-nav`,"data-open":s,"aria-label":`HQ navigation`,children:[(0,R.jsxs)(`div`,{className:`hq-secondary-header`,children:[(0,R.jsxs)(`div`,{className:`hq-secondary-brand`,children:[(0,R.jsx)(`img`,{src:`/wrongstack.svg`,alt:``,"aria-hidden":`true`,draggable:!1}),(0,R.jsxs)(`div`,{className:`hq-secondary-copy`,children:[(0,R.jsx)(`span`,{className:`hq-secondary-eyebrow`,children:`Command center`}),(0,R.jsx)(`strong`,{children:`WrongStack HQ`})]})]}),(0,R.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-secondary-close`,"aria-label":`Collapse HQ navigation`,title:`Collapse navigation (Ctrl+B)`,onClick:()=>c(!1),children:(0,R.jsx)(a,{size:16})})]}),(0,R.jsx)(`div`,{className:`hq-secondary-scroll`,children:kt.map(e=>(0,R.jsxs)(`section`,{className:`hq-nav-group`,children:[(0,R.jsx)(`div`,{className:`hq-nav-group-label`,children:e}),X.filter(t=>t.group===e).map(e=>{let t=e.icon,r=e.id===`mailbox`?ce:e.id===`alerts`?le:0;return(0,R.jsxs)(`button`,{type:`button`,className:`hq-nav-item`,"data-active":n===e.id,"aria-current":n===e.id?`page`:void 0,onClick:()=>pe(e.id),children:[(0,R.jsx)(t,{size:15}),(0,R.jsx)(`span`,{children:e.label}),e.shortcut===void 0?null:(0,R.jsxs)(`kbd`,{children:[`Alt+`,e.shortcut]}),r>0?(0,R.jsx)(`span`,{className:`hq-nav-badge`,children:r}):null]},e.id)})]},e))}),(0,R.jsxs)(`div`,{className:`hq-secondary-footer`,children:[(0,R.jsxs)(`div`,{className:`hq-link-state`,"data-live":i,children:[(0,R.jsx)(`span`,{className:`hq-link-dot`}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:i?`Connected`:`Reconnecting`}),(0,R.jsxs)(`span`,{children:[v?.activeMachines??0,` machines · `,v?.activeClients??0,` clients`]})]})]}),(0,R.jsx)(`span`,{className:`hq-build-label`,children:`@wrongstack/webui-hq`})]})]}),(0,R.jsxs)(`section`,{className:`hq-workbench`,"data-update-available":l?.outdated===!0,children:[(0,R.jsxs)(`header`,{className:`hq-header`,children:[(0,R.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-sidebar-toggle`,"aria-label":s?`Collapse HQ navigation`:`Expand HQ navigation`,"aria-expanded":s,title:`Toggle navigation (Ctrl+B)`,onClick:()=>c(e=>!e),children:s?(0,R.jsx)(a,{size:17}):(0,R.jsx)(te,{size:17})}),(0,R.jsx)(`div`,{className:`hq-view-icon`,"aria-hidden":`true`,children:(0,R.jsx)(de,{size:18})}),(0,R.jsxs)(`div`,{className:`hq-view-identity`,children:[(0,R.jsx)(`span`,{children:y.eyebrow}),(0,R.jsx)(`h1`,{children:y.label}),(0,R.jsx)(`p`,{children:y.description})]}),(0,R.jsxs)(`div`,{className:`hq-top-metrics`,children:[(0,R.jsx)(Z,{icon:re,label:`Machines`,value:v?.activeMachines??0}),(0,R.jsx)(Z,{icon:se,label:`Agents`,value:v?.activeAgents??0}),(0,R.jsx)(Z,{icon:o,label:`Sessions`,value:v?.activeSessions??0}),(0,R.jsx)(Z,{icon:p,label:`Cost`,value:`$${(v?.totalCostUsd??0).toFixed(2)}`,accent:!0})]}),(0,R.jsxs)(`div`,{className:`hq-connection-pill`,"data-live":i,children:[i?(0,R.jsx)(ae,{size:13}):(0,R.jsx)(ie,{size:13}),i?`Live`:`Reconnecting`]}),(0,R.jsx)(`button`,{type:`button`,className:`hq-icon-button hq-theme-toggle`,"aria-label":`Switch to ${h===`dark`?`light`:`dark`} mode`,title:`Switch to ${h===`dark`?`light`:`dark`} mode`,onClick:()=>vt({theme:h===`dark`?`light`:`dark`}),children:h===`dark`?(0,R.jsx)(ue,{size:16}):(0,R.jsx)(oe,{size:16})}),d?.tokenMode||d?.passwordMode?(0,R.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:ne,onClick:()=>void b(),children:(0,R.jsx)(ee,{size:16})}):null]}),l?.outdated?(0,R.jsx)(Pt,{status:l}):null,(0,R.jsx)(`main`,{className:`hq-main`,id:`hq-main`,tabIndex:-1,children:(0,R.jsx)(Mt,{view:n,children:(0,R.jsx)(w.Suspense,{fallback:(0,R.jsx)(Ft,{label:y.label}),children:(0,R.jsx)(fe,{})})})})]}),(0,R.jsx)(at,{})]})}function Pt({status:e}){let[t,n]=(0,w.useState)(!1),r=async()=>{try{await navigator.clipboard.writeText(e.command),n(!0),window.setTimeout(()=>n(!1),1500)}catch{n(!1)}};return(0,R.jsxs)(`aside`,{className:`hq-update-notice`,role:`status`,"aria-live":`polite`,children:[(0,R.jsx)(m,{size:16,"aria-hidden":`true`}),(0,R.jsxs)(`div`,{children:[(0,R.jsx)(`strong`,{children:`WrongStack update available`}),(0,R.jsxs)(`span`,{children:[`v`,e.current,` → v`,e.latest,`. Run `,(0,R.jsx)(`code`,{children:e.command}),` in your terminal, then restart HQ.`]})]}),(0,R.jsxs)(`button`,{type:`button`,onClick:()=>void r(),title:`Copy update command`,children:[(0,R.jsx)(_,{size:13,"aria-hidden":`true`}),t?`Copied`:`Copy command`]})]})}function Z({icon:e,label:t,value:n,accent:r=!1}){return(0,R.jsxs)(`div`,{className:`hq-top-metric`,"data-accent":r,children:[(0,R.jsx)(e,{size:12}),(0,R.jsx)(`span`,{children:t}),(0,R.jsx)(`strong`,{children:n})]})}function Ft({label:e}){return(0,R.jsxs)(`div`,{className:`hq-view-loading`,role:`status`,children:[(0,R.jsx)(r,{size:18}),(0,R.jsxs)(`span`,{children:[`Loading `,e,`…`]})]})}var It=25e3,Lt=1e4,Rt=3e4,zt=class{ws=null;handlers=new Set;stateHandlers=new Set;reconnectAttempt=0;connectionState=me();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??It,this.heartbeatTimeoutMs=e?.heartbeatTimeoutMs??Lt,this.maxBackoffMs=e?.maxBackoffMs??Rt,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=F(),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.connectionState=he(this.connectionState),this.emitState(`connecting`);let e;try{e=new WebSocket(this.url)}catch{this.scheduleReconnect();return}this.ws=e,e.onopen=()=>{this.reconnectAttempt=0,this.connectionState=ge(this.connectionState),this.lastMessageAt=Date.now(),this.connectionState=_e(this.connectionState,this.lastMessageAt),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.connectionState=ve(this.connectionState),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;let e=ye(this.connectionState,{...b,maxReconnectAttempts:this.maxRetries,maxBackoffMs:this.maxBackoffMs,heartbeatIntervalMs:this.heartbeatIntervalMs,heartbeatTimeoutMs:this.heartbeatTimeoutMs,jitterRatio:.5});if(this.connectionState=e.state,this.reconnectAttempt=e.state.reconnectAttempt,!e.plan){this.emitState(`disconnected`);return}this.emitState(`reconnecting`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e.plan.delayMs)}get isHeartbeatTimedOut(){return this.ws===null||be(this.connectionState,{...b,heartbeatIntervalMs:this.heartbeatIntervalMs,heartbeatTimeoutMs: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 Bt(){return Q===null&&(Q=new zt,Q.connect()),Q}var $=document.getElementById(`root`);if($!==null){Je();let e=Bt();e.onStateChange(e=>{z.getState()._setConnected(e===`connected`)}),e.on(e=>{if(e.type===`hq.snapshot`){let t=Ve(e);t&&z.getState()._onSnapshot(t.snapshot)}else if(e.type===`hq.event`){let t=He(e);t&&z.getState()._onEvent(t.event)}else if(e.type===`hq.alert`){let t=Ue(e);t&&z.getState()._onAlert(t.alert)}else if(e.type===`hq.command_status`){let t=We(e);t&&z.getState()._onCommandStatus(t.command)}}),(0,Ge.createRoot)($).render((0,R.jsx)(w.StrictMode,{children:(0,R.jsx)(Nt,{})}))}export{gt as a,ct as c,P as d,O as f,xt as i,z as l,_t as n,B as o,yt as r,lt as s,bt as t,I as u};