feat: Sprint 5 — xterm.js terminal with WebSocket mock shell, Alpine tab management

This commit is contained in:
swanadiva
2026-07-07 13:39:35 +07:00
parent 941a67b6ea
commit 04d9cfb096
10 changed files with 571 additions and 12 deletions
+5 -1
View File
@@ -9,6 +9,8 @@ require (
require (
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/fasthttp/websocket v1.5.8 // indirect
github.com/gofiber/contrib/websocket v1.3.4 // indirect
github.com/gofiber/template v1.8.3 // indirect
github.com/gofiber/utils v1.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
@@ -17,8 +19,10 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.51.0 // indirect
github.com/valyala/fasthttp v1.52.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sys v0.28.0 // indirect
)
+10
View File
@@ -2,6 +2,10 @@ github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fasthttp/websocket v1.5.8 h1:k5DpirKkftIF/w1R8ZzjSgARJrs54Je9YJK37DL/Ah8=
github.com/fasthttp/websocket v1.5.8/go.mod h1:d08g8WaT6nnyvg9uMm8K9zMYyDjfKyj3170AtPRuVU0=
github.com/gofiber/contrib/websocket v1.3.4 h1:tWeBdbJ8q0WFQXariLN4dBIbGH9KBU75s0s7YXplOSg=
github.com/gofiber/contrib/websocket v1.3.4/go.mod h1:kTFBPC6YENCnKfKx0BoOFjgXxdz7E85/STdkmZPEmPs=
github.com/gofiber/fiber/v2 v2.52.14 h1:Of3L+9qVFaQNwPlcmEdl5IIodHz8BSE0j37R7rWu4pE=
github.com/gofiber/fiber/v2 v2.52.14/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
github.com/gofiber/template v1.8.3 h1:hzHdvMwMo/T2kouz2pPCA0zGiLCeMnoGsQZBTSYgZxc=
@@ -25,14 +29,20 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511 h1:KanIMPX0QdEdB4R3CiimCAbxFrhB3j7h0/OvpYGVQa8=
github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511/go.mod h1:sM7Mt7uEoCeFSCBM+qBrqvEo+/9vdmj19wzp3yzUhmg=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
github.com/valyala/fasthttp v1.52.0 h1:wqBQpxH71XW0e2g+Og4dzQM8pk34aFYlA1Ga8db7gU0=
github.com/valyala/fasthttp v1.52.0/go.mod h1:hf5C4QnVMkNXMspnsUlfM3WitlgYflyhHYoKol/szxQ=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
+131
View File
@@ -0,0 +1,131 @@
package handler
import (
"fmt"
"log"
"strings"
"time"
"github.com/gofiber/contrib/websocket"
"github.com/gofiber/fiber/v2"
)
func Terminal(c *fiber.Ctx) error {
return c.Render("terminal", fiber.Map{
"View": "terminal",
"Title": "Terminal",
"NavItems": navItems,
})
}
var hostList = []struct {
ID string
Name string
IP string
}{
{"h1", "api-prod-01", "10.0.1.15"},
{"h2", "db-primary-01", "10.0.2.5"},
{"h6", "monitor-01", "10.0.0.5"},
{"h7", "worker-pool-01", "10.0.4.50"},
}
func TerminalWS(c *websocket.Conn) {
host := c.Params("host", "unknown")
log.Printf("WS connected: host=%s", host)
welcome := fmt.Sprintf("\x1b[1;32mWelcome to %s\x1b[0m\r\n\x1b[2mConnected at %s\x1b[0m\r\n\r\n", host, time.Now().Format(time.RFC822))
c.WriteMessage(websocket.TextMessage, []byte(welcome))
prompt := fmt.Sprintf("\x1b[1;34m%s:~$\x1b[0m ", host)
cwd := "~"
buf := ""
for {
_, msg, err := c.ReadMessage()
if err != nil {
break
}
input := string(msg)
switch {
case input == "\r":
output := handleCommand(buf, host, &cwd)
c.WriteMessage(websocket.TextMessage, []byte(output+prompt))
buf = ""
case input == "\x7f":
if len(buf) > 0 {
buf = buf[:len(buf)-1]
c.WriteMessage(websocket.TextMessage, []byte("\b \b"))
}
case input == "\x03":
buf = ""
c.WriteMessage(websocket.TextMessage, []byte("^C\r\n"+prompt))
default:
if input >= " " && input <= "~" {
buf += input
c.WriteMessage(websocket.TextMessage, []byte(input))
}
}
}
log.Printf("WS disconnected: host=%s", host)
}
func handleCommand(cmd, host string, cwd *string) string {
cmd = strings.TrimSpace(cmd)
if cmd == "" {
return ""
}
parts := strings.Fields(cmd)
if len(parts) == 0 {
return ""
}
switch parts[0] {
case "clear":
return "\x1b[2J\x1b[H"
case "exit", "logout":
return "logout\r\n\x1b[2J\x1b[H\x1b[1;31mConnection closed.\x1b[0m\r\n"
case "pwd":
return *cwd + "\r\n"
case "whoami":
return "deploy\r\n"
case "hostname":
return host + "\r\n"
case "date":
return time.Now().Format("Mon Jan 2 15:04:05 MST 2006") + "\r\n"
case "uptime":
return fmt.Sprintf(" 13:42:17 up %d day, 1 user, load average: 0.08, 0.12, 0.10\r\n", 1+time.Now().Day()%30)
case "uname":
if len(parts) > 1 && parts[1] == "-a" {
return fmt.Sprintf("Linux %s 6.8.0-45-generic #47-Ubuntu SMP PREEMPT x86_64 x86_64 x86_64 GNU/Linux\r\n", host)
}
return "Linux\r\n"
case "ls":
if *cwd == "~" || *cwd == "/home/deploy" {
return "Documents Downloads projects config.yml README.md .env\r\n"
}
return "total 0\r\n"
case "cd":
if len(parts) > 1 {
*cwd = parts[1]
} else {
*cwd = "~"
}
return ""
case "cat":
if len(parts) > 1 {
return fmt.Sprintf("\x1b[1;37m# Content of %s\x1b[0m\r\n(not implemented in mock shell)\r\n", parts[1])
}
return ""
case "echo":
return strings.Join(parts[1:], " ") + "\r\n"
case "ssh":
return "\x1b[1;33mSSH forwarding not available in mock mode\x1b[0m\r\n"
case "help":
return "Available commands: clear, exit, pwd, whoami, hostname, date, uptime, uname, ls, cd, cat, echo, ssh, help\r\n"
default:
return fmt.Sprintf("\x1b[1;31m%s: command not found\x1b[0m\r\n", parts[0])
}
}
+7
View File
@@ -3,6 +3,7 @@ package main
import (
"log"
"github.com/gofiber/contrib/websocket"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/logger"
@@ -52,6 +53,12 @@ func main() {
app.Get("/settings", handler.Settings)
app.Post("/settings", handler.UpdateConfig)
app.Get("/brief", handler.Brief)
app.Get("/terminal", handler.Terminal)
app.Get("/terminal/ws/:host", websocket.New(func(c *websocket.Conn) {
handler.TerminalWS(c)
}, websocket.Config{
Origins: []string{"*"},
}))
app.Get("/sftp", handler.SFTP)
app.Get("/sftp/pane", handler.SFTPPane)
app.Post("/sftp/mkdir", handler.CreateFolder)
+128
View File
@@ -0,0 +1,128 @@
document.addEventListener('alpine:init', () => {
const hostOptions = [
{ id: 'h1', name: 'api-prod-01', ip: '10.0.1.15' },
{ id: 'h2', name: 'db-primary-01', ip: '10.0.2.5' },
{ id: 'h6', name: 'monitor-01', ip: '10.0.0.5' },
{ id: 'h7', name: 'worker-pool-01', ip: '10.0.4.50' },
];
Alpine.data('terminalManager', () => ({
tabs: [],
activeTab: 0,
termInstances: {},
init() {
this.addTab();
},
addTab() {
const randomHost = hostOptions[Math.floor(Math.random() * hostOptions.length)];
const id = 'term-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6);
this.tabs.push({ id, name: randomHost.name, host: randomHost.id, connected: false });
this.activeTab = this.tabs.length - 1;
this.$nextTick(() => this.connectTerminal(id, randomHost.id, randomHost.name));
},
switchTab(i) {
this.activeTab = i;
},
closeTab(i) {
const tab = this.tabs[i];
if (this.termInstances[tab.id]) {
this.termInstances[tab.id].dispose();
delete this.termInstances[tab.id];
}
this.tabs.splice(i, 1);
if (this.tabs.length === 0) this.addTab();
else if (this.activeTab >= this.tabs.length) this.activeTab = this.tabs.length - 1;
},
connectTerminal(id, hostId, hostName) {
const container = document.getElementById('terminal-container-' + id);
if (!container) return;
const term = new Terminal({
cursorBlink: true,
cursorStyle: 'bar',
fontSize: 14,
fontFamily: "'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace",
theme: {
background: '#0d1117',
foreground: '#c9d1d9',
cursor: '#58a6ff',
selection: '#264f78',
black: '#484f58',
red: '#ff7b72',
green: '#3fb950',
yellow: '#d29922',
blue: '#58a6ff',
magenta: '#bc8cff',
cyan: '#39c5cf',
white: '#b1bac4',
brightBlack: '#6e7681',
brightRed: '#ffa198',
brightGreen: '#56d364',
brightYellow: '#e3b341',
brightBlue: '#79c0ff',
brightMagenta: '#d2a8ff',
brightCyan: '#56d4dd',
brightWhite: '#f0f6fc',
},
});
term.open(container);
this.termInstances[id] = term;
const tab = this.tabs.find(t => t.id === id);
if (tab) tab.connected = false;
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = protocol + '//' + window.location.host + '/terminal/ws/' + hostId;
let ws;
try {
ws = new WebSocket(wsUrl);
} catch (e) {
term.writeln('\x1b[1;31mWebSocket connection failed\x1b[0m');
return;
}
ws.onopen = () => {
if (tab) tab.connected = true;
term.focus();
};
ws.onmessage = (e) => {
if (e.data instanceof Blob) {
const reader = new FileReader();
reader.onload = () => term.write(reader.result);
reader.readAsText(e.data);
} else {
term.write(e.data);
}
};
ws.onerror = () => {
term.writeln('\x1b[1;31m\x1b[7m CONNECTION ERROR \x1b[0m');
};
ws.onclose = () => {
if (tab) tab.connected = false;
term.writeln('\r\n\x1b[2mConnection closed.\x1b[0m');
};
term.onData((data) => {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(data);
}
});
term.attachCustomKeyEventHandler((e) => {
if (e.type === 'keydown' && e.ctrlKey && e.key === 'c') {
return true;
}
return true;
});
},
}));
});
+209
View File
@@ -0,0 +1,209 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
cursor: text;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: #000;
color: #FFF;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: #000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer,
.xterm .xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility,
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
pointer-events: none;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
/* Dim should not apply to background, so the opacity of the foreground color is applied
* explicitly in the generated class and reset to 1 here */
opacity: 1 !important;
}
.xterm-underline-1 { text-decoration: underline; }
.xterm-underline-2 { text-decoration: double underline; }
.xterm-underline-3 { text-decoration: wavy underline; }
.xterm-underline-4 { text-decoration: dotted underline; }
.xterm-underline-5 { text-decoration: dashed underline; }
.xterm-overline {
text-decoration: overline;
}
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
.xterm-strikethrough {
text-decoration: line-through;
}
.xterm-screen .xterm-decoration-container .xterm-decoration {
z-index: 6;
position: absolute;
}
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
z-index: 7;
}
.xterm-decoration-overview-ruler {
z-index: 8;
position: absolute;
top: 0;
right: 0;
pointer-events: none;
}
.xterm-decoration-top {
z-index: 2;
position: relative;
}
File diff suppressed because one or more lines are too long
+61
View File
@@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Terminal · Hostkeeper V2</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/output.css">
<link rel="stylesheet" href="/static/css/custom.css">
<link rel="stylesheet" href="/static/xterm/xterm.css">
<script src="/static/js/htmx.min.js"></script>
<script src="/static/js/alpine.min.js" defer></script>
</head>
<body class="bg-surface text-on-surface antialiased dot-grid min-h-screen">
<div class="flex min-h-screen">
{{template "nav" .}}
<div class="flex-1 flex flex-col overflow-hidden">
<header class="h-14 border-b border-outline-variant/30 flex items-center gap-2 px-6 bg-white/70 backdrop-blur-md">
<h1 class="text-lg font-semibold text-on-surface">{{.Title}}</h1>
<div class="flex-1"></div>
<button @click="addTab()"
class="p-1.5 rounded-lg hover:bg-surface-container-low text-on-surface-variant hover:text-on-surface transition-colors" title="New Tab">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
</button>
</header>
<main id="main-content" class="flex-1 flex flex-col overflow-hidden bg-[#0d1117]"
x-data="terminalManager()"
x-init="init()">
<!-- Tab bar -->
<div class="flex items-center bg-[#161b22] border-b border-[#30363d] overflow-x-auto no-scrollbar shrink-0" style="height: 36px;">
<template x-for="(tab, i) in tabs" :key="tab.id">
<div @click="switchTab(i)"
:class="activeTab === i ? 'bg-[#0d1117] text-white border-t-2 border-[#58a6ff]' : 'bg-[#161b22] text-[#8b949e] hover:text-[#c9d1d9]'"
class="flex items-center gap-1.5 px-3 text-xs cursor-pointer border-r border-[#30363d] shrink-0 select-none"
style="height: 34px; padding-top: 1px;">
<span class="w-2 h-2 rounded-full" :class="tab.connected ? 'bg-[#3fb950]' : 'bg-[#8b949e]'"></span>
<span x-text="tab.name"></span>
<button @click.stop="closeTab(i)" class="ml-0.5 p-0.5 rounded hover:bg-[#30363d] text-[#8b949e] hover:text-white transition-colors">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</div>
</template>
</div>
<!-- Terminal containers -->
<div class="flex-1 relative">
<template x-for="(tab, i) in tabs" :key="tab.id">
<div :id="'terminal-container-' + tab.id"
x-show="activeTab === i"
class="absolute inset-0">
</div>
</template>
</div>
</main>
</div>
</div>
<script src="/static/xterm/xterm.js"></script>
<script src="/static/js/terminal.js"></script>
</body>
</html>