Skip to content

fix(gateway): persist webchat images as managed media - #70719

Merged
steipete merged 3 commits into
mainfrom
fix/chat-history-managed-images
Apr 23, 2026
Merged

steipete merged 3 commits into
mainfrom
fix/chat-history-managed-images

Conversation

@steipete

@steipete steipete commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: Control UI chat history could lose generated/assistant images because history sanitization strips raw image bytes and the UI had no durable media reference to load after reload.
  • Why it matters: image-only replies and generated images appeared live, then disappeared from the web UI chat after history reload.
  • What changed: assistant image replies are copied into managed Gateway media storage, persisted in transcript content as authenticated media URLs, served through a scoped /api/chat/media/outgoing/.../full route, and rendered by the Control UI through authenticated blob fetches.
  • What did NOT change (scope boundary): provider/model input plumbing still uses existing image attachment paths; sensitive media is still not persisted into transcript content.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: image replies were stored/displayed as raw inline data or legacy media strings, while chat.history intentionally strips large inline image payloads for safety.
  • Missing detection / guardrail: no regression covered an assistant image reply across chat.send -> transcript persistence -> chat.history -> Control UI render.
  • Contributing context: the previous UI-side image history work handled existing renderable references, but did not create durable references for assistant/generated image payloads.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file:
    • src/gateway/server.chat.gateway-server-chat.test.ts
    • src/gateway/managed-image-attachments.test.ts
    • ui/src/ui/chat/grouped-render.test.ts
  • Scenario the test should lock in: assistant image data URL replies become managed media blocks in chat.history, raw base64 is absent from history payloads, and the UI fetches managed image URLs with auth/session headers before rendering.
  • Why this is the smallest reliable guardrail: it exercises the gateway persistence boundary, the authenticated media route, and the exact UI render path without requiring a live provider.
  • Existing test that already covers this (if any): none.
  • If no new test is added, why not: N/A.

User-visible / Behavior Changes

Control UI chat reloads can display assistant/generated images through durable managed media URLs instead of depending on inline base64 history payloads.

Diagram (if applicable)

Before:
assistant image reply -> inline data / MEDIA text -> chat.history strips bytes -> no image

After:
assistant image reply -> managed media record -> transcript URL -> authenticated UI fetch -> image renders

Security Impact (required)

  • New permissions/capabilities? Yes
  • Secrets/tokens handling changed? No
  • New/changed network calls? Yes
  • Command/tool execution surface changed? No
  • Data access scope changed? Yes
  • If any Yes, explain risk + mitigation: the new media route serves only managed image records. It requires gateway HTTP auth, chat.history scope, requester session ownership for non-privileged auth, UUID attachment ids, and verifies the attachment is still referenced by the transcript before serving bytes.

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: local Node/pnpm repo checkout
  • Model/provider: mocked gateway chat dispatcher
  • Integration/channel (if any): Control UI / webchat
  • Relevant config (redacted): default local test config; QA mock-openai lane

Steps

  1. Send a webchat assistant reply payload with mediaUrls: [data:image/png;base64,...].
  2. Wait for final chat event and reload chat.history.
  3. Verify the assistant message content contains /api/chat/media/outgoing/.../full image blocks and no raw base64.
  4. Render the history message in Control UI and verify the UI fetches the managed image with auth/session headers and renders a blob preview.

Expected

  • History contains a durable image URL and renders an image after reload.

Actual

  • Before this fix, history could omit the image bytes and render no image.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios:
    • pnpm test src/gateway/managed-image-attachments.test.ts src/gateway/server.chat.gateway-server-chat.test.ts ui/src/ui/chat/grouped-render.test.ts
    • pnpm test src/gateway/server-methods/chat.directive-tags.test.ts src/gateway/managed-image-attachments.test.ts src/gateway/server.chat.gateway-server-chat.test.ts ui/src/ui/chat/grouped-render.test.ts
    • pnpm check:changed
    • pnpm build
    • pnpm openclaw qa suite --provider-mode mock-openai --scenario control-ui-qa-channel-image-roundtrip --output-dir .artifacts/qa-e2e/managed-images-control-ui-pr70719 --concurrency 1
  • Edge cases checked:
    • auth/session gating for managed media route
    • invalid/non-image sources skipped without leaking local paths
    • sensitive image media is not persisted into transcript content
    • directive tags remain persisted where needed while broadcast text remains clean
  • What you did not verify:
    • live provider image generation against a paid provider; mock QA exercised a real Control UI browser session and qa-channel image history reload.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No
  • If yes, exact upgrade steps: N/A

Risks and Mitigations

  • Risk: managed media records could outlive transcript references.
    • Mitigation: cleanup runs from chat.history, transient records expire, and the media route refuses records no longer referenced by transcript history.
  • Risk: browsers cannot attach Authorization headers to raw <img> tags.
    • Mitigation: Control UI fetches managed images with auth/session headers and renders blob URLs.

@aisle-research-bot

aisle-research-bot Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 5 potential security issue(s) in this PR:

# Severity Title
1 🟠 High Unbounded disk consumption via persisted managed outgoing images (no quota / retention pruning)
2 🟠 High IDOR: Managed outgoing image media endpoint bypasses session ownership for non-shared-secret auth methods
3 🟡 Medium Long-lived client-side caching of authenticated managed images (Cache-Control: private, max-age=31536000, immutable)
4 🟡 Medium Managed outgoing image fetch ignores configured maxBytes and may download up to MEDIA_MAX_BYTES per URL (DoS risk)
5 🟡 Medium Arbitrary file read via unvalidated on-disk managed image record path
1. 🟠 Unbounded disk consumption via persisted managed outgoing images (no quota / retention pruning)
Property Value
Severity High
CWE CWE-400
Location src/gateway/managed-image-attachments.ts:925-942

Description

The gateway persists assistant image attachments to disk under stateDir/media/outgoing/originals and records under stateDir/media/outgoing/records/*.json without any cap on:

  • number of images per message / request (mediaUrls can be arbitrarily long)
  • total disk usage per session / per operator / per instance
  • total number of retained ("history") records

When a transcript message is committed, attachManagedOutgoingImagesToMessage promotes referenced images to retentionClass: "history", which are then retained as long as they are referenced by the transcript. Cleanup (cleanupManagedOutgoingImageRecords) deletes only:

  • transient records older than ~15 minutes, or
  • records that are no longer referenced by the transcript

So an authenticated attacker (or a compromised client/operator token) can repeatedly generate messages with many images (each up to ~12MiB by default) and quickly exhaust disk, causing denial of service and potential data loss.

Vulnerable code (persistence + history retention):

const record: ManagedImageRecord = {
  attachmentId: randomUUID(),
  sessionKey,
  messageId: params.messageId ?? null,
  createdAt: new Date().toISOString(),
  retentionClass: params.messageId ? "history" : "transient",
  ...
};
await writeManagedImageRecord(record, stateDir);
await writeManagedImageRecord({
  ...record,
  messageId,
  retentionClass: "history",
  updatedAt: new Date().toISOString(),
});

Cleanup does not enforce any storage budget:

} else if (record.messageId) {
  shouldDelete = !(await recordMatchesTranscriptMessage(record, ...));
}

Recommendation

Add storage quotas and enforce them at creation time.

Suggested mitigations (can be combined):

  1. Limit images per message/request (e.g. maxImagesPerMessage) and reject or truncate mediaUrls beyond the limit.
  2. Per-session / global disk budget for media/outgoing/**.
    • Track cumulative bytes (sum of record.original.sizeBytes) for a session.
    • Refuse new managed images when the budget is exceeded.
  3. Retention policy for history images:
    • Limit max history images per session.
    • Evict oldest images (or oldest transcript messages containing images) when exceeding the cap.
  4. Run cleanup on a schedule (not only on chat.history) and include enforcement of the above quotas.

Example (limit number of image URLs processed):

const MAX_IMAGES_PER_MESSAGE = 4;
const mediaUrls = asArray(params.mediaUrls).slice(0, MAX_IMAGES_PER_MESSAGE);

Example (refuse when session exceeds a byte budget):

const SESSION_IMAGE_BUDGET_BYTES = 200 * 1024 * 1024; // 200MiB
const usedBytes = await sumManagedOutgoingBytesForSession(sessionKey, stateDir);
if (usedBytes + savedOriginal.size > SESSION_IMAGE_BUDGET_BYTES) {
  throw createManagedImageAttachmentError("Managed image attachment budget exceeded");
}
2. 🟠 IDOR: Managed outgoing image media endpoint bypasses session ownership for non-shared-secret auth methods
Property Value
Severity High
CWE CWE-639
Location src/gateway/managed-image-attachments.ts:1010-1063

Description

The GET /api/chat/media/outgoing/:sessionKey/:attachmentId/full endpoint allows access to managed outgoing image files without verifying that the requester owns the target session whenever privilegedAccess is true.

privilegedAccess is set based on requestAuth.trustDeclaredOperatorScopes:

  • trustDeclaredOperatorScopes is true for any gateway auth method other than shared-secret bearer (token/password) (see checkGatewayHttpRequestAuth() in http-utils.ts). This includes auth.mode === "none" and auth.mode === "trusted-proxy" (and other non-shared-secret methods).
  • When privilegedAccess is true, the endpoint skips the x-openclaw-requester-session-key ownership verification entirely.
  • The only remaining check is that the caller has chat.history scope. For non-shared-secret methods, resolveOpenAiCompatibleHttpOperatorScopes() falls back to resolveTrustedHttpOperatorScopes(), which grants default scopes when no x-openclaw-scopes header is present; those defaults include chat.history.

Impact:

  • A caller who can authenticate via any non-shared-secret method (or no-auth mode) can fetch any managed outgoing image referenced in a transcript by guessing/obtaining a valid (sessionKey, attachmentId) pair, even when they do not own the session.

Vulnerable code:

const privilegedAccess =
  requestAuth.trustDeclaredOperatorScopes || requestAuth.authMethod === "device-token";

...
if (!privilegedAccess) {
  const requesterSessionKey = resolveRequesterSessionKey(req);
  ...
  const ownsSession = await requesterOwnsManagedImageSession({ ... });
  if (!ownsSession) { ... }
}

Recommendation

Do not equate trustDeclaredOperatorScopes with authorization to bypass ownership checks.

Safer options:

  1. Always enforce requester-session ownership for this endpoint, regardless of auth method, unless the caller is explicitly an admin/owner.
  2. If a privileged bypass is desired, gate it on an explicit high-privilege scope (e.g. admin) rather than on trustDeclaredOperatorScopes.

Example fix (require session ownership unless admin):

const requestedScopes = resolveOpenAiCompatibleHttpOperatorScopes(req, requestAuth);
const isAdmin = requestedScopes.includes(ADMIN_SCOPE);

if (!isAdmin) {
  const requesterSessionKey = resolveRequesterSessionKey(req);
  if (!requesterSessionKey) {
    sendJson(res, 403, { ok: false, error: { type: "forbidden", message: "requester session ownership required" } });
    return true;
  }
  const ownsSession = await requesterOwnsManagedImageSession({
    requesterSessionKey,
    targetSessionKey: record.sessionKey,
  });
  if (!ownsSession) {
    sendJson(res, 403, { ok: false, error: { type: "forbidden", message: "requester session does not own attachment session" } });
    return true;
  }
}

Additionally, consider requiring a dedicated media scope (separate from chat.history) if broader chat-history access should not automatically grant media access.

3. 🟡 Long-lived client-side caching of authenticated managed images (Cache-Control: private, max-age=31536000, immutable)
Property Value
Severity Medium
CWE CWE-525
Location src/gateway/managed-image-attachments.ts:1087-1091

Description

handleManagedOutgoingImageHttpRequest() serves authenticated chat history images with a 1-year immutable cache lifetime:

  • The endpoint is gated by authentication/authorization, but the response includes Cache-Control: private, max-age=31536000, immutable.
  • private prevents shared caches from storing the response, but it explicitly allows browser/private caches to store it.
  • With immutable and a long max-age, a browser (or other private cache) may keep sensitive images available for a long time even after:
    • user logout,
    • device-token rotation/revocation,
    • session ownership changes.

This can lead to information disclosure on shared machines/profiles (e.g., another OS user, someone with access to the browser profile/disk, or a kiosk scenario) and makes incident response harder because cached artifacts persist for up to a year.

Vulnerable code:

res.setHeader("cache-control", "private, max-age=31536000, immutable");

Recommendation

Treat authenticated/media responses as sensitive and avoid long-lived caching.

Safer default (recommended for authenticated resources):

res.setHeader("Cache-Control", "no-store");
​// (Optionally) res.setHeader("Pragma", "no-cache");

If you need conditional caching for performance, prefer short-lived private caching and revalidation, and ensure caches key on auth:

res.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
res.setHeader("Vary", "Authorization, X-Openclaw-Requester-Session-Key");
​// plus an ETag/Last-Modified implementation if you want 304 responses

Also consider making the cache behavior configurable (e.g., disable caching when device-token auth is used or when running in shared environments).

4. 🟡 Managed outgoing image fetch ignores configured maxBytes and may download up to MEDIA_MAX_BYTES per URL (DoS risk)
Property Value
Severity Medium
CWE CWE-400
Location src/gateway/managed-image-attachments.ts:839-848

Description

createManagedOutgoingImageBlocks() downloads remote/local media via saveMediaSource() using Math.max(limits.maxBytes, MEDIA_MAX_BYTES).

  • limits.maxBytes is the managed-image attachment limit (potentially configured lower than the global MEDIA_MAX_BYTES)
  • saveMediaSource() enforces the provided maxBytes while streaming the HTTP response (downloadToFile() destroys the request only after total > maxBytes)
  • Because Math.max(...) is used, an attacker-controlled mediaUrl can force downloads up to MEDIA_MAX_BYTES even when limits.maxBytes is smaller
  • The file is only rejected after download (if (savedOriginal.size > limits.maxBytes) throw ...), so the extra bytes still consume outbound bandwidth/CPU/disk I/O, enabling resource-exhaustion via repeated requests/URLs

Vulnerable code:

return await saveMediaSource(
  mediaUrl,
  undefined,
  "outgoing/originals",
  Math.max(limits.maxBytes, MEDIA_MAX_BYTES),
);

Recommendation

Enforce the managed-image limit at download time.

  • Pass limits.maxBytes directly to saveMediaSource() (or a small sniffing allowance, not a larger global default).
  • If you need a higher cap for MIME sniffing/validation, use a separate, explicit upper bound and add rate limiting / concurrency limits.

Example fix:

return await saveMediaSource(
  mediaUrl,
  undefined,
  "outgoing/originals",
  limits.maxBytes,
);
5. 🟡 Arbitrary file read via unvalidated on-disk managed image record path
Property Value
Severity Medium
CWE CWE-73
Location src/gateway/managed-image-attachments.ts:1079-1082

Description

The managed outgoing media handler reads a filesystem path directly from an on-disk JSON record and returns its bytes in an HTTP response.

  • record.original.path is loaded from ${stateDir}/media/outgoing/records/<attachmentId>.json without validation.
  • The handler then performs fs.readFile(record.original.path) and returns the content to the requester.
  • If an attacker can tamper with the record JSON (or replace the referenced original file with a symlink), they can cause the endpoint to return arbitrary local files (e.g., /etc/passwd, application secrets).

Vulnerable code:

body = await fs.readFile(record.original.path);

While record files are normally written by the server, this is a security boundary issue in deployments where the records directory is writable by another process/user/tenant, or if another bug allows record modification. The read path contains no defense-in-depth checks (e.g., ensuring the path is under the managed originals directory and not a symlink).

Recommendation

Add defense-in-depth validation before reading:

  • Do not persist absolute paths in records. Persist only an opaque media ID (or relative filename) and resolve it server-side.
  • When resolving the file to serve, ensure it stays within the expected directory and refuse symlinks (use lstat).

Example fix:

const originalsDir = resolveOutgoingOriginalsDir(opts.stateDir ?? resolveStateDir());
const candidate = path.resolve(originalsDir, record.original.filename ?? "");
if (!candidate.startsWith(originalsDir + path.sep)) {
  sendStatus(res, 404, "not found");
  return true;
}
const st = await fs.lstat(candidate);
if (!st.isFile() || st.isSymbolicLink()) {
  sendStatus(res, 404, "not found");
  return true;
}
const body = await fs.readFile(candidate);

(Alternatively reuse a helper like resolveMediaBufferPath-style checks for the outgoing/originals subdir.)


Analyzed PR: #70719 at commit b542446

Last updated on: 2026-04-23T19:13:51Z

@cursor

cursor Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

PR Summary

Medium Risk
Adds a new authenticated media-serving HTTP route and new on-disk record lifecycle for assistant images; bugs here could leak or orphan media, though access is gated by auth, scopes, session-ownership, and transcript-reference checks.

Overview
Control UI chat images now survive history reloads by persisting assistant/generated images as managed Gateway media and storing transcript image blocks that reference authenticated /api/chat/media/outgoing/<sessionKey>/<uuid>/full URLs (instead of inline base64).

Gateway adds managed-image-attachments to ingest data URLs/local paths/remote URLs into state-dir storage with size/dimension limits + optional resizing, track records as transient vs history, serve bytes via a new scoped HTTP handler (auth + chat.history scope + session-ownership checks, and only if still referenced by the transcript), and perform background cleanup during chat.history.

Control UI rendering detects these managed-image URLs and fetches them with auth + requester session headers to render blob previews (avoiding <img> header limitations) while refusing to send auth to cross-origin lookalikes; docs and tests are updated to lock in the new behavior and ensure sensitive media still isn’t persisted.

Reviewed by Cursor Bugbot for commit b542446. Bugbot is set up for automated code reviews on this repo. Configure here.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime size: XL maintainer Maintainer-authored PR labels Apr 23, 2026
@greptile-apps

greptile-apps Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a real regression where assistant/generated images disappeared from the Control UI chat history on reload. It introduces a managed media layer (managed-image-attachments.ts) that persists image payloads under stateDir/media/outgoing/, serves them via an authenticated /api/chat/media/outgoing/.../full route, and has the UI fetch them with auth headers before rendering blob previews. The commit ordering in chat.ts is correct — the transcript is written and records are upgraded to "history" before the message is broadcast to the UI, so there is no race window where the media route would 404 on a live response.

Confidence Score: 5/5

Safe to merge; the two remaining findings are both P2 style/hardening concerns that do not block correctness.

Auth, session ownership, scope, UUID validation, and transcript-reference checks are all in place. The commit ordering in chat.ts ensures records are committed before the UI receives managed image URLs. All remaining findings are P2 (blob URL cache memory pressure and a missing containment assertion on the served file path). No P0/P1 issues found.

ui/src/ui/chat/grouped-render.ts (blob URL cache cleanup) and src/gateway/managed-image-attachments.ts (path containment on serve)

Prompt To Fix All With AI
This is a comment left during a code review.
Path: ui/src/ui/chat/grouped-render.ts
Line: 80-83

Comment:
**Blob URL cache lacks production cleanup**

`managedImageBlobUrlResolvedCache` accumulates `URL.createObjectURL` blob URLs indefinitely — there is no revocation in production paths (only in `resetAssistantAttachmentAvailabilityCacheForTest`). In long-lived Control UI sessions with many assistant images, each unique image URL creates a new `Blob` reference that is never released, leaking memory proportional to the number of images rendered.

Consider adding a maximum cache size with LRU eviction, calling `URL.revokeObjectURL` on evicted entries, or revoking on session reset/navigation events.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/gateway/managed-image-attachments.ts
Line: 1079-1085

Comment:
**No path-containment assertion before serving record file**

`record.original.path` is read from a JSON file on disk and passed directly to `fs.readFile` without verifying it stays within `stateDir/media/outgoing/originals/`. In practice, all records are written by `writeManagedImageRecord` which always places files under that subdirectory, so this is low risk. However, adding a containment assertion (`path.startsWith(resolveOutgoingOriginalsDir(opts.stateDir))`) would provide defense-in-depth against corrupt or manually tampered record files that could cause the handler to serve arbitrary filesystem paths.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(gateway): persist webchat images as ..." | Re-trigger Greptile

Comment on lines +80 to +83
const managedImageBlobUrlCache = new Map<string, Promise<string | null>>();
const managedImageBlobUrlResolvedCache = new Map<string, string>();
const managedImageBlobUrlMissCache = new Map<string, number>();
const MANAGED_IMAGE_BLOB_URL_MISS_RETRY_MS = 5_000;

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.

P2 Blob URL cache lacks production cleanup

managedImageBlobUrlResolvedCache accumulates URL.createObjectURL blob URLs indefinitely — there is no revocation in production paths (only in resetAssistantAttachmentAvailabilityCacheForTest). In long-lived Control UI sessions with many assistant images, each unique image URL creates a new Blob reference that is never released, leaking memory proportional to the number of images rendered.

Consider adding a maximum cache size with LRU eviction, calling URL.revokeObjectURL on evicted entries, or revoking on session reset/navigation events.

Prompt To Fix With AI
This is a comment left during a code review.
Path: ui/src/ui/chat/grouped-render.ts
Line: 80-83

Comment:
**Blob URL cache lacks production cleanup**

`managedImageBlobUrlResolvedCache` accumulates `URL.createObjectURL` blob URLs indefinitely — there is no revocation in production paths (only in `resetAssistantAttachmentAvailabilityCacheForTest`). In long-lived Control UI sessions with many assistant images, each unique image URL creates a new `Blob` reference that is never released, leaking memory proportional to the number of images rendered.

Consider adding a maximum cache size with LRU eviction, calling `URL.revokeObjectURL` on evicted entries, or revoking on session reset/navigation events.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +1079 to +1085
let body: Buffer;
try {
body = await fs.readFile(record.original.path);
} catch {
sendStatus(res, 404, "not found");
return true;
}

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.

P2 No path-containment assertion before serving record file

record.original.path is read from a JSON file on disk and passed directly to fs.readFile without verifying it stays within stateDir/media/outgoing/originals/. In practice, all records are written by writeManagedImageRecord which always places files under that subdirectory, so this is low risk. However, adding a containment assertion (path.startsWith(resolveOutgoingOriginalsDir(opts.stateDir))) would provide defense-in-depth against corrupt or manually tampered record files that could cause the handler to serve arbitrary filesystem paths.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/managed-image-attachments.ts
Line: 1079-1085

Comment:
**No path-containment assertion before serving record file**

`record.original.path` is read from a JSON file on disk and passed directly to `fs.readFile` without verifying it stays within `stateDir/media/outgoing/originals/`. In practice, all records are written by `writeManagedImageRecord` which always places files under that subdirectory, so this is low risk. However, adding a containment assertion (`path.startsWith(resolveOutgoingOriginalsDir(opts.stateDir))`) would provide defense-in-depth against corrupt or manually tampered record files that could cause the handler to serve arbitrary filesystem paths.

How can I resolve this? If you propose a fix, please make it concise.

Comment thread src/gateway/server-methods/chat.ts Resolved
const managedImageBlobUrlCache = new Map<string, Promise<string | null>>();
const managedImageBlobUrlResolvedCache = new Map<string, string>();
const managedImageBlobUrlMissCache = new Map<string, number>();
const MANAGED_IMAGE_BLOB_URL_MISS_RETRY_MS = 5_000;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Managed image blob URLs never revoked causing memory leak

Low Severity

managedImageBlobUrlResolvedCache accumulates blob URLs created via URL.createObjectURL but never revokes them outside of the test-only reset function. Each blob URL holds a reference to the full image binary data in browser memory. In long-lived sessions with many generated images, this causes unbounded memory growth.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ef180f1c0773fb5d760c44fb287aacbe13ba064d. Configure here.

@steipete
steipete force-pushed the fix/chat-history-managed-images branch from ef180f1 to 55b3bb3 Compare April 23, 2026 18:18
Comment thread src/gateway/server-methods/chat.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ef180f1c07

ℹ️ 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".

Comment on lines +942 to +944
const normalizedBasePath =
basePath && basePath !== "/" ? (basePath.endsWith("/") ? basePath.slice(0, -1) : basePath) : "";
return `${normalizedBasePath}${source}`;

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.

P1 Badge Stop prefixing managed image API URLs with control-ui basePath

Managed image URLs are persisted as absolute /api/chat/media/outgoing/... paths, but this helper now prepends basePath to any leading-slash source. In deployments where Control UI is mounted under a subpath (for example /openclaw), the browser fetches /openclaw/api/chat/media/outgoing/..., while the new gateway handler only matches /api/chat/media/outgoing/...; the fetch then misses the media handler and image history previews fail after reload for those installs.

Useful? React with 👍 / 👎.

Comment on lines +987 to +988
const blobUrl = URL.createObjectURL(blob);
managedImageBlobUrlResolvedCache.set(cacheKey, blobUrl);

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.

P2 Badge Revoke managed image blob URLs to avoid unbounded UI memory growth

Each successful managed-image fetch creates an object URL and stores it in managedImageBlobUrlResolvedCache, but production code never revokes these URLs or evicts the cache; revocation currently only happens in a test-reset helper. In long-lived chats with many distinct generated images, this causes renderer memory to grow indefinitely until a full page reload.

Useful? React with 👍 / 👎.

@cursor cursor 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.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 8cf9640. Configure here.

return path.resolve(trimmed);
}
return undefined;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Duplicated resolveLocalMediaPath utility across two files

Low Severity

The resolveLocalMediaPath function in managed-image-attachments.ts is nearly identical to the private resolveLocalMediaPath in media/local-roots.ts. Both handle data: URLs, file://, ~, absolute paths, and Windows drive prefixes in the same way. Maintaining two copies risks them drifting apart over time and makes security-sensitive path resolution harder to audit.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8cf9640. Configure here.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8cf964058d

ℹ️ 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".

Comment thread ui/src/ui/chat/grouped-render.ts Outdated
function isManagedOutgoingImageSource(source: string): boolean {
try {
const parsed = new URL(source, window.location.origin);
return parsed.pathname.startsWith("/api/chat/media/outgoing/");

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.

P1 Badge Reject cross-origin managed-image URLs before auth fetch

isManagedOutgoingImageSource treats any URL whose pathname starts with /api/chat/media/outgoing/ as managed, even when the origin is different. That lets a crafted image block like https://attacker.example/api/chat/media/outgoing/... enter the managed fetch path, where resolveManagedOutgoingImageBlobUrl adds Authorization and requester-session headers, leaking credentials to the attacker origin. Restrict managed-image detection/fetching to same-origin (or relative) URLs before attaching auth headers.

Useful? React with 👍 / 👎.

Comment on lines +839 to +843
const localMediaPath = resolveLocalMediaPath(mediaUrl);
if (localMediaPath) {
await assertLocalMediaAllowed(localMediaPath, params.localRoots);
}
return await saveMediaSource(

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.

P1 Badge Enforce localRoots for relative managed image paths

The local-path allowlist check is conditional on resolveLocalMediaPath(mediaUrl) returning a path, but that helper returns undefined for relative filesystem paths. As a result, relative sources (for example ../secret.png) skip assertLocalMediaAllowed and are still handed to saveMediaSource, which can read host files outside configured localRoots if the path resolves on disk. Relative local paths should be resolved and validated against localRoots (or rejected) before ingestion.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d018fe770e

ℹ️ 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".

Comment on lines +313 to +314
if (normalized.length === 0) {
return rawTextPayloadCount > 0 ? [{ type: "text", text: "" }] : 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.

P1 Badge Avoid creating empty content for dropped silent replies

When normalizeReplyPayloadsForDelivery filters out a payload (for example a NO_REPLY-only final payload), this branch still manufactures an empty text block. Downstream, chat.send treats assistantContent?.length as truthy and attempts a transcript append even though transcriptReply is empty, which can produce phantom assistant entries (blank/"undefined") instead of suppressing the reply. This regresses silent-reply behavior and pollutes chat.history for runs that intentionally emit no visible assistant text.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the fix/chat-history-managed-images branch from 10373a1 to b542446 Compare April 23, 2026 19:05

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b54244688f

ℹ️ 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".

Comment on lines +2569 to +2573
hasSensitiveMedia
? await buildAssistantDisplayContentFromReplyPayloads({
sessionKey,
payloads: finalPayloads,
managedImageLocalRoots: mediaLocalRoots,

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.

P1 Badge Reuse prepared managed image blocks for mixed-sensitivity replies

When hasSensitiveMedia is true, this branch calls buildAssistantDisplayContentFromReplyPayloads a second time even though assistantContent was already prepared earlier in the same flow. That second call creates a new set of managed image attachment IDs, so the transcript is appended with one set of URLs while attachManagedOutgoingImagesToMessage later marks the first set as history-linked; in mixed payloads (at least one sensitive media payload plus at least one non-sensitive image payload), the persisted image URLs can point to records that remain transient and then 404 on fetch.

Useful? React with 👍 / 👎.

Comment on lines +839 to +843
const localMediaPath = resolveLocalMediaPath(mediaUrl);
if (localMediaPath) {
await assertLocalMediaAllowed(localMediaPath, params.localRoots);
}
return await saveMediaSource(

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.

P2 Badge Save resolved local image path instead of raw source string

This code resolves local paths (including file:// and ~) into localMediaPath for access checks, but still passes the original mediaUrl to saveMediaSource. For non-HTTP local formats, saveMediaSource treats that raw string as a filesystem path literal, so valid allowed images like file:///.../image.png or ~/image.png fail to ingest and are silently dropped when continueOnPrepareError is enabled.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit 5473149 into main Apr 23, 2026
70 checks passed
@steipete
steipete deleted the fix/chat-history-managed-images branch April 23, 2026 19:17
@steipete

Copy link
Copy Markdown
Contributor Author

Landed via squash merge onto main.\n\n- Gate: pnpm check:changed; PR CI/parity/install-smoke all green\n- PR head before merge: b542446\n- Merge commit: 5473149

ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
* fix(gateway): persist webchat images as managed media

* fix(ui): keep managed image auth same-origin

* docs: note managed webchat image fix
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
* fix(gateway): persist webchat images as managed media

* fix(ui): keep managed image auth same-origin

* docs: note managed webchat image fix
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
* fix(gateway): persist webchat images as managed media

* fix(ui): keep managed image auth same-origin

* docs: note managed webchat image fix
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
* fix(gateway): persist webchat images as managed media

* fix(ui): keep managed image auth same-origin

* docs: note managed webchat image fix
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
* fix(gateway): persist webchat images as managed media

* fix(ui): keep managed image auth same-origin

* docs: note managed webchat image fix
@bodikri bodikri mentioned this pull request Jul 1, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
* fix(gateway): persist webchat images as managed media

* fix(ui): keep managed image auth same-origin

* docs: note managed webchat image fix
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
* fix(gateway): persist webchat images as managed media

* fix(ui): keep managed image auth same-origin

* docs: note managed webchat image fix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: No images shown in the web ui chat

1 participant