Skip to main content

orch/channels/
slack.rs

1//! Slack channel — receives commands and streams agent output.
2//!
3//! Uses the Slack Web API with HTTP polling (conversations.history) to receive
4//! messages and the chat.postMessage API to send responses.
5//!
6//! Configuration in `~/.orch/config.yml`:
7//! ```yaml
8//! channels:
9//!   slack:
10//!     bot_token: "xoxb-..."       # Bot User OAuth Token
11//!     channel_id: "C1234567890"   # Channel to monitor and post to
12//!     allowed_user_ids: ["U1234567890"]  # required: other senders are dropped
13//! ```
14//!
15//! The bot token requires the following OAuth scopes:
16//! - `channels:history` / `groups:history` — read messages
17//! - `chat:write` — post messages
18//! - `channels:read` — health check
19
20use super::access::Access;
21use super::{Channel, IncomingMessage, OutgoingMessage, Poller};
22use anyhow::Context;
23use async_trait::async_trait;
24use chrono::{DateTime, Utc};
25use reqwest::Client;
26use serde::Deserialize;
27use sha2::{Digest, Sha256};
28use std::fmt;
29use std::fmt::Debug;
30use std::fmt::Formatter;
31use std::fmt::Write as _;
32use std::sync::Arc;
33use std::time::Duration;
34use tokio::sync::Mutex;
35use tokio::sync::mpsc;
36use tokio::sync::mpsc::Receiver;
37use tokio::time;
38
39pub struct SlackChannel {
40    pub bot_token: String,
41    pub client: Client,
42    pub channel_id: Option<String>,
43    /// Cursor tracking the latest message timestamp seen (Slack uses `ts` as cursor).
44    pub last_ts: Arc<Mutex<Option<String>>>,
45    access: Access,
46    poller: Poller,
47}
48
49impl Debug for SlackChannel {
50    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
51        f.debug_struct("SlackChannel")
52            .field("channel_id", &self.channel_id)
53            .finish_non_exhaustive()
54    }
55}
56
57#[derive(Deserialize)]
58struct SlackMessage {
59    #[serde(rename = "type")]
60    msg_type: Option<String>,
61    ts: String,
62    /// Absent for bot-posted messages; present for human users.
63    user: Option<String>,
64    /// Present for bot messages.
65    bot_id: Option<String>,
66    text: Option<String>,
67}
68
69#[derive(Deserialize)]
70struct ResponseMetadata {
71    next_cursor: Option<String>,
72}
73
74#[derive(Deserialize)]
75struct ConversationsHistoryResponse {
76    ok: bool,
77    messages: Option<Vec<SlackMessage>>,
78    error: Option<String>,
79    has_more: Option<bool>,
80    response_metadata: Option<ResponseMetadata>,
81}
82
83#[derive(Deserialize)]
84struct PostMessageResponse {
85    ok: bool,
86    error: Option<String>,
87}
88
89#[derive(Deserialize)]
90struct AuthTestResponse {
91    ok: bool,
92    error: Option<String>,
93}
94
95impl SlackChannel {
96    pub fn new(bot_token: String, channel_id: Option<String>) -> anyhow::Result<Self> {
97        let client = Client::builder()
98            .timeout(Duration::from_secs(30))
99            .build()
100            .context("failed to build HTTP client")?;
101
102        Ok(Self {
103            bot_token,
104            client,
105            channel_id,
106            last_ts: Arc::new(Mutex::new(None)),
107            access: Access::default(),
108            poller: Poller::default(),
109        })
110    }
111
112    /// Restrict incoming messages to `channel_id`, `extra_channels` and the given user IDs.
113    /// With no channel or no user, every incoming message is dropped
114    #[must_use]
115    pub fn with_access(mut self, extra_channels: Vec<String>, user_ids: Vec<String>) -> Self {
116        let channels = self.channel_id.iter().cloned().chain(extra_channels);
117        self.access = Access::new(channels, user_ids);
118        self
119    }
120
121    fn api_url(method: &str) -> String {
122        format!("https://slack.com/api/{method}")
123    }
124
125    /// Fetch messages newer than `oldest` from a channel
126    ///
127    /// `oldest` is the Slack `ts` of the last processed message (exclusive lower bound).
128    /// With a cursor, pages until `has_more` is false. With none, one newest-first page seeds the cursor
129    async fn get_messages(
130        &self,
131        channel_id: &str,
132        oldest: Option<String>,
133    ) -> anyhow::Result<Vec<SlackMessage>> {
134        let mut all_messages: Vec<SlackMessage> = Vec::new();
135        let mut cursor: Option<String> = None;
136
137        loop {
138            let mut params = vec![
139                ("channel", channel_id.to_string()),
140                ("limit", "200".to_string()),
141            ];
142
143            if let Some(ref ts) = oldest {
144                params.push(("oldest", ts.clone()));
145            }
146
147            if let Some(ref c) = cursor {
148                params.push(("cursor", c.clone()));
149            }
150
151            let response = self
152                .client
153                .get(Self::api_url("conversations.history"))
154                .bearer_auth(&self.bot_token)
155                .query(&params)
156                .send()
157                .await?;
158
159            if !response.status().is_success() {
160                let body = response.text().await.unwrap_or_default();
161                anyhow::bail!("slack API HTTP error: {body}");
162            }
163
164            let result: ConversationsHistoryResponse = response.json().await?;
165
166            if !result.ok {
167                let err = result.error.as_deref().unwrap_or("unknown");
168                anyhow::bail!("slack conversations.history error: {err}");
169            }
170
171            all_messages.extend(result.messages.unwrap_or_default());
172
173            if oldest.is_none() {
174                break;
175            }
176
177            let has_more = result.has_more.unwrap_or(false);
178            let next_cursor = result
179                .response_metadata
180                .and_then(|m| m.next_cursor)
181                .filter(|c| !c.is_empty());
182
183            if !has_more || next_cursor.is_none() {
184                break;
185            }
186
187            cursor = next_cursor;
188        }
189
190        Ok(all_messages)
191    }
192
193    async fn send_message(&self, channel_id: &str, text: &str) -> anyhow::Result<()> {
194        let response = self
195            .client
196            .post(Self::api_url("chat.postMessage"))
197            .bearer_auth(&self.bot_token)
198            .json(&serde_json::json!({
199                "channel": channel_id,
200                "text": text,
201                "mrkdwn": true
202            }))
203            .send()
204            .await?;
205
206        if !response.status().is_success() {
207            let body = response.text().await.unwrap_or_default();
208            anyhow::bail!("slack API HTTP error: {body}");
209        }
210
211        let result: PostMessageResponse = response.json().await?;
212
213        if !result.ok {
214            let err = result.error.as_deref().unwrap_or("unknown");
215            anyhow::bail!("slack chat.postMessage error: {err}");
216        }
217
218        Ok(())
219    }
220}
221
222fn slack_ts_now() -> String {
223    let now = Utc::now();
224    format!("{}.{:06}", now.timestamp(), now.timestamp_subsec_micros())
225}
226
227/// First poll (`last_ts` is None) seeds the cursor from the newest ts or `now_ts` and emits nothing
228/// Later polls move `last_ts` to the newest returned ts, then emit only allowed human messages
229fn ingest_poll(
230    last_ts: &mut Option<String>,
231    messages: &[SlackMessage],
232    channel_id: &str,
233    now_ts: &str,
234    access: &Access,
235) -> Vec<IncomingMessage> {
236    let newest = messages.iter().map(|msg| msg.ts.as_str()).max();
237
238    if last_ts.is_none() {
239        let seed = newest.unwrap_or(now_ts);
240        tracing::info!(ts = %seed, "slack poller seeded cursor, skipping channel backlog");
241        *last_ts = Some(seed.to_string());
242        return Vec::new();
243    }
244
245    if let Some(ts) = newest
246        && last_ts.as_deref().is_none_or(|prev| ts > prev)
247    {
248        *last_ts = Some(ts.to_string());
249    }
250
251    let mut incoming = Vec::new();
252    for msg in messages.iter().rev() {
253        if msg.msg_type.as_deref() != Some("message") {
254            continue;
255        }
256        if msg.bot_id.is_some() {
257            continue;
258        }
259        let text = msg.text.as_deref().unwrap_or_default();
260        if text.is_empty() {
261            continue;
262        }
263
264        if !access.allows(channel_id, msg.user.as_deref().unwrap_or_default()) {
265            tracing::warn!(
266                channel_id = %channel_id,
267                user = msg.user.as_deref().unwrap_or("unknown"),
268                "slack message from a user not in allowed_user_ids, dropped"
269            );
270            continue;
271        }
272
273        let author = msg.user.as_deref().unwrap_or("unknown").to_string();
274        let timestamp = msg
275            .ts
276            .split('.')
277            .next()
278            .and_then(|s| s.parse::<i64>().ok())
279            .and_then(|secs| DateTime::from_timestamp(secs, 0))
280            .unwrap_or_else(Utc::now);
281
282        incoming.push(IncomingMessage {
283            channel: "slack".to_string(),
284            id: msg.ts.clone(),
285            thread_id: channel_id.to_string(),
286            author,
287            body: text.to_string(),
288            timestamp,
289            metadata: serde_json::json!({ "channel_id": channel_id }),
290            topic_id: None,
291        });
292    }
293    incoming
294}
295
296#[async_trait]
297impl Channel for SlackChannel {
298    fn name(&self) -> &'static str {
299        "slack"
300    }
301
302    async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>> {
303        let (tx, rx) = mpsc::channel(64);
304
305        // If no channel_id configured we can't poll
306        if self.channel_id.is_none() {
307            tracing::warn!("slack channel_id not configured, skipping message polling");
308            return Ok(rx);
309        }
310
311        let bot_token = self.bot_token.clone();
312        let client = self.client.clone();
313        let Some(channel_id) = self.channel_id.clone() else {
314            // Defensive: is_none() early-return above should prevent reaching here
315            tracing::error!("slack channel_id unexpectedly None after guard check");
316            return Ok(rx);
317        };
318        let last_ts = Arc::clone(&self.last_ts);
319        let access = self.access.clone();
320        access.warn_if_closed("slack");
321
322        let token_fingerprint = {
323            let mut hasher = Sha256::new();
324            hasher.update(bot_token.as_bytes());
325            let hash = hasher.finalize();
326            let hex = hash[..8].iter().fold(String::new(), |mut out, b| {
327                let _ = write!(out, "{b:02x}");
328                out
329            });
330            format!("sha256:{hex}")
331        };
332
333        tracing::info!(
334            token_fingerprint = %token_fingerprint,
335            channel_id = %channel_id,
336            "slack channel started"
337        );
338
339        let poll = tokio::spawn(async move {
340            let polling_interval = Duration::from_secs(5);
341
342            loop {
343                time::sleep(polling_interval).await;
344
345                let channel = SlackChannel {
346                    bot_token: bot_token.clone(),
347                    client: client.clone(),
348                    channel_id: Some(channel_id.clone()),
349                    last_ts: Arc::clone(&last_ts),
350                    access: access.clone(),
351                    poller: Poller::default(),
352                };
353
354                // Snapshot the cursor once so all pagination pages use the same lower bound.
355                let oldest = last_ts.lock().await.clone();
356
357                let messages = match channel.get_messages(&channel_id, oldest).await {
358                    Ok(m) => m,
359                    Err(e) => {
360                        tracing::warn!(?e, "failed to get slack messages");
361                        continue;
362                    }
363                };
364
365                let incoming = {
366                    let mut last = last_ts.lock().await;
367                    ingest_poll(&mut last, &messages, &channel_id, &slack_ts_now(), &access)
368                };
369
370                for msg in incoming {
371                    if tx.send(msg).await.is_err() {
372                        tracing::debug!("slack channel receiver dropped");
373                        return;
374                    }
375                }
376            }
377        });
378        self.poller.set(&poll);
379
380        Ok(rx)
381    }
382
383    async fn stop(&self) {
384        self.poller.stop();
385    }
386
387    async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()> {
388        let channel_id = self
389            .channel_id
390            .as_ref()
391            .ok_or_else(|| anyhow::anyhow!("slack channel_id not configured"))?;
392
393        self.send_message(channel_id, &msg.body).await
394    }
395
396    async fn health_check(&self) -> anyhow::Result<()> {
397        let response = self
398            .client
399            .get(Self::api_url("auth.test"))
400            .bearer_auth(&self.bot_token)
401            .send()
402            .await?;
403
404        if !response.status().is_success() {
405            let body = response.text().await.unwrap_or_default();
406            anyhow::bail!("slack health check HTTP error: {body}");
407        }
408
409        let result: AuthTestResponse = response.json().await?;
410
411        if !result.ok {
412            let err = result.error.as_deref().unwrap_or("unknown");
413            anyhow::bail!("slack auth.test failed: {err}");
414        }
415
416        tracing::info!("slack bot health check passed");
417        Ok(())
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn slack_channel_name() {
427        let ch = SlackChannel::new("xoxb-test".to_string(), None).unwrap();
428        assert_eq!(ch.name(), "slack");
429    }
430
431    #[test]
432    fn access_allows_listed_user_only() {
433        let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string()))
434            .unwrap()
435            .with_access(vec![], vec!["U1".to_string()]);
436        assert!(ch.access.allows("C1", "U1"));
437        assert!(!ch.access.allows("C1", "U2"));
438        assert!(!ch.access.allows("C1", ""));
439    }
440
441    #[test]
442    fn access_includes_mapped_channels() {
443        let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string()))
444            .unwrap()
445            .with_access(vec!["C2".to_string()], vec!["U1".to_string()]);
446        assert!(ch.access.allows("C2", "U1"));
447        assert!(!ch.access.allows("C3", "U1"));
448    }
449
450    #[test]
451    fn empty_policy_drops_everything() {
452        let ch = SlackChannel::new("xoxb-test".to_string(), Some("C1".to_string())).unwrap();
453        assert!(!ch.access.allows("C1", "U1"));
454        let ch = ch.with_access(vec![], vec![]);
455        assert!(!ch.access.allows("C1", "U1"));
456    }
457
458    #[test]
459    fn slack_api_url() {
460        assert_eq!(
461            SlackChannel::api_url("auth.test"),
462            "https://slack.com/api/auth.test"
463        );
464        assert_eq!(
465            SlackChannel::api_url("chat.postMessage"),
466            "https://slack.com/api/chat.postMessage"
467        );
468    }
469
470    #[test]
471    fn slack_ts_comparison_is_lexicographic() {
472        // Slack ts values are strings like "1700000000.123456"
473        // Lexicographic comparison works because the integer part is the same width
474        let older = "1700000000.000100".to_string();
475        let newer = "1700000001.000000".to_string();
476        assert!(newer > older);
477    }
478
479    #[test]
480    fn conversations_history_response_deserializes_pagination_fields() {
481        // Response with more pages available
482        let json = r#"{
483            "ok": true,
484            "messages": [{"type": "message", "ts": "1700000001.000000", "text": "hello"}],
485            "has_more": true,
486            "response_metadata": {"next_cursor": "bmV4dF90czoxNzAwMDAwMDAxLjAwMDAwMA=="}
487        }"#;
488        let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
489        assert!(resp.ok);
490        assert_eq!(resp.has_more, Some(true));
491        let meta = resp.response_metadata.unwrap();
492        assert_eq!(
493            meta.next_cursor.as_deref(),
494            Some("bmV4dF90czoxNzAwMDAwMDAxLjAwMDAwMA==")
495        );
496    }
497
498    #[test]
499    fn conversations_history_response_last_page_has_no_cursor() {
500        // Final page: has_more=false, empty next_cursor
501        let json = r#"{
502            "ok": true,
503            "messages": [{"type": "message", "ts": "1700000002.000000", "text": "last"}],
504            "has_more": false,
505            "response_metadata": {"next_cursor": ""}
506        }"#;
507        let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
508        assert_eq!(resp.has_more, Some(false));
509        let next = resp
510            .response_metadata
511            .and_then(|m| m.next_cursor)
512            .filter(|c| !c.is_empty());
513        assert!(
514            next.is_none(),
515            "empty next_cursor should be treated as no more pages"
516        );
517    }
518
519    #[test]
520    fn conversations_history_response_missing_pagination_fields() {
521        // Older API responses may omit has_more and response_metadata entirely
522        let json = r#"{"ok": true, "messages": []}"#;
523        let resp: ConversationsHistoryResponse = serde_json::from_str(json).unwrap();
524        assert_eq!(resp.has_more, None);
525        assert!(resp.response_metadata.is_none());
526        // has_more defaults to false — no pagination loop
527        assert!(!resp.has_more.unwrap_or(false));
528    }
529
530    fn slack_msg(ts: &str, text: &str) -> SlackMessage {
531        SlackMessage {
532            msg_type: Some("message".into()),
533            ts: ts.into(),
534            user: Some("U1".into()),
535            bot_id: None,
536            text: Some(text.into()),
537        }
538    }
539
540    fn bot_msg(ts: &str, text: &str) -> SlackMessage {
541        SlackMessage {
542            msg_type: Some("message".into()),
543            ts: ts.into(),
544            user: None,
545            bot_id: Some("B1".into()),
546            text: Some(text.into()),
547        }
548    }
549
550    fn open_access() -> Access {
551        Access::new(["C123".to_string()], ["U1".to_string()])
552    }
553
554    #[test]
555    fn first_poll_with_no_cursor_does_not_emit_historical_messages() {
556        let mut last_ts = None;
557        let messages = [
558            slack_msg("1700000002.000000", "newest"),
559            slack_msg("1700000001.000000", "older"),
560            slack_msg("1700000000.000000", "oldest"),
561        ];
562        let incoming = ingest_poll(
563            &mut last_ts,
564            &messages,
565            "C123",
566            "1700000099.000000",
567            &open_access(),
568        );
569        assert!(
570            incoming.is_empty(),
571            "first poll must not replay channel history"
572        );
573        assert_eq!(last_ts.as_deref(), Some("1700000002.000000"));
574    }
575
576    #[test]
577    fn first_poll_with_empty_history_seeds_from_now() {
578        let mut last_ts = None;
579        let incoming = ingest_poll(
580            &mut last_ts,
581            &[],
582            "C123",
583            "1700000099.000000",
584            &open_access(),
585        );
586        assert!(incoming.is_empty());
587        assert_eq!(last_ts.as_deref(), Some("1700000099.000000"));
588    }
589
590    #[test]
591    fn later_poll_emits_messages_newer_than_cursor() {
592        let mut last_ts = Some("1700000002.000000".into());
593        let messages = [slack_msg("1700000003.000000", "hello")];
594        let incoming = ingest_poll(
595            &mut last_ts,
596            &messages,
597            "C123",
598            "1700000099.000000",
599            &open_access(),
600        );
601        assert_eq!(incoming.len(), 1);
602        assert_eq!(incoming[0].body, "hello");
603        assert_eq!(incoming[0].id, "1700000003.000000");
604        assert_eq!(last_ts.as_deref(), Some("1700000003.000000"));
605    }
606
607    #[test]
608    fn later_poll_drops_unlisted_users_and_advances_cursor() {
609        let mut last_ts = Some("1700000002.000000".into());
610        let mut other = slack_msg("1700000003.000000", "nope");
611        other.user = Some("U2".into());
612        let messages = [other, slack_msg("1700000004.000000", "hello")];
613        let incoming = ingest_poll(
614            &mut last_ts,
615            &messages,
616            "C123",
617            "1700000099.000000",
618            &open_access(),
619        );
620        assert_eq!(incoming.len(), 1);
621        assert_eq!(incoming[0].body, "hello");
622        assert_eq!(last_ts.as_deref(), Some("1700000004.000000"));
623    }
624
625    #[test]
626    fn later_poll_advances_cursor_past_bot_messages() {
627        let mut last_ts = Some("1700000002.000000".into());
628        let messages = [
629            bot_msg("1700000004.000000", "newest bot"),
630            bot_msg("1700000003.000000", "older bot"),
631        ];
632        let incoming = ingest_poll(
633            &mut last_ts,
634            &messages,
635            "C123",
636            "1700000099.000000",
637            &open_access(),
638        );
639        assert!(
640            incoming.is_empty(),
641            "bot messages must not be emitted as incoming commands"
642        );
643        assert_eq!(last_ts.as_deref(), Some("1700000004.000000"));
644    }
645
646    #[test]
647    fn later_poll_emits_human_messages_and_advances_past_later_bots() {
648        let mut last_ts = Some("1700000002.000000".into());
649        let messages = [
650            bot_msg("1700000005.000000", "notification"),
651            slack_msg("1700000004.000000", "hello"),
652            bot_msg("1700000003.000000", "older bot"),
653        ];
654        let incoming = ingest_poll(
655            &mut last_ts,
656            &messages,
657            "C123",
658            "1700000099.000000",
659            &open_access(),
660        );
661        assert_eq!(incoming.len(), 1);
662        assert_eq!(incoming[0].body, "hello");
663        assert_eq!(last_ts.as_deref(), Some("1700000005.000000"));
664    }
665
666    #[test]
667    fn later_poll_advances_cursor_past_empty_and_non_message_events() {
668        let mut last_ts = Some("1700000002.000000".into());
669        let empty_text = SlackMessage {
670            msg_type: Some("message".into()),
671            ts: "1700000003.000000".into(),
672            user: Some("U1".into()),
673            bot_id: None,
674            text: Some(String::new()),
675        };
676        let other_type = SlackMessage {
677            msg_type: Some("desktop_notification".into()),
678            ts: "1700000004.000000".into(),
679            user: None,
680            bot_id: None,
681            text: Some("ignored".into()),
682        };
683        let messages = [other_type, empty_text];
684        let incoming = ingest_poll(
685            &mut last_ts,
686            &messages,
687            "C123",
688            "1700000099.000000",
689            &open_access(),
690        );
691        assert!(incoming.is_empty());
692        assert_eq!(last_ts.as_deref(), Some("1700000004.000000"));
693    }
694}