Skip to content

fix(matrix): a long reply with a code block arrives split into broken blocks - #196167

Merged
obviyus merged 3 commits into
openclaw:mainfrom
Chr0mium24:fix/matrix-long-code-reply-split
Nov 9, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
Chr0mium24:fix/matrix-long-code-reply-split

Conversation

@Chr0mium24

@Chr0mium24 Chr0mium24 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #196163
Related: #189312 (adjacent: separator handling in the shared chunker; no files in common)

What Problem This Solves

Fixes: a Matrix reply longer than 4000 characters that has a ``` code block crossing the split point arrives as broken messages: the first event ends inside an unclosed fence, the second renders the rest of the code as a paragraph (indentation lost), and the stray closing fence opens an empty code block around the trailing prose.

User Impact

User impact: long Matrix replies with code (agent final replies with streaming off, which is the default, and openclaw message send) now split into events that each render a complete, correctly highlighted code block, and each event stays within the 4000-character limit.

Why This Change Was Made

Durable finals are pre-chunked in core by the channel adapter's chunker before Matrix renders them. The Matrix adapters used chunkTextForOutbound, which breaks on newlines and spaces with no fence awareness (chunkerMode: "markdown" only selects how the optional newline-mode pre-split behaves). Matrix's own fence-aware chunkMatrixText never sees the oversize text on this path, because every pre-chunk already fits. Both Matrix outbound adapters (channel.ts, outbound.ts) now use the fence-aware chunkMarkdownTextWithMode(text, limit, "length"), imported from the light openclaw/plugin-sdk/reply-chunking subpath (the same owner chunkMarkdownText delegates to; Feishu uses the same call). That keeps reply dispatch out of the channel import path, so Matrix's deferred runtime loading is unchanged. It closes the fence at the end of a chunk and reopens it with the original info string in the next, inside the limit.

Scope is Matrix only. Mattermost, MS Teams and Signal use the same unaware chunker on this path but need separate checks (Signal renders through its own text-style pipeline and uses chunkerMode: "text"), so they are left as follow-ups.

Evidence

Live proof against a local Synapse (127.0.0.1, SQLite, two users) through the real openclaw message send --channel matrix with a 4532-character reply holding a Python block across the 4000 boundary, events read back as the second user (m.room.message):

main (4b077d31b): 2 events, as described above.

event 0: body len=3976  ends  "...result_68 = transform(items[68])  # indented step 68"   (no closing fence; formatted_body has <pre> only up to the cut)
event 1: body len=551   starts "result_69 = transform(items[69])  # indented step 69\n    result_70 = t..."
         formatted_body: "<p>result_69 = ...<br>\nresult_70 = ..." ... "</p>\n<pre><code>\nThat is all: the function above returns the first two results.</code></pre>"

this branch: 3 events, each one balanced and within 4000.

event 0: body len=38    "Here is the full script you asked for:"
event 1: body len=3997  starts "```python\ndef process_all(items):..." ends "...result_69 = transform(items[69])  # indented step 69\n```"
         formatted_body: <pre><code class="language-python">def process_all ... step 69\n</code></pre>
event 2: body len=508   starts "```python\n    result_70 = transform(items[70])  # indented step 70..." ends "```\n\nThat is all: the function above returns the first two results."
         formatted_body: <pre><code class="language-python">    result_70 ... </code></pre>\n<p>That is all: ...</p>

Tests: extensions/matrix/src/outbound.test.ts and channel.message-adapter.test.ts gain fence rows (they fail on main, pass here); test-line ratchet net -1.

Import boundary (follow-up commit 58ffe5f): lint:plugins:no-monolithic-plugin-sdk-entry-imports, lint:plugins:plugin-sdk-subpaths-exported and test:extensions:memory -- --extension matrix pass (matrix: ok). On the same 4532-character reply the new chunker output is byte-identical to the one used in the live proof above (chunks of 39, 3997 and 508 characters).

Not verified: an inbound model-driven reply (it reaches the same deliverOutboundPayloads pre-chunk path; I did not run a gateway with a fixture model), Mattermost, MS Teams, Signal, encrypted rooms.

Rebased onto 151db8d09; the Matrix tests above re-run there (20 passed). None of the files involved changed between the two bases.

… blocks

Durable final replies are pre-chunked in core by the channel adapter's
chunker before Matrix renders them. Matrix used chunkTextForOutbound, which
splits on newlines and spaces without knowing about fences, so a reply over
the 4000-character limit that had a code block across the boundary produced
one event ending inside an unclosed fence and a second event that lost the
code indentation and opened a stray block around the trailing prose.

Use the fence-aware chunkMarkdownText (as iMessage already does) for both
Matrix outbound adapters. It closes the fence at the end of a chunk and
reopens it with the original info string in the next, within the limit.
@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 9, 2026
@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Both Matrix outbound adapters use the existing fence-aware Markdown chunker to preserve code blocks across messages.

Example: Send a reply containing a 5.2k-character Python code block through Matrix.

  • Before: Two events contain broken fences, and 40 code lines render as prose.
  • After: Three events of 28, 3980, and 1231 characters close and reopen the Python fences, with no code lines rendered as prose.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused reuse of the existing owner, meaningful adapter regressions, and exact-head real transport proof support merging after required CI completes.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Exact head 2b4951e was exercised through openclaw message send, a running Gateway, and real Synapse, with second-user event readback showing balanced fences, preserved indentation, and bounded events; plain-text and Unicode controls remained unchanged.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Long Matrix replies split code blocks into unreadable prose and can render trailing prose as code.
Reason: A small adapter change restores intended Markdown rendering using an existing owner, without adding settings, state, or public APIs.

Merge readiness

✅ Ready for maintainer review

This PR fixes a verified Matrix formatting bug with a focused change and exact-head Synapse proof; no actionable defects remain, and required CI is still pending.

Priority: P2
Reviewed head: 2b4951ecebc58430f7198fef209bbd59ef287ee1

Before merge

None.

Findings

None.

Agent review details

How this fits together

Core outbound delivery splits reply text using the Matrix adapter before Matrix renders and sends each event to the homeserver.

flowchart LR
  A[CLI send or final reply] --> B[Core outbound planner]
  B --> C[Matrix adapter chunker]
  C --> D[Shared Markdown chunker]
  D --> E[Matrix event renderer]
  E --> F[Matrix homeserver]
Loading

Technical review

Best possible solution:

Land the existing narrow adapter repair once required exact-head CI passes.

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

Source confirms that fence-unaware pre-chunking bypasses Matrix's later repair opportunity, and supplied Synapse readbacks reproduce the failure against main; this review executed no target code.

Is this the best way to solve the issue?

This is the smallest complete fix: use the existing Markdown owner in both adapter registrations while retaining lazy loading, fractional-limit handling, and the separate public compatibility facade.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against e23c587c16f3.

Provenance checked

  • Matrix adapter chunking and cold-runtime operation changes intended behavior with a stated reason (23d5bad: Restore chunking before the Matrix runtime singleton is initialized.)
  • Deferred channel runtime loading keeps the original intent (a782358: Keep runtime-heavy Matrix operations off channel discovery imports.)
  • Fractional chunk limits and public Matrix compatibility behavior keeps the original intent (3f9b451: Ensure fractional limits make progress while preserving the public facade's distinct empty-text and whitespace behavior.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 05eda57 adds extensions/matrix/src/channel.ts:328 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 05eda57b3c72; files: extensions/matrix/src/channel.ts)
  • Vincent Koc: Raw commit a782358 adds extensions/matrix/src/channel.ts:44 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: a782358c9b64; files: extensions/matrix/src/channel.ts)

PR surface

Source -2, Tests -1. Total -3 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 5 7 -2
Tests 2 5 6 -1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 10 13 -3

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: Long Matrix replies containing code render incorrectly across message boundaries, with limited channel-specific impact.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-09T17:54:54.136Z sha 11c9602 :: needs changes before merge. :: [P2] Keep reply dispatch out of the Matrix channel import path
  • reviewed 2026-11-09T18:36:52.078Z sha 58ffe5f :: needs maintainer review before merge. :: none

Reviewed November 9, 2026, 2:22 PM ET / 19:22 UTC (Revision 3).

Use chunkMarkdownTextWithMode from reply-chunking instead of the reply-runtime barrel, which pulls reply orchestration into the hot channel.ts/outbound.ts imports.
@Chr0mium24

Copy link
Copy Markdown
Contributor Author

Addressed the P2 import-path finding in 58ffe5f: both Matrix adapters now take the chunker from openclaw/plugin-sdk/reply-chunking (chunkMarkdownTextWithMode(text, limit, "length")) instead of the reply-runtime barrel, so channel discovery no longer reaches reply dispatch. The extension memory check for matrix passes and the chunk output on the live-proof text is byte-identical; the PR body explains the deferred-loading point.

@clawsweeper re-review

🤖 Addressed by Claude Code

@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix size: XS labels Nov 9, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 9, 2026
@obviyus

obviyus commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

Real Synapse proof for 2b4951ecebc5 (this PR with current main merged) against main 56617cd00086.

Setup: Synapse 1.162.0 and both builds in Docker on Node 24.22.1. Each reply went through openclaw message send --channel matrix via a running Gateway. A second Matrix user then read the room events back through the client API. Two runs per build gave identical results.

scenario                                  main                                   this PR
4531-char reply, py block crosses 4000    2 events (3996/526)                    2 events (3687/842)
                                          event 1 ends in an open fence          prose, then the whole block in one fenced event
                                          16 code lines rendered as prose        0 code lines as prose
                                          1 line loses its indentation           indentation intact
                                          trailing note inside a stray <pre>     trailing note is plain text
5.2k code block (must split inside)       2 events, 1 fence each, 40 lines prose 3 events (28/3980/1231), fences closed/reopened as ```py, 0 lines prose
short reply with code (332)               1 event                                identical
9000 chars, no code                       3 events 3957/3957/1080                identical
code block ends before 4000               2 events 3820/2225                     identical
CJK/emoji/ZWJ text across split (5.2k)    2 events 3785/1413                     identical, no characters lost

Every PR event is at most 4000 chars and has an even number of fence lines. Focused tests on this head pass: outbound, channel message adapter, send and reply formatting (4 files, 74 tests).

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 9, 2026
@obviyus
obviyus merged commit e138bd4 into openclaw:main Nov 9, 2026
116 checks passed
@obviyus

obviyus commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

Landed in e138bd4. Thanks @Chr0mium24. Long Matrix replies now keep their code blocks intact.

obviyus added a commit that referenced this pull request Nov 10, 2026
fix(mattermost): use fence-aware chunker for outbound markdown

Mattermost split long replies with chunkTextForOutbound, which ignores code fences. A reply over 4000 characters whose code block crossed the split arrived with an open fence in the first post and a stray fence in the next, so code showed as plain text and lost indentation. Mattermost now uses the fence-aware splitter the plugin SDK already exports, the same change #196167 made for Matrix.

Evidence: a real Mattermost server and both builds in Docker on node:24.22.1, replies sent with openclaw message send --channel mattermost through a running Gateway and read back over the REST API. For a 4531-character reply, main posted 3996 and 526 characters with the first post ending inside an open fence and 16 code lines shown as plain text. With this change the prose and the whole Python block arrive in balanced, indented posts under 4000 characters. A short reply with code, 9000 characters without code, and Chinese text with emoji across the split are identical on both. Details: #196331 (comment).

Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
… blocks (openclaw#196167)

fix(matrix): a long reply with a code block arrives split into broken blocks

Matrix split long replies with chunkTextForOutbound, which ignores code fences. A reply over 4000 characters whose code block crossed the split arrived as an unclosed code block, then code shown as plain text, then the trailing text wrapped in a stray code block. Matrix now uses the fence-aware splitter the plugin SDK already exports and Feishu already uses.

Evidence: Synapse 1.162.0 and both builds in Docker on node:24.22.1, replies sent with openclaw message send through a running Gateway and read back by a second Matrix user, two runs per build. For a 4531-character reply with a Python block crossing 4000, main sent 2 events where the first ended in an open fence, 16 code lines showed as plain text and the trailing note landed in a stray code block. With this change the code block arrives whole and the note is plain text. For a 5.2k code block that has to split inside the fence, main left 40 code lines as plain text; this change closes the fence at the split and reopens it. A short reply, 9000 characters of plain text, a code block ending before the limit, and CJK/emoji/ZWJ text across the split are identical on both. Every event is at most 4000 characters. Details: openclaw#196167 (comment).

Thanks @Chr0mium24.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
…law#196331)

fix(mattermost): use fence-aware chunker for outbound markdown

Mattermost split long replies with chunkTextForOutbound, which ignores code fences. A reply over 4000 characters whose code block crossed the split arrived with an open fence in the first post and a stray fence in the next, so code showed as plain text and lost indentation. Mattermost now uses the fence-aware splitter the plugin SDK already exports, the same change openclaw#196167 made for Matrix.

Evidence: a real Mattermost server and both builds in Docker on node:24.22.1, replies sent with openclaw message send --channel mattermost through a running Gateway and read back over the REST API. For a 4531-character reply, main posted 3996 and 526 characters with the first post ending inside an open fence and 16 code lines shown as plain text. With this change the prose and the whole Python block arrive in balanced, indented posts under 4000 characters. A short reply with code, 9000 characters without code, and Chinese text with emoji across the split are identical on both. Details: openclaw#196331 (comment).

Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: matrix Channel integration: matrix P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Matrix: a reply over 4000 characters with a code block arrives split into broken blocks

2 participants