Skip to content

Fix large inbound PDF media handling - #90111

Closed
joeykrug wants to merge 4 commits into
openclaw:mainfrom
joeykrug:fix/90096-pdf-media-runtime
Closed

joeykrug wants to merge 4 commits into
openclaw:mainfrom
joeykrug:fix/90096-pdf-media-runtime

Conversation

@joeykrug

@joeykrug joeykrug commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add bounded, untrusted text extraction for managed inbound PDFs in auto-reply and embedded runner prompts
  • make gateway and Control UI attachment data URL/base64 handling stack-safe, and clean up stale stack-overflow queued sends
  • let oversized already-managed inbound PDFs pass through chat.send without sandbox staging-cap rejection while preserving non-PDF oversize rejection

Real behavior proof

  • Behavior or issue addressed: Large inbound PDFs from Signal/group-bot and Control UI/Emma were delivered to locked-down agents as attachment names or media://inbound/... markers only, and large Control UI PDF sends could fail with RangeError: Maximum call stack size exceeded before the agent saw the document.

  • Real environment tested: Local installed OpenClaw 2026.6.1 runtime on Joey's live workspace/gateway after applying source-equivalent runtime patches. group-bot and Emma remained locked down with no broad read or exec; PDF extraction only read managed inbound media paths.

  • Exact steps or command run after this patch: Ran a no-delivery smoke against the real FF-Hockey group-bot session with a managed inbound Semianalysis PDF present; ran a full gateway chat.send smoke with the 7.97 MB PDF and aborted after dispatch; Joey retried a real 15.6 MB / 58-page PDF upload through the live Control UI to Emma; ran the local post-update hook and runtime syntax/config validation.

  • Evidence after fix (screenshot, recording, terminal capture, console output, redacted runtime log, linked artifact, or copied live output): Redacted runtime log / console output from the live setup:

    Semianalysis PDF: media://inbound/...pdf, 7.97 MB / 102 pages
    direct extraction smoke: produced bounded text from managed media path
    group-bot no-delivery smoke: OK, agentHarnessId=openclaw
    
    gateway chat.send smoke with semianalysis-smoke.pdf:
    Offloaded attachment (application/pdf). Saved: media://inbound/semianalysis-smoke---...pdf
    chat.send status="started"
    no fresh RangeError or Maximum call stack entries after patch
    
    Control UI / Emma live retry:
    embedded inbound PDF context extracted ... chars=72791 bytes=15607476
    Emma returned a substantive summary of Introduction_to_Space_Datacenters_and_Orbital_Compute
    
  • Observed result after fix: The gateway accepted/staged large PDF attachments without the stack overflow, managed inbound PDFs reached agents through bounded media paths, and the embedded runner prompt included extracted untrusted PDF text so Emma summarized the actual document instead of only seeing the attachment name.

  • What was not tested: None.

  • Proof limitations or environment constraints: The proof uses redacted runtime logs/copy-pasted live output instead of screenshots because the relevant evidence is server-side gateway/agent logs. The local runtime patch was equivalent behavior applied to generated installed bundles before this source PR; this PR ports that behavior into source and adds regression tests.

  • Before evidence (optional but encouraged): Before the fix, Signal/group-bot prompts contained only [media attached: media://inbound/...pdf (application/pdf)] for PDFs, and Control UI/gateway logs showed chat.send attachment parse/stage failed: RangeError: Maximum call stack size exceeded.

Tests and validation

Which commands did you run?

  • node scripts/test-projects.mjs src/media/inbound-pdf-context.test.ts src/auto-reply/reply/prompt-prelude.test.ts src/gateway/chat-attachments.test.ts src/gateway/server-methods/chat.directive-tags.test.ts ui/src/ui/chat/composer-persistence.test.ts ui/src/ui/controllers/chat.test.ts
  • pnpm tsgo:core
  • pnpm tsgo:test:src && pnpm tsgo:test:ui
  • pnpm lint:core
  • pnpm exec oxfmt --check --threads=1 src/media/inbound-pdf-context.ts src/media/inbound-pdf-context.runtime.ts src/media/inbound-pdf-context.test.ts src/auto-reply/templating.ts src/auto-reply/reply/get-reply.ts src/auto-reply/reply/prompt-prelude.ts src/auto-reply/reply/prompt-prelude.test.ts src/agents/embedded-agent-runner/run/attempt.ts src/gateway/chat-attachments.ts src/gateway/chat-attachments.test.ts src/gateway/server-methods/chat.ts src/gateway/server-methods/chat.directive-tags.test.ts ui/src/ui/controllers/chat.ts ui/src/ui/controllers/chat.test.ts ui/src/ui/chat/composer-persistence.ts ui/src/ui/chat/composer-persistence.test.ts
  • pnpm build
  • git diff --check

What regression coverage was added or updated?

  • Added inbound PDF context extraction tests for managed media refs and extraction limits.
  • Added auto-reply prompt prelude tests for untrusted bounded PDF text context.
  • Added gateway/chat attachment tests for stack-safe data URL/base64 handling and managed inbound PDF pass-through.
  • Added Control UI tests for stack-safe data URL parsing and stale stack-overflow queue cleanup.

What failed before this fix, if known?

  • Locked-down text-only agents saw only PDF attachment markers or names.
  • Large PDF upload/normalization could raise RangeError: Maximum call stack size exceeded.
  • A stale failed Control UI queue entry could keep replaying the stack-overflow failure.

If no test was added, why not?

  • Not applicable; focused regression tests were added.

Closes #90096
Closes #90097
Closes #90098

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: L triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 4, 2026
@clawsweeper

clawsweeper Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 7, 2026, 11:07 PM ET / 03:07 UTC.

Summary
The branch adds bounded managed-inbound PDF text extraction, stack-safe large attachment parsing, managed PDF pass-through for chat.send, and stale stack-overflow queue cleanup with focused regression tests.

PR surface: Source +561, Tests +357. Total +918 across 16 files.

Reproducibility: yes. source inspection shows the current main path uses full-string regex parsing for large data URLs and rejects sandboxed non-image offloads above the 5 MB staging cap despite the 20 MB chat.send default. The PR body also includes live redacted logs for the before/after failure mode.

Review metrics: 2 noteworthy metrics.

  • Existing Default Semantics: 2 existing defaults reused, 0 new options. agents.defaults.mediaMaxMb and agents.defaults.pdfMaxBytesMb now affect automatic inbound PDF context extraction, so operators may see changed prompt content and extraction cost without a new config key.
  • Extraction Guardrails: 5 bounded limits enforced. The new PDF context path caps attachments, bytes, pages, chars, and timeout, which is the main safety argument for injecting untrusted document text automatically.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Maintainer should choose whether this broader PR is the canonical landing path over the narrower gateway-only PR.
  • [P2] Confirm required CI on the exact head before merge.

Risk before merge

  • [P1] This PR intentionally changes message-delivery behavior across gateway staging, auto-reply prompts, embedded-runner prompts, and Control UI queued sends; a regression can leave agents seeing only media markers or failed queued sends even when narrow unit tests pass.
  • [P1] Automatic PDF text extraction for locked-down agents reuses existing media/PDF defaults and managed-media trust checks, so maintainers should explicitly accept the prompt/security boundary before choosing this broad PR over the narrower gateway-only PR.

Maintainer options:

  1. Land After Maintainer Boundary Review (recommended)
    A maintainer can accept the broad fix if they are comfortable with automatic managed-PDF text injection for locked-down agents and the supplied live/log proof plus regression tests.
  2. Split To Gateway-Only Scope
    If maintainers want the lowest-risk landing path, keep this PR paused and use the narrower gateway-only work while a separate product/security decision covers automatic PDF prompt context.
  3. Request One More Live Gateway Proof
    Maintainers can ask for a fresh source-build live smoke that uploads a large PDF through Control UI and confirms the agent summary and gateway logs on the exact PR head.

Next step before merge

  • No automated repair is needed; the remaining action is maintainer review of the broad delivery/security boundary and overlap with the narrower gateway-only PR.

Security
Cleared: The diff is security-sensitive because it changes managed-media and sandbox-adjacent PDF handling, but the patch keeps extraction bounded to managed inbound refs, caps resource use, and marks document text as untrusted.

Review details

Best possible solution:

Land a single canonical fix that keeps extraction bounded to managed inbound PDFs, preserves non-PDF oversize rejection, and records maintainer acceptance of the broad delivery/security boundary before closing the linked issues.

Do we have a high-confidence way to reproduce the issue?

Yes, source inspection shows the current main path uses full-string regex parsing for large data URLs and rejects sandboxed non-image offloads above the 5 MB staging cap despite the 20 MB chat.send default. The PR body also includes live redacted logs for the before/after failure mode.

Is this the best way to solve the issue?

Yes, this is a coherent combined fix rather than a one-sided workaround: it updates the parser, gateway pass-through, auto-reply prompt, embedded-runner prompt, and stale UI queue paths together. The main alternative is the narrower gateway-only PR, but that would leave the Control UI stack-safe parsing and bounded PDF prompt-context gaps open.

AGENTS.md: found and applied where relevant.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 4780546c124d.

Label changes

Label changes:

  • add merge-risk: 🚨 security-boundary: The diff changes how locked-down agents receive text derived from managed inbound PDFs and when managed media paths bypass sandbox staging.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes redacted live runtime logs and copied output showing after-fix PDF extraction, chat.send acceptance, absence of fresh stack overflow, and a substantive agent summary; this is adequate server-side proof for the changed behavior.

Label justifications:

  • P1: The PR addresses a broken large-PDF agent/channel workflow that can prevent real Control UI or messaging-channel PDF sends from reaching the agent usefully.
  • merge-risk: 🚨 message-delivery: The diff changes chat.send media staging, auto-reply prompt construction, embedded-runner prompt construction, and Control UI queued-send persistence.
  • merge-risk: 🚨 security-boundary: The diff changes how locked-down agents receive text derived from managed inbound PDFs and when managed media paths bypass sandbox staging.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body includes redacted live runtime logs and copied output showing after-fix PDF extraction, chat.send acceptance, absence of fresh stack overflow, and a substantive agent summary; this is adequate server-side proof for the changed behavior.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes redacted live runtime logs and copied output showing after-fix PDF extraction, chat.send acceptance, absence of fresh stack overflow, and a substantive agent summary; this is adequate server-side proof for the changed behavior.
Evidence reviewed

PR surface:

Source +561, Tests +357. Total +918 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 10 590 29 +561
Tests 6 361 4 +357
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 951 33 +918

What I checked:

  • Repository policy read: Read the full root AGENTS.md plus scoped agents, embedded-runner, gateway, server-methods, and UI guides; the review applied the repo rules for whole-path review, real behavior proof, dependency-backed behavior, and merge-risk surfacing. (AGENTS.md:1, 4780546c124d)
  • Current main stack-prone gateway parser: Current main validates base64 and strips data URLs with full-string regexes, which matches the reported large-attachment stack-overflow surface. (src/gateway/chat-attachments.ts:149, 4780546c124d)
  • Current main sandbox staging cap mismatch: Current main rejects all sandboxed non-image offloads above the 5 MB staging cap even though chat.send accepts larger attachments by default, which explains the large managed-PDF failure path. (src/gateway/server-methods/chat.ts:1275, 4780546c124d)
  • PR stack-safe parser: The PR replaces gateway base64 validation and data URL prefix stripping with iterative/index-based logic instead of large regex captures. (src/gateway/chat-attachments.ts:149, 1cef7dc189d8)
  • PR managed PDF pass-through: The PR exempts oversized managed inbound PDFs from sandbox staging while preserving staging and oversize rejection for other non-image refs. (src/gateway/server-methods/chat.ts:1261, 1cef7dc189d8)
  • PR inbound PDF extraction guardrails: The new helper limits automatic extraction to managed inbound media refs, caps attachments, bytes, pages, chars, and timeout, and marks extracted text as untrusted document content. (src/media/inbound-pdf-context.ts:37, 1cef7dc189d8)

Likely related people:

  • vincentkoc: The available current-main blame for the gateway attachment parser, chat.send staging path, auto-reply staging hook, UI data URL parser, and PDF extraction callers attributes the checked-out snapshot to Vincent Koc; deeper provenance was not available through local git history, so this is a routing hint rather than blame. (role: recent area contributor; confidence: low; commits: 0f855ea71acc; files: src/gateway/chat-attachments.ts, src/gateway/server-methods/chat.ts, src/auto-reply/reply/get-reply.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jun 4, 2026
…imit

chat.send accepts and passes managed PDFs through up to the default 20 MB
(DEFAULT_CHAT_ATTACHMENT_MAX_MB / agents.defaults.mediaMaxMb), but inbound PDF
text extraction defaulted to 10 MB, so 10-20 MB managed PDFs reached locked-down
agents as the attachment marker only. Mirror the chat accept limit (mediaMaxMb
else 20 MB) for the extraction default; pdfMaxBytesMb still overrides and the
25 MB cap stays the safety ceiling. Adds regression coverage for a 15 MB PDF
(now extracted) and a 26 MB PDF (still skipped).

Addresses the ClawSweeper P1 review finding on PR openclaw#90111.
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 4, 2026
# Conflicts:
#	src/auto-reply/reply/prompt-prelude.ts
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 4, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 8, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jun 8, 2026
@amknight

Copy link
Copy Markdown
Member

Thanks for the thorough write-up and the real-behavior proof, Joey — the underlying problem is real and worth fixing. I'm closing this PR, though, because the approach reimplements a capability that already exists in the codebase, and that parallel path introduces correctness regressions. The linked issues (#90096–#90098) stay open; this is a "wrong mechanism," not "won't fix."

The capability already exists

Inbound document/PDF text extraction and untrusted-content injection is already implemented in the canonical media-understanding pipeline:

  • applyMediaUnderstanding runs extractFileBlocks unconditionally for every inbound media turn — src/media-understanding/apply.ts:682.
  • It extracts via the same clawpdf path this PR calls (extractFileContentFromSource → extractDocumentContent) — src/media-understanding/apply.ts:486.
  • It wraps the result as untrusted content (wrapUntrustedAttachmentContent, src/media-understanding/apply.ts:506,123) and even has the identical image-only PDF handling — src/media-understanding/apply.ts:509.
  • It appends the blocks into the prompt body — src/media-understanding/apply.ts:690.
  • application/pdf is in the default allow-list — src/media/input-files.ts:122.

And getReplyFromConfig already invokes it for all inbound media — src/auto-reply/reply/get-reply.ts:439-441 — the same function this PR adds its new call to at line 959.

Root cause is limit defaults, not a missing feature

The PDFs in the proof were 7.97 MB and 15.6 MB. The existing extraction path's defaults are:

  • DEFAULT_INPUT_FILE_MAX_BYTES = 5 MB — src/media/input-files.ts:127
  • DEFAULT_INPUT_PDF_MAX_PAGES = 4 — src/media/input-files.ts:135

Those PDFs hit the 5 MB cap in cache.getBuffer({ maxBytes }) (src/media-understanding/apply.ts:423), got skipped, and the agent saw only the marker. So the fix this issue actually needs is to raise/route the inbound file-extraction limits — ideally sourcing them from the very agents.defaults.pdfMaxBytesMb / pdfMaxPages / mediaMaxMb keys this PR already plumbs, but feeding resolveFileLimits / resolveInputFileLimits rather than a new module.

Consequence: double-injection

Because the new inbound-pdf-context.ts subsystem runs alongside the existing one, both fire for the same PDF on the auto-reply path:

  • src/auto-reply/reply/get-reply.ts:441 — applyMediaUnderstanding appends PDF text (≤5 MB / 4 pages) to ctx.Body, and
  • src/auto-reply/reply/get-reply.ts:959 — applyInboundPdfContextIfNeeded prepends PDF text (≤20 MB / 20 pages) as MediaExtractedContext.

The new INBOUND_PDF_CONTEXT_MARKER guard only dedupes the new path against itself; it doesn't know about the old wrapExternalContent blocks. So a ≤5 MB PDF gets its content injected twice across two subsystems with two different limit sets and two untrusted-wrapping formats.

Two confirmed correctness bugs (reproduced)

1. Duplicate extraction. collectContextPdfCandidates (src/media/inbound-pdf-context.ts:173) collects from MediaPaths/MediaPath and MediaUrls/MediaUrl with no dedup by source. Telegram/Signal mirror MediaUrl = MediaPath (extensions/telegram/src/bot-message-dispatch.media.ts:31), so one inbound PDF becomes two candidates → extractPdfContent runs twice and the document is embedded twice ([PDF attachment 1/2] + [2/2]). The sibling helpers both already dedupe (buildInboundMediaNote suppresses url === path; collectPromptPdfCandidates uses a seen set); this one doesn't.

2. Sandboxed small PDFs get noise instead of text. For chat.send to a sandboxed agent with a PDF ≤5 MB, prestaging rewrites ctx.MediaPaths to sandbox-relative media/inbound/<name> and sets MediaStaged=true. applyInboundPdfContextIfNeeded then calls resolveInboundMediaReference("media/inbound/<name>"), which returns null (not absolute, not media://), and emits [PDF attachment 1/1: extraction skipped: managed inbound media reference could not be resolved] (src/media/inbound-pdf-context.ts:243). So the feature's target case injects a confusing block instead of text; it only works for the oversized pass-through case (absolute path), which is exactly what the proof exercised, masking this.

Both are reachable in production and neither is covered by the added tests — inbound-pdf-context.test.ts mocks resolveInboundMediaReference to always resolve and only sets a single MediaPath (no MediaUrl, no sandbox-relative path).

On the embedded-runner premise

The PR notes "Control UI/Emma uses the embedded runner path, not the auto-reply path, so fixing only get-reply was insufficient." Tracing it: chat.send → dispatchInboundMessage → dispatchReplyFromConfig → getReplyFromConfig, which runs applyMediaUnderstanding for all inbound media (get-reply.ts:439), and runEmbeddedAttempt is just the builtin harness runAttempt downstream of that (src/agents/harness/builtin-openclaw.ts:18). So Control UI already flows through the canonical pipeline. If there is a genuinely separate embedded entry that bypasses media-understanding, the fix is to route that entry through applyMediaUnderstanding, not to add a second extraction system that scans the rendered prompt string for media://inbound/ refs.

Worth keeping

The gateway base64 / data-URL hardening (src/gateway/chat-attachments.ts:178, ui/src/ui/controllers/chat.ts:838) is orthogonal and reasonable — though the "recursive regex" framing isn't accurate (the replaced patterns are linear, not catastrophic), and the composer stale-overflow cleanup is fine.

Suggested path forward

A much smaller change that lands the same outcome:

  1. Raise/route the inbound file-extraction limits in resolveFileLimits / resolveInputFileLimits from agents.defaults.pdfMaxBytesMb / pdfMaxPages (and mediaMaxMb), so large PDFs are no longer skipped.
  2. If a real embedded-runner gap exists, route that entry through applyMediaUnderstanding rather than adding a parallel injector.
  3. Keep the base64/data-URL hardening as its own small PR.
  4. Re-justify the chat.send oversized pass-through on its own merits (it may help vision models that read PDFs natively); for text-only/locked-down agents it's largely moot once extraction limits are raised.

That deletes inbound-pdf-context.ts, both new injection sites, the MediaExtractedContext field, and both bugs above — for a fraction of the LOC, on one canonical path. Happy to help shape the follow-up. Thanks again for surfacing this.

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 gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants