Skip to content

feat(matrix): draft-based message streaming with edit-in-place - #32000

Closed
AOrobator wants to merge 9 commits into
openclaw:mainfrom
AOrobator:feat/matrix-streaming
Closed

AOrobator wants to merge 9 commits into
openclaw:mainfrom
AOrobator:feat/matrix-streaming

Conversation

@AOrobator

Copy link
Copy Markdown

Summary

Adds real-time streaming for Matrix channel responses using an edit-based "draft stream" pattern:

  • Draft message streaming: Creates a message on first partial update, then continuously edits it with throttled partial text + a cursor indicator (▌). Finalizes by editing the cursor away when the response completes.
  • editMessageMatrix() function: New export in send.ts for editing existing Matrix messages via m.relates_to / m.new_content (MSC2676 message replacement).
  • Multi-block bugfix: When a response contains multiple blocks (e.g., tool call + text), the handler now calls forceNewMessage() after finalizing each block, preventing all blocks from editing the same draft message.
  • Per-room send queue: send-queue.ts serializes sends per room to avoid race conditions with Matrix event ordering.

Configuration

{
  "channels": {
    "matrix": {
      "streaming": "partial",
      "streamThrottleMs": 800
    }
  }
}
  • streaming: "partial" — enables edit-based streaming (default: off)
  • streamThrottleMs — minimum ms between edits (default: 800)

New files

File Purpose
draft-stream.ts Core streaming engine (create → edit → finalize lifecycle)
draft-stream.test.ts 11 tests covering lifecycle, throttling, force-new-message
send-edit.test.ts 6 tests for editMessageMatrix() integration
handler.streaming.test.ts 7 tests for handler wiring, multi-block fix, config gating

Modified files

File Change
send.ts Added editMessageMatrix() export
send/types.ts Added MatrixEditOpts type
monitor/handler.ts Wired up draft stream creation, onPartialReply callback, finalization, and multi-block fix

Test plan

  • 29 new tests pass (pnpm vitest run --config vitest.extensions.config.ts extensions/matrix/)
  • Full matrix extension test suite passes (119 tests, 28 files)
  • Tested on live Synapse homeserver via Element Web:
    • Single-block streaming (simple question → text appears incrementally)
    • Multi-block streaming (tool call + text → separate messages, no duplicate edits)
    • Streaming disabled (config omitted → falls back to send-on-complete)

🤖 Generated with Claude Code

Add real-time streaming for Matrix channel responses. Instead of waiting
for the agent to finish thinking before showing the full reply, messages
now appear incrementally — a draft message is created and continuously
edited with partial text plus a cursor indicator (▌), then finalized
when the response completes.

Key changes:
- draft-stream.ts: Core streaming engine that creates a message, edits
  it with throttled partial updates, and finalizes on completion
- editMessageMatrix(): New function in send.ts for editing existing
  Matrix messages via m.relates_to / m.new_content
- handler.ts: Wire up draft stream creation, onPartialReply callback,
  and finalization. Includes bugfix for multi-block responses (tool call
  + text) where all blocks edited the same message instead of sending
  new ones — now calls forceNewMessage() after finalizing each block.
- MatrixEditOpts type in send/types.ts

Config:
  channels.matrix.streaming: "partial" (enables streaming)
  channels.matrix.streamThrottleMs: 800 (default throttle interval)

Tests: 29 new tests covering draft stream lifecycle, send-edit
integration, send-queue serialization, and handler streaming wiring.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix size: XL labels Mar 2, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2b70c94db7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@greptile-apps

greptile-apps Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR successfully implements real-time streaming for Matrix channel responses using an edit-based "draft stream" pattern. The implementation creates an initial message, continuously edits it with throttled partial text updates and a cursor indicator, then finalizes by removing the cursor when complete.

Key changes:

  • New draft-stream.ts module provides the core streaming engine with proper throttling, deduplication, and race condition handling through inFlight promise tracking
  • New editMessageMatrix() function implements Matrix MSC2676 message replacement with proper m.replace relations and backward-compatible fallback body
  • Handler integration wires up streaming lifecycle: creates draft stream, connects onPartialReply callback, handles in-place finalization, and calls forceNewMessage() after each block to prevent multiple blocks from editing the same message
  • Per-room send queue serializes initial message sends to preserve Matrix delivery order (edits intentionally bypass queue since they target specific events by ID)

Test coverage: 29 new tests covering lifecycle, throttling, multi-block handling, error fallbacks, and configuration gating. All tests follow proper patterns with mocked dependencies.

Notable design decisions:

  • Initial throttle prevents sending single-character drafts by coalescing early updates
  • stop() drains in-flight edits before returning to prevent race with final edit
  • Error fallback may result in duplicate messages (draft + new send) but ensures message delivery
  • Streaming only applies to text-only responses (skips media, errors)

Confidence Score: 5/5

  • This PR is safe to merge with high confidence
  • The implementation is well-architected with comprehensive test coverage (29 new tests), proper race condition handling, good error fallbacks, and clear separation of concerns. Code follows Matrix protocol correctly and handles edge cases like multi-block responses, concurrent edits, and throttling appropriately.
  • No files require special attention

Last reviewed commit: 2b70c94

…streaming

Address two review comments:

1. Gate outer finalize() on draftStream.getEventId() being non-null.
   When a short reply finishes before the first throttled draft send
   (< 800ms), deliver() already falls through to deliverMatrixReplies().
   Calling finalize() unconditionally would flush pending text as a
   duplicate second message. Now finalize() is skipped when no draft
   event was created.

2. Move lastSentText assignment after the successful network call in
   sendOrEdit(). Previously, a transient send/edit failure still marked
   the text as "sent", causing the dedup check to skip retries with
   the same text. Now lastSentText is only committed on success and
   reset to the previous value on failure.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5344b078fe

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +734 to +735
if (draftStream && !draftFinalized && draftStream.getEventId()) {
await draftStream.finalize();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Skip draft finalize after fallback media/error delivery

If a draft event already exists and deliver() falls back to deliverMatrixReplies (for example when hasMedia is true or payload.isError), draftFinalized stays false and this outer finalize() still runs. That sends an additional text edit for the old draft after the fallback reply, so streamed media/error responses can produce an extra stray text message. The draft should be marked handled/cleared on fallback paths so outer finalization does not emit another message.

Useful? React with 👍 / 👎.

Comment on lines +644 to +648
? createMatrixDraftStream({
roomId,
accountId: route.accountId ?? undefined,
threadId: threadTarget ?? null,
throttleMs: streamThrottleMs,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve reply relation when creating draft stream

The draft stream is initialized without any replyToId, so its first streamed send cannot include m.in_reply_to. In non-thread conversations where reply mode is enabled, this changes behavior from the normal deliverMatrixReplies path and streamed replies stop appearing as replies to the triggering message. Because edits only replace an existing event, the missing reply relation cannot be added later.

Useful? React with 👍 / 👎.

…rror

- Add `streaming` and `streamThrottleMs` to the MatrixConfig type so
  TypeScript recognizes them when accessed in handler.ts.
- Fix getMockImplementation() call signature in handler.streaming.test.ts
  by narrowing the type explicitly to avoid TS2349.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7cd4676b14

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +667 to +671
draftStream &&
finalText &&
!hasMedia &&
!payload.isError &&
streamEventId &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Drain in-flight draft sends before falling back

The fallback check relies on draftStream.getEventId() being non-null before it calls stop(), but createMatrixDraftStream only sets eventId after the async first send() resolves. If final delivery happens while that first send is still in flight, this branch skips stopping/draining and immediately calls deliverMatrixReplies, so the late draft send can still land afterward (showing a stray cursor draft) or get finalized later as a duplicate response depending on timing. The handler should drain the draft stream before deciding whether to use fallback final delivery.

Useful? React with 👍 / 👎.

…nt stray finalize

- Always drain in-flight draft sends (stop()) before checking getEventId()
  in deliver(), preventing late cursor messages when first send is still
  in-flight (P1 race condition fix)
- Pass replyToId (inbound event ID) when creating draft stream so streamed
  replies appear as replies to the triggering message in non-thread rooms (P2)
- Mark draftFinalized and call forceNewMessage() after fallback delivery
  (media/error path) so outer finalize() doesn't emit a stray text message (P1)
- Update streaming tests to match new behavior

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2960a3c777

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +710 to +712
if (draftStream) {
draftFinalized = true;
draftStream.forceNewMessage();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Clear stale draft event before fallback reply send

When a draft event already exists and deliver() falls back to deliverMatrixReplies() (for example hasMedia, payload.isError, or after a failed editMessageMatrix), this branch only calls forceNewMessage(), which resets local state but does not edit/delete the already-posted draft event. The prior streamed draft message (typically with the cursor suffix) remains visible and the fallback path sends another final message, so users can receive a stale draft plus a second reply in the same interaction.

Useful? React with 👍 / 👎.

@spengrah

spengrah commented Mar 2, 2026

Copy link
Copy Markdown

Chiming in here not with a comment on implementation quality but to emphasize how valuable this feature would be for me and anybody else using matrix as a comms channel with their agent!

When deliver() falls back to deliverMatrixReplies (media, error, or failed
in-place edit), finalize the existing draft event first to remove the cursor
suffix. Without this, users see a stale "...▌" draft message alongside the
final fallback reply.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7ab22717b7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +668 to +670
if (draftStream && !draftFinalized) {
await draftStream.stop();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep draft stream active across dispatcher payloads

deliver() unconditionally calls draftStream.stop() the first time it runs, and stop() permanently disables future update() calls for that stream. In requests that emit multiple payloads (for example, tool/block output followed by a final answer), the first payload will flip the stream into a stopped state, so later onPartialReply updates are ignored and Matrix partial streaming silently stops for the remainder of the same response.

Useful? React with 👍 / 👎.

The finalize() call edited the draft to partial text (minus cursor), then
deliverMatrixReplies sent the same final text as a new message. Revert to
avoid double messages; the cursor cleanup for fallback paths can be addressed
separately with a targeted edit approach.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0c24860054

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +675 to +679
draftStream &&
finalText &&
!hasMedia &&
!payload.isError &&
streamEventId &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve reasoning-only suppression in streaming finalize path

This fast path edits the draft event directly and returns, so it bypasses deliverMatrixReplies() where reasoning-only payloads are intentionally filtered out (extensions/matrix/src/matrix/monitor/replies.ts checks for Reasoning: / thinking tags before sending). With channels.matrix.streaming: "partial", if a response produces a draft event and the final payload is reasoning-only, that hidden reasoning text is now sent to Matrix instead of being dropped.

Useful? React with 👍 / 👎.

roomId,
accountId: route.accountId ?? undefined,
threadId: threadTarget ?? null,
replyToId: threadTarget ? undefined : messageId,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor replyToMode when creating draft stream replies

The draft stream is initialized with replyToId for every non-thread message, regardless of room replyToMode. In rooms configured with replyToMode: "off", streaming now still sends the draft/finalized message as a reply relation, while the normal path explicitly disables reply threading in that mode (extensions/matrix/src/matrix/monitor/replies.ts). This is a behavior regression gated on partial streaming being enabled.

Useful? React with 👍 / 👎.

AOrobator and others added 2 commits March 2, 2026 20:42
editMessageMatrix was sending plain text without HTML formatting, unlike
sendMessageMatrix which auto-converts via applyMatrixFormatting. This caused
raw markdown to appear during streaming edits in Element Web.

Now editMessageMatrix applies the same markdown-to-HTML conversion when
formattedText is not explicitly provided, so streaming drafts render
formatted text throughout.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…sors

If withReplyDispatcher or dispatchReplyFromConfig throws (agent error,
timeout, etc.), the outer finalize was skipped because it was inside the
try block. The cursor character stayed visible in the message forever.

Move the finalize cleanup to a finally block so it always runs, even on
error paths. Hoist draftStream/draftFinalized declarations to outer scope
so they're accessible from the finally block.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 777b789b6c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// timed out mid-response. Without this, a thrown exception in
// withReplyDispatcher/dispatchReplyFromConfig skips the finalize and
// leaves the cursor character visible in the message.
if (draftStream && !draftFinalized && draftStream.getEventId()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Cancel pending draft stream when no event exists

The cleanup path only runs when draftStream.getEventId() is truthy, so if partial text arrived but the first throttled send has not executed yet (default 800ms) and dispatch then errors, the stream is never stopped/cancelled. In that case the pending timer in createMatrixDraftStream can still fire after the handler exits, sending an orphan ▌ draft with no finalization pass to remove it. Cleanup should also cancel/stop pending draft work when no event ID exists.

Useful? React with 👍 / 👎.

Comment on lines +642 to +644
const matrixCfg = cfg.channels?.matrix;
const streamingEnabled = matrixCfg?.streaming === "partial";
const streamThrottleMs = matrixCfg?.streamThrottleMs ?? 800;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve streaming settings from the account-scoped config

Streaming is enabled from cfg.channels?.matrix here, but this handler runs per account and other reply behavior is already account-resolved. In multi-account setups, channels.matrix.accounts.<id>.streaming and streamThrottleMs are ignored unless also duplicated at the top level, so one account cannot independently enable/disable or tune partial streaming. Use the resolved account config for these flags.

Useful? React with 👍 / 👎.

Two fixes for messages getting cut off mid-stream:

1. editMessageMatrix now retries up to 3 times on M_LIMIT_EXCEEDED,
   respecting Synapse's retry_after_ms. Previously the final edit
   (cursor removal) would fail permanently on rate limit.

2. Draft stream finalize moved to a finally block so it always runs,
   even when withReplyDispatcher/dispatchReplyFromConfig throws.
   Previously an agent error/timeout would skip the finalize, leaving
   the cursor character visible forever.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4d127b4ebe

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +56 to +60
accountId: params.accountId,
threadId: params.threadId,
replyToId: params.replyToId,
});
eventId = result.messageId;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid chunked send for the first draft event

This initial draft send goes through sendMessageMatrix, which can split long text into multiple Matrix events and returns only the last event ID. The stream then stores that last ID and later edits it with the full accumulated text, so the earlier chunk messages remain in the room and the edited message repeats the prefix (duplicated/corrupted reply output). This happens when an early partial crosses the chunk limit (default 4000 chars), which is realistic with fast responses before the first throttled flush.

Useful? React with 👍 / 👎.

@ndbroadbent

Copy link
Copy Markdown
Contributor

Adding another +1 to say how important this is! Would be great to rebase this and get some attention on this so that streaming: "partial" works for Matrix.

I'm happy to help with beta testing of this branch

@gumadeiras

Copy link
Copy Markdown
Member

OpenClaw now uses a new Matrix plugin built on the official matrix-js-sdk. The older Matrix implementation is no longer supported.

Closing this as potentially fixed in the new plugin. If this still reproduces after migrating, please open a new issue/PR against the new Matrix plugin and link back here.

Migration/docs:
https://docs.openclaw.ai/channels/matrix
https://docs.openclaw.ai/install/migrating-matrix

@gumadeiras gumadeiras closed this Mar 19, 2026
@AOrobator
AOrobator deleted the feat/matrix-streaming branch March 20, 2026 01:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: matrix Channel integration: matrix size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants