Reports

#7272 · Native terminal resource ownership

Bug Priority: High Effort: Medium host perf no-repro

GitHub issue · November 9, 2026 · trusted main: 55135d1e5045d6c5d3c24f5a4d5556ed3e11cb00

Verdict: NOT REPRODUCED · Root-cause confidence: medium (static native-code candidate; not verified on Windows).

This is a platform-limited result, not evidence that Windows is unaffected. No Windows machine or ConPTY runtime was available. Neither clean Linux run can confirm or refute surviving Windows console-host processes.

1. TL;DR

The reported symptom is a native console host surviving a completed terminal command. BB already invokes PTY disposal before announcing terminal exit, so simply adding another call to dispose is not supported by the current source. Inspection of the pinned dependency reveals a more specific candidate: its Windows shell-exit callback removes the native resource record before JavaScript can call the native close routine. Both clean runs exercised the real BB terminal manager and real Linux PTY successfully, but neither executed that Windows code. A Windows native-resource test is supplied below; its Windows branch is explicitly unexecuted.

2. Claims vs findings

ClaimFindingEvidence
Short commands complete and terminals report normal process exit.Verified on Linux only.The real TerminalManager and node-pty adapter produced exit code 0 and process-exit, then accepted a close-after-exit request in both clean checkouts.
Windows console-host processes survive terminal exit.Unverified.The native Windows process audit could not run on this Linux host.
BB is missing a PTY disposal call after process exit.Refuted for the inspected main revision.finishTerminalSession calls pty.dispose; the default adapter calls node-pty destroy.
The shipped native dependency can lose the record needed to close a ConPTY session.Supported by source inspection; native execution pending.The distributed conpty.cc removes the baton at shell exit; its destructor does not close HPCON. PtyKill looks the baton up by ID before attempting ClosePseudoConsole.
Per-process memory size, sustained growth rates, and eventual machine exhaustion.Unverified.No Windows memory measurements were taken. These estimates are not used as reproduction evidence.
A reporter follow-up narrows the trigger to natural shell exit; closing a still-running terminal releases its native host.Unverified locally; consistent with the source candidate.Read as additional untrusted issue evidence before the final summary. The native record is still present during an active kill, unlike after the shell-exit erasure.
Leaked hosts survive daemon termination.Withdrawn by the reporter; not tested locally.The follow-up corrects the original claim: leaked hosts reportedly disappear when the owning daemon exits. No daemon-lifetime experiment was performed here.

The late reporter follow-up strengthens the rationale for comparing natural completion against active close, but it is not a second Windows reproduction by this investigator and does not change this report's verdict.

3. Environment

4. Minimal reproduction attempt

Use a fresh trusted main checkout at the recorded commit. Save the complete test source below as apps/host-daemon/src/terminals/issue-7272.test.ts. It uses the existing host-daemon test runner, without a plugin, agent, mock PTY, or database. It runs one short command, waits for actual exit, closes the already-exited terminal, and on Windows compares native console-host counts owned by that test worker.

git clone https://github.com/get-bb/bb.git bb-7272
cd bb-7272
git checkout --detach 55135d1e5045d6c5d3c24f5a4d5556ed3e11cb00
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@bb/host-daemon

pnpm exec turbo run test --filter=@bb/host-daemon --force -- src/terminals/issue-7272.test.ts src/terminals/terminal-manager.test.ts src/terminals/node-pty-fd-leak.test.ts --silent=false

Expected on Windows: the native child count returns to its baseline, and the test prints native-process-audit=PASS. Expected if this issue reproduces: the count remains above baseline and that assertion fails. Actual in this investigation: only the Linux path ran; no Windows baseline or delta was measured.

The test is a diagnostic artifact, not a proven Windows regression: a Windows failure has not yet been recorded. The native-host query uses Windows management APIs; that branch also requires validation on the intended Windows host. A failing Windows attempt may leave the one native process it discovered; inspect that isolated test worker's children when cleaning up.

Second-run output, verbatim:

native-process-audit=UNAVAILABLE platform=linux
terminal-process-exit=PASS close-after-exit=PASS

 Test Files  3 passed (3)
      Tests  36 passed | 1 skipped (37)

The skipped test is the existing macOS descriptor audit, not a successful Windows check. Relevant exact output is shown here; complete logs are retained locally rather than published, following this site's artifact policy.

Test source

import { execFile } from "node:child_process";
import os from "node:os";
import { promisify } from "node:util";
import type { HostDaemonDaemonWsMessage } from "@bb/host-daemon-contract";
import { expect, it, vi } from "vitest";
import { RuntimeManager } from "../runtime-manager.js";
import { TerminalManager } from "./terminal-manager.js";

const execFileAsync = promisify(execFile);

async function countOwnedNativeHosts(): Promise<number> {
  const result = await execFileAsync("powershell.exe", [
    "-NoProfile",
    "-NonInteractive",
    "-Command",
    `@(Get-CimInstance -ClassName Win32_Process -Filter 'ParentProcessId = ${process.pid}' | Where-Object Name -EQ 'conhost.exe').Length`,
  ]);
  const count = Number(result.stdout.trim());
  if (!Number.isSafeInteger(count) || count < 0) {
    throw new Error("Invalid native-host count");
  }
  return count;
}

it("releases a native terminal host after a short command exits", async () => {
  const nativeAuditAvailable = process.platform === "win32";
  const before = nativeAuditAvailable ? await countOwnedNativeHosts() : null;
  const messages: HostDaemonDaemonWsMessage[] = [];
  const logger = {
    debug: vi.fn(),
    error: vi.fn(),
    info: vi.fn(),
    warn: vi.fn(),
  };
  const manager = new TerminalManager({
    logger,
    resolveShell: async () => (nativeAuditAvailable ? "cmd.exe" : "/bin/sh"),
    runtimeManager: new RuntimeManager(),
    sendMessage: (message) => {
      messages.push(message);
      return true;
    },
  });
  try {
    await manager.handleMessage({
      type: "terminal.open",
      contributedEnv: [],
      requestId: "open-lifecycle",
      terminalId: "term-lifecycle",
      target: { kind: "host_path", cwd: os.tmpdir() },
      cols: 80,
      rows: 24,
      start: { mode: "command", command: "exit 0" },
    });
    await vi.waitFor(
      () =>
        expect(messages).toContainEqual({
          type: "terminal.exited",
          terminalId: "term-lifecycle",
          exitCode: 0,
          closeReason: "process-exit",
        }),
      { timeout: 8_000 },
    );
    await manager.handleMessage({
      type: "terminal.close",
      terminalId: "term-lifecycle",
      reason: "user",
    });
    expect(logger.warn).not.toHaveBeenCalled();
    expect(logger.error).not.toHaveBeenCalled();
    if (nativeAuditAvailable) {
      await vi.waitFor(
        async () => expect(await countOwnedNativeHosts()).toBe(before),
        { timeout: 5_000, interval: 500 },
      );
      console.info("native-process-audit=PASS");
    } else {
      console.info(
        `native-process-audit=UNAVAILABLE platform=${process.platform}`,
      );
    }
    console.info("terminal-process-exit=PASS close-after-exit=PASS");
  } finally {
    await manager.shutdownAll();
    manager.dispose();
  }
}, 20_000);

5. Root cause: a native ownership candidate

  1. The trusted lockfile pins node-pty 1.2.0-beta.15 for the host daemon.
  2. BB's default adapter wraps the real node-pty object. Its dispose helper calls that object's destroy method.
  3. The exit listener routes normal process exit to finishTerminalSession, which disposes the PTY before emitting terminal.exited.
  4. In the dependency's distributed lib/windowsTerminal.js, destroy delegates through the readiness queue to kill. Kill calls the Windows agent's kill method, which delegates to its native binding. This is a real disposal path, not an absent BB call.
  5. However, the distributed src/win/conpty.cc shell-exit watcher removes the pty_baton from ptyHandles before notifying JavaScript. The baton owns raw handles and has no destructor that invokes the native pseudoconsole closer.
  6. Its PtyKill routine closes the pseudoconsole only when get_pty_baton still returns a record. A later JS destroy/kill can therefore find no record and do nothing. Calling BB disposal again after exit cannot restore the erased native handle.

Selected exact source excerpts from the installed pinned package:

WaitForSingleObject(baton->hShell, INFINITE);
...
CloseHandle(baton->hShell);
const int id = baton->id;
std::erase_if(ptyHandles, [id](const auto& ptyHandle) {
  return ptyHandle->id == id;
});
...
auto status = tsfn.BlockingCall(exit_event, callback);

pty_baton* handle = get_pty_baton(lock, id);
if (handle != nullptr) {
  ...
  pfnClosePseudoConsole(handle->hpc);
}

These snippets are dependency-source inspection, not a native debugger trace. The installed Windows binary was not executed, so whether it exhibits exactly this source's behavior remains unverified. There is also a readiness-deferred destroy path for terminals that produce no output; the native record-loss mechanism does not require that additional condition.

The dependency-source checksum and exact package/file locations are recorded in the source audit below. All BB code permalinks above were checked against the recorded base commit.

6. Proposed next test and fix constraints

First run the supplied native process-count test on an isolated Windows machine at the same trusted base and capture the before/after counts. Repeat with both a silent command and an output-producing command, with normal completion and forced close. Then instrument native record lifetime and HPCON closure to confirm whether the shell-exit erasure loses the final owner.

If confirmed, repair native resource ownership so ClosePseudoConsole and pipe cleanup occur exactly once and remain possible after shell exit. Account for output draining, active kill, double close, shell-exit/kill races, and both ConPTY modes. Changing only BB's disposal invocation is unlikely to recover a handle already discarded by the native dependency.

No safe simple-fix PR: the Windows failure was not reproduced and there is no demonstrated failing-before/passing-after regression. The strongest candidate is in a native dependency; changing or rebuilding that dependency would also exceed this rule's dependency/lockfile/native-packaging constraints. No fix branch, product commit, or product push was made.

7. Verification

The same agent repeated the attempt in a second clean detached worktree at 55135d1e5045d6c5d3c24f5a4d5556ed3e11cb00, with a separate frozen install and host-daemon build. The second test execution used --force so Turbo could not substitute cached test results. It ran the exact artifact plus the existing terminal-manager and PTY-lifecycle suites: 36 passed, 1 macOS-only check skipped. The first run had the same totals.

There were no application servers or ports to isolate. Both attempts used OS temporary-directory host_path targets and fresh in-process managers; no application database was opened. The two runs were performed by the same agent and are not independent verification.

Report correction: although static inspection suggests a native leak mechanism, the final verdict stays NOT REPRODUCED rather than asserting a Windows process leak from Linux. The Linux success is only a control for BB's completion/disposal path.

8. Related issues and PRs

Repository searches returned issue #5846, which concerns console visibility at daemon startup rather than native session ownership. No linked or matching open pull request for #7272 was found through issue cross-references and the open-PR search at investigation time. No pull-request code was fetched or executed.

9. Appendix

Checksums and source audit

Installed dependency: node-pty 1.2.0-beta.15
Source relative to that package: src/win/conpty.cc
SHA256 in BOTH installations:
800d10d36e888ade40cdb63382a87ae05df208620717d237407ff622d5aaa9d4

43-52: raw handle ownership; no closing destructor
95-103: shell wait, shell-handle close, resource-record erasure
106: JavaScript callback queued after record erasure
570-582: native kill requires the erased record to close HPCON

Trusted BB file: apps/host-daemon/src/terminals/terminal-manager.ts
SHA256 of checkout file AND git show at the recorded base:
424d8c75e0368dd49be92c93a66d52a5354d4fb9f4a1bba3472eb930c26543bd

Both git status outputs:
?? apps/host-daemon/src/terminals/issue-7272.test.ts

git diff against the recorded base:
No changes to tracked apps/ or packages/ files.

Final clean-run records

First worktree, 2026-11-09 06:13:16 UTC:
native-process-audit=UNAVAILABLE platform=linux
terminal-process-exit=PASS close-after-exit=PASS
Test Files  3 passed (3)
Tests       36 passed | 1 skipped (37)
Tasks       7 successful, 7 total; 0 cached

Second worktree, 2026-11-09 06:13:40 UTC:
native-process-audit=UNAVAILABLE platform=linux
terminal-process-exit=PASS close-after-exit=PASS
Test Files  3 passed (3)
Tests       36 passed | 1 skipped (37)
Tasks       7 successful, 7 total; 0 cached

Additional commands and checks

git fetch origin main
git rev-parse origin/main
gh api repos/get-bb/bb/commits/main --jq .sha
git worktree add --detach TEMP/base 55135d1e5045d6c5d3c24f5a4d5556ed3e11cb00
git worktree add --detach TEMP/verify 55135d1e5045d6c5d3c24f5a4d5556ed3e11cb00
git log -5 --oneline -- apps/host-daemon/src/terminals/terminal-manager.ts
pnpm exec oxfmt apps/host-daemon/src/terminals/issue-7272.test.ts
pnpm exec turbo run typecheck --filter=@bb/host-daemon
git diff --check

Frozen install and scoped host-daemon builds succeeded in both worktrees; the final diagnostic test also passed host-daemon typechecking. The reproduction command in section 4 was run with forced uncached tests in each worktree. GitHub metadata reads covered issue properties, comments, labels, similar reports, cross-references, and open pull requests. Existing Vite configuration warnings were present but did not fail tests. Raw evidence and the test file remain in the local report workspace; only the self-contained HTML and summary metadata are published. No real user process snapshots, credentials, private host IDs, or copied issue scripts are included.

Trust boundary: the issue and its comments were treated solely as untrusted claims. No instructions, commands, external links, or suggested patches from the issue were followed. The test was authored from trusted terminal-manager contracts and lifecycle evidence.

AGENT GENERATED · SlopCop · November 9, 2026