Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat: interactive Terminal tab on /terminal over agent PTY (S8.3)

Juan Denisb2e4ac7c60bf
diff --git a/backend/app/sockets.py b/backend/app/sockets.py
index ae703ca2..d1efae85 100644
--- a/backend/app/sockets.py
+++ b/backend/app/sockets.py
@@ -117,6 +117,46 @@ def broadcast_metrics():
time.sleep(2) # Update every 2 seconds
[email protected]('subscribe_terminal')
+def handle_subscribe_terminal(data):
+ """Join the stream room for a remote terminal session (agent PTY output).
+
+ The agent streams base64 PTY output on channel `terminal:<session_id>`;
+ the agent gateway rebroadcasts it as `server_stream` events into the room
+ `server_<server_id>_terminal:<session_id>`. This handler is what lets a
+ browser join that room — without it the output never reaches the UI.
+ Session ids are unguessable uuids minted by TerminalService for the
+ authenticated creator.
+ """
+ from app.services.terminal_service import TerminalService
+
+ session_id = (data or {}).get('session_id')
+ if not session_id:
+ emit('error', {'message': 'session_id required'})
+ return
+
+ session = TerminalService.get_session(session_id)
+ if not session:
+ emit('error', {'message': 'Unknown terminal session'})
+ return
+
+ join_room(f"server_{session['server_id']}_terminal:{session_id}")
+ emit('subscribed', {'channel': f'terminal:{session_id}'})
+
+
[email protected]('unsubscribe_terminal')
+def handle_unsubscribe_terminal(data):
+ """Leave a terminal session's stream room."""
+ from app.services.terminal_service import TerminalService
+
+ session_id = (data or {}).get('session_id')
+ if not session_id:
+ return
+ session = TerminalService.get_session(session_id)
+ if session:
+ leave_room(f"server_{session['server_id']}_terminal:{session_id}")
+
+
@socketio.on('subscribe_logs')
def handle_subscribe_logs(data):
"""Subscribe to real-time log streaming."""
diff --git a/docs/REDESIGN_MAP.md b/docs/REDESIGN_MAP.md
index 0fa92fe3..c9dd74f9 100644
--- a/docs/REDESIGN_MAP.md
+++ b/docs/REDESIGN_MAP.md
@@ -275,12 +275,16 @@ payload — §5). Remaining in this group:
layout is a deliberate improvement — keep.
- Backend (§5): metrics-history AreaCharts, real template catalog (live has 1 hardcoded template).
-### 8.3 Terminal / Console — biggest IA gap
-Demo is a **unified console**: persistent left target rail (server/WP/DBs/containers/services groups, glowing
-status dots) + Terminal⇄Logs mode toggle + **interactive terminal pane**. Live is 4 separate tabs with a
-modal TargetPicker and **no terminal shell at all** on this page. Pass-1 restyled the log wells, but the
-shape of the page is not the demo's. Needs the §5 unified-targets endpoint to be fully real; an interim
-win: host the existing SSH/xterm console (RemoteTerminal is built but unmounted) as a Terminal tab.
+### 8.3 Terminal / Console — ✅ **Terminal tab shipped 2026-06-11** (rail IA still §5)
+The Terminal page now has an actual terminal: a **Terminal tab** (`.term-shell`: demo-style target rail with
+glowing status dots + xterm pane) hosting `RemoteTerminal` against paired agent servers. This required fixing
+the whole output path — `RemoteTerminal` referenced a **nonexistent `SocketContext`** and listened for a
+`terminal:<sid>` event nothing emits; rewired to `services/socket.js` + new `subscribe_terminal` /
+`unsubscribe_terminal` handlers in `sockets.py` that join the browser into the gateway's
+`server_<id>_terminal:<session>` stream room (agent PTY → gateway `server_stream` → xterm), with
+reconnect re-subscribe. 'logs' stays the default landing (shell needs a connected agent; panel-host PTY =
+§5 gap, local is rejected by TerminalService). Still §5: the unified all-targets rail (WP/DBs/containers
+groups) + live non-file log streaming.
### 8.4 WordPress — ✅ **JSX-only parts done 2026-06-11**
- List: **bulk-select shipped** — header + per-row checkboxes, accent `is-selected` rows, bulkbar with
diff --git a/frontend/src/components/RemoteTerminal.jsx b/frontend/src/components/RemoteTerminal.jsx
index 1cc97f9f..e344bb2c 100644
--- a/frontend/src/components/RemoteTerminal.jsx
+++ b/frontend/src/components/RemoteTerminal.jsx
@@ -4,7 +4,7 @@ import { FitAddon } from '@xterm/addon-fit';
import { WebLinksAddon } from '@xterm/addon-web-links';
import '@xterm/xterm/css/xterm.css';
import api from '../services/api';
-import { useSocket } from '../contexts/SocketContext';
+import socketService from '../services/socket';
/**
* RemoteTerminal - Interactive terminal component for remote server access
@@ -21,7 +21,6 @@ export default function RemoteTerminal({ serverId, onClose }) {
const [connected, setConnected] = useState(false);
const [error, setError] = useState(null);
const [shellName, setShellName] = useState('');
- const { socket, connected: socketConnected } = useSocket();
// Initialize terminal
useEffect(() => {
@@ -158,36 +157,45 @@ export default function RemoteTerminal({ serverId, onClose }) {
};
}, [sessionId, connected]);
- // Listen for terminal output via WebSocket
+ // Listen for terminal output: the agent streams base64 PTY data on the
+ // channel `terminal:<session_id>`, which the agent gateway rebroadcasts as
+ // `server_stream` events into a room we join via subscribe_terminal.
useEffect(() => {
- if (!socket || !sessionId || !socketConnected) return;
+ if (!sessionId) return;
- const channel = `terminal:${sessionId}`;
+ socketService.connect();
+ const sock = socketService.socket;
+ if (!sock) return;
- const handleTerminalData = (data) => {
- if (!terminalInstance.current) return;
+ const channel = `terminal:${sessionId}`;
- if (data.type === 'output' && data.data) {
- // Decode base64 output
+ const handleStream = (msg) => {
+ if (msg?.channel !== channel || !terminalInstance.current) return;
+ const payload = msg.data || {};
+ if (payload.type === 'output' && payload.data) {
try {
- const decoded = atob(data.data);
- terminalInstance.current.write(decoded);
+ terminalInstance.current.write(atob(payload.data));
} catch (err) {
console.error('Failed to decode terminal output:', err);
}
- } else if (data.type === 'closed') {
+ } else if (payload.type === 'closed') {
terminalInstance.current.writeln('');
terminalInstance.current.writeln('\x1b[1;33mSession closed\x1b[0m');
setConnected(false);
}
};
+ const subscribe = () => sock.emit('subscribe_terminal', { session_id: sessionId });
- socket.on(channel, handleTerminalData);
+ sock.on('server_stream', handleStream);
+ sock.on('connect', subscribe); // re-join the room after reconnects
+ if (sock.connected) subscribe();
return () => {
- socket.off(channel, handleTerminalData);
+ sock.off('server_stream', handleStream);
+ sock.off('connect', subscribe);
+ if (sock.connected) sock.emit('unsubscribe_terminal', { session_id: sessionId });
};
- }, [socket, sessionId, socketConnected]);
+ }, [sessionId]);
// Cleanup session on unmount
useEffect(() => {
diff --git a/frontend/src/pages/Terminal.jsx b/frontend/src/pages/Terminal.jsx
index dab84a9c..94fb3cb1 100644
--- a/frontend/src/pages/Terminal.jsx
+++ b/frontend/src/pages/Terminal.jsx
@@ -5,6 +5,7 @@ import { useToast } from '../contexts/ToastContext';
import { useConfirm } from '../hooks/useConfirm';
import { ConfirmDialog } from '../components/ConfirmDialog';
import TargetPicker from '../components/TargetPicker';
+import RemoteTerminal from '../components/RemoteTerminal';
import LogFileList from '../components/log-viewer/LogFileList';
import LogToolbar from '../components/log-viewer/LogToolbar';
import LogContent from '../components/log-viewer/LogContent';
@@ -13,9 +14,14 @@ import { Pill } from '../components/ds';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
-import { FileText, Clock, AlertCircle, Search, X, RefreshCw, AlertTriangle, Activity, Play, Square, RotateCw } from 'lucide-react';
+import {
+ FileText, Clock, AlertCircle, Search, X, RefreshCw, AlertTriangle, Activity,
+ Play, Square, RotateCw, Terminal as TerminalIcon,
+} from 'lucide-react';
-const VALID_TABS = ['logs', 'journal', 'processes', 'services'];
+// 'logs' stays first so the default landing keeps working on installs with no
+// paired agents (the interactive shell needs a connected agent).
+const VALID_TABS = ['logs', 'journal', 'processes', 'services', 'terminal'];
const Terminal = () => {
const [activeTab, setActiveTab] = useTabParam('/terminal', VALID_TABS);
@@ -31,6 +37,10 @@ const Terminal = () => {
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList>
+ <TabsTrigger value="terminal">
+ <TerminalIcon size={16} />
+ Terminal
+ </TabsTrigger>
<TabsTrigger value="logs">
<svg viewBox="0 0 24 24" width="16" height="16">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
@@ -67,6 +77,9 @@ const Terminal = () => {
</TabsList>
<div className="tab-content">
+ <TabsContent value="terminal">
+ <TerminalShellTab />
+ </TabsContent>
<TabsContent value="logs">
<LogFilesTab />
</TabsContent>
@@ -85,6 +98,77 @@ const Terminal = () => {
);
};
+// ─── Interactive shell tab (demo console: target rail + terminal pane) ───
+// Sessions run over the ServerKit agent (terminal:create); the panel host has
+// no PTY endpoint (§5 gap), so the rail lists paired agent servers only.
+const TerminalShellTab = () => {
+ const [servers, setServers] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [selectedId, setSelectedId] = useState(null);
+
+ useEffect(() => {
+ (async () => {
+ try {
+ const data = await api.getServers();
+ const list = Array.isArray(data) ? data : (data.servers || []);
+ setServers(list);
+ const firstOnline = list.find(s => s.status === 'online');
+ if (firstOnline) setSelectedId(firstOnline.id);
+ } catch (err) {
+ console.error('Failed to load servers:', err);
+ } finally {
+ setLoading(false);
+ }
+ })();
+ }, []);
+
+ const selected = servers.find(s => s.id === selectedId) || null;
+ const anyOnline = servers.some(s => s.status === 'online');
+
+ return (
+ <div className="term-shell">
+ <aside className="term-shell__rail" aria-label="Terminal targets">
+ <div className="term-shell__grp">Agent servers</div>
+ {loading && <div className="term-shell__hint">Loading servers…</div>}
+ {!loading && servers.length === 0 && (
+ <div className="term-shell__hint">No servers paired yet.</div>
+ )}
+ {servers.map(s => {
+ const online = s.status === 'online';
+ return (
+ <button
+ key={s.id}
+ type="button"
+ className={`term-shell__row ${s.id === selectedId ? 'is-active' : ''}`}
+ onClick={() => setSelectedId(s.id)}
+ disabled={!online}
+ title={online ? `Open a shell on ${s.name}` : `${s.name || s.id} is ${s.status || 'offline'}`}
+ >
+ <span className={`term-shell__dot ${online ? 'is-on' : ''}`} />
+ <span className="term-shell__name">{s.name || s.hostname || s.id}</span>
+ {s.ip_address && <span className="term-shell__sub">{s.ip_address}</span>}
+ </button>
+ );
+ })}
+ </aside>
+ <div className="term-shell__main">
+ {selected ? (
+ <RemoteTerminal key={selected.id} serverId={selected.id} onClose={() => setSelectedId(null)} />
+ ) : (
+ <div className="term-shell__empty">
+ <TerminalIcon size={26} />
+ <p>
+ {anyOnline
+ ? 'Pick a server on the left to open a shell.'
+ : 'Interactive shells run over the ServerKit agent. Pair a server (Servers → Add Server) and it will show up here.'}
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
const LOG_PREFS = {
showLineNumbers: 'serverkit-logs-line-numbers',
wrapLines: 'serverkit-logs-wrap',
diff --git a/frontend/src/styles/pages/_terminal.scss b/frontend/src/styles/pages/_terminal.scss
index b5e4cee6..534e183d 100644
--- a/frontend/src/styles/pages/_terminal.scss
+++ b/frontend/src/styles/pages/_terminal.scss
@@ -51,6 +51,127 @@ $lk-default: #646b7a;
.lv-page .spinning { animation: spin 1s linear infinite; }
@keyframes spin { from { transform: rotate(0); } to { transform: rotate(360deg); } }
+// ─── Interactive terminal tab (demo console: target rail + shell pane) ───
+.term-shell {
+ display: grid;
+ grid-template-columns: 260px 1fr;
+ height: calc(100vh - 220px);
+ min-height: 420px;
+ background: var(--surface);
+ border: 1px solid var(--border-soft);
+ border-radius: var(--radius-lg);
+ overflow: hidden;
+
+ &__rail {
+ border-right: 1px solid var(--border-soft);
+ overflow-y: auto;
+ padding: $space-2 0;
+ }
+
+ &__grp {
+ padding: 8px 14px 6px;
+ font-family: var(--mono);
+ font-size: 10px;
+ font-weight: $font-weight-semibold;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--text-ghost);
+ }
+
+ &__hint {
+ padding: 8px 14px;
+ font-size: 12.5px;
+ color: var(--text-faint);
+ }
+
+ &__row {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ width: 100%;
+ padding: 8px 14px;
+ background: transparent;
+ border: none;
+ text-align: left;
+ font-size: 13px;
+ color: var(--text-dim);
+ cursor: pointer;
+ transition: background 0.12s, color 0.12s;
+
+ &:hover:not(:disabled) { background: var(--surface-2); color: var(--text); }
+ &.is-active { background: var(--accent-bg); color: var(--accent-bright); }
+ &:disabled { opacity: 0.5; cursor: not-allowed; }
+ }
+
+ &__dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--text-ghost);
+ flex-shrink: 0;
+
+ &.is-on { background: var(--green); box-shadow: 0 0 5px var(--green); }
+ }
+
+ &__name {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__sub {
+ font-family: var(--mono);
+ font-size: 10.5px;
+ color: var(--text-ghost);
+ }
+
+ &__main {
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ padding: $space-3;
+
+ // RemoteTerminal brings drawer chrome — flatten it inside the frame
+ .remote-terminal-container {
+ flex: 1;
+ min-width: 0;
+ box-shadow: none;
+ }
+ }
+
+ &__empty {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: $space-3;
+ padding: $space-6;
+ color: var(--text-faint);
+ text-align: center;
+
+ p {
+ max-width: 400px;
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.6;
+ }
+ }
+
+ @media (max-width: $breakpoint-md) {
+ grid-template-columns: 1fr;
+ grid-template-rows: auto 1fr;
+
+ &__rail {
+ border-right: none;
+ border-bottom: 1px solid var(--border-soft);
+ max-height: 180px;
+ }
+ }
+}
+
// ─── Console frame (panes joined by 1px borders) ──────
.lv-page {
display: flex;