Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 36 additions & 27 deletions src/stream-terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
// never happened discards valid blocks (#249). "unknown" is the safe default
// (no rebase; the next request self-heals via kernel message-id deactivation).

import { finalizeSseLineEndings, normalizeSseLineEndings } from "./sse-util.js";

type TerminalState = "completed" | "failed" | "unknown";

const SUCCEEDED = "response.completed";
Expand All @@ -14,24 +16,24 @@ export async function observeResponsesTerminalState(stream: ReadableStream<Uint8
return isStream ? observeSseTerminalState(stream) : observeJsonTerminalState(stream);
}

function terminalFromSseLine(line: string): TerminalState | null {
if (line.startsWith("event:")) {
const name = line.slice(6).trim();
if (name === SUCCEEDED) return "completed";
if (FAILED_EVENTS.has(name)) return "failed";
return null;
function terminalFromSseFrame(frame: string): TerminalState | null {
let event = "";
const data: string[] = [];
for (const line of frame.split("\n")) {
if (line.startsWith("event:")) event = line.slice(6).trim();
else if (line.startsWith("data:")) data.push(line.charAt(5) === " " ? line.slice(6) : line.slice(5));
}
if (line.startsWith("data:")) {
const data = line.slice(5).trim();
if (!data.startsWith("{")) return null;
try {
const type = (JSON.parse(data) as { type?: unknown }).type;
if (type === SUCCEEDED) return "completed";
if (type === "response.failed" || type === "response.incomplete") return "failed";
} catch {
return null;
}
if (data.length === 0) return null;
let body: unknown;
try {
body = JSON.parse(data.join("\n"));
} catch {
return null;
}
if (typeof body !== "object" || body === null || Array.isArray(body)) return null;
const type = (body as { type?: unknown }).type;
if (FAILED_EVENTS.has(event) || (typeof type === "string" && FAILED_EVENTS.has(type))) return "failed";
if (event === SUCCEEDED || type === SUCCEEDED) return "completed";
return null;
}

Expand All @@ -40,21 +42,28 @@ async function observeSseTerminalState(stream: ReadableStream<Uint8Array>): Prom
const decoder = new TextDecoder();
let buf = "";
let state: TerminalState = "unknown";
const consumeFrames = () => {
let boundary: number;
while ((boundary = buf.indexOf("\n\n")) >= 0) {
const frame = buf.slice(0, boundary);
buf = buf.slice(boundary + 2);
const next = terminalFromSseFrame(frame);
if (next !== null) {
state = next;
break;
}
}
};
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).replace(/\r$/, "");
buf = buf.slice(nl + 1);
const next = terminalFromSseLine(line);
if (next !== null) {
state = next;
break;
}
if (done) {
buf = finalizeSseLineEndings(buf + decoder.decode());
consumeFrames();
break;
}
buf = normalizeSseLineEndings(buf + decoder.decode(value, { stream: true }));
consumeFrames();
if (state !== "unknown") {
// Release this tee branch; the client branch keeps draining the source.
await reader.cancel().catch(() => {});
Expand Down
37 changes: 37 additions & 0 deletions tests/terminal-sse-framing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { observeResponsesTerminalState } from "../src/stream-terminal.ts";

function stream(parts: string[]) {
const encoder = new TextEncoder();
return new ReadableStream<Uint8Array>({
start(controller) {
for (const part of parts) controller.enqueue(encoder.encode(part));
controller.close();
},
});
}

for (const tail of [
"event: response.completed\n",
'event: response.completed\ndata: {"type":',
'data: {"type":"response.completed"}\n',
"event: response.completed\n\n",
"event: response.completed\ndata: {broken}\n\n",
]) {
test(`an undispatched or invalid terminal SSE event is not completed: ${JSON.stringify(tail)}`, async () => {
assert.equal(await observeResponsesTerminalState(stream([tail]), true), "unknown");
});
}

for (const eol of ["\n", "\r\n", "\r"]) {
test(`multiline data with ${JSON.stringify(eol)} separators is assembled before classification`, async () => {
const input = ['data: {"type":', 'data: "response.completed"}', "", ""].join(eol);
assert.equal(await observeResponsesTerminalState(stream([...input]), true), "completed");
});
}

test("a terminal header cannot override a failure in its data", async () => {
const input = 'event: response.completed\ndata: {"type":"response.failed"}\n\n';
assert.equal(await observeResponsesTerminalState(stream([input]), true), "failed");
});
Loading