Skip to content

Commit f7cbe9e

Browse files
authored
fix(slack): preserve partial reply delivery (#127130)
1 parent f14efd2 commit f7cbe9e

2 files changed

Lines changed: 232 additions & 54 deletions

File tree

‎extensions/slack/src/monitor/replies.test.ts‎

Lines changed: 179 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
// Slack tests cover replies plugin behavior.
2+
import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
3+
import { PlatformMessageNotDispatchedError } from "openclaw/plugin-sdk/error-runtime";
4+
import { createReplyDispatcher } from "openclaw/plugin-sdk/reply-runtime";
25
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
36

47
const sendMock = vi.fn();
@@ -72,6 +75,17 @@ function requireSendCall(index = 0) {
7275
return call;
7376
}
7477

78+
function acceptedSlackSendResult(messageId: string, kind: "media" | "text" = "media") {
79+
return {
80+
messageId,
81+
channelId: "C123",
82+
receipt: createMessageReceiptFromOutboundResults({
83+
results: [{ channel: "slack", messageId, channelId: "C123" }],
84+
kind,
85+
}),
86+
};
87+
}
88+
7589
type SlashTestMessage = {
7690
text: string;
7791
blocks?: Array<Record<string, unknown>>;
@@ -228,6 +242,7 @@ describe("deliverReplies identity passthrough", () => {
228242
mediaUrl: "https://example.com/report.png",
229243
threadTs: "thread-ts",
230244
accountId: "work",
245+
onDeliveryResult: expect.any(Function),
231246
eventScope,
232247
textLimit: 4000,
233248
mediaMaxBytes: 1024,
@@ -239,6 +254,7 @@ describe("deliverReplies identity passthrough", () => {
239254
token: "xoxb-test",
240255
threadTs: "thread-ts",
241256
accountId: "work",
257+
onDeliveryResult: expect.any(Function),
242258
eventScope,
243259
textLimit: 4000,
244260
mediaMaxBytes: 1024,
@@ -1211,11 +1227,19 @@ describe("deliverReplies message_sent hook", () => {
12111227

12121228
it("emits one message_sent event after a multi-media reply succeeds", async () => {
12131229
messageHookRunner.hasHooks.mockImplementation((name: string) => name === "message_sent");
1230+
const first = acceptedSlackSendResult("media-1");
1231+
const second = acceptedSlackSendResult("media-2");
12141232
sendMock
1215-
.mockResolvedValueOnce({ messageId: "media-1", channelId: "C123" })
1216-
.mockResolvedValueOnce({ messageId: "media-2", channelId: "C123" });
1233+
.mockImplementationOnce(async (_target, _text, options) => {
1234+
await options.onDeliveryResult?.(first);
1235+
return first;
1236+
})
1237+
.mockImplementationOnce(async (_target, _text, options) => {
1238+
await options.onDeliveryResult?.(second);
1239+
return second;
1240+
});
12171241

1218-
await deliverReplies(
1242+
const result = await deliverReplies(
12191243
baseParams({
12201244
replies: [
12211245
{
@@ -1226,6 +1250,7 @@ describe("deliverReplies message_sent hook", () => {
12261250
}),
12271251
);
12281252

1253+
expect(result).toBe(second);
12291254
expect(sendMock).toHaveBeenCalledTimes(2);
12301255
expect(messageHookRunner.runMessageSent).toHaveBeenCalledTimes(1);
12311256
const event = messageHookRunner.runMessageSent.mock.calls[0]?.[0] as Record<string, unknown>;
@@ -1312,22 +1337,44 @@ describe("deliverReplies message_sent hook", () => {
13121337

13131338
it("emits only failure when a later attachment in the payload fails", async () => {
13141339
messageHookRunner.hasHooks.mockImplementation((name: string) => name === "message_sent");
1340+
const accepted = acceptedSlackSendResult("media-1");
1341+
const failure = new PlatformMessageNotDispatchedError("second_upload_failed", {
1342+
cause: new Error("upload connection refused"),
1343+
});
13151344
sendMock
1316-
.mockResolvedValueOnce({ messageId: "media-1", channelId: "C123" })
1317-
.mockRejectedValueOnce(new Error("second_upload_failed"));
1345+
.mockImplementationOnce(async (_target, _text, options) => {
1346+
await options.onDeliveryResult?.(accepted);
1347+
return accepted;
1348+
})
1349+
.mockRejectedValueOnce(failure);
13181350

1319-
await expect(
1320-
deliverReplies(
1321-
baseParams({
1322-
replies: [
1323-
{
1324-
text: "two attachments",
1325-
mediaUrls: ["https://example.com/one.png", "https://example.com/two.png"],
1326-
},
1327-
],
1328-
}),
1329-
),
1330-
).rejects.toThrow(/second_upload_failed/);
1351+
const error = await deliverReplies(
1352+
baseParams({
1353+
replies: [
1354+
{
1355+
text: "two attachments",
1356+
mediaUrls: ["https://example.com/one.png", "https://example.com/two.png"],
1357+
},
1358+
],
1359+
}),
1360+
).catch((caught: unknown) => caught);
1361+
1362+
expect(error).toMatchObject({
1363+
code: "CHANNEL_PARTIAL_DELIVERY",
1364+
sentBeforeError: true,
1365+
visibleReplySent: true,
1366+
deliveryResult: {
1367+
messageIds: ["media-1"],
1368+
visibleReplySent: true,
1369+
receipt: {
1370+
primaryPlatformMessageId: "media-1",
1371+
platformMessageIds: ["media-1"],
1372+
parts: [{ platformMessageId: "media-1", kind: "media", index: 0 }],
1373+
},
1374+
},
1375+
});
1376+
expect((error as Error).cause).toBe(failure);
1377+
expect(sendMock).toHaveBeenCalledTimes(2);
13311378

13321379
expect(messageHookRunner.runMessageSent).toHaveBeenCalledTimes(1);
13331380
const event = messageHookRunner.runMessageSent.mock.calls[0]?.[0] as Record<string, unknown>;
@@ -1337,6 +1384,121 @@ describe("deliverReplies message_sent hook", () => {
13371384
});
13381385
});
13391386

1387+
it("preserves an accepted internal chunk when the same Slack send later fails", async () => {
1388+
const accepted = acceptedSlackSendResult("chunk-1", "text");
1389+
const failure = new PlatformMessageNotDispatchedError("second_chunk_failed", {
1390+
cause: new Error("upload connection refused"),
1391+
});
1392+
sendMock.mockImplementationOnce(async (_target, _text, options) => {
1393+
await options.onDeliveryResult?.(accepted);
1394+
throw failure;
1395+
});
1396+
1397+
const error = await deliverReplies(baseParams({ replies: [{ text: "chunked reply" }] })).catch(
1398+
(caught: unknown) => caught,
1399+
);
1400+
1401+
expect(error).toMatchObject({
1402+
code: "CHANNEL_PARTIAL_DELIVERY",
1403+
deliveryResult: {
1404+
messageIds: ["chunk-1"],
1405+
receipt: { platformMessageIds: ["chunk-1"] },
1406+
visibleReplySent: true,
1407+
},
1408+
});
1409+
expect((error as Error).cause).toBe(failure);
1410+
expect(sendMock).toHaveBeenCalledOnce();
1411+
});
1412+
1413+
it("preserves an undispatched first-send failure without a partial wrapper", async () => {
1414+
const failure = new PlatformMessageNotDispatchedError("first_upload_failed", {
1415+
cause: new Error("upload connection refused"),
1416+
});
1417+
sendMock.mockRejectedValueOnce(failure);
1418+
1419+
await expect(
1420+
deliverReplies(
1421+
baseParams({
1422+
replies: [{ text: "one attachment", mediaUrls: ["https://example.com/one.png"] }],
1423+
}),
1424+
),
1425+
).rejects.toBe(failure);
1426+
expect(sendMock).toHaveBeenCalledOnce();
1427+
});
1428+
1429+
it("does not carry accepted receipts into the next logical reply", async () => {
1430+
const accepted = acceptedSlackSendResult("reply-1", "text");
1431+
const failure = new PlatformMessageNotDispatchedError("next_reply_failed", {
1432+
cause: new Error("upload connection refused"),
1433+
});
1434+
sendMock
1435+
.mockImplementationOnce(async (_target, _text, options) => {
1436+
await options.onDeliveryResult?.(accepted);
1437+
return accepted;
1438+
})
1439+
.mockRejectedValueOnce(failure);
1440+
1441+
await expect(
1442+
deliverReplies(baseParams({ replies: [{ text: "accepted" }, { text: "never sent" }] })),
1443+
).rejects.toBe(failure);
1444+
expect(sendMock).toHaveBeenCalledTimes(2);
1445+
});
1446+
1447+
it("settles real Slack transport chunks as visible failure without replaying the turn", async () => {
1448+
const failure = new PlatformMessageNotDispatchedError("third_chunk_failed", {
1449+
cause: new Error("upload connection refused"),
1450+
});
1451+
const postMessage = vi
1452+
.fn()
1453+
.mockResolvedValueOnce({ ok: true, ts: "chunk-1", channel: "C123" })
1454+
.mockResolvedValueOnce({ ok: true, ts: "chunk-2", channel: "C123" })
1455+
.mockRejectedValueOnce(failure);
1456+
const { sendMessageSlack } = await vi.importActual<typeof import("../send.js")>("../send.js");
1457+
sendMock.mockImplementationOnce(async (target, text, options) => {
1458+
return await sendMessageSlack(target, text, options);
1459+
});
1460+
const onError = vi.fn();
1461+
const dispatcher = createReplyDispatcher({
1462+
deliver: async (payload) =>
1463+
await deliverReplies(
1464+
baseParams({
1465+
replies: [payload],
1466+
eventScope: { teamId: "T123", client: { chat: { postMessage } } },
1467+
}),
1468+
),
1469+
onError,
1470+
propagateRetryableNoSendFailure: true,
1471+
});
1472+
1473+
expect(dispatcher.sendFinalReply({ text: "a".repeat(9_000) })).toBe(true);
1474+
dispatcher.markComplete();
1475+
const receipt = await dispatcher.waitForIdle();
1476+
1477+
expect(receipt).toMatchObject({
1478+
counts: { final: { failedBeforeSend: 0, failedAfterSend: 1 } },
1479+
anyVisibleDelivered: true,
1480+
});
1481+
expect(onError).toHaveBeenCalledOnce();
1482+
const deliveryError = onError.mock.calls[0]?.[0] as Error;
1483+
expect(deliveryError).toMatchObject({
1484+
code: "CHANNEL_PARTIAL_DELIVERY",
1485+
deliveryResult: {
1486+
messageIds: ["chunk-1", "chunk-2"],
1487+
receipt: {
1488+
primaryPlatformMessageId: "chunk-1",
1489+
platformMessageIds: ["chunk-1", "chunk-2"],
1490+
parts: [
1491+
{ platformMessageId: "chunk-1", kind: "text" },
1492+
{ platformMessageId: "chunk-2", kind: "text" },
1493+
],
1494+
},
1495+
},
1496+
});
1497+
expect(deliveryError.cause).toBe(failure);
1498+
expect(sendMock).toHaveBeenCalledOnce();
1499+
expect(postMessage).toHaveBeenCalledTimes(3);
1500+
});
1501+
13401502
it("does not emit the plugin hook when no listener observes message_sent", async () => {
13411503
messageHookRunner.hasHooks.mockReturnValue(false);
13421504
sendMock.mockResolvedValue({ messageId: "ts", channelId: "C123" });

‎extensions/slack/src/monitor/replies.ts‎

Lines changed: 53 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type { MessageMetadata } from "@slack/types";
33
import type { Block, KnownBlock } from "@slack/web-api";
44
import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
5+
import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
56
import type { MarkdownTableMode, OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
67
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
78
import {
@@ -146,42 +147,6 @@ export async function deliverReplies(params: {
146147
eventScope?: SlackEventScope;
147148
}) {
148149
let latestResult: SlackSendResult | undefined;
149-
const sendReply = async (input: {
150-
text: string;
151-
threadTs?: string | undefined;
152-
mediaUrl?: string | undefined;
153-
blocks?: (Block | KnownBlock)[] | undefined;
154-
authoredTextPlacement?: "none" | "blocks" | "outside-blocks";
155-
nativeDataFallbackBaseText?: string;
156-
textIsSlackMrkdwn?: boolean;
157-
textIsSlackPlainText?: boolean;
158-
}): Promise<SlackSendResult> => {
159-
return await sendMessageSlack(params.target, input.text, {
160-
cfg: params.cfg,
161-
token: params.token,
162-
threadTs: input.threadTs,
163-
accountId: params.accountId,
164-
...(input.mediaUrl ? { mediaUrl: input.mediaUrl } : {}),
165-
...(input.blocks ? { blocks: input.blocks } : {}),
166-
...(input.authoredTextPlacement
167-
? { authoredTextPlacement: input.authoredTextPlacement }
168-
: {}),
169-
...(Object.hasOwn(input, "nativeDataFallbackBaseText")
170-
? { nativeDataFallbackBaseText: input.nativeDataFallbackBaseText }
171-
: {}),
172-
...(input.textIsSlackMrkdwn ? { textIsSlackMrkdwn: true } : {}),
173-
...(input.textIsSlackPlainText ? { textIsSlackPlainText: true } : {}),
174-
...(params.eventScope
175-
? {
176-
eventScope: params.eventScope,
177-
textLimit: params.textLimit,
178-
...(params.mediaMaxBytes !== undefined ? { mediaMaxBytes: params.mediaMaxBytes } : {}),
179-
}
180-
: {}),
181-
...(params.identity ? { identity: params.identity } : {}),
182-
...(params.metadata ? { metadata: params.metadata } : {}),
183-
});
184-
};
185150
for (const payload of params.replies) {
186151
if (payload.isReasoning === true) {
187152
continue;
@@ -204,6 +169,49 @@ export async function deliverReplies(params: {
204169
continue;
205170
}
206171

172+
const acceptedResults: SlackSendResult[] = [];
173+
const sendReply = async (input: {
174+
text: string;
175+
threadTs?: string | undefined;
176+
mediaUrl?: string | undefined;
177+
blocks?: (Block | KnownBlock)[] | undefined;
178+
authoredTextPlacement?: "none" | "blocks" | "outside-blocks";
179+
nativeDataFallbackBaseText?: string;
180+
textIsSlackMrkdwn?: boolean;
181+
textIsSlackPlainText?: boolean;
182+
}): Promise<SlackSendResult> => {
183+
return await sendMessageSlack(params.target, input.text, {
184+
cfg: params.cfg,
185+
token: params.token,
186+
threadTs: input.threadTs,
187+
accountId: params.accountId,
188+
onDeliveryResult: (result) => {
189+
acceptedResults.push(result);
190+
},
191+
...(input.mediaUrl ? { mediaUrl: input.mediaUrl } : {}),
192+
...(input.blocks ? { blocks: input.blocks } : {}),
193+
...(input.authoredTextPlacement
194+
? { authoredTextPlacement: input.authoredTextPlacement }
195+
: {}),
196+
...(Object.hasOwn(input, "nativeDataFallbackBaseText")
197+
? { nativeDataFallbackBaseText: input.nativeDataFallbackBaseText }
198+
: {}),
199+
...(input.textIsSlackMrkdwn ? { textIsSlackMrkdwn: true } : {}),
200+
...(input.textIsSlackPlainText ? { textIsSlackPlainText: true } : {}),
201+
...(params.eventScope
202+
? {
203+
eventScope: params.eventScope,
204+
textLimit: params.textLimit,
205+
...(params.mediaMaxBytes !== undefined
206+
? { mediaMaxBytes: params.mediaMaxBytes }
207+
: {}),
208+
}
209+
: {}),
210+
...(params.identity ? { identity: params.identity } : {}),
211+
...(params.metadata ? { metadata: params.metadata } : {}),
212+
});
213+
};
214+
207215
// Fire the `message_sent` hook(s) after delivery, mirroring Telegram's
208216
// `emitMessageSentHooks` in `extensions/telegram/src/bot/delivery.replies.ts`.
209217
// `emitSlackMessageSentHooks` self-gates on registered listeners, so this is
@@ -309,7 +317,15 @@ export async function deliverReplies(params: {
309317
} catch (error) {
310318
const hookContent = hookParts.join("\n\n") || textRaw || spokenText || "";
311319
emitFailed(hookContent, error);
312-
throw error;
320+
if (acceptedResults.length === 0) {
321+
throw error;
322+
}
323+
const receipt = createMessageReceiptFromOutboundResults({ results: acceptedResults });
324+
throw createChannelPartialDeliveryError(error, {
325+
messageIds: receipt.platformMessageIds,
326+
receipt,
327+
visibleReplySent: true,
328+
});
313329
}
314330
if (delivered) {
315331
const hookContent = hookParts.join("\n\n") || textRaw || spokenText || "";

0 commit comments

Comments
 (0)