import type { Shell, ShellConfig } from '@astrale-os/shell' import type { ReactElement, ReactNode } from 'react' import { createShell } from '@astrale-os/shell' import { useCallback, useEffect, useReducer, useRef, useState } from 'react' import type { BootRef } from './boot/ownership.js' import type { SelfNode } from './session.context.js' import { primeUser } from '../application/user/user.store.js' import { GraphContext } from '../graph/graph.context.js' import { resolveGraphStoreScope, retainStore, storeFor } from '../graph/store.js' import { configIdentity, isShellConfig, resolveSelf } from './boot/boot.js' import { cancelTeardown, disposeShell, scheduleTeardown } from './boot/ownership.js' import { bootReducer, INITIAL_BOOT } from './boot/status.js' import { connectionStore } from './connection/connection.store.js' import { ShellContext } from './session.context.js' export type ShellError = { readonly kind: 'connection'; readonly error: unknown } export interface ShellProviderProps { /** A Shell configuration or an already-constructed Shell capability. */ readonly config: ShellConfig | Shell readonly fallback?: ReactNode readonly errorFallback?: (error: unknown, retry: () => void) => ReactNode readonly onError?: (error: ShellError) => void readonly children: ReactNode } /** Own and initialize exactly one Shell for a React subtree. */ export function ShellProvider(props: ShellProviderProps): ReactElement | null { const { config, fallback, errorFallback, onError, children } = props const [state, dispatch] = useReducer(bootReducer, INITIAL_BOOT) const [attempt, setAttempt] = useState(0) const bootRef = useRef({ key: null, shell: null, generation: 0 }) const configRef = useRef(config) configRef.current = config const onErrorRef = useRef(onError) onErrorRef.current = onError const configKey = configIdentity(config) const startBoot = useCallback((ref: BootRef) => { const generation = (ref.generation += 1) dispatch({ type: 'connecting' }) let shell: Shell try { const current = configRef.current shell = isShellConfig(current) ? createShell(current) : current } catch (error) { dispatch({ type: 'error', error }) onErrorRef.current?.({ kind: 'connection', error }) return } ref.shell = shell void (async () => { try { await shell.init() if (generation !== ref.generation) return const self: SelfNode | null = await resolveSelf(shell) if (generation !== ref.generation) return await primeUser(shell) if (generation !== ref.generation) return const storeScope = await resolveGraphStoreScope(shell, self) if (generation !== ref.generation) return const graph = storeFor(shell, storeScope) dispatch({ type: 'ready', runtime: { shell, self, storeScope, store: graph.store, ownsStore: graph.owned }, }) } catch (error) { if (generation !== ref.generation) return dispatch({ type: 'error', error }) onErrorRef.current?.({ kind: 'connection', error }) } })() }, []) useEffect(() => { const ref = bootRef.current const current = configRef.current const adopting = isShellConfig(current) ? ref.shell : current if (adopting !== null) cancelTeardown(adopting) if (ref.key !== configKey) { if (ref.shell !== null) { cancelTeardown(ref.shell) disposeShell(ref.shell) } ref.key = configKey ref.shell = null startBoot(ref) } return () => { if (ref.shell !== null) scheduleTeardown(ref.shell, ref) else ref.key = null } }, [configKey, attempt, startBoot]) const retry = useCallback(() => { const ref = bootRef.current ref.generation += 1 if (ref.shell !== null) { disposeShell(ref.shell) ref.shell = null } ref.key = null dispatch({ type: 'connecting' }) setAttempt((value) => value + 1) }, []) const shell = state.runtime?.shell ?? null useEffect(() => { if (shell !== null) connectionStore(shell).setRetry(retry) }, [shell, retry]) const store = state.runtime?.store ?? null const storeScope = state.runtime?.storeScope ?? null useEffect(() => { if (shell === null || store === null || storeScope === null) return return retainStore(storeFor(shell, storeScope)) }, [shell, store, storeScope]) if (state.status === 'error') { if (errorFallback !== undefined) return <>{errorFallback(state.error, retry)} throw state.error } if (state.status !== 'ready' || state.runtime === null) { return fallback === undefined ? null : <>{fallback} } return ( {children} ) }