Open History to see the last commit
1---
2title: Id Map (Advanced)
3id: id-map
4description: "The two ids in TanStack AI. threadId is the stable key that persistence stores and restores by. runId names one execution. How to pick a threadId, when to read runId, and what to do when restore shows nothing."
5keywords:
6 - threadId
7 - runId
8 - thread id
9 - run id
10 - persistence key
11 - generation scope
12 - restore after reload
13 - useChat threadId
14 - useGenerateImage threadId
15---
16
17Persistence matches rows by the id you choose and keep stable. A new id on each load returns an empty chat or the wrong image.
18
19| Id | Names | Lifetime | Who sets it |
20| --- | --- | --- | --- |
21| `threadId` | The thing that runs belong to: a conversation, or a generation slot | As long as your app uses the same string | You, from your own data |
22| `runId` | One execution: one streamed answer, one generation job | Starts with the execution, ends with it | The library |
23
24## Set the ids
25
261. Make a `threadId` from your own data: a conversation id, a product id, a route param.
272. Pass that `threadId` to every hook that has `persistence` on.
283. Read `runId` from the hook only when you must tell your server about the work that runs now.
29
30```tsx
31import {
32 fetchServerSentEvents,
33 useChat,
34 useGenerateImage,
35} from '@tanstack/ai-react'
36
37export function ProductPage({ productId }: { productId: string }) {
38 // Chat: the thread id names a conversation.
39 const support = useChat({
40 threadId: `support-${productId}`,
41 connection: fetchServerSentEvents('/api/chat'),
42 persistence: true,
43 })
44
45 // Generation: the thread id names a slot that jobs fill.
46 const hero = useGenerateImage({
47 threadId: `product-${productId}-hero`,
48 connection: fetchServerSentEvents('/api/generate/image'),
49 persistence: true,
50 })
51
52 // Each hook also reports the id of whatever runs right now.
53 return (
54 <p>
55 chat run {support.runId ?? 'none'}, image job {hero.runId ?? 'none'}
56 </p>
57 )
58}
59```
60
61Reload the page. Each hook finds its record again, because the `threadId` strings are the same.
62
63> [!WARNING]
64> Do not put `crypto.randomUUID()` or `useId()` in a `threadId`. Each mount then gets a new key, and nothing restores.
65
66`threadId` is the only identity on chat and generation clients. There is no separate `id` option.
67
68## How it works
69
70- Persistence writes one record per `threadId`. A reload reads the record by `threadId`.
71- On `useChat`, the thread is the conversation. All runs add messages to one transcript.
72- On a generation hook, the thread is a slot. Each job gets its own record, and a reload restores the newest job in the slot.
73- A `runId` is made fresh for each execution. You never pick it.
74
75Restore starts from the thread because a page that reloaded does not know the last `runId`. It does know its `threadId`, because your app made it from a product id or a route param. So the client sends the thread. The store answers with what happened in it, plus the run that still goes on, if there is one. Only then does the client read that run's delivery log.
76
77## When restore does nothing
78
79Look for one of these causes:
80
81- **The thread id changed.** A random value in the id makes a new key on each mount. Log the id on the client and on the server, and compare the two strings.
82- **The client and the server use different ids.** The hook files under one id and the middleware under another. They must match exactly.
83- **You keyed on a run id.** A fresh page load cannot find anything by `runId` alone. Restore starts from the thread.
84- **Byte storage is off.** A generation record never holds media bytes. `status` and `error` come back, but `result` stays `null`. Add [byte storage](./keep-generated-files) to get the media back too.
85
86## Advanced
87
88### On generation, the thread is a slot
89
90A generation job does not add to anything. It makes one result. So each job gets its own record, linked to the thread. Restore gives back the most recent job for that thread: its status, its error, and its result metadata.
91
92The first attempt, the retry, and the regenerate after a prompt change all land in one slot. The latest one is what the user sees. That is why a generation thread id reads like a place in your app:
93
94| The thing on screen | A good `threadId` |
95| --- | --- |
96| The hero image for a product | `product-${productId}-hero` |
97| The start frame of a video | `video-${videoId}-start-frame` |
98| The voice-over of a chapter | `chapter-${chapterId}-narration` |
99| A transcription of an upload | `upload-${uploadId}-transcript` |
100| The support conversation | `chat-${conversationId}` |
101
102Two rules follow from "one slot, latest job wins":
103
104- **Two different things need two different ids.** If a hero-image hook and a thumbnail hook share a thread, each one restores whatever ran last, in the UI of the other.
105- **The same thing keeps its id forever.** A regenerate is a new job in the same slot, not a new slot. That is why a reload lands on the newest attempt.
106
107### On chat, a run is one turn
108
109A run is everything between one `RUN_STARTED` and its `RUN_FINISHED`. Each hook reports the run that this client has in flight, or `null` when there is none.
110
111On chat, the runs do not map one-to-one to what the user did:
112
113- **A whole tool loop is one run.** The model calls a tool, gets the result, calls another tool, and writes the answer. However many loops the [agentic cycle](../chat/agentic-cycle) takes, that is one `runId`.
114- **One user message can make several runs.** An [interrupt](../interrupts/overview) ends the run. The resume continues the same turn under a **new** `runId`. Approve two tools one after the other, and one message spans three runs.
115- **A paused run is not in flight.** While a run waits for an approval, `runId` is `null`.
116
117So `useChat().runId` tells you what this client runs now. It does not tell you which message is which. In a [live subscription](../chat/streaming), a run that another client started is not yours to cancel, so the hook does not report it.
118
119```mermaid
120flowchart TB
121 subgraph chat ["useChat, threadId: support-42"]
122 direction LR
123 c1["run r1
124tool loop, one turn"] --> c2["run r2
125interrupted"] --> c3["run r3
126the resume of that same turn"]
127 end
128
129 subgraph gen ["useGenerateImage, threadId: product-7-hero"]
130 direction LR
131 g1["job g1
132first attempt"] --> g2["job g2
133retry"] --> g3["job g3
134running"]
135 end
136
137 chat -. "one transcript, keyed by threadId" .-> cstore["messages store"]
138 gen -. "one record per job, newest restores" .-> gstore["generationRuns store"]
139```
140
141### On generation, a run is the job
142
143One call to `generate(...)` is one job with one `runId`. There is no tool loop and no interrupt, so the mapping is one-to-one. The `runId` is the handle on the provider work in progress.
144
145Send that id to your own server when you cancel. `stop()` only stops the local stream. It does not stop a video render that still costs credits at the provider:
146
147```tsx
148import { fetchServerSentEvents, useGenerateVideo } from '@tanstack/ai-react'
149
150export function VideoPanel({ videoId }: { videoId: string }) {
151 const video = useGenerateVideo({
152 threadId: `video-${videoId}-clip`,
153 connection: fetchServerSentEvents('/api/generate/video'),
154 persistence: true,
155 })
156
157 async function cancel() {
158 // Stop the provider job on the server, then drop the local stream.
159 if (video.runId) {
160 await fetch(`/api/generate/video/cancel?runId=${video.runId}`, {
161 method: 'POST',
162 })
163 }
164 video.stop()
165 }
166
167 return (
168 <button type="button" onClick={() => void cancel()} disabled={!video.runId}>
169 Cancel
170 </button>
171 )
172}
173```
174
175A durability log is keyed by the same id. So `runId` is also the right value for a log line when you follow one execution across your server. See [Threads and runs](../chat/stream-events#threads-and-runs) for the protocol and [Resumable streams](../resumable-streams/overview) for the log.
176
177### The server uses the same thread id
178
179Persistence works only when the client and the server file under the same string. On the client, that is the hook's `threadId`. On the server, it is the activity's `threadId`. For generation, the middleware reads it from the activity, so you do not repeat it on `withGenerationPersistence`:
180
181```ts
182import {
183 generateImage,
184 generationParamsFromRequest,
185 toServerSentEventsResponse,
186} from '@tanstack/ai'
187import { openaiImage } from '@tanstack/ai-openai'
188import {
189 memoryPersistence,
190 withGenerationPersistence,
191} from '@tanstack/ai-persistence'
192
193const persistence = memoryPersistence()
194
195export async function POST(request: Request) {
196 const { input, threadId } = await generationParamsFromRequest('image', request)
197
198 if (typeof input.prompt !== 'string') {
199 throw new Error('This endpoint accepts text image prompts only.')
200 }
201
202 const stream = generateImage({
203 adapter: openaiImage('gpt-image-2.5-flare'),
204 prompt: input.prompt,
205 threadId,
206 stream: true,
207 middleware: [withGenerationPersistence(persistence)],
208 })
209
210 return toServerSentEventsResponse(stream)
211}
212```
213
214The client sends its `threadId` on the wire for you, so the hook only needs the option. Chat works the same way: the `threadId` that you pass to `useChat` is the one that `chatParamsFromRequest` gives your route, and `withPersistence` stores under it. See [Chat persistence](./chat-persistence) and [Generation persistence](./generation-persistence) for the full setup.
215
216### `threadId` without persistence
217
218`threadId` is required on every hook, also without persistence. The id is also the DevTools row for the session. Without persistence, the run works, but nobody can load it again after a reload. That is fine for a one-shot image that you show and forget.
219
220With `persistence` on, the `threadId` is also the key that the run is stored under. Pass the same id to the hook and to the activity that the middleware wraps.