workflow-blocked-reminder-clock.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. // ============================================================
  2. // 「主代理闲着、run 还欠着决定」的提醒钟(docs/dynamic-workflow/transcript-and-notifications.md
  3. // 「Reminding an idle main agent」)
  4. // ============================================================
  5. // 直接钉钟本身:它量的是**会话空闲了多久**而不是决定开了多久;每个 run 至多两次(15 分钟、再 30 分钟);
  6. // 开着什么永远在到点那一刻现读;只有用户发话或该 run 的开集变化才重新给一对。
  7. // 宿主是手写桩:手动时钟 + 手动定时器,一毫秒都不真等。
  8. import { describe, expect, it } from "vitest";
  9. import {
  10. WorkflowBlockedReminderClock,
  11. type WorkflowBlockedReminder,
  12. type WorkflowOpenDecisions,
  13. } from "../src/runtime-task/workflow-blocked-reminder.js";
  14. const MIN = 60_000;
  15. // 使用规格时间推进钟;不从实现读取期望值,避免延迟改错后测试跟着通过。
  16. const FIRST = 15 * MIN;
  17. const SECOND = 30 * MIN;
  18. function question(qid: string, askedAt = 0): WorkflowOpenDecisions["questions"][number] {
  19. return { qid, actor: "actor#1@1", question: `q ${qid}`, askedAt };
  20. }
  21. function hole(siteId: string, since = 0): WorkflowOpenDecisions["holes"][number] {
  22. return { siteId, ordinal: 1, name: siteId, type: "Plan", state: "waiting", since };
  23. }
  24. interface Harness {
  25. clock: WorkflowBlockedReminderClock;
  26. /** 每个 run 此刻开着的决定;缺席即没有。测试随手改它来模拟作答 / 补全。 */
  27. open: Map<string, WorkflowOpenDecisions>;
  28. live: Set<string>;
  29. sent: WorkflowBlockedReminder[];
  30. reads: string[];
  31. idle: { value: boolean };
  32. /** 推进手动时钟并触发到点的定时器(含回调里新排的),再让异步读快照落定。 */
  33. advance(ms: number): Promise<void>;
  34. /** 一轮开始又结束:钟先停、空闲沿再起。 */
  35. turn(durationMs?: number): Promise<void>;
  36. pendingTimers(): number;
  37. }
  38. function harness(): Harness {
  39. let now = 0;
  40. let nextTimerId = 0;
  41. const timers = new Map<number, { at: number; callback: () => void }>();
  42. const open = new Map<string, WorkflowOpenDecisions>();
  43. const live = new Set<string>();
  44. const sent: WorkflowBlockedReminder[] = [];
  45. const reads: string[] = [];
  46. const idle = { value: true };
  47. const clock = new WorkflowBlockedReminderClock({
  48. isIdle: () => idle.value,
  49. liveRunIds: () => [...live],
  50. now: () => now,
  51. readOpen: async (runId) => {
  52. reads.push(runId);
  53. return open.get(runId);
  54. },
  55. remind: (reminder) => {
  56. sent.push(reminder);
  57. },
  58. setTimer: (callback, delayMs) => {
  59. const id = nextTimerId++;
  60. timers.set(id, { at: now + delayMs, callback });
  61. return () => timers.delete(id);
  62. },
  63. });
  64. const settle = async (): Promise<void> => {
  65. for (let i = 0; i < 20; i++) await Promise.resolve();
  66. };
  67. const advance = async (ms: number): Promise<void> => {
  68. const target = now + ms;
  69. for (;;) {
  70. const due = [...timers.entries()]
  71. .filter(([, timer]) => timer.at <= target)
  72. .sort((a, b) => a[1].at - b[1].at)[0];
  73. if (due === undefined) break;
  74. timers.delete(due[0]);
  75. now = due[1].at;
  76. due[1].callback();
  77. await settle();
  78. }
  79. now = target;
  80. await settle();
  81. };
  82. return {
  83. advance,
  84. clock,
  85. idle,
  86. live,
  87. open,
  88. pendingTimers: () => timers.size,
  89. reads,
  90. sent,
  91. turn: async (durationMs = 0) => {
  92. idle.value = false;
  93. clock.sessionBusy();
  94. await advance(durationMs);
  95. idle.value = true;
  96. clock.sessionIdle();
  97. },
  98. };
  99. }
  100. describe("WorkflowBlockedReminderClock", () => {
  101. it("没有在飞的 run:空闲沿什么也不排", async () => {
  102. const h = harness();
  103. h.clock.sessionIdle();
  104. expect(h.pendingTimers()).toBe(0);
  105. await h.advance(2 * 60 * MIN);
  106. expect(h.sent).toEqual([]);
  107. expect(h.reads).toEqual([]);
  108. });
  109. it("空闲满 15 分钟且 run 还欠着决定:恰好一条提醒,载着到点那一刻读到的开集", async () => {
  110. const h = harness();
  111. h.live.add("run-a");
  112. h.open.set("run-a", { questions: [question("q1")], holes: [hole("hole#1")] });
  113. h.clock.sessionIdle();
  114. await h.advance(FIRST - 1);
  115. expect(h.sent).toEqual([]);
  116. // 到点之前不读快照:钟不是轮询。
  117. expect(h.reads).toEqual([]);
  118. await h.advance(1);
  119. expect(h.sent).toHaveLength(1);
  120. expect(h.sent[0]).toMatchObject({ runId: "run-a", ordinal: 1, total: 2, now: FIRST });
  121. expect(h.sent[0]?.open.questions.map((q) => q.qid)).toEqual(["q1"]);
  122. expect(h.sent[0]?.open.holes.map((entry) => entry.siteId)).toEqual(["hole#1"]);
  123. });
  124. it("到点时已经没有开着的决定:不提醒,也不烧掉这个 run 的次数", async () => {
  125. const h = harness();
  126. h.live.add("run-a");
  127. h.clock.sessionIdle();
  128. await h.advance(FIRST);
  129. expect(h.reads).toEqual(["run-a"]);
  130. expect(h.sent).toEqual([]);
  131. // 之后它真的停住了(经一轮通知),下一个空闲沿起仍是第 1 次。
  132. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  133. await h.turn();
  134. await h.advance(FIRST);
  135. expect(h.sent.map((r) => r.ordinal)).toEqual([1]);
  136. });
  137. it("量的是空闲时长:任何一轮开始都让钟归零,决定开了多久不算数", async () => {
  138. const h = harness();
  139. h.live.add("run-a");
  140. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  141. h.clock.sessionIdle();
  142. await h.advance(FIRST - MIN);
  143. // 第 14 分钟来了一轮(跑了 40 分钟):钟停着,这 40 分钟里一条提醒都没有。
  144. await h.turn(40 * MIN);
  145. expect(h.sent).toEqual([]);
  146. await h.advance(FIRST - 1);
  147. expect(h.sent).toEqual([]);
  148. await h.advance(1);
  149. expect(h.sent).toHaveLength(1);
  150. });
  151. it("第二条在第一条那一轮结束后再空闲 30 分钟;之后不再有", async () => {
  152. const h = harness();
  153. h.live.add("run-a");
  154. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  155. h.clock.sessionIdle();
  156. await h.advance(FIRST);
  157. expect(h.sent.map((r) => r.ordinal)).toEqual([1]);
  158. // 提醒自己唤起一轮(模型没作答就收了尾)。
  159. await h.turn(MIN);
  160. await h.advance(SECOND - 1);
  161. expect(h.sent).toHaveLength(1);
  162. await h.advance(1);
  163. expect(h.sent.map((r) => r.ordinal)).toEqual([1, 2]);
  164. await h.turn(MIN);
  165. await h.advance(24 * 60 * MIN);
  166. expect(h.sent).toHaveLength(2);
  167. // 两次用完后连钟都不排:没有在后台空转的定时器。
  168. expect(h.pendingTimers()).toBe(0);
  169. });
  170. it("别的后台通知唤起的一轮不是新的开始:次数不清零", async () => {
  171. const h = harness();
  172. h.live.add("run-a");
  173. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  174. h.clock.sessionIdle();
  175. await h.advance(FIRST);
  176. await h.turn();
  177. await h.advance(SECOND);
  178. expect(h.sent).toHaveLength(2);
  179. for (let i = 0; i < 5; i++) {
  180. await h.turn(MIN);
  181. await h.advance(SECOND);
  182. }
  183. expect(h.sent).toHaveLength(2);
  184. });
  185. it("用户发话给每个 run 一对新的提醒", async () => {
  186. const h = harness();
  187. h.live.add("run-a");
  188. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  189. h.clock.sessionIdle();
  190. await h.advance(FIRST);
  191. await h.turn();
  192. await h.advance(SECOND);
  193. expect(h.sent).toHaveLength(2);
  194. h.clock.userSpoke();
  195. await h.turn(MIN);
  196. await h.advance(FIRST);
  197. expect(h.sent.map((r) => r.ordinal)).toEqual([1, 2, 1]);
  198. });
  199. it("该 run 的开集变化给它一对新的提醒,别的 run 不受影响", async () => {
  200. const h = harness();
  201. h.live.add("run-a");
  202. h.live.add("run-b");
  203. h.open.set("run-a", { questions: [question("a1"), question("a2")], holes: [] });
  204. h.open.set("run-b", { questions: [], holes: [hole("hole#b")] });
  205. h.clock.sessionIdle();
  206. await h.advance(FIRST);
  207. await h.turn();
  208. await h.advance(SECOND);
  209. expect(h.sent.map((r) => `${r.runId}:${r.ordinal}`)).toEqual([
  210. "run-a:1",
  211. "run-b:1",
  212. "run-a:2",
  213. "run-b:2",
  214. ]);
  215. // 主代理在一轮里答掉了 run-a 的一个问题(escalation-resolved)。
  216. h.idle.value = false;
  217. h.clock.sessionBusy();
  218. h.open.set("run-a", { questions: [question("a2")], holes: [] });
  219. h.clock.openSetChanged("run-a");
  220. h.idle.value = true;
  221. h.clock.sessionIdle();
  222. await h.advance(FIRST);
  223. expect(h.sent.slice(4).map((r) => `${r.runId}:${r.ordinal}`)).toEqual(["run-a:1"]);
  224. });
  225. it("空闲期间开集变化:空闲钟从那一刻重新起算", async () => {
  226. const h = harness();
  227. h.live.add("run-a");
  228. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  229. h.clock.sessionIdle();
  230. await h.advance(FIRST);
  231. await h.turn();
  232. await h.advance(SECOND);
  233. expect(h.sent).toHaveLength(2);
  234. await h.turn();
  235. // 空闲了 3 小时之后,这个 run 的开集变了(没有经过任何一轮)。
  236. await h.advance(180 * MIN);
  237. h.clock.openSetChanged("run-a");
  238. await h.advance(FIRST - 1);
  239. expect(h.sent).toHaveLength(2);
  240. await h.advance(1);
  241. expect(h.sent.map((r) => r.ordinal)).toEqual([1, 2, 1]);
  242. });
  243. it("次数各算各的:一个 run 用了一次、另一个还没用过,到点各按各的延迟", async () => {
  244. const h = harness();
  245. h.live.add("run-a");
  246. h.open.set("run-a", { questions: [question("a1")], holes: [] });
  247. h.clock.sessionIdle();
  248. await h.advance(FIRST);
  249. expect(h.sent.map((r) => `${r.runId}:${r.ordinal}`)).toEqual(["run-a:1"]);
  250. // run-b 在提醒那一轮里起来并停在一处留白上。
  251. h.idle.value = false;
  252. h.clock.sessionBusy();
  253. h.live.add("run-b");
  254. h.open.set("run-b", { questions: [], holes: [hole("hole#b")] });
  255. h.clock.openSetChanged("run-b");
  256. h.idle.value = true;
  257. h.clock.sessionIdle();
  258. await h.advance(FIRST);
  259. expect(h.sent.slice(1).map((r) => `${r.runId}:${r.ordinal}`)).toEqual(["run-b:1"]);
  260. });
  261. it("到点那一刻会话其实不闲(钟没来得及被停):不读、不发", async () => {
  262. const h = harness();
  263. h.live.add("run-a");
  264. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  265. h.clock.sessionIdle();
  266. h.idle.value = false;
  267. await h.advance(FIRST);
  268. expect(h.reads).toEqual([]);
  269. expect(h.sent).toEqual([]);
  270. });
  271. it("读快照期间来了一轮:作废这次到点,不在那一轮旁边再塞一条", async () => {
  272. let now = 0;
  273. const timers: { at: number; callback: () => void }[] = [];
  274. let release: (() => void) | undefined;
  275. const sent: WorkflowBlockedReminder[] = [];
  276. const clock = new WorkflowBlockedReminderClock({
  277. isIdle: () => true,
  278. liveRunIds: () => ["run-a"],
  279. now: () => now,
  280. readOpen: () =>
  281. new Promise((resolve) => {
  282. release = () => resolve({ questions: [question("q1")], holes: [] });
  283. }),
  284. remind: (reminder) => {
  285. sent.push(reminder);
  286. },
  287. setTimer: (callback, delayMs) => {
  288. const timer = { at: now + delayMs, callback };
  289. timers.push(timer);
  290. return () => {
  291. const index = timers.indexOf(timer);
  292. if (index >= 0) timers.splice(index, 1);
  293. };
  294. },
  295. });
  296. clock.sessionIdle();
  297. now = FIRST;
  298. timers.shift()?.callback();
  299. await Promise.resolve();
  300. clock.sessionBusy();
  301. release?.();
  302. for (let i = 0; i < 10; i++) await Promise.resolve();
  303. expect(sent).toEqual([]);
  304. });
  305. it("读快照抛错:这个 run 跳过,别的 run 照常提醒", async () => {
  306. const sent: WorkflowBlockedReminder[] = [];
  307. let fire: (() => void) | undefined;
  308. const clock = new WorkflowBlockedReminderClock({
  309. isIdle: () => true,
  310. liveRunIds: () => ["run-bad", "run-ok"],
  311. now: () => FIRST,
  312. readOpen: async (runId) => {
  313. if (runId === "run-bad") throw new Error("journal closed");
  314. return { questions: [question("q1")], holes: [] };
  315. },
  316. remind: (reminder) => {
  317. sent.push(reminder);
  318. },
  319. setTimer: (callback) => {
  320. fire = callback;
  321. return () => {};
  322. },
  323. });
  324. clock.sessionIdle();
  325. fire?.();
  326. for (let i = 0; i < 20; i++) await Promise.resolve();
  327. expect(sent.map((r) => r.runId)).toEqual(["run-ok"]);
  328. });
  329. it("不再在飞的 run:跳过,并忘掉它的次数", async () => {
  330. const h = harness();
  331. h.live.add("run-a");
  332. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  333. h.clock.sessionIdle();
  334. await h.advance(FIRST);
  335. expect(h.sent).toHaveLength(1);
  336. // run 结算了;同一个 id 之后被 resume 重臂,应当从第 1 次算起。
  337. h.live.delete("run-a");
  338. await h.turn();
  339. await h.advance(SECOND);
  340. expect(h.sent).toHaveLength(1);
  341. h.live.add("run-a");
  342. await h.turn();
  343. await h.advance(FIRST);
  344. expect(h.sent.map((r) => r.ordinal)).toEqual([1, 1]);
  345. });
  346. it("stop 之后一切静默:到点不发,空闲沿不再排", async () => {
  347. const h = harness();
  348. h.live.add("run-a");
  349. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  350. h.clock.sessionIdle();
  351. h.clock.stop();
  352. expect(h.pendingTimers()).toBe(0);
  353. await h.advance(FIRST);
  354. h.clock.sessionBusy();
  355. h.clock.sessionIdle();
  356. await h.advance(FIRST);
  357. expect(h.sent).toEqual([]);
  358. });
  359. it("重复的空闲沿不重置空闲时长(空排一次队列不是一轮)", async () => {
  360. const h = harness();
  361. h.live.add("run-a");
  362. h.open.set("run-a", { questions: [question("q1")], holes: [] });
  363. h.clock.sessionIdle();
  364. await h.advance(FIRST - MIN);
  365. h.clock.sessionIdle();
  366. await h.advance(MIN);
  367. expect(h.sent).toHaveLength(1);
  368. });
  369. });