Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(channel-reader): notify unresolved Slack senders once per day per conversation
Jose Ramireza4ef21384e33
diff --git a/channel-reader/package-lock.json b/channel-reader/package-lock.jsonindex ac29781ff..ca77df2cd 100644--- a/channel-reader/package-lock.json+++ b/channel-reader/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-channel-reader",- "version": "0.1.87",+ "version": "0.1.88","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-channel-reader",- "version": "0.1.87",+ "version": "0.1.88","license": "SEE LICENSE IN LICENSE","dependencies": {"@kubernetes/client-node": "^1.0.0",diff --git a/channel-reader/package.json b/channel-reader/package.jsonindex 2dd7ab7ba..638361ed5 100644--- a/channel-reader/package.json+++ b/channel-reader/package.json@@ -1,6 +1,6 @@{"name": "clerum-channel-reader",- "version": "0.1.87",+ "version": "0.1.88","description": "Watches CommunicationChannel CRDs and fetches messages from Telegram, Email, and Slack","main": "dist/main.js","engines": {diff --git a/channel-reader/src/main.ts b/channel-reader/src/main.tsindex 4f9557ee8..19aff3f16 100644--- a/channel-reader/src/main.ts+++ b/channel-reader/src/main.ts@@ -97,6 +97,11 @@ const RESULT_POLL_FALLBACK_INTERVAL_MS = 2 * 1000const RESULT_POLL_FALLBACK_TIMEOUT_MS = 30 * 60 * 1000/** Telegram and Slack can redeliver the same provider event while poll offsets settle. */const PROVIDER_EVENT_DEDUPE_TTL_MS = 10 * 60 * 1000 // 10 minutes+/** One "you are not linked" notice per Slack user per conversation per day. */+const UNRESOLVED_NOTICE_TTL_MS = 24 * 60 * 60 * 1000 // 24 hours+const UNRESOLVED_NOTICE_COPY =+ "I can't accept messages from this Slack account. If you haven't linked it yet, " ++ 'do that in your evenfire profile. If you think you should already have access, contact your admin.'const SLACK_VERIFICATION_SCAN_INTERVAL_MS = 60 * 1000const TOOL_APPROVAL_ACTION_RE = /^tool:([ald]):([A-Za-z0-9_-]{16})$//**@@ -281,6 +286,8 @@ export class ChannelReader {private pendingApprovals: Map<string, PendingApprovalState> = new Map()/** Recently processed provider events keyed by stable provider or channel message identity. */private processedProviderEvents: Map<string, ProcessedProviderEvent> = new Map()+ /** Unresolved-sender notices already sent, keyed by workspace + user + channel. */+ private unresolvedNoticesSent: Map<string, { seenAt: number }> = new Map()/** Adapter route key by provider + CommunicationChannel ref. */private adapterKeysByCommunicationChannel: Map<string, string> = new Map()/** Adapter route key by provider + runtime channel id. */@@ -1388,6 +1395,9 @@ export class ChannelReader {console.warn(`[Main] Ignoring unauthorized ${msg.channelType} message from ${msg.sender} in ${msg.channelId}`)+ if (authorization.reason === 'unresolved') {+ await this.sendUnresolvedSenderNotice(msg)+ }continue}}@@ -1539,6 +1549,29 @@ export class ChannelReader {return ['message', msg.channelType, msg.channelId, msg.sender, messageId].join(':')}+ /**+ * Tell an unresolved Slack sender why the agent is ignoring them, at most once+ * per user per conversation per UNRESOLVED_NOTICE_TTL_MS.+ */+ private async sendUnresolvedSenderNotice(msg: Message): Promise<void> {+ if (msg.channelType !== 'slack') return+ const identity = msg.providerIdentity+ const userId = identity?.providerUserId?.trim()+ const workspaceId = identity?.providerWorkspaceId?.trim()+ const channelId = msg.channelId?.trim()+ if (!userId || !workspaceId || !channelId) return++ const key = `${workspaceId}:${userId}:${channelId}`+ if (this.unresolvedNoticesSent.has(key)) return+ // Record on ATTEMPT, not on success: a conversation Slack keeps rejecting+ // must not produce one outbound call per inbound message.+ this.unresolvedNoticesSent.set(key, { seenAt: Date.now() })++ const adapter = this.adapterForMessage(msg)+ if (!adapter?.sendEphemeral) return+ await adapter.sendEphemeral(channelId, userId, UNRESOLVED_NOTICE_COPY)+ }+private pendingApprovalChannelScope(msg: Message): string {return `${msg.channelType}:${msg.providerIdentity?.providerChannelId || msg.channelId}`}@@ -2154,6 +2187,11 @@ export class ChannelReader {this.processedProviderEvents.delete(key)}}+ for (const [key, notice] of this.unresolvedNoticesSent) {+ if (now - notice.seenAt > UNRESOLVED_NOTICE_TTL_MS) {+ this.unresolvedNoticesSent.delete(key)+ }+ }}/**diff --git a/channel-reader/test/unresolvedSenderNotice.test.ts b/channel-reader/test/unresolvedSenderNotice.test.tsindex b6260e037..30b1332cd 100644--- a/channel-reader/test/unresolvedSenderNotice.test.ts+++ b/channel-reader/test/unresolvedSenderNotice.test.ts@@ -1,8 +1,15 @@-import { describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { ChannelReader, type ChannelReaderOptions } from '../src/main'import { RPCClient } from '../src/rpcClient'+import type { ChannelAdapter, Message } from '../src/types'const mockCfg = vi.hoisted(() => ({+ devMode: true,hostRef: 'test-host',+ mcpHostUrl: 'http://mcp-host.test',+ namespace: '',+ pollIntervalSeconds: 1,+ devChannelConfig: undefined,}))vi.mock('../src/config', () => ({@@ -74,3 +81,171 @@ describe('authorizeProviderMessage response shape', () => {expect('reason' in result).toBe(false)})})++interface BuildReaderOptions {+ /** Omit the key entirely for the default; pass `undefined` for "no reason at all". */+ reason?: 'unresolved' | 'error'+ medium?: 'slack' | 'telegram'+ ephemeralThrows?: boolean+}++/**+ * Build a ChannelReader wired to a single stub adapter and a stub rpcClient that+ * always refuses authorization, plus the seams the notice tests need:+ * `deliver` pushes one message through `handleMessages`, and `runSweep` invokes+ * the periodic cleanup that `pollCycle` runs.+ */+function buildReader(options: BuildReaderOptions = {}) {+ const medium = options.medium ?? 'slack'+ const ephemeralThrows = options.ephemeralThrows ?? false+ // `{ reason: undefined }` has to survive as "no reason", so the default is+ // applied only when the caller omits the key. A `?? 'unresolved'` default+ // would silently turn the absent-reason case into the unresolved case.+ const reason: 'unresolved' | 'error' | undefined =+ 'reason' in options ? options.reason : 'unresolved'++ const sendEphemeral = vi.fn(async (_channelId: string, _userId: string, _content: string) => {+ if (ephemeralThrows) throw new Error('user_not_in_channel')+ })++ const adapter: ChannelAdapter = {+ channelType: medium,+ connect: vi.fn(async () => undefined),+ disconnect: vi.fn(async () => undefined),+ fetchMessages: vi.fn(async () => []),+ sendMessage: vi.fn(async () => undefined),+ editMessage: vi.fn(async () => undefined),+ sendEphemeral,+ }++ const authorizeProviderMessage = vi.fn(async () =>+ reason === undefined ? { authorized: false } : { authorized: false, reason }+ )++ const rpcClient = {+ healthCheck: vi.fn(async () => true),+ sendMessage: vi.fn(async () => ({+ success: true,+ status: 'pending' as const,+ taskId: 'task-1',+ })),+ getBaseUrl: vi.fn(() => 'http://mcp-host.test'),+ getTaskResult: vi.fn(),+ sendApproval: vi.fn(),+ sendDenial: vi.fn(),+ sendWorkflowApprovalDecision: vi.fn(),+ getCronResults: vi.fn(async () => []),+ acknowledgeCronResult: vi.fn(),+ authorizeProviderMessage,+ }++ const reader = new ChannelReader({+ rpcClient: rpcClient as unknown as NonNullable<ChannelReaderOptions['rpcClient']>,+ adapters: new Map([[medium, adapter]]),+ sleep: async () => undefined,+ })++ let eventSeq = 0+ const deliver = async (channelId: string, userId: string): Promise<void> => {+ eventSeq += 1+ const message: Message = {+ channelType: medium,+ channelId,+ sender: userId,+ content: 'hello',+ timestamp: new Date(),+ messageId: `msg-${eventSeq}`,+ providerIdentity: {+ medium,+ providerUserId: userId,+ providerWorkspaceId: 'T1',+ providerChannelId: channelId,+ // Unique per delivery on purpose. A repeated providerEventId is dropped by+ // the provider-event dedupe *before* authorization runs, which would make+ // every "sent only once" assertion below pass with no rate limiter at all.+ providerEventId: `evt-${eventSeq}`,+ },+ }+ // The real Slack adapter never throws (channels/slack.ts swallows Slack+ // errors); the ephemeralThrows stub throws only to prove the limiter key is+ // recorded before the send, so a rejection here is expected in that one case.+ await reader.handleMessages([message]).catch(() => undefined)+ }++ const runSweep = (): void => {+ ;(reader as unknown as { cleanupStaleApprovals(): void }).cleanupStaleApprovals()+ }++ return { deliver, runSweep, sendEphemeral, adapter, authorizeProviderMessage }+}++describe('unresolved sender notice', () => {+ afterEach(() => {+ vi.useRealTimers()+ })++ it('sends once, and not again for the same user and channel within 24h', async () => {+ vi.useFakeTimers()+ const { deliver, sendEphemeral } = buildReader()+ await deliver('C1', 'U1')+ await deliver('C1', 'U1')+ expect(sendEphemeral).toHaveBeenCalledTimes(1)+ })++ it('sends again after the TTL expires and the sweep runs', async () => {+ vi.useFakeTimers()+ const { deliver, sendEphemeral, runSweep } = buildReader()+ await deliver('C1', 'U1')+ await vi.advanceTimersByTimeAsync(23 * 60 * 60 * 1000)+ runSweep()+ await deliver('C1', 'U1')+ expect(sendEphemeral).toHaveBeenCalledTimes(1)++ await vi.advanceTimersByTimeAsync(2 * 60 * 60 * 1000)+ runSweep()+ await deliver('C1', 'U1')+ expect(sendEphemeral).toHaveBeenCalledTimes(2)+ })++ it('treats a second channel as its own conversation', async () => {+ vi.useFakeTimers()+ const { deliver, sendEphemeral } = buildReader()+ await deliver('C1', 'U1')+ await deliver('C2', 'U1')+ expect(sendEphemeral).toHaveBeenCalledTimes(2)+ })++ it('treats a second user in the same channel as its own recipient', async () => {+ vi.useFakeTimers()+ const { deliver, sendEphemeral } = buildReader()+ await deliver('C1', 'U1')+ await deliver('C1', 'U2')+ expect(sendEphemeral).toHaveBeenCalledTimes(2)+ })++ it('records the key even when sendEphemeral throws, so one failure is not retried forever', async () => {+ vi.useFakeTimers()+ const { deliver, sendEphemeral } = buildReader({ ephemeralThrows: true })+ await deliver('C1', 'U1')+ await deliver('C1', 'U1')+ expect(sendEphemeral).toHaveBeenCalledTimes(1)+ })++ it('never sends on reason error', async () => {+ const { deliver, sendEphemeral } = buildReader({ reason: 'error' })+ await deliver('C1', 'U1')+ expect(sendEphemeral).not.toHaveBeenCalled()+ })++ it('never sends when the reason is absent', async () => {+ const { deliver, sendEphemeral } = buildReader({ reason: undefined })+ await deliver('C1', 'U1')+ expect(sendEphemeral).not.toHaveBeenCalled()+ })++ it('never sends for a non-Slack medium', async () => {+ const { deliver, sendEphemeral } = buildReader({ medium: 'telegram' })+ await deliver('C1', 'U1')+ expect(sendEphemeral).not.toHaveBeenCalled()+ })+})