Repository navigation
Conversation
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]>
There was a problem hiding this comment.
💡 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 SummaryThis 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:
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:
Confidence Score: 5/5
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]>
There was a problem hiding this comment.
💡 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".
| if (draftStream && !draftFinalized && draftStream.getEventId()) { | ||
| await draftStream.finalize(); |
There was a problem hiding this comment.
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 👍 / 👎.
| ? createMatrixDraftStream({ | ||
| roomId, | ||
| accountId: route.accountId ?? undefined, | ||
| threadId: threadTarget ?? null, | ||
| throttleMs: streamThrottleMs, |
There was a problem hiding this comment.
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]>
There was a problem hiding this comment.
💡 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".
| draftStream && | ||
| finalText && | ||
| !hasMedia && | ||
| !payload.isError && | ||
| streamEventId && |
There was a problem hiding this comment.
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]>
There was a problem hiding this comment.
💡 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".
| if (draftStream) { | ||
| draftFinalized = true; | ||
| draftStream.forceNewMessage(); |
There was a problem hiding this comment.
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 👍 / 👎.
|
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]>
There was a problem hiding this comment.
💡 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".
| if (draftStream && !draftFinalized) { | ||
| await draftStream.stop(); | ||
| } |
There was a problem hiding this comment.
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]>
There was a problem hiding this comment.
💡 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".
| draftStream && | ||
| finalText && | ||
| !hasMedia && | ||
| !payload.isError && | ||
| streamEventId && |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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 👍 / 👎.
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]>
There was a problem hiding this comment.
💡 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()) { |
There was a problem hiding this comment.
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 👍 / 👎.
| const matrixCfg = cfg.channels?.matrix; | ||
| const streamingEnabled = matrixCfg?.streaming === "partial"; | ||
| const streamThrottleMs = matrixCfg?.streamThrottleMs ?? 800; |
There was a problem hiding this comment.
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]>
There was a problem hiding this comment.
💡 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".
| accountId: params.accountId, | ||
| threadId: params.threadId, | ||
| replyToId: params.replyToId, | ||
| }); | ||
| eventId = result.messageId; |
There was a problem hiding this comment.
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 👍 / 👎.
|
Adding another +1 to say how important this is! Would be great to rebase this and get some attention on this so that I'm happy to help with beta testing of this branch |
|
OpenClaw now uses a new Matrix plugin built on the official 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: |
Summary
Adds real-time streaming for Matrix channel responses using an edit-based "draft stream" pattern:
▌). Finalizes by editing the cursor away when the response completes.editMessageMatrix()function: New export insend.tsfor editing existing Matrix messages viam.relates_to/m.new_content(MSC2676 message replacement).forceNewMessage()after finalizing each block, preventing all blocks from editing the same draft message.send-queue.tsserializes 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
draft-stream.tsdraft-stream.test.tssend-edit.test.tseditMessageMatrix()integrationhandler.streaming.test.tsModified files
send.tseditMessageMatrix()exportsend/types.tsMatrixEditOptstypemonitor/handler.tsonPartialReplycallback, finalization, and multi-block fixTest plan
pnpm vitest run --config vitest.extensions.config.ts extensions/matrix/)🤖 Generated with Claude Code