BlueGit

ict rusty-teams

Files

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

pending.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
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
99 .values()
100 .filter(|reaction| !reaction.direct)
101 .map(|reaction| PendingProposal {
102 id: reaction.id.clone(),
103 conversation_id: reaction.conversation_id.clone(),
104 agent: agent_label(reaction.agent.as_deref()),
105 kind: PendingKind::Reaction {
106 glyph: reaction_glyph(&reaction.emoji),
107 message_id: reaction.message_id.clone(),
108 excerpt: excerpts.get(&reaction.id).cloned(),
109 },
110 created_at: reaction.created_at,
111 seen: seen.contains(&reaction.id),
112 });
113 let mut pending: Vec<PendingProposal> = replies.chain(reacts).collect();
114 pending.sort_by(|left, right| {
115 right
116 .created_at
117 .cmp(&left.created_at)
118 .then_with(|| left.id.cmp(&right.id))
119 });
120 pending
121}
122
123pub fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
124 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
125 return Some(chat_title(chat));
126 }
127 sidebar.teams.iter().find_map(|team| {
128 team.channels
129 .iter()
130 .find(|channel| channel.id == conversation_id)
131 .map(|channel| format!("{} > {}", team.team.name, channel.name))
132 })
133}
134
135pub fn reacted_excerpt(store: &Store, conversation_id: &str, message_id: &str) -> Option<String> {
136 let records = store
137 .messages_by_id(conversation_id, &[message_id.to_owned()])
138 .ok()?;
139 let record = records.get(message_id)?;
140 let text = single_line(&preview_label(&preview_of(record)));
141 Some(text.chars().take(EXCERPT_CHARACTERS).collect())
142}
143
144pub fn decode_seen(saved: Option<String>) -> HashSet<String> {
145 saved
146 .unwrap_or_default()
147 .lines()
148 .filter(|line| !line.is_empty())
149 .map(str::to_owned)
150 .collect()
151}
152
153pub fn encode_seen(seen: &HashSet<String>) -> String {
154 let mut ids: Vec<&str> = seen.iter().map(String::as_str).collect();
155 ids.sort_unstable();
156 ids.join("\n")
157}
158
159#[cfg(test)]
160mod tests {
161 use std::collections::{HashMap, HashSet};
162 use std::sync::Arc;
163
164 use chrono::{Local, TimeZone, Utc};
165 use mcp::{Proposal, ReactionProposal};
166
167 use super::*;
168
169 fn reply(
170 conversation_id: &str,
171 id: &str,
172 minute: u32,
173 status: ProposalStatus,
174 ) -> ProposalEntry {
175 ProposalEntry {
176 proposal: Proposal {
177 id: id.into(),
178 conversation_id: conversation_id.into(),
179 reply_to_message_id: None,
180 text: "Looks\n good to me".into(),
181 mentions: Vec::new(),
182 images: Vec::new(),
183 free_writing_ask: None,
184 agent: Some("claude".into()),
185 session_id: None,
186 created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
187 direct: false,
188 },
189 body: Arc::new(Vec::new()),
190 mention_labels: Vec::new(),
191 images: Vec::new(),
192 status,
193 }
194 }
195
196 fn reaction(id: &str, minute: u32) -> ReactionProposal {
197 ReactionProposal {
198 id: id.into(),
199 conversation_id: "chat-b".into(),
200 message_id: "m7".into(),
201 emoji: "like".into(),
202 agent: Some("copilot".into()),
203 session_id: None,
204 created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
205 direct: false,
206 }
207 }
208
209 #[test]
210 fn collect_lists_pending_replies_and_reactions_newest_first() {
211 let proposals = HashMap::from([
212 (
213 "chat-a".to_owned(),
214 reply("chat-a", "p1", 5, ProposalStatus::Pending),
215 ),
216 (
217 "chat-c".to_owned(),
218 reply(
219 "chat-c",
220 "p2",
221 9,
222 ProposalStatus::Stale {
223 answered_at: Local::now(),
224 },
225 ),
226 ),
227 ]);
228 let reactions =
229 HashMap::from([(("chat-b".to_owned(), "m7".to_owned()), reaction("r1", 7))]);
230 let excerpts = HashMap::from([("r1".to_owned(), "Ship it?".to_owned())]);
231 let seen = HashSet::from(["p1".to_owned()]);
232 let pending = collect(&proposals, &reactions, &excerpts, &seen);
233 let ids: Vec<&str> = pending.iter().map(|item| item.id.as_str()).collect();
234 assert_eq!(ids, ["r1", "p1"]);
235 assert!(!pending[0].seen);
236 assert!(pending[1].seen);
237 assert_eq!(pending[0].title(), "Copilot proposes a reaction");
238 assert_eq!(pending[0].jump_message_id(), "m7");
239 assert_eq!(pending[1].jump_message_id(), "");
240 assert_eq!(
241 pending[1].headline(Some("Release planning")),
242 "Claude proposes a reply in Release planning"
243 );
244 assert_eq!(pending[1].detail(), "Looks good to me");
245 assert!(pending[0].detail().ends_with(" to: Ship it?"));
246 }
247
248 #[test]
249 fn seen_ids_round_trip() {
250 let seen = HashSet::from(["b".to_owned(), "a".to_owned()]);
251 assert_eq!(encode_seen(&seen), "a\nb");
252 assert_eq!(decode_seen(Some(encode_seen(&seen))), seen);
253 assert!(decode_seen(None).is_empty());
254 }
255}