BlueGit

ict rusty-teams

Files

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

mod.rs

mod.rs 19.2 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.write && 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.write = 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)?
246 .read(cx)
247 .proposals
248 .get(conversation_id)
249 .filter(|entry| !entry.proposal.direct)
250 .cloned()
251}
252
253pub fn direct_messages(cx: &App) -> Vec<ProposalEntry> {
254 let Some(api) = handle(cx) else {
255 return Vec::new();
256 };
257 api.read(cx)
258 .proposals
259 .values()
260 .filter(|entry| entry.proposal.direct && entry.status == ProposalStatus::Pending)
261 .cloned()
262 .collect()
263}
264
265pub fn direct_reactions(cx: &App) -> Vec<ReactionProposal> {
266 let Some(api) = handle(cx) else {
267 return Vec::new();
268 };
269 api.read(cx)
270 .reactions
271 .values()
272 .filter(|reaction| reaction.direct)
273 .cloned()
274 .collect()
275}
276
277pub fn hold_for_review(conversation_id: &str, cx: &mut App) {
278 if let Some(api) = handle(cx) {
279 api.update(cx, |api, cx| {
280 if let Some(entry) = api.proposals.get_mut(conversation_id) {
281 entry.proposal.direct = false;
282 cx.notify();
283 }
284 });
285 }
286}
287
288pub fn hold_reaction_for_review(conversation_id: &str, message_id: &str, cx: &mut App) {
289 if let Some(api) = handle(cx) {
290 api.update(cx, |api, cx| {
291 let key = (conversation_id.to_owned(), message_id.to_owned());
292 if let Some(reaction) = api.reactions.get_mut(&key) {
293 reaction.direct = false;
294 cx.notify();
295 }
296 });
297 }
298}
299
300pub fn reaction_proposals(conversation_id: &str, cx: &App) -> HashMap<String, ReactionProposal> {
301 let Some(api) = handle(cx) else {
302 return HashMap::new();
303 };
304 api.read(cx)
305 .reactions
306 .values()
307 .filter(|reaction| reaction.conversation_id == conversation_id && !reaction.direct)
308 .map(|reaction| (reaction.message_id.clone(), reaction.clone()))
309 .collect()
310}
311
312pub fn resolve_reaction_proposal(
313 conversation_id: &str,
314 message_id: &str,
315 proposal_id: &str,
316 outcome: ReactionOutcome,
317 cx: &mut App,
318) {
319 if let Some(api) = handle(cx) {
320 api.update(cx, |api, cx| {
321 api.resolve_reaction(conversation_id, message_id, proposal_id, outcome, cx)
322 });
323 }
324}
325
326pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
327 let Some(api) = handle(cx) else {
328 return HashMap::new();
329 };
330 api.read(cx)
331 .proposals
332 .iter()
333 .filter(|(_, entry)| {
334 !entry.proposal.direct && !matches!(entry.status, ProposalStatus::Stale { .. })
335 })
336 .map(|(conversation_id, entry)| {
337 (
338 conversation_id.clone(),
339 agent_label(entry.proposal.agent.as_deref()),
340 )
341 })
342 .collect()
343}
344
345pub fn pending_proposals(cx: &App) -> Vec<PendingProposal> {
346 handle(cx).map_or_else(Vec::new, |api| api.read(cx).pending_proposals())
347}
348
349pub fn unseen_proposal_count(cx: &App) -> usize {
350 pending_proposals(cx)
351 .iter()
352 .filter(|pending| !pending.seen)
353 .count()
354}
355
356pub fn mark_proposal_seen(proposal_id: &str, cx: &mut App) {
357 mark_proposals_seen(cx, |pending| pending.id == proposal_id);
358}
359
360pub fn mark_conversation_proposals_seen(conversation_id: &str, cx: &mut App) {
361 mark_proposals_seen(cx, |pending| pending.conversation_id == conversation_id);
362}
363
364pub fn mark_all_proposals_seen(cx: &mut App) {
365 mark_proposals_seen(cx, |_| true);
366}
367
368fn mark_proposals_seen(cx: &mut App, matches: impl Fn(&PendingProposal) -> bool) {
369 let Some(api) = handle(cx) else {
370 return;
371 };
372 let fresh: Vec<String> = api
373 .read(cx)
374 .pending_proposals()
375 .into_iter()
376 .filter(|pending| !pending.seen && matches(pending))
377 .map(|pending| pending.id)
378 .collect();
379 if fresh.is_empty() {
380 return;
381 }
382 api.update(cx, |api, cx| api.mark_seen(fresh, cx));
383}
384
385pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
386 if let Some(api) = handle(cx) {
387 api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
388 }
389}
390
391pub fn fail_proposal(conversation_id: &str, reason: String, cx: &mut App) {
392 if let Some(api) = handle(cx) {
393 api.update(cx, |api, cx| {
394 if let Some(entry) = api.proposals.get_mut(conversation_id) {
395 entry.status = ProposalStatus::Failed { reason };
396 cx.notify();
397 }
398 });
399 }
400}
401
402pub fn user_typing(conversation_id: &str, cx: &App) {
403 if let Some(api) = handle(cx) {
404 api.read(cx).hub.user_typing(conversation_id);
405 }
406}
407
408pub fn user_sent(conversation_id: &str, cx: &App) {
409 if let Some(api) = handle(cx) {
410 api.read(cx).hub.user_sent(conversation_id);
411 }
412}
413
414pub fn note_caption(meeting_chat_id: &str, caption_id: &str, speaker: &str, text: &str, cx: &App) {
415 let Some(api) = handle(cx) else {
416 return;
417 };
418 let hub = &api.read(cx).hub;
419 let policy = hub.policy();
420 if policy.enabled && policy.transcripts {
421 hub.push_caption(meeting_chat_id, caption_id, speaker, text);
422 }
423}
424
425pub fn clear_captions(meeting_chat_id: &str, cx: &App) {
426 if let Some(api) = handle(cx) {
427 api.read(cx).hub.clear_captions(meeting_chat_id);
428 }
429}
430
431impl AgentApi {
432 pub fn status(&self) -> &ServerStatus {
433 &self.status
434 }
435
436 pub fn token(&self) -> &str {
437 &self.token
438 }
439
440 pub fn regenerate_token(&mut self, cx: &mut Context<Self>) {
441 if let Ok(token) = mcp::regenerate_token(&self.store) {
442 self.token = token;
443 self.reinstall_agent_configs(cx);
444 if self.hub.policy().enabled {
445 self.start_server(cx);
446 }
447 cx.notify();
448 }
449 }
450
451 pub fn pending_proposals(&self) -> Vec<PendingProposal> {
452 pending::collect(
453 &self.proposals,
454 &self.reactions,
455 &self.reaction_excerpts,
456 &self.seen_proposals,
457 )
458 }
459
460 fn mark_seen(&mut self, proposal_ids: Vec<String>, cx: &mut Context<Self>) {
461 self.seen_proposals.extend(proposal_ids);
462 let pending: HashSet<String> = self
463 .pending_proposals()
464 .into_iter()
465 .map(|pending| pending.id)
466 .collect();
467 self.seen_proposals.retain(|id| pending.contains(id));
468 let _ = self.store.set_meta(
469 SEEN_PROPOSALS_KEY,
470 &pending::encode_seen(&self.seen_proposals),
471 );
472 cx.notify();
473 }
474
475 pub fn reinstall_note(&self) -> Option<&str> {
476 self.reinstall_note.as_deref()
477 }
478
479 fn reinstall_agent_configs(&mut self, cx: &mut Context<Self>) {
480 let endpoint = McpEndpoint {
481 url: endpoint_url(self.hub.policy().port),
482 token: self.token.clone(),
483 };
484 let demo = self.demo;
485 let task = cx.background_spawn(async move {
486 mcp::install::reinstall_all(&endpoint, &agent_homes(demo))
487 });
488 cx.spawn(async move |this, cx| {
489 let results = task.await;
490 this.update(cx, |this, cx| {
491 this.reinstall_note = results.into_iter().find_map(|(target, result)| {
492 result
493 .err()
494 .map(|error| format!("Could not update {}: {error}", target.label()))
495 });
496 cx.notify();
497 })
498 .ok();
499 })
500 .detach();
501 }
502
503 pub fn update_policy(&mut self, change: impl FnOnce(&mut AgentPolicy), cx: &mut Context<Self>) {
504 let mut policy = self.hub.policy();
505 let previous_port = policy.port;
506 change(&mut policy);
507 let port_changed = policy.port != previous_port;
508 mcp::save_policy(&self.store, &policy);
509 self.hub.set_policy(policy);
510 self.reconcile(cx);
511 if port_changed {
512 self.reinstall_agent_configs(cx);
513 }
514 cx.notify();
515 }
516
517 fn apply_ui_event(
518 &mut self,
519 event: mcp::UiEvent,
520 pictures: Vec<ProposalPicture>,
521 cx: &mut Context<Self>,
522 ) {
523 if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event
524 && let Some(excerpt) = pending::reacted_excerpt(
525 &self.store,
526 &reaction.conversation_id,
527 &reaction.message_id,
528 )
529 {
530 self.reaction_excerpts.insert(reaction.id.clone(), excerpt);
531 }
532 bridge::apply(
533 &mut self.proposals,
534 &mut self.reactions,
535 event,
536 pictures,
537 &self.store,
538 );
539 let reactions = &self.reactions;
540 self.reaction_excerpts
541 .retain(|id, _| reactions.values().any(|reaction| &reaction.id == id));
542 cx.notify();
543 }
544
545 fn resolve(&mut self, conversation_id: &str, outcome: Outcome, cx: &mut Context<Self>) {
546 let Some(entry) = self.proposals.remove(conversation_id) else {
547 return;
548 };
549 if !matches!(entry.status, ProposalStatus::Stale { .. }) {
550 self.hub.resolve(&entry.proposal.id, outcome);
551 }
552 cx.notify();
553 }
554
555 fn resolve_reaction(
556 &mut self,
557 conversation_id: &str,
558 message_id: &str,
559 proposal_id: &str,
560 outcome: ReactionOutcome,
561 cx: &mut Context<Self>,
562 ) {
563 let key = (conversation_id.to_owned(), message_id.to_owned());
564 if self
565 .reactions
566 .get(&key)
567 .is_none_or(|reaction| reaction.id != proposal_id)
568 {
569 return;
570 }
571 if let Some(reaction) = self.reactions.remove(&key) {
572 self.hub.resolve_reaction(&reaction.id, outcome);
573 cx.notify();
574 }
575 }
576
577 fn reconcile(&mut self, cx: &mut Context<Self>) {
578 let policy = self.hub.policy();
579 let wanted = policy.enabled;
580 match (wanted, &self.status) {
581 (false, ServerStatus::Off) => {}
582 (false, _) => self.stop_server(cx),
583 (true, ServerStatus::Running(port)) if *port == policy.port => {}
584 (true, _) => self.start_server(cx),
585 }
586 }
587
588 fn stop_server(&mut self, cx: &mut Context<Self>) {
589 self.generation += 1;
590 if let Some(server) = self.server.take() {
591 drop(runtime::spawn(server.shutdown()));
592 }
593 self.status = ServerStatus::Off;
594 cx.notify();
595 }
596
597 fn start_server(&mut self, cx: &mut Context<Self>) {
598 self.generation += 1;
599 let generation = self.generation;
600 let previous = self.server.take();
601 let (hub, source, token) = (self.hub.clone(), self.source.clone(), self.token.clone());
602 let port = self.hub.policy().port;
603 self.status = ServerStatus::Starting;
604 let receiver = runtime::spawn(async move {
605 if let Some(previous) = previous {
606 previous.shutdown().await;
607 }
608 mcp::start(hub, source, port, token).await
609 });
610 cx.spawn(async move |this, cx| {
611 let Ok(result) = receiver.await else {
612 return;
613 };
614 this.update(cx, |this, cx| {
615 this.finish_start(generation, port, result, cx)
616 })
617 .ok();
618 })
619 .detach();
620 cx.notify();
621 }
622
623 fn finish_start(
624 &mut self,
625 generation: u64,
626 port: u16,
627 result: Result<ServerHandle, mcp::ServerError>,
628 cx: &mut Context<Self>,
629 ) {
630 if generation != self.generation {
631 if let Ok(server) = result {
632 drop(runtime::spawn(server.shutdown()));
633 }
634 return;
635 }
636 match result {
637 Ok(server) => {
638 if self.demo {
639 println!("mcp: {} token={}", endpoint_url(port), self.token);
640 }
641 self.server = Some(server);
642 self.status = ServerStatus::Running(port);
643 }
644 Err(mcp::ServerError::PortInUse { port }) => {
645 self.status = ServerStatus::PortInUse(port)
646 }
647 Err(error) => self.status = ServerStatus::Failed(error.to_string()),
648 }
649 cx.notify();
650 }
651}
652
653#[cfg(test)]
654mod tests {
655 use super::{agent_label, demo_port};
656
657 #[test]
658 fn demo_port_is_free_unless_configured() {
659 let picked = demo_port(None);
660 assert_ne!(picked, 0);
661 assert!(std::net::TcpListener::bind(("127.0.0.1", picked)).is_ok());
662 assert_ne!(demo_port(Some("not a port".into())), 0);
663 assert_eq!(demo_port(Some("48000".into())), 48000);
664 }
665
666 #[test]
667 fn agent_labels_know_the_common_agents() {
668 assert_eq!(agent_label(Some("claude")), "Claude");
669 assert_eq!(agent_label(Some("Copilot")), "Copilot");
670 assert_eq!(agent_label(Some("codex")), "Codex");
671 assert_eq!(agent_label(Some("other")), "Agent");
672 assert_eq!(agent_label(None), "Agent");
673 }
674}