subagentRuntimeConfig.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. import { mkdtemp, mkdir, rename, rm, writeFile } from "node:fs/promises";
  2. import * as fs from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, join, parse, resolve } from "node:path";
  5. import { randomUUID } from "node:crypto";
  6. import type { Stats } from "node:fs";
  7. import { EventEmitter, on } from "node:events";
  8. import { watch } from "chokidar";
  9. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  10. import * as shared from "@zcode/shared";
  11. import { createSubagentRuntimeConfigCache } from "../src/subagents/subagentRuntimeConfig.js";
  12. import { createSubagentConfigScope } from "../src/subagents/subagentConfigScope.js";
  13. const parentEvents = vi.hoisted(() => new Map<string, Set<EventEmitter>>());
  14. vi.mock("node:fs/promises", async (importOriginal) => {
  15. const actual = await importOriginal<typeof import("node:fs/promises")>();
  16. return {
  17. ...actual,
  18. readFile: vi.fn(actual.readFile),
  19. readdir: vi.fn(actual.readdir),
  20. stat: vi.fn(actual.stat),
  21. watch: vi.fn(async function* (path: string, options: { signal: AbortSignal }) {
  22. const emitter = new EventEmitter();
  23. if (!parentEvents.has(path)) parentEvents.set(path, new Set());
  24. parentEvents.get(path)!.add(emitter);
  25. try {
  26. for await (const [event] of on(emitter, "change", { signal: options.signal })) yield event;
  27. } finally {
  28. parentEvents.get(path)?.delete(emitter);
  29. }
  30. }),
  31. };
  32. });
  33. vi.mock("@zcode/shared", { spy: true });
  34. const readiness = vi.hoisted(() => ({ automatic: true }));
  35. const watched = vi.hoisted(() => new Set<EventEmitter>());
  36. vi.mock("chokidar", () => ({
  37. watch: vi.fn(() => {
  38. const watcher = Object.assign(new EventEmitter(), { close: vi.fn(async () => {}) });
  39. watched.add(watcher);
  40. if (readiness.automatic) queueMicrotask(() => watcher.emit("ready"));
  41. return watcher;
  42. }),
  43. }));
  44. beforeEach(async () => {
  45. readiness.automatic = true;
  46. vi.mocked(watch).mockClear();
  47. vi.mocked(fs.watch).mockClear();
  48. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  49. vi.mocked(fs.readFile).mockReset().mockImplementation(actual.readFile);
  50. vi.mocked(fs.readdir).mockReset().mockImplementation(actual.readdir);
  51. vi.mocked(fs.stat).mockReset().mockImplementation(actual.stat);
  52. vi.mocked(shared.parseAgentProfileFromMarkdown).mockClear();
  53. });
  54. const cleanup: Array<() => void | Promise<void>> = [];
  55. afterEach(async () => {
  56. for (const dispose of cleanup.splice(0).reverse()) await dispose();
  57. watched.clear();
  58. parentEvents.clear();
  59. vi.restoreAllMocks();
  60. });
  61. const markdown = (name: string, prompt = name) =>
  62. `---\nname: ${name}\ndescription: Test\n---\n${prompt}`;
  63. const until = (assertion: () => unknown) => vi.waitFor(assertion, { timeout: 5000, interval: 10 });
  64. function initialWatcherFor(path: string): ReturnType<typeof watch> {
  65. // 各 scope 并行 stat,注册顺序不固定;按监听路径取得初始实例,避免向其他 scope 发事件。
  66. const index = vi.mocked(watch).mock.calls.findIndex(([root]) => root === path);
  67. expect(index).toBeGreaterThanOrEqual(0);
  68. return vi.mocked(watch).mock.results[index]!.value;
  69. }
  70. async function fixture() {
  71. const root = await mkdtemp(join(tmpdir(), "subagent-snapshot-"));
  72. cleanup.push(() => rm(root, { recursive: true, force: true }));
  73. const userRoot = join(root, "user"),
  74. statePath = join(root, "state", "agents-state.json");
  75. await mkdir(userRoot);
  76. await mkdir(join(root, "state"));
  77. const state = {
  78. disabledAgentIds: [] as string[],
  79. builtInModelSelectionOverrides: {},
  80. pluginAgentModelSelectionOverrides: {},
  81. };
  82. const readState = vi.fn(async () => structuredClone(state));
  83. const cache = createSubagentRuntimeConfigCache({
  84. readUserRoot: async () => userRoot,
  85. readStatePath: async () => statePath,
  86. readState,
  87. });
  88. cleanup.push(() => cache.dispose());
  89. const workspace = { workspacePath: join(root, "workspace") };
  90. const emit = (path: string, event = "change", _rootPath = userRoot) =>
  91. [...watched].forEach((watcher) => watcher.emit("all", event, path));
  92. const read = () => cache.read(workspace);
  93. return { root, userRoot, statePath, state, readState, cache, workspace, emit, read };
  94. }
  95. describe("Host incremental subagent snapshots", () => {
  96. it("keeps the filesystem root observable when the configuration directory does not exist", async () => {
  97. // 使用当前平台的真实根路径,但 mock watcher,避免写入盘符根目录或监听整个文件系统。
  98. const volumeRoot = parse(resolve(tmpdir())).root;
  99. const parent = join(volumeRoot, `subagent-missing-${randomUUID()}`);
  100. const root = join(parent, "agents");
  101. const scope = createSubagentConfigScope({ root, load: async () => [], onSettled: vi.fn() });
  102. cleanup.push(() => scope.dispose());
  103. await scope.ready;
  104. const [anchor, options] = vi.mocked(watch).mock.calls.at(-1)!;
  105. expect(anchor).toBe(volumeRoot);
  106. const ignored = options?.ignored;
  107. if (typeof ignored !== "function") throw new Error("Expected watcher path filter");
  108. expect(ignored(volumeRoot)).toBe(false);
  109. expect(options?.depth).toBe(0);
  110. expect(ignored(parent, { isDirectory: () => true } as Stats)).toBe(false);
  111. expect(ignored(join(volumeRoot, "unrelated"), { isDirectory: () => true } as Stats)).toBe(
  112. false,
  113. );
  114. expect(
  115. ignored(join(volumeRoot, "unrelated.md"), {
  116. isDirectory: () => false,
  117. isSymbolicLink: () => false,
  118. } as Stats),
  119. ).toBe(true);
  120. expect(ignored(root)).toBe(true);
  121. expect(ignored(join(root, "reviewer.md"))).toBe(true);
  122. });
  123. it("switches missing ancestors to the original root and waits for stable initial files", async () => {
  124. const f = await fixture();
  125. await f.cache.prepare(f.workspace);
  126. const watchedPaths = vi.mocked(watch).mock.calls.map(([path]) => path);
  127. expect(watchedPaths.sort()).toEqual([f.userRoot, join(f.root, "state"), f.root].sort());
  128. const parentWatcher = initialWatcherFor(f.root);
  129. const project = join(f.workspace.workspacePath, ".zcode", "agents");
  130. await mkdir(project, { recursive: true });
  131. const path = join(project, "a.md"),
  132. temporary = join(project, "temporary.md");
  133. await writeFile(path, markdown("aaa", "partial"));
  134. await writeFile(temporary, markdown("temporary"));
  135. vi.mocked(fs.readFile).mockClear();
  136. vi.mocked(fs.readdir).mockClear();
  137. parentWatcher.emit("all", "addDir", f.workspace.workspacePath);
  138. await until(() => expect(vi.mocked(watch).mock.calls.at(-1)?.[0]).toBe(project));
  139. await until(() =>
  140. expect(
  141. vi.mocked(fs.stat).mock.calls.filter(([p]) => p === path).length,
  142. ).toBeGreaterThanOrEqual(2),
  143. );
  144. expect(vi.mocked(fs.readFile).mock.calls.filter(([p]) => p === path)).toEqual([]);
  145. expect(await f.read()).toMatchObject({ profiles: [] });
  146. await writeFile(path, markdown("aaa", "complete"));
  147. await rm(temporary);
  148. const added = join(project, "b.markdown");
  149. await writeFile(added, markdown("bbb"));
  150. f.emit(added, "add");
  151. await until(async () =>
  152. expect(await f.read()).toMatchObject({
  153. profiles: [{ name: "aaa", systemPrompt: "complete" }, { name: "bbb" }],
  154. }),
  155. );
  156. expect(vi.mocked(fs.readFile).mock.calls.filter(([p]) => p === path)).toHaveLength(1);
  157. expect(vi.mocked(fs.readFile).mock.calls.filter(([p]) => p === temporary)).toHaveLength(0);
  158. expect(vi.mocked(fs.readdir).mock.calls.filter(([p]) => p === project)).toHaveLength(1);
  159. const reads = vi.mocked(fs.readFile).mock.calls.length;
  160. parentWatcher.emit("all", "change", path);
  161. await Promise.all([f.read(), f.read()]);
  162. expect(vi.mocked(fs.readFile).mock.calls.length).toBe(reads);
  163. expect((parentWatcher as unknown as { close: unknown }).close).toHaveBeenCalledOnce();
  164. });
  165. it("rechecks directory changes during watcher readiness and ignores unrelated parent events", async () => {
  166. readiness.automatic = false;
  167. const f = await fixture();
  168. const preparing = f.cache.prepare(f.workspace);
  169. await until(() => expect(watched.size).toBe(3));
  170. const project = join(f.workspace.workspacePath, ".zcode", "agents");
  171. await mkdir(project, { recursive: true });
  172. await writeFile(join(project, "a.md"), markdown("aaa"));
  173. for (const watcher of watched) watcher.emit("ready");
  174. await until(() => expect(watched.size).toBe(4));
  175. await rm(f.workspace.workspacePath, { recursive: true });
  176. [...watched].at(-1)!.emit("ready");
  177. await until(() => expect(watched.size).toBe(5));
  178. [...watched].at(-1)!.emit("ready");
  179. await preparing;
  180. expect(await f.read()).toMatchObject({ profiles: [] });
  181. vi.mocked(fs.readFile).mockClear();
  182. vi.mocked(fs.readdir).mockClear();
  183. const parent = [...watched].at(-1)!;
  184. parent.emit("all", "addDir", join(f.root, "unrelated"));
  185. await until(() => expect(vi.mocked(fs.stat).mock.calls.at(-1)?.[0]).toBe(f.root));
  186. expect(watched.size).toBe(5);
  187. expect(fs.readFile).not.toHaveBeenCalled();
  188. expect(fs.readdir).not.toHaveBeenCalled();
  189. });
  190. it.each(["rebuild", "dispose"])(
  191. "cancels a recovered-directory load on %s without publishing its result",
  192. async (action) => {
  193. const f = await fixture();
  194. await f.cache.prepare(f.workspace);
  195. const project = join(f.workspace.workspacePath, ".zcode", "agents");
  196. const path = join(project, "a.md");
  197. await mkdir(project, { recursive: true });
  198. await writeFile(path, markdown("aaa", "discard"));
  199. f.emit(f.workspace.workspacePath, "addDir");
  200. await until(() => expect(vi.mocked(fs.stat).mock.calls.some(([p]) => p === path)).toBe(true));
  201. const obsolete = [...watched].at(-1)!;
  202. if (action === "dispose") {
  203. f.cache.dispose();
  204. await expect(f.read()).rejects.toThrow(/disposed/i);
  205. } else {
  206. await rm(project, { recursive: true });
  207. await mkdir(project);
  208. await writeFile(path, markdown("aaa", "latest"));
  209. obsolete.emit("all", "unlinkDir", project);
  210. await until(async () =>
  211. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "latest" }] }),
  212. );
  213. expect((obsolete as unknown as { close: unknown }).close).toHaveBeenCalledOnce();
  214. }
  215. expect(
  216. vi
  217. .mocked(shared.parseAgentProfileFromMarkdown)
  218. .mock.calls.some(([input]) => input.content.includes("discard")),
  219. ).toBe(false);
  220. },
  221. );
  222. it("discards an in-flight file read when its directory is replaced", async () => {
  223. const f = await fixture();
  224. const path = join(f.userRoot, "a.md");
  225. await writeFile(path, markdown("aaa", "initial"));
  226. await f.cache.prepare(f.workspace);
  227. const gate = Promise.withResolvers<string>();
  228. vi.mocked(fs.readFile).mockImplementationOnce(
  229. () => gate.promise as ReturnType<typeof fs.readFile>,
  230. );
  231. f.emit(path);
  232. await until(() => expect(vi.mocked(fs.readFile).mock.results.at(-1)?.value).toBe(gate.promise));
  233. const obsolete = initialWatcherFor(f.userRoot);
  234. // 删除后立即 mkdir 可能复用 inode,未必构成该用例要验证的目录身份替换。
  235. // 保留旧目录再建立新目录,确定性地产生不同身份,不依赖文件系统分配时序。
  236. await rename(f.userRoot, `${f.userRoot}-obsolete`);
  237. await mkdir(f.userRoot);
  238. await writeFile(path, markdown("aaa", "replacement"));
  239. // 快速替换时可能只有原生事件;路径仍存在,也必须关闭旧目录对象的监听。
  240. for (const events of parentEvents.get(dirname(f.userRoot)) ?? [])
  241. events.emit("change", { eventType: "rename", filename: "user" });
  242. await until(() =>
  243. expect((obsolete as unknown as { close: unknown }).close).toHaveBeenCalledOnce(),
  244. );
  245. gate.resolve(markdown("aaa", "obsolete"));
  246. await until(async () =>
  247. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "replacement" }] }),
  248. );
  249. expect(
  250. vi
  251. .mocked(shared.parseAgentProfileFromMarkdown)
  252. .mock.calls.some(([input]) => input.content.includes("obsolete")),
  253. ).toBe(false);
  254. });
  255. it("rebinds before publishing child unlinks when the directory unlink notification is late", async () => {
  256. const f = await fixture();
  257. const path = join(f.userRoot, "a.md");
  258. await writeFile(path, markdown("aaa"));
  259. await f.cache.prepare(f.workspace);
  260. const obsolete = initialWatcherFor(f.userRoot);
  261. await rm(f.userRoot, { recursive: true });
  262. // 原生库可先发文件 unlink;目录检查完成前就重建,会让它不再发 unlinkDir。
  263. obsolete.emit("all", "unlink", path);
  264. await until(async () => expect(await f.read()).toMatchObject({ profiles: [] }));
  265. expect((obsolete as unknown as { close: unknown }).close).toHaveBeenCalledOnce();
  266. await mkdir(f.userRoot);
  267. await writeFile(path, markdown("aaa", "recreated"));
  268. f.emit(f.userRoot, "addDir");
  269. await until(async () =>
  270. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "recreated" }] }),
  271. );
  272. });
  273. it("parses changed files once, never rereads other scopes, and returns independent memory copies", async () => {
  274. const f = await fixture();
  275. const a = join(f.userRoot, "a.md"),
  276. b = join(f.userRoot, "b.markdown");
  277. await writeFile(a, markdown("aaa"));
  278. await writeFile(b, markdown("bbb"));
  279. await f.cache.prepare(f.workspace);
  280. const readFile = vi.spyOn(fs, "readFile"),
  281. readdir = vi.spyOn(fs, "readdir"),
  282. parse = vi.spyOn(shared, "parseAgentProfileFromMarkdown");
  283. readFile.mockClear();
  284. readdir.mockClear();
  285. parse.mockClear();
  286. const before = await f.read();
  287. await writeFile(a, markdown("aaa", "new"));
  288. f.emit(a);
  289. f.emit(a);
  290. await until(async () =>
  291. expect(await f.read()).toMatchObject({
  292. kind: "ready",
  293. profiles: [{ systemPrompt: "new" }, { name: "bbb" }],
  294. }),
  295. );
  296. expect(readFile.mock.calls.map(([path]) => path)).toEqual([a]);
  297. expect(readdir).not.toHaveBeenCalled();
  298. expect(parse).toHaveBeenCalledTimes(1);
  299. f.state.disabledAgentIds = ["user:user:aaa"];
  300. f.emit(f.statePath, "change", join(f.root, "state"));
  301. await until(async () => expect(await f.read()).toMatchObject({ profiles: [{ name: "bbb" }] }));
  302. expect(readFile).toHaveBeenCalledTimes(1);
  303. expect(parse).toHaveBeenCalledTimes(1);
  304. await Promise.all(Array.from({ length: 10 }, f.read));
  305. expect(f.readState).toHaveBeenCalledTimes(2);
  306. expect(f.readState).toHaveBeenLastCalledWith(f.statePath);
  307. expect(before).toMatchObject({ profiles: [{ systemPrompt: "aaa" }, { name: "bbb" }] });
  308. const changed = await f.read();
  309. if (changed.kind === "ready") changed.profiles.length = 0;
  310. expect(await f.read()).toMatchObject({ profiles: [{ name: "bbb" }] });
  311. f.emit(join(f.userRoot, "ignored.txt"));
  312. f.emit(join(f.userRoot, "nested", "deep.md"));
  313. expect(readFile).toHaveBeenCalledTimes(1);
  314. });
  315. it("does not postpone a pending file batch when an unrelated parent event arrives", async () => {
  316. const f = await fixture();
  317. const path = join(f.userRoot, "a.md");
  318. await writeFile(path, markdown("aaa", "old"));
  319. await f.cache.prepare(f.workspace);
  320. const stats = await fs.stat(f.userRoot);
  321. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  322. vi.mocked(fs.stat).mockImplementation((path, options) =>
  323. path === f.userRoot
  324. ? (Promise.resolve(stats) as ReturnType<typeof fs.stat>)
  325. : actual.stat(path, options),
  326. );
  327. await writeFile(path, markdown("aaa", "new"));
  328. vi.mocked(fs.readFile).mockClear();
  329. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  330. try {
  331. f.emit(path);
  332. await vi.advanceTimersByTimeAsync(200);
  333. for (const events of parentEvents.get(dirname(f.userRoot)) ?? [])
  334. events.emit("change", { eventType: "rename", filename: "unrelated" });
  335. await vi.advanceTimersByTimeAsync(100);
  336. // 父目录检查不应重新开始文件批次的 300ms 合并窗口。
  337. expect(fs.readFile).toHaveBeenCalledWith(path, "utf8");
  338. await until(async () =>
  339. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "new" }] }),
  340. );
  341. } finally {
  342. vi.useRealTimers();
  343. }
  344. });
  345. it.each(["resolve", "reject"])(
  346. "keeps old snapshots during load and ignores stale %s without losing another changed file",
  347. async (completion) => {
  348. const f = await fixture();
  349. const a = join(f.userRoot, "a.md"),
  350. b = join(f.userRoot, "b.md");
  351. await writeFile(a, markdown("aaa"));
  352. await writeFile(b, markdown("bbb"));
  353. await f.cache.prepare(f.workspace);
  354. const before = await f.read();
  355. const gate = Promise.withResolvers<string>();
  356. const original = (
  357. await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises")
  358. ).readFile;
  359. let first = true;
  360. vi.spyOn(fs, "readFile").mockImplementation(((path: unknown, ...args: unknown[]) => {
  361. if (path === a && first) {
  362. first = false;
  363. return gate.promise;
  364. }
  365. return Reflect.apply(original, fs, [path, ...args]);
  366. }) as typeof fs.readFile);
  367. f.emit(a);
  368. await until(() => expect(first).toBe(false));
  369. expect(await Promise.all([f.read(), f.read()])).toEqual([before, before]);
  370. await writeFile(a, markdown("aaa", "latest-a"));
  371. await writeFile(b, markdown("bbb", "latest-b"));
  372. f.emit(a);
  373. f.emit(b);
  374. if (completion === "resolve") gate.resolve(markdown("aaa", "stale"));
  375. else gate.reject(new Error("stale"));
  376. await until(async () =>
  377. expect(await f.read()).toMatchObject({
  378. kind: "ready",
  379. profiles: [{ systemPrompt: "latest-a" }, { systemPrompt: "latest-b" }],
  380. }),
  381. );
  382. },
  383. );
  384. it("publishes fallback to concurrent readers without retrying on read, then recovers on a file event", async () => {
  385. const f = await fixture();
  386. await writeFile(join(f.userRoot, "a.md"), markdown("aaa"));
  387. await f.cache.prepare(f.workspace);
  388. f.readState.mockRejectedValue(new Error("state unavailable"));
  389. f.emit(f.statePath, "change", join(f.root, "state"));
  390. await until(async () => expect(await f.read()).toEqual({ kind: "built-in-fallback" }));
  391. const calls = f.readState.mock.calls.length;
  392. expect(await Promise.all([f.read(), f.read()])).toEqual([
  393. { kind: "built-in-fallback" },
  394. { kind: "built-in-fallback" },
  395. ]);
  396. expect(f.readState).toHaveBeenCalledTimes(calls);
  397. const retry = Promise.withResolvers<typeof f.state>();
  398. f.readState.mockReturnValueOnce(retry.promise);
  399. try {
  400. f.emit(f.statePath, "change", join(f.root, "state"));
  401. await until(() => expect(f.readState).toHaveBeenCalledTimes(calls + 1));
  402. // 真正读取失败后,重载完成前仍不可用,不能因允许临时回退恢复而重新启用旧值。
  403. expect(await Promise.all([f.read(), f.read()])).toEqual([
  404. { kind: "built-in-fallback" },
  405. { kind: "built-in-fallback" },
  406. ]);
  407. } finally {
  408. retry.resolve(f.state);
  409. }
  410. await until(async () =>
  411. expect(await f.read()).toMatchObject({ kind: "ready", profiles: [{ name: "aaa" }] }),
  412. );
  413. });
  414. it("waits for initialization, absorbs initial changes, and prevents late publication after disposal", async () => {
  415. const f = await fixture();
  416. const gate = Promise.withResolvers<typeof f.state>();
  417. f.readState.mockReturnValueOnce(gate.promise);
  418. const preparing = f.cache.prepare(f.workspace);
  419. await until(() => expect(f.readState).toHaveBeenCalledTimes(1));
  420. let done = false;
  421. const reading = f.read().then((v) => {
  422. done = true;
  423. return v;
  424. });
  425. await Promise.resolve();
  426. expect(done).toBe(false);
  427. const a = join(f.userRoot, "a.md");
  428. await writeFile(a, markdown("aaa"));
  429. f.emit(a, "add");
  430. gate.resolve(f.state);
  431. await preparing;
  432. expect(await reading).toMatchObject({ profiles: [{ name: "aaa" }] });
  433. const late = Promise.withResolvers<typeof f.state>();
  434. f.readState.mockReturnValueOnce(late.promise);
  435. f.emit(f.statePath, "change", join(f.root, "state"));
  436. await until(() => expect(f.readState).toHaveBeenCalledTimes(2));
  437. f.cache.dispose();
  438. late.resolve(f.state);
  439. await expect(f.read()).rejects.toThrow(/disposed/i);
  440. for (const watcher of watched.values())
  441. expect((watcher as unknown as { close: unknown }).close).toHaveBeenCalled();
  442. });
  443. it.each(["ready", "timeout"])(
  444. "reuses completed shared data with %s project initialization",
  445. async (mode) => {
  446. const f = await fixture();
  447. const path = join(f.userRoot, "a.md");
  448. await writeFile(path, markdown("aaa", "old"));
  449. await f.cache.prepare(f.workspace);
  450. const before = await f.read();
  451. const gate = Promise.withResolvers<string>();
  452. const others = ["b", "c"].map((name) => ({ workspacePath: join(f.root, name) }));
  453. const projectPath = join(others[0]!.workspacePath, ".zcode", "agents", "b.md");
  454. await mkdir(dirname(projectPath), { recursive: true });
  455. await writeFile(projectPath, markdown("bbb", "project"));
  456. const project = Promise.withResolvers<string>();
  457. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  458. vi.mocked(fs.readFile).mockImplementation(((readPath, ...args) => {
  459. if (readPath === path) return gate.promise;
  460. if (readPath === projectPath) return project.promise;
  461. return Reflect.apply(actual.readFile, fs, [readPath, ...args]);
  462. }) as typeof fs.readFile);
  463. f.emit(path);
  464. await until(() =>
  465. expect(vi.mocked(fs.readFile).mock.results.some((r) => r.value === gate.promise)).toBe(
  466. true,
  467. ),
  468. );
  469. if (mode === "ready") project.resolve(markdown("bbb", "project"));
  470. const completed: string[] = [];
  471. // 与 service 写队列一样顺序准备,不能为同一共享后台刷新反复等待。
  472. const preparing = (async () => {
  473. for (const workspace of others) {
  474. await f.cache.prepare(workspace);
  475. completed.push(workspace.workspacePath);
  476. }
  477. })();
  478. try {
  479. if (mode === "timeout") {
  480. await vi.waitFor(() => expect(completed).toContain(others[0]!.workspacePath), {
  481. timeout: 6500,
  482. });
  483. expect(await f.cache.read(others[0]!)).toEqual({ kind: "built-in-fallback" });
  484. project.resolve(markdown("bbb", "project"));
  485. }
  486. await vi.waitFor(() => expect(completed).toHaveLength(2), { timeout: 4000 });
  487. expect(await f.read()).toEqual(before);
  488. expect(await f.cache.read(others[1]!)).toEqual(before);
  489. // B 超时过也应和 C 一样复用共享完整结果,不能等共享后台刷新结束才恢复。
  490. await until(async () =>
  491. expect(await f.cache.read(others[0]!)).toMatchObject({
  492. kind: "ready",
  493. profiles: [{ systemPrompt: "old" }, { systemPrompt: "project" }],
  494. }),
  495. );
  496. expect(f.readState).toHaveBeenCalledOnce();
  497. expect(vi.mocked(fs.readFile).mock.calls.filter(([p]) => p === path)).toHaveLength(2);
  498. } finally {
  499. project.resolve(markdown("bbb", "project"));
  500. gate.resolve(markdown("aaa", "new"));
  501. await preparing;
  502. }
  503. await until(async () => {
  504. for (const workspace of [f.workspace, others[1]!])
  505. expect(await f.cache.read(workspace)).toMatchObject({
  506. profiles: [{ systemPrompt: "new" }],
  507. });
  508. expect(await f.cache.read(others[0]!)).toMatchObject({
  509. profiles: [{ systemPrompt: "new" }, { systemPrompt: "project" }],
  510. });
  511. });
  512. expect(before).toMatchObject({ profiles: [{ systemPrompt: "old" }] });
  513. },
  514. );
  515. it.each(["initial", "reload"])(
  516. "bounds %s waiting and publishes late completion without another file event",
  517. async (mode) => {
  518. const f = await fixture();
  519. const path = join(f.userRoot, "a.md");
  520. await writeFile(path, markdown("aaa", "old"));
  521. let before: Awaited<ReturnType<typeof f.read>> = { kind: "built-in-fallback" };
  522. if (mode === "reload") {
  523. await f.cache.prepare(f.workspace);
  524. before = await f.read();
  525. }
  526. await writeFile(path, markdown("aaa", "new"));
  527. const gate = Promise.withResolvers<typeof f.state>();
  528. f.readState.mockClear().mockReturnValueOnce(gate.promise);
  529. const started = performance.now();
  530. let prepared = false;
  531. const preparing = f.cache.prepare(f.workspace).then(() => {
  532. prepared = true;
  533. });
  534. let reading: Promise<unknown> | undefined;
  535. try {
  536. await until(() => expect(f.readState).toHaveBeenCalledOnce());
  537. let readDone = false;
  538. reading = f.read().then((snapshot) => {
  539. readDone = true;
  540. return snapshot;
  541. });
  542. expect(prepared).toBe(false);
  543. await vi.waitFor(() => expect(prepared && readDone).toBe(true), { timeout: 6500 });
  544. expect(performance.now() - started).toBeGreaterThanOrEqual(4900);
  545. expect(await reading).toEqual(before);
  546. const fileReads = vi.mocked(fs.readFile).mock.calls.length;
  547. expect(await Promise.all([f.read(), f.read()])).toEqual([before, before]);
  548. expect(fs.readFile).toHaveBeenCalledTimes(fileReads);
  549. expect(f.readState).toHaveBeenCalledOnce();
  550. } finally {
  551. gate.resolve(f.state);
  552. await preparing;
  553. await reading;
  554. }
  555. await until(async () =>
  556. expect(await f.read()).toMatchObject({
  557. kind: "ready",
  558. profiles: [{ systemPrompt: "new" }],
  559. }),
  560. );
  561. expect(f.readState).toHaveBeenCalledOnce();
  562. if (mode === "reload") expect(before).toMatchObject({ profiles: [{ systemPrompt: "old" }] });
  563. },
  564. );
  565. it.each(["dispose", "replace"])("ignores a timed-out initial load after %s", async (action) => {
  566. const f = await fixture();
  567. const path = join(f.userRoot, "a.md");
  568. await writeFile(path, markdown("aaa"));
  569. const gate = Promise.withResolvers<typeof f.state>();
  570. f.readState.mockReturnValueOnce(gate.promise);
  571. let prepared = false;
  572. const preparing = f.cache.prepare(f.workspace).then(() => {
  573. prepared = true;
  574. });
  575. try {
  576. await vi.waitFor(() => expect(prepared).toBe(true), { timeout: 6500 });
  577. expect(await f.read()).toEqual({ kind: "built-in-fallback" });
  578. if (action === "dispose") f.cache.dispose();
  579. else {
  580. await writeFile(path, markdown("aaa", "replacement"));
  581. await f.cache.prepare(f.workspace);
  582. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "replacement" }] });
  583. }
  584. } finally {
  585. // 已替换的读取不能用旧禁用状态覆盖新范围;销毁后不能重新发布。
  586. gate.resolve({ ...f.state, disabledAgentIds: ["user:user:aaa"] });
  587. await preparing;
  588. // preparing 已提前返回;让迟到读取的微任务链完成后再检查隔离结果。
  589. await new Promise<void>((resolve) => setImmediate(resolve));
  590. }
  591. if (action === "dispose") await expect(f.read()).rejects.toThrow(/disposed/i);
  592. else expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "replacement" }] });
  593. });
  594. it("isolates project failure and workspace identities, ignores nested profiles and preserves duplicate precedence", async () => {
  595. const f = await fixture();
  596. const project = join(f.workspace.workspacePath, ".zcode", "agents");
  597. await mkdir(project, { recursive: true });
  598. await writeFile(join(project, "a.md"), markdown("same", "project"));
  599. const nestedDirectories = [join(project, "deep"), join(f.userRoot, "deep")];
  600. for (const directory of nestedDirectories) {
  601. await mkdir(directory, { recursive: true });
  602. await writeFile(join(directory, "ignored.markdown"), markdown("nested"));
  603. }
  604. await writeFile(join(f.userRoot, "a.md"), markdown("same", "user"));
  605. await f.cache.prepare(f.workspace);
  606. const other = { workspacePath: join(f.root, "other"), workspaceIdentity: "remote:other" };
  607. await f.cache.prepare(other);
  608. const own = await f.read();
  609. expect(own).toMatchObject({
  610. profiles: [{ systemPrompt: "user" }, { systemPrompt: "project" }],
  611. });
  612. expect(await f.cache.read(other)).toMatchObject({ profiles: [{ systemPrompt: "user" }] });
  613. await f.cache.prepare(f.workspace);
  614. expect(await f.read()).toEqual(own);
  615. for (const directory of nestedDirectories) {
  616. expect(vi.mocked(fs.readdir).mock.calls.map(([path]) => path)).not.toContain(directory);
  617. expect(vi.mocked(fs.readFile).mock.calls.map(([path]) => path)).not.toContain(
  618. join(directory, "ignored.markdown"),
  619. );
  620. }
  621. const fail = vi.spyOn(fs, "readFile");
  622. fail.mockRejectedValueOnce(new Error("project unreadable"));
  623. f.emit(join(project, "bad.md"), "add", project);
  624. await until(async () => expect(await f.read()).toEqual({ kind: "built-in-fallback" }));
  625. expect(await f.cache.read(other)).toMatchObject({ profiles: [{ systemPrompt: "user" }] });
  626. fail.mockRestore();
  627. f.emit(join(project, "bad.md"), "unlink", project);
  628. await until(async () => expect(await f.read()).toEqual(own));
  629. });
  630. it("disposes before watcher readiness without hanging preparation", async () => {
  631. readiness.automatic = false;
  632. const f = await fixture();
  633. const preparing = f.cache.prepare(f.workspace);
  634. const rejected = expect(preparing).rejects.toThrow(/disposed/i);
  635. await until(() => expect(watched.size).toBe(3));
  636. f.cache.dispose();
  637. await rejected;
  638. });
  639. it("recovers initial failure on explicit reload and keeps same-path workspace identities separate", async () => {
  640. const f = await fixture();
  641. f.readState.mockRejectedValueOnce(new Error("initial unavailable"));
  642. await f.cache.prepare(f.workspace);
  643. expect(await f.read()).toEqual({ kind: "built-in-fallback" });
  644. await f.cache.prepare(f.workspace);
  645. const a = { ...f.workspace, workspaceIdentity: " test:a " };
  646. const b = { ...f.workspace, workspaceIdentity: "test:b" };
  647. await f.cache.prepare(a);
  648. await f.cache.prepare(b);
  649. expect(await f.cache.read({ ...a, workspaceIdentity: "test:a" })).toMatchObject({
  650. kind: "ready",
  651. });
  652. expect(await f.cache.read(b)).toMatchObject({ kind: "ready" });
  653. await expect(f.cache.read({ ...a, workspaceIdentity: "test:unknown" })).rejects.toThrow(
  654. /not prepared/,
  655. );
  656. });
  657. it("keeps the published snapshot after a watcher error until explicit reload rebuilds observation", async () => {
  658. const f = await fixture();
  659. const path = join(f.userRoot, "a.md");
  660. await writeFile(path, markdown("aaa", "old"));
  661. await f.cache.prepare(f.workspace);
  662. const before = await f.read();
  663. const watchers = [...watched];
  664. const subscriptions = vi.mocked(fs.watch).mock.calls.map(([, options]) => options?.signal);
  665. for (const watcher of watchers) watcher.emit("error", new Error("native watcher unavailable"));
  666. for (const events of parentEvents.values())
  667. for (const emitter of events) emitter.emit("error", new Error("parent watcher unavailable"));
  668. await writeFile(path, markdown("aaa", "updated"));
  669. expect(await f.read()).toEqual(before);
  670. expect([...watched]).toEqual(watchers);
  671. await f.cache.prepare(f.workspace);
  672. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "updated" }] });
  673. for (const watcher of watchers)
  674. expect((watcher as unknown as { close: unknown }).close).toHaveBeenCalled();
  675. for (const signal of subscriptions) expect(signal?.aborted).toBe(true);
  676. f.cache.dispose();
  677. for (const [, options] of vi.mocked(fs.watch).mock.calls)
  678. expect(options?.signal?.aborted).toBe(true);
  679. });
  680. });