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