conversation-session-git-review-entry.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import { open, utimes, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. TID_CHAT_SUMMARY_PANEL,
  5. TID_GIT_PANE,
  6. TID_TASK_ITEM,
  7. testId,
  8. } from "@zcode/shared";
  9. import type { ChainablePromiseElement } from "webdriverio";
  10. import {
  11. DEFAULT_WORKSPACE,
  12. clearAppData,
  13. waitForTestIdByDom,
  14. waitForWorkspaceApp,
  15. } from "../../../helpers/desktop-app.js";
  16. import { PROVIDER_READINESS_HISTORY_SESSION_ID } from "../../../helpers/provider-readiness-history-fixture.js";
  17. import { selectV4TaskById } from "../../../helpers/v4-conversation.js";
  18. const CASE_TIMEOUT_MS = 120_000;
  19. const FILE_NAME = "status-panel-review.txt";
  20. const CHANGES_LABELS = ["Changes", "更改"];
  21. const EXPAND_LABELS = ["Expand status", "展开状态"];
  22. const UNSTAGED_LABELS = ["Unstaged", "未暂存"];
  23. describe("SP13:status panel Git Changes 打开变更审阅", () => {
  24. after(async () => {
  25. await browser.electron.restoreAllMocks();
  26. await clearAppData();
  27. });
  28. it("点击 Changes 后打开 Git pane、选择 unstaged 并显示目标文件", async function () {
  29. this.timeout(CASE_TIMEOUT_MS);
  30. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
  31. await waitForTestIdByDom(
  32. testId(TID_TASK_ITEM, PROVIDER_READINESS_HISTORY_SESSION_ID),
  33. {
  34. timeout: 30_000,
  35. timeoutMsg: "SP13 预置的只读历史 session 没有出现在任务列表",
  36. },
  37. );
  38. await selectV4TaskById(PROVIDER_READINESS_HISTORY_SESSION_ID);
  39. await waitForExpandedStatusPanel();
  40. expect(await isGitPaneMounted()).toBe(false);
  41. await clickStatusPanelChanges();
  42. const review = await waitForGitReview();
  43. expect(UNSTAGED_LABELS).toContain(review.sourceLabel);
  44. expect(review.text).toContain(FILE_NAME);
  45. expect(review.rowCount).toBeGreaterThan(0);
  46. });
  47. it("Git 自动刷新跳过超限行数统计且 Host 内存有界", async function () {
  48. this.timeout(CASE_TIMEOUT_MS);
  49. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
  50. await selectV4TaskById(PROVIDER_READINESS_HISTORY_SESSION_ID);
  51. await waitForExpandedStatusPanel();
  52. // 通过真实文件 watcher 刷新;无需打开 Git pane,也不创建会话或调用模型。
  53. const caseRoot = join(DEFAULT_WORKSPACE, ".zcode-e2e/conversation-session-git-review-entry");
  54. const largeText = "large-untracked.txt";
  55. await browser.electron.execute((electron) => {
  56. const state = globalThis as typeof globalThis & {
  57. gitMemoryProbe?: { baseline: number; peak: number; timer: ReturnType<typeof setInterval> };
  58. };
  59. const readHostKb = () =>
  60. electron.app
  61. .getAppMetrics()
  62. .filter((metric) => metric.name?.startsWith("zcode-host"))
  63. .reduce((total, metric) => total + metric.memory.workingSetSize, 0);
  64. const baseline = readHostKb();
  65. if (!baseline) throw new Error("没有找到待采样的真实 Host 进程");
  66. const probe = {
  67. baseline,
  68. peak: baseline,
  69. timer: setInterval(() => {
  70. probe.peak = Math.max(probe.peak, readHostKb());
  71. }, 25),
  72. };
  73. state.gitMemoryProbe = probe;
  74. });
  75. try {
  76. await writeFile(join(caseRoot, largeText), "line\n".repeat(300_000));
  77. for (let index = 0; index < 8; index++) {
  78. const file = await open(join(caseRoot, `large-${index}.bin`), "w");
  79. try {
  80. await file.truncate(32 * 1024 * 1024);
  81. } finally {
  82. await file.close();
  83. }
  84. }
  85. await writeFile(join(caseRoot, FILE_NAME), "one\ntwo\nthree\nfour\n");
  86. // Linux 只监听 Git 元数据;触发同一自动刷新入口,避免依赖递归文件监听。
  87. const changedAt = new Date();
  88. await utimes(join(DEFAULT_WORKSPACE, ".git", "HEAD"), changedAt, changedAt);
  89. await browser.waitUntil(
  90. async () => {
  91. const changes = await findButtonByLabels(
  92. $(`[data-testid="${TID_CHAT_SUMMARY_PANEL}"]`),
  93. CHANGES_LABELS,
  94. );
  95. return Boolean(changes && /\+4\s+-0/u.test(await changes.getText()));
  96. },
  97. // 产品的 watcher 防抖为 60 秒;等到新快照后才判断内存。
  98. {
  99. timeout: 90_000,
  100. interval: 500,
  101. timeoutMsg: "自动刷新应更新小文件为 +4,大文本不应计入行数",
  102. },
  103. );
  104. } finally {
  105. const memory = await browser.electron.execute(() => {
  106. const state = globalThis as typeof globalThis & {
  107. gitMemoryProbe?: {
  108. baseline: number;
  109. peak: number;
  110. timer: ReturnType<typeof setInterval>;
  111. };
  112. };
  113. const probe = state.gitMemoryProbe;
  114. if (!probe) throw new Error("Host 内存探针不存在");
  115. clearInterval(probe.timer);
  116. delete state.gitMemoryProbe;
  117. return {
  118. baselineKb: probe.baseline,
  119. peakKb: probe.peak,
  120. deltaKb: probe.peak - probe.baseline,
  121. };
  122. });
  123. console.log("[git-untracked-memory]", JSON.stringify(memory));
  124. // 256 MiB 文件应在读取前跳过;为真实 Electron 噪声留出 96 MiB 余量。
  125. expect(memory.deltaKb).toBeLessThan(96 * 1024);
  126. }
  127. });
  128. });
  129. async function waitForExpandedStatusPanel() {
  130. await waitForTestIdByDom(TID_CHAT_SUMMARY_PANEL, {
  131. timeout: 30_000,
  132. timeoutMsg: "SP13 未显示包含 Git Tools 的 status panel",
  133. });
  134. const panel = $(`[data-testid="${TID_CHAT_SUMMARY_PANEL}"]`);
  135. if ((await panel.getAttribute("data-state")) !== "expanded") {
  136. const expandButton = await findButtonByLabels(panel, EXPAND_LABELS);
  137. if (!expandButton) {
  138. throw new Error("SP13 status panel 处于收起态,但没有可点击的展开入口");
  139. }
  140. await expandButton.click();
  141. }
  142. await browser.waitUntil(
  143. async () =>
  144. (await panel.getAttribute("data-state")) === "expanded" &&
  145. Boolean(await findButtonByLabels(panel, CHANGES_LABELS)),
  146. {
  147. timeout: 30_000,
  148. timeoutMsg: "SP13 status panel 展开后没有可点击的 Changes / 更改入口",
  149. },
  150. );
  151. }
  152. async function clickStatusPanelChanges() {
  153. const panel = $(`[data-testid="${TID_CHAT_SUMMARY_PANEL}"]`);
  154. const changesButton = await findButtonByLabels(panel, CHANGES_LABELS);
  155. if (!changesButton) {
  156. throw new Error("SP13 没有找到 Changes / 更改按钮");
  157. }
  158. expect(await changesButton.isEnabled()).toBe(true);
  159. await changesButton.click();
  160. }
  161. async function findButtonByLabels(
  162. root: ChainablePromiseElement,
  163. labels: readonly string[],
  164. ) {
  165. const buttons = await root.$$("button");
  166. for (const button of buttons) {
  167. const text = (await button.getText()).trim();
  168. const firstLine = text.split(/\r?\n/u, 1)[0] ?? "";
  169. const ariaLabel = (await button.getAttribute("aria-label"))?.trim() ?? "";
  170. if (
  171. labels.some(
  172. (label) => ariaLabel === label || firstLine === label,
  173. )
  174. ) {
  175. return button;
  176. }
  177. }
  178. return null;
  179. }
  180. function isGitPaneMounted() {
  181. return browser.execute(
  182. (gitPaneTestId) =>
  183. Boolean(document.querySelector(`[data-testid="${gitPaneTestId}"]`)),
  184. TID_GIT_PANE,
  185. );
  186. }
  187. interface GitReviewSnapshot {
  188. rowCount: number;
  189. sourceLabel: string;
  190. text: string;
  191. }
  192. async function waitForGitReview() {
  193. let latest: GitReviewSnapshot | null = null;
  194. try {
  195. await browser.waitUntil(
  196. async () => {
  197. latest = await readGitReviewSnapshot();
  198. return (
  199. UNSTAGED_LABELS.includes(latest.sourceLabel) &&
  200. latest.text.includes(FILE_NAME) &&
  201. latest.rowCount > 0
  202. );
  203. },
  204. {
  205. timeout: 30_000,
  206. timeoutMsg: "SP13 Git review 没有显示 unstaged 目标文件",
  207. },
  208. );
  209. } catch (error) {
  210. latest = await readGitReviewSnapshot().catch(() => latest);
  211. throw new Error(
  212. `SP13 Git review 断言失败: ${JSON.stringify(latest)}`,
  213. { cause: error },
  214. );
  215. }
  216. return readGitReviewSnapshot();
  217. }
  218. function readGitReviewSnapshot(): Promise<GitReviewSnapshot> {
  219. return browser.execute((gitPaneTestId) => {
  220. const pane = document.querySelector<HTMLElement>(
  221. `[data-testid="${gitPaneTestId}"]`,
  222. );
  223. const sourceTrigger = pane?.querySelector<HTMLElement>(
  224. '[data-slot="select-trigger"]',
  225. );
  226. return {
  227. rowCount:
  228. pane?.querySelectorAll("[data-git-pane-change-virtual-row]").length ?? 0,
  229. sourceLabel: sourceTrigger?.textContent?.trim() ?? "",
  230. text: pane?.innerText ?? "",
  231. };
  232. }, TID_GIT_PANE);
  233. }