Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): resume Web Chat sessions from URLs (#2379)

Casey Gowriea4fd288bbef8
diff --git a/.changeset/resume-web-chat-sessions.md b/.changeset/resume-web-chat-sessions.md
new file mode 100644
index 000000000..5fc77cd15
--- /dev/null
+++ b/.changeset/resume-web-chat-sessions.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add declarative `resume: true` and imperative `resume()` support for replaying durable frontend sessions and following in-flight turns. Generated Web Chat apps now keep session IDs in `/s/{sessionId}` URLs, restore conversations on reload, and provide a sessionless `/s` route for starting a new chat.
diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/app/_components/authenticated-agent-chat.tsx b/apps/docs/registry/channel/web-sign-in-with-vercel/app/_components/authenticated-agent-chat.tsx
new file mode 100644
index 000000000..7f315db4a
--- /dev/null
+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/app/_components/authenticated-agent-chat.tsx
@@ -0,0 +1,30 @@
+import { headers } from "next/headers";
+import { auth } from "@/lib/auth";
+import { AgentChat } from "./agent-chat";
+import { AccountControl, SignIn } from "./web-chat-auth";
+
+export async function AuthenticatedAgentChat({
+ sessionId,
+ sessionless,
+}: {
+ readonly sessionId?: string;
+ readonly sessionless?: boolean;
+}) {
+ if (process.env.NODE_ENV === "development") {
+ return <AgentChat sessionId={sessionId} sessionless={sessionless} />;
+ }
+
+ const session = await auth.api.getSession({ headers: await headers() });
+ if (!session) return <SignIn />;
+
+ return (
+ <>
+ <AgentChat sessionId={sessionId} sessionless={sessionless} />
+ <AccountControl
+ email={session.user.email}
+ image={session.user.image}
+ name={session.user.name}
+ />
+ </>
+ );
+}
diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/app/page.tsx b/apps/docs/registry/channel/web-sign-in-with-vercel/app/page.tsx
index 3d9a175e9..46428612c 100644
--- a/apps/docs/registry/channel/web-sign-in-with-vercel/app/page.tsx
+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/app/page.tsx
@@ -1,26 +1,5 @@
-import { headers } from "next/headers";
-import { AgentChat } from "./_components/agent-chat";
-import { AccountControl, SignIn } from "./_components/web-chat-auth";
-import { auth } from "@/lib/auth";
+import { AuthenticatedAgentChat } from "./_components/authenticated-agent-chat";
-export default async function Page() {
- if (process.env.NODE_ENV === "development") {
- return <AgentChat />;
- }
-
- const session = await auth.api.getSession({ headers: await headers() });
- if (!session) {
- return <SignIn />;
- }
-
- return (
- <>
- <AgentChat />
- <AccountControl
- email={session.user.email}
- image={session.user.image}
- name={session.user.name}
- />
- </>
- );
+export default function Page() {
+ return <AuthenticatedAgentChat />;
}
diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/app/s/[sessionId]/page.tsx b/apps/docs/registry/channel/web-sign-in-with-vercel/app/s/[sessionId]/page.tsx
new file mode 100644
index 000000000..33c287861
--- /dev/null
+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/app/s/[sessionId]/page.tsx
@@ -0,0 +1,10 @@
+import { AuthenticatedAgentChat } from "@/app/_components/authenticated-agent-chat";
+
+export default async function SessionPage({
+ params,
+}: {
+ readonly params: Promise<{ readonly sessionId: string }>;
+}) {
+ const { sessionId } = await params;
+ return <AuthenticatedAgentChat sessionId={sessionId} />;
+}
diff --git a/apps/docs/registry/channel/web-sign-in-with-vercel/app/s/page.tsx b/apps/docs/registry/channel/web-sign-in-with-vercel/app/s/page.tsx
new file mode 100644
index 000000000..27175c05c
--- /dev/null
+++ b/apps/docs/registry/channel/web-sign-in-with-vercel/app/s/page.tsx
@@ -0,0 +1,5 @@
+import { AuthenticatedAgentChat } from "@/app/_components/authenticated-agent-chat";
+
+export default function NewSessionPage() {
+ return <AuthenticatedAgentChat sessionless />;
+}
diff --git a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx b/apps/docs/registry/channel/web/app/_components/agent-chat.tsx
index 7d46d58b7..1a81ba9ee 100644
--- a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx
+++ b/apps/docs/registry/channel/web/app/_components/agent-chat.tsx
@@ -2,7 +2,7 @@
import type { UserContent } from "ai";
import { useEveAgent } from "eve/react";
-import { AlertCircleIcon, BrainIcon } from "lucide-react";
+import { AlertCircleIcon, BrainIcon, PlusIcon } from "lucide-react";
import { useState } from "react";
import {
Conversation,
@@ -17,15 +17,44 @@ import {
PromptInputTextarea,
} from "@/components/ai-elements/prompt-input";
import { Shimmer } from "@/components/ai-elements/shimmer";
+import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { AgentMessage } from "./agent-message";
const AGENT_NAME = "eve-agent";
-export function AgentChat() {
+export function AgentChat({
+ sessionId,
+ sessionless = false,
+}: {
+ readonly sessionId?: string;
+ readonly sessionless?: boolean;
+}) {
const [cancellationError, setCancellationError] = useState<string>();
- const agent = useEveAgent();
+ const agent = useEveAgent({
+ initialSession:
+ sessionId === undefined
+ ? undefined
+ : {
+ sessionId,
+ streamIndex: 0,
+ },
+ resume: sessionId !== undefined,
+ onSessionChange(session) {
+ if (sessionId === undefined && session !== undefined) {
+ // Next patches window.history to navigate, which would detach the active stream.
+ History.prototype.replaceState.call(
+ window.history,
+ window.history.state,
+ "",
+ `/s/${encodeURIComponent(session.sessionId)}`,
+ );
+ }
+ },
+ });
+
const isBusy = agent.status === "submitted" || agent.status === "streaming";
+ const isRestoring = sessionId !== undefined && agent.events.length === 0 && isBusy;
const isEmpty = agent.data.messages.length === 0;
const lastMessage = agent.data.messages.at(-1);
const isPendingAssistantShell =
@@ -36,6 +65,9 @@ export function AgentChat() {
(agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);
const turnFailure = isBusy ? undefined : getLatestTurnFailure(agent.events);
const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;
+ const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;
+ const showConversationLayout = isRestoring || hasConversationContent;
+ const activeSessionId = sessionId ?? agent.session?.sessionId;
const requestCancellation = () => {
setCancellationError(undefined);
@@ -73,37 +105,33 @@ export function AgentChat() {
const composer = (
<PromptInput onSubmit={handleSubmit}>
- <PromptInputTextarea disabled={isBusy} placeholder="Send a message…" />
- <PromptInputSubmit onStop={requestCancellation} status={agent.status} />
+ <PromptInputTextarea disabled={isBusy || isRestoring} placeholder="Send a message…" />
+ <PromptInputSubmit
+ disabled={isRestoring}
+ onStop={requestCancellation}
+ status={isRestoring ? undefined : agent.status}
+ />
</PromptInput>
);
return (
<main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">
- {isEmpty ? null : (
- <header className="flex h-14 shrink-0 items-center justify-center pl-4 pr-2">
- <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>
- </header>
- )}
-
- {errorMessage ? (
- <div className="mx-auto w-full max-w-3xl shrink-0 px-4 pt-2 sm:px-6">
- <div
- className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm"
- role="alert"
- >
- <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
- <div>
- <p className="font-medium">Request failed</p>
- <p className="mt-0.5 text-muted-foreground">{errorMessage}</p>
- </div>
- </div>
- </div>
+ {showConversationLayout ? (
+ <ChatHeader canStartNewChat={activeSessionId !== undefined} />
) : null}
- {isEmpty ? null : (
- <Conversation className="min-h-0 flex-1">
- <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 py-6 sm:px-6">
+ {showConversationLayout ? (
+ <Conversation
+ className="min-h-0 flex-1"
+ initial={sessionId === undefined ? undefined : false}
+ resize={activeSessionId === undefined ? "smooth" : "instant"}
+ scrollRestorationKey={
+ isEmpty || activeSessionId === undefined
+ ? undefined
+ : `eve:web-chat-scroll:${activeSessionId}`
+ }
+ >
+ <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 pt-20 pb-36 sm:px-6">
{agent.data.messages.map((message, index) =>
showPendingThinking &&
isPendingAssistantShell &&
@@ -123,30 +151,73 @@ export function AgentChat() {
),
)}
{showPendingThinking ? <PendingThinking /> : null}
+ {errorMessage ? <ErrorMessage message={errorMessage} /> : null}
</ConversationContent>
<ConversationScrollButton />
</Conversation>
- )}
+ ) : null}
<div
className={cn(
"mx-auto w-full px-4 sm:px-6",
- isEmpty
- ? "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]"
- : "max-w-3xl shrink-0 pb-6",
+ showConversationLayout
+ ? "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"
+ : "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]",
)}
>
- {isEmpty ? (
+ {showConversationLayout ? null : (
<div className="flex flex-col items-center gap-3 text-center">
<h1 className="font-medium text-5xl tracking-tighter">{AGENT_NAME}</h1>
</div>
- ) : null}
+ )}
<div className="w-full">{composer}</div>
</div>
</main>
);
}
+function ErrorMessage({ message }: { readonly message: string }) {
+ return (
+ <Message className="max-w-full" from="assistant">
+ <MessageContent>
+ <div
+ className="flex w-full items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm"
+ role="alert"
+ >
+ <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
+ <div>
+ <p className="font-medium">Request failed</p>
+ <p className="mt-0.5 text-muted-foreground">{message}</p>
+ </div>
+ </div>
+ </MessageContent>
+ </Message>
+ );
+}
+
+function ChatHeader({ canStartNewChat }: { readonly canStartNewChat: boolean }) {
+ return (
+ <header className="pointer-events-none fixed top-0 right-0 left-0 z-20 h-14">
+ <div className="relative mx-auto flex h-full w-full max-w-3xl items-center justify-center bg-background px-24">
+ <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>
+ {canStartNewChat ? (
+ <Button
+ aria-label="Start a new chat"
+ className="pointer-events-auto fixed top-2 right-6"
+ onClick={() => window.location.assign("/s")}
+ size="sm"
+ type="button"
+ variant="ghost"
+ >
+ <PlusIcon className="size-4" />
+ <span className="hidden sm:inline">New chat</span>
+ </Button>
+ ) : null}
+ </div>
+ </header>
+ );
+}
+
function PendingThinking() {
return (
<Message aria-live="polite" from="assistant">
diff --git a/apps/docs/registry/channel/web/app/_components/agent-message.tsx b/apps/docs/registry/channel/web/app/_components/agent-message.tsx
index c39b72b49..8209af1e2 100644
--- a/apps/docs/registry/channel/web/app/_components/agent-message.tsx
+++ b/apps/docs/registry/channel/web/app/_components/agent-message.tsx
@@ -61,6 +61,9 @@ export function AgentMessage({
(last, part, index) => (part.type === "text" ? index : last),
-1,
);
+ const hasAssistantText =
+ message.role === "assistant" &&
+ message.parts.some((part) => part.type === "text" && part.text.length > 0);
return (
<Message
@@ -68,15 +71,17 @@ export function AgentMessage({
from={message.role}
>
<MessageContent>
- {message.parts.map((part, index) => (
- <AgentMessagePart
- canRespond={canRespond}
- key={partKey(part, index)}
- onInputResponses={onInputResponses}
- part={part}
- showCaret={isStreaming && message.role === "assistant" && index === lastTextIndex}
- />
- ))}
+ {message.parts.map((part, index) =>
+ hasAssistantText && part.type === "reasoning" ? null : (
+ <AgentMessagePart
+ canRespond={canRespond}
+ key={partKey(part, index)}
+ onInputResponses={onInputResponses}
+ part={part}
+ showCaret={isStreaming && message.role === "assistant" && index === lastTextIndex}
+ />
+ ),
+ )}
</MessageContent>
</Message>
);
diff --git a/apps/docs/registry/channel/web/app/s/[sessionId]/page.tsx b/apps/docs/registry/channel/web/app/s/[sessionId]/page.tsx
new file mode 100644
index 000000000..9cffcc1c9
--- /dev/null
+++ b/apps/docs/registry/channel/web/app/s/[sessionId]/page.tsx
@@ -0,0 +1,10 @@
+import { AgentChat } from "@/app/_components/agent-chat";
+
+export default async function SessionPage({
+ params,
+}: {
+ readonly params: Promise<{ readonly sessionId: string }>;
+}) {
+ const { sessionId } = await params;
+ return <AgentChat sessionId={sessionId} />;
+}
diff --git a/apps/docs/registry/channel/web/app/s/page.tsx b/apps/docs/registry/channel/web/app/s/page.tsx
new file mode 100644
index 000000000..7038fea76
--- /dev/null
+++ b/apps/docs/registry/channel/web/app/s/page.tsx
@@ -0,0 +1,5 @@
+import { AgentChat } from "@/app/_components/agent-chat";
+
+export default function NewSessionPage() {
+ return <AgentChat sessionless />;
+}
diff --git a/apps/docs/registry/channel/web/components/ai-elements/conversation.tsx b/apps/docs/registry/channel/web/components/ai-elements/conversation.tsx
index 8bbc3fce7..ffb36f992 100644
--- a/apps/docs/registry/channel/web/components/ai-elements/conversation.tsx
+++ b/apps/docs/registry/channel/web/components/ai-elements/conversation.tsx
@@ -5,21 +5,116 @@ import { cn } from "@/lib/utils";
import type { UIMessage } from "ai";
import { ArrowDownIcon, DownloadIcon } from "lucide-react";
import type { ComponentProps } from "react";
-import { useCallback } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
-export type ConversationProps = ComponentProps<typeof StickToBottom>;
+export type ConversationProps = ComponentProps<typeof StickToBottom> & {
+ scrollRestorationKey?: string;
+};
-export const Conversation = ({ className, ...props }: ConversationProps) => (
+export const Conversation = ({
+ children,
+ className,
+ initial,
+ scrollRestorationKey,
+ ...props
+}: ConversationProps) => (
<StickToBottom
className={cn("relative flex-1 overflow-y-hidden", className)}
- initial="smooth"
+ initial={initial ?? (scrollRestorationKey === undefined ? "smooth" : false)}
resize="smooth"
role="log"
{...props}
- />
+ >
+ {typeof children === "function" ? (
+ (context) => (
+ <>
+ {children(context)}
+ {scrollRestorationKey === undefined ? null : (
+ <ConversationScrollRestoration storageKey={scrollRestorationKey} />
+ )}
+ </>
+ )
+ ) : (
+ <>
+ {children}
+ {scrollRestorationKey === undefined ? null : (
+ <ConversationScrollRestoration storageKey={scrollRestorationKey} />
+ )}
+ </>
+ )}
+ </StickToBottom>
);
+function ConversationScrollRestoration({ storageKey }: { readonly storageKey: string }) {
+ const { scrollRef, scrollToBottom, state } = useStickToBottomContext();
+ const restoredKeyRef = useRef<string | undefined>(undefined);
+
+ useLayoutEffect(() => {
+ const scrollElement = scrollRef.current;
+ if (scrollElement === null) return;
+
+ if (restoredKeyRef.current !== storageKey) {
+ const saved = readScrollPosition(sessionStorage.getItem(storageKey));
+ if (saved?.atBottom === false) {
+ scrollElement.scrollTop = saved.scrollTop;
+ requestAnimationFrame(() => {
+ scrollElement.scrollTop = saved.scrollTop;
+ });
+ } else {
+ scrollElement.scrollTop = scrollElement.scrollHeight;
+ scrollToBottom({ animation: "instant", ignoreEscapes: true });
+ }
+ restoredKeyRef.current = storageKey;
+ }
+
+ const saveNow = () => {
+ sessionStorage.setItem(
+ storageKey,
+ JSON.stringify({
+ atBottom: state.isAtBottom || state.isNearBottom,
+ scrollTop: scrollElement.scrollTop,
+ }),
+ );
+ };
+ let frame: number | undefined;
+ const scheduleSave = () => {
+ if (frame !== undefined) return;
+ frame = requestAnimationFrame(() => {
+ frame = undefined;
+ saveNow();
+ });
+ };
+ scrollElement.addEventListener("scroll", scheduleSave, { passive: true });
+ window.addEventListener("pagehide", saveNow);
+ return () => {
+ scrollElement.removeEventListener("scroll", scheduleSave);
+ window.removeEventListener("pagehide", saveNow);
+ if (frame !== undefined) cancelAnimationFrame(frame);
+ saveNow();
+ };
+ }, [scrollRef, scrollToBottom, state, storageKey]);
+
+ return null;
+}
+
+function readScrollPosition(value: string | null):
+ | {
+ readonly atBottom: boolean;
+ readonly scrollTop: number;
+ }
+ | undefined {
+ if (value === null) return undefined;
+ try {
+ const parsed = JSON.parse(value) as { atBottom?: unknown; scrollTop?: unknown };
+ return typeof parsed.atBottom === "boolean" && typeof parsed.scrollTop === "number"
+ ? { atBottom: parsed.atBottom, scrollTop: parsed.scrollTop }
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
export type ConversationContentProps = ComponentProps<typeof StickToBottom.Content>;
export const ConversationContent = ({ className, ...props }: ConversationContentProps) => (
@@ -66,16 +161,21 @@ export const ConversationScrollButton = ({
...props
}: ConversationScrollButtonProps) => {
const { isAtBottom, scrollToBottom } = useStickToBottomContext();
+ const [isReady, setIsReady] = useState(false);
+
+ useEffect(() => setIsReady(true), []);
const handleScrollToBottom = useCallback(() => {
scrollToBottom();
}, [scrollToBottom]);
return (
+ isReady &&
!isAtBottom && (
<Button
+ aria-label="Scroll to bottom"
className={cn(
- "absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full dark:bg-background dark:hover:bg-muted",
+ "absolute bottom-32 left-[50%] translate-x-[-50%] rounded-full dark:bg-background dark:hover:bg-muted",
className,
)}
onClick={handleScrollToBottom}
diff --git a/docs/guides/frontend/nextjs.mdx b/docs/guides/frontend/nextjs.mdx
index 97905b4ca..c261bdf0c 100644
--- a/docs/guides/frontend/nextjs.mdx
+++ b/docs/guides/frontend/nextjs.mdx
@@ -90,6 +90,29 @@ const agent = useEveAgent({
The browser still needs a production authentication policy. See [Authenticate browser requests](./overview#authenticate-browser-requests) for the default fail-closed behavior and channel configuration.
+## Use the generated Web Chat routes
+
+`eve init --channel-web-nextjs` and `eve add channel/web` generate a chat UI with URL-addressed durable sessions:
+
+- `/` is the initial landing page.
+- `/s` opens the conversation layout without creating an eve session. The first message creates the session.
+- `/s/[sessionId]` attaches to that durable session, replays its transcript, and follows an in-flight turn.
+
+After the first message is accepted, Web Chat replaces the browser URL with `/s/{sessionId}` without remounting the active stream. Reloading that URL passes the session to `useEveAgent` with `resume: true`, so completed history is replayed and an unfinished response continues streaming. **New chat** navigates to the sessionless `/s` route; it does not reset or delete the prior session, which remains available at its URL.
+
+The generated UI keeps transcript scroll position in browser `sessionStorage`. This is presentation state only and is not written to the eve session.
+
+For a custom Next.js chat route, pass the route session ID explicitly:
+
+```tsx
+const agent = useEveAgent({
+ initialSession: { sessionId, streamIndex: 0 },
+ resume: true,
+});
+```
+
+See [Resumable sessions](./overview#resumable-sessions) for persistence and replay semantics.
+
## Dev vs deploy topology
- **Local dev.** `npm run dev` boots the eve dev server next to `next dev` and rewrites the eve routes over to it. The browser only ever talks to the Next.js origin.
diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdx
index 5df252ae9..fdeef6d83 100644
--- a/docs/guides/frontend/overview.mdx
+++ b/docs/guides/frontend/overview.mdx
@@ -78,6 +78,7 @@ export function Chat() {
| `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. |
@@ -275,6 +276,7 @@ const [saved] = useState<SavedEveChat>(() => {
const agent = useEveAgent({
initialEvents: saved.events ?? [],
initialSession: saved.session,
+ resume: saved.session !== undefined,
onFinish(snapshot) {
localStorage.setItem(
"eve-chat",
@@ -295,9 +297,18 @@ 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. 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.
-For multiple chat threads, keep one saved event log and session cursor per thread. `agent`, `host`, `reducer`, `session`, `initialEvents`, `initialSession`, `auth`, `headers`, and `optimistic` 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}`.
-If the user can refresh or navigate immediately after pressing send, create your app-level chat row and store the pending user message before calling `send()`. After the request starts, persist the session state as soon as it contains a `sessionId`, then reconnect an interrupted in-flight turn with `session.stream({ startIndex: savedEvents.length })` from the lower-level client.
+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.
+
+```tsx
+const agent = useEveAgent({
+ initialSession: { sessionId, streamIndex: 0 },
+ resume: true,
+});
+```
+
+If the user can refresh or navigate immediately after pressing send, create your app-level chat row before calling `send()`, then persist the session ID from `onSessionChange`. This lets the reloaded UI mount with that ID and pass `resume: true` while the durable turn is still running.
## Custom hosts and headers
diff --git a/docs/guides/frontend/use-eve-agent-svelte.mdx b/docs/guides/frontend/use-eve-agent-svelte.mdx
index 53046d495..e47fccf74 100644
--- a/docs/guides/frontend/use-eve-agent-svelte.mdx
+++ b/docs/guides/frontend/use-eve-agent-svelte.mdx
@@ -44,14 +44,14 @@ Call the binding once for a conversation and read its reactive getters directly.
The state fields are reactive getters; the commands are ordinary methods:
-| Property | Svelte shape |
-| ------------------------------------ | --------------------------------- |
-| `data` | `TData` |
-| `status` | `UseEveAgentStatus` |
-| `error` | `Error \| undefined` |
-| `events` | `readonly MessageStreamEvent[]` |
-| `session` | `ClientSessionState \| undefined` |
-| `send`, `respond`, `cancel`, `reset` | Methods |
+| Property | Svelte shape |
+| ---------------------------------------------- | --------------------------------- |
+| `data` | `TData` |
+| `status` | `UseEveAgentStatus` |
+| `error` | `Error \| undefined` |
+| `events` | `readonly MessageStreamEvent[]` |
+| `session` | `ClientSessionState \| undefined` |
+| `send`, `respond`, `resume`, `cancel`, `reset` | Methods |
Read the getters directly in templates, `$derived`, or `$effect`. The [shared returned-state reference](./overview#returned-state) describes what each value and command does.
@@ -106,7 +106,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` and `initialEvents` to restore a saved conversation. 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. 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 credentials
diff --git a/docs/guides/frontend/use-eve-agent-vue.mdx b/docs/guides/frontend/use-eve-agent-vue.mdx
index 5b1abd67f..5e5464482 100644
--- a/docs/guides/frontend/use-eve-agent-vue.mdx
+++ b/docs/guides/frontend/use-eve-agent-vue.mdx
@@ -43,14 +43,14 @@ async function handleSubmit() {
The state fields are computed refs; the commands are ordinary methods:
-| Property | Vue shape |
-| ------------------------------------ | ---------------------------------------------- |
-| `data` | `ComputedRef<TData>` |
-| `status` | `ComputedRef<UseEveAgentStatus>` |
-| `error` | `ComputedRef<Error \| undefined>` |
-| `events` | `ComputedRef<readonly MessageStreamEvent[]>` |
-| `session` | `ComputedRef<ClientSessionState \| undefined>` |
-| `send`, `respond`, `cancel`, `reset` | Methods |
+| Property | Vue shape |
+| ---------------------------------------------- | ---------------------------------------------- |
+| `data` | `ComputedRef<TData>` |
+| `status` | `ComputedRef<UseEveAgentStatus>` |
+| `error` | `ComputedRef<Error \| undefined>` |
+| `events` | `ComputedRef<readonly MessageStreamEvent[]>` |
+| `session` | `ComputedRef<ClientSessionState \| undefined>` |
+| `send`, `respond`, `resume`, `cancel`, `reset` | Methods |
Destructuring preserves reactivity because each state value remains a ref. Read refs with `.value` in `<script>` and without `.value` in a template. The [shared returned-state reference](./overview#returned-state) describes what each value and command does.
@@ -108,7 +108,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` and `initialEvents` to restore a saved conversation. 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. 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 credentials
diff --git a/packages/eve/src/client/eve-agent-store.test.ts b/packages/eve/src/client/eve-agent-store.test.ts
index 14f58e67b..5fd3158e7 100644
--- a/packages/eve/src/client/eve-agent-store.test.ts
+++ b/packages/eve/src/client/eve-agent-store.test.ts
@@ -6,6 +6,7 @@ import { stampTestEvents } from "#internal/testing/events.js";
import {
createMessageCompletedEvent,
createMessageReceivedEvent,
+ createSessionFailedEvent,
createSessionWaitingEvent,
createTurnCancelledEvent,
createTurnStartedEvent,
@@ -49,6 +50,12 @@ function streamResponse(events: readonly MessageStreamEvent[]): Response {
);
}
+function boundedStreamResponse(events: readonly MessageStreamEvent[]): Response {
+ const response = streamResponse(events);
+ response.headers.set("x-eve-stream-tail-index", String(events.length - 1));
+ return response;
+}
+
function controlledStreamResponse() {
const encoder = new TextEncoder();
let controller: ReadableStreamDefaultController<Uint8Array> | undefined;
@@ -202,6 +209,139 @@ describe("EveAgentStore stream overlap", () => {
});
});
+describe("EveAgentStore session resume", () => {
+ it("publishes a replayed terminal failure with error status", async () => {
+ const failed = stampTestEvents([
+ createSessionFailedEvent({
+ code: "SESSION_FAILED",
+ message: "Session failed.",
+ sessionId: "session_1",
+ }),
+ ])[0]!;
+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(boundedStreamResponse([failed]));
+ const store = new EveAgentStore({
+ initialSession: { sessionId: "session_1", streamIndex: 0 },
+ reducer: defaultMessageReducer(),
+ });
+ const published: Array<{ eventType: string | undefined; status: string }> = [];
+ store.subscribe(() => {
+ published.push({
+ eventType: store.snapshot.events.at(-1)?.type,
+ status: store.snapshot.status,
+ });
+ });
+
+ await store.resume();
+
+ expect(published.find((snapshot) => snapshot.eventType === "session.failed")?.status).toBe(
+ "error",
+ );
+ expect(store.snapshot.error?.message).toBe("Session failed.");
+ });
+
+ it("replays a settled session without opening a live stream", async () => {
+ const events = turnEvents();
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValueOnce(boundedStreamResponse(events));
+ const store = new EveAgentStore({
+ initialSession: { sessionId: "session_1", streamIndex: 0 },
+ reducer: defaultMessageReducer(),
+ });
+ const publishedEventCounts: number[] = [];
+ store.subscribe(() => publishedEventCounts.push(store.snapshot.events.length));
+
+ await store.resume();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(publishedEventCounts).not.toContain(1);
+ expect(publishedEventCounts).not.toContain(2);
+ expect(store.snapshot.status).toBe("ready");
+ expect(store.snapshot.events).toEqual(events);
+ expect(store.snapshot.session).toEqual({ sessionId: "session_1", streamIndex: events.length });
+ });
+
+ it("replays history and follows an interrupted turn through its boundary", 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 live = controlledStreamResponse();
+ const requests: string[] = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (request) => {
+ const url =
+ typeof request === "string" ? request : request instanceof URL ? request.href : request.url;
+ requests.push(url);
+ return requests.length === 1 ? boundedStreamResponse([received!, started!]) : live.response;
+ });
+ const store = new EveAgentStore({
+ initialSession: { sessionId: "session_1", streamIndex: 0 },
+ reducer: defaultMessageReducer(),
+ });
+
+ const resuming = store.resume();
+ expect(store.resume()).toBe(resuming);
+ await vi.waitFor(() => expect(store.snapshot.status).toBe("streaming"));
+ expect(store.snapshot.events.map((event) => event.type)).toEqual([
+ "message.received",
+ "turn.started",
+ ]);
+
+ live.emit(completed!);
+ live.emit(waiting!);
+ live.close();
+ await resuming;
+
+ expect(store.snapshot.status).toBe("ready");
+ expect(store.snapshot.data.messages.at(-1)?.parts).toContainEqual({
+ state: "done",
+ stepIndex: 0,
+ text: "Hi there.",
+ type: "text",
+ });
+ expect(new URL(requests[0]!, "http://localhost").searchParams.get("startIndex")).toBeNull();
+ expect(new URL(requests[1]!, "http://localhost").searchParams.get("startIndex")).toBe("2");
+ });
+});
+
+describe("EveAgentStore terminal failure", () => {
+ it("publishes a live terminal failure with error status", async () => {
+ const failed = stampTestEvents([
+ createSessionFailedEvent({
+ code: "SESSION_FAILED",
+ message: "Session failed.",
+ sessionId: "session_1",
+ }),
+ ])[0]!;
+ vi.spyOn(globalThis, "fetch")
+ .mockResolvedValueOnce(startedResponse())
+ .mockResolvedValueOnce(streamResponse([failed]));
+ const store = new EveAgentStore({ reducer: defaultMessageReducer() });
+ const published: Array<{ eventType: string | undefined; status: string }> = [];
+ store.subscribe(() => {
+ published.push({
+ eventType: store.snapshot.events.at(-1)?.type,
+ status: store.snapshot.status,
+ });
+ });
+
+ await store.send({ message: "Hello" });
+
+ expect(published.find((snapshot) => snapshot.eventType === "session.failed")?.status).toBe(
+ "error",
+ );
+ expect(store.snapshot.error?.message).toBe("Session failed.");
+ });
+});
+
describe("EveAgentStore cancellation", () => {
it("queues cancellation until the turn id arrives and keeps streaming", async () => {
const stream = controlledStreamResponse();
diff --git a/packages/eve/src/client/eve-agent-store.ts b/packages/eve/src/client/eve-agent-store.ts
index 93dda83a2..f55af1970 100644
--- a/packages/eve/src/client/eve-agent-store.ts
+++ b/packages/eve/src/client/eve-agent-store.ts
@@ -3,7 +3,7 @@ import type { MessageResponse } from "#client/message-response.js";
import type { EveAgentReducer, EveAgentReducerEvent } from "#client/reducer.js";
import type { ClientSession } from "#client/session.js";
import { createEventDeduper } from "#protocol/event-dedupe.js";
-import type { MessageStreamEvent } from "#protocol/message.js";
+import { isCurrentTurnBoundaryEvent, type MessageStreamEvent } from "#protocol/message.js";
import { toError } from "#shared/errors.js";
import type {
CancelSessionResult,
@@ -94,7 +94,7 @@ const detachStore = Symbol("detachEveAgentStore");
interface ActiveTurn {
readonly abortController: AbortController;
- readonly response: Promise<MessageResponse | undefined>;
+ readonly cancel: () => Promise<CancelSessionResult>;
readonly resolveResponse: (response: MessageResponse | undefined) => void;
}
@@ -105,11 +105,11 @@ interface ActiveTurn {
* notification; framework integrations (React, Vue) wrap it with their own
* reactivity primitives.
*
- * Drives one turn at a time: `send` rejects if a turn is already submitted or
- * streaming. Read the latest projection via the `snapshot` getter, observe
- * changes with `subscribe`, register lifecycle hooks with `setCallbacks`,
- * cancel the durable in-flight turn with `cancel`, and discard all state with
- * `reset`.
+ * Drives one turn at a time: `send` rejects while a turn is active, and
+ * concurrent `resume` calls share one replay. Read the latest projection via
+ * the `snapshot` getter, observe changes with `subscribe`, register lifecycle
+ * hooks with `setCallbacks`, cancel the durable in-flight turn with `cancel`,
+ * and discard all state with `reset`.
*/
export class EveAgentStore<TData> {
readonly #client: Client | undefined;
@@ -128,6 +128,7 @@ export class EveAgentStore<TData> {
#events: readonly MessageStreamEvent[];
#pendingMessageSubmission: PendingMessageSubmission | undefined;
#projectionEvents: readonly EveAgentReducerEvent[];
+ #resumePromise: Promise<void> | undefined;
#session: ClientSession | undefined;
#snapshot: EveAgentStoreSnapshot<TData>;
#status: EveAgentStoreStatus = "ready";
@@ -186,7 +187,10 @@ export class EveAgentStore<TData> {
const response = Promise.withResolvers<MessageResponse | undefined>();
const turn: ActiveTurn = {
abortController: new AbortController(),
- response: response.promise,
+ cancel: () =>
+ response.promise.then((messageResponse) =>
+ messageResponse === undefined ? { status: "no_active_turn" } : messageResponse.cancel(),
+ ),
resolveResponse: response.resolve,
};
this.#activeTurn = turn;
@@ -215,26 +219,9 @@ export class EveAgentStore<TData> {
if (!this.#isActiveTurn(turn)) return;
turn.resolveResponse(response);
- let sawEvent = false;
for await (const event of response) {
- if (!this.#isActiveTurn(turn)) {
- return;
- }
-
- if (!sawEvent) {
- sawEvent = true;
- this.#status = "streaming";
- }
-
- if (!this.#seenEvents.admit(event)) {
- continue;
- }
-
- this.#events = [...this.#events, event];
- this.#applyServerEvent(event);
- this.#callbacks.onEvent?.(event);
- this.#applyTerminalStreamFailure(event);
- this.#publish();
+ if (!this.#isActiveTurn(turn)) return;
+ this.#acceptServerEvent(event);
}
if (!this.#isActiveTurn(turn)) {
@@ -267,6 +254,91 @@ export class EveAgentStore<TData> {
}
}
+ /** Replays this store's attached durable session and follows an in-flight turn. */
+ resume(): Promise<void> {
+ if (this.#resumePromise !== undefined) return this.#resumePromise;
+
+ const promise = this.#resume();
+ this.#resumePromise = promise;
+ const clear = () => {
+ if (this.#resumePromise === promise) this.#resumePromise = undefined;
+ };
+ void promise.then(clear, clear);
+ return promise;
+ }
+
+ async #resume(): Promise<void> {
+ if (this.#status === "streaming" || this.#status === "submitted") {
+ throw new Error("eve session is already processing a turn.");
+ }
+ if (this.#session === undefined) {
+ throw new Error("An eve session is required before resuming.");
+ }
+
+ const response = Promise.withResolvers<MessageResponse | undefined>();
+ const session = this.#session;
+ const turn: ActiveTurn = {
+ abortController: new AbortController(),
+ cancel: () => session.cancel(),
+ resolveResponse: response.resolve,
+ };
+ this.#activeTurn = turn;
+ this.#error = undefined;
+ this.#status = "submitted";
+ this.#publish();
+
+ try {
+ const replayed: MessageStreamEvent[] = [];
+ for await (const event of session.stream({
+ follow: false,
+ signal: turn.abortController.signal,
+ startIndex: 0,
+ })) {
+ if (!this.#isActiveTurn(turn)) return;
+ replayed.push(event);
+ this.#acceptServerEvent(event, false);
+ }
+
+ if (!this.#isActiveTurn(turn)) return;
+ this.#publish();
+ if (!isSettledSessionTail(replayed)) {
+ const pendingAuthorizations = collectPendingAuthorizations(replayed);
+ for await (const event of session.stream({ signal: turn.abortController.signal })) {
+ if (!this.#isActiveTurn(turn)) return;
+ this.#acceptServerEvent(event);
+ updatePendingAuthorizations(pendingAuthorizations, event);
+ if (
+ isCurrentTurnBoundaryEvent(event) &&
+ (event.type !== "session.waiting" || pendingAuthorizations.size === 0)
+ ) {
+ break;
+ }
+ }
+ }
+
+ if (this.#isActiveTurn(turn)) {
+ this.#status = this.#error === undefined ? "ready" : "error";
+ }
+ } catch (error) {
+ if (!this.#isActiveTurn(turn)) return;
+ if (isAbortError(error)) {
+ this.#status = "ready";
+ } else {
+ this.#error = toError(error);
+ this.#status = "error";
+ this.#callbacks.onError?.(this.#error);
+ }
+ } finally {
+ if (this.#isActiveTurn(turn)) {
+ turn.resolveResponse(undefined);
+ this.#activeTurn = undefined;
+ this.#callbacks.onSessionChange?.(session.state);
+ this.#publish();
+ this.#callbacks.onFinish?.(this.#snapshot);
+ }
+ }
+ }
+
/**
* Requests cooperative cancellation of the active durable turn.
*
@@ -276,9 +348,7 @@ export class EveAgentStore<TData> {
cancel(): Promise<CancelSessionResult> {
const turn = this.#activeTurn;
if (turn === undefined) return Promise.resolve({ status: "no_active_turn" });
- return turn.response.then<CancelSessionResult>((response) =>
- response === undefined ? { status: "no_active_turn" } : response.cancel(),
- );
+ return turn.cancel();
}
[detachStore](): void {
@@ -370,6 +440,16 @@ export class EveAgentStore<TData> {
});
}
+ #acceptServerEvent(event: MessageStreamEvent, publish = true): void {
+ if (!this.#seenEvents.admit(event)) return;
+ this.#events = [...this.#events, event];
+ this.#applyServerEvent(event);
+ this.#callbacks.onEvent?.(event);
+ this.#status = "streaming";
+ this.#applyTerminalStreamFailure(event);
+ if (publish) this.#publish();
+ }
+
#applyServerEvent(event: MessageStreamEvent): void {
if (event.type === "message.received" && this.#pendingMessageSubmission !== undefined) {
const submissionId = this.#pendingMessageSubmission.id;
@@ -481,6 +561,29 @@ export function detachEveAgentStore<TData>(store: EveAgentStore<TData>): void {
store[detachStore]();
}
+function isSettledSessionTail(events: readonly MessageStreamEvent[]): boolean {
+ const tail = events.at(-1);
+ return (
+ tail !== undefined &&
+ isCurrentTurnBoundaryEvent(tail) &&
+ (tail.type !== "session.waiting" || collectPendingAuthorizations(events).size === 0)
+ );
+}
+
+function collectPendingAuthorizations(events: readonly MessageStreamEvent[]): Set<string> {
+ const pending = new Set<string>();
+ for (const event of events) updatePendingAuthorizations(pending, event);
+ return pending;
+}
+
+function updatePendingAuthorizations(pending: Set<string>, event: MessageStreamEvent): void {
+ if (event.type === "authorization.required" && event.data.webhookUrl !== undefined) {
+ pending.add(event.data.name);
+ } else if (event.type === "authorization.completed") {
+ pending.delete(event.data.name);
+ }
+}
+
function assertExclusiveTurnInput(input: SendTurnPayload): void {
const hasMessage = input.message !== undefined;
const hasResponses = input.inputResponses !== undefined;
diff --git a/packages/eve/src/client/ndjson.ts b/packages/eve/src/client/ndjson.ts
index 317c391c1..450fc4ba3 100644
--- a/packages/eve/src/client/ndjson.ts
+++ b/packages/eve/src/client/ndjson.ts
@@ -35,6 +35,7 @@ export function isStreamDisconnectError(error: unknown): boolean {
*/
export async function* readNdjsonStream(
body: ReadableStream<Uint8Array>,
+ options?: { readonly idleTimeoutMs?: number },
): AsyncGenerator<MessageStreamEvent> {
const reader = body.getReader();
const decoder = new TextDecoder();
@@ -43,7 +44,7 @@ export async function* readNdjsonStream(
try {
while (true) {
- const result = await reader.read();
+ const result = await readWithIdleTimeout(reader, options?.idleTimeoutMs);
if (result.done) {
reachedEof = true;
@@ -84,3 +85,25 @@ export async function* readNdjsonStream(
reader.releaseLock();
}
}
+
+async function readWithIdleTimeout(
+ reader: ReadableStreamDefaultReader<Uint8Array>,
+ idleTimeoutMs: number | undefined,
+): ReturnType<ReadableStreamDefaultReader<Uint8Array>["read"]> {
+ if (idleTimeoutMs === undefined) return await reader.read();
+
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ reader.read(),
+ new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(
+ () => reject(new DOMException("Session stream was idle.", "AbortError")),
+ idleTimeoutMs,
+ );
+ }),
+ ]);
+ } finally {
+ if (timeout !== undefined) clearTimeout(timeout);
+ }
+}
diff --git a/packages/eve/src/client/open-stream.ts b/packages/eve/src/client/open-stream.ts
index a78c775e4..54d30edff 100644
--- a/packages/eve/src/client/open-stream.ts
+++ b/packages/eve/src/client/open-stream.ts
@@ -23,6 +23,8 @@ interface ResolvedStreamReconnectPolicy {
readonly streamOpenReconnectPolicy: RetryPolicy;
}
+const DEFAULT_STREAM_READ_IDLE_TIMEOUT_MS = 15_000;
+
const DEFAULT_STREAM_RECONNECT_POLICY: ResolvedStreamReconnectPolicy = {
retryableErrorStatuses: new Set([404, 409, 425, 500, 502, 503, 504]),
streamIdleReconnectPolicy: { baseDelayMs: 250, maxAttempts: 5, maxDelayMs: 4_000 },
@@ -79,6 +81,8 @@ interface FollowStreamInput {
/** Keep reconnecting after empty streams until the consumer aborts or stops iteration. */
readonly keepAlive?: boolean;
readonly streamReconnectPolicy?: StreamReconnectPolicy;
+ /** @internal Test override for reconnecting an open stream that stops producing bytes. */
+ readonly streamReadIdleTimeoutMs?: number;
readonly resolveHeaders: () => Promise<Headers>;
readonly redirect?: ClientRedirectPolicy;
readonly sessionId: string;
@@ -142,7 +146,7 @@ export async function* followStreamIterable(
if (input.follow === false && tailIndex === undefined) {
tailIndex = connection.tailIndex;
if (tailIndex === undefined) {
- await connection.body.cancel().catch(() => {});
+ connection.close();
throw new Error(
`stream({ follow: false }) requires the server to report the ${EVE_STREAM_TAIL_INDEX_HEADER} header. ` +
"The agent may be running an older eve version.",
@@ -151,13 +155,15 @@ export async function* followStreamIterable(
}
if (tailIndex !== undefined && startIndex > tailIndex) {
- await connection.body.cancel().catch(() => {});
+ connection.close();
return;
}
let deliveredEvent = false;
try {
- for await (const event of readNdjsonStream(connection.body)) {
+ for await (const event of readNdjsonStream(connection.body, {
+ idleTimeoutMs: input.streamReadIdleTimeoutMs ?? DEFAULT_STREAM_READ_IDLE_TIMEOUT_MS,
+ })) {
startIndex += 1;
deliveredEvent = true;
reconnectDelayMs = idleRetryPolicy.baseDelayMs;
@@ -169,9 +175,9 @@ export async function* followStreamIterable(
}
}
} catch (error) {
- if (!isStreamDisconnectError(error)) {
- throw error;
- }
+ if (!isStreamDisconnectError(error)) throw error;
+ } finally {
+ connection.close();
}
if (input.signal?.aborted || input.startIndex < 0 || idleRetryPolicy.maxAttempts === 0) {
@@ -199,6 +205,7 @@ export async function* followStreamIterable(
/** An opened connection: the response body plus the tail index from the response header, if any. */
interface OpenedStream {
readonly body: ReadableStream<Uint8Array>;
+ close(): void;
readonly tailIndex: number | undefined;
}
@@ -234,13 +241,17 @@ export async function openStreamBody(
);
const headers = await input.resolveHeaders();
+ const connectionController = new AbortController();
+ const signal = input.signal
+ ? AbortSignal.any([input.signal, connectionController.signal])
+ : connectionController.signal;
let response: Response;
try {
response = await fetch(url, {
cache: "no-store",
headers,
redirect: input.redirect,
- signal: input.signal ?? null,
+ signal,
});
} catch (error) {
if (
@@ -259,7 +270,11 @@ export async function openStreamBody(
if (!response.body) {
throw new ClientError(response.status, "Response body is null.", response.headers);
}
- return { body: response.body, tailIndex: parseTailIndexHeader(response.headers) };
+ return {
+ body: response.body,
+ close: () => connectionController.abort(),
+ tailIndex: parseTailIndexHeader(response.headers),
+ };
}
lastStatus = response.status;
diff --git a/packages/eve/src/client/stream-follow.integration.test.ts b/packages/eve/src/client/stream-follow.integration.test.ts
index 32295239c..dfdbc1a21 100644
--- a/packages/eve/src/client/stream-follow.integration.test.ts
+++ b/packages/eve/src/client/stream-follow.integration.test.ts
@@ -89,6 +89,44 @@ describe("stream following over real sockets", () => {
expect(session.state).toMatchObject({ sessionId: "s1", streamIndex: 6 });
});
+ it("reconnects an open stream that goes idle and continues from its cursor", async () => {
+ const events = [
+ { type: "step.started", data: {} },
+ { type: "message.appended", data: { messageDelta: "hello" } },
+ { type: "session.completed", data: {} },
+ ];
+ let connections = 0;
+ const host = await listen(
+ createServer((req, res) => {
+ connections += 1;
+ const index = startIndexOf(req.url);
+ res.writeHead(200, { "content-type": "application/x-ndjson" });
+ if (connections === 1) {
+ res.write(`${JSON.stringify(events[0])}\n`);
+ return;
+ }
+ for (const event of events.slice(index)) {
+ res.write(`${JSON.stringify(event)}\n`);
+ }
+ }),
+ );
+
+ const received: string[] = [];
+ for await (const event of followStreamIterable({
+ host,
+ resolveHeaders: () => Promise.resolve(new Headers()),
+ sessionId: "s",
+ startIndex: 0,
+ streamReadIdleTimeoutMs: 50,
+ })) {
+ received.push(event.type);
+ if (event.type === "session.completed") break;
+ }
+
+ expect(received).toEqual(["step.started", "message.appended", "session.completed"]);
+ expect(connections).toBe(2);
+ });
+
it("gives up after the idle-reconnect budget when a settled run's stream ends boundary-less", async () => {
let connections = 0;
const host = await listen(
diff --git a/packages/eve/src/react/use-eve-agent.test.ts b/packages/eve/src/react/use-eve-agent.test.ts
index 1e4a09752..82ad36fdb 100644
--- a/packages/eve/src/react/use-eve-agent.test.ts
+++ b/packages/eve/src/react/use-eve-agent.test.ts
@@ -42,6 +42,12 @@ function createEagerStreamResponse(events: readonly UnstampedMessageStreamEvent[
);
}
+function createBoundedStreamResponse(events: readonly UnstampedMessageStreamEvent[]): Response {
+ const response = createEagerStreamResponse(events);
+ response.headers.set("x-eve-stream-tail-index", String(events.length - 1));
+ return response;
+}
+
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
@@ -643,6 +649,62 @@ describe("useEveAgent", () => {
expect(helpers?.events).toEqual(stampTestEvents(events));
});
+ it("requires a session when automatic resume is enabled", async () => {
+ function TestComponent() {
+ useEveAgent({ resume: true });
+ return null;
+ }
+
+ await expect(
+ act(async () => {
+ create(createElement(TestComponent));
+ }),
+ ).rejects.toThrow("requires initialSession or session");
+ });
+
+ it("automatically replays an initial session when resume is enabled", async () => {
+ const events = [
+ createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),
+ createMessageCompletedEvent({
+ message: "Hi there.",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn_1",
+ }),
+ createSessionWaitingEvent(),
+ ];
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValueOnce(createBoundedStreamResponse(events));
+ let helpers: UseEveAgentHelpers<EveMessageData> | undefined;
+ const statuses: string[] = [];
+
+ function TestComponent() {
+ helpers = useEveAgent({
+ initialSession: { sessionId: "session_1", streamIndex: 0 },
+ resume: true,
+ });
+ statuses.push(helpers.status);
+ return null;
+ }
+
+ await act(async () => {
+ create(createElement(TestComponent));
+ await vi.waitFor(() => expect(helpers?.events).toHaveLength(events.length));
+ });
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(statuses[0]).toBe("submitted");
+ expect(helpers?.status).toBe("ready");
+ expect(helpers?.data).toEqual(
+ completedTurnData({
+ assistantMessage: "Hi there.",
+ turnId: "turn_1",
+ userMessage: "Hello",
+ }),
+ );
+ });
+
it("projects input responses before the resumed stream returns", async () => {
const startResponse = createDeferred<Response>();
vi.spyOn(globalThis, "fetch")
diff --git a/packages/eve/src/react/use-eve-agent.ts b/packages/eve/src/react/use-eve-agent.ts
index d0f65956a..f6e698be5 100644
--- a/packages/eve/src/react/use-eve-agent.ts
+++ b/packages/eve/src/react/use-eve-agent.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import {
detachEveAgentStore,
@@ -48,6 +48,8 @@ export type UseEveAgentSnapshot<TData> = EveAgentStoreSnapshot<TData>;
export interface UseEveAgentHelpers<TData> extends UseEveAgentSnapshot<TData> {
/** Requests durable cancellation of the active turn while continuing to receive its events. */
readonly cancel: () => Promise<CancelSessionResult>;
+ /** Replays the attached durable session and follows its in-flight turn, if any. */
+ readonly resume: () => Promise<void>;
/** Resets the session: detaches any local stream, recreates the owned session, and clears events and projected data. */
readonly reset: () => void;
/** Sends a message. Rejects if a turn is already in flight. */
@@ -106,6 +108,13 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>
*/
readonly optimistic?: boolean;
readonly reducer?: EveAgentReducer<TData>;
+ /**
+ * Replay the attached durable session after mount and follow its in-flight
+ * turn, if any. Requires `initialSession` or `session`.
+ *
+ * @default false
+ */
+ readonly resume?: boolean;
readonly session?: ClientSession;
}
@@ -121,13 +130,13 @@ export function useEveAgent<TData>(
* React hook that drives an eve session and projects its event stream into UI data.
*
* Returns the current snapshot (`data`, `events`, `session`, `status`, `error`)
- * plus the commands `send`, `respond`, `cancel`, and `reset`. With no reducer, `data` is the
+ * plus the commands `send`, `respond`, `resume`, `cancel`, and `reset`. With no reducer, `data` is the
* built-in `UIMessage` projection from {@link defaultMessageReducer} (`TData`
* is {@link EveMessageData}); pass a reducer to project into your own shape and
* infer `TData`.
*
* Session-shaping options (`host`, `reducer`, `session`, `initialEvents`,
- * `initialSession`, `auth`, `headers`, `optimistic`) are
+ * `initialSession`, `auth`, `headers`, `optimistic`, `resume`) are
* read once when the store is created; remount to change them. Lifecycle
* callbacks (`onError`, `onEvent`, `onFinish`, `onSessionChange`, `prepareSend`)
* refresh on every render.
@@ -136,8 +145,17 @@ export function useEveAgent<TData>(
options: UseEveAgentOptions<TData> = {},
): UseEveAgentHelpers<TData> {
const storeRef = useRef<EveAgentStore<TData> | undefined>(undefined);
+ const resumeOnMountRef = useRef(options.resume ?? false);
+ const [autoResumePending, setAutoResumePending] = useState(resumeOnMountRef.current);
if (!storeRef.current) {
+ if (
+ resumeOnMountRef.current &&
+ options.initialSession === undefined &&
+ options.session === undefined
+ ) {
+ throw new Error("useEveAgent({ resume: true }) requires initialSession or session.");
+ }
const reducer = options.reducer ?? (defaultMessageReducer() as EveAgentReducer<TData>);
storeRef.current = new EveAgentStore({
auth: options.auth,
@@ -171,9 +189,22 @@ export function useEveAgent<TData>(
);
useEffect(() => () => detachEveAgentStore(store), [store]);
+ useEffect(() => {
+ if (!resumeOnMountRef.current) return;
+ let active = true;
+ const finish = () => {
+ if (active) setAutoResumePending(false);
+ };
+ const timeout = setTimeout(() => void store.resume().then(finish, finish), 0);
+ return () => {
+ active = false;
+ clearTimeout(timeout);
+ };
+ }, [store]);
const cancel = useCallback(() => store.cancel(), [store]);
const reset = useCallback(() => store.reset(), [store]);
+ const resume = useCallback(() => store.resume(), [store]);
const send = useCallback(
<TOutput = unknown>(message: string | UserContent, options?: SendTurnOptions<TOutput>) => {
return store.send({ ...options, message });
@@ -187,14 +218,20 @@ export function useEveAgent<TData>(
) => store.send({ ...options, inputResponses }),
[store],
);
+ const visibleSnapshot =
+ autoResumePending && snapshot.status === "ready"
+ ? { ...snapshot, status: "submitted" as const }
+ : snapshot;
+
return useMemo(
() => ({
- ...snapshot,
+ ...visibleSnapshot,
cancel,
reset,
respond,
+ resume,
send,
}),
- [cancel, reset, respond, send, snapshot],
+ [cancel, reset, respond, resume, send, visibleSnapshot],
);
}
diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.ts
index 2e8248558..c047d1829 100644
--- a/packages/eve/src/setup/scaffold/create/web-template.ts
+++ b/packages/eve/src/setup/scaffold/create/web-template.ts
@@ -5,21 +5,25 @@ 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 } from "lucide-react";\nimport { useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n} from "@/components/ai-elements/conversation";\nimport { Message, MessageContent } from "@/components/ai-elements/message";\nimport {\n PromptInput,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n} from "@/components/ai-elements/prompt-input";\nimport { Shimmer } from "@/components/ai-elements/shimmer";\nimport { cn } from "@/lib/utils";\nimport { AgentMessage } from "./agent-message";\n\nconst AGENT_NAME = "__EVE_INIT_APP_NAME__";\n\nexport function AgentChat() {\n const [cancellationError, setCancellationError] = useState<string>();\n const agent = useEveAgent();\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\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\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) || isBusy) return;\n\n setCancellationError(undefined);\n\n if (message.files.length === 0) {\n await agent.send(text);\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);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea disabled={isBusy} placeholder="Send a message…" />\n <PromptInputSubmit onStop={requestCancellation} status={agent.status} />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {isEmpty ? null : (\n <header className="flex h-14 shrink-0 items-center justify-center pl-4 pr-2">\n <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>\n </header>\n )}\n\n {errorMessage ? (\n <div className="mx-auto w-full max-w-3xl shrink-0 px-4 pt-2 sm:px-6">\n <div\n className="flex 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">{errorMessage}</p>\n </div>\n </div>\n </div>\n ) : null}\n\n {isEmpty ? null : (\n <Conversation className="min-h-0 flex-1">\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 py-6 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 </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n )}\n\n <div\n className={cn(\n "mx-auto w-full px-4 sm:px-6",\n isEmpty\n ? "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]"\n : "max-w-3xl shrink-0 pb-6",\n )}\n >\n {isEmpty ? (\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 ) : null}\n <div className="w-full">{composer}</div>\n </div>\n </main>\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 } from "lucide-react";\nimport { useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n} from "@/components/ai-elements/conversation";\nimport { Message, MessageContent } from "@/components/ai-elements/message";\nimport {\n PromptInput,\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) || isBusy) return;\n\n setCancellationError(undefined);\n\n if (message.files.length === 0) {\n await agent.send(text);\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);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea disabled={isBusy || isRestoring} placeholder="Send a message…" />\n <PromptInputSubmit\n disabled={isRestoring}\n onStop={requestCancellation}\n status={isRestoring ? 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 <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',
"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\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 <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 </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',
+ '"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":
'@import "tailwindcss";\n@source "../node_modules/streamdown/dist/*.js";\n\n@theme inline {\n --color-background: var(--background);\n --color-foreground: var(--foreground);\n --color-card: var(--card);\n --color-card-foreground: var(--card-foreground);\n --color-popover: var(--popover);\n --color-popover-foreground: var(--popover-foreground);\n --color-primary: var(--primary);\n --color-primary-foreground: var(--primary-foreground);\n --color-secondary: var(--secondary);\n --color-secondary-foreground: var(--secondary-foreground);\n --color-muted: var(--muted);\n --color-muted-foreground: var(--muted-foreground);\n --color-accent: var(--accent);\n --color-accent-foreground: var(--accent-foreground);\n --color-destructive: var(--destructive);\n --color-border: var(--border);\n --color-input: var(--input);\n --color-ring: var(--ring);\n --radius-sm: calc(var(--radius) - 4px);\n --radius-md: calc(var(--radius) - 2px);\n --radius-lg: var(--radius);\n --radius-xl: calc(var(--radius) + 4px);\n --font-sans: "Geist", "Geist Fallback", ui-sans-serif, system-ui, sans-serif;\n --font-mono: "Geist Mono", "Geist Mono Fallback", ui-monospace, monospace;\n}\n\n:root {\n color-scheme: light;\n /* Soft neutral page with white elevated surfaces so cards/composer pop. */\n --background: oklch(0.971 0 0);\n --foreground: oklch(0.16 0 0);\n --card: oklch(1 0 0);\n --card-foreground: oklch(0.16 0 0);\n --popover: oklch(1 0 0);\n --popover-foreground: oklch(0.16 0 0);\n --primary: oklch(0.19 0 0);\n --primary-foreground: oklch(0.985 0 0);\n --secondary: oklch(0.94 0 0);\n --secondary-foreground: oklch(0.19 0 0);\n --muted: oklch(0.94 0 0);\n --muted-foreground: oklch(0.6 0 0);\n --accent: oklch(0.94 0 0);\n --accent-foreground: oklch(0.19 0 0);\n --destructive: oklch(0.577 0.245 27.325);\n --border: oklch(0.916 0 0);\n --input: oklch(0.916 0 0);\n --ring: oklch(0.708 0 0);\n --radius: 0.625rem;\n}\n\n@media (prefers-color-scheme: dark) {\n :root {\n color-scheme: dark;\n --background: oklch(0.145 0 0);\n --foreground: oklch(0.985 0 0);\n --card: oklch(0.205 0 0);\n --card-foreground: oklch(0.985 0 0);\n --popover: oklch(0.205 0 0);\n --popover-foreground: oklch(0.985 0 0);\n --primary: oklch(0.922 0 0);\n --primary-foreground: oklch(0.205 0 0);\n --secondary: oklch(0.269 0 0);\n --secondary-foreground: oklch(0.985 0 0);\n --muted: oklch(0.269 0 0);\n --muted-foreground: oklch(0.708 0 0);\n --accent: oklch(0.269 0 0);\n --accent-foreground: oklch(0.985 0 0);\n --destructive: oklch(0.704 0.191 22.216);\n --border: oklch(1 0 0 / 10%);\n --input: oklch(1 0 0 / 15%);\n --ring: oklch(0.556 0 0);\n }\n}\n\n* {\n border-color: var(--border);\n}\n\nhtml {\n height: 100%;\n}\n\nbody {\n min-height: 100%;\n margin: 0;\n background: var(--background);\n font-family: var(--font-sans);\n}\n\nbutton,\ninput,\ntextarea {\n font: inherit;\n}\n',
"app/layout.tsx":
'import type { Metadata } from "next";\nimport { Geist, Geist_Mono } from "next/font/google";\nimport type { ReactNode } from "react";\nimport { TooltipProvider } from "@/components/ui/tooltip";\nimport { cn } from "@/lib/utils";\nimport "./globals.css";\n\nconst sans = Geist({\n variable: "--font-sans",\n subsets: ["latin"],\n weight: "variable",\n display: "swap",\n});\n\nconst mono = Geist_Mono({\n variable: "--font-mono",\n subsets: ["latin"],\n weight: "variable",\n display: "swap",\n});\n\nexport const metadata: Metadata = {\n title: "__EVE_INIT_APP_NAME__",\n description: "A Next.js starter for eve agents with AI Elements.",\n};\n\nexport default function RootLayout({ children }: { readonly children: ReactNode }) {\n return (\n <html className={cn(sans.variable, mono.variable)} lang="en">\n <body>\n <TooltipProvider>{children}</TooltipProvider>\n </body>\n </html>\n );\n}\n',
"app/page.tsx":
'import { AgentChat } from "@/app/_components/agent-chat";\n\nexport default function Page() {\n return <AgentChat />;\n}\n',
+ "app/s/[sessionId]/page.tsx":
+ 'import { AgentChat } from "@/app/_components/agent-chat";\n\nexport default async function SessionPage({\n params,\n}: {\n readonly params: Promise<{ readonly sessionId: string }>;\n}) {\n const { sessionId } = await params;\n return <AgentChat sessionId={sessionId} />;\n}\n',
+ "app/s/page.tsx":
+ 'import { AgentChat } from "@/app/_components/agent-chat";\n\nexport default function NewSessionPage() {\n return <AgentChat sessionless />;\n}\n',
"components/ai-elements/chain-of-thought.tsx":
'"use client";\n\nimport { useControllableState } from "@radix-ui/react-use-controllable-state";\nimport { Badge } from "@/components/ui/badge";\nimport { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";\nimport { cn } from "@/lib/utils";\nimport type { LucideIcon } from "lucide-react";\nimport { BrainIcon, ChevronDownIcon, DotIcon } from "lucide-react";\nimport type { ComponentProps, ReactNode } from "react";\nimport { createContext, memo, useContext, useMemo } from "react";\n\ninterface ChainOfThoughtContextValue {\n isOpen: boolean;\n setIsOpen: (open: boolean) => void;\n}\n\nconst ChainOfThoughtContext = createContext<ChainOfThoughtContextValue | null>(null);\n\nconst useChainOfThought = () => {\n const context = useContext(ChainOfThoughtContext);\n if (!context) {\n throw new Error("ChainOfThought components must be used within ChainOfThought");\n }\n return context;\n};\n\nexport type ChainOfThoughtProps = ComponentProps<"div"> & {\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n};\n\nexport const ChainOfThought = memo(\n ({\n className,\n open,\n defaultOpen = false,\n onOpenChange,\n children,\n ...props\n }: ChainOfThoughtProps) => {\n const [isOpen, setIsOpen] = useControllableState({\n defaultProp: defaultOpen,\n onChange: onOpenChange,\n prop: open,\n });\n\n const chainOfThoughtContext = useMemo(() => ({ isOpen, setIsOpen }), [isOpen, setIsOpen]);\n\n return (\n <ChainOfThoughtContext.Provider value={chainOfThoughtContext}>\n <div className={cn("not-prose w-full space-y-4", className)} {...props}>\n {children}\n </div>\n </ChainOfThoughtContext.Provider>\n );\n },\n);\n\nexport type ChainOfThoughtHeaderProps = ComponentProps<typeof CollapsibleTrigger>;\n\nexport const ChainOfThoughtHeader = memo(\n ({ className, children, ...props }: ChainOfThoughtHeaderProps) => {\n const { isOpen, setIsOpen } = useChainOfThought();\n\n return (\n <Collapsible onOpenChange={setIsOpen} open={isOpen}>\n <CollapsibleTrigger\n className={cn(\n "flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",\n className,\n )}\n {...props}\n >\n <BrainIcon className="size-4" />\n <span className="flex-1 text-left">{children ?? "Chain of Thought"}</span>\n <ChevronDownIcon\n className={cn("size-4 transition-transform", isOpen ? "rotate-180" : "rotate-0")}\n />\n </CollapsibleTrigger>\n </Collapsible>\n );\n },\n);\n\nexport type ChainOfThoughtStepProps = ComponentProps<"div"> & {\n icon?: LucideIcon;\n label: ReactNode;\n description?: ReactNode;\n status?: "complete" | "active" | "pending";\n};\n\nconst stepStatusStyles = {\n active: "text-foreground",\n complete: "text-muted-foreground",\n pending: "text-muted-foreground/50",\n};\n\nexport const ChainOfThoughtStep = memo(\n ({\n className,\n icon: Icon = DotIcon,\n label,\n description,\n status = "complete",\n children,\n ...props\n }: ChainOfThoughtStepProps) => (\n <div\n className={cn(\n "flex gap-2 text-sm",\n stepStatusStyles[status],\n "fade-in-0 slide-in-from-top-2 animate-in",\n className,\n )}\n {...props}\n >\n <div className="relative mt-0.5">\n <Icon className="size-4" />\n <div className="absolute top-7 bottom-0 left-1/2 -mx-px w-px bg-border" />\n </div>\n <div className="flex-1 space-y-2 overflow-hidden">\n <div>{label}</div>\n {description && <div className="text-muted-foreground text-xs">{description}</div>}\n {children}\n </div>\n </div>\n ),\n);\n\nexport type ChainOfThoughtSearchResultsProps = ComponentProps<"div">;\n\nexport const ChainOfThoughtSearchResults = memo(\n ({ className, ...props }: ChainOfThoughtSearchResultsProps) => (\n <div className={cn("flex flex-wrap items-center gap-2", className)} {...props} />\n ),\n);\n\nexport type ChainOfThoughtSearchResultProps = ComponentProps<typeof Badge>;\n\nexport const ChainOfThoughtSearchResult = memo(\n ({ className, children, ...props }: ChainOfThoughtSearchResultProps) => (\n <Badge\n className={cn("gap-1 px-2 py-0.5 font-normal text-xs", className)}\n variant="secondary"\n {...props}\n >\n {children}\n </Badge>\n ),\n);\n\nexport type ChainOfThoughtContentProps = ComponentProps<typeof CollapsibleContent>;\n\nexport const ChainOfThoughtContent = memo(\n ({ className, children, ...props }: ChainOfThoughtContentProps) => {\n const { isOpen } = useChainOfThought();\n\n return (\n <Collapsible open={isOpen}>\n <CollapsibleContent\n className={cn(\n "mt-2 space-y-3",\n "data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",\n className,\n )}\n {...props}\n >\n {children}\n </CollapsibleContent>\n </Collapsible>\n );\n },\n);\n\nexport type ChainOfThoughtImageProps = ComponentProps<"div"> & {\n caption?: string;\n};\n\nexport const ChainOfThoughtImage = memo(\n ({ className, children, caption, ...props }: ChainOfThoughtImageProps) => (\n <div className={cn("mt-2 space-y-2", className)} {...props}>\n <div className="relative flex max-h-[22rem] items-center justify-center overflow-hidden rounded-lg bg-muted p-3">\n {children}\n </div>\n {caption && <p className="text-muted-foreground text-xs">{caption}</p>}\n </div>\n ),\n);\n\nChainOfThought.displayName = "ChainOfThought";\nChainOfThoughtHeader.displayName = "ChainOfThoughtHeader";\nChainOfThoughtStep.displayName = "ChainOfThoughtStep";\nChainOfThoughtSearchResults.displayName = "ChainOfThoughtSearchResults";\nChainOfThoughtSearchResult.displayName = "ChainOfThoughtSearchResult";\nChainOfThoughtContent.displayName = "ChainOfThoughtContent";\nChainOfThoughtImage.displayName = "ChainOfThoughtImage";\n',
"components/ai-elements/code-block.tsx":
'"use client";\n\nimport { Button } from "@/components/ui/button";\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from "@/components/ui/select";\nimport { cn } from "@/lib/utils";\nimport { CheckIcon, CopyIcon } from "lucide-react";\nimport type { ComponentProps, CSSProperties, HTMLAttributes } from "react";\nimport {\n createContext,\n memo,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from "react";\nimport type { BundledLanguage, BundledTheme, HighlighterGeneric, ThemedToken } from "shiki";\nimport { createHighlighter } from "shiki";\n\n// Shiki uses bitflags for font styles: 1=italic, 2=bold, 4=underline\n// oxlint-disable-next-line eslint(no-bitwise)\nconst isItalic = (fontStyle: number | undefined) => fontStyle && fontStyle & 1;\n// oxlint-disable-next-line eslint(no-bitwise)\nconst isBold = (fontStyle: number | undefined) => fontStyle && fontStyle & 2;\nconst isUnderline = (fontStyle: number | undefined) =>\n // oxlint-disable-next-line eslint(no-bitwise)\n fontStyle && fontStyle & 4;\n\n// Transform tokens to include pre-computed keys to avoid noArrayIndexKey lint\ninterface KeyedToken {\n token: ThemedToken;\n key: string;\n}\ninterface KeyedLine {\n tokens: KeyedToken[];\n key: string;\n}\n\nconst addKeysToTokens = (lines: ThemedToken[][]): KeyedLine[] =>\n lines.map((line, lineIdx) => ({\n key: `line-${lineIdx}`,\n tokens: line.map((token, tokenIdx) => ({\n key: `line-${lineIdx}-${tokenIdx}`,\n token,\n })),\n }));\n\n// Token rendering component\nconst TokenSpan = ({ token }: { token: ThemedToken }) => (\n <span\n className="dark:!bg-[var(--shiki-dark-bg)] dark:!text-[var(--shiki-dark)]"\n style={\n {\n backgroundColor: token.bgColor,\n color: token.color,\n fontStyle: isItalic(token.fontStyle) ? "italic" : undefined,\n fontWeight: isBold(token.fontStyle) ? "bold" : undefined,\n textDecoration: isUnderline(token.fontStyle) ? "underline" : undefined,\n ...token.htmlStyle,\n } as CSSProperties\n }\n >\n {token.content}\n </span>\n);\n\n// Line number styles using CSS counters\nconst LINE_NUMBER_CLASSES = cn(\n "block",\n "before:content-[counter(line)]",\n "before:inline-block",\n "before:[counter-increment:line]",\n "before:w-8",\n "before:mr-4",\n "before:text-right",\n "before:text-muted-foreground/50",\n "before:font-mono",\n "before:select-none",\n);\n\n// Line rendering component\nconst LineSpan = ({\n keyedLine,\n showLineNumbers,\n}: {\n keyedLine: KeyedLine;\n showLineNumbers: boolean;\n}) => (\n <span className={showLineNumbers ? LINE_NUMBER_CLASSES : "block"}>\n {keyedLine.tokens.length === 0\n ? "\\n"\n : keyedLine.tokens.map(({ token, key }) => <TokenSpan key={key} token={token} />)}\n </span>\n);\n\n// Types\ntype CodeBlockProps = HTMLAttributes<HTMLDivElement> & {\n code: string;\n language: BundledLanguage;\n showLineNumbers?: boolean;\n};\n\ninterface TokenizedCode {\n tokens: ThemedToken[][];\n fg: string;\n bg: string;\n}\n\ninterface CodeBlockContextType {\n code: string;\n}\n\n// Context\nconst CodeBlockContext = createContext<CodeBlockContextType>({\n code: "",\n});\n\n// Highlighter cache (singleton per language)\nconst highlighterCache = new Map<\n string,\n Promise<HighlighterGeneric<BundledLanguage, BundledTheme>>\n>();\n\n// Token cache\nconst tokensCache = new Map<string, TokenizedCode>();\n\n// Subscribers for async token updates\nconst subscribers = new Map<string, Set<(result: TokenizedCode) => void>>();\n\nconst getTokensCacheKey = (code: string, language: BundledLanguage) => {\n const start = code.slice(0, 100);\n const end = code.length > 100 ? code.slice(-100) : "";\n return `${language}:${code.length}:${start}:${end}`;\n};\n\nconst getHighlighter = (\n language: BundledLanguage,\n): Promise<HighlighterGeneric<BundledLanguage, BundledTheme>> => {\n const cached = highlighterCache.get(language);\n if (cached) {\n return cached;\n }\n\n const highlighterPromise = createHighlighter({\n langs: [language],\n themes: ["github-light", "github-dark"],\n });\n\n highlighterCache.set(language, highlighterPromise);\n return highlighterPromise;\n};\n\n// Create raw tokens for immediate display while highlighting loads\nconst createRawTokens = (code: string): TokenizedCode => ({\n bg: "transparent",\n fg: "inherit",\n tokens: code.split("\\n").map((line) =>\n line === ""\n ? []\n : [\n {\n color: "inherit",\n content: line,\n } as ThemedToken,\n ],\n ),\n});\n\n// Synchronous highlight with callback for async results\nexport const highlightCode = (\n code: string,\n language: BundledLanguage,\n // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-callbacks)\n callback?: (result: TokenizedCode) => void,\n): TokenizedCode | null => {\n const tokensCacheKey = getTokensCacheKey(code, language);\n\n // Return cached result if available\n const cached = tokensCache.get(tokensCacheKey);\n if (cached) {\n return cached;\n }\n\n // Subscribe callback if provided\n if (callback) {\n if (!subscribers.has(tokensCacheKey)) {\n subscribers.set(tokensCacheKey, new Set());\n }\n subscribers.get(tokensCacheKey)?.add(callback);\n }\n\n // Start highlighting in background - fire-and-forget async pattern\n getHighlighter(language)\n // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-then)\n .then((highlighter) => {\n const availableLangs = highlighter.getLoadedLanguages();\n const langToUse = availableLangs.includes(language) ? language : "text";\n\n const result = highlighter.codeToTokens(code, {\n lang: langToUse,\n themes: {\n dark: "github-dark",\n light: "github-light",\n },\n });\n\n const tokenized: TokenizedCode = {\n bg: result.bg ?? "transparent",\n fg: result.fg ?? "inherit",\n tokens: result.tokens,\n };\n\n // Cache the result\n tokensCache.set(tokensCacheKey, tokenized);\n\n // Notify all subscribers\n const subs = subscribers.get(tokensCacheKey);\n if (subs) {\n for (const sub of subs) {\n sub(tokenized);\n }\n subscribers.delete(tokensCacheKey);\n }\n })\n // oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-then), eslint-plugin-promise(prefer-await-to-callbacks)\n .catch((error) => {\n console.error("Failed to highlight code:", error);\n subscribers.delete(tokensCacheKey);\n });\n\n return null;\n};\n\nconst CodeBlockBody = memo(\n ({\n tokenized,\n showLineNumbers,\n className,\n }: {\n tokenized: TokenizedCode;\n showLineNumbers: boolean;\n className?: string;\n }) => {\n const preStyle = useMemo(\n () => ({\n backgroundColor: tokenized.bg,\n color: tokenized.fg,\n }),\n [tokenized.bg, tokenized.fg],\n );\n\n const keyedLines = useMemo(() => addKeysToTokens(tokenized.tokens), [tokenized.tokens]);\n\n return (\n <pre\n className={cn(\n "dark:!bg-[var(--shiki-dark-bg)] dark:!text-[var(--shiki-dark)] m-0 p-4 text-sm",\n className,\n )}\n style={preStyle}\n >\n <code\n className={cn(\n "font-mono text-sm",\n showLineNumbers && "[counter-increment:line_0] [counter-reset:line]",\n )}\n >\n {keyedLines.map((keyedLine) => (\n <LineSpan key={keyedLine.key} keyedLine={keyedLine} showLineNumbers={showLineNumbers} />\n ))}\n </code>\n </pre>\n );\n },\n (prevProps, nextProps) =>\n prevProps.tokenized === nextProps.tokenized &&\n prevProps.showLineNumbers === nextProps.showLineNumbers &&\n prevProps.className === nextProps.className,\n);\n\nCodeBlockBody.displayName = "CodeBlockBody";\n\nexport const CodeBlockContainer = ({\n className,\n language,\n style,\n ...props\n}: HTMLAttributes<HTMLDivElement> & { language: string }) => (\n <div\n className={cn(\n "group relative w-full overflow-hidden rounded-md border bg-background text-foreground",\n className,\n )}\n data-language={language}\n style={{\n containIntrinsicSize: "auto 200px",\n contentVisibility: "auto",\n ...style,\n }}\n {...props}\n />\n);\n\nexport const CodeBlockHeader = ({\n children,\n className,\n ...props\n}: HTMLAttributes<HTMLDivElement>) => (\n <div\n className={cn(\n "flex items-center justify-between border-b bg-muted/80 px-3 py-2 text-muted-foreground text-xs",\n className,\n )}\n {...props}\n >\n {children}\n </div>\n);\n\nexport const CodeBlockTitle = ({\n children,\n className,\n ...props\n}: HTMLAttributes<HTMLDivElement>) => (\n <div className={cn("flex items-center gap-2", className)} {...props}>\n {children}\n </div>\n);\n\nexport const CodeBlockFilename = ({\n children,\n className,\n ...props\n}: HTMLAttributes<HTMLSpanElement>) => (\n <span className={cn("font-mono", className)} {...props}>\n {children}\n </span>\n);\n\nexport const CodeBlockActions = ({\n children,\n className,\n ...props\n}: HTMLAttributes<HTMLDivElement>) => (\n <div className={cn("-my-1 -mr-1 flex items-center gap-2", className)} {...props}>\n {children}\n </div>\n);\n\nexport const CodeBlockContent = ({\n code,\n language,\n showLineNumbers = false,\n}: {\n code: string;\n language: BundledLanguage;\n showLineNumbers?: boolean;\n}) => {\n // Memoized raw tokens for immediate display\n const rawTokens = useMemo(() => createRawTokens(code), [code]);\n\n // Synchronous cache lookup — avoids setState in effect for cached results\n const syncTokens = useMemo(\n () => highlightCode(code, language) ?? rawTokens,\n [code, language, rawTokens],\n );\n\n // Async highlighting result (populated after shiki loads)\n const [asyncTokens, setAsyncTokens] = useState<TokenizedCode | null>(null);\n const asyncKeyRef = useRef({ code, language });\n\n // Invalidate stale async tokens synchronously during render\n if (asyncKeyRef.current.code !== code || asyncKeyRef.current.language !== language) {\n asyncKeyRef.current = { code, language };\n setAsyncTokens(null);\n }\n\n useEffect(() => {\n let cancelled = false;\n\n highlightCode(code, language, (result) => {\n if (!cancelled) {\n setAsyncTokens(result);\n }\n });\n\n return () => {\n cancelled = true;\n };\n }, [code, language]);\n\n const tokenized = asyncTokens ?? syncTokens;\n\n return (\n <div className="relative overflow-auto">\n <CodeBlockBody showLineNumbers={showLineNumbers} tokenized={tokenized} />\n </div>\n );\n};\n\nexport const CodeBlock = ({\n code,\n language,\n showLineNumbers = false,\n className,\n children,\n ...props\n}: CodeBlockProps) => {\n const contextValue = useMemo(() => ({ code }), [code]);\n\n return (\n <CodeBlockContext.Provider value={contextValue}>\n <CodeBlockContainer className={className} language={language} {...props}>\n {children}\n <CodeBlockContent code={code} language={language} showLineNumbers={showLineNumbers} />\n </CodeBlockContainer>\n </CodeBlockContext.Provider>\n );\n};\n\nexport type CodeBlockCopyButtonProps = ComponentProps<typeof Button> & {\n onCopy?: () => void;\n onError?: (error: Error) => void;\n timeout?: number;\n};\n\nexport const CodeBlockCopyButton = ({\n onCopy,\n onError,\n timeout = 2000,\n children,\n className,\n ...props\n}: CodeBlockCopyButtonProps) => {\n const [isCopied, setIsCopied] = useState(false);\n const timeoutRef = useRef<number>(0);\n const { code } = useContext(CodeBlockContext);\n\n const copyToClipboard = useCallback(async () => {\n if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {\n onError?.(new Error("Clipboard API not available"));\n return;\n }\n\n try {\n if (!isCopied) {\n await navigator.clipboard.writeText(code);\n setIsCopied(true);\n onCopy?.();\n timeoutRef.current = window.setTimeout(() => setIsCopied(false), timeout);\n }\n } catch (error) {\n onError?.(error as Error);\n }\n }, [code, onCopy, onError, timeout, isCopied]);\n\n useEffect(\n () => () => {\n window.clearTimeout(timeoutRef.current);\n },\n [],\n );\n\n const Icon = isCopied ? CheckIcon : CopyIcon;\n\n return (\n <Button\n className={cn("shrink-0", className)}\n onClick={copyToClipboard}\n size="icon"\n variant="ghost"\n {...props}\n >\n {children ?? <Icon size={14} />}\n </Button>\n );\n};\n\nexport type CodeBlockLanguageSelectorProps = ComponentProps<typeof Select>;\n\nexport const CodeBlockLanguageSelector = (props: CodeBlockLanguageSelectorProps) => (\n <Select {...props} />\n);\n\nexport type CodeBlockLanguageSelectorTriggerProps = ComponentProps<typeof SelectTrigger>;\n\nexport const CodeBlockLanguageSelectorTrigger = ({\n className,\n ...props\n}: CodeBlockLanguageSelectorTriggerProps) => (\n <SelectTrigger\n className={cn("h-7 border-none bg-transparent px-2 text-xs shadow-none", className)}\n size="sm"\n {...props}\n />\n);\n\nexport type CodeBlockLanguageSelectorValueProps = ComponentProps<typeof SelectValue>;\n\nexport const CodeBlockLanguageSelectorValue = (props: CodeBlockLanguageSelectorValueProps) => (\n <SelectValue {...props} />\n);\n\nexport type CodeBlockLanguageSelectorContentProps = ComponentProps<typeof SelectContent>;\n\nexport const CodeBlockLanguageSelectorContent = ({\n align = "end",\n ...props\n}: CodeBlockLanguageSelectorContentProps) => <SelectContent align={align} {...props} />;\n\nexport type CodeBlockLanguageSelectorItemProps = ComponentProps<typeof SelectItem>;\n\nexport const CodeBlockLanguageSelectorItem = (props: CodeBlockLanguageSelectorItemProps) => (\n <SelectItem {...props} />\n);\n',
"components/ai-elements/conversation.tsx":
- '"use client";\n\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\nimport type { UIMessage } from "ai";\nimport { ArrowDownIcon, DownloadIcon } from "lucide-react";\nimport type { ComponentProps } from "react";\nimport { useCallback } from "react";\nimport { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";\n\nexport type ConversationProps = ComponentProps<typeof StickToBottom>;\n\nexport const Conversation = ({ className, ...props }: ConversationProps) => (\n <StickToBottom\n className={cn("relative flex-1 overflow-y-hidden", className)}\n initial="smooth"\n resize="smooth"\n role="log"\n {...props}\n />\n);\n\nexport type ConversationContentProps = ComponentProps<typeof StickToBottom.Content>;\n\nexport const ConversationContent = ({ className, ...props }: ConversationContentProps) => (\n <StickToBottom.Content className={cn("flex flex-col gap-8 p-4", className)} {...props} />\n);\n\nexport type ConversationEmptyStateProps = ComponentProps<"div"> & {\n title?: string;\n description?: string;\n icon?: React.ReactNode;\n};\n\nexport const ConversationEmptyState = ({\n className,\n title = "No messages yet",\n description = "Start a conversation to see messages here",\n icon,\n children,\n ...props\n}: ConversationEmptyStateProps) => (\n <div\n className={cn(\n "flex size-full flex-col items-center justify-center gap-3 p-8 text-center",\n className,\n )}\n {...props}\n >\n {children ?? (\n <>\n {icon && <div className="text-muted-foreground">{icon}</div>}\n <div className="space-y-1">\n <h3 className="font-medium text-sm">{title}</h3>\n {description && <p className="text-muted-foreground text-sm">{description}</p>}\n </div>\n </>\n )}\n </div>\n);\n\nexport type ConversationScrollButtonProps = ComponentProps<typeof Button>;\n\nexport const ConversationScrollButton = ({\n className,\n ...props\n}: ConversationScrollButtonProps) => {\n const { isAtBottom, scrollToBottom } = useStickToBottomContext();\n\n const handleScrollToBottom = useCallback(() => {\n scrollToBottom();\n }, [scrollToBottom]);\n\n return (\n !isAtBottom && (\n <Button\n className={cn(\n "absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full dark:bg-background dark:hover:bg-muted",\n className,\n )}\n onClick={handleScrollToBottom}\n size="icon"\n type="button"\n variant="outline"\n {...props}\n >\n <ArrowDownIcon className="size-4" />\n </Button>\n )\n );\n};\n\nconst getMessageText = (message: UIMessage): string =>\n message.parts\n .filter((part) => part.type === "text")\n .map((part) => part.text)\n .join("");\n\nexport type ConversationDownloadProps = Omit<ComponentProps<typeof Button>, "onClick"> & {\n messages: UIMessage[];\n filename?: string;\n formatMessage?: (message: UIMessage, index: number) => string;\n};\n\nconst defaultFormatMessage = (message: UIMessage): string => {\n const roleLabel = message.role.charAt(0).toUpperCase() + message.role.slice(1);\n return `**${roleLabel}:** ${getMessageText(message)}`;\n};\n\nexport const messagesToMarkdown = (\n messages: UIMessage[],\n formatMessage: (message: UIMessage, index: number) => string = defaultFormatMessage,\n): string => messages.map((msg, i) => formatMessage(msg, i)).join("\\n\\n");\n\nexport const ConversationDownload = ({\n messages,\n filename = "conversation.md",\n formatMessage = defaultFormatMessage,\n className,\n children,\n ...props\n}: ConversationDownloadProps) => {\n const handleDownload = useCallback(() => {\n const markdown = messagesToMarkdown(messages, formatMessage);\n const blob = new Blob([markdown], { type: "text/markdown" });\n const url = URL.createObjectURL(blob);\n const link = document.createElement("a");\n link.href = url;\n link.download = filename;\n document.body.append(link);\n link.click();\n link.remove();\n URL.revokeObjectURL(url);\n }, [messages, filename, formatMessage]);\n\n return (\n <Button\n className={cn(\n "absolute top-4 right-4 rounded-full dark:bg-background dark:hover:bg-muted",\n className,\n )}\n onClick={handleDownload}\n size="icon"\n type="button"\n variant="outline"\n {...props}\n >\n {children ?? <DownloadIcon className="size-4" />}\n </Button>\n );\n};\n',
+ '"use client";\n\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\nimport type { UIMessage } from "ai";\nimport { ArrowDownIcon, DownloadIcon } from "lucide-react";\nimport type { ComponentProps } from "react";\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";\nimport { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";\n\nexport type ConversationProps = ComponentProps<typeof StickToBottom> & {\n scrollRestorationKey?: string;\n};\n\nexport const Conversation = ({\n children,\n className,\n initial,\n scrollRestorationKey,\n ...props\n}: ConversationProps) => (\n <StickToBottom\n className={cn("relative flex-1 overflow-y-hidden", className)}\n initial={initial ?? (scrollRestorationKey === undefined ? "smooth" : false)}\n resize="smooth"\n role="log"\n {...props}\n >\n {typeof children === "function" ? (\n (context) => (\n <>\n {children(context)}\n {scrollRestorationKey === undefined ? null : (\n <ConversationScrollRestoration storageKey={scrollRestorationKey} />\n )}\n </>\n )\n ) : (\n <>\n {children}\n {scrollRestorationKey === undefined ? null : (\n <ConversationScrollRestoration storageKey={scrollRestorationKey} />\n )}\n </>\n )}\n </StickToBottom>\n);\n\nfunction ConversationScrollRestoration({ storageKey }: { readonly storageKey: string }) {\n const { scrollRef, scrollToBottom, state } = useStickToBottomContext();\n const restoredKeyRef = useRef<string | undefined>(undefined);\n\n useLayoutEffect(() => {\n const scrollElement = scrollRef.current;\n if (scrollElement === null) return;\n\n if (restoredKeyRef.current !== storageKey) {\n const saved = readScrollPosition(sessionStorage.getItem(storageKey));\n if (saved?.atBottom === false) {\n scrollElement.scrollTop = saved.scrollTop;\n requestAnimationFrame(() => {\n scrollElement.scrollTop = saved.scrollTop;\n });\n } else {\n scrollElement.scrollTop = scrollElement.scrollHeight;\n scrollToBottom({ animation: "instant", ignoreEscapes: true });\n }\n restoredKeyRef.current = storageKey;\n }\n\n const saveNow = () => {\n sessionStorage.setItem(\n storageKey,\n JSON.stringify({\n atBottom: state.isAtBottom || state.isNearBottom,\n scrollTop: scrollElement.scrollTop,\n }),\n );\n };\n let frame: number | undefined;\n const scheduleSave = () => {\n if (frame !== undefined) return;\n frame = requestAnimationFrame(() => {\n frame = undefined;\n saveNow();\n });\n };\n scrollElement.addEventListener("scroll", scheduleSave, { passive: true });\n window.addEventListener("pagehide", saveNow);\n return () => {\n scrollElement.removeEventListener("scroll", scheduleSave);\n window.removeEventListener("pagehide", saveNow);\n if (frame !== undefined) cancelAnimationFrame(frame);\n saveNow();\n };\n }, [scrollRef, scrollToBottom, state, storageKey]);\n\n return null;\n}\n\nfunction readScrollPosition(value: string | null):\n | {\n readonly atBottom: boolean;\n readonly scrollTop: number;\n }\n | undefined {\n if (value === null) return undefined;\n try {\n const parsed = JSON.parse(value) as { atBottom?: unknown; scrollTop?: unknown };\n return typeof parsed.atBottom === "boolean" && typeof parsed.scrollTop === "number"\n ? { atBottom: parsed.atBottom, scrollTop: parsed.scrollTop }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport type ConversationContentProps = ComponentProps<typeof StickToBottom.Content>;\n\nexport const ConversationContent = ({ className, ...props }: ConversationContentProps) => (\n <StickToBottom.Content className={cn("flex flex-col gap-8 p-4", className)} {...props} />\n);\n\nexport type ConversationEmptyStateProps = ComponentProps<"div"> & {\n title?: string;\n description?: string;\n icon?: React.ReactNode;\n};\n\nexport const ConversationEmptyState = ({\n className,\n title = "No messages yet",\n description = "Start a conversation to see messages here",\n icon,\n children,\n ...props\n}: ConversationEmptyStateProps) => (\n <div\n className={cn(\n "flex size-full flex-col items-center justify-center gap-3 p-8 text-center",\n className,\n )}\n {...props}\n >\n {children ?? (\n <>\n {icon && <div className="text-muted-foreground">{icon}</div>}\n <div className="space-y-1">\n <h3 className="font-medium text-sm">{title}</h3>\n {description && <p className="text-muted-foreground text-sm">{description}</p>}\n </div>\n </>\n )}\n </div>\n);\n\nexport type ConversationScrollButtonProps = ComponentProps<typeof Button>;\n\nexport const ConversationScrollButton = ({\n className,\n ...props\n}: ConversationScrollButtonProps) => {\n const { isAtBottom, scrollToBottom } = useStickToBottomContext();\n const [isReady, setIsReady] = useState(false);\n\n useEffect(() => setIsReady(true), []);\n\n const handleScrollToBottom = useCallback(() => {\n scrollToBottom();\n }, [scrollToBottom]);\n\n return (\n isReady &&\n !isAtBottom && (\n <Button\n aria-label="Scroll to bottom"\n className={cn(\n "absolute bottom-32 left-[50%] translate-x-[-50%] rounded-full dark:bg-background dark:hover:bg-muted",\n className,\n )}\n onClick={handleScrollToBottom}\n size="icon"\n type="button"\n variant="outline"\n {...props}\n >\n <ArrowDownIcon className="size-4" />\n </Button>\n )\n );\n};\n\nconst getMessageText = (message: UIMessage): string =>\n message.parts\n .filter((part) => part.type === "text")\n .map((part) => part.text)\n .join("");\n\nexport type ConversationDownloadProps = Omit<ComponentProps<typeof Button>, "onClick"> & {\n messages: UIMessage[];\n filename?: string;\n formatMessage?: (message: UIMessage, index: number) => string;\n};\n\nconst defaultFormatMessage = (message: UIMessage): string => {\n const roleLabel = message.role.charAt(0).toUpperCase() + message.role.slice(1);\n return `**${roleLabel}:** ${getMessageText(message)}`;\n};\n\nexport const messagesToMarkdown = (\n messages: UIMessage[],\n formatMessage: (message: UIMessage, index: number) => string = defaultFormatMessage,\n): string => messages.map((msg, i) => formatMessage(msg, i)).join("\\n\\n");\n\nexport const ConversationDownload = ({\n messages,\n filename = "conversation.md",\n formatMessage = defaultFormatMessage,\n className,\n children,\n ...props\n}: ConversationDownloadProps) => {\n const handleDownload = useCallback(() => {\n const markdown = messagesToMarkdown(messages, formatMessage);\n const blob = new Blob([markdown], { type: "text/markdown" });\n const url = URL.createObjectURL(blob);\n const link = document.createElement("a");\n link.href = url;\n link.download = filename;\n document.body.append(link);\n link.click();\n link.remove();\n URL.revokeObjectURL(url);\n }, [messages, filename, formatMessage]);\n\n return (\n <Button\n className={cn(\n "absolute top-4 right-4 rounded-full dark:bg-background dark:hover:bg-muted",\n className,\n )}\n onClick={handleDownload}\n size="icon"\n type="button"\n variant="outline"\n {...props}\n >\n {children ?? <DownloadIcon className="size-4" />}\n </Button>\n );\n};\n',
"components/ai-elements/message.tsx":
'"use client";\n\nimport { Button } from "@/components/ui/button";\nimport { ButtonGroup, ButtonGroupText } from "@/components/ui/button-group";\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";\nimport { cn } from "@/lib/utils";\nimport { cjk } from "@streamdown/cjk";\nimport { code } from "@streamdown/code";\nimport { math } from "@streamdown/math";\nimport { mermaid } from "@streamdown/mermaid";\nimport type { UIMessage } from "ai";\nimport { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";\nimport type { ComponentProps, HTMLAttributes, ReactElement } from "react";\nimport { createContext, memo, useCallback, useContext, useEffect, useMemo, useState } from "react";\nimport { Streamdown } from "streamdown";\n\nexport type MessageProps = HTMLAttributes<HTMLDivElement> & {\n from: UIMessage["role"];\n};\n\nexport const Message = ({ className, from, ...props }: MessageProps) => (\n <div\n className={cn(\n "group flex w-full max-w-[95%] flex-col gap-2",\n from === "user" ? "is-user ml-auto justify-end" : "is-assistant",\n className,\n )}\n {...props}\n />\n);\n\nexport type MessageContentProps = HTMLAttributes<HTMLDivElement>;\n\nexport const MessageContent = ({ children, className, ...props }: MessageContentProps) => (\n <div\n className={cn(\n "is-user:dark flex w-fit min-w-0 max-w-full flex-col gap-2 overflow-hidden text-sm",\n "group-[.is-user]:ml-auto group-[.is-user]:rounded-2xl group-[.is-user]:bg-primary group-[.is-user]:px-4 group-[.is-user]:py-2.5 group-[.is-user]:text-primary-foreground",\n "group-[.is-assistant]:w-full group-[.is-assistant]:text-foreground",\n "group-data-[optimistic=true]:opacity-70",\n className,\n )}\n {...props}\n >\n {children}\n </div>\n);\n\nexport type MessageActionsProps = ComponentProps<"div">;\n\nexport const MessageActions = ({ className, children, ...props }: MessageActionsProps) => (\n <div className={cn("flex items-center gap-1", className)} {...props}>\n {children}\n </div>\n);\n\nexport type MessageActionProps = ComponentProps<typeof Button> & {\n tooltip?: string;\n label?: string;\n};\n\nexport const MessageAction = ({\n tooltip,\n children,\n label,\n variant = "ghost",\n size = "icon-sm",\n ...props\n}: MessageActionProps) => {\n const button = (\n <Button size={size} type="button" variant={variant} {...props}>\n {children}\n <span className="sr-only">{label || tooltip}</span>\n </Button>\n );\n\n if (tooltip) {\n return (\n <TooltipProvider>\n <Tooltip>\n <TooltipTrigger asChild>{button}</TooltipTrigger>\n <TooltipContent>\n <p>{tooltip}</p>\n </TooltipContent>\n </Tooltip>\n </TooltipProvider>\n );\n }\n\n return button;\n};\n\ninterface MessageBranchContextType {\n currentBranch: number;\n totalBranches: number;\n goToPrevious: () => void;\n goToNext: () => void;\n branches: ReactElement[];\n setBranches: (branches: ReactElement[]) => void;\n}\n\nconst MessageBranchContext = createContext<MessageBranchContextType | null>(null);\n\nconst useMessageBranch = () => {\n const context = useContext(MessageBranchContext);\n\n if (!context) {\n throw new Error("MessageBranch components must be used within MessageBranch");\n }\n\n return context;\n};\n\nexport type MessageBranchProps = HTMLAttributes<HTMLDivElement> & {\n defaultBranch?: number;\n onBranchChange?: (branchIndex: number) => void;\n};\n\nexport const MessageBranch = ({\n defaultBranch = 0,\n onBranchChange,\n className,\n ...props\n}: MessageBranchProps) => {\n const [currentBranch, setCurrentBranch] = useState(defaultBranch);\n const [branches, setBranches] = useState<ReactElement[]>([]);\n\n const handleBranchChange = useCallback(\n (newBranch: number) => {\n setCurrentBranch(newBranch);\n onBranchChange?.(newBranch);\n },\n [onBranchChange],\n );\n\n const goToPrevious = useCallback(() => {\n const newBranch = currentBranch > 0 ? currentBranch - 1 : branches.length - 1;\n handleBranchChange(newBranch);\n }, [currentBranch, branches.length, handleBranchChange]);\n\n const goToNext = useCallback(() => {\n const newBranch = currentBranch < branches.length - 1 ? currentBranch + 1 : 0;\n handleBranchChange(newBranch);\n }, [currentBranch, branches.length, handleBranchChange]);\n\n const contextValue = useMemo<MessageBranchContextType>(\n () => ({\n branches,\n currentBranch,\n goToNext,\n goToPrevious,\n setBranches,\n totalBranches: branches.length,\n }),\n [branches, currentBranch, goToNext, goToPrevious],\n );\n\n return (\n <MessageBranchContext.Provider value={contextValue}>\n <div className={cn("grid w-full gap-2 [&>div]:pb-0", className)} {...props} />\n </MessageBranchContext.Provider>\n );\n};\n\nexport type MessageBranchContentProps = HTMLAttributes<HTMLDivElement>;\n\nexport const MessageBranchContent = ({ children, ...props }: MessageBranchContentProps) => {\n const { currentBranch, setBranches, branches } = useMessageBranch();\n const childrenArray = useMemo(\n () => (Array.isArray(children) ? children : [children]),\n [children],\n );\n\n // Use useEffect to update branches when they change\n useEffect(() => {\n if (branches.length !== childrenArray.length) {\n setBranches(childrenArray);\n }\n }, [childrenArray, branches, setBranches]);\n\n return childrenArray.map((branch, index) => (\n <div\n className={cn(\n "grid gap-2 overflow-hidden [&>div]:pb-0",\n index === currentBranch ? "block" : "hidden",\n )}\n key={branch.key}\n {...props}\n >\n {branch}\n </div>\n ));\n};\n\nexport type MessageBranchSelectorProps = ComponentProps<typeof ButtonGroup>;\n\nexport const MessageBranchSelector = ({ className, ...props }: MessageBranchSelectorProps) => {\n const { totalBranches } = useMessageBranch();\n\n // Don\'t render if there\'s only one branch\n if (totalBranches <= 1) {\n return null;\n }\n\n return (\n <ButtonGroup\n className={cn(\n "[&>*:not(:first-child)]:rounded-l-md [&>*:not(:last-child)]:rounded-r-md",\n className,\n )}\n orientation="horizontal"\n {...props}\n />\n );\n};\n\nexport type MessageBranchPreviousProps = ComponentProps<typeof Button>;\n\nexport const MessageBranchPrevious = ({ children, ...props }: MessageBranchPreviousProps) => {\n const { goToPrevious, totalBranches } = useMessageBranch();\n\n return (\n <Button\n aria-label="Previous branch"\n disabled={totalBranches <= 1}\n onClick={goToPrevious}\n size="icon-sm"\n type="button"\n variant="ghost"\n {...props}\n >\n {children ?? <ChevronLeftIcon size={14} />}\n </Button>\n );\n};\n\nexport type MessageBranchNextProps = ComponentProps<typeof Button>;\n\nexport const MessageBranchNext = ({ children, ...props }: MessageBranchNextProps) => {\n const { goToNext, totalBranches } = useMessageBranch();\n\n return (\n <Button\n aria-label="Next branch"\n disabled={totalBranches <= 1}\n onClick={goToNext}\n size="icon-sm"\n type="button"\n variant="ghost"\n {...props}\n >\n {children ?? <ChevronRightIcon size={14} />}\n </Button>\n );\n};\n\nexport type MessageBranchPageProps = HTMLAttributes<HTMLSpanElement>;\n\nexport const MessageBranchPage = ({ className, ...props }: MessageBranchPageProps) => {\n const { currentBranch, totalBranches } = useMessageBranch();\n\n return (\n <ButtonGroupText\n className={cn("border-none bg-transparent text-muted-foreground shadow-none", className)}\n {...props}\n >\n {currentBranch + 1} of {totalBranches}\n </ButtonGroupText>\n );\n};\n\nexport type MessageResponseProps = ComponentProps<typeof Streamdown>;\n\nconst streamdownPlugins = { cjk, code, math, mermaid };\n\nexport const MessageResponse = memo(\n ({ className, ...props }: MessageResponseProps) => (\n <Streamdown\n className={cn("size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0", className)}\n plugins={streamdownPlugins}\n {...props}\n />\n ),\n (prevProps, nextProps) =>\n prevProps.children === nextProps.children && nextProps.isAnimating === prevProps.isAnimating,\n);\n\nMessageResponse.displayName = "MessageResponse";\n\nexport type MessageToolbarProps = ComponentProps<"div">;\n\nexport const MessageToolbar = ({ className, children, ...props }: MessageToolbarProps) => (\n <div className={cn("mt-4 flex w-full items-center justify-between gap-4", className)} {...props}>\n {children}\n </div>\n);\n',
"components/ai-elements/prompt-input.tsx":
@@ -80,6 +84,8 @@ export const WEB_APP_TEMPLATE_FILES = {
export const WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES = {
"agent/channels/eve.ts":
'import { eveChannel } from "eve/channels/eve";\nimport { localDev, type AuthFn, vercelOidc } from "eve/channels/auth";\nimport { auth } from "@/lib/auth";\n\nconst betterAuthSession: AuthFn<Request> = async (request) => {\n const session = await auth.api.getSession({ headers: request.headers });\n if (!session) return null;\n\n const attributes: Record<string, string> = {\n email: session.user.email,\n name: session.user.name,\n };\n if (session.user.image) {\n attributes.picture = session.user.image;\n }\n\n return {\n attributes,\n authenticator: "better-auth:vercel",\n principalId: session.user.id,\n principalType: "user",\n };\n};\n\nexport default eveChannel({\n auth: [betterAuthSession, vercelOidc(), localDev()],\n});\n',
+ "app/_components/authenticated-agent-chat.tsx":
+ 'import { headers } from "next/headers";\nimport { auth } from "@/lib/auth";\nimport { AgentChat } from "./agent-chat";\nimport { AccountControl, SignIn } from "./web-chat-auth";\n\nexport async function AuthenticatedAgentChat({\n sessionId,\n sessionless,\n}: {\n readonly sessionId?: string;\n readonly sessionless?: boolean;\n}) {\n if (process.env.NODE_ENV === "development") {\n return <AgentChat sessionId={sessionId} sessionless={sessionless} />;\n }\n\n const session = await auth.api.getSession({ headers: await headers() });\n if (!session) return <SignIn />;\n\n return (\n <>\n <AgentChat sessionId={sessionId} sessionless={sessionless} />\n <AccountControl\n email={session.user.email}\n image={session.user.image}\n name={session.user.name}\n />\n </>\n );\n}\n',
"app/_components/web-chat-auth.tsx":
'"use client";\n\nimport { LogOutIcon } from "lucide-react";\nimport { useState } from "react";\nimport { Button } from "@/components/ui/button";\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from "@/components/ui/dropdown-menu";\nimport { authClient } from "@/lib/auth-client";\n\nconst AGENT_NAME = "__EVE_INIT_APP_NAME__";\n\nexport function SignIn() {\n const [pending, setPending] = useState(false);\n const [error, setError] = useState<string>();\n\n async function signIn() {\n setPending(true);\n setError(undefined);\n try {\n const result = await authClient.signIn.social({\n callbackURL: "/",\n provider: "vercel",\n });\n if (!result.error) return;\n setPending(false);\n setError("Sign-in failed. Try again.");\n } catch {\n setPending(false);\n setError("Sign-in failed. Try again.");\n }\n }\n\n return (\n <main className="flex min-h-dvh items-center justify-center bg-background px-8 text-foreground">\n <div className="flex w-full max-w-[22rem] flex-col gap-5">\n <div className="text-foreground opacity-[0.08] dark:opacity-[0.12]">\n <EveWordmark className="h-auto w-[4.875rem]" />\n </div>\n <section aria-label="Sign in" className="flex flex-col gap-2">\n <h1 className="max-w-full break-words font-medium text-sm leading-6">{AGENT_NAME}</h1>\n <p className="flex flex-wrap items-center gap-2 text-muted-foreground text-sm leading-6">\n <span className="inline-flex items-center gap-2 text-emerald-600 dark:text-emerald-400">\n <span aria-hidden="true" className="size-1.5 rounded-full bg-current" />\n Ready\n </span>\n <span aria-hidden="true" className="text-border">\n /\n </span>\n <span>Sign in to start a session</span>\n </p>\n <Button className="mt-3 w-full gap-2 text-sm" disabled={pending} onClick={signIn}>\n <svg aria-hidden="true" className="size-3 fill-current" viewBox="0 0 24 20">\n <path d="M12 0 24 20H0L12 0Z" />\n </svg>\n <span className="leading-5">{pending ? "Redirecting…" : "Continue with Vercel"}</span>\n </Button>\n {error ? (\n <p className="text-destructive text-sm" role="alert">\n {error}\n </p>\n ) : null}\n </section>\n </div>\n </main>\n );\n}\n\nfunction EveWordmark({ className }: { readonly className?: string }) {\n return (\n <svg\n aria-hidden="true"\n className={className}\n fill="none"\n viewBox="0 0 169 53"\n xmlns="http://www.w3.org/2000/svg"\n >\n <path\n d="M169 8.47h-51.39L81.73 53H70.36L113 0H169zM169 44.51v8.47h-45.87V44.5zM45.87 52.98H0V44.5h45.87zM38.66 30.55H0v-8.47h38.66z"\n fill="currentColor"\n />\n <path d="M169 30.55h-38.66v-8.47H169zM75.52 8.47H0V0h75.52z" fill="currentColor" />\n </svg>\n );\n}\n\nexport function AccountControl({\n email,\n image,\n name,\n}: {\n readonly email: string;\n readonly image?: string | null;\n readonly name: string;\n}) {\n const [imageFailed, setImageFailed] = useState(false);\n const [pending, setPending] = useState(false);\n const initials = getInitials(name, email);\n\n async function signOut() {\n setPending(true);\n try {\n await authClient.signOut({\n fetchOptions: {\n onError: () => setPending(false),\n onSuccess: () => window.location.assign("/"),\n },\n });\n } catch {\n setPending(false);\n }\n }\n\n return (\n <div className="fixed top-3 right-3 z-10">\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n aria-label={`Open account menu for ${name}`}\n className="size-9 cursor-pointer overflow-hidden rounded-full p-0"\n size="icon"\n variant="outline"\n >\n {image && !imageFailed ? (\n <img\n alt=""\n className="size-full object-cover"\n onError={() => setImageFailed(true)}\n src={image}\n />\n ) : (\n <span aria-hidden="true" className="font-medium text-xs">\n {initials}\n </span>\n )}\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align="end" className="w-64">\n <div className="min-w-0 px-2 py-1.5 text-sm">\n <span className="block truncate font-medium leading-5" title={name}>\n {name}\n </span>\n <span className="block truncate text-muted-foreground leading-5" title={email}>\n {email}\n </span>\n </div>\n <DropdownMenuSeparator />\n <DropdownMenuItem\n className="cursor-pointer justify-between"\n disabled={pending}\n onSelect={signOut}\n >\n {pending ? "Logging out…" : "Log out"}\n <LogOutIcon aria-hidden="true" />\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n </div>\n );\n}\n\nfunction getInitials(name: string, email: string): string {\n const parts = name.trim().split(/\\s+/).filter(Boolean);\n if (parts.length >= 2) {\n return `${parts[0]?.[0] ?? ""}${parts.at(-1)?.[0] ?? ""}`.toUpperCase();\n }\n return (parts[0]?.[0] ?? email[0] ?? "?").toUpperCase();\n}\n',
"app/api/auth/[...all]/route.ts":
@@ -87,7 +93,11 @@ export const WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES = {
"app/layout.tsx":
'import type { Metadata } from "next";\nimport { Geist, Geist_Mono } from "next/font/google";\nimport type { ReactNode } from "react";\nimport { TooltipProvider } from "@/components/ui/tooltip";\nimport { cn } from "@/lib/utils";\nimport "./globals.css";\n\nconst sans = Geist({\n variable: "--font-sans",\n subsets: ["latin"],\n weight: "variable",\n display: "swap",\n});\n\nconst mono = Geist_Mono({\n variable: "--font-mono",\n subsets: ["latin"],\n weight: "variable",\n display: "swap",\n});\n\nexport const metadata: Metadata = {\n title: "__EVE_INIT_APP_NAME__",\n description: "A Next.js starter for eve agents with AI Elements.",\n};\n\n// The page and Eve routes validate the generated app\'s Better Auth session.\nexport default function RootLayout({ children }: { readonly children: ReactNode }) {\n return (\n <html className={cn(sans.variable, mono.variable)} lang="en">\n <body>\n <TooltipProvider>{children}</TooltipProvider>\n </body>\n </html>\n );\n}\n',
"app/page.tsx":
- 'import { headers } from "next/headers";\nimport { AgentChat } from "./_components/agent-chat";\nimport { AccountControl, SignIn } from "./_components/web-chat-auth";\nimport { auth } from "@/lib/auth";\n\nexport default async function Page() {\n if (process.env.NODE_ENV === "development") {\n return <AgentChat />;\n }\n\n const session = await auth.api.getSession({ headers: await headers() });\n if (!session) {\n return <SignIn />;\n }\n\n return (\n <>\n <AgentChat />\n <AccountControl\n email={session.user.email}\n image={session.user.image}\n name={session.user.name}\n />\n </>\n );\n}\n',
+ 'import { AuthenticatedAgentChat } from "./_components/authenticated-agent-chat";\n\nexport default function Page() {\n return <AuthenticatedAgentChat />;\n}\n',
+ "app/s/[sessionId]/page.tsx":
+ 'import { AuthenticatedAgentChat } from "@/app/_components/authenticated-agent-chat";\n\nexport default async function SessionPage({\n params,\n}: {\n readonly params: Promise<{ readonly sessionId: string }>;\n}) {\n const { sessionId } = await params;\n return <AuthenticatedAgentChat sessionId={sessionId} />;\n}\n',
+ "app/s/page.tsx":
+ 'import { AuthenticatedAgentChat } from "@/app/_components/authenticated-agent-chat";\n\nexport default function NewSessionPage() {\n return <AuthenticatedAgentChat sessionless />;\n}\n',
"lib/auth-client.ts":
'"use client";\n\nimport { createAuthClient } from "better-auth/react";\n\nexport const authClient = createAuthClient();\n',
"lib/auth.ts":
diff --git a/packages/eve/src/setup/scaffold/index.integration.test.ts b/packages/eve/src/setup/scaffold/index.integration.test.ts
index 9bfd68c44..7ff7e814c 100644
--- a/packages/eve/src/setup/scaffold/index.integration.test.ts
+++ b/packages/eve/src/setup/scaffold/index.integration.test.ts
@@ -239,7 +239,7 @@ describe("ensureChannel", () => {
join(projectRoot, "app/_components/agent-chat.tsx"),
"utf8",
);
- expect(agentChatSource).toContain("<PromptInputTextarea disabled={isBusy}");
+ expect(agentChatSource).toContain("disabled={isBusy || isRestoring}");
expect(agentChatSource).toContain("{showPendingThinking ? <PendingThinking /> : null}");
expect(agentChatSource).not.toContain("StatusDot");
await expect(readFile(join(projectRoot, "next.config.ts"), "utf8")).resolves.toContain(
@@ -309,9 +309,14 @@ describe("ensureChannel", () => {
expect(packageJson.dependencies.next).toBe("16.3.0");
const pageSource = await readFile(join(projectRoot, "app/page.tsx"), "utf8");
- expect(pageSource).toContain("auth.api.getSession");
- expect(pageSource).toContain("<SignIn />");
- expect(pageSource).toContain("<AccountControl");
+ expect(pageSource).toContain("<AuthenticatedAgentChat");
+ const authenticatedChatSource = await readFile(
+ join(projectRoot, "app/_components/authenticated-agent-chat.tsx"),
+ "utf8",
+ );
+ expect(authenticatedChatSource).toContain("auth.api.getSession");
+ expect(authenticatedChatSource).toContain("<SignIn />");
+ expect(authenticatedChatSource).toContain("<AccountControl");
const authSource = await readFile(join(projectRoot, "lib/auth.ts"), "utf8");
expect(authSource).toContain('requireEnvironmentVariable("BETTER_AUTH_SECRET")');
diff --git a/packages/eve/src/svelte/use-eve-agent.test.ts b/packages/eve/src/svelte/use-eve-agent.test.ts
index 1d4aef04a..0e29249dc 100644
--- a/packages/eve/src/svelte/use-eve-agent.test.ts
+++ b/packages/eve/src/svelte/use-eve-agent.test.ts
@@ -34,6 +34,12 @@ function createEagerStreamResponse(events: readonly UnstampedMessageStreamEvent[
);
}
+function createBoundedStreamResponse(events: readonly UnstampedMessageStreamEvent[]): Response {
+ const response = createEagerStreamResponse(events);
+ response.headers.set("x-eve-stream-tail-index", String(events.length - 1));
+ return response;
+}
+
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
@@ -81,6 +87,26 @@ describe("useEveAgent (Svelte rune binding)", () => {
expect(agent.status).toBe("ready");
});
+ it("automatically replays an initial session when resume is enabled", async () => {
+ vi.stubGlobal("window", {});
+ const events = [
+ createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),
+ createSessionWaitingEvent(),
+ ];
+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createBoundedStreamResponse(events));
+ const seenEvents: UnstampedMessageStreamEvent[] = [];
+
+ useEveAgent({
+ initialSession: { sessionId: "session_1", streamIndex: 0 },
+ resume: true,
+ onEvent(event) {
+ seenEvents.push(event);
+ },
+ });
+
+ await vi.waitFor(() => expect(seenEvents).toEqual(stampTestEvents(events)));
+ });
+
it("sends messages and notifies lifecycle callbacks from the shared store", async () => {
vi.stubGlobal("window", {});
const events = [
diff --git a/packages/eve/src/svelte/use-eve-agent.ts b/packages/eve/src/svelte/use-eve-agent.ts
index 21fd67d42..aab217282 100644
--- a/packages/eve/src/svelte/use-eve-agent.ts
+++ b/packages/eve/src/svelte/use-eve-agent.ts
@@ -55,6 +55,8 @@ export interface UseEveAgentReturn<TData> {
readonly error: Error | undefined;
/** Raw server events received during this session (authoritative stream). */
readonly events: readonly MessageStreamEvent[];
+ /** Replay the attached durable session and follow its in-flight turn, if any. */
+ readonly resume: () => Promise<void>;
/** Clear all state and start a new session. */
readonly reset: () => void;
/** Send a message with optional turn settings. */
@@ -125,6 +127,8 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>
* which fixes `TData` to {@link EveMessageData}.
*/
readonly reducer?: EveAgentReducer<TData>;
+ /** Replay the attached durable session after mount. Requires `initialSession` or `session`. */
+ readonly resume?: boolean;
/**
* Pre-built client session to bind to. When omitted, the binding creates its
* own session from `auth`, `headers`, and `host`.
@@ -188,6 +192,10 @@ class SvelteEveAgent<TData> implements UseEveAgentReturn<TData> {
this.#store.reset();
};
+ resume = (): Promise<void> => {
+ return this.#store.resume();
+ };
+
respond = <TOutput = unknown>(
inputResponses: Parameters<ClientSession["respond"]>[0],
options?: RespondTurnOptions<TOutput>,
@@ -223,6 +231,9 @@ export function useEveAgent<TData>(
export function useEveAgent<TData>(
options: UseEveAgentOptions<TData> = {},
): UseEveAgentReturn<TData> {
+ if (options.resume && options.initialSession === undefined && options.session === undefined) {
+ throw new Error("useEveAgent({ resume: true }) requires initialSession or session.");
+ }
const reducer = options.reducer ?? (defaultMessageReducer() as EveAgentReducer<TData>);
const store = new EveAgentStore<TData>({
auth: options.auth,
@@ -242,6 +253,7 @@ export function useEveAgent<TData>(
onSessionChange: options.onSessionChange,
prepareSend: options.prepareSend,
});
+ if ("window" in globalThis && options.resume) void store.resume();
return new SvelteEveAgent(store);
}
diff --git a/packages/eve/src/vue/use-eve-agent.test.ts b/packages/eve/src/vue/use-eve-agent.test.ts
index c18d6b4a3..299ad4e98 100644
--- a/packages/eve/src/vue/use-eve-agent.test.ts
+++ b/packages/eve/src/vue/use-eve-agent.test.ts
@@ -40,6 +40,12 @@ function createEagerStreamResponse(events: readonly UnstampedMessageStreamEvent[
);
}
+function createBoundedStreamResponse(events: readonly UnstampedMessageStreamEvent[]): Response {
+ const response = createEagerStreamResponse(events);
+ response.headers.set("x-eve-stream-tail-index", String(events.length - 1));
+ return response;
+}
+
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
@@ -334,6 +340,42 @@ describe("EveAgentStore (Vue composable backing store)", () => {
});
describe("useEveAgent (Vue composable wiring)", () => {
+ it("automatically replays an initial session when resume is enabled", async () => {
+ vi.stubGlobal("window", {});
+ const events = [
+ createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),
+ createMessageCompletedEvent({
+ message: "Hi there.",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn_1",
+ }),
+ createSessionWaitingEvent(),
+ ];
+ vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createBoundedStreamResponse(events));
+ const scope = effectScope();
+ const agent = scope.run(() =>
+ useEveAgent({
+ initialSession: { sessionId: "session_1", streamIndex: 0 },
+ resume: true,
+ }),
+ );
+ if (agent === undefined) throw new Error("effect scope did not run");
+
+ expect(agent.status.value).toBe("submitted");
+ await vi.waitFor(() => expect(agent.events.value).toHaveLength(events.length));
+ expect(agent.status.value).toBe("ready");
+ expect(agent.data.value).toEqual(
+ completedTurnData({
+ assistantMessage: "Hi there.",
+ turnId: "turn_1",
+ userMessage: "Hello",
+ }),
+ );
+
+ scope.stop();
+ });
+
it("projects streamed events into reactive refs in the browser", async () => {
vi.stubGlobal("window", {});
const events = [
diff --git a/packages/eve/src/vue/use-eve-agent.ts b/packages/eve/src/vue/use-eve-agent.ts
index 953e7c9cb..5f88d02d3 100644
--- a/packages/eve/src/vue/use-eve-agent.ts
+++ b/packages/eve/src/vue/use-eve-agent.ts
@@ -53,6 +53,8 @@ export interface UseEveAgentReturn<TData> {
readonly error: ComputedRef<Error | undefined>;
/** Raw server events from this session (authoritative stream). */
readonly events: ComputedRef<readonly MessageStreamEvent[]>;
+ /** Replay the attached durable session and follow its in-flight turn, if any. */
+ readonly resume: () => Promise<void>;
/** Clear all state and start a new session. */
readonly reset: () => void;
/** Send a message with optional turn settings. */
@@ -125,6 +127,8 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>
* @default defaultMessageReducer()
*/
readonly reducer?: EveAgentReducer<TData>;
+ /** Replay the attached durable session after mount. Requires `initialSession` or `session`. */
+ readonly resume?: boolean;
/**
* Externally owned {@link ClientSession} to bind instead of creating one.
*
@@ -148,13 +152,16 @@ export function useEveAgent<TData>(
* Without a `reducer`, events project into `EveMessageData` via
* `defaultMessageReducer()`; pass `reducer` to project into a custom `TData`.
* Returns reactive refs (`data`, `error`, `events`, `session`, `status`) plus
- * `send`, `respond`, `cancel`, and `reset`. Configuration is read once on store creation;
+ * `send`, `respond`, `resume`, `cancel`, and `reset`. Configuration is read once on store creation;
* remount to change it. On scope dispose, the in-flight request is detached and
* the store unsubscribed.
*/
export function useEveAgent<TData>(
options: UseEveAgentOptions<TData> = {},
): UseEveAgentReturn<TData> {
+ if (options.resume && options.initialSession === undefined && options.session === undefined) {
+ throw new Error("useEveAgent({ resume: true }) requires initialSession or session.");
+ }
const reducer = options.reducer ?? (defaultMessageReducer() as EveAgentReducer<TData>);
const store = new EveAgentStore<TData>({
@@ -182,6 +189,7 @@ export function useEveAgent<TData>(
const unsubscribe = store.subscribe(() => {
snapshot.value = store.snapshot;
});
+ if (options.resume) void store.resume();
onScopeDispose(() => {
unsubscribe();
@@ -199,6 +207,7 @@ export function useEveAgent<TData>(
inputResponses: Parameters<ClientSession["respond"]>[0],
options?: RespondTurnOptions<TOutput>,
) => store.send({ ...options, inputResponses }),
+ resume: () => store.resume(),
send: <TOutput = unknown>(message: string | UserContent, options?: SendTurnOptions<TOutput>) =>
store.send({ ...options, message }),
session: computed(() => snapshot.value.session),