test: share discord monitor fixtures

This commit is contained in:
Peter Steinberger
2026-03-26 20:10:52 +00:00
parent e035a0d98c
commit 236e041ef9
9 changed files with 439 additions and 530 deletions

View File

@@ -1,237 +1,49 @@
import type { Client } from "@buape/carbon";
import { ChannelType, MessageType } from "@buape/carbon";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { dispatchMock } from "./monitor.tool-result.test-harness.js";
import {
dispatchMock,
loadConfigMock,
readAllowFromStoreMock,
updateLastRouteMock,
upsertPairingRequestMock,
} from "./monitor.tool-result.test-harness.js";
import { createDiscordMessageHandler } from "./monitor/message-handler.js";
import { __resetDiscordChannelInfoCacheForTest } from "./monitor/message-utils.js";
import { createNoopThreadBindingManager } from "./monitor/thread-bindings.js";
type Config = ReturnType<typeof import("../../../src/config/config.js").loadConfig>;
const BASE_CFG: Config = {
agents: {
defaults: {
model: { primary: "anthropic/claude-opus-4-5" },
workspace: "/tmp/openclaw",
},
},
messages: {
inbound: { debounceMs: 0 },
},
session: { store: "/tmp/openclaw-sessions.json" },
};
captureNextDispatchCtx,
type Config,
createGuildHandler,
createGuildMessageEvent,
createGuildTextClient,
createMentionRequiredGuildConfig,
createThreadChannel,
createThreadClient,
createThreadEvent,
resetDiscordToolResultHarness,
} from "./monitor.tool-result.test-helpers.js";
beforeEach(() => {
__resetDiscordChannelInfoCacheForTest();
updateLastRouteMock.mockClear();
dispatchMock.mockClear().mockImplementation(async ({ dispatcher }) => {
dispatcher.sendFinalReply({ text: "hi" });
return { queuedFinal: true, counts: { tool: 0, block: 0, final: 1 } };
});
readAllowFromStoreMock.mockClear().mockResolvedValue([]);
upsertPairingRequestMock.mockClear().mockResolvedValue({ code: "PAIRCODE", created: true });
loadConfigMock.mockClear().mockReturnValue(BASE_CFG);
resetDiscordToolResultHarness();
});
function createHandlerBaseConfig(cfg: Config): Parameters<typeof createDiscordMessageHandler>[0] {
return {
cfg,
discordConfig: cfg.channels?.discord,
accountId: "default",
token: "token",
runtime: {
log: vi.fn(),
error: vi.fn(),
exit: (code: number): never => {
throw new Error(`exit ${code}`);
},
},
botUserId: "bot-id",
guildHistories: new Map(),
historyLimit: 0,
mediaMaxBytes: 10_000,
textLimit: 2000,
replyToMode: "off",
dmEnabled: true,
groupDmEnabled: false,
threadBindings: createNoopThreadBindingManager("default"),
};
}
async function createHandler(cfg: Config) {
loadConfigMock.mockReturnValue(cfg);
return createDiscordMessageHandler({
...createHandlerBaseConfig(cfg),
guildEntries: cfg.channels?.discord?.guilds,
});
return createGuildHandler({ cfg });
}
function createGuildTextClient() {
function createOpenGuildConfig(
channels: Record<string, { allow: boolean; includeThreadStarter?: boolean }>,
extra: Partial<Config> = {},
): Config {
return {
fetchChannel: vi.fn().mockResolvedValue({
id: "c1",
type: ChannelType.GuildText,
name: "general",
}),
rest: { get: vi.fn() },
} as unknown as Client;
}
function createGuildMessageEvent(params: {
messageId: string;
content: string;
messagePatch?: Record<string, unknown>;
eventPatch?: Record<string, unknown>;
}) {
const messageBase = {
timestamp: new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
};
return {
message: {
id: params.messageId,
content: params.content,
channelId: "c1",
...messageBase,
author: { id: "u1", bot: false, username: "Ada" },
...params.messagePatch,
},
author: { id: "u1", bot: false, username: "Ada" },
member: { nickname: "Ada" },
guild: { id: "g1", name: "Guild" },
guild_id: "g1",
...params.eventPatch,
};
}
function createThreadChannel(params: { includeStarter?: boolean; type?: ChannelType } = {}) {
return {
id: "t1",
type: params.type ?? ChannelType.PublicThread,
name: "thread-name",
parentId: params.type === ChannelType.PublicThread ? "forum-1" : "p1",
parent: {
id: params.type === ChannelType.PublicThread ? "forum-1" : "p1",
name: params.type === ChannelType.PublicThread ? "support" : "general",
},
isThread: () => true,
...(params.includeStarter
? {
fetchStarterMessage: async () => ({
content: "starter message",
author: { tag: "Alice#1", username: "Alice" },
createdTimestamp: Date.now(),
}),
}
: {}),
};
}
function createThreadClient(
params: {
fetchChannel?: ReturnType<typeof vi.fn>;
restGet?: ReturnType<typeof vi.fn>;
} = {},
) {
return {
fetchChannel:
params.fetchChannel ??
vi
.fn()
.mockResolvedValueOnce({
id: "t1",
type: ChannelType.PublicThread,
name: "thread-name",
parentId: "p1",
ownerId: "owner-1",
})
.mockResolvedValueOnce({
id: "p1",
type: ChannelType.GuildText,
name: "general",
}),
rest: {
get:
params.restGet ??
vi.fn().mockResolvedValue({
content: "starter message",
author: { id: "u1", username: "Alice", discriminator: "0001" },
timestamp: new Date().toISOString(),
}),
},
} as unknown as Client;
}
function createThreadEvent(messageId: string, channelId = "t1") {
return {
message: {
id: messageId,
content: "thread hello",
channelId,
timestamp: new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
author: { id: "u1", bot: false, username: "Ada" },
},
author: { id: "u1", bot: false, username: "Ada" },
member: { nickname: "Ada" },
guild: { id: "g1", name: "Guild" },
guild_id: "g1",
};
}
function createMentionRequiredGuildConfig(overrides?: Partial<Config>): Config {
return {
...BASE_CFG,
...createMentionRequiredGuildConfig(),
...extra,
channels: {
discord: {
dm: { enabled: true, policy: "open" },
groupPolicy: "open",
guilds: {
"*": {
requireMention: true,
channels: { c1: { allow: true } },
requireMention: false,
channels,
},
},
},
},
...overrides,
} as Config;
}
function captureNextDispatchCtx<
T extends {
SessionKey?: string;
ParentSessionKey?: string;
ThreadStarterBody?: string;
ThreadLabel?: string;
WasMentioned?: boolean;
},
>(): () => T | undefined {
let capturedCtx: T | undefined;
dispatchMock.mockImplementationOnce(async ({ ctx, dispatcher }) => {
capturedCtx = ctx as T;
dispatcher.sendFinalReply({ text: "hi" });
return { queuedFinal: true, counts: { final: 1 } };
});
return () => capturedCtx;
}
describe("discord tool result dispatch", () => {
it("accepts guild messages when mentionPatterns match", async () => {
const cfg = createMentionRequiredGuildConfig({
@@ -289,21 +101,7 @@ describe("discord tool result dispatch", () => {
ThreadStarterBody?: string;
ThreadLabel?: string;
}>();
const cfg = {
...createMentionRequiredGuildConfig(),
channels: {
discord: {
dm: { enabled: true, policy: "open" },
groupPolicy: "open",
guilds: {
"*": {
requireMention: false,
channels: { p1: { allow: true } },
},
},
},
},
} as Config;
const cfg = createOpenGuildConfig({ p1: { allow: true } });
const handler = await createHandler(cfg);
const client = createThreadClient({
@@ -325,23 +123,9 @@ describe("discord tool result dispatch", () => {
it("skips thread starter context when disabled", async () => {
const getCapturedCtx = captureNextDispatchCtx<{ ThreadStarterBody?: string }>();
const cfg = {
...createMentionRequiredGuildConfig(),
channels: {
discord: {
dm: { enabled: true, policy: "open" },
groupPolicy: "open",
guilds: {
"*": {
requireMention: false,
channels: {
p1: { allow: true, includeThreadStarter: false },
},
},
},
},
},
} as Config;
const cfg = createOpenGuildConfig({
p1: { allow: true, includeThreadStarter: false },
});
const handler = await createHandler(cfg);
const client = createThreadClient();
@@ -359,21 +143,7 @@ describe("discord tool result dispatch", () => {
ThreadStarterBody?: string;
ThreadLabel?: string;
}>();
const cfg = {
...createMentionRequiredGuildConfig(),
channels: {
discord: {
dm: { enabled: true, policy: "open" },
groupPolicy: "open",
guilds: {
"*": {
requireMention: false,
channels: { "forum-1": { allow: true } },
},
},
},
},
} as Config;
const cfg = createOpenGuildConfig({ "forum-1": { allow: true } });
const fetchChannel = vi
.fn()
@@ -411,22 +181,10 @@ describe("discord tool result dispatch", () => {
SessionKey?: string;
ParentSessionKey?: string;
}>();
const cfg = {
...createMentionRequiredGuildConfig(),
bindings: [{ agentId: "support", match: { channel: "discord", guildId: "g1" } }],
channels: {
discord: {
dm: { enabled: true, policy: "open" },
groupPolicy: "open",
guilds: {
"*": {
requireMention: false,
channels: { p1: { allow: true } },
},
},
},
},
} as Config;
const cfg = createOpenGuildConfig(
{ p1: { allow: true } },
{ bindings: [{ agentId: "support", match: { channel: "discord", guildId: "g1" } }] },
);
const handler = await createHandler(cfg);
const client = createThreadClient();

View File

@@ -1,159 +1,26 @@
import type { Client } from "@buape/carbon";
import { MessageType } from "@buape/carbon";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { expectPairingReplyText } from "../../../test/helpers/pairing-reply.js";
import {
dispatchMock,
loadConfigMock,
readAllowFromStoreMock,
sendMock,
updateLastRouteMock,
upsertPairingRequestMock,
} from "./monitor.tool-result.test-harness.js";
import {
BASE_CFG,
createCategoryGuildClient,
createCategoryGuildEvent,
createCategoryGuildHandler,
createDmClient,
createDmHandler,
type Config,
resetDiscordToolResultHarness,
} from "./monitor.tool-result.test-helpers.js";
type Config = ReturnType<typeof import("../../../src/config/config.js").loadConfig>;
let ChannelType: typeof import("@buape/carbon").ChannelType;
let createDiscordMessageHandler: typeof import("./monitor/message-handler.js").createDiscordMessageHandler;
let __resetDiscordChannelInfoCacheForTest: typeof import("./monitor/message-utils.js").__resetDiscordChannelInfoCacheForTest;
let createNoopThreadBindingManager: typeof import("./monitor/thread-bindings.js").createNoopThreadBindingManager;
beforeAll(async () => {
({ ChannelType } = await import("@buape/carbon"));
({ createDiscordMessageHandler } = await import("./monitor/message-handler.js"));
({ __resetDiscordChannelInfoCacheForTest } = await import("./monitor/message-utils.js"));
({ createNoopThreadBindingManager } = await import("./monitor/thread-bindings.js"));
beforeEach(() => {
resetDiscordToolResultHarness();
});
beforeEach(async () => {
__resetDiscordChannelInfoCacheForTest();
sendMock.mockClear().mockResolvedValue(undefined);
updateLastRouteMock.mockClear();
dispatchMock.mockClear().mockImplementation(async ({ dispatcher }) => {
dispatcher.sendFinalReply({ text: "hi" });
return { queuedFinal: true, counts: { tool: 0, block: 0, final: 1 } };
});
readAllowFromStoreMock.mockClear().mockResolvedValue([]);
upsertPairingRequestMock.mockClear().mockResolvedValue({ code: "PAIRCODE", created: true });
loadConfigMock.mockClear().mockReturnValue(BASE_CFG);
});
const BASE_CFG: Config = {
agents: {
defaults: {
model: { primary: "anthropic/claude-opus-4-5" },
workspace: "/tmp/openclaw",
},
},
messages: {
inbound: { debounceMs: 0 },
},
session: { store: "/tmp/openclaw-sessions.json" },
};
const CATEGORY_GUILD_CFG = {
...BASE_CFG,
channels: {
discord: {
dm: { enabled: true, policy: "open" },
guilds: {
"*": {
requireMention: false,
channels: { c1: { allow: true } },
},
},
},
},
} satisfies Config;
function createHandlerBaseConfig(
cfg: Config,
runtimeError?: (err: unknown) => void,
): Parameters<typeof createDiscordMessageHandler>[0] {
return {
cfg,
discordConfig: cfg.channels?.discord,
accountId: "default",
token: "token",
runtime: {
log: vi.fn(),
error: runtimeError ?? vi.fn(),
exit: (code: number): never => {
throw new Error(`exit ${code}`);
},
},
botUserId: "bot-id",
guildHistories: new Map(),
historyLimit: 0,
mediaMaxBytes: 10_000,
textLimit: 2000,
replyToMode: "off",
dmEnabled: true,
groupDmEnabled: false,
threadBindings: createNoopThreadBindingManager("default"),
};
}
async function createDmHandler(opts: { cfg: Config; runtimeError?: (err: unknown) => void }) {
loadConfigMock.mockReturnValue(opts.cfg);
return createDiscordMessageHandler(createHandlerBaseConfig(opts.cfg, opts.runtimeError));
}
function createDmClient() {
return {
fetchChannel: vi.fn().mockResolvedValue({
type: ChannelType.DM,
name: "dm",
}),
} as unknown as Client;
}
async function createCategoryGuildHandler(runtimeError?: (err: unknown) => void) {
loadConfigMock.mockReturnValue(CATEGORY_GUILD_CFG);
return createDiscordMessageHandler({
...createHandlerBaseConfig(CATEGORY_GUILD_CFG, runtimeError),
guildEntries: {
"*": { requireMention: false, channels: { c1: { allow: true } } },
},
});
}
function createCategoryGuildClient() {
return {
fetchChannel: vi.fn().mockResolvedValue({
type: ChannelType.GuildText,
name: "general",
parentId: "category-1",
}),
rest: { get: vi.fn() },
} as unknown as Client;
}
function createCategoryGuildEvent(params: {
messageId: string;
timestamp?: string;
author: Record<string, unknown>;
}) {
return {
message: {
id: params.messageId,
content: "hello",
channelId: "c1",
timestamp: params.timestamp ?? new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
author: params.author,
},
author: params.author,
member: { displayName: "Ada" },
guild: { id: "g1", name: "Guild" },
guild_id: "g1",
};
}
describe("discord tool result dispatch", () => {
it("uses channel id allowlists for non-thread channels with categories", async () => {
let capturedCtx: { SessionKey?: string } | undefined;

View File

@@ -0,0 +1,326 @@
import type { Client } from "@buape/carbon";
import { ChannelType, MessageType } from "@buape/carbon";
import type { loadConfig } from "openclaw/plugin-sdk/config-runtime";
import { vi } from "vitest";
import {
dispatchMock,
loadConfigMock,
readAllowFromStoreMock,
sendMock,
updateLastRouteMock,
upsertPairingRequestMock,
} from "./monitor.tool-result.test-harness.js";
import { createDiscordMessageHandler } from "./monitor/message-handler.js";
import { __resetDiscordChannelInfoCacheForTest } from "./monitor/message-utils.js";
import { createNoopThreadBindingManager } from "./monitor/thread-bindings.js";
export type Config = ReturnType<typeof loadConfig>;
export const BASE_CFG: Config = {
agents: {
defaults: {
model: { primary: "anthropic/claude-opus-4-5" },
workspace: "/tmp/openclaw",
},
},
messages: {
inbound: { debounceMs: 0 },
},
session: { store: "/tmp/openclaw-sessions.json" },
};
export const CATEGORY_GUILD_CFG = {
...BASE_CFG,
channels: {
discord: {
dm: { enabled: true, policy: "open" },
guilds: {
"*": {
requireMention: false,
channels: { c1: { allow: true } },
},
},
},
},
} satisfies Config;
export function resetDiscordToolResultHarness() {
__resetDiscordChannelInfoCacheForTest();
sendMock.mockClear().mockResolvedValue(undefined);
updateLastRouteMock.mockClear();
dispatchMock.mockClear().mockImplementation(async ({ dispatcher }) => {
dispatcher.sendFinalReply({ text: "hi" });
return { queuedFinal: true, counts: { tool: 0, block: 0, final: 1 } };
});
readAllowFromStoreMock.mockClear().mockResolvedValue([]);
upsertPairingRequestMock.mockClear().mockResolvedValue({ code: "PAIRCODE", created: true });
loadConfigMock.mockClear().mockReturnValue(BASE_CFG);
}
export function createHandlerBaseConfig(
cfg: Config,
runtimeError?: (err: unknown) => void,
): Parameters<typeof createDiscordMessageHandler>[0] {
return {
cfg,
discordConfig: cfg.channels?.discord,
accountId: "default",
token: "token",
runtime: {
log: vi.fn(),
error: runtimeError ?? vi.fn(),
exit: (code: number): never => {
throw new Error(`exit ${code}`);
},
},
botUserId: "bot-id",
guildHistories: new Map(),
historyLimit: 0,
mediaMaxBytes: 10_000,
textLimit: 2000,
replyToMode: "off",
dmEnabled: true,
groupDmEnabled: false,
threadBindings: createNoopThreadBindingManager("default"),
};
}
export async function createDmHandler(params: {
cfg: Config;
runtimeError?: (err: unknown) => void;
}) {
loadConfigMock.mockReturnValue(params.cfg);
return createDiscordMessageHandler(createHandlerBaseConfig(params.cfg, params.runtimeError));
}
export async function createGuildHandler(params: {
cfg: Config;
guildEntries?: Parameters<typeof createDiscordMessageHandler>[0]["guildEntries"];
runtimeError?: (err: unknown) => void;
}) {
loadConfigMock.mockReturnValue(params.cfg);
return createDiscordMessageHandler({
...createHandlerBaseConfig(params.cfg, params.runtimeError),
guildEntries:
params.guildEntries ??
(params.cfg.channels?.discord?.guilds as Parameters<
typeof createDiscordMessageHandler
>[0]["guildEntries"]),
});
}
export function createDmClient() {
return {
fetchChannel: vi.fn().mockResolvedValue({
type: ChannelType.DM,
name: "dm",
}),
} as unknown as Client;
}
export async function createCategoryGuildHandler(runtimeError?: (err: unknown) => void) {
return createGuildHandler({
cfg: CATEGORY_GUILD_CFG,
guildEntries: {
"*": { requireMention: false, channels: { c1: { allow: true } } },
},
runtimeError,
});
}
export function createCategoryGuildClient() {
return {
fetchChannel: vi.fn().mockResolvedValue({
type: ChannelType.GuildText,
name: "general",
parentId: "category-1",
}),
rest: { get: vi.fn() },
} as unknown as Client;
}
export function createCategoryGuildEvent(params: {
messageId: string;
timestamp?: string;
author: Record<string, unknown>;
}) {
return {
message: {
id: params.messageId,
content: "hello",
channelId: "c1",
timestamp: params.timestamp ?? new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
author: params.author,
},
author: params.author,
member: { displayName: "Ada" },
guild: { id: "g1", name: "Guild" },
guild_id: "g1",
};
}
export function createGuildTextClient() {
return {
fetchChannel: vi.fn().mockResolvedValue({
id: "c1",
type: ChannelType.GuildText,
name: "general",
}),
rest: { get: vi.fn() },
} as unknown as Client;
}
export function createGuildMessageEvent(params: {
messageId: string;
content: string;
messagePatch?: Record<string, unknown>;
eventPatch?: Record<string, unknown>;
}) {
const messageBase = {
timestamp: new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
};
return {
message: {
id: params.messageId,
content: params.content,
channelId: "c1",
...messageBase,
author: { id: "u1", bot: false, username: "Ada" },
...params.messagePatch,
},
author: { id: "u1", bot: false, username: "Ada" },
member: { nickname: "Ada" },
guild: { id: "g1", name: "Guild" },
guild_id: "g1",
...params.eventPatch,
};
}
export function createThreadChannel(params: { includeStarter?: boolean; type?: ChannelType } = {}) {
return {
id: "t1",
type: params.type ?? ChannelType.PublicThread,
name: "thread-name",
parentId: params.type === ChannelType.PublicThread ? "forum-1" : "p1",
parent: {
id: params.type === ChannelType.PublicThread ? "forum-1" : "p1",
name: params.type === ChannelType.PublicThread ? "support" : "general",
},
isThread: () => true,
...(params.includeStarter
? {
fetchStarterMessage: async () => ({
content: "starter message",
author: { tag: "Alice#1", username: "Alice" },
createdTimestamp: Date.now(),
}),
}
: {}),
};
}
export function createThreadClient(
params: {
fetchChannel?: ReturnType<typeof vi.fn>;
restGet?: ReturnType<typeof vi.fn>;
} = {},
) {
return {
fetchChannel:
params.fetchChannel ??
vi
.fn()
.mockResolvedValueOnce({
id: "t1",
type: ChannelType.PublicThread,
name: "thread-name",
parentId: "p1",
ownerId: "owner-1",
})
.mockResolvedValueOnce({
id: "p1",
type: ChannelType.GuildText,
name: "general",
}),
rest: {
get:
params.restGet ??
vi.fn().mockResolvedValue({
content: "starter message",
author: { id: "u1", username: "Alice", discriminator: "0001" },
timestamp: new Date().toISOString(),
}),
},
} as unknown as Client;
}
export function createThreadEvent(messageId: string, channelId = "t1") {
return {
message: {
id: messageId,
content: "thread hello",
channelId,
timestamp: new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
author: { id: "u1", bot: false, username: "Ada" },
},
author: { id: "u1", bot: false, username: "Ada" },
member: { nickname: "Ada" },
guild: { id: "g1", name: "Guild" },
guild_id: "g1",
};
}
export function createMentionRequiredGuildConfig(overrides?: Partial<Config>): Config {
return {
...BASE_CFG,
channels: {
discord: {
dm: { enabled: true, policy: "open" },
groupPolicy: "open",
guilds: {
"*": {
requireMention: true,
channels: { c1: { allow: true } },
},
},
},
},
...overrides,
} as Config;
}
export function captureNextDispatchCtx<
T extends {
SessionKey?: string;
ParentSessionKey?: string;
ThreadStarterBody?: string;
ThreadLabel?: string;
WasMentioned?: boolean;
},
>(): () => T | undefined {
let capturedCtx: T | undefined;
dispatchMock.mockImplementationOnce(async ({ ctx, dispatcher }) => {
capturedCtx = ctx as T;
dispatcher.sendFinalReply({ text: "hi" });
return { queuedFinal: true, counts: { final: 1 } };
});
return () => capturedCtx;
}

View File

@@ -0,0 +1,37 @@
import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
import { buildDiscordInboundAccessContext } from "./inbound-context.js";
export function buildFinalizedDiscordDirectInboundContext() {
const { groupSystemPrompt, ownerAllowFrom, untrustedContext } = buildDiscordInboundAccessContext({
channelConfig: null,
guildInfo: null,
sender: { id: "U1", name: "Alice", tag: "alice" },
isGuild: false,
});
return finalizeInboundContext({
Body: "hi",
BodyForAgent: "hi",
RawBody: "hi",
CommandBody: "hi",
From: "discord:U1",
To: "user:U1",
SessionKey: "agent:main:discord:direct:u1",
AccountId: "default",
ChatType: "direct",
ConversationLabel: "Alice",
SenderName: "Alice",
SenderId: "U1",
SenderUsername: "alice",
GroupSystemPrompt: groupSystemPrompt,
OwnerAllowFrom: ownerAllowFrom,
UntrustedContext: untrustedContext,
Provider: "discord",
Surface: "discord",
WasMentioned: false,
MessageSid: "m1",
CommandAuthorized: true,
OriginatingChannel: "discord",
OriginatingTo: "user:U1",
});
}

View File

@@ -2,42 +2,11 @@ import { describe, expect, it } from "vitest";
import { finalizeInboundContext } from "../../../../src/auto-reply/reply/inbound-context.js";
import { expectChannelInboundContextContract as expectInboundContextContract } from "../../../../src/channels/plugins/contracts/suites.js";
import { buildDiscordInboundAccessContext } from "./inbound-context.js";
import { buildFinalizedDiscordDirectInboundContext } from "./inbound-context.test-helpers.js";
describe("discord processDiscordMessage inbound context", () => {
it("builds a finalized direct-message MsgContext shape", () => {
const { groupSystemPrompt, ownerAllowFrom, untrustedContext } =
buildDiscordInboundAccessContext({
channelConfig: null,
guildInfo: null,
sender: { id: "U1", name: "Alice", tag: "alice" },
isGuild: false,
});
const ctx = finalizeInboundContext({
Body: "hi",
BodyForAgent: "hi",
RawBody: "hi",
CommandBody: "hi",
From: "discord:U1",
To: "user:U1",
SessionKey: "agent:main:discord:direct:u1",
AccountId: "default",
ChatType: "direct",
ConversationLabel: "Alice",
SenderName: "Alice",
SenderId: "U1",
SenderUsername: "alice",
GroupSystemPrompt: groupSystemPrompt,
OwnerAllowFrom: ownerAllowFrom,
UntrustedContext: untrustedContext,
Provider: "discord",
Surface: "discord",
WasMentioned: false,
MessageSid: "m1",
CommandAuthorized: true,
OriginatingChannel: "discord",
OriginatingTo: "user:U1",
});
const ctx = buildFinalizedDiscordDirectInboundContext();
expectInboundContextContract(ctx);
});

View File

@@ -1,32 +1,12 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
createDiscordOutboundHoisted,
createDiscordSendModuleMock,
createDiscordThreadBindingsModuleMock,
installDiscordOutboundModuleSpies,
resetDiscordOutboundMocks,
} from "./outbound-adapter.test-harness.js";
const hoisted = createDiscordOutboundHoisted();
const sendModule = await import("./send.js");
const mockedSendModule = await createDiscordSendModuleMock(hoisted, async () => sendModule);
vi.spyOn(sendModule, "sendMessageDiscord").mockImplementation(mockedSendModule.sendMessageDiscord);
vi.spyOn(sendModule, "sendDiscordComponentMessage").mockImplementation(
mockedSendModule.sendDiscordComponentMessage,
);
vi.spyOn(sendModule, "sendPollDiscord").mockImplementation(mockedSendModule.sendPollDiscord);
vi.spyOn(sendModule, "sendWebhookMessageDiscord").mockImplementation(
mockedSendModule.sendWebhookMessageDiscord,
);
const threadBindingsModule = await import("./monitor/thread-bindings.js");
const mockedThreadBindingsModule = await createDiscordThreadBindingsModuleMock(
hoisted,
async () => threadBindingsModule,
);
vi.spyOn(threadBindingsModule, "getThreadBindingManager").mockImplementation(
mockedThreadBindingsModule.getThreadBindingManager,
);
await installDiscordOutboundModuleSpies(hoisted);
const { discordOutbound } = await import("./outbound-adapter.js");

View File

@@ -53,6 +53,30 @@ export async function createDiscordThreadBindingsModuleMock(
};
}
export async function installDiscordOutboundModuleSpies(hoisted: DiscordOutboundHoisted) {
const sendModule = await import("./send.js");
const mockedSendModule = await createDiscordSendModuleMock(hoisted, async () => sendModule);
vi.spyOn(sendModule, "sendMessageDiscord").mockImplementation(
mockedSendModule.sendMessageDiscord,
);
vi.spyOn(sendModule, "sendDiscordComponentMessage").mockImplementation(
mockedSendModule.sendDiscordComponentMessage,
);
vi.spyOn(sendModule, "sendPollDiscord").mockImplementation(mockedSendModule.sendPollDiscord);
vi.spyOn(sendModule, "sendWebhookMessageDiscord").mockImplementation(
mockedSendModule.sendWebhookMessageDiscord,
);
const threadBindingsModule = await import("./monitor/thread-bindings.js");
const mockedThreadBindingsModule = await createDiscordThreadBindingsModuleMock(
hoisted,
async () => threadBindingsModule,
);
vi.spyOn(threadBindingsModule, "getThreadBindingManager").mockImplementation(
mockedThreadBindingsModule.getThreadBindingManager,
);
}
export function resetDiscordOutboundMocks(hoisted: DiscordOutboundHoisted) {
hoisted.sendMessageDiscordMock.mockReset().mockResolvedValue({
messageId: "msg-1",

View File

@@ -1,34 +1,14 @@
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import {
createDiscordOutboundHoisted,
createDiscordSendModuleMock,
createDiscordThreadBindingsModuleMock,
expectDiscordThreadBotSend,
installDiscordOutboundModuleSpies,
mockDiscordBoundThreadManager,
resetDiscordOutboundMocks,
} from "./outbound-adapter.test-harness.js";
const hoisted = createDiscordOutboundHoisted();
const sendModule = await import("./send.js");
const mockedSendModule = await createDiscordSendModuleMock(hoisted, async () => sendModule);
vi.spyOn(sendModule, "sendMessageDiscord").mockImplementation(mockedSendModule.sendMessageDiscord);
vi.spyOn(sendModule, "sendDiscordComponentMessage").mockImplementation(
mockedSendModule.sendDiscordComponentMessage,
);
vi.spyOn(sendModule, "sendPollDiscord").mockImplementation(mockedSendModule.sendPollDiscord);
vi.spyOn(sendModule, "sendWebhookMessageDiscord").mockImplementation(
mockedSendModule.sendWebhookMessageDiscord,
);
const threadBindingsModule = await import("./monitor/thread-bindings.js");
const mockedThreadBindingsModule = await createDiscordThreadBindingsModuleMock(
hoisted,
async () => threadBindingsModule,
);
vi.spyOn(threadBindingsModule, "getThreadBindingManager").mockImplementation(
mockedThreadBindingsModule.getThreadBindingManager,
);
await installDiscordOutboundModuleSpies(hoisted);
let normalizeDiscordOutboundTarget: typeof import("./normalize.js").normalizeDiscordOutboundTarget;
let discordOutbound: typeof import("./outbound-adapter.js").discordOutbound;

View File

@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { buildDiscordInboundAccessContext } from "../../../../extensions/discord/src/monitor/inbound-context.js";
import { buildFinalizedDiscordDirectInboundContext } from "../../../../extensions/discord/src/monitor/inbound-context.test-helpers.js";
import type { ResolvedSlackAccount } from "../../../../extensions/slack/src/accounts.js";
import type { SlackMessageEvent } from "../../../../extensions/slack/src/types.js";
import { withTempHome } from "../../../../test/helpers/temp-home.js";
@@ -114,39 +114,7 @@ describe("channel inbound contract", () => {
});
it("keeps Discord inbound context finalized", () => {
const { groupSystemPrompt, ownerAllowFrom, untrustedContext } =
buildDiscordInboundAccessContext({
channelConfig: null,
guildInfo: null,
sender: { id: "U1", name: "Alice", tag: "alice" },
isGuild: false,
});
const ctx = finalizeInboundContext({
Body: "hi",
BodyForAgent: "hi",
RawBody: "hi",
CommandBody: "hi",
From: "discord:U1",
To: "user:U1",
SessionKey: "agent:main:discord:direct:u1",
AccountId: "default",
ChatType: "direct",
ConversationLabel: "Alice",
SenderName: "Alice",
SenderId: "U1",
SenderUsername: "alice",
GroupSystemPrompt: groupSystemPrompt,
OwnerAllowFrom: ownerAllowFrom,
UntrustedContext: untrustedContext,
Provider: "discord",
Surface: "discord",
WasMentioned: false,
MessageSid: "m1",
CommandAuthorized: true,
OriginatingChannel: "discord",
OriginatingTo: "user:U1",
});
const ctx = buildFinalizedDiscordDirectInboundContext();
expectChannelInboundContextContract(ctx);
});