extracted terminal to a widget

This commit is contained in:
2026-02-17 18:46:18 +00:00
parent c6999ea66f
commit 0746844d6f
98 changed files with 487 additions and 3513 deletions
+384
View File
@@ -0,0 +1,384 @@
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 { fileURLToPath } from 'node:url';
import { getHomeDir } from '@@/data-path';
type WSData = { userId: number; email: 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;
port: number;
};
type ContainerInfo = {
userId: number;
email: string;
dockerId: string;
port: number;
};
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' };
};
const sendOutput = (ws: ServerWebSocket<WSData>, data: string) => {
try {
ws.send(JSON.stringify({ type: 'output', data }));
} catch {
// ws already closed
}
};
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];
let lastError: Error | null = null;
for (const delay of delays) {
try {
const ws = await new Promise<WebSocket>((resolve, reject) => {
const socket = new WebSocket(`ws://127.0.0.1:${port}`);
const timeout = setTimeout(() => {
try {
socket.close();
} catch {
// ignore
}
reject(new Error('Terminal sidecar timeout'));
}, 2000);
socket.addEventListener('open', () => {
clearTimeout(timeout);
resolve(socket);
});
socket.addEventListener('error', () => {
clearTimeout(timeout);
reject(new Error('Terminal sidecar connection failed'));
});
});
return ws;
} catch (err) {
lastError = err instanceof Error ? err : new Error('Terminal sidecar connection failed');
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
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');
if (!dockerPath) throw new Error('Docker not found');
const tag = 'officer-terminal-sidecar:v1';
const inspect = Bun.spawnSync({ cmd: [dockerPath, 'image', 'inspect', tag], stdout: 'ignore', stderr: 'ignore' });
if (inspect.exitCode === 0) {
dockerImageReady = true;
return;
}
const dockerfilePath = fileURLToPath(new URL('./Dockerfile.terminal-sidecar', import.meta.url));
const build = Bun.spawnSync({
cmd: [dockerPath, 'build', '-f', dockerfilePath, '-t', tag, '.'],
cwd: fileURLToPath(new URL('./', import.meta.url)),
stdout: 'inherit',
stderr: 'inherit',
});
if (build.exitCode !== 0) throw new Error('Failed to build terminal sandbox image');
dockerImageReady = true;
};
const startDockerSidecar = (port: number, homeDir: string, userId: number): { dockerId: string } => {
ensureDockerImage();
const dockerPath = Bun.which('docker') ?? 'docker';
const dockerId = `officer-terminal-${userId}`;
const tag = 'officer-terminal-sidecar:v1';
// Remove stale container with same name if it exists
if (dockerContainerExists(dockerId)) {
Bun.spawnSync({ cmd: [dockerPath, 'rm', '-f', dockerId], stdout: 'ignore', stderr: 'ignore' });
}
let userArgs: string[] = [];
try {
const stats = statSync(homeDir);
userArgs = ['--user', `${stats.uid}:${stats.gid}`];
} catch {
userArgs = [];
}
const run = Bun.spawnSync({
cmd: [
dockerPath,
'run',
'-d',
'--name',
dockerId,
'--restart',
'unless-stopped',
...userArgs,
'-p',
`127.0.0.1:${port}:${port}`,
'-e',
`TERMINAL_PTY_PORT=${port}`,
'-e',
'TERMINAL_PTY_HOST=0.0.0.0',
'-v',
`${homeDir}:/home/officer`,
'-w',
'/home/officer',
tag,
],
stdout: 'inherit',
stderr: 'inherit',
});
if (run.exitCode !== 0) throw new Error('Failed to start terminal sandbox container');
return { dockerId };
};
const stopDockerSidecar = (dockerId: string) => {
const dockerPath = Bun.which('docker') ?? 'docker';
Bun.spawnSync({ cmd: [dockerPath, 'rm', '-f', dockerId], stdout: 'ignore', stderr: 'ignore' });
};
const readDockerLogs = (dockerId: string) => {
const dockerPath = Bun.which('docker') ?? 'docker';
const logs = Bun.spawnSync({ cmd: [dockerPath, 'logs', '--tail', '200', dockerId], stdout: 'pipe', stderr: 'pipe' });
if (logs.exitCode !== 0) return '';
return logs.stdout.toString().trim();
};
const loadContainerMap = async (): Promise<Record<string, ContainerInfo>> => {
if (containersCache) return containersCache;
const data = await Bun.file(containerMapPath)
.json()
.catch(() => ({}));
containersCache = data as Record<string, ContainerInfo>;
return containersCache;
};
const saveContainerMap = async (map: Record<string, ContainerInfo>) => {
containersCache = map;
await Bun.write(containerMapPath, JSON.stringify(map, null, 2));
};
const getAvailablePort = (map: Record<string, ContainerInfo>, userId: number) => {
const base = 54000;
const used = new Set(Object.values(map).map((item) => item.port));
let port = base + (userId % 1000);
while (used.has(port)) port += 1;
return port;
};
const dockerContainerExists = (dockerId: string) => {
const dockerPath = Bun.which('docker') ?? 'docker';
const result = Bun.spawnSync({ cmd: [dockerPath, 'ps', '-a', '-q', '-f', `name=${dockerId}`], stdout: 'pipe' });
return result.exitCode === 0 && result.stdout.toString().trim().length > 0;
};
const dockerContainerRunning = (dockerId: string) => {
const dockerPath = Bun.which('docker') ?? 'docker';
const result = Bun.spawnSync({ cmd: [dockerPath, 'ps', '-q', '-f', `name=${dockerId}`], stdout: 'pipe' });
return result.exitCode === 0 && result.stdout.toString().trim().length > 0;
};
const dockerStart = (dockerId: string) => {
const dockerPath = Bun.which('docker') ?? 'docker';
const result = Bun.spawnSync({ cmd: [dockerPath, 'start', dockerId], stdout: 'ignore', stderr: 'ignore' });
return result.exitCode === 0;
};
const ensureDockerContainer = async (email: string, userId: number, homeDir: string) => {
const map = await loadContainerMap();
const existing = map[email];
if (existing && dockerContainerRunning(existing.dockerId)) return existing;
if (existing && dockerContainerExists(existing.dockerId)) {
if (dockerStart(existing.dockerId)) return existing;
stopDockerSidecar(existing.dockerId);
}
const port = existing?.port ?? getAvailablePort(map, userId);
const docker = startDockerSidecar(port, homeDir, userId);
const next = { userId, email, dockerId: docker.dockerId, port };
map[email] = next;
await saveContainerMap(map);
return next;
};
void prebuildDockerImage();
export const terminalWebsocket = {
async open(ws: ServerWebSocket<WSData>) {
const { email } = ws.data;
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;
try {
if (mode === 'docker') {
const info = await ensureDockerContainer(email, ws.data.userId, cwd);
dockerId = info.dockerId;
}
sidecar = await connectSidecar(port, mode);
} 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 (logs) {
sendOutput(ws, `\r\n[Docker logs]\r\n${logs}\r\n`);
}
}
sendOutput(ws, '\r\n[Process exited]\r\n');
if (dockerId) stopDockerSidecar(dockerId);
return;
}
sessions.set(ws, { client: ws, sidecar, mode, dockerId, 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
}
});
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,
userLabel: email,
}),
);
},
message(ws: ServerWebSocket<WSData>, raw: string | Buffer) {
const session = sessions.get(ws);
if (!session?.sidecar || session.sidecar.readyState !== WebSocket.OPEN) return;
try {
const payload = typeof raw === 'string' ? raw : raw.toString();
session.sidecar.send(payload);
} catch {
// ignore
}
},
close(ws: ServerWebSocket<WSData>) {
const session = sessions.get(ws);
if (session?.sidecar) {
try {
session.sidecar.close();
} catch {
// ignore
}
}
if (session?.dockerId) {
// keep sandbox containers running for reuse
}
sessions.delete(ws);
},
drain() {},
};