BlueGit

ict rusty-teams

Files

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

message_context.rs

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