Skip to content

Commit dc34274

Browse files
fix(outbound): recognize current-source message-tool sends (#116560)
* fix(discord): recognize adopted thread sends * fix(discord): require successful adopted thread delivery * fix(outbound): mark automatic current-source sends * test(gateway): cover automatic source projection
1 parent 4c33116 commit dc34274

6 files changed

Lines changed: 291 additions & 17 deletions

File tree

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
4+
const runtimeModule = await import("./runtime.js");
5+
const handleDiscordActionMock = vi
6+
.spyOn(runtimeModule, "handleDiscordAction")
7+
.mockResolvedValue({ content: [], details: { ok: true } });
8+
const { handleDiscordMessageAction } = await import("./handle-action.js");
9+
const { beginDiscordActiveTurnThreadRoute, notifyDiscordActiveTurnThreadCreated } =
10+
await import("../active-turn-thread-route.js");
11+
12+
function discordConfig(): OpenClawConfig {
13+
return {
14+
channels: { discord: { token: "tok" } },
15+
} as OpenClawConfig;
16+
}
17+
18+
describe("handleDiscordMessageAction adopted thread delivery", () => {
19+
beforeEach(() => {
20+
handleDiscordActionMock.mockClear();
21+
});
22+
23+
it("classifies generic sends only when targeting the active adopted thread", async () => {
24+
const sessionKey = "agent:main:discord:channel:channel-1";
25+
const onThreadReplyDelivered = vi.fn();
26+
const endRoute = beginDiscordActiveTurnThreadRoute(sessionKey, {
27+
accountId: "account-1",
28+
sourceChannelId: "channel-1",
29+
sourceMessageId: "message-1",
30+
onThreadAdopted: vi.fn(),
31+
onThreadReplyDelivered,
32+
});
33+
try {
34+
await notifyDiscordActiveTurnThreadCreated({
35+
sessionKey,
36+
accountId: "account-1",
37+
sourceChannelId: "channel-1",
38+
sourceMessageId: "message-1",
39+
threadId: "thread-1",
40+
});
41+
42+
const unrelatedResult = await handleDiscordMessageAction({
43+
action: "send",
44+
params: {
45+
to: "channel:thread-2",
46+
message: "unrelated",
47+
},
48+
cfg: discordConfig(),
49+
accountId: "account-1",
50+
sessionKey,
51+
});
52+
53+
expect(unrelatedResult.details).toEqual({ ok: true });
54+
expect(onThreadReplyDelivered).not.toHaveBeenCalled();
55+
56+
const result = await handleDiscordMessageAction({
57+
action: "send",
58+
params: {
59+
to: "channel:thread-1",
60+
message: "done",
61+
},
62+
cfg: discordConfig(),
63+
accountId: "account-1",
64+
sessionKey,
65+
});
66+
67+
expect(result.details).toEqual({
68+
ok: true,
69+
sourceReplyRoute: "current-source",
70+
});
71+
expect(onThreadReplyDelivered).toHaveBeenCalledWith("thread-1");
72+
} finally {
73+
endRoute();
74+
}
75+
});
76+
77+
it("classifies upload-file to the active adopted thread as current-source delivery", async () => {
78+
const sessionKey = "agent:main:discord:channel:channel-1";
79+
const onThreadReplyDelivered = vi.fn();
80+
const endRoute = beginDiscordActiveTurnThreadRoute(sessionKey, {
81+
accountId: "account-1",
82+
sourceChannelId: "channel-1",
83+
sourceMessageId: "message-1",
84+
onThreadAdopted: vi.fn(),
85+
onThreadReplyDelivered,
86+
});
87+
try {
88+
await notifyDiscordActiveTurnThreadCreated({
89+
sessionKey,
90+
accountId: "account-1",
91+
sourceChannelId: "channel-1",
92+
sourceMessageId: "message-1",
93+
threadId: "thread-1",
94+
});
95+
96+
const result = await handleDiscordMessageAction({
97+
action: "upload-file",
98+
params: {
99+
to: "channel:thread-1",
100+
filePath: "/tmp/report.md",
101+
},
102+
cfg: discordConfig(),
103+
accountId: "account-1",
104+
sessionKey,
105+
});
106+
107+
expect(result.details).toEqual({
108+
ok: true,
109+
sourceReplyRoute: "current-source",
110+
});
111+
expect(onThreadReplyDelivered).toHaveBeenCalledWith("thread-1");
112+
} finally {
113+
endRoute();
114+
}
115+
});
116+
117+
it("keeps the source fallback eligible when a matching-thread send reports failure", async () => {
118+
const sessionKey = "agent:main:discord:channel:channel-1";
119+
const onThreadReplyDelivered = vi.fn();
120+
const endRoute = beginDiscordActiveTurnThreadRoute(sessionKey, {
121+
accountId: "account-1",
122+
sourceChannelId: "channel-1",
123+
sourceMessageId: "message-1",
124+
onThreadAdopted: vi.fn(),
125+
onThreadReplyDelivered,
126+
});
127+
try {
128+
await notifyDiscordActiveTurnThreadCreated({
129+
sessionKey,
130+
accountId: "account-1",
131+
sourceChannelId: "channel-1",
132+
sourceMessageId: "message-1",
133+
threadId: "thread-1",
134+
});
135+
handleDiscordActionMock.mockResolvedValueOnce({
136+
content: [],
137+
details: { ok: false, error: "delivery failed" },
138+
});
139+
140+
const result = await handleDiscordMessageAction({
141+
action: "send",
142+
params: {
143+
to: "channel:thread-1",
144+
message: "done",
145+
},
146+
cfg: discordConfig(),
147+
accountId: "account-1",
148+
sessionKey,
149+
});
150+
151+
expect(result.details).toEqual({ ok: false, error: "delivery failed" });
152+
expect(onThreadReplyDelivered).not.toHaveBeenCalled();
153+
} finally {
154+
endRoute();
155+
}
156+
});
157+
158+
it("preserves a successful send when route-only target parsing rejects the target", async () => {
159+
const result = await handleDiscordMessageAction({
160+
action: "send",
161+
params: {
162+
to: "@alice",
163+
message: "hello",
164+
},
165+
cfg: discordConfig(),
166+
});
167+
168+
expect(result.details).toEqual({ ok: true });
169+
});
170+
});

‎extensions/discord/src/actions/handle-action.ts‎

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import {
2929
buildDiscordInteractiveComponents,
3030
buildDiscordPresentationComponents,
3131
} from "../shared-interactive.js";
32-
import { resolveDiscordChannelId } from "../targets.js";
32+
import { parseDiscordTarget, resolveDiscordChannelId } from "../targets.js";
3333
import { tryHandleDiscordMessageActionGuildAdmin } from "./handle-action.guild-admin.js";
3434
import type { DiscordMessagingActionOptions } from "./runtime.messaging.shared.js";
3535
import { readDiscordAutoArchiveDurationParam } from "./runtime.shared.js";
@@ -111,6 +111,40 @@ export async function handleDiscordMessageAction(
111111
accountId,
112112
inboundEventKind: ctx.inboundEventKind,
113113
});
114+
const withAdoptedThreadReplyRoute = (
115+
result: AgentToolResult<unknown>,
116+
to: string,
117+
fallbackSessionKey?: string,
118+
) => {
119+
const details =
120+
result.details && typeof result.details === "object" && !Array.isArray(result.details)
121+
? (result.details as { ok?: unknown })
122+
: undefined;
123+
// Only a positive runtime receipt may suppress the source fallback. A
124+
// resolved failure must leave the turn eligible for visible error delivery.
125+
if (details?.ok !== true) {
126+
return result;
127+
}
128+
let target;
129+
try {
130+
target = parseDiscordTarget(to, { defaultKind: "channel" });
131+
} catch {
132+
// Route classification runs after delivery and must not turn a
133+
// successfully resolved Discord target into a failed tool result.
134+
return result;
135+
}
136+
if (
137+
target?.kind === "channel" &&
138+
notifyDiscordActiveTurnThreadReplyDelivered({
139+
sessionKey: ctx.sessionKey ?? fallbackSessionKey,
140+
accountId,
141+
threadId: target.id,
142+
})
143+
) {
144+
return withCurrentSourceReplyRoute(result);
145+
}
146+
return result;
147+
};
114148

115149
const readTarget = () => {
116150
const target =
@@ -215,7 +249,7 @@ export async function handleDiscordMessageAction(
215249
actionOptions,
216250
);
217251
notifyVisibleOutbound(to, sessionKey);
218-
return result;
252+
return withAdoptedThreadReplyRoute(result, to, sessionKey);
219253
}
220254

221255
if (action === "upload-file") {
@@ -254,7 +288,7 @@ export async function handleDiscordMessageAction(
254288
actionOptions,
255289
);
256290
notifyVisibleOutbound(to, sessionKey);
257-
return result;
291+
return withAdoptedThreadReplyRoute(result, to, sessionKey);
258292
}
259293

260294
if (action === "poll") {
@@ -480,15 +514,7 @@ export async function handleDiscordMessageAction(
480514
if (action === "thread-reply") {
481515
const threadId = readStringParam(params, "threadId") ?? readTarget();
482516
notifyVisibleOutbound(threadId);
483-
if (
484-
notifyDiscordActiveTurnThreadReplyDelivered({
485-
sessionKey: ctx.sessionKey,
486-
accountId,
487-
threadId,
488-
})
489-
) {
490-
return withCurrentSourceReplyRoute(adminResult);
491-
}
517+
return withAdoptedThreadReplyRoute(adminResult, threadId);
492518
}
493519
return adminResult;
494520
}

‎src/auto-reply/reply/agent-runner-result-payloads.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,10 +175,10 @@ export async function prepareReplyAgentPayloads(state: {
175175
});
176176
return recovery.kind === "diagnostic" ? recovery.payload : undefined;
177177
};
178-
// Route-aware message-tool delivery attests observed delivery in every mode:
179-
// an automatic-mode turn answered via the message tool plus NO_REPLY must not
180-
// draw the no-visible-reply fallback into the source conversation. The dedupe
181-
// route matcher keeps unrelated-target tool sends from counting as the reply.
178+
// Structured source-reply delivery evidence is the canonical owner for current
179+
// runtimes. The route matcher remains only for legacy results that recorded
180+
// successful target/text/media aggregates before structured receipts existed.
181+
// It still keeps unrelated-target tool sends from counting as the source reply.
182182
const sourceRoutedMessagingToolDelivery =
183183
completedSourceReplyDelivery ||
184184
((runResult.messagingToolSentTargets?.length ?? 0) > 0 &&

‎src/gateway/chat-display-projection.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,52 @@
11
import { describe, expect, it } from "vitest";
22
import { sanitizeChatHistoryMessages } from "./chat-display-projection.js";
3+
import { mirrorMessageToolVisibleReplies } from "./chat-display-projection.message-tool.js";
4+
5+
describe("chat display message-tool projection", () => {
6+
it("mirrors an automatic-mode send confirmed for the current source", () => {
7+
const sourceReply = "Visible reply delivered to Slack.";
8+
const projected = mirrorMessageToolVisibleReplies([
9+
{
10+
role: "assistant",
11+
content: [
12+
{
13+
type: "toolCall",
14+
id: "call-message-current-source",
15+
name: "message",
16+
arguments: {
17+
action: "send",
18+
channel: "slack",
19+
target: "channel:C123",
20+
message: sourceReply,
21+
},
22+
},
23+
],
24+
},
25+
{
26+
role: "toolResult",
27+
toolName: "message",
28+
toolCallId: "call-message-current-source",
29+
content: { ok: true, messageId: "slack-242" },
30+
details: {
31+
ok: true,
32+
messageId: "slack-242",
33+
sourceReplyRoute: "current-source",
34+
},
35+
},
36+
{ role: "assistant", content: [{ type: "text", text: "NO_REPLY" }] },
37+
]);
38+
39+
expect(projected).toContainEqual(
40+
expect.objectContaining({
41+
role: "assistant",
42+
content: [{ type: "text", text: sourceReply }],
43+
openclawMessageToolMirror: expect.objectContaining({
44+
toolCallId: "call-message-current-source",
45+
}),
46+
}),
47+
);
48+
});
49+
});
350

451
describe("chat display tool-result detail projection", () => {
552
it("keeps authoritative write booleans and strips unrelated details", () => {

‎src/infra/outbound/message-action-runner.core-send.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -660,6 +660,35 @@ describe("runMessageAction core send routing", () => {
660660
expect(result.payload).toMatchObject({ sourceReplyRoute: "current-source" });
661661
});
662662

663+
it("marks automatic-mode Slack sends to the trusted current source conversation", async () => {
664+
registerSlackTextPlugin();
665+
666+
const result = await runMessageAction({
667+
cfg: slackConfig,
668+
action: "send",
669+
params: {
670+
channel: "slack",
671+
target: "channel:C123",
672+
message: "visible source reply",
673+
},
674+
messageActionAuthorization: {
675+
requesterAccountId: "default",
676+
toolContext: {
677+
currentChannelProvider: "slack",
678+
currentChannelId: "channel:C123",
679+
currentSourceTurnId: "source-turn-1",
680+
},
681+
},
682+
sessionKey: "agent:main:slack:channel:C123",
683+
defaultAccountId: "default",
684+
sourceReplyDeliveryMode: "automatic",
685+
dryRun: false,
686+
});
687+
688+
expect(result.kind).toBe("send");
689+
expect(result.payload).toMatchObject({ sourceReplyRoute: "current-source" });
690+
});
691+
663692
it("does not mark a message-scoped reply that enters a new thread as current-source", async () => {
664693
registerSlackTextPlugin();
665694

‎src/infra/outbound/message-action-runner.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,9 @@ function markDeliveredCurrentSourceReply<T extends MessageActionRunResult>(
291291
replyToIsExplicit: boolean;
292292
},
293293
): T {
294-
if (result.kind !== "send" || params.input.sourceReplyDeliveryMode !== "message_tool_only") {
294+
// Current-source identity comes from the authorized route and delivery receipt,
295+
// not the reply mode; automatic runs also use this marker to avoid false fallbacks.
296+
if (result.kind !== "send") {
295297
return result;
296298
}
297299
const authorization = params.input.messageActionAuthorization;

0 commit comments

Comments
 (0)