Skip to content

Open-source status page, incident response and uptime monitoring

fix: handle cannot_reply_to_message error in slack agent (#1991)

Thibault Le Ouay7a72088a001f
diff --git a/apps/server/package.json b/apps/server/package.json
index 5c3ea5b07..4ed547539 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -55,8 +55,8 @@
"nanoid": "5.0.7",
"percentile": "1.6.0",
"validator": "13.12.0",
- "@slack/web-api": "^7.8.0",
- "@ai-sdk/anthropic": "^1.2.0",
+ "@slack/web-api": "7.15.0",
+ "@ai-sdk/anthropic": "1.2.0",
"ai": "6.0.94",
"zod": "4.1.13"
},
diff --git a/apps/server/src/routes/slack/handler.test.ts b/apps/server/src/routes/slack/handler.test.ts
index dbb86e36e..9e5a78323 100644
--- a/apps/server/src/routes/slack/handler.test.ts
+++ b/apps/server/src/routes/slack/handler.test.ts
@@ -26,16 +26,25 @@ mock.module("./workspace-resolver", () => ({
},
}));
-let slackMessages: Array<{ method: string; args: unknown }> = [];
+let slackMessages: Array<{ method: string; args: Record<string, unknown> }> =
+ [];
+let postMessageOverride:
+ | ((args: Record<string, unknown>) => Promise<{ ts: string }>)
+ | null = null;
+let updateOverride:
+ | ((args: Record<string, unknown>) => Promise<{ ts: string }>)
+ | null = null;
mock.module("@slack/web-api", () => ({
WebClient: class {
chat = {
- postMessage: (args: unknown) => {
+ postMessage: (args: Record<string, unknown>) => {
+ if (postMessageOverride) return postMessageOverride(args);
slackMessages.push({ method: "postMessage", args });
return Promise.resolve({ ts: "msg.ts" });
},
- update: (args: unknown) => {
+ update: (args: Record<string, unknown>) => {
+ if (updateOverride) return updateOverride(args);
slackMessages.push({ method: "update", args });
return Promise.resolve({ ts: "msg.ts" });
},
@@ -49,12 +58,26 @@ mock.module("@slack/web-api", () => ({
},
}));
+let runAgentOverride:
+ | (() => Promise<{ text: string; toolResults: never[] }>)
+ | null = null;
+
mock.module("./agent", () => ({
- runAgent: () =>
- Promise.resolve({
+ runAgent: () => {
+ if (runAgentOverride) return runAgentOverride();
+ return Promise.resolve({
text: "Here is my response",
toolResults: [],
- }),
+ });
+ },
+}));
+
+mock.module("./confirmation-store", () => ({
+ store: () => Promise.resolve("test-action-id"),
+ get: () => Promise.resolve(undefined),
+ consume: () => Promise.resolve(undefined),
+ findByThread: () => Promise.resolve(undefined),
+ replace: () => Promise.resolve(),
}));
const { handleSlackEvent } = await import("./handler");
@@ -94,6 +117,9 @@ describe("handleSlackEvent", () => {
beforeEach(() => {
slackMessages = [];
+ postMessageOverride = null;
+ updateOverride = null;
+ runAgentOverride = null;
});
test("responds to url_verification challenge", async () => {
@@ -335,6 +361,46 @@ describe("handleSlackEvent", () => {
expect(slackMessages.length).toBe(0);
});
+ test("ignores channel_join system messages", async () => {
+ const res = await signAndPost(app, {
+ type: "event_callback",
+ team_id: "T_KNOWN",
+ event_id: `evt_join_${Date.now()}`,
+ event: {
+ type: "message",
+ subtype: "channel_join",
+ text: "<@U1> has joined the channel",
+ user: "U1",
+ channel: "C1",
+ ts: `${Date.now()}.10`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ await new Promise((r) => setTimeout(r, 50));
+ expect(slackMessages.length).toBe(0);
+ });
+
+ test("ignores channel_leave system messages", async () => {
+ const res = await signAndPost(app, {
+ type: "event_callback",
+ team_id: "T_KNOWN",
+ event_id: `evt_leave_${Date.now()}`,
+ event: {
+ type: "message",
+ subtype: "channel_leave",
+ text: "<@U1> has left the channel",
+ user: "U1",
+ channel: "C1",
+ ts: `${Date.now()}.11`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ await new Promise((r) => setTimeout(r, 50));
+ expect(slackMessages.length).toBe(0);
+ });
+
test("ignores events with no event payload", async () => {
const res = await signAndPost(app, {
type: "event_callback",
@@ -346,4 +412,129 @@ describe("handleSlackEvent", () => {
await new Promise((r) => setTimeout(r, 50));
expect(slackMessages.length).toBe(0);
});
+
+ test("falls back to top-level message on cannot_reply_to_message", async () => {
+ let callCount = 0;
+ postMessageOverride = (args: Record<string, unknown>) => {
+ callCount++;
+ if (callCount === 1) {
+ const err = new Error("An API error occurred: cannot_reply_to_message");
+ Object.assign(err, {
+ code: "slack_webapi_platform_error",
+ data: { ok: false, error: "cannot_reply_to_message" },
+ });
+ return Promise.reject(err);
+ }
+ slackMessages.push({ method: "postMessage", args });
+ return Promise.resolve({ ts: "fallback.ts" });
+ };
+
+ const res = await signAndPost(app, {
+ type: "event_callback",
+ team_id: "T_KNOWN",
+ event_id: `evt_cantreply_${Date.now()}`,
+ event: {
+ type: "app_mention",
+ text: "<@UBOT> hello",
+ user: "U1",
+ channel: "C1",
+ ts: `${Date.now()}.20`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ await new Promise((r) => setTimeout(r, 100));
+
+ const fallbackPost = slackMessages.find(
+ (m) => m.method === "postMessage" && !m.args.thread_ts,
+ );
+ expect(fallbackPost).toBeDefined();
+ });
+
+ test("returns early on non-recoverable postMessage error", async () => {
+ postMessageOverride = () => {
+ const err = new Error("An API error occurred: channel_not_found");
+ Object.assign(err, {
+ code: "slack_webapi_platform_error",
+ data: { ok: false, error: "channel_not_found" },
+ });
+ return Promise.reject(err);
+ };
+
+ const res = await signAndPost(app, {
+ type: "event_callback",
+ team_id: "T_KNOWN",
+ event_id: `evt_channotfound_${Date.now()}`,
+ event: {
+ type: "app_mention",
+ text: "<@UBOT> hello",
+ user: "U1",
+ channel: "C1",
+ ts: `${Date.now()}.21`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ await new Promise((r) => setTimeout(r, 100));
+
+ const updateMessages = slackMessages.filter((m) => m.method === "update");
+ expect(updateMessages.length).toBe(0);
+ });
+
+ test("shows error message when runAgent throws", async () => {
+ runAgentOverride = () => Promise.reject(new Error("agent exploded"));
+
+ const res = await signAndPost(app, {
+ type: "event_callback",
+ team_id: "T_KNOWN",
+ event_id: `evt_agenterr_${Date.now()}`,
+ event: {
+ type: "app_mention",
+ text: "<@UBOT> hello",
+ user: "U1",
+ channel: "C1",
+ ts: `${Date.now()}.30`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ await new Promise((r) => setTimeout(r, 100));
+
+ const errorUpdate = slackMessages.find(
+ (m) =>
+ m.method === "update" &&
+ typeof m.args.text === "string" &&
+ m.args.text.includes("Something went wrong"),
+ );
+ expect(errorUpdate).toBeDefined();
+ });
+
+ test("does not throw when both runAgent and error update fail", async () => {
+ runAgentOverride = () => Promise.reject(new Error("agent exploded"));
+ updateOverride = () => {
+ const err = new Error("An API error occurred: channel_not_found");
+ Object.assign(err, {
+ code: "slack_webapi_platform_error",
+ data: { ok: false, error: "channel_not_found" },
+ });
+ return Promise.reject(err);
+ };
+
+ const res = await signAndPost(app, {
+ type: "event_callback",
+ team_id: "T_KNOWN",
+ event_id: `evt_doublefail_${Date.now()}`,
+ event: {
+ type: "app_mention",
+ text: "<@UBOT> hello",
+ user: "U1",
+ channel: "C1",
+ ts: `${Date.now()}.31`,
+ },
+ });
+
+ expect(res.status).toBe(200);
+ await new Promise((r) => setTimeout(r, 100));
+ // No unhandled rejection — the .catch() in the error handler swallows it
+ });
});
diff --git a/apps/server/src/routes/slack/handler.ts b/apps/server/src/routes/slack/handler.ts
index 7c88f94b4..1a36bbffb 100644
--- a/apps/server/src/routes/slack/handler.ts
+++ b/apps/server/src/routes/slack/handler.ts
@@ -1,13 +1,17 @@
+import { getLogger } from "@logtape/logtape";
import { and, db, eq } from "@openstatus/db";
import { integration } from "@openstatus/db/src/schema";
import { WebClient } from "@slack/web-api";
import type { Context } from "hono";
+import { z } from "zod";
import { runAgent } from "./agent";
import { buildConfirmationBlocks } from "./blocks";
import { findByThread, replace, store } from "./confirmation-store";
import type { PendingAction } from "./confirmation-store";
import { resolveWorkspace } from "./workspace-resolver";
+const logger = getLogger("api-server");
+
const processedEvents = new Map<string, number>();
function dedup(eventId: string): boolean {
@@ -20,28 +24,47 @@ function dedup(eventId: string): boolean {
return false;
}
-interface SlackEvent {
- type: string;
- event?: {
- type: string;
- text?: string;
- user?: string;
- channel?: string;
- channel_type?: string;
- ts?: string;
- thread_ts?: string;
- bot_id?: string;
- };
- event_id?: string;
- team_id?: string;
- challenge?: string;
-}
+const slackEventSchema = z.object({
+ type: z.string(),
+ event: z
+ .object({
+ type: z.string(),
+ subtype: z.string().optional(),
+ text: z.string().optional(),
+ user: z.string().optional(),
+ channel: z.string().optional(),
+ channel_type: z.string().optional(),
+ ts: z.string().optional(),
+ thread_ts: z.string().optional(),
+ bot_id: z.string().optional(),
+ })
+ .optional(),
+ event_id: z.string().optional(),
+ team_id: z.string().optional(),
+ challenge: z.string().optional(),
+});
+
+type SlackEvent = z.infer<typeof slackEventSchema>;
+
+const threadMessageSchema = z.object({
+ user: z.string().optional(),
+ bot_id: z.string().optional(),
+ text: z.string().optional(),
+ ts: z.string().optional(),
+});
+
+type ThreadMessage = z.infer<typeof threadMessageSchema>;
-interface ThreadMessage {
- user?: string;
- bot_id?: string;
- text?: string;
- ts?: string;
+const slackPlatformErrorSchema = z.object({
+ code: z.literal("slack_webapi_platform_error"),
+ data: z.object({
+ error: z.string(),
+ }),
+});
+
+function isSlackPlatformError(err: unknown, errorCode: string): boolean {
+ const parsed = slackPlatformErrorSchema.safeParse(err);
+ return parsed.success && parsed.data.data.error === errorCode;
}
export async function handleSlackEvent(c: Context) {
@@ -60,7 +83,13 @@ export async function handleSlackEvent(c: Context) {
}
const promise = processEvent(body);
- promise.catch((err) => console.error("[slack] event processing error:", err));
+ promise.catch((err) =>
+ logger.error("slack event processing error", {
+ error: err,
+ teamId: body.team_id,
+ eventId: body.event_id,
+ }),
+ );
return c.json({ ok: true });
}
@@ -80,7 +109,7 @@ async function processEvent(body: SlackEvent) {
eq(integration.externalId, teamId),
),
);
- console.log(`[slack] cleaned up integration for team ${teamId}`);
+ logger.info("slack integration cleaned up", { teamId });
}
return;
}
@@ -88,12 +117,21 @@ async function processEvent(body: SlackEvent) {
if (event.type !== "app_mention" && event.type !== "message") return;
if (event.type === "message" && event.bot_id) return;
+ const ignoredSubtypes = [
+ "channel_join",
+ "channel_leave",
+ "channel_topic",
+ "channel_purpose",
+ "channel_name",
+ ];
+ if (event.subtype && ignoredSubtypes.includes(event.subtype)) return;
+
const teamId = body.team_id;
if (!teamId || !event.channel || !event.ts) return;
const resolved = await resolveWorkspace(teamId);
if (!resolved) {
- console.warn(`[slack] no integration found for team ${teamId}`);
+ logger.warn("slack integration not found", { teamId });
return;
}
@@ -105,15 +143,59 @@ async function processEvent(body: SlackEvent) {
if (!event.text?.includes(`<@${botUserId}>`)) return;
}
- const thinkingMsg = await slack.chat.postMessage({
+ logger.info("slack event received", {
+ teamId,
channel: event.channel,
- thread_ts: threadTs,
- text: ":hourglass_flowing_sand: Thinking...",
+ eventType: event.type,
+ threadTs,
+ user: event.user,
});
- const thinkingTs = thinkingMsg.ts;
+
+ let thinkingTs: string | undefined;
+ try {
+ const thinkingMsg = await slack.chat.postMessage({
+ channel: event.channel,
+ thread_ts: threadTs,
+ text: ":hourglass_flowing_sand: Thinking...",
+ });
+ thinkingTs = thinkingMsg.ts;
+ } catch (err) {
+ if (isSlackPlatformError(err, "cannot_reply_to_message")) {
+ logger.warn("slack cannot reply to message, falling back to top-level", {
+ channel: event.channel,
+ teamId,
+ threadTs,
+ });
+ try {
+ const fallbackMsg = await slack.chat.postMessage({
+ channel: event.channel,
+ text: ":hourglass_flowing_sand: Thinking...",
+ });
+ thinkingTs = fallbackMsg.ts;
+ } catch (fallbackErr) {
+ logger.error("slack failed to post fallback thinking message", {
+ error: fallbackErr,
+ channel: event.channel,
+ teamId,
+ });
+ return;
+ }
+ } else {
+ logger.error("slack failed to post thinking message", {
+ error: err,
+ channel: event.channel,
+ teamId,
+ threadTs,
+ });
+ return;
+ }
+ }
if (!thinkingTs) {
- console.error("[slack] failed to post thinking message — no ts returned");
+ logger.error("slack thinking message returned no ts", {
+ channel: event.channel,
+ teamId,
+ });
return;
}
@@ -132,6 +214,13 @@ async function processEvent(body: SlackEvent) {
thread = [{ user: event.user, text: event.text, ts: event.ts }];
}
+ logger.info("slack agent invoked", {
+ teamId,
+ channel: event.channel,
+ threadTs,
+ messageCount: thread.length,
+ });
+
const result = await runAgent(
resolved.workspace,
thread,
@@ -139,6 +228,13 @@ async function processEvent(body: SlackEvent) {
event.text,
);
+ logger.info("slack agent completed", {
+ teamId,
+ channel: event.channel,
+ threadTs,
+ toolCalls: result.toolResults.map((tr) => tr.toolName),
+ });
+
const confirmationResult = result.toolResults.find(
(tr) =>
tr.result &&
@@ -148,6 +244,12 @@ async function processEvent(body: SlackEvent) {
);
if (confirmationResult) {
+ logger.info("slack confirmation requested", {
+ teamId,
+ channel: event.channel,
+ threadTs,
+ toolName: confirmationResult.toolName,
+ });
await handleConfirmation(
slack,
event.channel,
@@ -164,14 +266,34 @@ async function processEvent(body: SlackEvent) {
ts: thinkingTs,
text: result.text || "Done!",
});
+ logger.info("slack response sent", {
+ teamId,
+ channel: event.channel,
+ threadTs,
+ });
}
} catch (err) {
- console.error("[slack] agent error:", err);
- await slack.chat.update({
+ logger.error("slack agent error", {
+ error: err,
channel: event.channel,
- ts: thinkingTs,
- text: ":x: Something went wrong. Please try again.",
+ teamId,
+ threadTs,
});
+ if (thinkingTs) {
+ await slack.chat
+ .update({
+ channel: event.channel,
+ ts: thinkingTs,
+ text: ":x: Something went wrong. Please try again.",
+ })
+ .catch((updateErr: unknown) => {
+ logger.error("slack failed to update error message", {
+ error: updateErr,
+ channel: event.channel,
+ thinkingTs,
+ });
+ });
+ }
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 90ce84871..e6efca8bf 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -417,8 +417,8 @@ importers:
apps/server:
dependencies:
'@ai-sdk/anthropic':
- specifier: ^1.2.0
- version: 1.2.12([email protected])
+ specifier: 1.2.0
+ version: 1.2.0([email protected])
'@bufbuild/protobuf':
specifier: 2.10.2
version: 2.10.2
@@ -528,8 +528,8 @@ importers:
specifier: 0.8.5
version: 0.8.5([email protected])
'@slack/web-api':
- specifier: ^7.8.0
- version: 7.14.1
+ specifier: 7.15.0
+ version: 7.15.0
'@t3-oss/env-core':
specifier: 0.13.10
@@ -2241,8 +2241,8 @@ importers:
packages:
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-YSzjlko7JvuiyQFmI9RN1tNZdEiZxc+6xld/0tq/VkJaHpEzGAb1yiNxxvmYVcjvfu/PcvCxAAYXmTYQQ63IHQ==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-VMm+wAx7FhSMSjqJv7Zeu3GVxzUdohmWoFpzDCWiODpxPGFHw0d0spDR3sVpk5KcyGRJfebGd86ZtpFLCnagOQ==}
engines: {node: '>=18'}
peerDependencies:
zod: ^3.0.0
@@ -2253,8 +2253,8 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-RX5BnDSqudjvZjwwpROcxVQElyX7rUn/xImBgaZLXekSGqq8f7/tefqDcQiRbDZjuCd4CVIfhrK8y/Pta8cPfQ==}
engines: {node: '>=18'}
peerDependencies:
zod: ^3.23.8
@@ -2265,8 +2265,8 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-0M+qjp+clUD0R1E5eWQFhxEvWLNaOtGQRUaBn8CUABnSKredagq92hUS9VjOzGsTm37xLfpaxl97AVtbeOsHew==}
engines: {node: '>=18'}
'@ai-sdk/[email protected]':
@@ -6440,16 +6440,16 @@ packages:
resolution: {integrity: sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==}
engines: {node: '>=18'}
- '@slack/[email protected]':
- resolution: {integrity: sha512-Wz7QYfPAlG/DR+DfABddUZeNgoeY7d1J39OCR2jR+v7VBsB8ezulDK5szTnDDPDwLH5IWhLvXIHlCFZV7MSKgA==}
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-6cmdPrV/RYfd2U0mDGiMK8S7OJqpCTm7enMLRR3edccsPX8j7zXTLnaEF4fhxxJJTAIOil6+qZrnUPTuaLvwrQ==}
engines: {node: '>= 18', npm: '>= 8.6.0'}
- '@slack/[email protected]':
- resolution: {integrity: sha512-PVF6P6nxzDMrzPC8fSCsnwaI+kF8YfEpxf3MqXmdyjyWTYsZQURpkK7WWUWvP5QpH55pB7zyYL9Qem/xSgc5VA==}
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-eWX2mdt1ktpn8+40iiMc404uGrih+2fxiky3zBcPjtXKj6HLRdYlmhrPkJi7JTJm8dpXR6BWVWEDBXtaWMKD6A==}
engines: {node: '>= 12.13.0', npm: '>= 6.12.0'}
- '@slack/[email protected]':
- resolution: {integrity: sha512-RoygyteJeFswxDPJjUMESn9dldWVMD2xUcHHd9DenVavSfVC6FeVnSdDerOO7m8LLvw4Q132nQM4hX8JiF7dng==}
+ '@slack/[email protected]':
+ resolution: {integrity: sha512-va7zYIt3QHG1x9M/jqXXRPFMoOVlVSSRHC5YH+DzKYsrz5xUKOA3lR4THsu/Zxha9N1jOndbKFKLtr0WOPW1Vw==}
engines: {node: '>= 18', npm: '>= 8.6.0'}
'@smithy/[email protected]':
@@ -12240,10 +12240,10 @@ packages:
snapshots:
dependencies:
- '@ai-sdk/provider': 1.1.3
- '@ai-sdk/provider-utils': 2.2.8([email protected])
+ '@ai-sdk/provider': 1.1.0
+ '@ai-sdk/provider-utils': 2.2.0([email protected])
zod: 4.1.13
@@ -12253,9 +12253,10 @@ snapshots:
'@vercel/oidc': 3.1.0
zod: 4.1.13
dependencies:
- '@ai-sdk/provider': 1.1.3
+ '@ai-sdk/provider': 1.1.0
+ eventsource-parser: 3.0.6
nanoid: 3.3.11
secure-json-parse: 2.7.0
zod: 4.1.13
@@ -12267,7 +12268,7 @@ snapshots:
eventsource-parser: 3.0.6
zod: 4.1.13
- '@ai-sdk/[email protected]':
+ '@ai-sdk/[email protected]':
dependencies:
json-schema: 0.4.0
@@ -16876,16 +16877,16 @@ snapshots:
'@sindresorhus/[email protected]': {}
- '@slack/[email protected]':
+ '@slack/[email protected]':
dependencies:
'@types/node': 24.0.8
- '@slack/[email protected]': {}
+ '@slack/[email protected]': {}
- '@slack/[email protected]':
+ '@slack/[email protected]':
dependencies:
- '@slack/logger': 4.0.0
- '@slack/types': 2.20.0
+ '@slack/logger': 4.0.1
+ '@slack/types': 2.20.1
'@types/node': 24.0.8
'@types/retry': 0.12.0
axios: 1.13.5