Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add TanStack Start as a Web Chat framework (#4395)

roboeve[bot]b6648386d346
diff --git a/.changeset/web-chat-tanstack-start.md b/.changeset/web-chat-tanstack-start.md
new file mode 100644
index 000000000..b6543a19b
--- /dev/null
+++ b/.changeset/web-chat-tanstack-start.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve add channel/web` now asks which framework Web Chat uses and can install a TanStack Start app under `apps/web/`, hosted as a separate Vercel service or inside the app through `eve/tanstack`; non-interactive installs keep Next.js unless you pass `--answer 'web-framework="tanstack"'`. Web Chat setup also checks for authored configuration before writing, removes the `vercel.ts` and scripts it wrote when you switch hosting modes, and renders text in the loaded Geist fonts.
diff --git a/apps/docs/registry.json b/apps/docs/registry.json
index fde7719c7..61e3a9c32 100644
--- a/apps/docs/registry.json
+++ b/apps/docs/registry.json
@@ -1917,6 +1917,262 @@
}
]
},
+ {
+ "name": "channel/web-tanstack",
+ "type": "registry:item",
+ "title": "Web Chat (TanStack Start)",
+ "description": "The TanStack Start variant of channel/web. Install it with eve add channel/web and choose TanStack Start.",
+ "meta": {
+ "eve": {
+ "setup": {
+ "command": "eve",
+ "package": "eve",
+ "bin": "eve",
+ "args": ["integration", "setup", "web"]
+ },
+ "docs": "/docs/guides/frontend/tanstack",
+ "implementation": "native",
+ "hidden": true
+ }
+ },
+ "dependencies": [
+ "@fontsource-variable/[email protected]",
+ "@fontsource-variable/[email protected]",
+ "@radix-ui/[email protected]",
+ "@shadcn/[email protected]",
+ "@shikijs/[email protected]",
+ "@shikijs/[email protected]",
+ "@shikijs/[email protected]",
+ "@streamdown/[email protected]",
+ "@streamdown/[email protected]",
+ "@streamdown/[email protected]",
+ "@streamdown/[email protected]",
+ "@tailwindcss/[email protected]",
+ "@tanstack/[email protected]",
+ "@tanstack/[email protected]",
+ "@vitejs/[email protected]",
+ ],
+ "devDependencies": [
+ "@types/node@26",
+ "@types/[email protected]",
+ "@types/[email protected]",
+ ],
+ "files": [
+ {
+ "path": "registry/channel/web/app/_components/agent-chat.tsx",
+ "type": "registry:file",
+ "target": "apps/web/app/_components/agent-chat.tsx"
+ },
+ {
+ "path": "registry/channel/web/app/_components/agent-message.tsx",
+ "type": "registry:file",
+ "target": "apps/web/app/_components/agent-message.tsx"
+ },
+ {
+ "path": "registry/channel/web-tanstack/app/fonts.css",
+ "type": "registry:file",
+ "target": "apps/web/app/fonts.css"
+ },
+ {
+ "path": "registry/channel/web/app/globals.css",
+ "type": "registry:file",
+ "target": "apps/web/app/globals.css"
+ },
+ {
+ "path": "registry/channel/web-tanstack/app/router.tsx",
+ "type": "registry:file",
+ "target": "apps/web/app/router.tsx"
+ },
+ {
+ "path": "registry/channel/web-tanstack/app/routes/__root.tsx",
+ "type": "registry:file",
+ "target": "apps/web/app/routes/__root.tsx"
+ },
+ {
+ "path": "registry/channel/web-tanstack/app/routes/index.tsx",
+ "type": "registry:file",
+ "target": "apps/web/app/routes/index.tsx"
+ },
+ {
+ "path": "registry/channel/web-tanstack/app/routes/s.session-id.tsx",
+ "type": "registry:file",
+ "target": "apps/web/app/routes/s.$sessionId.tsx"
+ },
+ {
+ "path": "registry/channel/web-tanstack/app/routes/s.index.tsx",
+ "type": "registry:file",
+ "target": "apps/web/app/routes/s.index.tsx"
+ },
+ {
+ "path": "registry/channel/web-tanstack/app/start.ts",
+ "type": "registry:file",
+ "target": "apps/web/app/start.ts"
+ },
+ {
+ "path": "registry/channel/web-tanstack/components.json",
+ "type": "registry:file",
+ "target": "apps/web/components.json"
+ },
+ {
+ "path": "registry/channel/web/components/ai-elements/chain-of-thought.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ai-elements/chain-of-thought.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ai-elements/code-block.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ai-elements/code-block.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ai-elements/conversation.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ai-elements/conversation.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ai-elements/message.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ai-elements/message.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ai-elements/prompt-input.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ai-elements/prompt-input.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ai-elements/reasoning.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ai-elements/reasoning.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ai-elements/shimmer.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ai-elements/shimmer.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ai-elements/tool.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ai-elements/tool.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/badge.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/badge.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/button-group.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/button-group.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/button.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/button.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/collapsible.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/collapsible.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/command.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/command.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/dialog.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/dialog.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/dropdown-menu.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/dropdown-menu.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/hover-card.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/hover-card.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/input-group.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/input-group.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/input.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/input.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/questionnaire.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/questionnaire.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/select.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/select.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/separator.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/separator.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/spinner.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/spinner.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/textarea.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/textarea.tsx"
+ },
+ {
+ "path": "registry/channel/web/components/ui/tooltip.tsx",
+ "type": "registry:file",
+ "target": "apps/web/components/ui/tooltip.tsx"
+ },
+ {
+ "path": "registry/channel/web/lib/utils.ts",
+ "type": "registry:file",
+ "target": "apps/web/lib/utils.ts"
+ },
+ {
+ "path": "registry/channel/web/app/icon.svg",
+ "type": "registry:file",
+ "target": "apps/web/public/icon.svg"
+ },
+ {
+ "path": "registry/channel/web-tanstack/tsconfig.json",
+ "type": "registry:file",
+ "target": "apps/web/tsconfig.json"
+ },
+ {
+ "path": "registry/channel/web-tanstack/vite.config.ts",
+ "type": "registry:file",
+ "target": "apps/web/vite.config.ts"
+ }
+ ]
+ },
{
"name": "channel/slack",
"type": "registry:item",
diff --git a/apps/docs/registry.staged-requirements.json b/apps/docs/registry.staged-requirements.json
new file mode 100644
index 000000000..6ad5cc7d5
--- /dev/null
+++ b/apps/docs/registry.staged-requirements.json
@@ -0,0 +1,3 @@
+{
+ "items": ["channel/web-tanstack"]
+}
diff --git a/apps/docs/registry/channel/web-tanstack/app/fonts.css b/apps/docs/registry/channel/web-tanstack/app/fonts.css
new file mode 100644
index 000000000..3c69d3ef2
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/app/fonts.css
@@ -0,0 +1,7 @@
+@import "@fontsource-variable/geist";
+@import "@fontsource-variable/geist-mono";
+
+:root {
+ --font-sans: "Geist Variable", ui-sans-serif, system-ui, sans-serif;
+ --font-mono: "Geist Mono Variable", ui-monospace, monospace;
+}
diff --git a/apps/docs/registry/channel/web-tanstack/app/router.tsx b/apps/docs/registry/channel/web-tanstack/app/router.tsx
new file mode 100644
index 000000000..afcf556c4
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/app/router.tsx
@@ -0,0 +1,24 @@
+import { createRouter } from "@tanstack/react-router";
+import { routeTree } from "./routeTree.gen";
+
+export function getRouter() {
+ return createRouter({
+ routeTree,
+ scrollRestoration: true,
+ defaultNotFoundComponent: NotFound,
+ });
+}
+
+function NotFound() {
+ return (
+ <main className="flex min-h-dvh items-center justify-center text-muted-foreground text-sm">
+ Page not found.
+ </main>
+ );
+}
+
+declare module "@tanstack/react-router" {
+ interface Register {
+ router: ReturnType<typeof getRouter>;
+ }
+}
diff --git a/apps/docs/registry/channel/web-tanstack/app/routes/__root.tsx b/apps/docs/registry/channel/web-tanstack/app/routes/__root.tsx
new file mode 100644
index 000000000..3f5df2705
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/app/routes/__root.tsx
@@ -0,0 +1,46 @@
+import { createRootRoute, HeadContent, Outlet, Scripts } from "@tanstack/react-router";
+import type { ReactNode } from "react";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import fontsCss from "../fonts.css?url";
+import globalsCss from "../globals.css?url";
+
+export const Route = createRootRoute({
+ head: () => ({
+ meta: [
+ { charSet: "utf-8" },
+ { name: "viewport", content: "width=device-width, initial-scale=1" },
+ { title: "eve TanStack Start Starter" },
+ { name: "description", content: "A TanStack Start starter for eve agents with AI Elements." },
+ ],
+ links: [
+ { rel: "stylesheet", href: globalsCss },
+ { rel: "stylesheet", href: fontsCss },
+ { rel: "icon", href: "/icon.svg", type: "image/svg+xml" },
+ ],
+ }),
+ component: RootComponent,
+});
+
+function RootComponent() {
+ return (
+ <RootDocument>
+ <TooltipProvider>
+ <Outlet />
+ </TooltipProvider>
+ </RootDocument>
+ );
+}
+
+function RootDocument({ children }: { readonly children: ReactNode }) {
+ return (
+ <html lang="en">
+ <head>
+ <HeadContent />
+ </head>
+ <body>
+ {children}
+ <Scripts />
+ </body>
+ </html>
+ );
+}
diff --git a/apps/docs/registry/channel/web-tanstack/app/routes/index.tsx b/apps/docs/registry/channel/web-tanstack/app/routes/index.tsx
new file mode 100644
index 000000000..f245d00e8
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/app/routes/index.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { AgentChat } from "@/app/_components/agent-chat";
+
+export const Route = createFileRoute("/")({
+ component: () => <AgentChat />,
+});
diff --git a/apps/docs/registry/channel/web-tanstack/app/routes/s.index.tsx b/apps/docs/registry/channel/web-tanstack/app/routes/s.index.tsx
new file mode 100644
index 000000000..7735bb9ac
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/app/routes/s.index.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { AgentChat } from "@/app/_components/agent-chat";
+
+export const Route = createFileRoute("/s/")({
+ component: () => <AgentChat sessionless />,
+});
diff --git a/apps/docs/registry/channel/web-tanstack/app/routes/s.session-id.tsx b/apps/docs/registry/channel/web-tanstack/app/routes/s.session-id.tsx
new file mode 100644
index 000000000..bea06447e
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/app/routes/s.session-id.tsx
@@ -0,0 +1,11 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { AgentChat } from "@/app/_components/agent-chat";
+
+export const Route = createFileRoute("/s/$sessionId")({
+ component: SessionPage,
+});
+
+function SessionPage() {
+ const { sessionId } = Route.useParams();
+ return <AgentChat sessionId={sessionId} />;
+}
diff --git a/apps/docs/registry/channel/web-tanstack/app/start.ts b/apps/docs/registry/channel/web-tanstack/app/start.ts
new file mode 100644
index 000000000..131d3f057
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/app/start.ts
@@ -0,0 +1,19 @@
+import { createMiddleware, createStart } from "@tanstack/react-start";
+
+// `vercel dev` routes /eve/* only through its router host; send direct hits there.
+const vercelDevRouter = createMiddleware({ type: "request" }).server(({ request, next }) => {
+ const routerHost = process.env.VERCEL_URL;
+ if (
+ process.env.__VERCEL_DEV_RUNNING === "1" &&
+ routerHost &&
+ request.headers.get("x-forwarded-host") !== routerHost
+ ) {
+ const target = new URL(request.url);
+ target.protocol = "http:";
+ target.host = routerHost;
+ return Response.redirect(target, 307);
+ }
+ return next();
+});
+
+export const startInstance = createStart(() => ({ requestMiddleware: [vercelDevRouter] }));
diff --git a/apps/docs/registry/channel/web-tanstack/components.json b/apps/docs/registry/channel/web-tanstack/components.json
new file mode 100644
index 000000000..bb84bc46c
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/components.json
@@ -0,0 +1,22 @@
+{
+ "$schema": "https://ui.shadcn.com/schema.json",
+ "style": "new-york",
+ "rsc": false,
+ "tsx": true,
+ "tailwind": {
+ "config": "",
+ "css": "app/globals.css",
+ "baseColor": "neutral",
+ "cssVariables": true,
+ "prefix": ""
+ },
+ "iconLibrary": "lucide",
+ "aliases": {
+ "components": "@/components",
+ "utils": "@/lib/utils",
+ "ui": "@/components/ui",
+ "lib": "@/lib",
+ "hooks": "@/hooks"
+ },
+ "registries": {}
+}
diff --git a/apps/docs/registry/channel/web-tanstack/tsconfig.json b/apps/docs/registry/channel/web-tanstack/tsconfig.json
new file mode 100644
index 000000000..e3d88ce4f
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "compilerOptions": {
+ "target": "ES2022",
+ "lib": ["dom", "dom.iterable", "esnext"],
+ "skipLibCheck": true,
+ "strict": true,
+ "noEmit": true,
+ "esModuleInterop": true,
+ "module": "esnext",
+ "moduleResolution": "Bundler",
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "jsx": "react-jsx",
+ "types": ["vite/client"],
+ "paths": {
+ "@/*": ["./*"]
+ }
+ },
+ "include": ["**/*.ts", "**/*.tsx"],
+ "exclude": ["node_modules", ".output", ".vercel"]
+}
diff --git a/apps/docs/registry/channel/web-tanstack/vite.config.ts b/apps/docs/registry/channel/web-tanstack/vite.config.ts
new file mode 100644
index 000000000..5c70b7b61
--- /dev/null
+++ b/apps/docs/registry/channel/web-tanstack/vite.config.ts
@@ -0,0 +1,10 @@
+import { tanstackStart } from "@tanstack/react-start/plugin/vite";
+import tailwindcss from "@tailwindcss/vite";
+import viteReact from "@vitejs/plugin-react";
+import { nitro } from "nitro/vite";
+import { defineConfig } from "vite";
+
+export default defineConfig({
+ resolve: { tsconfigPaths: true },
+ plugins: [tailwindcss(), tanstackStart({ srcDirectory: "app" }), viteReact(), nitro()],
+});
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 c9feebc6b..edfbe879c 100644
--- a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx
+++ b/apps/docs/registry/channel/web/app/_components/agent-chat.tsx
@@ -49,7 +49,8 @@ export function AgentChat({
resume: sessionId !== undefined,
onSessionChange(session) {
if (sessionId === undefined && session !== undefined) {
- // Next patches window.history to navigate, which would detach the active stream.
+ // 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,
diff --git a/apps/docs/registry/channel/web/app/globals.css b/apps/docs/registry/channel/web/app/globals.css
index 28b7b8c2f..835cd786c 100644
--- a/apps/docs/registry/channel/web/app/globals.css
+++ b/apps/docs/registry/channel/web/app/globals.css
@@ -24,6 +24,10 @@
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
+}
+
+/* Not inline: font utilities must read the variables so each host's font loader can override them. */
+@theme {
--font-sans: "Geist", "Geist Fallback", ui-sans-serif, system-ui, sans-serif;
--font-mono: "Geist Mono", "Geist Mono Fallback", ui-monospace, monospace;
}
diff --git a/apps/docs/scripts/validate-channel-registry.ts b/apps/docs/scripts/validate-channel-registry.ts
index 606148d36..891b27a6e 100644
--- a/apps/docs/scripts/validate-channel-registry.ts
+++ b/apps/docs/scripts/validate-channel-registry.ts
@@ -14,6 +14,7 @@ interface RegistryItem {
files?: RegistryFile[];
meta?: {
eve?: {
+ hidden?: boolean;
setup?:
| {
command?: string;
@@ -96,7 +97,13 @@ const nonStreamingCatalogSlugs = new Set(["chat-sdk-sendblue"]);
const docsRoot = join(import.meta.dirname, "..");
const registry = JSON.parse(await readFile(join(docsRoot, "registry.json"), "utf8")) as Registry;
-const items = registry.items.filter((item) => item.name.startsWith("channel/"));
+const channelItems = registry.items.filter((item) => item.name.startsWith("channel/"));
+
+// Framework variants of Web Chat that `eve add channel/web` installs. They are
+// one catalog channel, so they stay hidden and share the Web Chat setup.
+const webChatVariantNames = new Set(["channel/web-tanstack"]);
+const items = channelItems.filter((item) => !webChatVariantNames.has(item.name));
+const webChatVariants = channelItems.filter((item) => webChatVariantNames.has(item.name));
const registryEntries = channelEntries().filter((entry) => entry.surfaces.registry);
const expectedSlugs = registryEntries.map(
(entry) => registrySlugsByCatalogSlug[entry.slug] ?? entry.slug,
@@ -109,14 +116,56 @@ if (JSON.stringify(actualSlugs) !== JSON.stringify(expectedSlugs)) {
);
}
-for (const [index, item] of items.entries()) {
+function declaredSetups(item: RegistryItem) {
const declaredSetup = item.meta?.eve?.setup;
- const setups =
- declaredSetup === undefined
- ? undefined
- : Array.isArray(declaredSetup)
- ? declaredSetup
- : [declaredSetup];
+ return declaredSetup === undefined
+ ? undefined
+ : Array.isArray(declaredSetup)
+ ? declaredSetup
+ : [declaredSetup];
+}
+
+function assertDelegatesSetup(item: RegistryItem, setupKind: string): void {
+ const expectedArgs = ["integration", "setup", setupKind];
+ if (
+ JSON.stringify(declaredSetups(item)) !==
+ JSON.stringify([{ command: "eve", package: "eve", bin: "eve", args: expectedArgs }])
+ ) {
+ throw new Error(
+ `Registry item "${item.name}" must delegate setup to eve integration setup ${setupKind}.`,
+ );
+ }
+}
+
+function assertWebChatItem(item: RegistryItem): void {
+ if (
+ item.dependencies?.some((dependency) => dependency === "ai" || dependency.startsWith("ai@"))
+ ) {
+ throw new Error(
+ `Registry item "${item.name}" must preserve the agent's existing AI SDK dependency.`,
+ );
+ }
+ if (item.files?.some((file) => file.target === "tsconfig.json")) {
+ throw new Error(
+ `Registry item "${item.name}" must let eve prepare tsconfig.json before shadcn installs files.`,
+ );
+ }
+}
+
+for (const name of webChatVariantNames) {
+ const item = webChatVariants.find((candidate) => candidate.name === name);
+ if (item === undefined) throw new Error(`apps/docs/registry.json must define ${name}.`);
+ if (item.meta?.eve?.hidden !== true) {
+ throw new Error(
+ `Registry item "${name}" must be hidden; users install it through channel/web.`,
+ );
+ }
+ assertWebChatItem(item);
+ assertDelegatesSetup(item, "web");
+}
+
+for (const [index, item] of items.entries()) {
+ const setups = declaredSetups(item);
if (
setups?.some(
(setup) =>
@@ -133,32 +182,11 @@ for (const [index, item] of items.entries()) {
const entry = registryEntries[index];
if (entry === undefined) throw new Error(`Unexpected channel registry item "${item.name}".`);
- if (entry.slug === "eve") {
- if (
- item.dependencies?.some((dependency) => dependency === "ai" || dependency.startsWith("ai@"))
- ) {
- throw new Error(
- `Registry item "${item.name}" must preserve the agent's existing AI SDK dependency.`,
- );
- }
- if (item.files?.some((file) => file.target === "tsconfig.json")) {
- throw new Error(
- `Registry item "${item.name}" must let eve prepare tsconfig.json before shadcn installs files.`,
- );
- }
- }
+ if (entry.slug === "eve") assertWebChatItem(item);
const setupKind = setupKindsByCatalogSlug[entry.slug];
if (setupKind !== undefined) {
- const expectedArgs = ["integration", "setup", setupKind];
- if (
- JSON.stringify(setups) !==
- JSON.stringify([{ command: "eve", package: "eve", bin: "eve", args: expectedArgs }])
- ) {
- throw new Error(
- `Registry item "${item.name}" must delegate setup to eve integration setup ${expectedArgs[2]}.`,
- );
- }
+ assertDelegatesSetup(item, setupKind);
continue;
}
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index b7fb5c46e..dd24118e3 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -21,7 +21,8 @@ export default eveChannel({
## Web Chat with Sign in with Vercel
Run `eve add channel/web`, or select **Web Chat** from the terminal UI's channel
-picker. Choose a hosting layout, then **Sign in with Vercel**. Setup uses a
+picker. Choose **Next.js**, a hosting layout, then **Sign in with Vercel**. Sign
+in with Vercel is available only for the Next.js Web Chat app. Setup uses a
linked Vercel project and creates a Vercel App that only members of that
project's team can sign in to.
diff --git a/docs/concepts/project-structure.mdx b/docs/concepts/project-structure.mdx
index c39bb71bd..f530e91ad 100644
--- a/docs/concepts/project-structure.mdx
+++ b/docs/concepts/project-structure.mdx
@@ -32,7 +32,7 @@ project/
Create the agent with [Getting Started](/docs/getting-started). The [Agent Files reference](/docs/reference/agent-files) lists supported paths. Keep agent-only helpers in `agent/lib/`; share reusable capabilities through [extensions](/docs/extensions).
-For a generated Next.js chat UI, run `eve add channel/web` from the project root. For an existing browser app, follow your [framework integration guide](/docs/guides/frontend/overview#per-framework-integration).
+For a generated chat UI, run `eve add channel/web` from the project root and choose Next.js or TanStack Start. For an existing browser app, follow your [framework integration guide](/docs/guides/frontend/overview#per-framework-integration).
## Several root agents
@@ -79,7 +79,7 @@ Choose how the frontend and agents run together independently of how many agents
`apps/web/` is an organizational convention, not an eve filesystem slot. Deployment configuration owns peer services; eve discovers only the agents. Both Vercel integrations deploy the services together, not as independent releases.
-Run `eve add channel/web` from a standalone agent or select a workspace agent with `--agent <name>`. The installer creates a Next.js frontend under `apps/web/`. Choose **Vercel** to configure separate Vercel services and run them with `pnpm dev:all`; you don't need to link a Vercel project to run them locally. Choose **Other** to let Next.js host the agents and run the application with `pnpm dev:web`. Use `pnpm dev` or `pnpm dev:eve` when you only want one agent and the eve terminal UI.
+Run `eve add channel/web` from a standalone agent or select a workspace agent with `--agent <name>`. The installer asks which framework to use and creates a Next.js or TanStack Start frontend under `apps/web/`. Choose **Vercel services** to configure separate Vercel services and run them with `pnpm dev:all`; you don't need to link a Vercel project to run them locally. Choose **Next.js** or **TanStack Start** to let the frontend host the agent and run the application with `pnpm dev:web`. Use `pnpm dev` or `pnpm dev:eve` when you only want one agent and the eve terminal UI.
## Add a second root agent
diff --git a/docs/guides/frontend/nextjs.mdx b/docs/guides/frontend/nextjs.mdx
index d363d2e54..b51ff12df 100644
--- a/docs/guides/frontend/nextjs.mdx
+++ b/docs/guides/frontend/nextjs.mdx
@@ -15,7 +15,7 @@ Use this integration when Next.js owns the application's development and deploym
## Add the generated Web Chat app
-Install the generated Next.js Web Chat app from a standalone agent project:
+Install the generated Web Chat app from a standalone agent project, and choose **Next.js** when the installer asks which framework to use:
```bash
eve add channel/web
diff --git a/docs/guides/frontend/tanstack.mdx b/docs/guides/frontend/tanstack.mdx
index e62e7ad07..70bc5a4e5 100644
--- a/docs/guides/frontend/tanstack.mdx
+++ b/docs/guides/frontend/tanstack.mdx
@@ -11,6 +11,35 @@ description: "Run an eve agent and a TanStack Start app as one project with the
- An existing eve agent directory. If you don't have one, start from [Getting started](../../getting-started).
- A TanStack Start app using React, with the [Nitro Vite plugin](https://tanstack.com/start/latest/docs/framework/react/guide/hosting#nitro) (`nitro` installed and `nitro()` registered). TanStack Start deploys to Vercel through Nitro, and the plugin attaches eve to it.
+## Add the generated Web Chat app
+
+Run the Web Chat installer and choose **TanStack Start** when it asks which framework to use:
+
+```bash
+eve add channel/web
+```
+
+In automation, answer the framework and hosting questions up front. Without a `web-framework` answer, non-interactive installs use Next.js:
+
+```bash
+eve add channel/web --non-interactive \
+ --answer 'web-framework="tanstack"' \
+ --answer 'web-hosting="vercel"'
+```
+
+The installer creates a TanStack Start app under `apps/web/` and adds the `dev:web` and `build:web` scripts. It asks how to deploy it:
+
+- **Vercel services** (recommended) deploys Web Chat and the agent as separate services. Run both locally with `pnpm dev:all`; you don't need to link a Vercel project to do that.
+- **TanStack Start** hosts the agent in the TanStack Start app through `eveTanStack()`. Run it with `pnpm dev:web`. The app lives in `apps/web/` while its dependencies are in the project root `package.json`, so a Vercel deploy from the project root doesn't build it. Choose **Vercel services** to deploy Web Chat on Vercel.
+
+Rerun `eve add channel/web --skip-install` with the other choice to switch modes; the installer removes the `vercel.ts` and scripts it wrote for the previous one. When `apps/web/` already contains a Web Chat app, the installer keeps that app's framework and stops if you answer a different one. To switch between Next.js and TanStack Start, remove `apps/web/` first.
+
+Sign in with Vercel setup is available only for the Next.js Web Chat app, so the TanStack Start installer doesn't ask about authentication.
+
+The chat has the same URL-addressed durable sessions as the [Next.js Web Chat](./nextjs#use-the-generated-web-chat-routes): `/`, `/s`, and `/s/$sessionId`. Before accepting production browser traffic, replace the generated placeholder authorization policy. See [Authenticate browser requests](./overview#authenticate-browser-requests).
+
+The installer doesn't support selecting a workspace agent for single-app hosting: a workspace agent always deploys as a separate Vercel service. If you already have a TanStack Start app, skip the installer and follow the steps below.
+
## Register the Vite plugin
Add `eveTanStack()` to `vite.config.ts` next to `nitro()`:
diff --git a/docs/install-integrations.mdx b/docs/install-integrations.mdx
index cb84116ad..030cdd055 100644
--- a/docs/install-integrations.mdx
+++ b/docs/install-integrations.mdx
@@ -19,7 +19,7 @@ eve add memory/file
If an item is not found, `eve add` searches the available catalogs and prints close matches without installing anything.
-Web Chat installs a shared Next.js application at `apps/web` for either a standalone agent or a selected member of an agent workspace. Choose **Vercel services** (recommended) to deploy Web Chat and agents as separate services, or **Next.js** to serve Web Chat and route agent requests through one Next.js app. Vercel services run locally without a linked Vercel project; link one when you are ready to deploy. Existing authored Next.js or Vercel configuration is preserved, and eve stops with manual composition guidance instead of overwriting it. See [Project Structure](./concepts/project-structure) for browser-app placement and [Next.js](./guides/frontend/nextjs) for Next.js-owned integration.
+Web Chat installs a shared Next.js or TanStack Start application at `apps/web` for either a standalone agent or a selected member of an agent workspace. The installer asks which framework to use (`web-framework`), then how to deploy it; non-interactive runs use Next.js unless you answer `web-framework="tanstack"`. Choose **Vercel services** (recommended) to deploy Web Chat and agents as separate services, or the framework (**Next.js** or **TanStack Start**) to serve Web Chat and route agent requests through one app. Vercel services run locally without a linked Vercel project; link one when you are ready to deploy. Existing authored Next.js or Vercel configuration is preserved, and eve stops with manual composition guidance instead of overwriting it. See [Project Structure](./concepts/project-structure) for browser-app placement, and [Next.js](./guides/frontend/nextjs) or [TanStack Start](./guides/frontend/tanstack) for framework-owned integration.
If you do not know an item name yet, run `eve add` without an argument. Its help output shows how to search the registry with `eve registry search <query>`.
diff --git a/docs/tutorial/ship-it.mdx b/docs/tutorial/ship-it.mdx
index a1aca8dcb..f85c04661 100644
--- a/docs/tutorial/ship-it.mdx
+++ b/docs/tutorial/ship-it.mdx
@@ -7,7 +7,7 @@ The analytics assistant runs in the TUI. Now add a web dashboard and deploy a pr
## Add the Web Chat app
-Step 1 scaffolded the agent without a web frontend. Add one now with `eve add channel/web`, run from the `analytics-assistant/` directory:
+Step 1 scaffolded the agent without a web frontend. Add one now with `eve add channel/web`, run from the `analytics-assistant/` directory, and choose **Next.js** when it asks which framework to use:
```bash
npx eve add channel/web
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 90a73116b..9e1f54c6f 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -16,6 +16,7 @@
"observability",
"react",
"serverless",
+ "tanstack",
"tools",
"vercel",
"workflow"
diff --git a/packages/eve/src/cli/commands/registry-project.integration.test.ts b/packages/eve/src/cli/commands/registry-project.integration.test.ts
index c89796239..93e0a93e8 100644
--- a/packages/eve/src/cli/commands/registry-project.integration.test.ts
+++ b/packages/eve/src/cli/commands/registry-project.integration.test.ts
@@ -4,7 +4,13 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
-import { prepareWebRegistryProject, readRegistryConfig } from "./registry-project.js";
+import { parse as parseJsonc } from "#compiled/jsonc-parser/index.js";
+
+import {
+ prepareWebChatProjectRoot,
+ prepareWebRegistryProject,
+ readRegistryConfig,
+} from "./registry-project.js";
describe("readRegistryConfig", () => {
it("reads registry mappings from an agent workspace package", async () => {
@@ -34,4 +40,108 @@ describe("prepareWebRegistryProject", () => {
await expect(readFile(tsconfigPath, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
});
+
+ it("merges the TanStack Start tsconfig into an existing app without Next.js config", async () => {
+ const workspaceRoot = await mkdtemp(join(tmpdir(), "eve-registry-web-project-"));
+ const tsconfigPath = join(workspaceRoot, "apps", "web", "tsconfig.json");
+ await mkdir(join(workspaceRoot, "apps", "web"), { recursive: true });
+ await writeFile(
+ tsconfigPath,
+ '{\n // Authored settings.\n "compilerOptions": { "strict": false, "types": ["node"] },\n}\n',
+ );
+
+ await prepareWebRegistryProject(workspaceRoot, "tanstack");
+
+ const source = await readFile(tsconfigPath, "utf8");
+ expect(source).toContain("// Authored settings.");
+ expect(parseJsonc(source)).toEqual({
+ compilerOptions: {
+ strict: false,
+ types: ["node", "vite/client"],
+ target: "ES2022",
+ lib: ["dom", "dom.iterable", "esnext"],
+ skipLibCheck: true,
+ noEmit: true,
+ esModuleInterop: true,
+ module: "esnext",
+ moduleResolution: "Bundler",
+ resolveJsonModule: true,
+ isolatedModules: true,
+ jsx: "react-jsx",
+ paths: { "@/*": ["./*"] },
+ },
+ include: ["**/*.ts", "**/*.tsx"],
+ exclude: ["node_modules", ".output", ".vercel"],
+ });
+ });
+});
+
+describe("prepareWebChatProjectRoot", () => {
+ async function createProjectRoot(scripts: Record<string, string>): Promise<string> {
+ const root = await mkdtemp(join(tmpdir(), "eve-registry-web-scripts-"));
+ await mkdir(join(root, "agent"), { recursive: true });
+ await writeFile(
+ join(root, "package.json"),
+ JSON.stringify({ dependencies: { eve: "*" }, scripts }),
+ );
+ return root;
+ }
+
+ async function readScripts(root: string): Promise<Record<string, string>> {
+ return (
+ JSON.parse(await readFile(join(root, "package.json"), "utf8")) as {
+ scripts: Record<string, string>;
+ }
+ ).scripts;
+ }
+
+ it("adds Next.js web scripts by default", async () => {
+ const root = await createProjectRoot({});
+
+ await prepareWebChatProjectRoot(root);
+
+ await expect(readScripts(root)).resolves.toEqual({
+ "build:web": "next build apps/web",
+ "dev:web": "next dev apps/web",
+ });
+ });
+
+ it("adds Vite web scripts for TanStack Start and keeps authored scripts", async () => {
+ const root = await createProjectRoot({ "dev:web": "custom" });
+
+ await prepareWebChatProjectRoot(root, "tanstack");
+
+ await expect(readScripts(root)).resolves.toEqual({
+ "build:web": "vite build apps/web",
+ "dev:web": "custom",
+ });
+ });
+
+ it("replaces Next.js installer scripts when switching to TanStack Start", async () => {
+ const root = await createProjectRoot({
+ "build:web": "next build apps/web",
+ "dev:web": "next dev apps/web",
+ });
+
+ await prepareWebChatProjectRoot(root, "tanstack");
+
+ await expect(readScripts(root)).resolves.toEqual({
+ "build:web": "vite build apps/web",
+ "dev:web": "vite dev apps/web",
+ });
+ });
+
+ it("replaces TanStack Start installer scripts when switching to Next.js", async () => {
+ const root = await createProjectRoot({
+ "build:web": "vite build apps/web",
+ "dev:web": "vite dev apps/web",
+ });
+
+ await prepareWebChatProjectRoot(root, "next");
+
+ await expect(readScripts(root)).resolves.toEqual({
+ "build:web": "next build apps/web",
+ "dev:web": "next dev apps/web",
+ });
+ });
});
diff --git a/packages/eve/src/cli/commands/registry-project.ts b/packages/eve/src/cli/commands/registry-project.ts
index 9b2cbf065..952faeb16 100644
--- a/packages/eve/src/cli/commands/registry-project.ts
+++ b/packages/eve/src/cli/commands/registry-project.ts
@@ -9,7 +9,17 @@ import {
} from "#compiled/jsonc-parser/index.js";
import type { RegistryConfig, RegistrySource } from "#compiled/shadcn-registry/index.js";
import { resolveEveProjectContext } from "#internal/project-context.js";
-import { WEB_APP_TEMPLATE_FILES } from "#setup/scaffold/create/web-template.js";
+import type { Asker } from "#setup/ask.js";
+import {
+ detectWebChatFramework,
+ WEB_CHAT_FRAMEWORK_LABELS,
+ WEB_FRAMEWORK_QUESTION,
+ type WebChatFramework,
+} from "#setup/integrations/web/framework.js";
+import {
+ WEB_APP_TANSTACK_TEMPLATE_FILES,
+ WEB_APP_TEMPLATE_FILES,
+} from "#setup/scaffold/create/web-template.js";
interface RegistryPackage {
path: string;
@@ -85,8 +95,45 @@ function parseRegistryMapping(argument: string): { namespace: string; url: strin
return { namespace, url };
}
+/** Dev and build commands that run the Web Chat app in `apps/web`, by host framework. */
+const WEB_CHAT_SCRIPTS: Readonly<Record<WebChatFramework, Readonly<Record<string, string>>>> = {
+ next: { "dev:web": "next dev apps/web", "build:web": "next build apps/web" },
+ tanstack: { "dev:web": "vite dev apps/web", "build:web": "vite build apps/web" },
+};
+
+function isWebChatScriptDefault(name: string, command: string): boolean {
+ return Object.values(WEB_CHAT_SCRIPTS).some((scripts) => scripts[name] === command);
+}
+
+/**
+ * Picks the framework `eve add channel/web` installs, before it writes any file.
+ * An app already in `apps/web` decides; an explicit answer that conflicts fails.
+ */
+export async function resolveWebChatFramework(
+ appRoot: string,
+ asker: Asker,
+ answers: Readonly<Record<string, unknown>> = {},
+): Promise<WebChatFramework> {
+ const project = await resolveEveProjectContext(appRoot);
+ if (project.kind === "workspace") {
+ throw new Error("Web Chat setup requires a selected workspace agent.");
+ }
+ const existing = await detectWebChatFramework(join(project.environmentRoot, "apps", "web"));
+ if (existing !== undefined && !(WEB_FRAMEWORK_QUESTION.key in answers)) return existing;
+ const framework = await asker.ask(WEB_FRAMEWORK_QUESTION);
+ if (existing !== undefined && framework !== existing) {
+ throw new Error(
+ `apps/web already contains a ${WEB_CHAT_FRAMEWORK_LABELS[existing]} app. Remove apps/web to switch Web Chat to ${WEB_CHAT_FRAMEWORK_LABELS[framework]}, or answer ${WEB_FRAMEWORK_QUESTION.key}="${existing}".`,
+ );
+ }
+ return framework;
+}
+
/** Resolves and prepares the root package that owns Web Chat. */
-export async function prepareWebChatProjectRoot(appRoot: string): Promise<string> {
+export async function prepareWebChatProjectRoot(
+ appRoot: string,
+ framework: WebChatFramework = "next",
+): Promise<string> {
const project = await resolveEveProjectContext(appRoot);
if (project.kind === "workspace") {
throw new Error("Web Chat setup requires a selected workspace agent.");
@@ -99,8 +146,13 @@ export async function prepareWebChatProjectRoot(appRoot: string): Promise<string
[key: string]: unknown;
};
const scripts = { ...document.scripts };
- scripts["dev:web"] ??= "next dev apps/web";
- scripts["build:web"] ??= "next build apps/web";
+ for (const [name, command] of Object.entries(WEB_CHAT_SCRIPTS[framework])) {
+ const current = scripts[name];
+ // Another framework's installer default would run the wrong dev server.
+ if (current === undefined || isWebChatScriptDefault(name, current)) {
+ scripts[name] = command;
+ }
+ }
await writeFile(
packageJsonPath,
`${JSON.stringify({ ...document, scripts }, null, 2)}\n`,
@@ -123,7 +175,22 @@ function setJsoncValue(source: string, path: (string | number)[], value: unknown
);
}
-export function addWebRegistryTsconfig(source: string, path: string): string {
+interface WebRegistryTsconfigTemplate {
+ compilerOptions: Record<string, unknown>;
+ include: string[];
+ exclude: string[];
+}
+
+const WEB_REGISTRY_TSCONFIG_SOURCES: Readonly<Record<WebChatFramework, string>> = {
+ next: WEB_APP_TEMPLATE_FILES["tsconfig.json"],
+ tanstack: WEB_APP_TANSTACK_TEMPLATE_FILES["tsconfig.json"],
+};
+
+export function addWebRegistryTsconfig(
+ source: string,
+ path: string,
+ framework: WebChatFramework = "next",
+): string {
const errors: ParseError[] = [];
const parsed = parseJsonc(source, errors, { allowTrailingComma: true });
if (errors.length > 0 || typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
@@ -139,11 +206,9 @@ export function addWebRegistryTsconfig(source: string, path: string): string {
include?: string[];
exclude?: string[];
};
- const template = JSON.parse(WEB_APP_TEMPLATE_FILES["tsconfig.json"]) as {
- compilerOptions: Record<string, unknown>;
- include: string[];
- exclude: string[];
- };
+ const template = JSON.parse(
+ WEB_REGISTRY_TSCONFIG_SOURCES[framework],
+ ) as WebRegistryTsconfigTemplate;
const configuredAlias = document.compilerOptions?.paths?.["@/*"];
if (
configuredAlias !== undefined &&
@@ -156,10 +221,17 @@ export function addWebRegistryTsconfig(source: string, path: string): string {
let updated = source;
for (const [key, value] of Object.entries(template.compilerOptions)) {
- if (key === "paths" || key === "plugins" || document.compilerOptions?.[key] !== undefined) {
- continue;
+ if (key === "paths" || key === "plugins") continue;
+ const current = document.compilerOptions?.[key];
+ if (current === undefined) {
+ updated = setJsoncValue(updated, ["compilerOptions", key], value);
+ } else if (key === "types" && Array.isArray(current) && Array.isArray(value)) {
+ // Vite's `import.meta.env` typings must load alongside authored ambient types.
+ const types = [...new Set([...current, ...value])];
+ if (types.length > current.length) {
+ updated = setJsoncValue(updated, ["compilerOptions", "types"], types);
+ }
}
- updated = setJsoncValue(updated, ["compilerOptions", key], value);
}
if (configuredAlias === undefined) {
updated = setJsoncValue(updated, ["compilerOptions", "paths", "@/*"], ["./*"]);
@@ -170,7 +242,7 @@ export function addWebRegistryTsconfig(source: string, path: string): string {
(plugin) =>
typeof plugin === "object" && plugin !== null && "name" in plugin && plugin.name === "next",
);
- if (!hasNextPlugin) {
+ if (framework === "next" && !hasNextPlugin) {
updated = setJsoncValue(
updated,
["compilerOptions", "plugins"],
@@ -191,7 +263,10 @@ export function addWebRegistryTsconfig(source: string, path: string): string {
}
/** Prepares the TypeScript host configuration shadcn registry items expect. */
-export async function prepareWebRegistryProject(appRoot: string): Promise<void> {
+export async function prepareWebRegistryProject(
+ appRoot: string,
+ framework: WebChatFramework = "next",
+): Promise<void> {
const path = join(appRoot, "apps", "web", "tsconfig.json");
let source: string;
try {
@@ -204,7 +279,7 @@ export async function prepareWebRegistryProject(appRoot: string): Promise<void>
`Could not add Web Chat because ${path} could not be read: ${errorMessage(error)}`,
);
}
- const updated = addWebRegistryTsconfig(source, path);
+ const updated = addWebRegistryTsconfig(source, path, framework);
if (updated !== source) await writeFile(path, updated, "utf8");
}
diff --git a/packages/eve/src/cli/commands/registry.test.ts b/packages/eve/src/cli/commands/registry.test.ts
index 6786d147f..489ef01d7 100644
--- a/packages/eve/src/cli/commands/registry.test.ts
+++ b/packages/eve/src/cli/commands/registry.test.ts
@@ -30,6 +30,7 @@ const {
resolveInstalledPackageInfo,
unlink,
searchRegistries,
+ stat,
writeFile,
} = vi.hoisted(() => ({
addRegistryItems: vi.fn(),
@@ -46,6 +47,7 @@ const {
resolveInstalledPackageInfo: vi.fn(() => ({ name: "eve", version: "0.27.8" })),
unlink: vi.fn(),
searchRegistries: vi.fn(),
+ stat: vi.fn(),
writeFile: vi.fn(),
}));
@@ -60,7 +62,7 @@ vi.mock("#internal/project-context.js", () => ({ resolveEveProjectContext }));
vi.mock("./registry-pnpm-build-policy-flow.js", () => ({ prepareDeclaredPnpmBuildPolicy }));
vi.mock("#setup/scaffold/workspace-root.js", () => ({ applyPackageManagerWorkspaceConfiguration }));
vi.mock("#internal/application/package.js", () => ({ resolveInstalledPackageInfo }));
-vi.mock("node:fs/promises", () => ({ readFile, unlink, writeFile }));
+vi.mock("node:fs/promises", () => ({ readFile, stat, unlink, writeFile }));
function createLogger(): RegistryCommandLogger & { errors: string[]; logs: string[] } {
const errors: string[] = [];
@@ -88,6 +90,7 @@ describe("registry commands", () => {
kind: "standalone",
}));
getRegistryItems.mockResolvedValue([]);
+ stat.mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" }));
readFile.mockResolvedValue(
JSON.stringify({
name: "project",
@@ -461,6 +464,7 @@ describe("registry commands", () => {
expect(prepareWebRegistryProject).toHaveBeenCalledTimes(kind === "web" ? 1 : 0);
if (kind === "web") {
+ expect(prepareWebRegistryProject).toHaveBeenCalledWith("/project", "next");
expect(prepareWebRegistryProject.mock.invocationCallOrder[0]).toBeLessThan(
addRegistryItems.mock.invocationCallOrder[0]!,
);
@@ -550,6 +554,120 @@ describe("registry commands", () => {
expect(logger.errors).toEqual([]);
});
+ it("installs the TanStack Start files when Web Chat is answered with TanStack Start", async () => {
+ const logger = createLogger();
+ const prepareWebRegistryProject = vi.fn(async () => {});
+ const runSetupCommand = vi.fn(async () => ({ kind: "completed" as const, facts: [] }));
+ getRegistryItems.mockResolvedValue([
+ {
+ name: "channel/web-tanstack",
+ type: "registry:item",
+ meta: {
+ eve: {
+ setup: [{ package: "eve", bin: "eve", args: ["integration", "setup", "web"] }],
+ },
+ },
+ },
+ ]);
+
+ await runAddCommand(
+ logger,
+ "/project",
+ "channel/web",
+ { nonInteractive: true, answers: { "web-framework": "tanstack" } },
+ { loadSetupCommandRunner: async () => runSetupCommand, prepareWebRegistryProject },
+ );
+
+ expect(writeFile).toHaveBeenCalledWith(
+ "/project/package.json",
+ expect.stringContaining('"dev:web": "vite dev apps/web"'),
+ "utf8",
+ );
+ expect(prepareWebRegistryProject).toHaveBeenCalledWith("/project", "tanstack");
+ expect(getRegistryItems).toHaveBeenCalledWith(
+ ["https://eve.dev/r/channel/web-tanstack.json"],
+ expect.any(Object),
+ );
+ expect(addRegistryItems).toHaveBeenCalledWith(
+ ["https://eve.dev/r/channel/web-tanstack.json"],
+ expect.objectContaining({ cwd: "/project" }),
+ );
+ expect(runSetupCommand).toHaveBeenCalledWith(
+ "/project",
+ expect.objectContaining({ args: expect.arrayContaining(["integration", "setup", "web"]) }),
+ "channel/web",
+ expect.any(Object),
+ );
+ expect(logger.errors).toEqual([]);
+ });
+
+ it("installs the Next.js files when a headless install leaves the framework unanswered", async () => {
+ const logger = createLogger();
+ const prepareWebRegistryProject = vi.fn(async () => {});
+ getRegistryItems.mockResolvedValue([{ name: "channel/web", type: "registry:item" }]);
+
+ await runAddCommand(
+ logger,
+ "/project",
+ "channel/web",
+ { nonInteractive: true, skipSetup: true },
+ {
+ loadSetupCommandRunner: async () =>
+ vi.fn(async () => ({ kind: "completed" as const, facts: [] })),
+ prepareWebRegistryProject,
+ },
+ );
+
+ expect(prepareWebRegistryProject).toHaveBeenCalledWith("/project", "next");
+ expect(addRegistryItems).toHaveBeenCalledWith(
+ ["https://eve.dev/r/channel/web.json"],
+ expect.objectContaining({ cwd: "/project" }),
+ );
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it("reports an invalid headless framework answer before writing anything", async () => {
+ const logger = createLogger();
+
+ await runAddCommand(logger, "/project", "channel/web", {
+ nonInteractive: true,
+ answers: { "web-framework": "nuxt" },
+ });
+
+ expect(logger.errors.map((line) => JSON.parse(line))).toEqual([
+ expect.objectContaining({
+ type: "blocked",
+ item: "channel/web",
+ installed: false,
+ status: "input_required",
+ question: expect.objectContaining({ key: "web-framework" }),
+ issue: expect.objectContaining({ code: "invalid_answer" }),
+ }),
+ ]);
+ expect(writeFile).not.toHaveBeenCalled();
+ expect(addRegistryItems).not.toHaveBeenCalled();
+ expect(process.exitCode).toBe(2);
+ });
+
+ it("refuses to install a second Web Chat framework over an existing app", async () => {
+ const logger = createLogger();
+ stat.mockImplementation(async (path: string) => {
+ if (path === "/project/apps/web/next.config.ts") return {};
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ });
+
+ await runAddCommand(logger, "/project", "channel/web", {
+ nonInteractive: true,
+ answers: { "web-framework": "tanstack" },
+ });
+
+ expect(logger.errors).toEqual([
+ 'apps/web already contains a Next.js app. Remove apps/web to switch Web Chat to TanStack Start, or answer web-framework="next".',
+ ]);
+ expect(writeFile).not.toHaveBeenCalled();
+ expect(addRegistryItems).not.toHaveBeenCalled();
+ });
+
it("surfaces required deployment in non-interactive completion", async () => {
const logger = createLogger();
const runSetupCommand = vi.fn(async () => ({
diff --git a/packages/eve/src/cli/commands/registry.ts b/packages/eve/src/cli/commands/registry.ts
index 68af5a96c..5e1531803 100644
--- a/packages/eve/src/cli/commands/registry.ts
+++ b/packages/eve/src/cli/commands/registry.ts
@@ -7,9 +7,18 @@ import {
} from "#compiled/shadcn-registry/index.js";
import semver from "#compiled/semver/index.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
+import {
+ headlessAsker,
+ interactiveAsker,
+ InvalidAnswerError,
+ withAnswers,
+ withPolicy,
+} from "#setup/ask.js";
+import type { WebChatFramework } from "#setup/integrations/web/framework.js";
import type { SetupPrerequisite } from "#setup/integrations/shared/prerequisite.js";
import { createPrompter, type Prompter } from "#setup/prompter.js";
import type { RegistrySetupCompletion } from "#setup/registry-setup-protocol.js";
+import { setupQuestionToWire } from "#setup/setup-question-wire.js";
import { WizardCancelledError } from "#setup/step.js";
import { hasInteractiveTerminal } from "./preconditions.js";
@@ -37,11 +46,12 @@ import {
type RegistrySearchPresentationSection,
} from "./registry-presentation.js";
import type { runRegistrySetupCommand } from "./registry-setup-command.js";
-import { serializeHeadlessSetupEvent } from "./setup-headless.js";
+import { headlessSetupContinuation, serializeHeadlessSetupEvent } from "./setup-headless.js";
import {
prepareWebChatProjectRoot,
prepareWebRegistryProject,
readRegistryConfig,
+ resolveWebChatFramework,
} from "./registry-project.js";
export { runRegistryAddCommand } from "./registry-add-command.js";
export type { RegistryCommandLogger } from "./registry-recovery.js";
@@ -169,6 +179,70 @@ function itemAddress(item: string): string {
: `${OFFICIAL_REGISTRY}/${item}.json`;
}
+/** The registry item that carries each Web Chat framework's files. */
+const WEB_CHAT_ITEMS: Readonly<Record<WebChatFramework, string>> = {
+ next: "channel/web",
+ tanstack: "channel/web-tanstack",
+};
+
+/**
+ * Asks which framework Web Chat uses. Only an interactive terminal prompts;
+ * every other run takes the `web-framework` answer or the Next.js default.
+ * Returns `false` when cancelled and `undefined` after reporting an invalid
+ * headless answer.
+ */
+async function askWebChatFramework(
+ logger: RegistryCommandLogger,
+ appRoot: string,
+ item: string,
+ options: RunAddCommandOptions,
+ dependencies: AddCommandDependencies,
+): Promise<WebChatFramework | false | undefined> {
+ const nonInteractive = options.nonInteractive === true;
+ const canPrompt =
+ options.setupAuthorized === true ||
+ (
+ dependencies.hasInteractiveTerminal ?? defaultAddCommandDependencies.hasInteractiveTerminal!
+ )();
+ // Headless and scripted installs keep working without an answer, as before frameworks existed.
+ const asker = withAnswers(options.answers ?? {})(
+ options.yes === true || nonInteractive || !canPrompt
+ ? withPolicy("assume")(headlessAsker())
+ : interactiveAsker(
+ options.prompter ??
+ dependencies.createPrompter?.() ??
+ defaultAddCommandDependencies.createPrompter!(),
+ ),
+ );
+ try {
+ return await resolveWebChatFramework(appRoot, asker, options.answers);
+ } catch (error) {
+ if (error instanceof WizardCancelledError) return false;
+ if (!nonInteractive || !(error instanceof InvalidAnswerError)) throw error;
+ const question = setupQuestionToWire(error.question);
+ logger.error(
+ serializeHeadlessSetupEvent({
+ version: 1,
+ type: "blocked",
+ item,
+ installed: false,
+ completedItems: [],
+ status: "input_required",
+ question,
+ issue: { code: "invalid_answer", message: error.message },
+ next: headlessSetupContinuation({
+ item,
+ installed: false,
+ answers: options.answers,
+ question,
+ }),
+ }),
+ );
+ process.exitCode = 2;
+ return undefined;
+ }
+}
+
function assertCompatibleEveVersion(requiredVersion: string | undefined): void {
if (requiredVersion === undefined) return;
const installedVersion = resolveInstalledPackageInfo().version;
@@ -489,9 +563,18 @@ export async function runAddCommand(
};
const action = async () => {
const address = itemAddress(item);
+ let webChatFramework: WebChatFramework | undefined;
+ // Setup reads the framework from the installed files, so only installs ask.
+ if (address === itemAddress(WEB_CHAT_ITEMS.next) && options.skipInstall !== true) {
+ const framework = await askWebChatFramework(logger, appRoot, item, options, dependencies);
+ if (framework === false || framework === undefined) return framework;
+ webChatFramework = framework;
+ }
+ const installAddress =
+ webChatFramework === undefined ? address : itemAddress(WEB_CHAT_ITEMS[webChatFramework]);
const projectRoot =
- address === itemAddress("channel/web") && options.skipInstall !== true
- ? await prepareWebChatProjectRoot(appRoot)
+ webChatFramework !== undefined
+ ? await prepareWebChatProjectRoot(appRoot, webChatFramework)
: appRoot;
const config = await readEveRegistryConfig(appRoot);
if (options.skipInstall === true) {
@@ -509,7 +592,7 @@ export async function runAddCommand(
}
const registryItemResult = await resolveRegistryItemForAdd(
logger,
- async () => (await getRegistryItems([address], { config }))[0],
+ async () => (await getRegistryItems([installAddress], { config }))[0],
() => printAddSuggestions(logger, appRoot, item),
);
if (!registryItemResult.found) return;
@@ -545,8 +628,11 @@ export async function runAddCommand(
});
if (!installReady) return false;
- if (address === itemAddress("channel/web")) {
- await (dependencies.prepareWebRegistryProject ?? prepareWebRegistryProject)(projectRoot);
+ if (webChatFramework !== undefined) {
+ await (dependencies.prepareWebRegistryProject ?? prepareWebRegistryProject)(
+ projectRoot,
+ webChatFramework,
+ );
}
await installRegistryItemTransaction({
appRoot: projectRoot,
@@ -555,7 +641,7 @@ export async function runAddCommand(
nonInteractive: options.nonInteractive,
logger,
install: async () => {
- await addRegistryItems([address], {
+ await addRegistryItems([installAddress], {
config,
cwd: projectRoot,
overwrite: options.overwrite,
diff --git a/packages/eve/src/setup/build.ts b/packages/eve/src/setup/build.ts
index b772b8122..a31b83f9d 100644
--- a/packages/eve/src/setup/build.ts
+++ b/packages/eve/src/setup/build.ts
@@ -1,5 +1,6 @@
// Build-time generator for the setup island's Web Chat template. Reads the
-// `apps/docs/registry/channel/web` source item, applies the declared scaffold transforms,
+// `apps/docs/registry/channel/web` source item, its `web-sign-in-with-vercel`
+// overlay, and the `web-tanstack` host config files, applies the declared scaffold transforms,
// and writes `scaffold/create/web-template.ts`. Not part of the shipped package: it is
// excluded from tsconfig.build.json and run on demand via the package scripts
// `generate:web-template` (--write) and `check:web-template` (--check, drift).
@@ -17,6 +18,9 @@ const SIGN_IN_WITH_VERCEL_SOURCE_ROOT = join(
REPO_ROOT,
"apps/docs/registry/channel/web-sign-in-with-vercel",
);
+const TANSTACK_SOURCE_ROOT = join(REPO_ROOT, "apps/docs/registry/channel/web-tanstack");
+// Only the host config files Web Chat setup and `eve add` read or write.
+const TANSTACK_TEMPLATE_FILES = ["tsconfig.json", "vite.config.ts"] as const;
const REGISTRY_PATH = join(REPO_ROOT, "apps/docs/registry.json");
const OUTPUT_PATH = join(SETUP_ROOT, "scaffold/create/web-template.ts");
@@ -174,6 +178,14 @@ async function renderGeneratedModule(): Promise<string> {
return renderFileEntry(relativePath, source);
}),
);
+ const tanStackEntries = await Promise.all(
+ TANSTACK_TEMPLATE_FILES.map(async (relativePath) =>
+ renderFileEntry(
+ relativePath,
+ await readFile(join(TANSTACK_SOURCE_ROOT, relativePath), "utf8"),
+ ),
+ ),
+ );
const packageTemplate = parsePackageTemplate(await readFile(REGISTRY_PATH, "utf8"));
const webChannelTemplate = await readFile(join(SOURCE_ROOT, WEB_CHANNEL_SOURCE_PATH), "utf8");
const webSignInWithVercelChannelTemplate = await readFile(
@@ -198,6 +210,10 @@ async function renderGeneratedModule(): Promise<string> {
...signInWithVercelEntries,
"} as const;",
"",
+ "export const WEB_APP_TANSTACK_TEMPLATE_FILES = {",
+ ...tanStackEntries,
+ "} as const;",
+ "",
"export const WEB_APP_TEMPLATE_PACKAGE_JSON = {",
renderStringRecord("scripts", packageTemplate.scripts),
renderStringRecord("dependencies", packageTemplate.dependencies),
diff --git a/packages/eve/src/setup/integrations/web/framework.ts b/packages/eve/src/setup/integrations/web/framework.ts
new file mode 100644
index 000000000..f1f4ce9f0
--- /dev/null
+++ b/packages/eve/src/setup/integrations/web/framework.ts
@@ -0,0 +1,67 @@
+import { join } from "node:path";
+
+import { select } from "#setup/ask.js";
+import { pathExists } from "#setup/scaffold/files.js";
+
+/** Frontend frameworks the Web Chat installer can generate. */
+export type WebChatFramework = "next" | "tanstack";
+
+export const WEB_CHAT_FRAMEWORK_LABELS: Readonly<Record<WebChatFramework, string>> = {
+ next: "Next.js",
+ tanstack: "TanStack Start",
+};
+
+/** Asked by `eve add channel/web` before it installs the frontend files. */
+export const WEB_FRAMEWORK_QUESTION = select<WebChatFramework>({
+ key: "web-framework",
+ message: "Which framework should Web Chat use?",
+ options: [
+ {
+ id: "next",
+ label: WEB_CHAT_FRAMEWORK_LABELS.next,
+ hint: "(Recommended) Supports Sign in with Vercel.",
+ value: "next",
+ },
+ {
+ id: "tanstack",
+ label: WEB_CHAT_FRAMEWORK_LABELS.tanstack,
+ hint: "A Vite app built with TanStack Router.",
+ value: "tanstack",
+ },
+ ],
+ recommended: "next",
+ required: true,
+});
+
+const HOST_CONFIG_FILES: Readonly<Record<WebChatFramework, readonly string[]>> = {
+ next: ["next.config.ts", "next.config.mjs", "next.config.js"],
+ tanstack: ["vite.config.ts", "vite.config.mjs", "vite.config.js"],
+};
+
+async function hasAny(
+ root: string,
+ files: readonly string[],
+ exists: typeof pathExists,
+): Promise<boolean> {
+ for (const file of files) {
+ if (await exists(join(root, file))) return true;
+ }
+ return false;
+}
+
+/** The framework of the app already in `webRoot`, or `undefined` when it has none. */
+export async function detectWebChatFramework(
+ webRoot: string,
+ exists: typeof pathExists = pathExists,
+): Promise<WebChatFramework | undefined> {
+ const [next, tanstack] = await Promise.all([
+ hasAny(webRoot, HOST_CONFIG_FILES.next, exists),
+ hasAny(webRoot, HOST_CONFIG_FILES.tanstack, exists),
+ ]);
+ if (next && tanstack) {
+ throw new Error(
+ `${webRoot} contains both a Next.js and a Vite config. Remove the app you no longer use, then retry.`,
+ );
+ }
+ return next ? "next" : tanstack ? "tanstack" : undefined;
+}
diff --git a/packages/eve/src/setup/integrations/web/hosting.ts b/packages/eve/src/setup/integrations/web/hosting.ts
new file mode 100644
index 000000000..304bc5ab9
--- /dev/null
+++ b/packages/eve/src/setup/integrations/web/hosting.ts
@@ -0,0 +1,207 @@
+import { readFile, rm } from "node:fs/promises";
+import { join } from "node:path";
+
+import { resolveEveProjectContext } from "#internal/project-context.js";
+import { detectPackageManager, type PackageManagerKind } from "#setup/package-manager.js";
+import { WEB_CHANNEL_TEMPLATES } from "#setup/scaffold/create/web-template.js";
+import { pathExists, writeTextFile } from "#setup/scaffold/files.js";
+
+export interface WebChatHostingDeps {
+ detectPackageManager: typeof detectPackageManager;
+ pathExists: typeof pathExists;
+ readTextFile(path: string): Promise<string>;
+ /** Defaults to a forced `rm`. */
+ removeFile?(path: string): Promise<void>;
+ resolveEveProjectContext: typeof resolveEveProjectContext;
+ writeTextFile: typeof writeTextFile;
+}
+
+const removeFile = (path: string) => rm(path, { force: true });
+
+export const defaultWebChatHostingDeps: WebChatHostingDeps = {
+ detectPackageManager,
+ pathExists,
+ readTextFile: (path) => readFile(path, "utf8"),
+ removeFile,
+ resolveEveProjectContext,
+ writeTextFile,
+};
+
+const PEER_SERVICE_SCRIPTS = {
+ dev: "eve dev",
+ "dev:eve": "eve dev",
+ "dev:all": "vercel dev --local",
+} as const;
+
+export function peerServiceVercelConfig(
+ framework: "nextjs" | "tanstack-start",
+ buildCommand: string,
+): string {
+ return `import { withEve } from "eve/vercel";
+
+export default await withEve({
+ services: {
+ web: {
+ framework: "${framework}",
+ root: "apps/web",
+ buildCommand: "${buildCommand}",
+ },
+ },
+ routes: [
+ { src: "^(.*)$", destination: { type: "service", service: "web" } },
+ ],
+});
+`;
+}
+
+export function runScriptCommand(packageManager: PackageManagerKind, script: string): string {
+ switch (packageManager) {
+ case "npm":
+ return `npm run ${script}`;
+ case "pnpm":
+ return `pnpm ${script}`;
+ case "yarn":
+ return `yarn ${script}`;
+ case "bun":
+ return `bun run ${script}`;
+ }
+}
+
+export interface WebChatProject {
+ environmentRoot: string;
+ agentAppRoot: string;
+ /** Set for a workspace member so the chat app targets it by name. */
+ agentName?: string;
+}
+
+export async function resolveWebChatProject(
+ appRoot: string,
+ deps: WebChatHostingDeps,
+): Promise<WebChatProject> {
+ const project = await deps.resolveEveProjectContext(appRoot);
+ switch (project.kind) {
+ case "workspace":
+ throw new Error("Web Chat setup requires a selected workspace agent.");
+ case "workspace-member":
+ return {
+ environmentRoot: project.environmentRoot,
+ agentAppRoot: project.member.appRoot,
+ agentName: project.member.name,
+ };
+ case "standalone":
+ return { environmentRoot: project.environmentRoot, agentAppRoot: project.appRoot };
+ }
+}
+
+type FileOwnership = "absent" | "installer" | "authored";
+
+/** Whether `path` is absent, holds one of the `allowed` sources the installer writes, or is authored. */
+async function readFileOwnership(
+ path: string,
+ allowed: readonly string[],
+ deps: WebChatHostingDeps,
+): Promise<FileOwnership> {
+ if (!(await deps.pathExists(path))) return "absent";
+ try {
+ return allowed.includes(await deps.readTextFile(path)) ? "installer" : "authored";
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "absent";
+ throw error;
+ }
+}
+
+function assertNotAuthored(path: string, ownership: FileOwnership): void {
+ if (ownership === "authored") {
+ throw new Error(
+ `Could not configure Web Chat because ${path} contains authored configuration. Preserve it and compose the eve integration manually.`,
+ );
+ }
+}
+
+async function updatePeerServiceScripts(
+ root: string,
+ deps: WebChatHostingDeps,
+ update: (scripts: Record<string, string>) => void,
+): Promise<void> {
+ const path = join(root, "package.json");
+ const document = JSON.parse(await deps.readTextFile(path)) as {
+ scripts?: Record<string, string>;
+ [key: string]: unknown;
+ };
+ const scripts = { ...document.scripts };
+ update(scripts);
+ if (JSON.stringify(scripts) === JSON.stringify({ ...document.scripts })) return;
+ await deps.writeTextFile(path, `${JSON.stringify({ ...document, scripts }, null, 2)}\n`, {
+ force: true,
+ });
+}
+
+export interface WebChatHostingInput {
+ project: WebChatProject;
+ webRoot: string;
+ force?: boolean;
+ /** Whether to write the default channel when it is absent (or forced). */
+ writeChannel: boolean;
+ /** The web app's framework config, e.g. `next.config.ts`. */
+ hostConfig: { path: string; source: string; owned: readonly string[] };
+ vercelServices: boolean;
+ /** The installer's `vercel.ts`, followed by any it wrote in earlier releases. */
+ vercelConfigs: readonly [string, ...string[]];
+}
+
+/**
+ * Checks every file Web Chat hosting would overwrite or remove, then returns
+ * the writer, so an authored file fails setup before anything is written.
+ */
+export async function prepareWebChatHosting(
+ input: WebChatHostingInput,
+ deps: WebChatHostingDeps,
+): Promise<() => Promise<void>> {
+ const { project, webRoot, hostConfig } = input;
+ const vercelTsPath = join(project.environmentRoot, "vercel.ts");
+ const vercelJsonPath = join(project.environmentRoot, "vercel.json");
+ assertNotAuthored(
+ hostConfig.path,
+ await readFileOwnership(hostConfig.path, hostConfig.owned, deps),
+ );
+ // Framework hosting leaves an authored vercel.ts (e.g. crons) alone and only
+ // removes one the installer wrote for Vercel services.
+ const vercelTsOwnership = await readFileOwnership(vercelTsPath, input.vercelConfigs, deps);
+ if (input.vercelServices) {
+ assertNotAuthored(vercelTsPath, vercelTsOwnership);
+ }
+ if (input.vercelServices && (await deps.pathExists(vercelJsonPath))) {
+ throw new Error(
+ `Could not configure Vercel services because ${vercelJsonPath} already exists. Preserve it and compose eve/vercel manually.`,
+ );
+ }
+ return async () => {
+ const channelPath = join(project.agentAppRoot, "agent", "channels", "eve.ts");
+ if (input.writeChannel && (input.force || !(await deps.pathExists(channelPath)))) {
+ await deps.writeTextFile(channelPath, WEB_CHANNEL_TEMPLATES.default, { force: input.force });
+ }
+ await deps.writeTextFile(
+ join(webRoot, "app", "eve-agent.ts"),
+ `/** Named workspace agent selected by the Web Chat installer. */\nexport const WEB_CHAT_AGENT: string | undefined = ${project.agentName === undefined ? "undefined" : JSON.stringify(project.agentName)};\n`,
+ { force: true },
+ );
+ await deps.writeTextFile(hostConfig.path, hostConfig.source, { force: true });
+ if (input.vercelServices) {
+ await deps.writeTextFile(vercelTsPath, input.vercelConfigs[0], { force: true });
+ await updatePeerServiceScripts(project.environmentRoot, deps, (scripts) => {
+ for (const [name, command] of Object.entries(PEER_SERVICE_SCRIPTS)) {
+ scripts[name] ??= command;
+ }
+ });
+ } else if (vercelTsOwnership === "installer") {
+ // A leftover services config keeps the root preset at "services", so Vercel
+ // would route eve through both the services config and the framework host.
+ await (deps.removeFile ?? removeFile)(vercelTsPath);
+ await updatePeerServiceScripts(project.environmentRoot, deps, (scripts) => {
+ for (const name of ["dev:eve", "dev:all"] as const) {
+ if (scripts[name] === PEER_SERVICE_SCRIPTS[name]) delete scripts[name];
+ }
+ });
+ }
+ };
+}
diff --git a/packages/eve/src/setup/integrations/web/setup.test.ts b/packages/eve/src/setup/integrations/web/setup.test.ts
index 755da71c5..50350d440 100644
--- a/packages/eve/src/setup/integrations/web/setup.test.ts
+++ b/packages/eve/src/setup/integrations/web/setup.test.ts
@@ -26,6 +26,55 @@ function deps(): WebSetupDeps {
};
}
+function contexts() {
+ return createSetupContexts({
+ appRoot: "/project",
+ asker: headlessAsker(),
+ environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),
+ prompter: createFakePrompter().prompter,
+ resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),
+ });
+}
+
+/** Serves `files` from memory; every other path is absent. */
+function withFiles(effects: WebSetupDeps, files: Record<string, string>) {
+ vi.mocked(effects.pathExists).mockImplementation(async (path) => path in files);
+ vi.mocked(effects.readTextFile).mockImplementation(async (path) => {
+ const source = files[path];
+ if (source === undefined) throw Object.assign(new Error(path), { code: "ENOENT" });
+ return source;
+ });
+ effects.removeFile = vi.fn(async () => {});
+ return effects;
+}
+
+const SERVICES_VERCEL_CONFIG = `import { withEve } from "eve/vercel";
+
+export default await withEve({
+ services: {
+ web: {
+ framework: "nextjs",
+ root: "apps/web",
+ buildCommand: "node ../../node_modules/next/dist/bin/next build",
+ },
+ },
+ routes: [
+ { src: "^(.*)$", destination: { type: "service", service: "web" } },
+ ],
+});
+`;
+const LEGACY_SERVICES_VERCEL_CONFIG = `import { withEve } from "eve/vercel";
+
+export default await withEve({
+ services: {
+ web: { framework: "nextjs", root: "apps/web" },
+ },
+ routes: [
+ { src: "^(.*)$", destination: { type: "service", service: "web" } },
+ ],
+});
+`;
+
describe("Web setup", () => {
it("presents the hosting topology with concise guidance", async () => {
const effects = deps();
@@ -79,6 +128,7 @@ describe("Web setup", () => {
});
await expect(prepareWebSetup(ctx.prepare, effects)).resolves.toEqual({
+ framework: "next",
hosting: "vercel",
packageManager: "pnpm",
});
@@ -101,6 +151,7 @@ describe("Web setup", () => {
});
await expect(prepareWebSetup(ctx.prepare, effects)).resolves.toEqual({
+ framework: "next",
hosting: "next",
packageManager: "pnpm",
});
@@ -126,7 +177,11 @@ describe("Web setup", () => {
});
await expect(
- applyWebSetup({ hosting: "vercel", packageManager: "pnpm" }, ctx.apply, effects),
+ applyWebSetup(
+ { framework: "next", hosting: "vercel", packageManager: "pnpm" },
+ ctx.apply,
+ effects,
+ ),
).rejects.toThrow("Web Chat setup requires a selected workspace agent.");
expect(effects.writeTextFile).not.toHaveBeenCalled();
@@ -150,7 +205,11 @@ describe("Web setup", () => {
prompter: createFakePrompter().prompter,
resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),
});
- await applyWebSetup({ hosting: "vercel", packageManager: "pnpm" }, ctx.apply, effects);
+ await applyWebSetup(
+ { framework: "next", hosting: "vercel", packageManager: "pnpm" },
+ ctx.apply,
+ effects,
+ );
expect(effects.writeTextFile).toHaveBeenNthCalledWith(
1,
@@ -192,7 +251,11 @@ describe("Web setup", () => {
resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),
});
- await applyWebSetup({ hosting: "vercel", packageManager: "pnpm" }, ctx.apply, effects);
+ await applyWebSetup(
+ { framework: "next", hosting: "vercel", packageManager: "pnpm" },
+ ctx.apply,
+ effects,
+ );
expect(effects.writeTextFile).toHaveBeenCalledWith(
"/project/package.json",
@@ -217,7 +280,11 @@ describe("Web setup", () => {
resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),
});
await expect(
- applyWebSetup({ hosting: "vercel", packageManager: "npm" }, ctx.apply, effects),
+ applyWebSetup(
+ { framework: "next", hosting: "vercel", packageManager: "npm" },
+ ctx.apply,
+ effects,
+ ),
).resolves.toEqual({
facts: [{ label: "", value: "Start locally with `npm run dev:all`." }],
});
@@ -252,7 +319,11 @@ describe("Web setup", () => {
});
await expect(
- applyWebSetup({ hosting: "next", packageManager: "yarn" }, ctx.apply, effects),
+ applyWebSetup(
+ { framework: "next", hosting: "next", packageManager: "yarn" },
+ ctx.apply,
+ effects,
+ ),
).resolves.toEqual({
facts: [{ label: "", value: "Start locally with `yarn dev:web`." }],
});
@@ -267,6 +338,81 @@ describe("Web setup", () => {
expect.anything(),
);
});
+ it("writes the Vercel services config byte for byte", async () => {
+ const effects = deps();
+
+ await applyWebSetup(
+ { framework: "next", hosting: "vercel", packageManager: "pnpm" },
+ contexts().apply,
+ effects,
+ );
+
+ expect(effects.writeTextFile).toHaveBeenCalledWith(
+ "/project/vercel.ts",
+ SERVICES_VERCEL_CONFIG,
+ { force: true },
+ );
+ });
+
+ it.each([
+ ["next", "vercel", "/project/apps/web/next.config.ts"],
+ ["next", "next", "/project/apps/web/next.config.ts"],
+ ["next", "vercel", "/project/vercel.ts"],
+ ["tanstack", "tanstack", "/project/apps/web/vite.config.ts"],
+ ] as const)(
+ "refuses %s with %s hosting over authored %s before writing anything",
+ async (framework, hosting, path) => {
+ const effects = withFiles(deps(), { [path]: "export default {};\n" });
+
+ await expect(
+ applyWebSetup({ framework, hosting, packageManager: "pnpm" }, contexts().apply, effects),
+ ).rejects.toThrow(`${path} contains authored configuration`);
+ expect(effects.writeTextFile).not.toHaveBeenCalled();
+ expect(effects.removeFile).not.toHaveBeenCalled();
+ },
+ );
+
+ it("leaves an authored vercel.ts alone for Next.js hosting", async () => {
+ const effects = withFiles(deps(), { "/project/vercel.ts": "export default {};\n" });
+
+ await applyWebSetup(
+ { framework: "next", hosting: "next", packageManager: "pnpm" },
+ contexts().apply,
+ effects,
+ );
+
+ expect(effects.removeFile).not.toHaveBeenCalled();
+ expect(effects.writeTextFile).not.toHaveBeenCalledWith(
+ "/project/vercel.ts",
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it.each([SERVICES_VERCEL_CONFIG, LEGACY_SERVICES_VERCEL_CONFIG])(
+ "removes the installer's Vercel services config when switching to Next.js hosting",
+ async (vercelConfig) => {
+ const effects = withFiles(deps(), {
+ "/project/vercel.ts": vercelConfig,
+ "/project/package.json":
+ '{"scripts":{"dev":"eve dev","dev:eve":"eve dev","dev:all":"vercel dev --local"}}\n',
+ });
+
+ await applyWebSetup(
+ { framework: "next", hosting: "next", packageManager: "pnpm" },
+ contexts().apply,
+ effects,
+ );
+
+ expect(effects.removeFile).toHaveBeenCalledWith("/project/vercel.ts");
+ expect(effects.writeTextFile).toHaveBeenCalledWith(
+ "/project/package.json",
+ `${JSON.stringify({ scripts: { dev: "eve dev" } }, null, 2)}\n`,
+ { force: true },
+ );
+ },
+ );
+
it("resolves a project for sign-in and provisions it before installing auth", async () => {
const effects = deps();
const writeAuth = vi.fn(async () => {});
@@ -314,6 +460,7 @@ describe("Web setup", () => {
await expect(
applyWebSetup(
{
+ framework: "next",
hosting: "vercel",
packageManager: "pnpm",
authProject: { orgId: "team", projectId: "project" },
@@ -326,3 +473,130 @@ describe("Web setup", () => {
expect(effects.installScaffoldDependencies).not.toHaveBeenCalled();
});
});
+
+const TANSTACK_SERVICES_VERCEL_CONFIG = `import { withEve } from "eve/vercel";
+
+export default await withEve({
+ services: {
+ web: {
+ framework: "tanstack-start",
+ root: "apps/web",
+ buildCommand: "node ../../node_modules/vite/bin/vite.js build",
+ },
+ },
+ routes: [
+ { src: "^(.*)$", destination: { type: "service", service: "web" } },
+ ],
+});
+`;
+
+const supportMember: EveProjectContext = {
+ environmentRoot: "/project",
+ kind: "workspace-member",
+ member: { appRoot: "/project/agents/support", name: "support" },
+ workspace: {
+ root: "/project",
+ members: [{ appRoot: "/project/agents/support", name: "support" }],
+ },
+};
+
+describe("Web setup for a TanStack Start app", () => {
+ const tanStackApp = { "/project/apps/web/vite.config.ts": "export default {};\n" };
+
+ it("offers TanStack Start hosting and skips the Next.js-only sign-in question", async () => {
+ const resolveVercelProject = vi.fn(async () => ({ orgId: "team", projectId: "project" }));
+ const ctx = createSetupContexts({
+ appRoot: "/project",
+ // Headless refuses unanswered required questions, so a sign-in prompt would throw.
+ asker: withAnswers({ "web-hosting": "tanstack" })(headlessAsker()),
+ environment: integrationSetupEnvironment("cli-missing", { kind: "unresolved" }),
+ prompter: createFakePrompter().prompter,
+ resolveVercelProject,
+ });
+
+ await expect(prepareWebSetup(ctx.prepare, withFiles(deps(), tanStackApp))).resolves.toEqual({
+ framework: "tanstack",
+ hosting: "tanstack",
+ packageManager: "pnpm",
+ });
+ expect(resolveVercelProject).not.toHaveBeenCalled();
+ });
+
+ it("deploys a workspace member as a peer service without asking", async () => {
+ const effects = withFiles(deps(), tanStackApp);
+ vi.mocked(effects.resolveEveProjectContext).mockResolvedValue(supportMember);
+
+ await expect(prepareWebSetup(contexts().prepare, effects)).resolves.toEqual({
+ framework: "tanstack",
+ hosting: "vercel",
+ packageManager: "pnpm",
+ });
+ });
+
+ it("configures Vercel services without mounting the agent in the app", async () => {
+ const effects = deps();
+
+ await expect(
+ applyWebSetup(
+ { framework: "tanstack", hosting: "vercel", packageManager: "npm" },
+ contexts().apply,
+ effects,
+ ),
+ ).resolves.toEqual({
+ facts: [{ label: "", value: "Start locally with `npm run dev:all`." }],
+ });
+ expect(effects.writeTextFile).toHaveBeenCalledWith(
+ "/project/apps/web/vite.config.ts",
+ expect.not.stringContaining("eveTanStack"),
+ { force: true },
+ );
+ expect(effects.writeTextFile).toHaveBeenCalledWith(
+ "/project/vercel.ts",
+ TANSTACK_SERVICES_VERCEL_CONFIG,
+ { force: true },
+ );
+ });
+
+ it("mounts the agent with eveTanStack for TanStack Start hosting", async () => {
+ const effects = deps();
+
+ await expect(
+ applyWebSetup(
+ { framework: "tanstack", hosting: "tanstack", packageManager: "yarn" },
+ contexts().apply,
+ effects,
+ ),
+ ).resolves.toEqual({
+ facts: [{ label: "", value: "Start locally with `yarn dev:web`." }],
+ });
+ expect(effects.writeTextFile).toHaveBeenCalledWith(
+ "/project/apps/web/vite.config.ts",
+ expect.stringContaining("eveTanStack({ eveRoot })"),
+ { force: true },
+ );
+ expect(effects.writeTextFile).not.toHaveBeenCalledWith(
+ "/project/vercel.ts",
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it("replaces the Next.js services config the installer wrote before a framework switch", async () => {
+ const effects = withFiles(deps(), {
+ "/project/vercel.ts": SERVICES_VERCEL_CONFIG,
+ "/project/package.json": '{"scripts":{"dev":"eve dev"}}\n',
+ });
+
+ await applyWebSetup(
+ { framework: "tanstack", hosting: "vercel", packageManager: "pnpm" },
+ contexts().apply,
+ effects,
+ );
+
+ expect(effects.writeTextFile).toHaveBeenCalledWith(
+ "/project/vercel.ts",
+ TANSTACK_SERVICES_VERCEL_CONFIG,
+ { force: true },
+ );
+ });
+});
diff --git a/packages/eve/src/setup/integrations/web/setup.ts b/packages/eve/src/setup/integrations/web/setup.ts
index baf155f52..e8e7a5aeb 100644
--- a/packages/eve/src/setup/integrations/web/setup.ts
+++ b/packages/eve/src/setup/integrations/web/setup.ts
@@ -1,17 +1,27 @@
-import { readFile } from "node:fs/promises";
import { join } from "node:path";
-import { resolveEveProjectContext } from "#internal/project-context.js";
import { select } from "#setup/ask.js";
import type { RegistrySetupCompletion } from "#setup/registry-setup-protocol.js";
import type { VercelProjectReference } from "#setup/project-resolution.js";
+import type { PackageManagerKind } from "#setup/package-manager.js";
+import { WEB_APP_TANSTACK_TEMPLATE_FILES } from "#setup/scaffold/create/web-template.js";
import { installScaffoldDependencies } from "../shared/scaffold.js";
import { prepareWebAuthScaffold } from "./auth-scaffold.js";
import { WEB_AUTHENTICATION_QUESTION } from "./auth-options.js";
+import {
+ detectWebChatFramework,
+ WEB_CHAT_FRAMEWORK_LABELS,
+ type WebChatFramework,
+} from "./framework.js";
+import {
+ defaultWebChatHostingDeps,
+ peerServiceVercelConfig,
+ prepareWebChatHosting,
+ resolveWebChatProject,
+ runScriptCommand,
+ type WebChatHostingDeps,
+} from "./hosting.js";
import { provisionWebChatAuth } from "./provision-auth.js";
-import { detectPackageManager, type PackageManagerKind } from "#setup/package-manager.js";
-import { pathExists, writeTextFile } from "#setup/scaffold/files.js";
-import { WEB_CHANNEL_TEMPLATES } from "#setup/scaffold/create/web-template.js";
import {
defineSetupIntegration,
type SetupApplyContext,
@@ -33,93 +43,129 @@ const nextConfig: NextConfig = {};
export default nextConfig;
`;
-const PEER_SERVICE_WEB_BUILD_COMMAND = "node ../../node_modules/next/dist/bin/next build";
-const PEER_SERVICE_VERCEL_CONFIG = `import { withEve } from "eve/vercel";
+const REGISTRY_NEXT_CONFIG = `import type { NextConfig } from "next";
+import { withEve } from "eve/next";
-export default await withEve({
- services: {
- web: {
- framework: "nextjs",
- root: "apps/web",
- buildCommand: "${PEER_SERVICE_WEB_BUILD_COMMAND}",
- },
- },
- routes: [
- { src: "^(.*)$", destination: { type: "service", service: "web" } },
+const nextConfig: NextConfig = {};
+
+export default withEve(nextConfig);
+`;
+const NEXT_PEER_SERVICE_VERCEL_CONFIG = peerServiceVercelConfig(
+ "nextjs",
+ "node ../../node_modules/next/dist/bin/next build",
+);
+const LEGACY_NEXT_PEER_SERVICE_VERCEL_CONFIG = NEXT_PEER_SERVICE_VERCEL_CONFIG.replace(
+ / web: \{[^}]+\},/,
+ ' web: { framework: "nextjs", root: "apps/web" },',
+);
+
+const TANSTACK_REGISTRY_VITE_CONFIG = WEB_APP_TANSTACK_TEMPLATE_FILES["vite.config.ts"];
+const TANSTACK_HOSTED_VITE_CONFIG = `import { tanstackStart } from "@tanstack/react-start/plugin/vite";
+import tailwindcss from "@tailwindcss/vite";
+import viteReact from "@vitejs/plugin-react";
+import { eveTanStack } from "eve/tanstack";
+import { nitro } from "nitro/vite";
+import { fileURLToPath } from "node:url";
+import { defineConfig } from "vite";
+
+const eveRoot = fileURLToPath(new URL("../..", import.meta.url));
+
+export default defineConfig({
+ resolve: { tsconfigPaths: true },
+ plugins: [
+ eveTanStack({ eveRoot }),
+ tailwindcss(),
+ tanstackStart({ srcDirectory: "app" }),
+ viteReact(),
+ nitro(),
],
});
`;
+const TANSTACK_PEER_SERVICE_VERCEL_CONFIG = peerServiceVercelConfig(
+ "tanstack-start",
+ "node ../../node_modules/vite/bin/vite.js build",
+);
+
+/** Every `vercel.ts` the installer has written, so switching frameworks may replace it. */
+const INSTALLER_VERCEL_CONFIGS = [
+ NEXT_PEER_SERVICE_VERCEL_CONFIG,
+ LEGACY_NEXT_PEER_SERVICE_VERCEL_CONFIG,
+ TANSTACK_PEER_SERVICE_VERCEL_CONFIG,
+];
-export interface WebSetupDeps {
- detectPackageManager: typeof detectPackageManager;
- pathExists: typeof pathExists;
- readTextFile(path: string): Promise<string>;
- resolveEveProjectContext: typeof resolveEveProjectContext;
- writeTextFile: typeof writeTextFile;
+export interface WebSetupDeps extends WebChatHostingDeps {
prepareWebAuthScaffold: typeof prepareWebAuthScaffold;
provisionWebChatAuth: typeof provisionWebChatAuth;
installScaffoldDependencies: typeof installScaffoldDependencies;
}
-const defaultDeps: WebSetupDeps = {
- detectPackageManager,
- pathExists,
- readTextFile: (path) => readFile(path, "utf8"),
- resolveEveProjectContext,
- writeTextFile,
+const defaultWebSetupDeps: WebSetupDeps = {
+ ...defaultWebChatHostingDeps,
prepareWebAuthScaffold,
provisionWebChatAuth,
installScaffoldDependencies,
};
interface WebSetupPlan {
- hosting: "next" | "vercel";
+ framework: WebChatFramework;
+ hosting: WebChatFramework | "vercel";
packageManager: PackageManagerKind;
authProject?: VercelProjectReference;
rootWebChat?: boolean;
}
+function hostingQuestion(framework: WebChatFramework) {
+ const label = WEB_CHAT_FRAMEWORK_LABELS[framework];
+ return select<WebChatFramework | "vercel">({
+ key: "web-hosting",
+ message: "How should Web Chat and your agents be deployed?",
+ options: [
+ {
+ id: "vercel",
+ label: "Vercel services",
+ hint: "(Recommended) Web Chat and agents deploy as separate services.",
+ value: "vercel",
+ },
+ {
+ id: framework,
+ label,
+ hint: `One ${label} app serves Web Chat and routes agent requests.`,
+ value: framework,
+ },
+ ],
+ recommended: "vercel",
+ required: true,
+ });
+}
+
export async function prepareWebSetup(
context: SetupPrepareContext,
- deps: WebSetupDeps = defaultDeps,
+ deps: WebSetupDeps = defaultWebSetupDeps,
): Promise<WebSetupPlan> {
- const project = await deps.resolveEveProjectContext(context.appRoot);
- if (project.kind === "workspace") {
- throw new Error("Web Chat setup requires a selected workspace agent.");
- }
+ const project = await resolveWebChatProject(context.appRoot, deps);
+ // `eve add channel/web` installed the framework's files, so they decide it.
+ const framework =
+ (await detectWebChatFramework(join(project.environmentRoot, "apps", "web"), deps.pathExists)) ??
+ "next";
const rootWebChat =
+ framework === "next" &&
(await deps.pathExists(join(project.environmentRoot, "app", "eve-agent.ts"))) &&
!(await deps.pathExists(join(project.environmentRoot, "apps", "web", "app", "eve-agent.ts")));
+ // `eveTanStack()` mounts one agent, so a TanStack workspace member deploys as a peer service.
const hosting = rootWebChat
? "next"
- : await context.asker.ask(
- select({
- key: "web-hosting",
- message: "How should Web Chat and your agents be deployed?",
- options: [
- {
- id: "vercel",
- label: "Vercel services",
- hint: "(Recommended) Web Chat and agents deploy as separate services.",
- value: "vercel" as const,
- },
- {
- id: "next",
- label: "Next.js",
- hint: "One Next.js app serves Web Chat and routes agent requests.",
- value: "next" as const,
- },
- ],
- recommended: "vercel" as const,
- required: true,
- }),
- );
- const authentication = await context.asker.ask(WEB_AUTHENTICATION_QUESTION);
+ : framework === "tanstack" && project.agentName !== undefined
+ ? "vercel"
+ : await context.asker.ask(hostingQuestion(framework));
+ // Sign in with Vercel ships as Next.js files.
+ const authentication =
+ framework === "next" ? await context.asker.ask(WEB_AUTHENTICATION_QUESTION) : "custom";
const authProject =
authentication === "vercel"
? await context.resolveVercelProject("Web Chat sign-in")
: undefined;
const plan: WebSetupPlan = {
+ framework,
hosting,
packageManager: (await deps.detectPackageManager(project.environmentRoot)).kind,
};
@@ -128,59 +174,29 @@ export async function prepareWebSetup(
return plan;
}
-function runScriptCommand(packageManager: PackageManagerKind, script: string): string {
- switch (packageManager) {
- case "npm":
- return `npm run ${script}`;
- case "pnpm":
- return `pnpm ${script}`;
- case "yarn":
- return `yarn ${script}`;
- case "bun":
- return `bun run ${script}`;
+function hostConfig(plan: WebSetupPlan, webRoot: string) {
+ const vercelServices = plan.hosting === "vercel";
+ if (plan.framework === "tanstack") {
+ return {
+ path: join(webRoot, "vite.config.ts"),
+ source: vercelServices ? TANSTACK_REGISTRY_VITE_CONFIG : TANSTACK_HOSTED_VITE_CONFIG,
+ owned: [TANSTACK_REGISTRY_VITE_CONFIG, TANSTACK_HOSTED_VITE_CONFIG],
+ };
}
-}
-
-async function configurePeerServiceScripts(root: string, deps: WebSetupDeps): Promise<void> {
- const path = join(root, "package.json");
- const document = JSON.parse(await deps.readTextFile(path)) as {
- scripts?: Record<string, string>;
- [key: string]: unknown;
+ const hostedNextConfig = plan.rootWebChat ? REGISTRY_NEXT_CONFIG : NEXT_HOSTED_CONFIG;
+ return {
+ path: join(webRoot, "next.config.ts"),
+ source: vercelServices ? PEER_SERVICE_NEXT_CONFIG : hostedNextConfig,
+ owned: [REGISTRY_NEXT_CONFIG, NEXT_HOSTED_CONFIG, PEER_SERVICE_NEXT_CONFIG],
};
- const scripts = { ...document.scripts };
- scripts.dev ??= "eve dev";
- scripts["dev:eve"] ??= "eve dev";
- scripts["dev:all"] ??= "vercel dev --local";
- await deps.writeTextFile(path, `${JSON.stringify({ ...document, scripts }, null, 2)}\n`, {
- force: true,
- });
-}
-
-async function assertInstallerOwned(path: string, allowed: readonly string[]): Promise<void> {
- try {
- const source = await readFile(path, "utf8");
- if (allowed.includes(source)) return;
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
- throw error;
- }
- throw new Error(
- `Could not configure Web Chat because ${path} contains authored configuration. Preserve it and compose the eve integration manually.`,
- );
}
export async function applyWebSetup(
plan: WebSetupPlan,
context: SetupApplyContext,
- deps: WebSetupDeps = defaultDeps,
+ deps: WebSetupDeps = defaultWebSetupDeps,
) {
- const project = await deps.resolveEveProjectContext(context.appRoot);
- if (project.kind === "workspace") {
- throw new Error("Web Chat setup requires a selected workspace agent.");
- }
- const agentAppRoot =
- project.kind === "workspace-member" ? project.member.appRoot : project.appRoot;
- const channelPath = join(agentAppRoot, "agent", "channels", "eve.ts");
+ const project = await resolveWebChatProject(context.appRoot, deps);
const webRoot = plan.rootWebChat
? project.environmentRoot
: join(project.environmentRoot, "apps", "web");
@@ -189,62 +205,32 @@ export async function applyWebSetup(
? undefined
: await deps.prepareWebAuthScaffold({
environmentRoot: project.environmentRoot,
- agentAppRoot,
+ agentAppRoot: project.agentAppRoot,
webRoot,
force: context.force,
});
- if (writeAuth === undefined && (context.force || !(await deps.pathExists(channelPath)))) {
- await deps.writeTextFile(channelPath, WEB_CHANNEL_TEMPLATES.default, {
+ const vercelServices = plan.hosting === "vercel";
+ const vercelConfig =
+ plan.framework === "tanstack"
+ ? TANSTACK_PEER_SERVICE_VERCEL_CONFIG
+ : NEXT_PEER_SERVICE_VERCEL_CONFIG;
+ const writeHosting = await prepareWebChatHosting(
+ {
+ project,
+ webRoot,
force: context.force,
- });
- }
- const agentName = project.kind === "workspace-member" ? project.member.name : undefined;
- await deps.writeTextFile(
- join(webRoot, "app", "eve-agent.ts"),
- `/** Named workspace agent selected by the Web Chat installer. */\nexport const WEB_CHAT_AGENT: string | undefined = ${agentName === undefined ? "undefined" : JSON.stringify(agentName)};\n`,
- { force: true },
+ writeChannel: writeAuth === undefined,
+ hostConfig: hostConfig(plan, webRoot),
+ vercelServices,
+ vercelConfigs: [
+ vercelConfig,
+ ...INSTALLER_VERCEL_CONFIGS.filter((config) => config !== vercelConfig),
+ ],
+ },
+ deps,
);
- const nextConfigPath = join(webRoot, "next.config.ts");
- const registryNextConfig = `import type { NextConfig } from "next";
-import { withEve } from "eve/next";
-
-const nextConfig: NextConfig = {};
-
-export default withEve(nextConfig);
-`;
- await assertInstallerOwned(nextConfigPath, [
- registryNextConfig,
- NEXT_HOSTED_CONFIG,
- PEER_SERVICE_NEXT_CONFIG,
- ]);
- let startScript: string;
- if (plan.hosting === "vercel") {
- const vercelTsPath = join(project.environmentRoot, "vercel.ts");
- const vercelJsonPath = join(project.environmentRoot, "vercel.json");
- await assertInstallerOwned(vercelTsPath, [
- PEER_SERVICE_VERCEL_CONFIG,
- PEER_SERVICE_VERCEL_CONFIG.replace(
- / web: \{[^}]+\},/,
- ' web: { framework: "nextjs", root: "apps/web" },',
- ),
- ]);
- if (await deps.pathExists(vercelJsonPath)) {
- throw new Error(
- `Could not configure Vercel services because ${vercelJsonPath} already exists. Preserve it and compose eve/vercel manually.`,
- );
- }
- await deps.writeTextFile(nextConfigPath, PEER_SERVICE_NEXT_CONFIG, { force: true });
- await deps.writeTextFile(vercelTsPath, PEER_SERVICE_VERCEL_CONFIG, { force: true });
- await configurePeerServiceScripts(project.environmentRoot, deps);
- startScript = "dev:all";
- } else {
- await deps.writeTextFile(
- nextConfigPath,
- plan.rootWebChat ? registryNextConfig : NEXT_HOSTED_CONFIG,
- { force: true },
- );
- startScript = plan.rootWebChat ? "dev" : "dev:web";
- }
+ await writeHosting();
+ const startScript = vercelServices ? "dev:all" : plan.rootWebChat ? "dev" : "dev:web";
if (plan.authProject !== undefined && writeAuth !== undefined) {
await deps.provisionWebChatAuth(plan.authProject, context.signal);
context.signal?.throwIfAborted();
diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.ts
index 66882c236..adb546a8d 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 // Next patches window.history to navigate, which would detach the active stream.\n History.prototype.replaceState.call(\n window.history,\n window.history.state,\n "",\n `/s/${encodeURIComponent(session.sessionId)}`,\n );\n }\n },\n });\n\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isResuming = agent.status === "resuming";\n const isEmpty = agent.data.messages.length === 0;\n const lastMessage = agent.data.messages.at(-1);\n const isPendingAssistantShell =\n lastMessage?.role === "assistant" &&\n lastMessage.parts.every((part) => part.type === "step-start");\n const showPendingThinking =\n isBusy &&\n (agent.status === "submitted" || lastMessage?.role !== "assistant" || isPendingAssistantShell);\n const turnFailure = isBusy || isResuming ? undefined : getLatestTurnFailure(agent.events);\n const errorMessage = cancellationError ?? agent.error?.message ?? turnFailure;\n const hasConversationContent = sessionless || !isEmpty || errorMessage !== undefined;\n const showConversationLayout = isResuming || hasConversationContent;\n const activeSessionId = sessionId ?? agent.session?.sessionId;\n // 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 { 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',
"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":
@@ -11,7 +11,7 @@ export const WEB_APP_TEMPLATE_FILES = {
"app/eve-agent.ts":
'/** Named workspace agent selected by the Web Chat installer. */\nexport const WEB_CHAT_AGENT: string | undefined = undefined;\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 -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\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',
+ '@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}\n\n/* Not inline: font utilities must read the variables so each host\'s font loader can override them. */\n@theme {\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 -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\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/icon.svg":
'<svg width="102" height="102" viewBox="0 0 102 102" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path fill="#000" d="M0 0h102v102H0z" />\n <path\n fill="#fff"\n d="M49.28 66.94 75.03 34.96h-6.89L47.91 60.11l-5.49 6.83h6.86ZM0 34.96h42.4v5.11H0zm0 13.32h27.66v5.11H0zm0 13.54h27.66v5.11H0zm69.63-26.86H102v5.11H69.63zm4.71 13.32H102v5.11H74.34zm0 13.54H102v5.11H74.34z"\n />\n</svg>\n',
"app/layout.tsx":
@@ -113,6 +113,13 @@ export const WEB_APP_SIGN_IN_WITH_VERCEL_TEMPLATE_FILES = {
'import { betterAuth } from "better-auth";\n\nconst SESSION_MAX_AGE_SECONDS = 8 * 60 * 60;\nconst DEVELOPMENT_ALLOWED_HOSTS = ["localhost:*", "127.0.0.1:*"];\n\nfunction getAllowedHosts(): string[] {\n if (process.env.NODE_ENV === "development") {\n return DEVELOPMENT_ALLOWED_HOSTS;\n }\n const deploymentHosts = [\n process.env.VERCEL_URL,\n process.env.VERCEL_BRANCH_URL,\n process.env.VERCEL_PROJECT_PRODUCTION_URL,\n ].filter((host): host is string => Boolean(host));\n if (deploymentHosts.length === 0) {\n throw new Error("No trusted deployment hosts are configured");\n }\n return Array.from(new Set(deploymentHosts));\n}\n\nfunction requireEnvironmentVariable(name: string): string {\n const value = process.env[name];\n if (value) return value;\n if (process.env.NODE_ENV === "development") return `development-${name}`;\n throw new Error(`Missing required environment variable: ${name}`);\n}\n\nexport const auth = betterAuth({\n baseURL: {\n allowedHosts: getAllowedHosts(),\n protocol: process.env.NODE_ENV === "development" ? "auto" : "https",\n },\n secret: requireEnvironmentVariable("BETTER_AUTH_SECRET"),\n session: {\n expiresIn: SESSION_MAX_AGE_SECONDS,\n disableSessionRefresh: true,\n cookieCache: {\n enabled: true,\n maxAge: SESSION_MAX_AGE_SECONDS,\n refreshCache: false,\n strategy: "jwe",\n },\n },\n socialProviders: {\n vercel: {\n clientId: requireEnvironmentVariable("VERCEL_APP_CLIENT_ID"),\n clientSecret: requireEnvironmentVariable("VERCEL_APP_CLIENT_SECRET"),\n scope: ["openid", "email", "profile"],\n },\n },\n});\n',
} as const;
+export const WEB_APP_TANSTACK_TEMPLATE_FILES = {
+ "tsconfig.json":
+ '{\n "$schema": "https://json.schemastore.org/tsconfig",\n "compilerOptions": {\n "target": "ES2022",\n "lib": ["dom", "dom.iterable", "esnext"],\n "skipLibCheck": true,\n "strict": true,\n "noEmit": true,\n "esModuleInterop": true,\n "module": "esnext",\n "moduleResolution": "Bundler",\n "resolveJsonModule": true,\n "isolatedModules": true,\n "jsx": "react-jsx",\n "types": ["vite/client"],\n "paths": {\n "@/*": ["./*"]\n }\n },\n "include": ["**/*.ts", "**/*.tsx"],\n "exclude": ["node_modules", ".output", ".vercel"]\n}\n',
+ "vite.config.ts":
+ 'import { tanstackStart } from "@tanstack/react-start/plugin/vite";\nimport tailwindcss from "@tailwindcss/vite";\nimport viteReact from "@vitejs/plugin-react";\nimport { nitro } from "nitro/vite";\nimport { defineConfig } from "vite";\n\nexport default defineConfig({\n resolve: { tsconfigPaths: true },\n plugins: [tailwindcss(), tanstackStart({ srcDirectory: "app" }), viteReact(), nitro()],\n});\n',
+} as const;
+
export const WEB_APP_TEMPLATE_PACKAGE_JSON = {
scripts: {
build: "next build",
diff --git a/packages/eve/test/scenarios/registry-channel-web-tanstack.scenario.test.ts b/packages/eve/test/scenarios/registry-channel-web-tanstack.scenario.test.ts
new file mode 100644
index 000000000..78db9b400
--- /dev/null
+++ b/packages/eve/test/scenarios/registry-channel-web-tanstack.scenario.test.ts
@@ -0,0 +1,99 @@
+import { readdir, readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { describe, expect, it } from "vitest";
+
+import {
+ type ScenarioAppDescriptor,
+ useScenarioApp,
+} from "../../src/internal/testing/scenario-app.js";
+import { runPnpmCommand } from "../../src/internal/testing/run-pnpm-command.js";
+
+const REGISTRY_ROOT = fileURLToPath(new URL("../../../../apps/docs/", import.meta.url));
+const WEB_ROOT = "apps/web";
+
+const scenarioApp = useScenarioApp();
+
+interface RegistryItem {
+ readonly name: string;
+ readonly dependencies?: readonly string[];
+ readonly devDependencies?: readonly string[];
+ readonly files: readonly { readonly path: string; readonly target: string }[];
+}
+
+function dependencyRecord(specifiers: readonly string[]): Record<string, string> {
+ return Object.fromEntries(
+ specifiers.map((specifier) => {
+ const separator = specifier.lastIndexOf("@");
+ if (separator <= 0) throw new Error(`Registry dependency ${specifier} has no version.`);
+ return [specifier.slice(0, separator), specifier.slice(separator + 1)];
+ }),
+ );
+}
+
+/** The `channel/web-tanstack` item as `eve add channel/web` installs it, in Vercel services hosting. */
+async function createChannelTanStackDescriptor(): Promise<ScenarioAppDescriptor> {
+ const registry = JSON.parse(await readFile(join(REGISTRY_ROOT, "registry.json"), "utf8")) as {
+ readonly items: readonly RegistryItem[];
+ };
+ const item = registry.items.find((candidate) => candidate.name === "channel/web-tanstack");
+ if (item === undefined || item.files.length === 0) {
+ throw new Error("apps/docs/registry.json must define channel/web-tanstack with files.");
+ }
+
+ const files: Record<string, string> = {
+ // Written by `eve integration setup web`, not the registry item.
+ [`${WEB_ROOT}/app/eve-agent.ts`]:
+ "export const WEB_CHAT_AGENT: string | undefined = undefined;\n",
+ "pnpm-workspace.yaml": "minimumReleaseAge: 0\n",
+ };
+ for (const file of item.files) {
+ files[file.target] = await readFile(join(REGISTRY_ROOT, file.path), "utf8");
+ }
+
+ return {
+ dependencies: {
+ ...dependencyRecord(item.dependencies ?? []),
+ ...dependencyRecord(item.devDependencies ?? []),
+ },
+ files,
+ installDependencies: true,
+ name: "channel-web-tanstack",
+ };
+}
+
+async function readBuiltCss(appRoot: string): Promise<string> {
+ const assetsRoot = join(appRoot, WEB_ROOT, ".output", "public", "assets");
+ const stylesheets = (await readdir(assetsRoot)).filter((entry) => entry.endsWith(".css"));
+ if (stylesheets.length === 0) throw new Error(`Expected CSS assets in ${assetsRoot}.`);
+ const sources = await Promise.all(
+ stylesheets.map((entry) => readFile(join(assetsRoot, entry), "utf8")),
+ );
+ return sources.join("\n");
+}
+
+describe("registry channel/web-tanstack", () => {
+ it("builds and typechecks the installed TanStack Start Web Chat app", async () => {
+ const app = await scenarioApp(await createChannelTanStackDescriptor());
+
+ // The item's `build:web` script. `NITRO_PRESET` keeps the output under
+ // `.output/` even when CI or Vercel provider detection would pick another preset.
+ await runPnpmCommand({
+ args: ["exec", "vite", "build", WEB_ROOT],
+ cwd: app.appRoot,
+ env: { ...process.env, NITRO_PRESET: "node-server" },
+ });
+ // Runs after the build, which generates `app/routeTree.gen.ts`.
+ await runPnpmCommand({
+ args: ["exec", "tsc", "-p", WEB_ROOT],
+ cwd: app.appRoot,
+ });
+
+ // Font utilities must read the variables so `fonts.css` can swap in the
+ // Fontsource families; inlined theme values would hardcode "Geist Mono".
+ const css = await readBuiltCss(app.appRoot);
+ expect(css).toContain(".font-sans{font-family:var(--font-sans)}");
+ expect(css).toContain(".font-mono{font-family:var(--font-mono)}");
+ }, 300_000);
+});
diff --git a/packages/eve/test/scenarios/web-chat-service-build.scenario.test.ts b/packages/eve/test/scenarios/web-chat-service-build.scenario.test.ts
index 4022afab4..10f013ee9 100644
--- a/packages/eve/test/scenarios/web-chat-service-build.scenario.test.ts
+++ b/packages/eve/test/scenarios/web-chat-service-build.scenario.test.ts
@@ -49,7 +49,10 @@ it("builds the generated Web Chat service with pnpm dependencies installed only
prompter: createFakePrompter().prompter,
resolveVercelProject: async () => ({ orgId: "team", projectId: "project" }),
});
- await applyWebSetup({ hosting: "vercel", packageManager: "pnpm" }, contexts.apply);
+ await applyWebSetup(
+ { framework: "next", hosting: "vercel", packageManager: "pnpm" },
+ contexts.apply,
+ );
const configured = await runFile(
process.execPath,
[