migration part 1

This commit is contained in:
Nate 2025-08-24 21:54:58 -07:00
parent f5a880252d
commit fe2fa03087
18 changed files with 1240 additions and 662 deletions

View file

@ -0,0 +1,210 @@
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import type { ChatHistoryItem, ToolCallState } from "../../../../core/index.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { StreamCallbacks } from "../streamChatResponse.types.js";
// Modified version of streamChatResponse that supports interruption
export async function streamChatResponseWithInterruption(
state: ServerState,
llmApi: any,
abortController: AbortController,
shouldInterrupt: () => boolean,
): Promise<string> {
// Import the original streamChatResponse logic but add interruption checks
// Create a wrapper that checks for interruption
const originalSignal = abortController.signal;
const checkInterruption = () => {
if (shouldInterrupt() && !originalSignal.aborted) {
abortController.abort();
}
};
// Set up periodic interruption checks
const interruptionChecker = setInterval(checkInterruption, 100);
let currentStreamingItem: ChatHistoryItem | null = null;
// Create callbacks to capture tool events
const callbacks: StreamCallbacks = {
onContent: (content: string) => {
if (!currentStreamingItem) {
currentStreamingItem = {
message: { role: "assistant", content: "" },
contextItems: [],
};
state.unifiedHistory.push(currentStreamingItem);
}
currentStreamingItem.message.content =
(currentStreamingItem.message.content as string) + content;
},
onContentComplete: (content: string) => {
if (currentStreamingItem) {
currentStreamingItem.message.content = content;
currentStreamingItem = null;
} else {
// Add complete assistant message
state.unifiedHistory.push({
message: { role: "assistant", content: content },
contextItems: [],
});
}
},
onToolStart: (toolName: string, toolArgs?: any) => {
// If there was streaming content, finalize it first
if (currentStreamingItem && currentStreamingItem.message.content) {
currentStreamingItem = null;
}
// Add tool call to the last assistant message or create new one
const lastItem = state.unifiedHistory[state.unifiedHistory.length - 1];
if (lastItem && lastItem.message.role === "assistant") {
if (!lastItem.toolCallStates) {
lastItem.toolCallStates = [];
}
lastItem.toolCallStates.push({
toolCallId: `tool_${Date.now()}`,
toolCall: {
id: `tool_${Date.now()}`,
type: "function",
function: {
name: toolName,
arguments: JSON.stringify(toolArgs || {}),
},
},
status: "calling",
parsedArgs: toolArgs,
});
} else {
state.unifiedHistory.push({
message: { role: "assistant", content: "" },
contextItems: [],
toolCallStates: [{
toolCallId: `tool_${Date.now()}`,
toolCall: {
id: `tool_${Date.now()}`,
type: "function",
function: {
name: toolName,
arguments: JSON.stringify(toolArgs || {}),
},
},
status: "calling",
parsedArgs: toolArgs,
}],
});
}
},
onToolResult: (result: string, toolName: string) => {
// Find and update the corresponding tool call state
for (let i = state.unifiedHistory.length - 1; i >= 0; i--) {
const item = state.unifiedHistory[i];
if (item.toolCallStates) {
const toolState = item.toolCallStates.find(
(ts: ToolCallState) => ts.toolCall.function.name === toolName && ts.status === "calling"
);
if (toolState) {
toolState.status = "done";
toolState.output = [{
content: result,
name: `Tool Result: ${toolName}`,
description: "Tool execution result",
}];
return;
}
}
}
},
onToolError: (error: string, toolName?: string) => {
if (toolName) {
// Find and update the corresponding tool call state
for (let i = state.unifiedHistory.length - 1; i >= 0; i--) {
const item = state.unifiedHistory[i];
if (item.toolCallStates) {
const toolState = item.toolCallStates.find(
(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",
}];
return;
}
}
}
}
// Generic error if tool not found
state.unifiedHistory.push({
message: { role: "system", content: error },
contextItems: [],
});
},
onToolPermissionRequest: (
toolName: string,
toolArgs: any,
requestId: string,
) => {
// Set pending permission state
state.pendingPermission = {
toolName,
toolArgs,
requestId,
timestamp: Date.now(),
};
// Add a system message indicating permission is needed
state.unifiedHistory.push({
message: {
role: "system",
content: `⚠️ Tool ${toolName} requires permission`
},
contextItems: [],
});
// Don't wait here - the streamChatResponse will handle waiting
},
};
try {
const response = await streamChatResponse(
state.chatHistory,
state.model,
llmApi,
abortController,
callbacks,
);
return response || "";
} finally {
clearInterval(interruptionChecker);
// Ensure any streaming message is finalized
if (currentStreamingItem !== null) {
currentStreamingItem = null;
}
}
}
export interface PendingPermission {
toolName: string;
toolArgs: any;
requestId: string;
timestamp: number;
}
export interface ServerState {
chatHistory: ChatCompletionMessageParam[];
unifiedHistory: ChatHistoryItem[];
config: any;
model: any;
isProcessing: boolean;
lastActivity: number;
messageQueue: string[];
currentAbortController: AbortController | null;
shouldInterrupt: boolean;
serverRunning: boolean;
pendingPermission: PendingPermission | null;
systemMessage?: string;
}

View file

@ -1,13 +1,14 @@
import { exec } from "child_process";
import path from "path";
import { promisify } from "util";
import chalk from "chalk";
import express, { Request, Response } from "express";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import type { ChatHistoryItem } from "../../../../core/index.js";
import { getAssistantSlug } from "../auth/workos.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { convertToUnifiedHistory, convertFromUnifiedHistory } from "../messageConversion.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import {
getService,
@ -20,17 +21,14 @@ import {
ModelServiceState,
} from "../services/types.js";
import { saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { StreamCallbacks } from "../streamChatResponse.types.js";
import { constructSystemMessage } from "../systemMessage.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { getToolDisplayName } from "../tools/index.js";
import { DisplayMessage } from "../ui/types.js";
import { formatError } from "../util/formatError.js";
import { logger } from "../util/logger.js";
import { readStdinSync } from "../util/stdin.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
import { streamChatResponseWithInterruption, type PendingPermission } from "./serve.helpers.js";
const execAsync = promisify(exec);
@ -39,16 +37,9 @@ interface ServeOptions extends ExtendedCommandOptions {
port?: string;
}
interface PendingPermission {
toolName: string;
toolArgs: any;
requestId: string;
timestamp: number;
}
interface ServerState {
chatHistory: ChatCompletionMessageParam[];
displayMessages: DisplayMessage[]; // Messages formatted for display with tool info
unifiedHistory: ChatHistoryItem[]; // Unified format for display
config: any;
model: any;
isProcessing: boolean;
@ -141,7 +132,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// Initialize server state
const state: ServerState = {
chatHistory,
displayMessages: [], // Initialize empty display messages
unifiedHistory: convertToUnifiedHistory(chatHistory), // Convert to unified format
config,
model,
isProcessing: false,
@ -164,7 +155,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
app.get("/state", (_req: Request, res: Response) => {
state.lastActivity = Date.now();
res.json({
chatHistory: state.displayMessages, // Send display messages with proper formatting
chatHistory: convertFromUnifiedHistory(state.unifiedHistory), // Convert back to legacy format for API
isProcessing: state.isProcessing,
messageQueueLength: state.messageQueue.length,
pendingPermission: state.pendingPermission,
@ -214,11 +205,8 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
return res.status(400).json({ error: "Invalid request ID" });
}
// Remove the permission request message
const lastMsg = state.displayMessages[state.displayMessages.length - 1];
if (lastMsg && lastMsg.messageType === "tool-permission-request") {
state.displayMessages.pop();
}
// Remove the permission request message if it exists
// Permission requests are handled separately in unified format
// Send the permission response to the toolPermissionManager
if (approved) {
@ -357,7 +345,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// Add user message to history
state.chatHistory.push({ role: "user", content: userMessage });
state.displayMessages.push({ role: "user", content: userMessage });
state.unifiedHistory.push({
message: { role: "user", content: userMessage },
contextItems: [],
});
try {
// Create new abort controller for this response
@ -383,15 +374,14 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
if (lastMessage.role === "assistant" && !lastMessage.content) {
state.chatHistory.pop();
}
// Also remove partial display messages
const lastDisplayMessage =
state.displayMessages[state.displayMessages.length - 1];
// Also remove partial unified messages
const lastUnifiedMessage = state.unifiedHistory[state.unifiedHistory.length - 1];
if (
lastDisplayMessage &&
lastDisplayMessage.role === "assistant" &&
lastDisplayMessage.isStreaming
lastUnifiedMessage &&
lastUnifiedMessage.message.role === "assistant" &&
!lastUnifiedMessage.message.content
) {
state.displayMessages.pop();
state.unifiedHistory.pop();
}
} else {
logger.error(`Error: ${formatError(e)}`);
@ -401,9 +391,9 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
role: "assistant",
content: errorMessage,
});
state.displayMessages.push({
role: "assistant",
content: errorMessage,
state.unifiedHistory.push({
message: { role: "assistant", content: errorMessage },
contextItems: [],
});
}
} finally {
@ -448,163 +438,6 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
});
}
// Modified version of streamChatResponse that supports interruption
async function streamChatResponseWithInterruption(
state: ServerState,
llmApi: any,
abortController: AbortController,
shouldInterrupt: () => boolean,
): Promise<string> {
// Import the original streamChatResponse logic but add interruption checks
// Create a wrapper that checks for interruption
const originalSignal = abortController.signal;
const checkInterruption = () => {
if (shouldInterrupt() && !originalSignal.aborted) {
abortController.abort();
}
};
// Set up periodic interruption checks
const interruptionChecker = setInterval(checkInterruption, 100);
let currentStreamingMessage: DisplayMessage | null = null;
// Create callbacks to capture tool events
const callbacks: StreamCallbacks = {
onContent: (content: string) => {
if (!currentStreamingMessage) {
currentStreamingMessage = {
role: "assistant",
content: "",
isStreaming: true,
};
state.displayMessages.push(currentStreamingMessage);
}
currentStreamingMessage.content += content;
},
onContentComplete: (content: string) => {
if (currentStreamingMessage) {
currentStreamingMessage.content = content;
currentStreamingMessage.isStreaming = false;
currentStreamingMessage = null;
} else {
// Add complete assistant message
state.displayMessages.push({
role: "assistant",
content: content,
isStreaming: false,
});
}
},
onToolStart: (toolName: string, toolArgs?: any) => {
// Format tool call similar to local mode
const formatToolCall = (name: string, args: any) => {
const displayName = getToolDisplayName(name);
if (!args) return displayName;
const firstValue = Object.values(args)[0];
const formatPath = (value: any) => {
if (typeof value === "string" && path.isAbsolute(value)) {
const workspaceRoot = process.cwd();
const relativePath = path.relative(workspaceRoot, value);
return relativePath || value;
}
return value;
};
return `${displayName}(${formatPath(firstValue) || ""})`;
};
// If there was streaming content, finalize it first
if (currentStreamingMessage && currentStreamingMessage.content) {
currentStreamingMessage.isStreaming = false;
currentStreamingMessage = null;
}
state.displayMessages.push({
role: "system",
content: `○ ${formatToolCall(toolName, toolArgs)}`,
messageType: "tool-start",
toolName,
});
},
onToolResult: (result: string, toolName: string) => {
// Replace the tool-start message with tool-result
const displayName = getToolDisplayName(toolName);
// Find and replace the corresponding tool-start message
for (let i = state.displayMessages.length - 1; i >= 0; i--) {
if (
state.displayMessages[i].messageType === "tool-start" &&
state.displayMessages[i].toolName === toolName
) {
state.displayMessages[i] = {
...state.displayMessages[i],
content: `● ${displayName}`,
messageType: "tool-result",
toolResult: result,
};
return;
}
}
// If no tool-start found, add as new message (fallback)
state.displayMessages.push({
role: "system",
content: `● ${displayName}`,
messageType: "tool-result",
toolName,
toolResult: result,
});
},
onToolError: (error: string, toolName?: string) => {
state.displayMessages.push({
role: "system",
content: `✗ Tool error: ${error}`,
messageType: "tool-error",
toolName,
});
},
onToolPermissionRequest: (
toolName: string,
toolArgs: any,
requestId: string,
) => {
// Set pending permission state
state.pendingPermission = {
toolName,
toolArgs,
requestId,
timestamp: Date.now(),
};
// Add a display message indicating permission is needed
state.displayMessages.push({
role: "system",
content: `⚠️ Tool ${toolName} requires permission`,
messageType: "tool-permission-request" as any,
toolName,
});
// Don't wait here - the streamChatResponse will handle waiting
},
};
try {
const response = await streamChatResponse(
state.chatHistory,
state.model,
llmApi,
abortController,
callbacks,
);
return response || "";
} finally {
clearInterval(interruptionChecker);
// Ensure any streaming message is finalized
if (currentStreamingMessage !== null) {
// TypeScript is having issues with this line - the message will be finalized anyway
// currentStreamingMessage.isStreaming = false;
}
}
}
// Function moved to serve.helpers.ts - remove implementation
// async function streamChatResponseWithInterruption - moved to helpers {
// Implementation moved to serve.helpers.ts

View file

@ -0,0 +1,346 @@
/**
* 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.
*/
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import type {
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
MessageContent,
ToolCallState,
ToolStatus,
AssistantChatMessage,
ToolCall,
} from "../../../core/index.js";
/**
* Convert ChatCompletionMessageParam to ChatMessage
*/
export function convertToUnifiedMessage(
message: ChatCompletionMessageParam,
): ChatMessage {
switch (message.role) {
case "system":
return {
role: "system",
content: typeof message.content === "string" ? message.content : "",
};
case "user":
return {
role: "user",
content: convertMessageContent(message.content),
};
case "assistant": {
const assistantMessage: AssistantChatMessage = {
role: "assistant",
content: convertMessageContent(message.content || ""),
};
// Convert tool calls if present
if ('tool_calls' in message && message.tool_calls) {
assistantMessage.toolCalls = message.tool_calls.map((tc: any) => ({
id: tc.id,
type: "function" as const,
function: {
name: tc.function?.name || "",
arguments: tc.function?.arguments || "",
},
}));
}
return assistantMessage;
}
case "tool":
return {
role: "tool",
content: typeof message.content === "string" ? message.content : "",
toolCallId: message.tool_call_id,
};
default:
throw new Error(`Unsupported message role: ${(message as any).role}`);
}
}
/**
* Convert ChatMessage to ChatCompletionMessageParam
*/
export function convertFromUnifiedMessage(
message: ChatMessage,
): ChatCompletionMessageParam {
switch (message.role) {
case "system":
return {
role: "system",
content: message.content,
};
case "user":
return {
role: "user",
content: convertFromMessageContent(message.content),
};
case "assistant": {
const assistantMessage: ChatCompletionMessageParam = {
role: "assistant",
content: convertFromMessageContent(message.content),
};
// 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 || "",
},
}));
}
return assistantMessage;
}
case "tool":
return {
role: "tool",
content: message.content,
tool_call_id: message.toolCallId,
};
case "thinking":
// Thinking messages don't have a direct equivalent in OpenAI format
// Convert to assistant message with content
return {
role: "assistant",
content: convertFromMessageContent(message.content),
};
default:
throw new Error(`Unsupported message role: ${(message as any).role}`);
}
}
/**
* Convert OpenAI message content to unified MessageContent format
*/
function convertMessageContent(
content: string | null | Array<any>,
): MessageContent {
if (content === null) {
return "";
}
if (typeof content === "string") {
return content;
}
if (Array.isArray(content)) {
return content.map((part: any) => {
if (part.type === "text") {
return {
type: "text" as const,
text: part.text,
};
} else if (part.type === "image_url") {
return {
type: "imageUrl" as const,
imageUrl: { url: part.image_url.url },
};
}
throw new Error(`Unsupported content part type: ${part.type}`);
});
}
throw new Error(`Unsupported content type: ${typeof content}`);
}
/**
* Convert unified MessageContent to OpenAI format
*/
function convertFromMessageContent(
content: MessageContent,
): string | Array<any> {
if (typeof content === "string") {
return content;
}
if (Array.isArray(content)) {
return content.map((part: any) => {
if (part.type === "text") {
return {
type: "text",
text: part.text,
};
} else if (part.type === "imageUrl") {
return {
type: "image_url",
image_url: { url: part.imageUrl.url },
};
}
throw new Error(`Unsupported content part type: ${part.type}`);
});
}
throw new Error(`Unsupported content type: ${typeof content}`);
}
/**
* Create a ChatHistoryItem from a ChatMessage
*/
export function createHistoryItem(
message: ChatMessage,
contextItems: ContextItemWithId[] = [],
toolCallStates?: ToolCallState[],
): ChatHistoryItem {
return {
message,
contextItems,
...(toolCallStates && { toolCallStates }),
};
}
/**
* Handle tool result message by updating the corresponding tool call state
*/
function handleToolResult(
unifiedMessage: ChatMessage & { role: "tool" },
pendingToolCalls: Map<string, ToolCall>,
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"
);
if (lastAssistantIndex < 0) return;
if (!historyItems[lastAssistantIndex].toolCallStates) return;
const toolState = historyItems[lastAssistantIndex].toolCallStates?.find(
ts => ts.toolCallId === unifiedMessage.toolCallId
);
if (toolState) {
toolState.output = [{
content: unifiedMessage.content as string,
name: `Tool Result: ${toolCall.function.name}`,
description: "Tool execution result",
}];
}
}
/**
* Convert array of ChatCompletionMessageParam to ChatHistoryItem array
*/
export function convertToUnifiedHistory(
messages: ChatCompletionMessageParam[],
): ChatHistoryItem[] {
const historyItems: ChatHistoryItem[] = [];
const pendingToolCalls: Map<string, ToolCall> = new Map();
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),
};
});
historyItems.push(createHistoryItem(unifiedMessage, [], toolCallStates));
} else if (unifiedMessage.role === "tool") {
// Tool result - handle separately to reduce nesting
handleToolResult(unifiedMessage, pendingToolCalls, historyItems);
// Don't add tool messages as separate history items
} else {
historyItems.push(createHistoryItem(unifiedMessage));
}
}
return historyItems;
}
/**
* Convert ChatHistoryItem array to ChatCompletionMessageParam array
*/
export function convertFromUnifiedHistory(
historyItems: ChatHistoryItem[],
): ChatCompletionMessageParam[] {
const messages: ChatCompletionMessageParam[] = [];
for (const item of historyItems) {
const baseMessage = convertFromUnifiedMessage(item.message);
messages.push(baseMessage);
// Add tool result messages if there are completed tool calls
if (item.toolCallStates) {
for (const toolState of item.toolCallStates) {
if (toolState.output && toolState.output.length > 0) {
messages.push({
role: "tool",
content: toolState.output.map((o: any) => o.content).join("\n"),
tool_call_id: toolState.toolCallId,
});
}
}
}
}
return messages;
}
/**
* Extract tool call information from a ChatHistoryItem
*/
export function extractToolCallInfo(historyItem: ChatHistoryItem): {
hasToolCalls: boolean;
toolCalls?: ToolCall[];
toolStates?: ToolCallState[];
} {
const hasToolCalls = !!(historyItem.toolCallStates && historyItem.toolCallStates.length > 0);
return {
hasToolCalls,
toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall),
toolStates: historyItem.toolCallStates,
};
}
/**
* Helper to safely parse JSON
*/
function tryParseJson(str: string): any {
try {
return JSON.parse(str);
} catch {
return str;
}
}

View file

@ -5,7 +5,6 @@ import React from "react";
import { compactChatHistory } from "./compaction.js";
import { saveSession } from "./session.js";
import { DisplayMessage } from "./ui/types.js";
import { formatError } from "./util/formatError.js";
import { logger } from "./util/logger.js";
import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js";
@ -16,7 +15,7 @@ interface AutoCompactionCallbacks {
onContent?: (content: string) => void;
// For TUI mode
setMessages?: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setMessages?: React.Dispatch<React.SetStateAction<any>>; // Generic for compatibility
setChatHistory?: React.Dispatch<
React.SetStateAction<ChatCompletionMessageParam[]>
>;
@ -44,14 +43,7 @@ function notifyCompactionStart(
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(message);
} else if (callbacks?.setMessages) {
callbacks.setMessages((prev) => [
...prev,
{
role: "system",
content: message,
messageType: "system" as const,
},
]);
// TUI mode - handled by caller
}
}
@ -76,7 +68,7 @@ function handleCompactionSuccess(
) {
callbacks.setChatHistory(result.compactedHistory);
callbacks.setCompactionIndex(result.compactionIndex);
callbacks.setMessages((prev) => [
callbacks.setMessages((prev: any) => [
...prev,
{
role: "system",
@ -105,7 +97,7 @@ function handleCompactionError(
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(warningMessage);
} else if (callbacks?.setMessages) {
callbacks.setMessages((prev) => [
callbacks.setMessages((prev: any) => [
...prev,
{
role: "system",

View file

@ -8,6 +8,7 @@ import React, {
} from "react";
import { useServices } from "../hooks/useService.js";
import { convertFromUnifiedHistory } from "../messageConversion.js";
import {
ApiClientServiceState,
AuthServiceState,
@ -52,15 +53,15 @@ async function loadAndSetSession(
sessionId: string,
closeCurrentScreen: () => void,
setChatHistory: (history: any) => void,
setMessages: (messages: any) => void,
setShowIntroMessage: (show: boolean) => void,
) {
try {
// Close the session selector
closeCurrentScreen();
// Import session functions
// Import session functions and conversion utilities
const { loadSessionById } = await import("../session.js");
const { convertToUnifiedHistory } = await import("../messageConversion.js");
// Load the session history
const sessionHistory = loadSessionById(sessionId);
@ -75,18 +76,9 @@ async function loadAndSetSession(
"",
);
// Directly set the chat history and messages to the loaded session
setChatHistory(sessionHistory);
// Convert chat history to display messages (exclude system messages)
const displayMessages = sessionHistory
.filter((msg: any) => msg.role !== "system")
.map((msg: any) => ({
role: msg.role,
content: msg.content as string,
}));
setMessages(displayMessages);
// Convert to unified format and set the chat history
const unifiedHistory = convertToUnifiedHistory(sessionHistory);
setChatHistory(unifiedHistory);
// Clear the intro message since we're now showing a resumed session
setShowIntroMessage(false);
@ -193,8 +185,6 @@ const TUIChat: React.FC<TUIChatProps> = ({
);
const {
messages,
setMessages,
chatHistory,
setChatHistory,
isWaitingForResponse,
@ -233,7 +223,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
// Calculate context percentage
const contextData = useContextPercentage({
chatHistory,
chatHistory: convertFromUnifiedHistory(chatHistory),
model: services.model?.model || undefined,
});
@ -241,7 +231,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
const { handleConfigSelect, handleModelSelect } = useSelectors(
configPath,
setMessages,
setChatHistory,
resetChatHistory,
);
@ -252,11 +242,10 @@ const TUIChat: React.FC<TUIChatProps> = ({
sessionId,
closeCurrentScreen,
setChatHistory,
setMessages,
setShowIntroMessage,
);
},
[closeCurrentScreen, setChatHistory, setMessages, setShowIntroMessage],
[closeCurrentScreen, setChatHistory, setShowIntroMessage],
);
// Determine if input should be disabled
@ -289,7 +278,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
config={services.config?.config || undefined}
model={services.model?.model || undefined}
mcpService={services.mcp?.mcpService || undefined}
messages={messages}
chatHistory={chatHistory}
renderMessage={renderMessage}
refreshTrigger={staticRefreshTrigger}
/>

View file

@ -2,6 +2,7 @@ import { render } from "ink-testing-library";
import React from "react";
import { vi } from "vitest";
import type { ToolCallState, ChatHistoryItem } from "../../../../../core/index.js";
import { ToolPermissionSelector } from "../components/ToolPermissionSelector.js";
describe("TUIChat - Tool Permission Tests", () => {
@ -306,35 +307,63 @@ describe("TUIChat - Tool Permission Tests", () => {
const summary = summaryFrame();
expect(summary).toContain("Cancelled by user");
// Test the MemoizedMessage component with a tool-result message
const message = {
role: "assistant",
content: "Edit",
messageType: "tool-result" as const,
toolName: "Edit",
toolResult: "Permission denied by user",
// Test the MemoizedMessage component with a proper tool result in ChatHistoryItem
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
toolCall: {
id: "test-tool-call",
type: "function",
function: {
name: "Edit",
arguments: JSON.stringify({ file_path: "test.txt" }),
},
},
status: "errored", // Set to errored to show red dot
parsedArgs: { file_path: "test.txt" },
output: [
{
name: "tool_result",
content: "Permission denied by user",
description: "Tool execution denied",
},
],
};
const historyItem: ChatHistoryItem = {
message: {
role: "assistant",
content: "",
toolCalls: [
{
id: "test-tool-call",
function: {
name: "Edit",
arguments: JSON.stringify({ file_path: "test.txt" }),
},
type: "function",
},
],
},
contextItems: [],
toolCallStates: [toolCallState],
};
const { lastFrame: messageFrame } = render(
<MemoizedMessage message={message} index={0} />,
<MemoizedMessage item={historyItem} index={0} />,
);
await vi.advanceTimersByTimeAsync(100);
const messageOutput = messageFrame();
// Verify the red dot appears
// Verify the red dot appears (for failed tool call)
expect(messageOutput).toContain("●");
// Verify the tool name appears
expect(messageOutput).toContain("Edit");
// The MemoizedMessage component correctly identifies this as a failure
// because message.toolResult includes "Permission denied"
// because the tool result includes "Permission denied"
// This causes the red dot to be shown
// Verify the correct data is passed to the component
expect(message.toolResult).toBe("Permission denied by user");
expect(message.messageType).toBe("tool-result");
});
});

View file

@ -1,10 +1,9 @@
import { Server } from "http";
import express from "express";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import { describe, expect, test } from "vitest";
import { DisplayMessage } from "../types.js";
export interface MockRemoteServerConfig {
port?: number;
responses?: string[];
@ -13,7 +12,7 @@ export interface MockRemoteServerConfig {
export class MockRemoteServer {
private server: Server | null = null;
private app: express.Application;
private messages: DisplayMessage[] = [];
private messages: ChatCompletionMessageParam[] = [];
private responses: string[] = [];
private currentResponseIndex = 0;
private isProcessing = false;
@ -88,10 +87,9 @@ export class MockRemoteServer {
let charIndex = 0;
// Add initial streaming message
const streamingMessage: DisplayMessage = {
const streamingMessage: ChatCompletionMessageParam = {
role: "assistant",
content: "",
isStreaming: true,
};
this.messages.push(streamingMessage);
@ -103,7 +101,6 @@ export class MockRemoteServer {
charIndex++;
} else {
// Finish streaming
streamingMessage.isStreaming = false;
this.isProcessing = false;
if (this.streamInterval) {
@ -145,7 +142,7 @@ export class MockRemoteServer {
});
}
public getMessages(): DisplayMessage[] {
public getMessages(): ChatCompletionMessageParam[] {
return [...this.messages];
}

View file

@ -1,79 +1,36 @@
import { Box, Text } from "ink";
import React, { memo } from "react";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import { formatToolCall } from "../../tools/index.js";
import { MarkdownRenderer } from "../MarkdownRenderer.js";
import { ToolResultSummary } from "../ToolResultSummary.js";
import { DisplayMessage } from "../types.js";
interface MemoizedMessageProps {
message: DisplayMessage;
item: ChatHistoryItem;
index: number;
}
export const MemoizedMessage = memo<MemoizedMessageProps>(
({ message, index }) => {
({ item, index }) => {
const { message, toolCallStates, conversationSummary } = item;
const isUser = message.role === "user";
const isSystem = message.role === "system";
const isAssistant = message.role === "assistant";
// Handle system messages
if (isSystem) {
switch (message.messageType) {
case "tool-start":
return (
<Box key={index} marginLeft={1} marginBottom={1}>
{/* TODO: Change back to empty circle (○) with white color once we want to differentiate in-progress vs completed tool calls */}
<Text color="green">
●<Text color="white"> {message.content}</Text>
</Text>
</Box>
);
case "tool-result":
const isFailure =
message.toolResult?.startsWith("Permission denied") ||
message.toolResult?.startsWith("Error");
return (
<Box
key={index}
marginLeft={1}
marginBottom={1}
flexDirection="column"
>
<Box>
<Text color={isFailure ? "red" : "green"}>●</Text>
<Text> {message.content}</Text>
</Box>
<Box marginLeft={2}>
<ToolResultSummary
toolName={message.toolName}
content={message.toolResult || ""}
/>
</Box>
</Box>
);
case "tool-error":
return (
<Box key={index} marginLeft={1} marginBottom={1}>
<Text color="red" bold>
✗{" "}
</Text>
<Text color="red">Tool error: {message.content}</Text>
</Box>
);
default:
return (
<Box key={index} marginLeft={1} marginBottom={1}>
<Text color="gray" italic>
{message.content}
</Text>
</Box>
);
}
return (
<Box key={index} marginLeft={1} marginBottom={1}>
<Text color="gray" italic>
{message.content}
</Text>
</Box>
);
}
// Special rendering for compaction messages
if (message.messageType === "compaction") {
// Handle conversation summary (compaction)
if (conversationSummary) {
return (
<Box
key={index}
@ -87,35 +44,91 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
/>
);
}
// Handle tool calls
if (toolCallStates && toolCallStates.length > 0) {
return (
<Box key={index} flexDirection="column">
{/* Render assistant message content if any */}
{message.content && (
<Box marginLeft={1} marginBottom={1}>
<Text color="white">●</Text>
<Text> </Text>
<MarkdownRenderer content={message.content as string} />
</Box>
)}
{/* 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 (
<Box key={toolIndex} flexDirection="column">
<Box marginLeft={1} marginBottom={1}>
<Text color={isErrored ? "red" : isCompleted ? "green" : "white"}>
{isCompleted || isErrored ? "●" : "○"}
</Text>
<Text color="white"> {formatToolCall(toolName, toolArgs)}</Text>
</Box>
{/* Show tool result if available */}
{toolState.output && toolState.output.length > 0 && (
<Box marginLeft={3}>
<ToolResultSummary
toolName={toolName}
content={toolState.output.map(o => o.content).join("\n")}
/>
</Box>
)}
{/* Show error if tool errored */}
{isErrored && !toolState.output && (
<Box marginLeft={3}>
<Text color="red">Tool execution failed</Text>
</Box>
)}
</Box>
);
})}
</Box>
);
}
// Handle regular messages
const isStreaming = isAssistant && !message.content && !toolCallStates;
return (
<Box key={index} marginLeft={1} marginBottom={1}>
<Text color={isUser ? "green" : "white"}>●</Text>
<Text> </Text>
{isUser ? (
<Text color="gray">{message.content}</Text>
<Text color="gray">{typeof message.content === 'string' ? message.content : JSON.stringify(message.content)}</Text>
) : (
<MarkdownRenderer content={message.content} />
<MarkdownRenderer content={typeof message.content === 'string' ? message.content : JSON.stringify(message.content)} />
)}
{message.isStreaming && <Text color="gray">▋</Text>}
{isStreaming && <Text color="gray">▋</Text>}
</Box>
);
},
(prevProps, nextProps) => {
// Custom comparison function for better performance
// Only re-render if these properties change
const prevMessage = prevProps.item.message;
const nextMessage = nextProps.item.message;
const prevToolStates = prevProps.item.toolCallStates;
const nextToolStates = nextProps.item.toolCallStates;
return (
prevProps.message.content === nextProps.message.content &&
prevProps.message.role === nextProps.message.role &&
prevProps.message.messageType === nextProps.message.messageType &&
prevProps.message.isStreaming === nextProps.message.isStreaming &&
prevProps.message.toolName === nextProps.message.toolName &&
prevProps.message.toolResult === nextProps.message.toolResult &&
prevProps.message.permissionRequestId ===
nextProps.message.permissionRequestId &&
prevMessage.content === nextMessage.content &&
prevMessage.role === nextMessage.role &&
JSON.stringify(prevToolStates) === JSON.stringify(nextToolStates) &&
prevProps.item.conversationSummary === nextProps.item.conversationSummary &&
prevProps.index === nextProps.index
);
},
);
MemoizedMessage.displayName = "MemoizedMessage";
MemoizedMessage.displayName = "MemoizedMessage";

View file

@ -2,18 +2,18 @@ import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { Static, useStdout } from "ink";
import React, { useCallback, useEffect, useRef, useState } from "react";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import type { MCPService } from "../../services/MCPService.js";
import { useTerminalSize } from "../hooks/useTerminalSize.js";
import { IntroMessage } from "../IntroMessage.js";
import type { DisplayMessage } from "../types.js";
interface StaticChatContentProps {
showIntroMessage: boolean;
config?: AssistantUnrolled;
model?: ModelConfig;
mcpService?: MCPService;
messages: DisplayMessage[];
renderMessage: (message: DisplayMessage, index: number) => React.ReactElement;
chatHistory: ChatHistoryItem[];
renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement;
refreshTrigger?: number; // Add a prop to trigger refresh from parent
}
@ -22,7 +22,7 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
config,
model,
mcpService,
messages,
chatHistory,
renderMessage,
refreshTrigger,
}) => {
@ -81,13 +81,15 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
);
}
// Add all chat messages
messages.forEach((message, index) => {
items.push(renderMessage(message, index));
});
// Add all chat messages (filter out system messages)
chatHistory
.filter(item => item.message.role !== "system" || item.message.content) // Keep non-empty system messages
.forEach((item, index) => {
items.push(renderMessage(item, index));
});
return items;
}, [showIntroMessage, config, model, mcpService, messages, renderMessage]);
}, [showIntroMessage, config, model, mcpService, chatHistory, renderMessage]);
return (
<Static
@ -101,4 +103,4 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
{(item) => item}
</Static>
);
};
};

View file

@ -1,27 +1,30 @@
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<typeof vi.fn>;
let mockSetMessages: ReturnType<typeof vi.fn>;
let mockExit: ReturnType<typeof vi.fn>;
let mockOnClear: ReturnType<typeof vi.fn>;
beforeEach(() => {
mockSetChatHistory = vi.fn();
mockSetMessages = vi.fn();
mockExit = vi.fn();
mockOnClear = vi.fn();
});
it("should call onClear callback when processing clear command", () => {
const chatHistory: ChatCompletionMessageParam[] = [
const legacyHistory: ChatCompletionMessageParam[] = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there!" },
];
const chatHistory = convertToUnifiedHistory(legacyHistory);
const result = {
clear: true,
@ -32,7 +35,6 @@ describe("useChat clear command", () => {
result,
chatHistory,
setChatHistory: mockSetChatHistory,
setMessages: mockSetMessages,
exit: mockExit,
onShowConfigSelector: vi.fn(),
onClear: mockOnClear,
@ -43,18 +45,27 @@ describe("useChat clear command", () => {
// Verify that chat history was reset (keeping only system message)
expect(mockSetChatHistory).toHaveBeenCalledWith([
{ role: "system", content: "You are a helpful assistant" },
chatHistory[0], // The system message ChatHistoryItem
]);
// Verify that messages were cleared
expect(mockSetMessages).toHaveBeenCalledWith([]);
// Second call should be with the "Chat history cleared" message
expect(mockSetChatHistory).toHaveBeenLastCalledWith([
{
message: {
role: "system",
content: "Chat history cleared",
},
contextItems: [],
},
]);
});
it("should not call onClear if callback is not provided", () => {
const chatHistory: ChatCompletionMessageParam[] = [
const legacyHistory: ChatCompletionMessageParam[] = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "Hello" },
];
const chatHistory = convertToUnifiedHistory(legacyHistory);
const result = {
clear: true,
@ -66,18 +77,16 @@ describe("useChat clear command", () => {
result,
chatHistory,
setChatHistory: mockSetChatHistory,
setMessages: mockSetMessages,
exit: mockExit,
exit: mockExit,
onShowConfigSelector: vi.fn(),
// onClear is not provided
});
}).not.toThrow();
// Verify that history and messages are still reset
// Verify that history is still reset
expect(mockSetChatHistory).toHaveBeenCalledWith([
{ role: "system", content: "You are a helpful assistant" },
chatHistory[0], // The system message ChatHistoryItem
]);
expect(mockSetMessages).toHaveBeenCalledWith([]);
});
it("should preserve system message when clearing", () => {
@ -85,11 +94,13 @@ describe("useChat clear command", () => {
role: "system",
content: "Custom system message",
};
const chatHistory: ChatCompletionMessageParam[] = [
const legacyHistory: ChatCompletionMessageParam[] = [
systemMessage,
{ role: "user", content: "Test message" },
{ role: "assistant", content: "Test response" },
];
const chatHistory = convertToUnifiedHistory(legacyHistory);
const systemHistoryItem = chatHistory[0];
const result = { clear: true };
@ -97,26 +108,25 @@ describe("useChat clear command", () => {
result,
chatHistory,
setChatHistory: mockSetChatHistory,
setMessages: mockSetMessages,
exit: mockExit,
onShowConfigSelector: vi.fn(),
onClear: mockOnClear,
});
// Should keep only the system message
expect(mockSetChatHistory).toHaveBeenCalledWith([systemMessage]);
expect(mockSetChatHistory).toHaveBeenCalledWith([systemHistoryItem]);
expect(mockOnClear).toHaveBeenCalledOnce();
});
it("should handle clear with empty chat history", () => {
const chatHistory: ChatCompletionMessageParam[] = [];
const legacyHistory: ChatCompletionMessageParam[] = [];
const chatHistory = convertToUnifiedHistory(legacyHistory);
const result = { clear: true };
processSlashCommandResult({
result,
chatHistory,
setChatHistory: mockSetChatHistory,
setMessages: mockSetMessages,
exit: mockExit,
onShowConfigSelector: vi.fn(),
onClear: mockOnClear,
@ -124,7 +134,6 @@ describe("useChat clear command", () => {
// Should set empty history when no system message exists
expect(mockSetChatHistory).toHaveBeenCalledWith([]);
expect(mockSetMessages).toHaveBeenCalledWith([]);
expect(mockOnClear).toHaveBeenCalledOnce();
});
});

View file

@ -1,13 +1,12 @@
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import { initializeChatHistory } from "../../commands/chat.js";
import { compactChatHistory } from "../../compaction.js";
import { convertToUnifiedHistory, convertFromUnifiedHistory } from "../../messageConversion.js";
import { loadSession, saveSession } from "../../session.js";
import { posthogService } from "../../telemetry/posthogService.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import { formatError } from "../../util/formatError.js";
import { logger } from "../../util/logger.js";
import { DisplayMessage } from "../types.js";
import { SlashCommandResult } from "./useChat.types.js";
@ -17,11 +16,11 @@ import { SlashCommandResult } from "./useChat.types.js";
export async function initChatHistory(
resume?: boolean,
additionalRules?: string[],
): Promise<ChatCompletionMessageParam[]> {
): Promise<ChatHistoryItem[]> {
if (resume) {
const savedHistory = loadSession();
if (savedHistory) {
return savedHistory;
return convertToUnifiedHistory(savedHistory);
}
}
@ -29,7 +28,7 @@ export async function initChatHistory(
resume,
rule: additionalRules,
});
return history;
return convertToUnifiedHistory(history);
}
/**
@ -43,13 +42,12 @@ export function handleConfigCommand(onShowConfigSelector: () => void): void {
}
interface HandleCompactCommandOptions {
chatHistory: ChatCompletionMessageParam[];
chatHistory: ChatHistoryItem[];
model: any;
llmApi: any;
setChatHistory: React.Dispatch<
React.SetStateAction<ChatCompletionMessageParam[]>
React.SetStateAction<ChatHistoryItem[]>
>;
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
}
@ -61,44 +59,55 @@ export async function handleCompactCommand({
model,
llmApi,
setChatHistory,
setMessages,
setCompactionIndex,
}: HandleCompactCommandOptions): Promise<void> {
setMessages((prev) => [
// Add compacting message
setChatHistory((prev) => [
...prev,
{
role: "system",
content: "Compacting chat history...",
messageType: "system" as const,
message: {
role: "system",
content: "Compacting chat history...",
},
contextItems: [],
},
]);
try {
const result = await compactChatHistory(chatHistory, model, llmApi);
// Convert to legacy format for compaction
const legacyHistory = convertFromUnifiedHistory(chatHistory);
const result = await compactChatHistory(legacyHistory, model, llmApi);
// Convert compacted history back to unified format
const compactedUnifiedHistory = convertToUnifiedHistory(result.compactedHistory);
// Replace chat history with compacted version
setChatHistory(result.compactedHistory);
setChatHistory(compactedUnifiedHistory);
setCompactionIndex(result.compactionIndex);
// Save the compacted session
saveSession(result.compactedHistory);
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: "Chat history compacted successfully.",
messageType: "system" as const,
message: {
role: "system",
content: "Chat history compacted successfully.",
},
contextItems: [],
},
]);
} catch (error) {
logger.error("Compaction failed:", error);
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: `Compaction failed: ${formatError(error)}`,
messageType: "system" as const,
message: {
role: "system",
content: `Compaction failed: ${formatError(error)}`,
},
contextItems: [],
},
]);
}
@ -106,11 +115,10 @@ export async function handleCompactCommand({
interface ProcessSlashCommandResultOptions {
result: SlashCommandResult;
chatHistory: ChatCompletionMessageParam[];
chatHistory: ChatHistoryItem[];
setChatHistory: React.Dispatch<
React.SetStateAction<ChatCompletionMessageParam[]>
React.SetStateAction<ChatHistoryItem[]>
>;
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
exit: () => void;
onShowConfigSelector: () => void;
onShowModelSelector?: () => void;
@ -126,7 +134,6 @@ export function processSlashCommandResult({
result,
chatHistory,
setChatHistory,
setMessages,
exit,
onShowConfigSelector,
onShowModelSelector,
@ -160,10 +167,9 @@ export function processSlashCommandResult({
}
if (result.clear) {
const systemMessage = chatHistory.find((msg) => msg.role === "system");
const systemMessage = chatHistory.find((item) => item.message.role === "system");
const newHistory = systemMessage ? [systemMessage] : [];
setChatHistory(newHistory);
setMessages([]);
// Reset intro message state to show it again after clearing
if (onClear) {
@ -171,11 +177,13 @@ export function processSlashCommandResult({
}
if (result.output) {
setMessages([
setChatHistory([
{
role: "system",
content: result.output,
messageType: "system" as const,
message: {
role: "system",
content: result.output,
},
contextItems: [],
},
]);
}
@ -183,13 +191,15 @@ export function processSlashCommandResult({
}
if (result.output) {
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system" as const,
content: result.output || "",
messageType: "system" as const,
} as DisplayMessage,
message: {
role: "system",
content: result.output || "",
},
contextItems: [],
},
]);
}
@ -232,7 +242,7 @@ interface HandleSpecialCommandsOptions {
remoteUrl?: string;
onShowConfigSelector: () => void;
exit: () => void;
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
}
/**
@ -244,7 +254,7 @@ export async function handleSpecialCommands({
remoteUrl,
onShowConfigSelector,
exit,
setMessages,
setChatHistory,
}: HandleSpecialCommandsOptions): Promise<boolean> {
const trimmedMessage = message.trim();
@ -257,7 +267,7 @@ export async function handleSpecialCommands({
// Handle /exit command in remote mode
if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") {
const { handleRemoteExit } = await import("./useChat.remote.helpers.js");
await handleRemoteExit(remoteUrl, setMessages, exit);
await handleRemoteExit(remoteUrl, setChatHistory, exit);
return true;
}
@ -265,13 +275,12 @@ export async function handleSpecialCommands({
}
interface HandleAutoCompactionOptions {
chatHistory: ChatCompletionMessageParam[];
chatHistory: ChatHistoryItem[];
model: any;
llmApi: any;
compactionIndex: number | null;
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setChatHistory: React.Dispatch<
React.SetStateAction<ChatCompletionMessageParam[]>
React.SetStateAction<ChatHistoryItem[]>
>;
setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
}
@ -284,28 +293,49 @@ export async function handleAutoCompaction({
model,
llmApi,
compactionIndex: _compactionIndex,
setMessages,
setChatHistory,
setCompactionIndex,
}: HandleAutoCompactionOptions): Promise<{
currentChatHistory: ChatCompletionMessageParam[];
currentChatHistory: ChatHistoryItem[];
currentCompactionIndex: number | null;
}> {
const { handleAutoCompaction: coreAutoCompaction } = await import(
"../../streamChatResponse.autoCompaction.js"
);
const result = await coreAutoCompaction(chatHistory, model, llmApi, {
// Convert to legacy format for compaction
const legacyHistory = convertFromUnifiedHistory(chatHistory);
const result = await coreAutoCompaction(legacyHistory, model, llmApi, {
isHeadless: false,
callbacks: {
setMessages,
setChatHistory,
setMessages: (updater: any) => {
// Convert messages updates to chat history updates
if (typeof updater === 'function') {
setChatHistory((prev) => {
// For now, just return prev - compaction messages will be handled separately
return prev;
});
}
},
setChatHistory: (updater: any) => {
// Handle chat history updates
if (typeof updater === 'function') {
setChatHistory((prev) => {
const legacyPrev = convertFromUnifiedHistory(prev);
const updated = updater(legacyPrev);
return convertToUnifiedHistory(updated);
});
} else {
setChatHistory(convertToUnifiedHistory(updater));
}
},
setCompactionIndex,
},
});
return {
currentChatHistory: result.chatHistory,
currentChatHistory: convertToUnifiedHistory(result.chatHistory),
currentCompactionIndex: result.compactionIndex,
};
}
}

View file

@ -1,8 +1,7 @@
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import { convertToUnifiedHistory } from "../../messageConversion.js";
import { posthogService } from "../../telemetry/posthogService.js";
import { logger } from "../../util/logger.js";
import { DisplayMessage } from "../types.js";
import { RemoteServerState } from "./useChat.types.js";
@ -26,9 +25,8 @@ async function pollRemoteServerState(
interface SetupRemotePollingOptions {
remoteUrl: string;
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setChatHistory: React.Dispatch<
React.SetStateAction<ChatCompletionMessageParam[]>
React.SetStateAction<ChatHistoryItem[]>
>;
setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>;
responseStartTime: number | null;
@ -40,7 +38,6 @@ interface SetupRemotePollingOptions {
*/
export function setupRemotePolling({
remoteUrl,
setMessages,
setChatHistory,
setIsWaitingForResponse,
responseStartTime,
@ -59,7 +56,6 @@ export function setupRemotePolling({
if (state && isMounted) {
updateStateFromRemote({
state,
setMessages,
setChatHistory,
setIsWaitingForResponse,
responseStartTime,
@ -87,9 +83,8 @@ export function setupRemotePolling({
interface UpdateStateFromRemoteOptions {
state: RemoteServerState;
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setChatHistory: React.Dispatch<
React.SetStateAction<ChatCompletionMessageParam[]>
React.SetStateAction<ChatHistoryItem[]>
>;
setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>;
responseStartTime: number | null;
@ -101,61 +96,35 @@ interface UpdateStateFromRemoteOptions {
*/
function updateStateFromRemote({
state,
setMessages,
setChatHistory,
setIsWaitingForResponse,
responseStartTime,
setResponseStartTime,
}: UpdateStateFromRemoteOptions): void {
// Update messages from server
// Update chat history from server
if (state.chatHistory) {
setMessages((prevMessages) => {
setChatHistory((prevHistory) => {
// Convert server's legacy format to unified format
const newHistory = convertToUnifiedHistory(state.chatHistory);
// Quick length check first
if (prevMessages.length !== state.chatHistory.length) {
return state.chatHistory as DisplayMessage[];
if (prevHistory.length !== newHistory.length) {
return newHistory;
}
// Deep comparison - check if content actually changed
const hasChanged = state.chatHistory.some((msg: any, index: number) => {
const prevMsg = prevMessages[index];
const hasChanged = newHistory.some((item, index) => {
const prevItem = prevHistory[index];
return (
!prevMsg ||
prevMsg.role !== msg.role ||
prevMsg.content !== msg.content ||
prevMsg.messageType !== msg.messageType ||
prevMsg.toolName !== msg.toolName ||
prevMsg.toolResult !== msg.toolResult
!prevItem ||
prevItem.message.role !== item.message.role ||
prevItem.message.content !== item.message.content ||
JSON.stringify(prevItem.toolCallStates) !== JSON.stringify(item.toolCallStates)
);
});
// Only update if there are actual changes
return hasChanged
? (state.chatHistory as DisplayMessage[])
: prevMessages;
});
// Also update chat history for consistency
setChatHistory((prevChatHistory) => {
const newChatHistory = state.chatHistory.map((msg: any) => ({
role: msg.role,
content: msg.content,
}));
// Similar comparison for chat history
if (prevChatHistory.length !== newChatHistory.length) {
return newChatHistory;
}
const hasChanged = newChatHistory.some((msg: any, index: number) => {
const prevMsg = prevChatHistory[index];
return (
!prevMsg ||
prevMsg.role !== msg.role ||
prevMsg.content !== msg.content
);
});
return hasChanged ? newChatHistory : prevChatHistory;
return hasChanged ? newHistory : prevHistory;
});
}
@ -173,7 +142,7 @@ function updateStateFromRemote({
*/
export async function handleRemoteExit(
remoteUrl: string,
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>,
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>,
exit: () => void,
): Promise<void> {
posthogService.capture("useSlashCommand", {
@ -186,35 +155,41 @@ export async function handleRemoteExit(
});
if (response.ok) {
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: "Remote environment is shutting down...",
messageType: "system" as const,
message: {
role: "system",
content: "Remote environment is shutting down...",
},
contextItems: [],
},
]);
setTimeout(() => exit(), 1000);
} else {
const text = await response.text();
logger.error("Remote shutdown failed:", text);
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: "Failed to shutdown remote environment",
messageType: "system" as const,
message: {
role: "system",
content: "Failed to shutdown remote environment",
},
contextItems: [],
},
]);
}
} catch (error) {
logger.error("Failed to send exit request to remote server:", error);
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: "Error: Failed to connect to remote server for shutdown",
messageType: "system" as const,
message: {
role: "system",
content: "Error: Failed to connect to remote server for shutdown",
},
contextItems: [],
},
]);
}
@ -223,7 +198,7 @@ export async function handleRemoteExit(
interface HandleRemoteMessageOptions {
remoteUrl: string;
messageContent: string;
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
}
/**
@ -232,7 +207,7 @@ interface HandleRemoteMessageOptions {
export async function handleRemoteMessage({
remoteUrl,
messageContent,
setMessages,
setChatHistory,
}: HandleRemoteMessageOptions): Promise<void> {
try {
const response = await fetch(`${remoteUrl}/message`, {
@ -245,25 +220,29 @@ export async function handleRemoteMessage({
if (!response.ok) {
const error = await response.json();
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: `Error: ${error.error || "Failed to send message"}`,
messageType: "system" as const,
message: {
role: "system",
content: `Error: ${error.error || "Failed to send message"}`,
},
contextItems: [],
},
]);
}
// State will be updated by polling
} catch (error) {
logger.error("Failed to send message to remote server:", error);
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: `Error: Failed to connect to remote server`,
messageType: "system" as const,
message: {
role: "system",
content: `Error: Failed to connect to remote server`,
},
contextItems: [],
},
]);
}
}
}

View file

@ -1,10 +1,8 @@
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { formatToolCall } from "../../tools/index.js";
import { DisplayMessage } from "../types.js";
import type { ChatHistoryItem, ToolCallState } from "../../../../../core/index.js";
import { convertFromUnifiedHistory } from "../../messageConversion.js";
interface CreateStreamCallbacksOptions {
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
setActivePermissionRequest: React.Dispatch<React.SetStateAction<any>>;
}
@ -13,91 +11,159 @@ interface CreateStreamCallbacksOptions {
*/
export function createStreamCallbacks(
options: CreateStreamCallbacksOptions,
currentStreamingMessageRef: { current: any },
): any {
const { setMessages, setActivePermissionRequest } = options;
const { setChatHistory, setActivePermissionRequest } = options;
return {
onContent: (content: string) => {
if (!currentStreamingMessageRef.current) {
currentStreamingMessageRef.current = {
role: "assistant",
content: "",
isStreaming: true,
};
}
currentStreamingMessageRef.current.content += content;
},
onContent: (_: string) => {},
onContentComplete: (content: string) => {
if (currentStreamingMessageRef.current) {
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "assistant",
content: content,
isStreaming: false,
contextItems: [],
message: {
role: "assistant",
content: content,
isStreaming: false,
}
},
]);
currentStreamingMessageRef.current = null;
}
},
onToolStart: (toolName: string, toolArgs?: any) => {
if (
currentStreamingMessageRef.current &&
currentStreamingMessageRef.current.content
) {
const messageContent = currentStreamingMessageRef.current.content;
setMessages((prev) => [
...prev,
{
role: "assistant",
content: messageContent,
isStreaming: false,
},
]);
currentStreamingMessageRef.current = null;
}
setMessages((prev) => [
...prev,
{
role: "system",
content: formatToolCall(toolName, toolArgs),
messageType: "tool-start",
toolName,
},
]);
},
onToolResult: (result: string, toolName: string) => {
setMessages((prev) => {
const newMessages = [...prev];
for (let i = newMessages.length - 1; i >= 0; i--) {
if (
newMessages[i].messageType === "tool-start" &&
newMessages[i].toolName === toolName
) {
newMessages[i] = {
...newMessages[i],
messageType: "tool-result",
toolResult: result,
};
break;
onToolStart: (toolName: string, toolArgs?: any) => {
setChatHistory((prev) => {
const newHistory = [...prev];
const lastItem = newHistory[newHistory.length - 1];
// If we have an assistant message, add tool call to it
if (lastItem?.message.role === "assistant") {
// Initialize tool call states if not present
if (!lastItem.toolCallStates) {
lastItem.toolCallStates = [];
}
// Add new tool call state
const toolCallState: ToolCallState = {
toolCallId: `tool_${Date.now()}`,
toolCall: {
id: `tool_${Date.now()}`,
type: "function",
function: {
name: toolName,
arguments: JSON.stringify(toolArgs || {}),
},
},
status: "calling",
parsedArgs: toolArgs,
};
lastItem.toolCallStates.push(toolCallState);
} else {
// Create new assistant message with tool call
const toolCallState: ToolCallState = {
toolCallId: `tool_${Date.now()}`,
toolCall: {
id: `tool_${Date.now()}`,
type: "function",
function: {
name: toolName,
arguments: JSON.stringify(toolArgs || {}),
},
},
status: "calling",
parsedArgs: toolArgs,
};
newHistory.push({
message: {
role: "assistant",
content: "",
toolCalls: [{
id: toolCallState.toolCallId,
type: "function",
function: {
name: toolName,
arguments: JSON.stringify(toolArgs || {}),
},
}],
},
contextItems: [],
toolCallStates: [toolCallState],
});
}
return newMessages;
return newHistory;
});
},
onToolError: (error: string, toolName?: string) => {
setMessages((prev) => [
...prev,
{
role: "system",
content: error,
messageType: "tool-error",
toolName,
},
]);
onToolResult: (result: string, toolName: string) => {
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"
);
if (toolState) {
toolState.status = "done";
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"
);
if (toolState) {
toolState.status = "errored";
toolState.output = [{
content: error,
name: `Tool Error: ${toolName}`,
description: "Tool execution error",
}];
break;
}
}
}
} else {
// General error message
newHistory.push({
message: {
role: "system",
content: error,
},
contextItems: [],
});
}
return newHistory;
});
},
onToolPermissionRequest: (
toolName: string,
toolArgs: any,
@ -111,13 +177,16 @@ export function createStreamCallbacks(
toolCallPreview,
});
},
onSystemMessage: (message: string) => {
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: message,
messageType: "system" as const,
message: {
role: "system",
content: message,
},
contextItems: [],
},
]);
},
@ -125,7 +194,7 @@ export function createStreamCallbacks(
}
interface ExecuteStreamingOptions {
newHistory: ChatCompletionMessageParam[];
chatHistory: ChatHistoryItem[];
model: any;
llmApi: any;
controller: AbortController;
@ -137,7 +206,7 @@ interface ExecuteStreamingOptions {
* Execute streaming chat response
*/
export async function executeStreaming({
newHistory,
chatHistory,
model,
llmApi,
controller,
@ -146,18 +215,21 @@ export async function executeStreaming({
}: ExecuteStreamingOptions): Promise<void> {
const { getHistoryForLLM } = await import("../../compaction.js");
const { streamChatResponse } = await import("../../streamChatResponse.js");
// Convert to legacy format for LLM
const legacyHistory = convertFromUnifiedHistory(chatHistory);
if (model && llmApi) {
if (
currentCompactionIndex !== null &&
currentCompactionIndex !== undefined
) {
const historyForLLM = getHistoryForLLM(
newHistory,
legacyHistory,
currentCompactionIndex,
);
const originalLength = historyForLLM.length;
await streamChatResponse(
historyForLLM,
model,
@ -165,12 +237,12 @@ export async function executeStreaming({
controller,
streamCallbacks,
);
const newMessages = historyForLLM.slice(originalLength);
newHistory.push(...newMessages);
legacyHistory.push(...newMessages);
} else {
await streamChatResponse(
newHistory,
legacyHistory,
model,
llmApi,
controller,
@ -178,4 +250,4 @@ export async function executeStreaming({
);
}
}
}
}

View file

@ -0,0 +1,115 @@
import { describe, expect, it, vi } from "vitest";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import { createStreamCallbacks } from "./useChat.stream.helpers.js";
describe("useChat streaming", () => {
it("should progressively update assistant message content during streaming", () => {
let chatHistory: ChatHistoryItem[] = [];
const setChatHistory = vi.fn((updater: any) => {
if (typeof updater === "function") {
chatHistory = updater(chatHistory);
} else {
chatHistory = updater;
}
});
const callbacks = createStreamCallbacks({
setChatHistory,
setActivePermissionRequest: vi.fn(),
});
// Simulate streaming content
callbacks.onContent("Hello");
expect(setChatHistory).toHaveBeenCalledTimes(1);
expect(chatHistory).toHaveLength(1);
expect(chatHistory[0].message.content).toBe("Hello");
callbacks.onContent(" world");
expect(setChatHistory).toHaveBeenCalledTimes(2);
expect(chatHistory).toHaveLength(1);
expect(chatHistory[0].message.content).toBe("Hello world");
callbacks.onContent("!");
expect(setChatHistory).toHaveBeenCalledTimes(3);
expect(chatHistory).toHaveLength(1);
expect(chatHistory[0].message.content).toBe("Hello world!");
// Complete the streaming
callbacks.onContentComplete("Hello world!");
expect(setChatHistory).toHaveBeenCalledTimes(4);
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);
} else {
chatHistory = updater;
}
});
const callbacks = createStreamCallbacks({
setChatHistory,
setActivePermissionRequest: vi.fn(),
});
// Start with some content
callbacks.onContent("Let me help you with that.");
expect(chatHistory).toHaveLength(1);
expect(chatHistory[0].message.content).toBe("Let me help you with that.");
// Complete content before tool call
callbacks.onContentComplete("Let me help you with that.");
// Now a tool call
callbacks.onToolStart("Read", { file_path: "/test.txt" });
expect(chatHistory).toHaveLength(1);
expect(chatHistory[0].toolCallStates).toHaveLength(1);
expect(chatHistory[0].toolCallStates![0].status).toBe("calling");
// Tool result
callbacks.onToolResult("File contents", "Read");
expect(chatHistory[0].toolCallStates![0].status).toBe("done");
// More content after tool creates a new message
// (because the previous message has tool calls)
callbacks.onContent("Based on the file");
expect(chatHistory).toHaveLength(2);
expect(chatHistory[1].message.role).toBe("assistant");
expect(chatHistory[1].message.content).toBe("Based on the file");
});
it("should create new message if last message is not assistant", () => {
let chatHistory: ChatHistoryItem[] = [
{
message: { role: "user", content: "Hello" },
contextItems: [],
},
];
const setChatHistory = vi.fn((updater: any) => {
if (typeof updater === "function") {
chatHistory = updater(chatHistory);
} else {
chatHistory = updater;
}
});
const callbacks = createStreamCallbacks({
setChatHistory,
setActivePermissionRequest: vi.fn(),
});
callbacks.onContent("Hi there");
expect(chatHistory).toHaveLength(2);
expect(chatHistory[1].message.role).toBe("assistant");
expect(chatHistory[1].message.content).toBe("Hi there");
});
});

View file

@ -1,8 +1,9 @@
import { useApp } from "ink";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { useEffect, useState } from "react";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import { findCompactionIndex } from "../../compaction.js";
import { convertToUnifiedHistory, convertFromUnifiedHistory } from "../../messageConversion.js";
import { toolPermissionManager } from "../../permissions/permissionManager.js";
import { services } from "../../services/index.js";
import { loadSession, saveSession } from "../../session.js";
@ -10,7 +11,6 @@ import { handleSlashCommands } from "../../slashCommands.js";
import { telemetryService } from "../../telemetry/telemetryService.js";
import { formatError } from "../../util/formatError.js";
import { logger } from "../../util/logger.js";
import { DisplayMessage } from "../types.js";
import {
formatMessageWithFiles,
@ -54,7 +54,7 @@ export function useChat({
}: UseChatProps) {
const { exit } = useApp();
const [chatHistory, setChatHistory] = useState<ChatCompletionMessageParam[]>(
const [chatHistory, setChatHistory] = useState<ChatHistoryItem[]>(
() => {
// In remote mode, start with empty history (will be populated by polling)
if (isRemoteMode) {
@ -65,25 +65,16 @@ export function useChat({
// Load previous session if resume flag is used
// If no session loaded or not resuming, we'll need to add system message
// We can't make this async, so we'll handle it in the useEffect
return resume ? (loadSession() ?? []) : [];
if (resume) {
const savedHistory = loadSession();
if (savedHistory) {
return convertToUnifiedHistory(savedHistory);
}
}
return [];
},
);
const [messages, setMessages] = useState<DisplayMessage[]>(() => {
if (resume) {
const savedHistory = loadSession();
if (savedHistory) {
return savedHistory
.filter((msg) => msg.role !== "system")
.map((msg) => ({
role: msg.role,
content: msg.content as string,
}));
}
}
return [];
});
const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
const [responseStartTime, setResponseStartTime] = useState<number | null>(
null,
@ -128,7 +119,6 @@ export function useChat({
return setupRemotePolling({
remoteUrl,
setMessages,
setChatHistory,
setIsWaitingForResponse,
responseStartTime,
@ -187,7 +177,7 @@ export function useChat({
}, [initialPrompt, additionalPrompts, isChatHistoryInitialized]);
const executeStreamingResponse = async (
newHistory: ChatCompletionMessageParam[],
newHistory: ChatHistoryItem[],
currentCompactionIndex: number | null,
message: string,
) => {
@ -208,17 +198,13 @@ export function useChat({
});
try {
const currentStreamingMessageRef = {
current: null as DisplayMessage | null,
};
const streamCallbacks = createStreamCallbacks(
{ setMessages, setActivePermissionRequest },
currentStreamingMessageRef,
{ setChatHistory, setActivePermissionRequest }
);
// Execute streaming chat response
await executeStreaming({
newHistory,
chatHistory: newHistory,
model,
llmApi,
controller,
@ -226,39 +212,21 @@ export function useChat({
currentCompactionIndex,
});
if (
currentStreamingMessageRef.current &&
currentStreamingMessageRef.current.content
) {
const messageContent = currentStreamingMessageRef.current.content;
setMessages((prev) => [
...prev,
{
role: "assistant",
content: messageContent,
isStreaming: false,
},
]);
}
// Update the chat history with the complete conversation after streaming
setChatHistory(newHistory);
logger.debug("Chat history updated", {
finalHistoryLength: newHistory.length,
});
// Save the updated history to session
logger.debug("Saving session", { historyLength: newHistory.length });
saveSession(newHistory);
const legacyHistory = convertFromUnifiedHistory(newHistory);
saveSession(legacyHistory);
logger.debug("Session saved");
} catch (error: any) {
const errorMessage = `Error: ${formatError(error)}`;
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: errorMessage,
messageType: "system" as const,
message: {
role: "system",
content: errorMessage,
},
contextItems: [],
},
]);
} finally {
@ -280,7 +248,7 @@ export function useChat({
remoteUrl,
onShowConfigSelector,
exit,
setMessages,
setChatHistory,
});
if (handled) return;
@ -295,7 +263,6 @@ export function useChat({
model,
llmApi,
setChatHistory,
setMessages,
setCompactionIndex,
});
return;
@ -305,7 +272,6 @@ export function useChat({
result: commandResult,
chatHistory,
setChatHistory,
setMessages,
exit,
onShowConfigSelector,
onShowModelSelector,
@ -336,7 +302,7 @@ export function useChat({
await handleRemoteMessage({
remoteUrl,
messageContent,
setMessages,
setChatHistory,
});
return;
}
@ -348,19 +314,20 @@ export function useChat({
model,
llmApi,
compactionIndex,
setMessages,
setChatHistory,
setCompactionIndex,
});
// NOW add user message to history and UI
const newUserMessage: ChatCompletionMessageParam = {
role: "user",
content: messageContent,
// NOW add user message to history
const newUserMessage: ChatHistoryItem = {
message: {
role: "user",
content: messageContent,
},
contextItems: [],
};
const newHistory = [...currentChatHistory, newUserMessage];
setChatHistory(newHistory);
setMessages((prev) => [...prev, { role: "user", content: message }]);
// Execute the streaming response
await executeStreamingResponse(newHistory, currentCompactionIndex, message);
@ -385,12 +352,14 @@ export function useChat({
// Local mode: abort the controller
if (abortController && isWaitingForResponse) {
abortController.abort();
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content: "[Interrupted by user]",
messageType: "system" as const,
message: {
role: "system",
content: "[Interrupted by user]",
},
contextItems: [],
},
]);
}
@ -406,7 +375,6 @@ export function useChat({
additionalRules,
);
setChatHistory(newHistory);
setMessages([]);
};
const handleToolPermissionResponse = async (
@ -457,13 +425,15 @@ export function useChat({
// If this is a "stop stream" rejection, abort the current request
if (stopStream && abortController && isWaitingForResponse) {
abortController.abort();
setMessages((prev) => [
setChatHistory((prev) => [
...prev,
{
role: "system",
content:
"[Tool canceled - please tell Continue what to do differently]",
messageType: "system" as const,
message: {
role: "system",
content:
"[Tool canceled - please tell Continue what to do differently]",
},
contextItems: [],
},
]);
setIsWaitingForResponse(false);
@ -474,8 +444,6 @@ export function useChat({
};
return {
messages,
setMessages,
chatHistory,
setChatHistory,
isWaitingForResponse,

View file

@ -1,15 +1,15 @@
import React, { useCallback } from "react";
import type { ChatHistoryItem } from "../../../../../core/index.js";
import { MemoizedMessage } from "../components/MemoizedMessage.js";
import { DisplayMessage } from "../types.js";
export function useMessageRenderer() {
const renderMessage = useCallback(
(message: DisplayMessage, index: number) => {
return <MemoizedMessage key={index} message={message} index={index} />;
(item: ChatHistoryItem, index: number) => {
return <MemoizedMessage key={index} item={item} index={index} />;
},
[],
);
return { renderMessage };
}
}

View file

@ -108,7 +108,7 @@ export function useCurrentMode() {
// Custom hook to combine all selector logic
export function useSelectors(
configPath: string | undefined,
setMessages: React.Dispatch<React.SetStateAction<any[]>>,
setChatHistory: React.Dispatch<React.SetStateAction<any[]>>,
resetChatHistory: () => void,
): {
handleConfigSelect: (config: ConfigOption) => Promise<void>;
@ -117,14 +117,22 @@ export function useSelectors(
const { handleConfigSelect } = useConfigSelector({
configPath,
onMessage: (message) => {
setMessages((prev) => [...prev, message]);
// Convert message to ChatHistoryItem format
setChatHistory((prev) => [...prev, {
message: { role: "system", content: message.content },
contextItems: [],
}]);
},
onChatReset: resetChatHistory,
});
const { handleModelSelect } = useModelSelector({
onMessage: (message) => {
setMessages((prev) => [...prev, message]);
// Convert message to ChatHistoryItem format
setChatHistory((prev) => [...prev, {
message: { role: "system", content: message.content },
contextItems: [],
}]);
},
});

View file

@ -1,16 +1,2 @@
export interface DisplayMessage {
role: string;
content: string;
isStreaming?: boolean;
messageType?:
| "tool-start"
| "tool-result"
| "tool-error"
| "system"
| "tool-permission-request"
| "compaction";
toolName?: string;
toolResult?: string;
toolArgs?: any;
permissionRequestId?: string;
}
// This file has been intentionally left empty after migration to ChatHistoryItem
// All types have been migrated to use @continuedev/core types