The Open Framework for Building Agents
fix(eve): add session `resuming` lifecycle status (#2525)
Timo Linsdfe0d181a0aa
diff --git a/.changeset/calm-resume-lifecycle.md b/.changeset/calm-resume-lifecycle.mdnew file mode 100644index 000000000..d12a5bf7a--- /dev/null+++ b/.changeset/calm-resume-lifecycle.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Expose resumed session catch-up as a distinct `resuming` frontend lifecycle state so hydrated conversations do not show active-turn controls before an in-flight turn is confirmed.diff --git a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx b/apps/docs/registry/channel/web/app/_components/agent-chat.tsxindex b37ea6be4..161a23361 100644--- a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx+++ b/apps/docs/registry/channel/web/app/_components/agent-chat.tsx@@ -56,7 +56,7 @@ export function AgentChat({});const isBusy = agent.status === "submitted" || agent.status === "streaming";- const isRestoring = sessionId !== undefined && agent.events.length === 0 && isBusy;+ const isResuming = agent.status === "resuming";const isEmpty = agent.data.messages.length === 0;const lastMessage = agent.data.messages.at(-1);const isPendingAssistantShell =@@ -65,10 +65,10 @@ export function AgentChat({const showPendingThinking =isBusy &&(agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);- const turnFailure = isBusy ? undefined : getLatestTurnFailure(agent.events);+ const turnFailure = isBusy || isResuming ? undefined : getLatestTurnFailure(agent.events);const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;- const showConversationLayout = isRestoring || hasConversationContent;+ const showConversationLayout = isResuming || hasConversationContent;const activeSessionId = sessionId ?? agent.session?.sessionId;const requestCancellation = () => {@@ -80,7 +80,7 @@ export function AgentChat({const handleSubmit = async (message: PromptInputMessage) => {const text = message.text.trim();- if ((text.length === 0 && message.files.length === 0) || isRestoring) return;+ if ((text.length === 0 && message.files.length === 0) || isResuming) return;setCancellationError(undefined);const options = isBusy ? { turnPolicy: "steer" as const } : undefined;@@ -108,8 +108,8 @@ export function AgentChat({const composer = (<PromptInput onSubmit={handleSubmit}>- <PromptInputTextarea disabled={isRestoring} placeholder="Send a message…" />- {isBusy && !isRestoring ? (+ <PromptInputTextarea disabled={isResuming} placeholder="Send a message…" />+ {isBusy ? (<PromptInputButtonaria-label="Stop"className="absolute right-12 bottom-2.5 rounded-full"@@ -119,7 +119,10 @@ export function AgentChat({<SquareIcon className="size-3 fill-current" /></PromptInputButton>) : null}- <PromptInputSubmit disabled={isRestoring} status={isBusy ? undefined : agent.status} />+ <PromptInputSubmit+ disabled={isResuming}+ status={isBusy || isResuming ? undefined : agent.status}+ /></PromptInput>);@@ -147,7 +150,7 @@ export function AgentChat({isPendingAssistantShell &&message.id === lastMessage.id ? null : (<AgentMessage- canRespond={!isBusy}+ canRespond={!isBusy && !isResuming}isStreaming={agent.status === "streaming" && index === agent.data.messages.length - 1}diff --git a/apps/frameworks/nuxt/app/components/EveAgentConsole.vue b/apps/frameworks/nuxt/app/components/EveAgentConsole.vueindex 84aa71c0c..a183f2a22 100644--- a/apps/frameworks/nuxt/app/components/EveAgentConsole.vue+++ b/apps/frameworks/nuxt/app/components/EveAgentConsole.vue@@ -6,6 +6,8 @@ const { cancel, data, status, error, respond, send } = useEveAgent();type EveFilePart = Extract<EveMessagePart, { type: "file" }>;const isBusy = computed(() => status.value === "submitted" || status.value === "streaming");+const isResuming = computed(() => status.value === "resuming");+const isInputDisabled = computed(() => isBusy.value || isResuming.value);const isEmpty = computed(() => data.value.messages.length === 0);const cancellationError = ref<string>();const errorMessage = computed(() => cancellationError.value ?? error.value?.message);@@ -37,7 +39,7 @@ const messageText = ref("");function submitMessage() {const text = messageText.value.trim();- if (!text || isBusy.value) return;+ if (!text || isInputDisabled.value) return;cancellationError.value = undefined;messageText.value = "";void send(text);@@ -241,7 +243,7 @@ function formatBytes(size: number | undefined): string | undefined {<ToolBlockv-else-if="part.type === 'dynamic-tool'":part="part as EveDynamicToolPart"- :can-respond="!isBusy"+ :can-respond="!isInputDisabled"@input-responses="handleInputResponses"/></template>@@ -257,7 +259,7 @@ function formatBytes(size: number | undefined): string | undefined {><textareav-model="messageText"- :disabled="isBusy"+ :disabled="isInputDisabled"placeholder="Send a message…"rows="1"class="min-h-20 flex-1 resize-none border-0 bg-transparent px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"@@ -276,7 +278,7 @@ function formatBytes(size: number | undefined): string | undefined {<buttonv-elsetype="submit"- :disabled="!messageText.trim()"+ :disabled="isInputDisabled || !messageText.trim()"class="flex size-8 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50"><svgdiff --git a/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte b/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelteindex f631785cb..5478ae131 100644--- a/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte+++ b/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte@@ -11,6 +11,8 @@type EveFilePart = Extract<EveMessagePart, { type: "file" }>;let isBusy = $derived(agent.status === "submitted" || agent.status === "streaming");+ let isResuming = $derived(agent.status === "resuming");+ let isInputDisabled = $derived(isBusy || isResuming);let isEmpty = $derived(agent.data.messages.length === 0);let cancellationError = $state<string>();let errorMessage = $derived(cancellationError ?? agent.error?.message);@@ -45,7 +47,7 @@function submitMessage() {const text = messageText.trim();- if (!text || isBusy) return;+ if (!text || isInputDisabled) return;cancellationError = undefined;messageText = "";void agent.send(text);@@ -235,7 +237,7 @@{:else if part.type === "dynamic-tool"}<ToolBlock{part}- canRespond={!isBusy}+ canRespond={!isInputDisabled}onInputResponses={handleInputResponses}/>{/if}@@ -257,7 +259,7 @@><textareabind:value={messageText}- disabled={isBusy}+ disabled={isInputDisabled}placeholder="Send a message..."rows="1"class="min-h-20 flex-1 resize-none border-0 bg-transparent px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"@@ -278,7 +280,7 @@<buttontype="submit"aria-label="Send message"- disabled={!messageText.trim()}+ disabled={isInputDisabled || !messageText.trim()}class="flex size-8 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:pointer-events-none disabled:opacity-50"><svgdiff --git a/docs/guides/frontend/nuxt.mdx b/docs/guides/frontend/nuxt.mdxindex d2595adad..29f454520 100644--- a/docs/guides/frontend/nuxt.mdx+++ b/docs/guides/frontend/nuxt.mdx@@ -41,12 +41,13 @@ The `eve` key accepts only two options, `eveRoot` and `eveBuildCommand`.const { status, send } = useEveAgent();const isBusy = computed(() => status.value === "submitted" || status.value === "streaming");+const isInputDisabled = computed(() => isBusy.value || status.value === "resuming");const message = ref("");async function handleSubmit() {const text = message.value.trim();- if (!text || isBusy.value) return;+ if (!text || isInputDisabled.value) return;message.value = "";await send(text);}@@ -54,8 +55,8 @@ async function handleSubmit() {<template><form @submit.prevent="handleSubmit">- <input v-model="message" :disabled="isBusy" />- <button type="submit" :disabled="isBusy">Send</button>+ <input v-model="message" :disabled="isInputDisabled" />+ <button type="submit" :disabled="isInputDisabled">Send</button></form></template>```diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex 0858ee3dd..fcfe5a892 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -36,6 +36,7 @@ import { useEveAgent } from "eve/react";export function Chat() {const agent = useEveAgent();const isBusy = agent.status === "submitted" || agent.status === "streaming";+ const isResuming = agent.status === "resuming";return (<form@@ -43,7 +44,7 @@ export function Chat() {event.preventDefault();const form = new FormData(event.currentTarget);const message = String(form.get("message") ?? "").trim();- if (message.length > 0) {+ if (message.length > 0 && !isResuming) {void agent.send(message, isBusy ? { turnPolicy: "steer" } : undefined);}}}@@ -56,8 +57,10 @@ export function Chat() {)}</article>))}- <input name="message" />- <button type="submit">Send</button>+ <input disabled={isResuming} name="message" />+ <button disabled={isResuming} type="submit">+ Send+ </button></form>);}@@ -67,18 +70,18 @@ export function Chat() {`useEveAgent()` returns the current UI state plus commands:-| Field | What it is |-| --------- | --------------------------------------------------------------------------- |-| `data` | Projected UI state from the reducer. Defaults to `{ messages }`. |-| `status` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. Drives the composer. |-| `error` | The last `Error` thrown, if any. |-| `events` | Raw eve stream events for this session. |-| `session` | Serializable fixed session cursor (`sessionId`, `streamIndex`). |-| `send` | Send text or a multi-part message, with per-turn options. |-| `respond` | Answer pending HITL input requests, with per-turn options. |-| `resume` | Replay an attached session and follow its in-flight turn. |-| `cancel` | Request durable cancellation of the active turn. |-| `reset` | Clear local events, data, errors, and the local session cursor. |+| Field | What it is |+| --------- | ----------------------------------------------------------------------------------------- |+| `data` | Projected UI state from the reducer. Defaults to `{ messages }`. |+| `status` | `"ready"`, `"resuming"`, `"submitted"`, `"streaming"`, or `"error"`. Drives the composer. |+| `error` | The last `Error` thrown, if any. |+| `events` | Raw eve stream events for this session. |+| `session` | Serializable fixed session cursor (`sessionId`, `streamIndex`). |+| `send` | Send text or a multi-part message, with per-turn options. |+| `respond` | Answer pending HITL input requests, with per-turn options. |+| `resume` | Replay an attached session and follow its in-flight turn. |+| `cancel` | Request durable cancellation of the active turn. |+| `reset` | Clear local events, data, errors, and the local session cursor. |Most chat UIs only need `data.messages` and `status`. Drop down to `events` when you need the authoritative wire events directly, for example to persist an audit log or build a custom projection.@@ -104,7 +107,7 @@ await agent.send([]);```-Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and `status` moves from `ready` to `submitted` to `streaming` and back. To replace an active turn with a follow-up, send the message with `turnPolicy: "steer"`. eve accepts the message through the durable session, cancels the active turn, and keeps the hook attached through the replacement turn:+Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and a new turn moves `status` from `ready` to `submitted` to `streaming` and back. Resuming an attached session uses `resuming` while eve performs bounded catch-up. Disable message and HITL submission in that state. A settled tail moves directly to `ready`; an in-flight tail moves to `streaming` before eve follows it. To replace an active turn with a follow-up, send the message with `turnPolicy: "steer"`. eve accepts the message through the durable session, cancels the active turn, and keeps the hook attached through the replacement turn:```tsxawait agent.send(message, { turnPolicy: "steer" });@@ -299,11 +302,11 @@ render historical messages without replaying the whole stream. A database-backedchat app should usually persist stream events as they arrive with `onEvent` andthen 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. 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 a saved log that overlaps the replayed prefix renders once, and `onEvent` only fires for events your UI has not seen.+`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`, and `resume` are read when the hook creates its store, so remount the chat component when switching threads, for example with `key={chat.id}`.-Pass `resume: true` with `initialSession` to rebuild the projection from the durable stream after mount. If the stream ends at an in-flight turn, the binding stays attached until that turn reaches its boundary. If the stream already ends at a settled session boundary, replay stops at the history tail.+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. A settled tail changes directly to `"ready"`, and a terminal session failure changes to `"error"`.```tsxconst agent = useEveAgent({diff --git a/docs/guides/frontend/sveltekit.mdx b/docs/guides/frontend/sveltekit.mdxindex 14e32054e..ca4ffccb7 100644--- a/docs/guides/frontend/sveltekit.mdx+++ b/docs/guides/frontend/sveltekit.mdx@@ -51,10 +51,11 @@ With the plugin in `vite.config.ts`, components call [`useEveAgent`](./use-eve-aconst agent = useEveAgent();let message = $state("");let isBusy = $derived(agent.status === "submitted" || agent.status === "streaming");+ let isInputDisabled = $derived(isBusy || agent.status === "resuming");async function handleSubmit() {const text = message.trim();- if (!text || isBusy) return;+ if (!text || isInputDisabled) return;message = "";await agent.send(text);}@@ -64,8 +65,8 @@ With the plugin in `vite.config.ts`, components call [`useEveAgent`](./use-eve-aevent.preventDefault();void handleSubmit();}}>- <input bind:value={message} disabled={isBusy} />- <button type="submit" disabled={isBusy}>Send</button>+ <input bind:value={message} disabled={isInputDisabled} />+ <button type="submit" disabled={isInputDisabled}>Send</button></form>```diff --git a/docs/guides/frontend/use-eve-agent-svelte.mdx b/docs/guides/frontend/use-eve-agent-svelte.mdxindex e47fccf74..17b620b67 100644--- a/docs/guides/frontend/use-eve-agent-svelte.mdx+++ b/docs/guides/frontend/use-eve-agent-svelte.mdx@@ -18,10 +18,11 @@ Call the binding once for a conversation and read its reactive getters directly.const agent = useEveAgent();let message = $state("");let isBusy = $derived(agent.status === "submitted" || agent.status === "streaming");+ let isInputDisabled = $derived(isBusy || agent.status === "resuming");async function handleSubmit() {const text = message.trim();- if (!text || isBusy) return;+ if (!text || isInputDisabled) return;message = "";await agent.send(text);}@@ -35,8 +36,8 @@ Call the binding once for a conversation and read its reactive getters directly.event.preventDefault();void handleSubmit();}}>- <input bind:value={message} disabled={isBusy} />- <button type="submit" disabled={isBusy}>Send</button>+ <input bind:value={message} disabled={isInputDisabled} />+ <button type="submit" disabled={isInputDisabled}>Send</button></form>```@@ -106,7 +107,7 @@ See [Human-in-the-loop prompts](./overview#human-in-the-loop-prompts) for reques## Cancel, reset, and resume-Call `agent.cancel()` to stop the durable server-side turn while the binding remains attached through settlement. Destroying the component only disconnects its local stream; it does not cancel server execution. Call `agent.reset()` to clear local state and start a new session. Pass `initialSession`, `initialEvents`, and `resume: true` to restore a saved conversation and follow an in-flight turn. Use `agent.resume()` directly when restoration is controlled imperatively. See [Resumable sessions](./overview#resumable-sessions) for the persistence contract and [Sending and streaming](./overview#sending-and-streaming) for cancellation behavior.+Call `agent.cancel()` to stop the durable server-side turn while the binding remains attached through settlement. Destroying the component only disconnects its local stream; it does not cancel server execution. Call `agent.reset()` to clear local state and start a new session. Pass `initialSession`, `initialEvents`, and `resume: true` to restore a saved conversation and follow an in-flight turn. During bounded catch-up, `agent.status` is `"resuming"`; keep the hydrated conversation visible, disable submission, and wait for `"ready"`, `"error"`, or `"streaming"`. Use `agent.resume()` directly when restoration is controlled imperatively. See [Resumable sessions](./overview#resumable-sessions) for the persistence contract and [Sending and streaming](./overview#sending-and-streaming) for cancellation behavior.## Custom host and credentialsdiff --git a/docs/guides/frontend/use-eve-agent-vue.mdx b/docs/guides/frontend/use-eve-agent-vue.mdxindex 5e5464482..a90989051 100644--- a/docs/guides/frontend/use-eve-agent-vue.mdx+++ b/docs/guides/frontend/use-eve-agent-vue.mdx@@ -19,10 +19,11 @@ import { computed, ref } from "vue";const { data, status, send } = useEveAgent();const message = ref("");const isBusy = computed(() => status.value === "submitted" || status.value === "streaming");+const isInputDisabled = computed(() => isBusy.value || status.value === "resuming");async function handleSubmit() {const text = message.value.trim();- if (!text || isBusy.value) return;+ if (!text || isInputDisabled.value) return;message.value = "";await send(text);}@@ -33,8 +34,8 @@ async function handleSubmit() {<p>{{ item.role }}: {{ item.parts }}</p></div><form @submit.prevent="handleSubmit">- <input v-model="message" :disabled="isBusy" />- <button type="submit" :disabled="isBusy">Send</button>+ <input v-model="message" :disabled="isInputDisabled" />+ <button type="submit" :disabled="isInputDisabled">Send</button></form></template>```@@ -108,7 +109,7 @@ See [Human-in-the-loop prompts](./overview#human-in-the-loop-prompts) for reques## Cancel, reset, and resume-Call `cancel()` to stop the durable server-side turn while the composable remains attached through settlement. Disposing the component only disconnects its local stream; it does not cancel server execution. Call `reset()` to clear local state and start a new session. Pass `initialSession`, `initialEvents`, and `resume: true` to restore a saved conversation and follow an in-flight turn. Use `resume()` directly when restoration is controlled imperatively. See [Resumable sessions](./overview#resumable-sessions) for the persistence contract and [Sending and streaming](./overview#sending-and-streaming) for cancellation behavior.+Call `cancel()` to stop the durable server-side turn while the composable remains attached through settlement. Disposing the component only disconnects its local stream; it does not cancel server execution. Call `reset()` to clear local state and start a new session. Pass `initialSession`, `initialEvents`, and `resume: true` to restore a saved conversation and follow an in-flight turn. During bounded catch-up, `status.value` is `"resuming"`; keep the hydrated conversation visible, disable submission, and wait for `"ready"`, `"error"`, or `"streaming"`. Use `resume()` directly when restoration is controlled imperatively. See [Resumable sessions](./overview#resumable-sessions) for the persistence contract and [Sending and streaming](./overview#sending-and-streaming) for cancellation behavior.## Custom host and credentialsdiff --git a/packages/eve/src/client/eve-agent-store.test.ts b/packages/eve/src/client/eve-agent-store.test.tsindex 0fd8e829b..2c8b16ecc 100644--- a/packages/eve/src/client/eve-agent-store.test.ts+++ b/packages/eve/src/client/eve-agent-store.test.ts@@ -50,9 +50,12 @@ function streamResponse(events: readonly MessageStreamEvent[]): Response {);}-function boundedStreamResponse(events: readonly MessageStreamEvent[]): Response {+function boundedStreamResponse(+ events: readonly MessageStreamEvent[],+ tailIndex = events.length - 1,+): Response {const response = streamResponse(events);- response.headers.set("x-eve-stream-tail-index", String(events.length - 1));+ response.headers.set("x-eve-stream-tail-index", String(tailIndex));return response;}@@ -210,7 +213,100 @@ describe("EveAgentStore stream overlap", () => {});describe("EveAgentStore session resume", () => {- it("publishes a replayed terminal failure with error status", async () => {+ it("keeps a settled hydrated snapshot resuming until catch-up returns ready", async () => {+ const events = turnEvents();+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(boundedStreamResponse([], events.length - 1))+ .mockResolvedValueOnce(streamResponse([]));+ const store = new EveAgentStore({+ initialEvents: events,+ initialSession: { sessionId: "session_1", streamIndex: events.length },+ reducer: defaultMessageReducer(),+ });+ const statuses: string[] = [];+ store.subscribe(() => statuses.push(store.snapshot.status));++ await store.resume();++ expect(statuses[0]).toBe("resuming");+ expect(statuses).not.toContain("submitted");+ expect(statuses).not.toContain("streaming");+ expect(store.snapshot.status).toBe("ready");+ expect(store.snapshot.events).toEqual(events);+ expect(+ new URL(fetchMock.mock.calls[0]![0].toString(), "http://localhost").searchParams.get(+ "startIndex",+ ),+ ).toBe(String(events.length));+ });++ it("replays from index zero when the hydrated log does not match its cursor", async () => {+ const events = turnEvents();+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(boundedStreamResponse(events))+ .mockResolvedValueOnce(streamResponse([]));+ const store = new EveAgentStore({+ initialEvents: events.slice(0, 1),+ initialSession: { sessionId: "session_1", streamIndex: 2 },+ reducer: defaultMessageReducer(),+ });++ await store.resume();++ expect(+ new URL(fetchMock.mock.calls[0]![0].toString(), "http://localhost").searchParams.get(+ "startIndex",+ ),+ ).toBeNull();+ expect(store.snapshot.events).toEqual(events);+ expect(store.snapshot.status).toBe("ready");+ });++ it("moves an unsettled hydrated snapshot to streaming before following it", async () => {+ const [received, started, completed, waiting] = stampTestEvents([+ createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),+ createTurnStartedEvent({ sequence: 1, turnId: "turn_1" }),+ createMessageCompletedEvent({+ finishReason: "stop",+ message: "Hi there.",+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createSessionWaitingEvent(),+ ] as UnstampedMessageStreamEvent[]);+ const initialEvents = [received!, started!];+ const live = controlledStreamResponse();+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(boundedStreamResponse([], initialEvents.length - 1))+ .mockResolvedValueOnce(live.response);+ const store = new EveAgentStore({+ initialEvents,+ initialSession: { sessionId: "session_1", streamIndex: initialEvents.length },+ reducer: defaultMessageReducer(),+ });++ const resuming = store.resume();+ expect(store.snapshot.status).toBe("resuming");+ await vi.waitFor(() => expect(store.snapshot.status).toBe("streaming"));+ expect(+ new URL(fetchMock.mock.calls[0]![0].toString(), "http://localhost").searchParams.get(+ "startIndex",+ ),+ ).toBe(String(initialEvents.length));++ live.emit(completed!);+ live.emit(waiting!);+ live.close();+ await resuming;++ expect(store.snapshot.status).toBe("ready");+ });++ it("publishes a hydrated terminal failure with error status", async () => {const failed = stampTestEvents([createSessionFailedEvent({code: "SESSION_FAILED",@@ -218,9 +314,10 @@ describe("EveAgentStore session resume", () => {sessionId: "session_1",}),])[0]!;- vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(boundedStreamResponse([failed]));+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(boundedStreamResponse([], 0));const store = new EveAgentStore({- initialSession: { sessionId: "session_1", streamIndex: 0 },+ initialEvents: [failed],+ initialSession: { sessionId: "session_1", streamIndex: 1 },reducer: defaultMessageReducer(),});const published: Array<{ eventType: string | undefined; status: string }> = [];@@ -233,9 +330,7 @@ describe("EveAgentStore session resume", () => {await store.resume();- expect(published.find((snapshot) => snapshot.eventType === "session.failed")?.status).toBe(- "error",- );+ expect(published).toContainEqual({ eventType: "session.failed", status: "error" });expect(store.snapshot.error?.message).toBe("Session failed.");});diff --git a/packages/eve/src/client/eve-agent-store.ts b/packages/eve/src/client/eve-agent-store.tsindex ebc62e6c0..eb331421b 100644--- a/packages/eve/src/client/eve-agent-store.ts+++ b/packages/eve/src/client/eve-agent-store.ts@@ -25,12 +25,13 @@ import type {} from "#client/types.js";/**- * Lifecycle state of an {@link EveAgentStore}: `ready` (idle), `submitted`- * (turn sent, awaiting the first event), `streaming` (events arriving), and- * `error` (the turn failed). A turn advances `ready` to `submitted` to- * `streaming` to `ready` (or `error`).+ * Lifecycle state of an {@link EveAgentStore}: `ready` (idle), `resuming`+ * (checking an attached session for continuation), `submitted` (turn sent,+ * awaiting the first event), `streaming` (events arriving), and `error` (the+ * turn failed). A new turn advances `ready` to `submitted` to `streaming` to+ * `ready` (or `error`).*/-export type EveAgentStoreStatus = "error" | "ready" | "streaming" | "submitted";+export type EveAgentStoreStatus = "error" | "ready" | "resuming" | "streaming" | "submitted";/*** Prepares one outbound turn immediately before the client sends it, e.g. to@@ -197,6 +198,9 @@ export class EveAgentStore<TData> {async send<TOutput = unknown>(input: SendTurnPayload<TOutput>): Promise<void> {if (this.#activeTurn !== undefined) {+ if (this.#status === "resuming") {+ throw new Error("eve session is resuming.");+ }return await this.#sendFollowUp(this.#activeTurn, input);}@@ -298,7 +302,11 @@ export class EveAgentStore<TData> {}async #resume(): Promise<void> {- if (this.#status === "streaming" || this.#status === "submitted") {+ if (+ this.#status === "resuming" ||+ this.#status === "streaming" ||+ this.#status === "submitted"+ ) {throw new Error("eve session is already processing a turn.");}if (this.#session === undefined) {@@ -322,26 +330,30 @@ export class EveAgentStore<TData> {this.#activeTurn = turn;turn.resolveResponse(undefined);this.#error = undefined;- this.#status = "submitted";+ this.#status = "resuming";this.#publish();try {- const replayed: MessageStreamEvent[] = [];+ const hasCompleteInitialPrefix = this.#events.length === session.state.streamIndex;+ const replayed: MessageStreamEvent[] = hasCompleteInitialPrefix ? [...this.#events] : [];for await (const event of session.stream({follow: false,signal: turn.abortController.signal,- startIndex: 0,+ startIndex: hasCompleteInitialPrefix ? session.state.streamIndex : 0,})) {if (!this.#isActiveTurn(turn)) return;replayed.push(event);- this.#acceptServerEvent(event, false);+ this.#acceptServerEvent(event, { publish: false, transitionToStreaming: false });}if (!this.#isActiveTurn(turn)) return;- this.#publish();+ const replayTail = replayed.at(-1);+ if (replayTail !== undefined) this.#applyTerminalStreamFailure(replayTail);const replaySettled = isSettledSessionTail(replayed);- if (!replaySettled || replayed.at(-1)?.type === "session.waiting") {+ if (this.#error === undefined && (!replaySettled || replayTail?.type === "session.waiting")) {const pendingAuthorizations = collectPendingAuthorizations(replayed);+ if (!replaySettled) this.#status = "streaming";+ this.#publish();for await (const event of session.stream({signal: turn.abortController.signal,streamReconnectPolicy: replaySettled ? { reconnect: false } : undefined,@@ -356,6 +368,9 @@ export class EveAgentStore<TData> {break;}}+ } else {+ this.#status = this.#error === undefined ? "ready" : "error";+ this.#publish();}await this.#followSteeredTurns(turn);@@ -547,14 +562,17 @@ export class EveAgentStore<TData> {});}- #acceptServerEvent(event: MessageStreamEvent, publish = true): void {+ #acceptServerEvent(+ event: MessageStreamEvent,+ options: { readonly publish?: boolean; readonly transitionToStreaming?: boolean } = {},+ ): void {if (!this.#seenEvents.admit(event)) return;this.#events = [...this.#events, event];this.#applyServerEvent(event);this.#callbacks.onEvent?.(event);- this.#status = "streaming";+ if (options.transitionToStreaming ?? true) this.#status = "streaming";this.#applyTerminalStreamFailure(event);- if (publish) this.#publish();+ if (options.publish ?? true) this.#publish();}#applyServerEvent(event: MessageStreamEvent): void {diff --git a/packages/eve/src/react/use-eve-agent.test.ts b/packages/eve/src/react/use-eve-agent.test.tsindex 4508a8c27..5730e3561 100644--- a/packages/eve/src/react/use-eve-agent.test.ts+++ b/packages/eve/src/react/use-eve-agent.test.ts@@ -42,9 +42,12 @@ function createEagerStreamResponse(events: readonly UnstampedMessageStreamEvent[);}-function createBoundedStreamResponse(events: readonly UnstampedMessageStreamEvent[]): Response {+function createBoundedStreamResponse(+ events: readonly UnstampedMessageStreamEvent[],+ tailIndex = events.length - 1,+): Response {const response = createEagerStreamResponse(events);- response.headers.set("x-eve-stream-tail-index", String(events.length - 1));+ response.headers.set("x-eve-stream-tail-index", String(tailIndex));return response;}@@ -662,8 +665,8 @@ describe("useEveAgent", () => {).rejects.toThrow("requires initialSession or session");});- it("automatically replays an initial session when resume is enabled", async () => {- const events = [+ it("keeps settled hydrated history visible without publishing an active-turn status", async () => {+ const events = stampTestEvents([createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),createMessageCompletedEvent({message: "Hi there.",@@ -672,17 +675,18 @@ describe("useEveAgent", () => {turnId: "turn_1",}),createSessionWaitingEvent(),- ];+ ]);const fetchMock = vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createBoundedStreamResponse(events))+ .mockResolvedValueOnce(createBoundedStreamResponse([], events.length - 1)).mockResolvedValueOnce(createEagerStreamResponse([]));let helpers: UseEveAgentHelpers<EveMessageData> | undefined;const statuses: string[] = [];function TestComponent() {helpers = useEveAgent({- initialSession: { sessionId: "session_1", streamIndex: 0 },+ initialEvents: events,+ initialSession: { sessionId: "session_1", streamIndex: events.length },resume: true,});statuses.push(helpers.status);@@ -691,11 +695,13 @@ describe("useEveAgent", () => {await act(async () => {create(createElement(TestComponent));- await vi.waitFor(() => expect(helpers?.events).toHaveLength(events.length));+ await vi.waitFor(() => expect(helpers?.status).toBe("ready"));});expect(fetchMock).toHaveBeenCalledTimes(2);- expect(statuses[0]).toBe("submitted");+ expect(statuses[0]).toBe("resuming");+ expect(statuses).not.toContain("submitted");+ expect(statuses).not.toContain("streaming");expect(helpers?.status).toBe("ready");expect(helpers?.data).toEqual(completedTurnData({diff --git a/packages/eve/src/react/use-eve-agent.ts b/packages/eve/src/react/use-eve-agent.tsindex c20f42779..00481c992 100644--- a/packages/eve/src/react/use-eve-agent.ts+++ b/packages/eve/src/react/use-eve-agent.ts@@ -29,6 +29,7 @@ export type { PrepareSend };* Lifecycle status of an eve agent session.** - `"ready"`: idle, accepting a new turn.+ * - `"resuming"`: checking an attached session for events; submission is disabled.* - `"submitted"`: a turn was sent, no stream events received yet.* - `"streaming"`: stream events are arriving for the active turn.* - `"error"`: the last turn ended in a terminal failure (see `snapshot.error`).@@ -220,7 +221,7 @@ export function useEveAgent<TData>();const visibleSnapshot =autoResumePending && snapshot.status === "ready"- ? { ...snapshot, status: "submitted" as const }+ ? { ...snapshot, status: "resuming" as const }: snapshot;return useMemo(diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.tsindex 97ec6af7f..efa09523f 100644--- a/packages/eve/src/setup/scaffold/create/web-template.ts+++ b/packages/eve/src/setup/scaffold/create/web-template.ts@@ -5,7 +5,7 @@ export const WEB_APP_TEMPLATE_FILES = {"agent/channels/eve.ts":'import { eveChannel } from "eve/channels/eve";\nimport { localDev, placeholderAuth, vercelOidc } from "eve/channels/auth";\n\nexport default eveChannel({\n auth: [\n // Lets the eve TUI and your Vercel deployments reach the deployed agent.\n vercelOidc(),\n // Open on localhost for `eve dev` and the REPL; ignored in production.\n localDev(),\n // This placeholder will not allow browser requests in production.\n // Replace it with your app\'s auth provider, like Auth.js or Clerk,\n // or use none() for a public demo.\n placeholderAuth(),\n ],\n});\n',"app/_components/agent-chat.tsx":- '"use client";\n\nimport type { UserContent } from "ai";\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon, BrainIcon, PlusIcon, SquareIcon } from "lucide-react";\nimport { useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n ConversationTopFade,\n} from "@/components/ai-elements/conversation";\nimport { Message, MessageContent } from "@/components/ai-elements/message";\nimport {\n PromptInput,\n PromptInputButton,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n} from "@/components/ai-elements/prompt-input";\nimport { Shimmer } from "@/components/ai-elements/shimmer";\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\nimport { AgentMessage } from "./agent-message";\n\nconst AGENT_NAME = "__EVE_INIT_APP_NAME__";\n\nexport function AgentChat({\n sessionId,\n sessionless = false,\n}: {\n readonly sessionId?: string;\n readonly sessionless?: boolean;\n}) {\n const [cancellationError, setCancellationError] = useState<string>();\n const agent = useEveAgent({\n initialSession:\n sessionId === undefined\n ? undefined\n : {\n sessionId,\n streamIndex: 0,\n },\n resume: sessionId !== undefined,\n onSessionChange(session) {\n if (sessionId === undefined && session !== undefined) {\n // Next patches window.history to navigate, which would detach the active stream.\n History.prototype.replaceState.call(\n window.history,\n window.history.state,\n "",\n `/s/${encodeURIComponent(session.sessionId)}`,\n );\n }\n },\n });\n\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isRestoring = sessionId !== undefined && agent.events.length === 0 && isBusy;\n const isEmpty = agent.data.messages.length === 0;\n const lastMessage = agent.data.messages.at(-1);\n const isPendingAssistantShell =\n lastMessage?.role === "assistant" &&\n lastMessage.parts.every((part) => part.type === "step-start");\n const showPendingThinking =\n isBusy &&\n (agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);\n const turnFailure = isBusy ? undefined : getLatestTurnFailure(agent.events);\n const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;\n const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;\n const showConversationLayout = isRestoring || hasConversationContent;\n const activeSessionId = sessionId ?? agent.session?.sessionId;\n\n const requestCancellation = () => {\n setCancellationError(undefined);\n void agent.cancel().catch((error: unknown) => {\n setCancellationError(toErrorMessage(error));\n });\n };\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if ((text.length === 0 && message.files.length === 0) || isRestoring) return;\n\n setCancellationError(undefined);\n const options = isBusy ? { turnPolicy: "steer" as const } : undefined;\n\n if (message.files.length === 0) {\n await agent.send(text, options);\n return;\n }\n\n const parts: UserContent = [];\n if (text.length > 0) {\n parts.push({ text, type: "text" });\n }\n for (const file of message.files) {\n parts.push({\n data: file.url,\n filename: file.filename,\n mediaType: file.mediaType,\n type: "file",\n });\n }\n\n await agent.send(parts, options);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea disabled={isRestoring} placeholder="Send a message…" />\n {isBusy && !isRestoring ? (\n <PromptInputButton\n aria-label="Stop"\n className="absolute right-12 bottom-2.5 rounded-full"\n onClick={requestCancellation}\n variant="default"\n >\n <SquareIcon className="size-3 fill-current" />\n </PromptInputButton>\n ) : null}\n <PromptInputSubmit disabled={isRestoring} status={isBusy ? undefined : agent.status} />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {showConversationLayout ? (\n <ChatHeader canStartNewChat={activeSessionId !== undefined} />\n ) : null}\n\n {showConversationLayout ? (\n <Conversation\n className="min-h-0 flex-1"\n initial={sessionId === undefined ? undefined : false}\n resize={activeSessionId === undefined ? "smooth" : "instant"}\n scrollRestorationKey={\n isEmpty || activeSessionId === undefined\n ? undefined\n : `eve:web-chat-scroll:${activeSessionId}`\n }\n >\n <ConversationTopFade className="top-14" />\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 pt-20 pb-36 sm:px-6">\n {agent.data.messages.map((message, index) =>\n showPendingThinking &&\n isPendingAssistantShell &&\n message.id === lastMessage.id ? null : (\n <AgentMessage\n canRespond={!isBusy}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n onInputResponses={(inputResponses) => {\n setCancellationError(undefined);\n return agent.respond(inputResponses);\n }}\n />\n ),\n )}\n {showPendingThinking ? <PendingThinking /> : null}\n {errorMessage ? <ErrorMessage message={errorMessage} /> : null}\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n ) : null}\n\n <div\n className={cn(\n "mx-auto w-full px-4 sm:px-6",\n showConversationLayout\n ? "fixed bottom-0 left-1/2 z-20 max-w-3xl -translate-x-1/2 bg-gradient-to-t from-background via-background to-transparent pt-4 pb-6"\n : "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]",\n )}\n >\n {showConversationLayout ? null : (\n <div className="flex flex-col items-center gap-3 text-center">\n <h1 className="font-medium text-5xl tracking-tighter">{AGENT_NAME}</h1>\n </div>\n )}\n <div className="w-full">{composer}</div>\n </div>\n </main>\n );\n}\n\nfunction ErrorMessage({ message }: { readonly message: string }) {\n return (\n <Message className="max-w-full" from="assistant">\n <MessageContent>\n <div\n className="flex w-full items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm"\n role="alert"\n >\n <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />\n <div>\n <p className="font-medium">Request failed</p>\n <p className="mt-0.5 text-muted-foreground">{message}</p>\n </div>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction ChatHeader({ canStartNewChat }: { readonly canStartNewChat: boolean }) {\n return (\n <header className="pointer-events-none fixed top-0 right-0 left-0 z-20 h-14">\n <div className="relative mx-auto flex h-full w-full max-w-3xl items-center justify-center bg-background px-24">\n <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>\n {canStartNewChat ? (\n <Button\n aria-label="Start a new chat"\n className="pointer-events-auto fixed top-2 right-6"\n onClick={() => window.location.assign("/s")}\n size="sm"\n type="button"\n variant="ghost"\n >\n <PlusIcon className="size-4" />\n <span className="hidden sm:inline">New chat</span>\n </Button>\n ) : null}\n </div>\n </header>\n );\n}\n\nfunction PendingThinking() {\n return (\n <Message aria-live="polite" from="assistant">\n <MessageContent>\n <div className="mb-4 flex w-full items-center gap-2 text-muted-foreground text-sm">\n <BrainIcon className="size-4" />\n <Shimmer duration={1}>Thinking</Shimmer>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : "Unable to cancel the response.";\n}\n\nfunction getLatestTurnFailure(\n events: ReturnType<typeof useEveAgent>["events"],\n): string | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n\n if (event.type === "turn.failed") {\n return event.data.code === "MODEL_CALL_FAILED"\n ? "The model is temporarily unavailable. Please try again."\n : event.data.message;\n }\n\n if (event.type === "turn.completed" || event.type === "turn.cancelled") {\n return undefined;\n }\n\n if (event.type === "message.received") {\n return undefined;\n }\n }\n\n return undefined;\n}\n',+ '"use client";\n\nimport type { UserContent } from "ai";\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon, BrainIcon, PlusIcon, SquareIcon } from "lucide-react";\nimport { useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n ConversationTopFade,\n} from "@/components/ai-elements/conversation";\nimport { Message, MessageContent } from "@/components/ai-elements/message";\nimport {\n PromptInput,\n PromptInputButton,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n} from "@/components/ai-elements/prompt-input";\nimport { Shimmer } from "@/components/ai-elements/shimmer";\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\nimport { AgentMessage } from "./agent-message";\n\nconst AGENT_NAME = "__EVE_INIT_APP_NAME__";\n\nexport function AgentChat({\n sessionId,\n sessionless = false,\n}: {\n readonly sessionId?: string;\n readonly sessionless?: boolean;\n}) {\n const [cancellationError, setCancellationError] = useState<string>();\n const agent = useEveAgent({\n initialSession:\n sessionId === undefined\n ? undefined\n : {\n sessionId,\n streamIndex: 0,\n },\n resume: sessionId !== undefined,\n onSessionChange(session) {\n if (sessionId === undefined && session !== undefined) {\n // Next patches window.history to navigate, which would detach the active stream.\n History.prototype.replaceState.call(\n window.history,\n window.history.state,\n "",\n `/s/${encodeURIComponent(session.sessionId)}`,\n );\n }\n },\n });\n\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isResuming = agent.status === "resuming";\n const isEmpty = agent.data.messages.length === 0;\n const lastMessage = agent.data.messages.at(-1);\n const isPendingAssistantShell =\n lastMessage?.role === "assistant" &&\n lastMessage.parts.every((part) => part.type === "step-start");\n const showPendingThinking =\n isBusy &&\n (agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);\n const turnFailure = isBusy || isResuming ? undefined : getLatestTurnFailure(agent.events);\n const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;\n const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;\n const showConversationLayout = isResuming || hasConversationContent;\n const activeSessionId = sessionId ?? agent.session?.sessionId;\n\n const requestCancellation = () => {\n setCancellationError(undefined);\n void agent.cancel().catch((error: unknown) => {\n setCancellationError(toErrorMessage(error));\n });\n };\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if ((text.length === 0 && message.files.length === 0) || isResuming) return;\n\n setCancellationError(undefined);\n const options = isBusy ? { turnPolicy: "steer" as const } : undefined;\n\n if (message.files.length === 0) {\n await agent.send(text, options);\n return;\n }\n\n const parts: UserContent = [];\n if (text.length > 0) {\n parts.push({ text, type: "text" });\n }\n for (const file of message.files) {\n parts.push({\n data: file.url,\n filename: file.filename,\n mediaType: file.mediaType,\n type: "file",\n });\n }\n\n await agent.send(parts, options);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea disabled={isResuming} placeholder="Send a message…" />\n {isBusy ? (\n <PromptInputButton\n aria-label="Stop"\n className="absolute right-12 bottom-2.5 rounded-full"\n onClick={requestCancellation}\n variant="default"\n >\n <SquareIcon className="size-3 fill-current" />\n </PromptInputButton>\n ) : null}\n <PromptInputSubmit\n disabled={isResuming}\n status={isBusy || isResuming ? undefined : agent.status}\n />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {showConversationLayout ? (\n <ChatHeader canStartNewChat={activeSessionId !== undefined} />\n ) : null}\n\n {showConversationLayout ? (\n <Conversation\n className="min-h-0 flex-1"\n initial={sessionId === undefined ? undefined : false}\n resize={activeSessionId === undefined ? "smooth" : "instant"}\n scrollRestorationKey={\n isEmpty || activeSessionId === undefined\n ? undefined\n : `eve:web-chat-scroll:${activeSessionId}`\n }\n >\n <ConversationTopFade className="top-14" />\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 pt-20 pb-36 sm:px-6">\n {agent.data.messages.map((message, index) =>\n showPendingThinking &&\n isPendingAssistantShell &&\n message.id === lastMessage.id ? null : (\n <AgentMessage\n canRespond={!isBusy && !isResuming}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n onInputResponses={(inputResponses) => {\n setCancellationError(undefined);\n return agent.respond(inputResponses);\n }}\n />\n ),\n )}\n {showPendingThinking ? <PendingThinking /> : null}\n {errorMessage ? <ErrorMessage message={errorMessage} /> : null}\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n ) : null}\n\n <div\n className={cn(\n "mx-auto w-full px-4 sm:px-6",\n showConversationLayout\n ? "fixed bottom-0 left-1/2 z-20 max-w-3xl -translate-x-1/2 bg-gradient-to-t from-background via-background to-transparent pt-4 pb-6"\n : "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]",\n )}\n >\n {showConversationLayout ? null : (\n <div className="flex flex-col items-center gap-3 text-center">\n <h1 className="font-medium text-5xl tracking-tighter">{AGENT_NAME}</h1>\n </div>\n )}\n <div className="w-full">{composer}</div>\n </div>\n </main>\n );\n}\n\nfunction ErrorMessage({ message }: { readonly message: string }) {\n return (\n <Message className="max-w-full" from="assistant">\n <MessageContent>\n <div\n className="flex w-full items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm"\n role="alert"\n >\n <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />\n <div>\n <p className="font-medium">Request failed</p>\n <p className="mt-0.5 text-muted-foreground">{message}</p>\n </div>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction ChatHeader({ canStartNewChat }: { readonly canStartNewChat: boolean }) {\n return (\n <header className="pointer-events-none fixed top-0 right-0 left-0 z-20 h-14">\n <div className="relative mx-auto flex h-full w-full max-w-3xl items-center justify-center bg-background px-24">\n <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>\n {canStartNewChat ? (\n <Button\n aria-label="Start a new chat"\n className="pointer-events-auto fixed top-2 right-6"\n onClick={() => window.location.assign("/s")}\n size="sm"\n type="button"\n variant="ghost"\n >\n <PlusIcon className="size-4" />\n <span className="hidden sm:inline">New chat</span>\n </Button>\n ) : null}\n </div>\n </header>\n );\n}\n\nfunction PendingThinking() {\n return (\n <Message aria-live="polite" from="assistant">\n <MessageContent>\n <div className="mb-4 flex w-full items-center gap-2 text-muted-foreground text-sm">\n <BrainIcon className="size-4" />\n <Shimmer duration={1}>Thinking</Shimmer>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : "Unable to cancel the response.";\n}\n\nfunction getLatestTurnFailure(\n events: ReturnType<typeof useEveAgent>["events"],\n): string | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n\n if (event.type === "turn.failed") {\n return event.data.code === "MODEL_CALL_FAILED"\n ? "The model is temporarily unavailable. Please try again."\n : event.data.message;\n }\n\n if (event.type === "turn.completed" || event.type === "turn.cancelled") {\n return undefined;\n }\n\n if (event.type === "message.received") {\n return undefined;\n }\n }\n\n return undefined;\n}\n',"app/_components/agent-message.tsx":'"use client";\n\nimport type {\n EveAuthorizationPart,\n EveDynamicToolPart,\n EveMessage,\n EveMessageInputRequest,\n EveMessagePart,\n} from "eve/react";\nimport {\n CheckCircleIcon,\n ExternalLinkIcon,\n FileIcon,\n ImageIcon,\n KeyRoundIcon,\n XCircleIcon,\n} from "lucide-react";\nimport { Message, MessageContent, MessageResponse } from "@/components/ai-elements/message";\nimport {\n Question,\n QuestionActions,\n QuestionDescription,\n QuestionInput,\n QuestionOption,\n QuestionOptions,\n QuestionPrompt,\n type QuestionResponse,\n QuestionSubmit,\n} from "@/components/ai-elements/question";\nimport { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";\nimport {\n Tool,\n ToolContent,\n ToolHeader,\n ToolInput,\n ToolOutput,\n} from "@/components/ai-elements/tool";\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\n\nexport type AgentInputResponse = {\n readonly optionId?: string;\n readonly requestId: string;\n readonly text?: string;\n};\n\ntype EveFilePart = Extract<EveMessagePart, { type: "file" }>;\n\nexport function AgentMessage({\n canRespond,\n isStreaming,\n message,\n onInputResponses,\n}: {\n readonly canRespond: boolean;\n readonly isStreaming: boolean;\n readonly message: EveMessage;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n}) {\n const lastTextIndex = message.parts.reduce(\n (last, part, index) => (part.type === "text" ? index : last),\n -1,\n );\n const hasAssistantText =\n message.role === "assistant" &&\n message.parts.some((part) => part.type === "text" && part.text.length > 0);\n\n return (\n <Message\n data-optimistic={message.metadata?.optimistic ? "true" : undefined}\n from={message.role}\n >\n <MessageContent>\n {message.parts.map((part, index) =>\n hasAssistantText && part.type === "reasoning" ? null : (\n <AgentMessagePart\n canRespond={canRespond}\n key={partKey(part, index)}\n onInputResponses={onInputResponses}\n part={part}\n showCaret={isStreaming && message.role === "assistant" && index === lastTextIndex}\n />\n ),\n )}\n </MessageContent>\n </Message>\n );\n}\n\nfunction AgentMessagePart({\n canRespond,\n onInputResponses,\n part,\n showCaret,\n}: {\n readonly canRespond: boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveMessagePart;\n readonly showCaret: boolean;\n}) {\n switch (part.type) {\n case "step-start":\n return null;\n case "text":\n return (\n <MessageResponse caret="block" isAnimating={showCaret}>\n {part.text}\n </MessageResponse>\n );\n case "reasoning":\n return (\n <Reasoning defaultOpen isStreaming={part.state === "streaming"}>\n <ReasoningTrigger />\n <ReasoningContent>{part.text}</ReasoningContent>\n </Reasoning>\n );\n case "file":\n return <AttachmentPart part={part} />;\n case "authorization":\n return <AuthorizationPrompt part={part} />;\n case "dynamic-tool": {\n const inputRequest = part.toolMetadata?.eve?.inputRequest;\n if (inputRequest?.kind === "question") {\n return (\n <QuestionRequest\n canRespond={canRespond}\n inputRequest={inputRequest}\n inputResponse={part.toolMetadata?.eve?.inputResponse}\n onInputResponses={onInputResponses}\n />\n );\n }\n\n return (\n <Tool\n defaultOpen={part.state === "approval-requested" || part.state === "approval-responded"}\n >\n <ToolHeader\n state={part.state}\n title={part.toolName}\n toolName={part.toolName}\n type="dynamic-tool"\n />\n <ToolContent>\n <ToolInput input={part.input} />\n <InputRequestActions\n canRespond={canRespond}\n part={part}\n onInputResponses={onInputResponses}\n />\n <ToolOutput errorText={part.errorText} output={part.output} />\n </ToolContent>\n </Tool>\n );\n }\n }\n}\n\nfunction QuestionRequest({\n canRespond,\n inputRequest,\n inputResponse,\n onInputResponses,\n}: {\n readonly canRespond: boolean;\n readonly inputRequest: EveMessageInputRequest;\n readonly inputResponse?: AgentInputResponse;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n}) {\n const selectedOption = inputRequest.options?.find(\n (option) => option.id === inputResponse?.optionId,\n );\n const hasOptions = (inputRequest.options?.length ?? 0) > 0;\n const acceptsFreeform = inputRequest.allowFreeform === true || !hasOptions;\n\n const submitResponse = ({ selectedValues, text }: QuestionResponse) =>\n onInputResponses([\n {\n optionId: selectedValues[0],\n requestId: inputRequest.requestId,\n text,\n },\n ]);\n\n return (\n <Question\n defaultValue={{\n selectedValues: inputResponse?.optionId ? [inputResponse.optionId] : [],\n text: inputResponse?.text ?? "",\n }}\n disabled={!canRespond || inputResponse !== undefined}\n onSubmit={submitResponse}\n >\n <QuestionPrompt>{inputRequest.prompt}</QuestionPrompt>\n {hasOptions ? (\n <QuestionOptions className="flex-col items-stretch" aria-label={inputRequest.prompt}>\n {inputRequest.options?.map((option) => (\n <QuestionOption className="justify-start text-left" key={option.id} value={option.id}>\n <span>\n <span className="block">{option.label}</span>\n {option.description ? (\n <span className="block font-normal text-xs opacity-70">{option.description}</span>\n ) : null}\n </span>\n </QuestionOption>\n ))}\n </QuestionOptions>\n ) : null}\n {acceptsFreeform ? (\n <QuestionInput aria-label="Answer" placeholder="Type your answer…" />\n ) : null}\n {inputResponse ? (\n <QuestionDescription>\n Responded: {selectedOption?.label ?? inputResponse.text ?? inputResponse.optionId}\n </QuestionDescription>\n ) : (\n <QuestionActions>\n <QuestionSubmit>Answer</QuestionSubmit>\n </QuestionActions>\n )}\n </Question>\n );\n}\n\nfunction AttachmentPart({ part }: { readonly part: EveFilePart }) {\n const label = part.filename ?? "Attachment";\n const detail = [part.mediaType, formatBytes(part.size)].filter(Boolean).join(" - ");\n const isImage = part.mediaType.startsWith("image/") && part.url !== undefined;\n const Icon = isImage ? ImageIcon : FileIcon;\n const body = (\n <span className="flex max-w-sm items-center gap-3 rounded-md border bg-background/60 p-2 text-sm">\n {isImage ? (\n <img alt={label} className="size-12 shrink-0 rounded-sm object-cover" src={part.url} />\n ) : (\n <span className="flex size-10 shrink-0 items-center justify-center rounded-sm bg-muted text-muted-foreground">\n <Icon className="size-4" />\n </span>\n )}\n <span className="min-w-0 flex-1">\n <span className="block truncate font-medium">{label}</span>\n {detail ? <span className="block truncate text-muted-foreground">{detail}</span> : null}\n </span>\n {part.url ? <ExternalLinkIcon className="size-4 shrink-0 text-muted-foreground" /> : null}\n </span>\n );\n\n return part.url ? (\n <a href={part.url} rel="noreferrer" target="_blank">\n {body}\n </a>\n ) : (\n body\n );\n}\n\nfunction AuthorizationPrompt({ part }: { readonly part: EveAuthorizationPart }) {\n const isAuthorized = part.state === "completed" && part.outcome === "authorized";\n const isCompleted = part.state === "completed";\n const Icon = isAuthorized ? CheckCircleIcon : isCompleted ? XCircleIcon : KeyRoundIcon;\n const instructions = part.authorization?.instructions;\n const shouldShowInstructions = instructions !== undefined && instructions !== part.description;\n\n return (\n <div\n className={cn(\n "space-y-3 rounded-md border p-3",\n isAuthorized\n ? "border-emerald-500/30 bg-emerald-500/5"\n : isCompleted\n ? "border-destructive/30 bg-destructive/5"\n : "border-blue-500/30 bg-blue-500/5",\n )}\n >\n <div className="flex items-start gap-3">\n <span\n className={cn(\n "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full",\n isAuthorized\n ? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"\n : isCompleted\n ? "bg-destructive/10 text-destructive"\n : "bg-blue-500/10 text-blue-700 dark:text-blue-300",\n )}\n >\n <Icon className="size-4" />\n </span>\n <div className="min-w-0 flex-1 space-y-2">\n <p className="font-medium text-sm">{authorizationTitle(part)}</p>\n <p className="text-muted-foreground text-sm">{authorizationDescription(part)}</p>\n {shouldShowInstructions ? (\n <p className="text-muted-foreground text-sm">{instructions}</p>\n ) : null}\n {part.state === "required" && part.authorization?.userCode ? (\n <div className="flex flex-wrap items-center gap-2 text-sm">\n <span className="text-muted-foreground">Code</span>\n <code className="rounded-md bg-background px-2 py-1 font-mono">\n {part.authorization.userCode}\n </code>\n </div>\n ) : null}\n {part.state === "required" && part.authorization?.url ? (\n <Button asChild size="sm">\n <a href={part.authorization.url} rel="noreferrer" target="_blank">\n <ExternalLinkIcon className="size-4" />\n Sign in with {part.displayName}\n </a>\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n );\n}\n\nfunction authorizationTitle(part: EveAuthorizationPart): string {\n if (part.state === "required") {\n return `Connect ${part.displayName}`;\n }\n if (part.outcome === "authorized") {\n return `${part.displayName} connected`;\n }\n return `${part.displayName} authorization ${formatAuthorizationOutcome(part.outcome)}`;\n}\n\nfunction authorizationDescription(part: EveAuthorizationPart): string {\n if (part.state === "required") {\n return part.description;\n }\n if (part.outcome === "authorized") {\n return `${part.displayName} connected.`;\n }\n const tail = part.reason !== undefined ? ` (${part.reason})` : "";\n return `${part.displayName} authorization ${formatAuthorizationOutcome(part.outcome)}${tail}.`;\n}\n\nfunction formatAuthorizationOutcome(outcome: NonNullable<EveAuthorizationPart["outcome"]>): string {\n switch (outcome) {\n case "authorized":\n return "authorized";\n case "declined":\n return "declined";\n case "failed":\n return "failed";\n case "timed-out":\n return "timed out";\n }\n}\n\nfunction formatBytes(size: number | undefined): string | undefined {\n if (size === undefined) {\n return undefined;\n }\n if (size < 1024) {\n return `${size} B`;\n }\n if (size < 1024 * 1024) {\n return `${(size / 1024).toFixed(1)} KB`;\n }\n return `${(size / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nfunction InputRequestActions({\n canRespond,\n onInputResponses,\n part,\n}: {\n readonly canRespond: boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveDynamicToolPart;\n}) {\n const inputRequest = part.toolMetadata?.eve?.inputRequest;\n if (!inputRequest) {\n return null;\n }\n\n const inputResponse = part.toolMetadata?.eve?.inputResponse;\n const selectedOption = inputRequest.options?.find(\n (option) => option.id === inputResponse?.optionId,\n );\n\n return (\n <div className="space-y-3 rounded-md border border-yellow-500/30 bg-yellow-500/5 p-3">\n <p className="text-muted-foreground text-sm">{inputRequest.prompt}</p>\n {inputResponse ? (\n <p className="font-medium text-sm">\n Responded: {selectedOption?.label ?? inputResponse.text ?? inputResponse.optionId}\n </p>\n ) : (\n <div className="flex flex-wrap gap-2">\n {inputRequest.options?.map((option) => (\n <Button\n disabled={!canRespond}\n key={option.id}\n onClick={() => {\n void onInputResponses([\n {\n optionId: option.id,\n requestId: inputRequest.requestId,\n },\n ]);\n }}\n size="sm"\n type="button"\n variant={option.style === "danger" ? "destructive" : "default"}\n >\n {option.label}\n </Button>\n ))}\n </div>\n )}\n </div>\n );\n}\n\nfunction partKey(part: EveMessagePart, index: number): string {\n switch (part.type) {\n case "authorization":\n return `authorization:${part.turnId}:${part.stepIndex}:${part.name}`;\n case "dynamic-tool":\n return part.toolCallId;\n default:\n return `${part.type}:${index}`;\n }\n}\n',"app/globals.css":diff --git a/packages/eve/src/setup/scaffold/index.integration.test.ts b/packages/eve/src/setup/scaffold/index.integration.test.tsindex 58b1ac759..643856d39 100644--- a/packages/eve/src/setup/scaffold/index.integration.test.ts+++ b/packages/eve/src/setup/scaffold/index.integration.test.ts@@ -245,8 +245,10 @@ describe("ensureChannel", () => {join(projectRoot, "app/_components/agent-chat.tsx"),"utf8",);- expect(agentChatSource).toContain("<PromptInputTextarea disabled={isRestoring}");+ expect(agentChatSource).toContain("<PromptInputTextarea disabled={isResuming}");expect(agentChatSource).toContain('turnPolicy: "steer"');+ expect(agentChatSource).toContain('const isResuming = agent.status === "resuming"');+ expect(agentChatSource).toContain("canRespond={!isBusy && !isResuming}");expect(agentChatSource).toContain("{showPendingThinking ? <PendingThinking /> : null}");expect(agentChatSource).not.toContain("StatusDot");await expect(readFile(join(projectRoot, "next.config.ts"), "utf8")).resolves.toContain(diff --git a/packages/eve/src/svelte/use-eve-agent.ts b/packages/eve/src/svelte/use-eve-agent.tsindex aab217282..f7abc8f3a 100644--- a/packages/eve/src/svelte/use-eve-agent.ts+++ b/packages/eve/src/svelte/use-eve-agent.ts@@ -26,9 +26,9 @@ import type { MessageStreamEvent } from "#protocol/message.js";export type { PrepareSend };/**- * Session lifecycle phase: `"ready"` (idle), `"submitted"` (request sent,- * awaiting the first stream event), `"streaming"` (events arriving), or- * `"error"`.+ * Session lifecycle phase: `"ready"` (idle), `"resuming"` (checking an+ * attached session), `"submitted"` (request sent, awaiting the first stream+ * event), `"streaming"` (events arriving), or `"error"`.*/export type UseEveAgentStatus = EveAgentStoreStatus;@@ -71,7 +71,11 @@ export interface UseEveAgentReturn<TData> {) => Promise<void>;/** Current session identity and stream cursor. */readonly session: ClientSessionState | undefined;- /** Lifecycle phase: `"ready"` (idle), `"submitted"` (request sent, awaiting first event), `"streaming"` (events arriving), or `"error"`. */+ /**+ * Lifecycle phase: `"ready"` (idle), `"resuming"` (checking an attached+ * session), `"submitted"` (request sent, awaiting first event), `"streaming"`+ * (events arriving), or `"error"`.+ */readonly status: UseEveAgentStatus;}diff --git a/packages/eve/src/vue/use-eve-agent.test.ts b/packages/eve/src/vue/use-eve-agent.test.tsindex cb49c3639..ed7cc1af5 100644--- a/packages/eve/src/vue/use-eve-agent.test.ts+++ b/packages/eve/src/vue/use-eve-agent.test.ts@@ -364,7 +364,7 @@ describe("useEveAgent (Vue composable wiring)", () => {);if (agent === undefined) throw new Error("effect scope did not run");- expect(agent.status.value).toBe("submitted");+ expect(agent.status.value).toBe("resuming");await vi.waitFor(() => expect(agent.events.value).toHaveLength(events.length));expect(agent.status.value).toBe("ready");expect(agent.data.value).toEqual(diff --git a/packages/eve/src/vue/use-eve-agent.ts b/packages/eve/src/vue/use-eve-agent.tsindex 5f88d02d3..97fd1bfbb 100644--- a/packages/eve/src/vue/use-eve-agent.ts+++ b/packages/eve/src/vue/use-eve-agent.ts@@ -26,9 +26,9 @@ import type {export type { PrepareSend };/**- * Lifecycle phase of a `useEveAgent` session: `"ready"` (idle), `"submitted"`- * (request sent, awaiting first event), `"streaming"` (events arriving), or- * `"error"`.+ * Lifecycle phase of a `useEveAgent` session: `"ready"` (idle), `"resuming"`+ * (checking an attached session), `"submitted"` (request sent, awaiting first+ * event), `"streaming"` (events arriving), or `"error"`.*/export type UseEveAgentStatus = EveAgentStoreStatus;@@ -69,7 +69,11 @@ export interface UseEveAgentReturn<TData> {) => Promise<void>;/** Current session identity and stream cursor. */readonly session: ComputedRef<ClientSessionState | undefined>;- /** Lifecycle phase: `"ready"` (idle), `"submitted"` (request sent, awaiting first event), `"streaming"` (events arriving), or `"error"`. */+ /**+ * Lifecycle phase: `"ready"` (idle), `"resuming"` (checking an attached+ * session), `"submitted"` (request sent, awaiting first event), `"streaming"`+ * (events arriving), or `"error"`.+ */readonly status: ComputedRef<UseEveAgentStatus>;}