feat(persistence): generation run persistence (client + server) #1011
main fromrefs/pull/1011/head·merged by tombeckenham View on GitHub🎯 Changes#
Generation persistence — the media-generation parallel of chat persistence. A media run (image, video, audio, TTS, transcription, summarize) now survives a page reload or a dropped connection, restoring transparently into the normal hook fields, with optional durable storage of the generated bytes.
Split out of #987 and rebuilt on the current feat/persistence-core. The previously-stacked byte-storage half has been folded in, so this is now the whole feature in one PR.
Supersedes #997 (same change, renamed from feat/generation-persistence-client — the branch always contained the server half too) and folds in #998.
The shape#
A generation run is recorded in its own store, keyed by its runId (the same AG-UI run id the client sends), with threadId an optional link — it no longer overloads the chat RunStore. On the client, the hook picks a mode exactly the way useChat does:
// Client-driven: the browser holds a lightweight snapshot under `generation:<id>`.
useGenerateImage({ id: 'hero', connection, persistence: localStoragePersistence() })
// Server-driven: nothing is cached; the last run for `threadId` is fetched on mount.
useGenerateImage({ threadId, connection, persistence: true })
Restore is invisible. There is no resumeSnapshot / pendingArtifacts / resultArtifacts hook field — a reload repaints result / status / error as if the run had just finished. resumeState carries the in-flight run identity only.
Crucially, this restores a record, not provider work: generation still only begins when generate(...) is called, and nothing is ever restarted. A run that is still streaming is re-attached and finished in place, via the connection's joinRun durability replay — the same mechanism useChat uses.
Server#
withGenerationPersistencerecords each run in a dedicatedgenerationRuns(GenerationRunStore) store: activity/provider/model, lifecycle status, result metadata, and — when byte storage is on — the durable artifact refs.reconstructGeneration(persistence, request, options?)is the generation parallel ofreconstructChat: it reads?runId=(preferred) or the latest run linked to?threadId=, authorizes viaauthorize, and returns{ resumeSnapshot, activeRun }JSON for a server-authoritative client to hydrate from.- Byte storage (opt-in, layered on top): provide both an
artifacts(ArtifactStore) and ablobs(BlobStore) store and the middleware writes each generated file's bytes underartifacts/<runId>/<artifactId>, records anArtifactRecord, and attachesPersistedArtifactRefs to the result and the run record. The newartifactUrloption stamps a durable app-origin serve URL onto each ref and rewrites the live result's media URL to it, so live and restored results both render from your origin instead of the provider's expiring link.retrieveArtifact/retrieveBlob(and the sharedartifactBlobKey) serve the bytes back; extraction is customizable viaextractArtifacts/nameArtifact. memoryPersistence()ships in-memorygenerationRuns/artifacts/blobs;defineGenerationRunStore/defineArtifactStore/defineBlobStoretype a custom store inline the waydefineMessageStore/defineRunStorealready do.
Client#
Generation hooks (useGenerateImage, useGenerateVideo, useGenerateAudio, useGenerateSpeech, useGeneration, useSummarize, useTranscription, and the Solid/Vue/Svelte/Angular equivalents) take the same persistence option chat does. The option reuses the ChatStorageAdapter contract, so localStoragePersistence / sessionStoragePersistence / indexedDBPersistence work for generations too with no type argument — a bare call is correct on either side. Untrusted snapshots are validated on read with the new parseGenerationResumeSnapshot.
With byte storage configured, a restored result is rebuilt whole, its media resolved to the durable serve URL and its refs on result.artifacts. Without it, status / error restore and result stays null — a client snapshot never holds bytes.
The base generation return types (UseGenerationReturn / CreateGenerationReturn / InjectGenerationResult) also gained a defaulted TInput generic across all five frameworks, so generate is precisely typed (input: TInput) => Promise<void>. That deleted the unsound internal narrow-to-wide casts and every wrapper-level generate as cast — twenty-five in total — with existing single-generic references unaffected.
Packages#
@tanstack/ai-persistence—GenerationRunStore,reconstructGeneration, the byte-storage half (ArtifactStore/BlobStore/retrieveArtifact/retrieveBlob/artifactUrl), and thedefine*store helpers.@tanstack/ai-client— the resume-snapshot reducer,parseGenerationResumeSnapshot, mount hydration (client store and serverGET), result reconstruction from refs.@tanstack/ai-utils—base64ToUint8Array.- framework hooks — react / solid / vue / svelte / angular.
@tanstack/ai— the generation activities gainedthreadId/runIdoptions.
Docs, skills, examples, tests#
- Docs — new
docs/persistence/generation-persistence.mdanddocs/persistence/keep-generated-files.md, plus updates acrossclient-persistence,overview,controls,build-your-own-adapter,internals, thedocs/media/*pages,docs/chat/streaming.mdanddocs/interrupts/overview.md(threads / runs / turns are now explained consistently). All kiira-verified. - Skills —
ai-core/client-persistence,ai-core/media-generation,ai-persistence, and a newai-persistence/build-cloudflare-artifact-store. - Example —
examples/ts-react-chatwires generation persistence end to end (image + video via Grok Imagine). - E2E —
generation-persistence.spec.ts(client-driven: stream → reload → transparent restore → reset) andgeneration-persistence-server.spec.ts(server-driven:persistence: true, restore from a?threadId=GET,localStoragestays empty, no run auto-starts). Plus hydration/restore unit coverage in all five framework packages and the persistence package.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm run test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
- New Features
- Added end-to-end generation persistence across reloads/dropped connections, including resumable generation identity via
threadId+ ephemeralrunId. - Durably restore generated media using application-served artifact URLs (optional artifact metadata + durable byte storage).
- Generation hooks now expose
resumeStateand correctly repaintstatus/result/errorwhen persistence is enabled. - Introduced server-driven generation hydration keyed by
threadId, plus secure URL input fetching protections. - Generation events now include
threadId/runIdfor better correlation.
- Added end-to-end generation persistence across reloads/dropped connections, including resumable generation identity via
- Documentation
- Expanded threads/runs, generation persistence, durable media, adapter/store contracts, and server route examples.
- Tests
- Added extensive resume/persistence coverage across client/server modes, plus new type-level and unit/integration tests.
- 1
View your CI Pipeline Execution ↗ for commit 8f2305e3116b95d5dbc7c7e1453ccb9ee4096bd9
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 7m 51s View ↗ nx run-many --targets=build --exclude=examples/...✅ Succeeded 1m 52s View ↗
☁️ Nx Cloud last updated this comment at
2026-07-31 02:10:05UTCNote
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.
Use the checkboxes below for quick actions:
- ▶️ Resume reviews
- 🔍 Trigger review
📝 Walkthrough
Walkthrough#
Generation persistence adds resumable generation snapshots, server-side generation-run and artifact/blob stores, durable media URLs, secure artifact fetching, reconstruction endpoints, framework hook support, documentation, examples, and end-to-end tests.
Changes#
Generation persistence
Layer / File(s) Summary Client resume state and hydration
packages/ai-client/...Generation clients persist and validate snapshots, restore statuses and results, expose resumeState, hydrate through connection adapters, rejoin active runs, and guard updates after disposal.Server stores and middleware
packages/ai-persistence/...,packages/ai-utils/...Generation-run, artifact, and blob contracts are added with in-memory implementations, artifact extraction, bounded URL fetching, durable URL rewriting, reconstruction, retrieval, and authorization support. Core generation pipeline
packages/ai/src/...,packages/ai-event-client/src/index.tsGeneration activities propagate threadId/runId, apply middleware result transforms, and emit persisted artifact references.Framework integrations
packages/ai-react/...,packages/ai-vue/...,packages/ai-solid/...,packages/ai-svelte/...,packages/ai-angular/...Generation hooks and injectables accept persistence and resume options, reconstruct typed results, expose resume state, and suppress post-disposal updates. Documentation and examples
docs/...,examples/ts-react-chat/...,packages/ai/skills/...,packages/ai-persistence/skills/...Persistence concepts, adapter contracts, artifact serving, security controls, and example configurations are documented; example generation routes use persistence and Grok adapters. End-to-end coverage
testing/e2e/...Provider-free client-driven and server-driven persistence routes and Playwright tests cover reload restoration, durable image URLs, local-storage behavior, and reset. Estimated code review effort: 5 (Critical) | ~120 minutes
Possibly related PRs
- TanStack/ai#997: Overlaps with generation resume snapshots, persistence naming, and storage behavior.
- TanStack/ai#999: Overlaps with generation persistence middleware, reconstruction, artifact/blob storage, and framework integration.
Suggested reviewers:
jherr🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 49.66% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold. ✅ Passed checks (4 passed)
Check name Status Explanation Title check ✅ Passed The title is concise and accurately summarizes the main change: generation run persistence for client and server. Description check ✅ Passed The description follows the required template and includes the changes, checklist, and release impact sections. Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request. Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request. ✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
- Create stacked PR
- Commit on current branch
🧪 Generate unit tests (beta)
- Create PR with unit tests
- Commit unit tests in branch `feat/generation-persistence-full`
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment `@coderabbitai help` to get the list of available commands.@tanstack/ai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@1011@tanstack/ai-acp
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-acp@1011@tanstack/ai-angular
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-angular@1011@tanstack/ai-anthropic
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@1011@tanstack/ai-bedrock
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-bedrock@1011@tanstack/ai-claude-code
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-claude-code@1011@tanstack/ai-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@1011@tanstack/ai-code-mode
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode@1011@tanstack/ai-code-mode-skills
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode-skills@1011@tanstack/ai-codex
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-codex@1011@tanstack/ai-devtools-core
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@1011@tanstack/ai-durable-stream
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-durable-stream@1011@tanstack/ai-elevenlabs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-elevenlabs@1011@tanstack/ai-event-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-event-client@1011@tanstack/ai-fal
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-fal@1011@tanstack/ai-gemini
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@1011@tanstack/ai-grok
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@1011@tanstack/ai-grok-build
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok-build@1011@tanstack/ai-groq
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-groq@1011@tanstack/ai-isolate-cloudflare
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-cloudflare@1011@tanstack/ai-isolate-node
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-node@1011@tanstack/ai-isolate-quickjs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-quickjs@1011@tanstack/ai-mcp
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-mcp@1011@tanstack/ai-memory
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-memory@1011@tanstack/ai-mistral
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-mistral@1011@tanstack/ai-ollama
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@1011@tanstack/ai-openai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@1011@tanstack/ai-opencode
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-opencode@1011@tanstack/ai-openrouter
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@1011@tanstack/ai-persistence
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-persistence@1011@tanstack/ai-preact
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@1011@tanstack/ai-react
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@1011@tanstack/ai-react-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@1011@tanstack/ai-sandbox
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox@1011@tanstack/ai-sandbox-cloudflare
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-cloudflare@1011@tanstack/ai-sandbox-daytona
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-daytona@1011@tanstack/ai-sandbox-docker
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-docker@1011@tanstack/ai-sandbox-local-process
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-local-process@1011@tanstack/ai-sandbox-sprites
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-sprites@1011@tanstack/ai-sandbox-vercel
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-vercel@1011@tanstack/ai-solid
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@1011@tanstack/ai-solid-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@1011@tanstack/ai-svelte
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@1011@tanstack/ai-utils
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-utils@1011@tanstack/ai-vue
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@1011@tanstack/ai-vue-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@1011@tanstack/openai-base
npm i https://pkg.pr.new/TanStack/ai/@tanstack/openai-base@1011@tanstack/preact-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@1011@tanstack/react-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@1011@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@1011commit:
8f2305eActionable comments posted: 14
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/ai-svelte/src/create-generate-speech.svelte.ts (1)
111-114: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winDocument TTS persistence returning
result === null.createGenerateSpeechsupportspersistence/threadId/initialResumeSnapshot, but it passes noreconstructResulttocreateGenerationand there is no speech reconstruct mapper. SinceTTSResult.audiois base64 bytes plusformat, persisted speech metadata reloads with status/restoration state, but the audio cannot be rebuilt from storage — document this inCreateGenerateSpeechOptionsto avoid leaving users with a persisting run that never plays.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-svelte/src/create-generate-speech.svelte.ts` around lines 111 - 114, Document in CreateGenerateSpeechOptions that persistence, threadId, and initialResumeSnapshot restore speech state but do not reconstruct TTSResult.audio; persisted runs may therefore return result === null and cannot play audio after reload. Keep the existing createGeneration call unchanged unless needed to align the option documentation.🟡 Minor comments (16)
packages/ai/skills/ai-core/media-generation/SKILL.md-628-632 (1)
628-632: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winScope the no-byte-storage limitation to media payloads.
Transcription and summarize rebuild
resultfrom persistedtext/metadata (reconstructTranscriptionResultandreconstructSummarizeResult), while only image/audio/video refs require the durableartifactUrlblob route. Change this paragraph to say the media refs/media results need byte storage, not thatresultstaysnullgenerally.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/skills/ai-core/media-generation/SKILL.md` around lines 628 - 632, Revise the no-byte-storage paragraph to scope the limitation specifically to image, audio, and video media refs/results that depend on durable artifact storage. Preserve that transcription and summarize restore their results from persisted text/metadata via reconstructTranscriptionResult and reconstructSummarizeResult, and remove the blanket claim that a reload leaves result null.packages/ai/skills/ai-core/client-persistence/SKILL.md-156-158 (1)
156-158: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winClarify which results need byte storage on reload.
The client snapshot already preserves text results (
transcription.textandsummary) and artifact refs, so this should say media-bearing results need server byte storage /artifactUrlwhile text-output results restore without it.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/skills/ai-core/client-persistence/SKILL.md` around lines 156 - 158, The client snapshot preserves text outputs such as transcription.text and summary, so revise the result persistence guidance to distinguish them from media-bearing results. State that only media-bearing results require server byte storage or artifactUrl for reload, while text-output results restore without it, and update the surrounding examples accordingly.packages/ai-persistence/skills/ai-persistence/SKILL.md-45-63 (1)
45-63: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winNew store keys contradict "Critical rule 5".
This section documents
generationRuns/artifacts/blobs, but rule 5 (Line 197) still statesstoresaccepts onlymessages,runs,interrupts,metadata. An agent reading the rules section will reject valid configs — update that line alongside this table.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/skills/ai-persistence/SKILL.md` around lines 45 - 63, The “Critical rule 5” store-key list must include the generation persistence stores documented in the table. Update the rule’s `stores` description to accept `generationRuns`, `artifacts`, and `blobs` in addition to the existing chat stores, preserving the requirement that `artifacts` and `blobs` are provided together.packages/ai-persistence/src/middleware.ts-454-455 (1)
454-455: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winFallback mime
${type}/mpegyields bogusimage/mpeg/video/mpegfor prompt media.When a prompt part omits
source.mimeType, images get stored (and later served) asimage/mpeg. A per-type default is cheap:🐛 Proposed fix
- const mimeType = stringField(source, 'mimeType') ?? `${type}/mpeg` + const defaultMime = + type === 'image' ? 'image/png' : type === 'video' ? 'video/mp4' : 'audio/mpeg' + const mimeType = stringField(source, 'mimeType') ?? defaultMime🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/src/middleware.ts` around lines 454 - 455, Update the mimeType fallback in the source-processing logic near sourceType to use a valid per-type default instead of always constructing `${type}/mpeg`; preserve an explicitly provided source.mimeType and ensure image and video prompt media receive appropriate media types.packages/ai-persistence/src/middleware.ts-383-405 (1)
383-405: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winparseDataUrlrejects data URLs carrying media-type parameters.data:image/png;charset=utf-8;base64,…doesn't match the regex (only a bare;base64may follow the mime), sodescriptorBodyfalls through to the URL branch and throwsRefusing to fetch artifact over data:— failing the whole run instead of storing the inline bytes. Allowing arbitrary;param=valuesegments before the optional;base64fixes it.🐛 Proposed fix
- const match = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(value) + const match = /^data:([^;,]+)?((?:;[^;,]*)*?)(;base64)?,(.*)$/s.exec(value) if (!match) return undefined const mimeType = match[1] || 'application/octet-stream' - const raw = match[3] ?? '' + const raw = match[4] ?? ''and switch the base64 check to
match[3].🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/src/middleware.ts` around lines 383 - 405, Update parseDataUrl’s data-URL regex to accept arbitrary media-type parameter segments before the optional ;base64 marker, while preserving the existing MIME type and payload captures. Adjust the base64 detection to use the new capture index (match[3]) so parameterized URLs such as data:image/png;charset=utf-8;base64,... are decoded as inline bytes.packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md-345-355 (1)
345-355: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick winThe serve-route sample tells readers to authorize but shows no check.
Agents copy this handler as-is, producing an endpoint where any guessed
artifactIdstreams bytes. Show the actual check against the session-derived owner andrecord.threadId, returning 404.🛡️ Proposed fix
const record = await retrieveArtifact(persistence, artifactId) if (!record) return new Response('Not found', { status: 404 }) + + // Ownership comes from server-side session state, never from the caller's id. + const session = await getSession(request, env) + if (!session || !(await ownsThread(env, session.userId, record.threadId))) { + return new Response('Not found', { status: 404 }) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md` around lines 345 - 355, Update the GET handler sample to derive the authenticated owner from the session and validate it against the retrieved record’s record.threadId before calling retrieveBlob. Return a 404 response when authorization fails, ensuring artifact bytes are never served for an unauthorized artifactId.Source: Learnings
packages/ai-client/src/connection-adapters.ts-781-791 (1)
781-791: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winresumeState.threadIdis typed optional but is required by the client parser.parseGenerationResumeSnapshot(packages/ai-client/src/generation-types.ts, Lines 463-465) rejects the entire snapshot whenresumeStatelacks athreadId, so a server response matching this declared type is silently dropped rather than partially adopted. Either makethreadIdrequired here or have the parser tolerate its absence.🛠️ Proposed fix (tighten the type)
- resumeState: { threadId?: string; runId: string } | null + resumeState: { threadId: string; runId: string } | null🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-client/src/connection-adapters.ts` around lines 781 - 791, Make resumeState.threadId required in the GenerationHydrationResult interface, matching the validation behavior of parseGenerationResumeSnapshot. Update the nested resumeState type while preserving its nullable state and existing runId requirement.packages/ai-client/src/generation-client.ts-851-885 (1)
851-885: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winFailed rejoin leaves the visible state stuck on
generating.The catch only records the snapshot error;
status/errorare never repainted, so a rejoin that throws (network drop,joinRun404 after the log expired) leavesstatus: 'generating'withisLoading: falseand no error surfaced — the exact stuck staterecordResumeSnapshotErrorexists to avoid.generate()'s catch sets both.🛠️ Proposed fix
} catch (error) { if (!controller.signal.aborted) { - this.recordResumeSnapshotError( - error instanceof Error ? error : new Error(String(error)), - ) + const err = error instanceof Error ? error : new Error(String(error)) + this.setError(err) + this.setStatus('error') + this.recordResumeSnapshotError(err) + this.callbacksRef.onError?.(err) } } finally {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-client/src/generation-client.ts` around lines 851 - 885, Update the catch block in rejoinInFlight to surface failed rejoin errors through the same status and error state updates used by generate(), while preserving the existing abort check and snapshot error recording. Ensure a non-aborted joinRun/processStream failure repaints the visible error state instead of leaving status as generating.packages/ai-react/src/use-generate-speech.ts-125-134 (1)
125-134: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winDocument the missing speech snapshot restore path.
Speech result contains base64
audiobytes, and client-driven persistence only stores the lightweightGenerationResultSnapshotartifacts/ref metadata. BecauseuseGenerateSpeechhas noreconstructResult, a restored completed run will repaintresult = nulleven whenstatus/resumeStateare restored — update the speech options docs to say restored result data is unavailable unless anonResulttransform provides durable restore data.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-react/src/use-generate-speech.ts` around lines 125 - 134, Update the options documentation for useGenerateSpeech and its useGeneration configuration to document that completed speech results cannot be reconstructed from restored snapshots because audio bytes are not persisted; restored runs may have status/resumeState without result data unless an onResult transform supplies durable restore data..changeset/generation-persistence.md-22-22 (1)
22-22: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winClarify the
result.artifactswording.“Refs on
result.artifacts” is awkward; use “refs inresult.artifacts” for clearer documentation.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.changeset/generation-persistence.md at line 22, Update the generation persistence documentation sentence describing restored media references, replacing “refs on result.artifacts” with “refs in result.artifacts” while preserving the surrounding behavior and wording.Source: Linters/SAST tools
docs/interrupts/overview.md-44-49 (1)
44-49: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAvoid implying that every continuation immediately finishes.
A continuation can hit another interrupt, so “final answer” and “two run lifecycles” are only guaranteed for a single interrupt/continuation pair. Say “continues the agent” and “at least two runs” instead.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/interrupts/overview.md` around lines 44 - 49, Update the interrupt sequence description in the overview diagram and accompanying note to say the continuation continues the agent rather than producing a final answer, and describe the lifecycle as at least two runs. Preserve the explanation that the interrupted run ends and continuation starts a new run, while allowing for additional interrupts and runs.docs/config.json-392-392 (1)
392-392: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winRefresh the media documentation timestamps to July 29, 2026.
The corresponding documentation files were changed in this PR, but these entries still use
2026-07-28. Update theirupdatedAtvalues without changingaddedAt.As per coding guidelines, substantive documentation changes must refresh
updatedAtto today’s date.Also applies to: 404-422
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/config.json` at line 392, Update the updatedAt values for the affected media documentation entries in docs/config.json, including entries 392 and 404-422, from 2026-07-28 to 2026-07-29. Leave each corresponding addedAt value unchanged.Source: Coding guidelines
docs/media/generation-hooks.md-22-25 (1)
22-25: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winQualify the persistence guarantees across the documentation.
The callouts overpromise what
persistencealone provides: client snapshots are lightweight, expired media requires durable server-side artifact/blob storage, and result reconstruction is conditional.docs/media/generation-hooks.md#L22-L25: qualify that restoredresultdepends on the configured persistence mode.docs/media/audio-generation.md#L164-L166: state that retaining audio after provider URL expiry requires durable artifact/blob storage.docs/media/image-generation.md#L511-L512: state that retaining images after provider URL expiry requires durable artifact/blob storage.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/media/generation-hooks.md` around lines 22 - 25, Qualify the persistence documentation across all three sites: in docs/media/generation-hooks.md lines 22-25, state that restored result availability depends on the configured persistence mode; in docs/media/audio-generation.md lines 164-166 and docs/media/image-generation.md lines 511-512, clarify that retaining media after provider URL expiry requires durable server-side artifact/blob storage.examples/ts-react-chat/src/routes/generations.image.tsx-21-24 (1)
21-24: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winMake reset available after persisted failures.
Both examples enable persistence that can restore an error or status without a result, while their shared UIs only expose Clear when
resultexists.examples/ts-react-chat/src/routes/generations.image.tsx#L21-L24: update the streaming hook’s UI path to expose reset for restored error/non-idle states.examples/ts-react-chat/src/routes/generations.image.tsx#L42-L49: apply the same reset condition to the direct image variant.examples/ts-react-chat/src/routes/generations.image.tsx#L66-L73: apply the same reset condition to the server-function image variant.examples/ts-react-chat/src/routes/generations.video.tsx#L17-L20: update the streaming video variant.examples/ts-react-chat/src/routes/generations.video.tsx#L31-L38: update the direct video variant.examples/ts-react-chat/src/routes/generations.video.tsx#L48-L55: update the server-function video variant.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/routes/generations.image.tsx` around lines 21 - 24, Update the UI reset/Clear visibility condition for the generation hook results: examples/ts-react-chat/src/routes/generations.image.tsx lines 21-24, 42-49, and 66-73, and examples/ts-react-chat/src/routes/generations.video.tsx lines 17-20, 31-38, and 48-55. Expose reset when persisted state has an error or any non-idle status, even without a result, while preserving the existing result-based behavior.docs/persistence/build-your-own-adapter.md-938-971 (1)
938-971: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winReject negative page limits.
With
limit: -1, this code executesLIMIT 0, then returnstruncated: truewithout a cursor. Validate that limits are non-negative integers before constructing the query.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-adapter.md` around lines 938 - 971, Validate options.limit in list before constructing the SQL query, rejecting values that are negative or not integers; allow undefined and non-negative integers, including zero. Preserve the existing zero-limit response and pagination behavior for valid limits.docs/persistence/keep-generated-files.md-94-95 (1)
94-95: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick winCorrect the 404/403 explanation.
Returning the same
404for missing and unauthorized artifacts avoids confirming whether an ID exists; a403would be the distinguishable response. The current prose says the opposite.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/keep-generated-files.md` around lines 94 - 95, Correct the explanation associated with the owned check so it states that returning 404 for both missing and unauthorized artifacts prevents confirming whether an ID exists, while 403 would distinguish an existing but forbidden artifact. Keep the `if (!owned) return new Response('not found', { status: 404 })` behavior unchanged.🧹 Nitpick comments (15)
packages/ai/skills/ai-core/media-generation/SKILL.md (1)
593-593: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse one verified latest provider model across both examples.
packages/ai/skills/ai-core/media-generation/SKILL.md#L593-L593: verify whethergpt-image-1is current.packages/ai/skills/ai-core/client-persistence/SKILL.md#L199-L199: verify whethergpt-image-2is current.
As per coding guidelines, use the latest model from the adapter’s
model-meta.tsand keep edited examples consistent.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/skills/ai-core/media-generation/SKILL.md` at line 593, The OpenAI image model examples are inconsistent and may not use the latest verified provider model. Check the adapter’s model-meta.ts, update the adapter configuration at packages/ai/skills/ai-core/media-generation/SKILL.md:593-593 and the corresponding example at packages/ai/skills/ai-core/client-persistence/SKILL.md:199-199 to the latest model, and keep both examples consistent.Source: Coding guidelines
packages/ai-persistence/tests/persistence-validation.test.ts (1)
76-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe artifacts/blobs both-or-neither invariant is enforced twice but tested nowhere.
validateGenerationPersistenceStoresenforces it at runtime andInvalidGenerationPersistenceenforces it at the type level; neither branch has a test, so a regression in either would pass CI.packages/ai-persistence/tests/persistence-validation.test.ts#L76-L78: add cases with{ generationRuns, artifacts }and{ generationRuns, blobs }expecting/requires both stores\.artifacts and stores\.blobs/i.packages/ai-persistence/tests/persistence-types.test-d.ts#L155-L160: add@ts-expect-errorcalls towithGenerationPersistencefor the same two half-configured store sets.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/tests/persistence-validation.test.ts` around lines 76 - 78, The artifacts/blobs both-or-neither invariant lacks runtime and type-level coverage. In packages/ai-persistence/tests/persistence-validation.test.ts:76-78, add validation cases for { generationRuns, artifacts } and { generationRuns, blobs }, expecting /requires both stores\.artifacts and stores\.blobs/i. In packages/ai-persistence/tests/persistence-types.test-d.ts:155-160, add `@ts-expect-error` calls to withGenerationPersistence for those same half-configured store sets.packages/ai-persistence/src/memory.ts (1)
72-116: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider returning copies of run records.
createOrResume/gethand back the live map entry, so a caller mutating the returned object silently edits store state —MemoryArtifactStore.save(Line 229) already copies. A{ ...record }on return keeps the reference backend honest as a conformance target for real backends.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/src/memory.ts` around lines 72 - 116, The MemoryGenerationRunStore currently exposes live GenerationRunRecord objects, allowing callers to mutate stored state. Update createOrResume, get, and findLatestForThread to return shallow copies of records while preserving the map’s internal references; align this behavior with MemoryArtifactStore.save and keep update’s merge semantics unchanged.packages/ai-persistence/tests/reconstruct-generation.test.ts (1)
119-137: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider covering
authorizereturning aResponseand customparam/runParam. Thedecision instanceof Responsebranch and the option-renamed query params are unexercised; both are one-liner tests.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/tests/reconstruct-generation.test.ts` around lines 119 - 137, Add focused tests alongside the existing authorization test for reconstructGeneration: verify an authorize callback returning a Response is returned unchanged, and verify custom param/runParam option names are used to locate the generation run. Keep each case minimal and assert the expected response behavior.packages/ai-persistence/src/reconstruct-generation.ts (1)
42-51: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winauthorizecannot tell arunIdfrom athreadId. The callback gets a bareid, so an ownership check has to guess which lookup to run (or check both, widening what it accepts). Consider passing the kind alongside the id, e.g.authorize({ runId, threadId }, request)or a secondkind: 'run' | 'thread'argument, so tenancy checks stay precise.Authorization ordering itself is correct — it runs before any store read.
Also applies to: 157-171
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/src/reconstruct-generation.ts` around lines 42 - 51, The authorize callback currently receives only a bare id, preventing precise distinction between run and thread authorization. Update the authorize contract and its invocation in the reconstruction flow to pass the identifier kind alongside the id, such as an explicit runId/threadId object or run/thread kind argument, while preserving authorization before store reads and existing boolean/Response handling.Source: Learnings
packages/ai-persistence/tests/error-abort.test.ts (1)
265-265: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTest titles still say "job" after the jobs → runs rename. Store, records, and ids are all
run-flavoured now; renaming these titles to "run" keeps failure output consistent with the API.Also applies to: 289-289, 313-313, 338-338
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/tests/error-abort.test.ts` at line 265, Rename the test titles at the cases around lines 265, 289, 313, and 338 from “job” terminology to “run” terminology, preserving each test’s existing behavior and wording aside from the renamed entity.packages/ai-persistence/src/middleware.ts (1)
1404-1408: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocblock contradicts the artifact fallback.
persistGenerationArtifacts(Line 872) does setthreadId = ctx.threadId ?? ctx.requestIdon everyArtifactRecord/PersistedArtifactRef(required field), so "never faked from the request id" only holds for the run record. Worth wording it as "the run record never fakes a threadId; artifact records fall back to the request id".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/src/middleware.ts` around lines 1404 - 1408, The docblock above persistGenerationArtifacts incorrectly claims threadId is never faked from the request id. Clarify that only the generation run record preserves an optional caller-supplied threadId without fallback, while artifact records use ctx.threadId ?? ctx.requestId as their required threadId.packages/ai-persistence/tests/generation-artifacts.test.ts (1)
28-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThese
void (undefined as unknown as T)lines look like leftover scaffolding.The three types are only imported to be discarded here; either drop them (and the imports) or add real assertions, e.g. a
satisfies GenerationArtifactDescriptoron the literal passed toextractArtifactsat Line 388.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-persistence/tests/generation-artifacts.test.ts` around lines 28 - 30, Remove the unused GenerationArtifactDescriptor, GenerationArtifactExtractionInput, and GenerationArtifactNameInput imports and their corresponding void-cast scaffolding in generation-artifacts.test.ts. If type coverage is needed, replace the scaffolding with a real satisfies assertion on the extractArtifacts input literal, but do not retain discarded type references.packages/ai-client/src/generation-reconstruct.ts (1)
23-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: drop the
as stringcast withflatMap.- return restored.artifacts - .filter( - (a) => - a.role === 'output' && - a.source.mediaType === mediaType && - a.url != null, - ) - .map((a) => a.url as string) + return restored.artifacts.flatMap((a) => + a.role === 'output' && a.source.mediaType === mediaType && a.url != null + ? [a.url] + : [], + )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-client/src/generation-reconstruct.ts` around lines 23 - 35, Update mediaUrls to use flatMap so it returns each matching artifact URL only when present, allowing TypeScript to infer string values and removing the `as string` cast while preserving the existing output-role and media-type filters.packages/ai-angular/tests/inject-generation.test.ts (1)
50-80: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: collapse the three near-identical render helpers.
renderInjectGenerateVideo/renderInjectGenerateImagediffer fromrenderInjectGenerationonly in which injectable is called; a small factory taking the injectable would remove two copies.♻️ Sketch
function renderWith<T>(inject: (options: any) => T) { return (options: any) => { `@Component`({ standalone: true, template: '' }) class Host { gen = inject(options) } const fixture = TestBed.createComponent(Host) fixture.detectChanges() return { get result() { return fixture.componentInstance.gen }, flush: () => fixture.detectChanges(), destroy: () => fixture.destroy(), } } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-angular/tests/inject-generation.test.ts` around lines 50 - 80, Optionally replace the duplicated renderInjectGenerateVideo and renderInjectGenerateImage helpers, along with renderInjectGeneration, with a shared renderWith factory that accepts the injectable function and returns the options-based renderer. Preserve the existing Host component setup, fixture lifecycle methods, and result access behavior for each injectable.packages/ai-client/src/video-generation-client.ts (1)
529-554: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider a single clone helper instead of hand-rolled field spreads.
This copies each nested field explicitly, so any new field added to
GenerationResumeSnapshotsilently starts leaking an internal reference.structuredClone(this.resumeSnapshot)(or a sharedcloneResumeSnapshothelper ingeneration-types.ts, reusable by the other generation clients) keeps this correct as the shape grows. Note the current copy is also shallow at the element level —artifacts/pendingArtifactsentries are still shared references.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-client/src/video-generation-client.ts` around lines 529 - 554, Replace the hand-rolled cloning in getResumeSnapshot with structuredClone or a shared cloneResumeSnapshot helper, ensuring the entire GenerationResumeSnapshot—including nested objects and pendingArtifacts/artifacts entries—is deeply copied. If introducing the helper, place it with the generation types and reuse the established helper across generation clients.packages/ai-angular/src/inject-generate-video.ts (1)
38-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueInconsistent with the sibling injectables: consider
Pick<InjectGenerationOptions, …>.InjectGenerateAudioOptions(and the image/speech variants) inherit these three fields viaextends Pick<InjectGenerationOptions<…>, 'persistence' | 'threadId' | 'initialResumeSnapshot'>, while this file re-declares them plus the doc comment inline. Same for the Svelte/React/Vue video hooks. Inheriting keeps the docs and types in one place as the persistence surface evolves.Video's client is a separate class (
VideoGenerationClient, notGenerationClient), so this may be deliberate — if so, no change needed.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-angular/src/inject-generate-video.ts` around lines 38 - 52, Align the video injectable options with the sibling audio, image, and speech variants by inheriting persistence, threadId, and initialResumeSnapshot through Pick<InjectGenerationOptions<…>, 'persistence' | 'threadId' | 'initialResumeSnapshot'> instead of redeclaring them inline. Verify VideoGenerationClient supports the same option types; if it does not, preserve the current declarations and make no change.packages/ai-react/tests/use-generation.test.ts (1)
143-160: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueNit: the spy and the generator share the name
connect, andrunContextsis unused in the added tests.The inner
async *connectand the outerconst connect = vi.fn()reading the same identifier makes the helper harder to follow; considerconnectSpy. Also droprunContextsunless a test asserts on it.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-react/tests/use-generation.test.ts` around lines 143 - 160, In createRunContextCaptureAdapter, rename the outer vi.fn() variable from connect to connectSpy and update the returned property and all references accordingly, while retaining the adapter’s connect method. Remove the unused runContexts array, its push call, and its return property unless the added tests assert on it.packages/ai-vue/src/use-generation.ts (1)
165-170: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueComment contradicts the code.
The comment says the
bodykey must be omitted when absent under EOPT, but Line 170 assignsbody: options.bodyunconditionally (possiblyundefined). Either drop/reword the comment or apply the conditional spread used for the neighbouring options.♻️ Suggested change
- // Conditional spread on `body`: `GenerationClientOptions.body` is a strict - // optional (`body?: Record<string, any>`), and under EOPT we must omit the - // key when absent rather than assign `undefined`. const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = { id: clientId, - body: options.body, + ...(options.body !== undefined && { body: options.body }),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-vue/src/use-generation.ts` around lines 165 - 170, Update the clientOptions construction near GenerationClientOptions so body is conditionally spread only when options.body is present, matching the comment and strict optional-property requirements; preserve the existing id and other option handling.packages/ai-vue/src/use-generate-speech.ts (1)
114-123: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSpeech has no
reconstructResult, soresultnever repaints on restore — document it.Every other Vue generation composable injects a reconstructor (
reconstructImageResult,reconstructTranscriptionResult,reconstructSummarizeResult). Speech can't rebuild aTTSResultfrom a durable URL becauseaudiois base64 plus a requiredformat, so omitting it looks deliberate — but the inheritedpersistenceoption at Lines 22-25 now implies restore support. Add a short note on the option docs (or the hook JSDoc) that a restored speech snapshot repaintsstatus/erroronly.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-vue/src/use-generate-speech.ts` around lines 114 - 123, Add a concise documentation note near the inherited persistence option or the use-generate-speech hook JSDoc explaining that restored speech snapshots repaint only status and error; result is not reconstructed because TTS audio requires base64 data and its format. Keep the existing useGeneration configuration unchanged.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/persistence/build-your-own-adapter.md`: - Around line 893-923: The put method’s selectCreated-before-upsert flow is race-prone and can return values that differ from the stored row. Update put to atomically upsert the record and then re-read the persisted row, or use an atomic RETURNING-supported upsert, deriving createdAt and returned metadata from the record actually stored. - Around line 617-640: Validate and narrow persisted database values before hydrating records in mapGenerationRun, mapArtifact, and mapBlobRecord. Replace direct coercions and unguarded JSON.parse calls with schema validation or type guards, rejecting or safely handling malformed and partially migrated rows before constructing domain objects. Preserve valid-row hydration while preventing invalid state from reaching get and findLatestForThread. - Around line 655-676: Update createOrResume so it returns the persisted record after insert rather than reconstructing and returning the attempted input. Re-read the run using select.get(input.runId) after insert, including when ON CONFLICT DO NOTHING means another caller created it first, and map that stored record with mapGenerationRun. In `@docs/persistence/generation-persistence.md`: - Around line 29-35: Update the generation persistence documentation around withGenerationPersistence and generationRuns to distinguish client-side adapters from server persistence. State that a server run record is created only when the server route opts into withGenerationPersistence, and that server persistence is required for server-driven hydration and/or durable artifacts rather than for every persistence mode. - Around line 37-39: The persistence documentation should distinguish result metadata from durable media bytes. In docs/persistence/generation-persistence.md lines 37-39, remove the claim that result always remains null without byte storage; in lines 224-228, state that artifacts/blobs are required to restore durable media, while metadata and non-binary results can still be restored. - Around line 113-116: Make both persistence examples fail closed: in docs/persistence/generation-persistence.md lines 113-116, update the reconstructGeneration call to provide a real server-side authorize callback that validates the authenticated user’s ownership before using the client-supplied threadId; in docs/persistence/keep-generated-files.md lines 77-95, replace the const owned = true placeholder with session-derived artifact ownership validation. Ensure neither example permits client-provided identifiers alone to read another user’s generation. In `@docs/persistence/keep-generated-files.md`: - Around line 151-167: Add a concise client-side hook or component example to the “Wire the durable URL through to the client” section, showing consumption of durable media URLs from the result fields (such as result.images, result.url, or result.audio.url). Keep the snippet focused on rendering the persisted URL and complement the existing server-side explanation without changing the documented artifact flow. In `@examples/ts-react-chat/src/routes/generations.audio.tsx`: - Around line 81-94: Update the audio persistence configuration in examples/ts-react-chat/src/routes/generations.audio.tsx:81-94 and the speech persistence configuration in examples/ts-react-chat/src/routes/generations.speech.tsx:55-79 so persisted AudioOutput.url and SpeechOutput.audioUrl values are not stored as document-scoped object URLs; omit those fields or reconstruct them during hydration from a durable source while preserving the existing generation and playback behavior. - Around line 81-94: Update the audio generation persistence ids in examples/ts-react-chat/src/routes/generations.audio.tsx (lines 81-94) to include selectedModel. Update the speech generation persistence id and its useMemo dependencies in examples/ts-react-chat/src/routes/generations.speech.tsx (lines 55-79) to include voice, ensuring distinct models or voices cannot hydrate stale persisted output. In `@packages/ai-client/src/video-generation-client.ts`: - Around line 850-860: Update maybeHydrateResumeSnapshot and hydrateFromServer to check this.disposed immediately after their awaited storage/server hydration calls and return before applying state or rejoining work. Ensure disposed clients cannot call repaintFromSnapshot or start rejoinInFlight/joinRun, while preserving the existing live-state guards for active clients. In `@packages/ai/skills/ai-core/client-persistence/SKILL.md`: - Around line 209-219: Authorize all caller-supplied persistence identifiers using server-side session ownership checks. In packages/ai/skills/ai-core/client-persistence/SKILL.md lines 209-219, replace the unconditional authorization in GET with a real ownership check or fail-closed behavior; in packages/ai/skills/ai-core/media-generation/SKILL.md lines 590-595, authorize the submitted thread before persisting the run; and in lines 609-618, authorize record.threadId before retrieving or returning blob bytes. - Around line 191-203: Update the POST handler’s generation flow around generationParamsFromRequest and generateImage to ensure every request carries a stable threadId into withGenerationPersistence, including bare prompt requests. Use the request envelope or an equivalent propagated identifier so the persisted run identity matches the threadId used by hydration, and cover the POST-to-hydration path. In `@packages/ai/src/activities/generateAudio/index.ts`: - Around line 163-164: Propagate threadId and runId from the activity context into every aiEventClient.emit lifecycle payload. Update started, completed, error, and usage events in packages/ai/src/activities/generateAudio/index.ts (163-164), packages/ai/src/activities/generateImage/index.ts (256-257), packages/ai/src/activities/generateSpeech/index.ts (171-172), and packages/ai/src/activities/generateTranscription/index.ts (206-207); ensure all emitted payloads include both IDs. In `@testing/e2e/src/routes/api.generation-persistence-server.ts`: - Around line 36-39: Add a test-only reset path for the completedByThread record keyed by generation-server-thread, either through a DELETE handler or by clearing it in the persistence spec before the first page.goto. Ensure retries start with no prior completed generation while preserving the existing server-authoritative record behavior. --- Outside diff comments: In `@packages/ai-svelte/src/create-generate-speech.svelte.ts`: - Around line 111-114: Document in CreateGenerateSpeechOptions that persistence, threadId, and initialResumeSnapshot restore speech state but do not reconstruct TTSResult.audio; persisted runs may therefore return result === null and cannot play audio after reload. Keep the existing createGeneration call unchanged unless needed to align the option documentation. --- Minor comments: In @.changeset/generation-persistence.md: - Line 22: Update the generation persistence documentation sentence describing restored media references, replacing “refs on result.artifacts” with “refs in result.artifacts” while preserving the surrounding behavior and wording. In `@docs/config.json`: - Line 392: Update the updatedAt values for the affected media documentation entries in docs/config.json, including entries 392 and 404-422, from 2026-07-28 to 2026-07-29. Leave each corresponding addedAt value unchanged. In `@docs/interrupts/overview.md`: - Around line 44-49: Update the interrupt sequence description in the overview diagram and accompanying note to say the continuation continues the agent rather than producing a final answer, and describe the lifecycle as at least two runs. Preserve the explanation that the interrupted run ends and continuation starts a new run, while allowing for additional interrupts and runs. In `@docs/media/generation-hooks.md`: - Around line 22-25: Qualify the persistence documentation across all three sites: in docs/media/generation-hooks.md lines 22-25, state that restored result availability depends on the configured persistence mode; in docs/media/audio-generation.md lines 164-166 and docs/media/image-generation.md lines 511-512, clarify that retaining media after provider URL expiry requires durable server-side artifact/blob storage. In `@docs/persistence/build-your-own-adapter.md`: - Around line 938-971: Validate options.limit in list before constructing the SQL query, rejecting values that are negative or not integers; allow undefined and non-negative integers, including zero. Preserve the existing zero-limit response and pagination behavior for valid limits. In `@docs/persistence/keep-generated-files.md`: - Around line 94-95: Correct the explanation associated with the owned check so it states that returning 404 for both missing and unauthorized artifacts prevents confirming whether an ID exists, while 403 would distinguish an existing but forbidden artifact. Keep the `if (!owned) return new Response('not found', { status: 404 })` behavior unchanged. In `@examples/ts-react-chat/src/routes/generations.image.tsx`: - Around line 21-24: Update the UI reset/Clear visibility condition for the generation hook results: examples/ts-react-chat/src/routes/generations.image.tsx lines 21-24, 42-49, and 66-73, and examples/ts-react-chat/src/routes/generations.video.tsx lines 17-20, 31-38, and 48-55. Expose reset when persisted state has an error or any non-idle status, even without a result, while preserving the existing result-based behavior. In `@packages/ai-client/src/connection-adapters.ts`: - Around line 781-791: Make resumeState.threadId required in the GenerationHydrationResult interface, matching the validation behavior of parseGenerationResumeSnapshot. Update the nested resumeState type while preserving its nullable state and existing runId requirement. In `@packages/ai-client/src/generation-client.ts`: - Around line 851-885: Update the catch block in rejoinInFlight to surface failed rejoin errors through the same status and error state updates used by generate(), while preserving the existing abort check and snapshot error recording. Ensure a non-aborted joinRun/processStream failure repaints the visible error state instead of leaving status as generating. In `@packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md`: - Around line 345-355: Update the GET handler sample to derive the authenticated owner from the session and validate it against the retrieved record’s record.threadId before calling retrieveBlob. Return a 404 response when authorization fails, ensuring artifact bytes are never served for an unauthorized artifactId. In `@packages/ai-persistence/skills/ai-persistence/SKILL.md`: - Around line 45-63: The “Critical rule 5” store-key list must include the generation persistence stores documented in the table. Update the rule’s `stores` description to accept `generationRuns`, `artifacts`, and `blobs` in addition to the existing chat stores, preserving the requirement that `artifacts` and `blobs` are provided together. In `@packages/ai-persistence/src/middleware.ts`: - Around line 454-455: Update the mimeType fallback in the source-processing logic near sourceType to use a valid per-type default instead of always constructing `${type}/mpeg`; preserve an explicitly provided source.mimeType and ensure image and video prompt media receive appropriate media types. - Around line 383-405: Update parseDataUrl’s data-URL regex to accept arbitrary media-type parameter segments before the optional ;base64 marker, while preserving the existing MIME type and payload captures. Adjust the base64 detection to use the new capture index (match[3]) so parameterized URLs such as data:image/png;charset=utf-8;base64,... are decoded as inline bytes. In `@packages/ai-react/src/use-generate-speech.ts`: - Around line 125-134: Update the options documentation for useGenerateSpeech and its useGeneration configuration to document that completed speech results cannot be reconstructed from restored snapshots because audio bytes are not persisted; restored runs may have status/resumeState without result data unless an onResult transform supplies durable restore data. In `@packages/ai/skills/ai-core/client-persistence/SKILL.md`: - Around line 156-158: The client snapshot preserves text outputs such as transcription.text and summary, so revise the result persistence guidance to distinguish them from media-bearing results. State that only media-bearing results require server byte storage or artifactUrl for reload, while text-output results restore without it, and update the surrounding examples accordingly. In `@packages/ai/skills/ai-core/media-generation/SKILL.md`: - Around line 628-632: Revise the no-byte-storage paragraph to scope the limitation specifically to image, audio, and video media refs/results that depend on durable artifact storage. Preserve that transcription and summarize restore their results from persisted text/metadata via reconstructTranscriptionResult and reconstructSummarizeResult, and remove the blanket claim that a reload leaves result null. --- Nitpick comments: In `@packages/ai-angular/src/inject-generate-video.ts`: - Around line 38-52: Align the video injectable options with the sibling audio, image, and speech variants by inheriting persistence, threadId, and initialResumeSnapshot through Pick<InjectGenerationOptions<…>, 'persistence' | 'threadId' | 'initialResumeSnapshot'> instead of redeclaring them inline. Verify VideoGenerationClient supports the same option types; if it does not, preserve the current declarations and make no change. In `@packages/ai-angular/tests/inject-generation.test.ts`: - Around line 50-80: Optionally replace the duplicated renderInjectGenerateVideo and renderInjectGenerateImage helpers, along with renderInjectGeneration, with a shared renderWith factory that accepts the injectable function and returns the options-based renderer. Preserve the existing Host component setup, fixture lifecycle methods, and result access behavior for each injectable. In `@packages/ai-client/src/generation-reconstruct.ts`: - Around line 23-35: Update mediaUrls to use flatMap so it returns each matching artifact URL only when present, allowing TypeScript to infer string values and removing the `as string` cast while preserving the existing output-role and media-type filters. In `@packages/ai-client/src/video-generation-client.ts`: - Around line 529-554: Replace the hand-rolled cloning in getResumeSnapshot with structuredClone or a shared cloneResumeSnapshot helper, ensuring the entire GenerationResumeSnapshot—including nested objects and pendingArtifacts/artifacts entries—is deeply copied. If introducing the helper, place it with the generation types and reuse the established helper across generation clients. In `@packages/ai-persistence/src/memory.ts`: - Around line 72-116: The MemoryGenerationRunStore currently exposes live GenerationRunRecord objects, allowing callers to mutate stored state. Update createOrResume, get, and findLatestForThread to return shallow copies of records while preserving the map’s internal references; align this behavior with MemoryArtifactStore.save and keep update’s merge semantics unchanged. In `@packages/ai-persistence/src/middleware.ts`: - Around line 1404-1408: The docblock above persistGenerationArtifacts incorrectly claims threadId is never faked from the request id. Clarify that only the generation run record preserves an optional caller-supplied threadId without fallback, while artifact records use ctx.threadId ?? ctx.requestId as their required threadId. In `@packages/ai-persistence/src/reconstruct-generation.ts`: - Around line 42-51: The authorize callback currently receives only a bare id, preventing precise distinction between run and thread authorization. Update the authorize contract and its invocation in the reconstruction flow to pass the identifier kind alongside the id, such as an explicit runId/threadId object or run/thread kind argument, while preserving authorization before store reads and existing boolean/Response handling. In `@packages/ai-persistence/tests/error-abort.test.ts`: - Line 265: Rename the test titles at the cases around lines 265, 289, 313, and 338 from “job” terminology to “run” terminology, preserving each test’s existing behavior and wording aside from the renamed entity. In `@packages/ai-persistence/tests/generation-artifacts.test.ts`: - Around line 28-30: Remove the unused GenerationArtifactDescriptor, GenerationArtifactExtractionInput, and GenerationArtifactNameInput imports and their corresponding void-cast scaffolding in generation-artifacts.test.ts. If type coverage is needed, replace the scaffolding with a real satisfies assertion on the extractArtifacts input literal, but do not retain discarded type references. In `@packages/ai-persistence/tests/persistence-validation.test.ts`: - Around line 76-78: The artifacts/blobs both-or-neither invariant lacks runtime and type-level coverage. In packages/ai-persistence/tests/persistence-validation.test.ts:76-78, add validation cases for { generationRuns, artifacts } and { generationRuns, blobs }, expecting /requires both stores\.artifacts and stores\.blobs/i. In packages/ai-persistence/tests/persistence-types.test-d.ts:155-160, add `@ts-expect-error` calls to withGenerationPersistence for those same half-configured store sets. In `@packages/ai-persistence/tests/reconstruct-generation.test.ts`: - Around line 119-137: Add focused tests alongside the existing authorization test for reconstructGeneration: verify an authorize callback returning a Response is returned unchanged, and verify custom param/runParam option names are used to locate the generation run. Keep each case minimal and assert the expected response behavior. In `@packages/ai-react/tests/use-generation.test.ts`: - Around line 143-160: In createRunContextCaptureAdapter, rename the outer vi.fn() variable from connect to connectSpy and update the returned property and all references accordingly, while retaining the adapter’s connect method. Remove the unused runContexts array, its push call, and its return property unless the added tests assert on it. In `@packages/ai-vue/src/use-generate-speech.ts`: - Around line 114-123: Add a concise documentation note near the inherited persistence option or the use-generate-speech hook JSDoc explaining that restored speech snapshots repaint only status and error; result is not reconstructed because TTS audio requires base64 data and its format. Keep the existing useGeneration configuration unchanged. In `@packages/ai-vue/src/use-generation.ts`: - Around line 165-170: Update the clientOptions construction near GenerationClientOptions so body is conditionally spread only when options.body is present, matching the comment and strict optional-property requirements; preserve the existing id and other option handling. In `@packages/ai/skills/ai-core/media-generation/SKILL.md`: - Line 593: The OpenAI image model examples are inconsistent and may not use the latest verified provider model. Check the adapter’s model-meta.ts, update the adapter configuration at packages/ai/skills/ai-core/media-generation/SKILL.md:593-593 and the corresponding example at packages/ai/skills/ai-core/client-persistence/SKILL.md:199-199 to the latest model, and keep both examples consistent.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
@@ -477,0 +620,21 @@620+ ...(typeof row.thread_id === 'string' ? { threadId: row.thread_id } : {}),621+ activity: String(row.activity),622+ provider: String(row.provider),623+ model: String(row.model),624+ status: toGenerationRunStatus(row.status),625+ startedAt: Number(row.started_at),626+ ...(row.finished_at != null ? { finishedAt: Number(row.finished_at) } : {}),627+ ...(typeof row.error_json === 'string'628+ ? { error: JSON.parse(row.error_json) }629+ : {}),630+ ...(typeof row.result_json === 'string'631+ ? { result: JSON.parse(row.result_json) }632+ : {}),633+ ...(typeof row.artifacts_json === 'string'634+ ? { artifacts: JSON.parse(row.artifacts_json) }635+ : {}),636+ ...(typeof row.usage_json === 'string'637+ ? { usage: JSON.parse(row.usage_json) }638+ : {}),639+ }640+}🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Validate persisted rows before hydration.
mapGenerationRundirectly coerces database values and callsJSON.parse. A corrupt or partially migrated row can throw duringget/findLatestForThreador hydrate invalid state. Apply schema validation/type guards here and tomapArtifact(Lines 739-751) andmapBlobRecord(Lines 845-858).Based on learnings, hand-rolled persistence adapters must narrow and validate parsed values before use.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-adapter.md` around lines 617 - 640, Validate and narrow persisted database values before hydrating records in mapGenerationRun, mapArtifact, and mapBlobRecord. Replace direct coercions and unguarded JSON.parse calls with schema validation or type guards, rejecting or safely handling malformed and partially migrated rows before constructing domain objects. Preserve valid-row hydration while preventing invalid state from reaching get and findLatestForThread.Source: Learnings
✅ Addressed in commits 08ab3f7 to caa3e52
docs/persistence/build-your-own-adapter.md lines 726 to 747@@ -477,0 +656,21 @@656+ const existing = select.get(input.runId)657+ if (existing) return mapGenerationRun(existing)658+ const status: GenerationRunStatus = input.status ?? 'running'659+ insert.run(660+ input.runId,661+ input.threadId ?? null,662+ input.activity,663+ input.provider,664+ input.model,665+ status,666+ input.startedAt,667+ )668+ return {669+ runId: input.runId,670+ activity: input.activity,671+ provider: input.provider,672+ model: input.model,673+ status,674+ startedAt: input.startedAt,675+ ...(input.threadId !== undefined ? { threadId: input.threadId } : {}),676+ }🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Return the record after the insert.
Two concurrent callers can both miss
select.get; the loser’sON CONFLICT DO NOTHINGis ignored, and it returns its attempted input instead of the stored winner. That violates the documented idempotency contract and can report incorrect run metadata.Proposed fix
insert.run( input.runId, input.threadId ?? null, input.activity, input.provider, input.model, status, input.startedAt, ) - return { - runId: input.runId, - activity: input.activity, - provider: input.provider, - model: input.model, - status, - startedAt: input.startedAt, - ...(input.threadId !== undefined ? { threadId: input.threadId } : {}), - } + const created = select.get(input.runId) + if (!created) throw new Error('Generation run was not created') + return mapGenerationRun(created)📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
async createOrResume(input) { const existing = select.get(input.runId) if (existing) return mapGenerationRun(existing) const status: GenerationRunStatus = input.status ?? 'running' insert.run( input.runId, input.threadId ?? null, input.activity, input.provider, input.model, status, input.startedAt, ) const created = select.get(input.runId) if (!created) throw new Error('Generation run was not created') return mapGenerationRun(created)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-adapter.md` around lines 655 - 676, Update createOrResume so it returns the persisted record after insert rather than reconstructing and returning the attempted input. Re-read the run using select.get(input.runId) after insert, including when ON CONFLICT DO NOTHING means another caller created it first, and map that stored record with mapGenerationRun.@@ -477,0 +903,21 @@903+ bytes.byteLength,904+ etag,905+ options?.contentType ?? null,906+ options?.customMetadata ? JSON.stringify(options.customMetadata) : null,907+ createdAt,908+ now,909+ )910+ return {911+ key,912+ size: bytes.byteLength,913+ etag,914+ createdAt,915+ updatedAt: now,916+ ...(options?.contentType !== undefined917+ ? { contentType: options.contentType }918+ : {}),919+ ...(options?.customMetadata !== undefined920+ ? { customMetadata: options.customMetadata }921+ : {}),922+ }923+ },🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Avoid the read-before-upsert race.
Concurrent first writes can both observe no existing row, then one upsert over the other. The returned
createdAtand metadata may not match the row actually stored. Upsert first and re-read the stored record, or use an atomicRETURNINGclause.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-adapter.md` around lines 893 - 923, The put method’s selectCreated-before-upsert flow is race-prone and can return values that differ from the stored row. Update put to atomically upsert the record and then re-read the persisted row, or use an atomic RETURNING-supported upsert, deriving createdAt and returned metadata from the record actually stored.✅ Addressed in commits 08ab3f7 to d61611c
@@ -0,0 +15,21 @@15+images, long audio, a big transcription. For a quick one-shot image you show and16+forget, skip it.17+18+## Choose a mode19+20+Generation persistence mirrors chat's `persistence` option:21+22+- **`persistence: true`** — server-driven. The client caches nothing; on mount23+ it hydrates the last run for its `threadId` from the server.24+- **`persistence: <adapter>`** (e.g. `localStoragePersistence()`) — client-driven.25+ The client keeps a small snapshot in browser storage.26+- **omitted / `false`** — off. The run lives in memory only; a reload starts27+ empty.28+29+Either way the server keeps a **generation job** record:30+`withGenerationPersistence(persistence)` needs a `generationRuns` store (a31+`GenerationRunStore` keyed by the run's own `runId`; a generation has no conversation32+of its own, so `threadId` is only an optional link). `memoryPersistence()` ships33+one out of the box; see34+[Build your own adapter](./build-your-own-adapter#generation--media-stores) for35+your own backend.🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not imply client-driven persistence always writes a server run record.
persistence: <adapter>can be entirely browser-side; agenerationRunsrecord exists only when the server route opts intowithGenerationPersistence. Clarify that server persistence is required for server-driven hydration and/or durable artifacts, not every persistence mode.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/generation-persistence.md` around lines 29 - 35, Update the generation persistence documentation around withGenerationPersistence and generationRuns to distinguish client-side adapters from server persistence. State that a server run record is created only when the server route opts into withGenerationPersistence, and that server persistence is required for server-driven hydration and/or durable artifacts rather than for every persistence mode.✅ Addressed in commits 08ab3f7 to d61611c
@@ -0,0 +19,21 @@19+20+Generation persistence mirrors chat's `persistence` option:21+22+- **`persistence: true`** — server-driven. The client caches nothing; on mount23+ it hydrates the last run for its `threadId` from the server.24+- **`persistence: <adapter>`** (e.g. `localStoragePersistence()`) — client-driven.25+ The client keeps a small snapshot in browser storage.26+- **omitted / `false`** — off. The run lives in memory only; a reload starts27+ empty.28+29+Either way the server keeps a **generation job** record:30+`withGenerationPersistence(persistence)` needs a `generationRuns` store (a31+`GenerationRunStore` keyed by the run's own `runId`; a generation has no conversation32+of its own, so `threadId` is only an optional link). `memoryPersistence()` ships33+one out of the box; see34+[Build your own adapter](./build-your-own-adapter#generation--media-stores) for35+your own backend.36+37+The record never holds the generated bytes, so on its own a reload restores38+`status` and `error` while `result` stays `null`. To bring the media back too,39+add server byte storage: see [Keep generated files](./keep-generated-files).🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Separate result metadata from durable media bytes. The persistence contract can restore terminal result metadata without storing generated bytes;
artifacts/blobsare required for durable media restoration.docs/persistence/generation-persistence.md#L37-L39: remove the claim thatresultstays null whenever byte storage is absent.docs/persistence/generation-persistence.md#L224-L228: state that byte storage is needed for durable media, while metadata and non-binary results can still be restored.
📍 Affects 1 file
docs/persistence/generation-persistence.md#L37-L39(this comment)docs/persistence/generation-persistence.md#L224-L228
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/generation-persistence.md` around lines 37 - 39, The persistence documentation should distinguish result metadata from durable media bytes. In docs/persistence/generation-persistence.md lines 37-39, remove the claim that result always remains null without byte storage; in lines 224-228, state that artifacts/blobs are required to restore durable media, while metadata and non-binary results can still be restored.✅ Addressed in commits 08ab3f7 to 11f98a2
@@ -0,0 +96,21 @@96+ withGenerationPersistence(persistence, {97+ artifactUrl: (ref) => `/api/generate/image/artifact?id=${ref.artifactId}`,98+ }),99+ ],100+ })101+102+ return toServerSentEventsResponse(stream, {103+ durability: { adapter: durability },104+ })105+}106+107+export function GET(request: Request): Response | Promise<Response> {108+ const durability = memoryStream(request)109+ // A reconnecting client carries a resume cursor; replay the live stream.110+ if (durability.resumeFrom() !== null) {111+ return resumeServerSentEventsResponse({ adapter: durability })112+ }113+ // Otherwise this is the mount-time hydration (?threadId). In multi-user apps114+ // pass reconstructGeneration's `authorize` option so a guessed threadId can't115+ // read another user's generation.116+ return reconstructGeneration(persistence, request)🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
Make both persistence examples fail closed. Caller-provided identifiers must not be sufficient to read or reconstruct another user’s generation.
docs/persistence/generation-persistence.md#L113-L116: passreconstructGenerationan actual server-sideauthorizecallback.docs/persistence/keep-generated-files.md#L77-L95: replaceconst owned = truewith session-derived artifact ownership validation.
Based on learnings, persistence reads must authorize ownership from server-side identity before using client-provided identifiers.
📍 Affects 2 files
docs/persistence/generation-persistence.md#L113-L116(this comment)docs/persistence/keep-generated-files.md#L77-L95
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/generation-persistence.md` around lines 113 - 116, Make both persistence examples fail closed: in docs/persistence/generation-persistence.md lines 113-116, update the reconstructGeneration call to provide a real server-side authorize callback that validates the authenticated user’s ownership before using the client-supplied threadId; in docs/persistence/keep-generated-files.md lines 77-95, replace the const owned = true placeholder with session-derived artifact ownership validation. Ensure neither example permits client-provided identifiers alone to read another user’s generation.Source: Learnings
✅ Addressed in commits 08ab3f7 to f9001e3
docs/persistence/keep-generated-files.md lines 151 to 167Outdated@@ -0,0 +147,21 @@147+private address still passes a literal-IP check. Keep `allowInputUrl` narrow,148+and for stronger isolation inject `artifactFetch` to route downloads through an149+egress-restricted proxy that can check the address actually connected to.150+151+## Wire the durable URL through to the client152+153+`artifactUrl` is what makes the stored bytes reachable from the client without154+any extra plumbing. For each persisted ref it returns the app-origin URL that155+serves those bytes (the `GET` route above), and `withGenerationPersistence`156+does two things with it: it stamps the URL onto the ref (`ref.url`) and it157+rewrites the live result's media field to the same URL — `result.images[i].url`158+for images, `result.url` for a video, `result.audio.url` for audio. So the live159+result already points at your origin, not the provider's expiring link.160+161+Those durable refs ride along on `result.artifacts`, and they are what a reload162+restores from. In [Generation persistence](./generation-persistence), the163+generation hook rebuilds `result` from the persisted refs on mount, resolving164+each media field to its durable `ref.url` — so the restored result renders the165+same media the live run showed. The refs are the only artifact surface: there166+are no separate top-level artifact fields on the hook, final refs live on167+`result.artifacts` and in-flight ones on `resumeState.pendingArtifacts`.📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Add a client-side consumption snippet.
This page explains how
artifactUrlrewrites the result and how the client renders it, but only shows server code. As per coding guidelines, include a small client hook/component snippet that consumes the durable URL.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/keep-generated-files.md` around lines 151 - 167, Add a concise client-side hook or component example to the “Wire the durable URL through to the client” section, showing consumption of durable media URLs from the result fields (such as result.images, result.url, or result.audio.url). Keep the snippet focused on rendering the persisted URL and complement the existing server-side explanation without changing the documented artifact flow.Source: Coding guidelines
examples/ts-react-chat/src/routes/generations.audio.tsx lines 81 to 94Outdated@@ -74,13 +78,17 @@7478 const hookOptions = useMemo(() => {7579 if (mode === 'hooks') {7680 return {81+ id: `audio:${mode}:${config.id}`,7782 connection: fetchServerSentEvents('/api/generate/audio'),7883 body: { provider: config.id, model: selectedModel },84+ persistence: audioPersistence,7985 onResult: toAudioOutput,8086 }8187 }8288 return {89+ id: `audio:${mode}:${config.id}`,8390 fetcher: (input: { prompt: string; duration?: number }) =>8491 generateAudioFn({8592 data: { ...input, provider: config.id, model: selectedModel },8693 }),94+ persistence: audioPersistence,🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Client persistence can restore dead object URLs. Both routes persist UI results whose media URLs are scoped to the current browser document, so a full reload cannot play the restored result without reconstructing the media.
examples/ts-react-chat/src/routes/generations.audio.tsx#L81-L94: avoid persisting theAudioOutput.urlobject URL, or rebuild it from a durable/reconstructable source during hydration.examples/ts-react-chat/src/routes/generations.speech.tsx#L55-L79: avoid persisting theSpeechOutput.audioUrlobject URL, or rebuild it from a durable/reconstructable source during hydration.
📍 Affects 2 files
examples/ts-react-chat/src/routes/generations.audio.tsx#L81-L94(this comment)examples/ts-react-chat/src/routes/generations.speech.tsx#L55-L79
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/routes/generations.audio.tsx` around lines 81 - 94, Update the audio persistence configuration in examples/ts-react-chat/src/routes/generations.audio.tsx:81-94 and the speech persistence configuration in examples/ts-react-chat/src/routes/generations.speech.tsx:55-79 so persisted AudioOutput.url and SpeechOutput.audioUrl values are not stored as document-scoped object URLs; omit those fields or reconstruct them during hydration from a durable source while preserving the existing generation and playback behavior.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Generation persistence keys omit user-selected inputs. A persistence id must distinguish configurations whose generated results differ; otherwise reloads can hydrate stale output from another model or voice.
examples/ts-react-chat/src/routes/generations.audio.tsx#L81-L94: includeselectedModelin the id.examples/ts-react-chat/src/routes/generations.speech.tsx#L55-L79: includevoicein the id and itsuseMemodependencies.
📍 Affects 2 files
examples/ts-react-chat/src/routes/generations.audio.tsx#L81-L94(this comment)examples/ts-react-chat/src/routes/generations.speech.tsx#L55-L79
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/routes/generations.audio.tsx` around lines 81 - 94, Update the audio generation persistence ids in examples/ts-react-chat/src/routes/generations.audio.tsx (lines 81-94) to include selectedModel. Update the speech generation persistence id and its useMemo dependencies in examples/ts-react-chat/src/routes/generations.speech.tsx (lines 55-79) to include voice, ensuring distinct models or voices cannot hydrate stale persisted output.@@ -558,0 +840,21 @@840+ stored = await this.resumePersistence?.getItem(this.resumeSnapshotKey)841+ } catch (error) {842+ // A corrupt record (e.g. truncated JSON) or unavailable storage must843+ // not break construction; the app just starts without a snapshot.844+ console.warn(845+ '[TanStack AI] Failed to read persisted generation resume snapshot',846+ error,847+ )848+ return849+ }850+ if (stored === null || stored === undefined) return851+ const snapshot = parseGenerationResumeSnapshot(stored)852+ if (!snapshot) return853+ // Live state wins: adopt the stored snapshot only if nothing has been854+ // observed since construction.855+ if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return856+ this.repaintFromSnapshot(snapshot)857+ if (snapshot.status === 'running' && snapshot.resumeState?.runId) {858+ this.rejoinInFlight(snapshot.resumeState.runId)859+ }860+ }🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Async hydration can resume work on a disposed client.
maybeHydrateResumeSnapshot()starts in the constructor, but nothing re-checksthis.disposedafter theawaiton line 840. If the client is disposed while the storage read is in flight (unmount during hydration, or React StrictMode's mount → dispose → remount replay), this continues torepaintFromSnapshotand thenrejoinInFlight, which opens a freshjoinRunstream on a client that has already been torn down.dispose()has already run, so nothing will abort that controller.hydrateFromServer()(Line 875-892) has the same gap after awaitinghydrate(...).The existing
this.resumeSnapshot || this.isLoading || this.status !== 'idle'guard doesn't cover this — a disposed-and-never-restarted client is stillidle.🔒️ Proposed guard
if (stored === null || stored === undefined) return const snapshot = parseGenerationResumeSnapshot(stored) if (!snapshot) return // Live state wins: adopt the stored snapshot only if nothing has been // observed since construction. if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return + // The read is async: the client may have been disposed while it was in + // flight. Never repaint or rejoin onto a torn-down client. + if (this.disposed) return this.repaintFromSnapshot(snapshot)And mirror it in
hydrateFromServer():// Re-check: a send may have started while the fetch was in flight. if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return + if (this.disposed) return this.repaintFromSnapshot(snapshot)📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (stored === null || stored === undefined) return const snapshot = parseGenerationResumeSnapshot(stored) if (!snapshot) return // Live state wins: adopt the stored snapshot only if nothing has been // observed since construction. if (this.resumeSnapshot || this.isLoading || this.status !== 'idle') return // The read is async: the client may have been disposed while it was in // flight. Never repaint or rejoin onto a torn-down client. if (this.disposed) return this.repaintFromSnapshot(snapshot) if (snapshot.status === 'running' && snapshot.resumeState?.runId) { this.rejoinInFlight(snapshot.resumeState.runId) } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-client/src/video-generation-client.ts` around lines 850 - 860, Update maybeHydrateResumeSnapshot and hydrateFromServer to check this.disposed immediately after their awaited storage/server hydration calls and return before applying state or rejoining work. Ensure disposed clients cannot call repaintFromSnapshot or start rejoinInFlight/joinRun, while preserving the existing live-state guards for active clients.✅ Addressed in commits 08ab3f7 to 11f98a2
@@ -112,0 +183,21 @@183+ memoryPersistence,184+ reconstructGeneration,185+ withGenerationPersistence,186+} from '@tanstack/ai-persistence'187+188+// Needs `stores.generationRuns`; `memoryPersistence()` ships one.189+const persistence = memoryPersistence()190+191+export async function POST(request: Request) {192+ const { input } = await generationParamsFromRequest('image', request)193+ if (typeof input.prompt !== 'string') {194+ throw new Error('This endpoint accepts text image prompts only.')195+ }196+197+ return toServerSentEventsResponse(198+ generateImage({199+ adapter: openaiImage('gpt-image-2'),200+ prompt: input.prompt,201+ stream: true,202+ middleware: [withGenerationPersistence(persistence)],203+ }),🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Locate referenced files" git ls-files | rg 'packages/ai/skills/ai-core/client-persistence|generationParamsFromRequest|withGenerationPersistence|generateImage|toServerSentEventsResponse' || true echo echo "Candidate file size" wc -l packages/ai/skills/ai-core/client-persistence/SKILL.md packages/ai/skills/ai-core/client-persistence/*.ts || true echo echo "Outline SKILL.md" ast-grep outline packages/ai/skills/ai-core/client-persistence/SKILL.md || true echo echo "Search symbols" rg -n "generationParamsFromRequest|withGenerationPersistence|generateImage|toServerSentEventsResponse|requestId|threadId|ctx\.threadId|fallback" packages/ai/skills/ai-core/client-persistence packages -g '*.ts' -g '*.tsx' -g '*.md' | head -n 200Repository: TanStack/ai
Length of output: 23413
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Read referenced skill markdown" cat -n packages/ai/skills/ai-core/client-persistence/SKILL.md echo echo "Search local implementation symbols in package sources" rg -n "function generationParamsFromRequest|const generationParamsFromRequest|export function generationParamsFromRequest|withGenerationPersistence|function withGenerationPersistence|export function withGenerationPersistence|ctx\.threadId|fallback.*requestId|generateId|requestId" packages/ai/src packages -g '*.ts' -g '*.tsx' | head -n 300 echo echo "Inspect likely persisted middleware files" rg -l "withGenerationPersistence|generationParamsFromRequest|threadId.*requestId" packages -g '*.ts' -g '*.tsx' || trueRepository: TanStack/ai
Length of output: 39660
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Read generationParamsFromRequest implementation" sed -n '1,260p' packages/ai/src/client.ts | cat -n echo echo "Read image generation params implementation" sed -n '210,350p' packages/ai/src/activities/generateImage/index.ts | cat -n echo echo "Read generateImage type/schema and defaults" sed -n '1,220p' packages/ai/src/types.ts | cat -n rg -n "generationParamsSchema|GenerationParams|Thread|ThreadParams|threadId|runId|createId|createThreadContext|startGeneration|beforeModel|threadId: options\.threadId|threadId:" packages/ai/src/types.ts packages/ai/src/activities/generateImage packages/openai-base/src/adapters/image packages/openai/src/adapters/image -g '*.ts' | head -n 200 echo echo "Read persistence middleware" sed -n '1,260p' packages/ai-persistence/src/middleware.ts | cat -n rg -n "withGenerationPersistence|generationRuns|threadId|requestId|createId|metadata" packages/ai-persistence/src -g '*.ts' -A 20 -B 20 echo echo "Read retrieve/get generation" sed -n '1,260p' packages/ai-persistence/src/retrieve.ts | cat -nRepository: TanStack/ai
Length of output: 25368
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Read persistence middleware implementation" sed -n '1,260p' packages/ai-persistence/src/middleware.ts | cat -n echo echo "Read persistence retrieval implementation" sed -n '1,320p' packages/ai-persistence/src/retrieve.ts | cat -n echo echo "Read image activity option defaults" sed -n '120,300p' packages/ai/src/activities/generateImage/index.ts | cat -n echo echo "Read generate image type default schema" sed -n '980,1030p' packages/ai/src/types.ts | cat -n echo echo "Small read-only semantic verifier" node - <<'JS' const source = require('fs').readFileSync('packages/ai/src/activities/generateImage/index.ts', 'utf8') const middleware = require('fs').readFileSync('packages/ai-persistence/src/middleware.ts', 'utf8') const retrieve = require('fs').readFileSync('packages/ai-persistence/src/retrieve.ts', 'utf8') const checks = { 'generateImage passes explicit threadId/runId to context': /threadId,\s*\n\s*runId,\s*\n\s*\.\.\.rest[\s\S]*?createGenerationContext\(\{[\s\S]*?threadId,/, 'generateImage does not read ctx.request/headers for threadId': !/(request|headers|threadId|runId)\s*[?:]=\s*\(?ctx\.request|requestId = createId|runIdOverride\s*=|const request/i.test(source), 'middleware falls back to ctx.requestId on absent ctx.threadId': /function withGenerationPersistence[\s\S]*?\? ctx\.threadId|threadId = ctx\.(threadId|requestId)/.test(middleware), 'retrieve gets request params for threadId runId': /function reconstructGeneration[\s\S]*?requestParams|threadId\s*[?:]=\s*params\.(threadId|query\.threadId)/.test(retrieve), 'retrieve resolves latest by threadId': /threadId/, } for (const [name, ok] of Object.entries(checks)) { console.log(`${name}: ${ok ? 'true' : 'false'}`) } JSRepository: TanStack/ai
Length of output: 21958
🌐 Web query:
TanStack AI@tanstack/ai-persistencewithGenerationPersistence threadId requestId reconstructGeneration threadId GET ?threadId=💡 Result:
In TanStack AI,
@tanstack/ai-persistenceprovides the tools necessary for server-authoritative chat and generation persistence [1][2]. The terms you mentioned relate to how the library manages and recovers AI state: 1. reconstructGeneration: While the documentation focuses primarily on reconstructChat for rehydrating chat threads [3], the@tanstack/ai-persistencepackage includes withGenerationPersistence to record the lifecycle of generations [2]. This middleware creates or resumes a run record upon start and handles terminal states (finish, error, or abort) [2]. 2. threadId and requestId: These are standard identifiers used to scope interactions within the persistence system. When a client performs a GET request (typically to rehydrate state), it uses the threadId to locate the specific conversation or generation record [1][3]. For example, a server-side endpoint might use reconstructChat(persistence, request) to fetch the transcript and any active run associated with a threadId [3]. 3. Flow: When a client is configured with persistence: true, it does not store state locally [1][3]. Instead, upon mounting, the client makes a request to the server, often providing a threadId [3]. The server uses this identifier to retrieve the authoritative history from the configured store (e.g., SQLite, Drizzle, etc.) via the persistence middleware [4][5]. If a run was in progress, the system can reconstruct it, allowing the client to tail the stream to completion [3]. In summary,@tanstack/ai-persistenceserves as a contract layer rather than a database [1][5]. You implement adapters for your specific storage solution, and the middleware ensures that chat and generation states are saved and recoverable via identifiers like threadId [2][5].Citations:
- 1: https://tanstack.com/ai/latest/docs/persistence/overview
- 2: https://tanstack.com/ai/latest/docs/persistence/internals
- 3: https://tanstack.com/ai/latest/docs/persistence/client-persistence
- 4: https://tanstack.com/ai/latest/docs/persistence/chat-persistence
- 5: https://tanstack.com/ai/latest/docs/persistence/build-your-own-adapter
Carry
threadIdinto the persisted generation run.generationParamsFrom请求only addsthreadIdfrom an envelope; a barepromptrequest leaves it unset, sogenerateImagecreates/runs with the defaultrequestId. Since hydrate reads by?threadId=, records written without that identity cannot be resolved. Use an envelope like{ data: { prompt }, threadId }or an equivalent stable ID propagation in the route, and cover the POST-to-hydration path.🧰 Tools
🪛 SkillSpector (2.4.4)
[warning] 52: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/skills/ai-core/client-persistence/SKILL.md` around lines 191 - 203, Update the POST handler’s generation flow around generationParamsFromRequest and generateImage to ensure every request carries a stable threadId into withGenerationPersistence, including bare prompt requests. Use the request envelope or an equivalent propagated identifier so the persisted run identity matches the threadId used by hydration, and cover the POST-to-hydration path.✅ Addressed in commits 9c73d86 to 14b8d00
@@ -112,0 +199,21 @@199+ adapter: openaiImage('gpt-image-2'),200+ prompt: input.prompt,201+ stream: true,202+ middleware: [withGenerationPersistence(persistence)],203+ }),204+ )205+}206+207+// Mount-time hydration: resolves `?runId=` (preferred) or the latest run linked208+// to `?threadId=`, and returns `{ resumeSnapshot, activeRun }`.209+export function GET(request: Request) {210+ return reconstructGeneration(persistence, request, {211+ // Multi-user routes MUST authorize: the ids come from the caller. Derive212+ // identity from server-side session state, then check ownership.213+ authorize: async (id, req) => {214+ // const user = await auth(req)215+ // return user != null && (await db.threadOwnedBy(user.id, id))216+ void id217+ void req218+ return true219+ },🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Authorize every persistence identifier in the documentation examples.
The examples accept caller-controlled run/thread/artifact identifiers without consistently enforcing server-side ownership.
packages/ai/skills/ai-core/client-persistence/SKILL.md#L209-L219: replacereturn truewith a real session ownership check or fail closed.packages/ai/skills/ai-core/media-generation/SKILL.md#L590-L595: authorize the submitted thread before persisting the run.packages/ai/skills/ai-core/media-generation/SKILL.md#L609-L618: authorizerecord.threadIdbefore retrieving and returning blob bytes.
Based on learnings: persistence identifiers must be authorized against server-side session ownership before reads or writes.
🧰 Tools
🪛 SkillSpector (2.4.4)
[warning] 52: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
📍 Affects 2 files
packages/ai/skills/ai-core/client-persistence/SKILL.md#L209-L219(this comment)packages/ai/skills/ai-core/media-generation/SKILL.md#L590-L595packages/ai/skills/ai-core/media-generation/SKILL.md#L609-L618
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/skills/ai-core/client-persistence/SKILL.md` around lines 209 - 219, Authorize all caller-supplied persistence identifiers using server-side session ownership checks. In packages/ai/skills/ai-core/client-persistence/SKILL.md lines 209-219, replace the unconditional authorization in GET with a real ownership check or fail-closed behavior; in packages/ai/skills/ai-core/media-generation/SKILL.md lines 590-595, authorize the submitted thread before persisting the run; and in lines 609-618, authorize record.threadId before retrieving or returning blob bytes.Source: Learnings
✅ Addressed in commits 08ab3f7 to 11f98a2
packages/ai/src/activities/generateAudio/index.ts lines 168 to 169@@ -154,3 +160,5 @@154160 stream: _stream,155161 debug: _debug,156162 middleware,163+ threadId,164+ runId,🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Propagate correlation IDs into lifecycle events.
The IDs are only placed in middleware context; every
aiEventClient.emitpayload still omits them. Event subscribers therefore receive nothreadId/runId, despite the newly expanded event contracts.packages/ai/src/activities/generateAudio/index.ts#L163-L164: add both IDs to each started, completed, error, and usage payload.packages/ai/src/activities/generateImage/index.ts#L256-L257: add both IDs to each emitted lifecycle payload.packages/ai/src/activities/generateSpeech/index.ts#L171-L172: add both IDs to each started, completed, error, and usage payload.packages/ai/src/activities/generateTranscription/index.ts#L206-L207: add both IDs to each started, completed, error, and usage payload.
📍 Affects 4 files
packages/ai/src/activities/generateAudio/index.ts#L163-L164(this comment)packages/ai/src/activities/generateImage/index.ts#L256-L257packages/ai/src/activities/generateSpeech/index.ts#L171-L172packages/ai/src/activities/generateTranscription/index.ts#L206-L207
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/src/activities/generateAudio/index.ts` around lines 163 - 164, Propagate threadId and runId from the activity context into every aiEventClient.emit lifecycle payload. Update started, completed, error, and usage events in packages/ai/src/activities/generateAudio/index.ts (163-164), packages/ai/src/activities/generateImage/index.ts (256-257), packages/ai/src/activities/generateSpeech/index.ts (171-172), and packages/ai/src/activities/generateTranscription/index.ts (206-207); ensure all emitted payloads include both IDs.testing/e2e/src/routes/api.generation-persistence-server.ts lines 36 to 39@@ -0,0 +19,21 @@19+ * We hand-build the JSON here rather than pull `@tanstack/ai-persistence` into20+ * the e2e app (it is not a dependency), mirroring the `server-interrupt`21+ * scenario in `api.persistence-durability.ts`. `reconstructGeneration` itself is22+ * unit-tested in `@tanstack/ai-persistence`; this proves the CLIENT restore.23+ *24+ * Exempt from the aimock policy: this route streams a fixed AG-UI sequence and25+ * never reaches an LLM provider's HTTP layer, so there is nothing to mock.26+ */27+28+// 1x1 transparent PNG — the live result's inline bytes, never persisted.29+const TINY_PNG_B64 =30+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='31+32+// Durable app-origin serve URL for the generated image (as33+// `withGenerationPersistence`'s `artifactUrl` would stamp it).34+const DURABLE_IMAGE_URL = '/durable/generation-server/image-1.png'35+36+// Server-authoritative record of the last completed generation per thread. In37+// production this is a `GenerationRunStore` row; here a process-lifetime map is38+// enough for the reload round-trip (the e2e server stays up across reloads).39+const completedByThread = new Map<string, Record<string, unknown>>()🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== locate files ==" git ls-files | rg 'generation-persistence-server|playwright.config|package.json' | sed -n '1,120p' echo echo "== target route outline ==" ast-grep outline testing/e2e/src/routes/api.generation-persistence-server.ts --view expanded || true echo echo "== target route relevant lines ==" cat -n testing/e2e/src/routes/api.generation-persistence-server.ts | sed -n '1,220p' echo echo "== companion files relevant lines ==" fd 'generation-persistence-server' testing/e2e -t f -x sh -c 'echo "--- $1"; wc -l "$1"; cat -n "$1" | sed -n "1,220p"' sh {} echo echo "== playwirght config candidates summary ==" for f in $(git ls-files | rg '(^|/)(playwright\.config|.*playwright.*\.config).*\.(ts|js|mjs)$' | sed -n '1,50p'); do echo "--- $f" wc -l "$f" rg -n "webServer|timeout|retries|workers|projects|testDir|reporters|use:|useWebServer|web_servers|server" "$f" || true done echo echo "== relevant searches ==" rg -n "completedByThread|persistedResult|generation-persistence-server|THREAD_ID|generation-server-thread|DELETE|reset|webServer|retries" testing/e2e | sed -n '1,240p'Repository: TanStack/ai
Length of output: 31542
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== e2e playwright config relevant lines ==" cat -n testing/e2e/playwright.config.ts | sed -n '1,90p' echo echo "== e2e global setup/teardown ==" fd 'global|teardown|setup' testing/e2e -t f | sed -n '1,120p' for f in $(fd 'global|teardown|setup' testing/e2e -t f | sed -n '1,40p'); do echo "--- $f" rg -n "export default|testDir|globalSetup|globalTeardown|process|port|webServer|retries|shard|environmentVariables|playwright" "$f" || true done echo echo "== all shared server routes with DELETE/reset endpoints nearby generation-persistence server ==" cat -n testing/e2e/src/routes/api.middleware-test.ts | sed -n '360,455p' rg -n "DELETE:|reset|completedByThread|generation-server-thread|generation-persistence-server|threadId" testing/e2e/src/routes testing/e2e/tests/generation-persistence-server.spec.ts | sed -n '1,220p' echo echo "== deterministic probe: route behavior after first completed job without reset ==" python3 - <<'PY' completed_by_thread = {} thread_id = 'generation-server-thread' def persisted_result(thread_id, run_id): return {'id': 'image-1', 'model': 'mock-image-model', 'artifacts': [{'threadId': thread_id, 'runId': run_id}]} # Simulate the fixed-thread POST completing once completed_by_thread[thread_id] = persisted_result(thread_id, 'run-1') for i in range(3): result = completed_by_thread.get(thread_id) body = ( { 'resumeSnapshot': {'schemaVersion': 1, 'resumeState': None, 'status': 'complete', 'activity': 'image', 'result': result}, 'activeRun': None, } if result else {'resumeSnapshot': None, 'activeRun': None} ) print(f'request {i}: status={body["resumeSnapshot"]["status"] if body["resumeSnapshot"] else None}') print("no_route_deletion_found", all( 'completedByThread.delete' in code or "completedByThread.delete" in code for _ in [] )) PYRepository: TanStack/ai
Length of output: 20753
Add a reset/cleanup path for the server-driven persistence record.
completedByThreadis keyed by the hardcodedgeneration-server-threadID and is never cleared, while the e2e setup has no global teardown and Playwright reuses the dev server across retries. After the run completes once, the initialstatus→'idle'assertion can fail deterministically on retry. Add a test-onlyDELETE/reset handler for the thread record, or clear it from the spec before the firstpage.goto.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@testing/e2e/src/routes/api.generation-persistence-server.ts` around lines 36 - 39, Add a test-only reset path for the completedByThread record keyed by generation-server-thread, either through a DELETE handler or by clearing it in the persistence spec before the first page.goto. Ensure retries start with no prior completed generation while preserving the existing server-authoritative record behavior.🧹 Nitpick comments (1)
packages/ai-react/tests/use-generation.test.ts (1)
1-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPlace this test alongside its source module.
Move
packages/ai-react/tests/use-generation.test.tsnext topackages/ai-react/src/use-generation.ts(for example,packages/ai-react/src/use-generation.test.ts) to comply with the repository rule for**/*.test.ts.As per coding guidelines, unit tests must be placed in
*.test.tsfiles alongside the source they cover.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-react/tests/use-generation.test.ts` around lines 1 - 24, Move the use-generation test file from the package-level tests directory to sit alongside the useGeneration source module, preserving its existing contents and imports. Place it as use-generation.test.ts next to use-generation.ts so the repository’s test placement rule is satisfied.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@packages/ai-react/tests/use-generation.test.ts`: - Around line 1-24: Move the use-generation test file from the package-level tests directory to sit alongside the useGeneration source module, preserving its existing contents and imports. Place it as use-generation.test.ts next to use-generation.ts so the repository’s test placement rule is satisfied.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
d175f848-bc98-48ce-9a08-7dd8c82bf67a📥 Commits
Reviewing files that changed from the base of the PR and between 7d87a30f73c7b2ba382e2c11e139d745ded00860 and 951030f855fda23ce7a831b5d1e17eb49fe3be98.
📒 Files selected for processing (9)
docs/persistence/build-your-own-adapter.mdpackages/ai-client/src/generation-types.tspackages/ai-client/tests/generation-resume-state.test.tspackages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.mdpackages/ai-persistence/src/middleware.tspackages/ai-persistence/src/types.tspackages/ai-persistence/tests/generation-artifacts.test.tspackages/ai-react/tests/use-generation.test.tspackages/ai/src/types.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- packages/ai-client/tests/generation-resume-state.test.ts
- docs/persistence/build-your-own-adapter.md
- packages/ai-persistence/tests/generation-artifacts.test.ts
- packages/ai-persistence/src/middleware.ts
- packages/ai-client/src/generation-types.ts
- packages/ai-persistence/src/types.ts
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/ai-solid/src/use-generation.ts (2)
259-265: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winClear the previous body when the option becomes undefined.
The conditional spread on Line 263 skips the update when
currentBodyis removed, so the client keeps sending the previous body on later generations. Explicitly clear it using the supported empty/unset representation.Proposed fix
createEffect(() => { const currentBody = options.body - client.updateOptions({ - ...(currentBody !== undefined && { body: currentBody }), - }) + client.updateOptions({ body: currentBody ?? {} }) })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-solid/src/use-generation.ts` around lines 259 - 265, Update the body synchronization effect around currentBody and client.updateOptions so it explicitly clears the client’s previous body when options.body becomes undefined, using the client’s supported empty or unset representation; preserve passing the current body when it is defined.
186-201: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick winUse the conditional body spread described by this implementation comment.
options.bodymay be absent whileGenerationClientOptions.bodyis a strict optional, so this direct assignment can fail underexactOptionalPropertyTypes. Match the similar Svelte/React use-generation handling and omit the key when it is undefined.Proposed fix
- body: options.body, + ...(options.body !== undefined && { body: options.body }),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-solid/src/use-generation.ts` around lines 186 - 201, Update the clientOptions construction in useGeneration to remove the direct body assignment and conditionally spread body only when options.body is defined. Preserve the existing body value when present and omit the property when absent, matching the handling in the Svelte/React use-generation implementations.♻️ Duplicate comments (1)
packages/ai/skills/ai-core/client-persistence/SKILL.md (1)
198-210: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winMake every persisted generation route require and propagate
threadId.packages/ai/skills/ai-core/client-persistence/SKILL.md#L198-L210: pass the validated clientthreadIdintogenerateImage.packages/ai/skills/ai-core/media-generation/SKILL.md#L589-L595: reject missingthreadIdinstead of documenting it as optional.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/skills/ai-core/client-persistence/SKILL.md` around lines 198 - 210, Make every persisted generation route require a validated client threadId and propagate it through the generation call. In packages/ai/skills/ai-core/client-persistence/SKILL.md lines 198-210, update the POST handler and generateImage invocation to pass threadId; in packages/ai/skills/ai-core/media-generation/SKILL.md lines 589-595, change the documented contract to reject missing threadId rather than treating it as optional.🧹 Nitpick comments (1)
packages/ai-react/tests/use-generation-persistence-types.test.ts (1)
18-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffPlace these tests alongside their covered hooks.
This shared test is under
tests/while it covers modules insrc/. Split or relocate the assertions into colocated*.test.tsfiles. As per coding guidelines,**/*.test.ts: “Place unit tests in*.test.tsfiles alongside the source they cover.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-react/tests/use-generation-persistence-types.test.ts` around lines 18 - 24, The shared persistence type tests in use-generation-persistence-types.test.ts should be colocated with the hooks they cover. Split the assertions into *.test.ts files alongside useGenerateImage, useGenerateVideo, useGeneration, useSummarize, and useTranscription, preserving the existing coverage and removing the centralized tests/placement.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Outside diff comments: In `@packages/ai-solid/src/use-generation.ts`: - Around line 259-265: Update the body synchronization effect around currentBody and client.updateOptions so it explicitly clears the client’s previous body when options.body becomes undefined, using the client’s supported empty or unset representation; preserve passing the current body when it is defined. - Around line 186-201: Update the clientOptions construction in useGeneration to remove the direct body assignment and conditionally spread body only when options.body is defined. Preserve the existing body value when present and omit the property when absent, matching the handling in the Svelte/React use-generation implementations. --- Duplicate comments: In `@packages/ai/skills/ai-core/client-persistence/SKILL.md`: - Around line 198-210: Make every persisted generation route require a validated client threadId and propagate it through the generation call. In packages/ai/skills/ai-core/client-persistence/SKILL.md lines 198-210, update the POST handler and generateImage invocation to pass threadId; in packages/ai/skills/ai-core/media-generation/SKILL.md lines 589-595, change the documented contract to reject missing threadId rather than treating it as optional. --- Nitpick comments: In `@packages/ai-react/tests/use-generation-persistence-types.test.ts`: - Around line 18-24: The shared persistence type tests in use-generation-persistence-types.test.ts should be colocated with the hooks they cover. Split the assertions into *.test.ts files alongside useGenerateImage, useGenerateVideo, useGeneration, useSummarize, and useTranscription, preserving the existing coverage and removing the centralized tests/placement.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
c3d1d0d8-9105-4d15-9bf4-26d4ae4a53f1📥 Commits
Reviewing files that changed from the base of the PR and between 951030f855fda23ce7a831b5d1e17eb49fe3be98 and 14b8d008c4f7e6a30b0adeb1cef1bd1cceedf153.
📒 Files selected for processing (65)
.changeset/generation-persistence.mddocs/persistence/generation-persistence.mddocs/persistence/keep-generated-files.mdexamples/ts-react-chat/src/routes/generation-hooks.tsxexamples/ts-react-chat/src/routes/generations.audio.tsxexamples/ts-react-chat/src/routes/generations.image.tsxexamples/ts-react-chat/src/routes/generations.speech.tsxexamples/ts-react-chat/src/routes/generations.summarize.tsxexamples/ts-react-chat/src/routes/generations.transcription.tsxexamples/ts-react-chat/src/routes/generations.video.tsxpackages/ai-angular/src/inject-generate-audio.tspackages/ai-angular/src/inject-generate-image.tspackages/ai-angular/src/inject-generate-speech.tspackages/ai-angular/src/inject-generate-video.tspackages/ai-angular/src/inject-generation.tspackages/ai-angular/src/inject-summarize.tspackages/ai-angular/src/inject-transcription.tspackages/ai-angular/tests/inject-generation.test.tspackages/ai-client/src/generation-client.tspackages/ai-client/src/generation-types.tspackages/ai-client/src/index.tspackages/ai-persistence/skills/ai-persistence/SKILL.mdpackages/ai-persistence/src/index.tspackages/ai-persistence/src/middleware.tspackages/ai-persistence/src/reconstruct-generation.tspackages/ai-persistence/src/retrieve.tspackages/ai-persistence/src/types.tspackages/ai-persistence/tests/generation-artifacts.test.tspackages/ai-persistence/tests/reconstruct-generation.test.tspackages/ai-react/src/use-generate-audio.tspackages/ai-react/src/use-generate-image.tspackages/ai-react/src/use-generate-speech.tspackages/ai-react/src/use-generate-video.tspackages/ai-react/src/use-generation.tspackages/ai-react/src/use-summarize.tspackages/ai-react/src/use-transcription.tspackages/ai-react/tests/use-generation-persistence-types.test.tspackages/ai-react/tests/use-generation.test.tspackages/ai-solid/src/use-generate-audio.tspackages/ai-solid/src/use-generate-image.tspackages/ai-solid/src/use-generate-speech.tspackages/ai-solid/src/use-generate-video.tspackages/ai-solid/src/use-generation.tspackages/ai-solid/src/use-summarize.tspackages/ai-solid/src/use-transcription.tspackages/ai-solid/tests/use-generation.test.tspackages/ai-svelte/src/create-generate-audio.svelte.tspackages/ai-svelte/src/create-generate-image.svelte.tspackages/ai-svelte/src/create-generate-speech.svelte.tspackages/ai-svelte/src/create-generate-video.svelte.tspackages/ai-svelte/src/create-generation.svelte.tspackages/ai-svelte/src/create-summarize.svelte.tspackages/ai-svelte/src/create-transcription.svelte.tspackages/ai-svelte/tests/create-generation.test.tspackages/ai-vue/src/use-generate-audio.tspackages/ai-vue/src/use-generate-image.tspackages/ai-vue/src/use-generate-speech.tspackages/ai-vue/src/use-generate-video.tspackages/ai-vue/src/use-generation.tspackages/ai-vue/src/use-summarize.tspackages/ai-vue/src/use-transcription.tspackages/ai-vue/tests/use-generation.test.tspackages/ai/skills/ai-core/client-persistence/SKILL.mdpackages/ai/skills/ai-core/media-generation/SKILL.mdtesting/e2e/src/routes/generation-persistence.tsx
🚧 Files skipped from review as they are similar to previous changes (55)
- examples/ts-react-chat/src/routes/generations.audio.tsx
- packages/ai-persistence/src/retrieve.ts
- examples/ts-react-chat/src/routes/generations.speech.tsx
- packages/ai-client/src/index.ts
- examples/ts-react-chat/src/routes/generation-hooks.tsx
- docs/persistence/generation-persistence.md
- examples/ts-react-chat/src/routes/generations.image.tsx
- examples/ts-react-chat/src/routes/generations.summarize.tsx
- packages/ai-persistence/tests/reconstruct-generation.test.ts
- packages/ai-persistence/src/index.ts
- examples/ts-react-chat/src/routes/generations.video.tsx
- packages/ai-react/src/use-generate-speech.ts
- packages/ai-react/src/use-summarize.ts
- packages/ai-react/src/use-transcription.ts
- packages/ai-persistence/src/reconstruct-generation.ts
- packages/ai-solid/src/use-generate-audio.ts
- packages/ai-vue/src/use-generate-video.ts
- packages/ai-angular/src/inject-generate-video.ts
- packages/ai-vue/src/use-transcription.ts
- examples/ts-react-chat/src/routes/generations.transcription.tsx
- docs/persistence/keep-generated-files.md
- packages/ai-react/src/use-generate-audio.ts
- testing/e2e/src/routes/generation-persistence.tsx
- packages/ai-angular/src/inject-generate-image.ts
- packages/ai-react/src/use-generate-image.ts
- packages/ai-vue/src/use-generate-speech.ts
- packages/ai-solid/src/use-summarize.ts
- packages/ai-solid/src/use-generate-image.ts
- packages/ai-vue/src/use-summarize.ts
- packages/ai-svelte/src/create-generate-audio.svelte.ts
- packages/ai-solid/src/use-generate-video.ts
- packages/ai-persistence/tests/generation-artifacts.test.ts
- packages/ai-svelte/src/create-generate-video.svelte.ts
- packages/ai-angular/src/inject-generation.ts
- packages/ai-vue/src/use-generate-audio.ts
- packages/ai-angular/src/inject-generate-speech.ts
- packages/ai-solid/src/use-generate-speech.ts
- packages/ai-angular/src/inject-summarize.ts
- packages/ai-svelte/src/create-summarize.svelte.ts
- packages/ai-vue/src/use-generate-image.ts
- packages/ai-angular/src/inject-transcription.ts
- packages/ai-react/src/use-generation.ts
- packages/ai-vue/tests/use-generation.test.ts
- packages/ai-svelte/tests/create-generation.test.ts
- packages/ai-solid/src/use-transcription.ts
- packages/ai-solid/tests/use-generation.test.ts
- packages/ai-react/tests/use-generation.test.ts
- packages/ai-svelte/src/create-generation.svelte.ts
- packages/ai-client/src/generation-types.ts
- packages/ai-react/src/use-generate-video.ts
- packages/ai-svelte/src/create-transcription.svelte.ts
- packages/ai-persistence/src/middleware.ts
- packages/ai-client/src/generation-client.ts
- packages/ai-vue/src/use-generation.ts
- packages/ai-persistence/src/types.ts
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
examples/ts-react-chat/src/routes/generations.image.tsx (1)
186-195: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAvoid rendering a broken data URL after client-side restoration.
The documented direct/server-function restore path has no image bytes. When
img.urlandimg.b64Jsonare both absent, this rendersdata:image/png;base64,undefinedinstead of a meaningful unavailable state.Proposed fix
{result && ( <div className="space-y-4"> - {result.images.map((img, i) => ( + {result.images + .filter((img) => img.url || img.b64Json) + .map((img, i) => ( <img key={i} src={img.url || `data:image/png;base64,${img.b64Json}`} alt={img.revisedPrompt || prompt} className="w-full rounded-lg border border-gray-700" /> - ))} + ))} </div> )}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/routes/generations.image.tsx` around lines 186 - 195, Update the image rendering in the result.images map to handle entries where both img.url and img.b64Json are absent: avoid constructing a data URL with undefined and render a meaningful unavailable state instead. Preserve the existing URL and base64 image rendering for entries that contain image data.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@examples/ts-react-chat/src/routes/api.generate.image.ts`: - Around line 41-64: Authorize image-generation persistence using a server-derived per-session identity rather than trusting supplied opaque IDs. In examples/ts-react-chat/src/routes/api.generate.image.ts:41-64, validate ownership of supplied threadId/runId before passing them to generateImage and withGenerationPersistence; in examples/ts-react-chat/src/routes/api.generate.image.ts:71-96, provide the authorization callback during reconstruction and verify the artifact record’s threadId before returning bytes. In examples/ts-react-chat/src/routes/generations.image.tsx:29-38, replace the shared "image:streaming" identifier with a per-user/per-thread identifier, while continuing to authorize it at the route boundary. --- Outside diff comments: In `@examples/ts-react-chat/src/routes/generations.image.tsx`: - Around line 186-195: Update the image rendering in the result.images map to handle entries where both img.url and img.b64Json are absent: avoid constructing a data URL with undefined and render a meaningful unavailable state instead. Preserve the existing URL and base64 image rendering for entries that contain image data.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
be02f6ef-0654-4d85-b07c-48aa8fc75311📥 Commits
Reviewing files that changed from the base of the PR and between 14b8d008c4f7e6a30b0adeb1cef1bd1cceedf153 and 4c0a9b4c7b44c4f8f649a57313f0e1a711ba912f.
📒 Files selected for processing (11)
docs/persistence/build-your-own-adapter.mdexamples/ts-react-chat/src/lib/generation-persistence.tsexamples/ts-react-chat/src/lib/generation-server-store.tsexamples/ts-react-chat/src/routes/api.generate.image.tsexamples/ts-react-chat/src/routes/api.interrupts.test.tsexamples/ts-react-chat/src/routes/generations.image.tsxpackages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.mdpackages/ai-persistence/src/reconstruct-generation.tspackages/ai-persistence/src/types.tspackages/ai-persistence/tests/persistence-fixtures.tspackages/ai-persistence/tests/reconstruct-generation.test.ts
💤 Files with no reviewable changes (2)
- examples/ts-react-chat/src/routes/api.interrupts.test.ts
- packages/ai-persistence/tests/reconstruct-generation.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- examples/ts-react-chat/src/lib/generation-persistence.ts
- packages/ai-persistence/tests/persistence-fixtures.ts
- packages/ai-persistence/src/reconstruct-generation.ts
- packages/ai-persistence/src/types.ts
- docs/persistence/build-your-own-adapter.md
@@ -11,7 +48,17 @@11481249 const stream = generateImage({13- adapter: openaiImage(model ?? 'gpt-image-1'),14- prompt,15- size,16- numberOfImages,50+ adapter: grokImage('grok-imagine-image'),51+ prompt: input.prompt,52+ // `size` is deliberately not forwarded: the generic image input types53+ // it as `string`, while each adapter narrows it to its own union, and54+ // this page's UI never sends one.55+ ...(input.numberOfImages56+ ? { numberOfImages: input.numberOfImages }57+ : {}),58+ ...(threadId ? { threadId } : {}),59+ ...(runId ? { runId } : {}),1760 stream: true,61+ middleware: [62+ withGenerationPersistence(persistence, {63+ artifactUrl: (ref) => artifactServeUrl(ref.artifactId),64+ }),🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
Authorize generation persistence per session instead of using the shared thread.
Any visitor can request
?threadId=image:streaming, obtain the latest restored result and its artifact URL, then fetch the artifact bytes. The POST also accepts arbitrary run/thread IDs, allowing untrusted clients to write into that shared scope.examples/ts-react-chat/src/routes/api.generate.image.ts#L41-L64: derive the effective identity server-side and authorize supplied run/thread ownership before persisting.examples/ts-react-chat/src/routes/api.generate.image.ts#L71-L96: pass an authorization callback to reconstruction and verify the artifact record’sthreadIdbefore returning its blob.examples/ts-react-chat/src/routes/generations.image.tsx#L29-L38: replace the globally shared literal with a per-user/per-thread identifier; do not treat it as authorization.
Based on learnings,
threadIdmust be treated only as an opaque lookup key and authorized at the route boundary before persistence access.📍 Affects 2 files
examples/ts-react-chat/src/routes/api.generate.image.ts#L41-L64(this comment)examples/ts-react-chat/src/routes/api.generate.image.ts#L71-L96examples/ts-react-chat/src/routes/generations.image.tsx#L29-L38
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/routes/api.generate.image.ts` around lines 41 - 64, Authorize image-generation persistence using a server-derived per-session identity rather than trusting supplied opaque IDs. In examples/ts-react-chat/src/routes/api.generate.image.ts:41-64, validate ownership of supplied threadId/runId before passing them to generateImage and withGenerationPersistence; in examples/ts-react-chat/src/routes/api.generate.image.ts:71-96, provide the authorization callback during reconstruction and verify the artifact record’s threadId before returning bytes. In examples/ts-react-chat/src/routes/generations.image.tsx:29-38, replace the shared "image:streaming" identifier with a per-user/per-thread identifier, while continuing to authorize it at the route boundary.Source: Learnings
✅ Addressed in commits 08ab3f7 to 69c1d5f
Pushed: mid-run reload resumability + persistent-generation demo#
Three commits land the generation-persistence resumability work and a demo page that exercises every surface.
What's in:
- Durable runs survive a client disconnect.
toServerSentEventsResponse(stream, { durability })now decouples the producer from the HTTP response: a reload cancels only the reader, the run keeps draining into the log, and a mount-timejoinRuntails it to completion. Persistence off (no durability) still aborts on disconnect. Additive, no public API change. - One-shot activities are resumable —
RUN_STARTEDis now a durability flush boundary, so image/speech/transcription/summarize populate the log at the start of the run instead of only at the terminal (which was fast-failing the rejoin as "run gone"). - Summarize resumes mid-run —
summarize()threadsrunId/threadIdinto the wrapped chat, and@tanstack/openai-base's ResponseschatStreamhonorsoptions.runIdforRUN_STARTED, so its delivery log keys align with the client's rejoin. - TTS restore via new
reconstructSpeechResult(surfaces the durable artifact URL, sinceTTSResult.audiohas no URL slot). - Failed rejoin settles to
errorinstead of hanging ongenerating;dispose()no longer wipes the resumable snapshot (that'sstop()'s job). - OpenAI reasoning models drop unsupported
temperature/top_p(fixesgpt-5.5summarize/chat 400s). - Example: new
/generations/persistent-generationpage; server routes fall back toreconstructGenerationon GET; the video route drops the hand-rolledstartDetachedGeneration/tailGenerationResponseand uses the plain library path (the whole point — the library owns run lifetime now). - Unit tests + changesets for all of the above. Targeted suites green:
ai1293,ai-client587,openai-base136,ai-openai242; example type-checks + builds; docs links pass.
Verified in-browser: image/video/speech/transcription/summarize all resume a mid-run reload and restore on a done-refresh; a gone/interrupted run shows a clean
error.Still TODO (not in this push)#
- E2E tests (mandatory). Playwright specs in
testing/e2e/for: mid-run reload rejoins + completes; done-refresh restores; durable-run-survives-disconnect; failed-rejoin -> error. - Full
pnpm test:prgate. Ran targeted suites + example types/build + docs links, but not the whole affected gate (sherif/knip/oxlintacross all). - Kiira: 1 pre-existing failure at
docs/persistence/generation-persistence.md:263(thecreateServerFn+getGenerationHydrationserver-fn snippet). Unrelated to this change and in a file it doesn't touch, but it will keep the docs gate red until fixed. - Code-review pass over the full diff.
- Chat cleanup:
api.persistent-chat.tsstill hand-rollsstartDetachedRun; now redundant since the library survives disconnect. Simplify + verify chat mid-reload separately. - Duplicate artifact-serve setup in the example:
generation-server-store.ts+api.artifacts.ts(used by persistent-generation) vsgeneration-server-persistence.ts+api.generate.image.artifact.ts(used bygenerations.image). Worth consolidating to one. - Audio provider in the demo defaults to
fal-audio, which 403s without a music-capable key (env-dependent; not a code bug).
- Durable runs survive a client disconnect.
tombeckenham reviewed
I've tested this thoroughly. Everything through to the skills themselves in other projects. It works beautifully.
tombeckenham merged this996a980
tombeckenham closed this
Sign in to join this conversation.
🚀 Changeset Version Preview#
19 package(s) bumped directly, 32 bumped as dependents.
🟥 Major bumps#
@tanstack/ai-angular@tanstack/ai-durable-stream@tanstack/ai-memory@tanstack/ai-openai@tanstack/ai-openrouter@tanstack/ai-persistence@tanstack/ai-preact@tanstack/ai-react@tanstack/ai-sandbox@tanstack/ai-solid@tanstack/ai-svelte@tanstack/ai-vue@tanstack/openai-base@tanstack/ai-acp@tanstack/ai-anthropic@tanstack/ai-bedrock@tanstack/ai-claude-code@tanstack/ai-code-mode@tanstack/ai-code-mode-skills@tanstack/ai-codex@tanstack/ai-elevenlabs@tanstack/ai-fal@tanstack/ai-gemini@tanstack/ai-grok@tanstack/ai-grok-build@tanstack/ai-groq@tanstack/ai-isolate-node@tanstack/ai-isolate-quickjs@tanstack/ai-mistral@tanstack/ai-ollama@tanstack/ai-opencode@tanstack/ai-react-ui@tanstack/ai-sandbox-cloudflare@tanstack/ai-sandbox-daytona@tanstack/ai-sandbox-docker@tanstack/ai-sandbox-local-process@tanstack/ai-sandbox-sprites@tanstack/ai-sandbox-vercel@tanstack/ai-solid-ui🟨 Minor bumps#
@tanstack/ai@tanstack/ai-client@tanstack/ai-devtools-core@tanstack/ai-event-client@tanstack/ai-utils🟩 Patch bumps#
@tanstack/ai-mcp@tanstack/ai-isolate-cloudflare@tanstack/ai-vue-ui@tanstack/preact-ai-devtools@tanstack/react-ai-devtools@tanstack/solid-ai-devtoolsag-ui