Skip to content

Commit 8c20318

Browse files
authored
fix(slack): retain unavailable attachments alongside downloads (#129708)
* fix(slack): retain unavailable attachments alongside downloads * fix(slack): retain original attachment identity through download * test(slack): narrow optional attachment regression types
1 parent da7bad7 commit 8c20318

4 files changed

Lines changed: 145 additions & 39 deletions

File tree

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

Lines changed: 63 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1275,23 +1275,72 @@ 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+
};
1289+
1290+
const result = await resolveMessageFiles({
1291+
direct: [direct],
1292+
forwarded: [[forwarded]],
1293+
preloadedMedia: new Map([[voice, preloaded]]),
1294+
});
1295+
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+
);
1302+
1303+
it("keeps failed file identities beside renamed, overlapping, and ID-less downloads", async () => {
1304+
const downloaded = file("F11");
1305+
const unavailable = { id: "F1", name: "missing-contract.pdf", mimetype: "application/pdf" };
1306+
const downloadedWithoutId = { name: "available.png", mimetype: "image/png" };
1307+
const unavailableWithSameMetadata = { ...downloadedWithoutId };
1308+
const unavailableWithoutId = { name: "missing.png", mimetype: "image/png" };
12851309

12861310
const result = await resolveMessageFiles({
1287-
direct: [voice],
1288-
forwarded: [[file("FVOICE")]],
1289-
preloadedMedia: new Map([[voice, preloaded]]),
1311+
direct: [
1312+
downloaded,
1313+
unavailable,
1314+
downloadedWithoutId,
1315+
unavailableWithSameMetadata,
1316+
unavailableWithoutId,
1317+
],
1318+
preloadedMedia: new Map([
1319+
[
1320+
downloaded,
1321+
{
1322+
path: "/tmp/renamed.png",
1323+
fileName: "renamed.png",
1324+
placeholder: "[Slack file: renamed.png (fileId: F11)]",
1325+
},
1326+
],
1327+
[
1328+
downloadedWithoutId,
1329+
{
1330+
path: "/tmp/server-renamed.png",
1331+
fileName: "server-renamed.png",
1332+
placeholder: "[Slack file: server-renamed.png (image/png)]",
1333+
},
1334+
],
1335+
]),
12901336
});
12911337

1292-
expect(mockFetch).not.toHaveBeenCalled();
1293-
expect(result?.effectiveDirectMedia).toEqual([preloaded]);
1294-
expect(result?.effectiveDirectMedia?.[0]).toBe(preloaded);
1338+
expect(result?.effectiveDirectMedia).toHaveLength(2);
1339+
expect(result?.rawBody.match(/fileId: F11/g)).toHaveLength(1);
1340+
expect(result?.rawBody.match(/server-renamed\.png/g)).toHaveLength(1);
1341+
expect(result?.rawBody.match(/available\.png/g)).toHaveLength(1);
1342+
expect(result?.rawBody).toContain("missing-contract.pdf (application/pdf, fileId: F1)");
1343+
expect(result?.rawBody).toContain("missing.png (image/png)");
12951344
});
12961345

12971346
it("applies Slack's eight-file budget once across direct and forwarded sources", async () => {
@@ -1343,6 +1392,7 @@ describe("Slack message file intake", () => {
13431392
expect(result?.rawBody).toContain(
13441393
"FDIRECT)] [Forwarded image: first-image.png] [Slack file: FFIRST",
13451394
);
1395+
expect(result?.rawBody).toContain("FFAILED.png (image/png, fileId: FFAILED)");
13461396
});
13471397

13481398
it("preserves distinct files without Slack file identifiers", async () => {

‎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: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -116,16 +116,9 @@ export async function resolveSlackMessageContent(params: {
116116
: null;
117117

118118
const effectiveDirectMedia = attachmentContent?.media.length ? attachmentContent.media : null;
119-
const mediaPlaceholder = effectiveDirectMedia
120-
? effectiveDirectMedia.map((item) => item.placeholder).join(" ")
121-
: undefined;
119+
const mediaPlaceholder = effectiveDirectMedia?.map((item) => item.placeholder).join(" ");
122120

123-
const fallbackFiles = attachmentContent?.files ?? [];
124-
const fileOnlyFallback =
125-
!mediaPlaceholder && fallbackFiles.length > 0
126-
? fallbackFiles.map((file) => formatSlackFileReference(file)).join(", ")
127-
: undefined;
128-
const fileOnlyPlaceholder = fileOnlyFallback ? `[Slack file: ${fileOnlyFallback}]` : undefined;
121+
const fileOnlyFallback = attachmentContent?.files?.map(formatSlackFileReference).join(", ");
129122

130123
let botAttachmentText: string | undefined;
131124
if (params.isBotMessage && !attachmentContent?.text) {
@@ -180,7 +173,7 @@ export async function resolveSlackMessageContent(params: {
180173
renderedAttachmentText,
181174
renderedBotAttachmentText,
182175
mediaPlaceholder,
183-
fileOnlyPlaceholder,
176+
fileOnlyFallback ? `[Slack file: ${fileOnlyFallback}]` : undefined,
184177
]
185178
.filter(Boolean)
186179
.join("\n") || "";
@@ -193,12 +186,5 @@ export async function resolveSlackMessageContent(params: {
193186
} unavailable]`,
194187
});
195188
}
196-
if (!rawBody) {
197-
return null;
198-
}
199-
200-
return {
201-
rawBody,
202-
effectiveDirectMedia,
203-
};
189+
return rawBody ? { rawBody, effectiveDirectMedia } : null;
204190
}

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

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2098,6 +2098,62 @@ Second paragraph should still reach the agent after Slack's preview cutoff.`;
20982098
);
20992099
});
21002100

2101+
it("keeps a failed file recoverable when a sibling download reaches the agent", async () => {
2102+
const originalFetch = globalThis.fetch;
2103+
globalThis.fetch = vi.fn(
2104+
async (input: RequestInfo | URL) =>
2105+
new Response(Buffer.from("image contents"), {
2106+
status: 200,
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+
},
2113+
}),
2114+
) as typeof fetch;
2115+
let downloadedPaths: string[] = [];
2116+
2117+
try {
2118+
const prepared = await prepareWithDefaultCtx(
2119+
createSlackMessage({
2120+
text: "Please inspect both attachments",
2121+
files: [
2122+
{
2123+
id: "F11",
2124+
name: "available.png",
2125+
mimetype: "image/png",
2126+
url_private_download: "https://files.slack.com/available.png",
2127+
},
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" },
2134+
{ id: "F1", name: "missing-contract.pdf", mimetype: "application/pdf" },
2135+
],
2136+
}),
2137+
);
2138+
2139+
assertPrepared(prepared);
2140+
downloadedPaths =
2141+
prepared.ctxPayload.media?.flatMap((media) => (media.path ? [media.path] : [])) ?? [];
2142+
expect(prepared.ctxPayload.media).toHaveLength(2);
2143+
expect(prepared.ctxPayload.RawBody).toContain("available.png (image/png, fileId: F11)");
2144+
expect(prepared.ctxPayload.RawBody).toContain("server-renamed.png (image/png)");
2145+
expect(prepared.ctxPayload.RawBody?.match(/original-name\.png/g)).toHaveLength(1);
2146+
expect(prepared.ctxPayload.BodyForAgent).toContain(
2147+
"missing-contract.pdf (application/pdf, fileId: F1)",
2148+
);
2149+
} finally {
2150+
globalThis.fetch = originalFetch;
2151+
await Promise.all(
2152+
downloadedPaths.map((downloadedPath) => fs.rm(downloadedPath, { force: true })),
2153+
);
2154+
}
2155+
});
2156+
21012157
it("delivers forwarded file-only messages with metadata when media download fails", async () => {
21022158
const prepared = await prepareWithDefaultCtx(
21032159
createSlackMessage({

0 commit comments

Comments
 (0)