conversation-session-sidebar-selection-rendering.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { ServiceChannels } from "@zcode/shared";
  4. import { clearAppData, DEFAULT_WORKSPACE, waitForWorkspaceApp } from "#e2e/helpers/desktop-app";
  5. import { openProjectFileTree, startDraftFromProject } from "#e2e/helpers/project-sidebar";
  6. import {
  7. prepareV4ConversationE2E,
  8. sendV4Prompt,
  9. selectV4TaskById,
  10. waitForV4ConversationState,
  11. waitForV4TimelineContaining,
  12. } from "#e2e/helpers/v4-conversation";
  13. import {
  14. installHandoffRpcProbe,
  15. callHandoffHost,
  16. restoreHandoffProbes,
  17. } from "#e2e/helpers/remote-project-handoff-probe";
  18. // 生产 bundle 会压缩函数名;按生产组件的独有 props 形状识别内容层,不依赖函数名。
  19. // 在 React 启动前装配只读 commit hook;同一 Fiber 的 bailout 不重复计数。
  20. const probe = `(() => {
  21. const seen = new WeakMap();
  22. const sample = window.__sidebarSelection = { projects: {}, rows: {}, unmounts: 0, changes: [] };
  23. const kind = f => typeof f.type === 'function' && (f.memoizedProps?.project &&
  24. 'setActivatorNodeRef' in f.memoizedProps && 'editable' in f.memoizedProps ? 'projects' :
  25. f.memoizedProps?.task && 'showFiles' in f.memoizedProps && 'variant' in f.memoizedProps ? 'rows' : null);
  26. window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
  27. supportsFiber: true, inject: () => 1,
  28. onCommitFiberUnmount(_id, f) { if (kind(f)) sample.unmounts++; },
  29. onCommitFiberRoot(_id, root) {
  30. const walk = f => {
  31. if (!f) return;
  32. const group = kind(f);
  33. if (group) {
  34. const previous = seen.get(f) || seen.get(f.alternate);
  35. if (f.flags & 1 && previous !== f) {
  36. const p = f.memoizedProps;
  37. const key = group === 'projects' ? p.project.id : (p.task.workspaceIdentity || p.task.workspacePath) + ':' + p.task.taskId;
  38. sample[group][key] = (sample[group][key] || 0) + 1;
  39. if (group === 'projects') {
  40. const old = f.alternate?.memoizedProps || {};
  41. sample.changes.push({ key, props: Object.keys(p).filter(k => !Object.is(p[k], old[k])),
  42. tasks: (p.tasks || []).map(task => {
  43. const previous = (old.tasks || []).find(t => t.taskId === task.taskId);
  44. return { id: task.taskId, unreadBefore: previous?.unreadAt ?? null, unreadAfter: task.unreadAt ?? null,
  45. fields: [...new Set([...Object.keys(task), ...Object.keys(previous || {})])].filter(k => !Object.is(task[k], previous?.[k])) };
  46. }).filter(t => t.fields.length) });
  47. }
  48. }
  49. seen.set(f, f); if(f.alternate) seen.set(f.alternate, f);
  50. }
  51. walk(f.child); walk(f.sibling);
  52. }; walk(root.current);
  53. }
  54. };
  55. })()`;
  56. type ProjectChange = {
  57. key: string;
  58. props: string[];
  59. tasks: {
  60. id: string;
  61. fields: string[];
  62. unreadBefore: number | null;
  63. unreadAfter: number | null;
  64. }[];
  65. };
  66. type Counts = {
  67. projects: Record<string, number>;
  68. rows: Record<string, number>;
  69. unmounts: number;
  70. changes: ProjectChange[];
  71. };
  72. const readCounts = () =>
  73. browser.execute(() => structuredClone((window as any).__sidebarSelection) as Counts);
  74. const changed = (before: Record<string, number>, after: Record<string, number>) =>
  75. Object.keys(after)
  76. .filter((key) => after[key] !== before[key])
  77. .sort();
  78. async function enableProbe() {
  79. await browser.electron.execute(async (electron, source) => {
  80. const target = electron.BrowserWindow.getAllWindows().find((win) =>
  81. win.webContents.getURL().includes("/renderer/index.html"),
  82. );
  83. if (!target) throw new Error("Renderer unavailable");
  84. const debug = target.webContents.debugger;
  85. if (!debug.isAttached()) debug.attach("1.3");
  86. await debug.sendCommand("Page.enable");
  87. await debug.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source });
  88. target.webContents.reload();
  89. }, probe);
  90. // reload 发起后立即 detach 会清掉 CDP 的预注入脚本;确认新文档已装配后再释放。
  91. await browser.waitUntil(
  92. () => browser.execute(() => Boolean((window as any).__sidebarSelection)),
  93. {
  94. timeout: 30000,
  95. timeoutMsg: "The renderer must install the commit probe before React starts",
  96. },
  97. );
  98. await browser.electron.execute((electron) => {
  99. const target = electron.BrowserWindow.getAllWindows().find((win) =>
  100. win.webContents.getURL().includes("/renderer/index.html"),
  101. );
  102. target?.webContents.debugger.detach();
  103. });
  104. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45000);
  105. await browser.waitUntil(async () => Object.keys((await readCounts()).projects).length >= 44, {
  106. timeout: 30000,
  107. timeoutMsg: "44 project content instances must be observed before measurement",
  108. });
  109. }
  110. const out = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  111. describe("SPT08 full App session selection rendering", () => {
  112. after(async () => {
  113. await restoreHandoffProbes();
  114. await clearAppData();
  115. });
  116. it("switches real sessions without rerendering unrelated projects or rows", async function () {
  117. this.timeout(180000);
  118. await mkdir(out, { recursive: true });
  119. await prepareV4ConversationE2E();
  120. const ids: string[] = [];
  121. for (let index = 0; index < 3; index++) {
  122. // 首条也从项目入口创建;全局初始草稿可能未归类,新建时会合法切到另一目录。
  123. await startDraftFromProject(DEFAULT_WORKSPACE);
  124. await sendV4Prompt(`E2E_SPT08_SESSION_SEED_${index}`);
  125. await waitForV4TimelineContaining("SPT08_SESSION_READY", 45000);
  126. const state = await waitForV4ConversationState(
  127. (state) => Boolean(state.taskId) && state.state === "idle",
  128. "seed completed",
  129. 45000,
  130. );
  131. ids.push(state.taskId!);
  132. }
  133. await installHandoffRpcProbe();
  134. const seededTree = await callHandoffHost<{
  135. tasks: { taskId: string; projectId?: string | null }[];
  136. }>(ServiceChannels.Project, "readTree", []);
  137. for (const id of ids)
  138. expect(seededTree.tasks.find((task) => task.taskId === id)?.projectId).toBeTruthy();
  139. // 额外项目通过真实 Host 命令准备,保持模型会话、目录广播与导航 owner 不变。
  140. for (let index = 0; index < 44; index++)
  141. await callHandoffHost(ServiceChannels.Project, "saveProject", [
  142. {
  143. name: `SPT08 Project ${index}`,
  144. roots: [],
  145. },
  146. ]);
  147. await restoreHandoffProbes();
  148. await enableProbe();
  149. const evidence: unknown[] = [];
  150. const alreadyRead = new Set<string>();
  151. try {
  152. for (const theme of ["zai-light", "zai-dark"]) {
  153. await browser.execute((value) => (window as any).__testActions.setTheme(value), theme);
  154. await startDraftFromProject(DEFAULT_WORKSPACE);
  155. // 采样窗口用于让草稿初始化收口,不参与产品状态同步,也不判定性能耗时。
  156. await browser.pause(700);
  157. let before = await readCounts();
  158. let previous: string | null = null;
  159. for (const id of [ids[0]!, ids[1]!, ids[0]!, ids[1]!, ids[0]!]) {
  160. await selectV4TaskById(id);
  161. await waitForV4ConversationState(
  162. (state) => state.taskId === id && state.state === "idle",
  163. "selected session ready",
  164. 30000,
  165. );
  166. await browser.pause(300);
  167. const after = await readCounts();
  168. const sample = {
  169. theme,
  170. id,
  171. projects: changed(before.projects, after.projects),
  172. rows: changed(before.rows, after.rows),
  173. unmounts: after.unmounts - before.unmounts,
  174. changes: after.changes.slice(before.changes.length),
  175. };
  176. evidence.push(sample);
  177. // 首次打开未读会话会清除 Host 的 unreadAt;它只应更新所属项目。
  178. // 同一会话再次切换已无数据变化,项目内容必须零更新,不能吞掉真实未读更新来过断言。
  179. if (alreadyRead.has(id)) expect(sample.projects).toEqual([]);
  180. for (const change of sample.changes) {
  181. expect(change.tasks).toHaveLength(1);
  182. expect(change.tasks[0]).toMatchObject({ id, unreadAfter: null });
  183. expect(typeof change.tasks[0]!.unreadBefore).toBe("number");
  184. expect(change.tasks[0]!.fields).toContain("unreadAt");
  185. }
  186. expect(sample.rows).toEqual(
  187. [
  188. ...(previous ? [`${DEFAULT_WORKSPACE}:${previous}`] : []),
  189. `${DEFAULT_WORKSPACE}:${id}`,
  190. ].sort(),
  191. );
  192. expect(sample.unmounts).toBe(0);
  193. before = after;
  194. previous = id;
  195. alreadyRead.add(id);
  196. }
  197. // 复现首次从历史会话补开 tab 后缺少分类的状态;新建入口应自行补全,不能带动全列。
  198. await browser.execute((path) => {
  199. const store = (window as any).__zcodeTabStoreE2E;
  200. store.setState((state: any) => ({
  201. tabs: state.tabs.map((tab: any) =>
  202. tab.workspacePath === path ? { ...tab, workspacePurpose: undefined } : tab,
  203. ),
  204. }));
  205. }, DEFAULT_WORKSPACE);
  206. await browser.pause(300);
  207. const beforeDraft = await readCounts();
  208. await browser.$('[data-testid="task-new-button"]').click();
  209. await waitForV4ConversationState((state) => !state.taskId, "new draft ready", 30000);
  210. await browser.waitUntil(
  211. () =>
  212. browser.execute((path) => {
  213. const state = (window as any).__zcodeTabStoreE2E.getState();
  214. return (
  215. state.tabs.find((tab: any) => tab.workspacePath === path)?.workspacePurpose ===
  216. "project"
  217. );
  218. }, DEFAULT_WORKSPACE),
  219. { timeout: 10000, timeoutMsg: "New draft must fill the workspace classification" },
  220. );
  221. await browser.pause(700);
  222. const afterDraft = await readCounts();
  223. const draftSample = {
  224. theme,
  225. id: "new-draft-with-workspace-classification",
  226. projects: changed(beforeDraft.projects, afterDraft.projects),
  227. rows: changed(beforeDraft.rows, afterDraft.rows),
  228. unmounts: afterDraft.unmounts - beforeDraft.unmounts,
  229. changes: afterDraft.changes.slice(beforeDraft.changes.length),
  230. };
  231. evidence.push(draftSample);
  232. expect(draftSample.projects).toEqual([]);
  233. expect(draftSample.rows).toEqual([`${DEFAULT_WORKSPACE}:${previous}`]);
  234. expect(draftSample.unmounts).toBe(0);
  235. await openProjectFileTree(DEFAULT_WORKSPACE);
  236. await browser.saveScreenshot(join(out, `session-selection-${theme}.png`));
  237. }
  238. } finally {
  239. await writeFile(
  240. join(out, "session-selection-rendering.json"),
  241. JSON.stringify(evidence, null, 2),
  242. );
  243. }
  244. });
  245. });