Merge branch 'main' into tingwai/con-3770-compaction-ui
This commit is contained in:
commit
8775c3b470
6 changed files with 333 additions and 73 deletions
62
extensions/cli/src/stream/messageQueue.test.ts
Normal file
62
extensions/cli/src/stream/messageQueue.test.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../util/logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
setLevel: vi.fn(),
|
||||
configureHeadlessMode: vi.fn(),
|
||||
getLogPath: vi.fn(),
|
||||
getSessionId: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { messageQueue } from "./messageQueue.js";
|
||||
|
||||
describe("messageQueue", () => {
|
||||
beforeEach(() => {
|
||||
// Drain any leftover items from previous tests
|
||||
while (messageQueue.getAllQueuedMessages()) {}
|
||||
});
|
||||
|
||||
it("enqueues and emits messageQueued", async () => {
|
||||
const event = new Promise<any>((resolve) =>
|
||||
messageQueue.once("messageQueued", resolve),
|
||||
);
|
||||
|
||||
const ok = await messageQueue.enqueueMessage("hello world");
|
||||
expect(ok).toBe(true);
|
||||
expect(messageQueue.getQueueLength()).toBe(1);
|
||||
|
||||
const queued = await event;
|
||||
expect(queued.message).toBe("hello world");
|
||||
});
|
||||
|
||||
it("combines messages, merges image maps, writes history, and clears queue", async () => {
|
||||
const bufA = Buffer.from("A");
|
||||
const bufB = Buffer.from("B");
|
||||
|
||||
const img1 = new Map<string, Buffer>([["a", bufA]]);
|
||||
const img2 = new Map<string, Buffer>([["b", bufB]]);
|
||||
|
||||
const history = { addEntry: vi.fn() } as any;
|
||||
|
||||
await messageQueue.enqueueMessage("one", img1);
|
||||
await messageQueue.enqueueMessage("two", img2, history);
|
||||
|
||||
const combined = messageQueue.getAllQueuedMessages();
|
||||
expect(combined).toBeTruthy();
|
||||
expect(combined!.message).toBe("one\ntwo");
|
||||
expect(combined!.imageMap).toBeDefined();
|
||||
expect(combined!.imageMap!.get("a")).toEqual(bufA);
|
||||
expect(combined!.imageMap!.get("b")).toEqual(bufB);
|
||||
|
||||
// queue should be cleared
|
||||
expect(messageQueue.getQueueLength()).toBe(0);
|
||||
|
||||
// input history should receive the combined message
|
||||
expect(history.addEntry).toHaveBeenCalledWith("one\ntwo");
|
||||
});
|
||||
});
|
||||
94
extensions/cli/src/stream/messageQueue.ts
Normal file
94
extensions/cli/src/stream/messageQueue.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { EventEmitter } from "events";
|
||||
|
||||
import { InputHistory } from "../util/inputHistory.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
export interface QueuedMessage {
|
||||
message: string;
|
||||
imageMap?: Map<string, Buffer>;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface MessageProcessor {
|
||||
(message: string, imageMap?: Map<string, Buffer>): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queue to store messages that need to be processed later
|
||||
*/
|
||||
class MessageQueue extends EventEmitter {
|
||||
private queue: QueuedMessage[] = [];
|
||||
private inputHistory: InputHistory | undefined;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
async enqueueMessage(
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
inputHistory?: InputHistory,
|
||||
): Promise<boolean> {
|
||||
this.inputHistory = inputHistory;
|
||||
|
||||
const queuedMessage: QueuedMessage = {
|
||||
message,
|
||||
imageMap,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
this.queue.push(queuedMessage);
|
||||
logger.debug("MessageQueue: Message queued", {
|
||||
queueLength: this.queue.length,
|
||||
});
|
||||
|
||||
// Emit event for UI to show the queued message
|
||||
this.emit("messageQueued", queuedMessage);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public getAllQueuedMessages() {
|
||||
if (this.queue.length === 0) return undefined;
|
||||
|
||||
// Combine all queued messages into one
|
||||
const combinedMessage = this.queue.map((msg) => msg.message).join("\n");
|
||||
const combinedImageMap = new Map<string, Buffer>();
|
||||
|
||||
// Merge all image maps
|
||||
for (const queuedMsg of this.queue) {
|
||||
if (queuedMsg.imageMap) {
|
||||
for (const [key, value] of queuedMsg.imageMap) {
|
||||
combinedImageMap.set(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
message: combinedMessage,
|
||||
imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
// Add to input history and clear the queue
|
||||
this.inputHistory?.addEntry(combinedMessage);
|
||||
this.queue = [];
|
||||
|
||||
logger.debug("MessageQueue: All messages dequeued and combined", {
|
||||
combinedLength: combinedMessage.length,
|
||||
queueLength: this.queue.length,
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public getLatestMessage() {
|
||||
return this.getAllQueuedMessages();
|
||||
}
|
||||
|
||||
getQueueLength(): number {
|
||||
return this.queue.length;
|
||||
}
|
||||
}
|
||||
|
||||
export const messageQueue = new MessageQueue();
|
||||
|
|
@ -189,6 +189,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
inputMode,
|
||||
activePermissionRequest,
|
||||
wasInterrupted,
|
||||
queuedMessages,
|
||||
handleUserMessage,
|
||||
handleInterrupt,
|
||||
handleFileAttached,
|
||||
|
|
@ -283,6 +284,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
model={services.model?.model || undefined}
|
||||
mcpService={services.mcp?.mcpService || undefined}
|
||||
chatHistory={chatHistory}
|
||||
queuedMessages={queuedMessages}
|
||||
renderMessage={renderMessage}
|
||||
refreshTrigger={staticRefreshTrigger}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import type { PermissionMode } from "../permissions/types.js";
|
|||
import type { FileIndexServiceState } from "../services/FileIndexService.js";
|
||||
import { SERVICE_NAMES, serviceContainer } from "../services/index.js";
|
||||
import { modeService } from "../services/ModeService.js";
|
||||
import { messageQueue } from "../stream/messageQueue.js";
|
||||
import { InputHistory } from "../util/inputHistory.js";
|
||||
|
||||
import { FileSearchUI } from "./FileSearchUI.js";
|
||||
|
|
@ -517,7 +518,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
}
|
||||
|
||||
// Normal Enter behavior - submit if there's content
|
||||
if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) {
|
||||
if (textBuffer.text.trim() || wasInterrupted) {
|
||||
// Get images before expanding paste blocks
|
||||
const imageMap = textBuffer.getAllImages();
|
||||
|
||||
|
|
@ -525,14 +526,19 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
textBuffer.expandAllPasteBlocks();
|
||||
const submittedText = textBuffer.text.trim();
|
||||
|
||||
// Only add to history if there's actual text (not when resuming)
|
||||
if (submittedText) {
|
||||
if (isWaitingForResponse) {
|
||||
// Process message later when LLM has responded
|
||||
void messageQueue.enqueueMessage(
|
||||
submittedText,
|
||||
imageMap,
|
||||
inputHistory,
|
||||
);
|
||||
} else {
|
||||
// Submit with images
|
||||
inputHistory.addEntry(submittedText);
|
||||
onSubmit(submittedText, imageMap);
|
||||
}
|
||||
|
||||
// Submit with images
|
||||
onSubmit(submittedText, imageMap);
|
||||
|
||||
textBuffer.clear();
|
||||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
|
|
@ -655,15 +661,6 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
// Allow typing during streaming, but block submission
|
||||
if (!inputMode) {
|
||||
// Block only Enter key submission during streaming
|
||||
if (key.return && !key.shift) {
|
||||
return;
|
||||
}
|
||||
// Allow all other input (typing, navigation, etc.)
|
||||
}
|
||||
|
||||
// Handle slash command navigation
|
||||
if (showSlashCommands) {
|
||||
if (handleSlashCommandNavigation(key)) {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { Box, Static, useStdout } from "ink";
|
||||
import { Box, Static, Text, 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 type { QueuedMessage } from "../../stream/messageQueue.js";
|
||||
import { useTerminalSize } from "../hooks/useTerminalSize.js";
|
||||
import { IntroMessage } from "../IntroMessage.js";
|
||||
|
||||
|
|
@ -13,6 +14,7 @@ interface StaticChatContentProps {
|
|||
model?: ModelConfig;
|
||||
mcpService?: MCPService;
|
||||
chatHistory: ChatHistoryItem[];
|
||||
queuedMessages?: QueuedMessage[];
|
||||
renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement;
|
||||
refreshTrigger?: number; // Add a prop to trigger refresh from parent
|
||||
}
|
||||
|
|
@ -23,6 +25,7 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
|
|||
model,
|
||||
mcpService,
|
||||
chatHistory,
|
||||
queuedMessages = [],
|
||||
renderMessage,
|
||||
refreshTrigger,
|
||||
}) => {
|
||||
|
|
@ -140,6 +143,15 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
|
|||
<React.Fragment key={`pending-${index}`}>{item}</React.Fragment>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
{/* Queued messages - show at bottom with queue indicators */}
|
||||
{queuedMessages.length > 0 && (
|
||||
<Box paddingLeft={2} paddingBottom={1}>
|
||||
<Text color="gray" italic>
|
||||
{queuedMessages.map((msg) => msg.message).join("\n")}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
/* eslint-disable max-lines */
|
||||
|
||||
import type { ChatHistoryItem, Session } from "core/index.js";
|
||||
import { useApp } from "ink";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
|
@ -13,6 +12,7 @@ import {
|
|||
updateSessionHistory,
|
||||
} from "../../session.js";
|
||||
import { handleSlashCommands } from "../../slashCommands.js";
|
||||
import { messageQueue, QueuedMessage } from "../../stream/messageQueue.js";
|
||||
import { telemetryService } from "../../telemetry/telemetryService.js";
|
||||
import { formatError } from "../../util/formatError.js";
|
||||
import { logger } from "../../util/logger.js";
|
||||
|
|
@ -174,6 +174,22 @@ export function useChat({
|
|||
// Track interrupted state for resume functionality
|
||||
const [wasInterrupted, setWasInterrupted] = useState(false);
|
||||
|
||||
// Track queued messages for immediate display
|
||||
const [queuedMessages, setQueuedMessages] = useState<QueuedMessage[]>([]);
|
||||
|
||||
// Set up message queue listeners
|
||||
useEffect(() => {
|
||||
const onMessageQueued = (queuedMessage: QueuedMessage) => {
|
||||
setQueuedMessages((prev) => [...prev, queuedMessage]);
|
||||
};
|
||||
|
||||
messageQueue.on("messageQueued", onMessageQueued);
|
||||
|
||||
return () => {
|
||||
messageQueue.off("messageQueued", onMessageQueued);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Clean up abort controller on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
|
|
@ -314,6 +330,30 @@ export function useChat({
|
|||
setIsWaitingForResponse(false);
|
||||
setResponseStartTime(null);
|
||||
setInputMode(true);
|
||||
|
||||
// Check if there are queued messages and process them after a microtask delay
|
||||
// This ensures the GUI state has been updated before processing the next message
|
||||
const queuedMessageData = messageQueue.getLatestMessage();
|
||||
if (queuedMessageData) {
|
||||
const { message: latestQueuedMessage, imageMap } = queuedMessageData;
|
||||
logger.debug("processing queued message", { latestQueuedMessage });
|
||||
|
||||
// Clear all queued messages from display since we're processing them all together
|
||||
setQueuedMessages([]);
|
||||
|
||||
// Add the queued message to chat history so it shows in the GUI
|
||||
const formattedQueuedMessage = await formatMessageWithFiles(
|
||||
latestQueuedMessage,
|
||||
[], // No attached files for queued messages
|
||||
imageMap,
|
||||
);
|
||||
setChatHistory((prev) => [...prev, formattedQueuedMessage]);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui
|
||||
|
||||
// Process the queued message using the internal processing logic without re-adding to history
|
||||
await processQueuedMessage(latestQueuedMessage, imageMap);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -409,20 +449,11 @@ export function useChat({
|
|||
.join("");
|
||||
};
|
||||
|
||||
const handleUserMessage = async (
|
||||
const processMessage = async (
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
isQueuedMessage: boolean = false,
|
||||
) => {
|
||||
// Check if this is a resume request (empty message after interruption)
|
||||
if (await handleResumeRequest(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear interrupted state if user types a new message
|
||||
if (wasInterrupted && message !== "") {
|
||||
setWasInterrupted(false);
|
||||
}
|
||||
|
||||
// Handle special commands
|
||||
const handled = await handleSpecialCommands({
|
||||
message,
|
||||
|
|
@ -451,27 +482,9 @@ export function useChat({
|
|||
// Track telemetry
|
||||
trackUserMessage(message, model);
|
||||
|
||||
// Format message with attached files and images
|
||||
logger.debug("Processing message with images", {
|
||||
hasImages: !!(imageMap && imageMap.size > 0),
|
||||
imageCount: imageMap?.size || 0,
|
||||
});
|
||||
const newUserMessage = await formatMessageWithFiles(
|
||||
message,
|
||||
attachedFiles,
|
||||
imageMap,
|
||||
);
|
||||
logger.debug("Message formatted successfully");
|
||||
|
||||
if (attachedFiles.length > 0) {
|
||||
setAttachedFiles([]);
|
||||
}
|
||||
|
||||
// In remote mode, send message to server instead of processing locally
|
||||
if (isRemoteMode && remoteUrl) {
|
||||
const messageContentString = convertMessageContentToString(
|
||||
newUserMessage.message.content,
|
||||
);
|
||||
const messageContentString = convertMessageContentToString(message);
|
||||
|
||||
await handleRemoteMessage({
|
||||
remoteUrl,
|
||||
|
|
@ -480,38 +493,115 @@ export function useChat({
|
|||
return;
|
||||
}
|
||||
|
||||
// Check if auto-compacting is needed BEFORE adding user message
|
||||
const compactionController = new AbortController();
|
||||
setCompactionAbortController(compactionController);
|
||||
setIsCompacting(true);
|
||||
setCompactionStartTime(Date.now());
|
||||
// For non-queued messages, format and add to chat history
|
||||
if (isQueuedMessage) {
|
||||
// For queued messages, chat history is already updated
|
||||
// Check if auto-compacting is needed with current history
|
||||
const compactionController = new AbortController();
|
||||
setCompactionAbortController(compactionController);
|
||||
setIsCompacting(true);
|
||||
setCompactionStartTime(Date.now());
|
||||
|
||||
let currentChatHistory, currentCompactionIndex;
|
||||
try {
|
||||
const result = await handleAutoCompaction({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
compactionIndex,
|
||||
setChatHistory: setChatHistory,
|
||||
setCompactionIndex,
|
||||
abortController: compactionController,
|
||||
let currentChatHistory, currentCompactionIndex;
|
||||
try {
|
||||
const result = await handleAutoCompaction({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
compactionIndex,
|
||||
setChatHistory: setChatHistory,
|
||||
setCompactionIndex,
|
||||
abortController: compactionController,
|
||||
});
|
||||
currentChatHistory = result.currentChatHistory;
|
||||
currentCompactionIndex = result.currentCompactionIndex;
|
||||
} finally {
|
||||
setIsCompacting(false);
|
||||
setCompactionStartTime(null);
|
||||
setCompactionAbortController(null);
|
||||
}
|
||||
|
||||
// Execute the streaming response with the current history (which already includes the queued message)
|
||||
await executeStreamingResponse(
|
||||
currentChatHistory,
|
||||
currentCompactionIndex,
|
||||
);
|
||||
} else {
|
||||
// Format message with attached files and images
|
||||
logger.debug("Processing message with images", {
|
||||
hasImages: !!(imageMap && imageMap.size > 0),
|
||||
imageCount: imageMap?.size || 0,
|
||||
});
|
||||
const newUserMessage = await formatMessageWithFiles(
|
||||
message,
|
||||
attachedFiles,
|
||||
imageMap,
|
||||
);
|
||||
logger.debug("Message formatted successfully");
|
||||
|
||||
currentChatHistory = result.currentChatHistory;
|
||||
currentCompactionIndex = result.currentCompactionIndex;
|
||||
} finally {
|
||||
setIsCompacting(false);
|
||||
setCompactionStartTime(null);
|
||||
setCompactionAbortController(null);
|
||||
if (attachedFiles.length > 0) {
|
||||
setAttachedFiles([]);
|
||||
}
|
||||
|
||||
// Check if auto-compacting is needed BEFORE adding user message
|
||||
const compactionController = new AbortController();
|
||||
setCompactionAbortController(compactionController);
|
||||
setIsCompacting(true);
|
||||
setCompactionStartTime(Date.now());
|
||||
|
||||
let currentChatHistory, currentCompactionIndex;
|
||||
try {
|
||||
const result = await handleAutoCompaction({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
compactionIndex,
|
||||
setChatHistory: setChatHistory,
|
||||
setCompactionIndex,
|
||||
abortController: compactionController,
|
||||
});
|
||||
currentChatHistory = result.currentChatHistory;
|
||||
currentCompactionIndex = result.currentCompactionIndex;
|
||||
} finally {
|
||||
setIsCompacting(false);
|
||||
setCompactionStartTime(null);
|
||||
setCompactionAbortController(null);
|
||||
}
|
||||
|
||||
// Add the formatted user message to history
|
||||
const newHistory = [...currentChatHistory, newUserMessage];
|
||||
setChatHistory(newHistory);
|
||||
|
||||
// Execute the streaming response
|
||||
await executeStreamingResponse(newHistory, currentCompactionIndex);
|
||||
}
|
||||
};
|
||||
|
||||
const processQueuedMessage = async (
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
) => {
|
||||
// For queued messages, we can reuse the core message processing logic
|
||||
// by calling the internal processing function directly
|
||||
await processMessage(message, imageMap, true);
|
||||
};
|
||||
|
||||
const handleUserMessage = async (
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
) => {
|
||||
// Check if this is a resume request (empty message after interruption)
|
||||
if (await handleResumeRequest(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Add the formatted user message to history
|
||||
const newHistory = [...currentChatHistory, newUserMessage];
|
||||
setChatHistory(newHistory);
|
||||
// Clear interrupted state if user types a new message
|
||||
if (wasInterrupted && message !== "") {
|
||||
setWasInterrupted(false);
|
||||
}
|
||||
|
||||
// Execute the streaming response
|
||||
await executeStreamingResponse(newHistory, currentCompactionIndex);
|
||||
// Use the common message processing logic
|
||||
await processMessage(message, imageMap, false);
|
||||
};
|
||||
|
||||
const handleInterrupt = () => {
|
||||
|
|
@ -575,6 +665,8 @@ export function useChat({
|
|||
additionalRules,
|
||||
);
|
||||
setChatHistory(newHistory);
|
||||
// Clear any queued messages when resetting chat
|
||||
setQueuedMessages([]);
|
||||
};
|
||||
|
||||
const handleToolPermissionResponse = async (
|
||||
|
|
@ -654,6 +746,7 @@ export function useChat({
|
|||
attachedFiles,
|
||||
activePermissionRequest,
|
||||
wasInterrupted,
|
||||
queuedMessages,
|
||||
handleUserMessage,
|
||||
handleInterrupt,
|
||||
handleFileAttached,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue