Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): slack - coalesce thread refreshes (#1113)

Andrew Barba4133ffc19df9
diff --git a/.changeset/quiet-threads-refresh.md b/.changeset/quiet-threads-refresh.md
new file mode 100644
index 000000000..87a90062e
--- /dev/null
+++ b/.changeset/quiet-threads-refresh.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Slack thread helpers now reuse messages loaded within the same inbound handler, while overlapping `thread.refresh()` calls share one request and failed refreshes preserve the last successful snapshot.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 300d9beab..47b79051b 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -156,7 +156,7 @@ export default slackChannel({
- `"last-agent-reply"`: only messages after this installed agent's last reply, keeping repeated mentions incremental. Replies from other Slack bots do not move the boundary.
- A predicate `(message: SlackThreadMessage) => boolean`: only messages after the last one it matches, such as "since the last message that mentioned a particular user".
-`threadContext` performs one `conversations.replies` request for each triggering thread reply and requires the matching Slack history scope. Omit it when the agent should see only direct mentions. `loadThreadContextMessages` remains available when you need custom filtering or non-model processing of the raw thread messages.
+`threadContext` requires the matching Slack history scope. Thread helpers reuse messages already loaded within the same inbound handler, and overlapping refreshes share one `conversations.replies` request. Omit it when the agent should see only direct mentions. `loadThreadContextMessages` remains available when you need custom filtering or non-model processing of the raw thread messages.
### Slack API calls outside a handler
diff --git a/packages/eve/src/public/channels/slack/api.test.ts b/packages/eve/src/public/channels/slack/api.test.ts
index 8a6d8c240..3507c9511 100644
--- a/packages/eve/src/public/channels/slack/api.test.ts
+++ b/packages/eve/src/public/channels/slack/api.test.ts
@@ -449,6 +449,83 @@ describe("SlackThread.refresh", () => {
expect("metadata" in firstMessage).toBe(false);
});
+ it("shares one conversations.replies request across overlapping refreshes", async () => {
+ let resolveReplies!: (response: Response) => void;
+ const replies = new Promise<Response>((resolve) => {
+ resolveReplies = resolve;
+ });
+ mock.fetch.mockImplementation(async (input: string | URL | Request) => {
+ if (String(input) === "https://slack.com/api/conversations.replies") {
+ return replies;
+ }
+ return new Response(JSON.stringify({ ok: true }), {
+ headers: { "content-type": "application/json" },
+ });
+ });
+ const { thread } = buildSlackBinding({
+ botToken: "xoxb-test",
+ channelId: "C01",
+ threadTs: "1.0",
+ teamId: undefined,
+ });
+
+ const first = thread.refresh();
+ const second = thread.refresh();
+
+ expect(second).toBe(first);
+ await vi.waitFor(() => {
+ expect(mock.fetch).toHaveBeenCalledTimes(1);
+ });
+
+ resolveReplies(
+ new Response(
+ JSON.stringify({
+ ok: true,
+ messages: [{ text: "loaded once", ts: "1.0", user: "U01" }],
+ }),
+ { headers: { "content-type": "application/json" } },
+ ),
+ );
+ await Promise.all([first, second]);
+
+ expect(thread.recentMessages).toHaveLength(1);
+ });
+
+ it("starts a new request after the previous refresh completes", async () => {
+ const { thread } = buildSlackBinding({
+ botToken: "xoxb-test",
+ channelId: "C01",
+ threadTs: "1.0",
+ teamId: undefined,
+ });
+
+ await thread.refresh();
+ const firstSnapshot = thread.recentMessages;
+ await thread.refresh();
+
+ expect(
+ mock.calls.filter((call) => call.url === "https://slack.com/api/conversations.replies"),
+ ).toHaveLength(2);
+ expect(thread.recentMessages).not.toBe(firstSnapshot);
+ expect(firstSnapshot).toHaveLength(2);
+ });
+
+ it("preserves loaded messages when a later refresh fails", async () => {
+ const { thread } = buildSlackBinding({
+ botToken: "xoxb-test",
+ channelId: "C01",
+ threadTs: "1.0",
+ teamId: undefined,
+ });
+ await thread.refresh();
+ const loadedMessages = [...thread.recentMessages];
+ mock.fetch.mockRejectedValueOnce(new Error("Slack unavailable"));
+
+ await thread.refresh();
+
+ expect(thread.recentMessages).toEqual(loadedMessages);
+ });
+
it("marks only replies from the bound Slack app as mine", async () => {
mock.fetch.mockImplementation(async (input: string | URL | Request) => {
if (String(input) === "https://slack.com/api/conversations.replies") {
diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.ts
index c44639b11..0008460c3 100644
--- a/packages/eve/src/public/channels/slack/api.ts
+++ b/packages/eve/src/public/channels/slack/api.ts
@@ -277,8 +277,9 @@ export interface SlackThread {
/**
* Fetch the latest replies in this thread into {@link recentMessages}
- * via `conversations.replies` (50-message cap). Failures are logged and
- * swallowed, leaving `recentMessages` empty.
+ * via `conversations.replies` (50-message cap). Overlapping calls share
+ * one request. Failures are logged and swallowed without discarding the
+ * most recently loaded messages.
*/
refresh(): Promise<void>;
@@ -386,8 +387,9 @@ export function buildSlackBinding(input: {
readonly onThreadTsChanged?: (ts: string) => void;
}): SlackBinding {
const request = createSlackRequester(input.botToken);
- const messages: SlackThreadMessage[] = [];
+ let messages: readonly SlackThreadMessage[] = [];
let currentThreadTs = input.threadTs;
+ let refreshInFlight: Promise<void> | undefined;
function handleMessageTs(ts: string): void {
if (currentThreadTs || ts === currentThreadTs) return;
@@ -409,8 +411,47 @@ export function buildSlackBinding(input: {
});
}
+ function refreshMessages(): Promise<void> {
+ if (refreshInFlight !== undefined) return refreshInFlight;
+
+ // Scoped inside the coalescing check so no caller can start an
+ // uncoalesced fetch.
+ async function fetchAndReplace(): Promise<void> {
+ if (!input.channelId || !currentThreadTs) {
+ messages = [];
+ return;
+ }
+ try {
+ const response = await fetchSlackThreadReplies({
+ ...createSlackApiOptions(input.botToken),
+ channel: input.channelId,
+ limit: 50,
+ ts: currentThreadTs,
+ });
+ messages = (response.messages as Record<string, unknown>[]).map((raw) =>
+ parseThreadMessage(raw, currentThreadTs, {
+ appId: input.appId,
+ botUserId: input.botUserId,
+ }),
+ );
+ } catch (error) {
+ logError(log, "refresh threw — swallowed", error, { channelId: input.channelId });
+ }
+ }
+
+ const refresh = fetchAndReplace().finally(() => {
+ if (refreshInFlight === refresh) {
+ refreshInFlight = undefined;
+ }
+ });
+ refreshInFlight = refresh;
+ return refresh;
+ }
+
const thread: SlackThread = {
- recentMessages: messages,
+ get recentMessages() {
+ return messages;
+ },
async listParticipants() {
await thread.refresh();
const participants = new Set<string>();
@@ -499,27 +540,8 @@ export function buildSlackBinding(input: {
logError(log, "startTyping threw — swallowed", error, { channelId: input.channelId });
}
},
- async refresh() {
- messages.length = 0;
- if (!input.channelId || !currentThreadTs) return;
- try {
- const response = await fetchSlackThreadReplies({
- ...createSlackApiOptions(input.botToken),
- channel: input.channelId,
- limit: 50,
- ts: currentThreadTs,
- });
- for (const raw of response.messages as Record<string, unknown>[]) {
- messages.push(
- parseThreadMessage(raw, currentThreadTs, {
- appId: input.appId,
- botUserId: input.botUserId,
- }),
- );
- }
- } catch (error) {
- logError(log, "refresh threw — swallowed", error, { channelId: input.channelId });
- }
+ refresh() {
+ return refreshMessages();
},
mentionUser(userId) {
return `<@${userId}>`;
diff --git a/packages/eve/src/public/channels/slack/thread.test.ts b/packages/eve/src/public/channels/slack/thread.test.ts
index 311f0ae89..f2c706793 100644
--- a/packages/eve/src/public/channels/slack/thread.test.ts
+++ b/packages/eve/src/public/channels/slack/thread.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import type { SlackThreadMessage } from "#public/channels/slack/api.js";
import { loadThreadContextMessages } from "#public/channels/slack/thread.js";
@@ -64,6 +64,27 @@ describe("loadThreadContextMessages", () => {
).resolves.toEqual([messages[0], messages[1]]);
});
+ it("reuses messages already loaded by another thread helper", async () => {
+ const messages = [
+ threadMessage({ threadTs: "1700000000.000001", ts: "1700000000.000001", text: "root" }),
+ threadMessage({ threadTs: "1700000000.000001", ts: "1700000000.000002", text: "prior" }),
+ threadMessage({ threadTs: "1700000000.000001", ts: "1700000000.000003", text: "current" }),
+ ];
+ const refresh = vi.fn(async () => {});
+ const thread = {
+ recentMessages: messages,
+ refresh,
+ };
+
+ await expect(
+ loadThreadContextMessages(thread, {
+ threadTs: "1700000000.000001",
+ ts: "1700000000.000003",
+ }),
+ ).resolves.toEqual([messages[0], messages[1]]);
+ expect(refresh).not.toHaveBeenCalled();
+ });
+
it('with since: "last-agent-reply" returns only messages after the last agent reply', async () => {
const messages = [
threadMessage({ threadTs: "1700000000.000001", ts: "1700000000.000001", text: "root" }),
diff --git a/packages/eve/src/public/channels/slack/thread.ts b/packages/eve/src/public/channels/slack/thread.ts
index 1cc8e8069..88492d90d 100644
--- a/packages/eve/src/public/channels/slack/thread.ts
+++ b/packages/eve/src/public/channels/slack/thread.ts
@@ -29,9 +29,10 @@ export interface LoadThreadContextMessagesOptions {
* Slack thread turn.
*
* Returns an empty array when `message` is the thread root. For thread
- * replies, refreshes the bound Slack thread and returns its recent
- * messages before the triggering message, filtered by {@link options}.
- * Formatting and model-message role choice stay with the caller.
+ * replies, reuses already loaded thread messages or refreshes the bound
+ * Slack thread, then returns messages before the triggering message,
+ * filtered by {@link options}. Formatting and model-message role choice
+ * stay with the caller.
*/
export async function loadThreadContextMessages(
thread: Pick<SlackThread, "recentMessages" | "refresh">,
@@ -45,7 +46,9 @@ export async function loadThreadContextMessages(
return [];
}
- await thread.refresh();
+ if (thread.recentMessages.length === 0) {
+ await thread.refresh();
+ }
const currentIndex = thread.recentMessages.findIndex((entry) => entry.ts === message.ts);
const candidateMessages =
currentIndex === -1 ? thread.recentMessages : thread.recentMessages.slice(0, currentIndex);