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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import { waitForControlledReplay, releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  2. import { openStatusCapsule } from "#e2e/helpers/status-capsule";
  3. import { open, rm, utimes, writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { TID_GIT_PANE, TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  6. import type { ChainablePromiseElement } from "webdriverio";
  7. import {
  8. DEFAULT_WORKSPACE,
  9. clearAppData,
  10. waitForTestIdByDom,
  11. waitForWorkspaceApp,
  12. } from "#e2e/helpers/desktop-app";
  13. import { PROVIDER_READINESS_HISTORY_SESSION_ID } from "#e2e/helpers/provider-readiness-history-fixture";
  14. import {
  15. prepareV4ConversationE2E,
  16. sendV4Prompt,
  17. waitForV4TimelineContaining,
  18. selectV4TaskById,
  19. } from "#e2e/helpers/v4-conversation";
  20. const CASE_TIMEOUT_MS = 120_000;
  21. const FILE_NAME = "status-panel-review.txt";
  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(testId(TID_TASK_ITEM, PROVIDER_READINESS_HISTORY_SESSION_ID), {
  32. timeout: 30_000,
  33. timeoutMsg: "SP13 预置的只读历史 session 没有出现在任务列表",
  34. });
  35. await selectV4TaskById(PROVIDER_READINESS_HISTORY_SESSION_ID);
  36. await waitForExpandedStatusPanel();
  37. // 连接就绪会兑现暂存的输入框聚焦;用户已打开的 Git 浮层不能因此被关闭。
  38. await browser.waitUntil(
  39. async () =>
  40. (await $('[data-testid="v4-composer-input"]').getAttribute("contenteditable")) === "true",
  41. );
  42. await browser.executeAsync((done) =>
  43. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  44. );
  45. expect(await $('[data-status-capsule-content="git"]').isDisplayed()).toBe(true);
  46. // 分支入口复用真实服务;嵌套弹层关闭后仍能继续访问 Git 操作区。
  47. const branchTrigger = await $('[data-testid="status-git-current-branch"] button');
  48. await branchTrigger.waitForDisplayed();
  49. expect(await branchTrigger.getAttribute("title")).toBeTruthy();
  50. await branchTrigger.click();
  51. await $("[cmdk-input]").waitForDisplayed();
  52. await browser.keys("Escape");
  53. await $("[cmdk-input]").waitForExist({ reverse: true });
  54. // 嵌套菜单关闭后焦点应返回分支按钮,不能迟到地跳回输入框并关闭下一次菜单。
  55. await browser.waitUntil(
  56. () =>
  57. browser.execute(
  58. () =>
  59. document.activeElement ===
  60. document.querySelector('[data-testid="status-git-current-branch"] button'),
  61. ),
  62. { timeout: 5000 },
  63. );
  64. await openStatusCapsule("git");
  65. await $('[data-testid="status-git-current-branch"] button').click();
  66. await $("[cmdk-input]").waitForDisplayed();
  67. const createAction = await findButtonByLabels(
  68. $('[data-slot="popover-content"]:has([cmdk-input])'),
  69. ["Create and switch to new branch...", "创建并检出新分支..."],
  70. );
  71. if (!createAction) throw new Error("分支菜单缺少新建分支入口");
  72. await createAction.click();
  73. await $('[role="dialog"]').waitForDisplayed();
  74. await $('[data-status-capsule-content="git"]').waitForExist({ reverse: true });
  75. await $("#git-branch-switcher-create-input").setValue("e2e-git-action-host");
  76. // 中文实际文案为“创建并切换”;使用所属表单的 submit 语义,避免语言差异误报缺失。
  77. const createSubmit = $(
  78. '[role="dialog"] form:has(#git-branch-switcher-create-input) button[type="submit"]',
  79. );
  80. await createSubmit.waitForEnabled();
  81. await createSubmit.click();
  82. await $('[role="dialog"]').waitForExist({ reverse: true });
  83. await openStatusCapsule("git");
  84. await browser.waitUntil(
  85. async () =>
  86. (await $('[data-testid="status-git-current-branch"] button').getAttribute("title")) ===
  87. "e2e-git-action-host",
  88. { timeout: 10000 },
  89. );
  90. await $('[data-testid="status-git-current-branch"] button').click();
  91. await $("[cmdk-input]").waitForDisplayed();
  92. const graphAction = await findButtonByLabels(
  93. $('[data-slot="popover-content"]:has([cmdk-input])'),
  94. ["Git graph", "Git Graph", "Git 图谱"],
  95. );
  96. if (!graphAction) throw new Error("分支菜单缺少 Git 图谱入口");
  97. await graphAction.click();
  98. await $('[role="dialog"]').waitForDisplayed();
  99. await $('[data-status-capsule-content="git"]').waitForExist({ reverse: true });
  100. await $("[cmdk-input]").waitForExist({ reverse: true });
  101. await browser.keys("Escape");
  102. await $('[role="dialog"]').waitForExist({ reverse: true });
  103. expect(await $('[data-status-capsule-content="git"]').isExisting()).toBe(false);
  104. await openStatusCapsule("git");
  105. expect(await isGitPaneMounted()).toBe(false);
  106. await clickStatusPanelChanges();
  107. const review = await waitForGitReview();
  108. expect(UNSTAGED_LABELS).toContain(review.sourceLabel);
  109. expect(review.text).toContain(FILE_NAME);
  110. expect(review.rowCount).toBeGreaterThan(0);
  111. });
  112. it("整轮成功完成后不等 watcher 防抖就刷新 Git 文件", async function () {
  113. this.timeout(CASE_TIMEOUT_MS);
  114. await prepareV4ConversationE2E();
  115. await browser.execute(() =>
  116. document
  117. .querySelector('[data-testid="v4-composer-input"]')
  118. ?.setAttribute("data-git-scope-retained", "yes"),
  119. );
  120. await sendV4Prompt("E2E_GIT_TURN_REFRESH 等待受控完成");
  121. await waitForControlledReplay("git-turn-refresh");
  122. expect(
  123. await $('[data-testid="v4-composer-input"]').getAttribute("data-git-scope-retained"),
  124. ).toBe("yes");
  125. const name = "turn-completion-refresh.txt";
  126. try {
  127. await writeFile(join(DEFAULT_WORKSPACE, name), "completed turn refresh\n", "utf8");
  128. await releaseControlledReplay("git-turn-refresh");
  129. await waitForV4TimelineContaining("E2E_GIT_TURN_DONE", 15000);
  130. await openStatusCapsule("git");
  131. await browser.waitUntil(
  132. async () => (await $('[data-status-capsule-content="git"]').getText()).includes(name),
  133. {
  134. timeout: 15000,
  135. timeoutMsg: "整轮完成后 Git 列表未及时刷新",
  136. },
  137. );
  138. } finally {
  139. await rm(join(DEFAULT_WORKSPACE, name), { force: true });
  140. }
  141. });
  142. it("Git 自动刷新跳过超限行数统计且 Host 内存有界", async function () {
  143. this.timeout(CASE_TIMEOUT_MS);
  144. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 45_000);
  145. await browser.execute(() =>
  146. document
  147. .querySelector("[data-v4-timeline-scroll]")
  148. ?.setAttribute("data-git-task-retained", "yes"),
  149. );
  150. await selectV4TaskById(PROVIDER_READINESS_HISTORY_SESSION_ID);
  151. expect(await $("[data-v4-timeline-scroll]").getAttribute("data-git-task-retained")).toBe("yes");
  152. await waitForExpandedStatusPanel();
  153. // 通过真实文件 watcher 刷新;无需打开 Git pane,也不创建会话或调用模型。
  154. const caseRoot = join(DEFAULT_WORKSPACE, ".zcode-e2e/conversation-session-git-review-entry");
  155. const largeText = "large-untracked.txt";
  156. await browser.electron.execute((electron) => {
  157. const state = globalThis as typeof globalThis & {
  158. gitMemoryProbe?: { baseline: number; peak: number; timer: ReturnType<typeof setInterval> };
  159. };
  160. const readHostKb = () =>
  161. electron.app
  162. .getAppMetrics()
  163. .filter((metric) => metric.name?.startsWith("zcode-host"))
  164. .reduce((total, metric) => total + metric.memory.workingSetSize, 0);
  165. const baseline = readHostKb();
  166. if (!baseline) throw new Error("没有找到待采样的真实 Host 进程");
  167. const probe = {
  168. baseline,
  169. peak: baseline,
  170. timer: setInterval(() => {
  171. probe.peak = Math.max(probe.peak, readHostKb());
  172. }, 25),
  173. };
  174. state.gitMemoryProbe = probe;
  175. });
  176. try {
  177. await writeFile(join(caseRoot, largeText), "line\n".repeat(300_000));
  178. for (let index = 0; index < 8; index++) {
  179. const file = await open(join(caseRoot, `large-${index}.bin`), "w");
  180. try {
  181. await file.truncate(32 * 1024 * 1024);
  182. } finally {
  183. await file.close();
  184. }
  185. }
  186. await writeFile(join(caseRoot, FILE_NAME), "one\ntwo\nthree\nfour\n");
  187. // Linux 只监听 Git 元数据;触发同一自动刷新入口,避免依赖递归文件监听。
  188. const changedAt = new Date();
  189. await utimes(join(DEFAULT_WORKSPACE, ".git", "HEAD"), changedAt, changedAt);
  190. await browser.waitUntil(
  191. async () => {
  192. const text = await $('[data-status-capsule="git"]').getText();
  193. return /\+4\s+[−-]0/u.test(text);
  194. },
  195. // 产品的 watcher 防抖为 60 秒;等到新快照后才判断内存。
  196. {
  197. timeout: 90_000,
  198. interval: 500,
  199. timeoutMsg: "自动刷新应更新小文件为 +4,大文本不应计入行数",
  200. },
  201. );
  202. } finally {
  203. const memory = await browser.electron.execute(() => {
  204. const state = globalThis as typeof globalThis & {
  205. gitMemoryProbe?: {
  206. baseline: number;
  207. peak: number;
  208. timer: ReturnType<typeof setInterval>;
  209. };
  210. };
  211. const probe = state.gitMemoryProbe;
  212. if (!probe) throw new Error("Host 内存探针不存在");
  213. clearInterval(probe.timer);
  214. delete state.gitMemoryProbe;
  215. return {
  216. baselineKb: probe.baseline,
  217. peakKb: probe.peak,
  218. deltaKb: probe.peak - probe.baseline,
  219. };
  220. });
  221. console.log("[git-untracked-memory]", JSON.stringify(memory));
  222. // 256 MiB 文件应在读取前跳过;为真实 Electron 噪声留出 96 MiB 余量。
  223. expect(memory.deltaKb).toBeLessThan(96 * 1024);
  224. }
  225. });
  226. });
  227. async function waitForExpandedStatusPanel() {
  228. await openStatusCapsule("git");
  229. }
  230. async function clickStatusPanelChanges() {
  231. // 文件数属于按钮内容,不能用完整文案定位,否则计数变化会让入口失配。
  232. const changesButton = $(
  233. '[data-status-capsule-content="git"] [data-testid="status-git-view-all"]',
  234. );
  235. await changesButton.waitForDisplayed();
  236. const actionLayout = await browser.execute(() => {
  237. const review = document.querySelector('[data-testid="status-git-view-all"]')!;
  238. const branch = document.querySelector('[data-testid="status-git-current-branch"]')!;
  239. const count = review.querySelector("span:last-child")!;
  240. const capsule = document.querySelector('[data-status-capsule="git"]')!;
  241. const trailing = branch.querySelector("[data-branch-switcher-trailing-icon]")!;
  242. return {
  243. count: count.textContent?.trim(),
  244. capsuleText: capsule.textContent,
  245. reviewFirst: Boolean(
  246. review.compareDocumentPosition(branch) & Node.DOCUMENT_POSITION_FOLLOWING,
  247. ),
  248. rightDifference: Math.abs(
  249. count.getBoundingClientRect().right - trailing.getBoundingClientRect().right,
  250. ),
  251. countColor: getComputedStyle(count).color,
  252. arrowColor: getComputedStyle(trailing).color,
  253. };
  254. });
  255. expect(Number(actionLayout.count)).toBeGreaterThan(0);
  256. expect(actionLayout.capsuleText).toContain(actionLayout.count);
  257. expect(actionLayout.reviewFirst).toBe(true);
  258. expect(actionLayout.rightDifference).toBeLessThan(2);
  259. expect(actionLayout.arrowColor).toBe(actionLayout.countColor);
  260. expect(await changesButton.isEnabled()).toBe(true);
  261. // 失败时保留真实输入和只读导航证据,区分按钮未命中、只读目录及面板状态未提交。
  262. await browser.execute(() => {
  263. const trace: string[] = [];
  264. (window as Window & { __gitReviewClickTrace?: string[] }).__gitReviewClickTrace = trace;
  265. document.addEventListener(
  266. "click",
  267. (event) => {
  268. if (trace.length < 8)
  269. trace.push((event.target as Element)?.closest("button")?.outerHTML ?? "non-button");
  270. },
  271. { capture: true },
  272. );
  273. });
  274. await changesButton.click();
  275. }
  276. async function findButtonByLabels(root: ChainablePromiseElement, labels: readonly string[]) {
  277. const buttons = await root.$$("button");
  278. for (const button of buttons) {
  279. if (!(await button.isDisplayed())) continue;
  280. const text = (await button.getText()).trim();
  281. const firstLine = text.split(/\r?\n/u, 1)[0] ?? "";
  282. const ariaLabel = (await button.getAttribute("aria-label"))?.trim() ?? "";
  283. if (labels.includes(ariaLabel || firstLine)) {
  284. return button;
  285. }
  286. }
  287. return null;
  288. }
  289. function isGitPaneMounted() {
  290. return browser.execute(
  291. (gitPaneTestId) => Boolean(document.querySelector(`[data-testid="${gitPaneTestId}"]`)),
  292. TID_GIT_PANE,
  293. );
  294. }
  295. interface GitReviewSnapshot {
  296. rowCount: number;
  297. sourceLabel: string;
  298. text: string;
  299. }
  300. async function waitForGitReview() {
  301. let latest: GitReviewSnapshot | null = null;
  302. try {
  303. await browser.waitUntil(
  304. async () => {
  305. latest = await readGitReviewSnapshot();
  306. return (
  307. UNSTAGED_LABELS.includes(latest.sourceLabel) &&
  308. latest.text.includes(FILE_NAME) &&
  309. latest.rowCount > 0
  310. );
  311. },
  312. {
  313. timeout: 30_000,
  314. timeoutMsg: "SP13 Git review 没有显示 unstaged 目标文件",
  315. },
  316. );
  317. } catch (error) {
  318. latest = await readGitReviewSnapshot().catch(() => latest);
  319. const navigation = await browser.execute(() => {
  320. const bridge = window as Window & {
  321. __gitReviewClickTrace?: string[];
  322. __zcodeTabStoreE2E?: {
  323. getState(): { tabs: unknown[]; activeWorkspacePath: string | null };
  324. };
  325. };
  326. return {
  327. clickTrace: bridge.__gitReviewClickTrace,
  328. navigation: bridge.__zcodeTabStoreE2E?.getState().tabs,
  329. activePath: bridge.__zcodeTabStoreE2E?.getState().activeWorkspacePath,
  330. interfaceMode: localStorage.getItem("zcode-interface-mode"),
  331. sidePaneTabs: [...document.querySelectorAll("[data-side-pane-tab-id]")].map((el) => ({
  332. id: el.getAttribute("data-side-pane-tab-id"),
  333. state: el.getAttribute("data-state"),
  334. text: el.textContent,
  335. })),
  336. };
  337. });
  338. throw new Error(`SP13 Git review 断言失败: ${JSON.stringify({ ...latest, navigation })}`, {
  339. cause: error,
  340. });
  341. }
  342. return readGitReviewSnapshot();
  343. }
  344. function readGitReviewSnapshot(): Promise<GitReviewSnapshot> {
  345. return browser.execute((gitPaneTestId) => {
  346. const pane = document.querySelector<HTMLElement>(`[data-testid="${gitPaneTestId}"]`);
  347. const sourceTrigger = pane?.querySelector<HTMLElement>('[data-slot="select-trigger"]');
  348. return {
  349. rowCount: pane?.querySelectorAll("[data-git-pane-change-virtual-row]").length ?? 0,
  350. sourceLabel: sourceTrigger?.textContent?.trim() ?? "",
  351. text: pane?.innerText ?? "",
  352. };
  353. }, TID_GIT_PANE);
  354. }