Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Prewarm web chat sessions while users type (#4775)

Casey Gowrie8f336b848643
diff --git a/.changeset/prewarm-web-chat-on-input.md b/.changeset/prewarm-web-chat-on-input.md
new file mode 100644
index 000000000..ac4b9b5b1
--- /dev/null
+++ b/.changeset/prewarm-web-chat-on-input.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Prewarm new Web Chat sessions when the user starts typing, so durable session startup overlaps with composing the first message.
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 edfbe879c..6bec069de 100644
--- a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx
+++ b/apps/docs/registry/channel/web/app/_components/agent-chat.tsx
@@ -3,7 +3,7 @@
import type { UserContent } from "ai";
import { useEveAgent } from "eve/react";
import { AlertCircleIcon, BrainIcon, PlusIcon, SquareIcon } from "lucide-react";
-import { useState } from "react";
+import { useRef, useState } from "react";
import {
Conversation,
ConversationContent,
@@ -37,8 +37,21 @@ export function AgentChat({
}) {
const [cancellationError, setCancellationError] = useState<string>();
const [hasInputText, setHasInputText] = useState(false);
+ const hasSubmittedMessage = useRef(false);
+ const replaceSessionRoute = (nextSessionId: string) => {
+ if (sessionId !== undefined) return;
+ // Framework routers (Next.js, TanStack Router) patch window.history; navigating
+ // through them would remount this route and detach the active stream.
+ History.prototype.replaceState.call(
+ window.history,
+ window.history.state,
+ "",
+ `/s/${encodeURIComponent(nextSessionId)}`,
+ );
+ };
const agent = useEveAgent({
agent: WEB_CHAT_AGENT,
+ prewarm: hasInputText,
initialSession:
sessionId === undefined
? undefined
@@ -48,15 +61,8 @@ export function AgentChat({
},
resume: sessionId !== undefined,
onSessionChange(session) {
- if (sessionId === undefined && session !== undefined) {
- // Framework routers (Next.js, TanStack Router) patch window.history; navigating
- // through them would remount this route and detach the active stream.
- History.prototype.replaceState.call(
- window.history,
- window.history.state,
- "",
- `/s/${encodeURIComponent(session.sessionId)}`,
- );
+ if (hasSubmittedMessage.current && session !== undefined) {
+ replaceSessionRoute(session.sessionId);
}
},
});
@@ -98,6 +104,8 @@ export function AgentChat({
setHasInputText(false);
setCancellationError(undefined);
+ hasSubmittedMessage.current = true;
+ if (agent.session !== undefined) replaceSessionRoute(agent.session.sessionId);
const options = isBusy ? { turnPolicy: "steer" as const } : undefined;
if (message.files.length === 0) {
diff --git a/apps/frameworks/next-multi-agent/app/page.tsx b/apps/frameworks/next-multi-agent/app/page.tsx
index 7bc0c3985..17be14d12 100644
--- a/apps/frameworks/next-multi-agent/app/page.tsx
+++ b/apps/frameworks/next-multi-agent/app/page.tsx
@@ -48,8 +48,12 @@ function AgentPanel({
readonly name: AgentName;
};
}) {
- const eve = useEveAgent({ agent: agent.name });
const [message, setMessage] = useState(agent.initialPrompt);
+ const [hasEditedMessage, setHasEditedMessage] = useState(false);
+ const eve = useEveAgent({
+ agent: agent.name,
+ prewarm: hasEditedMessage && message.trim().length > 0,
+ });
const isBusy = eve.status === "submitted" || eve.status === "streaming";
const submit: ComponentProps<"form">["onSubmit"] = async (event) => {
@@ -88,7 +92,10 @@ function AgentPanel({
<form onSubmit={submit}>
<textarea
aria-label={`Message ${agent.name} agent`}
- onChange={(event) => setMessage(event.currentTarget.value)}
+ onChange={(event) => {
+ setHasEditedMessage(true);
+ setMessage(event.currentTarget.value);
+ }}
value={message}
/>
<button disabled={isBusy || message.trim().length === 0} type="submit">
diff --git a/apps/frameworks/next/app/_chat/App.tsx b/apps/frameworks/next/app/_chat/App.tsx
index 2d555df29..38a60680d 100644
--- a/apps/frameworks/next/app/_chat/App.tsx
+++ b/apps/frameworks/next/app/_chat/App.tsx
@@ -89,7 +89,7 @@ export function App() {
const conversationStageRef = useRef<HTMLElement | null>(null);
const reducer = useMemo(() => traceReducer(), []);
const agent = useEveAgent({
- prewarm: composerInput.length > 0,
+ prewarm: composerInput.trim().length > 0,
reducer,
});
diff --git a/apps/frameworks/nuxt/app/components/EveAgentConsole.vue b/apps/frameworks/nuxt/app/components/EveAgentConsole.vue
index a183f2a22..612b16fff 100644
--- a/apps/frameworks/nuxt/app/components/EveAgentConsole.vue
+++ b/apps/frameworks/nuxt/app/components/EveAgentConsole.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import type { EveDynamicToolPart, EveMessagePart } from "eve/vue";
-const { cancel, data, status, error, respond, send } = useEveAgent();
+const { cancel, data, status, error, prewarm, respond, send } = useEveAgent();
type EveFilePart = Extract<EveMessagePart, { type: "file" }>;
@@ -37,6 +37,13 @@ watch(
const messageText = ref("");
+watch(
+ () => messageText.value.trim().length > 0,
+ (shouldPrewarm) => {
+ if (shouldPrewarm) void prewarm().catch(() => {});
+ },
+);
+
function submitMessage() {
const text = messageText.value.trim();
if (!text || isInputDisabled.value) return;
diff --git a/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte b/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte
index 5478ae131..8a8af52be 100644
--- a/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte
+++ b/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte
@@ -44,6 +44,17 @@
});
let messageText = $state("");
+ let prewarmRequested = false;
+
+ $effect(() => {
+ if (messageText.trim().length === 0) {
+ prewarmRequested = false;
+ return;
+ }
+ if (prewarmRequested) return;
+ prewarmRequested = true;
+ void agent.prewarm().catch(() => {});
+ });
function submitMessage() {
const text = messageText.trim();
diff --git a/apps/frameworks/tanstack/src/components/EveAgentConsole.tsx b/apps/frameworks/tanstack/src/components/EveAgentConsole.tsx
index b42d200c1..5a0556407 100644
--- a/apps/frameworks/tanstack/src/components/EveAgentConsole.tsx
+++ b/apps/frameworks/tanstack/src/components/EveAgentConsole.tsx
@@ -61,8 +61,8 @@ function PartView({
}
export function EveAgentConsole() {
- const agent = useEveAgent();
const [draft, setDraft] = useState("");
+ const agent = useEveAgent({ prewarm: draft.trim().length > 0 });
const isBusy = agent.status === "submitted" || agent.status === "streaming";
const isInputDisabled = isBusy || agent.status === "resuming";
diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.ts
index adb546a8d..b60aacfc9 100644
--- a/packages/eve/src/setup/scaffold/create/web-template.ts
+++ b/packages/eve/src/setup/scaffold/create/web-template.ts
@@ -3,7 +3,7 @@
export const WEB_APP_TEMPLATE_FILES = {
"app/_components/agent-chat.tsx":
- '"use client";\n\nimport type { UserContent } from "ai";\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon, BrainIcon, PlusIcon, SquareIcon } from "lucide-react";\nimport { useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n ConversationTopFade,\n} from "@/components/ai-elements/conversation";\nimport { Message, MessageContent } from "@/components/ai-elements/message";\nimport {\n PromptInput,\n PromptInputButton,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n usePromptInputAttachments,\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";\nimport { WEB_CHAT_AGENT } from "@/app/eve-agent";\n\nconst DEFAULT_AGENT_NAME = "__EVE_INIT_APP_NAME__";\nconst AGENT_NAME = WEB_CHAT_AGENT ?? DEFAULT_AGENT_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 [hasInputText, setHasInputText] = useState(false);\n const agent = useEveAgent({\n agent: WEB_CHAT_AGENT,\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 // Framework routers (Next.js, TanStack Router) patch window.history; navigating\n // through them would remount this route and detach the active stream.\n History.prototype.replaceState.call(\n window.history,\n window.history.state,\n "",\n `/s/${encodeURIComponent(session.sessionId)}`,\n );\n }\n },\n });\n\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isResuming = agent.status === "resuming";\n const isEmpty = agent.data.messages.length === 0;\n const lastMessage = agent.data.messages.at(-1);\n const isPendingAssistantShell =\n lastMessage?.role === "assistant" &&\n lastMessage.parts.every((part) => part.type === "step-start");\n const showPendingThinking =\n isBusy &&\n (agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);\n const turnFailure = isBusy || isResuming ? undefined : getLatestTurnFailure(agent.events);\n const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;\n const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;\n const showConversationLayout = isResuming || hasConversationContent;\n const activeSessionId = sessionId ?? agent.session?.sessionId;\n // Answers are accepted while work runs; the server\'s settlement closes each request.\n const canRespond = (requestId: string) =>\n !isResuming && agent.data.inputs[requestId]?.status === "open";\n // A tool call can ask several questions at once, and its message part holds only the latest.\n const questionsFor = (callId: string) =>\n Object.values(agent.data.inputs).filter(\n (input) => input.request.kind === "question" && input.request.action.callId === callId,\n );\n\n const requestCancellation = () => {\n setCancellationError(undefined);\n void agent.cancel().catch((error: unknown) => {\n setCancellationError(toErrorMessage(error));\n });\n };\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if ((text.length === 0 && message.files.length === 0) || isResuming) return;\n\n setHasInputText(false);\n setCancellationError(undefined);\n const options = isBusy ? { turnPolicy: "steer" as const } : undefined;\n\n if (message.files.length === 0) {\n await agent.send(text, options);\n return;\n }\n\n const parts: UserContent = [];\n if (text.length > 0) {\n parts.push({ text, type: "text" });\n }\n for (const file of message.files) {\n parts.push({\n data: file.url,\n filename: file.filename,\n mediaType: file.mediaType,\n type: "file",\n });\n }\n\n await agent.send(parts, options);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea\n disabled={isResuming}\n onChange={(event) => setHasInputText(event.currentTarget.value.trim().length > 0)}\n placeholder="Send a message…"\n />\n <ComposerAction\n hasInputText={hasInputText}\n isBusy={isBusy}\n isResuming={isResuming}\n onCancel={requestCancellation}\n />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {showConversationLayout ? (\n <ChatHeader canStartNewChat={activeSessionId !== undefined} />\n ) : null}\n\n {showConversationLayout ? (\n <Conversation\n className="min-h-0 flex-1"\n initial={sessionId === undefined ? undefined : false}\n resize={activeSessionId === undefined ? "smooth" : "instant"}\n scrollRestorationKey={\n isEmpty || activeSessionId === undefined\n ? undefined\n : `eve:web-chat-scroll:${activeSessionId}`\n }\n >\n <ConversationTopFade className="top-14" />\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 pt-20 pb-36 sm:px-6">\n {agent.data.messages.map((message, index) =>\n showPendingThinking &&\n isPendingAssistantShell &&\n message.id === lastMessage.id ? null : (\n <AgentMessage\n canRespond={canRespond}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n questionsFor={questionsFor}\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 ComposerAction({\n hasInputText,\n isBusy,\n isResuming,\n onCancel,\n}: {\n readonly hasInputText: boolean;\n readonly isBusy: boolean;\n readonly isResuming: boolean;\n readonly onCancel: () => void;\n}) {\n const attachments = usePromptInputAttachments();\n const canSubmit = hasInputText || attachments.files.length > 0;\n\n if (!isBusy || canSubmit) {\n return <PromptInputSubmit disabled={isResuming} />;\n }\n\n return (\n <PromptInputButton\n aria-label="Stop"\n className="absolute right-2.5 bottom-2.5"\n onClick={onCancel}\n variant="outline"\n >\n <SquareIcon className="size-3 fill-current" />\n </PromptInputButton>\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-3 right-6 pr-4"\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 font-normal text-sm sm:inline">New chat</span>\n </Button>\n ) : null}\n </div>\n </header>\n );\n}\n\nfunction PendingThinking() {\n return (\n <Message aria-live="polite" from="assistant">\n <MessageContent>\n <div className="mb-4 flex w-full items-center gap-2 text-muted-foreground text-sm">\n <BrainIcon className="size-4" />\n <Shimmer duration={1}>Thinking</Shimmer>\n </div>\n </MessageContent>\n </Message>\n );\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : "Unable to cancel the response.";\n}\n\nfunction getLatestTurnFailure(\n events: ReturnType<typeof useEveAgent>["events"],\n): string | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n\n if (event.type === "turn.failed") {\n return event.data.code === "MODEL_CALL_FAILED"\n ? "The model is temporarily unavailable. Please try again."\n : event.data.message;\n }\n\n if (event.type === "turn.completed" || event.type === "turn.cancelled") {\n return undefined;\n }\n\n if (event.type === "message.received") {\n return undefined;\n }\n }\n\n return undefined;\n}\n',
+ '"use client";\n\nimport type { UserContent } from "ai";\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon, BrainIcon, PlusIcon, SquareIcon } from "lucide-react";\nimport { useRef, useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n ConversationTopFade,\n} from "@/components/ai-elements/conversation";\nimport { Message, MessageContent } from "@/components/ai-elements/message";\nimport {\n PromptInput,\n PromptInputButton,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n usePromptInputAttachments,\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";\nimport { WEB_CHAT_AGENT } from "@/app/eve-agent";\n\nconst DEFAULT_AGENT_NAME = "__EVE_INIT_APP_NAME__";\nconst AGENT_NAME = WEB_CHAT_AGENT ?? DEFAULT_AGENT_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 [hasInputText, setHasInputText] = useState(false);\n const hasSubmittedMessage = useRef(false);\n const replaceSessionRoute = (nextSessionId: string) => {\n if (sessionId !== undefined) return;\n // Framework routers (Next.js, TanStack Router) patch window.history; navigating\n // through them would remount this route and detach the active stream.\n History.prototype.replaceState.call(\n window.history,\n window.history.state,\n "",\n `/s/${encodeURIComponent(nextSessionId)}`,\n );\n };\n const agent = useEveAgent({\n agent: WEB_CHAT_AGENT,\n prewarm: hasInputText,\n initialSession:\n sessionId === undefined\n ? undefined\n : {\n sessionId,\n streamIndex: 0,\n },\n resume: sessionId !== undefined,\n onSessionChange(session) {\n if (hasSubmittedMessage.current && session !== undefined) {\n replaceSessionRoute(session.sessionId);\n }\n },\n });\n\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isResuming = agent.status === "resuming";\n const isEmpty = agent.data.messages.length === 0;\n const lastMessage = agent.data.messages.at(-1);\n const isPendingAssistantShell =\n lastMessage?.role === "assistant" &&\n lastMessage.parts.every((part) => part.type === "step-start");\n const showPendingThinking =\n isBusy &&\n (agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);\n const turnFailure = isBusy || isResuming ? undefined : getLatestTurnFailure(agent.events);\n const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;\n const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;\n const showConversationLayout = isResuming || hasConversationContent;\n const activeSessionId = sessionId ?? agent.session?.sessionId;\n // Answers are accepted while work runs; the server\'s settlement closes each request.\n const canRespond = (requestId: string) =>\n !isResuming && agent.data.inputs[requestId]?.status === "open";\n // A tool call can ask several questions at once, and its message part holds only the latest.\n const questionsFor = (callId: string) =>\n Object.values(agent.data.inputs).filter(\n (input) => input.request.kind === "question" && input.request.action.callId === callId,\n );\n\n const requestCancellation = () => {\n setCancellationError(undefined);\n void agent.cancel().catch((error: unknown) => {\n setCancellationError(toErrorMessage(error));\n });\n };\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if ((text.length === 0 && message.files.length === 0) || isResuming) return;\n\n setHasInputText(false);\n setCancellationError(undefined);\n hasSubmittedMessage.current = true;\n if (agent.session !== undefined) replaceSessionRoute(agent.session.sessionId);\n const options = isBusy ? { turnPolicy: "steer" as const } : undefined;\n\n if (message.files.length === 0) {\n await agent.send(text, options);\n return;\n }\n\n const parts: UserContent = [];\n if (text.length > 0) {\n parts.push({ text, type: "text" });\n }\n for (const file of message.files) {\n parts.push({\n data: file.url,\n filename: file.filename,\n mediaType: file.mediaType,\n type: "file",\n });\n }\n\n await agent.send(parts, options);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea\n disabled={isResuming}\n onChange={(event) => setHasInputText(event.currentTarget.value.trim().length > 0)}\n placeholder="Send a message…"\n />\n <ComposerAction\n hasInputText={hasInputText}\n isBusy={isBusy}\n isResuming={isResuming}\n onCancel={requestCancellation}\n />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {showConversationLayout ? (\n <ChatHeader canStartNewChat={activeSessionId !== undefined} />\n ) : null}\n\n {showConversationLayout ? (\n <Conversation\n className="min-h-0 flex-1"\n initial={sessionId === undefined ? undefined : false}\n resize={activeSessionId === undefined ? "smooth" : "instant"}\n scrollRestorationKey={\n isEmpty || activeSessionId === undefined\n ? undefined\n : `eve:web-chat-scroll:${activeSessionId}`\n }\n >\n <ConversationTopFade className="top-14" />\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 pt-20 pb-36 sm:px-6">\n {agent.data.messages.map((message, index) =>\n showPendingThinking &&\n isPendingAssistantShell &&\n message.id === lastMessage.id ? null : (\n <AgentMessage\n canRespond={canRespond}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n questionsFor={questionsFor}\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 ComposerAction({\n hasInputText,\n isBusy,\n isResuming,\n onCancel,\n}: {\n readonly hasInputText: boolean;\n readonly isBusy: boolean;\n readonly isResuming: boolean;\n readonly onCancel: () => void;\n}) {\n const attachments = usePromptInputAttachments();\n const canSubmit = hasInputText || attachments.files.length > 0;\n\n if (!isBusy || canSubmit) {\n return <PromptInputSubmit disabled={isResuming} />;\n }\n\n return (\n <PromptInputButton\n aria-label="Stop"\n className="absolute right-2.5 bottom-2.5"\n onClick={onCancel}\n variant="outline"\n >\n <SquareIcon className="size-3 fill-current" />\n </PromptInputButton>\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-3 right-6 pr-4"\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 font-normal text-sm 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 ConversationInput,\n EveAuthorizationPart,\n EveDynamicToolPart,\n EveMessage,\n EveMessageInputRequest,\n EveMessagePart,\n} from "eve/react";\nimport type { FormEvent } from "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 { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";\nimport {\n BashToolContent,\n Tool,\n ToolContent,\n ToolHeader,\n ToolInput,\n ToolOutput,\n} from "@/components/ai-elements/tool";\nimport { Button } from "@/components/ui/button";\nimport {\n Questionnaire,\n QuestionnaireActions,\n QuestionnaireChoice,\n QuestionnaireChoiceDescription,\n QuestionnaireChoices,\n QuestionnaireError,\n QuestionnaireInput,\n QuestionnaireItem,\n QuestionnaireSubmit,\n QuestionnaireTitle,\n} from "@/components/ui/questionnaire";\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 questionsFor,\n}: {\n readonly canRespond: (requestId: string) => boolean;\n readonly isStreaming: boolean;\n readonly message: EveMessage;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly questionsFor: (callId: string) => readonly ConversationInput[];\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 questionsFor={questionsFor}\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 questionsFor,\n showCaret,\n}: {\n readonly canRespond: (requestId: string) => boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveMessagePart;\n readonly questionsFor: (callId: string) => readonly ConversationInput[];\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 questions = questionsFor(part.toolCallId);\n if (questions.length > 0) {\n return (\n <div className="space-y-4">\n {questions.map(({ request, response }) => (\n <QuestionRequest\n canRespond={canRespond(request.requestId)}\n inputRequest={request}\n inputResponse={response}\n key={request.requestId}\n onInputResponses={onInputResponses}\n />\n ))}\n </div>\n );\n }\n\n return (\n <>\n <Tool>\n <ToolHeader\n state={part.state}\n title={part.toolMetadata?.eve?.label ?? part.toolName}\n toolName={part.toolName}\n type="dynamic-tool"\n />\n <ToolContent>\n {part.toolName === "bash" ? (\n <BashToolContent\n errorText={part.errorText}\n input={part.input}\n output={part.output}\n />\n ) : (\n <>\n <ToolInput input={part.input} />\n <ToolOutput errorText={part.errorText} output={part.output} />\n </>\n )}\n </ToolContent>\n </Tool>\n {/* Kept outside the collapsed card so a pending approval is always visible. */}\n <InputRequestActions\n canRespond={canRespond}\n part={part}\n onInputResponses={onInputResponses}\n />\n </>\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 options = inputRequest.options ?? [];\n const acceptsFreeform = inputRequest.allowFreeform === true || options.length === 0;\n const disabled = !canRespond || inputResponse !== undefined;\n\n const submitResponse = (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const answer = new FormData(event.currentTarget).get(inputRequest.requestId);\n if (typeof answer !== "string") {\n return;\n }\n\n const option = options.find(({ id }) => id === answer);\n void onInputResponses([\n option === undefined\n ? { requestId: inputRequest.requestId, text: answer.trim() }\n : { optionId: option.id, requestId: inputRequest.requestId },\n ]);\n };\n\n return (\n <Questionnaire\n className="gap-4 rounded-xl border bg-card p-4"\n // Validation reads disabled answers as missing, so locking a submitted form in place would\n // flag it invalid. Remounting restores the answer from the response instead.\n key={disabled ? "locked" : "open"}\n onSubmit={submitResponse}\n shortcuts="numbers"\n >\n <QuestionnaireItem name={inputRequest.requestId} required>\n <QuestionnaireTitle className="text-sm font-medium">\n {inputRequest.prompt}\n </QuestionnaireTitle>\n <QuestionnaireChoices>\n {options.map((option) => (\n <QuestionnaireChoice\n className={cn(inputResponse?.optionId === option.id && "data-disabled:opacity-100")}\n defaultChecked={inputResponse?.optionId === option.id}\n disabled={disabled}\n key={option.id}\n value={option.id}\n >\n {option.label}\n {option.description ? (\n <QuestionnaireChoiceDescription>\n {option.description}\n </QuestionnaireChoiceDescription>\n ) : null}\n </QuestionnaireChoice>\n ))}\n {acceptsFreeform ? (\n <QuestionnaireInput\n aria-label="Answer"\n className={cn(inputResponse?.text !== undefined && "disabled:opacity-100")}\n defaultValue={inputResponse?.text}\n disabled={disabled}\n placeholder="Type your answer…"\n />\n ) : null}\n </QuestionnaireChoices>\n <QuestionnaireError />\n </QuestionnaireItem>\n {disabled ? null : (\n <QuestionnaireActions>\n <QuestionnaireSubmit size="sm">Answer</QuestionnaireSubmit>\n </QuestionnaireActions>\n )}\n </Questionnaire>\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: (requestId: string) => 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 // An approval can settle before its batch resolves, without an input response.\n const settledApproval =\n part.approval?.approved === undefined\n ? undefined\n : part.approval.approved\n ? "Approved"\n : "Denied";\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 || settledApproval ? (\n <p className="font-medium text-sm">\n Responded:{" "}\n {selectedOption?.label ??\n inputResponse?.text ??\n inputResponse?.optionId ??\n settledApproval}\n </p>\n ) : (\n <div className="flex flex-wrap gap-2">\n {inputRequest.options?.map((option) => (\n <Button\n disabled={!canRespond(inputRequest.requestId)}\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 part.attemptId === undefined\n ? `authorization:${part.turnId}:${part.stepIndex}:${part.name}`\n : `authorization:${part.attemptId}`;\n case "dynamic-tool":\n return part.toolCallId;\n case "reasoning":\n case "text":\n return `${part.type}:${part.id ?? index}`;\n default:\n return `${part.type}:${index}`;\n }\n}\n',
"app/apple-icon.tsx":
diff --git a/packages/eve/src/setup/scaffold/index.integration.test.ts b/packages/eve/src/setup/scaffold/index.integration.test.ts
index cec965e59..e7db51a5f 100644
--- a/packages/eve/src/setup/scaffold/index.integration.test.ts
+++ b/packages/eve/src/setup/scaffold/index.integration.test.ts
@@ -272,6 +272,11 @@ describe("ensureChannel", () => {
expect(agentChatSource).toMatch(/<PromptInputTextarea\s+disabled=\{isResuming\}/);
expect(agentChatSource).toContain('turnPolicy: "steer"');
expect(agentChatSource).toContain('const isResuming = agent.status === "resuming"');
+ expect(agentChatSource).toContain("prewarm: hasInputText");
+ expect(agentChatSource).toContain("hasSubmittedMessage.current && session !== undefined");
+ expect(agentChatSource).toContain(
+ "if (agent.session !== undefined) replaceSessionRoute(agent.session.sessionId)",
+ );
expect(agentChatSource).toContain(
'!isResuming && agent.data.inputs[requestId]?.status === "open"',
);