fix: address feedback

This commit is contained in:
Nate 2025-08-26 10:05:01 -07:00
parent 3612d859d2
commit 3d8eb9086d
11 changed files with 100 additions and 58 deletions

View file

@ -60,7 +60,7 @@ export async function streamChatResponseWithInterruption(
}
// Always create a new assistant message for each tool call
const toolCallId = `tool_${Date.now()}`;
const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
const toolCallState: ToolCallState = {
toolCallId: toolCallId,
toolCall: {
@ -152,7 +152,7 @@ export async function streamChatResponseWithInterruption(
state.session.history.push({
message: {
role: "system",
content: `⚠️ Tool ${toolName} requires permission`,
content: `WARNING: Tool ${toolName} requires permission`,
},
contextItems: [],
});

View file

@ -4,6 +4,7 @@ import { promisify } from "util";
import chalk from "chalk";
import express, { Request, Response } from "express";
import type { ChatHistoryItem } from "../../../../core/index.js";
import { getAssistantSlug } from "../auth/workos.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { convertFromUnifiedHistory } from "../messageConversion.js";
@ -112,7 +113,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
true,
);
const initialHistory = [];
const initialHistory: ChatHistoryItem[] = [];
if (systemMessage) {
initialHistory.push({
message: { role: "system" as const, content: systemMessage },

View file

@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";
import { pruneLastMessage } from "./compaction.js";
import { convertToUnifiedHistory } from "./messageConversion.js";
import { logger } from "./util/logger.js";
describe("pruneLastMessage", () => {
it("should return empty array for empty input", () => {
@ -76,10 +77,10 @@ describe("pruneLastMessage", () => {
// The test data will be converted differently by the message converter
// Since assistant message with tool_calls gets combined with tool result
// We need to check what actually gets generated
console.log("Converted history:", JSON.stringify(history, null, 2));
logger.debug("Converted history:", { history });
const result = pruneLastMessage(history);
console.log("Pruned result:", JSON.stringify(result, null, 2));
logger.debug("Pruned result:", { result });
// For now, just check that it returns the expected structure
expect(result).toEqual([
@ -142,12 +143,12 @@ describe("pruneLastMessage", () => {
const result = pruneLastMessage(history);
// Check what we actually got
console.log("Result length:", result.length);
logger.debug("Result length:", { length: result.length });
if (result.length > 0) {
console.log("First item role:", result[0].message.role);
logger.debug("First item role:", { role: result[0].message.role });
}
if (result.length > 1) {
console.log("Second item role:", result[1].message.role);
logger.debug("Second item role:", { role: result[1].message.role });
}
// Adjust based on actual behavior

View file

@ -1,4 +1,5 @@
import type { ChatHistoryItem } from "../../../core/index.js";
import { convertFromUnifiedHistory } from "./messageConversion.js";
describe("convertFromUnifiedHistory", () => {
@ -32,7 +33,8 @@ describe("convertFromUnifiedHistory", () => {
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
role: "user",
content: "Please review @test-file.txt\n\n<file path=\"test-file.txt\">\nconsole.log('Hello, world!');\n</file>",
content:
"Please review @test-file.txt\n\n<file path=\"test-file.txt\">\nconsole.log('Hello, world!');\n</file>",
});
});
@ -99,7 +101,8 @@ describe("convertFromUnifiedHistory", () => {
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
role: "user",
content: "Compare @file1.js and @file2.js\n\n<file path=\"file1.js\">\nconst a = 1;\n</file>\n\n<file path=\"file2.js\">\nconst b = 2;\n</file>",
content:
'Compare @file1.js and @file2.js\n\n<file path="file1.js">\nconst a = 1;\n</file>\n\n<file path="file2.js">\nconst b = 2;\n</file>',
});
});
@ -136,4 +139,4 @@ describe("convertFromUnifiedHistory", () => {
content: "Here's the analysis",
});
});
});
});

View file

@ -3,6 +3,8 @@ import { BaseLlmApi } from "@continuedev/openai-adapters";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import React from "react";
import type { ChatHistoryItem } from "../../../core/index.js";
import { compactChatHistory } from "./compaction.js";
import {
convertFromUnifiedHistory,
@ -19,7 +21,7 @@ interface AutoCompactionCallbacks {
onContent?: (content: string) => void;
// For TUI mode
setMessages?: React.Dispatch<React.SetStateAction<any>>; // Generic for compatibility
setMessages?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
setChatHistory?: React.Dispatch<
React.SetStateAction<ChatCompletionMessageParam[]>
>;
@ -72,12 +74,14 @@ function handleCompactionSuccess(
) {
callbacks.setChatHistory(result.compactedHistory);
callbacks.setCompactionIndex(result.compactionIndex);
callbacks.setMessages((prev: any) => [
callbacks.setMessages((prev: ChatHistoryItem[]) => [
...prev,
{
role: "system",
content: successMessage,
messageType: "system" as const,
message: {
role: "system",
content: successMessage,
},
contextItems: [],
},
]);
}
@ -101,12 +105,14 @@ function handleCompactionError(
if (callbacks?.onSystemMessage) {
callbacks.onSystemMessage(warningMessage);
} else if (callbacks?.setMessages) {
callbacks.setMessages((prev: any) => [
callbacks.setMessages((prev: ChatHistoryItem[]) => [
...prev,
{
role: "system",
content: warningMessage,
messageType: "system" as const,
message: {
role: "system",
content: warningMessage,
},
contextItems: [],
},
]);
}

View file

@ -81,7 +81,7 @@ const ConfigSelector: React.FC<ConfigSelectorProps> = ({
return assistants.map((assistant) => {
const name =
(assistant.configResult.config as any)?.name ??
`${assistant.ownerSlug}/${assistant.configResult.config}`;
`${assistant.ownerSlug}/${assistant.packageSlug}`;
const displayName = `[${org.name}] ${name}`;
// Create unique ID that includes org info to avoid conflicts
const uniqueId = `${org.id || "personal"}-${assistant.packageSlug}`;

View file

@ -313,17 +313,17 @@ export async function handleAutoCompaction({
currentChatHistory: ChatHistoryItem[];
currentCompactionIndex: number | null;
}> {
// Check if auto-compaction is needed
// Convert to legacy format for token counting
const legacyHistory = convertFromUnifiedHistory(chatHistory);
if (!model || !shouldAutoCompact(legacyHistory, model)) {
return {
currentChatHistory: chatHistory,
currentCompactionIndex: _compactionIndex,
};
}
try {
// Check if auto-compaction is needed
// Convert to legacy format for token counting
const legacyHistory = convertFromUnifiedHistory(chatHistory);
if (!model || !shouldAutoCompact(legacyHistory, model)) {
return {
currentChatHistory: chatHistory,
currentCompactionIndex: _compactionIndex,
};
}
logger.info("Auto-compaction triggered for TUI mode");
// Add compacting message

View file

@ -39,7 +39,7 @@ export function createStreamCallbacks(
const newHistory = [...prev];
// Always create a new assistant message for each tool call
const toolCallId = `tool_${Date.now()}`;
const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
const toolCallState: ToolCallState = {
toolCallId: toolCallId,
toolCall: {

View file

@ -211,15 +211,19 @@ export function useChat({
currentCompactionIndex,
});
// Save the updated session
logger.debug("Saving session", { historyLength: newHistory.length });
const updatedSession: Session = {
...currentSession,
history: newHistory,
};
saveSession(updatedSession);
setCurrentSession(updatedSession);
logger.debug("Session saved");
// Save the updated session with the latest chat history that includes the assistant's reply
// The streamCallbacks update setChatHistory during streaming, so we need to get the current state
setChatHistory((currentHistory) => {
logger.debug("Saving session", { historyLength: currentHistory.length });
const updatedSession: Session = {
...currentSession,
history: currentHistory,
};
saveSession(updatedSession);
setCurrentSession(updatedSession);
logger.debug("Session saved");
return currentHistory;
});
} catch (error: any) {
const errorMessage = `Error: ${formatError(error)}`;
setChatHistory((prev) => [

View file

@ -5,7 +5,19 @@ import { MemoizedMessage } from "../components/MemoizedMessage.js";
export function useMessageRenderer() {
const renderMessage = useCallback((item: ChatHistoryItem, index: number) => {
return <MemoizedMessage key={index} item={item} index={index} />;
// Generate a unique key by combining message role, content hash, and timestamp
// This provides a stable identifier that won't change during re-renders
const messageContent = typeof item.message.content === 'string'
? item.message.content
: JSON.stringify(item.message.content);
const toolCallsKey = item.toolCallStates
? item.toolCallStates.map(tc => tc.toolCallId).join('-')
: '';
const uniqueKey = `${item.message.role}-${messageContent.slice(0, 50)}-${toolCallsKey}-${index}`;
return <MemoizedMessage key={uniqueKey} item={item} index={index} />;
}, []);
return { renderMessage };

View file

@ -4,6 +4,21 @@ import { existsSync, readFileSync } from "fs";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
// Import CLI logger for consistent logging
let logger;
try {
// Try to import the compiled logger
const loggerModule = await import('./dist/util/logger.js');
logger = loggerModule.logger;
} catch {
// Fallback to console if logger not available (e.g., not built yet)
logger = {
info: console.log,
warn: console.warn,
error: console.error
};
}
const __dirname = dirname(fileURLToPath(import.meta.url));
// Colors for output
@ -25,7 +40,7 @@ function getDefinedAliases() {
// Find the alias object in the build file
const aliasMatch = buildContent.match(/alias:\s*{([^}]+)}/s);
if (!aliasMatch) {
console.warn(
logger.warn(
`${colors.yellow}Warning: No aliases found in build.mjs${colors.reset}`,
);
return new Set();
@ -104,7 +119,7 @@ function findLocalPackages(startPath, visited = new Set()) {
}
}
} catch (error) {
console.error(
logger.error(
`${colors.red}Error reading ${packageJsonPath}: ${error.message}${colors.reset}`,
);
}
@ -120,7 +135,7 @@ function findLocalPackages(startPath, visited = new Set()) {
* Main validation function
*/
function validateAliases() {
console.log(
logger.info(
`${colors.blue}🔍 Validating esbuild aliases...${colors.reset}\n`,
);
@ -159,51 +174,51 @@ function validateAliases() {
// Report results
if (missingAliases.length > 0) {
console.log(
logger.error(
`${colors.red}❌ Missing aliases (WILL CAUSE RUNTIME ERRORS):${colors.reset}`,
);
missingAliases.forEach((pkg) => {
console.log(` ✗ ${pkg}`);
logger.error(` ✗ ${pkg}`);
});
console.log();
console.log(
logger.error("");
logger.error(
`${colors.red}Add these to the alias section in build.mjs:${colors.reset}`,
);
missingAliases.forEach((pkg) => {
const packageName = pkg.replace("@continuedev/", "").replace(/-/g, "_");
console.log(
logger.error(
` "${pkg}": resolve(__dirname, "../../packages/${pkg.replace("@continuedev/", "")}/dist/index.js"),`,
);
});
console.log();
logger.error("");
}
if (unnecessaryAliases.length > 0) {
console.log(
logger.warn(
`${colors.yellow}⚠️ Potentially unnecessary aliases:${colors.reset}`,
);
unnecessaryAliases.forEach((alias) => {
console.log(` ? ${alias}`);
logger.warn(` ? ${alias}`);
});
console.log();
logger.warn("");
}
// Exit with appropriate code
if (missingAliases.length > 0) {
console.log(
logger.error(
`${colors.red}✗ Validation failed! Missing ${missingAliases.length} required alias(es).${colors.reset}`,
);
console.log(
logger.error(
`${colors.red}This would cause runtime errors in the bundled CLI.${colors.reset}`,
);
process.exit(1);
} else if (unnecessaryAliases.length > 0) {
console.log(
logger.warn(
`${colors.yellow}✓ Validation passed with warnings.${colors.reset}`,
);
process.exit(0);
} else {
console.log(
logger.info(
`${colors.green}✅ All aliases are correctly configured!${colors.reset}`,
);
process.exit(0);