BlueGit

ict rusty-teams

Files

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

mod.rs

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