fix session with split screens

This commit is contained in:
2026-05-24 06:37:59 +00:00
parent 330cf01985
commit 45e18b5423
9 changed files with 760 additions and 224 deletions
+1
View File
@@ -3,3 +3,4 @@ upload/
gotermix
*.json
*.key
test*
+1
View File
@@ -29,6 +29,7 @@ type storedCreds struct {
Hash string `json:"hash"`
CertFile string `json:"cert_file,omitempty"`
KeyFile string `json:"key_file,omitempty"`
Workspaces map[string]*WorkspaceLayout `json:"workspaces,omitempty"`
}
type client struct {
+6 -8
View File
@@ -57,19 +57,17 @@ func handleStaticJS(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}
// handleIndex: clean URL, always creates a fresh session.
// The session-specific /s/<id> URL is available in the toolbar for sharing.
// handleIndex: always creates a fresh workspace and redirects to its stable URL.
// PTY sessions are started lazily by the frontend via WebSocket connections.
func handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
id := randHex(16)
getOrCreate(id)
serveTerminalPage(w, id, isAuthed(r))
http.Redirect(w, r, "/s/"+randHex(16), http.StatusFound)
}
// handleShell: reconnects to a specific session by ID.
// handleShell: serves the terminal page for an existing (or new) workspace ID.
func handleShell(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/s/")
if !validID(id) {
@@ -79,13 +77,13 @@ func handleShell(w http.ResponseWriter, r *http.Request) {
serveTerminalPage(w, id, isAuthed(r))
}
func serveTerminalPage(w http.ResponseWriter, id string, authed bool) {
func serveTerminalPage(w http.ResponseWriter, workspaceID string, authed bool) {
authedStr := "false"
if authed {
authedStr = "true"
}
html := strings.NewReplacer(
"[[SESSION_ID]]", id,
"[[WORKSPACE_ID]]", workspaceID,
"[[AUTHED]]", authedStr,
).Replace(shellPageHTML)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
+1
View File
@@ -145,6 +145,7 @@ func Run() {
mux.HandleFunc("/favicon.svg", handleFavicon)
mux.HandleFunc("/static/app.css", handleStaticCSS)
mux.HandleFunc("/static/app.js", handleStaticJS)
mux.HandleFunc("/api/workspace/", handleWorkspaceAPI)
ln, _ := net.Listen("tcp", *addr)
fmt.Printf("Go Web Shell https://%s\n", *addr)
+57 -1
View File
@@ -33,6 +33,12 @@ html, body { height: 100%; background: #0d0f14; color: #e2e8f0;
border-color: rgba(255,255,255,0.08);
}
.tab-label { cursor: pointer; }
.tab-rename-input {
background: #0d0f14; border: 1px solid rgba(110,231,183,0.45);
border-radius: 3px; color: #e2e8f0; font-size: 11px;
font-family: inherit; padding: 1px 5px; outline: none;
width: 90px; min-width: 40px;
}
.tab-x {
width: 16px; height: 16px; border: none; border-radius: 3px;
background: transparent; color: inherit; cursor: pointer;
@@ -54,7 +60,53 @@ html, body { height: 100%; background: #0d0f14; color: #e2e8f0;
#termContainer {
position: fixed; top: 36px; left: 0; right: 0; bottom: 48px;
}
.term-pane { width: 100%; height: 100%; }
/* One per tab — holds the entire pane tree for that tab */
.tab-pane { width: 100%; height: 100%; }
/* Leaf node — wraps an xterm canvas */
.term-pane { width: 100%; height: 100%; overflow: hidden; }
/* Active pane highlight (shown only when 2+ panes exist in a tab) */
.pane-active { box-shadow: inset 0 0 0 1px rgba(110,231,183,0.45); }
/* ── Split containers ── */
/* dir 'h': side-by-side with a vertical divider */
.split-h {
display: flex; flex-direction: row;
width: 100%; height: 100%; overflow: hidden;
}
/* dir 'v': stacked with a horizontal divider */
.split-v {
display: flex; flex-direction: column;
width: 100%; height: 100%; overflow: hidden;
}
/* ── Draggable dividers ── */
.split-div-h {
flex: 0 0 4px; height: 100%;
background: rgba(255,255,255,0.07);
cursor: col-resize;
transition: background 0.15s;
position: relative;
}
.split-div-h::after {
content: ''; position: absolute; inset: 0 -2px;
/* wider hit target without affecting layout */
}
.split-div-h:hover { background: rgba(110,231,183,0.35); }
.split-div-v {
flex: 0 0 4px; width: 100%;
background: rgba(255,255,255,0.07);
cursor: row-resize;
transition: background 0.15s;
position: relative;
}
.split-div-v::after {
content: ''; position: absolute; inset: -2px 0;
}
.split-div-v:hover { background: rgba(110,231,183,0.35); }
/* ── Compact toolbar ── */
.toolbar {
@@ -94,6 +146,10 @@ html, body { height: 100%; background: #0d0f14; color: #e2e8f0;
.tb-btn.accent { background: rgba(110,231,183,0.1); color: #6ee7b7;
border: 1px solid rgba(110,231,183,0.15); }
.tb-btn.accent:hover { background: rgba(110,231,183,0.18); }
.tb-btn.tb-danger { background: rgba(239,68,68,0.08); color: #f87171;
border: 1px solid rgba(239,68,68,0.15); }
.tb-btn.tb-danger:hover { background: rgba(239,68,68,0.16); color: #fca5a5; }
.tb-sep { width: 1px; height: 20px; background: rgba(255,255,255,0.07); flex-shrink: 0; margin: 0 2px; }
/* ── Toast ── */
.toast {
+505 -175
View File
@@ -1,23 +1,20 @@
// ── Session context (injected as inline <script> in shell.html) ─────
// SESSION_ID and AUTHED are defined before this file loads.
// WORKSPACE_ID and AUTHED injected as inline <script> in shell.html
// ── Terminal theme ──────────────────────────────────────────────────
// ── Theme ─────────────────────────────────────────────────────────────
const TERM_THEME = {
background: '#0d0f14', foreground: '#e2e8f0',
cursor: '#6ee7b7', cursorAccent: '#0d0f14',
selectionBackground: 'rgba(110,231,183,0.25)',
};
// ── Global state ─────────────────────────────────────────────────────
// ── Global state ─────────────────────────────────────────────────────
let tabs = [];
let activeTab = null;
let tabCounter = 0;
// Runtime auth flag — AUTHED is the page-load value; this tracks whether
// the user has authenticated in THIS session (including via the auth modal
// after page load, where AUTHED remains false but we are now connected).
let isAuthenticated = AUTHED;
let isAuthenticated = AUTHED; // updated to true after successful login
let saveTimer = null;
// ── Helpers ──────────────────────────────────────────────────────────
// ── Helpers ──────────────────────────────────────────────────────────
function randHexClient(n) {
const arr = new Uint8Array(n);
crypto.getRandomValues(arr);
@@ -25,28 +22,110 @@ function randHexClient(n) {
}
function pasteToTerminal() {
const leaf = activeTab && activeTab.activeLeaf;
navigator.clipboard.readText().then(
text => { if (text && activeTab) activeTab.term.paste(text); },
text => { if (text && leaf) leaf.term.paste(text); },
() => toast('Clipboard access denied — allow it in the browser address bar', 'err')
);
}
// ── URL hash: persist tab layout ──────────────────────────────────────
//
// Format: /s/<firstTabId>#t=id1,id2,id3
// When another browser opens this URL it reads the hash and opens the
// same sessions. The server only sees /s/<firstTabId> (hash is client-only).
function updateURLHash() {
if (tabs.length === 0) return;
const ids = tabs.map(t => t.id).join(',');
history.replaceState(null, '', '/s/' + tabs[0].id + '#t=' + ids);
// ── Workspace API ─────────────────────────────────────────────────────
async function loadWorkspace() {
try {
const res = await fetch('/api/workspace/' + WORKSPACE_ID);
if (res.status === 404) return null;
if (!res.ok) return null;
return await res.json();
} catch (_) {
return null;
}
}
function getTabIDsFromHash() {
const hash = location.hash; // e.g. "#t=aabb...,ccdd..."
if (!hash.startsWith('#t=')) return null;
const ids = hash.slice(3).split(',').filter(id => /^[0-9a-f]{32}$/.test(id));
return ids.length ? ids : null;
function saveWorkspace() {
clearTimeout(saveTimer);
saveTimer = setTimeout(_doSaveWorkspace, 300);
}
async function _doSaveWorkspace() {
if (!isAuthenticated || !tabs.length) return;
const ws = {
id: WORKSPACE_ID,
tabs: tabs.map(t => ({
tab_id: t.tabId,
label: t.label,
root: serializePane(t.root),
})),
};
try {
await fetch('/api/workspace/' + WORKSPACE_ID, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(ws),
});
} catch (_) {}
}
async function endSession() {
if (!confirm('End session? Saved layout will be cleared — this link will start a fresh session.')) return;
try {
await fetch('/api/workspace/' + WORKSPACE_ID, { method: 'DELETE' });
} catch (_) {}
// Close all sockets silently
tabs.forEach(t => walkLeaves(t.root, l => {
if (l.socket) { l.socket.onclose = null; l.socket.close(); }
}));
location.href = '/';
}
function copyLink() {
const url = location.protocol + '//' + location.host + '/s/' + WORKSPACE_ID;
navigator.clipboard.writeText(url).then(
() => toast('Workspace link copied!', 'ok'),
() => toast('Copy failed', 'err')
);
}
// ── Pane serialization ────────────────────────────────────────────────
function serializePane(node) {
if (node.type === 'leaf') return { type: 'leaf', id: node.id };
return {
type: 'split',
dir: node.dir,
ratio: node.ratio,
a: serializePane(node.a),
b: serializePane(node.b),
};
}
function deserializePane(data) {
if (data.type === 'leaf') {
return createLeaf(data.id);
}
// Split node — build children first, then container
const a = deserializePane(data.a);
const b = deserializePane(data.b);
const splitEl = document.createElement('div');
splitEl.className = data.dir === 'h' ? 'split-h' : 'split-v';
const divEl = document.createElement('div');
divEl.className = data.dir === 'h' ? 'split-div-h' : 'split-div-v';
const splitNode = {
type: 'split', dir: data.dir, ratio: data.ratio,
a, b, el: splitEl, divEl, parent: null,
};
a.parent = splitNode;
b.parent = splitNode;
splitEl.appendChild(a.el);
splitEl.appendChild(divEl);
splitEl.appendChild(b.el);
applyFlex(splitNode);
setupDivider(splitNode);
return splitNode;
}
// ── Global keyboard handler (capture phase) ───────────────────────────
@@ -54,58 +133,62 @@ document.addEventListener('keydown', function(e) {
const C = e.ctrlKey, S = e.shiftKey, A = e.altKey, M = e.metaKey;
if (A && !C && !M) {
// Alt+T → new tab
if (!S && e.code === 'KeyT') { e.preventDefault(); newTab(); return; }
// Alt+W → close active tab (last tab stays)
if (!S && e.code === 'KeyW') { e.preventDefault(); if (activeTab) closeTab(activeTab); return; }
// Alt+Shift+← / Alt+Shift+→ → prev / next tab
// (plain Alt+← / Alt+→ is word-nav below; Shift disambiguates)
if (S && e.code === 'ArrowLeft') {
if (!S) {
switch (e.code) {
case 'KeyT': e.preventDefault(); newTab(); return;
case 'KeyW': e.preventDefault(); if (activeTab) closeTab(activeTab); return;
case 'KeyX': e.preventDefault(); closePane(); return;
case 'Backslash': e.preventDefault(); splitPane('h'); return;
case 'Minus': e.preventDefault(); splitPane('v'); return;
case 'ArrowLeft':
e.preventDefault(); sendToActive('\x1bb'); return;
case 'ArrowRight':
e.preventDefault(); sendToActive('\x1bf'); return;
}
} else {
if (e.code === 'ArrowLeft') {
e.preventDefault();
const idx = tabs.indexOf(activeTab);
if (idx > 0) switchTab(tabs[idx - 1]);
return;
}
if (S && e.code === 'ArrowRight') {
if (e.code === 'ArrowRight') {
e.preventDefault();
const idx = tabs.indexOf(activeTab);
if (idx < tabs.length - 1) switchTab(tabs[idx + 1]);
return;
}
// Alt+← / Alt+→ → readline word-backward / word-forward
if (!S && (e.code === 'ArrowLeft' || e.code === 'ArrowRight')) {
e.preventDefault();
const t = activeTab;
if (t && t.socket && t.socket.readyState === WebSocket.OPEN)
t.socket.send(e.code === 'ArrowLeft' ? '\x1bb' : '\x1bf');
return;
}
}
// Block all Ctrl+key browser shortcuts; xterm still receives the event.
// Block ALL Ctrl+key browser shortcuts; xterm still gets the event.
if (C && !A && !M) {
e.preventDefault();
if (!S && e.code === 'KeyW') {
const t = activeTab;
if (t && t.socket && t.socket.readyState === WebSocket.OPEN) t.socket.send('\x17');
}
if (!S && e.code === 'KeyW') sendToActive('\x17');
return;
}
// Block all function keys
// Block function keys
if (!M && /^F\d+$/.test(e.key)) { e.preventDefault(); return; }
}, true); // capture phase
}, true);
// Chrome processes Ctrl+W before dispatching keydown — last guard.
window.addEventListener('beforeunload', function(e) {
if (tabs.some(t => t.socket && t.socket.readyState === WebSocket.OPEN)) {
e.preventDefault();
return e.returnValue = '';
function sendToActive(data) {
const leaf = activeTab && activeTab.activeLeaf;
if (leaf && leaf.socket && leaf.socket.readyState === WebSocket.OPEN) leaf.socket.send(data);
}
// Guard accidental tab close
window.addEventListener('beforeunload', function(e) {
const anyOpen = tabs.some(t => {
let f = false;
walkLeaves(t.root, l => { if (l.socket && l.socket.readyState === WebSocket.OPEN) f = true; });
return f;
});
if (anyOpen) { e.preventDefault(); return e.returnValue = ''; }
});
// ── Toast ─────────────────────────────────────────────────────────────
// ── Toast ─────────────────────────────────────────────────────────────
let toastTimer;
function toast(msg, type) {
const el = document.getElementById('toast');
@@ -125,26 +208,17 @@ function setStatus(text, state) {
}
function updateStatus() {
if (!activeTab) return;
const s = activeTab.socket;
const leaf = activeTab && activeTab.activeLeaf;
const wsShort = '/s/' + WORKSPACE_ID.slice(0, 8) + '...';
if (!leaf) { setStatus(wsShort, ''); return; }
const s = leaf.socket;
if (!s || s.readyState === WebSocket.CONNECTING) setStatus('connecting...', '');
else if (s.readyState === WebSocket.OPEN) setStatus('connected ' + activeTab.id.slice(0, 8) + '...', 'ok');
else if (s.readyState === WebSocket.OPEN)
setStatus(wsShort + ' pane:' + leaf.id.slice(0, 8), 'ok');
else setStatus('disconnected', 'err');
}
// copyLink encodes all open tab IDs in the URL hash so the recipient
// browser opens the same session layout.
function copyLink() {
const ids = tabs.map(t => t.id).join(',');
const url = location.protocol + '//' + location.host +
'/s/' + tabs[0].id + '#t=' + ids;
navigator.clipboard.writeText(url).then(
() => toast('Session link copied!', 'ok'),
() => toast('Copy failed', 'err')
);
}
// ── Modal helpers ─────────────────────────────────────────────────────
// ── Modal helpers ──────────────────────────────────────────────────────
function openModal(id) {
document.getElementById(id).classList.remove('hidden');
const inp = document.querySelector('#' + id + ' .m-input');
@@ -152,7 +226,8 @@ function openModal(id) {
}
function closeModal(id) {
document.getElementById(id).classList.add('hidden');
if (activeTab) activeTab.term.focus();
const leaf = activeTab && activeTab.activeLeaf;
if (leaf) leaf.term.focus();
}
function bgClose(evt, id) {
if (evt.target.id === id) closeModal(id);
@@ -165,7 +240,7 @@ document.addEventListener('keydown', e => {
}
});
// ── Auth ──────────────────────────────────────────────────────────────
// ── Auth ──────────────────────────────────────────────────────────────
async function doAuth() {
const username = document.getElementById('fUser').value.trim();
const password = document.getElementById('fPass').value;
@@ -186,10 +261,17 @@ async function doAuth() {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
const data = await res.json();
if (data.ok) {
isAuthenticated = true; // runtime flag: future newTab() calls will connect
isAuthenticated = true;
document.getElementById('authOverlay').classList.add('hidden');
tabs.forEach(t => { if (!t.socket) connectTab(t); });
if (activeTab) activeTab.term.focus();
// Load or create workspace after login
const ws = await loadWorkspace();
if (ws && ws.tabs && ws.tabs.length) {
restoreWorkspace(ws);
} else {
newTab();
}
const leaf = activeTab && activeTab.activeLeaf;
if (leaf) leaf.term.focus();
} else {
showAuthErr(data.error || 'Authentication failed');
}
@@ -214,57 +296,108 @@ document.getElementById('fPass').addEventListener('keydown', e => {
if (e.key === 'Enter') doAuth();
});
// ── Tab management ────────────────────────────────────────────────────
// ══════════════════════════════════════════════════════════════════════
// PANE TREE
// ══════════════════════════════════════════════════════════════════════
//
// Each tab:
// id 32-char hex session ID (server PTY key)
// term xterm.js Terminal
// fit FitAddon
// pane .term-pane <div>
// socket WebSocket /ws/<id>
// tabEl .tab-item <div>
// Leaf node: { type:'leaf', id, term, fit, socket, el, parent }
// Split node: { type:'split', dir:'h'|'v', a, b, ratio, el, divEl, parent }
//
// The "+" button lives inside #tabList; new tab elements are inserted
// before it so "+" always appears right after the last tab.
//
// Tab IDs are encoded in the URL hash (#t=id1,id2,...) so the link
// button produces a URL that reopens the same sessions in another browser.
// dir 'h' → side-by-side (flex-direction:row, vertical divider)
// dir 'v' → stacked (flex-direction:column, horizontal divider)
function newTab(sessionId) {
function walkLeaves(node, fn) {
if (!node) return;
if (node.type === 'leaf') { fn(node); return; }
walkLeaves(node.a, fn);
walkLeaves(node.b, fn);
}
function countLeaves(node) {
if (!node || node.type === 'leaf') return node ? 1 : 0;
return countLeaves(node.a) + countLeaves(node.b);
}
function findFirstLeaf(node) {
return node.type === 'leaf' ? node : findFirstLeaf(node.a);
}
function refitAll(tab) {
if (tab) walkLeaves(tab.root, l => { try { l.fit.fit(); } catch(_) {} });
}
// Replace oldNode with newNode in the JS tree and DOM.
function replaceNode(tab, oldNode, newNode) {
const p = oldNode.parent;
newNode.parent = p;
if (!p) {
tab.root = newNode;
tab.pane.innerHTML = '';
tab.pane.appendChild(newNode.el);
} else {
if (p.a === oldNode) p.a = newNode; else p.b = newNode;
p.el.replaceChild(newNode.el, oldNode.el);
}
}
function applyFlex(splitNode) {
const { a, b, dir, ratio } = splitNode;
const cross = dir === 'h' ? 'height' : 'width';
a.el.style.flex = `0 0 calc(${ratio * 100}% - 2px)`;
a.el.style[cross] = '100%';
a.el.style.minWidth = '0';
a.el.style.minHeight = '0';
a.el.style.overflow = 'hidden';
b.el.style.flex = '1 1 0%';
b.el.style[cross] = '100%';
b.el.style.minWidth = '0';
b.el.style.minHeight = '0';
b.el.style.overflow = 'hidden';
}
function refreshActiveHighlight(tab) {
const multi = countLeaves(tab.root) > 1;
walkLeaves(tab.root, l => {
l.el.classList.toggle('pane-active', multi && l === tab.activeLeaf);
});
}
function setActiveLeaf(tab, leaf) {
tab.activeLeaf = leaf;
refreshActiveHighlight(tab);
try { leaf.fit.fit(); } catch(_) {}
leaf.term.focus();
updateStatus();
}
// ── Create leaf ────────────────────────────────────────────────────────
function createLeaf(sessionId) {
const id = sessionId || randHexClient(16);
const tabNewBtn = document.getElementById('tabNew');
tabCounter++;
const tabLabel = 'bash ' + tabCounter;
// Terminal pane
const pane = document.createElement('div');
pane.className = 'term-pane';
pane.style.display = 'none';
document.getElementById('termContainer').appendChild(pane);
const el = document.createElement('div');
el.className = 'term-pane';
const term = new Terminal({
theme: TERM_THEME,
cursorBlink: true, fontSize: 14, scrollback: 20000,
fontFamily: '"JetBrains Mono","Fira Mono",monospace',
theme: TERM_THEME, cursorBlink: true, fontSize: 14,
scrollback: 20000, fontFamily: '"JetBrains Mono","Fira Mono",monospace',
});
const fit = new FitAddon.FitAddon();
term.loadAddon(fit);
term.open(pane);
term.open(el);
const tab = { id, label: tabLabel, term, fit, pane, socket: null, tabEl: null };
tabs.push(tab);
const leaf = { type: 'leaf', id, term, fit, socket: null, el, parent: null };
el.addEventListener('mousedown', () => {
if (activeTab && activeTab.activeLeaf !== leaf) setActiveLeaf(activeTab, leaf);
});
// Per-terminal key handler
term.attachCustomKeyEventHandler(evt => {
if (evt.type !== 'keydown') return true;
const C = evt.ctrlKey, S = evt.shiftKey, A = evt.altKey;
if (C && S && evt.code === 'KeyC') {
const sel = term.getSelection();
if (sel) navigator.clipboard.writeText(sel).then(
() => toast('Copied!', 'ok'),
() => toast('Copy failed', 'err')
);
() => toast('Copied!', 'ok'), () => toast('Copy failed', 'err'));
return false;
}
if (C && evt.code === 'KeyV') { pasteToTerminal(); return false; }
@@ -273,27 +406,231 @@ function newTab(sessionId) {
return true;
});
// Tab button — inserted BEFORE the "+" button so "+" stays at end
return leaf;
}
// ── Split ──────────────────────────────────────────────────────────────
function splitPane(dir) {
const tab = activeTab;
if (!tab || !tab.activeLeaf) return;
const leaf = tab.activeLeaf;
const newLeaf = createLeaf();
const splitEl = document.createElement('div');
splitEl.className = dir === 'h' ? 'split-h' : 'split-v';
const divEl = document.createElement('div');
divEl.className = dir === 'h' ? 'split-div-h' : 'split-div-v';
const splitNode = {
type: 'split', dir, a: leaf, b: newLeaf,
ratio: 0.5, el: splitEl, divEl, parent: null,
};
// replaceNode uses leaf.parent (old parent) — set new parents AFTER
replaceNode(tab, leaf, splitNode);
leaf.parent = splitNode;
newLeaf.parent = splitNode;
splitEl.appendChild(leaf.el);
splitEl.appendChild(divEl);
splitEl.appendChild(newLeaf.el);
applyFlex(splitNode);
setupDivider(splitNode);
if (isAuthenticated) connectLeaf(newLeaf);
setActiveLeaf(tab, newLeaf);
refreshActiveHighlight(tab);
setTimeout(() => refitAll(tab), 30);
saveWorkspace();
}
function setupDivider(splitNode) {
const { divEl, el, dir } = splitNode;
divEl.addEventListener('mousedown', e => {
e.preventDefault();
const rect = el.getBoundingClientRect();
const total = dir === 'h' ? rect.width : rect.height;
const origin = dir === 'h' ? rect.left : rect.top;
function onMove(ev) {
const pos = (dir === 'h' ? ev.clientX : ev.clientY) - origin;
splitNode.ratio = Math.max(0.1, Math.min(0.9, pos / total));
applyFlex(splitNode);
refitAll(activeTab);
}
function onUp() {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
document.body.style.cursor = document.body.style.userSelect = '';
saveWorkspace(); // persist ratio after drag
}
document.body.style.cursor = dir === 'h' ? 'col-resize' : 'row-resize';
document.body.style.userSelect = 'none';
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
});
}
// ── Close pane ─────────────────────────────────────────────────────────
function closePane() {
const tab = activeTab;
if (!tab || !tab.activeLeaf || !tab.activeLeaf.parent) return;
const leaf = tab.activeLeaf;
const splitNode = leaf.parent;
const sibling = splitNode.a === leaf ? splitNode.b : splitNode.a;
if (leaf.socket) { leaf.socket.onclose = null; leaf.socket.close(); }
leaf.term.dispose();
replaceNode(tab, splitNode, sibling);
sibling.el.removeAttribute('style');
const next = findFirstLeaf(sibling);
setActiveLeaf(tab, next);
refreshActiveHighlight(tab);
refitAll(tab);
saveWorkspace();
}
// ══════════════════════════════════════════════════════════════════════
// TAB MANAGEMENT
// ══════════════════════════════════════════════════════════════════════
// Build the label span with click + right-click rename handlers.
function buildLabelSpan(tab) {
const span = document.createElement('span');
span.className = 'tab-label';
span.textContent = tab.label;
span.addEventListener('click', () => switchTab(tab));
span.addEventListener('contextmenu', e => { e.preventDefault(); startRename(tab); });
return span;
}
// Inline tab rename: right-click → input → Enter/blur commit, Escape cancel.
function startRename(tab) {
const labelSpan = tab.tabEl.querySelector('.tab-label');
if (!labelSpan) return;
const oldLabel = tab.label;
const input = document.createElement('input');
input.className = 'tab-rename-input';
input.value = oldLabel;
labelSpan.replaceWith(input);
input.focus();
input.select();
let committed = false;
function commit() {
if (committed) return;
committed = true;
const val = input.value.trim();
tab.label = val || oldLabel;
input.replaceWith(buildLabelSpan(tab));
saveWorkspace();
}
function cancel() {
if (committed) return;
committed = true;
input.replaceWith(buildLabelSpan(tab));
}
input.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); commit(); }
if (e.key === 'Escape') { e.preventDefault(); cancel(); }
});
input.addEventListener('blur', commit);
}
// Create and insert the tab bar button for a tab.
function addTabButton(tab) {
const tabNewBtn = document.getElementById('tabNew');
const tabEl = document.createElement('div');
tabEl.className = 'tab-item';
tabEl.title = 'Session: ' + id;
tabEl.innerHTML =
`<span class="tab-label">${tabLabel}</span>` +
`<button class="tab-x" title="Close tab (Alt+W)">&#215;</button>`;
tabEl.querySelector('.tab-label').addEventListener('click', () => switchTab(tab));
tabEl.querySelector('.tab-x').addEventListener('click', ev => {
ev.stopPropagation(); closeTab(tab);
});
tabNewBtn.parentElement.insertBefore(tabEl, tabNewBtn); // right before "+"
const closeBtn = document.createElement('button');
closeBtn.className = 'tab-x';
closeBtn.title = 'Close tab (Alt+W)';
closeBtn.innerHTML = '&#215;';
closeBtn.addEventListener('click', e => { e.stopPropagation(); closeTab(tab); });
tabEl.appendChild(buildLabelSpan(tab));
tabEl.appendChild(closeBtn);
tabNewBtn.parentElement.insertBefore(tabEl, tabNewBtn);
tab.tabEl = tabEl;
}
// Create a new tab with fresh PTY leaf.
function newTab(tabId, sessionId) {
tabId = tabId || randHexClient(16);
tabCounter++;
const label = 'bash ' + tabCounter;
const pane = document.createElement('div');
pane.className = 'tab-pane';
pane.style.display = 'none';
document.getElementById('termContainer').appendChild(pane);
const rootLeaf = createLeaf(sessionId);
pane.appendChild(rootLeaf.el);
const tab = {
tabId,
label,
pane,
root: rootLeaf,
activeLeaf: rootLeaf,
tabEl: null,
};
tabs.push(tab);
addTabButton(tab);
switchTab(tab);
updateURLHash();
if (isAuthenticated) connectTab(tab); // connect immediately if already authed
saveWorkspace();
if (isAuthenticated) connectLeaf(rootLeaf);
return tab;
}
// Restore a single tab from workspace data (without calling saveWorkspace).
function restoreTab(tabData) {
tabCounter++;
const pane = document.createElement('div');
pane.className = 'tab-pane';
pane.style.display = 'none';
document.getElementById('termContainer').appendChild(pane);
const root = deserializePane(tabData.root);
pane.appendChild(root.el);
const tab = {
tabId: tabData.tab_id,
label: tabData.label || ('bash ' + tabCounter),
pane,
root,
activeLeaf: findFirstLeaf(root),
tabEl: null,
};
tabs.push(tab);
addTabButton(tab);
if (isAuthenticated) {
walkLeaves(root, l => connectLeaf(l));
}
return tab;
}
// Restore all tabs from saved workspace data.
function restoreWorkspace(ws) {
ws.tabs.forEach(tabData => restoreTab(tabData));
if (!tabs.length) { newTab(); return; }
switchTab(tabs[0]);
}
function switchTab(tab) {
if (activeTab) {
activeTab.pane.style.display = 'none';
@@ -302,73 +639,69 @@ function switchTab(tab) {
activeTab = tab;
tab.pane.style.display = 'block';
tab.tabEl.classList.add('active');
tab.fit.fit();
tab.term.focus();
refitAll(tab);
if (tab.activeLeaf) tab.activeLeaf.term.focus();
updateStatus();
}
function closeTab(tab) {
if (tabs.length === 1) return; // never close the last tab
if (tab.socket) {
tab.socket.onclose = null; // prevent auto-reconnect
tab.socket.close();
}
tab.term.dispose();
if (tabs.length === 1) return;
walkLeaves(tab.root, l => {
if (l.socket) { l.socket.onclose = null; l.socket.close(); }
l.term.dispose();
});
tab.pane.remove();
tab.tabEl.remove();
const idx = tabs.indexOf(tab);
tabs.splice(idx, 1);
if (activeTab === tab)
switchTab(tabs[Math.min(idx, tabs.length - 1)]);
updateURLHash();
if (activeTab === tab) switchTab(tabs[Math.min(idx, tabs.length - 1)]);
saveWorkspace();
}
// ── WebSocket (per tab) ───────────────────────────────────────────────
function connectTab(tab) {
tab.socket = new WebSocket('wss://' + location.host + '/ws/' + tab.id);
tab.socket.binaryType = 'arraybuffer';
// ── WebSocket per leaf ─────────────────────────────────────────────────
tab.socket.onopen = () => {
tab.fit.fit();
sendResizeFor(tab);
if (activeTab === tab) { updateStatus(); tab.term.focus(); }
function connectLeaf(leaf) {
leaf.socket = new WebSocket('wss://' + location.host + '/ws/' + leaf.id);
leaf.socket.binaryType = 'arraybuffer';
leaf.socket.onopen = () => {
leaf.fit.fit();
sendResizeFor(leaf);
if (activeTab && activeTab.activeLeaf === leaf) { updateStatus(); leaf.term.focus(); }
};
tab.socket.onmessage = e => {
leaf.socket.onmessage = e => {
if (typeof e.data === 'string') {
try {
const msg = JSON.parse(e.data);
if (msg.type === 'session' && activeTab === tab)
setStatus((msg.new ? 'new' : 'resumed') + ' ' + tab.id.slice(0, 8) + '...', 'ok');
if (msg.type === 'session' && activeTab && activeTab.activeLeaf === leaf)
setStatus((msg.new ? 'new' : 'resumed') + ' pane:' + leaf.id.slice(0, 8), 'ok');
} catch(_) {}
return;
}
tab.term.write(new Uint8Array(e.data));
leaf.term.write(new Uint8Array(e.data));
};
tab.socket.onclose = () => {
if (activeTab === tab) setStatus('reconnecting...', 'err');
setTimeout(() => connectTab(tab), 2000);
leaf.socket.onclose = () => {
if (activeTab && activeTab.activeLeaf === leaf) setStatus('reconnecting...', 'err');
setTimeout(() => connectLeaf(leaf), 2000);
};
tab.socket.onerror = () => tab.socket.close();
leaf.socket.onerror = () => leaf.socket.close();
tab.term.onData(d => {
if (tab.socket && tab.socket.readyState === WebSocket.OPEN) tab.socket.send(d);
leaf.term.onData(d => {
if (leaf.socket && leaf.socket.readyState === WebSocket.OPEN) leaf.socket.send(d);
});
tab.term.onResize(() => sendResizeFor(tab));
leaf.term.onResize(() => sendResizeFor(leaf));
}
function sendResizeFor(tab) {
if (tab.socket && tab.socket.readyState === WebSocket.OPEN)
tab.socket.send(JSON.stringify({ type: 'resize', cols: tab.term.cols, rows: tab.term.rows }));
function sendResizeFor(leaf) {
if (leaf.socket && leaf.socket.readyState === WebSocket.OPEN)
leaf.socket.send(JSON.stringify({ type: 'resize', cols: leaf.term.cols, rows: leaf.term.rows }));
}
window.addEventListener('resize', () => { if (activeTab) activeTab.fit.fit(); });
window.addEventListener('resize', () => { if (activeTab) refitAll(activeTab); });
// ── Upload ────────────────────────────────────────────────────────────
// ── Upload ────────────────────────────────────────────────────────────
function onFileChosen() {
const f = document.getElementById('upFile').files[0];
const zone = document.getElementById('fileZone');
@@ -381,15 +714,17 @@ async function doUpload() {
const f = document.getElementById('upFile').files[0];
if (!f) { modalFb('upFb', 'Select a file first', 'err'); return; }
const leaf = activeTab && activeTab.activeLeaf;
if (!leaf) { modalFb('upFb', 'No active terminal', 'err'); return; }
const btn = document.getElementById('upBtn');
const form = new FormData();
form.append('file', f);
form.append('dest', document.getElementById('upDest').value.trim());
form.append('sid', activeTab ? activeTab.id : SESSION_ID);
form.append('sid', leaf.id);
btn.disabled = true; btn.classList.add('busy');
modalFb('upFb', '', '');
try {
const res = await fetch('/upload', { method: 'POST', body: form });
const data = await res.json();
@@ -408,7 +743,7 @@ async function doUpload() {
}
}
// ── Download ──────────────────────────────────────────────────────────
// ── Download ──────────────────────────────────────────────────────────
function doDownload() {
const p = document.getElementById('dlPath').value.trim();
if (!p) { modalFb('dlFb', 'Enter a file path', 'err'); return; }
@@ -426,22 +761,17 @@ function modalFb(id, msg, type) {
el.className = 'm-fb' + (type ? ' ' + type : '');
}
// ── Bootstrap ─────────────────────────────────────────────────────────
//
// If the URL hash encodes tab IDs, open all of them (another browser
// shared the link). Otherwise open a single tab with the server-provided
// SESSION_ID.
(function bootstrap() {
const hashIds = getTabIDsFromHash();
if (hashIds && hashIds.length > 0) {
// Restore all sessions from the shared link.
// SESSION_ID might or might not be in the list — use hash as source of truth.
hashIds.forEach(id => newTab(id));
// ── Bootstrap ─────────────────────────────────────────────────────────
(async function bootstrap() {
if (isAuthenticated) {
document.getElementById('authOverlay').classList.add('hidden');
const ws = await loadWorkspace();
if (ws && ws.tabs && ws.tabs.length) {
restoreWorkspace(ws);
} else {
newTab(SESSION_ID);
newTab();
}
if (!isAuthenticated) {
} else {
setTimeout(() => document.getElementById('fUser').focus(), 80);
}
})();
+38 -4
View File
@@ -122,14 +122,48 @@
<span class="status-label" id="statusLabel">connecting...</span>
</div>
<div class="tb-right">
<!-- Copy session link -->
<button class="tb-btn accent" id="copyBtn" onclick="copyLink()" title="Copy session link">
<!-- Split left/right (Alt+\) -->
<button class="tb-btn" onclick="splitPane('h')" title="Split left/right (Alt+\)">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="2" y="3" width="20" height="18" rx="2"/>
<line x1="12" y1="3" x2="12" y2="21"/>
</svg>
Split H
</button>
<!-- Split top/bottom (Alt+-) -->
<button class="tb-btn" onclick="splitPane('v')" title="Split top/bottom (Alt+-)">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="2" y="3" width="20" height="18" rx="2"/>
<line x1="2" y1="12" x2="22" y2="12"/>
</svg>
Split V
</button>
<!-- Close active pane (Alt+X) -->
<button class="tb-btn" onclick="closePane()" title="Close active pane (Alt+X)">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="2" y="3" width="20" height="18" rx="2"/>
<line x1="9" y1="9" x2="15" y2="15"/><line x1="15" y1="9" x2="9" y2="15"/>
</svg>
Pane X
</button>
<div class="tb-sep"></div>
<!-- Copy workspace link -->
<button class="tb-btn accent" id="copyBtn" onclick="copyLink()" title="Copy workspace link">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="9" y="9" width="13" height="13" rx="2"/>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
</svg>
Link
</button>
<!-- End Session -->
<button class="tb-btn tb-danger" onclick="endSession()" title="End session — clears saved layout, next open starts fresh">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
<polyline points="16 17 21 12 16 7"/>
<line x1="21" y1="12" x2="9" y2="12"/>
</svg>
End
</button>
<!-- Upload -->
<button class="tb-btn" onclick="openModal('upOverlay')" title="Upload file">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
@@ -153,8 +187,8 @@
<div class="toast" id="toast"></div>
<script>
// Session context injected server-side consumed by app.js
const SESSION_ID = "[[SESSION_ID]]";
// Workspace context injected server-side, consumed by app.js
const WORKSPACE_ID = "[[WORKSPACE_ID]]";
const AUTHED = [[AUTHED]];
</script>
<script src="/static/app.js"></script>
+118
View File
@@ -0,0 +1,118 @@
package internals
import (
"encoding/json"
"net/http"
"strings"
"sync"
)
// credsMu guards concurrent reads/writes of appCreds.Workspaces from HTTP
// handlers. Credential fields (Username/Hash/etc.) are only written at
// startup via CLI flags that call os.Exit, so they don't need the lock.
var credsMu sync.Mutex
// WorkspacePaneLayout is a recursive pane tree.
// Leaf nodes own a PTY session; split nodes contain two children.
type WorkspacePaneLayout struct {
Type string `json:"type"` // "leaf" | "split"
ID string `json:"id,omitempty"` // PTY session hex ID (leaf only)
Dir string `json:"dir,omitempty"` // "h" | "v" (split only)
Ratio float64 `json:"ratio,omitempty"` // 0.10.9 (split only)
A *WorkspacePaneLayout `json:"a,omitempty"`
B *WorkspacePaneLayout `json:"b,omitempty"`
}
// WorkspaceTabLayout stores one tab's label and pane tree.
type WorkspaceTabLayout struct {
TabID string `json:"tab_id"`
Label string `json:"label"`
Root WorkspacePaneLayout `json:"root"`
}
// WorkspaceLayout is the full layout stored per workspace ID in gws-creds.json.
type WorkspaceLayout struct {
ID string `json:"id"`
Tabs []WorkspaceTabLayout `json:"tabs"`
}
// handleWorkspaceAPI dispatches GET / PUT / DELETE for /api/workspace/<id>.
// All methods require auth.
func handleWorkspaceAPI(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if !isAuthed(r) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"unauthorized"}`))
return
}
id := strings.TrimPrefix(r.URL.Path, "/api/workspace/")
if !validID(id) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"invalid id"}`))
return
}
switch r.Method {
case http.MethodGet:
workspaceGet(w, id)
case http.MethodPut:
workspacePut(w, r, id)
case http.MethodDelete:
workspaceDelete(w, id)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte(`{"error":"method not allowed"}`))
}
}
func workspaceGet(w http.ResponseWriter, id string) {
credsMu.Lock()
ws := appCreds.Workspaces[id]
credsMu.Unlock()
if ws == nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(`{"error":"not found"}`))
return
}
json.NewEncoder(w).Encode(ws) //nolint:errcheck
}
func workspacePut(w http.ResponseWriter, r *http.Request, id string) {
var ws WorkspaceLayout
if err := json.NewDecoder(r.Body).Decode(&ws); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"bad json"}`))
return
}
ws.ID = id
credsMu.Lock()
if appCreds.Workspaces == nil {
appCreds.Workspaces = make(map[string]*WorkspaceLayout)
}
appCreds.Workspaces[id] = &ws
err := saveCreds(appCreds)
credsMu.Unlock()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"error":"save failed"}`))
return
}
w.Write([]byte(`{"ok":true}`))
}
func workspaceDelete(w http.ResponseWriter, id string) {
credsMu.Lock()
if appCreds.Workspaces != nil {
delete(appCreds.Workspaces, id)
}
err := saveCreds(appCreds)
credsMu.Unlock()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"error":"save failed"}`))
return
}
w.Write([]byte(`{"ok":true}`))
}
-3
View File
@@ -1,3 +0,0 @@
#!/bin/bash
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=64000
CLAUDE_CODE_MAX_OUTPUT_TOKENS=64000 claude --resume dd1f4084-d53b-4d1a-9401-cb605b5c7718