import { createContext, useContext, useEffect, useState, useSyncExternalStore, type ReactNode } from 'react' import { useQuery } from '@tanstack/react-query' import { hostUsageSchema, type HostUsage } from '@open-mercato/cezar-api-client' import { getWorkspaceHostUsage } from './client' import { useHealth, workspaceQueryKeys } from './queries' import { effectiveHostView } from '@/lib/host-effective' import { useIsDesktop } from '@/lib/use-desktop' import { subscribeTopic } from './ws' /** * The Machine card's and the sidebar widget's data layer (spec * `.ai/specs/2026-09-20-host-telemetry-sidebar-widget.md`, Phase 2). * * One per-app store, two readers and three writers, and exactly one writer is live per viewport: * * - **root** (`useHostSubscription`, local && `md` and up) subscribes for the whole session and * feeds the store, so the widget and the card read one sample and one history. * - **card** (`useHostUsageSubscription`, gated `enabled: !useIsDesktop()` by the card) stays the * ` => new Promise((resolve, reject) => { if (signal?.aborted) { reject(new DOMException('Aborted', 'AbortError')) return } const onAbort = (): void => { clearTimeout(timer) reject(new DOMException('Aborted', 'AbortError')) } const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort) resolve() }, ms) signal?.addEventListener('abort', onAbort, { once: true }) }) /** * The remote read pair. The second read exists only to turn "no CPU baseline yet" into a real * ~2 s delta; when the first answer already carries `cpuPct` it is the whole read. * * `@internal` — exported for the abort test; the app's read path is `useHostUsageRoute()`. */ export async function readWorkspaceHostUsage( signal?: AbortSignal, ): Promise { const first = await getWorkspaceHostUsage({ signal }) if (first.cpuPct !== undefined) return first await delay(HOST_USAGE_WARMUP_MS, signal) return getWorkspaceHostUsage({ signal }) } /** * Which transport this cockpit has: `undefined` until health (the authenticated bootstrap) has * answered. The card uses it for its `live` / `last known` label; the writers use it to pick push * or fetch. Gating on health is deliberate — a local cockpit must not open a socket before the * deployment mode is known (the same rule `useHealthSubscription` follows). */ export function useHostTransport(): 'local' | 'remote' | undefined { const health = useHealth().data if (health === undefined) return undefined return health.capabilities?.localHandoff === true ? 'local' : 'remote' } // ---- the store --------------------------------------------------------------------------- /** 30 points × the server's 2 s cadence = the 60 s sparkline. */ export const HOST_HISTORY_LENGTH = 30 /** * A gap longer than this is not a line: a reconnection that skipped more than four frames * restarts the sparkline instead of drawing a segment nothing measured. */ export const HOST_HISTORY_GAP_MS = 8_000 export type HostUsageWriter = 'root' | 'card' | 'route' export interface HostUsagePoint { sampledAt: string /** The CLIENT receipt stamp, kept with the point: the staleness clock reads receipt, not the * server's own `sampledAt` (a clock-skewed server must not be able to freeze the readout). */ receivedAt: number cpuPct: number } export interface HostUsageState { latest?: HostUsage /** Client receipt stamp of the latest sample — the widget's `stale` clock. */ lastFrameAt?: number history: HostUsagePoint[] /** * The hub REFUSED the `host` topic for this origin (`{"type":"error","topic":"host"}`, the ws * upgrade guard's trust rule) rather than staying quiet. The card must say what happened and * read the authenticated route instead of showing `sampling…` forever. */ topicUnavailable?: boolean } export interface HostUsageStore { subscribe(listener: () => void): () => void /** The whole state BY REFERENCE: `useSyncExternalStore` needs identity stability between * pushes, and a selector then only re-renders the component whose slice changed. */ get(): HostUsageState push(sample: HostUsage, receivedAt: number, writer: HostUsageWriter): void /** The hub refused this origin's `host` subscription - see `HostUsageState.topicUnavailable`. */ markTopicUnavailable(): void /** For tests: forget every sample and the writer, as a fresh mount would. */ reset(): void } /** One shared empty state, so an idle cockpit hands every reader the same reference. */ const EMPTY_HOST_HISTORY: HostUsagePoint[] = Object.freeze([]) as unknown as HostUsagePoint[] export const EMPTY_HOST_USAGE_STATE: HostUsageState = Object.freeze({ history: EMPTY_HOST_HISTORY, }) export function createHostUsageStore(): HostUsageStore { let state: HostUsageState = EMPTY_HOST_USAGE_STATE let writer: HostUsageWriter | undefined const listeners = new Set<() => void>() const notify = (): void => { for (const listener of listeners) listener() } // A hidden tab renders nothing anyone sees, and a throttled one can be handed a backlog of // frames in one burst - each a sync commit (telemetry 21762d83). Fold them into the state and // re-render once, on return. let deferred = false const onVisible = (): void => { if (document.visibilityState === 'hidden') return document.removeEventListener('visibilitychange', onVisible) deferred = false notify() } const notifyFrame = (): void => { if (typeof document === 'undefined' || document.visibilityState !== 'hidden') return notify() if (deferred) return deferred = true document.addEventListener('visibilitychange', onVisible) } return { subscribe(listener) { listeners.add(listener) return () => listeners.delete(listener) }, get: () => state, push(sample, receivedAt, nextWriter) { const previous = state // The writer change is decided BEFORE the dedupe below: a new writer whose first frame // replays the sample the old writer already delivered is still a change of owner, and the // spec's rule is that a writer change clears the line. const writerChanged = writer !== undefined && writer !== nextWriter writer = nextWriter // A replayed snapshot (re-subscribe, reconnect, a second writer's identical view) must not // add a second point for one server sample. const replay = previous.latest?.sampledAt === sample.sampledAt if ( replay && previous.latest === sample && previous.lastFrameAt === receivedAt && !writerChanged ) { return } const lastPoint = previous.history[previous.history.length - 1] const gap = !replay && lastPoint !== undefined && Date.parse(sample.sampledAt) - Date.parse(lastPoint.sampledAt) > HOST_HISTORY_GAP_MS // The line belongs to the transport that can honestly draw one: a local cockpit receives a // point every 2 s, while the route writer answers on mount and on a reconnect/visibility // reconcile. Plotting those sparse points on a 2 s-scaled line (and announcing their count // as seconds) would state a rate nobody measured, so remote keeps the instantaneous bar and // no chart at all. const charted = nextWriter !== 'route' const base = writerChanged || gap || !charted ? [] : previous.history // The ring carries the EFFECTIVE percentage, the same number the card and the widget render: // a line of host-wide utilization under an effective core count is the scope mix the spec // forbids, and the two surfaces must never disagree about which series they are drawing. const effectiveCpuPct = effectiveHostView(sample).cpuPct // One server instant is one point in the KEPT history: after a writer change or a gap the // arriving sample legitimately starts the new line, a plain replay never doubles it. const lastKept = base[base.length - 1] const appendPoint = charted && effectiveCpuPct !== undefined && lastKept?.sampledAt !== sample.sampledAt const history = appendPoint ? [...base, { sampledAt: sample.sampledAt, receivedAt, cpuPct: effectiveCpuPct }].slice( -HOST_HISTORY_LENGTH, ) : base state = { latest: sample, lastFrameAt: receivedAt, history, // A refusal is a fact about the ORIGIN, not about one sample: the route-fallback pushes // (the very path the refusal switches on) must not clear it. ...(previous.topicUnavailable === true ? { topicUnavailable: true } : {}), } notifyFrame() }, markTopicUnavailable() { if (state.topicUnavailable === true) return state = { ...state, topicUnavailable: true } notify() }, reset() { writer = undefined state = EMPTY_HOST_USAGE_STATE notify() }, } } const HostUsageContext = createContext(null) /** * Owns the one store instance and hosts the root writer. Mounted once, above both readers — the * sidebar widget (through the shell) and the Settings card. */ export function HostUsageProvider({ children }: { children: ReactNode }) { const [store] = useState(createHostUsageStore) return ( {children} ) } /** Renders nothing; the session-long subscription lives here so it survives route changes. */ function HostUsageRootWriter() { useHostSubscription() return null } export function useHostUsageStore(): HostUsageStore | null { return useContext(HostUsageContext) } const noopSubscribe = (): (() => void) => () => undefined /** * The latest sample. Empty outside a provider rather than a throw: "no samples yet" is a real, * expected state, and a component rendered without the provider (a unit test of the card alone) * sees the same nothing it would see before the first frame. */ export function useHostUsage(): HostUsage | undefined { const store = useContext(HostUsageContext) return useSyncExternalStore( store ? store.subscribe : noopSubscribe, () => store?.get().latest, () => undefined, ) } /** The 60 s CPU ring. Same reference between pushes, so a sparkline only re-renders on a push. */ export function useHostHistory(): HostUsagePoint[] { const store = useContext(HostUsageContext) return useSyncExternalStore( store ? store.subscribe : noopSubscribe, () => store?.get().history ?? EMPTY_HOST_USAGE_STATE.history, () => EMPTY_HOST_USAGE_STATE.history, ) } /** When the client last received a sample — the `stale` clock's origin. */ export function useHostLastFrameAt(): number | undefined { const store = useContext(HostUsageContext) return useSyncExternalStore( store ? store.subscribe : noopSubscribe, () => store?.get().lastFrameAt, () => undefined, ) } /** * Whether this cockpit's `host` subscription was REFUSED by the hub (trust rule, not a quiet * socket). The card uses it to stop claiming `live` and to explain the fallback. */ export function useHostTopicUnavailable(): boolean { const store = useContext(HostUsageContext) return useSyncExternalStore( store ? store.subscribe : noopSubscribe, () => store?.get().topicUnavailable === true, () => false, ) } /** * The age of the MEASUREMENT, ticking once every second while a reader is mounted. * * `sampledAt` is the server's own stamp for the sample, so an answer served from the sampler's * small cache cannot read as fresher than it is - and the ticking clock is what keeps a cockpit * that stopped receiving anything (a dead socket, a stalled route read, a server that went away) * counting up instead of freezing at its last fresh-looking value. The receipt stamp is the * fallback when the server stamp is unreadable, and a slightly ahead server clock clamps at zero. * This is NOT the widget's `stale` clock, which stays receipt-based on purpose: staleness means * "nothing is arriving", and that must not depend on the server's clock. */ export function useHostSampleAgeSeconds(): number | undefined { const sample = useHostUsage() const lastFrameAt = useHostLastFrameAt() const [now, setNow] = useState(() => Date.now()) useEffect(() => { const timer = setInterval(() => setNow(Date.now()), 1_000) return () => clearInterval(timer) }, []) if (sample === undefined) return undefined const sampledAtMs = Date.parse(sample.sampledAt) if (!Number.isNaN(sampledAtMs)) return Math.max(0, Math.round((now - sampledAtMs) / 1_000)) return lastFrameAt === undefined ? undefined : Math.max(0, Math.round((now - lastFrameAt) / 1_000)) } // ---- the writers ------------------------------------------------------------------------- /** * One local `host` subscription that folds every pushed frame into the store. The caller decides * the gate; the transport gate (local only) is shared, so a remote cockpit can never open a * socket through either writer. */ function useHostFrames(writer: HostUsageWriter, enabled: boolean): void { const store = useContext(HostUsageContext) const transport = useHostTransport() const topicUnavailable = useHostTopicUnavailable() useEffect(() => { if (!store || !enabled || transport !== 'local') return return subscribeTopic( 'host', (data) => { const parsed = hostUsageSchema.safeParse(data) if (parsed.success) store.push(parsed.data, Date.now(), writer) }, // A refused subscription answers with `{type:'error', topic:'host'}` and then silence. That // is not `sampling…`: record it, so the card can name the reason and fall back to the // authenticated route (a dev-server proxy whose page origin differs from the server's // authority is the known case - the hub's trust rule is same-origin by design). () => store.markTopicUnavailable(), ) }, [store, enabled, transport, writer]) // A refused topic is not the end of live data (#1363): the same writer polls the authenticated // route at the sampler's cadence, and each read keeps the server's timer warm for the next. const polled = useQuery({ queryKey: [...workspaceQueryKeys.hostUsage, 'poll'], queryFn: ({ signal }) => getWorkspaceHostUsage({ signal }), enabled: store !== null && enabled && transport === 'local' && topicUnavailable, refetchInterval: HOST_USAGE_POLL_MS, staleTime: 0, retry: false, }) const polledSample = polled.data useEffect(() => { if (!store || polledSample === undefined) return store.push(polledSample, Date.now(), writer) }, [store, polledSample, writer]) } /** * The root writer: local cockpits at `md` and up, for the whole session, because the sidebar * widget is visible the whole session. Below `md` the widget is unmounted and the card's own * view-scoped subscription (below) is the demand, which is what keeps a phone from paying for a * sampler it cannot see. */ export function useHostSubscription(): void { useHostFrames('root', useIsDesktop()) } /** * The card's view-scoped writer, kept from v1 as the ` readWorkspaceHostUsage(signal), // Remote only: a LOCAL cockpit whose `host` topic the hub refused polls the route from its // live writer instead (`useHostFrames`), which also keeps the sidebar glance current. enabled: transport === 'remote', staleTime: 0, retry: false, }) const data = query.data useEffect(() => { if (!store || data === undefined) return store.push(data, Date.now(), 'route') }, [store, data]) return query }