/** * The connection store (API §3, rule 3). ONE per Shell — the provider owns it and * registers its `retry`; `useConnection` reads it via `useSyncExternalStore` so * connection churn re-renders only its subscribers. `status`/`seq` are a pinned * stub ('ready'/0) until the transport-status + result-`seq` feed lands (G6). */ import type { Shell } from '@astrale-os/shell' export type ConnectionStatus = 'connecting' | 'ready' | 'reconnecting' | 'error' /** Transport + memory-journal status for the subtree (API §3). */ export interface ConnectionValue { readonly status: ConnectionStatus readonly error: unknown readonly seq: number retry(): void } export interface ConnectionStore { subscribe(cb: () => void): () => void getSnapshot(): ConnectionValue /** The provider registers its boot-retry here; a change re-stamps the snapshot. */ setRetry(retry: () => void): void } const NOOP_RETRY = (): void => {} function createConnectionStore(): ConnectionStore { const listeners = new Set<() => void>() let retry: () => void = NOOP_RETRY let snapshot: ConnectionValue = { status: 'ready', error: undefined, seq: 0, retry } return { subscribe(cb) { listeners.add(cb) return () => listeners.delete(cb) }, getSnapshot: () => snapshot, setRetry(next) { if (next === retry) return retry = next snapshot = { status: snapshot.status, error: snapshot.error, seq: snapshot.seq, retry } for (const l of listeners) l() }, } } const stores = new WeakMap() /** The one connection store for a Shell (created on first touch). */ export function connectionStore(shell: Shell): ConnectionStore { let s = stores.get(shell) if (s === undefined) { s = createConnectionStore() stores.set(shell, s) } return s }