BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / agent_api / bridge.rs

bridge.rs

bridge.rs 3.5 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::Arc;
3
4use chrono::{DateTime, Local, Utc};
5use gpui_kit::*;
6use mcp::{AgentHub, UiEvent};
7use teams_core::CoreEvent;
8use tokio::sync::mpsc::UnboundedReceiver;
9
10use super::source::AppSource;
11use super::{AgentApi, ProposalEntry, ProposalStatus};
12use crate::backend::Engine;
13use crate::runtime;
14
15const PREVIEW_CHARACTERS: usize = 200;
16const NEW_MESSAGE_BATCH: usize = 50;
17
18pub fn drain_ui_events(
19 mut receiver: UnboundedReceiver<UiEvent>,
20 api: WeakEntity<AgentApi>,
21 cx: &mut App,
22) {
23 cx.spawn(async move |cx| {
24 while let Some(event) = receiver.recv().await {
25 if api
26 .update(cx, |api, cx| api.apply_ui_event(event, cx))
27 .is_err()
28 {
29 return;
30 }
31 }
32 })
33 .detach();
34}
35
36pub fn apply(proposals: &mut HashMap<String, ProposalEntry>, event: UiEvent) {
37 match event {
38 UiEvent::ProposalChanged(proposal) => {
39 proposals.insert(
40 proposal.conversation_id.clone(),
41 ProposalEntry {
42 proposal,
43 status: ProposalStatus::Pending,
44 },
45 );
46 }
47 UiEvent::ProposalStale(proposal) => {
48 proposals.insert(
49 proposal.conversation_id.clone(),
50 ProposalEntry {
51 proposal,
52 status: ProposalStatus::Stale {
53 answered_at: Local::now(),
54 },
55 },
56 );
57 }
58 UiEvent::ProposalRemoved { conversation_id } => {
59 proposals.remove(&conversation_id);
60 }
61 }
62}
63
64pub fn spawn_message_bridge(engine: Arc<Engine>, hub: Arc<AgentHub>, source: Arc<AppSource>) {
65 let started_at = Utc::now();
66 drop(runtime::spawn(async move {
67 let mut receiver = engine.subscribe();
68 let mut watermarks: HashMap<String, DateTime<Utc>> = HashMap::new();
69 loop {
70 let conversation_id = match receiver.recv().await {
71 Ok(CoreEvent::MessagesChanged { conversation_id }) => conversation_id,
72 Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
73 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
74 };
75 let Ok(store) = mcp::TeamsSource::store(source.as_ref()) else {
76 continue;
77 };
78 let watermark = watermarks
79 .entry(conversation_id.clone())
80 .or_insert(started_at);
81 let Ok(messages) =
82 store.messages_after(&conversation_id, *watermark, NEW_MESSAGE_BATCH)
83 else {
84 continue;
85 };
86 let my_id = mcp::TeamsSource::me_id(source.as_ref());
87 for message in messages {
88 *watermark = (*watermark).max(message.created_at);
89 if message.deleted {
90 continue;
91 }
92 let sender_is_me = my_id.is_some() && message.sender_id == my_id;
93 let preview: String = store::plain_text(&message.body_html)
94 .chars()
95 .take(PREVIEW_CHARACTERS)
96 .collect();
97 hub.message_arrived(
98 &conversation_id,
99 &message.message_id,
100 sender_is_me,
101 message.sender_name,
102 &preview,
103 );
104 }
105 }
106 }));
107}