Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

2.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import { takeSseFrame } from "./sse-framing.ts";

const LINE_BREAK = /\r?\n/;

function drainFrames(buffer: string): { payloads: string[]; rest: string } {
  const payloads: string[] = [];
  let rest = buffer;
  let frame = takeSseFrame(rest);
  while (frame) {
    rest = frame.remainder;
    const data = frame.event
      .split(LINE_BREAK)
      .filter((line) => line.startsWith("data:"))
      .map((line) => line.slice(5).trimStart())
      .join("\n");
    if (data) payloads.push(data);
    frame = takeSseFrame(rest);
  }
  return { payloads, rest };
}

function readWithStall(
  reader: ReadableStreamDefaultReader<Uint8Array>,
  onStall: () => void,
  stallMs: number | undefined,
): Promise<ReadableStreamReadResult<Uint8Array>> {
  if (stallMs === undefined) return reader.read();
  const stall = setTimeout(onStall, stallMs);
  return reader.read().finally(() => clearTimeout(stall));
}

/** `stallMs` abandons silent streams (proxies like Cloudflare can buffer SSE); ends without throwing. */
export async function* readSseJsonEvents<T>(
  body: ReadableStream<Uint8Array>,
  stallMs?: number,
): AsyncGenerator<T> {
  const reader = body.getReader();
  const decoder = new TextDecoder();
  // Cancelling resolves the pending read as done, so the generator ends without an error.
  const cancel = () => {
    reader.cancel().catch(() => undefined);
  };
  let buffer = "";
  try {
    while (true) {
      const chunk = await readWithStall(reader, cancel, stallMs);
      if (chunk.done) break;
      const { payloads, rest } = drainFrames(
        buffer + decoder.decode(chunk.value, { stream: true }),
      );
      buffer = rest;
      for (const data of payloads) {
        if (data === "[DONE]") return;
        try {
          yield JSON.parse(data) as T;
        } catch {
          // ignore unparseable frames; [DONE] still ends the loop
        }
      }
    }
  } finally {
    // Release the stream lock now instead of leaking the reader until GC.
    cancel();
  }
}