Repository navigation
feat(console-ui): image upload in chat for vision models (Gemma 4) - #295
Conversation
Adds Gemma 4-style image input to the chat composer: - ChatInput: file picker + paste intake, staged-image thumbnails with remove, per-message cap, validation; the attach button is shown only for vision models (modelSupportsImages). - useImageUpload hook: staging/validation/base64/cap state, extracted so the composer stays thin. - image-upload lib: validateImageFile, fileToDataURL, modelSupportsImages, buildApiContent (OpenAI/OpenRouter image_url parts, text-first). Media is base64 data: URIs only — the provider is E2E and rejects remote URLs. - Message model carries images[] (in-memory + display); stripped from persistence to avoid blowing the localStorage quota. - page.tsx threads images through send + retry via buildApiContent. - ChatMessage renders attached image thumbnails on user turns. - Tests: image-upload (19) + useImageUpload hook (5). Note: the upload button uses a vision-family bridge for Gemma 4 until the model catalog reports input_modalities/capabilities for VLMs.
…tion Review follow-ups: - useImageUpload: enforce MAX_IMAGES_PER_MESSAGE inside the setImages updater so two overlapping intakes (paste landing mid file-read) can't each append against a stale count and exceed the cap; add a race regression test. - page.tsx: document at both send sites that m.images is undefined for turns restored from persistence (images stripped from localStorage), so prior-turn image context isn't re-sent after a reload (IndexedDB follow-up).
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — 1 finding(s)
- 🔵 [INFO]
console-ui/src/lib/image-upload.ts:44-59— FileReader error handling may expose internal file system paths- Suggestion: Sanitize error messages to avoid potential path disclosure: reader.onerror = () => reject(new Error('Failed to read image file'))
Performance — 4 finding(s) (3 blocking)
- 🟡 [MEDIUM]
console-ui/src/hooks/useImageUpload.ts:70-72— Unbounded array growth in setImages updater without pre-allocation- Suggestion: Pre-allocate the result array with known size: const result = new Array(Math.min(prev.length + accepted.length, MAX_IMAGES_PER_MESSAGE)); then fill it efficiently instead of using spread operator and slice
- 🔵 [INFO]
console-ui/src/lib/image-upload.ts:44-59— Synchronous FileReader operations block the main thread during base64 encoding- Suggestion: Consider using Web Workers for large image processing or implement chunked reading with requestIdleCallback to avoid blocking the UI thread
- 🟡 [MEDIUM]
console-ui/src/app/page.tsx:148-151— buildApiContent called redundantly for each message in array map- Suggestion: Memoize buildApiContent results or pre-compute the API format when storing messages to avoid repeated text/image processing
- 🟡 [MEDIUM]
console-ui/src/app/page.tsx:279-281— Duplicate buildApiContent processing in retry path- Suggestion: Extract message formatting logic to avoid duplicate buildApiContent calls between send and retry paths
Type_diligence — 1 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/lib/api.ts:97-101— ChatMessage.content uses union with any-typed array without type guards- Suggestion: Add runtime type guards when processing ChatMessage.content to safely distinguish between string and ChatContentPart[] cases, or use a discriminated union with explicit type field
Additive_complexity — 4 finding(s) (1 blocking)
- 🔵 [INFO]
console-ui/src/lib/image-upload.ts:70— Hardcoded regex pattern for vision model detection creates maintenance burden- Suggestion: Consider making VISION_MODEL_PATTERN configurable or moving to a simple string array of known vision model IDs/families
- 🟡 [MEDIUM]
console-ui/src/hooks/useImageUpload.ts:74-76— Cap enforcement duplicated between addFiles validation and state updater- Suggestion: Extract cap enforcement to a single helper function or rely only on the state updater slice() to avoid redundant checks
- 🔵 [INFO]
console-ui/src/app/page.tsx:145-151— buildApiContent mapping duplicated in handleSend and retry logic- Suggestion: Extract message transformation to a shared helper function to avoid repeating the same mapping logic
- 🔵 [INFO]
console-ui/src/lib/image-upload.ts:77-91— modelSupportsImages has complex fallback chain for simple boolean check- Suggestion: Consider simplifying to just check input_modalities and a whitelist, removing the multi-field fallback complexity
10 finding(s) total, 5 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| /** Read a File into a base64 `data:` URI (e.g. `data:image/png;base64,...`). */ | ||
| export function fileToDataURL(file: File): Promise<string> { | ||
| return new Promise((resolve, reject) => { | ||
| const reader = new FileReader(); | ||
| reader.onerror = () => | ||
| reject(reader.error ?? new Error("Failed to read image file")); | ||
| reader.onload = () => { | ||
| const result = reader.result; | ||
| if (typeof result === "string") { | ||
| resolve(result); | ||
| } else { | ||
| reject(new Error("Unexpected file read result (not a data URL)")); | ||
| } | ||
| }; | ||
| reader.readAsDataURL(file); | ||
| }); |
There was a problem hiding this comment.
🔵 [INFO] 🔒 FileReader error handling may expose internal file system paths
💡 Suggestion: Sanitize error messages to avoid potential path disclosure: reader.onerror = () => reject(new Error('Failed to read image file'))
📊 Score: 2×3 = 6 · Category: missing-input-validation
| // while a prior file read is still awaiting) both read the same stale | ||
| // `images.length` above, so enforce the limit against the latest state. | ||
| setImages((prev) => [...prev, ...accepted].slice(0, MAX_IMAGES_PER_MESSAGE)); |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Unbounded array growth in setImages updater without pre-allocation
💡 Suggestion: Pre-allocate the result array with known size: const result = new Array(Math.min(prev.length + accepted.length, MAX_IMAGES_PER_MESSAGE)); then fill it efficiently instead of using spread operator and slice
📊 Score: 3×4 = 12 · Category: unbounded_allocations
| /** Read a File into a base64 `data:` URI (e.g. `data:image/png;base64,...`). */ | ||
| export function fileToDataURL(file: File): Promise<string> { | ||
| return new Promise((resolve, reject) => { | ||
| const reader = new FileReader(); | ||
| reader.onerror = () => | ||
| reject(reader.error ?? new Error("Failed to read image file")); | ||
| reader.onload = () => { | ||
| const result = reader.result; | ||
| if (typeof result === "string") { | ||
| resolve(result); | ||
| } else { | ||
| reject(new Error("Unexpected file read result (not a data URL)")); | ||
| } | ||
| }; | ||
| reader.readAsDataURL(file); | ||
| }); |
There was a problem hiding this comment.
🔵 [INFO] ⚡ Synchronous FileReader operations block the main thread during base64 encoding
💡 Suggestion: Consider using Web Workers for large image processing or implement chunked reading with requestIdleCallback to avoid blocking the UI thread
📊 Score: 2×3 = 6 · Category: blocking_io
| // Follow-up: durable image storage (IndexedDB) to close this gap. | ||
| const userMessages = [...priorMessages, userMsg].map((m) => ({ | ||
| role: m.role, | ||
| content: m.content, | ||
| content: buildApiContent(m.content, m.images), |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ buildApiContent called redundantly for each message in array map
💡 Suggestion: Memoize buildApiContent results or pre-compute the API format when storing messages to avoid repeated text/image processing
📊 Score: 2×4 = 8 · Category: repeated_work
| // m.images is undefined after a reload (stripped from persistence), | ||
| // so retrying an image turn post-reload re-sends text only. | ||
| .map((m) => ({ role: m.role, content: buildApiContent(m.content, m.images) })), |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Duplicate buildApiContent processing in retry path
💡 Suggestion: Extract message formatting logic to avoid duplicate buildApiContent calls between send and retry paths
📊 Score: 2×4 = 8 · Category: repeated_work
| role: "user" | "assistant" | "system"; | ||
| content: string; | ||
| // `string` for text-only turns (unchanged wire shape); a parts array when | ||
| // the turn carries images, matching the standard OpenAI/OpenRouter | ||
| // `image_url` content-part format. | ||
| content: string | ChatContentPart[]; |
There was a problem hiding this comment.
🟡 [MEDIUM] 🏷️ ChatMessage.content uses union with any-typed array without type guards
💡 Suggestion: Add runtime type guards when processing ChatMessage.content to safely distinguish between string and ChatContentPart[] cases, or use a discriminated union with explicit type field
📊 Score: 3×4 = 12 · Category: bare_interface
| * capability) for VLM models, the metadata checks take precedence and this | ||
| * becomes redundant. Keep it narrow — it is NOT a model catalog, just a | ||
| * capability heuristic. Gemma 4 (26B-A4B) is image+audio+video. | ||
| */ |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Hardcoded regex pattern for vision model detection creates maintenance burden
💡 Suggestion: Consider making VISION_MODEL_PATTERN configurable or moving to a simple string array of known vision model IDs/families
📊 Score: 2×3 = 6 · Category: over-configuration
| } | ||
| }, | ||
| [enabled, images.length] |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Cap enforcement duplicated between addFiles validation and state updater
💡 Suggestion: Extract cap enforcement to a single helper function or rely only on the state updater slice() to avoid redundant checks
📊 Score: 3×4 = 12 · Category: duplicate logic
| // NOTE: m.images is undefined for turns restored from persistence (images | ||
| // are stripped from localStorage to protect the quota — see store.ts), | ||
| // so earlier-turn image context isn't re-sent after a page reload. | ||
| // Follow-up: durable image storage (IndexedDB) to close this gap. | ||
| const userMessages = [...priorMessages, userMsg].map((m) => ({ | ||
| role: m.role, | ||
| content: m.content, | ||
| content: buildApiContent(m.content, m.images), |
There was a problem hiding this comment.
🔵 [INFO] 🧩 buildApiContent mapping duplicated in handleSend and retry logic
💡 Suggestion: Extract message transformation to a shared helper function to avoid repeating the same mapping logic
📊 Score: 2×3 = 6 · Category: duplicate logic
| */ | ||
| export function modelSupportsImages( | ||
| model?: Partial< | ||
| Pick<Model, "input_modalities" | "capabilities" | "id" | "architecture" | "family"> | ||
| > | null | ||
| ): boolean { | ||
| if (!model) return false; | ||
| const modalities = model.input_modalities?.map((m) => m.toLowerCase()) ?? []; | ||
| if (modalities.includes("image")) return true; | ||
| const caps = model.capabilities?.map((c) => c.toLowerCase()) ?? []; | ||
| if (caps.some((c) => c === "vision" || c === "image" || c === "multimodal")) { | ||
| return true; | ||
| } | ||
| const hay = `${model.id ?? ""} ${model.architecture ?? ""} ${model.family ?? ""}`; | ||
| return VISION_MODEL_PATTERN.test(hay); |
There was a problem hiding this comment.
🔵 [INFO] 🧩 modelSupportsImages has complex fallback chain for simple boolean check
💡 Suggestion: Consider simplifying to just check input_modalities and a whitelist, removing the multi-field fallback complexity
📊 Score: 2×2 = 4 · Category: over-abstraction
|
This PR adds multimodal (image) input support; the changes are net-neutral or mildly positive on security posture, with one new attack surface item requiring attention. Trust boundaries touched
Threat analysisT-003 · Coordinator sees plaintext prompts when sender encryption is off (TB-001)ℹ️ Neutral
T-018 · Chat history persists in localStorage after logout (TB-004)✅ Partially strengthens the mitigation
T-001 · API key theft enables consumer impersonation (TB-001)ℹ️ Neutral
New attack surface not covered by an existing threatImage URL injection (no existing threat ID)
// | { type: "image_url"; image_url: { url: string } }
// The image `url` is a base64 `data:` URI — our provider is
// end-to-end-encrypted and rejects remote http(s)/file URLsHowever, this rejection is enforced on the provider side, not in the browser or the coordinator. The coordinator forwards the
Recommendation: Add a client-side (BFF or browser) validation that rejects any Open findings resolved by this PRNone. SEC-006, SEC-015, SEC-024 remain open and are touched-but-not-fixed. 🔐 Threat model: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dccce3b0c5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| parts.push({ type: "text", text }); | ||
| } | ||
| for (const url of images) { | ||
| parts.push({ type: "image_url", image_url: { url } }); |
There was a problem hiding this comment.
Account for base64 images before token-budget admission
When this helper embeds the full data: URI in messages, the coordinator still estimates prompt tokens from the raw JSON bytes (estimatePromptTokens marshals non-string messages and divides by 4) before routing, and Swift providers with active_token_budget_max reject when that estimate exceeds the slot budget. A single allowed 1 MB photo becomes roughly 1.3 MB of base64, i.e. ~350k estimated tokens, so normal image uploads can be 429'd by QuickCapacityCheck/freeMemoryAdmits before the VLM provider ever sees them. Please either teach the coordinator to ignore/account image payload bytes separately or keep the UI from sending sizes that will trip admission.
Useful? React with 👍 / 👎.
|
|
||
| /** Max size per image. base64 inflates ~33%, and the whole request is sealed | ||
| * and sent inside the encrypted prompt, so keep this conservative. */ | ||
| export const MAX_IMAGE_BYTES = 10 * 1024 * 1024; // 10 MB |
There was a problem hiding this comment.
Keep encrypted uploads below the sealed body limit
When the user has “Encrypt to coordinator” enabled, a max-size 10 MiB image is first turned into a ~13.3 MiB data URL and then sealRequest base64-encodes the whole ciphertext envelope; the coordinator's sealed middleware caps the envelope with http.MaxBytesReader(..., 16<<20) (checked coordinator/api/sender_encryption.go:132). That makes a single image allowed here exceed the 16 MiB sealed-body limit and fail before inference, so please lower the per-image/message cap for encrypted requests or raise the sealed-body limit consistently.
Useful? React with 👍 / 👎.
| // Cap inside the updater: two overlapping intakes (e.g. a paste landing | ||
| // while a prior file read is still awaiting) both read the same stale | ||
| // `images.length` above, so enforce the limit against the latest state. | ||
| setImages((prev) => [...prev, ...accepted].slice(0, MAX_IMAGES_PER_MESSAGE)); |
There was a problem hiding this comment.
Recheck image support before committing async uploads
If a user starts reading a file while a vision model is selected and then switches to a text-only model before fileToDataURL resolves, this stale addFiles call still commits the accepted images after the effect has cleared the old state. At that point the attach control is hidden but images.length enables Send, so the next request includes media for a model that no longer supports it and fails at the provider instead of being gated by the composer. Please guard the async completion with the latest enabled/generation before calling setImages.
Useful? React with 👍 / 👎.
DRY the store-Message -> API ChatMessage transformation that was duplicated between the send and retry paths in page.tsx into src/lib/chat-messages.ts (toApiMessages), with the reload-context note in one place. Adds a focused test. Addresses the modularity review feedback on #295.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — 1 finding(s)
- 🔵 [INFO]
console-ui/src/lib/image-upload.ts:44-59— FileReader.readAsDataURL processes untrusted file content without validation- Suggestion: Add file header validation before FileReader processing to prevent malicious file exploitation
Performance — 4 finding(s) (3 blocking)
- 🟡 [MEDIUM]
console-ui/src/hooks/useImageUpload.ts:44-76— Multiple file reads without concurrency control can cause memory spikes- Suggestion: Add concurrency limiting (e.g., process files in batches of 2-3) or use a semaphore to prevent simultaneous large file reads
- 🔵 [INFO]
console-ui/src/hooks/useImageUpload.ts:62-64— fileToDataURL called sequentially in loop instead of parallel- Suggestion: Use Promise.all() to read files in parallel: const results = await Promise.all(files.map(fileToDataURL)); then filter/validate results
- 🟡 [MEDIUM]
console-ui/src/lib/image-upload.ts:44-59— FileReader operations are synchronous blocking calls on main thread- Suggestion: Consider using Web Workers for large file processing or add progress indicators for files >1MB to prevent UI freezing
- 🟡 [MEDIUM]
console-ui/src/lib/store.ts:170-182— Deep copying entire chat state with nested message arrays on every persist- Suggestion: Use structural sharing or only persist changed chats instead of mapping over all chats and messages on every state change
Type_diligence — 2 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/lib/api.ts:97-101— ChatMessage.content uses bare union with any[] via ChatContentPart[]- Suggestion: The ChatContentPart[] array could contain mixed types. Consider using a discriminated union or more specific typing to prevent runtime type confusion when processing content parts.
- 🔵 [INFO]
console-ui/src/lib/chat-messages.ts:16-18— Function relies on undefined images property without explicit handling- Suggestion: The comment mentions m.images is undefined for restored messages, but the code doesn't explicitly handle this case. Consider: m.images ?? [] to make the fallback explicit rather than relying on buildApiContent's implicit handling.
Additive_complexity — 3 finding(s)
- 🔵 [INFO]
console-ui/src/lib/image-upload.ts:70— Hardcoded regex pattern for vision model detection creates maintenance burden- Suggestion: Consider making VISION_MODEL_PATTERN configurable or moving to a simple string array of known vision model IDs/families
- 🔵 [INFO]
console-ui/src/hooks/useImageUpload.ts:44-48— Duplicate cap checking logic in addFiles function- Suggestion: Extract the cap check and error message into a helper function to avoid duplication
- 🔵 [INFO]
console-ui/src/lib/chat-messages.ts:8-14— Long comment explaining persistence behavior in transformation utility- Suggestion: Move persistence-related comments to store.ts where the partialize logic lives, keep this function focused on transformation
10 finding(s) total, 4 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| /** Read a File into a base64 `data:` URI (e.g. `data:image/png;base64,...`). */ | ||
| export function fileToDataURL(file: File): Promise<string> { | ||
| return new Promise((resolve, reject) => { | ||
| const reader = new FileReader(); | ||
| reader.onerror = () => | ||
| reject(reader.error ?? new Error("Failed to read image file")); | ||
| reader.onload = () => { | ||
| const result = reader.result; | ||
| if (typeof result === "string") { | ||
| resolve(result); | ||
| } else { | ||
| reject(new Error("Unexpected file read result (not a data URL)")); | ||
| } | ||
| }; | ||
| reader.readAsDataURL(file); | ||
| }); |
There was a problem hiding this comment.
🔵 [INFO] 🔒 FileReader.readAsDataURL processes untrusted file content without validation
💡 Suggestion: Add file header validation before FileReader processing to prevent malicious file exploitation
📊 Score: 2×3 = 6 · Category: unsafe-deserialization
| setImgError(null); | ||
| let remaining = MAX_IMAGES_PER_MESSAGE - images.length; | ||
| if (remaining <= 0) { | ||
| setImgError(`You can attach up to ${MAX_IMAGES_PER_MESSAGE} images per message.`); | ||
| return; | ||
| } | ||
| const accepted: string[] = []; | ||
| for (const file of files) { | ||
| if (remaining <= 0) { | ||
| setImgError(`You can attach up to ${MAX_IMAGES_PER_MESSAGE} images per message.`); | ||
| break; | ||
| } | ||
| const err = validateImageFile(file); | ||
| if (err) { | ||
| setImgError(err); | ||
| continue; | ||
| } | ||
| try { | ||
| accepted.push(await fileToDataURL(file)); | ||
| remaining -= 1; | ||
| } catch { | ||
| setImgError("Failed to read one of the images. Try again."); | ||
| } | ||
| } | ||
| if (accepted.length > 0) { | ||
| // Cap inside the updater: two overlapping intakes (e.g. a paste landing | ||
| // while a prior file read is still awaiting) both read the same stale | ||
| // `images.length` above, so enforce the limit against the latest state. | ||
| setImages((prev) => [...prev, ...accepted].slice(0, MAX_IMAGES_PER_MESSAGE)); | ||
| trackEvent("chat_image_attached", { count: accepted.length }); | ||
| } | ||
| }, | ||
| [enabled, images.length] |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Multiple file reads without concurrency control can cause memory spikes
💡 Suggestion: Add concurrency limiting (e.g., process files in batches of 2-3) or use a semaphore to prevent simultaneous large file reads
📊 Score: 3×4 = 12 · Category: unbounded_allocations
| accepted.push(await fileToDataURL(file)); | ||
| remaining -= 1; | ||
| } catch { |
There was a problem hiding this comment.
🔵 [INFO] ⚡ fileToDataURL called sequentially in loop instead of parallel
💡 Suggestion: Use Promise.all() to read files in parallel: const results = await Promise.all(files.map(fileToDataURL)); then filter/validate results
📊 Score: 2×3 = 6 · Category: repeated_work
| /** Read a File into a base64 `data:` URI (e.g. `data:image/png;base64,...`). */ | ||
| export function fileToDataURL(file: File): Promise<string> { | ||
| return new Promise((resolve, reject) => { | ||
| const reader = new FileReader(); | ||
| reader.onerror = () => | ||
| reject(reader.error ?? new Error("Failed to read image file")); | ||
| reader.onload = () => { | ||
| const result = reader.result; | ||
| if (typeof result === "string") { | ||
| resolve(result); | ||
| } else { | ||
| reject(new Error("Unexpected file read result (not a data URL)")); | ||
| } | ||
| }; | ||
| reader.readAsDataURL(file); | ||
| }); |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ FileReader operations are synchronous blocking calls on main thread
💡 Suggestion: Consider using Web Workers for large file processing or add progress indicators for files >1MB to prevent UI freezing
📊 Score: 2×4 = 8 · Category: blocking_io
| partialize: (state) => ({ | ||
| chats: state.chats.map((c) => ({ | ||
| ...c, | ||
| // Clear streaming flag on any messages that were mid-stream when page closed | ||
| messages: c.messages.map((m) => ({ ...m, streaming: false })), | ||
| messages: c.messages.map((m) => ({ | ||
| ...m, | ||
| // Clear streaming flag on any messages mid-stream when page closed. | ||
| streaming: false, | ||
| // Drop base64 image data from persistence — a few attachments would | ||
| // exceed the ~5-10MB localStorage quota and silently break saving | ||
| // the whole chat history. Images stay visible for the live session; | ||
| // they vanish on reload (follow-up: IndexedDB for durable storage). | ||
| images: undefined, | ||
| })), |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Deep copying entire chat state with nested message arrays on every persist
💡 Suggestion: Use structural sharing or only persist changed chats instead of mapping over all chats and messages on every state change
📊 Score: 3×4 = 12 · Category: large_object_copies
| role: "user" | "assistant" | "system"; | ||
| content: string; | ||
| // `string` for text-only turns (unchanged wire shape); a parts array when | ||
| // the turn carries images, matching the standard OpenAI/OpenRouter | ||
| // `image_url` content-part format. | ||
| content: string | ChatContentPart[]; |
There was a problem hiding this comment.
🟡 [MEDIUM] 🏷️ ChatMessage.content uses bare union with any[] via ChatContentPart[]
💡 Suggestion: The ChatContentPart[] array could contain mixed types. Consider using a discriminated union or more specific typing to prevent runtime type confusion when processing content parts.
📊 Score: 3×3 = 9 · Category: bare_interface
| export function toApiMessages( | ||
| messages: Pick<Message, "role" | "content" | "images">[] | ||
| ): ChatMessage[] { |
There was a problem hiding this comment.
🔵 [INFO] 🏷️ Function relies on undefined images property without explicit handling
💡 Suggestion: The comment mentions m.images is undefined for restored messages, but the code doesn't explicitly handle this case. Consider: m.images ?? [] to make the fallback explicit rather than relying on buildApiContent's implicit handling.
📊 Score: 2×2 = 4 · Category: implicit_zero_value
| * capability) for VLM models, the metadata checks take precedence and this | ||
| * becomes redundant. Keep it narrow — it is NOT a model catalog, just a | ||
| * capability heuristic. Gemma 4 (26B-A4B) is image+audio+video. | ||
| */ |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Hardcoded regex pattern for vision model detection creates maintenance burden
💡 Suggestion: Consider making VISION_MODEL_PATTERN configurable or moving to a simple string array of known vision model IDs/families
📊 Score: 2×3 = 6 · Category: over-configuration
| setImgError(null); | ||
| let remaining = MAX_IMAGES_PER_MESSAGE - images.length; | ||
| if (remaining <= 0) { | ||
| setImgError(`You can attach up to ${MAX_IMAGES_PER_MESSAGE} images per message.`); | ||
| return; |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Duplicate cap checking logic in addFiles function
💡 Suggestion: Extract the cap check and error message into a helper function to avoid duplication
📊 Score: 2×2 = 4 · Category: duplicate logic
| * strings). Shared by the send and retry paths so the transformation lives in | ||
| * one place. | ||
| * | ||
| * NOTE: `m.images` is undefined for turns restored from persistence (images are | ||
| * stripped from localStorage to protect the quota — see store.ts `partialize`), | ||
| * so earlier-turn image context isn't re-sent after a page reload. Follow-up: | ||
| * durable image storage (IndexedDB). |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Long comment explaining persistence behavior in transformation utility
💡 Suggestion: Move persistence-related comments to store.ts where the partialize logic lives, keep this function focused on transformation
📊 Score: 1×2 = 2 · Category: over-abstraction
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4edbbe5110
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const allMessages = [ | ||
| { role: "system" as const, content: SYSTEM_PROMPT }, | ||
| ...userMessages, | ||
| ...toApiMessages([...priorMessages, userMsg]), |
There was a problem hiding this comment.
Avoid replaying images to text-only models
When a chat already contains an image turn, switching selectedModel to a text-only model and sending another message still rebuilds the full history through toApiMessages, which inlines the earlier image_url parts regardless of the current model. The composer only prevents new uploads, but the Swift provider fails closed when non-VLM models receive media (VLMRequestInference.hasMedia leads to mediaUnsupportedByModel), so otherwise valid follow-up text requests/regenerations in the same chat start failing. Please strip historical images for non-vision models or block sending/switching in that state.
Useful? React with 👍 / 👎.
What
Adds Gemma 4-style image upload to the chat composer. Users attach images (file picker + paste); they're base64-encoded client-side and sent as standard OpenAI/OpenRouter
image_urlcontent parts. The provider (E2E-encrypted) decodes thedata:URI and runs the VLM (already merged: #293 + Layr-Labs/mlx-swift-lm#34).How
src/lib/image-upload.ts—validateImageFile,fileToDataURL,modelSupportsImages,buildApiContent(text-firstimage_urlparts).src/hooks/useImageUpload.ts— staging / validation / base64 / per-message cap (keeps the composer thin).ChatInput— file-picker + paste intake, staged thumbnails with remove, cap; attach button shown only for vision models.ChatMessage— renders attached thumbnails on user turns.page.tsx— threads images through the send and retry paths viabuildApiContent.store.ts—Message.images[]in memory; stripped from localStorage to protect the quota.api.ts—ChatContentParttype;ChatMessage.contentwidened tostring | ChatContentPart[].Media transport / E2E
Images are base64
data:URIs only (no remote URLs) — they ride inside the X25519-sealed request; the coordinator never sees them. Matches the provider'sdata:-only decode (SSRF-safe).Vision gating
The attach button uses
modelSupportsImages(readsinput_modalities/capabilities) with a temporarygemma-4family bridge, because the coordinator catalog currently reportsinput_modalities: ["text"]for all models. The clean fix is a separate coordinator PR that adds thevisioncapability soderiveModalitiesreports image input — after which the bridge is redundant (the gate already prefers real metadata).Tests
image-upload.test.ts(19) +useImageUpload.test.ts(6, incl. a cap-race regression).npm run buildcompiles.Follow-ups
Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.