Elffuss BraidHub

kikocis/continue public

Merge pull request #7377 from continuedev/small-improvements

feat: resource monitoring, other small updates
Changesetb931dc13c72fa5381bd99591c7c5a68657850a7911da5a9296dfb3622fb90f27
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-08-24 15:13 -07:00
CommitterGitHub <noreply@github.com> · 2025-08-24 15:13 -07:00
Parentsa5fcde5311cf, 91a9520f90b2

Browse the files at this changeset

11 files changed

added extensions/cli/src/services/ResourceMonitoringService.test.ts +108 −0
@@ -0,0 +1,108 @@
1+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
3+import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
4+
5+// Mock the logger and BaseService
6+vi.mock("../util/logger.js", () => ({
7+ logger: {
8+ debug: vi.fn(),
9+ info: vi.fn(),
10+ warn: vi.fn(),
11+ error: vi.fn(),
12+ },
13+}));
14+
15+vi.mock("./BaseService.js", () => ({
16+ BaseService: class MockBaseService {
17+ logger = {
18+ debug: vi.fn(),
19+ info: vi.fn(),
20+ warn: vi.fn(),
21+ error: vi.fn(),
22+ };
23+ },
24+}));
25+
26+describe("ResourceMonitoringService", () => {
27+ let service: ResourceMonitoringService;
28+
29+ beforeEach(async () => {
30+ // Remove process event listeners to prevent interference
31+ process.removeAllListeners("exit");
32+ process.removeAllListeners("SIGINT");
33+ process.removeAllListeners("SIGTERM");
34+
35+ service = new ResourceMonitoringService();
36+ await service.initialize();
37+ });
38+
39+ afterEach(async () => {
40+ if (service) {
41+ service.stopMonitoring(); // Ensure monitoring is stopped
42+ await service.cleanup();
43+ }
44+ });
45+
46+ it("should initialize without starting monitoring by default", () => {
47+ expect(service).toBeDefined();
48+ // Should not be monitoring unless --verbose is passed
49+ const usage = service.getCurrentResourceUsage();
50+ expect(usage.timestamp).toBeGreaterThan(0);
51+ });
52+
53+ it("should collect current resource usage", () => {
54+ const usage = service.getCurrentResourceUsage();
55+
56+ expect(usage.timestamp).toBeGreaterThan(0);
57+ expect(usage.memory.rss).toBeGreaterThan(0);
58+ expect(usage.memory.heapTotal).toBeGreaterThan(0);
59+ expect(usage.memory.heapUsed).toBeGreaterThan(0);
60+ expect(usage.cpu.user).toBeGreaterThanOrEqual(0);
61+ expect(usage.cpu.system).toBeGreaterThanOrEqual(0);
62+ expect(usage.system.uptime).toBeGreaterThan(0);
63+ expect(usage.system.totalMemory).toBeGreaterThan(0);
64+ expect(usage.eventLoop.lag).toBeGreaterThanOrEqual(0);
65+ });
66+
67+ it("should provide resource summary", () => {
68+ const summary = service.getResourceSummary();
69+
70+ expect(summary.current).toBeDefined();
71+ expect(summary.peak).toBeDefined();
72+ expect(summary.average).toBeDefined();
73+
74+ expect(summary.peak.memory).toBeGreaterThan(0);
75+ expect(summary.peak.cpu).toBeGreaterThanOrEqual(0);
76+
77+ expect(summary.average.memory).toBeGreaterThan(0);
78+ expect(summary.average.cpu).toBeGreaterThanOrEqual(0);
79+ });
80+
81+ it("should start and stop monitoring", async () => {
82+ service.startMonitoring(100); // 100ms interval for test
83+
84+ // Wait for some data collection
85+ await new Promise((resolve) => setTimeout(resolve, 250));
86+
87+ const history = service.getResourceHistory();
88+ expect(history.length).toBeGreaterThan(0);
89+
90+ service.stopMonitoring();
91+ });
92+
93+ it("should handle verbose mode initialization", async () => {
94+ // Mock argv to include --verbose
95+ const originalArgv = process.argv;
96+ process.argv = [...originalArgv, "--verbose"];
97+
98+ const verboseService = new ResourceMonitoringService();
99+ await verboseService.initialize();
100+
101+ // Should start monitoring automatically
102+ // Note: Testing this properly would require checking internal state
103+ // which isn't directly exposed
104+
105+ await verboseService.cleanup();
106+ process.argv = originalArgv;
107+ });
108+});
added extensions/cli/src/services/ResourceMonitoringService.ts +312 −0
@@ -0,0 +1,312 @@
1+import { exec } from "child_process";
2+import * as os from "os";
3+import { promisify } from "util";
4+
5+import { logger } from "../util/logger.js";
6+
7+const execAsync = promisify(exec);
8+
9+export interface ResourceUsage {
10+ timestamp: number;
11+ memory: {
12+ rss: number; // Resident Set Size
13+ heapTotal: number;
14+ heapUsed: number;
15+ external: number;
16+ arrayBuffers: number;
17+ };
18+ cpu: {
19+ user: number;
20+ system: number;
21+ percent?: number; // CPU percentage (calculated)
22+ };
23+ system: {
24+ loadAverage: number[];
25+ uptime: number;
26+ freeMemory: number;
27+ totalMemory: number;
28+ };
29+ eventLoop: {
30+ lag: number;
31+ };
32+ fileDescriptors?: number;
33+}
34+
35+export interface ResourceMonitoringState {
36+ isMonitoring: boolean;
37+ resourceHistory: ResourceUsage[];
38+}
39+
40+class ResourceMonitoringService {
41+ private isMonitoring = false;
42+ private monitoringInterval?: NodeJS.Timeout;
43+ private intervalMs = 1000; // Default 1 second
44+ private resourceHistory: ResourceUsage[] = [];
45+ private maxHistorySize = 300; // Keep 5 minutes at 1s intervals
46+ private lastCpuUsage = process.cpuUsage();
47+ private lastTimestamp = Date.now();
48+
49+ async initialize(): Promise<void> {
50+ // Start monitoring if verbose mode is enabled
51+ if (process.argv.includes("--verbose")) {
52+ this.startMonitoring();
53+ }
54+
55+ // Cleanup on exit
56+ process.on("exit", () => this.cleanup());
57+ process.on("SIGINT", () => this.cleanup());
58+ process.on("SIGTERM", () => this.cleanup());
59+ }
60+
61+ async cleanup(): Promise<void> {
62+ this.stopMonitoring();
63+ }
64+
65+ public startMonitoring(intervalMs = 1000): void {
66+ if (this.isMonitoring) return;
67+
68+ this.intervalMs = intervalMs;
69+ this.isMonitoring = true;
70+ this.lastCpuUsage = process.cpuUsage();
71+ this.lastTimestamp = Date.now();
72+
73+ this.monitoringInterval = setInterval(() => {
74+ this.collectResourceUsage();
75+ }, this.intervalMs);
76+
77+ logger.debug("Resource monitoring started", { intervalMs });
78+ }
79+
80+ public stopMonitoring(): void {
81+ if (!this.isMonitoring) return;
82+
83+ this.isMonitoring = false;
84+ if (this.monitoringInterval) {
85+ clearInterval(this.monitoringInterval);
86+ this.monitoringInterval = undefined;
87+ }
88+
89+ logger.debug("Resource monitoring stopped");
90+ }
91+
92+ public getCurrentResourceUsage(): ResourceUsage {
93+ const now = Date.now();
94+ const currentCpuUsage = process.cpuUsage();
95+ const timeDiff = now - this.lastTimestamp;
96+
97+ // Calculate CPU percentage
98+ const userDiff = currentCpuUsage.user - this.lastCpuUsage.user;
99+ const systemDiff = currentCpuUsage.system - this.lastCpuUsage.system;
100+ const totalDiff = userDiff + systemDiff;
101+ const cpuPercent = timeDiff > 0 ? (totalDiff / (timeDiff * 1000)) * 100 : 0;
102+
103+ const memoryUsage = process.memoryUsage();
104+
105+ const usage: ResourceUsage = {
106+ timestamp: now,
107+ memory: {
108+ rss: memoryUsage.rss,
109+ heapTotal: memoryUsage.heapTotal,
110+ heapUsed: memoryUsage.heapUsed,
111+ external: memoryUsage.external,
112+ arrayBuffers: memoryUsage.arrayBuffers,
113+ },
114+ cpu: {
115+ user: currentCpuUsage.user,
116+ system: currentCpuUsage.system,
117+ percent: Math.min(cpuPercent, 100), // Cap at 100%
118+ },
119+ system: {
120+ loadAverage: this.getLoadAverage(),
121+ uptime: this.getProcessUptime(),
122+ freeMemory: this.getFreeMemory(),
123+ totalMemory: this.getTotalMemory(),
124+ },
125+ eventLoop: {
126+ lag: this.measureEventLoopLag(),
127+ },
128+ };
129+
130+ // Try to get file descriptor count (Unix only)
131+ this.getFileDescriptorCount()
132+ .then((count) => {
133+ if (count !== null) {
134+ usage.fileDescriptors = count;
135+ }
136+ })
137+ .catch(() => {
138+ // Ignore errors for file descriptor counting
139+ });
140+
141+ return usage;
142+ }
143+
144+ public getResourceHistory(): ResourceUsage[] {
145+ return [...this.resourceHistory];
146+ }
147+
148+ public getResourceSummary(): {
149+ current: ResourceUsage;
150+ peak: {
151+ memory: number;
152+ cpu: number;
153+ };
154+ average: {
155+ memory: number;
156+ cpu: number;
157+ };
158+ } {
159+ const current = this.getCurrentResourceUsage();
160+
161+ if (this.resourceHistory.length === 0) {
162+ return {
163+ current,
164+ peak: {
165+ memory: current.memory.rss,
166+ cpu: current.cpu.percent || 0,
167+ },
168+ average: {
169+ memory: current.memory.rss,
170+ cpu: current.cpu.percent || 0,
171+ },
172+ };
173+ }
174+
175+ const peakMemory = Math.max(
176+ ...this.resourceHistory.map((r) => r.memory.rss),
177+ );
178+ const peakCpu = Math.max(
179+ ...this.resourceHistory.map((r) => r.cpu.percent || 0),
180+ );
181+
182+ const avgMemory =
183+ this.resourceHistory.reduce((sum, r) => sum + r.memory.rss, 0) /
184+ this.resourceHistory.length;
185+ const avgCpu =
186+ this.resourceHistory.reduce((sum, r) => sum + (r.cpu.percent || 0), 0) /
187+ this.resourceHistory.length;
188+
189+ return {
190+ current,
191+ peak: {
192+ memory: Math.max(peakMemory, current.memory.rss),
193+ cpu: Math.max(peakCpu, current.cpu.percent || 0),
194+ },
195+ average: {
196+ memory: avgMemory,
197+ cpu: avgCpu,
198+ },
199+ };
200+ }
201+
202+ private collectResourceUsage(): void {
203+ try {
204+ const usage = this.getCurrentResourceUsage();
205+
206+ // Update for next CPU calculation
207+ this.lastCpuUsage = process.cpuUsage();
208+ this.lastTimestamp = usage.timestamp;
209+
210+ // Add to history
211+ this.resourceHistory.push(usage);
212+
213+ // Trim history if too large
214+ if (this.resourceHistory.length > this.maxHistorySize) {
215+ this.resourceHistory = this.resourceHistory.slice(-this.maxHistorySize);
216+ }
217+
218+ // Check for potential issues and log warnings
219+ this.checkResourceThresholds(usage);
220+ } catch (error) {
221+ logger.error("Error collecting resource usage", error);
222+ }
223+ }
224+
225+ private checkResourceThresholds(usage: ResourceUsage): void {
226+ const memoryUsageMB = usage.memory.rss / 1024 / 1024;
227+ const cpuPercent = usage.cpu.percent || 0;
228+
229+ // Memory threshold: 500MB
230+ if (memoryUsageMB > 500) {
231+ logger.warn("High memory usage detected", {
232+ memoryMB: Math.round(memoryUsageMB),
233+ threshold: 500,
234+ });
235+ }
236+
237+ // CPU threshold: 80%
238+ if (cpuPercent > 80) {
239+ logger.warn("High CPU usage detected", {
240+ cpuPercent: Math.round(cpuPercent),
241+ threshold: 80,
242+ });
243+ }
244+
245+ // Event loop lag threshold: 100ms
246+ if (usage.eventLoop.lag > 100) {
247+ logger.warn("High event loop lag detected", {
248+ lagMs: Math.round(usage.eventLoop.lag),
249+ threshold: 100,
250+ });
251+ }
252+ }
253+
254+ private async getFileDescriptorCount(): Promise<number | null> {
255+ if (process.platform === "win32") {
256+ return null; // Not supported on Windows
257+ }
258+
259+ try {
260+ const { stdout } = await execAsync(`lsof -p ${process.pid} | wc -l`);
261+ return parseInt(stdout.trim(), 10) - 1; // Subtract 1 for header line
262+ } catch {
263+ return null;
264+ }
265+ }
266+
267+ private getLoadAverage(): number[] {
268+ try {
269+ return process.platform === "win32" ? [0, 0, 0] : os.loadavg();
270+ } catch {
271+ return [0, 0, 0];
272+ }
273+ }
274+
275+ private getProcessUptime(): number {
276+ try {
277+ return typeof process.uptime === "function" ? process.uptime() : 0;
278+ } catch {
279+ return 0;
280+ }
281+ }
282+
283+ private getFreeMemory(): number {
284+ try {
285+ return os.freemem();
286+ } catch {
287+ return 0;
288+ }
289+ }
290+
291+ private getTotalMemory(): number {
292+ try {
293+ return os.totalmem();
294+ } catch {
295+ return 1024 * 1024 * 1024; // 1GB default fallback
296+ }
297+ }
298+
299+ // Synchronous approximation of event loop lag
300+ private measureEventLoopLag(): number {
301+ // Return a simple approximation based on load average on Unix systems
302+ const loadAvg = this.getLoadAverage();
303+ if (loadAvg[0] > 0) {
304+ // Rough approximation: higher load = higher lag
305+ return Math.min(loadAvg[0] * 10, 200); // Cap at 200ms
306+ }
307+
308+ return 0;
309+ }
310+}
311+
312+export { ResourceMonitoringService };
modified extensions/cli/src/services/index.ts +10 −0
@@ -9,6 +9,7 @@
99 import { MCPService } from "./MCPService.js";
1010 import { ModelService } from "./ModelService.js";
1111 import { modeService } from "./ModeService.js";
12+import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
1213 import { serviceContainer } from "./ServiceContainer.js";
1314 import {
1415 ApiClientServiceState,
@@ -26,6 +27,7 @@
2627 const apiClientService = new ApiClientService();
2728 const mcpService = new MCPService();
2829 const fileIndexService = new FileIndexService();
30+const resourceMonitoringService = new ResourceMonitoringService();
2931
3032 /**
3133 * Initialize all services and register them with the service container
@@ -219,6 +221,12 @@
219221 [],
220222 );
221223
224+ serviceContainer.register(
225+ SERVICE_NAMES.RESOURCE_MONITORING,
226+ () => resourceMonitoringService.initialize(),
227+ [],
228+ );
229+
222230 // Eagerly initialize all services to ensure they're ready when needed
223231 // This avoids race conditions and "service not ready" errors
224232 await serviceContainer.initializeAll();
@@ -261,6 +269,7 @@
261269 SERVICE_NAMES.MODEL,
262270 SERVICE_NAMES.MCP,
263271 SERVICE_NAMES.FILE_INDEX,
272+ SERVICE_NAMES.RESOURCE_MONITORING,
264273 ].every((name) => serviceContainer.isReady(name));
265274 }
266275
@@ -282,6 +291,7 @@
282291 mcp: mcpService,
283292 fileIndex: fileIndexService,
284293 mode: modeService,
294+ resourceMonitoring: resourceMonitoringService,
285295 } as const;
286296
287297 // Export the service container for advanced usage
modified extensions/cli/src/services/types.ts +1 −0
@@ -102,6 +102,7 @@
102102 API_CLIENT: "apiClient",
103103 TOOL_PERMISSIONS: "toolPermissions",
104104 FILE_INDEX: "fileIndex",
105+ RESOURCE_MONITORING: "resourceMonitoring",
105106 } as const;
106107
107108 /**
modified extensions/cli/src/ui/SessionSelector.tsx +3 −3
@@ -63,7 +63,7 @@
6363 if (displaySessions[selectedIndex]) {
6464 onSelect(displaySessions[selectedIndex].id);
6565 }
66- } else if (key.escape || (key.ctrl && input === "c")) {
66+ } else if (key.escape || (key.ctrl && input === "d")) {
6767 onExit();
6868 }
6969 });
@@ -73,7 +73,7 @@
7373 <Box flexDirection="column" padding={1}>
7474 <Text color="yellow">No previous sessions found.</Text>
7575 <Text color="gray">Start a new conversation with: cn</Text>
76- <Text color="gray">Press ESC to exit</Text>
76+ <Text color="gray">Press ESC or Ctrl+D to exit</Text>
7777 </Box>
7878 );
7979 }
@@ -84,7 +84,7 @@
8484 Recent Sessions
8585 </Text>
8686 <Text color="gray">
87- Use ↑↓ arrows to navigate, Enter to select, ESC to exit
87+ Use ↑↓ arrows to navigate, Enter to select, ESC or Ctrl+D to exit
8888 </Text>
8989 <Text> </Text>
9090
modified extensions/cli/src/ui/TUIChat.tsx +138 −68
@@ -1,5 +1,11 @@
11 import { Box, Text } from "ink";
2-import React, { useMemo, useState } from "react";
2+import React, {
3+ useCallback,
4+ useEffect,
5+ useMemo,
6+ useRef,
7+ useState,
8+} from "react";
39
410 import { useServices } from "../hooks/useService.js";
511 import {
@@ -9,8 +15,10 @@
915 MCPServiceState,
1016 ModelServiceState,
1117 } from "../services/types.js";
18+import { logger } from "../util/logger.js";
1219
1320 import { BottomStatusBar } from "./components/BottomStatusBar.js";
21+import { ResourceDebugBar } from "./components/ResourceDebugBar.js";
1422 import { ScreenContent } from "./components/ScreenContent.js";
1523 import { StaticChatContent } from "./components/StaticChatContent.js";
1624 import { useNavigation } from "./context/NavigationContext.js";
@@ -39,6 +47,103 @@
3947 additionalPrompts?: string[];
4048 }
4149
50+// Helper function to load and set session
51+async function loadAndSetSession(
52+ sessionId: string,
53+ closeCurrentScreen: () => void,
54+ setChatHistory: (history: any) => void,
55+ setMessages: (messages: any) => void,
56+ setShowIntroMessage: (show: boolean) => void,
57+) {
58+ try {
59+ // Close the session selector
60+ closeCurrentScreen();
61+
62+ // Import session functions
63+ const { loadSessionById } = await import("../session.js");
64+
65+ // Load the session history
66+ const sessionHistory = loadSessionById(sessionId);
67+ if (!sessionHistory) {
68+ logger.error(`Session ${sessionId} could not be loaded.`);
69+ return;
70+ }
71+
72+ // Set the session ID so future operations use this session
73+ process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
74+ "continue-cli-",
75+ "",
76+ );
77+
78+ // Directly set the chat history and messages to the loaded session
79+ setChatHistory(sessionHistory);
80+
81+ // Convert chat history to display messages (exclude system messages)
82+ const displayMessages = sessionHistory
83+ .filter((msg: any) => msg.role !== "system")
84+ .map((msg: any) => ({
85+ role: msg.role,
86+ content: msg.content as string,
87+ }));
88+
89+ setMessages(displayMessages);
90+
91+ // Clear the intro message since we're now showing a resumed session
92+ setShowIntroMessage(false);
93+ } catch (error) {
94+ console.error("Error loading session:", error);
95+ }
96+}
97+
98+// Custom hook to manage services
99+function useTUIChatServices(remoteUrl?: string) {
100+ const isRemoteMode = useMemo(() => !!remoteUrl, [remoteUrl]);
101+
102+ const { services, allReady: allServicesReady } = useServices<{
103+ auth: AuthServiceState;
104+ config: ConfigServiceState;
105+ model: ModelServiceState;
106+ mcp: MCPServiceState;
107+ apiClient: ApiClientServiceState;
108+ }>(["auth", "config", "model", "mcp", "apiClient"]);
109+
110+ return { services, allServicesReady, isRemoteMode };
111+}
112+
113+// Custom hook for chat handlers
114+function useChatHandlers(
115+ setShowIntroMessage: (show: boolean) => void,
116+ setStaticRefreshTrigger: React.Dispatch<React.SetStateAction<number>>,
117+) {
118+ // Temporary refs to avoid circular dependency
119+ const resetChatHistoryRef = useRef<(() => void) | null>(null);
120+
121+ // Handle clearing chat and resetting intro message
122+ const handleClear = useCallback(() => {
123+ setShowIntroMessage(true);
124+ // Trigger static content refresh by incrementing the trigger
125+ setStaticRefreshTrigger((prev) => prev + 1);
126+ }, [setShowIntroMessage, setStaticRefreshTrigger]);
127+
128+ // Service reload handlers - these will trigger reactive updates
129+ const handleReload = useCallback(async () => {
130+ // Services will automatically update the UI when they reload
131+ // We just need to reset chat history, intro message, and clear the screen
132+ if (resetChatHistoryRef.current) {
133+ resetChatHistoryRef.current();
134+ }
135+ setShowIntroMessage(false);
136+ process.stdout.write("\x1b[2J\x1b[H");
137+ }, [setShowIntroMessage]);
138+
139+ return {
140+ handleClear,
141+ handleReload,
142+ resetChatHistoryRef,
143+ };
144+}
145+
146+// eslint-disable-next-line complexity
42147 const TUIChat: React.FC<TUIChatProps> = ({
43148 remoteUrl,
44149 configPath,
@@ -47,22 +152,12 @@
47152 additionalRules,
48153 additionalPrompts,
49154 }) => {
50- // Check if we're in remote mode
51- const isRemoteMode = useMemo(() => {
52- return !!remoteUrl;
53- }, [remoteUrl]);
155+ // Use custom hook for services
156+ const { services, allServicesReady, isRemoteMode } =
157+ useTUIChatServices(remoteUrl);
54158
55159 const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]);
56160
57- // Get all services reactively - only in normal mode
58- const { services, allReady: allServicesReady } = useServices<{
59- auth: AuthServiceState;
60- config: ConfigServiceState;
61- model: ModelServiceState;
62- mcp: MCPServiceState;
63- apiClient: ApiClientServiceState;
64- }>(["auth", "config", "model", "mcp", "apiClient"]);
65-
66161 // Use navigation context
67162 const {
68163 state: navState,
@@ -88,24 +183,14 @@
88183 closeCurrentScreen,
89184 );
90185
91- // Service reload handlers - these will trigger reactive updates
92- const handleReload = async () => {
93- // Services will automatically update the UI when they reload
94- // We just need to reset chat history, intro message, and clear the screen
95- resetChatHistory();
96- setShowIntroMessage(false);
97- process.stdout.write("\x1b[2J\x1b[H");
98- };
99-
100186 // State to trigger static content refresh for /clear command
101187 const [staticRefreshTrigger, setStaticRefreshTrigger] = useState(0);
102188
103- // Handle clearing chat and resetting intro message
104- const handleClear = () => {
105- setShowIntroMessage(true);
106- // Trigger static content refresh by incrementing the trigger
107- setStaticRefreshTrigger((prev) => prev + 1);
108- };
189+ // Use chat handlers hook
190+ const { handleClear, handleReload, resetChatHistoryRef } = useChatHandlers(
191+ setShowIntroMessage,
192+ setStaticRefreshTrigger,
193+ );
109194
110195 const {
111196 messages,
@@ -141,6 +226,11 @@
141226 remoteUrl,
142227 });
143228
229+ // Update ref after useChat returns
230+ useEffect(() => {
231+ resetChatHistoryRef.current = resetChatHistory;
232+ }, [resetChatHistory]);
233+
144234 // Calculate context percentage
145235 const contextData = useContextPercentage({
146236 chatHistory,
@@ -156,52 +246,27 @@
156246 );
157247
158248 // Session selection handler
159- const handleSessionSelect = async (sessionId: string) => {
160- try {
161- // Close the session selector
162- closeCurrentScreen();
163-
164- // Import session functions
165- const { loadSessionById } = await import("../session.js");
166-
167- // Load the session history
168- const sessionHistory = loadSessionById(sessionId);
169- if (!sessionHistory) {
170- console.error(`Session ${sessionId} could not be loaded.`);
171- return;
172- }
173-
174- // Set the session ID so future operations use this session
175- process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
176- "continue-cli-",
177- "",
249+ const handleSessionSelect = useCallback(
250+ async (sessionId: string) => {
251+ await loadAndSetSession(
252+ sessionId,
253+ closeCurrentScreen,
254+ setChatHistory,
255+ setMessages,
256+ setShowIntroMessage,
178257 );
179-
180- // Directly set the chat history and messages to the loaded session
181- setChatHistory(sessionHistory);
182-
183- // Convert chat history to display messages (exclude system messages)
184- const displayMessages = sessionHistory
185- .filter((msg) => msg.role !== "system")
186- .map((msg) => ({
187- role: msg.role,
188- content: msg.content as string,
189- }));
190-
191- setMessages(displayMessages);
192-
193- // Clear the intro message since we're now showing a resumed session
194- setShowIntroMessage(false);
195- } catch (error) {
196- console.error("Error loading session:", error);
197- }
198- };
258+ },
259+ [closeCurrentScreen, setChatHistory, setMessages, setShowIntroMessage],
260+ );
199261
200262 // Determine if input should be disabled
201263 // Allow input even when services are loading, but disable for UI overlays
202264 const isInputDisabled =
203265 navState.currentScreen !== "chat" || !!activePermissionRequest;
204266
267+ // Check if verbose mode is enabled for resource debugging
268+ const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []);
269+
205270 return (
206271 <Box flexDirection="column" height="100%">
207272 {/* Chat history - takes up all available space above input */}
@@ -268,6 +333,11 @@
268333 isRemoteMode={isRemoteMode}
269334 />
270335
336+ {/* Resource debug bar - only in verbose mode */}
337+ {isVerboseMode && !isRemoteMode && (
338+ <ResourceDebugBar visible={navState.currentScreen === "chat"} />
339+ )}
340+
271341 {/* Free trial status and Continue CLI info - always show */}
272342 <BottomStatusBar
273343 currentMode={currentMode}
modified extensions/cli/src/ui/UserInput.tsx +11 −0
@@ -412,6 +412,16 @@
412412 return false;
413413 };
414414
415+ // Clear input function
416+ const clearInput = () => {
417+ textBuffer.clear();
418+ setInputText("");
419+ setCursorPosition(0);
420+ setShowSlashCommands(false);
421+ setShowFileSearch(false);
422+ inputHistory.resetNavigation();
423+ };
424+
415425 useInput((input, key) => {
416426 // Don't handle any input when disabled
417427 if (disabled) {
@@ -427,6 +437,7 @@
427437 showSlashCommands,
428438 showFileSearch,
429439 cycleModes,
440+ clearInput,
430441 })
431442 ) {
432443 return;
added extensions/cli/src/ui/components/ResourceDebugBar.tsx +184 −0
@@ -0,0 +1,184 @@
1+import { Box, Text } from "ink";
2+import React, { useEffect, useState } from "react";
3+
4+import { services } from "../../services/index.js";
5+import { ResourceUsage } from "../../services/ResourceMonitoringService.js";
6+
7+interface ResourceDebugBarProps {
8+ visible: boolean;
9+}
10+
11+function formatBytes(bytes: number): string {
12+ const mb = bytes / 1024 / 1024;
13+ return mb >= 1 ? `${mb.toFixed(1)}MB` : `${(bytes / 1024).toFixed(1)}KB`;
14+}
15+
16+function formatPercent(percent: number): string {
17+ return `${Math.round(percent)}%`;
18+}
19+
20+function formatTime(ms: number): string {
21+ if (ms < 1000) return `${Math.round(ms)}ms`;
22+ return `${(ms / 1000).toFixed(1)}s`;
23+}
24+
25+export function ResourceDebugBar({ visible }: ResourceDebugBarProps) {
26+ const [resourceData, setResourceData] = useState<ResourceUsage | null>(null);
27+ const [isError, setIsError] = useState(false);
28+
29+ useEffect(() => {
30+ if (!visible) return;
31+
32+ const updateResourceData = () => {
33+ try {
34+ const usage = services.resourceMonitoring.getCurrentResourceUsage();
35+ setResourceData(usage);
36+ setIsError(false);
37+ } catch {
38+ setIsError(true);
39+ }
40+ };
41+
42+ // Initial update
43+ updateResourceData();
44+
45+ // Update every 2 seconds
46+ const intervalId = setInterval(updateResourceData, 2000);
47+
48+ return () => {
49+ clearInterval(intervalId);
50+ };
51+ }, [visible]);
52+
53+ if (!visible) {
54+ return null;
55+ }
56+
57+ if (isError) {
58+ return (
59+ <Box paddingX={1}>
60+ <Text color="red">Resource monitoring error</Text>
61+ </Box>
62+ );
63+ }
64+
65+ if (!resourceData) {
66+ return null;
67+ }
68+
69+ const memoryPercent =
70+ (resourceData.memory.rss / resourceData.system.totalMemory) * 100;
71+ const cpuPercent = resourceData.cpu.percent || 0;
72+ const heapPercent =
73+ (resourceData.memory.heapUsed / resourceData.memory.heapTotal) * 100;
74+
75+ // Color coding based on usage levels
76+ const getMemoryColor = () => {
77+ if (memoryPercent > 80) return "red";
78+ if (memoryPercent > 60) return "yellow";
79+ return "green";
80+ };
81+
82+ const getCpuColor = () => {
83+ if (cpuPercent > 80) return "red";
84+ if (cpuPercent > 60) return "yellow";
85+ return "green";
86+ };
87+
88+ const getEventLoopColor = () => {
89+ if (resourceData.eventLoop.lag > 100) return "red";
90+ if (resourceData.eventLoop.lag > 50) return "yellow";
91+ return "green";
92+ };
93+
94+ return (
95+ <Box paddingX={1}>
96+ <Text color="gray">Debug: </Text>
97+
98+ <Text color={getMemoryColor()}>
99+ MEM: {formatBytes(resourceData.memory.rss)}
100+ </Text>
101+ <Text color="gray"> | </Text>
102+
103+ <Text color="gray">HEAP: {formatPercent(heapPercent)}</Text>
104+ <Text color="gray"> | </Text>
105+
106+ <Text color={getCpuColor()}>CPU: {formatPercent(cpuPercent)}</Text>
107+ <Text color="gray"> | </Text>
108+
109+ <Text color={getEventLoopColor()}>
110+ LAG: {formatTime(resourceData.eventLoop.lag)}
111+ </Text>
112+
113+ {resourceData.fileDescriptors && (
114+ <>
115+ <Text color="gray"> | </Text>
116+ <Text color="gray">FD: {resourceData.fileDescriptors}</Text>
117+ </>
118+ )}
119+
120+ <Text color="gray"> | </Text>
121+ <Text color="gray">
122+ UP: {formatTime(resourceData.system.uptime * 1000)}
123+ </Text>
124+ </Box>
125+ );
126+}
127+
128+export function ResourceDebugDetails({ visible }: { visible: boolean }) {
129+ const [summary, setSummary] = useState<any>(null);
130+
131+ useEffect(() => {
132+ if (!visible) return;
133+
134+ const updateData = () => {
135+ try {
136+ const summaryData = services.resourceMonitoring.getResourceSummary();
137+ setSummary(summaryData);
138+ } catch {
139+ // Handle error silently
140+ }
141+ };
142+
143+ updateData();
144+ const intervalId = setInterval(updateData, 3000);
145+
146+ return () => clearInterval(intervalId);
147+ }, [visible]);
148+
149+ if (!visible || !summary) {
150+ return null;
151+ }
152+
153+ return (
154+ <Box
155+ flexDirection="column"
156+ borderStyle="single"
157+ borderColor="gray"
158+ paddingX={1}
159+ marginTop={1}
160+ >
161+ <Text color="cyan" bold>
162+ Resource Usage Summary
163+ </Text>
164+
165+ <Box marginTop={1}>
166+ <Text color="gray">Current: </Text>
167+ <Text>{formatBytes(summary.current.memory.rss)} mem, </Text>
168+ <Text>{formatPercent(summary.current.cpu.percent || 0)} cpu</Text>
169+ </Box>
170+
171+ <Box>
172+ <Text color="gray">Peak: </Text>
173+ <Text>{formatBytes(summary.peak.memory)} mem, </Text>
174+ <Text>{formatPercent(summary.peak.cpu)} cpu</Text>
175+ </Box>
176+
177+ <Box>
178+ <Text color="gray">Average: </Text>
179+ <Text>{formatBytes(summary.average.memory)} mem, </Text>
180+ <Text>{formatPercent(summary.average.cpu)} cpu</Text>
181+ </Box>
182+ </Box>
183+ );
184+}
modified extensions/cli/src/ui/hooks/useUserInput.ts +18 −4
@@ -9,14 +9,28 @@
99 showSlashCommands: boolean;
1010 showFileSearch: boolean;
1111 cycleModes: () => Promise<PermissionMode>;
12+ clearInput?: () => void;
1213 }
1314
1415 export function handleControlKeys(options: ControlKeysOptions): boolean {
15- const { input, key, exit, showSlashCommands, showFileSearch, cycleModes } =
16- options;
16+ const {
17+ input,
18+ key,
19+ exit,
20+ showSlashCommands,
21+ showFileSearch,
22+ cycleModes,
23+ clearInput,
24+ } = options;
1725
18- // Handle Ctrl+C and Ctrl+D
19- if (key.ctrl && (input === "c" || input === "d")) {
26+ // Handle Ctrl+C to clear input
27+ if (key.ctrl && input === "c" && clearInput) {
28+ clearInput();
29+ return true;
30+ }
31+
32+ // Handle Ctrl+D to exit
33+ if (key.ctrl && input === "d") {
2034 exit();
2135 return true;
2236 }
modified package-lock.json +1 −0
@@ -1,4 +1,5 @@
11 {
2+ "name": "wt-small-improvements",
23 "name": "wt-plan-mode-sys-prompt",
34 "lockfileVersion": 3,
45 "requires": true,
modified packages/openai-adapters/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.