From 91a257bf96cf6c5882474586e6a18acc2ee58e8d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 00:42:23 +0000 Subject: [PATCH] VC1: the apps on Workers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The v0 SDK example's two apps, each its own Cloudflare Worker per environment through @opennextjs/cloudflare: apps/web (the host — the chat UI, its server routes and the preview iframe) and apps/preview (upstream's apps/preview-proxy, the preview proxy on an origin of its own, so generated code never runs on the host's). What Vercel supplied around them is replaced: - Related Projects told each app the other's URL. Each build is now told it instead: NEXT_PUBLIC_V0_PREVIEW_PROXY_URL and NEXT_PUBLIC_V0_CLONE_ORIGIN are inlined at build (the environment's override when set, else the sibling Worker's workers.dev URL — wired in VC3), and `next dev` still gets localhost:3000/3001 as upstream does. Origins are validated as before; plain HTTP is allowed on loopback only. - Vercel OIDC, the fallback credential, has no Cloudflare equivalent and is left out: the key is V0_API_KEY (optional), else the visitor's own, saved through the dialog into an HTTP-only cookie on each origin. - V0_API_BASE_URL (unset in a product) points the v0 calls at another origin with the same paths — the stand-in v0 API the e2e serves. Also: a health route per app for the deploy's smoke (it names the other app's origin, and whether a server key is set, never its value); pnpm 10 + Node 22 and the reference's lint; Next 16.2.4 → 16.3.8 (the reference's OpenNext-tested version); the cookie and storage keys no longer carry the example's name. Upstream's bun tests run under vitest in tests/web, with new tests in tests/web and tests/preview for the origins, health, the proxy's key route (CORS from the host only), trusted preview hosts, the same-origin seam and the v0 fetch override: 43 + 19 green. Both Workers fit Workers Free (web 2,173 KiB, preview 1,600 KiB gzipped). Under wrangler dev, against a stand-in v0 API: both serve with no key, the host's dialog validates a key, the proxy accepts it only from the host's origin, and a chat's preview is served through the proxy with v0's token. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_019PcpNVpFBcbeiX3EHdXfmn --- apps/preview/.dev.vars.example | 6 + apps/preview/LICENSE | 13 + apps/preview/app/api/api-key/route.ts | 100 + apps/preview/app/api/health/route.ts | 19 + .../v0-preview/[chatId]/[[...path]]/route.ts | 23 + .../api/v0-preview/[chatId]/loading/route.ts | 59 + apps/preview/app/layout.tsx | 14 + apps/preview/app/page.tsx | 100 + apps/preview/cloudflare-env.d.ts | 10 + apps/preview/eslint.config.mjs | 9 + apps/preview/lib/authorize.ts | 14 + apps/preview/lib/origins.ts | 41 + apps/preview/lib/preview.ts | 54 + apps/preview/lib/trusted-host.ts | 88 + apps/preview/lib/v0-client.ts | 32 + apps/preview/lib/v0-fetch.ts | 16 + apps/preview/next.config.mjs | 25 + apps/preview/open-next.config.ts | 16 + apps/preview/package.json | 31 + apps/preview/proxy.ts | 24 + apps/preview/tsconfig.json | 46 + apps/preview/turbo.json | 22 + apps/preview/wrangler.jsonc | 20 + apps/web/.dev.vars.example | 6 + apps/web/LICENSE | 13 + .../app/api/chats/[chatId]/deploy/route.ts | 30 + .../api/chats/[chatId]/design-mode/route.ts | 24 + .../app/api/chats/[chatId]/download/route.ts | 15 + .../app/api/chats/[chatId]/duplicate/route.ts | 22 + .../web/app/api/chats/[chatId]/files/route.ts | 34 + .../messages/[messageId]/stop/route.ts | 15 + .../app/api/chats/[chatId]/messages/route.ts | 45 + .../app/api/chats/[chatId]/project/route.ts | 19 + .../app/api/chats/[chatId]/resolve/route.ts | 24 + .../app/api/chats/[chatId]/restore/route.ts | 24 + .../app/api/chats/[chatId]/resume/route.ts | 11 + apps/web/app/api/chats/[chatId]/route.ts | 34 + apps/web/app/api/chats/import/files/route.ts | 25 + apps/web/app/api/chats/import/repo/route.ts | 29 + apps/web/app/api/chats/import/zip/route.ts | 25 + apps/web/app/api/chats/route.ts | 62 + apps/web/app/api/health/route.ts | 19 + apps/web/app/api/settings/api-key/route.ts | 61 + apps/web/app/chats/[chatId]/page.tsx | 30 + apps/web/app/globals.css | 150 + apps/web/app/icon.svg | 26 + apps/web/app/layout.tsx | 50 + apps/web/app/page.tsx | 5 + apps/web/cloudflare-env.d.ts | 10 + apps/web/components.json | 25 + apps/web/components/ai-elements/loader.tsx | 85 + apps/web/components/ai-elements/message.tsx | 367 + .../components/ai-elements/prompt-input.tsx | 1256 ++ apps/web/components/ai-elements/response.tsx | 23 + .../components/ai-elements/web-preview.tsx | 233 + .../web/components/chat/chat-conversation.tsx | 279 + apps/web/components/chat/chat-header.tsx | 258 + apps/web/components/chat/chat-workspace.tsx | 120 + apps/web/components/chat/code-editor.tsx | 167 + .../web/components/chat/conversation-view.tsx | 157 + apps/web/components/chat/message-parts.tsx | 300 + apps/web/components/chat/task-resolution.tsx | 442 + apps/web/components/home/home-client.tsx | 280 + apps/web/components/layout/api-key-dialog.tsx | 173 + apps/web/components/layout/app-shell.tsx | 60 + apps/web/components/layout/chat-item.tsx | 199 + apps/web/components/layout/sidebar.tsx | 261 + apps/web/components/preview/preview-pane.tsx | 227 + .../preview/preview-proxy-provider.tsx | 23 + apps/web/components/prompt-box.tsx | 124 + apps/web/components/ui/badge.tsx | 46 + apps/web/components/ui/button-group.tsx | 78 + apps/web/components/ui/button.tsx | 62 + apps/web/components/ui/collapsible.tsx | 21 + apps/web/components/ui/command.tsx | 161 + apps/web/components/ui/dialog.tsx | 144 + apps/web/components/ui/dropdown-menu.tsx | 228 + apps/web/components/ui/hover-card.tsx | 38 + apps/web/components/ui/icons.tsx | 90 + apps/web/components/ui/input-group.tsx | 158 + apps/web/components/ui/input.tsx | 21 + apps/web/components/ui/label.tsx | 21 + apps/web/components/ui/scroll-area.tsx | 56 + apps/web/components/ui/select.tsx | 175 + apps/web/components/ui/separator.tsx | 28 + apps/web/components/ui/textarea.tsx | 18 + apps/web/components/ui/tooltip.tsx | 53 + apps/web/eslint.config.mjs | 24 + apps/web/lib/api-key-client.ts | 55 + apps/web/lib/design-mode-message.ts | 64 + apps/web/lib/hooks/useSettings.ts | 83 + apps/web/lib/icons.ts | 52 + apps/web/lib/preview-proxy.ts | 50 + apps/web/lib/proxy.ts | 14 + apps/web/lib/sidebar-chats.ts | 50 + apps/web/lib/utils.ts | 6 + apps/web/lib/v0-client.ts | 32 + apps/web/lib/v0-fetch.ts | 16 + apps/web/lib/v0-response.ts | 11 + apps/web/lib/vercel.ts | 39 + apps/web/next.config.mjs | 25 + apps/web/open-next.config.ts | 16 + apps/web/package.json | 48 + apps/web/postcss.config.mjs | 5 + apps/web/public/acme-logo.svg | 12 + apps/web/tsconfig.json | 46 + apps/web/turbo.json | 22 + apps/web/wrangler.jsonc | 20 + pnpm-lock.yaml | 11194 +++++++++++++++- tests/preview/eslint.config.js | 2 + tests/preview/package.json | 25 + tests/preview/src/api-key.test.ts | 63 + tests/preview/src/health.test.ts | 29 + tests/preview/src/origins.test.ts | 25 + tests/preview/src/stubs/server-only.ts | 1 + tests/preview/src/trusted-host.test.ts | 46 + tests/preview/src/v0-fetch.test.ts | 38 + tests/preview/tsconfig.json | 33 + tests/preview/vitest.config.ts | 17 + tests/web/eslint.config.js | 2 + tests/web/package.json | 28 + tests/web/src/design-mode-message.test.tsx | 173 + tests/web/src/design-mode-route.test.ts | 154 + tests/web/src/design-mode-stream.ts | 46 + tests/web/src/health.test.ts | 29 + tests/web/src/origins.test.ts | 31 + tests/web/src/preview-design-mode.test.tsx | 374 + tests/web/src/same-origin.test.ts | 13 + tests/web/src/stubs/server-only.ts | 1 + tests/web/src/v0-fetch.test.ts | 38 + tests/web/tsconfig.json | 34 + tests/web/vitest.config.ts | 19 + 132 files changed, 20538 insertions(+), 614 deletions(-) create mode 100644 apps/preview/.dev.vars.example create mode 100644 apps/preview/LICENSE create mode 100644 apps/preview/app/api/api-key/route.ts create mode 100644 apps/preview/app/api/health/route.ts create mode 100644 apps/preview/app/api/v0-preview/[chatId]/[[...path]]/route.ts create mode 100644 apps/preview/app/api/v0-preview/[chatId]/loading/route.ts create mode 100644 apps/preview/app/layout.tsx create mode 100644 apps/preview/app/page.tsx create mode 100644 apps/preview/cloudflare-env.d.ts create mode 100644 apps/preview/eslint.config.mjs create mode 100644 apps/preview/lib/authorize.ts create mode 100644 apps/preview/lib/origins.ts create mode 100644 apps/preview/lib/preview.ts create mode 100644 apps/preview/lib/trusted-host.ts create mode 100644 apps/preview/lib/v0-client.ts create mode 100644 apps/preview/lib/v0-fetch.ts create mode 100644 apps/preview/next.config.mjs create mode 100644 apps/preview/open-next.config.ts create mode 100644 apps/preview/package.json create mode 100644 apps/preview/proxy.ts create mode 100644 apps/preview/tsconfig.json create mode 100644 apps/preview/turbo.json create mode 100644 apps/preview/wrangler.jsonc create mode 100644 apps/web/.dev.vars.example create mode 100644 apps/web/LICENSE create mode 100644 apps/web/app/api/chats/[chatId]/deploy/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/design-mode/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/download/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/duplicate/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/files/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/messages/[messageId]/stop/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/messages/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/project/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/resolve/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/restore/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/resume/route.ts create mode 100644 apps/web/app/api/chats/[chatId]/route.ts create mode 100644 apps/web/app/api/chats/import/files/route.ts create mode 100644 apps/web/app/api/chats/import/repo/route.ts create mode 100644 apps/web/app/api/chats/import/zip/route.ts create mode 100644 apps/web/app/api/chats/route.ts create mode 100644 apps/web/app/api/health/route.ts create mode 100644 apps/web/app/api/settings/api-key/route.ts create mode 100644 apps/web/app/chats/[chatId]/page.tsx create mode 100644 apps/web/app/globals.css create mode 100644 apps/web/app/icon.svg create mode 100644 apps/web/app/layout.tsx create mode 100644 apps/web/app/page.tsx create mode 100644 apps/web/cloudflare-env.d.ts create mode 100644 apps/web/components.json create mode 100644 apps/web/components/ai-elements/loader.tsx create mode 100644 apps/web/components/ai-elements/message.tsx create mode 100644 apps/web/components/ai-elements/prompt-input.tsx create mode 100644 apps/web/components/ai-elements/response.tsx create mode 100644 apps/web/components/ai-elements/web-preview.tsx create mode 100644 apps/web/components/chat/chat-conversation.tsx create mode 100644 apps/web/components/chat/chat-header.tsx create mode 100644 apps/web/components/chat/chat-workspace.tsx create mode 100644 apps/web/components/chat/code-editor.tsx create mode 100644 apps/web/components/chat/conversation-view.tsx create mode 100644 apps/web/components/chat/message-parts.tsx create mode 100644 apps/web/components/chat/task-resolution.tsx create mode 100644 apps/web/components/home/home-client.tsx create mode 100644 apps/web/components/layout/api-key-dialog.tsx create mode 100644 apps/web/components/layout/app-shell.tsx create mode 100644 apps/web/components/layout/chat-item.tsx create mode 100644 apps/web/components/layout/sidebar.tsx create mode 100644 apps/web/components/preview/preview-pane.tsx create mode 100644 apps/web/components/preview/preview-proxy-provider.tsx create mode 100644 apps/web/components/prompt-box.tsx create mode 100644 apps/web/components/ui/badge.tsx create mode 100644 apps/web/components/ui/button-group.tsx create mode 100644 apps/web/components/ui/button.tsx create mode 100644 apps/web/components/ui/collapsible.tsx create mode 100644 apps/web/components/ui/command.tsx create mode 100644 apps/web/components/ui/dialog.tsx create mode 100644 apps/web/components/ui/dropdown-menu.tsx create mode 100644 apps/web/components/ui/hover-card.tsx create mode 100644 apps/web/components/ui/icons.tsx create mode 100644 apps/web/components/ui/input-group.tsx create mode 100644 apps/web/components/ui/input.tsx create mode 100644 apps/web/components/ui/label.tsx create mode 100644 apps/web/components/ui/scroll-area.tsx create mode 100644 apps/web/components/ui/select.tsx create mode 100644 apps/web/components/ui/separator.tsx create mode 100644 apps/web/components/ui/textarea.tsx create mode 100644 apps/web/components/ui/tooltip.tsx create mode 100644 apps/web/eslint.config.mjs create mode 100644 apps/web/lib/api-key-client.ts create mode 100644 apps/web/lib/design-mode-message.ts create mode 100644 apps/web/lib/hooks/useSettings.ts create mode 100644 apps/web/lib/icons.ts create mode 100644 apps/web/lib/preview-proxy.ts create mode 100644 apps/web/lib/proxy.ts create mode 100644 apps/web/lib/sidebar-chats.ts create mode 100644 apps/web/lib/utils.ts create mode 100644 apps/web/lib/v0-client.ts create mode 100644 apps/web/lib/v0-fetch.ts create mode 100644 apps/web/lib/v0-response.ts create mode 100644 apps/web/lib/vercel.ts create mode 100644 apps/web/next.config.mjs create mode 100644 apps/web/open-next.config.ts create mode 100644 apps/web/package.json create mode 100644 apps/web/postcss.config.mjs create mode 100644 apps/web/public/acme-logo.svg create mode 100644 apps/web/tsconfig.json create mode 100644 apps/web/turbo.json create mode 100644 apps/web/wrangler.jsonc create mode 100644 tests/preview/eslint.config.js create mode 100644 tests/preview/package.json create mode 100644 tests/preview/src/api-key.test.ts create mode 100644 tests/preview/src/health.test.ts create mode 100644 tests/preview/src/origins.test.ts create mode 100644 tests/preview/src/stubs/server-only.ts create mode 100644 tests/preview/src/trusted-host.test.ts create mode 100644 tests/preview/src/v0-fetch.test.ts create mode 100644 tests/preview/tsconfig.json create mode 100644 tests/preview/vitest.config.ts create mode 100644 tests/web/eslint.config.js create mode 100644 tests/web/package.json create mode 100644 tests/web/src/design-mode-message.test.tsx create mode 100644 tests/web/src/design-mode-route.test.ts create mode 100644 tests/web/src/design-mode-stream.ts create mode 100644 tests/web/src/health.test.ts create mode 100644 tests/web/src/origins.test.ts create mode 100644 tests/web/src/preview-design-mode.test.tsx create mode 100644 tests/web/src/same-origin.test.ts create mode 100644 tests/web/src/stubs/server-only.ts create mode 100644 tests/web/src/v0-fetch.test.ts create mode 100644 tests/web/tsconfig.json create mode 100644 tests/web/vitest.config.ts diff --git a/apps/preview/.dev.vars.example b/apps/preview/.dev.vars.example new file mode 100644 index 0000000..8a72d46 --- /dev/null +++ b/apps/preview/.dev.vars.example @@ -0,0 +1,6 @@ +# Copy to .dev.vars for `wrangler dev` / `pnpm preview` (never committed). +# +# Optional. Unset, each visitor saves their own v0 key through the app's +# dialog. Set, every visitor shares this key's v0 workspace and credits — +# set the same key on both apps (README, "Connecting v0"). +# V0_API_KEY= diff --git a/apps/preview/LICENSE b/apps/preview/LICENSE new file mode 100644 index 0000000..d9db03e --- /dev/null +++ b/apps/preview/LICENSE @@ -0,0 +1,13 @@ +Copyright 2025 Vercel, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/apps/preview/app/api/api-key/route.ts b/apps/preview/app/api/api-key/route.ts new file mode 100644 index 0000000..3c0cfa8 --- /dev/null +++ b/apps/preview/app/api/api-key/route.ts @@ -0,0 +1,100 @@ +// Demo only: remove browser-provided API key support before using this example in production. +import { cookies } from 'next/headers' +import { createV0Client } from 'v0' +import { v0Fetch } from '@/lib/v0-fetch' +import { getCloneOrigin } from '@/lib/origins' +import { ensureTrustedPreviewHost, TrustedHostError } from '@/lib/trusted-host' +import { V0_PROXY_API_KEY_COOKIE } from '@/lib/v0-client' + +const API_KEY_MAX_AGE = 60 * 60 * 4 + +export async function OPTIONS(request: Request) { + const headers = getCorsHeaders(request) + return new Response(null, { status: headers ? 204 : 403, headers }) +} + +export async function PUT(request: Request) { + const corsHeaders = getCorsHeaders(request) + if (!corsHeaders) return forbiddenResponse() + + if (process.env.V0_API_KEY) { + return Response.json( + { + message: + 'The preview proxy already uses V0_API_KEY. Set it on the web app too, or remove it from the proxy.', + }, + { status: 409, headers: corsHeaders }, + ) + } + + const body = (await request.json().catch(() => null)) as { apiKey?: unknown } | null + const apiKey = typeof body?.apiKey === 'string' ? body.apiKey.trim() : '' + + if (!apiKey) { + return Response.json({ message: 'Enter a v0 API key.' }, { status: 400, headers: corsHeaders }) + } + + const hostname = new URL(request.url).hostname + const client = createV0Client({ auth: apiKey, fetch: v0Fetch }) + + try { + await ensureTrustedPreviewHost(client, hostname) + } catch (error) { + return Response.json( + { + message: + error instanceof Error ? error.message : 'The preview proxy could not be configured.', + }, + { status: error instanceof TrustedHostError ? error.status : 502, headers: corsHeaders }, + ) + } + + const cookieStore = await cookies() + cookieStore.set(V0_PROXY_API_KEY_COOKIE, apiKey, getCookieOptions(API_KEY_MAX_AGE)) + + return Response.json({ configured: true }, { headers: corsHeaders }) +} + +export async function DELETE(request: Request) { + const corsHeaders = getCorsHeaders(request) + if (!corsHeaders) return forbiddenResponse() + + const cookieStore = await cookies() + cookieStore.set(V0_PROXY_API_KEY_COOKIE, '', getCookieOptions(0)) + + return Response.json({ configured: Boolean(process.env.V0_API_KEY) }, { headers: corsHeaders }) +} + +function getCorsHeaders(request: Request) { + const origin = request.headers.get('origin') + if (origin !== getCloneOrigin()) return undefined + + return { + 'Access-Control-Allow-Credentials': 'true', + 'Access-Control-Allow-Headers': 'Content-Type', + 'Access-Control-Allow-Methods': 'PUT, DELETE, OPTIONS', + 'Access-Control-Allow-Origin': origin, + 'Cache-Control': 'private, no-store', + Vary: 'Origin', + } +} + +function getCookieOptions(maxAge: number) { + const production = process.env.NODE_ENV === 'production' + + return { + httpOnly: true, + maxAge, + partitioned: production, + path: '/', + sameSite: production ? ('none' as const) : ('lax' as const), + secure: production, + } +} + +function forbiddenResponse() { + return Response.json( + { message: 'This origin cannot configure the preview proxy.' }, + { status: 403 }, + ) +} diff --git a/apps/preview/app/api/health/route.ts b/apps/preview/app/api/health/route.ts new file mode 100644 index 0000000..481a232 --- /dev/null +++ b/apps/preview/app/api/health/route.ts @@ -0,0 +1,19 @@ +import { getCloneOrigin } from '@/lib/origins' + +// The deploy's smoke reads this: it answers from the Worker alone — no v0 +// call, no key needed — and names the host app origin the build inlined (the +// only origin that may provision this proxy's key). It says whether a server +// key is set, never what it is. +export const dynamic = 'force-dynamic' + +export function GET() { + return Response.json( + { + ok: true, + app: 'preview', + cloneOrigin: getCloneOrigin(), + v0ApiKey: process.env.V0_API_KEY ? 'environment' : 'browser', + }, + { headers: { 'Cache-Control': 'no-store' } }, + ) +} diff --git a/apps/preview/app/api/v0-preview/[chatId]/[[...path]]/route.ts b/apps/preview/app/api/v0-preview/[chatId]/[[...path]]/route.ts new file mode 100644 index 0000000..505ef89 --- /dev/null +++ b/apps/preview/app/api/v0-preview/[chatId]/[[...path]]/route.ts @@ -0,0 +1,23 @@ +import { proxyPreviewRequest } from '@/lib/preview' +import { authorizeProxyRequest } from '@/lib/authorize' + +type RouteContext = { + params: Promise<{ chatId: string; path?: string[] }> +} + +async function handler(request: Request, context: RouteContext) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId, path = [] } = await context.params + return proxyPreviewRequest(request, chatId, path) +} + +export { + handler as DELETE, + handler as GET, + handler as HEAD, + handler as OPTIONS, + handler as PATCH, + handler as POST, + handler as PUT, +} diff --git a/apps/preview/app/api/v0-preview/[chatId]/loading/route.ts b/apps/preview/app/api/v0-preview/[chatId]/loading/route.ts new file mode 100644 index 0000000..c7fe03c --- /dev/null +++ b/apps/preview/app/api/v0-preview/[chatId]/loading/route.ts @@ -0,0 +1,59 @@ +import { getCloneOrigin } from '@/lib/origins' + +function escapeHtml(value: string) { + return value + .replaceAll('&', '&') + .replaceAll('"', '"') + .replaceAll('<', '<') + .replaceAll('>', '>') +} + +export async function GET(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const { chatId } = await params + const previewPath = `/api/v0-preview/${encodeURIComponent(chatId)}` + const requestedReturnTo = new URL(request.url).searchParams.get('returnTo') + const returnTo = + requestedReturnTo === previewPath || + requestedReturnTo?.startsWith(`${previewPath}/`) || + requestedReturnTo?.startsWith(`${previewPath}?`) + ? requestedReturnTo + : previewPath + const cloneOrigin = getCloneOrigin() + + return new Response( + ` + + + + + + + + + Loading preview… +`, + { + headers: { + 'Cache-Control': 'no-store', + 'Content-Type': 'text/html; charset=utf-8', + }, + }, + ) +} diff --git a/apps/preview/app/layout.tsx b/apps/preview/app/layout.tsx new file mode 100644 index 0000000..fcf298d --- /dev/null +++ b/apps/preview/app/layout.tsx @@ -0,0 +1,14 @@ +import type { Metadata } from 'next' + +export const metadata: Metadata = { + title: 'v0 Preview Proxy', + description: 'Isolated preview proxy for the v0 clone example.', +} + +export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { + return ( + + {children} + + ) +} diff --git a/apps/preview/app/page.tsx b/apps/preview/app/page.tsx new file mode 100644 index 0000000..844c5d6 --- /dev/null +++ b/apps/preview/app/page.tsx @@ -0,0 +1,100 @@ +import { getCloneOrigin } from '@/lib/origins' + +export const dynamic = 'force-dynamic' + +export default function PreviewProxyPage() { + const configuration = getConfiguration() + + return ( +
+
+
+ + + {configuration.ready ? 'Proxy online' : 'Configuration required'} + +
+

+ v0 Preview Proxy +

+

+ This deployment is the isolated origin used to serve generated previews. Open the v0 clone + app to create and view chats. +

+
+
Allowed clone origin
+
+ {configuration.value} +
+
+ {configuration.ready ? ( + + Open v0 Clone + + ) : null} +
+
+ ) +} + +function getConfiguration() { + try { + return { ready: true, value: getCloneOrigin() } + } catch (error) { + return { + ready: false, + value: error instanceof Error ? error.message : 'V0_CLONE_ORIGIN is invalid.', + } + } +} diff --git a/apps/preview/cloudflare-env.d.ts b/apps/preview/cloudflare-env.d.ts new file mode 100644 index 0000000..411a8be --- /dev/null +++ b/apps/preview/cloudflare-env.d.ts @@ -0,0 +1,10 @@ +// The Worker's environment as getCloudflareContext().env (and process.env, +// which @opennextjs/cloudflare fills from it) sees it: the static-assets +// binding, and the one optional Worker secret the deploy lane sets +// (tooling/wire/worker-secrets.mjs). The app's own code reads neither through +// Worker types — upstream's client code needs the DOM's, which +// @cloudflare/workers-types would shadow — so ASSETS is typed by its shape. +interface CloudflareEnv { + ASSETS: { fetch: typeof fetch } + V0_API_KEY?: string +} diff --git a/apps/preview/eslint.config.mjs b/apps/preview/eslint.config.mjs new file mode 100644 index 0000000..83484f3 --- /dev/null +++ b/apps/preview/eslint.config.mjs @@ -0,0 +1,9 @@ +import { defineConfig, globalIgnores } from "eslint/config"; +import nextVitals from "eslint-config-next/core-web-vitals"; +import nextTs from "eslint-config-next/typescript"; + +export default defineConfig([ + ...nextVitals, + ...nextTs, + globalIgnores([".next/**", ".open-next/**", ".wrangler/**", "next-env.d.ts", "cloudflare-env.d.ts"]), +]); diff --git a/apps/preview/lib/authorize.ts b/apps/preview/lib/authorize.ts new file mode 100644 index 0000000..1b72775 --- /dev/null +++ b/apps/preview/lib/authorize.ts @@ -0,0 +1,14 @@ +/** + * This proxy serves a credentialed channel into the preview of every chat in + * the deployer's v0 workspace. The same-origin check below is only a baseline + * against browser cross-origin abuse — it does not stop direct non-browser + * requests, and a chat ID is not a secret. Replace or extend it with your + * application's session auth, keyed to which viewer may see which chat, before + * exposing a deployment to untrusted users. + */ +export function authorizeProxyRequest(request: Request): Response | undefined { + const origin = request.headers.get('origin') + if (origin && origin !== new URL(request.url).origin) { + return Response.json({ message: 'Forbidden' }, { status: 403 }) + } +} diff --git a/apps/preview/lib/origins.ts b/apps/preview/lib/origins.ts new file mode 100644 index 0000000..7e104ac --- /dev/null +++ b/apps/preview/lib/origins.ts @@ -0,0 +1,41 @@ +const defaultCloneOrigin = 'http://localhost:3000' + +/** + * The host app's origin — the only origin allowed to provision this proxy's + * key (app/api/api-key/route.ts). + * + * On Vercel, Related Projects told this app the host's URL per deployment, + * with V0_CLONE_ORIGIN as the production override. Here each environment's + * build is told it: NEXT_PUBLIC_V0_CLONE_ORIGIN is inlined at build time, from + * the environment's V0_CLONE_ORIGIN when an owner sets one (a custom domain), + * else the host Worker's workers.dev URL for that environment (component.yaml's + * buildCommand). `next dev` sets neither and gets the local host app, as + * upstream does. + */ +export function getCloneOrigin() { + const configured = process.env.NEXT_PUBLIC_V0_CLONE_ORIGIN + if (!configured) return defaultCloneOrigin + + const url = new URL(configured) + + if ( + (url.protocol !== 'http:' && url.protocol !== 'https:') || + url.username || + url.password || + url.pathname !== '/' || + url.search || + url.hash + ) { + throw new Error('V0_CLONE_ORIGIN must be an HTTP(S) origin without a path.') + } + + if (url.protocol !== 'https:' && !isLoopback(url.hostname)) { + throw new Error('V0_CLONE_ORIGIN must use HTTPS.') + } + + return url.origin +} + +function isLoopback(hostname: string) { + return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' +} diff --git a/apps/preview/lib/preview.ts b/apps/preview/lib/preview.ts new file mode 100644 index 0000000..1c3952a --- /dev/null +++ b/apps/preview/lib/preview.ts @@ -0,0 +1,54 @@ +import { fetchPreview, type ChatsGetPreviewResponse } from 'v0' +import { ensureTrustedPreviewHost } from '@/lib/trusted-host' +import { getV0ApiKeyFingerprint, v0 } from '@/lib/v0-client' + +type Preview = NonNullable + +// This process-local cache is enough for the demo. Use a shared cache in production. +// OIDC requests bypass it because there is no API key with which to scope the entry. +// You will need to add your own auth mechanism to scope the cache. +const previewCache = new Map() + +async function getPreview(chatId: string, cacheKey?: string) { + const cached = cacheKey ? previewCache.get(cacheKey) : undefined + const now = Date.now() + + if (cached && cached.expiresAt.getTime() - now > 60_000) { + return cached + } + + const response = await v0.chats.getPreview({ chatId }) + if (response.error) throw new Error(response.error.message) + + const preview = response.data + if (cacheKey) { + if (preview) previewCache.set(cacheKey, preview) + else previewCache.delete(cacheKey) + } + + return preview +} + +export async function proxyPreviewRequest(request: Request, chatId: string, path: string[]) { + const proxyUrl = new URL(request.url) + if (path.length === 0) await ensureTrustedPreviewHost(v0, proxyUrl.hostname) + + const apiKeyFingerprint = await getV0ApiKeyFingerprint() + const cacheKey = apiKeyFingerprint ? `${apiKeyFingerprint}:${chatId}` : undefined + const preview = await getPreview(chatId, cacheKey) + const fallbackUrl = new URL( + `/api/v0-preview/${encodeURIComponent(chatId)}/loading`, + proxyUrl.origin, + ) + fallbackUrl.searchParams.set('returnTo', proxyUrl.pathname + proxyUrl.search) + + return fetchPreview({ + request, + preview, + path, + fallbackUrl, + onPreviewRefresh: () => { + if (cacheKey) previewCache.delete(cacheKey) + }, + }) +} diff --git a/apps/preview/lib/trusted-host.ts b/apps/preview/lib/trusted-host.ts new file mode 100644 index 0000000..9d31103 --- /dev/null +++ b/apps/preview/lib/trusted-host.ts @@ -0,0 +1,88 @@ +import { createV0Client } from 'v0' + +type V0Client = ReturnType + +const MAX_TRUSTED_HOSTS = 5 + +export class TrustedHostError extends Error { + constructor( + message: string, + readonly status: number, + ) { + super(message) + } +} + +export async function ensureTrustedPreviewHost(client: V0Client, hostname: string) { + if (isLocalhost(hostname)) return + + const trustedHostsResult = await client.settings.getPreviewHosts().catch(() => null) + + if (!trustedHostsResult) { + throw new TrustedHostError('The trusted preview hosts could not be loaded.', 502) + } + + if (trustedHostsResult.error) { + throw new TrustedHostError( + trustedHostsResult.error.message || 'The v0 credential could not be validated.', + trustedHostsResult.response.status, + ) + } + + const hosts = trustedHostsResult.data.hosts + + if (!isTrustedPreviewHost(hostname, hosts)) { + if (hosts.length >= MAX_TRUSTED_HOSTS) { + throw new TrustedHostError( + 'v0 already has five trusted preview hosts. Remove one and try again.', + 409, + ) + } + + const updateResult = await client.settings + .setPreviewHosts({ hosts: [...hosts, hostname] }) + .catch(() => null) + + if (!updateResult) { + throw new TrustedHostError('This preview proxy could not add itself as a trusted host.', 502) + } + + if (updateResult.error) { + throw new TrustedHostError( + updateResult.error.message || 'This preview proxy could not add itself as a trusted host.', + updateResult.response.status, + ) + } + } +} + +function isLocalhost(hostname: string) { + return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' +} + +function isTrustedPreviewHost(hostname: string, patterns: string[]) { + const normalizedHostname = hostname.toLowerCase() + const hostLabels = normalizedHostname.split('.') + + return patterns.some((value) => { + const pattern = value.toLowerCase() + + if (pattern.startsWith('**.')) { + const suffixLabels = pattern.slice(3).split('.') + return ( + hostLabels.length > suffixLabels.length && + hostLabels.slice(-suffixLabels.length).join('.') === suffixLabels.join('.') + ) + } + + if (pattern.startsWith('*.')) { + const suffixLabels = pattern.slice(2).split('.') + return ( + hostLabels.length === suffixLabels.length + 1 && + hostLabels.slice(1).join('.') === suffixLabels.join('.') + ) + } + + return pattern === normalizedHostname + }) +} diff --git a/apps/preview/lib/v0-client.ts b/apps/preview/lib/v0-client.ts new file mode 100644 index 0000000..2573890 --- /dev/null +++ b/apps/preview/lib/v0-client.ts @@ -0,0 +1,32 @@ +import 'server-only' + +import { createHash } from 'node:crypto' +import { cookies } from 'next/headers' +import { createV0Client } from 'v0' +import { v0Fetch } from '@/lib/v0-fetch' + +export const V0_PROXY_API_KEY_COOKIE = + process.env.NODE_ENV === 'production' + ? '__Host-v0-preview-api-key' + : 'v0-preview-api-key' + +async function getV0ApiKey() { + if (process.env.V0_API_KEY) return process.env.V0_API_KEY + + const cookieStore = await cookies() + return cookieStore.get(V0_PROXY_API_KEY_COOKIE)?.value +} + +export async function getV0ApiKeyFingerprint() { + const apiKey = await getV0ApiKey() + + return apiKey ? createHash('sha256').update(apiKey).digest('base64url') : undefined +} + +// Upstream fell back to Vercel OIDC when neither key was there; there is no +// OIDC token on Cloudflare, so with no key the v0 API refuses the call and the +// preview shows its loading page until the host app provisions a key. +export const v0 = createV0Client({ + auth: async () => (await getV0ApiKey()) ?? '', + fetch: v0Fetch, +}) diff --git a/apps/preview/lib/v0-fetch.ts b/apps/preview/lib/v0-fetch.ts new file mode 100644 index 0000000..b44081e --- /dev/null +++ b/apps/preview/lib/v0-fetch.ts @@ -0,0 +1,16 @@ +// Where the v0 API calls go. Unset — always, unless an owner sets it — every +// call goes to v0's API, exactly as upstream. V0_API_BASE_URL points them at +// another origin with the same paths: the stand-in v0 API the end-to-end test +// serves (testing/), or an egress proxy in front of v0. +const V0_API_ORIGIN = 'https://api.v0.dev' + +export const v0Fetch: typeof fetch = (input, init) => { + const base = process.env.V0_API_BASE_URL + if (!base) return fetch(input, init) + + const request = new Request(input, init) + const url = new URL(request.url) + if (url.origin !== V0_API_ORIGIN) return fetch(request) + + return fetch(new Request(new URL(url.pathname + url.search, new URL(base).origin), request)) +} diff --git a/apps/preview/next.config.mjs b/apps/preview/next.config.mjs new file mode 100644 index 0000000..595acdc --- /dev/null +++ b/apps/preview/next.config.mjs @@ -0,0 +1,25 @@ +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { initOpenNextCloudflareForDev } from '@opennextjs/cloudflare' +import { PHASE_DEVELOPMENT_SERVER } from 'next/constants.js' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) + +/** @type {import('next').NextConfig} */ +const nextConfig = { + // Required by @opennextjs/cloudflare, which bundles `.next/standalone/**` + // into the Worker; traced from the monorepo root. Upstream's config was + // empty — Vercel needs neither. + output: 'standalone', + outputFileTracingRoot: path.join(__dirname, '../..'), +} + +// `next dev` gets the Worker's environment (V0_API_KEY from .dev.vars, when +// set) through wrangler's local platform proxy. Only the dev server starts +// it: a build must need nothing from wrangler. +export default function config(phase) { + if (phase === PHASE_DEVELOPMENT_SERVER) { + initOpenNextCloudflareForDev() + } + return nextConfig +} diff --git a/apps/preview/open-next.config.ts b/apps/preview/open-next.config.ts new file mode 100644 index 0000000..2534eb1 --- /dev/null +++ b/apps/preview/open-next.config.ts @@ -0,0 +1,16 @@ +// OpenNext Cloudflare adapter config. +// +// Every route is dynamic: the pages read the visitor's v0 key from a cookie +// (or V0_API_KEY) and fetch chats from the v0 API per request, and nothing +// revalidates. The static-assets incremental cache serves whatever the build +// pre-rendered straight from the Worker's static assets (read only, nothing +// to provision for it; `opennextjs-cloudflare populateCache local` puts it +// there at build time, and with no remote bindings it needs no Cloudflare +// credential). A version that revalidates swaps this for the R2 incremental +// cache plus a tag cache. +import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"; +import staticAssetsIncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/static-assets-incremental-cache"; + +export default defineCloudflareConfig({ + incrementalCache: staticAssetsIncrementalCache, +}); diff --git a/apps/preview/package.json b/apps/preview/package.json new file mode 100644 index 0000000..1fda984 --- /dev/null +++ b/apps/preview/package.json @@ -0,0 +1,31 @@ +{ + "name": "@app/preview", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev --port 3001", + "build": "next build && opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck && opennextjs-cloudflare populateCache local", + "start": "next start --port 3001", + "preview": "opennextjs-cloudflare preview", + "typecheck": "tsc --noEmit", + "lint": "eslint ." + }, + "dependencies": { + "@opennextjs/cloudflare": "^1.20.11", + "next": "16.3.8", + "react": "19.2.7", + "react-dom": "19.2.7", + "v0": "3.0.12" + }, + "devDependencies": { + "@app/eslint-config": "workspace:*", + "@app/tsconfig": "workspace:*", + "@types/node": "^22.9.0", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9.27.0", + "eslint-config-next": "16.3.8", + "typescript": "^5.8.3", + "wrangler": "^4.151.0" + } +} diff --git a/apps/preview/proxy.ts b/apps/preview/proxy.ts new file mode 100644 index 0000000..6525f06 --- /dev/null +++ b/apps/preview/proxy.ts @@ -0,0 +1,24 @@ +import { NextResponse, type NextRequest } from 'next/server' + +const previewPath = /^\/api\/v0-preview\/([^/]+)(?:\/|$)/ + +export function proxy(request: NextRequest) { + const referer = request.headers.get('referer') + if (!referer) return NextResponse.next() + if (!URL.canParse(referer)) return NextResponse.next() + + const refererUrl = new URL(referer) + if (refererUrl.origin !== request.nextUrl.origin) return NextResponse.next() + + const chatId = refererUrl.pathname.match(previewPath)?.[1] + if (!chatId) return NextResponse.next() + + const proxyUrl = request.nextUrl.clone() + proxyUrl.pathname = `/api/v0-preview/${chatId}${request.nextUrl.pathname}` + + return NextResponse.redirect(proxyUrl, 307) +} + +export const config = { + matcher: '/((?!api/v0-preview/).*)', +} diff --git a/apps/preview/tsconfig.json b/apps/preview/tsconfig.json new file mode 100644 index 0000000..cd26f18 --- /dev/null +++ b/apps/preview/tsconfig.json @@ -0,0 +1,46 @@ +{ + "compilerOptions": { + "target": "ES2017", + "lib": [ + "dom", + "dom.iterable", + "esnext" + ], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "react-jsx", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@/*": [ + "./*" + ] + }, + "types": [ + "node" + ] + }, + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + ".next/types/**/*.ts", + ".next/dev/types/**/*.ts", + "cloudflare-env.d.ts" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/apps/preview/turbo.json b/apps/preview/turbo.json new file mode 100644 index 0000000..c6c32db --- /dev/null +++ b/apps/preview/turbo.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://turbo.build/schema.json", + "extends": [ + "//" + ], + "tasks": { + "build": { + "dependsOn": [ + "^build" + ], + "env": [ + "NEXT_PUBLIC_V0_PREVIEW_PROXY_URL", + "NEXT_PUBLIC_V0_CLONE_ORIGIN" + ], + "outputs": [ + ".open-next/**", + ".next/**", + "!.next/cache/**" + ] + } + } +} diff --git a/apps/preview/wrangler.jsonc b/apps/preview/wrangler.jsonc new file mode 100644 index 0000000..899dbbc --- /dev/null +++ b/apps/preview/wrangler.jsonc @@ -0,0 +1,20 @@ +// The preview proxy, on an origin of its own: it fetches each chat's preview with the v0 key and serves it into the host's iframe (upstream's apps/preview-proxy). Generated code runs here, never on the host's origin. +// Committed as-is: the composition's structure check needs it before the +// build, and nothing in it differs per environment — the Worker name gets its +// environment suffix from the deploy (component.yaml, +// environmentAwareWorkerName), and the other app's origin is inlined at build +// time (component.yaml's buildCommand). V0_API_KEY is an optional Worker +// SECRET, never a var (tooling/wire/worker-secrets.mjs; README, "Connecting +// v0"). +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "v0-clone-preview", + "main": ".open-next/worker.js", + "compatibility_date": "2026-10-01", + "compatibility_flags": ["nodejs_compat", "global_fetch_strictly_public"], + "assets": { + "directory": ".open-next/assets", + "binding": "ASSETS" + }, + "observability": { "enabled": true } +} diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example new file mode 100644 index 0000000..8a72d46 --- /dev/null +++ b/apps/web/.dev.vars.example @@ -0,0 +1,6 @@ +# Copy to .dev.vars for `wrangler dev` / `pnpm preview` (never committed). +# +# Optional. Unset, each visitor saves their own v0 key through the app's +# dialog. Set, every visitor shares this key's v0 workspace and credits — +# set the same key on both apps (README, "Connecting v0"). +# V0_API_KEY= diff --git a/apps/web/LICENSE b/apps/web/LICENSE new file mode 100644 index 0000000..d9db03e --- /dev/null +++ b/apps/web/LICENSE @@ -0,0 +1,13 @@ +Copyright 2025 Vercel, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/apps/web/app/api/chats/[chatId]/deploy/route.ts b/apps/web/app/api/chats/[chatId]/deploy/route.ts new file mode 100644 index 0000000..3a2e641 --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/deploy/route.ts @@ -0,0 +1,30 @@ +import { getVercelDeploymentUrl } from '@/lib/vercel' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { getV0ApiKey, v0 } from '@/lib/v0-client' + +export async function POST(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const apiKey = await getV0ApiKey() + const { chatId } = await params + const result = await v0.chats.deploy({ chatId }) + + if (result.error) return toV0JsonResponse(result) + + try { + const deploymentUrl = await getVercelDeploymentUrl(result.data.deploymentId, apiKey) + + return toV0JsonResponse(result, { + ...result.data, + deploymentUrl, + }) + } catch (error) { + return Response.json( + { + message: error instanceof Error ? error.message : 'Failed to fetch the deployment URL.', + }, + { status: 500 }, + ) + } +} diff --git a/apps/web/app/api/chats/[chatId]/design-mode/route.ts b/apps/web/app/api/chats/[chatId]/design-mode/route.ts new file mode 100644 index 0000000..6c708e8 --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/design-mode/route.ts @@ -0,0 +1,24 @@ +import { parseDesignModeMessage, type DesignModeMessage } from 'v0' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +export const maxDuration = 1800 + +export async function POST(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + + let message: DesignModeMessage + try { + message = parseDesignModeMessage(await request.json()) + } catch (error) { + return Response.json( + { message: error instanceof Error ? error.message : 'Invalid Design Mode input.' }, + { status: 422 }, + ) + } + + const result = await v0.messages.sendStream({ chatId, ...message }, { signal: request.signal }) + return result.toResponse() +} diff --git a/apps/web/app/api/chats/[chatId]/download/route.ts b/apps/web/app/api/chats/[chatId]/download/route.ts new file mode 100644 index 0000000..3829124 --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/download/route.ts @@ -0,0 +1,15 @@ +import { v0 } from '@/lib/v0-client' +import { authorizeProxyRequest } from '@/lib/proxy' + +export async function GET(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const result = await v0.chats.downloadFiles({ chatId }, { parseAs: 'stream' }) + + if (result.error) { + return Response.json(result.error, { status: result.response.status }) + } + + return result.response +} diff --git a/apps/web/app/api/chats/[chatId]/duplicate/route.ts b/apps/web/app/api/chats/[chatId]/duplicate/route.ts new file mode 100644 index 0000000..e9b11c1 --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/duplicate/route.ts @@ -0,0 +1,22 @@ +import { revalidatePath } from 'next/cache' +import type { ChatsDuplicateData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type DuplicateChatBody = ChatsDuplicateData['body'] + +export async function POST(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const body = (await request.json().catch(() => null)) as DuplicateChatBody | null + const result = await v0.chats.duplicate({ + chatId, + privacy: 'private', + ...(body?.title ? { title: body.title } : {}), + }) + + revalidatePath('/', 'layout') + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/[chatId]/files/route.ts b/apps/web/app/api/chats/[chatId]/files/route.ts new file mode 100644 index 0000000..7623b30 --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/files/route.ts @@ -0,0 +1,34 @@ +import type { ChatsUpdateFilesData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type UpdateFilesBody = ChatsUpdateFilesData['body'] +type RouteContext = { params: Promise<{ chatId: string }> } + +export async function GET(request: Request, { params }: RouteContext) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const result = await v0.chats.getFiles({ chatId }) + + return toV0JsonResponse(result) +} + +export async function PATCH(request: Request, { params }: RouteContext) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const body = (await request.json().catch(() => null)) as UpdateFilesBody | null + + if (!Array.isArray(body?.files) || body.files.length === 0) { + return Response.json({ message: 'At least one file update is required.' }, { status: 400 }) + } + + const result = await v0.chats.updateFiles({ + chatId, + files: body.files, + }) + + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/[chatId]/messages/[messageId]/stop/route.ts b/apps/web/app/api/chats/[chatId]/messages/[messageId]/stop/route.ts new file mode 100644 index 0000000..91ea171 --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/messages/[messageId]/stop/route.ts @@ -0,0 +1,15 @@ +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +export async function POST( + request: Request, + { params }: { params: Promise<{ chatId: string; messageId: string }> }, +) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId, messageId } = await params + const result = await v0.messages.stop({ chatId, messageId }) + + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/[chatId]/messages/route.ts b/apps/web/app/api/chats/[chatId]/messages/route.ts new file mode 100644 index 0000000..5bdc2ca --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/messages/route.ts @@ -0,0 +1,45 @@ +import type { MessagesSendData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type SendMessageBody = Pick + +export async function GET(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const searchParams = new URL(request.url).searchParams + const limit = Number(searchParams.get('limit') ?? 20) + + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { + return Response.json({ message: 'limit must be between 1 and 100.' }, { status: 400 }) + } + + const result = await v0.messages.list({ + chatId, + limit, + ...(searchParams.get('cursor') ? { cursor: searchParams.get('cursor')! } : {}), + }) + + return toV0JsonResponse(result) +} + +export async function POST(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const body = (await request.json().catch(() => null)) as SendMessageBody | null + + if (typeof body?.message !== 'string' || !body.message.trim()) { + return Response.json({ message: 'Enter a message.' }, { status: 400 }) + } + + const result = await v0.messages.sendStream({ + chatId, + message: body.message.trim(), + modelConfiguration: body.modelConfiguration, + }) + + return result.toResponse() +} diff --git a/apps/web/app/api/chats/[chatId]/project/route.ts b/apps/web/app/api/chats/[chatId]/project/route.ts new file mode 100644 index 0000000..3596d5d --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/project/route.ts @@ -0,0 +1,19 @@ +import type { ChatsCreateVercelProjectData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type CreateProjectBody = ChatsCreateVercelProjectData['body'] + +export async function POST(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const body = (await request.json().catch(() => ({}))) as CreateProjectBody + const result = await v0.chats.createVercelProject({ + chatId, + ...(body.name ? { name: body.name } : {}), + }) + + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/[chatId]/resolve/route.ts b/apps/web/app/api/chats/[chatId]/resolve/route.ts new file mode 100644 index 0000000..abeb907 --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/resolve/route.ts @@ -0,0 +1,24 @@ +import type { MessagesResolveStreamData } from 'v0' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type ResolveTaskBody = MessagesResolveStreamData['body'] + +export async function POST(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const body = (await request.json().catch(() => null)) as ResolveTaskBody | null + + if (!body?.task) { + return Response.json({ message: 'A task response is required.' }, { status: 400 }) + } + + const result = await v0.messages.resolveStream({ + chatId, + task: body.task, + modelConfiguration: body.modelConfiguration, + }) + + return result.toResponse() +} diff --git a/apps/web/app/api/chats/[chatId]/restore/route.ts b/apps/web/app/api/chats/[chatId]/restore/route.ts new file mode 100644 index 0000000..1abfd02 --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/restore/route.ts @@ -0,0 +1,24 @@ +import type { ChatsRestoreMessageData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type RestoreMessageBody = ChatsRestoreMessageData['body'] + +export async function POST(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const body = (await request.json().catch(() => null)) as RestoreMessageBody | null + + if (typeof body?.messageId !== 'string' || !body.messageId) { + return Response.json({ message: 'A message ID is required.' }, { status: 400 }) + } + + const result = await v0.chats.restoreMessage({ + chatId, + messageId: body.messageId, + }) + + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/[chatId]/resume/route.ts b/apps/web/app/api/chats/[chatId]/resume/route.ts new file mode 100644 index 0000000..c40301e --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/resume/route.ts @@ -0,0 +1,11 @@ +import { v0 } from '@/lib/v0-client' +import { authorizeProxyRequest } from '@/lib/proxy' + +export async function POST(request: Request, { params }: { params: Promise<{ chatId: string }> }) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const result = await v0.chats.resume({ chatId }) + + return result.toResponse() +} diff --git a/apps/web/app/api/chats/[chatId]/route.ts b/apps/web/app/api/chats/[chatId]/route.ts new file mode 100644 index 0000000..424653f --- /dev/null +++ b/apps/web/app/api/chats/[chatId]/route.ts @@ -0,0 +1,34 @@ +import { revalidatePath } from 'next/cache' +import type { ChatsUpdateData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type UpdateChatBody = ChatsUpdateData['body'] +type RouteContext = { params: Promise<{ chatId: string }> } + +export async function PATCH(request: Request, { params }: RouteContext) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const body = (await request.json().catch(() => null)) as UpdateChatBody | null + + if (!body || typeof body !== 'object') { + return Response.json({ message: 'Chat updates are required.' }, { status: 400 }) + } + + const result = await v0.chats.update({ chatId, ...body }) + + revalidatePath('/', 'layout') + return toV0JsonResponse(result) +} + +export async function DELETE(request: Request, { params }: RouteContext) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const { chatId } = await params + const result = await v0.chats.delete({ chatId }) + + revalidatePath('/', 'layout') + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/import/files/route.ts b/apps/web/app/api/chats/import/files/route.ts new file mode 100644 index 0000000..8a15a5f --- /dev/null +++ b/apps/web/app/api/chats/import/files/route.ts @@ -0,0 +1,25 @@ +import { revalidatePath } from 'next/cache' +import type { ChatsCreateFromFilesData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type CreateFromFilesBody = ChatsCreateFromFilesData['body'] + +export async function POST(request: Request) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const body = (await request.json().catch(() => null)) as CreateFromFilesBody | null + + if (!Array.isArray(body?.files) || body.files.length === 0) { + return Response.json({ message: 'Choose at least one file.' }, { status: 400 }) + } + + const result = await v0.chats.createFromFiles({ + ...body, + privacy: 'private', + }) + + revalidatePath('/', 'layout') + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/import/repo/route.ts b/apps/web/app/api/chats/import/repo/route.ts new file mode 100644 index 0000000..048bc62 --- /dev/null +++ b/apps/web/app/api/chats/import/repo/route.ts @@ -0,0 +1,29 @@ +import { revalidatePath } from 'next/cache' +import type { ChatsCreateFromRepoData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type CreateFromRepoBody = ChatsCreateFromRepoData['body'] + +export async function POST(request: Request) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const body = (await request.json().catch(() => null)) as CreateFromRepoBody | null + + if (typeof body?.repo?.url !== 'string' || !body.repo.url.trim()) { + return Response.json({ message: 'Enter a repository URL.' }, { status: 400 }) + } + + const result = await v0.chats.createFromRepo({ + ...body, + repo: { + ...body.repo, + url: body.repo.url.trim(), + }, + privacy: 'private', + }) + + revalidatePath('/', 'layout') + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/import/zip/route.ts b/apps/web/app/api/chats/import/zip/route.ts new file mode 100644 index 0000000..d495238 --- /dev/null +++ b/apps/web/app/api/chats/import/zip/route.ts @@ -0,0 +1,25 @@ +import { revalidatePath } from 'next/cache' +import type { ChatsCreateFromZipData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type CreateFromZipBody = ChatsCreateFromZipData['body'] + +export async function POST(request: Request) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const body = (await request.json().catch(() => null)) as CreateFromZipBody | null + + if (typeof body?.url !== 'string' || !body.url) { + return Response.json({ message: 'Choose a ZIP file.' }, { status: 400 }) + } + + const result = await v0.chats.createFromZip({ + ...body, + privacy: 'private', + }) + + revalidatePath('/', 'layout') + return toV0JsonResponse(result) +} diff --git a/apps/web/app/api/chats/route.ts b/apps/web/app/api/chats/route.ts new file mode 100644 index 0000000..6fe0097 --- /dev/null +++ b/apps/web/app/api/chats/route.ts @@ -0,0 +1,62 @@ +import { revalidatePath } from 'next/cache' +import type { ChatsCreateStreamData, ChatsListData } from 'v0' +import { toV0JsonResponse } from '@/lib/v0-response' +import { authorizeProxyRequest } from '@/lib/proxy' +import { v0 } from '@/lib/v0-client' + +type CreateChatBody = Pick + +export async function GET(request: Request) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const searchParams = new URL(request.url).searchParams + const limit = Number(searchParams.get('limit') ?? 20) + + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { + return Response.json({ message: 'limit must be between 1 and 100.' }, { status: 400 }) + } + + const metadata = parseMetadata(searchParams) + const query: ChatsListData['query'] = { + limit, + ...(searchParams.get('cursor') ? { cursor: searchParams.get('cursor')! } : {}), + ...(searchParams.get('authorId') ? { authorId: searchParams.get('authorId')! } : {}), + ...(searchParams.get('vercelProjectId') + ? { vercelProjectId: searchParams.get('vercelProjectId')! } + : {}), + ...(Object.keys(metadata).length > 0 ? { metadata } : {}), + } + const result = await v0.chats.list(query) + + return toV0JsonResponse(result) +} + +export async function POST(request: Request) { + const denied = authorizeProxyRequest(request) + if (denied) return denied + const body = (await request.json().catch(() => null)) as CreateChatBody | null + + if (typeof body?.message !== 'string' || !body.message.trim()) { + return Response.json({ message: 'Enter a message.' }, { status: 400 }) + } + + const result = await v0.chats.createStream({ + message: body.message.trim(), + modelConfiguration: body.modelConfiguration, + privacy: 'private', + }) + + revalidatePath('/', 'layout') + return result.toResponse() +} + +function parseMetadata(searchParams: URLSearchParams) { + const metadata: Record = {} + + for (const [key, value] of searchParams) { + const match = /^metadata\[([^\]]+)\]$/.exec(key) + if (match?.[1]) metadata[match[1]] = value + } + + return metadata +} diff --git a/apps/web/app/api/health/route.ts b/apps/web/app/api/health/route.ts new file mode 100644 index 0000000..23704c6 --- /dev/null +++ b/apps/web/app/api/health/route.ts @@ -0,0 +1,19 @@ +import { getPreviewProxyOrigin } from '@/lib/preview-proxy' + +// The deploy's smoke reads this: it answers from the Worker alone — no v0 +// call, no key needed — and names the preview proxy origin the build inlined, +// so the smoke can check that origin answers as the preview proxy. It says +// whether a server key is set, never what it is. +export const dynamic = 'force-dynamic' + +export function GET() { + return Response.json( + { + ok: true, + app: 'web', + previewProxy: getPreviewProxyOrigin(), + v0ApiKey: process.env.V0_API_KEY ? 'environment' : 'browser', + }, + { headers: { 'Cache-Control': 'no-store' } }, + ) +} diff --git a/apps/web/app/api/settings/api-key/route.ts b/apps/web/app/api/settings/api-key/route.ts new file mode 100644 index 0000000..a865bb7 --- /dev/null +++ b/apps/web/app/api/settings/api-key/route.ts @@ -0,0 +1,61 @@ +// Demo only: remove browser-provided API key support before using this example in production. +import { cookies } from 'next/headers' +import { createV0Client } from 'v0' +import { v0Fetch } from '@/lib/v0-fetch' +import { V0_API_KEY_COOKIE } from '@/lib/v0-client' + +const API_KEY_MAX_AGE = 60 * 60 * 4 + +export async function PUT(request: Request) { + if (process.env.V0_API_KEY) { + return Response.json({ message: 'This deployment already uses V0_API_KEY.' }, { status: 409 }) + } + + const body = (await request.json().catch(() => null)) as { apiKey?: unknown } | null + const apiKey = typeof body?.apiKey === 'string' ? body.apiKey.trim() : '' + + if (!apiKey) { + return Response.json({ message: 'Enter a v0 API key.' }, { status: 400 }) + } + + const client = createV0Client({ auth: apiKey, fetch: v0Fetch }) + const result = await client.chats.list({ limit: 1 }).catch(() => null) + + if (!result) { + return Response.json( + { message: 'The v0 API key could not be validated. Try again.' }, + { status: 502 }, + ) + } + + if (result.error) { + return Response.json( + { message: result.error.message || 'The v0 API key could not be validated.' }, + { status: result.response.status }, + ) + } + + const cookieStore = await cookies() + cookieStore.set(V0_API_KEY_COOKIE, apiKey, { + httpOnly: true, + maxAge: API_KEY_MAX_AGE, + path: '/', + sameSite: 'strict', + secure: process.env.NODE_ENV === 'production', + }) + + return Response.json({ configured: true }) +} + +export async function DELETE() { + const cookieStore = await cookies() + cookieStore.set(V0_API_KEY_COOKIE, '', { + httpOnly: true, + maxAge: 0, + path: '/', + sameSite: 'strict', + secure: process.env.NODE_ENV === 'production', + }) + + return Response.json({ configured: Boolean(process.env.V0_API_KEY) }) +} diff --git a/apps/web/app/chats/[chatId]/page.tsx b/apps/web/app/chats/[chatId]/page.tsx new file mode 100644 index 0000000..0e20655 --- /dev/null +++ b/apps/web/app/chats/[chatId]/page.tsx @@ -0,0 +1,30 @@ +import type { ChatFilesResult } from '@/components/chat/code-editor' +import { ChatWorkspace } from '@/components/chat/chat-workspace' +import { v0 } from '@/lib/v0-client' + +export default async function ChatPage({ params }: { params: Promise<{ chatId: string }> }) { + const { chatId } = await params + const filesPromise: Promise = v0.chats + .getFiles({ chatId }) + .then((response) => { + if (response.error) return { error: response.error.message } + return { files: response.data.files } + }) + .catch(() => ({ error: 'Failed to load files.' })) + const [chatResponse, messagesResponse] = await Promise.all([ + v0.chats.get({ chatId }), + v0.messages.list({ chatId, limit: 100 }), + ]) + + if (chatResponse.error) throw new Error(chatResponse.error.message) + if (messagesResponse.error) throw new Error(messagesResponse.error.message) + + return ( + + ) +} diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css new file mode 100644 index 0000000..bf9d3d5 --- /dev/null +++ b/apps/web/app/globals.css @@ -0,0 +1,150 @@ +@import 'tailwindcss'; +@import 'tw-animate-css'; + +@custom-variant dark (&:is(.dark *)); + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --font-sans: var(--font-geist-sans); + --font-mono: var(--font-geist-mono); + --color-sidebar-ring: var(--sidebar-ring); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar: var(--sidebar); + --color-chart-5: var(--chart-5); + --color-chart-4: var(--chart-4); + --color-chart-3: var(--chart-3); + --color-chart-2: var(--chart-2); + --color-chart-1: var(--chart-1); + --color-ring: var(--ring); + --color-input: var(--input); + --color-border: var(--border); + --color-destructive: var(--destructive); + --color-accent-foreground: var(--accent-foreground); + --color-accent: var(--accent); + --color-muted-foreground: var(--muted-foreground); + --color-muted: var(--muted); + --color-secondary-foreground: var(--secondary-foreground); + --color-secondary: var(--secondary); + --color-primary-foreground: var(--primary-foreground); + --color-primary: var(--primary); + --color-popover-foreground: var(--popover-foreground); + --color-popover: var(--popover); + --color-card-foreground: var(--card-foreground); + --color-card: var(--card); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); +} + +@keyframes fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes slide-up { + from { + transform: translateY(0.75rem); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +.animate-fade-in { + animation: fade-in 0.3s ease-out forwards; +} + +.animate-slide-up { + animation: slide-up 0.25s ease-out forwards; +} + +:root { + --radius: 0.625rem; + --background: oklch(1 0 0); + --foreground: oklch(0.145 0 0); + --card: oklch(1 0 0); + --card-foreground: oklch(0.145 0 0); + --popover: oklch(1 0 0); + --popover-foreground: oklch(0.145 0 0); + --primary: oklch(0.205 0 0); + --primary-foreground: oklch(0.985 0 0); + --secondary: oklch(0.97 0 0); + --secondary-foreground: oklch(0.205 0 0); + --muted: oklch(0.97 0 0); + --muted-foreground: oklch(0.556 0 0); + --accent: oklch(0.97 0 0); + --accent-foreground: oklch(0.205 0 0); + --destructive: oklch(0.577 0.245 27.325); + --border: oklch(0.922 0 0); + --input: oklch(0.922 0 0); + --ring: oklch(0.708 0 0); + --chart-1: oklch(0.646 0.222 41.116); + --chart-2: oklch(0.6 0.118 184.704); + --chart-3: oklch(0.398 0.07 227.392); + --chart-4: oklch(0.828 0.189 84.429); + --chart-5: oklch(0.769 0.188 70.08); + --sidebar: oklch(0.985 0 0); + --sidebar-foreground: oklch(0.145 0 0); + --sidebar-primary: oklch(0.205 0 0); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.97 0 0); + --sidebar-accent-foreground: oklch(0.205 0 0); + --sidebar-border: oklch(0.922 0 0); + --sidebar-ring: oklch(0.708 0 0); +} + +.dark { + --background: oklch(0.1689 0.0021 286.18); + --foreground: oklch(0.95 0 0); + --card: oklch(0.08 0 0); + --card-foreground: oklch(0.95 0 0); + --popover: oklch(0.08 0 0); + --popover-foreground: oklch(0.95 0 0); + --primary: oklch(0.95 0 0); + --primary-foreground: oklch(0.08 0 0); + --secondary: oklch(0.14 0 0); + --secondary-foreground: oklch(0.95 0 0); + --muted: oklch(0.18 0 0); + --muted-foreground: oklch(0.65 0 0); + --accent: oklch(0.14 0 0); + --accent-foreground: oklch(0.95 0 0); + --destructive: oklch(0.62 0.245 27.325); + --border: oklch(0.26 0 0); + --input: oklch(0.26 0 0); + --ring: oklch(0.65 0 0); + --chart-1: oklch(0.7 0.222 41.116); + --chart-2: oklch(0.65 0.118 184.704); + --chart-3: oklch(0.5 0.07 227.392); + --chart-4: oklch(0.85 0.189 84.429); + --chart-5: oklch(0.8 0.188 70.08); + --sidebar: oklch(0.08 0 0); + --sidebar-foreground: oklch(0.95 0 0); + --sidebar-primary: oklch(0.95 0 0); + --sidebar-primary-foreground: oklch(0.08 0 0); + --sidebar-accent: oklch(0.14 0 0); + --sidebar-accent-foreground: oklch(0.95 0 0); + --sidebar-border: oklch(0.26 0 0); + --sidebar-ring: oklch(0.65 0 0); +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + body { + @apply bg-background text-foreground font-sans; + } +} diff --git a/apps/web/app/icon.svg b/apps/web/app/icon.svg new file mode 100644 index 0000000..319c06b --- /dev/null +++ b/apps/web/app/icon.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx new file mode 100644 index 0000000..69db82a --- /dev/null +++ b/apps/web/app/layout.tsx @@ -0,0 +1,50 @@ +import type { Metadata } from 'next' +import { GeistSans } from 'geist/font/sans' +import { GeistMono } from 'geist/font/mono' +import { ThemeProvider } from 'next-themes' +import { TooltipProvider } from '@/components/ui/tooltip' +import { AppShell } from '@/components/layout/app-shell' +import { PreviewProxyProvider } from '@/components/preview/preview-proxy-provider' +import { getPreviewProxyOrigin } from '@/lib/preview-proxy' +import { getSidebarChats } from '@/lib/sidebar-chats' +import { getV0ApiKeyStatus } from '@/lib/v0-client' +import './globals.css' + +export const dynamic = 'force-dynamic' + +export const metadata: Metadata = { + title: 'v0 clone', + description: 'A v0.app clone built with AI Elements and Geist.', +} + +export default async function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode +}>) { + const sidebarChats = getSidebarChats() + const apiKeyStatus = await getV0ApiKeyStatus() + const previewProxyOrigin = getPreviewProxyOrigin() + + return ( + + + + + + + {children} + + + + + + + ) +} diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx new file mode 100644 index 0000000..9824014 --- /dev/null +++ b/apps/web/app/page.tsx @@ -0,0 +1,5 @@ +import { HomeClient } from '@/components/home/home-client' + +export default function HomePage() { + return +} diff --git a/apps/web/cloudflare-env.d.ts b/apps/web/cloudflare-env.d.ts new file mode 100644 index 0000000..411a8be --- /dev/null +++ b/apps/web/cloudflare-env.d.ts @@ -0,0 +1,10 @@ +// The Worker's environment as getCloudflareContext().env (and process.env, +// which @opennextjs/cloudflare fills from it) sees it: the static-assets +// binding, and the one optional Worker secret the deploy lane sets +// (tooling/wire/worker-secrets.mjs). The app's own code reads neither through +// Worker types — upstream's client code needs the DOM's, which +// @cloudflare/workers-types would shadow — so ASSETS is typed by its shape. +interface CloudflareEnv { + ASSETS: { fetch: typeof fetch } + V0_API_KEY?: string +} diff --git a/apps/web/components.json b/apps/web/components.json new file mode 100644 index 0000000..c87a43e --- /dev/null +++ b/apps/web/components.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "", + "css": "app/globals.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/lib/hooks" + }, + "iconLibrary": "geist", + "registries": { + "@ai-elements": "https://registry.ai-sdk.dev/{name}.json", + "@geist": "https://vercel.com/geist/r/{name}.json" + } +} diff --git a/apps/web/components/ai-elements/loader.tsx b/apps/web/components/ai-elements/loader.tsx new file mode 100644 index 0000000..608f403 --- /dev/null +++ b/apps/web/components/ai-elements/loader.tsx @@ -0,0 +1,85 @@ +import { cn } from '@/lib/utils' +import type { HTMLAttributes } from 'react' + +type LoaderIconProps = { + size?: number +} + +const LoaderIcon = ({ size = 16 }: LoaderIconProps) => ( + + Loader + + + + + + + + + + + + + + + + + + +) + +export type LoaderProps = HTMLAttributes & { + size?: number +} + +export const Loader = ({ className, size = 16, ...props }: LoaderProps) => ( +
+ +
+) diff --git a/apps/web/components/ai-elements/message.tsx b/apps/web/components/ai-elements/message.tsx new file mode 100644 index 0000000..3e7f96c --- /dev/null +++ b/apps/web/components/ai-elements/message.tsx @@ -0,0 +1,367 @@ +'use client' + +import { Button } from '@/components/ui/button' +import { ButtonGroup, ButtonGroupText } from '@/components/ui/button-group' +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import type { FileUIPart, UIMessage } from 'ai' +import { ChevronLeftIcon, ChevronRightIcon, PaperclipIcon, XIcon } from '@/components/ui/icons' +import type { ComponentProps, HTMLAttributes, ReactElement } from 'react' +import { createContext, memo, useContext, useEffect, useState } from 'react' +import { Streamdown } from 'streamdown' + +export type MessageProps = HTMLAttributes & { + from: UIMessage['role'] +} + +export const Message = ({ className, from, ...props }: MessageProps) => ( +
+) + +export type MessageContentProps = HTMLAttributes + +export const MessageContent = ({ children, className, ...props }: MessageContentProps) => ( +
+ {children} +
+) + +export type MessageActionsProps = ComponentProps<'div'> + +export const MessageActions = ({ className, children, ...props }: MessageActionsProps) => ( +
+ {children} +
+) + +export type MessageActionProps = ComponentProps & { + tooltip?: string + label?: string +} + +export const MessageAction = ({ + tooltip, + children, + label, + variant = 'ghost', + size = 'icon-sm', + ...props +}: MessageActionProps) => { + const button = ( + + ) + + if (tooltip) { + return ( + + + {button} + +

{tooltip}

+
+
+
+ ) + } + + return button +} + +type MessageBranchContextType = { + currentBranch: number + totalBranches: number + goToPrevious: () => void + goToNext: () => void + branches: ReactElement[] + setBranches: (branches: ReactElement[]) => void +} + +const MessageBranchContext = createContext(null) + +const useMessageBranch = () => { + const context = useContext(MessageBranchContext) + + if (!context) { + throw new Error('MessageBranch components must be used within MessageBranch') + } + + return context +} + +export type MessageBranchProps = HTMLAttributes & { + defaultBranch?: number + onBranchChange?: (branchIndex: number) => void +} + +export const MessageBranch = ({ + defaultBranch = 0, + onBranchChange, + className, + ...props +}: MessageBranchProps) => { + const [currentBranch, setCurrentBranch] = useState(defaultBranch) + const [branches, setBranches] = useState([]) + + const handleBranchChange = (newBranch: number) => { + setCurrentBranch(newBranch) + onBranchChange?.(newBranch) + } + + const goToPrevious = () => { + const newBranch = currentBranch > 0 ? currentBranch - 1 : branches.length - 1 + handleBranchChange(newBranch) + } + + const goToNext = () => { + const newBranch = currentBranch < branches.length - 1 ? currentBranch + 1 : 0 + handleBranchChange(newBranch) + } + + const contextValue: MessageBranchContextType = { + currentBranch, + totalBranches: branches.length, + goToPrevious, + goToNext, + branches, + setBranches, + } + + return ( + +
div]:pb-0', className)} {...props} /> + + ) +} + +export type MessageBranchContentProps = HTMLAttributes + +export const MessageBranchContent = ({ children, ...props }: MessageBranchContentProps) => { + const { currentBranch, setBranches, branches } = useMessageBranch() + const childrenArray = Array.isArray(children) ? children : [children] + + // Use useEffect to update branches when they change + useEffect(() => { + if (branches.length !== childrenArray.length) { + setBranches(childrenArray) + } + }, [childrenArray, branches, setBranches]) + + return childrenArray.map((branch, index) => ( +
div]:pb-0', + index === currentBranch ? 'block' : 'hidden', + )} + key={branch.key} + {...props} + > + {branch} +
+ )) +} + +export type MessageBranchSelectorProps = HTMLAttributes & { + from: UIMessage['role'] +} + +export const MessageBranchSelector = ({ + className, + from, + ...props +}: MessageBranchSelectorProps) => { + const { totalBranches } = useMessageBranch() + + // Don't render if there's only one branch + if (totalBranches <= 1) { + return null + } + + return ( + + ) +} + +export type MessageBranchPreviousProps = ComponentProps + +export const MessageBranchPrevious = ({ children, ...props }: MessageBranchPreviousProps) => { + const { goToPrevious, totalBranches } = useMessageBranch() + + return ( + + ) +} + +export type MessageBranchNextProps = ComponentProps + +export const MessageBranchNext = ({ children, className, ...props }: MessageBranchNextProps) => { + const { goToNext, totalBranches } = useMessageBranch() + + return ( + + ) +} + +export type MessageBranchPageProps = HTMLAttributes + +export const MessageBranchPage = ({ className, ...props }: MessageBranchPageProps) => { + const { currentBranch, totalBranches } = useMessageBranch() + + return ( + + {currentBranch + 1} of {totalBranches} + + ) +} + +export type MessageResponseProps = ComponentProps + +export const MessageResponse = memo( + ({ className, ...props }: MessageResponseProps) => ( + *:first-child]:mt-0 [&>*:last-child]:mb-0', className)} + {...props} + /> + ), + (prevProps, nextProps) => prevProps.children === nextProps.children, +) + +MessageResponse.displayName = 'MessageResponse' + +export type MessageAttachmentProps = HTMLAttributes & { + data: FileUIPart + className?: string + onRemove?: () => void +} + +export function MessageAttachment({ data, className, onRemove, ...props }: MessageAttachmentProps) { + const filename = data.filename || '' + const mediaType = data.mediaType?.startsWith('image/') && data.url ? 'image' : 'file' + const isImage = mediaType === 'image' + const attachmentLabel = filename || (isImage ? 'Image' : 'Attachment') + + return ( +
+ {isImage ? ( + <> + {filename + {onRemove && ( + + )} + + ) : ( + <> + + +
+ +
+
+ +

{attachmentLabel}

+
+
+ {onRemove && ( + + )} + + )} +
+ ) +} + +export type MessageAttachmentsProps = ComponentProps<'div'> + +export function MessageAttachments({ children, className, ...props }: MessageAttachmentsProps) { + if (!children) { + return null + } + + return ( +
+ {children} +
+ ) +} + +export type MessageToolbarProps = ComponentProps<'div'> + +export const MessageToolbar = ({ className, children, ...props }: MessageToolbarProps) => ( +
+ {children} +
+) diff --git a/apps/web/components/ai-elements/prompt-input.tsx b/apps/web/components/ai-elements/prompt-input.tsx new file mode 100644 index 0000000..d4416a6 --- /dev/null +++ b/apps/web/components/ai-elements/prompt-input.tsx @@ -0,0 +1,1256 @@ +'use client' + +import { Button } from '@/components/ui/button' +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, + CommandSeparator, +} from '@/components/ui/command' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu' +import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card' +import { + InputGroup, + InputGroupAddon, + InputGroupButton, + InputGroupTextarea, +} from '@/components/ui/input-group' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' +import { cn } from '@/lib/utils' +import type { ChatStatus, FileUIPart } from 'ai' +import { + CornerDownLeftIcon, + ImageIcon, + Loader2Icon, + MicIcon, + PaperclipIcon, + PlusIcon, + SquareIcon, + XIcon, +} from '@/components/ui/icons' +import { nanoid } from 'nanoid' +import { + type ChangeEvent, + type ChangeEventHandler, + Children, + type ClipboardEventHandler, + type ComponentProps, + createContext, + type FormEvent, + type FormEventHandler, + Fragment, + type HTMLAttributes, + type KeyboardEventHandler, + type PropsWithChildren, + type ReactNode, + type RefObject, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from 'react' + +// ============================================================================ +// Provider Context & Types +// ============================================================================ + +export type AttachmentsContext = { + files: (FileUIPart & { id: string })[] + add: (files: File[] | FileList) => void + remove: (id: string) => void + clear: () => void + openFileDialog: () => void + fileInputRef: RefObject +} + +export type TextInputContext = { + value: string + setInput: (v: string) => void + clear: () => void +} + +export type PromptInputControllerProps = { + textInput: TextInputContext + attachments: AttachmentsContext + /** INTERNAL: Allows PromptInput to register its file textInput + "open" callback */ + __registerFileInput: (ref: RefObject, open: () => void) => void +} + +const PromptInputController = createContext(null) +const ProviderAttachmentsContext = createContext(null) + +export const usePromptInputController = () => { + const ctx = useContext(PromptInputController) + if (!ctx) { + throw new Error( + 'Wrap your component inside to use usePromptInputController().', + ) + } + return ctx +} + +// Optional variants (do NOT throw). Useful for dual-mode components. +const useOptionalPromptInputController = () => useContext(PromptInputController) + +export const useProviderAttachments = () => { + const ctx = useContext(ProviderAttachmentsContext) + if (!ctx) { + throw new Error( + 'Wrap your component inside to use useProviderAttachments().', + ) + } + return ctx +} + +const useOptionalProviderAttachments = () => useContext(ProviderAttachmentsContext) + +export type PromptInputProviderProps = PropsWithChildren<{ + initialInput?: string +}> + +/** + * Optional global provider that lifts PromptInput state outside of PromptInput. + * If you don't use it, PromptInput stays fully self-managed. + */ +export function PromptInputProvider({ + initialInput: initialTextInput = '', + children, +}: PromptInputProviderProps) { + // ----- textInput state + const [textInput, setTextInput] = useState(initialTextInput) + const clearInput = useCallback(() => setTextInput(''), []) + + // ----- attachments state (global when wrapped) + const [attachmentFiles, setAttachmentFiles] = useState<(FileUIPart & { id: string })[]>([]) + const fileInputRef = useRef(null) + const openRef = useRef<() => void>(() => {}) + + const add = useCallback((files: File[] | FileList) => { + const incoming = Array.from(files) + if (incoming.length === 0) { + return + } + + setAttachmentFiles((prev) => + prev.concat( + incoming.map((file) => ({ + id: nanoid(), + type: 'file' as const, + url: URL.createObjectURL(file), + mediaType: file.type, + filename: file.name, + })), + ), + ) + }, []) + + const remove = useCallback((id: string) => { + setAttachmentFiles((prev) => { + const found = prev.find((f) => f.id === id) + if (found?.url) { + URL.revokeObjectURL(found.url) + } + return prev.filter((f) => f.id !== id) + }) + }, []) + + const clear = useCallback(() => { + setAttachmentFiles((prev) => { + for (const f of prev) { + if (f.url) { + URL.revokeObjectURL(f.url) + } + } + return [] + }) + }, []) + + // Keep a ref to attachments for cleanup on unmount (avoids stale closure) + const attachmentsRef = useRef(attachmentFiles) + attachmentsRef.current = attachmentFiles + + // Cleanup blob URLs on unmount to prevent memory leaks + useEffect(() => { + return () => { + for (const f of attachmentsRef.current) { + if (f.url) { + URL.revokeObjectURL(f.url) + } + } + } + }, []) + + const openFileDialog = useCallback(() => { + openRef.current?.() + }, []) + + const attachments = useMemo( + () => ({ + files: attachmentFiles, + add, + remove, + clear, + openFileDialog, + fileInputRef, + }), + [attachmentFiles, add, remove, clear, openFileDialog], + ) + + const __registerFileInput = useCallback( + (ref: RefObject, open: () => void) => { + fileInputRef.current = ref.current + openRef.current = open + }, + [], + ) + + const controller = useMemo( + () => ({ + textInput: { + value: textInput, + setInput: setTextInput, + clear: clearInput, + }, + attachments, + __registerFileInput, + }), + [textInput, clearInput, attachments, __registerFileInput], + ) + + return ( + + + {children} + + + ) +} + +// ============================================================================ +// Component Context & Hooks +// ============================================================================ + +const LocalAttachmentsContext = createContext(null) + +export const usePromptInputAttachments = () => { + // Dual-mode: prefer provider if present, otherwise use local + const provider = useOptionalProviderAttachments() + const local = useContext(LocalAttachmentsContext) + const context = provider ?? local + if (!context) { + throw new Error( + 'usePromptInputAttachments must be used within a PromptInput or PromptInputProvider', + ) + } + return context +} + +export type PromptInputAttachmentProps = HTMLAttributes & { + data: FileUIPart & { id: string } + className?: string +} + +export function PromptInputAttachment({ data, className, ...props }: PromptInputAttachmentProps) { + const attachments = usePromptInputAttachments() + + const filename = data.filename || '' + + const mediaType = data.mediaType?.startsWith('image/') && data.url ? 'image' : 'file' + const isImage = mediaType === 'image' + + const attachmentLabel = filename || (isImage ? 'Image' : 'Attachment') + + return ( + + +
+
+
+ {isImage ? ( + {filename + ) : ( +
+ +
+ )} +
+ +
+ + {attachmentLabel} +
+
+ +
+ {isImage && ( +
+ {filename +
+ )} +
+
+

+ {filename || (isImage ? 'Image' : 'Attachment')} +

+ {data.mediaType && ( +

{data.mediaType}

+ )} +
+
+
+
+
+ ) +} + +export type PromptInputAttachmentsProps = Omit, 'children'> & { + children: (attachment: FileUIPart & { id: string }) => ReactNode +} + +export function PromptInputAttachments({ + children, + className, + ...props +}: PromptInputAttachmentsProps) { + const attachments = usePromptInputAttachments() + + if (!attachments.files.length) { + return null + } + + return ( +
+ {attachments.files.map((file) => ( + {children(file)} + ))} +
+ ) +} + +export type PromptInputActionAddAttachmentsProps = ComponentProps & { + label?: string +} + +export const PromptInputActionAddAttachments = ({ + label = 'Add photos or files', + ...props +}: PromptInputActionAddAttachmentsProps) => { + const attachments = usePromptInputAttachments() + + return ( + { + e.preventDefault() + attachments.openFileDialog() + }} + > + {label} + + ) +} + +export type PromptInputMessage = { + text: string + files: FileUIPart[] +} + +export type PromptInputProps = Omit, 'onSubmit' | 'onError'> & { + accept?: string // e.g., "image/*" or leave undefined for any + multiple?: boolean + // When true, accepts drops anywhere on document. Default false (opt-in). + globalDrop?: boolean + // Render a hidden input with given name and keep it in sync for native form posts. Default false. + syncHiddenInput?: boolean + // Minimal constraints + maxFiles?: number + maxFileSize?: number // bytes + onError?: (err: { code: 'max_files' | 'max_file_size' | 'accept'; message: string }) => void + onSubmit: (message: PromptInputMessage, event: FormEvent) => void | Promise +} + +export const PromptInput = ({ + className, + accept, + multiple, + globalDrop, + syncHiddenInput, + maxFiles, + maxFileSize, + onError, + onSubmit, + children, + ...props +}: PromptInputProps) => { + // Try to use a provider controller if present + const controller = useOptionalPromptInputController() + const usingProvider = !!controller + + // Refs + const inputRef = useRef(null) + const formRef = useRef(null) + + // ----- Local attachments (only used when no provider) + const [items, setItems] = useState<(FileUIPart & { id: string })[]>([]) + const files = usingProvider ? controller.attachments.files : items + + // Keep a ref to files for cleanup on unmount (avoids stale closure) + const filesRef = useRef(files) + filesRef.current = files + + const openFileDialogLocal = useCallback(() => { + inputRef.current?.click() + }, []) + + const matchesAccept = useCallback( + (f: File) => { + if (!accept || accept.trim() === '') { + return true + } + + const patterns = accept + .split(',') + .map((s) => s.trim()) + .filter(Boolean) + + return patterns.some((pattern) => { + if (pattern.endsWith('/*')) { + const prefix = pattern.slice(0, -1) // e.g: image/* -> image/ + return f.type.startsWith(prefix) + } + return f.type === pattern + }) + }, + [accept], + ) + + const addLocal = useCallback( + (fileList: File[] | FileList) => { + const incoming = Array.from(fileList) + const accepted = incoming.filter((f) => matchesAccept(f)) + if (incoming.length && accepted.length === 0) { + onError?.({ + code: 'accept', + message: 'No files match the accepted types.', + }) + return + } + const withinSize = (f: File) => (maxFileSize ? f.size <= maxFileSize : true) + const sized = accepted.filter(withinSize) + if (accepted.length > 0 && sized.length === 0) { + onError?.({ + code: 'max_file_size', + message: 'All files exceed the maximum size.', + }) + return + } + + setItems((prev) => { + const capacity = + typeof maxFiles === 'number' ? Math.max(0, maxFiles - prev.length) : undefined + const capped = typeof capacity === 'number' ? sized.slice(0, capacity) : sized + if (typeof capacity === 'number' && sized.length > capacity) { + onError?.({ + code: 'max_files', + message: 'Too many files. Some were not added.', + }) + } + const next: (FileUIPart & { id: string })[] = [] + for (const file of capped) { + next.push({ + id: nanoid(), + type: 'file', + url: URL.createObjectURL(file), + mediaType: file.type, + filename: file.name, + }) + } + return prev.concat(next) + }) + }, + [matchesAccept, maxFiles, maxFileSize, onError], + ) + + const removeLocal = useCallback( + (id: string) => + setItems((prev) => { + const found = prev.find((file) => file.id === id) + if (found?.url) { + URL.revokeObjectURL(found.url) + } + return prev.filter((file) => file.id !== id) + }), + [], + ) + + const clearLocal = useCallback( + () => + setItems((prev) => { + for (const file of prev) { + if (file.url) { + URL.revokeObjectURL(file.url) + } + } + return [] + }), + [], + ) + + const add = usingProvider ? controller.attachments.add : addLocal + const remove = usingProvider ? controller.attachments.remove : removeLocal + const clear = usingProvider ? controller.attachments.clear : clearLocal + const openFileDialog = usingProvider ? controller.attachments.openFileDialog : openFileDialogLocal + + // Let provider know about our hidden file input so external menus can call openFileDialog() + useEffect(() => { + if (!usingProvider) return + controller.__registerFileInput(inputRef, () => inputRef.current?.click()) + }, [usingProvider, controller]) + + // Note: File input cannot be programmatically set for security reasons + // The syncHiddenInput prop is no longer functional + useEffect(() => { + if (syncHiddenInput && inputRef.current && files.length === 0) { + inputRef.current.value = '' + } + }, [files, syncHiddenInput]) + + // Attach drop handlers on nearest form and document (opt-in) + useEffect(() => { + const form = formRef.current + if (!form) return + if (globalDrop) return // when global drop is on, let the document-level handler own drops + + const onDragOver = (e: DragEvent) => { + if (e.dataTransfer?.types?.includes('Files')) { + e.preventDefault() + } + } + const onDrop = (e: DragEvent) => { + if (e.dataTransfer?.types?.includes('Files')) { + e.preventDefault() + } + if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) { + add(e.dataTransfer.files) + } + } + form.addEventListener('dragover', onDragOver) + form.addEventListener('drop', onDrop) + return () => { + form.removeEventListener('dragover', onDragOver) + form.removeEventListener('drop', onDrop) + } + }, [add, globalDrop]) + + useEffect(() => { + if (!globalDrop) return + + const onDragOver = (e: DragEvent) => { + if (e.dataTransfer?.types?.includes('Files')) { + e.preventDefault() + } + } + const onDrop = (e: DragEvent) => { + if (e.dataTransfer?.types?.includes('Files')) { + e.preventDefault() + } + if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) { + add(e.dataTransfer.files) + } + } + document.addEventListener('dragover', onDragOver) + document.addEventListener('drop', onDrop) + return () => { + document.removeEventListener('dragover', onDragOver) + document.removeEventListener('drop', onDrop) + } + }, [add, globalDrop]) + + useEffect( + () => () => { + if (!usingProvider) { + for (const f of filesRef.current) { + if (f.url) URL.revokeObjectURL(f.url) + } + } + }, + // eslint-disable-next-line react-hooks/exhaustive-deps -- cleanup only on unmount; filesRef always current + [usingProvider], + ) + + const handleChange: ChangeEventHandler = (event) => { + if (event.currentTarget.files) { + add(event.currentTarget.files) + } + // Reset input value to allow selecting files that were previously removed + event.currentTarget.value = '' + } + + const convertBlobUrlToDataUrl = async (url: string): Promise => { + try { + const response = await fetch(url) + const blob = await response.blob() + return new Promise((resolve) => { + const reader = new FileReader() + reader.onloadend = () => resolve(reader.result as string) + reader.onerror = () => resolve(null) + reader.readAsDataURL(blob) + }) + } catch { + return null + } + } + + const ctx = useMemo( + () => ({ + files: files.map((item) => ({ ...item, id: item.id })), + add, + remove, + clear, + openFileDialog, + fileInputRef: inputRef, + }), + [files, add, remove, clear, openFileDialog], + ) + + const handleSubmit: FormEventHandler = (event) => { + event.preventDefault() + + const form = event.currentTarget + const text = usingProvider + ? controller.textInput.value + : (() => { + const formData = new FormData(form) + return (formData.get('message') as string) || '' + })() + + // Reset form immediately after capturing text to avoid race condition + // where user input during async blob conversion would be lost + if (!usingProvider) { + form.reset() + } + + // Convert blob URLs to data URLs asynchronously + Promise.all( + files.map(async ({ id, ...item }) => { + if (item.url && item.url.startsWith('blob:')) { + const dataUrl = await convertBlobUrlToDataUrl(item.url) + // If conversion failed, keep the original blob URL + return { + ...item, + url: dataUrl ?? item.url, + } + } + return item + }), + ) + .then((convertedFiles: FileUIPart[]) => { + try { + const result = onSubmit({ text, files: convertedFiles }, event) + + // Handle both sync and async onSubmit + if (result instanceof Promise) { + result + .then(() => { + clear() + if (usingProvider) { + controller.textInput.clear() + } + }) + .catch(() => { + // Don't clear on error - user may want to retry + }) + } else { + // Sync function completed without throwing, clear attachments + clear() + if (usingProvider) { + controller.textInput.clear() + } + } + } catch { + // Don't clear on error - user may want to retry + } + }) + .catch(() => { + // Don't clear on error - user may want to retry + }) + } + + // Render with or without local provider + const inner = ( + <> + +
+ {children} +
+ + ) + + return usingProvider ? ( + inner + ) : ( + {inner} + ) +} + +export type PromptInputBodyProps = HTMLAttributes + +export const PromptInputBody = ({ className, ...props }: PromptInputBodyProps) => ( +
+) + +export type PromptInputTextareaProps = ComponentProps + +export const PromptInputTextarea = ({ + onChange, + className, + placeholder = 'What would you like to know?', + ...props +}: PromptInputTextareaProps) => { + const controller = useOptionalPromptInputController() + const attachments = usePromptInputAttachments() + const [isComposing, setIsComposing] = useState(false) + + const handleKeyDown: KeyboardEventHandler = (e) => { + if (e.key === 'Enter') { + if (isComposing || e.nativeEvent.isComposing) { + return + } + if (e.shiftKey) { + return + } + e.preventDefault() + + // Check if the submit button is disabled before submitting + const form = e.currentTarget.form + const submitButton = form?.querySelector('button[type="submit"]') as HTMLButtonElement | null + if (submitButton?.disabled) { + return + } + + form?.requestSubmit() + } + + // Remove last attachment when Backspace is pressed and textarea is empty + if (e.key === 'Backspace' && e.currentTarget.value === '' && attachments.files.length > 0) { + e.preventDefault() + const lastAttachment = attachments.files.at(-1) + if (lastAttachment) { + attachments.remove(lastAttachment.id) + } + } + } + + const handlePaste: ClipboardEventHandler = (event) => { + const items = event.clipboardData?.items + + if (!items) { + return + } + + const files: File[] = [] + + for (const item of items) { + if (item.kind === 'file') { + const file = item.getAsFile() + if (file) { + files.push(file) + } + } + } + + if (files.length > 0) { + event.preventDefault() + attachments.add(files) + } + } + + const controlledProps = controller + ? { + value: controller.textInput.value, + onChange: (e: ChangeEvent) => { + controller.textInput.setInput(e.currentTarget.value) + onChange?.(e) + }, + } + : { + onChange, + } + + return ( + setIsComposing(false)} + onCompositionStart={() => setIsComposing(true)} + onKeyDown={handleKeyDown} + onPaste={handlePaste} + placeholder={placeholder} + {...props} + {...controlledProps} + /> + ) +} + +export type PromptInputHeaderProps = Omit, 'align'> + +export const PromptInputHeader = ({ className, ...props }: PromptInputHeaderProps) => ( + +) + +export type PromptInputFooterProps = Omit, 'align'> + +export const PromptInputFooter = ({ className, ...props }: PromptInputFooterProps) => ( + +) + +export type PromptInputToolsProps = HTMLAttributes + +export const PromptInputTools = ({ className, ...props }: PromptInputToolsProps) => ( +
+) + +export type PromptInputButtonProps = ComponentProps + +export const PromptInputButton = ({ + variant = 'ghost', + className, + size, + ...props +}: PromptInputButtonProps) => { + const newSize = size ?? (Children.count(props.children) > 1 ? 'sm' : 'icon-sm') + + return ( + + ) +} + +export type PromptInputActionMenuProps = ComponentProps +export const PromptInputActionMenu = (props: PromptInputActionMenuProps) => ( + +) + +export type PromptInputActionMenuTriggerProps = PromptInputButtonProps + +export const PromptInputActionMenuTrigger = ({ + className, + children, + ...props +}: PromptInputActionMenuTriggerProps) => ( + + + {children ?? } + + +) + +export type PromptInputActionMenuContentProps = ComponentProps +export const PromptInputActionMenuContent = ({ + className, + ...props +}: PromptInputActionMenuContentProps) => ( + +) + +export type PromptInputActionMenuItemProps = ComponentProps +export const PromptInputActionMenuItem = ({ + className, + ...props +}: PromptInputActionMenuItemProps) => + +// Note: Actions that perform side-effects (like opening a file dialog) +// are provided in opt-in modules (e.g., prompt-input-attachments). + +export type PromptInputSubmitProps = ComponentProps & { + status?: ChatStatus +} + +export const PromptInputSubmit = ({ + className, + variant = 'default', + size = 'icon-sm', + status, + children, + ...props +}: PromptInputSubmitProps) => { + let Icon = + + if (status === 'submitted') { + Icon = + } else if (status === 'streaming') { + Icon = + } else if (status === 'error') { + Icon = + } + + return ( + + {children ?? Icon} + + ) +} + +interface SpeechRecognition extends EventTarget { + continuous: boolean + interimResults: boolean + lang: string + start(): void + stop(): void + onstart: ((this: SpeechRecognition, ev: Event) => any) | null + onend: ((this: SpeechRecognition, ev: Event) => any) | null + onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => any) | null + onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => any) | null +} + +interface SpeechRecognitionEvent extends Event { + results: SpeechRecognitionResultList + resultIndex: number +} + +type SpeechRecognitionResultList = { + readonly length: number + item(index: number): SpeechRecognitionResult + [index: number]: SpeechRecognitionResult +} + +type SpeechRecognitionResult = { + readonly length: number + item(index: number): SpeechRecognitionAlternative + [index: number]: SpeechRecognitionAlternative + isFinal: boolean +} + +type SpeechRecognitionAlternative = { + transcript: string + confidence: number +} + +interface SpeechRecognitionErrorEvent extends Event { + error: string +} + +declare global { + interface Window { + SpeechRecognition: { + new (): SpeechRecognition + } + webkitSpeechRecognition: { + new (): SpeechRecognition + } + } +} + +export type PromptInputSpeechButtonProps = ComponentProps & { + textareaRef?: RefObject + onTranscriptionChange?: (text: string) => void +} + +export const PromptInputSpeechButton = ({ + className, + textareaRef, + onTranscriptionChange, + ...props +}: PromptInputSpeechButtonProps) => { + const [isListening, setIsListening] = useState(false) + const [recognition, setRecognition] = useState(null) + const recognitionRef = useRef(null) + + useEffect(() => { + if ( + typeof window !== 'undefined' && + ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) + ) { + const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition + const speechRecognition = new SpeechRecognition() + + speechRecognition.continuous = true + speechRecognition.interimResults = true + speechRecognition.lang = 'en-US' + + speechRecognition.onstart = () => { + setIsListening(true) + } + + speechRecognition.onend = () => { + setIsListening(false) + } + + speechRecognition.onresult = (event) => { + let finalTranscript = '' + + for (let i = event.resultIndex; i < event.results.length; i++) { + const result = event.results[i] + if (result.isFinal) { + finalTranscript += result[0]?.transcript ?? '' + } + } + + if (finalTranscript && textareaRef?.current) { + const textarea = textareaRef.current + const currentValue = textarea.value + const newValue = currentValue + (currentValue ? ' ' : '') + finalTranscript + + textarea.value = newValue + textarea.dispatchEvent(new Event('input', { bubbles: true })) + onTranscriptionChange?.(newValue) + } + } + + speechRecognition.onerror = (event) => { + console.error('Speech recognition error:', event.error) + setIsListening(false) + } + + recognitionRef.current = speechRecognition + setRecognition(speechRecognition) + } + + return () => { + if (recognitionRef.current) { + recognitionRef.current.stop() + } + } + }, [textareaRef, onTranscriptionChange]) + + const toggleListening = useCallback(() => { + if (!recognition) { + return + } + + if (isListening) { + recognition.stop() + } else { + recognition.start() + } + }, [recognition, isListening]) + + return ( + + + + ) +} + +export type PromptInputSelectProps = ComponentProps + +export const PromptInputSelect = (props: PromptInputSelectProps) => + ) +} + +export type WebPreviewBodyProps = ComponentProps<'iframe'> & { + loading?: ReactNode +} + +export const WebPreviewBody = ({ className, loading, src, ...props }: WebPreviewBodyProps) => { + const { url } = useWebPreview() + + return ( +
+