feat: Implement a comprehensive Docker Compose stack management UI with file editing, deployment, container monitoring, and interactive bash access.

This commit is contained in:
SaelixCode
2026-02-24 19:48:56 -05:00
parent d5fac02da3
commit cdecbba59a
6 changed files with 703 additions and 131 deletions
+134 -62
View File
@@ -1,7 +1,6 @@
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 { useEffect, useRef, useState, useCallback } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from './ui/dialog';
import { Terminal as TerminalIcon } from 'lucide-react';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';
@@ -18,11 +17,72 @@ export default function BashExecModal({ isOpen, onClose, containerId, containerN
const xtermRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const initTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [isConnected, setIsConnected] = useState(false);
const cleanup = useCallback(() => {
if (initTimeoutRef.current) {
clearTimeout(initTimeoutRef.current);
initTimeoutRef.current = null;
}
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (xtermRef.current) {
xtermRef.current.dispose();
xtermRef.current = null;
}
fitAddonRef.current = null;
setIsConnected(false);
}, []);
useEffect(() => {
if (isOpen && terminalRef.current && !xtermRef.current) {
// Initialize xterm.js
if (!isOpen) {
cleanup();
return;
}
let attempts = 0;
const maxAttempts = 15; // up to 1.5 seconds
const checkAndInit = () => {
// If already initialized, stop.
if (xtermRef.current) return;
const container = terminalRef.current;
// If Radix Dialog Portal hasn't rendered the DOM node yet, poll.
if (!container) {
if (attempts++ < maxAttempts) {
initTimeoutRef.current = setTimeout(checkAndInit, 100);
} else {
console.error('BashExecModal: terminalRef never populated.');
}
return;
}
// DOM exists. Now verify it has actual layout size from CSS.
// During initial Radix zoom-in animation, it might be 0x0.
const rect = container.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) {
if (attempts++ < maxAttempts) {
initTimeoutRef.current = setTimeout(checkAndInit, 100);
} else {
console.warn('BashExecModal: terminal container has zero dimensions after 1.5s, forcing init anyway.');
initTerminal(container);
}
return;
}
// Node exists and has layout — safe to initialize xterm!
initTerminal(container);
};
// Start polling
initTimeoutRef.current = setTimeout(checkAndInit, 50);
function initTerminal(containerEl: HTMLDivElement) {
const term = new Terminal({
theme: {
background: '#1e1e1e',
@@ -38,30 +98,55 @@ export default function BashExecModal({ isOpen, onClose, containerId, containerN
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
term.open(terminalRef.current);
setTimeout(() => {
fitAddon.fit();
}, 100);
term.open(containerEl);
xtermRef.current = term;
fitAddonRef.current = fitAddon;
// Fit after xterm has rendered its canvas
requestAnimationFrame(() => {
try {
fitAddon.fit();
} catch {
// Ignore fit errors during initial render
}
});
// Connect to WebSocket for bash exec
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const ws = new WebSocket(`${wsProtocol}//${window.location.host}`);
wsRef.current = ws;
ws.onopen = () => {
// Kick off the exec session
ws.send(JSON.stringify({
action: 'execContainer',
containerId: containerId,
}));
setIsConnected(true);
// Focus so user can type immediately
term.focus();
// Fit again now that everything is settled, then send dimensions
setTimeout(() => {
try {
fitAddon.fit();
} catch {
// Ignore
}
if (ws.readyState === WebSocket.OPEN && term.rows > 0 && term.cols > 0) {
ws.send(JSON.stringify({
type: 'resize',
rows: term.rows,
cols: term.cols,
}));
}
}, 100);
};
ws.onmessage = (event) => {
// Write raw text directly to terminal
// Raw text from container → write directly to xterm
term.write(event.data);
};
@@ -75,73 +160,57 @@ export default function BashExecModal({ isOpen, onClose, containerId, containerN
setIsConnected(false);
};
// Handle user input
// Handle user input — JSON up
term.onData((data) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
action: 'input',
type: 'input',
data: data,
}));
}
});
// Handle resize
const handleResize = () => {
if (fitAddonRef.current) {
// ResizeObserver for modal/window resize events
const resizeObserver = new ResizeObserver(() => {
if (!fitAddonRef.current || !wsRef.current) return;
try {
fitAddonRef.current.fit();
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
action: 'resize',
cols: term.cols,
rows: term.rows,
}));
}
} catch {
return;
}
};
if (wsRef.current.readyState === WebSocket.OPEN && term.rows > 0 && term.cols > 0) {
wsRef.current.send(JSON.stringify({
type: 'resize',
rows: term.rows,
cols: term.cols,
}));
}
});
window.addEventListener('resize', handleResize);
resizeObserver.observe(containerEl);
return () => {
window.removeEventListener('resize', handleResize);
};
// Store observer cleanup on the container element for later
(containerEl as any).__resizeObserver = resizeObserver;
}
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);
// Clean up ResizeObserver
if (terminalRef.current && (terminalRef.current as any).__resizeObserver) {
(terminalRef.current as any).__resizeObserver.disconnect();
delete (terminalRef.current as any).__resizeObserver;
}
};
}, [isOpen, containerId]);
}, [isOpen, containerId, cleanup]);
const handleClose = () => {
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
if (xtermRef.current) {
xtermRef.current.dispose();
xtermRef.current = null;
}
setIsConnected(false);
cleanup();
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">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<TerminalIcon className="w-5 h-5" />
Bash: {containerName}
@@ -151,15 +220,18 @@ export default function BashExecModal({ isOpen, onClose, containerId, containerN
</span>
)}
</DialogTitle>
<Button variant="ghost" size="sm" onClick={handleClose}>
<X className="w-4 h-4" />
</Button>
<DialogDescription className="hidden">
Interactive bash terminal session for {containerName}
</DialogDescription>
</DialogHeader>
<div
ref={terminalRef}
className="flex-1 rounded-lg overflow-hidden bg-[#1e1e1e] p-2"
style={{ minHeight: '500px' }}
/>
{/* Styling wrapper — padding and rounded corners go here */}
<div className="flex-1 rounded-lg bg-[#1e1e1e] p-1 min-h-0" style={{ overflow: 'hidden' }}>
{/* Clean xterm container — NO padding, NO overflow-hidden, explicit dimensions */}
<div
ref={terminalRef}
style={{ width: '100%', height: '100%' }}
/>
</div>
</DialogContent>
</Dialog>
);
+37 -4
View File
@@ -4,13 +4,14 @@ import TerminalComponent from './Terminal';
import ErrorBoundary from './ErrorBoundary';
import HomeDashboard from './HomeDashboard';
import BashExecModal from './BashExecModal';
import MaintenanceModal from './MaintenanceModal';
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, Terminal, Sun, Moon, RotateCw, CloudDownload, Pencil, X, Search, Home, LogOut } from 'lucide-react';
import { Plus, Trash2, Play, Square, Save, Terminal, Sun, Moon, RotateCw, CloudDownload, Pencil, X, Search, Home, LogOut, Brush } from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
import { apiFetch } from '@/lib/api';
@@ -53,6 +54,9 @@ export default function EditorLayout() {
const [bashModalOpen, setBashModalOpen] = useState(false);
const [selectedContainer, setSelectedContainer] = useState<{ id: string; name: string } | null>(null);
// Maintenance modal state
const [maintenanceModalOpen, setMaintenanceModalOpen] = useState(false);
// Theme toggle effect
useEffect(() => {
const html = document.documentElement;
@@ -337,6 +341,7 @@ export default function EditorLayout() {
const deleteStack = async () => {
if (!stackToDelete) return;
setIsActionLoading(true);
try {
const response = await apiFetch(`/stacks/${stackToDelete}`, {
method: 'DELETE',
@@ -358,6 +363,8 @@ export default function EditorLayout() {
} catch (error) {
console.error('Failed to delete stack:', error);
alert('Failed to delete stack');
} finally {
setIsActionLoading(false);
}
};
@@ -370,13 +377,22 @@ export default function EditorLayout() {
method: 'POST',
body: JSON.stringify({ stackName }),
});
if (!response.ok) throw new Error('Failed to create stack');
if (!response.ok) {
if (response.status === 409) {
throw new Error('Stack already exists');
} else if (response.status === 400) {
throw new Error('Invalid stack name (use alphanumeric characters and hyphens only)');
}
throw new Error('Failed to create stack');
}
setCreateDialogOpen(false);
setNewStackName('');
await refreshStacks();
} catch (error) {
// Auto-load the new stack in the editor pane
await loadFile(stackName);
} catch (error: any) {
console.error('Failed to create stack:', error);
alert('Failed to create stack');
alert(error.message || 'Failed to create stack');
}
};
@@ -532,6 +548,17 @@ export default function EditorLayout() {
<Terminal className="w-4 h-4 mr-2" />
Console
</Button>
{/* System Janitor (Maintenance) Toggle */}
<Button
variant="outline"
size="sm"
className="rounded-lg"
onClick={() => setMaintenanceModalOpen(true)}
title="System Maintenance"
>
<Brush className="w-4 h-4 mr-2" />
Janitor
</Button>
{/* Theme Toggle */}
<Button
variant="outline"
@@ -761,6 +788,12 @@ export default function EditorLayout() {
containerName={selectedContainer.name}
/>
)}
{/* Maintenance Modal */}
<MaintenanceModal
isOpen={maintenanceModalOpen}
onClose={() => setMaintenanceModalOpen(false)}
/>
</div>
);
}
@@ -0,0 +1,293 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from './ui/dialog';
import { Tabs, TabsList, TabsTrigger, TabsContent } from './ui/tabs';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { apiFetch } from '@/lib/api';
import { Trash2, AlertTriangle, MonitorX, PackageMinus, Network } from 'lucide-react';
interface MaintenanceModalProps {
isOpen: boolean;
onClose: () => void;
}
interface ContainerInfo {
Id: string;
Names: string[];
State: string;
Status: string;
Image: string;
}
export default function MaintenanceModal({ isOpen, onClose }: MaintenanceModalProps) {
const [activeTab, setActiveTab] = useState<'ghosts' | 'system'>('ghosts');
// Ghost Hunter state
const [orphans, setOrphans] = useState<Record<string, ContainerInfo[]>>({});
const [isLoadingOrphans, setIsLoadingOrphans] = useState(false);
const [selectedOrphans, setSelectedOrphans] = useState<string[]>([]);
const [isPurging, setIsPurging] = useState(false);
// System Cleanup state
const [isPruning, setIsPruning] = useState(false);
const [pruneResult, setPruneResult] = useState<{ message: string; stdout: string; stderr: string } | null>(null);
useEffect(() => {
if (isOpen && activeTab === 'ghosts') {
fetchOrphans();
} else {
setPruneResult(null); // Reset when tab changes
}
}, [isOpen, activeTab]);
const fetchOrphans = async () => {
setIsLoadingOrphans(true);
try {
const res = await apiFetch('/system/orphans');
const data = await res.json();
setOrphans(data);
setSelectedOrphans([]);
} catch (error) {
console.error('Failed to fetch orphans:', error);
} finally {
setIsLoadingOrphans(false);
}
};
const toggleOrphanSelection = (containerId: string) => {
setSelectedOrphans(prev =>
prev.includes(containerId)
? prev.filter(id => id !== containerId)
: [...prev, containerId]
);
};
const selectAllOrphans = () => {
const allIds = Object.values(orphans).flat().map(c => c.Id);
if (selectedOrphans.length === allIds.length) {
setSelectedOrphans([]);
} else {
setSelectedOrphans(allIds);
}
};
const purgeSelectedOrphans = async () => {
if (selectedOrphans.length === 0) return;
if (!confirm(`Are you sure you want to forcefully remove ${selectedOrphans.length} ghost container(s) ? `)) {
return;
}
setIsPurging(true);
try {
const res = await apiFetch('/system/prune/orphans', {
method: 'POST',
body: JSON.stringify({ containerIds: selectedOrphans })
});
if (!res.ok) throw new Error('Purge failed');
await fetchOrphans(); // Refresh the list
} catch (error) {
console.error('Failed to purge orphans:', error);
alert('Failed to purge selected containers.');
} finally {
setIsPurging(false);
}
};
const pruneSystem = async (target: 'containers' | 'images' | 'networks') => {
if (!confirm(`Are you sure you want to prune all unused ${target}? This cannot be undone.`)) {
return;
}
setIsPruning(true);
setPruneResult(null);
try {
const res = await apiFetch('/system/prune/system', {
method: 'POST',
body: JSON.stringify({ target })
});
const data = await res.json();
setPruneResult(data);
} catch (error) {
console.error(`Failed to prune ${target}: `, error);
alert(`Failed to prune ${target}.`);
} finally {
setIsPruning(false);
}
};
const totalOrphansCount = Object.values(orphans).flat().length;
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-4xl h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<AlertTriangle className="w-5 h-5 text-yellow-500" />
System Janitor
</DialogTitle>
<DialogDescription>
Clean up orphaned containers and perform generic system maintenance.
</DialogDescription>
</DialogHeader>
<Tabs
value={activeTab}
onValueChange={(val) => setActiveTab(val as 'ghosts' | 'system')}
className="flex-1 flex flex-col min-h-0 mt-4"
>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="ghosts">Ghost Hunter</TabsTrigger>
<TabsTrigger value="system">System Cleanup</TabsTrigger>
</TabsList>
<TabsContent value="ghosts" className="flex-1 overflow-auto flex flex-col mt-4 border rounded-lg p-4 bg-muted/20">
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold flex items-center gap-2">
Detected Orphan Stacks <Badge variant="secondary">{totalOrphansCount}</Badge>
</h3>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={fetchOrphans}
disabled={isLoadingOrphans}
>
Refresh
</Button>
<Button
variant="destructive"
size="sm"
onClick={purgeSelectedOrphans}
disabled={selectedOrphans.length === 0 || isPurging}
>
<Trash2 className="w-4 h-4 mr-2" />
{isPurging ? 'Purging...' : `Purge Selected(${selectedOrphans.length})`}
</Button>
</div>
</div>
{isLoadingOrphans ? (
<div className="flex-1 flex items-center justify-center text-muted-foreground">
Hunting for ghosts...
</div>
) : totalOrphansCount === 0 ? (
<div className="flex-1 flex flex-col items-center justify-center text-muted-foreground">
<MonitorX className="w-12 h-12 mb-2 opacity-50" />
<p>No orphaned containers detected.</p>
<p className="text-xs mt-1">Your system is clean!</p>
</div>
) : (
<div className="flex-1 overflow-y-auto">
<div className="mb-2 flex items-center gap-2 px-2">
<input
type="checkbox"
onChange={selectAllOrphans}
checked={selectedOrphans.length === totalOrphansCount && totalOrphansCount > 0}
className="rounded border-gray-300 focus:ring-primary"
/>
<span className="text-sm font-medium">Select All</span>
</div>
{Object.entries(orphans).map(([project, containers]) => (
<div key={project} className="mb-6 last:mb-0 bg-card rounded-lg border shadow-sm overflow-hidden">
<div className="bg-muted px-4 py-2 border-b font-medium text-sm flex items-center gap-2">
<span className="w-3 h-3 rounded-full bg-red-500/80"></span>
Project: {project}
</div>
<div className="divide-y">
{containers.map(container => (
<div key={container.Id} className="flex items-center gap-4 p-3 hover:bg-muted/50 transition-colors">
<input
type="checkbox"
checked={selectedOrphans.includes(container.Id)}
onChange={() => toggleOrphanSelection(container.Id)}
className="rounded border-gray-300"
/>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-mono text-sm font-semibold truncate">
{container.Names[0]?.replace(/^\//, '') || container.Id.substring(0, 12)}
</span>
<Badge variant={container.State === 'running' ? 'default' : 'secondary'} className="text-[10px] h-4">
{container.State}
</Badge>
</div>
<div className="text-xs text-muted-foreground truncate mt-1">
Image: {container.Image}
</div>
</div>
</div>
))}
</div>
</div>
))}
</div>
)}
</TabsContent>
<TabsContent value="system" className="flex-1 mt-4 p-4 border rounded-lg bg-card">
<h3 className="text-lg font-semibold mb-6">Global Docker Pruning</h3>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
<Button
variant="outline"
className="h-24 flex flex-col items-center justify-center gap-2"
onClick={() => pruneSystem('containers')}
disabled={isPruning}
>
<MonitorX className="w-6 h-6 text-orange-500" />
<div className="text-center">
<div className="font-bold">Prune Containers</div>
<div className="text-xs text-muted-foreground font-normal">Removes all stopped containers</div>
</div>
</Button>
<Button
variant="outline"
className="h-24 flex flex-col items-center justify-center gap-2"
onClick={() => pruneSystem('images')}
disabled={isPruning}
>
<PackageMinus className="w-6 h-6 text-blue-500" />
<div className="text-center">
<div className="font-bold">Prune Images</div>
<div className="text-xs text-muted-foreground font-normal">Removes unused & dangling images</div>
</div>
</Button>
<Button
variant="outline"
className="h-24 flex flex-col items-center justify-center gap-2"
onClick={() => pruneSystem('networks')}
disabled={isPruning}
>
<Network className="w-6 h-6 text-green-500" />
<div className="text-center">
<div className="font-bold">Prune Networks</div>
<div className="text-xs text-muted-foreground font-normal">Removes all unused networks</div>
</div>
</Button>
</div>
{pruneResult && (
<div className="bg-muted p-4 rounded-lg font-mono text-sm overflow-x-auto whitespace-pre-wrap">
<div className="font-bold mb-2">Result:</div>
<div className="text-green-600 dark:text-green-400">{pruneResult.message}</div>
{pruneResult.stdout && <div className="mt-2 text-foreground">{pruneResult.stdout}</div>}
{pruneResult.stderr && <div className="mt-2 text-red-500">{pruneResult.stderr}</div>}
</div>
)}
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
);
}