e2e.mjs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. import assert from "node:assert/strict";
  2. import { createServer } from "node:http";
  3. import {
  4. appendFile,
  5. copyFile,
  6. cp,
  7. mkdir,
  8. mkdtemp,
  9. readFile,
  10. rm,
  11. writeFile,
  12. } from "node:fs/promises";
  13. import { tmpdir } from "node:os";
  14. import { dirname, join, resolve } from "node:path";
  15. import { fileURLToPath } from "node:url";
  16. import { build } from "esbuild";
  17. import { chromium } from "playwright-core";
  18. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  19. import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
  20. import { readPluginName } from "./plugin-name.mjs";
  21. /**
  22. * Real bundled server + official AppBridge host + the panel in an iframe that carries the ZCode
  23. * sandbox CSP (no network, wasm only by declaration). The script plays the agent: it calls the
  24. * server's model tools, forwards results to the page and calls the page's capture_view tool.
  25. * This does not exercise the Electron sandbox itself.
  26. *
  27. * Run it from a built plugin package; the steps follow the plugin's formats.
  28. */
  29. const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  30. const plugin = process.cwd();
  31. const name = await readPluginName(plugin);
  32. const { kinds } = JSON.parse(await readFile(join(plugin, "package.json"), "utf8")).office;
  33. const has = (kind) => kinds.includes(kind);
  34. const artifacts = resolve(process.env.OFFICE_E2E_ARTIFACTS || join(tmpdir(), `${name}-e2e`));
  35. await mkdir(artifacts, { recursive: true });
  36. const workspace = await mkdtemp(join(tmpdir(), `${name}-e2e-ws-`));
  37. await cp(join(root, "fixtures"), join(workspace, "docs"), {
  38. recursive: true,
  39. filter: (path) => !path.endsWith(".py"),
  40. });
  41. const client = new Client({ name: `${name}-e2e`, version: "1" });
  42. await client.connect(
  43. new StdioClientTransport({
  44. command: process.execPath,
  45. args: [join(plugin, "dist/server.mjs")],
  46. cwd: workspace,
  47. env: { PATH: process.env.PATH ?? "", ZCODE_WORKSPACE_ROOT: workspace },
  48. stderr: "inherit",
  49. }),
  50. );
  51. const panel = await client.readResource({ uri: `ui://${name}/panel.html` });
  52. const html = panel.contents[0].text;
  53. const relaxed = panel.contents[0]._meta?.["zcode/csp"]?.wasmUnsafeEval === true;
  54. // Same directives as the desktop sandbox (packages/desktop/src/main/pluginSandbox/csp.ts).
  55. const csp = [
  56. "default-src 'none'",
  57. `script-src 'self' 'unsafe-inline' blob: data:${relaxed ? " 'wasm-unsafe-eval'" : ""}`,
  58. "style-src 'self' 'unsafe-inline'",
  59. "img-src 'self' data: blob:",
  60. "media-src 'self' data: blob:",
  61. "font-src 'self' data:",
  62. "connect-src 'none'",
  63. "frame-src 'none'",
  64. "base-uri 'self'",
  65. "worker-src 'self' blob:",
  66. "object-src 'none'",
  67. "form-action 'none'",
  68. ].join("; ");
  69. const hostJs = await build({
  70. stdin: {
  71. contents: `
  72. import { AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge";
  73. const rpc = async (method, args) => {
  74. const response = await fetch('/rpc', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({method,args})});
  75. const result = await response.json(); if (!response.ok) throw Error(result.error); return result;
  76. };
  77. const params = new URLSearchParams(location.search);
  78. const context = { theme: params.get('theme') || 'light', locale: params.get('locale') || 'en-US', displayMode: params.get('mode') || 'fullscreen' };
  79. const bridge = new AppBridge(null, {name:'office-e2e',version:'1'}, {serverTools:{},serverResources:{},message:{text:{}},updateModelContext:{text:{}},openLinks:{},experimental:{"zcode/surface":{id:"panel",stateKey:params.get("tab")||"first"}}}, {hostContext:context});
  80. window.__messages = []; window.__context = null; window.__links = []; window.__initializations = 0;
  81. bridge.oncalltool = (args) => rpc('callTool', args);
  82. bridge.onreadresource = (args) => rpc('readResource', args);
  83. bridge.onmessage = async (p) => { window.__messages.push(p.content[0].text); return {}; };
  84. bridge.onupdatemodelcontext = async (p) => { window.__context = p; return {}; };
  85. bridge.onopenlink = async (p) => { window.__links.push(p.url); return {}; };
  86. bridge.onsizechange = () => {};
  87. bridge.oninitialized = () => { window.__initializations++; };
  88. window.__sendToolResult = (result) => bridge.sendToolResult(result);
  89. window.__callPageTool = (name, args) => bridge.callTool({ name, arguments: args });
  90. window.__listPageTools = () => bridge.listTools({});
  91. const frame = document.querySelector('iframe');
  92. await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow));
  93. frame.src = '/panel';
  94. `,
  95. resolveDir: root,
  96. sourcefile: "browser-host.mjs",
  97. },
  98. bundle: true,
  99. format: "esm",
  100. platform: "browser",
  101. write: false,
  102. });
  103. const server = createServer(async (request, response) => {
  104. try {
  105. const url = new URL(request.url, "http://localhost");
  106. if (url.pathname === "/") {
  107. response.setHeader("Content-Type", "text/html; charset=utf-8");
  108. response.end(
  109. '<style>html,body{margin:0;width:100%;height:100%}iframe{border:0;width:100%;height:100%}</style><iframe sandbox="allow-scripts allow-same-origin allow-forms"></iframe><script type="module" src="/host.js"></script>',
  110. );
  111. } else if (url.pathname === "/host.js") {
  112. response.setHeader("Content-Type", "text/javascript");
  113. response.end(hostJs.outputFiles[0].text);
  114. } else if (url.pathname === "/panel") {
  115. response.setHeader("Content-Type", "text/html; charset=utf-8");
  116. response.setHeader("Content-Security-Policy", csp);
  117. response.end(html);
  118. } else if (request.method === "POST" && url.pathname === "/rpc") {
  119. let body = "";
  120. for await (const chunk of request) body += chunk;
  121. const { method, args } = JSON.parse(body);
  122. const result =
  123. method === "readResource" ? await client.readResource(args) : await client.callTool(args);
  124. response.setHeader("Content-Type", "application/json");
  125. response.end(JSON.stringify(result));
  126. } else if (url.pathname === "/favicon.ico") response.writeHead(204).end();
  127. else response.writeHead(404).end();
  128. } catch (error) {
  129. response
  130. .writeHead(500, { "Content-Type": "application/json" })
  131. .end(JSON.stringify({ error: String(error) }));
  132. }
  133. });
  134. await new Promise((done) => server.listen(0, "127.0.0.1", done));
  135. const base = `http://127.0.0.1:${server.address().port}`;
  136. const browser = await chromium.launch(
  137. process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: "chrome" },
  138. );
  139. const errors = [];
  140. let opened = 0;
  141. const open = async (
  142. query = "",
  143. viewport = { width: Number(process.env.OFFICE_E2E_WIDTH || 900), height: 900 },
  144. init = null,
  145. ) => {
  146. const outer = await browser.newPage({ viewport });
  147. if (init) await outer.addInitScript(init);
  148. outer.on("pageerror", (error) => errors.push(`pageerror: ${error}`));
  149. outer.on("console", (message) => {
  150. if (message.type() === "error" && !/favicon/.test(message.text()))
  151. errors.push(`console: ${message.text()}`);
  152. });
  153. const target = new URL(`${base}/${query}`);
  154. if (!target.searchParams.has("tab"))
  155. target.searchParams.set("tab", opened++ === 0 ? "first" : `window-${opened}`);
  156. await outer.goto(target.href);
  157. await outer.waitForFunction(() => window.__initializations === 1);
  158. const frame = outer.frames().find((item) => item !== outer.mainFrame());
  159. assert.ok(frame, "panel iframe exists");
  160. await frame.locator(".app").waitFor();
  161. return { outer, frame };
  162. };
  163. /** Play the agent: call a model tool on the server and push the result to the page like the host does. */
  164. const agent = async (outer, name, args) => {
  165. const result = await client.callTool({ name, arguments: args });
  166. assert.ok(!result.isError, JSON.stringify(result.content));
  167. await outer.evaluate((value) => window.__sendToolResult(value), result);
  168. return result;
  169. };
  170. const capture = async (outer, args, file) => {
  171. const result = await outer.evaluate(
  172. (value) => window.__callPageTool("capture_view", value),
  173. args,
  174. );
  175. assert.ok(!result.isError, JSON.stringify(result.content));
  176. const image = result.content.find((item) => item.type === "image");
  177. assert.equal(image.mimeType, "image/png");
  178. const bytes = Buffer.from(image.data, "base64");
  179. assert.ok(bytes.length > 2000, `${file}: capture is not blank (${bytes.length} bytes)`);
  180. await writeFile(join(artifacts, file), bytes);
  181. return result.content.find((item) => item.type === "text").text;
  182. };
  183. const getView = async () =>
  184. (await client.callTool({ name: "get_view", arguments: { viewId: "first" } })).content[0].text;
  185. const waitForView = async (pattern) => {
  186. for (let i = 0; i < 40; i++) {
  187. const text = await getView();
  188. if (pattern.test(text)) return text;
  189. await new Promise((done) => setTimeout(done, 150));
  190. }
  191. throw new Error(`view never matched ${pattern}: ${await getView()}`);
  192. };
  193. try {
  194. const width = Number(process.env.OFFICE_E2E_WIDTH || 900);
  195. let { outer, frame } = await open();
  196. const shot = (name) => outer.screenshot({ path: join(artifacts, name) });
  197. let bar = frame.locator(".pop.bar");
  198. await frame.locator(".empty-open").waitFor();
  199. await shot("empty.png");
  200. const tools = await outer.evaluate(() => window.__listPageTools());
  201. assert.deepEqual(
  202. tools.tools.map((tool) => tool.name),
  203. ["capture_view"],
  204. );
  205. // 1. File browser → docx; click a paragraph; reference it in chat.
  206. if (has("docx")) {
  207. const chooser = outer.waitForEvent("filechooser");
  208. await frame.locator(".empty-open").click();
  209. await (await chooser).setFiles(join(root, "fixtures/report.docx"));
  210. await frame.locator('[data-at="p:4"]').first().waitFor({ timeout: 20000 });
  211. await outer.reload();
  212. await outer.waitForFunction(() => window.__initializations === 1);
  213. const restored = outer.frames().find((item) => item !== outer.mainFrame());
  214. await restored.locator('[data-at="p:4"]').first().waitFor({ timeout: 20000 });
  215. // 同一存储分区内的新窗口不能继承服务器的最后文档。
  216. await outer.goto(base + "/?tab=second");
  217. await outer.waitForFunction(() => window.__initializations === 1);
  218. const fresh = outer.frames().find((item) => item !== outer.mainFrame());
  219. await fresh.locator(".empty-open").waitFor();
  220. await outer.goto(base);
  221. await outer.waitForFunction(() => window.__initializations === 1);
  222. frame = outer.frames().find((item) => item !== outer.mainFrame());
  223. bar = frame.locator(".pop.bar");
  224. await frame.locator('[data-at="p:4"]').first().waitFor({ timeout: 20000 });
  225. await agent(outer, "open_document", { path: "docs/report.docx" });
  226. await frame.locator('[data-at="p:4"]').first().waitFor({ timeout: 20000 });
  227. await frame.locator('[data-at="t:1"]').first().waitFor();
  228. await frame.locator(".pill").waitFor();
  229. await frame.locator('[data-at="p:4"]').first().click();
  230. await bar.locator(".where", { hasText: "Paragraph 4" }).waitFor();
  231. await bar.getByRole("button", { name: "Add to chat" }).click();
  232. await outer.waitForFunction(() => window.__context !== null);
  233. const context = await outer.evaluate(() => window.__context);
  234. assert.match(context.content[0].text, /docs\/report\.docx#p:4: "Revenue grew by 12 percent/);
  235. await bar.getByText("Added to chat").waitFor();
  236. await bar.waitFor({ state: "detached", timeout: 4000 });
  237. await waitForView(/User selection: docs\/report\.docx#p:4/);
  238. // A table cell click addresses the cell.
  239. await frame.locator('[data-at="t:1"] td', { hasText: "South" }).click();
  240. await bar.locator(".where", { hasText: "Table 1 · R3C1" }).waitFor();
  241. // Ask: the bar grows into a question box and posts a user message with the anchor.
  242. await bar.getByRole("button", { name: "Ask" }).click();
  243. await frame.getByPlaceholder("Ask about this…").fill("Is this region growing?");
  244. await shot("docx-ask.png");
  245. await frame.locator(".pop.ask").getByRole("button", { name: "Send" }).click();
  246. await outer.waitForFunction(() => window.__messages.length === 1);
  247. assert.match(
  248. await outer.evaluate(() => window.__messages[0]),
  249. /Is this region growing\?[\s\S]*docs\/report\.docx#t:1\/r3c1/,
  250. );
  251. await frame.locator(".pop").waitFor({ state: "detached" });
  252. // Agent points at a paragraph with a quote: amber mark and a note beside it.
  253. await agent(outer, "show_in_viewer", {
  254. targets: [{ anchor: "docs/report.docx#p:6", quote: "steady growth" }],
  255. note: "Outlook",
  256. });
  257. await frame.locator(".callout", { hasText: "Outlook" }).waitFor();
  258. await shot("docx-panel.png");
  259. assert.match(
  260. await capture(outer, { anchor: "docs/report.docx#p:6" }, "docx.png"),
  261. /Captured docs\/report\.docx#p:6/,
  262. );
  263. }
  264. // 2. Agent opens the PDF at page 2; text layer, quote highlight, link routing, capture.
  265. if (has("pdf")) {
  266. await agent(outer, "open_document", { path: "docs/paper.pdf", at: "page:2" });
  267. await frame
  268. .locator('.pdf-page[data-at="page:1"] .textLayer span')
  269. .first()
  270. .waitFor({ timeout: 20000 });
  271. await frame.locator(".textLayer span", { hasText: "缓存显著降低延迟" }).waitFor();
  272. await waitForView(/Visible location: docs\/paper\.pdf#page:2/);
  273. await frame.locator(".pill .pgin").waitFor();
  274. // Several targets: the callout steps through them.
  275. await agent(outer, "show_in_viewer", {
  276. targets: [
  277. { anchor: "docs/paper.pdf#page:1", quote: "40 percent reduction" },
  278. { anchor: "docs/paper.pdf#page:2" },
  279. ],
  280. note: "Headline result",
  281. });
  282. await frame.locator(".callout", { hasText: "Agent · 1 of 2" }).waitFor();
  283. await shot("pdf-agent.png");
  284. await frame.locator(".callout").getByRole("button", { name: "Next" }).click();
  285. await frame.locator(".callout", { hasText: "Agent · 2 of 2" }).waitFor();
  286. await frame.locator(".callout").getByRole("button", { name: "Close" }).click();
  287. await frame.locator(".callout").waitFor({ state: "detached" });
  288. // Clicking a mark brings its note back (scroll back to it first: Next moved to page 2).
  289. await frame.evaluate(() => document.querySelector(".viewer-scroll").scrollTo({ top: 0 }));
  290. await new Promise((done) => setTimeout(done, 300));
  291. const mark = await frame.evaluate(() => {
  292. const range = [...CSS.highlights.get("office-reveal")][0];
  293. const rect = range.getClientRects()[0];
  294. return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
  295. });
  296. await frame.page().mouse.click(mark.x, mark.y);
  297. await frame.locator(".callout", { hasText: "Agent · 1 of 2" }).waitFor();
  298. assert.equal(await bar.count(), 0, "a click on a mark opens no selection bar");
  299. await frame.locator(".callout").getByRole("button", { name: "Close" }).click();
  300. await frame.locator(".pdf-link").first().click();
  301. await outer.waitForFunction(() => window.__links.length === 1);
  302. assert.equal(await outer.evaluate(() => window.__links[0]), "https://example.com/paper");
  303. const box = await frame.locator(".textLayer span", { hasText: "Abstract" }).boundingBox();
  304. await frame
  305. .locator('.pdf-page[data-at="page:1"]')
  306. .first()
  307. .evaluate(() => {
  308. const span = [...document.querySelectorAll(".textLayer span")].find((item) =>
  309. item.textContent.includes("Abstract"),
  310. );
  311. const range = document.createRange();
  312. range.selectNodeContents(span);
  313. getSelection().removeAllRanges();
  314. getSelection().addRange(range);
  315. });
  316. await frame
  317. .locator(".textLayer span", { hasText: "Abstract" })
  318. .dispatchEvent("mouseup", { clientX: box.x, clientY: box.y });
  319. await bar.getByRole("button", { name: "Copy" }).waitFor();
  320. await waitForView(/Selected text: """Abstract/);
  321. await shot("pdf-selection.png");
  322. await bar.getByRole("button", { name: "Add to chat" }).click();
  323. await outer.waitForFunction(() => /paper\.pdf#page:1/.test(window.__context?.content[0].text));
  324. assert.match(
  325. await outer.evaluate(() => window.__context.content[0].text),
  326. /docs\/paper\.pdf#page:1: "Abstract/,
  327. );
  328. // Find: search as you type, count, step, Esc closes.
  329. await frame.getByRole("button", { name: "Find" }).click();
  330. await frame.getByLabel("Find", { exact: true }).fill("percent");
  331. await frame.locator(".findfield .count", { hasText: /^1 of \d+$/ }).waitFor();
  332. await frame.getByLabel("Find", { exact: true }).press("Enter");
  333. await frame.locator(".findfield .count", { hasText: /^2 of \d+$|^1 of 1$/ }).waitFor();
  334. await shot("pdf-find.png");
  335. await frame.getByLabel("Find", { exact: true }).press("Escape");
  336. await frame.locator(".findbar").waitFor({ state: "detached" });
  337. // Zoom from the page control and back through the More menu.
  338. await frame.locator(".pill").hover();
  339. await frame.getByRole("button", { name: "Zoom in (⌘+)" }).click();
  340. await frame.locator(".pill .zoom", { hasText: "%" }).waitFor();
  341. await frame.getByRole("button", { name: "More" }).click();
  342. await frame.getByRole("menuitemradio", { name: "Fit width" }).click();
  343. await frame.locator(".pill .zoom", { hasText: "Fit" }).waitFor();
  344. // Pages drawer: thumbnails; picking one goes there.
  345. await frame.getByRole("button", { name: "Pages and outline" }).click();
  346. await frame.locator(".drawer .thumb canvas").first().waitFor({ timeout: 10000 });
  347. await shot("pdf-drawer.png");
  348. await frame.locator('.drawer .thumb[data-page="2"]').click();
  349. await waitForView(/Visible location: docs\/paper\.pdf#page:2/);
  350. if (width < 720) await frame.locator(".drawer").waitFor({ state: "detached" });
  351. else await frame.getByRole("button", { name: "Pages and outline" }).click();
  352. assert.match(await capture(outer, { anchor: "docs/paper.pdf#page:1" }, "pdf.png"), /page:1/);
  353. assert.equal(
  354. await frame.evaluate(() =>
  355. Math.round(document.querySelector(".docbar").getBoundingClientRect().top),
  356. ),
  357. 0,
  358. "the document bar stays at the top of the panel",
  359. );
  360. await shot("pdf-panel.png");
  361. }
  362. // 2b. CJK with non-embedded fonts: the panel registers same-style system CJK faces, radicals in
  363. // ToUnicode read as ideographs, and with no CJK font installed the bundled fallback draws them.
  364. if (has("pdf")) {
  365. await agent(outer, "open_document", { path: "docs/cjk.pdf" });
  366. await frame.locator(".textLayer span", { hasText: "天地玄黄" }).waitFor({ timeout: 20000 });
  367. assert.ok(
  368. await frame.evaluate(() =>
  369. [...document.fonts].some(
  370. (face) => face.family.startsWith("zcode-cjk-") && face.status === "loaded",
  371. ),
  372. ),
  373. "CJK faces are registered before the page is drawn",
  374. );
  375. await agent(outer, "show_in_viewer", {
  376. targets: [{ anchor: "docs/cjk.pdf#page:1", quote: "天地玄黄" }],
  377. note: "Radicals read as ideographs",
  378. });
  379. await frame.locator(".callout", { hasText: "Radicals read as ideographs" }).waitFor();
  380. await shot("pdf-cjk.png");
  381. await frame.locator(".callout").getByRole("button", { name: "Close" }).click();
  382. await frame.getByRole("button", { name: "Find" }).click();
  383. await frame.getByLabel("Find", { exact: true }).fill("文");
  384. await frame.locator(".findfield .count", { hasText: /^1 of 4$/ }).waitFor();
  385. await frame.getByLabel("Find", { exact: true }).press("Escape");
  386. await frame.locator(".findbar").waitFor({ state: "detached" });
  387. // No CJK font on the machine: every local() lookup fails, as on a minimal Linux.
  388. const bare = await open("", undefined, () => {
  389. const NativeFontFace = window.FontFace;
  390. window.FontFace = class extends NativeFontFace {
  391. constructor(family, source, descriptors) {
  392. const local = typeof source === "string" && source.includes("local(");
  393. super(family, local ? 'local("zcode-e2e-missing")' : source, descriptors);
  394. }
  395. };
  396. });
  397. await agent(bare.outer, "open_document", { path: "docs/cjk.pdf" });
  398. await bare.frame.waitForFunction(
  399. () =>
  400. [...document.fonts].filter(
  401. (face) => face.family === "zcode-cjk-fallback" && face.status === "loaded",
  402. ).length >= 50,
  403. null,
  404. { timeout: 30000 },
  405. );
  406. assert.equal(
  407. await bare.frame.evaluate(() =>
  408. [...document.fonts].some((face) => /^zcode-cjk-(sc|tc|jp|kr)-/.test(face.family)),
  409. ),
  410. false,
  411. "faces without an installed font are not registered",
  412. );
  413. await bare.frame.locator('.pdf-page[data-at="page:1"] canvas').waitFor({ timeout: 20000 });
  414. await bare.outer.screenshot({ path: join(artifacts, "pdf-cjk-fallback.png") });
  415. await bare.outer.close();
  416. }
  417. // 3. Presentation: slide rendering, shape hit testing, reveal of a shape, capture.
  418. if (has("pptx")) {
  419. await agent(outer, "open_document", { path: "docs/launch.pptx" });
  420. await frame
  421. .locator('.slide-frame[data-at="slide:2"] .slide-host > :not(.slide-overlay)')
  422. .first()
  423. .waitFor({ timeout: 20000 });
  424. const hit = (
  425. await client.callTool({
  426. name: "search_document",
  427. arguments: { path: "docs/launch.pptx", query: "Owner" },
  428. })
  429. ).structuredContent.hits[0].anchor;
  430. await agent(outer, "show_in_viewer", { targets: [{ anchor: hit }] });
  431. await frame.locator(".shape-revealed").waitFor();
  432. await new Promise((done) => setTimeout(done, 1000)); // let the smooth scroll settle
  433. const owner = await frame.locator(".shape-revealed").boundingBox();
  434. await frame.page().mouse.click(owner.x + owner.width / 2, owner.y + owner.height / 2);
  435. await bar.locator(".where", { hasText: "Slide 2 · Shape" }).waitFor();
  436. const selected = await waitForView(/User selection: docs\/launch\.pptx#slide:2\/shape:\d+/);
  437. assert.ok(selected.includes(`User selection: ${hit}`), selected);
  438. assert.match(selected, /Owner: Dana/);
  439. assert.match(
  440. await capture(outer, { anchor: "docs/launch.pptx#slide:3" }, "pptx.png"),
  441. /slide:3/,
  442. );
  443. await shot("pptx-panel.png");
  444. }
  445. // 4. Spreadsheet (wasm under CSP): reveal a range, select cells, capture.
  446. if (has("xlsx")) {
  447. await agent(outer, "show_in_viewer", {
  448. targets: [{ anchor: "docs/budget.xlsx#Revenue!B2:D4" }],
  449. });
  450. await waitForView(/Visible location: docs\/budget\.xlsx#Revenue/);
  451. await waitForView(/User selection: docs\/budget\.xlsx#Revenue!B2:D4/);
  452. const view = await getView();
  453. assert.match(view, /100\t110\t120/);
  454. await agent(outer, "show_in_viewer", { targets: [{ anchor: "docs/budget.xlsx#Notes!B2" }] });
  455. await frame.locator(".sheet-tabs button.active", { hasText: "Notes" }).waitFor();
  456. assert.match(await capture(outer, {}, "xlsx.png"), /Captured docs\/budget\.xlsx#Notes/);
  457. // The grid is a canvas: press inside it and the bar names the cell that got selected.
  458. const grid = await frame.locator(".xlsx-grid").boundingBox();
  459. await frame.page().mouse.click(grid.x + grid.width * 0.4, grid.y + grid.height * 0.25);
  460. await bar.locator(".where", { hasText: /^Notes · [A-Z]+\d+$/ }).waitFor();
  461. await shot("xlsx-panel.png");
  462. }
  463. // capture_view refuses a document that is not open.
  464. const refused = await outer.evaluate(
  465. (anchor) => window.__callPageTool("capture_view", { anchor }),
  466. {
  467. docx: "docs/other.docx#p:1",
  468. xlsx: "docs/other.xlsx#Sheet1!A1",
  469. pptx: "docs/other.pptx#slide:1",
  470. pdf: "docs/other.pdf#page:1",
  471. }[kinds[0]],
  472. );
  473. assert.ok(refused.isError && /open_document/.test(refused.content[0].text));
  474. // 两个窗口上报后,模型必须先选择窗口,不能收到最后上报者的选区。
  475. await client.callTool({
  476. name: "report_view",
  477. arguments: {
  478. viewId: "other-window",
  479. path: {
  480. docx: "docs/report.docx",
  481. pdf: "docs/paper.pdf",
  482. xlsx: "docs/budget.xlsx",
  483. pptx: "docs/launch.pptx",
  484. }[kinds[0]],
  485. at: null,
  486. },
  487. });
  488. const ambiguous = await client.callTool({ name: "get_view", arguments: {} });
  489. assert.equal(ambiguous.structuredContent.ambiguous, true);
  490. assert.ok(ambiguous.structuredContent.views.some((view) => view.viewId === "other-window"));
  491. await client.callTool({ name: "release_view", arguments: { viewId: "other-window" } });
  492. // 5. The file changes on disk: a notice offers to reload.
  493. if (has("pdf")) {
  494. await copyFile(join(workspace, "docs/paper.pdf"), join(workspace, "docs/draft.pdf"));
  495. await agent(outer, "open_document", { path: "docs/draft.pdf" });
  496. // Wait for the panel to report the new file: the previous PDF's canvas matches too, and
  497. // editing the file before the panel loads it would leave nothing to notice.
  498. await waitForView(/Visible location: docs\/draft\.pdf/);
  499. await frame.locator('.pdf-page[data-at="page:1"] canvas').waitFor({ timeout: 20000 });
  500. await appendFile(join(workspace, "docs/draft.pdf"), "\n% edited\n");
  501. await frame
  502. .locator(".banner", { hasText: "This file changed on disk." })
  503. .waitFor({ timeout: 10000 });
  504. await shot("changed.png");
  505. await frame.locator(".banner").getByRole("button", { name: "Reload" }).click();
  506. await frame.locator(".banner").waitFor({ state: "detached" });
  507. await frame.locator('.pdf-page[data-at="page:1"] canvas').waitFor({ timeout: 20000 });
  508. // 6. A damaged file shows a plain error with one way forward.
  509. await writeFile(join(workspace, "docs/broken.pdf"), "not a pdf");
  510. const brokenChooser = outer.waitForEvent("filechooser");
  511. await frame.getByRole("button", { name: /Switch document/ }).click();
  512. await frame.getByRole("menuitem", { name: "Open file" }).click();
  513. await (await brokenChooser).setFiles(join(workspace, "docs/broken.pdf"));
  514. await frame.locator(".failed h3").waitFor();
  515. await shot("error.png");
  516. const retryChooser = outer.waitForEvent("filechooser");
  517. await frame.getByRole("button", { name: "Open another file" }).click();
  518. await (await retryChooser).setFiles(join(workspace, "docs/paper.pdf"));
  519. await frame.locator(".pdf-page canvas").first().waitFor({ timeout: 20000 });
  520. }
  521. // 7. 新的深色中文窗口由 Agent 显式打开文档,不继承其他窗口。
  522. const inline = has("xlsx")
  523. ? ["docs/budget.xlsx", ".xlsx-root"]
  524. : has("pdf")
  525. ? ["docs/paper.pdf", ".pdf-page canvas"]
  526. : has("pptx")
  527. ? ["docs/launch.pptx", '.slide-frame[data-at="slide:1"] .slide-host > :not(.slide-overlay)']
  528. : ["docs/report.docx", '[data-at="p:1"]'];
  529. await agent(outer, "open_document", { path: inline[0] });
  530. const dark = await open("?theme=dark&locale=zh-CN&mode=inline", { width: 420, height: 380 });
  531. await agent(dark.outer, "open_document", { path: inline[0] });
  532. await dark.frame.locator(inline[1]).first().waitFor({ timeout: 20000 });
  533. assert.equal(await dark.frame.locator("html").getAttribute("data-theme"), "dark");
  534. await dark.frame.getByRole("button", { name: "在侧栏打开" }).first().waitFor();
  535. assert.ok(
  536. await dark.frame.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth),
  537. "no horizontal overflow at 420px",
  538. );
  539. await dark.outer.screenshot({ path: join(artifacts, "zh-dark-inline.png") });
  540. // 8. Dark side panel opened by the agent while ZCode animates the pane's width: the mark must
  541. // end up on the live text layer, not on one a resize replaced.
  542. const darkPanel = has("pdf") ? await open("?theme=dark", { width: 300, height: 760 }) : null;
  543. if (darkPanel) {
  544. await agent(darkPanel.outer, "show_in_viewer", {
  545. targets: [{ anchor: "docs/paper.pdf#page:1", quote: "40 percent reduction" }],
  546. note: "The headline result.",
  547. });
  548. for (let w = 300; w <= 460; w += 8) {
  549. await darkPanel.outer.setViewportSize({ width: w, height: 760 });
  550. await new Promise((done) => setTimeout(done, 16));
  551. }
  552. await darkPanel.outer.setViewportSize({ width: 440, height: 760 });
  553. await darkPanel.frame.locator(".callout", { hasText: "The headline result." }).waitFor({
  554. timeout: 20000,
  555. });
  556. await darkPanel.frame.waitForFunction(
  557. () => {
  558. const ranges = [...(CSS.highlights.get("office-reveal") ?? [])];
  559. return ranges.some((range) => {
  560. const rect = range.getBoundingClientRect();
  561. return (
  562. range.startContainer.isConnected &&
  563. range.startContainer.parentElement?.closest(".textLayer")?.isConnected &&
  564. rect.width > 0 &&
  565. rect.top >= 0 &&
  566. rect.bottom <= innerHeight
  567. );
  568. });
  569. },
  570. null,
  571. { timeout: 10000 },
  572. );
  573. await darkPanel.outer.screenshot({ path: join(artifacts, "pdf-dark.png") });
  574. }
  575. for (const page of [frame, dark.frame, darkPanel?.frame].filter(Boolean))
  576. assert.equal(
  577. await page.evaluate(() =>
  578. Math.round(document.querySelector(".docbar").getBoundingClientRect().top),
  579. ),
  580. 0,
  581. "the document bar stays at the top after all interactions",
  582. );
  583. assert.deepEqual(errors, []);
  584. process.stdout.write(`${name} e2e (${kinds.join(", ")}): ok (screenshots in ${artifacts})\n`);
  585. } catch (error) {
  586. // 先输出断言错误,避免连接清理等待掩盖实际失败位置。
  587. process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`);
  588. for (const page of browser.contexts().flatMap((context) => context.pages()))
  589. await page
  590. .screenshot({ path: join(artifacts, `failure-${Date.now()}.png`) })
  591. .catch(() => undefined);
  592. process.stderr.write(`Browser errors:\n${errors.join("\n")}\nScreenshots in ${artifacts}\n`);
  593. throw error;
  594. } finally {
  595. await browser.close();
  596. server.closeAllConnections();
  597. await new Promise((done) => server.close(done));
  598. await client.close();
  599. await rm(workspace, { recursive: true, force: true });
  600. }