Skip to content

Commit 11e897a

Browse files
steipetezheliu2
andauthored
fix(discord): preserve attachment content types (#114460)
Co-authored-by: Zhe Liu <[email protected]>
1 parent 5d98d2e commit 11e897a

8 files changed

Lines changed: 176 additions & 12 deletions

‎extensions/discord/src/internal/payload.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { Embed } from "./embeds.js";
55
export type MessagePayloadFile = {
66
name: string;
77
data: Blob | Uint8Array | ArrayBuffer;
8+
contentType?: string;
89
description?: string;
910
duration_secs?: number;
1011
waveform?: string;

‎extensions/discord/src/monitor/native-command-reply.test.ts‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
// Discord tests cover native command reply plugin behavior.
2-
import { describe, expect, it, vi } from "vitest";
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
33
import { Container, TextDisplay } from "../internal/discord.js";
4+
import { createDiscordLoopbackRest } from "../send.test-harness.js";
45
import {
56
deliverDiscordInteractionReply,
67
hasRenderableReplyPayload,
78
settleDiscordInteractionWithoutVisibleReply,
89
} from "./native-command-reply.js";
910

11+
const loadWebMediaMock = vi.hoisted(() => vi.fn());
12+
vi.mock("openclaw/plugin-sdk/web-media", () => ({
13+
loadWebMedia: loadWebMediaMock,
14+
}));
15+
1016
function createInteraction() {
1117
return {
1218
reply: vi.fn().mockResolvedValue({ ok: true }),
@@ -15,6 +21,10 @@ function createInteraction() {
1521
}
1622

1723
describe("deliverDiscordInteractionReply", () => {
24+
beforeEach(() => {
25+
loadWebMediaMock.mockReset();
26+
});
27+
1828
it("sends component-only native command replies as follow-ups", async () => {
1929
const interaction = createInteraction();
2030
const components = [new Container([new TextDisplay("Pick a model")])];
@@ -67,6 +77,45 @@ describe("deliverDiscordInteractionReply", () => {
6777
});
6878
expect(interaction.followUp).not.toHaveBeenCalled();
6979
});
80+
81+
it("sends the detected WebP media type across a real interaction multipart request", async () => {
82+
const loopback = await createDiscordLoopbackRest();
83+
loadWebMediaMock.mockResolvedValue({
84+
buffer: Buffer.from("webp"),
85+
fileName: "sticker.webp",
86+
contentType: "image/webp",
87+
kind: "image",
88+
});
89+
const interaction = {
90+
reply: vi.fn(async (data: unknown) =>
91+
loopback.rest.post("/interactions/123/token/callback", {
92+
body: { type: 4, data },
93+
}),
94+
),
95+
followUp: vi.fn(),
96+
};
97+
98+
try {
99+
await deliverDiscordInteractionReply({
100+
interaction: interaction as never,
101+
payload: {
102+
text: "sticker",
103+
mediaUrls: ["file:///tmp/sticker.webp"],
104+
},
105+
textLimit: 2000,
106+
preferFollowUp: false,
107+
chunkMode: "length",
108+
});
109+
110+
const upload = loopback.requests.find((request) => request.method === "POST");
111+
expect(upload?.path).toContain("/interactions/123/token/callback");
112+
expect(upload?.contentType).toMatch(/^multipart\/form-data; boundary=/);
113+
expect(upload?.body).toContain('name="files[0]"; filename="sticker.webp"');
114+
expect(upload?.body).toContain("Content-Type: image/webp");
115+
} finally {
116+
await loopback.close();
117+
}
118+
});
70119
});
71120

72121
describe("settleDiscordInteractionWithoutVisibleReply", () => {

‎extensions/discord/src/monitor/native-command-reply.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { chunkDiscordTextWithMode } from "../chunk.js";
1212
import type {
1313
ButtonInteraction,
1414
CommandInteraction,
15+
MessagePayloadFile,
1516
StringSelectMenuInteraction,
1617
TopLevelComponents,
1718
} from "../internal/discord.js";
@@ -106,7 +107,7 @@ export async function deliverDiscordInteractionReply(params: {
106107
let payloadDelivered = false;
107108
const sendMessage = async (
108109
content: string,
109-
files?: { name: string; data: Buffer }[],
110+
files?: MessagePayloadFile[],
110111
components?: TopLevelComponents[],
111112
) => {
112113
const contentPayload = content ? { content } : {};
@@ -118,13 +119,7 @@ export async function deliverDiscordInteractionReply(params: {
118119
...(params.responseEphemeral !== undefined
119120
? { ephemeral: params.responseEphemeral }
120121
: {}),
121-
files: files.map((file) => {
122-
if (file.data instanceof Blob) {
123-
return { name: file.name, data: file.data };
124-
}
125-
const arrayBuffer = Uint8Array.from(file.data).buffer;
126-
return { name: file.name, data: new Blob([arrayBuffer]) };
127-
}),
122+
files,
128123
}
129124
: {
130125
...contentPayload,
@@ -174,6 +169,7 @@ export async function deliverDiscordInteractionReply(params: {
174169
return {
175170
name: loaded.fileName ?? "upload",
176171
data: loaded.buffer,
172+
contentType: loaded.contentType,
177173
};
178174
}),
179175
);

‎extensions/discord/src/send.components.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Discord tests cover send.components plugin behavior.
22
import { ChannelType, MessageFlags } from "discord-api-types/v10";
33
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
4-
import { makeDiscordRest } from "./send.test-harness.js";
4+
import { createDiscordLoopbackRest, makeDiscordRest } from "./send.test-harness.js";
55

66
const loadConfigMock = vi.hoisted(() => vi.fn(() => ({ session: { dmScope: "main" } })));
77

@@ -52,6 +52,7 @@ function resetClassicMocks(): void {
5252
loadOutboundMediaFromUrlMock.mockResolvedValue({
5353
buffer: Buffer.from("media"),
5454
fileName: "report.pdf",
55+
contentType: "application/pdf",
5556
});
5657
vi.clearAllMocks();
5758
}
@@ -412,6 +413,36 @@ describe("sendDiscordComponentMessage classic message downgrade", () => {
412413
expect(modals[0]?.fields?.[0]?.label).toBe("Notes");
413414
});
414415

416+
it("sends the detected PDF media type across a real component multipart request", async () => {
417+
const loopback = await createDiscordLoopbackRest();
418+
try {
419+
await sendDiscordComponentMessage(
420+
"channel:789",
421+
{
422+
text: "report",
423+
modal: {
424+
title: "Feedback",
425+
fields: [{ type: "text", label: "Notes" }],
426+
},
427+
},
428+
{
429+
cfg: DISCORD_TEST_CFG,
430+
rest: loopback.rest,
431+
token: "test-token",
432+
mediaUrl: "https://example.com/report.pdf",
433+
},
434+
);
435+
436+
const upload = loopback.requests.find((request) => request.method === "POST");
437+
expect(upload?.path).toContain("/channels/789/messages");
438+
expect(upload?.contentType).toMatch(/^multipart\/form-data; boundary=/);
439+
expect(upload?.body).toContain('name="files[0]"; filename="report.pdf"');
440+
expect(upload?.body).toContain("Content-Type: application/pdf");
441+
} finally {
442+
await loopback.close();
443+
}
444+
});
445+
415446
it("treats bare numeric component send targets as channels", async () => {
416447
const { rest, postMock, getMock } = makeDiscordRest();
417448
getMock.mockResolvedValueOnce({

‎extensions/discord/src/send.components.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,7 @@ async function buildDiscordComponentPayload(params: {
220220
const filenameOverride = params.opts.filename?.trim();
221221
resolvedFileName = filenameOverride || media.fileName || "upload";
222222
spec = withImplicitComponentAttachmentBlock(spec, resolvedFileName);
223-
files = [{ data: media.buffer, name: resolvedFileName }];
223+
files = [{ data: media.buffer, name: resolvedFileName, contentType: media.contentType }];
224224
}
225225

226226
const attachmentNames = extractComponentAttachmentNames(spec);

‎extensions/discord/src/send.sends-basic-channel-messages.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import { ChannelType, MessageFlags, PermissionFlagsBits, Routes } from "discord-
33
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
44
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
55
import { Container, TextDisplay } from "./internal/discord.js";
6-
import { discordWebMediaMockFactory, makeDiscordRest } from "./send.test-harness.js";
6+
import {
7+
createDiscordLoopbackRest,
8+
discordWebMediaMockFactory,
9+
makeDiscordRest,
10+
} from "./send.test-harness.js";
711

812
vi.mock("openclaw/plugin-sdk/web-media", () => discordWebMediaMockFactory());
913

@@ -727,6 +731,26 @@ describe("sendMessageDiscord", () => {
727731
});
728732
});
729733

734+
it("sends the detected JPEG media type across a real loopback multipart request", async () => {
735+
const loopback = await createDiscordLoopbackRest();
736+
try {
737+
await sendMessageDiscord("channel:789", "photo", {
738+
rest: loopback.rest,
739+
token: "test-token",
740+
cfg: DISCORD_TEST_CFG,
741+
mediaUrl: "file:///tmp/photo.jpg",
742+
});
743+
744+
const upload = loopback.requests.find((request) => request.method === "POST");
745+
expect(upload?.path).toContain("/channels/789/messages");
746+
expect(upload?.contentType).toMatch(/^multipart\/form-data; boundary=/);
747+
expect(upload?.body).toContain('name="files[0]"; filename="photo.jpg"');
748+
expect(upload?.body).toContain("Content-Type: image/jpeg");
749+
} finally {
750+
await loopback.close();
751+
}
752+
});
753+
730754
it("preserves text when Discord rejects an upload with error 40005", async () => {
731755
const { rest, postMock } = makeDiscordRest();
732756
postMock

‎extensions/discord/src/send.shared.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,7 @@ async function sendDiscordMedia(params: DiscordMediaSendParams) {
466466
{
467467
data: media.buffer,
468468
name: resolvedFileName,
469+
contentType: media.contentType,
469470
},
470471
],
471472
});

‎extensions/discord/src/send.test-harness.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Discord plugin module implements send harness behavior.
2+
import { createServer } from "node:http";
23
import type { MockFn } from "openclaw/plugin-sdk/plugin-test-runtime";
34
import { vi } from "vitest";
5+
import { RequestClient } from "./internal/discord.js";
46

57
type DiscordWebMediaMockFactoryResult = {
68
loadWebMedia: MockFn;
@@ -16,6 +18,66 @@ type DiscordRestFactoryResult = {
1618
deleteMock: MockFn;
1719
};
1820

21+
type DiscordLoopbackRequest = {
22+
body: string;
23+
contentType: string | undefined;
24+
method: string | undefined;
25+
path: string | undefined;
26+
};
27+
28+
export async function createDiscordLoopbackRest(): Promise<{
29+
rest: RequestClient;
30+
requests: DiscordLoopbackRequest[];
31+
close: () => Promise<void>;
32+
}> {
33+
const requests: DiscordLoopbackRequest[] = [];
34+
const server = createServer((request, response) => {
35+
const chunks: Buffer[] = [];
36+
request.on("data", (chunk: Buffer) => chunks.push(chunk));
37+
request.on("error", (error) => response.destroy(error));
38+
request.on("end", () => {
39+
requests.push({
40+
body: Buffer.concat(chunks).toString("utf8"),
41+
contentType: request.headers["content-type"],
42+
method: request.method,
43+
path: request.url,
44+
});
45+
response.writeHead(200, { "Content-Type": "application/json" });
46+
response.end(
47+
JSON.stringify(
48+
request.method === "GET"
49+
? { id: "789", type: 0 }
50+
: { id: "loopback-message", channel_id: "789" },
51+
),
52+
);
53+
});
54+
});
55+
await new Promise<void>((resolve, reject) => {
56+
server.once("error", reject);
57+
server.listen(0, "127.0.0.1", () => {
58+
server.removeListener("error", reject);
59+
resolve();
60+
});
61+
});
62+
const address = server.address();
63+
if (!address || typeof address === "string") {
64+
server.close();
65+
throw new Error("Discord loopback server did not bind to a TCP port");
66+
}
67+
return {
68+
rest: new RequestClient("test-token", {
69+
baseUrl: `http://127.0.0.1:${address.port}`,
70+
queueRequests: false,
71+
}),
72+
requests,
73+
close: () =>
74+
new Promise<void>((resolve, reject) => {
75+
server.close((error) => (error ? reject(error) : resolve()));
76+
server.closeIdleConnections();
77+
}),
78+
};
79+
}
80+
1981
export function discordWebMediaMockFactory(): DiscordWebMediaMockFactoryResult {
2082
return {
2183
loadWebMedia: vi.fn().mockResolvedValue({

0 commit comments

Comments
 (0)