Open History to see the last commit
1Welcome to your new TanStack app!
2
3# Getting Started
4
5To run this application:
6
7```bash
8pnpm install
9pnpm dev
10```
11
12# Building For Production
13
14To build this application for production:
15
16```bash
17pnpm build
18```
19
20## Testing
21
22This project uses [Vitest](https://vitest.dev/) for testing. You can run the tests with:
23
24```bash
25pnpm test
26```
27
28## Styling
29
30This project uses [Tailwind CSS](https://tailwindcss.com/) for styling.
31
32# TanStack Chat Application
33
34An example chat application built with TanStack Start, TanStack Store, and **TanStack AI** (our open-source AI SDK).
35
36## .env Updates
37
38```env
39OPENAI_API_KEY=your_openai_api_key
40```
41
42No key? Open the key dialog and click **Continue with ChatGPT**. Start the app with `pnpm dev`, not `pnpm dev:vite`. `pnpm dev` also runs `scripts/serve-chatgpt-callback.mjs`, which sends the ChatGPT callback from `127.0.0.1` to `localhost`.
43
44## Trying Out Lazy Tool Discovery
45
46This example includes three **lazy tools** — tools that are not sent to the LLM upfront. Instead, the LLM sees a `__lazy__tool__discovery__` tool that lists their names. When the LLM needs one, it discovers it first (getting the full description and schema), then calls it normally.
47
48The lazy tools are: `compareGuitars`, `calculateFinancing`, and `searchGuitars`.
49
50### Test Prompts
51
52**Compare guitars** — triggers discovery of `compareGuitars`:
53
54> "Can you compare the Motherboard Guitar and the Racing Guitar for me?"
55
56**Financing** — triggers discovery of `calculateFinancing`:
57
58> "How much would it cost per month if I financed the Superhero Guitar over 12 months?"
59
60**Search** — triggers discovery of `searchGuitars`:
61
62> "Do you have any guitars with LED lights or tech features?"
63
64**Multi-discovery** — triggers discovery of multiple lazy tools at once:
65
66> "I'm looking for acoustic guitars. Can you search for them, then compare the ones you find, and show me financing options for the cheapest one?"
67
68**Self-correction** — the LLM may try calling a lazy tool directly without discovering it first. It will get an error telling it to discover first, then self-correct:
69
70> "Compare guitar 1 and guitar 4 right now"
71
72### What to watch for
73
74- The LLM calls `__lazy__tool__discovery__` before using a lazy tool for the first time
75- After discovery, the tool is called directly like any normal tool
76- In multi-turn conversations, previously discovered tools are usable immediately without re-discovery
77- If the LLM skips discovery, it gets an error and self-corrects
78
79## Generic interrupt playground
80
81Open `/generic-interrupts` to try first-party generic interrupts at each
82lifecycle phase:
83
84- `beforeModel`
85- `afterModel`
86- `beforeTools`
87- `afterTools`
88
89Pick a resume policy (`continue`, `cancel`, or `stop`). Each pause shows two
90typed cards (`reviewPlan` and `chooseAudience`). Resolve both, then watch the
91selected policy.
92
93## ✨ Features
94
95### AI Capabilities
96
97- 🤖 Powered by **TanStack AI** with OpenAI GPT-4o
98- 📝 Rich markdown formatting with syntax highlighting
99- 🎯 Customizable system prompts for tailored AI behavior
100- 🔄 Real-time streaming responses with Server-Sent Events
101- 🔌 **Connection adapters** - flexible streaming architecture
102- 🛠️ **Automatic tool execution loop** - tools are executed automatically by the SDK
103- 🎸 Tool/function calling with guitar recommendations
104
105### User Experience
106
107- 🎨 Modern UI with Tailwind CSS and Lucide icons
108- 🔍 Conversation management and history
109- 🔐 Secure API key management
110- 📋 Markdown rendering with code highlighting
111
112### Technical Features
113
114- 📦 Centralized state management with TanStack Store
115- 🔌 Extensible architecture for multiple AI providers
116- 🛠️ TypeScript for type safety
117
118## Architecture
119
120### Tech Stack
121
122- **Frontend Framework**: TanStack Start
123- **Routing**: TanStack Router
124- **State Management**: TanStack Store
125- **Styling**: Tailwind CSS
126- **AI Integration**: TanStack AI with OpenAI GPT-4o
127- **Chat Client**: `@tanstack/ai-react` with connection adapters
128- **Streaming**: Server-Sent Events via `fetchServerSentEvents`
129- **Tool Execution**: Automatic loop with `ToolCallManager`
130
131## Routing
132
133This project uses [TanStack Router](https://tanstack.com/router). The initial setup is a file based router. Which means that the routes are managed as files in `src/routes`.
134
135### Adding A Route
136
137To add a new route to your application just add another a new file in the `./src/routes` directory.
138
139TanStack will automatically generate the content of the route file for you.
140
141Now that you have two routes you can use a `Link` component to navigate between them.
142
143### Adding Links
144
145To use SPA (Single Page Application) navigation you will need to import the `Link` component from `@tanstack/react-router`.
146
147```tsx
148import { Link } from '@tanstack/react-router'
149```
150
151Then anywhere in your JSX you can use it like so:
152
153```tsx
154<Link to="/about">About</Link>
155```
156
157This will create a link that will navigate to the `/about` route.
158
159More information on the `Link` component can be found in the [Link documentation](https://tanstack.com/router/v1/docs/framework/react/api/router/linkComponent).
160
161### Using A Layout
162
163In the File Based Routing setup the layout is located in `src/routes/__root.tsx`. Anything you add to the root route will appear in all the routes. The route content will appear in the JSX where you use the `<Outlet />` component.
164
165Here is an example layout that includes a header:
166
167```tsx
168import { Outlet, createRootRoute } from '@tanstack/react-router'
169import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
170
171import { Link } from '@tanstack/react-router'
172
173export const Route = createRootRoute({
174 component: () => (
175 <>
176 <header>
177 <nav>
178 <Link to="/">Home</Link>
179 <Link to="/about">About</Link>
180 </nav>
181 </header>
182 <Outlet />
183 <TanStackRouterDevtools />
184 </>
185 ),
186})
187```
188
189The `<TanStackRouterDevtools />` component is not required so you can remove it if you don't want it in your layout.
190
191More information on layouts can be found in the [Layouts documentation](https://tanstack.com/router/latest/docs/framework/react/guide/routing-concepts#layouts).
192
193## Data Fetching
194
195There are multiple ways to fetch data in your application. You can use TanStack Query to fetch data from a server. But you can also use the `loader` functionality built into TanStack Router to load the data for a route before it's rendered.
196
197For example:
198
199```tsx
200const peopleRoute = createRoute({
201 getParentRoute: () => rootRoute,
202 path: '/people',
203 loader: async () => {
204 const response = await fetch('https://swapi.dev/api/people')
205 return response.json() as Promise<{
206 results: {
207 name: string
208 }[]
209 }>
210 },
211 component: () => {
212 const data = peopleRoute.useLoaderData()
213 return (
214 <ul>
215 {data.results.map((person) => (
216 <li key={person.name}>{person.name}</li>
217 ))}
218 </ul>
219 )
220 },
221})
222```
223
224Loaders simplify your data fetching logic dramatically. Check out more information in the [Loader documentation](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#loader-parameters).
225
226### React-Query
227
228React-Query is an excellent addition or alternative to route loading and integrating it into you application is a breeze.
229
230First add your dependencies:
231
232```bash
233pnpm add @tanstack/react-query @tanstack/react-query-devtools
234```
235
236Next we'll need to create a query client and provider. We recommend putting those in `main.tsx`.
237
238```tsx
239import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
240
241// ...
242
243const queryClient = new QueryClient()
244
245// ...
246
247if (!rootElement.innerHTML) {
248 const root = ReactDOM.createRoot(rootElement)
249
250 root.render(
251 <QueryClientProvider client={queryClient}>
252 <RouterProvider router={router} />
253 </QueryClientProvider>,
254 )
255}
256```
257
258You can also add TanStack Query Devtools to the root route (optional).
259
260```tsx
261import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
262
263const rootRoute = createRootRoute({
264 component: () => (
265 <>
266 <Outlet />
267 <ReactQueryDevtools buttonPosition="top-right" />
268 <TanStackRouterDevtools />
269 </>
270 ),
271})
272```
273
274Now you can use `useQuery` to fetch your data.
275
276```tsx
277import { useQuery } from '@tanstack/react-query'
278
279import './App.css'
280
281function App() {
282 const { data } = useQuery({
283 queryKey: ['people'],
284 queryFn: () =>
285 fetch('https://swapi.dev/api/people')
286 .then((res) => res.json())
287 .then((data) => data.results as { name: string }[]),
288 initialData: [],
289 })
290
291 return (
292 <div>
293 <ul>
294 {data.map((person) => (
295 <li key={person.name}>{person.name}</li>
296 ))}
297 </ul>
298 </div>
299 )
300}
301
302export default App
303```
304
305You can find out everything you need to know on how to use React-Query in the [React-Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview).
306
307## State Management
308
309Another common requirement for React applications is state management. There are many options for state management in React. TanStack Store provides a great starting point for your project.
310
311First you need to add TanStack Store as a dependency:
312
313```bash
314pnpm add @tanstack/store
315```
316
317Now let's create a simple counter in the `src/App.tsx` file as a demonstration.
318
319```tsx
320import { useStore } from '@tanstack/react-store'
321import { Store } from '@tanstack/store'
322import './App.css'
323
324const countStore = new Store(0)
325
326function App() {
327 const count = useStore(countStore)
328 return (
329 <div>
330 <button onClick={() => countStore.setState((n) => n + 1)}>
331 Increment - {count}
332 </button>
333 </div>
334 )
335}
336
337export default App
338```
339
340One of the many nice features of TanStack Store is the ability to derive state from other state. That derived state will update when the base state updates.
341
342Let's check this out by doubling the count using derived state.
343
344```tsx
345import { useStore } from '@tanstack/react-store'
346import { Store, Derived } from '@tanstack/store'
347import './App.css'
348
349const countStore = new Store(0)
350
351const doubledStore = new Derived({
352 fn: () => countStore.state * 2,
353 deps: [countStore],
354})
355doubledStore.mount()
356
357function App() {
358 const count = useStore(countStore)
359 const doubledCount = useStore(doubledStore)
360
361 return (
362 <div>
363 <button onClick={() => countStore.setState((n) => n + 1)}>
364 Increment - {count}
365 </button>
366 <div>Doubled - {doubledCount}</div>
367 </div>
368 )
369}
370
371export default App
372```
373
374We use the `Derived` class to create a new store that is derived from another store. The `Derived` class has a `mount` method that will start the derived store updating.
375
376Once we've created the derived store we can use it in the `App` component just like we would any other store using the `useStore` hook.
377
378You can find out everything you need to know on how to use TanStack Store in the [TanStack Store documentation](https://tanstack.com/store/latest).
379
380# Demo files
381
382Files prefixed with `demo` can be safely deleted. They are there to provide a starting point for you to play around with the features you've installed.
383
384# Learn More
385
386You can learn more about all of the offerings from TanStack in the [TanStack documentation](https://tanstack.com).
387
388## Persistent chat (`/persistent-chat`)
389
390A chat that survives a full page reload on both ends. The client writes the
391transcript to `localStorage` (via `localStoragePersistence`), so a reload
392restores the conversation instantly. The server writes the same transcript,
393run records, and interrupt state to SQLite with `withPersistence`, so it
394survives a server restart too — the DB lives at `.data/persistent-chat.db`
395(gitignored). The SQLite backend is `src/lib/sqlite-persistence.ts`, a
396self-contained `node:sqlite` store built on the `@tanstack/ai-persistence`
397core store contracts — a worked example of rolling your own adapter.
398
399Try it: send a message, wait for the reply, then reload the page. The
400conversation is still there. Needs `OPENAI_API_KEY` in `.env`.
401
402## Sandboxes — GitHub issue triage (`/sandboxes`)
403
404Pick a harness adapter (Claude Code, Codex, OpenCode) and a sandbox
405provider (Docker, local process, Vercel, Daytona, Railway), paste a GitHub **issue URL**,
406and the agent clones that repo into a sandbox, investigates read-only, and
407reports whether the bug is still relevant and its root cause — streaming tool
408calls and file activity live.
409
410### Providers
411
412- **Docker** — needs a running Docker daemon. The agent runs in a `node:22`
413 container; the harness CLI is installed on first create. Heavy investigations
414 can OOM the Docker VM (you'll see `exited with code 137`) — raise Docker
415 Desktop's memory (Settings → Resources) if so.
416- **Local process** — runs the chosen CLI directly on your host (no isolation;
417 dev only). On **Windows** the agent runs through git-bash/WSL `sh` (auto-located
418 from `git` on PATH; override with `TANSTACK_SANDBOX_SH`), since commands use
419 POSIX quoting — install Git for Windows, or set `TANSTACK_SANDBOX_SH`.
420- **Vercel** — `VERCEL_OIDC_TOKEN` (run `vercel env pull`), **or** `VERCEL_TOKEN`
421 - `VERCEL_TEAM_ID` + `VERCEL_PROJECT_ID`. (Token alone falls back to OIDC and
422 fails.) OIDC tokens are short-lived — re-pull when they expire.
423- **Daytona** — `DAYTONA_API_KEY`.
424- **Railway** — `RAILWAY_ENVIRONMENT_ID`, plus a project token in
425 `RAILWAY_TOKEN` **or** an account or workspace token in `RAILWAY_API_TOKEN`.
426
427### Harness keys
428
429Set the chosen harness's key in `.env.local` (read by the dev server):
430`ANTHROPIC_API_KEY` (Claude Code / OpenCode), `CODEX_API_KEY` (Codex).
431For **sandboxed** providers (Docker/Vercel/Daytona/Railway)
432the key is injected into the sandbox; for **local process** the host CLI uses
433your own host auth (the env key, or a `claude login`). Optional `GITHUB_TOKEN`
434for private repos / higher rate limits.
435
436### Use your Claude subscription instead of the API (no API billing)
437
438When running **Claude Code on the Local process provider**, tick **“use my
439subscription”** to bill your logged-in Claude Pro/Max account instead of the
440Anthropic API. It works by scrubbing `ANTHROPIC_API_KEY` from the spawned
441`claude`'s environment so the CLI falls back to your `claude login` credentials:
442
443```ts
444import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
445
446// Drop env vars before spawning so the host CLI uses its own stored auth.
447localProcessSandbox({ scrubEnv: ['ANTHROPIC_API_KEY'] })
448```
449
450Requires `claude login` (a Pro/Max subscription) on the host. Only local-process
451can do this — sandboxed providers have no host login, so they always use an API
452key. (The `-p` headless flag is unrelated to billing; it's just streaming mode.)
453
454### Tool bridge & code mode
455
456The triage run passes two `chat()` tools to the harness to exercise the
457**sandbox tool bridge** (host tools, called by the agent running inside the
458sandbox). The system prompt forces both before any repo work, so a broken
459bridge is obvious:
460
461- `fetchIssueComments` — a normal server tool (host fetches the issue thread).
462- `searchRelatedIssues` — exposed via **code mode**: the agent calls
463 `execute_typescript`, and the generated code invokes
464 `external_searchRelatedIssues(...)` (run on a host isolate).
465
466The bridge is a **localhost** HTTP server, so it's only directly reachable from
467same-machine providers (**local process**, **Docker**). For **remote** cloud
468sandboxes (Daytona, Vercel, Railway) the agent can't dial your laptop — set
469`NGROK_AUTHTOKEN` and the example tunnels the bridge out over ngrok so the tools
470work there too (the per-run bearer token still gates every call). Without it,
471cloud runs skip the tools and do a plain triage. In production you wouldn't need
472ngrok — your orchestrator already has a public URL to advertise.
473
474Set keys in `.env.local`, then `pnpm dev` and open `/sandboxes`.
475
476## App Studio
477
478A small product page at `/app-studio` on top of portable snapshots. You describe an app. The
479agent scaffolds a TanStack Start app in a Docker sandbox, starts the preview
480server, and shows the live URL. After the first build:
481
482- **Fork chat** copies the checkpoint and conversation into a new thread.
483 Continue from that copy. The source thread stays unchanged.
484- **Compare two directions** creates two forks. Each fork gets a different
485 visual prompt. Pick **Keep variant A** or **Keep variant B** to continue
486 on that branch.
487
488Needs:
489
490- Docker running on the host
491- `XAI_API_KEY` in `.env.local` (Grok Build runs inside the sandbox)
492
493Stay on the page during the first build. The first run installs the CLI,
494scaffolds the app, and starts the preview. If you leave, the request aborts.
495
496The snapshot store is `src/lib/sqlite-persistence.ts` at
497`.data/app-studio.db` (gitignored). The server route is `/api/app-studio`.
498The fork route is `/api/app-studio-fork`.
499
500See [Branch From a Version](../../docs/sandbox/portable-snapshots-fork.md)
501for the `snapshots.fork` contract this page uses.