fix: auto compaction between tool calls

This commit is contained in:
Nate 2025-08-22 21:13:09 -07:00
parent 1000694b63
commit 4c829d776b
7 changed files with 491 additions and 118 deletions

View file

@ -28,7 +28,6 @@ import { logger } from "../util/logger.js";
import {
calculateContextUsagePercentage,
countChatHistoryTokens,
getAutoCompactMessage,
shouldAutoCompact,
} from "../util/tokenizer.js";
@ -160,7 +159,7 @@ async function handleManualCompaction(
}
}
// Helper function to handle auto-compaction
// Helper function to handle auto-compaction for headless mode
async function handleAutoCompaction(
chatHistory: ChatCompletionMessageParam[],
model: ModelConfig,
@ -168,60 +167,68 @@ async function handleAutoCompaction(
isHeadless: boolean,
format?: "json",
): Promise<number | null> {
logger.info("Auto-compacting triggered due to context limit");
const { handleAutoCompaction: coreAutoCompaction } = await import(
"../streamChatResponse.autoCompaction.js"
);
if (!isHeadless) {
console.info(chalk.yellow(`\n${getAutoCompactMessage(model)}`));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "info",
message: "Auto-compacting triggered",
contextUsage:
calculateContextUsagePercentage(
countChatHistoryTokens(chatHistory),
model,
) + "%",
}) + "\n",
);
}
// Custom callbacks for headless mode console output
const callbacks = {
onSystemMessage: (message: string) => {
if (message.includes("Auto-compacting") || message.includes("Approaching")) {
if (!isHeadless) {
console.info(chalk.yellow(`\n${message}`));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "info",
message: "Auto-compacting triggered",
contextUsage:
calculateContextUsagePercentage(
countChatHistoryTokens(chatHistory),
model,
) + "%",
}) + "\n",
);
}
} else if (message.includes("✓")) {
if (!isHeadless) {
console.info(chalk.green(message));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "success",
message: "Auto-compacted successfully",
historyLength: chatHistory.length,
}) + "\n",
);
}
} else if (message.includes("Warning:")) {
if (!isHeadless) {
console.error(chalk.red(message));
console.info(chalk.yellow("Continuing without compaction..."));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "warning",
message: "Auto-compaction failed, continuing without compaction",
}) + "\n",
);
}
}
},
};
try {
const result = await compactChatHistory(chatHistory, model, llmApi);
chatHistory.length = 0;
chatHistory.push(...result.compactedHistory);
saveSession(chatHistory);
const result = await coreAutoCompaction(chatHistory, model, llmApi, {
isHeadless,
format,
callbacks,
});
if (!isHeadless) {
console.info(chalk.green("✓ Chat history auto-compacted successfully."));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "success",
message: "Auto-compacted successfully",
historyLength: chatHistory.length,
}) + "\n",
);
}
// Update the original array reference for headless mode
chatHistory.length = 0;
chatHistory.push(...result.chatHistory);
return result.compactionIndex;
} catch (error) {
const errorMsg = `Auto-compaction error: ${formatError(error)}`;
logger.error(errorMsg);
if (!isHeadless) {
console.error(chalk.red(`Warning: ${errorMsg}`));
console.info(chalk.yellow("Continuing without compaction..."));
} else if (format === "json") {
safeStdout(
JSON.stringify({
status: "warning",
message: "Auto-compaction failed, continuing without compaction",
}) + "\n",
);
}
return null;
}
return result.compactionIndex;
}
interface ProcessMessageOptions {

View file

@ -0,0 +1,208 @@
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
// Mock dependencies
vi.mock("./compaction.js", () => ({
compactChatHistory: vi.fn(),
}));
vi.mock("./session.js", () => ({
saveSession: vi.fn(),
}));
vi.mock("./util/tokenizer.js", () => ({
shouldAutoCompact: vi.fn(),
getAutoCompactMessage: vi.fn(),
}));
vi.mock("./util/formatError.js", () => ({
formatError: vi.fn((error) => error.message || String(error)),
}));
vi.mock("./util/logger.js", () => ({
logger: {
info: vi.fn(),
debug: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
}));
describe("handleAutoCompaction", () => {
const mockModel = {
provider: "openai",
name: "gpt-4",
model: "gpt-4",
defaultCompletionOptions: {
contextLength: 8192,
maxTokens: 2048,
},
} as any;
const mockLlmApi = {} as any;
const mockChatHistory: ChatCompletionMessageParam[] = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there!" },
];
beforeEach(() => {
vi.clearAllMocks();
});
it("should return original history when auto-compaction is not needed", async () => {
const { shouldAutoCompact } = await import("./util/tokenizer.js");
vi.mocked(shouldAutoCompact).mockReturnValue(false);
const result = await handleAutoCompaction(
mockChatHistory,
mockModel,
mockLlmApi,
{},
);
expect(result).toEqual({
chatHistory: mockChatHistory,
compactionIndex: null,
});
expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel);
});
it("should perform auto-compaction when context limit is approaching", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
const { compactChatHistory } = await import("./compaction.js");
const { saveSession } = await import("./session.js");
vi.mocked(shouldAutoCompact).mockReturnValue(true);
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
const mockCompactionResult = {
compactedHistory: [
{ role: "system", content: "You are a helpful assistant." } as ChatCompletionMessageParam,
{ role: "assistant", content: "[COMPACTED HISTORY]\nConversation summary..." } as ChatCompletionMessageParam,
],
compactionIndex: 1,
compactionContent: "Conversation summary...",
};
vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult);
const mockCallbacks = {
onSystemMessage: vi.fn(),
};
const result = await handleAutoCompaction(
mockChatHistory,
mockModel,
mockLlmApi,
{
isHeadless: false,
callbacks: mockCallbacks,
},
);
expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel);
expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel);
expect(compactChatHistory).toHaveBeenCalledWith(
mockChatHistory,
mockModel,
mockLlmApi,
expect.any(Object),
);
expect(saveSession).toHaveBeenCalledWith(mockCompactionResult.compactedHistory);
expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith("Auto-compacting...");
expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith("✓ Chat history auto-compacted successfully.");
expect(result).toEqual({
chatHistory: mockCompactionResult.compactedHistory,
compactionIndex: mockCompactionResult.compactionIndex,
});
});
it("should handle compaction errors gracefully", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
const { compactChatHistory } = await import("./compaction.js");
const { logger } = await import("./util/logger.js");
vi.mocked(shouldAutoCompact).mockReturnValue(true);
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
vi.mocked(compactChatHistory).mockRejectedValue(new Error("Compaction failed"));
const mockCallbacks = {
onSystemMessage: vi.fn(),
};
const result = await handleAutoCompaction(
mockChatHistory,
mockModel,
mockLlmApi,
{
isHeadless: false,
callbacks: mockCallbacks,
},
);
expect(logger.error).toHaveBeenCalledWith(
expect.stringContaining("Auto-compaction error"),
);
expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith(
expect.stringContaining("Warning: Auto-compaction error"),
);
// Should return original history on error
expect(result).toEqual({
chatHistory: mockChatHistory,
compactionIndex: null,
});
});
it("should not call system message callback in headless mode", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
const { compactChatHistory } = await import("./compaction.js");
vi.mocked(shouldAutoCompact).mockReturnValue(true);
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
const mockCompactionResult = {
compactedHistory: [{ role: "system", content: "System" } as ChatCompletionMessageParam],
compactionIndex: 0,
compactionContent: "Summary",
};
vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult);
const mockCallbacks = {
onSystemMessage: vi.fn(),
};
await handleAutoCompaction(
mockChatHistory,
mockModel,
mockLlmApi,
{
isHeadless: true,
callbacks: mockCallbacks,
},
);
expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled();
});
it("should handle missing model gracefully", async () => {
const result = await handleAutoCompaction(
mockChatHistory,
null as any,
mockLlmApi,
{},
);
expect(result).toEqual({
chatHistory: mockChatHistory,
compactionIndex: null,
});
});
});

View file

@ -0,0 +1,176 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import React from "react";
import { compactChatHistory } from "./compaction.js";
import { saveSession } from "./session.js";
import { DisplayMessage } from "./ui/types.js";
import { formatError } from "./util/formatError.js";
import { logger } from "./util/logger.js";
import {
getAutoCompactMessage,
shouldAutoCompact,
} from "./util/tokenizer.js";
interface AutoCompactionCallbacks {
// For streaming mode
onSystemMessage?: (message: string) => void;
onContent?: (content: string) => void;
// For TUI mode
setMessages?: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setChatHistory?: React.Dispatch<React.SetStateAction<ChatCompletionMessageParam[]>>;
setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>;
// For headless mode - no callbacks needed, just return values
}
interface AutoCompactionOptions {
isHeadless?: boolean;
format?: "json";
callbacks?: AutoCompactionCallbacks;
}
/**
* Notify user about compaction start
*/
function notifyCompactionStart(
message: string,
isHeadless: boolean,
callbacks?: AutoCompactionCallbacks,
) {
if (isHeadless) return;
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(message);
} else if (callbacks?.setMessages) {
callbacks.setMessages((prev) => [
...prev,
{
role: "system",
content: message,
messageType: "system" as const,
},
]);
}
}
/**
* Handle successful compaction state updates
*/
function handleCompactionSuccess(
result: any,
isHeadless: boolean,
callbacks?: AutoCompactionCallbacks,
) {
if (isHeadless) return;
const successMessage = "✓ Chat history auto-compacted successfully.";
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(successMessage);
} else if (callbacks?.setMessages && callbacks?.setChatHistory && callbacks?.setCompactionIndex) {
callbacks.setChatHistory(result.compactedHistory);
callbacks.setCompactionIndex(result.compactionIndex);
callbacks.setMessages((prev) => [
...prev,
{
role: "system",
content: successMessage,
messageType: "system" as const,
},
]);
}
}
/**
* Handle compaction error notification
*/
function handleCompactionError(
error: any,
isHeadless: boolean,
callbacks?: AutoCompactionCallbacks,
) {
const errorMessage = `Auto-compaction error: ${formatError(error)}`;
logger.error(errorMessage);
if (isHeadless) return;
const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`;
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(warningMessage);
} else if (callbacks?.setMessages) {
callbacks.setMessages((prev) => [
...prev,
{
role: "system",
content: warningMessage,
messageType: "system" as const,
},
]);
}
}
/**
* Unified auto-compaction handler for all modes (streaming, TUI, headless)
* @param chatHistory Current chat history
* @param model Model configuration
* @param llmApi LLM API instance
* @param options Configuration options for different usage contexts
* @returns Updated chat history and compaction index, or original if no compaction needed
*/
export async function handleAutoCompaction(
chatHistory: ChatCompletionMessageParam[],
model: ModelConfig,
llmApi: BaseLlmApi,
options: AutoCompactionOptions = {},
): Promise<{
chatHistory: ChatCompletionMessageParam[];
compactionIndex: number | null;
}> {
const { isHeadless = false, callbacks } = options;
if (!model || !shouldAutoCompact(chatHistory, model)) {
return { chatHistory, compactionIndex: null };
}
logger.info(`Auto-compaction triggered${isHeadless ? ' in headless mode' : ''}`);
// Notify about compaction start
notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks);
try {
// Compact the history
const result = await compactChatHistory(
chatHistory,
model,
llmApi,
isHeadless
? undefined
: {
onStreamContent: callbacks?.onContent,
onStreamComplete: () => {},
},
);
// Save the compacted session
saveSession(result.compactedHistory);
// Handle success notification
handleCompactionSuccess(result, isHeadless, callbacks);
return {
chatHistory: result.compactedHistory,
compactionIndex: result.compactionIndex,
};
} catch (error: any) {
// Handle error notification
handleCompactionError(error, isHeadless, callbacks);
// Continue without compaction on error
return { chatHistory, compactionIndex: null };
}
}

View file

@ -15,6 +15,7 @@ import {
SERVICE_NAMES,
} from "./services/index.js";
import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
import {
executeStreamedToolCalls,
preprocessStreamedToolCalls,
@ -513,6 +514,24 @@ export async function streamChatResponse(
return finalResponse || content || fullResponse;
}
// Check for auto-compaction after tool execution
if (shouldContinue) {
const { chatHistory: updatedChatHistory, compactionIndex } =
await handleAutoCompaction(chatHistory, model, llmApi, {
isHeadless,
callbacks: {
onSystemMessage: callbacks?.onSystemMessage,
onContent: callbacks?.onContent,
},
});
// Only update chat history if compaction actually occurred
if (compactionIndex !== null && updatedChatHistory !== chatHistory) {
chatHistory.length = 0;
chatHistory.push(...updatedChatHistory);
}
}
// Check if we should continue
if (!shouldContinue) {
break;

View file

@ -15,6 +15,7 @@ export interface StreamCallbacks {
requestId: string,
preview?: ToolCallPreview[],
) => void;
onSystemMessage?: (message: string) => void;
}
export function getDefaultCompletionOptions(

View file

@ -7,10 +7,6 @@ import { posthogService } from "../../telemetry/posthogService.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import { formatError } from "../../util/formatError.js";
import { logger } from "../../util/logger.js";
import {
getAutoCompactMessage,
shouldAutoCompact,
} from "../../util/tokenizer.js";
import { DisplayMessage } from "../types.js";
import { SlashCommandResult } from "./useChat.types.js";
@ -281,13 +277,13 @@ interface HandleAutoCompactionOptions {
}
/**
* Handle auto-compaction when approaching context limit
* Handle auto-compaction when approaching context limit - TUI wrapper
*/
export async function handleAutoCompaction({
chatHistory,
model,
llmApi,
compactionIndex,
compactionIndex: _compactionIndex,
setMessages,
setChatHistory,
setCompactionIndex,
@ -295,69 +291,25 @@ export async function handleAutoCompaction({
currentChatHistory: ChatCompletionMessageParam[];
currentCompactionIndex: number | null;
}> {
if (!model || !shouldAutoCompact(chatHistory, model)) {
return {
currentChatHistory: chatHistory,
currentCompactionIndex: compactionIndex,
};
if (!llmApi) {
throw new Error("LLM API is not available for auto-compaction");
}
logger.info("Auto-compacting triggered in TUI mode");
const { handleAutoCompaction: coreAutoCompaction } = await import(
"../../streamChatResponse.autoCompaction.js"
);
setMessages((prev) => [
...prev,
{
role: "system",
content: getAutoCompactMessage(model),
messageType: "system" as const,
const result = await coreAutoCompaction(chatHistory, model, llmApi, {
isHeadless: false,
callbacks: {
setMessages,
setChatHistory,
setCompactionIndex,
},
]);
});
try {
if (!llmApi) {
throw new Error("LLM API is not available for auto-compaction");
}
// Compact the history WITHOUT the current user message
const result = await compactChatHistory(chatHistory, model, llmApi);
// Update state
setChatHistory(result.compactedHistory);
setCompactionIndex(result.compactionIndex);
// Save the compacted session
saveSession(result.compactedHistory);
setMessages((prev) => [
...prev,
{
role: "system",
content: "✓ Chat history auto-compacted successfully.",
messageType: "system" as const,
},
]);
return {
currentChatHistory: result.compactedHistory,
currentCompactionIndex: result.compactionIndex,
};
} catch (error: any) {
const errorMessage = `Auto-compaction error: ${formatError(error)}`;
logger.error(errorMessage);
setMessages((prev) => [
...prev,
{
role: "system",
content: `Warning: ${errorMessage}. Continuing without compaction...`,
messageType: "system" as const,
},
]);
// Continue without compaction on error
return {
currentChatHistory: chatHistory,
currentCompactionIndex: compactionIndex,
};
}
return {
currentChatHistory: result.chatHistory,
currentCompactionIndex: result.compactionIndex,
};
}

View file

@ -111,6 +111,16 @@ export function createStreamCallbacks(
toolCallPreview,
});
},
onSystemMessage: (message: string) => {
setMessages((prev) => [
...prev,
{
role: "system",
content: message,
messageType: "system" as const,
},
]);
},
};
}