| 1 | use std::cell::RefCell; |
| 2 | use std::collections::HashSet; |
| 3 | use std::rc::Rc; |
| 4 | |
| 5 | use chrono::Utc; |
| 6 | use gpui_kit::*; |
| 7 | use mcp::{Outcome, ReactionOutcome, ReactionProposal}; |
| 8 | use store::{MessageRecord, OutboxTarget}; |
| 9 | |
| 10 | use crate::agent_api::{self, ProposalEntry}; |
| 11 | use crate::app_state::AppState; |
| 12 | use crate::notice::short_error; |
| 13 | use crate::outbox::{deliver, new_outbox_id, outbox_record}; |
| 14 | use crate::rows::{api_reaction, reaction_glyph, reply_excerpt}; |
| 15 | use crate::runtime; |
| 16 | use crate::views::composer::ReplyPreview; |
| 17 | use crate::views::proposal_card::{needs_upload, outgoing_for}; |
| 18 | |
| 19 | pub fn install(state: Entity<AppState>, cx: &mut App) { |
| 20 | let Some(api) = agent_api::handle(cx) else { |
| 21 | return; |
| 22 | }; |
| 23 | let reacting: Rc<RefCell<HashSet<String>>> = Rc::default(); |
| 24 | cx.observe(&api, move |_, cx| { |
| 25 | for entry in agent_api::direct_messages(cx) { |
| 26 | send_message(&state, entry, cx); |
| 27 | } |
| 28 | for reaction in agent_api::direct_reactions(cx) { |
| 29 | if reacting.borrow_mut().insert(reaction.id.clone()) { |
| 30 | add_reaction(&state, reaction, reacting.clone(), cx); |
| 31 | } |
| 32 | } |
| 33 | }) |
| 34 | .detach(); |
| 35 | } |
| 36 | |
| 37 | fn live_engine( |
| 38 | state: &Entity<AppState>, |
| 39 | cx: &App, |
| 40 | ) -> Option<std::sync::Arc<crate::backend::Engine>> { |
| 41 | let state = state.read(cx); |
| 42 | state |
| 43 | .engine |
| 44 | .clone() |
| 45 | .filter(|_| !state.mode.read_only && !state.mode.demo) |
| 46 | } |
| 47 | |
| 48 | fn message( |
| 49 | state: &Entity<AppState>, |
| 50 | conversation_id: &str, |
| 51 | message_id: &str, |
| 52 | cx: &App, |
| 53 | ) -> Option<MessageRecord> { |
| 54 | state |
| 55 | .read(cx) |
| 56 | .store |
| 57 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 58 | .ok() |
| 59 | .and_then(|mut found| found.remove(message_id)) |
| 60 | .filter(|record| !record.deleted) |
| 61 | } |
| 62 | |
| 63 | #[derive(Debug, PartialEq)] |
| 64 | struct Route { |
| 65 | target: OutboxTarget, |
| 66 | thread_root_id: Option<String>, |
| 67 | quoted: Option<MessageRecord>, |
| 68 | } |
| 69 | |
| 70 | fn route(in_channel: bool, target_message: Option<MessageRecord>) -> Route { |
| 71 | match (in_channel, target_message) { |
| 72 | (true, Some(record)) => Route { |
| 73 | target: OutboxTarget::Thread, |
| 74 | thread_root_id: Some( |
| 75 | record |
| 76 | .reply_to_id |
| 77 | .clone() |
| 78 | .unwrap_or_else(|| record.message_id.clone()), |
| 79 | ), |
| 80 | quoted: record.reply_to_id.is_some().then_some(record), |
| 81 | }, |
| 82 | (true, None) => Route { |
| 83 | target: OutboxTarget::Post, |
| 84 | thread_root_id: None, |
| 85 | quoted: None, |
| 86 | }, |
| 87 | (false, quoted) => Route { |
| 88 | target: OutboxTarget::Flat, |
| 89 | thread_root_id: None, |
| 90 | quoted, |
| 91 | }, |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | fn send_message(state: &Entity<AppState>, entry: ProposalEntry, cx: &mut App) { |
| 96 | let conversation_id = entry.proposal.conversation_id.clone(); |
| 97 | let Some(engine) = live_engine(state, cx).filter(|_| !needs_upload(&entry)) else { |
| 98 | agent_api::hold_for_review(&conversation_id, cx); |
| 99 | return; |
| 100 | }; |
| 101 | let in_channel = state |
| 102 | .read(cx) |
| 103 | .store |
| 104 | .channel(&conversation_id) |
| 105 | .ok() |
| 106 | .flatten() |
| 107 | .is_some(); |
| 108 | let target_message = entry |
| 109 | .proposal |
| 110 | .reply_to_message_id |
| 111 | .as_deref() |
| 112 | .and_then(|message_id| message(state, &conversation_id, message_id, cx)); |
| 113 | let Route { |
| 114 | target, |
| 115 | thread_root_id, |
| 116 | quoted, |
| 117 | } = route(in_channel, target_message); |
| 118 | let quote = quoted.map(|record| ReplyPreview { |
| 119 | message_id: record.message_id.clone(), |
| 120 | author: record |
| 121 | .sender_name |
| 122 | .clone() |
| 123 | .unwrap_or_else(|| "Unknown".to_owned()), |
| 124 | excerpt: reply_excerpt(&record), |
| 125 | }); |
| 126 | let outgoing = outgoing_for(&entry, quote); |
| 127 | let outbox_id = new_outbox_id(); |
| 128 | let store = state.read(cx).store.clone(); |
| 129 | if let Some(record) = outbox_record( |
| 130 | &outbox_id, |
| 131 | &conversation_id, |
| 132 | target, |
| 133 | thread_root_id.as_deref(), |
| 134 | &outgoing, |
| 135 | Utc::now(), |
| 136 | ) { |
| 137 | store.put_outbox(&record).ok(); |
| 138 | } |
| 139 | agent_api::resolve_proposal(&conversation_id, Outcome::Sent, cx); |
| 140 | state.update(cx, |state, cx| { |
| 141 | state.outbox_changed(conversation_id.clone(), cx) |
| 142 | }); |
| 143 | let receiver = runtime::spawn({ |
| 144 | let conversation_id = conversation_id.clone(); |
| 145 | async move { |
| 146 | deliver( |
| 147 | &engine, |
| 148 | &conversation_id, |
| 149 | target, |
| 150 | thread_root_id.as_deref(), |
| 151 | &outgoing, |
| 152 | ) |
| 153 | .await |
| 154 | } |
| 155 | }); |
| 156 | let state = state.downgrade(); |
| 157 | cx.spawn(async move |cx| { |
| 158 | let failure = match receiver.await { |
| 159 | Ok(Ok(_)) => None, |
| 160 | Ok(Err(error)) => Some(short_error(&error)), |
| 161 | Err(error) => Some(short_error(&error)), |
| 162 | }; |
| 163 | match failure { |
| 164 | None => store.delete_outbox(&outbox_id).ok(), |
| 165 | Some(error) => store.mark_outbox_failed(&outbox_id, &error).ok(), |
| 166 | }; |
| 167 | state |
| 168 | .update(cx, |state, cx| state.outbox_changed(conversation_id, cx)) |
| 169 | .ok(); |
| 170 | }) |
| 171 | .detach(); |
| 172 | } |
| 173 | |
| 174 | fn add_reaction( |
| 175 | state: &Entity<AppState>, |
| 176 | reaction: ReactionProposal, |
| 177 | reacting: Rc<RefCell<HashSet<String>>>, |
| 178 | cx: &mut App, |
| 179 | ) { |
| 180 | let (conversation_id, message_id) = ( |
| 181 | reaction.conversation_id.clone(), |
| 182 | reaction.message_id.clone(), |
| 183 | ); |
| 184 | let Some(engine) = live_engine(state, cx) else { |
| 185 | agent_api::hold_reaction_for_review(&conversation_id, &message_id, cx); |
| 186 | reacting.borrow_mut().remove(&reaction.id); |
| 187 | return; |
| 188 | }; |
| 189 | if message(state, &conversation_id, &message_id, cx).is_none() { |
| 190 | agent_api::resolve_reaction_proposal( |
| 191 | &conversation_id, |
| 192 | &message_id, |
| 193 | &reaction.id, |
| 194 | ReactionOutcome::Stale, |
| 195 | cx, |
| 196 | ); |
| 197 | reacting.borrow_mut().remove(&reaction.id); |
| 198 | return; |
| 199 | } |
| 200 | let reaction_type = api_reaction(&reaction_glyph(&reaction.emoji)); |
| 201 | let receiver = runtime::spawn({ |
| 202 | let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone()); |
| 203 | async move { |
| 204 | engine |
| 205 | .set_reaction(&conversation_id, &message_id, &reaction_type) |
| 206 | .await |
| 207 | } |
| 208 | }); |
| 209 | cx.spawn(async move |cx| { |
| 210 | let added = matches!(receiver.await, Ok(Ok(()))); |
| 211 | cx.update(|cx| { |
| 212 | if added { |
| 213 | agent_api::resolve_reaction_proposal( |
| 214 | &conversation_id, |
| 215 | &message_id, |
| 216 | &reaction.id, |
| 217 | ReactionOutcome::Accepted, |
| 218 | cx, |
| 219 | ); |
| 220 | } else { |
| 221 | agent_api::hold_reaction_for_review(&conversation_id, &message_id, cx); |
| 222 | } |
| 223 | reacting.borrow_mut().remove(&reaction.id); |
| 224 | }); |
| 225 | }) |
| 226 | .detach(); |
| 227 | } |
| 228 | |
| 229 | #[cfg(test)] |
| 230 | mod tests { |
| 231 | use store::{MessageRecord, OutboxTarget}; |
| 232 | |
| 233 | use super::{Route, route}; |
| 234 | |
| 235 | fn record(message_id: &str, reply_to_id: Option<&str>) -> MessageRecord { |
| 236 | MessageRecord { |
| 237 | message_id: message_id.to_owned(), |
| 238 | reply_to_id: reply_to_id.map(str::to_owned), |
| 239 | ..MessageRecord::default() |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | #[test] |
| 244 | fn chats_quote_and_channels_answer_in_the_thread() { |
| 245 | let chat = route(false, Some(record("m1", None))); |
| 246 | assert_eq!( |
| 247 | (chat.target, chat.quoted.map(|quoted| quoted.message_id)), |
| 248 | (OutboxTarget::Flat, Some("m1".to_owned())) |
| 249 | ); |
| 250 | assert_eq!( |
| 251 | route(true, None), |
| 252 | Route { |
| 253 | target: OutboxTarget::Post, |
| 254 | thread_root_id: None, |
| 255 | quoted: None |
| 256 | } |
| 257 | ); |
| 258 | let to_post = route(true, Some(record("root", None))); |
| 259 | assert_eq!( |
| 260 | ( |
| 261 | to_post.target, |
| 262 | to_post.thread_root_id.as_deref(), |
| 263 | to_post.quoted |
| 264 | ), |
| 265 | (OutboxTarget::Thread, Some("root"), None) |
| 266 | ); |
| 267 | let to_reply = route(true, Some(record("r2", Some("root")))); |
| 268 | assert_eq!(to_reply.thread_root_id.as_deref(), Some("root")); |
| 269 | assert_eq!( |
| 270 | to_reply.quoted.map(|quoted| quoted.message_id).as_deref(), |
| 271 | Some("r2") |
| 272 | ); |
| 273 | } |
| 274 | } |