follow up fixes
This commit is contained in:
parent
44a142492d
commit
749f337ea4
9 changed files with 133 additions and 179 deletions
|
|
@ -14,7 +14,7 @@ import { safeStdout } from "../init.js";
|
|||
import { configureLogger } from "../logger.js";
|
||||
import * as logging from "../logging.js";
|
||||
import { sentryService } from "../sentry.js";
|
||||
import { initializeServices } from "../services/index.js";
|
||||
import { initializeServices, services } from "../services/index.js";
|
||||
import { serviceContainer } from "../services/ServiceContainer.js";
|
||||
import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
|
||||
import {
|
||||
|
|
@ -115,14 +115,15 @@ async function handleManualCompaction(
|
|||
}
|
||||
|
||||
try {
|
||||
const result = await compactChatHistory(chatHistory, model, llmApi);
|
||||
const current = services.chatHistory.getHistory();
|
||||
const result = await compactChatHistory(current, model, llmApi);
|
||||
|
||||
// Replace chat history with compacted version
|
||||
chatHistory.length = 0;
|
||||
chatHistory.push(...result.compactedHistory);
|
||||
|
||||
// Save the compacted session
|
||||
updateSessionHistory(chatHistory);
|
||||
// Update service-driven history and persist session
|
||||
services.chatHistory.compact(
|
||||
result.compactedHistory,
|
||||
result.compactionIndex,
|
||||
);
|
||||
updateSessionHistory(result.compactedHistory);
|
||||
|
||||
if (isHeadless) {
|
||||
safeStdout(
|
||||
|
|
@ -210,15 +211,19 @@ async function handleAutoCompaction(
|
|||
},
|
||||
};
|
||||
|
||||
const result = await coreAutoCompaction(chatHistory, model, llmApi, {
|
||||
isHeadless,
|
||||
format,
|
||||
callbacks,
|
||||
});
|
||||
const result = await coreAutoCompaction(
|
||||
services.chatHistory.getHistory(),
|
||||
model,
|
||||
llmApi,
|
||||
{
|
||||
isHeadless,
|
||||
format,
|
||||
callbacks,
|
||||
},
|
||||
);
|
||||
|
||||
// Update the original array reference for headless mode
|
||||
chatHistory.length = 0;
|
||||
chatHistory.push(...result.chatHistory);
|
||||
// Update service-driven history
|
||||
services.chatHistory.setHistory(result.chatHistory);
|
||||
|
||||
return result.compactionIndex;
|
||||
}
|
||||
|
|
@ -286,7 +291,7 @@ async function processMessage(
|
|||
telemetryService.logUserPrompt(userInput.length, userInput);
|
||||
|
||||
// Check if auto-compacting is needed BEFORE adding user message
|
||||
if (shouldAutoCompact(chatHistory, model)) {
|
||||
if (shouldAutoCompact(services.chatHistory.getHistory(), model)) {
|
||||
const newIndex = await handleAutoCompaction(
|
||||
chatHistory,
|
||||
model,
|
||||
|
|
@ -296,17 +301,12 @@ async function processMessage(
|
|||
);
|
||||
if (newIndex !== null) {
|
||||
compactionIndex = newIndex;
|
||||
// Replace chatHistory with compacted version
|
||||
chatHistory.length = 0;
|
||||
chatHistory.push(...chatHistory);
|
||||
// Service already updated in handleAutoCompaction via setHistory
|
||||
}
|
||||
}
|
||||
|
||||
// Add user message to history AFTER potential compaction
|
||||
chatHistory.push({
|
||||
message: { role: "user", content: userInput },
|
||||
contextItems: [],
|
||||
});
|
||||
services.chatHistory.addUserMessage(userInput);
|
||||
|
||||
// Get AI response with potential tool usage
|
||||
if (!isHeadless) {
|
||||
|
|
@ -316,12 +316,13 @@ async function processMessage(
|
|||
try {
|
||||
const abortController = new AbortController();
|
||||
|
||||
// Handle compaction properly - streamChatResponse modifies the array in place
|
||||
// Service-driven streaming; history updates occur via ChatHistoryService
|
||||
let finalResponse;
|
||||
if (compactionIndex !== null && compactionIndex !== undefined) {
|
||||
// When using compaction, we need to send a subset but capture the full history
|
||||
const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex);
|
||||
const originalLength = historyForLLM.length;
|
||||
// Use service to compute history for LLM
|
||||
const historyForLLM = services.chatHistory.getHistoryForLLM(
|
||||
compactionIndex,
|
||||
);
|
||||
|
||||
finalResponse = await streamChatResponse(
|
||||
historyForLLM,
|
||||
|
|
@ -329,19 +330,14 @@ async function processMessage(
|
|||
llmApi,
|
||||
abortController,
|
||||
);
|
||||
|
||||
// Append any new messages (assistant/tool) that were added by streamChatResponse
|
||||
const newMessages = historyForLLM.slice(originalLength);
|
||||
chatHistory.push(...newMessages);
|
||||
} else {
|
||||
// No compaction - just pass the full history directly
|
||||
// No compaction - get full history from service
|
||||
finalResponse = await streamChatResponse(
|
||||
chatHistory,
|
||||
services.chatHistory.getHistory(),
|
||||
model,
|
||||
llmApi,
|
||||
abortController,
|
||||
);
|
||||
// No need to sync back - streamChatResponse modifies chatHistory in place
|
||||
}
|
||||
|
||||
// Generate session title after first assistant response
|
||||
|
|
@ -368,7 +364,7 @@ async function processMessage(
|
|||
}
|
||||
|
||||
// Save session after each successful response
|
||||
updateSessionHistory(chatHistory);
|
||||
updateSessionHistory(services.chatHistory.getHistory());
|
||||
} catch (e: any) {
|
||||
const error = e instanceof Error ? e : new Error(String(e));
|
||||
|
||||
|
|
@ -381,11 +377,17 @@ async function processMessage(
|
|||
sentryService.captureException(error, {
|
||||
context: "chat_response",
|
||||
isHeadless,
|
||||
chatHistoryLength: chatHistory.length,
|
||||
chatHistoryLength: services.chatHistory.getHistory().length,
|
||||
});
|
||||
if (!isHeadless) {
|
||||
logger.info(
|
||||
chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`),
|
||||
chalk.dim(
|
||||
`Chat history:\n${JSON.stringify(
|
||||
services.chatHistory.getHistory(),
|
||||
null,
|
||||
2,
|
||||
)}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -414,12 +416,11 @@ async function runHeadlessMode(
|
|||
throw new Error("No models were found.");
|
||||
}
|
||||
|
||||
// Initialize chat history
|
||||
// Initialize service-driven history (resume if requested)
|
||||
const chatHistory = await initializeChatHistory(options);
|
||||
|
||||
// Track compaction index if resuming with compacted history
|
||||
let compactionIndex: number | null = null;
|
||||
if (options.resume) {
|
||||
services.chatHistory.setHistory(chatHistory);
|
||||
compactionIndex = findCompactionIndex(chatHistory);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -80,7 +80,7 @@ export async function compactChatHistory(
|
|||
historyForCompaction = [...historyToUse, compactionPrompt];
|
||||
}
|
||||
|
||||
// Stream the compaction response
|
||||
// Stream the compaction response (service drives updates; this collects content locally)
|
||||
const controller = new AbortController();
|
||||
|
||||
let compactionContent = "";
|
||||
|
|
|
|||
|
|
@ -109,21 +109,47 @@ export class ChatHistoryService extends BaseService<ChatHistoryState> {
|
|||
message.toolCalls = toolCalls;
|
||||
}
|
||||
|
||||
const toolCallStates = toolCalls?.map((tc) => ({
|
||||
toolCallId: tc.id,
|
||||
toolCall: {
|
||||
id: tc.id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.name || tc.function?.name,
|
||||
arguments: typeof tc.arguments === "string"
|
||||
? tc.arguments
|
||||
: JSON.stringify(tc.arguments || tc.function?.arguments || {}),
|
||||
const toolCallStates = toolCalls?.map((tc) => {
|
||||
const id = tc.id;
|
||||
const name = tc.function?.name ?? tc.name;
|
||||
// Prefer explicit string arguments; otherwise stringify object arguments
|
||||
const rawArgStr =
|
||||
typeof tc.arguments === "string"
|
||||
? tc.arguments
|
||||
: typeof tc.function?.arguments === "string"
|
||||
? tc.function.arguments
|
||||
: tc.arguments !== undefined
|
||||
? JSON.stringify(tc.arguments)
|
||||
: tc.function?.arguments !== undefined
|
||||
? String(tc.function.arguments)
|
||||
: "{}";
|
||||
|
||||
// parsedArgs: prefer object, else parse the string if possible
|
||||
let parsedArgs: any = {};
|
||||
if (tc && typeof tc.arguments === "object" && tc.arguments !== null) {
|
||||
parsedArgs = tc.arguments;
|
||||
} else if (typeof rawArgStr === "string") {
|
||||
try {
|
||||
parsedArgs = JSON.parse(rawArgStr);
|
||||
} catch {
|
||||
parsedArgs = {};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
toolCallId: id,
|
||||
toolCall: {
|
||||
id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name,
|
||||
arguments: rawArgStr,
|
||||
},
|
||||
},
|
||||
},
|
||||
status: "generated" as ToolStatus,
|
||||
parsedArgs: typeof tc.arguments === "object" ? tc.arguments : {},
|
||||
}));
|
||||
status: "generated" as ToolStatus,
|
||||
parsedArgs,
|
||||
};
|
||||
});
|
||||
|
||||
const newMessage = createHistoryItem(message, [], toolCallStates);
|
||||
const newHistory = [...this.currentState.history, newMessage];
|
||||
|
|
@ -165,7 +191,7 @@ export class ChatHistoryService extends BaseService<ChatHistoryState> {
|
|||
}
|
||||
|
||||
/**
|
||||
* Add a generic history item (for compatibility during migration)
|
||||
* Add a generic history item
|
||||
*/
|
||||
addHistoryItem(item: ChatHistoryItem): ChatHistoryItem {
|
||||
const newHistory = [...this.currentState.history, item];
|
||||
|
|
|
|||
|
|
@ -33,22 +33,8 @@ export async function handleToolCalls(
|
|||
if (toolCalls.length === 0) {
|
||||
if (content) {
|
||||
if (useService) {
|
||||
// Service-driven: rely solely on service state (no local mutations)
|
||||
try {
|
||||
const svcHistory = chatHistorySvc.getHistory();
|
||||
const svcLast = svcHistory[svcHistory.length - 1];
|
||||
const isDuplicateSvc =
|
||||
!!svcLast &&
|
||||
svcLast.message.role === "assistant" &&
|
||||
typeof svcLast.message.content === "string" &&
|
||||
svcLast.message.content === content &&
|
||||
!(svcLast as any).toolCallStates?.length;
|
||||
if (!isDuplicateSvc) {
|
||||
chatHistorySvc.addAssistantMessage(content);
|
||||
}
|
||||
} catch {
|
||||
chatHistorySvc.addAssistantMessage(content);
|
||||
}
|
||||
// Service-driven: write assistant message via service
|
||||
chatHistorySvc.addAssistantMessage(content);
|
||||
} else {
|
||||
// Fallback only when service is unavailable
|
||||
chatHistory.push(
|
||||
|
|
|
|||
|
|
@ -295,7 +295,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, setChatHistory, exit);
|
||||
await handleRemoteExit(remoteUrl, exit);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import type { ChatHistoryItem } from "core/index.js";
|
||||
|
||||
import { services } from "../../services/index.js";
|
||||
import { posthogService } from "../../telemetry/posthogService.js";
|
||||
import { logger } from "../../util/logger.js";
|
||||
|
||||
|
|
@ -25,7 +26,6 @@ async function pollRemoteServerState(
|
|||
|
||||
interface SetupRemotePollingOptions {
|
||||
remoteUrl: string;
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
responseStartTime: number | null;
|
||||
setResponseStartTime: React.Dispatch<React.SetStateAction<number | null>>;
|
||||
|
|
@ -36,7 +36,6 @@ interface SetupRemotePollingOptions {
|
|||
*/
|
||||
export function setupRemotePolling({
|
||||
remoteUrl,
|
||||
setChatHistory,
|
||||
setIsWaitingForResponse,
|
||||
responseStartTime,
|
||||
setResponseStartTime,
|
||||
|
|
@ -54,7 +53,6 @@ export function setupRemotePolling({
|
|||
if (state && isMounted) {
|
||||
updateStateFromRemote({
|
||||
state,
|
||||
setChatHistory,
|
||||
setIsWaitingForResponse,
|
||||
responseStartTime,
|
||||
setResponseStartTime,
|
||||
|
|
@ -81,7 +79,6 @@ export function setupRemotePolling({
|
|||
|
||||
interface UpdateStateFromRemoteOptions {
|
||||
state: RemoteServerState;
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setIsWaitingForResponse: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
responseStartTime: number | null;
|
||||
setResponseStartTime: React.Dispatch<React.SetStateAction<number | null>>;
|
||||
|
|
@ -92,37 +89,16 @@ interface UpdateStateFromRemoteOptions {
|
|||
*/
|
||||
function updateStateFromRemote({
|
||||
state,
|
||||
setChatHistory,
|
||||
setIsWaitingForResponse,
|
||||
responseStartTime,
|
||||
setResponseStartTime,
|
||||
}: UpdateStateFromRemoteOptions): void {
|
||||
// Update chat history from server - now using session.history directly
|
||||
if (state.session && state.session.history) {
|
||||
setChatHistory((prevHistory) => {
|
||||
// Use session history directly - it already has the correct type
|
||||
const newHistory = state.session.history;
|
||||
|
||||
// Quick length check first
|
||||
if (prevHistory.length !== newHistory.length) {
|
||||
return newHistory;
|
||||
}
|
||||
|
||||
// Deep comparison - check if content actually changed
|
||||
const hasChanged = newHistory.some((item, index) => {
|
||||
const prevItem = prevHistory[index];
|
||||
return (
|
||||
!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 ? newHistory : prevHistory;
|
||||
});
|
||||
const newHistory = state.session.history as ChatHistoryItem[];
|
||||
// Let ChatHistoryService own the history and emit updates to UI
|
||||
services.chatHistory.setRemoteMode(true);
|
||||
services.chatHistory.setHistory(newHistory);
|
||||
}
|
||||
|
||||
// Update processing state
|
||||
|
|
@ -139,7 +115,6 @@ function updateStateFromRemote({
|
|||
*/
|
||||
export async function handleRemoteExit(
|
||||
remoteUrl: string,
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>,
|
||||
exit: () => void,
|
||||
): Promise<void> {
|
||||
posthogService.capture("useSlashCommand", {
|
||||
|
|
@ -152,50 +127,34 @@ export async function handleRemoteExit(
|
|||
});
|
||||
|
||||
if (response.ok) {
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Remote environment is shutting down...",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
try {
|
||||
services.chatHistory.addSystemMessage(
|
||||
"Remote environment is shutting down...",
|
||||
);
|
||||
} catch {}
|
||||
setTimeout(() => exit(), 1000);
|
||||
} else {
|
||||
const text = await response.text();
|
||||
logger.error("Remote shutdown failed:", text);
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Failed to shutdown remote environment",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
try {
|
||||
services.chatHistory.addSystemMessage(
|
||||
"Failed to shutdown remote environment",
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("Failed to send exit request to remote server:", error);
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Error: Failed to connect to remote server for shutdown",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
try {
|
||||
services.chatHistory.addSystemMessage(
|
||||
"Error: Failed to connect to remote server for shutdown",
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
interface HandleRemoteMessageOptions {
|
||||
remoteUrl: string;
|
||||
messageContent: string;
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -204,7 +163,6 @@ interface HandleRemoteMessageOptions {
|
|||
export async function handleRemoteMessage({
|
||||
remoteUrl,
|
||||
messageContent,
|
||||
setChatHistory,
|
||||
}: HandleRemoteMessageOptions): Promise<void> {
|
||||
try {
|
||||
const response = await fetch(`${remoteUrl}/message`, {
|
||||
|
|
@ -217,29 +175,19 @@ export async function handleRemoteMessage({
|
|||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Error: ${error.error || "Failed to send message"}`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
try {
|
||||
services.chatHistory.addSystemMessage(
|
||||
`Error: ${error.error || "Failed to send message"}`,
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
// State will be updated by polling
|
||||
} catch (error) {
|
||||
logger.error("Failed to send message to remote server:", error);
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Error: Failed to connect to remote server`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
try {
|
||||
services.chatHistory.addSystemMessage(
|
||||
"Error: Failed to connect to remote server",
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,27 +24,25 @@ export function createStreamCallbacks(
|
|||
onContent: (_: string) => {},
|
||||
|
||||
onContentComplete: async (content: string) => {
|
||||
// Update local React state for UI
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
contextItems: [],
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: content,
|
||||
isStreaming: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
// Also update service; handleToolCalls will de-dup when no tools
|
||||
// Do not add assistant messages via service; handleToolCalls is the single writer
|
||||
// For environments where the service isn't ready (unit tests), update local state only
|
||||
try {
|
||||
const svc = services.chatHistory;
|
||||
if (typeof svc?.isReady === "function" && svc.isReady()) {
|
||||
svc.addAssistantMessage(content);
|
||||
const useService = typeof svc?.isReady === "function" && svc.isReady();
|
||||
if (!useService && content) {
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
contextItems: [],
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: content,
|
||||
isStreaming: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// Generate session title after first assistant response
|
||||
if (content && llmApi && model) {
|
||||
const currentSession = getCurrentSession();
|
||||
|
|
@ -273,8 +271,7 @@ export async function executeStreaming({
|
|||
streamCallbacks,
|
||||
);
|
||||
|
||||
// streamChatResponse modifies the array in place
|
||||
// The new messages are already in historyForLLM
|
||||
// Service-driven streaming; history updates occur via ChatHistoryService
|
||||
} else {
|
||||
await streamChatResponse(
|
||||
chatHistory,
|
||||
|
|
|
|||
|
|
@ -160,7 +160,6 @@ export function useChat({
|
|||
|
||||
return setupRemotePolling({
|
||||
remoteUrl,
|
||||
setChatHistory: setChatHistory,
|
||||
setIsWaitingForResponse,
|
||||
responseStartTime,
|
||||
setResponseStartTime,
|
||||
|
|
@ -389,7 +388,6 @@ export function useChat({
|
|||
await handleRemoteMessage({
|
||||
remoteUrl,
|
||||
messageContent: messageText,
|
||||
setChatHistory: setChatHistory,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
// This file has been intentionally left empty after migration to ChatHistoryItem
|
||||
// All types have been migrated to use @continuedev/core types
|
||||
Loading…
Add table
Reference in a new issue