conversation-session-remote-memory-settings.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import { mkdir, readFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  4. import {
  5. TID_SETTINGS_BACK_BUTTON,
  6. TID_SETTINGS_MEMORY_SWITCH,
  7. TID_SETTINGS_PAGE,
  8. TID_SETTINGS_SECTION_NAV,
  9. TID_TASK_SETTINGS_BUTTON,
  10. testId,
  11. } from "@zcode/shared/test-ids";
  12. import {
  13. clearAppData,
  14. clickTestIdByDom,
  15. setCurrentElectronRendererContentSize,
  16. waitForTestIdByDom,
  17. } from "#e2e/helpers/desktop-app";
  18. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  19. import {
  20. bringRemoteDeviceOnline,
  21. chmodRemoteContainerPath,
  22. readRemoteContainerFile,
  23. readRemoteDockerContainer,
  24. takeRemoteDeviceOffline,
  25. writeRemoteContainerFile,
  26. } from "#e2e/helpers/remote-docker-target";
  27. import { clickOpenScopeMenuOption } from "#e2e/helpers/settings-scope-menu";
  28. import {
  29. connectSSHWorkspace,
  30. prepareSSHConnectionPage,
  31. readSSHRuntimeConfig,
  32. } from "#e2e/helpers/ssh-remote-p0";
  33. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  34. const CASE_MARKER = "E2E_REMOTE_MEMORY_SETTINGS";
  35. const DEVICE_TRIGGER = "settings-memory-device-trigger";
  36. const REMOTE_SETTINGS_DIR = "/home/dev/.zcode/v2";
  37. const REMOTE_SETTINGS = `${REMOTE_SETTINGS_DIR}/setting.json`;
  38. async function openSection(section: string): Promise<void> {
  39. if (!(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isExisting())) {
  40. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 30_000 });
  41. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 30_000 });
  42. }
  43. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, section));
  44. }
  45. async function openDeviceMenu(): Promise<void> {
  46. await waitForTestIdByDom(DEVICE_TRIGGER, { timeout: 30_000 });
  47. // 与现有 Scope 用例相同:已打开时不再次切换,Radix 只发送一次 pointerdown 打开。
  48. await browser.waitUntil(
  49. () =>
  50. browser.execute((id) => {
  51. const trigger = document.querySelector<HTMLElement>(`[data-testid="${id}"]`);
  52. if (trigger?.dataset.state === "open") {
  53. return [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].some(
  54. (item) => item.getClientRects().length > 0,
  55. );
  56. }
  57. trigger?.dispatchEvent(
  58. new PointerEvent("pointerdown", { bubbles: true, button: 0, pointerType: "mouse" }),
  59. );
  60. return false;
  61. }, DEVICE_TRIGGER),
  62. { timeout: 15_000, interval: 500, timeoutMsg: `${CASE_MARKER}: 设备菜单未打开` },
  63. );
  64. }
  65. async function selectDevice(key: string): Promise<void> {
  66. await openDeviceMenu();
  67. await clickOpenScopeMenuOption(key);
  68. await browser.waitUntil(
  69. async () =>
  70. (await $(`[data-testid="${DEVICE_TRIGGER}"]`).getAttribute("data-plugin-scope-key")) === key,
  71. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 没有选中 ${key}` },
  72. );
  73. }
  74. async function readMemorySwitch(): Promise<boolean | null> {
  75. return browser.execute((id) => {
  76. const control = document.querySelector<HTMLButtonElement>(`[data-testid="${id}"]`);
  77. return !control || control.disabled ? null : control.getAttribute("aria-checked") === "true";
  78. }, TID_SETTINGS_MEMORY_SWITCH);
  79. }
  80. async function waitForSwitch(expected: boolean): Promise<void> {
  81. await browser.waitUntil(async () => (await readMemorySwitch()) === expected, {
  82. timeout: 30_000,
  83. timeoutMsg: `${CASE_MARKER}: 开关未显示 ${expected}`,
  84. });
  85. }
  86. async function readLocalMemory(): Promise<boolean> {
  87. const raw = await readFile(join(resolveE2EStorageRoot(), "v2", "setting.json"), "utf8");
  88. return (JSON.parse(raw) as { memoryEnabled?: boolean }).memoryEnabled === true;
  89. }
  90. async function readRemoteMemory(container: string): Promise<boolean> {
  91. const raw = await readRemoteContainerFile(container, REMOTE_SETTINGS);
  92. return (JSON.parse(raw) as { memoryEnabled?: boolean }).memoryEnabled === true;
  93. }
  94. async function setMemory(enabled: boolean, read: () => Promise<boolean>): Promise<void> {
  95. await waitForSwitch(!enabled);
  96. await clickTestIdByDom(TID_SETTINGS_MEMORY_SWITCH);
  97. await browser.waitUntil(async () => (await read()) === enabled, {
  98. timeout: 30_000,
  99. timeoutMsg: `${CASE_MARKER}: 目标设备未保存 ${enabled}`,
  100. });
  101. await waitForSwitch(enabled);
  102. }
  103. async function captureLayouts(): Promise<void> {
  104. const root = process.env.ZCODE_E2E_ARTIFACT_DIR;
  105. if (!root) throw new Error(`${CASE_MARKER}: 缺少工件目录`);
  106. const dir = resolve(root, "memory-devices");
  107. await mkdir(dir, { recursive: true });
  108. for (const locale of ["zh-CN", "en-US"]) {
  109. for (const theme of ["light", "dark"]) {
  110. await browser.execute(
  111. (language, color) => {
  112. const actions = (
  113. window as Window & {
  114. __testActions?: { setLocale(value: string): void; setTheme(value: string): void };
  115. }
  116. ).__testActions;
  117. actions?.setLocale(language);
  118. actions?.setTheme(color);
  119. },
  120. locale,
  121. theme,
  122. );
  123. for (const width of [1280, 700]) {
  124. await setCurrentElectronRendererContentSize(width, 800);
  125. await openDeviceMenu();
  126. expect(await $(`[data-testid="${DEVICE_TRIGGER}"]`).getAttribute("aria-expanded")).toBe(
  127. "true",
  128. );
  129. await browser.saveScreenshot(join(dir, `${locale}-${theme}-${width}.png`));
  130. await browser.keys("Escape");
  131. expect(await $(`[data-testid="${TID_SETTINGS_MEMORY_SWITCH}"]`).isDisplayed()).toBe(true);
  132. }
  133. }
  134. }
  135. await browser.execute(() => {
  136. const actions = (
  137. window as Window & {
  138. __testActions?: { setLocale(value: string): void; setTheme(value: string): void };
  139. }
  140. ).__testActions;
  141. actions?.setLocale("zh-CN");
  142. actions?.setTheme("light");
  143. });
  144. await setCurrentElectronRendererContentSize(1280, 800);
  145. }
  146. describe(`${CASE_MARKER}: 按设备设置记忆`, () => {
  147. let container = "";
  148. let sourceId = "";
  149. let configured = false;
  150. let offlineTarget: { host: string; port: number } | null = null;
  151. after(async () => {
  152. if (offlineTarget) await bringRemoteDeviceOnline(container, offlineTarget);
  153. if (container) {
  154. await chmodRemoteContainerPath(container, "u+w", REMOTE_SETTINGS_DIR);
  155. // 同批 SSH P0 复用这个容器;清理只恢复本例开关,保留最新的其他设置。
  156. const settings = JSON.parse(
  157. await readRemoteContainerFile(container, REMOTE_SETTINGS),
  158. ) as Record<string, unknown>;
  159. await writeRemoteContainerFile(
  160. container,
  161. REMOTE_SETTINGS,
  162. JSON.stringify({ ...settings, memoryEnabled: false }),
  163. );
  164. }
  165. await browser.electron.restoreAllMocks();
  166. await clearAppData();
  167. });
  168. it("MEM-DEVICE-01 复用设备菜单,远端与本机开关分别保存并读回", async function () {
  169. this.timeout(20 * 60_000);
  170. const config = readSSHRuntimeConfig(CASE_MARKER);
  171. container = readRemoteDockerContainer(CASE_MARKER);
  172. await prepareSSHConnectionPage(CASE_MARKER);
  173. await prepareV4ConversationE2E({ skipProvider: true });
  174. const remote = await connectSSHWorkspace({
  175. caseMarker: CASE_MARKER,
  176. config,
  177. workspacePath: config.workspacePaths[0],
  178. });
  179. sourceId = parseRemoteWorkspaceIdentity(remote.workspaceIdentity ?? "")?.sourceServerId ?? "";
  180. expect(sourceId).toBeTruthy();
  181. await openSection("memory");
  182. await openDeviceMenu();
  183. const menu = await browser.execute(() => ({
  184. headings: [
  185. ...document.querySelectorAll<HTMLElement>('[data-scope-device-heading="true"]'),
  186. ].map((item) => item.innerText.trim()),
  187. keys: [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].map(
  188. (item) => item.dataset.pluginScopeKey,
  189. ),
  190. projects: document.querySelectorAll('[data-scope-projects-trigger="true"]').length,
  191. }));
  192. expect(menu.headings).toHaveLength(2);
  193. expect(menu.headings[0]).toBe("本机");
  194. expect(menu.keys).toEqual(["user", `source-user:${sourceId}`]);
  195. expect(menu.projects).toBe(0);
  196. await browser.keys("Escape");
  197. expect(await $(`[data-testid="${DEVICE_TRIGGER}"]`).getAttribute("data-plugin-scope-key")).toBe(
  198. `source-user:${sourceId}`,
  199. );
  200. await waitForSwitch(false);
  201. await setMemory(true, () => readRemoteMemory(container));
  202. expect(await readLocalMemory()).toBe(false);
  203. expect(await $('[data-testid="settings-memory-remote-details"]').isDisplayed()).toBe(true);
  204. await selectDevice("user");
  205. await waitForSwitch(false);
  206. await setMemory(true, readLocalMemory);
  207. await setMemory(false, readLocalMemory);
  208. expect(await readRemoteMemory(container)).toBe(true);
  209. await selectDevice(`source-user:${sourceId}`);
  210. await waitForSwitch(true);
  211. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  212. await openSection("memory");
  213. await waitForSwitch(true);
  214. configured = true;
  215. });
  216. it("MEM-DEVICE-03 保存失败保留原值,重试成功;切换、主题与窄窗口正常", async function () {
  217. this.timeout(5 * 60_000);
  218. if (!configured) this.skip();
  219. await selectDevice(`source-user:${sourceId}`);
  220. await waitForSwitch(true);
  221. // 真实远端目录拒绝写入,覆盖 RPC 保存失败;不以 mock 替代 SSH 持久化。
  222. await chmodRemoteContainerPath(container, "a-w", REMOTE_SETTINGS_DIR);
  223. try {
  224. await clickTestIdByDom(TID_SETTINGS_MEMORY_SWITCH);
  225. await waitForTestIdByDom("settings-memory-error", { timeout: 30_000 });
  226. await waitForSwitch(true);
  227. expect(await readRemoteMemory(container)).toBe(true);
  228. expect(await readLocalMemory()).toBe(false);
  229. } finally {
  230. await chmodRemoteContainerPath(container, "u+w", REMOTE_SETTINGS_DIR);
  231. }
  232. await setMemory(false, () => readRemoteMemory(container));
  233. await setMemory(true, () => readRemoteMemory(container));
  234. for (let index = 0; index < 3; index++) {
  235. await selectDevice("user");
  236. expect([null, false]).toContain(await readMemorySwitch());
  237. await waitForSwitch(false);
  238. await selectDevice(`source-user:${sourceId}`);
  239. expect([null, true]).toContain(await readMemorySwitch());
  240. await waitForSwitch(true);
  241. }
  242. await captureLayouts();
  243. });
  244. it("MEM-DEVICE-02 远端离线不回退本机,恢复后读回远端开关", async function () {
  245. this.timeout(10 * 60_000);
  246. if (!configured) this.skip();
  247. const config = readSSHRuntimeConfig(CASE_MARKER);
  248. offlineTarget = { host: config.host, port: config.port };
  249. await takeRemoteDeviceOffline(container);
  250. await $('[data-scope-blocked="offline"]').waitForDisplayed({ timeout: 5 * 60_000 });
  251. expect(await readMemorySwitch()).toBeNull();
  252. expect(await $(`[data-testid="${DEVICE_TRIGGER}"]`).getAttribute("data-plugin-scope-key")).toBe(
  253. `source-user:${sourceId}`,
  254. );
  255. await selectDevice("user");
  256. await waitForSwitch(false);
  257. await bringRemoteDeviceOnline(container, offlineTarget);
  258. offlineTarget = null;
  259. await openSection("remoteDevices");
  260. await browser.waitUntil(
  261. () =>
  262. browser.execute((id) => {
  263. const card = document.querySelector(`[data-source-server-card="${id}"]`);
  264. if (card?.querySelector('[data-remote-connection-status="online"]')) return true;
  265. const connect = [...(card?.querySelectorAll<HTMLButtonElement>("button") ?? [])].find(
  266. (button) => !button.disabled && ["连接", "Connect"].includes(button.innerText.trim()),
  267. );
  268. connect?.click();
  269. return false;
  270. }, sourceId),
  271. { timeout: 120_000, interval: 1_000 },
  272. );
  273. await openSection("memory");
  274. await selectDevice(`source-user:${sourceId}`);
  275. await waitForSwitch(true);
  276. expect(await readLocalMemory()).toBe(false);
  277. });
  278. });