fix(infra): guard os.networkInterfaces errors

This commit is contained in:
Hongpeng Jin 2026-01-29 16:50:21 -05:00
parent 4583f88626
commit 63da3808f4
2 changed files with 54 additions and 15 deletions

View File

@ -0,0 +1,33 @@
import { describe, expect, it, vi } from "vitest";
const realOs = await vi.importActual<typeof import("node:os")>("node:os");
vi.mock("node:os", () => {
const hostname = () => "moltbot-test-host";
const platform = () => "linux";
const networkInterfaces = () => {
throw new Error("uv_interface_addresses returned Unknown system error 1");
};
return {
...realOs,
default: {
...realOs,
hostname,
platform,
networkInterfaces,
},
hostname,
platform,
networkInterfaces,
};
});
describe("system-presence", () => {
it("does not crash when os.networkInterfaces throws", async () => {
vi.resetModules();
const { listSystemPresence } = await import("./system-presence.js");
const entries = listSystemPresence();
expect(entries.length).toBeGreaterThan(0);
expect(entries.some((entry) => entry.host === "moltbot-test-host")).toBe(true);
});
});

View File

@ -39,6 +39,7 @@ function normalizePresenceKey(key: string | undefined): string | undefined {
} }
function resolvePrimaryIPv4(): string | undefined { function resolvePrimaryIPv4(): string | undefined {
try {
const nets = os.networkInterfaces(); const nets = os.networkInterfaces();
const prefer = ["en0", "eth0"]; const prefer = ["en0", "eth0"];
const pick = (names: string[]) => { const pick = (names: string[]) => {
@ -54,6 +55,11 @@ function resolvePrimaryIPv4(): string | undefined {
return undefined; return undefined;
}; };
return pick(prefer) ?? os.hostname(); return pick(prefer) ?? os.hostname();
} catch {
// Some environments (e.g. certain VPS setups) can throw from os.networkInterfaces().
// Fall back to hostname so the CLI can still boot.
return os.hostname();
}
} }
function initSelfPresence() { function initSelfPresence() {