Skip to content

Commit 9317aad

Browse files
authored
feat(slack): add opt-in scoped presence events (#108510)
* feat(slack): add opt-in presence events * style(slack): satisfy presence lint rules * chore: keep release changelog centralized * fix(slack): satisfy presence integration gates * fix(slack): preserve eligible presence targets
1 parent d3dcb36 commit 9317aad

17 files changed

Lines changed: 836 additions & 21 deletions
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
50c32bcc6b56dcfd033d131a5d616f84129d8f71e0ff078af01f53e2ad9b8534 config-baseline.json
2-
d6d937acf4f30846ba0122f3798f3e13dd60249414e31f9eeae87272991daac9 config-baseline.core.json
3-
7014814073220be9ff934dd1332d45d0a979d41a02842b337a0198596034562e config-baseline.channel.json
4-
5448611186a80c70279825b5a6ed6fbea21d5efb8d07eeba4dfb3055566bee4d config-baseline.plugin.json
1+
644812f4bad7795ad2176e518ac1d2a7aed65ba004d738c31b08bea899793179 config-baseline.json
2+
bffe3c4e08c881864a08c48a4d633328dc8ed2ad902f2e127af57f3a75cceb30 config-baseline.core.json
3+
b03d17b85699d6afaee87ec6f5a71e5f0ab0e12ec12d7a57a06b9ab076c466a6 config-baseline.channel.json
4+
94c4a99b19db7e1e3b516e491000b402ad419787026e94aade8b235ca0a27b04 config-baseline.plugin.json
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
25f96bb0ea9201fa0a2b47156911297de8fd0a83af806c63bd6679c60511b1b8 plugin-sdk-api-baseline.json
2-
eb7359b5c19b6543da999194471f576fe715f099aa1c44e81cfe5d307275f2b6 plugin-sdk-api-baseline.jsonl
1+
d79413170fd0a7a9601c36231fe72c691248cf667e02c80232756e0baad44549 plugin-sdk-api-baseline.json
2+
3b0b2398c5c26b6605c7e7b851c77073137b6a2655c2355cca6340f3acc38278 plugin-sdk-api-baseline.jsonl

‎docs/channels/slack.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1784,6 +1784,7 @@ Same-chat `/approve` also works in Slack channels and DMs that already support c
17841784
- Thread broadcasts ("Also send to channel" thread replies) are processed as normal user messages.
17851785
- Reaction add/remove events are mapped into system events.
17861786
- Member join/leave, channel created/renamed, and pin add/remove events are mapped into system events.
1787+
- Optional presence polling can map an observed human participant's `away` to `active` transition into the participant's most recently active eligible Slack session. The default is off.
17871788
- `channel_id_changed` can migrate channel config keys when `configWrites` is enabled.
17881789
- Channel topic/purpose metadata is treated as untrusted context and can be injected into routing context.
17891790
- Thread starter and initial thread-history context seeding are filtered by configured sender allowlists when applicable.
@@ -1795,6 +1796,32 @@ Same-chat `/approve` also works in Slack channels and DMs that already support c
17951796

17961797
Define global or message shortcuts in your Slack app configuration and use any non-empty callback ID. OpenClaw acknowledges matching shortcut payloads, applies the same DM/channel sender policy as other Slack interactions, and queues the sanitized event for the routed agent session. Trigger IDs and response URLs are redacted from agent context.
17971798

1799+
### Presence events
1800+
1801+
Slack does not send presence changes through the Events API or Socket Mode. OpenClaw can instead poll [`users.getPresence`](https://docs.slack.dev/reference/methods/users.getPresence/) for human participants whose messages passed normal Slack access and routing checks.
1802+
1803+
```json5
1804+
{
1805+
channels: {
1806+
slack: {
1807+
presenceEvents: { mode: "auto" },
1808+
channels: {
1809+
C0123456789: { presenceEvents: { mode: "on" } },
1810+
C0987654321: { presenceEvents: { mode: "off" } },
1811+
},
1812+
},
1813+
},
1814+
}
1815+
```
1816+
1817+
- `off` (default): no presence timer or Slack API calls.
1818+
- `auto`: monitor DMs, MPIMs, and Slack threads active in the last 24 hours with at most 8 observed human participants. Top-level channel sessions are excluded.
1819+
- `on`: monitor the same conversations without the participant cap and include top-level channel sessions. Use a per-channel override to force or suppress one channel.
1820+
1821+
OpenClaw polls at most 45 unique users per minute per Slack account, seeds the first result without waking the agent, and only wakes on an observed `away` to `active` transition. A durable 8-hour cooldown applies per Slack account and user, even if that person participates in several threads. The event routes only to that person's most recently active eligible conversation and tells the agent to consult memory/wiki and known timezone context before deciding whether to send one short greeting. The agent may stay silent.
1822+
1823+
The bot token needs `users:read`, which is already included in the recommended manifest. Presence events are unavailable for Enterprise Grid org-wide installs.
1824+
17981825
## Configuration reference
17991826

18001827
Primary reference: [Configuration reference - Slack](/gateway/config-channels#slack).
@@ -1806,6 +1833,7 @@ Primary reference: [Configuration reference - Slack](/gateway/config-channels#sl
18061833
- compatibility toggle: `dangerouslyAllowNameMatching` (break-glass; keep off unless needed)
18071834
- channel access: `groupPolicy`, `channels.*`, `channels.*.users`, `channels.*.requireMention`
18081835
- threading/history: `replyToMode`, `replyToModeByChatType`, `thread.*`, `historyLimit`, `dmHistoryLimit`, `dms.*.historyLimit`
1836+
- presence wakes: `presenceEvents.mode`, `channels.*.presenceEvents.mode` (`off|auto|on`; default `off`)
18091837
- delivery: `textChunkLimit`, `streaming.chunkMode`, `mediaMaxMb`, `streaming`, `streaming.nativeTransport`, `streaming.preview.toolProgress`
18101838
- unfurls: `unfurlLinks` (default: `false`), `unfurlMedia` for `chat.postMessage` link/media preview control; set `unfurlLinks: true` to opt back into link previews
18111839
- ops/features: `configWrites`, `commands.native`, `slashCommand.*`, `actions.*`, `userToken`, `userTokenReadOnly`

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
895895
- H3: Plugin-owned modal submissions
896896
- H2: Native approvals in Slack
897897
- H2: Events and operational behavior
898+
- H3: Presence events
898899
- H2: Configuration reference
899900
- H2: Troubleshooting
900901
- H2: Attachment media reference

‎extensions/slack/src/config-schema.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,20 @@ describe("slack config schema", () => {
3838
}
3939
});
4040

41+
it("keeps presence events off by default and accepts account/channel modes", () => {
42+
const absent = SlackConfigSchema.safeParse({});
43+
expect(absent.success).toBe(true);
44+
if (absent.success) {
45+
expect(absent.data.presenceEvents).toBeUndefined();
46+
}
47+
expectSlackConfigValid({ presenceEvents: { mode: "auto" } });
48+
expectSlackConfigValid({
49+
accounts: { ops: { presenceEvents: { mode: "on" } } },
50+
channels: { C123: { presenceEvents: { mode: "off" } } },
51+
});
52+
expectSlackConfigIssue({ presenceEvents: { mode: "enabled" } }, "presenceEvents.mode");
53+
});
54+
4155
it("accepts historyLimit overrides per account", () => {
4256
const res = SlackConfigSchema.safeParse({
4357
historyLimit: 7,

‎extensions/slack/src/config-ui-hints.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,18 @@ export const slackChannelConfigUiHints = {
102102
label: "Slack Exec Approvals",
103103
help: "Slack-native exec approval routing and approver authorization. When unset, OpenClaw auto-enables DM-first native approvals if approvers can be resolved for this workspace account.",
104104
},
105+
presenceEvents: {
106+
label: "Slack Presence Events",
107+
help: 'Poll observed human participants and wake the routed agent on away-to-active transitions. Default: "off".',
108+
},
109+
"presenceEvents.mode": {
110+
label: "Slack Presence Event Mode",
111+
help: '"off" disables polling; "auto" covers DMs, MPIMs, and recent threads with up to 8 observed people; "on" also covers larger threads and top-level channels.',
112+
},
113+
"channels.*.presenceEvents.mode": {
114+
label: "Slack Channel Presence Event Mode",
115+
help: 'Override presence events for one Slack channel. Use "on" to include large threads or top-level channel sessions.',
116+
},
105117
"execApprovals.enabled": {
106118
label: "Slack Exec Approvals Enabled",
107119
help: 'Controls Slack native exec approvals for this account: unset or "auto" enables DM-first native approvals when approvers can be resolved, true forces native approvals on, and false disables them.',

‎extensions/slack/src/monitor/channel-config.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
import type {
88
ChannelBotLoopProtectionConfig,
99
ReplyToMode,
10+
SlackChannelConfig,
1011
} from "openclaw/plugin-sdk/config-contracts";
1112
import { mergePairLoopGuardConfig } from "openclaw/plugin-sdk/pair-loop-guard-runtime";
1213
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
@@ -23,6 +24,7 @@ export type SlackChannelConfigResolved = {
2324
users?: Array<string | number>;
2425
skills?: string[];
2526
systemPrompt?: string;
27+
presenceEvents?: SlackChannelConfig["presenceEvents"];
2628
matchKey?: string;
2729
matchSource?: ChannelMatchSource;
2830
};
@@ -37,6 +39,7 @@ type SlackChannelConfigEntry = {
3739
users?: Array<string | number>;
3840
skills?: string[];
3941
systemPrompt?: string;
42+
presenceEvents?: SlackChannelConfig["presenceEvents"];
4043
};
4144

4245
export type SlackChannelConfigEntries = Record<string, SlackChannelConfigEntry>;
@@ -130,6 +133,7 @@ export function resolveSlackChannelConfig(params: {
130133
const users = firstDefined(resolved.users, fallback?.users);
131134
const skills = firstDefined(resolved.skills, fallback?.skills);
132135
const systemPrompt = firstDefined(resolved.systemPrompt, fallback?.systemPrompt);
136+
const presenceEvents = firstDefined(resolved.presenceEvents, fallback?.presenceEvents);
133137
const result: SlackChannelConfigResolved = {
134138
allowed,
135139
requireMention,
@@ -140,6 +144,7 @@ export function resolveSlackChannelConfig(params: {
140144
users,
141145
skills,
142146
systemPrompt,
147+
presenceEvents,
143148
};
144149
return applyChannelMatchMeta(result, match);
145150
}

‎extensions/slack/src/monitor/message-handler.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
buildSlackDebounceKey,
2424
buildTopLevelSlackConversationKey,
2525
} from "./message-handler/debounce-key.js";
26+
import type { PreparedSlackMessage } from "./message-handler/types.js";
2627
import { createSlackThreadTsResolver } from "./thread-resolution.js";
2728

2829
const loadSlackMessagePipeline = createLazyRuntimeModule(
@@ -103,8 +104,10 @@ export function createSlackMessageHandler(params: {
103104
account: ResolvedSlackAccount;
104105
/** Called on each inbound event to update liveness tracking. */
105106
trackEvent?: () => void;
107+
/** Called after access/routing preparation accepts a human message. */
108+
onPrepared?: (prepared: PreparedSlackMessage) => void;
106109
}): SlackMessageHandler {
107-
const { ctx, account, trackEvent } = params;
110+
const { ctx, account, trackEvent, onPrepared } = params;
108111
const { debounceMs, debouncer } = createChannelInboundDebouncer<{
109112
message: SlackMessageEvent;
110113
opts: QueuedSlackMessageOptions;
@@ -261,6 +264,7 @@ export function createSlackMessageHandler(params: {
261264
if (!prepared) {
262265
return;
263266
}
267+
onPrepared?.(prepared);
264268
if (entries.length > 1) {
265269
const ids = entries.map((entry) => entry.message.ts).filter(Boolean) as string[];
266270
if (ids.length > 0) {
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
3+
const openSyncKeyedStore = vi.hoisted(() => vi.fn(() => ({})));
4+
5+
vi.mock("../runtime.js", () => ({
6+
getSlackRuntime: () => ({ state: { openSyncKeyedStore } }),
7+
}));
8+
9+
import { openSlackPresenceCooldownStore } from "./presence-cooldown-store.js";
10+
11+
describe("openSlackPresenceCooldownStore", () => {
12+
it("preserves active cooldowns by rejecting new users at capacity", () => {
13+
openSlackPresenceCooldownStore();
14+
15+
expect(openSyncKeyedStore).toHaveBeenCalledWith(
16+
expect.objectContaining({
17+
maxEntries: 25_000,
18+
overflowPolicy: "reject-new",
19+
}),
20+
);
21+
});
22+
});
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Slack plugin module persists presence-greeting cooldowns across gateway restarts.
2+
import type { PluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-runtime";
3+
import { getSlackRuntime } from "../runtime.js";
4+
import { SLACK_PRESENCE_GREETING_COOLDOWN_MS } from "./presence-monitor.js";
5+
6+
const SLACK_PRESENCE_COOLDOWN_MAX_ENTRIES = 25_000;
7+
8+
export function openSlackPresenceCooldownStore(): PluginStateSyncKeyedStore<number> {
9+
return getSlackRuntime().state.openSyncKeyedStore<number>({
10+
namespace: "presence-greeting-cooldowns",
11+
maxEntries: SLACK_PRESENCE_COOLDOWN_MAX_ENTRIES,
12+
overflowPolicy: "reject-new",
13+
defaultTtlMs: SLACK_PRESENCE_GREETING_COOLDOWN_MS,
14+
});
15+
}

0 commit comments

Comments
 (0)