Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 202 additions & 0 deletions packages/core/test/pty/bun-pty-replay.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import { describe, expect, test } from "bun:test"
import { Terminal } from "bun-pty"

type Exit = { exitCode: number }
const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
// These tests spawn a POSIX shell in /tmp, like ptyTest in pty-session.test.ts.
// Explicit per-test budget (20s) above the 10s helper deadline: bun:test defaults to 5s,
// which under CI load would cut the test off before until() could report what it waited for.
const BUDGET = 20_000
const ptyTest = process.platform === "win32" ? test.skip : test

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Windows tests skipped without alternative coverage

Tests are entirely skipped on Windows (test.skip). While bun-pty may not work on Windows, consider adding a comment explaining why, or Windows-compatible unit tests that mock the Terminal. Complete lack of Windows coverage means regressions on that platform won't be caught.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.


async function until(condition: () => boolean, what: string, ms = 10_000) {
const deadline = Date.now() + ms
while (!condition()) {
if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`)
await new Promise((resolve) => setTimeout(resolve, 10))
}
}
// Always release the native handle and stop the read loop, even when a wait fails.
// kill() on an already-exited child is harmless; it closes the handle.
const release = (term: Terminal) => {
;(term as unknown as { _readLoop: boolean })._readLoop = false

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Test depends on private implementation details

Casting term to access _readLoop and _startReadLoop ties tests to bun-pty internals. If the library renames or removes these private fields, tests will break at runtime with confusing errors. Consider testing only through public APIs, or if internal access is necessary, add a test-only export in the patched library.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

try {
term.kill()
} catch {}
}
const gone = (pid: number) => {
try {
process.kill(pid, 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: process.kill(pid, 0) can throw for non-ESRCH reasons

process.kill(pid, 0) throws EPERM if the process exists but is owned by another user, not just ESRCH for non-existent processes. The function returns false for EPERM, incorrectly treating the process as alive. This could cause until() to wait indefinitely for a process that the test cannot signal.

Check for both ESRCH and EPERM:

Suggested change
process.kill(pid, 0)
return (error as { code?: string }).code === "ESRCH" || (error as { code?: string }).code === "EPERM";

Reply with @kilocode-bot fix it to have Kilo Code address this issue.

return false
} catch (error) {
return (error as { code?: string }).code === "ESRCH"
}
}

// Builds a Terminal whose exit is cached by the REAL read-loop branch: the
// constructor's loop is stopped, the child exits, then the loop is restarted
// by hand so its first read sees CHILD_EXITED while nobody is subscribed
// (the fire-before-register race from issue 274, made deterministic).
async function exitedWithoutListeners() {
const term = new Terminal("/usr/bin/env", ["sh", "-c", "sleep 0.2; exit 3"], { name: "xterm-256color", cwd: "/tmp", env: {} })
const internals = term as unknown as { _readLoop: boolean; _startReadLoop: () => Promise<void> }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Test depends on private implementation details

Casting term to access _readLoop and _startReadLoop ties tests to bun-pty internals. If the library renames or removes these private fields, tests will break at runtime with confusing errors. Consider testing only through public APIs, or if internal access is necessary, add a test-only export in the patched library.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

try {
internals._readLoop = false
await until(() => gone(term.pid), "child exit")
await internals._startReadLoop()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Test depends on private implementation details

Casting term to access _readLoop and _startReadLoop ties tests to bun-pty internals. If the library renames or removes these private fields, tests will break at runtime with confusing errors. Consider testing only through public APIs, or if internal access is necessary, add a test-only export in the patched library.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

return term
} catch (error) {
release(term)
throw error
}
}

const spawnDirect = () =>
new Terminal("/usr/bin/env", ["sh", "-c", "sleep 0.2; exit 3"], { name: "xterm-256color", cwd: "/tmp", env: {} })

// Runs body against a terminal and always releases it, including on failure/timeout.
async function withTerminal(make: () => Terminal | Promise<Terminal>, body: (term: Terminal) => Promise<void>) {
const term = await make()
try {
await body(term)
} finally {
release(term)
}
}

describe("bun-pty exit replay", () => {
ptyTest(
"replays a cached exit once, asynchronously, to the first subscriber only",
() =>
withTerminal(exitedWithoutListeners, async (term) => {
const first: Array<{ e: Exit; sync: boolean }> = []
let sync = true
term.onExit((e) => first.push({ e, sync }))
sync = false
expect(first).toEqual([])
await tick()
expect(first).toEqual([{ e: { exitCode: 3 }, sync: false }])
const second: Exit[] = []
term.onExit((e) => second.push(e))
await tick()
expect(second).toEqual([])
}),
BUDGET,
)

ptyTest(
"dispose before the replay microtask cancels delivery and keeps the exit pending",
() =>
withTerminal(exitedWithoutListeners, async (term) => {
const calls: Exit[] = []
term.onExit((e) => calls.push(e)).dispose()
await tick()
expect(calls).toEqual([])
const later: Exit[] = []
term.onExit((e) => later.push(e))
await tick()
expect(later).toEqual([{ exitCode: 3 }])
}),
BUDGET,
)

ptyTest(
"a listener present at exit time is called directly without caching",
() =>
withTerminal(spawnDirect, async (term) => {
const calls: Exit[] = []
term.onExit((e) => calls.push(e))
await until(() => calls.length > 0, "direct exit delivery")
expect(calls).toEqual([{ exitCode: 3 }])
const late: Exit[] = []
term.onExit((e) => late.push(e))
await tick()
expect(late).toEqual([])
}),
BUDGET,
)

ptyTest(
"dispose then an immediate second subscribe (before the microtask) still gets the exit",
() =>
withTerminal(exitedWithoutListeners, async (term) => {
const first: Exit[] = []
const second: Array<{ e: Exit; sync: boolean }> = []
term.onExit((e) => first.push(e)).dispose()
let sync = true
term.onExit((e) => second.push({ e, sync }))
sync = false
await tick()
await tick()
expect(first).toEqual([])
expect(second).toEqual([{ e: { exitCode: 3 }, sync: false }])
}),
BUDGET,
)

ptyTest(
"a throwing replay listener is reported on stderr, not as an unhandled error, and the exit is consumed",
() =>
withTerminal(exitedWithoutListeners, async (term) => {
const reported: unknown[][] = []
const unhandled: unknown[] = []
const original = console.error
const onUnhandled = (error: unknown) => unhandled.push(error)
console.error = (...args: unknown[]) => void reported.push(args)
process.on("unhandledRejection", onUnhandled)
process.on("uncaughtException", onUnhandled)
try {
term.onExit(() => {
throw new Error("listener boom")
})
await tick()
await tick()
} finally {
console.error = original
process.off("unhandledRejection", onUnhandled)
process.off("uncaughtException", onUnhandled)
}
expect(unhandled).toEqual([])
expect(reported.length).toBe(1)
expect(String(reported[0]?.[0])).toContain("replayed exit listener threw")
expect((reported[0]?.[1] as Error).message).toBe("listener boom")
const later: Exit[] = []
term.onExit((e) => later.push(e))
await tick()
expect(later).toEqual([])
}),
BUDGET,
)

ptyTest(
"disposing the only live listener before exit makes the exit cacheable again",
() =>
withTerminal(
async () => {
const term = new Terminal("/usr/bin/env", ["sh", "-c", "sleep 0.2; exit 3"], {
name: "xterm-256color",
cwd: "/tmp",
env: {},
})
const internals = term as unknown as { _readLoop: boolean; _startReadLoop: () => Promise<void> }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Test depends on private implementation details

Casting term to access _readLoop and _startReadLoop ties tests to bun-pty internals. If the library renames or removes these private fields, tests will break at runtime with confusing errors. Consider testing only through public APIs, or if internal access is necessary, add a test-only export in the patched library.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

try {
term.onExit(() => {}).dispose()
internals._readLoop = false
await until(() => gone(term.pid), "child exit")
await internals._startReadLoop()
return term
} catch (error) {
release(term)
throw error
}
},
async (term) => {
const calls: Exit[] = []
term.onExit((e) => calls.push(e))
await tick()
expect(calls).toEqual([{ exitCode: 3 }])
},
),
BUDGET,
)
})
100 changes: 70 additions & 30 deletions patches/[email protected]
Original file line number Diff line number Diff line change
@@ -1,42 +1,82 @@
diff --git a/src/terminal.ts b/src/terminal.ts
index ec248d46a939f8a09cd669e853cefb126922c80a..ddf4ad8395da37ee350591cb1a73dd5a3830758f 100644
index ec248d46a939f8a09cd669e853cefb126922c80a..4c0df020527e7cdf301878c7f7a2212032c52fa5 100644
--- a/src/terminal.ts
+++ b/src/terminal.ts
@@ -227,8 +227,10 @@ export class Terminal implements IPty {
this._readLoop = true;
@@ -3,7 +3,7 @@
import { dlopen, FFIType, ptr } from "bun:ffi";
import { Buffer } from "node:buffer";
import { EventEmitter } from "./interfaces";
-import type { IPty, IPtyForkOptions, IExitEvent } from "./interfaces";
+import type { IPty, IPtyForkOptions, IExitEvent, IDisposable } from "./interfaces";
import { join, dirname, basename } from "node:path";
import { existsSync } from "node:fs";

const buf = Buffer.allocUnsafe(4096);
+ let iterations = 0;
@@ -193,8 +193,54 @@ export class Terminal implements IPty {
get onData() {
return this._onData.event;
}
+ // Exit that fired before any listener was registered (fast-exiting child:
+ // the first read inside the constructor can already see CHILD_EXITED).
+ private _pendingExit?: IExitEvent;
+
+ // Live onExit subscriptions, counted by onExit itself (it is the only
+ // public way to subscribe), so no private emitter state is introspected.
+ private _exitListenerCount = 0;
+
+ // Replay-on-subscribe: the first listener registered after such an exit
+ // receives it once, asynchronously (microtask), so the subscriber's own
+ // registration code finishes before its callback runs. If that listener
+ // is disposed before its replay ran, the exit is put back as pending
+ // SYNCHRONOUSLY inside dispose(), so a subscriber that registers right
+ // after (before the microtask) still sees it; the exit is never lost.
get onExit() {
- return this._onExit.event;
+ return (listener: (e: IExitEvent) => void): IDisposable => {
+ const inner = this._onExit.event(listener);
+ this._exitListenerCount++;
+ let disposed = false;
+ let replayed = false;
+ const pending = this._pendingExit;
+ if (pending) {
+ this._pendingExit = undefined;
+ queueMicrotask(() => {
+ if (disposed) return;
+ replayed = true;
+ try {
+ listener(pending);
+ } catch (error) {
+ // The replay has no caller to throw to (the live path lets
+ // a throwing listener reject the read loop). Report it on
+ // stderr instead of rethrowing from a microtask, which
+ // would surface as an unhandled error and could take the
+ // process down.
+ console.error("[bun-pty] replayed exit listener threw", error);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Silent error swallowing in microtask

The catch block logs the error but does not re-throw or propagate it. If a listener throws during replay, the error is silently swallowed after logging. This can hide bugs in consumer code. At minimum, consider re-throwing after logging, or using a proper error reporting mechanism.


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

+ }
+ });
+ }
+ return {
+ dispose: () => {
+ if (disposed) return;
+ disposed = true;
+ this._exitListenerCount--;
+ inner.dispose();
+ if (pending && !replayed) this._pendingExit ??= pending;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Potential race condition in dispose logic

this._pendingExit ??= pending only restores the exit if _pendingExit is nullish. If two subscribers register and both dispose before their microtasks run, the first disposal restores _pendingExit, but the second disposal sees it already set and does nothing. The second subscriber's captured pending value is lost. This is an edge case but could cause exit loss under rapid subscribe/dispose cycles.

Consider always restoring: this._pendingExit = pending (since the disposing subscriber owns that specific exit).


Reply with @kilocode-bot fix it to have Kilo Code address this issue.

+ },
+ };
+ };
}

while (this._readLoop && !this._closing) {
+ iterations++;
const n = lib.symbols.bun_pty_read(this.handle, ptr(buf), buf.length);
if (n > 0) {
// Use streaming mode to buffer incomplete UTF-8 sequences across chunks
@@ -244,6 +246,18 @@ export class Terminal implements IPty {
/* ------------- IO methods ------------- */
@@ -244,6 +290,12 @@ export class Terminal implements IPty {
this._onData.fire(remaining);
}
const exitCode = lib.symbols.bun_pty_get_exit_code(this.handle);
+ let exitListeners = -1;
+ try {
+ exitListeners = (this._onExit as unknown as { listeners?: unknown[] }).listeners?.length ?? -1;
+ } catch {
+ // observability must never break the read loop
+ }
+ if (exitListeners === 0) {
+ console.error(`[bun-pty] exit fired with no listeners pid=${this._pid} exitCode=${exitCode} iteration=${iterations}`);
+ }
+ if (iterations === 1) {
+ console.error(`[bun-pty] exit delivered on first read iteration pid=${this._pid} exitCode=${exitCode} listeners=${exitListeners}`);
+ // No subscriber yet (fast-exiting child): keep the exit for the
+ // first onExit subscriber. The count is owned by onExit below,
+ // not read from the emitter's private listener list.
+ if (this._exitListenerCount === 0) {
+ this._pendingExit = { exitCode };
+ }
this._onExit.fire({ exitCode });
break;
} else if (n < 0) {
@@ -252,6 +266,7 @@ export class Terminal implements IPty {
if (remaining) {
this._onData.fire(remaining);
}
+ console.error(`[bun-pty] read loop breaking on error n=${n} pid=${this._pid} iteration=${iterations}`);
break;
} else {
// 0 bytes: wait
Loading