visualize-skill-gate.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { createConfig } from "@zcode/adapters/config";
  5. import { createNodeSkillAdapter } from "@zcode/adapters/skills";
  6. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  7. import type { Logger } from "@zcode/contracts";
  8. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  9. import { createWorkflowChildSkillPort } from "../src/app/script-workflow-child-runtime.js";
  10. import { resolveStartupPlugins } from "../src/app/startup-marks.js";
  11. import type { ZCodeApp, ZCodeAppOptions } from "../src/app/types.js";
  12. import { setZCodePluginEnabled } from "../src/plugins.js";
  13. import { inspectZCodeSkill, listZCodeSkills } from "../src/skills.js";
  14. import { StartupTimer } from "../src/startup-logging.js";
  15. import { getSkillReferenceCatalog } from "../src/zcode-protocol/skill-reference-catalog.js";
  16. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  17. import { createWorkspaceZCodeApp } from "../src/zcode-protocol/workspace-model-runtime.js";
  18. import { createRegistryBackedTestApp } from "./helpers/registry-backed-test-app.js";
  19. const VISUALIZE_PLUGIN_ID = "visualize@zcode-plugins-official";
  20. const VISUALIZE_SKILL = "visualize:visualize";
  21. const logger = {
  22. debug() {},
  23. info() {},
  24. warn() {},
  25. error() {},
  26. } as unknown as Logger;
  27. describe("visualize protocol-only skill discovery", () => {
  28. let root: string;
  29. let env: NodeJS.ProcessEnv;
  30. beforeEach(async () => {
  31. root = await mkdtemp(join(tmpdir(), "zcode-visualize-gate-"));
  32. vi.stubEnv("HOME", root);
  33. vi.stubEnv("USERPROFILE", root);
  34. env = { ZCODE_STORAGE_DIR: join(root, "storage") };
  35. });
  36. afterEach(async () => {
  37. vi.unstubAllEnvs();
  38. await rm(root, { recursive: true, force: true });
  39. });
  40. it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
  41. "loads skills with a read-only project config directory",
  42. async () => {
  43. const directory = join(root, ".zcode");
  44. const configPath = join(directory, "config.json");
  45. const original = JSON.stringify({
  46. plugins: { enabledPlugins: { [VISUALIZE_PLUGIN_ID]: true } },
  47. });
  48. await mkdir(directory);
  49. await writeFile(configPath, original);
  50. await chmod(directory, 0o555);
  51. try {
  52. const result = await listZCodeSkills({
  53. env,
  54. skipUserConfig: true,
  55. includeVisualize: true,
  56. workingDirectory: root,
  57. });
  58. expect(result.skills.some((skill) => skill.pluginId === VISUALIZE_PLUGIN_ID)).toBe(false);
  59. expect(result.skills.some((skill) => skill.name === "pdf")).toBe(true);
  60. expect(await readFile(configPath, "utf8")).toBe(original);
  61. } finally {
  62. await chmod(directory, 0o700);
  63. }
  64. },
  65. );
  66. it.each([undefined, false, true])(
  67. "list and inspect agree with includeVisualize=%s",
  68. async (includeVisualize) => {
  69. const userConfigPath = join(root, "config.json");
  70. await writeFile(
  71. userConfigPath,
  72. JSON.stringify({
  73. plugins: {
  74. visualizeDefaultOffMigrated: true,
  75. enabledPlugins: { [VISUALIZE_PLUGIN_ID]: true },
  76. },
  77. }),
  78. );
  79. const options = { env, includeVisualize, userConfigPath, workingDirectory: root };
  80. const outcome = await listZCodeSkills(options);
  81. expect(outcome.skills.some((skill) => skill.pluginId === VISUALIZE_PLUGIN_ID)).toBe(
  82. includeVisualize === true,
  83. );
  84. expect(outcome.skills.some((skill) => skill.name === "pdf")).toBe(true);
  85. for (const name of ["visualize", VISUALIZE_SKILL]) {
  86. if (includeVisualize) {
  87. const result = await inspectZCodeSkill({ ...options, name });
  88. expect(result.skill.metadata.pluginId).toBe(VISUALIZE_PLUGIN_ID);
  89. expect(result.skill.content).toContain("Inline HTML output contract");
  90. } else {
  91. await expect(inspectZCodeSkill({ ...options, name })).rejects.toThrow("Skill not found:");
  92. }
  93. }
  94. },
  95. );
  96. it.each([undefined, false, true])(
  97. "startup and workflow child agree with includeVisualize=%s",
  98. async (includeVisualize) => {
  99. const configResult = createConfig({
  100. env,
  101. skipUserConfig: true,
  102. workingDirectory: root,
  103. cliOverrides: { plugins: { enabledPlugins: { [VISUALIZE_PLUGIN_ID]: true } } },
  104. });
  105. const appOptions = { includeVisualize } as ZCodeAppOptions;
  106. const plugins = await resolveStartupPlugins({
  107. cliStorageRoot: join(root, "storage", "cli"),
  108. configResult,
  109. env,
  110. options: appOptions,
  111. startupTimer: new StartupTimer(logger, {}),
  112. workingDirectory: root,
  113. });
  114. const parentPort = createNodeSkillAdapter({ extraResolvedRoots: plugins.skillRoots });
  115. const childPort = createWorkflowChildSkillPort({
  116. appOptions,
  117. configResult,
  118. pluginSkillRoots: plugins.skillRoots,
  119. });
  120. for (const port of [parentPort, childPort!]) {
  121. const outcome = await port.discoverSkills({ workingDirectory: root });
  122. expect(outcome.skills.some((skill) => skill.pluginId === VISUALIZE_PLUGIN_ID)).toBe(
  123. includeVisualize === true,
  124. );
  125. expect(outcome.skills.some((skill) => skill.name === "pdf")).toBe(true);
  126. }
  127. },
  128. );
  129. it("keeps project skills with the same name available in CLI", async () => {
  130. const skillDir = join(root, ".agents", "skills", "visualize");
  131. await mkdir(skillDir, { recursive: true });
  132. await writeFile(
  133. join(skillDir, "SKILL.md"),
  134. "---\nname: visualize\ndescription: Project visualization.\n---\nProject skill.",
  135. );
  136. const result = await inspectZCodeSkill({
  137. env,
  138. skipUserConfig: true,
  139. workingDirectory: root,
  140. name: "visualize",
  141. });
  142. expect(result.skill.metadata.source).toBe("agents");
  143. expect(result.skill.content).toBe("Project skill.");
  144. });
  145. it("does not override explicit plugin disablement in protocol mode", async () => {
  146. const configPath = join(root, "config.json");
  147. await writeFile(
  148. configPath,
  149. JSON.stringify({ plugins: { enabledPlugins: { [VISUALIZE_PLUGIN_ID]: false } } }),
  150. );
  151. const options = {
  152. env,
  153. includeVisualize: true,
  154. userConfigPath: configPath,
  155. workingDirectory: root,
  156. };
  157. const outcome = await listZCodeSkills(options);
  158. expect(outcome.skills.some((skill) => skill.pluginId === VISUALIZE_PLUGIN_ID)).toBe(false);
  159. await expect(inspectZCodeSkill({ ...options, name: VISUALIZE_SKILL })).rejects.toThrow(
  160. "Skill not found:",
  161. );
  162. });
  163. it.each([
  164. { name: "default disabled", plugins: {}, expected: false },
  165. {
  166. name: "legacy enabled",
  167. plugins: { enabledPlugins: { [VISUALIZE_PLUGIN_ID]: true } },
  168. expected: false,
  169. },
  170. {
  171. name: "explicitly enabled",
  172. plugins: {
  173. visualizeDefaultOffMigrated: true,
  174. enabledPlugins: { [VISUALIZE_PLUGIN_ID]: true },
  175. },
  176. expected: true,
  177. },
  178. {
  179. name: "disabled",
  180. plugins: { enabledPlugins: { [VISUALIZE_PLUGIN_ID]: false } },
  181. expected: false,
  182. },
  183. {
  184. name: "uninstalled",
  185. plugins: { suppressedBuiltins: [VISUALIZE_PLUGIN_ID] },
  186. expected: false,
  187. },
  188. { name: "all plugins disabled", plugins: { enabled: false }, expected: false },
  189. ])("gates model context on the resolved plugin state: $name", async ({ plugins, expected }) => {
  190. const configPath = join(root, "config.json");
  191. await writeFile(configPath, JSON.stringify({ plugins }));
  192. const sessionStore = await createSqliteSessionStore({ dbPath: ":memory:" });
  193. const requests: string[] = [];
  194. let app: ZCodeApp | undefined;
  195. try {
  196. app = await createRegistryBackedTestApp({
  197. env: { ...env, ZCODE_GEN_UI_OUTPUT_ROOT: join(root, "visualizations") },
  198. includeVisualize: true,
  199. userConfigPath: configPath,
  200. sessionStore,
  201. runtimeConfig: {
  202. workingDirectory: root,
  203. presentationSurface: "zcode_desktop",
  204. mcp: { enabled: false },
  205. },
  206. modelExecutor: {
  207. async generateText(request) {
  208. requests.push(JSON.stringify(request.messages));
  209. return { text: "ok", finishReason: "stop", usage: {} };
  210. },
  211. },
  212. });
  213. await app.submitPrompt("hello");
  214. expect(requests).toHaveLength(1);
  215. const text = requests[0]!;
  216. expect(text.includes("### Interactive views")).toBe(expected);
  217. expect(text.includes("Visualization directory for this session:")).toBe(expected);
  218. expect(text.includes("This Desktop host supports Gen UI")).toBe(expected);
  219. expect(text.includes("Widget modelContent may accompany")).toBe(expected);
  220. expect(text).not.toContain("inline Gen UI is unavailable");
  221. expect(text).toContain("### Files & URLs");
  222. expect(text).toContain("### Inline Code Comments");
  223. } finally {
  224. await app?.close?.();
  225. sessionStore.close();
  226. }
  227. });
  228. it("keeps the built-in installed, resets old settings and retains re-enable across discovery", async () => {
  229. const userConfigPath = join(root, "config.json");
  230. await writeFile(
  231. userConfigPath,
  232. JSON.stringify({ plugins: { enabledPlugins: { [VISUALIZE_PLUGIN_ID]: true } } }),
  233. );
  234. const options = { env, includeVisualize: true, userConfigPath, workingDirectory: root };
  235. expect(
  236. (await listZCodeSkills(options)).skills.some(
  237. (skill) => skill.pluginId === VISUALIZE_PLUGIN_ID,
  238. ),
  239. ).toBe(false);
  240. await setZCodePluginEnabled({
  241. ...options,
  242. plugin: VISUALIZE_PLUGIN_ID,
  243. enabled: true,
  244. scope: "user",
  245. });
  246. for (let restart = 0; restart < 2; restart++) {
  247. expect(
  248. (await listZCodeSkills(options)).skills.some(
  249. (skill) => skill.pluginId === VISUALIZE_PLUGIN_ID,
  250. ),
  251. ).toBe(true);
  252. }
  253. expect(JSON.parse(await readFile(userConfigPath, "utf8")).plugins).toMatchObject({
  254. visualizeDefaultOffMigrated: true,
  255. enabledPlugins: { [VISUALIZE_PLUGIN_ID]: true },
  256. });
  257. });
  258. it.each([false, true])(
  259. "keeps protocol draft discovery consistent with enabled=%s",
  260. async (enabled) => {
  261. if (enabled) {
  262. await mkdir(join(root, ".zcode"));
  263. await writeFile(
  264. join(root, ".zcode", "config.json"),
  265. JSON.stringify({
  266. plugins: {
  267. visualizeDefaultOffMigrated: true,
  268. enabledPlugins: { [VISUALIZE_PLUGIN_ID]: true },
  269. },
  270. }),
  271. );
  272. }
  273. const createZCodeApp = vi.fn(() => ({}) as ZCodeApp);
  274. const context = {
  275. deps: { createZCodeApp, env },
  276. sessions: new Map(),
  277. } as unknown as ZCodeProtocolAgentServerContext;
  278. const workspace = { workspacePath: root, workspaceKey: root };
  279. await createWorkspaceZCodeApp(context, workspace, {
  280. providerRuntimeHeadersPort: {} as ZCodeAppOptions["providerRuntimeHeadersPort"],
  281. });
  282. expect(createZCodeApp).toHaveBeenCalledWith(
  283. expect.objectContaining({ includeVisualize: true }),
  284. );
  285. const catalog = await getSkillReferenceCatalog(context, { workspace });
  286. expect(catalog.skills.some((skill) => skill.pluginName === "visualize")).toBe(enabled);
  287. },
  288. );
  289. });