"use client"; /** * @module @trigger.dev/sdk/chat/react * * React hooks for AI SDK chat transport integration. * Use alongside `@trigger.dev/sdk/chat` for a type-safe, ergonomic DX. * * @example * ```tsx * import { useChat } from "@ai-sdk/react"; * import { useTriggerChatTransport } from "@trigger.dev/sdk/chat/react"; * import type { chat } from "@/trigger/chat"; * * function Chat() { * const transport = useTriggerChatTransport({ * task: "ai-chat", * accessToken: ({ chatId }) => fetchToken(chatId), * }); * * const { messages, sendMessage } = useChat({ transport }); * } * ``` */ import { useCallback, useEffect, useRef, useState } from "react"; import { TriggerChatTransport, type TriggerChatTransportOptions } from "./chat.js"; import type { AnyTask, TaskIdentifier } from "@trigger.dev/core/v3"; import { PENDING_MESSAGE_INJECTED_TYPE, type InferChatClientData, type InferChatUIMessage, } from "./ai-shared.js"; import type { UIMessage, ChatRequestOptions } from "ai"; import { createSubAgentMessages, type SubAgentMessages, type SubAgentMessagesOptions, } from "./subAgentStream.js"; /** * Options for `useTriggerChatTransport`, with a type-safe `task` field. * * Pass a task type parameter to get compile-time validation of the task ID: * ```ts * useTriggerChatTransport({ task: "my-task", ... }) * ``` */ export type UseTriggerChatTransportOptions = Omit< TriggerChatTransportOptions>, "task" > & { /** The task ID. Strongly typed when a task type parameter is provided. */ task: TaskIdentifier; }; export type { InferChatUIMessage }; export type { ChatTransportEvent, ChatTransportSendSource } from "./chat.js"; /** What a `chat.createLoadTranscriptAction` action returns, as `useLoadTranscript` reads it. */ export type LoadTranscriptResult = { messages: TUIMessage[]; cursors?: { lastOutEventId?: string; lastInEventId?: string }; nextCursor?: string; }; export type UseLoadTranscriptOptions = { /** * When given, the transport's resume cursor for this chat is seeded from * the loaded transcript, so the live subscription opens just past the * persisted history instead of replaying it. Only applies once the * transport knows the session (from `sessions` or after `start`). */ transport?: TriggerChatTransport; /** Page size passed to the action. */ limit?: number; }; /** * Move the transport's resume cursor for `chatId` to the transcript's * `lastOutEventId`, so the live subscription opens just past the persisted * history. Applied to the session now if it exists, otherwise held by the * transport until the session is created, so a load that resolves before the * session exists still moves the cursor. The `.in` cursor goes with it, so the * transport can tell whether the transcript was saved after a send it still has * outstanding was answered. A no-op when the transcript carries no `.out` * cursor. Returns whether a cursor was provided. */ export function seedTranscriptCursor( transport: Pick, chatId: string, cursors: { lastOutEventId?: string; lastInEventId?: string } | undefined ): boolean { const lastEventId = cursors?.lastOutEventId; if (!lastEventId) return false; transport.seedResumeCursor(chatId, lastEventId, cursors?.lastInEventId); return true; } /** * Load a conversation's history through a server action created with * `chat.createLoadTranscriptAction`, for rendering before the chat connects. * * Re-runs when `chatId` changes. Pass `undefined` to load nothing. * * @example * ```tsx * const { messages, isLoading } = useLoadTranscript(chatId, loadTranscript, { transport }); * if (isLoading) return ; * return ; * ``` */ export function useLoadTranscript( chatId: string | undefined, load: (params: { chatId: string; limit?: number }) => Promise>, options?: UseLoadTranscriptOptions ): { messages: TUIMessage[]; isLoading: boolean; error: Error | undefined; /** The id to pass as `before` to the action for the page before this one. */ nextCursor: string | undefined; } { const [state, setState] = useState<{ chatId: string | undefined; messages: TUIMessage[]; isLoading: boolean; error: Error | undefined; nextCursor: string | undefined; }>({ chatId, messages: [], isLoading: chatId !== undefined, error: undefined, nextCursor: undefined, }); const loadRef = useRef(load); loadRef.current = load; const transportRef = useRef(options?.transport); transportRef.current = options?.transport; const limit = options?.limit; useEffect(() => { if (chatId === undefined) { setState({ chatId, messages: [], isLoading: false, error: undefined, nextCursor: undefined }); return; } let cancelled = false; setState({ chatId, messages: [], isLoading: true, error: undefined, nextCursor: undefined }); loadRef .current({ chatId, ...(limit !== undefined ? { limit } : {}) }) .then((result) => { if (cancelled) return; if (transportRef.current) { seedTranscriptCursor(transportRef.current, chatId, result.cursors); } setState({ chatId, messages: result.messages, isLoading: false, error: undefined, nextCursor: result.nextCursor, }); }) .catch((cause: unknown) => { if (cancelled) return; const error = cause instanceof Error ? cause : new Error(String(cause)); setState({ chatId, messages: [], isLoading: false, error, nextCursor: undefined }); }); return () => { cancelled = true; }; }, [chatId, limit]); return { messages: state.chatId === chatId ? state.messages : [], isLoading: state.chatId === chatId ? state.isLoading : chatId !== undefined, error: state.chatId === chatId ? state.error : undefined, nextCursor: state.chatId === chatId ? state.nextCursor : undefined, }; } /** * React hook that creates and memoizes a `TriggerChatTransport` instance. * * The transport is created once on first render and reused for the lifetime * of the component. This avoids the need for `useMemo` and ensures the * transport's internal session state (run IDs, lastEventId, etc.) * is preserved across re-renders. * * For dynamic access tokens, pass a function — it will be called on each * request without needing to recreate the transport. * * The `onSessionChange` callback is kept in a ref so the transport always * calls the latest version without needing to be recreated. * * @example * ```tsx * import { useChat } from "@ai-sdk/react"; * import { useTriggerChatTransport } from "@trigger.dev/sdk/chat/react"; * import type { chat } from "@/trigger/chat"; * * function Chat() { * const transport = useTriggerChatTransport({ * task: "ai-chat", * accessToken: ({ chatId }) => fetchToken(chatId), * }); * * const { messages, sendMessage } = useChat({ transport }); * } * ``` */ export function useTriggerChatTransport( options: UseTriggerChatTransportOptions ): TriggerChatTransport { const ref = useRef(null); if (ref.current === null) { ref.current = new TriggerChatTransport(options as TriggerChatTransportOptions); } // Keep callbacks up to date without recreating the transport. const { onSessionChange, clientData, onEvent, accessToken, startSession, fetch: fetchOverride, } = options; useEffect(() => { ref.current?.setOnSessionChange(onSessionChange); }, [onSessionChange]); useEffect(() => { ref.current?.setOnEvent(onEvent); }, [onEvent]); // Keep `clientData` up to date so the transport's per-turn merge and // `startSession` callback both see the latest value without // reconstructing the transport. useEffect(() => { ref.current?.setClientData(clientData as Record | undefined); }, [clientData]); // Same for the request-time callbacks: a host that closes over a changing // endpoint (a dashboard navigating between projects) would otherwise keep // sending to the one captured on first render. useEffect(() => { ref.current?.setAccessToken(accessToken); }, [accessToken]); useEffect(() => { ref.current?.setStartSession( startSession as Parameters[0] ); }, [startSession]); useEffect(() => { ref.current?.setFetch(fetchOverride); }, [fetchOverride]); // Note: dispose() is NOT called in effect cleanup because React strict mode // runs cleanup+re-setup, but the transport lives in a ref and isn't recreated. // Calling dispose() would permanently close the BroadcastChannel. // The coordinator's beforeunload handler handles tab close cleanup instead. return ref.current; } /** * Sync chat messages across browser tabs. * * Requires `multiTab: true` on the transport. Handles: * - Tracking read-only state (`isReadOnly`) when another tab is active * - Broadcasting messages from the active tab to other tabs * - Receiving messages from other tabs and updating local state via `setMessages` * * @example * ```tsx * const transport = useTriggerChatTransport({ task: "my-chat", multiTab: true, accessToken }); * const { messages, setMessages } = useChat({ id: chatId, transport }); * const { isReadOnly } = useMultiTabChat(transport, chatId, messages, setMessages); * * * ``` */ export function useMultiTabChat( transport: TriggerChatTransport, chatId: string, messages: T[], setMessages: (messages: T[]) => void ): { isReadOnly: boolean } { const [isReadOnly, setIsReadOnly] = useState(() => transport.isReadOnly(chatId)); // Track read-only state useEffect(() => { const listener = (id: string, readOnly: boolean) => { if (id === chatId) setIsReadOnly(readOnly); }; transport.addReadOnlyListener(listener); setIsReadOnly(transport.isReadOnly(chatId)); return () => transport.removeReadOnlyListener(listener); }, [transport, chatId]); // Active tab: broadcast messages to other tabs on change. // Only broadcast when THIS tab holds the claim (is the current sender). // Deferred via requestIdleCallback so the structured clone in // BroadcastChannel.postMessage never blocks rendering during streaming. const idleRef = useRef | null>(null); const latestMessagesRef = useRef(messages); latestMessagesRef.current = messages; useEffect(() => { if (!transport.hasClaim(chatId) || messages.length === 0) return; if (idleRef.current !== null) return; // Already scheduled const schedule = typeof requestIdleCallback === "function" ? requestIdleCallback : (fn: () => void) => setTimeout(fn, 50); idleRef.current = schedule(() => { idleRef.current = null; if (transport.hasClaim(chatId)) { transport.broadcastMessages(chatId, latestMessagesRef.current as unknown[]); } }); }, [transport, chatId, messages]); // Flush final state when claim is released (turn complete) useEffect(() => { if (!transport.hasClaim(chatId) && latestMessagesRef.current.length > 0) { if (idleRef.current !== null) { const cancel = typeof cancelIdleCallback === "function" ? cancelIdleCallback : clearTimeout; cancel(idleRef.current as any); idleRef.current = null; } transport.broadcastMessages(chatId, latestMessagesRef.current as unknown[]); } }, [transport, chatId, isReadOnly]); // Read-only tab: receive messages from the active tab useEffect(() => { const listener = (id: string, msgs: unknown[]) => { if (id === chatId) { setMessages(msgs as T[]); } }; transport.addMessagesListener(listener); return () => transport.removeMessagesListener(listener); }, [transport, chatId, setMessages]); return { isReadOnly }; } // --------------------------------------------------------------------------- // usePendingMessages — manage steering messages during streaming // --------------------------------------------------------------------------- /** A pending message tracked by `usePendingMessages`. */ export type PendingMessage = { id: string; text: string; /** How this message is being handled. */ mode: "steering" | "queued"; /** Whether the backend confirmed this message was injected mid-response. */ injected: boolean; }; /** Options for `usePendingMessages`. */ export type UsePendingMessagesOptions = { /** The chat transport instance. */ transport: TriggerChatTransport; /** The chat session ID. */ chatId: string; /** The current useChat status. */ status: string; /** The current messages from useChat. */ messages: TUIMessage[]; /** The setMessages function from useChat. */ setMessages: (fn: TUIMessage[] | ((prev: TUIMessage[]) => TUIMessage[])) => void; /** The sendMessage function from useChat. */ sendMessage: (message: { text: string }, options?: ChatRequestOptions) => void; /** Metadata to include when sending (e.g. `{ model }` for model selection). */ metadata?: Record; }; /** A message embedded in an injection point data part. */ export type InjectedMessage = { id: string; text: string; }; /** Return value of `usePendingMessages`. */ export type UsePendingMessagesReturn = { /** Current pending messages with their mode and injection status. */ pending: PendingMessage[]; /** Send a steering message during streaming, or a normal message when ready. */ steer: (text: string) => void; /** Queue a message for the next turn (sent after current response finishes). */ queue: (text: string) => void; /** Promote a queued message to a steering message (sends via input stream immediately). */ promoteToSteering: (id: string) => void; /** Check if an assistant message part is an injection point. */ isInjectionPoint: (part: unknown) => boolean; /** Get the injected message IDs from an injection point part. */ getInjectedMessageIds: (part: unknown) => string[]; /** Get the injected messages (id + text) from an injection point part. Self-contained — works after turn complete. */ getInjectedMessages: (part: unknown) => InjectedMessage[]; }; /** @internal */ export function isInjectionPart(part: unknown): boolean { return ( typeof part === "object" && part !== null && (part as any).type === PENDING_MESSAGE_INJECTED_TYPE ); } /** @internal */ export function injectedMessageIdsOf(part: unknown): string[] { if (!isInjectionPart(part)) return []; const ids = (part as any).data?.messageIds; return Array.isArray(ids) ? ids : []; } /** @internal */ export function injectedMessagesOf(part: unknown): InjectedMessage[] { if (!isInjectionPart(part)) return []; const msgs = (part as any).data?.messages; return Array.isArray(msgs) ? msgs : []; } /** @internal */ export function collectInjectedMessageIds(messages: ReadonlyArray): string[] { const ids: string[] = []; for (const msg of messages) { if (msg.role !== "assistant") continue; for (const part of msg.parts ?? []) { ids.push(...injectedMessageIdsOf(part)); } } return ids; } /** * React hook for managing pending messages (steering) during streaming. * * Handles: * - Sending messages via input stream during streaming (bypassing useChat) * - Tracking which messages were injected mid-response vs queued for next turn * - Inserting injected messages into the conversation on turn complete * - Auto-sending non-injected messages as the next turn * * @example * ```tsx * const pending = usePendingMessages({ * transport, chatId, status, messages, setMessages, sendMessage, * metadata: { model }, * }); * * // In the form: *
{ * e.preventDefault(); * pending.send(input); * setInput(""); * }}> * * // Render pending messages: * {pending.pending.map(msg => ( *
{msg.text} — {msg.injected ? "Injected" : "Pending"}
* ))} * * // Render injection points inline in assistant messages: * {msg.parts.map((part, i) => * pending.isInjectionPoint(part) * ? * : * )} * ``` */ export function usePendingMessages( options: UsePendingMessagesOptions ): UsePendingMessagesReturn { const { transport, chatId, status, messages, setMessages: _setMessages, sendMessage, metadata, } = options; // Internal state: track messages with their mode type InternalMessage = TUIMessage & { _mode: "steering" | "queued" }; const [pendingMsgs, setPendingMsgs] = useState([]); const pendingMsgsRef = useRef(pendingMsgs); pendingMsgsRef.current = pendingMsgs; const injectedIdsRef = useRef>(new Set()); const prevStatusRef = useRef(status); // Watch for injection confirmation chunks in streaming messages useEffect(() => { if (status !== "streaming") return; let newlyInjected = false; for (const id of collectInjectedMessageIds(messages)) { if (!injectedIdsRef.current.has(id)) { injectedIdsRef.current.add(id); newlyInjected = true; } } // Remove injected steering messages from the pending overlay immediately if (newlyInjected) { setPendingMsgs((prev) => prev.filter((m) => !injectedIdsRef.current.has(m.id))); } }, [status, messages]); // Handle turn completion useEffect(() => { const turnCompleted = prevStatusRef.current === "streaming" && status === "ready"; prevStatusRef.current = status; if (!turnCompleted) return; // Auto-send non-injected messages as the next turn. // This includes queued messages AND steering messages that weren't // injected (arrived too late, no prepareStep boundary, etc.). // Note: steering messages were also sent via sendPendingMessage to // the backend's wire buffer, so the backend may already have them. // Calling sendMessage here ensures useChat subscribes to the response. const toSend = pendingMsgs.filter((m) => !injectedIdsRef.current.has(m.id)); // Clean up setPendingMsgs([]); injectedIdsRef.current.clear(); promotedIdsRef.current.clear(); // Auto-send as next turn if (toSend.length > 0) { const text = toSend.map((m) => (m.parts?.[0] as any)?.text ?? "").join("\n"); sendMessage({ text }, metadata ? { metadata } : undefined); } }, [status, pendingMsgs, sendMessage, metadata, messages]); // Send a steering message (injected mid-response via prepareStep) const steer = useCallback( (text: string) => { if (status === "streaming") { const msg = { id: crypto.randomUUID(), role: "user" as const, parts: [{ type: "text" as const, text }], _mode: "steering" as const, } as InternalMessage; transport.sendPendingMessage(chatId, msg, metadata); setPendingMsgs((prev) => [...prev, msg]); } else { // Not streaming — just send normally sendMessage({ text }, metadata ? { metadata } : undefined); } }, [status, transport, chatId, sendMessage, metadata] ); // Queue a message for the next turn (no injection attempt) const queue = useCallback( (text: string) => { if (status === "streaming") { const msg = { id: crypto.randomUUID(), role: "user" as const, parts: [{ type: "text" as const, text }], _mode: "queued" as const, } as InternalMessage; setPendingMsgs((prev) => [...prev, msg]); } else { sendMessage({ text }, metadata ? { metadata } : undefined); } }, [status, sendMessage, metadata] ); // Promote a queued message to steering (send via input stream immediately) const promotedIdsRef = useRef>(new Set()); const promoteToSteering = useCallback( (id: string) => { // Guard against double-click — ref check is synchronous if (promotedIdsRef.current.has(id)) { return; } // Read from the ref, send OUTSIDE the state updater. React may invoke // updaters more than once (StrictMode, update rebasing), so a network // call inside one can double-send. const msg = pendingMsgsRef.current.find((m) => m.id === id); if (!msg || msg._mode !== "queued") return; promotedIdsRef.current.add(id); transport.sendPendingMessage(chatId, msg, metadata); setPendingMsgs((prev) => prev.map((m) => (m.id === id ? { ...m, _mode: "steering" as const } : m)) ); }, [transport, chatId, metadata] ); const isInjectionPoint = isInjectionPart; const getInjectedMessageIds = injectedMessageIdsOf; const getInjectedMessages = injectedMessagesOf; const pending: PendingMessage[] = pendingMsgs.map((m) => ({ id: m.id, text: (m.parts?.[0] as any)?.text ?? "", mode: m._mode, injected: injectedIdsRef.current.has(m.id), })); return { pending, steer, queue, promoteToSteering, isInjectionPoint, getInjectedMessageIds, getInjectedMessages, }; } /** * Send actions through `useChat`, so an action that returns `chat.turn()` on * the server renders like any turn. * * `transport.sendAction` returns the response as a stream that `useChat` never * reads. This hook sends the action as a `useChat` request instead (the * transport recognises `body.action` and sends it as an action), so `useChat` * owns the response: it streams into the message list, `status` and `error` * behave as for a message, and `stop` works. An action that returns nothing on * the server completes with no message added. * * History changes the action makes on the server (an undo removing messages, * for example) are not mirrored automatically; apply those with `setMessages` * optimistically, as before. * * @example * ```tsx * const transport = useTriggerChatTransport({ task: "my-chat", accessToken }); * const { messages, sendMessage, setMessages } = useChat({ id: chatId, transport }); * const { sendAction } = useChatActions({ sendMessage }); * * * ``` */ export function useChatActions(options: { /** `useChat`'s `sendMessage`. */ sendMessage: ( message: undefined, options?: { body?: object; headers?: Record | Headers } ) => Promise | void; }): { /** Send an action; resolves when `useChat` has finished the request. */ sendAction: (action: unknown) => Promise; } { const { sendMessage } = options; const sendMessageRef = useRef(sendMessage); sendMessageRef.current = sendMessage; const sendAction = useCallback(async (action: unknown) => { await sendMessageRef.current(undefined, { body: { action } }); }, []); return { sendAction }; } /** * Render sub-agents streamed with `chat.forwardSubAgent` while they run. * * Pass `onData` to `useChat`, then read a sub-agent's message by the parent * tool call's id. While the sub-agent runs the parent tool part has no output * yet, so fall back to `part.output` for finished calls and reloaded history. * * Each message is rebuilt from the chunks received so far at most once per * `throttleMs`, so a long reply costs a bounded number of rebuilds. * * @example * ```tsx * const subAgents = useSubAgentMessages(); * const { messages } = useChat({ transport, onData: subAgents.onData }); * * // inside the parent's tool card * const message = subAgents.get(part.toolCallId) ?? part.output; * ``` */ export function useSubAgentMessages( options?: Pick ): Pick, "onData" | "get"> { const [, setVersion] = useState(0); const mountedRef = useRef(false); const storeRef = useRef | null>(null); if (storeRef.current === null) { storeRef.current = createSubAgentMessages({ throttleMs: options?.throttleMs, onChange: () => { if (mountedRef.current) setVersion((current) => current + 1); }, }); } const store = storeRef.current; useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; }; }, []); return { onData: store.onData, get: store.get }; }