smoke.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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, title } = 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. // read / search 服务面板中的讨论:描述点名本插件的面板与生产技能,并要求先打开文档。
  77. for (const toolName of ["read_document", "search_document"]) {
  78. const { description } = tools.find((tool) => tool.name === toolName);
  79. assert.ok(description.includes(`${title.en} panel`), `${toolName} names the ${title.en} panel`);
  80. assert.ok(description.includes("open_document first"), `${toolName} asks to open first`);
  81. for (const kind of ["docx", "xlsx", "pptx", "pdf"])
  82. assert.equal(
  83. description.includes(`\`${kind}\``),
  84. has(kind),
  85. `${toolName} names the ${kind} skill`,
  86. );
  87. }
  88. // Panel resource and assets.
  89. const panel = await client.readResource({ uri: ui("panel.html") });
  90. assert.equal(panel.contents[0].mimeType, "text/html;profile=mcp-app");
  91. assert.deepEqual(panel.contents[0]._meta, { "zcode/csp": { wasmUnsafeEval: true } });
  92. const html = panel.contents[0].text;
  93. assert.ok(html.includes('<div id="root">') && !html.includes("__BOOTSTRAP__"));
  94. assert.ok(!html.includes("__TITLE__"));
  95. assert.equal(html.match(/<\/script/gi).length, 1, "loader must not close its script tag early");
  96. assert.ok(
  97. Buffer.byteLength(html) < 4 * 1024 * 1024,
  98. "panel HTML stays small; the UI loads as resources",
  99. );
  100. const manifest = JSON.parse(
  101. (await client.readResource({ uri: ui("assets/assets.json") })).contents[0].text,
  102. );
  103. for (const script of manifest.scripts) {
  104. const part = await client.readResource({ uri: ui(`assets/${script}`) });
  105. assert.ok(Buffer.byteLength(part.contents[0].text) <= 4 * 1024 * 1024);
  106. }
  107. const cmapUri = ui("assets/pdfjs/cmaps/UniGB-UCS2-H.bcmap");
  108. if (has("pdf")) {
  109. const cmap = await client.readResource({ uri: cmapUri });
  110. assert.equal(cmap.contents[0].mimeType, "application/octet-stream");
  111. assert.ok(cmap.contents[0].blob.length > 100);
  112. } else await assert.rejects(client.readResource({ uri: cmapUri }));
  113. // pdf.js wasm(JPEG 2000 / ICC)与无 CJK 系统字体时的兜底字体。
  114. const fallbackUri = ui("assets/cjk-fallback.json");
  115. if (has("pdf")) {
  116. const openjpeg = await client.readResource({ uri: ui("assets/pdfjs/wasm/openjpeg.wasm") });
  117. assert.ok(
  118. Buffer.from(openjpeg.contents[0].blob, "base64")
  119. .subarray(0, 4)
  120. .equals(Buffer.from([0, 0x61, 0x73, 0x6d])),
  121. );
  122. const { faces } = JSON.parse(
  123. (await client.readResource({ uri: fallbackUri })).contents[0].text,
  124. );
  125. assert.ok(faces.length >= 50 && faces.every((face) => face.unicodeRange.startsWith("U+")));
  126. const slice = await client.readResource({ uri: ui(`assets/${faces[0].file}`) });
  127. assert.equal(Buffer.from(slice.contents[0].blob, "base64").subarray(0, 4).toString(), "wOF2");
  128. } else await assert.rejects(client.readResource({ uri: fallbackUri }));
  129. const wasmUri = ui("assets/sheets.wasm");
  130. if (has("xlsx")) {
  131. const wasm = await client.readResource({ uri: wasmUri });
  132. assert.ok(
  133. Buffer.from(wasm.contents[0].blob, "base64")
  134. .subarray(0, 4)
  135. .equals(Buffer.from([0, 0x61, 0x73, 0x6d])),
  136. );
  137. } else await assert.rejects(client.readResource({ uri: wasmUri }));
  138. await assert.rejects(client.readResource({ uri: ui("assets/..%2Fserver.mjs") }));
  139. // Empty viewer, listing.
  140. assert.equal((await ok("get_viewer")).structuredContent.document, null);
  141. assert.match(text(await ok("get_view")), /no document open/);
  142. const listed = (await ok("list_documents")).structuredContent.documents
  143. .map((doc) => doc.path)
  144. .sort();
  145. const fixtures = {
  146. xlsx: "docs/budget.xlsx",
  147. pptx: "docs/launch.pptx",
  148. pdf: "docs/paper.pdf",
  149. docx: "docs/report.docx",
  150. };
  151. assert.deepEqual(
  152. listed.filter((path) => !path.includes("escape")),
  153. [
  154. ...Object.entries(fixtures)
  155. .filter(([kind]) => has(kind))
  156. .map(([, path]) => path),
  157. ...(has("pdf") ? ["docs/cjk.pdf"] : []),
  158. ].sort(),
  159. );
  160. // Path safety.
  161. const sampleKind = has("docx") ? "docx" : kinds[0];
  162. const sample = fixtures[sampleKind];
  163. assert.equal(
  164. await failCode("open_document", { path: `../outside.${sampleKind}` }),
  165. "path_outside_workspace",
  166. );
  167. if (has("pdf"))
  168. assert.equal(
  169. await failCode("open_document", { path: "docs/escape.pdf" }),
  170. "path_outside_workspace",
  171. );
  172. assert.equal(
  173. await failCode("open_document", { path: sample.replace(/[^/.]+\./, "missing.") }),
  174. "not_found",
  175. );
  176. assert.equal(await failCode("open_document", { path: "docs/generate.txt" }), "unsupported_type");
  177. for (const [kind, path] of Object.entries(fixtures))
  178. if (!has(kind))
  179. assert.equal(await failCode("open_document", { path }), "unsupported_type", path);
  180. // Open + reveal.
  181. let opened;
  182. if (has("docx")) {
  183. opened = await ok("open_document", { path: "docs/report.docx", at: "p:4" });
  184. assert.equal(opened.structuredContent.document.kind, "docx");
  185. assert.deepEqual(opened.structuredContent.reveal.targets, [{ at: "p:4" }]);
  186. assert.match(text(opened), /docs\/report\.docx#p:3 {2}Revenue/);
  187. assert.equal(
  188. await failCode("open_document", { path: "docs/report.docx", at: "slide:2" }),
  189. "invalid_anchor",
  190. );
  191. } else {
  192. opened = await ok("open_document", { path: sample });
  193. assert.equal(opened.structuredContent.document.kind, kinds[0]);
  194. }
  195. // Read and search each format.
  196. if (has("docx"))
  197. assert.match(
  198. text(await ok("read_document", { anchor: "docs/report.docx#t:1" })),
  199. /\| North \| 120 \|/,
  200. );
  201. if (has("xlsx"))
  202. assert.match(
  203. text(await ok("read_document", { anchor: "docs/budget.xlsx#Revenue!A1:E5" })),
  204. /E2: =SUM\(B2:D2\)/,
  205. );
  206. if (has("pptx")) {
  207. assert.match(
  208. text(await ok("read_document", { anchor: "docs/launch.pptx#slide:2" })),
  209. /Speaker notes/,
  210. );
  211. const hits = (await ok("search_document", { path: "docs/launch.pptx", query: "dana" }))
  212. .structuredContent.hits;
  213. assert.equal(hits.length, 1);
  214. assert.match(hits[0].anchor, /^docs\/launch\.pptx#slide:2\/shape:\d+$/);
  215. }
  216. if (has("pdf")) {
  217. assert.match(
  218. text(await ok("read_document", { anchor: "docs/paper.pdf#page:1" })),
  219. /缓存显著降低延迟/,
  220. );
  221. const hits = (await ok("search_document", { path: "docs/paper.pdf", query: "缓存" }))
  222. .structuredContent.hits;
  223. assert.ok(hits.length > 0);
  224. assert.match(hits[0].anchor, /^docs\/paper\.pdf#page:\d+$/);
  225. assert.equal(
  226. await failCode("read_document", { anchor: "docs/paper.pdf#page:9" }),
  227. "invalid_anchor",
  228. );
  229. }
  230. // show_in_viewer switches documents and normalises anchors.
  231. if (has("xlsx")) {
  232. const shown = await ok("show_in_viewer", {
  233. targets: [
  234. { anchor: "docs/budget.xlsx#revenue!e2:B2" },
  235. { anchor: "docs/budget.xlsx#Notes!B2", quote: "0.12" },
  236. ],
  237. note: "Totals",
  238. });
  239. assert.equal(shown.structuredContent.document.path, "docs/budget.xlsx");
  240. assert.deepEqual(shown.structuredContent.reveal.targets, [
  241. { at: "Revenue!B2:E2" },
  242. { at: "Notes!B2", quote: "0.12" },
  243. ]);
  244. assert.equal(shown.structuredContent.reveal.note, "Totals");
  245. assert.ok(shown.structuredContent.reveal.seq > (opened.structuredContent.reveal?.seq ?? 0));
  246. }
  247. if (has("pdf")) {
  248. const shown = await ok("show_in_viewer", {
  249. targets: [{ anchor: "docs/paper.pdf#page:1", quote: "缓存" }],
  250. note: "Here",
  251. });
  252. assert.equal(shown.structuredContent.document.path, "docs/paper.pdf");
  253. assert.deepEqual(shown.structuredContent.reveal.targets, [{ at: "page:1", quote: "缓存" }]);
  254. assert.ok(shown.structuredContent.reveal.seq > (opened.structuredContent.reveal?.seq ?? 0));
  255. }
  256. if (kinds.length > 1)
  257. assert.equal(
  258. await failCode("show_in_viewer", {
  259. targets: kinds.slice(0, 2).map((kind) => ({ anchor: fixtures[kind] })),
  260. }),
  261. "invalid_anchor",
  262. );
  263. // Panel loads bytes in chunks and reports the view.
  264. const loaded = (await ok("load_document", { path: sample })).structuredContent;
  265. assert.equal(loaded.file.chunks, 1);
  266. if (has("docx")) assert.equal(loaded.blocks[0].at, "p:1");
  267. const chunk = await client.readResource({ uri: ui(`file/${loaded.file.token}/0`) });
  268. assert.equal(Buffer.from(chunk.contents[0].blob, "base64").length, loaded.file.bytes);
  269. await assert.rejects(client.readResource({ uri: ui("file/nope/0") }));
  270. const selection = {
  271. docx: { at: "p:4", text: "Revenue grew by 12 percent" },
  272. xlsx: { at: "Revenue!B2", text: "100" },
  273. pptx: { at: "slide:2", text: "Owner: Dana" },
  274. pdf: { at: "page:1", text: "缓存显著降低延迟" },
  275. }[sampleKind];
  276. await ok("report_view", { path: sample, at: selection.at, selection });
  277. const view = await ok("get_view");
  278. assert.ok(text(view).includes(`User selection: ${sample}#${selection.at}`), text(view));
  279. assert.ok(text(view).includes(selection.text));
  280. assert.equal((await ok("get_viewer")).structuredContent.document.path, sample);
  281. assert.equal(
  282. (await ok("check_document", { path: sample })).structuredContent.revision,
  283. loaded.info.revision,
  284. );
  285. // One server serves every session of a workspace: the host names the session in _meta.
  286. const inSession = (session, name, args = {}) =>
  287. client.callTool({ name, arguments: args, _meta: { session_id: session } });
  288. await inSession("s1", "open_document", { path: sample });
  289. await inSession("s1", "report_view", { viewId: "w1", path: sample, at: selection.at, selection });
  290. assert.equal((await inSession("s2", "get_viewer")).structuredContent.document, null);
  291. assert.match(text(await inSession("s2", "get_view")), /no document open/);
  292. assert.ok(text(await inSession("s1", "get_view")).includes(selection.text));
  293. const other = (await inSession("s2", "load_document", { path: sample })).structuredContent;
  294. const first = (await inSession("s1", "load_document", { path: sample })).structuredContent;
  295. for (let i = 0; i < 6; i++) await inSession("s2", "load_document", { path: sample });
  296. await assert.rejects(client.readResource({ uri: ui(`file/${other.file.token}/0`) }));
  297. await client.readResource({ uri: ui(`file/${first.file.token}/0`) });
  298. process.stdout.write(`${name} smoke (${kinds.join(", ")}): ok\n`);
  299. } finally {
  300. await client.close();
  301. await rm(workspace, { recursive: true, force: true });
  302. }