Skip to content

Commit 1125b40

Browse files
pnupuclaudejuliusmarminge
authored
fix(server): reset terminal modes a dead shell leaves in inherited history (pingdotgg#9221)
Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 26338ea commit 1125b40

5 files changed

Lines changed: 260 additions & 12 deletions

File tree

‎apps/server/src/terminal/Manager.test.ts‎

Lines changed: 206 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as NodeURL from "node:url";
12
import * as NodeServices from "@effect/platform-node/NodeServices";
23
import { assert, it } from "@effect/vitest";
34
import {
@@ -45,12 +46,26 @@ import * as ProcessRunner from "../processRunner.ts";
4546
import * as ServerSettings from "../serverSettings.ts";
4647
import * as TerminalManager from "./Manager.ts";
4748
import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
49+
import {
50+
applyTerminalAttachStreamEvent,
51+
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
52+
nextTerminalAttachSeedState,
53+
terminalOutputText,
54+
} from "../../../../packages/client-runtime/src/state/terminalSession.ts";
4855

4956
vi.mock("effect/SynchronizedRef", async (importOriginal) => {
5057
const original = await importOriginal<typeof SynchronizedRef>();
5158
return { ...original, make: vi.fn(original.make) };
5259
});
5360

61+
// The server omits DOM types, which include TypeScript's WebAssembly declarations.
62+
declare const WebAssembly: {
63+
instantiate(
64+
bytes: ArrayBuffer,
65+
imports: { env: { log: () => void } },
66+
): Promise<{ instance: { exports: Record<string, unknown> } }>;
67+
};
68+
5469
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
5570

5671
class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{
@@ -1697,7 +1712,187 @@ it.layer(
16971712
yield* manager.close({ threadId: "thread-1" });
16981713

16991714
const reopened = yield* manager.open(openInput());
1700-
assert.equal(reopened.history, "prompt \u001b[32mok\u001b[0m done\n");
1715+
expect(reopened.history.startsWith("prompt \u001b[32mok\u001b[0m done\n")).toBe(true);
1716+
}),
1717+
);
1718+
1719+
it.effect("restores dead-process history without resetting a live terminal", () =>
1720+
Effect.gen(function* () {
1721+
const fs = yield* FileSystem.FileSystem;
1722+
const wasm = yield* fs.readFile(
1723+
NodeURL.fileURLToPath(
1724+
new URL("../../../web/src/terminal/ghostty/vendor/ghostty-vt.wasm", import.meta.url),
1725+
),
1726+
);
1727+
const { instance } = yield* Effect.promise(() =>
1728+
WebAssembly.instantiate(Uint8Array.from(wasm).buffer, { env: { log: () => {} } }),
1729+
);
1730+
const memory = instance.exports.memory as { buffer: ArrayBuffer };
1731+
const call = (name: string, ...args: number[]) =>
1732+
(instance.exports[name] as (...args: number[]) => number)(...args);
1733+
const buffer = call("ghostty_wasm_alloc_u8_array", 16384);
1734+
new Uint8Array(memory.buffer, buffer, 16384).fill(0);
1735+
const view = () => new DataView(memory.buffer);
1736+
view().setUint16(buffer, 100, true);
1737+
view().setUint16(buffer + 2, 24, true);
1738+
view().setUint32(buffer + 4, 100, true);
1739+
expect(call("ghostty_terminal_new", 0, buffer + 8, buffer)).toBe(0);
1740+
const terminal = view().getUint32(buffer + 8, true);
1741+
expect(call("ghostty_key_encoder_new", 0, buffer + 12)).toBe(0);
1742+
expect(call("ghostty_key_event_new", 0, buffer + 16)).toBe(0);
1743+
const encoder = view().getUint32(buffer + 12, true);
1744+
const key = view().getUint32(buffer + 16, true);
1745+
call("ghostty_key_event_set_key", key, 22); // GhosttyKey C in the vendored ABI.
1746+
call("ghostty_key_event_set_unshifted_codepoint", key, 99);
1747+
new Uint8Array(memory.buffer, buffer + 96, 1).set([99]);
1748+
call("ghostty_key_event_set_utf8", key, buffer + 96, 1);
1749+
yield* Effect.addFinalizer(() =>
1750+
Effect.sync(() => {
1751+
call("ghostty_key_event_free", key);
1752+
call("ghostty_key_encoder_free", encoder);
1753+
call("ghostty_terminal_free", terminal);
1754+
call("ghostty_wasm_free_u8_array", buffer, 16384);
1755+
}),
1756+
);
1757+
1758+
// Replay the actual server snapshot in the shipped emulator, not a second mode parser.
1759+
const replay = (history: string) => {
1760+
call("ghostty_terminal_reset", terminal);
1761+
const bytes = new TextEncoder().encode(history);
1762+
for (let offset = 0; offset < bytes.length; offset += 16256) {
1763+
const chunk = bytes.subarray(offset, offset + 16256);
1764+
new Uint8Array(memory.buffer, buffer + 128, chunk.length).set(chunk);
1765+
call("ghostty_terminal_vt_write", terminal, buffer + 128, chunk.length);
1766+
}
1767+
const get = (name: string, field: number) => {
1768+
view().setUint32(buffer + 20, 0, true);
1769+
expect(call(name, terminal, field, buffer + 20)).toBe(0);
1770+
return view().getUint32(buffer + 20, true);
1771+
};
1772+
const state = {
1773+
cursor: [get("ghostty_terminal_get", 3), get("ghostty_terminal_get", 4)],
1774+
screen: get("ghostty_terminal_get", 6),
1775+
visible: get("ghostty_terminal_get", 7),
1776+
kitty: get("ghostty_terminal_get", 8),
1777+
mouse: get("ghostty_terminal_get", 11),
1778+
modes: [1, 66, 67, 1004, 1006, 1035, 1036, 2004].map((mode) =>
1779+
get("ghostty_terminal_mode_get", mode),
1780+
),
1781+
};
1782+
call("ghostty_key_encoder_setopt_from_terminal", encoder, terminal);
1783+
call("ghostty_key_event_set_action", key, 0);
1784+
call("ghostty_key_event_set_mods", key, 0);
1785+
expect(
1786+
call("ghostty_key_encoder_encode", encoder, key, buffer + 128, 16256, buffer + 80),
1787+
).toBe(0);
1788+
const release = new TextDecoder().decode(
1789+
new Uint8Array(memory.buffer, buffer + 128, view().getUint32(buffer + 80, true)),
1790+
);
1791+
call("ghostty_key_event_set_action", key, 1);
1792+
call("ghostty_key_event_set_mods", key, 4);
1793+
expect(
1794+
call("ghostty_key_encoder_encode", encoder, key, buffer + 128, 16256, buffer + 80),
1795+
).toBe(0);
1796+
const modifiedPress = new TextDecoder().decode(
1797+
new Uint8Array(memory.buffer, buffer + 128, view().getUint32(buffer + 80, true)),
1798+
);
1799+
view().setUint32(buffer + 32, 32, true);
1800+
expect(call("ghostty_terminal_select_all", terminal, buffer + 32)).toBe(0);
1801+
expect(call("ghostty_terminal_set", terminal, 21, buffer + 32)).toBe(0);
1802+
view().setUint32(buffer + 64, 16, true);
1803+
view().setUint8(buffer + 72, 1);
1804+
view().setUint8(buffer + 73, 1);
1805+
expect(
1806+
call(
1807+
"ghostty_terminal_selection_format_buf",
1808+
terminal,
1809+
buffer + 64,
1810+
buffer + 128,
1811+
16256,
1812+
buffer + 80,
1813+
),
1814+
).toBe(0);
1815+
const text = new TextDecoder().decode(
1816+
new Uint8Array(memory.buffer, buffer + 128, view().getUint32(buffer + 80, true)),
1817+
);
1818+
return { ...state, release, modifiedPress, text };
1819+
};
1820+
1821+
const { manager, ptyAdapter, logsDir } = yield* createManager(100);
1822+
const logPath = yield* historyLogPath(logsDir);
1823+
const text = `${Array.from({ length: 30 }, (_, i) => `history ${i}\r\n`).join("")}prompt % `;
1824+
const dirty = `${text}\u001b[>7u\u001b[>0u\u001b[>7u\u001b[?1049h\u001b[7;18H\u001b[?47h\u001b[>4;2m\u001b[>7u\u001b[>0u\u001b[>7u\u001b[?25l\u001b[?1;66;67;1003;1004;1006;2004h\u001b[?1035;1036ldead app`;
1825+
const clean = replay(text);
1826+
expect(clean).toMatchObject({ screen: 0, visible: 1, kitty: 0, mouse: 0, release: "" });
1827+
expect(clean.text).toContain("history 0");
1828+
expect(replay(dirty)).toMatchObject({ screen: 1, visible: 0, kitty: 7, mouse: 1 });
1829+
expect(replay(dirty).release).not.toBe("");
1830+
yield* fs.writeFileString(logPath, dirty);
1831+
1832+
const events: TerminalAttachStreamEvent[] = [];
1833+
const outputReceived = yield* Deferred.make<void>();
1834+
const unsubscribe = yield* manager.attachStream(openInput(), (event) =>
1835+
Effect.gen(function* () {
1836+
events.push(event);
1837+
if (event.type === "output") yield* Deferred.succeed(outputReceived, undefined);
1838+
}),
1839+
);
1840+
yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1841+
const first = yield* manager.open(openInput());
1842+
expect(replay(first.history).cursor).toEqual(replay(dirty + "\u001b[?1049l").cursor);
1843+
expect(replay(first.history)).toEqual(clean);
1844+
expect(replay(first.history + "\u001b[<u\u001b[<u")).toEqual(clean);
1845+
expect(replay(first.history + "\u001b[?1049h\u001b[<u\u001b[<unext app")).toEqual(
1846+
replay(text + "\u001b[?1049hnext app"),
1847+
);
1848+
const trimmed = (history: string) => history.slice(history.indexOf("dead app"));
1849+
expect(replay(trimmed(first.history)).cursor).toEqual(replay(trimmed(dirty)).cursor);
1850+
expect(replay(first.history + "\u001b[?1049hnext app")).toEqual(
1851+
replay(text + "\u001b[?1049hnext app"),
1852+
);
1853+
expect(events[0]).toMatchObject({ type: "snapshot", snapshot: { history: first.history } });
1854+
expect(ptyAdapter.spawnInputs).toHaveLength(1);
1855+
1856+
const freshOutput = "fresh shell\u001b[>7u\u001b[?1003;1004h";
1857+
ptyAdapter.processes[0]!.emitData(freshOutput);
1858+
yield* Deferred.await(outputReceived);
1859+
const active = yield* manager.open(openInput());
1860+
expect(active.history).toBe(first.history + freshOutput);
1861+
expect(replay(active.history)).toMatchObject({ kitty: 7, mouse: 1 });
1862+
expect(ptyAdapter.spawnInputs).toHaveLength(1);
1863+
expect(events[1]).toMatchObject({ type: "output", data: freshOutput });
1864+
yield* manager.close({ threadId: "thread-1" });
1865+
expect(yield* fs.readFileString(logPath)).toBe(active.history);
1866+
1867+
const restarted = yield* TerminalManager.makeWithOptions({
1868+
logsDir,
1869+
historyLineLimit: 100,
1870+
ptyAdapter,
1871+
processKillGraceMs: 1,
1872+
});
1873+
const second = yield* restarted.open(openInput());
1874+
expect(replay(second.history)).toEqual(replay(text + "fresh shell"));
1875+
yield* restarted.close({ threadId: "thread-1" });
1876+
expect(yield* fs.readFileString(logPath)).toBe(second.history);
1877+
const third = yield* restarted.open(openInput());
1878+
expect(replay(third.history)).toEqual(replay(text + "fresh shell"));
1879+
expect(ptyAdapter.spawnInputs).toHaveLength(3);
1880+
1881+
const cut = yield* createManager(100);
1882+
const mixed = `main\u001b[4;10H\u001b[?1049h${"\r".repeat(DEFAULT_MAX_TERMINAL_BUFFER_BYTES)}\u001b[7;18Hretained\u001b[?47hmore`;
1883+
yield* fs.writeFileString(yield* historyLogPath(cut.logsDir), mixed);
1884+
const snapshot = yield* cut.manager.open(openInput());
1885+
const clientHistory = terminalOutputText(
1886+
applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
1887+
type: "snapshot",
1888+
snapshot,
1889+
}).output,
1890+
);
1891+
expect(replay(clientHistory).cursor).toEqual(
1892+
replay("\u001b[7;18Hretained\u001b[?47hmore\u001b[?47l").cursor,
1893+
);
1894+
expect(replay(clientHistory)).toMatchObject({ screen: 0, kitty: 0, mouse: 0, release: "" });
1895+
yield* cut.manager.close({ threadId: "thread-1" });
17011896
}),
17021897
);
17031898

@@ -1721,7 +1916,9 @@ it.layer(
17211916
yield* manager.close({ threadId: "thread-1" });
17221917

17231918
const reopened = yield* manager.open(openInput());
1724-
assert.equal(reopened.history, 'prompt \u001b[!p\u001b["p\u001b[4 q\u001b[udone\n');
1919+
expect(reopened.history.startsWith('prompt \u001b[!p\u001b["p\u001b[4 q\u001b[udone\n')).toBe(
1920+
true,
1921+
);
17251922
}),
17261923
);
17271924

@@ -1771,10 +1968,11 @@ it.layer(
17711968
yield* manager.close({ threadId: "thread-1" });
17721969

17731970
const reopened = yield* manager.open(openInput());
1774-
assert.equal(
1775-
reopened.history,
1776-
"before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n",
1777-
);
1971+
expect(
1972+
reopened.history.startsWith(
1973+
"before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n",
1974+
),
1975+
).toBe(true);
17781976
}),
17791977
);
17801978

@@ -1793,7 +1991,7 @@ it.layer(
17931991
yield* manager.close({ threadId: "thread-1" });
17941992

17951993
const reopened = yield* manager.open(openInput());
1796-
assert.equal(reopened.history, "before \u001b(Bafter\n");
1994+
expect(reopened.history.startsWith("before \u001b(Bafter\n")).toBe(true);
17971995
}),
17981996
);
17991997

@@ -1814,7 +2012,7 @@ it.layer(
18142012
yield* manager.close({ threadId: "thread-1" });
18152013

18162014
const reopened = yield* manager.open(openInput());
1817-
assert.equal(reopened.history, "before \u001b(Bafter\n");
2015+
expect(reopened.history.startsWith("before \u001b(Bafter\n")).toBe(true);
18182016
}),
18192017
);
18202018

‎apps/server/src/terminal/Manager.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
22
import {
33
DEFAULT_TERMINAL_ID,
4+
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
45
TerminalCwdError,
56
TerminalCwdNotDirectoryError,
67
TerminalCwdNotFoundError,
@@ -986,6 +987,46 @@ export class BoundedTerminalHistory {
986987
}
987988
}
988989

990+
// Pop beyond Ghostty's eight-entry Kitty stacks on both screens before clearing
991+
// flags. A 1049 round trip preserves the main cursor, text, and scrollback.
992+
const INHERITED_INPUT_RESET =
993+
"\u001b[?1049h\u001b[<100u\u001b[=0;1u\u001b[?1049l" +
994+
"\u001b[?1;9;66;67;1000;1002;1003;1004;1005;1006;1015;2004l" +
995+
"\u001b[?25;1035;1036h\u001b[<100u\u001b[=0;1u\u001b[>4m";
996+
997+
function neutralizeInheritedHistory(history: string, maxLines: number, maxBytes: number): string {
998+
// Scan exactly the cold replay window, reserving the entire longest reset so
999+
// neither the server nor the client can trim away the entry after we choose its exit.
1000+
const resetBytes = history.includes("\u001b")
1001+
? Buffer.byteLength(INHERITED_INPUT_RESET + "\u001b7\u001b[?1049l")
1002+
: 0;
1003+
history = new BoundedTerminalHistory(
1004+
// The suffix occupies the empty line after a trailing newline, too.
1005+
resetBytes > 0 && history.endsWith("\n") ? maxLines - 1 : maxLines,
1006+
history,
1007+
Math.max(0, maxBytes - resetBytes),
1008+
).value();
1009+
if (!history.includes("\u001b")) return history;
1010+
// An unconditional 1049 reset restores a stale saved cursor on the main
1011+
// screen. The exit must match the inherited screen's cursor-save behavior.
1012+
let alternateScreen: number | undefined;
1013+
// eslint-disable-next-line no-control-regex -- Match replayed alternate-screen controls.
1014+
for (const match of history.matchAll(/\u001b(?:\[\?([0-9;]+)([hl])|(c))/gu)) {
1015+
if (match[3]) alternateScreen = undefined;
1016+
for (const parameter of (match[1] ?? "").split(";")) {
1017+
const mode = Number(parameter);
1018+
if (mode === 47 || mode === 1047 || mode === 1049) {
1019+
alternateScreen = match[2] === "h" ? (alternateScreen ?? mode) : undefined;
1020+
}
1021+
}
1022+
}
1023+
// A client may trim away the entry, leaving us on main: save its current
1024+
// cursor before exiting. On alternate this saves only the alternate cursor.
1025+
const leaveAlternateScreen =
1026+
alternateScreen === undefined ? "" : `\u001b7\u001b[?${alternateScreen}l`;
1027+
return history + leaveAlternateScreen + INHERITED_INPUT_RESET;
1028+
}
1029+
9891030
function isCsiFinalByte(codePoint: number): boolean {
9901031
return codePoint >= 0x40 && codePoint <= 0x7e;
9911032
}
@@ -2582,7 +2623,16 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
25822623
const existing = yield* getSession(input.threadId, terminalId);
25832624
if (Option.isNone(existing)) {
25842625
yield* flushPersist(input.threadId, terminalId);
2585-
const history = yield* readHistory(input.threadId, terminalId);
2626+
const inherited = yield* readHistory(input.threadId, terminalId);
2627+
const history = new BoundedTerminalHistory(
2628+
historyLineLimit,
2629+
neutralizeInheritedHistory(
2630+
inherited.value(),
2631+
historyLineLimit,
2632+
Math.min(historyByteLimit, DEFAULT_MAX_TERMINAL_BUFFER_BYTES),
2633+
),
2634+
historyByteLimit,
2635+
);
25862636
const cols = input.cols ?? DEFAULT_OPEN_COLS;
25872637
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
25882638
const session: TerminalSessionState = {

‎packages/client-runtime/src/state/terminalOutput.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ export type TerminalOutputUpdate =
4040
readonly data: string;
4141
};
4242

43-
export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 512 * 1024;
4443
const DEFAULT_TERMINAL_CHUNK_BYTES = 16 * 1024;
4544
const MAX_TERMINAL_OUTPUT_CHUNKS = 1_024;
4645
const textEncoder = new TextEncoder();

‎packages/client-runtime/src/state/terminalSession.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,23 @@ import type {
66
TerminalSummary,
77
ThreadId,
88
} from "@t3tools/contracts";
9+
import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts";
910
import {
1011
appendOutput,
11-
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
1212
EMPTY_TERMINAL_OUTPUT_STATE,
1313
resetOutput,
1414
type TerminalOutputState,
1515
} from "./terminalOutput.ts";
1616

1717
export {
18-
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
1918
INITIAL_TERMINAL_OUTPUT_CURSOR,
2019
readTerminalOutputUpdate,
2120
terminalOutputText,
2221
type TerminalOutputCursor,
2322
type TerminalOutputState,
2423
type TerminalOutputUpdate,
2524
} from "./terminalOutput.ts";
25+
export { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts";
2626

2727
export interface TerminalSessionState {
2828
readonly summary: TerminalSummary | null;

‎packages/contracts/src/terminal.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts";
33
import { ProviderInstanceId } from "./providerInstance.ts";
44

55
export const DEFAULT_TERMINAL_ID = "term-1";
6+
export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 512 * 1024;
67

78
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
89
const TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(

0 commit comments

Comments
 (0)