conversation-session-preinstalled-tools-real-loopback.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import { cp, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
  2. import { execFile } from "node:child_process";
  3. import { createHash } from "node:crypto";
  4. import { dirname, join } from "node:path";
  5. import { promisify } from "node:util";
  6. import type {
  7. PreinstalledToolResource,
  8. PreinstalledToolsState,
  9. } from "@zcode/shared/preinstalled-tools";
  10. import {
  11. countUpstreamRequests,
  12. getLatestUpstreamToolResultByToolCallId,
  13. } from "#e2e/helpers/conversation-session-network";
  14. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  15. import { resolveE2ERuntimePath, resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  16. import { preinstalledEntryPath } from "#e2e/helpers/preinstalled-tools-fixture";
  17. import {
  18. getV4PaneSnapshot,
  19. prepareV4ConversationE2E,
  20. sendV4Prompt,
  21. switchV4Mode,
  22. waitForV4AssistantMessageContaining,
  23. waitForV4ConversationState,
  24. } from "#e2e/helpers/v4-conversation";
  25. const CASE = "conversation-session-preinstalled-tools-real-loopback";
  26. const tools = ["python", "qpdf", "pandoc", "poppler", "libreoffice"];
  27. const card = (id: string) => `[data-tool-id="${id}"]`;
  28. const fixture = () => process.env.ZCODE_E2E_PREINSTALL_FIXTURE_URL!;
  29. const state = () =>
  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(`${fixture()}/status`)).json() as Promise<{
  39. requests: number;
  40. completed: number;
  41. maxActive: number;
  42. events: Array<{ event: string; toolId: string; resourceId: string }>;
  43. tools: Record<string, { requests: number }>;
  44. }>;
  45. async function openDialog() {
  46. await $('[data-testid="workspace-help-menu-trigger"]').click();
  47. await $('[data-testid="workspace-help-menu-preinstalled-tools"]').click();
  48. await $('[data-testid="preinstalled-tools-dialog"]').waitForDisplayed();
  49. }
  50. async function waitStatus(id: string, expected: string) {
  51. let failure: string | undefined;
  52. await browser.waitUntil(
  53. async () => {
  54. // 轮询只传回该工具的简短状态,避免五工具完整快照反复写日志影响真实资源验收。
  55. const current = await browser.execute(async (toolId: string) => {
  56. const snapshot = await (
  57. window as typeof window & {
  58. zcode: { getPreinstalledToolsState(): Promise<PreinstalledToolsState> };
  59. }
  60. ).zcode.getPreinstalledToolsState();
  61. const tool = snapshot.tools.find((item) => item.toolId === toolId)!;
  62. return { status: tool.status, phase: tool.phase, errorKind: tool.error };
  63. }, id);
  64. if (current.status === "failed") {
  65. failure = JSON.stringify(current);
  66. return true;
  67. }
  68. return current.status === expected;
  69. },
  70. // 单个工具从下载到 ready 的上限。Windows Defender 会逐个扫描解包写出的文件,真实 Python 资源
  71. // 在 Windows 上解包约 2.4~2.7 分钟,原 180 秒没有余量,曾因此超时;放宽到 300 秒。
  72. { timeout: 300000, interval: 500, timeoutMsg: `${id} 未到达 ${expected}` },
  73. );
  74. // waitUntil 会吞下条件异常继续轮询;失败状态必须在条件之外立即报告。
  75. if (failure) throw new Error(`${id} preparation failed: ${failure}`);
  76. }
  77. async function absent(path: string) {
  78. await expect(stat(path)).rejects.toHaveProperty("code", "ENOENT");
  79. }
  80. /**
  81. * Windows 上 Agent 的 Bash 是 Git Bash;裸 bash 可能是 WSL,按 git.exe 位置定位同一安装。
  82. * 修复原因:探针要观察 Agent 会话实际的命令解析顺序。Git 的 bin\bash.exe 是包装器,会把
  83. * /ucrt64/bin、/usr/bin 重新放到 PATH 最前,Git 自带的 pdftotext 因此抢先于预装入口;
  84. * 用 usr\bin\bash.exe 不改写 PATH,沿用 Agent 会话里已把 <bin> 放在最前的顺序。
  85. */
  86. async function resolveAgentBash(): Promise<string> {
  87. if (process.platform !== "win32") return "/bin/bash";
  88. const { stdout } = await promisify(execFile)("where.exe", ["git"], { windowsHide: true });
  89. const git = stdout.split(/\r?\n/).find((line) => line.toLowerCase().endsWith("\\cmd\\git.exe"));
  90. if (!git) throw new Error("没有找到 Git for Windows");
  91. const candidate = join(dirname(dirname(git)), "usr", "bin", "bash.exe");
  92. await stat(candidate);
  93. return candidate;
  94. }
  95. describe("五个真实预装工具 loopback(待审核)", () => {
  96. after(async () => {
  97. try {
  98. await cp(
  99. resolveE2ERuntimePath(CASE),
  100. `${process.env.ZCODE_E2E_ARTIFACT_DIR}/real-document-results`,
  101. { recursive: true },
  102. );
  103. } catch (error) {
  104. if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
  105. }
  106. });
  107. it("PT-01/13/14/17/18:原会话、四插件、开关、升级、删除与文档结果", async function () {
  108. // 与 WDIO 外层预算一致:Windows 实测 14 分 11 秒,原 15 分钟余量不足 1 分钟。
  109. this.timeout(1500000);
  110. // 平台与 resourceId 以真实 .artifact.json 为准,不按开发机写死。
  111. const artifactPaths = JSON.parse(
  112. await readFile(process.env.ZCODE_E2E_PREINSTALL_ARTIFACTS!, "utf8"),
  113. ) as string[];
  114. const readResource = async (path: string) =>
  115. (JSON.parse(await readFile(path, "utf8")) as { resource: PreinstalledToolResource }).resource;
  116. const resources = await Promise.all(artifactPaths.map(readResource));
  117. const upgradeResource = await readResource(process.env.ZCODE_E2E_PREINSTALL_UPGRADE_ARTIFACT!);
  118. for (const resource of [...resources, upgradeResource])
  119. if (
  120. !resource.platforms.some(
  121. (item) => item.platform === process.platform && item.arch === process.arch,
  122. )
  123. )
  124. throw new Error(`${resource.resourceId} 不适用于 ${process.platform}-${process.arch}`);
  125. const qpdfResourceIds = {
  126. before: resources.find((resource) => resource.toolId === "qpdf")!.resourceId,
  127. after: upgradeResource.resourceId,
  128. };
  129. const python = process.env.ZCODE_E2E_DOCUMENT_PYTHON;
  130. const samples = process.env.ZCODE_E2E_DOCUMENT_SAMPLES;
  131. const systemApplication = process.env.ZCODE_E2E_LIBREOFFICE_SYSTEM_APP;
  132. const defaultProfile = process.env.ZCODE_E2E_LIBREOFFICE_DEFAULT_PROFILE;
  133. if (!python || !samples || !systemApplication || !defaultProfile)
  134. throw new Error("必须提供准备用 Python、真实样例、系统 LibreOffice 和默认配置路径");
  135. const sourcePackageVersion = JSON.parse(
  136. await readFile(new URL("../../../../../../../package.json", import.meta.url), "utf8"),
  137. ).version as string;
  138. await prepareV4ConversationE2E();
  139. await switchV4Mode("yolo");
  140. const directory = resolveE2ERuntimePath(CASE);
  141. const root = join(resolveE2EStorageRoot(), "preinstalled-tools", "development");
  142. await mkdir(directory, { recursive: true });
  143. await cp(
  144. new URL(`../../../fixtures/fs/conversation-session/${CASE}/`, import.meta.url),
  145. directory,
  146. { recursive: true },
  147. );
  148. await mkdir(join(directory, "中文 空格"), { recursive: true });
  149. for (const name of ["中文 字体验收.docx", "中文 字体验收.pptx", "legacy/中文 字体验收.doc"]) {
  150. await mkdir(join(directory, "中文 空格", name, ".."), { recursive: true });
  151. await cp(join(samples, name), join(directory, "中文 空格", name));
  152. }
  153. const helper = new URL(
  154. "../../../../../../../apps/zcode-cli/packages/documents-plugin/scripts/zcode_libreoffice.py",
  155. import.meta.url,
  156. );
  157. await writeFile(
  158. join(directory, "config.json"),
  159. JSON.stringify({
  160. python,
  161. systemApplication,
  162. defaultProfile,
  163. storageRoot: resolveE2EStorageRoot(),
  164. root,
  165. bash: await resolveAgentBash(),
  166. qpdfResourceIds,
  167. helperSha256: createHash("sha256")
  168. .update(await readFile(helper))
  169. .digest("hex"),
  170. }),
  171. );
  172. let sessionId: string | null = null;
  173. const observations: Record<string, unknown> = {};
  174. const observe = async (phase: string, timeout = 240000) => {
  175. const marker = `E2E_PT_REAL_${phase.toUpperCase().replaceAll("-", "_")}`;
  176. await sendV4Prompt(`${marker}: Run the exact real preinstalled tools acceptance phase.`);
  177. await waitForV4AssistantMessageContaining(`${marker}_DONE`, timeout);
  178. await waitForV4ConversationState((value) => value.state === "idle", `${phase} 未结束`);
  179. const result = await getLatestUpstreamToolResultByToolCallId(
  180. `toolu_pt_real_${phase.replaceAll("-", "_")}`,
  181. );
  182. expect(result?.isError).toBe(false);
  183. const current = (await getV4PaneSnapshot()).sessionId;
  184. expect(current).not.toBeNull();
  185. if (sessionId) expect(current).toBe(sessionId);
  186. sessionId = current;
  187. const receipt = JSON.parse(await readFile(join(directory, `${phase}.json`), "utf8"));
  188. observations[phase] = receipt;
  189. return receipt;
  190. };
  191. await waitStatus("python", "preparing");
  192. expect((await state()).tools.find((tool) => tool.toolId === "python")?.phase).toBe(
  193. "downloading",
  194. );
  195. const before = await observe("before");
  196. expect(before.systemCheck.source).toBe("system");
  197. expect(before.snapshots.length).toBeGreaterThan(0);
  198. const requestsBefore = await countUpstreamRequests({
  199. includes: ["E2E_PT_REAL"],
  200. excludes: ["Generate a concise title"],
  201. });
  202. await fetch(`${fixture()}/release`);
  203. for (const tool of tools) await waitStatus(tool, "ready");
  204. expect(
  205. await countUpstreamRequests({
  206. includes: ["E2E_PT_REAL"],
  207. excludes: ["Generate a concise title"],
  208. }),
  209. ).toBe(requestsBefore);
  210. const downloads = await http();
  211. expect(
  212. downloads.events.filter((event) => event.event === "requested").map((event) => event.toolId),
  213. ).toEqual(tools);
  214. expect(downloads.maxActive).toBe(1);
  215. expect(downloads.completed).toBe(5);
  216. await openDialog();
  217. // 与 tracer 相同的原因:Windows 上并发读取元素属性会遇到 chromedriver 拒绝新连接,改为一次 execute。
  218. expect(
  219. await browser.execute(() =>
  220. Array.from(document.querySelectorAll("[data-tool-id]"), (element) =>
  221. element.getAttribute("data-tool-id"),
  222. ),
  223. ),
  224. ).toEqual(tools);
  225. await browser.saveScreenshot(`${process.env.ZCODE_E2E_ARTIFACT_DIR}/five-tools-ready.png`);
  226. await $('[data-testid="preinstalled-tools-auto-install"]').click();
  227. await browser.waitUntil(async () => !(await state()).autoInstallEnabled);
  228. await browser.keys("Escape");
  229. const main = await observe("main", 360000);
  230. expect(main.plugins).toEqual(["documents", "pdf", "spreadsheets", "presentations"]);
  231. expect(main.formulas).toEqual({ C1: 5, D1: "#DIV/0!" });
  232. // Windows 上 pdf2image 解析到入口目录下带扩展名的入口;探针已按 PATH 实际结果核对目录。
  233. expect(main.pdf2imageEntry.toLowerCase()).toContain(
  234. join(root, "bin", "pdftoppm").toLowerCase(),
  235. );
  236. const records = Object.fromEntries(
  237. await Promise.all(
  238. tools.map(async (tool) => [
  239. tool,
  240. JSON.parse(await readFile(join(root, "tools", tool, "installation.json"), "utf8")),
  241. ]),
  242. ),
  243. );
  244. for (const tool of tools) {
  245. await openDialog();
  246. const toggle = $(`${card(tool)} [data-testid="preinstalled-tools-agent-enabled"]`);
  247. await toggle.scrollIntoView();
  248. await toggle.click();
  249. await browser.waitUntil(
  250. async () => !(await state()).tools.find((item) => item.toolId === tool)?.agentEnabled,
  251. );
  252. await browser.keys("Escape");
  253. await observe(`${tool}-off`);
  254. for (const id of tools)
  255. expect(
  256. JSON.parse(await readFile(join(root, "tools", id, "installation.json"), "utf8")),
  257. ).toEqual(records[id]);
  258. await openDialog();
  259. await $(`${card(tool)} [data-testid="preinstalled-tools-agent-enabled"]`).scrollIntoView();
  260. await $(`${card(tool)} [data-testid="preinstalled-tools-agent-enabled"]`).click();
  261. await browser.waitUntil(
  262. async () => !!(await state()).tools.find((item) => item.toolId === tool)?.agentEnabled,
  263. );
  264. await browser.keys("Escape");
  265. await observe(`${tool}-on`);
  266. }
  267. expect((await http()).requests).toBe(5);
  268. await observe("fallbacks", 180000);
  269. const finish = await observe("finish");
  270. expect(finish.pythonBaseUnchanged).toBe(true);
  271. expect(finish.defaultProfileUnchanged).toBe(true);
  272. expect(finish.signatures).toBe(
  273. process.platform === "darwin" ? "valid-before-and-after" : "not-applicable",
  274. );
  275. const originalSessionId = sessionId;
  276. await writeFile(
  277. join(directory, "initial-session-evidence.json"),
  278. JSON.stringify({ sessionId, observations, downloads: await http() }, null, 2),
  279. );
  280. // Main 在 worker 重启时复用初始 catalog;只有真正 App 重启才载入新版本清单。
  281. await fetch(`${fixture()}/upgrade`);
  282. const previousAppPid = await browser.electron.execute(() => process.pid);
  283. await reloadElectronSessionPreservingBrowserProfile(browser);
  284. await prepareV4ConversationE2E();
  285. await switchV4Mode("yolo");
  286. const upgradedAppPid = await browser.electron.execute(() => process.pid);
  287. expect(upgradedAppPid).not.toBe(previousAppPid);
  288. sessionId = null;
  289. await waitStatus("qpdf", "not-installed");
  290. expect((await http()).requests).toBe(5);
  291. await openDialog();
  292. await $(`${card("qpdf")} [data-testid="preinstalled-tools-update"]`).click();
  293. await waitStatus("qpdf", "preparing");
  294. await browser.keys("Escape");
  295. await observe("upgrade-before");
  296. await fetch(`${fixture()}/release/${qpdfResourceIds.after}`);
  297. await waitStatus("qpdf", "ready");
  298. await observe("upgrade-after");
  299. await expect(stat(records.qpdf.installationDir)).resolves.toBeDefined();
  300. for (const id of tools.filter((tool) => tool !== "qpdf")) {
  301. expect((await http()).tools[id]!.requests).toBe(1);
  302. expect(
  303. JSON.parse(await readFile(join(root, "tools", id, "installation.json"), "utf8")),
  304. ).toEqual(records[id]);
  305. }
  306. await writeFile(
  307. join(directory, "session-evidence.json"),
  308. JSON.stringify(
  309. {
  310. originalSessionId,
  311. upgradeSessionId: sessionId,
  312. appReload: { previousAppPid, upgradedAppPid },
  313. observations,
  314. downloads: await http(),
  315. requestsBefore,
  316. sourcePackageVersion,
  317. // default-App 的 getVersion 可能是 Electron 包版本,不能冒充本仓库产品版本。
  318. electronReportedAppVersion: await browser.electron.execute((electron) =>
  319. electron.app.getVersion(),
  320. ),
  321. electronVersion: await browser.electron.execute(() => process.versions.electron),
  322. platform: process.platform,
  323. arch: process.arch,
  324. },
  325. null,
  326. 2,
  327. ),
  328. );
  329. // 真正 App 启动才回收旧版本;先结束原会话验收,再通过退出屏障重启。
  330. await reloadElectronSessionPreservingBrowserProfile(browser);
  331. await prepareV4ConversationE2E();
  332. for (const tool of tools) await waitStatus(tool, "ready");
  333. await absent(records.qpdf.installationDir);
  334. await openDialog();
  335. const remainingRecords = Object.fromEntries(
  336. await Promise.all(
  337. tools.map(async (tool) => [
  338. tool,
  339. JSON.parse(await readFile(join(root, "tools", tool, "installation.json"), "utf8")),
  340. ]),
  341. ),
  342. );
  343. for (const tool of tools) {
  344. const recordPath = join(root, "tools", tool, "installation.json");
  345. const installed = JSON.parse(await readFile(recordPath, "utf8"));
  346. await $(`${card(tool)} [data-testid="preinstalled-tools-delete"]`).scrollIntoView();
  347. await $(`${card(tool)} [data-testid="preinstalled-tools-delete"]`).click();
  348. await $('[data-testid="preinstalled-tools-delete-confirm"]').waitForDisplayed();
  349. if (tool === "python")
  350. expect(await $('[data-testid="preinstalled-tools-delete-confirm"]').getText()).toContain(
  351. "Agent 额外安装的 Python 包也会删除",
  352. );
  353. await $('[data-testid="preinstalled-tools-delete-confirm-accept"]').click();
  354. await waitStatus(tool, "not-installed");
  355. await browser.waitUntil(
  356. async () => $(`${card(tool)} [data-testid="preinstalled-tools-download"]`).isEnabled(),
  357. { timeout: 30000 },
  358. );
  359. await absent(recordPath);
  360. await absent(installed.installationDir);
  361. expect(await readdir(join(root, "tools", tool, "versions"))).toEqual([]);
  362. expect((await state()).tools.find((item) => item.toolId === tool)?.agentEnabled).toBe(true);
  363. // Windows 入口是 <name>.exe 加 <name>.shim;只查无扩展名路径会让删除断言恒为真。
  364. for (const entry of installed.entries) {
  365. await absent(preinstalledEntryPath(join(root, "bin"), entry.name));
  366. if (process.platform === "win32") await absent(join(root, "bin", `${entry.name}.shim`));
  367. }
  368. delete remainingRecords[tool];
  369. for (const [other, expected] of Object.entries(remainingRecords)) {
  370. expect(
  371. JSON.parse(await readFile(join(root, "tools", other, "installation.json"), "utf8")),
  372. ).toEqual(expected);
  373. expect((await state()).tools.find((item) => item.toolId === other)?.status).toBe("ready");
  374. }
  375. }
  376. expect((await http()).requests).toBe(6);
  377. await browser.saveScreenshot(`${process.env.ZCODE_E2E_ARTIFACT_DIR}/five-tools-deleted.png`);
  378. await writeFile(
  379. join(directory, "deletion-evidence.json"),
  380. JSON.stringify(
  381. { tools, oldQpdfRemovedOnAppRestart: true, http: await http(), state: await state() },
  382. null,
  383. 2,
  384. ),
  385. );
  386. await cp(directory, `${process.env.ZCODE_E2E_ARTIFACT_DIR}/real-document-results`, {
  387. recursive: true,
  388. });
  389. });
  390. });