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, isAiEnabled, registerViewCleanup, type ClientState, type ServerEntry, } from '../state.js'; import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; import { clearTerminalComposition, 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 { 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(); 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 = {}; 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 { if (currentCleanup) { currentCleanup(); currentCleanup = null; } root.replaceChildren(); const q = state.routeQuery ?? {}; const targetServer = q.server ?? q.serverId; 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 (targetServer && q.cwd !== undefined && servers.some((s) => s.config.id === targetServer)) { // 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: targetServer, 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: targetServer === 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, ...(state.safeMode ? [ el( 'p', { class: 'warn-text mono' }, '[SAFE MODE] Read-only terminal view: keyboard input, reconnect, and session creation are locked.', ), ] : []), 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', ); const exportCastBtn = el( 'a', { href: `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=cast`, class: 'btn btn-sm', download: '', }, 'Export .cast', ); const reconnectPtyBtn = el( 'button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action', hidden: !current.exited, }, 'Reconnect Session', ); reconnectPtyBtn.addEventListener('click', async () => { reconnectPtyBtn.disabled = true; try { await apiFetch(`/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/reconnect`, { method: 'POST', body: {}, }); showToast('PTY session reconnected.', 'ok'); await renderTerminalView(root, state, wsClient); } catch (err) { msgEl.className = 'form-msg err-text'; msgEl.textContent = extractErrorMessage(err); showToast(extractErrorMessage(err), 'err'); reconnectPtyBtn.disabled = false; } }); let term: Terminal | null = null; let fitAddon: FitAddon | null = null; let suppressCompositionUntil = 0; 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 aiTermBtn = isAiEnabled(state) ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Helper]') : null; if (aiTermBtn) { aiTermBtn.addEventListener('click', async () => { let scrollbackTail = ''; try { const res = await fetch( `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=plain`, { credentials: 'same-origin' }, ); if (res.ok) { scrollbackTail = (await res.text()).slice(-4000); } } catch { // Ignore export errors } const { openAiAssistantDrawer } = await import('./ai-drawer.js'); await openAiAssistantDrawer({ state, wsClient, surface: 'snippets', title: `AI Terminal Helper (${current.serverId})`, contextText: scrollbackTail, serverId: current.serverId, defaultDraftKind: 'snippet', onInsertTerminalText: (cmd) => { sendPtyInput(cmd.replace(/[\r\n]+/g, ' ')); term?.focus(); }, }); }); } const closeTabBtn = el( 'button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Close Session', ); const applyFontAndFit = () => { if (!term || !fitAddon || !termContainer.isConnected) return; term.options.fontSize = fontSize; term.options.theme = readXtermTheme(); fitAddon.fit(); termContainer.scrollLeft = 0; termContainer.scrollTop = 0; 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 (prevent pointer/mouse focus steal so Android IME does not jump or leave ghosts) const touchBar = el('div', { class: 'touch-keybar', role: 'toolbar', 'aria-label': 'Mobile Terminal Keys' }); const keepTermFocus = (btn: HTMLButtonElement) => { btn.addEventListener('pointerdown', (e) => e.preventDefault()); btn.addEventListener('mousedown', (e) => e.preventDefault()); }; const makeTouchBtn = (label: string, onPress: () => void) => { const btn = el('button', { type: 'button', class: 'touch-key' }, label); keepTermFocus(btn); btn.addEventListener('click', () => { if (term) clearTerminalComposition(term, termContainer); onPress(); term?.focus(); }); return btn; }; const ctrlBtn = el('button', { type: 'button', class: 'touch-key', 'aria-pressed': 'false' }, 'Ctrl'); keepTermFocus(ctrlBtn); ctrlBtn.addEventListener('click', () => { ctrlSticky = !ctrlSticky; ctrlBtn.classList.toggle('active', ctrlSticky); ctrlBtn.setAttribute('aria-pressed', ctrlSticky ? 'true' : 'false'); if (term) clearTerminalComposition(term, termContainer); term?.focus(); }); const altBtn = el('button', { type: 'button', class: 'touch-key', 'aria-pressed': 'false' }, 'Alt'); keepTermFocus(altBtn); altBtn.addEventListener('click', () => { altSticky = !altSticky; altBtn.classList.toggle('active', altSticky); altBtn.setAttribute('aria-pressed', altSticky ? 'true' : 'false'); if (term) clearTerminalComposition(term, termContainer); term?.focus(); }); touchBar.append( makeTouchBtn('Esc', () => sendPtyInput('\x1b')), makeTouchBtn('Tab', () => sendPtyInput('\t')), ctrlBtn, altBtn, makeTouchBtn('Ctrl+C', () => sendPtyInput('\x03')), makeTouchBtn('Ctrl+X', () => sendPtyInput('\x18')), 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, ...(aiTermBtn ? [aiTermBtn] : []), reconnectPtyBtn, exportPlainBtn, exportAnsiBtn, exportCastBtn, 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 consumeStickyText = (text: string): boolean => { if (!ctrlSticky && !altSticky) return false; if (!text) return false; const ch = text.slice(-1); suppressCompositionUntil = Date.now() + 140; sendPtyInput(ch); if (term) { clearTerminalComposition(term, termContainer); window.setTimeout(() => { if (term && termContainer.isConnected) clearTerminalComposition(term, termContainer); }, 20); } return true; }; const ta = term.textarea; const textareaCleanups: Array<() => void> = []; if (ta) { const addTa = ( evt: K, handler: (e: HTMLElementEventMap[K]) => void, ) => { ta.addEventListener(evt, handler as EventListener, true); textareaCleanups.push(() => ta.removeEventListener(evt, handler as EventListener, true)); }; addTa('keydown', (ev) => { if ((ctrlSticky || altSticky) && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.key.length === 1) { ev.preventDefault(); ev.stopImmediatePropagation(); consumeStickyText(ev.key); } }); addTa('beforeinput', (ev) => { const ie = ev as InputEvent; if (Date.now() < suppressCompositionUntil) { ev.preventDefault(); ev.stopImmediatePropagation(); return; } if ((ctrlSticky || altSticky) && ie.data && consumeStickyText(ie.data)) { ev.preventDefault(); ev.stopImmediatePropagation(); } }); addTa('compositionupdate', (ev) => { const ce = ev as CompositionEvent; if (Date.now() < suppressCompositionUntil) { ev.preventDefault(); ev.stopImmediatePropagation(); clearTerminalComposition(term!, termContainer); return; } if ((ctrlSticky || altSticky) && ce.data && consumeStickyText(ce.data)) { ev.preventDefault(); ev.stopImmediatePropagation(); } }); addTa('input', (ev) => { if (Date.now() < suppressCompositionUntil) { ev.preventDefault(); ev.stopImmediatePropagation(); clearTerminalComposition(term!, termContainer); } }); addTa('compositionend', (ev) => { if (Date.now() < suppressCompositionUntil) { ev.preventDefault(); ev.stopImmediatePropagation(); clearTerminalComposition(term!, termContainer); return; } window.setTimeout(() => { const comp = termContainer.querySelector('.composition-view'); if (comp && !comp.textContent) comp.classList.remove('active'); }, 30); }); } const dataDisposable = term.onData((data) => { if (Date.now() < suppressCompositionUntil) return; sendPtyInput(data); }); const resizeDisposable = term.onResize(({ cols, rows }) => { wsClient.send({ type: 'pty:resize', sessionId: current.sessionId, cols, rows, }); }); let fitRaf: number | null = null; let lastFitCols = term.cols; let lastFitRows = term.rows; const scheduleFit = () => { if (fitRaf !== null) return; fitRaf = window.requestAnimationFrame(() => { fitRaf = null; if (!term || !fitAddon || !termContainer.isConnected) return; fitAddon.fit(); termContainer.scrollLeft = 0; termContainer.scrollTop = 0; if (term.cols !== lastFitCols || term.rows !== lastFitRows) { lastFitCols = term.cols; lastFitRows = term.rows; wsClient.send({ type: 'pty:resize', sessionId: current.sessionId, cols: term.cols, rows: term.rows, }); } }); }; window.addEventListener('resize', scheduleFit); window.visualViewport?.addEventListener('resize', scheduleFit); const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null; ro?.observe(termContainer); const themeObs = typeof MutationObserver !== 'undefined' ? new MutationObserver(() => { if (term) term.options.theme = readXtermTheme(); }) : null; themeObs?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); 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) { current.exited = true; reconnectPtyBtn.hidden = false; 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; } }); const unsubChannel = wsClient.subscribe([`pty:${current.sessionId}`]); let cleaned = false; const disposeTerminalView = () => { if (cleaned) return; cleaned = true; currentCleanup = null; if (fitRaf !== null) window.cancelAnimationFrame(fitRaf); unsubChannel(); unsubFrame(); themeObs?.disconnect(); ro?.disconnect(); window.removeEventListener('resize', scheduleFit); window.visualViewport?.removeEventListener('resize', scheduleFit); for (const fn of textareaCleanups) fn(); dataDisposable.dispose(); resizeDisposable.dispose(); term?.dispose(); }; currentCleanup = disposeTerminalView; registerViewCleanup(disposeTerminalView); wsClient.send({ type: 'pty:resize', sessionId: current.sessionId, cols: term.cols, rows: term.rows, }); term.focus(); }