feat(client): add lazy-loaded xterm terminal, SFTP editor with diff, tunnels UI, and multi-page Systems views

This commit is contained in:
tyuXX 2026-11-26 21:46:10 +00:00
parent 98d36c8288
commit c4a0df8ef2
13 changed files with 2299 additions and 70 deletions

View file

@ -32,6 +32,15 @@ async function buildClient(): Promise<void> {
});
}
const xtermCssSrc = path.resolve('node_modules/@xterm/xterm/css/xterm.css');
if (fs.existsSync(xtermCssSrc)) {
await esbuild.build({
entryPoints: [xtermCssSrc],
minify: true,
outfile: path.join(outDir, 'xterm.css'),
});
}
for (const asset of ['index.html', 'manifest.json', 'icon.svg']) {
fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset));
}
@ -50,6 +59,15 @@ async function buildClient(): Promise<void> {
);
}
const chunksDir = path.join(outDir, 'chunks');
if (fs.existsSync(chunksDir)) {
for (const chunk of fs.readdirSync(chunksDir).sort()) {
const cBuf = fs.readFileSync(path.join(chunksDir, chunk));
const cGz = zlib.gzipSync(cBuf, { level: 9 });
console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B`);
}
}
console.log(
`Core bundle total: raw=${totalRaw}B (${(totalRaw / 1024).toFixed(2)} KB), gzip=${totalGzip}B (${(totalGzip / 1024).toFixed(2)} KB / 50.00 KB budget)`,
);

View file

@ -503,6 +503,93 @@ dialog::backdrop {
margin-bottom: 12px;
}
.subtab-bar {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 12px;
}
.breadcrumbs {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
}
.chip-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
align-items: center;
}
.term-shell {
border: 1px solid var(--border);
background: var(--bg);
contain: layout style paint;
}
.term-viewport {
width: 100%;
height: 55dvh;
min-height: 260px;
padding: 4px;
background: var(--bg);
}
.touch-keybar {
display: flex;
flex-wrap: wrap;
gap: 4px;
padding: 6px;
border-top: 1px solid var(--border);
background: var(--bg-elevated);
}
.touch-key {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 34px;
min-width: 38px;
padding: 4px 8px;
border: 1px solid var(--border);
background: var(--bg);
color: var(--fg);
font-family: inherit;
font-size: 12px;
cursor: pointer;
}
.touch-key:hover {
border-color: var(--accent);
}
.touch-key.active {
border-color: var(--accent);
color: var(--accent);
font-weight: 700;
}
.stream-log {
max-height: 45dvh;
overflow: auto;
background: var(--bg);
border: 1px solid var(--border);
padding: 8px;
margin: 8px 0;
white-space: pre-wrap;
word-break: break-word;
font-size: 12px;
contain: layout style paint;
}
.sftp-dropzone.drag-over {
border-color: var(--accent);
background: var(--bg-elevated);
}
@media (max-width: 767px) {
.metric-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
@ -515,6 +602,7 @@ dialog::backdrop {
.btn,
.nav-link,
.touch-key,
input,
select {
min-height: 44px;

View file

@ -37,6 +37,53 @@ function readCookie(name: string): string | null {
return null;
}
function buildSecurityHeaders(hasJsonBody: boolean): Record<string, string> {
const headers: Record<string, string> = {};
if (hasJsonBody) {
headers['Content-Type'] = 'application/json';
}
const csrf = readCookie('gcoord_csrf') ?? inMemoryCsrf;
if (csrf) headers['X-CSRF-Token'] = csrf;
if (safeModeActive) headers['X-GCoord-Safe-Mode'] = '1';
return headers;
}
export async function apiUploadBinary<T = unknown>(
url: string,
body: Blob | ArrayBuffer,
): Promise<T> {
const headers = buildSecurityHeaders(false);
headers['Content-Type'] = 'application/octet-stream';
const res = await fetch(url, {
method: 'POST',
headers,
body,
credentials: 'same-origin',
});
const text = await res.text();
let data: Record<string, unknown> = {};
if (text) {
try {
data = JSON.parse(text) as Record<string, unknown>;
} catch {
data = { message: text };
}
}
if (!res.ok) {
const err = new Error(
typeof data.message === 'string'
? data.message
: typeof data.error === 'string'
? data.error
: `HTTP ${res.status}`,
) as ApiError;
err.status = res.status;
err.code = typeof data.error === 'string' ? data.error : undefined;
throw err;
}
return data as T;
}
export async function apiFetch<T = unknown>(
url: string,
options: {
@ -46,17 +93,12 @@ export async function apiFetch<T = unknown>(
} = {},
): Promise<T> {
const method = (options.method ?? 'GET').toUpperCase();
const headers: Record<string, string> = {};
if (options.body !== undefined) {
headers['Content-Type'] = 'application/json';
}
if (method !== 'GET' && method !== 'HEAD') {
const csrf = readCookie('gcoord_csrf') ?? inMemoryCsrf;
if (csrf) headers['X-CSRF-Token'] = csrf;
if (safeModeActive) headers['X-GCoord-Safe-Mode'] = '1';
}
const headers =
method !== 'GET' && method !== 'HEAD'
? buildSecurityHeaders(options.body !== undefined)
: options.body !== undefined
? { 'Content-Type': 'application/json' }
: {};
const res = await fetch(url, {
method,

View file

@ -57,14 +57,36 @@ const state: ClientState = {
overview: null,
};
function parseRouteFromHash(): { route: RouteId; serverId?: string } {
function parseRouteFromHash(): {
route: RouteId;
serverId?: string;
segments: string[];
query: Record<string, string>;
} {
const raw = window.location.hash.replace(/^#/, '');
if (raw.startsWith('server/')) {
const serverId = decodeURIComponent(raw.slice('server/'.length));
if (serverId) return { route: 'server-detail', serverId };
const qIdx = raw.indexOf('?');
const pathPart = qIdx >= 0 ? raw.slice(0, qIdx) : raw;
const queryPart = qIdx >= 0 ? raw.slice(qIdx + 1) : '';
const query: Record<string, string> = {};
if (queryPart) {
for (const [k, v] of new URLSearchParams(queryPart)) {
query[k] = v;
}
const route = raw as RouteId;
return VALID_ROUTES.has(route) ? { route } : { route: 'dashboard' };
}
const segs = pathPart
.split('/')
.filter(Boolean)
.map((s) => decodeURIComponent(s));
if (segs[0] === 'server' && segs[1]) {
return { route: 'server-detail', serverId: segs[1], segments: segs.slice(1), query };
}
const candidate = (segs[0] ?? 'dashboard') as RouteId;
if (VALID_ROUTES.has(candidate)) {
return { route: candidate, segments: segs.slice(1), query };
}
return { route: 'dashboard', segments: [], query };
}
function updateTopBarUi(): void {
@ -186,7 +208,23 @@ async function renderCurrentView(): Promise<void> {
return;
}
if (route !== 'server-detail') {
if (route === 'terminal') {
const { renderTerminalView } = await import('./views/terminal-view.js');
await renderTerminalView(root, state, wsClient);
return;
}
if (route === 'sftp') {
const { renderSftpView } = await import('./views/sftp-view.js');
await renderSftpView(root, state);
return;
}
if (route === 'systems') {
const { renderSystemsView } = await import('./views/systems-view.js');
await renderSystemsView(root, state, wsClient);
return;
}
if (route === 'workflows' || route === 'alerts') {
renderSectionShell(root, route, state.overview!);
}
}
@ -260,6 +298,8 @@ async function bootstrapApp(): Promise<void> {
const parsed = parseRouteFromHash();
state.route = parsed.route;
state.selectedServerId = parsed.serverId;
state.routeSegments = parsed.segments;
state.routeQuery = parsed.query;
await syncStatusAndRender();
if (state.authenticated) {
wsClient.connect();
@ -362,6 +402,8 @@ document.addEventListener('DOMContentLoaded', () => {
const parsed = parseRouteFromHash();
state.route = parsed.route;
state.selectedServerId = parsed.serverId;
state.routeSegments = parsed.segments;
state.routeQuery = parsed.query;
void renderCurrentView();
});

View file

@ -104,6 +104,8 @@ export interface ClientState {
theme: string;
route: RouteId;
selectedServerId?: string;
routeSegments?: string[];
routeQuery?: Record<string, string>;
overview: ConfigOverview | null;
security?: ClientSecuritySettings;
authRequirements?: ClientAuthRequirements;

View file

@ -435,6 +435,8 @@ export async function renderDashboardView(
'div',
{ class: 'row' },
reconnBtn,
el('a', { href: `#terminal?server=${encodeURIComponent(config.id)}`, class: 'btn btn-sm' }, 'Term'),
el('a', { href: `#sftp?server=${encodeURIComponent(config.id)}`, class: 'btn btn-sm' }, 'SFTP'),
el('a', { href: `#server/${encodeURIComponent(config.id)}`, class: 'btn btn-sm btn-primary' }, 'Inspect / Keys'),
),
),

View file

@ -2,36 +2,11 @@ import { el, type ConfigOverview, type RouteId } from '../state.js';
export function renderSectionShell(
root: HTMLElement,
route: Exclude<RouteId, 'dashboard' | 'server-detail' | 'config' | 'vault' | 'settings'>,
route: 'workflows' | 'alerts',
overview: ConfigOverview,
): void {
root.replaceChildren();
if (route === 'systems') {
const panel = el('section', { class: 'panel' });
panel.append(
el('h1', {}, 'Custom Systems Definitions (/data/config/systems/*.json)'),
el('p', { class: 'muted' }, 'Live SSH discovery, multi-file activeFiles[] overlays, and interactive debug shells activate in Phase 3.'),
);
const grid = el('div', { class: 'grid-3' });
for (const sys of overview.systems) {
const actions = Array.isArray(sys.actions) ? sys.actions : [];
grid.append(
el(
'div',
{ class: 'panel panel-region' },
el('h2', {}, String(sys.name ?? sys.id)),
el('p', { class: 'muted' }, String(sys.description ?? '')),
el('div', { class: 'mono' }, `ID: ${String(sys.id)} | TTL: ${String(sys.cacheTtlSec ?? 45)}s`),
el('div', { class: 'muted' }, `Actions (${actions.length}): ${actions.map((a) => String((a as Record<string, unknown>).id)).join(', ')}`),
),
);
}
panel.append(grid);
root.append(panel);
return;
}
if (route === 'workflows') {
const panel = el('section', { class: 'panel' });
panel.append(
@ -62,7 +37,6 @@ export function renderSectionShell(
return;
}
if (route === 'alerts') {
const panel = el('section', { class: 'panel' });
const rules = overview.alerts.rules ?? [];
const channels = overview.alerts.channels ?? [];
@ -72,17 +46,4 @@ export function renderSectionShell(
el('p', { class: 'muted' }, `Configured in alerts.json: ${rules.length} rules, ${channels.length} channels, ${windows.length} maintenance windows. AlertEngine evaluates live samples starting Phase 4.`),
);
root.append(panel);
return;
}
const label = route === 'terminal' ? 'Persistent PTY Terminal (xterm.js)' : 'SFTP File Manager & Tunnel Proxy';
root.append(
el(
'section',
{ class: 'panel' },
el('h1', {}, label),
el('p', { class: 'muted' }, 'Interactive SSH client, lazy-loaded xterm.js, and SFTP manager activate in Phase 3.'),
el('a', { href: '#dashboard', class: 'btn btn-sm' }, 'Back to Fleet Dashboard'),
),
);
}

View file

@ -9,7 +9,7 @@ import {
type ServerEntry,
} from '../state.js';
type DetailTab = 'metrics' | 'inspector' | 'keys';
type DetailTab = 'metrics' | 'inspector' | 'keys' | 'tunnels';
let activeTab: DetailTab = 'metrics';
let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h';
@ -70,7 +70,7 @@ export async function renderServerDetailView(
const tabsRow = el(
'div',
{ class: 'row', style: 'margin-top:8px' },
...(['metrics', 'inspector', 'keys'] as DetailTab[]).map((t) => {
...(['metrics', 'inspector', 'keys', 'tunnels'] as DetailTab[]).map((t) => {
const b = el(
'button',
{
@ -81,7 +81,9 @@ export async function renderServerDetailView(
? 'Metrics & Probes'
: t === 'inspector'
? 'Server Inspector'
: 'SSH Keys & Rotation',
: t === 'keys'
? 'SSH Keys & Rotation'
: 'Tunnels & Proxy',
);
b.addEventListener('click', () => {
activeTab = t;
@ -89,6 +91,8 @@ export async function renderServerDetailView(
});
return b;
}),
el('a', { href: `#terminal?server=${encodeURIComponent(serverId)}`, class: 'btn btn-sm' }, 'Terminal'),
el('a', { href: `#sftp?server=${encodeURIComponent(serverId)}`, class: 'btn btn-sm' }, 'SFTP'),
el('a', { href: '#config', class: 'btn btn-sm' }, 'Edit JSON'),
);
@ -122,8 +126,11 @@ export async function renderServerDetailView(
await renderMetricsTab(body, serverId);
} else if (activeTab === 'inspector') {
await renderInspectorTab(body, serverId);
} else {
} else if (activeTab === 'keys') {
await renderKeysTab(body, serverId);
} else {
const { renderTunnelsPanel } = await import('./tunnels-panel.js');
await renderTunnelsPanel(body, serverId);
}
}

View file

@ -0,0 +1,507 @@
import { computeLineDiff } from '../../../shared/diff.js';
import { apiFetch, apiUploadBinary } from '../api.js';
import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js';
import { renderTunnelsPanel } from './tunnels-panel.js';
interface SftpEntry {
name: string;
path: string;
type: 'dir' | 'file' | 'symlink' | 'other';
size: number;
mode: number;
permissionsOctal: string;
mtimeMs: number;
}
interface SftpTextPayload {
path: string;
content: string;
sha256: string;
size: number;
mode: number;
}
let activeSubTab: 'files' | 'tunnels' = 'files';
let currentServerId = '';
let currentPath = '';
let activeEdit: SftpTextPayload | null = null;
let activeEditSudo = false;
function fmtFileSize(bytes: number): string {
if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}
function showSftpDiffDialog(
filePath: string,
originalText: string,
nextText: string,
sudo: boolean,
onConfirm: (force: boolean) => Promise<void>,
): void {
const diff = computeLineDiff(originalText, nextText, 'remote', 'edited');
const dialog = document.createElement('dialog');
dialog.className = 'dialog-wide';
dialog.setAttribute('aria-labelledby', 'sftp-diff-title');
const pre = el('pre', { class: 'diff-body mono' });
for (const line of diff.lines) {
const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : '';
const prefix = line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' ';
pre.append(el('div', { class: cls }, `${prefix}${line.text}`));
}
const errEl = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' });
const forceWrap = el('div', { hidden: true });
const cancelBtn = el('button', { type: 'button', class: 'btn', autofocus: true }, 'Cancel');
const writeBtn = el('button', { type: 'button', class: 'btn btn-primary mutating-action' }, 'Confirm Save');
const forceBtn = el('button', { type: 'button', class: 'btn btn-danger mutating-action' }, 'Overwrite Anyway');
cancelBtn.addEventListener('click', () => {
if (dialog.open) dialog.close();
});
const runSave = async (force: boolean) => {
errEl.textContent = '';
try {
await onConfirm(force);
if (dialog.open) dialog.close();
} catch (err) {
const apiErr = err as { code?: string; message?: string };
errEl.textContent = apiErr?.message ?? extractErrorMessage(err);
if (apiErr?.code === 'CONFLICT') {
forceWrap.hidden = false;
}
}
};
writeBtn.addEventListener('click', () => void runSave(false));
forceBtn.addEventListener('click', () => void runSave(true));
forceWrap.append(forceBtn);
dialog.append(
el('div', { class: 'row-between' }, el('h1', { id: 'sftp-diff-title' }, `Pre-Save Diff: ${filePath}${sudo ? ' [SUDO]' : ''}`), cancelBtn),
el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`),
pre,
errEl,
el('div', { class: 'dialog-actions' }, forceWrap, writeBtn),
);
dialog.addEventListener('close', () => dialog.remove());
document.body.append(dialog);
dialog.showModal();
}
export async function renderSftpView(
root: HTMLElement,
state: ClientState,
): Promise<void> {
root.replaceChildren();
const q = state.routeQuery ?? {};
if (q.tab === 'tunnels') activeSubTab = 'tunnels';
else if (q.tab === 'files' || q.edit || q.path) activeSubTab = 'files';
const tabs = el(
'div',
{ class: 'subtab-bar' },
...(['files', 'tunnels'] as const).map((t) => {
const btn = el(
'button',
{ type: 'button', class: `btn btn-sm${activeSubTab === t ? ' btn-primary' : ''}` },
t === 'files' ? 'SFTP File Manager' : 'Port Forwards & Web Proxy',
);
btn.addEventListener('click', () => {
activeSubTab = t;
activeEdit = null;
void renderSftpView(root, state);
});
return btn;
}),
);
root.append(tabs);
if (activeSubTab === 'tunnels') {
const wrap = el('div', { class: 'stack' });
root.append(wrap);
await renderTunnelsPanel(wrap);
return;
}
const serversRes = await apiFetch<{ servers: ServerEntry[] }>('/api/servers');
const servers = serversRes.servers;
if (servers.length === 0) {
root.append(
el('section', { class: 'panel' }, el('p', { class: 'muted' }, 'No servers registered yet.')),
);
return;
}
if (q.server && servers.some((s) => s.config.id === q.server)) {
if (currentServerId !== q.server) currentPath = '';
currentServerId = q.server;
} else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) {
currentServerId = servers[0]!.config.id;
}
if (q.path) currentPath = q.path;
if (q.sudo === '1') activeEditSudo = true;
if (q.edit && currentServerId) {
try {
const loaded = await apiFetch<{ file: SftpTextPayload }>(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/text?path=${encodeURIComponent(q.edit)}&sudo=${activeEditSudo ? '1' : '0'}`,
);
activeEdit = loaded.file;
currentPath = loaded.file.path.slice(0, loaded.file.path.lastIndexOf('/')) || '/';
} catch {
// Show error below
}
window.location.hash = '#sftp';
return;
}
const serverSel = el('select', { class: 'input-sm', 'aria-label': 'SFTP Server' });
for (const s of servers) {
serverSel.append(
el(
'option',
{ value: s.config.id, selected: s.config.id === currentServerId },
`${s.config.name} (${s.config.id})`,
),
);
}
serverSel.addEventListener('change', () => {
currentServerId = serverSel.value;
currentPath = '';
activeEdit = null;
void renderSftpView(root, state);
});
const pathInput = el('input', { value: currentPath || '~', 'aria-label': 'Remote path' });
const statusMsg = el('p', { class: 'form-msg' });
const goBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Go');
const goPath = (nextPath: string) => {
currentPath = nextPath;
activeEdit = null;
void renderSftpView(root, state);
};
goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~'));
pathInput.addEventListener('keydown', (ev) => {
if (ev.key === 'Enter') {
ev.preventDefault();
goPath(pathInput.value.trim() || '~');
}
});
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh');
refreshBtn.addEventListener('click', () => void renderSftpView(root, state));
const mkdirBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Folder');
const uploadInput = el('input', { type: 'file', multiple: true, style: 'display:none' });
const uploadBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Upload Files');
uploadBtn.addEventListener('click', () => uploadInput.click());
let listing: { path: string; parentPath: string | null; entries: SftpEntry[] } | null = null;
try {
const queryPath = currentPath ? `?path=${encodeURIComponent(currentPath)}` : '';
listing = await apiFetch<{ path: string; parentPath: string | null; entries: SftpEntry[] }>(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/list${queryPath}`,
);
currentPath = listing.path;
pathInput.value = listing.path;
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
const doUploadFiles = async (files: FileList | File[]) => {
const arr = [...files];
if (arr.length === 0) return;
const baseDir = currentPath || '/';
statusMsg.className = 'form-msg';
try {
for (const file of arr) {
statusMsg.textContent = `Uploading ${file.name} (${fmtFileSize(file.size)})...`;
const dest = baseDir === '/' ? `/${file.name}` : `${baseDir}/${file.name}`;
await apiUploadBinary(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/upload?path=${encodeURIComponent(dest)}`,
file,
);
}
await renderSftpView(root, state);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
};
uploadInput.addEventListener('change', () => {
if (uploadInput.files) void doUploadFiles(uploadInput.files);
});
mkdirBtn.addEventListener('click', async () => {
const name = window.prompt('New folder name:');
if (!name || !name.trim()) return;
const target = currentPath === '/' ? `/${name.trim()}` : `${currentPath}/${name.trim()}`;
try {
await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/mkdir`, {
method: 'POST',
body: { path: target },
});
await renderSftpView(root, state);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
});
const termHref = `#terminal?server=${encodeURIComponent(currentServerId)}&cwd=${encodeURIComponent(currentPath || '~')}`;
const archiveAutoHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=auto`;
const archiveGzHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=tar.gz`;
// Clickable breadcrumbs
const crumbs = el('div', { class: 'breadcrumbs', style: 'margin-top:8px' });
const parts = (currentPath || '/').split('/').filter(Boolean);
const rootBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '/');
rootBtn.addEventListener('click', () => goPath('/'));
crumbs.append(rootBtn);
parts.forEach((seg, idx) => {
const segPath = `/${parts.slice(0, idx + 1).join('/')}`;
const b = el('button', { type: 'button', class: 'btn btn-sm' }, seg);
b.addEventListener('click', () => goPath(segPath));
crumbs.append(el('span', { class: 'muted' }, '/'), b);
});
const topPanel = el(
'section',
{ class: 'panel' },
el(
'div',
{ class: 'row-between' },
el('h1', {}, 'SFTP File Manager'),
el('div', { class: 'row' }, serverSel, refreshBtn),
),
el('div', { class: 'row', style: 'margin-top:8px' }, pathInput, goBtn),
crumbs,
el(
'div',
{ class: 'row', style: 'margin-top:8px' },
el('a', { href: termHref, class: 'btn btn-sm' }, 'Open Terminal Here'),
el('a', { href: archiveAutoHref, class: 'btn btn-sm', download: '' }, 'Archive Folder (.tar.zst/.gz)'),
el('a', { href: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'),
mkdirBtn,
uploadBtn,
uploadInput,
),
statusMsg,
);
root.append(topPanel);
// Inline Editor with Pre-Save Diff
if (activeEdit) {
const editBox = el('section', { class: 'panel' });
const textarea = el('textarea', { class: 'code-editor mono' });
textarea.value = activeEdit.content;
const sudoChk = el('input', { type: 'checkbox', checked: activeEditSudo });
sudoChk.addEventListener('change', async () => {
activeEditSudo = sudoChk.checked;
try {
const res = await apiFetch<{ file: SftpTextPayload }>(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/text?path=${encodeURIComponent(activeEdit!.path)}&sudo=${activeEditSudo ? '1' : '0'}`,
);
activeEdit = res.file;
textarea.value = res.file.content;
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
});
const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save');
saveBtn.addEventListener('click', () => {
if (!activeEdit) return;
showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => {
const res = await apiFetch<{ path: string; sha256: string; size: number }>(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/text`,
{
method: 'PUT',
body: {
path: activeEdit!.path,
content: textarea.value,
expectedSha256: activeEdit!.sha256,
force,
sudo: activeEditSudo,
},
},
);
activeEdit = { ...activeEdit!, content: textarea.value, sha256: res.sha256, size: res.size };
statusMsg.className = 'form-msg ok-text';
statusMsg.textContent = `Saved ${res.path} (${res.size} B)`;
});
});
const closeEdBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close Editor');
closeEdBtn.addEventListener('click', () => {
activeEdit = null;
void renderSftpView(root, state);
});
editBox.append(
el(
'div',
{ class: 'row-between', style: 'margin-bottom:8px' },
el('strong', { class: 'mono' }, `Editing ${activeEdit.path} (${activeEdit.size} B)`),
el('div', { class: 'row' }, el('label', { class: 'chk-row' }, sudoChk, 'sudo'), saveBtn, closeEdBtn),
),
textarea,
);
root.append(editBox);
}
if (!listing) return;
const dropPanel = el('section', { class: 'panel sftp-dropzone' });
dropPanel.addEventListener('dragover', (ev) => {
ev.preventDefault();
dropPanel.classList.add('drag-over');
});
dropPanel.addEventListener('dragleave', () => {
dropPanel.classList.remove('drag-over');
});
dropPanel.addEventListener('drop', (ev) => {
ev.preventDefault();
dropPanel.classList.remove('drag-over');
if (ev.dataTransfer?.files) {
void doUploadFiles(ev.dataTransfer.files);
}
});
const tbl = el('table');
tbl.append(
el(
'thead',
{},
el(
'tr',
{},
el('th', {}, 'Name'),
el('th', {}, 'Type'),
el('th', {}, 'Size'),
el('th', {}, 'Mode'),
el('th', {}, 'Modified'),
el('th', {}, 'Actions'),
),
),
);
const tbody = el('tbody');
if (listing.parentPath) {
const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)');
upBtn.addEventListener('click', () => goPath(listing!.parentPath!));
tbody.append(el('tr', {}, el('td', { colspan: 6 }, upBtn)));
}
for (const entry of listing.entries) {
const nameCell = el('td', {});
if (entry.type === 'dir') {
const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`);
openBtn.addEventListener('click', () => goPath(entry.path));
nameCell.append(openBtn);
} else {
nameCell.append(el('span', { class: 'mono' }, entry.name));
}
const actionsRow = el('div', { class: 'row' });
if (entry.type !== 'dir') {
actionsRow.append(
el(
'a',
{
href: `/api/servers/${encodeURIComponent(currentServerId)}/sftp/download?path=${encodeURIComponent(entry.path)}`,
class: 'btn btn-sm',
download: '',
},
'Download',
),
);
const editBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Edit');
editBtn.addEventListener('click', async () => {
try {
const res = await apiFetch<{ file: SftpTextPayload }>(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/text?path=${encodeURIComponent(entry.path)}&sudo=0`,
);
activeEditSudo = false;
activeEdit = res.file;
await renderSftpView(root, state);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
});
actionsRow.append(editBtn);
}
const renBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Rename');
renBtn.addEventListener('click', async () => {
const next = window.prompt('Rename / Move to path:', entry.path);
if (!next || next.trim() === entry.path) return;
await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/rename`, {
method: 'POST',
body: { fromPath: entry.path, toPath: next.trim() },
});
await renderSftpView(root, state);
});
const chmodBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Chmod');
chmodBtn.addEventListener('click', async () => {
const mode = window.prompt('POSIX mode (octal, e.g. 0644):', entry.permissionsOctal);
if (!mode) return;
await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/chmod`, {
method: 'POST',
body: { path: entry.path, mode: mode.trim() },
});
await renderSftpView(root, state);
});
const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
delBtn.addEventListener('click', async () => {
const ok = await confirmDialog(
'dialog-confirm',
entry.type === 'dir'
? `Recursively delete directory "${entry.path}" and all contents?`
: `Delete remote file "${entry.path}"?`,
);
if (!ok) return;
await apiFetch(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/entry?path=${encodeURIComponent(entry.path)}&recursive=${entry.type === 'dir' ? '1' : '0'}`,
{ method: 'DELETE' },
);
await renderSftpView(root, state);
});
actionsRow.append(renBtn, chmodBtn, delBtn);
tbody.append(
el(
'tr',
{},
nameCell,
el('td', { class: 'mono' }, entry.type),
el('td', { class: 'mono' }, entry.type === 'dir' ? '—' : fmtFileSize(entry.size)),
el('td', { class: 'mono' }, entry.permissionsOctal),
el('td', { class: 'mono' }, fmtTime(entry.mtimeMs)),
el('td', {}, actionsRow),
),
);
}
tbl.append(tbody);
dropPanel.append(
el('div', { class: 'muted', style: 'margin-bottom:6px' }, 'Tip: Drag files anywhere onto this table to stream upload via SFTP.'),
el('div', { class: 'table-wrap' }, tbl),
);
root.append(dropPanel);
}

View file

@ -0,0 +1,681 @@
import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js';
import type { MultiplexWsClient } from '../ws-client.js';
interface SystemActionDef {
id: string;
label: string;
scope: 'system' | 'item' | 'subitem';
mode: 'oneshot' | 'stream' | 'interactive';
sudo: boolean;
confirm: boolean;
}
interface SystemParamDef {
name: string;
type: 'string' | 'number' | 'boolean' | 'string[]';
default?: unknown;
required: boolean;
description?: string;
}
interface SystemConfigView {
id: string;
name: string;
description?: string;
cacheTtlSec: number;
params: SystemParamDef[];
actions: SystemActionDef[];
editableFiles: string[];
}
interface DiscoveredItemView {
name: string;
dir?: string;
activeFiles: string[];
selectableFiles: string[];
editableFiles: string[];
status: {
health: 'ok' | 'warn' | 'down' | 'unknown';
subItems: Array<{ name: string; health: 'ok' | 'warn' | 'down' | 'unknown'; stateText?: string }>;
rawSummary: string;
exitCode: number | null;
};
}
interface ServerSnapshotView {
serverId: string;
systemId: string;
fetchedAt: number;
cached: boolean;
error?: string;
params: Record<string, unknown>;
items: DiscoveredItemView[];
systemHealth: 'ok' | 'warn' | 'down' | 'unknown';
}
let unsubStreamListener: (() => void) | null = null;
function healthBadgeClass(h: string): string {
if (h === 'ok') return 'badge badge-ok';
if (h === 'warn') return 'badge badge-warn';
if (h === 'down') return 'badge badge-err';
return 'badge';
}
async function openAttachModal(
system: SystemConfigView,
onSaved: () => Promise<void>,
): Promise<void> {
const serversRes = await apiFetch<{ servers: ServerEntry[] }>('/api/servers');
const dialog = document.createElement('dialog');
dialog.setAttribute('aria-labelledby', 'attach-sys-title');
const closeBtn = el('button', { type: 'button', class: 'btn btn-sm', autofocus: true }, 'Cancel');
closeBtn.addEventListener('click', () => {
if (dialog.open) dialog.close();
});
const serverSel = el('select', { name: 'serverId', required: true });
for (const s of serversRes.servers) {
serverSel.append(el('option', { value: s.config.id }, `${s.config.name} (${s.config.id})`));
}
const paramControls = new Map<string, { def: SystemParamDef; node: HTMLInputElement }>();
const fieldsBox = el('div', { class: 'stack' });
for (const p of system.params) {
const defText = Array.isArray(p.default)
? p.default.join(', ')
: p.default !== undefined
? String(p.default)
: '';
const inp = el('input', {
type: p.type === 'number' ? 'number' : p.type === 'boolean' ? 'checkbox' : 'text',
value: p.type === 'boolean' ? undefined : defText,
checked: p.type === 'boolean' ? Boolean(p.default) : undefined,
placeholder: p.description ?? p.name,
});
paramControls.set(p.name, { def: p, node: inp });
fieldsBox.append(
el('label', {}, `${p.name} (${p.type})${p.description ? ` — ${p.description}` : ''}`),
inp,
);
}
const errEl = el('p', { class: 'form-msg err-text' });
const form = el(
'form',
{ class: 'stack' },
el('label', {}, 'Target Server'),
serverSel,
fieldsBox,
errEl,
el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Attach System')),
);
form.addEventListener('submit', async (ev) => {
ev.preventDefault();
errEl.textContent = '';
if (!serverSel.value) {
errEl.textContent = 'Register a server first.';
return;
}
const paramsPayload: Record<string, unknown> = {};
for (const [name, { def, node }] of paramControls.entries()) {
if (def.type === 'boolean') paramsPayload[name] = node.checked;
else if (def.type === 'number') paramsPayload[name] = Number(node.value || 0);
else if (def.type === 'string[]') {
paramsPayload[name] = node.value
.split(/[\n,]/)
.map((s) => s.trim())
.filter(Boolean);
} else {
paramsPayload[name] = node.value;
}
}
try {
await apiFetch(
`/api/systems/${encodeURIComponent(system.id)}/servers/${encodeURIComponent(serverSel.value)}/attach`,
{ method: 'PUT', body: { params: paramsPayload } },
);
if (dialog.open) dialog.close();
await onSaved();
} catch (err) {
errEl.textContent = extractErrorMessage(err);
}
});
dialog.append(el('h1', { id: 'attach-sys-title' }, `Attach ${system.name}`), form);
dialog.addEventListener('close', () => dialog.remove());
document.body.append(dialog);
dialog.showModal();
}
async function runSystemAction(opts: {
systemId: string;
serverId: string;
action: SystemActionDef;
itemName?: string;
subItemName?: string;
outputHost: HTMLElement;
wsClient: MultiplexWsClient;
onFinished: () => Promise<void>;
}): Promise<void> {
const { action } = opts;
if (action.confirm) {
const target = opts.subItemName ?? opts.itemName ?? opts.serverId;
const ok = await confirmDialog(
'dialog-confirm',
`Run "${action.label}" (${action.mode}) on ${target}?`,
);
if (!ok) return;
}
opts.outputHost.replaceChildren(el('p', { class: 'muted mono' }, `Running ${action.label}...`));
const res = await apiFetch<
| { mode: 'oneshot'; exitCode: number | null; stdout: string; stderr: string; durationMs: number }
| { mode: 'stream'; jobId: string }
| { mode: 'interactive'; session: { sessionId: string } }
>(
`/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`,
{
method: 'POST',
body: {
itemName: opts.itemName,
subItemName: opts.subItemName,
},
},
);
if (res.mode === 'interactive') {
window.location.hash = `#terminal?session=${encodeURIComponent(res.session.sessionId)}`;
return;
}
if (res.mode === 'oneshot') {
opts.outputHost.replaceChildren(
el(
'div',
{ class: 'panel' },
el('div', { class: 'row-between' }, el('strong', {}, `${action.label} finished (exit ${String(res.exitCode)}, ${res.durationMs}ms)`)),
el('pre', { class: 'stream-log mono' }, [res.stdout, res.stderr].filter(Boolean).join('\n') || '(no output)'),
),
);
await opts.onFinished();
return;
}
// Stream mode
if (unsubStreamListener) {
unsubStreamListener();
unsubStreamListener = null;
}
const logPre = el('pre', { class: 'stream-log mono' });
const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Stop Stream');
stopBtn.addEventListener('click', async () => {
await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' });
stopBtn.disabled = true;
});
opts.outputHost.replaceChildren(
el(
'div',
{ class: 'panel' },
el('div', { class: 'row-between' }, el('strong', {}, `Live Stream: ${action.label} (${res.jobId})`), stopBtn),
logPre,
),
);
unsubStreamListener = opts.wsClient.onFrame((frame: ServerWsFrame) => {
if (frame.type !== 'stream:chunk' || frame.jobId !== res.jobId) return;
if (frame.stream === 'meta') {
try {
const meta = JSON.parse(frame.data) as { event?: string; exitCode?: number | null };
if (meta.event === 'exit') {
logPre.textContent += `\n[Exited with code ${String(meta.exitCode)}]\n`;
stopBtn.disabled = true;
void opts.onFinished();
}
} catch {
// Ignore meta parse errors
}
} else {
logPre.textContent += frame.data;
}
logPre.scrollTop = logPre.scrollHeight;
});
opts.wsClient.subscribe([`stream:${res.jobId}`]);
}
export async function renderSystemsView(
root: HTMLElement,
state: ClientState,
wsClient: MultiplexWsClient,
): Promise<void> {
if (unsubStreamListener) {
unsubStreamListener();
unsubStreamListener = null;
}
root.replaceChildren();
const segs = state.routeSegments ?? [];
const forceRefresh = state.routeQuery?.refresh === '1';
// 1. Hub: #systems
if (segs.length === 0) {
const res = await apiFetch<{
systems: Array<{
system: SystemConfigView;
attachedServers: Array<{ serverId: string; serverName: string; params: Record<string, unknown> }>;
}>;
}>('/api/systems');
root.append(
el(
'section',
{ class: 'panel row-between' },
el('div', {}, el('h1', {}, 'Custom Systems Engine'), el('p', { class: 'muted' }, 'Declarative service managers defined in /data/config/systems/*.json')),
el('a', { href: '#config', class: 'btn btn-sm' }, 'Edit System JSONs'),
),
);
const grid = el('div', { class: 'grid-3' });
for (const entry of res.systems) {
const attachBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Attach Server');
attachBtn.addEventListener('click', () => {
void openAttachModal(entry.system, () => renderSystemsView(root, state, wsClient));
});
grid.append(
el(
'article',
{ class: 'panel panel-region' },
el('h2', {}, entry.system.name),
el('p', { class: 'muted' }, entry.system.description ?? ''),
el('div', { class: 'mono' }, `ID: ${entry.system.id} | TTL: ${entry.system.cacheTtlSec}s`),
el('div', { class: 'mono muted' }, `Attached Servers: ${entry.attachedServers.length}`),
el('div', { class: 'muted' }, `Actions: ${entry.system.actions.map((a) => a.label).join(', ')}`),
el(
'div',
{ class: 'row', style: 'margin-top:8px' },
el('a', { href: `#systems/${encodeURIComponent(entry.system.id)}`, class: 'btn btn-sm btn-primary' }, 'Open System →'),
attachBtn,
),
),
);
}
root.append(grid);
return;
}
const systemId = segs[0]!;
const targetServerId = segs[1];
const targetItemName = segs[2];
const data = await apiFetch<{ system: SystemConfigView; snapshots: ServerSnapshotView[] }>(
`/api/systems/${encodeURIComponent(systemId)}?refresh=${forceRefresh ? '1' : '0'}${targetServerId ? `&serverId=${encodeURIComponent(targetServerId)}` : ''}`,
);
const { system, snapshots } = data;
const actionOutputHost = el('div', { class: 'stack' });
// 3. Service Detail: #systems/<systemId>/<serverId>/<item>
if (targetServerId && targetItemName) {
const snap = snapshots.find((s) => s.serverId === targetServerId);
const item = snap?.items.find((i) => i.name === targetItemName);
if (!snap || !item) {
root.append(
el(
'section',
{ class: 'panel' },
el('h1', {}, `Service "${targetItemName}" not found`),
el('a', { href: `#systems/${encodeURIComponent(systemId)}`, class: 'btn btn-sm' }, `← Back to ${system.name}`),
),
);
return;
}
const itemActions = system.actions.filter((a) => a.scope === 'item');
const actionRow = el('div', { class: 'row' });
for (const act of itemActions) {
const btn = el(
'button',
{ type: 'button', class: `btn btn-sm mutating-action${act.id === 'down' ? ' btn-danger' : ''}` },
act.label,
);
btn.addEventListener('click', () => {
void runSystemAction({
systemId,
serverId: targetServerId,
action: act,
itemName: item.name,
outputHost: actionOutputHost,
wsClient,
onFinished: async () => {
state.routeQuery = { ...state.routeQuery, refresh: '1' };
await renderSystemsView(root, state, wsClient);
},
});
});
actionRow.append(btn);
}
root.append(
el(
'section',
{ class: 'panel' },
el(
'div',
{ class: 'row-between' },
el(
'div',
{},
el('h1', {}, `${system.name} / ${item.name}`),
el('div', { class: 'mono muted' }, `${targetServerId}${item.dir ? ` — ${item.dir}` : ''}`),
),
el(
'div',
{ class: 'row' },
el('span', { class: healthBadgeClass(item.status.health) }, `[${item.status.health.toUpperCase()}]`),
el('a', { href: `#systems/${encodeURIComponent(systemId)}`, class: 'btn btn-sm' }, `← ${system.name}`),
),
),
el('div', { style: 'margin-top:8px' }, actionRow),
),
actionOutputHost,
);
// Multi-file activeFiles[] overlay selector
if (item.selectableFiles.length > 0) {
const overlayPanel = el('section', { class: 'panel' });
let orderedSelected = [...item.activeFiles];
const availableExtras = item.selectableFiles.filter((f) => !orderedSelected.includes(f));
let displayList = [...orderedSelected, ...availableExtras];
const filesListEl = el('div', { class: 'stack' });
const overlayMsg = el('p', { class: 'form-msg' });
const redrawFiles = () => {
filesListEl.replaceChildren();
displayList.forEach((fname, idx) => {
const checked = orderedSelected.includes(fname);
const chk = el('input', { type: 'checkbox', checked });
chk.addEventListener('change', () => {
if (chk.checked && !orderedSelected.includes(fname)) {
orderedSelected.push(fname);
} else if (!chk.checked) {
orderedSelected = orderedSelected.filter((x) => x !== fname);
}
});
const upBtn = el('button', { type: 'button', class: 'btn btn-sm', disabled: idx === 0 }, '↑');
upBtn.addEventListener('click', () => {
if (idx <= 0) return;
const prev = displayList[idx - 1]!;
displayList[idx - 1] = fname;
displayList[idx] = prev;
orderedSelected = displayList.filter((f) => orderedSelected.includes(f));
redrawFiles();
});
filesListEl.append(
el('div', { class: 'row-between' }, el('label', { class: 'chk-row mono' }, chk, fname), upBtn),
);
});
};
redrawFiles();
const saveOverlaysBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Save activeFiles[] & Refresh');
saveOverlaysBtn.addEventListener('click', async () => {
if (orderedSelected.length === 0) {
overlayMsg.className = 'form-msg err-text';
overlayMsg.textContent = 'Select at least one config file.';
return;
}
await apiFetch(
`/api/systems/${encodeURIComponent(systemId)}/servers/${encodeURIComponent(targetServerId)}/items/${encodeURIComponent(item.name)}/files`,
{ method: 'PUT', body: { activeFiles: orderedSelected } },
);
state.routeQuery = { ...state.routeQuery, refresh: '1' };
await renderSystemsView(root, state, wsClient);
});
overlayPanel.append(
el('div', { class: 'row-between' }, el('h2', {}, 'Active Overlay Files (activeFiles[])'), saveOverlaysBtn),
filesListEl,
overlayMsg,
);
root.append(overlayPanel);
}
// Sub-items table (containers / processes)
const subActions = system.actions.filter((a) => a.scope === 'subitem');
const subPanel = el('section', { class: 'panel' });
subPanel.append(el('h2', {}, `Sub-Items (${item.status.subItems.length})`));
if (item.status.subItems.length === 0) {
subPanel.append(el('div', { class: 'mono muted' }, item.status.rawSummary || 'No sub-items reported.'));
} else {
const tbl = el('table');
tbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Name'), el('th', {}, 'Health'), el('th', {}, 'State'), el('th', {}, 'Actions'))));
const tbody = el('tbody');
for (const sub of item.status.subItems) {
const sRow = el('div', { class: 'row' });
for (const act of subActions) {
const btn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, act.label);
btn.addEventListener('click', () => {
void runSystemAction({
systemId,
serverId: targetServerId,
action: act,
itemName: item.name,
subItemName: sub.name,
outputHost: actionOutputHost,
wsClient,
onFinished: async () => undefined,
});
});
sRow.append(btn);
}
tbody.append(
el(
'tr',
{},
el('td', { class: 'mono' }, sub.name),
el('td', {}, el('span', { class: healthBadgeClass(sub.health) }, `[${sub.health.toUpperCase()}]`)),
el('td', { class: 'mono' }, sub.stateText ?? '—'),
el('td', {}, sRow),
),
);
}
tbl.append(tbody);
subPanel.append(el('div', { class: 'table-wrap' }, tbl));
}
root.append(subPanel);
// Quick Editable Files via SFTP inline diff editor
if (item.editableFiles.length > 0) {
const editRow = el('div', { class: 'chip-list' });
for (const fPath of item.editableFiles) {
editRow.append(
el(
'a',
{
href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}`,
class: 'btn btn-sm',
},
`Edit ${fPath.split('/').pop()}`,
),
);
}
root.append(el('section', { class: 'panel' }, el('h2', {}, 'Editable Service Files (SFTP Inline Diff)'), editRow));
}
// Per-Service Tasks & Cron workflows matching scope
const scopedWfs = (state.overview?.workflows ?? []).filter((wf) => {
const scope = wf.scope as { serverId?: string; systemId?: string; item?: string } | undefined;
if (!scope) return false;
if (scope.systemId && scope.systemId !== systemId) return false;
if (scope.serverId && scope.serverId !== targetServerId) return false;
if (scope.item && scope.item !== item.name) return false;
return Boolean(scope.systemId);
});
const tasksPanel = el('section', { class: 'panel' });
tasksPanel.append(
el('div', { class: 'row-between' }, el('h2', {}, `Tasks & Cron (${scopedWfs.length})`), el('a', { href: '#config', class: 'btn btn-sm' }, 'Configure Workflows')),
);
if (scopedWfs.length === 0) {
tasksPanel.append(el('p', { class: 'muted' }, 'No scoped workflows yet. Phase 4 adds interactive scheduling and execution here.'));
} else {
for (const wf of scopedWfs) {
tasksPanel.append(el('div', { class: 'mono' }, `• ${String(wf.name ?? wf.id)} (${String(wf.id)})`));
}
}
root.append(tasksPanel);
return;
}
// 2. System Page: #systems/<systemId>
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Force Refresh');
refreshBtn.addEventListener('click', () => {
state.routeQuery = { ...state.routeQuery, refresh: '1' };
void renderSystemsView(root, state, wsClient);
});
const attachBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, '+ Attach Server');
attachBtn.addEventListener('click', () => {
void openAttachModal(system, () => renderSystemsView(root, state, wsClient));
});
root.append(
el(
'section',
{ class: 'panel row-between' },
el('div', {}, el('h1', {}, system.name), el('p', { class: 'muted' }, system.description ?? '')),
el('div', { class: 'row' }, refreshBtn, attachBtn, el('a', { href: '#systems', class: 'btn btn-sm' }, '← All Systems')),
),
actionOutputHost,
);
if (snapshots.length === 0) {
root.append(
el('section', { class: 'panel' }, el('p', { class: 'muted' }, 'No enabled servers have this system attached yet. Click "+ Attach Server" above.')),
);
return;
}
const systemActions = system.actions.filter((a) => a.scope === 'system');
const itemActions = system.actions.filter((a) => a.scope === 'item');
for (const snap of snapshots) {
const srvPanel = el('section', { class: 'panel panel-region' });
const sysBtns = el('div', { class: 'row' });
for (const act of systemActions) {
const btn = el(
'button',
{ type: 'button', class: `btn btn-sm mutating-action${act.confirm ? ' btn-danger' : ''}` },
act.label,
);
btn.addEventListener('click', () => {
void runSystemAction({
systemId,
serverId: snap.serverId,
action: act,
outputHost: actionOutputHost,
wsClient,
onFinished: async () => {
state.routeQuery = { ...state.routeQuery, refresh: '1' };
await renderSystemsView(root, state, wsClient);
},
});
});
sysBtns.append(btn);
}
const detachBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Detach');
detachBtn.addEventListener('click', async () => {
const ok = await confirmDialog('dialog-confirm', `Detach "${system.name}" from "${snap.serverId}"?`);
if (!ok) return;
await apiFetch(
`/api/systems/${encodeURIComponent(systemId)}/servers/${encodeURIComponent(snap.serverId)}/attach`,
{ method: 'DELETE' },
);
await renderSystemsView(root, state, wsClient);
});
srvPanel.append(
el(
'div',
{ class: 'row-between', style: 'margin-bottom:8px' },
el(
'div',
{},
el('h2', {}, snap.serverId),
el('div', { class: 'mono muted' }, `Updated ${fmtTime(snap.fetchedAt)}${snap.cached ? ' (cached)' : ''}`),
),
el('div', { class: 'row' }, el('span', { class: healthBadgeClass(snap.systemHealth) }, `[${snap.systemHealth.toUpperCase()}]`), sysBtns, detachBtn),
),
);
if (snap.error) {
srvPanel.append(el('p', { class: 'err-text mono' }, snap.error));
} else if (snap.items.length === 0) {
srvPanel.append(el('p', { class: 'muted' }, 'No services discovered for the configured roots/filter.'));
} else {
const tbl = el('table');
tbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Service / Item'), el('th', {}, 'Health'), el('th', {}, 'Active Files / Summary'), el('th', {}, 'Quick Actions'))));
const tbody = el('tbody');
for (const item of snap.items) {
const qRow = el('div', { class: 'row' });
for (const act of itemActions.slice(0, 4)) {
const b = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, act.label);
b.addEventListener('click', () => {
void runSystemAction({
systemId,
serverId: snap.serverId,
action: act,
itemName: item.name,
outputHost: actionOutputHost,
wsClient,
onFinished: async () => {
state.routeQuery = { ...state.routeQuery, refresh: '1' };
await renderSystemsView(root, state, wsClient);
},
});
});
qRow.append(b);
}
qRow.append(
el(
'a',
{
href: `#systems/${encodeURIComponent(systemId)}/${encodeURIComponent(snap.serverId)}/${encodeURIComponent(item.name)}`,
class: 'btn btn-sm btn-primary',
},
'Manage →',
),
);
tbody.append(
el(
'tr',
{},
el('td', {}, el('strong', {}, item.name), item.dir ? el('div', { class: 'mono muted' }, item.dir) : ''),
el('td', {}, el('span', { class: healthBadgeClass(item.status.health) }, `[${item.status.health.toUpperCase()}]`)),
el(
'td',
{ class: 'mono' },
item.activeFiles.length > 0 ? el('div', {}, `files: ${item.activeFiles.join(', ')}`) : '',
el('div', { class: 'muted' }, item.status.rawSummary.slice(0, 120)),
),
el('td', {}, qRow),
),
);
}
tbl.append(tbody);
srvPanel.append(el('div', { class: 'table-wrap' }, tbl));
}
root.append(srvPanel);
}
}

View file

@ -0,0 +1,504 @@
import type { Terminal } from '@xterm/xterm';
import type { FitAddon } from '@xterm/addon-fit';
import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js';
import type { MultiplexWsClient } from '../ws-client.js';
import { createFittedTerminal, ensureXtermCss, readXtermTheme } from './xterm-runtime.js';
interface PtySessionInfo {
sessionId: string;
serverId: string;
title: string;
cwd?: string;
command?: string;
cols: number;
rows: number;
createdAt: number;
lastActivityAt: number;
exited: boolean;
exitCode: number | null;
scrollbackBytes: number;
}
let activeSessionId: string | null = null;
let fontSize = 14;
let ctrlSticky = false;
let altSticky = false;
let currentCleanup: (() => void) | null = null;
function toCtrlSequence(data: string): string {
if (!data || data.length !== 1) return data;
const ch = data.toUpperCase();
const code = ch.charCodeAt(0);
if (code >= 64 && code <= 95) {
return String.fromCharCode(code - 64);
}
return data;
}
function interpolateSnippetCommand(
template: string,
values: Record<string, string>,
): string {
return template.replace(/\{\{inputs\.([A-Za-z0-9_.-]+)\}\}/g, (_m, key: string) => {
const val = values[key] ?? '';
return `'${val.replace(/'/g, "'\\''")}'`;
});
}
function openSnippetsDialog(
state: ClientState,
onSend: (command: string, executeNow: boolean) => void,
): void {
const snips = state.overview?.snippets.snippets ?? [];
const dialog = document.createElement('dialog');
dialog.className = 'dialog-wide';
dialog.setAttribute('aria-labelledby', 'snippets-dlg-title');
const closeBtn = el('button', { type: 'button', class: 'btn btn-sm', autofocus: true }, 'Close');
closeBtn.addEventListener('click', () => {
if (dialog.open) dialog.close();
});
const searchInput = el('input', {
type: 'search',
placeholder: 'Filter snippets by name or tag...',
'aria-label': 'Filter snippets',
});
const listWrap = el('div', { class: 'stack', style: 'max-height:55dvh;overflow:auto;margin-top:8px' });
const renderSnippets = () => {
listWrap.replaceChildren();
const q = searchInput.value.trim().toLowerCase();
const filtered = snips.filter((raw) => {
if (!q) return true;
const name = String(raw.name ?? '').toLowerCase();
const cmd = String(raw.command ?? '').toLowerCase();
const tags = Array.isArray(raw.tags) ? raw.tags.map((t) => String(t).toLowerCase()).join(' ') : '';
return name.includes(q) || cmd.includes(q) || tags.includes(q);
});
if (filtered.length === 0) {
listWrap.append(el('p', { class: 'muted' }, 'No matching snippets in snippets.json.'));
return;
}
for (const raw of filtered) {
const inputs = Array.isArray(raw.inputs)
? (raw.inputs as Array<{ name: string; label?: string; default?: unknown; required?: boolean }>)
: [];
const fieldEls = new Map<string, HTMLInputElement>();
const inputsRow = el('div', { class: 'stack' });
for (const inp of inputs) {
const iEl = el('input', {
placeholder: inp.label ?? inp.name,
value: inp.default !== undefined ? String(inp.default) : '',
});
fieldEls.set(inp.name, iEl);
inputsRow.append(el('label', {}, inp.label ?? inp.name), iEl);
}
const buildCmd = () => {
const vals: Record<string, string> = {};
for (const [k, inputEl] of fieldEls.entries()) {
vals[k] = inputEl.value;
}
return interpolateSnippetCommand(String(raw.command ?? ''), vals);
};
const insertBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Insert');
insertBtn.addEventListener('click', () => {
onSend(buildCmd(), false);
if (dialog.open) dialog.close();
});
const runBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Run');
runBtn.addEventListener('click', async () => {
const cmd = buildCmd();
if (raw.confirm) {
const ok = await confirmDialog('dialog-confirm', `Execute snippet "${String(raw.name)}"?\n${cmd}`);
if (!ok) return;
}
onSend(raw.sudo ? `sudo sh -c '${cmd.replace(/'/g, "'\\''")}'` : cmd, true);
if (dialog.open) dialog.close();
});
listWrap.append(
el(
'div',
{ class: 'panel' },
el(
'div',
{ class: 'row-between' },
el('strong', {}, String(raw.name ?? raw.id)),
el('div', { class: 'row' }, insertBtn, runBtn),
),
el('div', { class: 'mono muted' }, String(raw.command ?? '')),
raw.description ? el('div', { class: 'muted' }, String(raw.description)) : '',
inputs.length > 0 ? inputsRow : '',
),
);
}
};
searchInput.addEventListener('input', renderSnippets);
renderSnippets();
dialog.append(
el('div', { class: 'row-between' }, el('h1', { id: 'snippets-dlg-title' }, 'Command Snippets Drawer'), closeBtn),
searchInput,
listWrap,
);
dialog.addEventListener('close', () => {
dialog.remove();
});
document.body.append(dialog);
dialog.showModal();
}
export async function renderTerminalView(
root: HTMLElement,
state: ClientState,
wsClient: MultiplexWsClient,
): Promise<void> {
if (currentCleanup) {
currentCleanup();
currentCleanup = null;
}
root.replaceChildren();
const q = state.routeQuery ?? {};
const [sessionsRes, serversRes] = await Promise.all([
apiFetch<{ sessions: PtySessionInfo[] }>('/api/terminal/sessions'),
apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
]);
let sessions = sessionsRes.sessions;
const servers = serversRes.servers;
if (q.session && sessions.some((s) => s.sessionId === q.session)) {
activeSessionId = q.session;
} else if (q.server && q.cwd !== undefined && servers.some((s) => s.config.id === q.server)) {
// Open-Terminal-Here shortcut if not disabled by Safe Mode
if (!state.safeMode) {
try {
const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', {
method: 'POST',
body: { serverId: q.server, cwd: q.cwd, cols: 90, rows: 26 },
});
sessions = [created.session, ...sessions];
activeSessionId = created.session.sessionId;
window.location.hash = '#terminal';
return;
} catch {
// Fall back to prefilled launcher below
}
}
}
if (!activeSessionId || !sessions.some((s) => s.sessionId === activeSessionId)) {
activeSessionId = sessions[0]?.sessionId ?? null;
}
const msgEl = el('p', { class: 'form-msg' });
const serverSel = el('select', { class: 'input-sm', 'aria-label': 'Target Server' });
for (const s of servers) {
serverSel.append(
el(
'option',
{ value: s.config.id, selected: q.server === s.config.id },
`${s.config.name} (${s.config.id})`,
),
);
}
const cwdInput = el('input', {
class: 'input-sm',
placeholder: 'Optional startup dir (e.g. ~/Services)',
value: q.cwd ?? '',
'aria-label': 'Startup directory',
});
const openShellBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-primary mutating-action' },
'+ Open Shell',
);
openShellBtn.addEventListener('click', async () => {
if (!serverSel.value) {
msgEl.className = 'form-msg err-text';
msgEl.textContent = 'Register an SSH server first.';
return;
}
msgEl.textContent = 'Opening persistent PTY...';
try {
const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', {
method: 'POST',
body: {
serverId: serverSel.value,
cwd: cwdInput.value.trim() || undefined,
cols: 90,
rows: 26,
},
});
activeSessionId = created.session.sessionId;
await renderTerminalView(root, state, wsClient);
} catch (err) {
msgEl.className = 'form-msg err-text';
msgEl.textContent = extractErrorMessage(err);
}
});
const tabsRow = el('div', { class: 'row', style: 'margin-top:8px' });
for (const sess of sessions) {
const isAct = sess.sessionId === activeSessionId;
const label = `${sess.title}${sess.exited ? ' [EXIT]' : ''}`;
const tabBtn = el(
'button',
{ type: 'button', class: `btn btn-sm${isAct ? ' btn-primary' : ''}` },
label,
);
tabBtn.addEventListener('click', () => {
activeSessionId = sess.sessionId;
void renderTerminalView(root, state, wsClient);
});
tabsRow.append(tabBtn);
}
root.append(
el(
'section',
{ class: 'panel' },
el(
'div',
{ class: 'row-between' },
el('h1', {}, 'Persistent SSH Terminal (xterm.js)'),
el('div', { class: 'row' }, serverSel, cwdInput, openShellBtn),
),
tabsRow,
msgEl,
),
);
const current = sessions.find((s) => s.sessionId === activeSessionId);
if (!current) {
root.append(
el(
'section',
{ class: 'panel' },
el('p', { class: 'muted' }, 'No active PTY sessions. Pick a server above and click "+ Open Shell".'),
),
);
return;
}
// Controls + xterm container
const termContainer = el('div', { class: 'term-viewport' });
const exportPlainBtn = el(
'a',
{
href: `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=plain`,
class: 'btn btn-sm',
download: '',
},
'Export Plain',
);
const exportAnsiBtn = el(
'a',
{
href: `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=ansi`,
class: 'btn btn-sm',
download: '',
},
'Export ANSI',
);
let term: Terminal | null = null;
let fitAddon: FitAddon | null = null;
const sendPtyInput = (raw: string) => {
if (!current || current.exited) return;
let payload = raw;
if (ctrlSticky && payload.length === 1) {
payload = toCtrlSequence(payload);
ctrlSticky = false;
ctrlBtn.classList.remove('active');
ctrlBtn.setAttribute('aria-pressed', 'false');
}
if (altSticky) {
payload = `\x1b${payload}`;
altSticky = false;
altBtn.classList.remove('active');
altBtn.setAttribute('aria-pressed', 'false');
}
wsClient.send({
type: 'pty:input',
sessionId: current.sessionId,
data: payload,
});
};
const fontMinusBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'A-');
const fontPlusBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'A+');
const fitBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Fit');
const snippetsBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Snippets');
const closeTabBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-danger mutating-action' },
'Close Session',
);
const applyFontAndFit = () => {
if (!term || !fitAddon) return;
term.options.fontSize = fontSize;
term.options.theme = readXtermTheme();
fitAddon.fit();
wsClient.send({
type: 'pty:resize',
sessionId: current.sessionId,
cols: term.cols,
rows: term.rows,
});
};
fontMinusBtn.addEventListener('click', () => {
fontSize = Math.max(9, fontSize - 1);
applyFontAndFit();
});
fontPlusBtn.addEventListener('click', () => {
fontSize = Math.min(24, fontSize + 1);
applyFontAndFit();
});
fitBtn.addEventListener('click', applyFontAndFit);
snippetsBtn.addEventListener('click', () => {
openSnippetsDialog(state, (cmd, executeNow) => {
sendPtyInput(executeNow ? `${cmd}\n` : cmd);
term?.focus();
});
});
closeTabBtn.addEventListener('click', async () => {
await apiFetch(`/api/terminal/sessions/${encodeURIComponent(current.sessionId)}`, {
method: 'DELETE',
});
if (activeSessionId === current.sessionId) activeSessionId = null;
await renderTerminalView(root, state, wsClient);
});
// Mobile Touch-Key Bar
const touchBar = el('div', { class: 'touch-keybar', role: 'toolbar', 'aria-label': 'Mobile Terminal Keys' });
const makeTouchBtn = (label: string, onPress: () => void) => {
const btn = el('button', { type: 'button', class: 'touch-key' }, label);
btn.addEventListener('click', () => {
onPress();
term?.focus();
});
return btn;
};
const ctrlBtn = el('button', { type: 'button', class: 'touch-key', 'aria-pressed': 'false' }, 'Ctrl');
ctrlBtn.addEventListener('click', () => {
ctrlSticky = !ctrlSticky;
ctrlBtn.classList.toggle('active', ctrlSticky);
ctrlBtn.setAttribute('aria-pressed', ctrlSticky ? 'true' : 'false');
term?.focus();
});
const altBtn = el('button', { type: 'button', class: 'touch-key', 'aria-pressed': 'false' }, 'Alt');
altBtn.addEventListener('click', () => {
altSticky = !altSticky;
altBtn.classList.toggle('active', altSticky);
altBtn.setAttribute('aria-pressed', altSticky ? 'true' : 'false');
term?.focus();
});
touchBar.append(
makeTouchBtn('Esc', () => sendPtyInput('\x1b')),
makeTouchBtn('Tab', () => sendPtyInput('\t')),
ctrlBtn,
altBtn,
makeTouchBtn('Ctrl+C', () => sendPtyInput('\x03')),
makeTouchBtn('↑', () => sendPtyInput('\x1b[A')),
makeTouchBtn('↓', () => sendPtyInput('\x1b[B')),
makeTouchBtn('←', () => sendPtyInput('\x1b[D')),
makeTouchBtn('→', () => sendPtyInput('\x1b[C')),
makeTouchBtn('|', () => sendPtyInput('|')),
makeTouchBtn('/', () => sendPtyInput('/')),
makeTouchBtn('~', () => sendPtyInput('~')),
makeTouchBtn('-', () => sendPtyInput('-')),
);
root.append(
el(
'section',
{ class: 'panel' },
el(
'div',
{ class: 'row-between', style: 'margin-bottom:8px' },
el(
'div',
{ class: 'mono muted' },
`${current.title} | ${current.cols}x${current.rows} | opened ${fmtTime(current.createdAt)}`,
),
el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, exportPlainBtn, exportAnsiBtn, closeTabBtn),
),
el('div', { class: 'term-shell' }, termContainer, touchBar),
),
);
await ensureXtermCss();
if (!termContainer.isConnected) return;
const created = createFittedTerminal(termContainer, fontSize);
term = created.term;
fitAddon = created.fitAddon;
const dataDisposable = term.onData((data) => {
sendPtyInput(data);
});
const resizeDisposable = term.onResize(({ cols, rows }) => {
wsClient.send({
type: 'pty:resize',
sessionId: current.sessionId,
cols,
rows,
});
});
const onWindowResize = () => {
if (!termContainer.isConnected) return;
fitAddon?.fit();
};
window.addEventListener('resize', onWindowResize);
const unsubFrame = wsClient.onFrame((frame: ServerWsFrame) => {
if (!term || !termContainer.isConnected) return;
if (frame.type === 'pty:output' && frame.sessionId === current.sessionId) {
if (frame.replay) {
term.reset();
}
term.write(frame.data);
} else if (frame.type === 'pty:exit' && frame.sessionId === current.sessionId) {
term.writeln(`\r\n[Session exited with code ${String(frame.exitCode)}]`);
} else if (frame.type === 'error' && frame.code === 'SAFE_MODE_ACTIVE') {
msgEl.className = 'form-msg warn-text';
msgEl.textContent = frame.message;
}
});
currentCleanup = () => {
unsubFrame();
window.removeEventListener('resize', onWindowResize);
dataDisposable.dispose();
resizeDisposable.dispose();
term?.dispose();
};
wsClient.subscribe([`pty:${current.sessionId}`]);
wsClient.send({
type: 'pty:resize',
sessionId: current.sessionId,
cols: term.cols,
rows: term.rows,
});
term.focus();
}

View file

@ -0,0 +1,310 @@
import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, type ServerEntry } from '../state.js';
export interface TunnelViewEntry {
key: string;
serverId: string;
tunnel: {
id: string;
name: string;
mode: 'http-proxy' | 'local-tcp' | 'remote-tcp';
bindHost?: string;
bindPort?: number;
targetHost: string;
targetPort: number;
autoStart: boolean;
};
active: boolean;
localBoundHost?: string;
localBoundPort?: number;
remoteBoundPort?: number;
proxyPath?: string;
activeConnections: number;
totalConnections: number;
bytesIn: number;
bytesOut: number;
startedAt?: number;
lastError?: string;
}
function fmtBytes(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}
export async function renderTunnelsPanel(
root: HTMLElement,
fixedServerId?: string,
): Promise<void> {
root.replaceChildren();
const statusMsg = el('p', { class: 'form-msg' });
const [tunnelsRes, serversRes] = await Promise.all([
apiFetch<{ tunnels: TunnelViewEntry[] }>('/api/tunnels'),
fixedServerId
? Promise.resolve({ servers: [] as ServerEntry[] })
: apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
]);
const tunnels = fixedServerId
? tunnelsRes.tunnels.filter((t) => t.serverId === fixedServerId)
: tunnelsRes.tunnels;
const listPanel = el('section', { class: 'panel' });
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh');
refreshBtn.addEventListener('click', () => {
void renderTunnelsPanel(root, fixedServerId);
});
listPanel.append(
el(
'div',
{ class: 'row-between' },
el('h2', {}, `SSH Tunnels & Authenticated HTTP/WS Proxy (${tunnels.length})`),
refreshBtn,
),
statusMsg,
);
if (tunnels.length === 0) {
listPanel.append(el('p', { class: 'muted' }, 'No tunnels configured yet.'));
} else {
const tbl = el('table');
tbl.append(
el(
'thead',
{},
el(
'tr',
{},
el('th', {}, 'Server / ID'),
el('th', {}, 'Mode'),
el('th', {}, 'Binding / Proxy URL'),
el('th', {}, 'Target'),
el('th', {}, 'Stats'),
el('th', {}, 'Actions'),
),
),
);
const tbody = el('tbody');
for (const item of tunnels) {
const bindInfo = item.proxyPath
? el('a', { href: item.proxyPath, target: '_blank', rel: 'noopener', class: 'mono' }, item.proxyPath)
: item.tunnel.mode === 'remote-tcp'
? el(
'span',
{ class: 'mono' },
item.active && item.remoteBoundPort
? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}`
: `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
)
: el(
'span',
{ class: 'mono' },
item.active && item.localBoundPort
? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}`
: `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
);
const toggleBtn = el(
'button',
{
type: 'button',
class: `btn btn-sm mutating-action${item.active ? '' : ' btn-primary'}`,
},
item.active ? 'Stop' : 'Start',
);
toggleBtn.addEventListener('click', async () => {
statusMsg.textContent = item.active ? 'Stopping tunnel...' : 'Starting tunnel...';
try {
await apiFetch(
`/api/tunnels/${encodeURIComponent(item.serverId)}/${encodeURIComponent(item.tunnel.id)}/${item.active ? 'stop' : 'start'}`,
{ method: 'POST' },
);
await renderTunnelsPanel(root, fixedServerId);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
});
const delBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-danger mutating-action' },
'Delete',
);
delBtn.addEventListener('click', async () => {
const ok = await confirmDialog(
'dialog-confirm',
`Delete tunnel "${item.tunnel.name}" (${item.tunnel.id}) from ${item.serverId}?`,
);
if (!ok) return;
try {
await apiFetch(
`/api/tunnels/${encodeURIComponent(item.serverId)}/${encodeURIComponent(item.tunnel.id)}`,
{ method: 'DELETE' },
);
await renderTunnelsPanel(root, fixedServerId);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
});
tbody.append(
el(
'tr',
{},
el(
'td',
{},
el('strong', {}, item.tunnel.name),
el('div', { class: 'mono muted' }, `${item.serverId} / ${item.tunnel.id}`),
),
el(
'td',
{},
el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()),
item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '',
),
el('td', {}, bindInfo),
el('td', { class: 'mono' }, `${item.tunnel.targetHost}:${item.tunnel.targetPort}`),
el(
'td',
{ class: 'mono' },
`act:${item.activeConnections} tot:${item.totalConnections}`,
el('div', { class: 'muted' }, `↓${fmtBytes(item.bytesIn)} ↑${fmtBytes(item.bytesOut)}`),
item.startedAt ? el('div', { class: 'muted' }, fmtTime(item.startedAt)) : '',
),
el('td', {}, el('div', { class: 'row' }, toggleBtn, delBtn)),
),
);
}
tbl.append(tbody);
listPanel.append(el('div', { class: 'table-wrap' }, tbl));
}
// Add Tunnel Form
const addPanel = el('section', { class: 'panel' });
addPanel.append(
el('h2', {}, 'Add Port Forward / Authenticated Web Proxy'),
el(
'p',
{ class: 'muted' },
'http-proxy binds strictly inside 127.0.0.1 and serves behind GCoordinator auth/CSRF/Safe-Mode at /proxy/<id>/.',
),
);
const form = el('form', { class: 'stack' });
const serverSel = el('select', { name: 'serverId', required: true });
if (fixedServerId) {
serverSel.append(el('option', { value: fixedServerId }, fixedServerId));
} else {
for (const s of serversRes.servers) {
serverSel.append(el('option', { value: s.config.id }, `${s.config.name} (${s.config.id})`));
}
}
const idInput = el('input', { name: 'id', placeholder: 'grafana', required: true });
const nameInput = el('input', { name: 'name', placeholder: 'Grafana Web UI', required: true });
const modeSel = el(
'select',
{ name: 'mode' },
el('option', { value: 'http-proxy' }, 'http-proxy (Zero-Port Web Proxy /proxy/<id>/)'),
el('option', { value: 'local-tcp' }, 'local-tcp (Local Bind -> Target)'),
el('option', { value: 'remote-tcp' }, 'remote-tcp (Remote Bind -R -> Hub/LAN)'),
);
const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true });
const targetPortInput = el('input', {
name: 'targetPort',
type: 'number',
min: 1,
max: 65535,
value: '3000',
required: true,
});
const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp modes)' });
const bindPortInput = el('input', {
name: 'bindPort',
type: 'number',
min: 1,
max: 65535,
placeholder: 'auto (tcp modes)',
});
const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' });
const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true });
const formMsg = el('p', { class: 'form-msg' });
form.append(
el(
'div',
{ class: 'grid-3' },
el('div', {}, el('label', {}, 'Server'), serverSel),
el('div', {}, el('label', {}, 'Tunnel ID'), idInput),
el('div', {}, el('label', {}, 'Display Name'), nameInput),
el('div', {}, el('label', {}, 'Mode'), modeSel),
el('div', {}, el('label', {}, 'Target Host'), targetHostInput),
el('div', {}, el('label', {}, 'Target Port'), targetPortInput),
el('div', {}, el('label', {}, 'Bind Host (TCP only)'), bindHostInput),
el('div', {}, el('label', {}, 'Bind Port (TCP only)'), bindPortInput),
),
el(
'div',
{ class: 'row' },
el('label', { class: 'chk-row' }, autoStartChk, 'Auto-start when Vault unlocks'),
el('label', { class: 'chk-row' }, startNowChk, 'Start immediately'),
),
el('div', { class: 'row' }, el('button', { type: 'submit', class: 'btn btn-primary btn-sm mutating-action' }, 'Save Tunnel')),
formMsg,
);
form.addEventListener('submit', async (ev) => {
ev.preventDefault();
formMsg.textContent = '';
const srvId = serverSel.value;
if (!srvId) {
formMsg.className = 'form-msg err-text';
formMsg.textContent = 'Register a server first.';
return;
}
const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp';
const bindHost = bindHostInput.value.trim() || undefined;
const bindPortVal = bindPortInput.value.trim();
const bindPort = bindPortVal ? Number(bindPortVal) : undefined;
try {
const res = await apiFetch<{ startError?: string }>('/api/tunnels', {
method: 'POST',
body: {
serverId: srvId,
tunnel: {
id: idInput.value.trim(),
name: nameInput.value.trim(),
mode,
targetHost: targetHostInput.value.trim() || '127.0.0.1',
targetPort: Number(targetPortInput.value),
bindHost: mode === 'http-proxy' ? undefined : bindHost,
bindPort: mode === 'http-proxy' ? undefined : bindPort,
autoStart: autoStartChk.checked,
},
start: startNowChk.checked,
},
});
if (res.startError) {
statusMsg.className = 'form-msg warn-text';
statusMsg.textContent = `Saved, but start failed: ${res.startError}`;
}
await renderTunnelsPanel(root, fixedServerId);
} catch (err) {
formMsg.className = 'form-msg err-text';
formMsg.textContent = extractErrorMessage(err);
}
});
addPanel.append(form);
root.append(listPanel, addPanel);
}

View file

@ -0,0 +1,65 @@
import { FitAddon } from '@xterm/addon-fit';
import { Terminal, type ITheme } from '@xterm/xterm';
let cssPromise: Promise<void> | null = null;
export function ensureXtermCss(): Promise<void> {
if (cssPromise) return cssPromise;
const existing = document.querySelector('link[href="/xterm.css"]');
if (existing) {
cssPromise = Promise.resolve();
return cssPromise;
}
cssPromise = new Promise<void>((resolve) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/xterm.css';
const done = () => resolve();
link.addEventListener('load', done, { once: true });
link.addEventListener('error', done, { once: true });
document.head.append(link);
});
return cssPromise;
}
export function readXtermTheme(): ITheme {
const styles = getComputedStyle(document.documentElement);
const get = (name: string, fallback: string) => styles.getPropertyValue(name).trim() || fallback;
const bg = get('--bg', '#0b110d');
const fg = get('--fg', '#d7f7dc');
const accent = get('--accent', '#39ff14');
const ok = get('--ok', '#39ff14');
const warn = get('--warn', '#ffbe3b');
const err = get('--err', '#ff4f5e');
return {
background: bg,
foreground: fg,
cursor: accent,
cursorAccent: bg,
selectionBackground: accent,
green: ok,
yellow: warn,
red: err,
brightGreen: accent,
};
}
export function createFittedTerminal(
container: HTMLElement,
fontSize: number,
): { term: Terminal; fitAddon: FitAddon } {
const term = new Terminal({
cursorBlink: true,
fontFamily: 'ui-monospace, "Cascadia Code", "JetBrains Mono", Menlo, Consolas, monospace',
fontSize,
scrollback: 2500,
theme: readXtermTheme(),
});
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
term.open(container);
fitAddon.fit();
return { term, fitAddon };
}