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
@@ -0,0 +1,35 @@
FROM node:20-bookworm-slim
RUN apt-get update \
&& apt-get install -y python3 make g++ zsh git curl ca-certificates fortune-mod cowsay \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY pty-sidecar.mjs /app/pty-sidecar.mjs
COPY templates /opt/terminal-templates
RUN npm init -y \
&& npm install ws@8.18.1 node-pty@1.1.0
RUN curl -fsSL https://starship.rs/install.sh | sh -s -- -y -b /usr/local/bin
RUN git clone --depth 1 https://github.com/ohmyzsh/ohmyzsh.git /opt/oh-my-zsh
ENV EZA_VERSION=0.18.15
RUN curl -fsSL "https://github.com/eza-community/eza/releases/download/v${EZA_VERSION}/eza_x86_64-unknown-linux-gnu.tar.gz" -o /tmp/eza.tar.gz \
&& tar -xzf /tmp/eza.tar.gz -C /tmp \
&& mv /tmp/eza /usr/local/bin/eza \
&& chmod +x /usr/local/bin/eza \
&& rm -rf /tmp/eza.tar.gz /tmp/completions /tmp/man
WORKDIR /home/officer
ENV TERMINAL_PTY_PORT=5337
ENV PATH="/usr/games:${PATH}"
EXPOSE 5337
CMD ["node", "/app/pty-sidecar.mjs"]
+178
View File
@@ -0,0 +1,178 @@
import http from 'node:http';
import { existsSync } from 'node:fs';
import { cp, mkdir } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { WebSocketServer } from 'ws';
import * as pty from 'node-pty';
const __dirname = dirname(fileURLToPath(import.meta.url));
const isDocker = existsSync('/opt/terminal-templates/.zshrc');
const templateDir = isDocker ? '/opt/terminal-templates' : join(__dirname, 'templates');
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 server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('terminal-sidecar');
});
const wss = new WebSocketServer({ server });
const sendJson = (ws, msg) => {
try {
ws.send(JSON.stringify(msg));
} catch {
// ignore
}
};
const ensureUserFiles = async (homeDir) => {
await mkdir(homeDir, { recursive: true });
await mkdir(join(homeDir, '.config'), { recursive: true });
await mkdir(join(homeDir, '.local', 'bin'), { recursive: true });
const zshrcPath = join(homeDir, '.zshrc');
if (!existsSync(zshrcPath)) {
await cp(join(templateDir, '.zshrc'), zshrcPath);
}
const starshipPath = join(homeDir, '.config', 'starship-officer.toml');
if (!existsSync(starshipPath)) {
await cp(join(templateDir, 'starship-officer.toml'), starshipPath);
}
const ohMyZshPath = join(homeDir, '.oh-my-zsh');
if (!existsSync(ohMyZshPath)) {
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',
stderr: 'ignore',
});
await proc.exited;
}
}
// Install starship on host if missing (not needed in Docker)
if (!isDocker) {
const starshipBin = join(homeDir, '.local', 'bin', 'starship');
if (!existsSync(starshipBin)) {
const installProc = Bun.spawn({
cmd: ['sh', '-c', 'curl -sS https://starship.rs/install.sh | sh -s -- -y -b "$HOME/.local/bin"'],
env: { ...process.env, HOME: homeDir },
stdout: 'ignore',
stderr: 'ignore',
});
await installProc.exited;
}
}
};
wss.on('connection', (ws) => {
let term = null;
let initialized = false;
const cleanup = () => {
if (term) {
try {
term.kill();
} catch {
// ignore
}
}
term = null;
};
ws.on('message', async (data) => {
let msg;
try {
msg = JSON.parse(typeof data === 'string' ? data : data.toString());
} catch {
return;
}
if (msg.type === 'init' && !initialized) {
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 \$ `;
try {
await ensureUserFiles(homeDir);
} catch {
// ignore
}
try {
term = pty.spawn(shell.command, shell.args ?? [], {
name: 'xterm-256color',
cols: 80,
rows: 24,
cwd,
env: {
...process.env,
HOME: homeDir,
ZDOTDIR: homeDir,
ZSH: `${homeDir}/.oh-my-zsh`,
SHELL: shell.command,
USER: userLabel,
LOGNAME: userLabel,
OFFICER_TERMINAL_USER: userLabel,
PROMPT: prompt,
PS1: bashPrompt,
TERM: 'xterm-256color',
},
});
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to start terminal';
sendJson(ws, { type: 'output', data: `\r\n[Terminal error] ${message}\r\n` });
sendJson(ws, { type: 'exit' });
return;
}
initialized = true;
term.onData((output) => {
sendJson(ws, { type: 'output', data: output });
});
term.onExit(() => {
sendJson(ws, { type: 'exit' });
cleanup();
});
return;
}
if (!term) return;
switch (msg.type) {
case 'input':
term.write(msg.data ?? '');
break;
case 'resize':
if (msg.cols > 0 && msg.rows > 0) term.resize(msg.cols, msg.rows);
break;
case 'cwd':
if (msg.path) term.write(`cd ${JSON.stringify(msg.path)}\r`);
break;
}
});
ws.on('close', () => {
cleanup();
});
});
server.listen(port, host, () => {
console.log(`[terminal-sidecar] listening on ${host}:${port}`);
});
+73
View File
@@ -0,0 +1,73 @@
# If you come from bash you might have to change your $PATH.
export PATH=$HOME/.local/bin:$PATH
# Path to your Oh My Zsh installation.
export ZSH="$HOME/.oh-my-zsh"
# Set name of the theme to load --- if set to "random", it will
# load a random theme each time Oh My Zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME=""
# Which plugins would you like to load?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git)
source $ZSH/oh-my-zsh.sh
# ============================================================================
# STARSHIP PROMPT
# ============================================================================
if [[ -n "$OFFICER_TERMINAL_USER" ]]; then
export STARSHIP_CONFIG="$HOME/.config/starship-officer.toml"
fi
# Auto-install starship if not available (host mode)
if ! command -v starship &> /dev/null; then
if [[ ! -x "$HOME/.local/bin/starship" ]]; then
mkdir -p "$HOME/.local/bin"
echo "Installing starship..."
curl -sS https://starship.rs/install.sh | sh -s -- -y -b "$HOME/.local/bin" 2>/dev/null
fi
export PATH="$HOME/.local/bin:$PATH"
fi
eval "$(starship init zsh)"
# ============================================================================
# EZA ALIASES (colors and icons for ls)
# ============================================================================
alias ls='eza --icons'
alias la='eza --icons -la'
alias ll='eza --icons -l'
alias lll='eza --icons -lA'
alias lh='eza --icons -lhA'
alias ltr='eza --icons -ltr'
alias l='eza --icons -la'
# Other common aliases (oh-my-zsh standard)
alias grep='grep --color=auto'
alias less='less -R'
alias diff='diff --color=auto'
alias cp='cp -iv'
alias mv='mv -iv'
alias rm='rm -i'
alias mkdir='mkdir -p'
alias which='which -a'
alias history='fc -l 1'
alias n="nvim"
alias vim="n"
alias sz="source ~/.zshrc"
alias ld="lazydocker"
alias hr="hyprctl reload"
alias hir="omarchy-restart-hypridle"
alias setupmines="WINEPREFIX=~/wine/minesweeper winecfg"
alias httpserver="python -m http.server 8888"
clear
fortune | cowsay
@@ -0,0 +1,20 @@
format = "$env_var:$hostname $directory $character"
[env_var]
variable = "OFFICER_TERMINAL_USER"
format = "[$env_value]($style)"
style = "bold #0891B2"
[hostname]
ssh_only = false
format = "[officer.dev]($style)"
style = "bold yellow"
[directory]
truncation_length = 3
truncate_to_repo = false
style = "blue"
[character]
success_symbol = ">"
error_symbol = ">"
+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() {},
};