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
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
fix(slack): trigger only on @-mentions and activated-thread replies
Chaitanya Girie6dc569ee294
diff --git a/src/main/slack-trigger.cjs b/src/main/slack-trigger.cjsnew file mode 100644index 00000000..9120761c--- /dev/null+++ b/src/main/slack-trigger.cjs@@ -0,0 +1,85 @@+'use strict';++// Pure trigger-decision logic for the Slack mention filter.+// Extracted as plain CommonJS so test/slack.test.cjs can require() it directly+// without a TypeScript compile step — same pattern as compact-gate.cjs.+//+// Responsibilities:+// - isMention: ev.type==='app_mention' OR text includes <@botUserId>+// - activatedThreads: bounded FIFO set of thread roots where the bot was mentioned+// - shouldTrigger: combines channel filter, self-loop safety, mention/thread check++/** Maximum number of thread roots to remember. FIFO eviction above this limit+ * prevents unbounded memory growth in long-running bots. */+const ACTIVATED_THREADS_MAX = 500;++/**+ * Bounded FIFO set of thread timestamps where the bot was @-mentioned.+ * Once the bot is mentioned in a thread, all subsequent replies in that+ * thread trigger onMessage — until the entry is FIFO-evicted.+ */+class ActivatedThreads {+ constructor(maxSize = ACTIVATED_THREADS_MAX) {+ this.maxSize = maxSize;+ this._set = new Set();+ this._order = []; // FIFO eviction queue — parallel to _set+ }++ add(threadTs) {+ if (this._set.has(threadTs)) return; // already tracked+ if (this._set.size >= this.maxSize) {+ const oldest = this._order.shift();+ if (oldest !== undefined) this._set.delete(oldest);+ }+ this._set.add(threadTs);+ this._order.push(threadTs);+ }++ has(threadTs) { return this._set.has(threadTs); }+ get size() { return this._set.size; }+}++/**+ * Decide whether a Slack event should trigger onMessage.+ *+ * @param ev - The `payload.event` object (any shape, may be partial)+ * @param botUserId - Cached bot user id (string) or null if not yet known+ * @param channelId - Channel filter (string) or null/undefined for any channel+ * @param activatedThreads - Mutable ActivatedThreads instance (mutated on mention)+ * @returns {{ trigger: boolean, text: string }} — trigger: whether to fire onMessage;+ * text: the raw ev.text string (stripping is done in the caller)+ */+function shouldTrigger(ev, botUserId, channelId, activatedThreads) {+ if (!ev) return { trigger: false, text: '' };++ // Channel filter+ const channelOk = !channelId || ev.channel === channelId;+ if (!channelOk) return { trigger: false, text: '' };++ // Self-loop + subtype safety: never trigger on edits/joins/bot posts.+ // ev.subtype is set for message-changed, channel-join, etc.+ if (ev.subtype || ev.bot_id) return { trigger: false, text: '' };++ const text = typeof ev.text === 'string' ? ev.text : '';++ // Is this an @-mention of the bot?+ const isMention =+ ev.type === 'app_mention' ||+ (ev.type === 'message' && botUserId != null && text.includes(`<@${botUserId}>`));++ // Is this a reply inside a thread where the bot was already mentioned?+ const isActivatedThread = !!(ev.thread_ts && activatedThreads.has(ev.thread_ts));++ if (!isMention && !isActivatedThread) return { trigger: false, text: '' };++ // On mention: activate the thread so future replies in it also trigger.+ // Use thread_ts if the mention is itself a reply, else the message's own ts.+ if (isMention) {+ const threadRoot = ev.thread_ts || ev.ts;+ if (threadRoot) activatedThreads.add(threadRoot);+ }++ return { trigger: true, text };+}++module.exports = { shouldTrigger, ActivatedThreads, ACTIVATED_THREADS_MAX };diff --git a/src/main/slack.ts b/src/main/slack.tsindex 4893e07b..6aea53ad 100644--- a/src/main/slack.ts+++ b/src/main/slack.ts@@ -27,6 +27,24 @@ import { createHmac, timingSafeEqual } from 'node:crypto';// `openTunnel()` instead — Rollup preserves dynamic import() in CJS output, which// 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 {+ shouldTrigger: (+ ev: SlackPayload['event'],+ botUserId: string | null,+ channelId: string | undefined,+ activatedThreads: _IActivatedThreads+ ) => { trigger: boolean; text: string };+ ActivatedThreads: new (maxSize?: number) => _IActivatedThreads;+ };++interface _IActivatedThreads {+ add(threadTs: string): void;+ has(threadTs: string): boolean;+ readonly size: number;+}+export interface SlackWebhookServerOptions {/** Local TCP port the HTTP server binds to (and the tunnel forwards to). */port: number;@@ -65,6 +83,12 @@ export class SlackWebhookServer {private readonly signingSecret: string;private readonly channelId?: string;private readonly onMessage: (m: SlackInboundMessage) => void;+ /** Bot's own Slack user id — learned from `authorizations[].user_id` on the+ * first event_callback. Used to detect <@BOTID> text mentions. */+ private botUserId: string | null = null;+ /** 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();constructor(opts: SlackWebhookServerOptions) {this.port = opts.port;@@ -177,18 +201,22 @@ export class SlackWebhookServer {return;}- // 3) Real events: only plain user messages (no subtype = not an edit/join/- // bot post), optionally filtered to one channel.+ // 3) Real events: only @-mentions or replies in activated threads — not every+ // plain channel message. Cache the bot user id from authorizations so we+ // can detect text mentions (<@BOTID>) without an extra API scope.if (payload.type === 'event_callback' && payload.event) {+ // Learn the bot's own user id on first sighting (present on every event_callback).+ const authUserId = payload.authorizations?.[0]?.user_id;+ if (authUserId && !this.botUserId) this.botUserId = authUserId;+const ev = payload.event;- const isPlainMessage = ev.type === 'message' && !ev.subtype && !ev.bot_id;- const channelOk = !this.channelId || ev.channel === this.channelId;- if (isPlainMessage && channelOk) {- const text = stripLeadingMention(typeof ev.text === 'string' ? ev.text : '');+ const { trigger, text: rawText } = _shouldTrigger(+ ev, this.botUserId, this.channelId, this.activatedThreads+ );+ if (trigger) {+ const text = stripLeadingMention(rawText);const channel = typeof ev.channel === 'string' ? ev.channel : '';const ts = typeof ev.ts === 'string' ? ev.ts : '';- // Reply under the original message's thread; if the event is itself a- // threaded reply, stay in that thread, else open one rooted at its ts.const thread_ts = (typeof ev.thread_ts === 'string' && ev.thread_ts) || ts;if (text && channel && ts) {try { this.onMessage({ text, channel, ts, thread_ts }); } catch { /* delivery is best-effort */ }@@ -231,7 +259,11 @@ export class SlackWebhookServer {interface SlackPayload {type?: string;challenge?: string;+ /** Present on event_callback — contains the bot's own user_id so we can+ * detect <@BOTID> text mentions without any extra API scope. */+ authorizations?: { user_id?: string }[];event?: {+ /** 'message' for regular channel messages; 'app_mention' for @-mentions. */type?: string;subtype?: string;bot_id?: string;diff --git a/test/slack.test.cjs b/test/slack.test.cjsnew file mode 100644index 00000000..9b6cf3a3--- /dev/null+++ b/test/slack.test.cjs@@ -0,0 +1,204 @@+'use strict';++const assert = require('assert');+const { shouldTrigger, ActivatedThreads, ACTIVATED_THREADS_MAX } =+ require('../src/main/slack-trigger.cjs');++let failures = 0;+async function test(name, fn) {+ try {+ await fn();+ console.log(` ✓ ${name}`);+ } catch (err) {+ failures++;+ console.log(` ✗ ${name}\n ${err.message}`);+ }+}++const BOT_ID = 'U12345BOT';+const CHANNEL = 'C99999';++function ev(overrides = {}) {+ return {+ type: 'message',+ channel: CHANNEL,+ text: 'hello',+ ts: '1000.0001',+ thread_ts: undefined,+ bot_id: undefined,+ subtype: undefined,+ ...overrides,+ };+}++(async () => {+ console.log('slack trigger tests (mention + activated-thread filter)');++ // ─── Case 1: plain message, no mention, no active thread → NOT triggered ───++ await test('plain message with no mention and no active thread → NOT triggered', () => {+ const threads = new ActivatedThreads();+ const result = shouldTrigger(ev({ text: 'hello world' }), BOT_ID, null, threads);+ assert.strictEqual(result.trigger, false);+ assert.strictEqual(threads.size, 0, 'thread must not be activated');+ });++ // ─── Case 2: message mentioning bot → triggered + thread activated ──────────++ await test('message with @mention → triggered and thread root activated', () => {+ const threads = new ActivatedThreads();+ const result = shouldTrigger(+ ev({ text: `<@${BOT_ID}> please help`, ts: '1000.0002' }),+ BOT_ID, null, threads+ );+ assert.strictEqual(result.trigger, true);+ assert.ok(result.text.includes('please help'), 'text forwarded');+ assert.ok(threads.has('1000.0002'), 'message ts activated as thread root');+ });++ await test('app_mention event type → triggered even without text mention', () => {+ const threads = new ActivatedThreads();+ const result = shouldTrigger(+ ev({ type: 'app_mention', text: 'do something', ts: '1000.0003' }),+ null, null, threads // botUserId=null — type alone is enough+ );+ assert.strictEqual(result.trigger, true);+ assert.ok(threads.has('1000.0003'), 'app_mention activates thread root');+ });++ // ─── Case 3: reply in activated thread (no mention) → triggered ─────────────++ await test('reply in activated thread without re-mention → triggered', () => {+ const threads = new ActivatedThreads();+ // First: mention activates the thread+ shouldTrigger(ev({ text: `<@${BOT_ID}> start`, ts: '2000.0001' }), BOT_ID, null, threads);+ assert.ok(threads.has('2000.0001'));+ // Then: a plain reply in that thread triggers+ const result = shouldTrigger(+ ev({ text: 'follow-up question', ts: '2000.0002', thread_ts: '2000.0001' }),+ BOT_ID, null, threads+ );+ assert.strictEqual(result.trigger, true, 'thread reply should trigger');+ assert.strictEqual(result.text, 'follow-up question');+ });++ // ─── Case 4: bot's own reply (bot_id set) → NOT triggered ───────────────────++ await test("bot's own threaded reply (bot_id) → NOT triggered (self-loop safety)", () => {+ const threads = new ActivatedThreads();+ // Activate the thread first+ shouldTrigger(ev({ text: `<@${BOT_ID}> hi`, ts: '3000.0001' }), BOT_ID, null, threads);+ // Bot posts a reply — must NOT trigger+ const result = shouldTrigger(+ ev({ text: 'I am the bot response', ts: '3000.0002', thread_ts: '3000.0001', bot_id: 'B_BOT' }),+ BOT_ID, null, threads+ );+ assert.strictEqual(result.trigger, false, 'bot reply must not loop back');+ });++ await test('subtype message (e.g. message_changed) → NOT triggered', () => {+ const threads = new ActivatedThreads();+ const result = shouldTrigger(+ ev({ text: `<@${BOT_ID}> edit`, subtype: 'message_changed' }),+ BOT_ID, null, threads+ );+ assert.strictEqual(result.trigger, false);+ });++ // ─── Case 5: mention inside sub-thread → activates ev.thread_ts ─────────────++ await test('mention in a reply → activates ev.thread_ts (not ev.ts)', () => {+ const threads = new ActivatedThreads();+ const rootTs = '4000.0001';+ const replyTs = '4000.0099';+ // Bot is mentioned in a reply (not a root message)+ const result = shouldTrigger(+ ev({ text: `<@${BOT_ID}> help in thread`, ts: replyTs, thread_ts: rootTs }),+ BOT_ID, null, threads+ );+ assert.strictEqual(result.trigger, true);+ // thread_ts is the key, not ts+ assert.ok(threads.has(rootTs), 'thread root activated');+ assert.ok(!threads.has(replyTs), 'reply ts not stored as root');+ });++ // ─── Case 6: channel filter respected ────────────────────────────────────────++ await test('wrong channel → NOT triggered even with mention', () => {+ const threads = new ActivatedThreads();+ const result = shouldTrigger(+ ev({ text: `<@${BOT_ID}> help`, channel: 'C_OTHER' }),+ BOT_ID, CHANNEL, threads // channelId = CHANNEL, event is in C_OTHER+ );+ assert.strictEqual(result.trigger, false);+ assert.strictEqual(threads.size, 0, 'wrong-channel mention must not activate thread');+ });++ await test('matching channel → triggered', () => {+ const threads = new ActivatedThreads();+ const result = shouldTrigger(+ ev({ text: `<@${BOT_ID}> hello`, channel: CHANNEL }),+ BOT_ID, CHANNEL, threads+ );+ assert.strictEqual(result.trigger, true);+ });++ await test('no channel filter (null) → any channel triggers', () => {+ const threads = new ActivatedThreads();+ const result = shouldTrigger(+ ev({ text: `<@${BOT_ID}> hi`, channel: 'C_RANDOM' }),+ BOT_ID, null, threads+ );+ assert.strictEqual(result.trigger, true);+ });++ // ─── Case 7: activatedThreads bound enforced ─────────────────────────────────++ await test('activatedThreads evicts oldest when cap is reached', () => {+ const maxSize = 3;+ const threads = new ActivatedThreads(maxSize);+ // Fill to cap+ threads.add('t1');+ threads.add('t2');+ threads.add('t3');+ assert.strictEqual(threads.size, maxSize);+ // Add one more — t1 should be evicted (FIFO)+ threads.add('t4');+ assert.strictEqual(threads.size, maxSize, 'size stays at cap');+ assert.ok(!threads.has('t1'), 't1 evicted');+ assert.ok(threads.has('t2'), 't2 still present');+ assert.ok(threads.has('t3'), 't3 still present');+ assert.ok(threads.has('t4'), 't4 added');+ });++ await test('default cap is ACTIVATED_THREADS_MAX', () => {+ assert.strictEqual(ACTIVATED_THREADS_MAX, 500);+ const threads = new ActivatedThreads();+ // Fill to cap + 1 — size must stay at ACTIVATED_THREADS_MAX+ for (let i = 0; i <= ACTIVATED_THREADS_MAX; i++) threads.add(`t${i}`);+ assert.strictEqual(threads.size, ACTIVATED_THREADS_MAX);+ assert.ok(!threads.has('t0'), 't0 evicted');+ assert.ok(threads.has(`t${ACTIVATED_THREADS_MAX}`), 'last entry present');+ });++ // ─── Edge cases ───────────────────────────────────────────────────────────────++ await test('botUserId null → text mention not detected (app_mention still works)', () => {+ const threads = new ActivatedThreads();+ // Text mention with no known botUserId → no trigger+ const r1 = shouldTrigger(ev({ text: `<@UNKNOWN> hi` }), null, null, threads);+ assert.strictEqual(r1.trigger, false);+ // app_mention type still triggers regardless+ const r2 = shouldTrigger(ev({ type: 'app_mention', text: 'hi' }), null, null, threads);+ assert.strictEqual(r2.trigger, true);+ });++ await test('null/undefined event → NOT triggered', () => {+ const threads = new ActivatedThreads();+ assert.strictEqual(shouldTrigger(null, BOT_ID, null, threads).trigger, false);+ assert.strictEqual(shouldTrigger(undefined, BOT_ID, null, threads).trigger, false);+ });++ console.log(failures === 0 ? '\nall passed' : `\n${failures} failure(s)`);+ process.exit(failures === 0 ? 0 : 1);+})();