/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
+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);
},