mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-07 22:41:25 +00:00
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>
This commit is contained in:
373
src/agents/sessions-spawn-hooks.test.ts
Normal file
373
src/agents/sessions-spawn-hooks.test.ts
Normal file
@@ -0,0 +1,373 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import "./test-helpers/fast-core-tools.js";
|
||||
import {
|
||||
getCallGatewayMock,
|
||||
getSessionsSpawnTool,
|
||||
setSessionsSpawnConfigOverride,
|
||||
} from "./openclaw-tools.subagents.sessions-spawn.test-harness.js";
|
||||
|
||||
const hookRunnerMocks = vi.hoisted(() => ({
|
||||
hasSubagentEndedHook: true,
|
||||
runSubagentSpawning: vi.fn(async (event: unknown) => {
|
||||
const input = event as {
|
||||
threadRequested?: boolean;
|
||||
requester?: { channel?: string };
|
||||
};
|
||||
if (!input.threadRequested) {
|
||||
return undefined;
|
||||
}
|
||||
const channel = input.requester?.channel?.trim().toLowerCase();
|
||||
if (channel !== "discord") {
|
||||
const channelLabel = input.requester?.channel?.trim() || "unknown";
|
||||
return {
|
||||
status: "error" as const,
|
||||
error: `thread=true is not supported for channel "${channelLabel}". Only Discord thread-bound subagent sessions are supported right now.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: "ok" as const,
|
||||
threadBindingReady: true,
|
||||
};
|
||||
}),
|
||||
runSubagentSpawned: vi.fn(async () => {}),
|
||||
runSubagentEnded: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("../plugins/hook-runner-global.js", () => ({
|
||||
getGlobalHookRunner: vi.fn(() => ({
|
||||
hasHooks: (hookName: string) =>
|
||||
hookName === "subagent_spawning" ||
|
||||
hookName === "subagent_spawned" ||
|
||||
(hookName === "subagent_ended" && hookRunnerMocks.hasSubagentEndedHook),
|
||||
runSubagentSpawning: hookRunnerMocks.runSubagentSpawning,
|
||||
runSubagentSpawned: hookRunnerMocks.runSubagentSpawned,
|
||||
runSubagentEnded: hookRunnerMocks.runSubagentEnded,
|
||||
})),
|
||||
}));
|
||||
|
||||
describe("sessions_spawn subagent lifecycle hooks", () => {
|
||||
beforeEach(() => {
|
||||
hookRunnerMocks.hasSubagentEndedHook = true;
|
||||
hookRunnerMocks.runSubagentSpawning.mockClear();
|
||||
hookRunnerMocks.runSubagentSpawned.mockClear();
|
||||
hookRunnerMocks.runSubagentEnded.mockClear();
|
||||
const callGatewayMock = getCallGatewayMock();
|
||||
callGatewayMock.mockReset();
|
||||
setSessionsSpawnConfigOverride({
|
||||
session: {
|
||||
mainKey: "main",
|
||||
scope: "per-sender",
|
||||
},
|
||||
});
|
||||
callGatewayMock.mockImplementation(async (opts: unknown) => {
|
||||
const request = opts as { method?: string };
|
||||
if (request.method === "agent") {
|
||||
return { runId: "run-1", status: "accepted", acceptedAt: 1 };
|
||||
}
|
||||
if (request.method === "agent.wait") {
|
||||
return { runId: "run-1", status: "running" };
|
||||
}
|
||||
return {};
|
||||
});
|
||||
});
|
||||
|
||||
it("runs subagent_spawning and emits subagent_spawned with requester metadata", async () => {
|
||||
const tool = await getSessionsSpawnTool({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "work",
|
||||
agentTo: "channel:123",
|
||||
agentThreadId: 456,
|
||||
});
|
||||
|
||||
const result = await tool.execute("call", {
|
||||
task: "do thing",
|
||||
label: "research",
|
||||
runTimeoutSeconds: 1,
|
||||
thread: true,
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({ status: "accepted", runId: "run-1" });
|
||||
expect(hookRunnerMocks.runSubagentSpawning).toHaveBeenCalledTimes(1);
|
||||
expect(hookRunnerMocks.runSubagentSpawning).toHaveBeenCalledWith(
|
||||
{
|
||||
childSessionKey: expect.stringMatching(/^agent:main:subagent:/),
|
||||
agentId: "main",
|
||||
label: "research",
|
||||
mode: "session",
|
||||
requester: {
|
||||
channel: "discord",
|
||||
accountId: "work",
|
||||
to: "channel:123",
|
||||
threadId: 456,
|
||||
},
|
||||
threadRequested: true,
|
||||
},
|
||||
{
|
||||
childSessionKey: expect.stringMatching(/^agent:main:subagent:/),
|
||||
requesterSessionKey: "main",
|
||||
},
|
||||
);
|
||||
|
||||
expect(hookRunnerMocks.runSubagentSpawned).toHaveBeenCalledTimes(1);
|
||||
const [event, ctx] = (hookRunnerMocks.runSubagentSpawned.mock.calls[0] ?? []) as unknown as [
|
||||
Record<string, unknown>,
|
||||
Record<string, unknown>,
|
||||
];
|
||||
expect(event).toMatchObject({
|
||||
runId: "run-1",
|
||||
agentId: "main",
|
||||
label: "research",
|
||||
mode: "session",
|
||||
requester: {
|
||||
channel: "discord",
|
||||
accountId: "work",
|
||||
to: "channel:123",
|
||||
threadId: 456,
|
||||
},
|
||||
threadRequested: true,
|
||||
});
|
||||
expect(event.childSessionKey).toEqual(expect.stringMatching(/^agent:main:subagent:/));
|
||||
expect(ctx).toMatchObject({
|
||||
runId: "run-1",
|
||||
requesterSessionKey: "main",
|
||||
childSessionKey: event.childSessionKey,
|
||||
});
|
||||
});
|
||||
|
||||
it("emits subagent_spawned with threadRequested=false when not requested", async () => {
|
||||
const tool = await getSessionsSpawnTool({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "discord",
|
||||
agentTo: "channel:123",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call2", {
|
||||
task: "do thing",
|
||||
runTimeoutSeconds: 1,
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({ status: "accepted", runId: "run-1" });
|
||||
expect(hookRunnerMocks.runSubagentSpawning).not.toHaveBeenCalled();
|
||||
expect(hookRunnerMocks.runSubagentSpawned).toHaveBeenCalledTimes(1);
|
||||
const [event] = (hookRunnerMocks.runSubagentSpawned.mock.calls[0] ?? []) as unknown as [
|
||||
Record<string, unknown>,
|
||||
];
|
||||
expect(event).toMatchObject({
|
||||
mode: "run",
|
||||
threadRequested: false,
|
||||
requester: {
|
||||
channel: "discord",
|
||||
to: "channel:123",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("respects explicit mode=run when thread binding is requested", async () => {
|
||||
const tool = await getSessionsSpawnTool({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "discord",
|
||||
agentTo: "channel:123",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call3", {
|
||||
task: "do thing",
|
||||
runTimeoutSeconds: 1,
|
||||
thread: true,
|
||||
mode: "run",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({ status: "accepted", runId: "run-1", mode: "run" });
|
||||
expect(hookRunnerMocks.runSubagentSpawning).toHaveBeenCalledTimes(1);
|
||||
const [event] = (hookRunnerMocks.runSubagentSpawned.mock.calls[0] ?? []) as unknown as [
|
||||
Record<string, unknown>,
|
||||
];
|
||||
expect(event).toMatchObject({
|
||||
mode: "run",
|
||||
threadRequested: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns error when thread binding cannot be created", async () => {
|
||||
hookRunnerMocks.runSubagentSpawning.mockResolvedValueOnce({
|
||||
status: "error",
|
||||
error: "Unable to create or bind a Discord thread for this subagent session.",
|
||||
});
|
||||
const tool = await getSessionsSpawnTool({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "work",
|
||||
agentTo: "channel:123",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call4", {
|
||||
task: "do thing",
|
||||
runTimeoutSeconds: 1,
|
||||
thread: true,
|
||||
mode: "session",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({ status: "error" });
|
||||
const details = result.details as { error?: string; childSessionKey?: string };
|
||||
expect(details.error).toMatch(/thread/i);
|
||||
expect(hookRunnerMocks.runSubagentSpawned).not.toHaveBeenCalled();
|
||||
const callGatewayMock = getCallGatewayMock();
|
||||
const calledMethods = callGatewayMock.mock.calls.map((call: [unknown]) => {
|
||||
const request = call[0] as { method?: string };
|
||||
return request.method;
|
||||
});
|
||||
expect(calledMethods).toContain("sessions.delete");
|
||||
expect(calledMethods).not.toContain("agent");
|
||||
const deleteCall = callGatewayMock.mock.calls
|
||||
.map((call: [unknown]) => call[0] as { method?: string; params?: Record<string, unknown> })
|
||||
.find(
|
||||
(request: { method?: string; params?: Record<string, unknown> }) =>
|
||||
request.method === "sessions.delete",
|
||||
);
|
||||
expect(deleteCall?.params).toMatchObject({
|
||||
key: details.childSessionKey,
|
||||
emitLifecycleHooks: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects mode=session when thread=true is not requested", async () => {
|
||||
const tool = await getSessionsSpawnTool({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "discord",
|
||||
agentTo: "channel:123",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call6", {
|
||||
task: "do thing",
|
||||
mode: "session",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({ status: "error" });
|
||||
const details = result.details as { error?: string };
|
||||
expect(details.error).toMatch(/requires thread=true/i);
|
||||
expect(hookRunnerMocks.runSubagentSpawning).not.toHaveBeenCalled();
|
||||
expect(hookRunnerMocks.runSubagentSpawned).not.toHaveBeenCalled();
|
||||
const callGatewayMock = getCallGatewayMock();
|
||||
expect(callGatewayMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects thread=true on channels without thread support", async () => {
|
||||
const tool = await getSessionsSpawnTool({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "signal",
|
||||
agentTo: "+123",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call5", {
|
||||
task: "do thing",
|
||||
thread: true,
|
||||
mode: "session",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({ status: "error" });
|
||||
const details = result.details as { error?: string };
|
||||
expect(details.error).toMatch(/only discord/i);
|
||||
expect(hookRunnerMocks.runSubagentSpawning).toHaveBeenCalledTimes(1);
|
||||
expect(hookRunnerMocks.runSubagentSpawned).not.toHaveBeenCalled();
|
||||
const callGatewayMock = getCallGatewayMock();
|
||||
const calledMethods = callGatewayMock.mock.calls.map((call: [unknown]) => {
|
||||
const request = call[0] as { method?: string };
|
||||
return request.method;
|
||||
});
|
||||
expect(calledMethods).toContain("sessions.delete");
|
||||
expect(calledMethods).not.toContain("agent");
|
||||
});
|
||||
|
||||
it("runs subagent_ended cleanup hook when agent start fails after successful bind", async () => {
|
||||
const callGatewayMock = getCallGatewayMock();
|
||||
callGatewayMock.mockImplementation(async (opts: unknown) => {
|
||||
const request = opts as { method?: string };
|
||||
if (request.method === "agent") {
|
||||
throw new Error("spawn failed");
|
||||
}
|
||||
return {};
|
||||
});
|
||||
const tool = await getSessionsSpawnTool({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "work",
|
||||
agentTo: "channel:123",
|
||||
agentThreadId: "456",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call7", {
|
||||
task: "do thing",
|
||||
thread: true,
|
||||
mode: "session",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({ status: "error" });
|
||||
expect(hookRunnerMocks.runSubagentEnded).toHaveBeenCalledTimes(1);
|
||||
const [event] = (hookRunnerMocks.runSubagentEnded.mock.calls[0] ?? []) as unknown as [
|
||||
Record<string, unknown>,
|
||||
];
|
||||
expect(event).toMatchObject({
|
||||
targetSessionKey: expect.stringMatching(/^agent:main:subagent:/),
|
||||
accountId: "work",
|
||||
targetKind: "subagent",
|
||||
reason: "spawn-failed",
|
||||
sendFarewell: true,
|
||||
outcome: "error",
|
||||
error: "Session failed to start",
|
||||
});
|
||||
const deleteCall = callGatewayMock.mock.calls
|
||||
.map((call: [unknown]) => call[0] as { method?: string; params?: Record<string, unknown> })
|
||||
.find(
|
||||
(request: { method?: string; params?: Record<string, unknown> }) =>
|
||||
request.method === "sessions.delete",
|
||||
);
|
||||
expect(deleteCall?.params).toMatchObject({
|
||||
key: event.targetSessionKey,
|
||||
deleteTranscript: true,
|
||||
emitLifecycleHooks: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to sessions.delete cleanup when subagent_ended hook is unavailable", async () => {
|
||||
hookRunnerMocks.hasSubagentEndedHook = false;
|
||||
const callGatewayMock = getCallGatewayMock();
|
||||
callGatewayMock.mockImplementation(async (opts: unknown) => {
|
||||
const request = opts as { method?: string };
|
||||
if (request.method === "agent") {
|
||||
throw new Error("spawn failed");
|
||||
}
|
||||
return {};
|
||||
});
|
||||
const tool = await getSessionsSpawnTool({
|
||||
agentSessionKey: "main",
|
||||
agentChannel: "discord",
|
||||
agentAccountId: "work",
|
||||
agentTo: "channel:123",
|
||||
agentThreadId: "456",
|
||||
});
|
||||
|
||||
const result = await tool.execute("call8", {
|
||||
task: "do thing",
|
||||
thread: true,
|
||||
mode: "session",
|
||||
});
|
||||
|
||||
expect(result.details).toMatchObject({ status: "error" });
|
||||
expect(hookRunnerMocks.runSubagentEnded).not.toHaveBeenCalled();
|
||||
const methods = callGatewayMock.mock.calls.map((call: [unknown]) => {
|
||||
const request = call[0] as { method?: string };
|
||||
return request.method;
|
||||
});
|
||||
expect(methods).toContain("sessions.delete");
|
||||
const deleteCall = callGatewayMock.mock.calls
|
||||
.map((call: [unknown]) => call[0] as { method?: string; params?: Record<string, unknown> })
|
||||
.find(
|
||||
(request: { method?: string; params?: Record<string, unknown> }) =>
|
||||
request.method === "sessions.delete",
|
||||
);
|
||||
expect(deleteCall?.params).toMatchObject({
|
||||
deleteTranscript: true,
|
||||
emitLifecycleHooks: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user