Elffuss BraidHub

kikocis/continue public

Merge pull request #7695 from continuedev/tingwai/con-3770-compaction-ui

feat: improve compaction UI, show compaction message as status message
Changesetcda4ebce3e94c9b923e200294c6ce90bfe42107c8d05101dd1ea1ed4b767dfd3
AuthorTing-Wai <40179554+tingwai@users.noreply.github.com> · 2025-09-11 13:44 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-11 13:44 -07:00
Parentsa1c2d8694414, 8ae1d4b12543

Browse the files at this changeset

11 files changed

modified extensions/cli/src/compaction.ts +3 −1
@@ -28,6 +28,7 @@
2828 * @param model The model configuration
2929 * @param llmApi The LLM API instance
3030 * @param callbacks Optional callbacks for streaming updates
31+ * @param abortController Optional abort controller for cancellation
3132 * @returns The compacted history with compaction index
3233 */
3334 export async function compactChatHistory(
@@ -35,6 +36,7 @@
3536 model: ModelConfig,
3637 llmApi: BaseLlmApi,
3738 callbacks?: CompactionCallbacks,
39+ abortController?: AbortController,
3840 ): Promise<CompactionResult> {
3941 // Create a prompt to summarize the conversation
4042 const compactionPrompt: ChatHistoryItem = {
@@ -81,7 +83,7 @@
8183 }
8284
8385 // Stream the compaction response (service drives updates; this collects content locally)
84- const controller = new AbortController();
86+ const controller = abortController || new AbortController();
8587
8688 let compactionContent = "";
8789 const streamCallbacks: StreamCallbacks = {
modified extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts +1 −1
@@ -147,7 +147,7 @@
147147 "Auto-compacting...",
148148 );
149149 expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith(
150- "✓ Chat history auto-compacted successfully.",
150+ "Chat history auto-compacted successfully.",
151151 );
152152
153153 expect(result).toEqual({
modified extensions/cli/src/stream/streamChatResponse.autoCompaction.ts +1 −1
@@ -55,7 +55,7 @@
5555 ) {
5656 if (isHeadless) return;
5757
58- const successMessage = "✓ Chat history auto-compacted successfully.";
58+ const successMessage = "Chat history auto-compacted successfully.";
5959
6060 if (callbacks?.onSystemMessage) {
6161 callbacks.onSystemMessage(successMessage);
modified extensions/cli/src/ui/TUIChat.tsx +20 −15
@@ -1,4 +1,4 @@
1-import { Box, Text } from "ink";
1+import { Box } from "ink";
22 import React, {
33 useCallback,
44 useEffect,
@@ -17,6 +17,7 @@
1717 } from "../services/types.js";
1818 import { logger } from "../util/logger.js";
1919
20+import { ActionStatus } from "./components/ActionStatus.js";
2021 import { BottomStatusBar } from "./components/BottomStatusBar.js";
2122 import { ResourceDebugBar } from "./components/ResourceDebugBar.js";
2223 import { ScreenContent } from "./components/ScreenContent.js";
@@ -31,8 +32,6 @@
3132 useLoginHandlers,
3233 useSelectors,
3334 } from "./hooks/useTUIChatHooks.js";
34-import { LoadingAnimation } from "./LoadingAnimation.js";
35-import { Timer } from "./Timer.js";
3635
3736 interface TUIChatProps {
3837 // Remote mode props
@@ -185,6 +184,8 @@
185184 setChatHistory,
186185 isWaitingForResponse,
187186 responseStartTime,
187+ isCompacting,
188+ compactionStartTime,
188189 inputMode,
189190 activePermissionRequest,
190191 wasInterrupted,
@@ -292,18 +293,21 @@
292293 {/* Fixed bottom section */}
293294 <Box flexDirection="column" flexShrink={0}>
294295 {/* Status */}
295- {isWaitingForResponse && responseStartTime && (
296- <Box paddingX={1} flexDirection="row" gap={1}>
297- <LoadingAnimation visible={isWaitingForResponse} />
298- <Text key="loading-start" color="gray">
299- (
300- </Text>
301- <Timer startTime={responseStartTime} />
302- <Text key="loading-end" color="gray">
303- • esc to interrupt )
304- </Text>
305- </Box>
306- )}
296+ <ActionStatus
297+ visible={isWaitingForResponse && !!responseStartTime}
298+ startTime={responseStartTime || 0}
299+ message=""
300+ showSpinner={true}
301+ />
302+
303+ {/* Compaction Status */}
304+ <ActionStatus
305+ visible={isCompacting && !!compactionStartTime}
306+ startTime={compactionStartTime || 0}
307+ message="Compacting history"
308+ showSpinner={true}
309+ loadingColor="grey"
310+ />
307311
308312 {/* All screen-specific content */}
309313 <ScreenContent
@@ -320,6 +324,7 @@
320324 handleToolPermissionResponse={handleToolPermissionResponse}
321325 handleUserMessage={handleUserMessage}
322326 isWaitingForResponse={isWaitingForResponse}
327+ isCompacting={isCompacting}
323328 inputMode={inputMode}
324329 handleInterrupt={handleInterrupt}
325330 handleFileAttached={handleFileAttached}
modified extensions/cli/src/ui/UserInput.tsx +10 −2
@@ -95,6 +95,7 @@
9595 interface UserInputProps {
9696 onSubmit: (message: string, imageMap?: Map<string, Buffer>) => void;
9797 isWaitingForResponse: boolean;
98+ isCompacting?: boolean;
9899 inputMode: boolean;
99100 onInterrupt?: () => void;
100101 assistant?: AssistantConfig;
@@ -110,6 +111,7 @@
110111 const UserInput: React.FC<UserInputProps> = ({
111112 onSubmit,
112113 isWaitingForResponse,
114+ isCompacting = false,
113115 inputMode,
114116 onInterrupt,
115117 assistant,
@@ -524,8 +526,8 @@
524526 textBuffer.expandAllPasteBlocks();
525527 const submittedText = textBuffer.text.trim();
526528
527- if (isWaitingForResponse) {
528- // Process message later when LLM has responded
529+ if (isWaitingForResponse || isCompacting) {
530+ // Process message later when LLM has responded or compaction is complete
529531 void messageQueue.enqueueMessage(
530532 submittedText,
531533 imageMap,
@@ -576,6 +578,12 @@
576578 return true;
577579 }
578580
581+ // Handle escape key to interrupt compaction (higher priority)
582+ if (isCompacting && onInterrupt) {
583+ onInterrupt();
584+ return true;
585+ }
586+
579587 // Handle escape key to interrupt streaming
580588 if (isWaitingForResponse && onInterrupt) {
581589 onInterrupt();
added extensions/cli/src/ui/__tests__/TUIChat.actionStatus.test.tsx +214 −0
@@ -0,0 +1,214 @@
1+import { render } from "ink-testing-library";
2+import React from "react";
3+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
5+import { createUITestContext } from "../../test-helpers/ui-test-context.js";
6+import { AppRoot } from "../AppRoot.js";
7+
8+// Mock the useChat hook to control state
9+const mockUseChat = vi.fn();
10+
11+vi.mock("../hooks/useChat.js", () => ({
12+ useChat: () => mockUseChat(),
13+}));
14+
15+describe("TUIChat - ActionStatus", () => {
16+ let context: any;
17+
18+ beforeEach(() => {
19+ context = createUITestContext({
20+ allServicesReady: true,
21+ serviceState: "ready",
22+ });
23+
24+ // Default mock return value
25+ mockUseChat.mockReturnValue({
26+ chatHistory: [],
27+ setChatHistory: vi.fn(),
28+ isWaitingForResponse: false,
29+ responseStartTime: null,
30+ isCompacting: false,
31+ compactionStartTime: null,
32+ inputMode: true,
33+ attachedFiles: [],
34+ activePermissionRequest: null,
35+ wasInterrupted: false,
36+ handleUserMessage: vi.fn(),
37+ handleInterrupt: vi.fn(),
38+ handleFileAttached: vi.fn(),
39+ resetChatHistory: vi.fn(),
40+ handleToolPermissionResponse: vi.fn(),
41+ });
42+ });
43+
44+ afterEach(() => {
45+ context.cleanup();
46+ vi.clearAllMocks();
47+ });
48+
49+ it("shows only response status when waiting for response", () => {
50+ const responseStartTime = Date.now();
51+
52+ mockUseChat.mockReturnValue({
53+ chatHistory: [],
54+ setChatHistory: vi.fn(),
55+ isWaitingForResponse: true,
56+ responseStartTime,
57+ isCompacting: false,
58+ compactionStartTime: null,
59+ inputMode: false,
60+ attachedFiles: [],
61+ activePermissionRequest: null,
62+ wasInterrupted: false,
63+ handleUserMessage: vi.fn(),
64+ handleInterrupt: vi.fn(),
65+ handleFileAttached: vi.fn(),
66+ resetChatHistory: vi.fn(),
67+ handleToolPermissionResponse: vi.fn(),
68+ });
69+
70+ const { lastFrame, unmount } = render(React.createElement(AppRoot, {}));
71+
72+ try {
73+ const frame = lastFrame();
74+ expect(frame).toBeDefined();
75+
76+ // Should show spinner/response indicator but not compaction message
77+ expect(frame).toContain("esc to interrupt");
78+ expect(frame).not.toContain("Compacting history");
79+ } finally {
80+ unmount();
81+ }
82+ });
83+
84+ it("shows only compaction status when compacting", () => {
85+ const compactionStartTime = Date.now();
86+
87+ mockUseChat.mockReturnValue({
88+ chatHistory: [],
89+ setChatHistory: vi.fn(),
90+ isWaitingForResponse: false,
91+ responseStartTime: null,
92+ isCompacting: true,
93+ compactionStartTime,
94+ inputMode: true,
95+ attachedFiles: [],
96+ activePermissionRequest: null,
97+ wasInterrupted: false,
98+ handleUserMessage: vi.fn(),
99+ handleInterrupt: vi.fn(),
100+ handleFileAttached: vi.fn(),
101+ resetChatHistory: vi.fn(),
102+ handleToolPermissionResponse: vi.fn(),
103+ });
104+
105+ const { lastFrame, unmount } = render(React.createElement(AppRoot, {}));
106+
107+ try {
108+ const frame = lastFrame();
109+ expect(frame).toBeDefined();
110+
111+ // Should show compaction message but not spinner
112+ expect(frame).toContain("Compacting history");
113+ expect(frame).toContain("esc to interrupt");
114+ } finally {
115+ unmount();
116+ }
117+ });
118+
119+ it("shows neither status when both states are false", () => {
120+ mockUseChat.mockReturnValue({
121+ chatHistory: [],
122+ setChatHistory: vi.fn(),
123+ isWaitingForResponse: false,
124+ responseStartTime: null,
125+ isCompacting: false,
126+ compactionStartTime: null,
127+ inputMode: true,
128+ attachedFiles: [],
129+ activePermissionRequest: null,
130+ wasInterrupted: false,
131+ handleUserMessage: vi.fn(),
132+ handleInterrupt: vi.fn(),
133+ handleFileAttached: vi.fn(),
134+ resetChatHistory: vi.fn(),
135+ handleToolPermissionResponse: vi.fn(),
136+ });
137+
138+ const { lastFrame, unmount } = render(React.createElement(AppRoot, {}));
139+
140+ try {
141+ const frame = lastFrame();
142+ expect(frame).toBeDefined();
143+
144+ // Should not show any status messages
145+ expect(frame).not.toContain("Compacting history");
146+ // The basic UI should still be there
147+ expect(frame).toContain("Ask anything");
148+ } finally {
149+ unmount();
150+ }
151+ });
152+
153+ it("handles state transitions correctly", () => {
154+ const { lastFrame, rerender, unmount } = render(
155+ React.createElement(AppRoot, {}),
156+ );
157+
158+ // Start with compaction
159+ const compactionStartTime = Date.now();
160+ mockUseChat.mockReturnValue({
161+ chatHistory: [],
162+ setChatHistory: vi.fn(),
163+ isWaitingForResponse: false,
164+ responseStartTime: null,
165+ isCompacting: true,
166+ compactionStartTime,
167+ inputMode: true,
168+ attachedFiles: [],
169+ activePermissionRequest: null,
170+ wasInterrupted: false,
171+ handleUserMessage: vi.fn(),
172+ handleInterrupt: vi.fn(),
173+ handleFileAttached: vi.fn(),
174+ resetChatHistory: vi.fn(),
175+ handleToolPermissionResponse: vi.fn(),
176+ });
177+
178+ try {
179+ rerender(React.createElement(AppRoot, {}));
180+
181+ let frame = lastFrame();
182+ expect(frame).toContain("Compacting history");
183+ expect(frame).not.toContain("⠀⠁⠃⠇⠏⠟⠿⣿"); // No spinner chars when only compacting
184+
185+ // Transition to response waiting
186+ const responseStartTime = Date.now();
187+ mockUseChat.mockReturnValue({
188+ chatHistory: [],
189+ setChatHistory: vi.fn(),
190+ isWaitingForResponse: true,
191+ responseStartTime,
192+ isCompacting: false,
193+ compactionStartTime: null,
194+ inputMode: false,
195+ attachedFiles: [],
196+ activePermissionRequest: null,
197+ wasInterrupted: false,
198+ handleUserMessage: vi.fn(),
199+ handleInterrupt: vi.fn(),
200+ handleFileAttached: vi.fn(),
201+ resetChatHistory: vi.fn(),
202+ handleToolPermissionResponse: vi.fn(),
203+ });
204+
205+ rerender(React.createElement(AppRoot, {}));
206+
207+ frame = lastFrame();
208+ expect(frame).not.toContain("Compacting history");
209+ expect(frame).toContain("esc to interrupt");
210+ } finally {
211+ unmount();
212+ }
213+ });
214+});
added extensions/cli/src/ui/__tests__/TUIChat.compactionCancellation.test.tsx +141 −0
@@ -0,0 +1,141 @@
1+import { render } from "ink-testing-library";
2+import React from "react";
3+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
5+import { createUITestContext } from "../../test-helpers/ui-test-context.js";
6+import { AppRoot } from "../AppRoot.js";
7+
8+// Mock the useChat hook to control state
9+const mockUseChat = vi.fn();
10+const mockHandleInterrupt = vi.fn();
11+
12+vi.mock("../hooks/useChat.js", () => ({
13+ useChat: () => mockUseChat(),
14+}));
15+
16+describe("TUIChat - Compaction Cancellation", () => {
17+ let context: any;
18+
19+ beforeEach(() => {
20+ context = createUITestContext({
21+ allServicesReady: true,
22+ serviceState: "ready",
23+ });
24+
25+ // Reset the mock
26+ mockHandleInterrupt.mockClear();
27+ });
28+
29+ afterEach(() => {
30+ context.cleanup();
31+ vi.clearAllMocks();
32+ });
33+
34+ it("calls handleInterrupt when ESC is pressed during compaction", () => {
35+ const compactionStartTime = Date.now();
36+
37+ mockUseChat.mockReturnValue({
38+ chatHistory: [],
39+ setChatHistory: vi.fn(),
40+ isWaitingForResponse: false,
41+ responseStartTime: null,
42+ isCompacting: true,
43+ compactionStartTime,
44+ inputMode: true, // Changed to true so ESC handling is active
45+ attachedFiles: [],
46+ activePermissionRequest: null,
47+ wasInterrupted: false,
48+ handleUserMessage: vi.fn(),
49+ handleInterrupt: mockHandleInterrupt,
50+ handleFileAttached: vi.fn(),
51+ resetChatHistory: vi.fn(),
52+ handleToolPermissionResponse: vi.fn(),
53+ });
54+
55+ const { stdin, unmount } = render(React.createElement(AppRoot, {}));
56+
57+ try {
58+ // Give some time for the component to render and set up input handling
59+ setTimeout(() => {
60+ // Simulate ESC key press during compaction
61+ stdin.write("\x1b"); // ESC key
62+
63+ // The handleInterrupt should be called
64+ expect(mockHandleInterrupt).toHaveBeenCalledTimes(1);
65+ }, 100);
66+ } finally {
67+ unmount();
68+ }
69+ });
70+
71+ it("shows compaction status with esc to interrupt message", () => {
72+ const compactionStartTime = Date.now();
73+
74+ mockUseChat.mockReturnValue({
75+ chatHistory: [],
76+ setChatHistory: vi.fn(),
77+ isWaitingForResponse: false,
78+ responseStartTime: null,
79+ isCompacting: true,
80+ compactionStartTime,
81+ inputMode: false,
82+ attachedFiles: [],
83+ activePermissionRequest: null,
84+ wasInterrupted: false,
85+ handleUserMessage: vi.fn(),
86+ handleInterrupt: mockHandleInterrupt,
87+ handleFileAttached: vi.fn(),
88+ resetChatHistory: vi.fn(),
89+ handleToolPermissionResponse: vi.fn(),
90+ });
91+
92+ const { lastFrame, unmount } = render(React.createElement(AppRoot, {}));
93+
94+ try {
95+ const frame = lastFrame();
96+ expect(frame).toBeDefined();
97+
98+ // Should show compaction message with interrupt option
99+ expect(frame).toContain("Compacting history");
100+ expect(frame).toContain("esc to interrupt");
101+ } finally {
102+ unmount();
103+ }
104+ });
105+
106+ it("prioritizes compaction cancellation over response cancellation", () => {
107+ // This tests the case where both might be true (theoretical edge case)
108+ const compactionStartTime = Date.now();
109+ const responseStartTime = Date.now();
110+
111+ mockUseChat.mockReturnValue({
112+ chatHistory: [],
113+ setChatHistory: vi.fn(),
114+ isWaitingForResponse: true,
115+ responseStartTime,
116+ isCompacting: true,
117+ compactionStartTime,
118+ inputMode: false,
119+ attachedFiles: [],
120+ activePermissionRequest: null,
121+ wasInterrupted: false,
122+ handleUserMessage: vi.fn(),
123+ handleInterrupt: mockHandleInterrupt,
124+ handleFileAttached: vi.fn(),
125+ resetChatHistory: vi.fn(),
126+ handleToolPermissionResponse: vi.fn(),
127+ });
128+
129+ const { stdin, unmount } = render(React.createElement(AppRoot, {}));
130+
131+ try {
132+ // Simulate ESC key press when both states are active
133+ stdin.write("\x1b"); // ESC key
134+
135+ // Should still call handleInterrupt (which will prioritize compaction)
136+ expect(mockHandleInterrupt).toHaveBeenCalledTimes(1);
137+ } finally {
138+ unmount();
139+ }
140+ });
141+});
added extensions/cli/src/ui/components/ActionStatus.tsx +37 −0
@@ -0,0 +1,37 @@
1+import { Box, Text } from "ink";
2+import React from "react";
3+
4+import { LoadingAnimation } from "../LoadingAnimation.js";
5+import { Timer } from "../Timer.js";
6+
7+interface ActionStatusProps {
8+ visible: boolean;
9+ startTime: number;
10+ message: string;
11+ showSpinner?: boolean;
12+ color?: string;
13+ loadingColor?: string;
14+}
15+
16+const ActionStatus: React.FC<ActionStatusProps> = ({
17+ visible,
18+ startTime,
19+ message,
20+ showSpinner = false,
21+ color = "gray",
22+ loadingColor = "green",
23+}) => {
24+ if (!visible) return null;
25+
26+ return (
27+ <Box paddingX={1} flexDirection="row" gap={1}>
28+ {showSpinner && <LoadingAnimation color={loadingColor} visible={true} />}
29+ <Text color={color}>{message}</Text>
30+ <Text color="gray">(</Text>
31+ <Timer startTime={startTime} />
32+ <Text color="gray">• esc to interrupt )</Text>
33+ </Box>
34+ );
35+};
36+
37+export { ActionStatus };
modified extensions/cli/src/ui/components/ScreenContent.tsx +3 −0
@@ -32,6 +32,7 @@
3232 ) => void;
3333 handleUserMessage: (message: string, imageMap?: Map<string, Buffer>) => void;
3434 isWaitingForResponse: boolean;
35+ isCompacting: boolean;
3536 inputMode: boolean;
3637 handleInterrupt: () => void;
3738 handleFileAttached: (filePath: string, content: string) => void;
@@ -55,6 +56,7 @@
5556 handleToolPermissionResponse,
5657 handleUserMessage,
5758 isWaitingForResponse,
59+ isCompacting,
5860 inputMode,
5961 handleInterrupt,
6062 handleFileAttached,
@@ -149,6 +151,7 @@
149151 <UserInput
150152 onSubmit={handleUserMessage}
151153 isWaitingForResponse={isWaitingForResponse}
154+ isCompacting={isCompacting}
152155 inputMode={inputMode}
153156 onInterrupt={handleInterrupt}
154157 assistant={services.config?.config || undefined}
modified extensions/cli/src/ui/hooks/useChat.compaction.ts +79 −50
@@ -14,6 +14,9 @@
1414 setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
1515 currentSession: Session;
1616 setCurrentSession: React.Dispatch<React.SetStateAction<Session>>;
17+ setIsCompacting: (value: boolean) => void;
18+ setCompactionStartTime: (time: number | null) => void;
19+ setCompactionAbortController: (controller: AbortController | null) => void;
1720 }
1821
1922 /**
@@ -27,22 +30,32 @@
2730 setCompactionIndex,
2831 currentSession,
2932 setCurrentSession,
33+ setIsCompacting,
34+ setCompactionStartTime,
35+ setCompactionAbortController,
3036 }: HandleCompactCommandOptions): Promise<void> {
31- // Add compacting message
32- setChatHistory((prev) => [
33- ...prev,
34- {
35- message: {
36- role: "system",
37- content: "Compacting chat history...",
38- },
39- contextItems: [],
40- },
41- ]);
37+ // Create abort controller for cancellation support
38+ const compactionController = new AbortController();
39+ setCompactionAbortController(compactionController);
40+
41+ // Start compaction status display
42+ setIsCompacting(true);
43+ setCompactionStartTime(Date.now());
4244
4345 try {
44- // Compact the chat history directly (already in unified format)
45- const result = await compactChatHistory(chatHistory, model, llmApi);
46+ // Compact the chat history directly (already in unified format) with abort controller
47+ const result = await compactChatHistory(
48+ chatHistory,
49+ model,
50+ llmApi,
51+ undefined,
52+ compactionController,
53+ );
54+
55+ // Check if operation was aborted before proceeding with success actions
56+ if (compactionController.signal.aborted) {
57+ return;
58+ }
4659
4760 // Replace chat history with compacted version
4861 setChatHistory(result.compactedHistory);
@@ -56,6 +69,7 @@
5669 updateSessionHistory(result.compactedHistory);
5770 setCurrentSession(updatedSession);
5871
72+ // Add success message to chat
5973 setChatHistory((prev) => [
6074 ...prev,
6175 {
@@ -67,17 +81,37 @@
6781 },
6882 ]);
6983 } catch (error) {
70- logger.error("Compaction failed:", error);
71- setChatHistory((prev) => [
72- ...prev,
73- {
74- message: {
75- role: "system",
76- content: `Compaction failed: ${formatError(error)}`,
84+ // Check if the error was due to abortion
85+ if (compactionController.signal.aborted) {
86+ logger.info("Manual compaction was cancelled by user");
87+ setChatHistory((prev) => [
88+ ...prev,
89+ {
90+ message: {
91+ role: "system",
92+ content: "Compaction cancelled.",
93+ },
94+ contextItems: [],
7795 },
78- contextItems: [],
79- },
80- ]);
96+ ]);
97+ } else {
98+ logger.error("Compaction failed:", error);
99+ setChatHistory((prev) => [
100+ ...prev,
101+ {
102+ message: {
103+ role: "system",
104+ content: `Compaction failed: ${formatError(error)}`,
105+ },
106+ contextItems: [],
107+ },
108+ ]);
109+ }
110+ } finally {
111+ // Stop compaction status display
112+ setIsCompacting(false);
113+ setCompactionStartTime(null);
114+ setCompactionAbortController(null);
81115 }
82116 }
83117
@@ -88,6 +122,7 @@
88122 compactionIndex: number | null;
89123 setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
90124 setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
125+ abortController?: AbortController;
91126 }
92127
93128 /**
@@ -100,6 +135,7 @@
100135 compactionIndex: _compactionIndex,
101136 setChatHistory,
102137 setCompactionIndex,
138+ abortController,
103139 }: HandleAutoCompactionOptions): Promise<{
104140 currentChatHistory: ChatHistoryItem[];
105141 currentCompactionIndex: number | null;
@@ -116,20 +152,14 @@
116152
117153 logger.info("Auto-compaction triggered for TUI mode");
118154
119- // Add compacting message
120- setChatHistory((prev) => [
121- ...prev,
122- {
123- message: {
124- role: "system",
125- content: "Auto-compacting chat history...",
126- },
127- contextItems: [],
128- },
129- ]);
130-
131155 // Compact the unified history
132- const result = await compactChatHistory(chatHistory, model, llmApi);
156+ const result = await compactChatHistory(
157+ chatHistory,
158+ model,
159+ llmApi,
160+ undefined,
161+ abortController,
162+ );
133163
134164 // Keep the system message and append the compaction summary
135165 // This replaces the old messages with a summary to reduce context size
@@ -151,23 +181,22 @@
151181 ? [systemMessage, compactedMessage]
152182 : [compactedMessage];
153183
154- setChatHistory(updatedHistory);
155- setCompactionIndex(updatedHistory.length - 1);
156-
157- // Add success message
158- setChatHistory((prev) => [
159- ...prev,
160- {
161- message: {
162- role: "system",
163- content: "✓ Chat history auto-compacted successfully.",
164- },
165- contextItems: [],
184+ // Add success message to the history that will be returned
185+ const successMessage: ChatHistoryItem = {
186+ message: {
187+ role: "system",
188+ content: "Chat history auto-compacted successfully.",
166189 },
167- ]);
190+ contextItems: [],
191+ };
192+
193+ const finalHistory = [...updatedHistory, successMessage];
194+
195+ setChatHistory(finalHistory);
196+ setCompactionIndex(updatedHistory.length - 1);
168197
169198 return {
170- currentChatHistory: updatedHistory,
199+ currentChatHistory: finalHistory,
171200 currentCompactionIndex: updatedHistory.length - 1,
172201 };
173202 } catch (error) {
modified extensions/cli/src/ui/hooks/useChat.ts +113 −20
@@ -1,4 +1,5 @@
11 /* eslint-disable max-lines */
2+/* eslint-disable max-statements */
23 import type { ChatHistoryItem, Session } from "core/index.js";
34 import { useApp } from "ink";
45 import { useEffect, useRef, useState } from "react";
@@ -140,9 +141,15 @@
140141 const [responseStartTime, setResponseStartTime] = useState<number | null>(
141142 null,
142143 );
144+ const [isCompacting, setIsCompacting] = useState(false);
145+ const [compactionStartTime, setCompactionStartTime] = useState<number | null>(
146+ null,
147+ );
143148 const [inputMode, setInputMode] = useState(true);
144149 const [abortController, setAbortController] =
145150 useState<AbortController | null>(null);
151+ const [compactionAbortController, setCompactionAbortController] =
152+ useState<AbortController | null>(null);
146153 const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState(
147154 // If we're resuming and found a saved session, we're already initialized
148155 // If we're forking and found a session to fork from, we're already initialized
@@ -332,20 +339,13 @@
332339 const { message: latestQueuedMessage, imageMap } = queuedMessageData;
333340 logger.debug("processing queued message", { latestQueuedMessage });
334341
335- // Clear all queued messages from display since we're processing them all together
342+ // Clear queued messages from display since they're about to be processed
343+ // Note: messageQueue.getLatestMessage() already cleared the actual queue
336344 setQueuedMessages([]);
337345
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-
346346 await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui
347347
348- // Process the queued message using the internal processing logic without re-adding to history
348+ // Process the queued message - it will handle adding to history and compaction display
349349 await processQueuedMessage(latestQueuedMessage, imageMap);
350350 }
351351 }
@@ -404,6 +404,9 @@
404404 setCompactionIndex,
405405 currentSession,
406406 setCurrentSession,
407+ setIsCompacting,
408+ setCompactionStartTime,
409+ setCompactionAbortController,
407410 });
408411 return null;
409412 }
@@ -486,23 +489,64 @@
486489
487490 // For non-queued messages, format and add to chat history
488491 if (isQueuedMessage) {
489- // For queued messages, chat history is already updated
492+ // For queued messages, we need to format and add to history after compaction
493+ // First, format the message
494+ const formattedQueuedMessage = await formatMessageWithFiles(
495+ message,
496+ [], // No attached files for queued messages
497+ imageMap,
498+ );
499+
490500 // Check if auto-compacting is needed with current history
491- const { currentChatHistory, currentCompactionIndex } =
492- await handleAutoCompaction({
501+ const compactionController = new AbortController();
502+ setCompactionAbortController(compactionController);
503+ setIsCompacting(true);
504+ setCompactionStartTime(Date.now());
505+
506+ // Add the queued message to queue display during compaction
507+ const queuedMessageForDisplay: QueuedMessage = {
508+ message,
509+ imageMap,
510+ timestamp: Date.now(),
511+ };
512+ setQueuedMessages((prev) => [...prev, queuedMessageForDisplay]);
513+
514+ let currentChatHistory, currentCompactionIndex;
515+ try {
516+ const result = await handleAutoCompaction({
493517 chatHistory,
494518 model,
495519 llmApi,
496520 compactionIndex,
497521 setChatHistory: setChatHistory,
498522 setCompactionIndex,
523+ abortController: compactionController,
499524 });
525+ currentChatHistory = result.currentChatHistory;
526+ currentCompactionIndex = result.currentCompactionIndex;
527+ } catch (error) {
528+ // If compaction fails, remove the queued message from display
529+ setQueuedMessages((prev) =>
530+ prev.filter((msg) => msg !== queuedMessageForDisplay),
531+ );
532+ throw error; // Re-throw to maintain error handling
533+ } finally {
534+ setIsCompacting(false);
535+ setCompactionStartTime(null);
536+ setCompactionAbortController(null);
537+ }
500538
501- // Execute the streaming response with the current history (which already includes the queued message)
502- await executeStreamingResponse(
503- currentChatHistory,
504- currentCompactionIndex,
539+ // Add the formatted queued message to history after compaction completes
540+ const newHistory = [...currentChatHistory, formattedQueuedMessage];
541+ setChatHistory(newHistory);
542+
543+ // Remove the queued message from display since it's now in chat history
544+ setQueuedMessages((prev) =>
545+ prev.filter((msg) => msg !== queuedMessageForDisplay),
505546 );
547+
548+ // Execute the streaming response with the updated history
549+ await executeStreamingResponse(newHistory, currentCompactionIndex);
506550 } else {
507551 // Format message with attached files and images
508552 logger.debug("Processing message with images", {
@@ -521,20 +565,53 @@
521565 }
522566
523567 // Check if auto-compacting is needed BEFORE adding user message
524- const { currentChatHistory, currentCompactionIndex } =
525- await handleAutoCompaction({
568+ const compactionController = new AbortController();
569+ setCompactionAbortController(compactionController);
570+ setIsCompacting(true);
571+ setCompactionStartTime(Date.now());
572+
573+ // Add the triggering message to queue display during compaction
574+ const compactionQueuedMessage: QueuedMessage = {
575+ message,
576+ imageMap,
577+ timestamp: Date.now(),
578+ };
579+ setQueuedMessages((prev) => [...prev, compactionQueuedMessage]);
580+
581+ let currentChatHistory, currentCompactionIndex;
582+ try {
583+ const result = await handleAutoCompaction({
526584 chatHistory,
527585 model,
528586 llmApi,
529587 compactionIndex,
530588 setChatHistory: setChatHistory,
531589 setCompactionIndex,
590+ abortController: compactionController,
532591 });
592+ currentChatHistory = result.currentChatHistory;
593+ currentCompactionIndex = result.currentCompactionIndex;
594+ } catch (error) {
595+ // If compaction fails, remove the triggering message from queue display
596+ setQueuedMessages((prev) =>
597+ prev.filter((msg) => msg !== compactionQueuedMessage),
598+ );
599+ throw error; // Re-throw to maintain error handling
600+ } finally {
601+ setIsCompacting(false);
602+ setCompactionStartTime(null);
603+ setCompactionAbortController(null);
604+ }
533605
534606 // Add the formatted user message to history
535607 const newHistory = [...currentChatHistory, newUserMessage];
536608 setChatHistory(newHistory);
537609
610+ // Remove the triggering message from queue display since it's now in chat history
611+ setQueuedMessages((prev) =>
612+ prev.filter((msg) => msg !== compactionQueuedMessage),
613+ );
614+
538615 // Execute the streaming response
539616 await executeStreamingResponse(newHistory, currentCompactionIndex);
540617 }
@@ -583,7 +660,21 @@
583660 return;
584661 }
585662
586- // Local mode: abort the controller
663+ // Local mode: abort the appropriate controller
664+
665+ // If compaction is running, abort compaction
666+ if (compactionAbortController && isCompacting) {
667+ compactionAbortController.abort();
668+ setIsCompacting(false);
669+ setCompactionStartTime(null);
670+ setCompactionAbortController(null);
671+ setInputMode(true);
672+ // Clear any queued messages (including the triggering message) when compaction is interrupted
673+ setQueuedMessages([]);
674+ return;
675+ }
676+
677+ // If response is running, abort response
587678 if (abortController && isWaitingForResponse) {
588679 abortController.abort();
589680
@@ -691,6 +782,8 @@
691782 setChatHistory: setChatHistory,
692783 isWaitingForResponse,
693784 responseStartTime,
785+ isCompacting,
786+ compactionStartTime,
694787 inputMode,
695788 attachedFiles,
696789 activePermissionRequest,