Merge pull request #2039 from modelcontextprotocol/v2/chore/1959-no-floating-promises

chore(lint): enable @typescript-eslint/no-floating-promises in all five ESLint scopes
This commit is contained in:
Cliff Hall 2026-08-16 22:35:52 -04:00 • committed by GitHub
commit 405d0f4d0d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 656 additions and 113 deletions

View file

@ -69,25 +69,27 @@ type Story = StoryObj<typeof Button>;
export const ProjectAnnotationsApplied: Story = {
play: async ({ canvasElement, parameters }) => {
const canvas = within(canvasElement);
expect(canvas.getByRole("button", { name: "Themed" })).toBeInTheDocument();
await expect(
canvas.getByRole("button", { name: "Themed" }),
).toBeInTheDocument();
const root = getComputedStyle(document.documentElement);
// `MantineProvider` (the `./preview` decorator) injects the theme's CSS
// variables onto `:root`. No provider, no variables.
expect(root.getPropertyValue("--mantine-primary-color-filled").trim()).toBe(
expectedPrimaryColor(),
);
await expect(
root.getPropertyValue("--mantine-primary-color-filled").trim(),
).toBe(expectedPrimaryColor());
// `--inspector-brand-primary` is defined in `App.css`, which only reaches
// the story through `./preview`'s stylesheet import — and it resolves
// *through* the Mantine variable above, so this covers both layers.
expect(root.getPropertyValue("--inspector-brand-primary").trim()).toBe(
expectedPrimaryColor(),
);
await expect(
root.getPropertyValue("--inspector-brand-primary").trim(),
).toBe(expectedPrimaryColor());
// The preview `parameters` merged into the story context — the same channel
// that carries `a11y: { test: "error" }` to the a11y addon.
expect(parameters.a11y).toMatchObject({ test: "error" });
await expect(parameters.a11y).toMatchObject({ test: "error" });
},
};

View file

@ -117,12 +117,12 @@ describe("EmaTransportOAuthProvider", () => {
expect(await provider.clientInformation()).toEqual({ client_id: "abc" });
expect(await provider.codeVerifier()).toBe("verifier-xyz");
provider.saveClientInformation({ client_id: "new" } as never);
await provider.saveClientInformation({ client_id: "new" } as never);
expect(inner.saveClientInformation).toHaveBeenCalledWith({
client_id: "new",
});
provider.saveCodeVerifier("cv");
await provider.saveCodeVerifier("cv");
expect(inner.saveCodeVerifier).toHaveBeenCalledWith("cv");
});

View file

@ -1588,7 +1588,7 @@ describe("OAuthManager", () => {
});
const provider = await manager.createOAuthProviderForTransport();
provider.redirectToAuthorization(
await provider.redirectToAuthorization(
new URL("https://as.example.com/authorize?client_id=abc&state=xyz"),
);
@ -1610,7 +1610,7 @@ describe("OAuthManager", () => {
});
const provider = await manager.createOAuthProviderForTransport();
provider.redirectToAuthorization(
await provider.redirectToAuthorization(
new URL("https://as.example.com/authorize?client_id=abc&state=xyz"),
);

View file

@ -20,6 +20,7 @@ import { serve } from "@hono/node-server";
import type { ServerType } from "@hono/node-server";
import type pinoType from "pino";
import {
closeAbortedStream,
createRemoteApp,
requestIdForSendWait,
mcpParamHeadersOnly,
@ -1107,4 +1108,37 @@ describe("server.ts supplemental coverage", () => {
}
});
});
describe("closeAbortedStream", () => {
it("owns a rejected close instead of letting it go unhandled", async () => {
// The whole reason the helper exists. Both SSE `onAbort` listeners run
// after the peer is already gone, so `close()` can lose the race and
// reject — and Hono invokes abort subscribers with a bare
// `subscriber()`, so nothing upstream would catch it. A regression here
// does not fail at the call site; it fails the whole vitest run from
// wherever the rejection happens to surface.
const rejected = Promise.reject(new Error("peer already gone"));
const unhandled: unknown[] = [];
const onUnhandled = (err: unknown) => unhandled.push(err);
process.on("unhandledRejection", onUnhandled);
try {
expect(closeAbortedStream({ close: () => rejected })).toBeUndefined();
// An unhandledRejection fires on a later macrotask, not this one.
await new Promise((resolve) => setTimeout(resolve, 20));
} finally {
process.off("unhandledRejection", onUnhandled);
}
expect(unhandled).toEqual([]);
});
it("returns without waiting on a close that resolves", async () => {
let closed = false;
closeAbortedStream({
close: async () => {
closed = true;
},
});
await Promise.resolve();
expect(closed).toBe(true);
});
});
});

View file

@ -0,0 +1,149 @@
/**
* `autoOpen` browser launch (#1959).
*
* Both servers call `openBrowser` from a synchronous callback — the prod
* server from `serve()`'s listen callback, the dev plugin from `logBanner` —
* so a rejection there has nowhere to go. On a headless or otherwise
* browser-less host that rejection is the *ordinary* outcome, not an edge
* case, and before #1959 it escaped as an unhandled rejection from a server
* that had already started listening and printed a perfectly usable URL.
*
* The helper is shared precisely so this behavior has one implementation to
* pin. The unit tests below cover it directly; the end-to-end test then
* proves the prod server routes through it and survives the failure. The dev
* plugin is not booted here — it returns early under `VITEST` by design (see
* `vite-hono-plugin.ts`) — but it calls the same tested helper.
*/
import { describe, it, expect, afterEach, vi } from "vitest";
import { createServer } from "node:net";
import { mkdtemp, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { WebServerConfig } from "../../../../server/web-server-config.js";
import type { WebServerHandle } from "../../../../server/types.js";
const openMock = vi.hoisted(() => vi.fn());
vi.mock("open", () => ({ default: openMock }));
// Imported after the mock is registered so both bind to the double.
const { openBrowser } = await import("../../../../server/web-server-config.js");
const { startHonoServer } = await import("../../../../server/server.js");
const WARNING = "Could not open a browser automatically:";
async function findFreePort(): Promise<number> {
return new Promise((resolve, reject) => {
const srv = createServer();
srv.unref();
srv.on("error", reject);
srv.listen(0, "127.0.0.1", () => {
const addr = srv.address();
if (addr && typeof addr === "object") {
const { port } = addr;
srv.close(() => resolve(port));
} else {
srv.close(() => reject(new Error("Could not resolve a free port")));
}
});
});
}
/** An unhandledRejection fires on a later macrotask than the rejection. */
async function settle() {
await new Promise((resolve) => setTimeout(resolve, 50));
}
const INDEX_HTML =
"<!doctype html><html><body><div id=root></div></body></html>";
let handle: WebServerHandle | undefined;
let staticRoot: string | undefined;
afterEach(async () => {
await handle?.close();
handle = undefined;
if (staticRoot) await rm(staticRoot, { recursive: true, force: true });
staticRoot = undefined;
openMock.mockReset();
vi.restoreAllMocks();
});
describe("openBrowser", () => {
it("owns a rejection and warns instead of letting it go unhandled", async () => {
// Suppress the expected warning rather than letting it pollute the run,
// but assert on it — the warning IS the user-visible half of the fix.
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const unhandled: unknown[] = [];
const onUnhandled = (err: unknown) => unhandled.push(err);
process.on("unhandledRejection", onUnhandled);
try {
openMock.mockRejectedValue(new Error("no browser on this host"));
expect(openBrowser("http://127.0.0.1:6274")).toBeUndefined();
await settle();
} finally {
process.off("unhandledRejection", onUnhandled);
}
expect(unhandled).toEqual([]);
expect(warn).toHaveBeenCalledWith(WARNING, expect.any(Error));
});
it("stays quiet when the browser opens", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
openMock.mockResolvedValue(undefined);
openBrowser("http://127.0.0.1:6274");
await settle();
expect(openMock).toHaveBeenCalledWith("http://127.0.0.1:6274");
expect(warn).not.toHaveBeenCalledWith(WARNING, expect.anything());
});
});
describe("startHonoServer autoOpen", () => {
it("keeps serving when the browser cannot be opened", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const unhandled: unknown[] = [];
const onUnhandled = (err: unknown) => unhandled.push(err);
process.on("unhandledRejection", onUnhandled);
try {
openMock.mockRejectedValue(new Error("no browser on this host"));
staticRoot = await mkdtemp(join(tmpdir(), "inspector-autoopen-"));
await writeFile(join(staticRoot, "index.html"), INDEX_HTML, "utf-8");
const port = await findFreePort();
const baseUrl = `http://127.0.0.1:${port}`;
const config: WebServerConfig = {
port,
hostname: "127.0.0.1",
authToken: "auto-open-token",
dangerouslyOmitAuth: false,
initialMcpConfig: null,
mcpConfigPath: undefined,
writable: true,
initialServers: null,
storageDir: undefined,
allowedOrigins: [baseUrl],
sandboxPort: 0,
sandboxHost: "127.0.0.1",
logger: undefined,
autoOpen: true,
staticRoot,
};
handle = await startHonoServer(config);
// `serve()`'s listen callback fires after startHonoServer resolves.
for (let i = 0; i < 100 && openMock.mock.calls.length === 0; i++) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
await settle();
expect(openMock).toHaveBeenCalledWith(expect.stringContaining(baseUrl));
expect(unhandled).toEqual([]);
expect(warn).toHaveBeenCalledWith(WARNING, expect.any(Error));
// The point of warning rather than throwing: the server is still up.
const res = await fetch(`${baseUrl}/`);
expect(res.status).toBe(200);
} finally {
process.off("unhandledRejection", onUnhandled);
}
});
});

View file

@ -6,22 +6,24 @@ import { expect } from "storybook/test";
* hidden when idle (`type="scroll"`, so it shows only while scrolling rather
* than on hover). Shared by the Protocol/Network/Logging panel stories (#1474).
*/
export function expectScrollbarGutterIdleHidden(canvasElement: HTMLElement) {
export async function expectScrollbarGutterIdleHidden(
canvasElement: HTMLElement,
) {
const viewport = canvasElement.querySelector(".mantine-ScrollArea-viewport");
if (!(viewport instanceof HTMLElement)) {
throw new Error("scroll viewport not found");
}
// offsetScrollbars reserves a non-zero inline-end gutter for the scrollbar.
const pad = parseFloat(getComputedStyle(viewport).paddingInlineEnd);
expect(pad).toBeGreaterThan(0);
await expect(pad).toBeGreaterThan(0);
// type="scroll" → scrollbars are mounted but hidden until the user scrolls.
// Assert at least one exists first so the loop isn't trivially-true if a
// future change stops rendering the scrollbar element.
const scrollbars = canvasElement.querySelectorAll(
".mantine-ScrollArea-scrollbar",
);
expect(scrollbars.length).toBeGreaterThan(0);
await expect(scrollbars.length).toBeGreaterThan(0);
for (const bar of scrollbars) {
expect(bar.getAttribute("data-state")).toBe("hidden");
await expect(bar.getAttribute("data-state")).toBe("hidden");
}
}