Open History to see the last commit
1import { describe, expect, it, vi } from "vitest";
2
3import { resolveDesktopBackendPort } from "./backendPort.ts";
4
5describe("resolveDesktopBackendPort", () => {
6 it("returns the starting port when it is available", async () => {
7 const canListenOnHost = vi.fn(async (port: number) => port === 3773);
8
9 await expect(
10 resolveDesktopBackendPort({
11 host: "127.0.0.1",
12 startPort: 3773,
13 canListenOnHost,
14 }),
15 ).resolves.toBe(3773);
16
17 expect(canListenOnHost).toHaveBeenCalledTimes(1);
18 expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
19 });
20
21 it("increments sequentially until it finds an available port", async () => {
22 const canListenOnHost = vi.fn(async (port: number) => port === 3775);
23
24 await expect(
25 resolveDesktopBackendPort({
26 host: "127.0.0.1",
27 startPort: 3773,
28 canListenOnHost,
29 }),
30 ).resolves.toBe(3775);
31
32 expect(canListenOnHost.mock.calls).toEqual([
33 [3773, "127.0.0.1"],
34 [3774, "127.0.0.1"],
35 [3775, "127.0.0.1"],
36 ]);
37 });
38
39 it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
40 const canListenOnHost = vi.fn(async (port: number, host: string) => {
41 if (port === 3773 && host === "127.0.0.1") return true;
42 if (port === 3773 && host === "0.0.0.0") return false;
43 return port === 3774;
44 });
45
46 await expect(
47 resolveDesktopBackendPort({
48 host: "127.0.0.1",
49 requiredHosts: ["0.0.0.0"],
50 startPort: 3773,
51 canListenOnHost,
52 }),
53 ).resolves.toBe(3774);
54
55 expect(canListenOnHost.mock.calls).toEqual([
56 [3773, "127.0.0.1"],
57 [3773, "0.0.0.0"],
58 [3774, "127.0.0.1"],
59 [3774, "0.0.0.0"],
60 ]);
61 });
62
63 it("checks overlapping hosts sequentially to avoid self-interference", async () => {
64 let inFlightCount = 0;
65 const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
66 inFlightCount += 1;
67 const overlapped = inFlightCount > 1;
68 await Promise.resolve();
69 inFlightCount -= 1;
70 return !overlapped;
71 });
72
73 await expect(
74 resolveDesktopBackendPort({
75 host: "127.0.0.1",
76 requiredHosts: ["0.0.0.0", "::"],
77 startPort: 3773,
78 maxPort: 3773,
79 canListenOnHost,
80 }),
81 ).resolves.toBe(3773);
82
83 expect(canListenOnHost.mock.calls).toEqual([
84 [3773, "127.0.0.1"],
85 [3773, "0.0.0.0"],
86 [3773, "::"],
87 ]);
88 });
89
90 it("fails when the scan range is exhausted", async () => {
91 const canListenOnHost = vi.fn(async () => false);
92
93 await expect(
94 resolveDesktopBackendPort({
95 host: "127.0.0.1",
96 startPort: 65534,
97 maxPort: 65535,
98 canListenOnHost,
99 }),
100 ).rejects.toThrow(
101 "No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
102 );
103
104 expect(canListenOnHost.mock.calls).toEqual([
105 [65534, "127.0.0.1"],
106 [65535, "127.0.0.1"],
107 ]);
108 });
109});