feat: multiple modalities from the client #263
main fromrefs/pull/263/head·merged by AlemTuzlak View on GitHub🎯 Changes#
Added the ability to send multi-modal messages from the client Added the ability to send extra body data with sendMessage api added ability to add messageIds from the client Added new e2e tests to the smoke tests harness
✅ 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
- Multimodal messaging: send text with images, audio, video, and documents in one message; sendMessage accepts multimodal payloads and optional custom IDs
- Image attachment UI: previews, removal, Enter-to-send, and file upload flows
- MIME-aware handling and detection: inline (base64) sources require mimeType; URL sources may include optional mimeType; image MIME detection utility exported
Documentation
- Expanded multimodal guides and client-side examples (React, hooks, file uploads); provider examples updated to show mimeType usage
Tests
- New comprehensive multimodal test suites and smoke tests covering image, audio, video, document, and structured outputs
- 1
Actionable comments posted: 5
🤖 Fix all issues with AI agents
In `@docs/guides/multimodal-content.md`: - Around line 432-442: The FileReader promise in handleFileUpload lacks error handling and can hang if reading fails; update the promise used in handleFileUpload to attach reader.onerror and reject the promise with the error (and optionally reader.onabort) so callers receive an error instead of waiting forever, and ensure any cleanup (e.g., removing handlers) happens on both success and error paths. In `@examples/ts-react-chat/src/routes/index.tsx`: - Around line 362-364: The forEach callback currently uses a concise arrow body that implicitly returns the value of URL.revokeObjectURL, which static analysis flags; update the callback to a block body that does not return anything — e.g., change the call on attachedImages (attachedImages.forEach((img) => URL.revokeObjectURL(img.preview))) to use a statement body like attachedImages.forEach((img) => { URL.revokeObjectURL(img.preview); }); to ensure no value is returned from the forEach callback. - Around line 292-300: The FileReader promise for producing `base64` lacks error handling and can hang on read failures; change the constructor to new Promise<string>((resolve, reject) => { ... }) and add `reader.onerror = (e) => reject(e)` (and optionally `reader.onabort = () => reject(new Error('File read aborted'))`) alongside the existing `reader.onload` handler; also consider removing/clearing handlers after resolution/rejection to avoid leaks and keep using `reader.readAsDataURL(file)` to start the read. - Around line 159-174: The image data URL is hardcoded to "image/png" when part.source.type !== 'url'; update the construction of imageUrl to use the actual MIME type from the part metadata (e.g., read a mime/type field such as part.source.mediaType or part.source.mimeType or part.metadata.mimeType) instead of "image/png" so the prefix becomes `data:{actualMime};base64,${part.source.value}` when rendering in the branch that handles part.source.type !== 'url'; keep the existing branch for URL sources unchanged. In `@packages/typescript/smoke-tests/adapters/src/tests/index.ts`: - Around line 129-157: The multimodal tests (MMJ, MMP, MMS, MMT) declare requires: ['text'] but send image content; update the test metadata and capability enum by adding a new AdapterCapability value (e.g., 'vision') to the AdapterCapability enum, then change the four tests (identifiable by id: 'MMJ','MMP','MMS','MMT' in the tests array) to requires: ['text','vision']; alternatively, if you prefer the existing IMG/TTS/TRN pattern, set skipByDefault: true on those test objects instead of changing requires — ensure references to AdapterCapability and the test objects are updated consistently.🧹 Nitpick comments (10)
packages/typescript/ai-openai/src/adapters/text.ts (1)
816-824: Consider usingdetectImageMimeTypefor consistent MIME type detection.The Anthropic and Gemini adapters use
detectImageMimeTypeto infer the actual image format from base64 magic bytes, but this adapter hardcodesimage/jpeg. While data URIs with incorrect MIME types often still work, using the utility would provide more accurate MIME types.♻️ Proposed fix to use detectImageMimeType
First, add the import at the top of the file:
import { detectImageMimeType } from '@tanstack/ai'Then update the data URI construction:
// For base64 data, construct a data URI if not already one const imageValue = part.source.value + const detectedMimeType = detectImageMimeType(imageValue) ?? 'image/jpeg' const imageUrl = imageValue.startsWith('data:') ? imageValue - : `data:image/jpeg;base64,${imageValue}` + : `data:${detectedMimeType};base64,${imageValue}`packages/typescript/ai-grok/src/adapters/text.ts (1)
505-517: Consider usingdetectImageMimeTypefor consistent MIME type detection.Similar to the OpenAI adapter, this hardcodes
image/jpegfor the data URI MIME type. UsingdetectImageMimeType(as done in Anthropic and Gemini adapters) would provide more accurate MIME types based on the actual image format.♻️ Proposed fix to use detectImageMimeType
First, add the import at the top of the file:
import { detectImageMimeType } from '@tanstack/ai'Then update the data URI construction:
// For base64 data, construct a data URI if not already one const imageValue = part.source.value + const detectedMimeType = detectImageMimeType(imageValue) ?? 'image/jpeg' const imageUrl = part.source.type === 'data' && !imageValue.startsWith('data:') - ? `data:image/jpeg;base64,${imageValue}` + ? `data:${detectedMimeType};base64,${imageValue}` : imageValuepackages/typescript/ai/src/utils.ts (1)
17-41: Consider handling data URI prefixes gracefully.The function assumes raw base64 input, but callers might accidentally pass a full data URI (e.g.,
data:image/png;base64,iVBOR...). This would returnundefinedsince the string starts withdata:rather than the magic bytes.♻️ Proposed enhancement to handle data URI input
export function detectImageMimeType( base64Data: string, ): 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | undefined { + // Strip data URI prefix if present + const data = base64Data.includes(',') + ? base64Data.split(',')[1] ?? base64Data + : base64Data + // Get first few bytes (base64 encoded) - const prefix = base64Data.substring(0, 20) + const prefix = data.substring(0, 20)packages/typescript/ai-anthropic/src/adapters/text.ts (1)
312-337: Minor optimization: detect MIME type only for base64 data sources.detectImageMimeTypeis called unconditionally, but for URL sources the detection is wasteful since the value is a URL string (not base64) and the result is unused.♻️ Proposed optimization
case 'image': { const metadata = part.metadata as AnthropicImageMetadata | undefined - // Detect mime type from base64 magic bytes if not provided - const detectedMimeType = detectImageMimeType(part.source.value) const imageSource: Base64ImageSource | URLImageSource = part.source.type === 'data' ? { type: 'base64', data: part.source.value, media_type: - metadata?.mediaType ?? detectedMimeType ?? 'image/jpeg', + metadata?.mediaType ?? + detectImageMimeType(part.source.value) ?? + 'image/jpeg', } : { type: 'url', url: part.source.value, }packages/typescript/ai-openrouter/src/adapters/text.ts (1)
593-605: Consider usingdetectImageMimeTypefor consistent MIME type detection.Similar to OpenAI and Grok adapters, this hardcodes
image/jpegfor the data URI MIME type. For consistency with Anthropic and Gemini adapters, consider usingdetectImageMimeType.♻️ Proposed fix to use detectImageMimeType
First, add the import at the top of the file:
import { detectImageMimeType } from '@tanstack/ai'Then update the data URI construction:
case 'image': { const meta = part.metadata as OpenRouterImageMetadata | undefined // For base64 data, construct a data URI if not already one const imageValue = part.source.value + const detectedMimeType = detectImageMimeType(imageValue) ?? 'image/jpeg' const imageUrl = part.source.type === 'data' && !imageValue.startsWith('data:') - ? `data:image/jpeg;base64,${imageValue}` + ? `data:${detectedMimeType};base64,${imageValue}` : imageValueexamples/ts-react-chat/src/routes/index.tsx (2)
24-29: Use the exportedgenerateMessageIdfrom@tanstack/aiinstead of duplicating.This function duplicates
generateMessageIdwhich is already exported from@tanstack/ai(visible in the re-exports atpackages/typescript/ai-client/src/index.tsline 41). Consider importing and using the shared implementation for consistency.♻️ Suggested change
-/** - * Generate a random message ID - */ -function generateMessageId(): string { - return `msg-${Date.now()}-${Math.random().toString(36).substring(2, 9)}` -} +import { generateMessageId } from '@tanstack/ai-react'Remove the local function and add
generateMessageIdto the existing imports from@tanstack/ai-react.
347-354: Redundant metadata fields: bothmediaTypeandmimeTypeare set to the same value.Consider using a single field name for consistency. Based on the type definitions,
metadatais provider-specific, but having both fields with the same value adds no benefit.♻️ Suggested simplification
contentParts.push({ type: 'image', source: { type: 'data', value: img.base64 }, - metadata: { mediaType: img.mimeType, mimeType: img.mimeType }, + metadata: { mimeType: img.mimeType }, })docs/guides/multimodal-content.md (1)
370-377: Model override example doesn't demonstrate the override.The example shows
model: 'gpt-5'in both the base body and the per-message override, which doesn't clearly demonstrate the override behavior.📝 Suggested improvement
const client = new ChatClient({ connection: fetchServerSentEvents('/api/chat'), body: { model: 'gpt-5' }, // Base body params }) // Override model for this specific message await client.sendMessage('Analyze this complex problem', { - model: 'gpt-5', + model: 'gpt-5-turbo', // Overrides base model for this request temperature: 0.2, })packages/typescript/smoke-tests/adapters/src/tests/mms-multimodal-structured.ts (2)
10-25: Extract duplicatedgetMimeTypeto a shared utility.This function is duplicated verbatim in
mmi-multimodal-image.ts. Consider extracting it to a shared module (e.g.,test-utils.ts) to follow DRY principles.♻️ Proposed refactor
Create a new file
packages/typescript/smoke-tests/adapters/src/tests/utils.ts:/** * Detect image mime type from file extension */ export function getMimeType(filename: string): string { const ext = filename.toLowerCase().split('.').pop() switch (ext) { case 'jpg': case 'jpeg': return 'image/jpeg' case 'png': return 'image/png' case 'gif': return 'image/gif' case 'webp': return 'image/webp' default: return 'image/jpeg' } }Then import from both test files:
-function getMimeType(filename: string): string { - // ... implementation -} +import { getMimeType } from './utils'
99-118: Consider extracting shared JSON validation logic.The JSON parsing and validation logic in
runMMS(lines 99-118) andrunMMT(lines 201-220) are nearly identical. For better maintainability, consider extracting a helper function.♻️ Proposed helper extraction
function parseAndValidateImageDescription( response: string ): { parsed: ImageDescription | null error?: string validationMeta: Record<string, boolean> } { let parsed: ImageDescription | null = null try { const jsonMatch = response.match(/```(?:json)?\s*([\s\S]*?)```/) const jsonStr = jsonMatch && jsonMatch[1] ? jsonMatch[1].trim() : response.trim() parsed = JSON.parse(jsonStr) } catch { try { parsed = JSON.parse(response) } catch { return { parsed: null, error: `Failed to parse response as JSON: ${response.substring(0, 200)}`, validationMeta: {} } } } const hasDescription = typeof parsed?.description === 'string' && parsed.description.length > 0 const hasMainSubject = typeof parsed?.mainSubject === 'string' && parsed.mainSubject.length > 0 const hasColors = Array.isArray(parsed?.colors) && parsed.colors.length > 0 const hasTextBoolean = typeof parsed?.hasText === 'boolean' return { parsed, validationMeta: { hasDescription, hasMainSubject, hasColors, hasTextBoolean } } }Also applies to: 201-220
@@ -317,0 +422,21 @@422+423+```tsx424+import { useChat } from '@tanstack/ai-react'425+import { fetchServerSentEvents } from '@tanstack/ai-client'426+427+function ChatWithFileUpload() {428+ const { sendMessage } = useChat({429+ connection: fetchServerSentEvents('/api/chat'),430+ })431+432+ const handleFileUpload = async (file: File) => {433+ // Convert file to base64434+ const base64 = await new Promise<string>((resolve) => {435+ const reader = new FileReader()436+ reader.onload = () => {437+ const result = reader.result as string438+ // Remove data URL prefix (e.g., "data:image/png;base64,")439+ resolve(result.split(',')[1])440+ }441+ reader.readAsDataURL(file)442+ })⚠️ Potential issue | 🟡 Minor
File reading promise missing error handling.
The
FileReaderpromise doesn't handle theonerrorevent. If file reading fails, the promise will never resolve, causing the function to hang.📝 Suggested improvement
// Convert file to base64 - const base64 = await new Promise<string>((resolve) => { + const base64 = await new Promise<string>((resolve, reject) => { const reader = new FileReader() reader.onload = () => { const result = reader.result as string // Remove data URL prefix (e.g., "data:image/png;base64,") resolve(result.split(',')[1]) } + reader.onerror = () => reject(new Error('Failed to read file')) reader.readAsDataURL(file) })📝 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.
Suggested change443+ const handleFileUpload = async (file: File) => {444+ // Convert file to base64445+ const base64 = await new Promise<string>((resolve, reject) => {446+ const reader = new FileReader()447+ reader.onload = () => {448+ const result = reader.result as string449+ // Remove data URL prefix (e.g., "data:image/png;base64,")450+ resolve(result.split(',')[1])451+ }452+ reader.onerror = () => reject(new Error('Failed to read file'))453+ reader.readAsDataURL(file)454+ })🤖 Prompt for AI Agents
In `@docs/guides/multimodal-content.md` around lines 432 - 442, The FileReader promise in handleFileUpload lacks error handling and can hang if reading fails; update the promise used in handleFileUpload to attach reader.onerror and reject the promise with the error (and optionally reader.onabort) so callers receive an error instead of waiting forever, and ensure any cleanup (e.g., removing handlers) happens on both success and error paths.examples/ts-react-chat/src/routes/index.tsx lines 159 to 174Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -148,3 +156,19 @@148156 )149157 }150158159+ // Render image parts160+ if (part.type === 'image') {161+ const imageUrl =162+ part.source.type === 'url'163+ ? part.source.value164+ : `data:image/png;base64,${part.source.value}`165+ return (166+ <div key={`image-${index}`} className="mt-2 mb-2">167+ <img168+ src={imageUrl}169+ alt="Attached image"170+ className="max-w-md rounded-lg border border-gray-700"171+ />172+ </div>173+ )174+ }⚠️ Potential issue | 🟡 Minor
Use the actual MIME type instead of hardcoding
image/png.When rendering base64 images, the code hardcodes
data:image/png;base64,but the actual MIME type may differ (e.g., JPEG, GIF, WebP). The metadata should contain the original MIME type.🐛 Proposed fix
if (part.type === 'image') { + // Extract mime type from metadata if available + const mimeType = (part.metadata as { mimeType?: string })?.mimeType || 'image/png' const imageUrl = part.source.type === 'url' ? part.source.value - : `data:image/png;base64,${part.source.value}` + : `data:${mimeType};base64,${part.source.value}`📝 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.
Suggested change159- // Render image parts160- if (part.type === 'image') {161- const imageUrl =162- part.source.type === 'url'163- ? part.source.value164- : `data:image/png;base64,${part.source.value}`165- return (166- <div key={`image-${index}`} className="mt-2 mb-2">167- <img168- src={imageUrl}169- alt="Attached image"170- className="max-w-md rounded-lg border border-gray-700"171- />172- </div>173- )174- }159+ // Render image parts160+ if (part.type === 'image') {161+ // Extract mime type from metadata if available162+ const mimeType = (part.metadata as { mimeType?: string })?.mimeType || 'image/png'163+ const imageUrl =164+ part.source.type === 'url'165+ ? part.source.value166+ : `data:${mimeType};base64,${part.source.value}`167+ return (168+ <div key={`image-${index}`} className="mt-2 mb-2">169+ <img170+ src={imageUrl}171+ alt="Attached image"172+ className="max-w-md rounded-lg border border-gray-700"173+ />174+ </div>175+ )176+ }🤖 Prompt for AI Agents
In `@examples/ts-react-chat/src/routes/index.tsx` around lines 159 - 174, The image data URL is hardcoded to "image/png" when part.source.type !== 'url'; update the construction of imageUrl to use the actual MIME type from the part metadata (e.g., read a mime/type field such as part.source.mediaType or part.source.mimeType or part.metadata.mimeType) instead of "image/png" so the prefix becomes `data:{actualMime};base64,${part.source.value}` when rendering in the branch that handles part.source.type !== 'url'; keep the existing branch for URL sources unchanged.✅ Addressed in commit 4940683
@@ -245,0 +280,21 @@280+ if (!files || files.length === 0) return281+282+ const newImages: Array<{283+ id: string284+ base64: string285+ mimeType: string286+ preview: string287+ }> = []288+289+ for (const file of Array.from(files)) {290+ if (!file.type.startsWith('image/')) continue291+292+ const base64 = await new Promise<string>((resolve) => {293+ const reader = new FileReader()294+ reader.onload = () => {295+ const result = reader.result as string296+ // Remove data URL prefix (e.g., "data:image/png;base64,")297+ resolve(result.split(',')[1])298+ }299+ reader.readAsDataURL(file)300+ })⚠️ Potential issue | 🟡 Minor
Add error handling for FileReader.
The
FileReaderpromise doesn't handle theonerrorcase, which could cause the promise to hang indefinitely if the file read fails.🛡️ Proposed fix to add error handling
const base64 = await new Promise<string>((resolve, reject) => { const reader = new FileReader() reader.onload = () => { const result = reader.result as string // Remove data URL prefix (e.g., "data:image/png;base64,") resolve(result.split(',')[1]) } + reader.onerror = () => reject(reader.error) reader.readAsDataURL(file) })📝 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.
Suggested change292- const base64 = await new Promise<string>((resolve) => {293- const reader = new FileReader()294- reader.onload = () => {295- const result = reader.result as string296- // Remove data URL prefix (e.g., "data:image/png;base64,")297- resolve(result.split(',')[1])298- }299- reader.readAsDataURL(file)300- })292+ const base64 = await new Promise<string>((resolve, reject) => {293+ const reader = new FileReader()294+ reader.onload = () => {295+ const result = reader.result as string296+ // Remove data URL prefix (e.g., "data:image/png;base64,")297+ resolve(result.split(',')[1])298+ }299+ reader.onerror = () => reject(reader.error)300+ reader.readAsDataURL(file)301+ })🤖 Prompt for AI Agents
In `@examples/ts-react-chat/src/routes/index.tsx` around lines 292 - 300, The FileReader promise for producing `base64` lacks error handling and can hang on read failures; change the constructor to new Promise<string>((resolve, reject) => { ... }) and add `reader.onerror = (e) => reject(e)` (and optionally `reader.onabort = () => reject(new Error('File read aborted'))`) alongside the existing `reader.onload` handler; also consider removing/clearing handlers after resolution/rejection to avoid leaks and keep using `reader.readAsDataURL(file)` to start the read.@@ -245,0 +344,21 @@344+ contentParts.push({ type: 'text', content: input.trim() })345+ }346+347+ // Add images with mime type metadata348+ for (const img of attachedImages) {349+ contentParts.push({350+ type: 'image',351+ source: { type: 'data', value: img.base64 },352+ metadata: { mediaType: img.mimeType, mimeType: img.mimeType },353+ })354+ }355+356+ // Send with custom message ID357+ sendMessage({358+ content: contentParts,359+ id: generateMessageId(),360+ })361+362+ // Clean up image previews363+ attachedImages.forEach((img) => URL.revokeObjectURL(img.preview))364+ setAttachedImages([])⚠️ Potential issue | 🟡 Minor
Fix the
forEachcallback to not return a value.The static analysis tool flagged this: the callback passed to
forEach()should not return a value.URL.revokeObjectURLreturnsundefined, but using it in an arrow function expression body implies a return.🐛 Proposed fix
// Clean up image previews - attachedImages.forEach((img) => URL.revokeObjectURL(img.preview)) + for (const img of attachedImages) { + URL.revokeObjectURL(img.preview) + } setAttachedImages([])📝 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.
Suggested change361-362- // Clean up image previews363- attachedImages.forEach((img) => URL.revokeObjectURL(img.preview))361+ // Clean up image previews362+ for (const img of attachedImages) {363+ URL.revokeObjectURL(img.preview)364+ }365+ setAttachedImages([])🧰 Tools
🪛 Biome (2.3.13)
[error] 363-363: This callback passed to forEach() iterable method should not return a value.
Either remove this return or remove the returned value.
(lint/suspicious/useIterableCallbackReturn)
🤖 Prompt for AI Agents
In `@examples/ts-react-chat/src/routes/index.tsx` around lines 362 - 364, The forEach callback currently uses a concise arrow body that implicitly returns the value of URL.revokeObjectURL, which static analysis flags; update the callback to a block body that does not return anything — e.g., change the call on attachedImages (attachedImages.forEach((img) => URL.revokeObjectURL(img.preview))) to use a statement body like attachedImages.forEach((img) => { URL.revokeObjectURL(img.preview); }); to ensure no value is returned from the forEach callback.@@ -127,0 +137,21 @@137+ {138+ id: 'MMP',139+ name: 'Multimodal PNG',140+ description: 'Describe a PNG image (beach scene with AG UI text)',141+ run: runMMP,142+ requires: ['text'],143+ },144+ {145+ id: 'MMS',146+ name: 'Multimodal Structured JPEG',147+ description: 'Describe a JPEG image with structured JSON output',148+ run: runMMS,149+ requires: ['text'],150+ },151+ {152+ id: 'MMT',153+ name: 'Multimodal Structured PNG',154+ description: 'Describe a PNG image with structured JSON output',155+ run: runMMT,156+ requires: ['text'],157+ },⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
# First, let's understand the file structure and locate the test file git ls-files packages/typescript/smoke-tests/adapters/ | head -20Repository: TanStack/ai
Length of output: 1368
🏁 Script executed:
# Find AdapterCapability definition rg -n "type AdapterCapability|enum AdapterCapability|AdapterCapability\s*=" --type ts -g '**/*.ts'Repository: TanStack/ai
Length of output: 149
🏁 Script executed:
# Check the full test file to see all test definitions and how capabilities are used wc -l packages/typescript/smoke-tests/adapters/src/tests/index.tsRepository: TanStack/ai
Length of output: 118
🏁 Script executed:
# Search for vision/multimodal capability or references rg -n "vision|multimodal" --type ts -g '**/adapters/**'Repository: TanStack/ai
Length of output: 2253
🏁 Script executed:
# Check IMG, TTS, TRN tests mentioned in the review to see skipByDefault pattern rg -n "'IMG'|'TTS'|'TRN'" --type ts -g '**/tests/**'Repository: TanStack/ai
Length of output: 291
🏁 Script executed:
# Look at how ContentPart is used in adapters rg -n "ContentPart" --type ts -g '**/adapters/**'Repository: TanStack/ai
Length of output: 4726
🏁 Script executed:
# Read the AdapterCapability definition and context sed -n '20,50p' packages/typescript/smoke-tests/adapters/src/tests/index.tsRepository: TanStack/ai
Length of output: 785
🏁 Script executed:
# Read the test definitions including IMG, TTS, TRN to see skipByDefault pattern sed -n '100,160p' packages/typescript/smoke-tests/adapters/src/tests/index.tsRepository: TanStack/ai
Length of output: 1512
🏁 Script executed:
# Check if there's a skipByDefault property mentioned anywhere rg -n "skipByDefault" --type ts -g '**/adapters/**'Repository: TanStack/ai
Length of output: 883
🏁 Script executed:
# Read the mmi-multimodal-image.ts test implementation to see what happens cat packages/typescript/smoke-tests/adapters/src/tests/mmi-multimodal-image.tsRepository: TanStack/ai
Length of output: 5918
🏁 Script executed:
# Check how adapters handle image content that they may not support # Look for error handling in adapter implementations rg -n "type.*image|image.*support|unsupported.*image" --type ts -g '**/ai-*/src/adapters/**' -A 2Repository: TanStack/ai
Length of output: 2916
🏁 Script executed:
# Check the harness to understand test execution and error handling cat packages/typescript/smoke-tests/adapters/src/harness.tsRepository: TanStack/ai
Length of output: 11441
Add 'vision' capability to AdapterCapability enum and update multimodal tests accordingly.
Multimodal tests (MMJ, MMP, MMS, MMT) declare
requires: ['text']but actually send image content that requires vision support. TheAdapterCapabilityenum lacks a 'vision' or 'multimodal' option to properly declare this dependency. This mismatch means these tests will attempt to run on all text adapters, failing on those without vision support (e.g., text-only models).Recommended approach: Add 'vision' to the AdapterCapability enum and update these four tests to
requires: ['text', 'vision']. Alternatively, follow the IMG/TTS/TRN pattern by addingskipByDefault: trueto reduce noise from unsupported adapters.🤖 Prompt for AI Agents
In `@packages/typescript/smoke-tests/adapters/src/tests/index.ts` around lines 129 - 157, The multimodal tests (MMJ, MMP, MMS, MMT) declare requires: ['text'] but send image content; update the test metadata and capability enum by adding a new AdapterCapability value (e.g., 'vision') to the AdapterCapability enum, then change the four tests (identifiable by id: 'MMJ','MMP','MMS','MMT' in the tests array) to requires: ['text','vision']; alternatively, if you prefer the existing IMG/TTS/TRN pattern, set skipByDefault: true on those test objects instead of changing requires — ensure references to AdapterCapability and the test objects are updated consistently.View your CI Pipeline Execution ↗ for commit 33c9e54a5dfb65646e50ee27544c95860556f95d
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 7s View ↗ nx run-many --targets=build --exclude=examples/**✅ Succeeded 1s View ↗
☁️ Nx Cloud last updated this comment at
2026-02-07 12:43:13UTC@tanstack/ai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@263@tanstack/ai-anthropic
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@263@tanstack/ai-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@263@tanstack/ai-devtools-core
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@263@tanstack/ai-gemini
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@263@tanstack/ai-grok
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@263@tanstack/ai-ollama
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@263@tanstack/ai-openai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@263@tanstack/ai-openrouter
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@263@tanstack/ai-preact
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@263@tanstack/ai-react
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@263@tanstack/ai-react-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@263@tanstack/ai-solid
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@263@tanstack/ai-solid-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@263@tanstack/ai-svelte
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@263@tanstack/ai-vue
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@263@tanstack/ai-vue-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@263@tanstack/preact-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@263@tanstack/react-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@263@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@263commit:
33c9e54Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@docs/guides/multimodal-content.md`: - Around line 464-473: The example passed to sendMessage places mimeType inside the metadata object incorrectly; update the content payload so that the file item's mimeType is moved into the source object (i.e., for the array element with keys type and source, add mimeType under source rather than metadata) to match the type definitions and other examples; locate the sendMessage call and adjust the file element structure (the object with fields type, source, metadata) so source includes mimeType and metadata is either removed or left for other metadata only.🧹 Nitpick comments (4)
packages/typescript/ai-react/tests/use-chat.test.ts (1)
1313-1345: Consider adding audio URL test for completeness.The tests cover audio with data source but not with URL source. For consistency with image, video, and document tests (which cover both URL and data sources), consider adding a test for audio URLs.
📝 Suggested test case
it('should send a multimodal message with audio URL', async () => { const chunks = createTextChunks('The audio says hello') const adapter = createMockConnectionAdapter({ chunks }) const { result } = renderUseChat({ connection: adapter }) await result.current.sendMessage({ content: [ { type: 'text', content: 'Transcribe this audio' }, { type: 'audio', source: { type: 'url', value: 'https://example.com/audio.mp3' }, }, ], }) await waitFor(() => { expect(result.current.messages.length).toBeGreaterThan(0) }) const userMessage = result.current.messages.find((m) => m.role === 'user') expect(userMessage?.parts[1]).toEqual({ type: 'audio', source: { type: 'url', value: 'https://example.com/audio.mp3' }, }) })examples/ts-react-chat/src/routes/index.tsx (1)
24-29: Consider using the exportedgenerateMessageIdfrom@tanstack/aiinstead of duplicating it.This local implementation duplicates the utility already exported from
packages/typescript/ai/src/activities/chat/messages.ts. Using the exported version would reduce code duplication and ensure consistency across the codebase.Note: There's a subtle difference - the exported version uses
substring(7)while this usessubstring(2, 9). If the 7-character output is intentional for consistency, import from@tanstack/ai.♻️ Suggested change
-/** - * Generate a random message ID - */ -function generateMessageId(): string { - return `msg-${Date.now()}-${Math.random().toString(36).substring(2, 9)}` -} +import { generateMessageId } from '@tanstack/ai'packages/typescript/smoke-tests/adapters/src/tests/mms-multimodal-structured.ts (2)
30-45: RenameSTRUCTURED_PROMPTto camelCase for consistency. This keeps variable naming aligned with the codebase convention.♻️ Proposed rename
-const STRUCTURED_PROMPT = `Analyze this image and provide a structured description. Return ONLY valid JSON (no markdown code blocks) matching this schema: +const structuredPrompt = `Analyze this image and provide a structured description. Return ONLY valid JSON (no markdown code blocks) matching this schema: { "description": "A brief description of what the image shows", "hasText": true/false, "textContent": "The text content visible in the image, if any", "mainSubject": "The main subject or focal point of the image", "colors": ["array", "of", "primary", "colors"] }` @@ - content: STRUCTURED_PROMPT, + content: structuredPrompt, @@ - content: STRUCTURED_PROMPT, + content: structuredPrompt,As per coding guidelines:
**/*.{ts,tsx,js,jsx}: Use camelCase for function and variable names throughout the codebase.
55-147: Consider extracting shared validation/payload logic to reduce duplication withrunMMT. Both runners repeat the same fixture loading, content construction, and JSON validation; a shared helper would make future changes safer and smaller.@@ -317,0 +453,21 @@453+ })454+455+ // Determine content type based on file type456+ const type = file.type.startsWith('image/')457+ ? 'image'458+ : file.type.startsWith('audio/')459+ ? 'audio'460+ : file.type.startsWith('video/')461+ ? 'video'462+ : 'document'463+464+ await sendMessage({465+ content: [466+ { type: 'text', content: `Please analyze this ${type}` },467+ {468+ type,469+ source: { type: 'data', value: base64 },470+ metadata: { mimeType: file.type }471+ }472+ ]473+ })⚠️ Potential issue | 🟡 Minor
Incorrect mimeType placement in file upload example.
The example places
mimeTypeinmetadata, but according to the type definitions and all other examples in this document,mimeTypeshould be in thesourceobject for data sources.📝 Proposed fix
await sendMessage({ content: [ { type: 'text', content: `Please analyze this ${type}` }, { type, - source: { type: 'data', value: base64 }, - metadata: { mimeType: file.type } + source: { type: 'data', value: base64, mimeType: file.type } } ] })🤖 Prompt for AI Agents
In `@docs/guides/multimodal-content.md` around lines 464 - 473, The example passed to sendMessage places mimeType inside the metadata object incorrectly; update the content payload so that the file item's mimeType is moved into the source object (i.e., for the array element with keys type and source, add mimeType under source rather than metadata) to match the type definitions and other examples; locate the sendMessage call and adjust the file element structure (the object with fields type, source, metadata) so source includes mimeType and metadata is either removed or left for other metadata only.jherr approved these changes
LGTM
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@packages/typescript/ai-client/src/chat-client.ts`: - Around line 423-429: The mergedBody construction in sendMessage (where mergedBody = { ...this.body, ...this.pendingMessageBody, conversationId: this.uniqueId }) silently overrides any caller-supplied conversationId from the per-message body; update sendMessage's JSDoc near the function (and/or add a short warning log in sendMessage) to explicitly state that conversationId is forced to this.uniqueId and will override per-message values, or alternatively change the merge order to preserve a caller-supplied conversationId if that behavior is desired—refer to mergedBody, this.body, this.pendingMessageBody, and this.uniqueId when making the change. - Around line 334-337: The empty-content guard currently only checks string inputs via the emptyMessage variable and lets MultimodalContent values with empty payloads through; update the check to detect MultimodalContent (type or interface name MultimodalContent) and treat it as empty when its inner content is an empty string or an empty array. Concretely, inside the method that defines emptyMessage (referencing emptyMessage and this.isLoading) add a branch that detects MultimodalContent (or use a small helper isMultimodalContent) and returns true when its .content is "" after trim or when .content is an array with length === 0, then keep the existing early return if (emptyMessage || this.isLoading).🧹 Nitpick comments (1)
packages/typescript/ai-client/src/chat-client.ts (1)
29-29: Consider passingbodyas a parameter tostreamResponseinstead of using a class field.pendingMessageBodyintroduces temporal coupling —streamResponsedepends on this field being set by its caller. Since onlysendMessageneeds per-message body, an optional parameter onstreamResponsewould be more explicit and eliminate the need for set-then-clear bookkeeping:private async streamResponse(perMessageBody?: Record<string, any>): Promise<void> {This is a minor structural improvement and entirely optional.
Also applies to: 402-437
@@ -286,5 +319,19 @@319+ * {320+ * content: [321+ * { type: 'text', content: 'Describe this audio' },322+ * { type: 'audio', source: { type: 'data', value: 'base64...' } }323+ * ],324+ * id: 'custom-message-id'325+ * },326+ * { model: 'gpt-4-audio' }327+ * )328+ * ```286329 */287- async sendMessage(content: string): Promise<void> {288- if (!content.trim() || this.isLoading) {330+ async sendMessage(331+ content: string | MultimodalContent,332+ body?: Record<string, any>,333+ ): Promise<void> {334+ const emptyMessage = typeof content === 'string' && !content.trim()335+ if (emptyMessage || this.isLoading) {289336 return290337 }⚠️ Potential issue | 🟡 Minor
Empty-content guard doesn't cover
MultimodalContentinputs.A
MultimodalContentwithcontent: ''orcontent: []bypasses the guard and sends a contentless user message. Consider extending the check:Proposed fix
- const emptyMessage = typeof content === 'string' && !content.trim() - if (emptyMessage || this.isLoading) { + const emptyMessage = + typeof content === 'string' + ? !content.trim() + : typeof content.content === 'string' + ? !content.content.trim() + : content.content.length === 0 + if (emptyMessage || this.isLoading) { return }🤖 Prompt for AI Agents
In `@packages/typescript/ai-client/src/chat-client.ts` around lines 334 - 337, The empty-content guard currently only checks string inputs via the emptyMessage variable and lets MultimodalContent values with empty payloads through; update the check to detect MultimodalContent (type or interface name MultimodalContent) and treat it as empty when its inner content is an empty string or an empty array. Concretely, inside the method that defines emptyMessage (referencing emptyMessage and this.isLoading) add a branch that detects MultimodalContent (or use a small helper isMultimodalContent) and returns true when its .content is "" after trim or when .content is an array with length === 0, then keep the existing early return if (emptyMessage || this.isLoading).@@ -351,8 +420,10 @@351420 // Call onResponse callback352421 await this.callbacksRef.current.onResponse()353422354- // Include conversationId in the body for server-side event correlation355- const bodyWithConversationId = {423+ // Merge body: base body + per-message body (per-message takes priority)424+ // Include conversationId for server-side event correlation425+ const mergedBody = {356426 ...this.body,427+ ...this.pendingMessageBody,357428 conversationId: this.uniqueId,358429 }⚠️ Potential issue | 🟡 Minor
conversationIdsilently overrides per-message body value.The
conversationIdproperty is assigned after spreadingpendingMessageBody, so a caller-suppliedconversationIdin thebodyparameter will be silently discarded. This is likely intentional, but the JSDoc onsendMessage(line 299) says "per-message body taking priority" without noting this exception. A brief doc note or a warning log would avoid confusion.🤖 Prompt for AI Agents
In `@packages/typescript/ai-client/src/chat-client.ts` around lines 423 - 429, The mergedBody construction in sendMessage (where mergedBody = { ...this.body, ...this.pendingMessageBody, conversationId: this.uniqueId }) silently overrides any caller-supplied conversationId from the per-message body; update sendMessage's JSDoc near the function (and/or add a short warning log in sendMessage) to explicitly state that conversationId is forced to this.uniqueId and will override per-message values, or alternatively change the merge order to preserve a caller-supplied conversationId if that behavior is desired—refer to mergedBody, this.body, this.pendingMessageBody, and this.uniqueId when making the change.AlemTuzlak merged this0158d14
AlemTuzlak closed this
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
Adds first-class multimodal support: new multimodal types and utils, ChatClient.sendMessage accepts multimodal payloads and per-message body, adapters build data: URIs using mimeType, UI/example file-attachment flow, message conversion/stream updates, tests, and multimodal smoke tests.
Changes#
docs/guides/multimodal-content.md,examples/ts-react-chat/src/routes/index.tsxmimeType, add client-side file upload, previews, removal, custom IDs, and send multimodalContentPartarrays (data & URL sources).packages/typescript/ai-client/src/chat-client.ts,packages/typescript/ai-client/src/events.ts,packages/typescript/ai-client/src/types.ts,packages/typescript/ai-client/src/index.tssendMessageto `stringpackages/typescript/ai/src/types.ts,packages/typescript/ai/src/utils.ts,packages/typescript/ai/src/index.tsContentPartsources (datarequiresmimeType,urloptional), added multimodal MessagePart variants, anddetectImageMimeTypeutil (re-exported).packages/typescript/ai/src/activities/chat/messages.ts,packages/typescript/ai/src/activities/chat/stream/processor.tsContentPart[]for multimodal messages;addUserMessagenow accepts `stringpackages/typescript/ai-anthropic/src/adapters/text.ts,packages/typescript/ai-gemini/src/adapters/text.ts,packages/typescript/ai-grok/src/adapters/text.ts,packages/typescript/ai-openai/src/adapters/text.ts,packages/typescript/ai-openrouter/src/adapters/text.tspart.source.mimeTypefor data/URL sources and constructdata:URIs for base64 inline data when needed; removed metadata-based fallbacks and simplified mime resolution.packages/typescript/ai-devtools/src/store/ai-context.tsxsource/metadata; mapping updated to include/skip multimodal parts.packages/typescript/ai-client/tests/chat-client.test.ts,packages/typescript/ai/tests/message-converters.test.ts,packages/typescript/ai-react/tests/use-chat.test.tspackages/typescript/smoke-tests/adapters/src/tests/index.ts,.../mmi-multimodal-image.ts,.../mms-multimodal-structured.tspackages/typescript/ai-anthropic/src/index.ts,packages/typescript/ai-gemini/src/index.tspackages/typescript/smoke-tests/adapters/src/adapters/index.ts,.changeset/*grok-4; added changesets for patch releases and multimodal feature bump notes.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs#
messageSentsignature changes.Suggested reviewers#
Poem#
🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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.
❤️ Share