Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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) |
Expand Down
2 changes: 1 addition & 1 deletion CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<chatId>/<id>`; 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.
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
```

Expand All @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions README.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -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。放任何私密内容之前,请先加上认证。
Expand Down Expand Up @@ -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 运行器
```

Expand All @@ -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 的入口。
Expand Down
8 changes: 4 additions & 4 deletions apps/web/content/blog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
8 changes: 4 additions & 4 deletions apps/web/content/blog.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -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。
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion apps/web/content/harness.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion apps/web/content/harness.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 与来源一致。

Expand Down
14 changes: 10 additions & 4 deletions apps/web/src/components/chat/use-chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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)) {
Expand All @@ -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()
Expand Down
15 changes: 0 additions & 15 deletions apps/web/src/lib/api-problem.ts

This file was deleted.

53 changes: 53 additions & 0 deletions apps/web/src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -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<typeof apiError>
export type ErrorCode = ApiError["code"]
type ValidationError = Extract<ApiError, { code: "VALIDATION_ERROR" }>

/**
* 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<ApiError | undefined> {
const body: unknown = await response.json().catch(() => undefined)
return apiError.safeParse(body).data
}
20 changes: 6 additions & 14 deletions apps/web/src/lib/chat.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand All @@ -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({
Expand All @@ -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 })

Expand Down
9 changes: 5 additions & 4 deletions apps/web/src/routes/api/chats/$chatId/answer.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
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")({
server: {
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)
}),
},
},
Expand Down
Loading
Loading