subagentRuntimeConfig.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. import { mkdtemp, mkdir, 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. await rm(f.userRoot, { recursive: true });
  235. await mkdir(f.userRoot);
  236. await writeFile(path, markdown("aaa", "replacement"));
  237. // 快速替换时可能只有原生事件;路径仍存在,也必须关闭旧目录对象的监听。
  238. for (const events of parentEvents.get(dirname(f.userRoot)) ?? [])
  239. events.emit("change", { eventType: "rename", filename: "user" });
  240. await until(() =>
  241. expect((obsolete as unknown as { close: unknown }).close).toHaveBeenCalledOnce(),
  242. );
  243. gate.resolve(markdown("aaa", "obsolete"));
  244. await until(async () =>
  245. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "replacement" }] }),
  246. );
  247. expect(
  248. vi
  249. .mocked(shared.parseAgentProfileFromMarkdown)
  250. .mock.calls.some(([input]) => input.content.includes("obsolete")),
  251. ).toBe(false);
  252. });
  253. it("rebinds before publishing child unlinks when the directory unlink notification is late", async () => {
  254. const f = await fixture();
  255. const path = join(f.userRoot, "a.md");
  256. await writeFile(path, markdown("aaa"));
  257. await f.cache.prepare(f.workspace);
  258. const obsolete = initialWatcherFor(f.userRoot);
  259. await rm(f.userRoot, { recursive: true });
  260. // 原生库可先发文件 unlink;目录检查完成前就重建,会让它不再发 unlinkDir。
  261. obsolete.emit("all", "unlink", path);
  262. await until(async () => expect(await f.read()).toMatchObject({ profiles: [] }));
  263. expect((obsolete as unknown as { close: unknown }).close).toHaveBeenCalledOnce();
  264. await mkdir(f.userRoot);
  265. await writeFile(path, markdown("aaa", "recreated"));
  266. f.emit(f.userRoot, "addDir");
  267. await until(async () =>
  268. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "recreated" }] }),
  269. );
  270. });
  271. it("parses changed files once, never rereads other scopes, and returns independent memory copies", async () => {
  272. const f = await fixture();
  273. const a = join(f.userRoot, "a.md"),
  274. b = join(f.userRoot, "b.markdown");
  275. await writeFile(a, markdown("aaa"));
  276. await writeFile(b, markdown("bbb"));
  277. await f.cache.prepare(f.workspace);
  278. const readFile = vi.spyOn(fs, "readFile"),
  279. readdir = vi.spyOn(fs, "readdir"),
  280. parse = vi.spyOn(shared, "parseAgentProfileFromMarkdown");
  281. readFile.mockClear();
  282. readdir.mockClear();
  283. parse.mockClear();
  284. const before = await f.read();
  285. await writeFile(a, markdown("aaa", "new"));
  286. f.emit(a);
  287. f.emit(a);
  288. await until(async () =>
  289. expect(await f.read()).toMatchObject({
  290. kind: "ready",
  291. profiles: [{ systemPrompt: "new" }, { name: "bbb" }],
  292. }),
  293. );
  294. expect(readFile.mock.calls.map(([path]) => path)).toEqual([a]);
  295. expect(readdir).not.toHaveBeenCalled();
  296. expect(parse).toHaveBeenCalledTimes(1);
  297. f.state.disabledAgentIds = ["user:user:aaa"];
  298. f.emit(f.statePath, "change", join(f.root, "state"));
  299. await until(async () => expect(await f.read()).toMatchObject({ profiles: [{ name: "bbb" }] }));
  300. expect(readFile).toHaveBeenCalledTimes(1);
  301. expect(parse).toHaveBeenCalledTimes(1);
  302. await Promise.all(Array.from({ length: 10 }, f.read));
  303. expect(f.readState).toHaveBeenCalledTimes(2);
  304. expect(f.readState).toHaveBeenLastCalledWith(f.statePath);
  305. expect(before).toMatchObject({ profiles: [{ systemPrompt: "aaa" }, { name: "bbb" }] });
  306. const changed = await f.read();
  307. if (changed.kind === "ready") changed.profiles.length = 0;
  308. expect(await f.read()).toMatchObject({ profiles: [{ name: "bbb" }] });
  309. f.emit(join(f.userRoot, "ignored.txt"));
  310. f.emit(join(f.userRoot, "nested", "deep.md"));
  311. expect(readFile).toHaveBeenCalledTimes(1);
  312. });
  313. it("does not postpone a pending file batch when an unrelated parent event arrives", async () => {
  314. const f = await fixture();
  315. const path = join(f.userRoot, "a.md");
  316. await writeFile(path, markdown("aaa", "old"));
  317. await f.cache.prepare(f.workspace);
  318. const stats = await fs.stat(f.userRoot);
  319. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  320. vi.mocked(fs.stat).mockImplementation((path, options) =>
  321. path === f.userRoot
  322. ? (Promise.resolve(stats) as ReturnType<typeof fs.stat>)
  323. : actual.stat(path, options),
  324. );
  325. await writeFile(path, markdown("aaa", "new"));
  326. vi.mocked(fs.readFile).mockClear();
  327. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  328. try {
  329. f.emit(path);
  330. await vi.advanceTimersByTimeAsync(200);
  331. for (const events of parentEvents.get(dirname(f.userRoot)) ?? [])
  332. events.emit("change", { eventType: "rename", filename: "unrelated" });
  333. await vi.advanceTimersByTimeAsync(100);
  334. // 父目录检查不应重新开始文件批次的 300ms 合并窗口。
  335. expect(fs.readFile).toHaveBeenCalledWith(path, "utf8");
  336. await until(async () =>
  337. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "new" }] }),
  338. );
  339. } finally {
  340. vi.useRealTimers();
  341. }
  342. });
  343. it.each(["resolve", "reject"])(
  344. "keeps old snapshots during load and ignores stale %s without losing another changed file",
  345. async (completion) => {
  346. const f = await fixture();
  347. const a = join(f.userRoot, "a.md"),
  348. b = join(f.userRoot, "b.md");
  349. await writeFile(a, markdown("aaa"));
  350. await writeFile(b, markdown("bbb"));
  351. await f.cache.prepare(f.workspace);
  352. const before = await f.read();
  353. const gate = Promise.withResolvers<string>();
  354. const original = (
  355. await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises")
  356. ).readFile;
  357. let first = true;
  358. vi.spyOn(fs, "readFile").mockImplementation(((path: unknown, ...args: unknown[]) => {
  359. if (path === a && first) {
  360. first = false;
  361. return gate.promise;
  362. }
  363. return Reflect.apply(original, fs, [path, ...args]);
  364. }) as typeof fs.readFile);
  365. f.emit(a);
  366. await until(() => expect(first).toBe(false));
  367. expect(await Promise.all([f.read(), f.read()])).toEqual([before, before]);
  368. await writeFile(a, markdown("aaa", "latest-a"));
  369. await writeFile(b, markdown("bbb", "latest-b"));
  370. f.emit(a);
  371. f.emit(b);
  372. if (completion === "resolve") gate.resolve(markdown("aaa", "stale"));
  373. else gate.reject(new Error("stale"));
  374. await until(async () =>
  375. expect(await f.read()).toMatchObject({
  376. kind: "ready",
  377. profiles: [{ systemPrompt: "latest-a" }, { systemPrompt: "latest-b" }],
  378. }),
  379. );
  380. },
  381. );
  382. it("publishes fallback to concurrent readers without retrying on read, then recovers on a file event", async () => {
  383. const f = await fixture();
  384. await writeFile(join(f.userRoot, "a.md"), markdown("aaa"));
  385. await f.cache.prepare(f.workspace);
  386. f.readState.mockRejectedValue(new Error("state unavailable"));
  387. f.emit(f.statePath, "change", join(f.root, "state"));
  388. await until(async () => expect(await f.read()).toEqual({ kind: "built-in-fallback" }));
  389. const calls = f.readState.mock.calls.length;
  390. expect(await Promise.all([f.read(), f.read()])).toEqual([
  391. { kind: "built-in-fallback" },
  392. { kind: "built-in-fallback" },
  393. ]);
  394. expect(f.readState).toHaveBeenCalledTimes(calls);
  395. const retry = Promise.withResolvers<typeof f.state>();
  396. f.readState.mockReturnValueOnce(retry.promise);
  397. try {
  398. f.emit(f.statePath, "change", join(f.root, "state"));
  399. await until(() => expect(f.readState).toHaveBeenCalledTimes(calls + 1));
  400. // 真正读取失败后,重载完成前仍不可用,不能因允许临时回退恢复而重新启用旧值。
  401. expect(await Promise.all([f.read(), f.read()])).toEqual([
  402. { kind: "built-in-fallback" },
  403. { kind: "built-in-fallback" },
  404. ]);
  405. } finally {
  406. retry.resolve(f.state);
  407. }
  408. await until(async () =>
  409. expect(await f.read()).toMatchObject({ kind: "ready", profiles: [{ name: "aaa" }] }),
  410. );
  411. });
  412. it("waits for initialization, absorbs initial changes, and prevents late publication after disposal", async () => {
  413. const f = await fixture();
  414. const gate = Promise.withResolvers<typeof f.state>();
  415. f.readState.mockReturnValueOnce(gate.promise);
  416. const preparing = f.cache.prepare(f.workspace);
  417. await until(() => expect(f.readState).toHaveBeenCalledTimes(1));
  418. let done = false;
  419. const reading = f.read().then((v) => {
  420. done = true;
  421. return v;
  422. });
  423. await Promise.resolve();
  424. expect(done).toBe(false);
  425. const a = join(f.userRoot, "a.md");
  426. await writeFile(a, markdown("aaa"));
  427. f.emit(a, "add");
  428. gate.resolve(f.state);
  429. await preparing;
  430. expect(await reading).toMatchObject({ profiles: [{ name: "aaa" }] });
  431. const late = Promise.withResolvers<typeof f.state>();
  432. f.readState.mockReturnValueOnce(late.promise);
  433. f.emit(f.statePath, "change", join(f.root, "state"));
  434. await until(() => expect(f.readState).toHaveBeenCalledTimes(2));
  435. f.cache.dispose();
  436. late.resolve(f.state);
  437. await expect(f.read()).rejects.toThrow(/disposed/i);
  438. for (const watcher of watched.values())
  439. expect((watcher as unknown as { close: unknown }).close).toHaveBeenCalled();
  440. });
  441. it.each(["ready", "timeout"])(
  442. "reuses completed shared data with %s project initialization",
  443. async (mode) => {
  444. const f = await fixture();
  445. const path = join(f.userRoot, "a.md");
  446. await writeFile(path, markdown("aaa", "old"));
  447. await f.cache.prepare(f.workspace);
  448. const before = await f.read();
  449. const gate = Promise.withResolvers<string>();
  450. const others = ["b", "c"].map((name) => ({ workspacePath: join(f.root, name) }));
  451. const projectPath = join(others[0]!.workspacePath, ".zcode", "agents", "b.md");
  452. await mkdir(dirname(projectPath), { recursive: true });
  453. await writeFile(projectPath, markdown("bbb", "project"));
  454. const project = Promise.withResolvers<string>();
  455. const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  456. vi.mocked(fs.readFile).mockImplementation(((readPath, ...args) => {
  457. if (readPath === path) return gate.promise;
  458. if (readPath === projectPath) return project.promise;
  459. return Reflect.apply(actual.readFile, fs, [readPath, ...args]);
  460. }) as typeof fs.readFile);
  461. f.emit(path);
  462. await until(() =>
  463. expect(vi.mocked(fs.readFile).mock.results.some((r) => r.value === gate.promise)).toBe(
  464. true,
  465. ),
  466. );
  467. if (mode === "ready") project.resolve(markdown("bbb", "project"));
  468. const completed: string[] = [];
  469. // 与 service 写队列一样顺序准备,不能为同一共享后台刷新反复等待。
  470. const preparing = (async () => {
  471. for (const workspace of others) {
  472. await f.cache.prepare(workspace);
  473. completed.push(workspace.workspacePath);
  474. }
  475. })();
  476. try {
  477. if (mode === "timeout") {
  478. await vi.waitFor(() => expect(completed).toContain(others[0]!.workspacePath), {
  479. timeout: 6500,
  480. });
  481. expect(await f.cache.read(others[0]!)).toEqual({ kind: "built-in-fallback" });
  482. project.resolve(markdown("bbb", "project"));
  483. }
  484. await vi.waitFor(() => expect(completed).toHaveLength(2), { timeout: 4000 });
  485. expect(await f.read()).toEqual(before);
  486. expect(await f.cache.read(others[1]!)).toEqual(before);
  487. // B 超时过也应和 C 一样复用共享完整结果,不能等共享后台刷新结束才恢复。
  488. await until(async () =>
  489. expect(await f.cache.read(others[0]!)).toMatchObject({
  490. kind: "ready",
  491. profiles: [{ systemPrompt: "old" }, { systemPrompt: "project" }],
  492. }),
  493. );
  494. expect(f.readState).toHaveBeenCalledOnce();
  495. expect(vi.mocked(fs.readFile).mock.calls.filter(([p]) => p === path)).toHaveLength(2);
  496. } finally {
  497. project.resolve(markdown("bbb", "project"));
  498. gate.resolve(markdown("aaa", "new"));
  499. await preparing;
  500. }
  501. await until(async () => {
  502. for (const workspace of [f.workspace, others[1]!])
  503. expect(await f.cache.read(workspace)).toMatchObject({
  504. profiles: [{ systemPrompt: "new" }],
  505. });
  506. expect(await f.cache.read(others[0]!)).toMatchObject({
  507. profiles: [{ systemPrompt: "new" }, { systemPrompt: "project" }],
  508. });
  509. });
  510. expect(before).toMatchObject({ profiles: [{ systemPrompt: "old" }] });
  511. },
  512. );
  513. it.each(["initial", "reload"])(
  514. "bounds %s waiting and publishes late completion without another file event",
  515. async (mode) => {
  516. const f = await fixture();
  517. const path = join(f.userRoot, "a.md");
  518. await writeFile(path, markdown("aaa", "old"));
  519. let before: Awaited<ReturnType<typeof f.read>> = { kind: "built-in-fallback" };
  520. if (mode === "reload") {
  521. await f.cache.prepare(f.workspace);
  522. before = await f.read();
  523. }
  524. await writeFile(path, markdown("aaa", "new"));
  525. const gate = Promise.withResolvers<typeof f.state>();
  526. f.readState.mockClear().mockReturnValueOnce(gate.promise);
  527. const started = performance.now();
  528. let prepared = false;
  529. const preparing = f.cache.prepare(f.workspace).then(() => {
  530. prepared = true;
  531. });
  532. let reading: Promise<unknown> | undefined;
  533. try {
  534. await until(() => expect(f.readState).toHaveBeenCalledOnce());
  535. let readDone = false;
  536. reading = f.read().then((snapshot) => {
  537. readDone = true;
  538. return snapshot;
  539. });
  540. expect(prepared).toBe(false);
  541. await vi.waitFor(() => expect(prepared && readDone).toBe(true), { timeout: 6500 });
  542. expect(performance.now() - started).toBeGreaterThanOrEqual(4900);
  543. expect(await reading).toEqual(before);
  544. const fileReads = vi.mocked(fs.readFile).mock.calls.length;
  545. expect(await Promise.all([f.read(), f.read()])).toEqual([before, before]);
  546. expect(fs.readFile).toHaveBeenCalledTimes(fileReads);
  547. expect(f.readState).toHaveBeenCalledOnce();
  548. } finally {
  549. gate.resolve(f.state);
  550. await preparing;
  551. await reading;
  552. }
  553. await until(async () =>
  554. expect(await f.read()).toMatchObject({
  555. kind: "ready",
  556. profiles: [{ systemPrompt: "new" }],
  557. }),
  558. );
  559. expect(f.readState).toHaveBeenCalledOnce();
  560. if (mode === "reload") expect(before).toMatchObject({ profiles: [{ systemPrompt: "old" }] });
  561. },
  562. );
  563. it.each(["dispose", "replace"])("ignores a timed-out initial load after %s", async (action) => {
  564. const f = await fixture();
  565. const path = join(f.userRoot, "a.md");
  566. await writeFile(path, markdown("aaa"));
  567. const gate = Promise.withResolvers<typeof f.state>();
  568. f.readState.mockReturnValueOnce(gate.promise);
  569. let prepared = false;
  570. const preparing = f.cache.prepare(f.workspace).then(() => {
  571. prepared = true;
  572. });
  573. try {
  574. await vi.waitFor(() => expect(prepared).toBe(true), { timeout: 6500 });
  575. expect(await f.read()).toEqual({ kind: "built-in-fallback" });
  576. if (action === "dispose") f.cache.dispose();
  577. else {
  578. await writeFile(path, markdown("aaa", "replacement"));
  579. await f.cache.prepare(f.workspace);
  580. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "replacement" }] });
  581. }
  582. } finally {
  583. // 已替换的读取不能用旧禁用状态覆盖新范围;销毁后不能重新发布。
  584. gate.resolve({ ...f.state, disabledAgentIds: ["user:user:aaa"] });
  585. await preparing;
  586. // preparing 已提前返回;让迟到读取的微任务链完成后再检查隔离结果。
  587. await new Promise<void>((resolve) => setImmediate(resolve));
  588. }
  589. if (action === "dispose") await expect(f.read()).rejects.toThrow(/disposed/i);
  590. else expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "replacement" }] });
  591. });
  592. it("isolates project failure and workspace identities, ignores nested profiles and preserves duplicate precedence", async () => {
  593. const f = await fixture();
  594. const project = join(f.workspace.workspacePath, ".zcode", "agents");
  595. await mkdir(project, { recursive: true });
  596. await writeFile(join(project, "a.md"), markdown("same", "project"));
  597. const nestedDirectories = [join(project, "deep"), join(f.userRoot, "deep")];
  598. for (const directory of nestedDirectories) {
  599. await mkdir(directory, { recursive: true });
  600. await writeFile(join(directory, "ignored.markdown"), markdown("nested"));
  601. }
  602. await writeFile(join(f.userRoot, "a.md"), markdown("same", "user"));
  603. await f.cache.prepare(f.workspace);
  604. const other = { workspacePath: join(f.root, "other"), workspaceIdentity: "remote:other" };
  605. await f.cache.prepare(other);
  606. const own = await f.read();
  607. expect(own).toMatchObject({
  608. profiles: [{ systemPrompt: "user" }, { systemPrompt: "project" }],
  609. });
  610. expect(await f.cache.read(other)).toMatchObject({ profiles: [{ systemPrompt: "user" }] });
  611. await f.cache.prepare(f.workspace);
  612. expect(await f.read()).toEqual(own);
  613. for (const directory of nestedDirectories) {
  614. expect(vi.mocked(fs.readdir).mock.calls.map(([path]) => path)).not.toContain(directory);
  615. expect(vi.mocked(fs.readFile).mock.calls.map(([path]) => path)).not.toContain(
  616. join(directory, "ignored.markdown"),
  617. );
  618. }
  619. const fail = vi.spyOn(fs, "readFile");
  620. fail.mockRejectedValueOnce(new Error("project unreadable"));
  621. f.emit(join(project, "bad.md"), "add", project);
  622. await until(async () => expect(await f.read()).toEqual({ kind: "built-in-fallback" }));
  623. expect(await f.cache.read(other)).toMatchObject({ profiles: [{ systemPrompt: "user" }] });
  624. fail.mockRestore();
  625. f.emit(join(project, "bad.md"), "unlink", project);
  626. await until(async () => expect(await f.read()).toEqual(own));
  627. });
  628. it("disposes before watcher readiness without hanging preparation", async () => {
  629. readiness.automatic = false;
  630. const f = await fixture();
  631. const preparing = f.cache.prepare(f.workspace);
  632. const rejected = expect(preparing).rejects.toThrow(/disposed/i);
  633. await until(() => expect(watched.size).toBe(3));
  634. f.cache.dispose();
  635. await rejected;
  636. });
  637. it("recovers initial failure on explicit reload and keeps same-path workspace identities separate", async () => {
  638. const f = await fixture();
  639. f.readState.mockRejectedValueOnce(new Error("initial unavailable"));
  640. await f.cache.prepare(f.workspace);
  641. expect(await f.read()).toEqual({ kind: "built-in-fallback" });
  642. await f.cache.prepare(f.workspace);
  643. const a = { ...f.workspace, workspaceIdentity: " test:a " };
  644. const b = { ...f.workspace, workspaceIdentity: "test:b" };
  645. await f.cache.prepare(a);
  646. await f.cache.prepare(b);
  647. expect(await f.cache.read({ ...a, workspaceIdentity: "test:a" })).toMatchObject({
  648. kind: "ready",
  649. });
  650. expect(await f.cache.read(b)).toMatchObject({ kind: "ready" });
  651. await expect(f.cache.read({ ...a, workspaceIdentity: "test:unknown" })).rejects.toThrow(
  652. /not prepared/,
  653. );
  654. });
  655. it("keeps the published snapshot after a watcher error until explicit reload rebuilds observation", async () => {
  656. const f = await fixture();
  657. const path = join(f.userRoot, "a.md");
  658. await writeFile(path, markdown("aaa", "old"));
  659. await f.cache.prepare(f.workspace);
  660. const before = await f.read();
  661. const watchers = [...watched];
  662. const subscriptions = vi.mocked(fs.watch).mock.calls.map(([, options]) => options?.signal);
  663. for (const watcher of watchers) watcher.emit("error", new Error("native watcher unavailable"));
  664. for (const events of parentEvents.values())
  665. for (const emitter of events) emitter.emit("error", new Error("parent watcher unavailable"));
  666. await writeFile(path, markdown("aaa", "updated"));
  667. expect(await f.read()).toEqual(before);
  668. expect([...watched]).toEqual(watchers);
  669. await f.cache.prepare(f.workspace);
  670. expect(await f.read()).toMatchObject({ profiles: [{ systemPrompt: "updated" }] });
  671. for (const watcher of watchers)
  672. expect((watcher as unknown as { close: unknown }).close).toHaveBeenCalled();
  673. for (const signal of subscriptions) expect(signal?.aborted).toBe(true);
  674. f.cache.dispose();
  675. for (const [, options] of vi.mocked(fs.watch).mock.calls)
  676. expect(options?.signal?.aborted).toBe(true);
  677. });
  678. });