feat: enhance terminal functionality and settings

- Added new endpoints for terminal settings: GET and PUT /settings to retrieve and update terminal configurations.
- Implemented session limit checks during session creation, returning a 429 status when the limit is reached.
- Introduced a new TerminalSection in settings view for customizing terminal appearance and behavior, including font family, default font size, line height, and screen reader mode.
- Added support for new terminal features such as search functionality and improved error handling with a TerminalErrorBoundary component.
- Updated terminal layout persistence to include session IDs for reconnection and enhanced terminal state management.
- Introduced new keyboard shortcuts for terminal actions, including creating new terminal tabs.
- Enhanced UI with scrollbar theming for terminal components.
This commit is contained in:
SuperComboGamer
2025-12-20 22:56:25 -05:00
parent 8fcc6cb4db
commit 195b98e688
24 changed files with 2729 additions and 149 deletions

View File

@@ -21,6 +21,10 @@ import {
} from "./routes/sessions.js";
import { createSessionDeleteHandler } from "./routes/session-delete.js";
import { createSessionResizeHandler } from "./routes/session-resize.js";
import {
createSettingsGetHandler,
createSettingsUpdateHandler,
} from "./routes/settings.js";
// Re-export for use in main index.ts
export { validateTerminalToken, isTerminalEnabled, isTerminalPasswordRequired };
@@ -39,6 +43,8 @@ export function createTerminalRoutes(): Router {
router.post("/sessions", createSessionsCreateHandler());
router.delete("/sessions/:id", createSessionDeleteHandler());
router.post("/sessions/:id/resize", createSessionResizeHandler());
router.get("/settings", createSettingsGetHandler());
router.put("/settings", createSettingsUpdateHandler());
return router;
}

View File

@@ -34,6 +34,21 @@ export function createSessionsCreateHandler() {
shell,
});
// Check if session creation was refused due to limit
if (!session) {
const maxSessions = terminalService.getMaxSessions();
const currentSessions = terminalService.getSessionCount();
logger.warn(`Session limit reached: ${currentSessions}/${maxSessions}`);
res.status(429).json({
success: false,
error: "Maximum terminal sessions reached",
details: `Server limit is ${maxSessions} concurrent sessions. Please close unused terminals.`,
currentSessions,
maxSessions,
});
return;
}
res.json({
success: true,
data: {

View File

@@ -0,0 +1,55 @@
/**
* GET/PUT /settings endpoint - Get/Update terminal settings
*/
import type { Request, Response } from "express";
import { getTerminalService } from "../../../services/terminal-service.js";
import { getErrorMessage, logError } from "../common.js";
export function createSettingsGetHandler() {
return (_req: Request, res: Response): void => {
const terminalService = getTerminalService();
res.json({
success: true,
data: {
maxSessions: terminalService.getMaxSessions(),
currentSessions: terminalService.getSessionCount(),
},
});
};
}
export function createSettingsUpdateHandler() {
return (req: Request, res: Response): void => {
try {
const terminalService = getTerminalService();
const { maxSessions } = req.body;
if (typeof maxSessions === "number") {
if (maxSessions < 1 || maxSessions > 500) {
res.status(400).json({
success: false,
error: "maxSessions must be between 1 and 500",
});
return;
}
terminalService.setMaxSessions(maxSessions);
}
res.json({
success: true,
data: {
maxSessions: terminalService.getMaxSessions(),
currentSessions: terminalService.getSessionCount(),
},
});
} catch (error) {
logError(error, "Update terminal settings failed");
res.status(500).json({
success: false,
error: "Failed to update terminal settings",
details: getErrorMessage(error),
});
}
};
}

View File

@@ -13,9 +13,16 @@ import * as fs from "fs";
// Maximum scrollback buffer size (characters)
const MAX_SCROLLBACK_SIZE = 50000; // ~50KB per terminal
// Maximum number of concurrent terminal sessions
// Can be overridden via TERMINAL_MAX_SESSIONS environment variable
// Default set to 1000 - effectively unlimited for most use cases
let maxSessions = parseInt(process.env.TERMINAL_MAX_SESSIONS || "1000", 10);
// Throttle output to prevent overwhelming WebSocket under heavy load
const OUTPUT_THROTTLE_MS = 16; // ~60fps max update rate
const OUTPUT_BATCH_SIZE = 8192; // Max bytes to send per batch
// Using 4ms for responsive input feedback while still preventing flood
// Note: 16ms caused perceived input lag, especially with backspace
const OUTPUT_THROTTLE_MS = 4; // ~250fps max update rate for responsive input
const OUTPUT_BATCH_SIZE = 4096; // Smaller batches for lower latency
export interface TerminalSession {
id: string;
@@ -176,9 +183,40 @@ export class TerminalService extends EventEmitter {
}
/**
* Create a new terminal session
* Get current session count
*/
createSession(options: TerminalOptions = {}): TerminalSession {
getSessionCount(): number {
return this.sessions.size;
}
/**
* Get maximum allowed sessions
*/
getMaxSessions(): number {
return maxSessions;
}
/**
* Set maximum allowed sessions (can be called dynamically)
*/
setMaxSessions(limit: number): void {
if (limit >= 1 && limit <= 500) {
maxSessions = limit;
console.log(`[Terminal] Max sessions limit updated to ${limit}`);
}
}
/**
* Create a new terminal session
* Returns null if the maximum session limit has been reached
*/
createSession(options: TerminalOptions = {}): TerminalSession | null {
// Check session limit
if (this.sessions.size >= maxSessions) {
console.error(`[Terminal] Max sessions (${maxSessions}) reached, refusing new session`);
return null;
}
const id = `term-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
const { shell: detectedShell, args: shellArgs } = this.detectShell();
@@ -188,11 +226,15 @@ export class TerminalService extends EventEmitter {
const cwd = this.resolveWorkingDirectory(options.cwd);
// Build environment with some useful defaults
// These settings ensure consistent terminal behavior across platforms
const env: Record<string, string> = {
...process.env,
TERM: "xterm-256color",
COLORTERM: "truecolor",
TERM_PROGRAM: "automaker-terminal",
// Ensure proper locale for character handling
LANG: process.env.LANG || "en_US.UTF-8",
LC_ALL: process.env.LC_ALL || process.env.LANG || "en_US.UTF-8",
...options.env,
};
@@ -350,12 +392,16 @@ export class TerminalService extends EventEmitter {
clearTimeout(session.resizeDebounceTimeout);
session.resizeDebounceTimeout = null;
}
session.pty.kill();
// Use SIGKILL for forceful termination - shell processes may ignore SIGTERM/SIGHUP
// This ensures the PTY process is actually killed, especially on WSL
session.pty.kill("SIGKILL");
this.sessions.delete(sessionId);
console.log(`[Terminal] Session ${sessionId} killed`);
return true;
} catch (error) {
console.error(`[Terminal] Error killing session ${sessionId}:`, error);
// Still try to remove from map even if kill fails
this.sessions.delete(sessionId);
return false;
}
}