426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
420 lines
12 KiB
TypeScript
420 lines
12 KiB
TypeScript
/**
|
|
* Unit tests for the Discord message-connector adapter — outbound send routing
|
|
* through the account client pool, against a partially-constructed
|
|
* `DiscordService` and mocked discord.js client.
|
|
*/
|
|
import type { IAgentRuntime, MessageConnectorTarget } from "@elizaos/core";
|
|
import type { Message } from "discord.js";
|
|
import { describe, expect, it, vi } from "vitest";
|
|
import { DiscordAccountClientPool } from "../account-client-pool";
|
|
import { DEFAULT_ACCOUNT_ID } from "../accounts";
|
|
import {
|
|
buildMemoryFromMessage,
|
|
type HistoryServiceInternals,
|
|
} from "../discord-history";
|
|
import { DiscordService } from "../service";
|
|
|
|
function createDiscordConnectorTestService<
|
|
TProperties extends Record<string, unknown>,
|
|
>(properties: TProperties): DiscordService & TProperties {
|
|
return Object.assign(
|
|
Object.create(DiscordService.prototype),
|
|
properties,
|
|
) as DiscordService & TProperties;
|
|
}
|
|
|
|
function createRuntime() {
|
|
return {
|
|
agentId: "agent-1",
|
|
registerMessageConnector: vi.fn(),
|
|
registerSendHandler: vi.fn(),
|
|
logger: {
|
|
info: vi.fn(),
|
|
debug: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
},
|
|
ensureConnection: vi.fn().mockResolvedValue(undefined),
|
|
createMemory: vi.fn().mockImplementation(async (memory) => memory.id),
|
|
getMemoryById: vi.fn().mockResolvedValue(null),
|
|
getRoom: vi.fn(),
|
|
getEntityById: vi.fn(),
|
|
getRelationships: vi.fn().mockResolvedValue([]),
|
|
} as IAgentRuntime & {
|
|
registerMessageConnector: ReturnType<typeof vi.fn>;
|
|
registerSendHandler: ReturnType<typeof vi.fn>;
|
|
};
|
|
}
|
|
|
|
describe("Discord message connector adapter", () => {
|
|
it("registers connector metadata and dispatches through the existing send handler", async () => {
|
|
const runtime = createRuntime();
|
|
const service = Object.create(
|
|
DiscordService.prototype,
|
|
) as DiscordService & {
|
|
handleSendMessage: ReturnType<typeof vi.fn>;
|
|
resolveConnectorTargets: ReturnType<typeof vi.fn>;
|
|
listRecentConnectorTargets: ReturnType<typeof vi.fn>;
|
|
listConnectorRooms: ReturnType<typeof vi.fn>;
|
|
getConnectorChatContext: ReturnType<typeof vi.fn>;
|
|
getConnectorUserContext: ReturnType<typeof vi.fn>;
|
|
};
|
|
service.handleSendMessage = vi.fn().mockResolvedValue(undefined);
|
|
service.resolveConnectorTargets = vi.fn();
|
|
service.listRecentConnectorTargets = vi.fn();
|
|
service.listConnectorRooms = vi.fn();
|
|
service.getConnectorChatContext = vi.fn();
|
|
service.getConnectorUserContext = vi.fn();
|
|
Object.assign(service, {
|
|
accountPool: new DiscordAccountClientPool(),
|
|
defaultAccountId: DEFAULT_ACCOUNT_ID,
|
|
});
|
|
|
|
DiscordService.registerSendHandlers(runtime, service);
|
|
|
|
expect(runtime.registerMessageConnector).toHaveBeenCalledOnce();
|
|
const registration = runtime.registerMessageConnector.mock.calls[0][0];
|
|
expect(registration).toMatchObject({
|
|
source: "discord",
|
|
label: "Discord",
|
|
capabilities: expect.arrayContaining([
|
|
"send_message",
|
|
"resolve_targets",
|
|
"chat_context",
|
|
"user_context",
|
|
]),
|
|
supportedTargetKinds: ["channel", "thread", "user"],
|
|
contexts: ["social", "connectors"],
|
|
});
|
|
|
|
await registration.sendHandler(
|
|
runtime,
|
|
{ source: "discord", channelId: "123456789012345678" },
|
|
{ text: "hello" },
|
|
);
|
|
expect(service.handleSendMessage).toHaveBeenCalledWith(
|
|
runtime,
|
|
{ source: "discord", channelId: "123456789012345678" },
|
|
{ text: "hello" },
|
|
);
|
|
});
|
|
|
|
it("resolves cached channels and users into unified message targets", async () => {
|
|
const runtime = createRuntime();
|
|
const guild: Record<string, unknown> = {
|
|
id: "111111111111111111",
|
|
name: "Eliza",
|
|
};
|
|
const channel = {
|
|
id: "222222222222222222",
|
|
name: "general",
|
|
guild,
|
|
isTextBased: () => true,
|
|
isVoiceBased: () => false,
|
|
isThread: () => false,
|
|
};
|
|
const member = {
|
|
id: "333333333333333333",
|
|
displayName: "Ada",
|
|
user: {
|
|
id: "333333333333333333",
|
|
username: "ada",
|
|
globalName: "Ada Lovelace",
|
|
tag: "ada#0001",
|
|
bot: false,
|
|
},
|
|
};
|
|
guild.channels = { cache: new Map([[channel.id, channel]]) };
|
|
guild.members = {
|
|
cache: new Map([[member.id, member]]),
|
|
fetch: vi.fn().mockResolvedValue(new Map([[member.id, member]])),
|
|
};
|
|
|
|
const service = createDiscordConnectorTestService({
|
|
runtime,
|
|
allowedChannelIds: undefined,
|
|
dynamicChannelIds: new Set<string>(),
|
|
accountPool: new DiscordAccountClientPool(),
|
|
defaultAccountId: DEFAULT_ACCOUNT_ID,
|
|
client: {
|
|
guilds: { cache: new Map([[guild.id, guild]]) },
|
|
channels: { fetch: vi.fn().mockResolvedValue(channel) },
|
|
users: { fetch: vi.fn().mockResolvedValue(member.user) },
|
|
},
|
|
});
|
|
|
|
const channelTargets = await service.resolveConnectorTargets("general", {
|
|
runtime,
|
|
});
|
|
expect(channelTargets[0]).toMatchObject({
|
|
kind: "channel",
|
|
label: "#general",
|
|
target: {
|
|
source: "discord",
|
|
channelId: "222222222222222222",
|
|
serverId: "111111111111111111",
|
|
},
|
|
});
|
|
|
|
const userTargets: MessageConnectorTarget[] =
|
|
await service.resolveConnectorTargets("ada", {
|
|
runtime,
|
|
});
|
|
expect(userTargets.some((target) => target.kind === "user")).toBe(true);
|
|
expect(
|
|
userTargets.find((target) => target.kind === "user")?.target.entityId,
|
|
).toBe("333333333333333333");
|
|
});
|
|
|
|
it("registers account-scoped connectors and routes sends with accountId", async () => {
|
|
const runtime = createRuntime();
|
|
const service = createDiscordConnectorTestService({
|
|
getAccountIds: vi.fn(() => ["default", "team"]),
|
|
getDefaultAccountId: vi.fn(() => "default"),
|
|
getAccountLabel: vi.fn((accountId: string) =>
|
|
accountId === "team" ? "Team Bot" : "Default Bot",
|
|
),
|
|
handleSendMessage: vi.fn().mockResolvedValue(undefined),
|
|
resolveConnectorTargets: vi.fn().mockResolvedValue([]),
|
|
listRecentConnectorTargets: vi.fn().mockResolvedValue([]),
|
|
listConnectorRooms: vi.fn().mockResolvedValue([]),
|
|
listConnectorServers: vi.fn().mockResolvedValue([]),
|
|
fetchConnectorMessages: vi.fn().mockResolvedValue([]),
|
|
searchConnectorMessages: vi.fn().mockResolvedValue([]),
|
|
reactConnectorMessage: vi.fn().mockResolvedValue(undefined),
|
|
editConnectorMessage: vi.fn(),
|
|
deleteConnectorMessage: vi.fn().mockResolvedValue(undefined),
|
|
pinConnectorMessage: vi.fn().mockResolvedValue(undefined),
|
|
joinConnectorChannel: vi.fn(),
|
|
leaveConnectorChannel: vi.fn().mockResolvedValue(undefined),
|
|
getConnectorUser: vi.fn(),
|
|
getConnectorChatContext: vi.fn(),
|
|
getConnectorUserContext: vi.fn(),
|
|
});
|
|
|
|
DiscordService.registerSendHandlers(runtime, service);
|
|
|
|
expect(runtime.registerMessageConnector).toHaveBeenCalledTimes(3);
|
|
const registrations = runtime.registerMessageConnector.mock.calls.map(
|
|
(call) => call[0],
|
|
);
|
|
expect(registrations.map((registration) => registration.accountId)).toEqual(
|
|
[undefined, "default", "team"],
|
|
);
|
|
|
|
const teamRegistration = registrations.find(
|
|
(registration) => registration.accountId === "team",
|
|
);
|
|
await teamRegistration.sendHandler(
|
|
runtime,
|
|
{ source: "discord", channelId: "222222222222222222" },
|
|
{ text: "team hello" },
|
|
);
|
|
expect(service.handleSendMessage).toHaveBeenCalledWith(
|
|
runtime,
|
|
{
|
|
source: "discord",
|
|
channelId: "222222222222222222",
|
|
accountId: "team",
|
|
},
|
|
{ text: "team hello" },
|
|
);
|
|
});
|
|
|
|
it("stamps inbound Discord memories with the accountId", async () => {
|
|
const runtime = {
|
|
agentId: "00000000-0000-0000-0000-000000000001",
|
|
logger: {
|
|
debug: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
},
|
|
} as HistoryServiceInternals["runtime"];
|
|
const channel = {
|
|
id: "222222222222222222",
|
|
type: 0,
|
|
guild: { id: "111111111111111111" },
|
|
};
|
|
const message = {
|
|
id: "333333333333333333",
|
|
content: "hello from team",
|
|
createdTimestamp: 1_700_000_000_000,
|
|
url: "https://discord.com/channels/111/222/333",
|
|
author: {
|
|
id: "444444444444444444",
|
|
username: "ada",
|
|
bot: false,
|
|
displayAvatarURL: () => "https://cdn.example/avatar.png",
|
|
},
|
|
channel,
|
|
guild: { id: "111111111111111111" },
|
|
reference: null,
|
|
};
|
|
const memory = await buildMemoryFromMessage(
|
|
{
|
|
accountId: "team",
|
|
runtime,
|
|
messageManager: undefined,
|
|
client: {} as HistoryServiceInternals["client"],
|
|
resolveDiscordEntityId: (userId: string) =>
|
|
`00000000-0000-0000-0000-${userId.slice(-12)}`,
|
|
getChannelType: vi.fn().mockResolvedValue("GROUP"),
|
|
isGuildTextBasedChannel: vi.fn(),
|
|
},
|
|
message as Message,
|
|
{ processedContent: "hello from team" },
|
|
);
|
|
|
|
expect(memory?.metadata).toMatchObject({
|
|
accountId: "team",
|
|
discord: {
|
|
accountId: "team",
|
|
channelId: "222222222222222222",
|
|
messageId: "333333333333333333",
|
|
},
|
|
});
|
|
});
|
|
|
|
it("uses an external message id as a Discord reply reference when sending through connector targets", async () => {
|
|
const runtime = Object.assign(createRuntime(), {
|
|
getRoom: vi.fn().mockResolvedValue({
|
|
channelId: "222222222222222222",
|
|
}),
|
|
ensureConnection: vi.fn().mockResolvedValue(undefined),
|
|
createMemory: vi.fn().mockResolvedValue(undefined),
|
|
});
|
|
const send = vi.fn(async (options: unknown) => ({
|
|
id: "444444444444444444",
|
|
content:
|
|
typeof options === "object" && options
|
|
? String((options as { content?: string }).content ?? "")
|
|
: String(options ?? ""),
|
|
attachments: { size: 0 },
|
|
url: "https://discord.com/channels/111/222/444",
|
|
createdTimestamp: 123,
|
|
}));
|
|
const channel = {
|
|
id: "222222222222222222",
|
|
name: "general",
|
|
guild: { id: "111111111111111111", name: "Eliza" },
|
|
isTextBased: () => true,
|
|
isVoiceBased: () => false,
|
|
send,
|
|
};
|
|
const client = {
|
|
isReady: () => true,
|
|
channels: { fetch: vi.fn().mockResolvedValue(channel) },
|
|
user: {
|
|
id: "999999999999999999",
|
|
username: "bot",
|
|
displayName: "Bot",
|
|
},
|
|
};
|
|
const accountPool = new DiscordAccountClientPool();
|
|
accountPool.set({
|
|
accountId: DEFAULT_ACCOUNT_ID,
|
|
account: { id: DEFAULT_ACCOUNT_ID, token: "token", enabled: true },
|
|
client,
|
|
settings: {},
|
|
dynamicChannelIds: new Set<string>(),
|
|
clientReadyPromise: null,
|
|
loginFailed: false,
|
|
} as never);
|
|
const service = createDiscordConnectorTestService({
|
|
runtime,
|
|
accountPool,
|
|
defaultAccountId: DEFAULT_ACCOUNT_ID,
|
|
getChannelType: vi.fn().mockResolvedValue("GROUP"),
|
|
});
|
|
|
|
await service.handleSendMessage(
|
|
runtime,
|
|
{
|
|
source: "discord",
|
|
roomId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
|
},
|
|
{
|
|
text: "done",
|
|
inReplyTo: "1506947499212935208",
|
|
},
|
|
);
|
|
|
|
expect(send).toHaveBeenCalledWith({
|
|
content: "done",
|
|
reply: { messageReference: "1506947499212935208" },
|
|
files: undefined,
|
|
});
|
|
});
|
|
|
|
it("suppresses identical connector sends that race the inbound callback", async () => {
|
|
const runtime = Object.assign(createRuntime(), {
|
|
getRoom: vi.fn().mockResolvedValue({
|
|
channelId: "222222222222222223",
|
|
}),
|
|
});
|
|
const send = vi.fn(async (options: unknown) => ({
|
|
id: `44444444444444444${send.mock.calls.length}`,
|
|
content:
|
|
typeof options === "object" && options
|
|
? String((options as { content?: string }).content ?? "")
|
|
: String(options ?? ""),
|
|
attachments: { size: 0 },
|
|
url: "https://discord.com/channels/111/223/444",
|
|
createdTimestamp: 123,
|
|
}));
|
|
const channel = {
|
|
id: "222222222222222223",
|
|
name: "general",
|
|
guild: { id: "111111111111111111", name: "Eliza" },
|
|
isTextBased: () => true,
|
|
isVoiceBased: () => false,
|
|
send,
|
|
};
|
|
const client = {
|
|
isReady: () => true,
|
|
channels: { fetch: vi.fn().mockResolvedValue(channel) },
|
|
user: {
|
|
id: "999999999999999999",
|
|
username: "bot",
|
|
displayName: "Bot",
|
|
},
|
|
};
|
|
const accountPool = new DiscordAccountClientPool();
|
|
accountPool.set({
|
|
accountId: DEFAULT_ACCOUNT_ID,
|
|
account: { id: DEFAULT_ACCOUNT_ID, token: "token", enabled: true },
|
|
client,
|
|
settings: {},
|
|
dynamicChannelIds: new Set<string>(),
|
|
clientReadyPromise: null,
|
|
loginFailed: false,
|
|
} as never);
|
|
const service = createDiscordConnectorTestService({
|
|
runtime,
|
|
accountPool,
|
|
defaultAccountId: DEFAULT_ACCOUNT_ID,
|
|
getChannelType: vi.fn().mockResolvedValue("GROUP"),
|
|
});
|
|
const target = {
|
|
source: "discord",
|
|
roomId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
|
};
|
|
const content = {
|
|
text: "Bitcoin is currently at $61,984 USD.",
|
|
inReplyTo: "1506947499212935209",
|
|
};
|
|
|
|
await service.handleSendMessage(runtime, target, content);
|
|
await service.handleSendMessage(runtime, target, content);
|
|
|
|
expect(send).toHaveBeenCalledOnce();
|
|
expect(runtime.logger.debug).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
src: "plugin:discord",
|
|
channelId: "222222222222222223",
|
|
}),
|
|
"Suppressing duplicate Discord connector delivery",
|
|
);
|
|
});
|
|
});
|