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

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