Skip to content

Commit 18224d2

Browse files
committed
fix(slack): retain original attachment identity through download
1 parent 5c1d39f commit 18224d2

4 files changed

Lines changed: 71 additions & 51 deletions

File tree

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

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1275,25 +1275,30 @@ describe("Slack message file intake", () => {
12751275
expect(result?.rawBody).toContain("FRICH.png (image/png, fileId: FRICH)");
12761276
});
12771277

1278-
it("reuses the exact preloaded voice-file object across forwarded duplicates", async () => {
1279-
const voice = file("FVOICE");
1280-
const preloaded = {
1281-
path: "/tmp/preloaded-voice.ogg",
1282-
contentType: "audio/ogg",
1283-
placeholder: "[Slack file: voice.ogg (fileId: FVOICE)]",
1284-
};
1278+
it.each(["direct", "forwarded"] as const)(
1279+
"reuses the exact preloaded %s voice-file object across forwarded duplicates",
1280+
async (source) => {
1281+
const voice = file("FVOICE");
1282+
const direct = source === "direct" ? voice : file(" FVOICE ");
1283+
const forwarded = source === "forwarded" ? voice : file("FVOICE");
1284+
const preloaded = {
1285+
path: "/tmp/preloaded-voice.ogg",
1286+
contentType: "audio/ogg",
1287+
placeholder: "[Slack file: voice.ogg (fileId: FVOICE)]",
1288+
};
12851289

1286-
const result = await resolveMessageFiles({
1287-
direct: [voice],
1288-
forwarded: [[file("FVOICE")]],
1289-
preloadedMedia: new Map([[voice, preloaded]]),
1290-
});
1290+
const result = await resolveMessageFiles({
1291+
direct: [direct],
1292+
forwarded: [[forwarded]],
1293+
preloadedMedia: new Map([[voice, preloaded]]),
1294+
});
12911295

1292-
expect(mockFetch).not.toHaveBeenCalled();
1293-
expect(result?.effectiveDirectMedia).toEqual([preloaded]);
1294-
expect(result?.effectiveDirectMedia?.[0]).toBe(preloaded);
1295-
expect(result?.rawBody.match(/fileId: FVOICE/g)).toHaveLength(1);
1296-
});
1296+
expect(mockFetch).not.toHaveBeenCalled();
1297+
expect(result?.effectiveDirectMedia).toEqual([preloaded]);
1298+
expect(result?.effectiveDirectMedia?.[0]).toBe(preloaded);
1299+
expect(result?.rawBody.match(/fileId: FVOICE/g)).toHaveLength(1);
1300+
},
1301+
);
12971302

12981303
it("keeps failed file identities beside renamed, overlapping, and ID-less downloads", async () => {
12991304
const downloaded = file("F11");
@@ -1322,17 +1327,18 @@ describe("Slack message file intake", () => {
13221327
[
13231328
downloadedWithoutId,
13241329
{
1325-
path: "/tmp/available.png",
1326-
fileName: "available.png",
1327-
placeholder: "[Slack file: available.png (image/png)]",
1330+
path: "/tmp/server-renamed.png",
1331+
fileName: "server-renamed.png",
1332+
placeholder: "[Slack file: server-renamed.png (image/png)]",
13281333
},
13291334
],
13301335
]),
13311336
});
13321337

13331338
expect(result?.effectiveDirectMedia).toHaveLength(2);
13341339
expect(result?.rawBody.match(/fileId: F11/g)).toHaveLength(1);
1335-
expect(result?.rawBody.match(/available\.png/g)).toHaveLength(2);
1340+
expect(result?.rawBody.match(/server-renamed\.png/g)).toHaveLength(1);
1341+
expect(result?.rawBody.match(/available\.png/g)).toHaveLength(1);
13361342
expect(result?.rawBody).toContain("missing-contract.pdf (application/pdf, fileId: F1)");
13371343
expect(result?.rawBody).toContain("missing.png (image/png)");
13381344
});

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

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,7 @@ export async function resolveSlackMedia(params: {
334334
totalTimeoutMs?: number;
335335
abortSignal?: AbortSignal;
336336
preloadedMedia?: ReadonlyMap<SlackFile, SlackMediaResult>;
337+
resolvedFiles?: Set<SlackFile>;
337338
}): Promise<SlackMediaResult[] | null> {
338339
const govSlack = isGovSlackClient(params.client);
339340
const files = params.files ?? [];
@@ -393,7 +394,12 @@ export async function resolveSlackMedia(params: {
393394
errorMode: "stop",
394395
throwOnError: true,
395396
});
396-
const resolved = results.filter((result): result is SlackMediaResult => result !== null);
397+
const resolved = results.filter((result, index): result is SlackMediaResult => {
398+
if (result) {
399+
params.resolvedFiles?.add(limitedFiles[index]!);
400+
}
401+
return result !== null;
402+
});
397403

398404
return resolved.length > 0 ? resolved : null;
399405
}
@@ -442,12 +448,17 @@ export async function resolveSlackAttachmentContent(params: {
442448
.slice(0, MAX_SLACK_MEDIA_FILES)
443449
.map((file) => {
444450
const fileId = normalizeOptionalString(file.id);
445-
if (
446-
!fileId ||
447-
params.preloadedMedia?.has(file) ||
448-
file.url_private_download ||
449-
file.url_private
450-
) {
451+
const preloaded =
452+
fileId &&
453+
candidates.find(
454+
(candidate) =>
455+
normalizeOptionalString(candidate.id) === fileId &&
456+
params.preloadedMedia?.has(candidate),
457+
);
458+
if (preloaded) {
459+
return preloaded;
460+
}
461+
if (!fileId || file.url_private_download || file.url_private) {
451462
return file;
452463
}
453464
const downloadable = candidates.find(
@@ -460,9 +471,11 @@ export async function resolveSlackAttachmentContent(params: {
460471
const pendingFiles = new Map<SlackFile | string, SlackFile>(
461472
allFiles.map((file) => [normalizeOptionalString(file.id) ?? file, file]),
462473
);
474+
const resolvedFiles = new Set<SlackFile>();
463475
const resolveFiles = (files?: SlackFile[]) =>
464476
resolveSlackMedia({
465477
...params,
478+
resolvedFiles,
466479
files: files?.flatMap((file) => {
467480
const key = normalizeOptionalString(file.id) ?? file;
468481
const selected = pendingFiles.get(key);
@@ -520,6 +533,7 @@ export async function resolveSlackAttachmentContent(params: {
520533
}
521534

522535
const allMedia = [...((await directMediaPromise) ?? []), ...attachmentMedia];
536+
const unavailableFiles = allFiles.filter((file) => !resolvedFiles.has(file));
523537
const combinedText = textBlocks.join("\n\n");
524538
if (
525539
!combinedText &&
@@ -533,6 +547,6 @@ export async function resolveSlackAttachmentContent(params: {
533547
text: combinedText,
534548
media: allMedia,
535549
unavailableImageCount,
536-
...(allFiles.length > 0 ? { files: allFiles } : {}),
550+
...(unavailableFiles.length > 0 ? { files: unavailableFiles } : {}),
537551
};
538552
}

‎extensions/slack/src/monitor/message-handler/prepare-content.ts‎

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -118,20 +118,7 @@ export async function resolveSlackMessageContent(params: {
118118
const effectiveDirectMedia = attachmentContent?.media.length ? attachmentContent.media : null;
119119
const mediaPlaceholder = effectiveDirectMedia?.map((item) => item.placeholder).join(" ");
120120

121-
const fallbackFiles = [...(attachmentContent?.files ?? [])];
122-
for (const { placeholder } of effectiveDirectMedia ?? []) {
123-
const match = fallbackFiles.findIndex((file) =>
124-
placeholder.includes(
125-
file.id?.trim()
126-
? `fileId: ${file.id.trim()})]`
127-
: `[Slack file: ${formatSlackFileReference(file)}]`,
128-
),
129-
);
130-
if (match >= 0) {
131-
fallbackFiles.splice(match, 1);
132-
}
133-
}
134-
const fileOnlyFallback = fallbackFiles.map(formatSlackFileReference).join(", ");
121+
const fileOnlyFallback = attachmentContent?.files?.map(formatSlackFileReference).join(", ");
135122

136123
let botAttachmentText: string | undefined;
137124
if (params.isBotMessage && !attachmentContent?.text) {

‎extensions/slack/src/monitor/message-handler/prepare.test.ts‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2101,13 +2101,18 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
21012101
it("keeps a failed file recoverable when a sibling download reaches the agent", async () => {
21022102
const originalFetch = globalThis.fetch;
21032103
globalThis.fetch = vi.fn(
2104-
async () =>
2104+
async (input: RequestInfo | URL) =>
21052105
new Response(Buffer.from("image contents"), {
21062106
status: 200,
2107-
headers: { "content-type": "image/png" },
2107+
headers: {
2108+
"content-type": "image/png",
2109+
...(typeof input === "string" && input.includes("original-name.png")
2110+
? { "content-disposition": 'attachment; filename="server-renamed.png"' }
2111+
: {}),
2112+
},
21082113
}),
21092114
) as typeof fetch;
2110-
let downloadedPath: string | undefined;
2115+
let downloadedPaths: string[] = [];
21112116

21122117
try {
21132118
const prepared = await prepareWithDefaultCtx(
@@ -2120,23 +2125,31 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
21202125
mimetype: "image/png",
21212126
url_private_download: "https://files.slack.com/available.png",
21222127
},
2128+
{
2129+
name: "original-name.png",
2130+
mimetype: "image/png",
2131+
url_private_download: "https://files.slack.com/original-name.png",
2132+
},
2133+
{ name: "original-name.png", mimetype: "image/png" },
21232134
{ id: "F1", name: "missing-contract.pdf", mimetype: "application/pdf" },
21242135
],
21252136
}),
21262137
);
21272138

21282139
assertPrepared(prepared);
2129-
downloadedPath = prepared.ctxPayload.media?.[0]?.path;
2130-
expect(prepared.ctxPayload.media).toHaveLength(1);
2140+
downloadedPaths = prepared.ctxPayload.media?.map((media) => media.path) ?? [];
2141+
expect(prepared.ctxPayload.media).toHaveLength(2);
21312142
expect(prepared.ctxPayload.RawBody).toContain("available.png (image/png, fileId: F11)");
2143+
expect(prepared.ctxPayload.RawBody).toContain("server-renamed.png (image/png)");
2144+
expect(prepared.ctxPayload.RawBody.match(/original-name\.png/g)).toHaveLength(1);
21322145
expect(prepared.ctxPayload.BodyForAgent).toContain(
21332146
"missing-contract.pdf (application/pdf, fileId: F1)",
21342147
);
21352148
} finally {
21362149
globalThis.fetch = originalFetch;
2137-
if (downloadedPath) {
2138-
await fs.rm(downloadedPath, { force: true });
2139-
}
2150+
await Promise.all(
2151+
downloadedPaths.map((downloadedPath) => fs.rm(downloadedPath, { force: true })),
2152+
);
21402153
}
21412154
});
21422155

0 commit comments

Comments
 (0)