Skip to content

Commit bba826e

Browse files
committed
client: SSE parser handles CRLF and flushes the final unterminated frame
Both are legal SSE and both previously caused a silent exit 0 with the complete event (and its report) swallowed: \r\n\r\n never matched the \n\n separator, and a final frame without a trailing blank line stayed in the buffer. Normalize \r\n and lone \r to \n (holding a chunk-boundary \r), flush the decoder, and parse the remainder at stream end. Fixes #3
1 parent 21a6018 commit bba826e

2 files changed

Lines changed: 49 additions & 4 deletions

File tree

‎src/client.ts‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,17 @@ export async function* postStream(
102102
const reader = res.body.getReader();
103103
const decoder = new TextDecoder();
104104
let buffer = "";
105+
let heldCR = false; // a trailing \r may be half of a \r\n split across chunks
105106

106-
while (true) {
107-
const { done, value } = await reader.read();
108-
if (done) break;
109-
buffer += decoder.decode(value, { stream: true });
107+
// SSE allows \r\n, \n, or \r line endings — normalize everything to \n.
108+
const toLF = (chunk: string): string => {
109+
let text = (heldCR ? "\r" : "") + chunk;
110+
heldCR = text.endsWith("\r");
111+
if (heldCR) text = text.slice(0, -1);
112+
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
113+
};
110114

115+
function* drainFrames(): Generator<SseEvent> {
111116
// SSE frames are separated by a blank line.
112117
let sep: number;
113118
while ((sep = buffer.indexOf("\n\n")) >= 0) {
@@ -117,6 +122,23 @@ export async function* postStream(
117122
if (evt) yield normalize(evt);
118123
}
119124
}
125+
126+
while (true) {
127+
const { done, value } = await reader.read();
128+
if (done) break;
129+
buffer += toLF(decoder.decode(value, { stream: true }));
130+
yield* drainFrames();
131+
}
132+
133+
// Stream ended: flush the decoder and any held \r, then emit whatever
134+
// remains — servers may omit the blank line after the final frame.
135+
buffer += toLF(decoder.decode());
136+
if (heldCR) buffer += "\n";
137+
yield* drainFrames();
138+
if (buffer.trim()) {
139+
const evt = parseFrame(buffer);
140+
if (evt) yield normalize(evt);
141+
}
120142
}
121143

122144
function parseFrame(frame: string): SseEvent | null {

‎test/cli.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,17 @@ beforeAll(() => {
4747
return Response.json({ summary: "A short summary." });
4848
}
4949
if (url.pathname === "/v1/research") {
50+
const q = (body as any).query ?? "";
51+
// Rude variants: CRLF line endings, and no blank line after the
52+
// final frame — both legal SSE that the parser must survive.
53+
if (q.includes("crlf")) {
54+
const sse = `event: start\r\ndata: {"message":"go"}\r\n\r\nevent: complete\r\ndata: ${JSON.stringify({ report: "# CRLF Report" })}\r\n\r\n`;
55+
return new Response(sse, { headers: { "Content-Type": "text/event-stream" } });
56+
}
57+
if (q.includes("unterminated")) {
58+
const sse = `event: start\ndata: {"message":"go"}\n\nevent: complete\ndata: ${JSON.stringify({ report: "# Last Frame Report" })}\n`;
59+
return new Response(sse, { headers: { "Content-Type": "text/event-stream" } });
60+
}
5061
const sse = [
5162
`event: start\ndata: ${JSON.stringify({ message: "go" })}\n\n`,
5263
`event: complete\ndata: ${JSON.stringify({ report: "# Report\nbody", metadata: { citedPages: [{ title: "Src", url: "https://e.com" }] } })}\n\n`,
@@ -152,6 +163,18 @@ test("research -o pretty streams and prints the report to stdout", async () => {
152163
expect(stderr).toContain("Cited 1 source"); // citations go to stderr
153164
});
154165

166+
test("research survives CRLF line endings in the SSE stream", async () => {
167+
const { stdout, code } = await run(["research", "crlf endings", "-o", "pretty"]);
168+
expect(code).toBe(0);
169+
expect(stdout).toContain("# CRLF Report");
170+
});
171+
172+
test("research does not drop a final frame missing its trailing blank line", async () => {
173+
const { stdout, code } = await run(["research", "unterminated stream", "-o", "pretty"]);
174+
expect(code).toBe(0);
175+
expect(stdout).toContain("# Last Frame Report");
176+
});
177+
155178
test("research piped emits NDJSON, one event per line", async () => {
156179
const { stdout, code } = await run(["research", "anything"]);
157180
expect(code).toBe(0);

0 commit comments

Comments
 (0)