Skip to main content

agentmux_srv/messaging/slack/
socket.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Slack Socket Mode connection lifecycle: `apps.connections.open`, the
5//! hello/events_api/disconnect-warning state machine, per-event ACK, the
6//! make-before-break reconnect-on-warning dance, and the 5-minute
7//! dead-connection timer — plus the outbound `chat.postMessage` sender.
8//!
9//! ## Two independent tasks, not one interleaved loop
10//!
11//! `run_bridge` joins the inbound socket loop (`run_socket_loop`) and the
12//! outbound send loop (`run_outbound_loop`) via `tokio::join!`, exactly like
13//! `telegram/poller.rs::run_poll_loop` joins its inbound/outbound loops —
14//! see that file's doc comment for the full review finding that motivated
15//! the split (an interleaved `tokio::select!` let an outbound
16//! backoff-sleep block inbound polling for as long as the backoff lasted).
17//! The same coupling would be worse for Slack: the inbound loop must ACK
18//! every `events_api` envelope within a hard 3-second deadline (spec §2.2),
19//! so anything that could delay servicing inbound frames — including an
20//! outbound rate-limit wait — must live on a fully separate task. The two
21//! loops share no state; outbound doesn't touch the WebSocket at all, it
22//! only calls `rest::post_message`.
23//!
24//! ## Make-before-break reconnect-on-warning (spec §2.3)
25//!
26//! This is entirely internal to `run_socket_loop`'s per-connection state
27//! (`run_session`), not a second top-level task — the dance is about
28//! managing one logical inbound connection's lifecycle, which is exactly
29//! what `run_socket_loop` already owns.
30//!
31//! `run_session` holds at most two live socket halves at once:
32//! - `primary: WsHalf` — the currently-active connection. All *new* inbound
33//!   processing (routing, ACKs for anything just arriving) happens here.
34//! - `old: Option<WsHalf>` — set only during the ~10s window between a
35//!   `disconnect: warning` and Slack force-closing that connection. Frames
36//!   still arriving here (Slack can route events to it right up until the
37//!   close) are drained and ACKed exactly like `primary`'s, just not
38//!   promoted to primary status.
39//!
40//! When a `warning` arrives on `primary`, we don't tear the connection down
41//! and reconnect — we kick off a *second*, independent connect (fetch a
42//! fresh URL via `apps.connections.open`, open a new WS, wait for its
43//! `hello`) while continuing to service `primary` unmodified. That connect
44//! runs as a pinned, boxed future (`cutover_connect`) polled as one more
45//! `tokio::select!` branch each loop iteration — the same technique
46//! `discord/gateway.rs` uses for its heartbeat-interval sleep (`hb_sleep`):
47//! a `Pin<Box<dyn Future>>` defaulting to `std::future::pending()` when
48//! there's nothing in flight, swapped in only when there's real async work
49//! to track. This is what makes the second connect genuinely concurrent
50//! with continuing to drain `primary` within a single task, no extra
51//! `tokio::spawn` required.
52//!
53//! Once that future resolves successfully (new socket reached `hello`), the
54//! *next* loop iteration promotes it: `old = Some(mem::replace(primary,
55//! new))`. From that point on, `primary`'s branch handles all new frames as
56//! usual, and a second `tokio::select!` branch (guarded by `old.is_some()`,
57//! built from the `next_frame` helper below so it evaluates to
58//! `std::future::pending()` — i.e. never fires — when `old` is `None`)
59//! keeps draining and ACKing `old` until it errors or closes, at which
60//! point it's dropped. A duplicate `warning` arriving while a cutover is
61//! already in flight is logged and ignored (`cutover_pending` guard) rather
62//! than launching a second concurrent connect.
63//!
64//! An unexpected close on `primary` with no prior warning (network blip,
65//! Slack silently dying, etc.) is the plain backoff path: `run_session`
66//! returns `Err`, and the outer `run_socket_loop` retry loop reconnects
67//! after an exponentially-increasing delay (capped at 60s, matching
68//! Discord's `RECONNECT_DELAY_SECS`/`MAX_RECONNECT_DELAY_SECS` constants),
69//! always fetching a fresh URL first (never retrying a stale one).
70
71use std::collections::HashMap;
72use std::sync::{Arc, Mutex};
73use std::time::{Duration, Instant};
74
75use futures_util::stream::{SplitSink, SplitStream};
76use futures_util::{SinkExt, StreamExt};
77use tokio::sync::mpsc;
78use tokio_tungstenite::{tungstenite::Message, MaybeTlsStream, WebSocketStream};
79
80use crate::backend::reactive::types::InjectionRequest;
81use crate::messaging::{BridgeHealth, BridgeStatus, OutboundMsg};
82
83use super::rest;
84use super::types::{AckFrame, EventsApiPayload, SlackEvent, SocketEnvelope};
85
86const RECONNECT_DELAY_SECS: u64 = 5;
87const MAX_RECONNECT_DELAY_SECS: u64 = 60;
88
89/// Proactive dead-connection heuristic (spec §2.3): if no frame of any kind
90/// has arrived in this long, force a reconnect even though nothing signaled
91/// a close.
92const DEAD_CONN_TIMEOUT_SECS: u64 = 300;
93
94/// Minimum spacing between two outbound sends to the same channel (spec
95/// §2.6 — "~1 msg/s/channel", enforced with a bit of headroom).
96const CHANNEL_MIN_SPACING: Duration = Duration::from_millis(1100);
97
98/// Timeout waiting for the first frame (must be `hello`) after connecting.
99const HELLO_TIMEOUT_SECS: u64 = 10;
100
101type WsStream = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
102type WsWrite = SplitSink<WsStream, Message>;
103type WsRead = SplitStream<WsStream>;
104
105struct WsHalf {
106    write: WsWrite,
107    read: WsRead,
108}
109
110/// Orchestrates the two independent tasks described in the module doc
111/// comment. Called once from `SlackBridge::init_global`'s spawned task.
112pub async fn run_bridge(
113    app_token: String,
114    bot_token: String,
115    channel_id: String,
116    target_agent: Option<String>,
117    http: reqwest::Client,
118    outbound_rx: mpsc::UnboundedReceiver<OutboundMsg>,
119    health: Arc<Mutex<BridgeHealth>>,
120) {
121    let outbound_http = http.clone();
122    let default_channel = channel_id.clone();
123    tokio::join!(
124        run_socket_loop(app_token, channel_id, target_agent, http, health),
125        run_outbound_loop(outbound_http, bot_token, default_channel, outbound_rx),
126    );
127}
128
129// ── Inbound: Socket Mode connection lifecycle ───────────────────────────────
130
131/// Outer retry-forever loop: fetch a fresh WS URL, run a session until it
132/// ends (cleanly or with an error), back off, repeat. Every attempt —
133/// initial connect included — fetches a new URL via `apps.connections.open`
134/// (spec §2.1: the URL is single-use, there is no Discord-style constant
135/// Gateway URL to fall back to).
136async fn run_socket_loop(
137    app_token: String,
138    channel_id: String,
139    target_agent: Option<String>,
140    http: reqwest::Client,
141    health: Arc<Mutex<BridgeHealth>>,
142) {
143    let mut delay_secs = RECONNECT_DELAY_SECS;
144
145    loop {
146        {
147            let mut h = health.lock().unwrap();
148            h.status = BridgeStatus::Connecting;
149        }
150
151        let session_start = Instant::now();
152
153        match connect_and_run(&app_token, &channel_id, &target_agent, &http, &health).await {
154            Ok(()) => {
155                tracing::info!("slack_bridge: session ended cleanly");
156            }
157            Err(e) => {
158                tracing::warn!("slack_bridge: session error: {e}");
159                let mut h = health.lock().unwrap();
160                h.status = BridgeStatus::Error;
161                h.error = Some(e);
162                h.reconnect_count += 1;
163            }
164        }
165
166        if session_start.elapsed().as_secs() > 30 {
167            delay_secs = RECONNECT_DELAY_SECS;
168        }
169
170        {
171            let mut h = health.lock().unwrap();
172            if h.status != BridgeStatus::Error {
173                h.status = BridgeStatus::Disconnected;
174            }
175        }
176
177        tokio::time::sleep(Duration::from_secs(delay_secs)).await;
178        delay_secs = (delay_secs * 2).min(MAX_RECONNECT_DELAY_SECS);
179    }
180}
181
182async fn connect_and_run(
183    app_token: &str,
184    channel_id: &str,
185    target_agent: &Option<String>,
186    http: &reqwest::Client,
187    health: &Arc<Mutex<BridgeHealth>>,
188) -> Result<(), String> {
189    let mut primary = open_and_await_hello(app_token, http).await?;
190
191    {
192        let mut h = health.lock().unwrap();
193        h.status = BridgeStatus::Connected;
194        h.error = None;
195        h.last_event_at = Some(unix_secs());
196    }
197    tracing::info!("slack_bridge: connected (hello received)");
198
199    run_session(app_token, channel_id, target_agent, http, health, &mut primary).await
200}
201
202/// Fetches a fresh Socket Mode URL and connects, waiting for the mandatory
203/// first `hello` frame (spec §2.1, §4.1). Used both for the initial connect
204/// and for the cutover half of the make-before-break dance.
205async fn open_and_await_hello(app_token: &str, http: &reqwest::Client) -> Result<WsHalf, String> {
206    let url = rest::open_connection(http, app_token).await?;
207    tracing::debug!(
208        "slack_bridge: opened connection ({})",
209        rest::redact_ticket(&url)
210    );
211
212    let request = tokio_tungstenite::tungstenite::http::Request::builder()
213        .uri(&url)
214        .body(())
215        .map_err(|e| format!("slack_bridge: build ws request: {e}"))?;
216
217    let (ws_stream, _) = crate::muxbus::ws_connect::connect(request)
218        .await
219        .map_err(|e| format!("slack_bridge: ws connect: {e}"))?;
220
221    let (write, mut read) = ws_stream.split();
222
223    match tokio::time::timeout(Duration::from_secs(HELLO_TIMEOUT_SECS), read.next()).await {
224        Ok(Some(Ok(Message::Text(text)))) => match serde_json::from_str::<SocketEnvelope>(&text) {
225            Ok(SocketEnvelope::Hello(_)) => Ok(WsHalf { write, read }),
226            Ok(_) => Err("slack_bridge: expected hello as first frame, got a different envelope type".to_string()),
227            Err(e) => Err(format!("slack_bridge: parse first frame: {e}")),
228        },
229        Ok(Some(Ok(_))) => Err("slack_bridge: expected hello as first frame, got a non-text frame".to_string()),
230        Ok(Some(Err(e))) => Err(format!("slack_bridge: ws recv error awaiting hello: {e}")),
231        Ok(None) => Err("slack_bridge: socket closed before hello".to_string()),
232        Err(_) => Err("slack_bridge: timed out waiting for hello".to_string()),
233    }
234}
235
236/// Await a frame on `old` if present, else never resolve. Lets the cutover
237/// socket's read half participate in the same `tokio::select!` as
238/// `primary`'s without needing a separate task — mirrors how
239/// `discord/gateway.rs` boxes an optional sleep future for its heartbeat.
240async fn next_frame(
241    old: &mut Option<WsHalf>,
242) -> Option<Result<Message, tokio_tungstenite::tungstenite::Error>> {
243    match old {
244        Some(half) => half.read.next().await,
245        None => std::future::pending().await,
246    }
247}
248
249enum FrameOutcome {
250    Continue,
251    WarningReceived,
252    Closed,
253}
254
255/// Runs one connection's session loop, holding at most two live socket
256/// halves (`primary` + optionally `old`, see module doc comment).
257///
258/// Returns `Ok(())` on a clean close (primary closed with no error) or
259/// `Err(e)` on anything reconnect-worthy (unexpected close, dead-connection
260/// timeout, ws send/recv error). Either way the caller (`run_socket_loop`)
261/// starts a fresh session with a freshly-fetched URL.
262async fn run_session(
263    app_token: &str,
264    channel_id: &str,
265    target_agent: &Option<String>,
266    http: &reqwest::Client,
267    health: &Arc<Mutex<BridgeHealth>>,
268    primary: &mut WsHalf,
269) -> Result<(), String> {
270    let mut old: Option<WsHalf> = None;
271    let mut cutover_pending = false;
272
273    let mut cutover_connect: std::pin::Pin<
274        Box<dyn std::future::Future<Output = Result<WsHalf, String>> + Send>,
275    > = Box::pin(std::future::pending());
276
277    let mut dead_conn_sleep = Box::pin(tokio::time::sleep(Duration::from_secs(
278        DEAD_CONN_TIMEOUT_SECS,
279    )));
280
281    loop {
282        tokio::select! {
283            // Proactive dead-connection heuristic (spec §2.3).
284            _ = &mut dead_conn_sleep => {
285                return Err(format!(
286                    "no frames received for {DEAD_CONN_TIMEOUT_SECS}s — treating connection as dead"
287                ));
288            }
289
290            // Cutover connect finished (success or failure).
291            result = &mut cutover_connect, if cutover_pending => {
292                cutover_pending = false;
293                cutover_connect = Box::pin(std::future::pending());
294                match result {
295                    Ok(new_half) => {
296                        tracing::info!("slack_bridge: cutover connection ready (hello received) — promoting to primary");
297                        let retiring = std::mem::replace(primary, new_half);
298                        old = Some(retiring);
299                        dead_conn_sleep = Box::pin(tokio::time::sleep(Duration::from_secs(DEAD_CONN_TIMEOUT_SECS)));
300                        let mut h = health.lock().unwrap();
301                        h.last_event_at = Some(unix_secs());
302                    }
303                    Err(e) => {
304                        // Stay on the current primary — it may still get
305                        // force-closed by Slack at the end of the warning
306                        // period, at which point the plain unexpected-close
307                        // path (primary.read.next() below) takes over.
308                        tracing::warn!("slack_bridge: cutover connect failed: {e} — staying on current primary until it closes");
309                    }
310                }
311            }
312
313            // Frame on the active (primary) socket.
314            frame = primary.read.next() => {
315                match frame {
316                    None => return Ok(()),
317                    Some(Err(e)) => return Err(format!("ws recv (primary): {e}")),
318                    Some(Ok(msg)) => {
319                        dead_conn_sleep = Box::pin(tokio::time::sleep(Duration::from_secs(DEAD_CONN_TIMEOUT_SECS)));
320                        let outcome = handle_frame(msg, &mut primary.write, channel_id, target_agent, health).await?;
321                        match outcome {
322                            FrameOutcome::Continue => {}
323                            FrameOutcome::Closed => return Ok(()),
324                            FrameOutcome::WarningReceived => {
325                                // Guard on `old.is_some()` too, not just
326                                // `cutover_pending`: a warning arriving on the
327                                // newly-promoted primary before the previous
328                                // retiring connection (`old`) has finished
329                                // draining must not start a second cutover —
330                                // its success arm below unconditionally
331                                // overwrites `old`, which would silently drop
332                                // the still-open first retiring connection
333                                // instead of finishing its drain, violating
334                                // "at most two live socket halves." Worst case
335                                // of ignoring it: Slack force-closes this
336                                // primary at the end of its warning window,
337                                // which falls through to the plain
338                                // unexpected-close error path below and
339                                // reconnects via the outer session retry loop
340                                // — the same degraded-but-safe fallback this
341                                // module already accepts when a cutover
342                                // connect attempt itself fails (see the `Err`
343                                // arm above).
344                                if cutover_pending || old.is_some() {
345                                    tracing::debug!(
346                                        "slack_bridge: disconnect warning while a cutover is already in flight or draining — ignoring"
347                                    );
348                                } else {
349                                    tracing::info!("slack_bridge: disconnect warning received — starting make-before-break reconnect");
350                                    cutover_pending = true;
351                                    let app_token = app_token.to_string();
352                                    let http = http.clone();
353                                    cutover_connect = Box::pin(async move { open_and_await_hello(&app_token, &http).await });
354                                }
355                            }
356                        }
357                    }
358                }
359            }
360
361            // Frame on the retiring (old) socket — only polled once a
362            // cutover has actually promoted a new primary.
363            frame = next_frame(&mut old), if old.is_some() => {
364                match frame {
365                    None | Some(Err(_)) => {
366                        tracing::debug!("slack_bridge: old socket closed/errored after cutover — discarding");
367                        old = None;
368                    }
369                    Some(Ok(msg)) => {
370                        // Best-effort: ACK/drain the old socket, but don't
371                        // let its errors tear down the (already-promoted)
372                        // primary session.
373                        if let Some(half) = old.as_mut() {
374                            match handle_frame(msg, &mut half.write, channel_id, target_agent, health).await {
375                                Ok(FrameOutcome::Closed) => {
376                                    tracing::info!("slack_bridge: old socket closed cleanly after cutover");
377                                    old = None;
378                                }
379                                Ok(_) => {}
380                                Err(e) => {
381                                    tracing::debug!("slack_bridge: old socket error after cutover (harmless — draining): {e}");
382                                    old = None;
383                                }
384                            }
385                        }
386                    }
387                }
388            }
389        }
390    }
391}
392
393/// Handles one WS frame: ACKs `events_api`/`slash_commands` envelopes
394/// immediately (before any parsing/routing — spec §2.2's hard 3-second
395/// requirement), then routes `events_api` payloads to the reactive bus.
396async fn handle_frame(
397    msg: Message,
398    write: &mut WsWrite,
399    channel_id: &str,
400    target_agent: &Option<String>,
401    health: &Arc<Mutex<BridgeHealth>>,
402) -> Result<FrameOutcome, String> {
403    match msg {
404        Message::Text(text) => {
405            let envelope: SocketEnvelope = match serde_json::from_str(&text) {
406                Ok(e) => e,
407                Err(e) => {
408                    tracing::warn!("slack_bridge: parse error: {e}");
409                    return Ok(FrameOutcome::Continue);
410                }
411            };
412
413            match envelope {
414                SocketEnvelope::Hello(_) => {
415                    tracing::debug!("slack_bridge: hello frame on an already-active socket");
416                    Ok(FrameOutcome::Continue)
417                }
418                SocketEnvelope::EventsApi(ev) => {
419                    ack_envelope(write, &ev.envelope_id).await?;
420                    route_event(ev.payload, channel_id, target_agent, health);
421                    Ok(FrameOutcome::Continue)
422                }
423                SocketEnvelope::SlashCommands(ev) => {
424                    // ACK required same as any other envelope (spec §2.5),
425                    // but slash commands are out of scope for this PR — no
426                    // further handling.
427                    ack_envelope(write, &ev.envelope_id).await?;
428                    tracing::debug!("slack_bridge: received slash_commands envelope (not handled — out of scope for this PR)");
429                    Ok(FrameOutcome::Continue)
430                }
431                SocketEnvelope::Disconnect(d) => {
432                    if d.reason.as_deref() == Some("warning") {
433                        Ok(FrameOutcome::WarningReceived)
434                    } else {
435                        tracing::info!("slack_bridge: disconnect frame (reason={:?})", d.reason);
436                        Ok(FrameOutcome::Closed)
437                    }
438                }
439                SocketEnvelope::Unknown => {
440                    tracing::debug!("slack_bridge: unhandled envelope type");
441                    Ok(FrameOutcome::Continue)
442                }
443            }
444        }
445        Message::Ping(data) => {
446            let _ = write.send(Message::Pong(data)).await;
447            Ok(FrameOutcome::Continue)
448        }
449        Message::Close(_) => Ok(FrameOutcome::Closed),
450        _ => Ok(FrameOutcome::Continue),
451    }
452}
453
454/// Sends `{"envelope_id": "..."}` back on the socket the envelope arrived
455/// on. Kept allocation-light and infallible-as-possible per spec §2.2's
456/// note that the ACK path should stay cheap and unconditional.
457async fn ack_envelope(write: &mut WsWrite, envelope_id: &str) -> Result<(), String> {
458    let ack = AckFrame {
459        envelope_id: envelope_id.to_string(),
460    };
461    let ack_json = serde_json::to_string(&ack).unwrap_or_default();
462    write
463        .send(Message::Text(ack_json.into()))
464        .await
465        .map_err(|e| format!("slack_bridge: ack send: {e}"))
466}
467
468/// True when a `SlackEvent` should be routed to the reactive bus: right
469/// event type, right channel, not self-authored. Pure/testable without a
470/// real socket.
471fn should_route(event: &SlackEvent, channel_id: &str) -> bool {
472    if event.bot_id.is_some() {
473        return false; // spec §9.4 — bot-message loop prevention
474    }
475    if event.type_ != "message" && event.type_ != "app_mention" {
476        return false;
477    }
478    event.channel.as_deref() == Some(channel_id) // spec §9.3 — channel allowlist
479}
480
481fn route_event(
482    payload: Option<EventsApiPayload>,
483    channel_id: &str,
484    target_agent: &Option<String>,
485    health: &Arc<Mutex<BridgeHealth>>,
486) {
487    let Some(event) = payload.and_then(|p| p.event) else {
488        return;
489    };
490
491    if !should_route(&event, channel_id) {
492        return;
493    }
494
495    {
496        let mut h = health.lock().unwrap();
497        h.last_event_at = Some(unix_secs());
498    }
499
500    let Some(target) = target_agent else {
501        tracing::debug!("slack_bridge: event in #{channel_id} (no target agent configured)");
502        return;
503    };
504
505    let user = event.user.as_deref().unwrap_or("unknown");
506    let text = event.text.as_deref().unwrap_or("");
507    let envelope = format!("[Slack #{channel_id} @{user}]: {text}");
508
509    let req = InjectionRequest {
510        target_agent: target.clone(),
511        message: envelope,
512        source_agent: Some("slack".to_string()),
513        request_id: event.ts.clone(),
514        priority: None,
515        jekt_tier: None,
516        delivery_tier: Some("wan".to_string()),
517        forward_hops: 0,
518        ..Default::default()
519    };
520    let result = crate::server::jekt_entry::inject_from_bridge(req, text);
521    if result.success {
522        tracing::debug!("slack_bridge: injected msg from {user} to agent {target}");
523    } else {
524        tracing::warn!(
525            "slack_bridge: inject to agent {target} failed: {:?}",
526            result.error
527        );
528    }
529}
530
531// ── Outbound: chat.postMessage sender ───────────────────────────────────────
532
533async fn run_outbound_loop(
534    http: reqwest::Client,
535    bot_token: String,
536    default_channel_id: String,
537    mut outbound_rx: mpsc::UnboundedReceiver<OutboundMsg>,
538) {
539    // Per-channel outbound rate limiting (spec §2.6, v1 scope: spacing +
540    // reactive 429 backoff only). Owned entirely by this task — never
541    // shared with the inbound loop.
542    let mut channel_last_sent: HashMap<String, Instant> = HashMap::new();
543    let mut channel_backoff_until: HashMap<String, Instant> = HashMap::new();
544    let mut channel_backoff_secs: HashMap<String, u64> = HashMap::new();
545
546    while let Some(msg) = outbound_rx.recv().await {
547        handle_outbound(
548            &http,
549            &bot_token,
550            &default_channel_id,
551            msg,
552            &mut channel_last_sent,
553            &mut channel_backoff_until,
554            &mut channel_backoff_secs,
555        )
556        .await;
557    }
558}
559
560/// Resolves an `OutboundMsg.channel_id` (empty → bridge default) into the
561/// channel id to send to. Pure/testable.
562fn resolve_channel_id(channel_id: &str, default_channel_id: &str) -> Option<String> {
563    if !channel_id.is_empty() {
564        return Some(channel_id.to_string());
565    }
566    if default_channel_id.is_empty() {
567        return None;
568    }
569    Some(default_channel_id.to_string())
570}
571
572/// Next backoff duration after a repeated failure, doubling and capped —
573/// same family used for reconnects (spec §2.6: "on repeated 429s apply the
574/// same exponential backoff used for reconnects"). Pure/testable.
575fn next_backoff_secs(current: u64) -> u64 {
576    (current * 2).min(MAX_RECONNECT_DELAY_SECS)
577}
578
579async fn handle_outbound(
580    http: &reqwest::Client,
581    bot_token: &str,
582    default_channel_id: &str,
583    msg: OutboundMsg,
584    channel_last_sent: &mut HashMap<String, Instant>,
585    channel_backoff_until: &mut HashMap<String, Instant>,
586    channel_backoff_secs: &mut HashMap<String, u64>,
587) {
588    let Some(channel_id) = resolve_channel_id(&msg.channel_id, default_channel_id) else {
589        tracing::warn!(
590            "slack_bridge: send dropped — no channel_id (empty channel_id and no messaging:slack:channel configured)"
591        );
592        return;
593    };
594
595    if let Some(until) = channel_backoff_until.get(&channel_id).copied() {
596        let now = Instant::now();
597        if now < until {
598            tokio::time::sleep(until - now).await;
599        }
600        channel_backoff_until.remove(&channel_id);
601    }
602
603    if let Some(last) = channel_last_sent.get(&channel_id) {
604        let elapsed = last.elapsed();
605        if elapsed < CHANNEL_MIN_SPACING {
606            tokio::time::sleep(CHANNEL_MIN_SPACING - elapsed).await;
607        }
608    }
609
610    match rest::post_message(http, bot_token, &channel_id, &msg).await {
611        Ok(()) => {
612            channel_last_sent.insert(channel_id.clone(), Instant::now());
613            channel_backoff_secs.remove(&channel_id);
614        }
615        Err(e) if e.retry_after.is_some() => {
616            // Spec §2.6: on 429, wait Retry-After then retry once.
617            let retry_after = e.retry_after.unwrap();
618            tracing::warn!(
619                "slack_bridge: rate limited sending to #{channel_id}, retry_after={retry_after}s — waiting then retrying once"
620            );
621            tokio::time::sleep(Duration::from_secs(retry_after)).await;
622
623            match rest::post_message(http, bot_token, &channel_id, &msg).await {
624                Ok(()) => {
625                    channel_last_sent.insert(channel_id.clone(), Instant::now());
626                    channel_backoff_secs.remove(&channel_id);
627                }
628                Err(e2) if e2.retry_after.is_some() => {
629                    // Still rate-limited after the single Retry-After wait —
630                    // apply exponential channel backoff.
631                    tracing::warn!(
632                        "slack_bridge: retry after rate limit still rate-limited for #{channel_id}: {e2}"
633                    );
634                    let current = channel_backoff_secs
635                        .get(&channel_id)
636                        .copied()
637                        .unwrap_or(RECONNECT_DELAY_SECS);
638                    channel_backoff_until.insert(channel_id.clone(), Instant::now() + Duration::from_secs(current));
639                    channel_backoff_secs.insert(channel_id, next_backoff_secs(current));
640                }
641                Err(e2) => {
642                    // A different, non-rate-limit failure (e.g.
643                    // channel_not_found, invalid_auth) — don't conflate it
644                    // with throttling by scheduling a rate-limit backoff;
645                    // just log it, matching the plain-failure arm below.
646                    tracing::warn!(
647                        "slack_bridge: retry after rate limit failed for #{channel_id} for an unrelated reason: {e2}"
648                    );
649                }
650            }
651        }
652        Err(e) => {
653            tracing::warn!("slack_bridge: send to #{channel_id} failed: {e}");
654        }
655    }
656}
657
658fn unix_secs() -> u64 {
659    agentmux_common::time::now_secs_u64()
660}
661
662#[cfg(test)]
663mod tests {
664    use super::*;
665    use super::super::types::SlackEvent;
666
667    fn event(type_: &str, channel: Option<&str>, bot_id: Option<&str>) -> SlackEvent {
668        SlackEvent {
669            type_: type_.to_string(),
670            channel: channel.map(str::to_string),
671            user: Some("U1".to_string()),
672            text: Some("hi".to_string()),
673            ts: Some("123.4".to_string()),
674            bot_id: bot_id.map(str::to_string),
675        }
676    }
677
678    #[test]
679    fn should_route_accepts_message_in_configured_channel() {
680        let e = event("message", Some("C1"), None);
681        assert!(should_route(&e, "C1"));
682    }
683
684    #[test]
685    fn should_route_accepts_app_mention() {
686        let e = event("app_mention", Some("C1"), None);
687        assert!(should_route(&e, "C1"));
688    }
689
690    #[test]
691    fn should_route_rejects_other_channel() {
692        let e = event("message", Some("C2"), None);
693        assert!(!should_route(&e, "C1"));
694    }
695
696    #[test]
697    fn should_route_rejects_missing_channel() {
698        let e = event("message", None, None);
699        assert!(!should_route(&e, "C1"));
700    }
701
702    #[test]
703    fn should_route_rejects_bot_authored_events() {
704        let e = event("message", Some("C1"), Some("B1"));
705        assert!(!should_route(&e, "C1"));
706    }
707
708    #[test]
709    fn should_route_rejects_unrelated_event_types() {
710        let e = event("channel_join", Some("C1"), None);
711        assert!(!should_route(&e, "C1"));
712    }
713
714    #[test]
715    fn resolve_channel_id_uses_explicit_channel_when_present() {
716        assert_eq!(resolve_channel_id("C1", "C_default"), Some("C1".to_string()));
717    }
718
719    #[test]
720    fn resolve_channel_id_falls_back_to_default_when_empty() {
721        assert_eq!(resolve_channel_id("", "C_default"), Some("C_default".to_string()));
722    }
723
724    #[test]
725    fn resolve_channel_id_none_when_both_empty() {
726        assert_eq!(resolve_channel_id("", ""), None);
727    }
728
729    #[test]
730    fn next_backoff_secs_doubles() {
731        assert_eq!(next_backoff_secs(5), 10);
732        assert_eq!(next_backoff_secs(10), 20);
733    }
734
735    #[test]
736    fn next_backoff_secs_caps_at_max() {
737        assert_eq!(next_backoff_secs(45), MAX_RECONNECT_DELAY_SECS);
738        assert_eq!(next_backoff_secs(60), MAX_RECONNECT_DELAY_SECS);
739    }
740
741    // ── Reconnect-on-warning state transition (no real socket needed) ──────
742
743    #[test]
744    fn duplicate_warning_while_cutover_pending_is_a_noop_decision() {
745        // Mirrors the guard in run_session's WarningReceived arm: a second
746        // warning while `cutover_pending` is true must not start a second
747        // concurrent connect. This is the pure boolean condition that
748        // guards that branch.
749        let cutover_pending = true;
750        let should_start_new_cutover = !cutover_pending;
751        assert!(!should_start_new_cutover);
752    }
753
754    #[test]
755    fn fresh_warning_when_not_pending_starts_cutover() {
756        let cutover_pending = false;
757        let should_start_new_cutover = !cutover_pending;
758        assert!(should_start_new_cutover);
759    }
760}