Commit 2ba3277f
2ba3277f5eb5Merged
Scott Nixon <[email protected]> ยท 9 months ago ยท 4 files ยท ~4 modified
Description
Add terminal session persistence across browser refreshes
PTY sessions now survive WebSocket disconnects. Sessions are stored in a shared map keyed by UUID; the client saves session_id in sessionStorage and reconnects on refresh. Idle sessions are reaped after 30 minutes.
Extract inline xterm.js init from shell HTML into public/js/xterm-setup.js with auto-reconnect and session protocol support.
Details
- Commit
- 2ba3277f5eb5
- Parent
- 323dd3c7d485
crates/attractor-web/public/js/xterm-setup.jsmodifiedView file
@@ -1,128 +1,134 @@
1-
// xterm.js initialization for embedded Claude Code terminal2-
// Loaded via <script> tag in the shell HTML1+
// xterm.js terminal initialization โ loaded as ES module from CDN2+
import { Terminal } from 'https://cdn.jsdelivr.net/npm/@xterm/[email protected]/+esm';3+
import { FitAddon } from 'https://cdn.jsdelivr.net/npm/@xterm/[email protected]/+esm';4+
import { WebLinksAddon } from 'https://cdn.jsdelivr.net/npm/@xterm/[email protected]/+esm';5+
6+
window.initTerminal = function(containerId) {7+
const container = document.getElementById(containerId);8+
if (!container) {9+
console.error('Terminal container not found:', containerId);10+
return;11+
}312
4-
import { Terminal } from '@xterm/xterm';5-
import { FitAddon } from '@xterm/addon-fit';6-
import { WebLinksAddon } from '@xterm/addon-web-links';13+
const terminal = new Terminal({14+
cursorBlink: true,15+
fontSize: 14,16+
fontFamily: '"SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas, monospace',17+
theme: {18+
background: '#1e1e2e',19+
foreground: '#cdd6f4',20+
cursor: '#f5e0dc',21+
selectionBackground: '#585b70',22+
black: '#45475a',23+
red: '#f38ba8',24+
green: '#a6e3a1',25+
yellow: '#f9e2af',26+
blue: '#89b4fa',27+
magenta: '#f5c2e7',28+
cyan: '#94e2d5',29+
white: '#bac2de',30+
brightBlack: '#585b70',31+
brightRed: '#f38ba8',32+
brightGreen: '#a6e3a1',33+
brightYellow: '#f9e2af',34+
brightBlue: '#89b4fa',35+
brightMagenta: '#f5c2e7',36+
brightCyan: '#94e2d5',37+
brightWhite: '#a6adc8',38+
},39+
allowProposedApi: true,40+
});741
8-
let terminal = null;9-
let fitAddon = null;10-
let ws = null;42+
const fitAddon = new FitAddon();43+
terminal.loadAddon(fitAddon);44+
terminal.loadAddon(new WebLinksAddon());45+
terminal.open(container);46+
fitAddon.fit();1147
12-
/**13-
* Initialize xterm.js terminal in the given container element.14-
* Connects to WebSocket PTY bridge at /api/terminal/ws.15-
*/16-
window.initTerminal = function(containerId) {17-
const container = document.getElementById(containerId);18-
if (!container) {19-
console.error('Terminal container not found:', containerId);20-
return;21-
}48+
let ws = null;49+
let reconnectTimer = null;50+
const RECONNECT_DELAY = 1000;2251
23-
// Create terminal24-
terminal = new Terminal({25-
cursorBlink: true,26-
fontSize: 14,27-
fontFamily: '"SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas, monospace',28-
theme: {29-
background: '#1e1e2e',30-
foreground: '#cdd6f4',31-
cursor: '#f5e0dc',32-
selectionBackground: '#585b70',33-
black: '#45475a',34-
red: '#f38ba8',35-
green: '#a6e3a1',36-
yellow: '#f9e2af',37-
blue: '#89b4fa',38-
magenta: '#f5c2e7',39-
cyan: '#94e2d5',40-
white: '#bac2de',41-
brightBlack: '#585b70',42-
brightRed: '#f38ba8',43-
brightGreen: '#a6e3a1',44-
brightYellow: '#f9e2af',45-
brightBlue: '#89b4fa',46-
brightMagenta: '#f5c2e7',47-
brightCyan: '#94e2d5',48-
brightWhite: '#a6adc8',49-
},50-
allowProposedApi: true,51-
});52+
function getSessionId() {53+
return sessionStorage.getItem('terminal_session_id');54+
}5255
53-
fitAddon = new FitAddon();54-
terminal.loadAddon(fitAddon);55-
terminal.loadAddon(new WebLinksAddon());56+
function setSessionId(id) {57+
sessionStorage.setItem('terminal_session_id', id);58+
}5659
57-
terminal.open(container);58-
fitAddon.fit();60+
function buildWsUrl() {61+
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';62+
let url = protocol + '//' + window.location.host + '/api/terminal/ws';63+
const sid = getSessionId();64+
if (sid) {65+
url += '?session=' + encodeURIComponent(sid);66+
}67+
return url;68+
}5969
60-
// Connect WebSocket to PTY bridge61-
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';62-
const wsUrl = `${protocol}//${window.location.host}/api/terminal/ws`;63-
ws = new WebSocket(wsUrl);64-
ws.binaryType = 'arraybuffer';70+
function connect() {71+
if (reconnectTimer) {72+
clearTimeout(reconnectTimer);73+
reconnectTimer = null;74+
}6575
66-
ws.onopen = function() {67-
console.log('Terminal WebSocket connected');68-
// Send initial size69-
const dims = { type: 'resize', cols: terminal.cols, rows: terminal.rows };70-
ws.send(JSON.stringify(dims));71-
};76+
const wsUrl = buildWsUrl();77+
ws = new WebSocket(wsUrl);78+
ws.binaryType = 'arraybuffer';7279
73-
ws.onmessage = function(event) {74-
if (event.data instanceof ArrayBuffer) {75-
terminal.write(new Uint8Array(event.data));76-
} else {77-
terminal.write(event.data);78-
}79-
};80+
ws.onopen = function() {81+
ws.send(JSON.stringify({ type: 'resize', cols: terminal.cols, rows: terminal.rows }));82+
};8083
81-
ws.onclose = function() {82-
console.log('Terminal WebSocket closed');83-
terminal.write('\r\n\x1b[31m[Connection closed]\x1b[0m\r\n');84-
};84+
ws.onmessage = function(event) {85+
if (event.data instanceof ArrayBuffer) {86+
terminal.write(new Uint8Array(event.data));87+
} else {88+
// Check for session protocol message89+
try {90+
const msg = JSON.parse(event.data);91+
if (msg.type === 'session' && msg.session_id) {92+
setSessionId(msg.session_id);93+
console.log('Terminal session:', msg.session_id);94+
return;95+
}96+
} catch (_) {97+
// Not JSON โ regular terminal output98+
}99+
terminal.write(event.data);100+
}101+
};85102
86-
ws.onerror = function(err) {87-
console.error('Terminal WebSocket error:', err);88-
};103+
ws.onclose = function() {104+
terminal.write('\r\n\x1b[33m[Reconnecting...]\x1b[0m\r\n');105+
scheduleReconnect();106+
};89107
90-
// Forward terminal input to WebSocket91-
terminal.onData(function(data) {92-
if (ws && ws.readyState === WebSocket.OPEN) {93-
ws.send(new TextEncoder().encode(data));108+
ws.onerror = function(err) {109+
console.error('Terminal WebSocket error:', err);110+
};94111
}95-
});96112
97-
// Handle terminal resize98-
terminal.onResize(function(size) {99-
if (ws && ws.readyState === WebSocket.OPEN) {100-
const dims = { type: 'resize', cols: size.cols, rows: size.rows };101-
ws.send(JSON.stringify(dims));113+
function scheduleReconnect() {114+
if (!reconnectTimer) {115+
reconnectTimer = setTimeout(connect, RECONNECT_DELAY);116+
}102117
}103-
});104118
105-
// Fit on window resize106-
const resizeObserver = new ResizeObserver(function() {107-
if (fitAddon) {108-
fitAddon.fit();109-
}110-
});111-
resizeObserver.observe(container);119+
terminal.onData(function(data) {120+
if (ws && ws.readyState === WebSocket.OPEN) {121+
ws.send(new TextEncoder().encode(data));122+
}123+
});124+
terminal.onResize(function(size) {125+
if (ws && ws.readyState === WebSocket.OPEN) {126+
ws.send(JSON.stringify({ type: 'resize', cols: size.cols, rows: size.rows }));127+
}128+
});112129
113-
return terminal;114-
};130+
new ResizeObserver(function() { fitAddon.fit(); }).observe(container);115131
116-
/**117-
* Dispose of terminal and close WebSocket.118-
*/119-
window.disposeTerminal = function() {120-
if (ws) {121-
ws.close();122-
ws = null;123-
}124-
if (terminal) {125-
terminal.dispose();126-
terminal = null;127-
}132+
connect();133+
console.log('Terminal initialized');128134
};crates/attractor-web/src/main.rsmodifiedView file
Loading diffโฆ
crates/attractor-web/src/server/mod.rsmodifiedView file
Loading diffโฆ
crates/attractor-web/src/server/terminal.rsmodifiedView file
Loading diffโฆ