Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(slack): collect thread files since the last mention and skip remote files (#4637)

Andrew Barba13998d2b2356
diff --git a/.changeset/slack-thread-files.md b/.changeset/slack-thread-files.md
new file mode 100644
index 000000000..6af23af43
--- /dev/null
+++ b/.changeset/slack-thread-files.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The Slack channel now collects every file posted in a thread since the previous mention of the app, up to 10 messages back, instead of only the newest message's files, so a file shared before a follow-up question reaches the agent. It skips Google Drive, Dropbox, and other remote files, whose links stay in the message text, keeps audio and video attachments, and stops a file download after 30 seconds.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 123c033d3..471ea6c22 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -744,6 +744,10 @@ For a Slack post without an agent turn, use `ctx.thread.post(...)` in an inbound
Inbound files behind authenticated Slack URLs are staged with `fetchFile`. See [File uploads](./custom#file-uploads) for the `fetchFile` contract.
+The agent receives the files attached to the message that reaches it. When a mention carries no files, eve also collects the files posted in the thread since the previous mention of the app, up to 10 messages back, so a person can share a file and then ask about it in a follow-up. This works for mentions up to 1,000 replies into a thread. The app's own messages are skipped. A DM, or a thread where the app answers without a mention, gets no lookback, because each earlier message brought its own files.
+
+Images, PDFs, audio, video, and other files all reach the agent. See [Inbound attachments](../sandbox#inbound-attachments) for which files the model reads directly and which it opens with tools. Files shared through an integration such as Google Drive or Dropbox are links to the other service, not Slack files, so eve skips them; their link stays in the message text. A download that fails or takes longer than 30 seconds reaches the model as a note.
+
Private file downloads resolve credentials from the session's app installation workspace and require the Slack bot token's `files:read` scope. Add the scope and reinstall the Slack app before sending attachments.
Downloads cover Slack's own file hosts plus URLs under a configured [`api.fileBaseUrl`](#point-the-channel-at-a-different-slack-api-host), and travel on `api.fetch` when one is configured.
diff --git a/packages/eve/src/public/channels/slack/api.test.ts b/packages/eve/src/public/channels/slack/api.test.ts
index 9abbf6a7a..c4d0af8f1 100644
--- a/packages/eve/src/public/channels/slack/api.test.ts
+++ b/packages/eve/src/public/channels/slack/api.test.ts
@@ -4,6 +4,7 @@ import { Card, CardText } from "#compiled/chat/index.js";
import { decodeSlackApiBody } from "#internal/testing/slack-api-body.js";
import {
buildSlackBinding,
+ fetchSlackThreadWindow,
callSlackApi,
resolveSlackBotToken,
type SlackBotTokenContext,
@@ -401,6 +402,58 @@ describe("Slack outbound text", () => {
});
});
+describe("fetchSlackThreadWindow", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("pages to the trigger and keeps the last messages before it", async () => {
+ const pages = [
+ {
+ messages: [
+ { text: "a", ts: "1.0" },
+ { text: "b", ts: "2.0" },
+ ],
+ next_cursor: "page2",
+ },
+ {
+ messages: [
+ { text: "c", ts: "3.0" },
+ { text: "d", ts: "4.0" },
+ ],
+ next_cursor: "",
+ },
+ ];
+ const bodies: (Record<string, unknown> | undefined)[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
+ const contentType = init?.headers ? new Headers(init.headers).get("content-type") : null;
+ bodies.push(decodeSlackApiBody(init?.body, contentType) as Record<string, unknown>);
+ const page = pages[bodies.length - 1]!;
+ return Response.json({
+ ok: true,
+ messages: page.messages,
+ response_metadata: { next_cursor: page.next_cursor },
+ });
+ }),
+ );
+ const { thread } = buildSlackBinding({
+ botToken: "xoxb-test",
+ channelId: "C01",
+ threadTs: "1.0",
+ teamId: undefined,
+ });
+
+ const window = await fetchSlackThreadWindow(thread, "4.0", 3);
+
+ expect(window?.map((message) => message.ts)).toEqual(["2.0", "3.0", "4.0"]);
+ expect(bodies[0]).toMatchObject({ inclusive: "true", latest: "4.0", ts: "1.0" });
+ expect(bodies[1]).toMatchObject({ cursor: "page2" });
+ expect(thread.recentMessages).toEqual([]);
+ });
+});
+
describe("SlackThread.refresh", () => {
let mock: ReturnType<typeof buildFetchMock>;
diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.ts
index 628de4ffd..ffd2398fc 100644
--- a/packages/eve/src/public/channels/slack/api.ts
+++ b/packages/eve/src/public/channels/slack/api.ts
@@ -391,6 +391,35 @@ interface SlackBinding {
readonly slack: SlackHandle;
}
+/** Replies {@link SlackThread.refresh} loads: the thread's first page. */
+export const THREAD_REFRESH_LIMIT = 50;
+/** Replies per page when paging to a message. */
+const WINDOW_PAGE_SIZE = 200;
+/** Pages read before giving up on reaching a message: 1000 replies. */
+const WINDOW_MAX_PAGES = 5;
+
+type ThreadWindowFetcher = (
+ latest: string,
+ size: number,
+) => Promise<readonly SlackThreadMessage[] | undefined>;
+
+const threadWindowFetchers = new WeakMap<SlackThread, ThreadWindowFetcher>();
+
+/**
+ * Fetches the last `size` messages of a thread up to and including the one at
+ * `latest`, oldest first, without touching {@link SlackThread.recentMessages}.
+ * Slack returns replies oldest first, so this pages forward to `latest`.
+ * Returns `undefined` when `latest` sits more than 1000 replies in, or for a
+ * thread {@link buildSlackBinding} didn't build.
+ */
+export async function fetchSlackThreadWindow(
+ thread: SlackThread,
+ latest: string,
+ size: number,
+): Promise<readonly SlackThreadMessage[] | undefined> {
+ return await threadWindowFetchers.get(thread)?.(latest, size);
+}
+
/**
* Constructs the `{ thread, slack }` pair.
*
@@ -458,7 +487,7 @@ export function buildSlackBinding(input: {
const response = await fetchSlackThreadReplies({
...apiOptions,
channel: input.channelId,
- limit: 50,
+ limit: THREAD_REFRESH_LIMIT,
ts: currentThreadTs,
});
messages = (response.messages as Record<string, unknown>[]).map((raw) =>
@@ -481,6 +510,37 @@ export function buildSlackBinding(input: {
return refresh;
}
+ async function fetchWindow(
+ latest: string,
+ size: number,
+ ): Promise<readonly SlackThreadMessage[] | undefined> {
+ if (!input.channelId || !currentThreadTs) return undefined;
+ let window: Record<string, unknown>[] = [];
+ let cursor: string | undefined;
+ for (let page = 0; page < WINDOW_MAX_PAGES; page += 1) {
+ const response = await fetchSlackThreadReplies({
+ ...apiOptions,
+ channel: input.channelId,
+ cursor,
+ inclusive: true,
+ latest,
+ limit: WINDOW_PAGE_SIZE,
+ ts: currentThreadTs,
+ });
+ window = [...window, ...(response.messages as Record<string, unknown>[])].slice(-size);
+ cursor = response.nextCursor;
+ if (cursor === undefined || cursor === "") {
+ return window.map((raw) =>
+ parseThreadMessage(raw, currentThreadTs, {
+ appId: input.appId,
+ botUserId: input.botUserId,
+ }),
+ );
+ }
+ }
+ return undefined;
+ }
+
const thread: SlackThread = {
get recentMessages() {
return messages;
@@ -591,6 +651,7 @@ export function buildSlackBinding(input: {
uploadFiles,
};
+ threadWindowFetchers.set(thread, fetchWindow);
return { thread, slack };
}
diff --git a/packages/eve/src/public/channels/slack/attachments.test.ts b/packages/eve/src/public/channels/slack/attachments.test.ts
index 356932c73..e5b9878f4 100644
--- a/packages/eve/src/public/channels/slack/attachments.test.ts
+++ b/packages/eve/src/public/channels/slack/attachments.test.ts
@@ -63,7 +63,7 @@ describe("collectSlackFileParts", () => {
expect(parts[1]?.filename).toBe("cat.png");
});
- it("skips audio and video attachments", () => {
+ it("keeps audio and video attachments for the agent to open with tools", () => {
const attachments = makeAttachments([
{ type: "audio", url: "https://files.slack.com/a/b/voice.m4a", mimeType: "audio/mp4" },
{ type: "video", url: "https://files.slack.com/a/b/clip.mp4", mimeType: "video/mp4" },
@@ -72,8 +72,7 @@ describe("collectSlackFileParts", () => {
const parts = collectSlackFileParts(attachments, DEFAULT_UPLOAD_POLICY);
- expect(parts).toHaveLength(1);
- expect(parts[0]?.mediaType).toBe("image/png");
+ expect(parts.map((part) => part.mediaType)).toEqual(["audio/mp4", "video/mp4", "image/png"]);
});
it("drops attachments missing a url (nothing for fetchFile to fetch)", () => {
@@ -205,6 +204,7 @@ describe("createSlackFetchFile", () => {
expect(fetchSpy).toHaveBeenCalledWith(url, {
headers: { authorization: "Bearer xoxb-test-token" },
+ signal: expect.any(AbortSignal),
});
});
@@ -291,6 +291,7 @@ describe("createSlackFetchFile", () => {
expect(result?.bytes.equals(Buffer.from([7]))).toBe(true);
expect(apiFetch).toHaveBeenCalledWith("http://localhost:3000/files/F01/cat.png", {
headers: { authorization: "Bearer xoxb-test-token" },
+ signal: expect.any(AbortSignal),
});
expect(globalSpy).not.toHaveBeenCalled();
});
@@ -329,6 +330,7 @@ describe("createSlackFetchFile", () => {
expect(result?.bytes.equals(Buffer.from([7]))).toBe(true);
expect(globalFetch).toHaveBeenCalledWith("https://files.slack.com/files-pri/T01-F01/cat.png", {
headers: { authorization: "Bearer xoxb-test-token" },
+ signal: expect.any(AbortSignal),
});
// A stand-in's api.fetch attaches that stand-in's credentials, and this URL
// arrives in an inbound payload.
@@ -347,6 +349,7 @@ describe("createSlackFetchFile", () => {
expect(result?.bytes.equals(Buffer.from([7]))).toBe(true);
expect(apiFetch).toHaveBeenCalledWith("https://files.slack.com/files-pri/T01-F01/cat.png", {
headers: { authorization: "Bearer xoxb-test-token" },
+ signal: expect.any(AbortSignal),
});
expect(globalSpy).not.toHaveBeenCalled();
});
@@ -362,24 +365,182 @@ describe("collectInboundFileParts", () => {
mimeType: "text/csv",
},
]),
+ ts: "9.0",
};
- const emptyMention = { attachments: [] };
+ const emptyMention = { attachments: [], ts: "9.0" };
function makeSlackThread(input: {
refresh: () => Promise<void>;
- recentMessages?: readonly { isMe: boolean; raw?: Record<string, unknown> }[];
+ recentMessages?: readonly {
+ isMe: boolean;
+ raw?: Record<string, unknown>;
+ text?: string;
+ ts?: string;
+ }[];
}): never {
+ const messages = (input.recentMessages ?? []).map((message, index) => ({
+ text: "",
+ ts: `${index + 1}.0`,
+ ...message,
+ }));
+ // The refreshed thread holds the triggering mention, as Slack returns it.
+ if (messages.length > 0 && !messages.some((message) => message.ts === "9.0")) {
+ messages.push({ isMe: false, raw: {}, text: "<@UBOT> what is this?", ts: "9.0" });
+ }
+ return { refresh: input.refresh, recentMessages: messages } as never;
+ }
+
+ function collect(
+ input: Omit<Parameters<typeof collectInboundFileParts>[0], "botUserId" | "isMentioned"> &
+ Partial<Parameters<typeof collectInboundFileParts>[0]>,
+ ) {
+ return collectInboundFileParts({ botUserId: "UBOT", isMentioned: true, ...input });
+ }
+
+ function slackFile(id: string, extra: Record<string, unknown> = {}) {
return {
- refresh: input.refresh,
- recentMessages: input.recentMessages ?? [],
- } as never;
+ id,
+ mimetype: "text/csv",
+ name: `${id}.csv`,
+ url_private: `https://files.slack.com/a/b/${id}.csv`,
+ ...extra,
+ };
}
+ it("collects files from every message since the previous mention, in thread order (#705)", async () => {
+ const thread = makeSlackThread({
+ refresh: vi.fn(),
+ recentMessages: [
+ { isMe: false, raw: { files: [slackFile("F1")] }, text: "<@UBOT> look at this" },
+ { isMe: false, raw: { files: [slackFile("F2")] } },
+ { isMe: false, raw: {}, text: "and here is the sheet" },
+ { isMe: false, raw: { files: [slackFile("DRIVE", { mode: "external" })] } },
+ { isMe: true, raw: { files: [slackFile("F3")] } },
+ { isMe: false, raw: { files: [slackFile("F4")] } },
+ { isMe: false, raw: {}, text: "<@UBOT> what do these say?", ts: "9.0" },
+ ],
+ });
+
+ const parts = await collect({ mention: emptyMention, thread, policy: DEFAULT_UPLOAD_POLICY });
+
+ expect(parts.map((part) => part.filename)).toEqual(["F2.csv", "F4.csv"]);
+ });
+
+ it("looks back at most 10 messages before the trigger, once per file", async () => {
+ const thread = makeSlackThread({
+ refresh: vi.fn(),
+ recentMessages: [
+ ...Array.from({ length: 12 }, (_, index) => ({
+ isMe: false,
+ raw: { files: [slackFile(index === 11 ? "F10" : `F${index}`)] },
+ ts: `${index + 1}.0`,
+ })),
+ { isMe: false, raw: {}, text: "<@UBOT|eve> what are these?", ts: "20.0" },
+ { isMe: false, raw: { files: [slackFile("LATER")] }, ts: "21.0" },
+ ],
+ });
+
+ const parts = await collect({
+ mention: { attachments: [], ts: "20.0" },
+ thread,
+ policy: DEFAULT_UPLOAD_POLICY,
+ });
+
+ // Messages 3-12 fall in the window; message 12 repeats F10, and the reply
+ // after the trigger isn't collected.
+ expect(parts.map((part) => part.filename)).toEqual(
+ ["F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10"].map((id) => `${id}.csv`),
+ );
+ });
+
+ it("fetches the window ending at a trigger past the cached first page", async () => {
+ // The cache holds the thread's first 50 replies; the mention is reply 80.
+ const thread = {
+ recentMessages: Array.from({ length: 50 }, (_, index) => ({
+ isMe: false,
+ raw: { files: [slackFile(`EARLY${index}`)] },
+ text: "",
+ ts: `${index + 1}.0`,
+ })),
+ refresh: vi.fn(),
+ } as never;
+ const fetchThreadWindow = vi.fn(
+ async () =>
+ [
+ { isMe: false, raw: { files: [slackFile("F79")] }, text: "", ts: "79.0" },
+ { isMe: false, raw: {}, text: "<@UBOT> what is this?", ts: "80.0" },
+ ] as never,
+ );
+ const mention = { attachments: [], ts: "80.0" };
+
+ const parts = await collect({
+ fetchThreadWindow,
+ mention,
+ thread,
+ policy: DEFAULT_UPLOAD_POLICY,
+ });
+
+ expect(fetchThreadWindow).toHaveBeenCalledWith("80.0", 11);
+ expect(parts.map((part) => part.filename)).toEqual(["F79.csv"]);
+ // A short first page holds the whole thread, so there's nothing to fetch.
+ const shortThread = { recentMessages: [], refresh: vi.fn() } as never;
+ const notCalled = vi.fn(async () => undefined);
+ await expect(
+ collect({
+ fetchThreadWindow: notCalled,
+ mention,
+ thread: shortThread,
+ policy: DEFAULT_UPLOAD_POLICY,
+ }),
+ ).resolves.toEqual([]);
+ expect(notCalled).not.toHaveBeenCalled();
+ // Past the paging limit, the window is unknown and nothing is collected.
+ await expect(
+ collect({
+ fetchThreadWindow: async () => undefined,
+ mention,
+ thread,
+ policy: DEFAULT_UPLOAD_POLICY,
+ }),
+ ).resolves.toEqual([]);
+ });
+
+ it("stops at a labelled mention of the app", async () => {
+ const thread = makeSlackThread({
+ refresh: vi.fn(),
+ recentMessages: [
+ { isMe: false, raw: { files: [slackFile("OLD")] } },
+ { isMe: false, raw: {}, text: "<@UBOT|eve> first question" },
+ { isMe: false, raw: { files: [slackFile("NEW")] } },
+ ],
+ });
+
+ const parts = await collect({ mention: emptyMention, thread, policy: DEFAULT_UPLOAD_POLICY });
+
+ expect(parts.map((part) => part.filename)).toEqual(["NEW.csv"]);
+ });
+
+ it("looks back only when the message mentions the app", async () => {
+ const thread = makeSlackThread({
+ refresh: vi.fn(),
+ recentMessages: [{ isMe: false, raw: { files: [slackFile("F1")] } }],
+ });
+
+ const parts = await collect({
+ isMentioned: false,
+ mention: emptyMention,
+ thread,
+ policy: DEFAULT_UPLOAD_POLICY,
+ });
+
+ expect(parts).toEqual([]);
+ });
+
it("returns mention attachments without refreshing when present", async () => {
const refresh = vi.fn().mockResolvedValue(undefined);
const thread = makeSlackThread({ refresh });
- const parts = await collectInboundFileParts({
+ const parts = await collect({
mention: mentionWithFile,
thread,
policy: DEFAULT_UPLOAD_POLICY,
@@ -410,7 +571,7 @@ describe("collectInboundFileParts", () => {
],
});
- const parts = await collectInboundFileParts({
+ const parts = await collect({
mention: emptyMention,
thread,
policy: DEFAULT_UPLOAD_POLICY,
@@ -453,7 +614,7 @@ describe("collectInboundFileParts", () => {
],
});
- const parts = await collectInboundFileParts({
+ const parts = await collect({
mention: emptyMention,
thread,
policy: DEFAULT_UPLOAD_POLICY,
@@ -487,7 +648,7 @@ describe("collectInboundFileParts", () => {
],
});
- const parts = await collectInboundFileParts({
+ const parts = await collect({
mention: emptyMention,
thread,
policy,
@@ -502,7 +663,7 @@ describe("collectInboundFileParts", () => {
const refresh = vi.fn().mockResolvedValue(undefined);
const thread = makeSlackThread({ refresh });
- const parts = await collectInboundFileParts({
+ const parts = await collect({
mention: mentionWithFile,
thread,
policy: DISABLED_POLICY,
@@ -523,7 +684,7 @@ describe("collectInboundFileParts", () => {
const refresh = vi.fn().mockResolvedValue(undefined);
const thread = makeSlackThread({ refresh });
- const parts = await collectInboundFileParts({
+ const parts = await collect({
mention: mentionWithFile,
thread,
policy: ZERO_BYTES_POLICY,
@@ -538,7 +699,7 @@ describe("collectInboundFileParts", () => {
const refresh = vi.fn().mockRejectedValue(new Error("Slack 500"));
const thread = makeSlackThread({ refresh });
- const parts = await collectInboundFileParts({
+ const parts = await collect({
mention: emptyMention,
thread,
policy: DEFAULT_UPLOAD_POLICY,
diff --git a/packages/eve/src/public/channels/slack/attachments.ts b/packages/eve/src/public/channels/slack/attachments.ts
index 47e310094..632c2ce5d 100644
--- a/packages/eve/src/public/channels/slack/attachments.ts
+++ b/packages/eve/src/public/channels/slack/attachments.ts
@@ -6,10 +6,16 @@ import { readLimitedBytes } from "#internal/attachments/limited-read.js";
import { createLogger } from "#internal/logging.js";
import {
resolveSlackBotToken,
+ THREAD_REFRESH_LIMIT,
type SlackBotToken,
type SlackThread,
+ type SlackThreadMessage,
} from "#public/channels/slack/api.js";
-import type { SlackAttachment, SlackMessage } from "#public/channels/slack/inbound.js";
+import {
+ parseAttachments,
+ type SlackAttachment,
+ type SlackMessage,
+} from "#public/channels/slack/inbound.js";
import {
isConfiguredSlackFileUrl,
resolveSlackTransportOptions,
@@ -24,11 +30,16 @@ import { DEFAULT_UPLOAD_POLICY, type UploadPolicy } from "#public/channels/uploa
const log = createLogger("slack.attachments");
+/** Thread messages the lookback inspects, newest first, when a mention carries no files. */
+const THREAD_LOOKBACK_MESSAGES = 10;
+/** Slack file downloads give up after this long, so one slow file can't stall the turn. */
+const FILE_FETCH_TIMEOUT_MS = 30_000;
+
/**
- * Emits one {@link FilePart} per supported attachment in the inbound
- * message, with `data` set to a `URL` object pointing at the Slack
- * file. Audio, video, URL-less, and policy-violating attachments are
- * dropped so a single bad upload never blocks the text portion.
+ * Emits one {@link FilePart} per attachment in the inbound message, with
+ * `data` set to a `URL` object pointing at the Slack file. URL-less and
+ * policy-violating attachments are dropped so a single bad upload never
+ * blocks the text portion.
*
* The `URL` object in `data` is resolved by the channel's `fetchFile`
* function at staging time inside the workflow step.
@@ -55,9 +66,6 @@ export function collectSlackFileParts(
}
function toSlackFilePart(attachment: SlackAttachment, index: number): FilePart | null {
- if (attachment.type === "audio" || attachment.type === "video") {
- return null;
- }
if (!attachment.url) {
log.warn("dropped attachment — no url available", {
name: attachment.name,
@@ -74,28 +82,41 @@ function toSlackFilePart(attachment: SlackAttachment, index: number): FilePart |
}
/**
- * Collects file parts for an inbound mention.
+ * Collects file parts for an inbound message.
*
- * Prefers attachments on the triggering mention (the common case: user
- * uploads a file and mentions the bot in the same message). When the
- * mention has none, refreshes the thread via {@link SlackThread.refresh}
- * and picks the attachments of the latest message this app did not
- * author (the thread message `isMe` classification) — covering the case
- * where a user or another bot dropped a file in the thread first, then a
- * user mentioned the bot in a follow-up. Any error during refresh is logged
- * and treated as "no attachments" so the text portion of the mention
- * still gets delivered.
+ * Prefers attachments on the triggering message (the common case: a person
+ * uploads a file and mentions the app in the same message). When a mention
+ * carries none, refreshes the thread via {@link SlackThread.refresh} and
+ * collects, in thread order, the files of the messages between the previous
+ * mention of the app and the trigger, up to {@link THREAD_LOOKBACK_MESSAGES}
+ * messages back. When the cached replies don't reach the trigger, as in a
+ * thread past Slack's first page, the window ending at the trigger is
+ * fetched; a trigger neither returns gets no lookback.
+ * That earlier mention started its own turn, which collected the files before
+ * it. The app's own messages and remote files are skipped. A message that
+ * didn't mention the app gets no lookback: the app answers every message in
+ * that conversation, so each earlier message brought its own files.
*
- * Skips the thread-history lookback when the policy disables uploads,
- * since the refresh can't surface anything we'd deliver.
+ * Any error during refresh is logged and treated as "no attachments" so the
+ * text portion of the message still gets delivered. Skips the lookback when
+ * the policy disables uploads, since the refresh can't surface anything we'd
+ * deliver.
*/
export async function collectInboundFileParts(input: {
- readonly mention: Pick<SlackMessage, "attachments">;
+ readonly mention: Pick<SlackMessage, "attachments" | "ts">;
readonly thread: SlackThread;
readonly policy: UploadPolicy;
+ /** Whether the triggering message mentions the app. */
+ readonly isMentioned: boolean;
+ readonly botUserId: string | undefined;
+ /** Fetches the `size` thread messages ending at `latest`, oldest first. */
+ readonly fetchThreadWindow?: (
+ latest: string,
+ size: number,
+ ) => Promise<readonly SlackThreadMessage[] | undefined>;
}): Promise<FilePart[]> {
const fromMention = collectSlackFileParts(input.mention.attachments, input.policy);
- if (fromMention.length > 0) return fromMention;
+ if (fromMention.length > 0 || !input.isMentioned) return fromMention;
if (isUploadsDisabled(input.policy)) return [];
if (input.thread.recentMessages.length === 0) {
@@ -107,42 +128,57 @@ export async function collectInboundFileParts(input: {
}
}
- const recent = input.thread.recentMessages;
- for (let i = recent.length - 1; i >= 0; i -= 1) {
- const candidate = recent[i];
- if (!candidate || candidate.isMe) continue;
- const raw = candidate.raw as { files?: readonly Record<string, unknown>[] } | undefined;
- const attachments = extractAttachmentsFromRaw(raw?.files);
- const parts = collectSlackFileParts(attachments, input.policy);
- if (parts.length > 0) return parts;
- return [];
+ // Anchor on the trigger: messages posted after it aren't its files.
+ const recent = await withTrigger(input);
+ const trigger = recent.findIndex((message) => message.ts === input.mention.ts);
+ if (trigger === -1) return [];
+ const earlier = recent.slice(Math.max(0, trigger - THREAD_LOOKBACK_MESSAGES), trigger);
+ const attachments: SlackAttachment[] = [];
+ const seen = new Set<string>();
+ for (const message of earlier.toReversed()) {
+ if (message.isMe) continue;
+ if (mentionsApp(message.text, input.botUserId)) break;
+ const raw = message.raw as { files?: readonly Record<string, unknown>[] } | undefined;
+ const files = parseAttachments(raw?.files).filter(
+ (file) => file.id === "" || !seen.has(file.id),
+ );
+ for (const file of files) seen.add(file.id);
+ attachments.unshift(...files);
}
- return [];
+ return collectSlackFileParts(attachments, input.policy);
}
-function extractAttachmentsFromRaw(
- files: readonly Record<string, unknown>[] | undefined,
-): SlackAttachment[] {
- if (!Array.isArray(files)) return [];
- return files.map((file) => {
- const mimeType = typeof file.mimetype === "string" ? file.mimetype : undefined;
- return {
- id: typeof file.id === "string" ? file.id : "",
- type: inferAttachmentType(mimeType),
- url: typeof file.url_private === "string" ? file.url_private : undefined,
- name: typeof file.name === "string" ? file.name : undefined,
- mimeType,
- size: typeof file.size === "number" ? file.size : undefined,
- };
- });
+/**
+ * Returns thread messages that include the trigger. The cached replies are
+ * the thread's first page, so a later trigger needs its own window.
+ */
+async function withTrigger(input: {
+ readonly mention: Pick<SlackMessage, "ts">;
+ readonly thread: SlackThread;
+ readonly fetchThreadWindow?: (
+ latest: string,
+ size: number,
+ ) => Promise<readonly SlackThreadMessage[] | undefined>;
+}): Promise<readonly SlackThreadMessage[]> {
+ const cached = input.thread.recentMessages;
+ if (cached.some((message) => message.ts === input.mention.ts)) return cached;
+ // Only a full first page means the thread continues past it. A short or
+ // failed refresh has nothing further to fetch.
+ if (input.fetchThreadWindow === undefined || cached.length < THREAD_REFRESH_LIMIT) return [];
+ try {
+ return (await input.fetchThreadWindow(input.mention.ts, THREAD_LOOKBACK_MESSAGES + 1)) ?? [];
+ } catch (error) {
+ log.warn("slack thread window fetch failed for attachment collection", { error });
+ return [];
+ }
}
-function inferAttachmentType(mimeType: string | undefined): "image" | "file" | "video" | "audio" {
- if (mimeType === undefined) return "file";
- if (mimeType.startsWith("image/")) return "image";
- if (mimeType.startsWith("video/")) return "video";
- if (mimeType.startsWith("audio/")) return "audio";
- return "file";
+/** Matches `<@U123>` and the labelled `<@U123|name>` form. */
+function mentionsApp(text: string, botUserId: string | undefined): boolean {
+ return (
+ botUserId !== undefined &&
+ (text.includes(`<@${botUserId}>`) || text.includes(`<@${botUserId}|`))
+ );
}
/**
@@ -190,6 +226,7 @@ export function createSlackFetchFile(input: {
});
const response = await (api?.fetch ?? fetch)(url, {
headers: { authorization: `Bearer ${token}` },
+ signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS),
});
if (!response.ok) {
throw new EveAttachmentError({
diff --git a/packages/eve/src/public/channels/slack/inbound.test.ts b/packages/eve/src/public/channels/slack/inbound.test.ts
index 281110aab..690f9bc73 100644
--- a/packages/eve/src/public/channels/slack/inbound.test.ts
+++ b/packages/eve/src/public/channels/slack/inbound.test.ts
@@ -177,7 +177,7 @@ describe("parseAppMentionEvent", () => {
expect(message?.author?.isBot).toBe(true);
});
- it("collects file attachments with inferred type", () => {
+ it("collects file attachments with inferred type, skipping remote files", () => {
const message = parseAppMentionEvent({
type: "event_callback",
event: {
@@ -194,6 +194,14 @@ describe("parseAppMentionEvent", () => {
url_private: "https://files.slack.com/a/chart.png",
size: 1024,
},
+ // A Google Drive file shared through Slack's integration (#855).
+ {
+ id: "F2",
+ mode: "external",
+ name: "Plan",
+ mimetype: "application/vnd.google-apps.document",
+ url_private: "https://docs.google.com/document/d/1",
+ },
],
},
});
@@ -426,6 +434,15 @@ describe("parseDirectMessageEvent", () => {
name: "diagram.png",
size: 2048,
},
+ // A Dropbox file shared through Slack's integration is skipped (#855).
+ {
+ id: "F02",
+ is_external: true,
+ mimetype: "application/pdf",
+ mode: "external",
+ name: "plan.pdf",
+ url_private: "https://www.dropbox.com/s/abc/plan.pdf",
+ },
],
},
}),
diff --git a/packages/eve/src/public/channels/slack/inbound.ts b/packages/eve/src/public/channels/slack/inbound.ts
index 7f8008be4..2943f46ad 100644
--- a/packages/eve/src/public/channels/slack/inbound.ts
+++ b/packages/eve/src/public/channels/slack/inbound.ts
@@ -365,11 +365,20 @@ function parseAuthor(event: SlackAppMentionEvent | SlackMessageEvent): SlackAuth
};
}
-function parseAttachments(
+/**
+ * Parses the `files` of a raw Slack message. A remote file, such as a Google
+ * Drive link, carries `mode: "external"` and a URL on the third party's host
+ * that the bot token can't open; its link stays in the message text.
+ */
+export function parseAttachments(
files: readonly Record<string, unknown>[] | undefined,
): SlackAttachment[] {
if (!Array.isArray(files)) return [];
- return files.map(toAttachment);
+ return files.filter((file) => !isRemoteFile(file)).map(toAttachment);
+}
+
+function isRemoteFile(file: Readonly<Record<string, unknown>>): boolean {
+ return file.mode === "external" || file.is_external === true;
}
function toAttachment(file: Record<string, unknown>): SlackAttachment {
@@ -420,7 +429,7 @@ function parsePayloadAuthor(
function parsePayloadAttachments(files: readonly SlackFile[] | undefined): SlackAttachment[] {
if (!Array.isArray(files)) return [];
- return files.map(toPayloadAttachment);
+ return files.filter((file) => !isRemoteFile(file.raw)).map(toPayloadAttachment);
}
/**
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 187abc6ee..54cd708db 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -28,6 +28,7 @@ import type {
import {
buildSlackBinding,
buildSlackWorkspaceHandle,
+ fetchSlackThreadWindow,
slackContinuationToken,
type SlackBotToken,
type SlackHandle,
@@ -1456,6 +1457,10 @@ async function deliverSlackMessage(input: {
: await loadThreadContextMessages(thread, message, input.threadContext);
const threadContext = formatSlackThreadContext(priorMessages);
const fileParts = await collectInboundFileParts({
+ botUserId: input.botUserId,
+ fetchThreadWindow: (latest, size) => fetchSlackThreadWindow(thread, latest, size),
+ // A DM can mention the app too, but every DM message brings its own files.
+ isMentioned: input.kind === "app_mention",
mention: message,
thread,
policy: input.uploadPolicy,