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
@@ -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;
}