Files
nas-tools/dashboard/frontend/src/routes/Terminal.svelte
T
Gan, Jimmy c9f06fbbbb
Deploy Dashboard (Dev) / deploy-dev (push) Successful in 2m23s
fix: keep terminal sessions alive
Add WebSocket and SSH keepalives so idle dashboard terminal sessions stay connected across proxies and long-running idle periods.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-06 16:11:43 +08:00

391 lines
16 KiB
Svelte

<script>
import { onMount, onDestroy } from "svelte";
import { VoiceSession } from "../lib/voice.js";
const hosts = [
{ id: "nas", label: "NAS" },
{ id: "vps", label: "VPS" },
{ id: "caddy-vps", label: "Caddy VPS" },
{ id: "mac", label: "Mac" },
{ id: "claude-dev", label: "Claude Dev" },
];
const DARK_THEME = {
background: "#0f172a", foreground: "#e2e8f0", cursor: "#6366f1",
cursorAccent: "#0f172a", selectionBackground: "#334155",
black: "#0f172a", red: "#f43f5e", green: "#10b981",
yellow: "#f59e0b", blue: "#3b82f6", magenta: "#a855f7",
cyan: "#06b6d4", white: "#e2e8f0",
};
const LIGHT_THEME = {
background: "#f8fafc", foreground: "#0f172a", cursor: "#4f46e5",
cursorAccent: "#f8fafc", selectionBackground: "#cbd5e1",
black: "#0f172a", red: "#e11d48", green: "#059669",
yellow: "#d97706", blue: "#2563eb", magenta: "#9333ea",
cyan: "#0891b2", white: "#334155",
};
let tabs = $state([]);
let activeTab = $state(null);
let showMenu = $state(false);
let voiceTick = $state(0);
let isDark = $state(false);
let tabCounter = 0;
const tabData = new Map();
function currentTheme() {
return isDark ? DARK_THEME : LIGHT_THEME;
}
function applyThemeToTerminals() {
const theme = currentTheme();
tabData.forEach((d) => {
d.term?.options && (d.term.options.theme = theme);
});
}
function syncTheme() {
isDark = document.documentElement.classList.contains("dark");
applyThemeToTerminals();
}
const themeObserver = new MutationObserver((mutations) => {
if (mutations.some((m) => m.attributeName === "class")) syncTheme();
});
onMount(() => {
syncTheme();
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
});
function cleanName(name) {
return (name || "image")
.replace(/[^a-zA-Z0-9._-]/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "") || "image";
}
function extensionFor(type) {
if (type === "image/png") return "png";
if (type === "image/jpeg") return "jpg";
if (type === "image/webp") return "webp";
if (type === "image/gif") return "gif";
return "bin";
}
async function fileToBase64(file) {
const buf = await file.arrayBuffer();
let binary = "";
const bytes = new Uint8Array(buf);
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
return btoa(binary);
}
async function sendDroppedImage(term, ws, file) {
if (!file?.type?.startsWith("image/")) return;
if (ws.readyState !== 1) return;
const ext = extensionFor(file.type);
const baseName = cleanName(file.name).replace(/\.[a-zA-Z0-9]+$/, "");
const stamp = Date.now();
const imagePath = `/tmp/claude-images/${baseName || "image"}-${stamp}.${ext}`;
const b64 = await fileToBase64(file);
const cmd = [
"python3 - <<'PY'",
"import base64, pathlib",
`p = pathlib.Path(${JSON.stringify(imagePath)})`,
"p.parent.mkdir(parents=True, exist_ok=True)",
`p.write_bytes(base64.b64decode(${JSON.stringify(b64)}))`,
`print(f'saved image -> {p}')`,
"PY",
"",
].join("\n");
ws.send(new TextEncoder().encode(cmd));
term.write(`\r\n\x1b[90m[Uploaded image to ${imagePath}]\x1b[0m\r\n`);
}
function addTab(hostId) {
const id = ++tabCounter;
const label = hosts.find((h) => h.id === hostId).label;
tabs = [...tabs, { id, hostId, label, connected: false, error: "" }];
activeTab = id;
showMenu = false;
}
function closeTab(id) {
const d = tabData.get(id);
if (d) {
d.voice?.destroy();
d.ro?.disconnect();
if (d.heartbeat) clearInterval(d.heartbeat);
d.term?.element?.removeEventListener("dragover", d.handleDragOver);
d.term?.element?.removeEventListener("drop", d.handleDrop);
d.term?.textarea?.removeEventListener("paste", d.handlePaste);
d.ws?.close();
d.term?.dispose();
tabData.delete(id);
}
tabs = tabs.filter((t) => t.id !== id);
if (activeTab === id) activeTab = tabs.length ? tabs[tabs.length - 1].id : null;
}
function updateTab(tabId, props) {
tabs = tabs.map((t) => (t.id === tabId ? { ...t, ...props } : t));
}
function initTerminal(el, tab) {
const tabId = tab.id;
(async () => {
const { Terminal } = await import("@xterm/xterm");
const { FitAddon } = await import("@xterm/addon-fit");
await import("@xterm/xterm/css/xterm.css");
const term = new Terminal({
cursorBlink: true, fontSize: 13,
fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', 'Menlo', monospace",
lineHeight: 1.4,
theme: currentTheme(),
});
const fit = new FitAddon();
term.loadAddon(fit);
term.open(el);
fit.fit();
const proto = location.protocol === "https:" ? "wss:" : "ws:";
const token = localStorage.getItem("token") || "";
const ws = new WebSocket(
`${proto}//${location.host}/ws/terminal?host=${tab.hostId}`
);
ws.binaryType = "arraybuffer";
function sendSize() {
if (ws.readyState === 1) {
const buf = new Uint8Array(5);
buf[0] = 0x01;
new DataView(buf.buffer).setUint16(1, term.cols);
new DataView(buf.buffer).setUint16(3, term.rows);
ws.send(buf);
}
}
ws.onopen = () => { ws.send(token); updateTab(tabId, { connected: true, error: "" }); sendSize(); };
ws.onmessage = (e) => term.write(new Uint8Array(e.data));
ws.onclose = (e) => {
const reason = e.reason || `Connection closed (code ${e.code})`;
updateTab(tabId, { connected: false, error: reason });
term.write(`\r\n\x1b[90m[${reason}]\x1b[0m`);
};
ws.onerror = () => updateTab(tabId, { connected: false, error: "Connection failed" });
term.onData((data) => ws.readyState === 1 && ws.send(new TextEncoder().encode(data)));
const heartbeat = setInterval(() => {
if (ws.readyState === 1) ws.send("__ping__");
}, 25000);
const handleDragOver = (e) => {
e.preventDefault();
};
const handleDrop = async (e) => {
e.preventDefault();
if (activeTab !== tabId) return;
const files = [...(e.dataTransfer?.files || [])].filter((f) => f.type?.startsWith("image/"));
for (const file of files) {
await sendDroppedImage(term, ws, file);
}
};
const handlePaste = async (e) => {
if (activeTab !== tabId) return;
const items = [...(e.clipboardData?.items || [])]
.filter((it) => it.kind === "file" && it.type?.startsWith("image/"));
for (const item of items) {
const file = item.getAsFile();
if (file) await sendDroppedImage(term, ws, file);
}
};
term.element?.addEventListener("dragover", handleDragOver);
term.element?.addEventListener("drop", handleDrop);
term.textarea?.addEventListener("paste", handlePaste);
const ro = new ResizeObserver(() => { fit.fit(); sendSize(); });
ro.observe(el);
const voice = new VoiceSession(() => { voiceTick++; });
voice.attach(term, ws);
tabData.set(tabId, { ws, term, ro, el, voice, heartbeat, handleDragOver, handleDrop, handlePaste });
})();
}
function activeVoice() { return voiceTick >= 0 && tabData.get(activeTab)?.voice; }
onDestroy(() => {
themeObserver.disconnect();
tabData.forEach((d) => {
d.voice?.destroy();
d.ro?.disconnect();
if (d.heartbeat) clearInterval(d.heartbeat);
d.term?.element?.removeEventListener("dragover", d.handleDragOver);
d.term?.element?.removeEventListener("drop", d.handleDrop);
d.term?.textarea?.removeEventListener("paste", d.handlePaste);
d.ws?.close();
d.term?.dispose();
});
});
</script>
<div class={activeVoice()?.voiceMode ? 'flex flex-col h-[calc(100vh-4rem)] overflow-hidden gap-1' : 'space-y-2'}>
{#if !activeVoice()?.voiceMode}
<h1 class="text-2xl font-bold text-surface-900 dark:text-surface-100 tracking-tight">Terminal</h1>
{/if}
<div class="flex items-center gap-1 border-b border-surface-300 dark:border-surface-700 pb-1 relative">
{#each tabs as tab (tab.id)}
<button
class="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-t-lg transition-colors {activeTab === tab.id ? 'bg-surface-200 dark:bg-surface-800 text-surface-900 dark:text-surface-100' : 'text-surface-600 dark:text-surface-400 hover:text-surface-800 dark:hover:text-surface-200 hover:bg-surface-100 dark:hover:bg-surface-800/50'}"
onclick={() => activeTab = tab.id}
>
{#if tab.connected}
<span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
{:else if tab.error}
<span class="w-1.5 h-1.5 rounded-full bg-rose-500"></span>
{:else}
<span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"></span>
{/if}
{tab.label}
<span
class="ml-1 text-surface-500 hover:text-rose-400 cursor-pointer"
role="button"
tabindex="0"
onclick={(e) => { e.stopPropagation(); closeTab(tab.id); }}
onkeydown={(e) => e.key === 'Enter' && closeTab(tab.id)}
>&times;</span>
</button>
{/each}
<div class="relative">
<button
class="px-2 py-1 text-surface-600 dark:text-surface-400 hover:text-surface-900 dark:hover:text-surface-100 hover:bg-surface-200 dark:hover:bg-surface-800 rounded text-lg leading-none"
onclick={() => showMenu = !showMenu}
>+</button>
{#if showMenu}
<div class="absolute top-full left-0 mt-1 bg-surface-100 dark:bg-surface-800 border border-surface-300 dark:border-surface-600 rounded-lg shadow-xl z-10 py-1 min-w-[140px]">
{#each hosts as h}
<button
class="block w-full text-left px-3 py-1.5 text-sm text-surface-800 dark:text-surface-200 hover:bg-surface-200 dark:hover:bg-surface-700"
onclick={() => addTab(h.id)}
>{h.label}</button>
{/each}
</div>
{/if}
</div>
{#if activeTab && tabs.find(t => t.id === activeTab)?.connected && activeVoice()}
{@const v = activeVoice()}
<div class="ml-auto">
<button
class="px-2 py-1 rounded text-sm transition-colors {v.voiceMode ? 'text-rose-400' : v.sttAvailable ? 'text-surface-600 dark:text-surface-500 hover:text-surface-800 dark:hover:text-surface-300' : 'text-surface-300 dark:text-surface-700 cursor-not-allowed'}"
title={!v.sttAvailable ? 'STT not supported' : v.voiceMode ? 'Voice mode on' : 'Enter voice mode'}
disabled={!v.sttAvailable}
onclick={() => { if (!v.voiceMode) v.enterVoiceMode(); else v.exitVoiceMode(); voiceTick++; }}
>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/><path d="M19 10v2a7 7 0 01-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
</button>
</div>
{/if}
</div>
<p class="text-xs text-surface-600 dark:text-surface-500">
Tip: drag & drop or paste images into the active terminal tab to upload them to <code class="text-surface-700 dark:text-surface-400">/tmp/claude-images</code>.
</p>
{#if !tabs.length}
<div class="flex items-center justify-center h-[calc(100vh-12rem)] text-surface-600 dark:text-surface-500 text-sm">
Click + to open a terminal
</div>
{/if}
{#each tabs as tab (tab.id)}
<div class="{activeTab === tab.id ? '' : 'hidden'} {activeVoice()?.voiceMode ? 'flex-1 min-h-0' : ''}">
<div
use:initTerminal={tab}
class="h-full rounded-xl overflow-hidden shadow-lg border border-surface-300 dark:border-surface-700 bg-surface-50 dark:bg-[#0f172a] transition-all duration-300"
style="{activeVoice()?.voiceMode ? '' : 'height: calc(100vh - 10rem);'}"
></div>
</div>
{/each}
{#if activeVoice()?.voiceMode}
{@const v = activeVoice()}
<div class="mt-1 shrink-0 rounded-xl bg-surface-100/95 dark:bg-surface-800/95 border border-surface-300 dark:border-surface-700 shadow-xl overflow-hidden animate-slide-up">
<!-- Header -->
<div class="flex items-center justify-between px-3 py-1.5 border-b border-surface-300/50 dark:border-surface-700/50">
<span class="text-xs font-medium text-surface-700 dark:text-surface-300">Voice Mode</span>
<div class="flex items-center gap-2">
<select
class="bg-surface-200 dark:bg-surface-700 text-surface-800 dark:text-surface-300 text-xs rounded px-1 py-0.5 outline-none max-w-[120px]"
onchange={(e) => { v.setVoice(+e.target.value); voiceTick++; }}
>
{#each v.voices as voice, i}
<option value={i} selected={i === v.voiceIdx}>{voice.name}</option>
{/each}
</select>
<button
class="px-1.5 py-0.5 rounded text-xs font-medium text-surface-600 dark:text-surface-400 hover:text-surface-800 dark:hover:text-surface-200 hover:bg-surface-200 dark:hover:bg-surface-700"
onclick={() => { v.cycleLang(); voiceTick++; }}
>{v.langLabel}</button>
<button
class="px-1.5 py-0.5 rounded text-xs font-medium text-surface-600 dark:text-surface-400 hover:text-surface-800 dark:hover:text-surface-200 hover:bg-surface-200 dark:hover:bg-surface-700"
onclick={() => { v.cycleTalkMode(); voiceTick++; }}
>{v.modeLabel}</button>
<button
class="px-1.5 py-0.5 rounded text-xs text-surface-500 hover:text-rose-400"
onclick={() => { v.exitVoiceMode(); voiceTick++; }}
>&times;</button>
</div>
</div>
<!-- Transcript + Mic -->
<div class="flex items-center gap-3 px-3 py-2">
{#if v.talkMode === "hold"}
<button
aria-label="Hold to talk"
class="w-10 h-10 shrink-0 rounded-full flex items-center justify-center transition-colors {v.listening ? 'bg-rose-500/30 text-rose-400' : 'bg-surface-200 dark:bg-surface-700 text-surface-700 dark:text-surface-300 hover:bg-surface-300 dark:hover:bg-surface-600'}"
onpointerdown={() => { v.startHold(); voiceTick++; }}
onpointerup={() => { v.releaseHold(); voiceTick++; }}
onpointerleave={() => { if (v.listening) { v.releaseHold(); voiceTick++; } }}
>
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/><path d="M19 10v2a7 7 0 01-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
</button>
{:else if v.talkMode === "tap"}
<button
aria-label="Tap to talk"
class="w-10 h-10 shrink-0 rounded-full flex items-center justify-center transition-colors {v.listening ? 'bg-rose-500/30 text-rose-400' : 'bg-surface-200 dark:bg-surface-700 text-surface-700 dark:text-surface-300 hover:bg-surface-300 dark:hover:bg-surface-600'}"
onclick={() => { v.tapMic(); voiceTick++; }}
>
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/><path d="M19 10v2a7 7 0 01-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
</button>
{:else}
<div class="w-10 h-10 shrink-0 rounded-full flex items-center justify-center {v.listening ? 'bg-emerald-500/20 text-emerald-400 animate-pulse' : 'bg-surface-200 dark:bg-surface-700 text-surface-500'}">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/><path d="M19 10v2a7 7 0 01-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
</div>
{/if}
<div class="flex-1 min-w-0">
{#if v.transcript}
<p class="text-sm text-surface-600 dark:text-surface-400 italic truncate">"{v.transcript}"</p>
{:else}
<p class="text-xs text-surface-500 dark:text-surface-600">{v.speaking ? 'Speaking...' : v.listening ? 'Listening...' : 'Ready'}</p>
{/if}
</div>
</div>
</div>
{/if}
</div>
<style>
@keyframes slide-up {
from { transform: translateY(100%); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
.animate-slide-up { animation: slide-up 0.25s ease-out; }
</style>