Skip to content

Commit 329ed12

Browse files
fix(discord): chunk long thread initial messages (#117354)
Discord rejected over-limit starter messages and could leave ordinary threads empty after creation. Split initial content through the existing Discord chunking and nonce-retry path while preserving confirmed-versus-ambiguous partial-delivery results. Co-authored-by: zhang-guiping <[email protected]>
1 parent 6ad5d11 commit 329ed12

4 files changed

Lines changed: 462 additions & 20 deletions

File tree

‎extensions/discord/src/actions/runtime.messaging.send.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,12 +351,14 @@ export async function handleDiscordMessageSendAction(ctx: DiscordMessagingAction
351351
return jsonResult({ ok: true, thread });
352352
} catch (error) {
353353
if (error instanceof DiscordThreadInitialMessageError) {
354+
const initialMessageDelivery = error.initialMessageDelivery;
354355
return jsonResult({
355356
ok: true,
356357
partial: true,
357358
thread: error.thread,
358-
warning: "Discord thread was created, but sending the initial message failed.",
359+
warning: `${error.initialMessageWarning}.`,
359360
initialMessageError: error.initialMessageError,
361+
...(initialMessageDelivery ? { initialMessageDelivery } : {}),
360362
});
361363
}
362364
throw error;

‎extensions/discord/src/actions/runtime.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2527,6 +2527,95 @@ describe("handleDiscordMessagingAction", () => {
25272527
initialMessageError: "missing access",
25282528
});
25292529
});
2530+
2531+
it("returns delivery progress when Discord only delivers part of the initial content", async () => {
2532+
const thread = { id: "T1", name: "thread", type: 11 };
2533+
createThreadDiscord.mockRejectedValueOnce(
2534+
new DiscordThreadInitialMessageError(
2535+
thread as ConstructorParameters<typeof DiscordThreadInitialMessageError>[0],
2536+
new Error("missing access"),
2537+
{
2538+
starterMessageDelivered: true,
2539+
deliveredChunkCount: 1,
2540+
deliveredMessageIds: ["starter1"],
2541+
failedChunkDelivery: "unknown",
2542+
failedChunkIndex: 1,
2543+
totalChunkCount: 2,
2544+
},
2545+
),
2546+
);
2547+
2548+
const result = await handleMessagingAction(
2549+
"threadCreate",
2550+
{
2551+
channelId: "C1",
2552+
name: "thread",
2553+
content: "Initial post",
2554+
},
2555+
enableAllActions,
2556+
);
2557+
2558+
expect(result.details).toEqual({
2559+
ok: true,
2560+
partial: true,
2561+
thread,
2562+
warning:
2563+
"Discord thread was created, but delivery of the remaining initial content could not be confirmed.",
2564+
initialMessageError: "missing access",
2565+
initialMessageDelivery: {
2566+
starterMessageDelivered: true,
2567+
deliveredChunkCount: 1,
2568+
deliveredMessageIds: ["starter1"],
2569+
failedChunkDelivery: "unknown",
2570+
failedChunkIndex: 1,
2571+
totalChunkCount: 2,
2572+
},
2573+
});
2574+
});
2575+
2576+
it("reports unconfirmed delivery when the first initial content chunk is ambiguous", async () => {
2577+
const thread = { id: "T1", name: "thread", type: 11 };
2578+
createThreadDiscord.mockRejectedValueOnce(
2579+
new DiscordThreadInitialMessageError(
2580+
thread as ConstructorParameters<typeof DiscordThreadInitialMessageError>[0],
2581+
new Error("response lost"),
2582+
{
2583+
starterMessageDelivered: false,
2584+
deliveredChunkCount: 0,
2585+
deliveredMessageIds: [],
2586+
failedChunkDelivery: "unknown",
2587+
failedChunkIndex: 0,
2588+
totalChunkCount: 1,
2589+
},
2590+
),
2591+
);
2592+
2593+
const result = await handleMessagingAction(
2594+
"threadCreate",
2595+
{
2596+
channelId: "C1",
2597+
name: "thread",
2598+
content: "Initial post",
2599+
},
2600+
enableAllActions,
2601+
);
2602+
2603+
expect(result.details).toEqual({
2604+
ok: true,
2605+
partial: true,
2606+
thread,
2607+
warning: "Discord thread was created, but initial message delivery could not be confirmed.",
2608+
initialMessageError: "response lost",
2609+
initialMessageDelivery: {
2610+
starterMessageDelivered: false,
2611+
deliveredChunkCount: 0,
2612+
deliveredMessageIds: [],
2613+
failedChunkDelivery: "unknown",
2614+
failedChunkIndex: 0,
2615+
totalChunkCount: 1,
2616+
},
2617+
});
2618+
});
25302619
});
25312620

25322621
describe("handleDiscordGuildAction", () => {

‎extensions/discord/src/send.creates-thread.test.ts‎

Lines changed: 244 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
44
import { loadWebMediaRaw } from "openclaw/plugin-sdk/web-media";
55
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
66
import { RateLimitError } from "./internal/discord.js";
7+
import { hasDiscordMessageCreateAmbiguity } from "./retry.js";
78
import { makeDiscordRest } from "./send.test-harness.js";
89

910
vi.mock("openclaw/plugin-sdk/web-media", async () => {
@@ -302,6 +303,110 @@ describe("sendMessageDiscord", () => {
302303
});
303304
});
304305

306+
it("keeps forum starter messages within Discord's content limit", async () => {
307+
const { rest, getMock, postMock } = makeDiscordRest();
308+
getMock.mockResolvedValue({ type: ChannelType.GuildForum });
309+
postMock.mockResolvedValue({ id: "t1" });
310+
const content = "a".repeat(2001);
311+
312+
await createThreadDiscord("chan1", { name: "thread", content }, discordClientOpts(rest));
313+
314+
expect(postMock).toHaveBeenCalledTimes(2);
315+
expect(requestBody(postMock as unknown as MockCallSource, 0)).toEqual({
316+
name: "thread",
317+
message: { content: "a".repeat(2000) },
318+
});
319+
expect(requestPath(postMock as unknown as MockCallSource, 1)).toBe(
320+
Routes.channelMessages("t1"),
321+
);
322+
expect(requestBody(postMock as unknown as MockCallSource, 1)).toMatchObject({
323+
content: "a",
324+
enforce_nonce: true,
325+
});
326+
});
327+
328+
it("keeps sub-limit multi-line forum content in one starter message", async () => {
329+
const { rest, getMock, postMock } = makeDiscordRest();
330+
getMock.mockResolvedValue({ type: ChannelType.GuildForum });
331+
postMock.mockResolvedValue({ id: "t1" });
332+
const content = Array.from({ length: 18 }, (_, index) => `line ${index + 1}`).join("\n");
333+
334+
await createThreadDiscord("chan1", { name: "thread", content }, discordClientOpts(rest));
335+
336+
expect(postMock).toHaveBeenCalledTimes(1);
337+
expect(requestBody(postMock as unknown as MockCallSource)).toEqual({
338+
name: "thread",
339+
message: { content },
340+
});
341+
});
342+
343+
it("reports a delivered forum starter when a continuation chunk fails", async () => {
344+
const { rest, getMock, postMock } = makeDiscordRest();
345+
getMock.mockResolvedValue({ type: ChannelType.GuildForum });
346+
postMock
347+
.mockResolvedValueOnce({ id: "t1", message: { id: "starter1", channel_id: "t1" } })
348+
.mockRejectedValueOnce(Object.assign(new Error("missing access"), { status: 403 }));
349+
350+
let thrown: unknown;
351+
try {
352+
await createThreadDiscord(
353+
"chan1",
354+
{ name: "thread", content: "a".repeat(2001) },
355+
discordClientOpts(rest),
356+
);
357+
} catch (error) {
358+
thrown = error;
359+
}
360+
361+
expect(thrown).toBeInstanceOf(DiscordThreadInitialMessageError);
362+
expect(requireRecord(thrown, "thread initial message error").initialMessageDelivery).toEqual({
363+
starterMessageDelivered: true,
364+
deliveredChunkCount: 1,
365+
deliveredMessageIds: ["starter1"],
366+
failedChunkDelivery: "not_delivered",
367+
failedChunkIndex: 1,
368+
totalChunkCount: 2,
369+
});
370+
});
371+
372+
it("reports an exhausted ambiguous forum continuation as unknown delivery", async () => {
373+
const { rest, getMock, postMock } = makeDiscordRest();
374+
getMock.mockResolvedValue({ type: ChannelType.GuildForum });
375+
const ambiguous = Object.assign(new Error("response lost"), { status: 502 });
376+
postMock
377+
.mockResolvedValueOnce({ id: "t1", message: { id: "starter1", channel_id: "t1" } })
378+
.mockRejectedValue(ambiguous);
379+
380+
let thrown: unknown;
381+
try {
382+
await createThreadDiscord(
383+
"chan1",
384+
{ name: "thread", content: "a".repeat(2001) },
385+
{
386+
...discordClientOpts(rest),
387+
retry: { attempts: 2, minDelayMs: 0, maxDelayMs: 0, jitter: 0 },
388+
},
389+
);
390+
} catch (error) {
391+
thrown = error;
392+
}
393+
394+
expect(postMock).toHaveBeenCalledTimes(3);
395+
expect(thrown).toBeInstanceOf(DiscordThreadInitialMessageError);
396+
expect(hasDiscordMessageCreateAmbiguity(thrown)).toBe(true);
397+
expect(requireRecord(thrown, "thread initial message error").message).toContain(
398+
"delivery of the remaining initial content could not be confirmed",
399+
);
400+
expect(requireRecord(thrown, "thread initial message error").initialMessageDelivery).toEqual({
401+
starterMessageDelivered: true,
402+
deliveredChunkCount: 1,
403+
deliveredMessageIds: ["starter1"],
404+
failedChunkDelivery: "unknown",
405+
failedChunkIndex: 1,
406+
totalChunkCount: 2,
407+
});
408+
});
409+
305410
it("inherits default_auto_archive_duration for forum threads", async () => {
306411
const { rest, getMock, postMock } = makeDiscordRest();
307412
getMock.mockResolvedValue({
@@ -457,11 +562,146 @@ describe("sendMessageDiscord", () => {
457562
expect(requestPath(postMock as unknown as MockCallSource, 1)).toBe(
458563
Routes.channelMessages("t1"),
459564
);
460-
expect(requestBody(postMock as unknown as MockCallSource, 1)).toEqual({
565+
expect(requestBody(postMock as unknown as MockCallSource, 1)).toMatchObject({
461566
content: "Hello thread!",
567+
enforce_nonce: true,
568+
});
569+
});
570+
571+
it("chunks long initial messages for non-forum threads", async () => {
572+
const { rest, getMock, postMock } = makeDiscordRest();
573+
getMock.mockResolvedValue({ type: ChannelType.GuildText });
574+
postMock.mockResolvedValue({ id: "t1" });
575+
const content = "a".repeat(2001);
576+
577+
await createThreadDiscord("chan1", { name: "thread", content }, discordClientOpts(rest));
578+
579+
expect(postMock).toHaveBeenCalledTimes(3);
580+
expect(requestPath(postMock as unknown as MockCallSource, 1)).toBe(
581+
Routes.channelMessages("t1"),
582+
);
583+
expect(requestBody(postMock as unknown as MockCallSource, 1)).toMatchObject({
584+
content: "a".repeat(2000),
585+
enforce_nonce: true,
586+
});
587+
expect(requestPath(postMock as unknown as MockCallSource, 2)).toBe(
588+
Routes.channelMessages("t1"),
589+
);
590+
expect(requestBody(postMock as unknown as MockCallSource, 2)).toMatchObject({
591+
content: "a",
592+
enforce_nonce: true,
593+
});
594+
});
595+
596+
it("keeps sub-limit multi-line non-forum content in one initial message", async () => {
597+
const { rest, getMock, postMock } = makeDiscordRest();
598+
getMock.mockResolvedValue({ type: ChannelType.GuildText });
599+
postMock.mockResolvedValue({ id: "t1", channel_id: "t1" });
600+
const content = Array.from({ length: 18 }, (_, index) => `line ${index + 1}`).join("\n");
601+
602+
await createThreadDiscord("chan1", { name: "thread", content }, discordClientOpts(rest));
603+
604+
expect(postMock).toHaveBeenCalledTimes(2);
605+
expect(requestBody(postMock as unknown as MockCallSource, 1)).toMatchObject({ content });
606+
});
607+
608+
it("reports delivered non-forum chunks when a later chunk fails", async () => {
609+
const { rest, getMock, postMock } = makeDiscordRest();
610+
getMock.mockResolvedValue({ type: ChannelType.GuildText });
611+
postMock
612+
.mockResolvedValueOnce({ id: "t1", name: "thread", type: ChannelType.PublicThread })
613+
.mockResolvedValueOnce({ id: "msg1", channel_id: "t1" })
614+
.mockRejectedValueOnce(Object.assign(new Error("missing access"), { status: 403 }));
615+
616+
let thrown: unknown;
617+
try {
618+
await createThreadDiscord(
619+
"chan1",
620+
{ name: "thread", content: "a".repeat(4001) },
621+
discordClientOpts(rest),
622+
);
623+
} catch (error) {
624+
thrown = error;
625+
}
626+
627+
expect(thrown).toBeInstanceOf(DiscordThreadInitialMessageError);
628+
expect(requireRecord(thrown, "thread initial message error").initialMessageDelivery).toEqual({
629+
starterMessageDelivered: false,
630+
deliveredChunkCount: 1,
631+
deliveredMessageIds: ["msg1"],
632+
failedChunkDelivery: "not_delivered",
633+
failedChunkIndex: 1,
634+
totalChunkCount: 3,
462635
});
463636
});
464637

638+
it("reports an exhausted ambiguous non-forum chunk as unknown delivery", async () => {
639+
const { rest, getMock, postMock } = makeDiscordRest();
640+
getMock.mockResolvedValue({ type: ChannelType.GuildText });
641+
const ambiguous = Object.assign(new Error("response lost"), { status: 502 });
642+
postMock
643+
.mockResolvedValueOnce({ id: "t1", name: "thread", type: ChannelType.PublicThread })
644+
.mockResolvedValueOnce({ id: "msg1", channel_id: "t1" })
645+
.mockRejectedValue(ambiguous);
646+
647+
let thrown: unknown;
648+
try {
649+
await createThreadDiscord(
650+
"chan1",
651+
{ name: "thread", content: "a".repeat(4001) },
652+
{
653+
...discordClientOpts(rest),
654+
retry: { attempts: 2, minDelayMs: 0, maxDelayMs: 0, jitter: 0 },
655+
},
656+
);
657+
} catch (error) {
658+
thrown = error;
659+
}
660+
661+
expect(postMock).toHaveBeenCalledTimes(4);
662+
expect(thrown).toBeInstanceOf(DiscordThreadInitialMessageError);
663+
expect(hasDiscordMessageCreateAmbiguity(thrown)).toBe(true);
664+
expect(requireRecord(thrown, "thread initial message error").message).toContain(
665+
"delivery of the remaining initial content could not be confirmed",
666+
);
667+
expect(requireRecord(thrown, "thread initial message error").initialMessageDelivery).toEqual({
668+
starterMessageDelivered: false,
669+
deliveredChunkCount: 1,
670+
deliveredMessageIds: ["msg1"],
671+
failedChunkDelivery: "unknown",
672+
failedChunkIndex: 1,
673+
totalChunkCount: 3,
674+
});
675+
});
676+
677+
it("retries continuation sends with a stable nonce per chunk", async () => {
678+
const { rest, getMock, postMock } = makeDiscordRest();
679+
getMock.mockResolvedValue({ type: ChannelType.GuildText });
680+
postMock
681+
.mockResolvedValueOnce({ id: "t1", name: "thread", type: ChannelType.PublicThread })
682+
.mockRejectedValueOnce(Object.assign(new Error("bad gateway"), { status: 502 }))
683+
.mockResolvedValueOnce({ id: "msg1", channel_id: "t1" })
684+
.mockResolvedValueOnce({ id: "msg2", channel_id: "t1" });
685+
686+
await createThreadDiscord(
687+
"chan1",
688+
{ name: "thread", content: "a".repeat(2001) },
689+
{
690+
...discordClientOpts(rest),
691+
retry: { attempts: 2, minDelayMs: 0, maxDelayMs: 0, jitter: 0 },
692+
},
693+
);
694+
695+
expect(postMock).toHaveBeenCalledTimes(4);
696+
const firstAttempt = requestBody(postMock as unknown as MockCallSource, 1);
697+
const retryAttempt = requestBody(postMock as unknown as MockCallSource, 2);
698+
const nextChunk = requestBody(postMock as unknown as MockCallSource, 3);
699+
expect(firstAttempt.enforce_nonce).toBe(true);
700+
expect(retryAttempt.nonce).toBe(firstAttempt.nonce);
701+
expect(nextChunk.enforce_nonce).toBe(true);
702+
expect(nextChunk.nonce).not.toBe(firstAttempt.nonce);
703+
});
704+
465705
it("keeps created non-forum thread details when initial message send fails", async () => {
466706
const { rest, getMock, postMock } = makeDiscordRest();
467707
getMock.mockResolvedValue({ type: ChannelType.GuildText });
@@ -483,6 +723,7 @@ describe("sendMessageDiscord", () => {
483723
expect(thrown).toBeInstanceOf(DiscordThreadInitialMessageError);
484724
const error = requireRecord(thrown, "thread initial message error");
485725
expect(error.name).toBe("DiscordThreadInitialMessageError");
726+
expect(error.message).toContain("initial message delivery could not be confirmed");
486727
expect(error.initialMessageError).toBe("missing access");
487728
expect(error.thread).toEqual({ id: "t1", name: "thread", type: ChannelType.PublicThread });
488729
});
@@ -507,8 +748,9 @@ describe("sendMessageDiscord", () => {
507748
expect(requestPath(postMock as unknown as MockCallSource, 1)).toBe(
508749
Routes.channelMessages("t1"),
509750
);
510-
expect(requestBody(postMock as unknown as MockCallSource, 1)).toEqual({
751+
expect(requestBody(postMock as unknown as MockCallSource, 1)).toMatchObject({
511752
content: "Discussion here",
753+
enforce_nonce: true,
512754
});
513755
});
514756

0 commit comments

Comments
 (0)