Merge pull request #7435 from continuedev/generate-message-titles-in-cli
feat: Generate message titles in CLI
This commit is contained in:
commit
7ad698c774
56 changed files with 1320 additions and 529 deletions
|
|
@ -5,6 +5,7 @@ import { removeCodeBlocksAndTrim, removeQuotesAndEscapes } from ".";
|
|||
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
|
||||
import type { IMessenger } from "../protocol/messenger";
|
||||
import { renderChatMessage } from "./messageContent";
|
||||
import { convertFromUnifiedHistory } from "./messageConversion";
|
||||
|
||||
export class ChatDescriber {
|
||||
static maxTokens = 12;
|
||||
|
|
@ -46,6 +47,67 @@ export class ChatDescriber {
|
|||
return removeQuotesAndEscapes(renderChatMessage(titleResponse));
|
||||
}
|
||||
|
||||
// CLI-specific method that works with BaseLlmApi
|
||||
static async describeWithBaseLlmApi(
|
||||
llmApi: any, // BaseLlmApi - using any to avoid import issues
|
||||
modelConfig: any, // ModelConfig - using any to avoid import issues
|
||||
message: string,
|
||||
): Promise<string | undefined> {
|
||||
if (!ChatDescriber.prompt) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clean up and distill the message we want to send to the LLM
|
||||
message = removeCodeBlocksAndTrim(message);
|
||||
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create the chat message in the unified format
|
||||
const chatMessage = {
|
||||
role: "user" as const,
|
||||
content: ChatDescriber.prompt + message,
|
||||
};
|
||||
|
||||
// Convert to OpenAI format - use a simple fallback to avoid import issues
|
||||
const openaiMessages = convertFromUnifiedHistory([
|
||||
{
|
||||
message: chatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
// Set up completion options for non-streaming
|
||||
const completionOptions = {
|
||||
model: modelConfig.model,
|
||||
messages: openaiMessages,
|
||||
max_tokens: ChatDescriber.maxTokens,
|
||||
stream: false as const,
|
||||
};
|
||||
|
||||
// Call the LLM
|
||||
const titleResponse = await llmApi.chatCompletionNonStream(
|
||||
completionOptions,
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
// Extract and clean up the response
|
||||
if (titleResponse.choices && titleResponse.choices.length > 0) {
|
||||
const content = titleResponse.choices[0].message.content;
|
||||
if (content) {
|
||||
return removeQuotesAndEscapes(content);
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
console.debug("Error generating chat title:", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// // TODO: Allow the user to manually set specific/tailored prompts to generate their titles
|
||||
// static async setup() {
|
||||
// if(config?.prompt) {
|
||||
|
|
|
|||
|
|
@ -93,8 +93,9 @@ describe("Many sessions created", () => {
|
|||
const offset = 10;
|
||||
|
||||
const sessions = historyManager.list({ offset: offset, limit: limit });
|
||||
// Sessions are now reversed, so newest (99) comes first
|
||||
const sessionIds = Array.from({ length: limit }, (_, i) =>
|
||||
(i + offset).toString(),
|
||||
(99 - offset - i).toString(),
|
||||
);
|
||||
const isSessionIdInList = (sessionId: string) =>
|
||||
sessions.some((session) => session.sessionId === sessionId);
|
||||
|
|
@ -105,7 +106,10 @@ describe("Many sessions created", () => {
|
|||
const limit = 25;
|
||||
|
||||
const sessions = historyManager.list({ limit: limit });
|
||||
const sessionIds = Array.from({ length: limit }, (_, i) => i.toString());
|
||||
// Sessions are now reversed, so newest (99) comes first
|
||||
const sessionIds = Array.from({ length: limit }, (_, i) =>
|
||||
(99 - i).toString(),
|
||||
);
|
||||
|
||||
const isSessionIdInList = (sessionId: string) =>
|
||||
sessions.some((session) => session.sessionId === sessionId);
|
||||
|
|
|
|||
|
|
@ -30,10 +30,13 @@ export class HistoryManager {
|
|||
const content = fs.readFileSync(filepath, "utf8");
|
||||
|
||||
let sessions = safeParseArray<SessionMetadata>(content) ?? [];
|
||||
sessions = sessions.filter((session: any) => {
|
||||
// Filter out old format
|
||||
return typeof session.session_id !== "string";
|
||||
});
|
||||
sessions = sessions
|
||||
.filter((session: any) => {
|
||||
// Filter out old format
|
||||
return typeof session.session_id !== "string";
|
||||
// Reverse to show newest first; sessions.json is chronological by creation
|
||||
})
|
||||
.reverse();
|
||||
|
||||
// Apply limit and offset
|
||||
if (options.limit) {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
* format and the unified ChatHistoryItem format from the core package.
|
||||
*/
|
||||
|
||||
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import type {
|
||||
AssistantChatMessage,
|
||||
ChatHistoryItem,
|
||||
|
|
@ -14,8 +15,7 @@ import type {
|
|||
ToolCall,
|
||||
ToolCallState,
|
||||
ToolStatus,
|
||||
} from "core/index.js";
|
||||
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
} from "../index.js";
|
||||
|
||||
/**
|
||||
* Convert ChatCompletionMessageParam to ChatMessage
|
||||
|
|
@ -222,15 +222,18 @@ function handleToolResult(
|
|||
if (!toolCall) return;
|
||||
|
||||
// Add tool result as context to the previous assistant message
|
||||
const lastAssistantIndex = historyItems.findLastIndex(
|
||||
(item) => item.message.role === "assistant",
|
||||
);
|
||||
|
||||
let lastAssistantIndex = -1;
|
||||
for (let i = historyItems.length - 1; i >= 0; i--) {
|
||||
if (historyItems[i].message.role === "assistant") {
|
||||
lastAssistantIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastAssistantIndex < 0) return;
|
||||
if (!historyItems[lastAssistantIndex].toolCallStates) return;
|
||||
|
||||
const toolState = historyItems[lastAssistantIndex].toolCallStates?.find(
|
||||
(ts) => ts.toolCallId === unifiedMessage.toolCallId,
|
||||
(ts: ToolCallState) => ts.toolCallId === unifiedMessage.toolCallId,
|
||||
);
|
||||
|
||||
if (toolState) {
|
||||
|
|
@ -311,7 +314,7 @@ export function convertFromUnifiedHistory(
|
|||
) {
|
||||
const contextContent = item.contextItems
|
||||
.map(
|
||||
(contextItem) =>
|
||||
(contextItem: ContextItemWithId) =>
|
||||
`<context name="${contextItem.name}">\n${contextItem.content}\n</context>\n\n`,
|
||||
)
|
||||
.join("");
|
||||
|
|
@ -341,6 +344,30 @@ export function convertFromUnifiedHistory(
|
|||
return messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message
|
||||
* @param historyItems - The chat history items
|
||||
* @param systemMessage - The system message to inject at the beginning
|
||||
*/
|
||||
export function convertFromUnifiedHistoryWithSystemMessage(
|
||||
historyItems: ChatHistoryItem[],
|
||||
systemMessage: string,
|
||||
): ChatCompletionMessageParam[] {
|
||||
const messages: ChatCompletionMessageParam[] = [];
|
||||
|
||||
// Inject system message at the beginning
|
||||
messages.push({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
|
||||
// Convert the rest of the history
|
||||
const convertedMessages = convertFromUnifiedHistory(historyItems);
|
||||
messages.push(...convertedMessages);
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract tool call information from a ChatHistoryItem
|
||||
*/
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import chalk from "chalk";
|
||||
import type { ChatHistoryItem, Session } from "core/index.js";
|
||||
import { ChatDescriber } from "core/util/chatDescriber.js";
|
||||
import * as readlineSync from "readline-sync";
|
||||
|
||||
import { getDisplayableAsciiArt } from "../asciiArt.js";
|
||||
import {
|
||||
compactChatHistory,
|
||||
findCompactionIndex,
|
||||
|
|
@ -17,9 +17,12 @@ 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, updateSessionHistory } from "../session.js";
|
||||
import { streamChatResponse } from "../streamChatResponse.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import {
|
||||
loadSession,
|
||||
updateSessionHistory,
|
||||
updateSessionTitle,
|
||||
} from "../session.js";
|
||||
import { streamChatResponse } from "../stream/streamChatResponse.js";
|
||||
import { posthogService } from "../telemetry/posthogService.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { startTUIChat } from "../ui/index.js";
|
||||
|
|
@ -97,21 +100,7 @@ export async function initializeChatHistory(
|
|||
}
|
||||
}
|
||||
|
||||
// If no session loaded or not resuming, initialize with system message
|
||||
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;
|
||||
return [];
|
||||
}
|
||||
|
||||
// Helper function to handle manual compaction
|
||||
|
|
@ -168,7 +157,7 @@ async function handleAutoCompaction(
|
|||
format?: "json",
|
||||
): Promise<number | null> {
|
||||
const { handleAutoCompaction: coreAutoCompaction } = await import(
|
||||
"../streamChatResponse.autoCompaction.js"
|
||||
"../stream/streamChatResponse.autoCompaction.js"
|
||||
);
|
||||
|
||||
// Custom callbacks for headless mode console output
|
||||
|
|
@ -234,6 +223,33 @@ async function handleAutoCompaction(
|
|||
return result.compactionIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to generate and update session title after first assistant response
|
||||
*/
|
||||
async function handleTitleGeneration(
|
||||
assistantResponse: string,
|
||||
llmApi: any,
|
||||
model: ModelConfig,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (!assistantResponse) return;
|
||||
|
||||
const generatedTitle = await ChatDescriber.describeWithBaseLlmApi(
|
||||
llmApi,
|
||||
model,
|
||||
assistantResponse,
|
||||
);
|
||||
|
||||
if (generatedTitle) {
|
||||
updateSessionTitle(generatedTitle);
|
||||
logger.debug("Generated session title:", generatedTitle);
|
||||
}
|
||||
} catch (error) {
|
||||
// Don't fail the response if title generation fails
|
||||
logger.debug("Session title generation failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
interface ProcessMessageOptions {
|
||||
userInput: string;
|
||||
chatHistory: ChatHistoryItem[];
|
||||
|
|
@ -243,6 +259,7 @@ interface ProcessMessageOptions {
|
|||
format?: "json";
|
||||
silent?: boolean;
|
||||
compactionIndex?: number | null;
|
||||
firstAssistantResponse?: boolean;
|
||||
}
|
||||
|
||||
async function processMessage(
|
||||
|
|
@ -257,6 +274,7 @@ async function processMessage(
|
|||
format,
|
||||
silent,
|
||||
compactionIndex: initialCompactionIndex,
|
||||
firstAssistantResponse = false,
|
||||
} = options;
|
||||
let compactionIndex = initialCompactionIndex;
|
||||
// Check for slash commands in headless mode
|
||||
|
|
@ -326,6 +344,11 @@ async function processMessage(
|
|||
// No need to sync back - streamChatResponse modifies chatHistory in place
|
||||
}
|
||||
|
||||
// Generate session title after first assistant response
|
||||
if (firstAssistantResponse && finalResponse && finalResponse.trim()) {
|
||||
await handleTitleGeneration(finalResponse, llmApi, model);
|
||||
}
|
||||
|
||||
// In headless mode, only print the final response using safe stdout
|
||||
if (isHeadless && finalResponse && finalResponse.trim()) {
|
||||
let processedResponse = finalResponse;
|
||||
|
|
@ -433,6 +456,7 @@ async function runHeadlessMode(
|
|||
format: options.format,
|
||||
silent: options.silent,
|
||||
compactionIndex,
|
||||
firstAssistantResponse: isFirstMessage && !options.resume, // Only generate title for new conversations
|
||||
});
|
||||
|
||||
// Update compaction index if compaction occurred
|
||||
|
|
@ -474,9 +498,6 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
|
|||
console.log(chalk.green("✓ Setup complete! Starting chat..."));
|
||||
}
|
||||
|
||||
// Show ASCII art and version for TUI mode
|
||||
console.log(getDisplayableAsciiArt());
|
||||
|
||||
// Start TUI with skipOnboarding since we already handled it
|
||||
const tuiOptions: any = {
|
||||
initialPrompt: prompt,
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import type {
|
|||
ToolStatus,
|
||||
} from "core/index.js";
|
||||
|
||||
import { streamChatResponse } from "../streamChatResponse.js";
|
||||
import { StreamCallbacks } from "../streamChatResponse.types.js";
|
||||
import { streamChatResponse } from "../stream/streamChatResponse.js";
|
||||
import { StreamCallbacks } from "../stream/streamChatResponse.types.js";
|
||||
|
||||
// Modified version of streamChatResponse that supports interruption
|
||||
export async function streamChatResponseWithInterruption(
|
||||
|
|
|
|||
|
|
@ -3,11 +3,11 @@ import { promisify } from "util";
|
|||
|
||||
import chalk from "chalk";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { convertFromUnifiedHistory } from "core/util/messageConversion.js";
|
||||
import express, { Request, Response } from "express";
|
||||
|
||||
import { getAssistantSlug } from "../auth/workos.js";
|
||||
import { processCommandFlags } from "../flags/flagProcessor.js";
|
||||
import { convertFromUnifiedHistory } from "../messageConversion.js";
|
||||
import { toolPermissionManager } from "../permissions/permissionManager.js";
|
||||
import {
|
||||
getService,
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { convertToUnifiedHistory } from "core/util/messageConversion.js";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { compactChatHistory } from "./compaction.js";
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
import { streamChatResponse } from "./stream/streamChatResponse.js";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("./streamChatResponse.js", () => ({
|
||||
vi.mock("./stream/streamChatResponse.js", () => ({
|
||||
streamChatResponse: vi.fn(),
|
||||
}));
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { convertToUnifiedHistory } from "core/util/messageConversion.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { pruneLastMessage } from "./compaction.js";
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
describe("pruneLastMessage", () => {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { convertToUnifiedHistory } from "core/util/messageConversion.js";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
|
|
@ -8,11 +9,10 @@ import {
|
|||
findCompactionIndex,
|
||||
getHistoryForLLM,
|
||||
} from "./compaction.js";
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
import { streamChatResponse } from "./stream/streamChatResponse.js";
|
||||
|
||||
// Mock the streamChatResponse function
|
||||
vi.mock("./streamChatResponse.js", () => ({
|
||||
vi.mock("./stream/streamChatResponse.js", () => ({
|
||||
streamChatResponse: vi.fn(),
|
||||
}));
|
||||
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ import { ModelConfig } from "@continuedev/config-yaml";
|
|||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
import { StreamCallbacks } from "./streamChatResponse.types.js";
|
||||
import { streamChatResponse } from "./stream/streamChatResponse.js";
|
||||
import { StreamCallbacks } from "./stream/streamChatResponse.types.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
import {
|
||||
countChatHistoryTokens,
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import {
|
|||
getConfigUri,
|
||||
getOrganizationId,
|
||||
isEnvironmentAuthConfig,
|
||||
loadAuthConfig,
|
||||
updateConfigUri,
|
||||
} from "./auth/workos.js";
|
||||
import { CLIPlatformClient } from "./CLIPlatformClient.js";
|
||||
|
|
@ -358,7 +359,7 @@ async function loadAssistantSlug(
|
|||
uriType: "slug",
|
||||
fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" },
|
||||
},
|
||||
null,
|
||||
getAccessToken(loadAuthConfig()),
|
||||
organizationId,
|
||||
apiClient,
|
||||
);
|
||||
|
|
|
|||
4
extensions/cli/src/constants/session.ts
Normal file
4
extensions/cli/src/constants/session.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/**
|
||||
* Session-related constants
|
||||
*/
|
||||
export const DEFAULT_SESSION_TITLE = "Untitled Session";
|
||||
|
|
@ -29,13 +29,23 @@ describe("E2E: Authentication", () => {
|
|||
await fs.writeFile(
|
||||
authPath,
|
||||
JSON.stringify({
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
user: { id: "test-user", email: "test@example.com" },
|
||||
refreshToken: "test-refresh-token",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: null,
|
||||
}),
|
||||
);
|
||||
|
||||
// Run logout
|
||||
const result = await runCLI(context, { args: ["logout"] });
|
||||
const result = await runCLI(context, {
|
||||
args: ["logout"],
|
||||
env: {
|
||||
HOME: context.testDir,
|
||||
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue")
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("Successfully logged out");
|
||||
|
|
@ -49,7 +59,13 @@ describe("E2E: Authentication", () => {
|
|||
});
|
||||
|
||||
it("should handle logout when not logged in", async () => {
|
||||
const result = await runCLI(context, { args: ["logout"] });
|
||||
const result = await runCLI(context, {
|
||||
args: ["logout"],
|
||||
env: {
|
||||
HOME: context.testDir,
|
||||
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue")
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("No active session found");
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ describe("E2E: Resume Flag", () => {
|
|||
env: {
|
||||
// Use a fixed session ID so both CLI calls use the same session
|
||||
CONTINUE_CLI_TEST_SESSION_ID: "test-session-123",
|
||||
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"),
|
||||
},
|
||||
timeout: 15000,
|
||||
});
|
||||
|
|
@ -45,6 +46,14 @@ describe("E2E: Resume Flag", () => {
|
|||
|
||||
// Verify that a session file was created
|
||||
const sessionDir = path.join(context.testDir, ".continue", "sessions");
|
||||
|
||||
// Ensure session directory exists
|
||||
try {
|
||||
await fs.mkdir(sessionDir, { recursive: true });
|
||||
} catch (error) {
|
||||
// Directory already exists, continue
|
||||
}
|
||||
|
||||
const sessionFiles = (await fs.readdir(sessionDir)).filter(
|
||||
f => f.endsWith('.json') && f !== 'sessions.json'
|
||||
);
|
||||
|
|
@ -75,6 +84,7 @@ describe("E2E: Resume Flag", () => {
|
|||
args: ["--resume", "--config", context.configPath],
|
||||
env: {
|
||||
CONTINUE_CLI_TEST_SESSION_ID: "test-session-123",
|
||||
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"),
|
||||
},
|
||||
timeout: 15000,
|
||||
});
|
||||
|
|
@ -92,6 +102,7 @@ describe("E2E: Resume Flag", () => {
|
|||
args: ["--resume", "--config", context.configPath],
|
||||
env: {
|
||||
CONTINUE_CLI_TEST_SESSION_ID: "no-session-456",
|
||||
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"),
|
||||
},
|
||||
timeout: 15000,
|
||||
});
|
||||
|
|
@ -129,6 +140,7 @@ describe("E2E: Resume Flag", () => {
|
|||
args: ["-p", "--config", context.configPath, "first message"],
|
||||
env: {
|
||||
CONTINUE_CLI_TEST_SESSION_ID: sessionId,
|
||||
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"),
|
||||
},
|
||||
timeout: 15000,
|
||||
});
|
||||
|
|
@ -138,6 +150,14 @@ describe("E2E: Resume Flag", () => {
|
|||
|
||||
// Verify the first session was saved correctly
|
||||
const sessionDir = path.join(context.testDir, ".continue", "sessions");
|
||||
|
||||
// Ensure session directory exists
|
||||
try {
|
||||
await fs.mkdir(sessionDir, { recursive: true });
|
||||
} catch (error) {
|
||||
// Directory already exists, continue
|
||||
}
|
||||
|
||||
let sessionFiles = (await fs.readdir(sessionDir)).filter(
|
||||
f => f.endsWith('.json') && f !== 'sessions.json'
|
||||
);
|
||||
|
|
@ -159,6 +179,7 @@ describe("E2E: Resume Flag", () => {
|
|||
],
|
||||
env: {
|
||||
CONTINUE_CLI_TEST_SESSION_ID: sessionId,
|
||||
CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"),
|
||||
},
|
||||
timeout: 15000,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import type { ChatHistoryItem } from "core/index.js";
|
||||
|
||||
import { convertFromUnifiedHistory } from "./messageConversion.js";
|
||||
import { convertFromUnifiedHistory } from "core/util/messageConversion.js";
|
||||
|
||||
describe("convertFromUnifiedHistory", () => {
|
||||
it("should expand contextItems into user message content", () => {
|
||||
|
|
|
|||
187
extensions/cli/src/services/SystemMessageService.test.ts
Normal file
187
extensions/cli/src/services/SystemMessageService.test.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { modeService } from "./ModeService.js";
|
||||
import { SystemMessageService } from "./SystemMessageService.js";
|
||||
|
||||
// Mock the systemMessage module
|
||||
vi.mock("../systemMessage.js", () => ({
|
||||
constructSystemMessage: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock the logger
|
||||
vi.mock("../util/logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("SystemMessageService", () => {
|
||||
let service: SystemMessageService;
|
||||
let constructSystemMessageMock: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Reset mocks
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Get mock reference
|
||||
const { constructSystemMessage } = await import("../systemMessage.js");
|
||||
constructSystemMessageMock = constructSystemMessage as any;
|
||||
|
||||
// Create new service instance
|
||||
service = new SystemMessageService();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await service.cleanup();
|
||||
});
|
||||
|
||||
describe("initialization", () => {
|
||||
it("should initialize with provided configuration", async () => {
|
||||
const config = {
|
||||
additionalRules: ["rule1", "rule2"],
|
||||
format: "json" as const,
|
||||
headless: true,
|
||||
};
|
||||
|
||||
const state = await service.initialize(config);
|
||||
|
||||
expect(state).toEqual(config);
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
it("should initialize with empty configuration", async () => {
|
||||
const state = await service.initialize({});
|
||||
|
||||
expect(state).toEqual({});
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSystemMessage", () => {
|
||||
it("should call constructSystemMessage with current configuration and mode", async () => {
|
||||
const config = {
|
||||
additionalRules: ["rule1"],
|
||||
format: "json" as const,
|
||||
headless: true,
|
||||
};
|
||||
|
||||
constructSystemMessageMock.mockResolvedValue("Test system message");
|
||||
|
||||
await service.initialize(config);
|
||||
const message = await service.getSystemMessage();
|
||||
|
||||
expect(constructSystemMessageMock).toHaveBeenCalledWith(
|
||||
["rule1"],
|
||||
"json",
|
||||
true,
|
||||
"normal", // Default mode
|
||||
);
|
||||
expect(message).toBe("Test system message");
|
||||
});
|
||||
|
||||
it("should use updated mode when mode changes", async () => {
|
||||
constructSystemMessageMock.mockResolvedValue("Updated system message");
|
||||
|
||||
await service.initialize({});
|
||||
|
||||
// Simulate mode change
|
||||
modeService.emit("modeChanged", "plan", "normal");
|
||||
|
||||
const message = await service.getSystemMessage();
|
||||
|
||||
expect(constructSystemMessageMock).toHaveBeenCalledWith(
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
"plan",
|
||||
);
|
||||
expect(message).toBe("Updated system message");
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateConfig", () => {
|
||||
it("should update configuration partially", async () => {
|
||||
await service.initialize({
|
||||
additionalRules: ["rule1"],
|
||||
headless: false,
|
||||
});
|
||||
|
||||
service.updateConfig({
|
||||
format: "json",
|
||||
});
|
||||
|
||||
constructSystemMessageMock.mockResolvedValue("Updated message");
|
||||
await service.getSystemMessage();
|
||||
|
||||
expect(constructSystemMessageMock).toHaveBeenCalledWith(
|
||||
["rule1"],
|
||||
"json",
|
||||
false,
|
||||
"normal",
|
||||
);
|
||||
});
|
||||
|
||||
it("should override existing configuration", async () => {
|
||||
await service.initialize({
|
||||
additionalRules: ["rule1"],
|
||||
format: "json" as const,
|
||||
});
|
||||
|
||||
service.updateConfig({
|
||||
additionalRules: ["rule2", "rule3"],
|
||||
});
|
||||
|
||||
constructSystemMessageMock.mockResolvedValue("Updated message");
|
||||
await service.getSystemMessage();
|
||||
|
||||
expect(constructSystemMessageMock).toHaveBeenCalledWith(
|
||||
["rule2", "rule3"],
|
||||
"json",
|
||||
undefined,
|
||||
"normal",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mode tracking", () => {
|
||||
it("should track current mode from ModeService", async () => {
|
||||
await service.initialize({});
|
||||
|
||||
expect(service.getCurrentMode()).toBe("normal");
|
||||
|
||||
// Simulate mode change
|
||||
modeService.emit("modeChanged", "auto", "normal");
|
||||
|
||||
expect(service.getCurrentMode()).toBe("auto");
|
||||
});
|
||||
|
||||
it("should initialize with current mode from ModeService", async () => {
|
||||
// Mock modeService.getCurrentMode
|
||||
vi.spyOn(modeService, "getCurrentMode").mockReturnValue("plan");
|
||||
|
||||
const newService = new SystemMessageService();
|
||||
await newService.initialize({});
|
||||
|
||||
expect(newService.getCurrentMode()).toBe("plan");
|
||||
|
||||
await newService.cleanup();
|
||||
});
|
||||
});
|
||||
|
||||
describe("error handling", () => {
|
||||
it("should handle constructSystemMessage errors gracefully", async () => {
|
||||
constructSystemMessageMock.mockRejectedValue(
|
||||
new Error("Failed to construct"),
|
||||
);
|
||||
|
||||
await service.initialize({});
|
||||
|
||||
await expect(service.getSystemMessage()).rejects.toThrow(
|
||||
"Failed to construct",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
106
extensions/cli/src/services/SystemMessageService.ts
Normal file
106
extensions/cli/src/services/SystemMessageService.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import { PermissionMode } from "../permissions/types.js";
|
||||
import { constructSystemMessage } from "../systemMessage.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService } from "./BaseService.js";
|
||||
import { modeService } from "./ModeService.js";
|
||||
|
||||
export interface SystemMessageServiceState {
|
||||
additionalRules?: string[];
|
||||
format?: "json";
|
||||
headless?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for managing dynamic system message construction
|
||||
* Provides fresh system messages that reflect current mode and configuration
|
||||
*/
|
||||
export class SystemMessageService extends BaseService<SystemMessageServiceState> {
|
||||
private currentMode: PermissionMode = "normal";
|
||||
|
||||
constructor() {
|
||||
super("SystemMessageService", {});
|
||||
|
||||
// Listen to mode changes from ModeService
|
||||
this.setupModeListener();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up listener for mode changes
|
||||
*/
|
||||
private setupModeListener(): void {
|
||||
modeService.on("modeChanged", (newMode: PermissionMode) => {
|
||||
logger.debug(`SystemMessageService: Mode changed to ${newMode}`);
|
||||
this.currentMode = newMode;
|
||||
});
|
||||
|
||||
// Initialize current mode
|
||||
this.currentMode = modeService.getCurrentMode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the service
|
||||
*/
|
||||
async doInitialize(args: {
|
||||
additionalRules?: string[];
|
||||
format?: "json";
|
||||
headless?: boolean;
|
||||
}): Promise<SystemMessageServiceState> {
|
||||
this.setState({
|
||||
additionalRules: args.additionalRules,
|
||||
format: args.format,
|
||||
headless: args.headless,
|
||||
});
|
||||
|
||||
logger.debug("SystemMessageService initialized", {
|
||||
hasAdditionalRules: !!args.additionalRules?.length,
|
||||
format: args.format,
|
||||
headless: args.headless,
|
||||
});
|
||||
|
||||
return this.currentState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a fresh system message with current mode and configuration
|
||||
*/
|
||||
public async getSystemMessage(): Promise<string> {
|
||||
const { additionalRules, format, headless } = this.currentState;
|
||||
|
||||
const systemMessage = await constructSystemMessage(
|
||||
additionalRules,
|
||||
format,
|
||||
headless,
|
||||
this.currentMode,
|
||||
);
|
||||
|
||||
logger.debug("Generated fresh system message", {
|
||||
mode: this.currentMode,
|
||||
messageLength: systemMessage.length,
|
||||
});
|
||||
|
||||
return systemMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update configuration that affects system message
|
||||
*/
|
||||
public updateConfig(config: Partial<SystemMessageServiceState>): void {
|
||||
this.setState({
|
||||
...this.currentState,
|
||||
...config,
|
||||
});
|
||||
|
||||
logger.debug("SystemMessageService config updated", config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current mode being used for system messages
|
||||
*/
|
||||
public getCurrentMode(): PermissionMode {
|
||||
return this.currentMode;
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const systemMessageService = new SystemMessageService();
|
||||
|
|
@ -11,6 +11,7 @@ import { ModelService } from "./ModelService.js";
|
|||
import { modeService } from "./ModeService.js";
|
||||
import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import { systemMessageService } from "./SystemMessageService.js";
|
||||
import {
|
||||
ApiClientServiceState,
|
||||
AuthServiceState,
|
||||
|
|
@ -111,6 +112,18 @@ export async function initializeServices(
|
|||
toolPermissionState,
|
||||
);
|
||||
|
||||
// Initialize SystemMessageService with command options
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.SYSTEM_MESSAGE,
|
||||
() =>
|
||||
systemMessageService.initialize({
|
||||
additionalRules: commandOptions.rule,
|
||||
format: (commandOptions as any).format, // format option from CLI
|
||||
headless: initOptions.headless,
|
||||
}),
|
||||
[], // No dependencies
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.AUTH,
|
||||
() => authService.initialize(),
|
||||
|
|
@ -293,6 +306,7 @@ export const services = {
|
|||
fileIndex: fileIndexService,
|
||||
mode: modeService,
|
||||
resourceMonitoring: resourceMonitoringService,
|
||||
systemMessage: systemMessageService,
|
||||
} as const;
|
||||
|
||||
// Export the service container for advanced usage
|
||||
|
|
|
|||
|
|
@ -106,6 +106,7 @@ export const SERVICE_NAMES = {
|
|||
TOOL_PERMISSIONS: "toolPermissions",
|
||||
FILE_INDEX: "fileIndex",
|
||||
RESOURCE_MONITORING: "resourceMonitoring",
|
||||
SYSTEM_MESSAGE: "systemMessage",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import fs from "fs";
|
|||
import os from "os";
|
||||
|
||||
import type { ChatHistoryItem, Session } from "core/index.js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
|
|
@ -11,6 +12,7 @@ import {
|
|||
hasSession,
|
||||
loadSession,
|
||||
saveSession,
|
||||
startNewSession,
|
||||
updateSessionHistory,
|
||||
updateSessionTitle,
|
||||
} from "./session.js";
|
||||
|
|
@ -352,4 +354,51 @@ describe("SessionManager", () => {
|
|||
expect(session.history[0].message.content).toBe("Test message");
|
||||
});
|
||||
});
|
||||
|
||||
describe("startNewSession", () => {
|
||||
it("should clear the current session and create a new one", () => {
|
||||
const firstSession = createSession();
|
||||
const firstSessionId = firstSession.sessionId;
|
||||
|
||||
vi.mocked(uuidv4).mockReturnValue("new-uuid-456" as any);
|
||||
|
||||
const secondSession = startNewSession();
|
||||
|
||||
expect(secondSession.sessionId).toBe("new-uuid-456");
|
||||
expect(secondSession.sessionId).not.toBe(firstSessionId);
|
||||
expect(secondSession.title).toBe("Untitled Session");
|
||||
expect(secondSession.history).toEqual([]);
|
||||
});
|
||||
|
||||
it("should create a new session with provided history", () => {
|
||||
const history: ChatHistoryItem[] = [
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "You are a helpful assistant",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(uuidv4).mockReturnValue("new-uuid-789" as any);
|
||||
|
||||
const session = startNewSession(history);
|
||||
|
||||
expect(session.sessionId).toBe("new-uuid-789");
|
||||
expect(session.history).toBe(history);
|
||||
});
|
||||
|
||||
it("should set the new session as current", () => {
|
||||
const originalSession = createSession();
|
||||
|
||||
vi.mocked(uuidv4).mockReturnValue("new-session-id" as any);
|
||||
|
||||
const newSession = startNewSession();
|
||||
const currentSession = getCurrentSession();
|
||||
|
||||
expect(currentSession).toBe(newSession);
|
||||
expect(currentSession).not.toBe(originalSession);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,11 +6,12 @@ import type { ChatHistoryItem, Session, SessionMetadata } from "core/index.js";
|
|||
import historyManager from "core/util/history.js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { DEFAULT_SESSION_TITLE } from "./constants/session.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
// Re-export SessionMetadata for external consumers
|
||||
export type { SessionMetadata };
|
||||
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
// 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.
|
||||
|
|
@ -31,8 +32,10 @@ function getSessionDir(): string {
|
|||
return sessionDir;
|
||||
}
|
||||
|
||||
const homeDir = os.homedir();
|
||||
const sessionDir = path.join(homeDir, ".continue", "sessions");
|
||||
// Use CONTINUE_GLOBAL_DIR if set (for testing)
|
||||
const continueHome =
|
||||
process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue");
|
||||
const sessionDir = path.join(continueHome, "sessions");
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if (!fs.existsSync(sessionDir)) {
|
||||
|
|
@ -67,9 +70,14 @@ class SessionManager {
|
|||
|
||||
getCurrentSession(): Session {
|
||||
if (!this.currentSession) {
|
||||
// Use test session ID for testing consistency
|
||||
const sessionId = process.env.CONTINUE_CLI_TEST_SESSION_ID
|
||||
? process.env.CONTINUE_CLI_TEST_SESSION_ID
|
||||
: uuidv4();
|
||||
|
||||
this.currentSession = {
|
||||
sessionId: uuidv4(),
|
||||
title: "Untitled Session",
|
||||
sessionId,
|
||||
title: DEFAULT_SESSION_TITLE,
|
||||
workspaceDirectory: process.cwd(),
|
||||
history: [],
|
||||
};
|
||||
|
|
@ -187,7 +195,7 @@ export function loadSession(): Session | null {
|
|||
export function createSession(history: ChatHistoryItem[] = []): Session {
|
||||
const session: Session = {
|
||||
sessionId: uuidv4(),
|
||||
title: "Untitled Session",
|
||||
title: DEFAULT_SESSION_TITLE,
|
||||
workspaceDirectory: process.cwd(),
|
||||
history,
|
||||
};
|
||||
|
|
@ -265,7 +273,7 @@ function getSessionMetadataWithPreview(
|
|||
|
||||
return {
|
||||
sessionId: sessionData.sessionId,
|
||||
title: sessionData.title || "Untitled Session",
|
||||
title: sessionData.title || DEFAULT_SESSION_TITLE,
|
||||
dateCreated: stats.birthtime.toISOString(),
|
||||
workspaceDirectory: sessionData.workspaceDirectory || "",
|
||||
firstUserMessage,
|
||||
|
|
@ -347,3 +355,24 @@ export function updateSessionTitle(title: string): void {
|
|||
export function getCurrentSession(): Session {
|
||||
return SessionManager.getInstance().getCurrentSession();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new session with a new sessionId
|
||||
*/
|
||||
export function startNewSession(history: ChatHistoryItem[] = []): Session {
|
||||
const manager = SessionManager.getInstance();
|
||||
|
||||
// Clear the current session from memory (don't delete the file)
|
||||
manager.clear();
|
||||
|
||||
// Create a new session with a new sessionId
|
||||
const newSession: Session = {
|
||||
sessionId: uuidv4(),
|
||||
title: DEFAULT_SESSION_TITLE,
|
||||
workspaceDirectory: process.cwd(),
|
||||
history,
|
||||
};
|
||||
|
||||
manager.setSession(newSession);
|
||||
return newSession;
|
||||
}
|
||||
|
|
|
|||
139
extensions/cli/src/slashCommands.info.test.ts
Normal file
139
extensions/cli/src/slashCommands.info.test.ts
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import * as workosModule from "./auth/workos.js";
|
||||
import { services } from "./services/index.js";
|
||||
import * as sessionModule from "./session.js";
|
||||
import { handleSlashCommands } from "./slashCommands.js";
|
||||
import { posthogService } from "./telemetry/posthogService.js";
|
||||
import * as versionModule from "./version.js";
|
||||
|
||||
// Mock all dependencies
|
||||
vi.mock("./auth/workos.js");
|
||||
vi.mock("./version.js");
|
||||
vi.mock("./session.js");
|
||||
vi.mock("./telemetry/posthogService.js");
|
||||
|
||||
vi.mock("./services/index.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("./services/index.js")>();
|
||||
return {
|
||||
...actual,
|
||||
services: {
|
||||
config: {
|
||||
getState: vi.fn(),
|
||||
},
|
||||
model: {
|
||||
getModelInfo: vi.fn(),
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
describe("handleSlashCommands - /info", () => {
|
||||
const mockAssistant = {
|
||||
prompts: [],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock process.cwd
|
||||
vi.spyOn(process, "cwd").mockReturnValue("/test/working/directory");
|
||||
|
||||
// Mock posthog
|
||||
vi.mocked(posthogService.capture).mockReturnValue(Promise.resolve());
|
||||
|
||||
// Mock version
|
||||
vi.mocked(versionModule.getVersion).mockReturnValue("1.2.3");
|
||||
|
||||
// Mock session
|
||||
vi.mocked(sessionModule.getSessionFilePath).mockReturnValue(
|
||||
"/test/session.json",
|
||||
);
|
||||
});
|
||||
|
||||
it("should include version and working directory in output", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockReturnValue(false);
|
||||
|
||||
// Mock config service
|
||||
const mockConfigState = {
|
||||
config: { name: "test-config", version: "1.0.0" } as any,
|
||||
configPath: "/test/config.yaml",
|
||||
};
|
||||
vi.mocked(services.config.getState).mockReturnValue(mockConfigState);
|
||||
vi.mocked(services.model.getModelInfo).mockReturnValue({
|
||||
provider: "openai",
|
||||
name: "gpt-4",
|
||||
});
|
||||
|
||||
const result = await handleSlashCommands("/info", mockAssistant as any);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.output).toContain("CLI Information:");
|
||||
expect(result?.output).toContain("Version: 1.2.3");
|
||||
expect(result?.output).toContain(
|
||||
"Working Directory: /test/working/directory",
|
||||
);
|
||||
expect(result?.output).toContain("Configuration:");
|
||||
expect(result?.output).toContain("Model: gpt-4");
|
||||
expect(result?.exit).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle authenticated user info", async () => {
|
||||
// Mock auth as authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(workosModule.loadAuthConfig).mockReturnValue({
|
||||
userEmail: "test@example.com",
|
||||
userId: "test-user",
|
||||
} as any);
|
||||
vi.mocked(workosModule.isAuthenticatedConfig).mockReturnValue(true);
|
||||
|
||||
// Mock config service
|
||||
const mockConfigState = {
|
||||
config: { name: "test-config", version: "1.0.0" } as any,
|
||||
configPath: "/test/config.yaml",
|
||||
};
|
||||
vi.mocked(services.config.getState).mockReturnValue(mockConfigState);
|
||||
vi.mocked(services.model.getModelInfo).mockReturnValue({
|
||||
provider: "anthropic",
|
||||
name: "claude-3-sonnet",
|
||||
});
|
||||
|
||||
const result = await handleSlashCommands("/info", mockAssistant as any);
|
||||
|
||||
expect(result?.output).toContain("Authentication:");
|
||||
expect(result?.output).toContain("Email: test@example.com");
|
||||
expect(result?.output).toContain("Model: claude-3-sonnet");
|
||||
});
|
||||
|
||||
it("should handle missing model info gracefully", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockReturnValue(false);
|
||||
|
||||
// Mock config service with no model info
|
||||
const mockConfigState = {
|
||||
config: { name: "test-config", version: "1.0.0" } as any,
|
||||
configPath: "/test/config.yaml",
|
||||
};
|
||||
vi.mocked(services.config.getState).mockReturnValue(mockConfigState);
|
||||
vi.mocked(services.model.getModelInfo).mockReturnValue(null);
|
||||
|
||||
const result = await handleSlashCommands("/info", mockAssistant as any);
|
||||
|
||||
expect(result?.output).toContain("Model: Not available");
|
||||
});
|
||||
|
||||
it("should handle config service error", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockReturnValue(false);
|
||||
|
||||
// Mock config service throwing error
|
||||
vi.mocked(services.config.getState).mockImplementation(() => {
|
||||
throw new Error("Service not available");
|
||||
});
|
||||
|
||||
const result = await handleSlashCommands("/info", mockAssistant as any);
|
||||
|
||||
expect(result?.output).toContain("Configuration service not available");
|
||||
});
|
||||
});
|
||||
|
|
@ -44,11 +44,30 @@ vi.mock("./commands/commands.js", () => ({
|
|||
getAllSlashCommands: vi.fn(() => []),
|
||||
}));
|
||||
|
||||
// Mock logger to avoid file system operations
|
||||
vi.mock("./util/logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock env.js to avoid file operations
|
||||
vi.mock("./env.js", () => ({
|
||||
env: {
|
||||
continueHome: "/home/test/.continue",
|
||||
appUrl: "https://hub.continue.dev",
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock os and path
|
||||
vi.mock("os", () => ({
|
||||
default: {
|
||||
homedir: vi.fn(() => "/home/test"),
|
||||
},
|
||||
homedir: vi.fn(() => "/home/test"),
|
||||
}));
|
||||
|
||||
vi.mock("path", () => ({
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
|
|||
import { getSessionFilePath } from "./session.js";
|
||||
import { posthogService } from "./telemetry/posthogService.js";
|
||||
import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
|
||||
import { getVersion } from "./version.js";
|
||||
|
||||
type CommandHandler = (
|
||||
args: string[],
|
||||
|
|
@ -102,22 +103,33 @@ async function handleInfo() {
|
|||
|
||||
const infoLines = [];
|
||||
|
||||
// Version and working directory info
|
||||
const version = getVersion();
|
||||
const cwd = process.cwd();
|
||||
|
||||
infoLines.push(chalk.white("CLI Information:"));
|
||||
infoLines.push(` Version: ${chalk.green(version)}`);
|
||||
infoLines.push(` Working Directory: ${chalk.blue(cwd)}`);
|
||||
|
||||
// Auth info
|
||||
if (isAuthenticated()) {
|
||||
const config = loadAuthConfig();
|
||||
if (config && isAuthenticatedConfig(config)) {
|
||||
const email = config.userEmail || config.userId;
|
||||
const org = "(no org)"; // Organization info not available in AuthenticatedConfig
|
||||
infoLines.push("");
|
||||
infoLines.push(chalk.white("Authentication:"));
|
||||
infoLines.push(` Email: ${chalk.green(email)}`);
|
||||
infoLines.push(` Organization: ${chalk.cyan(org)}`);
|
||||
} else {
|
||||
infoLines.push("");
|
||||
infoLines.push(chalk.white("Authentication:"));
|
||||
infoLines.push(
|
||||
` ${chalk.yellow("Authenticated via environment variable")}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
infoLines.push("");
|
||||
infoLines.push(chalk.white("Authentication:"));
|
||||
infoLines.push(` ${chalk.red("Not logged in")}`);
|
||||
}
|
||||
|
|
@ -135,6 +147,18 @@ async function handleInfo() {
|
|||
if (configState.configPath) {
|
||||
infoLines.push(` Path: ${chalk.blue(configState.configPath)}`);
|
||||
}
|
||||
|
||||
// Add current model info
|
||||
try {
|
||||
const modelInfo = services.model?.getModelInfo();
|
||||
if (modelInfo) {
|
||||
infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`);
|
||||
} else {
|
||||
infoLines.push(` Model: ${chalk.red("Not available")}`);
|
||||
}
|
||||
} catch {
|
||||
infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`);
|
||||
}
|
||||
} catch {
|
||||
infoLines.push("");
|
||||
infoLines.push(chalk.white("Configuration:"));
|
||||
|
|
|
|||
224
extensions/cli/src/stream/handleToolCalls.ts
Normal file
224
extensions/cli/src/stream/handleToolCalls.ts
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
import type { ChatHistoryItem, ToolStatus } from "core/index.js";
|
||||
import { stripImages } from "core/util/messageContent.js";
|
||||
import { createHistoryItem } from "core/util/messageConversion.js";
|
||||
import type { ChatCompletionTool } from "openai/resources.mjs";
|
||||
|
||||
import { filterExcludedTools } from "../permissions/index.js";
|
||||
import {
|
||||
getServiceSync,
|
||||
MCPServiceState,
|
||||
MCPTool,
|
||||
SERVICE_NAMES,
|
||||
} from "../services/index.js";
|
||||
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
|
||||
import { getAllBuiltinTools, ToolCall } from "../tools/index.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import {
|
||||
executeStreamedToolCalls,
|
||||
preprocessStreamedToolCalls,
|
||||
} from "./streamChatResponse.helpers.js";
|
||||
import { StreamCallbacks } from "./streamChatResponse.types.js";
|
||||
|
||||
export async function handleToolCalls(
|
||||
toolCalls: ToolCall[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
content: string,
|
||||
callbacks: StreamCallbacks | undefined,
|
||||
isHeadless: boolean,
|
||||
): Promise<boolean> {
|
||||
if (toolCalls.length === 0) {
|
||||
if (content) {
|
||||
chatHistory.push(
|
||||
createHistoryItem({
|
||||
role: "assistant",
|
||||
content,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create tool call states for the ChatHistoryItem
|
||||
const toolCallStates = toolCalls.map((tc) => ({
|
||||
toolCallId: tc.id,
|
||||
toolCall: {
|
||||
id: tc.id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.name,
|
||||
arguments: JSON.stringify(tc.arguments),
|
||||
},
|
||||
},
|
||||
status: "generated" as ToolStatus,
|
||||
parsedArgs: tc.arguments,
|
||||
}));
|
||||
|
||||
// Create assistant message with tool calls
|
||||
const assistantMessage = {
|
||||
role: "assistant" as const,
|
||||
content: content || "",
|
||||
toolCalls: toolCalls.map((tc) => ({
|
||||
id: tc.id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.name,
|
||||
arguments: JSON.stringify(tc.arguments),
|
||||
},
|
||||
})),
|
||||
};
|
||||
|
||||
chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
|
||||
|
||||
// First preprocess the tool calls
|
||||
const { preprocessedCalls, errorChatEntries } =
|
||||
await preprocessStreamedToolCalls(toolCalls, callbacks);
|
||||
|
||||
// Add any preprocessing errors to chat history
|
||||
// Convert error entries from OpenAI format to ChatHistoryItem format
|
||||
errorChatEntries.forEach((errorEntry) => {
|
||||
chatHistory.push(
|
||||
createHistoryItem({
|
||||
role: "tool",
|
||||
content: stripImages(errorEntry.content) || "",
|
||||
toolCallId: errorEntry.tool_call_id,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Execute the valid preprocessed tool calls
|
||||
const { chatHistoryEntries: toolResults, hasRejection } =
|
||||
await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless);
|
||||
|
||||
if (isHeadless && hasRejection) {
|
||||
logger.debug(
|
||||
"Tool call rejected in headless mode - returning current content",
|
||||
);
|
||||
return true; // Signal early return needed
|
||||
}
|
||||
|
||||
// Convert tool results from OpenAI format to ChatHistoryItem format
|
||||
// and add them to the chat history
|
||||
toolResults.forEach((toolResult) => {
|
||||
// Find the corresponding tool call state to update
|
||||
const lastAssistantIndex = chatHistory.findLastIndex(
|
||||
(item) => item.message.role === "assistant" && item.toolCallStates,
|
||||
);
|
||||
|
||||
if (
|
||||
lastAssistantIndex >= 0 &&
|
||||
chatHistory[lastAssistantIndex].toolCallStates
|
||||
) {
|
||||
const toolState = chatHistory[lastAssistantIndex].toolCallStates.find(
|
||||
(ts) => ts.toolCallId === toolResult.tool_call_id,
|
||||
);
|
||||
|
||||
if (toolState) {
|
||||
toolState.status = hasRejection ? "canceled" : "done";
|
||||
toolState.output = [
|
||||
{
|
||||
content:
|
||||
typeof toolResult.content === "string" ? toolResult.content : "",
|
||||
name: `Tool Result`,
|
||||
description: "Tool execution result",
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function getAllTools() {
|
||||
// Get all available tool names
|
||||
const allBuiltinTools = getAllBuiltinTools();
|
||||
const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
|
||||
|
||||
let mcpTools: MCPTool[] = [];
|
||||
let mcpToolNames: string[] = [];
|
||||
const mcpServiceResult = getServiceSync<MCPServiceState>(SERVICE_NAMES.MCP);
|
||||
if (mcpServiceResult.state === "ready") {
|
||||
mcpTools = mcpServiceResult?.value?.tools ?? [];
|
||||
mcpToolNames = mcpTools.map((t) => t.name);
|
||||
} else {
|
||||
// MCP is lazy
|
||||
// throw new Error("MCP Service not initialized");
|
||||
}
|
||||
|
||||
const allToolNames = [...builtinToolNames, ...mcpToolNames];
|
||||
|
||||
// Check if the ToolPermissionService is ready
|
||||
const permissionsServiceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
|
||||
let allowedToolNames: string[];
|
||||
if (
|
||||
permissionsServiceResult.state === "ready" &&
|
||||
permissionsServiceResult.value
|
||||
) {
|
||||
// Filter out excluded tools based on permissions
|
||||
allowedToolNames = filterExcludedTools(
|
||||
allToolNames,
|
||||
permissionsServiceResult.value.permissions,
|
||||
);
|
||||
} else {
|
||||
// Service not ready - this is a critical error since tools should only be
|
||||
// requested after services are properly initialized
|
||||
logger.error(
|
||||
"ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue",
|
||||
);
|
||||
throw new Error(
|
||||
"ToolPermissionService not initialized. Services must be initialized before requesting tools.",
|
||||
);
|
||||
}
|
||||
|
||||
const allowedToolNamesSet = new Set(allowedToolNames);
|
||||
|
||||
// Filter builtin tools
|
||||
const allowedBuiltinTools = allBuiltinTools.filter((tool) =>
|
||||
allowedToolNamesSet.has(tool.name),
|
||||
);
|
||||
|
||||
const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: Object.fromEntries(
|
||||
Object.entries(tool.parameters).map(([key, param]) => [
|
||||
key,
|
||||
{
|
||||
type: param.type,
|
||||
description: param.description,
|
||||
items: param.items,
|
||||
},
|
||||
]),
|
||||
),
|
||||
required: Object.entries(tool.parameters)
|
||||
.filter(([_, param]) => param.required)
|
||||
.map(([key, _]) => key),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
// Add filtered MCP tools
|
||||
const allowedMcpTools = mcpTools.filter((tool) =>
|
||||
allowedToolNamesSet.has(tool.name),
|
||||
);
|
||||
|
||||
allTools.push(
|
||||
...allowedMcpTools.map((tool) => ({
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: tool.inputSchema,
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
return allTools;
|
||||
}
|
||||
|
|
@ -1,15 +1,15 @@
|
|||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { convertToUnifiedHistory } from "core/util/messageConversion.js";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("./compaction.js", () => ({
|
||||
vi.mock("../compaction.js", () => ({
|
||||
compactChatHistory: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./session.js", () => ({
|
||||
vi.mock("../session.js", () => ({
|
||||
createSession: vi.fn((history) => ({
|
||||
sessionId: "test",
|
||||
title: "Test",
|
||||
|
|
@ -20,16 +20,16 @@ vi.mock("./session.js", () => ({
|
|||
updateSessionHistory: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./util/tokenizer.js", () => ({
|
||||
vi.mock("../util/tokenizer.js", () => ({
|
||||
shouldAutoCompact: vi.fn(),
|
||||
getAutoCompactMessage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./util/formatError.js", () => ({
|
||||
vi.mock("../util/formatError.js", () => ({
|
||||
formatError: vi.fn((error) => error.message || String(error)),
|
||||
}));
|
||||
|
||||
vi.mock("./util/logger.js", () => ({
|
||||
vi.mock("../util/logger.js", () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
|
|
@ -69,8 +69,9 @@ describe("handleAutoCompaction", () => {
|
|||
});
|
||||
|
||||
it("should return original history when auto-compaction is not needed", async () => {
|
||||
const { shouldAutoCompact } = await import("./util/tokenizer.js");
|
||||
vi.mocked(shouldAutoCompact).mockReturnValue(false);
|
||||
const { shouldAutoCompact } = await import("../util/tokenizer.js");
|
||||
const mockedShouldAutoCompact = shouldAutoCompact as any;
|
||||
mockedShouldAutoCompact.mockReturnValue(false);
|
||||
|
||||
const result = await handleAutoCompaction(
|
||||
mockChatHistory,
|
||||
|
|
@ -90,10 +91,10 @@ describe("handleAutoCompaction", () => {
|
|||
|
||||
it("should perform auto-compaction when context limit is approaching", async () => {
|
||||
const { shouldAutoCompact, getAutoCompactMessage } = await import(
|
||||
"./util/tokenizer.js"
|
||||
"../util/tokenizer.js"
|
||||
);
|
||||
const { compactChatHistory } = await import("./compaction.js");
|
||||
const { updateSessionHistory } = await import("./session.js");
|
||||
const { compactChatHistory } = await import("../compaction.js");
|
||||
const { updateSessionHistory } = await import("../session.js");
|
||||
|
||||
vi.mocked(shouldAutoCompact).mockReturnValue(true);
|
||||
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
|
||||
|
|
@ -113,7 +114,8 @@ describe("handleAutoCompaction", () => {
|
|||
compactionContent: "Conversation summary...",
|
||||
};
|
||||
|
||||
vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult);
|
||||
const mockedCompactChatHistory = compactChatHistory as any;
|
||||
mockedCompactChatHistory.mockResolvedValue(mockCompactionResult);
|
||||
|
||||
const mockCallbacks = {
|
||||
onSystemMessage: vi.fn(),
|
||||
|
|
@ -157,10 +159,10 @@ describe("handleAutoCompaction", () => {
|
|||
|
||||
it("should handle compaction errors gracefully", async () => {
|
||||
const { shouldAutoCompact, getAutoCompactMessage } = await import(
|
||||
"./util/tokenizer.js"
|
||||
"../util/tokenizer.js"
|
||||
);
|
||||
const { compactChatHistory } = await import("./compaction.js");
|
||||
const { logger } = await import("./util/logger.js");
|
||||
const { compactChatHistory } = await import("../compaction.js");
|
||||
const { logger } = await import("../util/logger.js");
|
||||
|
||||
vi.mocked(shouldAutoCompact).mockReturnValue(true);
|
||||
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
|
||||
|
|
@ -200,9 +202,9 @@ describe("handleAutoCompaction", () => {
|
|||
|
||||
it("should not call system message callback in headless mode", async () => {
|
||||
const { shouldAutoCompact, getAutoCompactMessage } = await import(
|
||||
"./util/tokenizer.js"
|
||||
"../util/tokenizer.js"
|
||||
);
|
||||
const { compactChatHistory } = await import("./compaction.js");
|
||||
const { compactChatHistory } = await import("../compaction.js");
|
||||
|
||||
vi.mocked(shouldAutoCompact).mockReturnValue(true);
|
||||
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
|
||||
|
|
@ -215,7 +217,8 @@ describe("handleAutoCompaction", () => {
|
|||
compactionContent: "Summary",
|
||||
};
|
||||
|
||||
vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult);
|
||||
const mockedCompactChatHistory = compactChatHistory as any;
|
||||
mockedCompactChatHistory.mockResolvedValue(mockCompactionResult);
|
||||
|
||||
const mockCallbacks = {
|
||||
onSystemMessage: vi.fn(),
|
||||
|
|
@ -3,11 +3,11 @@ import { BaseLlmApi } from "@continuedev/openai-adapters";
|
|||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import React from "react";
|
||||
|
||||
import { compactChatHistory } from "./compaction.js";
|
||||
import { updateSessionHistory } from "./session.js";
|
||||
import { formatError } from "./util/formatError.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js";
|
||||
import { compactChatHistory } from "../compaction.js";
|
||||
import { updateSessionHistory } from "../session.js";
|
||||
import { formatError } from "../util/formatError.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
import { getAutoCompactMessage, shouldAutoCompact } from "../util/tokenizer.js";
|
||||
|
||||
interface AutoCompactionCallbacks {
|
||||
// For streaming mode
|
||||
|
|
@ -5,8 +5,9 @@ import {
|
|||
initializeServices,
|
||||
SERVICE_NAMES,
|
||||
serviceContainer,
|
||||
} from "./services/index.js";
|
||||
import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
|
||||
} from "../services/index.js";
|
||||
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
|
||||
|
||||
import { getAllTools } from "./streamChatResponse.js";
|
||||
|
||||
describe("getAllTools - Tool Filtering", () => {
|
||||
|
|
@ -2,21 +2,22 @@
|
|||
|
||||
import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs";
|
||||
|
||||
import { checkToolPermission } from "./permissions/permissionChecker.js";
|
||||
import { toolPermissionManager } from "./permissions/permissionManager.js";
|
||||
import { ToolCallRequest } from "./permissions/types.js";
|
||||
import { StreamCallbacks } from "./streamChatResponse.types.js";
|
||||
import { telemetryService } from "./telemetry/telemetryService.js";
|
||||
import { calculateTokenCost } from "./telemetry/utils.js";
|
||||
import { checkToolPermission } from "../permissions/permissionChecker.js";
|
||||
import { toolPermissionManager } from "../permissions/permissionManager.js";
|
||||
import { ToolCallRequest } from "../permissions/types.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { calculateTokenCost } from "../telemetry/utils.js";
|
||||
import {
|
||||
executeToolCall,
|
||||
getAllBuiltinTools,
|
||||
getAvailableTools,
|
||||
Tool,
|
||||
validateToolCallArgsPresent,
|
||||
} from "./tools/index.js";
|
||||
import { PreprocessedToolCall, ToolCall } from "./tools/types.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
} from "../tools/index.js";
|
||||
import { PreprocessedToolCall, ToolCall } from "../tools/types.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { StreamCallbacks } from "./streamChatResponse.types.js";
|
||||
|
||||
// Helper function to handle permission denied
|
||||
export function handlePermissionDenied(
|
||||
|
|
@ -1,12 +1,13 @@
|
|||
import { describe, expect, test, vi, beforeEach } from "vitest";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
serviceContainer,
|
||||
SERVICE_NAMES,
|
||||
initializeServices,
|
||||
} from "./services/index.js";
|
||||
import { modeService } from "./services/ModeService.js";
|
||||
import { getAllTools } from "./streamChatResponse.js";
|
||||
serviceContainer,
|
||||
} from "../services/index.js";
|
||||
import { modeService } from "../services/ModeService.js";
|
||||
|
||||
import { getAllTools } from "./handleToolCalls.js";
|
||||
|
||||
describe("streamChatResponse - Mode Switch During Streaming", () => {
|
||||
beforeEach(async () => {
|
||||
|
|
@ -4,17 +4,18 @@ import type { ChatHistoryItem } from "core/index.js";
|
|||
import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { toolPermissionManager } from "./permissions/permissionManager.js";
|
||||
import { toolPermissionManager } from "../permissions/permissionManager.js";
|
||||
import { ToolCall } from "../tools/index.js";
|
||||
import { readFileTool } from "../tools/readFile.js";
|
||||
import { searchCodeTool } from "../tools/searchCode.js";
|
||||
import { PreprocessedToolCall } from "../tools/types.js";
|
||||
import { writeFileTool } from "../tools/writeFile.js";
|
||||
|
||||
import {
|
||||
preprocessStreamedToolCalls,
|
||||
executeStreamedToolCalls,
|
||||
preprocessStreamedToolCalls,
|
||||
} from "./streamChatResponse.helpers.js";
|
||||
import { processStreamingResponse } from "./streamChatResponse.js";
|
||||
import { ToolCall } from "./tools/index.js";
|
||||
import { readFileTool } from "./tools/readFile.js";
|
||||
import { searchCodeTool } from "./tools/searchCode.js";
|
||||
import { PreprocessedToolCall } from "./tools/types.js";
|
||||
import { writeFileTool } from "./tools/writeFile.js";
|
||||
|
||||
// Test the chunk processing logic that was identified as buggy
|
||||
describe("processStreamingResponse - content preservation", () => {
|
||||
|
|
@ -438,7 +439,7 @@ describe.skip("preprocessStreamedToolCalls", () => {
|
|||
|
||||
it("handles tool preprocessing errors correctly", async () => {
|
||||
// Set the spy to throw an error
|
||||
const toolsModule = await import("./tools/index.js");
|
||||
const toolsModule = await import("../tools/index.js");
|
||||
vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce(
|
||||
() => {
|
||||
throw new Error("Missing required argument");
|
||||
|
|
@ -510,12 +511,12 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
|
||||
it("executes tool calls with allowed permissions", async () => {
|
||||
// Setup spies instead of mocks
|
||||
const permissionsModule = await import("./permissions/index.js");
|
||||
const permissionsModule = await import("../permissions/index.js");
|
||||
vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
|
||||
permission: "allow",
|
||||
});
|
||||
|
||||
const toolsModule = await import("./tools/index.js");
|
||||
const toolsModule = await import("../tools/index.js");
|
||||
const mockedExecuteToolCall = vi
|
||||
.spyOn(toolsModule, "executeToolCall")
|
||||
.mockResolvedValue("Tool execution successful");
|
||||
|
|
@ -559,7 +560,7 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
|
||||
it("handles permission denied correctly", async () => {
|
||||
// Setup permission to ask
|
||||
const permissionsModule = await import("./permissions/index.js");
|
||||
const permissionsModule = await import("../permissions/index.js");
|
||||
vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
|
||||
permission: "ask",
|
||||
});
|
||||
|
|
@ -646,12 +647,12 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
|
||||
it("handles tool execution errors", async () => {
|
||||
// Setup spies
|
||||
const permissionsModule = await import("./permissions/index.js");
|
||||
const permissionsModule = await import("../permissions/index.js");
|
||||
vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
|
||||
permission: "allow",
|
||||
});
|
||||
|
||||
const toolsModule = await import("./tools/index.js");
|
||||
const toolsModule = await import("../tools/index.js");
|
||||
vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue(
|
||||
new Error("Execution failed"),
|
||||
);
|
||||
|
|
@ -1,25 +1,27 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import type { ChatHistoryItem, ToolStatus } from "core/index.js";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { convertFromUnifiedHistoryWithSystemMessage } from "core/util/messageConversion.js";
|
||||
import * as dotenv from "dotenv";
|
||||
import type { ChatCompletionTool } from "openai/resources.mjs";
|
||||
import type {
|
||||
ChatCompletionMessageParam,
|
||||
ChatCompletionTool,
|
||||
} from "openai/resources.mjs";
|
||||
|
||||
import { getServiceSync, SERVICE_NAMES } from "../services/index.js";
|
||||
import { systemMessageService } from "../services/SystemMessageService.js";
|
||||
import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { ToolCall } from "../tools/index.js";
|
||||
import {
|
||||
convertFromUnifiedHistory,
|
||||
createHistoryItem,
|
||||
} from "./messageConversion.js";
|
||||
import { filterExcludedTools } from "./permissions/index.js";
|
||||
import {
|
||||
getServiceSync,
|
||||
MCPServiceState,
|
||||
MCPTool,
|
||||
SERVICE_NAMES,
|
||||
} from "./services/index.js";
|
||||
import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
|
||||
chatCompletionStreamWithBackoff,
|
||||
withExponentialBackoff,
|
||||
} from "../util/exponentialBackoff.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { getAllTools, handleToolCalls } from "./handleToolCalls.js";
|
||||
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
|
||||
import {
|
||||
executeStreamedToolCalls,
|
||||
preprocessStreamedToolCalls,
|
||||
processChunkContent,
|
||||
processToolCallDelta,
|
||||
recordStreamTelemetry,
|
||||
|
|
@ -29,13 +31,6 @@ import {
|
|||
getDefaultCompletionOptions,
|
||||
StreamCallbacks,
|
||||
} from "./streamChatResponse.types.js";
|
||||
import { telemetryService } from "./telemetry/telemetryService.js";
|
||||
import { getAllBuiltinTools, ToolCall } from "./tools/index.js";
|
||||
import {
|
||||
chatCompletionStreamWithBackoff,
|
||||
withExponentialBackoff,
|
||||
} from "./util/exponentialBackoff.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
|
|
@ -69,208 +64,6 @@ function handleContentDisplay(
|
|||
}
|
||||
}
|
||||
|
||||
async function handleToolCalls(
|
||||
toolCalls: ToolCall[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
content: string,
|
||||
callbacks: StreamCallbacks | undefined,
|
||||
isHeadless: boolean,
|
||||
): Promise<boolean> {
|
||||
if (toolCalls.length === 0) {
|
||||
if (content) {
|
||||
chatHistory.push(
|
||||
createHistoryItem({
|
||||
role: "assistant",
|
||||
content,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create tool call states for the ChatHistoryItem
|
||||
const toolCallStates = toolCalls.map((tc) => ({
|
||||
toolCallId: tc.id,
|
||||
toolCall: {
|
||||
id: tc.id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.name,
|
||||
arguments: JSON.stringify(tc.arguments),
|
||||
},
|
||||
},
|
||||
status: "generated" as ToolStatus,
|
||||
parsedArgs: tc.arguments,
|
||||
}));
|
||||
|
||||
// Create assistant message with tool calls
|
||||
const assistantMessage = {
|
||||
role: "assistant" as const,
|
||||
content: content || "",
|
||||
toolCalls: toolCalls.map((tc) => ({
|
||||
id: tc.id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.name,
|
||||
arguments: JSON.stringify(tc.arguments),
|
||||
},
|
||||
})),
|
||||
};
|
||||
|
||||
chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
|
||||
|
||||
// First preprocess the tool calls
|
||||
const { preprocessedCalls, errorChatEntries } =
|
||||
await preprocessStreamedToolCalls(toolCalls, callbacks);
|
||||
|
||||
// Add any preprocessing errors to chat history
|
||||
// Convert error entries from OpenAI format to ChatHistoryItem format
|
||||
errorChatEntries.forEach((errorEntry) => {
|
||||
chatHistory.push(
|
||||
createHistoryItem({
|
||||
role: "assistant",
|
||||
content: errorEntry.content || "",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Execute the valid preprocessed tool calls
|
||||
const { chatHistoryEntries: toolResults, hasRejection } =
|
||||
await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless);
|
||||
|
||||
if (isHeadless && hasRejection) {
|
||||
logger.debug(
|
||||
"Tool call rejected in headless mode - returning current content",
|
||||
);
|
||||
return true; // Signal early return needed
|
||||
}
|
||||
|
||||
// Convert tool results from OpenAI format to ChatHistoryItem format
|
||||
// and add them to the chat history
|
||||
toolResults.forEach((toolResult) => {
|
||||
// Find the corresponding tool call state to update
|
||||
const lastAssistantIndex = chatHistory.findLastIndex(
|
||||
(item) => item.message.role === "assistant" && item.toolCallStates,
|
||||
);
|
||||
|
||||
if (
|
||||
lastAssistantIndex >= 0 &&
|
||||
chatHistory[lastAssistantIndex].toolCallStates
|
||||
) {
|
||||
const toolState = chatHistory[lastAssistantIndex].toolCallStates.find(
|
||||
(ts) => ts.toolCallId === toolResult.tool_call_id,
|
||||
);
|
||||
|
||||
if (toolState) {
|
||||
toolState.status = hasRejection ? "canceled" : "done";
|
||||
toolState.output = [
|
||||
{
|
||||
content:
|
||||
typeof toolResult.content === "string" ? toolResult.content : "",
|
||||
name: `Tool Result`,
|
||||
description: "Tool execution result",
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function getAllTools() {
|
||||
// Get all available tool names
|
||||
const allBuiltinTools = getAllBuiltinTools();
|
||||
const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
|
||||
|
||||
let mcpTools: MCPTool[] = [];
|
||||
let mcpToolNames: string[] = [];
|
||||
const mcpServiceResult = getServiceSync<MCPServiceState>(SERVICE_NAMES.MCP);
|
||||
if (mcpServiceResult.state === "ready") {
|
||||
mcpTools = mcpServiceResult?.value?.tools ?? [];
|
||||
mcpToolNames = mcpTools.map((t) => t.name);
|
||||
} else {
|
||||
// MCP is lazy
|
||||
// throw new Error("MCP Service not initialized");
|
||||
}
|
||||
|
||||
const allToolNames = [...builtinToolNames, ...mcpToolNames];
|
||||
|
||||
// Check if the ToolPermissionService is ready
|
||||
const permissionsServiceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
|
||||
let allowedToolNames: string[];
|
||||
if (
|
||||
permissionsServiceResult.state === "ready" &&
|
||||
permissionsServiceResult.value
|
||||
) {
|
||||
// Filter out excluded tools based on permissions
|
||||
allowedToolNames = filterExcludedTools(
|
||||
allToolNames,
|
||||
permissionsServiceResult.value.permissions,
|
||||
);
|
||||
} else {
|
||||
// Service not ready - this is a critical error since tools should only be
|
||||
// requested after services are properly initialized
|
||||
logger.error(
|
||||
"ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue",
|
||||
);
|
||||
throw new Error(
|
||||
"ToolPermissionService not initialized. Services must be initialized before requesting tools.",
|
||||
);
|
||||
}
|
||||
|
||||
const allowedToolNamesSet = new Set(allowedToolNames);
|
||||
|
||||
// Filter builtin tools
|
||||
const allowedBuiltinTools = allBuiltinTools.filter((tool) =>
|
||||
allowedToolNamesSet.has(tool.name),
|
||||
);
|
||||
|
||||
const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: Object.fromEntries(
|
||||
Object.entries(tool.parameters).map(([key, param]) => [
|
||||
key,
|
||||
{
|
||||
type: param.type,
|
||||
description: param.description,
|
||||
items: param.items,
|
||||
},
|
||||
]),
|
||||
),
|
||||
required: Object.entries(tool.parameters)
|
||||
.filter(([_, param]) => param.required)
|
||||
.map(([key, _]) => key),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
// Add filtered MCP tools
|
||||
const allowedMcpTools = mcpTools.filter((tool) =>
|
||||
allowedToolNamesSet.has(tool.name),
|
||||
);
|
||||
|
||||
allTools.push(
|
||||
...allowedMcpTools.map((tool) => ({
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: tool.inputSchema,
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
return allTools;
|
||||
}
|
||||
|
||||
// Helper function to process a single chunk
|
||||
interface ProcessChunkOptions {
|
||||
chunk: any;
|
||||
|
|
@ -353,7 +146,13 @@ export async function processStreamingResponse(
|
|||
isHeadless,
|
||||
tools,
|
||||
} = options;
|
||||
const openaiChatHistory = convertFromUnifiedHistory(chatHistory);
|
||||
|
||||
// Get fresh system message and inject it
|
||||
const systemMessage = await systemMessageService.getSystemMessage();
|
||||
const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
|
||||
chatHistory,
|
||||
systemMessage,
|
||||
) as ChatCompletionMessageParam[];
|
||||
const requestStartTime = Date.now();
|
||||
|
||||
const streamFactory = async (retryAbortSignal: AbortSignal) => {
|
||||
|
|
@ -601,3 +400,4 @@ export async function streamChatResponse(
|
|||
// Otherwise, return the full response
|
||||
return isHeadless ? finalResponse : fullResponse;
|
||||
}
|
||||
export { getAllTools };
|
||||
|
|
@ -2,7 +2,7 @@ import { CompletionOptions } from "@continuedev/config-yaml";
|
|||
import type { ToolStatus } from "core/index.js";
|
||||
import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs";
|
||||
|
||||
import { ToolCallPreview } from "./tools/types.js";
|
||||
import { ToolCallPreview } from "../tools/types.js";
|
||||
|
||||
export interface StreamCallbacks {
|
||||
onContent?: (content: string) => void;
|
||||
|
|
@ -18,6 +18,8 @@ vi.mock("./args.js", () => ({
|
|||
.mockImplementation((spec: string) => Promise.resolve(spec)),
|
||||
}));
|
||||
|
||||
const PLAN_MODE_STRING = "You are operating in _Plan Mode_";
|
||||
|
||||
describe("constructSystemMessage", () => {
|
||||
it("should return base system message with rules when additionalRules is provided", async () => {
|
||||
const rules = ["These are the rules for the assistant."];
|
||||
|
|
@ -167,7 +169,7 @@ Rule 3: Third rule`;
|
|||
);
|
||||
|
||||
expect(result).toContain("You are an agent in the Continue CLI");
|
||||
expect(result).toContain("PLAN MODE: You are operating in plan mode");
|
||||
expect(result).toContain(PLAN_MODE_STRING);
|
||||
expect(result).toContain(
|
||||
"which means that your goal is to help the user investigate their ideas",
|
||||
);
|
||||
|
|
@ -187,7 +189,7 @@ Rule 3: Third rule`;
|
|||
);
|
||||
|
||||
expect(result).toContain("You are an agent in the Continue CLI");
|
||||
expect(result).not.toContain("PLAN MODE: You are operating in plan mode");
|
||||
expect(result).not.toContain(PLAN_MODE_STRING);
|
||||
expect(result).not.toContain(
|
||||
"which means that your goal is to help the user investigate their ideas",
|
||||
);
|
||||
|
|
@ -197,7 +199,7 @@ Rule 3: Third rule`;
|
|||
const result = await constructSystemMessage();
|
||||
|
||||
expect(result).toContain("You are an agent in the Continue CLI");
|
||||
expect(result).not.toContain("PLAN MODE: You are operating in plan mode");
|
||||
expect(result).not.toContain(PLAN_MODE_STRING);
|
||||
expect(result).not.toContain(
|
||||
"which means that your goal is to help the user investigate their ideas",
|
||||
);
|
||||
|
|
@ -211,7 +213,7 @@ Rule 3: Third rule`;
|
|||
"plan",
|
||||
);
|
||||
|
||||
expect(result).toContain("PLAN MODE: You are operating in plan mode");
|
||||
expect(result).toContain(PLAN_MODE_STRING);
|
||||
expect(result).toContain("read-only tools");
|
||||
expect(result).toContain("write / delete / create files");
|
||||
});
|
||||
|
|
@ -225,7 +227,7 @@ Rule 3: Third rule`;
|
|||
);
|
||||
|
||||
expect(result).toContain("IMPORTANT: You are running in headless mode");
|
||||
expect(result).toContain("PLAN MODE: You are operating in plan mode");
|
||||
expect(result).toContain(PLAN_MODE_STRING);
|
||||
expect(result).toContain(
|
||||
"which means that your goal is to help the user investigate their ideas",
|
||||
);
|
||||
|
|
@ -242,7 +244,7 @@ Rule 3: Third rule`;
|
|||
expect(result).toContain(
|
||||
"IMPORTANT: You are operating in JSON output mode",
|
||||
);
|
||||
expect(result).toContain("PLAN MODE: You are operating in plan mode");
|
||||
expect(result).toContain(PLAN_MODE_STRING);
|
||||
expect(result).toContain(
|
||||
"which means that your goal is to help the user investigate their ideas",
|
||||
);
|
||||
|
|
|
|||
|
|
@ -172,6 +172,12 @@ export async function constructSystemMessage(
|
|||
// Construct the comprehensive system message
|
||||
let systemMessage = baseSystemMessage;
|
||||
|
||||
// Add plan mode specific instructions if in plan mode
|
||||
if (currentMode === "plan") {
|
||||
systemMessage +=
|
||||
'\n<context name="planMode">You are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.</context>\n';
|
||||
}
|
||||
|
||||
// In headless mode, add instructions to be concise and only provide final answers
|
||||
if (headless) {
|
||||
systemMessage += `
|
||||
|
|
@ -191,13 +197,6 @@ Example response format:
|
|||
}`;
|
||||
}
|
||||
|
||||
// Add plan mode specific instructions if in plan mode
|
||||
if (currentMode === "plan") {
|
||||
systemMessage += `
|
||||
|
||||
PLAN MODE: You are operating in plan mode, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files.`;
|
||||
}
|
||||
|
||||
// Add rules section if we have any rules or agent content
|
||||
if (agentContent || processedRules.length > 0) {
|
||||
systemMessage += '\n\n<context name="userRules">';
|
||||
|
|
|
|||
50
extensions/cli/src/tools/ToolCallTitle.tsx
Normal file
50
extensions/cli/src/tools/ToolCallTitle.tsx
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { Text } from "ink";
|
||||
import React from "react";
|
||||
|
||||
import { formatToolArgument } from "./formatters.js";
|
||||
|
||||
import { getToolDisplayName } from "./index.js";
|
||||
|
||||
/**
|
||||
* Formats a tool call with its arguments for display
|
||||
* @param toolName The name of the tool
|
||||
* @param args The tool arguments
|
||||
* @returns A React node with bolded tool name like "<b>ToolName</b>(arg)" or just "<b>ToolName</b>" if no args
|
||||
*/
|
||||
export function ToolCallTitle(props: { toolName: string; args?: any }) {
|
||||
const { toolName, args } = props;
|
||||
|
||||
const displayName = getToolDisplayName(toolName);
|
||||
|
||||
if (!args || Object.keys(args).length === 0) {
|
||||
return <Text bold>{displayName}</Text>;
|
||||
}
|
||||
|
||||
// Get the first argument value if it's a simple one
|
||||
let formattedValue = "";
|
||||
const [key, value] = Object.entries(args)[0];
|
||||
if (
|
||||
key.toLowerCase().includes("path") ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean"
|
||||
) {
|
||||
formattedValue = formatToolArgument(value);
|
||||
} else if (typeof value === "string") {
|
||||
const valueLines = value.split("\n");
|
||||
if (valueLines.length === 1) {
|
||||
formattedValue = formatToolArgument(value);
|
||||
} else {
|
||||
// For multi-line strings, show first line with ellipsis
|
||||
const firstLine = valueLines[0].trim();
|
||||
formattedValue = firstLine
|
||||
? `${formatToolArgument(firstLine)}...`
|
||||
: "...";
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Text>
|
||||
<Text bold>{displayName}</Text>({formattedValue})
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
import { vi } from "vitest";
|
||||
|
||||
import { formatToolArgument } from "./formatters.js";
|
||||
|
||||
import { formatToolCall } from "./index.js";
|
||||
|
||||
describe("formatToolCall", () => {
|
||||
beforeEach(() => {
|
||||
// Mock process.cwd to return a consistent value
|
||||
vi.spyOn(process, "cwd").mockReturnValue("/Users/test/project");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should format tool name without arguments", () => {
|
||||
expect(formatToolCall("Write")).toBe("Write");
|
||||
expect(formatToolCall("Read", {})).toBe("Read");
|
||||
expect(formatToolCall("non_existent_tool", null)).toBe("non_existent_tool");
|
||||
});
|
||||
|
||||
it("should format tool name with relative path argument", () => {
|
||||
expect(formatToolCall("Write", { filepath: "README.md" })).toBe(
|
||||
"Write(README.md)",
|
||||
);
|
||||
expect(formatToolCall("Read", { filepath: "src/index.ts" })).toBe(
|
||||
"Read(src/index.ts)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should convert absolute paths to relative paths", () => {
|
||||
expect(
|
||||
formatToolCall("Write", {
|
||||
filepath: "/Users/test/project/README.md",
|
||||
}),
|
||||
).toBe("Write(README.md)");
|
||||
|
||||
expect(
|
||||
formatToolCall("Read", {
|
||||
filepath: "/Users/test/project/src/components/App.tsx",
|
||||
}),
|
||||
).toBe("Read(src/components/App.tsx)");
|
||||
});
|
||||
|
||||
it("should handle absolute paths outside the project", () => {
|
||||
expect(formatToolCall("Write", { filepath: "/Users/other/file.txt" })).toBe(
|
||||
"Write(../../other/file.txt)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle non-path arguments", () => {
|
||||
expect(formatToolCall("Search", { pattern: "TODO" })).toBe("Search(TODO)");
|
||||
expect(formatToolCall("Search", { pattern: 123 })).toBe("Search(123)");
|
||||
});
|
||||
|
||||
it("should use first argument when multiple are provided", () => {
|
||||
expect(
|
||||
formatToolCall("Write", {
|
||||
filepath: "test.txt",
|
||||
content: "Hello world",
|
||||
}),
|
||||
).toBe("Write(test.txt)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatToolArgument", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(process, "cwd").mockReturnValue("/Users/test/project");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should return empty string for null/undefined", () => {
|
||||
expect(formatToolArgument(null)).toBe("");
|
||||
expect(formatToolArgument(undefined)).toBe("");
|
||||
});
|
||||
|
||||
it("should convert absolute paths to relative", () => {
|
||||
expect(formatToolArgument("/Users/test/project/README.md")).toBe(
|
||||
"README.md",
|
||||
);
|
||||
expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe(
|
||||
"src/index.ts",
|
||||
);
|
||||
});
|
||||
|
||||
it("should preserve relative paths", () => {
|
||||
expect(formatToolArgument("README.md")).toBe("README.md");
|
||||
expect(formatToolArgument("./src/index.ts")).toBe("./src/index.ts");
|
||||
});
|
||||
|
||||
it("should handle non-string values", () => {
|
||||
expect(formatToolArgument(123)).toBe("123");
|
||||
expect(formatToolArgument(true)).toBe("true");
|
||||
expect(formatToolArgument({ key: "value" })).toBe("[object Object]");
|
||||
});
|
||||
});
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { getToolDisplayName, extractToolCalls } from "./index.js";
|
||||
import { extractToolCalls, getToolDisplayName } from "./index.js";
|
||||
|
||||
describe("tools/index utilities", () => {
|
||||
describe("getToolDisplayName", () => {
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
// @ts-ignore
|
||||
import {
|
||||
getServiceSync,
|
||||
MCPServiceState,
|
||||
|
|
@ -11,7 +12,6 @@ import { logger } from "../util/logger.js";
|
|||
import { editTool } from "./edit.js";
|
||||
import { exitTool } from "./exit.js";
|
||||
import { fetchTool } from "./fetch.js";
|
||||
import { formatToolArgument } from "./formatters.js";
|
||||
import { listFilesTool } from "./listFiles.js";
|
||||
import { multiEditTool } from "./multiEdit.js";
|
||||
import { readFileTool } from "./readFile.js";
|
||||
|
|
@ -202,35 +202,3 @@ export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a tool call with its arguments for display
|
||||
* @param toolName The name of the tool
|
||||
* @param args The tool arguments
|
||||
* @returns A formatted string like "ToolName(arg)" or just "ToolName" if no args
|
||||
*/
|
||||
export function formatToolCall(toolName: string, args?: any): string {
|
||||
const displayName = getToolDisplayName(toolName);
|
||||
|
||||
if (!args || Object.keys(args).length === 0) {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
// Get the first argument value if it's a simple one
|
||||
let formattedValue = "";
|
||||
const [key, value] = Object.entries(args)[0];
|
||||
if (
|
||||
key.toLowerCase().includes("path") ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean"
|
||||
) {
|
||||
formattedValue = formatToolArgument(value);
|
||||
} else if (typeof value === "string") {
|
||||
const valueLines = value.split("\n");
|
||||
if (valueLines.length === 1) {
|
||||
formattedValue = formatToolArgument(value);
|
||||
}
|
||||
}
|
||||
|
||||
return `${displayName}(${formattedValue})`;
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
|||
import { Box, Text } from "ink";
|
||||
import React, { useMemo } from "react";
|
||||
|
||||
import { getDisplayableAsciiArt } from "../asciiArt.js";
|
||||
import { MCPService } from "../services/MCPService.js";
|
||||
import { isModelCapable } from "../utils/modelCapability.js";
|
||||
|
||||
|
|
@ -41,6 +42,10 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
|
|||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} paddingY={1}>
|
||||
{/* ASCII Art */}
|
||||
<Text>{getDisplayableAsciiArt()}</Text>
|
||||
<Text> </Text>
|
||||
|
||||
{/* Agent name */}
|
||||
{config && (
|
||||
<Text color="blue">
|
||||
|
|
|
|||
|
|
@ -231,7 +231,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
const { handleConfigSelect, handleModelSelect } = useSelectors(
|
||||
configPath,
|
||||
setChatHistory,
|
||||
resetChatHistory,
|
||||
handleClear,
|
||||
);
|
||||
|
||||
// Session selection handler
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import path from "path";
|
|||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
|
||||
import { getToolDisplayName } from "../tools/index.js";
|
||||
import { getToolDisplayName } from "src/tools/index.js";
|
||||
|
||||
import { ColoredDiff } from "./ColoredDiff.js";
|
||||
import { ChecklistDisplay } from "./components/ChecklistDisplay.js";
|
||||
|
|
|
|||
|
|
@ -386,6 +386,27 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
|
||||
const handleEnterKey = (key: any): boolean => {
|
||||
if (key.return && !key.shift) {
|
||||
// Check for backslash continuation
|
||||
const beforeCursor = textBuffer.text.slice(0, cursorPosition);
|
||||
const trimmedBeforeCursor = beforeCursor.trimEnd();
|
||||
|
||||
if (trimmedBeforeCursor.endsWith("\\")) {
|
||||
// Handle backslash continuation: remove the trailing "\" and add newline
|
||||
const beforeBackslash = trimmedBeforeCursor.slice(0, -1);
|
||||
const afterCursor = textBuffer.text.slice(cursorPosition);
|
||||
const newText = beforeBackslash + "\n" + afterCursor;
|
||||
const newCursorPos = beforeBackslash.length + 1;
|
||||
|
||||
textBuffer.setText(newText);
|
||||
textBuffer.setCursor(newCursorPos);
|
||||
setInputText(newText);
|
||||
setCursorPosition(newCursorPos);
|
||||
updateSlashCommandState(newText, newCursorPos);
|
||||
updateFileSearchState(newText, newCursorPos);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Normal Enter behavior - submit if there's content
|
||||
if (textBuffer.text.trim() && !isWaitingForResponse) {
|
||||
// Expand all paste blocks before submitting
|
||||
textBuffer.expandAllPasteBlocks();
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ import { render } from "ink-testing-library";
|
|||
import React from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { getAllTools } from "src/stream/handleToolCalls.js";
|
||||
|
||||
import { SERVICE_NAMES, serviceContainer } from "../../services/index.js";
|
||||
import { modeService } from "../../services/ModeService.js";
|
||||
import { getAllTools } from "../../streamChatResponse.js";
|
||||
import { createUITestContext } from "../../test-helpers/ui-test-context.js";
|
||||
import { AppRoot } from "../AppRoot.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { Box, Text } from "ink";
|
||||
import React, { memo } from "react";
|
||||
|
||||
import { ToolCallTitle } from "src/tools/ToolCallTitle.js";
|
||||
|
||||
import type { ChatHistoryItem } from "../../../../../core/index.js";
|
||||
import { formatToolCall } from "../../tools/index.js";
|
||||
import { MarkdownRenderer } from "../MarkdownRenderer.js";
|
||||
import { ToolResultSummary } from "../ToolResultSummary.js";
|
||||
|
||||
|
|
@ -92,7 +93,7 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
|
|||
</Text>
|
||||
<Text color="white">
|
||||
{" "}
|
||||
{formatToolCall(toolName, toolArgs)}
|
||||
<ToolCallTitle toolName={toolName} args={toolArgs} />
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useState } from "react";
|
||||
|
||||
import { formatToolCall } from "../../tools/index.js";
|
||||
import { ToolCallTitle } from "src/tools/ToolCallTitle.js";
|
||||
|
||||
import { ToolCallPreview } from "../../tools/types.js";
|
||||
|
||||
import { ToolPreview } from "./ToolPreview.js";
|
||||
|
|
@ -101,8 +102,6 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
|
|||
}
|
||||
});
|
||||
|
||||
const toolCallDisplay = formatToolCall(toolName, toolArgs);
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
|
|
@ -111,7 +110,7 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
|
|||
borderColor="magenta"
|
||||
>
|
||||
<Text color="magenta" bold>
|
||||
{toolCallDisplay}
|
||||
<ToolCallTitle toolName={toolName} args={toolArgs} />
|
||||
</Text>
|
||||
|
||||
{/* Show preview of what the tool will do */}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,27 @@
|
|||
import { convertToUnifiedHistory } from "core/util/messageConversion.js";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { convertToUnifiedHistory } from "../../messageConversion.js";
|
||||
import { startNewSession } from "../../session.js";
|
||||
|
||||
import { processSlashCommandResult } from "./useChat.helpers.js";
|
||||
|
||||
// Mock the session module
|
||||
vi.mock("../../session.js", () => ({
|
||||
loadSession: vi.fn(),
|
||||
updateSessionHistory: vi.fn(),
|
||||
startNewSession: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("useChat clear command", () => {
|
||||
let mockSetChatHistory: ReturnType<typeof vi.fn>;
|
||||
let mockExit: ReturnType<typeof vi.fn>;
|
||||
let mockOnClear: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Clear all mocks to prevent call history leaking between tests
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockSetChatHistory = vi.fn();
|
||||
mockExit = vi.fn();
|
||||
mockOnClear = vi.fn();
|
||||
|
|
@ -41,6 +52,11 @@ describe("useChat clear command", () => {
|
|||
// Verify that onClear was called
|
||||
expect(mockOnClear).toHaveBeenCalledOnce();
|
||||
|
||||
// Verify that a new session was started with the system message
|
||||
expect(startNewSession).toHaveBeenCalledWith([
|
||||
chatHistory[0], // The system message ChatHistoryItem
|
||||
]);
|
||||
|
||||
// Verify that chat history was reset (keeping only system message)
|
||||
expect(mockSetChatHistory).toHaveBeenCalledWith([
|
||||
chatHistory[0], // The system message ChatHistoryItem
|
||||
|
|
@ -81,6 +97,11 @@ describe("useChat clear command", () => {
|
|||
});
|
||||
}).not.toThrow();
|
||||
|
||||
// Verify that a new session was started with the system message
|
||||
expect(startNewSession).toHaveBeenCalledWith([
|
||||
chatHistory[0], // The system message ChatHistoryItem
|
||||
]);
|
||||
|
||||
// Verify that history is still reset
|
||||
expect(mockSetChatHistory).toHaveBeenCalledWith([
|
||||
chatHistory[0], // The system message ChatHistoryItem
|
||||
|
|
@ -111,6 +132,9 @@ describe("useChat clear command", () => {
|
|||
onClear: mockOnClear,
|
||||
});
|
||||
|
||||
// Verify that a new session was started with the system message
|
||||
expect(startNewSession).toHaveBeenCalledWith([systemHistoryItem]);
|
||||
|
||||
// Should keep only the system message
|
||||
expect(mockSetChatHistory).toHaveBeenCalledWith([systemHistoryItem]);
|
||||
expect(mockOnClear).toHaveBeenCalledOnce();
|
||||
|
|
@ -130,6 +154,9 @@ describe("useChat clear command", () => {
|
|||
onClear: mockOnClear,
|
||||
});
|
||||
|
||||
// Verify that a new session was started with empty history
|
||||
expect(startNewSession).toHaveBeenCalledWith([]);
|
||||
|
||||
// Should set empty history when no system message exists
|
||||
expect(mockSetChatHistory).toHaveBeenCalledWith([]);
|
||||
expect(mockOnClear).toHaveBeenCalledOnce();
|
||||
|
|
|
|||
|
|
@ -4,9 +4,13 @@ import type { ChatHistoryItem, Session } from "core/index.js";
|
|||
import { getLastNPathParts } from "core/util/uri.js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { initializeChatHistory } from "../../commands/chat.js";
|
||||
import { compactChatHistory } from "../../compaction.js";
|
||||
import { loadSession, updateSessionHistory } from "../../session.js";
|
||||
import { DEFAULT_SESSION_TITLE } from "../../constants/session.js";
|
||||
import {
|
||||
loadSession,
|
||||
updateSessionHistory,
|
||||
startNewSession,
|
||||
} from "../../session.js";
|
||||
import { posthogService } from "../../telemetry/posthogService.js";
|
||||
import { telemetryService } from "../../telemetry/telemetryService.js";
|
||||
import { formatError } from "../../util/formatError.js";
|
||||
|
|
@ -16,11 +20,11 @@ import { shouldAutoCompact } from "../../util/tokenizer.js";
|
|||
import { SlashCommandResult } from "./useChat.types.js";
|
||||
|
||||
/**
|
||||
* Initialize chat history with proper system message
|
||||
* Initialize chat history
|
||||
*/
|
||||
export async function initChatHistory(
|
||||
resume?: boolean,
|
||||
additionalRules?: string[],
|
||||
_additionalRules?: string[],
|
||||
): Promise<ChatHistoryItem[]> {
|
||||
if (resume) {
|
||||
const savedSession = loadSession();
|
||||
|
|
@ -29,11 +33,8 @@ export async function initChatHistory(
|
|||
}
|
||||
}
|
||||
|
||||
const history = await initializeChatHistory({
|
||||
resume,
|
||||
rule: additionalRules,
|
||||
});
|
||||
return history;
|
||||
// Start with empty history - system message will be injected when needed
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -177,6 +178,10 @@ export function processSlashCommandResult({
|
|||
(item) => item.message.role === "system",
|
||||
);
|
||||
const newHistory = systemMessage ? [systemMessage] : [];
|
||||
|
||||
// Start a new session with a new sessionId
|
||||
startNewSession(newHistory);
|
||||
|
||||
setChatHistory(newHistory);
|
||||
|
||||
// Reset intro message state to show it again after clearing
|
||||
|
|
@ -407,3 +412,41 @@ export async function handleAutoCompaction({
|
|||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a title for the session based on the first assistant response
|
||||
*/
|
||||
export async function generateSessionTitle(
|
||||
assistantResponse: string,
|
||||
llmApi: any,
|
||||
model: any,
|
||||
currentSessionTitle?: string,
|
||||
): Promise<string | undefined> {
|
||||
// Only generate title for untitled sessions
|
||||
if (currentSessionTitle && currentSessionTitle !== DEFAULT_SESSION_TITLE) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!assistantResponse || !llmApi || !model) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const { ChatDescriber } = await import("core/util/chatDescriber.js");
|
||||
const generatedTitle = await ChatDescriber.describeWithBaseLlmApi(
|
||||
llmApi,
|
||||
model,
|
||||
assistantResponse,
|
||||
);
|
||||
|
||||
logger.debug("Generated session title", {
|
||||
original: currentSessionTitle,
|
||||
generated: generatedTitle,
|
||||
});
|
||||
|
||||
return generatedTitle;
|
||||
} catch (error) {
|
||||
logger.error("Failed to generate session title:", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { convertToUnifiedHistory } from "core/util/messageConversion.js";
|
||||
|
||||
import { convertToUnifiedHistory } from "../../messageConversion.js";
|
||||
import { posthogService } from "../../telemetry/posthogService.js";
|
||||
import { logger } from "../../util/logger.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,14 @@
|
|||
import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js";
|
||||
|
||||
import { getCurrentSession, updateSessionTitle } from "../../session.js";
|
||||
|
||||
import { generateSessionTitle } from "./useChat.helpers.js";
|
||||
|
||||
interface CreateStreamCallbacksOptions {
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setActivePermissionRequest: React.Dispatch<React.SetStateAction<any>>;
|
||||
llmApi?: any;
|
||||
model?: any;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -11,12 +17,12 @@ interface CreateStreamCallbacksOptions {
|
|||
export function createStreamCallbacks(
|
||||
options: CreateStreamCallbacksOptions,
|
||||
): any {
|
||||
const { setChatHistory, setActivePermissionRequest } = options;
|
||||
const { setChatHistory, setActivePermissionRequest, llmApi, model } = options;
|
||||
|
||||
return {
|
||||
onContent: (_: string) => {},
|
||||
|
||||
onContentComplete: (content: string) => {
|
||||
onContentComplete: async (content: string) => {
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
|
|
@ -28,6 +34,21 @@ export function createStreamCallbacks(
|
|||
},
|
||||
},
|
||||
]);
|
||||
|
||||
// Generate session title after first assistant response
|
||||
if (content && llmApi && model) {
|
||||
const currentSession = getCurrentSession();
|
||||
const generatedTitle = await generateSessionTitle(
|
||||
content,
|
||||
llmApi,
|
||||
model,
|
||||
currentSession.title,
|
||||
);
|
||||
|
||||
if (generatedTitle) {
|
||||
updateSessionTitle(generatedTitle);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
onToolStart: (toolName: string, toolArgs?: any) => {
|
||||
|
|
@ -198,7 +219,9 @@ export async function executeStreaming({
|
|||
currentCompactionIndex,
|
||||
}: ExecuteStreamingOptions): Promise<void> {
|
||||
const { getHistoryForLLM } = await import("../../compaction.js");
|
||||
const { streamChatResponse } = await import("../../streamChatResponse.js");
|
||||
const { streamChatResponse } = await import(
|
||||
"../../stream/streamChatResponse.js"
|
||||
);
|
||||
|
||||
if (model && llmApi) {
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -203,6 +203,8 @@ export function useChat({
|
|||
const streamCallbacks = createStreamCallbacks({
|
||||
setChatHistory,
|
||||
setActivePermissionRequest,
|
||||
llmApi,
|
||||
model,
|
||||
});
|
||||
|
||||
// Execute streaming chat response
|
||||
|
|
|
|||
|
|
@ -20,14 +20,14 @@ interface UseConfigSelectorProps {
|
|||
content: string;
|
||||
messageType: "system";
|
||||
}) => void;
|
||||
onChatReset: () => void;
|
||||
handleClear: () => void;
|
||||
}
|
||||
|
||||
const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
|
||||
|
||||
export function useConfigSelector({
|
||||
onMessage,
|
||||
onChatReset,
|
||||
handleClear,
|
||||
}: UseConfigSelectorProps) {
|
||||
const { closeCurrentScreen } = useNavigation();
|
||||
|
||||
|
|
@ -98,12 +98,6 @@ export function useConfigSelector({
|
|||
// Only config path is changing, no organization switch needed
|
||||
await services.config.updateConfigPath(targetConfigPath);
|
||||
} else {
|
||||
onMessage({
|
||||
role: "system",
|
||||
content: `Switching to organization for ${config.name}...`,
|
||||
messageType: "system" as const,
|
||||
});
|
||||
|
||||
// Switch organization first
|
||||
await services.auth.switchOrganization(config.organizationId ?? null);
|
||||
|
||||
|
|
@ -112,11 +106,7 @@ export function useConfigSelector({
|
|||
await services.config.updateConfigPath(targetConfigPath);
|
||||
}
|
||||
|
||||
// Reset chat history
|
||||
onChatReset();
|
||||
|
||||
// Clear the screen completely
|
||||
process.stdout.write("\x1b[2J\x1b[H");
|
||||
handleClear();
|
||||
|
||||
// Show success message
|
||||
onMessage({
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ export function useCurrentMode() {
|
|||
export function useSelectors(
|
||||
configPath: string | undefined,
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<any[]>>,
|
||||
resetChatHistory: () => void,
|
||||
handleClear: () => void,
|
||||
): {
|
||||
handleConfigSelect: (config: ConfigOption) => Promise<void>;
|
||||
handleModelSelect: (model: ModelOption) => Promise<void>;
|
||||
|
|
@ -115,7 +115,7 @@ export function useSelectors(
|
|||
},
|
||||
]);
|
||||
},
|
||||
onChatReset: resetChatHistory,
|
||||
handleClear,
|
||||
});
|
||||
|
||||
const { handleModelSelect } = useModelSelector({
|
||||
|
|
|
|||
|
|
@ -19,6 +19,9 @@ vi.mock("./src/systemMessage.js", () => ({
|
|||
),
|
||||
}));
|
||||
|
||||
// Mock environment for tests
|
||||
process.env.CONTINUE_GLOBAL_DIR = "/tmp/continue-test";
|
||||
|
||||
// Set up global afterEach hook to clear all timers and reset console
|
||||
afterEach(() => {
|
||||
// Clear vitest timers
|
||||
|
|
|
|||
2
package-lock.json
generated
2
package-lock.json
generated
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"name": "wt-generate-message-titles-in-cli",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue