feat(client): add lazy-loaded xterm terminal, SFTP editor with diff, tunnels UI, and multi-page Systems views
This commit is contained in:
parent
98d36c8288
commit
c4a0df8ef2
13 changed files with 2299 additions and 70 deletions
504
src/client/ts/views/terminal-view.ts
Normal file
504
src/client/ts/views/terminal-view.ts
Normal 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();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue