diff --git a/lib/ghostty.ts b/lib/ghostty.ts index f0798857..7a6d2c0e 100644 --- a/lib/ghostty.ts +++ b/lib/ghostty.ts @@ -341,6 +341,7 @@ export class GhosttyTerminal { write(data: string | Uint8Array): void { const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data; + if (bytes.length === 0) return; // a zero-length allocation makes the copy below throw const ptr = this.exports.ghostty_wasm_alloc_u8_array(bytes.length); new Uint8Array(this.memory.buffer).set(bytes, ptr); this.exports.ghostty_terminal_write(this.handle, ptr, bytes.length); diff --git a/lib/terminal.test.ts b/lib/terminal.test.ts index 8c764612..e02b2535 100644 --- a/lib/terminal.test.ts +++ b/lib/terminal.test.ts @@ -272,6 +272,40 @@ describe('Terminal', () => { term.dispose(); }); + test('write() with an empty string is a no-op', async () => { + const term = await createIsolatedTerminal(); + term.open(container!); + + expect(() => term.write('')).not.toThrow(); + term.write('after'); + expect(term.buffer.active.getLine(0)?.translateToString(true)).toBe('after'); + + term.dispose(); + }); + + test('write() with an empty Uint8Array is a no-op', async () => { + const term = await createIsolatedTerminal(); + term.open(container!); + + expect(() => term.write(new Uint8Array(0))).not.toThrow(); + + term.dispose(); + }); + + test('write() with empty data still calls the callback', async () => { + const term = await createIsolatedTerminal(); + term.open(container!); + + let called = false; + term.write('', () => { + called = true; + }); + await new Promise((r) => setTimeout(r, 50)); + expect(called).toBe(true); + + term.dispose(); + }); + test('writeln() adds newline', async () => { const term = await createIsolatedTerminal(); term.open(container!); diff --git a/lib/terminal.ts b/lib/terminal.ts index 92d5f3d0..6af93fd5 100644 --- a/lib/terminal.ts +++ b/lib/terminal.ts @@ -555,6 +555,13 @@ export class Terminal implements ITerminalCore { * Internal write implementation (extracted from write()) */ private writeInternal(data: string | Uint8Array, callback?: () => void): void { + // Nothing to write: the WASM side throws a RangeError on an empty buffer. Stay a no-op (as in + // xterm.js), but keep the callback contract. + if (data.length === 0) { + if (callback) requestAnimationFrame(callback); + return; + } + // Note: We intentionally do NOT clear selection on write - most modern terminals // preserve selection when new data arrives. Selection is cleared by user actions // like clicking or typing, not by incoming data.