Repository navigation
Conversation
Greptile SummaryThis PR adds inline image rendering to both the TUI and WebUI via a new Strengths:
Critical issue:
This concurrency bug must be fixed before merging, as it could cause data loss in production under load. Confidence Score: 2/5
Last reviewed commit: 39539f8 |
There was a problem hiding this comment.
💡 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".
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]>
|
@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:
|
…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.
b5c806e to
75cf884
Compare
There was a problem hiding this comment.
💡 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".
Reviewer Summary — Security & SafetyGreptile flagged 3 issues (score 2/5) — all resolved1. Path traversal in Additional defense layers unchanged:
2.
3. Hardcoded MEDIA regex — FIXED in What's safe to merge
|
Greptile Score Update (2/5 → should be re-evaluated)The Greptile summary above was reviewed at commit
Both code fixes are in commit @greptile-apps please re-review at HEAD ( |
…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]>
| 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; |
There was a problem hiding this 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:
// 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.There was a problem hiding this comment.
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.
| 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; | ||
| } |
There was a problem hiding this 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:
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.There was a problem hiding this comment.
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.
| 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); | ||
| } | ||
| } |
There was a problem hiding this 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:
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]>
|
Closing to reopen with a clean single commit and fresh bot review. Same changes, squashed. |
There was a problem hiding this comment.
💡 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".
| // Strategy 1a: Collect images from MEDIA: lines in tool_result content blocks. | ||
| if (pendingImages.length < MAX_PENDING_IMAGES) { | ||
| const mediaImages = await collectMediaImagesFromBlock(b, seenPaths); |
There was a problem hiding this comment.
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 👍 / 👎.
| // Strategy 2: Collect images from exec commands with image-viewer patterns. | ||
| if (pendingImages.length < MAX_PENDING_IMAGES) { | ||
| const execImages = await collectImagePathsFromToolUse(b, seenPaths); |
There was a problem hiding this comment.
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 👍 / 👎.
Security & Safety Summary
normalize()75cf884— check moved before normalizestatSyncfollows symlinks in TUI4ef5e14— switched tolstatSync+ symlink rejection4ef5e14— mirrors server-sideIMAGE_VIEWER_CMD_RE75cf884— uses sharedMEDIA_IMAGE_LINE_REimporttool-eventscap for all browserstoolEventRecipientsper-run mapDefense-in-depth for image reads:
..traversal rejection (TUI + gateway)lstatSync/lstatsymlink detection (TUI + gateway).png/.jpg/.gif/.webponly)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
imagetool. Images flow through a newMEDIA:protocol that carries container-absolute paths from the image tool through the gateway to rendering surfaces.Key changes:
image-tool.ts: EmitsMEDIA:<container-path>text blocks alongside{ type: "image", data: base64 }content blockstool-execution.ts: Renders images inline in TUI via file-based reading + base64 fallback with dedupserver-chat.ts: Gateway MEDIA bypass preserves tool results containing image datachat.ts: Server-methods image injection forchat.historyreload 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 pipelineparse.ts: SharedMEDIA_IMAGE_LINE_REregex for image-only MEDIA line matchingtui-formatters.ts/tui-event-handlers.ts/tui-session-actions.ts: TUI event plumbingNot changed:
dangerouslyDisableDeviceAuthis NOT touched (upstream code, separate concern — see fix(gateway): prevent browser rate-limit death spiral on missing credentials #36138)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 PASSpnpm 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 PASSpnpm vitest run src/tui/tui-formatters.test.ts— 35 tests PASSpnpm vitest run ui/src/ui/app-tool-stream.node.test.ts— 4 tests PASSpnpm vitest run ui/src/ui/chat-event-reload.test.ts— 7 tests PASSpnpm tsgo— zero errorspnpm check— zero lint errors on committed codeapp-gateway.node.test.ts— pre-existing upstreamlocalStoragefailure, identical onmain114 tests passing across 6 test files. CI green (30/30 checks on prior push).
🤖 Generated with Claude Code