BlueGit

ict rusty-teams

Files

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

message_context.rs

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