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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import { pinE2ELocale } from "#e2e/helpers/desktop-app";
  2. import {
  3. PREINSTALLED_FIXTURE_PROGRAM,
  4. preinstalledFixtureRecordPath,
  5. preinstalledEntryPath,
  6. } from "#e2e/helpers/preinstalled-tools-fixture";
  7. import {
  8. copyFile,
  9. chmod,
  10. mkdir,
  11. open,
  12. readFile,
  13. readdir,
  14. rm,
  15. stat,
  16. writeFile,
  17. } from "node:fs/promises";
  18. import { basename, join, resolve } from "node:path";
  19. import { randomUUID } from "node:crypto";
  20. import { spawn, type ChildProcess } from "node:child_process";
  21. import { once } from "node:events";
  22. import type { PreinstalledToolsState } from "@zcode/shared/preinstalled-tools";
  23. import {
  24. TID_RESOURCE_MANAGER_STORAGE_CATEGORY_CLEAN,
  25. TID_RESOURCE_MANAGER_STORAGE_CATEGORY_ROW,
  26. TID_RESOURCE_MANAGER_STORAGE_STATUS,
  27. testId,
  28. } from "@zcode/shared/test-ids";
  29. import { resolveE2EHomeDir, resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  30. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  31. import { setPluginPresentation } from "#e2e/helpers/plugin-management-lifecycle";
  32. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  33. import {
  34. activateResourceManagerTab,
  35. isMainRendererUrl,
  36. isResourceManagerUrl,
  37. openResourceManager,
  38. switchToElectronRendererTarget,
  39. waitForResourceManagerReady,
  40. } from "#e2e/helpers/resource-manager";
  41. const fixtureUrl = () => process.env.ZCODE_E2E_PREINSTALL_FIXTURE_URL!;
  42. const screenshot = (name: string) =>
  43. browser.saveScreenshot(`${process.env.ZCODE_E2E_ARTIFACT_DIR}/lop-delete-${name}.png`);
  44. async function openDialog() {
  45. await $('[data-testid="workspace-help-menu-trigger"]').click();
  46. await $('[data-testid="workspace-help-menu-preinstalled-tools"]').click();
  47. await $('[data-testid="preinstalled-tools-dialog"]').waitForDisplayed();
  48. }
  49. async function waitStatus(status: string) {
  50. await browser.waitUntil(
  51. async () =>
  52. (await $(
  53. '[data-tool-id="libreoffice"] [data-testid="preinstalled-tools-status"]',
  54. ).getAttribute("data-status")) === status,
  55. { timeout: 30000, timeoutMsg: `预装状态未达到 ${status}` },
  56. );
  57. }
  58. async function attemptDelete() {
  59. await $('[data-testid="preinstalled-tools-delete"]').click();
  60. await $('[data-testid="preinstalled-tools-delete-confirm"]').waitForDisplayed();
  61. await $('[data-testid="preinstalled-tools-delete-confirm-accept"]').click();
  62. await $('[data-testid="preinstalled-tools-delete-confirm"]').waitForDisplayed({ reverse: true });
  63. }
  64. async function waitBlocked() {
  65. await $('[data-testid="preinstalled-tools-delete-blocked"]').waitForDisplayed();
  66. await browser.waitUntil(async () => $('[data-testid="preinstalled-tools-delete"]').isEnabled(), {
  67. timeout: 10000,
  68. });
  69. await waitStatus("ready");
  70. }
  71. async function nativeHolder(directory: string) {
  72. await mkdir(directory, { recursive: true });
  73. // Windows 只按扩展名启动程序;副本需保留 .exe 才能作为真实原生进程运行。
  74. const executable = join(
  75. directory,
  76. process.platform === "win32" ? "中文 held-native.exe" : "中文 held-native",
  77. );
  78. await copyFile(process.execPath, executable);
  79. await chmod(executable, 0o755);
  80. // 真实原生程序位于受管目录;不用外部 shell/curl 的 PID 冒充目录内进程。
  81. const child = spawn(
  82. executable,
  83. ["-e", 'process.stdout.write("LOP_NATIVE_READY");setInterval(()=>{},1000)'],
  84. { cwd: process.cwd(), env: { PATH: process.env.PATH }, stdio: ["ignore", "pipe", "pipe"] },
  85. );
  86. const exit = once(child, "exit");
  87. const data = await Promise.race([
  88. once(child.stdout!, "data"),
  89. exit.then(() => {
  90. throw new Error("原生占用夹具提前退出");
  91. }),
  92. ]);
  93. expect(String(data[0])).toContain("LOP_NATIVE_READY");
  94. return {
  95. child,
  96. stop: async () => {
  97. if (child.exitCode === null && child.signalCode === null) {
  98. child.kill();
  99. await exit;
  100. }
  101. },
  102. };
  103. }
  104. async function reload(setup?: () => Promise<void>) {
  105. await reloadElectronSessionPreservingBrowserProfile(browser, { afterElectronProcessExit: setup });
  106. await prepareV4ConversationE2E();
  107. // 宿主可能使用英文,环境变量不能保证 macOS 界面语言;固定语言后再核对中文文案。
  108. await pinE2ELocale("zh-CN");
  109. await openDialog();
  110. }
  111. describe("预装工具删除与存储(待审核)", () => {
  112. it("LOP-25/26/28: 删除确认、占用保护、旧版本和存储归属", async function () {
  113. this.timeout(480000);
  114. let holder: { child: ChildProcess; stop(): Promise<void> } | undefined;
  115. let restorePermissions: string | undefined;
  116. try {
  117. await prepareV4ConversationE2E();
  118. await pinE2ELocale("zh-CN");
  119. await fetch(`${fixtureUrl()}/release`);
  120. await fetch(`${fixtureUrl()}/finish-check`);
  121. await openDialog();
  122. await waitStatus("ready");
  123. const storageRoot = resolveE2EStorageRoot();
  124. expect(storageRoot).toBe(join(resolveE2EHomeDir(), ".zcode"));
  125. const roots = join(storageRoot, "preinstalled-tools");
  126. const release = (await readdir(roots))[0]!;
  127. const root = join(roots, release);
  128. const recordPath = await preinstalledFixtureRecordPath(root);
  129. const versions = join(root, "tools", "libreoffice", "versions");
  130. const entry = preinstalledEntryPath(join(root, "bin"), "zcode-soffice");
  131. expect((await stat(entry)).isFile()).toBe(true);
  132. let record = JSON.parse(await readFile(recordPath, "utf8"));
  133. const firstInstalledAt = record.installedAt;
  134. await $('[data-testid="preinstalled-tools-delete"]').waitForDisplayed({ timeout: 10000 });
  135. await $('[data-testid="preinstalled-tools-delete"]').click();
  136. // 对话框挂载不等于可见;过渡期间 getText 曾返回空值,先观察真实显示状态。
  137. await $('[data-testid="preinstalled-tools-delete-confirm"]').waitForDisplayed();
  138. expect(await $('[data-testid="preinstalled-tools-delete-confirm"]').getText()).toContain(
  139. "下次启动",
  140. );
  141. await screenshot("confirm-auto-on");
  142. await $('[data-testid="preinstalled-tools-delete-confirm-cancel"]').click();
  143. await $('[data-testid="preinstalled-tools-auto-install"]').click();
  144. await browser.waitUntil(
  145. async () =>
  146. (await $('[data-testid="preinstalled-tools-auto-install"]').getAttribute(
  147. "aria-checked",
  148. )) === "false",
  149. { timeout: 10000 },
  150. );
  151. await setPluginPresentation({
  152. locale: "en-US",
  153. theme: "zai-light",
  154. width: 1000,
  155. height: 760,
  156. });
  157. await $('[data-testid="preinstalled-tools-delete"]').click();
  158. // 对话框挂载不等于可见;过渡期间 getText 曾返回空值,先观察真实显示状态。
  159. await $('[data-testid="preinstalled-tools-delete-confirm"]').waitForDisplayed();
  160. expect(await $('[data-testid="preinstalled-tools-delete-confirm"]').getText()).not.toContain(
  161. "next time",
  162. );
  163. await screenshot("confirm-auto-off-light");
  164. await $('[data-testid="preinstalled-tools-delete-confirm-cancel"]').click();
  165. await setPluginPresentation({ locale: "zh-CN", theme: "zai-dark", width: 1000, height: 760 });
  166. holder = await nativeHolder(join(record.installationDir, "bin"));
  167. await attemptDelete();
  168. await waitBlocked();
  169. expect(JSON.parse(await readFile(recordPath, "utf8")).installedAt).toBe(firstInstalledAt);
  170. expect((await stat(entry)).isFile()).toBe(true);
  171. await screenshot("native-busy");
  172. const deadPid = holder.child.pid!;
  173. await holder.stop();
  174. holder = undefined;
  175. const usage = join(root, "usage");
  176. await mkdir(usage, { recursive: true });
  177. // Windows 文件名不能含冒号;这些历史标记只需名字唯一,不解析时间。
  178. const markerStamp = firstInstalledAt.replaceAll(":", "-");
  179. const activeMarker = join(usage, `${markerStamp}.${process.pid}.${randomUUID()}`);
  180. await mkdir(activeMarker);
  181. // 通用合同已删除调用标记;这些历史文件不再代表真实占用,也不由删除链路维护。
  182. // 真实权限故障不能被视为无占用;恢复权限后用户仍能重试。
  183. // 该故障依赖 POSIX 目录权限让 lsof//proc 探针无法确认;Windows 按进程可执行路径探测,
  184. // chmod 也不限制目录访问,制造不出同一前提,只在 POSIX 执行。
  185. if (process.platform !== "win32") {
  186. restorePermissions = versions;
  187. await chmod(versions, 0o000);
  188. await attemptDelete();
  189. await waitBlocked();
  190. await chmod(versions, 0o755);
  191. restorePermissions = undefined;
  192. }
  193. const staleMarker = join(usage, `${markerStamp}.${deadPid}.${randomUUID()}`);
  194. await mkdir(staleMarker);
  195. const otherRelease = join(roots, release === "preview" ? "production" : "preview");
  196. await mkdir(otherRelease, { recursive: true });
  197. await writeFile(join(otherRelease, "keep.txt"), "other-release");
  198. // 普通文件读取不会像程序/库映射一样阻止删除。
  199. const reader = await open(join(record.installationDir, PREINSTALLED_FIXTURE_PROGRAM));
  200. try {
  201. await attemptDelete();
  202. await waitStatus("not-installed");
  203. await browser.waitUntil(
  204. async () => $('[data-testid="preinstalled-tools-download"]').isEnabled(),
  205. { timeout: 10000 },
  206. );
  207. } finally {
  208. await reader.close();
  209. }
  210. await expect(stat(entry)).rejects.toHaveProperty("code", "ENOENT");
  211. await expect(stat(recordPath)).rejects.toHaveProperty("code", "ENOENT");
  212. expect(await readdir(versions)).toEqual([]);
  213. expect((await readdir(usage)).sort()).toEqual(
  214. [basename(activeMarker), basename(staleMarker)].sort(),
  215. );
  216. expect(await readFile(join(otherRelease, "keep.txt"), "utf8")).toBe("other-release");
  217. expect(
  218. await $('[data-testid="preinstalled-tools-auto-install"]').getAttribute("aria-checked"),
  219. ).toBe("false");
  220. await screenshot("deleted");
  221. await $('[data-testid="preinstalled-tools-download"]').click();
  222. await waitStatus("ready");
  223. record = JSON.parse(await readFile(recordPath, "utf8"));
  224. expect(record.installedAt).not.toBe(firstInstalledAt);
  225. const oldAfterPublish = join(versions, "fixture-old-after-publish");
  226. await mkdir(oldAfterPublish);
  227. await writeFile(join(oldAfterPublish, "keep-until-app-start.txt"), "old");
  228. const workerBeforeCrash = await browser.electron.execute(
  229. (electron) =>
  230. electron.app.getAppMetrics().find((item) => item.name === "zcode-preinstalled-tools")
  231. ?.pid,
  232. );
  233. expect(workerBeforeCrash).toBeDefined();
  234. await browser.electron.execute((_electron, pid) => {
  235. process.kill(pid!, "SIGKILL");
  236. }, workerBeforeCrash);
  237. await browser.waitUntil(
  238. async () => {
  239. const pid = await browser.electron.execute(
  240. (electron) =>
  241. electron.app.getAppMetrics().find((item) => item.name === "zcode-preinstalled-tools")
  242. ?.pid,
  243. );
  244. return Boolean(pid && pid !== workerBeforeCrash);
  245. },
  246. { timeout: 15000 },
  247. );
  248. await browser.execute(async () =>
  249. (
  250. window as typeof window & {
  251. zcode: { getPreinstalledToolsState(): Promise<PreinstalledToolsState> };
  252. }
  253. ).zcode.getPreinstalledToolsState(),
  254. );
  255. expect((await stat(oldAfterPublish)).isDirectory()).toBe(true);
  256. const oldBusy = join(versions, "fixture-old-busy");
  257. const oldIdle = join(versions, "fixture-old-idle");
  258. await browser.keys("Escape");
  259. await reload(async () => {
  260. await mkdir(oldIdle);
  261. await writeFile(join(oldIdle, "keep-until-start.txt"), "old");
  262. holder = await nativeHolder(oldBusy);
  263. });
  264. await waitStatus("ready");
  265. expect((await stat(oldBusy)).isDirectory()).toBe(true);
  266. await expect(stat(oldIdle)).rejects.toHaveProperty("code", "ENOENT");
  267. await expect(stat(oldAfterPublish)).rejects.toHaveProperty("code", "ENOENT");
  268. await holder!.stop();
  269. holder = undefined;
  270. await browser.keys("Escape");
  271. await reload();
  272. await waitStatus("ready");
  273. await expect(stat(oldBusy)).rejects.toHaveProperty("code", "ENOENT");
  274. expect(JSON.parse(await readFile(recordPath, "utf8")).installedAt).toBe(record.installedAt);
  275. // 外部文件系统夹具重放“记录已撤销、进程退出前未删完”的持久边界。
  276. await browser.keys("Escape");
  277. await reload(async () => {
  278. await rm(recordPath);
  279. holder = await nativeHolder(join(record.installationDir, "bin"));
  280. });
  281. await waitStatus("not-installed");
  282. await expect(stat(recordPath)).rejects.toHaveProperty("code", "ENOENT");
  283. expect((await stat(record.installationDir)).isDirectory()).toBe(true);
  284. const beforeRetry = (await (await fetch(`${fixtureUrl()}/status`)).json()) as {
  285. requests: number;
  286. };
  287. await $('[data-testid="preinstalled-tools-download"]').click();
  288. await waitStatus("failed");
  289. expect(
  290. ((await (await fetch(`${fixtureUrl()}/status`)).json()) as { requests: number }).requests,
  291. ).toBe(beforeRetry.requests + 1);
  292. await holder!.stop();
  293. holder = undefined;
  294. await $('[data-testid="preinstalled-tools-retry"]').click();
  295. await waitStatus("ready");
  296. record = JSON.parse(await readFile(recordPath, "utf8"));
  297. await browser.keys("Escape");
  298. await openResourceManager();
  299. await switchToElectronRendererTarget(isResourceManagerUrl);
  300. await waitForResourceManagerReady();
  301. await activateResourceManagerTab("storage");
  302. await browser.waitUntil(
  303. async () =>
  304. (await $(`[data-testid="${TID_RESOURCE_MANAGER_STORAGE_STATUS}"]`).getAttribute(
  305. "data-state",
  306. )) === "complete",
  307. { timeout: 60000 },
  308. );
  309. expect(
  310. await $(
  311. `[data-testid="${testId(TID_RESOURCE_MANAGER_STORAGE_CATEGORY_ROW, "preinstalledTools")}"]`,
  312. ).isDisplayed(),
  313. ).toBe(true);
  314. expect(
  315. await $(
  316. `[data-testid="${testId(TID_RESOURCE_MANAGER_STORAGE_CATEGORY_CLEAN, "preinstalledTools")}"]`,
  317. ).isExisting(),
  318. ).toBe(false);
  319. const storage = await browser.execute(async () => {
  320. const bridge = (
  321. window as typeof window & {
  322. resourceManager: {
  323. storage: {
  324. getSnapshot(): Promise<{ roots: Array<{ id: string; path: string }> }>;
  325. clean(request: { rootId: string; categoryId: string }): Promise<unknown>;
  326. };
  327. };
  328. }
  329. ).resourceManager.storage;
  330. const snapshot = await bridge.getSnapshot();
  331. let error = "";
  332. try {
  333. await bridge.clean({ rootId: "home", categoryId: "preinstalledTools" });
  334. } catch (caught) {
  335. error = String(caught);
  336. }
  337. return { snapshot, blockedMessage: error };
  338. });
  339. expect(
  340. storage.snapshot.roots.some((item) => resolve(item.path) === resolve(storageRoot)),
  341. ).toBe(true);
  342. expect(storage.blockedMessage).toContain("not cleanable");
  343. await screenshot("storage");
  344. await browser.electron.execute((electron) => {
  345. for (const window of electron.BrowserWindow.getAllWindows())
  346. if (window.webContents.getURL().includes("resource-manager.html")) window.close();
  347. });
  348. await switchToElectronRendererTarget(isMainRendererUrl);
  349. await writeFile(
  350. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "lop-delete-facts.json"),
  351. JSON.stringify(
  352. {
  353. release,
  354. recordPath,
  355. installedAt: record.installedAt,
  356. oldVersionsCleaned: true,
  357. workerRestartKeptOld: true,
  358. },
  359. null,
  360. 2,
  361. ),
  362. );
  363. } finally {
  364. if (restorePermissions) await chmod(restorePermissions, 0o755);
  365. await holder?.stop();
  366. // 本用例的原生确认替代会自行恢复,避免退出后访问旧 CDP 掩盖原始错误。
  367. }
  368. });
  369. });