conversation-session-streaming-word-reveal.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { clearAppData } from "#e2e/helpers/desktop-app";
  2. import { startConversationModelProviderReplayServer } from "#e2e/helpers/model-provider-replay";
  3. import {
  4. prepareV4ConversationE2E,
  5. sendV4Prompt,
  6. waitForV4AssistantMessageContaining,
  7. } from "#e2e/helpers/v4-conversation";
  8. const CASE = "conversation-session-streaming-word-reveal";
  9. /** fixture 里各段的片段,用来确认完成态文本完整。 */
  10. const TEXT_FRAGMENTS = [
  11. "节奏要能看清楚",
  12. "列表项四",
  13. "不能落在后面",
  14. "The burst sentence still spreads out.",
  15. ] as const;
  16. /** fixture 里各段的标记,用来把单元归到段落:慢速段、列表段、快速段、停顿后的突发段。 */
  17. const SEGMENT_MARKERS = ["慢速段", "列表项", "快速段", "突发段"] as const;
  18. const SLOW = 0;
  19. const FAST = 2;
  20. const BURST = 3;
  21. /** 第二轮 fixture 的正文片段。 */
  22. const SECOND_ROUND_FRAGMENT = "Second round fades in too.";
  23. interface RevealMount {
  24. text: string;
  25. tag: string;
  26. state: string;
  27. /** 排期写在 --zcode-reveal-delay 上的延迟。 */
  28. delay: number;
  29. /** 挂载时 opacity 过渡的实际时长;没有过渡时为 -1。 */
  30. duration: number;
  31. at: number;
  32. fading: boolean;
  33. paragraph: Element | null;
  34. }
  35. interface MarkerMount {
  36. state: string;
  37. fading: boolean;
  38. duration: number;
  39. /** 挂载时 li 的文本片段,用来定位是哪一项的圆点。 */
  40. item: string;
  41. }
  42. interface StoredRevealProbe {
  43. mounts: RevealMount[];
  44. markerMounts: MarkerMount[];
  45. settle: { changed: number; inDelay: number; inDelayKept: number; durationKept: number };
  46. observer: MutationObserver;
  47. markers: string[];
  48. }
  49. interface SegmentTiming {
  50. count: number;
  51. medianDuration: number;
  52. medianDelay: number;
  53. maxDelay: number;
  54. }
  55. interface RevealProbeResult {
  56. /** 新挂载、标为 new 的单元数(词 span 与行内 code)。 */
  57. newUnits: number;
  58. /** 其中挂载后确实带着 opacity CSSTransition 的数量——CSS 没生效时这里是 0。 */
  59. newUnitsWithTransition: number;
  60. /** 每段的排期统计,下标对应 SEGMENT_MARKERS。 */
  61. segments: SegmentTiming[];
  62. /** 含汉字却不止一个字的单元;中文按字切分时应为空。 */
  63. multiCharHanUnits: string[];
  64. /** 行内 code 作为一个单元淡入。 */
  65. inlineCode: { newMounted: number; withTransition: number };
  66. /** 列表圆点 / 序号:li::marker 上的 color 过渡。 */
  67. markers: { newMounted: number; withTransition: number };
  68. /** 停顿后整句突发到达的那一段的排期。 */
  69. burst: { count: number; monotonic: boolean; spreadMs: number };
  70. /** 单元在延迟期间从 new 变成 settled 时,淡入是否仍在、时长是否不变。 */
  71. settleDuringDelay: {
  72. changed: number;
  73. inDelay: number;
  74. inDelayKept: number;
  75. durationKept: number;
  76. };
  77. sample: { text: string; delay: number; duration: number } | null;
  78. /** 以 settled 新挂载的单元:没有经过淡入就直接出现。 */
  79. settledMounts: { text: string; paragraph: string }[];
  80. /** 每个圆点挂载时的状态与所在项。 */
  81. markerItems: { state: string; item: string; fading: boolean }[];
  82. }
  83. /**
  84. * SWR01 逐字 / 逐词浮现。
  85. *
  86. * 这个用例盯的是最容易悄悄失效、静态检查都发现不了的环节:
  87. * 1. rehype 插件有没有真的进管线并产出单元,会不会被 rehype-sanitize 剥掉;
  88. * 2. 「单元生成了但没有任何 CSS 规则消费」——Streamdown 内置动画当初就是这样失效的,
  89. * 所以断言挂载后存在 opacity 的 CSSTransition,而不是元素存在;
  90. * 3. 进度按 block 记录:后面的段落必须从第一个单元开始淡入,不能被前一段的进度吞掉;
  91. * 4. 中文按字切分;行内 code 作为一个单元淡入;列表圆点(li::marker)跟着第一个字淡入;
  92. * 5. 只有滞后按到达速度缩放:快速段滞后明显低于 250ms 上限;淡入时长快慢段都是 300ms;
  93. * 6. 停顿后整句突发到达时,排期把整句铺开,延迟单调递增,而不是同时起跳;
  94. * 7. 单元在延迟期间就变成 settled、内联的 delay 被移除时,已排好的淡入不被取消、时长不变。
  95. *
  96. * 流式窗口很窄,轮询会漏,因此探针在发送之前就挂上 MutationObserver,
  97. * 只统计新挂载的节点与 new → settled 的属性变化。
  98. */
  99. describe("SWR01 streaming word reveal", () => {
  100. let replay: Awaited<ReturnType<typeof startConversationModelProviderReplayServer>>;
  101. before(async function () {
  102. this.timeout(240000);
  103. replay = await startConversationModelProviderReplayServer(CASE);
  104. await clearAppData();
  105. await prepareV4ConversationE2E();
  106. });
  107. after(async () => {
  108. await replay?.stop();
  109. });
  110. it("按到达速度调节节奏,逐字淡入、突发铺开,行内 code 与列表圆点同步淡入,完成态无残留", async function () {
  111. this.timeout(120000);
  112. await browser.execute(
  113. (markers: string[]) => {
  114. const mounts: RevealMount[] = [];
  115. const markerMounts: MarkerMount[] = [];
  116. const byElement = new WeakMap<Element, RevealMount>();
  117. const settle = { changed: 0, inDelay: 0, inDelayKept: 0, durationKept: 0 };
  118. // getAnimations 会强制一次样式计算;@starting-style 生效时这里能拿到过渡(含延迟阶段)。
  119. const opacityTransition = (el: Element) =>
  120. el
  121. .getAnimations()
  122. .find(
  123. (animation): animation is CSSTransition =>
  124. animation instanceof CSSTransition && animation.transitionProperty === "opacity",
  125. );
  126. const markerTransition = (el: Element) =>
  127. el
  128. .getAnimations({ subtree: true })
  129. .find(
  130. (animation): animation is CSSTransition =>
  131. animation instanceof CSSTransition &&
  132. animation.transitionProperty === "color" &&
  133. (animation.effect as KeyframeEffect | null)?.pseudoElement === "::marker",
  134. );
  135. const durationOf = (transition: CSSTransition | undefined) => {
  136. const duration = transition?.effect?.getTiming().duration;
  137. return typeof duration === "number" ? duration : -1;
  138. };
  139. const inspectUnit = (el: HTMLElement) => {
  140. const state = el.getAttribute("data-zcode-reveal") ?? "";
  141. const delay = Number.parseFloat(el.style.getPropertyValue("--zcode-reveal-delay"));
  142. const transition = state === "new" ? opacityTransition(el) : undefined;
  143. const mount: RevealMount = {
  144. text: el.textContent ?? "",
  145. tag: el.tagName.toLowerCase(),
  146. state,
  147. delay: Number.isFinite(delay) ? delay : 0,
  148. duration: durationOf(transition),
  149. at: performance.now(),
  150. fading: transition !== undefined,
  151. paragraph: el.closest("p, li"),
  152. };
  153. mounts.push(mount);
  154. byElement.set(el, mount);
  155. };
  156. const inspectMarker = (el: HTMLElement) => {
  157. const state = el.getAttribute("data-zcode-reveal-marker") ?? "";
  158. const transition = state === "new" ? markerTransition(el) : undefined;
  159. markerMounts.push({
  160. state,
  161. fading: transition !== undefined,
  162. duration: durationOf(transition),
  163. item: (el.textContent ?? "").slice(0, 12),
  164. });
  165. };
  166. const observer = new MutationObserver((records) => {
  167. for (const record of records) {
  168. if (record.type === "attributes") {
  169. const target = record.target as HTMLElement;
  170. if (record.oldValue !== "new") continue;
  171. if (target.getAttribute("data-zcode-reveal") !== "settled") continue;
  172. const mount = byElement.get(target);
  173. if (!mount) continue;
  174. settle.changed += 1;
  175. if (performance.now() - mount.at < mount.delay) {
  176. settle.inDelay += 1;
  177. const kept = opacityTransition(target);
  178. if (kept) {
  179. settle.inDelayKept += 1;
  180. if (Math.abs(durationOf(kept) - mount.duration) < 0.5) settle.durationKept += 1;
  181. }
  182. }
  183. continue;
  184. }
  185. for (const node of record.addedNodes) {
  186. if (!(node instanceof HTMLElement)) continue;
  187. if (node.hasAttribute("data-zcode-reveal")) inspectUnit(node);
  188. if (node.hasAttribute("data-zcode-reveal-marker")) inspectMarker(node);
  189. node.querySelectorAll<HTMLElement>("[data-zcode-reveal]").forEach(inspectUnit);
  190. node
  191. .querySelectorAll<HTMLElement>("[data-zcode-reveal-marker]")
  192. .forEach(inspectMarker);
  193. }
  194. }
  195. });
  196. observer.observe(document.body, {
  197. childList: true,
  198. subtree: true,
  199. attributes: true,
  200. attributeFilter: ["data-zcode-reveal"],
  201. attributeOldValue: true,
  202. });
  203. const probe: StoredRevealProbe = { mounts, markerMounts, settle, observer, markers };
  204. (window as unknown as { __revealProbe: StoredRevealProbe }).__revealProbe = probe;
  205. },
  206. [...SEGMENT_MARKERS],
  207. );
  208. await sendV4Prompt("E2E_WORD_REVEAL: 输出几段节奏不同的中英混合正文用于逐字浮现验证。");
  209. await waitForV4AssistantMessageContaining(TEXT_FRAGMENTS[3]);
  210. // 完成态切到 static 后插件退出管线,单元全部消失;以此作为流式结束的信号。
  211. await browser.waitUntil(
  212. () =>
  213. browser.execute(
  214. () =>
  215. document.querySelectorAll("[data-zcode-reveal], [data-zcode-reveal-marker]").length ===
  216. 0,
  217. ),
  218. { timeout: 30000, timeoutMsg: "完成态仍残留逐字浮现单元" },
  219. );
  220. const probe = await browser.execute((burstIndex: number): RevealProbeResult => {
  221. const stored = (window as unknown as { __revealProbe: StoredRevealProbe }).__revealProbe;
  222. stored.observer.disconnect();
  223. const median = (values: number[]) => {
  224. if (values.length === 0) return -1;
  225. const sorted = [...values].sort((left, right) => left - right);
  226. return sorted[Math.floor(sorted.length / 2)] ?? -1;
  227. };
  228. // 完成态重建后旧段落已脱离文档,但其 textContent 仍是流式最后一帧,可用来归段。
  229. const segmentIndex = (mount: RevealMount) => {
  230. const text = mount.paragraph?.textContent ?? "";
  231. return stored.markers.findIndex((marker) => text.includes(marker));
  232. };
  233. const fresh = stored.mounts.filter((mount) => mount.state === "new");
  234. const han = /\p{Script=Han}/u;
  235. const code = fresh.filter((mount) => mount.tag === "code");
  236. const markers = stored.markerMounts.filter((mount) => mount.state === "new");
  237. const segments = stored.markers.map((_, index) => {
  238. const units = fresh.filter((mount) => segmentIndex(mount) === index);
  239. const delays = units.map((mount) => mount.delay);
  240. return {
  241. count: units.length,
  242. medianDuration: median(units.map((mount) => mount.duration)),
  243. medianDelay: median(delays),
  244. maxDelay: delays.length > 0 ? Math.max(...delays) : -1,
  245. };
  246. });
  247. const burstDelays = fresh
  248. .filter((mount) => segmentIndex(mount) === burstIndex)
  249. .map((mount) => mount.delay);
  250. const first = fresh[0];
  251. return {
  252. newUnits: fresh.length,
  253. newUnitsWithTransition: fresh.filter((mount) => mount.fading).length,
  254. segments,
  255. multiCharHanUnits: fresh
  256. .filter(
  257. (mount) =>
  258. mount.tag === "span" && han.test(mount.text) && Array.from(mount.text).length > 1,
  259. )
  260. .map((mount) => mount.text),
  261. inlineCode: {
  262. newMounted: code.length,
  263. withTransition: code.filter((mount) => mount.fading).length,
  264. },
  265. markers: {
  266. newMounted: markers.length,
  267. withTransition: markers.filter((mount) => mount.fading).length,
  268. },
  269. burst: {
  270. count: burstDelays.length,
  271. monotonic: burstDelays.every(
  272. (delay, index) => index === 0 || delay >= (burstDelays[index - 1] ?? delay),
  273. ),
  274. spreadMs: burstDelays.length > 0 ? (burstDelays.at(-1) ?? 0) - (burstDelays[0] ?? 0) : 0,
  275. },
  276. settleDuringDelay: { ...stored.settle },
  277. sample: first ? { text: first.text, delay: first.delay, duration: first.duration } : null,
  278. settledMounts: stored.mounts
  279. .filter((mount) => mount.state === "settled")
  280. .slice(0, 40)
  281. .map((mount) => ({
  282. text: mount.text,
  283. paragraph: (mount.paragraph?.textContent ?? "").slice(0, 16),
  284. })),
  285. markerItems: stored.markerMounts.map((mount) => ({
  286. state: mount.state,
  287. item: mount.item,
  288. fading: mount.fading,
  289. })),
  290. };
  291. }, BURST);
  292. console.log("[SWR01] reveal probe:", JSON.stringify(probe));
  293. expect(probe.newUnits).toBeGreaterThan(0);
  294. // 单元在而过渡不在,就是「CSS 没有规则消费」的原貌,必须断死在这里。
  295. expect(probe.newUnitsWithTransition).toBeGreaterThanOrEqual(Math.ceil(probe.newUnits * 0.9));
  296. // 每一段都要有新单元淡入:后面的段落不能被前一段的进度吞掉。
  297. for (const segment of probe.segments) expect(segment.count).toBeGreaterThan(0);
  298. expect(probe.multiCharHanUnits).toEqual([]);
  299. expect(probe.inlineCode.newMounted).toBeGreaterThan(0);
  300. expect(probe.inlineCode.withTransition).toBeGreaterThan(0);
  301. // fixture 有两个无序、两个有序列表项,每个圆点 / 序号都要带 color 过渡。
  302. expect(probe.markers.newMounted).toBeGreaterThanOrEqual(4);
  303. expect(probe.markers.withTransition).toBe(probe.markers.newMounted);
  304. // 只有滞后按到达速度缩放:快速段的滞后要明显低于 250ms 上限(固定参数时会一直顶在上限)。
  305. // 淡入时长固定 300ms,快慢段一样:曾经按速度缩到 120ms,每个字只有 2–3 帧渐变,看起来没有动画。
  306. const slow = probe.segments[SLOW];
  307. const fast = probe.segments[FAST];
  308. expect(slow?.medianDuration ?? -1).toBeGreaterThanOrEqual(290);
  309. expect(fast?.medianDuration ?? -1).toBeGreaterThanOrEqual(290);
  310. expect(fast?.medianDelay ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(150);
  311. for (const segment of probe.segments) expect(segment.maxDelay).toBeLessThanOrEqual(255);
  312. // 突发整句要被铺开:延迟单调递增且拉开跨度,而不是同时起跳。
  313. expect(probe.burst.count).toBeGreaterThanOrEqual(10);
  314. expect(probe.burst.monotonic).toBe(true);
  315. expect(probe.burst.spreadMs).toBeGreaterThanOrEqual(40);
  316. // 延迟期间变成 settled 的单元,淡入必须仍在,时长也不变。
  317. expect(probe.settleDuringDelay.inDelay).toBeGreaterThan(0);
  318. expect(probe.settleDuringDelay.inDelayKept).toBe(probe.settleDuringDelay.inDelay);
  319. expect(probe.settleDuringDelay.durationKept).toBe(probe.settleDuringDelay.inDelayKept);
  320. const text = await browser.execute(() =>
  321. Array.from(document.querySelectorAll<HTMLElement>(".group\\/assistant-row"))
  322. .map((row) => row.innerText)
  323. .join("\n"),
  324. );
  325. for (const fragment of TEXT_FRAGMENTS) expect(text).toContain(fragment);
  326. });
  327. /*
  328. * 回归:Streamdown 的 processor 缓存按 rehype 插件函数的 name 生成 key,整个 App 共用一份。
  329. * 插件实例原来都叫 streamingRevealRehypePlugin,第二条流式消息命中缓存,拿到第一条消息的
  330. * 插件实例和它已结束的状态(incremental=false),所有字都被当成 settled 直接出现。
  331. * 上一个用例只覆盖 App 启动后的第一条消息,所以这里在同一会话里接着问第二轮。
  332. */
  333. it("同一会话的第二轮回复同样逐字淡入", async function () {
  334. this.timeout(120000);
  335. await browser.execute(() => {
  336. // settledLater:已挂载的单元在后续帧由 new 变成 settled 的次数,代表本条消息的进度在推进。
  337. const counts = { fresh: 0, fading: 0, settled: 0, settledLater: 0 };
  338. const inspect = (el: HTMLElement) => {
  339. const state = el.getAttribute("data-zcode-reveal");
  340. if (state === "settled") {
  341. counts.settled += 1;
  342. return;
  343. }
  344. if (state !== "new") return;
  345. counts.fresh += 1;
  346. const fading = el
  347. .getAnimations()
  348. .some(
  349. (animation) =>
  350. animation instanceof CSSTransition && animation.transitionProperty === "opacity",
  351. );
  352. if (fading) counts.fading += 1;
  353. };
  354. const observer = new MutationObserver((records) => {
  355. for (const record of records) {
  356. if (record.type === "attributes") {
  357. const target = record.target as HTMLElement;
  358. if (record.oldValue === "new" && target.getAttribute("data-zcode-reveal") === "settled")
  359. counts.settledLater += 1;
  360. continue;
  361. }
  362. for (const node of record.addedNodes) {
  363. if (!(node instanceof HTMLElement)) continue;
  364. if (node.hasAttribute("data-zcode-reveal")) inspect(node);
  365. node.querySelectorAll<HTMLElement>("[data-zcode-reveal]").forEach(inspect);
  366. }
  367. }
  368. });
  369. observer.observe(document.body, {
  370. childList: true,
  371. subtree: true,
  372. attributes: true,
  373. attributeFilter: ["data-zcode-reveal"],
  374. attributeOldValue: true,
  375. });
  376. (
  377. window as unknown as {
  378. __secondRoundProbe: { counts: typeof counts; observer: MutationObserver };
  379. }
  380. ).__secondRoundProbe = { counts, observer };
  381. });
  382. await sendV4Prompt("E2E_SECOND_ROUND_REVEAL: 再输出一段正文,验证第二轮也逐字淡入。");
  383. await waitForV4AssistantMessageContaining(SECOND_ROUND_FRAGMENT);
  384. await browser.waitUntil(
  385. () => browser.execute(() => document.querySelectorAll("[data-zcode-reveal]").length === 0),
  386. { timeout: 30000, timeoutMsg: "第二轮完成态仍残留逐字浮现单元" },
  387. );
  388. const counts = await browser.execute(() => {
  389. const stored = (
  390. window as unknown as {
  391. __secondRoundProbe: {
  392. counts: { fresh: number; fading: number; settled: number; settledLater: number };
  393. observer: MutationObserver;
  394. };
  395. }
  396. ).__secondRoundProbe;
  397. stored.observer.disconnect();
  398. return stored.counts;
  399. });
  400. console.log("[SWR01] second round probe:", JSON.stringify(counts));
  401. // fixture 约 40 个单元,第二轮也要逐字淡入。
  402. expect(counts.fresh).toBeGreaterThanOrEqual(20);
  403. expect(counts.fading).toBeGreaterThanOrEqual(Math.ceil(counts.fresh * 0.9));
  404. // 第二轮自己的进度必须推进:已挂载的单元在后续帧变成 settled。共用第一条消息的插件实例时,
  405. // 第二轮的进度写进第一条消息的 state、永远不会被提交,每帧都把整段当新增,这个计数是 0;
  406. // 第一条消息若以 incremental=false 结束,第二轮则全部以 settled 挂载、没有任何动画。
  407. expect(counts.settledLater).toBeGreaterThanOrEqual(Math.ceil(counts.fresh * 0.5));
  408. });
  409. });