The Open Framework for Building Agents
feat(eve): React - make prewarming reactive (#3490)
Andrew Barbaa87ad469a9b9
diff --git a/.changeset/reactive-react-prewarming.md b/.changeset/reactive-react-prewarming.mdnew file mode 100644index 000000000..b7f246f56--- /dev/null+++ b/.changeset/reactive-react-prewarming.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Allow React `useEveAgent` to observe `prewarm` across renders so interfaces can prepare a session when the user starts composing. Reset uses the latest rendered value, while disabling prewarming does not discard a session already starting or created.diff --git a/apps/frameworks/next/app/_chat/App.tsx b/apps/frameworks/next/app/_chat/App.tsxindex b5a1847ce..2d555df29 100644--- a/apps/frameworks/next/app/_chat/App.tsx+++ b/apps/frameworks/next/app/_chat/App.tsx@@ -89,6 +89,7 @@ export function App() {const conversationStageRef = useRef<HTMLElement | null>(null);const reducer = useMemo(() => traceReducer(), []);const agent = useEveAgent({+ prewarm: composerInput.length > 0,reducer,});diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex 59fa9f754..f0ccbca85 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -98,9 +98,43 @@ export function Chat() {}```-Prewarming defaults to `false`: the first send creates the session. Enable it when your-application's auth, headers, and any chat-record binding are ready at mount. Applications-that prepare those in the submit handler should keep the default.+In React, `prewarm` is a live boolean. Use component state to wait until the user starts+composing a message:++```tsx+import { useEveAgent } from "eve/react";+import { useState } from "react";++export function Chat() {+ const [message, setMessage] = useState("");+ const agent = useEveAgent({ prewarm: message.length > 0 });++ return (+ <>+ <input value={message} onChange={(event) => setMessage(event.currentTarget.value)} />+ <button+ onClick={() => {+ setMessage("");+ agent.reset();+ }}+ type="button"+ >+ New chat+ </button>+ </>+ );+}+```++An initial `true` value or a later `false` to `true` change prepares the current owned session.+Changing `prewarm` back to `false` does not abort creation or discard an existing session. If+a reset and state update happen in the same event, React applies both before deciding whether+to prepare the next session. Vue and Svelte read `prewarm` when their binding is created; call+their returned `prewarm()` method for interaction-driven creation.++Prewarming defaults to `false`: the first send creates the session. Set it to `true` only after+your application's auth, headers, and any chat-record binding are ready. Applications that+prepare those in the submit handler should keep the default until then.Prewarming starts the workflow and establishes its inbox, then parks before session hooks,dynamic definitions, or sandbox setup run. The first message passes through the channel's@@ -117,7 +151,9 @@ events are not a prerequisite for sending.A failed create sets `error` and calls `onError` when no send is waiting. A waiting send canfall back to creating a session with its message. After creation succeeds, initializationfailures arrive on the stream during the first turn. The configured session timeout starts-at creation, so an unused prewarmed session can expire before its first message.+at creation, so an unused prewarmed session can expire before its first message. React does not+retry a failed prewarm on unrelated renders while the option remains `true`; call `prewarm()`,+change the option from `false` to `true` again, reset, or send a message to recover.The hook keeps consuming one session stream across turns and idle periods. Replies,authorization updates, and turns started elsewhere all update the same projection. A turn settling@@ -125,9 +161,9 @@ does not close the connection. The transport reconnects from its cursor after aserver's renewable 60-second lease; lease renewal does not start a turn or clear UI state.Unmounting or resetting closes the local stream without cancelling the old durable session.-`reset()` reuses the hook instance and clears the conversation. With `prewarm: true`, it-immediately prepares the next owned session; otherwise, the next send creates it. An explicitly supplied-`session` remains externally owned and is never replaced by prewarming or reset. Use+`reset()` reuses the hook instance and clears the conversation. When `prewarm` is true after+the reset, it prepares the next owned session; otherwise, the next send creates it. An explicitly+supplied `session` remains externally owned and is never replaced by prewarming or reset. Use`initialSession` with `resume: true` to restore a saved chat.`data.messages` are eve-owned `EveMessage[]`. Common text, reasoning, file, and dynamic-tool parts follow the [AI SDK `UIMessage`](https://ai-sdk.dev/docs/reference/ai-sdk-core/ui-message) rendering convention, but the types are not interchangeable. eve also exposes authorization and HITL metadata, and a file part's URL can be absent. Adapt those parts before passing messages to an API typed as `UIMessage[]`.@@ -351,7 +387,7 @@ then save a final snapshot in `onFinish`.`initialEvents` must be an ordered prefix of the same session's stream, but its endpoint does not have to line up exactly with where the stream resumes. When the event count matches `initialSession.streamIndex`, catch-up continues from that cursor. A partial or overlapping saved log falls back to index `0`. Every event carries a stable [`meta.id`](/docs/concepts/sessions-runs-and-streaming#the-event-envelope), and the store drops any event whose id it has already applied, so an overlapping replay renders once and `onEvent` only fires for events your UI has not seen.-For multiple chat threads, keep one saved event log and session cursor per thread. `agent`, `host`, `reducer`, `session`, `initialEvents`, `initialSession`, `auth`, `headers`, `optimistic`, `prewarm`, and `resume` are read when the hook creates its store, so remount the chat component when switching threads, for example with `key={chat.id}`.+For multiple chat threads, keep one saved event log and session cursor per thread. `agent`, `host`, `reducer`, `session`, `initialEvents`, `initialSession`, `auth`, `headers`, `optimistic`, and `resume` are read when the hook creates its store, so remount the chat component when switching threads, for example with `key={chat.id}`. React reads `prewarm` on every render.Pass `resume: true` with `initialSession` to rebuild the projection from the durable stream after mount. While `status` is `"resuming"`, render hydrated `data` but disable message and HITL submission; do not present cancellation or active-turn progress controls. If catch-up finds an in-flight turn, `status` changes to `"streaming"` before the binding follows it to a boundary. The stream reports its initial durable tail so catch-up can finish without closing the connection or waiting for an idle timeout. A settled tail changes directly to `"ready"`; a newer turn or pending authorization remains `"streaming"`. The connection stays open to receive later events. A terminal session failure changes to `"error"`.diff --git a/packages/eve/src/react/use-eve-agent.test.ts b/packages/eve/src/react/use-eve-agent.test.tsindex d9eed06d0..37b168165 100644--- a/packages/eve/src/react/use-eve-agent.test.ts+++ b/packages/eve/src/react/use-eve-agent.test.ts@@ -1,4 +1,4 @@-import { createElement, StrictMode } from "react";+import { createElement, StrictMode, useState } from "react";import { act, create as createRenderer } from "react-test-renderer";import { afterEach, describe, expect, it, vi } from "vitest";@@ -201,6 +201,155 @@ describe("useEveAgent", () => {expect(streams[1]?.cancel).toHaveBeenCalledOnce();});+ it("prewarms when the option changes from false to true without replacing the session", async () => {+ let creates = 0;+ const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) => {+ if (init?.method === "POST") return createStartedMessageResponse(`session_${++creates}`, "");+ return createEagerStreamResponse([createSessionWaitingEvent()]);+ });+ let agent: UseEveAgentHelpers<EveMessageData> | undefined;+ function Chat({+ label: _label,+ prewarm,+ }: {+ readonly label: string;+ readonly prewarm: boolean;+ }) {+ agent = useEveAgent({ prewarm });+ return null;+ }+ let root: ReturnType<typeof create> | undefined;++ await act(async () => {+ root = create(createElement(Chat, { label: "initial", prewarm: false }));+ await new Promise((resolve) => setTimeout(resolve, 10));+ });+ expect(fetchMock).not.toHaveBeenCalled();++ await act(async () => {+ root?.update(createElement(Chat, { label: "first character", prewarm: true }));+ });+ await act(async () => {+ await vi.waitFor(() => expect(agent?.session?.sessionId).toBe("session_1"));+ });++ await act(async () => {+ root?.update(createElement(Chat, { label: "rerender", prewarm: true }));+ });+ await act(async () => {+ root?.update(createElement(Chat, { label: "cleared", prewarm: false }));+ });+ await act(async () => {+ root?.update(createElement(Chat, { label: "typed again", prewarm: true }));+ });+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 10));+ });++ expect(creates).toBe(1);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(agent?.session?.sessionId).toBe("session_1");+ });++ it("does not abort prewarming when the option changes to false", async () => {+ const accepted = createDeferred<Response>();+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockReturnValueOnce(accepted.promise)+ .mockResolvedValueOnce(createEagerStreamResponse([createSessionWaitingEvent()]));+ let agent: UseEveAgentHelpers<EveMessageData> | undefined;+ function Chat({ prewarm }: { readonly prewarm: boolean }) {+ agent = useEveAgent({ prewarm });+ return null;+ }+ let root: ReturnType<typeof create> | undefined;++ await act(async () => {+ root = create(createElement(Chat, { prewarm: false }));+ });+ await act(async () => {+ root?.update(createElement(Chat, { prewarm: true }));+ });+ await act(async () => {+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());+ });+ const createSignal = fetchMock.mock.calls[0]![1]?.signal;++ await act(async () => {+ root?.update(createElement(Chat, { prewarm: false }));+ });+ expect(createSignal?.aborted).toBe(false);++ await act(async () => {+ accepted.resolve(createStartedMessageResponse("session_1", ""));+ await vi.waitFor(() => expect(agent?.session?.sessionId).toBe("session_1"));+ });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("does not retry failed prewarming on unrelated renders", async () => {+ const error = new Error("create failed");+ const fetchMock = vi.spyOn(globalThis, "fetch").mockRejectedValue(error);+ let agent: UseEveAgentHelpers<EveMessageData> | undefined;+ function Chat({ label: _label }: { readonly label: string }) {+ agent = useEveAgent({ prewarm: true });+ return null;+ }+ let root: ReturnType<typeof create> | undefined;++ await act(async () => {+ root = create(createElement(Chat, { label: "initial" }));+ });+ await act(async () => {+ await vi.waitFor(() => expect(agent?.status).toBe("error"));+ });++ await act(async () => {+ root?.update(createElement(Chat, { label: "rerender" }));+ });+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 10));+ });++ expect(fetchMock).toHaveBeenCalledOnce();+ expect(agent?.error).toBe(error);+ });++ it("uses the latest batched prewarm value after reset", async () => {+ let creates = 0;+ const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) => {+ if (init?.method === "POST") return createStartedMessageResponse(`session_${++creates}`, "");+ return createEagerStreamResponse([createSessionWaitingEvent()]);+ });+ let agent: UseEveAgentHelpers<EveMessageData> | undefined;+ let setPrewarm: ((value: boolean) => void) | undefined;+ function Chat() {+ const [prewarm, setPrewarmState] = useState(true);+ setPrewarm = setPrewarmState;+ agent = useEveAgent({ prewarm });+ return null;+ }++ await act(async () => {+ create(createElement(Chat));+ });+ await act(async () => {+ await vi.waitFor(() => expect(agent?.session?.sessionId).toBe("session_1"));+ });++ await act(async () => {+ setPrewarm?.(false);+ agent?.reset();+ });+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 10));+ });++ expect(creates).toBe(1);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(agent?.session).toBeUndefined();+ });+it("keeps the helpers object stable across renders without store changes", async () => {const seenHelpers: Array<UseEveAgentHelpers<EveMessageData>> = [];let root: ReturnType<typeof create> | undefined;diff --git a/packages/eve/src/react/use-eve-agent.ts b/packages/eve/src/react/use-eve-agent.tsindex b685894ee..82bad1b02 100644--- a/packages/eve/src/react/use-eve-agent.ts+++ b/packages/eve/src/react/use-eve-agent.ts@@ -54,7 +54,7 @@ export interface UseEveAgentHelpers<TData> extends UseEveAgentSnapshot<TData> {readonly resume: () => Promise<void>;/** Creates the session without starting its first turn. */readonly prewarm: () => Promise<void>;- /** Resets the session: detaches any local stream, recreates the owned session, and clears events and projected data. */+ /** Resets the session: detaches any local stream and clears events and projected data. */readonly reset: () => void;/** Sends a message. While a turn is active, pass `turnPolicy: "steer"` to replace it. */readonly send: <TOutput = unknown>(@@ -111,7 +111,16 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>* @default true*/readonly optimistic?: boolean;- /** Prewarm an owned session on mount and after reset. @default false */+ /**+ * Prewarm an owned session when true. React observes this value across renders;+ * changing it from false to true prepares the current session, and reset checks+ * the latest rendered value before preparing the next session.+ *+ * Changing the value to false does not discard an existing session or abort+ * session creation already in flight.+ *+ * @default false+ */readonly prewarm?: boolean;readonly reducer?: EveAgentReducer<TData>;/**@@ -142,8 +151,8 @@ export function useEveAgent<TData>(* infer `TData`.** Session-shaping options (`host`, `reducer`, `session`, `initialEvents`,- * `initialSession`, `auth`, `headers`, `optimistic`, `prewarm`, `resume`) are- * read once when the store is created; remount to change them. Lifecycle+ * `initialSession`, `auth`, `headers`, `optimistic`, `resume`) are read once+ * when the store is created; remount to change them. `prewarm` and lifecycle* callbacks (`onError`, `onEvent`, `onFinish`, `onSessionChange`, `prepareSend`)* refresh on every render.*/@@ -153,6 +162,8 @@ export function useEveAgent<TData>(const storeRef = useRef<EveAgentStore<TData> | undefined>(undefined);const resumeOnMountRef = useRef(options.resume ?? false);const [autoResumePending, setAutoResumePending] = useState(resumeOnMountRef.current);+ const [prewarmResetGeneration, setPrewarmResetGeneration] = useState(0);+ const shouldPrewarm = options.prewarm ?? false;if (!storeRef.current) {if (@@ -170,7 +181,6 @@ export function useEveAgent<TData>(initialEvents: options.initialEvents,initialSession: options.initialSession,optimistic: options.optimistic,- prewarm: options.prewarm,reducer,session: options.session,});@@ -202,6 +212,11 @@ export function useEveAgent<TData>(detachEveAgentStore(store);};}, [store]);+ useEffect(() => {+ if (!shouldPrewarm) return;+ const timeout = setTimeout(() => void store.prewarm().catch(() => {}), 0);+ return () => clearTimeout(timeout);+ }, [prewarmResetGeneration, shouldPrewarm, store]);useEffect(() => {if (!resumeOnMountRef.current) return;let active = true;@@ -216,7 +231,10 @@ export function useEveAgent<TData>(}, [store]);const cancel = useCallback(() => store.cancel(), [store]);- const reset = useCallback(() => store.reset(), [store]);+ const reset = useCallback(() => {+ store.reset();+ setPrewarmResetGeneration((generation) => generation + 1);+ }, [store]);const prewarm = useCallback(() => store.prewarm(), [store]);const resume = useCallback(() => store.resume(), [store]);const send = useCallback(diff --git a/research/session-prewarming.md b/research/session-prewarming.mdindex a443c8ea5..4833e3b1e 100644--- a/research/session-prewarming.md+++ b/research/session-prewarming.md@@ -1,7 +1,7 @@---issue: https://github.com/vercel/eve/issues/1476status: implemented-last_updated: "2026-09-16"+last_updated: "2026-09-17"---# Session prewarming@@ -13,9 +13,12 @@ without a message. They return an accepted session ID. `session.send(message)` smessage to that ID; `create({ message })` still creates and starts a turn in one request.React, Vue, and Svelte accept `useEveAgent({ prewarm: true })` to prewarm on mount and after-reset. The default is `false`. The explicit `prewarm()` method resolves on `202 Accepted`;-concurrent calls share the same request. Applications must have auth, headers, and any chat-row-binding ready before opting into automatic prewarming.+reset. The default is `false`. React also observes the boolean across renders: a `false` to `true`+change prepares the current owned session, while `true` to `false` does not abort or discard one.+Reset reevaluates the value after batched React state updates. Vue and Svelte keep construction-time+option semantics. The explicit `prewarm()` method resolves on `202 Accepted`; concurrent calls+share the same request. Applications must have auth, headers, and any chat-row binding ready before+opting into automatic prewarming.Eval contexts expose `t.session(options?)` to create an accepted session without a turn,and `t.send(message, options?)` to create a fresh session with its first message in one@@ -41,7 +44,7 @@ step or harness mode is needed.```mermaidflowchart LR- Mount["mount with prewarm: true"] --> Create["start workflow + establish inbox"]+ Trigger["mount, reset, or React false → true with prewarm enabled"] --> Create["start workflow + establish inbox"]Create --> Wait["wait before initialization"]Send["send message"] --> Channel["onMessage"]Channel --> Wait