BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / agent_api / pending.rs

pending.rs

pending.rs 8.0 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2
3use chrono::{DateTime, Utc};
4use mcp::ReactionProposal;
5use store::{Sidebar, Store};
6
7use super::{ProposalEntry, ProposalStatus, agent_label};
8use crate::activity::preview_label;
9use crate::app_state::chat_title;
10use crate::notify::preview_of;
11use crate::rows::reaction_glyph;
12
13const EXCERPT_CHARACTERS: usize = 120;
14
15#[derive(Debug, Clone, PartialEq)]
16pub enum PendingKind {
17 Reply {
18 text: String,
19 },
20 Reaction {
21 glyph: String,
22 message_id: String,
23 excerpt: Option<String>,
24 },
25}
26
27#[derive(Debug, Clone, PartialEq)]
28pub struct PendingProposal {
29 pub id: String,
30 pub conversation_id: String,
31 pub agent: &'static str,
32 pub kind: PendingKind,
33 pub created_at: DateTime<Utc>,
34 pub seen: bool,
35}
36
37impl PendingProposal {
38 pub fn title(&self) -> String {
39 let what = match self.kind {
40 PendingKind::Reply { .. } => "a reply",
41 PendingKind::Reaction { .. } => "a reaction",
42 };
43 format!("{} proposes {what}", self.agent)
44 }
45
46 pub fn headline(&self, conversation: Option<&str>) -> String {
47 match conversation {
48 Some(conversation) => format!("{} in {conversation}", self.title()),
49 None => self.title(),
50 }
51 }
52
53 pub fn detail(&self) -> String {
54 match &self.kind {
55 PendingKind::Reply { text } => single_line(text),
56 PendingKind::Reaction {
57 glyph,
58 excerpt: Some(excerpt),
59 ..
60 } => format!("{glyph} to: {excerpt}"),
61 PendingKind::Reaction { glyph, .. } => glyph.clone(),
62 }
63 }
64
65 pub fn jump_message_id(&self) -> &str {
66 match &self.kind {
67 PendingKind::Reply { .. } => "",
68 PendingKind::Reaction { message_id, .. } => message_id,
69 }
70 }
71}
72
73fn single_line(text: &str) -> String {
74 text.split_whitespace().collect::<Vec<_>>().join(" ")
75}
76
77pub fn collect(
78 proposals: &HashMap<String, ProposalEntry>,
79 reactions: &HashMap<(String, String), ReactionProposal>,
80 excerpts: &HashMap<String, String>,
81 seen: &HashSet<String>,
82) -> Vec<PendingProposal> {
83 let replies = proposals
84 .values()
85 .filter(|entry| {
86 !entry.proposal.direct && !matches!(entry.status, ProposalStatus::Stale { .. })
87 })
88 .map(|entry| PendingProposal {
89 id: entry.proposal.id.clone(),
90 conversation_id: entry.proposal.conversation_id.clone(),
91 agent: agent_label(entry.proposal.agent.as_deref()),
92 kind: PendingKind::Reply {
93 text: entry.proposal.text.clone(),
94 },
95 created_at: entry.proposal.created_at,
96 seen: seen.contains(&entry.proposal.id),
97 });
98 let reacts = reactions.values().filter(|reaction| !reaction.direct).map(|reaction| PendingProposal {
99 id: reaction.id.clone(),
100 conversation_id: reaction.conversation_id.clone(),
101 agent: agent_label(reaction.agent.as_deref()),
102 kind: PendingKind::Reaction {
103 glyph: reaction_glyph(&reaction.emoji),
104 message_id: reaction.message_id.clone(),
105 excerpt: excerpts.get(&reaction.id).cloned(),
106 },
107 created_at: reaction.created_at,
108 seen: seen.contains(&reaction.id),
109 });
110 let mut pending: Vec<PendingProposal> = replies.chain(reacts).collect();
111 pending.sort_by(|left, right| {
112 right
113 .created_at
114 .cmp(&left.created_at)
115 .then_with(|| left.id.cmp(&right.id))
116 });
117 pending
118}
119
120pub fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
121 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
122 return Some(chat_title(chat));
123 }
124 sidebar.teams.iter().find_map(|team| {
125 team.channels
126 .iter()
127 .find(|channel| channel.id == conversation_id)
128 .map(|channel| format!("{} > {}", team.team.name, channel.name))
129 })
130}
131
132pub fn reacted_excerpt(store: &Store, conversation_id: &str, message_id: &str) -> Option<String> {
133 let records = store
134 .messages_by_id(conversation_id, &[message_id.to_owned()])
135 .ok()?;
136 let record = records.get(message_id)?;
137 let text = single_line(&preview_label(&preview_of(record)));
138 Some(text.chars().take(EXCERPT_CHARACTERS).collect())
139}
140
141pub fn decode_seen(saved: Option<String>) -> HashSet<String> {
142 saved
143 .unwrap_or_default()
144 .lines()
145 .filter(|line| !line.is_empty())
146 .map(str::to_owned)
147 .collect()
148}
149
150pub fn encode_seen(seen: &HashSet<String>) -> String {
151 let mut ids: Vec<&str> = seen.iter().map(String::as_str).collect();
152 ids.sort_unstable();
153 ids.join("\n")
154}
155
156#[cfg(test)]
157mod tests {
158 use std::collections::{HashMap, HashSet};
159 use std::sync::Arc;
160
161 use chrono::{Local, TimeZone, Utc};
162 use mcp::{Proposal, ReactionProposal};
163
164 use super::*;
165
166 fn reply(
167 conversation_id: &str,
168 id: &str,
169 minute: u32,
170 status: ProposalStatus,
171 ) -> ProposalEntry {
172 ProposalEntry {
173 proposal: Proposal {
174 id: id.into(),
175 conversation_id: conversation_id.into(),
176 reply_to_message_id: None,
177 text: "Looks\n good to me".into(),
178 mentions: Vec::new(),
179 images: Vec::new(),
180 free_writing_ask: None,
181 agent: Some("claude".into()),
182 session_id: None,
183 created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
184 direct: false,
185 },
186 body: Arc::new(Vec::new()),
187 mention_labels: Vec::new(),
188 images: Vec::new(),
189 status,
190 }
191 }
192
193 fn reaction(id: &str, minute: u32) -> ReactionProposal {
194 ReactionProposal {
195 id: id.into(),
196 conversation_id: "chat-b".into(),
197 message_id: "m7".into(),
198 emoji: "like".into(),
199 agent: Some("copilot".into()),
200 session_id: None,
201 created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
202 direct: false,
203 }
204 }
205
206 #[test]
207 fn collect_lists_pending_replies_and_reactions_newest_first() {
208 let proposals = HashMap::from([
209 (
210 "chat-a".to_owned(),
211 reply("chat-a", "p1", 5, ProposalStatus::Pending),
212 ),
213 (
214 "chat-c".to_owned(),
215 reply(
216 "chat-c",
217 "p2",
218 9,
219 ProposalStatus::Stale {
220 answered_at: Local::now(),
221 },
222 ),
223 ),
224 ]);
225 let reactions =
226 HashMap::from([(("chat-b".to_owned(), "m7".to_owned()), reaction("r1", 7))]);
227 let excerpts = HashMap::from([("r1".to_owned(), "Ship it?".to_owned())]);
228 let seen = HashSet::from(["p1".to_owned()]);
229 let pending = collect(&proposals, &reactions, &excerpts, &seen);
230 let ids: Vec<&str> = pending.iter().map(|item| item.id.as_str()).collect();
231 assert_eq!(ids, ["r1", "p1"]);
232 assert!(!pending[0].seen);
233 assert!(pending[1].seen);
234 assert_eq!(pending[0].title(), "Copilot proposes a reaction");
235 assert_eq!(pending[0].jump_message_id(), "m7");
236 assert_eq!(pending[1].jump_message_id(), "");
237 assert_eq!(
238 pending[1].headline(Some("Release planning")),
239 "Claude proposes a reply in Release planning"
240 );
241 assert_eq!(pending[1].detail(), "Looks good to me");
242 assert!(pending[0].detail().ends_with(" to: Ship it?"));
243 }
244
245 #[test]
246 fn seen_ids_round_trip() {
247 let seen = HashSet::from(["b".to_owned(), "a".to_owned()]);
248 assert_eq!(encode_seen(&seen), "a\nb");
249 assert_eq!(decode_seen(Some(encode_seen(&seen))), seen);
250 assert!(decode_seen(None).is_empty());
251 }
252}