Open History to see the last commit
1---
2title: Id Map (Advanced)
3id: id-map
4description: "The two ids in TanStack AI and what each one means: threadId is the stable key persistence stores and restores by, runId names one execution. What they mean on useChat versus the generation hooks, how to choose a threadId, and when to read runId."
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
17There are only two ids to know, and mixing them up is what makes persistence look
18broken.
19
20| Id | Names | Lifetime | You provide it |
21| --- | --- | --- | --- |
22| `threadId` | the thing runs belong to: a conversation, or a generation slot | as long as your app keeps using the same string | yes, from your own domain |
23| `runId` | one execution: one streamed answer, one generation job | minted at the start, dead when it ends | no, it is minted for you |
24
25Persistence stores and restores by `threadId`. `runId` is what you read when you
26need to talk to your own server about the execution happening right now.
27
28If you omit `threadId`, the client mints one after the view mounts. That
29ephemeral id is the wire thread and the DevTools row for this session. A reload
30starts a new conversation. Persistence needs an explicit `threadId` from your
31app.
32
33Do not pass a separate `id`. `threadId` is the only identity on chat and
34generation clients.
35
36```tsx
37import {
38 fetchServerSentEvents,
39 useChat,
40 useGenerateImage,
41} from '@tanstack/ai-react'
42
43export function ProductPage({ productId }: { productId: string }) {
44 // Chat: the thread id names a conversation.
45 const support = useChat({
46 threadId: `support-${productId}`,
47 connection: fetchServerSentEvents('/api/chat'),
48 persistence: true,
49 })
50
51 // Generation: the thread id names a slot that jobs fill.
52 const hero = useGenerateImage({
53 threadId: `product-${productId}-hero`,
54 connection: fetchServerSentEvents('/api/generate/image'),
55 persistence: true,
56 })
57
58 // Each hook also reports the id of whatever is running right now.
59 return (
60 <p>
61 chat run {support.runId ?? 'none'}, image job {hero.runId ?? 'none'}
62 </p>
63 )
64}
65```
66
67## `threadId`: the key everything is filed under
68
69A record is written **per `threadId`** and a reload looks it up **by
70`threadId`**. If the string is not identical after the reload, there is nothing to
71find. Pick it from your own domain, keep it stable, and restore works. Mint a
72fresh one on every mount and nothing ever restores.
73
74### On chat, the thread is the conversation
75
76Every run in it contributes messages to one growing transcript, stored under the
77thread id. Restoring means replaying that transcript. Runs are internal detail the
78user never sees, they just see the conversation.
79
80### On generation, the thread is a slot
81
82A generation job does not append to anything, it produces one result. So each job
83gets its own record, linked to the thread, and restore hands back the **most
84recent** job for that thread: its status, its error, its result metadata.
85Successive jobs for the same thing (the first attempt, the retry, the regenerate
86after a prompt tweak) all land in one slot, and the latest one is what the user is
87looking at.
88
89That is why generation thread ids read like a place in your app rather than a
90conversation:
91
92| The thing on screen | A good `threadId` |
93| --- | --- |
94| The hero image for a product | `product-${productId}-hero` |
95| The start frame of a video | `video-${videoId}-start-frame` |
96| The voice-over of a chapter | `chapter-${chapterId}-narration` |
97| A transcription of an upload | `upload-${uploadId}-transcript` |
98| The support conversation | `chat-${conversationId}` |
99
100Two rules follow from "one slot, latest job wins":
101
102- **Two different things need two different ids.** Point a hero-image hook and a
103 thumbnail hook at the same thread and each restores whatever ran last, in the
104 other's UI.
105- **The same thing keeps its id forever.** A regenerate is a new job in the same
106 slot, not a new slot. That is what makes a reload land on the newest attempt.
107
108## `runId`: one execution
109
110A run is everything between one `RUN_STARTED` and its `RUN_FINISHED`. It is minted
111fresh each time and thrown away when it ends. Both kinds of hook report the one
112this client has in flight, or `null` when there is none.
113
114### On chat, a run is one turn
115
116It changes from turn to turn, and the mapping to what the user did is not
117one-to-one:
118
119- **A whole tool loop is one run.** The model calls a tool, you return a result,
120 it calls another, it writes the final answer. However many loops the
121 [agentic cycle](../chat/agentic-cycle) takes, that is a single `runId`.
122- **One user message can produce several runs.** Pausing on an
123 [interrupt](../interrupts/overview) ends the run; resuming continues the same
124 turn under a **new** `runId`. Approve two tools in sequence and one message has
125 spanned three runs. While the run sits paused waiting on that approval, nothing
126 is in flight, so `runId` is `null`.
127
128So `useChat().runId` answers "what is this client running right now", never
129"which message is this". In a [live subscription](../chat/streaming), a run
130another client started is not yours to cancel, so it is not reported here.
131
132```mermaid
133flowchart TB
134 subgraph chat ["useChat, threadId: support-42"]
135 direction LR
136 c1["run r1
137tool loop, one turn"] --> c2["run r2
138interrupted"] --> c3["run r3
139the resume of that same turn"]
140 end
141
142 subgraph gen ["useGenerateImage, threadId: product-7-hero"]
143 direction LR
144 g1["job g1
145first attempt"] --> g2["job g2
146retry"] --> g3["job g3
147running"]
148 end
149
150 chat -. "one transcript, keyed by threadId" .-> cstore["messages store"]
151 gen -. "one record per job, newest restores" .-> gstore["generationRuns store"]
152```
153
154### On generation, a run is the job
155
156One call to `generate(...)` is one job with one `runId`. There is no tool loop and
157no interrupt, so the mapping is exactly one-to-one: `runId` is the handle on the
158provider work currently in progress.
159
160That makes it the id you hand your own server, because `stop()` only aborts the
161local stream. It does not stop a video render already burning credits on the
162provider:
163
164```tsx
165import { fetchServerSentEvents, useGenerateVideo } from '@tanstack/ai-react'
166
167export function VideoPanel({ videoId }: { videoId: string }) {
168 const video = useGenerateVideo({
169 threadId: `video-${videoId}-clip`,
170 connection: fetchServerSentEvents('/api/generate/video'),
171 persistence: true,
172 })
173
174 async function cancel() {
175 // Stop the provider job server-side, then drop the local stream.
176 if (video.runId) {
177 await fetch(`/api/generate/video/cancel?runId=${video.runId}`, {
178 method: 'POST',
179 })
180 }
181 video.stop()
182 }
183
184 return (
185 <button type="button" onClick={() => void cancel()} disabled={!video.runId}>
186 Cancel
187 </button>
188 )
189}
190```
191
192The same id is what a durability log is keyed by, so it is also the right thing to
193put in a log line when you are chasing one execution across your server.
194
195## Why restore keys on the thread, not the run
196
197A page that just reloaded has no idea what the last `runId` was, so it cannot ask
198for it. It does know its `threadId`, because your app derived it from a product
199id, a route param, a video id. So the client presents the thread, and the store
200answers "here is what happened in it, and here is the run still going, if any."
201
202Only then does the client tail that run's delivery log. Run ids stay essential one
203layer down, they are just never the entry point. See
204[Threads and runs](../chat/stream-events#threads-and-runs) for the protocol anatomy
205and [Resumable streams](../resumable-streams/overview) for the log itself.
206
207## Both sides use the same thread id
208
209Persistence only works when the client and the server file under the same string.
210On the client that is the hook's `threadId`. On the server it is the activity's
211`threadId`. For generation the middleware reads it straight off the activity,
212so there is nothing to repeat on `withGenerationPersistence`:
213
214```ts
215import {
216 generateImage,
217 generationParamsFromRequest,
218 toServerSentEventsResponse,
219} from '@tanstack/ai'
220import { openaiImage } from '@tanstack/ai-openai'
221import {
222 memoryPersistence,
223 withGenerationPersistence,
224} from '@tanstack/ai-persistence'
225
226const persistence = memoryPersistence()
227
228export async function POST(request: Request) {
229 const { input, threadId } = await generationParamsFromRequest('image', request)
230
231 // No scope, nothing to file the job under, so nothing could ever hydrate it.
232 // Reject instead of inventing an id.
233 if (threadId === undefined) {
234 return new Response('`threadId` is required', { status: 400 })
235 }
236 if (typeof input.prompt !== 'string') {
237 throw new Error('This endpoint accepts text image prompts only.')
238 }
239
240 const stream = generateImage({
241 adapter: openaiImage('gpt-image-2'),
242 prompt: input.prompt,
243 threadId,
244 stream: true,
245 middleware: [withGenerationPersistence(persistence)],
246 })
247
248 return toServerSentEventsResponse(stream)
249}
250```
251
252The client sends its `threadId` on the wire for you, so the hook side is just the
253option. Chat is the same shape: the `threadId` you pass `useChat` is the one
254`chatParamsFromRequest` hands your route and `withPersistence` stores under. See
255[Chat persistence](./chat-persistence) and
256[Generation persistence](./generation-persistence) for the full wiring.
257
258## When you can skip `threadId`
259
260Without persistence, `threadId` is optional. After the view mounts, the client
261mints an ephemeral thread id to satisfy the protocol. That id is also the
262DevTools row for the session. The run works, it just cannot be found again,
263which is fine for a one-shot image you show and forget.
264
265Turn `persistence` on and `threadId` becomes required, on the hook and on the
266activity the middleware wraps. `withGenerationPersistence` throws when neither
267the activity nor its own `threadId` **override** supplies one. An app that
268cannot name the slot has nothing to restore into.
269
270## When restore does nothing
271
272Almost always one of these:
273
274- **The thread id changed.** A `crypto.randomUUID()` or a `useId()` in it means a
275 new key on every mount. Log the id on both sides and compare the two strings.
276- **The client and server disagree.** The hook files under one id, the middleware
277 under another. They must match exactly.
278- **You keyed on a run id.** Nothing durable is addressable by `runId` alone from
279 a fresh page load. Restore starts from the thread.
280- **Byte storage is off.** For generation, the record never holds media bytes, so
281 `status` and `error` come back while `result` stays `null`. Add
282 [byte storage](./keep-generated-files) to get the media back too.