/** * The OS-plane user store (API §2/§12.2). Provider-boot priming (`primeUser`) seeds * the per-Shell user cache so `useUser` is synchronous, and tracks OS-plane * availability: a missing/rejecting `shell.user.me` marks the plane down (the other * OS hooks then read idle) without failing boot. A never-primed shell falls back to * a lazy cold read that SUSPENDS on first use (§1.4). */ import type { Shell, UserNode } from '@astrale-os/shell' export type UserEntry = | { status: 'pending'; promise: Promise } | { status: 'resolved'; value: UserNode } | { status: 'rejected'; error: unknown } /** OS plane absent — throw descriptively, do NOT re-load (a reload just refails). */ | { status: 'unavailable'; error: unknown } export const userCache = new WeakMap() /** Shells whose OS plane could not be resolved at boot — OS hooks read idle. */ const osPlaneDown = new WeakSet() /** Is the OS plane (shell.user/spaces/apps) usable for this shell? */ export function isOsPlaneAvailable(shell: Shell): boolean { return !osPlaneDown.has(shell) } interface UserSurface { user?: { me?: () => Promise } } function osPlaneError(cause: unknown): Error { const detail = cause instanceof Error ? cause.message : String(cause) return new Error( `The OS plane is unavailable (useUser/useSpaces/useApps/useDomains): ` + `shell.user.me() could not resolve ` + `— the workspace/shell domain may not be installed for this identity. (${detail})`, ) } /** * Provider-boot priming (API §2). Best-effort: seed the user cache so `useUser` * is synchronous, or mark the OS plane down. NEVER throws — boot must not fail on * a missing OS plane. */ export async function primeUser(shell: Shell): Promise { const me = (shell as unknown as UserSurface).user?.me if (typeof me !== 'function') { osPlaneDown.add(shell) userCache.set(shell, { status: 'unavailable', error: osPlaneError('shell.user.me is not a function'), }) return } try { const value = await me.call((shell as unknown as UserSurface).user) osPlaneDown.delete(shell) userCache.set(shell, { status: 'resolved', value }) } catch (error) { osPlaneDown.add(shell) userCache.set(shell, { status: 'unavailable', error: osPlaneError(error) }) } } /** Kick off `me()` lazily (a shell that was never primed) and cache a suspense cell. */ export function loadUser(shell: Shell): UserEntry { const cell: { status: 'pending' | 'resolved' | 'rejected' promise?: Promise value?: UserNode error?: unknown } = { status: 'pending' } cell.promise = shell.user.me().then( (value) => { cell.status = 'resolved' cell.value = value }, (error: unknown) => { cell.status = 'rejected' cell.error = error }, ) const entry = cell as unknown as UserEntry userCache.set(shell, entry) return entry }