dynamic-workflow-blocked-reminder.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. // ============================================================
  2. // 「run 还欠着决定、主代理闲着」的提醒:文案、载荷与 runtime 接线
  3. // (docs/dynamic-workflow/transcript-and-notifications.md「Reminding an idle main agent」)
  4. // ============================================================
  5. // 钟的规则在 workflow-blocked-reminder-clock.test.ts;这里钉另外三件事:
  6. // 1. 模型读到的 `<workflow-blocked>` 文本(逐字的下一步、两次的收尾句、截断诚实);
  7. // 2. runtime 宿主:从任务注册表取在飞的 run、从端口快照取开集、铸 `workflowBlocked` 载荷并走既有的后台通知入口;
  8. // 3. 四个接线点:队列排空 = 空闲沿、命令开始 = 忙、用户 prompt / steer = 新的一对、开集事件 = 该 run 新的一对。
  9. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  10. import {
  11. createSessionId,
  12. type BackgroundResultOriginMeta,
  13. type DynamicWorkflowRunPort,
  14. type DynamicWorkflowRunSnapshot,
  15. } from "@zcode/contracts";
  16. import { AgentRuntime } from "../src/index.js";
  17. import { createRuntimeCommandQueue } from "../src/runtime/command-queue.js";
  18. import type { RuntimeCommand, RuntimeCommandId } from "../src/runtime/command-queue.js";
  19. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  20. import { drainRuntimeCommandQueue } from "../src/runtime/methods/runtime-command-queue.js";
  21. import { steerTurn } from "../src/runtime/methods/steering.js";
  22. import { InMemoryRuntimeTaskRegistry } from "../src/runtime-task/registry.js";
  23. import {
  24. WORKFLOW_BLOCKED_REMINDER_DELAYS_MS,
  25. WorkflowBlockedReminderClock,
  26. } from "../src/runtime-task/workflow-blocked-reminder.js";
  27. import { formatWorkflowBlockedNotification } from "../src/runtime-task/workflow-notification-copy.js";
  28. import { createTestSessionEventStore } from "./test-event-store.js";
  29. const MIN = 60_000;
  30. const [FIRST, SECOND] = WORKFLOW_BLOCKED_REMINDER_DELAYS_MS;
  31. describe("formatWorkflowBlockedNotification", () => {
  32. const base = {
  33. runLabel: "nightly audit",
  34. runId: "dwfrun-1",
  35. now: 20 * MIN,
  36. questions: [
  37. {
  38. qid: "dwfq-aaaa-1",
  39. actor: "actor#1@2",
  40. actorName: "reviewer",
  41. question: "通过线是 96 还是 95?",
  42. context: "已经试了 6 轮。",
  43. askedAt: 3 * MIN,
  44. },
  45. ],
  46. holes: [
  47. {
  48. siteId: "hole#21b40fca",
  49. ordinal: 1,
  50. name: "修复方案",
  51. type: "Plan",
  52. state: "waiting" as const,
  53. since: 5 * MIN,
  54. line: 42,
  55. },
  56. ],
  57. draftPath: "/Users/dev/proj/.zcode/workflow-drafts/audit.dwf.ts",
  58. };
  59. it("第 1 次:块里是 run、次数与每个开着的决定;散文给逐字的下一步,并说还有一次", () => {
  60. const text = formatWorkflowBlockedNotification({ ...base, ordinal: 1, total: 2 });
  61. expect(text).toContain("[SYSTEM NOTIFICATION - NOT USER INPUT]");
  62. expect(text).toContain("<workflow-blocked>");
  63. expect(text).toContain("<run-id>dwfrun-1</run-id>");
  64. expect(text).toContain("<run>nightly audit</run>");
  65. expect(text).toContain("<reminder>1 of 2</reminder>");
  66. expect(text).toContain('<open-questions count="1" shown="1">');
  67. expect(text).toContain('<question id="dwfq-aaaa-1" subagent="reviewer" waited-ms="1020000">');
  68. expect(text).toContain("<text>通过线是 96 还是 95?</text>");
  69. expect(text).toContain("<context>已经试了 6 轮。</context>");
  70. expect(text).toContain('<open-holes count="1" shown="1">');
  71. expect(text).toContain(
  72. '<hole id="hole#21b40fca" name="修复方案" type="Plan" line="42" waited-ms="900000"/>',
  73. );
  74. expect(text).toContain("<draft>/Users/dev/proj/.zcode/workflow-drafts/audit.dwf.ts</draft>");
  75. // 最久的那个决定等了 17 分钟。
  76. expect(text).toContain(
  77. "Workflow run nightly audit (dwfrun-1) is still waiting on you: 1 question and 1 hole are open, the oldest for 17 minutes, and you have not acted on them since your last turn ended.",
  78. );
  79. expect(text).toContain(
  80. "call ResolveWorkflowQuestion with its id as question_id and your answer",
  81. );
  82. expect(text).toContain('call FillWorkflowHole with run_id="dwfrun-1" and its id as hole_id');
  83. expect(text).toContain("read the draft at /Users/dev/proj/.zcode/workflow-drafts/audit.dwf.ts");
  84. expect(text).toContain(
  85. "If a decision needs the user, tell the user exactly what you need from them and end your turn; do not guess an answer to make the reminders stop.",
  86. );
  87. expect(text).toContain("One more reminder follows if nothing changes.");
  88. expect(text).toContain("nothing times out on their behalf");
  89. });
  90. it("第 2 次:说这是最后一次,以及什么会重新开始", () => {
  91. const text = formatWorkflowBlockedNotification({ ...base, ordinal: 2, total: 2 });
  92. expect(text).toContain("<reminder>2 of 2</reminder>");
  93. expect(text).toContain(
  94. "This is the last reminder: nothing further is sent until the user writes or this run's open decisions change.",
  95. );
  96. expect(text).not.toContain("One more reminder follows");
  97. });
  98. it("只有问题 / 只有留白:另一节整节缺席,下一步也只说在场的那一种", () => {
  99. const onlyQuestions = formatWorkflowBlockedNotification({
  100. ...base,
  101. holes: [],
  102. ordinal: 1,
  103. total: 2,
  104. });
  105. expect(onlyQuestions).not.toContain("<open-holes");
  106. expect(onlyQuestions).not.toContain("FillWorkflowHole");
  107. expect(onlyQuestions).toContain("1 question is open, for 17 minutes");
  108. const onlyHoles = formatWorkflowBlockedNotification({
  109. ...base,
  110. questions: [],
  111. ordinal: 1,
  112. total: 2,
  113. });
  114. expect(onlyHoles).not.toContain("<open-questions");
  115. expect(onlyHoles).not.toContain("ResolveWorkflowQuestion");
  116. expect(onlyHoles).toContain("1 hole is open, for 15 minutes");
  117. });
  118. it("没有草稿路径:让模型用 GetWorkflowRun 取留白的上下文", () => {
  119. const text = formatWorkflowBlockedNotification({
  120. ...base,
  121. draftPath: undefined,
  122. ordinal: 1,
  123. total: 2,
  124. });
  125. expect(text).not.toContain("<draft>");
  126. expect(text).toContain('read the run\'s script with GetWorkflowRun (run_id="dwfrun-1")');
  127. });
  128. it("匿名子代理用结构化引用;标记字符被转义", () => {
  129. const text = formatWorkflowBlockedNotification({
  130. ...base,
  131. runLabel: "a <b> & c",
  132. questions: [{ qid: "q-1", actor: "actor#3@1", question: 'x < y && "z"', askedAt: 0 }],
  133. holes: [],
  134. ordinal: 1,
  135. total: 2,
  136. });
  137. expect(text).toContain("<run>a &lt;b&gt; &amp; c</run>");
  138. expect(text).toContain('subagent="actor#3@1"');
  139. expect(text).toContain("<text>x &lt; y &amp;&amp; &quot;z&quot;</text>");
  140. });
  141. it("截断诚实:至多列 8 个问题与 8 处留白,count 说真数;长文本截到 2000 字符", () => {
  142. const questions = Array.from({ length: 11 }, (_, index) => ({
  143. qid: `q-${index}`,
  144. actor: "actor#1@1",
  145. question: index === 0 ? "长".repeat(5_000) : `问题 ${index}`,
  146. askedAt: 0,
  147. }));
  148. const holes = Array.from({ length: 9 }, (_, index) => ({
  149. siteId: `hole#${index}`,
  150. ordinal: 1,
  151. name: `留白 ${index}`,
  152. type: "T",
  153. state: "waiting" as const,
  154. since: 0,
  155. }));
  156. const text = formatWorkflowBlockedNotification({
  157. ...base,
  158. questions,
  159. holes,
  160. ordinal: 1,
  161. total: 2,
  162. });
  163. expect(text).toContain('<open-questions count="11" shown="8">');
  164. expect(text).toContain('<open-holes count="9" shown="8">');
  165. expect(text).not.toContain('id="q-8"');
  166. expect(text).not.toContain('id="hole#8"');
  167. expect(text).toContain(`<text>${"长".repeat(1_999)}…</text>`);
  168. expect(text).toContain("11 questions and 9 holes are open");
  169. expect(text).toContain("GetWorkflowRun lists the ones not shown here");
  170. });
  171. });
  172. // ————————————————————————————————————————————————
  173. // runtime 宿主
  174. // ————————————————————————————————————————————————
  175. interface Captured {
  176. text: string;
  177. taskId?: string;
  178. originMeta?: BackgroundResultOriginMeta;
  179. }
  180. function makeRuntime(
  181. name: string,
  182. snapshots: Map<string, Partial<DynamicWorkflowRunSnapshot> | Error>,
  183. ): {
  184. runtime: AgentRuntime;
  185. internal: AgentRuntimeInternal;
  186. registry: InMemoryRuntimeTaskRegistry;
  187. captured: Captured[];
  188. getTask: ReturnType<typeof vi.fn>;
  189. } {
  190. const registry = new InMemoryRuntimeTaskRegistry();
  191. const getTask = vi.fn(async (runId: string) => {
  192. const snapshot = snapshots.get(runId);
  193. if (snapshot instanceof Error) throw snapshot;
  194. return snapshot as DynamicWorkflowRunSnapshot | undefined;
  195. });
  196. const runtime = new AgentRuntime(
  197. createSessionId(name),
  198. { agentName: "dwf-blocked-test", workingDirectory: "/tmp/zcode-dwf-blocked" },
  199. {
  200. dynamicWorkflowRunPort: { getTask } as unknown as DynamicWorkflowRunPort,
  201. eventStore: createTestSessionEventStore(),
  202. modelAdapter: {} as never,
  203. runtimeTaskRegistry: registry,
  204. },
  205. );
  206. const captured: Captured[] = [];
  207. (
  208. runtime as unknown as { enqueueBackgroundTaskNotification: (n: Captured) => void }
  209. ).enqueueBackgroundTaskNotification = (notification) => {
  210. captured.push(notification);
  211. };
  212. return {
  213. captured,
  214. getTask,
  215. internal: runtime as unknown as AgentRuntimeInternal,
  216. registry,
  217. runtime,
  218. };
  219. }
  220. function registerRun(
  221. registry: InMemoryRuntimeTaskRegistry,
  222. runId: string,
  223. overrides: Record<string, unknown> = {},
  224. ): void {
  225. registry.register({
  226. agentId: runId,
  227. agentType: "local_dynamic_workflow",
  228. description: `run ${runId}`,
  229. isBackgrounded: true,
  230. startedAt: new Date(0),
  231. status: "running",
  232. taskId: runId,
  233. taskType: "local_dynamic_workflow",
  234. type: "local_dynamic_workflow",
  235. ...overrides,
  236. } as never);
  237. }
  238. const openSnapshot: Partial<DynamicWorkflowRunSnapshot> = {
  239. pendingQuestions: [
  240. { qid: "dwfq-1", actor: "actor#1@1", actorName: "poet", question: "继续吗?", askedAt: 0 },
  241. { qid: "dwfq-2", actor: "actor#2@1", question: "用哪个分支?", askedAt: 4 * MIN },
  242. ],
  243. holes: [
  244. {
  245. siteId: "hole#aa",
  246. ordinal: 1,
  247. name: "下一步",
  248. type: "Plan",
  249. state: "waiting",
  250. since: 2 * MIN,
  251. },
  252. { siteId: "hole#bb", ordinal: 1, name: "已补", type: "Plan", state: "filled", filledAt: MIN },
  253. ],
  254. scriptPath: "/Users/dev/proj/.zcode/workflow-drafts/x.dwf.ts",
  255. };
  256. describe("runtime 上的提醒钟", () => {
  257. beforeEach(() => {
  258. vi.useFakeTimers();
  259. vi.setSystemTime(0);
  260. });
  261. afterEach(() => {
  262. vi.useRealTimers();
  263. });
  264. it("空闲 15 分钟:一条 blocked 通知,载荷是计数与最久的等待,taskId 让它继承 run 的分支代", async () => {
  265. const { runtime, internal, registry, captured } = makeRuntime(
  266. "dwf-blocked-first",
  267. new Map([["dwfrun-a", openSnapshot]]),
  268. );
  269. registerRun(registry, "dwfrun-a");
  270. await internal.drainRuntimeCommandQueue();
  271. await vi.advanceTimersByTimeAsync(FIRST - 1);
  272. expect(captured).toEqual([]);
  273. await vi.advanceTimersByTimeAsync(1);
  274. expect(captured).toHaveLength(1);
  275. expect(captured[0]?.taskId).toBe("dwfrun-a");
  276. expect(captured[0]?.originMeta).toEqual({
  277. backgroundSource: "workflow",
  278. title: "run dwfrun-a",
  279. workId: "dwfrun-a",
  280. // 补过的留白不算开着;最久的是 askedAt = 0 的那个问题。载荷在它自己的键上,不进
  281. // `workflowNotification` 的闭集:闭集多一个 kind,老客户端会拒掉整帧。
  282. workflowBlocked: { questions: 2, holes: 1, sinceMs: FIRST },
  283. });
  284. const text = captured[0]?.text ?? "";
  285. expect(text).toContain("<reminder>1 of 2</reminder>");
  286. expect(text).toContain('<question id="dwfq-1" subagent="poet"');
  287. expect(text).toContain('<question id="dwfq-2" subagent="actor#2@1"');
  288. expect(text).toContain('<hole id="hole#aa"');
  289. expect(text).not.toContain("hole#bb");
  290. expect(text).toContain("<draft>/Users/dev/proj/.zcode/workflow-drafts/x.dwf.ts</draft>");
  291. runtime.beginShutdown();
  292. });
  293. it("没有开着的决定:读过快照,但不发", async () => {
  294. const { runtime, internal, registry, captured, getTask } = makeRuntime(
  295. "dwf-blocked-none",
  296. new Map([
  297. [
  298. "dwfrun-a",
  299. { holes: [{ siteId: "h", ordinal: 1, name: "n", type: "T", state: "filled" }] },
  300. ],
  301. ]),
  302. );
  303. registerRun(registry, "dwfrun-a");
  304. await internal.drainRuntimeCommandQueue();
  305. await vi.advanceTimersByTimeAsync(FIRST);
  306. expect(getTask).toHaveBeenCalledWith("dwfrun-a");
  307. expect(captured).toEqual([]);
  308. runtime.beginShutdown();
  309. });
  310. it("只看在飞的 workflow run:结算了的、别的任务类型、被 rewind 掉的分支都不算", async () => {
  311. const { runtime, internal, registry, captured, getTask } = makeRuntime(
  312. "dwf-blocked-live",
  313. new Map([
  314. ["dwfrun-done", openSnapshot],
  315. ["bash-1", openSnapshot],
  316. ["dwfrun-stale", openSnapshot],
  317. ]),
  318. );
  319. registerRun(registry, "dwfrun-done", { status: "completed" });
  320. registerRun(registry, "bash-1", { type: "local_bash", taskType: "local_bash" });
  321. registerRun(registry, "dwfrun-stale", { branchGeneration: 7 });
  322. await internal.drainRuntimeCommandQueue();
  323. await vi.advanceTimersByTimeAsync(SECOND + FIRST);
  324. expect(getTask).not.toHaveBeenCalled();
  325. expect(captured).toEqual([]);
  326. runtime.beginShutdown();
  327. });
  328. it("快照读失败只跳过那个 run,不抛、不影响别的 run", async () => {
  329. const { runtime, internal, registry, captured } = makeRuntime(
  330. "dwf-blocked-read-error",
  331. new Map<string, Partial<DynamicWorkflowRunSnapshot> | Error>([
  332. ["dwfrun-bad", new Error("journal closed")],
  333. ["dwfrun-ok", openSnapshot],
  334. ]),
  335. );
  336. registerRun(registry, "dwfrun-bad");
  337. registerRun(registry, "dwfrun-ok");
  338. await internal.drainRuntimeCommandQueue();
  339. await vi.advanceTimersByTimeAsync(FIRST);
  340. expect(captured.map((entry) => entry.taskId)).toEqual(["dwfrun-ok"]);
  341. runtime.beginShutdown();
  342. });
  343. it("开集事件(raised / resolved / reached / filled)给该 run 新的一对;其余 run 事件不动次数", async () => {
  344. const { runtime, internal, registry, captured } = makeRuntime(
  345. "dwf-blocked-events",
  346. new Map([["dwfrun-a", openSnapshot]]),
  347. );
  348. registerRun(registry, "dwfrun-a");
  349. const spend = (): void => {
  350. // 每条提醒唤起的那一轮:忙 → 闲。
  351. internal.workflowBlockedReminder?.sessionBusy();
  352. internal.workflowBlockedReminder?.sessionIdle();
  353. };
  354. await internal.drainRuntimeCommandQueue();
  355. await vi.advanceTimersByTimeAsync(FIRST);
  356. spend();
  357. await vi.advanceTimersByTimeAsync(SECOND);
  358. spend();
  359. const blocked = (): number =>
  360. captured.filter((entry) => entry.originMeta?.workflowBlocked !== undefined).length;
  361. expect(blocked()).toBe(2);
  362. // 与开集无关的事件:不给新的一对。
  363. await runtime.recordDynamicWorkflowRunProgress({
  364. runId: "dwfrun-a",
  365. sequence: 20,
  366. eventType: "node-dispatched",
  367. payload: { instance: { siteId: "ask#1", ordinal: 1 } },
  368. });
  369. await vi.advanceTimersByTimeAsync(SECOND + FIRST);
  370. expect(blocked()).toBe(2);
  371. for (const [sequence, eventType] of [
  372. [21, "escalation-resolved"],
  373. [22, "hole-filled"],
  374. [23, "escalation-raised"],
  375. [24, "hole-reached"],
  376. ] as const) {
  377. // 事件自己的通知(raised / reached,这里载荷不全会被跳过)不是要数的;只看它给不给新的一对。
  378. await runtime.recordDynamicWorkflowRunProgress({
  379. runId: "dwfrun-a",
  380. sequence,
  381. eventType,
  382. payload: {},
  383. });
  384. const before = blocked();
  385. await vi.advanceTimersByTimeAsync(FIRST);
  386. expect(blocked(), eventType).toBe(before + 1);
  387. spend();
  388. await vi.advanceTimersByTimeAsync(SECOND);
  389. spend();
  390. expect(blocked(), eventType).toBe(before + 2);
  391. }
  392. runtime.beginShutdown();
  393. });
  394. it("beginShutdown 停钟:关会话之后不再唤起任何一轮", async () => {
  395. const { runtime, internal, registry, captured } = makeRuntime(
  396. "dwf-blocked-shutdown",
  397. new Map([["dwfrun-a", openSnapshot]]),
  398. );
  399. registerRun(registry, "dwfrun-a");
  400. await internal.drainRuntimeCommandQueue();
  401. runtime.beginShutdown();
  402. await vi.advanceTimersByTimeAsync(SECOND + FIRST);
  403. expect(captured).toEqual([]);
  404. expect(vi.getTimerCount()).toBe(0);
  405. });
  406. });
  407. // ————————————————————————————————————————————————
  408. // 队列与 steer 上的接线点(忙 / 闲 / 用户发话)
  409. // ————————————————————————————————————————————————
  410. function fakeClock(): {
  411. clock: WorkflowBlockedReminderClock;
  412. calls: string[];
  413. } {
  414. const calls: string[] = [];
  415. const clock = {
  416. openSetChanged: (runId: string) => calls.push(`changed:${runId}`),
  417. sessionBusy: () => calls.push("busy"),
  418. sessionIdle: () => calls.push("idle"),
  419. stop: () => calls.push("stop"),
  420. userSpoke: () => calls.push("user"),
  421. } as unknown as WorkflowBlockedReminderClock;
  422. return { calls, clock };
  423. }
  424. function queueRuntime(clock: WorkflowBlockedReminderClock): AgentRuntimeInternal {
  425. return {
  426. activeForegroundExecution: undefined,
  427. activeTurn: undefined,
  428. activeTurnStartReservation: undefined,
  429. executeTurnCommand: vi.fn().mockResolvedValue({}),
  430. foregroundPromotionLease: undefined,
  431. runtimeCommandDrainActive: false,
  432. runtimeCommandQueue: createRuntimeCommandQueue(),
  433. workflowBlockedReminder: clock,
  434. } as unknown as AgentRuntimeInternal;
  435. }
  436. function prompt(id: string, options?: Record<string, unknown>): RuntimeCommand {
  437. return {
  438. createdAt: new Date(0),
  439. id: id as RuntimeCommandId,
  440. input: id,
  441. mode: "prompt",
  442. ...(options ? { options } : {}),
  443. priority: "next",
  444. reject: () => {},
  445. resolve: () => {},
  446. traceContext: { sessionId: "sess_blocked_queue", spanId: `span_${id}`, traceId: "trace" },
  447. } as RuntimeCommand;
  448. }
  449. describe("命令队列上的接线", () => {
  450. it("用户 prompt:忙 + 用户发话,排空后闲", async () => {
  451. const { clock, calls } = fakeClock();
  452. const runtime = queueRuntime(clock);
  453. runtime.runtimeCommandQueue.enqueue(prompt("hello"));
  454. await drainRuntimeCommandQueue.call(runtime);
  455. expect(calls).toEqual(["busy", "user", "idle"]);
  456. });
  457. it("带合成来源的 prompt 不是用户发话", async () => {
  458. const { clock, calls } = fakeClock();
  459. const runtime = queueRuntime(clock);
  460. runtime.runtimeCommandQueue.enqueue(prompt("synthetic", { inputSource: "todo_reminder" }));
  461. await drainRuntimeCommandQueue.call(runtime);
  462. expect(calls).toEqual(["busy", "idle"]);
  463. });
  464. it("空排一次队列也报闲(钟自己去重),持着晋升租约时不报", async () => {
  465. const { clock, calls } = fakeClock();
  466. const runtime = queueRuntime(clock);
  467. await drainRuntimeCommandQueue.call(runtime);
  468. expect(calls).toEqual(["idle"]);
  469. calls.length = 0;
  470. runtime.foregroundPromotionLease = { leaseId: "l", promotedInputId: "p" };
  471. runtime.runtimeCommandQueue.enqueue(prompt("waiting-behind-lease"));
  472. await drainRuntimeCommandQueue.call(runtime);
  473. expect(calls).toEqual([]);
  474. });
  475. it("连着两条命令:每条开始都报忙,只在全部排空后报一次闲", async () => {
  476. const { clock, calls } = fakeClock();
  477. const runtime = queueRuntime(clock);
  478. runtime.runtimeCommandQueue.enqueue(prompt("one"));
  479. runtime.runtimeCommandQueue.enqueue(prompt("two", { inputSource: "goal-continuation" }));
  480. await drainRuntimeCommandQueue.call(runtime);
  481. expect(calls).toEqual(["busy", "user", "busy", "idle"]);
  482. });
  483. });
  484. describe("steer 上的接线", () => {
  485. function steerRuntime(clock: WorkflowBlockedReminderClock): AgentRuntimeInternal {
  486. return {
  487. activeTurn: {
  488. kind: "regular",
  489. pendingInputs: [],
  490. steerable: true,
  491. traceContext: { sessionId: "sess_blocked_steer", spanId: "span", traceId: "trace" },
  492. turnId: "turn_1",
  493. },
  494. appendEvent: vi.fn().mockResolvedValue(undefined),
  495. createPendingInputId: () => "pending_1",
  496. sessionId: createSessionId("sess_blocked_steer"),
  497. workflowBlockedReminder: clock,
  498. } as unknown as AgentRuntimeInternal;
  499. }
  500. it("用户 steer 进在跑的一轮:算用户发话", async () => {
  501. const { clock, calls } = fakeClock();
  502. const result = await steerTurn.call(steerRuntime(clock), {
  503. input: "先答那个问题",
  504. inputPresentation: "user_steer",
  505. });
  506. expect(result.kind).toBe("queued");
  507. expect(calls).toEqual(["user"]);
  508. });
  509. it("协调者 / 信箱 / 工具跟进的 steer 不是用户发话", async () => {
  510. const { clock, calls } = fakeClock();
  511. const runtime = steerRuntime(clock);
  512. await steerTurn.call(runtime, {
  513. input: "from coordinator",
  514. inputPresentation: "coordinator_steer",
  515. });
  516. await steerTurn.call(runtime, { delivery: "guide", input: "mailbox" });
  517. expect(calls).toEqual([]);
  518. });
  519. });