import type { Call } from '@astrale-os/sdk/client' import type { SessionRequestOptions } from '@astrale-os/sdk/client/session' import type { Value } from '@astrale-os/sdk/value' import type { KernelClient } from '@astrale-os/shell' import { useCallback, useEffect, useReducer, useRef } from 'react' import { useSessionKernel } from '../../auth/session-kernel.js' export type KernelStream = Awaited> export type StreamItem = Value export type CallAuthor = Call | ((...args: A) => Call) export interface StreamOptions extends SessionRequestOptions { readonly onChunk?: (chunk: T) => void } export interface StreamHandle { start(...args: A): Promise readonly chunks: readonly T[] readonly last: T | null readonly streaming: boolean readonly error: unknown cancel(): void } interface Snapshot { readonly chunks: readonly T[] readonly last: T | null readonly streaming: boolean readonly error: unknown } type Event = | { readonly type: 'start' } | { readonly type: 'chunk'; readonly value: T } | { readonly type: 'end' } | { readonly type: 'error'; readonly error: unknown } | { readonly type: 'cancel' } function reducer(state: Snapshot, event: Event): Snapshot { switch (event.type) { case 'start': return { chunks: [], last: null, streaming: true, error: undefined } case 'chunk': return { chunks: [...state.chunks, event.value], last: event.value, streaming: true, error: undefined, } case 'end': case 'cancel': return { ...state, streaming: false } case 'error': return { ...state, streaming: false, error: event.error } } } export function useStream( author: CallAuthor | null, options?: StreamOptions, ): StreamHandle { const kernel = useSessionKernel() const kernelRef = useRef(kernel) kernelRef.current = kernel const authorRef = useRef(author) authorRef.current = author const optionsRef = useRef(options) optionsRef.current = options const [snapshot, dispatch] = useReducer(reducer, { chunks: [], last: null, streaming: false, error: undefined, }) const runId = useRef(0) const controller = useRef(null) const cancel = useCallback(() => { runId.current += 1 controller.current?.abort() controller.current = null dispatch({ type: 'cancel' }) }, []) useEffect(() => cancel, [cancel]) const start = useCallback( async (...args: A): Promise => { const current = authorRef.current if (current === null) throw new Error('useStream: idle handle started') cancel() const id = ++runId.current const abort = new AbortController() controller.current = abort dispatch({ type: 'start' }) const call = typeof current === 'function' ? current(...args) : current try { const { onChunk: _onChunk, ...requestOptions } = optionsRef.current ?? {} const stream = await kernelRef.current.stream(call, { ...requestOptions, signal: abort.signal, }) for await (const chunk of stream) { if (id !== runId.current) return dispatch({ type: 'chunk', value: chunk }) optionsRef.current?.onChunk?.(chunk) } if (id === runId.current) dispatch({ type: 'end' }) } catch (error) { if (id !== runId.current) return dispatch({ type: 'error', error }) throw error } finally { if (id === runId.current) controller.current = null } }, [cancel], ) return { start, cancel, ...snapshot } }