[bug]: Streaming assistant messages fragment mid-word into separate rows, corrupting markdown
Update: root-caused in this comment, which also carries a suggested patch. The cause is the reducer closing text segments on async events (layer 2 below). The layer 1 claim is narrower than written here โ see the strikethrough.
Summary
A single streamed assistant turn is rendered as many disconnected message rows, split at arbitrary streaming-delta offsets rather than at markdown boundaries. Because each fragment is parsed as an independent markdown document, inline markdown state does not survive the split and content is visually lost, not just mis-styled.
Observed with a Claude session running under claude-acp.mjs.
Symptoms
Splits land in places no markdown boundary would produce:
- mid-word โ
The registry still sh/ows zero Codex sessions... - mid-contraction โ
Spinning up more sessions won/'t bridge them - mid-sentence โ
Reply's/in, and it confirms it:
Resulting markdown corruption:
- An inline code span opened before a boundary never closes. Everything after it renders in monospace, including literal unrendered
**bold**asterisks. - A stray code span containing only
, branchappears, from mispaired backticks. - A blockquote terminates early; its remainder continues as body text.
- A bullet's continuation becomes a top-level paragraph and the list restarts.
- The leaked code span does not wrap, so text is clipped at the right viewport edge and is genuinely unreadable (
...answerable froโ remainder lost). - A stray
Copyaffordance appears mid-paragraph, confirming these are separate message rows rather than one row rendered badly.
Repro
- Run a Claude session in Emdash.
- Ask for a long answer that interleaves prose with several tool calls and uses inline code spans containing slashes and colons (e.g. file paths).
- Watch the streamed output: fragments split mid-word and code spans leak into following text.
Expected
One assistant turn renders as one message row. Streaming deltas are concatenated before markdown parsing, or committed only at boundaries safe for all inline constructs โ not just fenced code.
Analysis
Two layers are implicated. The second looks like the root cause.
1. packages/chat-ui/src/core/caches.ts
parseBlocksStreaming (~L396) commits "settled" text and parses each settled chunk as a standalone document via parseMarkdownToBlocks(settledChunk, ...). Markdown state is therefore not carried across chunk boundaries by construction.
Its safety rests entirely on findSafeStreamBoundary (L106), which tracks only open code fences (```/~~~) and blank lines. ~~It has no notion of inline code spans, emphasis, blockquote context, or loose-list continuation โ so a "safe" blank-line boundary can still land inside an open inline construct.~~
Corrected: I tested each of those โ ordered lists, loose lists and fenced code all survive. The only real defect here is indented (4-space/tab) code blocks: a blank line between two indented lines looks like a block boundary and splits one code block in two.
2. packages/core/src/runtimes/acp/api/reducer/
decode.ts (L242) passes messageId: update.messageId ?? null for agent_message_chunk. For providers sending null message ids, reducer.ts synthesizes segment ids (synthesizedMessageId, L180) and closes them via closeSynthesizedSegment (L185).
The observed fragmentation is consistent with a synthesized segment being closed mid-stream, so subsequent deltas open a new message item โ which matches the per-fragment Copy buttons.
Fragment boundaries cluster around interleaved tool calls, suggesting a tool-call event closes the open assistant text segment instead of leaving it open for continuation. I did not confirm that last step, so treat it as a lead rather than a conclusion โ the two layers would need different fixes.
Correction + suggested patch
I've since root-caused this properly. Two corrections to my original analysis, then a patch.
The root cause is the reducer, not the markdown layer
materializeEvent closes the open synthesized text segment for every non-message event:
const closed = closeSynthesizedSegment(transcript, segment, at);
return { ...closed, event: event as FoldEvent };
closeSynthesizedSegment advances the per-stream segment counter, so the next text delta synthesizes a different messageId. foldItem looks that id up, misses, and appends a new message item instead of concatenating.
Providers sending null messageIds โ i.e. every delta of a streamed turn โ depend entirely on that segment staying open. tool_call_update and plan arrive asynchronously, so a tool status transition or terminal-output append can land between any two text deltas, including mid-word. That is the whole chain: the mid-word splits, the per-fragment Copy buttons, and the code-span leak, since each resulting item is parsed as an independent markdown document.
I over-claimed on findSafeStreamBoundary
The original report said this also broke inline code spans, emphasis, blockquotes, and loose-list continuation. I tested each of those: ordered lists, loose lists, and fenced code all survive correctly. Indented (4-space/tab) code blocks were the only real defect โ a blank line between two indented lines looks like a block boundary and splits one code block in two. Apologies for the noise; the narrower claim is the accurate one.
Suggested patch
Two commits against upstream/main (810e17f35), applyable with git am:
packages/coreโ only structural events close a text segment.tool_updateandplanleave an open text segment intact;tool_call/content_blockstill close it, so text before and after a tool call stays separate (pinned by a test). Thinking segments deliberately still close:foldItemfinalizes the open thinking row for these same events, so the counter must advance or the next reasoning delta reuses the finalized row's id.packages/chat-uiโ a blank line counts as a boundary only when the next non-blank line isn't indented 4+ spaces or a tab. When nothing follows yet the answer is unknowable, so it defers โ always safe, since the text stays in the re-parsed growing tail and is parsed in full on turn freeze.
Both new tests fail before the change and pass after.
Verification (branch based on upstream/main):
packages/coreโ 1727 passed / 1 skipped, 229 filespackages/chat-uiโ 256 tests / 20 files (node project)- ACP suite โ 295 tests
oxfmt --checkandoxlintclean on all touched files
tsgo reports pre-existing errors in chat-ui from unbuilt workspace deps (@emdash/shared/markdown, @emdash/core/runtimes/acp/api/client); I confirmed the identical list on a reverted tree, none in touched files.
I'd have opened this as a PR, but my checkout isn't a GitHub fork of this repo, so the patch is inline instead. Happy to send it as a PR if you'd prefer.
Patch series (git am)
From 51b9fcf2ebb0f2af14ba431e9223f88b96f53fe2 Mon Sep 17 00:00:00 2001
From: Ned Williamson <[email protected]>
Date: Tue, 8 Sep 2026 00:59:14 -0700
Subject: [PATCH 1/2] fix(acp): keep text segments open across non-structural
updates
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Providers that send null messageIds rely on the reducer's synthesized
segments to group consecutive agent text deltas into one message item.
materializeEvent closed the open segment for every non-message event,
including tool_call_update and plan revisions. Those arrive
asynchronously and can land between any two text deltas, so a single
assistant turn was split into several message items at arbitrary
offsets โ frequently mid-word. Each fragment is then parsed as an
independent markdown document, so inline state (code spans, emphasis)
leaks across the seam: an unclosed code span swallows the following
text and, because it does not wrap, clips it at the viewport edge.
Only close the segment for events that introduce a new visible row.
tool_update and plan now leave an open text segment intact.
Thinking segments still close: foldItem finalizes the open thinking row
for these same events, so the segment counter must advance or the next
reasoning delta would reuse the finalized row's id.
Fixes #3166
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
---
.../src/runtimes/acp/api/reducer/reducer.ts | 28 +++++
.../api/reducer/streaming-segments.test.ts | 109 ++++++++++++++++++
2 files changed, 137 insertions(+)
create mode 100644 packages/core/src/runtimes/acp/api/reducer/streaming-segments.test.ts
diff --git a/packages/core/src/runtimes/acp/api/reducer/reducer.ts b/packages/core/src/runtimes/acp/api/reducer/reducer.ts
index 68257654c..35eee9442 100644
--- a/packages/core/src/runtimes/acp/api/reducer/reducer.ts
+++ b/packages/core/src/runtimes/acp/api/reducer/reducer.ts
@@ -280,10 +280,38 @@ function materializeEvent(
return { ...closed, event: event as FoldEvent };
}
+ if (preservesTextSegment(segment, event)) {
+ return { transcript, segment, event: event as FoldEvent };
+ }
+
const closed = closeSynthesizedSegment(transcript, segment, at);
return { ...closed, event: event as FoldEvent };
}
+/**
+ * True when `event` must leave an open synthesized TEXT segment untouched.
+ *
+ * Providers that send null messageIds depend on the open segment to group
+ * consecutive agent text deltas into a single message item. Events that merely
+ * update existing transcript state โ tool status/output, plan revisions โ
+ * arrive asynchronously and can land between any two deltas, including in the
+ * middle of a word. Closing the segment for those splits one assistant turn
+ * into several message items, so each fragment is parsed as an independent
+ * markdown document and inline state (code spans, emphasis) leaks across the
+ * seam. See #3166.
+ *
+ * Events that introduce a NEW visible row (tool_call, content_block, ...) still
+ * close the segment, so text before and after a tool call stays separate.
+ *
+ * Thinking segments are deliberately excluded: foldItem finalizes the open
+ * thinking row for these same events, so the segment counter must advance or
+ * the next reasoning delta would reuse the finalized row's id.
+ */
+function preservesTextSegment(segment: SegmentState, event: NormalizedEvent): boolean {
+ if (segment.open === null || segment.open === 'thinking') return false;
+ return event.kind === 'tool_update' || event.kind === 'plan';
+}
+
function toAgentStatus(
status: Extract<NormalizedEvent, { kind: 'subagent' }>['status']
): AgentStatus {
diff --git a/packages/core/src/runtimes/acp/api/reducer/streaming-segments.test.ts b/packages/core/src/runtimes/acp/api/reducer/streaming-segments.test.ts
new file mode 100644
index 000000000..b82dc09bb
--- /dev/null
+++ b/packages/core/src/runtimes/acp/api/reducer/streaming-segments.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Regression tests for streaming text segmentation (issue #3166).
+ *
+ * Providers that send null messageIds rely on the reducer's synthesized
+ * segments to group consecutive agent text deltas into one message item.
+ * Asynchronous, non-structural events (tool status/output updates, plan
+ * updates) must NOT close that segment โ otherwise a single assistant turn is
+ * split into multiple message items at arbitrary delta offsets, which shows up
+ * as text broken mid-word and markdown state (code spans, emphasis) leaking
+ * because each fragment is parsed as an independent document.
+ */
+
+import type { SessionUpdate } from '@agentclientprotocol/sdk';
+import { describe, expect, it } from 'vitest';
+import { AcpTranscriptParser } from './parser';
+
+const CID = 'conv-seg';
+
+function deps() {
+ return { conversationId: CID };
+}
+
+function textChunk(text: string): SessionUpdate {
+ return {
+ sessionUpdate: 'agent_message_chunk',
+ sessionId: 'sess-1',
+ messageId: null,
+ content: { type: 'text', text },
+ } as unknown as SessionUpdate;
+}
+
+function toolCall(toolCallId: string): SessionUpdate {
+ return {
+ sessionUpdate: 'tool_call',
+ sessionId: 'sess-1',
+ toolCallId,
+ title: 'Terminal',
+ kind: 'execute',
+ status: 'pending',
+ } as unknown as SessionUpdate;
+}
+
+function toolUpdate(toolCallId: string, status: string): SessionUpdate {
+ return {
+ sessionUpdate: 'tool_call_update',
+ sessionId: 'sess-1',
+ toolCallId,
+ title: null,
+ kind: null,
+ status,
+ } as unknown as SessionUpdate;
+}
+
+function planUpdate(): SessionUpdate {
+ return {
+ sessionUpdate: 'plan',
+ sessionId: 'sess-1',
+ entries: [{ content: 'step one', priority: 'medium', status: 'in_progress' }],
+ } as unknown as SessionUpdate;
+}
+
+function assistantTexts(p: AcpTranscriptParser): string[] {
+ return p.history[0].items
+ .filter((it) => it.kind === 'message' && it.role === 'assistant')
+ .map((it) => (it as { text: string }).text);
+}
+
+describe('streaming text segmentation', () => {
+ it('does not split a message when a tool status update arrives mid-stream', () => {
+ const p = new AcpTranscriptParser(deps());
+ p.push(toolCall('t1'));
+ p.push(textChunk('The registry still sh'));
+ p.push(toolUpdate('t1', 'completed'));
+ p.push(textChunk('ows zero Codex sessions.'));
+ p.endTurn();
+
+ expect(assistantTexts(p)).toEqual(['The registry still shows zero Codex sessions.']);
+ });
+
+ it('does not split a message when a plan update arrives mid-stream', () => {
+ const p = new AcpTranscriptParser(deps());
+ p.push(textChunk('Spinning up more sessions won'));
+ p.push(planUpdate());
+ p.push(textChunk("'t bridge them."));
+ p.endTurn();
+
+ expect(assistantTexts(p)).toEqual(["Spinning up more sessions won't bridge them."]);
+ });
+
+ it('keeps an inline code span intact across an interleaved tool update', () => {
+ const p = new AcpTranscriptParser(deps());
+ p.push(textChunk('paths under `/tmp/cc-'));
+ p.push(toolUpdate('t1', 'in_progress'));
+ p.push(textChunk('socks/` are per-pid.'));
+ p.endTurn();
+
+ expect(assistantTexts(p)).toEqual(['paths under `/tmp/cc-socks/` are per-pid.']);
+ });
+
+ it('still starts a new message after a new tool call is introduced', () => {
+ const p = new AcpTranscriptParser(deps());
+ p.push(textChunk('before'));
+ p.push(toolCall('t1'));
+ p.push(textChunk('after'));
+ p.endTurn();
+
+ expect(assistantTexts(p)).toEqual(['before', 'after']);
+ });
+});
--
2.50.1 (Apple Git-155)
From c7874ed220e8ca3b87f995f521069709d7709bde Mon Sep 17 00:00:00 2001
From: Ned Williamson <[email protected]>
Date: Tue, 8 Sep 2026 01:01:17 -0700
Subject: [PATCH 2/2] fix(chat-ui): don't commit a stream boundary inside an
indented code block
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
findSafeStreamBoundary tracked open code fences but not indented code
blocks, so a blank line between two indented lines looked like a block
boundary. Committing there parsed the halves as independent documents
and split one code block into two.
Treat a blank line as a boundary only when the next non-blank line is
not indented 4+ spaces or a tab. When nothing follows yet the answer is
unknowable, so defer โ deferring is always safe, since the text stays in
the re-parsed growing tail and is parsed in full on turn freeze.
Refs #3166
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
---
packages/chat-ui/src/core/caches.ts | 26 +++++++++-
.../chat-ui/src/core/stream-boundary.test.ts | 51 +++++++++++++++++++
2 files changed, 75 insertions(+), 2 deletions(-)
create mode 100644 packages/chat-ui/src/core/stream-boundary.test.ts
diff --git a/packages/chat-ui/src/core/caches.ts b/packages/chat-ui/src/core/caches.ts
index da8a6fbdd..32f9d0ade 100644
--- a/packages/chat-ui/src/core/caches.ts
+++ b/packages/chat-ui/src/core/caches.ts
@@ -103,6 +103,25 @@ function endsInsideFence(text: string): boolean {
* `stableText` is used to determine whether the start of `tail` is already
* inside a code fence opened in the stable prefix.
*/
+/**
+ * True when a blank line is a safe commit point, given the text that follows it
+ * starting at `from`.
+ *
+ * A blank line is NOT a block boundary when the next non-blank line is indented
+ * 4+ spaces or a tab โ the blank may sit inside an indented code block, and
+ * committing there would split one code block in two.
+ *
+ * When nothing follows yet, the answer is unknowable, so defer. Deferring is
+ * always safe: the text stays in the re-parsed growing tail and is reconsidered
+ * on the next chunk (and parsed in full on turn freeze).
+ */
+function blankLineIsSafeBoundary(text: string, from: number): boolean {
+ let i = from;
+ while (i < text.length && text[i] === '\n') i += 1;
+ if (i >= text.length) return false;
+ return !(text.startsWith(' ', i) || text.startsWith('\t', i));
+}
+
function findSafeStreamBoundary(stableText: string, tail: string): number {
let inside = endsInsideFence(stableText);
let lastSafe = 0;
@@ -119,8 +138,11 @@ function findSafeStreamBoundary(stableText: string, tail: string): number {
// code block is structurally complete even without a trailing blank line.
if (!inside) lastSafe = nlIdx + 1;
}
- // A blank line outside a fence is also a safe boundary.
- if (!inside && tail[nlIdx + 1] === '\n') {
+ // A blank line outside a fence is also a safe boundary โ unless the content
+ // that follows it is indented, in which case the blank line may sit INSIDE
+ // an indented code block. Committing there would split one code block into
+ // two. Deferring is always safe: the tail is simply re-parsed next chunk.
+ if (!inside && tail[nlIdx + 1] === '\n' && blankLineIsSafeBoundary(tail, nlIdx + 2)) {
lastSafe = nlIdx + 2;
}
i = nlIdx + 1;
diff --git a/packages/chat-ui/src/core/stream-boundary.test.ts b/packages/chat-ui/src/core/stream-boundary.test.ts
new file mode 100644
index 000000000..cb94c7723
--- /dev/null
+++ b/packages/chat-ui/src/core/stream-boundary.test.ts
@@ -0,0 +1,51 @@
+// @vitest-environment jsdom
+/**
+ * Regression tests for streaming block boundaries (issue #3166).
+ *
+ * parseBlocksStreaming commits "settled" text at blank lines and parses each
+ * settled chunk as an independent document. A blank line inside an indented
+ * code block is not a real block boundary, so committing there split one code
+ * block into two. Streaming a document in chunks must produce the same block
+ * structure as parsing the finished text in one shot.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { createParseCaches } from './caches';
+
+function streamed(chunks: string[]) {
+ const caches = createParseCaches();
+ let acc = '';
+ let blocks = caches.parseBlocksStreaming('m1', '');
+ for (const chunk of chunks) {
+ acc += chunk;
+ blocks = caches.parseBlocksStreaming('m1', acc);
+ }
+ return { streaming: blocks, oneShot: createParseCaches().parseBlocks('m2', acc) };
+}
+
+describe('parseBlocksStreaming block boundaries', () => {
+ it('keeps an indented code block whole across an interior blank line', () => {
+ const r = streamed([' line one\n\n', ' line two\n']);
+ expect(r.streaming).toHaveLength(r.oneShot.length);
+ });
+
+ it('keeps a tab-indented code block whole across an interior blank line', () => {
+ const r = streamed(['\tline one\n\n', '\tline two\n']);
+ expect(r.streaming).toHaveLength(r.oneShot.length);
+ });
+
+ it('still commits at a blank line between ordinary paragraphs', () => {
+ const r = streamed(['first para\n\n', 'second para\n']);
+ expect(r.streaming).toHaveLength(r.oneShot.length);
+ });
+
+ it('preserves ordered list numbering across blank lines', () => {
+ const r = streamed(['1. first\n\n', '2. second\n\n', '3. third\n']);
+ expect(r.streaming).toHaveLength(r.oneShot.length);
+ });
+
+ it('keeps a fenced code block whole across an interior blank line', () => {
+ const r = streamed(['```js\nconst a = 1;\n\n', 'const b = 2;\n```\n']);
+ expect(r.streaming).toHaveLength(r.oneShot.length);
+ });
+});
--
2.50.1 (Apple Git-155)
Aside, offered because it seems on-topic for Emdash rather than as an excuse: these issues were filed by an agent running inside Emdash. My user asked it to "report this to emdash," meaning the emdash agent session in another worktree โ the agent resolved "emdash" to this GitHub org and filed publicly instead. The bug reports are real and intended to be here, so no harm done, but the ambiguity might be worth a thought in a product where agent sessions, the app, and the repo all share one name. The irreversible reading was the one it picked.
Human here, sorry the tone there is not great. Again, just learning how all this works! Thanks so much for a cool project!
I will take this issue. Please assign it to me.
The problem seems to be with the parseBlocksStreaming function in packages/chat-ui/src/core/caches.ts. It commits text segments too early, causing markdown parsing to happen on incomplete fragments. I would first examine how parseMarkdownToBlocks is handling these segments. A small fix could involve adjusting the logic to ensure that text is only committed at safe markdown boundaries. I will inspect the async event handling to confirm this and test with markdown-heavy content to verify the fix.