useDeferredHookMessages.ts
hooks/useDeferredHookMessages.ts
No strong subsystem tag
47
Lines
1499
Bytes
1
Exports
2
Imports
10
Keywords
What this is
This page documents one file from the repository and includes its full source so you can read it without leaving the docs site.
Beginner explanation
This file is one piece of the larger system. Its name, directory, imports, and exports show where it fits. Start by reading the exports and related files first.
How it is used
Start from the exports list and related files. Those are the easiest clues for where this file fits into the system.
Expert explanation
Architecturally, this file intersects with general runtime concerns. It contains 47 lines, 2 detected imports, and 1 detected exports.
Important relationships
Detected exports
useDeferredHookMessages
Keywords
currentpromisependingrefmsgssetmessagesresolvedrefhookprevuserefmessage
Detected imports
react../types/message.js
Source notes
This page embeds the full file contents. Small or leaf files are still indexed honestly instead of being over-explained.
Full source
import { useCallback, useEffect, useRef } from 'react'
import type { HookResultMessage, Message } from '../types/message.js'
/**
* Manages deferred SessionStart hook messages so the REPL can render
* immediately instead of blocking on hook execution (~500ms).
*
* Hook messages are injected asynchronously when the promise resolves.
* Returns a callback that onSubmit should call before the first API
* request to ensure the model always sees hook context.
*/
export function useDeferredHookMessages(
pendingHookMessages: Promise<HookResultMessage[]> | undefined,
setMessages: (action: React.SetStateAction<Message[]>) => void,
): () => Promise<void> {
const pendingRef = useRef(pendingHookMessages ?? null)
const resolvedRef = useRef(!pendingHookMessages)
useEffect(() => {
const promise = pendingRef.current
if (!promise) return
let cancelled = false
promise.then(msgs => {
if (cancelled) return
resolvedRef.current = true
pendingRef.current = null
if (msgs.length > 0) {
setMessages(prev => [...msgs, ...prev])
}
})
return () => {
cancelled = true
}
}, [setMessages])
return useCallback(async () => {
if (resolvedRef.current || !pendingRef.current) return
const msgs = await pendingRef.current
if (resolvedRef.current) return
resolvedRef.current = true
pendingRef.current = null
if (msgs.length > 0) {
setMessages(prev => [...msgs, ...prev])
}
}, [setMessages])
}