← reports

#5634 · Terminal relay shares the server event loop

Bug Priority: Medium Effort: High host ui perf · GitHub issue · 2026-10-16 · base 399d63d27702638622ed6522bf874808a364fb40

Verdict: REPRODUCED · Root-cause confidence: high · Label: confirmed-repro

1. TL;DR

A terminal key can wait behind unrelated synchronous work in the server before its echo returns. A fresh probe using the real server WebSocket routes, real migrated SQLite, a separate client process, and an actual PTY reproduced approximately 903 ms of echo latency when input arrived 100 ms into a one-second server-thread stall. A separate delayed TCP connection added approximately 80 ms to echo latency, as expected for a round trip. The server data relay runs on the same event loop as product work; removing individual slow operations does not make that relay independent. Immediate predictive drawing would be new client behavior and is not approved by this report.

2. Claims vs findings

ClaimStatusEvidence
Added connection RTT appears in terminal echo latency.VerifiedEach clean run compares a direct connection with a TCP proxy delaying both directions by 40 ms. Exact measurements follow.
Unrelated server-thread blocking freezes terminal echo.VerifiedInput is sent by an unblocked child process into an already attached terminal while the server test worker spins. The responsiveness assertion fails at approximately 903 ms in both checkouts.
The browser currently does not predict local printable input.Verified by source inspectionThe xterm input callback forwards data to the transport; the output callback writes received server data. This report does not measure browser frames.
A particular deployed server experienced the reported seven-day stall counts and causes.UnverifiedNo production instance, personal database, or production logs were accessed.
A specific worker design or predictive-echo implementation is ready to adopt.Unverified / design decisionNo candidate implementation was executed. This investigation establishes the blocking boundary, not approval of an architecture or product feature.

3. Environment

4. Minimal reproduction

Run only in a disposable checkout: the test intentionally stalls its own server worker for one second. It does not signal or attach an inspector to another process.

  1. Obtain the trusted base and install/build its existing dependencies:
    git clone https://github.com/get-bb/bb.git bb-5634-a
    cd bb-5634-a
    git checkout --detach 399d63d27702638622ed6522bf874808a364fb40
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
  2. Save the two complete embedded diagnostic files into apps/server/test/public/: slopcop-5634.test.ts and slopcop-5634-client.mjs. They are new diagnostic code derived from the trusted route implementation, not the issue's scripts. The source is embedded rather than published as separate files, in accordance with this report site's rules.
  3. Run the focused responsiveness assertion:
    pnpm exec turbo run test --filter=@bb/server -- test/public/slopcop-5634.test.ts

Expected contract: the actual PTY echoes every marker unchanged, a delayed connection adds its RTT, and unrelated main-thread work does not postpone the terminal echo beyond the generous 50 ms assertion. Actual: data is preserved and the RTT check passes, but the responsiveness assertion fails. This is an intentionally failing regression reproducer, not a passing fix test.

Run A: actual output

@bb/server:test: TERMINAL_PROBE {"serverPort":"56304","baseline":{"echo":"alpha","latencyMs":4.9},"delayed":{"echo":"bravo","latencyMs":84.5},"stalled":{"echo":"charlie","latencyMs":902.6},"injectedStallMs":1000,"productionCodeChanged":false}
@bb/server:test: AssertionError: expected 902.6 to be less than 50
@bb/server:test:  Test Files  1 failed (1)
@bb/server:test:       Tests  1 failed (1)

Run B: actual output

@bb/server:test: TERMINAL_PROBE {"serverPort":"61358","baseline":{"echo":"alpha","latencyMs":5.5},"delayed":{"echo":"bravo","latencyMs":84.2},"stalled":{"echo":"charlie","latencyMs":903.2},"injectedStallMs":1000,"productionCodeChanged":false}
@bb/server:test: AssertionError: expected 903.2 to be less than 50
@bb/server:test:  Test Files  1 failed (1)
@bb/server:test:       Tests  1 failed (1)

The delayed probe tests remote echo, not visual local echo. There is one marker per condition in each run; these values are not percentile estimates or a sustained-throughput benchmark. The fixture does not include the production daemon's output batching, so its absolute baseline should not be compared directly with production p50 values.

Complete regression reproducer: slopcop-5634.test.ts
import { fork } from "node:child_process";
import { once } from "node:events";
import { fileURLToPath } from "node:url";
import { createTerminalSession } from "@bb/db";
import { expect, it } from "vitest";
import { seedEnvironment, seedHostSession, seedProjectWithSource } from "../helpers/seed.js";
import { createTestDaemonHostKey, startTestServer } from "../helpers/test-app.js";

it("keeps terminal echo responsive during unrelated main-thread work", async () => {
  const server = await startTestServer({ seedFirstPartyProviders: false });
  const { host, session } = seedHostSession(server.deps, { id: "probe-host", platform: "linux" });
  const { project } = seedProjectWithSource(server.deps, { hostId: host.id, path: server.config.dataDir });
  const environment = seedEnvironment(server.deps, {
    hostId: host.id,
    projectId: project.id,
    path: server.config.dataDir,
  });
  const terminal = createTerminalSession(server.db, {
    cols: 80,
    rows: 24,
    daemonSessionId: session.id,
    environmentId: environment.id,
    hostId: host.id,
    initialCwd: server.config.dataDir,
    status: "running",
    threadId: null,
    title: "probe",
  });
  const child = fork(fileURLToPath(new URL("./slopcop-5634-client.mjs", import.meta.url)), [], {
    cwd: fileURLToPath(new URL("../../../../", import.meta.url)),
    stdio: ["ignore", "inherit", "inherit", "ipc"],
    execArgv: [],
  });
  function request(payload: Record<string, string | number>) {
    const response = once(child, "message");
    child.send(payload);
    return response.then(([message]) => message);
  }
  try {
    await request({
      action: "init",
      url: server.baseUrl,
      hostKey: createTestDaemonHostKey({ hostId: host.id }),
      sessionId: session.id,
      terminalId: terminal.id,
      cwd: server.config.dataDir,
    });
    const baseline = await request({ action: "measure", key: "alpha", delayMs: 0 });
    await request({ action: "prepare", oneWayMs: 40 });
    const delayed = await request({ action: "measure", key: "bravo", delayMs: 0 });
    await request({ action: "prepare", oneWayMs: 0 });
    const stalledResponse = request({ action: "measure", key: "charlie", delayMs: 100 });
    const blockUntil = performance.now() + 1000;
    while (performance.now() < blockUntil) {}
    const stalled = await stalledResponse;
    console.log("TERMINAL_PROBE", JSON.stringify({
      serverPort: new URL(server.baseUrl).port,
      baseline,
      delayed,
      stalled,
      injectedStallMs: 1000,
      productionCodeChanged: false,
    }));
    expect(baseline.echo).toBe("alpha");
    expect(delayed.echo).toBe("bravo");
    expect(stalled.echo).toBe("charlie");
    expect(baseline.latencyMs).toBeLessThan(100);
    expect(delayed.latencyMs - baseline.latencyMs).toBeGreaterThan(60);
    expect(stalled.latencyMs).toBeLessThan(50);
  } finally {
    if (child.connected) {
      await request({ action: "stop" });
    }
    child.kill();
    await server.close();
  }
}, 30000);
Complete separate-process PTY and WebSocket fixture: slopcop-5634-client.mjs
import { createRequire } from "node:module";
import { createServer, connect } from "node:net";
import { once } from "node:events";
import { resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";

const serverRequire = createRequire(resolve("apps/server/package.json"));
const hostRequire = createRequire(resolve("apps/host-daemon/package.json"));
const WebSocket = serverRequire("ws");
const { spawn } = hostRequire("node-pty");
let daemon;
let browser;
let terminal;
let terminalId;
let serverUrl;
let nextSeq = 0;
let pending;
let proxy;
const sockets = new Set();

async function openBrowser(oneWayMs) {
  if (browser) {
    browser.close();
    await once(browser, "close");
  }
  if (proxy) {
    for (const socket of sockets) socket.destroy();
    proxy.close();
    proxy = null;
  }
  const address = new URL(serverUrl);
  let port = address.port;
  if (oneWayMs > 0) {
    proxy = createServer((downstream) => {
      const upstream = connect(Number(address.port), "127.0.0.1");
      for (const socket of [upstream, downstream]) {
        sockets.add(socket);
        socket.on("close", () => sockets.delete(socket));
        socket.on("error", () => {});
      }
      for (const [source, destination] of [[upstream, downstream], [downstream, upstream]]) {
        source.on("data", (bytes) => setTimeout(() => {
          if (!destination.destroyed) destination.write(bytes);
        }, oneWayMs));
        source.on("end", () => setTimeout(() => destination.end(), oneWayMs));
      }
    });
    proxy.listen(0, "127.0.0.1");
    await once(proxy, "listening");
    port = proxy.address().port;
  }
  browser = new WebSocket(`ws://127.0.0.1:${port}/ws/terminals/${terminalId}`);
  await new Promise((resolveAttached, reject) => {
    browser.on("error", reject);
    browser.on("message", (raw) => {
      const message = JSON.parse(raw.toString());
      if (message.type === "attached") resolveAttached();
      if (message.type === "error") reject(new Error(message.message));
      if (message.type === "output" && pending) {
        pending.text += Buffer.from(message.chunk.dataBase64, "base64").toString();
        if (pending.text.includes(pending.key)) {
          const current = pending;
          pending = null;
          clearTimeout(current.timeout);
          current.resolve({
            echo: current.key,
            latencyMs: Math.round((performance.now() - current.started) * 10) / 10,
          });
        }
      }
    });
  });
}

async function initialize(message) {
  serverUrl = message.url;
  terminalId = message.terminalId;
  terminal = spawn("/bin/cat", [], {
    name: "xterm-256color",
    cols: 80,
    rows: 24,
    cwd: message.cwd,
    env: { PATH: "/usr/bin:/bin", TERM: "xterm-256color", LANG: "C.UTF-8" },
  });
  daemon = new WebSocket(`${serverUrl.replace("http:", "ws:")}/internal/ws?sessionId=${message.sessionId}`, "bb-host-daemon.v1", {
    headers: { Authorization: `Bearer ${message.hostKey}` },
  });
  daemon.on("message", (raw) => {
    const command = JSON.parse(raw.toString());
    if (command.type === "terminal.attach") {
      daemon.send(JSON.stringify({
        type: "terminal.replay",
        requestId: command.requestId,
        terminalId,
        chunks: [],
        replayStartSeq: nextSeq,
        nextSeq,
      }));
    }
    if (command.type === "terminal.input") {
      terminal.write(Buffer.from(command.dataBase64, "base64").toString());
    }
  });
  terminal.onData((text) => {
    const bytes = Buffer.from(text);
    daemon.send(JSON.stringify({
      type: "terminal.output",
      terminalId,
      chunk: { seq: nextSeq, dataBase64: bytes.toString("base64") },
    }));
    nextSeq += bytes.length;
  });
  await once(daemon, "open");
  await openBrowser(0);
  return { ready: true };
}

async function measure(message) {
  await sleep(message.delayMs);
  return new Promise((resolveEcho, reject) => {
    pending = {
      key: message.key,
      text: "",
      started: performance.now(),
      resolve: resolveEcho,
      timeout: setTimeout(() => reject(new Error("No terminal echo within 5 seconds")), 5000),
    };
    browser.send(JSON.stringify({ type: "input", dataBase64: Buffer.from(message.key).toString("base64") }));
  });
}

process.on("message", async (message) => {
  try {
    if (message.action === "init") process.send(await initialize(message));
    if (message.action === "prepare") {
      await openBrowser(message.oneWayMs);
      process.send({ prepared: true });
    }
    if (message.action === "measure") process.send(await measure(message));
    if (message.action === "stop") {
      browser?.terminate();
      daemon?.terminate();
      terminal?.kill();
      for (const socket of sockets) socket.destroy();
      proxy?.close();
      process.send({ stopped: true });
    }
  } catch (error) {
    console.error(error);
    process.send({ error: String(error) });
  }
});

5. Root cause

The two WebSocket routes are installed into the same server instance. Their message callbacks directly invoke the terminal lifecycle and daemon protocol handlers; there is no independently scheduled data plane. A synchronous loop on the server worker prevents those callbacks from handling newly arriving bytes even while the external client and PTY remain schedulable.

onMessage: (event, socket) =>
  onTerminalSocketMessage(deps, {
    raw: event.data,
    socket,
    terminalId,
  })
const sent = this.options.hub.sendDaemonSessionMessage(
  current.daemonSessionId,
  {
    type: "terminal.input",
    terminalId: current.id,
    dataBase64: args.message.dataBase64,
  },
);

The database work is part of the serial path, but this experiment does not attribute the injected stall to a slow database query. The stall is deliberately unrelated work in the same event loop. Caching terminal rows or shrinking one slow task cannot guarantee continuous I/O while that event loop is blocked. Separately, without local prediction the client cannot show confirmed PTY echo before the remote trip completes; a renderer replacement alone does not remove this network dependency.

6. Proposed fix and safe-fix gate

Establish an independently serviced terminal-byte path, keeping authorization, terminal lifecycle, database policy, and plugin event policy on the main server. Any design must preserve ordering, replay offsets, pacing/acks, disconnect revocation, session ownership, and daemon compatibility. In particular, moving only browser sockets while keeping incoming daemon bytes on the blocked server loop would not isolate output.

Predictive local echo should be treated as a separate product feature, with explicit rules for passwords, alternate-screen programs, mismatches, settings, SDK, and CLI. This report does not authorize that feature.

No automatic PR: the verified failure is an execution/transport ownership problem. A safe repair requires architecture and potentially public daemon-protocol decisions, so it fails the simple-fix gate even if a small superficial optimization could fit the line limit. No production patch, branch, or push was made to bb. No linked open PR was found in the issue timeline or an open-PR search for this issue number.

7. Verification

The same agent repeated the reproduction in a second newly created clean checkout at the identical trusted commit. Both worktrees had clean tracked files before the two new probe files were added. Each performed its own frozen install and Turbo build, and each used a fresh test server, new port, fresh test data, and a new PTY child. The same Turbo test command above failed specifically at the latency assertion, after all echo equality checks and the added-delay check passed.

Run B confirms the final diagnosis. No report correction was necessary. This is a repeated clean reproduction by one agent, not a claim of independent human or agent verification. Production code remained unchanged. Cleanup closes sockets and the temporary server, kills the PTY child, and removes harness-created data.

8. Related evidence

Trusted history shows commit 8abfcd77e (terminal output pacing, PR #4993) already precedes this base; that protects a different output-flow behavior and does not detach sockets from the server event loop. A repository issue search also finds #4163 on plugin stall attribution and #1207 on synchronous thread-list work. These are context, not a verified source of this experiment's stall, and they were not modified.

9. Appendix

Verbatim result excerpts from both runs and the complete runnable diagnostic files are embedded above. Raw evidence is retained locally outside the public report repository; no raw logs or diagnostic source files are committed to the site.

Investigation operations: fetched and validated trusted main; read the issue and all available comments as untrusted data; read repository classifications and nearby examples; applied only missing Type/Priority/Effort/area values; inspected trusted server, terminal lifecycle, client, test harness, and daemon schema; installed and built both clean worktrees; ran the diagnostic test in each; searched issue cross-reference metadata and open PRs; checked diffs for whitespace errors. No issue-supplied command, script, branch, patch, binary, test, or external link was executed or fetched. No production logs, credentials, or personal runtime data were read.

Untrusted-data note: the issue included runnable scripts and architectural suggestions. They were treated only as claims; the probes were authored anew from trusted repository evidence.

> AGENT GENERATED