Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix: cancel failed SSE streams

nash_suc92f82ff42d6
diff --git a/src/lib/llm-client.test.ts b/src/lib/llm-client.test.ts
index bb6fcb96..e84d1337 100644
--- a/src/lib/llm-client.test.ts
+++ b/src/lib/llm-client.test.ts
@@ -130,6 +130,39 @@ describe("streamChat — buffered streaming responses", () => {
expect(onDone).not.toHaveBeenCalled()
})
+ it("cancels a still-open response body after an SSE endpoint error", async () => {
+ let bodyCancelled = false
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(
+ 'data: {"error":{"message":"stream failed"}}\n',
+ ))
+ },
+ cancel() {
+ bodyCancelled = true
+ },
+ })
+ mockHttpFetch.mockResolvedValue(new Response(body, {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ }))
+ const onToken = vi.fn()
+ const onDone = vi.fn()
+ const onError = vi.fn()
+
+ await streamChat(
+ customStreamingCfg,
+ [{ role: "user", content: "hi" }],
+ { onToken, onDone, onError },
+ )
+
+ expect(onError).toHaveBeenCalledTimes(1)
+ expect(onError.mock.calls[0][0].message).toBe("LLM endpoint error: stream failed")
+ expect(bodyCancelled).toBe(true)
+ expect(onToken).not.toHaveBeenCalled()
+ expect(onDone).not.toHaveBeenCalled()
+ })
+
it("parses every record from a fully buffered SSE body", async () => {
const body = [
openAiSseToken("Hello"),
diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.ts
index 0de8118f..9bd3e604 100644
--- a/src/lib/llm-client.ts
+++ b/src/lib/llm-client.ts
@@ -359,6 +359,17 @@ export async function streamChat(
}
return parseEndpointErrorEnvelope(trimmed)
}
+ const stopForEndpointError = async (error: Error) => {
+ // An endpoint can emit an error event without closing its SSE response.
+ // Cancel the body so that the transport does not keep the connection and
+ // its buffers alive after the caller has already received the failure.
+ try {
+ await reader.cancel()
+ } catch {
+ // Preserve the endpoint's actionable error if transport cleanup fails.
+ }
+ onError(error)
+ }
try {
while (true) {
@@ -369,7 +380,7 @@ export async function streamChat(
for (const line of splitFinalStreamRecords(finalText)) {
const endpointError = processRecord(line)
if (endpointError) {
- onError(endpointError)
+ await stopForEndpointError(endpointError)
return
}
}
@@ -382,7 +393,7 @@ export async function streamChat(
for (const line of lines) {
const endpointError = processRecord(line)
if (endpointError) {
- onError(endpointError)
+ await stopForEndpointError(endpointError)
return
}
}