perf(test): dedupe slow discord monitor cases

This commit is contained in:
Peter Steinberger
2026-02-18 04:03:59 +00:00
parent ac0db68235
commit b099171db5
3 changed files with 86 additions and 117 deletions

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { createExecTool } from "./bash-tools.exec.js";
const isWin = process.platform === "win32";
@@ -25,7 +26,6 @@ describe("exec script preflight", () => {
"utf-8",
);
const { createExecTool } = await import("./bash-tools.exec.js");
const tool = createExecTool({ host: "gateway", security: "full", ask: "off" });
await expect(
@@ -50,7 +50,6 @@ describe("exec script preflight", () => {
"utf-8",
);
const { createExecTool } = await import("./bash-tools.exec.js");
const tool = createExecTool({ host: "gateway", security: "full", ask: "off" });
await expect(

View File

@@ -8,11 +8,13 @@ import {
updateLastRouteMock,
upsertPairingRequestMock,
} from "./monitor.tool-result.test-harness.js";
import { createDiscordMessageHandler } from "./monitor/message-handler.js";
import { __resetDiscordChannelInfoCacheForTest } from "./monitor/message-utils.js";
type Config = ReturnType<typeof import("../config/config.js").loadConfig>;
beforeEach(() => {
vi.resetModules();
__resetDiscordChannelInfoCacheForTest();
sendMock.mockReset().mockResolvedValue(undefined);
updateLastRouteMock.mockReset();
dispatchMock.mockReset().mockImplementation(async ({ dispatcher }) => {
@@ -49,7 +51,6 @@ const CATEGORY_GUILD_CFG = {
} satisfies Config;
async function createDmHandler(opts: { cfg: Config; runtimeError?: (err: unknown) => void }) {
const { createDiscordMessageHandler } = await import("./monitor.js");
return createDiscordMessageHandler({
cfg: opts.cfg,
discordConfig: opts.cfg.channels?.discord,
@@ -73,19 +74,16 @@ async function createDmHandler(opts: { cfg: Config; runtimeError?: (err: unknown
});
}
function createDmClient(fetchChannel?: ReturnType<typeof vi.fn>) {
const resolvedFetchChannel =
fetchChannel ??
vi.fn().mockResolvedValue({
function createDmClient() {
return {
fetchChannel: vi.fn().mockResolvedValue({
type: ChannelType.DM,
name: "dm",
});
return { fetchChannel: resolvedFetchChannel } as unknown as Client;
}),
} as unknown as Client;
}
async function createCategoryGuildHandler() {
const { createDiscordMessageHandler } = await import("./monitor.js");
return createDiscordMessageHandler({
cfg: CATEGORY_GUILD_CFG,
discordConfig: CATEGORY_GUILD_CFG.channels?.discord,
@@ -124,108 +122,6 @@ function createCategoryGuildClient() {
}
describe("discord tool result dispatch", () => {
it("caches channel info lookups between messages", async () => {
const cfg = {
...BASE_CFG,
channels: { discord: { dm: { enabled: true, policy: "open" } } },
} as ReturnType<typeof import("../config/config.js").loadConfig>;
const handler = await createDmHandler({ cfg });
const fetchChannel = vi.fn().mockResolvedValue({
type: ChannelType.DM,
name: "dm",
});
const client = createDmClient(fetchChannel);
const baseMessage = {
content: "hello",
channelId: "cache-channel-1",
timestamp: new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
author: { id: "u-cache", bot: false, username: "Ada" },
};
await handler(
{
message: { ...baseMessage, id: "m-cache-1" },
author: baseMessage.author,
guild_id: null,
},
client,
);
await handler(
{
message: { ...baseMessage, id: "m-cache-2" },
author: baseMessage.author,
guild_id: null,
},
client,
);
expect(fetchChannel).toHaveBeenCalledTimes(1);
});
it("includes forwarded message snapshots in body", async () => {
let capturedBody = "";
dispatchMock.mockImplementationOnce(async ({ ctx, dispatcher }) => {
capturedBody = ctx.Body ?? "";
dispatcher.sendFinalReply({ text: "ok" });
return { queuedFinal: true, counts: { final: 1 } };
});
const cfg = {
...BASE_CFG,
channels: { discord: { dm: { enabled: true, policy: "open" } } },
} as ReturnType<typeof import("../config/config.js").loadConfig>;
const handler = await createDmHandler({ cfg });
const client = createDmClient();
await handler(
{
message: {
id: "m-forward-1",
content: "",
channelId: "c-forward-1",
timestamp: new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
author: { id: "u1", bot: false, username: "Ada" },
rawData: {
message_snapshots: [
{
message: {
content: "forwarded hello",
embeds: [],
attachments: [],
author: {
id: "u2",
username: "Bob",
discriminator: "0",
},
},
},
],
},
},
author: { id: "u1", bot: false, username: "Ada" },
guild_id: null,
},
client,
);
expect(capturedBody).toContain("[Forwarded message from @Bob]");
expect(capturedBody).toContain("forwarded hello");
});
it("uses channel id allowlists for non-thread channels with categories", async () => {
let capturedCtx: { SessionKey?: string } | undefined;
dispatchMock.mockImplementationOnce(async ({ ctx, dispatcher }) => {

View File

@@ -1,4 +1,4 @@
import type { Message } from "@buape/carbon";
import { ChannelType, type Client, type Message } from "@buape/carbon";
import { beforeEach, describe, expect, it, vi } from "vitest";
const fetchRemoteMedia = vi.fn();
@@ -16,8 +16,13 @@ vi.mock("../../globals.js", () => ({
logVerbose: () => {},
}));
const { resolveDiscordMessageChannelId, resolveForwardedMediaList } =
await import("./message-utils.js");
const {
__resetDiscordChannelInfoCacheForTest,
resolveDiscordChannelInfo,
resolveDiscordMessageChannelId,
resolveDiscordMessageText,
resolveForwardedMediaList,
} = await import("./message-utils.js");
function asMessage(payload: Record<string, unknown>): Message {
return payload as unknown as Message;
@@ -122,3 +127,72 @@ describe("resolveForwardedMediaList", () => {
expect(fetchRemoteMedia).not.toHaveBeenCalled();
});
});
describe("resolveDiscordMessageText", () => {
it("includes forwarded message snapshots in body text", () => {
const text = resolveDiscordMessageText(
asMessage({
content: "",
rawData: {
message_snapshots: [
{
message: {
content: "forwarded hello",
embeds: [],
attachments: [],
author: {
id: "u2",
username: "Bob",
discriminator: "0",
},
},
},
],
},
}),
{ includeForwarded: true },
);
expect(text).toContain("[Forwarded message from @Bob]");
expect(text).toContain("forwarded hello");
});
});
describe("resolveDiscordChannelInfo", () => {
beforeEach(() => {
__resetDiscordChannelInfoCacheForTest();
});
it("caches channel lookups between calls", async () => {
const fetchChannel = vi.fn().mockResolvedValue({
type: ChannelType.DM,
name: "dm",
});
const client = { fetchChannel } as unknown as Client;
const first = await resolveDiscordChannelInfo(client, "cache-channel-1");
const second = await resolveDiscordChannelInfo(client, "cache-channel-1");
expect(first).toEqual({
type: ChannelType.DM,
name: "dm",
topic: undefined,
parentId: undefined,
ownerId: undefined,
});
expect(second).toEqual(first);
expect(fetchChannel).toHaveBeenCalledTimes(1);
});
it("negative-caches missing channels", async () => {
const fetchChannel = vi.fn().mockResolvedValue(null);
const client = { fetchChannel } as unknown as Client;
const first = await resolveDiscordChannelInfo(client, "missing-channel");
const second = await resolveDiscordChannelInfo(client, "missing-channel");
expect(first).toBeNull();
expect(second).toBeNull();
expect(fetchChannel).toHaveBeenCalledTimes(1);
});
});