chore: format

This commit is contained in:
Nate 2025-08-23 10:57:03 -07:00
parent a93c2bcb0d
commit bb41c5406e
7 changed files with 225 additions and 124 deletions

View file

@ -174,7 +174,10 @@ async function handleAutoCompaction(
// Custom callbacks for headless mode console output
const callbacks = {
onSystemMessage: (message: string) => {
if (message.includes("Auto-compacting") || message.includes("Approaching")) {
if (
message.includes("Auto-compacting") ||
message.includes("Approaching")
) {
if (!isHeadless) {
console.info(chalk.yellow(`\n${message}`));
} else if (format === "json") {

View file

@ -24,13 +24,15 @@ describe("compaction infinite loop prevention", () => {
defaultCompletionOptions: {
maxTokens: 1000,
contextLength: 4000,
}
},
} as ModelConfig;
const mockLlmApi = {} as BaseLlmApi;
it("should not loop infinitely when pruning doesn't reduce history size", async () => {
const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js");
const { countChatHistoryTokens, getModelContextLimit } = await import(
"./util/tokenizer.js"
);
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockCountTokens = vi.mocked(countChatHistoryTokens);
const mockGetContextLimit = vi.mocked(getModelContextLimit);
@ -38,11 +40,13 @@ describe("compaction infinite loop prevention", () => {
// Setup mocks
mockGetContextLimit.mockReturnValue(4000);
mockCountTokens.mockReturnValue(5000); // Always too big
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.();
return "Summary";
});
mockStreamResponse.mockImplementation(
async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.();
return "Summary";
},
);
// History that can't be pruned further (only system message)
const history: ChatCompletionMessageParam[] = [
@ -51,14 +55,16 @@ describe("compaction infinite loop prevention", () => {
// This should not hang - it should break out of the loop
const result = await compactChatHistory(history, mockModel, mockLlmApi);
// Should complete successfully even though token count is still too high
expect(result.compactedHistory).toBeDefined();
expect(mockCountTokens).toHaveBeenCalled();
});
it("should not loop infinitely with history ending in assistant message", async () => {
const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js");
const { countChatHistoryTokens, getModelContextLimit } = await import(
"./util/tokenizer.js"
);
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockCountTokens = vi.mocked(countChatHistoryTokens);
const mockGetContextLimit = vi.mocked(getModelContextLimit);
@ -66,11 +72,13 @@ describe("compaction infinite loop prevention", () => {
// Setup mocks
mockGetContextLimit.mockReturnValue(4000);
mockCountTokens.mockReturnValue(5000); // Always too big
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.();
return "Summary";
});
mockStreamResponse.mockImplementation(
async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.();
return "Summary";
},
);
// History that ends with assistant - pruning won't change it
const history: ChatCompletionMessageParam[] = [
@ -81,19 +89,21 @@ describe("compaction infinite loop prevention", () => {
// This should not hang
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toBeDefined();
});
it("should successfully prune when pruning actually reduces size", async () => {
const { countChatHistoryTokens, getModelContextLimit } = await import("./util/tokenizer.js");
const { countChatHistoryTokens, getModelContextLimit } = await import(
"./util/tokenizer.js"
);
const mockStreamResponse = vi.mocked(streamChatResponse);
const mockCountTokens = vi.mocked(countChatHistoryTokens);
const mockGetContextLimit = vi.mocked(getModelContextLimit);
// Setup mocks
mockGetContextLimit.mockReturnValue(4000);
// Mock token counting to show reduction after pruning
let callCount = 0;
mockCountTokens.mockImplementation(() => {
@ -102,12 +112,14 @@ describe("compaction infinite loop prevention", () => {
if (callCount === 2) return 3000; // After pruning, fits
return 2000; // Subsequent calls
});
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.();
return "Summary";
});
mockStreamResponse.mockImplementation(
async (history, model, api, controller, callbacks) => {
callbacks?.onContent?.("Summary");
callbacks?.onContentComplete?.();
return "Summary";
},
);
// History that can be successfully pruned
const history: ChatCompletionMessageParam[] = [
@ -118,9 +130,9 @@ describe("compaction infinite loop prevention", () => {
];
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toBeDefined();
// The function will call countTokens multiple times during the process
expect(mockCountTokens).toHaveBeenCalled();
});
});
});

View file

@ -53,16 +53,18 @@ describe("pruneLastMessage", () => {
];
const result = pruneLastMessage(history);
expect(result).toEqual([
{ role: "system", content: "System" },
]);
expect(result).toEqual([{ role: "system", content: "System" }]);
});
it("should remove assistant+tool sequence when second-to-last is assistant with tool calls", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System" },
{ role: "user", content: "Run command" },
{ role: "assistant", content: "Running...", tool_calls: [{ id: "1" } as any] },
{
role: "assistant",
content: "Running...",
tool_calls: [{ id: "1" } as any],
},
{ role: "tool", content: "Command output", tool_call_id: "1" },
];
@ -95,16 +97,18 @@ describe("pruneLastMessage", () => {
];
const result = pruneLastMessage(history);
expect(result).toEqual([
{ role: "system", content: "System" },
]);
expect(result).toEqual([{ role: "system", content: "System" }]);
});
it("should handle tool call sequences by removing user after tool", () => {
const history: ChatCompletionMessageParam[] = [
{ role: "system", content: "System" },
{ role: "user", content: "Do something" },
{ role: "assistant", content: "I'll help", tool_calls: [{ id: "1" } as any] },
{
role: "assistant",
content: "I'll help",
tool_calls: [{ id: "1" } as any],
},
{ role: "tool", content: "Tool result", tool_call_id: "1" },
{ role: "user", content: "Follow up question" },
];
@ -113,7 +117,11 @@ describe("pruneLastMessage", () => {
expect(result).toEqual([
{ role: "system", content: "System" },
{ role: "user", content: "Do something" },
{ role: "assistant", content: "I'll help", tool_calls: [{ id: "1" } as any] },
{
role: "assistant",
content: "I'll help",
tool_calls: [{ id: "1" } as any],
},
{ role: "tool", content: "Tool result", tool_call_id: "1" },
]);
});
@ -134,7 +142,11 @@ describe("pruneLastMessage", () => {
{ role: "user", content: "Request 1" },
{ role: "assistant", content: "Response 1" },
{ role: "user", content: "Request 2" },
{ role: "assistant", content: "Using tool", tool_calls: [{ id: "1" } as any] },
{
role: "assistant",
content: "Using tool",
tool_calls: [{ id: "1" } as any],
},
{ role: "tool", content: "Tool result", tool_call_id: "1" },
{ role: "assistant", content: "Final response" },
{ role: "user", content: "Follow up 1" },
@ -147,7 +159,11 @@ describe("pruneLastMessage", () => {
{ role: "user", content: "Request 1" },
{ role: "assistant", content: "Response 1" },
{ role: "user", content: "Request 2" },
{ role: "assistant", content: "Using tool", tool_calls: [{ id: "1" } as any] },
{
role: "assistant",
content: "Using tool",
tool_calls: [{ id: "1" } as any],
},
{ role: "tool", content: "Tool result", tool_call_id: "1" },
{ role: "assistant", content: "Final response" },
]);
@ -166,4 +182,4 @@ describe("pruneLastMessage", () => {
{ role: "assistant", content: "Hi" },
]);
});
});
});

View file

@ -1,5 +1,12 @@
import type { AssistantUnrolled } from "@continuedev/config-yaml";
import { describe, it, expect, vi, beforeEach, type MockedFunction } from "vitest";
import {
describe,
it,
expect,
vi,
beforeEach,
type MockedFunction,
} from "vitest";
import type { AuthConfig, AuthenticatedConfig } from "./auth/workos.js";
import type { ConfigServiceState } from "./services/types.js";
@ -9,58 +16,60 @@ import { handleSlashCommands } from "./slashCommands.js";
vi.mock("./services/index.js", () => ({
services: {
config: {
getState: vi.fn()
}
getState: vi.fn(),
},
},
reloadService: vi.fn(),
SERVICE_NAMES: {
AUTH: 'AUTH'
}
AUTH: "AUTH",
},
}));
// Mock auth functions
vi.mock("./auth/workos.js", () => ({
isAuthenticated: vi.fn(),
isAuthenticatedConfig: vi.fn(),
loadAuthConfig: vi.fn()
loadAuthConfig: vi.fn(),
}));
// Mock telemetry
vi.mock("./telemetry/posthogService.js", () => ({
posthogService: {
capture: vi.fn()
}
capture: vi.fn(),
},
}));
// Mock commands
vi.mock("./commands/commands.js", () => ({
getAllSlashCommands: vi.fn(() => [])
getAllSlashCommands: vi.fn(() => []),
}));
// Mock os and path
vi.mock("os", () => ({
default: {
homedir: vi.fn(() => "/home/test")
}
homedir: vi.fn(() => "/home/test"),
},
}));
vi.mock("path", () => ({
default: {
join: vi.fn((...parts) => parts.join("/"))
join: vi.fn((...parts) => parts.join("/")),
},
join: vi.fn((...parts) => parts.join("/"))
join: vi.fn((...parts) => parts.join("/")),
}));
// Mock session functions
vi.mock("./session.js", () => ({
getSessionFilePath: vi.fn(() => "/home/test/.continue/cli-sessions/continue-cli-pid-12345.json"),
hasSession: vi.fn(() => false)
getSessionFilePath: vi.fn(
() => "/home/test/.continue/cli-sessions/continue-cli-pid-12345.json",
),
hasSession: vi.fn(() => false),
}));
describe("slashCommands", () => {
const mockAssistant: AssistantUnrolled = {
name: "test-assistant",
version: "1.0.0"
version: "1.0.0",
};
beforeEach(() => {
@ -71,11 +80,17 @@ describe("slashCommands", () => {
it("should handle /info command when not authenticated", async () => {
const { isAuthenticated } = await import("./auth/workos.js");
const { services } = await import("./services/index.js");
(isAuthenticated as MockedFunction<typeof isAuthenticated>).mockReturnValue(false);
(services.config.getState as MockedFunction<typeof services.config.getState>).mockReturnValue({
(
isAuthenticated as MockedFunction<typeof isAuthenticated>
).mockReturnValue(false);
(
services.config.getState as MockedFunction<
typeof services.config.getState
>
).mockReturnValue({
config: null,
configPath: "/test/config.yaml"
configPath: "/test/config.yaml",
} as ConfigServiceState);
const result = await handleSlashCommands("/info", mockAssistant);
@ -91,46 +106,66 @@ describe("slashCommands", () => {
});
it("should handle /info command when authenticated via environment", async () => {
const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = await import("./auth/workos.js");
const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } =
await import("./auth/workos.js");
const { services } = await import("./services/index.js");
(isAuthenticated as MockedFunction<typeof isAuthenticated>).mockReturnValue(true);
(loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue({} as AuthConfig);
(
isAuthenticated as MockedFunction<typeof isAuthenticated>
).mockReturnValue(true);
(loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(
{} as AuthConfig,
);
(isAuthenticatedConfig as any).mockReturnValue(false);
(services.config.getState as MockedFunction<typeof services.config.getState>).mockReturnValue({
(
services.config.getState as MockedFunction<
typeof services.config.getState
>
).mockReturnValue({
config: null,
configPath: undefined
configPath: undefined,
} as ConfigServiceState);
const result = await handleSlashCommands("/info", mockAssistant);
expect(result).toBeDefined();
expect(result?.output).toContain("Authentication:");
expect(result?.output).toContain("Authenticated via environment variable");
expect(result?.output).toContain(
"Authenticated via environment variable",
);
expect(result?.output).toContain("Configuration:");
expect(result?.output).toContain("Config not found");
expect(result?.exit).toBe(false);
});
it("should handle /info command when authenticated with user config", async () => {
const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = await import("./auth/workos.js");
const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } =
await import("./auth/workos.js");
const { services } = await import("./services/index.js");
const mockAuthConfig: AuthenticatedConfig = {
userId: "test-user-id",
userEmail: "test@example.com",
accessToken: "test-token",
refreshToken: "test-refresh-token",
expiresAt: Date.now() + 3600000,
organizationId: "test-org-id"
organizationId: "test-org-id",
};
(isAuthenticated as MockedFunction<typeof isAuthenticated>).mockReturnValue(true);
(loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(mockAuthConfig);
(
isAuthenticated as MockedFunction<typeof isAuthenticated>
).mockReturnValue(true);
(loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(
mockAuthConfig,
);
(isAuthenticatedConfig as any).mockReturnValue(true);
(services.config.getState as MockedFunction<typeof services.config.getState>).mockReturnValue({
(
services.config.getState as MockedFunction<
typeof services.config.getState
>
).mockReturnValue({
config: null,
configPath: "/custom/config.yaml"
configPath: "/custom/config.yaml",
} as ConfigServiceState);
const result = await handleSlashCommands("/info", mockAssistant);
@ -147,9 +182,15 @@ describe("slashCommands", () => {
it("should handle config service errors gracefully", async () => {
const { isAuthenticated } = await import("./auth/workos.js");
const { services } = await import("./services/index.js");
(isAuthenticated as MockedFunction<typeof isAuthenticated>).mockReturnValue(false);
(services.config.getState as MockedFunction<typeof services.config.getState>).mockImplementation(() => {
(
isAuthenticated as MockedFunction<typeof isAuthenticated>
).mockReturnValue(false);
(
services.config.getState as MockedFunction<
typeof services.config.getState
>
).mockImplementation(() => {
throw new Error("Service not ready");
});
@ -163,14 +204,22 @@ describe("slashCommands", () => {
const { isAuthenticated } = await import("./auth/workos.js");
const { services } = await import("./services/index.js");
const { getSessionFilePath } = await import("./session.js");
// Mock the session path for this specific test
(getSessionFilePath as any).mockReturnValue("/test-home/.continue/cli-sessions/continue-cli-test-123.json");
(isAuthenticated as MockedFunction<typeof isAuthenticated>).mockReturnValue(false);
(services.config.getState as MockedFunction<typeof services.config.getState>).mockReturnValue({
(getSessionFilePath as any).mockReturnValue(
"/test-home/.continue/cli-sessions/continue-cli-test-123.json",
);
(
isAuthenticated as MockedFunction<typeof isAuthenticated>
).mockReturnValue(false);
(
services.config.getState as MockedFunction<
typeof services.config.getState
>
).mockReturnValue({
config: null,
configPath: undefined
configPath: undefined,
} as ConfigServiceState);
const result = await handleSlashCommands("/info", mockAssistant);
@ -179,4 +228,4 @@ describe("slashCommands", () => {
expect(result?.output).toContain(".json");
});
});
});
});

View file

@ -72,17 +72,25 @@ describe("handleAutoCompaction", () => {
});
it("should perform auto-compaction when context limit is approaching", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
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,
{
role: "system",
content: "You are a helpful assistant.",
} as ChatCompletionMessageParam,
{
role: "assistant",
content: "[COMPACTED HISTORY]\nConversation summary...",
} as ChatCompletionMessageParam,
],
compactionIndex: 1,
compactionContent: "Conversation summary...",
@ -112,10 +120,16 @@ describe("handleAutoCompaction", () => {
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(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,
@ -124,13 +138,17 @@ describe("handleAutoCompaction", () => {
});
it("should handle compaction errors gracefully", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
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"));
vi.mocked(compactChatHistory).mockRejectedValue(
new Error("Compaction failed"),
);
const mockCallbacks = {
onSystemMessage: vi.fn(),
@ -161,14 +179,18 @@ describe("handleAutoCompaction", () => {
});
it("should not call system message callback in headless mode", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js");
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],
compactedHistory: [
{ role: "system", content: "System" } as ChatCompletionMessageParam,
],
compactionIndex: 0,
compactionContent: "Summary",
};
@ -179,15 +201,10 @@ describe("handleAutoCompaction", () => {
onSystemMessage: vi.fn(),
};
await handleAutoCompaction(
mockChatHistory,
mockModel,
mockLlmApi,
{
isHeadless: true,
callbacks: mockCallbacks,
},
);
await handleAutoCompaction(mockChatHistory, mockModel, mockLlmApi, {
isHeadless: true,
callbacks: mockCallbacks,
});
expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled();
});
@ -205,4 +222,4 @@ describe("handleAutoCompaction", () => {
compactionIndex: null,
});
});
});
});

View file

@ -8,21 +8,20 @@ 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";
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[]>>;
setChatHistory?: React.Dispatch<
React.SetStateAction<ChatCompletionMessageParam[]>
>;
setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>;
// For headless mode - no callbacks needed, just return values
}
@ -41,7 +40,7 @@ function notifyCompactionStart(
callbacks?: AutoCompactionCallbacks,
) {
if (isHeadless) return;
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(message);
} else if (callbacks?.setMessages) {
@ -65,12 +64,16 @@ function handleCompactionSuccess(
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) {
} else if (
callbacks?.setMessages &&
callbacks?.setChatHistory &&
callbacks?.setCompactionIndex
) {
callbacks.setChatHistory(result.compactedHistory);
callbacks.setCompactionIndex(result.compactionIndex);
callbacks.setMessages((prev) => [
@ -96,9 +99,9 @@ function handleCompactionError(
logger.error(errorMessage);
if (isHeadless) return;
const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`;
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(warningMessage);
} else if (callbacks?.setMessages) {
@ -136,7 +139,9 @@ export async function handleAutoCompaction(
return { chatHistory, compactionIndex: null };
}
logger.info(`Auto-compaction triggered${isHeadless ? ' in headless mode' : ''}`);
logger.info(
`Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`,
);
// Notify about compaction start
notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks);
@ -173,4 +178,3 @@ export async function handleAutoCompaction(
return { chatHistory, compactionIndex: null };
}
}

View file

@ -39,13 +39,13 @@ export const readFileTool: Tool = {
const content = fs.readFileSync(args.filepath, "utf-8");
// Mark this file as read for the edit tool
markFileAsRead(args.filepath);
const lines = content.split('\n');
const lines = content.split("\n");
if (lines.length > 5000) {
const truncatedContent = lines.slice(0, 5000).join('\n');
const truncatedContent = lines.slice(0, 5000).join("\n");
return `Content of ${args.filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`;
}
return `Content of ${args.filepath}:\n${content}`;
} catch (error) {
return `Error reading file: ${