Repository navigation
Description
Summary
When you type into a bb terminal, each key travels from the browser to the bb server, then to the host daemon and the PTY. The echo comes back the same way, and the browser draws nothing until it arrives. Two things make this feel slow:
- Every key waits a full network round trip. When the browser is far from the server, each echo costs the RTT plus about 1 ms. Nothing is drawn locally in the meantime.
- Typing freezes while the server's main thread is stalled. Terminal input and output are relayed on the server's main event loop. When something else blocks that loop, keys wait until it is free. On one ordinary server this happened 60 times in 7 days, for 0.5–1.8 s each.
Expected: typing should feel immediate on a remote connection, and should keep working while the server is busy with unrelated work.
This is an umbrella issue for one PR. The proposed fix below states the design we chose and why. Part B (local echo) is a user-facing feature, so it ships off by default.
Versions and environment
- bb 0.46.0 (desktop app) on Linux 7.2.5 (Arch-based Omarchy), x86_64. This is the server and host daemon the stall logs come from.
- Also reproduced from source at
54a14908a(main, 2026-10-16), which includes 0.46.1. The terminal code is unchanged betweendesktop-v0.46.1and54a14908a. The source run used an isolated dev server (pnpm dev) with Node 26.10.0. - I use the app from a Mac browser through bb Connect. The probes below don't depend on that: they run on the server machine and add RTT with a local proxy.
- No provider or agent is involved.
Steps to reproduce
The two scripts are inlined at the end of this issue. Save them as scripts/terminal-echo-probe.mjs and scripts/event-loop-stall-report.mjs in a bb checkout. They only need Node 22+ and use no dependencies.
A. Echo time is the network RTT
- Create a terminal that runs
cat. Its tty echoes each key straight back.bb terminal create --machine "$(hostname)" --json -- cat # note the "id"
- Measure with no added delay:
node scripts/terminal-echo-probe.mjs --terminal term_xxx --keys 150 --interval-ms 50
- Measure again with 80 ms of added RTT. A local TCP proxy delays each direction by 40 ms.
node scripts/terminal-echo-probe.mjs --terminal term_xxx --keys 60 --interval-ms 50 --rtt-ms 80
- Clean up:
bb terminal close term_xxx
B. Echo freezes during a server main-thread stall (use an isolated dev server, never a live one)
- From a checkout at
54a14908a, runpnpm install && pnpm dev. Note the server port it prints (Server listening … "port":NNNNN). - Create a
catterminal on that dev server:BB_SERVER_URL=http://127.0.0.1:NNNNN NODE_ENV=development \ node --conditions=source --import tsx packages/scripts/src/commands/run-cli.ts \ terminal create --machine "$(hostname)" --json -- cat - Find the server process. It must be the node process that listens on the port, not the dev supervisor.
SERVER_PID=$(lsof -ti tcp:NNNNN -sTCP:LISTEN) - Run the probe with injected stalls.
--stall-pidsends SIGUSR1 to open the inspector on port 9229. It then runs a 1 s busy loop on the server's main thread every 3 s.node scripts/terminal-echo-probe.mjs --server http://127.0.0.1:NNNNN --terminal term_xxx \ --keys 200 --interval-ms 50 --stall-pid "$SERVER_PID" --stall-ms 1000 --stall-every-ms 3000
C. How often real stalls happen on your server
node scripts/event-loop-stall-report.mjs --days 7This reads the Event loop stalled lines that ~/.bb/logs/server*.log already records (#4751).
Did not reproduce: stalls caused by terminal output. Before #4993 this machine logged about 4,400 stalls in two days (Sep 3–4), mostly ws:daemon terminal.output. None of the stalls in the last 7 days are caused by terminal traffic. #4993 fixed that part.
Expected vs actual
A2. No added delay (live 0.46.0 server, loopback):
"all": { "count": 150, "p50": 0.9, "p90": 1.1, "p99": 37.4, "max": 42.7, "over100ms": 0 }, "lost": 0
A3. --rtt-ms 80:
"all": { "count": 60, "p50": 81.3, "p90": 81.7, "max": 83.9 }, "lost": 0
B4. Dev server at 54a14908a, 1 s stall every 3 s (baseline on the same server: p50 1.2, max 4.8):
"stallsInjected": 4, "lost": 0,
"waitOverlappedStall": { "count": 4, "p50": 959, "p90": 989.1, "max": 989.1, "over500ms": 4 },
"waitClearOfStall": { "count": 196, "p50": 1.1, "p90": 1.5, "max": 1.9, "over500ms": 0 }
C. Live 0.46.0 server, last 7 days:
"stalls": 60, "stalledMsTotal": 53258,
"maxDelayMs": { "p50": 753.9, "p90": 1646.3, "max": 1846.5, "over1000ms": 16, "over3000ms": 0 },
"perDay": { "2026-10-10": 2, "2026-10-11": 1, "2026-10-12": 4, "2026-10-13": 25, "2026-10-14": 11, "2026-10-15": 12, "2026-10-16": 5 },
"stallAttribution": { "unattributed": 52, "candidate": 5, "(none)": 3 }
Expected:
- A: on a remote connection, printable keys should appear right away instead of one RTT later. The echo cost itself (about 1 ms on top of the RTT) is fine.
- B: keys typed while the main thread is busy with unrelated work should echo in about 1 ms, as they do outside the stall. Today each one waits for the whole stall.
Evidence
How it is measured. The probe connects to /ws/terminals/:id with the same JSON messages as the browser. It keeps one key in flight. It times from input sent to the first output chunk that contains that key, using performance.now(). waitOverlappedStall counts keys whose wait overlapped an injected stall window.
Code path (permalinks at 54a14908a):
- The browser terminal socket is served by the main server process:
apps/server/src/server.ts#L965-L1000. - So is the shared daemon socket that carries
terminal.inputandterminal.output, together with every other daemon message:
apps/server/src/server.ts#L1004-L1006. - Input is forwarded on the main thread. It looks up the terminal in the database, forwards the key, and emits a plugin event:
terminal-session-lifecycle.ts#L1830-L1871. - Output is relayed on the main thread, with a database read for each chunk:
terminal-session-lifecycle.ts#L1683-L1701. - The client sends each key and draws nothing until the PTY echo returns. There is no prediction or local echo:
ThreadTerminalView.tsx#L473-L489and
#L1125-L1139.
Where real stalls come from. These are observed causes, not terminal ones:
- Of the 60 stalls, 5 were attributed (all
timeline-build, Latest timeline page decodes every event of an open turn on each build, bypassing timelineWindowEventBudget #4674). - Across all 60, the longest tracked work was
timeline-buildin 39 andws:daemon heartbeatin 13. In 34 of the unattributed stalls a timeline build was the longest tracked work but was still shorter than the stall. - The hourly vacuum (Slow / command lookup on remote servers: server stalls (hourly vacuum, timeline builds) dominate, not round trips #5192, Run the hourly database vacuum in chunks that yield to requests #5193) is the largest known cause on servers with big databases.
- These fixes shorten individual stalls. They don't stop the next unrelated stall from freezing the terminal.
Stall attribution gap (observed). My injected 1 s busy loop was logged as "stallAttribution":"unattributed", with longestSynchronousWork: "ws:daemon terminal.output" at 0.3 ms. The monitor calls a stall a candidate only when one tracked span is as long as the stall:
event-loop-stall-monitor.ts#L24-L36.
So stalls caused by untracked work are unattributed. 52 of the 60 real stalls are unattributed. That is outside this issue; I can add it to #5192 if useful.
Source. Investigation thread: bb thread thr_8546rjcajy.
What you ruled out
- Not the renderer or local overhead. On loopback, browser socket → server → daemon → PTY → back takes about 1 ms (p50 0.9 ms). xterm.js rendering is not in this path; Pace terminal output to what the browser has rendered #4993 measured bb's idle terminal overhead at 1.9 ms vs 0.8 ms for plain xterm.js.
- Not a renderer swap. I evaluated
ghostty-web/ libghostty-vt as a replacement for xterm.js. They are not ready to adopt now: coder/ghostty-web 0.4.0 is Canvas-2D only (WebGL is [Feature] WebGL Renderer coder/ghostty-web#155), has open input bugs (bb/update prompt box blockquotes thr di9ekcpsru #203 Alt/Meta, Fix optimistic thread read state #204 Ctrl+Shift+C, feat(timeline): action-specific system message titles, icons & markdown bodies #192 the key-handler contract) and has no screen-reader support ([codex] optimize provisioning metadata and output #187). It would not fix either cause above anyway. - Not output floods. Pace terminal output to what the browser has rendered #4993 fixed those; see "Did not reproduce" above.
- Not a duplicate:
- Slow / command lookup on remote servers: server stalls (hourly vacuum, timeline builds) dominate, not round trips #5192 is the same stalls seen through the
/menu. Its fixes (Run the hourly database vacuum in chunks that yield to requests #5193, Latest timeline page decodes every event of an open turn on each build, bypassing timelineWindowEventBudget #4674) remove specific stalls; this issue makes terminal I/O independent of them and adds local echo. - Built-in terminal is slow to reopen and unreliable under sustained output #1075 (closed) was about reopen speed and sustained output.
- The feature gaps stay in their own issues and are not part of this one: Terminal ignores standard macOS line-editing shortcuts (Cmd+Left/Right, Cmd+Backspace, Option+Left/Right) #4759/Support macOS line-editing shortcuts in the terminal #4760 (macOS shortcuts), Terminal has no clear command: Cmd+K does nothing, and neither keyboard settings nor a plugin can add it #3570 (clear), feat(terminal): allow themes to set the terminal font size #5089 (font size), Complete the mobile terminal keyboard and paste interaction #1763/Add touch text selection and copy controls to the mobile terminal #1764 (mobile).
- Slow / command lookup on remote servers: server stalls (hourly vacuum, timeline builds) dominate, not round trips #5192 is the same stalls seen through the
- Still present on
main: reproduced at54a14908a, which includes 0.46.1.
Suggested priority and effort (optional)
Medium priority:
- Every keystroke on every remote terminal pays the RTT.
- Every terminal freezes for the length of each server stall: on this server, 1–25 a day, 0.5–1.8 s each.
- The workaround is SSH plus a local terminal.
- No data is lost.
Effort is High, because Part A needs a daemon protocol change.
Proposed fix (one PR, scoped commits)
A. Move the terminal data plane into a dedicated relay process
Decision: the server forks one child process, the terminal relay. It owns the browser terminal sockets and a new daemon terminal data socket. Terminal bytes never touch the main event loop. The main process keeps all policy.
How it works:
- Browser socket handoff. The main process keeps the one HTTP listener and runs the same Hono middleware, origin check and auth for
/ws/terminals/:idas today (app.request, as@hono/node-wsalready does). It does not complete the WebSocket handshake. It sends the raw socket, theheadbytes, the request headers and a terminal snapshot to the relay withchild.send(message, socket). The relay completes the handshake withws.handleUpgrade. This is the same handle passing that Node'sclusteruses, and it works on Windows. - Daemon data socket. The daemon opens a second socket,
/internal/ws/terminals, next to/internal/ws. The main process authenticates it with the machine credential, binds it to the daemon session, and hands it to the relay the same way.- It carries
terminal.attach,input,resize,ackandflow-controlto the daemon. - It carries
terminal.output,replay,exitedanderrorback. terminal.open,openedandclosestay on/internal/ws, because they change lifecycle state.- Output and
exitedshare one socket, so the browser always gets the last output beforeexited.
- It carries
- The relay owns output sequencing, replay catch-up and ack pacing (Pace terminal output to what the browser has rendered #4993), moved from
terminal-session-lifecycle.ts. - The main process keeps:
- terminal lifecycle and all database writes. The relay never opens SQLite, so a vacuum or a long transaction cannot block it;
- the first-input timestamp,
cols/rowswrites andsession-updated. The relay reports these over IPC, and only on change, not per key; - plugin terminal events (
emitPluginTerminalInput). The relay posts them over IPC; plugins see them a moment later, as they would after any queue; - the REST/CLI input and read-output routes. Input is forwarded to the relay over IPC.
- Supervision. The main process restarts the relay with backoff if it exits. Browsers reconnect with
sinceSeqand the daemon reconnects its data socket; both paths exist today. The daemon's replay buffer covers the gap. - Build and run. The relay is a new build entry (
dist/terminal-relay.js).fork()passes onexecArgv(tsx in dev) andELECTRON_RUN_AS_NODE(desktop), so dev, desktop andbb serverall start it the same way. - Wire contract. The new daemon socket changes the server/daemon contract, so this bumps
HOST_DAEMON_PROTOCOL_VERSION(238 → 239).
Why this design. We looked at how the app works today and how other terminals solve the same problem:
| Option | Survives a main-loop stall? | Problems |
|---|---|---|
| Relay child process with socket handoff (chosen) | Yes. Separate loop and separate heap, so main-process GC pauses don't reach it either. | One more Node process. Measured: about 103 MiB RSS for an idle compiled relay, about 55 MiB above an idle Node process. Our first estimate of 40–60 MB was too low; the PR has the breakdown. Socket handoff code and an IPC contract. |
worker_threads |
Yes | Node cannot transfer a socket to a worker. The worker would need its own port. A second port breaks bb Connect, reverse proxies and the desktop app, which all expect one origin. |
| Main thread accepts sockets and pipes bytes to a worker | No | Every byte still waits for the main loop. |
| Fix stalls one by one (#4674, #5193) | Only for the causes found | Plugins run in the server process (plugin-runtime.ts imports them), GC pauses remain, and 52 of 60 real stalls are unattributed (#4751). Still worth doing; it is complementary. |
| Keep one daemon socket and route it through the relay | Yes | Every daemon message, not just terminal ones, takes an extra hop through the relay. A relay crash then breaks the whole daemon session. |
| A front proxy process for all HTTP | Yes | Changes every route, auth path and deployment for one feature. |
| Browser talks straight to the daemon | Yes | Remote daemons are not reachable from the browser; that is why the server relays. |
Prior art: VS Code moves PTYs into a separate ptyHost process so the main process stays thin. ttyd and wetty run terminals in dedicated processes. Coder's relay is in Go, so there is no single event loop to block. Jupyter's terminado relays on its main loop and has the same freeze we see here.
Risks we will cover in the PR:
- Socket handoff after the upgrade request was parsed. The
headbytes are passed with the socket, and the relay is tested on Linux, macOS and Windows CI. - A relay that dies with sockets open. Tests kill the relay and check that the browser and daemon reconnect without lost or repeated output.
Out of scope: stalls in the host daemon's own event loop, and the bb Connect tunnel, which runs in the daemon.
Rough size: 1,500–2,500 lines, including tests.
Acceptance: probe B shows waitOverlappedStall p99 under 20 ms during injected 1 s main-thread stalls, with lost: 0. A server test injects a main-loop stall and checks that echo still arrives.
B. Opt-in predictive local echo
Draw predicted printable characters and cursor moves at once, and reconcile them with the PTY output. This is the approach of mosh and VS Code's terminal typeahead.
- It is only active when the measured RTT is above a threshold. VS Code uses 30 ms.
- Predictions are styled until the PTY confirms them.
- It rolls back on a mismatch. It stops predicting when echo is off (password prompts) or in the alternate screen.
- It is off by default at first. The setting is exposed through the usual settings, SDK, and CLI surfaces.
- Rough size: 800–1,500 lines, including tests. VS Code's version is about 1,600.
- Acceptance: with
--rtt-ms 80, predicted characters appear on the next frame, and confirmed text matches the PTY output byte for byte.
C. The repro scripts
The two scripts below, committed under scripts/, so the PR's verification can be rerun.
Checks
- I reproduced this on the latest release or on
main, or I say above that I could not. - I searched open and closed issues for the same problem.
- If an agent wrote this, the body ends with
> AGENT GENERATEDand links the thread or report.
Repro scripts
scripts/terminal-echo-probe.mjs
#!/usr/bin/env node
import net from "node:net";
import { parseArgs } from "node:util";
const USAGE = `Usage: node scripts/terminal-echo-probe.mjs --terminal <id> [options]
Types one key at a time into a bb terminal over the same WebSocket the browser
uses (/ws/terminals/:id) and times each key until its echo arrives.
Run it against a terminal whose program is \`cat\`, for example:
bb terminal create --machine <host> --json -- cat
Options:
--server <url> bb server URL (default: http://127.0.0.1:38886)
--terminal <id> Terminal to type into (required)
--keys <n> Keys to send (default: 200)
--interval-ms <n> Gap between keys (default: 100)
--timeout-ms <n> Give up on one echo after this long (default: 10000)
--rtt-ms <n> Add this much round-trip delay with a local TCP proxy
--stall-pid <pid> Block this server's main thread through its inspector
(sends SIGUSR1). Use a dev server, never a live one.
--stall-ms <n> Length of each injected stall (default: 1000)
--stall-every-ms <n> Start a stall this often (default: 5000)
--inspect-port <n> Inspector port for --stall-pid (default: 9229)
--json Print the full result as JSON
`;
const { values: args } = parseArgs({
options: {
server: { type: "string", default: "http://127.0.0.1:38886" },
terminal: { type: "string" },
keys: { type: "string", default: "200" },
"interval-ms": { type: "string", default: "100" },
"timeout-ms": { type: "string", default: "10000" },
"rtt-ms": { type: "string" },
"stall-pid": { type: "string" },
"stall-ms": { type: "string", default: "1000" },
"stall-every-ms": { type: "string", default: "5000" },
"inspect-port": { type: "string", default: "9229" },
json: { type: "boolean", default: false },
help: { type: "boolean", default: false },
},
});
if (args.help || args.terminal === undefined) {
process.stdout.write(USAGE);
process.exit(args.help ? 0 : 2);
}
function positiveInt(name) {
const value = Number(args[name]);
if (!Number.isInteger(value) || value < 0) {
throw new Error(`--${name} must be a non-negative integer`);
}
return value;
}
const keyCount = positiveInt("keys");
const intervalMs = positiveInt("interval-ms");
const timeoutMs = positiveInt("timeout-ms");
const rttMs = args["rtt-ms"] === undefined ? 0 : positiveInt("rtt-ms");
const stallPid =
args["stall-pid"] === undefined ? null : positiveInt("stall-pid");
const stallMs = positiveInt("stall-ms");
const stallEveryMs = positiveInt("stall-every-ms");
const inspectPort = positiveInt("inspect-port");
const serverUrl = new URL(args.server);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function startDelayProxy(target, oneWayMs) {
const server = net.createServer((client) => {
const upstream = net.connect(Number(target.port), target.hostname);
const pipeDelayed = (from, to) => {
from.on("data", (data) => {
setTimeout(() => to.writable && to.write(data), oneWayMs);
});
from.on("end", () => setTimeout(() => to.end(), oneWayMs));
from.on("error", () => to.destroy());
};
pipeDelayed(client, upstream);
pipeDelayed(upstream, client);
});
return new Promise((resolve) => {
server.listen(0, "127.0.0.1", () => {
resolve({ port: server.address().port, close: () => server.close() });
});
});
}
async function startStallInjector(pid) {
process.kill(pid, "SIGUSR1");
let targets = null;
for (let attempt = 0; attempt < 50 && targets === null; attempt += 1) {
try {
const response = await fetch(`http://127.0.0.1:${inspectPort}/json/list`);
targets = await response.json();
} catch {
await sleep(100);
}
}
if (targets === null || targets.length === 0) {
throw new Error(`No inspector on port ${inspectPort} for pid ${pid}`);
}
const socket = new WebSocket(targets[0].webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
socket.onopen = resolve;
socket.onerror = () => reject(new Error("Inspector connection failed"));
});
let nextId = 1;
const windows = [];
let stopped = false;
const loop = (async () => {
await sleep(stallEveryMs);
while (!stopped) {
const startedAt = performance.now();
windows.push({ startMs: startedAt, endMs: startedAt + stallMs });
socket.send(
JSON.stringify({
id: nextId++,
method: "Runtime.evaluate",
params: {
expression: `{const end=Date.now()+${stallMs};while(Date.now()<end){}}`,
},
}),
);
await sleep(stallEveryMs);
}
})();
return {
windows,
stop: async () => {
stopped = true;
await loop;
socket.close();
},
};
}
function summarize(samples) {
const sorted = samples.toSorted((a, b) => a - b);
const at = (q) =>
sorted.length === 0
? null
: Math.round(sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] * 10) / 10;
return {
count: sorted.length,
p50: at(0.5),
p90: at(0.9),
p99: at(0.99),
max: sorted.length === 0 ? null : Math.round(sorted.at(-1) * 10) / 10,
over100ms: sorted.filter((value) => value > 100).length,
over500ms: sorted.filter((value) => value > 500).length,
};
}
async function main() {
const proxy =
rttMs > 0 ? await startDelayProxy(serverUrl, rttMs / 2) : null;
const socketUrl = new URL(
`/ws/terminals/${encodeURIComponent(args.terminal)}`,
serverUrl,
);
socketUrl.protocol = serverUrl.protocol === "https:" ? "wss:" : "ws:";
if (proxy !== null) {
socketUrl.hostname = "127.0.0.1";
socketUrl.port = String(proxy.port);
}
const socket = new WebSocket(socketUrl);
let pending = null;
let attached = false;
socket.onmessage = (event) => {
const message = JSON.parse(String(event.data));
if (message.type === "attached") {
attached = true;
return;
}
if (message.type === "error" || message.type === "exited") {
console.error(`terminal ${message.type}: ${message.message ?? ""}`);
process.exit(1);
}
if (message.type !== "output" || pending === null) {
return;
}
const text = Buffer.from(message.chunk.dataBase64, "base64").toString("latin1");
if (text.includes(pending.key)) {
pending.resolve(performance.now());
}
};
await new Promise((resolve, reject) => {
socket.onopen = resolve;
socket.onerror = () => reject(new Error(`Could not open ${socketUrl}`));
});
while (!attached) {
await sleep(10);
}
await sleep(300);
const typeKey = (key) =>
new Promise((resolve) => {
const sentAt = performance.now();
const timer = setTimeout(() => {
pending = null;
resolve({ sentAt, latencyMs: null });
}, timeoutMs);
pending = {
key,
resolve: (receivedAt) => {
clearTimeout(timer);
pending = null;
resolve({ sentAt, latencyMs: receivedAt - sentAt });
},
};
socket.send(
JSON.stringify({
type: "input",
dataBase64: Buffer.from(key, "latin1").toString("base64"),
}),
);
});
const stalls = stallPid === null ? null : await startStallInjector(stallPid);
const results = [];
for (let index = 0; index < keyCount; index += 1) {
const key = String.fromCharCode(97 + (index % 26));
results.push(await typeKey(key));
if (index % 60 === 59) {
socket.send(
JSON.stringify({ type: "input", dataBase64: Buffer.from("\r").toString("base64") }),
);
await sleep(200);
}
await sleep(intervalMs);
}
await stalls?.stop();
socket.close();
proxy?.close();
const echoed = results.filter((result) => result.latencyMs !== null);
const inStall = (result) =>
stalls !== null &&
stalls.windows.some(
(window) =>
result.sentAt < window.endMs &&
result.sentAt + result.latencyMs > window.startMs,
);
const report = {
server: serverUrl.href,
terminal: args.terminal,
addedRttMs: rttMs,
stallMs: stalls === null ? null : stallMs,
stallsInjected: stalls?.windows.length ?? 0,
lost: results.length - echoed.length,
all: summarize(echoed.map((result) => result.latencyMs)),
...(stalls === null
? {}
: {
waitOverlappedStall: summarize(
echoed.filter(inStall).map((result) => result.latencyMs),
),
waitClearOfStall: summarize(
echoed.filter((result) => !inStall(result)).map((result) => result.latencyMs),
),
}),
};
if (args.json) {
console.log(JSON.stringify({ ...report, samples: results }, null, 2));
return;
}
console.log(JSON.stringify(report, null, 2));
}
main().catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});scripts/event-loop-stall-report.mjs
#!/usr/bin/env node
import { createReadStream, readdirSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import readline from "node:readline";
import { parseArgs } from "node:util";
const USAGE = `Usage: node scripts/event-loop-stall-report.mjs [options] [log files...]
Summarizes "Event loop stalled" lines from bb server logs. While the server
main thread is stalled, terminal input, output, and echo wait for it.
With no files, reads every server*.log in --logs-dir.
Options:
--logs-dir <dir> Directory to scan (default: ~/.bb/logs)
--days <n> Only count stalls from the last n days (default: 7)
--min-ms <n> Only count stalls at least this long (default: 0)
--json Print the full result as JSON
`;
const { values: args, positionals } = parseArgs({
allowPositionals: true,
options: {
"logs-dir": { type: "string", default: path.join(os.homedir(), ".bb", "logs") },
days: { type: "string", default: "7" },
"min-ms": { type: "string", default: "0" },
json: { type: "boolean", default: false },
help: { type: "boolean", default: false },
},
});
if (args.help) {
process.stdout.write(USAGE);
process.exit(0);
}
const days = Number(args.days);
const minMs = Number(args["min-ms"]);
if (!Number.isFinite(days) || days <= 0 || !Number.isFinite(minMs) || minMs < 0) {
throw new Error("--days must be positive and --min-ms must be non-negative");
}
const since = Date.now() - days * 24 * 60 * 60 * 1000;
const files =
positionals.length > 0
? positionals
: readdirSync(args["logs-dir"])
.filter((name) => /^server(\.\d+)?\.log$/.test(name))
.map((name) => path.join(args["logs-dir"], name));
function parseStall(line) {
if (!line.includes("Event loop stalled")) {
return null;
}
const start = line.indexOf("{");
if (start === -1) {
return null;
}
try {
const entry = JSON.parse(line.slice(start));
if (entry.msg !== "Event loop stalled" || typeof entry.time !== "number") {
return null;
}
return entry;
} catch {
return null;
}
}
function percentile(sorted, q) {
return sorted.length === 0
? null
: sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
}
function countBy(entries, key) {
const counts = new Map();
for (const entry of entries) {
const value = key(entry) ?? "(none)";
counts.set(value, (counts.get(value) ?? 0) + 1);
}
return Object.fromEntries([...counts].toSorted((a, b) => b[1] - a[1]).slice(0, 10));
}
async function main() {
const seen = new Set();
const stalls = [];
for (const file of files) {
const lines = readline.createInterface({ input: createReadStream(file) });
for await (const line of lines) {
const entry = parseStall(line);
if (entry === null || entry.time < since || entry.maxDelayMs < minMs) {
continue;
}
const key = `${entry.time}:${entry.maxDelayMs}`;
if (seen.has(key)) {
continue;
}
seen.add(key);
stalls.push(entry);
}
}
stalls.sort((a, b) => a.time - b.time);
const delays = stalls.map((entry) => entry.maxDelayMs).toSorted((a, b) => a - b);
const perDay = countBy(stalls, (entry) => new Date(entry.time).toISOString().slice(0, 10));
const report = {
files: files.length,
days,
stalls: stalls.length,
stalledMsTotal: Math.round(delays.reduce((sum, value) => sum + value, 0)),
maxDelayMs: {
p50: percentile(delays, 0.5),
p90: percentile(delays, 0.9),
max: delays.at(-1) ?? null,
over1000ms: delays.filter((value) => value >= 1000).length,
over3000ms: delays.filter((value) => value >= 3000).length,
},
perDay: Object.fromEntries(Object.entries(perDay).toSorted(([a], [b]) => a.localeCompare(b))),
stallAttribution: countBy(stalls, (entry) => entry.stallAttribution),
stallCauseCandidate: countBy(stalls, (entry) => entry.stallCauseCandidate),
longestSynchronousWork: countBy(stalls, (entry) => entry.longestSynchronousWork),
inFlightWorkAtObservation: countBy(stalls, (entry) => entry.inFlightWorkAtObservation),
};
if (args.json) {
console.log(JSON.stringify({ ...report, entries: stalls }, null, 2));
return;
}
console.log(JSON.stringify(report, null, 2));
}
main().catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});AGENT GENERATED
Activity
bb-slop-cop commentedon Oct 16, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilothost,ui,perf,confirmed-repro. No existing classifications were replaced.slopcop-5634.test.tsreproducer and documents fixture limitations. Four existing output-flow-control tests also pass.Add terminal relay stall and crash tests
Forward terminal relay warnings to the main process log
Harden the terminal relay after review
Add opt-in predictive local echo for terminals
Add terminal echo and event-loop stall repro scripts
Extract terminal data plane behind an interface
Add daemon terminal data socket and bump protocol to 242
Implement terminal relay IPC and runtime
Run the terminal data plane in a forked relay process
Add terminal relay stall and crash tests
Forward terminal relay warnings to the main process log
Harden the terminal relay after review
Add opt-in predictive local echo for terminals
Prototype: relay terminal traffic through a forked process