test: dedupe slack missing-thread tests and cover history failures

This commit is contained in:
Peter Steinberger
2026-02-18 05:31:06 +00:00
parent 12ad708ce5
commit a9cce800df
2 changed files with 77 additions and 150 deletions

View File

@@ -34,6 +34,7 @@ type SlackClient = {
conversations: { conversations: {
info: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>>; info: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>>;
replies: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>>; replies: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>>;
history: Mock<(...args: unknown[]) => Promise<Record<string, unknown>>>;
}; };
users: { users: {
info: Mock<(...args: unknown[]) => Promise<{ user: { profile: { display_name: string } } }>>; info: Mock<(...args: unknown[]) => Promise<{ user: { profile: { display_name: string } } }>>;
@@ -197,6 +198,7 @@ vi.mock("@slack/bolt", () => {
channel: { name: "dm", is_im: true }, channel: { name: "dm", is_im: true },
}), }),
replies: vi.fn().mockResolvedValue({ messages: [] }), replies: vi.fn().mockResolvedValue({ messages: [] }),
history: vi.fn().mockResolvedValue({ messages: [] }),
}, },
users: { users: {
info: vi.fn().mockResolvedValue({ info: vi.fn().mockResolvedValue({

View File

@@ -1,122 +1,75 @@
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
import { resetInboundDedupe } from "../auto-reply/reply/inbound-dedupe.js"; import { resetInboundDedupe } from "../auto-reply/reply/inbound-dedupe.js";
import {
flush,
getSlackClient,
getSlackHandlerOrThrow,
getSlackTestState,
resetSlackTestState,
startSlackMonitor,
stopSlackMonitor,
} from "./monitor.test-helpers.js";
const { monitorSlackProvider } = await import("./monitor.js"); const { monitorSlackProvider } = await import("./monitor.js");
const sendMock = vi.fn(); const slackTestState = getSlackTestState();
const replyMock = vi.fn();
const updateLastRouteMock = vi.fn();
const reactMock = vi.fn();
let config: Record<string, unknown> = {};
const readAllowFromStoreMock = vi.fn();
const upsertPairingRequestMock = vi.fn();
const getSlackHandlers = () =>
(
globalThis as {
__slackHandlers?: Map<string, (args: unknown) => Promise<void>>;
}
).__slackHandlers;
const getSlackClient = () =>
(globalThis as { __slackClient?: Record<string, unknown> }).__slackClient;
vi.mock("../config/config.js", async (importOriginal) => { type SlackConversationsClient = {
const actual = await importOriginal<typeof import("../config/config.js")>(); history: ReturnType<typeof vi.fn>;
info: ReturnType<typeof vi.fn>;
};
function makeThreadReplyEvent() {
return { return {
...actual, event: {
loadConfig: () => config, type: "message",
}; user: "U1",
}); text: "hello",
ts: "456",
vi.mock("../auto-reply/reply.js", () => ({ parent_user_id: "U2",
getReplyFromConfig: (...args: unknown[]) => replyMock(...args), channel: "C1",
})); channel_type: "channel",
vi.mock("./resolve-channels.js", () => ({
resolveSlackChannelAllowlist: async ({ entries }: { entries: string[] }) =>
entries.map((input) => ({ input, resolved: false })),
}));
vi.mock("./resolve-users.js", () => ({
resolveSlackUserAllowlist: async ({ entries }: { entries: string[] }) =>
entries.map((input) => ({ input, resolved: false })),
}));
vi.mock("./send.js", () => ({
sendMessageSlack: (...args: unknown[]) => sendMock(...args),
}));
vi.mock("../pairing/pairing-store.js", () => ({
readChannelAllowFromStore: (...args: unknown[]) => readAllowFromStoreMock(...args),
upsertChannelPairingRequest: (...args: unknown[]) => upsertPairingRequestMock(...args),
}));
vi.mock("../config/sessions.js", () => ({
resolveStorePath: vi.fn(() => "/tmp/openclaw-sessions.json"),
updateLastRoute: (...args: unknown[]) => updateLastRouteMock(...args),
resolveSessionKey: vi.fn(),
readSessionUpdatedAt: vi.fn(() => undefined),
recordSessionMetaFromInbound: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@slack/bolt", () => {
const handlers = new Map<string, (args: unknown) => Promise<void>>();
(globalThis as { __slackHandlers?: typeof handlers }).__slackHandlers = handlers;
const client = {
auth: { test: vi.fn().mockResolvedValue({ user_id: "bot-user" }) },
conversations: {
info: vi.fn().mockResolvedValue({
channel: { name: "general", is_channel: true },
}),
replies: vi.fn().mockResolvedValue({ messages: [] }),
history: vi.fn().mockResolvedValue({ messages: [] }),
},
users: {
info: vi.fn().mockResolvedValue({
user: { profile: { display_name: "Ada" } },
}),
},
assistant: {
threads: {
setStatus: vi.fn().mockResolvedValue({ ok: true }),
},
},
reactions: {
add: (...args: unknown[]) => reactMock(...args),
}, },
}; };
(globalThis as { __slackClient?: typeof client }).__slackClient = client; }
class App {
client = client;
event(name: string, handler: (args: unknown) => Promise<void>) {
handlers.set(name, handler);
}
command() {
/* no-op */
}
start = vi.fn().mockResolvedValue(undefined);
stop = vi.fn().mockResolvedValue(undefined);
}
class HTTPReceiver {
requestListener = vi.fn();
}
return { App, HTTPReceiver, default: { App, HTTPReceiver } };
});
const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); function getConversationsClient(): SlackConversationsClient {
const client = getSlackClient();
async function waitForEvent(name: string) { if (!client) {
for (let i = 0; i < 10; i += 1) { throw new Error("Slack client not registered");
if (getSlackHandlers()?.has(name)) {
return;
}
await flush();
} }
return client.conversations as SlackConversationsClient;
}
async function runMissingThreadScenario(params: {
historyResponse?: { messages: Array<{ ts?: string; thread_ts?: string }> };
historyError?: Error;
}) {
slackTestState.replyMock.mockResolvedValue({ text: "thread reply" });
const conversations = getConversationsClient();
if (params.historyError) {
conversations.history.mockRejectedValueOnce(params.historyError);
} else {
conversations.history.mockResolvedValueOnce(
params.historyResponse ?? { messages: [{ ts: "456" }] },
);
}
const { controller, run } = startSlackMonitor(monitorSlackProvider);
const handler = await getSlackHandlerOrThrow("message");
await handler(makeThreadReplyEvent());
await flush();
await stopSlackMonitor({ controller, run });
expect(slackTestState.sendMock).toHaveBeenCalledTimes(1);
return slackTestState.sendMock.mock.calls[0]?.[2];
} }
beforeEach(() => { beforeEach(() => {
resetInboundDedupe(); resetInboundDedupe();
getSlackHandlers()?.clear(); resetSlackTestState({
config = {
messages: { responsePrefix: "PFX" }, messages: { responsePrefix: "PFX" },
channels: { channels: {
slack: { slack: {
@@ -125,60 +78,32 @@ beforeEach(() => {
channels: { C1: { allow: true, requireMention: false } }, channels: { C1: { allow: true, requireMention: false } },
}, },
}, },
}; });
sendMock.mockReset().mockResolvedValue(undefined); const conversations = getConversationsClient();
replyMock.mockReset(); conversations.info.mockResolvedValue({
updateLastRouteMock.mockReset(); channel: { name: "general", is_channel: true },
reactMock.mockReset(); });
readAllowFromStoreMock.mockReset().mockResolvedValue([]);
upsertPairingRequestMock.mockReset().mockResolvedValue({ code: "PAIRCODE", created: true });
}); });
describe("monitorSlackProvider threading", () => { describe("monitorSlackProvider threading", () => {
it("recovers missing thread_ts when parent_user_id is present", async () => { it("recovers missing thread_ts when parent_user_id is present", async () => {
replyMock.mockResolvedValue({ text: "thread reply" }); const options = await runMissingThreadScenario({
historyResponse: { messages: [{ ts: "456", thread_ts: "111.222" }] },
const client = getSlackClient();
if (!client) {
throw new Error("Slack client not registered");
}
const conversations = client.conversations as {
history: ReturnType<typeof vi.fn>;
};
conversations.history.mockResolvedValueOnce({
messages: [{ ts: "456", thread_ts: "111.222" }],
}); });
expect(options).toMatchObject({ threadTs: "111.222" });
});
const controller = new AbortController(); it("continues without thread_ts when history lookup returns no thread result", async () => {
const run = monitorSlackProvider({ const options = await runMissingThreadScenario({
botToken: "bot-token", historyResponse: { messages: [{ ts: "456" }] },
appToken: "app-token",
abortSignal: controller.signal,
}); });
expect(options).not.toMatchObject({ threadTs: "111.222" });
});
await waitForEvent("message"); it("continues without thread_ts when history lookup throws", async () => {
const handler = getSlackHandlers()?.get("message"); const options = await runMissingThreadScenario({
if (!handler) { historyError: new Error("history failed"),
throw new Error("Slack message handler not registered");
}
await handler({
event: {
type: "message",
user: "U1",
text: "hello",
ts: "456",
parent_user_id: "U2",
channel: "C1",
channel_type: "channel",
},
}); });
expect(options).not.toMatchObject({ threadTs: "111.222" });
await flush();
controller.abort();
await run;
expect(sendMock).toHaveBeenCalledTimes(1);
expect(sendMock.mock.calls[0][2]).toMatchObject({ threadTs: "111.222" });
}); });
}); });