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.

Studio: stop the streaming prefix checks scanning the whole reply (#9038)

Daniel Hanbf60ff8b2354
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 4d963ace181..9a6618c8ae1 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -466,7 +466,9 @@ function useCoalescedStreamingText(
isStreaming &&
displayed.messageId === messageId &&
text.length >= displayed.text.length &&
- text.startsWith(displayed.text)
+ // Not startsWith, which scans a growing reply. See hasPrefix in
+ // streaming-render-schedule.ts for the measurement.
+ text.slice(0, displayed.text.length) === displayed.text
) {
return displayed.text;
}
diff --git a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
index 2847f12a4d1..96c37928e5b 100644
--- a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
@@ -614,6 +614,25 @@ function normalizeLineEndings(text: string): string {
return text.includes("\r") ? text.replace(/\r\n?/g, "\n") : text;
}
+/**
+ * `a` begins with `b`.
+ *
+ * `String.prototype.startsWith` is the obvious spelling and is far slower here,
+ * because it scans where slicing to the prefix length and comparing lets the
+ * engine reject on length and then compare natively.
+ *
+ * The win is in the PREFIX length, not in how the strings are represented. Swept
+ * on V8: at an 8 character prefix `startsWith` is FASTER (0.4x), at 1,024 it is
+ * 105x slower and at 60,000 it is 250x slower, and a cons receiver behaves the
+ * same as a flat one (250x against 254x). So do not reach for this helper for
+ * short prefixes; it earns its place on a reply-length one.
+ *
+ * Semantically identical: `slice` clamps to the string length, so a `b` longer
+ * than `a` yields a short slice that cannot equal it.
+ */
+export const hasPrefix = (a: string, b: string): boolean =>
+ a.length >= b.length && a.slice(0, b.length) === b;
+
function sharedPrefixLength(left: string, right: string): number {
const limit = Math.min(left.length, right.length);
let index = 0;
@@ -774,7 +793,7 @@ export class IncrementalMarkdownCache {
// one native comparison plus a scan of the tail (about to be re-lexed
// anyway) rather than a scan of the whole reply.
const committedPrefix = this.source.slice(0, this.committedLength);
- const shared = markdown.startsWith(committedPrefix)
+ const shared = hasPrefix(markdown, committedPrefix)
? this.committedLength +
sharedPrefixLength(markdown.slice(this.committedLength), this.tail)
: sharedPrefixLength(markdown, committedPrefix);
@@ -828,7 +847,7 @@ export class IncrementalMarkdownCache {
}
private updateTail(markdown: string): void {
- if (markdown.startsWith(this.source)) {
+ if (hasPrefix(markdown, this.source)) {
this.tail += markdown.slice(this.source.length);
} else if (!this.rewindToRewrite(markdown)) {
if (this.committedBlocks.length > 0) {
@@ -859,7 +878,7 @@ export class IncrementalMarkdownCache {
};
}
- if (this.fullDocumentMode && markdown.startsWith(this.source)) {
+ if (this.fullDocumentMode && hasPrefix(markdown, this.source)) {
this.source = markdown;
return this.renderFullDocument(markdown);
}
diff --git a/studio/frontend/tests/markdown-streaming-scheduling.test.ts b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
index 320cca8fe29..6385f0418e5 100644
--- a/studio/frontend/tests/markdown-streaming-scheduling.test.ts
+++ b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
@@ -133,7 +133,25 @@ test("stream updates are paint-coalesced without a time or length throttle", ()
// A running message can be replaced rather than appended to, as the audio
// path does when it swaps its placeholder for the player, so holding the last
// painted text has to be gated on the new text extending it.
- assert.ok(hook.includes("text.startsWith(displayed.text)"));
+ //
+ // The spelling is pinned, not left open. `startsWith` scans a growing reply,
+ // 74 ms against 1.6 ms over a 60,000 character stream, and the two spellings
+ // are behaviourally identical, so no output test can tell them apart and this
+ // source check is the only thing standing between the hot path and a quiet
+ // revert. Written as `slice || startsWith` it accepted both and passed on the
+ // previous code unchanged, which is to say it measured nothing.
+ assert.ok(
+ hook.includes("text.length >= displayed.text.length"),
+ "the coalescer must reject a shorter replacement on length first",
+ );
+ assert.ok(
+ hook.includes("text.slice(0, displayed.text.length) === displayed.text"),
+ "the coalescer must hold the painted text only when the new text extends it",
+ );
+ assert.ok(
+ !hook.includes("text.startsWith(displayed.text)"),
+ "the coalescer must not scan the reply to decide the new text extends it",
+ );
});
test("streaming reparses only the active Markdown tail", () => {
diff --git a/studio/frontend/tests/streaming-has-prefix.test.ts b/studio/frontend/tests/streaming-has-prefix.test.ts
new file mode 100644
index 00000000000..ea1331dbcf4
--- /dev/null
+++ b/studio/frontend/tests/streaming-has-prefix.test.ts
@@ -0,0 +1,143 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * `hasPrefix` replaces `String.prototype.startsWith` on the streaming hot path
+ * purely for speed, so the only thing worth asserting is that it is the same
+ * function. A behavioural difference here would not show up as a slow render;
+ * it would show up as the incremental cache silently resetting, or failing to
+ * reset when it must, which is invisible until a reply renders wrong.
+ *
+ * Surrogate pairs are included deliberately. `slice` counts UTF-16 code units,
+ * so a prefix boundary can land inside an astral character; the comparison is
+ * still exact, and this pins that rather than leaving it to be re-reasoned.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import { hasPrefix } from "../src/components/assistant-ui/streaming-render-schedule.ts";
+
+const CORPUS = [
+ "",
+ "a",
+ "ab",
+ "abc",
+ "\n",
+ " ",
+ "a\nb\nc",
+ "$5 and \\(x\\)",
+ "```ts\nconst a = 1;\n```",
+ "é", // combining acute
+ "\u{1F600}", // astral, two code units
+ "x\u{1F600}y",
+ "\u{1F600}\u{1F600}",
+ "aaaaaaaaaa",
+ "aaaaaaaaab",
+ // Case, which nothing else here varies: a compare that folded case would
+ // otherwise agree with startsWith on every entry above.
+ "A",
+ "aB",
+ "AAAAAAAAAA",
+];
+
+test("hasPrefix agrees with startsWith on a fixed corpus", () => {
+ for (const a of CORPUS) {
+ for (const b of CORPUS) {
+ assert.equal(
+ hasPrefix(a, b),
+ a.startsWith(b),
+ `disagreed on a=${JSON.stringify(a)} b=${JSON.stringify(b)}`,
+ );
+ }
+ }
+});
+
+test("hasPrefix agrees with startsWith on split points of astral text", () => {
+ // Every cut of a string whose characters straddle code-unit boundaries.
+ const s = "a\u{1F600}b\u{1F601}c";
+ for (let i = 0; i <= s.length; i += 1) {
+ const b = s.slice(0, i);
+ assert.equal(hasPrefix(s, b), s.startsWith(b), `cut at ${i}`);
+ assert.equal(hasPrefix(b, s), b.startsWith(s), `reversed cut at ${i}`);
+ }
+});
+
+test("hasPrefix agrees with startsWith under randomised growth", () => {
+ // mulberry32: a seeded generator whose low bits are usable, unlike the
+ // multiply-and-mask shape whose product exceeds 2^53.
+ let seed = 0x9e3779b9;
+ const rand = () => {
+ seed = (seed + 0x6d2b79f5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ const alphabet = [..."ab\n $\\`", "\u{1F600}", "́"];
+
+ let agreed = 0;
+ let bothTrue = 0;
+ for (let trial = 0; trial < 20_000; trial += 1) {
+ const len = Math.floor(rand() * 12);
+ let a = "";
+ for (let i = 0; i < len; i += 1) {
+ a += alphabet[Math.floor(rand() * alphabet.length)];
+ }
+ // Half the time compare against a true prefix, so the true branch is
+ // actually exercised rather than only the cheap length rejection.
+ const b =
+ rand() < 0.5
+ ? a.slice(0, Math.floor(rand() * (a.length + 1)))
+ : (() => {
+ let x = "";
+ const n = Math.floor(rand() * 12);
+ for (let i = 0; i < n; i += 1) {
+ x += alphabet[Math.floor(rand() * alphabet.length)];
+ }
+ return x;
+ })();
+ const expected = a.startsWith(b);
+ assert.equal(
+ hasPrefix(a, b),
+ expected,
+ `a=${JSON.stringify(a)} b=${JSON.stringify(b)}`,
+ );
+ agreed += 1;
+ if (expected) bothTrue += 1;
+ }
+ assert.equal(agreed, 20_000);
+ // Without this the run could pass by rejecting everything on length.
+ assert.ok(
+ bothTrue > 4_000,
+ `only ${bothTrue} of 20,000 cases were real prefixes; the true branch is barely covered`,
+ );
+});
+
+// `hasPrefix` and `startsWith` return the same answer, so no output test can
+// tell the cache's three growing-reply comparisons apart from the spelling this
+// replaced. Without a source check, reverting them costs nothing and no test
+// notices. The rule is narrower than "never call startsWith": the one call the
+// helper cannot express takes a start position and compares a fixed block, so
+// it does not grow with the reply and is left alone.
+test("the incremental cache tests prefixes without scanning the reply", () => {
+ const source = readFileSync(
+ new URL(
+ "../src/components/assistant-ui/streaming-render-schedule.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const bare = [...source.matchAll(/\.startsWith\(([^)]*)\)/g)].filter(
+ (match) => !match[1].includes(","),
+ );
+ assert.deepEqual(
+ bare.map((match) => match[0]),
+ [],
+ "a one-argument startsWith on this path scans the whole reply; use hasPrefix",
+ );
+ assert.ok(
+ source.split("hasPrefix(").length - 1 >= 3,
+ "hasPrefix should be the spelling every prefix test on this path uses",
+ );
+});