| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436 |
- import { existsSync, mkdirSync, rmSync } from "node:fs";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import { Agent } from "@earendil-works/pi-agent-core";
- import { type AssistantMessage, getModel } from "@earendil-works/pi-ai";
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
- import { AgentSession } from "../src/core/agent-session.ts";
- import { AuthStorage } from "../src/core/auth-storage.ts";
- import { ModelRegistry } from "../src/core/model-registry.ts";
- import { SessionManager } from "../src/core/session-manager.ts";
- import { SettingsManager } from "../src/core/settings-manager.ts";
- import { createTestResourceLoader } from "./utilities.ts";
- vi.mock("../src/core/compaction/index.js", () => ({
- calculateContextTokens: (usage: {
- input: number;
- output: number;
- cacheRead: number;
- cacheWrite: number;
- totalTokens?: number;
- }) => usage.totalTokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite,
- collectEntriesForBranchSummary: () => ({ entries: [], commonAncestorId: null }),
- compact: async () => ({
- summary: "compacted",
- firstKeptEntryId: "entry-1",
- tokensBefore: 100,
- details: {},
- }),
- estimateContextTokens: (
- messages: Array<{
- role: string;
- usage?: { input: number; output: number; cacheRead: number; cacheWrite: number; totalTokens?: number };
- stopReason?: string;
- }>,
- ) => {
- // Walk backwards to find last non-error, non-aborted assistant with usage
- for (let i = messages.length - 1; i >= 0; i--) {
- const msg = messages[i];
- if (msg.role === "assistant" && msg.stopReason !== "error" && msg.stopReason !== "aborted" && msg.usage) {
- const tokens =
- msg.usage.totalTokens ?? msg.usage.input + msg.usage.output + msg.usage.cacheRead + msg.usage.cacheWrite;
- return { tokens, usageTokens: tokens, trailingTokens: 0, lastUsageIndex: i };
- }
- }
- return { tokens: 0, usageTokens: 0, trailingTokens: 0, lastUsageIndex: null };
- },
- generateBranchSummary: async () => ({ summary: "", aborted: false, readFiles: [], modifiedFiles: [] }),
- prepareCompaction: () => ({ dummy: true }),
- shouldCompact: (
- contextTokens: number,
- contextWindow: number,
- settings: { enabled: boolean; reserveTokens: number },
- ) => settings.enabled && contextTokens > contextWindow - settings.reserveTokens,
- }));
- describe("AgentSession auto-compaction queue resume", () => {
- let session: AgentSession;
- let sessionManager: SessionManager;
- let tempDir: string;
- beforeEach(() => {
- tempDir = join(tmpdir(), `pi-auto-compaction-queue-${Date.now()}`);
- mkdirSync(tempDir, { recursive: true });
- vi.useFakeTimers();
- const model = getModel("anthropic", "claude-sonnet-4-5")!;
- const agent = new Agent({
- initialState: {
- model,
- systemPrompt: "Test",
- tools: [],
- },
- });
- sessionManager = SessionManager.inMemory();
- const settingsManager = SettingsManager.create(tempDir, tempDir);
- const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
- authStorage.setRuntimeApiKey("anthropic", "test-key");
- const modelRegistry = ModelRegistry.create(authStorage, tempDir);
- session = new AgentSession({
- agent,
- sessionManager,
- settingsManager,
- cwd: tempDir,
- modelRegistry,
- resourceLoader: createTestResourceLoader(),
- });
- });
- afterEach(() => {
- session.dispose();
- vi.useRealTimers();
- vi.restoreAllMocks();
- if (tempDir && existsSync(tempDir)) {
- rmSync(tempDir, { recursive: true });
- }
- });
- it("should resume after threshold compaction when only agent-level queued messages exist", async () => {
- session.agent.followUp({
- role: "custom",
- customType: "test",
- content: [{ type: "text", text: "Queued custom" }],
- display: false,
- timestamp: Date.now(),
- });
- expect(session.pendingMessageCount).toBe(0);
- expect(session.agent.hasQueuedMessages()).toBe(true);
- const continueSpy = vi.spyOn(session.agent, "continue").mockResolvedValue();
- const runAutoCompaction = (
- session as unknown as {
- _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<boolean>;
- }
- )._runAutoCompaction.bind(session);
- await expect(runAutoCompaction("threshold", false)).resolves.toBe(true);
- expect(continueSpy).not.toHaveBeenCalled();
- });
- it("should not compact repeatedly after overflow recovery already attempted", async () => {
- const model = session.model!;
- const overflowMessage: AssistantMessage = {
- role: "assistant",
- content: [{ type: "text", text: "" }],
- api: model.api,
- provider: model.provider,
- model: model.id,
- usage: {
- input: 0,
- output: 0,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 0,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- },
- stopReason: "error",
- errorMessage: "prompt is too long",
- timestamp: Date.now(),
- };
- const runAutoCompactionSpy = vi
- .spyOn(
- session as unknown as {
- _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
- },
- "_runAutoCompaction",
- )
- .mockResolvedValue();
- const events: Array<{ type: string; reason: string; errorMessage?: string }> = [];
- session.subscribe((event) => {
- if (event.type === "compaction_end") {
- events.push({ type: event.type, reason: event.reason, errorMessage: event.errorMessage });
- }
- });
- const checkCompaction = (
- session as unknown as {
- _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
- }
- )._checkCompaction.bind(session);
- await checkCompaction(overflowMessage);
- await checkCompaction({ ...overflowMessage, timestamp: Date.now() + 1 });
- expect(runAutoCompactionSpy).toHaveBeenCalledTimes(1);
- expect(events).toContainEqual({
- type: "compaction_end",
- reason: "overflow",
- errorMessage:
- "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
- });
- });
- it("should ignore stale pre-compaction assistant usage on pre-prompt compaction checks", async () => {
- const model = session.model!;
- const staleAssistantTimestamp = Date.now() - 10_000;
- const staleAssistant: AssistantMessage = {
- role: "assistant",
- content: [{ type: "text", text: "large response before compaction" }],
- api: model.api,
- provider: model.provider,
- model: model.id,
- usage: {
- input: 600_000,
- output: 10_000,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 610_000,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- },
- stopReason: "stop",
- timestamp: staleAssistantTimestamp,
- };
- sessionManager.appendMessage({
- role: "user",
- content: [{ type: "text", text: "before compaction" }],
- timestamp: staleAssistantTimestamp - 1000,
- });
- sessionManager.appendMessage(staleAssistant);
- const firstKeptEntryId = sessionManager.getEntries()[0]!.id;
- sessionManager.appendCompaction("summary", firstKeptEntryId, staleAssistant.usage.totalTokens, undefined, false);
- sessionManager.appendMessage({
- role: "user",
- content: [{ type: "text", text: "session recovery payload" }],
- timestamp: Date.now(),
- });
- const runAutoCompactionSpy = vi
- .spyOn(
- session as unknown as {
- _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
- },
- "_runAutoCompaction",
- )
- .mockResolvedValue();
- const checkCompaction = (
- session as unknown as {
- _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
- }
- )._checkCompaction.bind(session);
- await checkCompaction(staleAssistant, false);
- expect(runAutoCompactionSpy).not.toHaveBeenCalled();
- });
- it("should trigger threshold compaction for error messages using last successful usage", async () => {
- const model = session.model!;
- // A successful assistant message with high token usage (near context limit)
- const successfulAssistant: AssistantMessage = {
- role: "assistant",
- content: [{ type: "text", text: "large successful response" }],
- api: model.api,
- provider: model.provider,
- model: model.id,
- usage: {
- input: 180_000,
- output: 10_000,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 190_000,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- },
- stopReason: "stop",
- timestamp: Date.now(),
- };
- // An error message (e.g. 529 overloaded) with no useful usage data
- const errorAssistant: AssistantMessage = {
- role: "assistant",
- content: [{ type: "text", text: "" }],
- api: model.api,
- provider: model.provider,
- model: model.id,
- usage: {
- input: 0,
- output: 0,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 0,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- },
- stopReason: "error",
- errorMessage: "529 overloaded",
- timestamp: Date.now() + 1000,
- };
- // Put both messages into agent state so estimateContextTokens can find the successful one
- session.agent.state.messages = [
- { role: "user", content: [{ type: "text", text: "hello" }], timestamp: Date.now() - 1000 },
- successfulAssistant,
- { role: "user", content: [{ type: "text", text: "another prompt" }], timestamp: Date.now() + 500 },
- errorAssistant,
- ];
- const runAutoCompactionSpy = vi
- .spyOn(
- session as unknown as {
- _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
- },
- "_runAutoCompaction",
- )
- .mockResolvedValue();
- const checkCompaction = (
- session as unknown as {
- _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
- }
- )._checkCompaction.bind(session);
- await checkCompaction(errorAssistant);
- expect(runAutoCompactionSpy).toHaveBeenCalledWith("threshold", false);
- });
- it("should not trigger threshold compaction for error messages when no prior usage exists", async () => {
- const model = session.model!;
- // An error message with no prior successful assistant in context
- const errorAssistant: AssistantMessage = {
- role: "assistant",
- content: [{ type: "text", text: "" }],
- api: model.api,
- provider: model.provider,
- model: model.id,
- usage: {
- input: 0,
- output: 0,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 0,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- },
- stopReason: "error",
- errorMessage: "529 overloaded",
- timestamp: Date.now(),
- };
- session.agent.state.messages = [
- { role: "user", content: [{ type: "text", text: "hello" }], timestamp: Date.now() - 1000 },
- errorAssistant,
- ];
- const runAutoCompactionSpy = vi
- .spyOn(
- session as unknown as {
- _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
- },
- "_runAutoCompaction",
- )
- .mockResolvedValue();
- const checkCompaction = (
- session as unknown as {
- _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
- }
- )._checkCompaction.bind(session);
- await checkCompaction(errorAssistant);
- expect(runAutoCompactionSpy).not.toHaveBeenCalled();
- });
- it("should not trigger threshold compaction for error messages when only kept pre-compaction usage exists", async () => {
- const model = session.model!;
- const preCompactionTimestamp = Date.now() - 10_000;
- // A "kept" assistant message from before compaction with high usage
- const keptAssistant: AssistantMessage = {
- role: "assistant",
- content: [{ type: "text", text: "kept response from before compaction" }],
- api: model.api,
- provider: model.provider,
- model: model.id,
- usage: {
- input: 180_000,
- output: 10_000,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 190_000,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- },
- stopReason: "stop",
- timestamp: preCompactionTimestamp,
- };
- // Record the kept assistant in the session and create a compaction after it
- sessionManager.appendMessage({
- role: "user",
- content: [{ type: "text", text: "before compaction" }],
- timestamp: preCompactionTimestamp - 1000,
- });
- sessionManager.appendMessage(keptAssistant);
- const firstKeptEntryId = sessionManager.getEntries()[0]!.id;
- sessionManager.appendCompaction("summary", firstKeptEntryId, keptAssistant.usage.totalTokens, undefined, false);
- // Post-compaction error message
- const errorAssistant: AssistantMessage = {
- role: "assistant",
- content: [{ type: "text", text: "" }],
- api: model.api,
- provider: model.provider,
- model: model.id,
- usage: {
- input: 0,
- output: 0,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 0,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- },
- stopReason: "error",
- errorMessage: "529 overloaded",
- timestamp: Date.now(),
- };
- // Agent state has the kept assistant (pre-compaction) and the error (post-compaction)
- session.agent.state.messages = [
- { role: "user", content: [{ type: "text", text: "kept user msg" }], timestamp: preCompactionTimestamp - 1000 },
- keptAssistant,
- { role: "user", content: [{ type: "text", text: "new prompt" }], timestamp: Date.now() - 500 },
- errorAssistant,
- ];
- const runAutoCompactionSpy = vi
- .spyOn(
- session as unknown as {
- _runAutoCompaction: (reason: "overflow" | "threshold", willRetry: boolean) => Promise<void>;
- },
- "_runAutoCompaction",
- )
- .mockResolvedValue();
- const checkCompaction = (
- session as unknown as {
- _checkCompaction: (assistantMessage: AssistantMessage, skipAbortedCheck?: boolean) => Promise<void>;
- }
- )._checkCompaction.bind(session);
- await checkCompaction(errorAssistant);
- // Should NOT compact because the only usage data is from a kept pre-compaction message
- expect(runAutoCompactionSpy).not.toHaveBeenCalled();
- });
- });
|