Skip to content

Commit 62014e0

Browse files
committed
fix gateway status sandbox diagnostics
1 parent 2af2111 commit 62014e0

6 files changed

Lines changed: 121 additions & 12 deletions

File tree

‎src/cli/daemon-cli/status.gather.test.ts‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ import os from "node:os";
33
import path from "node:path";
44
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
import type { StaleOpenClawUpdateLaunchdJob } from "../../daemon/launchd.js";
6+
import type { GatewayServiceRuntime } from "../../daemon/service-runtime.js";
67
import { createMockGatewayService } from "../../daemon/service.test-helpers.js";
7-
import type { PortConnections } from "../../infra/ports.js";
8+
import type { PortConnections, PortUsage } from "../../infra/ports.js";
89
import type { GatewayRestartHandoff } from "../../infra/restart-handoff.js";
910
import { captureEnv } from "../../test-utils/env.js";
1011
import { VERSION } from "../../version.js";
@@ -34,7 +35,7 @@ const findExtraGatewayServices = vi.fn(async (_env?: unknown, _opts?: unknown) =
3435
const findStaleOpenClawUpdateLaunchdJobs = vi.fn<
3536
(env?: NodeJS.ProcessEnv) => Promise<StaleOpenClawUpdateLaunchdJob[]>
3637
>(async () => []);
37-
const inspectPortUsage = vi.fn(async (port: number) => ({
38+
const inspectPortUsage = vi.fn<(port: number) => Promise<PortUsage>>(async (port: number) => ({
3839
port,
3940
status: "free" as const,
4041
listeners: [],
@@ -52,7 +53,9 @@ const readGatewayRestartHandoffSync = vi.fn<
5253
>(() => null);
5354
const auditGatewayServiceConfig = vi.fn(async (_opts?: unknown) => undefined);
5455
const serviceIsLoaded = vi.fn(async (_opts?: unknown) => true);
55-
const serviceReadRuntime = vi.fn(async (_env?: NodeJS.ProcessEnv) => ({ status: "running" }));
56+
const serviceReadRuntime = vi.fn<(_env?: NodeJS.ProcessEnv) => Promise<GatewayServiceRuntime>>(
57+
async (_env?: NodeJS.ProcessEnv) => ({ status: "running" }),
58+
);
5659
const inspectGatewayRestart = vi.fn<(opts?: unknown) => Promise<GatewayRestartSnapshot>>(
5760
async (_opts?: unknown) => ({
5861
runtime: { status: "running", pid: 1234 },
@@ -453,6 +456,32 @@ describe("gatherDaemonStatus", () => {
453456
expect((status.service.runtime as { detail?: string }).detail).toBe("19001");
454457
});
455458

459+
it("suppresses busy-port hints when all listeners belong to the running gateway pid", async () => {
460+
serviceReadRuntime.mockResolvedValueOnce({ status: "running", pid: 73614 });
461+
inspectPortUsage.mockResolvedValueOnce({
462+
port: 19001,
463+
status: "busy",
464+
listeners: [
465+
{ pid: 73614, command: "node", address: "127.0.0.1:19001" },
466+
{ pid: 73614, command: "node", address: "[::1]:19001" },
467+
],
468+
hints: [
469+
"Another process is listening on this port.",
470+
"Multiple listeners detected; ensure only one gateway/tunnel per port unless intentionally running isolated profiles.",
471+
],
472+
});
473+
474+
const status = await gatherDaemonStatus({
475+
rpc: {},
476+
probe: false,
477+
deep: false,
478+
});
479+
480+
expect(status.port?.status).toBe("busy");
481+
expect(status.port?.listeners).toHaveLength(2);
482+
expect(status.port?.hints).toEqual([]);
483+
});
484+
456485
it("surfaces recent service restart handoffs only during deep status", async () => {
457486
readGatewayRestartHandoffSync.mockReturnValueOnce({
458487
kind: "gateway-supervisor-restart-handoff",

‎src/cli/daemon-cli/status.gather.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
resolveBestEffortGatewayBindHostForDisplay,
2626
} from "../../infra/network-discovery-display.js";
2727
import { parseStrictPositiveInteger } from "../../infra/parse-finite-number.js";
28+
import { isExpectedGatewayListenersForPid } from "../../infra/ports-format.js";
2829
import {
2930
formatPortDiagnostics,
3031
inspectPortConnections,
@@ -450,6 +451,22 @@ function toPortStatusSummary(
450451
};
451452
}
452453

454+
function suppressKnownGatewayPortHints(
455+
status: PortStatusSummary | undefined,
456+
runtime: GatewayServiceRuntime | undefined,
457+
): PortStatusSummary | undefined {
458+
if (status?.status !== "busy" || status.hints.length === 0 || runtime?.status !== "running") {
459+
return status;
460+
}
461+
if (!isExpectedGatewayListenersForPid(status.listeners, status.port, runtime.pid)) {
462+
return status;
463+
}
464+
return {
465+
...status,
466+
hints: [],
467+
};
468+
}
469+
453470
async function inspectDaemonPortStatuses(params: {
454471
daemonPort: number;
455472
cliPort: number;
@@ -537,6 +554,7 @@ export async function gatherDaemonStatus(
537554
daemonPort,
538555
cliPort,
539556
});
557+
const daemonPortStatus = suppressKnownGatewayPortHints(portStatus, runtime);
540558
const establishedClients = await inspectEstablishedGatewayClients({
541559
daemonPort,
542560
deep: opts.deep,
@@ -633,7 +651,12 @@ export async function gatherDaemonStatus(
633651
: undefined;
634652

635653
let lastError: string | undefined;
636-
if (loaded && runtime?.status === "running" && portStatus && portStatus.status !== "busy") {
654+
if (
655+
loaded &&
656+
runtime?.status === "running" &&
657+
daemonPortStatus &&
658+
daemonPortStatus.status !== "busy"
659+
) {
637660
lastError = (await readLastGatewayErrorLine(mergedDaemonEnv as NodeJS.ProcessEnv)) ?? undefined;
638661
}
639662

@@ -664,7 +687,7 @@ export async function gatherDaemonStatus(
664687
}
665688
: {}),
666689
},
667-
port: portStatus,
690+
port: daemonPortStatus,
668691
...(portCliStatus ? { portCli: portCliStatus } : {}),
669692
...(establishedClients ? { connections: establishedClients } : {}),
670693
lastError,

‎src/gateway/net.test.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import net from "node:net";
12
import os from "node:os";
23
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
34
import { makeNetworkInterfacesSnapshot } from "../test-helpers/network-interfaces.js";
@@ -22,6 +23,26 @@ import {
2223

2324
const flyMachineEnvKeys = ["FLY_MACHINE_ID", "FLY_APP_NAME"] as const;
2425

26+
function mockCanBindToHost(bindable: boolean) {
27+
vi.spyOn(net, "createServer").mockImplementation(() => {
28+
const handlers = new Map<string, () => void>();
29+
const server = {
30+
once: vi.fn((event: string, handler: () => void) => {
31+
handlers.set(event, handler);
32+
return server;
33+
}),
34+
listen: vi.fn(() => {
35+
queueMicrotask(() => {
36+
handlers.get(bindable ? "listening" : "error")?.();
37+
});
38+
return server;
39+
}),
40+
close: vi.fn(),
41+
};
42+
return server as unknown as net.Server;
43+
});
44+
}
45+
2546
function clearFlyMachineEnvForTest(): () => void {
2647
const previousEnv = new Map<(typeof flyMachineEnvKeys)[number], string | undefined>();
2748
for (const key of flyMachineEnvKeys) {
@@ -673,8 +694,11 @@ describe("resolveGatewayBindHost", () => {
673694
vi.restoreAllMocks();
674695
});
675696

676-
it("returns 127.0.0.1 for loopback mode", async () => {
697+
it("returns 127.0.0.1 for loopback mode without probing bind fallback", async () => {
698+
const createServer = vi.spyOn(net, "createServer");
699+
677700
expect(await resolveGatewayBindHost("loopback")).toBe("127.0.0.1");
701+
expect(createServer).not.toHaveBeenCalled();
678702
});
679703

680704
it("returns 0.0.0.0 for lan mode", async () => {
@@ -687,6 +711,7 @@ describe("resolveGatewayBindHost", () => {
687711
throw new Error("ENOENT");
688712
});
689713
vi.spyOn(fs, "readFileSync").mockReturnValue("12:memory:/user.slice\n");
714+
mockCanBindToHost(true);
690715
expect(await resolveGatewayBindHost("auto")).toBe("127.0.0.1");
691716
});
692717

‎src/gateway/net.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ export {
251251
* Resolves gateway bind host with fallback strategy.
252252
*
253253
* Modes:
254-
* - loopback: 127.0.0.1 (rarely fails, but handled gracefully)
254+
* - loopback: 127.0.0.1
255255
* - lan: always 0.0.0.0 (no fallback)
256256
* - tailnet: Tailnet IPv4 if available, else loopback
257257
* - auto: 0.0.0.0 inside containers (Docker/Podman/K8s); loopback otherwise
@@ -266,11 +266,7 @@ export async function resolveGatewayBindHost(
266266
const mode = bind ?? "loopback";
267267

268268
if (mode === "loopback") {
269-
// 127.0.0.1 rarely fails, but handle gracefully
270-
if (await canBindToHost("127.0.0.1")) {
271-
return "127.0.0.1";
272-
}
273-
return "0.0.0.0"; // extreme fallback
269+
return "127.0.0.1";
274270
}
275271

276272
if (mode === "tailnet") {

‎src/infra/ports-format.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
formatPortListener,
88
isDualStackLoopbackGatewayListeners,
99
isExpectedGatewayListeners,
10+
isExpectedGatewayListenersForPid,
1011
isSingleExpectedGatewayListener,
1112
} from "./ports-format.js";
1213

@@ -53,6 +54,17 @@ describe("ports-format", () => {
5354
expect(buildPortHints(listeners, 18789)).toEqual([]);
5455
});
5556

57+
it("recognizes expected loopback listeners owned by a known gateway service pid", () => {
58+
const listeners = [
59+
{ pid: 73614, command: "node", address: "127.0.0.1:18789" },
60+
{ pid: 73614, command: "node", address: "[::1]:18789" },
61+
];
62+
63+
expect(isExpectedGatewayListeners(listeners, 18789)).toBe(false);
64+
expect(isExpectedGatewayListenersForPid(listeners, 18789, 73614)).toBe(true);
65+
expect(isExpectedGatewayListenersForPid(listeners, 18789, 12345)).toBe(false);
66+
});
67+
5668
it.each([
5769
"127.0.0.1:18789",
5870
"[::1]:18789",

‎src/infra/ports-format.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,30 @@ export function isExpectedGatewayListeners(listeners: PortListener[], port: numb
134134
);
135135
}
136136

137+
export function isExpectedGatewayListenersForPid(
138+
listeners: PortListener[],
139+
port: number,
140+
pid: number | undefined,
141+
): boolean {
142+
if (!listeners.length || typeof pid !== "number" || !Number.isFinite(pid)) {
143+
return false;
144+
}
145+
for (const listener of listeners) {
146+
if (listener.pid !== pid || typeof listener.address !== "string") {
147+
return false;
148+
}
149+
const parsedAddress = parseListenerAddress(listener.address);
150+
if (
151+
!parsedAddress ||
152+
parsedAddress.port !== port ||
153+
!isExpectedGatewayBindAddress(parsedAddress.host)
154+
) {
155+
return false;
156+
}
157+
}
158+
return true;
159+
}
160+
137161
export function buildPortHints(listeners: PortListener[], port: number): string[] {
138162
if (listeners.length === 0) {
139163
return [];

0 commit comments

Comments
 (0)