Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

revert: undo streaming fade order (#3204)

MagicLizi469681c35728
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index 7e09dcddd6..7308a7fa1c 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -11,7 +11,7 @@
* into Markdown image nodes before HTML filtering.
*/
-import { createElement, memo, useCallback, useEffect, useLayoutEffect, useRef, useState, useMemo, isValidElement, type AnimationEvent as ReactAnimationEvent, type HTMLAttributes, type ReactNode } from 'react';
+import { createElement, memo, useCallback, useEffect, useRef, useState, useMemo, isValidElement, type AnimationEvent as ReactAnimationEvent, type HTMLAttributes, type ReactNode } from 'react';
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkCjkFriendly from 'remark-cjk-friendly';
@@ -33,8 +33,6 @@ import remarkSessionLinks from './remarkSessionLinks';
import { rehypeMathBlockMarker } from './rehypeMathBlockMarker';
import { FENCED_CODE_PROP, rehypeFencedCodeMarker } from './rehypeFencedCodeMarker';
import {
- commitWordFadeCandidate,
- createWordFadeCandidate,
getOrCreateWordFadeState,
markSettledFromAnimationEnd,
releaseWordFadeState,
@@ -431,9 +429,7 @@ function useStreamingThrottle(value: string, enabled: boolean, intervalMs = 100)
};
}, []);
- // useEffect 在 paint 后才执行。流式结束时本次 render 直接返回最新原文,
- // effect 只负责同步内部 state,供未来可能的新流式周期使用。
- return enabled ? throttled : value;
+ return throttled;
}
/**
@@ -1642,10 +1638,10 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
// so the throttle is fully bypassed — same behavior as before.
const throttledContent = useStreamingThrottle(content, isStreaming);
// 流式逐词淡入(rehypeStreamWordFade,§14.4 第五个 sanctioned motion class):
- // 仅 isStreaming + 非 reduced-motion 时把插件挂到 rehype 链尾。committed state
- // 按消息身份跨 parse / remount 保留;本次 render 只写 candidate,layout effect
- // 确认 DOM 已提交后才落状态,避免被放弃的并发 render 提前推进 key / 时间线。
- // 根节点监听 animationend 把播完的段落袋(settled),下一次 parse 还原纯文本。
+ // 仅 isStreaming + 非 reduced-motion 时把插件挂到 rehype 链尾。state 按渲染器
+ // 实例持有(useMemo 键 isStreaming):流式期间跨 parse tick 记住每个词的 delay
+ // 保证不重播;根节点监听冒泡的 animationend 把播完的词落袋(settled),下一次
+ // parse 直接还原纯文本 —— 结构性 remount 也无从重播(双保险,详见插件头注释)。
// isStreaming 翻 false 时整段回落到模块级常量 REHYPE_PLUGINS —— 终版渲染无
// 任何 span 包装,插件、state 与监听一起被回收,静态路径零开销。
// 用户开关(Settings → 个性化 → 流式动效,默认开)与 reduced-motion 取 AND:
@@ -1653,13 +1649,23 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
const reducedMotion = useReducedMotion();
const streamFadeEnabled = useStreamFadeEnabled();
const streamFade = isStreaming && !reducedMotion && streamFadeEnabled;
- const wordFadeState = useMemo(() => {
+ const wordFade = useMemo(() => {
if (!streamFade) return null;
- return getOrCreateWordFadeState(streamFadeKey);
+ const state = getOrCreateWordFadeState(streamFadeKey);
+ return {
+ state,
+ plugins: [...REHYPE_PLUGINS, [rehypeStreamWordFade, state]] as PluggableList,
+ };
}, [streamFade, streamFadeKey]);
useEffect(() => {
if (!isStreaming) releaseWordFadeState(streamFadeKey);
}, [isStreaming, streamFadeKey]);
+ const rehypePlugins = wordFade?.plugins ?? REHYPE_PLUGINS;
+ const handleWordFadeAnimationEnd = useMemo(() => {
+ if (!wordFade) return undefined;
+ return (event: ReactAnimationEvent<HTMLDivElement>) =>
+ markSettledFromAnimationEnd(wordFade.state, event.nativeEvent);
+ }, [wordFade]);
// LaTeX 定界符归一化(`\(...\)` / `\[...\]` → `$...$` / `$$...$$`)。
// emitSourceLines(TextLightbox 行锚点 doc 模式,依赖 data-source-line 与
// 源文件行号一致)时走保行数模式:单行 inline 照常转换(同行替换不改行
@@ -1677,26 +1683,6 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
() => normalizeMathDelimiters(repairedContent, { preserveLineCount: emitSourceLines }),
[repairedContent, emitSourceLines],
);
- const wordFade = useMemo(() => {
- if (!wordFadeState) return null;
- const candidate = createWordFadeCandidate(wordFadeState);
- return {
- candidate,
- plugins: [...REHYPE_PLUGINS, [rehypeStreamWordFade, candidate]] as PluggableList,
- };
- // animationend 不触发 React state;即使正文没变,其它 render 也要克隆最新 settled。
- }, [wordFadeState, renderedContent, wordFadeState?.settled.size]);
- useLayoutEffect(() => {
- if (wordFadeState && wordFade) {
- commitWordFadeCandidate(wordFadeState, wordFade.candidate);
- }
- }, [wordFadeState, wordFade]);
- const rehypePlugins = wordFade?.plugins ?? REHYPE_PLUGINS;
- const handleWordFadeAnimationEnd = useMemo(() => {
- if (!wordFadeState) return undefined;
- return (event: ReactAnimationEvent<HTMLDivElement>) =>
- markSettledFromAnimationEnd(wordFadeState, event.nativeEvent);
- }, [wordFadeState]);
const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
// 远程入方向:远程会话里 markdown 的图片/音频 URL 指向远端机器,按来源改写到
// cindy-remote-media://(device 经 OSS 中转、ssh 经 file-service 落盘缓存)。本地
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/rehypeStreamWordFade.test.ts b/apps/desktop/src/renderer/components/chat/__tests__/rehypeStreamWordFade.test.ts
index 29808d9891..22f84a1ba6 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/rehypeStreamWordFade.test.ts
+++ b/apps/desktop/src/renderer/components/chat/__tests__/rehypeStreamWordFade.test.ts
@@ -1,9 +1,9 @@
/**
* rehypeStreamWordFade.test.ts
* ---------------------------------------------------------------------------
- * 流式分段淡入插件的行为测试:切词、零 stagger、稳定 key(不重播)、结构
- * 变化下的 key 稳定性、render candidate 提交、inline-code 原子淡入、
- * pre/KaTeX 跳过,以及 CSS 侧动画本体的静态回归。
+ * 流式逐词淡入插件的行为测试:切词、稳定 key 与 delay 分配(不重播)、结构
+ * 变化下的 key 稳定性(序号漂移回归)、settled 落袋、背压压缩、code/KaTeX
+ * 跳过,以及 CSS 侧动画本体的静态回归。
*/
import { readFileSync } from 'node:fs';
@@ -13,8 +13,6 @@ import type { Element, Root, Text } from 'hast';
import {
_resetWordFadeStateCacheForTests,
- commitWordFadeCandidate,
- createWordFadeCandidate,
createWordFadeState,
getOrCreateWordFadeState,
markSettledFromAnimationEnd,
@@ -32,11 +30,7 @@ function textNode(value: string): Text {
return { type: 'text', value };
}
-function el(
- tagName: string,
- children: Element['children'],
- properties: Element['properties'] = {},
-): Element {
+function el(tagName: string, children: Element['children'], properties: Element['properties'] = {}): Element {
return { type: 'element', tagName, properties, children };
}
@@ -51,26 +45,18 @@ function run(tree: Root, state: WordFadeState, nowMs = 0): Root {
return tree;
}
-function nodeText(node: Root | Element): string {
- let out = '';
- for (const child of node.children) {
- if (child.type === 'text') out += child.value;
- else if (child.type === 'element') out += nodeText(child);
- }
- return out;
-}
-
-/** 收集树里所有 stream-word span 的 (text, delay, key)。inline code 取整体文本。 */
+/** 收集树里所有 stream-word span 的 (text, delay, key)。 */
function collectWords(node: Root | Element): { text: string; delay: number; key: string }[] {
const out: { text: string; delay: number; key: string }[] = [];
for (const child of node.children) {
if (child.type !== 'element') continue;
const cls = child.properties?.className;
if (Array.isArray(cls) && cls.includes('stream-word')) {
+ const t = child.children[0];
const style = String(child.properties?.style ?? '');
const m = /--wf-delay:(-?\d+)ms/.exec(style);
out.push({
- text: nodeText(child),
+ text: t?.type === 'text' ? t.value : '',
delay: m ? Number(m[1]) : NaN,
key: String(child.properties?.dataWfKey ?? ''),
});
@@ -124,13 +110,13 @@ describe('rehypeStreamWordFade', () => {
expect(getOrCreateWordFadeState(cacheKey)).not.toBe(active);
});
- it('普通聊天零 stagger:同 tick 新词全部从 0ms 开始淡入', () => {
+ it('文本节点被切成带 --wf-delay 的 stream-word span,首词 0ms 起、24ms/词递进', () => {
const state = createWordFadeState();
const tree = root(el('p', [textNode('one two three')]));
run(tree, state);
const words = collectWords(tree);
expect(words.map((w) => w.text)).toEqual(['one ', 'two ', 'three']);
- expect(words.map((w) => w.delay)).toEqual([0, 0, 0]);
+ expect(words.map((w) => w.delay)).toEqual([0, 24, 48]);
});
it('同一 state 重跑(流式 re-parse)已见词拿回同一 key,发剩余(负)delay 续播', () => {
@@ -139,7 +125,7 @@ describe('rehypeStreamWordFade', () => {
run(tree1, state);
const keys1 = collectWords(tree1).map((w) => w.key);
- // 下一个 tick(100ms 后):全文重建 + 新词到达。
+ // 下一个 tick(100ms 后):全文重建 + 新词到达,队列尾(48ms)已落到过去。
const tree2 = root(el('p', [textNode('one two three four')]));
run(tree2, state, 100);
const words = collectWords(tree2);
@@ -148,29 +134,32 @@ describe('rehypeStreamWordFade', () => {
expect(words[0].key).toBe(keys1[0]);
expect(words[1].key).toBe(keys1[1]);
expect(words[0].delay).toBe(-100);
- expect(words[1].delay).toBe(-100);
- // 所有新词都从本 tick 的 0 起播,不互相排队。
+ expect(words[1].delay).toBe(-76);
+ // 新词从本 tick 的 0 起接着排。
expect(words[2].delay).toBe(0);
- expect(words[3].delay).toBe(0);
+ expect(words[3].delay).toBe(24);
});
- it('跨 tick 没有历史积压:后到的新词仍立即开始', () => {
+ it('timeline 跨 tick 连续:队列尾在未来时后到的词接着排,不插队', () => {
const state = createWordFadeState();
+ // tick 1(t=0):4 词排到 96ms(尾部)。
run(root(el('p', [textNode('a b c d')])), state);
+ // tick 2(t=50):队列尾 96ms 还在未来,新词从 96-50=46ms 接着排。
const tree2 = root(el('p', [textNode('a b c d e f')]));
run(tree2, state, 50);
const words = collectWords(tree2);
- expect(words.slice(0, 4).map((word) => word.delay)).toEqual([-50, -50, -50, -50]);
- expect(words.slice(4).map((word) => word.delay)).toEqual([0, 0]);
+ expect(words[4].delay).toBe(46);
+ expect(words[5].delay).toBe(70);
});
- it('卡顿后突发的大段文字也整批立即开始,不产生新的可见积压', () => {
+ it('卡顿后突发:队列已排空则第一词立即开始,整段连贯波浪推进', () => {
const state = createWordFadeState();
run(root(el('p', [textNode('a b')])), state);
+ // 卡顿 5 秒后一大坨到达:尾部(48ms)远落在过去,从 0 重新起排。
const tree2 = root(el('p', [textNode('a b x y z')]));
run(tree2, state, 5000);
const words = collectWords(tree2);
- expect(words.slice(2).map((w) => w.delay)).toEqual([0, 0, 0]);
+ expect(words.slice(2).map((w) => w.delay)).toEqual([0, 24, 48]);
});
it('chunk 边界半个词长成整词:前缀延续复用同一 key', () => {
@@ -224,91 +213,75 @@ describe('rehypeStreamWordFade', () => {
expect(words2[0].key).toBe(keys1[0]);
});
- it('超大 tick 也不把尾部排到未来', () => {
+ it('自适应背压:预算富余时步长恒为 24ms 上限(慢速输出与 Codex 观感一致)', () => {
const state = createWordFadeState();
- const many = Array.from({ length: 500 }, (_, i) => `w${i}`).join(' ');
+ // 10 词:320/10=32ms ≥ 24ms 上限,不压缩,全程 24ms 步进。
+ const many = Array.from({ length: 10 }, (_, i) => `w${i}`).join(' ');
const tree = root(el('p', [textNode(many)]));
run(tree, state);
const delays = collectWords(tree).map((w) => w.delay);
- expect(delays).toHaveLength(500);
- expect(new Set(delays)).toEqual(new Set([0]));
+ expect(delays[0]).toBe(0);
+ expect(delays[1]).toBe(24);
+ expect(delays[9]).toBe(216);
});
- it('被放弃的 render candidate 不污染 committed key 状态', () => {
- const committed = createWordFadeState();
- const abandoned = createWordFadeCandidate(committed);
- run(root(el('p', [textNode('abandoned render')])), abandoned, 10);
-
- expect(committed.nextId).toBe(0);
- expect(committed.previous).toEqual([]);
- expect(committed.startAtByKey.size).toBe(0);
-
- const mounted = createWordFadeCandidate(committed);
- const tree = root(el('p', [textNode('mounted render')]));
- run(tree, mounted, 20);
- expect(collectWords(tree)[0].key).toBe('wf-0');
+ it('自适应背压:大 tick 步长按预算压缩,超前量封顶 MAX_LEAD_MS(与模型吐词速率无关)', () => {
+ const state = createWordFadeState();
+ // 500 词一次性到达(超快模型):步长压到 320/500=0.64ms,总积压 ≤320ms。
+ const many = Array.from({ length: 500 }, (_, i) => `w${i}`).join(' ');
+ const tree = root(el('p', [textNode(many)]));
+ run(tree, state);
+ const delays = collectWords(tree).map((w) => w.delay);
+ expect(Math.max(...delays)).toBeLessThanOrEqual(320);
+ // 仍保持递增波浪(不是整块同帧蹦出)。
+ expect(delays[499]).toBeGreaterThan(delays[250]);
+ // 下一 tick(t=320,积压已消化)新词从 0 接着排,不被历史积压顶到未来。
+ const tree2 = root(el('p', [textNode(`${many} fresh`)]));
+ run(tree2, state, 320);
+ const words2 = collectWords(tree2);
+ expect(words2[500].text).toBe('fresh');
+ expect(words2[500].delay).toBeLessThanOrEqual(24);
+ // 慢速恢复后(下一 tick 词少)步长回到 24ms:fresh2 在 fresh 之后 24ms。
+ const tree3 = root(el('p', [textNode(`${many} fresh fresh2`)]));
+ run(tree3, state, 320);
+ const words3 = collectWords(tree3);
+ expect(words3[501].delay - words3[500].delay).toBe(24);
});
- it('layout commit 发布 candidate,并保留提交间隙到达的 settled 事件', () => {
- const committed = createWordFadeState();
- const candidate = createWordFadeCandidate(committed);
- const tree = root(el('p', [textNode('one two')]));
- run(tree, candidate, 0);
- const keys = collectWords(tree).map((word) => word.key);
-
- committed.settled.add('older-frame');
- commitWordFadeCandidate(committed, candidate);
-
- expect(committed.previous.map((segment) => segment.key)).toEqual(keys);
- expect(committed.startAtByKey.size).toBe(2);
- expect(committed.settled.has('older-frame')).toBe(true);
+ it('持续快速到达:每 tick 预算重算,积压始终收敛不发散', () => {
+ const state = createWordFadeState();
+ // 模拟 300 tok/s:每 100ms 到达 30 词,连续 10 tick。
+ let text = '';
+ for (let tick = 0; tick < 10; tick++) {
+ text += (text ? ' ' : '') + Array.from({ length: 30 }, (_, i) => `t${tick}w${i}`).join(' ');
+ const tree = root(el('p', [textNode(text)]));
+ run(tree, state, tick * 100);
+ const nowMs = tick * 100;
+ // 不变量:排程尾部超前 now 永远不超过 MAX_LEAD_MS + 一个步长。
+ expect(state.nextStartAtMs - nowMs).toBeLessThanOrEqual(320 + 24);
+ // 感知不变量:本 tick 到达的词,可见时刻落后到达 < 0.5s(预算+动画)。
+ const delays = collectWords(tree).map((w) => w.delay);
+ expect(Math.max(...delays)).toBeLessThanOrEqual(320);
+ }
});
- it('截图回归:前文与后到 inline code 同时开始淡入,code 不再抢先显示', () => {
+ it('code / pre 子树跳过(路径 chip 与代码块保持整体形态)', () => {
const state = createWordFadeState();
- const code = el('code', [textNode('meta.Disabled')]);
+ const code = el('code', [textNode('src/foo bar.ts')]);
const pre = el('pre', [el('code', [textNode('const a = 1')])]);
- const paragraph = el('p', [textNode('看 line 241 上下文和 line 145 '), code]);
- const tree = root(paragraph, pre);
+ const tree = root(el('p', [code]), pre);
run(tree, state);
- const segments = collectWords(tree);
- const codeSegment = paragraph.children.at(-1) as Element;
-
- expect(segments.at(-1)?.text).toBe('meta.Disabled');
- expect(segments.every((segment) => segment.delay === 0)).toBe(true);
- expect(codeSegment.tagName).toBe('span');
- expect(codeSegment.properties?.className).toContain('stream-word');
- expect(codeSegment.children).toEqual([code]);
- // fenced code block 仍保持整体,不进入流式淡入。
- expect((pre.children[0] as Element).tagName).toBe('code');
- expect((pre.children[0] as Element).properties?.className).toBeUndefined();
- });
-
- it('inline code 作为带类型的原子段复用稳定 key,不与同文本正文串 key', () => {
- const state = createWordFadeState();
- const tree1 = root(el('p', [textNode('same '), el('code', [textNode('same')])]));
- run(tree1, state, 0);
- const first = collectWords(tree1);
-
- const tree2 = root(
- el('p', [textNode('same '), el('code', [textNode('same')]), textNode(' tail')]),
- );
- run(tree2, state, 100);
- const second = collectWords(tree2);
-
- expect(first[0].key).not.toBe(first[1].key);
- expect(second[0].key).toBe(first[0].key);
- expect(second[1].key).toBe(first[1].key);
- expect(second[1].delay).toBe(-100);
+ expect(collectWords(tree)).toEqual([]);
+ expect((code.children[0] as Text).value).toBe('src/foo bar.ts');
});
- it('表格格内文字照常分段淡入,结构(table/tr/td)不打任何动画标', () => {
+ it('表格格内文字照常逐词淡入,结构(table/tr/td)不打任何动画标', () => {
const state = createWordFadeState();
const td = el('td', [textNode('早晚 跑步 最佳')]);
const tr = el('tr', [td]);
const tree = root(el('table', [el('tbody', [tr])]));
run(tree, state);
- // Codex 模型:结构即时出现,文字与正文共用同一淡入时机。
+ // Codex 模型:结构即时出现,文字与正文共用同一条 timeline 逐词浮现。
expect(collectWords(tree).map((w) => w.text)).toEqual(['早晚 ', '跑步 ', '最佳']);
expect(tr.properties?.dataStreamBlock).toBeUndefined();
expect(tr.properties?.dataStreamMarker).toBeUndefined();
@@ -323,11 +296,11 @@ describe('rehypeStreamWordFade', () => {
run(tree, state);
const words = collectWords(tree);
expect(words.map((w) => w.text)).toEqual(['alpha ', 'beta', 'quoted']);
- // 圆点与 li 内第一个段共 key 共 delay(同帧出现,不额外占段位)。
+ // 圆点与 li 内第一个词共 key 共 delay(同帧出现,不占队列位)。
expect(li.properties?.dataStreamMarker).toBe(true);
expect(li.properties?.dataWfKey).toBe(words[0].key);
expect(String(li.properties?.style)).toContain(`--wf-delay:${words[0].delay}ms`);
- // 块结构不淡入;动效对象只有文本词、inline-code 原子和圆点。
+ // 结构元素不淡入(Codex 模型:只有词和圆点两类动效对象)。
expect(hr.properties?.dataStreamMarker).toBeUndefined();
expect(quote.properties?.dataStreamMarker).toBeUndefined();
// 打标不覆盖已有属性。
@@ -337,13 +310,15 @@ describe('rehypeStreamWordFade', () => {
expect(li2.properties?.dataStreamMarker).toBe(true);
});
- it('空 li 立即淡入,文字到达后切到首段 key 不重播', () => {
+ it('空 li(结构刚长出、文字未到)借队列尾 delay,文字到达后切到词 key 不重播', () => {
const state = createWordFadeState();
+ // tick 1:前文 3 个词把队列推到 72ms,空 li 同时出现。
const li = el('li', []);
run(root(el('p', [textNode('one two three')]), el('ul', [li])), state, 0);
expect(li.properties?.dataStreamMarker).toBe(true);
expect(li.properties?.dataWfKey).toBeUndefined();
- expect(String(li.properties?.style)).toContain('--wf-delay:0ms');
+ // 借队列尾部当前值(3 词 × 24ms),且不推进队列。
+ expect(String(li.properties?.style)).toContain('--wf-delay:72ms');
// tick 2:文字到达,圆点挂到第一个词的 key/delay 上。
const li2 = el('li', [textNode('four')]);
run(root(el('p', [textNode('one two three')]), el('ul', [li2])), state, 0);
@@ -410,10 +385,11 @@ describe('rehypeStreamWordFade', () => {
expect(words2.map((w) => w.text)).toEqual(['two ', 'three ', 'four']);
const p = tree2.children[0] as Element;
expect(p.children[0]).toEqual(textNode('one '));
- // 活动词仍保住原 key,负 delay 继续提供 remount 免疫;新词立即开始。
+ // 活动词仍保住原 key,负 delay 继续提供 remount 免疫。
+ // 在播词续播,新词接排。
expect(words2[0].key).toBe(words1[1].key);
expect(words2[1].key).toBe(words1[2].key);
- expect(words2[1].delay).toBe(-500);
+ expect(words2[1].delay).toBe(-452);
});
it('长 settled 前缀只保留一个原生文本节点', () => {
@@ -486,8 +462,6 @@ describe('globals.css 的 stream-word 动画本体', () => {
expect(css).not.toContain('data-stream-block');
// 与 .stream-word 同在 reduced-motion 的 animation:none 关停清单里
// (文件里有多个 reduce 块,按同规则相邻断言而不是抓第一个块)。
- expect(css).toMatch(
- /\.stream-word,\s*\[data-stream-marker\]::marker,[\s\S]{0,300}?animation: none !important/,
- );
+ expect(css).toMatch(/\.stream-word,\s*\[data-stream-marker\]::marker,[\s\S]{0,300}?animation: none !important/);
});
});
diff --git a/apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts b/apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts
index 04b887826c..abaec67fde 100644
--- a/apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts
+++ b/apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts
@@ -1,17 +1,17 @@
/**
- * rehypeStreamWordFade — 流式正文分段淡入(DESIGN.md §14.4 第五个 sanctioned
+ * rehypeStreamWordFade — 流式正文逐词淡入(DESIGN.md §14.4 第五个 sanctioned
* motion class,2026-08-07)。
*
- * 形态:流式输出时,每个新词与 inline-code 原子以 150ms opacity 淡入「浮现」。
- * 这**不是**被红线禁止的逐字打字机 —— 段整体已渲染就位,只有透明度渐变;
+ * 形态:流式输出时,每个新词以 150ms opacity 淡入「浮现」,而不是硬蹦出来。
+ * 这**不是**被红线禁止的逐字打字机 —— 词整体已渲染就位,只有透明度渐变;
* 设计裁决(2026-08-07)按「浮现 ≠ 打字」放行。
*
* 架构:CSS 管形态、JS 只管时序:
- * - 本插件仅在 isStreaming 且非 reduced-motion 时挂进 rehype 链尾,把文本词段
- * 与 inline-code 原子包 `<span class="stream-word" style="--wf-delay:Nms">`;动画本体是
+ * - 本插件仅在 isStreaming 且非 reduced-motion 时挂进 rehype 链尾,把文本节点
+ * 切词并包 `<span class="stream-word" style="--wf-delay:Nms">`;动画本体是
* globals.css 的 stream-word-in(--motion-fast 淡入,`both` 填充,delay 前隐藏)。
- * - **不重播 —— 内容匹配的稳定 key**:delay 与 settled 都按段的稳定 key 记账,
- * 不按文档序号。每次 parse 把本次段列表与上一次(state.previous)做匹配:
+ * - **不重播 —— 内容匹配的稳定 key**:delay 与 settled 都按词的稳定 key 记账,
+ * 不按文档序号。每次 parse 把本次词列表与上一次(state.previous)做匹配:
* 同位置内容相等或前缀延续(chunk 边界半个词长成整词)→ 复用旧 key;错位则
* 按内容从后往前找未被占用的旧 key(结构变化整体平移的词都能找回自己);都
* 没有才发新 key。markdown 结构变化(列表标记吃掉 "2. "、加粗闭合劈开文本
@@ -20,40 +20,41 @@
* - **settled 落袋 + settled 前缀还原纯文本**:span 带 data-wf-key,
* MarkdownRenderer 根节点监听冒泡的 animationend(markSettledFromAnimationEnd),
* 播完的 key 进 state.settled;settled 词从槽位中还原为合并后的原生文本,
- * settled inline code 则恢复原始 code 节点,
* 只保留仍在播放的尾部 span——流式长文档的元素数因此回落到与无动效渲染
* 同阶,react-markdown 每 tick 的重建 + diff 不随已播完的前文线性涨
* (曾因全文逐词包 span,几千元素把主线程打满,流式中点击切换 session
* 无响应,2026-08-09 实测)。部分 settled 的槽位仍整槽包 span(settled 词
* 的负 delay 已超动画时长,both 填充直接呈现终态,不重播)。抽掉 span 引
* 发的兄弟位置 key 平移由 remount 免疫兜底(见下),不再需要空壳保位。
- * - **普通聊天零 stagger**(Codex Desktop 普通聊天同款,2026-08-21):同一
- * parse tick 新到的词段都从 0ms 开始 150ms opacity 淡入,不再跨词排队。
- * 旧实现把专用展示场景的 24ms stagger 推广到普通聊天,又让行内 code
- * 完全跳过动画,导致后到的 code chip 已清晰显示、前文仍在排队的视觉反序。
+ * - **timeline 队列 + 背压**(Codex Desktop 同源,2026-08-08):delay 不按
+ * tick 静态起算,而是对着 state.nextStartAtMs(队列尾部绝对时间戳)动态
+ * 分配:新词排在 max(队列尾, now),随后尾部推进一个步长(上限 24ms/词,
+ * 按剩余预算自适应压缩,见 planTickStep)。跨 tick 连续 —— 上游卡顿后突发
+ * 的大段文字即使分落多个 parse tick,后到的词也永远排在先到的词后面
+ * (不插队、不乱序);卡顿期间队列自然排空(尾部落到过去),突发第一词
+ * 从 0ms 立即开始,整段呈连贯波浪推进而不是整块蹦出。
* - **remount 免疫 —— 存开播时刻、每 tick 发剩余 delay**(2026-08-08,与
* Codex 的根本差异所要求的补偿):Codex 自研渲染器用 segmentKey 当 React
* key,span 永不 remount;我们骑在 react-markdown 上,React key 是位置
* 序号,流式中正在生长的区域(表格尾行、成形中的列表)每 tick 都可能
* remount。若给 span 发固定 delay,remount 会让 CSS 动画带原始 delay 从头
* 重等,下一 tick 又 remount —— 词永远透明(2026-08-08 表格实测)。故
- * state 仍记**绝对开播时刻**,每个 tick 重新发出「开播时刻 - now」:
+ * state 记的是**绝对开播时刻**,每个 tick 重新发出「开播时刻 - now」:
* 已过时刻发**负 delay**,CSS 负 animation-delay 让动画从中途续播,
* remount 后帧级跳回正确进度,观感无缝。
* - 流式结束(isStreaming 翻 false)由 MarkdownRenderer 切回无插件的常量链,
- * 终版渲染没有任何 span 包装,按消息缓存的 state 同步释放。
+ * 终版渲染没有任何 span 包装,state 随 memo 一起被回收。
*
- * 原子淡入:inline code / 路径 chip 保持内部结构不拆,外层只包一个 stream-word,
- * 与同 tick 正文一起从 0ms 淡入。跳过:pre 代码块与 KaTeX 子树(公式内部是
- * 几十个定位 span,逐词包装会拆坏排版)。
+ * 跳过:code / pre(路径 chip 与代码块保持整体形态)与 KaTeX 子树(公式内部
+ * 是几十个定位 span,逐词包装会拆坏排版)。
*
- * 淡入对象模型(Codex Desktop 架构 + inline-code 顺序修正):**只有文本词段、
- * 行内代码原子和列表圆点淡入,块级结构永远即时出现**。表格边框、引用 rail、分隔线不做
+ * 淡入对象模型(Codex Desktop 对齐,2026-08-08 第二版):**只有文本词段和
+ * 列表圆点两类东西淡入,结构永远即时出现**。表格边框、引用 rail、分隔线不做
* 块级整体淡入 —— 曾试过 tr/li 整块排队,大积压窗口下必然出现"空骨架先
* 画好、文字憋一坨"(2026-08-08 两轮实测翻车)。表格格内文字与正文一样逐词
* 淡入(Codex FIa 对 table 的处理同款)。列表圆点(::marker)单独处理:li 打
- * data-stream-marker,delay/key **借用 li 内第一个段**(listItemDecorationByToken
- * 同构)—— 圆点与正文同帧浮现,不额外占段位,空 li 长出文字也不重播。
+ * data-stream-marker,delay/key **借用 li 内第一个词**(listItemDecorationByToken
+ * 同构)—— 圆点与它的文字同帧浮现,不占队列位,空 li 长出文字也不重播。
* 标记用 data 属性而不是 className:MarkdownRenderer 的自定义 renderer 是
* `className={cn(...)} {...props}` 写法,hast 塞 className 会经 spread 把样式
* 类整个覆盖掉;data-* 从 spread 直通,互不相扰。
@@ -65,15 +66,30 @@
import type { Plugin } from 'unified';
import type { Element, ElementContent, Root } from 'hast';
-type FadeSegmentKind = 'text' | 'inline-code';
-
-interface FadeSegment {
- kind: FadeSegmentKind;
- content: string;
-}
+/** 逐词 stagger 步长上限(Codex Desktop 同款 24ms;慢速输出时的标准节奏)。 */
+const STEP_MS = 24;
+/**
+ * 排程超前量预算(有意偏离 Codex,2026-08-08):Codex 的背压是固定压缩步长
+ * (800ms 积压后 6ms/词),隐含假设词到达慢于消费、队列终会排空;但吐词速率
+ * 因模型而异(超快模型 300+ tok/s ≈ 3ms/词,比 6ms 消费还快一倍),任何写死
+ * 的压缩步长都会在更快的模型下积压无界增长 —— 文档尾部(常见:表格)排到几
+ * 秒开外,骨架长时间空等(2026-08-08 实测)。
+ *
+ * 故改为**自适应步长**:每个 parse tick 按「剩余预算 / 本 tick 新词数」现算
+ * 本 tick 的步长(封顶 STEP_MS,见 planTickStep)。消费速率自动匹配任意到达
+ * 速率:慢模型恒拿 24ms(与 Codex 观感一致),快模型步长自动压小,积压永远
+ * 收敛在预算内 —— 文字落后数据到达最多约 MAX_LEAD_MS + 动画时长,与模型无关。
+ *
+ * 预算取值按**感知**定,不按节奏上限反推:逐词波浪只在到达速率低于人眼分辨
+ * (约十几词/秒)时有美学价值;300 tok/s 的模型没人能看清单词级波浪,却要为
+ * 大预算付出"结构骨架先画好、整表空着等文字"的代价(1200ms 预算 × 270 tok/s
+ * ≈ 一整个表格的空骨架,2026-08-08 实测截图)。320ms 上限保证任何模型下可见
+ * 文字落后数据到达 < 0.5s(320 + 150ms 动画),空骨架窗口压到亚秒级;慢模型
+ * 每 tick 词少、远用不满预算,24ms 波浪节奏不受影响。
+ */
+const MAX_LEAD_MS = 320;
interface PreviousSegment {
- kind: FadeSegmentKind;
content: string;
key: string;
}
@@ -81,7 +97,7 @@ interface PreviousSegment {
export interface WordFadeState {
/** 稳定 key 发号器。 */
nextId: number;
- /** 上一次 parse 的淡入段列表(文档序),类型 + 内容匹配复用 key 的依据。 */
+ /** 上一次 parse 的词列表(文档序),内容匹配复用 key 的依据。 */
previous: PreviousSegment[];
/**
* key → 绝对开播时刻(performance.now() 基准)。只排一次;每个 tick 由
@@ -91,6 +107,10 @@ export interface WordFadeState {
startAtByKey: Map<string, number>;
/** 已播完淡入的 key(animationend 落袋)。后续 parse 摘掉动画类。 */
settled: Set<string>;
+ /** timeline 队列尾部的绝对时间戳(performance.now() 基准),跨 tick 连续。 */
+ nextStartAtMs: number;
+ /** 本 tick 的自适应步长(planTickStep 计算,ensureDelay 消费)。 */
+ tickStepMs: number;
/** 时钟注入口,仅测试用;生产恒为 performance.now。 */
nowFn?: () => number;
}
@@ -101,31 +121,11 @@ export function createWordFadeState(): WordFadeState {
previous: [],
startAtByKey: new Map(),
settled: new Set(),
+ nextStartAtMs: 0,
+ tickStepMs: STEP_MS,
};
}
-/**
- * React render 只允许改 candidate。真正挂载后由 MarkdownRenderer 的
- * useLayoutEffect 提交,被并发渲染放弃的 parse 不会偷跑稳定 key / 时间线。
- */
-export function createWordFadeCandidate(committed: WordFadeState): WordFadeState {
- return {
- nextId: committed.nextId,
- previous: committed.previous,
- startAtByKey: new Map(committed.startAtByKey),
- settled: new Set(committed.settled),
- nowFn: committed.nowFn,
- };
-}
-
-export function commitWordFadeCandidate(committed: WordFadeState, candidate: WordFadeState): void {
- committed.nextId = candidate.nextId;
- committed.previous = candidate.previous;
- committed.startAtByKey = new Map(candidate.startAtByKey);
- // render 到 layout-effect 之间可能正好收到上一帧的 animationend;只合并,不能覆盖。
- committed.settled = new Set([...committed.settled, ...candidate.settled]);
-}
-
/**
* 流式消息在切换任务时会随 MessageStream 一起卸载。动画状态如果只挂在
* MarkdownRenderer 实例上,回来后整条已有正文会被当成首次到达并重播。
@@ -165,7 +165,7 @@ export function _resetWordFadeStateCacheForTests(): void {
/**
* animationend 落袋入口:MarkdownRenderer 根节点上监听冒泡的 animationend,
- * 把播完 stream-word-in 的段 key 记进 state.settled。按动画名过滤 —— 同一子树里
+ * 把播完 stream-word-in 的词 key 记进 state.settled。按动画名过滤 —— 同一子树里
* 其它动画(代码高亮、chip 等)的 animationend 不误伤。
*/
export function markSettledFromAnimationEnd(
@@ -178,12 +178,14 @@ export function markSettledFromAnimationEnd(
if (key) state.settled.add(key);
}
-/** 整棵子树跳过(不进入):块级代码、非正文节点与公式内部结构。 */
-const SKIP_TAGS = new Set(['pre', 'script', 'style', 'textarea']);
+/** 整棵子树跳过(不进入):代码、公式内部结构。 */
+const SKIP_TAGS = new Set(['code', 'pre', 'script', 'style', 'textarea']);
function isKatexSubtree(node: Element): boolean {
const cls = node.properties?.className;
- return Array.isArray(cls) && cls.some((c) => typeof c === 'string' && c.startsWith('katex'));
+ return (
+ Array.isArray(cls) && cls.some((c) => typeof c === 'string' && c.startsWith('katex'))
+ );
}
// Chromium(Electron renderer)恒有 Intl.Segmenter;条件判断只为让 Node 测试
@@ -241,53 +243,32 @@ export function splitWords(text: string): string[] {
/** pass 1 收集的待包装文本槽位:parent.children[index] 是原文本节点。 */
interface TextSlot {
- kind: 'text';
parent: Root | Element;
index: number;
words: string[];
- /** 本槽第一个词在全文档淡入段列表(segments)中的下标。 */
- segmentStart: number;
+ /** 本槽第一个词在全文档词列表(contents)中的下标。 */
+ wordStart: number;
}
-/** 行内 code 整体作为一个淡入段,内部 chip / 路径结构保持原样。 */
-interface InlineCodeSlot {
- kind: 'inline-code';
- parent: Root | Element;
- index: number;
- node: Element;
- segmentStart: number;
-}
-
-type FadeSlot = TextSlot | InlineCodeSlot;
-
-/** 列表项圆点条目:圆点借用 li 内第一个段的 key/delay(Codex 同款)。 */
+/** 列表项圆点条目:圆点借用 li 内第一个词的 key/delay(Codex 同款)。 */
interface MarkerEntry {
node: Element;
- /** li 内第一个段在全文档段列表中的下标;li 收集完仍相等 = 暂无内容。 */
- segmentStart: number;
- /** li 子树收集结束时的段列表长度,> segmentStart 才说明首段真在 li 内。 */
- segmentEnd: number;
+ /** li 内第一个词在全文档词列表中的下标;li 收集完仍等于收集前长度 = 暂无文字。 */
+ wordStart: number;
+ /** li 子树收集结束时的词表长度,> wordStart 才说明第一个词真在 li 内。 */
+ wordEnd: number;
}
interface Collected {
- slots: FadeSlot[];
- segments: FadeSegment[];
+ slots: TextSlot[];
+ contents: string[];
markers: MarkerEntry[];
}
-function elementText(node: Element): string {
- let out = '';
- for (const child of node.children) {
- if (child.type === 'text') out += child.value;
- else if (child.type === 'element') out += elementText(child);
- }
- return out;
-}
-
/**
- * 按文档序收集文本、行内 code 槽位与列表项条目。普通文本(含表格格内)切词;
- * inline code 整体占一个原子段。其它结构元素不占段位 —— li 圆点记下首段的
- * 下标,之后与该段共享 key 和 delay(Codex Desktop listItemDecorationByToken
+ * 按文档序收集文本槽位与列表项条目。所有文本(含表格格内)统一切词排队;
+ * 结构元素不占队列位 —— 唯一的结构动效是 li 圆点,它记下自己第一个词的
+ * 下标,之后与该词共享 key 和 delay(Codex Desktop listItemDecorationByToken
* 同构),圆点与文字永远同帧浮现,不会"圆点亮了文字干等"。
*/
function collect(node: Root | Element, out: Collected): void {
@@ -296,21 +277,11 @@ function collect(node: Root | Element, out: Collected): void {
const child = children[i];
if (child.type === 'element') {
if (SKIP_TAGS.has(child.tagName) || isKatexSubtree(child)) continue;
- if (child.tagName === 'code') {
- const segmentStart = out.segments.length;
- out.slots.push({ kind: 'inline-code', parent: node, index: i, node: child, segmentStart });
- out.segments.push({ kind: 'inline-code', content: elementText(child) });
- continue;
- }
if (child.tagName === 'li') {
- const entry: MarkerEntry = {
- node: child,
- segmentStart: out.segments.length,
- segmentEnd: 0,
- };
+ const entry: MarkerEntry = { node: child, wordStart: out.contents.length, wordEnd: 0 };
out.markers.push(entry);
collect(child, out);
- entry.segmentEnd = out.segments.length;
+ entry.wordEnd = out.contents.length;
continue;
}
collect(child, out);
@@ -320,15 +291,9 @@ function collect(node: Root | Element, out: Collected): void {
const words = splitWords(child.value);
// 单段且是纯空白(块间换行等)→ 原样保留,不改树。
if (words.length === 0 || (words.length === 1 && !words[0].trim())) continue;
- out.slots.push({
- kind: 'text',
- parent: node,
- index: i,
- words,
- segmentStart: out.segments.length,
- });
+ out.slots.push({ parent: node, index: i, words, wordStart: out.contents.length });
// 纯空白段(只可能出现在段首)不占词位。
- for (const w of words) if (w.trim()) out.segments.push({ kind: 'text', content: w });
+ for (const w of words) if (w.trim()) out.contents.push(w);
}
}
@@ -339,34 +304,27 @@ function collect(node: Root | Element, out: Collected): void {
* 3. 都没有 → 发新 key。
* 匹配完成后把本次列表写回 state.previous,供下一次 parse 匹配。
*/
-function segmentLookupKey(segment: FadeSegment): string {
- return `${segment.kind}\u0000${segment.content}`;
-}
-
-function assignKeys(segments: FadeSegment[], state: WordFadeState): string[] {
+function assignKeys(contents: string[], state: WordFadeState): string[] {
const unmatched = new Set<number>(state.previous.keys());
const byContent = new Map<string, number[]>();
for (let i = state.previous.length - 1; i >= 0; i--) {
- const lookupKey = segmentLookupKey(state.previous[i]);
- const arr = byContent.get(lookupKey);
+ const content = state.previous[i].content;
+ const arr = byContent.get(content);
if (arr) arr.push(i);
- else byContent.set(lookupKey, [i]);
+ else byContent.set(content, [i]);
}
- const keys = segments.map((segment, i) => {
+ const keys = contents.map((content, i) => {
const prev = state.previous[i];
if (
prev &&
unmatched.has(i) &&
- prev.kind === segment.kind &&
- (prev.content === segment.content ||
- (segment.kind === 'text' &&
- prev.content.length > 0 &&
- segment.content.startsWith(prev.content)))
+ (prev.content === content ||
+ (prev.content.length > 0 && content.startsWith(prev.content)))
) {
unmatched.delete(i);
return prev.key;
}
- const candidates = byContent.get(segmentLookupKey(segment));
+ const candidates = byContent.get(content);
let idx = candidates?.pop();
while (idx !== undefined && !unmatched.has(idx)) idx = candidates?.pop();
if (idx !== undefined) {
@@ -375,32 +333,42 @@ function assignKeys(segments: FadeSegment[], state: WordFadeState): string[] {
}
return `wf-${state.nextId++}`;
});
- state.previous = keys.map((key, i) => ({ ...segments[i], key }));
+ state.previous = keys.map((key, i) => ({ content: contents[i], key }));
return keys;
}
/**
* 取(必要时分配)某个 key 的开播时刻,返回**本 tick 视角的剩余 delay**。
- * 普通聊天不 stagger:同一 parse tick 的所有新 key 都以 nowMs 为开播时刻。
+ * timeline 队列:新 key 排在队列尾部(尾部已落到过去则立即开始),尾部按当前
+ * 积压深度推进(步长由 planTickStep 现算,超前量封顶 MAX_LEAD_MS)。
* 已见 key 不重排,但每个 tick 都按「开播时刻 - now」重新发剩余 delay:开播
* 时刻已过去则为负值,CSS 负 animation-delay 从中途续播 —— react-markdown
* 位置 key 引发的 remount 只会让动画跳回正确进度,不会从头重等(remount 免疫)。
*/
+/**
+ * 每个 parse tick 开头调用:按「剩余排程预算 / 本 tick 新词数」现算本 tick
+ * 的自适应步长。慢速输出(新词少、预算富余)恒拿 STEP_MS 上限,与 Codex 观感
+ * 一致;快速输出(新词多)步长按比例压小,保证本 tick 排完后超前量仍在
+ * MAX_LEAD_MS 预算内 —— 消费速率自动匹配任意模型的到达速率。
+ */
+function planTickStep(newWordCount: number, state: WordFadeState, nowMs: number): void {
+ if (newWordCount <= 0) return;
+ const backlog = Math.max(state.nextStartAtMs - nowMs, 0);
+ const budget = Math.max(MAX_LEAD_MS - backlog, 0);
+ state.tickStepMs = Math.min(STEP_MS, budget / newWordCount);
+}
+
function ensureDelay(key: string, state: WordFadeState, nowMs: number): number {
let startAt = state.startAtByKey.get(key);
if (startAt === undefined) {
- startAt = nowMs;
+ startAt = Math.min(Math.max(state.nextStartAtMs, nowMs), nowMs + MAX_LEAD_MS);
state.startAtByKey.set(key, startAt);
+ state.nextStartAtMs = startAt + state.tickStepMs;
}
return Math.round(startAt - nowMs);
}
-function makeFadeNode(
- children: ElementContent[],
- key: string,
- state: WordFadeState,
- nowMs: number,
-): ElementContent {
+function makeWordNode(word: string, key: string, state: WordFadeState, nowMs: number): ElementContent {
return {
type: 'element',
tagName: 'span',
@@ -409,7 +377,7 @@ function makeFadeNode(
style: `--wf-delay:${ensureDelay(key, state, nowMs)}ms`,
dataWfKey: key,
},
- children,
+ children: [{ type: 'text', value: word }],
};
}
@@ -419,18 +387,21 @@ function makeFadeNode(
* 性能核心。settled 词若逐个包空 span,元素数随全文词数线性涨(几千 span),
* react-markdown 每 tick 重建 + React diff 全量元素,主线程被 parse tick 打满,
* 点击/切换 session 全部排不上队(2026-08-09 实测:流式中无法切换会话)。
- * 还原成纯文本后,React 元素数回落到与无动效渲染同阶;只有 150ms 动画窗口
- * 内仍在播的段才有 span。安全性依赖 remount 免疫:文本节点数量变化会让后续
+ * 还原成纯文本后,React 元素数回落到与无动效渲染同阶;仍在播的词(320ms 预算
+ * 内,几十个)才有 span。安全性依赖 remount 免疫:文本节点数量变化会让后续
* 兄弟位置 key 平移、在播 span remount,但绝对开播时刻 + 负 delay 续播保证
* remount 后动画进度不变(而非从头重播)。
*/
-function isSlotFullySettled(slot: FadeSlot, keys: string[], state: WordFadeState): boolean {
- if (slot.kind === 'inline-code') return state.settled.has(keys[slot.segmentStart]);
- let segmentIndex = slot.segmentStart;
+function isSlotFullySettled(
+ slot: TextSlot,
+ keys: string[],
+ state: WordFadeState,
+): boolean {
+ let wordIndex = slot.wordStart;
for (const w of slot.words) {
if (!w.trim()) continue;
- if (!state.settled.has(keys[segmentIndex])) return false;
- segmentIndex++;
+ if (!state.settled.has(keys[wordIndex])) return false;
+ wordIndex++;
}
return true;
}
@@ -443,46 +414,39 @@ function appendPlainText(nodes: ElementContent[], value: string): void {
}
function makeSlotNodes(
- slot: FadeSlot,
+ slot: TextSlot,
keys: string[],
state: WordFadeState,
nowMs: number,
): ElementContent[] {
- if (slot.kind === 'inline-code') {
- const key = keys[slot.segmentStart];
- return [makeFadeNode([slot.node], key, state, nowMs)];
- }
const nodes: ElementContent[] = [];
- let segmentIndex = slot.segmentStart;
+ let wordIndex = slot.wordStart;
for (const word of slot.words) {
if (!word.trim()) {
appendPlainText(nodes, word);
continue;
}
- const key = keys[segmentIndex++];
+ const key = keys[wordIndex++];
if (state.settled.has(key)) appendPlainText(nodes, word);
- else nodes.push(makeFadeNode([{ type: 'text', value: word }], key, state, nowMs));
+ else nodes.push(makeWordNode(word, key, state, nowMs));
}
return nodes;
}
/**
* 给 li 挂圆点淡入(Codex Desktop fadeListDecoration 同构)。动画打在
- * `::marker` 上(CSS 见 globals.css),delay/key 借用 li 内第一个段 ——
- * 圆点与正文同帧浮现。li 内暂无内容(结构刚长出)→ 直接 0ms 淡入;
- * 内容到达后按首段 key 正常淡入,圆点已见 key 不重播。
+ * `::marker` 上(CSS 见 globals.css),delay/key 借用 li 内第一个词 ——
+ * 圆点与文字同帧浮现。li 内暂无文字(结构刚长出)→ 借队列尾部当前值,
+ * 不推进队列;文字到达后按词 key 正常淡入,圆点已见 key 不重播。
* 已 settled 的 key 不打标 —— 全新 hast 树上无动画类即无重播。
*/
-function applyMarkerFade(
- entry: MarkerEntry,
- keys: string[],
- state: WordFadeState,
- nowMs: number,
-): void {
- const hasSegment = entry.segmentEnd > entry.segmentStart;
- const key = hasSegment ? keys[entry.segmentStart] : undefined;
+function applyMarkerFade(entry: MarkerEntry, keys: string[], state: WordFadeState, nowMs: number): void {
+ const hasWord = entry.wordEnd > entry.wordStart;
+ const key = hasWord ? keys[entry.wordStart] : undefined;
if (key && state.settled.has(key)) return;
- const delay = key ? ensureDelay(key, state, nowMs) : 0;
+ const delay = key
+ ? ensureDelay(key, state, nowMs)
+ : Math.max(Math.round(state.nextStartAtMs - nowMs), 0);
entry.node.properties = {
...entry.node.properties,
dataStreamMarker: true,
@@ -493,16 +457,23 @@ function applyMarkerFade(
export const rehypeStreamWordFade: Plugin<[WordFadeState], Root> = (state) => {
return (tree) => {
- // pass 1:按文档序收集文本 / inline-code 槽位、全文档段列表与 li 圆点条目。
- const collected: Collected = { slots: [], segments: [], markers: [] };
+ // pass 1:按文档序收集文本槽位、全文档词列表与 li 圆点条目。
+ const collected: Collected = { slots: [], contents: [], markers: [] };
collect(tree, collected);
- const { slots, segments, markers } = collected;
- if (segments.length === 0 && markers.length === 0) return;
- // pass 2:类型 + 内容匹配分配稳定 key(已见段命中旧 key 拿回 delay/settled)。
- const keys = assignKeys(segments, state);
- // pass 3:回填 span。同 tick 新段全部 0ms 开始,旧段按绝对开播时刻续播。
+ const { slots, contents, markers } = collected;
+ if (contents.length === 0 && markers.length === 0) return;
+ // pass 2:内容匹配分配稳定 key(已见词命中旧 key 拿回旧 delay/settled)。
+ const keys = assignKeys(contents, state);
+ // pass 3:回填 span。timeline 队列只被"本 tick 新词"推进。
// 槽位从后往前 splice,前面槽位的 index 不受影响。
+ // delay 分配须按文档序(stagger 与阅读序一致),先按序生成节点再回填。
const nowMs = (state.nowFn ?? (() => performance.now()))();
+ // 自适应步长:先数本 tick 新词(未排程的 key),按剩余预算定步长。
+ const newWordCount = keys.reduce(
+ (n, k) => (state.startAtByKey.has(k) ? n : n + 1),
+ 0,
+ );
+ planTickStep(newWordCount, state, nowMs);
const nodesBySlot = slots.map((slot) => {
// 全 settled 槽位不改树(性能核心,见 isSlotFullySettled 注释)。
if (isSlotFullySettled(slot, keys, state)) return null;
diff --git a/apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx b/apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx
index 77cf9e1c51..2af743ad8d 100644
--- a/apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx
@@ -1,8 +1,8 @@
/**
* StreamFadeSection — Settings → 个性化 下的「流式动效」开关。
*
- * 控制流式输出时正文的淡入浮现动效(词段 / inline code 原子 + 列表圆点同帧
- * 浮现,见 rehypeStreamWordFade):开(默认)= 新内容淡入;关 = 文字直接显示。
+ * 控制流式输出时正文的淡入浮现动效(逐词淡入 + 列表圆点同帧浮现,见
+ * rehypeStreamWordFade):开(默认)= 新内容淡入;关 = 文字直接显示。
* 系统 reduced-motion 开启时动效无条件关闭,本开关不覆盖该行为。
*
* 存储走 useStreamFadePreference(localStorage 只存 override,切回默认即
diff --git a/apps/desktop/src/renderer/hooks/useStreamFadePreference.ts b/apps/desktop/src/renderer/hooks/useStreamFadePreference.ts
index 6d517f2eca..5cd23146eb 100644
--- a/apps/desktop/src/renderer/hooks/useStreamFadePreference.ts
+++ b/apps/desktop/src/renderer/hooks/useStreamFadePreference.ts
@@ -2,7 +2,7 @@
* useStreamFadePreference — 流式输出淡入动效的开关偏好(Settings → 个性化)。
* ---------------------------------------------------------------------------
* 两态,默认开启(2026-08-11 裁决):
- * - 'on' 流式输出时新内容淡入浮现(正文词段 + inline code 原子 + 列表圆点)。
+ * - 'on' 流式输出时新内容淡入浮现(逐词 + 列表圆点,rehypeStreamWordFade)。
* - 'off' 关闭动效,文字直接显示。
*
* 规则 20(配置默认值 vs override)落法:localStorage 只存 override——
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 3b4120bcc7..4ea0fa1760 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -1148,11 +1148,11 @@ body.resizing-pane [data-ghost-webview] {
}
}
-/* 流式正文分段淡入(§14.4 第五个 sanctioned motion class,2026-08-07):
- 每个新词与 inline-code 原子以 --motion-fast 从透明「浮现」。普通聊天不做
- 跨词 stagger,新段的 --wf-delay 为 0ms;已见段 remount 时可用负 delay 恢复
- 原动画进度。不是逐字打字机 —— 段整体已就位,只有 opacity 渐变;
- pure-opacity 一次性动画,compositor-only。`both` 保证负 delay / remount 续播。
+/* 流式正文逐词淡入(§14.4 第五个 sanctioned motion class,2026-08-07):
+ 每个新词以 --motion-fast 从透明「浮现」,delay 由 rehypeStreamWordFade 按词序
+ 写进 --wf-delay(上限 24ms/词,按排程预算自适应压缩)。不是逐字打字机 ——
+ 词整体已就位,只有 opacity 渐变;pure-opacity 一次性动画,compositor-only。
+ `both`:delay 未到时停在 0% 帧(透明),避免先闪现再淡入。
reduced-motion 双保险:JS 侧短路(插件不挂载,span 不进 DOM)+ 下方 reduce
块的 animation: none(摘掉动画连同 both 填充,span 落回自然 opacity 1,
不会钉在透明帧 —— 与「forwards/both 入场动画只能时长归零」那条坑的区别在于
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 51950fe352..7b9300adea 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -684,11 +684,11 @@ _Reference-implementation paths in this table are relative to `apps/desktop/src/
- **Definition**: the seal's signature running animation (two gapped arcs, outer 83/17 + inner 39/61, spinning as a whole at 2.4s linear on an HTML wrapper) is a beloved product signature and is preserved verbatim. What was missing was an ending: when the turn stops, the gaps used to freeze in place and read as "stuck mid-load". The choreography gives the animation a curtain call instead of replacing it: **while still spinning, both arcs close their gaps into full circles** (600ms one-shot `stroke-dasharray` transition — permitted as a one-shot transient per the red lines above); when the turn actually issued a `ghost_call` (fulfilled), a success-colored halo ring then dilates outward once (`summon-seal-halo`, 0.9s scale 1→1.65 + fade) while a ✓ badge pops at the avatar's corner (reusing the Done semantic's sanctioned overshoot curve, same as `status-done-pop`); the spin is removed only after the circles are closed — a spinning full circle is visually static, so the removal is seamless. Semantics stay self-consistent: gap = in progress, full circle = turn finished; ✓/halo appear **only on a fulfilled call** — a cancelled/never-issued call closes neutrally with no success badge (the ring must not fake success).
- **Parameter red lines**: close 600ms (`--motion-ease-out`; outside the duration tiers — sanctioned here, do not reuse elsewhere), halo 0.9s one-shot, tick pop 0.3s. Historic messages mount directly on the closed static frame with zero animation; the choreography plays only for a mount that actually witnessed `running` flip false. Halo/badge fill comes from the status-dot done-green exemption (`--card-status-done`); the ✓ glyph uses `--completion-badge-fg` (dark ink both modes, 5.29:1 on the done green — white would be 2.88:1, below the WCAG 1.4.11 non-text 3:1 floor). All keyframes are in the `prefers-reduced-motion` whitelist — reduced motion lands straight on the terminal frame.
- **Scope boundary**: this seal only. The closing-ring language must not leak into other spinners or progress indicators. Implementation: `apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx` + `.summon-seal-*` in `globals.css`.
-- **Stream-word fade(流式正文分段淡入)** — the fifth sanctioned motion class (approved 2026-08-07, ordinary-chat timing aligned 2026-08-21), **only** for streaming assistant prose in the chat message flow:
- - **Definition**: during streaming, each newly-arrived text **word** and each inline-code atom fades in over `--motion-fast` (150ms, opacity only) instead of popping in — content appears to *surface*, not *type*. This is explicitly **not** the forbidden per-character typewriter: each segment is fully rendered and positioned from its first frame; only opacity ramps. CJK is segmented per word via `Intl.Segmenter`; an inline-code chip keeps its internal structure and fades as one indivisible segment.
- - **Architecture red lines**: CSS owns the form, JS owns only the timing — `rehypeStreamWordFade` wraps words and inline-code atoms in `span.stream-word` and writes `--wf-delay`. Ordinary chat has **no cross-segment stagger**: every segment newly received in one render starts at `0ms`, matching Codex Desktop's normal-chat default and preventing later semantic atoms from overtaking queued prose. Segments are keyed by type + stable content matching (same-position matches, text-prefix continuation, and bounded backward matching), not by document index. Render computes a candidate state; only a committed DOM render may publish it from a layout effect. Each segment keeps an absolute start time / remaining delay across re-parse and remount, so already-seen content never replays. The animation itself is a pure-opacity one-shot keyframe in `globals.css` (compositor-only). The final (non-streaming) render carries **zero** wrapper spans — the plugin only mounts while `isStreaming`.
+- **Stream-word fade(流式正文逐词淡入)** — the fifth sanctioned motion class (approved 2026-08-07), **only** for streaming assistant prose in the chat message flow:
+ - **Definition**: during streaming, each newly-arrived **word** fades in over `--motion-fast` (150ms, opacity only) instead of popping in — text appears to *surface*, not *type*. This is explicitly **not** the forbidden per-character typewriter: the word is fully rendered and positioned from its first frame; only opacity ramps. CJK is segmented per word via `Intl.Segmenter`, so Chinese prose flows word-by-word too.
+ - **Architecture red lines**: CSS owns the form, JS owns only the timing — `rehypeStreamWordFade` wraps words in `span.stream-word` and writes a per-word `--wf-delay`. The nominal tick step is capped at **24ms per word**; when the pending lead would exceed the **320ms** lead budget, the step is compressed adaptively so rendering keeps up with any arrival rate. Words are keyed by stable content matching (same-position matches, prefix continuation, and bounded backward matching), not by document word index. Each word keeps an absolute scheduled start time / remaining delay across re-parse and remount, so already-seen words never replay. The animation itself is a pure-opacity one-shot keyframe in `globals.css` (compositor-only). The final (non-streaming) render carries **zero** wrapper spans — the plugin only mounts while `isStreaming`.
- **Degradation**: `prefers-reduced-motion` short-circuits in JS (plugin not mounted, no spans in DOM) *and* the CSS reduce block strips the animation — double coverage, and the CSS side is safe because `.stream-word` has no own opacity declaration to get stuck on.
- - **Scope boundary**: streaming chat prose only. Inline `code` participates as one atomic segment; fenced `pre` code blocks and KaTeX subtrees are skipped. Must not be applied to static content, titles, toasts, or any non-streamed text. Implementation: `apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts` + `.stream-word` in `globals.css`; tests: `rehypeStreamWordFade.test.ts`.
+ - **Scope boundary**: streaming chat prose only. Skips `code`/`pre` (chips and code blocks keep whole-form) and KaTeX subtrees. Must not be applied to static content, titles, toasts, or any non-streamed text. Implementation: `apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts` + `.stream-word` in `globals.css`; tests: `rehypeStreamWordFade.test.ts`.
- **Session-loading wordmark sheen(会话加载字标扫光)** — the sixth sanctioned motion class (approved 2026-08-10), **only** for Desktop `BrandLoadingMark` while `MessageStream` defers its message tree during a session switch:
- **Definition**: the active theme's official Light/Dark Cindy wordmark sits centered in the empty message viewport at 35% opacity; after a 200ms delayed-reveal threshold, one narrow neutral highlight traverses the wordmark shape. The PNG alpha channel is the mask, so motion is confined to the glyphs and never paints a panel/background. This is functional loading feedback for a measured long switch, not a decorative brand loop: ordinary sessions complete before the reveal threshold and never show it; the mark unmounts immediately when the message tree mounts.
- **Parameters / performance**: highlight cycle 1.6s, `cubic-bezier(0.4, 0, 0.2, 1)`, HTML pseudo-element `transform: translateX(-120% → 350%)` only (compositor-only). The neutral gradient is the narrow §2 exception registered under “Gradient System”; it may use only `transparent` and `--text-primary`, never brand red or a component-authored chromatic value. `prefers-reduced-motion` removes both the reveal and sheen animations and shows a static wordmark; `[data-app-hidden='true']` pauses the infinite sheen via `animation-play-state` while the window is hidden.