design-plugin.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import { execFileSync, spawnSync } from "node:child_process";
  2. import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
  3. import { mkdtemp, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { describe, expect, it } from "vitest";
  8. // 设计工作流插件 design:入口技能 + 设计资源 + SessionStart 注入。
  9. // 宿主侧的插件 seed、默认启用与 hook 执行由 bootstrap / build-sea / desktop 的测试覆盖,这里只测插件内容。
  10. const pluginRoot = fileURLToPath(new URL("../", import.meta.url));
  11. const skillRoot = join(pluginRoot, "skills", "design");
  12. function read(relative: string): string {
  13. return readFileSync(join(skillRoot, ...relative.split("/")), "utf8");
  14. }
  15. function listMarkdown(dir: string): string[] {
  16. return readdirSync(dir)
  17. .filter((name) => name.endsWith(".md"))
  18. .map((name) => join(dir, name));
  19. }
  20. const ruleFiles = () => [join(skillRoot, "SKILL.md"), ...listMarkdown(join(skillRoot, "references"))];
  21. describe("design 插件结构", () => {
  22. // 原用例与另一份设计包逐项对照,对照对象不在本仓库;
  23. // 内置到 ZCode 后改成直接钉住随包内容,断言不变。
  24. it("随包子技能:四个方法型子技能齐全;第三方技能合集只带 SKILL.md、不带上游宣传页", () => {
  25. const skills = join(pluginRoot, "skills", "design", "design-resources", "skills");
  26. for (const kept of ["design-review", "plan-design-review", "design-consultation", "brand-guidelines"]) {
  27. expect(existsSync(join(skills, kept, "SKILL.md")), kept).toBe(true);
  28. }
  29. expect(existsSync(join(skills, "plan-design-review", "sections", "review-sections.md"))).toBe(true);
  30. expect(existsSync(join(skills, "design-consultation", "sections", "proposal-and-preview.md"))).toBe(true);
  31. // 上游任何版本都没有许可原文的子技能不随包。
  32. expect(existsSync(join(skills, "competitive-ads-extractor"))).toBe(false);
  33. // 带独立许可的子技能随目录带上游许可原文;主体许可是 Open Design 的 Apache-2.0。
  34. expect(readFileSync(join(skills, "frontend-design", "LICENSE.txt"), "utf8")).toContain("Apache License");
  35. expect(readFileSync(join(skills, "taste-skill", "LICENSE"), "utf8")).toContain("Copyright (c) 2026 Leonxlnx");
  36. const resources = join(pluginRoot, "skills", "design", "design-resources");
  37. expect(readFileSync(join(resources, "LICENSE.md"), "utf8")).toContain("Copyright 2026 Open Design contributors");
  38. expect(readFileSync(join(resources, "NOTICE.md"), "utf8")).toContain("https://github.com/nexu-io/open-design");
  39. });
  40. it("技能发现只扫 skills/ 下一层:只有入口技能 design,design-resources 里的嵌套技能不会被单独注册", () => {
  41. const entries = readdirSync(join(pluginRoot, "skills"), { withFileTypes: true }).filter((e) => e.isDirectory());
  42. expect(entries.map((e) => e.name)).toEqual(["design"]);
  43. expect(existsSync(join(pluginRoot, "skills", "design", "SKILL.md"))).toBe(true);
  44. });
  45. });
  46. describe("design 官方插件内容与加载", () => {
  47. it("manifest 与 package 版本一致,只声明技能,不声明 MCP、不需要配置", () => {
  48. const manifest = JSON.parse(readFileSync(join(pluginRoot, ".zcode-plugin", "plugin.json"), "utf8"));
  49. const pkg = JSON.parse(readFileSync(join(pluginRoot, "package.json"), "utf8"));
  50. expect(manifest.name).toBe("design");
  51. expect(manifest.version).toBe(pkg.version);
  52. expect(manifest.skills).toBe("./skills");
  53. for (const forbidden of ["agents", "hooks", "commands", "identity", "instructions", "mcpServers", "userConfig"]) {
  54. expect(manifest, forbidden).not.toHaveProperty(forbidden);
  55. }
  56. expect(JSON.stringify(manifest)).not.toContain("user_config");
  57. expect(existsSync(join(pluginRoot, "mcp"))).toBe(false);
  58. expect(existsSync(join(pluginRoot, ".mcp.json"))).toBe(false);
  59. });
  60. it(".zcode-plugin 与 .claude-plugin 两份宿主清单逐字节一致", () => {
  61. const zcode = readFileSync(join(pluginRoot, ".zcode-plugin", "plugin.json"), "utf8");
  62. expect(readFileSync(join(pluginRoot, ".claude-plugin", "plugin.json"), "utf8")).toBe(zcode);
  63. });
  64. it("入口技能 frontmatter 声明 design,并按产物把对话内视图与 pptx 排除在外", () => {
  65. const entry = read("SKILL.md");
  66. expect(entry).toMatch(/^---\nname: design\n/);
  67. const description = entry.match(/^description: "([^"]+)"/m)?.[1] ?? "";
  68. expect(description).toContain("visualize");
  69. expect(description).toContain("presentations");
  70. // 两个宿主的技能描述加载上限都按 1024 字符算。
  71. expect([...description].length).toBeLessThanOrEqual(1024);
  72. });
  73. it("规则层文件固定为入口 + 11 份按需文件,各自不超体量上限;超过 100 行的在顶部有目录,都不超过 500 行", () => {
  74. // 0.8.0 按交付物分流(deck / app / page / motion,产出约定并回入口 Output),并接回生图(image.md);总量 40 KB。
  75. const limits: Record<string, number> = {
  76. "SKILL.md": 4, "references/design-system.md": 5, "references/create.md": 4, "references/redesign.md": 4,
  77. "references/check.md": 3, "references/interact.md": 2, "references/catalog.md": 6, "references/deck.md": 6,
  78. "references/app.md": 5, "references/page.md": 5, "references/motion.md": 1, "references/image.md": 8,
  79. };
  80. const actual = ruleFiles().map((file) => file.slice(skillRoot.length + 1)).sort();
  81. expect(actual).toEqual(Object.keys(limits).sort());
  82. let total = 0;
  83. for (const [file, kb] of Object.entries(limits)) {
  84. const text = read(file);
  85. const bytes = Buffer.byteLength(text, "utf8");
  86. total += bytes;
  87. expect(bytes, file).toBeLessThanOrEqual(kb * 1024);
  88. const lines = text.split("\n").length;
  89. expect(lines, file).toBeLessThanOrEqual(500);
  90. if (lines > 100) expect(text.split("\n").slice(0, 12).join("\n"), file).toMatch(/Contents|目录/);
  91. }
  92. expect(total).toBeLessThanOrEqual(40 * 1024);
  93. });
  94. it("入口与 references 里的相对链接从所在文件出发都能解析到随包文件", () => {
  95. const files = ruleFiles();
  96. const broken: string[] = [];
  97. let checked = 0;
  98. for (const file of files) {
  99. for (const match of readFileSync(file, "utf8").matchAll(/\]\(([^)\s]+)\)/g)) {
  100. const target = (match[1] as string).split("#")[0] as string;
  101. // 「原型/…」是交付示例里的工作区产物路径,不是随包文件。
  102. if (target === "" || target.startsWith("原型/") || /^[a-z][a-z0-9+.-]*:/i.test(target)) continue;
  103. checked += 1;
  104. if (!existsSync(join(dirname(file), ...target.split("/")))) broken.push(`${file.slice(skillRoot.length)} -> ${target}`);
  105. }
  106. }
  107. expect(checked).toBeGreaterThan(15);
  108. expect(broken).toEqual([]);
  109. });
  110. it("入口与 references 正文统一为英文;路径、文件名示例和 catalog 里转引的资源元数据除外", () => {
  111. const mixed = ruleFiles()
  112. .filter((file) => !file.endsWith("catalog.md"))
  113. .filter((file) => {
  114. // deck / app / page 里的骨架块由 build-catalog.mjs 从资源元数据生成,和 catalog 一样不算正文。
  115. const prose = readFileSync(file, "utf8")
  116. .replace(/<!-- Skeletons generated[\s\S]*?<!-- End of generated skeletons\. -->/g, "")
  117. .replace(/^description: .*$/m, "")
  118. .replace(/```[\s\S]*?```/g, "")
  119. .replace(/`[^`]*`/g, "")
  120. .replace(/\]\([^)]*\)/g, "]");
  121. return /[\u4e00-\u9fff]/.test(prose);
  122. });
  123. expect(mixed).toEqual([]);
  124. });
  125. it("不残留 Zwork 平台专有写法,也不点名只有某一个宿主才有的工具", () => {
  126. const banned =
  127. /skill:\/\/|deliver_file|zwork|memory_change|browser_tool|process\.exec|ask_user_question|tool_search|image_recognition|update_run_checklist|propose_work_plan|artifactCard|generate_image_seedream|search_image|control-browser|zcode-file-citation|在 Browser 中|AskUserQuestion|TodoWrite|ToolSearch/i;
  128. const hits = ruleFiles().filter((file) =>
  129. banned.test(readFileSync(file, "utf8")),
  130. );
  131. expect(hits).toEqual([]);
  132. // 唯一点名的外部工具是 image-generation 插件的 generate_image,只出现在生图规则里。
  133. const namesTool = ruleFiles().filter((file) => /\bgenerate_image\b/.test(readFileSync(file, "utf8")));
  134. expect(namesTool.map((file) => file.slice(skillRoot.length).replace(/^\//, ""))).toEqual(["references/image.md"]);
  135. });
  136. it("产出约定:file:// 直接可开、data-zcode-design 标记、section.slide / data-variant / CSS 变量;入口点名这些约定", () => {
  137. // 0.8.0 起产出约定并入入口的 Output 一节,幻灯片标记在 deck.md。
  138. const entry = read("SKILL.md");
  139. const output = entry.slice(entry.indexOf("## Output"), entry.indexOf("## Evidence"));
  140. for (const phrase of ["file://", 'type="module"', "fetch", "<html data-zcode-design>", "data-variant", "CSS custom properties"]) {
  141. expect(output, phrase).toContain(phrase);
  142. }
  143. // 宿主设计模式按 section.slide 数页,幻灯片只认这一种写法。
  144. const deck = read("references/deck.md");
  145. expect(deck).toContain('<section class="slide">');
  146. expect(deck).not.toContain("<section data-slide>");
  147. expect(read("references/page.md")).toContain("no deck markers");
  148. expect(entry).toContain("file://");
  149. expect(entry).toContain("data-zcode-design");
  150. expect(entry.split("\n").length).toBeLessThanOrEqual(500);
  151. expect([...(entry.match(/^description: "([^"]+)"/m)?.[1] ?? "")].length).toBeLessThanOrEqual(1024);
  152. });
  153. it("宿主设计模式按有无降级:有就提示用它钉评 / 轻改,没有就退回浏览器打开 + 文字描述,不声称不存在的功能", () => {
  154. const entry = read("SKILL.md");
  155. const section = entry.slice(entry.indexOf("## Output"), entry.indexOf("## Evidence"));
  156. expect(section).toMatch(/design mode/);
  157. expect(section).toMatch(/pin comments/);
  158. expect(section).toMatch(/open the file in a browser/);
  159. expect(section).toMatch(/describe (the )?changes/);
  160. expect(section).toMatch(/Never claim/);
  161. expect(read("SKILL.md")).toMatch(/design mode[^\n]*browser/);
  162. });
  163. it("adapt-canvas.mjs 校验模板哈希并写出适配副本,已存在的输出不覆盖", async () => {
  164. const dir = await mkdtemp(join(tmpdir(), "zcode-design-canvas-"));
  165. try {
  166. const out = join(dir, "canvas.html");
  167. const script = join(skillRoot, "scripts", "adapt-canvas.mjs");
  168. execFileSync(process.execPath, [script, out], { encoding: "utf8" });
  169. const adapted = readFileSync(out, "utf8");
  170. const template = read("design-resources/skills/infinite-canvas/assets/infinite-canvas-template.html");
  171. expect(adapted).not.toBe(template);
  172. expect(adapted).toContain("prefers-reduced-motion");
  173. expect(() => execFileSync(process.execPath, [script, out], { encoding: "utf8", stdio: "pipe" })).toThrow();
  174. } finally {
  175. await rm(dir, { force: true, recursive: true });
  176. }
  177. });
  178. it("gstack 三份子技能默认不读:规则文件不指向它们", () => {
  179. for (const name of ["design-review", "plan-design-review", "design-consultation"]) {
  180. for (const file of ruleFiles()) {
  181. expect(readFileSync(file, "utf8"), `${file} -> ${name}`).not.toContain(`skills/${name}/`);
  182. }
  183. }
  184. });
  185. it("生图:入口路由到 image.md;调 image-generation 插件的 generate_image,本插件不带 MCP;缺工具或失败时如实说明、不画替代图", () => {
  186. expect(read("SKILL.md")).toContain("[image](references/image.md)");
  187. const image = read("references/image.md");
  188. expect(image).toContain("`generate_image` tool of the `image-generation` plugin");
  189. // 只用工具真实声明的三个参数,不编造尺寸、比例、种子等参数。
  190. for (const param of ["`prompt`", "`reference_image`", "`output_path`"]) expect(image, param).toContain(param);
  191. expect(image).toMatch(/There is no size, ratio, seed, mask, format or transparency parameter/);
  192. expect(image).toMatch(/Never pass off a hand-drawn SVG, HTML or CSS picture as the generated image/);
  193. expect(image).toMatch(/do not resend/);
  194. expect(image).toMatch(/never put it in a page/);
  195. // 国内出图带「由 Z.ai 生成」可见水印和 AIGC 标识,真机上见过模型自己裁掉,必须明令保留。
  196. expect(image).toMatch(/Keep the generated image's watermark and AI label: never crop, cover, blur or paint over it/);
  197. expect(existsSync(join(pluginRoot, "mcp"))).toBe(false);
  198. });
  199. // 设计工作流入口的常驻注入:SessionStart hook,POSIX sh,不依赖 Node。
  200. describe("SessionStart 注入设计工作流", () => {
  201. const hooksDir = join(pluginRoot, "hooks");
  202. const runHook = (env: Record<string, string>) =>
  203. spawnSync("sh", [join(hooksDir, "run-hook.cmd"), "design-rules"], { encoding: "utf8", timeout: 20000, env: { PATH: "/usr/bin:/bin", ...env } });
  204. it("hooks.json 先用 sh 调启动器、失败再直接调(市场安装不恢复可执行位),且出错放行", () => {
  205. const hooks = JSON.parse(readFileSync(join(hooksDir, "hooks.json"), "utf8"));
  206. const entry = hooks.hooks.SessionStart[0].hooks[0];
  207. expect(entry.command).toBe(
  208. 'sh "${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd" design-rules || "${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd" design-rules',
  209. );
  210. expect(entry.onError).toBe("allow");
  211. expect(entry.command).not.toMatch(/\bnode\b/);
  212. });
  213. it("在没有 Node 的 PATH 下输出合法的 additionalContext:只是指向 design 技能的指针,写明 base directory", () => {
  214. const run = runHook({ ZCODE_PLUGIN_ROOT: pluginRoot.replace(/\/$/, "") });
  215. expect(run.status).toBe(0);
  216. const out = JSON.parse(run.stdout);
  217. expect(out.hookSpecificOutput.hookEventName).toBe("SessionStart");
  218. const ctx: string = out.hookSpecificOutput.additionalContext;
  219. expect(ctx).toContain(`relative to: ${skillRoot.replace(/\/$/, "")}`);
  220. expect(ctx).toContain("load the `design` skill first");
  221. for (const deliverable of ["HTML design", "prototype", "HTML deck", "redesign"]) {
  222. expect(ctx, deliverable).toContain(deliverable);
  223. }
  224. // 内置后默认启用,每个会话都会带上它:只放一句指针 + 路径基准,不注入入口正文。
  225. // 压短后(0.7.0 内置)去掉路径约 110 字节,上限从 1 KB 收到 160 字节,防止再长回去。
  226. expect(ctx).not.toContain("# 设计专家 · 工作流入口");
  227. expect(Buffer.byteLength(ctx.replace(skillRoot.replace(/\/$/, ""), ""), "utf8")).toBeLessThanOrEqual(160);
  228. });
  229. it("宿主只提供 CLAUDE_PLUGIN_ROOT 时也能定位插件目录", () => {
  230. const run = runHook({ CLAUDE_PLUGIN_ROOT: pluginRoot.replace(/\/$/, "") });
  231. expect(run.status).toBe(0);
  232. expect(JSON.parse(run.stdout).hookSpecificOutput.additionalContext).toContain(`relative to: ${skillRoot.replace(/\/$/, "")}`);
  233. });
  234. it("Windows(Git Bash 有 cygpath)时把路径转成 C:/ 形式,Node 侧的文件工具才读得到", () => {
  235. // 用假 cygpath 模拟 Git Bash:-u 原样返回,-m 返回盘符路径。
  236. const bin = mkdtempSync(join(tmpdir(), "design-cygpath-"));
  237. writeFileSync(join(bin, "cygpath"), '#!/bin/sh\n[ "$1" = "-m" ] && printf "C:/fake%s\\n" "$2" || printf "%s\\n" "$2"\n');
  238. chmodSync(join(bin, "cygpath"), 0o755);
  239. const run = spawnSync("sh", [join(hooksDir, "run-hook.cmd"), "design-rules"], {
  240. encoding: "utf8",
  241. timeout: 20000,
  242. env: { PATH: `${bin}:/usr/bin:/bin`, ZCODE_PLUGIN_ROOT: pluginRoot.replace(/\/$/, "") },
  243. });
  244. expect(run.status).toBe(0);
  245. const ctx: string = JSON.parse(run.stdout).hookSpecificOutput.additionalContext;
  246. expect(ctx).toContain(`relative to: C:/fake${skillRoot.replace(/\/$/, "")}`);
  247. });
  248. it("入口缺失或路径错误时静默退出 0,不阻塞会话", () => {
  249. const run = runHook({ ZCODE_PLUGIN_ROOT: join(pluginRoot, "does-not-exist") });
  250. expect(run.status).toBe(0);
  251. expect(run.stdout).toBe("");
  252. });
  253. });
  254. });