BlueGit

ict rusty-teams

Files

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

mod.rs

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