import type { IntentRegistry, RequestIntentOptions } from '@astrale-os/shell' import { requestChildIntent, requestIntent } from '@astrale-os/shell' import { useCallback, useEffect, useRef } from 'react' import type { IntentPayload, IntentReply } from './envelope.js' import { useShell } from '../session/shell.hook.js' import { resolveIntentTarget } from './resolve-intent-target.js' /** Typed request sender backed exclusively by Shell's core correlation implementation. */ export interface SendIntent { ( name: K, payload: IntentPayload, options?: RequestIntentOptions & { readonly to?: 'parent' | string }, ): Promise> } export function useSendIntent(): SendIntent { const shell = useShell() const lifetime = useRef(new AbortController()) useEffect(() => { const controller = lifetime.current.signal.aborted ? new AbortController() : lifetime.current lifetime.current = controller return () => controller.abort(new Error('Intent requester unmounted')) }, []) return useCallback( ( name: K, payload: IntentPayload, options?: RequestIntentOptions & { readonly to?: 'parent' | string }, ): Promise> => { const target = resolveIntentTarget(shell, options?.to) if (target.kind === 'invalid') { return Promise.reject(new Error(`useSendIntent: ${target.reason}`)) } const signal = options?.signal === undefined ? lifetime.current.signal : AbortSignal.any([lifetime.current.signal, options.signal]) const requestOptions: RequestIntentOptions = { signal, ...(options?.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }), } return target.kind === 'parent' ? requestIntent(shell.parent!, name, payload, requestOptions) : requestChildIntent(shell.children, target.windowId, name, payload, requestOptions) }, [shell], ) }