Skip to content

feat(tui): inline image rendering via MEDIA: protocol - #36641

Closed
ademczuk wants to merge 5 commits into
openclaw:mainfrom
ademczuk:feat/tui-inline-image-rendering
Closed

ademczuk wants to merge 5 commits into
openclaw:mainfrom
ademczuk:feat/tui-inline-image-rendering

Conversation

@ademczuk

@ademczuk ademczuk commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Security & Safety Summary

All Greptile findings resolved. Score 2/5 was from pre-fix commit b5c806e — all 5 issues fixed in subsequent commits.

Finding Severity Status Commit
Path traversal check after normalize() High FIXED 75cf884 — check moved before normalize
statSync follows symlinks in TUI Medium FIXED 4ef5e14 — switched to lstatSync + symlink rejection
Exec heuristic too broad (spurious reloads) Low FIXED 4ef5e14 — mirrors server-side IMAGE_VIEWER_CMD_RE
Hardcoded MEDIA regex duplication Low FIXED 75cf884 — uses shared MEDIA_IMAGE_LINE_RE import
tool-events cap for all browsers Info By design — required for feature; server-side gating via toolEventRecipients per-run map

Defense-in-depth for image reads:

  • Pre-normalize .. traversal rejection (TUI + gateway)
  • lstatSync / lstat symlink detection (TUI + gateway)
  • Image extension whitelist (.png/.jpg/.gif/.webp only)
  • File size bounds (MAX_IMAGE_BYTES, reject empty)

No auth/security boundary changes. Rate limiters, token validation, device auth all untouched.


Summary

Adds inline image rendering to the TUI and WebUI when the agent generates or processes images via the image tool. Images flow through a new MEDIA: protocol that carries container-absolute paths from the image tool through the gateway to rendering surfaces.

Key changes:

  • image-tool.ts: Emits MEDIA:<container-path> text blocks alongside { type: "image", data: base64 } content blocks
  • tool-execution.ts: Renders images inline in TUI via file-based reading + base64 fallback with dedup
  • server-chat.ts: Gateway MEDIA bypass preserves tool results containing image data
  • chat.ts: Server-methods image injection for chat.history reload path (2 strategies: MEDIA token extraction + exec command path parsing)
  • pi-embedded-subscribe.tools.ts: Sanitizer bypass when MEDIA blocks present (prevents base64 stripping)
  • app-tool-stream.ts / chat-event-reload.ts / grouped-render.ts / tool-cards.ts: WebUI rendering pipeline
  • parse.ts: Shared MEDIA_IMAGE_LINE_RE regex for image-only MEDIA line matching
  • tui-formatters.ts / tui-event-handlers.ts / tui-session-actions.ts: TUI event plumbing

Not changed:

Previous PR

Replaces #23764 (closed per maintainer request to reduce bot comment noise — 100 accumulated comments across 34 review rounds). Same changes, clean review surface.

Test plan

  • pnpm vitest run src/agents/tools/image-tool.test.ts — 27 tests PASS
  • pnpm vitest run src/gateway/server-methods/chat.media-injection.test.ts — 26 tests PASS (NEW file)
  • pnpm vitest run src/tui/tui-event-handlers.test.ts — 15 tests PASS
  • pnpm vitest run src/tui/tui-formatters.test.ts — 35 tests PASS
  • pnpm vitest run ui/src/ui/app-tool-stream.node.test.ts — 4 tests PASS
  • pnpm vitest run ui/src/ui/chat-event-reload.test.ts — 7 tests PASS
  • pnpm tsgo — zero errors
  • pnpm check — zero lint errors on committed code
  • app-gateway.node.test.ts — pre-existing upstream localStorage failure, identical on main

114 tests passing across 6 test files. CI green (30/30 checks on prior push).

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: XL labels Mar 5, 2026
@greptile-apps

greptile-apps Bot commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds inline image rendering to both the TUI and WebUI via a new MEDIA: protocol. Images from the image tool flow as MEDIA:<path> text blocks through the gateway where the server reads and injects base64 data into chat history for the browser, while the TUI renders them directly from the filesystem.

Strengths:

  • Security posture is solid: readImageAsBase64 uses lstat (no symlink follow), validates .. traversal before normalization, enforces size limits, and mitigates TOCTOU by re-checking buffer size after readFile
  • The imagePreserveQuota logic in sanitizeToolResult correctly handles local, web, and mixed image scenarios
  • MEDIA_IMAGE_LINE_RE is now properly shared from parse.ts and imported by all consumers (no hardcoded duplication)
  • Test coverage is comprehensive across image tool emission, TUI formatters, and WebUI rendering pipelines

Critical issue:

  • Concurrency bug in collectImagePathsFromToolUse (lines 584–595): The module-level regex IMAGE_PATH_IN_COMMAND_RE with the /g flag maintains mutable lastIndex state. When await readImageAsBase64(p) suspends inside the while loop, a concurrent chat.history request can reset lastIndex and start its own traversal, causing the first call to miss image paths when it resumes. Under concurrent load, injected images can be silently skipped.

This concurrency bug must be fixed before merging, as it could cause data loss in production under load.

Confidence Score: 2/5

  • Not safe to merge due to a concurrency bug that can silently drop injected images under concurrent load.
  • The PR implements a thoughtful approach to inline image rendering with good security guards around symlink handling and path traversal. However, the collectImagePathsFromToolUse function contains a critical correctness bug: its use of a module-level regex with mutable lastIndex inside an async loop means concurrent chat.history requests will interfere with each other, causing image paths to be silently skipped. This is a data-loss bug in the image injection pipeline that must be fixed before shipping. All other aspects of the implementation are solid.
  • src/gateway/server-methods/chat.ts — the collectImagePathsFromToolUse function (lines 584–595) must move regex matching outside the async loop to avoid concurrent state corruption.

Last reviewed commit: 39539f8

Comment thread src/gateway/server-methods/chat.ts Resolved
Comment thread ui/src/ui/gateway.ts Resolved
Comment thread ui/src/ui/app-tool-stream.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: b5c806e336

ℹ️ 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 src/gateway/server-methods/chat.ts Resolved
ademczuk and others added 2 commits March 5, 2026 21:23
Render AI-generated images directly in the TUI terminal (iTerm2/Kitty)
and the web UI chat transcript. The full pipeline:

  image-tool.ts → MEDIA:<path> text + {type:"image"} base64 blocks
  → sanitizeToolResult bypass (preserves base64 when MEDIA present)
  → gateway MEDIA bypass (preserves data.result for image events)
  → tool-execution.ts renders inline (file-based + base64 fallback)
  → web UI injects base64 into chat history for transcript replay

Key changes by subsystem:

  TUI (src/tui/):
  - tool-execution.ts: two-stage render (readFileSync + base64 dedup)
  - tui-formatters.ts: resultHasMedia() detection for MEDIA + image blocks
  - tui-event-handlers.ts: preserve chatRunHasMedia across terminal events
  - tui-session-actions.ts: propagate media flag to session state
  - MEDIA_IMAGE_LINE_RE filter: only strip image MEDIA: lines, let
    TTS/audio pass through as text

  Gateway (src/gateway/):
  - server-chat.ts: MEDIA bypass in verbose filter preserves data.result
    when content has MEDIA: paths or {type:"image"} blocks
  - chat.ts: injectMediaImagesIntoHistory() for web UI transcript replay
    with 2MB byte budget, path dedup, and TOCTOU-safe file reads
  - chat.media-injection.test.ts: 17 tests covering injection, budget,
    dedup, symlink rejection, TOCTOU races

  Agents (src/agents/):
  - pi-embedded-subscribe.tools.ts: sanitizeToolResult bypass when MEDIA
    text blocks present (prevents base64 stripping)
  - image-tool.ts: emit both MEDIA:<path> text and base64 image blocks

  Web UI (ui/src/ui/):
  - app-tool-stream.ts: extract and forward image blocks from tool events
  - grouped-render.ts: render inline images in chat message groups
  - tool-cards.ts: image block rendering in tool result cards
  - chat-event-reload.ts: preserve images across event replay
  - gateway.ts: request tool-events capability

  Shared (src/media/):
  - parse.ts: MEDIA_IMAGE_LINE_RE regex for image-only matching

103 tests pass (image-tool, tui-formatters, tui-event-handlers,
chat.media-injection, app-tool-stream, app-gateway, chat-event-reload).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Screenshot shows inline image rendering working on openclaw v2026.3.3
after squash-rebase onto main:
- Left: Docker TUI terminal with iTerm2 graphics protocol rendering
- Right: WebUI Control UI showing same image in chat transcript
- Both rendering A1.jpg from the agent's workspace folder

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@ademczuk

ademczuk commented Mar 5, 2026

Copy link
Copy Markdown
Contributor Author

@Takhoffman — would you mind reviewing this? Fresh reopen of #23764 (closed per maintainer directive to clear bot comment noise). Same rebased commits, clean review surface.

This adds inline image rendering to the TUI and WebUI via a new MEDIA: protocol. 26 files, ~1700 insertions, includes 426-line media injection test suite. CI all green (30/30 checks pass).

Key areas for review:

  • src/gateway/server-methods/chat.ts — media injection on chat.history reload (largest change, 468 lines)
  • src/tui/components/tool-execution.ts — TUI image rendering with file + base64 fallback
  • src/agents/pi-embedded-subscribe.tools.ts — sanitizer bypass when MEDIA blocks present

…IA regex via shared constant

Address Greptile review feedback on PR openclaw#36641:
1. Move '..' traversal check before path.normalize() so /tmp/../etc/shadow.png
   is rejected pre-normalization (previously normalize resolved it to /etc/shadow.png
   which passed the check).
2. Replace hardcoded MEDIA image regex in app-tool-stream.ts with shared
   MEDIA_IMAGE_LINE_RE from src/media/parse.ts to prevent divergence.
3. Update test to verify the new pre-normalization rejection behavior.
@ademczuk
ademczuk force-pushed the feat/tui-inline-image-rendering branch from b5c806e to 75cf884 Compare March 5, 2026 20:34

@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: 75cf8847b9

ℹ️ 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 src/gateway/server-methods/chat.ts Resolved
@ademczuk

ademczuk commented Mar 5, 2026

Copy link
Copy Markdown
Contributor Author

Reviewer Summary — Security & Safety

Greptile flagged 3 issues (score 2/5) — all resolved

1. Path traversal in readImageAsBase64 — FIXED in 75cf884
The .. check was running after path.normalize(), which resolves traversal sequences in absolute paths (e.g. /workspace/../etc/shadow → /etc/shadow), making the check dead code. Fix: moved the check before normalization. Test added: verifies /tmp/../etc/image.png is now rejected.

Additional defense layers unchanged:

  • lstat() symlink rejection (prevents symlink-based traversal)
  • Image extension whitelist (only .png/.jpg/.gif/.webp proceed)
  • Paths originate from loadImageSource() which always produces absolute container paths

2. caps: ["tool-events"] enabled for all browser connections — intentional, server-gated
Required for the feature — without this cap, the gateway silently drops tool events and the browser can never render inline images. The server-side gating is strict:

  • toolEventRecipients map scopes events per-run — clients only receive events for runs they're subscribed to
  • broadcastToConnIds() sends only to declared recipients, not all connections
  • Bandwidth impact is minimal: tool events are small JSON payloads, images are only injected on chat.history reload (not streamed)

3. Hardcoded MEDIA regex — FIXED in 75cf884
Replaced inline regex with shared MEDIA_IMAGE_LINE_RE import from src/media/parse.ts. Single source of truth.

What's safe to merge

  • No auth/security boundary changes — rate limiters, token validation, device auth all untouched
  • No breaking API changes — tool-events is an opt-in capability; clients that don't declare it see zero behavioral change
  • 103 tests pass across 4 test files (26 new media injection tests, 77 existing)
  • Path traversal is now defense-in-depth — pre-normalize rejection + symlink guard + extension whitelist

@ademczuk

ademczuk commented Mar 5, 2026

Copy link
Copy Markdown
Contributor Author

Greptile Score Update (2/5 → should be re-evaluated)

The Greptile summary above was reviewed at commit b5c806e and gave 2/5 primarily due to:

  1. Path traversal guard broken — Fixed in 75cf884. Moved the .includes("..") check BEFORE path.normalize() so traversal paths are rejected on raw input. Test updated to verify rejection.

  2. Hardcoded MEDIA regex duplicates shared constant — Fixed in 75cf884. Replaced inline regex with import { MEDIA_IMAGE_LINE_RE } from "../../../src/media/parse.js".

  3. tool-events capability enabled for all browser connections — This is an intentional design decision for v1 (explained in inline reply). Without it, the browser cannot render inline images at all.

Both code fixes are in commit 75cf884 with corresponding test updates. The score reflects the pre-fix state and should be 3-5/5 post-fix (core feature logic is sound, security issue resolved, DRY violation resolved, remaining concern is an acknowledged design tradeoff).

@greptile-apps please re-review at HEAD (75cf884).

…gating

Addresses Greptile review concern about unscoped tool-events capability.
The cap is required for inline image rendering; server-side gating via
toolEventRecipients per-run map ensures clients only receive events for
runs they are subscribed to.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/tui/components/tool-execution.ts Outdated
Comment on lines +62 to +72
const stat = statSync(filePath);
if (!stat.isFile()) {
return false;
}
if (stat.size > MAX_IMAGE_BYTES || stat.size === 0) {
return false;
}
} catch {
return false;
}
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.

statSync follows symlinks; no path traversal guard

validateMediaPath uses statSync, which silently follows symlinks, and has no .. traversal check. The server-side equivalent readImageAsBase64 (in chat.ts) explicitly uses lstat and rejects both symlinks and .. components.

An agent could create a symlink from a valid image path (e.g. /workspace/result.png) to any file readable in the container, or emit a MEDIA path like MEDIA:/workspace/../etc/secret.png. validateMediaPath would pass, readFileSync would read the target, and the file's bytes would be base64-encoded and rendered.

This doesn't elevate the agent's permissions (it already has filesystem access), but it creates an inconsistency between the TUI and gateway code paths. Use lstatSync and add a .. check to match the server-side security posture:

// Reject traversal components before normalization.
if (filePath.includes("..")) {
  return false;
}
const ext = extname(filePath).toLowerCase();
if (!ALLOWED_IMAGE_EXTENSIONS.has(ext)) {
  return false;
}
try {
  const stat = lstatSync(filePath);
  if (stat.isSymbolicLink() || !stat.isFile()) {
    return false;
  }
  if (stat.size > MAX_IMAGE_BYTES || stat.size === 0) {
    return false;
  }
} catch {
  return false;
}

(lstatSync is also available from node:fs.)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/tui/components/tool-execution.ts
Line: 62-72

Comment:
**`statSync` follows symlinks; no path traversal guard**

`validateMediaPath` uses `statSync`, which silently follows symlinks, and has no `..` traversal check. The server-side equivalent `readImageAsBase64` (in `chat.ts`) explicitly uses `lstat` and rejects both symlinks and `..` components.

An agent could create a symlink from a valid image path (e.g. `/workspace/result.png`) to any file readable in the container, or emit a MEDIA path like `MEDIA:/workspace/../etc/secret.png`. `validateMediaPath` would pass, `readFileSync` would read the target, and the file's bytes would be base64-encoded and rendered.

This doesn't elevate the agent's permissions (it already has filesystem access), but it creates an inconsistency between the TUI and gateway code paths. Use `lstatSync` and add a `..` check to match the server-side security posture:

```ts
// Reject traversal components before normalization.
if (filePath.includes("..")) {
  return false;
}
const ext = extname(filePath).toLowerCase();
if (!ALLOWED_IMAGE_EXTENSIONS.has(ext)) {
  return false;
}
try {
  const stat = lstatSync(filePath);
  if (stat.isSymbolicLink() || !stat.isFile()) {
    return false;
  }
  if (stat.size > MAX_IMAGE_BYTES || stat.size === 0) {
    return false;
  }
} catch {
  return false;
}
```

(`lstatSync` is also available from `node:fs`.)

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4ef5e14. Switched statSync to lstatSync to detect symlinks without following them, and added filePath.includes("..") traversal check before normalization — now matches the server-side readImageAsBase64 guard exactly.

Comment on lines +493 to +506
if (phase === "start" && !host.chatRunHasMedia && name === "exec") {
const cmdStr = (() => {
if (typeof args === "string") {
return args;
}
if (args && typeof args === "object") {
const a = args as Record<string, unknown>;
return typeof a.command === "string" ? a.command : "";
}
return "";
})();
if (/\.(?:png|jpe?g|gif|webp)\b/i.test(cmdStr)) {
host.chatRunHasMedia = 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.

Overly broad exec heuristic triggers spurious history reloads

The client-side detection sets chatRunHasMedia = true for any exec command whose argument string contains an image file extension:

if (/\.(?:png|jpe?g|gif|webp)\b/i.test(cmdStr)) {
  host.chatRunHasMedia = true;
}

The server-side injection (Strategy 2 in collectImagePathsFromToolUse) only extracts images from commands that also match IMAGE_VIEWER_CMD_RE (view-image, imgcat, icat, viu, timg, catimg, chafa, kitty icat). Any agent command that merely references a file with an image extension — e.g. rm /workspace/photo.png, cp report.jpg /tmp/, ls /images/*.png, convert input.jpg output.gif — will set the flag here, triggering a full loadChatHistory round-trip, but the server will inject nothing, making the reload a no-op.

Consider mirroring the server-side IMAGE_VIEWER_CMD_RE gate, or at minimum combining both conditions:

const IMAGE_VIEWER_RE = /\b(?:view[-_]?image|imgcat|icat|viu|timg|catimg|chafa|kitty\s+icat)\b/i;
const IMAGE_EXT_RE = /\.(?:png|jpe?g|gif|webp)\b/i;
if (IMAGE_VIEWER_RE.test(cmdStr) && IMAGE_EXT_RE.test(cmdStr)) {
  host.chatRunHasMedia = true;
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: ui/src/ui/app-tool-stream.ts
Line: 493-506

Comment:
**Overly broad exec heuristic triggers spurious history reloads**

The client-side detection sets `chatRunHasMedia = true` for any exec command whose argument string contains an image file extension:

```ts
if (/\.(?:png|jpe?g|gif|webp)\b/i.test(cmdStr)) {
  host.chatRunHasMedia = true;
}
```

The server-side injection (`Strategy 2` in `collectImagePathsFromToolUse`) only extracts images from commands that also match `IMAGE_VIEWER_CMD_RE` (`view-image`, `imgcat`, `icat`, `viu`, `timg`, `catimg`, `chafa`, `kitty icat`). Any agent command that merely references a file with an image extension — e.g. `rm /workspace/photo.png`, `cp report.jpg /tmp/`, `ls /images/*.png`, `convert input.jpg output.gif` — will set the flag here, triggering a full `loadChatHistory` round-trip, but the server will inject nothing, making the reload a no-op.

Consider mirroring the server-side `IMAGE_VIEWER_CMD_RE` gate, or at minimum combining both conditions:

```ts
const IMAGE_VIEWER_RE = /\b(?:view[-_]?image|imgcat|icat|viu|timg|catimg|chafa|kitty\s+icat)\b/i;
const IMAGE_EXT_RE = /\.(?:png|jpe?g|gif|webp)\b/i;
if (IMAGE_VIEWER_RE.test(cmdStr) && IMAGE_EXT_RE.test(cmdStr)) {
  host.chatRunHasMedia = true;
}
```

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4ef5e14. Added IMAGE_VIEWER_RE gate mirroring the server-side IMAGE_VIEWER_CMD_RE — now both extension AND viewer command must match. Commands like rm photo.png or ls *.jpg no longer trigger spurious history reloads.

@ademczuk ademczuk closed this Mar 5, 2026
@ademczuk ademczuk reopened this Mar 5, 2026
Comment on lines +584 to +595
IMAGE_PATH_IN_COMMAND_RE.lastIndex = 0;
while ((match = IMAGE_PATH_IN_COMMAND_RE.exec(command)) !== null) {
const p = match[1];
if (!p || !path.isAbsolute(p) || p.includes("\0") || seen.has(p)) {
continue;
}
const img = await readImageAsBase64(p);
if (img) {
images.push({ type: "image", ...img });
seen.add(p);
}
}

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.

Module-level /g regex with await inside while-exec loop

IMAGE_PATH_IN_COMMAND_RE (line 530) is a module-level constant with the g flag, whose lastIndex is mutated by every exec() call. The await readImageAsBase64(p) at line 590 suspends the loop, giving a concurrent chat.history request a window to enter collectImagePathsFromToolUse, reset lastIndex = 0 at line 584, and start its own traversal. When the first call resumes and calls exec() again, it restarts from the concurrent call's position — causing each interleaved pair of requests to skip each other's matches.

Concrete failure mode: With two simultaneous chat.history requests (e.g. two browser tabs loading), Request A executes exec() advancing lastIndex to 15, suspends on await. Request B resets lastIndex = 0 and advances it to 20 before its own await. Request A resumes and calls exec() starting from lastIndex = 20, silently missing the path at position 5–15.

Fix: Collect all matches synchronously before any await:

const matchedPaths: string[] = [];
IMAGE_PATH_IN_COMMAND_RE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = IMAGE_PATH_IN_COMMAND_RE.exec(command)) !== null) {
  if (m[1]) matchedPaths.push(m[1]);
}
const images: Array<{ type: string; data: string; media_type: string }> = [];
for (const p of matchedPaths) {
  if (!p || !path.isAbsolute(p) || p.includes("\0") || seen.has(p)) {
    continue;
  }
  const img = await readImageAsBase64(p);
  if (img) {
    images.push({ type: "image", ...img });
    seen.add(p);
  }
}
return images;
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/server-methods/chat.ts
Line: 584-595

Comment:
**Module-level `/g` regex with `await` inside `while`-exec loop**

`IMAGE_PATH_IN_COMMAND_RE` (line 530) is a module-level constant with the `g` flag, whose `lastIndex` is mutated by every `exec()` call. The `await readImageAsBase64(p)` at line 590 suspends the loop, giving a concurrent `chat.history` request a window to enter `collectImagePathsFromToolUse`, reset `lastIndex = 0` at line 584, and start its own traversal. When the first call resumes and calls `exec()` again, it restarts from the concurrent call's position — causing each interleaved pair of requests to skip each other's matches.

**Concrete failure mode**: With two simultaneous `chat.history` requests (e.g. two browser tabs loading), Request A executes `exec()` advancing `lastIndex` to 15, suspends on `await`. Request B resets `lastIndex = 0` and advances it to 20 before its own `await`. Request A resumes and calls `exec()` starting from `lastIndex = 20`, silently missing the path at position 5–15.

**Fix**: Collect all matches synchronously before any `await`:

```ts
const matchedPaths: string[] = [];
IMAGE_PATH_IN_COMMAND_RE.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = IMAGE_PATH_IN_COMMAND_RE.exec(command)) !== null) {
  if (m[1]) matchedPaths.push(m[1]);
}
const images: Array<{ type: string; data: string; media_type: string }> = [];
for (const p of matchedPaths) {
  if (!p || !path.isAbsolute(p) || p.includes("\0") || seen.has(p)) {
    continue;
  }
  const img = await readImageAsBase64(p);
  if (img) {
    images.push({ type: "image", ...img });
    seen.add(p);
  }
}
return images;
```

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

…istic

- validateMediaPath: use lstatSync instead of statSync to detect symlinks,
  add ".." traversal check before normalization (matches server-side guard)
- app-tool-stream: mirror server-side IMAGE_VIEWER_CMD_RE gate so commands
  like "rm photo.png" don't trigger spurious history reloads

Both fixes address Greptile review findings on PR openclaw#36641.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@ademczuk

ademczuk commented Mar 5, 2026

Copy link
Copy Markdown
Contributor Author

Closing to reopen with a clean single commit and fresh bot review. Same changes, squashed.

@ademczuk ademczuk closed this Mar 5, 2026

@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: 4ef5e14eb7

ℹ️ 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 +655 to +657
// Strategy 1a: Collect images from MEDIA: lines in tool_result content blocks.
if (pendingImages.length < MAX_PENDING_IMAGES) {
const mediaImages = await collectMediaImagesFromBlock(b, seenPaths);

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 Restrict MEDIA file reads to trusted tool results

This path reads and inlines MEDIA: file references from any tool_result block without checking tool trust, but the existing policy explicitly excludes plugin/MCP tools from local MEDIA path reads to prevent untrusted file access (src/agents/pi-embedded-subscribe.tools.ts:160-209). As written, any tool result text that includes MEDIA:/...png can trigger a server-side file read and leak the file contents through chat.history, so the same trust gating needs to be applied before collectMediaImagesFromBlock is used.

Useful? React with 👍 / 👎.

Comment on lines +678 to +680
// Strategy 2: Collect images from exec commands with image-viewer patterns.
if (pendingImages.length < MAX_PENDING_IMAGES) {
const execImages = await collectImagePathsFromToolUse(b, seenPaths);

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 Gate exec image injection on execution success

The history injector reads image paths directly from exec tool_use command text, but this runs before/independent of whether the command actually succeeded or was approved; a denied/failed view-image /path.png still causes readImageAsBase64 to read and inject that file. That bypasses the expected semantics of exec approvals/failures and can expose local images even when the tool action did not complete successfully.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant