@@ -27,6 +27,9 @@ export interface Terminal {
2727 export class ProcessTerminal implements Terminal {
2828 private wasRaw = false;
2929 private resizeHandler?: () => void;
30+ private inputHandler?: (data: string) => void;
31+ private cleanupBound?: () => void;
32+ private stopped = false;
3033
3134 get columns(): number {
3235 return process.stdout.columns || 80;
@@ -41,7 +44,13 @@ export class ProcessTerminal implements Terminal {
4144 }
4245
4346 start(onInput: (data: string) => void, onResize: () => void): void {
44- this.resizeHandler = onResize;
47+ this.stopped = false;
48+ this.inputHandler = onInput;
49+ this.resizeHandler = () => {
50+ // Clear screen on resize to avoid scrollback artifacts
51+ this.write("\x1b[2J\x1b[H");
52+ onResize();
53+ };
4554 this.wasRaw = process.stdin.isRaw || false;
4655
4756 if (process.stdin.setRawMode) {
@@ -50,14 +59,40 @@ export class ProcessTerminal implements Terminal {
5059 process.stdin.setEncoding("utf8");
5160 process.stdin.resume();
5261 process.stdin.on("data", onInput);
53- process.stdout.on("resize", onResize);
62+ process.stdout.on("resize", this.resizeHandler);
5463
5564 // Enable mouse SGR mode
5665 this.write("\x1b[?1006h");
5766 this.hideCursor();
67+
68+ // Register cleanup handlers for crash/exit scenarios
69+ this.cleanupBound = () => this.cleanup();
70+ process.on("exit", this.cleanupBound);
71+ process.on("SIGINT", this.cleanupBound);
72+ process.on("SIGTERM", this.cleanupBound);
73+ process.on("uncaughtException", (err) => {
74+ this.cleanup();
75+ console.error(err);
76+ process.exit(1);
77+ });
78+ process.on("unhandledRejection", (err) => {
79+ this.cleanup();
80+ console.error(err);
81+ process.exit(1);
82+ });
5883 }
5984
6085 stop(): void {
86+ this.cleanup();
87+ }
88+
89+ /**
90+ * Restore terminal state. Safe to call multiple times.
91+ */
92+ private cleanup(): void {
93+ if (this.stopped) return;
94+ this.stopped = true;
95+
6196 // Disable mouse mode
6297 this.write("\x1b[?1006l");
6398 this.showCursor();
@@ -65,11 +100,21 @@ export class ProcessTerminal implements Terminal {
65100 if (this.resizeHandler) {
66101 process.stdout.removeListener("resize", this.resizeHandler);
67102 }
103+ if (this.inputHandler) {
104+ process.stdin.removeListener("data", this.inputHandler);
105+ }
68106
69107 process.stdin.pause();
70108 if (process.stdin.setRawMode) {
71109 process.stdin.setRawMode(this.wasRaw);
72110 }
111+
112+ // Remove process handlers
113+ if (this.cleanupBound) {
114+ process.removeListener("exit", this.cleanupBound);
115+ process.removeListener("SIGINT", this.cleanupBound);
116+ process.removeListener("SIGTERM", this.cleanupBound);
117+ }
73118 }
74119
75120 hideCursor(): void {