Skip to content

fix(gateway): prevent RangeError on large clipboard screenshot attachments (#99163) - #99173

Closed
jtcole wants to merge 1 commit into
openclaw:mainfrom
jtcole:fix/attachment-range-error-large-screenshots
Closed

jtcole wants to merge 1 commit into
openclaw:mainfrom
jtcole:fix/attachment-range-error-large-screenshots

Conversation

@jtcole

@jtcole jtcole commented Jul 2, 2026

Copy link
Copy Markdown

Summary

Pasting a ~2MB PNG screenshot into the Control UI webchat triggered RangeError: Maximum call stack size exceeded server-side in the chat.send attachment parse/stage pipeline. Smaller images (~200KB) worked fine.

Root Cause

canonicalizeBase64 in packages/media-core/src/base64.ts built its output string using character-by-character concatenation (cleaned += base64[i]) in a loop. For large base64 payloads (~2.7M chars from a ~2MB clipboard PNG), this created a deeply nested V8 cons-string tree. When any downstream operation triggered V8 string flattening — e.g. .slice() or Buffer.from(..., "base64") in sniffMimeFromBase64 — V8 recursed into the cons-string tree and overflowed the call stack.

The call chain is:

chat.send handler
  → parseMessageWithAttachments
    → sniffMimeFromBase64
      → canonicalizeBase64  ← creates deep cons-string tree
      → canonicalBase64.slice(0, sliceLen)  ← V8 flattens tree → RangeError

Fix

Replace character-by-character string concatenation with array accumulation + single join("") at the end. This produces a flat string in O(n) without deep V8 recursion.

Before:

let cleaned = "";
for (...) {
  cleaned += base64[i];  // creates deep cons-string tree
}

After:

const parts: string[] = [];
for (...) {
  parts.push(base64[i]);
}
let cleaned = parts.join("");  // flat string, no deep recursion

Tests

  • packages/media-core/src/base64.test.ts: Added regression test verifying canonicalizeBase64 handles ~2MB PNG payloads (~2.7M base64 chars) without RangeError on .slice() or Buffer.from(). Also tests large payloads with embedded whitespace.
  • src/gateway/chat-attachments.test.ts: Added end-to-end regression test verifying parseMessageWithAttachments processes a ~2MB PNG screenshot attachment without RangeError, confirming the full attachment pipeline (sniff → size check → offload) works.

Affected Paths

canonicalizeBase64 is also called from:

  • src/media/input-files.ts — inbound file attachment handling
  • src/infra/outbound/message-action-params.ts — outbound message params
  • src/image-generation/image-assets.ts — generated image assets
  • src/agents/tool-images.ts — agent tool image handling
  • packages/media-core/src/inline-image-data-url.ts — inline image data URL sanitization

All of these paths benefit from the fix.

Closes #99163

…ments (#99163)

canonicalizeBase64 in packages/media-core/src/base64.ts built its output
string using character-by-character concatenation ()
in a loop. For large base64 payloads (~2.7M chars from a ~2MB clipboard PNG
screenshot), this created a deeply nested V8 cons-string tree. When any
downstream operation triggered V8 string flattening — e.g.  or
 in sniffMimeFromBase64 — V8 recursed into the
cons-string tree and overflowed the call stack, producing:

  RangeError: Maximum call stack size exceeded

in the gateway's chat.send attachment parse/stage pipeline. Smaller images
(~200KB) worked fine because their cons-string trees were shallow enough to
flatten without stack overflow.

Fix: accumulate characters in an array and join once at the end, producing
a flat string in O(n) without deep V8 recursion.

The function is called from sniffMimeFromBase64 → parseMessageWithAttachments
→ chat.send handler, so this fix resolves the crash for all attachment types
that go through the base64 canonicalization path.

Tests:
- Added regression test in base64.test.ts verifying canonicalizeBase64
  handles ~2MB PNG payloads without RangeError on .slice() or Buffer.from()
- Added regression test in base64.test.ts for large payloads with whitespace
- Added end-to-end regression test in chat-attachments.test.ts verifying
  parseMessageWithAttachments processes ~2MB PNG without RangeError
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 2, 2026
@clawsweeper

clawsweeper Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 2, 2026, 1:08 PM ET / 17:08 UTC.

Summary
The PR changes canonicalizeBase64 to accumulate base64 characters in an array before joining and adds media-core plus gateway regression coverage for large PNG attachments.

PR surface: Source +9, Tests +68. Total +77 across 3 files.

Reproducibility: yes. at source/report level, but I did not run a live current-main reproduction in this read-only review. Current main builds canonical base64 with repeated concatenation and the linked issue supplies matching v2026.6.11 gateway RangeError logs.

Review metrics: none identified.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #99163
Summary: This PR is the candidate fix for the narrow linked canonicalizeBase64/gateway RangeError report, while the older broad large-attachment tracker overlaps but does not cover this media-core helper change.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦐 gold shrimp
Result: blocked until real behavior proof is added.

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

Rank-up moves:

  • Correct the added gateway regression test so its payload is greater than OFFLOAD_THRESHOLD_BYTES or assert the exact-threshold inline behavior.
  • [P1] Add redacted after-fix real behavior proof from Control UI/Gateway, such as terminal logs or a recording with diagnostics showing a large screenshot send succeeds.
  • Rerun the focused media-core and gateway attachment tests after the test correction.

Proof guidance:

  • [P1] Needs real behavior proof before merge: No after-fix real Control UI/Gateway proof is supplied; the contributor should add redacted terminal/log/recording proof to the PR body, which should trigger a fresh ClawSweeper review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Mantis proof suggestion
A real Control UI paste/send proof would materially show the gateway crash path is fixed. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis visual task: verify a ~2 MB screenshot pasted into Control UI webchat sends without gateway RangeError and reaches the chat.

Risk before merge

  • [P1] The PR currently lacks after-fix real Control UI/Gateway proof, so the external-PR proof gate is not satisfied even though the code path is plausible.
  • [P1] The new gateway regression test asserts offload at exactly the production threshold, so focused validation cannot pass until the payload size or expectation is corrected.

Maintainer options:

  1. Decide the mitigation before merge
    Keep the media-core fix shape, correct the gateway regression test to use a payload above the offload threshold or assert inline boundary behavior, and add redacted real Control UI/Gateway proof before merge.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Next step before merge

  • [P1] Needs contributor or human follow-up: fix the threshold-mismatch test and add redacted real behavior proof; ClawSweeper should not auto-repair because the required proof must come from a real setup.

Security
Cleared: No concrete security or supply-chain concern found; the diff changes TypeScript base64 handling and tests without new dependencies, workflows, scripts, permissions, or credential paths.

Review findings

  • [P2] Use a payload that actually crosses the offload threshold — src/gateway/chat-attachments.test.ts:547-550
Review details

Best possible solution:

Keep the media-core fix shape, correct the gateway regression test to use a payload above the offload threshold or assert inline boundary behavior, and add redacted real Control UI/Gateway proof before merge.

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

Yes at source/report level, but I did not run a live current-main reproduction in this read-only review. Current main builds canonical base64 with repeated concatenation and the linked issue supplies matching v2026.6.11 gateway RangeError logs.

Is this the best way to solve the issue?

No, not merge-ready as submitted. The runtime fix is the right narrow layer, but the gateway regression test must match the strict offload threshold and the external PR still needs real behavior proof.

Full review comments:

  • [P2] Use a payload that actually crosses the offload threshold — src/gateway/chat-attachments.test.ts:547-550
    The new test allocates exactly 2_000_000 decoded bytes, but production offloads only when sizeBytes > OFFLOAD_THRESHOLD_BYTES, and that threshold is also 2_000_000. This payload stays inline, so offloadedRefs is empty and these assertions fail; bump the payload above the threshold, or change the expectations if this is meant to pin the exact boundary.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 3f289fdb4042.

Label changes

Label justifications:

  • P1: The PR targets a production-reported chat.send attachment RangeError that blocks a real Control UI screenshot/file delivery workflow.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: No after-fix real Control UI/Gateway proof is supplied; the contributor should add redacted terminal/log/recording proof to the PR body, which should trigger a fresh ClawSweeper review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +9, Tests +68. Total +77 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 13 4 +9
Tests 2 68 0 +68
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 81 4 +77

What I checked:

  • Repository policy read: Root review policy requires full path review, source/tests/history evidence, scoped AGENTS checks, and real behavior proof handling for PRs. (AGENTS.md:1, 3f289fdb4042)
  • Scoped gateway policy read: Gateway scoped policy was read; it emphasizes hot-path care and benchmarking the affected Gateway test file when changing this area. (src/gateway/AGENTS.md:1, 3f289fdb4042)
  • Current main still has the stack-prone helper: Current canonicalizeBase64 appends one character at a time with cleaned +=, which is the path the PR replaces. (packages/media-core/src/base64.ts:54, 3f289fdb4042)
  • Gateway parse path reaches the helper: parseMessageWithAttachments estimates size, then calls sniffMimeFromBase64; the sniffer canonicalizes the full payload before slicing a prefix for MIME detection. (src/gateway/chat-attachments.ts:273, 3f289fdb4042)
  • Offload threshold is strict greater-than: Current gateway code offloads only when sizeBytes > OFFLOAD_THRESHOLD_BYTES; equality remains inline. (src/gateway/chat-attachments.ts:346, 3f289fdb4042)
  • PR test assertion conflicts with current threshold: PR head allocates exactly 2_000_000 bytes, then expects one offloaded ref even though the production threshold is also 2_000_000 and uses >. (src/gateway/chat-attachments.test.ts:546, 3e49e93a9ddf)

Likely related people:

  • NianJiuZst: PR metadata and blame tie the current media-core base64 helper plus gateway attachment parser files to [codex] Support Android selected photo access #98059, authored by this account. (role: introduced current helper surface; confidence: high; commits: 04e4c3719de3; files: packages/media-core/src/base64.ts, src/gateway/chat-attachments.ts, src/media/sniff-mime-from-base64.ts)
  • steipete: Live PR metadata shows steipete merged the PR that introduced the current helper files, and history shows prior media/gateway attachment work in the same path. (role: merger and adjacent area contributor; confidence: high; commits: 04e4c3719de3, 1dd5c97ae00c, 193ebba657f9; files: src/gateway/chat-attachments.ts, src/media/sniff-mime-from-base64.ts, packages/media-core/src/base64.ts)
  • Syysean: History credits this contributor on prior gateway attachment offload regression work that shaped the same parse/offload path. (role: gateway attachment offload contributor; confidence: medium; commits: c6f2db150687; files: src/gateway/chat-attachments.ts, src/gateway/server-methods/chat.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 rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. labels Jul 2, 2026
@steipete

steipete commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Thanks @jtcole. Closing this older candidate as superseded by the actively maintained canonical fix in #99213.

The current branch is far behind main, and its threshold regression does not exercise the claimed offload branch: it allocates exactly 2,000,000 bytes while the production condition is strictly greater than 2,000,000. Its one-string-per-character array also amplifies the same large-payload memory pressure under investigation.

#99213 owns the shared base64 canonicalizer and strict Gateway validation path, preserves malformed-tail rejection, and carries focused parser plus real Control UI browser proof. We will keep #99163 open until that canonical branch lands. Thank you for investigating the large-attachment failure.

@steipete steipete closed this Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RangeError: Maximum call stack size exceeded in chat.send attachment parse/stage for ~2MB clipboard screenshots

2 participants