feat: save cli sessions in same format / location as extensions
This commit is contained in:
parent
100ff72bbe
commit
8a7d936b6c
21 changed files with 607 additions and 596 deletions
|
|
@ -3,6 +3,7 @@ import chalk from "chalk";
|
|||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import * as readlineSync from "readline-sync";
|
||||
|
||||
import type { ChatHistoryItem, Session } from "../../../../core/index.js";
|
||||
import { getDisplayableAsciiArt } from "../asciiArt.js";
|
||||
import {
|
||||
compactChatHistory,
|
||||
|
|
@ -13,11 +14,12 @@ import { processCommandFlags } from "../flags/flagProcessor.js";
|
|||
import { safeStdout } from "../init.js";
|
||||
import { configureLogger } from "../logger.js";
|
||||
import * as logging from "../logging.js";
|
||||
import { convertFromUnifiedHistory, convertToUnifiedHistory } from "../messageConversion.js";
|
||||
import { sentryService } from "../sentry.js";
|
||||
import { initializeServices } from "../services/index.js";
|
||||
import { serviceContainer } from "../services/ServiceContainer.js";
|
||||
import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
|
||||
import { loadSession, saveSession } from "../session.js";
|
||||
import { loadSession, saveSession, createSession } from "../session.js";
|
||||
import { streamChatResponse } from "../streamChatResponse.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import { posthogService } from "../telemetry/posthogService.js";
|
||||
|
|
@ -83,30 +85,32 @@ export interface ChatOptions extends ExtendedCommandOptions {
|
|||
|
||||
export async function initializeChatHistory(
|
||||
options: ChatOptions,
|
||||
): Promise<ChatCompletionMessageParam[]> {
|
||||
let chatHistory: ChatCompletionMessageParam[] = [];
|
||||
): Promise<ChatHistoryItem[]> {
|
||||
let session: Session | null = null;
|
||||
|
||||
// Load previous session if --resume flag is used
|
||||
if (options.resume) {
|
||||
const savedHistory = loadSession();
|
||||
if (savedHistory) {
|
||||
chatHistory = savedHistory;
|
||||
session = loadSession();
|
||||
if (session) {
|
||||
logger.info(chalk.yellow("Resuming previous session..."));
|
||||
return session.history;
|
||||
} else {
|
||||
logger.info(chalk.yellow("No previous session found, starting fresh..."));
|
||||
}
|
||||
}
|
||||
|
||||
// If no session loaded or not resuming, initialize with system message
|
||||
if (chatHistory.length === 0) {
|
||||
const systemMessage = await constructSystemMessage(
|
||||
options.rule,
|
||||
options.format,
|
||||
options.headless,
|
||||
);
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
}
|
||||
const chatHistory: ChatHistoryItem[] = [];
|
||||
const systemMessage = await constructSystemMessage(
|
||||
options.rule,
|
||||
options.format,
|
||||
options.headless,
|
||||
);
|
||||
if (systemMessage) {
|
||||
chatHistory.push({
|
||||
message: { role: "system", content: systemMessage },
|
||||
contextItems: [],
|
||||
});
|
||||
}
|
||||
|
||||
return chatHistory;
|
||||
|
|
@ -114,7 +118,7 @@ export async function initializeChatHistory(
|
|||
|
||||
// Helper function to handle manual compaction
|
||||
async function handleManualCompaction(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
model: ModelConfig,
|
||||
llmApi: any,
|
||||
isHeadless: boolean,
|
||||
|
|
@ -131,7 +135,8 @@ async function handleManualCompaction(
|
|||
chatHistory.push(...result.compactedHistory);
|
||||
|
||||
// Save the compacted session
|
||||
saveSession(chatHistory);
|
||||
const session = createSession(chatHistory);
|
||||
saveSession(session);
|
||||
|
||||
if (isHeadless) {
|
||||
safeStdout(
|
||||
|
|
@ -259,7 +264,8 @@ async function processMessage(
|
|||
let compactionIndex = initialCompactionIndex;
|
||||
// Check for slash commands in headless mode
|
||||
if (userInput.trim() === "/compact") {
|
||||
return handleManualCompaction(chatHistory, model, llmApi, isHeadless);
|
||||
const unifiedHistory = convertToUnifiedHistory(chatHistory);
|
||||
return handleManualCompaction(unifiedHistory, model, llmApi, isHeadless);
|
||||
}
|
||||
|
||||
// Track user prompt
|
||||
|
|
@ -294,7 +300,8 @@ async function processMessage(
|
|||
let finalResponse;
|
||||
if (compactionIndex !== null && compactionIndex !== undefined) {
|
||||
// When using compaction, we need to send a subset but capture the full history
|
||||
const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex);
|
||||
const unifiedHistory = convertToUnifiedHistory(chatHistory);
|
||||
const historyForLLM = getHistoryForLLM(unifiedHistory, compactionIndex);
|
||||
const originalLength = historyForLLM.length;
|
||||
|
||||
finalResponse = await streamChatResponse(
|
||||
|
|
@ -306,15 +313,22 @@ async function processMessage(
|
|||
|
||||
// Append any new messages (assistant/tool) that were added by streamChatResponse
|
||||
const newMessages = historyForLLM.slice(originalLength);
|
||||
chatHistory.push(...newMessages);
|
||||
const legacyNewMessages = convertFromUnifiedHistory(newMessages);
|
||||
chatHistory.push(...legacyNewMessages);
|
||||
} else {
|
||||
// No compaction - just pass the full history directly
|
||||
const unifiedHistory = convertToUnifiedHistory(chatHistory);
|
||||
const originalLength = unifiedHistory.length;
|
||||
finalResponse = await streamChatResponse(
|
||||
chatHistory,
|
||||
unifiedHistory,
|
||||
model,
|
||||
llmApi,
|
||||
abortController,
|
||||
);
|
||||
// Sync back any new messages added by streamChatResponse
|
||||
const newMessages = unifiedHistory.slice(originalLength);
|
||||
const legacyNewMessages = convertFromUnifiedHistory(newMessages);
|
||||
chatHistory.push(...legacyNewMessages);
|
||||
}
|
||||
|
||||
// In headless mode, only print the final response using safe stdout
|
||||
|
|
@ -336,7 +350,9 @@ async function processMessage(
|
|||
}
|
||||
|
||||
// Save session after each successful response
|
||||
saveSession(chatHistory);
|
||||
const unifiedHistory = convertToUnifiedHistory(chatHistory);
|
||||
const session = createSession(unifiedHistory);
|
||||
saveSession(session);
|
||||
} catch (e: any) {
|
||||
const error = e instanceof Error ? e : new Error(String(e));
|
||||
|
||||
|
|
@ -383,12 +399,13 @@ async function runHeadlessMode(
|
|||
}
|
||||
|
||||
// Initialize chat history
|
||||
const chatHistory = await initializeChatHistory(options);
|
||||
const unifiedChatHistory = await initializeChatHistory(options);
|
||||
const chatHistory = convertFromUnifiedHistory(unifiedChatHistory);
|
||||
|
||||
// Track compaction index if resuming with compacted history
|
||||
let compactionIndex: number | null = null;
|
||||
if (options.resume) {
|
||||
compactionIndex = findCompactionIndex(chatHistory);
|
||||
compactionIndex = findCompactionIndex(unifiedChatHistory);
|
||||
}
|
||||
|
||||
// Handle additional prompts from --prompt flags
|
||||
|
|
|
|||
|
|
@ -44,17 +44,17 @@ describe("listSessionsCommand", () => {
|
|||
it("should output JSON format when format is json", async () => {
|
||||
const mockSessions = [
|
||||
{
|
||||
id: "session-1",
|
||||
path: "/path/to/session1.json",
|
||||
timestamp: new Date("2023-01-01T10:00:00Z"),
|
||||
messageCount: 5,
|
||||
sessionId: "session-1",
|
||||
title: "Session 1",
|
||||
dateCreated: "2023-01-01T10:00:00.000Z",
|
||||
workspaceDirectory: "/workspace",
|
||||
firstUserMessage: "Hello world",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
path: "/path/to/session2.json",
|
||||
timestamp: new Date("2023-01-01T09:00:00Z"),
|
||||
messageCount: 3,
|
||||
sessionId: "session-2",
|
||||
title: "Session 2",
|
||||
dateCreated: "2023-01-01T09:00:00.000Z",
|
||||
workspaceDirectory: "/workspace",
|
||||
firstUserMessage: "Test message",
|
||||
},
|
||||
];
|
||||
|
|
@ -72,13 +72,15 @@ describe("listSessionsCommand", () => {
|
|||
{
|
||||
id: "session-1",
|
||||
timestamp: "2023-01-01T10:00:00.000Z",
|
||||
messageCount: 5,
|
||||
workspaceDirectory: "/workspace",
|
||||
title: "Session 1",
|
||||
firstUserMessage: "Hello world",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
timestamp: "2023-01-01T09:00:00.000Z",
|
||||
messageCount: 3,
|
||||
workspaceDirectory: "/workspace",
|
||||
title: "Session 2",
|
||||
firstUserMessage: "Test message",
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -39,9 +39,10 @@ export async function listSessionsCommand(
|
|||
JSON.stringify(
|
||||
{
|
||||
sessions: sessions.map((session) => ({
|
||||
id: session.id,
|
||||
timestamp: session.timestamp.toISOString(),
|
||||
messageCount: session.messageCount,
|
||||
id: session.sessionId,
|
||||
timestamp: session.dateCreated,
|
||||
workspaceDirectory: session.workspaceDirectory,
|
||||
title: session.title,
|
||||
firstUserMessage: session.firstUserMessage,
|
||||
})),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
|
||||
import type { ChatHistoryItem, ToolCallState } from "../../../../core/index.js";
|
||||
import type { ChatHistoryItem, Session, ToolCallState } from "../../../../core/index.js";
|
||||
import { streamChatResponse } from "../streamChatResponse.js";
|
||||
import { StreamCallbacks } from "../streamChatResponse.types.js";
|
||||
|
||||
|
|
@ -33,7 +31,7 @@ export async function streamChatResponseWithInterruption(
|
|||
message: { role: "assistant", content: "" },
|
||||
contextItems: [],
|
||||
};
|
||||
state.unifiedHistory.push(currentStreamingItem);
|
||||
state.session.history.push(currentStreamingItem);
|
||||
}
|
||||
currentStreamingItem.message.content =
|
||||
(currentStreamingItem.message.content as string) + content;
|
||||
|
|
@ -44,7 +42,7 @@ export async function streamChatResponseWithInterruption(
|
|||
currentStreamingItem = null;
|
||||
} else {
|
||||
// Add complete assistant message
|
||||
state.unifiedHistory.push({
|
||||
state.session.history.push({
|
||||
message: { role: "assistant", content: content },
|
||||
contextItems: [],
|
||||
});
|
||||
|
|
@ -72,7 +70,7 @@ export async function streamChatResponseWithInterruption(
|
|||
parsedArgs: toolArgs,
|
||||
};
|
||||
|
||||
state.unifiedHistory.push({
|
||||
state.session.history.push({
|
||||
message: { role: "assistant", content: "" },
|
||||
contextItems: [],
|
||||
toolCallStates: [toolCallState],
|
||||
|
|
@ -80,8 +78,8 @@ export async function streamChatResponseWithInterruption(
|
|||
},
|
||||
onToolResult: (result: string, toolName: string) => {
|
||||
// Find and update the corresponding tool call state
|
||||
for (let i = state.unifiedHistory.length - 1; i >= 0; i--) {
|
||||
const item = state.unifiedHistory[i];
|
||||
for (let i = state.session.history.length - 1; i >= 0; i--) {
|
||||
const item = state.session.history[i];
|
||||
if (item.toolCallStates) {
|
||||
const toolState = item.toolCallStates.find(
|
||||
(ts: ToolCallState) => ts.toolCall.function.name === toolName && ts.status === "calling"
|
||||
|
|
@ -101,8 +99,8 @@ export async function streamChatResponseWithInterruption(
|
|||
onToolError: (error: string, toolName?: string) => {
|
||||
if (toolName) {
|
||||
// Find and update the corresponding tool call state
|
||||
for (let i = state.unifiedHistory.length - 1; i >= 0; i--) {
|
||||
const item = state.unifiedHistory[i];
|
||||
for (let i = state.session.history.length - 1; i >= 0; i--) {
|
||||
const item = state.session.history[i];
|
||||
if (item.toolCallStates) {
|
||||
const toolState = item.toolCallStates.find(
|
||||
(ts: ToolCallState) => ts.toolCall.function.name === toolName && ts.status === "calling"
|
||||
|
|
@ -120,7 +118,7 @@ export async function streamChatResponseWithInterruption(
|
|||
}
|
||||
}
|
||||
// Generic error if tool not found
|
||||
state.unifiedHistory.push({
|
||||
state.session.history.push({
|
||||
message: { role: "system", content: error },
|
||||
contextItems: [],
|
||||
});
|
||||
|
|
@ -139,7 +137,7 @@ export async function streamChatResponseWithInterruption(
|
|||
};
|
||||
|
||||
// Add a system message indicating permission is needed
|
||||
state.unifiedHistory.push({
|
||||
state.session.history.push({
|
||||
message: {
|
||||
role: "system",
|
||||
content: `⚠️ Tool ${toolName} requires permission`
|
||||
|
|
@ -153,7 +151,7 @@ export async function streamChatResponseWithInterruption(
|
|||
|
||||
try {
|
||||
const response = await streamChatResponse(
|
||||
state.chatHistory,
|
||||
state.session.history,
|
||||
state.model,
|
||||
llmApi,
|
||||
abortController,
|
||||
|
|
@ -177,8 +175,7 @@ export interface PendingPermission {
|
|||
}
|
||||
|
||||
export interface ServerState {
|
||||
chatHistory: ChatCompletionMessageParam[];
|
||||
unifiedHistory: ChatHistoryItem[];
|
||||
session: Session;
|
||||
config: any;
|
||||
model: any;
|
||||
isProcessing: boolean;
|
||||
|
|
|
|||
|
|
@ -3,12 +3,10 @@ import { promisify } from "util";
|
|||
|
||||
import chalk from "chalk";
|
||||
import express, { Request, Response } from "express";
|
||||
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
|
||||
import type { ChatHistoryItem } from "../../../../core/index.js";
|
||||
import { getAssistantSlug } from "../auth/workos.js";
|
||||
import { processCommandFlags } from "../flags/flagProcessor.js";
|
||||
import { convertToUnifiedHistory, convertFromUnifiedHistory } from "../messageConversion.js";
|
||||
import { convertFromUnifiedHistory } from "../messageConversion.js";
|
||||
import { toolPermissionManager } from "../permissions/permissionManager.js";
|
||||
import {
|
||||
getService,
|
||||
|
|
@ -20,7 +18,7 @@ import {
|
|||
ConfigServiceState,
|
||||
ModelServiceState,
|
||||
} from "../services/types.js";
|
||||
import { saveSession } from "../session.js";
|
||||
import { saveSession, createSession } from "../session.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { formatError } from "../util/formatError.js";
|
||||
|
|
@ -28,7 +26,7 @@ import { logger } from "../util/logger.js";
|
|||
import { readStdinSync } from "../util/stdin.js";
|
||||
|
||||
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
|
||||
import { streamChatResponseWithInterruption, type PendingPermission } from "./serve.helpers.js";
|
||||
import { streamChatResponseWithInterruption, type ServerState } from "./serve.helpers.js";
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
|
|
@ -37,19 +35,6 @@ interface ServeOptions extends ExtendedCommandOptions {
|
|||
port?: string;
|
||||
}
|
||||
|
||||
interface ServerState {
|
||||
chatHistory: ChatCompletionMessageParam[];
|
||||
unifiedHistory: ChatHistoryItem[]; // Unified format for display
|
||||
config: any;
|
||||
model: any;
|
||||
isProcessing: boolean;
|
||||
lastActivity: number;
|
||||
messageQueue: string[];
|
||||
currentAbortController: AbortController | null;
|
||||
shouldInterrupt: boolean;
|
||||
serverRunning: boolean;
|
||||
pendingPermission: PendingPermission | null;
|
||||
}
|
||||
|
||||
export async function serve(prompt?: string, options: ServeOptions = {}) {
|
||||
// Check if prompt should come from stdin instead of parameter
|
||||
|
|
@ -118,21 +103,26 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
console.log(chalk.dim(` Config file: ${options.config}`));
|
||||
}
|
||||
|
||||
// Initialize chat history
|
||||
const chatHistory: ChatCompletionMessageParam[] = [];
|
||||
// Initialize session with system message
|
||||
const systemMessage = await constructSystemMessage(
|
||||
options.rule,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
|
||||
const initialHistory = [];
|
||||
if (systemMessage) {
|
||||
chatHistory.push({ role: "system", content: systemMessage });
|
||||
initialHistory.push({
|
||||
message: { role: "system" as const, content: systemMessage },
|
||||
contextItems: [],
|
||||
});
|
||||
}
|
||||
|
||||
const session = createSession(initialHistory);
|
||||
|
||||
// Initialize server state
|
||||
const state: ServerState = {
|
||||
chatHistory,
|
||||
unifiedHistory: convertToUnifiedHistory(chatHistory), // Convert to unified format
|
||||
session,
|
||||
config,
|
||||
model,
|
||||
isProcessing: false,
|
||||
|
|
@ -155,7 +145,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
app.get("/state", (_req: Request, res: Response) => {
|
||||
state.lastActivity = Date.now();
|
||||
res.json({
|
||||
chatHistory: convertFromUnifiedHistory(state.unifiedHistory), // Convert back to legacy format for API
|
||||
chatHistory: convertFromUnifiedHistory(state.session.history), // Convert back to legacy format for API
|
||||
isProcessing: state.isProcessing,
|
||||
messageQueueLength: state.messageQueue.length,
|
||||
pendingPermission: state.pendingPermission,
|
||||
|
|
@ -344,8 +334,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
state.lastActivity = Date.now();
|
||||
|
||||
// Add user message to history
|
||||
state.chatHistory.push({ role: "user", content: userMessage });
|
||||
state.unifiedHistory.push({
|
||||
state.session.history.push({
|
||||
message: { role: "user", content: userMessage },
|
||||
contextItems: [],
|
||||
});
|
||||
|
|
@ -363,35 +352,26 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
|
|||
);
|
||||
|
||||
// Save session after successful response
|
||||
saveSession(state.chatHistory);
|
||||
saveSession(state.session);
|
||||
|
||||
state.lastActivity = Date.now();
|
||||
} catch (e: any) {
|
||||
if (e.name === "AbortError") {
|
||||
logger.debug("Response interrupted");
|
||||
// Remove the partial assistant message if it exists
|
||||
const lastMessage = state.chatHistory[state.chatHistory.length - 1];
|
||||
if (lastMessage.role === "assistant" && !lastMessage.content) {
|
||||
state.chatHistory.pop();
|
||||
}
|
||||
// Also remove partial unified messages
|
||||
const lastUnifiedMessage = state.unifiedHistory[state.unifiedHistory.length - 1];
|
||||
const lastMessage = state.session.history[state.session.history.length - 1];
|
||||
if (
|
||||
lastUnifiedMessage &&
|
||||
lastUnifiedMessage.message.role === "assistant" &&
|
||||
!lastUnifiedMessage.message.content
|
||||
lastMessage &&
|
||||
lastMessage.message.role === "assistant" &&
|
||||
!lastMessage.message.content
|
||||
) {
|
||||
state.unifiedHistory.pop();
|
||||
state.session.history.pop();
|
||||
}
|
||||
} else {
|
||||
logger.error(`Error: ${formatError(e)}`);
|
||||
// Add error message to chat history and display messages
|
||||
const errorMessage = `Error: ${formatError(e)}`;
|
||||
state.chatHistory.push({
|
||||
role: "assistant",
|
||||
content: errorMessage,
|
||||
});
|
||||
state.unifiedHistory.push({
|
||||
state.session.history.push({
|
||||
message: { role: "assistant", content: errorMessage },
|
||||
contextItems: [],
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import { compactChatHistory } from "./compaction.js";
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
|
||||
// Mock the dependencies
|
||||
|
|
@ -49,9 +49,9 @@ describe("compaction infinite loop prevention", () => {
|
|||
);
|
||||
|
||||
// History that can't be pruned further (only system message)
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
];
|
||||
]);
|
||||
|
||||
// This should not hang - it should break out of the loop
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
|
||||
|
|
@ -81,11 +81,11 @@ describe("compaction infinite loop prevention", () => {
|
|||
);
|
||||
|
||||
// History that ends with assistant - pruning won't change it
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
]);
|
||||
|
||||
// This should not hang
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
|
||||
|
|
@ -122,12 +122,12 @@ describe("compaction infinite loop prevention", () => {
|
|||
);
|
||||
|
||||
// History that can be successfully pruned
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
{ role: "user", content: "Another question" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { pruneLastMessage } from "./compaction.js";
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
|
||||
describe("pruneLastMessage", () => {
|
||||
it("should return empty array for empty input", () => {
|
||||
|
|
@ -10,54 +10,54 @@ describe("pruneLastMessage", () => {
|
|||
});
|
||||
|
||||
it("should remove single user message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return empty array for single system message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return empty array for single assistant message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "assistant", content: "Hello" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return empty array for single tool message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "tool", content: "Tool output", tool_call_id: "1" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should remove last message when second-to-last is user", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
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[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Run command" },
|
||||
{
|
||||
|
|
@ -66,7 +66,7 @@ describe("pruneLastMessage", () => {
|
|||
tool_calls: [{ id: "1" } as any],
|
||||
},
|
||||
{ role: "tool", content: "Command output", tool_call_id: "1" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([
|
||||
|
|
@ -76,11 +76,11 @@ describe("pruneLastMessage", () => {
|
|||
});
|
||||
|
||||
it("should prune last message when second-to-last is not user or assistant with tool calls", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
{ role: "user", content: "Another question" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([
|
||||
|
|
@ -90,18 +90,18 @@ describe("pruneLastMessage", () => {
|
|||
});
|
||||
|
||||
it("should handle multiple user messages by removing two at a time", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Question 1" },
|
||||
{ role: "user", content: "Question 2" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([{ role: "system", content: "System" }]);
|
||||
});
|
||||
|
||||
it("should handle tool call sequences by removing user after tool", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Do something" },
|
||||
{
|
||||
|
|
@ -111,7 +111,7 @@ describe("pruneLastMessage", () => {
|
|||
},
|
||||
{ role: "tool", content: "Tool result", tool_call_id: "1" },
|
||||
{ role: "user", content: "Follow up question" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([
|
||||
|
|
@ -127,17 +127,17 @@ describe("pruneLastMessage", () => {
|
|||
});
|
||||
|
||||
it("should remove both user messages when consecutive", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should handle complex conversation flow", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Request 1" },
|
||||
{ role: "assistant", content: "Response 1" },
|
||||
|
|
@ -151,7 +151,7 @@ describe("pruneLastMessage", () => {
|
|||
{ role: "assistant", content: "Final response" },
|
||||
{ role: "user", content: "Follow up 1" },
|
||||
{ role: "user", content: "Follow up 2" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([
|
||||
|
|
@ -170,11 +170,11 @@ describe("pruneLastMessage", () => {
|
|||
});
|
||||
|
||||
it("should handle history starting with non-system message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
{ role: "user", content: "Follow up" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = pruneLastMessage(history);
|
||||
expect(result).toEqual([
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import type { ChatHistoryItem } from "../../../core/index.js";
|
||||
|
||||
import {
|
||||
compactChatHistory,
|
||||
findCompactionIndex,
|
||||
getHistoryForLLM,
|
||||
COMPACTION_MARKER,
|
||||
} from "./compaction.js";
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
|
||||
// Mock the streamChatResponse function
|
||||
|
|
@ -27,7 +29,7 @@ describe("compaction", () => {
|
|||
|
||||
describe("findCompactionIndex", () => {
|
||||
it("should find compaction marker in chat history", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
|
|
@ -36,73 +38,73 @@ describe("compaction", () => {
|
|||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
]);
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(3);
|
||||
});
|
||||
|
||||
it("should return null if no compaction marker found", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
]);
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
||||
it("should return first compaction marker when multiple exist", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nFirst summary` },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSecond summary` },
|
||||
];
|
||||
]);
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(1);
|
||||
});
|
||||
|
||||
it("should return null for empty chat history", () => {
|
||||
const history: ChatCompletionMessageParam[] = [];
|
||||
const history = convertToUnifiedHistory([]);
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
||||
it("should not match marker in middle of content", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `Some text ${COMPACTION_MARKER} in the middle`,
|
||||
},
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
]);
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle non-string content", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: null as any },
|
||||
{ role: "assistant", content: undefined as any },
|
||||
{ role: "assistant", content: 123 as any },
|
||||
];
|
||||
]);
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
||||
it("should only match assistant role messages", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: `${COMPACTION_MARKER}\nSystem compaction?` },
|
||||
{ role: "user", content: `${COMPACTION_MARKER}\nUser compaction?` },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nReal compaction` },
|
||||
];
|
||||
]);
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(2);
|
||||
|
|
@ -111,18 +113,18 @@ describe("compaction", () => {
|
|||
|
||||
describe("getHistoryForLLM", () => {
|
||||
it("should return full history when no compaction index", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = getHistoryForLLM(history, null);
|
||||
expect(result).toEqual(history);
|
||||
});
|
||||
|
||||
it("should return compacted history with system message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
|
|
@ -131,7 +133,7 @@ describe("compaction", () => {
|
|||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = getHistoryForLLM(history, 3);
|
||||
expect(result).toEqual([
|
||||
|
|
@ -145,33 +147,33 @@ describe("compaction", () => {
|
|||
});
|
||||
|
||||
it("should return compacted history without system message when compaction is at index 0", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = getHistoryForLLM(history, 0);
|
||||
expect(result).toEqual(history);
|
||||
});
|
||||
|
||||
it("should return full history when compactionIndex is out of bounds", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = getHistoryForLLM(history, 10);
|
||||
expect(result).toEqual(history);
|
||||
});
|
||||
|
||||
it("should handle negative compactionIndex", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = getHistoryForLLM(history, -1);
|
||||
// Negative index with slice means "from the end", so -1 gives us only the last message
|
||||
|
|
@ -180,26 +182,26 @@ describe("compaction", () => {
|
|||
});
|
||||
|
||||
it("should handle empty history", () => {
|
||||
const history: ChatCompletionMessageParam[] = [];
|
||||
const history = convertToUnifiedHistory([]);
|
||||
const result = getHistoryForLLM(history, 0);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should handle history with only system message", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = getHistoryForLLM(history, 0);
|
||||
expect(result).toEqual(history);
|
||||
});
|
||||
|
||||
it("should handle history without system message but with compaction", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "First message" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "user", content: "New message" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = getHistoryForLLM(history, 1);
|
||||
expect(result).toEqual([
|
||||
|
|
@ -209,12 +211,12 @@ describe("compaction", () => {
|
|||
});
|
||||
|
||||
it("should include system message when first message is not system", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "First user message" },
|
||||
{ role: "system", content: "System message in wrong position" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "user", content: "New message" },
|
||||
];
|
||||
]);
|
||||
|
||||
// Since system message is not at index 0, it's not included
|
||||
const result = getHistoryForLLM(history, 2);
|
||||
|
|
@ -225,7 +227,7 @@ describe("compaction", () => {
|
|||
});
|
||||
|
||||
it("should preserve message order from compaction point", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Old 1" },
|
||||
{ role: "assistant", content: "Old 2" },
|
||||
|
|
@ -233,7 +235,7 @@ describe("compaction", () => {
|
|||
{ role: "user", content: "New 1" },
|
||||
{ role: "assistant", content: "New 2" },
|
||||
{ role: "user", content: "New 3" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = getHistoryForLLM(history, 3);
|
||||
expect(result).toEqual([
|
||||
|
|
@ -259,11 +261,11 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
|
@ -295,9 +297,9 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
]);
|
||||
|
||||
await compactChatHistory(history, mockModel, mockLlmApi, {
|
||||
onStreamContent,
|
||||
|
|
@ -316,9 +318,9 @@ describe("compaction", () => {
|
|||
|
||||
mockStreamResponse.mockRejectedValue(mockError);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
]);
|
||||
|
||||
await expect(
|
||||
compactChatHistory(history, mockModel, mockLlmApi, { onError }),
|
||||
|
|
@ -339,18 +341,18 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "You are a helpful assistant" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2);
|
||||
expect(result.compactedHistory[0]).toEqual({
|
||||
expect(result.compactedHistory[0].message).toEqual({
|
||||
role: "system",
|
||||
content: "You are a helpful assistant",
|
||||
});
|
||||
expect(result.compactedHistory[1].content).toContain(COMPACTION_MARKER);
|
||||
expect(result.compactedHistory[1].message.content).toContain(COMPACTION_MARKER);
|
||||
});
|
||||
|
||||
it("should handle empty content from stream", async () => {
|
||||
|
|
@ -364,19 +366,19 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactionContent).toBe("");
|
||||
expect(result.compactedHistory[0].content).toBe(`${COMPACTION_MARKER}\n`);
|
||||
expect(result.compactedHistory[0].message.content).toBe(`${COMPACTION_MARKER}\n`);
|
||||
});
|
||||
|
||||
it("should correctly construct prompt for compaction", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
let capturedHistory: ChatCompletionMessageParam[] = [];
|
||||
let capturedHistory: ChatHistoryItem[] = [];
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
|
|
@ -387,17 +389,17 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
];
|
||||
]);
|
||||
|
||||
await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
// Should have original history plus the compaction prompt
|
||||
expect(capturedHistory).toHaveLength(4);
|
||||
expect(capturedHistory[3]).toEqual({
|
||||
expect(capturedHistory[3].message).toEqual({
|
||||
role: "user",
|
||||
content: expect.stringContaining("provide a concise summary"),
|
||||
});
|
||||
|
|
@ -415,13 +417,13 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Do something" },
|
||||
{ role: "assistant", content: "I'll help", tool_calls: [{} as any] },
|
||||
{ role: "tool", content: "Tool result", tool_call_id: "123" },
|
||||
{ role: "assistant", content: "Done" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
|
@ -441,13 +443,19 @@ describe("compaction", () => {
|
|||
);
|
||||
|
||||
// Create a very long history
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
];
|
||||
]);
|
||||
|
||||
for (let i = 0; i < 100; i++) {
|
||||
history.push({ role: "user", content: `User message ${i}` });
|
||||
history.push({ role: "assistant", content: `Assistant response ${i}` });
|
||||
history.push({
|
||||
message: { role: "user", content: `User message ${i}` },
|
||||
contextItems: []
|
||||
});
|
||||
history.push({
|
||||
message: { role: "assistant", content: `Assistant response ${i}` },
|
||||
contextItems: []
|
||||
});
|
||||
}
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
|
@ -468,15 +476,15 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(1); // Only compaction
|
||||
expect(result.compactedHistory[0].role).toBe("assistant");
|
||||
expect(result.compactedHistory[0].message.role).toBe("assistant");
|
||||
expect(result.compactionIndex).toBe(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -484,23 +492,23 @@ describe("compaction", () => {
|
|||
describe("property-based tests", () => {
|
||||
it("getHistoryForLLM should always return a subset of the original history", () => {
|
||||
const testCases: Array<{
|
||||
history: ChatCompletionMessageParam[];
|
||||
history: ChatHistoryItem[];
|
||||
compactionIndex: number | null;
|
||||
}> = [
|
||||
{
|
||||
history: [
|
||||
history: convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
],
|
||||
]),
|
||||
compactionIndex: 1,
|
||||
},
|
||||
{
|
||||
history: [
|
||||
history: convertToUnifiedHistory([
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
{ role: "user", content: "User 2" },
|
||||
],
|
||||
]),
|
||||
compactionIndex: 2,
|
||||
},
|
||||
{
|
||||
|
|
@ -523,27 +531,30 @@ describe("compaction", () => {
|
|||
});
|
||||
|
||||
it("getHistoryForLLM should always include system message if it exists at index 0", () => {
|
||||
const systemMessage: ChatCompletionMessageParam = {
|
||||
role: "system",
|
||||
content: "System",
|
||||
const systemMessage: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "system",
|
||||
content: "System",
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
const testCases: Array<{
|
||||
history: ChatCompletionMessageParam[];
|
||||
history: ChatHistoryItem[];
|
||||
compactionIndex: number | null;
|
||||
}> = [
|
||||
{
|
||||
history: [
|
||||
systemMessage,
|
||||
history: convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
],
|
||||
]),
|
||||
compactionIndex: 2,
|
||||
},
|
||||
{
|
||||
history: [
|
||||
systemMessage,
|
||||
history: convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
],
|
||||
]),
|
||||
compactionIndex: 1,
|
||||
},
|
||||
];
|
||||
|
|
@ -552,11 +563,11 @@ describe("compaction", () => {
|
|||
const result = getHistoryForLLM(history, compactionIndex);
|
||||
|
||||
if (
|
||||
history[0]?.role === "system" &&
|
||||
history[0]?.message?.role === "system" &&
|
||||
compactionIndex !== null &&
|
||||
compactionIndex > 0
|
||||
) {
|
||||
expect(result[0]).toEqual(systemMessage);
|
||||
expect(result[0]).toEqual(history[0]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -572,19 +583,19 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const testHistories: ChatCompletionMessageParam[][] = [
|
||||
[
|
||||
const testHistories: ChatHistoryItem[][] = [
|
||||
convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
{ role: "user", content: "User 2" },
|
||||
{ role: "assistant", content: "Assistant 2" },
|
||||
],
|
||||
[
|
||||
]),
|
||||
convertToUnifiedHistory([
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
{ role: "user", content: "User 2" },
|
||||
],
|
||||
]),
|
||||
];
|
||||
|
||||
for (const history of testHistories) {
|
||||
|
|
@ -610,16 +621,16 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const histories: ChatCompletionMessageParam[][] = [
|
||||
[
|
||||
const histories: ChatHistoryItem[][] = [
|
||||
convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Hello" },
|
||||
],
|
||||
[
|
||||
]),
|
||||
convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
],
|
||||
[{ role: "system", content: "System" }],
|
||||
]),
|
||||
convertToUnifiedHistory([{ role: "system", content: "System" }]),
|
||||
];
|
||||
|
||||
for (const history of histories) {
|
||||
|
|
@ -628,10 +639,10 @@ describe("compaction", () => {
|
|||
// The message at compactionIndex should contain the marker
|
||||
const compactionMessage =
|
||||
result.compactedHistory[result.compactionIndex];
|
||||
expect(compactionMessage.role).toBe("assistant");
|
||||
expect(compactionMessage.message.role).toBe("assistant");
|
||||
expect(
|
||||
typeof compactionMessage.content === "string" &&
|
||||
compactionMessage.content.startsWith(COMPACTION_MARKER),
|
||||
typeof compactionMessage.message.content === "string" &&
|
||||
compactionMessage.message.content.startsWith(COMPACTION_MARKER),
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
|
|
@ -647,20 +658,16 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const systemMessage: ChatCompletionMessageParam = {
|
||||
role: "system",
|
||||
content: "You are helpful",
|
||||
};
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
systemMessage,
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "You are helpful" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
// System message should still be at index 0
|
||||
expect(result.compactedHistory[0]).toEqual(systemMessage);
|
||||
expect(result.compactedHistory[0]).toEqual(history[0]);
|
||||
});
|
||||
|
||||
it("findCompactionIndex should be consistent with compactChatHistory result", async () => {
|
||||
|
|
@ -674,10 +681,10 @@ describe("compaction", () => {
|
|||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
];
|
||||
]);
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
|
||||
import type { ChatHistoryItem } from "../../../core/index.js";
|
||||
|
||||
import { convertFromUnifiedHistory } from "./messageConversion.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
import { StreamCallbacks } from "./streamChatResponse.types.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
|
@ -13,7 +15,7 @@ import {
|
|||
export const COMPACTION_MARKER = "[COMPACTED HISTORY]";
|
||||
|
||||
export interface CompactionResult {
|
||||
compactedHistory: ChatCompletionMessageParam[];
|
||||
compactedHistory: ChatHistoryItem[];
|
||||
compactionIndex: number;
|
||||
compactionContent: string;
|
||||
}
|
||||
|
|
@ -33,21 +35,25 @@ export interface CompactionCallbacks {
|
|||
* @returns The compacted history with compaction index
|
||||
*/
|
||||
export async function compactChatHistory(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
model: ModelConfig,
|
||||
llmApi: BaseLlmApi,
|
||||
callbacks?: CompactionCallbacks,
|
||||
): Promise<CompactionResult> {
|
||||
// Create a prompt to summarize the conversation
|
||||
const compactionPrompt: ChatCompletionMessageParam = {
|
||||
role: "user",
|
||||
content:
|
||||
"Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.",
|
||||
const compactionPrompt: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "user" as const,
|
||||
content:
|
||||
"Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.",
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
|
||||
// Check if the history with compaction prompt is too long, prune if necessary
|
||||
let historyToUse = chatHistory;
|
||||
let historyForCompaction = [...historyToUse, compactionPrompt];
|
||||
let historyForCompactionLegacy = convertFromUnifiedHistory(historyForCompaction);
|
||||
|
||||
const contextLimit = getModelContextLimit(model);
|
||||
const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;
|
||||
|
|
@ -57,11 +63,11 @@ export async function compactChatHistory(
|
|||
|
||||
// Check if we need to prune to fit within context
|
||||
while (
|
||||
countChatHistoryTokens(historyForCompaction) > availableForInput &&
|
||||
countChatHistoryTokens(historyForCompactionLegacy) > availableForInput &&
|
||||
historyToUse.length > 0
|
||||
) {
|
||||
logger.debug("Compaction history too long, pruning last message", {
|
||||
tokenCount: countChatHistoryTokens(historyForCompaction),
|
||||
tokenCount: countChatHistoryTokens(historyForCompactionLegacy),
|
||||
availableForInput,
|
||||
historyLength: historyToUse.length,
|
||||
});
|
||||
|
|
@ -77,6 +83,7 @@ export async function compactChatHistory(
|
|||
|
||||
historyToUse = prunedHistory;
|
||||
historyForCompaction = [...historyToUse, compactionPrompt];
|
||||
historyForCompactionLegacy = convertFromUnifiedHistory(historyForCompaction);
|
||||
}
|
||||
|
||||
// Stream the compaction response
|
||||
|
|
@ -103,17 +110,25 @@ export async function compactChatHistory(
|
|||
);
|
||||
|
||||
// Create the compacted history with a special marker
|
||||
const systemMessage = chatHistory.find((msg) => msg.role === "system");
|
||||
const compactedMessage: ChatCompletionMessageParam = {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\n${compactionContent}`,
|
||||
const systemMessage = chatHistory.find((item) => item.message.role === "system");
|
||||
const compactedMessage: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\n${compactionContent}`,
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
|
||||
// Set new chat history with only system message and compaction
|
||||
const compactedHistory = systemMessage
|
||||
? [systemMessage, compactedMessage]
|
||||
: [compactedMessage];
|
||||
|
||||
// Mark the compaction in the unified format
|
||||
const compactionIndex = compactedHistory.length - 1;
|
||||
if (compactedHistory[compactionIndex]) {
|
||||
compactedHistory[compactionIndex].conversationSummary = compactionContent;
|
||||
}
|
||||
|
||||
logger.debug("Chat history compacted", {
|
||||
originalLength: chatHistory.length,
|
||||
|
|
@ -139,13 +154,10 @@ export async function compactChatHistory(
|
|||
* @returns The index of the compaction message, or null if not found
|
||||
*/
|
||||
export function findCompactionIndex(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
): number | null {
|
||||
const compactedIndex = chatHistory.findIndex(
|
||||
(msg) =>
|
||||
msg.role === "assistant" &&
|
||||
typeof msg.content === "string" &&
|
||||
msg.content.startsWith(COMPACTION_MARKER),
|
||||
(item) => item.conversationSummary !== undefined
|
||||
);
|
||||
return compactedIndex === -1 ? null : compactedIndex;
|
||||
}
|
||||
|
|
@ -163,8 +175,8 @@ export function findCompactionIndex(
|
|||
* @returns The pruned chat history ending with assistant or tool message
|
||||
*/
|
||||
export function pruneLastMessage(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
): ChatCompletionMessageParam[] {
|
||||
chatHistory: ChatHistoryItem[],
|
||||
): ChatHistoryItem[] {
|
||||
if (chatHistory.length === 0) {
|
||||
return chatHistory;
|
||||
}
|
||||
|
|
@ -175,14 +187,14 @@ export function pruneLastMessage(
|
|||
}
|
||||
|
||||
const secondToLastIndex = chatHistory.length - 2;
|
||||
const secondToLastMessage = chatHistory[secondToLastIndex];
|
||||
const secondToLastItem = chatHistory[secondToLastIndex];
|
||||
|
||||
if (
|
||||
secondToLastMessage.role === "assistant" &&
|
||||
secondToLastMessage.tool_calls?.length
|
||||
secondToLastItem.message.role === "assistant" &&
|
||||
(secondToLastItem.message as any).toolCalls?.length
|
||||
) {
|
||||
return chatHistory.slice(0, -2);
|
||||
} else if (secondToLastMessage.role === "user") {
|
||||
} else if (secondToLastItem.message.role === "user") {
|
||||
return chatHistory.slice(0, -2);
|
||||
}
|
||||
|
||||
|
|
@ -190,16 +202,16 @@ export function pruneLastMessage(
|
|||
}
|
||||
|
||||
export function getHistoryForLLM(
|
||||
fullHistory: ChatCompletionMessageParam[],
|
||||
fullHistory: ChatHistoryItem[],
|
||||
compactionIndex: number | null,
|
||||
): ChatCompletionMessageParam[] {
|
||||
): ChatHistoryItem[] {
|
||||
if (compactionIndex === null || compactionIndex >= fullHistory.length) {
|
||||
return fullHistory;
|
||||
}
|
||||
|
||||
// Include system message (if at index 0) and everything from compaction index forward
|
||||
const systemMessage =
|
||||
fullHistory[0]?.role === "system" ? fullHistory[0] : null;
|
||||
fullHistory[0]?.message?.role === "system" ? fullHistory[0] : null;
|
||||
const messagesFromCompaction = fullHistory.slice(compactionIndex);
|
||||
|
||||
return systemMessage && compactionIndex > 0
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { saveSession, hasSession, clearSession } from "./session.js";
|
||||
import { saveSession, hasSession, clearSession, createSession } from "./session.js";
|
||||
|
||||
describe("Session Management", () => {
|
||||
let originalEnv: NodeJS.ProcessEnv;
|
||||
|
|
@ -28,13 +28,19 @@ describe("Session Management", () => {
|
|||
it("should create unique sessions for different TMUX_PANE values", () => {
|
||||
// Test first session
|
||||
process.env.TMUX_PANE = "%1";
|
||||
saveSession([{ role: "user", content: "test1" }]);
|
||||
const session1 = createSession([
|
||||
{ message: { role: "user", content: "test1" }, contextItems: [] }
|
||||
]);
|
||||
saveSession(session1);
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
|
||||
// Test second session with different TMUX_PANE
|
||||
process.env.TMUX_PANE = "%2";
|
||||
saveSession([{ role: "user", content: "test2" }]);
|
||||
const session2 = createSession([
|
||||
{ message: { role: "user", content: "test2" }, contextItems: [] }
|
||||
]);
|
||||
saveSession(session2);
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
});
|
||||
|
|
@ -42,7 +48,10 @@ describe("Session Management", () => {
|
|||
it("should use TERM_SESSION_ID when TMUX_PANE is not available", () => {
|
||||
process.env.TERM_SESSION_ID = "w1t0s0:0.0";
|
||||
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
const session = createSession([
|
||||
{ message: { role: "user", content: "test" }, contextItems: [] }
|
||||
]);
|
||||
saveSession(session);
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
});
|
||||
|
|
@ -50,7 +59,10 @@ describe("Session Management", () => {
|
|||
it("should use SSH_TTY when other env vars are not available", () => {
|
||||
process.env.SSH_TTY = "/dev/pts/0";
|
||||
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
const session = createSession([
|
||||
{ message: { role: "user", content: "test" }, contextItems: [] }
|
||||
]);
|
||||
saveSession(session);
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
});
|
||||
|
|
@ -60,7 +72,10 @@ describe("Session Management", () => {
|
|||
|
||||
// Should not throw error despite special characters
|
||||
expect(() => {
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
const session = createSession([
|
||||
{ message: { role: "user", content: "test" }, contextItems: [] }
|
||||
]);
|
||||
saveSession(session);
|
||||
}).not.toThrow();
|
||||
|
||||
expect(hasSession()).toBe(true);
|
||||
|
|
@ -72,7 +87,10 @@ describe("Session Management", () => {
|
|||
it("should use test session ID when provided", () => {
|
||||
process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-123";
|
||||
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
const session = createSession([
|
||||
{ message: { role: "user", content: "test" }, contextItems: [] }
|
||||
]);
|
||||
saveSession(session);
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
});
|
||||
|
|
@ -84,7 +102,10 @@ describe("Session Management", () => {
|
|||
|
||||
// Should fall back to TTY path, process tree, or PID
|
||||
expect(() => {
|
||||
saveSession([{ role: "user", content: "fallback test" }]);
|
||||
const session = createSession([
|
||||
{ message: { role: "user", content: "fallback test" }, contextItems: [] }
|
||||
]);
|
||||
saveSession(session);
|
||||
}).not.toThrow();
|
||||
|
||||
expect(hasSession()).toBe(true);
|
||||
|
|
@ -95,12 +116,13 @@ describe("Session Management", () => {
|
|||
process.env.TMUX_PANE = "%test";
|
||||
|
||||
const testHistory = [
|
||||
{ role: "user" as const, content: "Hello" },
|
||||
{ role: "assistant" as const, content: "Hi there!" },
|
||||
{ message: { role: "user" as const, content: "Hello" }, contextItems: [] },
|
||||
{ message: { role: "assistant" as const, content: "Hi there!" }, contextItems: [] },
|
||||
];
|
||||
|
||||
// Save session
|
||||
saveSession(testHistory);
|
||||
const session = createSession(testHistory);
|
||||
saveSession(session);
|
||||
expect(hasSession()).toBe(true);
|
||||
|
||||
// Clear and verify it's gone
|
||||
|
|
@ -115,7 +137,10 @@ describe("Session Management", () => {
|
|||
process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-with-various-chars";
|
||||
|
||||
expect(() => {
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
const session = createSession([
|
||||
{ message: { role: "user", content: "test" }, contextItems: [] }
|
||||
]);
|
||||
saveSession(session);
|
||||
}).not.toThrow();
|
||||
|
||||
clearSession();
|
||||
|
|
|
|||
|
|
@ -1,154 +1,19 @@
|
|||
import { execSync } from "child_process";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import type { ChatHistoryItem, Session, SessionMetadata } from "../../../core/index.js";
|
||||
|
||||
// Re-export SessionMetadata for external consumers
|
||||
export type { SessionMetadata };
|
||||
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
// List of known terminal process names
|
||||
const TERMINAL_PROCESSES = [
|
||||
"Terminal",
|
||||
"iTerm",
|
||||
"tmux",
|
||||
"screen",
|
||||
"bash",
|
||||
"zsh",
|
||||
"fish",
|
||||
"kitty",
|
||||
"alacritty",
|
||||
"wt", // Windows Terminal
|
||||
"cmd", // Windows Command Prompt
|
||||
"powershell",
|
||||
];
|
||||
|
||||
// Check if a process name looks like a terminal
|
||||
function isTerminalProcess(comm: string): boolean {
|
||||
if (!comm) return false;
|
||||
return TERMINAL_PROCESSES.some((term) => comm.includes(term));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the terminal process ID by walking up the process tree
|
||||
*/
|
||||
function getTerminalProcessId(): string | null {
|
||||
try {
|
||||
// Skip on Windows - ps command doesn't exist
|
||||
if (os.platform() === "win32") {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get parent process info by walking up the tree
|
||||
let currentPid = process.ppid;
|
||||
|
||||
for (let i = 0; i < 10 && currentPid; i++) {
|
||||
try {
|
||||
const psOutput = execSync(`ps -o pid,ppid,comm -p ${currentPid}`, {
|
||||
encoding: "utf8",
|
||||
timeout: 1000,
|
||||
stdio: ["ignore", "pipe", "ignore"], // Suppress stderr
|
||||
}).trim();
|
||||
|
||||
const lines = psOutput.split("\n");
|
||||
if (lines.length < 2) break;
|
||||
|
||||
const processInfo = lines[1].trim().split(/\s+/);
|
||||
const [pid, ppid, comm] = processInfo;
|
||||
|
||||
// Check if this looks like a terminal process
|
||||
if (isTerminalProcess(comm)) {
|
||||
return pid;
|
||||
}
|
||||
|
||||
const nextPid = parseInt(ppid);
|
||||
if (isNaN(nextPid) || nextPid <= 1) break;
|
||||
currentPid = nextPid;
|
||||
} catch {
|
||||
// Continue to next iteration if this process lookup fails
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silently fail - this is a fallback mechanism
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the TTY device path for unique terminal identification
|
||||
*/
|
||||
function getTtyPath(): string | null {
|
||||
try {
|
||||
// Skip on Windows - tty command doesn't exist
|
||||
if (os.platform() === "win32") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (process.stdin.isTTY) {
|
||||
// Get the TTY device path
|
||||
const ttyPath = execSync("tty", {
|
||||
encoding: "utf8",
|
||||
timeout: 1000,
|
||||
stdio: ["ignore", "pipe", "ignore"], // Suppress stderr
|
||||
}).trim();
|
||||
|
||||
if (
|
||||
ttyPath &&
|
||||
ttyPath !== "not a tty" &&
|
||||
!ttyPath.includes("not found")
|
||||
) {
|
||||
// Convert /dev/ttys002 to ttys002 for cleaner ID
|
||||
return ttyPath.replace("/dev/", "");
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silently fail - this is a fallback mechanism
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a unique session identifier for the current terminal session
|
||||
* Uses environment variables to ensure each terminal window has its own session
|
||||
*/
|
||||
function getSessionId(): string {
|
||||
// For tests, use a specific session ID if provided
|
||||
if (process.env.CONTINUE_CLI_TEST_SESSION_ID) {
|
||||
return `continue-cli-${process.env.CONTINUE_CLI_TEST_SESSION_ID}`;
|
||||
}
|
||||
|
||||
// Try environment variables first (most reliable)
|
||||
const envSession =
|
||||
process.env.TMUX_PANE ||
|
||||
process.env.TERM_SESSION_ID ||
|
||||
process.env.SSH_TTY ||
|
||||
process.env.TMUX ||
|
||||
process.env.STY;
|
||||
|
||||
if (envSession) {
|
||||
const cleanSessionId = envSession.replace(/[^a-zA-Z0-9-_]/g, "-");
|
||||
return `continue-cli-${cleanSessionId}`;
|
||||
}
|
||||
|
||||
// Fallback 1: Try to get TTY device path (unique per terminal window)
|
||||
const ttyPath = getTtyPath();
|
||||
if (ttyPath) {
|
||||
const cleanTtyId = ttyPath.replace(/[^a-zA-Z0-9-_]/g, "-");
|
||||
return `continue-cli-tty-${cleanTtyId}`;
|
||||
}
|
||||
|
||||
// Fallback 2: Try to get terminal process ID (unique per terminal process)
|
||||
const terminalPid = getTerminalProcessId();
|
||||
if (terminalPid) {
|
||||
return `continue-cli-term-${terminalPid}`;
|
||||
}
|
||||
|
||||
// Final fallback: Use process PID (least reliable but always available)
|
||||
return `continue-cli-pid-${process.pid}`;
|
||||
}
|
||||
// Note: We now use UUID-based session IDs instead of terminal-based IDs.
|
||||
// Each new chat session gets a unique UUID.
|
||||
// The --resume flag loads the most recent session.
|
||||
|
||||
/**
|
||||
* Get the session storage directory
|
||||
|
|
@ -156,7 +21,7 @@ function getSessionId(): string {
|
|||
function getSessionDir(): string {
|
||||
// For tests, use the test directory if we're in test mode
|
||||
if (process.env.CONTINUE_CLI_TEST && process.env.HOME) {
|
||||
const sessionDir = path.join(process.env.HOME, ".continue", "cli-sessions");
|
||||
const sessionDir = path.join(process.env.HOME, ".continue", "sessions");
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if (!fs.existsSync(sessionDir)) {
|
||||
|
|
@ -167,7 +32,7 @@ function getSessionDir(): string {
|
|||
}
|
||||
|
||||
const homeDir = os.homedir();
|
||||
const sessionDir = path.join(homeDir, ".continue", "cli-sessions");
|
||||
const sessionDir = path.join(homeDir, ".continue", "sessions");
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if (!fs.existsSync(sessionDir)) {
|
||||
|
|
@ -177,108 +42,200 @@ function getSessionDir(): string {
|
|||
return sessionDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the sessions list file path
|
||||
*/
|
||||
function getSessionsListPath(): string {
|
||||
const sessionDir = getSessionDir();
|
||||
const listPath = path.join(sessionDir, "sessions.json");
|
||||
|
||||
// Initialize with empty array if doesn't exist
|
||||
if (!fs.existsSync(listPath)) {
|
||||
fs.writeFileSync(listPath, JSON.stringify([]));
|
||||
}
|
||||
|
||||
return listPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the session file path for the current session
|
||||
*/
|
||||
export function getSessionFilePath(): string {
|
||||
const sessionId = getSessionId();
|
||||
const sessionId = getCurrentSessionId();
|
||||
const sessionDir = getSessionDir();
|
||||
return path.join(sessionDir, `${sessionId}.json`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save chat history to session file
|
||||
*/
|
||||
export function saveSession(chatHistory: ChatCompletionMessageParam[]): void {
|
||||
try {
|
||||
const sessionFilePath = getSessionFilePath();
|
||||
const sessionData = {
|
||||
timestamp: new Date().toISOString(),
|
||||
chatHistory,
|
||||
};
|
||||
// Store the current session ID for the terminal
|
||||
let currentSessionId: string | null = null;
|
||||
|
||||
fs.writeFileSync(sessionFilePath, JSON.stringify(sessionData, null, 2));
|
||||
/**
|
||||
* Get or create a session ID for the current terminal
|
||||
*/
|
||||
function getCurrentSessionId(): string {
|
||||
if (!currentSessionId) {
|
||||
currentSessionId = uuidv4();
|
||||
}
|
||||
return currentSessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session to file
|
||||
*/
|
||||
export function saveSession(session: Session): void {
|
||||
try {
|
||||
// Store the session ID for future reference
|
||||
currentSessionId = session.sessionId;
|
||||
|
||||
const sessionFilePath = path.join(getSessionDir(), `${session.sessionId}.json`);
|
||||
|
||||
// Write the session file
|
||||
fs.writeFileSync(sessionFilePath, JSON.stringify(session, null, 2));
|
||||
|
||||
// Update the sessions list
|
||||
updateSessionsList(session);
|
||||
} catch (error) {
|
||||
logger.error("Error saving session:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load chat history from session file
|
||||
* Update the sessions list file
|
||||
*/
|
||||
export function loadSession(): ChatCompletionMessageParam[] | null {
|
||||
function updateSessionsList(session: Session): void {
|
||||
try {
|
||||
const sessionFilePath = getSessionFilePath();
|
||||
const listPath = getSessionsListPath();
|
||||
let sessions: SessionMetadata[] = [];
|
||||
|
||||
if (fs.existsSync(listPath)) {
|
||||
const content = fs.readFileSync(listPath, 'utf8');
|
||||
try {
|
||||
sessions = JSON.parse(content);
|
||||
} catch {
|
||||
sessions = [];
|
||||
}
|
||||
}
|
||||
|
||||
// Find or create session metadata
|
||||
const existingIndex = sessions.findIndex(s => s.sessionId === session.sessionId);
|
||||
const metadata: SessionMetadata = {
|
||||
sessionId: session.sessionId,
|
||||
title: session.title || "Untitled Session",
|
||||
dateCreated: existingIndex >= 0 ? sessions[existingIndex].dateCreated : new Date().toISOString(),
|
||||
workspaceDirectory: session.workspaceDirectory || process.cwd(),
|
||||
};
|
||||
|
||||
if (existingIndex >= 0) {
|
||||
sessions[existingIndex] = metadata;
|
||||
} else {
|
||||
sessions.push(metadata);
|
||||
}
|
||||
|
||||
fs.writeFileSync(listPath, JSON.stringify(sessions, null, 2));
|
||||
} catch (error) {
|
||||
logger.error("Error updating sessions list:", error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!fs.existsSync(sessionFilePath)) {
|
||||
/**
|
||||
* Load session from current terminal's session file
|
||||
*/
|
||||
export function loadSession(): Session | null {
|
||||
try {
|
||||
// For resume, we need to find the most recent session
|
||||
const sessionDir = getSessionDir();
|
||||
if (!fs.existsSync(sessionDir)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, "utf8"));
|
||||
return sessionData.chatHistory || null;
|
||||
const files = fs.readdirSync(sessionDir)
|
||||
.filter(f => f.endsWith('.json') && !f.includes('sessions-list'))
|
||||
.map(f => ({
|
||||
name: f,
|
||||
path: path.join(sessionDir, f),
|
||||
mtime: fs.statSync(path.join(sessionDir, f)).mtime
|
||||
}))
|
||||
.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
||||
|
||||
if (files.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Load the most recent session
|
||||
const session: Session = JSON.parse(fs.readFileSync(files[0].path, "utf8"));
|
||||
// Set this as the current session for future saves
|
||||
currentSessionId = session.sessionId;
|
||||
return session;
|
||||
} catch (error) {
|
||||
logger.error("Error loading session:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new session
|
||||
*/
|
||||
export function createSession(history: ChatHistoryItem[] = []): Session {
|
||||
const sessionId = uuidv4();
|
||||
currentSessionId = sessionId; // Store for future reference
|
||||
return {
|
||||
sessionId,
|
||||
title: "Untitled Session",
|
||||
workspaceDirectory: process.cwd(),
|
||||
history,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the current session
|
||||
*/
|
||||
export function clearSession(): void {
|
||||
try {
|
||||
const sessionFilePath = getSessionFilePath();
|
||||
if (fs.existsSync(sessionFilePath)) {
|
||||
fs.unlinkSync(sessionFilePath);
|
||||
if (currentSessionId) {
|
||||
const sessionFilePath = path.join(getSessionDir(), `${currentSessionId}.json`);
|
||||
if (fs.existsSync(sessionFilePath)) {
|
||||
fs.unlinkSync(sessionFilePath);
|
||||
}
|
||||
currentSessionId = null;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("Error clearing session:", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if a session exists for the current terminal
|
||||
*/
|
||||
export function hasSession(): boolean {
|
||||
const sessionFilePath = getSessionFilePath();
|
||||
if (!currentSessionId) {
|
||||
return false;
|
||||
}
|
||||
const sessionFilePath = path.join(getSessionDir(), `${currentSessionId}.json`);
|
||||
return fs.existsSync(sessionFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Session metadata for listing sessions
|
||||
*/
|
||||
export interface SessionMetadata {
|
||||
id: string; // Session ID from filename
|
||||
path: string; // Full file path
|
||||
timestamp: Date; // Last modified or session timestamp
|
||||
messageCount: number; // Total messages in session
|
||||
firstUserMessage?: string; // Preview of first user input
|
||||
}
|
||||
|
||||
/**
|
||||
* Get metadata from a session file
|
||||
* Get metadata from a session file with first user message preview
|
||||
*/
|
||||
function getSessionMetadata(filePath: string): SessionMetadata | null {
|
||||
function getSessionMetadataWithPreview(filePath: string): SessionMetadata & { firstUserMessage?: string } | null {
|
||||
try {
|
||||
const fileName = path.basename(filePath, ".json");
|
||||
const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
||||
const stats = fs.statSync(filePath);
|
||||
const sessionData = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
||||
|
||||
const chatHistory = sessionData.chatHistory || [];
|
||||
const messageCount = chatHistory.length;
|
||||
|
||||
// Find the first user message
|
||||
// Find the first user message for preview
|
||||
let firstUserMessage: string | undefined;
|
||||
for (let i = 0; i < chatHistory.length; i++) {
|
||||
if (chatHistory[i].role === "user") {
|
||||
const content = chatHistory[i].content;
|
||||
for (const item of sessionData.history || []) {
|
||||
if (item.message.role === "user") {
|
||||
const content = item.message.content;
|
||||
// Handle both string and array content types
|
||||
if (typeof content === "string") {
|
||||
firstUserMessage = content;
|
||||
} else if (Array.isArray(content)) {
|
||||
// For array content, find the first text part
|
||||
const textPart = content.find((part) => part.type === "text");
|
||||
firstUserMessage = textPart?.text || "(multimodal message)";
|
||||
firstUserMessage = textPart && 'text' in textPart ? textPart.text : "(multimodal message)";
|
||||
} else {
|
||||
firstUserMessage = "(unknown content type)";
|
||||
}
|
||||
|
|
@ -286,16 +243,11 @@ function getSessionMetadata(filePath: string): SessionMetadata | null {
|
|||
}
|
||||
}
|
||||
|
||||
// Use session timestamp if available, otherwise file modification time
|
||||
const timestamp = sessionData.timestamp
|
||||
? new Date(sessionData.timestamp)
|
||||
: stats.mtime;
|
||||
|
||||
return {
|
||||
id: fileName,
|
||||
path: filePath,
|
||||
timestamp,
|
||||
messageCount,
|
||||
sessionId: sessionData.sessionId,
|
||||
title: sessionData.title || "Untitled Session",
|
||||
dateCreated: stats.birthtime.toISOString(),
|
||||
workspaceDirectory: sessionData.workspaceDirectory || "",
|
||||
firstUserMessage,
|
||||
};
|
||||
} catch (error) {
|
||||
|
|
@ -307,7 +259,7 @@ function getSessionMetadata(filePath: string): SessionMetadata | null {
|
|||
/**
|
||||
* List all available sessions with metadata
|
||||
*/
|
||||
export function listSessions(limit: number = 10): SessionMetadata[] {
|
||||
export function listSessions(limit: number = 10): (SessionMetadata & { firstUserMessage?: string })[] {
|
||||
try {
|
||||
const sessionDir = getSessionDir();
|
||||
|
||||
|
|
@ -317,21 +269,21 @@ export function listSessions(limit: number = 10): SessionMetadata[] {
|
|||
|
||||
const files = fs
|
||||
.readdirSync(sessionDir)
|
||||
.filter((file) => file.endsWith(".json"))
|
||||
.filter((file) => file.endsWith(".json") && file !== "sessions.json")
|
||||
.map((file) => path.join(sessionDir, file));
|
||||
|
||||
const sessions: SessionMetadata[] = [];
|
||||
const sessions: (SessionMetadata & { firstUserMessage?: string })[] = [];
|
||||
|
||||
for (const filePath of files) {
|
||||
const metadata = getSessionMetadata(filePath);
|
||||
const metadata = getSessionMetadataWithPreview(filePath);
|
||||
if (metadata) {
|
||||
sessions.push(metadata);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by timestamp (most recent first) and limit results
|
||||
// Sort by date created (most recent first) and limit results
|
||||
return sessions
|
||||
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
|
||||
.sort((a, b) => new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime())
|
||||
.slice(0, limit);
|
||||
} catch (error) {
|
||||
logger.error("Error listing sessions:", error);
|
||||
|
|
@ -340,11 +292,9 @@ export function listSessions(limit: number = 10): SessionMetadata[] {
|
|||
}
|
||||
|
||||
/**
|
||||
* Load chat history from a specific session file
|
||||
* Load session by ID
|
||||
*/
|
||||
export function loadSessionById(
|
||||
sessionId: string,
|
||||
): ChatCompletionMessageParam[] | null {
|
||||
export function loadSessionById(sessionId: string): Session | null {
|
||||
try {
|
||||
const sessionDir = getSessionDir();
|
||||
const sessionFilePath = path.join(sessionDir, `${sessionId}.json`);
|
||||
|
|
@ -353,8 +303,8 @@ export function loadSessionById(
|
|||
return null;
|
||||
}
|
||||
|
||||
const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, "utf8"));
|
||||
return sessionData.chatHistory || null;
|
||||
const session: Session = JSON.parse(fs.readFileSync(sessionFilePath, "utf8"));
|
||||
return session;
|
||||
} catch (error) {
|
||||
logger.error("Error loading session by ID:", error);
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
|
||||
|
||||
// Mock dependencies
|
||||
|
|
@ -9,6 +10,7 @@ vi.mock("./compaction.js", () => ({
|
|||
}));
|
||||
|
||||
vi.mock("./session.js", () => ({
|
||||
createSession: vi.fn((history) => ({ sessionId: "test", title: "Test", workspaceDirectory: "/test", history })),
|
||||
saveSession: vi.fn(),
|
||||
}));
|
||||
|
||||
|
|
@ -82,16 +84,16 @@ describe("handleAutoCompaction", () => {
|
|||
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
|
||||
|
||||
const mockCompactionResult = {
|
||||
compactedHistory: [
|
||||
compactedHistory: convertToUnifiedHistory([
|
||||
{
|
||||
role: "system",
|
||||
content: "You are a helpful assistant.",
|
||||
} as ChatCompletionMessageParam,
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: "[COMPACTED HISTORY]\nConversation summary...",
|
||||
} as ChatCompletionMessageParam,
|
||||
],
|
||||
},
|
||||
]),
|
||||
compactionIndex: 1,
|
||||
compactionContent: "Conversation summary...",
|
||||
};
|
||||
|
|
@ -188,9 +190,9 @@ describe("handleAutoCompaction", () => {
|
|||
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
|
||||
|
||||
const mockCompactionResult = {
|
||||
compactedHistory: [
|
||||
{ role: "system", content: "System" } as ChatCompletionMessageParam,
|
||||
],
|
||||
compactedHistory: convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
]),
|
||||
compactionIndex: 0,
|
||||
compactionContent: "Summary",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -3,8 +3,10 @@ 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 { convertFromUnifiedHistory, convertToUnifiedHistory } from "./messageConversion.js";
|
||||
import { createSession, saveSession } from "./session.js";
|
||||
import { formatError } from "./util/formatError.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js";
|
||||
|
|
@ -139,9 +141,12 @@ export async function handleAutoCompaction(
|
|||
notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks);
|
||||
|
||||
try {
|
||||
// Convert to unified format for compaction
|
||||
const unifiedHistory = convertToUnifiedHistory(chatHistory);
|
||||
|
||||
// Compact the history
|
||||
const result = await compactChatHistory(
|
||||
chatHistory,
|
||||
unifiedHistory,
|
||||
model,
|
||||
llmApi,
|
||||
isHeadless
|
||||
|
|
@ -153,13 +158,17 @@ export async function handleAutoCompaction(
|
|||
);
|
||||
|
||||
// Save the compacted session
|
||||
saveSession(result.compactedHistory);
|
||||
const session = createSession(result.compactedHistory);
|
||||
saveSession(session);
|
||||
|
||||
// Handle success notification
|
||||
handleCompactionSuccess(result, isHeadless, callbacks);
|
||||
|
||||
// Convert back to legacy format for return
|
||||
const compactedLegacyHistory = convertFromUnifiedHistory(result.compactedHistory);
|
||||
|
||||
return {
|
||||
chatHistory: result.compactedHistory,
|
||||
chatHistory: compactedLegacyHistory,
|
||||
compactionIndex: result.compactionIndex,
|
||||
};
|
||||
} catch (error: any) {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@ import type {
|
|||
ChatCompletionTool,
|
||||
} from "openai/resources.mjs";
|
||||
|
||||
import type { ChatHistoryItem } from "../../../core/index.js";
|
||||
|
||||
import { convertFromUnifiedHistory } from "./messageConversion.js";
|
||||
import { filterExcludedTools } from "./permissions/index.js";
|
||||
import {
|
||||
getServiceSync,
|
||||
|
|
@ -445,12 +448,15 @@ export async function processStreamingResponse(
|
|||
|
||||
// Main function that handles the conversation loop
|
||||
export async function streamChatResponse(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
model: ModelConfig,
|
||||
llmApi: BaseLlmApi,
|
||||
abortController: AbortController,
|
||||
callbacks?: StreamCallbacks,
|
||||
) {
|
||||
// Convert to legacy format for processing
|
||||
const legacyHistory = convertFromUnifiedHistory(chatHistory);
|
||||
|
||||
logger.debug("streamChatResponse called", {
|
||||
model,
|
||||
historyLength: chatHistory.length,
|
||||
|
|
@ -479,7 +485,7 @@ export async function streamChatResponse(
|
|||
// Get response from LLM
|
||||
const { content, toolCalls, shouldContinue } =
|
||||
await processStreamingResponse({
|
||||
chatHistory,
|
||||
chatHistory: legacyHistory,
|
||||
model,
|
||||
llmApi,
|
||||
abortController,
|
||||
|
|
@ -504,7 +510,7 @@ export async function streamChatResponse(
|
|||
// Handle tool calls and check for early return
|
||||
const shouldReturn = await handleToolCalls(
|
||||
toolCalls,
|
||||
chatHistory,
|
||||
legacyHistory,
|
||||
content,
|
||||
callbacks,
|
||||
isHeadless,
|
||||
|
|
@ -517,7 +523,7 @@ export async function streamChatResponse(
|
|||
// Check for auto-compaction after tool execution
|
||||
if (shouldContinue) {
|
||||
const { chatHistory: updatedChatHistory, compactionIndex } =
|
||||
await handleAutoCompaction(chatHistory, model, llmApi, {
|
||||
await handleAutoCompaction(legacyHistory, model, llmApi, {
|
||||
isHeadless,
|
||||
callbacks: {
|
||||
onSystemMessage: callbacks?.onSystemMessage,
|
||||
|
|
@ -526,9 +532,9 @@ export async function streamChatResponse(
|
|||
});
|
||||
|
||||
// Only update chat history if compaction actually occurred
|
||||
if (compactionIndex !== null && updatedChatHistory !== chatHistory) {
|
||||
chatHistory.length = 0;
|
||||
chatHistory.push(...updatedChatHistory);
|
||||
if (compactionIndex !== null && updatedChatHistory !== legacyHistory) {
|
||||
legacyHistory.length = 0;
|
||||
legacyHistory.push(...updatedChatHistory);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -540,7 +546,7 @@ export async function streamChatResponse(
|
|||
|
||||
logger.debug("streamChatResponse complete", {
|
||||
totalResponseLength: fullResponse.length,
|
||||
totalMessages: chatHistory.length,
|
||||
totalMessages: legacyHistory.length,
|
||||
});
|
||||
|
||||
// For headless mode, we return only the final response
|
||||
|
|
|
|||
|
|
@ -17,47 +17,42 @@ describe("SessionSelector", () => {
|
|||
|
||||
it("formats timestamps correctly for different time periods", () => {
|
||||
const now = new Date();
|
||||
const today = addHours(startOfDay(now), 14); // 2 PM today
|
||||
const yesterday = subDays(today, 1);
|
||||
const thisWeek = subDays(today, 3); // 3 days ago (this week)
|
||||
const thisYear = subMonths(today, 2); // 2 months ago (this year)
|
||||
const lastYear = subYears(today, 1); // 1 year ago
|
||||
const today = addHours(startOfDay(now), 14).toISOString(); // 2 PM today
|
||||
const yesterday = subDays(new Date(today), 1).toISOString();
|
||||
const thisWeek = subDays(new Date(today), 3).toISOString(); // 3 days ago (this week)
|
||||
const thisYear = subMonths(new Date(today), 2).toISOString(); // 2 months ago (this year)
|
||||
const lastYear = subYears(new Date(today), 1).toISOString(); // 1 year ago
|
||||
|
||||
const sessions: SessionMetadata[] = [
|
||||
{
|
||||
id: "session-1",
|
||||
path: "/test/session-1.json",
|
||||
timestamp: today,
|
||||
messageCount: 10,
|
||||
firstUserMessage: "Today's session",
|
||||
sessionId: "session-1",
|
||||
title: "Today's session",
|
||||
dateCreated: today,
|
||||
workspaceDirectory: "/test",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
path: "/test/session-2.json",
|
||||
timestamp: yesterday,
|
||||
messageCount: 5,
|
||||
firstUserMessage: "Yesterday's session",
|
||||
sessionId: "session-2",
|
||||
workspaceDirectory: "/test",
|
||||
dateCreated: yesterday,
|
||||
title: "Yesterday's session",
|
||||
},
|
||||
{
|
||||
id: "session-3",
|
||||
path: "/test/session-3.json",
|
||||
timestamp: thisWeek,
|
||||
messageCount: 8,
|
||||
firstUserMessage: "This week's session",
|
||||
sessionId: "session-3",
|
||||
workspaceDirectory: "/test",
|
||||
dateCreated: thisWeek,
|
||||
title: "This week's session",
|
||||
},
|
||||
{
|
||||
id: "session-4",
|
||||
path: "/test/session-4.json",
|
||||
timestamp: thisYear,
|
||||
messageCount: 12,
|
||||
firstUserMessage: "This year's session",
|
||||
sessionId: "session-4",
|
||||
workspaceDirectory: "/test",
|
||||
dateCreated: thisYear,
|
||||
title: "This year's session",
|
||||
},
|
||||
{
|
||||
id: "session-5",
|
||||
path: "/test/session-5.json",
|
||||
timestamp: lastYear,
|
||||
messageCount: 3,
|
||||
firstUserMessage: "Last year's session",
|
||||
sessionId: "session-5",
|
||||
workspaceDirectory: "/test",
|
||||
dateCreated: lastYear,
|
||||
title: "Last year's session",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -100,11 +95,10 @@ describe("SessionSelector", () => {
|
|||
it("handles sessions without first user message", () => {
|
||||
const sessions: SessionMetadata[] = [
|
||||
{
|
||||
id: "session-1",
|
||||
path: "/test/session-1.json",
|
||||
timestamp: new Date(),
|
||||
messageCount: 0,
|
||||
firstUserMessage: undefined,
|
||||
sessionId: "session-1",
|
||||
workspaceDirectory: "/test",
|
||||
dateCreated: new Date().toISOString(),
|
||||
title: "Empty session",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ export function SessionSelector({
|
|||
);
|
||||
} else if (key.return) {
|
||||
if (displaySessions[selectedIndex]) {
|
||||
onSelect(displaySessions[selectedIndex].id);
|
||||
onSelect(displaySessions[selectedIndex].sessionId);
|
||||
}
|
||||
} else if (key.escape || (key.ctrl && input === "d")) {
|
||||
onExit();
|
||||
|
|
@ -94,21 +94,20 @@ export function SessionSelector({
|
|||
const color = isSelected ? "cyan" : "white";
|
||||
|
||||
return (
|
||||
<Box key={session.id} flexDirection="column">
|
||||
<Box key={session.sessionId} flexDirection="column">
|
||||
<Box paddingRight={3}>
|
||||
<Text color={color} wrap="truncate-end">
|
||||
{indicator}
|
||||
{formatMessage(session.firstUserMessage)}
|
||||
{formatMessage(session.title)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginLeft={2}>
|
||||
<Text color="gray">
|
||||
{formatTimestamp(session.timestamp)} - {session.messageCount}{" "}
|
||||
{session.messageCount === 1 ? "message" : "messages"}
|
||||
{formatTimestamp(new Date(session.dateCreated))}
|
||||
</Text>
|
||||
</Box>
|
||||
{index < displaySessions.length - 1 && (
|
||||
<Text key={`spacer-${session.id}`}> </Text>
|
||||
<Text key={`spacer-${session.sessionId}`}> </Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -59,13 +59,12 @@ async function loadAndSetSession(
|
|||
// Close the session selector
|
||||
closeCurrentScreen();
|
||||
|
||||
// Import session functions and conversion utilities
|
||||
// Import session functions
|
||||
const { loadSessionById } = await import("../session.js");
|
||||
const { convertToUnifiedHistory } = await import("../messageConversion.js");
|
||||
|
||||
// Load the session history
|
||||
const sessionHistory = loadSessionById(sessionId);
|
||||
if (!sessionHistory) {
|
||||
// Load the session
|
||||
const session = loadSessionById(sessionId);
|
||||
if (!session) {
|
||||
logger.error(`Session ${sessionId} could not be loaded.`);
|
||||
return;
|
||||
}
|
||||
|
|
@ -76,9 +75,8 @@ async function loadAndSetSession(
|
|||
"",
|
||||
);
|
||||
|
||||
// Convert to unified format and set the chat history
|
||||
const unifiedHistory = convertToUnifiedHistory(sessionHistory);
|
||||
setChatHistory(unifiedHistory);
|
||||
// Set the chat history from the session
|
||||
setChatHistory(session.history);
|
||||
|
||||
// Clear the intro message since we're now showing a resumed session
|
||||
setShowIntroMessage(false);
|
||||
|
|
|
|||
|
|
@ -20,6 +20,13 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
|
|||
|
||||
// Handle system messages
|
||||
if (isSystem) {
|
||||
// TODO: Properly separate LLM system messages from UI informational messages
|
||||
// using discriminated union types. For now, skip displaying the first system
|
||||
// message which is typically the LLM's system prompt.
|
||||
if (index === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box key={index} marginLeft={1} marginBottom={1}>
|
||||
<Text color="gray" italic>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { ChatHistoryItem } from "../../../../../core/index.js";
|
||||
import type { ChatHistoryItem, Session } from "../../../../../core/index.js";
|
||||
import { initializeChatHistory } from "../../commands/chat.js";
|
||||
import { compactChatHistory } from "../../compaction.js";
|
||||
import { convertToUnifiedHistory, convertFromUnifiedHistory } from "../../messageConversion.js";
|
||||
import { convertFromUnifiedHistory, convertToUnifiedHistory } from "../../messageConversion.js";
|
||||
import { loadSession, saveSession } from "../../session.js";
|
||||
import { posthogService } from "../../telemetry/posthogService.js";
|
||||
import { telemetryService } from "../../telemetry/telemetryService.js";
|
||||
|
|
@ -18,9 +18,9 @@ export async function initChatHistory(
|
|||
additionalRules?: string[],
|
||||
): Promise<ChatHistoryItem[]> {
|
||||
if (resume) {
|
||||
const savedHistory = loadSession();
|
||||
if (savedHistory) {
|
||||
return convertToUnifiedHistory(savedHistory);
|
||||
const savedSession = loadSession();
|
||||
if (savedSession) {
|
||||
return savedSession.history;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +28,7 @@ export async function initChatHistory(
|
|||
resume,
|
||||
rule: additionalRules,
|
||||
});
|
||||
return convertToUnifiedHistory(history);
|
||||
return history;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -49,6 +49,8 @@ interface HandleCompactCommandOptions {
|
|||
React.SetStateAction<ChatHistoryItem[]>
|
||||
>;
|
||||
setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
|
||||
currentSession: Session;
|
||||
setCurrentSession: React.Dispatch<React.SetStateAction<Session>>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -60,6 +62,8 @@ export async function handleCompactCommand({
|
|||
llmApi,
|
||||
setChatHistory,
|
||||
setCompactionIndex,
|
||||
currentSession,
|
||||
setCurrentSession,
|
||||
}: HandleCompactCommandOptions): Promise<void> {
|
||||
// Add compacting message
|
||||
setChatHistory((prev) => [
|
||||
|
|
@ -74,19 +78,20 @@ export async function handleCompactCommand({
|
|||
]);
|
||||
|
||||
try {
|
||||
// Convert to legacy format for compaction
|
||||
const legacyHistory = convertFromUnifiedHistory(chatHistory);
|
||||
const result = await compactChatHistory(legacyHistory, model, llmApi);
|
||||
|
||||
// Convert compacted history back to unified format
|
||||
const compactedUnifiedHistory = convertToUnifiedHistory(result.compactedHistory);
|
||||
// Compact the chat history directly (already in unified format)
|
||||
const result = await compactChatHistory(chatHistory, model, llmApi);
|
||||
|
||||
// Replace chat history with compacted version
|
||||
setChatHistory(compactedUnifiedHistory);
|
||||
setChatHistory(result.compactedHistory);
|
||||
setCompactionIndex(result.compactionIndex);
|
||||
|
||||
// Save the compacted session
|
||||
saveSession(result.compactedHistory);
|
||||
const updatedSession: Session = {
|
||||
...currentSession,
|
||||
history: result.compactedHistory,
|
||||
};
|
||||
saveSession(updatedSession);
|
||||
setCurrentSession(updatedSession);
|
||||
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import type { ChatHistoryItem, ToolCallState } from "../../../../../core/index.js";
|
||||
import { convertFromUnifiedHistory } from "../../messageConversion.js";
|
||||
|
||||
interface CreateStreamCallbacksOptions {
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
|
|
@ -191,19 +190,16 @@ export async function executeStreaming({
|
|||
const { getHistoryForLLM } = await import("../../compaction.js");
|
||||
const { streamChatResponse } = await import("../../streamChatResponse.js");
|
||||
|
||||
// Convert to legacy format for LLM
|
||||
const legacyHistory = convertFromUnifiedHistory(chatHistory);
|
||||
|
||||
if (model && llmApi) {
|
||||
if (
|
||||
currentCompactionIndex !== null &&
|
||||
currentCompactionIndex !== undefined
|
||||
) {
|
||||
const historyForLLM = getHistoryForLLM(
|
||||
legacyHistory,
|
||||
chatHistory,
|
||||
currentCompactionIndex,
|
||||
);
|
||||
const originalLength = historyForLLM.length;
|
||||
const _originalLength = historyForLLM.length;
|
||||
|
||||
await streamChatResponse(
|
||||
historyForLLM,
|
||||
|
|
@ -213,11 +209,11 @@ export async function executeStreaming({
|
|||
streamCallbacks,
|
||||
);
|
||||
|
||||
const newMessages = historyForLLM.slice(originalLength);
|
||||
legacyHistory.push(...newMessages);
|
||||
// streamChatResponse modifies the array in place
|
||||
// The new messages are already in historyForLLM
|
||||
} else {
|
||||
await streamChatResponse(
|
||||
legacyHistory,
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
controller,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,11 @@
|
|||
import { useApp } from "ink";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import type { ChatHistoryItem } from "../../../../../core/index.js";
|
||||
import type { ChatHistoryItem, Session } from "../../../../../core/index.js";
|
||||
import { findCompactionIndex } from "../../compaction.js";
|
||||
import { convertToUnifiedHistory, convertFromUnifiedHistory } from "../../messageConversion.js";
|
||||
import { toolPermissionManager } from "../../permissions/permissionManager.js";
|
||||
import { services } from "../../services/index.js";
|
||||
import { loadSession, saveSession } from "../../session.js";
|
||||
import { loadSession, saveSession, createSession } from "../../session.js";
|
||||
import { handleSlashCommands } from "../../slashCommands.js";
|
||||
import { telemetryService } from "../../telemetry/telemetryService.js";
|
||||
import { formatError } from "../../util/formatError.js";
|
||||
|
|
@ -54,25 +53,27 @@ export function useChat({
|
|||
}: UseChatProps) {
|
||||
const { exit } = useApp();
|
||||
|
||||
const [chatHistory, setChatHistory] = useState<ChatHistoryItem[]>(
|
||||
() => {
|
||||
// In remote mode, start with empty history (will be populated by polling)
|
||||
if (isRemoteMode) {
|
||||
return [];
|
||||
}
|
||||
// Store the current session
|
||||
const [currentSession, setCurrentSession] = useState<Session>(() => {
|
||||
// In remote mode, start with empty session (will be populated by polling)
|
||||
if (isRemoteMode) {
|
||||
return createSession([]);
|
||||
}
|
||||
|
||||
// Synchronously initialize chat history to prevent race conditions
|
||||
// Load previous session if resume flag is used
|
||||
// If no session loaded or not resuming, we'll need to add system message
|
||||
// We can't make this async, so we'll handle it in the useEffect
|
||||
if (resume) {
|
||||
const savedHistory = loadSession();
|
||||
if (savedHistory) {
|
||||
return convertToUnifiedHistory(savedHistory);
|
||||
}
|
||||
// Load previous session if resume flag is used
|
||||
if (resume) {
|
||||
const savedSession = loadSession();
|
||||
if (savedSession) {
|
||||
return savedSession;
|
||||
}
|
||||
return [];
|
||||
},
|
||||
}
|
||||
|
||||
// Create new session
|
||||
return createSession([]);
|
||||
});
|
||||
|
||||
const [chatHistory, setChatHistory] = useState<ChatHistoryItem[]>(
|
||||
() => currentSession.history
|
||||
);
|
||||
|
||||
const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
|
||||
|
|
@ -85,7 +86,7 @@ export function useChat({
|
|||
const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState(
|
||||
// If we're resuming and found a saved session, we're already initialized
|
||||
// If we're in remote mode, we're initialized (will be populated by polling)
|
||||
isRemoteMode || (resume && loadSession() !== null),
|
||||
isRemoteMode || (resume && currentSession.history.length > 0),
|
||||
);
|
||||
|
||||
// Capture initial rules to prevent re-initialization when rules change
|
||||
|
|
@ -95,11 +96,8 @@ export function useChat({
|
|||
useState<ActivePermissionRequest | null>(null);
|
||||
const [compactionIndex, setCompactionIndex] = useState<number | null>(() => {
|
||||
// When resuming, check for compaction markers in the loaded history
|
||||
if (resume) {
|
||||
const savedHistory = loadSession();
|
||||
if (savedHistory) {
|
||||
return findCompactionIndex(savedHistory);
|
||||
}
|
||||
if (resume && currentSession.history.length > 0) {
|
||||
return findCompactionIndex(currentSession.history);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
|
@ -212,10 +210,14 @@ export function useChat({
|
|||
currentCompactionIndex,
|
||||
});
|
||||
|
||||
// Save the updated history to session
|
||||
// Save the updated session
|
||||
logger.debug("Saving session", { historyLength: newHistory.length });
|
||||
const legacyHistory = convertFromUnifiedHistory(newHistory);
|
||||
saveSession(legacyHistory);
|
||||
const updatedSession: Session = {
|
||||
...currentSession,
|
||||
history: newHistory,
|
||||
};
|
||||
saveSession(updatedSession);
|
||||
setCurrentSession(updatedSession);
|
||||
logger.debug("Session saved");
|
||||
} catch (error: any) {
|
||||
const errorMessage = `Error: ${formatError(error)}`;
|
||||
|
|
@ -264,6 +266,8 @@ export function useChat({
|
|||
llmApi,
|
||||
setChatHistory,
|
||||
setCompactionIndex,
|
||||
currentSession,
|
||||
setCurrentSession,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue