/workspaces refactor

This commit is contained in:
2026-02-19 16:07:00 +00:00
parent 4dde3aec66
commit 9870fa7ae8
21 changed files with 716 additions and 227 deletions
+98 -28
View File
@@ -15,6 +15,11 @@ const ohMyZshSource = isDocker ? '/opt/oh-my-zsh' : null;
const port = Number(process.env.TERMINAL_PTY_PORT ?? '5337');
const host = process.env.TERMINAL_PTY_HOST ?? '127.0.0.1';
const BUFFER_MAX = 50 * 1024;
/** @type {Map<string, { term: import('node-pty').IPty, buffer: string, cols: number, rows: number, ws: import('ws').WebSocket | null, initConfig: object }>} */
const sessions = new Map();
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('terminal-sidecar');
@@ -50,7 +55,6 @@ const ensureUserFiles = async (homeDir) => {
if (ohMyZshSource && existsSync(ohMyZshSource)) {
await cp(ohMyZshSource, ohMyZshPath, { recursive: true });
} else {
// Clone oh-my-zsh on first run (host mode)
const proc = Bun.spawn({
cmd: ['git', 'clone', '--depth=1', 'https://github.com/ohmyzsh/ohmyzsh.git', ohMyZshPath],
stdout: 'ignore',
@@ -60,7 +64,6 @@ const ensureUserFiles = async (homeDir) => {
}
}
// Install starship on host if missing (not needed in Docker)
if (!isDocker) {
const starshipBin = join(homeDir, '.local', 'bin', 'starship');
if (!existsSync(starshipBin)) {
@@ -75,20 +78,15 @@ const ensureUserFiles = async (homeDir) => {
}
};
wss.on('connection', (ws) => {
let term = null;
let initialized = false;
const appendBuffer = (session, data) => {
session.buffer += data;
if (session.buffer.length > BUFFER_MAX) {
session.buffer = session.buffer.slice(-BUFFER_MAX);
}
};
const cleanup = () => {
if (term) {
try {
term.kill();
} catch {
// ignore
}
}
term = null;
};
wss.on('connection', (ws) => {
let currentSessionId = null;
ws.on('message', async (data) => {
let msg;
@@ -98,13 +96,58 @@ wss.on('connection', (ws) => {
return;
}
if (msg.type === 'init' && !initialized) {
if (msg.type === 'init') {
const sessionId = msg.sessionId;
if (!sessionId) return;
currentSessionId = sessionId;
const existing = sessions.get(sessionId);
console.log(`[sidecar] init sessionId=${sessionId} existing=${!!existing} total=${sessions.size}`);
if (existing) {
// Evict old WS if still attached
if (existing.ws && existing.ws !== ws) {
sendJson(existing.ws, { type: 'detached' });
try {
existing.ws.close();
} catch {
// ignore
}
}
existing.ws = ws;
// Replay buffer
if (existing.buffer.length > 0) {
sendJson(ws, { type: 'output', data: existing.buffer });
}
// Resize PTY to new client dimensions
const cols = msg.cols ?? existing.cols;
const rows = msg.rows ?? existing.rows;
if (cols > 0 && rows > 0 && (cols !== existing.cols || rows !== existing.rows)) {
existing.cols = cols;
existing.rows = rows;
try {
existing.term.resize(cols, rows);
} catch {
// ignore
}
}
return;
}
// New session — spawn PTY
const shell = msg.shell ?? { command: '/bin/bash', args: ['-i'] };
const cwd = msg.cwd ?? process.cwd();
const homeDir = msg.homeDir ?? process.cwd();
const userLabel = msg.userLabel ?? 'officer';
const prompt = `${userLabel} in %~ %# `;
const bashPrompt = `${userLabel} \w \$ `;
const bashPrompt = `${userLabel} \\w \\$ `;
const cols = msg.cols ?? 80;
const rows = msg.rows ?? 24;
try {
await ensureUserFiles(homeDir);
@@ -112,11 +155,12 @@ wss.on('connection', (ws) => {
// ignore
}
let term;
try {
term = pty.spawn(shell.command, shell.args ?? [], {
name: 'xterm-256color',
cols: 80,
rows: 24,
cols,
rows,
cwd,
env: {
...process.env,
@@ -139,37 +183,63 @@ wss.on('connection', (ws) => {
return;
}
initialized = true;
const session = {
term,
buffer: '',
cols,
rows,
ws,
initConfig: { shell, cwd, homeDir, userLabel },
};
sessions.set(sessionId, session);
term.onData((output) => {
sendJson(ws, { type: 'output', data: output });
appendBuffer(session, output);
if (session.ws) {
sendJson(session.ws, { type: 'output', data: output });
}
});
term.onExit(() => {
sendJson(ws, { type: 'exit' });
cleanup();
if (session.ws) {
sendJson(session.ws, { type: 'exit' });
}
sessions.delete(sessionId);
});
return;
}
if (!term) return;
// Route other messages to current session
if (!currentSessionId) return;
const session = sessions.get(currentSessionId);
if (!session) return;
switch (msg.type) {
case 'input':
term.write(msg.data ?? '');
session.term.write(msg.data ?? '');
break;
case 'resize':
if (msg.cols > 0 && msg.rows > 0) term.resize(msg.cols, msg.rows);
if (msg.cols > 0 && msg.rows > 0) {
session.cols = msg.cols;
session.rows = msg.rows;
session.term.resize(msg.cols, msg.rows);
}
break;
case 'cwd':
if (msg.path) term.write(`cd ${JSON.stringify(msg.path)}\r`);
if (msg.path) session.term.write(`cd ${JSON.stringify(msg.path)}\r`);
break;
}
});
ws.on('close', () => {
cleanup();
// Detach WS from session — do NOT kill PTY
if (currentSessionId) {
const session = sessions.get(currentSessionId);
if (session && session.ws === ws) {
session.ws = null;
}
}
});
});
+114 -106
View File
@@ -1,19 +1,16 @@
import type { ServerWebSocket } from 'bun';
import { mkdirSync, existsSync, statSync } from 'node:fs';
import { dirname } from 'node:path';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { mkdirSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { getHomeDir } from '@@/data-path';
import { officerdb, Users } from 'officerdb';
type WSData = { userId: number; email: string };
type WSData = { userId: number; email: string; role: string; sandboxed: boolean; sessionId?: string };
type ShellInfo = { command: string; args: string[]; name: string };
type TerminalMode = 'host' | 'docker';
type BridgeSession = {
client: ServerWebSocket<WSData>;
sidecar: WebSocket | null;
mode: TerminalMode;
dockerId?: string;
dockerId: string;
port: number;
};
@@ -24,49 +21,14 @@ type ContainerInfo = {
port: number;
};
const HOST_SIDECAR_PORT = 5338;
const sessions = new Map<ServerWebSocket<WSData>, BridgeSession>();
const defaultSidecarPort = Number(process.env.TERMINAL_PTY_PORT ?? '5337');
const containerMapPath = join(getHomeDir(''), '..', 'terminal-containers.json');
let sidecarProcess: Bun.Subprocess | null = null;
let dockerImageReady = false;
let containersCache: Record<string, ContainerInfo> | null = null;
const resolveShell = (): ShellInfo => {
const envShell = process.env.SHELL?.trim();
if (envShell) {
const shellName = envShell.split('/').pop() ?? envShell;
return {
command: envShell,
args: shellName === 'zsh' ? ['-d', '-i'] : shellName === 'bash' ? ['-i'] : ['-i'],
name: shellName,
};
}
const candidates = ['/bin/zsh', '/usr/bin/zsh', '/bin/bash', '/usr/bin/bash'];
for (const candidate of candidates) {
if (existsSync(candidate)) {
const shellName = candidate.split('/').pop() ?? candidate;
return {
command: candidate,
args: shellName === 'zsh' ? ['-d', '-i'] : shellName === 'bash' ? ['-i'] : ['-i'],
name: shellName,
};
}
}
try {
const proc = Bun.spawnSync(['which', 'zsh'], { stdout: 'pipe', stderr: 'pipe' });
if (proc.exitCode === 0) {
const command = proc.stdout.toString().trim();
return { command, args: ['-d', '-i'], name: 'zsh' };
}
} catch {
// fall through
}
return { command: 'bash', args: ['-i'], name: 'bash' };
};
let hostSidecarProcess: ReturnType<typeof import('bun').spawn> | null = null;
const sendOutput = (ws: ServerWebSocket<WSData>, data: string) => {
try {
@@ -76,25 +38,8 @@ const sendOutput = (ws: ServerWebSocket<WSData>, data: string) => {
}
};
const startSidecar = (port: number) => {
if (sidecarProcess) return;
const nodePath = Bun.which('node') ?? 'node';
const sidecarPath = fileURLToPath(new URL('./pty-sidecar.mjs', import.meta.url));
sidecarProcess = Bun.spawn({
cmd: [nodePath, sidecarPath],
env: { ...process.env, TERMINAL_PTY_PORT: String(port), TERMINAL_PTY_HOST: '127.0.0.1' },
stdout: 'inherit',
stderr: 'inherit',
});
sidecarProcess.exited.then(() => {
sidecarProcess = null;
});
};
const connectSidecar = async (port: number, mode: TerminalMode): Promise<WebSocket> => {
if (mode === 'host') startSidecar(port);
const delays = mode === 'docker' ? [200, 300, 500, 800, 1200, 1600, 2000] : [50, 150, 300, 600, 1200];
const connectSidecar = async (port: number): Promise<WebSocket> => {
const delays = [200, 300, 500, 800, 1200, 1600, 2000];
let lastError: Error | null = null;
for (const delay of delays) {
@@ -130,17 +75,6 @@ const connectSidecar = async (port: number, mode: TerminalMode): Promise<WebSock
throw lastError ?? new Error('Terminal sidecar connection failed');
};
const getSettings = async (): Promise<{ terminalSandboxed?: boolean }> => {
const settingsPath = `${homedir()}/.config/officer.dev/server-settings.json`;
return await Bun.file(settingsPath)
.json()
.catch(() => ({}));
};
const prebuildDockerImage = async () => {
ensureDockerImage();
};
const ensureDockerImage = () => {
if (dockerImageReady) return;
const dockerPath = Bun.which('docker');
@@ -284,48 +218,127 @@ const ensureDockerContainer = async (email: string, userId: number, homeDir: str
return next;
};
void prebuildDockerImage();
const sidecarAlive = async (port: number): Promise<boolean> => {
try {
const res = await fetch(`http://127.0.0.1:${port}`, { signal: AbortSignal.timeout(500) });
return res.ok;
} catch {
return false;
}
};
const startHostSidecar = async () => {
if (await sidecarAlive(HOST_SIDECAR_PORT)) {
console.log(`[terminal] host sidecar already running on port ${HOST_SIDECAR_PORT}`);
return;
}
if (hostSidecarProcess) {
hostSidecarProcess.kill();
await hostSidecarProcess.exited.catch(() => {});
hostSidecarProcess = null;
}
const sidecarPath = fileURLToPath(new URL('./pty-sidecar.mjs', import.meta.url));
hostSidecarProcess = Bun.spawn({
cmd: ['bun', sidecarPath],
env: { ...process.env, TERMINAL_PTY_PORT: String(HOST_SIDECAR_PORT) },
stdout: 'inherit',
stderr: 'inherit',
});
console.log(`[terminal] host sidecar started on port ${HOST_SIDECAR_PORT}`);
};
export const initTerminalSidecars = async () => {
await startHostSidecar();
ensureDockerImage();
const users = await officerdb.select({ id: Users.id, email: Users.email }).from(Users);
for (const user of users) {
const homeDir = getHomeDir(user.email);
mkdirSync(dirname(homeDir), { recursive: true });
mkdirSync(homeDir, { recursive: true });
try {
await ensureDockerContainer(user.email, user.id, homeDir);
console.log(`[terminal] sidecar ready for ${user.email}`);
} catch (err) {
console.error(`[terminal] failed to start sidecar for ${user.email}:`, err);
}
}
};
const containerShell: ShellInfo = { command: '/bin/zsh', args: ['-d', '-i'], name: 'zsh' };
const containerHome = '/home/officer';
export const terminalWebsocket = {
async open(ws: ServerWebSocket<WSData>) {
const { email } = ws.data;
const { email, role, sandboxed } = ws.data;
if (!sandboxed && role !== 'Super Admin') {
sendOutput(ws, '\r\n[Permission denied] Host terminal requires Super Admin role.\r\n');
return;
}
if (!sandboxed) {
let sidecar: WebSocket | null = null;
try {
sidecar = await connectSidecar(HOST_SIDECAR_PORT);
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to connect host sidecar';
sendOutput(ws, `\r\n[Terminal error] ${message}\r\n`);
return;
}
sessions.set(ws, { client: ws, sidecar, dockerId: '', port: HOST_SIDECAR_PORT });
sidecar.addEventListener('message', (ev) => {
try {
if (typeof ev.data === 'string') {
ws.send(ev.data);
} else {
ws.send(new TextDecoder().decode(ev.data));
}
} catch {
// ws already closed
}
});
sidecar.send(
JSON.stringify({
type: 'init',
sessionId: ws.data.sessionId ?? `host-${ws.data.userId}`,
shell: { command: process.env.SHELL ?? '/bin/zsh', args: ['-i'] },
cwd: process.env.HOME,
homeDir: process.env.HOME,
userLabel: email,
}),
);
return;
}
const cwd = getHomeDir(email);
const userRoot = dirname(cwd);
mkdirSync(userRoot, { recursive: true });
mkdirSync(cwd, { recursive: true });
const shell = resolveShell();
const settings = await getSettings();
const mode: TerminalMode = settings.terminalSandboxed ? 'docker' : 'host';
const containerHome = '/home/officer';
const containerShell: ShellInfo = { command: '/bin/zsh', args: ['-d', '-i'], name: 'zsh' };
const port =
mode === 'docker' ? (await ensureDockerContainer(email, ws.data.userId, cwd)).port : defaultSidecarPort;
let sidecar: WebSocket | null = null;
let dockerId: string | undefined;
let info: ContainerInfo | undefined;
try {
if (mode === 'docker') {
const info = await ensureDockerContainer(email, ws.data.userId, cwd);
dockerId = info.dockerId;
}
sidecar = await connectSidecar(port, mode);
info = await ensureDockerContainer(email, ws.data.userId, cwd);
sidecar = await connectSidecar(info.port);
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to connect terminal sidecar';
sendOutput(ws, `\r\n[Terminal error] ${message}\r\n`);
if (dockerId) {
const logs = readDockerLogs(dockerId);
if (info) {
const logs = readDockerLogs(info.dockerId);
if (logs) {
sendOutput(ws, `\r\n[Docker logs]\r\n${logs}\r\n`);
}
}
sendOutput(ws, '\r\n[Process exited]\r\n');
if (dockerId) stopDockerSidecar(dockerId);
if (info) stopDockerSidecar(info.dockerId);
return;
}
sessions.set(ws, { client: ws, sidecar, mode, dockerId, port });
sessions.set(ws, { client: ws, sidecar, dockerId: info.dockerId, port: info.port });
sidecar.addEventListener('message', (ev) => {
try {
@@ -339,15 +352,13 @@ export const terminalWebsocket = {
}
});
const initCwd = mode === 'docker' ? containerHome : cwd;
const initHome = mode === 'docker' ? containerHome : cwd;
const initShell = mode === 'docker' ? containerShell : shell;
sidecar.send(
JSON.stringify({
type: 'init',
shell: initShell,
cwd: initCwd,
homeDir: initHome,
sessionId: ws.data.sessionId ?? `default-${ws.data.userId}`,
shell: containerShell,
cwd: containerHome,
homeDir: containerHome,
userLabel: email,
}),
);
@@ -374,9 +385,6 @@ export const terminalWebsocket = {
// ignore
}
}
if (session?.dockerId) {
// keep sandbox containers running for reuse
}
sessions.delete(ws);
},