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
18 changes: 18 additions & 0 deletions src/bus-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import type { BusEnvelope, BusHealth } from "./types.js";

const BASE_URL = "http://127.0.0.1";

// Spawn lock — prevents concurrent connect() calls from spawning duplicate
// bus processes while a start is already in flight. Released on settle.
let spawnLock: Promise<number> | null = null;

/**
* Server-side client for the plugin bus.
* Plugins import BusClient, publish messages via HTTP POST.
Expand Down Expand Up @@ -67,8 +71,22 @@ export class BusClient {

/**
* Spawn the bus binary and read the port from stdout.
* Guarded by a module-level spawn lock so concurrent connect() calls share
* the same in-flight spawn instead of forking multiple bus processes.
*/
private static async startBus(timeoutMs: number): Promise<number> {
if (spawnLock) return spawnLock;
spawnLock = BusClient.spawnBus(timeoutMs).finally(() => {
spawnLock = null;
});
return spawnLock;
}

/**
* Inner spawn implementation — wraps the child process in a Promise.
* Kept separate from startBus() so the spawn lock can be released cleanly.
*/
private static spawnBus(timeoutMs: number): Promise<number> {
const binary = BusClient.findBusBinary();
return new Promise((resolve, reject) => {
const child = spawn(binary, [], {
Expand Down
9 changes: 9 additions & 0 deletions src/bus-tui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,15 @@ export class BusTui {
private scheduleReconnect(): void {
if (this.closed) return;
this.reconnectTimer = setTimeout(async () => {
// Re-read the port file — the bus may have restarted on a new port
// (e.g. after a crash) and the cached port would now be dead.
this.port = 0;
try {
const port = await discoverPort(2000);
if (port > 0) this.port = port;
} catch {
// discoverPort failed — keep port=0, open() will report and retry
}
try {
await this.open();
} catch {
Expand Down
Loading