Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(slack): skip the final reply when the thread root was deleted (#5137)

Ben Pankow62d3227604aa
diff --git a/.changeset/skip-reply-to-deleted-slack-root.md b/.changeset/skip-reply-to-deleted-slack-root.md
new file mode 100644
index 000000000..ad596e2af
--- /dev/null
+++ b/.changeset/skip-reply-to-deleted-slack-root.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Skip the final Slack reply when the message that started the turn was deleted, instead of letting Slack post it as a top-level channel message.
diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.ts
index b7c7a9622..d258742f2 100644
--- a/packages/eve/src/public/channels/slack/api.ts
+++ b/packages/eve/src/public/channels/slack/api.ts
@@ -430,6 +430,11 @@ export async function fetchSlackThreadWindow(
* live `threadTs` and firing `onThreadTsChanged` so the caller can
* persist the anchor. Ephemerals and upload-only file posts do not
* anchor.
+ *
+ * `onPosted` fires after each reply this binding posts into its existing
+ * thread, through `thread.post`, `uploadFiles`, or
+ * `request("chat.postMessage")`. A post that anchors a new thread is its
+ * root, not a reply, so it does not fire.
*/
export function buildSlackBinding(input: {
/** Slack app id used to identify this app's fetched thread replies. */
@@ -450,11 +455,26 @@ export function buildSlackBinding(input: {
/** Actor/content workspace exposed on the public handle. */
readonly teamId: string | undefined;
readonly onThreadTsChanged?: (ts: string) => void;
+ readonly onPosted?: () => void;
}): SlackBinding {
const context = { teamId: input.installationTeamId };
const token = () => resolveSlackBotToken(input.botToken, context);
const apiOptions = slackApiOptions(input.api, token);
- const request = createSlackRequester(input.api, input.botToken, context);
+ const send = createSlackRequester(input.api, input.botToken, context);
+ const request: SlackHandle["request"] = async (operation, body) => {
+ const response = await send(operation, body);
+ if (operation === "chat.postMessage" && response.ok === true) {
+ const target = body as { readonly channel?: unknown; readonly thread_ts?: unknown };
+ if (
+ currentThreadTs &&
+ target.channel === input.channelId &&
+ target.thread_ts === currentThreadTs
+ ) {
+ input.onPosted?.();
+ }
+ }
+ return response;
+ };
let messages: readonly SlackThreadMessage[] = [];
let currentThreadTs = input.threadTs;
let threadHasReplies = input.threadHasReplies ?? currentThreadTs !== "";
@@ -473,12 +493,16 @@ export function buildSlackBinding(input: {
const channelId = options?.channelId ?? input.channelId;
const threadTs = options?.threadTs ?? currentThreadTs;
const uploads = files.map((file) => toSlackFileUpload(file, options?.snippetType));
- return uploadSlackFiles(uploads, {
+ const result = await uploadSlackFiles(uploads, {
...apiOptions,
channelId: channelId || undefined,
initialComment: options?.initialComment,
threadTs: threadTs || undefined,
});
+ if (threadTs && channelId === input.channelId && threadTs === currentThreadTs) {
+ input.onPosted?.();
+ }
+ return result;
}
function refreshMessages(): Promise<void> {
@@ -582,10 +606,12 @@ export function buildSlackBinding(input: {
return { id, raw: result.raw };
}
+ const replyTo = currentThreadTs;
const response = await postSlackMessage(
- buildPostMessageOptions(message, input.channelId, currentThreadTs, apiOptions),
+ buildPostMessageOptions(message, input.channelId, replyTo, apiOptions),
);
const id = response.id;
+ if (replyTo) input.onPosted?.();
if (currentThreadTs) threadHasReplies = true;
handleMessageTs(id);
diff --git a/packages/eve/src/public/channels/slack/reply-delivery.ts b/packages/eve/src/public/channels/slack/reply-delivery.ts
index 582d227dc..76121ff37 100644
--- a/packages/eve/src/public/channels/slack/reply-delivery.ts
+++ b/packages/eve/src/public/channels/slack/reply-delivery.ts
@@ -6,6 +6,7 @@ import {
} from "#public/channels/slack/limits.js";
import type {
SlackChannelInternalEvents,
+ SlackChannelContext,
SlackChannelState,
SlackContext,
SlackEventContext,
@@ -15,6 +16,7 @@ const log = createLogger("slack.reply");
const LONG_RESPONSE_FILENAME = "eve-response.md";
const LONG_RESPONSE_NOTICE = "Here's a snippet with the full response.";
const FALLBACK_LOG = "Slack refused the final reply; delivering it with a fallback";
+const ROOT_GONE_LOG = "Slack thread root was deleted; dropping the final reply";
/**
* Slack error codes for a message payload Slack refused as too large or
@@ -64,6 +66,11 @@ export type SlackCompletedReply =
* This requires the `files:write` bot scope. In a session without a
* thread yet, the note posts first and anchors the thread.
*
+ * Before any of that, while eve has not yet posted in the thread, it checks
+ * that the bound thread's root still exists. Slack posts a reply to a
+ * deleted root as a top-level channel message, so eve drops the reply
+ * instead of posting it unthreaded.
+ *
* Any other error, and a failed upload, is thrown so your renderer sees it.
* eve logs each fallback it takes with Slack's error code, never the reply.
*
@@ -94,6 +101,10 @@ export async function deliverCompletedSlackReply(
logFields: { readonly turnId?: string },
): Promise<void> {
const { blocks, markdown, text } = typeof reply === "string" ? { markdown: reply } : reply;
+ if (await threadRootIsGone(channel)) {
+ log.warn(ROOT_GONE_LOG, logFields);
+ return;
+ }
let slackError: string | undefined;
if (blocks !== undefined) {
try {
@@ -122,6 +133,35 @@ export async function deliverCompletedSlackReply(
await uploadReplySnippet(channel, markdown);
}
+/**
+ * True when the bound thread's root message no longer exists. Slack accepts
+ * a `thread_ts` whose parent is gone and posts the message at the top level
+ * of the channel, so a reply to a deleted root would leak into the channel.
+ *
+ * `chat.getPermalink` needs no scopes, unlike `conversations.replies`, so
+ * the check works with the minimal `app_mentions:read` + `chat:write` app.
+ * Only `message_not_found` counts as gone. Any other failure to look it up
+ * counts as "not gone", so a lookup problem never swallows a reply.
+ *
+ * Once eve has posted in the thread, deleting the root leaves a tombstone
+ * that keeps the thread, and `chat.getPermalink` may not tell a tombstone
+ * from a missing message, so the check is skipped.
+ */
+async function threadRootIsGone(channel: SlackContext): Promise<boolean> {
+ const { channelId, threadTs } = channel.slack;
+ if (!channelId || !threadTs) return false;
+ if ((channel as Partial<SlackChannelContext>).state?.postedInThread === true) return false;
+ try {
+ const response = await channel.slack.request("chat.getPermalink", {
+ channel: channelId,
+ message_ts: threadTs,
+ });
+ return response.ok !== true && response.error === "message_not_found";
+ } catch {
+ return false;
+ }
+}
+
async function uploadReplySnippet(channel: SlackContext, message: string): Promise<void> {
const file = {
data: new Blob([message], { type: "text/markdown" }),
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 006dc1f69..5b54d9136 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -1,6 +1,7 @@
import { createHmac } from "node:crypto";
import { afterAll, afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
+import type { Mock } from "vitest";
import { buildAdapterContext } from "#channel/adapter-context.js";
import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";
@@ -108,6 +109,25 @@ function parseSlackRequestBody(init: RequestInit | undefined): Record<string, un
return decodeSlackApiBody(init.body, contentType) as Record<string, unknown>;
}
+// Wraps a recording `fetch` mock so the final-reply root check
+// (`chat.getPermalink`) finds a live thread root without being recorded.
+// Tests of that check supply their own `lookup` and read the lookups made.
+function withLiveThreadRoot(
+ fetchMock: ReturnType<typeof vi.fn>,
+ lookup: () => Record<string, unknown> = () => ({ ok: true, permalink: "https://slack.test/p1" }),
+ lookups: string[] = [],
+): typeof fetch {
+ return (async (input: string | URL | Request, init?: RequestInit) => {
+ if (String(input) === "https://slack.com/api/chat.getPermalink") {
+ lookups.push(String(parseSlackRequestBody(init).message_ts));
+ return new Response(JSON.stringify(lookup()), {
+ headers: { "content-type": "application/json" },
+ });
+ }
+ return (fetchMock as Mock<typeof fetch>)(input, init);
+ }) as typeof fetch;
+}
+
// Selects the captured calls to one Slack Web API method. The transport
// hands `fetch` a `URL`, which never equals a string, so a URL assertion
// has to stringify before comparing.
@@ -571,7 +591,7 @@ describe("slackChannel() default event handlers", () => {
}),
),
);
- vi.stubGlobal("fetch", fetchMock);
+ vi.stubGlobal("fetch", withLiveThreadRoot(fetchMock));
});
afterEach(() => {
vi.useRealTimers();
@@ -1952,10 +1972,17 @@ describe("slackChannel() default event handlers", () => {
describe("slackChannel() final reply delivery", () => {
let fetchMock: ReturnType<typeof vi.fn>;
let uploadedBodies: string[];
+ let rootLookup: () => Record<string, unknown>;
+ let rootLookups: string[];
beforeEach(() => {
fetchMock = vi.fn();
uploadedBodies = useSuccessfulSlackFileUpload(fetchMock);
- vi.stubGlobal("fetch", fetchMock);
+ rootLookup = () => ({ ok: true, permalink: "https://slack.test/p1700000000000001" });
+ rootLookups = [];
+ vi.stubGlobal(
+ "fetch",
+ withLiveThreadRoot(fetchMock, () => rootLookup(), rootLookups),
+ );
});
// Fails the next calls to each named Slack method with the queued error
@@ -2061,6 +2088,135 @@ describe("slackChannel() final reply delivery", () => {
const shortAnswer = `# Findings\n\n${"r".repeat(6_000)}`;
const longAnswer = `# Findings\n\n${"r".repeat(SLACK_MARKDOWN_TEXT_MAX_LENGTH)}`;
+ describe("deleted thread root", () => {
+ const rootGoneLog = "Slack thread root was deleted; dropping the final reply";
+
+ // Slack posts a reply to a deleted root as a top-level channel message.
+ it("drops the reply when Slack reports the root as message_not_found", async () => {
+ const logs = captureLogRecords();
+ rootLookup = () => ({ ok: false, error: "message_not_found" });
+ const { adapter, ctx } = adapterWith();
+
+ await callCompletionHandler(adapter, finalReply("hello"), ctx);
+
+ expect(rootLookups).toEqual(["1700000000.000001"]);
+ expect(urls()).toEqual([]);
+ expect(logs.records.some((entry) => entry.message === rootGoneLog)).toBe(true);
+ });
+
+ it("drops a reply sent through postCompletedSlackReply", async () => {
+ rootLookup = () => ({ ok: false, error: "message_not_found" });
+ const { adapter, ctx } = adapterWith([helperReplies()]);
+
+ await callCompletionHandler(adapter, finalReply(shortAnswer), ctx);
+
+ expect(urls()).toEqual([]);
+ });
+
+ it("posts the reply when the root is live", async () => {
+ const { adapter, ctx } = adapterWith();
+
+ await callCompletionHandler(adapter, finalReply("hello"), ctx);
+
+ expect(rootLookups).toEqual(["1700000000.000001"]);
+ expect(urls()).toEqual(["https://slack.com/api/chat.postMessage"]);
+ });
+
+ // Once eve has posted, deleting the root leaves a tombstone that keeps the
+ // thread, which chat.getPermalink may report as message_not_found.
+ it("skips the check once eve has posted in the thread", async () => {
+ rootLookup = () => ({ ok: false, error: "message_not_found" });
+ const { adapter, ctx } = adapterWith();
+ ctx.state.postedInThread = true;
+
+ await callCompletionHandler(adapter, finalReply("hello"), ctx);
+
+ expect(rootLookups).toEqual([]);
+ expect(urls()).toEqual(["https://slack.com/api/chat.postMessage"]);
+ });
+
+ it("checks the root only until eve's first post in the thread", async () => {
+ const { adapter, ctx } = adapterWith();
+
+ await callCompletionHandler(adapter, finalReply("first"), ctx);
+ await callCompletionHandler(adapter, finalReply("second"), ctx);
+
+ expect(ctx.state.postedInThread).toBe(true);
+ expect(rootLookups).toEqual(["1700000000.000001"]);
+ expect(urls()).toEqual([
+ "https://slack.com/api/chat.postMessage",
+ "https://slack.com/api/chat.postMessage",
+ ]);
+ });
+
+ it("counts a raw chat.postMessage into the thread as eve's post", async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ ok: true, ts: "1700000000.000009" }), {
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const { ctx } = adapterWith();
+
+ await ctx.slack.request("chat.postMessage", {
+ channel: "C01",
+ text: "task card",
+ thread_ts: "1700000000.000001",
+ });
+
+ expect(ctx.state.postedInThread).toBe(true);
+ });
+
+ it("does not count a raw chat.postMessage to another thread", async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ ok: true, ts: "1700000000.000009" }), {
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const { ctx } = adapterWith();
+
+ await ctx.slack.request("chat.postMessage", { channel: "C02", text: "elsewhere" });
+
+ expect(ctx.state.postedInThread).toBeUndefined();
+ });
+
+ // The anchor is the thread's root, not a reply under it.
+ it("does not count a post that anchors a new thread", async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ ok: true, ts: "1700000000.000042" }), {
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const adapter = withState(
+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),
+ { ...THREAD_STATE, threadTs: null },
+ );
+ const ctx = buildAdapterContext(adapter, stubAccessor());
+
+ await ctx.thread.post("proactive update");
+
+ expect(ctx.state.threadTs).toBe("1700000000.000042");
+ expect(ctx.state.postedInThread).toBeUndefined();
+ });
+
+ it.each([
+ ["a Slack error", () => ({ ok: false, error: "ratelimited" })],
+ ["an unreadable channel", () => ({ ok: false, error: "channel_not_found" })],
+ [
+ "a thrown lookup",
+ () => {
+ throw new Error("network down");
+ },
+ ],
+ ])("posts the reply when the root lookup fails with %s", async (_label, lookup) => {
+ rootLookup = lookup;
+ const { adapter, ctx } = adapterWith();
+
+ await callCompletionHandler(adapter, finalReply("hello"), ctx);
+
+ expect(urls()).toEqual(["https://slack.com/api/chat.postMessage"]);
+ });
+ });
+
describe("postCompletedSlackReply", () => {
it("posts the caller's Markdown once when Slack refuses the blocks", async () => {
const logs = captureLogRecords();
@@ -2427,7 +2583,7 @@ describe("rebuildSlackContext", () => {
headers: { "content-type": "application/json" },
}),
);
- vi.stubGlobal("fetch", fetchMock);
+ vi.stubGlobal("fetch", withLiveThreadRoot(fetchMock));
const adapter = withState(
getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),
@@ -3714,6 +3870,40 @@ describe("slackChannel() onMessage", () => {
expect(onEvent).toHaveBeenCalledTimes(1);
});
+ // The final reply no longer leaks into the channel when the user deletes the
+ // message that started a turn (see "deleted thread root" under final reply
+ // delivery). eve still drops `message_deleted`, so nothing cancels the
+ // in-flight turn and it runs to completion before its reply is discarded.
+ // Remove `.fails` once eve cancels the turn bound to a deleted thread root.
+ it.fails("cancels the turn bound to a thread root that the user deleted", async () => {
+ const channel = slackChannel({ credentials: { botToken: "xoxb-test" } });
+ const rootTs = "1700000000.000100";
+ const body = buildEventBody(
+ {
+ channel: "C_DELETED",
+ channel_type: "channel",
+ deleted_ts: rootTs,
+ hidden: true,
+ previous_message: {
+ text: "<@U_BOT> a question",
+ ts: rootTs,
+ type: "message",
+ user: "U01",
+ },
+ subtype: "message_deleted",
+ ts: "1700000000.000200",
+ type: "message",
+ },
+ { authorizations: [{ is_bot: true, user_id: "U_BOT" }] },
+ );
+
+ const { cancel } = await firePost(channel, buildSignedRequest({ body }));
+
+ expect(cancel).toHaveBeenCalledWith(
+ expect.objectContaining({ continuationToken: `C_DELETED:${rootTs}` }),
+ );
+ });
+
it("gives specialized message hooks precedence", async () => {
const onAppMention = vi.fn(() => null);
const onMessage = vi.fn(() => ({ auth: null }));
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index d8488bfac..e5b09797d 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -281,6 +281,12 @@ export interface SlackChannelState {
* message tells the model the reply was not seen, then clears it.
*/
undeliveredReplyErrorId?: string | null;
+ /**
+ * Whether eve has posted in this thread. Once it has, deleting the root
+ * leaves a tombstone that keeps the thread, so the final reply skips the
+ * deleted-root check.
+ */
+ postedInThread?: boolean;
}
/**
@@ -814,6 +820,9 @@ function rebuildSlackContext(
session.continuation?.alias(slackContinuationToken(state.channelId, ts));
}
},
+ onPosted() {
+ state.postedInThread = true;
+ },
});
return { thread, slack, state };
}