Skip to content

Commit b717829

Browse files
ml12580claude
andcommitted
fix(streaming): preserve paragraph separators across block-streamed deliveries
Carry the paragraph boundary through the delivered block-reply path and keep emitted chunks within maxChars (#42106): - chunker: attach the canonical `\n\n` separator to paragraph-split chunks and reserve its length in the fit check; re-attach in #emitBreakResult only when the result stays within maxChars. - emitBlockChunk: preserve a single trailing `\n\n` on non-final deliveries (the separator the chunker attached) so successive separate deliveries reconstruct the blank line; keep assistantTexts separator-free via visibleChunk. - coalescer: joinBufferedText strips a trailing whitespace run from the left before re-joining (whitespace joiner) so separator-carrying chunks in one flush do not produce `\n\n\n\n`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent add9f3c commit b717829

8 files changed

Lines changed: 187 additions & 22 deletions

‎src/agents/embedded-agent-block-chunker.test.ts‎

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,45 @@ function expectChunksWithinLength(chunks: string[], maxLength: number) {
2727
}
2828

2929
describe("EmbeddedBlockChunker", () => {
30+
it("preserves the paragraph separator across separate flushed chunks (#42106)", () => {
31+
// A reply split into more than one block-streamed delivery must stay
32+
// Markdown-equivalent when a client concatenates the deliveries.
33+
const chunker = createFlushOnParagraphChunker({ minChars: 1, maxChars: 200 });
34+
chunker.append("# Title\n\nFirst paragraph.\n\nSecond paragraph.");
35+
36+
const chunks: string[] = [];
37+
chunker.drain({ force: false, emit: (chunk) => chunks.push(chunk) });
38+
chunker.drain({ force: true, emit: (chunk) => chunks.push(chunk) });
39+
40+
expect(chunks.length).toBeGreaterThan(1);
41+
// Concatenating the streamed deliveries reconstructs the original text,
42+
// blank-line paragraph boundaries included.
43+
expect(chunks.join("")).toBe("# Title\n\nFirst paragraph.\n\nSecond paragraph.");
44+
// No delivery is just whitespace.
45+
for (const chunk of chunks) {
46+
expect(chunk.trim().length).toBeGreaterThan(0);
47+
}
48+
});
49+
50+
it("keeps paragraph-boundary chunks within maxChars including the separator (#94216)", () => {
51+
// Exact-boundary repro: a paragraph whose length equals maxChars must not
52+
// emit `chunk + "\n\n"` (which would exceed maxChars). With maxChars 10 and
53+
// "abcdefghij\n\nRest", the paragraph fast path must not emit a 12-char
54+
// chunk; it falls through to the size-split path, which respects the bound.
55+
const chunker = createFlushOnParagraphChunker({ minChars: 1, maxChars: 10 });
56+
chunker.append("abcdefghij\n\nRest");
57+
58+
const chunks: string[] = [];
59+
chunker.drain({ force: false, emit: (chunk) => chunks.push(chunk) });
60+
chunker.drain({ force: true, emit: (chunk) => chunks.push(chunk) });
61+
62+
// No emitted chunk may exceed the delivery bound, separator included.
63+
expectChunksWithinLength(chunks, 10);
64+
// No content is lost when the over-limit paragraph falls back to size splitting.
65+
expect(chunks.join("")).toContain("abcdefghij");
66+
expect(chunks.join("")).toContain("Rest");
67+
});
68+
3069
it("breaks at paragraph boundary right after fence close", () => {
3170
// A closed fence is a safe boundary; splitting before it would corrupt
3271
// markdown rendered by downstream clients.
@@ -52,7 +91,10 @@ describe("EmbeddedBlockChunker", () => {
5291

5392
expect(chunks.length).toBe(1);
5493
expect(chunks[0]).toContain("console.log");
55-
expect(chunks[0]).toMatch(/```\n?$/);
94+
// The chunk still ends at the closed fence (never mid-fence) and now carries
95+
// the trailing paragraph boundary it ended at so successive deliveries
96+
// reconstruct the "\n\n" separator (#42106).
97+
expect(chunks[0]).toMatch(/```\n\n$/);
5698
expect(chunks[0]).not.toContain("After");
5799
expect(chunker.bufferedText).toMatch(/^After/);
58100
});
@@ -64,7 +106,7 @@ describe("EmbeddedBlockChunker", () => {
64106

65107
const chunks = drainChunks(chunker);
66108

67-
expect(chunks).toEqual(["First paragraph.\n\nSecond paragraph."]);
109+
expect(chunks).toEqual(["First paragraph.\n\nSecond paragraph.\n\n"]);
68110
expect(chunker.bufferedText).toBe("Third paragraph.");
69111
});
70112

@@ -107,7 +149,12 @@ describe("EmbeddedBlockChunker", () => {
107149
const chunks = drainChunks(chunker);
108150

109151
expectChunksWithinLength(chunks, 10);
110-
expect(chunks).toEqual(["abcdefghij", "k"]);
152+
// "abcdefghij" is a maxChars clamp (no boundary). "k" ends at the paragraph
153+
// break, so post-fix (#42106) it carries the consumed "\n\n".
154+
expect(chunks).toEqual(["abcdefghij", "k\n\n"]);
155+
// The clamped body still respects maxChars; only the boundary chunk gains
156+
// the 2-char separator appended after the size decision.
157+
expect(chunks[0].length).toBeLessThanOrEqual(10);
111158
expect(chunker.bufferedText).toBe("Rest");
112159
});
113160

@@ -135,7 +182,7 @@ describe("EmbeddedBlockChunker", () => {
135182

136183
const chunks = drainChunks(chunker);
137184

138-
expect(chunks).toEqual(["Intro\n```js\nconst a = 1;\n\nconst b = 2;\n```"]);
185+
expect(chunks).toEqual(["Intro\n```js\nconst a = 1;\n\nconst b = 2;\n```\n\n"]);
139186
expect(chunker.bufferedText).toBe("After fence");
140187
});
141188

‎src/agents/embedded-agent-block-chunker.ts‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,11 @@ export class EmbeddedBlockChunker {
149149
const { force, emit } = params;
150150
const minChars = Math.max(1, Math.floor(this.#chunking.minChars));
151151
const maxChars = Math.max(minChars, Math.floor(this.#chunking.maxChars));
152+
// Canonical paragraph boundary attached to paragraph-split chunks so a
153+
// downstream client that concatenates successive streamed deliveries
154+
// reconstructs the blank line (#42106). Its length is reserved in the fit
155+
// check below so emitted chunks never exceed maxChars (#94216).
156+
const paragraphSeparator = "\n\n";
152157

153158
if (this.#buffer.length < minChars && !force) {
154159
return;
@@ -178,10 +183,20 @@ export class EmbeddedBlockChunker {
178183
if (this.#chunking.flushOnParagraph && !force) {
179184
const paragraphBreak = findNextParagraphBreak(source, fenceSpans, start, minChars);
180185
const paragraphLimit = Math.max(1, maxChars - reopenPrefix.length);
181-
if (paragraphBreak && paragraphBreak.index - start <= paragraphLimit) {
186+
// Reserve the appended separator so the emitted chunk (slice + separator)
187+
// stays within maxChars; a paragraph that would overflow falls through to
188+
// the size-split path below instead of breaching the delivery bound (#94216).
189+
if (
190+
paragraphBreak &&
191+
paragraphBreak.index - start <= paragraphLimit - paragraphSeparator.length
192+
) {
182193
const chunk = `${reopenPrefix}${source.slice(start, paragraphBreak.index)}`;
183194
if (chunk.trim().length > 0) {
184-
emit(chunk);
195+
// Attach the canonical paragraph boundary the chunk just ended at so a
196+
// downstream client concatenating successive deliveries reconstructs the
197+
// separator (#42106). The coalescer collapses any trailing newline run
198+
// before re-joining, so this never compounds into 4+ newlines.
199+
emit(`${chunk}${paragraphSeparator}`);
185200
}
186201
start = skipLeadingNewlines(source, paragraphBreak.index + paragraphBreak.length);
187202
reopenFence = undefined;
@@ -212,6 +227,8 @@ export class EmbeddedBlockChunker {
212227
reopenPrefix,
213228
source,
214229
start,
230+
maxChars,
231+
paragraphSeparator,
215232
});
216233
if (consumed === null) {
217234
continue;
@@ -239,8 +256,10 @@ export class EmbeddedBlockChunker {
239256
reopenPrefix: string;
240257
source: string;
241258
start: number;
259+
maxChars: number;
260+
paragraphSeparator: string;
242261
}): { start: number; reopenFence?: FenceSpan } | null {
243-
const { breakResult, emit, reopenPrefix, source, start } = params;
262+
const { breakResult, emit, reopenPrefix, source, start, maxChars, paragraphSeparator } = params;
244263
const breakIdx = breakResult.index;
245264
if (breakIdx <= 0) {
246265
return null;
@@ -260,6 +279,21 @@ export class EmbeddedBlockChunker {
260279
rawChunk = `${rawChunk}${closeFence}`;
261280
}
262281

282+
// When a non-fence break consumed a genuine paragraph boundary (a blank line
283+
// "\n[ \t]*\n" follows in the source), re-attach the canonical "\n\n"
284+
// separator — mirroring the paragraph fast path above — so a downstream client
285+
// concatenating successive separate deliveries reconstructs the separator
286+
// (#42106). The size-split / force path (message_end flush, leftover-buffer
287+
// flush) would otherwise drop the boundary. Skipped for fence splits (they
288+
// manage their own newline handling) and only applied when it stays within
289+
// maxChars, preserving the #94216 delivery-bound invariant.
290+
if (!fenceSplit && /^\n[ \t]*\n/.test(source.slice(absoluteBreakIdx))) {
291+
const withSeparator = `${rawChunk.replace(/\s+$/, "")}${paragraphSeparator}`;
292+
if (withSeparator.length <= maxChars) {
293+
rawChunk = withSeparator;
294+
}
295+
}
296+
263297
emit(rawChunk);
264298

265299
if (fenceSplit) {

‎src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.keeps-indented-fenced-blocks-intact.test.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,12 @@ describe("subscribeEmbeddedAgentSession", () => {
2525
emitAssistantTextDeltaAndEnd({ emit, text });
2626

2727
expect(onBlockReply).toHaveBeenCalledTimes(3);
28-
expect(extractTextPayloads(onBlockReply.mock.calls)).toEqual([
29-
"Intro",
30-
" ```js\n const x = 1;\n ```",
31-
"Outro",
32-
]);
28+
// #42106: non-final per-paragraph deliveries carry their trailing "\n\n" so the
29+
// separate deliveries reconstruct the inter-paragraph separator; the fence stays
30+
// intact and the terminal delivery stays trimmed.
31+
const indentedDelivered = extractTextPayloads(onBlockReply.mock.calls);
32+
expect(indentedDelivered).toEqual(["Intro\n\n", " ```js\n const x = 1;\n ```\n\n", "Outro"]);
33+
expect(indentedDelivered.join("")).toBe(text);
3334
});
3435
it("accepts longer fence markers for close", () => {
3536
const onBlockReply = vi.fn();
@@ -46,6 +47,9 @@ describe("subscribeEmbeddedAgentSession", () => {
4647
emitAssistantTextDeltaAndEnd({ emit, text });
4748

4849
const payloadTexts = extractTextPayloads(onBlockReply.mock.calls);
49-
expect(payloadTexts).toEqual(["Intro", "````md\nline1\nline2\n````", "Outro"]);
50+
// #42106: non-final deliveries carry their trailing "\n\n"; the longer-marker fence
51+
// stays intact and the deliveries reconstruct the source.
52+
expect(payloadTexts).toEqual(["Intro\n\n", "````md\nline1\nline2\n````\n\n", "Outro"]);
53+
expect(payloadTexts.join("")).toBe(text);
5054
});
5155
});

‎src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.reopens-fenced-blocks-splitting-inside-them.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ describe("subscribeEmbeddedAgentSession", () => {
3838
emitAssistantTextDeltaAndEnd({ emit, text });
3939

4040
expect(onBlockReply).toHaveBeenCalledTimes(3);
41-
expect(onBlockReply.mock.calls.at(1)?.[0].text).toBe("~~~sh\nline1\nline2\n~~~");
41+
// #42106: the tilde fence is never split; the middle (non-final) delivery now
42+
// also carries the trailing paragraph boundary "\n\n" it ended at so the
43+
// separate deliveries reconstruct the inter-paragraph separator.
44+
expect(onBlockReply.mock.calls.at(1)?.[0].text).toBe("~~~sh\nline1\nline2\n~~~\n\n");
4245
});
4346
});

‎src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.streams-soft-chunks-paragraph-preference.test.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,31 @@ describe("subscribeEmbeddedAgentSession", () => {
2727
emitAssistantTextDeltaAndEnd({ emit, text });
2828

2929
expect(onBlockReply).toHaveBeenCalledTimes(2);
30-
expect(blockReplyTexts(onBlockReply)).toEqual(["First block line", "Second block line"]);
30+
// #42106: non-final per-paragraph deliveries carry their trailing "\n\n" so
31+
// that concatenating the separate deliveries reconstructs the inter-paragraph
32+
// separator; the terminal delivery stays trimEnd-ed (no successor to join with).
33+
expect(blockReplyTexts(onBlockReply)).toEqual(["First block line\n\n", "Second block line"]);
3134
expect(subscription.assistantTexts).toEqual(["First block line", "Second block line"]);
3235
});
36+
it("delivered payloads reconstruct the paragraph separator across separate deliveries (#42106)", () => {
37+
const onBlockReply = vi.fn();
38+
const { emit } = createParagraphChunkedBlockReplyHarness({
39+
onBlockReply,
40+
chunking: { minChars: 5, maxChars: 25 }, // forces separate per-paragraph deliveries
41+
});
42+
43+
const source = "# Title\n\nFirst paragraph.\n\nSecond paragraph.";
44+
emitAssistantTextDeltaAndEnd({ emit, text: source });
45+
46+
const delivered = blockReplyTexts(onBlockReply);
47+
48+
// Concatenating the separate streamed deliveries reconstructs the source,
49+
// blank-line paragraph boundaries included.
50+
expect(delivered.join("")).toBe(source);
51+
// The boundary lives on the non-final deliveries; the terminal stays trimmed.
52+
expect(delivered.at(-1)).toBe("Second paragraph.");
53+
expect(delivered.slice(0, -1).every((payload) => payload.endsWith("\n\n"))).toBe(true);
54+
});
3355
it("avoids splitting inside fenced code blocks", () => {
3456
const onBlockReply = vi.fn();
3557
const { emit } = createParagraphChunkedBlockReplyHarness({
@@ -45,6 +67,11 @@ describe("subscribeEmbeddedAgentSession", () => {
4567
emitAssistantTextDeltaAndEnd({ emit, text });
4668

4769
expect(onBlockReply).toHaveBeenCalledTimes(3);
48-
expect(blockReplyTexts(onBlockReply)).toEqual(["Intro", "```bash\nline1\nline2\n```", "Outro"]);
70+
// #42106: non-final per-paragraph deliveries carry their trailing "\n\n" so the
71+
// separate deliveries reconstruct the inter-paragraph separator (including
72+
// across a fenced block); the terminal delivery stays trimEnd-ed.
73+
const fencedDelivered = blockReplyTexts(onBlockReply);
74+
expect(fencedDelivered).toEqual(["Intro\n\n", "```bash\nline1\nline2\n```\n\n", "Outro"]);
75+
expect(fencedDelivered.join("")).toBe(text);
4976
});
5077
});

‎src/agents/embedded-agent-subscribe.ts‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -992,12 +992,20 @@ export function subscribeEmbeddedAgentSession(params: SubscribeEmbeddedAgentSess
992992
}
993993
// Strip <think> and <final> blocks across chunk boundaries to avoid leaking reasoning.
994994
// Also strip downgraded tool call text ([Tool Call: ...], [Historical context: ...], etc.).
995-
const blockReplyText = stripDowngradedToolCallText(
995+
const stripped = stripDowngradedToolCallText(
996996
stripBlockTags(text, state.blockState, {
997997
final: options?.final === true,
998998
completeMarkdownChunk: options?.completeMarkdownChunk === true,
999999
}),
1000-
).trimEnd();
1000+
);
1001+
// Preserve a single trailing paragraph boundary the chunker attached (#42106)
1002+
// on non-final deliveries so successive separate deliveries reconstruct "\n\n";
1003+
// otherwise trim exactly as before. Never preserve it on the terminal/final
1004+
// delivery — the last block has no successor to concatenate with.
1005+
const endedAtParagraphBoundary = options?.final !== true && /\n[ \t]*\n[ \t]*$/.test(stripped);
1006+
const blockReplyText = endedAtParagraphBoundary
1007+
? `${stripped.trimEnd()}\n\n`
1008+
: stripped.trimEnd();
10011009
if (!blockReplyText) {
10021010
return;
10031011
}
@@ -1035,6 +1043,12 @@ export function subscribeEmbeddedAgentSession(params: SubscribeEmbeddedAgentSess
10351043
return;
10361044
}
10371045

1046+
// assistantTexts records the visible per-message text; the trailing paragraph
1047+
// boundary (#42106) is a delivery-reconstruction artifact that must not leak
1048+
// into the recorded visible text, so strip it for the assistantTexts record
1049+
// only. The delivered payload below still carries the boundary.
1050+
const visibleChunk = chunk.replace(/\n[ \t]*\n[ \t]*$/, "");
1051+
10381052
// Only check committed (successful) messaging tool texts - checking pending texts
10391053
// is risky because if the tool fails after suppression, the user gets no response
10401054
const normalizedChunk = normalizeTextForComparison(chunk);
@@ -1064,7 +1078,7 @@ export function subscribeEmbeddedAgentSession(params: SubscribeEmbeddedAgentSess
10641078
}
10651079

10661080
if (!params.onBlockReply) {
1067-
pushAssistantText(chunk);
1081+
pushAssistantText(visibleChunk);
10681082
markBlockReplyTextHandled();
10691083
return;
10701084
}
@@ -1089,7 +1103,7 @@ export function subscribeEmbeddedAgentSession(params: SubscribeEmbeddedAgentSess
10891103
}
10901104
return;
10911105
}
1092-
pushAssistantText(chunk);
1106+
pushAssistantText(visibleChunk);
10931107
emitBlockReply(
10941108
{
10951109
text: cleanedText,

‎src/auto-reply/reply/block-reply-coalescer.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,22 @@ export function createBlockReplyCoalescer(params: {
2525
const joiner = config.joiner ?? "";
2626
const flushOnEnqueue = config.flushOnEnqueue === true;
2727

28+
/**
29+
* Joins a buffered chunk with the next one using the configured joiner while
30+
* collapsing any boundary that already exists at the seam. Block chunks now
31+
* carry their own trailing paragraph separator (issue #42106), so re-applying
32+
* a "\n\n" joiner verbatim would produce "\n\n\n\n". When the joiner is itself
33+
* whitespace we strip a trailing run of that whitespace from the left side
34+
* before joining, leaving exactly one separator regardless of whether the
35+
* boundary arrived in-band on the chunk or only via the joiner.
36+
*/
37+
const joinBufferedText = (left: string, right: string): string => {
38+
if (!joiner || joiner.trim().length > 0) {
39+
return `${left}${joiner}${right}`;
40+
}
41+
return `${left.replace(/\s+$/, "")}${joiner}${right}`;
42+
};
43+
2844
let bufferText = "";
2945
let bufferReplyToId: ReplyPayload["replyToId"];
3046
let bufferAudioAsVoice: ReplyPayload["audioAsVoice"];
@@ -118,7 +134,7 @@ export function createBlockReplyCoalescer(params: {
118134

119135
/** Merges buffered text into a media payload without changing media metadata. */
120136
const mergeBufferedTextWithMedia = (payload: ReplyPayload, text: string): ReplyPayload => {
121-
const mergedText = text ? `${bufferText}${joiner}${text}` : bufferText;
137+
const mergedText = text ? joinBufferedText(bufferText, text) : bufferText;
122138
const mergedPayload: ReplyPayload = {
123139
...payload,
124140
text: mergedText,
@@ -192,7 +208,7 @@ export function createBlockReplyCoalescer(params: {
192208
startBufferFromPayload(payload);
193209
}
194210

195-
const nextText = bufferText ? `${bufferText}${joiner}${text}` : text;
211+
const nextText = bufferText ? joinBufferedText(bufferText, text) : text;
196212
if (nextText.length > maxChars) {
197213
if (bufferText) {
198214
void flush({ force: true });

‎src/auto-reply/reply/reply-utils.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -973,6 +973,26 @@ describe("block reply coalescer", () => {
973973
coalescer.stop();
974974
});
975975

976+
it("does not emit quadruple newlines when chunks already carry their paragraph boundary (#42106)", async () => {
977+
// Post-fix the block chunker attaches the consumed "\n\n" to each emitted
978+
// chunk. Re-applying the "\n\n" joiner verbatim would yield "\n\n\n\n"; the
979+
// coalescer must collapse the seam to exactly one paragraph separator.
980+
vi.useFakeTimers();
981+
const { flushes, coalescer } = createBlockCoalescerHarness({
982+
minChars: 1,
983+
maxChars: 2000,
984+
idleMs: 50,
985+
joiner: "\n\n",
986+
});
987+
988+
coalescer.enqueue({ text: "First paragraph\n\n" });
989+
coalescer.enqueue({ text: "Second paragraph" });
990+
991+
await vi.advanceTimersByTimeAsync(50);
992+
expect(flushes).toEqual(["First paragraph\n\nSecond paragraph"]);
993+
coalescer.stop();
994+
});
995+
976996
it("force flushes buffered newline-style chunks even below minChars", async () => {
977997
const { flushes, coalescer } = createBlockCoalescerHarness({
978998
minChars: 100,

0 commit comments

Comments
 (0)