subagentRuntimeConfigWatcher.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import {
  2. mkdtemp,
  3. rm,
  4. mkdir,
  5. writeFile,
  6. rename,
  7. readFile,
  8. chmod,
  9. symlink,
  10. stat,
  11. } from "node:fs/promises";
  12. import { tmpdir } from "node:os";
  13. import { join } from "node:path";
  14. import { setTimeout as delay } from "node:timers/promises";
  15. import { afterEach, describe, expect, it, vi } from "vitest";
  16. import { createSubagentsService } from "../src/subagents/subagentsService.js";
  17. // 仅观察真实补扫的 stat 次数,以实际进入稳定等待作为时序证据。
  18. vi.mock("node:fs/promises", async (importOriginal) => {
  19. const actual = await importOriginal<typeof import("node:fs/promises")>();
  20. return { ...actual, stat: vi.fn(actual.stat) };
  21. });
  22. const cleanup: Array<() => void | Promise<void>> = [];
  23. afterEach(async () => {
  24. for (const dispose of cleanup.splice(0).reverse()) await dispose();
  25. vi.mocked(stat).mockClear();
  26. });
  27. const until = (assertion: () => unknown) => vi.waitFor(assertion, { timeout: 8000, interval: 20 });
  28. async function pair(prepareHome?: (homeDir: string) => Promise<void>) {
  29. const homeDir = await mkdtemp(join(tmpdir(), "subagent-host-watch-"));
  30. cleanup.push(() => rm(homeDir, { recursive: true, force: true }));
  31. await prepareHome?.(homeDir);
  32. const a = createSubagentsService({ homeDir }),
  33. b = createSubagentsService({ homeDir });
  34. cleanup.push(
  35. () => a.disposeAll(),
  36. () => b.disposeAll(),
  37. );
  38. const workspace = { workspacePath: join(homeDir, "workspace") };
  39. await a.prepareRuntimeState(workspace);
  40. await b.prepareRuntimeState(workspace);
  41. // Bug 根因:macOS 上 fs.watch 走 FSEvents,watch() 返回、Chokidar ready 之后原生流仍需
  42. // 短暂时间才真正生效,期间的变更会直接丢失(实测立即写入约 1/8 丢失、200ms 后为 0)。
  43. // 整份文件连续运行时负载更高,用例随机等不到事件;先越过启动空窗再开始改文件。
  44. await delay(500);
  45. const both = async (expected: unknown) =>
  46. until(async () => {
  47. expect(await a.readRuntimeConfig(workspace)).toMatchObject(expected);
  48. expect(await b.readRuntimeConfig(workspace)).toEqual(await a.readRuntimeConfig(workspace));
  49. });
  50. return { a, b, workspace, homeDir, both };
  51. }
  52. const config = (name = "researcher", systemPrompt = "old") => ({
  53. name,
  54. description: "Research",
  55. systemPrompt,
  56. });
  57. const markdown = (name: string, prompt = "old") =>
  58. `---\nname: ${name}\ndescription: Research\n---\n${prompt}`;
  59. async function sameDirectory(left: string, right: string) {
  60. const a = await stat(left);
  61. const b = await stat(right).catch((error: NodeJS.ErrnoException) => {
  62. if (error.code === "ENOENT") return undefined;
  63. throw error;
  64. });
  65. return Boolean(b && a.dev === b.dev && a.ino === b.ino);
  66. }
  67. describe("native subagent Host watchers", () => {
  68. it("keeps shared recovery in the background while new workspace preparations and queued saves finish", async () => {
  69. const f = await pair();
  70. const root = join(f.homeDir, ".zcode", "agents");
  71. await rm(root, { recursive: true, force: true });
  72. await f.both({ kind: "ready", profiles: [] });
  73. const path = join(root, "researcher.md");
  74. await mkdir(root, { recursive: true });
  75. let active = true,
  76. writes = 0;
  77. await writeFile(path, markdown("researcher", `write-${writes}`));
  78. const writer = (async () => {
  79. while (active) {
  80. await delay(100);
  81. if (active) await writeFile(path, markdown("researcher", `write-${++writes}`));
  82. }
  83. })();
  84. const stop = async () => {
  85. active = false;
  86. await writer;
  87. };
  88. cleanup.push(stop);
  89. await until(() =>
  90. expect(vi.mocked(stat).mock.calls.filter(([p]) => p === path).length).toBeGreaterThanOrEqual(
  91. 4,
  92. ),
  93. );
  94. const before = await f.a.readRuntimeConfig(f.workspace);
  95. expect(before).toMatchObject({ kind: "ready", profiles: [] });
  96. const others = ["b", "c"].map((name) => ({ workspacePath: join(f.homeDir, name) }));
  97. let completed = false;
  98. const preparing = Promise.all([
  99. ...others.map((workspace) => f.a.prepareRuntimeState(workspace)),
  100. f.a.setEnabled({ agentId: "user:user:unrelated", enabled: false }),
  101. ]).then(() => {
  102. completed = true;
  103. });
  104. try {
  105. // 等待期间持续写入,不能先停止写入再证明准备及写队列已释放。
  106. await vi.waitFor(() => expect(completed).toBe(true), { timeout: 4000 });
  107. for (const workspace of others)
  108. expect(await f.a.readRuntimeConfig(workspace)).toEqual(before);
  109. await until(() => expect(writes).toBeGreaterThanOrEqual(60));
  110. await f.both(before);
  111. } finally {
  112. await stop();
  113. await preparing;
  114. }
  115. const expected = { kind: "ready", profiles: [{ systemPrompt: `write-${writes}` }] };
  116. await f.both(expected);
  117. for (const workspace of others)
  118. expect(await f.a.readRuntimeConfig(workspace)).toMatchObject(expected);
  119. expect(before).toMatchObject({ profiles: [] });
  120. }, 20000);
  121. for (const scope of ["user", "project"] as const) {
  122. for (const operation of ["update", "delete", "rename"] as const) {
  123. it(`${scope} ${operation} reaches both Hosts when the real directory is AGENTS`, async ({
  124. skip,
  125. }) => {
  126. const f = await pair(async (home) => {
  127. const parent =
  128. scope === "user" ? join(home, ".zcode") : join(home, "workspace", ".zcode");
  129. const actual = join(parent, "AGENTS");
  130. await mkdir(actual, { recursive: true });
  131. if (!(await sameDirectory(actual, join(parent, "agents"))))
  132. skip("Requires a case-insensitive test filesystem");
  133. await writeFile(join(actual, "researcher.md"), markdown("researcher"));
  134. });
  135. await f.both({ kind: "ready", profiles: [{ name: "researcher", systemPrompt: "old" }] });
  136. const parent =
  137. scope === "user" ? join(f.homeDir, ".zcode") : join(f.workspace.workspacePath, ".zcode");
  138. const logical = join(parent, "agents", "researcher.md");
  139. const actual = join(parent, "AGENTS", "researcher.md");
  140. if (operation === "delete") await rm(logical);
  141. else {
  142. const agentId =
  143. scope === "user"
  144. ? "user:user:researcher"
  145. : `workspace:${f.workspace.workspacePath}:researcher`;
  146. await f.a.updateAgent({
  147. agentId,
  148. oldFilePath: logical,
  149. ...(scope === "project"
  150. ? ({ scope: "workspace", workspacePath: f.workspace.workspacePath } as const)
  151. : {}),
  152. config: config(operation === "rename" ? "renamed" : "researcher", "new"),
  153. });
  154. expect(
  155. await readFile(
  156. operation === "rename" ? join(parent, "AGENTS", "renamed.md") : actual,
  157. "utf8",
  158. ),
  159. ).toContain("new");
  160. }
  161. if (operation !== "update")
  162. await expect(stat(actual)).rejects.toMatchObject({ code: "ENOENT" });
  163. // 文件已成功落盘后,两个独立缓存都必须收敛;不能用重启或手动 reload 修正结果。
  164. await f.both({
  165. profiles:
  166. operation === "delete"
  167. ? []
  168. : [{ name: operation === "rename" ? "renamed" : "researcher", systemPrompt: "new" }],
  169. });
  170. }, 15000);
  171. }
  172. }
  173. for (const mode of ["first creation", "recreation"]) {
  174. it(`observes project directory ${mode} with different casing`, async ({ skip }) => {
  175. const f = await pair(async (home) => {
  176. const probe = join(home, "CaseProbe");
  177. await mkdir(probe);
  178. if (!(await sameDirectory(probe, join(home, "caseprobe"))))
  179. skip("Requires a case-insensitive test filesystem");
  180. await rm(probe, { recursive: true });
  181. });
  182. const parent = join(f.workspace.workspacePath, ".zcode");
  183. const logical = join(parent, "agents");
  184. if (mode === "recreation") {
  185. await mkdir(logical, { recursive: true });
  186. await writeFile(join(logical, "researcher.md"), markdown("researcher"));
  187. await f.both({ profiles: [{ name: "researcher", systemPrompt: "old" }] });
  188. await rm(logical, { recursive: true });
  189. await f.both({ profiles: [] });
  190. }
  191. await mkdir(join(parent, "AGENTS"), { recursive: true });
  192. await writeFile(join(logical, "researcher.md"), markdown("researcher", "new"));
  193. await f.both({ profiles: [{ name: "researcher", systemPrompt: "new" }] });
  194. }, 20000);
  195. }
  196. it("does not merge distinct agents and AGENTS directories on a case-sensitive filesystem", async ({
  197. skip,
  198. }) => {
  199. const f = await pair(async (home) => {
  200. const root = join(home, ".zcode", "agents");
  201. await mkdir(root, { recursive: true });
  202. if (await sameDirectory(root, join(home, ".zcode", "AGENTS")))
  203. skip("Requires a case-sensitive test filesystem");
  204. await mkdir(join(home, ".zcode", "AGENTS"));
  205. await writeFile(join(root, "researcher.md"), markdown("researcher"));
  206. await writeFile(join(home, ".zcode", "AGENTS", "unrelated.md"), markdown("unrelated"));
  207. });
  208. await f.both({ profiles: [{ name: "researcher", systemPrompt: "old" }] });
  209. await writeFile(
  210. join(f.homeDir, ".zcode", "AGENTS", "unrelated.md"),
  211. markdown("unrelated", "wrong"),
  212. );
  213. await writeFile(
  214. join(f.homeDir, ".zcode", "agents", "researcher.md"),
  215. markdown("researcher", "new"),
  216. );
  217. await f.both({ profiles: [{ name: "researcher", systemPrompt: "new" }] });
  218. });
  219. it("removes the old cache entry after a filename-only case rename", async () => {
  220. const f = await pair(async (home) => {
  221. await mkdir(join(home, ".zcode", "agents"), { recursive: true });
  222. await writeFile(join(home, ".zcode", "agents", "Researcher.MD"), markdown("researcher"));
  223. });
  224. await f.both({ profiles: [{ name: "researcher", systemPrompt: "old" }] });
  225. const root = join(f.homeDir, ".zcode", "agents");
  226. await rename(join(root, "Researcher.MD"), join(root, "researcher.md"));
  227. await writeFile(join(root, "researcher.md"), markdown("researcher", "new"));
  228. await f.both({ profiles: [{ name: "researcher", systemPrompt: "new" }] });
  229. await rm(join(root, "researcher.md"));
  230. await f.both({ profiles: [] });
  231. });
  232. it("both Hosts observe profile and state changes through a linked configuration root", async () => {
  233. const f = await pair(async (homeDir) => {
  234. const storage = join(homeDir, "linked-storage");
  235. await mkdir(join(storage, "agents"), { recursive: true });
  236. await mkdir(join(storage, "v2"));
  237. // Windows 使用无需管理员权限的目录 junction;其余平台使用目录符号链接。
  238. await symlink(
  239. storage,
  240. join(homeDir, ".zcode"),
  241. process.platform === "win32" ? "junction" : "dir",
  242. );
  243. await writeFile(
  244. join(storage, "agents", "researcher.md"),
  245. "---\nname: researcher\ndescription: Research\n---\nold",
  246. );
  247. });
  248. await f.both({ kind: "ready", profiles: [{ name: "researcher", systemPrompt: "old" }] });
  249. const agentId = "user:user:researcher";
  250. await f.a.updateAgent({
  251. agentId,
  252. oldFilePath: join(f.homeDir, ".zcode", "agents", "researcher.md"),
  253. config: config("researcher", "new"),
  254. });
  255. expect(
  256. await readFile(join(f.homeDir, "linked-storage", "agents", "researcher.md"), "utf8"),
  257. ).toContain("new");
  258. await f.both({ profiles: [{ name: "researcher", systemPrompt: "new" }] });
  259. await f.a.setEnabled({ agentId, enabled: false });
  260. await f.both({ profiles: [] });
  261. }, 15000);
  262. it.each([
  263. "create",
  264. "update",
  265. "rename",
  266. "delete",
  267. "disable",
  268. "enable",
  269. "builtin",
  270. "plugin",
  271. ] as const)(
  272. "both independent Hosts consume %s without broadcasts",
  273. async (operation) => {
  274. const f = await pair();
  275. const { agent } = await f.a.createAgent({ config: config() });
  276. await f.both({ kind: "ready", profiles: [{ name: "researcher" }] });
  277. if (operation === "enable" || operation === "rename") {
  278. await f.a.setEnabled({ agentId: agent.id, enabled: false });
  279. await f.both({ profiles: [] });
  280. }
  281. const before = await f.b.readRuntimeConfig(f.workspace);
  282. if (operation === "create") await f.a.createAgent({ config: config("second") });
  283. if (operation === "update" || operation === "rename")
  284. await f.a.updateAgent({
  285. agentId: agent.id,
  286. oldFilePath: agent.path,
  287. config: config(operation === "rename" ? "renamed" : "researcher", "new"),
  288. });
  289. if (operation === "delete")
  290. await f.a.deleteAgent({ agentId: agent.id, filePath: agent.path });
  291. if (operation === "disable" || operation === "enable")
  292. await f.a.setEnabled({ agentId: agent.id, enabled: operation === "enable" });
  293. if (operation === "builtin")
  294. await f.a.setBuiltInModelOverride({
  295. agentName: "Explore",
  296. modelSelection: { providerId: "test", modelId: "new" },
  297. });
  298. if (operation === "plugin")
  299. await f.a.setPluginAgentModelOverride({
  300. agentId: "plugin:test:researcher",
  301. modelSelection: { providerId: "test", modelId: "new" },
  302. });
  303. await until(async () => {
  304. const next = await f.a.readRuntimeConfig(f.workspace);
  305. expect(next).toEqual(await f.b.readRuntimeConfig(f.workspace));
  306. if (operation !== "rename") expect(next).not.toEqual(before);
  307. if (operation === "rename") {
  308. expect(next).toMatchObject({ profiles: [] });
  309. expect(
  310. JSON.parse(await readFile(join(f.homeDir, ".zcode", "v2", "agents-state.json"), "utf8"))
  311. .disabledAgentIds,
  312. ).toContain("user:user:renamed");
  313. }
  314. });
  315. if (operation === "rename") {
  316. await f.a.setEnabled({ agentId: "user:user:renamed", enabled: true });
  317. await f.both({ profiles: [{ name: "renamed", systemPrompt: "new" }] });
  318. }
  319. },
  320. 15000,
  321. );
  322. it.each(["user", "project"] as const)(
  323. "keeps %s scans and native updates limited to direct files",
  324. async (scope) => {
  325. const rootFor = (home: string) =>
  326. join(home, ...(scope === "project" ? ["workspace"] : []), ".zcode", "agents");
  327. const md = (prompt: string) => `---\nname: external\ndescription: External\n---\n${prompt}`;
  328. const f = await pair(async (home) => {
  329. const root = rootFor(home);
  330. await mkdir(join(root, "nested"), { recursive: true });
  331. await writeFile(join(root, "nested", "deep.md"), markdown("nested-agent", "initial"));
  332. await writeFile(join(root, "external.markdown"), md("first"));
  333. });
  334. const root = rootFor(f.homeDir);
  335. const path = join(root, "external.markdown");
  336. await f.both({ profiles: [{ name: "external", systemPrompt: "first" }] });
  337. await writeFile(join(root, "temp"), md("atomic"));
  338. await rename(join(root, "temp"), path);
  339. await f.both({ profiles: [{ systemPrompt: "atomic" }] });
  340. await rm(root, { recursive: true });
  341. await f.both({ profiles: [] });
  342. await mkdir(join(root, "nested"), { recursive: true });
  343. await writeFile(join(root, "nested", "deep.md"), markdown("nested-agent", "rebuilt"));
  344. await writeFile(path, md("recreated"));
  345. await f.both({ profiles: [{ systemPrompt: "recreated" }] });
  346. await writeFile(join(root, "nested", "deep.md"), markdown("nested-agent", "edited"));
  347. await writeFile(path, md("final"));
  348. await f.both({ profiles: [{ systemPrompt: "final" }] });
  349. await f.a.prepareRuntimeState(f.workspace);
  350. await f.b.prepareRuntimeState(f.workspace);
  351. await f.both({ profiles: [{ name: "external", systemPrompt: "final" }] });
  352. await rm(join(root, "nested", "deep.md"));
  353. await writeFile(path, md("after-delete"));
  354. await f.both({ profiles: [{ name: "external", systemPrompt: "after-delete" }] });
  355. },
  356. 20000,
  357. );
  358. it("recovers after deleting missing-path parents and after moving a replacement directory into place", async () => {
  359. const f = await pair(async (home) => {
  360. await mkdir(join(home, "workspace", ".zcode"), { recursive: true });
  361. });
  362. const root = join(f.workspace.workspacePath, ".zcode", "agents");
  363. // 目标缺失时,连临时监听的空父目录也可能被整体移走。
  364. await rename(
  365. join(f.workspace.workspacePath, ".zcode"),
  366. join(f.workspace.workspacePath, "saved"),
  367. );
  368. await mkdir(root, { recursive: true });
  369. const path = join(root, "a.md");
  370. await writeFile(path, markdown("aaa", "first"));
  371. await f.both({ profiles: [{ systemPrompt: "first" }] });
  372. await rm(f.workspace.workspacePath, { recursive: true });
  373. await f.both({ profiles: [] });
  374. await mkdir(root, { recursive: true });
  375. await writeFile(path, markdown("aaa", "rebuilt"));
  376. await f.both({ profiles: [{ systemPrompt: "rebuilt" }] });
  377. const replacement = join(f.homeDir, "replacement");
  378. await mkdir(replacement);
  379. await writeFile(join(replacement, "a.md"), markdown("aaa", "replacement"));
  380. await rm(root, { recursive: true });
  381. await rename(replacement, root);
  382. await f.both({ profiles: [{ systemPrompt: "replacement" }] });
  383. await writeFile(path, markdown("aaa", "later"));
  384. await f.both({ profiles: [{ systemPrompt: "later" }] });
  385. }, 25000);
  386. it("observes files created after an empty configuration directory is rebuilt", async () => {
  387. const f = await pair();
  388. const root = join(f.workspace.workspacePath, ".zcode", "agents");
  389. await mkdir(root, { recursive: true });
  390. const path = join(root, "a.md");
  391. await writeFile(path, markdown("aaa"));
  392. await f.both({ profiles: [{ name: "aaa" }] });
  393. await rm(root, { recursive: true });
  394. await f.both({ profiles: [] });
  395. await mkdir(root);
  396. await writeFile(path, markdown("aaa", "returned"));
  397. await f.both({ profiles: [{ systemPrompt: "returned" }] });
  398. }, 15000);
  399. it("reads state from the prepared path without re-resolving CLI storage on every event", async () => {
  400. const f = await pair();
  401. const { agent } = await f.a.createAgent({ config: config() });
  402. await f.both({ profiles: [{ name: "researcher" }] });
  403. const cliRoot = join(f.homeDir, ".zcode", "cli");
  404. await mkdir(cliRoot, { recursive: true });
  405. await writeFile(
  406. join(cliRoot, "config.json"),
  407. JSON.stringify({ storage: { dir: join(f.homeDir, "other-storage") } }),
  408. );
  409. const stateRoot = join(f.homeDir, ".zcode", "v2");
  410. await mkdir(stateRoot, { recursive: true });
  411. await writeFile(
  412. join(stateRoot, "agents-state.json"),
  413. JSON.stringify({ disabledAgentIds: [agent.id] }),
  414. );
  415. await f.both({ kind: "ready", profiles: [] });
  416. }, 15000);
  417. it.skipIf(process.platform === "win32")(
  418. "publishes initial fallback when state cannot be read, including its migration",
  419. async () => {
  420. const homeDir = await mkdtemp(join(tmpdir(), "subagent-initial-state-"));
  421. cleanup.push(() => rm(homeDir, { recursive: true, force: true }));
  422. const path = join(homeDir, ".zcode", "v2", "agents-state.json");
  423. await mkdir(join(homeDir, ".zcode", "v2"), { recursive: true });
  424. await writeFile(path, "{}");
  425. await chmod(path, 0o200);
  426. cleanup.push(() => chmod(path, 0o600));
  427. const service = createSubagentsService({ homeDir });
  428. cleanup.push(() => service.disposeAll());
  429. const workspace = { workspacePath: join(homeDir, "workspace") };
  430. await service.prepareRuntimeState(workspace);
  431. expect(await service.readRuntimeConfig(workspace)).toEqual({ kind: "built-in-fallback" });
  432. },
  433. );
  434. it.skipIf(process.platform === "win32")(
  435. "does not publish a write rejected before disk mutation, but consumes a partially failed rename",
  436. async () => {
  437. const f = await pair();
  438. const { agent } = await f.a.createAgent({ config: config() });
  439. await f.both({ profiles: [{ name: "researcher" }] });
  440. await expect(f.a.createAgent({ config: config() })).rejects.toThrow();
  441. await f.both({ profiles: [{ systemPrompt: "old" }] });
  442. await f.a.setEnabled({ agentId: agent.id, enabled: false });
  443. await f.both({ profiles: [] });
  444. await f.a.setEnabled({ agentId: agent.id, enabled: true });
  445. await f.both({ profiles: [{ name: "researcher" }] });
  446. // state 无读取权限使迁移失败;先写入的新 Markdown 是真实磁盘事实,watcher 仍会观察。
  447. const statePath = join(f.homeDir, ".zcode", "v2", "agents-state.json");
  448. await mkdir(join(f.homeDir, ".zcode", "v2"), { recursive: true });
  449. await writeFile(statePath, JSON.stringify({ disabledAgentIds: [] }));
  450. await chmod(statePath, 0);
  451. cleanup.push(() => chmod(statePath, 0o600));
  452. await expect(
  453. f.a.updateAgent({ agentId: agent.id, oldFilePath: agent.path, config: config("renamed") }),
  454. ).rejects.toThrow();
  455. await f.both({ kind: "built-in-fallback" });
  456. await chmod(statePath, 0o600);
  457. await writeFile(statePath, JSON.stringify({ disabledAgentIds: [] }));
  458. await f.both({ kind: "ready", profiles: [{ name: "renamed" }, { name: "researcher" }] });
  459. },
  460. 15000,
  461. );
  462. it("observes an empty root moved away, an invalid file replacement, and directory recovery", async () => {
  463. const f = await pair(async (home) => {
  464. await mkdir(join(home, "workspace", ".zcode", "agents"), { recursive: true });
  465. });
  466. const root = join(f.workspace.workspacePath, ".zcode", "agents");
  467. await rename(root, root + "-saved");
  468. await writeFile(root, "not a directory");
  469. await f.both({ kind: "built-in-fallback" });
  470. await rm(root);
  471. await rename(root + "-saved", root);
  472. await writeFile(join(root, "researcher.md"), markdown("researcher", "restored"));
  473. await f.both({ kind: "ready", profiles: [{ systemPrompt: "restored" }] });
  474. }, 20000);
  475. });