diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 90d1acfe1..27705add0 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -14,7 +14,10 @@ import { processCommandFlags } from "../flags/flagProcessor.js"; import { safeStdout } from "../init.js"; import { configureLogger } from "../logger.js"; import * as logging from "../logging.js"; -import { convertFromUnifiedHistory, convertToUnifiedHistory } from "../messageConversion.js"; +import { + convertFromUnifiedHistory, + convertToUnifiedHistory, +} from "../messageConversion.js"; import { sentryService } from "../sentry.js"; import { initializeServices } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts index 1fc8dc9e7..5a7d8c440 100644 --- a/extensions/cli/src/commands/serve.helpers.ts +++ b/extensions/cli/src/commands/serve.helpers.ts @@ -1,4 +1,9 @@ -import type { ChatHistoryItem, Session, ToolCallState, ToolStatus } from "../../../../core/index.js"; +import type { + ChatHistoryItem, + Session, + ToolCallState, + ToolStatus, +} from "../../../../core/index.js"; import { streamChatResponse } from "../streamChatResponse.js"; import { StreamCallbacks } from "../streamChatResponse.types.js"; @@ -33,7 +38,7 @@ export async function streamChatResponseWithInterruption( }; state.session.history.push(currentStreamingItem); } - currentStreamingItem.message.content = + currentStreamingItem.message.content = (currentStreamingItem.message.content as string) + content; }, onContentComplete: (content: string) => { @@ -69,7 +74,7 @@ export async function streamChatResponseWithInterruption( status: "calling", parsedArgs: toolArgs, }; - + state.session.history.push({ message: { role: "assistant", content: "" }, contextItems: [], @@ -82,15 +87,18 @@ export async function streamChatResponseWithInterruption( const item = state.session.history[i]; if (item.toolCallStates) { const toolState = item.toolCallStates.find( - (ts: ToolCallState) => ts.toolCall.function.name === toolName && ts.status === "calling" + (ts: ToolCallState) => + ts.toolCall.function.name === toolName && ts.status === "calling", ); if (toolState) { toolState.status = status; - toolState.output = [{ - content: result, - name: `Tool Result: ${toolName}`, - description: "Tool execution result", - }]; + toolState.output = [ + { + content: result, + name: `Tool Result: ${toolName}`, + description: "Tool execution result", + }, + ]; return; } } @@ -103,15 +111,19 @@ export async function streamChatResponseWithInterruption( const item = state.session.history[i]; if (item.toolCallStates) { const toolState = item.toolCallStates.find( - (ts: ToolCallState) => ts.toolCall.function.name === toolName && ts.status === "calling" + (ts: ToolCallState) => + ts.toolCall.function.name === toolName && + ts.status === "calling", ); if (toolState) { toolState.status = "errored"; - toolState.output = [{ - content: error, - name: `Tool Error: ${toolName}`, - description: "Tool execution error", - }]; + toolState.output = [ + { + content: error, + name: `Tool Error: ${toolName}`, + description: "Tool execution error", + }, + ]; return; } } @@ -138,9 +150,9 @@ export async function streamChatResponseWithInterruption( // Add a system message indicating permission is needed state.session.history.push({ - message: { - role: "system", - content: `⚠️ Tool ${toolName} requires permission` + message: { + role: "system", + content: `⚠️ Tool ${toolName} requires permission`, }, contextItems: [], }); @@ -187,4 +199,3 @@ export interface ServerState { pendingPermission: PendingPermission | null; systemMessage?: string; } - diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index ad12aecae..8a68f4027 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -26,7 +26,10 @@ import { logger } from "../util/logger.js"; import { readStdinSync } from "../util/stdin.js"; import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; -import { streamChatResponseWithInterruption, type ServerState } from "./serve.helpers.js"; +import { + streamChatResponseWithInterruption, + type ServerState, +} from "./serve.helpers.js"; const execAsync = promisify(exec); @@ -35,7 +38,6 @@ interface ServeOptions extends ExtendedCommandOptions { port?: string; } - export async function serve(prompt?: string, options: ServeOptions = {}) { // Check if prompt should come from stdin instead of parameter let actualPrompt = prompt; @@ -109,7 +111,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { undefined, true, ); - + const initialHistory = []; if (systemMessage) { initialHistory.push({ @@ -117,7 +119,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { contextItems: [], }); } - + const session = createSession(initialHistory); // Initialize server state @@ -359,7 +361,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { if (e.name === "AbortError") { logger.debug("Response interrupted"); // Remove the partial assistant message if it exists - const lastMessage = state.session.history[state.session.history.length - 1]; + const lastMessage = + state.session.history[state.session.history.length - 1]; if ( lastMessage && lastMessage.message.role === "assistant" && diff --git a/extensions/cli/src/compaction.test.ts b/extensions/cli/src/compaction.test.ts index 429a2aa4a..81b88b690 100644 --- a/extensions/cli/src/compaction.test.ts +++ b/extensions/cli/src/compaction.test.ts @@ -352,7 +352,9 @@ describe("compaction", () => { role: "system", content: "You are a helpful assistant", }); - expect(result.compactedHistory[1].message.content).toContain(COMPACTION_MARKER); + expect(result.compactedHistory[1].message.content).toContain( + COMPACTION_MARKER, + ); }); it("should handle empty content from stream", async () => { @@ -373,7 +375,9 @@ describe("compaction", () => { const result = await compactChatHistory(history, mockModel, mockLlmApi); expect(result.compactionContent).toBe(""); - expect(result.compactedHistory[0].message.content).toBe(`${COMPACTION_MARKER}\n`); + expect(result.compactedHistory[0].message.content).toBe( + `${COMPACTION_MARKER}\n`, + ); }); it("should correctly construct prompt for compaction", async () => { @@ -448,13 +452,13 @@ describe("compaction", () => { ]); for (let i = 0; i < 100; i++) { - history.push({ + history.push({ message: { role: "user", content: `User message ${i}` }, - contextItems: [] + contextItems: [], }); - history.push({ + history.push({ message: { role: "assistant", content: `Assistant response ${i}` }, - contextItems: [] + contextItems: [], }); } diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index dd5767b91..f579be57d 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -53,7 +53,8 @@ export async function compactChatHistory( // Check if the history with compaction prompt is too long, prune if necessary let historyToUse = chatHistory; let historyForCompaction = [...historyToUse, compactionPrompt]; - let historyForCompactionLegacy = convertFromUnifiedHistory(historyForCompaction); + let historyForCompactionLegacy = + convertFromUnifiedHistory(historyForCompaction); const contextLimit = getModelContextLimit(model); const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; @@ -83,7 +84,8 @@ export async function compactChatHistory( historyToUse = prunedHistory; historyForCompaction = [...historyToUse, compactionPrompt]; - historyForCompactionLegacy = convertFromUnifiedHistory(historyForCompaction); + historyForCompactionLegacy = + convertFromUnifiedHistory(historyForCompaction); } // Stream the compaction response @@ -110,7 +112,9 @@ export async function compactChatHistory( ); // Create the compacted history with a special marker - const systemMessage = chatHistory.find((item) => item.message.role === "system"); + const systemMessage = chatHistory.find( + (item) => item.message.role === "system", + ); const compactedMessage: ChatHistoryItem = { message: { role: "assistant", @@ -123,7 +127,7 @@ export async function compactChatHistory( const compactedHistory = systemMessage ? [systemMessage, compactedMessage] : [compactedMessage]; - + // Mark the compaction in the unified format const compactionIndex = compactedHistory.length - 1; if (compactedHistory[compactionIndex]) { @@ -157,7 +161,7 @@ export function findCompactionIndex( chatHistory: ChatHistoryItem[], ): number | null { const compactedIndex = chatHistory.findIndex( - (item) => item.conversationSummary !== undefined + (item) => item.conversationSummary !== undefined, ); return compactedIndex === -1 ? null : compactedIndex; } diff --git a/extensions/cli/src/messageConversion.ts b/extensions/cli/src/messageConversion.ts index 2b4803bf7..dcf29ffbb 100644 --- a/extensions/cli/src/messageConversion.ts +++ b/extensions/cli/src/messageConversion.ts @@ -1,6 +1,6 @@ /** * Message conversion utilities for transitioning to unified ChatHistoryItem type. - * + * * This module provides conversion functions between the OpenAI ChatCompletionMessageParam * format and the unified ChatHistoryItem format from the core package. */ @@ -44,7 +44,7 @@ export function convertToUnifiedMessage( }; // Convert tool calls if present - if ('tool_calls' in message && message.tool_calls) { + if ("tool_calls" in message && message.tool_calls) { assistantMessage.toolCalls = message.tool_calls.map((tc: any) => ({ id: tc.id, type: "function" as const, @@ -97,14 +97,16 @@ export function convertFromUnifiedMessage( // Convert tool calls if present if (message.toolCalls && message.toolCalls.length > 0) { - (assistantMessage as any).tool_calls = message.toolCalls.map((tc: any) => ({ - id: tc.id, - type: "function", - function: { - name: tc.function?.name || "", - arguments: tc.function?.arguments || "", - }, - })); + (assistantMessage as any).tool_calls = message.toolCalls.map( + (tc: any) => ({ + id: tc.id, + type: "function", + function: { + name: tc.function?.name || "", + arguments: tc.function?.arguments || "", + }, + }), + ); } return assistantMessage; @@ -215,29 +217,31 @@ export function createHistoryItem( function handleToolResult( unifiedMessage: ChatMessage & { role: "tool" }, pendingToolCalls: Map, - historyItems: ChatHistoryItem[] + historyItems: ChatHistoryItem[], ): void { const toolCall = pendingToolCalls.get(unifiedMessage.toolCallId); if (!toolCall) return; - + // Add tool result as context to the previous assistant message const lastAssistantIndex = historyItems.findLastIndex( - item => item.message.role === "assistant" + (item) => item.message.role === "assistant", ); - + if (lastAssistantIndex < 0) return; if (!historyItems[lastAssistantIndex].toolCallStates) return; - + const toolState = historyItems[lastAssistantIndex].toolCallStates?.find( - ts => ts.toolCallId === unifiedMessage.toolCallId + (ts) => ts.toolCallId === unifiedMessage.toolCallId, ); - + if (toolState) { - toolState.output = [{ - content: unifiedMessage.content as string, - name: `Tool Result: ${toolCall.function.name}`, - description: "Tool execution result", - }]; + toolState.output = [ + { + content: unifiedMessage.content as string, + name: `Tool Result: ${toolCall.function.name}`, + description: "Tool execution result", + }, + ]; } } @@ -252,28 +256,30 @@ export function convertToUnifiedHistory( for (const message of messages) { const unifiedMessage = convertToUnifiedMessage(message); - + if (unifiedMessage.role === "assistant" && unifiedMessage.toolCalls) { // Store tool calls for matching with results - const toolCallStates: ToolCallState[] = unifiedMessage.toolCalls.map((tc: any) => { - const toolCall: ToolCall = { - id: tc.id || "", - type: "function", - function: { - name: tc.function?.name || "", - arguments: tc.function?.arguments || "", - }, - }; - pendingToolCalls.set(toolCall.id, toolCall); - - return { - toolCallId: toolCall.id, - toolCall, - status: "done" as ToolStatus, // Historical calls are complete - parsedArgs: tryParseJson(toolCall.function.arguments), - }; - }); - + const toolCallStates: ToolCallState[] = unifiedMessage.toolCalls.map( + (tc: any) => { + const toolCall: ToolCall = { + id: tc.id || "", + type: "function", + function: { + name: tc.function?.name || "", + arguments: tc.function?.arguments || "", + }, + }; + pendingToolCalls.set(toolCall.id, toolCall); + + return { + toolCallId: toolCall.id, + toolCall, + status: "done" as ToolStatus, // Historical calls are complete + parsedArgs: tryParseJson(toolCall.function.arguments), + }; + }, + ); + historyItems.push(createHistoryItem(unifiedMessage, [], toolCallStates)); } else if (unifiedMessage.role === "tool") { // Tool result - handle separately to reduce nesting @@ -324,8 +330,10 @@ export function extractToolCallInfo(historyItem: ChatHistoryItem): { toolCalls?: ToolCall[]; toolStates?: ToolCallState[]; } { - const hasToolCalls = !!(historyItem.toolCallStates && historyItem.toolCallStates.length > 0); - + const hasToolCalls = !!( + historyItem.toolCallStates && historyItem.toolCallStates.length > 0 + ); + return { hasToolCalls, toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall), @@ -343,4 +351,3 @@ function tryParseJson(str: string): any { return str; } } - diff --git a/extensions/cli/src/session.test.ts b/extensions/cli/src/session.test.ts index db666225e..85c6da284 100644 --- a/extensions/cli/src/session.test.ts +++ b/extensions/cli/src/session.test.ts @@ -1,4 +1,9 @@ -import { saveSession, hasSession, clearSession, createSession } from "./session.js"; +import { + saveSession, + hasSession, + clearSession, + createSession, +} from "./session.js"; describe("Session Management", () => { let originalEnv: NodeJS.ProcessEnv; @@ -29,7 +34,7 @@ describe("Session Management", () => { // Test first session process.env.TMUX_PANE = "%1"; const session1 = createSession([ - { message: { role: "user", content: "test1" }, contextItems: [] } + { message: { role: "user", content: "test1" }, contextItems: [] }, ]); saveSession(session1); expect(hasSession()).toBe(true); @@ -38,7 +43,7 @@ describe("Session Management", () => { // Test second session with different TMUX_PANE process.env.TMUX_PANE = "%2"; const session2 = createSession([ - { message: { role: "user", content: "test2" }, contextItems: [] } + { message: { role: "user", content: "test2" }, contextItems: [] }, ]); saveSession(session2); expect(hasSession()).toBe(true); @@ -49,7 +54,7 @@ describe("Session Management", () => { process.env.TERM_SESSION_ID = "w1t0s0:0.0"; const session = createSession([ - { message: { role: "user", content: "test" }, contextItems: [] } + { message: { role: "user", content: "test" }, contextItems: [] }, ]); saveSession(session); expect(hasSession()).toBe(true); @@ -60,7 +65,7 @@ describe("Session Management", () => { process.env.SSH_TTY = "/dev/pts/0"; const session = createSession([ - { message: { role: "user", content: "test" }, contextItems: [] } + { message: { role: "user", content: "test" }, contextItems: [] }, ]); saveSession(session); expect(hasSession()).toBe(true); @@ -73,7 +78,7 @@ describe("Session Management", () => { // Should not throw error despite special characters expect(() => { const session = createSession([ - { message: { role: "user", content: "test" }, contextItems: [] } + { message: { role: "user", content: "test" }, contextItems: [] }, ]); saveSession(session); }).not.toThrow(); @@ -88,7 +93,7 @@ describe("Session Management", () => { process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-123"; const session = createSession([ - { message: { role: "user", content: "test" }, contextItems: [] } + { message: { role: "user", content: "test" }, contextItems: [] }, ]); saveSession(session); expect(hasSession()).toBe(true); @@ -103,7 +108,10 @@ describe("Session Management", () => { // Should fall back to TTY path, process tree, or PID expect(() => { const session = createSession([ - { message: { role: "user", content: "fallback test" }, contextItems: [] } + { + message: { role: "user", content: "fallback test" }, + contextItems: [], + }, ]); saveSession(session); }).not.toThrow(); @@ -116,8 +124,14 @@ describe("Session Management", () => { process.env.TMUX_PANE = "%test"; const testHistory = [ - { message: { role: "user" as const, content: "Hello" }, contextItems: [] }, - { message: { role: "assistant" as const, content: "Hi there!" }, contextItems: [] }, + { + message: { role: "user" as const, content: "Hello" }, + contextItems: [], + }, + { + message: { role: "assistant" as const, content: "Hi there!" }, + contextItems: [], + }, ]; // Save session @@ -138,7 +152,7 @@ describe("Session Management", () => { expect(() => { const session = createSession([ - { message: { role: "user", content: "test" }, contextItems: [] } + { message: { role: "user", content: "test" }, contextItems: [] }, ]); saveSession(session); }).not.toThrow(); diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index b0092f458..3c0cd6ee4 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -4,12 +4,16 @@ import path from "path"; import { v4 as uuidv4 } from "uuid"; -import type { ChatHistoryItem, Session, SessionMetadata } from "../../../core/index.js"; +import type { + ChatHistoryItem, + Session, + SessionMetadata, +} from "../../../core/index.js"; // Re-export SessionMetadata for external consumers export type { SessionMetadata }; - import { logger } from "./util/logger.js"; +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. @@ -48,12 +52,12 @@ function getSessionDir(): string { function getSessionsListPath(): string { const sessionDir = getSessionDir(); const listPath = path.join(sessionDir, "sessions.json"); - + // Initialize with empty array if doesn't exist if (!fs.existsSync(listPath)) { fs.writeFileSync(listPath, JSON.stringify([])); } - + return listPath; } @@ -86,23 +90,26 @@ export function saveSession(session: Session): void { try { // Store the session ID for future reference currentSessionId = session.sessionId; - + // Filter out system messages except for the first one // TODO: Properly handle system messages vs informational messages in the future const filteredHistory = session.history.filter((item, index) => { return index === 0 || item.message.role !== "system"; }); - + const sessionToSave: Session = { ...session, - history: filteredHistory + history: filteredHistory, }; - - const sessionFilePath = path.join(getSessionDir(), `${session.sessionId}.json`); - + + const sessionFilePath = path.join( + getSessionDir(), + `${session.sessionId}.json`, + ); + // Write the session file fs.writeFileSync(sessionFilePath, JSON.stringify(sessionToSave, null, 2)); - + // Update the sessions list updateSessionsList(sessionToSave); } catch (error) { @@ -117,31 +124,36 @@ function updateSessionsList(session: Session): void { try { const listPath = getSessionsListPath(); let sessions: SessionMetadata[] = []; - + if (fs.existsSync(listPath)) { - const content = fs.readFileSync(listPath, 'utf8'); + const content = fs.readFileSync(listPath, "utf8"); try { sessions = JSON.parse(content); } catch { sessions = []; } } - + // Find or create session metadata - const existingIndex = sessions.findIndex(s => s.sessionId === session.sessionId); + const existingIndex = sessions.findIndex( + (s) => s.sessionId === session.sessionId, + ); const metadata: SessionMetadata = { sessionId: session.sessionId, title: session.title || "Untitled Session", - dateCreated: existingIndex >= 0 ? sessions[existingIndex].dateCreated : new Date().toISOString(), + dateCreated: + existingIndex >= 0 + ? sessions[existingIndex].dateCreated + : new Date().toISOString(), workspaceDirectory: session.workspaceDirectory || process.cwd(), }; - + if (existingIndex >= 0) { sessions[existingIndex] = metadata; } else { sessions.push(metadata); } - + fs.writeFileSync(listPath, JSON.stringify(sessions, null, 2)); } catch (error) { logger.error("Error updating sessions list:", error); @@ -159,12 +171,13 @@ export function loadSession(): Session | null { return null; } - const files = fs.readdirSync(sessionDir) - .filter(f => f.endsWith('.json') && !f.includes('sessions-list')) - .map(f => ({ + const files = fs + .readdirSync(sessionDir) + .filter((f) => f.endsWith(".json") && !f.includes("sessions-list")) + .map((f) => ({ name: f, path: path.join(sessionDir, f), - mtime: fs.statSync(path.join(sessionDir, f)).mtime + mtime: fs.statSync(path.join(sessionDir, f)).mtime, })) .sort((a, b) => b.mtime.getTime() - a.mtime.getTime()); @@ -203,7 +216,10 @@ export function createSession(history: ChatHistoryItem[] = []): Session { export function clearSession(): void { try { if (currentSessionId) { - const sessionFilePath = path.join(getSessionDir(), `${currentSessionId}.json`); + const sessionFilePath = path.join( + getSessionDir(), + `${currentSessionId}.json`, + ); if (fs.existsSync(sessionFilePath)) { fs.unlinkSync(sessionFilePath); } @@ -214,7 +230,6 @@ export function clearSession(): void { } } - /** * Check if a session exists for the current terminal */ @@ -222,15 +237,19 @@ export function hasSession(): boolean { if (!currentSessionId) { return false; } - const sessionFilePath = path.join(getSessionDir(), `${currentSessionId}.json`); + const sessionFilePath = path.join( + getSessionDir(), + `${currentSessionId}.json`, + ); return fs.existsSync(sessionFilePath); } - /** * Get metadata from a session file with first user message preview */ -function getSessionMetadataWithPreview(filePath: string): SessionMetadata & { firstUserMessage?: string } | null { +function getSessionMetadataWithPreview( + filePath: string, +): (SessionMetadata & { firstUserMessage?: string }) | null { try { const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8")); const stats = fs.statSync(filePath); @@ -246,7 +265,10 @@ function getSessionMetadataWithPreview(filePath: string): SessionMetadata & { fi } else if (Array.isArray(content)) { // For array content, find the first text part const textPart = content.find((part) => part.type === "text"); - firstUserMessage = textPart && 'text' in textPart ? textPart.text : "(multimodal message)"; + firstUserMessage = + textPart && "text" in textPart + ? textPart.text + : "(multimodal message)"; } else { firstUserMessage = "(unknown content type)"; } @@ -270,7 +292,9 @@ function getSessionMetadataWithPreview(filePath: string): SessionMetadata & { fi /** * List all available sessions with metadata */ -export function listSessions(limit: number = 10): (SessionMetadata & { firstUserMessage?: string })[] { +export function listSessions( + limit: number = 10, +): (SessionMetadata & { firstUserMessage?: string })[] { try { const sessionDir = getSessionDir(); @@ -294,7 +318,10 @@ export function listSessions(limit: number = 10): (SessionMetadata & { firstUser // Sort by date created (most recent first) and limit results return sessions - .sort((a, b) => new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime()) + .sort( + (a, b) => + new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(), + ) .slice(0, limit); } catch (error) { logger.error("Error listing sessions:", error); @@ -314,7 +341,9 @@ export function loadSessionById(sessionId: string): Session | null { return null; } - const session: Session = JSON.parse(fs.readFileSync(sessionFilePath, "utf8")); + const session: Session = JSON.parse( + fs.readFileSync(sessionFilePath, "utf8"), + ); return session; } catch (error) { logger.error("Error loading session by ID:", error); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts index f3c14f6c5..47e1f73e3 100644 --- a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts +++ b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts @@ -10,7 +10,12 @@ vi.mock("./compaction.js", () => ({ })); vi.mock("./session.js", () => ({ - createSession: vi.fn((history) => ({ sessionId: "test", title: "Test", workspaceDirectory: "/test", history })), + createSession: vi.fn((history) => ({ + sessionId: "test", + title: "Test", + workspaceDirectory: "/test", + history, + })), saveSession: vi.fn(), })); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.ts b/extensions/cli/src/streamChatResponse.autoCompaction.ts index 13584d746..8ec03e251 100644 --- a/extensions/cli/src/streamChatResponse.autoCompaction.ts +++ b/extensions/cli/src/streamChatResponse.autoCompaction.ts @@ -3,9 +3,11 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatCompletionMessageParam } from "openai/resources.mjs"; import React from "react"; - import { compactChatHistory } from "./compaction.js"; -import { convertFromUnifiedHistory, convertToUnifiedHistory } from "./messageConversion.js"; +import { + convertFromUnifiedHistory, + convertToUnifiedHistory, +} from "./messageConversion.js"; import { createSession, saveSession } from "./session.js"; import { formatError } from "./util/formatError.js"; import { logger } from "./util/logger.js"; @@ -143,7 +145,7 @@ export async function handleAutoCompaction( try { // Convert to unified format for compaction const unifiedHistory = convertToUnifiedHistory(chatHistory); - + // Compact the history const result = await compactChatHistory( unifiedHistory, @@ -165,8 +167,10 @@ export async function handleAutoCompaction( handleCompactionSuccess(result, isHeadless, callbacks); // Convert back to legacy format for return - const compactedLegacyHistory = convertFromUnifiedHistory(result.compactedHistory); - + const compactedLegacyHistory = convertFromUnifiedHistory( + result.compactedHistory, + ); + return { chatHistory: compactedLegacyHistory, compactionIndex: result.compactionIndex, diff --git a/extensions/cli/src/streamChatResponse.helpers.ts b/extensions/cli/src/streamChatResponse.helpers.ts index 726a53951..230ef814c 100644 --- a/extensions/cli/src/streamChatResponse.helpers.ts +++ b/extensions/cli/src/streamChatResponse.helpers.ts @@ -327,7 +327,8 @@ export async function preprocessStreamedToolCalls( // Notify the UI about the tool start, even though it failed callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); - const errorMessage = error instanceof Error ? error.message : String(error); + const errorMessage = + error instanceof Error ? error.message : String(error); logger.error("Invalid tool call", { name: toolCall.name, diff --git a/extensions/cli/src/streamChatResponse.ts b/extensions/cli/src/streamChatResponse.ts index 10e2675ba..756651bc1 100644 --- a/extensions/cli/src/streamChatResponse.ts +++ b/extensions/cli/src/streamChatResponse.ts @@ -456,7 +456,7 @@ export async function streamChatResponse( ) { // Convert to legacy format for processing const legacyHistory = convertFromUnifiedHistory(chatHistory); - + logger.debug("streamChatResponse called", { model, historyLength: chatHistory.length, diff --git a/extensions/cli/src/ui/IntroMessage.test.tsx b/extensions/cli/src/ui/IntroMessage.test.tsx index bece320f3..101d9a61f 100644 --- a/extensions/cli/src/ui/IntroMessage.test.tsx +++ b/extensions/cli/src/ui/IntroMessage.test.tsx @@ -177,22 +177,16 @@ The UI should only show the slug 'org/complex-rule'.`, } as any; const { lastFrame: frame2 } = render( - , + , ); output = frame2(); expect(output).toContain("Test Assistant"); expect(output).toContain("Loading..."); expect(output).toContain("Rule 1"); - // Test with only config missing + // Test with only config missing const { lastFrame: frame3 } = render( - , + , ); output = frame3(); expect(output).toContain("claude-3-sonnet"); diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx index 5c208d694..969547104 100644 --- a/extensions/cli/src/ui/IntroMessage.tsx +++ b/extensions/cli/src/ui/IntroMessage.tsx @@ -32,11 +32,9 @@ const IntroMessage: React.FC = ({ const allRules = configRules; // Check if model is capable - now checking both name and model properties - const modelCapable = model ? isModelCapable( - model.provider, - model.name, - model.model, - ) : true; // Default to true if model not loaded yet + const modelCapable = model + ? isModelCapable(model.provider, model.name, model.model) + : true; // Default to true if model not loaded yet return { allRules, modelCapable }; }, [config?.rules, model?.provider, model?.name, model?.model]); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.streamStopping.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.streamStopping.test.tsx index 5d71e5238..66483065d 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.streamStopping.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.streamStopping.test.tsx @@ -155,7 +155,11 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => { for (let i = 1; i < mockMultipleToolCalls.length; i++) { const remainingToolCall = mockMultipleToolCalls[i]; const cancelledMessage = "Cancelled due to previous tool rejection"; - mockCallbacks.onToolResult(cancelledMessage, remainingToolCall.name, "canceled"); + mockCallbacks.onToolResult( + cancelledMessage, + remainingToolCall.name, + "canceled", + ); } // Verify all tool calls got results diff --git a/extensions/cli/src/ui/__tests__/TUIChat.toolPermission.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.toolPermission.test.tsx index 81b1e6c61..22e2ebb6a 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.toolPermission.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.toolPermission.test.tsx @@ -2,7 +2,10 @@ import { render } from "ink-testing-library"; import React from "react"; import { vi } from "vitest"; -import type { ToolCallState, ChatHistoryItem } from "../../../../../core/index.js"; +import type { + ToolCallState, + ChatHistoryItem, +} from "../../../../../core/index.js"; import { ToolPermissionSelector } from "../components/ToolPermissionSelector.js"; describe("TUIChat - Tool Permission Tests", () => { @@ -347,7 +350,7 @@ describe("TUIChat - Tool Permission Tests", () => { contextItems: [], toolCallStates: [toolCallState], }; - + const { lastFrame: messageFrame } = render( , ); diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 286c96ab3..9f682376d 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -17,7 +17,7 @@ export const MemoizedMessage = memo( const isUser = message.role === "user"; const isSystem = message.role === "system"; const isAssistant = message.role === "assistant"; - + // Handle system messages if (isSystem) { // TODO: Properly separate LLM system messages from UI informational messages @@ -26,7 +26,7 @@ export const MemoizedMessage = memo( if (index === 0) { return null; } - + return ( @@ -35,7 +35,7 @@ export const MemoizedMessage = memo( ); } - + // Handle conversation summary (compaction) if (conversationSummary) { return ( @@ -51,7 +51,7 @@ export const MemoizedMessage = memo( /> ); } - + // Handle tool calls if (toolCallStates && toolCallStates.length > 0) { return ( @@ -64,33 +64,40 @@ export const MemoizedMessage = memo( )} - + {/* Render tool calls */} {toolCallStates.map((toolState, toolIndex) => { const toolName = toolState.toolCall.function.name; const toolArgs = toolState.parsedArgs; const isCompleted = toolState.status === "done"; const isErrored = toolState.status === "errored"; - + return ( - + {isCompleted || isErrored ? "●" : "○"} - {formatToolCall(toolName, toolArgs)} + + {" "} + {formatToolCall(toolName, toolArgs)} + - + {/* Show tool result if available */} {toolState.output && toolState.output.length > 0 && ( o.content).join("\n")} + content={toolState.output + .map((o) => o.content) + .join("\n")} /> )} - + {/* Show error if tool errored */} {isErrored && !toolState.output && ( @@ -103,18 +110,28 @@ export const MemoizedMessage = memo( ); } - + // Handle regular messages const isStreaming = isAssistant && !message.content && !toolCallStates; - + return ( ● {isUser ? ( - {typeof message.content === 'string' ? message.content : JSON.stringify(message.content)} + + {typeof message.content === "string" + ? message.content + : JSON.stringify(message.content)} + ) : ( - + )} {isStreaming && ▋} @@ -127,15 +144,16 @@ export const MemoizedMessage = memo( const nextMessage = nextProps.item.message; const prevToolStates = prevProps.item.toolCallStates; const nextToolStates = nextProps.item.toolCallStates; - + return ( prevMessage.content === nextMessage.content && prevMessage.role === nextMessage.role && JSON.stringify(prevToolStates) === JSON.stringify(nextToolStates) && - prevProps.item.conversationSummary === nextProps.item.conversationSummary && + prevProps.item.conversationSummary === + nextProps.item.conversationSummary && prevProps.index === nextProps.index ); }, ); -MemoizedMessage.displayName = "MemoizedMessage"; \ No newline at end of file +MemoizedMessage.displayName = "MemoizedMessage"; diff --git a/extensions/cli/src/ui/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx index effc37928..1f8d4ee2b 100644 --- a/extensions/cli/src/ui/components/StaticChatContent.tsx +++ b/extensions/cli/src/ui/components/StaticChatContent.tsx @@ -83,7 +83,7 @@ export const StaticChatContent: React.FC = ({ // Add all chat messages (filter out system messages) chatHistory - .filter(item => item.message.role !== "system" || item.message.content) // Keep non-empty system messages + .filter((item) => item.message.role !== "system" || item.message.content) // Keep non-empty system messages .forEach((item, index) => { items.push(renderMessage(item, index)); }); @@ -103,4 +103,4 @@ export const StaticChatContent: React.FC = ({ {(item) => item} ); -}; \ No newline at end of file +}; diff --git a/extensions/cli/src/ui/hooks/useChat.clear.test.ts b/extensions/cli/src/ui/hooks/useChat.clear.test.ts index 28dec38ee..91f7e62d4 100644 --- a/extensions/cli/src/ui/hooks/useChat.clear.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.clear.test.ts @@ -1,12 +1,10 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { beforeEach, describe, expect, it, vi } from "vitest"; - import { convertToUnifiedHistory } from "../../messageConversion.js"; import { processSlashCommandResult } from "./useChat.helpers.js"; - describe("useChat clear command", () => { let mockSetChatHistory: ReturnType; let mockExit: ReturnType; @@ -77,7 +75,7 @@ describe("useChat clear command", () => { result, chatHistory, setChatHistory: mockSetChatHistory, - exit: mockExit, + exit: mockExit, onShowConfigSelector: vi.fn(), // onClear is not provided }); diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 886c40cc5..22b03609b 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -1,7 +1,10 @@ import type { ChatHistoryItem, Session } from "../../../../../core/index.js"; import { initializeChatHistory } from "../../commands/chat.js"; import { compactChatHistory } from "../../compaction.js"; -import { convertFromUnifiedHistory, convertToUnifiedHistory } from "../../messageConversion.js"; +import { + convertFromUnifiedHistory, + convertToUnifiedHistory, +} from "../../messageConversion.js"; import { loadSession, saveSession } from "../../session.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; @@ -45,9 +48,7 @@ interface HandleCompactCommandOptions { chatHistory: ChatHistoryItem[]; model: any; llmApi: any; - setChatHistory: React.Dispatch< - React.SetStateAction - >; + setChatHistory: React.Dispatch>; setCompactionIndex: React.Dispatch>; currentSession: Session; setCurrentSession: React.Dispatch>; @@ -80,7 +81,7 @@ export async function handleCompactCommand({ try { // Compact the chat history directly (already in unified format) const result = await compactChatHistory(chatHistory, model, llmApi); - + // Replace chat history with compacted version setChatHistory(result.compactedHistory); setCompactionIndex(result.compactionIndex); @@ -121,9 +122,7 @@ export async function handleCompactCommand({ interface ProcessSlashCommandResultOptions { result: SlashCommandResult; chatHistory: ChatHistoryItem[]; - setChatHistory: React.Dispatch< - React.SetStateAction - >; + setChatHistory: React.Dispatch>; exit: () => void; onShowConfigSelector: () => void; onShowModelSelector?: () => void; @@ -172,7 +171,9 @@ export function processSlashCommandResult({ } if (result.clear) { - const systemMessage = chatHistory.find((item) => item.message.role === "system"); + const systemMessage = chatHistory.find( + (item) => item.message.role === "system", + ); const newHistory = systemMessage ? [systemMessage] : []; setChatHistory(newHistory); @@ -284,9 +285,7 @@ interface HandleAutoCompactionOptions { model: any; llmApi: any; compactionIndex: number | null; - setChatHistory: React.Dispatch< - React.SetStateAction - >; + setChatHistory: React.Dispatch>; setCompactionIndex: React.Dispatch>; } @@ -307,16 +306,16 @@ export async function handleAutoCompaction({ const { handleAutoCompaction: coreAutoCompaction } = await import( "../../streamChatResponse.autoCompaction.js" ); - + // Convert to legacy format for compaction const legacyHistory = convertFromUnifiedHistory(chatHistory); - + const result = await coreAutoCompaction(legacyHistory, model, llmApi, { isHeadless: false, callbacks: { setMessages: (updater: any) => { // Convert messages updates to chat history updates - if (typeof updater === 'function') { + if (typeof updater === "function") { setChatHistory((prev) => { // For now, just return prev - compaction messages will be handled separately return prev; @@ -325,7 +324,7 @@ export async function handleAutoCompaction({ }, setChatHistory: (updater: any) => { // Handle chat history updates - if (typeof updater === 'function') { + if (typeof updater === "function") { setChatHistory((prev) => { const legacyPrev = convertFromUnifiedHistory(prev); const updated = updater(legacyPrev); @@ -343,4 +342,4 @@ export async function handleAutoCompaction({ currentChatHistory: convertToUnifiedHistory(result.chatHistory), currentCompactionIndex: result.compactionIndex, }; -} \ No newline at end of file +} diff --git a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts index ded837a4a..e271ae94c 100644 --- a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts @@ -25,9 +25,7 @@ async function pollRemoteServerState( interface SetupRemotePollingOptions { remoteUrl: string; - setChatHistory: React.Dispatch< - React.SetStateAction - >; + setChatHistory: React.Dispatch>; setIsWaitingForResponse: React.Dispatch>; responseStartTime: number | null; setResponseStartTime: React.Dispatch>; @@ -83,9 +81,7 @@ export function setupRemotePolling({ interface UpdateStateFromRemoteOptions { state: RemoteServerState; - setChatHistory: React.Dispatch< - React.SetStateAction - >; + setChatHistory: React.Dispatch>; setIsWaitingForResponse: React.Dispatch>; responseStartTime: number | null; setResponseStartTime: React.Dispatch>; @@ -106,7 +102,7 @@ function updateStateFromRemote({ setChatHistory((prevHistory) => { // Convert server's legacy format to unified format const newHistory = convertToUnifiedHistory(state.chatHistory); - + // Quick length check first if (prevHistory.length !== newHistory.length) { return newHistory; @@ -119,7 +115,8 @@ function updateStateFromRemote({ !prevItem || prevItem.message.role !== item.message.role || prevItem.message.content !== item.message.content || - JSON.stringify(prevItem.toolCallStates) !== JSON.stringify(item.toolCallStates) + JSON.stringify(prevItem.toolCallStates) !== + JSON.stringify(item.toolCallStates) ); }); @@ -245,4 +242,4 @@ export async function handleRemoteMessage({ }, ]); } -} \ No newline at end of file +} diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 8be082676..39b6c914c 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -1,4 +1,8 @@ -import type { ChatHistoryItem, ToolCallState, ToolStatus } from "../../../../../core/index.js"; +import type { + ChatHistoryItem, + ToolCallState, + ToolStatus, +} from "../../../../../core/index.js"; interface CreateStreamCallbacksOptions { setChatHistory: React.Dispatch>; @@ -12,28 +16,28 @@ export function createStreamCallbacks( options: CreateStreamCallbacksOptions, ): any { const { setChatHistory, setActivePermissionRequest } = options; - + return { onContent: (_: string) => {}, - + onContentComplete: (content: string) => { setChatHistory((prev) => [ - ...prev, - { - contextItems: [], - message: { - role: "assistant", - content: content, - isStreaming: false, - } + ...prev, + { + contextItems: [], + message: { + role: "assistant", + content: content, + isStreaming: false, }, + }, ]); }, - + onToolStart: (toolName: string, toolArgs?: any) => { setChatHistory((prev) => { const newHistory = [...prev]; - + // Always create a new assistant message for each tool call const toolCallId = `tool_${Date.now()}`; const toolCallState: ToolCallState = { @@ -49,76 +53,86 @@ export function createStreamCallbacks( status: "calling", parsedArgs: toolArgs, }; - + newHistory.push({ message: { role: "assistant", content: "", - toolCalls: [{ - id: toolCallId, - type: "function", - function: { - name: toolName, - arguments: JSON.stringify(toolArgs || {}), + toolCalls: [ + { + id: toolCallId, + type: "function", + function: { + name: toolName, + arguments: JSON.stringify(toolArgs || {}), + }, }, - }], + ], }, contextItems: [], toolCallStates: [toolCallState], }); - + return newHistory; }); }, - + onToolResult: (result: string, toolName: string, status: ToolStatus) => { setChatHistory((prev) => { const newHistory = [...prev]; - + // Find the tool call state and update it for (let i = newHistory.length - 1; i >= 0; i--) { const item = newHistory[i]; if (item.toolCallStates) { const toolState = item.toolCallStates.find( - ts => ts.toolCall.function.name === toolName && ts.status === "calling" + (ts) => + ts.toolCall.function.name === toolName && + ts.status === "calling", ); - + if (toolState) { toolState.status = status; - toolState.output = [{ - content: result, - name: `Tool Result: ${toolName}`, - description: "Tool execution result", - }]; + toolState.output = [ + { + content: result, + name: `Tool Result: ${toolName}`, + description: "Tool execution result", + }, + ]; break; } } } - + return newHistory; }); }, - + onToolError: (error: string, toolName?: string) => { setChatHistory((prev) => { const newHistory = [...prev]; - + // Find the tool call state and mark it as errored if (toolName) { for (let i = newHistory.length - 1; i >= 0; i--) { const item = newHistory[i]; if (item.toolCallStates) { const toolState = item.toolCallStates.find( - ts => ts.toolCall.function.name === toolName && ts.status === "calling" + (ts) => + ts.toolCall.function.name === toolName && + ts.status === "calling", ); - + if (toolState) { toolState.status = "errored"; - toolState.output = [{ - content: error, - name: `Tool Error: ${toolName}`, - description: "Tool execution error", - }]; + toolState.output = [ + { + content: error, + name: `Tool Error: ${toolName}`, + description: "Tool execution error", + }, + ]; break; } } @@ -133,11 +147,11 @@ export function createStreamCallbacks( contextItems: [], }); } - + return newHistory; }); }, - + onToolPermissionRequest: ( toolName: string, toolArgs: any, @@ -151,7 +165,7 @@ export function createStreamCallbacks( toolCallPreview, }); }, - + onSystemMessage: (message: string) => { setChatHistory((prev) => [ ...prev, @@ -189,7 +203,7 @@ export async function executeStreaming({ }: ExecuteStreamingOptions): Promise { const { getHistoryForLLM } = await import("../../compaction.js"); const { streamChatResponse } = await import("../../streamChatResponse.js"); - + if (model && llmApi) { if ( currentCompactionIndex !== null && @@ -200,7 +214,7 @@ export async function executeStreaming({ currentCompactionIndex, ); const _originalLength = historyForLLM.length; - + await streamChatResponse( historyForLLM, model, @@ -208,7 +222,7 @@ export async function executeStreaming({ controller, streamCallbacks, ); - + // streamChatResponse modifies the array in place // The new messages are already in historyForLLM } else { @@ -221,4 +235,4 @@ export async function executeStreaming({ ); } } -} \ No newline at end of file +} diff --git a/extensions/cli/src/ui/hooks/useChat.stream.test.ts b/extensions/cli/src/ui/hooks/useChat.stream.test.ts index fd7abf1b0..6e8e18265 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.test.ts @@ -7,7 +7,7 @@ import { createStreamCallbacks } from "./useChat.stream.helpers.js"; describe("useChat streaming", () => { it("should handle content completion", () => { let chatHistory: ChatHistoryItem[] = []; - + const setChatHistory = vi.fn((updater: any) => { if (typeof updater === "function") { chatHistory = updater(chatHistory); @@ -15,35 +15,35 @@ describe("useChat streaming", () => { chatHistory = updater; } }); - + const callbacks = createStreamCallbacks({ setChatHistory, setActivePermissionRequest: vi.fn(), }); - + // onContent is now empty and doesn't update history callbacks.onContent("Hello"); expect(setChatHistory).toHaveBeenCalledTimes(0); expect(chatHistory).toHaveLength(0); - + callbacks.onContent(" world"); expect(setChatHistory).toHaveBeenCalledTimes(0); expect(chatHistory).toHaveLength(0); - + callbacks.onContent("!"); expect(setChatHistory).toHaveBeenCalledTimes(0); expect(chatHistory).toHaveLength(0); - + // Complete the streaming - this adds the message callbacks.onContentComplete("Hello world!"); expect(setChatHistory).toHaveBeenCalledTimes(1); expect(chatHistory).toHaveLength(1); expect(chatHistory[0].message.content).toBe("Hello world!"); }); - + it("should handle tool calls during streaming", () => { let chatHistory: ChatHistoryItem[] = []; - + const setChatHistory = vi.fn((updater: any) => { if (typeof updater === "function") { chatHistory = updater(chatHistory); @@ -51,41 +51,41 @@ describe("useChat streaming", () => { chatHistory = updater; } }); - + const callbacks = createStreamCallbacks({ setChatHistory, setActivePermissionRequest: vi.fn(), }); - + // Start with some content callbacks.onContent("Let me help you with that."); expect(chatHistory).toHaveLength(0); // onContent is empty, doesn't add messages - + // Complete content before tool call callbacks.onContentComplete("Let me help you with that."); expect(chatHistory).toHaveLength(1); expect(chatHistory[0].message.content).toBe("Let me help you with that."); - + // Now a tool call - creates a new message callbacks.onToolStart("Read", { file_path: "/test.txt" }); expect(chatHistory).toHaveLength(2); // New message for tool call expect(chatHistory[1].toolCallStates).toHaveLength(1); expect(chatHistory[1].toolCallStates![0].status).toBe("calling"); - + // Tool result callbacks.onToolResult("File contents", "Read", "done"); expect(chatHistory[1].toolCallStates![0].status).toBe("done"); - + // More content after tool creates a new message callbacks.onContent("Based on the file"); expect(chatHistory).toHaveLength(2); // onContent is empty, doesn't add - + callbacks.onContentComplete("Based on the file"); expect(chatHistory).toHaveLength(3); // New message from onContentComplete expect(chatHistory[2].message.role).toBe("assistant"); expect(chatHistory[2].message.content).toBe("Based on the file"); }); - + it("should create new message if last message is not assistant", () => { let chatHistory: ChatHistoryItem[] = [ { @@ -93,7 +93,7 @@ describe("useChat streaming", () => { contextItems: [], }, ]; - + const setChatHistory = vi.fn((updater: any) => { if (typeof updater === "function") { chatHistory = updater(chatHistory); @@ -101,24 +101,24 @@ describe("useChat streaming", () => { chatHistory = updater; } }); - + const callbacks = createStreamCallbacks({ setChatHistory, setActivePermissionRequest: vi.fn(), }); - + callbacks.onContent("Hi there"); expect(chatHistory).toHaveLength(1); // onContent is empty, doesn't add - + callbacks.onContentComplete("Hi there"); expect(chatHistory).toHaveLength(2); expect(chatHistory[1].message.role).toBe("assistant"); expect(chatHistory[1].message.content).toBe("Hi there"); }); - + it("should create separate messages for each tool call", () => { let chatHistory: ChatHistoryItem[] = []; - + const setChatHistory = vi.fn((updater: any) => { if (typeof updater === "function") { chatHistory = updater(chatHistory); @@ -126,45 +126,54 @@ describe("useChat streaming", () => { chatHistory = updater; } }); - + const callbacks = createStreamCallbacks({ setChatHistory, setActivePermissionRequest: vi.fn(), }); - + // Add initial content callbacks.onContentComplete("Let me check multiple things"); expect(chatHistory).toHaveLength(1); - + // First tool call - creates new message callbacks.onToolStart("Read", { file_path: "/first.txt" }); expect(chatHistory).toHaveLength(2); expect(chatHistory[1].toolCallStates).toHaveLength(1); - expect(chatHistory[1].toolCallStates![0].toolCall.function.name).toBe("Read"); - + expect(chatHistory[1].toolCallStates![0].toolCall.function.name).toBe( + "Read", + ); + // First tool result callbacks.onToolResult("First file contents", "Read", "done"); expect(chatHistory[1].toolCallStates![0].status).toBe("done"); - + // Second tool call - creates another new message - callbacks.onToolStart("Write", { file_path: "/second.txt", content: "test" }); + callbacks.onToolStart("Write", { + file_path: "/second.txt", + content: "test", + }); expect(chatHistory).toHaveLength(3); expect(chatHistory[2].toolCallStates).toHaveLength(1); - expect(chatHistory[2].toolCallStates![0].toolCall.function.name).toBe("Write"); - + expect(chatHistory[2].toolCallStates![0].toolCall.function.name).toBe( + "Write", + ); + // Second tool result callbacks.onToolResult("Write successful", "Write", "done"); expect(chatHistory[2].toolCallStates![0].status).toBe("done"); - + // Third tool call - creates yet another new message callbacks.onToolStart("Read", { file_path: "/third.txt" }); expect(chatHistory).toHaveLength(4); expect(chatHistory[3].toolCallStates).toHaveLength(1); - expect(chatHistory[3].toolCallStates![0].toolCall.function.name).toBe("Read"); - + expect(chatHistory[3].toolCallStates![0].toolCall.function.name).toBe( + "Read", + ); + // Final content after all tools callbacks.onContentComplete("All operations completed"); expect(chatHistory).toHaveLength(5); expect(chatHistory[4].message.content).toBe("All operations completed"); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 357459dff..cdcb280f2 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -67,13 +67,13 @@ export function useChat({ return savedSession; } } - + // Create new session return createSession([]); }); const [chatHistory, setChatHistory] = useState( - () => currentSession.history + () => currentSession.history, ); const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); @@ -196,9 +196,10 @@ export function useChat({ }); try { - const streamCallbacks = createStreamCallbacks( - { setChatHistory, setActivePermissionRequest } - ); + const streamCallbacks = createStreamCallbacks({ + setChatHistory, + setActivePermissionRequest, + }); // Execute streaming chat response await executeStreaming({ diff --git a/extensions/cli/src/ui/hooks/useMessageRenderer.tsx b/extensions/cli/src/ui/hooks/useMessageRenderer.tsx index e3bf2c3f9..e89d92fba 100644 --- a/extensions/cli/src/ui/hooks/useMessageRenderer.tsx +++ b/extensions/cli/src/ui/hooks/useMessageRenderer.tsx @@ -4,12 +4,9 @@ import type { ChatHistoryItem } from "../../../../../core/index.js"; import { MemoizedMessage } from "../components/MemoizedMessage.js"; export function useMessageRenderer() { - const renderMessage = useCallback( - (item: ChatHistoryItem, index: number) => { - return ; - }, - [], - ); + const renderMessage = useCallback((item: ChatHistoryItem, index: number) => { + return ; + }, []); return { renderMessage }; -} \ No newline at end of file +} diff --git a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts index 9740deff2..1d95b1fa1 100644 --- a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts +++ b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts @@ -32,8 +32,8 @@ export function getRepoUrlText(remoteUrl?: string): string { // Custom hook for intro message export function useIntroMessage( isRemoteMode: boolean, - services: any, - allServicesReady: boolean, + _services: any, + _allServicesReady: boolean, ) { const [showIntroMessage, setShowIntroMessage] = useState(false); @@ -107,10 +107,13 @@ export function useSelectors( configPath, onMessage: (message) => { // Convert message to ChatHistoryItem format - setChatHistory((prev) => [...prev, { - message: { role: "system", content: message.content }, - contextItems: [], - }]); + setChatHistory((prev) => [ + ...prev, + { + message: { role: "system", content: message.content }, + contextItems: [], + }, + ]); }, onChatReset: resetChatHistory, }); @@ -118,10 +121,13 @@ export function useSelectors( const { handleModelSelect } = useModelSelector({ onMessage: (message) => { // Convert message to ChatHistoryItem format - setChatHistory((prev) => [...prev, { - message: { role: "system", content: message.content }, - contextItems: [], - }]); + setChatHistory((prev) => [ + ...prev, + { + message: { role: "system", content: message.content }, + contextItems: [], + }, + ]); }, }); diff --git a/extensions/cli/src/ui/types.ts b/extensions/cli/src/ui/types.ts index f15d9e43f..a18e4a9b2 100644 --- a/extensions/cli/src/ui/types.ts +++ b/extensions/cli/src/ui/types.ts @@ -1,2 +1,2 @@ // This file has been intentionally left empty after migration to ChatHistoryItem -// All types have been migrated to use @continuedev/core types \ No newline at end of file +// All types have been migrated to use @continuedev/core types diff --git a/package-lock.json b/package-lock.json index 6981243e3..aff7f7f23 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "wt-mcp-flag", + "name": "wt-message-format-migration", "lockfileVersion": 3, "requires": true, "packages": {