From 32e648d18002ac27c2b0df3e9c5a1d69e39d54cf Mon Sep 17 00:00:00 2001 From: SweetRetry Date: Thu, 22 Oct 2026 16:15:32 +0800 Subject: [PATCH 1/2] feat(web)!: replace RFC 9457 problems with a flat { code, message } error body Every /api/* error now answers application/json with { code, message, issues?, traceId? }. issues lists failed fields only on VALIDATION_ERROR; traceId (the cf-ray id, or a random UUID locally, also logged as api.failed) comes only with INTERNAL_SERVER_ERROR. - errorResponse() in server/error-response.ts replaces problemResponse(); codes are the eight of the shared API contract, one status each. - lib/api.ts is the one client parse point (readApiError) and builds validation bodies. - PAYLOAD_TOO_LARGE (413) folds into VALIDATION_ERROR (400) with the field in issues. - A missing visitor cookie answers 401 UNAUTHORIZED instead of 400. - 429 keeps retry-after; the retryAt member is gone. - Route-level tests assert status and literal body for every error path. Co-Authored-By: Claude Opus 5.5 --- CONTEXT.md | 2 +- README.md | 4 +- README.zh.md | 4 +- apps/web/content/blog.md | 6 +- apps/web/content/blog.zh.md | 6 +- apps/web/src/components/chat/use-chat.ts | 14 +- apps/web/src/lib/api-problem.ts | 15 -- apps/web/src/lib/api.ts | 53 ++++ apps/web/src/lib/chat.ts | 20 +- .../src/routes/api/chats/$chatId/answer.ts | 9 +- .../routes/api/chats/$chatId/files/$fileId.ts | 7 +- .../src/routes/api/chats/$chatId/messages.ts | 28 +-- apps/web/src/server/api.server.ts | 26 +- apps/web/src/server/chat.server.ts | 40 ++- apps/web/src/server/error-response.ts | 18 ++ apps/web/src/server/problem.ts | 40 --- apps/web/test/api.test.ts | 235 ++++++++++++++++++ apps/web/test/chat.test.ts | 52 ++-- apps/web/test/problem.test.ts | 50 ---- docs/README.md | 2 +- docs/api.md | 54 ++-- docs/architecture.md | 2 +- docs/future/void-starter.md | 2 +- docs/observability.md | 6 +- 24 files changed, 448 insertions(+), 247 deletions(-) delete mode 100644 apps/web/src/lib/api-problem.ts create mode 100644 apps/web/src/lib/api.ts create mode 100644 apps/web/src/server/error-response.ts delete mode 100644 apps/web/src/server/problem.ts create mode 100644 apps/web/test/api.test.ts delete mode 100644 apps/web/test/problem.test.ts diff --git a/CONTEXT.md b/CONTEXT.md index 0283f54..45bc74e 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -8,7 +8,7 @@ Project vocabulary. Use these terms in requirements, designs and code names. - **Answer.** The assistant turn streamed from Workers AI through AI Gateway and saved when the stream finishes. _Avoid_: "completion". - **Reasoning.** The thinking a reasoning model streams before its answer (`reasoning_content`), saved beside the answer and shown in the thinking block. - **Attachment.** A file on a user turn. The bytes live in R2 under `chats//`; the text the model reads is saved in D1. -- **Problem.** An RFC 9457 error body from an `/api/*` route. `code` is the field clients branch on. See `docs/api.md`. +- **API error.** The `{ code, message, issues?, traceId? }` body an `/api/*` route returns with a 4xx or 5xx. Clients branch on `code` and the status, never on `message`. See `docs/api.md`. _Avoid_: problem, problem+json. - **Connect.** Linking a clone to a Cloudflare account with `pnpm connect`. Workers AI in dev and every deploy need it. - **Motif.** The registry the chat UI was copied from (`motif.sweetretry.com`). The copies under `apps/web/src/components` are now local code: maintained, trimmed and linted here, with no sync back to Motif. - **Retry.** The design language this starter ships: `DESIGN.md` is its spec, `packages/ui/src/styles/retry.css` its tokens. diff --git a/README.md b/README.md index 3b3e447..39e2b4e 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ A full-stack TypeScript starter that deploys to your own Cloudflare account with - **AI.** Workers AI models on Cloudflare's free daily allowance, so no provider key. Every call goes through AI Gateway, and reasoning models stream their thinking. - **Blog.** `/` and every post are prerendered to static HTML at build time, in English and Chinese (`/en/*`, `/zh/*`). - **UI.** Tailwind CSS v4, shadcn/ui on Base UI, the Retry design language ([DESIGN.md](DESIGN.md)), and the chat block from [Motif](https://motif.sweetretry.com). -- **Errors.** RFC 9457 problem+json on every `/api/*` route ([docs/api.md](docs/api.md)). +- **Errors.** One flat `{ code, message }` JSON body on every `/api/*` error ([docs/api.md](docs/api.md)). - **Gates.** Vite+ (format, lint, test), typecheck, knip and project rules behind one command, `pnpm verify`. `pnpm e2e` drives the app in headless Chromium. There are no accounts. A cookie gives each browser a random visitor id, and the sidebar lists that visitor's chats; other browsers get a 404. Add auth before you put anything private in it. @@ -80,7 +80,7 @@ scripts/ skill sync and the e2e runner ## Docs - [docs/architecture.md](docs/architecture.md) explains the stack and why each choice was made. -- [docs/api.md](docs/api.md) defines the error contract and every problem type. +- [docs/api.md](docs/api.md) defines the error contract and every error code. - [docs/deployment.md](docs/deployment.md) covers AI Gateway, models, usage limits and rollback. - [docs/observability.md](docs/observability.md) covers logs and traces, locally and in production. - [AGENTS.md](AGENTS.md) is the entry point for coding agents. diff --git a/README.zh.md b/README.zh.md index 01b0604..3da9934 100644 --- a/README.zh.md +++ b/README.zh.md @@ -14,7 +14,7 @@ - **AI。** 使用 Workers AI 模型,消耗 Cloudflare 每日免费额度,不需要任何供应商密钥。每次调用都经过 AI Gateway,推理模型会流式输出思考过程。 - **博客。** `/` 和每篇文章都在构建时预渲染成静态 HTML,有中英两个版本(`/en/*`、`/zh/*`)。 - **界面。** Tailwind CSS v4、基于 Base UI 的 shadcn/ui、Retry 设计语言([DESIGN.md](DESIGN.md)),以及来自 [Motif](https://motif.sweetretry.com) 的聊天组件。 -- **错误。** 每个 `/api/*` 路由都返回 RFC 9457 problem+json([docs/api.md](docs/api.md))。 +- **错误。** 每个 `/api/*` 错误都返回扁平的 `{ code, message }` JSON([docs/api.md](docs/api.md))。 - **检查。** Vite+(格式化、lint、测试)、类型检查、knip 和项目规则,统一由 `pnpm verify` 执行。`pnpm e2e` 用无头 Chromium 操作应用。 没有账号系统。每个浏览器通过 cookie 拿到一个随机访客 id,侧边栏只列出这个访客的聊天,其他浏览器访问会得到 404。放任何私密内容之前,请先加上认证。 @@ -80,7 +80,7 @@ scripts/ skill 同步和 e2e 运行器 ## 文档 - [docs/architecture.md](docs/architecture.md) 介绍技术栈和每个选择的理由。 -- [docs/api.md](docs/api.md) 定义错误约定和所有 problem 类型。 +- [docs/api.md](docs/api.md) 定义错误约定和所有错误码。 - [docs/deployment.md](docs/deployment.md) 介绍 AI Gateway、模型、用量限制和回滚。 - [docs/observability.md](docs/observability.md) 介绍本地和生产环境的日志与 trace。 - [AGENTS.md](AGENTS.md) 是编码 agent 的入口。 diff --git a/apps/web/content/blog.md b/apps/web/content/blog.md index c1190d9..536762e 100644 --- a/apps/web/content/blog.md +++ b/apps/web/content/blog.md @@ -60,15 +60,15 @@ export default defineConfig({ `POST /api/chats/:chatId/answer` streams tokens from `@cf/*` models through AI Gateway. Reasoning models stream `reasoning_content` ahead of the answer text; the Worker forwards both streams to the browser and writes the completed turn to D1. -### RFC 9457 errors +### One error body -Every `/api/*` error returns `application/problem+json` with a machine-readable `code` field and the Cloudflare `cf-ray` request ID in `instance`. +Every `/api/*` error returns a flat JSON body: a machine-readable `code` the client branches on and a `message` for the person. Validation failures list each field in `issues`; a `500` carries the Cloudflare `cf-ray` request ID as `traceId`. ## Cloudflare details ### Remote AI in dev -D1 and R2 run locally in Miniflare. Workers AI runs on Cloudflare's network and requires `pnpm connect` (`void connect --platform cloudflare`). Before connecting, model calls return a `503` Problem naming the command to run. +D1 and R2 run locally in Miniflare. Workers AI runs on Cloudflare's network and requires `pnpm connect` (`void connect --platform cloudflare`). Before connecting, model calls return a `503` error naming the command to run. ### AI Gateway diff --git a/apps/web/content/blog.zh.md b/apps/web/content/blog.zh.md index 294be7e..e0b6a04 100644 --- a/apps/web/content/blog.zh.md +++ b/apps/web/content/blog.zh.md @@ -60,15 +60,15 @@ export default defineConfig({ `POST /api/chats/:chatId/answer` 通过 Cloudflare AI Gateway 流式调用 `@cf/*` 模型。推理模型会先流式输出 `reasoning_content` 思考内容再输出正文,Worker 将两者实时转发给前端,并在流结束后一并写入 D1。 -### RFC 9457 错误契约 +### 统一错误体 -所有 `/api/*` 路由错误均返回 `application/problem+json`,包含供前端判断的 `code` 字段,并在 `instance` 中记录 Cloudflare `cf-ray` 请求 ID。 +所有 `/api/*` 路由错误均返回扁平的 JSON:供前端判断的 `code` 字段和展示给用户的 `message`。校验失败时在 `issues` 中逐字段列出;`500` 错误在 `traceId` 中带上 Cloudflare `cf-ray` 请求 ID。 ## Cloudflare 细节 ### 开发环境连接 AI -D1 和 R2 在本地由 Miniflare 运行;Workers AI 运行在云端,需先执行 `pnpm connect` (`void connect --platform cloudflare`)。未连接时调用模型会返回 `503` Problem 并提示需执行的命令。 +D1 和 R2 在本地由 Miniflare 运行;Workers AI 运行在云端,需先执行 `pnpm connect` (`void connect --platform cloudflare`)。未连接时调用模型会返回 `503` 错误并提示需执行的命令。 ### AI Gateway diff --git a/apps/web/src/components/chat/use-chat.ts b/apps/web/src/components/chat/use-chat.ts index 93ce198..8eff305 100644 --- a/apps/web/src/components/chat/use-chat.ts +++ b/apps/web/src/components/chat/use-chat.ts @@ -3,8 +3,8 @@ import { useCallback, useEffect, useRef, useState } from "react" import { toast } from "sonner" import { readAiStream } from "@/lib/ai-stream" -import { problemDetail } from "@/lib/api-problem" -import { chatPaths, sendInput, sendProblem } from "@/lib/chat" +import { readApiError } from "@/lib/api" +import { chatPaths, sendError, sendInput } from "@/lib/chat" import type { ChatFile, ChatTurn, Turn } from "@/lib/chat" import { DEFAULT_MODEL, MODELS } from "@/lib/models" @@ -43,7 +43,13 @@ export function useChat(chatId: string, saved: Turn[], savedModel?: string) { try { const response = await request() if (!response.ok || !response.body) { - toast.error(await problemDetail(response, "The message wasn't sent. Try again.")) + const error = await readApiError(response) + toast.error(error?.message ?? "The message wasn't sent. Try again.", { + // A reference the person can quote; the server logged it with the failure. + ...(error?.code === "INTERNAL_SERVER_ERROR" && { + description: `Reference: ${error.traceId}`, + }), + }) return false } for await (const event of readAiStream(response.body)) { @@ -70,7 +76,7 @@ export function useChat(chatId: string, saved: Turn[], savedModel?: string) { async (content: string, files: ChatFile[]) => { const uploads = files.flatMap((file) => (file.file ? [file.file] : [])) const input = sendInput.safeParse({ content, model, files: uploads }) - if (!input.success) return toast.error(sendProblem(input.error).detail) + if (!input.success) return toast.error(sendError(input.error).message) const userId = crypto.randomUUID() const answerId = crypto.randomUUID() diff --git a/apps/web/src/lib/api-problem.ts b/apps/web/src/lib/api-problem.ts deleted file mode 100644 index a18d3be..0000000 --- a/apps/web/src/lib/api-problem.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** The user-facing sentence from a failed `/api/*` response (RFC 9457 `detail`), or a fallback. */ -export async function problemDetail(response: Response, fallback: string): Promise { - try { - const body: unknown = await response.json() - if ( - typeof body === "object" && - body !== null && - "detail" in body && - typeof body.detail === "string" - ) { - return body.detail - } - } catch {} - return fallback -} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts new file mode 100644 index 0000000..e53fdf5 --- /dev/null +++ b/apps/web/src/lib/api.ts @@ -0,0 +1,53 @@ +import { z } from "zod" + +/** + * The `/api/*` error contract (docs/api.md): a flat `{ code, message, issues?, traceId? }` body. + * `issues` comes only with `VALIDATION_ERROR`, `traceId` only with `INTERNAL_SERVER_ERROR`. The + * routes send it through `errorResponse()`; the browser reads it only through `readApiError()`. + */ +const message = z.string() +const apiError = z.discriminatedUnion("code", [ + z.object({ + code: z.literal("VALIDATION_ERROR"), + message, + issues: z.array(z.object({ path: z.string(), message })).optional(), + }), + z.object({ code: z.literal("INTERNAL_SERVER_ERROR"), message, traceId: z.string() }), + z.object({ + code: z.enum([ + "UNAUTHORIZED", + "FORBIDDEN", + "NOT_FOUND", + "CONFLICT", + "TOO_MANY_REQUESTS", + "SERVICE_UNAVAILABLE", + ]), + message, + }), +]) + +export type ApiError = z.infer +export type ErrorCode = ApiError["code"] +type ValidationError = Extract + +/** + * A failed parse as a `VALIDATION_ERROR`, its message the first issue's. Every check carries the + * sentence the person sees; a wrong type means a caller that isn't this app's UI, so Zod's own + * wording for it gives way to `wrongType`. + */ +export function validationError(error: z.ZodError, wrongType: string): ValidationError { + const issues = error.issues.map((issue) => ({ + path: issue.path.map(String).join("."), + message: issue.code === "invalid_type" ? wrongType : issue.message, + })) + return { code: "VALIDATION_ERROR", message: issues[0]?.message ?? wrongType, issues } +} + +/** + * The error body of a failed `/api/*` response, or undefined when the body isn't one (a proxy's + * page, a cut connection). Branch on `code` and the status; show `message`, never parse it. + */ +export async function readApiError(response: Response): Promise { + const body: unknown = await response.json().catch(() => undefined) + return apiError.safeParse(body).data +} diff --git a/apps/web/src/lib/chat.ts b/apps/web/src/lib/chat.ts index 5b68b1a..8706dff 100644 --- a/apps/web/src/lib/chat.ts +++ b/apps/web/src/lib/chat.ts @@ -1,5 +1,6 @@ import { z } from "zod" +import { validationError } from "./api" import { MODELS } from "./models" /** Limits the composer and the API share. Every message that names one is built from it. */ @@ -16,8 +17,8 @@ const modelId = z.enum(MODELS.map((model) => model.id) as [string, ...string[]], /** * A user turn, as the composer checks it before sending and the API checks it on arrival. - * Each check carries the sentence the person sees; only a wrong type (a client that isn't - * the composer) falls back to Zod's own wording, which `sendProblem` replaces. + * Each check carries the sentence the person sees; a wrong type (a client that isn't the + * composer) gets the one from `sendError`. */ export const sendInput = z .object({ @@ -42,18 +43,9 @@ export const sendInput = z error: "Write a message or attach a file.", }) -/** The sentence and status class for a failed `sendInput`. */ -export function sendProblem(error: z.ZodError) { - const [issue] = error.issues - if (!issue || issue.code === "invalid_type") { - return { tooLarge: false, detail: "Send the message as form data." } - } - const fileSize = - issue.path[0] === "files" && - issue.path.length === 2 && - (issue.code === "too_big" || issue.code === "too_small") - return { tooLarge: fileSize, detail: issue.message } -} +/** A failed `sendInput` as the API's validation error, which the composer shows too. */ +export const sendError = (error: z.ZodError) => + validationError(error, "Send the message as form data.") export const regenerateInput = z.object({ model: modelId }) diff --git a/apps/web/src/routes/api/chats/$chatId/answer.ts b/apps/web/src/routes/api/chats/$chatId/answer.ts index 110bf8e..cd1f772 100644 --- a/apps/web/src/routes/api/chats/$chatId/answer.ts +++ b/apps/web/src/routes/api/chats/$chatId/answer.ts @@ -1,9 +1,10 @@ import { createFileRoute } from "@tanstack/react-router" +import { validationError } from "@/lib/api" import { chatId, regenerateInput } from "@/lib/chat" import { chatRoute } from "@/server/api.server" import { dropTrailingAnswers, streamAnswer } from "@/server/chat.server" -import { problemResponse } from "@/server/problem" +import { errorResponse } from "@/server/error-response" /** POST `{ model }` to answer the latest user turn again. The previous answer is replaced. */ export const Route = createFileRoute("/api/chats/$chatId/answer")({ @@ -11,11 +12,11 @@ export const Route = createFileRoute("/api/chats/$chatId/answer")({ handlers: { POST: chatRoute(chatId, async ({ request, params, access }) => { const input = regenerateInput.safeParse(await request.json().catch(() => null)) - if (!input.success) return problemResponse(request, "VALIDATION_ERROR", "Pick a model.") + if (!input.success) return errorResponse(validationError(input.error, "Pick a model.")) if (access === "new" || !(await dropTrailingAnswers(params.chatId))) { - return problemResponse(request, "NOT_FOUND", "There's no message to answer.") + return errorResponse({ code: "NOT_FOUND", message: "There's no message to answer." }) } - return streamAnswer(request, params.chatId, input.data.model) + return streamAnswer(params.chatId, input.data.model) }), }, }, diff --git a/apps/web/src/routes/api/chats/$chatId/files/$fileId.ts b/apps/web/src/routes/api/chats/$chatId/files/$fileId.ts index dde0bf7..35b951c 100644 --- a/apps/web/src/routes/api/chats/$chatId/files/$fileId.ts +++ b/apps/web/src/routes/api/chats/$chatId/files/$fileId.ts @@ -6,7 +6,7 @@ import { z } from "zod" import { attachment } from "../../../../../../db/schema" import { chatId, isPreviewableImage } from "@/lib/chat" import { chatRoute } from "@/server/api.server" -import { problemResponse } from "@/server/problem" +import { errorResponse } from "@/server/error-response" const fileParams = chatId.extend({ fileId: z.uuid() }) @@ -14,14 +14,15 @@ const fileParams = chatId.extend({ fileId: z.uuid() }) export const Route = createFileRoute("/api/chats/$chatId/files/$fileId")({ server: { handlers: { - GET: chatRoute(fileParams, async ({ request, params }) => { + GET: chatRoute(fileParams, async ({ params }) => { const { fileId } = params const [row] = await db .select() .from(attachment) .where(and(eq(attachment.id, fileId), eq(attachment.chatId, params.chatId))) const object = row ? await storage.get(row.key) : null - if (!(row && object)) return problemResponse(request, "NOT_FOUND", "File not found.") + if (!(row && object)) + return errorResponse({ code: "NOT_FOUND", message: "File not found." }) const headers = new Headers() object.writeHttpMetadata(headers) diff --git a/apps/web/src/routes/api/chats/$chatId/messages.ts b/apps/web/src/routes/api/chats/$chatId/messages.ts index 6dce0c7..635adbf 100644 --- a/apps/web/src/routes/api/chats/$chatId/messages.ts +++ b/apps/web/src/routes/api/chats/$chatId/messages.ts @@ -1,9 +1,9 @@ import { createFileRoute } from "@tanstack/react-router" -import { chatId, MAX_FILE_BYTES, MAX_FILES, sendInput, sendProblem } from "@/lib/chat" +import { chatId, MAX_FILE_BYTES, MAX_FILES, sendError, sendInput } from "@/lib/chat" import { chatRoute } from "@/server/api.server" import { saveUserTurn, streamAnswer } from "@/server/chat.server" -import { problemResponse } from "@/server/problem" +import { errorResponse } from "@/server/error-response" /** * POST a user turn as multipart form data (`content`, `model`, up to four `files`). Files go to @@ -16,29 +16,29 @@ export const Route = createFileRoute("/api/chats/$chatId/messages")({ // Refuse an oversized body before reading it. const declared = Number(request.headers.get("content-length") ?? 0) if (declared > MAX_FILES * MAX_FILE_BYTES + 64 * 1024) { - return problemResponse(request, "PAYLOAD_TOO_LARGE", "The message is too large to send.") + return errorResponse({ + code: "VALIDATION_ERROR", + message: "The message is too large to send.", + }) } const form = await request.formData().catch(() => null) - if (!form) - return problemResponse(request, "VALIDATION_ERROR", "Send the message as form data.") + if (!form) { + return errorResponse({ + code: "VALIDATION_ERROR", + message: "Send the message as form data.", + }) + } const input = sendInput.safeParse({ content: form.get("content"), model: form.get("model"), files: form.getAll("files"), }) - if (!input.success) { - const { tooLarge, detail } = sendProblem(input.error) - return problemResponse( - request, - tooLarge ? "PAYLOAD_TOO_LARGE" : "VALIDATION_ERROR", - detail - ) - } + if (!input.success) return errorResponse(sendError(input.error)) const { content, model, files } = input.data await saveUserTurn(params.chatId, visitor, content, files) - return streamAnswer(request, params.chatId, model) + return streamAnswer(params.chatId, model) }), }, }, diff --git a/apps/web/src/server/api.server.ts b/apps/web/src/server/api.server.ts index 64798e8..5e74b74 100644 --- a/apps/web/src/server/api.server.ts +++ b/apps/web/src/server/api.server.ts @@ -2,7 +2,7 @@ import type { z } from "zod" import type { chatId } from "@/lib/chat" import { chatAccess } from "./chat.server" -import { problemResponse } from "./problem" +import { errorResponse } from "./error-response" import { currentVisitor } from "./visitor.server" type ChatContext = { @@ -14,8 +14,8 @@ type ChatContext = { /** * Wrap a `/api/chats/$chatId/*` handler. `params` parses the path; a malformed id answers 404, - * like someone else's chat. It answers 400 without a visitor cookie, and an unexpected throw - * still leaves as problem+json carrying the ray id. + * like someone else's chat. It answers 401 without a visitor cookie, and an unexpected throw + * answers 500 with a `traceId` that the `api.failed` log carries too. */ export function chatRoute>( params: z.ZodType, @@ -23,14 +23,18 @@ export function chatRoute>( ) { return async ({ request, params: raw }: { request: Request; params: unknown }) => { const parsed = params.safeParse(raw) - if (!parsed.success) return problemResponse(request, "NOT_FOUND", "Not found.") + if (!parsed.success) return errorResponse({ code: "NOT_FOUND", message: "Not found." }) try { const visitor = currentVisitor() if (!visitor) { - return problemResponse(request, "VALIDATION_ERROR", "Reload the page to start a session.") + return errorResponse({ + code: "UNAUTHORIZED", + message: "Reload the page to start a session.", + }) } const access = await chatAccess(parsed.data.chatId, visitor) - if (access === "other") return problemResponse(request, "NOT_FOUND", "Chat not found.") + if (access === "other") + return errorResponse({ code: "NOT_FOUND", message: "Chat not found." }) return await handler({ request, params: parsed.data, visitor, access }) } catch (error) { // An Error serializes to {} in Workers Logs; keep its name, message and stack. @@ -38,8 +42,14 @@ export function chatRoute>( error instanceof Error ? { name: error.name, message: error.message, stack: error.stack } : error - console.error("api.failed", { path: new URL(request.url).pathname, error: cause }) - return problemResponse(request, "INTERNAL_SERVER_ERROR", "Something went wrong on our side.") + // The edge's ray id when there is one, so Workers Logs finds the request by it. + const traceId = request.headers.get("cf-ray") ?? crypto.randomUUID() + console.error("api.failed", { traceId, path: new URL(request.url).pathname, error: cause }) + return errorResponse({ + code: "INTERNAL_SERVER_ERROR", + message: "Something went wrong on our side.", + traceId, + }) } } } diff --git a/apps/web/src/server/chat.server.ts b/apps/web/src/server/chat.server.ts index 690f203..208c955 100644 --- a/apps/web/src/server/chat.server.ts +++ b/apps/web/src/server/chat.server.ts @@ -8,7 +8,7 @@ import { attachment, chat, message } from "../../db/schema" import { readAiStream } from "@/lib/ai-stream" import { chatPaths, isPreviewableImage, type Session, type Turn } from "@/lib/chat" import { AI_GATEWAY_ID, FILE_TEXT_CHARS, HISTORY_TURNS, SYSTEM_PROMPT } from "./ai" -import { problemResponse } from "./problem" +import { errorResponse } from "./error-response" /** Whether a chat id is free, the visitor's own, or someone else's. */ export async function chatAccess(chatId: string, visitor: string) { @@ -183,7 +183,7 @@ async function promptFor(chatId: string) { * Stream an answer to the chat's latest user turn as SSE through AI Gateway. The browser renders * the stream; a copy is read here and saved once it finishes, unless a newer turn landed first. */ -export async function streamAnswer(request: Request, chatId: string, model: string) { +export async function streamAnswer(chatId: string, model: string) { const { messages, lastId } = await promptFor(chatId) let stream: Response @@ -194,7 +194,7 @@ export async function streamAnswer(request: Request, chatId: string, model: stri { gateway: { id: AI_GATEWAY_ID } } ) } catch (error) { - return aiProblem(request, error) + return aiError(error) } const [toBrowser, toSave] = stream.body!.tee() @@ -202,32 +202,30 @@ export async function streamAnswer(request: Request, chatId: string, model: stri return new Response(toBrowser, { headers: stream.headers }) } -/** The problem response for a known way `ai.stream()` refuses; anything else rethrows. */ -function aiProblem(request: Request, error: unknown): Response { +/** The error response for a known way `ai.stream()` refuses; anything else rethrows. */ +function aiError(error: unknown): Response { // Void binds Workers AI only once the clone is connected to Cloudflare. if (error instanceof Error && error.message.startsWith("ai: Not available")) { - return problemResponse( - request, - "SERVICE_UNAVAILABLE", - "AI isn't connected yet. Run `pnpm connect`, then restart `pnpm dev`." - ) + return errorResponse({ + code: "SERVICE_UNAVAILABLE", + message: "AI isn't connected yet. Run `pnpm connect`, then restart `pnpm dev`.", + }) } // Workers AI refuses a gateway id the account hasn't created (AiGatewayError 2001). if (error instanceof Error && error.message.includes("Please configure AI Gateway")) { - return problemResponse( - request, - "SERVICE_UNAVAILABLE", - `AI Gateway "${AI_GATEWAY_ID}" doesn't exist yet. Create it in the Cloudflare dashboard under AI › AI Gateway.` - ) + return errorResponse({ + code: "SERVICE_UNAVAILABLE", + message: `AI Gateway "${AI_GATEWAY_ID}" doesn't exist yet. Create it in the Cloudflare dashboard under AI › AI Gateway.`, + }) } if (!(error instanceof UsageLimit)) throw error const retryAt = error.retryAt ? Date.parse(error.retryAt) : Number.NaN - return problemResponse(request, "TOO_MANY_REQUESTS", "AI is busy. Try again shortly.", { - ...(Number.isFinite(retryAt) && { - headers: { "retry-after": String(Math.max(1, Math.ceil((retryAt - Date.now()) / 1000))) }, - extensions: { retryAt: error.retryAt }, - }), - }) + return errorResponse( + { code: "TOO_MANY_REQUESTS", message: "AI is busy. Try again shortly." }, + Number.isFinite(retryAt) + ? { "retry-after": String(Math.max(1, Math.ceil((retryAt - Date.now()) / 1000))) } + : undefined + ) } async function saveAnswer( diff --git a/apps/web/src/server/error-response.ts b/apps/web/src/server/error-response.ts new file mode 100644 index 0000000..5adbda6 --- /dev/null +++ b/apps/web/src/server/error-response.ts @@ -0,0 +1,18 @@ +import type { ApiError, ErrorCode } from "@/lib/api" + +/** One status per code. The body carries the code; the status is what HTTP clients see. */ +const statuses = { + VALIDATION_ERROR: 400, + UNAUTHORIZED: 401, + FORBIDDEN: 403, + NOT_FOUND: 404, + CONFLICT: 409, + TOO_MANY_REQUESTS: 429, + INTERNAL_SERVER_ERROR: 500, + SERVICE_UNAVAILABLE: 503, +} as const satisfies Record + +/** The response every `/api/*` route returns on failure. See docs/api.md. */ +export function errorResponse(error: ApiError, headers?: HeadersInit): Response { + return Response.json(error, { status: statuses[error.code], headers }) +} diff --git a/apps/web/src/server/problem.ts b/apps/web/src/server/problem.ts deleted file mode 100644 index 5d715d4..0000000 --- a/apps/web/src/server/problem.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * API error contract for `/api/*` server routes: RFC 9457 Problem Details. See docs/api.md. - * - * `type` is omitted, which RFC 9457 §4.2.1 reads as `about:blank`: the HTTP status carries the - * meaning and `title` is its reason phrase. `code` is an extension member and the field clients - * branch on. `instance` is `urn:cf-ray:`, the id Workers Logs records for the request. - */ - -const problems = { - VALIDATION_ERROR: { status: 400, title: "Bad Request" }, - NOT_FOUND: { status: 404, title: "Not Found" }, - PAYLOAD_TOO_LARGE: { status: 413, title: "Content Too Large" }, - TOO_MANY_REQUESTS: { status: 429, title: "Too Many Requests" }, - INTERNAL_SERVER_ERROR: { status: 500, title: "Internal Server Error" }, - SERVICE_UNAVAILABLE: { status: 503, title: "Service Unavailable" }, -} as const - -type ErrorCode = keyof typeof problems - -/** The response every `/api/*` route returns on failure. */ -export function problemResponse( - request: Request, - code: ErrorCode, - detail: string, - init: { headers?: HeadersInit; extensions?: Record } = {} -): Response { - const { status, title } = problems[code] - const rayId = request.headers.get("cf-ray") - const body = { - title, - status, - detail, - code, - ...(rayId && { instance: `urn:cf-ray:${rayId}` }), - ...init.extensions, - } - const headers = new Headers(init.headers) - headers.set("content-type", "application/problem+json") - return new Response(JSON.stringify(body), { status, headers }) -} diff --git a/apps/web/test/api.test.ts b/apps/web/test/api.test.ts new file mode 100644 index 0000000..dbf66f1 --- /dev/null +++ b/apps/web/test/api.test.ts @@ -0,0 +1,235 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test" + +import { readApiError } from "../src/lib/api.ts" +import { DEFAULT_MODEL } from "../src/lib/models.ts" + +/** + * The `/api/*` error contract (docs/api.md), asserted through the route handlers the way a client + * hits them. Only the platform is faked: D1 answers each awaited query from `rows` in order (an + * empty result once it runs out), and `ai.stream` refuses the way Workers AI does. + */ +const platform = vi.hoisted(() => { + const state = { + visitor: undefined as string | undefined, + rows: [] as unknown[], + stream: (() => Promise.reject(new Error("unused"))) as () => Promise, + } + const query: unknown = new Proxy(() => {}, { + get: (_, key) => + key === "then" + ? (resolve: (rows: unknown) => void, reject: (error: unknown) => void) => { + const next = state.rows.shift() ?? [] + if (next instanceof Error) reject(next) + else resolve(next) + } + : () => query, + }) + class UsageLimit extends Error { + constructor(readonly retryAt?: string) { + super("AI usage limit exceeded.") + } + } + return { state, query, UsageLimit } +}) + +vi.mock("@tanstack/react-start/server", () => ({ + getCookie: () => platform.state.visitor, + setCookie: () => {}, +})) +vi.mock("cloudflare:workers", () => ({ waitUntil: () => {} })) +vi.mock("void/db", () => { + const helper = () => ({}) + return { db: platform.query, and: helper, asc: helper, desc: helper, eq: helper, gt: helper } +}) +vi.mock("void/storage", () => ({ storage: { get: async () => null, put: async () => {} } })) +vi.mock("void/ai", () => ({ ai: { stream: () => platform.state.stream() } })) +vi.mock("void/limits", () => ({ UsageLimit: platform.UsageLimit })) +vi.mock("../db/schema.ts", () => ({ chat: {}, message: {}, attachment: {} })) + +const { Route: messages } = await import("../src/routes/api/chats/$chatId/messages.ts") +const { Route: answer } = await import("../src/routes/api/chats/$chatId/answer.ts") +const { Route: file } = await import("../src/routes/api/chats/$chatId/files/$fileId.ts") + +type Handler = (context: { request: Request; params: unknown }) => Promise +const handler = (route: { options: unknown }, method: "GET" | "POST") => + (route.options as { server: { handlers: Record } }).server.handlers[method]! + +const VISITOR = "7d9c4a52-1f0e-4b8a-9f3d-2c6e8b1a0f47" +const CHAT = "0b6f3c1e-8a2d-4f7b-9c5e-1d3a7e9b2f60" +const FILE = "5e2a9c7d-3b1f-4e6a-8d0c-9f4b2a6e1c38" + +function post(path: string, body: BodyInit, headers: HeadersInit = {}) { + return new Request(`http://localhost:5173/api/chats/${CHAT}/${path}`, { + method: "POST", + body, + headers, + }) +} + +function form(fields: Record) { + const data = new FormData() + for (const [name, value] of Object.entries(fields)) data.append(name, value) + return data +} + +async function expectError(response: Response, status: number, body: unknown) { + expect(response.status).toBe(status) + expect(response.headers.get("content-type")).toBe("application/json") + expect(await response.json()).toEqual(body) +} + +const send = (request: Request, chatId = CHAT) => + handler(messages, "POST")({ request, params: { chatId } }) + +afterEach(() => { + platform.state.visitor = VISITOR + platform.state.rows = [] + platform.state.stream = () => Promise.reject(new Error("unused")) + vi.restoreAllMocks() +}) +platform.state.visitor = VISITOR + +describe("/api/chats/:chatId/*", () => { + it("answers a malformed chat id as 404, like someone else's chat", async () => { + const response = await handler( + file, + "GET" + )({ + request: new Request("http://localhost:5173/api/chats/nope/files/nope"), + params: { chatId: "nope", fileId: "nope" }, + }) + await expectError(response, 404, { code: "NOT_FOUND", message: "Not found." }) + }) + + it("answers 401 without a visitor cookie", async () => { + platform.state.visitor = undefined + await expectError(await send(post("messages", form({ content: "hi" }))), 401, { + code: "UNAUTHORIZED", + message: "Reload the page to start a session.", + }) + }) + + it("answers another visitor's chat as 404", async () => { + platform.state.rows = [[{ visitorId: "someone-else" }]] + await expectError(await send(post("messages", form({ content: "hi" }))), 404, { + code: "NOT_FOUND", + message: "Chat not found.", + }) + }) + + it("answers a missing file as 404", async () => { + platform.state.rows = [[{ visitorId: VISITOR }], []] + const response = await handler( + file, + "GET" + )({ + request: new Request(`http://localhost:5173/api/chats/${CHAT}/files/${FILE}`), + params: { chatId: CHAT, fileId: FILE }, + }) + await expectError(response, 404, { code: "NOT_FOUND", message: "File not found." }) + }) +}) + +describe("POST /api/chats/:chatId/messages", () => { + it("lists each failed field in issues, with the first as the message", async () => { + const big = new File([new Uint8Array(5 * 1024 * 1024 + 1)], "big.txt") + const response = await send(post("messages", form({ content: "", model: "gpt-9", files: big }))) + await expectError(response, 400, { + code: "VALIDATION_ERROR", + message: "Pick a model.", + issues: [ + { path: "model", message: "Pick a model." }, + { path: "files.0", message: "Files can be up to 5 MB each." }, + ], + }) + }) + + it("never shows Zod's own wording for a wrong type", async () => { + const response = await send(post("messages", form({ model: DEFAULT_MODEL, files: "text" }))) + await expectError(response, 400, { + code: "VALIDATION_ERROR", + message: "Send the message as form data.", + issues: [ + { path: "content", message: "Send the message as form data." }, + { path: "files.0", message: "Send the message as form data." }, + ], + }) + }) + + it("refuses a body over the limit before reading it", async () => { + const request = post("messages", "x", { "content-length": String(30 * 1024 * 1024) }) + await expectError(await send(request), 400, { + code: "VALIDATION_ERROR", + message: "The message is too large to send.", + }) + }) + + it("answers 503 while AI isn't connected", async () => { + platform.state.stream = () => Promise.reject(new Error("ai: Not available in this context")) + const response = await send(post("messages", form({ content: "hi", model: DEFAULT_MODEL }))) + await expectError(response, 503, { + code: "SERVICE_UNAVAILABLE", + message: "AI isn't connected yet. Run `pnpm connect`, then restart `pnpm dev`.", + }) + }) + + it("answers 429 with retry-after when a usage limit is reached", async () => { + vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-10-16T12:00:00Z")) + platform.state.stream = () => Promise.reject(new platform.UsageLimit("2026-10-16T12:00:05Z")) + const response = await send(post("messages", form({ content: "hi", model: DEFAULT_MODEL }))) + expect(response.headers.get("retry-after")).toBe("5") + await expectError(response, 429, { + code: "TOO_MANY_REQUESTS", + message: "AI is busy. Try again shortly.", + }) + }) + + it("answers an unexpected failure as 500 with the ray id as traceId, and logs it", async () => { + const log = vi.spyOn(console, "error").mockImplementation(() => {}) + platform.state.rows = [[], new Error("D1_ERROR: no such table: chat")] + const request = post("messages", form({ content: "hi", model: DEFAULT_MODEL }), { + "cf-ray": "8f1c2d3b4a5e6f70-SJC", + }) + await expectError(await send(request), 500, { + code: "INTERNAL_SERVER_ERROR", + message: "Something went wrong on our side.", + traceId: "8f1c2d3b4a5e6f70-SJC", + }) + expect(log.mock.calls[0]?.[0]).toBe("api.failed") + expect(log.mock.calls[0]?.[1]).toMatchObject({ traceId: "8f1c2d3b4a5e6f70-SJC" }) + }) +}) + +describe("POST /api/chats/:chatId/answer", () => { + const regenerate = (body: string) => + handler(answer, "POST")({ request: post("answer", body), params: { chatId: CHAT } }) + + it("asks for a model when the body isn't one", async () => { + await expectError(await regenerate("not json"), 400, { + code: "VALIDATION_ERROR", + message: "Pick a model.", + issues: [{ path: "", message: "Pick a model." }], + }) + }) + + it("answers 404 when the chat has no turn to answer", async () => { + await expectError(await regenerate(JSON.stringify({ model: DEFAULT_MODEL })), 404, { + code: "NOT_FOUND", + message: "There's no message to answer.", + }) + }) +}) + +describe("readApiError", () => { + it("reads a contract body from a failed response", async () => { + const body = { code: "INTERNAL_SERVER_ERROR", message: "Something broke.", traceId: "abc" } + expect(await readApiError(Response.json(body, { status: 500 }))).toEqual(body) + }) + + it("gives undefined for a body outside the contract", async () => { + const page = new Response("

502 Bad Gateway

", { status: 502 }) + expect(await readApiError(page)).toBeUndefined() + const legacy = Response.json({ title: "Not Found", status: 404, detail: "Gone." }) + expect(await readApiError(legacy)).toBeUndefined() + }) +}) diff --git a/apps/web/test/chat.test.ts b/apps/web/test/chat.test.ts index 8bd3e52..db553bc 100644 --- a/apps/web/test/chat.test.ts +++ b/apps/web/test/chat.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vite-plus/test" -import { sendInput, sendProblem } from "../src/lib/chat.ts" +import { sendError, sendInput } from "../src/lib/chat.ts" import { DEFAULT_MODEL } from "../src/lib/models.ts" const file = (bytes: number, name = "a.txt") => new File([new Uint8Array(bytes)], name) -const problem = (input: unknown) => { +const error = (input: unknown) => { const result = sendInput.safeParse(input) - return result.success ? null : sendProblem(result.error) + return result.success ? null : sendError(result.error) } describe("sendInput", () => { @@ -16,48 +16,38 @@ describe("sendInput", () => { expect(result.files).toHaveLength(1) }) - it("answers a file over 5 MB as too large, with the limit in the sentence", () => { + it("answers a file over 5 MB with the limit in the sentence", () => { expect( - problem({ content: "", model: DEFAULT_MODEL, files: [file(5 * 1024 * 1024 + 1)] }) + error({ content: "", model: DEFAULT_MODEL, files: [file(5 * 1024 * 1024 + 1)] }) ).toEqual({ - tooLarge: true, - detail: "Files can be up to 5 MB each.", + code: "VALIDATION_ERROR", + message: "Files can be up to 5 MB each.", + issues: [{ path: "files.0", message: "Files can be up to 5 MB each." }], }) }) - it("answers an empty file as too large, as docs/api.md says", () => { - expect(problem({ content: "x", model: DEFAULT_MODEL, files: [file(0)] })).toEqual({ - tooLarge: true, - detail: "Files can't be empty.", + it("refuses an empty file", () => { + expect(error({ content: "x", model: DEFAULT_MODEL, files: [file(0)] })).toEqual({ + code: "VALIDATION_ERROR", + message: "Files can't be empty.", + issues: [{ path: "files.0", message: "Files can't be empty." }], }) }) it("caps the number of files", () => { const files = Array.from({ length: 5 }, () => file(1)) - expect(problem({ content: "x", model: DEFAULT_MODEL, files })).toEqual({ - tooLarge: false, - detail: "Attach up to 4 files.", + expect(error({ content: "x", model: DEFAULT_MODEL, files })).toEqual({ + code: "VALIDATION_ERROR", + message: "Attach up to 4 files.", + issues: [{ path: "files", message: "Attach up to 4 files." }], }) }) it("needs text or a file", () => { - expect(problem({ content: " ", model: DEFAULT_MODEL, files: [] })).toEqual({ - tooLarge: false, - detail: "Write a message or attach a file.", - }) - }) - - it("names the model when it is unknown", () => { - expect(problem({ content: "x", model: "gpt-9", files: [] })).toEqual({ - tooLarge: false, - detail: "Pick a model.", - }) - }) - - it("never shows Zod's own wording for a wrong type", () => { - expect(problem({ content: null, model: DEFAULT_MODEL, files: ["not a file"] })).toEqual({ - tooLarge: false, - detail: "Send the message as form data.", + expect(error({ content: " ", model: DEFAULT_MODEL, files: [] })).toEqual({ + code: "VALIDATION_ERROR", + message: "Write a message or attach a file.", + issues: [{ path: "", message: "Write a message or attach a file." }], }) }) }) diff --git a/apps/web/test/problem.test.ts b/apps/web/test/problem.test.ts deleted file mode 100644 index 6c996e0..0000000 --- a/apps/web/test/problem.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { describe, expect, it } from "vite-plus/test" - -import { problemResponse } from "../src/server/problem.ts" - -describe("problemResponse", () => { - it("answers problem+json with the mapped status and the ray id as instance", async () => { - const request = new Request("https://example.com/api/chats/1", { - headers: { "cf-ray": "8f1c2d-SJC" }, - }) - const response = problemResponse(request, "NOT_FOUND", "Chat not found.") - expect(response.status).toBe(404) - expect(response.headers.get("content-type")).toBe("application/problem+json") - expect(await response.json()).toEqual({ - title: "Not Found", - status: 404, - detail: "Chat not found.", - code: "NOT_FOUND", - instance: "urn:cf-ray:8f1c2d-SJC", - }) - }) - - it("omits instance outside Cloudflare's edge", async () => { - const response = problemResponse( - new Request("http://localhost:5173/api/chats/1/messages"), - "PAYLOAD_TOO_LARGE", - "Files can be up to 5 MB each." - ) - expect(await response.json()).toEqual({ - title: "Content Too Large", - status: 413, - detail: "Files can be up to 5 MB each.", - code: "PAYLOAD_TOO_LARGE", - }) - }) - - it("keeps extra headers and extension members", async () => { - const response = problemResponse( - new Request("http://localhost:5173/api/chats/1/answer"), - "TOO_MANY_REQUESTS", - "AI is busy. Try again shortly.", - { headers: { "retry-after": "5" }, extensions: { retryAt: "2026-10-16T12:00:05Z" } } - ) - expect(response.status).toBe(429) - expect(response.headers.get("retry-after")).toBe("5") - expect(await response.json()).toMatchObject({ - code: "TOO_MANY_REQUESTS", - retryAt: "2026-10-16T12:00:05Z", - }) - }) -}) diff --git a/docs/README.md b/docs/README.md index d63da87..16fdb89 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,7 +5,7 @@ ```text docs/ architecture.md the stack, the decisions behind it, and where code lives - api.md the HTTP error contract and every problem type + api.md the HTTP error contract and every error code deployment.md Cloudflare deploy, secrets, OAuth, AI Gateway, rollback observability.md logs and traces, locally and in production guardrails.md the hooks, lint and scans that check an agent's work, and what to do when one fails diff --git a/docs/api.md b/docs/api.md index 0bb9f13..4d7cb8b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -21,42 +21,44 @@ Both streams are Workers AI's SSE. Older models send `data: {"response": "..."}` Files are served with `x-content-type-options: nosniff` and `content-security-policy: sandbox`, so an uploaded HTML or SVG file never runs on the app's origin. -There are no accounts. The first page load sets a `visitor` cookie (a random UUID, HttpOnly, one year), and the first message ties the chat to it. Every route answers `404` for a chat owned by another visitor, the same as for a missing one, and `400` when the cookie is absent. +There are no accounts. The first page load sets a `visitor` cookie (a random UUID, HttpOnly, one year), and the first message ties the chat to it. Every route answers `404` for a chat owned by another visitor, the same as for a missing one, and `401` when the cookie is absent. ## Error contract -Every `/api/*` error is an [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html) problem with the media type `application/problem+json`: +Every `/api/*` error is a 4xx or 5xx response with `content-type: application/json` and a flat body: ```json { - "title": "Not Found", - "status": 404, - "detail": "Chat not found.", - "code": "NOT_FOUND", - "instance": "urn:cf-ray:8c1f2a3b4d5e6f70-SJC" + "code": "VALIDATION_ERROR", + "message": "Files can be up to 5 MB each.", + "issues": [{ "path": "files.0", "message": "Files can be up to 5 MB each." }] } ``` -- `type` is omitted, which RFC 9457 reads as `about:blank`: the HTTP status carries the meaning and `title` is its reason phrase. -- `code` is the field a client branches on. Each code maps to exactly one status. -- `detail` is a sentence for the person using the app. It never holds stack traces, SQL or raw validation output. -- `instance` is `urn:cf-ray:` on requests through Cloudflare's edge. Workers Logs records the same id, so an error report leads to the request ([observability.md](observability.md)). -- Extension members, such as `retryAt` on a 429, may be added. Clients ignore members they don't know. - -| `code` | Status | When | -| :---------------------- | :----- | :--------------------------------------------------------------------------- | -| `VALIDATION_ERROR` | 400 | The input doesn't match the schema | -| `NOT_FOUND` | 404 | The chat id is malformed, or the file doesn't exist in that chat | -| `PAYLOAD_TOO_LARGE` | 413 | A file is over 5 MB, or empty | -| `TOO_MANY_REQUESTS` | 429 | A usage limit was reached; wait for `retry-after` seconds | -| `INTERNAL_SERVER_ERROR` | 500 | An unexpected failure; the ray id finds it in the logs | -| `SERVICE_UNAVAILABLE` | 503 | A dependency isn't configured or reachable, such as AI before `pnpm connect` | +- `code` and the status are what a client branches on. Each code maps to exactly one status. +- `message` is a sentence for the person using the app. Clients show it and never parse it. +- `issues` comes only with `VALIDATION_ERROR`: one `{ path, message }` per failed field, `path` dotted (`files.0`) and `""` for the whole input. `message` repeats the first issue. +- `traceId` comes only with `INTERNAL_SERVER_ERROR`. It is the request's `cf-ray` id through Cloudflare's edge, or a random UUID locally, and the `api.failed` log carries the same value ([observability.md](observability.md)). +- A body never holds stack traces, SQL, internal hostnames or the validation library's own wording. Headers such as `retry-after` carry anything else. + +| `code` | Status | When | +| :---------------------- | :----- | :--------------------------------------------------------------------------------------- | +| `VALIDATION_ERROR` | 400 | The input doesn't match the schema, a file is over 5 MB or empty, or the body is too big | +| `UNAUTHORIZED` | 401 | Credentials are missing, invalid or expired: today, no `visitor` cookie | +| `FORBIDDEN` | 403 | The resource is visible, but this identity may not do that. Unused today | +| `NOT_FOUND` | 404 | The chat or file doesn't exist, the id is malformed, or another visitor owns the chat | +| `CONFLICT` | 409 | The request conflicts with the resource's current state. Unused today | +| `TOO_MANY_REQUESTS` | 429 | A usage limit was reached; wait for `retry-after` seconds | +| `INTERNAL_SERVER_ERROR` | 500 | An unexpected failure; `traceId` finds it in the logs | +| `SERVICE_UNAVAILABLE` | 503 | A dependency isn't configured or reachable, such as AI before `pnpm connect` | ### Rules -1. Build every error with `problemResponse()` from `apps/web/src/server/problem.ts`. Never write error JSON by hand. -2. Wrap every `/api/chats/$chatId/*` handler in `chatRoute()` (`src/server/api.server.ts`). It answers `404` for a malformed id, and an unexpected throw still answers as problem+json and is logged as `api.failed`. -3. Success bodies carry the result directly. There is no `{ success, data }` envelope. -4. Add a code only when a client must react differently and the status alone can't tell it. A published code never changes meaning. +1. Build every error with `errorResponse()` from `apps/web/src/server/error-response.ts`, and every validation failure with `validationError()` from `src/lib/api.ts`. Never write error JSON by hand. +2. Wrap every `/api/chats/$chatId/*` handler in `chatRoute()` (`src/server/api.server.ts`). It answers `404` for a malformed id and `401` without a visitor, and an unexpected throw still answers `500` with a `traceId` and is logged as `api.failed`. +3. The browser reads an error body only through `readApiError()` in `src/lib/api.ts`. +4. Success bodies carry the result directly. There is no `{ success, data }` envelope. +5. Answer `404`, not `403`, when the caller may not know the resource exists. +6. Add a code only when a client must react differently and the status alone can't tell it. Renaming or removing a published code is a breaking change. -`apps/web/test/problem.test.ts` covers the response shape. +`apps/web/test/api.test.ts` asserts the status and body of each error through the route handlers. diff --git a/docs/architecture.md b/docs/architecture.md index 1f3ad46..67ec2a5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -54,7 +54,7 @@ Each decision names the alternative it beat, so a later change can tell whether - **Base UI under shadcn/ui.** The components were regenerated on the `base-nova` preset. Base UI has no `Form` registry item; forms use shadcn's `Field` with react-hook-form's `Controller`. - **Retry is the design language.** [DESIGN.md](../DESIGN.md) is the spec and `packages/ui/src/styles/retry.css` holds its tokens. Both are this repo's own files; change them like any other design decision. Retry's component deltas (`DESIGN.md` › Components) are baked into `packages/ui/src/components`. - **Vite+ for format, lint and test.** One toolchain (`vp fmt`, `vp lint`, `vp test`) replaces Biome, oxlint config files and a bare Vitest. `@shadcn/lint` rules run inside `vp lint`. -- **RFC 9457 for every `/api/*` error.** One helper builds every error body, and `instance` carries the `cf-ray` id, so a user's report finds the request in Workers Logs ([api.md](api.md)). +- **One flat error body for every `/api/*` error.** `{ code, message, issues?, traceId? }`, built by one helper and read by one client function. Clients branch on `code` and the status, and a `500`'s `traceId` is the `cf-ray` id, so a user's report finds the request in Workers Logs ([api.md](api.md)). ## Data and migrations diff --git a/docs/future/void-starter.md b/docs/future/void-starter.md index 3cb6e7a..8143096 100644 --- a/docs/future/void-starter.md +++ b/docs/future/void-starter.md @@ -22,7 +22,7 @@ pnpm run deploy # void deploy: D1, R2, AI binding, migrations 5. Chats and turns in D1, loaded through a server function. 6. R2 attachments with size limits, `toMarkdown` text for the model, and sandboxed downloads. 7. Streaming answers and reasoning from free Workers AI models through AI Gateway, saved when the stream finishes. -8. RFC 9457 contract on `/api/*`; Workers Logs and Traces turned on in `void.config.ts`. +8. A flat `{ code, message }` error contract on `/api/*`; Workers Logs and Traces turned on in `void.config.ts`. 9. Retry design: tokens, DESIGN.md, Base UI components with Retry deltas. 10. Docs in English: README, AGENTS.md, CONTEXT.md, docs/, rules/, scripts. diff --git a/docs/observability.md b/docs/observability.md index e891ab8..55cde9f 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -1,6 +1,6 @@ # Observability -The Worker's logs and traces are the record of what a request did. The `cf-ray` id ties a user's error report to that record: every `/api/*` error carries it as `instance: "urn:cf-ray:"` ([api.md](api.md)). +The Worker's logs and traces are the record of what a request did. The `traceId` ties a user's error report to that record: every `/api/*` `500` carries it, and the `api.failed` log holds the same value ([api.md](api.md)). Through Cloudflare's edge it is the request's `cf-ray` id. ## Logging @@ -35,7 +35,7 @@ where s.parent_id is null and l.level = 'error' order by l.ts_ms desc limit 10; ``` -Local requests have no `cf-ray`, so local errors carry no `instance`. Find them by time or path instead. +Local requests have no `cf-ray`, so a local `500` carries a random UUID as its `traceId`. Find the `api.failed` log that holds it, or search by time or path. ## Production @@ -51,6 +51,6 @@ cloudflare: { }, ``` -- **Dashboard.** Workers & Pages › your Worker › Observability shows logs and traces. Filter by the ray id from an error's `instance`. +- **Dashboard.** Workers & Pages › your Worker › Observability shows logs and traces. Filter by the ray id from an error's `traceId`. - **Live tail.** `pnpm --filter web exec void project logs` streams logs from the deployed Worker. - **AI.** AI Gateway's logs show each model call, with its latency, tokens and cache status. From ecf48ed60be61222b9668f6d0baa6f836fe43999 Mon Sep 17 00:00:00 2001 From: SweetRetry Date: Thu, 22 Oct 2026 16:16:48 +0800 Subject: [PATCH 2/2] docs(rules): move rules/ under docs/rules/ Engineering rules now live with the rest of the system knowledge. The Zod scan, knip ignore, AGENTS.md routing, READMEs, guardrails and blog layout trees point at the new path. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 ++-- README.md | 2 +- README.zh.md | 2 +- apps/web/content/blog.md | 2 +- apps/web/content/blog.zh.md | 2 +- apps/web/content/harness.md | 2 +- apps/web/content/harness.zh.md | 2 +- docs/README.md | 3 ++- docs/future/README.md | 2 +- docs/future/void-starter.md | 2 +- docs/guardrails.md | 4 ++-- {rules => docs/rules}/README.md | 2 +- {rules => docs/rules}/zod-v4/README.md | 0 {rules => docs/rules}/zod-v4/check.js | 4 ++-- {rules => docs/rules}/zod-v4/scan.js | 0 knip.json | 2 +- package.json | 2 +- 17 files changed, 19 insertions(+), 18 deletions(-) rename {rules => docs/rules}/README.md (92%) rename {rules => docs/rules}/zod-v4/README.md (100%) rename {rules => docs/rules}/zod-v4/check.js (92%) rename {rules => docs/rules}/zod-v4/scan.js (100%) diff --git a/AGENTS.md b/AGENTS.md index 2c48d6a..8357bb7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ Void Starter is a full-stack TypeScript starter in a Turborepo + pnpm workspace. ## Where things go -Route content by kind: system and usage knowledge → `docs/`; plans not decided yet → `docs/future/`; engineering constraints → `rules/`; repo tooling → `scripts/`. Read `rules/README.md` before adding or changing a rule. +Route content by kind: system and usage knowledge → `docs/`; plans not decided yet → `docs/future/`; engineering constraints → `docs/rules/`; repo tooling → `scripts/`. Read `docs/rules/README.md` before adding or changing a rule. ## Vocabulary @@ -31,7 +31,7 @@ Route content by kind: system and usage knowledge → `docs/`; plans not decided | Trigger | Read first | | :-------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------- | | Void: bindings, CLI, config, deploy | [.agents/skills/void/SKILL.md](.agents/skills/void/SKILL.md); its `docs/` live in `apps/web/node_modules/void/docs/` | -| Using Zod or changing validation | `rules/zod-v4/README.md` | +| Using Zod or changing validation | `docs/rules/zod-v4/README.md` | | Frontend UI: screens, layout, motion, components | [DESIGN.md](DESIGN.md) | | `/api/*` routes and error responses | [docs/api.md](docs/api.md) | | Env vars, secrets, deploy, AI Gateway | [docs/deployment.md](docs/deployment.md) | diff --git a/README.md b/README.md index 39e2b4e..e97bebc 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ apps/web/ TanStack Start app deployed by Void packages/ui/ shadcn/ui components and Retry tokens packages/typescript-config/ docs/ architecture, API, deployment, observability -rules/ engineering rules with their gates +docs/rules/ engineering rules with their gates scripts/ skill sync and the e2e runner ``` diff --git a/README.zh.md b/README.zh.md index 3da9934..a214bbe 100644 --- a/README.zh.md +++ b/README.zh.md @@ -61,7 +61,7 @@ apps/web/ 由 Void 部署的 TanStack Start 应用 packages/ui/ shadcn/ui 组件和 Retry 设计 token packages/typescript-config/ docs/ 架构、API、部署、可观测性 -rules/ 工程规则及其检查 +docs/rules/ 工程规则及其检查 scripts/ skill 同步和 e2e 运行器 ``` diff --git a/apps/web/content/blog.md b/apps/web/content/blog.md index 536762e..8c4532b 100644 --- a/apps/web/content/blog.md +++ b/apps/web/content/blog.md @@ -23,9 +23,9 @@ void-starter/ apps/web/ TanStack Start app, Drizzle schema, Void config packages/ui/ shadcn/ui (Base UI) + Retry tokens packages/typescript-config/ Shared TypeScript presets - rules/ Zod v4 static check scripts/ Skill sync and E2E runner docs/ Architecture, API contract, deploy and logs + docs/rules/ Engineering rules, with the Zod v4 static check ``` `apps/web` holds the routes, server functions and API endpoints. `packages/ui` exports the shared component primitives and theme tokens. diff --git a/apps/web/content/blog.zh.md b/apps/web/content/blog.zh.md index e0b6a04..ede89db 100644 --- a/apps/web/content/blog.zh.md +++ b/apps/web/content/blog.zh.md @@ -23,9 +23,9 @@ void-starter/ apps/web/ TanStack Start 应用、Drizzle Schema 与 Void 配置 packages/ui/ shadcn/ui 基础组件(Base UI)与 Retry Token packages/typescript-config/ 共享 TypeScript 编译配置 - rules/ Zod v4 静态检查 scripts/ Skill 同步与 E2E 运行脚本 docs/ 架构、API 错误契约、部署与日志文档 + docs/rules/ 工程规则,含 Zod v4 静态检查 ``` `apps/web` 包含路由、服务端函数与 API 接口;`packages/ui` 通过 `exports` 提供共享基础组件与样式 Token。 diff --git a/apps/web/content/harness.md b/apps/web/content/harness.md index da01989..5ea0670 100644 --- a/apps/web/content/harness.md +++ b/apps/web/content/harness.md @@ -63,7 +63,7 @@ Call sites pass only layout utilities (`margin`, `width`, flex and grid placemen `pnpm rules:check` runs three scripts: -- **`pnpm zod:check`** (`rules/zod-v4/check.js`): checks for deprecated Zod v3 APIs. +- **`pnpm zod:check`** (`docs/rules/zod-v4/check.js`): checks for deprecated Zod v3 APIs. - **`pnpm ui:check`** (`.agents/skills/sweet-mode/scripts/ui-guardrails.js`): checks motion, z-index, color and type bans such as `transition-all`, `ease-in` and arbitrary `z-[...]` classes. - **`pnpm skills:check`** (`scripts/agent-skills.js`): checks the copied agent skills against their sources. diff --git a/apps/web/content/harness.zh.md b/apps/web/content/harness.zh.md index 82047d3..d1e3161 100644 --- a/apps/web/content/harness.zh.md +++ b/apps/web/content/harness.zh.md @@ -63,7 +63,7 @@ rules: { `pnpm rules:check` 执行三个脚本: -- **`pnpm zod:check`** (`rules/zod-v4/check.js`):检查已废弃的 Zod v3 写法。 +- **`pnpm zod:check`** (`docs/rules/zod-v4/check.js`):检查已废弃的 Zod v3 写法。 - **`pnpm ui:check`** (`.agents/skills/sweet-mode/scripts/ui-guardrails.js`):检查动效、z-index、色值与字号禁令,如 `transition-all`、`ease-in` 与任意 `z-[...]` 类名。 - **`pnpm skills:check`** (`scripts/agent-skills.js`):检查复制进来的 agent skill 与来源一致。 diff --git a/docs/README.md b/docs/README.md index 16fdb89..2574b6b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # Docs -`docs/` answers "what is this" and "how do I use it". It is the system knowledge base for developers and agents. +`docs/` answers "what is this", "how do I use it" and "what must I follow". It is the system knowledge base for developers and agents. ```text docs/ @@ -10,6 +10,7 @@ docs/ observability.md logs and traces, locally and in production guardrails.md the hooks, lint and scans that check an agent's work, and what to do when one fails future/ plans not decided yet, each with the signal that would trigger it + rules/ engineering constraints in force, with their gates ``` Routing across the repo (docs, rules, scripts) lives in [AGENTS.md](../AGENTS.md). diff --git a/docs/future/README.md b/docs/future/README.md index 9d6a876..30fa984 100644 --- a/docs/future/README.md +++ b/docs/future/README.md @@ -4,5 +4,5 @@ Plans that are known but not decided, or not due yet. They live here so ideas do - One topic per file, named `{topic}.md`. - Each file states the problem, the candidate approaches and the signal that should trigger the work. -- Once decided, the outcome moves into `docs/` (system knowledge) or `rules/` (engineering constraints). The entry here is deleted when the work ships. +- Once decided, the outcome moves into `docs/` (system knowledge) or `docs/rules/` (engineering constraints). The entry here is deleted when the work ships. - Nothing here changes current behavior. Agents don't act on these entries. diff --git a/docs/future/void-starter.md b/docs/future/void-starter.md index 8143096..b0bd3ae 100644 --- a/docs/future/void-starter.md +++ b/docs/future/void-starter.md @@ -24,7 +24,7 @@ pnpm run deploy # void deploy: D1, R2, AI binding, migrations 7. Streaming answers and reasoning from free Workers AI models through AI Gateway, saved when the stream finishes. 8. A flat `{ code, message }` error contract on `/api/*`; Workers Logs and Traces turned on in `void.config.ts`. 9. Retry design: tokens, DESIGN.md, Base UI components with Retry deltas. -10. Docs in English: README, AGENTS.md, CONTEXT.md, docs/, rules/, scripts. +10. Docs in English: README, AGENTS.md, CONTEXT.md, docs/ (with its rules/), scripts. ## 11. Ship diff --git a/docs/guardrails.md b/docs/guardrails.md index f5b82d4..c0ac762 100644 --- a/docs/guardrails.md +++ b/docs/guardrails.md @@ -30,7 +30,7 @@ Hooks come from `lefthook.yml` and install with `pnpm install`. Pre-commit forma - `shadcn/no-unknown-classes` and `shadcn/require-static-classes` keep class names known and statically readable. - `apps/web/src/components/{agents,scroll-rail,ui}` is the app's own component library and is exempt from the color, value and inline-style rules. `no-restyle` still applies there. - **Rule scans.** `pnpm rules:check` runs three scans with no room for judgment: - - `zod:check` fails on Zod v3 patterns and deprecated APIs ([rules/zod-v4/README.md](../rules/zod-v4/README.md)). + - `zod:check` fails on Zod v3 patterns and deprecated APIs ([rules/zod-v4/README.md](rules/zod-v4/README.md)). - `ui:check` runs the [sweet-mode](../.agents/skills/sweet-mode/SKILL.md) scanner. It fails on `transition-all`, transitions on layout properties, `ease-in`, entering from `scale: 0`, z-index off the `-z-10` to `z-50` ladder, hard-coded colors in classes, and arbitrary font sizes and families. It skips `packages/ui`, `components/ui`, tests and skill directories. - `skills:check` fails when a copied skill drifted from its source. `.agents/skills/void` must match the installed `void` package byte for byte. `.agents/skills/sweet-mode` must match the hash recorded in `.agents/skills/skills-lock.json`. - **Types.** `tsc --noEmit` per workspace through Turborepo, with `strict` and `noUncheckedIndexedAccess`. In `apps/web` it runs `void prepare` first, which generates the binding types. @@ -60,4 +60,4 @@ Fix the cause the message names. Every scan prints the file, the rule and the re ## What no tool checks -Judgment stays in review: spacing optics, composition, copy, API response shape and whether a component belongs in `packages/ui`. The checklists for those are routed from [AGENTS.md](../AGENTS.md). [rules/README.md](../rules/README.md) explains why a rule becomes a scan only when its boundary is sharp. +Judgment stays in review: spacing optics, composition, copy, API response shape and whether a component belongs in `packages/ui`. The checklists for those are routed from [AGENTS.md](../AGENTS.md). [rules/README.md](rules/README.md) explains why a rule becomes a scan only when its boundary is sharp. diff --git a/rules/README.md b/docs/rules/README.md similarity index 92% rename from rules/README.md rename to docs/rules/README.md index cfb65d1..e56fd1b 100644 --- a/rules/README.md +++ b/docs/rules/README.md @@ -1,6 +1,6 @@ # Rules -`rules/` holds the engineering constraints in force, each routed from [AGENTS.md](../AGENTS.md) by its trigger. +`docs/rules/` holds the engineering constraints in force, each routed from [AGENTS.md](../../AGENTS.md) by its trigger. ## Writing a rule diff --git a/rules/zod-v4/README.md b/docs/rules/zod-v4/README.md similarity index 100% rename from rules/zod-v4/README.md rename to docs/rules/zod-v4/README.md diff --git a/rules/zod-v4/check.js b/docs/rules/zod-v4/check.js similarity index 92% rename from rules/zod-v4/check.js rename to docs/rules/zod-v4/check.js index 1561b68..39f0e00 100644 --- a/rules/zod-v4/check.js +++ b/docs/rules/zod-v4/check.js @@ -4,7 +4,7 @@ import { join, resolve } from "node:path" import { fileURLToPath } from "node:url" import { scanContent } from "./scan.js" -const repositoryRoot = resolve(fileURLToPath(new URL("../..", import.meta.url))) +const repositoryRoot = resolve(fileURLToPath(new URL("../../..", import.meta.url))) function listSourceFiles() { const output = execFileSync( @@ -21,7 +21,7 @@ function listSourceFiles() { (f) => !f.includes("node_modules") && !f.includes("/dist/") && - !f.includes("rules/zod-v4/") && + !f.includes("docs/rules/zod-v4/") && !f.startsWith("packages/ui/") ) } diff --git a/rules/zod-v4/scan.js b/docs/rules/zod-v4/scan.js similarity index 100% rename from rules/zod-v4/scan.js rename to docs/rules/zod-v4/scan.js diff --git a/knip.json b/knip.json index b8dc4fc..8b544c5 100644 --- a/knip.json +++ b/knip.json @@ -1,6 +1,6 @@ { "$schema": "https://unpkg.com/knip@6/schema.json", - "ignore": ["rules/**"], + "ignore": ["docs/rules/**"], "workspaces": { ".": { "entry": ["scripts/e2e-browser.js"], diff --git a/package.json b/package.json index 5524103..abea722 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "format:check": "vp fmt --check", "md:check": "markdownlint-cli2", "md:fix": "markdownlint-cli2 --fix", - "zod:check": "node rules/zod-v4/check.js", + "zod:check": "node docs/rules/zod-v4/check.js", "ui:check": "node .agents/skills/sweet-mode/scripts/ui-guardrails.js", "skills:check": "node scripts/agent-skills.js", "skills:update": "node scripts/agent-skills.js --update",