subagentsService.test.ts 42 KB

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