fix: keep terminal pty size in sync

This commit is contained in:
Federico Jaramillo Martinez
2026-05-13 23:09:29 +02:00
parent 7386a9bf08
commit a807569018
10 changed files with 317 additions and 35 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@jmfederico/pi-web": patch
---
Fix browser terminal sizing so progress/status lines update in place instead of wrapping when the PTY size has not caught up with the visible terminal.
+3 -2
View File
@@ -6,8 +6,9 @@ export function globalSessionEvents(): WebSocket {
return new WebSocket(`${webSocketBaseUrl()}/api/sessions/events`);
}
export function terminalSocket(projectId: string, workspaceId: string, terminalId: string): WebSocket {
return new WebSocket(`${webSocketBaseUrl()}/api/projects/${encodeURIComponent(projectId)}/workspaces/${encodeURIComponent(workspaceId)}/terminals/${encodeURIComponent(terminalId)}/socket`);
export function terminalSocket(projectId: string, workspaceId: string, terminalId: string, initialSize?: { cols: number; rows: number }): WebSocket {
const sizeQuery = initialSize === undefined ? "" : `?cols=${encodeURIComponent(String(initialSize.cols))}&rows=${encodeURIComponent(String(initialSize.rows))}`;
return new WebSocket(`${webSocketBaseUrl()}/api/projects/${encodeURIComponent(projectId)}/workspaces/${encodeURIComponent(workspaceId)}/terminals/${encodeURIComponent(terminalId)}/socket${sizeQuery}`);
}
export function realtimeEvents(): WebSocket {
+58 -15
View File
@@ -1,10 +1,20 @@
import { css, html, LitElement } from "lit";
import { customElement, property, query, state } from "lit/decorators.js";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { Terminal, type ITerminalOptions } from "@xterm/xterm";
import { FitAddon, type ITerminalDimensions } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css";
import { terminalSocket, terminalsApi, type TerminalInfo, type Workspace } from "../api";
const TERMINAL_OPTIONS: ITerminalOptions = {
cursorBlink: true,
convertEol: true,
fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
fontSize: 13,
theme: { background: "#05070a", foreground: "#e6edf3", cursor: "#58a6ff", selectionBackground: "#264f78" },
};
const DEFAULT_TERMINAL_SIZE: TerminalSize = { cols: 100, rows: 30 };
@customElement("terminal-panel")
export class TerminalPanel extends LitElement {
@property({ attribute: false }) workspace: Workspace | undefined;
@@ -82,7 +92,8 @@ export class TerminalPanel extends LitElement {
if (this.workspace === undefined) return;
this.error = undefined;
try {
const terminal = await terminalsApi.startTerminal(this.workspace.projectId, this.workspace.id, { cols: 100, rows: 30 });
const size = this.measureTerminalSize() ?? DEFAULT_TERMINAL_SIZE;
const terminal = await terminalsApi.startTerminal(this.workspace.projectId, this.workspace.id, size);
this.terminals = [...this.terminals, terminal];
this.selectTerminal(terminal.id);
} catch (error) {
@@ -115,13 +126,7 @@ export class TerminalPanel extends LitElement {
private ensureTerminalView(): void {
const workspace = this.workspace;
if (!this.visible || this.terminal !== undefined || this.selectedId === undefined || this.terminalHost === undefined || workspace === undefined) return;
const terminal = new Terminal({
cursorBlink: true,
convertEol: true,
fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
fontSize: 13,
theme: { background: "#05070a", foreground: "#e6edf3", cursor: "#58a6ff", selectionBackground: "#264f78" },
});
const terminal = new Terminal(TERMINAL_OPTIONS);
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
terminal.open(this.terminalHost);
@@ -134,13 +139,14 @@ export class TerminalPanel extends LitElement {
const filtered = filterTerminalInput(data);
if (filtered !== "") this.send({ type: "input", data: filtered });
});
this.connectSocket(workspace.projectId, workspace.id, this.selectedId, terminal);
const initialSize = this.fitTerminal();
this.connectSocket(workspace.projectId, workspace.id, this.selectedId, terminal, initialSize);
requestAnimationFrame(() => { this.fitAndNotify(); });
terminal.focus();
}
private connectSocket(projectId: string, workspaceId: string, terminalId: string, terminal: Terminal): void {
const socket = terminalSocket(projectId, workspaceId, terminalId);
private connectSocket(projectId: string, workspaceId: string, terminalId: string, terminal: Terminal, initialSize: TerminalSize | undefined): void {
const socket = terminalSocket(projectId, workspaceId, terminalId, initialSize);
socket.binaryType = "arraybuffer";
this.socket = socket;
socket.addEventListener("open", () => { this.fitAndNotify(); });
@@ -180,9 +186,32 @@ export class TerminalPanel extends LitElement {
}
private fitAndNotify(): void {
if (this.fitAddon === undefined || this.terminal === undefined) return;
const size = this.fitTerminal();
if (size === undefined) return;
this.send({ type: "resize", ...size });
}
private fitTerminal(): TerminalSize | undefined {
if (this.fitAddon === undefined || this.terminal === undefined) return undefined;
const dimensions = this.fitAddon.proposeDimensions();
const size = terminalSizeFromDimensions(dimensions);
if (size === undefined) return undefined;
this.fitAddon.fit();
this.send({ type: "resize", cols: this.terminal.cols, rows: this.terminal.rows });
return size;
}
private measureTerminalSize(): TerminalSize | undefined {
const currentSize = this.fitTerminal();
if (currentSize !== undefined) return currentSize;
if (this.terminal !== undefined || this.terminalHost === undefined) return undefined;
const measuringTerminal = new Terminal(TERMINAL_OPTIONS);
const measuringFitAddon = new FitAddon();
measuringTerminal.loadAddon(measuringFitAddon);
measuringTerminal.open(this.terminalHost);
const size = terminalSizeFromDimensions(measuringFitAddon.proposeDimensions());
measuringTerminal.dispose();
return size;
}
private send(message: { type: "input"; data: string } | { type: "resize"; cols: number; rows: number }): void {
@@ -249,6 +278,11 @@ export class TerminalPanel extends LitElement {
`;
}
interface TerminalSize {
cols: number;
rows: number;
}
type ServerTerminalMessage =
| { type: "output"; data: string; replay?: boolean }
| { type: "exit"; exitCode?: number }
@@ -278,6 +312,15 @@ async function socketDataToString(data: unknown): Promise<string> {
return String(data);
}
function terminalSizeFromDimensions(dimensions: ITerminalDimensions | undefined): TerminalSize | undefined {
if (dimensions === undefined || !isValidTerminalSize(dimensions.cols, dimensions.rows)) return undefined;
return { cols: Math.floor(dimensions.cols), rows: Math.floor(dimensions.rows) };
}
function isValidTerminalSize(cols: number, rows: number): boolean {
return Number.isFinite(cols) && Number.isFinite(rows) && cols > 0 && rows > 0;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
+5 -15
View File
@@ -1,9 +1,10 @@
import type { FastifyInstance, FastifyReply } from "fastify";
import { WebSocket, type RawData } from "ws";
import type { ProjectService } from "./projects/projectService.js";
import { SessionDaemonClient } from "./sessiond/sessionDaemonClient.js";
import { resolveWorkspaceContext } from "./workspaces/workspaceContext.js";
import type { WorkspaceService } from "./workspaces/workspaceService.js";
import { terminalSizeQuery } from "./terminals/terminalSize.js";
import { bridgeSockets } from "./webSocketBridge.js";
export function registerTerminalProxyRoutes(app: FastifyInstance, projects: ProjectService, workspaces: WorkspaceService, daemon = new SessionDaemonClient()): void {
app.get<{ Params: { projectId: string; workspaceId: string } }>("/api/projects/:projectId/workspaces/:workspaceId/terminals", async (request, reply) => {
@@ -36,10 +37,11 @@ export function registerTerminalProxyRoutes(app: FastifyInstance, projects: Proj
}
});
app.get<{ Params: { projectId: string; workspaceId: string; terminalId: string } }>("/api/projects/:projectId/workspaces/:workspaceId/terminals/:terminalId/socket", { websocket: true }, async (socket, request) => {
app.get<{ Params: { projectId: string; workspaceId: string; terminalId: string }; Querystring: { cols?: string; rows?: string } }>("/api/projects/:projectId/workspaces/:workspaceId/terminals/:terminalId/socket", { websocket: true }, async (socket, request) => {
try {
await resolveWorkspaceContext(projects, workspaces, request.params.projectId, request.params.workspaceId);
bridgeSockets(socket, daemon.connectWebSocket(`/terminals/${request.params.terminalId}/socket`));
const sizeQuery = terminalSizeQuery(request.query.cols, request.query.rows);
bridgeSockets(socket, daemon.connectWebSocket(`/terminals/${request.params.terminalId}/socket${sizeQuery}`));
} catch (error) {
socket.send(JSON.stringify({ type: "error", message: error instanceof Error ? error.message : String(error) }));
socket.close();
@@ -60,15 +62,3 @@ function requestFailed(reply: FastifyReply, error: unknown): void {
reply.code(400).send({ error: error instanceof Error ? error.message : String(error) });
}
function bridgeSockets(client: WebSocket, upstream: WebSocket): void {
client.on("message", (data) => { sendIfOpen(upstream, data); });
upstream.on("message", (data) => { sendIfOpen(client, data); });
client.on("close", () => { upstream.close(); });
upstream.on("close", () => { client.close(); });
upstream.on("error", () => { client.close(); });
client.on("error", () => { upstream.close(); });
}
function sendIfOpen(socket: WebSocket, data: RawData): void {
if (socket.readyState === WebSocket.OPEN) socket.send(data);
}
@@ -0,0 +1,92 @@
import Fastify, { type FastifyInstance } from "fastify";
import fastifyWebsocket from "@fastify/websocket";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { WebSocket, type RawData } from "ws";
import type { TerminalInfo } from "./terminalService.js";
import { registerTerminalRoutes, type TerminalRouteService } from "./terminalRoutes.js";
let app: FastifyInstance;
let terminals: FakeTerminals;
beforeEach(async () => {
app = Fastify({ logger: false });
await app.register(fastifyWebsocket);
terminals = new FakeTerminals();
registerTerminalRoutes(app, terminals);
await app.listen({ host: "127.0.0.1", port: 0 });
});
afterEach(async () => {
await app.close();
});
describe("terminal socket routes", () => {
it("applies the initial socket size before attaching and replaying output", async () => {
const socket = new WebSocket(`${serverUrl(app)}/terminals/t1/socket?cols=120.9&rows=40.2`);
await expect(nextMessage(socket)).resolves.toBe(JSON.stringify({ type: "output", data: "replayed", replay: true }));
expect(terminals.events).toEqual(["resize:t1:120x40", "attach:t1"]);
socket.close();
});
});
class FakeTerminals implements TerminalRouteService {
readonly events: string[] = [];
list(cwd: string): TerminalInfo[] {
void cwd;
return [];
}
create(options: { cwd: string; name?: string; cols?: number; rows?: number }): TerminalInfo {
return {
id: "t1",
cwd: options.cwd,
name: options.name ?? "Shell 1",
createdAt: "2026-05-13T00:00:00.000Z",
exited: false,
};
}
close(id: string): void {
this.events.push(`close:${id}`);
}
attach(id: string, handlers: { output: (data: string, replay: boolean) => void; exit: (exitCode: number | undefined) => void }): () => void {
this.events.push(`attach:${id}`);
handlers.output("replayed", true);
return () => {
this.events.push(`detach:${id}`);
};
}
write(id: string, data: string): void {
this.events.push(`write:${id}:${data}`);
}
resize(id: string, cols: number, rows: number): void {
this.events.push(`resize:${id}:${String(cols)}x${String(rows)}`);
}
}
function serverUrl(instance: FastifyInstance): string {
const address = instance.server.address();
if (address === null || typeof address === "string") throw new Error("Expected TCP server address");
return `ws://127.0.0.1:${String(address.port)}`;
}
function nextMessage(socket: WebSocket): Promise<string> {
return new Promise((resolve) => {
socket.once("message", (data) => {
resolve(rawDataToString(data));
});
});
}
function rawDataToString(data: RawData): string {
if (typeof data === "string") return data;
if (data instanceof ArrayBuffer) return Buffer.from(data).toString("utf8");
if (Array.isArray(data)) return Buffer.concat(data).toString("utf8");
return data.toString("utf8");
}
+15 -3
View File
@@ -1,8 +1,18 @@
import type { FastifyInstance } from "fastify";
import type { RawData } from "ws";
import type { TerminalService } from "./terminalService.js";
import type { TerminalInfo } from "./terminalService.js";
import { parseTerminalSize } from "./terminalSize.js";
export function registerTerminalRoutes(app: FastifyInstance, terminals: TerminalService, prefix = ""): void {
export interface TerminalRouteService {
list(cwd: string): TerminalInfo[];
create(options: { cwd: string; name?: string; cols?: number; rows?: number }): TerminalInfo;
close(id: string): void;
attach(id: string, handlers: { output: (data: string, replay: boolean) => void; exit: (exitCode: number | undefined) => void }): () => void;
write(id: string, data: string): void;
resize(id: string, cols: number, rows: number): void;
}
export function registerTerminalRoutes(app: FastifyInstance, terminals: TerminalRouteService, prefix = ""): void {
app.get<{ Querystring: { cwd?: string } }>(`${prefix}/terminals`, (request, reply) => {
if (request.query.cwd === undefined || request.query.cwd === "") return reply.code(400).send({ error: "cwd query parameter is required" });
return terminals.list(request.query.cwd);
@@ -21,9 +31,11 @@ export function registerTerminalRoutes(app: FastifyInstance, terminals: Terminal
return { closed: true };
});
app.get<{ Params: { terminalId: string } }>(`${prefix}/terminals/:terminalId/socket`, { websocket: true }, (socket, request) => {
app.get<{ Params: { terminalId: string }; Querystring: { cols?: string; rows?: string } }>(`${prefix}/terminals/:terminalId/socket`, { websocket: true }, (socket, request) => {
let detach: (() => void) | undefined;
try {
const initialSize = parseTerminalSize(request.query.cols, request.query.rows);
if (initialSize !== undefined) terminals.resize(request.params.terminalId, initialSize.cols, initialSize.rows);
detach = terminals.attach(request.params.terminalId, {
output: (data, replay) => { socket.send(JSON.stringify({ type: "output", data, replay })); },
exit: (exitCode) => { socket.send(JSON.stringify({ type: "exit", exitCode })); },
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { parseTerminalSize, terminalSizeQuery } from "./terminalSize.js";
describe("terminal size helpers", () => {
it("normalizes valid terminal dimensions", () => {
expect(parseTerminalSize("120.9", "40.2")).toEqual({ cols: 120, rows: 40 });
expect(parseTerminalSize(80, 24)).toEqual({ cols: 80, rows: 24 });
});
it("rejects missing or invalid dimensions", () => {
expect(parseTerminalSize(undefined, "24")).toBeUndefined();
expect(parseTerminalSize("0", "24")).toBeUndefined();
expect(parseTerminalSize("80", "NaN")).toBeUndefined();
expect(parseTerminalSize("80", "-1")).toBeUndefined();
});
it("builds a normalized query string only for valid dimensions", () => {
expect(terminalSizeQuery("120.9", "40.2")).toBe("?cols=120&rows=40");
expect(terminalSizeQuery("invalid", "40")).toBe("");
});
});
+21
View File
@@ -0,0 +1,21 @@
export interface TerminalSize {
cols: number;
rows: number;
}
export function parseTerminalSize(cols: string | number | undefined, rows: string | number | undefined): TerminalSize | undefined {
const parsedCols = Number(cols);
const parsedRows = Number(rows);
if (!isValidTerminalSize(parsedCols, parsedRows)) return undefined;
return { cols: Math.floor(parsedCols), rows: Math.floor(parsedRows) };
}
export function terminalSizeQuery(cols: string | number | undefined, rows: string | number | undefined): string {
const size = parseTerminalSize(cols, rows);
if (size === undefined) return "";
return `?cols=${encodeURIComponent(String(size.cols))}&rows=${encodeURIComponent(String(size.rows))}`;
}
export function isValidTerminalSize(cols: number, rows: number): boolean {
return Number.isFinite(cols) && Number.isFinite(rows) && cols > 0 && rows > 0;
}
+66
View File
@@ -0,0 +1,66 @@
import { afterEach, describe, expect, it } from "vitest";
import { WebSocket, WebSocketServer, type RawData } from "ws";
import { createBufferedSender } from "./webSocketBridge.js";
let server: WebSocketServer | undefined;
afterEach(async () => {
const socketServer = server;
if (socketServer === undefined) return;
await new Promise<void>((resolve) => {
socketServer.close(() => { resolve(); });
});
server = undefined;
});
describe("createBufferedSender", () => {
it("queues messages while a WebSocket is still connecting", async () => {
const socketServer = new WebSocketServer({ host: "127.0.0.1", port: 0 });
server = socketServer;
const connected = new Promise<WebSocket>((resolve) => {
socketServer.once("connection", resolve);
});
await waitForListening(socketServer);
const client = new WebSocket(serverUrl(socketServer));
const send = createBufferedSender(client);
send("queued-before-open");
const serverSocket = await connected;
await expect(nextMessage(serverSocket)).resolves.toBe("queued-before-open");
client.close();
serverSocket.close();
});
});
function waitForListening(socketServer: WebSocketServer): Promise<void> {
if (socketServer.address() !== null) return Promise.resolve();
return new Promise((resolve, reject) => {
socketServer.once("error", reject);
socketServer.once("listening", () => {
socketServer.off("error", reject);
resolve();
});
});
}
function serverUrl(socketServer: WebSocketServer): string {
const address = socketServer.address();
if (address === null || typeof address === "string") throw new Error("Expected TCP server address");
return `ws://127.0.0.1:${String(address.port)}`;
}
function nextMessage(socket: WebSocket): Promise<string> {
return new Promise((resolve) => {
socket.once("message", (data) => {
resolve(rawDataToString(data));
});
});
}
function rawDataToString(data: RawData): string {
if (typeof data === "string") return data;
if (data instanceof ArrayBuffer) return Buffer.from(data).toString("utf8");
if (Array.isArray(data)) return Buffer.concat(data).toString("utf8");
return data.toString("utf8");
}
+31
View File
@@ -0,0 +1,31 @@
import { WebSocket, type Data } from "ws";
export function bridgeSockets(client: WebSocket, upstream: WebSocket): void {
const sendToClient = createBufferedSender(client);
const sendToUpstream = createBufferedSender(upstream);
client.on("message", (data) => { sendToUpstream(data); });
upstream.on("message", (data) => { sendToClient(data); });
client.on("close", () => { upstream.close(); });
upstream.on("close", () => { client.close(); });
upstream.on("error", () => { client.close(); });
client.on("error", () => { upstream.close(); });
}
export function createBufferedSender(socket: WebSocket): (data: Data) => void {
const queue: Data[] = [];
const flush = () => {
while (socket.readyState === WebSocket.OPEN) {
const data = queue.shift();
if (data === undefined) return;
socket.send(data);
}
};
socket.on("open", flush);
return (data) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(data);
return;
}
if (socket.readyState === WebSocket.CONNECTING) queue.push(data);
};
}