Skip to content

Commit 8daf012

Browse files
committed
fix(subagents): avoid duplicate parent send replies
1 parent c571deb commit 8daf012

3 files changed

Lines changed: 130 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Docs: https://docs.openclaw.ai
2929
- Plugins/web-provider: reuse the active gateway plugin registry for runtime web provider resolution after deriving the same candidate plugin ids as the loader path, avoiding a redundant `loadOpenClawPlugins` call on every request while preserving origin and scope filters. Fixes #75513. Thanks @jochen.
3030
- Crestodian/CLI: exit non-zero when interactive Crestodian is invoked without a TTY, so scripts and CI no longer treat the setup error as success. Fixes #73646 and supersedes #73928 and #74059. Thanks @bittoby, @luyao618, and @Linux2010.
3131
- Cron: keep implicit/default isolated cron announce deliveries out of the main session awareness queue, so isolated jobs do not accumulate in the main conversation. Fixes #61426. Thanks @Lihannon.
32+
- Subagents: avoid duplicate parent-visible replies when a parent uses `sessions_send` on its own persistent native subagent session, while preserving announce delivery for async sends. Fixes #73550. Thanks @sylviazhang2006-design.
3233
- Agents/sandbox: preserve existing workspace file modes when sandbox edits atomically replace files, so 0644 files do not collapse to 0600 after Write/Edit/apply_patch. Fixes #44077. Thanks @patosullivan.
3334
- Agents/models: keep legacy CLI runtime model refs such as `claude-cli/*` in the configured allowlist after canonical runtime migration, so cron `payload.model` overrides keep working. Fixes #75753. Thanks @RyanSandoval.
3435
- Codex/app-server: restart the shared Codex app-server client once when it closes during startup thread resume, preserving the existing thread binding instead of retrying `thread/start` on a closed client. Thanks @vincentkoc.

‎src/agents/openclaw-tools.sessions.test.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ const callGatewayMock = vi.fn();
1010
vi.mock("../gateway/call.js", () => ({
1111
callGateway: (opts: unknown) => callGatewayMock(opts),
1212
}));
13+
const loadSessionEntryByKeyMock = vi.fn();
14+
vi.mock("./subagent-announce-delivery.js", () => ({
15+
loadSessionEntryByKey: (sessionKey: string) => loadSessionEntryByKeyMock(sessionKey),
16+
}));
1317

1418
vi.mock("../config/config.js", () => ({
1519
getRuntimeConfig: () => ({
@@ -156,6 +160,8 @@ const waitForCalls = async (getCount: () => number, count: number, timeoutMs = 2
156160
describe("sessions tools", () => {
157161
beforeEach(() => {
158162
callGatewayMock.mockClear();
163+
loadSessionEntryByKeyMock.mockReset();
164+
loadSessionEntryByKeyMock.mockReturnValue(undefined);
159165
installMessagingTestRegistry();
160166
agentStepTesting.setDepsForTest({
161167
agentCommandFromIngress: async () => ({
@@ -1092,6 +1098,85 @@ describe("sessions tools", () => {
10921098
});
10931099
});
10941100

1101+
it("sessions_send skips duplicate A2A delivery for waited parent-owned native subagents", async () => {
1102+
const calls: Array<{ method?: string; params?: unknown }> = [];
1103+
const requesterKey = "agent:main:discord:direct:parent";
1104+
const targetKey = "agent:main:subagent:child";
1105+
let historyCallCount = 0;
1106+
loadSessionEntryByKeyMock.mockImplementation((sessionKey: string) =>
1107+
sessionKey === targetKey
1108+
? {
1109+
sessionId: "child-session",
1110+
updatedAt: 1,
1111+
spawnedBy: requesterKey,
1112+
deliveryContext: {
1113+
channel: "discord",
1114+
to: "direct:parent",
1115+
},
1116+
}
1117+
: undefined,
1118+
);
1119+
callGatewayMock.mockImplementation(async (opts: unknown) => {
1120+
const request = opts as { method?: string; params?: unknown };
1121+
calls.push(request);
1122+
if (request.method === "agent") {
1123+
return { runId: "run-child", status: "accepted", acceptedAt: 2000 };
1124+
}
1125+
if (request.method === "agent.wait") {
1126+
return { runId: "run-child", status: "ok" };
1127+
}
1128+
if (request.method === "chat.history") {
1129+
historyCallCount += 1;
1130+
return {
1131+
messages:
1132+
historyCallCount === 1
1133+
? []
1134+
: [
1135+
{
1136+
role: "assistant",
1137+
content: [{ type: "text", text: "child reply" }],
1138+
timestamp: 20,
1139+
},
1140+
],
1141+
};
1142+
}
1143+
return {};
1144+
});
1145+
1146+
const tool = createOpenClawTools({
1147+
agentSessionKey: requesterKey,
1148+
agentChannel: "discord",
1149+
}).find((candidate) => candidate.name === "sessions_send");
1150+
expect(tool).toBeDefined();
1151+
if (!tool) {
1152+
throw new Error("missing sessions_send tool");
1153+
}
1154+
1155+
const waited = await tool.execute("call-parent-owned-native-subagent", {
1156+
sessionKey: targetKey,
1157+
message: "ping",
1158+
timeoutSeconds: 1,
1159+
});
1160+
1161+
expect(waited.details).toMatchObject({
1162+
status: "ok",
1163+
reply: "child reply",
1164+
delivery: { status: "skipped", mode: "announce" },
1165+
});
1166+
expect(calls.filter((call) => call.method === "agent")).toHaveLength(1);
1167+
expect(
1168+
calls.some(
1169+
(call) =>
1170+
call.method === "agent" &&
1171+
typeof (call.params as { extraSystemPrompt?: string })?.extraSystemPrompt === "string" &&
1172+
(call.params as { extraSystemPrompt?: string }).extraSystemPrompt?.includes(
1173+
"Agent-to-agent reply step",
1174+
),
1175+
),
1176+
).toBe(false);
1177+
expect(calls.some((call) => call.method === "send")).toBe(false);
1178+
});
1179+
10951180
it("sessions_send preserves threadId when announce target is hydrated via sessions.list", async () => {
10961181
const calls: Array<{ method?: string; params?: unknown }> = [];
10971182
let agentCallCount = 0;

‎src/agents/tools/sessions-send-tool.ts‎

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,15 @@ import crypto from "node:crypto";
22
import { Type } from "typebox";
33
import { isRequesterParentOfBackgroundAcpSession } from "../../acp/session-interaction-mode.js";
44
import { parseSessionThreadInfoFast } from "../../config/sessions/thread-info.js";
5+
import type { SessionEntry } from "../../config/sessions/types.js";
56
import type { OpenClawConfig } from "../../config/types.openclaw.js";
67
import { callGateway } from "../../gateway/call.js";
78
import { formatErrorMessage } from "../../infra/errors.js";
8-
import { normalizeAgentId, resolveAgentIdFromSessionKey } from "../../routing/session-key.js";
9+
import {
10+
isSubagentSessionKey,
11+
normalizeAgentId,
12+
resolveAgentIdFromSessionKey,
13+
} from "../../routing/session-key.js";
914
import { annotateInterSessionPromptText } from "../../sessions/input-provenance.js";
1015
import { SESSION_LABEL_MAX_LENGTH } from "../../sessions/session-label.js";
1116
import { normalizeOptionalString } from "../../shared/string-coerce.js";
@@ -47,6 +52,25 @@ const SessionsSendToolSchema = Type.Object({
4752
type GatewayCaller = typeof callGateway;
4853
const SESSIONS_SEND_REPLY_HISTORY_LIMIT = 50;
4954

55+
type SessionsSendRouteEntry = Pick<SessionEntry, "acp" | "parentSessionKey" | "spawnedBy">;
56+
57+
function isRequesterParentOfNativeSubagentSession(params: {
58+
entry: SessionsSendRouteEntry | null | undefined;
59+
requesterSessionKey: string | null | undefined;
60+
targetSessionKey: string;
61+
}): boolean {
62+
if (!params.entry || params.entry.acp || !isSubagentSessionKey(params.targetSessionKey)) {
63+
return false;
64+
}
65+
const requester = normalizeOptionalString(params.requesterSessionKey);
66+
if (!requester) {
67+
return false;
68+
}
69+
const spawnedBy = normalizeOptionalString(params.entry.spawnedBy);
70+
const parentSessionKey = normalizeOptionalString(params.entry.parentSessionKey);
71+
return requester === spawnedBy || requester === parentSessionKey;
72+
}
73+
5074
async function startAgentRun(params: {
5175
callGateway: GatewayCaller;
5276
runId: string;
@@ -304,24 +328,34 @@ export function createSessionsSendTool(opts?: {
304328
const maxPingPongTurns = resolvePingPongTurns(cfg);
305329

306330
// Skip the A2A ping-pong + announce flow when the current caller is the
307-
// parent of a parent-owned background ACP subagent it spawned itself.
308-
// Such sessions already report their results back to the parent through
309-
// the `[Internal task completion event]` announcement path, and treating
310-
// them as a peer agent causes the parent to be woken with the child's
311-
// reply, generate a user-facing response, and have that response
312-
// forwarded back to the child as a new message — producing a
313-
// ping-pong loop between parent and ACP child (bounded by
314-
// maxPingPongTurns, but user-visible as a runaway conversation).
331+
// parent of a parent-owned child session it spawned itself and another
332+
// parent-visible result path already exists.
333+
//
334+
// ACP background sessions report through the internal task completion
335+
// path. Waited native subagent sends return the child reply inline. In
336+
// both cases treating the child as a peer agent wakes the parent with
337+
// the child's reply, can generate another user-facing response, and can
338+
// forward that response back to the child as a new message — producing a
339+
// ping-pong loop (bounded by maxPingPongTurns, but visible as duplicate
340+
// conversation output).
315341
//
316342
// The skip is gated on requester ownership, not just target type: an
317343
// unrelated sender that can see the same target (e.g. under
318344
// `tools.sessions.visibility=all`) must still go through the normal A2A
319345
// path so it actually receives a follow-up delivery.
320346
const targetSessionEntry = loadSessionEntryByKey(resolvedKey);
321-
const skipA2AFlow = isRequesterParentOfBackgroundAcpSession(
347+
const skipAcpA2AFlow = isRequesterParentOfBackgroundAcpSession(
322348
targetSessionEntry,
323349
effectiveRequesterKey,
324350
);
351+
const skipNativeParentA2AFlow =
352+
timeoutSeconds !== 0 &&
353+
isRequesterParentOfNativeSubagentSession({
354+
entry: targetSessionEntry,
355+
requesterSessionKey: effectiveRequesterKey,
356+
targetSessionKey: resolvedKey,
357+
});
358+
const skipA2AFlow = skipAcpA2AFlow || skipNativeParentA2AFlow;
325359
// When the A2A flow is skipped, no follow-up announcement will fire and
326360
// the reply (when present) is returned inline via the `reply` field.
327361
// Reflect that in the metadata so the parent LLM does not wait for a

0 commit comments

Comments
 (0)