watched-source-directories.test.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import { EventEmitter } from "node:events";
  2. import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { basename, join } from "node:path";
  5. import { afterEach, beforeEach, expect, it, vi } from "vitest";
  6. import {
  7. createWatchedEntry,
  8. WATCHED_SOURCE_DEBOUNCE_MS,
  9. type WatchedLoad,
  10. } from "../src/watch/watched-source.js";
  11. type Ignored = (path: string, stats?: Awaited<ReturnType<typeof stat>>) => boolean;
  12. const state = vi.hoisted(() => ({
  13. watchers: [] as Array<EventEmitter & { anchor: string; ignored: Ignored; closed: boolean }>,
  14. }));
  15. vi.mock("chokidar", () => ({
  16. watch: (anchor: string, options: { ignored: Ignored }) => {
  17. const watcher = Object.assign(new EventEmitter(), {
  18. anchor,
  19. ignored: options.ignored,
  20. closed: false,
  21. close: vi.fn(async () => {
  22. watcher.closed = true;
  23. }),
  24. });
  25. state.watchers.push(watcher);
  26. queueMicrotask(() => watcher.emit("ready"));
  27. return watcher;
  28. },
  29. }));
  30. let root: string;
  31. beforeEach(async () => {
  32. root = await mkdtemp(join(tmpdir(), "watched-source-directories-"));
  33. state.watchers = [];
  34. });
  35. afterEach(async () => {
  36. vi.useRealTimers();
  37. await rm(root, { recursive: true, force: true });
  38. });
  39. function open() {
  40. return state.watchers.filter((watcher) => !watcher.closed);
  41. }
  42. /** 每次 load 按当前磁盘重新给出监听集合,与真实加载器一致。 */
  43. function loaderOf(
  44. compute: () => Promise<Omit<WatchedLoad, "commit">> | Omit<WatchedLoad, "commit">,
  45. ) {
  46. const load = vi.fn(async () => ({ ...(await compute()), commit: () => {} }));
  47. return load;
  48. }
  49. it("watches an existing directory itself and admits only its direct child directories", async () => {
  50. const skills = join(root, "skills");
  51. await mkdir(join(skills, "existing"), { recursive: true });
  52. await writeFile(join(skills, "existing", "SKILL.md"), "---\nname: existing\n---\n");
  53. await writeFile(join(skills, "README.md"), "notes");
  54. const load = loaderOf(() => ({
  55. files: new Set([join(skills, "SKILL.md")]),
  56. directories: new Set([skills]),
  57. }));
  58. const entry = await createWatchedEntry({
  59. load,
  60. bounds: [root],
  61. childName: (name) => !name.startsWith("."),
  62. label: "Skill catalog",
  63. });
  64. try {
  65. expect(open().map((watcher) => watcher.anchor)).toEqual([skills]);
  66. const { ignored } = open()[0]!;
  67. const directory = await stat(join(skills, "existing"));
  68. const file = await stat(join(skills, "README.md"));
  69. expect(ignored(skills)).toBe(false);
  70. // 子目录在 depth 0 下不开句柄;新建、删除、改名都落在根目录的事件里。
  71. expect(ignored(join(skills, "existing"))).toBe(false);
  72. expect(ignored(join(skills, "existing"), directory)).toBe(false);
  73. expect(ignored(join(skills, "fresh"))).toBe(false);
  74. // 修复前 relevant 只认登记的文件及其祖先,新建的 skill 目录事件被丢掉。
  75. // 带文件类型时直接子文件不登记就不相关:chokidar 会给每个通过过滤的文件单独开句柄。
  76. expect(ignored(join(skills, "README.md"), file)).toBe(true);
  77. expect(ignored(join(skills, "SKILL.md"), file)).toBe(false);
  78. expect(ignored(join(skills, ".hidden"), directory)).toBe(true);
  79. expect(ignored(join(skills, "existing", "SKILL.md"), file)).toBe(true);
  80. expect(ignored(join(root, "elsewhere"), directory)).toBe(true);
  81. } finally {
  82. entry.close();
  83. }
  84. });
  85. it("reloads for a direct child directory event and ignores nested and filtered paths", async () => {
  86. const skills = join(root, "skills");
  87. await mkdir(skills, { recursive: true });
  88. const load = loaderOf(() => ({ files: new Set<string>(), directories: new Set([skills]) }));
  89. const entry = await createWatchedEntry({
  90. load,
  91. bounds: [root],
  92. childName: (name) => !name.startsWith("."),
  93. label: "Skill catalog",
  94. });
  95. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  96. try {
  97. const watcher = open()[0]!;
  98. const settle = async () => {
  99. await vi.advanceTimersByTimeAsync(WATCHED_SOURCE_DEBOUNCE_MS);
  100. await vi.advanceTimersByTimeAsync(0);
  101. await entry.flush();
  102. };
  103. const before = load.mock.calls.length;
  104. watcher.emit("raw", "rename", "nested", { watchedPath: join(skills, "child") });
  105. watcher.emit("raw", "rename", ".DS_Store", { watchedPath: skills });
  106. await vi.advanceTimersByTimeAsync(WATCHED_SOURCE_DEBOUNCE_MS * 2);
  107. expect(load.mock.calls.length).toBe(before);
  108. watcher.emit("raw", "rename", "fresh", { watchedPath: skills });
  109. await settle();
  110. expect(load.mock.calls.length).toBeGreaterThan(before);
  111. } finally {
  112. entry.close();
  113. }
  114. });
  115. it("anchors a missing directory inside its bound and moves to the directory once created", async () => {
  116. const base = join(root, "home", ".agents");
  117. const skills = join(base, "skills");
  118. const outside = join(root, "home", ".zcode", "skills");
  119. await mkdir(base, { recursive: true });
  120. const load = loaderOf(() => ({
  121. files: new Set<string>(),
  122. directories: new Set([skills, outside]),
  123. }));
  124. const entry = await createWatchedEntry({
  125. load,
  126. bounds: [base, join(root, "home", ".zcode")],
  127. childName: () => true,
  128. label: "Skill catalog",
  129. });
  130. try {
  131. // 边界目录本身不存在时不监听,不向上监听用户目录。
  132. expect(open().map((watcher) => watcher.anchor)).toEqual([base]);
  133. expect(open()[0]!.ignored(skills)).toBe(false);
  134. expect(open()[0]!.ignored(join(base, "other"))).toBe(true);
  135. await mkdir(skills);
  136. await entry.flush();
  137. expect(open().map((watcher) => watcher.anchor)).toEqual([skills]);
  138. } finally {
  139. entry.close();
  140. }
  141. });
  142. it("anchors a registered missing file on its existing directory and releases it once dropped", async () => {
  143. const skills = join(root, "skills");
  144. const pending = join(skills, "pending");
  145. await mkdir(pending, { recursive: true });
  146. const load = loaderOf(async () => {
  147. const candidate = join(pending, "SKILL.md");
  148. const exists = await stat(candidate).then(
  149. () => true,
  150. () => false,
  151. );
  152. return {
  153. files: new Set(exists ? [] : [candidate]),
  154. directories: new Set([skills]),
  155. };
  156. });
  157. const entry = await createWatchedEntry({
  158. load,
  159. bounds: [root],
  160. childName: () => true,
  161. label: "Skill catalog",
  162. });
  163. try {
  164. expect(
  165. open()
  166. .map((watcher) => watcher.anchor)
  167. .toSorted(),
  168. ).toEqual([pending, skills].toSorted());
  169. const temporary = open().find((watcher) => watcher.anchor === pending)!;
  170. expect(temporary.ignored(join(pending, "SKILL.md"))).toBe(false);
  171. expect(temporary.ignored(join(pending, "notes.md"))).toBe(true);
  172. await writeFile(join(pending, "SKILL.md"), "---\nname: pending\n---\n");
  173. await entry.flush();
  174. expect(open().map((watcher) => basename(watcher.anchor))).toEqual(["skills"]);
  175. } finally {
  176. entry.close();
  177. }
  178. });