test(agents): dedupe agent and cron test scaffolds

This commit is contained in:
Peter Steinberger
2026-03-02 06:40:42 +00:00
parent 281494ae52
commit 7e29d604ba
38 changed files with 3114 additions and 4486 deletions

View File

@@ -40,6 +40,58 @@ function getActionEnum(properties: Record<string, unknown>) {
return (properties.action as { enum?: string[] } | undefined)?.enum ?? [];
}
function createChannelPlugin(params: {
id: string;
label: string;
docsPath: string;
blurb: string;
actions: string[];
supportsButtons?: boolean;
messaging?: ChannelPlugin["messaging"];
}): ChannelPlugin {
return {
id: params.id as ChannelPlugin["id"],
meta: {
id: params.id as ChannelPlugin["id"],
label: params.label,
selectionLabel: params.label,
docsPath: params.docsPath,
blurb: params.blurb,
},
capabilities: { chatTypes: ["direct", "group"], media: true },
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
...(params.messaging ? { messaging: params.messaging } : {}),
actions: {
listActions: () => params.actions as never,
...(params.supportsButtons ? { supportsButtons: () => true } : {}),
},
};
}
async function executeSend(params: {
action: Record<string, unknown>;
toolOptions?: Partial<Parameters<typeof createMessageTool>[0]>;
}) {
const tool = createMessageTool({
config: {} as never,
...params.toolOptions,
});
await tool.execute("1", {
action: "send",
...params.action,
});
return mocks.runMessageAction.mock.calls[0]?.[0] as
| {
params?: Record<string, unknown>;
sandboxRoot?: string;
requesterSenderId?: string;
}
| undefined;
}
describe("message tool agent routing", () => {
it("derives agentId from the session key", async () => {
mockSendResult();
@@ -62,141 +114,103 @@ describe("message tool agent routing", () => {
});
describe("message tool path passthrough", () => {
it("does not convert path to media for send", async () => {
it.each([
{ field: "path", value: "~/Downloads/voice.ogg" },
{ field: "filePath", value: "./tmp/note.m4a" },
])("does not convert $field to media for send", async ({ field, value }) => {
mockSendResult({ to: "telegram:123" });
const tool = createMessageTool({
config: {} as never,
const call = await executeSend({
action: {
target: "telegram:123",
[field]: value,
message: "",
},
});
await tool.execute("1", {
action: "send",
target: "telegram:123",
path: "~/Downloads/voice.ogg",
message: "",
});
const call = mocks.runMessageAction.mock.calls[0]?.[0];
expect(call?.params?.path).toBe("~/Downloads/voice.ogg");
expect(call?.params?.media).toBeUndefined();
});
it("does not convert filePath to media for send", async () => {
mockSendResult({ to: "telegram:123" });
const tool = createMessageTool({
config: {} as never,
});
await tool.execute("1", {
action: "send",
target: "telegram:123",
filePath: "./tmp/note.m4a",
message: "",
});
const call = mocks.runMessageAction.mock.calls[0]?.[0];
expect(call?.params?.filePath).toBe("./tmp/note.m4a");
expect(call?.params?.[field]).toBe(value);
expect(call?.params?.media).toBeUndefined();
});
});
describe("message tool schema scoping", () => {
const telegramPlugin: ChannelPlugin = {
const telegramPlugin = createChannelPlugin({
id: "telegram",
meta: {
id: "telegram",
label: "Telegram",
selectionLabel: "Telegram",
docsPath: "/channels/telegram",
blurb: "Telegram test plugin.",
},
capabilities: { chatTypes: ["direct", "group"], media: true },
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
actions: {
listActions: () => ["send", "react"] as const,
supportsButtons: () => true,
},
};
label: "Telegram",
docsPath: "/channels/telegram",
blurb: "Telegram test plugin.",
actions: ["send", "react"],
supportsButtons: true,
});
const discordPlugin: ChannelPlugin = {
const discordPlugin = createChannelPlugin({
id: "discord",
meta: {
id: "discord",
label: "Discord",
selectionLabel: "Discord",
docsPath: "/channels/discord",
blurb: "Discord test plugin.",
},
capabilities: { chatTypes: ["direct", "group"], media: true },
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
actions: {
listActions: () => ["send", "poll"] as const,
},
};
label: "Discord",
docsPath: "/channels/discord",
blurb: "Discord test plugin.",
actions: ["send", "poll"],
});
afterEach(() => {
setActivePluginRegistry(createTestRegistry([]));
});
it("hides discord components when scoped to telegram", () => {
setActivePluginRegistry(
createTestRegistry([
{ pluginId: "telegram", source: "test", plugin: telegramPlugin },
{ pluginId: "discord", source: "test", plugin: discordPlugin },
]),
);
it.each([
{
provider: "telegram",
expectComponents: false,
expectButtons: true,
expectButtonStyle: true,
expectedActions: ["send", "react", "poll"],
},
{
provider: "discord",
expectComponents: true,
expectButtons: false,
expectButtonStyle: false,
expectedActions: ["send", "poll", "react"],
},
])(
"scopes schema fields for $provider",
({ provider, expectComponents, expectButtons, expectButtonStyle, expectedActions }) => {
setActivePluginRegistry(
createTestRegistry([
{ pluginId: "telegram", source: "test", plugin: telegramPlugin },
{ pluginId: "discord", source: "test", plugin: discordPlugin },
]),
);
const tool = createMessageTool({
config: {} as never,
currentChannelProvider: "telegram",
});
const properties = getToolProperties(tool);
const actionEnum = getActionEnum(properties);
const tool = createMessageTool({
config: {} as never,
currentChannelProvider: provider,
});
const properties = getToolProperties(tool);
const actionEnum = getActionEnum(properties);
expect(properties.components).toBeUndefined();
expect(properties.buttons).toBeDefined();
const buttonItemProps =
(
properties.buttons as {
items?: { items?: { properties?: Record<string, unknown> } };
}
)?.items?.items?.properties ?? {};
expect(buttonItemProps.style).toBeDefined();
expect(actionEnum).toContain("send");
expect(actionEnum).toContain("react");
// Other channels' actions are included so isolated/cron agents can use them
expect(actionEnum).toContain("poll");
});
it("shows discord components when scoped to discord", () => {
setActivePluginRegistry(
createTestRegistry([
{ pluginId: "telegram", source: "test", plugin: telegramPlugin },
{ pluginId: "discord", source: "test", plugin: discordPlugin },
]),
);
const tool = createMessageTool({
config: {} as never,
currentChannelProvider: "discord",
});
const properties = getToolProperties(tool);
const actionEnum = getActionEnum(properties);
expect(properties.components).toBeDefined();
expect(properties.buttons).toBeUndefined();
expect(actionEnum).toContain("send");
expect(actionEnum).toContain("poll");
// Other channels' actions are included so isolated/cron agents can use them
expect(actionEnum).toContain("react");
});
if (expectComponents) {
expect(properties.components).toBeDefined();
} else {
expect(properties.components).toBeUndefined();
}
if (expectButtons) {
expect(properties.buttons).toBeDefined();
} else {
expect(properties.buttons).toBeUndefined();
}
if (expectButtonStyle) {
const buttonItemProps =
(
properties.buttons as {
items?: { items?: { properties?: Record<string, unknown> } };
}
)?.items?.items?.properties ?? {};
expect(buttonItemProps.style).toBeDefined();
}
for (const action of expectedActions) {
expect(actionEnum).toContain(action);
}
},
);
});
describe("message tool description", () => {
@@ -204,20 +218,12 @@ describe("message tool description", () => {
setActivePluginRegistry(createTestRegistry([]));
});
const bluebubblesPlugin: ChannelPlugin = {
const bluebubblesPlugin = createChannelPlugin({
id: "bluebubbles",
meta: {
id: "bluebubbles",
label: "BlueBubbles",
selectionLabel: "BlueBubbles",
docsPath: "/channels/bluebubbles",
blurb: "BlueBubbles test plugin.",
},
capabilities: { chatTypes: ["direct", "group"], media: true },
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
label: "BlueBubbles",
docsPath: "/channels/bluebubbles",
blurb: "BlueBubbles test plugin.",
actions: ["react", "renameGroup", "addParticipant", "removeParticipant", "leaveGroup"],
messaging: {
normalizeTarget: (raw) => {
const trimmed = raw.trim().replace(/^bluebubbles:/i, "");
@@ -233,11 +239,7 @@ describe("message tool description", () => {
return trimmed;
},
},
actions: {
listActions: () =>
["react", "renameGroup", "addParticipant", "removeParticipant", "leaveGroup"] as const,
},
};
});
it("hides BlueBubbles group actions for DM targets", () => {
setActivePluginRegistry(
@@ -257,43 +259,21 @@ describe("message tool description", () => {
});
it("includes other configured channels when currentChannel is set", () => {
const signalPlugin: ChannelPlugin = {
const signalPlugin = createChannelPlugin({
id: "signal",
meta: {
id: "signal",
label: "Signal",
selectionLabel: "Signal",
docsPath: "/channels/signal",
blurb: "Signal test plugin.",
},
capabilities: { chatTypes: ["direct", "group"], media: true },
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
actions: {
listActions: () => ["send", "react"] as const,
},
};
label: "Signal",
docsPath: "/channels/signal",
blurb: "Signal test plugin.",
actions: ["send", "react"],
});
const telegramPluginFull: ChannelPlugin = {
const telegramPluginFull = createChannelPlugin({
id: "telegram",
meta: {
id: "telegram",
label: "Telegram",
selectionLabel: "Telegram",
docsPath: "/channels/telegram",
blurb: "Telegram test plugin.",
},
capabilities: { chatTypes: ["direct", "group"], media: true },
config: {
listAccountIds: () => ["default"],
resolveAccount: () => ({}),
},
actions: {
listActions: () => ["send", "react", "delete", "edit", "topic-create"] as const,
},
};
label: "Telegram",
docsPath: "/channels/telegram",
blurb: "Telegram test plugin.",
actions: ["send", "react", "delete", "edit", "topic-create"],
});
setActivePluginRegistry(
createTestRegistry([
@@ -330,103 +310,80 @@ describe("message tool description", () => {
});
describe("message tool reasoning tag sanitization", () => {
it("strips <think> tags from text field before sending", async () => {
mockSendResult({ channel: "signal", to: "signal:+15551234567" });
const tool = createMessageTool({ config: {} as never });
await tool.execute("1", {
action: "send",
it.each([
{
field: "text",
input: "<think>internal reasoning</think>Hello!",
expected: "Hello!",
target: "signal:+15551234567",
text: "<think>internal reasoning</think>Hello!",
});
const call = mocks.runMessageAction.mock.calls[0]?.[0];
expect(call?.params?.text).toBe("Hello!");
});
it("strips <think> tags from content field before sending", async () => {
mockSendResult({ channel: "discord", to: "discord:123" });
const tool = createMessageTool({ config: {} as never });
await tool.execute("1", {
action: "send",
channel: "signal",
},
{
field: "content",
input: "<think>reasoning here</think>Reply text",
expected: "Reply text",
target: "discord:123",
content: "<think>reasoning here</think>Reply text",
});
const call = mocks.runMessageAction.mock.calls[0]?.[0];
expect(call?.params?.content).toBe("Reply text");
});
it("passes through text without reasoning tags unchanged", async () => {
mockSendResult({ channel: "signal", to: "signal:+15551234567" });
const tool = createMessageTool({ config: {} as never });
await tool.execute("1", {
action: "send",
channel: "discord",
},
{
field: "text",
input: "Normal message without any tags",
expected: "Normal message without any tags",
target: "signal:+15551234567",
text: "Normal message without any tags",
});
channel: "signal",
},
])(
"sanitizes reasoning tags in $field before sending",
async ({ channel, target, field, input, expected }) => {
mockSendResult({ channel, to: target });
const call = mocks.runMessageAction.mock.calls[0]?.[0];
expect(call?.params?.text).toBe("Normal message without any tags");
});
const call = await executeSend({
action: {
target,
[field]: input,
},
});
expect(call?.params?.[field]).toBe(expected);
},
);
});
describe("message tool sandbox passthrough", () => {
it("forwards sandboxRoot to runMessageAction", async () => {
it.each([
{
name: "forwards sandboxRoot to runMessageAction",
toolOptions: { sandboxRoot: "/tmp/sandbox" },
expected: "/tmp/sandbox",
},
{
name: "omits sandboxRoot when not configured",
toolOptions: {},
expected: undefined,
},
])("$name", async ({ toolOptions, expected }) => {
mockSendResult({ to: "telegram:123" });
const tool = createMessageTool({
config: {} as never,
sandboxRoot: "/tmp/sandbox",
const call = await executeSend({
toolOptions,
action: {
target: "telegram:123",
message: "",
},
});
await tool.execute("1", {
action: "send",
target: "telegram:123",
message: "",
});
const call = mocks.runMessageAction.mock.calls[0]?.[0];
expect(call?.sandboxRoot).toBe("/tmp/sandbox");
});
it("omits sandboxRoot when not configured", async () => {
mockSendResult({ to: "telegram:123" });
const tool = createMessageTool({
config: {} as never,
});
await tool.execute("1", {
action: "send",
target: "telegram:123",
message: "",
});
const call = mocks.runMessageAction.mock.calls[0]?.[0];
expect(call?.sandboxRoot).toBeUndefined();
expect(call?.sandboxRoot).toBe(expected);
});
it("forwards trusted requesterSenderId to runMessageAction", async () => {
mockSendResult({ to: "discord:123" });
const tool = createMessageTool({
config: {} as never,
requesterSenderId: "1234567890",
const call = await executeSend({
toolOptions: { requesterSenderId: "1234567890" },
action: {
target: "discord:123",
message: "hi",
},
});
await tool.execute("1", {
action: "send",
target: "discord:123",
message: "hi",
});
const call = mocks.runMessageAction.mock.calls[0]?.[0];
expect(call?.requesterSenderId).toBe("1234567890");
});
});

View File

@@ -35,6 +35,10 @@ import { createSessionsSendTool } from "./sessions-send-tool.js";
let resolveAnnounceTarget: (typeof import("./sessions-announce-target.js"))["resolveAnnounceTarget"];
let setActivePluginRegistry: (typeof import("../../plugins/runtime.js"))["setActivePluginRegistry"];
const MAIN_AGENT_SESSION_KEY = "agent:main:main";
const MAIN_AGENT_CHANNEL = "whatsapp";
type SessionsListResult = Awaited<ReturnType<ReturnType<typeof createSessionsListTool>["execute"]>>;
const installRegistry = async () => {
setActivePluginRegistry(
@@ -82,6 +86,52 @@ const installRegistry = async () => {
);
};
function createMainSessionsListTool() {
return createSessionsListTool({ agentSessionKey: MAIN_AGENT_SESSION_KEY });
}
async function executeMainSessionsList() {
return createMainSessionsListTool().execute("call1", {});
}
function createMainSessionsSendTool() {
return createSessionsSendTool({
agentSessionKey: MAIN_AGENT_SESSION_KEY,
agentChannel: MAIN_AGENT_CHANNEL,
});
}
function getFirstListedSession(result: SessionsListResult) {
const details = result.details as
| { sessions?: Array<{ key?: string; transcriptPath?: string }> }
| undefined;
return details?.sessions?.[0];
}
function expectWorkerTranscriptPath(
result: SessionsListResult,
params: { containsPath: string; sessionId: string },
) {
const session = getFirstListedSession(result);
expect(session).toMatchObject({ key: "agent:worker:main" });
const transcriptPath = String(session?.transcriptPath ?? "");
expect(path.normalize(transcriptPath)).toContain(path.normalize(params.containsPath));
expect(transcriptPath).toMatch(new RegExp(`${params.sessionId}\\.jsonl$`));
}
async function withStubbedStateDir<T>(
name: string,
run: (stateDir: string) => Promise<T>,
): Promise<T> {
const stateDir = path.join(os.tmpdir(), name);
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
try {
return await run(stateDir);
} finally {
vi.unstubAllEnvs();
}
}
describe("sanitizeTextContent", () => {
it("strips minimax tool call XML and downgraded markers", () => {
const input =
@@ -209,11 +259,11 @@ describe("sessions_list gating", () => {
});
it("filters out other agents when tools.agentToAgent.enabled is false", async () => {
const tool = createSessionsListTool({ agentSessionKey: "agent:main:main" });
const tool = createMainSessionsListTool();
const result = await tool.execute("call1", {});
expect(result.details).toMatchObject({
count: 1,
sessions: [{ key: "agent:main:main" }],
sessions: [{ key: MAIN_AGENT_SESSION_KEY }],
});
});
});
@@ -231,10 +281,7 @@ describe("sessions_list transcriptPath resolution", () => {
});
it("resolves cross-agent transcript paths from agent defaults when gateway store path is relative", async () => {
const stateDir = path.join(os.tmpdir(), "openclaw-state-relative");
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
try {
await withStubbedStateDir("openclaw-state-relative", async () => {
callGatewayMock.mockResolvedValueOnce({
path: "agents/main/sessions/sessions.json",
sessions: [
@@ -246,27 +293,16 @@ describe("sessions_list transcriptPath resolution", () => {
],
});
const tool = createSessionsListTool({ agentSessionKey: "agent:main:main" });
const result = await tool.execute("call1", {});
const details = result.details as
| { sessions?: Array<{ key?: string; transcriptPath?: string }> }
| undefined;
const session = details?.sessions?.[0];
expect(session).toMatchObject({ key: "agent:worker:main" });
const transcriptPath = String(session?.transcriptPath ?? "");
expect(path.normalize(transcriptPath)).toContain(path.join("agents", "worker", "sessions"));
expect(transcriptPath).toMatch(/sess-worker\.jsonl$/);
} finally {
vi.unstubAllEnvs();
}
const result = await executeMainSessionsList();
expectWorkerTranscriptPath(result, {
containsPath: path.join("agents", "worker", "sessions"),
sessionId: "sess-worker",
});
});
});
it("resolves transcriptPath even when sessions.list does not return a store path", async () => {
const stateDir = path.join(os.tmpdir(), "openclaw-state-no-path");
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
try {
await withStubbedStateDir("openclaw-state-no-path", async () => {
callGatewayMock.mockResolvedValueOnce({
sessions: [
{
@@ -277,27 +313,16 @@ describe("sessions_list transcriptPath resolution", () => {
],
});
const tool = createSessionsListTool({ agentSessionKey: "agent:main:main" });
const result = await tool.execute("call1", {});
const details = result.details as
| { sessions?: Array<{ key?: string; transcriptPath?: string }> }
| undefined;
const session = details?.sessions?.[0];
expect(session).toMatchObject({ key: "agent:worker:main" });
const transcriptPath = String(session?.transcriptPath ?? "");
expect(path.normalize(transcriptPath)).toContain(path.join("agents", "worker", "sessions"));
expect(transcriptPath).toMatch(/sess-worker-no-path\.jsonl$/);
} finally {
vi.unstubAllEnvs();
}
const result = await executeMainSessionsList();
expectWorkerTranscriptPath(result, {
containsPath: path.join("agents", "worker", "sessions"),
sessionId: "sess-worker-no-path",
});
});
});
it("falls back to agent defaults when gateway path is non-string", async () => {
const stateDir = path.join(os.tmpdir(), "openclaw-state-non-string-path");
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
try {
await withStubbedStateDir("openclaw-state-non-string-path", async () => {
callGatewayMock.mockResolvedValueOnce({
path: { raw: "agents/main/sessions/sessions.json" },
sessions: [
@@ -309,27 +334,16 @@ describe("sessions_list transcriptPath resolution", () => {
],
});
const tool = createSessionsListTool({ agentSessionKey: "agent:main:main" });
const result = await tool.execute("call1", {});
const details = result.details as
| { sessions?: Array<{ key?: string; transcriptPath?: string }> }
| undefined;
const session = details?.sessions?.[0];
expect(session).toMatchObject({ key: "agent:worker:main" });
const transcriptPath = String(session?.transcriptPath ?? "");
expect(path.normalize(transcriptPath)).toContain(path.join("agents", "worker", "sessions"));
expect(transcriptPath).toMatch(/sess-worker-shape\.jsonl$/);
} finally {
vi.unstubAllEnvs();
}
const result = await executeMainSessionsList();
expectWorkerTranscriptPath(result, {
containsPath: path.join("agents", "worker", "sessions"),
sessionId: "sess-worker-shape",
});
});
});
it("falls back to agent defaults when gateway path is '(multiple)'", async () => {
const stateDir = path.join(os.tmpdir(), "openclaw-state-multiple");
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
try {
await withStubbedStateDir("openclaw-state-multiple", async (stateDir) => {
callGatewayMock.mockResolvedValueOnce({
path: "(multiple)",
sessions: [
@@ -341,22 +355,12 @@ describe("sessions_list transcriptPath resolution", () => {
],
});
const tool = createSessionsListTool({ agentSessionKey: "agent:main:main" });
const result = await tool.execute("call1", {});
const details = result.details as
| { sessions?: Array<{ key?: string; transcriptPath?: string }> }
| undefined;
const session = details?.sessions?.[0];
expect(session).toMatchObject({ key: "agent:worker:main" });
const transcriptPath = String(session?.transcriptPath ?? "");
expect(path.normalize(transcriptPath)).toContain(
path.join(stateDir, "agents", "worker", "sessions"),
);
expect(transcriptPath).toMatch(/sess-worker-multiple\.jsonl$/);
} finally {
vi.unstubAllEnvs();
}
const result = await executeMainSessionsList();
expectWorkerTranscriptPath(result, {
containsPath: path.join(stateDir, "agents", "worker", "sessions"),
sessionId: "sess-worker-multiple",
});
});
});
it("resolves absolute {agentId} template paths per session agent", async () => {
@@ -373,18 +377,12 @@ describe("sessions_list transcriptPath resolution", () => {
],
});
const tool = createSessionsListTool({ agentSessionKey: "agent:main:main" });
const result = await tool.execute("call1", {});
const details = result.details as
| { sessions?: Array<{ key?: string; transcriptPath?: string }> }
| undefined;
const session = details?.sessions?.[0];
expect(session).toMatchObject({ key: "agent:worker:main" });
const transcriptPath = String(session?.transcriptPath ?? "");
const result = await executeMainSessionsList();
const expectedSessionsDir = path.dirname(templateStorePath.replace("{agentId}", "worker"));
expect(path.normalize(transcriptPath)).toContain(path.normalize(expectedSessionsDir));
expect(transcriptPath).toMatch(/sess-worker-template\.jsonl$/);
expectWorkerTranscriptPath(result, {
containsPath: expectedSessionsDir,
sessionId: "sess-worker-template",
});
});
});
@@ -394,10 +392,7 @@ describe("sessions_send gating", () => {
});
it("returns an error when neither sessionKey nor label is provided", async () => {
const tool = createSessionsSendTool({
agentSessionKey: "agent:main:main",
agentChannel: "whatsapp",
});
const tool = createMainSessionsSendTool();
const result = await tool.execute("call-missing-target", {
message: "hi",
@@ -413,10 +408,7 @@ describe("sessions_send gating", () => {
it("returns an error when label resolution fails", async () => {
callGatewayMock.mockRejectedValueOnce(new Error("No session found with label: nope"));
const tool = createSessionsSendTool({
agentSessionKey: "agent:main:main",
agentChannel: "whatsapp",
});
const tool = createMainSessionsSendTool();
const result = await tool.execute("call-missing-label", {
label: "nope",
@@ -435,10 +427,7 @@ describe("sessions_send gating", () => {
});
it("blocks cross-agent sends when tools.agentToAgent.enabled is false", async () => {
const tool = createSessionsSendTool({
agentSessionKey: "agent:main:main",
agentChannel: "whatsapp",
});
const tool = createMainSessionsSendTool();
const result = await tool.execute("call1", {
sessionKey: "agent:other:main",