openclaw/native-plugins/discord/src/monitor.tool-result.sends-status-replies-responseprefix.test.ts

228 lines
6.6 KiB
TypeScript
Raw Permalink Normal View History

import type { Client } from "@buape/carbon";
import { ChannelType, MessageType } from "@buape/carbon";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
dispatchMock,
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";
feat: thread-bound subagents on Discord (#21805) * docs: thread-bound subagents plan * docs: add exact thread-bound subagent implementation touchpoints * Docs: prioritize auto thread-bound subagent flow * Docs: add ACP harness thread-binding extensions * Discord: add thread-bound session routing and auto-bind spawn flow * Subagents: add focus commands and ACP/session binding lifecycle hooks * Tests: cover thread bindings, focus commands, and ACP unbind hooks * Docs: add plugin-hook appendix for thread-bound subagents * Plugins: add subagent lifecycle hook events * Core: emit subagent lifecycle hooks and decouple Discord bindings * Discord: handle subagent bind lifecycle via plugin hooks * Subagents: unify completion finalizer and split registry modules * Add subagent lifecycle events module * Hooks: fix subagent ended context key * Discord: share thread bindings across ESM and Jiti * Subagents: add persistent sessions_spawn mode for thread-bound sessions * Subagents: clarify thread intro and persistent completion copy * test(subagents): stabilize sessions_spawn lifecycle cleanup assertions * Discord: add thread-bound session TTL with auto-unfocus * Subagents: fail session spawns when thread bind fails * Subagents: cover thread session failure cleanup paths * Session: add thread binding TTL config and /session ttl controls * Tests: align discord reaction expectations * Agent: persist sessionFile for keyed subagent sessions * Discord: normalize imports after conflict resolution * Sessions: centralize sessionFile resolve/persist helper * Discord: harden thread-bound subagent session routing * Rebase: resolve upstream/main conflicts * Subagents: move thread binding into hooks and split bindings modules * Docs: add channel-agnostic subagent routing hook plan * Agents: decouple subagent routing from Discord * Discord: refactor thread-bound subagent flows * Subagents: prevent duplicate end hooks and orphaned failed sessions * Refactor: split subagent command and provider phases * Subagents: honor hook delivery target overrides * Discord: add thread binding kill switches and refresh plan doc * Discord: fix thread bind channel resolution * Routing: centralize account id normalization * Discord: clean up thread bindings on startup failures * Discord: add startup cleanup regression tests * Docs: add long-term thread-bound subagent architecture * Docs: split session binding plan and dedupe thread-bound doc * Subagents: add channel-agnostic session binding routing * Subagents: stabilize announce completion routing tests * Subagents: cover multi-bound completion routing * Subagents: suppress lifecycle hooks on failed thread bind * tests: fix discord provider mock typing regressions * docs/protocol: sync slash command aliases and delete param models * fix: add changelog entry for Discord thread-bound subagents (#21805) (thanks @onutc) --------- Co-authored-by: Shadow <hi@shadowing.dev>
2026-02-21 16:14:55 +01:00
import { createNoopThreadBindingManager } from "./monitor/thread-bindings.js";
type Config = ReturnType<typeof import("../../../src/config/config.js").loadConfig>;
beforeEach(() => {
__resetDiscordChannelInfoCacheForTest();
sendMock.mockClear().mockResolvedValue(undefined);
updateLastRouteMock.mockClear();
dispatchMock.mockClear().mockImplementation(async ({ dispatcher }) => {
dispatcher.sendFinalReply({ text: "hi" });
2026-01-23 22:51:37 +00:00
return { queuedFinal: true, counts: { tool: 0, block: 0, final: 1 } };
});
readAllowFromStoreMock.mockClear().mockResolvedValue([]);
upsertPairingRequestMock.mockClear().mockResolvedValue({ code: "PAIRCODE", created: true });
});
2026-02-17 12:22:34 +09:00
const BASE_CFG: Config = {
agents: {
defaults: {
2026-02-17 12:22:34 +09:00
model: { primary: "anthropic/claude-opus-4-5" },
workspace: "/tmp/openclaw",
},
},
session: { store: "/tmp/openclaw-sessions.json" },
2026-02-17 12:22:34 +09:00
};
const CATEGORY_GUILD_CFG = {
...BASE_CFG,
channels: {
discord: {
dm: { enabled: true, policy: "open" },
guilds: {
"*": {
requireMention: false,
channels: { c1: { allow: true } },
},
},
},
},
2026-02-17 12:22:34 +09:00
} 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,
feat: thread-bound subagents on Discord (#21805) * docs: thread-bound subagents plan * docs: add exact thread-bound subagent implementation touchpoints * Docs: prioritize auto thread-bound subagent flow * Docs: add ACP harness thread-binding extensions * Discord: add thread-bound session routing and auto-bind spawn flow * Subagents: add focus commands and ACP/session binding lifecycle hooks * Tests: cover thread bindings, focus commands, and ACP unbind hooks * Docs: add plugin-hook appendix for thread-bound subagents * Plugins: add subagent lifecycle hook events * Core: emit subagent lifecycle hooks and decouple Discord bindings * Discord: handle subagent bind lifecycle via plugin hooks * Subagents: unify completion finalizer and split registry modules * Add subagent lifecycle events module * Hooks: fix subagent ended context key * Discord: share thread bindings across ESM and Jiti * Subagents: add persistent sessions_spawn mode for thread-bound sessions * Subagents: clarify thread intro and persistent completion copy * test(subagents): stabilize sessions_spawn lifecycle cleanup assertions * Discord: add thread-bound session TTL with auto-unfocus * Subagents: fail session spawns when thread bind fails * Subagents: cover thread session failure cleanup paths * Session: add thread binding TTL config and /session ttl controls * Tests: align discord reaction expectations * Agent: persist sessionFile for keyed subagent sessions * Discord: normalize imports after conflict resolution * Sessions: centralize sessionFile resolve/persist helper * Discord: harden thread-bound subagent session routing * Rebase: resolve upstream/main conflicts * Subagents: move thread binding into hooks and split bindings modules * Docs: add channel-agnostic subagent routing hook plan * Agents: decouple subagent routing from Discord * Discord: refactor thread-bound subagent flows * Subagents: prevent duplicate end hooks and orphaned failed sessions * Refactor: split subagent command and provider phases * Subagents: honor hook delivery target overrides * Discord: add thread binding kill switches and refresh plan doc * Discord: fix thread bind channel resolution * Routing: centralize account id normalization * Discord: clean up thread bindings on startup failures * Discord: add startup cleanup regression tests * Docs: add long-term thread-bound subagent architecture * Docs: split session binding plan and dedupe thread-bound doc * Subagents: add channel-agnostic session binding routing * Subagents: stabilize announce completion routing tests * Subagents: cover multi-bound completion routing * Subagents: suppress lifecycle hooks on failed thread bind * tests: fix discord provider mock typing regressions * docs/protocol: sync slash command aliases and delete param models * fix: add changelog entry for Discord thread-bound subagents (#21805) (thanks @onutc) --------- Co-authored-by: Shadow <hi@shadowing.dev>
2026-02-21 16:14:55 +01:00
threadBindings: createNoopThreadBindingManager("default"),
};
}
async function createDmHandler(opts: { cfg: Config; runtimeError?: (err: unknown) => void }) {
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() {
return createDiscordMessageHandler({
...createHandlerBaseConfig(CATEGORY_GUILD_CFG),
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;
dispatchMock.mockImplementationOnce(async ({ ctx, dispatcher }) => {
capturedCtx = ctx;
dispatcher.sendFinalReply({ text: "hi" });
return { queuedFinal: true, counts: { final: 1 } };
});
const handler = await createCategoryGuildHandler();
const client = createCategoryGuildClient();
await handler(
createCategoryGuildEvent({
messageId: "m-category",
author: { id: "u1", bot: false, username: "Ada", tag: "Ada#1" },
}),
client,
);
await vi.waitFor(() => expect(dispatchMock).toHaveBeenCalledTimes(1));
expect(capturedCtx?.SessionKey).toBe("agent:main:discord:channel:c1");
});
2026-01-17 05:21:02 +00:00
it("prefixes group bodies with sender label", async () => {
let capturedBody = "";
dispatchMock.mockImplementationOnce(async ({ ctx, dispatcher }) => {
capturedBody = ctx.Body ?? "";
dispatcher.sendFinalReply({ text: "ok" });
return { queuedFinal: true, counts: { final: 1 } };
});
const handler = await createCategoryGuildHandler();
const client = createCategoryGuildClient();
2026-01-17 05:21:02 +00:00
await handler(
createCategoryGuildEvent({
messageId: "m-prefix",
timestamp: new Date("2026-01-17T00:00:00Z").toISOString(),
2026-01-17 05:21:02 +00:00
author: { id: "u1", bot: false, username: "Ada", discriminator: "1234" },
}),
2026-01-17 05:21:02 +00:00
client,
);
await vi.waitFor(() => expect(dispatchMock).toHaveBeenCalledTimes(1));
2026-01-17 05:21:02 +00:00
expect(capturedBody).toContain("Ada (Ada#1234): hello");
});
it("replies with pairing code and sender id when dmPolicy is pairing", async () => {
const cfg = {
...BASE_CFG,
channels: {
discord: { dm: { enabled: true, policy: "pairing", allowFrom: [] } },
},
} as Config;
const handler = await createDmHandler({ cfg });
const client = createDmClient();
await handler(
{
message: {
id: "m1",
content: "hello",
channelId: "c1",
timestamp: new Date().toISOString(),
type: MessageType.Default,
attachments: [],
embeds: [],
mentionedEveryone: false,
mentionedUsers: [],
mentionedRoles: [],
author: { id: "u2", bot: false, username: "Ada" },
},
author: { id: "u2", bot: false, username: "Ada" },
guild_id: null,
},
client,
);
expect(dispatchMock).not.toHaveBeenCalled();
expect(upsertPairingRequestMock).toHaveBeenCalled();
expect(sendMock).toHaveBeenCalledTimes(1);
expect(String(sendMock.mock.calls[0]?.[1] ?? "")).toContain("Your Discord user id: u2");
expect(String(sendMock.mock.calls[0]?.[1] ?? "")).toContain("Pairing code: PAIRCODE");
}, 10000);
});