feat: terminal tabs with on-demand connections and Claude Dev host

This commit is contained in:
Gan, Jimmy
2026-02-26 02:59:25 +08:00
parent 332696689a
commit b03b20aee6
2 changed files with 101 additions and 81 deletions
+3 -1
View File
@@ -8,6 +8,8 @@ import config
HOSTS = { HOSTS = {
"nas": {"host": config.SSH_HOST, "user": config.SSH_USER, "key": config.SSH_KEY_PATH}, "nas": {"host": config.SSH_HOST, "user": config.SSH_USER, "key": config.SSH_KEY_PATH},
"vps": {"host": config.VPS_SSH_HOST, "user": config.VPS_SSH_USER, "key": config.VPS_SSH_KEY_PATH}, "vps": {"host": config.VPS_SSH_HOST, "user": config.VPS_SSH_USER, "key": config.VPS_SSH_KEY_PATH},
"claude-dev": {"host": config.SSH_HOST, "user": config.SSH_USER, "key": config.SSH_KEY_PATH,
"command": "/volume1/@appstore/ContainerManager/usr/bin/docker exec -it claude-dev bash"},
} }
@@ -35,7 +37,7 @@ async def ws_endpoint(websocket: WebSocket, token: str = Query(""), host: str =
try: try:
process = await conn.create_process( process = await conn.create_process(
term_type="xterm-256color", term_size=(80, 24), h.get("command"), term_type="xterm-256color", term_size=(80, 24),
encoding=None, encoding=None,
) )
+94 -76
View File
@@ -4,37 +4,55 @@
const hosts = [ const hosts = [
{ id: "nas", label: "NAS" }, { id: "nas", label: "NAS" },
{ id: "vps", label: "VPS" }, { id: "vps", label: "VPS" },
{ id: "claude-dev", label: "Claude Dev" },
]; ];
let mobileHost = $state("nas"); let tabs = $state([]);
let terminals = $state({}); let activeTab = $state(null);
let cleanups = []; let showMenu = $state(false);
let tabCounter = 0;
const tabData = new Map();
function initTerminal(el, hostId) { 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.ro?.disconnect();
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 () => { (async () => {
const { Terminal } = await import("@xterm/xterm"); const { Terminal } = await import("@xterm/xterm");
const { FitAddon } = await import("@xterm/addon-fit"); const { FitAddon } = await import("@xterm/addon-fit");
await import("@xterm/xterm/css/xterm.css"); await import("@xterm/xterm/css/xterm.css");
const term = new Terminal({ const term = new Terminal({
cursorBlink: true, cursorBlink: true, fontSize: 13,
fontSize: 13,
fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', 'Menlo', monospace", fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', 'Menlo', monospace",
lineHeight: 1.4, lineHeight: 1.4,
theme: { theme: {
background: "#0f172a", background: "#0f172a", foreground: "#e2e8f0", cursor: "#6366f1",
foreground: "#e2e8f0", cursorAccent: "#0f172a", selectionBackground: "#334155",
cursor: "#6366f1", black: "#0f172a", red: "#f43f5e", green: "#10b981",
cursorAccent: "#0f172a", yellow: "#f59e0b", blue: "#3b82f6", magenta: "#a855f7",
selectionBackground: "#334155", cyan: "#06b6d4", white: "#e2e8f0",
black: "#0f172a",
red: "#f43f5e",
green: "#10b981",
yellow: "#f59e0b",
blue: "#3b82f6",
magenta: "#a855f7",
cyan: "#06b6d4",
white: "#e2e8f0",
}, },
}); });
const fit = new FitAddon(); const fit = new FitAddon();
@@ -45,10 +63,9 @@
const proto = location.protocol === "https:" ? "wss:" : "ws:"; const proto = location.protocol === "https:" ? "wss:" : "ws:";
const token = localStorage.getItem("token") || ""; const token = localStorage.getItem("token") || "";
const ws = new WebSocket( const ws = new WebSocket(
`${proto}//${location.host}/ws/terminal?token=${encodeURIComponent(token)}&host=${hostId}` `${proto}//${location.host}/ws/terminal?token=${encodeURIComponent(token)}&host=${tab.hostId}`
); );
ws.binaryType = "arraybuffer"; ws.binaryType = "arraybuffer";
function sendSize() { function sendSize() {
if (ws.readyState === 1) { if (ws.readyState === 1) {
const buf = new Uint8Array(5); const buf = new Uint8Array(5);
@@ -59,79 +76,80 @@
} }
} }
ws.onopen = () => { ws.onopen = () => { updateTab(tabId, { connected: true }); sendSize(); };
terminals[hostId] = { connected: true, error: "" };
sendSize();
};
ws.onmessage = (e) => term.write(new Uint8Array(e.data)); ws.onmessage = (e) => term.write(new Uint8Array(e.data));
ws.onclose = () => { ws.onclose = () => {
terminals[hostId] = { ...terminals[hostId], connected: false }; updateTab(tabId, { connected: false });
term.write("\r\n\x1b[90m[Connection closed]\x1b[0m"); term.write("\r\n\x1b[90m[Connection closed]\x1b[0m");
}; };
ws.onerror = () => { ws.onerror = () => updateTab(tabId, { connected: false, error: "Connection failed" });
terminals[hostId] = { connected: false, error: "WebSocket connection failed" };
};
term.onData((data) => ws.readyState === 1 && ws.send(new TextEncoder().encode(data))); term.onData((data) => ws.readyState === 1 && ws.send(new TextEncoder().encode(data)));
const ro = new ResizeObserver(() => { const ro = new ResizeObserver(() => { fit.fit(); sendSize(); });
fit.fit();
sendSize();
});
ro.observe(el); ro.observe(el);
tabData.set(tabId, { ws, term, ro, el });
cleanups.push(() => {
ro.disconnect();
ws.close();
term.dispose();
});
})(); })();
} }
onDestroy(() => cleanups.forEach((fn) => fn())); onDestroy(() => tabData.forEach((d) => { d.ro?.disconnect(); d.ws?.close(); d.term?.dispose(); }));
function statusFor(hostId) {
const t = terminals[hostId];
if (!t) return { connected: false, error: "" };
return t;
}
</script> </script>
<div class="space-y-2">
<div class="space-y-4">
<div class="flex items-center justify-between">
<div>
<h1 class="text-2xl font-bold text-surface-900 tracking-tight">Terminal</h1> <h1 class="text-2xl font-bold text-surface-900 tracking-tight">Terminal</h1>
<div class="mt-2 md:hidden">
<select
class="bg-surface-800 text-surface-200 border border-surface-600 rounded-lg px-3 py-1.5 text-sm"
bind:value={mobileHost}
>
{#each hosts as h}
<option value={h.id}>{h.label}</option>
{/each}
</select>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <div class="flex items-center gap-1 border-b border-surface-700 pb-1 relative">
{#each hosts as h (h.id)} {#each tabs as tab (tab.id)}
<div class="hidden md:block" class:!block={mobileHost === h.id}> <button
<div class="flex items-center gap-2 mb-2 text-sm text-surface-400"> class="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-t-lg transition-colors {activeTab === tab.id ? 'bg-surface-800 text-surface-100' : 'text-surface-400 hover:text-surface-200 hover:bg-surface-800/50'}"
<span class="font-medium text-surface-200">{h.label}</span> onclick={() => activeTab = tab.id}
{#if statusFor(h.id).connected} >
<span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span> Connected {#if tab.connected}
{:else if statusFor(h.id).error} <span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
<span class="text-rose-500">{statusFor(h.id).error}</span> {:else if tab.error}
<span class="w-1.5 h-1.5 rounded-full bg-rose-500"></span>
{:else} {:else}
<span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"></span> Connecting... <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-400 hover:text-surface-100 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-800 border 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-200 hover:bg-surface-700"
onclick={() => addTab(h.id)}
>{h.label}</button>
{/each}
</div>
{/if} {/if}
</div> </div>
</div>
{#if !tabs.length}
<div class="flex items-center justify-center h-[calc(100vh-12rem)] text-surface-500 text-sm">
Click + to open a terminal
</div>
{/if}
{#each tabs as tab (tab.id)}
<div class={activeTab === tab.id ? '' : 'hidden'}>
<div <div
use:initTerminal={h.id} use:initTerminal={tab}
class="h-[calc(100vh-12rem)] rounded-xl overflow-hidden shadow-lg border border-surface-700" class="h-[calc(100vh-10rem)] rounded-xl overflow-hidden shadow-lg border border-surface-700"
style="background: #0f172a;" style="background: #0f172a;"
></div> ></div>
</div> </div>
{/each} {/each}
</div> </div>
</div>