feat: resource monitoring
This commit is contained in:
parent
5f782366af
commit
6bad79645e
10 changed files with 770 additions and 76 deletions
109
extensions/cli/src/services/ResourceMonitoringService.test.ts
Normal file
109
extensions/cli/src/services/ResourceMonitoringService.test.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
|
||||
|
||||
// Mock the logger and BaseService
|
||||
vi.mock("../util/logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./BaseService.js", () => ({
|
||||
BaseService: class MockBaseService {
|
||||
logger = {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
describe("ResourceMonitoringService", () => {
|
||||
let service: ResourceMonitoringService;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Remove process event listeners to prevent interference
|
||||
process.removeAllListeners('exit');
|
||||
process.removeAllListeners('SIGINT');
|
||||
process.removeAllListeners('SIGTERM');
|
||||
|
||||
service = new ResourceMonitoringService();
|
||||
await service.initialize();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (service) {
|
||||
service.stopMonitoring(); // Ensure monitoring is stopped
|
||||
await service.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("should initialize without starting monitoring by default", () => {
|
||||
expect(service).toBeDefined();
|
||||
// Should not be monitoring unless --verbose is passed
|
||||
const usage = service.getCurrentResourceUsage();
|
||||
expect(usage.timestamp).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("should collect current resource usage", () => {
|
||||
const usage = service.getCurrentResourceUsage();
|
||||
|
||||
expect(usage.timestamp).toBeGreaterThan(0);
|
||||
expect(usage.memory.rss).toBeGreaterThan(0);
|
||||
expect(usage.memory.heapTotal).toBeGreaterThan(0);
|
||||
expect(usage.memory.heapUsed).toBeGreaterThan(0);
|
||||
expect(usage.cpu.user).toBeGreaterThanOrEqual(0);
|
||||
expect(usage.cpu.system).toBeGreaterThanOrEqual(0);
|
||||
expect(usage.system.uptime).toBeGreaterThan(0);
|
||||
expect(usage.system.totalMemory).toBeGreaterThan(0);
|
||||
expect(usage.eventLoop.lag).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
|
||||
it("should provide resource summary", () => {
|
||||
const summary = service.getResourceSummary();
|
||||
|
||||
expect(summary.current).toBeDefined();
|
||||
expect(summary.peak).toBeDefined();
|
||||
expect(summary.average).toBeDefined();
|
||||
|
||||
expect(summary.peak.memory).toBeGreaterThan(0);
|
||||
expect(summary.peak.cpu).toBeGreaterThanOrEqual(0);
|
||||
|
||||
expect(summary.average.memory).toBeGreaterThan(0);
|
||||
expect(summary.average.cpu).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it("should start and stop monitoring", async () => {
|
||||
service.startMonitoring(100); // 100ms interval for test
|
||||
|
||||
// Wait for some data collection
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
|
||||
const history = service.getResourceHistory();
|
||||
expect(history.length).toBeGreaterThan(0);
|
||||
|
||||
service.stopMonitoring();
|
||||
});
|
||||
|
||||
it("should handle verbose mode initialization", async () => {
|
||||
// Mock argv to include --verbose
|
||||
const originalArgv = process.argv;
|
||||
process.argv = [...originalArgv, '--verbose'];
|
||||
|
||||
const verboseService = new ResourceMonitoringService();
|
||||
await verboseService.initialize();
|
||||
|
||||
// Should start monitoring automatically
|
||||
// Note: Testing this properly would require checking internal state
|
||||
// which isn't directly exposed
|
||||
|
||||
await verboseService.cleanup();
|
||||
process.argv = originalArgv;
|
||||
});
|
||||
});
|
||||
316
extensions/cli/src/services/ResourceMonitoringService.ts
Normal file
316
extensions/cli/src/services/ResourceMonitoringService.ts
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
import { exec } from "child_process";
|
||||
import { promisify } from "util";
|
||||
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
export interface ResourceUsage {
|
||||
timestamp: number;
|
||||
memory: {
|
||||
rss: number; // Resident Set Size
|
||||
heapTotal: number;
|
||||
heapUsed: number;
|
||||
external: number;
|
||||
arrayBuffers: number;
|
||||
};
|
||||
cpu: {
|
||||
user: number;
|
||||
system: number;
|
||||
percent?: number; // CPU percentage (calculated)
|
||||
};
|
||||
system: {
|
||||
loadAverage: number[];
|
||||
uptime: number;
|
||||
freeMemory: number;
|
||||
totalMemory: number;
|
||||
};
|
||||
eventLoop: {
|
||||
lag: number;
|
||||
};
|
||||
fileDescriptors?: number;
|
||||
}
|
||||
|
||||
export interface ResourceMonitoringState {
|
||||
isMonitoring: boolean;
|
||||
resourceHistory: ResourceUsage[];
|
||||
}
|
||||
|
||||
class ResourceMonitoringService {
|
||||
private isMonitoring = false;
|
||||
private monitoringInterval?: NodeJS.Timeout;
|
||||
private intervalMs = 1000; // Default 1 second
|
||||
private resourceHistory: ResourceUsage[] = [];
|
||||
private maxHistorySize = 300; // Keep 5 minutes at 1s intervals
|
||||
private lastCpuUsage = process.cpuUsage();
|
||||
private lastTimestamp = Date.now();
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
// Start monitoring if verbose mode is enabled
|
||||
if (process.argv.includes("--verbose")) {
|
||||
this.startMonitoring();
|
||||
}
|
||||
|
||||
// Cleanup on exit
|
||||
process.on("exit", () => this.cleanup());
|
||||
process.on("SIGINT", () => this.cleanup());
|
||||
process.on("SIGTERM", () => this.cleanup());
|
||||
}
|
||||
|
||||
async cleanup(): Promise<void> {
|
||||
this.stopMonitoring();
|
||||
}
|
||||
|
||||
public startMonitoring(intervalMs = 1000): void {
|
||||
if (this.isMonitoring) return;
|
||||
|
||||
this.intervalMs = intervalMs;
|
||||
this.isMonitoring = true;
|
||||
this.lastCpuUsage = process.cpuUsage();
|
||||
this.lastTimestamp = Date.now();
|
||||
|
||||
this.monitoringInterval = setInterval(() => {
|
||||
this.collectResourceUsage();
|
||||
}, this.intervalMs);
|
||||
|
||||
logger.debug("Resource monitoring started", { intervalMs });
|
||||
}
|
||||
|
||||
public stopMonitoring(): void {
|
||||
if (!this.isMonitoring) return;
|
||||
|
||||
this.isMonitoring = false;
|
||||
if (this.monitoringInterval) {
|
||||
clearInterval(this.monitoringInterval);
|
||||
this.monitoringInterval = undefined;
|
||||
}
|
||||
|
||||
logger.debug("Resource monitoring stopped");
|
||||
}
|
||||
|
||||
public getCurrentResourceUsage(): ResourceUsage {
|
||||
const now = Date.now();
|
||||
const currentCpuUsage = process.cpuUsage();
|
||||
const timeDiff = now - this.lastTimestamp;
|
||||
|
||||
// Calculate CPU percentage
|
||||
const userDiff = currentCpuUsage.user - this.lastCpuUsage.user;
|
||||
const systemDiff = currentCpuUsage.system - this.lastCpuUsage.system;
|
||||
const totalDiff = userDiff + systemDiff;
|
||||
const cpuPercent = timeDiff > 0 ? (totalDiff / (timeDiff * 1000)) * 100 : 0;
|
||||
|
||||
const memoryUsage = process.memoryUsage();
|
||||
|
||||
const usage: ResourceUsage = {
|
||||
timestamp: now,
|
||||
memory: {
|
||||
rss: memoryUsage.rss,
|
||||
heapTotal: memoryUsage.heapTotal,
|
||||
heapUsed: memoryUsage.heapUsed,
|
||||
external: memoryUsage.external,
|
||||
arrayBuffers: memoryUsage.arrayBuffers,
|
||||
},
|
||||
cpu: {
|
||||
user: currentCpuUsage.user,
|
||||
system: currentCpuUsage.system,
|
||||
percent: Math.min(cpuPercent, 100), // Cap at 100%
|
||||
},
|
||||
system: {
|
||||
loadAverage: this.getLoadAverage(),
|
||||
uptime: this.getProcessUptime(),
|
||||
freeMemory: this.getFreeMemory(),
|
||||
totalMemory: this.getTotalMemory(),
|
||||
},
|
||||
eventLoop: {
|
||||
lag: this.measureEventLoopLag(),
|
||||
},
|
||||
};
|
||||
|
||||
// Try to get file descriptor count (Unix only)
|
||||
this.getFileDescriptorCount()
|
||||
.then((count) => {
|
||||
if (count !== null) {
|
||||
usage.fileDescriptors = count;
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// Ignore errors for file descriptor counting
|
||||
});
|
||||
|
||||
return usage;
|
||||
}
|
||||
|
||||
public getResourceHistory(): ResourceUsage[] {
|
||||
return [...this.resourceHistory];
|
||||
}
|
||||
|
||||
public getResourceSummary(): {
|
||||
current: ResourceUsage;
|
||||
peak: {
|
||||
memory: number;
|
||||
cpu: number;
|
||||
};
|
||||
average: {
|
||||
memory: number;
|
||||
cpu: number;
|
||||
};
|
||||
} {
|
||||
const current = this.getCurrentResourceUsage();
|
||||
|
||||
if (this.resourceHistory.length === 0) {
|
||||
return {
|
||||
current,
|
||||
peak: {
|
||||
memory: current.memory.rss,
|
||||
cpu: current.cpu.percent || 0,
|
||||
},
|
||||
average: {
|
||||
memory: current.memory.rss,
|
||||
cpu: current.cpu.percent || 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const peakMemory = Math.max(...this.resourceHistory.map((r) => r.memory.rss));
|
||||
const peakCpu = Math.max(
|
||||
...this.resourceHistory.map((r) => r.cpu.percent || 0),
|
||||
);
|
||||
|
||||
const avgMemory =
|
||||
this.resourceHistory.reduce((sum, r) => sum + r.memory.rss, 0) /
|
||||
this.resourceHistory.length;
|
||||
const avgCpu =
|
||||
this.resourceHistory.reduce((sum, r) => sum + (r.cpu.percent || 0), 0) /
|
||||
this.resourceHistory.length;
|
||||
|
||||
return {
|
||||
current,
|
||||
peak: {
|
||||
memory: Math.max(peakMemory, current.memory.rss),
|
||||
cpu: Math.max(peakCpu, current.cpu.percent || 0),
|
||||
},
|
||||
average: {
|
||||
memory: avgMemory,
|
||||
cpu: avgCpu,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private collectResourceUsage(): void {
|
||||
try {
|
||||
const usage = this.getCurrentResourceUsage();
|
||||
|
||||
// Update for next CPU calculation
|
||||
this.lastCpuUsage = process.cpuUsage();
|
||||
this.lastTimestamp = usage.timestamp;
|
||||
|
||||
// Add to history
|
||||
this.resourceHistory.push(usage);
|
||||
|
||||
// Trim history if too large
|
||||
if (this.resourceHistory.length > this.maxHistorySize) {
|
||||
this.resourceHistory = this.resourceHistory.slice(-this.maxHistorySize);
|
||||
}
|
||||
|
||||
// Check for potential issues and log warnings
|
||||
this.checkResourceThresholds(usage);
|
||||
} catch (error) {
|
||||
logger.error("Error collecting resource usage", error);
|
||||
}
|
||||
}
|
||||
|
||||
private checkResourceThresholds(usage: ResourceUsage): void {
|
||||
const memoryUsageMB = usage.memory.rss / 1024 / 1024;
|
||||
const cpuPercent = usage.cpu.percent || 0;
|
||||
|
||||
// Memory threshold: 500MB
|
||||
if (memoryUsageMB > 500) {
|
||||
logger.warn("High memory usage detected", {
|
||||
memoryMB: Math.round(memoryUsageMB),
|
||||
threshold: 500,
|
||||
});
|
||||
}
|
||||
|
||||
// CPU threshold: 80%
|
||||
if (cpuPercent > 80) {
|
||||
logger.warn("High CPU usage detected", {
|
||||
cpuPercent: Math.round(cpuPercent),
|
||||
threshold: 80,
|
||||
});
|
||||
}
|
||||
|
||||
// Event loop lag threshold: 100ms
|
||||
if (usage.eventLoop.lag > 100) {
|
||||
logger.warn("High event loop lag detected", {
|
||||
lagMs: Math.round(usage.eventLoop.lag),
|
||||
threshold: 100,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async getFileDescriptorCount(): Promise<number | null> {
|
||||
if (process.platform === "win32") {
|
||||
return null; // Not supported on Windows
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execAsync(`lsof -p ${process.pid} | wc -l`);
|
||||
return parseInt(stdout.trim(), 10) - 1; // Subtract 1 for header line
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private getLoadAverage(): number[] {
|
||||
try {
|
||||
return process.platform !== "win32" &&
|
||||
typeof (process as any).loadavg === "function"
|
||||
? (process as any).loadavg()
|
||||
: [0, 0, 0];
|
||||
} catch {
|
||||
return [0, 0, 0];
|
||||
}
|
||||
}
|
||||
|
||||
private getProcessUptime(): number {
|
||||
try {
|
||||
return typeof process.uptime === "function" ? process.uptime() : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private getFreeMemory(): number {
|
||||
try {
|
||||
return typeof (process as any).freemem === "function"
|
||||
? (process as any).freemem()
|
||||
: 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private getTotalMemory(): number {
|
||||
try {
|
||||
return typeof (process as any).totalmem === "function"
|
||||
? (process as any).totalmem()
|
||||
: 1024 * 1024 * 1024; // 1GB default
|
||||
} catch {
|
||||
return 1024 * 1024 * 1024; // 1GB default
|
||||
}
|
||||
}
|
||||
|
||||
// Synchronous approximation of event loop lag
|
||||
private measureEventLoopLag(): number {
|
||||
// Return a simple approximation based on load average on Unix systems
|
||||
const loadAvg = this.getLoadAverage();
|
||||
if (loadAvg[0] > 0) {
|
||||
// Rough approximation: higher load = higher lag
|
||||
return Math.min(loadAvg[0] * 10, 200); // Cap at 200ms
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
export { ResourceMonitoringService };
|
||||
|
|
@ -9,6 +9,7 @@ import { FileIndexService } from "./FileIndexService.js";
|
|||
import { MCPService } from "./MCPService.js";
|
||||
import { ModelService } from "./ModelService.js";
|
||||
import { modeService } from "./ModeService.js";
|
||||
import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import {
|
||||
ApiClientServiceState,
|
||||
|
|
@ -26,6 +27,7 @@ const modelService = new ModelService();
|
|||
const apiClientService = new ApiClientService();
|
||||
const mcpService = new MCPService();
|
||||
const fileIndexService = new FileIndexService();
|
||||
const resourceMonitoringService = new ResourceMonitoringService();
|
||||
|
||||
/**
|
||||
* Initialize all services and register them with the service container
|
||||
|
|
@ -219,6 +221,12 @@ export async function initializeServices(
|
|||
[],
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.RESOURCE_MONITORING,
|
||||
() => resourceMonitoringService.initialize(),
|
||||
[],
|
||||
);
|
||||
|
||||
// Eagerly initialize all services to ensure they're ready when needed
|
||||
// This avoids race conditions and "service not ready" errors
|
||||
await serviceContainer.initializeAll();
|
||||
|
|
@ -261,6 +269,7 @@ export function areServicesReady(): boolean {
|
|||
SERVICE_NAMES.MODEL,
|
||||
SERVICE_NAMES.MCP,
|
||||
SERVICE_NAMES.FILE_INDEX,
|
||||
SERVICE_NAMES.RESOURCE_MONITORING,
|
||||
].every((name) => serviceContainer.isReady(name));
|
||||
}
|
||||
|
||||
|
|
@ -282,11 +291,13 @@ export const services = {
|
|||
mcp: mcpService,
|
||||
fileIndex: fileIndexService,
|
||||
mode: modeService,
|
||||
resourceMonitoring: resourceMonitoringService,
|
||||
} as const;
|
||||
|
||||
// Export the service container for advanced usage
|
||||
export { serviceContainer };
|
||||
|
||||
// Export service names and types
|
||||
export type * from "./types.js";
|
||||
export { SERVICE_NAMES } from "./types.js";
|
||||
export type * from "./types.js";
|
||||
export { SERVICE_NAMES } from "./types.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -102,6 +102,7 @@ export const SERVICE_NAMES = {
|
|||
API_CLIENT: "apiClient",
|
||||
TOOL_PERMISSIONS: "toolPermissions",
|
||||
FILE_INDEX: "fileIndex",
|
||||
RESOURCE_MONITORING: "resourceMonitoring",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -63,7 +63,7 @@ export function SessionSelector({
|
|||
if (displaySessions[selectedIndex]) {
|
||||
onSelect(displaySessions[selectedIndex].id);
|
||||
}
|
||||
} else if (key.escape || (key.ctrl && input === "c")) {
|
||||
} else if (key.escape || (key.ctrl && input === "d")) {
|
||||
onExit();
|
||||
}
|
||||
});
|
||||
|
|
@ -73,7 +73,7 @@ export function SessionSelector({
|
|||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="yellow">No previous sessions found.</Text>
|
||||
<Text color="gray">Start a new conversation with: cn</Text>
|
||||
<Text color="gray">Press ESC to exit</Text>
|
||||
<Text color="gray">Press ESC or Ctrl+D to exit</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -84,7 +84,7 @@ export function SessionSelector({
|
|||
Recent Sessions
|
||||
</Text>
|
||||
<Text color="gray">
|
||||
Use ↑↓ arrows to navigate, Enter to select, ESC to exit
|
||||
Use ↑↓ arrows to navigate, Enter to select, ESC or Ctrl+D to exit
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Box, Text } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { useServices } from "../hooks/useService.js";
|
||||
import {
|
||||
|
|
@ -11,6 +11,7 @@ import {
|
|||
} from "../services/types.js";
|
||||
|
||||
import { BottomStatusBar } from "./components/BottomStatusBar.js";
|
||||
import { ResourceDebugBar } from "./components/ResourceDebugBar.js";
|
||||
import { ScreenContent } from "./components/ScreenContent.js";
|
||||
import { StaticChatContent } from "./components/StaticChatContent.js";
|
||||
import { useNavigation } from "./context/NavigationContext.js";
|
||||
|
|
@ -39,6 +40,103 @@ interface TUIChatProps {
|
|||
additionalPrompts?: string[];
|
||||
}
|
||||
|
||||
// Helper function to load and set session
|
||||
async function loadAndSetSession(
|
||||
sessionId: string,
|
||||
closeCurrentScreen: () => void,
|
||||
setChatHistory: (history: any) => void,
|
||||
setMessages: (messages: any) => void,
|
||||
setShowIntroMessage: (show: boolean) => void,
|
||||
) {
|
||||
try {
|
||||
// Close the session selector
|
||||
closeCurrentScreen();
|
||||
|
||||
// Import session functions
|
||||
const { loadSessionById } = await import("../session.js");
|
||||
|
||||
// Load the session history
|
||||
const sessionHistory = loadSessionById(sessionId);
|
||||
if (!sessionHistory) {
|
||||
console.error(`Session ${sessionId} could not be loaded.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set the session ID so future operations use this session
|
||||
process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
|
||||
"continue-cli-",
|
||||
"",
|
||||
);
|
||||
|
||||
// Directly set the chat history and messages to the loaded session
|
||||
setChatHistory(sessionHistory);
|
||||
|
||||
// Convert chat history to display messages (exclude system messages)
|
||||
const displayMessages = sessionHistory
|
||||
.filter((msg: any) => msg.role !== "system")
|
||||
.map((msg: any) => ({
|
||||
role: msg.role,
|
||||
content: msg.content as string,
|
||||
}));
|
||||
|
||||
setMessages(displayMessages);
|
||||
|
||||
// Clear the intro message since we're now showing a resumed session
|
||||
setShowIntroMessage(false);
|
||||
} catch (error) {
|
||||
console.error("Error loading session:", error);
|
||||
}
|
||||
}
|
||||
|
||||
// Custom hook to manage services
|
||||
function useTUIChatServices(remoteUrl?: string) {
|
||||
const isRemoteMode = useMemo(() => !!remoteUrl, [remoteUrl]);
|
||||
|
||||
const { services, allReady: allServicesReady } = useServices<{
|
||||
auth: AuthServiceState;
|
||||
config: ConfigServiceState;
|
||||
model: ModelServiceState;
|
||||
mcp: MCPServiceState;
|
||||
apiClient: ApiClientServiceState;
|
||||
}>(["auth", "config", "model", "mcp", "apiClient"]);
|
||||
|
||||
return { services, allServicesReady, isRemoteMode };
|
||||
}
|
||||
|
||||
// Custom hook for chat handlers
|
||||
function useChatHandlers(
|
||||
setShowIntroMessage: (show: boolean) => void,
|
||||
setStaticRefreshTrigger: React.Dispatch<React.SetStateAction<number>>,
|
||||
) {
|
||||
// Temporary refs to avoid circular dependency
|
||||
const resetChatHistoryRef = useRef<(() => void) | null>(null);
|
||||
|
||||
// Handle clearing chat and resetting intro message
|
||||
const handleClear = useCallback(() => {
|
||||
setShowIntroMessage(true);
|
||||
// Trigger static content refresh by incrementing the trigger
|
||||
setStaticRefreshTrigger((prev) => prev + 1);
|
||||
}, [setShowIntroMessage, setStaticRefreshTrigger]);
|
||||
|
||||
// Service reload handlers - these will trigger reactive updates
|
||||
const handleReload = useCallback(async () => {
|
||||
// Services will automatically update the UI when they reload
|
||||
// We just need to reset chat history, intro message, and clear the screen
|
||||
if (resetChatHistoryRef.current) {
|
||||
resetChatHistoryRef.current();
|
||||
}
|
||||
setShowIntroMessage(false);
|
||||
process.stdout.write("\x1b[2J\x1b[H");
|
||||
}, [setShowIntroMessage]);
|
||||
|
||||
return {
|
||||
handleClear,
|
||||
handleReload,
|
||||
resetChatHistoryRef,
|
||||
};
|
||||
}
|
||||
|
||||
// eslint-disable-next-line complexity
|
||||
const TUIChat: React.FC<TUIChatProps> = ({
|
||||
remoteUrl,
|
||||
configPath,
|
||||
|
|
@ -47,22 +145,11 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
additionalRules,
|
||||
additionalPrompts,
|
||||
}) => {
|
||||
// Check if we're in remote mode
|
||||
const isRemoteMode = useMemo(() => {
|
||||
return !!remoteUrl;
|
||||
}, [remoteUrl]);
|
||||
// Use custom hook for services
|
||||
const { services, allServicesReady, isRemoteMode } = useTUIChatServices(remoteUrl);
|
||||
|
||||
const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]);
|
||||
|
||||
// Get all services reactively - only in normal mode
|
||||
const { services, allReady: allServicesReady } = useServices<{
|
||||
auth: AuthServiceState;
|
||||
config: ConfigServiceState;
|
||||
model: ModelServiceState;
|
||||
mcp: MCPServiceState;
|
||||
apiClient: ApiClientServiceState;
|
||||
}>(["auth", "config", "model", "mcp", "apiClient"]);
|
||||
|
||||
// Use navigation context
|
||||
const {
|
||||
state: navState,
|
||||
|
|
@ -88,24 +175,14 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
closeCurrentScreen,
|
||||
);
|
||||
|
||||
// Service reload handlers - these will trigger reactive updates
|
||||
const handleReload = async () => {
|
||||
// Services will automatically update the UI when they reload
|
||||
// We just need to reset chat history, intro message, and clear the screen
|
||||
resetChatHistory();
|
||||
setShowIntroMessage(false);
|
||||
process.stdout.write("\x1b[2J\x1b[H");
|
||||
};
|
||||
|
||||
// State to trigger static content refresh for /clear command
|
||||
const [staticRefreshTrigger, setStaticRefreshTrigger] = useState(0);
|
||||
|
||||
// Handle clearing chat and resetting intro message
|
||||
const handleClear = () => {
|
||||
setShowIntroMessage(true);
|
||||
// Trigger static content refresh by incrementing the trigger
|
||||
setStaticRefreshTrigger((prev) => prev + 1);
|
||||
};
|
||||
// Use chat handlers hook
|
||||
const { handleClear, handleReload, resetChatHistoryRef } = useChatHandlers(
|
||||
setShowIntroMessage,
|
||||
setStaticRefreshTrigger,
|
||||
);
|
||||
|
||||
const {
|
||||
messages,
|
||||
|
|
@ -141,6 +218,11 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
remoteUrl,
|
||||
});
|
||||
|
||||
// Update ref after useChat returns
|
||||
useEffect(() => {
|
||||
resetChatHistoryRef.current = resetChatHistory;
|
||||
}, [resetChatHistory]);
|
||||
|
||||
// Calculate context percentage
|
||||
const contextData = useContextPercentage({
|
||||
chatHistory,
|
||||
|
|
@ -156,52 +238,27 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
);
|
||||
|
||||
// Session selection handler
|
||||
const handleSessionSelect = async (sessionId: string) => {
|
||||
try {
|
||||
// Close the session selector
|
||||
closeCurrentScreen();
|
||||
|
||||
// Import session functions
|
||||
const { loadSessionById } = await import("../session.js");
|
||||
|
||||
// Load the session history
|
||||
const sessionHistory = loadSessionById(sessionId);
|
||||
if (!sessionHistory) {
|
||||
console.error(`Session ${sessionId} could not be loaded.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set the session ID so future operations use this session
|
||||
process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
|
||||
"continue-cli-",
|
||||
"",
|
||||
const handleSessionSelect = useCallback(
|
||||
async (sessionId: string) => {
|
||||
await loadAndSetSession(
|
||||
sessionId,
|
||||
closeCurrentScreen,
|
||||
setChatHistory,
|
||||
setMessages,
|
||||
setShowIntroMessage,
|
||||
);
|
||||
|
||||
// Directly set the chat history and messages to the loaded session
|
||||
setChatHistory(sessionHistory);
|
||||
|
||||
// Convert chat history to display messages (exclude system messages)
|
||||
const displayMessages = sessionHistory
|
||||
.filter((msg) => msg.role !== "system")
|
||||
.map((msg) => ({
|
||||
role: msg.role,
|
||||
content: msg.content as string,
|
||||
}));
|
||||
|
||||
setMessages(displayMessages);
|
||||
|
||||
// Clear the intro message since we're now showing a resumed session
|
||||
setShowIntroMessage(false);
|
||||
} catch (error) {
|
||||
console.error("Error loading session:", error);
|
||||
}
|
||||
};
|
||||
},
|
||||
[closeCurrentScreen, setChatHistory, setMessages, setShowIntroMessage],
|
||||
);
|
||||
|
||||
// Determine if input should be disabled
|
||||
// Allow input even when services are loading, but disable for UI overlays
|
||||
const isInputDisabled =
|
||||
navState.currentScreen !== "chat" || !!activePermissionRequest;
|
||||
|
||||
// Check if verbose mode is enabled for resource debugging
|
||||
const isVerboseMode = useMemo(() => process.argv.includes('--verbose'), []);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" height="100%">
|
||||
{/* Chat history - takes up all available space above input */}
|
||||
|
|
@ -268,6 +325,11 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
isRemoteMode={isRemoteMode}
|
||||
/>
|
||||
|
||||
{/* Resource debug bar - only in verbose mode */}
|
||||
{isVerboseMode && !isRemoteMode && (
|
||||
<ResourceDebugBar visible={navState.currentScreen === "chat"} />
|
||||
)}
|
||||
|
||||
{/* Free trial status and Continue CLI info - always show */}
|
||||
<BottomStatusBar
|
||||
currentMode={currentMode}
|
||||
|
|
|
|||
|
|
@ -412,6 +412,16 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return false;
|
||||
};
|
||||
|
||||
// Clear input function
|
||||
const clearInput = () => {
|
||||
textBuffer.clear();
|
||||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
setShowSlashCommands(false);
|
||||
setShowFileSearch(false);
|
||||
inputHistory.resetNavigation();
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
// Don't handle any input when disabled
|
||||
if (disabled) {
|
||||
|
|
@ -427,6 +437,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
showSlashCommands,
|
||||
showFileSearch,
|
||||
cycleModes,
|
||||
clearInput,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
|
|
|
|||
176
extensions/cli/src/ui/components/ResourceDebugBar.tsx
Normal file
176
extensions/cli/src/ui/components/ResourceDebugBar.tsx
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
import { Box, Text } from "ink";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import { services } from "../../services/index.js";
|
||||
import { ResourceUsage } from "../../services/ResourceMonitoringService.js";
|
||||
|
||||
interface ResourceDebugBarProps {
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
const mb = bytes / 1024 / 1024;
|
||||
return mb >= 1 ? `${mb.toFixed(1)}MB` : `${(bytes / 1024).toFixed(1)}KB`;
|
||||
}
|
||||
|
||||
function formatPercent(percent: number): string {
|
||||
return `${Math.round(percent)}%`;
|
||||
}
|
||||
|
||||
function formatTime(ms: number): string {
|
||||
if (ms < 1000) return `${Math.round(ms)}ms`;
|
||||
return `${(ms / 1000).toFixed(1)}s`;
|
||||
}
|
||||
|
||||
export function ResourceDebugBar({ visible }: ResourceDebugBarProps) {
|
||||
const [resourceData, setResourceData] = useState<ResourceUsage | null>(null);
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
|
||||
const updateResourceData = () => {
|
||||
try {
|
||||
const usage = services.resourceMonitoring.getCurrentResourceUsage();
|
||||
setResourceData(usage);
|
||||
setIsError(false);
|
||||
} catch {
|
||||
setIsError(true);
|
||||
}
|
||||
};
|
||||
|
||||
// Initial update
|
||||
updateResourceData();
|
||||
|
||||
// Update every 2 seconds
|
||||
const intervalId = setInterval(updateResourceData, 2000);
|
||||
|
||||
return () => {
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [visible]);
|
||||
|
||||
if (!visible || !resourceData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Text color="red">Resource monitoring error</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const memoryPercent = (resourceData.memory.rss / resourceData.system.totalMemory) * 100;
|
||||
const cpuPercent = resourceData.cpu.percent || 0;
|
||||
const heapPercent = (resourceData.memory.heapUsed / resourceData.memory.heapTotal) * 100;
|
||||
|
||||
// Color coding based on usage levels
|
||||
const getMemoryColor = () => {
|
||||
if (memoryPercent > 80) return "red";
|
||||
if (memoryPercent > 60) return "yellow";
|
||||
return "green";
|
||||
};
|
||||
|
||||
const getCpuColor = () => {
|
||||
if (cpuPercent > 80) return "red";
|
||||
if (cpuPercent > 60) return "yellow";
|
||||
return "green";
|
||||
};
|
||||
|
||||
const getEventLoopColor = () => {
|
||||
if (resourceData.eventLoop.lag > 100) return "red";
|
||||
if (resourceData.eventLoop.lag > 50) return "yellow";
|
||||
return "green";
|
||||
};
|
||||
|
||||
return (
|
||||
<Box paddingX={1}>
|
||||
<Text color="gray">Debug: </Text>
|
||||
|
||||
<Text color={getMemoryColor()}>
|
||||
MEM: {formatBytes(resourceData.memory.rss)}
|
||||
</Text>
|
||||
<Text color="gray"> | </Text>
|
||||
|
||||
<Text color="gray">
|
||||
HEAP: {formatPercent(heapPercent)}
|
||||
</Text>
|
||||
<Text color="gray"> | </Text>
|
||||
|
||||
<Text color={getCpuColor()}>
|
||||
CPU: {formatPercent(cpuPercent)}
|
||||
</Text>
|
||||
<Text color="gray"> | </Text>
|
||||
|
||||
<Text color={getEventLoopColor()}>
|
||||
LAG: {formatTime(resourceData.eventLoop.lag)}
|
||||
</Text>
|
||||
|
||||
{resourceData.fileDescriptors && (
|
||||
<>
|
||||
<Text color="gray"> | </Text>
|
||||
<Text color="gray">
|
||||
FD: {resourceData.fileDescriptors}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Text color="gray"> | </Text>
|
||||
<Text color="gray">
|
||||
UP: {formatTime(resourceData.system.uptime * 1000)}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export function ResourceDebugDetails({ visible }: { visible: boolean }) {
|
||||
const [summary, setSummary] = useState<any>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
|
||||
const updateData = () => {
|
||||
try {
|
||||
const summaryData = services.resourceMonitoring.getResourceSummary();
|
||||
setSummary(summaryData);
|
||||
} catch {
|
||||
// Handle error silently
|
||||
}
|
||||
};
|
||||
|
||||
updateData();
|
||||
const intervalId = setInterval(updateData, 3000);
|
||||
|
||||
return () => clearInterval(intervalId);
|
||||
}, [visible]);
|
||||
|
||||
if (!visible || !summary) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" borderStyle="single" borderColor="gray" paddingX={1} marginTop={1}>
|
||||
<Text color="cyan" bold>Resource Usage Summary</Text>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text color="gray">Current: </Text>
|
||||
<Text>{formatBytes(summary.current.memory.rss)} mem, </Text>
|
||||
<Text>{formatPercent(summary.current.cpu.percent || 0)} cpu</Text>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<Text color="gray">Peak: </Text>
|
||||
<Text>{formatBytes(summary.peak.memory)} mem, </Text>
|
||||
<Text>{formatPercent(summary.peak.cpu)} cpu</Text>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<Text color="gray">Average: </Text>
|
||||
<Text>{formatBytes(summary.average.memory)} mem, </Text>
|
||||
<Text>{formatPercent(summary.average.cpu)} cpu</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -9,14 +9,21 @@ interface ControlKeysOptions {
|
|||
showSlashCommands: boolean;
|
||||
showFileSearch: boolean;
|
||||
cycleModes: () => Promise<PermissionMode>;
|
||||
clearInput?: () => void;
|
||||
}
|
||||
|
||||
export function handleControlKeys(options: ControlKeysOptions): boolean {
|
||||
const { input, key, exit, showSlashCommands, showFileSearch, cycleModes } =
|
||||
const { input, key, exit, showSlashCommands, showFileSearch, cycleModes, clearInput } =
|
||||
options;
|
||||
|
||||
// Handle Ctrl+C and Ctrl+D
|
||||
if (key.ctrl && (input === "c" || input === "d")) {
|
||||
// Handle Ctrl+C to clear input
|
||||
if (key.ctrl && input === "c" && clearInput) {
|
||||
clearInput();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Handle Ctrl+D to exit
|
||||
if (key.ctrl && input === "d") {
|
||||
exit();
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
1
packages/openai-adapters/package-lock.json
generated
1
packages/openai-adapters/package-lock.json
generated
|
|
@ -12528,6 +12528,7 @@
|
|||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz",
|
||||
"integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==",
|
||||
"dev": true,
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue