Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.
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
44 changes: 33 additions & 11 deletions packages/cli/src/commands/local/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,36 @@ async function startBackgroundServer(
};
}

/**
* Get a live event tail on `host:port`, whichever way is available.
*
* Prefers attaching to whatever already holds the port so we never compete
* with it, and falls back to attaching if the bind loses a race. `run` wraps
* the user's dev command, so a busy port must never be fatal here.
*/
async function openEventTail(port: number, host: string): Promise<EventTail> {
const url = `http://${host}:${port}`;

if (await isServerRunning(url)) {
logger.info(`Connected to existing server at ${bold(url)}`);
return attachToExistingServer(url);
}

logger.info("No server detected, starting one in the background...");
try {
const bg = await startBackgroundServer(port, host);
logger.info(`Background server listening on ${bold(bg.url)}`);
return bg;
} catch (err) {
if (!(err instanceof ValidationError && err.field === "port")) {
throw err;
}
// Something grabbed the port between the probe and the bind.
logger.warn(`${err.message}; attaching to it instead`);
return attachToExistingServer(url);
}
}

/** Augment PATH with `./node_modules/.bin` for Node project scripts. */
function augmentPathForNode(
env: Record<string, string | undefined>,
Expand Down Expand Up @@ -310,17 +340,9 @@ export const runCommand = buildCommand({
}

let url = `http://${flags.host}:${flags.port}`;
let tail: EventTail;

if (await isServerRunning(url)) {
logger.info(`Connected to existing server at ${bold(url)}`);
tail = attachToExistingServer(url);
} else {
logger.info("No server detected, starting one in the background...");
tail = await startBackgroundServer(flags.port, flags.host);
url = tail.url;
logger.info(`Background server listening on ${bold(url)}`);
}

const tail = await openEventTail(flags.port, flags.host);
url = tail.url;

const spotlightUrl = `${url}/stream`;
logger.info(`Starting: ${bold(args.join(" "))}`);
Expand Down
21 changes: 18 additions & 3 deletions packages/cli/src/commands/local/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,15 +376,30 @@ export function tryListen(
}

/**
* Check whether a server is already running on the given URL.
* Returns `true` if the health endpoint responds successfully.
* Check whether something is already serving on the given URL.
*
* Any HTTP reply — including an error status — means the port is taken, so
* this deliberately does not require a 2xx. Spotlight's own sidecar can
* answer `/health` with a 5xx while still holding the port and ingesting
* envelopes; treating that as "nothing there" made the CLI try to bind the
* port anyway and abort with `Port 8969 is in use after 3 retries`, killing
* the user's dev command instead of attaching to the sidecar.
*
* Only a transport-level failure (connection refused, timeout) counts as
* "no server". If the responder turns out not to speak the envelope
* protocol, {@link consumeSSE} reports that when the stream fails to open.
*/
export async function isServerRunning(url: string): Promise<boolean> {
try {
const res = await fetch(`${url}/health`, {
signal: AbortSignal.timeout(2000),
});
return res.ok;
if (!res.ok) {
logger.debug(
`Server at ${url} answered /health with HTTP ${res.status}; treating the port as occupied`
);
}
return true;
} catch (err) {
logger.debug(
`No existing server at ${url}`,
Expand Down
27 changes: 27 additions & 0 deletions packages/cli/test/commands/local/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
*/

import { createSpotlightBuffer } from "@spotlightjs/spotlight/sdk";
import { Hono } from "hono";
import { describe, expect, test } from "vitest";
import {
buildApp,
feedSSELine,
isServerRunning,
parsePort,
SERVER_IDENTIFIER,
tryListen,
} from "../../../src/commands/local/server.js";
import { ValidationError } from "../../../src/lib/errors.js";
import { SENTRY_CONTENT_TYPE } from "../../../src/lib/formatters/local.js";
Expand Down Expand Up @@ -315,6 +317,31 @@ describe("buildApp", () => {
});

describe("isServerRunning", () => {
test("returns true when /health answers with an error status", async () => {
// Spotlight's sidecar can 5xx on /health while still holding the port and
// ingesting envelopes. Reporting "no server" made the CLI try to bind the
// port anyway and abort with "Port 8969 is in use after 3 retries".
const unhealthy = new Hono();
unhealthy.get("/health", (c) => c.text("Internal Server Error", 500));
const { server, port } = await tryListen(unhealthy, 0, "127.0.0.1");

const savedFetch = globalThis.fetch;
const realFetch = (globalThis as { __originalFetch?: typeof fetch })
.__originalFetch;
if (realFetch) {
globalThis.fetch = realFetch;
}

try {
await expect(isServerRunning(`http://127.0.0.1:${port}`)).resolves.toBe(
true
);
} finally {
globalThis.fetch = savedFetch;
await new Promise<void>((done) => server.close(() => done()));
}
});

test("returns false when no server is running", async () => {
// isServerRunning uses global fetch which is mocked in tests.
// Verify the function handles connection errors gracefully.
Expand Down
Loading