Elffuss BraidHub

kikocis/continue public

fix: auto compaction between tool calls
Changesete0c6756e65e23bca92bc2c1cd43626822a9eed60f3326a37626002fef091ff11
AuthorNate <sestinj@gmail.com> · 2025-08-22 21:13 -07:00
CommitterNate <sestinj@gmail.com> · 2025-08-22 21:13 -07:00
Parentsb87cf24dd006

Browse the files at this changeset

7 files changed

modified extensions/cli/src/commands/chat.ts +63 −56
@@ -28,7 +28,6 @@
2828 import {
2929 calculateContextUsagePercentage,
3030 countChatHistoryTokens,
31- getAutoCompactMessage,
3231 shouldAutoCompact,
3332 } from "../util/tokenizer.js";
3433
@@ -160,7 +159,7 @@
160159 }
161160 }
162161
163-// Helper function to handle auto-compaction
162+// Helper function to handle auto-compaction for headless mode
164163 async function handleAutoCompaction(
165164 chatHistory: ChatCompletionMessageParam[],
166165 model: ModelConfig,
@@ -168,60 +167,68 @@
168167 isHeadless: boolean,
169168 format?: "json",
170169 ): Promise<number | null> {
171- logger.info("Auto-compacting triggered due to context limit");
172-
173- if (!isHeadless) {
174- console.info(chalk.yellow(`\n${getAutoCompactMessage(model)}`));
175- } else if (format === "json") {
176- safeStdout(
177- JSON.stringify({
178- status: "info",
179- message: "Auto-compacting triggered",
180- contextUsage:
181- calculateContextUsagePercentage(
182- countChatHistoryTokens(chatHistory),
183- model,
184- ) + "%",
185- }) + "\n",
186- );
187- }
188-
189- try {
190- const result = await compactChatHistory(chatHistory, model, llmApi);
191- chatHistory.length = 0;
192- chatHistory.push(...result.compactedHistory);
193- saveSession(chatHistory);
194-
195- if (!isHeadless) {
196- console.info(chalk.green("✓ Chat history auto-compacted successfully."));
197- } else if (format === "json") {
198- safeStdout(
199- JSON.stringify({
200- status: "success",
201- message: "Auto-compacted successfully",
202- historyLength: chatHistory.length,
203- }) + "\n",
204- );
205- }
206-
207- return result.compactionIndex;
208- } catch (error) {
209- const errorMsg = `Auto-compaction error: ${formatError(error)}`;
210- logger.error(errorMsg);
211-
212- if (!isHeadless) {
213- console.error(chalk.red(`Warning: ${errorMsg}`));
214- console.info(chalk.yellow("Continuing without compaction..."));
215- } else if (format === "json") {
216- safeStdout(
217- JSON.stringify({
218- status: "warning",
219- message: "Auto-compaction failed, continuing without compaction",
220- }) + "\n",
221- );
222- }
223- return null;
224- }
170+ const { handleAutoCompaction: coreAutoCompaction } = await import(
171+ "../streamChatResponse.autoCompaction.js"
172+ );
173+
174+ // Custom callbacks for headless mode console output
175+ const callbacks = {
176+ onSystemMessage: (message: string) => {
177+ if (message.includes("Auto-compacting") || message.includes("Approaching")) {
178+ if (!isHeadless) {
179+ console.info(chalk.yellow(`\n${message}`));
180+ } else if (format === "json") {
181+ safeStdout(
182+ JSON.stringify({
183+ status: "info",
184+ message: "Auto-compacting triggered",
185+ contextUsage:
186+ calculateContextUsagePercentage(
187+ countChatHistoryTokens(chatHistory),
188+ model,
189+ ) + "%",
190+ }) + "\n",
191+ );
192+ }
193+ } else if (message.includes("✓")) {
194+ if (!isHeadless) {
195+ console.info(chalk.green(message));
196+ } else if (format === "json") {
197+ safeStdout(
198+ JSON.stringify({
199+ status: "success",
200+ message: "Auto-compacted successfully",
201+ historyLength: chatHistory.length,
202+ }) + "\n",
203+ );
204+ }
205+ } else if (message.includes("Warning:")) {
206+ if (!isHeadless) {
207+ console.error(chalk.red(message));
208+ console.info(chalk.yellow("Continuing without compaction..."));
209+ } else if (format === "json") {
210+ safeStdout(
211+ JSON.stringify({
212+ status: "warning",
213+ message: "Auto-compaction failed, continuing without compaction",
214+ }) + "\n",
215+ );
216+ }
217+ }
218+ },
219+ };
220+
221+ const result = await coreAutoCompaction(chatHistory, model, llmApi, {
222+ isHeadless,
223+ format,
224+ callbacks,
225+ });
226+
227+ // Update the original array reference for headless mode
228+ chatHistory.length = 0;
229+ chatHistory.push(...result.chatHistory);
230+
231+ return result.compactionIndex;
225232 }
226233
227234 interface ProcessMessageOptions {
added extensions/cli/src/streamChatResponse.autoCompaction.test.ts +208 −0
@@ -0,0 +1,208 @@
1+import { ChatCompletionMessageParam } from "openai/resources.mjs";
2+import { describe, it, expect, vi, beforeEach } from "vitest";
3+
4+import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
5+
6+// Mock dependencies
7+vi.mock("./compaction.js", () => ({
8+ compactChatHistory: vi.fn(),
9+}));
10+
11+vi.mock("./session.js", () => ({
12+ saveSession: vi.fn(),
13+}));
14+
15+vi.mock("./util/tokenizer.js", () => ({
16+ shouldAutoCompact: vi.fn(),
17+ getAutoCompactMessage: vi.fn(),
18+}));
19+
20+vi.mock("./util/formatError.js", () => ({
21+ formatError: vi.fn((error) => error.message || String(error)),
22+}));
23+
24+vi.mock("./util/logger.js", () => ({
25+ logger: {
26+ info: vi.fn(),
27+ debug: vi.fn(),
28+ error: vi.fn(),
29+ warn: vi.fn(),
30+ },
31+}));
32+
33+describe("handleAutoCompaction", () => {
34+ const mockModel = {
35+ provider: "openai",
36+ name: "gpt-4",
37+ model: "gpt-4",
38+ defaultCompletionOptions: {
39+ contextLength: 8192,
40+ maxTokens: 2048,
41+ },
42+ } as any;
43+
44+ const mockLlmApi = {} as any;
45+ const mockChatHistory: ChatCompletionMessageParam[] = [
46+ { role: "system", content: "You are a helpful assistant." },
47+ { role: "user", content: "Hello" },
48+ { role: "assistant", content: "Hi there!" },
49+ ];
50+
51+ beforeEach(() => {
52+ vi.clearAllMocks();
53+ });
54+
55+ it("should return original history when auto-compaction is not needed", async () => {
56+ const { shouldAutoCompact } = await import("./util/tokenizer.js");
57+ vi.mocked(shouldAutoCompact).mockReturnValue(false);
58+
59+ const result = await handleAutoCompaction(
60+ mockChatHistory,
61+ mockModel,
62+ mockLlmApi,
63+ {},
64+ );
65+
66+ expect(result).toEqual({
67+ chatHistory: mockChatHistory,
68+ compactionIndex: null,
69+ });
70+
71+ expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel);
72+ });
73+
74+ it("should perform auto-compaction when context limit is approaching", async () => {
75+ const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
76+ const { compactChatHistory } = await import("./compaction.js");
77+ const { saveSession } = await import("./session.js");
78+
79+ vi.mocked(shouldAutoCompact).mockReturnValue(true);
80+ vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
81+
82+ const mockCompactionResult = {
83+ compactedHistory: [
84+ { role: "system", content: "You are a helpful assistant." } as ChatCompletionMessageParam,
85+ { role: "assistant", content: "[COMPACTED HISTORY]\nConversation summary..." } as ChatCompletionMessageParam,
86+ ],
87+ compactionIndex: 1,
88+ compactionContent: "Conversation summary...",
89+ };
90+
91+ vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult);
92+
93+ const mockCallbacks = {
94+ onSystemMessage: vi.fn(),
95+ };
96+
97+ const result = await handleAutoCompaction(
98+ mockChatHistory,
99+ mockModel,
100+ mockLlmApi,
101+ {
102+ isHeadless: false,
103+ callbacks: mockCallbacks,
104+ },
105+ );
106+
107+ expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel);
108+ expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel);
109+ expect(compactChatHistory).toHaveBeenCalledWith(
110+ mockChatHistory,
111+ mockModel,
112+ mockLlmApi,
113+ expect.any(Object),
114+ );
115+ expect(saveSession).toHaveBeenCalledWith(mockCompactionResult.compactedHistory);
116+
117+ expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith("Auto-compacting...");
118+ expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith("✓ Chat history auto-compacted successfully.");
119+
120+ expect(result).toEqual({
121+ chatHistory: mockCompactionResult.compactedHistory,
122+ compactionIndex: mockCompactionResult.compactionIndex,
123+ });
124+ });
125+
126+ it("should handle compaction errors gracefully", async () => {
127+ const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
128+ const { compactChatHistory } = await import("./compaction.js");
129+ const { logger } = await import("./util/logger.js");
130+
131+ vi.mocked(shouldAutoCompact).mockReturnValue(true);
132+ vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
133+ vi.mocked(compactChatHistory).mockRejectedValue(new Error("Compaction failed"));
134+
135+ const mockCallbacks = {
136+ onSystemMessage: vi.fn(),
137+ };
138+
139+ const result = await handleAutoCompaction(
140+ mockChatHistory,
141+ mockModel,
142+ mockLlmApi,
143+ {
144+ isHeadless: false,
145+ callbacks: mockCallbacks,
146+ },
147+ );
148+
149+ expect(logger.error).toHaveBeenCalledWith(
150+ expect.stringContaining("Auto-compaction error"),
151+ );
152+ expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith(
153+ expect.stringContaining("Warning: Auto-compaction error"),
154+ );
155+
156+ // Should return original history on error
157+ expect(result).toEqual({
158+ chatHistory: mockChatHistory,
159+ compactionIndex: null,
160+ });
161+ });
162+
163+ it("should not call system message callback in headless mode", async () => {
164+ const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
165+ const { compactChatHistory } = await import("./compaction.js");
166+
167+ vi.mocked(shouldAutoCompact).mockReturnValue(true);
168+ vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
169+
170+ const mockCompactionResult = {
171+ compactedHistory: [{ role: "system", content: "System" } as ChatCompletionMessageParam],
172+ compactionIndex: 0,
173+ compactionContent: "Summary",
174+ };
175+
176+ vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult);
177+
178+ const mockCallbacks = {
179+ onSystemMessage: vi.fn(),
180+ };
181+
182+ await handleAutoCompaction(
183+ mockChatHistory,
184+ mockModel,
185+ mockLlmApi,
186+ {
187+ isHeadless: true,
188+ callbacks: mockCallbacks,
189+ },
190+ );
191+
192+ expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled();
193+ });
194+
195+ it("should handle missing model gracefully", async () => {
196+ const result = await handleAutoCompaction(
197+ mockChatHistory,
198+ null as any,
199+ mockLlmApi,
200+ {},
201+ );
202+
203+ expect(result).toEqual({
204+ chatHistory: mockChatHistory,
205+ compactionIndex: null,
206+ });
207+ });
208+});
No newline at the end of the file
added extensions/cli/src/streamChatResponse.autoCompaction.ts +176 −0
@@ -0,0 +1,176 @@
1+import { ModelConfig } from "@continuedev/config-yaml";
2+import { BaseLlmApi } from "@continuedev/openai-adapters";
3+import type { ChatCompletionMessageParam } from "openai/resources.mjs";
4+import React from "react";
5+
6+import { compactChatHistory } from "./compaction.js";
7+import { saveSession } from "./session.js";
8+import { DisplayMessage } from "./ui/types.js";
9+import { formatError } from "./util/formatError.js";
10+import { logger } from "./util/logger.js";
11+import {
12+ getAutoCompactMessage,
13+ shouldAutoCompact,
14+} from "./util/tokenizer.js";
15+
16+interface AutoCompactionCallbacks {
17+ // For streaming mode
18+ onSystemMessage?: (message: string) => void;
19+ onContent?: (content: string) => void;
20+
21+ // For TUI mode
22+ setMessages?: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
23+ setChatHistory?: React.Dispatch<React.SetStateAction<ChatCompletionMessageParam[]>>;
24+ setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>;
25+
26+ // For headless mode - no callbacks needed, just return values
27+}
28+
29+interface AutoCompactionOptions {
30+ isHeadless?: boolean;
31+ format?: "json";
32+ callbacks?: AutoCompactionCallbacks;
33+}
34+
35+/**
36+ * Notify user about compaction start
37+ */
38+function notifyCompactionStart(
39+ message: string,
40+ isHeadless: boolean,
41+ callbacks?: AutoCompactionCallbacks,
42+) {
43+ if (isHeadless) return;
44+
45+ if (callbacks?.onSystemMessage) {
46+ callbacks.onSystemMessage(message);
47+ } else if (callbacks?.setMessages) {
48+ callbacks.setMessages((prev) => [
49+ ...prev,
50+ {
51+ role: "system",
52+ content: message,
53+ messageType: "system" as const,
54+ },
55+ ]);
56+ }
57+}
58+
59+/**
60+ * Handle successful compaction state updates
61+ */
62+function handleCompactionSuccess(
63+ result: any,
64+ isHeadless: boolean,
65+ callbacks?: AutoCompactionCallbacks,
66+) {
67+ if (isHeadless) return;
68+
69+ const successMessage = "✓ Chat history auto-compacted successfully.";
70+
71+ if (callbacks?.onSystemMessage) {
72+ callbacks.onSystemMessage(successMessage);
73+ } else if (callbacks?.setMessages && callbacks?.setChatHistory && callbacks?.setCompactionIndex) {
74+ callbacks.setChatHistory(result.compactedHistory);
75+ callbacks.setCompactionIndex(result.compactionIndex);
76+ callbacks.setMessages((prev) => [
77+ ...prev,
78+ {
79+ role: "system",
80+ content: successMessage,
81+ messageType: "system" as const,
82+ },
83+ ]);
84+ }
85+}
86+
87+/**
88+ * Handle compaction error notification
89+ */
90+function handleCompactionError(
91+ error: any,
92+ isHeadless: boolean,
93+ callbacks?: AutoCompactionCallbacks,
94+) {
95+ const errorMessage = `Auto-compaction error: ${formatError(error)}`;
96+ logger.error(errorMessage);
97+
98+ if (isHeadless) return;
99+
100+ const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`;
101+
102+ if (callbacks?.onSystemMessage) {
103+ callbacks.onSystemMessage(warningMessage);
104+ } else if (callbacks?.setMessages) {
105+ callbacks.setMessages((prev) => [
106+ ...prev,
107+ {
108+ role: "system",
109+ content: warningMessage,
110+ messageType: "system" as const,
111+ },
112+ ]);
113+ }
114+}
115+
116+/**
117+ * Unified auto-compaction handler for all modes (streaming, TUI, headless)
118+ * @param chatHistory Current chat history
119+ * @param model Model configuration
120+ * @param llmApi LLM API instance
121+ * @param options Configuration options for different usage contexts
122+ * @returns Updated chat history and compaction index, or original if no compaction needed
123+ */
124+export async function handleAutoCompaction(
125+ chatHistory: ChatCompletionMessageParam[],
126+ model: ModelConfig,
127+ llmApi: BaseLlmApi,
128+ options: AutoCompactionOptions = {},
129+): Promise<{
130+ chatHistory: ChatCompletionMessageParam[];
131+ compactionIndex: number | null;
132+}> {
133+ const { isHeadless = false, callbacks } = options;
134+
135+ if (!model || !shouldAutoCompact(chatHistory, model)) {
136+ return { chatHistory, compactionIndex: null };
137+ }
138+
139+ logger.info(`Auto-compaction triggered${isHeadless ? ' in headless mode' : ''}`);
140+
141+ // Notify about compaction start
142+ notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks);
143+
144+ try {
145+ // Compact the history
146+ const result = await compactChatHistory(
147+ chatHistory,
148+ model,
149+ llmApi,
150+ isHeadless
151+ ? undefined
152+ : {
153+ onStreamContent: callbacks?.onContent,
154+ onStreamComplete: () => {},
155+ },
156+ );
157+
158+ // Save the compacted session
159+ saveSession(result.compactedHistory);
160+
161+ // Handle success notification
162+ handleCompactionSuccess(result, isHeadless, callbacks);
163+
164+ return {
165+ chatHistory: result.compactedHistory,
166+ compactionIndex: result.compactionIndex,
167+ };
168+ } catch (error: any) {
169+ // Handle error notification
170+ handleCompactionError(error, isHeadless, callbacks);
171+
172+ // Continue without compaction on error
173+ return { chatHistory, compactionIndex: null };
174+ }
175+}
176+
modified extensions/cli/src/streamChatResponse.ts +19 −0
@@ -15,6 +15,7 @@
1515 SERVICE_NAMES,
1616 } from "./services/index.js";
1717 import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
18+import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
1819 import {
1920 executeStreamedToolCalls,
2021 preprocessStreamedToolCalls,
@@ -513,6 +514,24 @@
513514 return finalResponse || content || fullResponse;
514515 }
515516
517+ // Check for auto-compaction after tool execution
518+ if (shouldContinue) {
519+ const { chatHistory: updatedChatHistory, compactionIndex } =
520+ await handleAutoCompaction(chatHistory, model, llmApi, {
521+ isHeadless,
522+ callbacks: {
523+ onSystemMessage: callbacks?.onSystemMessage,
524+ onContent: callbacks?.onContent,
525+ },
526+ });
527+
528+ // Only update chat history if compaction actually occurred
529+ if (compactionIndex !== null && updatedChatHistory !== chatHistory) {
530+ chatHistory.length = 0;
531+ chatHistory.push(...updatedChatHistory);
532+ }
533+ }
534+
516535 // Check if we should continue
517536 if (!shouldContinue) {
518537 break;
modified extensions/cli/src/streamChatResponse.types.ts +1 −0
@@ -15,6 +15,7 @@
1515 requestId: string,
1616 preview?: ToolCallPreview[],
1717 ) => void;
18+ onSystemMessage?: (message: string) => void;
1819 }
1920
2021 export function getDefaultCompletionOptions(
modified extensions/cli/src/ui/hooks/useChat.helpers.ts +19 −67
@@ -7,10 +7,6 @@
77 import { telemetryService } from "../../telemetry/telemetryService.js";
88 import { formatError } from "../../util/formatError.js";
99 import { logger } from "../../util/logger.js";
10-import {
11- getAutoCompactMessage,
12- shouldAutoCompact,
13-} from "../../util/tokenizer.js";
1410 import { DisplayMessage } from "../types.js";
1511
1612 import { SlashCommandResult } from "./useChat.types.js";
@@ -281,13 +277,13 @@
281277 }
282278
283279 /**
284- * Handle auto-compaction when approaching context limit
280+ * Handle auto-compaction when approaching context limit - TUI wrapper
285281 */
286282 export async function handleAutoCompaction({
287283 chatHistory,
288284 model,
289285 llmApi,
290- compactionIndex,
286+ compactionIndex: _compactionIndex,
291287 setMessages,
292288 setChatHistory,
293289 setCompactionIndex,
@@ -295,69 +291,25 @@
295291 currentChatHistory: ChatCompletionMessageParam[];
296292 currentCompactionIndex: number | null;
297293 }> {
298- if (!model || !shouldAutoCompact(chatHistory, model)) {
299- return {
300- currentChatHistory: chatHistory,
301- currentCompactionIndex: compactionIndex,
302- };
294+ if (!llmApi) {
295+ throw new Error("LLM API is not available for auto-compaction");
303296 }
304297
305- logger.info("Auto-compacting triggered in TUI mode");
306-
307- setMessages((prev) => [
308- ...prev,
309- {
310- role: "system",
311- content: getAutoCompactMessage(model),
312- messageType: "system" as const,
298+ const { handleAutoCompaction: coreAutoCompaction } = await import(
299+ "../../streamChatResponse.autoCompaction.js"
300+ );
301+
302+ const result = await coreAutoCompaction(chatHistory, model, llmApi, {
303+ isHeadless: false,
304+ callbacks: {
305+ setMessages,
306+ setChatHistory,
307+ setCompactionIndex,
313308 },
314- ]);
315-
316- try {
317- if (!llmApi) {
318- throw new Error("LLM API is not available for auto-compaction");
319- }
320-
321- // Compact the history WITHOUT the current user message
322- const result = await compactChatHistory(chatHistory, model, llmApi);
323-
324- // Update state
325- setChatHistory(result.compactedHistory);
326- setCompactionIndex(result.compactionIndex);
327-
328- // Save the compacted session
329- saveSession(result.compactedHistory);
330-
331- setMessages((prev) => [
332- ...prev,
333- {
334- role: "system",
335- content: "✓ Chat history auto-compacted successfully.",
336- messageType: "system" as const,
337- },
338- ]);
339-
340- return {
341- currentChatHistory: result.compactedHistory,
342- currentCompactionIndex: result.compactionIndex,
343- };
344- } catch (error: any) {
345- const errorMessage = `Auto-compaction error: ${formatError(error)}`;
346- logger.error(errorMessage);
347-
348- setMessages((prev) => [
349- ...prev,
350- {
351- role: "system",
352- content: `Warning: ${errorMessage}. Continuing without compaction...`,
353- messageType: "system" as const,
354- },
355- ]);
309+ });
356310
357- // Continue without compaction on error
358- return {
359- currentChatHistory: chatHistory,
360- currentCompactionIndex: compactionIndex,
361- };
362- }
311+ return {
312+ currentChatHistory: result.chatHistory,
313+ currentCompactionIndex: result.compactionIndex,
314+ };
363315 }
modified extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +10 −0
@@ -111,6 +111,16 @@
111111 toolCallPreview,
112112 });
113113 },
114+ onSystemMessage: (message: string) => {
115+ setMessages((prev) => [
116+ ...prev,
117+ {
118+ role: "system",
119+ content: message,
120+ messageType: "system" as const,
121+ },
122+ ]);
123+ },
114124 };
115125 }
116126