Spaces:
Paused
Paused
File size: 8,092 Bytes
ded72f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | import { describe, expect, it } from "vitest";
import {
MessageUpdateStatus,
MessageUpdateType,
type MessageUpdate,
} from "$lib/types/MessageUpdate";
import { applyStreamingMode, resolveStreamingMode, smoothStreamUpdates } from "./messageUpdates";
async function* fromArray<T>(values: T[]): AsyncGenerator<T> {
for (const value of values) {
yield value;
}
}
async function collect(iter: AsyncGenerator<MessageUpdate>) {
const updates: MessageUpdate[] = [];
for await (const update of iter) {
updates.push(update);
}
return updates;
}
const streamText = (updates: MessageUpdate[]) =>
updates
.filter((u) => u.type === MessageUpdateType.Stream)
.map((u) => u.token)
.join("");
describe("smoothStreamUpdates", () => {
it("merges partial words and preserves final text", async () => {
const source: MessageUpdate[] = [
{ type: MessageUpdateType.Stream, token: "Hel" },
{ type: MessageUpdateType.Stream, token: "lo " },
{ type: MessageUpdateType.Stream, token: "wor" },
{ type: MessageUpdateType.Stream, token: "ld!" },
{ type: MessageUpdateType.Status, status: MessageUpdateStatus.Finished },
];
const updates = await collect(
smoothStreamUpdates(fromArray(source), {
minDelayMs: 0,
maxDelayMs: 0,
_internal: { detectChunk: (buffer) => /\S+\s+/.exec(buffer)?.[0] ?? null },
})
);
const streamedChunks = updates.filter((u) => u.type === MessageUpdateType.Stream);
expect(streamedChunks.map((u) => u.token)).toEqual(["Hello ", "world!"]);
expect(streamText(updates)).toBe("Hello world!");
});
it("flushes buffered stream text before non-stream updates", async () => {
const source: MessageUpdate[] = [
{ type: MessageUpdateType.Stream, token: "hello" },
{ type: MessageUpdateType.Stream, token: " world" },
{ type: MessageUpdateType.Title, title: "done" },
];
const updates = await collect(
smoothStreamUpdates(fromArray(source), { minDelayMs: 0, maxDelayMs: 0 })
);
expect(updates[0]).toMatchObject({ type: MessageUpdateType.Stream });
expect(updates[1]).toMatchObject({ type: MessageUpdateType.Stream });
expect(updates[2]).toEqual({ type: MessageUpdateType.Title, title: "done" });
expect(streamText(updates)).toBe("hello world");
});
it("spreads burst tokens over time", async () => {
const bigToken = "word ".repeat(40); // 200 chars, 40 words
const source: MessageUpdate[] = [{ type: MessageUpdateType.Stream, token: bigToken }];
let nowMs = 0;
const emitTimes: number[] = [];
const iter = smoothStreamUpdates(fromArray(source), {
minDelayMs: 5,
maxDelayMs: 80,
minRateCharsPerMs: 0.3,
_internal: {
now: () => nowMs,
sleep: async (ms: number) => {
nowMs += ms;
},
detectChunk: (buffer) => /\S+\s+/.exec(buffer)?.[0] ?? null,
},
});
for await (const update of iter) {
if (update.type === MessageUpdateType.Stream) {
emitTimes.push(nowMs);
}
}
// Should have multiple emissions
expect(emitTimes.length).toBeGreaterThan(5);
// Gap between first and last emission should be significant (not instant dump)
const totalSpread = (emitTimes.at(-1) ?? 0) - (emitTimes[0] ?? 0);
expect(totalSpread).toBeGreaterThan(100);
});
it("keeps delays within configured bounds", async () => {
const source: MessageUpdate[] = [
{
type: MessageUpdateType.Stream,
token: "one two three four five six seven eight nine ten ",
},
];
const delays: number[] = [];
let nowMs = 0;
await collect(
smoothStreamUpdates(fromArray(source), {
minDelayMs: 5,
maxDelayMs: 80,
minRateCharsPerMs: 0.3,
_internal: {
now: () => nowMs,
sleep: async (ms: number) => {
delays.push(ms);
nowMs += ms;
},
detectChunk: (buffer) => /\S+\s+/.exec(buffer)?.[0] ?? null,
},
})
);
expect(delays.length).toBeGreaterThan(2);
expect(delays.every((d) => d >= 5 && d <= 80)).toBe(true);
// First delay should be >= later delays (rate floor dominates initially)
expect(delays[0]).toBeGreaterThanOrEqual(delays.at(-1) ?? 0);
});
it("handles CJK text correctly", async () => {
const source: MessageUpdate[] = [{ type: MessageUpdateType.Stream, token: "你好,世界!" }];
const updates = await collect(
smoothStreamUpdates(fromArray(source), { minDelayMs: 0, maxDelayMs: 0 })
);
expect(streamText(updates)).toBe("你好,世界!");
});
it("propagates source errors to consumer", async () => {
async function* failingSource(): AsyncGenerator<MessageUpdate> {
yield { type: MessageUpdateType.Stream, token: "hello " };
throw new Error("source failed");
}
await expect(
collect(smoothStreamUpdates(failingSource(), { minDelayMs: 0, maxDelayMs: 0 }))
).rejects.toThrow("source failed");
});
it("propagates source errors even when no full chunk was emitted yet", async () => {
async function* failingSource(): AsyncGenerator<MessageUpdate> {
yield { type: MessageUpdateType.Stream, token: "hel" };
throw new Error("source failed");
}
await expect(
collect(
smoothStreamUpdates(failingSource(), {
minDelayMs: 0,
maxDelayMs: 0,
_internal: { detectChunk: (buffer) => /\S+\s+/.exec(buffer)?.[0] ?? null },
})
)
).rejects.toThrow("source failed");
});
it("drains queued stream chunks before throwing source errors", async () => {
async function* failingSource(): AsyncGenerator<MessageUpdate> {
yield { type: MessageUpdateType.Stream, token: "a " };
yield { type: MessageUpdateType.Stream, token: "b " };
yield { type: MessageUpdateType.Stream, token: "c " };
throw new Error("source failed");
}
const seen: MessageUpdate[] = [];
let seenError: Error | null = null;
try {
for await (const update of smoothStreamUpdates(failingSource(), {
minDelayMs: 0,
maxDelayMs: 0,
_internal: { detectChunk: (buffer) => /\S+\s+/.exec(buffer)?.[0] ?? null },
})) {
seen.push(update);
}
} catch (error) {
seenError = error as Error;
}
expect(streamText(seen)).toBe("a b c ");
expect(seenError?.message).toBe("source failed");
});
it("caps burst tail latency with backlog acceleration", async () => {
const source: MessageUpdate[] = [
{ type: MessageUpdateType.Stream, token: "word ".repeat(500) },
];
let nowMs = 0;
await collect(
smoothStreamUpdates(fromArray(source), {
minDelayMs: 5,
maxDelayMs: 80,
minRateCharsPerMs: 0.3,
maxBufferedMs: 400,
_internal: {
now: () => nowMs,
sleep: async (ms: number) => {
nowMs += ms;
},
detectChunk: (buffer) => /\S+\s+/.exec(buffer)?.[0] ?? null,
},
})
);
expect(nowMs).toBeLessThan(1500);
});
it("skips empty tokens gracefully", async () => {
const source: MessageUpdate[] = [
{ type: MessageUpdateType.Stream, token: "" },
{ type: MessageUpdateType.Stream, token: "hello " },
{ type: MessageUpdateType.Stream, token: "" },
{ type: MessageUpdateType.Stream, token: "world!" },
{ type: MessageUpdateType.Status, status: MessageUpdateStatus.Finished },
];
const updates = await collect(
smoothStreamUpdates(fromArray(source), { minDelayMs: 0, maxDelayMs: 0 })
);
expect(streamText(updates)).toBe("hello world!");
});
});
describe("applyStreamingMode", () => {
it("keeps stream unchanged for raw mode", async () => {
const source: MessageUpdate[] = [
{ type: MessageUpdateType.Stream, token: "Hello" },
{ type: MessageUpdateType.Status, status: MessageUpdateStatus.Finished },
];
const raw = await collect(applyStreamingMode(fromArray(source), "raw"));
expect(raw).toEqual(source);
});
});
describe("resolveStreamingMode", () => {
it("returns explicit streamingMode when set", () => {
expect(resolveStreamingMode({ streamingMode: "raw" })).toBe("raw");
expect(resolveStreamingMode({ streamingMode: "smooth" })).toBe("smooth");
});
it("defaults to smooth when unset", () => {
expect(resolveStreamingMode({})).toBe("smooth");
});
it("maps unsupported legacy values to smooth", () => {
expect(resolveStreamingMode({ streamingMode: "final" })).toBe("smooth");
});
});
|