conversation-session-r3-hooks-local-scope.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import { access, mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { basename, join, resolve } from "node:path";
  3. import {
  4. TID_SETTINGS_PAGE,
  5. TID_SETTINGS_SECTION_NAV,
  6. TID_TASK_SETTINGS_BUTTON,
  7. testId,
  8. } from "@zcode/shared/test-ids";
  9. import {
  10. clearAppData,
  11. clickTestIdByDom,
  12. DEFAULT_WORKSPACE,
  13. waitForTestIdByDom,
  14. } from "#e2e/helpers/desktop-app";
  15. import {
  16. clickLastEnabledSSHDialogButton,
  17. completeSSHProjectConnection,
  18. fillSSHPasswordSettings,
  19. openSSHRemoteDialog,
  20. prepareSSHConnectionPage,
  21. readSSHRuntimeConfig,
  22. runSSHCommand,
  23. } from "#e2e/helpers/ssh-remote-p0";
  24. import {
  25. clickOpenScopeMenuOption,
  26. readOpenScopeMenuOptions,
  27. } from "#e2e/helpers/settings-scope-menu";
  28. import { prepareV4ConversationE2E, startNewV4Draft } from "#e2e/helpers/v4-conversation";
  29. const CASE_MARKER = "E2E_R3_HOOKS_LOCAL_SCOPE";
  30. const artifactDir = resolve(
  31. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-hooks-local-scope",
  32. );
  33. const LOCAL_MARKER = "E2E_R3_HOOKS_LOCAL_SCOPE_LOCAL";
  34. const REMOTE_MARKER = "E2E_R3_HOOKS_LOCAL_SCOPE_REMOTE";
  35. const SCOPE_TRIGGER = '[data-plugin-scope-trigger="true"]';
  36. const HOOK_FORM = '[data-testid="hooks-form"]';
  37. async function openHooksSection(): Promise<void> {
  38. const onSettings = await browser.execute(
  39. (pageId) => Boolean(document.querySelector(`[data-testid="${pageId}"]`)),
  40. TID_SETTINGS_PAGE,
  41. );
  42. if (!onSettings) {
  43. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  44. timeout: 15_000,
  45. timeoutMsg: `${CASE_MARKER}: 没有设置入口`,
  46. });
  47. await waitForTestIdByDom(TID_SETTINGS_PAGE, {
  48. timeout: 15_000,
  49. timeoutMsg: `${CASE_MARKER}: 设置页没有渲染`,
  50. });
  51. }
  52. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "hooks"), {
  53. timeout: 15_000,
  54. timeoutMsg: `${CASE_MARKER}: 设置页没有 hooks 分区`,
  55. });
  56. await $('[data-testid="hooks-settings-section"]').waitForDisplayed({ timeout: 15_000 });
  57. await $(SCOPE_TRIGGER).waitForClickable({ timeout: 15_000 });
  58. }
  59. async function readScopeOptions(): Promise<string[]> {
  60. await $(SCOPE_TRIGGER).click();
  61. await browser.waitUntil(
  62. () => browser.execute(() => document.querySelectorAll('[role="menuitemradio"]').length > 0),
  63. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: scope 菜单没有选项` },
  64. );
  65. // 项目在各设备的「项目」子菜单里(19 号票),逐个打开后合并。
  66. const options = (await readOpenScopeMenuOptions()).map((option) => option.text);
  67. await browser.keys(["Escape"]);
  68. await browser.waitUntil(
  69. () => browser.execute(() => document.querySelectorAll('[role="menuitemradio"]').length === 0),
  70. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: scope 菜单没有关闭` },
  71. );
  72. return options;
  73. }
  74. /** 同名目录必须按 scope key(identity 或本机路径)选择,不按位置或名称推断。 */
  75. async function selectScopeKey(key: string): Promise<void> {
  76. await $(SCOPE_TRIGGER).click();
  77. await browser.waitUntil(
  78. () => browser.execute(() => document.querySelectorAll('[role="menuitemradio"]').length > 0),
  79. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: scope 菜单打不开` },
  80. );
  81. await clickOpenScopeMenuOption(key, { timeoutMsg: `${CASE_MARKER}: scope 菜单没有 ${key}` });
  82. await browser.waitUntil(
  83. async () => (await $(SCOPE_TRIGGER).getAttribute("data-plugin-scope-key")) === key,
  84. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: scope 没有切到 ${key}` },
  85. );
  86. }
  87. async function createHook(marker: string): Promise<string[]> {
  88. await browser.waitUntil(
  89. () =>
  90. browser.execute(() => {
  91. const button = document.querySelector<HTMLButtonElement>(
  92. '[data-settings-create-action="settings.hooks.add"]',
  93. );
  94. if (!button || button.disabled) return false;
  95. button.click();
  96. return true;
  97. }),
  98. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 没有“新建钩子”入口` },
  99. );
  100. const form = $(HOOK_FORM);
  101. await form.waitForDisplayed({ timeout: 15_000 });
  102. // matcher 不会命中任何真实工具;命令只是 printf,且本测试不信任、不执行该 hook。
  103. await form.$("#matcher").setValue(`${marker}_MATCHER_NEVER`);
  104. await form.$("#command").setValue("/usr/bin/printf");
  105. await form.$("#args").setValue(marker);
  106. await browser.waitUntil(
  107. () =>
  108. browser.execute((selector) => {
  109. const formNode = document.querySelector<HTMLElement>(selector);
  110. const button = Array.from(
  111. formNode?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  112. ).find((item) => /^(保存|Save)$/iu.test(item.innerText.trim()) && !item.disabled);
  113. button?.click();
  114. return Boolean(button);
  115. }, HOOK_FORM),
  116. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 钩子表单没有可用的保存按钮` },
  117. );
  118. await browser.waitUntil(async () => !(await form.isExisting()), {
  119. timeout: 30_000,
  120. timeoutMsg: `${CASE_MARKER}: 保存后钩子表单没有关闭`,
  121. });
  122. await browser.pause(1_500);
  123. return browser.execute(() =>
  124. Array.from(document.querySelectorAll<HTMLElement>('[role="alert"], [data-sonner-toast]'))
  125. .map((node) => (node.innerText ?? "").replace(/\s+/gu, " ").trim())
  126. .filter(Boolean),
  127. );
  128. }
  129. async function readLocalFile(path: string, waitMs: number): Promise<string | null> {
  130. const deadline = Date.now() + waitMs;
  131. for (;;) {
  132. try {
  133. await access(path);
  134. return await readFile(path, "utf8");
  135. } catch {
  136. if (Date.now() >= deadline) return null;
  137. await browser.pause(500);
  138. }
  139. }
  140. }
  141. describe(`${CASE_MARKER}: 远端项目激活时钩子按选中的 scope 落盘`, () => {
  142. const facts: Record<string, unknown> = {};
  143. after(async () => {
  144. await mkdir(artifactDir, { recursive: true });
  145. await writeFile(resolve(artifactDir, "hooks-local-scope.json"), JSON.stringify(facts, null, 2));
  146. await browser.electron.restoreAllMocks();
  147. await clearAppData();
  148. });
  149. it("R3A-DEV-06-hooks-local-scope 活动工作区在远端时选本机项目 scope 保存钩子只写本机;选远端项目 scope 只写远端", async function () {
  150. this.timeout(20 * 60_000);
  151. const config = readSSHRuntimeConfig(CASE_MARKER);
  152. const [workspaceA] = config.workspacePaths;
  153. const localConfigPath = join(DEFAULT_WORKSPACE, ".zcode", "config.json");
  154. await prepareSSHConnectionPage(CASE_MARKER);
  155. await prepareV4ConversationE2E({ skipProvider: true });
  156. await runSSHCommand(config, `rm -f "${workspaceA}/.zcode/config.json"`);
  157. // 活动工作区切到远端项目 A。
  158. await startNewV4Draft();
  159. await openSSHRemoteDialog(CASE_MARKER);
  160. await fillSSHPasswordSettings(config);
  161. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  162. const remote = await completeSSHProjectConnection(config, CASE_MARKER);
  163. expect(remote.workspaceIdentity).toBeTruthy();
  164. await openHooksSection();
  165. const options = await readScopeOptions();
  166. facts.scopeOptions = options;
  167. expect(options).toEqual(
  168. expect.arrayContaining([
  169. expect.stringContaining(basename(DEFAULT_WORKSPACE)),
  170. expect.stringContaining(basename(workspaceA)),
  171. ]),
  172. );
  173. // 本机项目 scope:目标只由选中条目决定,不能借用活动远端工作区的身份把本机路径发往远端。
  174. await selectScopeKey(DEFAULT_WORKSPACE);
  175. const localAlerts = await createHook(LOCAL_MARKER);
  176. facts.localAlerts = localAlerts;
  177. expect(localAlerts.join(" ")).not.toMatch(/EACCES|permission denied|mkdir/iu);
  178. const localConfig = await readLocalFile(localConfigPath, 15_000);
  179. facts.localConfigHasLocalMarker = localConfig?.includes(LOCAL_MARKER) ?? false;
  180. expect(localConfig).toContain(LOCAL_MARKER);
  181. const remoteAfterLocal = await runSSHCommand(
  182. config,
  183. `grep -rl "${LOCAL_MARKER}" "$HOME/.zcode" "${workspaceA}" 2>/dev/null; echo END`,
  184. );
  185. facts.remoteAfterLocal = remoteAfterLocal.stdout.trim();
  186. expect(remoteAfterLocal.stdout.trim()).toBe("END");
  187. // 对照:远端项目 scope 仍只写远端。
  188. await selectScopeKey(remote.workspaceIdentity!);
  189. const remoteAlerts = await createHook(REMOTE_MARKER);
  190. facts.remoteAlerts = remoteAlerts;
  191. expect(remoteAlerts.join(" ")).not.toMatch(/EACCES|permission denied/iu);
  192. let remoteConfig = "";
  193. await browser.waitUntil(
  194. async () => {
  195. remoteConfig = (
  196. await runSSHCommand(config, `cat "${workspaceA}/.zcode/config.json" 2>/dev/null`)
  197. ).stdout;
  198. return remoteConfig.includes(REMOTE_MARKER);
  199. },
  200. {
  201. interval: 1000,
  202. timeout: 30_000,
  203. timeoutMsg: `${CASE_MARKER}: 远端项目 scope 钩子没有写入远端`,
  204. },
  205. );
  206. facts.remoteConfigHasRemoteMarker = true;
  207. const localAfterRemote = await readLocalFile(localConfigPath, 0);
  208. expect(localAfterRemote).toContain(LOCAL_MARKER);
  209. expect(localAfterRemote).not.toContain(REMOTE_MARKER);
  210. expect(remoteConfig).not.toContain(LOCAL_MARKER);
  211. await browser.saveScreenshot(resolve(artifactDir, "hooks-scopes.png")).catch(() => undefined);
  212. });
  213. });