1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
//! Slack Message Handler
//!
//! Processes incoming Slack messages: text, allowlist enforcement,
//! session routing (owner shares TUI session, others get per-user sessions).
//!
//! Uses a module-level static for handler state because slack-morphism's
//! Socket Mode callbacks require plain function pointers (not closures).
use super::SlackState;
use crate::brain::agent::AgentService;
use crate::config::{Config, RespondTo};
use crate::db::ChannelMessageRepository;
use crate::db::models::ChannelMessage as DbChannelMessage;
use crate::services::SessionService;
use crate::utils::sanitize::redact_secrets;
use crate::utils::truncate_str;
use slack_morphism::prelude::*;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, OnceLock};
use tokio::sync::Mutex;
use uuid::Uuid;
/// Socket Mode interaction callback — handles button clicks for tool approvals.
pub async fn on_interaction(
event: SlackInteractionEvent,
client: Arc<SlackHyperClient>,
_states: SlackClientEventsUserState,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if let SlackInteractionEvent::BlockActions(block_actions) = event {
let state = match HANDLER_STATE.get() {
Some(s) => s.clone(),
None => {
tracing::warn!("Slack: interaction received but HANDLER_STATE not initialized");
return Ok(());
}
};
if let Some(actions) = block_actions.actions {
for action in actions {
let action_id = action.action_id.0.as_str();
tracing::info!("Slack callback received: action_id={}", action_id);
// Provider picker callback → show models for that provider
if let Some(provider_name) = action_id.strip_prefix("provider:") {
let resp = crate::channels::commands::models_for_provider(provider_name).await;
tracing::info!("Slack: showing models for provider {}", provider_name);
if let Some(ref channel) = block_actions.channel {
let token =
SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
// Agent-handled providers (OpenRouter 300+ models, custom)
if resp.agent_handled {
let session_id = *state.shared_session.lock().await;
let display =
crate::channels::commands::provider_display_name(provider_name);
if let Ok(config) = crate::config::Config::load()
&& let Ok(new_provider) =
crate::brain::provider::factory::create_provider_by_name(
&config,
provider_name,
)
.await
{
state.agent.swap_provider(new_provider);
}
if !resp.current_model.is_empty() {
let _ = crate::channels::commands::switch_model(
&state.agent,
&resp.current_model,
session_id,
)
.await;
}
if let Some(sid) = session_id {
let prompt = if resp.current_model.is_empty() {
format!(
"[System: User selected {} provider but no default model is set. \
Ask them which model they want. Use config_manager tool to read \
providers section, then set the default_model. Keep current provider \
until a model is chosen.]",
display
)
} else {
format!(
"[System: User switched to {} provider with model {}. \
Confirm the switch. Ask if they want a different model — \
if so, use config_manager to update providers.{}.default_model \
and confirm.]",
display,
resp.current_model,
if provider_name == "openrouter" {
"openrouter"
} else {
provider_name
}
)
};
let agent_clone = state.agent.clone();
let bot_token = state.current_bot_token();
let channel_id_clone = channel.id.clone();
let client_clone = client.clone();
tokio::spawn(async move {
match agent_clone.send_message(sid, prompt, None).await {
Ok(r) => {
let token = SlackApiToken::new(
SlackApiTokenValue::from(bot_token),
);
let session = client_clone.open_session(&token);
let request = SlackApiChatPostMessageRequest::new(
channel_id_clone,
SlackMessageContent::new().with_text(r.content),
);
let _ = session.chat_post_message(&request).await;
}
Err(e) => tracing::error!("Agent follow-up failed: {}", e),
}
});
}
continue;
}
let header = SlackBlock::Section(SlackSectionBlock::new().with_text(
SlackBlockText::MarkDown(SlackBlockMarkDownText::new(
resp.text.clone(),
)),
));
let buttons: Vec<SlackActionBlockElement> = resp
.models
.iter()
.take(25)
.map(|m| {
let label = if *m == resp.current_model {
format!("✓ {}", m)
} else {
m.clone()
};
SlackActionBlockElement::Button(SlackBlockButtonElement::new(
SlackActionId::new(format!(
"model:{}:{}",
resp.provider_name, m
)),
SlackBlockPlainTextOnly::from(SlackBlockPlainText::new(label)),
))
})
.collect();
let mut blocks = vec![header];
for chunk in buttons.chunks(5) {
blocks
.push(SlackBlock::Actions(SlackActionsBlock::new(chunk.to_vec())));
}
let request = SlackApiChatPostMessageRequest::new(
channel.id.clone(),
SlackMessageContent::new().with_blocks(blocks),
);
let _ = session.chat_post_message(&request).await;
}
continue;
}
// Model switch callback (format: model:<provider>:<model>)
if let Some(rest) = action_id.strip_prefix("model:") {
let (provider_name, model_name) = if let Some((p, m)) = rest.split_once(':') {
(Some(p), m)
} else {
(None, rest)
};
let mut provider_err: Option<String> = None;
if let Some(pname) = provider_name {
match crate::config::Config::load() {
Ok(config) => {
match crate::brain::provider::factory::create_provider_by_name(
&config, pname,
)
.await
{
Ok(new_provider) => state.agent.swap_provider(new_provider),
Err(e) => {
provider_err = Some(format!(
"Failed to create provider '{}': {}",
pname, e
))
}
}
}
Err(e) => provider_err = Some(format!("Failed to load config: {}", e)),
}
}
let reply = if let Some(err) = provider_err {
tracing::warn!("Slack: provider switch failed: {}", err);
format!("⚠️ {}", err)
} else {
let session_id = *state.shared_session.lock().await;
match crate::channels::commands::switch_model(
&state.agent,
model_name,
session_id,
)
.await
{
Ok(_) => {
tracing::info!("Slack: model switched to {}", model_name);
format!("✅ Model switched to `{}`", model_name)
}
Err(e) => {
tracing::warn!("Slack: model switch failed: {}", e);
format!("⚠️ {}", e)
}
}
};
if let Some(ref channel) = block_actions.channel {
let token =
SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let request = SlackApiChatPostMessageRequest::new(
channel.id.clone(),
SlackMessageContent::new().with_text(reply),
);
let _ = session.chat_post_message(&request).await;
}
continue;
}
// Session switch callback
if let Some(session_id_str) = action_id.strip_prefix("session:") {
if let Ok(new_id) = session_id_str.parse::<Uuid>() {
let cfg = state.config_rx.borrow().clone();
let caller_id = block_actions
.user
.as_ref()
.map(|u| u.id.0.as_str())
.unwrap_or("");
let is_owner = cfg.channels.slack.allowed_users.is_empty()
|| cfg
.channels
.slack
.allowed_users
.first()
.map(|a| a == caller_id)
.unwrap_or(false);
if is_owner {
*state.shared_session.lock().await = Some(new_id);
} else {
state
.extra_sessions
.lock()
.await
.insert(caller_id.to_string(), (new_id, std::time::Instant::now()));
}
if let Some(ref channel) = block_actions.channel {
state
.slack_state
.register_session_channel(new_id, channel.id.0.to_string())
.await;
let token = SlackApiToken::new(SlackApiTokenValue::from(
state.current_bot_token(),
));
let session = client.open_session(&token);
let display = match state.session_svc.get_session(new_id).await {
Ok(Some(s)) => s.title.unwrap_or_else(|| {
session_id_str[..8.min(session_id_str.len())].to_string()
}),
_ => session_id_str[..8.min(session_id_str.len())].to_string(),
};
let request = SlackApiChatPostMessageRequest::new(
channel.id.clone(),
SlackMessageContent::new()
.with_text(format!("✅ Switched to session `{}`", display)),
);
let _ = session.chat_post_message(&request).await;
}
}
continue;
}
let (approved, always, yolo, id) =
if let Some(id) = action_id.strip_prefix("approve:") {
(true, false, false, id.to_string())
} else if let Some(id) = action_id.strip_prefix("always:") {
(true, true, false, id.to_string())
} else if let Some(id) = action_id.strip_prefix("yolo:") {
(true, true, true, id.to_string())
} else if let Some(id) = action_id.strip_prefix("deny:") {
(false, false, false, id.to_string())
} else {
tracing::warn!("Slack: unknown action_id: {}", action_id);
continue;
};
if yolo {
crate::utils::persist_auto_always_policy();
}
let resolved = state
.slack_state
.resolve_pending_approval(&id, approved, always)
.await;
tracing::info!(
"Slack approval resolved: id={}, approved={}, always={}, found_pending={}",
id,
approved,
always,
resolved
);
if !resolved {
tracing::warn!(
"Slack: no pending approval for id={} — may have timed out or already resolved",
id
);
}
}
}
}
Ok(())
}
/// Global handler state — set once by the agent before starting the listener.
pub static HANDLER_STATE: OnceLock<Arc<HandlerState>> = OnceLock::new();
/// Shared state for the Slack message handler callbacks.
pub struct HandlerState {
pub agent: Arc<AgentService>,
pub session_svc: SessionService,
pub extra_sessions: Arc<Mutex<HashMap<String, (Uuid, std::time::Instant)>>>,
pub shared_session: Arc<Mutex<Option<Uuid>>>,
pub slack_state: Arc<SlackState>,
pub bot_token: String,
pub bot_user_id: Option<String>,
pub config_rx: tokio::sync::watch::Receiver<Config>,
pub channel_msg_repo: ChannelMessageRepository,
/// Dedup: recently seen message timestamps (Slack retries if ack is slow).
/// Entries are pruned when they exceed 200.
pub seen_ts: Mutex<HashSet<String>>,
}
impl HandlerState {
/// Get the current bot token — prefers hot-reloaded config, falls back to startup token.
pub fn current_bot_token(&self) -> String {
self.config_rx
.borrow()
.channels
.slack
.token
.clone()
.filter(|t| !t.is_empty())
.unwrap_or_else(|| self.bot_token.clone())
}
}
/// Split a message into chunks that fit Slack's limit (conservative 3000 chars).
pub fn split_message(text: &str, max_len: usize) -> Vec<&str> {
if text.len() <= max_len {
return vec![text];
}
let mut chunks = Vec::new();
let mut start = 0;
while start < text.len() {
let mut end = (start + max_len).min(text.len());
// Ensure end falls on a char boundary (back up if inside a multi-byte char)
while end < text.len() && !text.is_char_boundary(end) {
end -= 1;
}
let break_at = if end < text.len() {
text[start..end]
.rfind('\n')
.filter(|&pos| pos > end - start - 200)
.map(|pos| start + pos + 1)
.unwrap_or(end)
} else {
end
};
chunks.push(&text[start..break_at]);
start = break_at;
}
chunks
}
/// Socket Mode push event callback (function pointer — required by slack-morphism).
///
/// Returns immediately so Slack gets the ack within 3 s (prevents retries).
/// Actual processing is spawned as a background task.
/// Deduplicates by message timestamp to drop Slack retries.
pub async fn on_push_event(
event: SlackPushEventCallback,
client: Arc<SlackHyperClient>,
_states: SlackClientEventsUserState,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
tracing::debug!("Slack: received push event");
match event.event {
SlackEventCallbackBody::Message(msg) => {
let ts = msg.origin.ts.to_string();
if !dedup_ts(&ts).await {
return Ok(());
}
tracing::debug!(
"Slack: message event from user={:?}, channel={:?}, bot_id={:?}",
msg.sender.user,
msg.origin.channel,
msg.sender.bot_id
);
tokio::spawn(async move {
handle_message(&msg, client, false).await;
});
}
SlackEventCallbackBody::AppMention(mention) => {
let ts = mention.origin.ts.to_string();
if !dedup_ts(&ts).await {
return Ok(());
}
tracing::info!(
"Slack: app_mention from user={:?}, channel={:?}, text={:?}",
mention.user,
mention.channel,
mention
.content
.text
.as_ref()
.map(|t| crate::utils::truncate_str(t, 80)),
);
// Convert app_mention into a SlackMessageEvent so handle_message can process it
let msg = SlackMessageEvent {
origin: SlackMessageOrigin {
ts: mention.origin.ts,
channel: Some(mention.channel),
channel_type: None,
thread_ts: mention.origin.thread_ts,
client_msg_id: None,
},
content: Some(mention.content),
sender: SlackMessageSender {
user: Some(mention.user),
bot_id: None,
username: None,
display_as_bot: None,
user_profile: None,
bot_profile: None,
},
subtype: None,
hidden: None,
message: None,
previous_message: None,
deleted_ts: None,
};
tokio::spawn(async move {
handle_message(&msg, client, true).await;
});
}
other => {
tracing::debug!(
"Slack: unhandled event type: {:?}",
std::any::type_name_of_val(&other)
);
}
}
Ok(())
}
/// Returns `true` if this is the first time we see this timestamp (proceed).
/// Returns `false` if it's a duplicate (skip).
async fn dedup_ts(ts: &str) -> bool {
let state = match HANDLER_STATE.get() {
Some(s) => s,
None => return true,
};
let mut seen = state.seen_ts.lock().await;
if !seen.insert(ts.to_string()) {
tracing::debug!("Slack: dropping duplicate event ts={}", ts);
return false;
}
// Prune if too large to avoid unbounded growth
if seen.len() > 200 {
seen.clear();
seen.insert(ts.to_string());
}
true
}
/// Socket Mode error handler.
pub fn on_error(
err: Box<dyn std::error::Error + Send + Sync>,
_client: Arc<SlackHyperClient>,
_states: SlackClientEventsUserState,
) -> HttpStatusCode {
tracing::error!("Slack: socket mode error: {}", err);
HttpStatusCode::OK
}
/// Handle an incoming Slack message event.
async fn handle_message(
msg: &SlackMessageEvent,
client: Arc<SlackHyperClient>,
is_app_mention: bool,
) {
let state = match HANDLER_STATE.get() {
Some(s) => s.clone(),
None => {
tracing::error!("Slack: handler state not initialized");
return;
}
};
// Skip bot messages
if msg.sender.bot_id.is_some() {
tracing::debug!(
"Slack: skipping bot message (bot_id={:?})",
msg.sender.bot_id
);
return;
}
// Extract user ID
let user_id = match &msg.sender.user {
Some(uid) => uid.to_string(),
None => {
tracing::debug!("Slack: message has no sender user ID, ignoring");
return;
}
};
// Extract channel ID
let channel_id = match &msg.origin.channel {
Some(ch) => ch.to_string(),
None => {
tracing::debug!("Slack: message has no channel ID, ignoring");
return;
}
};
// Resolve user display name via Slack API (cached per conversation turn)
let user_name = {
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
match session
.users_info(&SlackApiUsersInfoRequest::new(SlackUserId::new(
user_id.clone(),
)))
.await
{
Ok(resp) => resp
.user
.profile
.as_ref()
.and_then(|p| {
p.display_name
.clone()
.filter(|n| !n.is_empty())
.or_else(|| p.real_name.clone())
})
.unwrap_or_else(|| user_id.clone()),
Err(e) => {
tracing::debug!("Slack: failed to resolve user name for {}: {}", user_id, e);
user_id.clone()
}
}
};
// Resolve channel name via Slack API
let channel_name = {
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
match session
.conversations_info(&SlackApiConversationsInfoRequest::new(SlackChannelId::new(
channel_id.clone(),
)))
.await
{
Ok(resp) => resp
.channel
.name
.map(|n| format!("#{n}"))
.unwrap_or_else(|| channel_id.clone()),
Err(e) => {
tracing::debug!(
"Slack: failed to resolve channel name for {}: {}",
channel_id,
e
);
channel_id.clone()
}
}
};
// Extract text (may be empty if user sent files only)
let text = msg
.content
.as_ref()
.and_then(|c| c.text.clone())
.unwrap_or_default();
// Check for files
let files: Vec<_> = msg
.content
.as_ref()
.and_then(|c| c.files.as_ref())
.map(|v| v.as_slice())
.unwrap_or(&[])
.to_vec();
// Require at least text or files
if text.is_empty() && files.is_empty() {
tracing::debug!("Slack: message has no text and no files, ignoring");
return;
}
// Helper: passively capture a channel message for history
let store_channel_msg = |text: String| {
let repo = state.channel_msg_repo.clone();
let ch_id = channel_id.clone();
let uid = user_id.clone();
let uname = user_name.clone();
let ch_name = channel_name.clone();
async move {
if text.is_empty() {
return;
}
let cm = DbChannelMessage::new(
"slack".into(),
ch_id,
Some(ch_name),
uid,
uname,
text,
"text".into(),
None,
);
if let Err(e) = repo.insert(&cm).await {
tracing::warn!("Failed to store Slack channel message: {e}");
}
}
};
// Read latest config from watch channel — single source of truth
let cfg = state.config_rx.borrow().clone();
let sl_cfg = &cfg.channels.slack;
let allowed: HashSet<String> = sl_cfg.allowed_users.iter().cloned().collect();
let respond_to = &sl_cfg.respond_to;
let allowed_channels: HashSet<String> = sl_cfg.allowed_channels.iter().cloned().collect();
let idle_timeout_hours = sl_cfg.session_idle_hours;
let voice_config = cfg.voice_config();
// Allowlist check — if allowed list is empty, accept all
if !allowed.is_empty() && !allowed.contains(&user_id) {
tracing::debug!("Slack: ignoring message from non-allowed user {}", user_id);
return;
}
// respond_to / allowed_channels filtering — DMs (channel starts with 'D') always pass
let is_dm = channel_id.starts_with('D');
if !is_dm {
// Check allowed_channels (empty = all channels allowed)
if !allowed_channels.is_empty() && !allowed_channels.contains(&channel_id) {
tracing::debug!(
"Slack: ignoring message in non-allowed channel {}",
channel_id
);
store_channel_msg(text.clone()).await;
return;
}
match respond_to {
RespondTo::DmOnly => {
tracing::debug!("Slack: respond_to=dm_only, ignoring channel message");
store_channel_msg(text.clone()).await;
return;
}
RespondTo::Mention => {
// app_mention events are already verified by Slack — trust them
let mentioned = is_app_mention
|| if let Some(ref bid) = state.bot_user_id {
text.contains(&format!("<@{}>", bid))
} else {
text.contains("<@U")
};
if !mentioned {
tracing::debug!(
"Slack: respond_to=mention, bot not mentioned — ignoring (bot_user_id={:?}, text={:?})",
state.bot_user_id,
crate::utils::truncate_str(&text, 120),
);
store_channel_msg(text.clone()).await;
return;
}
}
RespondTo::All => {} // pass through
}
}
// Also store directed channel messages for complete history
if !is_dm {
store_channel_msg(text.clone()).await;
}
// Strip <@BOT_ID> from text when responding to a mention
let text = if !is_dm && *respond_to == RespondTo::Mention {
if let Some(ref bid) = state.bot_user_id {
text.replace(&format!("<@{}>", bid), "").trim().to_string()
} else {
// bot_user_id unknown — strip any <@U...> mention tag
let re = regex::Regex::new(r"<@U[A-Z0-9]+>").unwrap();
re.replace_all(&text, "").trim().to_string()
}
} else {
text
};
let text_preview = truncate_str(&text, 50);
tracing::info!("Slack: message from {}: {}", user_id, text_preview);
// Track owner's channel for proactive messaging
let is_owner = allowed.is_empty()
|| allowed
.iter()
.next()
.map(|a| *a == user_id)
.unwrap_or(false);
if is_owner {
state
.slack_state
.set_owner_channel(channel_id.clone())
.await;
}
// Resolve session: owner DM shares TUI session; channels/groups get per-channel sessions
let session_id = if is_owner && is_dm {
let shared = state.shared_session.lock().await;
match *shared {
Some(id) => id,
None => {
drop(shared);
// Resume most recent session from DB (survives daemon restarts)
let restored = match state.session_svc.get_most_recent_session().await {
Ok(Some(s)) => {
tracing::info!("Slack: restored most recent session {}", s.id);
Some(s.id)
}
_ => None,
};
let id = match restored {
Some(id) => id,
None => {
tracing::info!("Slack: no existing session, creating one for owner");
match crate::channels::session_init::create_channel_session(
&state.session_svc,
Some("Chat".to_string()),
)
.await
{
Ok(session) => session.id,
Err(e) => {
tracing::error!("Slack: failed to create session: {}", e);
return;
}
}
}
};
*state.shared_session.lock().await = Some(id);
id
}
}
} else {
// Non-DM-owner sessions: keyed by channel_id for channels (shared per channel),
// by user_id for DMs (separate per user).
// Persisted in DB by title — survives restarts.
let session_title = if is_dm {
format!("Slack: {}", user_id)
} else {
format!("Slack: #{}", channel_id)
};
// Look up existing session from DB
let existing = state
.session_svc
.find_session_by_title(&session_title)
.await
.ok()
.flatten();
if let Some(session) = existing {
// Check idle timeout
if idle_timeout_hours.is_some_and(|h| {
let elapsed = (chrono::Utc::now() - session.updated_at).num_seconds();
elapsed > (h * 3600.0) as i64
}) {
if let Err(e) = state.session_svc.archive_session(session.id).await {
tracing::error!("Slack: failed to archive session {}: {}", session.id, e);
}
match crate::channels::session_init::create_channel_session(
&state.session_svc,
Some(session_title),
)
.await
{
Ok(new_session) => new_session.id,
Err(e) => {
tracing::error!("Slack: failed to create session: {}", e);
return;
}
}
} else {
session.id
}
} else {
match crate::channels::session_init::create_channel_session(
&state.session_svc,
Some(session_title),
)
.await
{
Ok(session) => {
tracing::info!(
"Slack: created new channel session {} for {}",
session.id,
if is_dm { &user_id } else { &channel_id }
);
session.id
}
Err(e) => {
tracing::error!("Slack: failed to create session: {}", e);
return;
}
}
}
};
// Process attached files — images as <<IMG:tmp_path>>, text files extracted inline
let mut content = text.clone();
// Set to true if an incoming audio attachment is successfully transcribed.
// Used to decide whether to mirror the text response as a TTS voice note.
let mut is_voice = false;
if !files.is_empty() {
use crate::utils::{inject_file_content, process_file_with_vision};
let cfg = match crate::config::Config::load() {
Ok(c) => c,
Err(e) => {
tracing::error!("Slack: failed to load config: {}", e);
return;
}
};
let http = reqwest::Client::new();
for file in &files {
let mime = file.mimetype.as_ref().map(|m| m.0.as_str()).unwrap_or("");
let fname = file.name.as_deref().unwrap_or("file");
// Download file using bot token (Slack private URLs require auth)
let dl_url = match file
.url_private_download
.as_ref()
.or(file.url_private.as_ref())
{
Some(u) => u.to_string(),
None => continue,
};
let dl_bytes = match http
.get(&dl_url)
.header(
"Authorization",
format!("Bearer {}", state.current_bot_token()),
)
.send()
.await
{
Ok(resp) => match resp.bytes().await {
Ok(b) => b.to_vec(),
Err(e) => {
tracing::error!("Slack: failed to read file bytes: {e}");
continue;
}
},
Err(e) => {
tracing::error!("Slack: failed to download file {}: {e}", fname);
continue;
}
};
// Audio → STT
if mime.starts_with("audio/") {
if voice_config.stt_enabled {
match crate::channels::voice::transcribe(dl_bytes, &voice_config).await {
Ok(transcript) => {
tracing::info!(
"Slack: transcribed audio: {}",
truncate_str(&transcript, 80)
);
if content.is_empty() {
content = transcript;
} else {
content.push_str(&format!("\n\n[Transcription]: {transcript}"));
}
is_voice = true;
}
Err(e) => tracing::error!("Slack: STT error: {e}"),
}
}
continue;
}
let fc = process_file_with_vision(&dl_bytes, mime, fname, &cfg);
let injected = inject_file_content(&fc).0;
if !injected.is_empty() {
if content.is_empty() {
content = injected;
} else {
content.push_str(&format!("\n\n{injected}"));
}
}
}
}
if content.is_empty() {
tracing::debug!("Slack: no processable content after file handling, ignoring");
return;
}
// Restore session's own provider (each session keeps its provider independently)
let session_meta = state
.session_svc
.get_session(session_id)
.await
.ok()
.flatten();
crate::channels::commands::sync_provider_for_session(
&state.agent,
session_meta
.as_ref()
.and_then(|s| s.provider_name.as_deref()),
session_meta.as_ref().and_then(|s| s.model.as_deref()),
)
.await;
// ── Channel commands (/help, /usage, /models) ──────────────────────────
{
use crate::channels::commands::{self, ChannelCommand};
let cmd =
commands::handle_command(&content, session_id, &state.agent, &state.session_svc).await;
// Handle simple text-response commands (Help, Usage, Evolve, Doctor, etc.)
if let Some(reply) = commands::try_execute_text_command(&cmd).await {
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new().with_text(reply),
);
let _ = session.chat_post_message(&request).await;
return;
}
match cmd {
ChannelCommand::Models(resp) => {
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let header = SlackBlock::Section(SlackSectionBlock::new().with_text(
SlackBlockText::MarkDown(SlackBlockMarkDownText::new(resp.text.clone())),
));
let buttons: Vec<SlackActionBlockElement> = resp
.providers
.iter()
.take(25)
.map(|(name, label)| {
let display = if *name == resp.current_provider {
format!("✓ {}", label)
} else {
label.clone()
};
SlackActionBlockElement::Button(SlackBlockButtonElement::new(
SlackActionId::new(format!("provider:{}", name)),
SlackBlockPlainTextOnly::from(SlackBlockPlainText::new(display)),
))
})
.collect();
let mut blocks = vec![header];
for chunk in buttons.chunks(5) {
blocks.push(SlackBlock::Actions(SlackActionsBlock::new(chunk.to_vec())));
}
let request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new().with_blocks(blocks),
);
let _ = session.chat_post_message(&request).await;
return;
}
ChannelCommand::NewSession => {
// Archive the current channel session before creating a new one
let session_title = if is_dm {
format!("Slack: {}", user_id)
} else {
format!("Slack: #{}", channel_id)
};
if let Ok(Some(old)) = state
.session_svc
.find_session_by_title(&session_title)
.await
&& let Err(e) = state.session_svc.archive_session(old.id).await
{
tracing::error!("Slack: failed to archive old session {}: {}", old.id, e);
}
match crate::channels::session_init::create_channel_session(
&state.session_svc,
Some(session_title),
)
.await
{
Ok(new_session) => {
if is_owner && is_dm {
*state.shared_session.lock().await = Some(new_session.id);
}
state
.slack_state
.register_session_channel(new_session.id, channel_id.clone())
.await;
let token =
SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new()
.with_text("✅ New session started.".to_string()),
);
let _ = session.chat_post_message(&request).await;
}
Err(e) => {
tracing::error!("Slack: failed to create session: {}", e);
let token =
SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new()
.with_text("Failed to create session.".to_string()),
);
let _ = session.chat_post_message(&request).await;
}
}
return;
}
ChannelCommand::Sessions(resp) => {
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let header = SlackBlock::Section(SlackSectionBlock::new().with_text(
SlackBlockText::MarkDown(SlackBlockMarkDownText::new(resp.text.clone())),
));
let buttons: Vec<SlackActionBlockElement> = resp
.sessions
.iter()
.take(25)
.map(|(id, label)| {
let display = if *id == resp.current_session_id {
format!("✓ {}", label)
} else {
label.clone()
};
SlackActionBlockElement::Button(SlackBlockButtonElement::new(
SlackActionId::new(format!("session:{}", id)),
SlackBlockPlainTextOnly::from(SlackBlockPlainText::new(display)),
))
})
.collect();
let mut blocks = vec![header];
for chunk in buttons.chunks(5) {
blocks.push(SlackBlock::Actions(SlackActionsBlock::new(chunk.to_vec())));
}
let request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new().with_blocks(blocks),
);
let _ = session.chat_post_message(&request).await;
return;
}
ChannelCommand::Stop => {
let cancelled = state.slack_state.cancel_session(session_id).await;
let reply = if cancelled {
"Operation cancelled."
} else {
"No operation in progress."
};
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new().with_text(reply.to_string()),
);
let _ = session.chat_post_message(&request).await;
return;
}
ChannelCommand::Compact => {
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id.clone()),
SlackMessageContent::new().with_text("⏳ Compacting context...".to_string()),
);
let _ = session.chat_post_message(&request).await;
content =
"[SYSTEM: Compact context now. Summarize this conversation for continuity.]"
.to_string();
}
ChannelCommand::UserPrompt(prompt) => {
content = prompt;
// fall through to agent with the prompt as the message
}
ChannelCommand::NotACommand => {}
// Help, Usage, Evolve, Doctor, UserSystem handled by try_execute_text_command above
_ => {}
}
}
// Detect thread replies so the agent knows the message is in a thread context.
// Also store the thread_ts so we reply in the same thread.
let thread_ts = msg.origin.thread_ts.clone();
let reply_context = thread_ts
.as_ref()
.map(|ts| format!("[Replying in thread (thread_ts: {ts})]"));
// For non-owner users, prepend sender identity so the agent knows who
// it's talking to and doesn't assume it's the owner.
let agent_input = if !is_owner {
if is_dm {
format!("[Slack DM from {user_name} ({user_id})]\n{content}")
} else {
format!("[Slack message from {user_name} ({user_id}) in {channel_name}]\n{content}")
}
} else {
content
};
// Prepend reply/thread context if the message is in a thread.
let agent_input = if let Some(ref ctx) = reply_context {
format!("{ctx}\n{agent_input}")
} else {
agent_input
};
// Inject recent channel history so the agent has full conversation context.
let agent_input = if !is_dm {
match state
.channel_msg_repo
.recent(Some("slack"), &channel_id, 30)
.await
{
Ok(messages) if !messages.is_empty() => {
let history: Vec<String> = messages
.iter()
.rev()
.map(|m| {
let ts = m.created_at.format("%H:%M");
format!("[{}] {}: {}", ts, m.sender_name, m.content)
})
.collect();
format!(
"[Recent channel history ({} messages):\n{}\n--- end history ---]\n{}",
history.len(),
history.join("\n"),
agent_input
)
}
_ => agent_input,
}
} else {
agent_input
};
// Tell the LLM its text response is automatically delivered to the chat,
// so it should NOT use slack_send for simple text replies.
let agent_input = format!(
"[Channel: Slack — your text response is automatically sent to this channel. \
Do NOT call slack_send to deliver your answer. Only use slack_send for: \
sending to a different channel, threads, blocks, reactions, files, or moderation.]\n{agent_input}"
);
// Register channel for approval routing, then send with approval callback
state
.slack_state
.register_session_channel(session_id, channel_id.clone())
.await;
let approval_cb = make_approval_callback(state.slack_state.clone());
let cancel_token = tokio_util::sync::CancellationToken::new();
state
.slack_state
.store_cancel_token(session_id, cancel_token.clone())
.await;
// Post a "thinking" placeholder so the user knows we're processing
let thinking_ts: Arc<Mutex<Option<SlackTs>>> = Arc::new(Mutex::new(None));
{
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let mut req = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id.clone()),
SlackMessageContent::new().with_text("_thinking..._".to_string()),
);
if let Some(ref ts) = thread_ts {
req = req.with_thread_ts(ts.clone());
}
if let Ok(resp) = session.chat_post_message(&req).await {
*thinking_ts.lock().await = Some(resp.ts);
}
}
// Track sent intermediate messages for dedup against final response
let sent_intermediates: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let sent_intermediates_final = sent_intermediates.clone();
// Build progress callback — sends tool call status as Slack messages
let progress_cb: crate::brain::agent::ProgressCallback = {
use crate::brain::agent::ProgressEvent;
struct ToolEntry {
msg_ts: Option<SlackTs>,
name: String,
context: String,
}
let tools: Arc<Mutex<Vec<ToolEntry>>> = Arc::new(Mutex::new(Vec::new()));
let bot_token_cb = state.current_bot_token();
let channel_cb = SlackChannelId::new(channel_id.clone());
let client_cb = client.clone();
let thinking_ts_cb = thinking_ts.clone();
let thread_ts_cb = thread_ts.clone();
Arc::new(move |_session_id, event| {
let tools = tools.clone();
let sent = sent_intermediates.clone();
let token = SlackApiToken::new(SlackApiTokenValue::from(bot_token_cb.clone()));
let channel = channel_cb.clone();
let client = client_cb.clone();
let thread_ts_inner = thread_ts_cb.clone();
match event {
ProgressEvent::ToolStarted {
tool_name,
tool_input,
} => {
let thinking_ts = thinking_ts_cb.clone();
let ctx = crate::utils::tool_context_hint(&tool_name, &tool_input);
tokio::spawn(async move {
let session = client.open_session(&token);
// Delete the "thinking..." placeholder on first tool call
if let Some(ts) = thinking_ts.lock().await.take() {
let del = SlackApiChatDeleteRequest::new(channel.clone(), ts);
let _ = session.chat_delete(&del).await;
}
let text = format!("⚙️ *{}*{}", tool_name, ctx);
let mut req = SlackApiChatPostMessageRequest::new(
channel,
SlackMessageContent::new().with_text(text),
);
if let Some(ref ts) = thread_ts_inner {
req = req.with_thread_ts(ts.clone());
}
if let Ok(resp) = session.chat_post_message(&req).await {
let mut t = tools.lock().await;
t.push(ToolEntry {
msg_ts: Some(resp.ts),
name: tool_name,
context: ctx,
});
}
});
}
ProgressEvent::ToolCompleted {
tool_name, success, ..
} => {
tokio::spawn(async move {
let session = client.open_session(&token);
let mut t = tools.lock().await;
if let Some(entry) = t
.iter_mut()
.rev()
.find(|e| e.name == tool_name && e.msg_ts.is_some())
{
let icon = if success { "✅" } else { "❌" };
let text = format!("{} *{}*{}", icon, entry.name, entry.context);
if let Some(ts) = entry.msg_ts.take() {
let upd = SlackApiChatUpdateRequest::new(
channel,
SlackMessageContent::new().with_text(text),
ts,
);
let _ = session.chat_update(&upd).await;
}
}
});
}
ProgressEvent::SelfHealingAlert { message } => {
let thread_ts_heal = thread_ts_inner.clone();
tokio::spawn(async move {
let session = client.open_session(&token);
let text = format!("🔧 {}", message);
let mut req = SlackApiChatPostMessageRequest::new(
channel,
SlackMessageContent::new().with_text(text),
);
if let Some(ref ts) = thread_ts_heal {
req = req.with_thread_ts(ts.clone());
}
let _ = session.chat_post_message(&req).await;
});
}
ProgressEvent::IntermediateText { text, .. } => {
let thread_ts_resp = thread_ts_inner.clone();
let sent_ref = sent.clone();
tokio::spawn(async move {
let session = client.open_session(&token);
let text_fmt = crate::utils::slack_fmt::markdown_to_mrkdwn(&text);
let mut req = SlackApiChatPostMessageRequest::new(
channel,
SlackMessageContent::new().with_text(text_fmt),
);
if let Some(ref ts) = thread_ts_resp {
req = req.with_thread_ts(ts.clone());
}
if let Err(e) = session.chat_post_message(&req).await {
tracing::debug!("Slack: failed to send intermediate text: {}", e);
} else {
sent_ref.lock().await.push(text);
}
});
}
_ => {}
}
})
};
let result = state
.agent
.send_message_with_tools_and_callback(
session_id,
agent_input,
None,
Some(cancel_token),
Some(approval_cb),
Some(progress_cb),
"slack",
Some(&channel_id),
)
.await;
state.slack_state.remove_cancel_token(session_id).await;
// Delete the "thinking..." placeholder if it's still around
{
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
if let Some(ts) = thinking_ts.lock().await.take() {
let del = SlackApiChatDeleteRequest::new(SlackChannelId::new(channel_id.clone()), ts);
let _ = session.chat_delete(&del).await;
}
}
match result {
Ok(response) => {
// Extract <<IMG:path>> markers — upload each as a Slack file.
let (text_only, img_paths) = crate::utils::extract_img_markers(&response.content);
let text_only = crate::utils::sanitize::strip_llm_artifacts(&text_only);
let text_only = redact_secrets(&text_only);
// Dedup: strip text that was already sent as intermediate messages
// to avoid duplicating content on Slack.
let sent = sent_intermediates_final.lock().await.clone();
tracing::info!(
"Slack dedup: response.content len={}, sent_intermediates count={}",
text_only.len(),
sent.len()
);
let text_only = if !sent.is_empty() {
let mut remaining = text_only.clone();
for intermediate in &sent {
remaining = remaining.replace(intermediate.as_str(), "");
}
let result = remaining.trim().to_string();
if result != text_only {
tracing::info!(
"Slack dedup: stripped {} chars, remaining len={}",
text_only.len() - result.len(),
result.len()
);
} else {
tracing::warn!(
"Slack dedup: NO MATCH — none of {} intermediates found in response",
sent.len()
);
}
// If dedup stripped everything, the intermediates already
// cover the full response — nothing new to send. Safe here
// because Slack's intermediate handler only pushes to
// sent_intermediates on confirmed successful post.
if result.is_empty() {
tracing::info!(
"Slack dedup: result empty after stripping — intermediates already delivered full response (len={})",
text_only.len()
);
String::new()
} else {
result
}
} else {
tracing::info!("Slack dedup: no intermediates to strip");
text_only
};
let text_only = crate::utils::slack_fmt::markdown_to_mrkdwn(&text_only);
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
for img_path in img_paths {
match tokio::fs::read(&img_path).await {
Ok(bytes) => {
let fname = std::path::Path::new(&img_path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("image.png")
.to_string();
#[allow(deprecated)]
let req = SlackApiFilesUploadRequest {
channels: Some(vec![SlackChannelId::new(channel_id.clone())]),
binary_content: Some(bytes),
filename: Some(fname),
filetype: None,
content: None,
initial_comment: None,
thread_ts: None,
title: None,
file_content_type: Some("image/png".to_string()),
};
#[allow(deprecated)]
if let Err(e) = session.files_upload(&req).await {
tracing::error!("Slack: failed to upload generated image: {}", e);
}
}
Err(e) => {
tracing::error!("Slack: failed to read image {}: {}", img_path, e);
}
}
}
for chunk in split_message(&text_only, 3000) {
if chunk.is_empty() {
continue;
}
let mut request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id.clone()),
SlackMessageContent::new().with_text(chunk.to_string()),
);
if let Some(ref ts) = thread_ts {
request = request.with_thread_ts(ts.clone());
}
if let Err(e) = session.chat_post_message(&request).await {
tracing::error!("Slack: failed to send reply: {}", e);
}
}
// Record the bot's reply in channel_messages so recent() context
// queries on the next turn see both sides of the conversation,
// not only user messages. Matches the Telegram/Discord/WhatsApp
// pattern. Applies to all Slack chats (channels + DMs) since
// store_channel_msg above also stores for both.
if !text_only.trim().is_empty() {
let cm = DbChannelMessage::new(
"slack".into(),
channel_id.clone(),
Some(channel_name.clone()),
"bot:opencrabs".to_string(),
"OpenCrabs".to_string(),
text_only.clone(),
"text".into(),
None,
);
if let Err(e) = state.channel_msg_repo.insert(&cm).await {
tracing::warn!(
"Slack: failed to record bot reply in channel_messages: {}",
e
);
}
}
// If input was audio AND TTS is enabled, also upload a voice note
// (OGG/Opus) alongside the text reply. Slack doesn't have a
// dedicated "voice note" primitive like Telegram's send_voice —
// audio files uploaded via files.upload play inline with a
// waveform UI, which is the closest analogue.
if is_voice && voice_config.tts_enabled {
tracing::info!(
"Slack: TTS requested — synthesizing response text (len={})",
response.content.len()
);
match crate::channels::voice::synthesize(&response.content, &voice_config).await {
Ok(audio_bytes) => {
tracing::info!(
"Slack: TTS succeeded — {} bytes of audio, uploading to channel {}",
audio_bytes.len(),
channel_id
);
#[allow(deprecated)]
let req = SlackApiFilesUploadRequest {
channels: Some(vec![SlackChannelId::new(channel_id.clone())]),
binary_content: Some(audio_bytes),
filename: Some("response.ogg".to_string()),
filetype: Some(SlackFileType("ogg".to_string())),
content: None,
initial_comment: None,
thread_ts: thread_ts.clone(),
title: None,
file_content_type: Some("audio/ogg".to_string()),
};
#[allow(deprecated)]
if let Err(e) = session.files_upload(&req).await {
tracing::error!("Slack: failed to upload TTS voice note: {}", e);
}
}
Err(e) => {
tracing::error!("Slack: TTS synthesis failed: {:#}", e);
}
}
}
}
Err(ref e) if matches!(e, crate::brain::agent::AgentError::Cancelled) => {
tracing::info!("Slack: agent call cancelled for session {}", session_id);
}
Err(e) => {
tracing::error!("Slack: agent error: {}", e);
let token = SlackApiToken::new(SlackApiTokenValue::from(state.current_bot_token()));
let session = client.open_session(&token);
let error_msg = format!("Error: {}", e);
let mut request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new().with_text(error_msg),
);
if let Some(ref ts) = thread_ts {
request = request.with_thread_ts(ts.clone());
}
let _ = session.chat_post_message(&request).await;
}
}
}
/// Build an `ApprovalCallback` that sends a Slack Block Kit message with 3 buttons
/// (Yes / Always / No) and waits up to 5 min for a click.
pub(crate) fn make_approval_callback(
state: Arc<super::SlackState>,
) -> crate::brain::agent::ApprovalCallback {
use crate::brain::agent::ToolApprovalInfo;
use crate::utils::{check_approval_policy, persist_auto_session_policy};
use tokio::sync::oneshot;
Arc::new(move |info: ToolApprovalInfo| {
let state = state.clone();
Box::pin(async move {
if let Some(result) = check_approval_policy() {
return Ok(result);
}
let client = match state.client().await {
Some(c) => c,
None => {
tracing::warn!("Slack approval: bot not connected");
return Ok((false, false));
}
};
let bot_token = match state.bot_token().await {
Some(t) => t,
None => {
tracing::warn!("Slack approval: no bot token");
return Ok((false, false));
}
};
let channel_id = match state.session_channel(info.session_id).await {
Some(id) => id,
None => match state.owner_channel_id().await {
Some(id) => id,
None => {
tracing::warn!(
"Slack approval: no channel_id for session {}",
info.session_id
);
return Ok((false, false));
}
},
};
let approval_id = uuid::Uuid::new_v4().to_string();
let safe_input = crate::utils::redact_tool_input(&info.tool_input);
let input_pretty = serde_json::to_string_pretty(&safe_input)
.unwrap_or_else(|_| safe_input.to_string());
let text = format!(
"🔐 *Tool Approval Required*\n\nTool: `{}`\nInput:\n```\n{}\n```",
info.tool_name,
truncate_str(&input_pretty, 1800),
);
let section = SlackBlock::Section(SlackSectionBlock::new().with_text(
SlackBlockText::MarkDown(SlackBlockMarkDownText::new(text.clone())),
));
let approve_btn = SlackBlockButtonElement::new(
SlackActionId::new(format!("approve:{}", approval_id)),
SlackBlockPlainTextOnly::from(SlackBlockPlainText::new("✅ Yes".to_string())),
)
.with_style("primary".to_string());
let always_btn = SlackBlockButtonElement::new(
SlackActionId::new(format!("always:{}", approval_id)),
SlackBlockPlainTextOnly::from(SlackBlockPlainText::new(
"🔁 Always (session)".to_string(),
)),
);
let yolo_btn = SlackBlockButtonElement::new(
SlackActionId::new(format!("yolo:{}", approval_id)),
SlackBlockPlainTextOnly::from(SlackBlockPlainText::new("🔥 YOLO".to_string())),
);
let deny_btn = SlackBlockButtonElement::new(
SlackActionId::new(format!("deny:{}", approval_id)),
SlackBlockPlainTextOnly::from(SlackBlockPlainText::new("❌ No".to_string())),
)
.with_style("danger".to_string());
let actions = SlackBlock::Actions(SlackActionsBlock::new(vec![
SlackActionBlockElement::Button(approve_btn),
SlackActionBlockElement::Button(always_btn),
SlackActionBlockElement::Button(yolo_btn),
SlackActionBlockElement::Button(deny_btn),
]));
let content = SlackMessageContent::new()
.with_text(text)
.with_blocks(vec![section, actions]);
let request = SlackApiChatPostMessageRequest::new(
SlackChannelId::new(channel_id.clone()),
content,
);
let token = SlackApiToken::new(SlackApiTokenValue::from(bot_token.clone()));
let session = client.open_session(&token);
// Register BEFORE sending to prevent race condition
let (tx, rx) = oneshot::channel();
state
.register_pending_approval(approval_id.clone(), tx)
.await;
tracing::info!(
"Slack approval: registered pending id={}, sending to channel={}",
approval_id,
channel_id
);
let sent = match session.chat_post_message(&request).await {
Ok(r) => r,
Err(e) => {
tracing::error!("Slack approval: failed to send message: {}", e);
return Ok((false, false));
}
};
let msg_ts = sent.ts.clone();
tracing::info!(
"Slack approval: message sent, waiting for response (id={})",
approval_id
);
match tokio::time::timeout(std::time::Duration::from_secs(300), rx).await {
Ok(Ok((approved, always))) => {
tracing::info!(
"Slack approval: user responded id={}, approved={}, always={}",
approval_id,
approved,
always
);
if always {
persist_auto_session_policy();
}
let label = if always {
"🔁 Always approved (session)"
} else if approved {
"✅ Approved"
} else {
"❌ Denied"
};
let update = SlackApiChatUpdateRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new().with_text(label.to_string()),
msg_ts,
);
let _ = session.chat_update(&update).await;
Ok((approved, always))
}
Ok(Err(_)) => {
tracing::warn!(
"Slack approval: oneshot channel closed (id={})",
approval_id
);
Ok((false, false))
}
Err(_) => {
tracing::warn!(
"Slack approval: 5-minute timeout — auto-denying (id={})",
approval_id
);
let update = SlackApiChatUpdateRequest::new(
SlackChannelId::new(channel_id),
SlackMessageContent::new()
.with_text("⏱️ Approval timed out — denied".to_string()),
msg_ts,
);
let _ = session.chat_update(&update).await;
Ok((false, false))
}
}
})
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_split_short_message() {
let chunks = split_message("hello", 3000);
assert_eq!(chunks, vec!["hello"]);
}
#[test]
fn test_split_long_message() {
let text = "a\n".repeat(2000);
let chunks = split_message(&text, 3000);
assert!(chunks.len() >= 2);
for chunk in &chunks {
assert!(chunk.len() <= 3000);
}
let joined: String = chunks.into_iter().collect();
assert_eq!(joined, text);
}
}