conversation-session-preinstalled-tools-agent-switch.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import { cp, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import type { PreinstalledToolsState } from "@zcode/shared/preinstalled-tools";
  4. import {
  5. lockPreinstalledDirectory,
  6. preinstalledFixtureRecordPath,
  7. unlockPreinstalledDirectory,
  8. preinstalledEntryPath,
  9. } from "#e2e/helpers/preinstalled-tools-fixture";
  10. import { resolveE2ERuntimePath, resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  11. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  12. import { setPluginPresentation } from "#e2e/helpers/plugin-management-lifecycle";
  13. import { getLatestUpstreamToolResultByToolCallId } from "#e2e/helpers/conversation-session-network";
  14. import {
  15. getV4PaneSnapshot,
  16. prepareV4ConversationE2E,
  17. sendV4Prompt,
  18. switchV4Mode,
  19. waitForV4AssistantMessageContaining,
  20. waitForV4ConversationState,
  21. } from "#e2e/helpers/v4-conversation";
  22. const fixtureUrl = () => process.env.ZCODE_E2E_PREINSTALL_FIXTURE_URL!;
  23. const card = (toolId: string) =>
  24. `[data-testid="preinstalled-tools-card"][data-tool-id="${toolId}"]`;
  25. const toggle = (toolId: string) =>
  26. $(`${card(toolId)} [data-testid="preinstalled-tools-agent-enabled"]`);
  27. const snapshot = () =>
  28. browser.execute(async () =>
  29. (
  30. window as typeof window & {
  31. zcode: { getPreinstalledToolsState(): Promise<PreinstalledToolsState> };
  32. }
  33. ).zcode.getPreinstalledToolsState(),
  34. );
  35. const requests = async () =>
  36. (await (await fetch(`${fixtureUrl()}/status`)).json()).requests as number;
  37. const syncRetry = (toolId: string) =>
  38. $(`${card(toolId)} [data-testid="preinstalled-tools-sync-entries"]`);
  39. async function waitEntrySync(toolId: string, outOfSync: boolean) {
  40. await browser.waitUntil(
  41. async () =>
  42. (await snapshot()).tools.find((tool) => tool.toolId === toolId)?.entryOutOfSync ===
  43. outOfSync && (await toggle(toolId).isEnabled()),
  44. { timeout: 10000 },
  45. );
  46. expect(
  47. await $(`${card(toolId)} [data-testid="preinstalled-tools-entry-out-of-sync"]`).isExisting(),
  48. ).toBe(outOfSync);
  49. }
  50. async function deleteTool(toolId: string) {
  51. await $(`${card(toolId)} [data-testid="preinstalled-tools-delete"]`).click();
  52. await $('[data-testid="preinstalled-tools-delete-confirm-accept"]').click();
  53. }
  54. async function openDialog() {
  55. await $('[data-testid="workspace-help-menu-trigger"]').click();
  56. await $('[data-testid="workspace-help-menu-preinstalled-tools"]').click();
  57. await $('[data-testid="preinstalled-tools-dialog"]').waitForDisplayed();
  58. }
  59. async function setEnabled(toolId: string, enabled: boolean, keyboard = false) {
  60. const control = toggle(toolId);
  61. await control.scrollIntoView();
  62. if ((await control.getAttribute("aria-checked")) !== String(enabled)) {
  63. if (keyboard) {
  64. await control.execute((element) => element.focus());
  65. await browser.keys("Space");
  66. } else await control.click();
  67. }
  68. await browser.waitUntil(
  69. async () =>
  70. (await control.getAttribute("aria-checked")) === String(enabled) &&
  71. (await control.isEnabled()),
  72. { timeout: 10000 },
  73. );
  74. }
  75. async function waitStatus(toolId: string, status: string) {
  76. await browser.waitUntil(
  77. async () =>
  78. (await $(`${card(toolId)} [data-testid="preinstalled-tools-status"]`).getAttribute(
  79. "data-status",
  80. )) === status,
  81. { timeout: 60000 },
  82. );
  83. }
  84. describe("每工具 Agent 使用开关(待审核)", () => {
  85. it("PT-14/23 LO-06: 原会话切换、隔离、失败与持久化", async function () {
  86. this.timeout(360000);
  87. const directory = resolveE2ERuntimePath("conversation-session-preinstalled-tools-agent-switch");
  88. const system = join(directory, "system-bin");
  89. await mkdir(system, { recursive: true });
  90. await cp(
  91. new URL(
  92. "../../../fixtures/fs/conversation-session/conversation-session-preinstalled-tools-agent-switch/probe.mjs",
  93. import.meta.url,
  94. ),
  95. join(directory, "probe.mjs"),
  96. );
  97. await writeFile(join(system, "qpdf"), "#!/bin/sh\nprintf 'system-qpdf\\n'\n", { mode: 0o755 });
  98. await writeFile(join(system, "soffice"), "#!/bin/sh\nprintf 'LibreOffice 26.2.0\\n'\n", {
  99. mode: 0o755,
  100. });
  101. if (process.platform === "win32") {
  102. // Git Bash 按无扩展名脚本查找,cmd 按 .cmd 查找;两种调用都要落到假系统程序。
  103. await writeFile(join(system, "qpdf.cmd"), "@echo system-qpdf\r\n");
  104. await writeFile(join(system, "soffice.cmd"), "@echo LibreOffice 26.2.0\r\n");
  105. }
  106. await writeFile(
  107. join(directory, "config.json"),
  108. JSON.stringify({
  109. storageRoot: resolveE2EStorageRoot(),
  110. python: process.env.ZCODE_E2E_DOCUMENT_PYTHON || "python3",
  111. }),
  112. );
  113. await prepareV4ConversationE2E();
  114. await switchV4Mode("yolo");
  115. await openDialog();
  116. await waitStatus("qpdf", "preparing");
  117. await setEnabled("qpdf", false, true);
  118. await waitStatus("qpdf", "preparing");
  119. for (const toolId of ["qpdf", "libreoffice"]) {
  120. await fetch(`${fixtureUrl()}/${toolId}/finish-check`);
  121. await fetch(`${fixtureUrl()}/${toolId}/release`);
  122. await waitStatus(toolId, "ready");
  123. }
  124. const roots = join(resolveE2EStorageRoot(), "preinstalled-tools");
  125. const root = join(roots, (await readdir(roots))[0]!);
  126. const bin = join(root, "bin");
  127. const qpdfRecord = await preinstalledFixtureRecordPath(root, "qpdf");
  128. const officeRecord = await preinstalledFixtureRecordPath(root);
  129. await expect(stat(preinstalledEntryPath(bin, "qpdf"))).rejects.toHaveProperty("code", "ENOENT");
  130. expect(JSON.parse(await readFile(qpdfRecord, "utf8")).toolId).toBe("qpdf");
  131. await $('[data-testid="preinstalled-tools-auto-install"]').click();
  132. await browser.waitUntil(
  133. async () =>
  134. (await $('[data-testid="preinstalled-tools-auto-install"]').getAttribute(
  135. "aria-checked",
  136. )) === "false",
  137. { timeout: 10000 },
  138. );
  139. const observations = [];
  140. let sessionId: string | null = null;
  141. for (const [stage, qpdfManaged, officeManaged] of [
  142. ["BEFORE", false, true],
  143. ["ON", true, true],
  144. ["OFF", true, false],
  145. ["RESTORED", true, true],
  146. ] as const) {
  147. if (stage === "ON") await setEnabled("qpdf", true);
  148. if (stage === "OFF") await setEnabled("libreoffice", false);
  149. if (stage === "RESTORED") await setEnabled("libreoffice", true);
  150. await browser.keys("Escape");
  151. const marker = `E2E_PT_AGENT_${stage}`;
  152. await sendV4Prompt(`${marker}: Run the exact read-only preinstalled-tools selection probe.`);
  153. await waitForV4AssistantMessageContaining(`${marker}_DONE`, 90000);
  154. await waitForV4ConversationState((state) => state.state === "idle", "入口探测未结束");
  155. const result = await getLatestUpstreamToolResultByToolCallId(
  156. `toolu_pt_agent_${stage.toLowerCase()}`,
  157. );
  158. expect(result?.isError).toBe(false);
  159. const observed = JSON.parse(result!.content);
  160. expect(observed.pathFirst).toBe(bin);
  161. // 预装入口在 Windows 上是 qpdf.exe;假系统程序仍是无扩展名的 sh 脚本,由 Git Bash 运行。
  162. expect(observed.qpdfPath).toBe(
  163. qpdfManaged ? preinstalledEntryPath(bin, "qpdf") : join(system, "qpdf"),
  164. );
  165. expect(observed.qpdf).toContain(qpdfManaged ? "qpdf fixture" : "system-qpdf");
  166. expect(observed.office.source).toBe(officeManaged ? "managed" : "system");
  167. if (!officeManaged) expect(observed.officeNotice).toContain("未就绪或已关闭");
  168. const current = (await getV4PaneSnapshot()).sessionId;
  169. if (sessionId) expect(current).toBe(sessionId);
  170. sessionId = current;
  171. observations.push({ stage, ...observed });
  172. await openDialog();
  173. }
  174. // 从可读但不可写的设置目录制造真实保存失败,不注入 UI/store 状态。
  175. const settingsDirectory = join(resolveE2EStorageRoot(), "v2");
  176. try {
  177. await lockPreinstalledDirectory(settingsDirectory);
  178. await toggle("qpdf").click();
  179. await $(
  180. `${card("qpdf")} [data-testid="preinstalled-tools-command-error"]`,
  181. ).waitForDisplayed();
  182. expect(await toggle("qpdf").getAttribute("aria-checked")).toBe("true");
  183. expect(await stat(preinstalledEntryPath(bin, "qpdf"))).toBeDefined();
  184. expect(await $$("[data-sonner-toast]").length).toBe(0);
  185. } finally {
  186. await unlockPreinstalledDirectory(settingsDirectory);
  187. }
  188. // 设置已保存但 bin 删除失败:观察公开快照和真实文件,不再把旧开关当作事实。
  189. const settingsPath = join(settingsDirectory, "setting.json");
  190. const requestsBeforeRetry = await requests();
  191. let failedSnapshot: PreinstalledToolsState;
  192. let savedAfterFailure: string;
  193. try {
  194. await lockPreinstalledDirectory(bin);
  195. await setEnabled("qpdf", false);
  196. await waitEntrySync("qpdf", true);
  197. failedSnapshot = await snapshot();
  198. expect(failedSnapshot.tools.find((tool) => tool.toolId === "qpdf")).toMatchObject({
  199. agentEnabled: false,
  200. entryOutOfSync: true,
  201. status: "ready",
  202. });
  203. expect(failedSnapshot.tools.find((tool) => tool.toolId === "qpdf")?.error ?? null).toBeNull();
  204. savedAfterFailure = await readFile(settingsPath, "utf8");
  205. expect(JSON.parse(savedAfterFailure).preinstalledToolsAgentDisabled).toEqual(["qpdf"]);
  206. expect(await stat(preinstalledEntryPath(bin, "qpdf"))).toBeDefined();
  207. expect(
  208. await $(`${card("qpdf")} [data-testid="preinstalled-tools-delete"]`).isExisting(),
  209. ).toBe(true);
  210. const workerPid = await browser.electron.execute(
  211. (electron) =>
  212. electron.app.getAppMetrics().find((item) => item.name === "zcode-preinstalled-tools")!
  213. .pid,
  214. );
  215. process.kill(workerPid, "SIGKILL");
  216. await browser.waitUntil(
  217. async () => {
  218. const pid = await browser.electron.execute(
  219. (electron) =>
  220. electron.app.getAppMetrics().find((item) => item.name === "zcode-preinstalled-tools")
  221. ?.pid,
  222. );
  223. return Boolean(pid && pid !== workerPid);
  224. },
  225. { timeout: 30000 },
  226. );
  227. for (const toolId of ["qpdf", "libreoffice"]) {
  228. await waitStatus(toolId, "ready");
  229. await waitEntrySync(toolId, true);
  230. expect(
  231. (await snapshot()).tools.find((tool) => tool.toolId === toolId)?.error ?? null,
  232. ).toBeNull();
  233. }
  234. expect((await snapshot()).tools.find((tool) => tool.toolId === "qpdf")?.agentEnabled).toBe(
  235. false,
  236. );
  237. await browser.keys("Escape");
  238. await openDialog();
  239. await waitEntrySync("qpdf", true);
  240. await syncRetry("qpdf").click();
  241. await waitEntrySync("qpdf", true);
  242. expect(await readFile(settingsPath, "utf8")).toBe(savedAfterFailure);
  243. expect(await requests()).toBe(requestsBeforeRetry);
  244. } finally {
  245. await unlockPreinstalledDirectory(bin);
  246. }
  247. await syncRetry("qpdf").click();
  248. await waitEntrySync("qpdf", false);
  249. await syncRetry("libreoffice").click();
  250. await waitEntrySync("libreoffice", false);
  251. await expect(stat(preinstalledEntryPath(bin, "qpdf"))).rejects.toHaveProperty("code", "ENOENT");
  252. expect(await readFile(settingsPath, "utf8")).toBe(savedAfterFailure!);
  253. expect(await requests()).toBe(requestsBeforeRetry);
  254. // 删除第一步无法撤入口时必须停止,不能删除仍被入口引用的有效资源。
  255. await setEnabled("qpdf", true);
  256. const beforeDelete = await readFile(qpdfRecord, "utf8");
  257. const installationDir = JSON.parse(beforeDelete).installationDir;
  258. try {
  259. await lockPreinstalledDirectory(bin);
  260. await deleteTool("qpdf");
  261. await waitEntrySync("qpdf", true);
  262. expect(await readFile(qpdfRecord, "utf8")).toBe(beforeDelete);
  263. expect(await stat(installationDir)).toBeDefined();
  264. expect((await snapshot()).tools.find((tool) => tool.toolId === "qpdf")).toMatchObject({
  265. status: "ready",
  266. agentEnabled: true,
  267. entryOutOfSync: true,
  268. });
  269. for (const locale of ["zh-CN", "en-US"] as const)
  270. for (const theme of ["zai-light", "zai-dark"] as const) {
  271. await setPluginPresentation({ locale, theme, width: 760, height: 640 });
  272. await syncRetry("qpdf").scrollIntoView();
  273. const layout = await browser.execute(() => {
  274. const dialog = document.querySelector<HTMLElement>(
  275. '[data-testid="preinstalled-tools-dialog"]',
  276. )!;
  277. const rect = dialog.getBoundingClientRect();
  278. return {
  279. overflow: dialog.scrollWidth > dialog.clientWidth + 1,
  280. left: rect.left,
  281. right: rect.right,
  282. bottom: rect.bottom,
  283. width: innerWidth,
  284. height: innerHeight,
  285. };
  286. });
  287. expect(layout.overflow).toBe(false);
  288. expect(layout.left).toBeGreaterThanOrEqual(0);
  289. expect(layout.right).toBeLessThanOrEqual(layout.width + 1);
  290. expect(layout.bottom).toBeLessThanOrEqual(layout.height + 1);
  291. await browser.saveScreenshot(
  292. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/agent-switch-unsynced-${locale}-${theme}.png`,
  293. );
  294. }
  295. await setPluginPresentation({ locale: "zh-CN", theme: "zai-dark", width: 1000, height: 760 });
  296. } finally {
  297. await unlockPreinstalledDirectory(bin);
  298. }
  299. await syncRetry("qpdf").click();
  300. await waitEntrySync("qpdf", false);
  301. expect(await requests()).toBe(requestsBeforeRetry);
  302. // 发布点之后写入口失败:资源仍就绪,重试只补入口,不能重复下载或回滚记录。
  303. await deleteTool("qpdf");
  304. await waitStatus("qpdf", "not-installed");
  305. const enabledSettings = await readFile(settingsPath, "utf8");
  306. try {
  307. await lockPreinstalledDirectory(bin);
  308. await $(`${card("qpdf")} [data-testid="preinstalled-tools-download"]`).click();
  309. await waitStatus("qpdf", "ready");
  310. await waitEntrySync("qpdf", true);
  311. expect(await stat(qpdfRecord)).toBeDefined();
  312. expect(await stat(installationDir)).toBeDefined();
  313. expect(
  314. (await snapshot()).tools.find((tool) => tool.toolId === "qpdf")?.error ?? null,
  315. ).toBeNull();
  316. } finally {
  317. await unlockPreinstalledDirectory(bin);
  318. }
  319. const requestsAfterPublication = await requests();
  320. expect(requestsAfterPublication).toBe(requestsBeforeRetry + 1);
  321. const publishedRecord = await readFile(qpdfRecord, "utf8");
  322. await syncRetry("qpdf").click();
  323. await waitEntrySync("qpdf", false);
  324. expect(await stat(preinstalledEntryPath(bin, "qpdf"))).toBeDefined();
  325. expect(await readFile(qpdfRecord, "utf8")).toBe(publishedRecord);
  326. expect(JSON.parse(await readFile(settingsPath, "utf8")).preinstalledToolsAgentDisabled).toEqual(
  327. JSON.parse(enabledSettings).preinstalledToolsAgentDisabled,
  328. );
  329. expect(await requests()).toBe(requestsAfterPublication);
  330. // 重现旧缺陷的完整序列:关闭失败后删除、再次发布,入口不能按旧缓存复活。
  331. try {
  332. await lockPreinstalledDirectory(bin);
  333. await setEnabled("qpdf", false);
  334. await waitEntrySync("qpdf", true);
  335. } finally {
  336. await unlockPreinstalledDirectory(bin);
  337. }
  338. await deleteTool("qpdf");
  339. await waitStatus("qpdf", "not-installed");
  340. await $(`${card("qpdf")} [data-testid="preinstalled-tools-download"]`).click();
  341. await waitStatus("qpdf", "ready");
  342. await waitEntrySync("qpdf", false);
  343. expect(await toggle("qpdf").getAttribute("aria-checked")).toBe("false");
  344. await expect(stat(preinstalledEntryPath(bin, "qpdf"))).rejects.toHaveProperty("code", "ENOENT");
  345. expect(JSON.parse(await readFile(settingsPath, "utf8")).preinstalledToolsAgentDisabled).toEqual(
  346. ["qpdf"],
  347. );
  348. expect(await requests()).toBe(requestsAfterPublication + 1);
  349. await setEnabled("libreoffice", false);
  350. await browser.keys("Escape");
  351. await reloadElectronSessionPreservingBrowserProfile(browser);
  352. await prepareV4ConversationE2E();
  353. await openDialog();
  354. for (const toolId of ["qpdf", "libreoffice"]) {
  355. await waitStatus(toolId, "ready");
  356. expect(await toggle(toolId).getAttribute("aria-checked")).toBe("false");
  357. }
  358. await expect(stat(preinstalledEntryPath(bin, "qpdf"))).rejects.toHaveProperty("code", "ENOENT");
  359. await expect(stat(preinstalledEntryPath(bin, "zcode-soffice"))).rejects.toHaveProperty(
  360. "code",
  361. "ENOENT",
  362. );
  363. await $(`${card("libreoffice")} [data-testid="preinstalled-tools-delete"]`).click();
  364. await $('[data-testid="preinstalled-tools-delete-confirm-accept"]').click();
  365. await waitStatus("libreoffice", "not-installed");
  366. expect(await toggle("libreoffice").getAttribute("aria-checked")).toBe("false");
  367. await expect(stat(officeRecord)).rejects.toHaveProperty("code", "ENOENT");
  368. expect(await stat(qpdfRecord)).toBeDefined();
  369. const settings = JSON.parse(await readFile(join(settingsDirectory, "setting.json"), "utf8"));
  370. expect(settings.preinstalledToolsAgentDisabled.sort()).toEqual(["libreoffice", "qpdf"]);
  371. await writeFile(
  372. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "agent-switch-evidence.json"),
  373. JSON.stringify(
  374. {
  375. observations,
  376. failedSnapshot: failedSnapshot!,
  377. entryRetryPreservedSettingsAndRequests: true,
  378. failedDeletePreservedRecordAndDirectory: true,
  379. failedPublicationPreservedRecordAndDirectory: true,
  380. disabledPublicationKeptEntriesAbsent: true,
  381. persistedDisabled: settings.preinstalledToolsAgentDisabled,
  382. deletionKeepsPreference: true,
  383. },
  384. null,
  385. 2,
  386. ),
  387. );
  388. });
  389. });