rpc-prompt-response-semantics.test.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import { existsSync, mkdirSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { Agent } from "@earendil-works/pi-agent-core";
  5. import {
  6. type AssistantMessage,
  7. type AssistantMessageEvent,
  8. EventStream,
  9. getModel,
  10. type Model,
  11. } from "@earendil-works/pi-ai";
  12. import { afterEach, describe, expect, it, vi } from "vitest";
  13. import { AgentSession } from "../src/core/agent-session.ts";
  14. import type { AgentSessionRuntime } from "../src/core/agent-session-runtime.ts";
  15. import { AuthStorage } from "../src/core/auth-storage.ts";
  16. import { ModelRegistry } from "../src/core/model-registry.ts";
  17. import { SessionManager } from "../src/core/session-manager.ts";
  18. import { SettingsManager } from "../src/core/settings-manager.ts";
  19. import { runRpcMode } from "../src/modes/rpc/rpc-mode.ts";
  20. import { createTestResourceLoader } from "./utilities.ts";
  21. const rpcIo = vi.hoisted(() => ({
  22. outputLines: [] as string[],
  23. lineHandler: undefined as ((line: string) => void) | undefined,
  24. }));
  25. vi.mock("../src/core/output-guard.js", () => ({
  26. flushRawStdout: vi.fn(async () => {}),
  27. takeOverStdout: vi.fn(),
  28. waitForRawStdoutBackpressure: vi.fn(async () => {}),
  29. writeRawStdout: (line: string) => {
  30. rpcIo.outputLines.push(line);
  31. },
  32. }));
  33. vi.mock("../src/modes/interactive/theme/theme.js", () => ({ theme: {} }));
  34. vi.mock("../src/modes/rpc/jsonl.js", () => ({
  35. attachJsonlLineReader: vi.fn((_stream: NodeJS.ReadableStream, onLine: (line: string) => void) => {
  36. rpcIo.lineHandler = onLine;
  37. return () => {};
  38. }),
  39. serializeJsonLine: (value: unknown) => `${JSON.stringify(value)}\n`,
  40. }));
  41. class MockAssistantStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
  42. constructor() {
  43. super(
  44. (event) => event.type === "done" || event.type === "error",
  45. (event) => {
  46. if (event.type === "done") return event.message;
  47. if (event.type === "error") return event.error;
  48. throw new Error("Unexpected event type");
  49. },
  50. );
  51. }
  52. }
  53. function createAssistantMessage(text: string): AssistantMessage {
  54. return {
  55. role: "assistant",
  56. content: [{ type: "text", text }],
  57. api: "anthropic-messages",
  58. provider: "anthropic",
  59. model: "claude-sonnet-4-5",
  60. usage: {
  61. input: 0,
  62. output: 0,
  63. cacheRead: 0,
  64. cacheWrite: 0,
  65. totalTokens: 0,
  66. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  67. },
  68. stopReason: "stop",
  69. timestamp: Date.now(),
  70. };
  71. }
  72. type ParsedOutputLine = Record<string, unknown>;
  73. function parseOutputLines(outputLines: string[]): ParsedOutputLine[] {
  74. return outputLines
  75. .flatMap((line) => line.split("\n"))
  76. .filter((line) => line.trim().length > 0)
  77. .map((line) => JSON.parse(line) as ParsedOutputLine);
  78. }
  79. function getPromptResponses(outputLines: string[], id: string): ParsedOutputLine[] {
  80. return parseOutputLines(outputLines).filter(
  81. (record) => record.id === id && record.type === "response" && record.command === "prompt",
  82. );
  83. }
  84. function sleep(ms: number): Promise<void> {
  85. return new Promise((resolve) => setTimeout(resolve, ms));
  86. }
  87. function createRuntimeHost(options: { withAuth: boolean; responseDelayMs: number; model?: Model<any> }): {
  88. runtimeHost: AgentSessionRuntime;
  89. cleanup: () => Promise<void>;
  90. } {
  91. const tempDir = join(tmpdir(), `pi-rpc-prompt-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  92. mkdirSync(tempDir, { recursive: true });
  93. const model = options.model ?? getModel("anthropic", "claude-sonnet-4-5");
  94. if (!model) {
  95. throw new Error("Test model not found");
  96. }
  97. const agent = new Agent({
  98. getApiKey: () => "test-key",
  99. initialState: {
  100. model,
  101. systemPrompt: "Test",
  102. tools: [],
  103. },
  104. streamFn: (_model, _context, _options) => {
  105. const stream = new MockAssistantStream();
  106. queueMicrotask(() => {
  107. stream.push({ type: "start", partial: createAssistantMessage("") });
  108. setTimeout(() => {
  109. stream.push({ type: "done", reason: "stop", message: createAssistantMessage("done") });
  110. }, options.responseDelayMs);
  111. });
  112. return stream;
  113. },
  114. });
  115. const sessionManager = SessionManager.inMemory();
  116. const settingsManager = SettingsManager.create(tempDir, tempDir);
  117. const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
  118. const modelRegistry = ModelRegistry.create(authStorage, tempDir);
  119. if (options.withAuth) {
  120. authStorage.setRuntimeApiKey("anthropic", "test-key");
  121. }
  122. const session = new AgentSession({
  123. agent,
  124. sessionManager,
  125. settingsManager,
  126. cwd: tempDir,
  127. modelRegistry,
  128. resourceLoader: createTestResourceLoader(),
  129. });
  130. const runtimeHost = {
  131. session,
  132. newSession: vi.fn(async () => ({ cancelled: true })),
  133. switchSession: vi.fn(async () => ({ cancelled: true })),
  134. fork: vi.fn(async () => ({ cancelled: true, selectedText: "" })),
  135. dispose: vi.fn(async () => {}),
  136. setRebindSession: vi.fn(),
  137. } as unknown as AgentSessionRuntime;
  138. return {
  139. runtimeHost,
  140. cleanup: async () => {
  141. try {
  142. if (session.isStreaming) {
  143. await session.abort();
  144. }
  145. } catch {
  146. // ignore test cleanup failures
  147. }
  148. session.dispose();
  149. if (existsSync(tempDir)) {
  150. rmSync(tempDir, { recursive: true });
  151. }
  152. },
  153. };
  154. }
  155. async function startRpcMode(options: { withAuth: boolean; responseDelayMs: number; model?: Model<any> }): Promise<{
  156. lineHandler: (line: string) => void;
  157. cleanup: () => Promise<void>;
  158. }> {
  159. rpcIo.outputLines = [];
  160. rpcIo.lineHandler = undefined;
  161. const { runtimeHost, cleanup } = createRuntimeHost(options);
  162. void runRpcMode(runtimeHost);
  163. await vi.waitFor(() => expect(rpcIo.lineHandler).toBeDefined());
  164. return { lineHandler: rpcIo.lineHandler!, cleanup };
  165. }
  166. describe("RPC prompt response semantics", () => {
  167. afterEach(() => {
  168. rpcIo.outputLines = [];
  169. rpcIo.lineHandler = undefined;
  170. });
  171. it("emits one failure response when prompt preflight rejects", async () => {
  172. const { lineHandler, cleanup } = await startRpcMode({
  173. withAuth: false,
  174. responseDelayMs: 0,
  175. model: {
  176. id: "fake-model",
  177. name: "Fake Model",
  178. api: "openai-completions",
  179. provider: "fake-provider",
  180. baseUrl: "https://example.invalid",
  181. reasoning: false,
  182. input: [],
  183. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  184. contextWindow: 0,
  185. maxTokens: 0,
  186. },
  187. });
  188. try {
  189. lineHandler(JSON.stringify({ id: "b1", type: "prompt", message: "Hello" }));
  190. await vi.waitFor(() => {
  191. const responses = getPromptResponses(rpcIo.outputLines, "b1");
  192. expect(responses).toHaveLength(1);
  193. expect(responses[0]).toMatchObject({
  194. id: "b1",
  195. type: "response",
  196. command: "prompt",
  197. success: false,
  198. error: expect.stringContaining(
  199. "No API key found for fake-provider.\n\nUse /login to log into a provider via OAuth or API key. See:",
  200. ),
  201. });
  202. });
  203. } finally {
  204. await cleanup();
  205. }
  206. });
  207. it("emits one success response when prompt preflight succeeds", async () => {
  208. const { lineHandler, cleanup } = await startRpcMode({ withAuth: true, responseDelayMs: 0 });
  209. try {
  210. lineHandler(JSON.stringify({ id: "b2", type: "prompt", message: "Hello" }));
  211. await vi.waitFor(() => {
  212. const responses = getPromptResponses(rpcIo.outputLines, "b2");
  213. expect(responses).toHaveLength(1);
  214. expect(responses[0]).toMatchObject({
  215. id: "b2",
  216. type: "response",
  217. command: "prompt",
  218. success: true,
  219. });
  220. });
  221. } finally {
  222. await cleanup();
  223. }
  224. });
  225. it("emits one success response when prompt is queued during streaming", async () => {
  226. const { lineHandler, cleanup } = await startRpcMode({ withAuth: true, responseDelayMs: 100 });
  227. try {
  228. lineHandler(JSON.stringify({ id: "b3-start", type: "prompt", message: "Start" }));
  229. await vi.waitFor(() => {
  230. expect(getPromptResponses(rpcIo.outputLines, "b3-start")).toHaveLength(1);
  231. });
  232. rpcIo.outputLines = [];
  233. lineHandler(
  234. JSON.stringify({
  235. id: "b3",
  236. type: "prompt",
  237. message: "Queue this",
  238. streamingBehavior: "followUp",
  239. }),
  240. );
  241. await vi.waitFor(() => {
  242. const responses = getPromptResponses(rpcIo.outputLines, "b3");
  243. expect(responses).toHaveLength(1);
  244. expect(responses[0]).toMatchObject({
  245. id: "b3",
  246. type: "response",
  247. command: "prompt",
  248. success: true,
  249. });
  250. });
  251. await sleep(150);
  252. } finally {
  253. await cleanup();
  254. }
  255. });
  256. });