subagentsService.test.ts 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import {
  6. parseSubagentMarkdown,
  7. serializeSubagentMarkdown,
  8. } from "../src/subagents/subagentMarkdown.js";
  9. import {
  10. resolveSubagentStateFile,
  11. resolveUserSubagentRoot,
  12. } from "../src/subagents/subagentStorage.js";
  13. import { createSubagentsService } from "../src/subagents/subagentsService.js";
  14. const tempRoots: string[] = [];
  15. async function makeTempHome(prefix = "zcode-subagents-home-"): Promise<string> {
  16. const home = await mkdtemp(join(tmpdir(), prefix));
  17. tempRoots.push(home);
  18. return home;
  19. }
  20. /** 在临时 HOME 下构造一个内置官方插件缓存目录(无 installed_plugins.json 记录),返回版本根目录。 */
  21. async function writeOfficialPluginFixture(
  22. home: string,
  23. pluginName: string,
  24. version: string,
  25. agentName: string,
  26. frontmatter: { model?: string } = {},
  27. ): Promise<string> {
  28. const root = join(
  29. home,
  30. ".zcode",
  31. "cli",
  32. "plugins",
  33. "cache",
  34. "zcode-plugins-official",
  35. pluginName,
  36. version,
  37. );
  38. await mkdir(join(home, ".zcode", "cli", "plugins"), { recursive: true });
  39. await mkdir(join(root, ".zcode-plugin"), { recursive: true });
  40. await mkdir(join(root, "agents"), { recursive: true });
  41. await writeFile(
  42. join(root, ".zcode-plugin", "plugin.json"),
  43. JSON.stringify({ name: pluginName, version }),
  44. "utf8",
  45. );
  46. await writeFile(
  47. join(root, "agents", `${agentName}.md`),
  48. [
  49. "---",
  50. `name: ${agentName}`,
  51. `description: ${pluginName} ${agentName} @ ${version}`,
  52. ...(frontmatter.model ? [`model: ${frontmatter.model}`] : []),
  53. "---",
  54. `${agentName} prompt ${version}`,
  55. ].join("\n"),
  56. "utf8",
  57. );
  58. return root;
  59. }
  60. afterEach(async () => {
  61. while (tempRoots.length > 0) {
  62. const root = tempRoots.pop();
  63. if (root) {
  64. await rm(root, { recursive: true, force: true });
  65. }
  66. }
  67. });
  68. describe("subagent markdown helpers", () => {
  69. it("lists only direct custom profiles while preserving recursive plugin discovery", async () => {
  70. const home = await makeTempHome();
  71. const workspacePath = join(home, "workspace");
  72. for (const [scope, root] of [
  73. ["user", join(home, ".zcode", "agents")],
  74. ["project", join(workspacePath, ".zcode", "agents")],
  75. ] as const) {
  76. await mkdir(join(root, "nested"), { recursive: true });
  77. for (const nested of [false, true]) {
  78. const name = `${scope}-${nested ? "nested" : "direct"}`;
  79. await writeFile(
  80. join(root, ...(nested ? ["nested"] : []), `${name}.MARKDOWN`),
  81. serializeSubagentMarkdown({ name, description: name, systemPrompt: name }),
  82. );
  83. }
  84. }
  85. const pluginRoot = await writeOfficialPluginFixture(home, "documents", "0.1.4", "direct");
  86. await mkdir(join(pluginRoot, "agents", "nested"));
  87. await writeFile(
  88. join(pluginRoot, "agents", "nested", "deep.md"),
  89. serializeSubagentMarkdown({ name: "deep", description: "Deep", systemPrompt: "Deep" }),
  90. );
  91. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  92. for (const mode of ["settingsUserOnly", "allRuntimeScopes"] as const) {
  93. const result = await service.list({ workspacePath, mode });
  94. expect(
  95. result.agents.filter((agent) => agent.source === "user").map((agent) => agent.name),
  96. ).toEqual(mode === "settingsUserOnly" ? ["user-direct"] : ["user-direct", "project-direct"]);
  97. expect(result.pluginAgents.map((agent) => agent.name).sort()).toEqual([
  98. "documents:deep",
  99. "documents:direct",
  100. ]);
  101. expect(result.pluginAgents.find((agent) => agent.name === "documents:deep")?.path).toBe(
  102. join(pluginRoot, "agents", "nested", "deep.md"),
  103. );
  104. expect(result.diagnostics).toEqual([]);
  105. }
  106. });
  107. it("lists built-in official plugin agents from the official cache without an install record", async () => {
  108. // Bug 根因:discoverPluginAgents 只读 installed_plugins.json,内置官方插件由 CLI seed 到
  109. // cache/zcode-plugins-official 且没有安装记录,documents:visual-judge 在 Settings 永远不可见。
  110. const home = await makeTempHome();
  111. const workspacePath = join(home, "workspace");
  112. const oldRoot = await writeOfficialPluginFixture(home, "documents", "0.1.9", "visual-judge");
  113. const newRoot = await writeOfficialPluginFixture(home, "documents", "0.1.10", "visual-judge");
  114. const invalidRoot = await writeOfficialPluginFixture(home, "documents", "99.0", "visual-judge");
  115. await writeFile(
  116. join(invalidRoot, ".zcode-plugin", "plugin.json"),
  117. JSON.stringify({ name: "wrong" }),
  118. );
  119. await writeOfficialPluginFixture(home, "documents", "99.0.backup-1", "visual-judge");
  120. await mkdir(join(newRoot, "..", "0.1.4.backup-1"), { recursive: true });
  121. await mkdir(join(newRoot, "..", ".seed-lock"), { recursive: true });
  122. // ios-simulator 不在默认启用集合里,且 config 没有显式启用,必须被忽略。
  123. await writeOfficialPluginFixture(home, "ios-simulator", "0.2.0", "simulator-runner");
  124. // browser-use 默认启用,但被用户「卸载」进入 suppressedBuiltins,同样不能贡献 agent。
  125. await writeOfficialPluginFixture(home, "browser-use", "0.5.0", "browser-auditor");
  126. await writeFile(
  127. join(home, ".zcode", "cli", "config.json"),
  128. JSON.stringify({
  129. plugins: {
  130. suppressedBuiltins: ["browser-use@zcode-plugins-official"],
  131. },
  132. }),
  133. "utf8",
  134. );
  135. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  136. const result = await service.list({ workspacePath, provider: "glm" });
  137. expect(result.pluginAgents.map((agent) => agent.name)).toEqual(["documents:visual-judge"]);
  138. expect(result.pluginAgents[0]).toMatchObject({
  139. id: "plugin:documents@zcode-plugins-official:visual-judge",
  140. pluginId: "documents@zcode-plugins-official",
  141. pluginName: "documents",
  142. // 多版本缓存共存时取数字感知最新的版本目录,而不是字典序首项。
  143. path: join(newRoot, "agents", "visual-judge.md"),
  144. scope: "user",
  145. source: "plugin",
  146. });
  147. expect(result.pluginAgents[0]?.path).not.toBe(join(oldRoot, "agents", "visual-judge.md"));
  148. expect(
  149. result.agents.filter((agent) => agent.source === "plugin").map((agent) => agent.name),
  150. ).toEqual(["documents:visual-judge", "visual-judge"]);
  151. await writeFile(
  152. join(home, ".zcode", "cli", "config.json"),
  153. JSON.stringify({
  154. plugins: {
  155. enabledPlugins: { "documents@zcode-plugins-official": false },
  156. suppressedBuiltins: ["browser-use@zcode-plugins-official"],
  157. },
  158. }),
  159. );
  160. expect((await service.list({ workspacePath, provider: "glm" })).pluginAgents).toEqual([]);
  161. });
  162. it("settingsUserOnly 仍返回本地插件资源,不引入运行时别名或项目文件", async () => {
  163. const home = await makeTempHome();
  164. const workspacePath = join(home, "workspace");
  165. await writeOfficialPluginFixture(home, "documents", "0.1.4", "visual-judge");
  166. const projectPath = join(workspacePath, ".zcode", "agents", "project.md");
  167. await mkdir(join(workspacePath, ".zcode", "agents"), { recursive: true });
  168. const projectContent =
  169. "---\nname: project\nmodel: builtin:zai-coding-plan/GLM-5.3\n---\nProject.";
  170. await writeFile(projectPath, projectContent);
  171. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  172. const result = await service.list({ workspacePath, mode: "settingsUserOnly" });
  173. expect(result.pluginAgents.map((agent) => agent.name)).toEqual(["documents:visual-judge"]);
  174. expect(result.pluginAgents[0]?.readOnly).toBe(true);
  175. expect(
  176. result.agents.some((agent) => agent.source === "plugin" || agent.scope === "workspace"),
  177. ).toBe(false);
  178. expect(await readFile(projectPath, "utf8")).toBe(projectContent);
  179. });
  180. it("prefers the install record over the official cache for the same plugin id", async () => {
  181. const home = await makeTempHome();
  182. const workspacePath = join(home, "workspace");
  183. await writeOfficialPluginFixture(home, "documents", "0.1.4", "visual-judge");
  184. const installedRoot = join(home, "installed", "documents");
  185. await mkdir(join(installedRoot, ".zcode-plugin"), { recursive: true });
  186. await mkdir(join(installedRoot, "agents"), { recursive: true });
  187. await writeFile(
  188. join(installedRoot, ".zcode-plugin", "plugin.json"),
  189. JSON.stringify({ name: "documents" }),
  190. "utf8",
  191. );
  192. await writeFile(
  193. join(installedRoot, "agents", "visual-judge.md"),
  194. "---\nname: visual-judge\ndescription: installed visual-judge\n---\ninstalled prompt",
  195. "utf8",
  196. );
  197. await writeFile(
  198. join(home, ".zcode", "cli", "plugins", "installed_plugins.json"),
  199. JSON.stringify({
  200. version: 1,
  201. plugins: [
  202. {
  203. id: "documents@zcode-plugins-official",
  204. name: "documents",
  205. marketplace: "zcode-plugins-official",
  206. version: "9.9.9",
  207. installPath: installedRoot,
  208. scope: "user",
  209. },
  210. ],
  211. }),
  212. "utf8",
  213. );
  214. await writeFile(
  215. join(home, ".zcode", "cli", "config.json"),
  216. JSON.stringify({
  217. plugins: { enabledPlugins: { "documents@zcode-plugins-official": true } },
  218. }),
  219. "utf8",
  220. );
  221. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  222. const result = await service.list({ workspacePath, provider: "glm" });
  223. expect(result.pluginAgents.map((agent) => agent.path)).toEqual([
  224. join(installedRoot, "agents", "visual-judge.md"),
  225. ]);
  226. await writeFile(
  227. join(home, ".zcode", "cli", "config.json"),
  228. JSON.stringify({
  229. plugins: {
  230. enabledPlugins: { "documents@zcode-plugins-official": true },
  231. suppressedBuiltins: ["documents@zcode-plugins-official"],
  232. },
  233. }),
  234. );
  235. expect((await service.list({ workspacePath, provider: "glm" })).pluginAgents).toEqual([]);
  236. await writeFile(
  237. join(home, ".zcode", "cli", "config.json"),
  238. JSON.stringify({
  239. plugins: { enabledPlugins: { "documents@zcode-plugins-official": false } },
  240. }),
  241. );
  242. expect((await service.list({ workspacePath, provider: "glm" })).pluginAgents).toEqual([]);
  243. });
  244. it("插件覆盖按稳定身份原子保存,别名一致,清除后回到未修改的插件默认", async () => {
  245. const home = await makeTempHome();
  246. const pluginRoot = join(home, "installed", "fixture");
  247. const pluginStorage = join(home, ".zcode", "cli", "plugins");
  248. const pluginId = "fixture@personal";
  249. const agentId = "plugin:fixture@personal:visual-judge";
  250. const path = join(pluginRoot, "agents", "visual-judge.md");
  251. await mkdir(join(pluginRoot, "agents"), { recursive: true });
  252. await mkdir(join(pluginRoot, ".zcode-plugin"), { recursive: true });
  253. await mkdir(pluginStorage, { recursive: true });
  254. await writeFile(
  255. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  256. JSON.stringify({ name: "fixture" }),
  257. );
  258. const markdown =
  259. "---\nname: visual-judge\ndescription: visual-judge\nmodel: custom:p:old\nthoughtLevel: low\n---\nKeep prompt";
  260. await writeFile(path, markdown);
  261. await writeFile(
  262. join(pluginStorage, "installed_plugins.json"),
  263. JSON.stringify({
  264. version: 1,
  265. plugins: [{ id: pluginId, name: "fixture", installPath: pluginRoot, scope: "user" }],
  266. }),
  267. );
  268. await writeFile(
  269. join(home, ".zcode", "cli", "config.json"),
  270. JSON.stringify({
  271. plugins: { enabledPlugins: { [pluginId]: true } },
  272. }),
  273. );
  274. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  275. const selection = { providerId: "p", modelId: "new", options: { reasoningLevel: "high" } };
  276. await Promise.all([
  277. service.setPluginAgentModelOverride({ agentId, modelSelection: selection }),
  278. service.setBuiltInModelOverride({ agentName: "Explore", modelSelection: selection }),
  279. service.setEnabled({ agentId: "user:user:disabled", enabled: false }),
  280. ]);
  281. const statePath = await resolveSubagentStateFile({ homeDir: home });
  282. const state = JSON.parse(await readFile(statePath, "utf8"));
  283. expect(state).toMatchObject({
  284. pluginAgentModelSelectionOverrides: { [agentId]: selection },
  285. builtInModelSelectionOverrides: { Explore: selection },
  286. disabledAgentIds: ["user:user:disabled"],
  287. });
  288. expect(state.pluginAgentModelOverrides).toBeUndefined();
  289. const result = await service.list({ workspacePath: join(home, "workspace"), provider: "glm" });
  290. expect(result.pluginAgents[0]).toMatchObject({
  291. modelSelection: selection,
  292. modelSelectionOverride: selection,
  293. defaultModelSelection: {
  294. providerId: "p",
  295. modelId: "old",
  296. options: { reasoningLevel: "low" },
  297. },
  298. });
  299. expect(result.agents.filter((a) => a.source === "plugin").map((a) => a.modelSelection)).toEqual(
  300. [selection, selection],
  301. );
  302. await service.setPluginAgentModelOverride({
  303. agentId,
  304. modelSelection: { providerId: "p", modelId: "no-effort" },
  305. });
  306. const modelOnly = await service.list({
  307. workspacePath: join(home, "workspace"),
  308. provider: "glm",
  309. });
  310. expect(modelOnly.pluginAgents[0]?.modelSelection).toEqual({
  311. providerId: "p",
  312. modelId: "no-effort",
  313. });
  314. await service.setPluginAgentModelOverride({ agentId });
  315. const cleared = await service.list({ workspacePath: join(home, "workspace"), provider: "glm" });
  316. expect(cleared.pluginAgents[0]?.modelSelectionOverride).toBeUndefined();
  317. expect(cleared.pluginAgents[0]?.modelSelection).toEqual({
  318. providerId: "p",
  319. modelId: "old",
  320. options: { reasoningLevel: "low" },
  321. });
  322. expect(
  323. JSON.parse(await readFile(statePath, "utf8")).pluginAgentModelSelectionOverrides,
  324. ).toEqual({});
  325. expect(await readFile(path, "utf8")).toBe(markdown);
  326. });
  327. it("serializes user subagent markdown with runtime profile fields", () => {
  328. const markdown = serializeSubagentMarkdown({
  329. name: "code-reviewer",
  330. description: "提交前审查代码",
  331. systemPrompt: "你是严格的代码审查员。",
  332. color: "cyan",
  333. modelSelection: {
  334. providerId: "provider-a",
  335. modelId: "lite",
  336. options: { reasoningLevel: "high" },
  337. },
  338. tools: ["Read", "Grep", "Bash(git diff *)"],
  339. disallowedTools: ["Write"],
  340. skills: ["code-review"],
  341. permissionMode: "acceptEdits",
  342. maxTurns: 7,
  343. background: true,
  344. injectAgentsMd: false,
  345. });
  346. expect(markdown).toContain('name: "code-reviewer"');
  347. expect(markdown).toContain('description: "提交前审查代码"');
  348. expect(markdown).toContain("tools:");
  349. expect(markdown).toContain("- Read");
  350. expect(markdown).toContain("- Bash(git diff *)");
  351. expect(markdown).toContain("permissionMode: acceptEdits");
  352. expect(markdown).toContain("model: provider-a/lite");
  353. expect(markdown).toContain("thoughtLevel: high");
  354. expect(markdown).not.toContain("modelSelection:");
  355. expect(markdown).toContain("maxTurns: 7");
  356. expect(markdown).toContain("background: true");
  357. expect(markdown).toContain("injectAgentsMd: false");
  358. expect(markdown).toContain("你是严格的代码审查员。");
  359. });
  360. it("parses user subagent markdown into the settings summary shape", () => {
  361. const parsed = parseSubagentMarkdown({
  362. content: `---
  363. name: code-reviewer
  364. description: 提交前审查代码
  365. model: custom:custom-openai:lite
  366. thoughtLevel: high
  367. tools:
  368. - Read
  369. - Bash(git diff *)
  370. disallowedTools:
  371. - Write
  372. skills:
  373. - code-review
  374. permissionMode: acceptEdits
  375. maxTurns: 7
  376. background: true
  377. injectAgentsMd: true
  378. color: cyan
  379. ---
  380. 你是严格的代码审查员。`,
  381. path: "/tmp/code-reviewer.md",
  382. scope: "user",
  383. });
  384. expect(parsed.diagnostic).toBeUndefined();
  385. expect(parsed.agent).toMatchObject({
  386. id: "user:user:code-reviewer",
  387. name: "code-reviewer",
  388. description: "提交前审查代码",
  389. modelSelection: {
  390. providerId: "custom-openai",
  391. modelId: "lite",
  392. options: { reasoningLevel: "high" },
  393. },
  394. tools: ["Read", "Bash(git diff *)"],
  395. disallowedTools: ["Write"],
  396. skills: ["code-review"],
  397. permissionMode: "acceptEdits",
  398. maxTurns: 7,
  399. background: true,
  400. injectAgentsMd: true,
  401. color: "cyan",
  402. enabled: true,
  403. readOnly: false,
  404. systemPrompt: "你是严格的代码审查员。",
  405. });
  406. });
  407. it("preserves concrete model select values from subagent markdown", () => {
  408. const markdown = serializeSubagentMarkdown({
  409. name: "custom-model-reviewer",
  410. description: "Use selected model",
  411. systemPrompt: "Review carefully.",
  412. modelSelection: {
  413. providerId: "custom-openai",
  414. modelId: "gpt-5.4",
  415. options: { reasoningLevel: "high" },
  416. },
  417. });
  418. const parsed = parseSubagentMarkdown({
  419. content: markdown,
  420. path: "/tmp/custom-model-reviewer.md",
  421. scope: "user",
  422. });
  423. expect(markdown).toContain("model: custom-openai/gpt-5.4");
  424. expect(parsed.agent?.modelSelection).toEqual({
  425. providerId: "custom-openai",
  426. modelId: "gpt-5.4",
  427. options: { reasoningLevel: "high" },
  428. });
  429. });
  430. it.each([true, false])(
  431. "round-trips injectAgentsMd=%s through subagent markdown",
  432. (injectAgentsMd) => {
  433. const markdown = serializeSubagentMarkdown({
  434. name: "instruction-aware-reviewer",
  435. description: "Controls AGENTS.md injection",
  436. systemPrompt: "Review carefully.",
  437. injectAgentsMd,
  438. });
  439. const parsed = parseSubagentMarkdown({
  440. content: markdown,
  441. path: "/tmp/instruction-aware-reviewer.md",
  442. scope: "user",
  443. });
  444. expect(parsed.agent?.injectAgentsMd).toBe(injectAgentsMd);
  445. },
  446. );
  447. it("keeps missing injectAgentsMd unset for legacy markdown", () => {
  448. const parsed = parseSubagentMarkdown({
  449. content: `---
  450. name: legacy-reviewer
  451. description: Legacy profile
  452. ---
  453. Review carefully.`,
  454. path: "/tmp/legacy-reviewer.md",
  455. scope: "user",
  456. });
  457. expect(parsed.agent?.injectAgentsMd).toBeUndefined();
  458. });
  459. it("parses runtime-compatible loose frontmatter that is not strict YAML", () => {
  460. const parsed = parseSubagentMarkdown({
  461. content: `---
  462. name: reviewer
  463. description: foo: bar
  464. tools:
  465. - Read
  466. - Bash(git commit -m foo: bar)
  467. ---
  468. prompt`,
  469. path: "/tmp/reviewer.md",
  470. scope: "user",
  471. });
  472. expect(parsed.diagnostic).toBeUndefined();
  473. expect(parsed.agent).toMatchObject({
  474. name: "reviewer",
  475. description: "foo: bar",
  476. tools: ["Read", "Bash(git commit -m foo: bar)"],
  477. });
  478. });
  479. it("round-trips structured mcpServers entries through markdown serialization", () => {
  480. const mcpServers = [
  481. {
  482. name: "github",
  483. command: "gh",
  484. args: ["repo", "view"],
  485. env: {
  486. GITHUB_TOKEN: "${GITHUB_TOKEN}",
  487. },
  488. },
  489. {
  490. name: "linear",
  491. type: "sse",
  492. url: "https://mcp.linear.app/sse",
  493. },
  494. ];
  495. const markdown = serializeSubagentMarkdown({
  496. name: "mcp-reviewer",
  497. description: "checks changes with MCP context",
  498. systemPrompt: "Use MCP context when available.",
  499. mcpServers,
  500. });
  501. const parsed = parseSubagentMarkdown({
  502. content: markdown,
  503. path: "/tmp/mcp-reviewer.md",
  504. scope: "user",
  505. });
  506. expect(parsed.diagnostic).toBeUndefined();
  507. expect(parsed.agent?.mcpServers).toEqual(mcpServers);
  508. });
  509. });
  510. describe("subagent storage roots", () => {
  511. it("uses runtime storage.dir agents root for user subagents", async () => {
  512. const home = await makeTempHome();
  513. const storageRoot = join(home, "custom-storage");
  514. await mkdir(join(home, ".zcode", "cli"), { recursive: true });
  515. await writeFile(
  516. join(home, ".zcode", "cli", "config.json"),
  517. JSON.stringify({ storage: { dir: storageRoot } }),
  518. "utf8",
  519. );
  520. await expect(resolveUserSubagentRoot({ homeDir: home })).resolves.toBe(
  521. join(storageRoot, "agents"),
  522. );
  523. await expect(resolveSubagentStateFile({ homeDir: home })).resolves.toBe(
  524. join(storageRoot, "v2", "agents-state.json"),
  525. );
  526. });
  527. });
  528. describe("createSubagentsService", () => {
  529. it("用户 Markdown 先原地迁移后正式读取,项目文件和中间格式不自动迁", async () => {
  530. const home = await makeTempHome();
  531. const userRoot = await resolveUserSubagentRoot({ homeDir: home });
  532. const workspacePath = join(home, "workspace");
  533. const projectRoot = join(workspacePath, ".zcode", "agents");
  534. await mkdir(userRoot, { recursive: true });
  535. await mkdir(projectRoot, { recursive: true });
  536. const content =
  537. "---\nname: helper\ndescription: review\nmodel: builtin:zai-coding-plan/m\nthoughtLevel: high\n# comment\nextra: user-data\n---\n正文 builtin:zai-coding-plan/m\n";
  538. const userFile = join(userRoot, "helper.md");
  539. const projectFile = join(projectRoot, "project.md");
  540. await writeFile(userFile, content);
  541. await writeFile(projectFile, content.replace("name: helper", "name: project-helper"));
  542. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  543. const result = await service.list({ workspacePath });
  544. expect(result.agents.find((agent) => agent.name === "helper")?.modelSelection?.providerId).toBe(
  545. "account:zai-individual-coding-plan",
  546. );
  547. expect(
  548. result.agents.find((agent) => agent.name === "project-helper")?.modelSelection?.providerId,
  549. ).toBe("builtin:zai-coding-plan");
  550. expect(await readFile(userFile, "utf8")).toBe(
  551. content.replace(
  552. "model: builtin:zai-coding-plan",
  553. "model: account:zai-individual-coding-plan",
  554. ),
  555. );
  556. expect(await readFile(projectFile, "utf8")).toBe(
  557. content.replace("name: helper", "name: project-helper"),
  558. );
  559. expect(
  560. (
  561. await createSubagentsService({ homeDir: home, isDesktopRuntime: true }).list({
  562. workspacePath,
  563. })
  564. ).agents.find((agent) => agent.name === "helper")?.modelSelection,
  565. ).toEqual(result.agents.find((agent) => agent.name === "helper")?.modelSelection);
  566. });
  567. it("损坏的 Subagent state 不阻塞整个会话启动,也不覆盖原文件", async () => {
  568. const home = await makeTempHome();
  569. const path = await resolveSubagentStateFile({ homeDir: home });
  570. await mkdir(join(home, ".zcode", "v2"), { recursive: true });
  571. const original = '{"builtInModelOverrides":';
  572. await writeFile(path, original);
  573. await expect(
  574. createSubagentsService({ homeDir: home }).prepareRuntimeState(),
  575. ).resolves.toBeUndefined();
  576. expect(await readFile(path, "utf8")).toBe(original);
  577. });
  578. it("启动准备将旧内置选择落盘,让独立 Agent loader 不必等待用户编辑", async () => {
  579. const home = await makeTempHome();
  580. const statePath = await resolveSubagentStateFile({ homeDir: home });
  581. await mkdir(join(home, ".zcode", "v2"), { recursive: true });
  582. const legacy = {
  583. builtInModelOverrides: { Explore: "custom:builtin%3Azai-coding-plan:GLM-5.3-Flash" },
  584. builtInThoughtLevelOverrides: { Explore: "high" },
  585. disabledAgentIds: ["disabled-profile"],
  586. };
  587. await writeFile(statePath, JSON.stringify(legacy));
  588. const service = createSubagentsService({
  589. homeDir: home,
  590. });
  591. await service.prepareRuntimeState();
  592. const saved = JSON.parse(await readFile(statePath, "utf8"));
  593. expect(saved).toMatchObject(legacy);
  594. expect(saved.builtInModelSelectionOverrides.Explore).toEqual({
  595. providerId: "account:zai-individual-coding-plan",
  596. modelId: "GLM-5.3-Flash",
  597. options: { reasoningLevel: "high" },
  598. });
  599. await service.setBuiltInModelOverride({ agentName: "Explore", modelSelection: undefined });
  600. await service.prepareRuntimeState();
  601. expect(JSON.parse(await readFile(statePath, "utf8")).builtInModelSelectionOverrides).toEqual(
  602. {},
  603. );
  604. });
  605. it("并发启动导入与新版手动清空,写队列保留用户结果", async () => {
  606. const home = await makeTempHome();
  607. const statePath = await resolveSubagentStateFile({ homeDir: home });
  608. await mkdir(join(home, ".zcode", "v2"), { recursive: true });
  609. await writeFile(
  610. statePath,
  611. JSON.stringify({ builtInModelOverrides: { Explore: "custom:builtin%3Azai-coding-plan:m" } }),
  612. );
  613. const service = createSubagentsService({ homeDir: home });
  614. await Promise.all([
  615. service.prepareRuntimeState(),
  616. service.setBuiltInModelOverride({ agentName: "Explore", modelSelection: undefined }),
  617. ]);
  618. await service.prepareRuntimeState();
  619. expect(JSON.parse(await readFile(statePath, "utf8")).builtInModelSelectionOverrides).toEqual(
  620. {},
  621. );
  622. });
  623. it("旧内置模型覆盖导入并随正常保存固定;旧字段仅保留供回滚", async () => {
  624. const home = await makeTempHome();
  625. const statePath = await resolveSubagentStateFile({ homeDir: home });
  626. await mkdir(join(home, ".zcode", "v2"), { recursive: true });
  627. const legacy = {
  628. builtInModelOverrides: { Explore: "custom:builtin%3Azai-coding-plan:GLM-5.3-Flash" },
  629. builtInThoughtLevelOverrides: { Explore: "high" },
  630. disabledAgentIds: [],
  631. };
  632. await writeFile(statePath, JSON.stringify(legacy));
  633. const service = createSubagentsService({
  634. homeDir: home,
  635. isDesktopRuntime: true,
  636. });
  637. const params = { workspacePath: join(home, "workspace"), mode: "settingsUserOnly" as const };
  638. const listed = await service.list(params);
  639. const explore = listed.agents.find((agent) => agent.name === "Explore")!;
  640. expect(explore.modelSelection).toEqual({
  641. providerId: "account:zai-individual-coding-plan",
  642. modelId: "GLM-5.3-Flash",
  643. options: { reasoningLevel: "high" },
  644. });
  645. await service.setEnabled({ agentId: explore.id, enabled: false });
  646. const saved = JSON.parse(await readFile(statePath, "utf8"));
  647. expect(saved).toMatchObject({
  648. builtInModelOverrides: legacy.builtInModelOverrides,
  649. builtInThoughtLevelOverrides: legacy.builtInThoughtLevelOverrides,
  650. });
  651. expect(saved.builtInModelSelectionOverrides.Explore).toEqual(explore.modelSelection);
  652. await service.setBuiltInModelOverride({ agentName: "Explore", modelSelection: undefined });
  653. expect(
  654. (await service.list(params)).agents.find((agent) => agent.name === "Explore")?.modelSelection,
  655. ).toBeUndefined();
  656. });
  657. it("persists model overrides for built-in subagents without making them editable", async () => {
  658. const home = await makeTempHome();
  659. const workspacePath = join(home, "workspace");
  660. const service = createSubagentsService({
  661. homeDir: home,
  662. isDesktopRuntime: true,
  663. });
  664. await service.setBuiltInModelOverride({
  665. agentName: "general-purpose",
  666. modelSelection: {
  667. providerId: "custom-openai",
  668. modelId: "gpt-5.4",
  669. options: { reasoningLevel: "high" },
  670. },
  671. });
  672. await service.setBuiltInModelOverride({
  673. agentName: "Explore",
  674. modelSelection: {
  675. providerId: "custom-openai",
  676. modelId: "glm-5.2",
  677. options: { reasoningLevel: "max" },
  678. },
  679. });
  680. const result = await service.list({
  681. workspacePath,
  682. provider: "glm",
  683. mode: "settingsUserOnly",
  684. });
  685. const state = JSON.parse(
  686. await readFile(await resolveSubagentStateFile({ homeDir: home }), "utf8"),
  687. ) as {
  688. builtInModelSelectionOverrides: Record<string, unknown>;
  689. disabledAgentIds: string[];
  690. };
  691. expect(result.agents.find((agent) => agent.name === "general-purpose")).toMatchObject({
  692. modelSelection: {
  693. providerId: "custom-openai",
  694. modelId: "gpt-5.4",
  695. options: { reasoningLevel: "high" },
  696. },
  697. modelSelectionOverride: {
  698. providerId: "custom-openai",
  699. modelId: "gpt-5.4",
  700. options: { reasoningLevel: "high" },
  701. },
  702. readOnly: true,
  703. });
  704. expect(result.agents.find((agent) => agent.name === "Explore")).toMatchObject({
  705. modelSelection: {
  706. providerId: "custom-openai",
  707. modelId: "glm-5.2",
  708. options: { reasoningLevel: "max" },
  709. },
  710. modelSelectionOverride: {
  711. providerId: "custom-openai",
  712. modelId: "glm-5.2",
  713. options: { reasoningLevel: "max" },
  714. },
  715. readOnly: true,
  716. });
  717. expect(state.builtInModelSelectionOverrides).toEqual({
  718. Explore: {
  719. providerId: "custom-openai",
  720. modelId: "glm-5.2",
  721. options: { reasoningLevel: "max" },
  722. },
  723. "general-purpose": {
  724. providerId: "custom-openai",
  725. modelId: "gpt-5.4",
  726. options: { reasoningLevel: "high" },
  727. },
  728. });
  729. });
  730. it("clears a built-in subagent model override and restores inheritance", async () => {
  731. const home = await makeTempHome();
  732. const workspacePath = join(home, "workspace");
  733. const service = createSubagentsService({
  734. homeDir: home,
  735. isDesktopRuntime: true,
  736. });
  737. await service.setBuiltInModelOverride({
  738. agentName: "Explore",
  739. modelSelection: {
  740. providerId: "custom-openai",
  741. modelId: "glm-5.2",
  742. options: { reasoningLevel: "max" },
  743. },
  744. });
  745. await service.setBuiltInModelOverride({
  746. agentName: "Explore",
  747. modelSelection: undefined,
  748. });
  749. const result = await service.list({
  750. workspacePath,
  751. provider: "glm",
  752. mode: "settingsUserOnly",
  753. });
  754. expect(result.agents.find((agent) => agent.name === "Explore")).toMatchObject({
  755. modelSelection: undefined,
  756. modelSelectionOverride: undefined,
  757. readOnly: true,
  758. });
  759. const state = JSON.parse(
  760. await readFile(await resolveSubagentStateFile({ homeDir: home }), "utf8"),
  761. ) as {
  762. builtInModelSelectionOverrides: Record<string, unknown>;
  763. };
  764. expect(state.builtInModelSelectionOverrides).toEqual({});
  765. });
  766. it("settings user-only list hides workspace agents but keeps built-ins and user agents", async () => {
  767. const home = await makeTempHome();
  768. const workspacePath = join(home, "workspace");
  769. await mkdir(join(home, ".zcode", "agents"), { recursive: true });
  770. await mkdir(join(workspacePath, ".zcode", "agents"), { recursive: true });
  771. await writeFile(
  772. join(home, ".zcode", "agents", "code-reviewer.md"),
  773. serializeSubagentMarkdown({
  774. name: "code-reviewer",
  775. description: "提交前审查代码",
  776. systemPrompt: "你是严格的代码审查员。",
  777. }),
  778. "utf8",
  779. );
  780. await writeFile(
  781. join(workspacePath, ".zcode", "agents", "workspace-reviewer.md"),
  782. serializeSubagentMarkdown({
  783. name: "workspace-reviewer",
  784. description: "工作区审查",
  785. systemPrompt: "workspace prompt",
  786. }),
  787. "utf8",
  788. );
  789. const service = createSubagentsService({
  790. homeDir: home,
  791. isDesktopRuntime: true,
  792. });
  793. const result = await service.list({
  794. workspacePath,
  795. provider: "glm",
  796. mode: "settingsUserOnly",
  797. });
  798. expect(result.agents.map((agent) => agent.name)).toEqual([
  799. "general-purpose",
  800. "Explore",
  801. "code-reviewer",
  802. ]);
  803. expect(result.agents.every((agent) => agent.scope !== "workspace")).toBe(true);
  804. // Bugfix 回归:workspace profile 曾被 parser 标为 readOnly,于是在设置页既不可编辑
  805. // 也不可删除,还被归入“内置”分组。只有内置 agent 才是真正只读的。
  806. const allScopes = await service.list({
  807. workspacePath,
  808. provider: "glm",
  809. });
  810. expect(allScopes.agents.find((agent) => agent.name === "workspace-reviewer")).toMatchObject({
  811. scope: "workspace",
  812. source: "user",
  813. readOnly: false,
  814. });
  815. expect(result.agents.find((agent) => agent.name === "general-purpose")?.readOnly).toBe(true);
  816. expect(result.agents.find((agent) => agent.name === "general-purpose")?.color).toBe("blue");
  817. expect(result.agents.find((agent) => agent.name === "Explore")?.color).toBe("cyan");
  818. expect(result.agents.find((agent) => agent.name === "code-reviewer")?.readOnly).toBe(false);
  819. });
  820. it("lists enabled plugin agents from installed plugin cache", async () => {
  821. const home = await makeTempHome();
  822. const workspacePath = join(home, "workspace");
  823. const pluginRoot = join(
  824. home,
  825. ".zcode",
  826. "cli",
  827. "plugins",
  828. "cache",
  829. "claude-plugins-official",
  830. "feature-dev",
  831. "0.0.0",
  832. );
  833. await mkdir(join(home, ".zcode", "cli", "plugins"), { recursive: true });
  834. await mkdir(join(pluginRoot, ".claude-plugin"), { recursive: true });
  835. await mkdir(join(pluginRoot, "agents"), { recursive: true });
  836. await writeFile(
  837. join(home, ".zcode", "cli", "config.json"),
  838. JSON.stringify({
  839. plugins: {
  840. enabledPlugins: {
  841. "feature-dev@claude-plugins-official": true,
  842. },
  843. },
  844. }),
  845. "utf8",
  846. );
  847. await writeFile(
  848. join(home, ".zcode", "cli", "plugins", "installed_plugins.json"),
  849. JSON.stringify({
  850. version: 1,
  851. plugins: [
  852. {
  853. id: "feature-dev@claude-plugins-official",
  854. name: "feature-dev",
  855. marketplace: "claude-plugins-official",
  856. version: "0.0.0",
  857. installPath: pluginRoot,
  858. installedAt: "2026-06-27T00:00:00.000Z",
  859. scope: "user",
  860. },
  861. ],
  862. }),
  863. "utf8",
  864. );
  865. await writeFile(
  866. join(pluginRoot, ".claude-plugin", "plugin.json"),
  867. JSON.stringify({ name: "feature-dev", description: "Feature workflow" }),
  868. "utf8",
  869. );
  870. await writeFile(
  871. join(pluginRoot, "agents", "code-architect.md"),
  872. `---
  873. name: code-architect
  874. description: 设计功能架构
  875. tools:
  876. - Read
  877. ---
  878. 架构 prompt`,
  879. "utf8",
  880. );
  881. const service = createSubagentsService({
  882. homeDir: home,
  883. isDesktopRuntime: true,
  884. });
  885. const result = await service.list({ workspacePath, provider: "glm" });
  886. expect(
  887. result.agents.filter((agent) => agent.source === "plugin").map((agent) => agent.name),
  888. ).toEqual(["code-architect", "feature-dev:code-architect"]);
  889. expect(result.pluginAgents.map((agent) => agent.name)).toEqual(["feature-dev:code-architect"]);
  890. expect(new Set(result.pluginAgents.map((agent) => agent.path))).toEqual(
  891. new Set([join(pluginRoot, "agents", "code-architect.md")]),
  892. );
  893. expect(result.pluginAgents.every((agent) => agent.source === "plugin")).toBe(true);
  894. expect(result.pluginAgents.every((agent) => agent.readOnly)).toBe(true);
  895. });
  896. it("lists built-in official plugin agents from the official cache without an install record", async () => {
  897. // Bug 根因:discoverPluginAgents 只读 installed_plugins.json,内置官方插件由 CLI seed 到
  898. // cache/zcode-plugins-official 且没有安装记录,documents:visual-judge 在 Settings 永远不可见。
  899. const home = await makeTempHome();
  900. const workspacePath = join(home, "workspace");
  901. const oldRoot = await writeOfficialPluginFixture(home, "documents", "0.1.2", "visual-judge");
  902. const newRoot = await writeOfficialPluginFixture(home, "documents", "0.1.4", "visual-judge");
  903. await mkdir(join(newRoot, "..", "0.1.4.backup-1"), { recursive: true });
  904. await mkdir(join(newRoot, "..", ".seed-lock"), { recursive: true });
  905. // ios-simulator 不在默认启用集合里,且 config 没有显式启用,必须被忽略。
  906. await writeOfficialPluginFixture(home, "ios-simulator", "0.2.0", "simulator-runner");
  907. // browser-use 默认启用,但被用户「卸载」进入 suppressedBuiltins,同样不能贡献 agent。
  908. await writeOfficialPluginFixture(home, "browser-use", "0.5.0", "browser-auditor");
  909. await writeFile(
  910. join(home, ".zcode", "cli", "config.json"),
  911. JSON.stringify({
  912. plugins: {
  913. suppressedBuiltins: ["browser-use@zcode-plugins-official"],
  914. },
  915. }),
  916. "utf8",
  917. );
  918. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  919. const result = await service.list({ workspacePath, provider: "glm" });
  920. expect(result.pluginAgents.map((agent) => agent.name)).toEqual(["documents:visual-judge"]);
  921. expect(result.pluginAgents[0]).toMatchObject({
  922. id: "plugin:documents@zcode-plugins-official:visual-judge",
  923. pluginId: "documents@zcode-plugins-official",
  924. pluginName: "documents",
  925. // 多版本缓存共存时取数字感知最新的版本目录,而不是字典序首项。
  926. path: join(newRoot, "agents", "visual-judge.md"),
  927. scope: "user",
  928. source: "plugin",
  929. });
  930. expect(result.pluginAgents[0]?.path).not.toBe(join(oldRoot, "agents", "visual-judge.md"));
  931. expect(
  932. result.agents.filter((agent) => agent.source === "plugin").map((agent) => agent.name),
  933. ).toEqual(["documents:visual-judge", "visual-judge"]);
  934. });
  935. it("prefers the install record over the official cache for the same plugin id", async () => {
  936. const home = await makeTempHome();
  937. const workspacePath = join(home, "workspace");
  938. await writeOfficialPluginFixture(home, "documents", "0.1.4", "visual-judge");
  939. const installedRoot = join(home, "installed", "documents");
  940. await mkdir(join(installedRoot, ".zcode-plugin"), { recursive: true });
  941. await mkdir(join(installedRoot, "agents"), { recursive: true });
  942. await writeFile(
  943. join(installedRoot, ".zcode-plugin", "plugin.json"),
  944. JSON.stringify({ name: "documents" }),
  945. "utf8",
  946. );
  947. await writeFile(
  948. join(installedRoot, "agents", "visual-judge.md"),
  949. "---\nname: visual-judge\ndescription: installed visual-judge\n---\ninstalled prompt",
  950. "utf8",
  951. );
  952. await writeFile(
  953. join(home, ".zcode", "cli", "plugins", "installed_plugins.json"),
  954. JSON.stringify({
  955. version: 1,
  956. plugins: [
  957. {
  958. id: "documents@zcode-plugins-official",
  959. name: "documents",
  960. marketplace: "zcode-plugins-official",
  961. version: "9.9.9",
  962. installPath: installedRoot,
  963. scope: "user",
  964. },
  965. ],
  966. }),
  967. "utf8",
  968. );
  969. await writeFile(
  970. join(home, ".zcode", "cli", "config.json"),
  971. JSON.stringify({
  972. plugins: { enabledPlugins: { "documents@zcode-plugins-official": true } },
  973. }),
  974. "utf8",
  975. );
  976. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  977. const result = await service.list({ workspacePath, provider: "glm" });
  978. expect(result.pluginAgents.map((agent) => agent.path)).toEqual([
  979. join(installedRoot, "agents", "visual-judge.md"),
  980. ]);
  981. });
  982. it("persists plugin agent model overrides by agent id and echoes them in list", async () => {
  983. const home = await makeTempHome();
  984. const workspacePath = join(home, "workspace");
  985. const pluginRoot = await writeOfficialPluginFixture(home, "documents", "0.1.4", "visual-judge", {
  986. model: "custom:custom-openai:gpt-5.4",
  987. });
  988. const agentId = "plugin:documents@zcode-plugins-official:visual-judge";
  989. const service = createSubagentsService({ homeDir: home, isDesktopRuntime: true });
  990. const before = await service.list({ workspacePath, provider: "glm" });
  991. expect(before.pluginAgents[0]).toMatchObject({
  992. defaultModelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  993. modelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  994. path: join(pluginRoot, "agents", "visual-judge.md"),
  995. });
  996. expect(before.pluginAgents[0]?.modelSelectionOverride).toBeUndefined();
  997. const selection = {
  998. providerId: "custom-openai",
  999. modelId: "glm-5.2",
  1000. options: { reasoningLevel: "high" },
  1001. };
  1002. await service.setPluginAgentModelOverride({
  1003. agentId,
  1004. modelSelection: selection,
  1005. });
  1006. const stateFile = await resolveSubagentStateFile({ homeDir: home });
  1007. expect(JSON.parse(await readFile(stateFile, "utf8"))).toMatchObject({
  1008. pluginAgentModelSelectionOverrides: { [agentId]: selection },
  1009. });
  1010. const overridden = await service.list({ workspacePath, provider: "glm" });
  1011. expect(overridden.pluginAgents[0]).toMatchObject({
  1012. defaultModelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  1013. modelSelection: selection,
  1014. modelSelectionOverride: selection,
  1015. });
  1016. // 运行时投影(规范名 + 裸名别名)与设置页资源投影必须回显同一覆盖,否则 @ 提及与设置页不一致。
  1017. expect(
  1018. overridden.agents.filter((agent) => agent.source === "plugin").map((agent) => agent.modelSelection),
  1019. ).toEqual([selection, selection]);
  1020. // 清除完整选择时一并清掉档位,回落到 md 声明;不恢复旧双 map 保存入口。
  1021. await service.setPluginAgentModelOverride({ agentId });
  1022. const cleared = await service.list({ workspacePath, provider: "glm" });
  1023. expect(cleared.pluginAgents[0]).toMatchObject({
  1024. modelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  1025. });
  1026. expect(cleared.pluginAgents[0]?.modelSelectionOverride).toBeUndefined();
  1027. expect(JSON.parse(await readFile(stateFile, "utf8"))).toMatchObject({
  1028. pluginAgentModelSelectionOverrides: {},
  1029. });
  1030. });
  1031. it("creates user agents in the runtime-consumed user agents root", async () => {
  1032. const home = await makeTempHome();
  1033. const service = createSubagentsService({
  1034. homeDir: home,
  1035. isDesktopRuntime: true,
  1036. });
  1037. const result = await service.createAgent({
  1038. provider: "glm",
  1039. config: {
  1040. name: "code-reviewer",
  1041. description: "提交前审查代码",
  1042. systemPrompt: "你是严格的代码审查员。",
  1043. tools: ["Read", "Grep"],
  1044. },
  1045. });
  1046. expect(result.agent.path).toBe(join(home, ".zcode", "agents", "code-reviewer.md"));
  1047. await expect(readFile(result.agent.path, "utf8")).resolves.toContain("你是严格的代码审查员。");
  1048. });
  1049. it("creates and updates workspace agents in the selected workspace root", async () => {
  1050. const home = await makeTempHome();
  1051. const workspacePath = join(home, "workspace");
  1052. const service = createSubagentsService({
  1053. homeDir: home,
  1054. isDesktopRuntime: true,
  1055. });
  1056. const created = await service.createAgent({
  1057. provider: "glm",
  1058. scope: "workspace",
  1059. workspacePath,
  1060. workspaceIdentity: "ssh://dev/workspace",
  1061. config: {
  1062. name: "workspace-reviewer",
  1063. description: "reviews this workspace",
  1064. systemPrompt: "Review workspace changes.",
  1065. },
  1066. });
  1067. expect(created.agent).toMatchObject({
  1068. scope: "workspace",
  1069. projectPath: workspacePath,
  1070. path: join(workspacePath, ".zcode", "agents", "workspace-reviewer.md"),
  1071. });
  1072. const updated = await service.updateAgent({
  1073. agentId: created.agent.id,
  1074. oldFilePath: created.agent.path,
  1075. provider: "glm",
  1076. scope: "workspace",
  1077. workspacePath,
  1078. workspaceIdentity: "ssh://dev/workspace",
  1079. config: {
  1080. name: "workspace-reviewer-v2",
  1081. description: "reviews this workspace",
  1082. systemPrompt: "Review workspace changes carefully.",
  1083. },
  1084. });
  1085. expect(updated.agent.scope).toBe("workspace");
  1086. expect(updated.agent.path).toBe(
  1087. join(workspacePath, ".zcode", "agents", "workspace-reviewer-v2.md"),
  1088. );
  1089. await expect(readFile(updated.agent.path, "utf8")).resolves.toContain(
  1090. "Review workspace changes carefully.",
  1091. );
  1092. });
  1093. it("removes a custom thoughtLevel when the updated config omits it", async () => {
  1094. const home = await makeTempHome();
  1095. const service = createSubagentsService({
  1096. homeDir: home,
  1097. isDesktopRuntime: true,
  1098. });
  1099. const created = await service.createAgent({
  1100. provider: "glm",
  1101. config: {
  1102. name: "effort-reviewer",
  1103. description: "Review with explicit effort",
  1104. systemPrompt: "Review carefully.",
  1105. modelSelection: {
  1106. providerId: "custom-openai",
  1107. modelId: "gpt-5.4",
  1108. options: { reasoningLevel: "high" },
  1109. },
  1110. },
  1111. });
  1112. await service.updateAgent({
  1113. agentId: created.agent.id,
  1114. oldFilePath: created.agent.path,
  1115. provider: "glm",
  1116. config: {
  1117. name: "effort-reviewer",
  1118. description: "Review with model default effort",
  1119. systemPrompt: "Review carefully.",
  1120. modelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  1121. },
  1122. });
  1123. const markdown = await readFile(created.agent.path, "utf8");
  1124. expect(markdown).toContain("model: custom-openai/gpt-5.4");
  1125. expect(markdown).not.toContain("thoughtLevel:");
  1126. });
  1127. it("creates agents with wildcard and colon tool patterns as valid markdown", async () => {
  1128. const home = await makeTempHome();
  1129. const service = createSubagentsService({
  1130. homeDir: home,
  1131. isDesktopRuntime: true,
  1132. });
  1133. const result = await service.createAgent({
  1134. provider: "glm",
  1135. config: {
  1136. name: "wildcard-runner",
  1137. description: "runs broad tools",
  1138. systemPrompt: "Use the selected tools.",
  1139. tools: ["*", "Bash(git commit -m foo: bar)"],
  1140. },
  1141. });
  1142. expect(result.agent.tools).toEqual(["*", "Bash(git commit -m foo: bar)"]);
  1143. const raw = await readFile(result.agent.path, "utf8");
  1144. expect(raw).toContain(' - "*"');
  1145. expect(raw).toContain(' - "Bash(git commit -m foo: bar)"');
  1146. expect(
  1147. parseSubagentMarkdown({
  1148. content: raw,
  1149. path: result.agent.path,
  1150. scope: "user",
  1151. }).diagnostic,
  1152. ).toBeUndefined();
  1153. });
  1154. it("preserves disabled state when a user agent is renamed", async () => {
  1155. const home = await makeTempHome();
  1156. const service = createSubagentsService({
  1157. homeDir: home,
  1158. isDesktopRuntime: true,
  1159. });
  1160. const created = await service.createAgent({
  1161. provider: "glm",
  1162. config: {
  1163. name: "code-reviewer",
  1164. description: "reviews code",
  1165. systemPrompt: "Review the code.",
  1166. },
  1167. });
  1168. await service.setEnabled({
  1169. agentId: created.agent.id,
  1170. enabled: false,
  1171. });
  1172. await service.setBuiltInModelOverride({
  1173. agentName: "Explore",
  1174. modelSelection: { providerId: "custom-openai", modelId: "glm-5.2" },
  1175. });
  1176. const renamed = await service.updateAgent({
  1177. agentId: created.agent.id,
  1178. oldFilePath: created.agent.path,
  1179. provider: "glm",
  1180. config: {
  1181. name: "code-reviewer-v2",
  1182. description: "reviews code",
  1183. systemPrompt: "Review the code.",
  1184. },
  1185. });
  1186. const listed = await service.list({
  1187. workspacePath: join(home, "workspace"),
  1188. provider: "glm",
  1189. mode: "settingsUserOnly",
  1190. });
  1191. const state = JSON.parse(
  1192. await readFile(await resolveSubagentStateFile({ homeDir: home }), "utf8"),
  1193. ) as {
  1194. builtInModelSelectionOverrides: Record<string, unknown>;
  1195. disabledAgentIds: string[];
  1196. };
  1197. expect(listed.agents.find((agent) => agent.name === "code-reviewer-v2")?.enabled).toBe(false);
  1198. expect(state.builtInModelSelectionOverrides).toEqual({
  1199. Explore: { providerId: "custom-openai", modelId: "glm-5.2" },
  1200. });
  1201. expect(state.disabledAgentIds).toContain(renamed.agent.id);
  1202. expect(state.disabledAgentIds).not.toContain(created.agent.id);
  1203. });
  1204. });