| 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(state: &Entity<AppState>, cx: &App) -> Option<std::sync::Arc<crate::backend::Engine>> { |
| 38 | let state = state.read(cx); |
| 39 | state |
| 40 | .engine |
| 41 | .clone() |
| 42 | .filter(|_| !state.mode.read_only && !state.mode.demo) |
| 43 | } |
| 44 | |
| 45 | fn message(state: &Entity<AppState>, conversation_id: &str, message_id: &str, cx: &App) -> Option<MessageRecord> { |
| 46 | state |
| 47 | .read(cx) |
| 48 | .store |
| 49 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 50 | .ok() |
| 51 | .and_then(|mut found| found.remove(message_id)) |
| 52 | .filter(|record| !record.deleted) |
| 53 | } |
| 54 | |
| 55 | #[derive(Debug, PartialEq)] |
| 56 | struct Route { |
| 57 | target: OutboxTarget, |
| 58 | thread_root_id: Option<String>, |
| 59 | quoted: Option<MessageRecord>, |
| 60 | } |
| 61 | |
| 62 | fn route(in_channel: bool, target_message: Option<MessageRecord>) -> Route { |
| 63 | match (in_channel, target_message) { |
| 64 | (true, Some(record)) => Route { |
| 65 | target: OutboxTarget::Thread, |
| 66 | thread_root_id: Some(record.reply_to_id.clone().unwrap_or_else(|| record.message_id.clone())), |
| 67 | quoted: record.reply_to_id.is_some().then_some(record), |
| 68 | }, |
| 69 | (true, None) => Route { target: OutboxTarget::Post, thread_root_id: None, quoted: None }, |
| 70 | (false, quoted) => Route { target: OutboxTarget::Flat, thread_root_id: None, quoted }, |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | fn send_message(state: &Entity<AppState>, entry: ProposalEntry, cx: &mut App) { |
| 75 | let conversation_id = entry.proposal.conversation_id.clone(); |
| 76 | let Some(engine) = live_engine(state, cx).filter(|_| !needs_upload(&entry)) else { |
| 77 | agent_api::hold_for_review(&conversation_id, cx); |
| 78 | return; |
| 79 | }; |
| 80 | let in_channel = state.read(cx).store.channel(&conversation_id).ok().flatten().is_some(); |
| 81 | let target_message = entry |
| 82 | .proposal |
| 83 | .reply_to_message_id |
| 84 | .as_deref() |
| 85 | .and_then(|message_id| message(state, &conversation_id, message_id, cx)); |
| 86 | let Route { target, thread_root_id, quoted } = route(in_channel, target_message); |
| 87 | let quote = quoted.map(|record| ReplyPreview { |
| 88 | message_id: record.message_id.clone(), |
| 89 | author: record.sender_name.clone().unwrap_or_else(|| "Unknown".to_owned()), |
| 90 | excerpt: reply_excerpt(&record), |
| 91 | }); |
| 92 | let outgoing = outgoing_for(&entry, quote); |
| 93 | let outbox_id = new_outbox_id(); |
| 94 | let store = state.read(cx).store.clone(); |
| 95 | if let Some(record) = outbox_record(&outbox_id, &conversation_id, target, thread_root_id.as_deref(), &outgoing, Utc::now()) { |
| 96 | store.put_outbox(&record).ok(); |
| 97 | } |
| 98 | agent_api::resolve_proposal(&conversation_id, Outcome::Sent, cx); |
| 99 | state.update(cx, |state, cx| state.outbox_changed(conversation_id.clone(), cx)); |
| 100 | let receiver = runtime::spawn({ |
| 101 | let conversation_id = conversation_id.clone(); |
| 102 | async move { deliver(&engine, &conversation_id, target, thread_root_id.as_deref(), &outgoing).await } |
| 103 | }); |
| 104 | let state = state.downgrade(); |
| 105 | cx.spawn(async move |cx| { |
| 106 | let failure = match receiver.await { |
| 107 | Ok(Ok(_)) => None, |
| 108 | Ok(Err(error)) => Some(short_error(&error)), |
| 109 | Err(error) => Some(short_error(&error)), |
| 110 | }; |
| 111 | match failure { |
| 112 | None => store.delete_outbox(&outbox_id).ok(), |
| 113 | Some(error) => store.mark_outbox_failed(&outbox_id, &error).ok(), |
| 114 | }; |
| 115 | state.update(cx, |state, cx| state.outbox_changed(conversation_id, cx)).ok(); |
| 116 | }) |
| 117 | .detach(); |
| 118 | } |
| 119 | |
| 120 | fn add_reaction( |
| 121 | state: &Entity<AppState>, |
| 122 | reaction: ReactionProposal, |
| 123 | reacting: Rc<RefCell<HashSet<String>>>, |
| 124 | cx: &mut App, |
| 125 | ) { |
| 126 | let (conversation_id, message_id) = (reaction.conversation_id.clone(), reaction.message_id.clone()); |
| 127 | let Some(engine) = live_engine(state, cx) else { |
| 128 | agent_api::hold_reaction_for_review(&conversation_id, &message_id, cx); |
| 129 | reacting.borrow_mut().remove(&reaction.id); |
| 130 | return; |
| 131 | }; |
| 132 | if message(state, &conversation_id, &message_id, cx).is_none() { |
| 133 | agent_api::resolve_reaction_proposal(&conversation_id, &message_id, &reaction.id, ReactionOutcome::Stale, cx); |
| 134 | reacting.borrow_mut().remove(&reaction.id); |
| 135 | return; |
| 136 | } |
| 137 | let reaction_type = api_reaction(&reaction_glyph(&reaction.emoji)); |
| 138 | let receiver = runtime::spawn({ |
| 139 | let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone()); |
| 140 | async move { engine.set_reaction(&conversation_id, &message_id, &reaction_type).await } |
| 141 | }); |
| 142 | cx.spawn(async move |cx| { |
| 143 | let added = matches!(receiver.await, Ok(Ok(()))); |
| 144 | cx.update(|cx| { |
| 145 | if added { |
| 146 | agent_api::resolve_reaction_proposal(&conversation_id, &message_id, &reaction.id, ReactionOutcome::Accepted, cx); |
| 147 | } else { |
| 148 | agent_api::hold_reaction_for_review(&conversation_id, &message_id, cx); |
| 149 | } |
| 150 | reacting.borrow_mut().remove(&reaction.id); |
| 151 | }); |
| 152 | }) |
| 153 | .detach(); |
| 154 | } |
| 155 | |
| 156 | #[cfg(test)] |
| 157 | mod tests { |
| 158 | use store::{MessageRecord, OutboxTarget}; |
| 159 | |
| 160 | use super::{Route, route}; |
| 161 | |
| 162 | fn record(message_id: &str, reply_to_id: Option<&str>) -> MessageRecord { |
| 163 | MessageRecord { |
| 164 | message_id: message_id.to_owned(), |
| 165 | reply_to_id: reply_to_id.map(str::to_owned), |
| 166 | ..MessageRecord::default() |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | #[test] |
| 171 | fn chats_quote_and_channels_answer_in_the_thread() { |
| 172 | let chat = route(false, Some(record("m1", None))); |
| 173 | assert_eq!((chat.target, chat.quoted.map(|quoted| quoted.message_id)), (OutboxTarget::Flat, Some("m1".to_owned()))); |
| 174 | assert_eq!(route(true, None), Route { target: OutboxTarget::Post, thread_root_id: None, quoted: None }); |
| 175 | let to_post = route(true, Some(record("root", None))); |
| 176 | assert_eq!((to_post.target, to_post.thread_root_id.as_deref(), to_post.quoted), (OutboxTarget::Thread, Some("root"), None)); |
| 177 | let to_reply = route(true, Some(record("r2", Some("root")))); |
| 178 | assert_eq!(to_reply.thread_root_id.as_deref(), Some("root")); |
| 179 | assert_eq!(to_reply.quoted.map(|quoted| quoted.message_id).as_deref(), Some("r2")); |
| 180 | } |
| 181 | } |