Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(slack): dedupe one message delivered as both app_mention + message.*

Chaitanya Girie364e77bd08f
diff --git a/src/main/slack-trigger.cjs b/src/main/slack-trigger.cjs
index febe618e..c0a69b53 100644
--- a/src/main/slack-trigger.cjs
+++ b/src/main/slack-trigger.cjs
@@ -14,6 +14,9 @@
const ACTIVATED_THREADS_MAX = 500;
/** Per-message file cap — any extras beyond this are silently dropped. */
const MAX_FILES_PER_MESSAGE = 10;
+/** Maximum number of recently-seen message identities to remember for dedup.
+ * FIFO eviction above this caps memory in long-running bots. */
+const SEEN_EVENTS_MAX = 500;
/**
* Bounded FIFO set of thread timestamps where the bot was @-mentioned.
@@ -41,6 +44,61 @@ class ActivatedThreads {
get size() { return this._set.size; }
}
+/**
+ * Bounded FIFO set used as an idempotency cache. Remembers recently-processed
+ * message identities so the SAME logical Slack message — delivered twice because
+ * the app subscribes to BOTH `app_mention` AND `message.*` (an @-mention in a
+ * channel fires both), or re-delivered by Slack's retry of an un-acked event —
+ * only fires onMessage (and therefore the ack reply) once.
+ */
+class SeenEvents {
+ constructor(maxSize = SEEN_EVENTS_MAX) {
+ this.maxSize = maxSize;
+ this._set = new Set();
+ this._order = []; // FIFO eviction queue — parallel to _set
+ }
+
+ /**
+ * Record `key` and report whether it was ALREADY present.
+ * @returns {boolean} true if `key` was seen before (caller should skip as a
+ * duplicate); false if it is new (now recorded — caller should process).
+ * Empty/falsy keys are never deduped: they always return false and are
+ * not stored (so a malformed event can't poison or fill the cache).
+ */
+ seen(key) {
+ if (!key) return false;
+ if (this._set.has(key)) return true;
+ if (this._set.size >= this.maxSize) {
+ const oldest = this._order.shift();
+ if (oldest !== undefined) this._set.delete(oldest);
+ }
+ this._set.add(key);
+ this._order.push(key);
+ return false;
+ }
+
+ get size() { return this._set.size; }
+}
+
+/**
+ * Stable identity for a Slack message, shared across the event types that can
+ * carry it. The SAME user message arrives as BOTH an `app_mention` and a
+ * `message.*` event when the app subscribes to both — two SEPARATE
+ * event_callback deliveries. Those two deliveries share `channel` + `ts` (the
+ * message timestamp) but each gets its OWN outer `event_id`, and `client_msg_id`
+ * is not guaranteed on `app_mention`. So the only reliable cross-type key is
+ * `channel:ts` — using event_id or client_msg_id here would let the duplicate
+ * through. `channel:ts` also matches Slack's retry of an un-acked event.
+ *
+ * @returns {string} `"<channel>:<ts>"`, or '' when either is missing (uncacheable).
+ */
+function dedupKey(ev) {
+ if (!ev) return '';
+ const channel = typeof ev.channel === 'string' ? ev.channel : '';
+ const ts = typeof ev.ts === 'string' ? ev.ts : '';
+ return channel && ts ? `${channel}:${ts}` : '';
+}
+
/**
* Decide whether a Slack event should trigger onMessage.
*
@@ -102,4 +160,12 @@ function shouldTrigger(ev, botUserId, channelId, activatedThreads) {
return { trigger: true, text, files };
}
-module.exports = { shouldTrigger, ActivatedThreads, ACTIVATED_THREADS_MAX, MAX_FILES_PER_MESSAGE };
+module.exports = {
+ shouldTrigger,
+ ActivatedThreads,
+ SeenEvents,
+ dedupKey,
+ ACTIVATED_THREADS_MAX,
+ SEEN_EVENTS_MAX,
+ MAX_FILES_PER_MESSAGE,
+};
diff --git a/src/main/slack.ts b/src/main/slack.ts
index 062bee15..5b12888b 100644
--- a/src/main/slack.ts
+++ b/src/main/slack.ts
@@ -28,8 +28,12 @@ import { createHmac, timingSafeEqual } from 'node:crypto';
// can load ESM. Do not hoist this back to a top-level import.
// eslint-disable-next-line @typescript-eslint/no-require-imports
-const { shouldTrigger: _shouldTrigger, ActivatedThreads: _ActivatedThreads } =
- require('./slack-trigger.cjs') as {
+const {
+ shouldTrigger: _shouldTrigger,
+ ActivatedThreads: _ActivatedThreads,
+ SeenEvents: _SeenEvents,
+ dedupKey: _dedupKey,
+} = require('./slack-trigger.cjs') as {
shouldTrigger: (
ev: SlackPayload['event'],
botUserId: string | null,
@@ -37,6 +41,8 @@ const { shouldTrigger: _shouldTrigger, ActivatedThreads: _ActivatedThreads } =
activatedThreads: _IActivatedThreads
) => { trigger: boolean; text: string; files: _SlackEventFile[] };
ActivatedThreads: new (maxSize?: number) => _IActivatedThreads;
+ SeenEvents: new (maxSize?: number) => _ISeenEvents;
+ dedupKey: (ev: SlackPayload['event']) => string;
};
interface _IActivatedThreads {
@@ -45,6 +51,11 @@ interface _IActivatedThreads {
readonly size: number;
}
+interface _ISeenEvents {
+ seen(key: string): boolean;
+ readonly size: number;
+}
+
/** Raw Slack file metadata as received in the `files[]` array of a file_share event.
* Populated by slack-trigger.cjs; consumed and stripped by index.ts after download. */
export interface SlackEventFile {
@@ -111,6 +122,11 @@ export class SlackWebhookServer {
/** Thread roots where the bot was @-mentioned; subsequent replies in these
* threads also trigger onMessage. Bounded FIFO to prevent unbounded growth. */
private readonly activatedThreads: _IActivatedThreads = new _ActivatedThreads();
+ /** Idempotency cache of recently-forwarded message identities (channel:ts).
+ * Stops a single message from firing onMessage — and thus the ack reply —
+ * twice when the app subscribes to both `app_mention` and `message.*` (Slack
+ * sends both for one @-mention), and absorbs Slack's retry of un-acked events. */
+ private readonly seenEvents: _ISeenEvents = new _SeenEvents();
constructor(opts: SlackWebhookServerOptions) {
this.port = opts.port;
@@ -242,9 +258,18 @@ export class SlackWebhookServer {
const thread_ts = (typeof ev.thread_ts === 'string' && ev.thread_ts) || ts;
// Fire when text is non-empty OR files are attached (file_share may have no caption).
if ((text || rawFiles.length > 0) && channel && ts) {
- const msg: SlackInboundMessage = { text, channel, ts, thread_ts };
- if (rawFiles.length > 0) msg._rawFiles = rawFiles;
- try { void this.onMessage(msg); } catch { /* delivery is best-effort */ }
+ // Dedup: only ONE onMessage (and thus one ack) per logical message. When
+ // the app subscribes to both `app_mention` and `message.*`, a single
+ // @-mention arrives as TWO event_callbacks that share channel:ts; this
+ // also absorbs Slack's retry of an un-acked event. Gated AFTER the
+ // mention/thread filter, so non-triggering messages are unaffected.
+ const dupKey = _dedupKey(ev);
+ const isDuplicate = dupKey ? this.seenEvents.seen(dupKey) : false;
+ if (!isDuplicate) {
+ const msg: SlackInboundMessage = { text, channel, ts, thread_ts };
+ if (rawFiles.length > 0) msg._rawFiles = rawFiles;
+ try { void this.onMessage(msg); } catch { /* delivery is best-effort */ }
+ }
}
}
}
diff --git a/test/slack.test.cjs b/test/slack.test.cjs
index ce3a216c..116e2e91 100644
--- a/test/slack.test.cjs
+++ b/test/slack.test.cjs
@@ -1,7 +1,7 @@
'use strict';
const assert = require('assert');
-const { shouldTrigger, ActivatedThreads, ACTIVATED_THREADS_MAX, MAX_FILES_PER_MESSAGE } =
+const { shouldTrigger, ActivatedThreads, SeenEvents, dedupKey, ACTIVATED_THREADS_MAX, SEEN_EVENTS_MAX, MAX_FILES_PER_MESSAGE } =
require('../src/main/slack-trigger.cjs');
let failures = 0;
@@ -325,6 +325,88 @@ function ev(overrides = {}) {
assert.ok(ipcFiles[0].path.startsWith('/'), 'path is absolute');
});
+ // ─── Dedup: same message via app_mention + message.* fires onMessage once ───
+
+ await test('dedupKey is identical for app_mention and message events of the SAME message', () => {
+ // The two deliveries share channel + ts but get distinct outer event_ids.
+ const appMention = ev({ type: 'app_mention', text: `<@${BOT_ID}> hi`, ts: '1700.0001' });
+ const message = ev({ type: 'message', text: `<@${BOT_ID}> hi`, ts: '1700.0001' });
+ const k1 = dedupKey(appMention);
+ const k2 = dedupKey(message);
+ assert.strictEqual(k1, `${CHANNEL}:1700.0001`, 'key is channel:ts');
+ assert.strictEqual(k1, k2, 'app_mention and message yield the SAME dedup key');
+ });
+
+ await test('dedupKey returns "" when channel or ts is missing (uncacheable)', () => {
+ assert.strictEqual(dedupKey(ev({ ts: undefined })), '', 'no ts → empty');
+ assert.strictEqual(dedupKey(ev({ channel: undefined })), '', 'no channel → empty');
+ assert.strictEqual(dedupKey(null), '', 'null event → empty');
+ });
+
+ await test('SeenEvents.seen: first occurrence false (new), repeat true (duplicate)', () => {
+ const seen = new SeenEvents();
+ assert.strictEqual(seen.seen('C1:100.1'), false, 'first time is new');
+ assert.strictEqual(seen.seen('C1:100.1'), true, 'second time is a duplicate');
+ assert.strictEqual(seen.seen('C1:100.2'), false, 'a different key is new');
+ });
+
+ await test('SeenEvents never dedupes empty/falsy keys (and does not store them)', () => {
+ const seen = new SeenEvents();
+ assert.strictEqual(seen.seen(''), false, 'empty key never a duplicate');
+ assert.strictEqual(seen.seen(''), false, 'empty key still never a duplicate');
+ assert.strictEqual(seen.size, 0, 'empty keys are not stored');
+ });
+
+ await test('SeenEvents is bounded FIFO — oldest key evicted past the cap', () => {
+ const seen = new SeenEvents(3);
+ seen.seen('a'); seen.seen('b'); seen.seen('c');
+ assert.strictEqual(seen.size, 3, 'at cap');
+ seen.seen('d'); // evicts 'a'
+ assert.strictEqual(seen.size, 3, 'still at cap after eviction');
+ assert.strictEqual(seen.seen('a'), false, 'evicted "a" is treated as new again');
+ assert.strictEqual(seen.seen('c'), true, '"c" still remembered');
+ });
+
+ await test('SEEN_EVENTS_MAX default is exported and sane', () => {
+ assert.strictEqual(typeof SEEN_EVENTS_MAX, 'number', 'is a number');
+ assert.ok(SEEN_EVENTS_MAX >= 100, 'reasonable cap');
+ });
+
+ await test('integration: dual-subscription double-fire collapses to ONE delivery', () => {
+ // Mirrors slack.ts handleBody: shouldTrigger (gate) THEN seenEvents dedup.
+ const threads = new ActivatedThreads();
+ const seen = new SeenEvents();
+ let fires = 0;
+ const ingest = (event) => {
+ const { trigger } = shouldTrigger(event, BOT_ID, CHANNEL, threads);
+ if (!trigger) return;
+ const key = dedupKey(event);
+ if (key && seen.seen(key)) return; // duplicate — skip
+ fires++;
+ };
+ // SAME @-mention delivered as both event types (shared channel:ts).
+ ingest(ev({ type: 'app_mention', text: `<@${BOT_ID}> ship it`, ts: '1800.0009' }));
+ ingest(ev({ type: 'message', text: `<@${BOT_ID}> ship it`, ts: '1800.0009' }));
+ assert.strictEqual(fires, 1, 'onMessage fires exactly once for the duplicated message');
+ });
+
+ await test('integration: a genuinely new message in same channel still fires', () => {
+ const threads = new ActivatedThreads();
+ const seen = new SeenEvents();
+ let fires = 0;
+ const ingest = (event) => {
+ const { trigger } = shouldTrigger(event, BOT_ID, CHANNEL, threads);
+ if (!trigger) return;
+ const key = dedupKey(event);
+ if (key && seen.seen(key)) return;
+ fires++;
+ };
+ ingest(ev({ type: 'app_mention', text: `<@${BOT_ID}> one`, ts: '1900.0001' }));
+ ingest(ev({ type: 'message', text: `<@${BOT_ID}> one`, ts: '1900.0001' })); // dup
+ ingest(ev({ type: 'app_mention', text: `<@${BOT_ID}> two`, ts: '1900.0002' })); // new
+ assert.strictEqual(fires, 2, 'distinct ts values each fire once');
+ });
+
console.log(failures === 0 ? '\nall passed' : `\n${failures} failure(s)`);
process.exit(failures === 0 ? 0 : 1);
})();