conversation-session-ssh-remote-resource-settings.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import { mkdir, readFile, writeFile } 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_PAGE,
  7. TID_SETTINGS_SECTION_NAV,
  8. TID_TASK_SETTINGS_BUTTON,
  9. testId,
  10. } from "@zcode/shared/test-ids";
  11. import {
  12. clearAppData,
  13. clickTestIdByDom,
  14. getE2EAppDataPaths,
  15. pinE2ELocale,
  16. } from "#e2e/helpers/desktop-app";
  17. import {
  18. connectSSHWorkspace,
  19. readDualSSHRuntimeConfig,
  20. runSSHCommand,
  21. } from "#e2e/helpers/ssh-remote-p0";
  22. import { uploadSSHFixtureFile } from "#e2e/helpers/ssh-version-policy-fixture";
  23. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  24. const MARKER = "E2E_SSH_RESOURCE_SETTINGS";
  25. const resource = process.env.R3_RESOURCE_SETTINGS_CASE ?? "command";
  26. const artifactDir = resolve(
  27. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/ssh-resource-settings",
  28. );
  29. const name = `ssh-guide-${resource}`;
  30. async function openSection() {
  31. if (!(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isDisplayed()))
  32. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  33. await clickTestIdByDom(
  34. testId(
  35. TID_SETTINGS_SECTION_NAV,
  36. resource === "command" ? "commands" : resource === "hook" ? "hooks" : resource,
  37. ),
  38. );
  39. }
  40. async function clickLabel(label: string) {
  41. await browser.waitUntil(
  42. () =>
  43. browser.execute((text) => {
  44. const item = Array.from(
  45. document.querySelectorAll<HTMLButtonElement>("[data-settings-content-frame] button"),
  46. ).find(
  47. (button) =>
  48. !button.disabled &&
  49. button.getClientRects().length &&
  50. (button.innerText.trim() === text ||
  51. button.getAttribute("aria-label") === text ||
  52. button.getAttribute("title") === text),
  53. );
  54. item?.click();
  55. return Boolean(item);
  56. }, label),
  57. { timeout: 15_000, timeoutMsg: `${MARKER}: 缺少 ${label}` },
  58. );
  59. }
  60. describe(`${MARKER}: 同名同路径设备上的设置隔离`, () => {
  61. const facts: Record<string, unknown> = { resource };
  62. after(async () => {
  63. await mkdir(artifactDir, { recursive: true });
  64. await writeFile(join(artifactDir, "resource-settings.json"), JSON.stringify(facts, null, 2));
  65. await browser.electron.restoreAllMocks();
  66. await clearAppData();
  67. });
  68. it(`SSH-GUIDE-RESOURCE ${resource}: 当前机器管理不串到同路径另一台机器或本机`, async function () {
  69. this.timeout(20 * 60_000);
  70. if (!["skill", "mcp", "command", "hook"].includes(resource)) throw new Error("未知资源类型");
  71. const config = readDualSSHRuntimeConfig(MARKER);
  72. const [a, b] = config.targets;
  73. await prepareV4ConversationE2E({ skipProvider: true });
  74. // 宿主可能默认英文;下方按中文按钮操作,先固定测试语言再连接远端。
  75. await pinE2ELocale("zh-CN");
  76. await mkdir(artifactDir, { recursive: true });
  77. if (resource === "skill") {
  78. for (const [target, actor] of [
  79. [a, "A"],
  80. [b, "B"],
  81. ] as const) {
  82. const file = join(artifactDir, `skill-${actor}.md`);
  83. await writeFile(
  84. file,
  85. `---\nname: ${name}\ndescription: GUIDE_SKILL_${actor}\n---\n\nReturn GUIDE_SKILL_${actor}.\n`,
  86. );
  87. expect((await runSSHCommand(target, `mkdir -p "$HOME/.zcode/skills/${name}"`)).code).toBe(
  88. 0,
  89. );
  90. await uploadSSHFixtureFile(
  91. target,
  92. file,
  93. `/home/${target.username}/.zcode/skills/${name}/SKILL.md`,
  94. );
  95. }
  96. }
  97. const tabA = await connectSSHWorkspace({
  98. caseMarker: MARKER,
  99. config: a,
  100. workspacePath: config.workspacePath,
  101. });
  102. const tabB = await connectSSHWorkspace({
  103. caseMarker: MARKER,
  104. config: b,
  105. workspacePath: config.workspacePath,
  106. });
  107. expect(parseRemoteWorkspaceIdentity(tabA.workspaceIdentity!)?.sourceServerId).not.toBe(
  108. parseRemoteWorkspaceIdentity(tabB.workspaceIdentity!)?.sourceServerId,
  109. );
  110. await connectSSHWorkspace({
  111. caseMarker: MARKER,
  112. config: a,
  113. workspacePath: config.workspacePath,
  114. });
  115. await openSection();
  116. expect(await $("[data-settings-machine]").isExisting()).toBe(false);
  117. expect(await $('[data-plugin-scope-trigger="true"]').getText()).not.toContain("本机");
  118. if (resource === "skill") {
  119. await browser.waitUntil(
  120. async () => (await $("[data-settings-content-frame]").getText()).includes("GUIDE_SKILL_A"),
  121. { timeout: 30_000 },
  122. );
  123. expect(await $("[data-settings-content-frame]").getText()).not.toContain("GUIDE_SKILL_B");
  124. await browser.waitUntil(
  125. () =>
  126. browser.execute((skill) => {
  127. const heading = Array.from(
  128. document.querySelectorAll<HTMLElement>(
  129. "[data-settings-content-frame] h3, [data-settings-content-frame] p, [data-settings-content-frame] span",
  130. ),
  131. ).find((item) => item.textContent?.trim() === skill);
  132. let row: Element | null | undefined = heading;
  133. while (row && !row.querySelector('button[aria-label="删除"]')) row = row.parentElement;
  134. const button = row?.querySelector<HTMLButtonElement>('button[aria-label="删除"]');
  135. button?.click();
  136. return Boolean(button);
  137. }, name),
  138. { timeout: 15_000, timeoutMsg: "当前设备技能没有删除入口" },
  139. );
  140. await browser.waitUntil(
  141. () =>
  142. browser.execute(() => {
  143. const button = Array.from(
  144. document.querySelectorAll<HTMLButtonElement>(
  145. '[role="dialog"] button, [role="alertdialog"] button',
  146. ),
  147. ).find((item) => /^(删除|Delete)$/iu.test(item.innerText.trim()));
  148. button?.click();
  149. return Boolean(button);
  150. }),
  151. { timeout: 15_000 },
  152. );
  153. await browser.waitUntil(
  154. async () =>
  155. (await runSSHCommand(a, `test ! -e "$HOME/.zcode/skills/${name}/SKILL.md"`)).code === 0,
  156. );
  157. expect(
  158. (await runSSHCommand(b, `cat "$HOME/.zcode/skills/${name}/SKILL.md"`)).stdout,
  159. ).toContain("GUIDE_SKILL_B");
  160. facts.deletedOnlyTargetSkill = true;
  161. } else {
  162. await clickLabel(
  163. resource === "mcp" ? "新建 MCP 服务器" : resource === "hook" ? "新建钩子" : "新建",
  164. );
  165. if (resource === "mcp") {
  166. const file = join(artifactDir, "mcp-server.mjs");
  167. await writeFile(
  168. file,
  169. 'import { createInterface } from "node:readline";\ncreateInterface({ input: process.stdin }).on("line", line => { const r = JSON.parse(line); if (r.id == null) return; const result = r.method === "initialize" ? { protocolVersion: r.params.protocolVersion, serverInfo: {name:"guide",version:"1"}, capabilities:{tools:{}} } : r.method === "tools/list" ? {tools:[]} : {}; process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:r.id,result})+"\\n"); });\n',
  170. );
  171. const remoteFile = `${config.workspacePath}/.zcode-e2e/resource-settings/mcp-server.mjs`;
  172. expect(
  173. (
  174. await runSSHCommand(
  175. a,
  176. `mkdir -p '${config.workspacePath}/.zcode-e2e/resource-settings'`,
  177. )
  178. ).code,
  179. ).toBe(0);
  180. await uploadSSHFixtureFile(a, file, remoteFile);
  181. const installed = JSON.parse(
  182. (await runSSHCommand(a, 'cat "$HOME/.zcode/server/current.json"')).stdout,
  183. );
  184. await $('input[placeholder="my-mcp-server"]').setValue(name);
  185. await $('input[placeholder="npx"]').setValue(`${installed.releaseDir}/runtime/node`);
  186. await $('input[placeholder="-y @modelcontextprotocol/server-memory"]').setValue(remoteFile);
  187. } else if (resource === "command") {
  188. await $('input[placeholder="my-command"]').setValue(name);
  189. await $("[data-settings-content-frame] textarea").setValue(`GUIDE_COMMAND_A ${name}`);
  190. } else {
  191. await $("#command").setValue(`printf '${name}'`);
  192. }
  193. await clickLabel("保存");
  194. let paths = "";
  195. const lookup = `find "$HOME/.zcode" '${config.workspacePath}/.zcode' -type f \\( -name '*.json' -o -name '*.md' \\) -exec grep -lF '${name}' {} \\; 2>/dev/null || true`;
  196. await browser.waitUntil(
  197. async () => {
  198. paths = (await runSSHCommand(a, lookup)).stdout.trim();
  199. return Boolean(paths);
  200. },
  201. { timeout: 30_000, timeoutMsg: `${MARKER}: UI 保存没有落到目标机器` },
  202. );
  203. expect((await runSSHCommand(b, lookup)).stdout.trim()).toBe("");
  204. facts.targetFiles = paths.split("\n");
  205. }
  206. await browser.saveScreenshot(join(artifactDir, "target-a.png"));
  207. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  208. await connectSSHWorkspace({
  209. caseMarker: MARKER,
  210. config: b,
  211. workspacePath: config.workspacePath,
  212. });
  213. await openSection();
  214. if (resource === "skill") {
  215. await browser.waitUntil(
  216. async () => (await $("[data-settings-content-frame]").getText()).includes("GUIDE_SKILL_B"),
  217. { timeout: 30_000 },
  218. );
  219. } else {
  220. expect(await $("[data-settings-content-frame]").getText()).not.toContain(name);
  221. }
  222. for (const relative of ["cli/config.json", `commands/${name}.md`, `cli/commands/${name}.md`]) {
  223. const local = await readFile(join(getE2EAppDataPaths().storageRoot, relative), "utf8").catch(
  224. (error: NodeJS.ErrnoException) => {
  225. if (error.code === "ENOENT") return "";
  226. throw error;
  227. },
  228. );
  229. expect(local).not.toContain(name);
  230. }
  231. facts.otherSourceAndLocalUnchanged = true;
  232. });
  233. });