agent-session-auto-compaction-queue.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 { type AssistantMessage, getModel } from "@earendil-works/pi-ai";
  6. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  7. import { AgentSession } from "../src/core/agent-session.ts";
  8. import { AuthStorage } from "../src/core/auth-storage.ts";
  9. import { ModelRegistry } from "../src/core/model-registry.ts";
  10. import { SessionManager } from "../src/core/session-manager.ts";
  11. import { SettingsManager } from "../src/core/settings-manager.ts";
  12. import { createTestResourceLoader } from "./utilities.ts";
  13. vi.mock("../src/core/compaction/index.js", () => ({
  14. calculateContextTokens: (usage: {
  15. input: number;
  16. output: number;
  17. cacheRead: number;
  18. cacheWrite: number;
  19. totalTokens?: number;
  20. }) => usage.totalTokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite,
  21. collectEntriesForBranchSummary: () => ({ entries: [], commonAncestorId: null }),
  22. compact: async () => ({
  23. summary: "compacted",
  24. firstKeptEntryId: "entry-1",
  25. tokensBefore: 100,
  26. details: {},
  27. }),
  28. estimateContextTokens: (
  29. messages: Array<{
  30. role: string;
  31. usage?: { input: number; output: number; cacheRead: number; cacheWrite: number; totalTokens?: number };
  32. stopReason?: string;
  33. }>,
  34. ) => {
  35. // Walk backwards to find last non-error, non-aborted assistant with usage
  36. for (let i = messages.length - 1; i >= 0; i--) {
  37. const msg = messages[i];
  38. if (msg.role === "assistant" && msg.stopReason !== "error" && msg.stopReason !== "aborted" && msg.usage) {
  39. const tokens =
  40. msg.usage.totalTokens ?? msg.usage.input + msg.usage.output + msg.usage.cacheRead + msg.usage.cacheWrite;
  41. return { tokens, usageTokens: tokens, trailingTokens: 0, lastUsageIndex: i };
  42. }
  43. }
  44. return { tokens: 0, usageTokens: 0, trailingTokens: 0, lastUsageIndex: null };
  45. },
  46. generateBranchSummary: async () => ({ summary: "", aborted: false, readFiles: [], modifiedFiles: [] }),
  47. prepareCompaction: () => ({ dummy: true }),
  48. shouldCompact: (
  49. contextTokens: number,
  50. contextWindow: number,
  51. settings: { enabled: boolean; reserveTokens: number },
  52. ) => settings.enabled && contextTokens > contextWindow - settings.reserveTokens,
  53. }));
  54. describe("AgentSession auto-compaction queue resume", () => {
  55. let session: AgentSession;
  56. let sessionManager: SessionManager;
  57. let tempDir: string;
  58. beforeEach(() => {
  59. tempDir = join(tmpdir(), `pi-auto-compaction-queue-${Date.now()}`);
  60. mkdirSync(tempDir, { recursive: true });
  61. vi.useFakeTimers();
  62. const model = getModel("anthropic", "claude-sonnet-4-5")!;
  63. const agent = new Agent({
  64. initialState: {
  65. model,
  66. systemPrompt: "Test",
  67. tools: [],
  68. },
  69. });
  70. sessionManager = SessionManager.inMemory();
  71. const settingsManager = SettingsManager.create(tempDir, tempDir);
  72. const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
  73. authStorage.setRuntimeApiKey("anthropic", "test-key");
  74. const modelRegistry = ModelRegistry.create(authStorage, tempDir);
  75. session = new AgentSession({
  76. agent,
  77. sessionManager,
  78. settingsManager,
  79. cwd: tempDir,
  80. modelRegistry,
  81. resourceLoader: createTestResourceLoader(),
  82. });
  83. });
  84. afterEach(() => {
  85. session.dispose();
  86. vi.useRealTimers();
  87. vi.restoreAllMocks();
  88. if (tempDir && existsSync(tempDir)) {
  89. rmSync(tempDir, { recursive: true });
  90. }
  91. });
  92. it("should resume after threshold compaction when only agent-level queued messages exist", async () => {
  93. session.agent.followUp({
  94. role: "custom",
  95. customType: "test",
  96. content: [{ type: "text", text: "Queued custom" }],
  97. display: false,
  98. timestamp: Date.now(),
  99. });
  100. expect(session.pendingMessageCount).toBe(0);
  101. expect(session.agent.hasQueuedMessages()).toBe(true);
  102. const continueSpy = vi.spyOn(session.agent, "continue").mockResolvedValue();
  103. const runAutoCompaction = (
  104. session as unknown as {
  105. _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<boolean>;
  106. }
  107. )._runAutoCompaction.bind(session);
  108. await expect(runAutoCompaction("threshold", false)).resolves.toBe(true);
  109. expect(continueSpy).not.toHaveBeenCalled();
  110. });
  111. it("should not compact repeatedly after overflow recovery already attempted", async () => {
  112. const model = session.model!;
  113. const overflowMessage: AssistantMessage = {
  114. role: "assistant",
  115. content: [{ type: "text", text: "" }],
  116. api: model.api,
  117. provider: model.provider,
  118. model: model.id,
  119. usage: {
  120. input: 0,
  121. output: 0,
  122. cacheRead: 0,
  123. cacheWrite: 0,
  124. totalTokens: 0,
  125. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  126. },
  127. stopReason: "error",
  128. errorMessage: "prompt is too long",
  129. timestamp: Date.now(),
  130. };
  131. const runAutoCompactionSpy = vi
  132. .spyOn(
  133. session as unknown as {
  134. _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
  135. },
  136. "_runAutoCompaction",
  137. )
  138. .mockResolvedValue();
  139. const events: Array<{ type: string; reason: string; errorMessage?: string }> = [];
  140. session.subscribe((event) => {
  141. if (event.type === "compaction_end") {
  142. events.push({ type: event.type, reason: event.reason, errorMessage: event.errorMessage });
  143. }
  144. });
  145. const checkCompaction = (
  146. session as unknown as {
  147. _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
  148. }
  149. )._checkCompaction.bind(session);
  150. await checkCompaction(overflowMessage);
  151. await checkCompaction({ ...overflowMessage, timestamp: Date.now() + 1 });
  152. expect(runAutoCompactionSpy).toHaveBeenCalledTimes(1);
  153. expect(events).toContainEqual({
  154. type: "compaction_end",
  155. reason: "overflow",
  156. errorMessage:
  157. "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
  158. });
  159. });
  160. it("should ignore stale pre-compaction assistant usage on pre-prompt compaction checks", async () => {
  161. const model = session.model!;
  162. const staleAssistantTimestamp = Date.now() - 10_000;
  163. const staleAssistant: AssistantMessage = {
  164. role: "assistant",
  165. content: [{ type: "text", text: "large response before compaction" }],
  166. api: model.api,
  167. provider: model.provider,
  168. model: model.id,
  169. usage: {
  170. input: 600_000,
  171. output: 10_000,
  172. cacheRead: 0,
  173. cacheWrite: 0,
  174. totalTokens: 610_000,
  175. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  176. },
  177. stopReason: "stop",
  178. timestamp: staleAssistantTimestamp,
  179. };
  180. sessionManager.appendMessage({
  181. role: "user",
  182. content: [{ type: "text", text: "before compaction" }],
  183. timestamp: staleAssistantTimestamp - 1000,
  184. });
  185. sessionManager.appendMessage(staleAssistant);
  186. const firstKeptEntryId = sessionManager.getEntries()[0]!.id;
  187. sessionManager.appendCompaction("summary", firstKeptEntryId, staleAssistant.usage.totalTokens, undefined, false);
  188. sessionManager.appendMessage({
  189. role: "user",
  190. content: [{ type: "text", text: "session recovery payload" }],
  191. timestamp: Date.now(),
  192. });
  193. const runAutoCompactionSpy = vi
  194. .spyOn(
  195. session as unknown as {
  196. _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
  197. },
  198. "_runAutoCompaction",
  199. )
  200. .mockResolvedValue();
  201. const checkCompaction = (
  202. session as unknown as {
  203. _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
  204. }
  205. )._checkCompaction.bind(session);
  206. await checkCompaction(staleAssistant, false);
  207. expect(runAutoCompactionSpy).not.toHaveBeenCalled();
  208. });
  209. it("should trigger threshold compaction for error messages using last successful usage", async () => {
  210. const model = session.model!;
  211. // A successful assistant message with high token usage (near context limit)
  212. const successfulAssistant: AssistantMessage = {
  213. role: "assistant",
  214. content: [{ type: "text", text: "large successful response" }],
  215. api: model.api,
  216. provider: model.provider,
  217. model: model.id,
  218. usage: {
  219. input: 180_000,
  220. output: 10_000,
  221. cacheRead: 0,
  222. cacheWrite: 0,
  223. totalTokens: 190_000,
  224. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  225. },
  226. stopReason: "stop",
  227. timestamp: Date.now(),
  228. };
  229. // An error message (e.g. 529 overloaded) with no useful usage data
  230. const errorAssistant: AssistantMessage = {
  231. role: "assistant",
  232. content: [{ type: "text", text: "" }],
  233. api: model.api,
  234. provider: model.provider,
  235. model: model.id,
  236. usage: {
  237. input: 0,
  238. output: 0,
  239. cacheRead: 0,
  240. cacheWrite: 0,
  241. totalTokens: 0,
  242. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  243. },
  244. stopReason: "error",
  245. errorMessage: "529 overloaded",
  246. timestamp: Date.now() + 1000,
  247. };
  248. // Put both messages into agent state so estimateContextTokens can find the successful one
  249. session.agent.state.messages = [
  250. { role: "user", content: [{ type: "text", text: "hello" }], timestamp: Date.now() - 1000 },
  251. successfulAssistant,
  252. { role: "user", content: [{ type: "text", text: "another prompt" }], timestamp: Date.now() + 500 },
  253. errorAssistant,
  254. ];
  255. const runAutoCompactionSpy = vi
  256. .spyOn(
  257. session as unknown as {
  258. _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
  259. },
  260. "_runAutoCompaction",
  261. )
  262. .mockResolvedValue();
  263. const checkCompaction = (
  264. session as unknown as {
  265. _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
  266. }
  267. )._checkCompaction.bind(session);
  268. await checkCompaction(errorAssistant);
  269. expect(runAutoCompactionSpy).toHaveBeenCalledWith("threshold", false);
  270. });
  271. it("should not trigger threshold compaction for error messages when no prior usage exists", async () => {
  272. const model = session.model!;
  273. // An error message with no prior successful assistant in context
  274. const errorAssistant: AssistantMessage = {
  275. role: "assistant",
  276. content: [{ type: "text", text: "" }],
  277. api: model.api,
  278. provider: model.provider,
  279. model: model.id,
  280. usage: {
  281. input: 0,
  282. output: 0,
  283. cacheRead: 0,
  284. cacheWrite: 0,
  285. totalTokens: 0,
  286. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  287. },
  288. stopReason: "error",
  289. errorMessage: "529 overloaded",
  290. timestamp: Date.now(),
  291. };
  292. session.agent.state.messages = [
  293. { role: "user", content: [{ type: "text", text: "hello" }], timestamp: Date.now() - 1000 },
  294. errorAssistant,
  295. ];
  296. const runAutoCompactionSpy = vi
  297. .spyOn(
  298. session as unknown as {
  299. _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
  300. },
  301. "_runAutoCompaction",
  302. )
  303. .mockResolvedValue();
  304. const checkCompaction = (
  305. session as unknown as {
  306. _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
  307. }
  308. )._checkCompaction.bind(session);
  309. await checkCompaction(errorAssistant);
  310. expect(runAutoCompactionSpy).not.toHaveBeenCalled();
  311. });
  312. it("should not trigger threshold compaction for error messages when only kept pre-compaction usage exists", async () => {
  313. const model = session.model!;
  314. const preCompactionTimestamp = Date.now() - 10_000;
  315. // A "kept" assistant message from before compaction with high usage
  316. const keptAssistant: AssistantMessage = {
  317. role: "assistant",
  318. content: [{ type: "text", text: "kept response from before compaction" }],
  319. api: model.api,
  320. provider: model.provider,
  321. model: model.id,
  322. usage: {
  323. input: 180_000,
  324. output: 10_000,
  325. cacheRead: 0,
  326. cacheWrite: 0,
  327. totalTokens: 190_000,
  328. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  329. },
  330. stopReason: "stop",
  331. timestamp: preCompactionTimestamp,
  332. };
  333. // Record the kept assistant in the session and create a compaction after it
  334. sessionManager.appendMessage({
  335. role: "user",
  336. content: [{ type: "text", text: "before compaction" }],
  337. timestamp: preCompactionTimestamp - 1000,
  338. });
  339. sessionManager.appendMessage(keptAssistant);
  340. const firstKeptEntryId = sessionManager.getEntries()[0]!.id;
  341. sessionManager.appendCompaction("summary", firstKeptEntryId, keptAssistant.usage.totalTokens, undefined, false);
  342. // Post-compaction error message
  343. const errorAssistant: AssistantMessage = {
  344. role: "assistant",
  345. content: [{ type: "text", text: "" }],
  346. api: model.api,
  347. provider: model.provider,
  348. model: model.id,
  349. usage: {
  350. input: 0,
  351. output: 0,
  352. cacheRead: 0,
  353. cacheWrite: 0,
  354. totalTokens: 0,
  355. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  356. },
  357. stopReason: "error",
  358. errorMessage: "529 overloaded",
  359. timestamp: Date.now(),
  360. };
  361. // Agent state has the kept assistant (pre-compaction) and the error (post-compaction)
  362. session.agent.state.messages = [
  363. { role: "user", content: [{ type: "text", text: "kept user msg" }], timestamp: preCompactionTimestamp - 1000 },
  364. keptAssistant,
  365. { role: "user", content: [{ type: "text", text: "new prompt" }], timestamp: Date.now() - 500 },
  366. errorAssistant,
  367. ];
  368. const runAutoCompactionSpy = vi
  369. .spyOn(
  370. session as unknown as {
  371. _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
  372. },
  373. "_runAutoCompaction",
  374. )
  375. .mockResolvedValue();
  376. const checkCompaction = (
  377. session as unknown as {
  378. _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
  379. }
  380. )._checkCompaction.bind(session);
  381. await checkCompaction(errorAssistant);
  382. // Should NOT compact because the only usage data is from a kept pre-compaction message
  383. expect(runAutoCompactionSpy).not.toHaveBeenCalled();
  384. });
  385. });