Skip to content

feat(console-ui): image upload in chat for vision models (Gemma 4) - #295

Merged
Gajesh2007 merged 3 commits into
masterfrom
feat/console-ui-image-upload
Jun 9, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
feat/console-ui-image-upload

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 9, 2026 •

Copy link
Copy Markdown
Member

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_url content parts. The provider (E2E-encrypted) decodes the data: 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-first image_url parts).
  • 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 via buildApiContent.
  • store.ts — Message.images[] in memory; stripped from localStorage to protect the quota.
  • api.ts — ChatContentPart type; ChatMessage.content widened to string | 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's data:-only decode (SSRF-safe).

Vision gating

The attach button uses modelSupportsImages (reads input_modalities / capabilities) with a temporary gemma-4 family bridge, because the coordinator catalog currently reports input_modalities: ["text"] for all models. The clean fix is a separate coordinator PR that adds the vision capability so deriveModalities reports 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).
  • 236 vitest tests pass; eslint 0 errors; npm run build compiles.
  • Reviewed by both quality-gate reviewers (codex + claude): substantive PASS; flagged items fixed.

Follow-ups

  • Images stripped from persistence → prior-turn image context isn't re-sent after a page reload (documented at both send sites; IndexedDB follow-up).
  • Not user-visible until a release ships + a provider serves Gemma 4 as VLM.

View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

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).
@vercel

vercel Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 9, 2026 7:14pm
d-inference-console-ui-dev Ready Ready Preview Jun 9, 2026 7:14pm
d-inference-landing Ready Ready Preview Jun 9, 2026 7:14pm

Request Review

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +44 to +59
/** 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);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +70 to +72
// 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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +44 to +59
/** 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);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment thread console-ui/src/app/page.tsx Outdated
Comment on lines +148 to +151
// 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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment thread console-ui/src/app/page.tsx Outdated
Comment on lines +279 to +281
// 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) })),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment thread console-ui/src/lib/api.ts
Comment on lines 97 to +101
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[];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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.
*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +74 to +76
}
},
[enabled, images.length]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment thread console-ui/src/app/page.tsx Outdated
Comment on lines +145 to +151
// 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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +77 to +91
*/
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

@github-actions

github-actions Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

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

  • TB-001 – consumer→coordinator API (api.ts content shape change)
  • TB-004 – browser/console-ui (page.tsx, store.ts)

Threat analysis

T-003 · Coordinator sees plaintext prompts when sender encryption is off (TB-001)

ℹ️ Neutral

api.ts widens ChatMessage.content from string to string | ChatContentPart[]. The encrypted transport path (sealedTransport / encryption.ts) is not modified here. Base64 image data rides inside the same request body as text, so the pre-existing plaintext exposure when sender encryption is off (SEC-015) applies equally to image bytes — no new gap, but the blast radius of SEC-015 is now larger (images can be far larger than text prompts).

⚠️ Worth flagging: The existing io.ReadAll body-size issue (T-002 / SEC-006) is compounded here. A base64-encoded image can easily be several MB, and the coordinator's inference endpoints still have no MaxBytesReader. This PR does not introduce that gap, but it makes exploiting it meaningfully cheaper — an authenticated consumer can now craft a legitimate-looking multimodal request with large image payloads to exhaust coordinator memory. Recommend noting this against SEC-006.

T-018 · Chat history persists in localStorage after logout (TB-004)

✅ Partially strengthens the mitigation

store.ts lines 177-182: partialize now explicitly sets images: undefined before persisting to localStorage. This prevents base64 image blobs (potentially MBs each) from being written to the persistent store. The core SEC-024 finding (chat text persisting after logout) is unchanged — content (the text) is still persisted — but at least image data won't accumulate in localStorage and the risk of a localStorage-quota crash silently nuking all chat history is mitigated.

T-001 · API key theft enables consumer impersonation (TB-001)

ℹ️ Neutral

api.ts type change only affects message shape; auth handling is untouched.


New attack surface not covered by an existing threat

Image URL injection (no existing threat ID)

ChatContentPart at api.ts:93-94 documents that only data: URIs should be used, and states the provider rejects remote URLs:

// | { 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 URLs

However, this rejection is enforced on the provider side, not in the browser or the coordinator. The coordinator forwards the image_url.url value verbatim to the provider inside the encrypted payload. A consumer (ADV-002) can trivially pass an http:// or file:// URI rather than a data: URI:

  1. If the provider-side check has any bypass (e.g. redirects, file:// local paths on the provider Mac), this could reach local files or internal services from the provider process — an SSRF/LFI primitive targeting ADV-001's machine from a consumer's request.
  2. Even without a bypass, the coordinator never validates the content type, so a consumer could send arbitrarily large non-base64 payloads through the multimodal path, compounding SEC-006.

Recommendation: Add a client-side (BFF or browser) validation that rejects any image_url.url value that does not start with data:image/ before it reaches the coordinator or the encrypted payload. The coordinator should additionally validate content-part types before forwarding to providers.


Open findings resolved by this PR

None. SEC-006, SEC-015, SEC-024 remain open and are touched-but-not-fixed.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 } });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +44 to +59
/** 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);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +44 to +76
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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +62 to +64
accepted.push(await fileToDataURL(file));
remaining -= 1;
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +44 to +59
/** 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);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines 170 to +182
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,
})),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment thread console-ui/src/lib/api.ts
Comment on lines 97 to +101
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[];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +16 to +18
export function toApiMessages(
messages: Pick<Message, "role" | "content" | "images">[]
): ChatMessage[] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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.
*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +44 to +48
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +8 to +14
* 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).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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]),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@Gajesh2007
Gajesh2007 merged commit 2d9bdb2 into master Jun 9, 2026
51 of 55 checks passed

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 4edbbe51 Deployed Jun 9, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 4edbbe51 Deployed Jun 9, 2026 by vercel[bot]
Preview – d-inference-landing — 4edbbe51 Deployed Jun 9, 2026 by vercel[bot]
benchmarks — 4edbbe51 Deployed Jun 9, 2026 by Gajesh2007 via E2E Benchmarks #661
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants