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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
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 in-flow updates", async () => {
		const source: MessageUpdate[] = [
			{ type: MessageUpdateType.Stream, token: "hello" },
			{ type: MessageUpdateType.Stream, token: " world" },
			{ type: MessageUpdateType.Status, status: MessageUpdateStatus.Finished },
		];

		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.Status,
			status: MessageUpdateStatus.Finished,
		});
		expect(streamText(updates)).toBe("hello world");
	});

	it("passes out-of-band updates through without splitting words", async () => {
		const source: MessageUpdate[] = [
			{ type: MessageUpdateType.Stream, token: "hel" },
			{ type: MessageUpdateType.Title, title: "My conversation" },
			{ type: MessageUpdateType.RouterMetadata, route: "casual", model: "some-model" },
			{ type: MessageUpdateType.Stream, token: "lo" },
			{ type: MessageUpdateType.Status, status: MessageUpdateStatus.Finished },
		];

		const updates = await collect(
			smoothStreamUpdates(fromArray(source), { minDelayMs: 0, maxDelayMs: 0 })
		);

		const chunks = updates.filter((u) => u.type === MessageUpdateType.Stream).map((u) => u.token);
		// Title and router metadata render outside the message text; they must
		// not force "hel" out as its own fragment.
		expect(chunks).toEqual(["hello"]);
		expect(updates.some((u) => u.type === MessageUpdateType.Title)).toBe(true);
		expect(updates.some((u) => u.type === MessageUpdateType.RouterMetadata)).toBe(true);
	});

	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);
	});

	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,
				},
			})
		);

		// Everything queued at t=0 must finish draining by ~maxBufferedMs.
		expect(nowMs).toBeLessThanOrEqual(450);
	});

	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!");
	});

	it("does not split words on keep-alive updates", async () => {
		const source: MessageUpdate[] = [
			{ type: MessageUpdateType.Stream, token: "hel" },
			{ type: MessageUpdateType.Status, status: MessageUpdateStatus.KeepAlive },
			{ type: MessageUpdateType.Stream, token: "lo" },
			{ type: MessageUpdateType.Status, status: MessageUpdateStatus.Finished },
		];

		const updates = await collect(
			smoothStreamUpdates(fromArray(source), { minDelayMs: 0, maxDelayMs: 0 })
		);

		const chunks = updates.filter((u) => u.type === MessageUpdateType.Stream).map((u) => u.token);
		// The keep-alive between the two halves must not flush "hel" on its own.
		expect(chunks).toEqual(["hello"]);
	});

	it("emits CJK text at word-level cadence", async () => {
		const text = "这是一个关于人工智能的长篇讨论,模型逐字输出中文内容。";
		const source: MessageUpdate[] = [{ type: MessageUpdateType.Stream, token: text }];

		const updates = await collect(
			smoothStreamUpdates(fromArray(source), { minDelayMs: 0, maxDelayMs: 0 })
		);

		const chunks = updates.filter((u) => u.type === MessageUpdateType.Stream);
		// CJK has no spaces; words must still stream out incrementally rather
		// than waiting for punctuation or end of stream.
		expect(chunks.length).toBeGreaterThan(5);
		expect(streamText(updates)).toBe(text);
	});

	it("keeps emitting through boundary-less text (hashes, base64)", async () => {
		const blob = "QmFzZTY0RGF0YQ".repeat(30); // 420 chars, no word boundaries
		const tokens = blob.match(/.{1,60}/g) ?? [];
		const source: MessageUpdate[] = tokens.map((token) => ({
			type: MessageUpdateType.Stream,
			token,
		}));

		const updates = await collect(
			smoothStreamUpdates(fromArray(source), { minDelayMs: 0, maxDelayMs: 0 })
		);

		const chunks = updates.filter((u) => u.type === MessageUpdateType.Stream);
		// Without the pending-buffer cap this would be held until stream end
		// and dumped as a single chunk.
		expect(chunks.length).toBeGreaterThan(3);
		expect(streamText(updates)).toBe(blob);
	});

	it("preserves long text across reattach-style backlogs and bursts", async () => {
		const text =
			Array.from(
				{ length: 2_500 },
				(_, i) =>
					`passage-${i} over the murderous reefs stretching westward Some keepers brought dogs `
			).join("") + "the end";
		const sizes = [4_096, 1, 127, 8_192, 7, 509, 2_048, 3, 997];
		const events: TimedEvent[] = [];
		let offset = 0;
		let sizeIndex = 0;
		let burstChars = 0;
		let at = 0;

		while (offset < text.length) {
			const size = sizes[sizeIndex++ % sizes.length];
			const token = text.slice(offset, offset + size);
			events.push({
				at,
				update: { type: MessageUpdateType.Stream, token },
			});
			offset += token.length;
			burstChars += token.length;
			if (burstChars >= 8_000) {
				at += 250;
				burstChars = 0;
			}
		}

		const clock = createVirtualClock();
		const emitted = await collectTimed(events, clock);

		expect(text.length).toBeGreaterThan(20_000);
		expect(emitted.map((event) => event.token).join("")).toBe(text);
	});

	it("closes the source iterator when the consumer stops early", async () => {
		let closed = false;
		async function* source(): AsyncGenerator<MessageUpdate> {
			try {
				yield { type: MessageUpdateType.Stream, token: "a " };
				yield { type: MessageUpdateType.Stream, token: "b " };
				yield { type: MessageUpdateType.Stream, token: "c " };
			} finally {
				closed = true;
			}
		}

		const iter = smoothStreamUpdates(source(), { minDelayMs: 0, maxDelayMs: 0 });
		await iter.next();
		await iter.return(undefined);
		await new Promise((resolve) => setImmediate(resolve));

		expect(closed).toBe(true);
	});
});

/**
 * Deterministic virtual clock: drives the smoother and a timed source from the
 * same simulated timeline so emission timing can be asserted exactly.
 */
function createVirtualClock() {
	let nowMs = 0;
	let seq = 0;
	const timers: Array<{ at: number; seq: number; resolve: () => void }> = [];
	const sleep = (ms: number) =>
		new Promise<void>((resolve) => {
			timers.push({ at: nowMs + Math.max(0, ms), seq: seq++, resolve });
		});
	const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
	const run = async <T>(promise: Promise<T>): Promise<T> => {
		let settled = false;
		promise.then(
			() => (settled = true),
			() => (settled = true)
		);
		let idleTicks = 0;
		while (!settled) {
			await tick();
			if (settled) break;
			if (timers.length === 0) {
				if (++idleTicks > 20) throw new Error(`virtual clock stalled at t=${nowMs}ms`);
				continue;
			}
			idleTicks = 0;
			timers.sort((a, b) => a.at - b.at || a.seq - b.seq);
			const timer = timers.shift();
			if (!timer) continue;
			nowMs = Math.max(nowMs, timer.at);
			timer.resolve();
		}
		return promise;
	};
	return { now: () => nowMs, sleep, run };
}

type Clock = ReturnType<typeof createVirtualClock>;
type TimedEvent = { at: number; update: MessageUpdate };

async function* timedSource(events: TimedEvent[], clock: Clock): AsyncGenerator<MessageUpdate> {
	for (const event of events) {
		const wait = event.at - clock.now();
		if (wait > 0) await clock.sleep(wait);
		yield event.update;
	}
}

async function collectTimed(events: TimedEvent[], clock: Clock) {
	const emitted: Array<{ at: number; token: string }> = [];
	await clock.run(
		(async () => {
			const iter = smoothStreamUpdates(timedSource(events, clock), {
				_internal: { now: clock.now, sleep: clock.sleep },
			});
			for await (const update of iter) {
				if (update.type === MessageUpdateType.Stream) {
					emitted.push({ at: clock.now(), token: update.token });
				}
			}
		})()
	);
	return emitted;
}

describe("smoothStreamUpdates timing", () => {
	const word = (at: number, token = "lorem "): TimedEvent => ({
		at,
		update: { type: MessageUpdateType.Stream, token },
	});

	it("shows the first word the moment it arrives", async () => {
		const clock = createVirtualClock();
		const emitted = await collectTimed([word(0, "Hello "), word(30, "world ")], clock);

		expect(emitted[0]).toMatchObject({ at: 0, token: "Hello " });
	});

	it("adds no latency to streams slower than the pacing floor", async () => {
		const clock = createVirtualClock();
		const events = Array.from({ length: 10 }, (_, i) => word(i * 100));
		const emitted = await collectTimed(events, clock);

		// Each word renders exactly when it arrives; pacing reservations
		// (~20ms per word at the floor rate) are absorbed by the 100ms gaps.
		expect(emitted.map((e) => e.at)).toEqual(events.map((e) => e.at));
	});

	it("spreads a large single burst evenly until the buffered deadline", async () => {
		const clock = createVirtualClock();
		const emitted = await collectTimed([word(0, "lorem ".repeat(300))], clock);

		expect(emitted.length).toBe(300);
		// Drains close to (and never far past) the 400ms default budget.
		const last = emitted.at(-1)?.at ?? 0;
		expect(last).toBeGreaterThan(300);
		expect(last).toBeLessThanOrEqual(450);
		// Linear spread: no large rendering gap while a backlog exists.
		let maxGap = 0;
		for (let i = 1; i < emitted.length; i++) {
			maxGap = Math.max(maxGap, emitted[i].at - emitted[i - 1].at);
		}
		expect(maxGap).toBeLessThanOrEqual(25);
	});

	it("never holds a chunk more than maxBufferedMs past its arrival", async () => {
		const clock = createVirtualClock();
		// Fast provider: 60 chars every 10ms (~6000 cps) for 300ms.
		const events = Array.from({ length: 30 }, (_, i) => word(i * 10, "lorem ".repeat(10)));

		const arrivals: Array<{ endIndex: number; at: number }> = [];
		let total = 0;
		for (const e of events) {
			if (e.update.type === MessageUpdateType.Stream) {
				total += e.update.token.length;
				arrivals.push({ endIndex: total, at: e.at });
			}
		}
		const arrivedAt = (charIndex: number) => arrivals.find((a) => charIndex < a.endIndex)?.at ?? 0;

		const emitted = await collectTimed(events, clock);
		let emittedChars = 0;
		for (const e of emitted) {
			const lastChar = emittedChars + e.token.length - 1;
			expect(e.at - arrivedAt(lastChar)).toBeLessThanOrEqual(410);
			emittedChars += e.token.length;
		}
		expect(emittedChars).toBe(total);
	});

	it("recovers promptly after a mid-stream stall", async () => {
		const clock = createVirtualClock();
		const events = [
			...Array.from({ length: 5 }, (_, i) => word(i * 30)),
			// 2s stall, then the stream resumes.
			...Array.from({ length: 5 }, (_, i) => word(2000 + i * 30)),
		];
		const emitted = await collectTimed(events, clock);

		const firstAfterStall = emitted.find((e) => e.at >= 2000);
		expect(firstAfterStall?.at).toBe(2000);
		expect(emitted.length).toBe(10);
	});
});

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");
	});
});