Initial commit: Sencho V1 complete with Auth and Dockerization

This commit is contained in:
unknown
2026-02-20 18:39:32 -05:00
commit 293f9cef26
51 changed files with 11547 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
# Sencho Configuration
# Copy this file to .env and update the values for production
# JWT secret - generate a secure random string for production
JWT_SECRET=your-secure-jwt-secret-here
# Directory containing docker-compose files
COMPOSE_DIR=/path/to/your/compose/files
+27
View File
@@ -0,0 +1,27 @@
# Dependencies
node_modules/
frontend/node_modules/
backend/node_modules/
# Environment Variables (CRITICAL: Never commit secrets)
.env
.env.*
!.env.example
# Build Outputs
dist/
frontend/dist/
backend/dist/
# Sencho User Data & Mocks
data/
mock_data/
docker/
sencho.json
# OS Generated Files
.DS_Store
Thumbs.db
#PRD
Product Requirements Document
+58
View File
@@ -0,0 +1,58 @@
# Stage 1: Build Frontend
FROM node:20-alpine AS frontend-builder
WORKDIR /app/frontend
# Copy frontend package files
COPY frontend/package*.json ./
# Install dependencies
RUN npm install
# Copy frontend source
COPY frontend/ ./
# Build frontend
RUN npm run build
# Stage 2: Build Backend
FROM node:20-alpine AS backend-builder
WORKDIR /app/backend
# Copy backend package files
COPY backend/package*.json ./
# Install dependencies
RUN npm install
# Copy backend source
COPY backend/ ./
# Build backend
RUN npm run build
# Stage 3: Production
FROM node:20-alpine
# Install Docker CLI and Docker Compose CLI
RUN apk add --no-cache docker-cli docker-cli-compose
WORKDIR /app
# Copy built backend and node_modules from backend-builder
COPY --from=backend-builder /app/backend/dist ./dist
COPY --from=backend-builder /app/backend/node_modules ./node_modules
COPY --from=backend-builder /app/backend/package.json ./
# Copy built frontend from frontend-builder to public folder
COPY --from=frontend-builder /app/frontend/dist ./public
# Set environment to production
ENV NODE_ENV=production
# Expose port
EXPOSE 3000
# Start the server
CMD ["node", "dist/index.js"]
+2653
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "nodemon --exec ts-node src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"devDependencies": {
"@types/bcrypt": "^6.0.0",
"@types/cookie-parser": "^1.4.10",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^25.3.0",
"nodemon": "^3.1.13",
"ts-node": "^10.9.2",
"typescript": "^5.9.3"
},
"dependencies": {
"@types/cors": "^2.8.19",
"@types/dockerode": "^4.0.1",
"@types/express": "^5.0.6",
"@types/ws": "^8.18.1",
"bcrypt": "^6.0.0",
"composerize": "^1.7.5",
"cookie-parser": "^1.4.7",
"cors": "^2.8.6",
"dockerode": "^4.0.9",
"express": "^5.2.1",
"jsonwebtoken": "^9.0.3",
"systeminformation": "^5.31.1",
"ws": "^8.19.0"
}
}
+510
View File
@@ -0,0 +1,510 @@
import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import WebSocket from 'ws';
import jwt from 'jsonwebtoken';
import DockerController from './services/DockerController';
import { FileSystemService } from './services/FileSystemService';
import { ComposeService } from './services/ComposeService';
import { ConfigService } from './services/ConfigService';
import composerize from 'composerize';
import si from 'systeminformation';
import http from 'http';
const app = express();
const PORT = 3000;
// Environment variables
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
// ConfigService for persistent auth storage
const configService = new ConfigService();
// Cookie settings
const COOKIE_NAME = 'sencho_token';
const COOKIE_OPTIONS = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict' as const,
maxAge: 24 * 60 * 60 * 1000, // 24 hours
};
// Middleware
app.use(cors({
origin: true,
credentials: true,
}));
app.use(express.json());
app.use(cookieParser());
// Extend Express Request type for user
declare module 'express' {
interface Request {
user?: { username: string };
}
}
// Authentication Middleware
const authMiddleware = (req: Request, res: Response, next: NextFunction): void => {
const token = req.cookies[COOKIE_NAME];
if (!token) {
res.status(401).json({ error: 'Authentication required' });
return;
}
try {
const decoded = jwt.verify(token, JWT_SECRET) as { username: string };
req.user = { username: decoded.username };
next();
} catch {
res.status(401).json({ error: 'Invalid or expired token' });
return;
}
};
// Auth Routes (no authentication required)
// Check if setup is needed
app.get('/api/auth/status', async (req: Request, res: Response): Promise<void> => {
try {
const needsSetup = await configService.needsSetup();
res.json({ needsSetup });
} catch (error) {
console.error('Error checking setup status:', error);
res.json({ needsSetup: true });
}
});
// Initial setup endpoint
app.post('/api/auth/setup', async (req: Request, res: Response): Promise<void> => {
try {
// Check if setup is still needed
const needsSetup = await configService.needsSetup();
if (!needsSetup) {
res.status(400).json({ error: 'Setup has already been completed' });
return;
}
const { username, password, confirmPassword } = req.body;
// Validation
if (!username || !password || !confirmPassword) {
res.status(400).json({ error: 'All fields are required' });
return;
}
if (username.length < 3) {
res.status(400).json({ error: 'Username must be at least 3 characters' });
return;
}
if (password.length < 6) {
res.status(400).json({ error: 'Password must be at least 6 characters' });
return;
}
if (password !== confirmPassword) {
res.status(400).json({ error: 'Passwords do not match' });
return;
}
// Save credentials
await configService.saveConfig(username, password);
// Issue JWT and log user in
const token = jwt.sign({ username }, JWT_SECRET, { expiresIn: '24h' });
res.cookie(COOKIE_NAME, token, COOKIE_OPTIONS);
res.json({ success: true, message: 'Setup completed successfully' });
} catch (error) {
console.error('Setup error:', error);
res.status(500).json({ error: 'Failed to complete setup' });
}
});
// Login endpoint
app.post('/api/auth/login', async (req: Request, res: Response): Promise<void> => {
const { username, password } = req.body;
if (!username || !password) {
res.status(400).json({ error: 'Username and password are required' });
return;
}
try {
const isValid = await configService.validateCredentials(username, password);
if (isValid) {
const token = jwt.sign({ username }, JWT_SECRET, { expiresIn: '24h' });
res.cookie(COOKIE_NAME, token, COOKIE_OPTIONS);
res.json({ success: true, message: 'Login successful' });
return;
}
res.status(401).json({ error: 'Invalid credentials' });
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'Login failed' });
}
});
app.post('/api/auth/logout', (req: Request, res: Response): void => {
res.clearCookie(COOKIE_NAME, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
});
res.json({ success: true, message: 'Logged out successfully' });
});
// Check authentication status
app.get('/api/auth/check', authMiddleware, (req: Request, res: Response): void => {
res.json({ authenticated: true, user: req.user });
});
// Apply authentication middleware to all /api/* routes except /api/auth/*
app.use('/api', (req: Request, res: Response, next: NextFunction): void => {
if (req.path.startsWith('/auth/')) {
next();
return;
}
authMiddleware(req, res, next);
});
// Create HTTP server for WebSocket upgrade handling
const server = http.createServer(app);
// WebSocket server with authentication
const wss = new WebSocket.Server({ noServer: true });
let terminalWs: WebSocket | null = null;
// Handle WebSocket upgrade with JWT authentication
server.on('upgrade', (req, socket, head) => {
// Parse cookies from the upgrade request
const cookieHeader = req.headers.cookie || '';
const cookies = Object.fromEntries(
cookieHeader.split(';').map(c => c.trim().split('=')).filter(([k, v]) => k && v)
);
const token = cookies[COOKIE_NAME];
if (!token) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
try {
jwt.verify(token, JWT_SECRET);
// Authentication successful, proceed with WebSocket connection
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
} catch (error) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
});
wss.on('connection', (ws) => {
console.log('WebSocket connected');
ws.on('message', (message) => {
try {
const data = JSON.parse(message.toString());
if (data.action === 'connectTerminal') {
terminalWs = ws;
} else if (data.action === 'streamStats') {
const dockerController = DockerController.getInstance();
dockerController.streamStats(data.containerId, ws);
} else if (data.action === 'execContainer') {
// Handle container exec for bash access
const dockerController = DockerController.getInstance();
dockerController.execContainer(data.containerId, ws);
} else if (data.action === 'input') {
// Forward input to exec stream
const dockerController = DockerController.getInstance();
dockerController.sendExecInput(data.data);
} else if (data.action === 'resize') {
const dockerController = DockerController.getInstance();
dockerController.resizeExec(data.cols, data.rows);
}
} catch (error) {
ws.send(JSON.stringify({ error: 'Invalid message' }));
}
});
});
// API Routes (all protected by authMiddleware)
app.get('/api/containers', async (req: Request, res: Response) => {
try {
const dockerController = DockerController.getInstance();
const containers = await dockerController.getRunningContainers();
res.json(containers);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch containers' });
}
});
const fileSystemService = new FileSystemService();
app.get('/api/stacks', async (req: Request, res: Response) => {
try {
const files = await fileSystemService.getStackFiles();
res.json(files);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch stack files' });
}
});
app.get('/api/stacks/:filename', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
const content = await fileSystemService.getStackContent(filename);
res.send(content);
} catch (error) {
res.status(500).json({ error: 'Failed to read file' });
}
});
app.put('/api/stacks/:filename', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
const { content } = req.body;
console.log('PUT /api/stacks/:filename', { filename, contentType: typeof content, contentLength: content?.length });
if (typeof content !== 'string') {
console.error('Content is not a string:', content);
return res.status(400).json({ error: 'Content must be a string' });
}
await fileSystemService.saveStackContent(filename, content);
console.log('File saved successfully:', filename);
res.json({ message: 'File saved successfully' });
} catch (error) {
console.error('Failed to save file:', error);
res.status(500).json({ error: 'Failed to save file' });
}
});
app.get('/api/stacks/:filename/env', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
const exists = await fileSystemService.envExists(filename);
if (!exists) {
return res.status(404).json({ error: 'Env file not found' });
}
const content = await fileSystemService.getEnvContent(filename);
res.send(content);
} catch (error) {
res.status(500).json({ error: 'Failed to read env file' });
}
});
app.put('/api/stacks/:filename/env', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
const { content } = req.body;
if (typeof content !== 'string') {
return res.status(400).json({ error: 'Content must be a string' });
}
await fileSystemService.saveEnvContent(filename, content);
res.json({ message: 'Env file saved successfully' });
} catch (error) {
console.error('Failed to save env file:', error);
res.status(500).json({ error: 'Failed to save env file' });
}
});
app.post('/api/stacks', async (req: Request, res: Response) => {
try {
const { filename } = req.body;
if (!filename || typeof filename !== 'string') {
return res.status(400).json({ error: 'Filename is required and must be a string' });
}
await fileSystemService.createStack(filename);
res.json({ message: 'Stack created successfully' });
} catch (error) {
console.error('Failed to create stack:', error);
res.status(500).json({ error: 'Failed to create stack' });
}
});
app.delete('/api/stacks/:filename', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
await fileSystemService.deleteStack(filename);
res.json({ message: 'Stack deleted successfully' });
} catch (error) {
console.error('Failed to delete stack:', error);
res.status(500).json({ error: 'Failed to delete stack' });
}
});
app.get('/api/stacks/:filename/containers', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
const stackName = filename.replace(/\.yml$/, '');
const dockerController = DockerController.getInstance();
const containers = await dockerController.getContainersByStack(stackName);
res.json(containers);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch containers' });
}
});
app.post('/api/containers/:id/start', async (req: Request, res: Response) => {
try {
const id = req.params.id as string;
const dockerController = DockerController.getInstance();
await dockerController.startContainer(id);
res.json({ message: 'Container started' });
} catch (error) {
res.status(500).json({ error: 'Failed to start container' });
}
});
app.post('/api/containers/:id/stop', async (req: Request, res: Response) => {
try {
const id = req.params.id as string;
const dockerController = DockerController.getInstance();
await dockerController.stopContainer(id);
res.json({ message: 'Container stopped' });
} catch (error) {
res.status(500).json({ error: 'Failed to stop container' });
}
});
app.post('/api/containers/:id/restart', async (req: Request, res: Response) => {
try {
const id = req.params.id as string;
const dockerController = DockerController.getInstance();
await dockerController.restartContainer(id);
res.json({ message: 'Container restarted' });
} catch (error) {
res.status(500).json({ error: 'Failed to restart container' });
}
});
const composeService = new ComposeService();
app.post('/api/stacks/:filename/up', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
composeService.runCommand(filename, 'up', terminalWs || undefined);
res.json({ status: 'Command started' });
} catch (error) {
res.status(500).json({ error: 'Failed to start command' });
}
});
app.post('/api/stacks/:filename/down', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
composeService.runCommand(filename, 'down', terminalWs || undefined);
res.json({ status: 'Command started' });
} catch (error) {
res.status(500).json({ error: 'Failed to start command' });
}
});
// Update stack: pull images and recreate containers
app.post('/api/stacks/:filename/update', async (req: Request, res: Response) => {
try {
const filename = req.params.filename as string;
// Run update asynchronously, don't wait for completion
composeService.updateStack(filename, terminalWs || undefined).catch(error => {
console.error('Update stack error:', error);
});
res.json({ status: 'Update started' });
} catch (error) {
res.status(500).json({ error: 'Failed to start update' });
}
});
// Docker Run to Compose converter endpoint
app.post('/api/convert', async (req: Request, res: Response) => {
try {
const { dockerRun } = req.body;
if (!dockerRun || typeof dockerRun !== 'string') {
return res.status(400).json({ error: 'dockerRun command is required' });
}
const yaml = composerize(dockerRun);
res.json({ yaml });
} catch (error) {
console.error('Conversion error:', error);
res.status(500).json({ error: 'Failed to convert docker run command' });
}
});
// Get all containers stats for dashboard
app.get('/api/stats', async (req: Request, res: Response) => {
try {
const dockerController = DockerController.getInstance();
const containers = await dockerController.getRunningContainers();
const allContainers = await dockerController.getAllContainers();
const active = containers.length;
const exited = allContainers.filter((c: { State: string }) => c.State === 'exited').length;
const total = allContainers.length;
res.json({ active, exited, total, inactive: total - active - exited });
} catch (error) {
res.status(500).json({ error: 'Failed to fetch stats' });
}
});
// Get host system stats
app.get('/api/system/stats', async (req: Request, res: Response) => {
try {
const [currentLoad, mem, fsSize] = await Promise.all([
si.currentLoad(),
si.mem(),
si.fsSize(),
]);
// Find the main mount (usually the largest or root mount)
const mainDisk = fsSize.find(fs => fs.mount === '/' || fs.mount === 'C:') || fsSize[0];
res.json({
cpu: {
usage: currentLoad.currentLoad.toFixed(1),
cores: currentLoad.cpus.length,
},
memory: {
total: mem.total,
used: mem.used,
free: mem.free,
usagePercent: ((mem.used / mem.total) * 100).toFixed(1),
},
disk: mainDisk ? {
fs: mainDisk.fs,
mount: mainDisk.mount,
total: mainDisk.size,
used: mainDisk.used,
free: mainDisk.available,
usagePercent: mainDisk.use ? mainDisk.use.toFixed(1) : '0',
} : null,
});
} catch (error) {
console.error('Failed to fetch system stats:', error);
res.status(500).json({ error: 'Failed to fetch system stats' });
}
});
// Serve static files in production (for Docker deployment)
if (process.env.NODE_ENV === 'production') {
app.use(express.static('public'));
// Handle SPA routing - serve index.html for non-API routes
app.get('*', (req: Request, res: Response) => {
if (!req.path.startsWith('/api')) {
res.sendFile('index.html', { root: 'public' });
}
});
}
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
+105
View File
@@ -0,0 +1,105 @@
import { spawn } from 'child_process';
import path from 'path';
import WebSocket from 'ws';
export class ComposeService {
private baseDir: string;
constructor() {
this.baseDir = process.env.COMPOSE_DIR || path.join(process.cwd(), '..', 'mock_data', 'docker', 'compose');
}
runCommand(filename: string, action: 'up' | 'down', ws?: WebSocket) {
const filePath = path.join(this.baseDir, filename);
const args = action === 'up' ? ['compose', '-f', filePath, 'up', '-d'] : ['compose', '-f', filePath, 'down'];
const child = spawn('docker', args, { shell: true });
if (ws) {
child.stdout.on('data', (data: Buffer) => {
ws.send(data.toString());
});
child.stderr.on('data', (data: Buffer) => {
ws.send(data.toString());
});
child.on('close', (code: number | null) => {
ws.send(`Command exited with code ${code}\n`);
});
child.on('error', (error: Error) => {
ws.send(`Error: ${error.message}\n`);
});
}
}
// Update command: pull images first, then recreate containers
async updateStack(filename: string, ws?: WebSocket): Promise<void> {
const filePath = path.join(this.baseDir, filename);
const sendOutput = (data: string) => {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(data);
}
};
// Step 1: Pull images
sendOutput('=== Pulling latest images ===\n');
await new Promise<void>((resolve, reject) => {
const pullProcess = spawn('docker', ['compose', '-f', filePath, 'pull'], { shell: true });
pullProcess.stdout.on('data', (data: Buffer) => {
sendOutput(data.toString());
});
pullProcess.stderr.on('data', (data: Buffer) => {
sendOutput(data.toString());
});
pullProcess.on('close', (code: number | null) => {
if (code === 0) {
sendOutput('=== Images pulled successfully ===\n');
resolve();
} else {
sendOutput(`=== Pull failed with code ${code} ===\n`);
reject(new Error(`Pull failed with code ${code}`));
}
});
pullProcess.on('error', (error: Error) => {
sendOutput(`Pull error: ${error.message}\n`);
reject(error);
});
});
// Step 2: Recreate containers with new images
sendOutput('=== Recreating containers ===\n');
await new Promise<void>((resolve, reject) => {
const upProcess = spawn('docker', ['compose', '-f', filePath, 'up', '-d'], { shell: true });
upProcess.stdout.on('data', (data: Buffer) => {
sendOutput(data.toString());
});
upProcess.stderr.on('data', (data: Buffer) => {
sendOutput(data.toString());
});
upProcess.on('close', (code: number | null) => {
if (code === 0) {
sendOutput('=== Stack updated successfully ===\n');
resolve();
} else {
sendOutput(`=== Update failed with code ${code} ===\n`);
reject(new Error(`Up failed with code ${code}`));
}
});
upProcess.on('error', (error: Error) => {
sendOutput(`Update error: ${error.message}\n`);
reject(error);
});
});
}
}
+61
View File
@@ -0,0 +1,61 @@
import { promises as fs } from 'fs';
import path from 'path';
import bcrypt from 'bcrypt';
interface AuthConfig {
username: string;
passwordHash: string;
}
export class ConfigService {
private dataDir: string;
private configPath: string;
constructor() {
this.dataDir = process.env.DATA_DIR || path.join(process.cwd(), 'data');
this.configPath = path.join(this.dataDir, 'sencho.json');
}
private async ensureDataDir(): Promise<void> {
try {
await fs.mkdir(this.dataDir, { recursive: true });
} catch {
// Directory already exists
}
}
async needsSetup(): Promise<boolean> {
try {
const config = await this.readConfig();
return !config || !config.username || !config.passwordHash;
} catch {
return true;
}
}
async readConfig(): Promise<AuthConfig | null> {
try {
const data = await fs.readFile(this.configPath, 'utf-8');
return JSON.parse(data);
} catch {
return null;
}
}
async saveConfig(username: string, password: string): Promise<void> {
await this.ensureDataDir();
const saltRounds = 10;
const passwordHash = await bcrypt.hash(password, saltRounds);
const config: AuthConfig = { username, passwordHash };
await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), 'utf-8');
}
async validateCredentials(username: string, password: string): Promise<boolean> {
const config = await this.readConfig();
if (!config) return false;
if (username !== config.username) return false;
return await bcrypt.compare(password, config.passwordHash);
}
}
+149
View File
@@ -0,0 +1,149 @@
import Docker from 'dockerode';
import WebSocket from 'ws';
import { Duplex } from 'stream';
class DockerController {
private static instance: DockerController;
private docker: Docker;
private execStream: Duplex | null = null;
private currentExec: Docker.Exec | null = null;
private constructor() {
this.docker = new Docker({ socketPath: '/var/run/docker.sock' });
}
public static getInstance(): DockerController {
if (!DockerController.instance) {
DockerController.instance = new DockerController();
}
return DockerController.instance;
}
public async getRunningContainers() {
const containers = await this.docker.listContainers({ all: false });
return containers;
}
public async getAllContainers() {
const containers = await this.docker.listContainers({ all: true });
return containers;
}
public async getContainersByStack(stackName: string) {
const containers = await this.docker.listContainers({ all: true });
// Normalize the stack name: remove all non-alphanumeric characters and lowercase
// Docker Compose strips hyphens and underscores from project names
const normalizedStackName = stackName.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return containers.filter(container => {
if (!container.Labels || !container.Labels['com.docker.compose.project']) {
return false;
}
// Normalize the Docker label for comparison
const projectLabel = container.Labels['com.docker.compose.project'].replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return projectLabel === normalizedStackName;
});
}
public async startContainer(containerId: string) {
const container = this.docker.getContainer(containerId);
await container.start();
}
public async stopContainer(containerId: string) {
const container = this.docker.getContainer(containerId);
await container.stop();
}
public async restartContainer(containerId: string) {
const container = this.docker.getContainer(containerId);
await container.restart();
}
public async streamStats(containerId: string, ws: WebSocket) {
const container = this.docker.getContainer(containerId);
const stats = await container.stats({ stream: true });
stats.on('data', (chunk: Buffer) => {
ws.send(chunk.toString());
});
stats.on('error', (err: Error) => {
ws.send(JSON.stringify({ error: err.message }));
});
stats.on('end', () => {
ws.send(JSON.stringify({ end: true }));
});
}
public async execContainer(containerId: string, ws: WebSocket) {
try {
const container = this.docker.getContainer(containerId);
// Try bash first, fall back to sh
let exec: Docker.Exec;
try {
exec = await container.exec({
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Tty: true,
Cmd: ['/bin/bash'],
});
} catch {
exec = await container.exec({
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Tty: true,
Cmd: ['/bin/sh'],
});
}
this.currentExec = exec;
const stream = await exec.start({ hijack: true, stdin: true });
this.execStream = stream;
// Handle output from container
stream.on('data', (chunk: Buffer) => {
ws.send(JSON.stringify({ type: 'output', data: chunk.toString() }));
});
stream.on('error', (err: Error) => {
ws.send(JSON.stringify({ type: 'error', message: err.message }));
});
stream.on('end', () => {
ws.send(JSON.stringify({ type: 'exit' }));
this.execStream = null;
this.currentExec = null;
});
ws.send(JSON.stringify({ type: 'connected' }));
} catch (error) {
const err = error as Error;
ws.send(JSON.stringify({ type: 'error', message: err.message }));
}
}
public sendExecInput(data: string) {
if (this.execStream) {
this.execStream.write(data);
}
}
public async resizeExec(cols: number, rows: number) {
if (this.currentExec) {
try {
await this.currentExec.resize({ w: cols, h: rows });
} catch {
// Ignore resize errors
}
}
}
}
export default DockerController;
+116
View File
@@ -0,0 +1,116 @@
import { promises as fs } from 'fs';
import path from 'path';
export class FileSystemService {
private baseDir: string;
constructor() {
this.baseDir = process.env.COMPOSE_DIR || path.join(process.cwd(), '..', 'mock_data', 'docker', 'compose');
}
async getStackFiles(): Promise<string[]> {
try {
const files = await fs.readdir(this.baseDir);
return files.filter(file => file.endsWith('.yml') || file.endsWith('.yaml'));
} catch (error) {
console.error('Error reading stack files:', error);
return [];
}
}
async getStackContent(filename: string): Promise<string> {
const filePath = path.join(this.baseDir, filename);
try {
return await fs.readFile(filePath, 'utf-8');
} catch (error) {
console.error('Error reading file:', error);
throw new Error(`Failed to read file: ${filename}`);
}
}
async saveStackContent(filename: string, content: string): Promise<void> {
const filePath = path.join(this.baseDir, filename);
console.log('Saving to path:', filePath);
try {
await fs.writeFile(filePath, content, 'utf-8');
console.log('File written successfully');
} catch (error) {
console.error('Error writing file:', error);
throw new Error(`Failed to save file: ${filename}`);
}
}
async envExists(filename: string): Promise<boolean> {
const envFilename = filename.replace(/\.yml$/, '.env');
const envPath = path.join(this.baseDir, envFilename);
try {
await fs.access(envPath);
return true;
} catch {
return false;
}
}
async getEnvContent(filename: string): Promise<string> {
const envFilename = filename.replace(/\.yml$/, '.env');
const envPath = path.join(this.baseDir, envFilename);
try {
return await fs.readFile(envPath, 'utf-8');
} catch (error) {
console.error('Error reading env file:', error);
throw new Error(`Failed to read env file for: ${filename}`);
}
}
async saveEnvContent(filename: string, content: string): Promise<void> {
const envFilename = filename.replace(/\.yml$/, '.env');
const envPath = path.join(this.baseDir, envFilename);
console.log('Saving env to path:', envPath);
try {
await fs.writeFile(envPath, content, 'utf-8');
console.log('Env file written successfully');
} catch (error) {
console.error('Error writing env file:', error);
throw new Error(`Failed to save env file for: ${filename}`);
}
}
async createStack(filename: string): Promise<void> {
if (!filename.endsWith('.yml')) {
throw new Error('Filename must end with .yml');
}
const filePath = path.join(this.baseDir, filename);
const boilerplate = `version: '3.8'
services:
# Add your services here
`;
try {
await fs.writeFile(filePath, boilerplate, 'utf-8');
console.log('Stack file created successfully:', filename);
} catch (error) {
console.error('Error creating stack file:', error);
throw new Error(`Failed to create stack file: ${filename}`);
}
}
async deleteStack(filename: string): Promise<void> {
const filePath = path.join(this.baseDir, filename);
const envFilename = filename.replace(/\.yml$/, '.env');
const envPath = path.join(this.baseDir, envFilename);
try {
await fs.unlink(filePath);
console.log('Stack file deleted successfully:', filename);
// Try to delete env file if it exists
try {
await fs.unlink(envPath);
console.log('Associated env file deleted:', envFilename);
} catch {
// Env file doesn't exist, ignore
}
} catch (error) {
console.error('Error deleting stack file:', error);
throw new Error(`Failed to delete stack file: ${filename}`);
}
}
}
+3
View File
@@ -0,0 +1,3 @@
declare module 'composerize' {
export default function composerize(dockerRun: string): string;
}
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+19
View File
@@ -0,0 +1,19 @@
services:
sencho:
build: .
container_name: sencho
ports:
- "3000:3000"
volumes:
# Docker socket for managing containers
- /var/run/docker.sock:/var/run/docker.sock
# Compose files directory
- ${COMPOSE_DIR:-./mock_data/docker/compose}:/app/compose
# Persistent data directory for auth config
- ./data:/app/data
environment:
- NODE_ENV=production
- JWT_SECRET=${JWT_SECRET:-change-this-secret-in-production}
- COMPOSE_DIR=/app/compose
- DATA_DIR=/app/data
restart: unless-stopped
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+23
View File
@@ -0,0 +1,23 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+4954
View File
File diff suppressed because it is too large Load Diff
+46
View File
@@ -0,0 +1,46 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.575.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"tailwind-merge": "^3.5.0",
"tailwindcss": "^3.4.19",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.1",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"autoprefixer": "^10.4.24",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"postcss": "^8.5.6",
"typescript": "~5.9.3",
"typescript-eslint": "^8.48.0",
"vite": "^7.3.1"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+42
View File
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
+44
View File
@@ -0,0 +1,44 @@
import { AuthProvider, useAuth } from './context/AuthContext';
import { Login } from './components/Login';
import { Setup } from './components/Setup';
import EditorLayout from './components/EditorLayout';
function AppContent() {
const { appStatus, isAuthenticated, needsSetup, completeSetup } = useAuth();
if (appStatus === 'loading') {
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-muted-foreground">Loading...</div>
</div>
);
}
if (needsSetup) {
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<Setup className="w-full max-w-sm" onComplete={completeSetup} />
</div>
);
}
if (!isAuthenticated) {
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<Login className="w-full max-w-sm" />
</div>
);
}
return <EditorLayout />;
}
function App() {
return (
<AuthProvider>
<AppContent />
</AuthProvider>
);
}
export default App;
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

+176
View File
@@ -0,0 +1,176 @@
import { useEffect, useRef, useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
import { Button } from './ui/button';
import { Terminal as TerminalIcon, X } from 'lucide-react';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';
interface BashExecModalProps {
isOpen: boolean;
onClose: () => void;
containerId: string;
containerName: string;
}
export default function BashExecModal({ isOpen, onClose, containerId, containerName }: BashExecModalProps) {
const terminalRef = useRef<HTMLDivElement>(null);
const xtermRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const [isConnected, setIsConnected] = useState(false);
useEffect(() => {
if (isOpen && terminalRef.current && !xtermRef.current) {
// Initialize xterm.js
const term = new Terminal({
theme: {
background: '#1e1e1e',
foreground: '#d4d4d4',
cursor: '#ffffff',
cursorAccent: '#000000',
selectionBackground: 'rgba(255, 255, 255, 0.3)',
},
fontFamily: 'Consolas, "Courier New", monospace',
fontSize: 14,
cursorBlink: true,
});
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
term.open(terminalRef.current);
setTimeout(() => {
fitAddon.fit();
}, 100);
xtermRef.current = term;
fitAddonRef.current = fitAddon;
// Connect to WebSocket for bash exec
const ws = new WebSocket('ws://localhost:3000');
wsRef.current = ws;
ws.onopen = () => {
ws.send(JSON.stringify({
action: 'execContainer',
containerId: containerId,
}));
setIsConnected(true);
};
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.type === 'output') {
term.write(data.data);
} else if (data.type === 'error') {
term.write(`\r\n\x1b[31mError: ${data.message}\x1b[0m\r\n`);
} else if (data.type === 'exit') {
term.write('\r\n\x1b[33mSession ended\x1b[0m\r\n');
setIsConnected(false);
}
} catch {
// Raw output
term.write(event.data);
}
};
ws.onerror = () => {
term.write('\r\n\x1b[31mConnection error\x1b[0m\r\n');
setIsConnected(false);
};
ws.onclose = () => {
setIsConnected(false);
};
// Handle user input
term.onData((data) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
action: 'input',
data: data,
}));
}
});
// Handle resize
const handleResize = () => {
if (fitAddonRef.current) {
fitAddonRef.current.fit();
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
action: 'resize',
cols: term.cols,
rows: term.rows,
}));
}
}
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}
return () => {
// Cleanup on close
if (!isOpen) {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (xtermRef.current) {
xtermRef.current.dispose();
xtermRef.current = null;
}
if (fitAddonRef.current) {
fitAddonRef.current = null;
}
setIsConnected(false);
}
};
}, [isOpen, containerId]);
const handleClose = () => {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (xtermRef.current) {
xtermRef.current.dispose();
xtermRef.current = null;
}
setIsConnected(false);
onClose();
};
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
<DialogContent className="max-w-4xl h-[600px] flex flex-col">
<DialogHeader className="flex flex-row items-center justify-between">
<DialogTitle className="flex items-center gap-2">
<TerminalIcon className="w-5 h-5" />
Bash: {containerName}
{isConnected && (
<span className="ml-2 text-xs bg-green-500/20 text-green-500 px-2 py-0.5 rounded-full">
Connected
</span>
)}
</DialogTitle>
<Button variant="ghost" size="sm" onClick={handleClose}>
<X className="w-4 h-4" />
</Button>
</DialogHeader>
<div
ref={terminalRef}
className="flex-1 rounded-lg overflow-hidden bg-[#1e1e1e] p-2"
style={{ minHeight: '500px' }}
/>
</DialogContent>
</Dialog>
);
}
+769
View File
@@ -0,0 +1,769 @@
import { useState, useEffect } from 'react';
import Editor from '@monaco-editor/react';
import TerminalComponent from './Terminal';
import ErrorBoundary from './ErrorBoundary';
import HomeDashboard from './HomeDashboard';
import BashExecModal from './BashExecModal';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription, DialogTrigger } from './ui/dialog';
import { Tabs, TabsList, TabsTrigger } from './ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Plus, Trash2, Play, Square, Save, RefreshCw, Terminal, Sun, Moon, RotateCw, CloudDownload, Pencil, X, Search, Home, LogOut } from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
import { apiFetch } from '@/lib/api';
interface ContainerInfo {
Id: string;
Names: string[];
State: string;
}
interface StackStatus {
[key: string]: 'running' | 'exited' | 'unknown';
}
export default function EditorLayout() {
const { logout } = useAuth();
const [files, setFiles] = useState<string[]>([]);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [content, setContent] = useState<string>('');
const [originalContent, setOriginalContent] = useState<string>('');
const [envContent, setEnvContent] = useState<string>('');
const [originalEnvContent, setOriginalEnvContent] = useState<string>('');
const [envExists, setEnvExists] = useState<boolean>(false);
const [containers, setContainers] = useState<ContainerInfo[]>([]);
const [containerStats, setContainerStats] = useState<Record<string, {cpu: string, ram: string}>>({});
const [activeTab, setActiveTab] = useState<'compose' | 'env'>('compose');
const [createDialogOpen, setCreateDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [newStackName, setNewStackName] = useState('');
const [stackToDelete, setStackToDelete] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [isDarkMode, setIsDarkMode] = useState(true);
const [showConsole, setShowConsole] = useState(true);
const [isEditing, setIsEditing] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [stackStatuses, setStackStatuses] = useState<StackStatus>({});
// Bash exec modal state
const [bashModalOpen, setBashModalOpen] = useState(false);
const [selectedContainer, setSelectedContainer] = useState<{ id: string; name: string } | null>(null);
// Theme toggle effect
useEffect(() => {
const html = document.documentElement;
if (isDarkMode) {
html.classList.add('dark');
} else {
html.classList.remove('dark');
}
}, [isDarkMode]);
const refreshStacks = async () => {
setIsLoading(true);
try {
const res = await apiFetch('/stacks');
const stacks = await res.json();
setFiles(Array.isArray(stacks) ? stacks : []);
// Fetch status for each stack
const statuses: StackStatus = {};
for (const file of stacks) {
try {
const containersRes = await apiFetch(`/stacks/${file}/containers`);
const containers = await containersRes.json();
const hasRunning = Array.isArray(containers) && containers.some((c: ContainerInfo) => c.State === 'running');
statuses[file] = hasRunning ? 'running' : (Array.isArray(containers) && containers.length > 0 ? 'exited' : 'unknown');
} catch {
statuses[file] = 'unknown';
}
}
setStackStatuses(statuses);
} catch (error) {
console.error('Failed to refresh stacks:', error);
setFiles([]);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
refreshStacks();
}, []);
useEffect(() => {
const wsMap: Record<string, WebSocket> = {};
(containers || []).forEach(container => {
if (!container?.Id) return;
try {
const ws = new WebSocket('ws://localhost:3000');
wsMap[container.Id] = ws;
ws.onopen = () => ws.send(JSON.stringify({ action: 'streamStats', containerId: container.Id }));
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.cpu_stats && data.precpu_stats && data.memory_stats) {
const cpuDelta = data.cpu_stats.cpu_usage.total_usage - data.precpu_stats.cpu_usage.total_usage;
const systemDelta = data.cpu_stats.system_cpu_usage - data.precpu_stats.system_cpu_usage;
const cpuPercent = systemDelta > 0 ? ((cpuDelta / systemDelta) * data.cpu_stats.online_cpus * 100).toFixed(2) : '0.00';
const ramUsage = (data.memory_stats.usage / (1024 * 1024)).toFixed(2) + ' MB';
setContainerStats(prev => ({ ...prev, [container.Id]: { cpu: cpuPercent + '%', ram: ramUsage } }));
}
} catch {
// Ignore parse errors
}
};
} catch {
// Ignore WebSocket errors
}
});
return () => {
Object.values(wsMap).forEach(ws => {
try {
ws.close();
} catch {
// Ignore close errors
}
});
};
}, [containers]);
const loadFile = async (filename: string) => {
if (!filename) return;
setIsFileLoading(true);
setIsEditing(false); // Reset to view mode when loading a new file
try {
const res = await apiFetch(`/stacks/${filename}`);
const text = await res.text();
setSelectedFile(filename);
setContent(text || '');
setOriginalContent(text || '');
// Load env file
try {
const envRes = await apiFetch(`/stacks/${filename}/env`);
if (envRes.ok) {
const envText = await envRes.text();
setEnvContent(envText || '');
setOriginalEnvContent(envText || '');
setEnvExists(true);
} else {
setEnvContent('');
setOriginalEnvContent('');
setEnvExists(false);
}
} catch {
setEnvContent('');
setOriginalEnvContent('');
setEnvExists(false);
}
// Load containers
try {
const containersRes = await apiFetch(`/stacks/${filename}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
} catch (error) {
console.error('Failed to load containers:', error);
setContainers([]);
}
} catch (error) {
console.error('Failed to load file:', error);
setSelectedFile(null);
setContent('');
setOriginalContent('');
setEnvContent('');
setOriginalEnvContent('');
setContainers([]);
} finally {
setIsFileLoading(false);
}
};
const saveFile = async () => {
if (!selectedFile) return;
const currentContent = activeTab === 'compose' ? (content || '') : (envContent || '');
const endpoint = activeTab === 'compose' ? `/stacks/${selectedFile}` : `/stacks/${selectedFile}/env`;
try {
const response = await apiFetch(endpoint, {
method: 'PUT',
body: JSON.stringify({ content: currentContent }),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
// Update original content after save
if (activeTab === 'compose') {
setOriginalContent(content);
} else {
setOriginalEnvContent(envContent);
}
setIsEditing(false);
alert('File saved successfully!');
} catch (error) {
console.error('Failed to save file:', error);
alert(`Failed to save file: ${(error as Error).message}`);
}
};
const discardChanges = () => {
if (activeTab === 'compose') {
setContent(originalContent);
} else {
setEnvContent(originalEnvContent);
}
setIsEditing(false);
};
const enterEditMode = () => {
setIsEditing(true);
};
const deployStack = async () => {
if (!selectedFile) return;
try {
await apiFetch(`/stacks/${selectedFile}/up`, {
method: 'POST',
});
// Refresh containers after deploy
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to deploy:', error);
}
};
const stopStack = async () => {
if (!selectedFile) return;
try {
await apiFetch(`/stacks/${selectedFile}/down`, {
method: 'POST',
});
// Refresh containers after stop
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to stop:', error);
}
};
const restartStack = async () => {
if (!selectedFile) return;
try {
await apiFetch(`/stacks/${selectedFile}/down`, {
method: 'POST',
});
await apiFetch(`/stacks/${selectedFile}/up`, {
method: 'POST',
});
// Refresh containers after restart
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to restart:', error);
}
};
const updateStack = async () => {
if (!selectedFile) return;
try {
await apiFetch(`/stacks/${selectedFile}/update`, {
method: 'POST',
});
// Refresh containers after update
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to update:', error);
}
};
const deleteStack = async () => {
if (!stackToDelete) return;
try {
const response = await apiFetch(`/stacks/${stackToDelete}`, {
method: 'DELETE',
});
if (!response.ok) throw new Error('Failed to delete stack');
setDeleteDialogOpen(false);
setStackToDelete(null);
if (selectedFile === stackToDelete) {
setSelectedFile(null);
setContent('');
setOriginalContent('');
setEnvContent('');
setOriginalEnvContent('');
setEnvExists(false);
setContainers([]);
setIsEditing(false);
}
await refreshStacks();
} catch (error) {
console.error('Failed to delete stack:', error);
alert('Failed to delete stack');
}
};
const startContainer = async (id: string) => {
if (!id || !selectedFile) return;
try {
await apiFetch(`/containers/${id}/start`, { method: 'POST' });
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to start container:', error);
}
};
const stopContainer = async (id: string) => {
if (!id || !selectedFile) return;
try {
await apiFetch(`/containers/${id}/stop`, { method: 'POST' });
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to stop container:', error);
}
};
const restartContainer = async (id: string) => {
if (!id || !selectedFile) return;
try {
await apiFetch(`/containers/${id}/restart`, { method: 'POST' });
const containersRes = await apiFetch(`/stacks/${selectedFile}/containers`);
const conts = await containersRes.json();
setContainers(Array.isArray(conts) ? conts : []);
refreshStacks();
} catch (error) {
console.error('Failed to restart container:', error);
}
};
const handleCreateStack = async () => {
if (!newStackName.trim()) return;
const filename = newStackName.endsWith('.yml') ? newStackName : newStackName + '.yml';
try {
const response = await apiFetch('/stacks', {
method: 'POST',
body: JSON.stringify({ filename }),
});
if (!response.ok) throw new Error('Failed to create stack');
setCreateDialogOpen(false);
setNewStackName('');
await refreshStacks();
} catch (error) {
console.error('Failed to create stack:', error);
alert('Failed to create stack');
}
};
const openBashModal = (containerId: string, containerName: string) => {
setSelectedContainer({ id: containerId, name: containerName });
setBashModalOpen(true);
};
const closeBashModal = () => {
setBashModalOpen(false);
setSelectedContainer(null);
};
// Safe container list with fallback
const safeContainers = containers || [];
// Safe content strings with fallback
const safeContent = content || '';
const safeEnvContent = envContent || '';
// Get stack name without extension
const stackName = selectedFile ? selectedFile.replace('.yml', '').replace('.yaml', '') : '';
// Filter files based on search query
const filteredFiles = files.filter(file => {
const nameWithoutExt = file.replace('.yml', '').replace('.yaml', '').toLowerCase();
return nameWithoutExt.includes(searchQuery.toLowerCase());
});
// Get display name for stack (without extension)
const getDisplayName = (filename: string) => {
return filename.replace('.yml', '').replace('.yaml', '');
};
return (
<div className="flex h-screen w-screen overflow-hidden bg-background text-foreground">
{/* Left Sidebar (Stacks) */}
<div className="w-64 border-r border-border bg-card flex flex-col">
{/* Branding Header */}
<div className="h-16 flex items-center justify-between px-4 border-b border-border">
<h1 className="text-2xl font-bold tracking-tight">Sencho</h1>
<Button
variant="ghost"
size="icon"
onClick={logout}
title="Logout"
className="text-muted-foreground hover:text-foreground"
>
<LogOut className="w-5 h-5" />
</Button>
</div>
{/* Create Stack Button */}
<div className="p-4">
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
<DialogTrigger asChild>
<Button className="w-full rounded-lg">
<Plus className="w-4 h-4 mr-2" />
Create Stack
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Stack</DialogTitle>
</DialogHeader>
<div className="py-4">
<Input
placeholder="Stack name (e.g., myapp)"
value={newStackName}
onChange={(e) => setNewStackName(e.target.value)}
/>
</div>
<DialogFooter>
<Button onClick={handleCreateStack}>Create</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
{/* Search Input */}
<div className="px-4 pb-2">
<div className="relative">
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="Search stacks..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-8 rounded-lg"
/>
</div>
</div>
{/* Stack List */}
<div className="flex flex-col gap-1 px-2 flex-1 overflow-y-auto">
<h3 className="text-sm font-semibold text-muted-foreground mb-2 px-2">STACKS</h3>
{isLoading ? (
<div className="text-muted-foreground px-2 py-4">Loading...</div>
) : (
(filteredFiles || []).map(file => (
<Button
key={file}
variant="ghost"
className={`justify-start rounded-lg ${selectedFile === file ? 'bg-accent text-accent-foreground' : ''}`}
onClick={() => loadFile(file)}
>
<span className="flex items-center gap-2">
<span
className={`w-2 h-2 rounded-full ${
stackStatuses[file] === 'running' ? 'bg-green-500' :
stackStatuses[file] === 'exited' ? 'bg-red-500' : 'bg-gray-400'
}`}
/>
{getDisplayName(file)}
</span>
</Button>
))
)}
</div>
</div>
{/* Main Content Area */}
<div className="flex-1 flex flex-col overflow-hidden">
{/* Top Header Bar */}
<div className="h-16 flex items-center justify-end px-6 border-b border-border gap-4">
{/* Home Button */}
<Button
variant="outline"
size="sm"
className="rounded-lg"
onClick={() => {
setSelectedFile(null);
setContent('');
setOriginalContent('');
setEnvContent('');
setOriginalEnvContent('');
setEnvExists(false);
setContainers([]);
setIsEditing(false);
}}
title="Go to Home Dashboard"
>
<Home className="w-4 h-4 mr-2" />
Home
</Button>
{/* Console Toggle */}
<Button
variant="outline"
size="sm"
className="rounded-lg"
onClick={() => setShowConsole(!showConsole)}
>
<Terminal className="w-4 h-4 mr-2" />
Console
</Button>
{/* Theme Toggle */}
<Button
variant="outline"
size="sm"
className="rounded-lg"
onClick={() => setIsDarkMode(!isDarkMode)}
>
{isDarkMode ? (
<>
<Sun className="w-4 h-4 mr-2" />
Light
</>
) : (
<>
<Moon className="w-4 h-4 mr-2" />
Dark
</>
)}
</Button>
</div>
{/* Main Workspace */}
<div className="flex-1 overflow-y-auto p-6">
{!isLoading && selectedFile ? (
<ErrorBoundary>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Left Column (Command Center & Terminal) */}
<div className="flex flex-col gap-6">
{/* Command Center Card */}
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="p-4 pb-2">
<div className="flex flex-col gap-3">
{/* Stack Name */}
<CardTitle className="text-2xl font-bold">{stackName}</CardTitle>
{/* Action Bar */}
<div className="flex items-center gap-2 flex-wrap">
<Button size="sm" className="rounded-lg" onClick={deployStack}>
<Play className="w-4 h-4 mr-2" />
Deploy
</Button>
<Button size="sm" variant="outline" className="rounded-lg" onClick={restartStack}>
<RotateCw className="w-4 h-4 mr-2" />
Restart
</Button>
<Button size="sm" variant="outline" className="rounded-lg" onClick={updateStack}>
<CloudDownload className="w-4 h-4 mr-2" />
Update
</Button>
<Button size="sm" variant="outline" className="rounded-lg" onClick={stopStack}>
<Square className="w-4 h-4 mr-2" />
Stop
</Button>
<Button
size="sm"
variant="destructive"
className="rounded-lg"
onClick={() => {
setStackToDelete(selectedFile);
setDeleteDialogOpen(true);
}}
>
<Trash2 className="w-4 h-4 mr-2" />
Delete
</Button>
</div>
</div>
</CardHeader>
<CardContent className="p-4 pt-2">
{/* Containers List */}
<div className="mt-4">
<h4 className="text-sm font-semibold text-muted-foreground mb-3">CONTAINERS</h4>
{safeContainers.length === 0 ? (
<div className="text-muted-foreground text-sm">No containers running for this stack.</div>
) : (
<div className="flex flex-col gap-3">
{safeContainers.map(container => (
<div key={container?.Id || Math.random()} className="flex items-center justify-between p-3 rounded-lg bg-muted/50">
<div className="flex flex-col gap-1">
<span className="font-medium text-sm">{container?.Names?.[0]?.replace('/', '') || 'Unknown'}</span>
<div className="flex items-center gap-2">
<Badge variant={container?.State === 'running' ? 'default' : 'destructive'} className="text-xs">
{container?.State || 'unknown'}
</Badge>
<span className="text-xs text-muted-foreground">
CPU: {containerStats[container?.Id]?.cpu || 'N/A'} | RAM: {containerStats[container?.Id]?.ram || 'N/A'}
</span>
</div>
</div>
<div className="flex gap-1">
<Button
size="sm"
variant="ghost"
className="rounded-lg h-8 w-8 p-0"
onClick={() => startContainer(container?.Id)}
title="Start"
>
<Play className="w-3 h-3" />
</Button>
<Button
size="sm"
variant="ghost"
className="rounded-lg h-8 w-8 p-0"
onClick={() => stopContainer(container?.Id)}
title="Stop"
>
<Square className="w-3 h-3" />
</Button>
<Button
size="sm"
variant="ghost"
className="rounded-lg h-8 w-8 p-0"
onClick={() => restartContainer(container?.Id)}
title="Restart"
>
<RefreshCw className="w-3 h-3" />
</Button>
<Button
size="sm"
variant="outline"
className="rounded-lg h-8 px-2"
onClick={() => openBashModal(container?.Id, container?.Names?.[0]?.replace('/', '') || 'container')}
disabled={container?.State !== 'running'}
title="Open Bash"
>
<Terminal className="w-3 h-3 mr-1" />
Bash
</Button>
</div>
</div>
))}
</div>
)}
</div>
</CardContent>
</Card>
{/* Terminal Section */}
{showConsole && (
<div className="rounded-xl overflow-hidden border border-muted bg-black p-3 h-[400px]">
<h3 className="text-sm font-semibold text-muted-foreground mb-2">Terminal</h3>
<div className="h-[calc(100%-24px)]">
<ErrorBoundary>
<TerminalComponent />
</ErrorBoundary>
</div>
</div>
)}
</div>
{/* Right Column (The Editor) */}
<Card className="rounded-xl border-muted overflow-hidden flex flex-col h-[700px] bg-card">
<div className="p-4 border-b border-muted flex items-center justify-between">
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'compose' | 'env')}>
<TabsList className="bg-muted">
<TabsTrigger value="compose" className="rounded-lg">compose.yaml</TabsTrigger>
<TabsTrigger value="env" disabled={!envExists} className="rounded-lg">.env</TabsTrigger>
</TabsList>
</Tabs>
<div className="flex gap-2">
{!isEditing ? (
<Button size="sm" variant="default" className="rounded-lg" onClick={enterEditMode}>
<Pencil className="w-4 h-4 mr-2" />
Edit
</Button>
) : (
<>
<Button size="sm" variant="outline" className="rounded-lg" onClick={discardChanges}>
<X className="w-4 h-4 mr-2" />
Discard
</Button>
<Button size="sm" variant="default" className="rounded-lg" onClick={saveFile}>
<Save className="w-4 h-4 mr-2" />
Save
</Button>
</>
)}
</div>
</div>
<div className="flex-1 min-h-0">
{!isFileLoading && (
<Editor
height="100%"
language={activeTab === 'compose' ? 'yaml' : 'plaintext'}
theme={isDarkMode ? 'vs-dark' : 'vs'}
value={activeTab === 'compose' ? safeContent : safeEnvContent}
onChange={(value) => {
if (!isEditing) return; // Prevent changes in view mode
if (activeTab === 'compose') {
setContent(value || '');
} else {
setEnvContent(value || '');
}
}}
options={{
minimap: { enabled: false },
fontSize: 14,
padding: { top: 10 },
scrollBeyondLastLine: false,
readOnly: !isEditing,
}}
/>
)}
{isFileLoading && (
<div className="flex items-center justify-center h-full text-muted-foreground">
Loading...
</div>
)}
</div>
</Card>
</div>
</ErrorBoundary>
) : (
<HomeDashboard />
)}
</div>
</div>
{/* Delete Confirmation Dialog */}
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Delete Stack</DialogTitle>
<DialogDescription>
Are you sure you want to delete {stackToDelete}? This action cannot be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>Cancel</Button>
<Button variant="destructive" onClick={deleteStack}>Delete</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Bash Exec Modal */}
{selectedContainer && (
<BashExecModal
isOpen={bashModalOpen}
onClose={closeBashModal}
containerId={selectedContainer.id}
containerName={selectedContainer.name}
/>
)}
</div>
);
}
+47
View File
@@ -0,0 +1,47 @@
import React, { Component } from 'react';
import type { ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false,
error: null,
};
public static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('ErrorBoundary caught an error:', error, errorInfo);
}
public render() {
if (this.state.hasError) {
return (
<div className="p-6 bg-red-900/20 border border-red-500 rounded-xl m-4">
<h2 className="text-lg font-bold text-red-500 mb-2">Something went wrong</h2>
<p className="text-red-300 text-sm mb-4">{this.state.error?.message || 'Unknown error'}</p>
<button
className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600"
onClick={() => this.setState({ hasError: false, error: null })}
>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
+289
View File
@@ -0,0 +1,289 @@
import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './ui/dialog';
import { Activity, Square, PauseCircle, ArrowRight, Plus, Cpu, HardDrive, MemoryStick } from 'lucide-react';
import { apiFetch } from '@/lib/api';
interface Stats {
active: number;
exited: number;
total: number;
inactive: number;
}
interface SystemStats {
cpu: {
usage: string;
cores: number;
};
memory: {
total: number;
used: number;
free: number;
usagePercent: string;
};
disk: {
fs: string;
mount: string;
total: number;
used: number;
free: number;
usagePercent: string;
} | null;
}
function formatBytes(bytes: number): string {
const gb = bytes / (1024 * 1024 * 1024);
if (gb >= 1024) {
return (gb / 1024).toFixed(1) + ' TB';
}
return gb.toFixed(1) + ' GB';
}
export default function HomeDashboard() {
const [dockerRunInput, setDockerRunInput] = useState('');
const [isConverting, setIsConverting] = useState(false);
const [convertedYaml, setConvertedYaml] = useState('');
const [createDialogOpen, setCreateDialogOpen] = useState(false);
const [newStackName, setNewStackName] = useState('');
const [stats, setStats] = useState<Stats>({ active: 0, exited: 0, total: 0, inactive: 0 });
const [systemStats, setSystemStats] = useState<SystemStats | null>(null);
// Fetch stats from backend
useEffect(() => {
const fetchStats = async () => {
try {
const res = await apiFetch('/stats');
const data = await res.json();
setStats(data);
} catch (error) {
console.error('Failed to fetch stats:', error);
}
};
fetchStats();
const interval = setInterval(fetchStats, 5000);
return () => clearInterval(interval);
}, []);
// Fetch system stats from backend
useEffect(() => {
const fetchSystemStats = async () => {
try {
const res = await apiFetch('/system/stats');
const data = await res.json();
setSystemStats(data);
} catch (error) {
console.error('Failed to fetch system stats:', error);
}
};
fetchSystemStats();
const interval = setInterval(fetchSystemStats, 5000);
return () => clearInterval(interval);
}, []);
const handleConvert = async () => {
if (!dockerRunInput.trim()) return;
setIsConverting(true);
try {
const response = await apiFetch('/convert', {
method: 'POST',
body: JSON.stringify({ dockerRun: dockerRunInput }),
});
if (!response.ok) throw new Error('Conversion failed');
const data = await response.json();
setConvertedYaml(data.yaml);
} catch (error) {
console.error('Conversion error:', error);
alert('Failed to convert docker run command');
} finally {
setIsConverting(false);
}
};
const handleCreateStack = async () => {
if (!newStackName.trim() || !convertedYaml) return;
const filename = newStackName.endsWith('.yml') ? newStackName : newStackName + '.yml';
try {
// Create the stack
const createResponse = await apiFetch('/stacks', {
method: 'POST',
body: JSON.stringify({ filename }),
});
if (!createResponse.ok) throw new Error('Failed to create stack');
// Save the converted YAML content
const saveResponse = await apiFetch(`/stacks/${filename}`, {
method: 'PUT',
body: JSON.stringify({ content: convertedYaml }),
});
if (!saveResponse.ok) throw new Error('Failed to save stack content');
setCreateDialogOpen(false);
setNewStackName('');
setConvertedYaml('');
setDockerRunInput('');
window.location.reload(); // Refresh to show new stack
} catch (error) {
console.error('Failed to create stack:', error);
alert('Failed to create stack');
}
};
const handleUseConvertedYaml = () => {
setCreateDialogOpen(true);
};
return (
<div className="flex-1 p-6 space-y-6">
{/* Container Stats Row */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Active Containers</CardTitle>
<Activity className="h-4 w-4 text-green-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-green-500">{stats.active}</div>
<p className="text-xs text-muted-foreground mt-1">Currently running</p>
</CardContent>
</Card>
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Exited Containers</CardTitle>
<Square className="h-4 w-4 text-red-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-red-500">{stats.exited}</div>
<p className="text-xs text-muted-foreground mt-1">Stopped or crashed</p>
</CardContent>
</Card>
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Inactive Stacks</CardTitle>
<PauseCircle className="h-4 w-4 text-yellow-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-yellow-500">{Math.max(0, stats.inactive)}</div>
<p className="text-xs text-muted-foreground mt-1">Not deployed</p>
</CardContent>
</Card>
</div>
{/* Host System Stats Row */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Host CPU</CardTitle>
<Cpu className="h-4 w-4 text-blue-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-blue-500">
{systemStats ? `${systemStats.cpu.usage}%` : '...'}
</div>
<p className="text-xs text-muted-foreground mt-1">
{systemStats ? `${systemStats.cpu.cores} cores` : 'Loading...'}
</p>
</CardContent>
</Card>
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Host RAM</CardTitle>
<MemoryStick className="h-4 w-4 text-purple-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-purple-500">
{systemStats ? `${systemStats.memory.usagePercent}%` : '...'}
</div>
<p className="text-xs text-muted-foreground mt-1">
{systemStats
? `${formatBytes(systemStats.memory.used)} / ${formatBytes(systemStats.memory.total)}`
: 'Loading...'}
</p>
</CardContent>
</Card>
<Card className="rounded-xl border-muted bg-card">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Host Disk</CardTitle>
<HardDrive className="h-4 w-4 text-orange-500" />
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-orange-500">
{systemStats?.disk ? `${systemStats.disk.usagePercent}%` : '...'}
</div>
<p className="text-xs text-muted-foreground mt-1">
{systemStats?.disk
? `${formatBytes(systemStats.disk.used)} / ${formatBytes(systemStats.disk.total)}`
: 'Loading...'}
</p>
</CardContent>
</Card>
</div>
{/* Docker Run Converter */}
<Card className="rounded-xl border-muted bg-card">
<CardHeader>
<CardTitle className="text-lg">Convert Docker Run to Compose</CardTitle>
<p className="text-sm text-muted-foreground">
Paste your <code className="bg-muted px-1 rounded">docker run</code> command below to convert it to a Docker Compose YAML file.
</p>
</CardHeader>
<CardContent className="space-y-4">
<textarea
className="w-full h-32 p-3 rounded-lg border border-muted bg-background text-foreground font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="docker run -d --name my-app -p 8080:80 -e TZ=UTC nginx:latest"
value={dockerRunInput}
onChange={(e) => setDockerRunInput(e.target.value)}
/>
<div className="flex gap-2">
<Button onClick={handleConvert} disabled={isConverting || !dockerRunInput.trim()}>
{isConverting ? 'Converting...' : 'Convert'}
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</div>
{convertedYaml && (
<div className="space-y-3">
<div className="p-3 rounded-lg bg-muted/50 font-mono text-sm whitespace-pre-wrap overflow-auto max-h-64">
{convertedYaml}
</div>
<Button onClick={handleUseConvertedYaml}>
<Plus className="w-4 h-4 mr-2" />
Create Stack from YAML
</Button>
</div>
)}
</CardContent>
</Card>
{/* Create Stack Dialog */}
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Stack</DialogTitle>
</DialogHeader>
<div className="py-4 space-y-4">
<Input
placeholder="Stack name (e.g., myapp)"
value={newStackName}
onChange={(e) => setNewStackName(e.target.value)}
/>
<div className="p-3 rounded-lg bg-muted/50 font-mono text-sm whitespace-pre-wrap overflow-auto max-h-48">
{convertedYaml}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCreateDialogOpen(false)}>Cancel</Button>
<Button onClick={handleCreateStack} disabled={!newStackName.trim()}>Create Stack</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { useState } from 'react';
import { useAuth } from '@/context/AuthContext';
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export function Login({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
const { login } = useAuth();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setIsLoading(true);
const result = await login(username, password);
if (!result.success) {
setError(result.error || 'Login failed');
}
setIsLoading(false);
};
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Sencho</CardTitle>
<CardDescription>
Enter your credentials to access the dashboard
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
type="text"
placeholder="admin"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{error && (
<div className="text-sm text-red-500 text-center">
{error}
</div>
)}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Logging in...' : 'Login'}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
+132
View File
@@ -0,0 +1,132 @@
import { useState } from 'react';
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface SetupProps {
onComplete: () => void;
}
export function Setup({
onComplete,
className,
...props
}: SetupProps & React.ComponentPropsWithoutRef<"div">) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
// Client-side validation
if (password !== confirmPassword) {
setError('Passwords do not match');
return;
}
if (username.length < 3) {
setError('Username must be at least 3 characters');
return;
}
if (password.length < 6) {
setError('Password must be at least 6 characters');
return;
}
setIsLoading(true);
try {
const response = await fetch('/api/auth/setup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ username, password, confirmPassword }),
});
const data = await response.json();
if (response.ok && data.success) {
onComplete();
} else {
setError(data.error || 'Setup failed');
}
} catch {
setError('Network error. Please try again.');
} finally {
setIsLoading(false);
}
};
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Welcome to Sencho</CardTitle>
<CardDescription>
Create your admin account to get started
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
type="text"
placeholder="admin"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="confirmPassword">Confirm Password</Label>
<Input
id="confirmPassword"
type="password"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
</div>
{error && (
<div className="text-sm text-red-500 text-center">
{error}
</div>
)}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? 'Setting up...' : 'Complete Setup'}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
+136
View File
@@ -0,0 +1,136 @@
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { useEffect, useRef } from 'react';
import '@xterm/xterm/css/xterm.css';
export default function TerminalComponent() {
const terminalRef = useRef<HTMLDivElement>(null);
const terminalInstance = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const wsRef = useRef<WebSocket | null>(null);
useEffect(() => {
if (!terminalRef.current) {
console.error('Terminal ref not ready');
return;
}
// Clean up any existing terminal
if (terminalInstance.current) {
try {
terminalInstance.current.dispose();
} catch {
// Ignore dispose errors
}
}
if (wsRef.current) {
try {
wsRef.current.close();
} catch {
// Ignore close errors
}
}
let mounted = true;
const initTerminal = () => {
if (!mounted || !terminalRef.current) return;
try {
const term = new Terminal({
cursorBlink: true,
convertEol: true,
theme: {
background: '#000000',
foreground: '#ffffff',
cursor: '#ffffff',
},
fontFamily: 'Consolas, Monaco, monospace',
fontSize: 13,
});
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
fitAddonRef.current = fitAddon;
term.open(terminalRef.current);
terminalInstance.current = term;
// Fit after DOM paint using requestAnimationFrame
requestAnimationFrame(() => {
if (!mounted || !fitAddonRef.current || !terminalRef.current) return;
try {
fitAddonRef.current.fit();
} catch (err) {
console.error('Error fitting terminal:', err);
}
});
const ws = new WebSocket('ws://localhost:3000');
wsRef.current = ws;
ws.onopen = () => {
if (mounted) {
ws.send(JSON.stringify({ action: 'connectTerminal' }));
}
};
ws.onmessage = (event) => {
if (mounted && terminalInstance.current) {
terminalInstance.current.write(event.data);
}
};
ws.onerror = (err) => {
console.error('WebSocket error:', err);
};
} catch (err) {
console.error('Error initializing terminal:', err);
}
};
// Initialize terminal after a small delay to ensure container is rendered
const timeoutId = setTimeout(initTerminal, 50);
// Attach ResizeObserver to the terminal's parent container
const resizeObserver = new ResizeObserver(() => {
if (fitAddonRef.current && terminalRef.current && mounted) {
try {
fitAddonRef.current.fit();
} catch {
// Ignore fit errors during resize
}
}
});
if (terminalRef.current.parentElement) {
resizeObserver.observe(terminalRef.current.parentElement);
}
return () => {
mounted = false;
clearTimeout(timeoutId);
resizeObserver.disconnect();
if (wsRef.current) {
try {
wsRef.current.close();
} catch {
// Ignore close errors
}
wsRef.current = null;
}
if (terminalInstance.current) {
try {
terminalInstance.current.dispose();
} catch {
// Ignore dispose errors
}
terminalInstance.current = null;
}
fitAddonRef.current = null;
};
}, []);
return <div ref={terminalRef} className="h-full w-full" />;
}
+68
View File
@@ -0,0 +1,68 @@
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
export function LoginForm({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Login</CardTitle>
<CardDescription>
Enter your email below to login to your account
</CardDescription>
</CardHeader>
<CardContent>
<form>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="m@example.com"
required
/>
</div>
<div className="grid gap-2">
<div className="flex items-center">
<Label htmlFor="password">Password</Label>
<a
href="#"
className="ml-auto inline-block text-sm underline-offset-4 hover:underline"
>
Forgot your password?
</a>
</div>
<Input id="password" type="password" required />
</div>
<Button type="submit" className="w-full">
Login
</Button>
<Button variant="outline" className="w-full">
Login with Google
</Button>
</div>
<div className="mt-4 text-center text-sm">
Don&apos;t have an account?{" "}
<a href="#" className="underline underline-offset-4">
Sign up
</a>
</div>
</form>
</CardContent>
</Card>
</div>
)
}
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+57
View File
@@ -0,0 +1,57 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
+76
View File
@@ -0,0 +1,76 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+122
View File
@@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
@@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }
+55
View File
@@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
+114
View File
@@ -0,0 +1,114 @@
import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
type AppStatus = 'loading' | 'needsSetup' | 'notAuthenticated' | 'authenticated';
interface AuthContextType {
appStatus: AppStatus;
isAuthenticated: boolean;
needsSetup: boolean;
login: (username: string, password: string) => Promise<{ success: boolean; error?: string }>;
logout: () => Promise<void>;
completeSetup: () => void;
checkAuth: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [appStatus, setAppStatus] = useState<AppStatus>('loading');
const checkAuth = async () => {
try {
// First check if setup is needed
const statusResponse = await fetch('/api/auth/status', {
credentials: 'include',
});
const statusData = await statusResponse.json();
if (statusData.needsSetup) {
setAppStatus('needsSetup');
return;
}
// Then check if already authenticated
const authResponse = await fetch('/api/auth/check', {
credentials: 'include',
});
if (authResponse.ok) {
setAppStatus('authenticated');
} else {
setAppStatus('notAuthenticated');
}
} catch {
setAppStatus('notAuthenticated');
}
};
useEffect(() => {
checkAuth();
}, []);
const login = async (username: string, password: string): Promise<{ success: boolean; error?: string }> => {
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (response.ok && data.success) {
setAppStatus('authenticated');
return { success: true };
} else {
return { success: false, error: data.error || 'Login failed' };
}
} catch {
return { success: false, error: 'Network error. Please try again.' };
}
};
const logout = async () => {
try {
await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include',
});
} catch (error) {
console.error('Logout error:', error);
} finally {
setAppStatus('notAuthenticated');
}
};
const completeSetup = () => {
setAppStatus('authenticated');
};
return (
<AuthContext.Provider value={{
appStatus,
isAuthenticated: appStatus === 'authenticated',
needsSetup: appStatus === 'needsSetup',
login,
logout,
completeSetup,
checkAuth
}}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
+87
View File
@@ -0,0 +1,87 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--radius: 0.5rem;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 14.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 14.9%;
--muted-foreground: 0 0% 63.9%;
--accent: 0 0% 14.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body, #root {
height: 100%;
width: 100%;
overflow: hidden;
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
line-height: 1.5;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* xterm.js styles */
.xterm {
padding: 0;
}
+27
View File
@@ -0,0 +1,27 @@
const API_BASE = '/api';
export async function apiFetch(
endpoint: string,
options: RequestInit = {}
): Promise<Response> {
const url = `${API_BASE}${endpoint}`;
const defaultOptions: RequestInit = {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...options.headers,
},
};
const response = await fetch(url, { ...defaultOptions, ...options });
if (response.status === 401) {
// Clear auth state and redirect to login
window.location.href = '/';
throw new Error('Unauthorized');
}
return response;
}
export { API_BASE };
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+60
View File
@@ -0,0 +1,60 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
darkMode: ['class', "class"],
theme: {
extend: {
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))'
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))'
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))'
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))'
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))'
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))'
},
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))'
},
chart: {
'1': 'hsl(var(--chart-1))',
'2': 'hsl(var(--chart-2))',
'3': 'hsl(var(--chart-3))',
'4': 'hsl(var(--chart-4))',
'5': 'hsl(var(--chart-5))'
}
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)'
}
}
},
plugins: [require("tailwindcss-animate")],
}
+33
View File
@@ -0,0 +1,33 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
}
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})