agent-session-queue.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import type { AgentTool } from "@earendil-works/pi-agent-core";
  2. import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
  3. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  4. import { Type } from "typebox";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { createHarness, getAssistantTexts, getMessageText, getUserTexts, type Harness } from "./harness.ts";
  7. async function createWaitingHarness(
  8. options: {
  9. tools?: AgentTool[];
  10. extensionFactories?: Harness["session"]["extensionRunner"] extends never
  11. ? never
  12. : Array<(pi: ExtensionAPI) => void>;
  13. } = {},
  14. ): Promise<{
  15. harness: Harness;
  16. releaseToolExecution: () => void;
  17. promptPromise: Promise<void>;
  18. waitForToolStart: Promise<void>;
  19. }> {
  20. let releaseToolExecution: (() => void) | undefined;
  21. const toolRelease = new Promise<void>((resolve) => {
  22. releaseToolExecution = resolve;
  23. });
  24. const waitTool: AgentTool = {
  25. name: "wait",
  26. label: "Wait",
  27. description: "Wait for release",
  28. parameters: Type.Object({}),
  29. execute: async () => {
  30. await toolRelease;
  31. return {
  32. content: [{ type: "text", text: "released" }],
  33. details: {},
  34. };
  35. },
  36. };
  37. const harness = await createHarness({
  38. tools: [waitTool, ...(options.tools ?? [])],
  39. extensionFactories: options.extensionFactories,
  40. });
  41. const waitForToolStart = new Promise<void>((resolve) => {
  42. const unsubscribe = harness.session.subscribe((event) => {
  43. if (event.type === "tool_execution_start" && event.toolName === "wait") {
  44. unsubscribe();
  45. resolve();
  46. }
  47. });
  48. });
  49. return {
  50. harness,
  51. releaseToolExecution: () => releaseToolExecution?.(),
  52. promptPromise: harness.session.prompt("start"),
  53. waitForToolStart,
  54. };
  55. }
  56. describe("AgentSession queue characterization", () => {
  57. const harnesses: Harness[] = [];
  58. afterEach(() => {
  59. while (harnesses.length > 0) {
  60. harnesses.pop()?.cleanup();
  61. }
  62. });
  63. it("dispatches extension commands immediately when prompted while idle", async () => {
  64. const commandRuns: string[] = [];
  65. const harness = await createHarness({
  66. extensionFactories: [
  67. (pi) => {
  68. pi.registerCommand("testcmd", {
  69. description: "Test command",
  70. handler: async (args) => {
  71. commandRuns.push(args);
  72. },
  73. });
  74. },
  75. ],
  76. });
  77. harnesses.push(harness);
  78. await harness.session.prompt("/testcmd hello world");
  79. expect(commandRuns).toEqual(["hello world"]);
  80. expect(harness.getPendingResponseCount()).toBe(0);
  81. expect(harness.session.messages).toEqual([]);
  82. });
  83. it("delivers extension-origin steering messages before the next LLM call", async () => {
  84. let extensionApi: ExtensionAPI | undefined;
  85. const waiting = await createWaitingHarness({
  86. extensionFactories: [
  87. (pi) => {
  88. extensionApi = pi;
  89. },
  90. ],
  91. });
  92. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  93. harnesses.push(harness);
  94. harness.setResponses([
  95. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  96. (context) => {
  97. const sawSteer = context.messages.some(
  98. (message) => message.role === "user" && getMessageText(message) === "steer now",
  99. );
  100. return fauxAssistantMessage(sawSteer ? "saw steer" : "missing steer");
  101. },
  102. ]);
  103. await waitForToolStart;
  104. await new Promise((resolve) => setTimeout(resolve, 0));
  105. extensionApi?.sendUserMessage("steer now", { deliverAs: "steer" });
  106. releaseToolExecution();
  107. await promptPromise;
  108. expect(getUserTexts(harness)).toEqual(["start", "steer now"]);
  109. expect(getAssistantTexts(harness)).toContain("saw steer");
  110. });
  111. it("delivers follow-up messages only after the current run finishes", async () => {
  112. const waiting = await createWaitingHarness();
  113. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  114. harnesses.push(harness);
  115. const assistantSeenBeforeFollowUp: string[] = [];
  116. harness.setResponses([
  117. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  118. (context) => {
  119. assistantSeenBeforeFollowUp.push(
  120. ...context.messages
  121. .filter((message) => message.role === "assistant")
  122. .map((message) =>
  123. message.content
  124. .filter((part): part is { type: "text"; text: string } => part.type === "text")
  125. .map((part) => part.text)
  126. .join("\n"),
  127. ),
  128. );
  129. return fauxAssistantMessage("follow-up response");
  130. },
  131. ]);
  132. await waitForToolStart;
  133. await harness.session.followUp("after current run");
  134. releaseToolExecution();
  135. await promptPromise;
  136. expect(getUserTexts(harness)).toEqual(["start", "after current run"]);
  137. expect(assistantSeenBeforeFollowUp).toContain("");
  138. expect(getAssistantTexts(harness)).toContain("follow-up response");
  139. });
  140. it("delivers multiple steering messages in order in one-at-a-time mode", async () => {
  141. const waiting = await createWaitingHarness();
  142. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  143. harnesses.push(harness);
  144. harness.setResponses([
  145. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  146. fauxAssistantMessage("handled steer 1"),
  147. fauxAssistantMessage("handled steer 2"),
  148. ]);
  149. await waitForToolStart;
  150. await harness.session.steer("steer 1");
  151. await harness.session.steer("steer 2");
  152. releaseToolExecution();
  153. await promptPromise;
  154. expect(getUserTexts(harness)).toEqual(["start", "steer 1", "steer 2"]);
  155. expect(getAssistantTexts(harness)).toEqual(["", "handled steer 1", "handled steer 2"]);
  156. });
  157. it("delivers multiple follow-up messages in order in one-at-a-time mode", async () => {
  158. const waiting = await createWaitingHarness();
  159. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  160. harnesses.push(harness);
  161. harness.setResponses([
  162. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  163. fauxAssistantMessage("original turn complete"),
  164. fauxAssistantMessage("handled follow-up 1"),
  165. fauxAssistantMessage("handled follow-up 2"),
  166. ]);
  167. await waitForToolStart;
  168. await harness.session.followUp("follow-up 1");
  169. await harness.session.followUp("follow-up 2");
  170. releaseToolExecution();
  171. await promptPromise;
  172. expect(getUserTexts(harness)).toEqual(["start", "follow-up 1", "follow-up 2"]);
  173. expect(getAssistantTexts(harness)).toEqual([
  174. "",
  175. "original turn complete",
  176. "handled follow-up 1",
  177. "handled follow-up 2",
  178. ]);
  179. });
  180. it("delivers all steering messages in one batch in all mode", async () => {
  181. const waiting = await createWaitingHarness();
  182. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  183. harnesses.push(harness);
  184. harness.session.setSteeringMode("all");
  185. let batchedUserMessages: string[] = [];
  186. harness.setResponses([
  187. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  188. (context) => {
  189. batchedUserMessages = context.messages
  190. .filter((message) => message.role === "user")
  191. .map((message) => getMessageText(message));
  192. return fauxAssistantMessage("batched steer response");
  193. },
  194. ]);
  195. await waitForToolStart;
  196. await harness.session.steer("steer 1");
  197. await harness.session.steer("steer 2");
  198. releaseToolExecution();
  199. await promptPromise;
  200. expect(batchedUserMessages).toEqual(["start", "steer 1", "steer 2"]);
  201. expect(getAssistantTexts(harness)).toEqual(["", "batched steer response"]);
  202. });
  203. it("delivers all follow-up messages in one batch in all mode", async () => {
  204. const waiting = await createWaitingHarness();
  205. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  206. harnesses.push(harness);
  207. harness.session.setFollowUpMode("all");
  208. let batchedUserMessages: string[] = [];
  209. harness.setResponses([
  210. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  211. fauxAssistantMessage("original turn complete"),
  212. (context) => {
  213. batchedUserMessages = context.messages
  214. .filter((message) => message.role === "user")
  215. .map((message) => getMessageText(message));
  216. return fauxAssistantMessage("batched follow-up response");
  217. },
  218. ]);
  219. await waitForToolStart;
  220. await harness.session.followUp("follow-up 1");
  221. await harness.session.followUp("follow-up 2");
  222. releaseToolExecution();
  223. await promptPromise;
  224. expect(batchedUserMessages).toEqual(["start", "follow-up 1", "follow-up 2"]);
  225. expect(getAssistantTexts(harness)).toEqual(["", "original turn complete", "batched follow-up response"]);
  226. });
  227. it("queues custom messages with deliverAs steer while streaming", async () => {
  228. const waiting = await createWaitingHarness();
  229. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  230. harnesses.push(harness);
  231. let sawCustomMessage = false;
  232. harness.setResponses([
  233. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  234. (context) => {
  235. sawCustomMessage = context.messages.some(
  236. (message) =>
  237. message.role === "user" &&
  238. typeof message.content !== "string" &&
  239. message.content.some((part) => part.type === "text" && part.text === "steer custom"),
  240. );
  241. return fauxAssistantMessage("done");
  242. },
  243. ]);
  244. await waitForToolStart;
  245. await harness.session.sendCustomMessage(
  246. { customType: "queue-test", content: "steer custom", display: true, details: { value: 1 } },
  247. { deliverAs: "steer" },
  248. );
  249. releaseToolExecution();
  250. await promptPromise;
  251. expect(sawCustomMessage).toBe(true);
  252. expect(
  253. harness.session.messages.some((message) => message.role === "custom" && message.customType === "queue-test"),
  254. ).toBe(true);
  255. });
  256. it("queues custom messages with deliverAs followUp while streaming", async () => {
  257. const waiting = await createWaitingHarness();
  258. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  259. harnesses.push(harness);
  260. let sawCustomMessage = false;
  261. harness.setResponses([
  262. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  263. fauxAssistantMessage("original turn complete"),
  264. (context) => {
  265. sawCustomMessage = context.messages.some(
  266. (message) =>
  267. message.role === "user" &&
  268. typeof message.content !== "string" &&
  269. message.content.some((part) => part.type === "text" && part.text === "follow-up custom"),
  270. );
  271. return fauxAssistantMessage("done");
  272. },
  273. ]);
  274. await waitForToolStart;
  275. await harness.session.sendCustomMessage(
  276. { customType: "queue-test", content: "follow-up custom", display: true, details: { value: 1 } },
  277. { deliverAs: "followUp" },
  278. );
  279. releaseToolExecution();
  280. await promptPromise;
  281. expect(sawCustomMessage).toBe(true);
  282. expect(
  283. harness.session.messages.some((message) => message.role === "custom" && message.customType === "queue-test"),
  284. ).toBe(true);
  285. });
  286. it("injects nextTurn custom messages into the next prompt", async () => {
  287. const harness = await createHarness();
  288. harnesses.push(harness);
  289. let sawCustomMessage = false;
  290. await harness.session.sendCustomMessage(
  291. { customType: "next-turn", content: "carry this", display: true, details: {} },
  292. { deliverAs: "nextTurn" },
  293. );
  294. harness.setResponses([
  295. (context) => {
  296. sawCustomMessage = context.messages.some(
  297. (message) =>
  298. message.role === "user" &&
  299. typeof message.content !== "string" &&
  300. message.content.some((part) => part.type === "text" && part.text === "carry this"),
  301. );
  302. return fauxAssistantMessage("done");
  303. },
  304. ]);
  305. await harness.session.prompt("normal prompt");
  306. expect(sawCustomMessage).toBe(true);
  307. expect(harness.session.messages.map((message) => message.role)).toEqual(["user", "custom", "assistant"]);
  308. });
  309. it("updates pendingMessageCount and removes queued text before message_start is emitted", async () => {
  310. const waiting = await createWaitingHarness();
  311. const { harness, waitForToolStart, promptPromise, releaseToolExecution } = waiting;
  312. harnesses.push(harness);
  313. const countsAtQueuedMessageStart: number[] = [];
  314. harness.setResponses([
  315. fauxAssistantMessage(fauxToolCall("wait", {}), { stopReason: "toolUse" }),
  316. fauxAssistantMessage("done"),
  317. ]);
  318. harness.session.subscribe((event) => {
  319. if (
  320. event.type === "message_start" &&
  321. event.message.role === "user" &&
  322. getMessageText(event.message) === "queued"
  323. ) {
  324. countsAtQueuedMessageStart.push(harness.session.pendingMessageCount);
  325. }
  326. });
  327. await waitForToolStart;
  328. await harness.session.steer("queued");
  329. expect(harness.session.pendingMessageCount).toBe(1);
  330. releaseToolExecution();
  331. await promptPromise;
  332. expect(countsAtQueuedMessageStart).toEqual([0]);
  333. expect(harness.session.pendingMessageCount).toBe(0);
  334. });
  335. it("throws when queueing an extension command with steer", async () => {
  336. const harness = await createHarness({
  337. extensionFactories: [
  338. (pi) => {
  339. pi.registerCommand("testcmd", {
  340. description: "Test command",
  341. handler: async () => {},
  342. });
  343. },
  344. ],
  345. });
  346. harnesses.push(harness);
  347. await expect(harness.session.steer("/testcmd queued")).rejects.toThrow(
  348. 'Extension command "/testcmd" cannot be queued. Use prompt() or execute the command when not streaming.',
  349. );
  350. });
  351. it("throws when queueing an extension command with followUp", async () => {
  352. const harness = await createHarness({
  353. extensionFactories: [
  354. (pi) => {
  355. pi.registerCommand("testcmd", {
  356. description: "Test command",
  357. handler: async () => {},
  358. });
  359. },
  360. ],
  361. });
  362. harnesses.push(harness);
  363. await expect(harness.session.followUp("/testcmd queued")).rejects.toThrow(
  364. 'Extension command "/testcmd" cannot be queued. Use prompt() or execute the command when not streaming.',
  365. );
  366. });
  367. it("delivers follow-ups queued during agent_end", async () => {
  368. let sent = false;
  369. const harness = await createHarness({
  370. extensionFactories: [
  371. (pi: ExtensionAPI) => {
  372. pi.on("agent_end", async () => {
  373. if (sent) return;
  374. sent = true;
  375. pi.sendUserMessage("conflict report", { deliverAs: "followUp" });
  376. });
  377. },
  378. ],
  379. });
  380. harnesses.push(harness);
  381. harness.setResponses([fauxAssistantMessage("reply"), fauxAssistantMessage("follow-up reply")]);
  382. await harness.session.prompt("hello");
  383. await harness.session.agent.waitForIdle();
  384. expect(getUserTexts(harness)).toEqual(["hello", "conflict report"]);
  385. });
  386. });