| 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 | /// Newest non-deleted messages of a chat, oldest-first, capped at [`THREAD_LIMIT`]. |
| 122 | pub fn recent_thread(state: &AppState, conversation_id: &str) -> Vec<ThreadMessage> { |
| 123 | let names = local_names(state); |
| 124 | let sender_of = |entry: &MessageRecord| { |
| 125 | entry |
| 126 | .sender_name |
| 127 | .clone() |
| 128 | .filter(|name| !name.trim().is_empty()) |
| 129 | .or_else(|| { |
| 130 | entry |
| 131 | .sender_id |
| 132 | .as_ref() |
| 133 | .and_then(|user_id| names.get(user_id).cloned()) |
| 134 | }) |
| 135 | .unwrap_or_else(|| UNKNOWN_SENDER.to_owned()) |
| 136 | }; |
| 137 | let mut records = state |
| 138 | .store |
| 139 | .messages(conversation_id, None, THREAD_LIMIT) |
| 140 | .unwrap_or_default(); |
| 141 | records.retain(|entry| !entry.deleted); |
| 142 | let skipped = records.len().saturating_sub(THREAD_LIMIT); |
| 143 | records |
| 144 | .into_iter() |
| 145 | .skip(skipped) |
| 146 | .map(|entry| ThreadMessage { |
| 147 | sender: sender_of(&entry), |
| 148 | text: message_text(&entry), |
| 149 | time: entry |
| 150 | .created_at |
| 151 | .with_timezone(&Local) |
| 152 | .format(TIME_FORMAT) |
| 153 | .to_string(), |
| 154 | }) |
| 155 | .collect() |
| 156 | } |
| 157 | |
| 158 | pub fn chat_title(state: &AppState, conversation_id: &str) -> String { |
| 159 | selection_for(&state.sidebar, conversation_id) |
| 160 | .as_ref() |
| 161 | .map(|selection| selection_title(&state.sidebar, selection)) |
| 162 | .unwrap_or_else(|| "Chat".to_owned()) |
| 163 | } |
| 164 | |
| 165 | /// Plain-text ask for a local write-with profile: chat title, recent thread, question. |
| 166 | pub fn ask_prompt(chat: &str, thread: &[ThreadMessage], question: &str) -> String { |
| 167 | let thread_block = if thread.is_empty() { |
| 168 | "(no messages yet)".to_owned() |
| 169 | } else { |
| 170 | thread |
| 171 | .iter() |
| 172 | .map(|entry| format!("{} ({}): {}", entry.sender, entry.time, entry.text)) |
| 173 | .collect::<Vec<_>>() |
| 174 | .join("\n") |
| 175 | }; |
| 176 | format!("Chat \"{chat}\"\n\n{thread_block}\n\nQuestion: {question}") |
| 177 | } |
| 178 | |
| 179 | #[cfg(test)] |
| 180 | mod tests { |
| 181 | use std::sync::Arc; |
| 182 | |
| 183 | use chrono::{TimeZone, Utc}; |
| 184 | use store::{ChatRecord, Store}; |
| 185 | |
| 186 | use super::*; |
| 187 | use crate::app_state::Mode; |
| 188 | |
| 189 | fn message(id: &str, reply_to: Option<&str>, minute: u32, sender: &str) -> MessageRecord { |
| 190 | MessageRecord { |
| 191 | conversation_id: "19:chat".to_owned(), |
| 192 | message_id: id.to_owned(), |
| 193 | reply_to_id: reply_to.map(str::to_owned), |
| 194 | sender_name: Some(sender.to_owned()), |
| 195 | created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, minute, 0).unwrap(), |
| 196 | body_html: format!("<p>text {id}</p>"), |
| 197 | attachments_json: "[]".to_owned(), |
| 198 | reactions_json: "[]".to_owned(), |
| 199 | mentions_json: "[]".to_owned(), |
| 200 | links_json: "[]".to_owned(), |
| 201 | ..MessageRecord::default() |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | fn state_with(records: &[MessageRecord]) -> AppState { |
| 206 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 207 | store.upsert_messages(records).unwrap(); |
| 208 | let mut state = AppState::new(store, Mode::default()); |
| 209 | state.sidebar.chats.push(ChatRecord { |
| 210 | id: "19:chat".to_owned(), |
| 211 | kind: "chat".to_owned(), |
| 212 | title: "Ops".to_owned(), |
| 213 | member_summary: String::new(), |
| 214 | last_message_at: None, |
| 215 | preview_at: None, |
| 216 | last_read_at: None, |
| 217 | unread: false, |
| 218 | muted: false, |
| 219 | members: Vec::new(), |
| 220 | last_message_preview: None, |
| 221 | last_message_sender_id: None, |
| 222 | last_message_sender_name: None, |
| 223 | last_message_deleted: false, |
| 224 | last_event_system: false, |
| 225 | keeps_stored_preview: false, |
| 226 | without_last_message: false, |
| 227 | }); |
| 228 | state |
| 229 | } |
| 230 | |
| 231 | #[test] |
| 232 | fn chat_context_takes_up_to_twenty_earlier_messages_oldest_first() { |
| 233 | let records: Vec<MessageRecord> = (0..30) |
| 234 | .map(|minute| message(&format!("m{minute}"), None, minute, "Ada")) |
| 235 | .collect(); |
| 236 | let state = state_with(&records); |
| 237 | let context = build(&state, "19:chat", "m25").unwrap(); |
| 238 | assert_eq!(context.chat, "Ops"); |
| 239 | assert_eq!(context.sender, "Ada"); |
| 240 | assert_eq!(context.message, "text m25"); |
| 241 | assert_eq!(context.thread.len(), 20); |
| 242 | assert_eq!(context.thread[0].text, "text m5"); |
| 243 | assert_eq!(context.thread[19].text, "text m24"); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn deleted_and_missing_messages_give_no_context() { |
| 248 | let mut deleted = message("m1", None, 1, "Ada"); |
| 249 | deleted.deleted = true; |
| 250 | let state = state_with(&[deleted]); |
| 251 | assert!(build(&state, "19:chat", "m1").is_none()); |
| 252 | assert!(build(&state, "19:chat", "nope").is_none()); |
| 253 | } |
| 254 | |
| 255 | #[test] |
| 256 | fn channel_context_follows_the_thread_root() { |
| 257 | let records = [ |
| 258 | message("root", None, 1, "Ada"), |
| 259 | message("other", None, 2, "Bo"), |
| 260 | message("reply-1", Some("root"), 3, "Cy"), |
| 261 | message("reply-2", Some("root"), 4, "Di"), |
| 262 | ]; |
| 263 | let mut state = state_with(&records); |
| 264 | state.sidebar.chats.clear(); |
| 265 | state.sidebar.teams.push(store::SidebarTeam { |
| 266 | rights: Default::default(), |
| 267 | team: store::TeamRecord { |
| 268 | id: "team".to_owned(), |
| 269 | name: "Platform".to_owned(), |
| 270 | }, |
| 271 | channels: vec![store::ChannelRecord { |
| 272 | id: "19:chat".to_owned(), |
| 273 | team_id: "team".to_owned(), |
| 274 | name: "Releases".to_owned(), |
| 275 | membership_type: None, |
| 276 | last_message_at: None, |
| 277 | unread: false, |
| 278 | }], |
| 279 | hidden: false, |
| 280 | hidden_channel_ids: Vec::new(), |
| 281 | notifications: Default::default(), |
| 282 | mentions: Default::default(), |
| 283 | }); |
| 284 | let context = build(&state, "19:chat", "reply-2").unwrap(); |
| 285 | let texts: Vec<&str> = context |
| 286 | .thread |
| 287 | .iter() |
| 288 | .map(|entry| entry.text.as_str()) |
| 289 | .collect(); |
| 290 | assert_eq!(texts, ["text root", "text reply-1"]); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn preview_renders_the_template_with_a_session_placeholder() { |
| 295 | let state = state_with(&[message("m1", None, 1, "Ada")]); |
| 296 | let action = AgentAction::answer_this("claude"); |
| 297 | let prompt = preview_prompt(&state, &action, "19:chat", "m1", "").unwrap(); |
| 298 | assert!(prompt.starts_with("Ada asked me in the Teams chat \"Ops\"")); |
| 299 | assert!(prompt.contains("session_id \"(session id)\"")); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn recent_thread_keeps_the_newest_twenty_non_deleted() { |
| 304 | let mut records: Vec<MessageRecord> = (0..25) |
| 305 | .map(|minute| message(&format!("m{minute}"), None, minute, "Ada")) |
| 306 | .collect(); |
| 307 | records[0].deleted = true; |
| 308 | let state = state_with(&records); |
| 309 | let thread = recent_thread(&state, "19:chat"); |
| 310 | assert_eq!(thread.len(), 20); |
| 311 | assert_eq!(thread[0].text, "text m5"); |
| 312 | assert_eq!(thread[19].text, "text m24"); |
| 313 | assert_eq!(chat_title(&state, "19:chat"), "Ops"); |
| 314 | let prompt = ask_prompt("Ops", &thread, "Summarize this chat"); |
| 315 | assert!(prompt.contains("Chat \"Ops\"")); |
| 316 | assert!(prompt.contains("text m5")); |
| 317 | assert!(prompt.contains("Question: Summarize this chat")); |
| 318 | } |
| 319 | } |