import type { IntentMessage, IntentRegistry } from '@astrale-os/shell' /** * useIntent (API §11) — subscribe ONE handler to inbound intents (post-middleware, * via shell.onIntent) with the REAL sender windowId and an exactly-once, * unmount-safe `ctx.reply`. The subscription identity is independent of the * handler closure (latest-handler ref), so re-renders never re-register. Reply * obligations are tracked per sender window so a child close drops ours before a * late async handler can aim a reply at a gone counterparty. */ import { useEffect, useRef } from 'react' import type { IntentPayload, IntentReply } from './envelope.js' import { useShell } from '../session/shell.hook.js' import { NOOP } from './envelope.js' import { sendReply } from './reply.js' /** Delivery context passed alongside an inbound intent's payload. */ export interface IntentCtx { /** REAL source windowId; the `''` sentinel for a parent-delivered intent. */ readonly sender: string /** Reply to the sender's pending request — exactly-once; dropped if it died. */ reply(result: IntentReply): void } /** * Subscribe `handler` to inbound `name` intents. `ctx.sender` is the REAL * windowId (the channel-authenticated id, or `''` upstream); `ctx.reply` * answers a correlated request once. */ export function useIntent( name: K, handler: (payload: IntentPayload, ctx: IntentCtx) => void | Promise, ): void { const shell = useShell() const handlerRef = useRef(handler) handlerRef.current = handler useEffect(() => { let alive = true // Open reply obligations by sender window, so a child close drops ours // before a late async handler can aim a reply at a gone counterparty. const bySender = new Map void>>() const track = (sender: string, drop: () => void): (() => void) => { let set = bySender.get(sender) if (set === undefined) { set = new Set() bySender.set(sender, set) } set.add(drop) return () => set.delete(drop) } const offClose = shell.children.onClose((windowId) => { const set = bySender.get(windowId) if (set === undefined) return for (const drop of set) drop() bySender.delete(windowId) }) const off = shell.onIntent(name, (message: IntentMessage) => { const { payload, correlationId } = message.envelope const sender = message.envelope.sender.windowId let settled = false const untrack = correlationId === undefined ? NOOP : track(sender, () => { settled = true }) const ctx: IntentCtx = { sender, reply(result) { if (settled || !alive) return settled = true untrack() if (correlationId === undefined) return sendReply(shell, sender, correlationId, result) }, } void Promise.resolve(handlerRef.current(payload as IntentPayload, ctx)) .catch(NOOP) .finally(untrack) }) return () => { alive = false off() offClose() } }, [shell, name]) }