Skip to content

Open-source, local-first AI agent for real work.

5.7 KB
Raw Blame
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { pruneReveals, STREAMING_FADE_MS, type StreamingReveal } from "./streaming-fade";
import { DEFAULT_RATE_PER_MS, planReveal, REVEAL_TICK_MS, STREAMING_STALL_FLUSH_MS } from "./streaming-reveal";

function clearTimeoutRef(ref: { current: number | null }): void {
	if (ref.current !== null) {
		window.clearTimeout(ref.current);
		ref.current = null;
	}
}

/** 到达速率的采样窗口:只看最近这么久。 */
const RATE_WINDOW_MS = 1500;

interface ArrivalSample {
	readonly at: number;
	readonly length: number;
}

/** 最近窗口内的到达速率(字符/毫秒);样本不够时用默认值。 */
function estimateRate(samples: readonly ArrivalSample[], now: number): number {
	const first = samples.find((sample) => now - sample.at <= RATE_WINDOW_MS) ?? samples[0];
	const last = samples.at(-1);
	if (!first || !last || last.at - first.at < 50 || last.length <= first.length) return DEFAULT_RATE_PER_MS;
	return (last.length - first.length) / (last.at - first.at);
}

export interface StreamingDisplay {
	readonly text: string;
	/** 仍在淡入期的放出区间,供尾块给新文字挂淡入(见 streaming-fade)。 */
	readonly reveals: readonly StreamingReveal[];
}

const NO_REVEALS: readonly StreamingReveal[] = [];

/**
 * 流式尾块:把显示文本匀速追向宿主文本(节奏见 streaming-reveal),并记下每次放出的区间与时刻,
 * 让新文字平滑淡入(streaming-fade)。
 * 放出由 `text` 变化(宿主每 100ms 一次的增量刷新)驱动,在布局效果里同步更新,与那次渲染落在同一帧;
 * 没有新文本时由兜底 tick 收尾。尾部未写完的词、未闭合的行内语法先扣着;流结束后一次放完。
 *
 * 从未作为尾块流式过的实例(历史消息、产品故事等由宿主自己驱动逐字的场景)直接镜像 `text`,不淡入。
 */
export function useStreamingDisplayText(text: string, active: boolean): StreamingDisplay {
	const [display, setDisplay] = useState<StreamingDisplay>(() => ({ text: active ? "" : text, reveals: NO_REVEALS }));
	const displayRef = useRef(active ? "" : text);
	const targetRef = useRef(text);
	const activeRef = useRef(active);
	const streamedRef = useRef(active);
	const samplesRef = useRef<ArrivalSample[]>([]);
	/** 显示文本上次实际推进的时间:扣留、等词写完期间预算按它累计,闭合后能一次放出整段。 */
	const lastAdvanceAtRef = useRef(0);
	const lastArrivalAtRef = useRef(0);
	/** 扣留开始的时间;null 表示当前没有扣留。 */
	const heldSinceRef = useRef<number | null>(null);
	const tickTimerRef = useRef<number | null>(null);
	/** 最后一段淡入结束后撤掉包裹,让尾块回到纯文本节点。 */
	const fadeClearTimerRef = useRef<number | null>(null);

	const reveal = useCallback(function reveal(): void {
		clearTimeoutRef(tickTimerRef);
		const now = Date.now();
		const target = targetRef.current;
		const shown = displayRef.current.length;
		const final = !activeRef.current;
		const stalled = !final && now - lastArrivalAtRef.current >= STREAMING_STALL_FLUSH_MS;
		const step = planReveal({
			text: target,
			revealed: shown,
			final,
			ratePerMs: estimateRate(samplesRef.current, now),
			elapsedMs: lastAdvanceAtRef.current ? now - lastAdvanceAtRef.current : REVEAL_TICK_MS,
			stalled,
			heldMs: heldSinceRef.current === null ? 0 : now - heldSinceRef.current,
		});
		if (step?.held) heldSinceRef.current ??= now;
		else heldSinceRef.current = null;
		if (step && step.end > shown) {
			const next = target.slice(0, step.end);
			displayRef.current = next;
			const at = performance.now();
			setDisplay((current) => ({
				text: next,
				reveals: [...pruneReveals(current.reveals, at), { start: shown, end: next.length, at }],
			}));
			clearTimeoutRef(fadeClearTimerRef);
			fadeClearTimerRef.current = window.setTimeout(() => {
				fadeClearTimerRef.current = null;
				// 计时从最后一次放出算起,到点时所有记录都已淡入完。
				setDisplay((current) =>
					current.reveals.length === 0 ? current : { text: current.text, reveals: NO_REVEALS },
				);
			}, STREAMING_FADE_MS);
			lastAdvanceAtRef.current = now;
		}
		if (displayRef.current.length >= target.length) lastAdvanceAtRef.current = now;
		if (displayRef.current.length < target.length) {
			tickTimerRef.current = window.setTimeout(reveal, REVEAL_TICK_MS);
		} else if (final) {
			// 流已结束且已放完:之后的文本变化直接镜像。
			streamedRef.current = false;
		}
	}, []);

	useEffect(
		() => () => {
			clearTimeoutRef(tickTimerRef);
			clearTimeoutRef(fadeClearTimerRef);
		},
		[],
	);

	// 用布局效果:放出后的 setState 会在浏览器绘制前同步重渲染,与宿主那次增量刷新落在同一帧。
	useLayoutEffect(() => {
		const textChanged = targetRef.current !== text;
		targetRef.current = text;
		activeRef.current = active;
		if (active) streamedRef.current = true;

		const shown = displayRef.current;
		if (!streamedRef.current || !text.startsWith(shown)) {
			// 从未流式过,或宿主改写了已显示内容(不是追加):直接对齐,不做节奏。
			clearTimeoutRef(tickTimerRef);
			clearTimeoutRef(fadeClearTimerRef);
			samplesRef.current = [];
			heldSinceRef.current = null;
			displayRef.current = text;
			setDisplay({ text, reveals: NO_REVEALS });
			streamedRef.current = active;
			return;
		}

		const now = Date.now();
		if (textChanged || lastArrivalAtRef.current === 0) {
			lastArrivalAtRef.current = now;
			const samples = samplesRef.current.filter((sample) => now - sample.at <= RATE_WINDOW_MS);
			samples.push({ at: now, length: text.length });
			samplesRef.current = samples;
		}
		reveal();
	}, [text, active, reveal]);

	return display;
}