BlueGit

ict rusty-teams

Files

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

mod.rs

refactor(app): extract app-base crate
metis Daniel Däschle · pushed by metis · 7 weeks ago
16e522c2 History
mod.rs 15.1 KiB Download Raw
1mod bridge;
2mod source;
3
4use std::collections::{BTreeSet, HashMap};
5use std::sync::Arc;
6
7use chrono::{DateTime, Local};
8use gpui_kit::*;
9use mcp::install::{Homes, Location};
10use mcp::{
11 Access, AgentHub, AgentPolicy, McpEndpoint, Outcome, Proposal, ReactionOutcome,
12 ReactionProposal, ServerHandle,
13};
14use store::Store;
15use app_base::agent_api::{extras, image_scale};
16
17use crate::backend::Engine;
18use crate::runtime;
19use source::AppSource;
20
21#[derive(Debug, Clone, PartialEq)]
22pub enum ProposalStatus {
23 Pending,
24 Stale { answered_at: DateTime<Local> },
25 Failed { reason: String },
26}
27
28#[derive(Debug, Clone, PartialEq)]
29pub struct Thumbnail {
30 pub image: Arc<Image>,
31 pub dimensions: (u32, u32),
32}
33
34#[derive(Debug, Clone, PartialEq)]
35pub struct ProposalPicture {
36 pub name: String,
37 pub bytes: Arc<Vec<u8>>,
38 pub thumbnail: Option<Thumbnail>,
39}
40
41#[derive(Debug, Clone, PartialEq)]
42pub struct ProposalEntry {
43 pub proposal: Proposal,
44 pub body: Arc<Vec<crate::render::Block>>,
45 pub mention_labels: Vec<String>,
46 pub images: Vec<ProposalPicture>,
47 pub status: ProposalStatus,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum ServerStatus {
52 Off,
53 Starting,
54 Running(u16),
55 PortInUse(u16),
56 Failed(String),
57}
58
59pub struct AgentApi {
60 hub: Arc<AgentHub>,
61 source: Arc<AppSource>,
62 store: Arc<Store>,
63 token: String,
64 proposals: HashMap<String, ProposalEntry>,
65 reactions: HashMap<(String, String), ReactionProposal>,
66 server: Option<ServerHandle>,
67 status: ServerStatus,
68 generation: u64,
69 reinstall_note: Option<String>,
70 demo: bool,
71}
72
73struct AgentApiHandle(Entity<AgentApi>);
74
75impl Global for AgentApiHandle {}
76
77const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";
78
79pub fn endpoint_url(port: u16) -> String {
80 format!("http://127.0.0.1:{port}/mcp")
81}
82
83fn demo_port(configured: Option<String>) -> u16 {
84 configured
85 .and_then(|value| value.parse().ok())
86 .or_else(|| {
87 std::net::TcpListener::bind(("127.0.0.1", 0))
88 .and_then(|listener| listener.local_addr())
89 .map(|addr| addr.port())
90 .ok()
91 })
92 .unwrap_or_default()
93}
94
95pub fn is_demo(cx: &App) -> bool {
96 handle(cx).is_some_and(|api| api.read(cx).demo)
97}
98
99pub fn agent_homes(demo: bool) -> Homes {
100 if demo {
101 Homes {
102 entries: vec![(
103 Location::Native,
104 std::env::temp_dir().join("rusty-teams-demo-home"),
105 )],
106 }
107 } else {
108 Homes::detect()
109 }
110}
111
112pub fn agent_label(agent: Option<&str>) -> &'static str {
113 match agent.map(str::to_ascii_lowercase).as_deref() {
114 Some("claude") => "Claude",
115 Some("copilot") => "Copilot",
116 Some("codex") => "Codex",
117 _ => "Agent",
118 }
119}
120
121pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
122 let (ui, receiver) = tokio::sync::mpsc::unbounded_channel();
123 let mut policy = mcp::load_policy(&store);
124 if demo {
125 policy.port = demo_port(std::env::var(DEMO_PORT_ENV).ok());
126 }
127 let hub = AgentHub::new(store.clone(), policy, ui);
128 let token = mcp::load_or_create_token(&store).unwrap_or_default();
129 let source = Arc::new(AppSource::new(store.clone()));
130 let api = cx.new(|_| AgentApi {
131 hub,
132 source,
133 store,
134 token,
135 proposals: HashMap::new(),
136 reactions: HashMap::new(),
137 server: None,
138 status: ServerStatus::Off,
139 generation: 0,
140 reinstall_note: None,
141 demo,
142 });
143 bridge::drain_ui_events(receiver, api.downgrade(), cx);
144 api.update(cx, |api, cx| {
145 let _ = api.hub.restore_pending();
146 api.reconcile(cx);
147 });
148 cx.set_global(AgentApiHandle(api));
149}
150
151pub fn engine_ready(engine: Arc<Engine>, cx: &mut App) {
152 let Some(api) = handle(cx) else {
153 return;
154 };
155 let api = api.read(cx);
156 if api.source.set_engine(engine.clone()) {
157 bridge::spawn_message_bridge(engine, api.hub.clone(), api.source.clone());
158 }
159}
160
161pub fn handle(cx: &App) -> Option<Entity<AgentApi>> {
162 cx.try_global::<AgentApiHandle>()
163 .map(|handle| handle.0.clone())
164}
165
166pub fn mcp_endpoint(cx: &App) -> Option<McpEndpoint> {
167 let api = handle(cx)?.read(cx);
168 match api.status {
169 ServerStatus::Running(port) => Some(McpEndpoint {
170 url: endpoint_url(port),
171 token: api.token.clone(),
172 }),
173 _ => None,
174 }
175}
176
177pub fn configured_endpoint(cx: &App) -> Option<McpEndpoint> {
178 let api = handle(cx)?.read(cx);
179 Some(McpEndpoint {
180 url: endpoint_url(api.hub.policy().port),
181 token: api.token.clone(),
182 })
183}
184
185pub fn policy(cx: &App) -> AgentPolicy {
186 handle(cx)
187 .map(|api| api.read(cx).hub.policy())
188 .unwrap_or_default()
189}
190
191pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {
192 let Some(api) = handle(cx) else {
193 return false;
194 };
195 let api = api.read(cx);
196 let policy = api.hub.policy();
197 policy.propose && policy.can_read_any_kind(conversation_id)
198}
199
200pub fn allow_chat(conversation_id: &str, cx: &mut App) {
201 let Some(api) = handle(cx) else {
202 return;
203 };
204 let conversation_id = conversation_id.to_owned();
205 api.update(cx, |api, cx| {
206 let is_channel = api.store.channel(&conversation_id).ok().flatten().is_some();
207 api.update_policy(
208 move |policy| {
209 policy.enabled = true;
210 policy.propose = true;
211 let access = if is_channel {
212 &mut policy.channels
213 } else {
214 &mut policy.chats
215 };
216 match access {
217 Access::All => {}
218 Access::Selected(ids) => {
219 ids.insert(conversation_id);
220 }
221 Access::None => *access = Access::Selected(BTreeSet::from([conversation_id])),
222 }
223 },
224 cx,
225 );
226 });
227}
228
229pub fn update_policy(cx: &mut App, change: impl FnOnce(&mut AgentPolicy)) {
230 if let Some(api) = handle(cx) {
231 api.update(cx, |api, cx| api.update_policy(change, cx));
232 }
233}
234
235pub fn proposal(conversation_id: &str, cx: &App) -> Option<ProposalEntry> {
236 handle(cx)?.read(cx).proposals.get(conversation_id).cloned()
237}
238
239pub fn reaction_proposals(conversation_id: &str, cx: &App) -> HashMap<String, ReactionProposal> {
240 let Some(api) = handle(cx) else {
241 return HashMap::new();
242 };
243 api.read(cx)
244 .reactions
245 .values()
246 .filter(|reaction| reaction.conversation_id == conversation_id)
247 .map(|reaction| (reaction.message_id.clone(), reaction.clone()))
248 .collect()
249}
250
251pub fn resolve_reaction_proposal(
252 conversation_id: &str,
253 message_id: &str,
254 proposal_id: &str,
255 outcome: ReactionOutcome,
256 cx: &mut App,
257) {
258 if let Some(api) = handle(cx) {
259 api.update(cx, |api, cx| {
260 api.resolve_reaction(conversation_id, message_id, proposal_id, outcome, cx)
261 });
262 }
263}
264
265pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
266 let Some(api) = handle(cx) else {
267 return HashMap::new();
268 };
269 api.read(cx)
270 .proposals
271 .iter()
272 .filter(|(_, entry)| !matches!(entry.status, ProposalStatus::Stale { .. }))
273 .map(|(conversation_id, entry)| {
274 (
275 conversation_id.clone(),
276 agent_label(entry.proposal.agent.as_deref()),
277 )
278 })
279 .collect()
280}
281
282pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
283 if let Some(api) = handle(cx) {
284 api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
285 }
286}
287
288pub fn fail_proposal(conversation_id: &str, reason: String, cx: &mut App) {
289 if let Some(api) = handle(cx) {
290 api.update(cx, |api, cx| {
291 if let Some(entry) = api.proposals.get_mut(conversation_id) {
292 entry.status = ProposalStatus::Failed { reason };
293 cx.notify();
294 }
295 });
296 }
297}
298
299pub fn user_typing(conversation_id: &str, cx: &App) {
300 if let Some(api) = handle(cx) {
301 api.read(cx).hub.user_typing(conversation_id);
302 }
303}
304
305pub fn user_sent(conversation_id: &str, cx: &App) {
306 if let Some(api) = handle(cx) {
307 api.read(cx).hub.user_sent(conversation_id);
308 }
309}
310
311pub fn note_caption(meeting_chat_id: &str, caption_id: &str, speaker: &str, text: &str, cx: &App) {
312 let Some(api) = handle(cx) else {
313 return;
314 };
315 let hub = &api.read(cx).hub;
316 let policy = hub.policy();
317 if policy.enabled && policy.transcripts {
318 hub.push_caption(meeting_chat_id, caption_id, speaker, text);
319 }
320}
321
322pub fn clear_captions(meeting_chat_id: &str, cx: &App) {
323 if let Some(api) = handle(cx) {
324 api.read(cx).hub.clear_captions(meeting_chat_id);
325 }
326}
327
328impl AgentApi {
329 pub fn status(&self) -> &ServerStatus {
330 &self.status
331 }
332
333 pub fn token(&self) -> &str {
334 &self.token
335 }
336
337 pub fn regenerate_token(&mut self, cx: &mut Context<Self>) {
338 if let Ok(token) = mcp::regenerate_token(&self.store) {
339 self.token = token;
340 self.reinstall_agent_configs(cx);
341 if self.hub.policy().enabled {
342 self.start_server(cx);
343 }
344 cx.notify();
345 }
346 }
347
348 pub fn reinstall_note(&self) -> Option<&str> {
349 self.reinstall_note.as_deref()
350 }
351
352 fn reinstall_agent_configs(&mut self, cx: &mut Context<Self>) {
353 let endpoint = McpEndpoint {
354 url: endpoint_url(self.hub.policy().port),
355 token: self.token.clone(),
356 };
357 let demo = self.demo;
358 let task = cx.background_spawn(async move {
359 mcp::install::reinstall_all(&endpoint, &agent_homes(demo))
360 });
361 cx.spawn(async move |this, cx| {
362 let results = task.await;
363 this.update(cx, |this, cx| {
364 this.reinstall_note = results.into_iter().find_map(|(target, result)| {
365 result
366 .err()
367 .map(|error| format!("Could not update {}: {error}", target.label()))
368 });
369 cx.notify();
370 })
371 .ok();
372 })
373 .detach();
374 }
375
376 pub fn update_policy(&mut self, change: impl FnOnce(&mut AgentPolicy), cx: &mut Context<Self>) {
377 let mut policy = self.hub.policy();
378 let previous_port = policy.port;
379 change(&mut policy);
380 let port_changed = policy.port != previous_port;
381 mcp::save_policy(&self.store, &policy);
382 self.hub.set_policy(policy);
383 self.reconcile(cx);
384 if port_changed {
385 self.reinstall_agent_configs(cx);
386 }
387 cx.notify();
388 }
389
390 fn apply_ui_event(
391 &mut self,
392 event: mcp::UiEvent,
393 pictures: Vec<ProposalPicture>,
394 cx: &mut Context<Self>,
395 ) {
396 bridge::apply(
397 &mut self.proposals,
398 &mut self.reactions,
399 event,
400 pictures,
401 &self.store,
402 );
403 cx.notify();
404 }
405
406 fn resolve(&mut self, conversation_id: &str, outcome: Outcome, cx: &mut Context<Self>) {
407 let Some(entry) = self.proposals.remove(conversation_id) else {
408 return;
409 };
410 if !matches!(entry.status, ProposalStatus::Stale { .. }) {
411 self.hub.resolve(&entry.proposal.id, outcome);
412 }
413 cx.notify();
414 }
415
416 fn resolve_reaction(
417 &mut self,
418 conversation_id: &str,
419 message_id: &str,
420 proposal_id: &str,
421 outcome: ReactionOutcome,
422 cx: &mut Context<Self>,
423 ) {
424 let key = (conversation_id.to_owned(), message_id.to_owned());
425 if self
426 .reactions
427 .get(&key)
428 .is_none_or(|reaction| reaction.id != proposal_id)
429 {
430 return;
431 }
432 if let Some(reaction) = self.reactions.remove(&key) {
433 self.hub.resolve_reaction(&reaction.id, outcome);
434 cx.notify();
435 }
436 }
437
438 fn reconcile(&mut self, cx: &mut Context<Self>) {
439 let policy = self.hub.policy();
440 let wanted = policy.enabled;
441 match (wanted, &self.status) {
442 (false, ServerStatus::Off) => {}
443 (false, _) => self.stop_server(cx),
444 (true, ServerStatus::Running(port)) if *port == policy.port => {}
445 (true, _) => self.start_server(cx),
446 }
447 }
448
449 fn stop_server(&mut self, cx: &mut Context<Self>) {
450 self.generation += 1;
451 if let Some(server) = self.server.take() {
452 drop(runtime::spawn(server.shutdown()));
453 }
454 self.status = ServerStatus::Off;
455 cx.notify();
456 }
457
458 fn start_server(&mut self, cx: &mut Context<Self>) {
459 self.generation += 1;
460 let generation = self.generation;
461 let previous = self.server.take();
462 let (hub, source, token) = (self.hub.clone(), self.source.clone(), self.token.clone());
463 let port = self.hub.policy().port;
464 self.status = ServerStatus::Starting;
465 let receiver = runtime::spawn(async move {
466 if let Some(previous) = previous {
467 previous.shutdown().await;
468 }
469 mcp::start(hub, source, port, token).await
470 });
471 cx.spawn(async move |this, cx| {
472 let Ok(result) = receiver.await else {
473 return;
474 };
475 this.update(cx, |this, cx| {
476 this.finish_start(generation, port, result, cx)
477 })
478 .ok();
479 })
480 .detach();
481 cx.notify();
482 }
483
484 fn finish_start(
485 &mut self,
486 generation: u64,
487 port: u16,
488 result: Result<ServerHandle, mcp::ServerError>,
489 cx: &mut Context<Self>,
490 ) {
491 if generation != self.generation {
492 if let Ok(server) = result {
493 drop(runtime::spawn(server.shutdown()));
494 }
495 return;
496 }
497 match result {
498 Ok(server) => {
499 if self.demo {
500 println!("mcp: {} token={}", endpoint_url(port), self.token);
501 }
502 self.server = Some(server);
503 self.status = ServerStatus::Running(port);
504 }
505 Err(mcp::ServerError::PortInUse { port }) => {
506 self.status = ServerStatus::PortInUse(port)
507 }
508 Err(error) => self.status = ServerStatus::Failed(error.to_string()),
509 }
510 cx.notify();
511 }
512}
513
514#[cfg(test)]
515mod tests {
516 use super::{agent_label, demo_port};
517
518 #[test]
519 fn demo_port_is_free_unless_configured() {
520 let picked = demo_port(None);
521 assert_ne!(picked, 0);
522 assert!(std::net::TcpListener::bind(("127.0.0.1", picked)).is_ok());
523 assert_ne!(demo_port(Some("not a port".into())), 0);
524 assert_eq!(demo_port(Some("48000".into())), 48000);
525 }
526
527 #[test]
528 fn agent_labels_know_the_common_agents() {
529 assert_eq!(agent_label(Some("claude")), "Claude");
530 assert_eq!(agent_label(Some("Copilot")), "Copilot");
531 assert_eq!(agent_label(Some("codex")), "Codex");
532 assert_eq!(agent_label(Some("other")), "Agent");
533 assert_eq!(agent_label(None), "Agent");
534 }
535}