conversation-session-snapshot-retention.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // 生产 renderer 的独立 CDP E2E;使用 node:test,不能放入 WDIO/Docker preset。
  2. // 前置:隔离 HOME 中播种 8 个 sess_probe_retention_0..7 已完成会话,启动未开启 E2E bridge 的 App。
  3. // ZCODE_RETENTION_CDP_URL=http://127.0.0.1:9326 ZCODE_RETENTION_ARTIFACT_DIR=<dir>
  4. // pnpm --filter @zcode/desktop test:e2e:retention
  5. import assert from "node:assert/strict";
  6. import { createWriteStream } from "node:fs";
  7. import { mkdir, writeFile, appendFile } from "node:fs/promises";
  8. import { join, resolve } from "node:path";
  9. import { setTimeout as pause } from "node:timers/promises";
  10. import { test } from "node:test";
  11. import { chromium, type Browser } from "playwright-core";
  12. import { countRetainedHistory } from "#e2e/helpers/session-pane-retention-heap";
  13. const prefix = "sess_probe_retention_";
  14. // SPR03 的 fixture 使用 8 个独立工作区,覆盖每个 transport 各遗留一个预热 owner 的路径。
  15. const crossWorkspace = process.env.ZCODE_RETENTION_CROSS_WORKSPACE === "1";
  16. // SPR04/05 复用同工作区 fixture,直接检查已脱离 store 的历史 snapshot。
  17. const sameWorkspace = process.env.ZCODE_RETENTION_SAME_WORKSPACE === "1";
  18. const returnToDraft = crossWorkspace || sameWorkspace;
  19. function rendererPage(browser: Browser) {
  20. const page = browser
  21. .contexts()
  22. .flatMap((context) => context.pages())
  23. .find((candidate) => candidate.url().includes("/renderer/index.html"));
  24. assert(page, "缺少真实生产 renderer");
  25. return page;
  26. }
  27. test(
  28. sameWorkspace
  29. ? "SPR04/05: same-workspace history and draft roundtrips release snapshots and callbacks"
  30. : crossWorkspace
  31. ? "SPR03: cross-workspace switches and return to draft release prewarm owners and history"
  32. : "SPR01: 136 session switches release inactive snapshots and closed stores",
  33. { timeout: 1_200_000 },
  34. async () => {
  35. const endpoint = process.env.ZCODE_RETENTION_CDP_URL;
  36. const artifactDir = process.env.ZCODE_RETENTION_ARTIFACT_DIR;
  37. const sourceMapPath = process.env.ZCODE_RETENTION_RENDERER_SOURCEMAP;
  38. assert(!sameWorkspace || sourceMapPath, "SPR04/05 需要精确生产 renderer sourcemap 校验回调族");
  39. assert(endpoint && artifactDir, "需要显式指定隔离 App CDP 与证据目录");
  40. const output = resolve(artifactDir);
  41. await mkdir(output, { recursive: true });
  42. let browser = await chromium.connectOverCDP(endpoint);
  43. // 前置 bridge 断言也可能失败;连接从建立起就归 finally 清理,避免失败后进程挂起。
  44. try {
  45. let page = rendererPage(browser);
  46. // 测试 bridge 会额外持有 store;误连普通 E2E 构建会污染生产回收证据,必须先拒绝。
  47. assert.deepEqual(
  48. await page.evaluate((allowEmptyTrajectoryBridge) => {
  49. return Object.keys(window).filter((key) => {
  50. if (!/^__zcode.*StoreE2E$/u.test(key)) return false;
  51. // 现有生产构建无条件暴露该无历史入口。保留它,只接受空请求;不能删除根来伪造回收。
  52. if (allowEmptyTrajectoryBridge && key === "__zcodeModelTrajectoryStoreE2E") {
  53. const bridge = (
  54. window as Window & {
  55. __zcodeModelTrajectoryStoreE2E?: { getState(): { pendingRequest: unknown } };
  56. }
  57. ).__zcodeModelTrajectoryStoreE2E;
  58. return bridge?.getState().pendingRequest !== null;
  59. }
  60. return true;
  61. });
  62. }, returnToDraft),
  63. [],
  64. "SPR01 必须使用未暴露 E2E store bridge 的生产 renderer",
  65. );
  66. let cdp = await page.context().newCDPSession(page);
  67. const measurements: Array<
  68. { name: string; switches: number; heapMiB: number } & Awaited<
  69. ReturnType<typeof countRetainedHistory>
  70. >
  71. > = [];
  72. let switches = 0;
  73. await cdp.send("HeapProfiler.enable");
  74. try {
  75. // 基线从 session 0 开始;随后固定按 1..7,0 循环。
  76. await page.getByTestId(`task-item-${prefix}7`).waitFor({ state: "visible" });
  77. const more = page.locator("[data-task-list-show-more]");
  78. for (const button of await more.all()) {
  79. if (await button.isVisible()) await button.click();
  80. }
  81. const select = async (index: number) => {
  82. await page.locator(`[data-testid="task-item-${prefix}${index}"]`).click();
  83. await page.waitForFunction(
  84. ({ prefix, index }) => {
  85. const pane = document.querySelector('[data-testid="v4-session-pane-workspace-main"]');
  86. return (
  87. pane?.getAttribute("data-session-id") === `${prefix}${index}` &&
  88. pane.textContent?.includes(`RETENTION_REPLY_${index}`)
  89. );
  90. },
  91. { prefix, index },
  92. // 首次跨工作区可能冷启动 runtime;验收等待内容就绪,不把机器负载当作泄漏失败。
  93. { timeout: 60_000 },
  94. );
  95. if (sameWorkspace) {
  96. const editor = page
  97. .locator('[data-testid="v4-session-pane-workspace-main"] [contenteditable="true"]')
  98. .first();
  99. await editor.click();
  100. await editor.fill("/");
  101. const panel = page.locator('[data-testid="prompt-suggestion-panel"][data-trigger="/"]');
  102. await panel.waitFor({ state: "visible" });
  103. assert((await panel.locator('[role="option"]').count()) > 0, "slash 选项必须实际出现");
  104. await editor.press("Escape");
  105. await panel.waitFor({ state: "hidden" });
  106. await editor.fill("");
  107. }
  108. await pause(150);
  109. };
  110. const showDraft = async () => {
  111. await page.getByTestId("task-new-button").click();
  112. await page.waitForFunction(
  113. () =>
  114. document
  115. .querySelector('[data-testid="v4-session-pane-workspace-main"]')
  116. ?.getAttribute("data-session-id") === "draft",
  117. );
  118. };
  119. await select(0);
  120. const checkpoints: Array<[string, number]> = sameWorkspace
  121. ? [
  122. ["draft-008", 8],
  123. ["draft-032", 32],
  124. ["draft-064", 64],
  125. ["draft-128", 128],
  126. ["idle-control", 128],
  127. ["single-connection-roundtrips", 128],
  128. ]
  129. : crossWorkspace
  130. ? [
  131. ["draft-008", 8],
  132. ["draft-016", 16],
  133. ["draft-032", 32],
  134. ["idle-control", 32],
  135. ]
  136. : [
  137. ["warmup-008", 8],
  138. ["switch-040", 40],
  139. ["switch-072", 72],
  140. ["switch-136", 136],
  141. ["idle-control", 136],
  142. ];
  143. for (const [name, target] of checkpoints) {
  144. while (switches < target) {
  145. await select((switches + 1) % 8);
  146. switches++;
  147. await appendFile(
  148. join(output, "switches.jsonl"),
  149. JSON.stringify({ switches, loaded: true }) + "\n",
  150. );
  151. }
  152. if (name === "single-connection-roundtrips") {
  153. // 四次往返共用一个操作连接;中途没有采堆、GC 或重连,排除检查点促成累积。
  154. for (const index of [1, 2, 3, 4]) {
  155. await select(index);
  156. await showDraft();
  157. await appendFile(
  158. join(output, "roundtrips.jsonl"),
  159. JSON.stringify({ index, returnedToDraft: true }) + "\n",
  160. );
  161. }
  162. } else if (returnToDraft && name !== "idle-control") {
  163. await showDraft();
  164. }
  165. // 自动化的 InjectedScript/UtilityScript 会持有 DOM。采样前释放操作连接,
  166. // 重连后先采堆,不执行页面脚本;不清除或修改任何产品引用。
  167. if (returnToDraft) {
  168. await cdp.detach();
  169. await browser.close();
  170. }
  171. // 只在测试等待既有 30s keep-warm 到期;不改变产品回收策略。
  172. await pause(35_000);
  173. if (returnToDraft) {
  174. browser = await chromium.connectOverCDP(endpoint);
  175. page = rendererPage(browser);
  176. cdp = await page.context().newCDPSession(page);
  177. await cdp.send("HeapProfiler.enable");
  178. }
  179. await cdp.send("Runtime.discardConsoleEntries");
  180. await cdp.send("HeapProfiler.collectGarbage");
  181. await pause(300);
  182. await cdp.send("HeapProfiler.collectGarbage");
  183. const usage = await cdp.send("Runtime.getHeapUsage");
  184. const path = join(output, `${name}.heapsnapshot`);
  185. const stream = createWriteStream(path);
  186. const chunk = ({ chunk }: { chunk: string }) => {
  187. stream.write(chunk);
  188. };
  189. cdp.on("HeapProfiler.addHeapSnapshotChunk", chunk);
  190. try {
  191. await cdp.send("HeapProfiler.takeHeapSnapshot", {
  192. reportProgress: false,
  193. captureNumericValue: true,
  194. });
  195. } finally {
  196. cdp.off("HeapProfiler.addHeapSnapshotChunk", chunk);
  197. await new Promise<void>((resolve, reject) => {
  198. stream.on("error", reject);
  199. stream.end(resolve);
  200. });
  201. }
  202. const counts = await countRetainedHistory(
  203. path,
  204. returnToDraft ? "draft" : `${prefix}0`,
  205. sourceMapPath,
  206. );
  207. const sample = { name, switches, heapMiB: usage.usedSize / 1048576, ...counts };
  208. measurements.push(sample);
  209. await writeFile(join(output, "measurements.json"), JSON.stringify(measurements, null, 2));
  210. await page.screenshot({ path: join(output, `${name}.png`) });
  211. console.log(JSON.stringify(sample));
  212. }
  213. if (sameWorkspace) {
  214. const idle = measurements.find((sample) => sample.name === "idle-control")!.callbacks!;
  215. const roundtrips = measurements.at(-1)!.callbacks!;
  216. for (const sample of measurements) {
  217. assert.equal(sample.callbacks!.onFocus, 1, `${sample.name}: onFocus 回调累积`);
  218. assert.deepEqual(
  219. sample.callbacks!.lexicalUpdateListeners,
  220. measurements[0]!.callbacks!.lexicalUpdateListeners,
  221. `${sample.name}: Lexical listener 累积`,
  222. );
  223. }
  224. // 相同草稿表面允许 React alternate 多持有一份,不能按往返次数保留旧 render 链。
  225. assert(roundtrips.prewarmWaiter <= idle.prewarmWaiter + 1, "预热等待回调随往返累积");
  226. assert(roundtrips.fileLink <= idle.fileLink + 1, "旧页面文件链接回调随往返累积");
  227. }
  228. // 先收齐全部检查点及闲置对照,红灯时也保留完整曲线和堆快照。
  229. for (const sample of measurements) {
  230. // SPR03 中间返回草稿时,当前编辑器的 slash 回调可能仍持有上一页闭包;
  231. // 它不属于预热注册表。保留中间证据,最终与闲置对照都必须真正释放历史。
  232. if (sameWorkspace || !crossWorkspace || sample.switches === 32) {
  233. assert.equal(sample.inactiveSnapshots, 0, `${sample.name}: 非当前会话 snapshot 未释放`);
  234. assert.equal(sample.closedStores, 0, `${sample.name}: 已关闭 store 未释放`);
  235. }
  236. assert.equal(
  237. sample.liveStores,
  238. returnToDraft ? 0 : 1,
  239. `${sample.name}: 历史 store 数量错误`,
  240. );
  241. if (returnToDraft) {
  242. assert.equal(
  243. sample.inactivePrewarmCoordinators,
  244. 0,
  245. `${sample.name}: 空闲预热 owner 未释放`,
  246. );
  247. }
  248. }
  249. } finally {
  250. if (browser.isConnected()) {
  251. await cdp.send("HeapProfiler.disable");
  252. await cdp.detach();
  253. }
  254. }
  255. } finally {
  256. await browser.close();
  257. }
  258. },
  259. );