| 1 | use agents::{AgentAction, MessageContext, ThreadMessage, build_prompt}; |
| 2 | use chrono::Local; |
| 3 | use store::MessageRecord; |
| 4 | |
| 5 | use crate::app_state::{AppState, Selection, selection_for, selection_title}; |
| 6 | use crate::people::local_names; |
| 7 | use crate::rows::message_text; |
| 8 | |
| 9 | const THREAD_LIMIT: usize = 20; |
| 10 | const UNKNOWN_SENDER: &str = "Unknown"; |
| 11 | const SESSION_PLACEHOLDER: &str = "(session id)"; |
| 12 | const TIME_FORMAT: &str = "%Y-%m-%d %H:%M"; |
| 13 | |
| 14 | fn 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 | |
| 43 | pub 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 | |
| 56 | pub 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 | |
| 104 | pub 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)] |
| 122 | mod 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 | last_read_at: None, |
| 158 | unread: false, |
| 159 | muted: false, |
| 160 | members: Vec::new(), |
| 161 | last_message_preview: None, |
| 162 | last_message_sender_id: None, |
| 163 | last_message_sender_name: None, |
| 164 | last_message_deleted: false, |
| 165 | last_event_system: false, |
| 166 | last_event_call: 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 | } |