conversation-session-workspace-zcodeignore.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { DEFAULT_WORKSPACE } from "../../../helpers/desktop-app.js";
  4. import { skipOccupationOnboardingIfPresent } from "../../../helpers/occupation-onboarding.js";
  5. import {
  6. prepareConversationE2E,
  7. startNewTask,
  8. typeChatPrompt,
  9. } from "../../../helpers/conversation-session.js";
  10. // gitignore 解析按行识别,行尾风格不影响规则;统一写 \n 避免 e2e 源码里出现跨行字面量。
  11. const LINE_SEP = "\n";
  12. // E2E case for .zcodeignore 单一真相源(spec 2026-08-07 2026-09-15 增补,ZCT-2096811705629528064)。
  13. // 验证真实 Electron Desktop 上的完整交互链路:
  14. // 1. workspace 存在 .gitignore(含 obj/) 时,@ 扫描仅在内存中加载规则,不创建 .zcodeignore,
  15. // obj/ 整棵剪枝,obj 下文件不可搜;
  16. // 2. 手动创建 .zcodeignore 放开排除规则(设置入口当前隐藏,文件编辑是真实用户路径),
  17. // 关闭重开 @ 面板重扫后,obj 下文件恢复可搜。
  18. // 过滤 authority 在 services 层 fileService.listWorkspaceFiles;本 spec 只取证用户可见矩阵。
  19. const TEST_TIMEOUT_MS = 180000;
  20. const TID_PROMPT_SUGGESTION_PANEL = "prompt-suggestion-panel";
  21. const TID_PROMPT_SUGGESTION_OPTION = "prompt-suggestion-option";
  22. const TID_PROMPT_SUGGESTION_STATUS = "prompt-suggestion-status";
  23. interface PanelOptionSnapshot {
  24. id: string | null;
  25. index: number;
  26. sectionId: string | null;
  27. selected: boolean;
  28. text: string;
  29. }
  30. interface PanelSnapshot {
  31. options: PanelOptionSnapshot[];
  32. statuses: Array<{ sectionId: string | null; status: string | null; text: string }>;
  33. trigger: string | null;
  34. }
  35. // seed 产生的待清理状态:新目录 + 手动创建的 .zcodeignore + .gitignore 的原内容恢复。
  36. let seededDirs: string[] = [];
  37. let createdZcodeIgnore = false;
  38. let originalGitignore: string | null = null;
  39. describe("会话区 .zcodeignore 工作区搜索忽略规则 E2E", () => {
  40. before(async function () {
  41. this.timeout(TEST_TIMEOUT_MS);
  42. // 新隔离 profile 会先显示职业引导,完成后才能进入文件搜索场景。
  43. await skipOccupationOnboardingIfPresent();
  44. await prepareConversationE2E();
  45. });
  46. beforeEach(async function () {
  47. this.timeout(TEST_TIMEOUT_MS);
  48. await startNewTask();
  49. });
  50. after(async () => {
  51. await Promise.all(seededDirs.map((dir) => rm(dir, { recursive: true, force: true })));
  52. seededDirs = [];
  53. if (createdZcodeIgnore) {
  54. await rm(join(DEFAULT_WORKSPACE, ".zcodeignore"), { force: true });
  55. createdZcodeIgnore = false;
  56. }
  57. const gitignorePath = join(DEFAULT_WORKSPACE, ".gitignore");
  58. if (originalGitignore === null) {
  59. await rm(gitignorePath, { force: true });
  60. } else {
  61. await writeFile(gitignorePath, originalGitignore, "utf-8");
  62. }
  63. originalGitignore = null;
  64. await browser.electron.restoreAllMocks();
  65. });
  66. it("@ 按内存规则剪枝且不创建 .zcodeignore;手动规则文件仍生效", async function () {
  67. this.timeout(TEST_TIMEOUT_MS);
  68. const runId = Date.now();
  69. const marker = `zci-e2e-${runId}`;
  70. const objFileRelPath = join("obj", "Debug", `${marker}.cs`);
  71. const srcFileRelPath = join("src", `${marker}.ts`);
  72. // seed:合并写入 .gitignore(保留原内容,after 恢复),obj 与 src 各放一个 marker 文件。
  73. const gitignorePath = join(DEFAULT_WORKSPACE, ".gitignore");
  74. originalGitignore = await readFile(gitignorePath, "utf-8").catch(() => null);
  75. const baseGitignore = originalGitignore ?? "";
  76. if (!/^obj\/$/m.test(baseGitignore)) {
  77. await writeFile(gitignorePath, `${baseGitignore}${baseGitignore.endsWith("\n") || !baseGitignore ? "" : "\n"}obj/\n`, "utf-8");
  78. }
  79. const objDir = join(DEFAULT_WORKSPACE, "obj");
  80. const srcDir = join(DEFAULT_WORKSPACE, "src");
  81. await mkdir(join(objDir, "Debug"), { recursive: true });
  82. await mkdir(srcDir, { recursive: true });
  83. await writeFile(join(DEFAULT_WORKSPACE, objFileRelPath), `// ${marker}\n`, "utf-8");
  84. await writeFile(join(DEFAULT_WORKSPACE, srcFileRelPath), `// ${marker}\n`, "utf-8");
  85. seededDirs.push(objDir, srcDir);
  86. // 1) 默认剪枝:src marker 可搜(证明面板与索引正常),obj/Debug 不可搜(内存规则生效)。
  87. await typeChatPrompt(`@${marker}`);
  88. const visiblePanel = await waitForPanelSections("@", ["files"], "@ 文件候选面板没有打开");
  89. expect(visiblePanel.options.map((o) => o.text).join("\n")).toContain(`${marker}.ts`);
  90. await typeChatPrompt(`@${marker}.cs`);
  91. await waitForPanelNoOptionContaining("obj/Debug", "obj/ 下被忽略文件不应进入候选");
  92. // 管理入口隐藏期间,搜索不应自动在工作区创建配置文件。
  93. const zcodeIgnorePath = join(DEFAULT_WORKSPACE, ".zcodeignore");
  94. await expect(stat(zcodeIgnorePath)).rejects.toMatchObject({ code: "ENOENT" });
  95. // 2) 手动创建规则文件放开 obj/:设置入口当前隐藏(HIDDEN_SETTINGS_SECTIONS),
  96. // 真实用户路径是直接编辑 .zcodeignore;写入空规则等价于"删除全部排除规则"。
  97. // 用数组 join 写出字面 "\n" 结尾内容,避免字符串字面量跨行。
  98. await writeFile(zcodeIgnorePath, ["# emptied by e2e", ""].join(LINE_SEP), "utf-8");
  99. createdZcodeIgnore = true;
  100. // 3) 规则放开生效:先输入普通文本关闭 @ 面板(本地 30s TTL 缓存已移除——面板
  101. // 关闭即清理、重新打开必然重扫,spec 2026-08-26 2026-09-15 更新),随后刻意复用
  102. // 与第二步完全相同的 query 验证新规则:若缓存语义回退(miss-refresh 防重复会挡掉
  103. // 同 query 重扫),本断言将失败,形成回归保护。
  104. // 注意不能省略关闭步骤:第二步的 @ query 文本仍在输入框里,面板
  105. // enabled 从未变 false,不经历"关闭→重开"周期就不会重新读取索引。
  106. // 同会话第二次打开面板时 plugins/skills 分区已缓存就绪,故只断言 files 分区包含目标。
  107. await typeChatPrompt("refresh-panel");
  108. await typeChatPrompt(`@${marker}.cs`);
  109. await waitForPanelFilesOptionContaining(
  110. `${marker}.cs`,
  111. "删除规则后 obj/Debug 下文件未恢复可搜",
  112. );
  113. });
  114. });
  115. // 与 filter spec 相同的正向断言:面板 trigger 命中、files 分区出现且候选非空。
  116. async function waitForPanelSections(
  117. trigger: string,
  118. expectedSectionIds: string[],
  119. timeoutMsg: string,
  120. ) {
  121. let latest: PanelSnapshot | null = null;
  122. await browser.waitUntil(
  123. async () => {
  124. latest = await getPanelSnapshot();
  125. return (
  126. latest.trigger === trigger &&
  127. latest.options.length > 0 &&
  128. arraysEqual(optionSectionIds(latest), expectedSectionIds)
  129. );
  130. },
  131. { timeout: 15000, timeoutMsg },
  132. );
  133. return latest ?? getPanelSnapshot();
  134. }
  135. function optionSectionIds(snapshot: PanelSnapshot): string[] {
  136. return Array.from(new Set(snapshot.options.map((option) => option.sectionId ?? "?")));
  137. }
  138. // 等待 files 分区出现包含 needle 的候选;不限制其他分区是否同时可见。
  139. async function waitForPanelFilesOptionContaining(needle: string, timeoutMsg: string) {
  140. await browser.waitUntil(
  141. async () => {
  142. const snapshot = await getPanelSnapshot();
  143. if (snapshot.trigger !== "@") {
  144. return false;
  145. }
  146. return snapshot.options
  147. .filter((option) => option.sectionId === "files")
  148. .some((option) => option.text.includes(needle));
  149. },
  150. { timeout: 15000, timeoutMsg },
  151. );
  152. }
  153. function arraysEqual(left: string[], right: string[]) {
  154. return left.length === right.length && left.every((value, index) => value === right[index]);
  155. }
  156. // 与 filter spec 相同的排除断言:连续两帧面板快照一致后,files 候选不得包含 needle。
  157. async function waitForPanelNoOptionContaining(needle: string, timeoutMsg: string) {
  158. let previous: PanelSnapshot | null = null;
  159. let stable: PanelSnapshot | null = null;
  160. await browser.waitUntil(
  161. async () => {
  162. const snapshot = await getPanelSnapshot();
  163. const signature = panelSignature(snapshot);
  164. const previousSignature = previous ? panelSignature(previous) : null;
  165. previous = snapshot;
  166. if (previousSignature !== null && previousSignature === signature) {
  167. stable = snapshot;
  168. return true;
  169. }
  170. return false;
  171. },
  172. { timeout: 15000, timeoutMsg: `${timeoutMsg}(候选面板持续抖动,无法判定稳定终态)` },
  173. );
  174. const finalSnapshot = stable ?? previous ?? (await getPanelSnapshot());
  175. const finalTexts = finalSnapshot.options
  176. .filter((option) => option.sectionId === "files")
  177. .map((option) => option.text);
  178. if (finalTexts.some((text) => text.includes(needle))) {
  179. throw new Error(
  180. `${timeoutMsg}(needle="${needle}",实际 files 候选:${JSON.stringify(finalTexts)})`,
  181. );
  182. }
  183. }
  184. function panelSignature(snapshot: PanelSnapshot): string {
  185. const filesStatuses = snapshot.statuses
  186. .filter((entry) => entry.sectionId === "files")
  187. .map((entry) => `${entry.status ?? "?"}:${entry.text}`)
  188. .join("|");
  189. const filesOptions = snapshot.options
  190. .filter((option) => option.sectionId === "files")
  191. .map((option) => option.text)
  192. .join("|");
  193. return `trigger=${snapshot.trigger ?? "?"};filesStatus=${filesStatuses};filesOptions=${filesOptions}`;
  194. }
  195. function getPanelSnapshot(): Promise<PanelSnapshot> {
  196. return browser.execute(
  197. (panelTestId, optionPrefix, statusPrefix) => {
  198. const panel = document.querySelector<HTMLElement>(`[data-testid="${panelTestId}"]`);
  199. const options = Array.from(
  200. panel?.querySelectorAll<HTMLElement>(`[data-testid^="${optionPrefix}-"]`) ?? [],
  201. ).map((element) => ({
  202. id: element.getAttribute("data-option-id"),
  203. index: Number(element.getAttribute("data-option-index") ?? "0"),
  204. sectionId: element.getAttribute("data-section-id"),
  205. selected: element.getAttribute("data-selected") === "true",
  206. text: (element.innerText || element.textContent || "").replace(/\u00a0/g, " ").trim(),
  207. }));
  208. const statuses = Array.from(
  209. panel?.querySelectorAll<HTMLElement>(`[data-testid^="${statusPrefix}-"]`) ?? [],
  210. ).map((element) => ({
  211. sectionId: element.getAttribute("data-section-id"),
  212. status: element.getAttribute("data-status"),
  213. text: (element.innerText || element.textContent || "").replace(/\u00a0/g, " ").trim(),
  214. }));
  215. return {
  216. options,
  217. statuses,
  218. trigger: panel?.getAttribute("data-trigger") ?? null,
  219. };
  220. },
  221. TID_PROMPT_SUGGESTION_PANEL,
  222. TID_PROMPT_SUGGESTION_OPTION,
  223. TID_PROMPT_SUGGESTION_STATUS,
  224. );
  225. }