Elffuss BraidHub

kikocis/continue public

Merge pull request #7632 from uinstinct/cli-message-queueing

feat(cli): message queueing
Changesetb804d5856fb5b149b02ca7d7c495d2fe63db995f759e2db8fc7bffd2fb10a891
AuthorTing-Wai <40179554+tingwai@users.noreply.github.com> · 2025-09-11 09:35 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-11 09:35 -07:00
Parentsf8351646b87f, 50b835c12af2

Browse the files at this changeset

6 files changed

added extensions/cli/src/stream/messageQueue.test.ts +62 −0
@@ -0,0 +1,62 @@
1+import { beforeEach, describe, expect, it, vi } from "vitest";
2+
3+vi.mock("../util/logger.js", () => ({
4+ logger: {
5+ debug: vi.fn(),
6+ info: vi.fn(),
7+ warn: vi.fn(),
8+ error: vi.fn(),
9+ setLevel: vi.fn(),
10+ configureHeadlessMode: vi.fn(),
11+ getLogPath: vi.fn(),
12+ getSessionId: vi.fn(),
13+ },
14+}));
15+
16+import { messageQueue } from "./messageQueue.js";
17+
18+describe("messageQueue", () => {
19+ beforeEach(() => {
20+ // Drain any leftover items from previous tests
21+ while (messageQueue.getAllQueuedMessages()) {}
22+ });
23+
24+ it("enqueues and emits messageQueued", async () => {
25+ const event = new Promise<any>((resolve) =>
26+ messageQueue.once("messageQueued", resolve),
27+ );
28+
29+ const ok = await messageQueue.enqueueMessage("hello world");
30+ expect(ok).toBe(true);
31+ expect(messageQueue.getQueueLength()).toBe(1);
32+
33+ const queued = await event;
34+ expect(queued.message).toBe("hello world");
35+ });
36+
37+ it("combines messages, merges image maps, writes history, and clears queue", async () => {
38+ const bufA = Buffer.from("A");
39+ const bufB = Buffer.from("B");
40+
41+ const img1 = new Map<string, Buffer>([["a", bufA]]);
42+ const img2 = new Map<string, Buffer>([["b", bufB]]);
43+
44+ const history = { addEntry: vi.fn() } as any;
45+
46+ await messageQueue.enqueueMessage("one", img1);
47+ await messageQueue.enqueueMessage("two", img2, history);
48+
49+ const combined = messageQueue.getAllQueuedMessages();
50+ expect(combined).toBeTruthy();
51+ expect(combined!.message).toBe("one\ntwo");
52+ expect(combined!.imageMap).toBeDefined();
53+ expect(combined!.imageMap!.get("a")).toEqual(bufA);
54+ expect(combined!.imageMap!.get("b")).toEqual(bufB);
55+
56+ // queue should be cleared
57+ expect(messageQueue.getQueueLength()).toBe(0);
58+
59+ // input history should receive the combined message
60+ expect(history.addEntry).toHaveBeenCalledWith("one\ntwo");
61+ });
62+});
added extensions/cli/src/stream/messageQueue.ts +94 −0
@@ -0,0 +1,94 @@
1+import { EventEmitter } from "events";
2+
3+import { InputHistory } from "../util/inputHistory.js";
4+import { logger } from "../util/logger.js";
5+
6+export interface QueuedMessage {
7+ message: string;
8+ imageMap?: Map<string, Buffer>;
9+ timestamp: number;
10+}
11+
12+export interface MessageProcessor {
13+ (message: string, imageMap?: Map<string, Buffer>): Promise<void>;
14+}
15+
16+/**
17+ * A queue to store messages that need to be processed later
18+ */
19+class MessageQueue extends EventEmitter {
20+ private queue: QueuedMessage[] = [];
21+ private inputHistory: InputHistory | undefined;
22+
23+ constructor() {
24+ super();
25+ }
26+
27+ async enqueueMessage(
28+ message: string,
29+ imageMap?: Map<string, Buffer>,
30+ inputHistory?: InputHistory,
31+ ): Promise<boolean> {
32+ this.inputHistory = inputHistory;
33+
34+ const queuedMessage: QueuedMessage = {
35+ message,
36+ imageMap,
37+ timestamp: Date.now(),
38+ };
39+
40+ this.queue.push(queuedMessage);
41+ logger.debug("MessageQueue: Message queued", {
42+ queueLength: this.queue.length,
43+ });
44+
45+ // Emit event for UI to show the queued message
46+ this.emit("messageQueued", queuedMessage);
47+
48+ return true;
49+ }
50+
51+ public getAllQueuedMessages() {
52+ if (this.queue.length === 0) return undefined;
53+
54+ // Combine all queued messages into one
55+ const combinedMessage = this.queue.map((msg) => msg.message).join("\n");
56+ const combinedImageMap = new Map<string, Buffer>();
57+
58+ // Merge all image maps
59+ for (const queuedMsg of this.queue) {
60+ if (queuedMsg.imageMap) {
61+ for (const [key, value] of queuedMsg.imageMap) {
62+ combinedImageMap.set(key, value);
63+ }
64+ }
65+ }
66+
67+ const result = {
68+ message: combinedMessage,
69+ imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined,
70+ timestamp: Date.now(),
71+ };
72+
73+ // Add to input history and clear the queue
74+ this.inputHistory?.addEntry(combinedMessage);
75+ this.queue = [];
76+
77+ logger.debug("MessageQueue: All messages dequeued and combined", {
78+ combinedLength: combinedMessage.length,
79+ queueLength: this.queue.length,
80+ });
81+
82+ return result;
83+ }
84+
85+ public getLatestMessage() {
86+ return this.getAllQueuedMessages();
87+ }
88+
89+ getQueueLength(): number {
90+ return this.queue.length;
91+ }
92+}
93+
94+export const messageQueue = new MessageQueue();
modified extensions/cli/src/ui/TUIChat.tsx +2 −0
@@ -188,6 +188,7 @@
188188 inputMode,
189189 activePermissionRequest,
190190 wasInterrupted,
191+ queuedMessages,
191192 handleUserMessage,
192193 handleInterrupt,
193194 handleFileAttached,
@@ -282,6 +283,7 @@
282283 model={services.model?.model || undefined}
283284 mcpService={services.mcp?.mcpService || undefined}
284285 chatHistory={chatHistory}
286+ queuedMessages={queuedMessages}
285287 renderMessage={renderMessage}
286288 refreshTrigger={staticRefreshTrigger}
287289 />
modified extensions/cli/src/ui/UserInput.tsx +12 −15
@@ -9,6 +9,7 @@
99 import type { FileIndexServiceState } from "../services/FileIndexService.js";
1010 import { SERVICE_NAMES, serviceContainer } from "../services/index.js";
1111 import { modeService } from "../services/ModeService.js";
12+import { messageQueue } from "../stream/messageQueue.js";
1213 import { InputHistory } from "../util/inputHistory.js";
1314
1415 import { FileSearchUI } from "./FileSearchUI.js";
@@ -515,7 +516,7 @@
515516 }
516517
517518 // Normal Enter behavior - submit if there's content
518- if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) {
519+ if (textBuffer.text.trim() || wasInterrupted) {
519520 // Get images before expanding paste blocks
520521 const imageMap = textBuffer.getAllImages();
521522
@@ -523,14 +524,19 @@
523524 textBuffer.expandAllPasteBlocks();
524525 const submittedText = textBuffer.text.trim();
525526
526- // Only add to history if there's actual text (not when resuming)
527- if (submittedText) {
527+ if (isWaitingForResponse) {
528+ // Process message later when LLM has responded
529+ void messageQueue.enqueueMessage(
530+ submittedText,
531+ imageMap,
532+ inputHistory,
533+ );
534+ } else {
535+ // Submit with images
528536 inputHistory.addEntry(submittedText);
537+ onSubmit(submittedText, imageMap);
529538 }
530539
531- // Submit with images
532- onSubmit(submittedText, imageMap);
533-
534540 textBuffer.clear();
535541 setInputText("");
536542 setCursorPosition(0);
@@ -647,15 +653,6 @@
647653 return;
648654 }
649655
650- // Allow typing during streaming, but block submission
651- if (!inputMode) {
652- // Block only Enter key submission during streaming
653- if (key.return && !key.shift) {
654- return;
655- }
656- // Allow all other input (typing, navigation, etc.)
657- }
658-
659656 // Handle slash command navigation
660657 if (showSlashCommands) {
661658 if (handleSlashCommandNavigation(key)) {
modified extensions/cli/src/ui/components/StaticChatContent.tsx +13 −1
@@ -1,9 +1,10 @@
11 import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
2-import { Box, Static, useStdout } from "ink";
2+import { Box, Static, Text, useStdout } from "ink";
33 import React, { useCallback, useEffect, useRef, useState } from "react";
44
55 import type { ChatHistoryItem } from "../../../../../core/index.js";
66 import type { MCPService } from "../../services/MCPService.js";
7+import type { QueuedMessage } from "../../stream/messageQueue.js";
78 import { useTerminalSize } from "../hooks/useTerminalSize.js";
89 import { IntroMessage } from "../IntroMessage.js";
910
@@ -13,6 +14,7 @@
1314 model?: ModelConfig;
1415 mcpService?: MCPService;
1516 chatHistory: ChatHistoryItem[];
17+ queuedMessages?: QueuedMessage[];
1618 renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement;
1719 refreshTrigger?: number; // Add a prop to trigger refresh from parent
1820 }
@@ -23,6 +25,7 @@
2325 model,
2426 mcpService,
2527 chatHistory,
28+ queuedMessages = [],
2629 renderMessage,
2730 refreshTrigger,
2831 }) => {
@@ -140,6 +143,15 @@
140143 <React.Fragment key={`pending-${index}`}>{item}</React.Fragment>
141144 ))}
142145 </Box>
146+
147+ {/* Queued messages - show at bottom with queue indicators */}
148+ {queuedMessages.length > 0 && (
149+ <Box paddingLeft={2} paddingBottom={1}>
150+ <Text color="gray" italic>
151+ {queuedMessages.map((msg) => msg.message).join("\n")}
152+ </Text>
153+ </Box>
154+ )}
143155 </Box>
144156 );
145157 };
modified extensions/cli/src/ui/hooks/useChat.ts +126 −44
@@ -1,3 +1,4 @@
1+/* eslint-disable max-lines */
12 import type { ChatHistoryItem, Session } from "core/index.js";
23 import { useApp } from "ink";
34 import { useEffect, useRef, useState } from "react";
@@ -11,6 +12,7 @@
1112 updateSessionHistory,
1213 } from "../../session.js";
1314 import { handleSlashCommands } from "../../slashCommands.js";
15+import { messageQueue, QueuedMessage } from "../../stream/messageQueue.js";
1416 import { telemetryService } from "../../telemetry/telemetryService.js";
1517 import { formatError } from "../../util/formatError.js";
1618 import { logger } from "../../util/logger.js";
@@ -166,6 +168,22 @@
166168 // Track interrupted state for resume functionality
167169 const [wasInterrupted, setWasInterrupted] = useState(false);
168170
171+ // Track queued messages for immediate display
172+ const [queuedMessages, setQueuedMessages] = useState<QueuedMessage[]>([]);
173+
174+ // Set up message queue listeners
175+ useEffect(() => {
176+ const onMessageQueued = (queuedMessage: QueuedMessage) => {
177+ setQueuedMessages((prev) => [...prev, queuedMessage]);
178+ };
179+
180+ messageQueue.on("messageQueued", onMessageQueued);
181+
182+ return () => {
183+ messageQueue.off("messageQueued", onMessageQueued);
184+ };
185+ }, []);
186+
169187 // Clean up abort controller on unmount
170188 useEffect(() => {
171189 return () => {
@@ -306,6 +324,30 @@
306324 setIsWaitingForResponse(false);
307325 setResponseStartTime(null);
308326 setInputMode(true);
327+
328+ // Check if there are queued messages and process them after a microtask delay
329+ // This ensures the GUI state has been updated before processing the next message
330+ const queuedMessageData = messageQueue.getLatestMessage();
331+ if (queuedMessageData) {
332+ const { message: latestQueuedMessage, imageMap } = queuedMessageData;
333+ logger.debug("processing queued message", { latestQueuedMessage });
334+
335+ // Clear all queued messages from display since we're processing them all together
336+ setQueuedMessages([]);
337+
338+ // Add the queued message to chat history so it shows in the GUI
339+ const formattedQueuedMessage = await formatMessageWithFiles(
340+ latestQueuedMessage,
341+ [], // No attached files for queued messages
342+ imageMap,
343+ );
344+ setChatHistory((prev) => [...prev, formattedQueuedMessage]);
345+
346+ await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui
347+
348+ // Process the queued message using the internal processing logic without re-adding to history
349+ await processQueuedMessage(latestQueuedMessage, imageMap);
350+ }
309351 }
310352 };
311353
@@ -398,20 +440,11 @@
398440 .join("");
399441 };
400442
401- const handleUserMessage = async (
443+ const processMessage = async (
402444 message: string,
403445 imageMap?: Map<string, Buffer>,
446+ isQueuedMessage: boolean = false,
404447 ) => {
405- // Check if this is a resume request (empty message after interruption)
406- if (await handleResumeRequest(message)) {
407- return;
408- }
409-
410- // Clear interrupted state if user types a new message
411- if (wasInterrupted && message !== "") {
412- setWasInterrupted(false);
413- }
414-
415448 // Handle special commands
416449 const handled = await handleSpecialCommands({
417450 message,
@@ -440,27 +473,9 @@
440473 // Track telemetry
441474 trackUserMessage(message, model);
442475
443- // Format message with attached files and images
444- logger.debug("Processing message with images", {
445- hasImages: !!(imageMap && imageMap.size > 0),
446- imageCount: imageMap?.size || 0,
447- });
448- const newUserMessage = await formatMessageWithFiles(
449- message,
450- attachedFiles,
451- imageMap,
452- );
453- logger.debug("Message formatted successfully");
454-
455- if (attachedFiles.length > 0) {
456- setAttachedFiles([]);
457- }
458-
459476 // In remote mode, send message to server instead of processing locally
460477 if (isRemoteMode && remoteUrl) {
461- const messageContentString = convertMessageContentToString(
462- newUserMessage.message.content,
463- );
478+ const messageContentString = convertMessageContentToString(message);
464479
465480 await handleRemoteMessage({
466481 remoteUrl,
@@ -469,23 +484,87 @@
469484 return;
470485 }
471486
472- // Check if auto-compacting is needed BEFORE adding user message
473- const { currentChatHistory, currentCompactionIndex } =
474- await handleAutoCompaction({
475- chatHistory,
476- model,
477- llmApi,
478- compactionIndex,
479- setChatHistory: setChatHistory,
480- setCompactionIndex,
487+ // For non-queued messages, format and add to chat history
488+ if (isQueuedMessage) {
489+ // For queued messages, chat history is already updated
490+ // Check if auto-compacting is needed with current history
491+ const { currentChatHistory, currentCompactionIndex } =
492+ await handleAutoCompaction({
493+ chatHistory,
494+ model,
495+ llmApi,
496+ compactionIndex,
497+ setChatHistory: setChatHistory,
498+ setCompactionIndex,
499+ });
500+
501+ // Execute the streaming response with the current history (which already includes the queued message)
502+ await executeStreamingResponse(
503+ currentChatHistory,
504+ currentCompactionIndex,
505+ );
506+ } else {
507+ // Format message with attached files and images
508+ logger.debug("Processing message with images", {
509+ hasImages: !!(imageMap && imageMap.size > 0),
510+ imageCount: imageMap?.size || 0,
481511 });
512+ const newUserMessage = await formatMessageWithFiles(
513+ message,
514+ attachedFiles,
515+ imageMap,
516+ );
517+ logger.debug("Message formatted successfully");
482518
483- // Add the formatted user message to history
484- const newHistory = [...currentChatHistory, newUserMessage];
485- setChatHistory(newHistory);
519+ if (attachedFiles.length > 0) {
520+ setAttachedFiles([]);
521+ }
522+
523+ // Check if auto-compacting is needed BEFORE adding user message
524+ const { currentChatHistory, currentCompactionIndex } =
525+ await handleAutoCompaction({
526+ chatHistory,
527+ model,
528+ llmApi,
529+ compactionIndex,
530+ setChatHistory: setChatHistory,
531+ setCompactionIndex,
532+ });
533+
534+ // Add the formatted user message to history
535+ const newHistory = [...currentChatHistory, newUserMessage];
536+ setChatHistory(newHistory);
537+
538+ // Execute the streaming response
539+ await executeStreamingResponse(newHistory, currentCompactionIndex);
540+ }
541+ };
542+
543+ const processQueuedMessage = async (
544+ message: string,
545+ imageMap?: Map<string, Buffer>,
546+ ) => {
547+ // For queued messages, we can reuse the core message processing logic
548+ // by calling the internal processing function directly
549+ await processMessage(message, imageMap, true);
550+ };
551+
552+ const handleUserMessage = async (
553+ message: string,
554+ imageMap?: Map<string, Buffer>,
555+ ) => {
556+ // Check if this is a resume request (empty message after interruption)
557+ if (await handleResumeRequest(message)) {
558+ return;
559+ }
560+
561+ // Clear interrupted state if user types a new message
562+ if (wasInterrupted && message !== "") {
563+ setWasInterrupted(false);
564+ }
486565
487- // Execute the streaming response
488- await executeStreamingResponse(newHistory, currentCompactionIndex);
566+ // Use the common message processing logic
567+ await processMessage(message, imageMap, false);
489568 };
490569
491570 const handleInterrupt = () => {
@@ -537,6 +616,8 @@
537616 additionalRules,
538617 );
539618 setChatHistory(newHistory);
619+ // Clear any queued messages when resetting chat
620+ setQueuedMessages([]);
540621 };
541622
542623 const handleToolPermissionResponse = async (
@@ -614,6 +695,7 @@
614695 attachedFiles,
615696 activePermissionRequest,
616697 wasInterrupted,
698+ queuedMessages,
617699 handleUserMessage,
618700 handleInterrupt,
619701 handleFileAttached,