BlueGit

ict rusty-teams

Files

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

mod.rs

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