/workspaces refactor
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
import { mkdir, readdir, rename, rm } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { createRouter } from '../../create-router';
|
||||
import { getUserWorkspacesDir, getUserHomepageWorkspaceDir, getUserStateFile } from '@@/data-path';
|
||||
|
||||
export const workspacesRouter = createRouter();
|
||||
|
||||
type KeyMapping = { file: string; dir?: string };
|
||||
|
||||
type ResolveDirs = { wsDir: string; homepageDir: string };
|
||||
|
||||
function workspaceDir(dirs: ResolveDirs, id: string) {
|
||||
return id === 'ws-homepage' ? dirs.homepageDir : join(dirs.wsDir, id);
|
||||
}
|
||||
|
||||
function resolveKey(dirs: ResolveDirs, key: string): KeyMapping | null {
|
||||
if (key === 'workspaces') return { file: join(dirs.wsDir, 'index.json') };
|
||||
if (key === 'ws-terminals-default') return { file: join(dirs.wsDir, 'default-terminals.json') };
|
||||
if (key === 'ws-host-terminals-default') return { file: join(dirs.wsDir, 'default-host-terminals.json') };
|
||||
|
||||
const layoutMatch = key.match(/^ws-layout-(.+)$/);
|
||||
if (layoutMatch) {
|
||||
const id = layoutMatch[1]!;
|
||||
const dir = workspaceDir(dirs, id);
|
||||
return { file: join(dir, 'layout.json'), dir };
|
||||
}
|
||||
|
||||
const terminalsMatch = key.match(/^ws-terminals-(.+)$/);
|
||||
if (terminalsMatch) {
|
||||
const id = terminalsMatch[1]!;
|
||||
const dir = workspaceDir(dirs, id);
|
||||
return { file: join(dir, 'terminals.json'), dir };
|
||||
}
|
||||
|
||||
const hostTerminalsMatch = key.match(/^ws-host-terminals-(.+)$/);
|
||||
if (hostTerminalsMatch) {
|
||||
const id = hostTerminalsMatch[1]!;
|
||||
const dir = workspaceDir(dirs, id);
|
||||
return { file: join(dir, 'host-terminals.json'), dir };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function readJsonFile(path: string): Promise<unknown | null> {
|
||||
const file = Bun.file(path);
|
||||
if (await file.exists()) return file.json();
|
||||
return null;
|
||||
}
|
||||
|
||||
async function writeJsonFile(path: string, data: unknown) {
|
||||
await Bun.write(path, JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
async function migrateFromState(email: string, dirs: ResolveDirs) {
|
||||
const stateFile = getUserStateFile(email);
|
||||
const file = Bun.file(stateFile);
|
||||
if (!(await file.exists())) return;
|
||||
|
||||
const state = (await file.json()) as Record<string, unknown>;
|
||||
const wsKeys = Object.keys(state).filter(
|
||||
(k) => k === 'workspaces' || k.startsWith('ws-layout-') || k.startsWith('ws-terminals-') || k.startsWith('ws-host-terminals-'),
|
||||
);
|
||||
if (wsKeys.length === 0) return;
|
||||
|
||||
await mkdir(dirs.wsDir, { recursive: true });
|
||||
|
||||
for (const key of wsKeys) {
|
||||
const migratedKey = key === 'ws-layout-workspaces' ? 'ws-layout-ws-homepage' : key;
|
||||
const mapping = resolveKey(dirs, migratedKey);
|
||||
if (!mapping) continue;
|
||||
if (mapping.dir) await mkdir(mapping.dir, { recursive: true });
|
||||
await writeJsonFile(mapping.file, state[key]);
|
||||
}
|
||||
|
||||
const cleaned = { ...state };
|
||||
for (const key of wsKeys) delete cleaned[key];
|
||||
await Bun.write(stateFile, JSON.stringify(cleaned, null, 2));
|
||||
}
|
||||
|
||||
async function migrateListLayout(dirs: ResolveDirs) {
|
||||
const oldFile = join(dirs.wsDir, 'list-layout.json');
|
||||
if (!(await Bun.file(oldFile).exists())) return;
|
||||
await mkdir(dirs.homepageDir, { recursive: true });
|
||||
await rename(oldFile, join(dirs.homepageDir, 'layout.json'));
|
||||
}
|
||||
|
||||
async function migrateHomepageFromWorkspaces(dirs: ResolveDirs) {
|
||||
const oldDir = join(dirs.wsDir, 'ws-homepage');
|
||||
const layoutFile = join(oldDir, 'layout.json');
|
||||
if (!(await Bun.file(layoutFile).exists())) return;
|
||||
await mkdir(dirs.homepageDir, { recursive: true });
|
||||
for (const name of ['layout.json', 'terminals.json', 'host-terminals.json']) {
|
||||
const src = join(oldDir, name);
|
||||
if (await Bun.file(src).exists()) {
|
||||
await rename(src, join(dirs.homepageDir, name));
|
||||
}
|
||||
}
|
||||
const remaining = await readdir(oldDir);
|
||||
if (remaining.length === 0) await rm(oldDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
async function readWorkspaceDir(dirPath: string, id: string, result: Record<string, unknown>) {
|
||||
const layout = await readJsonFile(join(dirPath, 'layout.json'));
|
||||
if (layout !== null) result[`ws-layout-${id}`] = layout;
|
||||
|
||||
const terminals = await readJsonFile(join(dirPath, 'terminals.json'));
|
||||
if (terminals !== null) result[`ws-terminals-${id}`] = terminals;
|
||||
|
||||
const hostTerminals = await readJsonFile(join(dirPath, 'host-terminals.json'));
|
||||
if (hostTerminals !== null) result[`ws-host-terminals-${id}`] = hostTerminals;
|
||||
}
|
||||
|
||||
async function readAllWorkspacesState(dirs: ResolveDirs): Promise<Record<string, unknown>> {
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
const indexData = await readJsonFile(join(dirs.wsDir, 'index.json'));
|
||||
if (indexData !== null) result['workspaces'] = indexData;
|
||||
|
||||
const defaultTerminals = await readJsonFile(join(dirs.wsDir, 'default-terminals.json'));
|
||||
if (defaultTerminals !== null) result['ws-terminals-default'] = defaultTerminals;
|
||||
|
||||
const defaultHostTerminals = await readJsonFile(join(dirs.wsDir, 'default-host-terminals.json'));
|
||||
if (defaultHostTerminals !== null) result['ws-host-terminals-default'] = defaultHostTerminals;
|
||||
|
||||
// Read ws-homepage from its own dir
|
||||
await readWorkspaceDir(dirs.homepageDir, 'ws-homepage', result);
|
||||
|
||||
// Read per-workspace subdirs
|
||||
let entries: import('node:fs').Dirent[] = [];
|
||||
try {
|
||||
entries = await readdir(dirs.wsDir, { withFileTypes: true });
|
||||
} catch {
|
||||
return result;
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
await readWorkspaceDir(join(dirs.wsDir, entry.name), entry.name, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function getDirs(email: string): ResolveDirs {
|
||||
return { wsDir: getUserWorkspacesDir(email), homepageDir: getUserHomepageWorkspaceDir(email) };
|
||||
}
|
||||
|
||||
// GET /workspaces-state
|
||||
workspacesRouter.get('/workspaces-state', async (ctx) => {
|
||||
const email = ctx.get('user').email;
|
||||
const dirs = getDirs(email);
|
||||
|
||||
const dirFile = Bun.file(join(dirs.wsDir, 'index.json'));
|
||||
if (!(await dirFile.exists())) {
|
||||
await migrateFromState(email, dirs);
|
||||
}
|
||||
|
||||
await migrateListLayout(dirs);
|
||||
await migrateHomepageFromWorkspaces(dirs);
|
||||
|
||||
const state = await readAllWorkspacesState(dirs);
|
||||
return ctx.json(state);
|
||||
});
|
||||
|
||||
// PATCH /workspaces-state
|
||||
workspacesRouter.patch('/workspaces-state', async (ctx) => {
|
||||
const email = ctx.get('user').email;
|
||||
const body = ctx.get('body') as Record<string, unknown>;
|
||||
const dirs = getDirs(email);
|
||||
|
||||
await mkdir(dirs.wsDir, { recursive: true });
|
||||
|
||||
for (const [key, value] of Object.entries(body)) {
|
||||
const mapping = resolveKey(dirs, key);
|
||||
if (!mapping) continue;
|
||||
|
||||
if (value === null) {
|
||||
try {
|
||||
await rm(mapping.file, { force: true });
|
||||
if (mapping.dir) {
|
||||
const remaining = await readdir(mapping.dir);
|
||||
if (remaining.length === 0) await rm(mapping.dir, { recursive: true, force: true });
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (mapping.dir) await mkdir(mapping.dir, { recursive: true });
|
||||
await writeJsonFile(mapping.file, value);
|
||||
}
|
||||
|
||||
const state = await readAllWorkspacesState(dirs);
|
||||
return ctx.json(state);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
|
||||
|
||||
@@ -25,6 +25,10 @@ export const getUserSettingsFile = (email: string) => join(DATA_PATH, email, 'se
|
||||
|
||||
export const getUserStateFile = (email: string) => join(DATA_PATH, email, 'state.json');
|
||||
|
||||
export const getUserWorkspacesDir = (email: string) => join(DATA_PATH, email, 'workspaces');
|
||||
|
||||
export const getUserHomepageWorkspaceDir = (email: string) => join(DATA_PATH, email, 'ws-homepage');
|
||||
|
||||
export const getNativeSkillsDir = () => join(SEED_PATH, 'skills');
|
||||
|
||||
export const getGlobalSkillsDir = () => join(DATA_PATH, 'skills');
|
||||
|
||||
@@ -16,6 +16,7 @@ import { sessionsRouter } from './api/sessions/sessions';
|
||||
import { scrapeRouter } from './api/scrape/scrape';
|
||||
import { uploadRouter } from './api/upload/upload';
|
||||
import { settingsRouter } from './api/settings/settings';
|
||||
import { workspacesRouter } from './api/settings/workspaces';
|
||||
import { taskLogsRouter } from './api/task-logs/task-logs';
|
||||
import { router as fileBrowserRouter } from './api/file-browser/router';
|
||||
import { CustomError } from './custom-errors';
|
||||
@@ -55,6 +56,7 @@ protectedRouter.route('/', opencodeModelsRouter);
|
||||
protectedRouter.route('/scrape', scrapeRouter);
|
||||
protectedRouter.route('/upload', uploadRouter);
|
||||
protectedRouter.route('/user', settingsRouter);
|
||||
protectedRouter.route('/user', workspacesRouter);
|
||||
protectedRouter.route('/task-logs', taskLogsRouter);
|
||||
protectedRouter.route('/file-browser', fileBrowserRouter);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user