Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

CONTRIBUTING.md

282 lines18.0 KB

1# Contributing to TanStack AI
2​
3Thanks for contributing! This guide covers everything you need to get from a fresh clone to a merged PR.
4​
5## Before you start
6​
7- Search the [open and closed issues](https://github.com/TanStack/ai/issues?q=is%3Aissue) and [open and closed pull requests](https://github.com/TanStack/ai/pulls?q=is%3Apr) before starting work to avoid duplicating an existing report or contribution.
8- Keep each pull request focused on one change or topic. Pull requests that combine unrelated changes will be closed with a request to split them into separately reviewable contributions.
9- Every pull request must follow the [TanStack AI pull request template](.github/pull_request_template.md). Write a concise description that clearly explains what changed and why, and complete the template without removing or bypassing its required sections.
10- You may use AI tools to help generate code, but you remain responsible for understanding, testing, and verifying every submitted change. Do not submit unreviewed, low-quality, or irrelevant generated code.
11- Do not mass-submit unrelated or low-quality AI-generated pull requests. We treat that behavior as spam and may close the pull requests, block the contributor, and report the GitHub account.
12​
13## Prerequisites
14​
15- **pnpm**: 11.9.0 or newer. Use the version pinned in `packageManager` (`pnpm@11.9.0`).
16 - Recommended: install via [Corepack](https://nodejs.org/api/corepack.html). Run `corepack enable` once and pnpm is managed automatically.
17- **Git**.
18​
19## Initial setup
20​
21```bash
22git clone https://github.com/TanStack/ai.git
23cd ai
24pnpm install
25pnpm run build:all # build all public packages once so workspace deps resolve
26```
27​
28`pnpm install` runs Playwright's chromium download (used by the E2E suite). If you don't need E2E, you can skip it via `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 pnpm install`.
29​
30## Repository layout
31​
32```
33packages/ # Public, published packages (@tanstack/ai, @tanstack/ai-openai, etc.)
34testing/ # Internal test harnesses — NOT published
35 e2e/ # Playwright + aimock E2E suite (mandatory coverage for all changes)
36 panel/ # Stream processor visualisation panel
37examples/ # Example apps (React, Solid, Vue, Svelte, vanilla)
38codemods/ # Internal codemods (not published)
39docs/ # Documentation source
40scripts/ # Repo-level scripts (doc generation, model sync, link verification, maintainer sweep)
41agent-scripts/ # Repo GitHub agents (PR review bot)
42```
43​
44- Direct children of `packages/` are public packages (published to npm).
45- Everything under `examples/`, `testing/`, and `codemods/` is `"private": true` and excluded from build/publish.
46- The build system is **Nx** with affected-target detection.
47- The package manager is **pnpm** with workspace + catalog protocols.
48​
49For deeper architecture details (adapter system, isomorphic tools, framework integrations), see `CLAUDE.md` at the repo root.
50​
51## Syncing model metadata
52​
53`pnpm generate:models` is the maintainer command behind the daily **Sync Model Metadata** workflow (branch `automated/sync-models`). It:
54​
551. Fetches OpenRouter, Vercel AI Gateway, and Lovable AI Gateway catalogs.
562. Regenerates `packages/ai-openrouter/src/model-meta.ts` and the Vercel Gateway model list.
573. Inserts **new** native-provider models into `packages/ai-openai`, `ai-anthropic`, `ai-gemini`, and `ai-grok`.
584. Writes a patch changeset for the packages that changed.
59​
60Rules the generator follows:
61​
62- Keep OpenRouter routing aliases (ids that start with `~`) in the OpenRouter catalog. Users can pass `chat({ model: '~anthropic/claude-haiku-latest' })`. The generated constant name maps `~` to `_`.
63- Do **not** copy those aliases into native provider files (`ai-openai`, `ai-anthropic`, `ai-gemini`, `ai-grok`). Those adapters only accept the provider's own ids.
64- For a new native-provider model, write id, modalities, and pricing. Infer features from OpenRouter `supported_parameters` when that field exists. Do **not** copy another model's tool list (`computer_use`, `google_search`, `x_search`, and similar).
65- Anthropic first-party ids use dashes (`claude-fable-5-1`). OpenRouter uses dots (`claude-fable-5.1`). The generator hyphenates Anthropic ids on insert. Do not copy the dotted OpenRouter slug into `ai-anthropic`.
66- Write a row in the provider's `*ChatModelToolCapabilitiesByName` map for every new chat model, even when `supports.tools` is still `[]`. Missing that row makes `ResolveToolCapabilities` fall back to `readonly []`.
67- For new Anthropic models, infer the provider-options mix from the catalog: no sampling parameters → `AnthropicMaxTokensOptions`; `reasoning.mandatory` → `AnthropicAdaptiveOnlyThinkingOptions` plus `AnthropicOutputConfigOptions`.
68- Leave curated tools and flags on existing models alone. Edit those by hand after the sync PR opens.
69​
70Do not rebase or hand-edit `automated/sync-models`. The next scheduled run force-pushes that branch from `main`. Merge generator fixes to `main` first, then let the workflow rebuild the sync PR.
71​
72The workflow pushes with `GITHUB_TOKEN`, so GitHub does not start Test / E2E on that push. After a sync, a maintainer with write access can run the PR checks from the Actions tab, or push an empty commit to `automated/sync-models`.
73​
74## Day-to-day commands
75​
76All commands are run from the repo root. Nx handles affected detection and caching.
77​
78| Goal | Command |
79| ----------------------------- | ------------------- |
80| Run unit tests (affected) | `pnpm test:lib` |
81| Watch unit tests | `pnpm test:lib:dev` |
82| Type-check (affected) | `pnpm test:types` |
83| Lint (affected) | `pnpm test:oxlint` |
84| Verify build artifacts | `pnpm test:build` |
85| Format the repo | `pnpm format` |
86| Build (affected) | `pnpm build` |
87| Build everything | `pnpm build:all` |
88| Run the full CI suite locally | `pnpm test` |
89| Run the affected-PR check | `pnpm test:pr` |
90| E2E suite | `pnpm test:e2e` |
91| E2E with Playwright UI | `pnpm test:e2e:ui` |
92​
93Working on a single package? `cd packages/<pkg>` and use its scripts directly (`pnpm test:lib`, `pnpm test:types`, etc.).
94​
95### Faster local runs
96​
97Root `pnpm test`, `pnpm test:pr`, and `pnpm test:lib` set `VITEST_MAX_WORKERS=1`. Nx runs 4 tasks at a time (`nx.json` `parallel`). Together that stops each package from spawning one Vitest worker per CPU core while 15 packages already run in parallel.
98​
99A single package still uses all cores:
100​
101```bash
102cd packages/ai
103pnpm test:lib
104```
105​
106Local `pnpm test:e2e` runs openai, anthropic, and gemini. If none of those providers support a feature, the feature still runs on the providers that do. An explicit `E2E_PROVIDERS` list runs only those providers. CI always runs the full matrix.
107​
108```bash
109E2E_PROVIDERS=* pnpm test:e2e # full matrix locally
110E2E_PROVIDERS=grok pnpm test:e2e # one provider
111```
112​
113Playwright does not retry or record video locally. CI retries twice and keeps the video of a failed test.
114​
115## Coverage
116​
117**Coverage runs in CI only. It is not part of `pnpm test`, `pnpm test:pr`, or any git hook, and you are not expected to run it locally.**
118​
119The `Coverage` job on every PR measures each affected package that has a `test:coverage` target twice: once on your branch and once on its merge-base with `main`. A drop of more than 0.5 percentage points in any metric (statements, branches, functions, lines) fails the job. Packages your PR didn't affect, and packages without that target, are never measured.
120​
121There is no baseline file to keep in sync, and nothing to update when a package is added or removed: both numbers come from the same job on the same runner. There are also no target percentages to hit — the gate only catches coverage getting _worse_ in what you touched, and never blocks a PR for being below some repo-wide bar.
122​
123Read the numbers from the PR's Checks tab: open the `Coverage` job. When at least one package with `test:coverage` is affected, the job summary has a per-package table with deltas, pass or fail. It is not posted as a PR comment.
124​
125Re-measuring the merge-base is usually close to free. On every push to `main`, a separate `Coverage` workflow runs `test:coverage` for every package with the same forwarded args as the PR job, and fills the Nx Cloud cache. `test:coverage` declares its `coverage/` directory as a task output, so the base-side run restores the cached summaries and does not run the tests again. If that workflow did not finish for the merge-base commit (for example, a newer push to `main` cancelled it), the base-side tests run again. Keep the `--` args in `coverage.yml` and `pr.yml` identical: Nx hashes them, so any difference causes a cache miss.
126​
127### If the job says coverage dropped
128​
129Add tests covering the code you changed. That's the whole remedy — there is no number to override. If you genuinely deleted well-tested code and the drop is expected, say so in the PR and a maintainer can merge past the failing check.
130​
131Two known limitations:
132​
133- Uncovered `.tsx` files can't be remapped by the coverage provider and are dropped from the report with a `Failed to parse ... Excluding it from coverage` warning. `.tsx` files that tests _do_ load are measured normally, so the UI packages read higher than their real coverage.
134- `ai-react-ui`, `ai-solid-ui`, `ai-vue-ui`, `preact-ai-devtools`, `react-ai-devtools`, `solid-ai-devtools`, and `svelte-ai-devtools` have no tests, so they have no `test:coverage` script. The collect step fails when a measured package reports 0 statements. Add the script back when the package gets tests.
135​
136A **new package that defines `test:coverage`** shows as `new` and cannot fail the comparison. Packages without that script are not measured.
137​
138If a package was measured on the base commit and has no summary on this PR, the job fails. A crashing `test:coverage` suite on either side also fails the job. It is not treated as `new`.
139​
140## Generate a React playground
141​
142You need a TanStack Start chat app to try a feature. Do not copy `examples/ts-react-chat`. Run the generator.
143​
1441. From the repo root, run `pnpm nx g @tanstack/workspace-plugin:react-app <name>`.
1452. Run `pnpm install`.
1463. Copy `examples/<name>/.env.example` to `examples/<name>/.env.local` and add a key.
1474. Run `pnpm --filter <name> dev` (port 3100).
1485. Change the index route for the feature. If the server must change, change `/api/chat`.
149​
150Do not commit the new example unless you mean to keep it as a lasting example.
151​
152## TypeScript configuration
153​
154There is a single `tsconfig.base.json` at the repo root with the shared `compilerOptions`. Every package extends it and overrides only what's unique to that package (e.g. `outDir`, JSX runtime, framework lib).
155​
156The standardised per-package shape is:
157​
158```jsonc
160 "extends": "../../../tsconfig.base.json",
161 "compilerOptions": {
162 "outDir": "dist",
163 // + package-specific overrides only
164 },
165 "include": ["src", "tests"],
166 "exclude": ["node_modules", "dist"],
168```
169​
170Tests are included in typecheck. `vite.config.ts` / `vitest.config.ts` are not — they're tooling configs typechecked by the build tools themselves.
171​
172## Adding a unit test
173​
174- Place tests under `packages/<pkg>/tests/` with the suffix `.test.ts` (or `.test.tsx` for JSX).
175- Vitest's defaults discover anything matching `**/*.{test,spec}.?(c|m)[jt]s?(x)` — no per-package config is needed.
176- Tests are typechecked by `tsc` and linted by oxlint.
177​
178## Adding E2E test coverage (required)
179​
180**Every feature, bug fix, or behaviour change MUST have E2E coverage.** See `testing/e2e/README.md` for the full guide. Quick reference:
181​
182| Change type | What to add |
183| -------------------------------------- | ------------------------------------------------------------------------ |
184| New provider adapter | Add provider to `feature-support.ts` + `test-matrix.ts`. Tests auto-run. |
185| New feature (e.g. new generation type) | Add to types, feature config, support matrix, fixture, spec file. |
186| Chat / streaming bug fix | Test case in `chat.spec.ts` or `tools-test/`. |
187| Tool system change | Scenario in `tools-test-scenarios.ts` + spec. |
188| Middleware change | Test in `middleware.spec.ts`. |
189| Client-side change (useChat etc.) | Test covering the observable behavior change. |
190​
191Run the suite locally with `pnpm test:e2e`. Record real LLM fixtures with `OPENAI_API_KEY=sk-... pnpm --filter @tanstack/ai-e2e record`.
192​
193## Documentation (required when relevant)
194​
195If the change is user-facing, update `docs/` in the same PR. Do not ship the code now and the docs later.
196​
197User-facing means a caller can see or do something new or different:
198​
199- New or changed public API (exports, types, flags, env vars)
200- New or changed behaviour
201- New adapter capability
202- Changed defaults, errors, or documented contracts
203​
204Skip docs only when nothing user-facing changed (CI, internal tests, same-behaviour refactors, agent files). Write that reason in the PR body.
205​
206## Changesets (required on the PR)
207​
208Any PR that changes a published package MUST include a changeset file on that PR. Run this before you open the PR:
209​
210```bash
211pnpm changeset
212```
213​
214Pick the affected packages and the bump type:
215​
216- **patch**: bug fix, internal refactor, perf, docs in package, no API change.
217- **minor**: new public API, new opt-in behaviour, backwards-compatible enhancement.
218- **major**: breaking change to a published API surface. Coordinate with maintainers first.
219​
220Do not add the changeset after review as a follow-up. It belongs in the first push of the PR.
221​
222Skip a changeset only when the PR does not change published packages (docs, CI, examples, testing, contributing). Tick the docs/CI/dev-only box on the PR template.
223​
224The defensive `ignore` list in `.changeset/config.json` blocks accidental publication from examples/testing/codemods even if `"private": true` is ever dropped.
225​
226## Branches and commits
227​
228- Branch off `main`. Name the branch after the change (`fix/openai-streaming-eof`, `feat/anthropic-cache-control`).
229- Conventional Commits aren't strictly enforced, but follow the prefixes you see in `git log`: `feat:`, `fix:`, `docs:`, `refactor:`, `chore:`, `ci:`.
230- Keep commits logical. The repo prefers a few coherent commits over one giant squash.
231​
232## Pull request flow
233​
2341. Push your branch and open a PR against `main`.
2352. Fill the PR template. Tick **docs** and **changeset** honestly, or say why you skipped them.
2363. CI runs: `pnpm test:pr` (sherif workspace check, knip dead-code, docs link verification, oxlint, unit tests, typecheck, build artifacts, build), the `Coverage` regression gate, and the full E2E suite.
2374. Address review comments.
2385. A maintainer merges. Releases are cut via Changesets. Your changeset entry lands in the next release.
239​
240The PR template lists the steps. The `Test plan` section is required — describe how a reviewer can verify your change.
241​
242### Automated Grok review
243​
244A Grok agent comments on open, non-draft PRs. The first lines of that comment say it is automated. It is not a maintainer review.
245​
246The bot sets exactly one of these labels:
247​
248- `ai-rejected` — the change is not useful, or it does not fix the claimed bug.
249- `ai-needs-work` — the review listed fixes, but they are not on the branch yet (often a fork with maintainer edits off).
250- `ai-ready` — the bot thinks a maintainer can merge after they Approve.
251​
252The bot never GitHub-approves and never merges. The `ready-to-merge` label still means a human approval plus green CI.
253​
254If the bot pushes, it only commits bugs and suggestions the review listed. Maintainers start a new run with a `/ai-review` comment, or from Actions (`workflow_dispatch`).
255​
256## Adding a new provider adapter
257​
258The pattern lives in `packages/ai-openai/`, `packages/ai-anthropic/`, `packages/ai-gemini/`, etc. New core adapters typically:
259​
2601. Create `packages/ai-<provider>/` with `package.json`, `tsconfig.json`, `src/`, `tests/`, `README.md`. Copy structure from an existing adapter. The README must start with the TanStack AI `<picture>` banner from `packages/ai/README.md` (`https://tanstack.com/api/readme/ai.png`). Do not use `media/header_ai.png`.
2612. Implement tree-shakeable adapter exports under `src/adapters/` (`text.ts`, `embed.ts`, `summarize.ts`, etc.).
2623. Add `model-meta.ts` so per-model type safety works.
2634. Wire the provider into `testing/e2e/feature-support.ts` and `testing/e2e/test-matrix.ts`. Existing provider-coverage tests pick it up automatically.
2645. Record fixtures (`OPENAI_API_KEY=... pnpm --filter @tanstack/ai-e2e record`) — or write deterministic ones by hand. **No real API keys at test time.**
2656. Update `docs/` for the adapter, and add a `pnpm changeset` entry on the same PR.
266​
267If you're building a community/third-party adapter that lives outside this repo, follow `docs/community-adapters/guide.md` instead.
268​
269## Known gaps
270​
271- **Vue/Svelte SFCs are not currently linted.** Our linter doesn't yet support `.vue`/`.svelte` parsers in the toolchain we use; the script blocks inside those files rely on TypeScript and tests for safety. If you're touching a `.svelte` or `.vue` file, lean on `tsc` / `svelte-check` / `vue-tsc` and explicit tests.
272- **Build configs (`vite.config.ts`, `vitest.config.ts`) are not in the `tsc` typecheck pass.** They're typechecked at build time by vite/vitest themselves. If you make changes there, run `pnpm build` or `pnpm test:lib` to surface issues.
273​
274## Reporting issues / getting help
275​
276- Bugs: first search the [open and closed issues](https://github.com/TanStack/ai/issues?q=is%3Aissue), then use the [bug report template](https://github.com/TanStack/ai/issues/new?template=bug_report.yml) with a minimal reproduction if the bug has not already been reported.
277- Questions / discussions: [TanStack Discord](https://tlinz.com/discord).
278- Security: follow the disclosure process in `SECURITY.md` (if applicable) or email the maintainers directly.
279​
280## Code of Conduct
281​
282By participating you agree to abide by our [Code of Conduct](./CODE_OF_CONDUCT.md).