conversation-session-remote-data-sync-plugin-push.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import { randomBytes } from "node:crypto";
  2. import { mkdir, readFile, writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import {
  5. TID_SETTINGS_PAGE,
  6. TID_SETTINGS_SECTION_NAV,
  7. TID_TASK_SETTINGS_BUTTON,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import {
  11. clearAppData,
  12. clickTestIdByDom,
  13. getE2EAppDataPaths,
  14. waitForTestIdByDom,
  15. } from "#e2e/helpers/desktop-app";
  16. import {
  17. execInRemoteContainer,
  18. readRemoteContainerFile,
  19. readRemoteDockerContainer,
  20. remoteContainerPathExists,
  21. writeRemoteContainerFile,
  22. } from "#e2e/helpers/remote-docker-target";
  23. import {
  24. connectSSHWorkspace,
  25. prepareSSHConnectionPage,
  26. readSSHRuntimeConfig,
  27. } from "#e2e/helpers/ssh-remote-p0";
  28. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  29. // DSYNC-07:设置 → 数据同步 → 设备 → 推送 inline 插件(docs/remote/data-sync.md「插件」)。
  30. // 远端为本机 Docker runner(或服务器队列)提供的真实 Linux 容器;远端断言用 docker exec 读容器内 ~/.zcode。
  31. const CASE_MARKER = "E2E_DSYNC_07_PLUGIN_PUSH";
  32. const PLUGIN_NAME = "e2e-dsync-plugin";
  33. const PLUGIN_KEY = `${PLUGIN_NAME}@inline`;
  34. const REMOTE_PLUGIN_DIR = `/home/dev/.zcode/plugins/${PLUGIN_NAME}`;
  35. const REMOTE_CONFIG = "/home/dev/.zcode/cli/config.json";
  36. const REMOTE_DATA_MARKER = `${CASE_MARKER}_REMOTE_DATA`;
  37. const BIG_PLUGIN_NAME = "e2e-dsync-big-plugin";
  38. const BIG_PLUGIN_KEY = `${BIG_PLUGIN_NAME}@inline`;
  39. const REMOTE_BIG_PLUGIN_DIR = `/home/dev/.zcode/plugins/${BIG_PLUGIN_NAME}`;
  40. // 32MiB 随机内容:RPC 若把归档展开成 JSON 数字数组(约 3.6 倍)会超过远端 WebSocket 单条消息上限 100MiB;
  41. // 按 base64(约 4/3 倍)传输约 43MiB。
  42. const BIG_PLUGIN_PAYLOAD_BYTES = 32 * 1024 * 1024;
  43. function localPluginDir(): string {
  44. return join(getE2EAppDataPaths().homeDir, ".zcode", "plugins", PLUGIN_NAME);
  45. }
  46. async function writeLocalPlugin(version: string): Promise<void> {
  47. const dir = localPluginDir();
  48. await mkdir(join(dir, ".zcode-plugin"), { recursive: true });
  49. await writeFile(
  50. join(dir, ".zcode-plugin", "plugin.json"),
  51. `${JSON.stringify({ name: PLUGIN_NAME, version, description: "data sync e2e plugin" }, null, 2)}\n`,
  52. );
  53. await mkdir(join(dir, "skills", "dsync-hello"), { recursive: true });
  54. await writeFile(
  55. join(dir, "skills", "dsync-hello", "SKILL.md"),
  56. `---\nname: dsync-hello\ndescription: ${CASE_MARKER} ${version}\n---\nHello ${version}\n`,
  57. );
  58. // 本机的 data/ 是运行数据,不应推送到远端。
  59. await mkdir(join(dir, "data"), { recursive: true });
  60. await writeFile(join(dir, "data", "local.json"), `{"marker":"${CASE_MARKER}_LOCAL_DATA"}\n`);
  61. }
  62. /** 把插件目录登记到本机 config.json 的 plugins.dirs(保留已有字段)。 */
  63. async function registerLocalPlugin(pluginDir = localPluginDir()): Promise<void> {
  64. const configPath = join(getE2EAppDataPaths().homeDir, ".zcode", "cli", "config.json");
  65. let config: Record<string, unknown> = {};
  66. try {
  67. config = JSON.parse(await readFile(configPath, "utf-8")) as Record<string, unknown>;
  68. } catch {
  69. config = {};
  70. }
  71. const plugins = (config.plugins ?? {}) as Record<string, unknown>;
  72. const dirs = Array.isArray(plugins.dirs) ? (plugins.dirs as string[]) : [];
  73. await mkdir(join(configPath, ".."), { recursive: true });
  74. await writeFile(
  75. configPath,
  76. `${JSON.stringify({ ...config, plugins: { ...plugins, dirs: [...dirs, pluginDir] } }, null, 2)}\n`,
  77. );
  78. }
  79. async function readRowState(key: string) {
  80. return await browser.execute((rowTestId) => {
  81. const row = Array.from(document.querySelectorAll<HTMLButtonElement>("[data-testid]")).find(
  82. (element) => element.dataset.testid === rowTestId,
  83. );
  84. return row
  85. ? {
  86. status: row.dataset.syncStatus ?? null,
  87. checked: row.getAttribute("aria-checked"),
  88. text: row.textContent ?? "",
  89. }
  90. : null;
  91. }, `remote-sync-row-${key}`);
  92. }
  93. async function waitForRowStatus(key: string, status: string, timeoutMsg: string) {
  94. await browser.waitUntil(async () => (await readRowState(key))?.status === status, {
  95. timeout: 60_000,
  96. timeoutMsg: `${CASE_MARKER}: ${timeoutMsg}`,
  97. });
  98. return (await readRowState(key))!;
  99. }
  100. async function readButtonText(buttonTestId: string): Promise<string> {
  101. return await browser.execute(
  102. (id) => document.querySelector(`[data-testid="${id}"]`)?.textContent?.trim() ?? "",
  103. buttonTestId,
  104. );
  105. }
  106. async function pushPluginsAndWait(): Promise<void> {
  107. await clickTestIdByDom("remote-sync-push", {
  108. timeout: 30_000,
  109. timeoutMsg: `${CASE_MARKER}: 推送插件按钮不可用`,
  110. });
  111. await browser.waitUntil(async () => (await readButtonText("remote-sync-push")) === "再次同步", {
  112. timeout: 120_000,
  113. timeoutMsg: `${CASE_MARKER}: 推送插件没有完成`,
  114. });
  115. }
  116. async function openPluginsTab(): Promise<void> {
  117. await clickTestIdByDom("remote-sync-device-action", { timeout: 30_000 });
  118. await waitForTestIdByDom("remote-sync-dialog", { timeout: 30_000 });
  119. await clickTestIdByDom("remote-sync-tab-plugins", {
  120. timeout: 30_000,
  121. timeoutMsg: `${CASE_MARKER}: 同步弹窗没有插件分类`,
  122. });
  123. }
  124. async function readRemoteConfig(container: string): Promise<{ plugins?: { dirs?: string[] } }> {
  125. return JSON.parse(await readRemoteContainerFile(container, REMOTE_CONFIG)) as {
  126. plugins?: { dirs?: string[] };
  127. };
  128. }
  129. describe(`${CASE_MARKER}: 数据同步页推送 inline 插件`, () => {
  130. after(async () => {
  131. await browser.electron.restoreAllMocks();
  132. await clearAppData();
  133. });
  134. it("DSYNC-07-01/02 新插件写入远端并登记 plugins.dirs;本机版本更新后远端原位更新且 data/ 不变", async function () {
  135. this.timeout(20 * 60_000);
  136. const config = readSSHRuntimeConfig(CASE_MARKER);
  137. const container = readRemoteDockerContainer(CASE_MARKER);
  138. const workspacePath = config.workspacePaths[0];
  139. await writeLocalPlugin("1.0.0");
  140. await registerLocalPlugin();
  141. await prepareSSHConnectionPage(CASE_MARKER);
  142. await prepareV4ConversationE2E({ skipProvider: true });
  143. await connectSSHWorkspace({ caseMarker: CASE_MARKER, config, workspacePath });
  144. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 30_000 });
  145. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 30_000 });
  146. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "dataSync"), {
  147. timeout: 30_000,
  148. timeoutMsg: `${CASE_MARKER}: 设置页没有数据同步分区`,
  149. });
  150. await waitForTestIdByDom("remote-sync-device-list", {
  151. timeout: 60_000,
  152. timeoutMsg: `${CASE_MARKER}: 数据同步页没有在线设备`,
  153. });
  154. // DSYNC-07-01:只在本机存在的 inline 插件显示「推送」并默认勾选;推送后远端目录和 plugins.dirs 都写入。
  155. await openPluginsTab();
  156. const newRow = await waitForRowStatus(PLUGIN_KEY, "push", "新插件没有显示为「推送」");
  157. expect(newRow.checked).toBe("true");
  158. await pushPluginsAndWait();
  159. await waitForRowStatus(PLUGIN_KEY, "synced", "推送后插件没有变为「已同步」");
  160. expect(
  161. await readRemoteContainerFile(container, `${REMOTE_PLUGIN_DIR}/.zcode-plugin/plugin.json`),
  162. ).toContain('"version": "1.0.0"');
  163. expect(
  164. await readRemoteContainerFile(container, `${REMOTE_PLUGIN_DIR}/skills/dsync-hello/SKILL.md`),
  165. ).toContain("Hello 1.0.0");
  166. expect(await remoteContainerPathExists(container, `${REMOTE_PLUGIN_DIR}/data`)).toBe(false);
  167. expect((await readRemoteConfig(container)).plugins?.dirs).toContain(REMOTE_PLUGIN_DIR);
  168. // DSYNC-07-02:远端插件有自己的 data/;本机升级版本后显示「1.0.0 → 1.1.0 · 更新」,推送后原位更新,data/ 不变。
  169. await writeRemoteContainerFile(
  170. container,
  171. `${REMOTE_PLUGIN_DIR}/data/state.json`,
  172. `{"marker":"${REMOTE_DATA_MARKER}"}\n`,
  173. );
  174. await writeLocalPlugin("1.1.0");
  175. await clickTestIdByDom("remote-sync-tab-overview");
  176. await clickTestIdByDom("remote-sync-close");
  177. await openPluginsTab();
  178. const updateRow = await waitForRowStatus(PLUGIN_KEY, "update", "本机新版本没有显示为「更新」");
  179. expect(updateRow.checked).toBe("true");
  180. expect(updateRow.text).toContain("1.0.0");
  181. expect(updateRow.text).toContain("1.1.0");
  182. await pushPluginsAndWait();
  183. await waitForRowStatus(PLUGIN_KEY, "synced", "更新后插件没有变为「已同步」");
  184. expect(
  185. await readRemoteContainerFile(container, `${REMOTE_PLUGIN_DIR}/.zcode-plugin/plugin.json`),
  186. ).toContain('"version": "1.1.0"');
  187. expect(
  188. await readRemoteContainerFile(container, `${REMOTE_PLUGIN_DIR}/skills/dsync-hello/SKILL.md`),
  189. ).toContain("Hello 1.1.0");
  190. expect(
  191. await readRemoteContainerFile(container, `${REMOTE_PLUGIN_DIR}/data/state.json`),
  192. ).toContain(REMOTE_DATA_MARKER);
  193. // 更新不重复登记目录。
  194. expect(
  195. (await readRemoteConfig(container)).plugins?.dirs?.filter((dir) => dir === REMOTE_PLUGIN_DIR),
  196. ).toHaveLength(1);
  197. });
  198. it("DSYNC-07-03 约 32MB 的 inline 插件推送成功,远端收到完整内容", async function () {
  199. this.timeout(15 * 60_000);
  200. const container = readRemoteDockerContainer(CASE_MARKER);
  201. // 接续 DSYNC-07-01/02:弹窗停在插件分类。
  202. await clickTestIdByDom("remote-sync-tab-overview");
  203. await clickTestIdByDom("remote-sync-close");
  204. const dir = join(getE2EAppDataPaths().homeDir, ".zcode", "plugins", BIG_PLUGIN_NAME);
  205. await mkdir(join(dir, ".zcode-plugin"), { recursive: true });
  206. await writeFile(
  207. join(dir, ".zcode-plugin", "plugin.json"),
  208. `${JSON.stringify({ name: BIG_PLUGIN_NAME, version: "1.0.0", description: "large data sync e2e plugin" }, null, 2)}\n`,
  209. );
  210. await writeFile(join(dir, "payload.bin"), randomBytes(BIG_PLUGIN_PAYLOAD_BYTES));
  211. await registerLocalPlugin(dir);
  212. await openPluginsTab();
  213. const bigRow = await waitForRowStatus(BIG_PLUGIN_KEY, "push", "大插件没有显示为「推送」");
  214. expect(bigRow.checked).toBe("true");
  215. await clickTestIdByDom("remote-sync-push", {
  216. timeout: 30_000,
  217. timeoutMsg: `${CASE_MARKER}: 推送插件按钮不可用`,
  218. });
  219. await browser
  220. .waitUntil(async () => (await readRowState(BIG_PLUGIN_KEY))?.status === "synced", {
  221. timeout: 5 * 60_000,
  222. interval: 1_000,
  223. })
  224. .catch(async (error: unknown) => {
  225. const state = await readRowState(BIG_PLUGIN_KEY);
  226. const pushError = await browser.execute(
  227. () => document.querySelector('[data-testid="remote-sync-push-error"]')?.textContent ?? "",
  228. );
  229. throw new Error(
  230. `${CASE_MARKER}: 大插件推送后没有变为「已同步」;行=${JSON.stringify(state)};分类错误=${pushError}`,
  231. { cause: error },
  232. );
  233. });
  234. const remoteSize = (
  235. await execInRemoteContainer(container, [
  236. "stat",
  237. "-c",
  238. "%s",
  239. `${REMOTE_BIG_PLUGIN_DIR}/payload.bin`,
  240. ])
  241. ).stdout.trim();
  242. expect(Number(remoteSize)).toBe(BIG_PLUGIN_PAYLOAD_BYTES);
  243. expect((await readRemoteConfig(container)).plugins?.dirs).toContain(REMOTE_BIG_PLUGIN_DIR);
  244. await clickTestIdByDom("remote-sync-tab-overview");
  245. await clickTestIdByDom("remote-sync-close");
  246. });
  247. });