BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / agents / message_context.rs

message_context.rs

message_context.rs 7.6 KiB Download Raw
1use agents::{AgentAction, MessageContext, ThreadMessage, build_prompt};
2use chrono::Local;
3use store::MessageRecord;
4
5use crate::app_state::{AppState, Selection, selection_title};
6use crate::notify::selection_for;
7use crate::people::local_names;
8use crate::rows::message_text;
9
10const THREAD_LIMIT: usize = 20;
11const UNKNOWN_SENDER: &str = "Unknown";
12const SESSION_PLACEHOLDER: &str = "(session id)";
13const TIME_FORMAT: &str = "%Y-%m-%d %H:%M";
14
15fn earlier_records(
16 state: &AppState,
17 selection: Option<&Selection>,
18 record: &MessageRecord,
19) -> Vec<MessageRecord> {
20 let conversation_id = record.conversation_id.as_str();
21 let mut earlier = match selection {
22 Some(Selection::Channel(_)) => {
23 let root_id = record
24 .reply_to_id
25 .clone()
26 .unwrap_or_else(|| record.message_id.clone());
27 let mut thread = state
28 .store
29 .thread_messages(conversation_id, &root_id)
30 .unwrap_or_default();
31 thread.retain(|entry| entry.created_at < record.created_at);
32 thread
33 }
34 _ => state
35 .store
36 .messages(conversation_id, Some(record.created_at), THREAD_LIMIT)
37 .unwrap_or_default(),
38 };
39 earlier.retain(|entry| !entry.deleted);
40 let skipped = earlier.len().saturating_sub(THREAD_LIMIT);
41 earlier.split_off(skipped)
42}
43
44pub fn build(state: &AppState, conversation_id: &str, message_id: &str) -> Option<MessageContext> {
45 let record = state
46 .store
47 .messages_by_id(conversation_id, &[message_id.to_owned()])
48 .ok()?
49 .remove(message_id)
50 .filter(|record| !record.deleted)?;
51 let names = local_names(state);
52 let sender_of = |entry: &MessageRecord| {
53 entry
54 .sender_name
55 .clone()
56 .filter(|name| !name.trim().is_empty())
57 .or_else(|| {
58 entry
59 .sender_id
60 .as_ref()
61 .and_then(|user_id| names.get(user_id).cloned())
62 })
63 .unwrap_or_else(|| UNKNOWN_SENDER.to_owned())
64 };
65 let selection = selection_for(&state.sidebar, conversation_id);
66 let chat = selection
67 .as_ref()
68 .map(|selection| selection_title(&state.sidebar, selection))
69 .unwrap_or_else(|| "Chat".to_owned());
70 let thread = earlier_records(state, selection.as_ref(), &record)
71 .iter()
72 .map(|entry| ThreadMessage {
73 sender: sender_of(entry),
74 text: message_text(entry),
75 time: entry
76 .created_at
77 .with_timezone(&Local)
78 .format(TIME_FORMAT)
79 .to_string(),
80 })
81 .collect();
82 Some(MessageContext {
83 sender: sender_of(&record),
84 chat,
85 conversation_id: conversation_id.to_owned(),
86 message_id: message_id.to_owned(),
87 message: message_text(&record),
88 thread,
89 })
90}
91
92pub fn preview_prompt(
93 state: &AppState,
94 action: &AgentAction,
95 conversation_id: &str,
96 message_id: &str,
97 extra: &str,
98) -> Option<String> {
99 let context = build(state, conversation_id, message_id)?;
100 Some(build_prompt(
101 action,
102 &context,
103 extra,
104 SESSION_PLACEHOLDER,
105 &action.agent_id,
106 ))
107}
108
109#[cfg(test)]
110mod tests {
111 use std::sync::Arc;
112
113 use chrono::{TimeZone, Utc};
114 use store::{ChatRecord, Store};
115
116 use super::*;
117 use crate::app_state::Mode;
118
119 fn message(id: &str, reply_to: Option<&str>, minute: u32, sender: &str) -> MessageRecord {
120 MessageRecord {
121 conversation_id: "19:chat".to_owned(),
122 message_id: id.to_owned(),
123 reply_to_id: reply_to.map(str::to_owned),
124 sender_name: Some(sender.to_owned()),
125 created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, minute, 0).unwrap(),
126 body_html: format!("<p>text {id}</p>"),
127 attachments_json: "[]".to_owned(),
128 reactions_json: "[]".to_owned(),
129 mentions_json: "[]".to_owned(),
130 links_json: "[]".to_owned(),
131 ..MessageRecord::default()
132 }
133 }
134
135 fn state_with(records: &[MessageRecord]) -> AppState {
136 let store = Arc::new(Store::open_in_memory().unwrap());
137 store.upsert_messages(records).unwrap();
138 let mut state = AppState::new(store, Mode::default());
139 state.sidebar.chats.push(ChatRecord {
140 id: "19:chat".to_owned(),
141 kind: "chat".to_owned(),
142 title: "Ops".to_owned(),
143 member_summary: String::new(),
144 last_message_at: None,
145 last_read_at: None,
146 unread: false,
147 muted: false,
148 members: Vec::new(),
149 last_message_preview: None,
150 last_message_sender_id: None,
151 last_message_sender_name: None,
152 last_message_deleted: false,
153 last_event_system: false,
154 });
155 state
156 }
157
158 #[test]
159 fn chat_context_takes_up_to_twenty_earlier_messages_oldest_first() {
160 let records: Vec<MessageRecord> = (0..30)
161 .map(|minute| message(&format!("m{minute}"), None, minute, "Ada"))
162 .collect();
163 let state = state_with(&records);
164 let context = build(&state, "19:chat", "m25").unwrap();
165 assert_eq!(context.chat, "Ops");
166 assert_eq!(context.sender, "Ada");
167 assert_eq!(context.message, "text m25");
168 assert_eq!(context.thread.len(), 20);
169 assert_eq!(context.thread[0].text, "text m5");
170 assert_eq!(context.thread[19].text, "text m24");
171 }
172
173 #[test]
174 fn deleted_and_missing_messages_give_no_context() {
175 let mut deleted = message("m1", None, 1, "Ada");
176 deleted.deleted = true;
177 let state = state_with(&[deleted]);
178 assert!(build(&state, "19:chat", "m1").is_none());
179 assert!(build(&state, "19:chat", "nope").is_none());
180 }
181
182 #[test]
183 fn channel_context_follows_the_thread_root() {
184 let records = [
185 message("root", None, 1, "Ada"),
186 message("other", None, 2, "Bo"),
187 message("reply-1", Some("root"), 3, "Cy"),
188 message("reply-2", Some("root"), 4, "Di"),
189 ];
190 let mut state = state_with(&records);
191 state.sidebar.chats.clear();
192 state.sidebar.teams.push(store::SidebarTeam {
193 team: store::TeamRecord {
194 id: "team".to_owned(),
195 name: "Platform".to_owned(),
196 },
197 channels: vec![store::ChannelRecord {
198 id: "19:chat".to_owned(),
199 team_id: "team".to_owned(),
200 name: "Releases".to_owned(),
201 membership_type: None,
202 last_message_at: None,
203 unread: false,
204 }],
205 hidden: false,
206 hidden_channel_ids: Vec::new(),
207 notifications: Default::default(),
208 });
209 let context = build(&state, "19:chat", "reply-2").unwrap();
210 let texts: Vec<&str> = context
211 .thread
212 .iter()
213 .map(|entry| entry.text.as_str())
214 .collect();
215 assert_eq!(texts, ["text root", "text reply-1"]);
216 }
217
218 #[test]
219 fn preview_renders_the_template_with_a_session_placeholder() {
220 let state = state_with(&[message("m1", None, 1, "Ada")]);
221 let action = AgentAction::answer_this("claude");
222 let prompt = preview_prompt(&state, &action, "19:chat", "m1", "").unwrap();
223 assert!(prompt.starts_with("Ada asked me in the Teams chat \"Ops\""));
224 assert!(prompt.contains("session_id \"(session id)\""));
225 }
226}