Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(chat): a CRLF stream came back as an empty answer

purplebd406da5af7c
diff --git a/src/api/__tests__/sse-parser.test.ts b/src/api/__tests__/sse-parser.test.ts
index 43b4079c..2feeaa5d 100644
--- a/src/api/__tests__/sse-parser.test.ts
+++ b/src/api/__tests__/sse-parser.test.ts
@@ -92,6 +92,41 @@ describe('parseSSEStream', () => {
expect(events[0].data).toBe('{"content":"hello"}')
})
+ // The spec allows CRLF and lone CR as terminators. Splitting on '\n\n' only
+ // glued a CRLF stream into a single block whose JSON never parsed, so the
+ // answer arrived silently empty.
+ it('parses events separated by CRLF', async () => {
+ const res = mockResponse('data: {"a":1}\r\n\r\ndata: {"a":2}\r\n\r\ndata: [DONE]\r\n\r\n')
+ const events = []
+ for await (const event of parseSSEStream(res)) {
+ events.push(event)
+ }
+ expect(events.map(e => e.data)).toEqual(['{"a":1}', '{"a":2}', '[DONE]'])
+ })
+
+ it('parses events separated by lone CR', async () => {
+ const res = mockResponse('data: {"a":1}\r\rdata: {"a":2}\r\r')
+ const events = []
+ for await (const event of parseSSEStream(res)) {
+ events.push(event)
+ }
+ expect(events.map(e => e.data)).toEqual(['{"a":1}', '{"a":2}'])
+ })
+
+ it('does not split an event when a CRLF straddles two reads', async () => {
+ const res = mockChunkedResponse([
+ 'event: content_block_delta\r',
+ '\ndata: {"a":1}\r\n\r\n',
+ ])
+ const events = []
+ for await (const event of parseSSEStream(res)) {
+ events.push(event)
+ }
+ expect(events).toHaveLength(1)
+ expect(events[0].event).toBe('content_block_delta')
+ expect(events[0].data).toBe('{"a":1}')
+ })
+
it('ignores comment lines', async () => {
const res = mockResponse(': this is a comment\ndata: {"a":1}\n\n')
const events = []
diff --git a/src/api/sse.ts b/src/api/sse.ts
index b41fda48..150d6688 100644
--- a/src/api/sse.ts
+++ b/src/api/sse.ts
@@ -22,6 +22,28 @@ export interface SSEEvent {
* Parse an SSE stream into individual events.
* Handles multi-line data fields, event types, and the [DONE] sentinel.
*/
+/** One `event:`/`data:` block into an SSEEvent, or null if it carries no data. */
+function parseEventBlock(block: string): SSEEvent | null {
+ const trimmed = block.trim()
+ if (!trimmed) return null
+
+ let event: string | undefined
+ let data = ''
+
+ for (const line of trimmed.split('\n')) {
+ if (line.startsWith('event:')) {
+ event = line.slice(6).trim()
+ } else if (line.startsWith('data:')) {
+ // Accumulate data lines (multi-line data support)
+ if (data) data += '\n'
+ data += line.slice(5).trim()
+ }
+ // Ignore other fields (id:, retry:, comments starting with :)
+ }
+
+ return data ? { event, data } : null
+}
+
export async function* parseSSEStream(response: Response): AsyncGenerator<SSEEvent> {
const reader = response.body?.getReader()
if (!reader) throw new Error('No response body')
@@ -36,52 +58,28 @@ export async function* parseSSEStream(response: Response): AsyncGenerator<SSEEve
buffer += decoder.decode(value, { stream: true })
+ // The SSE spec allows CRLF and lone CR as line terminators, and some
+ // servers and proxies use them. Splitting on '\n\n' alone glued every
+ // event of such a stream into one block whose JSON never parsed — the
+ // whole answer came back silently empty.
+ // A trailing '\r' may be the first half of a CRLF split across two reads,
+ // so it waits in the buffer until we can see what follows it.
+ const carry = buffer.endsWith('\r') ? '\r' : ''
+ const normalized = (carry ? buffer.slice(0, -1) : buffer).replace(/\r\n?/g, '\n')
+
// SSE events are separated by double newline
- const parts = buffer.split('\n\n')
- buffer = parts.pop() || ''
+ const parts = normalized.split('\n\n')
+ buffer = (parts.pop() || '') + carry
for (const part of parts) {
- const trimmed = part.trim()
- if (!trimmed) continue
-
- let event: string | undefined
- let data = ''
-
- for (const line of trimmed.split('\n')) {
- if (line.startsWith('event:')) {
- event = line.slice(6).trim()
- } else if (line.startsWith('data:')) {
- // Accumulate data lines (multi-line data support)
- if (data) data += '\n'
- data += line.slice(5).trim()
- }
- // Ignore other fields (id:, retry:, comments starting with :)
- }
-
- if (data) {
- yield { event, data }
- }
+ const parsed = parseEventBlock(part)
+ if (parsed) yield parsed
}
}
// Process any remaining buffer
- if (buffer.trim()) {
- let event: string | undefined
- let data = ''
-
- for (const line of buffer.trim().split('\n')) {
- if (line.startsWith('event:')) {
- event = line.slice(6).trim()
- } else if (line.startsWith('data:')) {
- if (data) data += '\n'
- data += line.slice(5).trim()
- }
- }
-
- if (data) {
- yield { event, data }
- }
- }
+ const tail = parseEventBlock(buffer.replace(/\r\n?/g, '\n'))
+ if (tail) yield tail
} finally {
reader.releaseLock()
}