smoke.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import assert from "node:assert/strict";
  2. import { cp, mkdtemp, readFile, rm, symlink } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, join, resolve } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { Client } from "@modelcontextprotocol/sdk/client/index.js";
  7. import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
  8. import { readPluginName } from "./plugin-name.mjs";
  9. // Run from a built plugin package, or pass its directory. Checks follow the plugin's formats,
  10. // from its package.json.
  11. // 内置插件的包目录即安装目录,格式声明直接从插件根目录读取。
  12. const here = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  13. const root = resolve(process.argv[2] ?? process.cwd());
  14. const name = await readPluginName(root);
  15. const { kinds } = JSON.parse(await readFile(join(root, "package.json"), "utf8")).office;
  16. const has = (...wanted) => wanted.every((kind) => kinds.includes(kind));
  17. const ui = (path) => `ui://${name}/${path}`;
  18. const workspace = await mkdtemp(join(tmpdir(), `${name}-smoke-`));
  19. await cp(join(here, "fixtures"), join(workspace, "docs"), {
  20. recursive: true,
  21. filter: (path) => !path.endsWith(".py"),
  22. });
  23. await symlink("/etc/hosts", join(workspace, "docs/escape.pdf")).catch(() => undefined);
  24. const client = new Client({ name: `${name}-smoke`, version: "1" });
  25. const call = (name, args = {}) => client.callTool({ name, arguments: args });
  26. const ok = async (name, args) => {
  27. const result = await call(name, args);
  28. assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content)}`);
  29. return result;
  30. };
  31. const failCode = async (name, args) => {
  32. const result = await call(name, args);
  33. assert.ok(result.isError, `${name} should fail: ${JSON.stringify(result.content)}`);
  34. return result.structuredContent.error.code;
  35. };
  36. const text = (result) => result.content[0].text;
  37. try {
  38. await client.connect(
  39. new StdioClientTransport({
  40. command: process.execPath,
  41. args: [join(root, "dist/server.mjs")],
  42. cwd: workspace,
  43. env: { PATH: process.env.PATH ?? "", ZCODE_WORKSPACE_ROOT: workspace },
  44. stderr: "pipe",
  45. }),
  46. );
  47. const { tools } = await client.listTools();
  48. const meta = Object.fromEntries(tools.map((tool) => [tool.name, tool._meta?.ui]));
  49. assert.deepEqual(meta.open_document, {
  50. resourceUri: ui("panel.html"),
  51. surface: name,
  52. visibility: ["model", "app"],
  53. });
  54. assert.equal(meta.show_in_viewer.surface, name);
  55. assert.deepEqual(meta.show_in_viewer.visibility, ["model"]);
  56. for (const name of ["read_document", "search_document", "get_view"]) {
  57. assert.deepEqual(meta[name], { visibility: ["model"] }, `${name} renders no page`);
  58. }
  59. for (const name of [
  60. "list_documents",
  61. "load_document",
  62. "check_document",
  63. "get_viewer",
  64. "report_view",
  65. ])
  66. assert.deepEqual(meta[name].visibility, ["app"]);
  67. const open = tools.find((tool) => tool.name === "open_document");
  68. assert.equal(open._meta["openai/ui"].preferredModelDisplayMode, "fullscreen");
  69. // Descriptions name only the formats this plugin opens.
  70. for (const kind of ["docx", "xlsx", "pptx", "pdf"])
  71. assert.equal(
  72. open.description.includes(`.${kind}`),
  73. has(kind),
  74. `open_document mentions .${kind}`,
  75. );
  76. // Panel resource and assets.
  77. const panel = await client.readResource({ uri: ui("panel.html") });
  78. assert.equal(panel.contents[0].mimeType, "text/html;profile=mcp-app");
  79. assert.deepEqual(panel.contents[0]._meta, { "zcode/csp": { wasmUnsafeEval: true } });
  80. const html = panel.contents[0].text;
  81. assert.ok(html.includes('<div id="root">') && !html.includes("__BOOTSTRAP__"));
  82. assert.ok(!html.includes("__TITLE__"));
  83. assert.equal(html.match(/<\/script/gi).length, 1, "loader must not close its script tag early");
  84. assert.ok(
  85. Buffer.byteLength(html) < 4 * 1024 * 1024,
  86. "panel HTML stays small; the UI loads as resources",
  87. );
  88. const manifest = JSON.parse(
  89. (await client.readResource({ uri: ui("assets/assets.json") })).contents[0].text,
  90. );
  91. for (const script of manifest.scripts) {
  92. const part = await client.readResource({ uri: ui(`assets/${script}`) });
  93. assert.ok(Buffer.byteLength(part.contents[0].text) <= 4 * 1024 * 1024);
  94. }
  95. const cmapUri = ui("assets/pdfjs/cmaps/UniGB-UCS2-H.bcmap");
  96. if (has("pdf")) {
  97. const cmap = await client.readResource({ uri: cmapUri });
  98. assert.equal(cmap.contents[0].mimeType, "application/octet-stream");
  99. assert.ok(cmap.contents[0].blob.length > 100);
  100. } else await assert.rejects(client.readResource({ uri: cmapUri }));
  101. // pdf.js wasm(JPEG 2000 / ICC)与无 CJK 系统字体时的兜底字体。
  102. const fallbackUri = ui("assets/cjk-fallback.json");
  103. if (has("pdf")) {
  104. const openjpeg = await client.readResource({ uri: ui("assets/pdfjs/wasm/openjpeg.wasm") });
  105. assert.ok(
  106. Buffer.from(openjpeg.contents[0].blob, "base64")
  107. .subarray(0, 4)
  108. .equals(Buffer.from([0, 0x61, 0x73, 0x6d])),
  109. );
  110. const { faces } = JSON.parse(
  111. (await client.readResource({ uri: fallbackUri })).contents[0].text,
  112. );
  113. assert.ok(faces.length >= 50 && faces.every((face) => face.unicodeRange.startsWith("U+")));
  114. const slice = await client.readResource({ uri: ui(`assets/${faces[0].file}`) });
  115. assert.equal(Buffer.from(slice.contents[0].blob, "base64").subarray(0, 4).toString(), "wOF2");
  116. } else await assert.rejects(client.readResource({ uri: fallbackUri }));
  117. const wasmUri = ui("assets/sheets.wasm");
  118. if (has("xlsx")) {
  119. const wasm = await client.readResource({ uri: wasmUri });
  120. assert.ok(
  121. Buffer.from(wasm.contents[0].blob, "base64")
  122. .subarray(0, 4)
  123. .equals(Buffer.from([0, 0x61, 0x73, 0x6d])),
  124. );
  125. } else await assert.rejects(client.readResource({ uri: wasmUri }));
  126. await assert.rejects(client.readResource({ uri: ui("assets/..%2Fserver.mjs") }));
  127. // Empty viewer, listing.
  128. assert.equal((await ok("get_viewer")).structuredContent.document, null);
  129. assert.match(text(await ok("get_view")), /no document open/);
  130. const listed = (await ok("list_documents")).structuredContent.documents
  131. .map((doc) => doc.path)
  132. .sort();
  133. const fixtures = {
  134. xlsx: "docs/budget.xlsx",
  135. pptx: "docs/launch.pptx",
  136. pdf: "docs/paper.pdf",
  137. docx: "docs/report.docx",
  138. };
  139. assert.deepEqual(
  140. listed.filter((path) => !path.includes("escape")),
  141. [
  142. ...Object.entries(fixtures)
  143. .filter(([kind]) => has(kind))
  144. .map(([, path]) => path),
  145. ...(has("pdf") ? ["docs/cjk.pdf"] : []),
  146. ].sort(),
  147. );
  148. // Path safety.
  149. const sampleKind = has("docx") ? "docx" : kinds[0];
  150. const sample = fixtures[sampleKind];
  151. assert.equal(
  152. await failCode("open_document", { path: `../outside.${sampleKind}` }),
  153. "path_outside_workspace",
  154. );
  155. if (has("pdf"))
  156. assert.equal(
  157. await failCode("open_document", { path: "docs/escape.pdf" }),
  158. "path_outside_workspace",
  159. );
  160. assert.equal(
  161. await failCode("open_document", { path: sample.replace(/[^/.]+\./, "missing.") }),
  162. "not_found",
  163. );
  164. assert.equal(await failCode("open_document", { path: "docs/generate.txt" }), "unsupported_type");
  165. for (const [kind, path] of Object.entries(fixtures))
  166. if (!has(kind))
  167. assert.equal(await failCode("open_document", { path }), "unsupported_type", path);
  168. // Open + reveal.
  169. let opened;
  170. if (has("docx")) {
  171. opened = await ok("open_document", { path: "docs/report.docx", at: "p:4" });
  172. assert.equal(opened.structuredContent.document.kind, "docx");
  173. assert.deepEqual(opened.structuredContent.reveal.targets, [{ at: "p:4" }]);
  174. assert.match(text(opened), /docs\/report\.docx#p:3 {2}Revenue/);
  175. assert.equal(
  176. await failCode("open_document", { path: "docs/report.docx", at: "slide:2" }),
  177. "invalid_anchor",
  178. );
  179. } else {
  180. opened = await ok("open_document", { path: sample });
  181. assert.equal(opened.structuredContent.document.kind, kinds[0]);
  182. }
  183. // Read and search each format.
  184. if (has("docx"))
  185. assert.match(
  186. text(await ok("read_document", { anchor: "docs/report.docx#t:1" })),
  187. /\| North \| 120 \|/,
  188. );
  189. if (has("xlsx"))
  190. assert.match(
  191. text(await ok("read_document", { anchor: "docs/budget.xlsx#Revenue!A1:E5" })),
  192. /E2: =SUM\(B2:D2\)/,
  193. );
  194. if (has("pptx")) {
  195. assert.match(
  196. text(await ok("read_document", { anchor: "docs/launch.pptx#slide:2" })),
  197. /Speaker notes/,
  198. );
  199. const hits = (await ok("search_document", { path: "docs/launch.pptx", query: "dana" }))
  200. .structuredContent.hits;
  201. assert.equal(hits.length, 1);
  202. assert.match(hits[0].anchor, /^docs\/launch\.pptx#slide:2\/shape:\d+$/);
  203. }
  204. if (has("pdf")) {
  205. assert.match(
  206. text(await ok("read_document", { anchor: "docs/paper.pdf#page:1" })),
  207. /缓存显著降低延迟/,
  208. );
  209. const hits = (await ok("search_document", { path: "docs/paper.pdf", query: "缓存" }))
  210. .structuredContent.hits;
  211. assert.ok(hits.length > 0);
  212. assert.match(hits[0].anchor, /^docs\/paper\.pdf#page:\d+$/);
  213. assert.equal(
  214. await failCode("read_document", { anchor: "docs/paper.pdf#page:9" }),
  215. "invalid_anchor",
  216. );
  217. }
  218. // show_in_viewer switches documents and normalises anchors.
  219. if (has("xlsx")) {
  220. const shown = await ok("show_in_viewer", {
  221. targets: [
  222. { anchor: "docs/budget.xlsx#revenue!e2:B2" },
  223. { anchor: "docs/budget.xlsx#Notes!B2", quote: "0.12" },
  224. ],
  225. note: "Totals",
  226. });
  227. assert.equal(shown.structuredContent.document.path, "docs/budget.xlsx");
  228. assert.deepEqual(shown.structuredContent.reveal.targets, [
  229. { at: "Revenue!B2:E2" },
  230. { at: "Notes!B2", quote: "0.12" },
  231. ]);
  232. assert.equal(shown.structuredContent.reveal.note, "Totals");
  233. assert.ok(shown.structuredContent.reveal.seq > (opened.structuredContent.reveal?.seq ?? 0));
  234. }
  235. if (has("pdf")) {
  236. const shown = await ok("show_in_viewer", {
  237. targets: [{ anchor: "docs/paper.pdf#page:1", quote: "缓存" }],
  238. note: "Here",
  239. });
  240. assert.equal(shown.structuredContent.document.path, "docs/paper.pdf");
  241. assert.deepEqual(shown.structuredContent.reveal.targets, [{ at: "page:1", quote: "缓存" }]);
  242. assert.ok(shown.structuredContent.reveal.seq > (opened.structuredContent.reveal?.seq ?? 0));
  243. }
  244. if (kinds.length > 1)
  245. assert.equal(
  246. await failCode("show_in_viewer", {
  247. targets: kinds.slice(0, 2).map((kind) => ({ anchor: fixtures[kind] })),
  248. }),
  249. "invalid_anchor",
  250. );
  251. // Panel loads bytes in chunks and reports the view.
  252. const loaded = (await ok("load_document", { path: sample })).structuredContent;
  253. assert.equal(loaded.file.chunks, 1);
  254. if (has("docx")) assert.equal(loaded.blocks[0].at, "p:1");
  255. const chunk = await client.readResource({ uri: ui(`file/${loaded.file.token}/0`) });
  256. assert.equal(Buffer.from(chunk.contents[0].blob, "base64").length, loaded.file.bytes);
  257. await assert.rejects(client.readResource({ uri: ui("file/nope/0") }));
  258. const selection = {
  259. docx: { at: "p:4", text: "Revenue grew by 12 percent" },
  260. xlsx: { at: "Revenue!B2", text: "100" },
  261. pptx: { at: "slide:2", text: "Owner: Dana" },
  262. pdf: { at: "page:1", text: "缓存显著降低延迟" },
  263. }[sampleKind];
  264. await ok("report_view", { path: sample, at: selection.at, selection });
  265. const view = await ok("get_view");
  266. assert.ok(text(view).includes(`User selection: ${sample}#${selection.at}`), text(view));
  267. assert.ok(text(view).includes(selection.text));
  268. assert.equal((await ok("get_viewer")).structuredContent.document.path, sample);
  269. assert.equal(
  270. (await ok("check_document", { path: sample })).structuredContent.revision,
  271. loaded.info.revision,
  272. );
  273. process.stdout.write(`${name} smoke (${kinds.join(", ")}): ok\n`);
  274. } finally {
  275. await client.close();
  276. await rm(workspace, { recursive: true, force: true });
  277. }