Skip to content

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

Merged
obviyus merged 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/mattermost-fence-aware-chunking
Nov 10, 2026
Merged

obviyus merged 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/mattermost-fence-aware-chunking

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Mattermost's outbound adapter uses the fence-blind chunkTextForOutbound chunker. When a reply exceeds 4000 characters and contains fenced code blocks, the chunker splits mid-fence — the first chunk arrives with an unclosed code block and the second starts with a stray closing fence. The channel renders broken markdown.

Why This Change Was Made

The canonical fence-aware chunker chunkMarkdownTextWithMode(text, limit, "length") already exists in src/auto-reply/chunk.ts and is re-exported via openclaw/plugin-sdk/reply-chunking. Matrix adopted it in e138bd4 (#196167), which explicitly leaves Mattermost as a follow-up. This PR applies the same one-line adapter swap: close the fence at chunk end, reopen with the original info string at chunk start.

Production diff: +3/−5 (import swap + chunker lambda). Test: folded a fence row into the existing it.each in outbound-delivery.test.ts, net 0 lines, no allocation.

User Impact

Mattermost users receiving long replies with code blocks now see properly balanced fences in every chunk. No config change required; the existing textChunkLimit: 4000 and chunkerMode: "markdown" are unchanged.

Evidence

Real behavior proof — shipped CLI, main vs this head (2026-11-10). Built the worktree twice in isolation: once with extensions/mattermost/src/channel.ts swapped to origin/main (bd63497), once restored to this PR's head (3742be4). Sent the same 4,587-character reply through the shipped command node openclaw.mjs message send --channel mattermost --target channel:PROOFCHAN1 --message … --json against a local loopback Mattermost-API fixture (127.0.0.1) that records every POST /api/v4/posts; the config set dangerouslyAllowPrivateNetwork: true to allow the loopback transport, and a synthetic bearer token supplied the API auth the real client path requires.

origin/main build → 2 posts, fence cut mid-block, markdown broken in-channel:

post 0: id=proofpost001 len=3949 fences=1 BROKEN codeLines=68
  head: "Here is the full script you asked for:\n\n```python\ndef process_all(items)…"
  tail: "…indented step 66\n    result_67 = transform(items[67])  # indented step 67"
post 1: id=proofpost002 len=633 fences=1 BROKEN codeLines=9
  head: "result_68 = transform(items[68])  # indented step 68…"
summary: allFencesBalanced=false codeLinesTotal=77/78 allWithin4000=true

post 0 ends with an open block and post 1 begins mid-code with lost indentation, then closes a fence that post 1 never opened.

This PR's head → 3 posts, every post fence-balanced, all 78 indented code lines preserved:

post 0: id=proofpost001 len=38   fences=0 BALANCED codeLines=0
post 1: id=proofpost002 len=3970 fences=2 BALANCED codeLines=69
post 2: id=proofpost003 len=590  fences=2 BALANCED codeLines=9
summary: allFencesBalanced=true codeLinesTotal=78/78 allWithin4000=true

The block closes cleanly at post 1's end and reopens in post 2 with the original ```python info string, so each post renders as valid markdown. The request log from the same run shows the full shipped send path, not an injected sender: bearer-authenticated GET /api/v4/users/me → GET /api/v4/users/proofbot/teams → GET /api/v4/teams/…/channels/name/PROOFCHAN1 (the channel: name target resolved through the real HTTP channel-name lookup), then 2 POST /api/v4/posts for the baseline run and 3 for the fixed run.

Before / after at a glance:

Signal (same 4,587-char reply) origin/main (bd63497) this head (3742be4)
Posts delivered 2 3
Fence markers per post 1 / 1 — both BROKEN 0 / 2 / 2 — all BALANCED
Indented code lines preserved 77 / 78 (result_68 loses indentation at the cut) 78 / 78
Block continuation resumes mid-code, then a stray close fence reopens with the original python info string, closes cleanly
Largest post 3,949 chars 3,970 chars (≤ 4,000)
Mattermost render broken code block spanning two posts valid, balanced code block in every post

Regression test, RED on origin/main (bd63497) — fence row fails, base produces broken chunks:

- Expected  ["```py\n  a\n```", "```py\n  b\n```", "end"]
+ Received  ["```py\n  a\n  b", "```\n\nend"]

 ❯ extensions/mattermost/src/outbound-delivery.test.ts:69:71
 Test Files  1 failed (1)
      Tests  1 failed | 4 skipped (5)

GREEN on this head (3742be4) — all 5 tests pass, including "sends sanitized fence through the channel handler".

Sibling regression — full mattermost lane (51 files): 464/465 pass; 1 pre-existing locale failure in setup.test.ts (Chinese prompt strings vs English expectation, unrelated to chunking).

Lane: test/vitest/vitest.extension-database-workers.config.ts (outbound-delivery is routed there via vitest.extension-database-workers-paths.mjs). Typecheck not run locally (worktree symlink boundary); expression is byte-identical to matrix's merged channel.ts line.

Switch the outbound adapter from fence-blind chunkTextForOutbound to
chunkMarkdownTextWithMode("length"), matching the matrix precedent
(e138bd4). Fenced code blocks in replies >4000 chars now close and
reopen at chunk boundaries instead of arriving broken in the channel.
@clawsweeper

clawsweeper Bot commented Nov 10, 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.

@openclaw-barnacle openclaw-barnacle Bot added channel: mattermost Channel integration: mattermost size: XS labels Nov 10, 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. P2 Normal backlog priority with limited blast radius. 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. 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 10, 2026
@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR uses the existing fence-aware Markdown chunker for long outbound Mattermost messages.

Example: Send a 4,587-character reply containing a Python code block with 78 indented code lines.

  • Before: Two posts contain unbalanced fences, and one code line loses indentation.
  • After: Three posts preserve all 78 indented lines with balanced fences and remain within 4,000 characters.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused existing-owner repair with shipped-entry-point before/after evidence, a reported red/green delivery regression, passing exact-head gates, and no open findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): At reviewed head 3742be4, the supplied shipped-CLI output exercises the changed adapter and real HTTP client against a loopback Mattermost API fixture: a 4,587-character fenced reply changes from two broken posts to three balanced posts, preserves all 78 indented code lines, and stays within 4,000 characters per post; this resolves the previous same-head proof request.
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 Mattermost replies split fenced code across posts, breaking code formatting and indentation.
Reason: This restores valid Markdown through an existing supported chunker, preserves configuration and runtime independence, and follows the merged Matrix repair.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current Mattermost formatting bug with a focused adapter change; no actionable defects remain, and the updated CLI proof resolves the earlier proof blocker.

Priority: P2
Reviewed head: 3742be47f480708f18b13c58f0d4e7dbe8514def

Before merge

None.

Findings

None.

Agent review details

How this fits together

Core outbound delivery passes reply text through the Mattermost adapter's chunker before the plugin's HTTP client creates Mattermost posts.

flowchart LR
  A[CLI or agent reply] --> B[Core outbound delivery]
  B --> C[Mattermost adapter]
  C --> D[Shared Markdown chunker]
  D --> E[Mattermost HTTP client]
  E --> F[Mattermost posts]
Loading

Technical review

Best possible solution:

Use the existing shared Markdown chunker at Mattermost's pre-send boundary while preserving sanitization, configured limits, and cold-runtime operation.

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

Current-main source exposes the fence-blind pre-chunking path, and the contributor supplies a matching failing baseline CLI trace and regression-test result; no target code was executed during this review.

Is this the best way to solve the issue?

The patch is the smallest complete repair: replace the adapter's chunker with the existing SDK owner and extend the current delivery regression table without adding production machinery.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Mattermost outbound chunker changes intended behavior with a stated reason (196d347: Restore cold-runtime chunking by removing dependence on an initialized Mattermost runtime; later lifecycle refactoring carried that selection forward.)
  • Outbound sanitization and delivery tests keeps the original intent (1ef4544: Strip internal assistant tool-trace banners at the shared outbound sanitization boundary; later test consolidation retained those behavioral cases.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 05eda57 adds extensions/mattermost/src/channel.ts:268 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/mattermost/src/channel.ts)
  • Vincent Koc: Raw commit 4133e3b adds extensions/mattermost/src/channel.ts:19 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4133e3bb1dc9; files: extensions/mattermost/src/channel.ts)
  • Tak Hoffman: Raw commit 5b7b552 adds extensions/mattermost/src/channel.ts:15 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 5b7b5529f1db; files: extensions/mattermost/src/channel.ts)

PR surface

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

View PR surface stats
Area Files Added Removed Net
Source 1 3 5 -2
Tests 1 12 12 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 15 17 -2

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 proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Long Mattermost replies containing fenced code render incorrectly, with impact limited to message formatting.
  • 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 (1 earlier review cycle)
  • reviewed 2026-11-10T00:20:07.817Z sha 3742be4 :: needs real behavior proof before merge. :: none

Reviewed November 9, 2026, 9:10 PM ET / November 10, 2026, 02:10 UTC (Revision 2).

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review.

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 10, 2026
@obviyus

obviyus commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

Real Mattermost proof for 3742be47f480 against main 426543e904b1.

Setup: Mattermost server (mattermost-preview) and both builds in Docker on Node 24.22.1. Each reply went through openclaw message send --channel mattermost via a running Gateway. A second Mattermost user then read the channel posts back through the REST API.

scenario                                  main                                    this PR
4531-char reply, py block crosses 4000    2 posts (3996/526), fences 1/1          2 posts (3687/842), fences 0/2
                                          post 1 ends inside an open fence        prose, then the whole block in one fenced post
                                          16 code lines outside a fence in post 2 0 code lines outside a fence
                                          1 indented line loses its indentation   indentation intact
short reply with code (332)               1 post                                  identical
9000 chars, no code                       3 posts 3957/3957/1080                  identical
CJK/emoji/ZWJ text across split (5201)    2 posts 3785/1413                       identical, no characters lost

Every post on this PR is within 4000 chars and has balanced fences. Main is clean against this head (no merge needed).

@obviyus
obviyus merged commit 48beb40 into openclaw:main Nov 10, 2026
145 of 146 checks passed
@obviyus

obviyus commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator

Landed in 48beb40. Thanks @SunnyShu0925. Long Mattermost replies now keep their code blocks intact.

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]>
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@obviyus Thanks a lot !

moguangyu5-design added a commit to moguangyu5-design/openclaw that referenced this pull request Nov 16, 2026
ClawSweeper round 3 accepted the Tlon shipped-entry trace and raised no
code findings, but MS Teams and Zalouser cannot receive tenant-free
shipped-entry proof: the Bot Framework serviceUrl boundary only permits
Microsoft HTTPS hosts (bot-framework-service-url.ts), and Zalouser sends
through the Zalo user protocol with no configurable endpoint. Follow the
single-channel precedent of the merged Mattermost repair (openclaw#196331) and
keep this PR to the Tlon adapter, which has recorded CLI-plus-Gateway
delivery proof; Teams and Zalouser remain broken on main and are filed as
a follow-up. Allocation updated to the Tlon-only net test growth (+114).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: mattermost Channel integration: mattermost 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.

2 participants