conversation-session-preinstalled-tools-upgrade.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import { spawn } from "node:child_process";
  2. import { once } from "node:events";
  3. import { chmod, copyFile, cp, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import {
  6. preinstalledToolsCatalogSchema,
  7. type PreinstalledToolsState,
  8. } from "@zcode/shared/preinstalled-tools";
  9. import { getLatestUpstreamToolResultByToolCallId } from "#e2e/helpers/conversation-session-network";
  10. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  11. import { resolveE2ERuntimePath, resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  12. import {
  13. executePreinstalledEntry,
  14. preinstalledFixtureRecordPath,
  15. preinstalledFixtureTarget,
  16. preinstalledEntryPath,
  17. } from "#e2e/helpers/preinstalled-tools-fixture";
  18. import { setPluginPresentation } from "#e2e/helpers/plugin-management-lifecycle";
  19. import {
  20. getV4PaneSnapshot,
  21. prepareV4ConversationE2E,
  22. sendV4Prompt,
  23. switchV4Mode,
  24. waitForV4AssistantMessageContaining,
  25. waitForV4ConversationState,
  26. } from "#e2e/helpers/v4-conversation";
  27. const fixtureUrl = () => process.env.ZCODE_E2E_PREINSTALL_FIXTURE_URL!;
  28. const card = (toolId = "libreoffice") => `[data-tool-id="${toolId}"]`;
  29. const state = async () =>
  30. browser.execute(async () =>
  31. (
  32. window as typeof window & {
  33. zcode: { getPreinstalledToolsState(): Promise<PreinstalledToolsState> };
  34. }
  35. ).zcode.getPreinstalledToolsState(),
  36. );
  37. const http = async () =>
  38. (await fetch(`${fixtureUrl()}/status`)).json() as Promise<{
  39. requests: number;
  40. tools: Record<string, { requests: number }>;
  41. }>;
  42. async function waitStatus(expected: string, toolId = "libreoffice") {
  43. await browser.waitUntil(
  44. async () => {
  45. if ((await state()).tools.find((tool) => tool.toolId === toolId)?.status !== expected)
  46. return false;
  47. const label = $(`${card(toolId)} [data-testid="preinstalled-tools-status"]`);
  48. return !(await label.isExisting()) || (await label.getAttribute("data-status")) === expected;
  49. },
  50. { timeout: 30000, timeoutMsg: `${toolId} 未达到 ${expected}` },
  51. );
  52. }
  53. async function openDialog() {
  54. await $('[data-testid="workspace-help-menu-trigger"]').click();
  55. await $('[data-testid="workspace-help-menu-preinstalled-tools"]').click();
  56. await $('[data-testid="preinstalled-tools-dialog"]').waitForDisplayed();
  57. await $(card()).waitForDisplayed();
  58. }
  59. async function captureUpgradePresentation() {
  60. for (const locale of ["zh-CN", "en-US"] as const) {
  61. for (const theme of ["zai-dark", "zai-light"] as const) {
  62. await setPluginPresentation({ locale, theme, width: 760, height: 640 });
  63. await browser.waitUntil(
  64. async () =>
  65. (await $(`${card()} [data-testid="preinstalled-tools-status"]`).getText()) ===
  66. (locale === "zh-CN" ? "可更新" : "Update available"),
  67. );
  68. await $(`${card()} [data-testid="preinstalled-tools-update"]`).scrollIntoView();
  69. const fits = await browser.execute(() => {
  70. const dialog = document.querySelector('[data-testid="preinstalled-tools-dialog"]')!;
  71. const box = dialog.getBoundingClientRect();
  72. return (
  73. dialog.scrollWidth <= dialog.clientWidth + 1 &&
  74. box.left >= 0 &&
  75. box.right <= innerWidth + 1
  76. );
  77. });
  78. expect(fits).toBe(true);
  79. await browser.saveScreenshot(
  80. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/upgrade-${locale}-${theme}.png`,
  81. );
  82. }
  83. }
  84. await setPluginPresentation({ locale: "zh-CN", theme: "zai-dark", width: 1000, height: 760 });
  85. await browser.waitUntil(
  86. async () =>
  87. (await $(`${card()} [data-testid="preinstalled-tools-status"]`).getText()) === "可更新",
  88. );
  89. }
  90. async function restart(setup?: () => Promise<void>) {
  91. await reloadElectronSessionPreservingBrowserProfile(browser, { afterElectronProcessExit: setup });
  92. await prepareV4ConversationE2E();
  93. await openDialog();
  94. }
  95. async function nativeHolder(directory: string) {
  96. // Windows 只按扩展名启动程序;副本需保留 .exe 才能作为真实原生进程运行。
  97. const executable = join(
  98. directory,
  99. process.platform === "win32" ? "中文 held-native.exe" : "中文 held-native",
  100. );
  101. await copyFile(process.execPath, executable);
  102. await chmod(executable, 0o755);
  103. const child = spawn(
  104. executable,
  105. ["-e", 'process.stdout.write("PT_UPGRADE_NATIVE_READY");setInterval(()=>{},1000)'],
  106. { cwd: process.cwd(), env: { PATH: process.env.PATH }, stdio: ["ignore", "pipe", "pipe"] },
  107. );
  108. const exit = once(child, "exit");
  109. const first = await Promise.race([
  110. once(child.stdout!, "data"),
  111. exit.then(() => {
  112. throw new Error("占用夹具提前退出");
  113. }),
  114. ]);
  115. expect(String(first[0])).toContain("PT_UPGRADE_NATIVE_READY");
  116. return {
  117. child,
  118. stop: async () => {
  119. if (child.exitCode === null && child.signalCode === null) {
  120. child.kill();
  121. await exit;
  122. }
  123. },
  124. };
  125. }
  126. describe("预装工具升级与启动清理(待审核)", () => {
  127. it("PT-17: 旧入口持续可用,发布切换且启动按占用回收", async function () {
  128. this.timeout(360000);
  129. const probe = resolveE2ERuntimePath("conversation-session-preinstalled-tools-upgrade");
  130. await mkdir(probe, { recursive: true });
  131. await cp(
  132. new URL(
  133. "../../../fixtures/fs/conversation-session/conversation-session-preinstalled-tools-upgrade/probe.mjs",
  134. import.meta.url,
  135. ),
  136. join(probe, "probe.mjs"),
  137. );
  138. await prepareV4ConversationE2E();
  139. for (const id of ["qpdf", "libreoffice"]) {
  140. await fetch(`${fixtureUrl()}/${id}/release`);
  141. await fetch(`${fixtureUrl()}/${id}/finish-check`);
  142. await waitStatus("ready", id);
  143. }
  144. await openDialog();
  145. await $('[data-testid="preinstalled-tools-auto-install"]').click();
  146. await browser.waitUntil(async () => (await state()).autoInstallEnabled === false);
  147. const roots = join(resolveE2EStorageRoot(), "preinstalled-tools");
  148. const root = join(roots, (await readdir(roots))[0]!);
  149. const recordPath = await preinstalledFixtureRecordPath(root);
  150. const previous = JSON.parse(await readFile(recordPath, "utf8"));
  151. const qpdfPath = await preinstalledFixtureRecordPath(root, "qpdf");
  152. const qpdf = JSON.parse(await readFile(qpdfPath, "utf8"));
  153. expect(
  154. (await state()).tools.find((tool) => tool.toolId === "libreoffice")?.installed,
  155. ).toMatchObject({ resourceId: previous.resourceId });
  156. const catalogPath = process.env.ZCODE_E2E_PREINSTALLED_TOOLS_CATALOG!;
  157. const catalog = preinstalledToolsCatalogSchema.parse(
  158. JSON.parse(await readFile(catalogPath, "utf8")),
  159. );
  160. const resource = catalog.find((tool) => tool.toolId === "libreoffice")!.resources[0]!;
  161. const expectedOutput = resource.runtimeChecks[0]!.expectedOutput;
  162. const nativeArch = resource.binaryArch;
  163. resource.resourceId += "-r2";
  164. resource.version = "26.8.2";
  165. // 小夹具只验证跨架构声明的错误分类与诊断,不声称执行了真实仿真程序。
  166. resource.binaryArch = process.arch === "arm64" ? "x64" : "arm64";
  167. resource.runtimeChecks[0]!.expectedOutput = "E2E_PT_UPGRADE_RUNTIME_MISMATCH";
  168. await restart(() => writeFile(catalogPath, JSON.stringify(catalog)));
  169. await waitStatus("not-installed");
  170. expect(await $(`${card()} [data-testid="preinstalled-tools-status"]`).getText()).toBe("可更新");
  171. expect(await $(card()).getText()).toContain("正在使用版本 26.8.1");
  172. await captureUpgradePresentation();
  173. await $(`${card()} [data-testid="preinstalled-tools-update"]`).click();
  174. await waitStatus("failed");
  175. expect((await state()).tools.find((tool) => tool.toolId === "libreoffice")?.error).toBe(
  176. "runtime",
  177. );
  178. const logDir = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR!);
  179. let failureDiagnostic: Record<string, unknown> | null = null;
  180. await browser.waitUntil(
  181. async () => {
  182. const logs = await Promise.all(
  183. (await readdir(logDir))
  184. .filter((name) => name.endsWith(".log"))
  185. .map((name) => readFile(join(logDir, name), "utf8")),
  186. );
  187. const line = logs
  188. .join("\n")
  189. .split("\n")
  190. .find(
  191. (value) =>
  192. value.includes("准备失败") && value.includes(JSON.stringify(resource.resourceId)),
  193. );
  194. if (!line) return false;
  195. failureDiagnostic = JSON.parse(line.slice(line.indexOf("{", line.indexOf("准备失败"))));
  196. expect(failureDiagnostic).toMatchObject({
  197. binaryArch: resource.binaryArch,
  198. hostArch: process.arch,
  199. errorKind: "runtime",
  200. });
  201. return true;
  202. },
  203. { timeout: 10000, timeoutMsg: "落盘失败日志缺少资源与本机架构诊断" },
  204. );
  205. expect(await $(card()).getText()).toContain("正在使用版本 26.8.1");
  206. expect(await $(`${card()} [data-testid="preinstalled-tools-delete"]`).isDisplayed()).toBe(true);
  207. const publicEntry = preinstalledEntryPath(join(root, "bin"), "zcode-soffice");
  208. expect(
  209. (
  210. await executePreinstalledEntry(join(root, "bin"), "zcode-soffice", ["--fixture-location"])
  211. ).stdout.trim(),
  212. ).toBe(join(previous.installationDir, preinstalledFixtureTarget("libreoffice")));
  213. expect(JSON.parse(await readFile(recordPath, "utf8")).resourceId).toBe(previous.resourceId);
  214. await browser.saveScreenshot(
  215. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/upgrade-failed-old-ready.png`,
  216. );
  217. resource.binaryArch = nativeArch;
  218. resource.runtimeChecks[0]!.expectedOutput = expectedOutput;
  219. await fetch(`${fixtureUrl()}/libreoffice/hold`);
  220. await fetch(`${fixtureUrl()}/libreoffice/hold-check`);
  221. await restart(() => writeFile(catalogPath, JSON.stringify(catalog)));
  222. await waitStatus("not-installed");
  223. await browser.keys("Escape");
  224. await switchV4Mode("yolo");
  225. const observations: Array<{ executable: string; available: string }> = [];
  226. let sessionId: string | null = null;
  227. const observe = async (stage: "before" | "during" | "after", directory: string) => {
  228. const marker = `E2E_PT_UPGRADE_${stage.toUpperCase()}`;
  229. await sendV4Prompt(
  230. `${marker}: Run the exact read-only preinstalled executable location probe.`,
  231. );
  232. await waitForV4AssistantMessageContaining(`${marker}_DONE`, 90000);
  233. await waitForV4ConversationState((value) => value.state === "idle", "升级入口探测未结束");
  234. const result = await getLatestUpstreamToolResultByToolCallId(`toolu_pt_upgrade_${stage}`);
  235. expect(result?.isError).toBe(false);
  236. const observed = JSON.parse(result!.content);
  237. expect(observed.available).toBe("1");
  238. expect(observed.executable).toBe(join(directory, preinstalledFixtureTarget("libreoffice")));
  239. const current = (await getV4PaneSnapshot()).sessionId;
  240. if (sessionId) expect(current).toBe(sessionId);
  241. sessionId = current;
  242. observations.push(observed);
  243. };
  244. await observe("before", previous.installationDir);
  245. await openDialog();
  246. await $(`${card()} [data-testid="preinstalled-tools-update"]`).click();
  247. await waitStatus("preparing");
  248. expect(await $(card()).getText()).toContain("正在使用版本 26.8.1");
  249. await browser.saveScreenshot(
  250. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/upgrade-preparing-old-ready.png`,
  251. );
  252. await browser.keys("Escape");
  253. await observe("during", previous.installationDir);
  254. await fetch(`${fixtureUrl()}/libreoffice/release`);
  255. await fetch(`${fixtureUrl()}/libreoffice/finish-check`);
  256. await waitStatus("ready");
  257. const installed = JSON.parse(await readFile(recordPath, "utf8"));
  258. expect(installed.resourceId).toBe(resource.resourceId);
  259. await observe("after", installed.installationDir);
  260. expect(JSON.parse(await readFile(qpdfPath, "utf8"))).toEqual(qpdf);
  261. expect((await http()).tools.qpdf!.requests).toBe(1);
  262. await expect(stat(previous.installationDir)).resolves.toBeDefined();
  263. const orphan = join(root, "tools", "libreoffice", "versions", "unpublished-orphan");
  264. await mkdir(orphan);
  265. const staging = join(root, "tools", "libreoffice", "staging");
  266. await writeFile(join(staging, "interrupted.tmp"), "unpublished");
  267. const workerPid = await browser.electron.execute(
  268. (electron) =>
  269. electron.app.getAppMetrics().find((item) => item.name === "zcode-preinstalled-tools")!.pid,
  270. );
  271. process.kill(workerPid, "SIGKILL");
  272. await browser.waitUntil(
  273. async () =>
  274. (await browser.electron.execute(
  275. (electron) =>
  276. electron.app.getAppMetrics().find((item) => item.name === "zcode-preinstalled-tools")
  277. ?.pid,
  278. )) !== workerPid,
  279. { timeout: 30000 },
  280. );
  281. await waitStatus("ready");
  282. expect(await readdir(staging)).toEqual([]);
  283. await expect(stat(orphan)).resolves.toBeDefined();
  284. await expect(stat(previous.installationDir)).resolves.toBeDefined();
  285. const requests = (await http()).requests;
  286. let holder: Awaited<ReturnType<typeof nativeHolder>> | undefined;
  287. try {
  288. // 重启 helper 会按 HOME 回收旧进程;退出屏障之后再建占用,才能测到新 App 的真实保护。
  289. await restart(async () => {
  290. holder = await nativeHolder(join(previous.installationDir, "bin"));
  291. });
  292. await waitStatus("ready");
  293. expect(holder!.child.exitCode).toBeNull();
  294. expect(holder!.child.signalCode).toBeNull();
  295. await expect(stat(orphan)).rejects.toHaveProperty("code", "ENOENT");
  296. await expect(stat(previous.installationDir)).resolves.toBeDefined();
  297. expect((await http()).requests).toBe(requests);
  298. } finally {
  299. await holder?.stop();
  300. }
  301. await restart();
  302. await waitStatus("ready");
  303. await expect(stat(previous.installationDir)).rejects.toHaveProperty("code", "ENOENT");
  304. expect((await http()).requests).toBe(requests);
  305. resource.resourceId += "-r3";
  306. resource.version = "26.8.3";
  307. await fetch(`${fixtureUrl()}/libreoffice/hold`);
  308. await restart(() => writeFile(catalogPath, JSON.stringify(catalog)));
  309. await $(`${card()} [data-testid="preinstalled-tools-update"]`).click();
  310. await waitStatus("preparing");
  311. await browser.waitUntil(async () => (await http()).requests === requests + 1);
  312. await restart();
  313. await waitStatus("not-installed");
  314. expect(await readdir(staging)).toEqual([]);
  315. expect((await http()).requests).toBe(requests + 1);
  316. expect(
  317. (await state()).tools.find((tool) => tool.toolId === "libreoffice")?.installed?.resourceId,
  318. ).toBe(installed.resourceId);
  319. const remaining = catalog.filter((tool) => tool.toolId === "libreoffice");
  320. remaining[0]!.resources = [];
  321. await restart(() => writeFile(catalogPath, JSON.stringify(remaining)));
  322. await waitStatus("ready");
  323. await expect(stat(preinstalledEntryPath(join(root, "bin"), "qpdf"))).rejects.toHaveProperty(
  324. "code",
  325. "ENOENT",
  326. );
  327. await expect(stat(join(root, "tools", "qpdf"))).rejects.toHaveProperty("code", "ENOENT");
  328. expect(await $(card()).getText()).toContain("当前版本暂未提供此工具");
  329. expect(await $(card()).getText()).toContain("正在使用版本 26.8.2");
  330. await browser.saveScreenshot(
  331. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/upgrade-installed-without-target.png`,
  332. );
  333. await $(`${card()} [data-testid="preinstalled-tools-delete"]`).click();
  334. await $('[data-testid="preinstalled-tools-delete-confirm-accept"]').click();
  335. await waitStatus("not-installed");
  336. expect(
  337. (await state()).tools.find((tool) => tool.toolId === "libreoffice")?.installed,
  338. ).toBeNull();
  339. await expect(stat(publicEntry)).rejects.toHaveProperty("code", "ENOENT");
  340. await writeFile(
  341. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "upgrade-facts.json"),
  342. JSON.stringify(
  343. { previous, installed, qpdf, observations, failureDiagnostic, requests: await http() },
  344. null,
  345. 2,
  346. ),
  347. );
  348. });
  349. });