BlueGit

ict rusty-teams

Files

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

mod.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
mod.rs 21.2 KiB Download Raw
1pub mod body;
2pub mod bridge;
3pub mod meetings;
4pub mod pending;
5pub mod source;
6
7use std::collections::{BTreeSet, HashMap, HashSet};
8use std::sync::Arc;
9
10use app_base::agent_api::{extras, image_scale};
11use chrono::{DateTime, Local};
12use gpui_kit::*;
13use mcp::install::{Homes, Location};
14use mcp::{
15 Access, AgentHub, AgentPolicy, McpEndpoint, Outcome, Proposal, ReactionOutcome,
16 ReactionProposal, ServerHandle,
17};
18use store::Store;
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(
160 crate::demo::agent_meeting_draft(),
161 Some("claude".to_owned()),
162 None,
163 );
164 }
165 api.reconcile(cx);
166 });
167 cx.set_global(AgentApiHandle(api));
168}
169
170pub fn engine_ready(engine: Arc<Engine>, cx: &mut App) {
171 let Some(api) = handle(cx) else {
172 return;
173 };
174 let api = api.read(cx);
175 if api.source.set_engine(engine.clone()) {
176 bridge::spawn_message_bridge(engine, api.hub.clone(), api.source.clone());
177 }
178}
179
180pub fn handle(cx: &App) -> Option<Entity<AgentApi>> {
181 cx.try_global::<AgentApiHandle>()
182 .map(|handle| handle.0.clone())
183}
184
185pub fn mcp_endpoint(cx: &App) -> Option<McpEndpoint> {
186 let api = handle(cx)?.read(cx);
187 match api.status {
188 ServerStatus::Running(port) => Some(McpEndpoint {
189 url: endpoint_url(port),
190 token: api.token.clone(),
191 }),
192 _ => None,
193 }
194}
195
196pub fn configured_endpoint(cx: &App) -> Option<McpEndpoint> {
197 let api = handle(cx)?.read(cx);
198 Some(McpEndpoint {
199 url: endpoint_url(api.hub.policy().port),
200 token: api.token.clone(),
201 })
202}
203
204pub fn policy(cx: &App) -> AgentPolicy {
205 handle(cx)
206 .map(|api| api.read(cx).hub.policy())
207 .unwrap_or_default()
208}
209
210pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {
211 let Some(api) = handle(cx) else {
212 return false;
213 };
214 let api = api.read(cx);
215 let policy = api.hub.policy();
216 policy.write && policy.can_read_any_kind(conversation_id)
217}
218
219pub fn allow_chat(conversation_id: &str, cx: &mut App) {
220 let Some(api) = handle(cx) else {
221 return;
222 };
223 let conversation_id = conversation_id.to_owned();
224 api.update(cx, |api, cx| {
225 let is_channel = api.store.channel(&conversation_id).ok().flatten().is_some();
226 api.update_policy(
227 move |policy| {
228 policy.enabled = true;
229 policy.write = true;
230 let access = if is_channel {
231 &mut policy.channels
232 } else {
233 &mut policy.chats
234 };
235 match access {
236 Access::All => {}
237 Access::Selected(ids) => {
238 ids.insert(conversation_id);
239 }
240 Access::None => *access = Access::Selected(BTreeSet::from([conversation_id])),
241 }
242 },
243 cx,
244 );
245 });
246}
247
248pub fn update_policy(cx: &mut App, change: impl FnOnce(&mut AgentPolicy)) {
249 if let Some(api) = handle(cx) {
250 api.update(cx, |api, cx| api.update_policy(change, cx));
251 }
252}
253
254pub fn proposal(conversation_id: &str, cx: &App) -> Option<ProposalEntry> {
255 handle(cx)?
256 .read(cx)
257 .proposals
258 .get(conversation_id)
259 .filter(|entry| !entry.proposal.direct)
260 .cloned()
261}
262
263pub fn free_writing(conversation_id: &str, cx: &App) -> Option<mcp::FreeWriting> {
264 handle(cx)?.read(cx).hub.free_writing(conversation_id)
265}
266
267pub fn allow_free_writing(
268 conversation_id: &str,
269 minutes: u32,
270 agent: Option<String>,
271 cx: &mut App,
272) {
273 let Some(api) = handle(cx) else {
274 return;
275 };
276 let lasting = std::time::Duration::from_secs(u64::from(minutes) * 60);
277 let until = chrono::Utc::now() + chrono::Duration::minutes(i64::from(minutes));
278 api.update(cx, |api, cx| {
279 api.hub.grant_free_writing(conversation_id, until, agent);
280 cx.notify();
281 let conversation_id = conversation_id.to_owned();
282 cx.spawn(async move |this, cx| {
283 cx.background_executor().timer(lasting).await;
284 this.update(cx, |api, cx| {
285 if api.hub.free_writing(&conversation_id).is_none() {
286 api.hub.stop_free_writing(&conversation_id);
287 }
288 cx.notify();
289 })
290 .ok();
291 })
292 .detach();
293 });
294}
295
296pub fn stop_free_writing(conversation_id: &str, cx: &mut App) {
297 if let Some(api) = handle(cx) {
298 api.update(cx, |api, cx| {
299 api.hub.stop_free_writing(conversation_id);
300 cx.notify();
301 });
302 }
303}
304
305pub fn direct_messages(cx: &App) -> Vec<ProposalEntry> {
306 let Some(api) = handle(cx) else {
307 return Vec::new();
308 };
309 api.read(cx)
310 .proposals
311 .values()
312 .filter(|entry| entry.proposal.direct && entry.status == ProposalStatus::Pending)
313 .cloned()
314 .collect()
315}
316
317pub fn direct_reactions(cx: &App) -> Vec<ReactionProposal> {
318 let Some(api) = handle(cx) else {
319 return Vec::new();
320 };
321 api.read(cx)
322 .reactions
323 .values()
324 .filter(|reaction| reaction.direct)
325 .cloned()
326 .collect()
327}
328
329pub fn hold_for_review(conversation_id: &str, cx: &mut App) {
330 if let Some(api) = handle(cx) {
331 api.update(cx, |api, cx| {
332 if let Some(entry) = api.proposals.get_mut(conversation_id) {
333 entry.proposal.direct = false;
334 cx.notify();
335 }
336 });
337 }
338}
339
340pub fn hold_reaction_for_review(conversation_id: &str, message_id: &str, cx: &mut App) {
341 if let Some(api) = handle(cx) {
342 api.update(cx, |api, cx| {
343 let key = (conversation_id.to_owned(), message_id.to_owned());
344 if let Some(reaction) = api.reactions.get_mut(&key) {
345 reaction.direct = false;
346 cx.notify();
347 }
348 });
349 }
350}
351
352pub fn reaction_proposals(conversation_id: &str, cx: &App) -> HashMap<String, ReactionProposal> {
353 let Some(api) = handle(cx) else {
354 return HashMap::new();
355 };
356 api.read(cx)
357 .reactions
358 .values()
359 .filter(|reaction| reaction.conversation_id == conversation_id && !reaction.direct)
360 .map(|reaction| (reaction.message_id.clone(), reaction.clone()))
361 .collect()
362}
363
364pub fn resolve_reaction_proposal(
365 conversation_id: &str,
366 message_id: &str,
367 proposal_id: &str,
368 outcome: ReactionOutcome,
369 cx: &mut App,
370) {
371 if let Some(api) = handle(cx) {
372 api.update(cx, |api, cx| {
373 api.resolve_reaction(conversation_id, message_id, proposal_id, outcome, cx)
374 });
375 }
376}
377
378pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
379 let Some(api) = handle(cx) else {
380 return HashMap::new();
381 };
382 api.read(cx)
383 .proposals
384 .iter()
385 .filter(|(_, entry)| {
386 !entry.proposal.direct && !matches!(entry.status, ProposalStatus::Stale { .. })
387 })
388 .map(|(conversation_id, entry)| {
389 (
390 conversation_id.clone(),
391 agent_label(entry.proposal.agent.as_deref()),
392 )
393 })
394 .collect()
395}
396
397pub fn pending_proposals(cx: &App) -> Vec<PendingProposal> {
398 handle(cx).map_or_else(Vec::new, |api| api.read(cx).pending_proposals())
399}
400
401pub fn unseen_proposal_count(cx: &App) -> usize {
402 pending_proposals(cx)
403 .iter()
404 .filter(|pending| !pending.seen)
405 .count()
406}
407
408pub fn mark_proposal_seen(proposal_id: &str, cx: &mut App) {
409 mark_proposals_seen(cx, |pending| pending.id == proposal_id);
410}
411
412pub fn mark_conversation_proposals_seen(conversation_id: &str, cx: &mut App) {
413 mark_proposals_seen(cx, |pending| pending.conversation_id == conversation_id);
414}
415
416pub fn mark_all_proposals_seen(cx: &mut App) {
417 mark_proposals_seen(cx, |_| true);
418}
419
420fn mark_proposals_seen(cx: &mut App, matches: impl Fn(&PendingProposal) -> bool) {
421 let Some(api) = handle(cx) else {
422 return;
423 };
424 let fresh: Vec<String> = api
425 .read(cx)
426 .pending_proposals()
427 .into_iter()
428 .filter(|pending| !pending.seen && matches(pending))
429 .map(|pending| pending.id)
430 .collect();
431 if fresh.is_empty() {
432 return;
433 }
434 api.update(cx, |api, cx| api.mark_seen(fresh, cx));
435}
436
437pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
438 if let Some(api) = handle(cx) {
439 api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
440 }
441}
442
443pub fn fail_proposal(conversation_id: &str, reason: String, cx: &mut App) {
444 if let Some(api) = handle(cx) {
445 api.update(cx, |api, cx| {
446 if let Some(entry) = api.proposals.get_mut(conversation_id) {
447 entry.status = ProposalStatus::Failed { reason };
448 cx.notify();
449 }
450 });
451 }
452}
453
454pub fn user_typing(conversation_id: &str, cx: &App) {
455 if let Some(api) = handle(cx) {
456 api.read(cx).hub.user_typing(conversation_id);
457 }
458}
459
460pub fn user_sent(conversation_id: &str, cx: &App) {
461 if let Some(api) = handle(cx) {
462 api.read(cx).hub.user_sent(conversation_id);
463 }
464}
465
466pub fn note_caption(meeting_chat_id: &str, caption_id: &str, speaker: &str, text: &str, cx: &App) {
467 let Some(api) = handle(cx) else {
468 return;
469 };
470 let hub = &api.read(cx).hub;
471 let policy = hub.policy();
472 if policy.enabled && policy.transcripts {
473 hub.push_caption(meeting_chat_id, caption_id, speaker, text);
474 }
475}
476
477pub fn clear_captions(meeting_chat_id: &str, cx: &App) {
478 if let Some(api) = handle(cx) {
479 api.read(cx).hub.clear_captions(meeting_chat_id);
480 }
481}
482
483impl AgentApi {
484 pub fn status(&self) -> &ServerStatus {
485 &self.status
486 }
487
488 pub fn token(&self) -> &str {
489 &self.token
490 }
491
492 pub fn regenerate_token(&mut self, cx: &mut Context<Self>) {
493 if let Ok(token) = mcp::regenerate_token(&self.store) {
494 self.token = token;
495 self.reinstall_agent_configs(cx);
496 if self.hub.policy().enabled {
497 self.start_server(cx);
498 }
499 cx.notify();
500 }
501 }
502
503 pub fn pending_proposals(&self) -> Vec<PendingProposal> {
504 pending::collect(
505 &self.proposals,
506 &self.reactions,
507 &self.reaction_excerpts,
508 &self.seen_proposals,
509 )
510 }
511
512 fn mark_seen(&mut self, proposal_ids: Vec<String>, cx: &mut Context<Self>) {
513 self.seen_proposals.extend(proposal_ids);
514 let pending: HashSet<String> = self
515 .pending_proposals()
516 .into_iter()
517 .map(|pending| pending.id)
518 .collect();
519 self.seen_proposals.retain(|id| pending.contains(id));
520 let _ = self.store.set_meta(
521 SEEN_PROPOSALS_KEY,
522 &pending::encode_seen(&self.seen_proposals),
523 );
524 cx.notify();
525 }
526
527 pub fn reinstall_note(&self) -> Option<&str> {
528 self.reinstall_note.as_deref()
529 }
530
531 fn reinstall_agent_configs(&mut self, cx: &mut Context<Self>) {
532 let endpoint = McpEndpoint {
533 url: endpoint_url(self.hub.policy().port),
534 token: self.token.clone(),
535 };
536 let demo = self.demo;
537 let task = cx.background_spawn(async move {
538 mcp::install::reinstall_all(&endpoint, &agent_homes(demo))
539 });
540 cx.spawn(async move |this, cx| {
541 let results = task.await;
542 this.update(cx, |this, cx| {
543 this.reinstall_note = results.into_iter().find_map(|(target, result)| {
544 result
545 .err()
546 .map(|error| format!("Could not update {}: {error}", target.label()))
547 });
548 cx.notify();
549 })
550 .ok();
551 })
552 .detach();
553 }
554
555 pub fn update_policy(&mut self, change: impl FnOnce(&mut AgentPolicy), cx: &mut Context<Self>) {
556 let mut policy = self.hub.policy();
557 let previous_port = policy.port;
558 change(&mut policy);
559 let port_changed = policy.port != previous_port;
560 mcp::save_policy(&self.store, &policy);
561 self.hub.set_policy(policy);
562 self.reconcile(cx);
563 if port_changed {
564 self.reinstall_agent_configs(cx);
565 }
566 cx.notify();
567 }
568
569 fn apply_ui_event(
570 &mut self,
571 event: mcp::UiEvent,
572 pictures: Vec<ProposalPicture>,
573 cx: &mut Context<Self>,
574 ) {
575 if matches!(event, mcp::UiEvent::MeetingProposalsChanged) {
576 let pending = self.hub.pending_meetings();
577 for proposal in meetings::unannounced(&self.announced_meetings, &pending) {
578 meetings::announce(proposal, cx);
579 }
580 self.announced_meetings = pending.into_iter().map(|proposal| proposal.id).collect();
581 }
582 if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event
583 && let Some(excerpt) = pending::reacted_excerpt(
584 &self.store,
585 &reaction.conversation_id,
586 &reaction.message_id,
587 )
588 {
589 self.reaction_excerpts.insert(reaction.id.clone(), excerpt);
590 }
591 bridge::apply(
592 &mut self.proposals,
593 &mut self.reactions,
594 event,
595 pictures,
596 &self.store,
597 );
598 let reactions = &self.reactions;
599 self.reaction_excerpts
600 .retain(|id, _| reactions.values().any(|reaction| &reaction.id == id));
601 cx.notify();
602 }
603
604 fn resolve(&mut self, conversation_id: &str, outcome: Outcome, cx: &mut Context<Self>) {
605 let Some(entry) = self.proposals.remove(conversation_id) else {
606 return;
607 };
608 if !matches!(entry.status, ProposalStatus::Stale { .. }) {
609 self.hub.resolve(&entry.proposal.id, outcome);
610 }
611 cx.notify();
612 }
613
614 fn resolve_reaction(
615 &mut self,
616 conversation_id: &str,
617 message_id: &str,
618 proposal_id: &str,
619 outcome: ReactionOutcome,
620 cx: &mut Context<Self>,
621 ) {
622 let key = (conversation_id.to_owned(), message_id.to_owned());
623 if self
624 .reactions
625 .get(&key)
626 .is_none_or(|reaction| reaction.id != proposal_id)
627 {
628 return;
629 }
630 if let Some(reaction) = self.reactions.remove(&key) {
631 self.hub.resolve_reaction(&reaction.id, outcome);
632 cx.notify();
633 }
634 }
635
636 fn reconcile(&mut self, cx: &mut Context<Self>) {
637 let policy = self.hub.policy();
638 let wanted = policy.enabled;
639 match (wanted, &self.status) {
640 (false, ServerStatus::Off) => {}
641 (false, _) => self.stop_server(cx),
642 (true, ServerStatus::Running(port)) if *port == policy.port => {}
643 (true, _) => self.start_server(cx),
644 }
645 }
646
647 fn stop_server(&mut self, cx: &mut Context<Self>) {
648 self.generation += 1;
649 if let Some(server) = self.server.take() {
650 drop(runtime::spawn(server.shutdown()));
651 }
652 self.status = ServerStatus::Off;
653 cx.notify();
654 }
655
656 fn start_server(&mut self, cx: &mut Context<Self>) {
657 self.generation += 1;
658 let generation = self.generation;
659 let previous = self.server.take();
660 let (hub, source, token) = (self.hub.clone(), self.source.clone(), self.token.clone());
661 let port = self.hub.policy().port;
662 self.status = ServerStatus::Starting;
663 let receiver = runtime::spawn(async move {
664 if let Some(previous) = previous {
665 previous.shutdown().await;
666 }
667 mcp::start(hub, source, port, token).await
668 });
669 cx.spawn(async move |this, cx| {
670 let Ok(result) = receiver.await else {
671 return;
672 };
673 this.update(cx, |this, cx| {
674 this.finish_start(generation, port, result, cx)
675 })
676 .ok();
677 })
678 .detach();
679 cx.notify();
680 }
681
682 fn finish_start(
683 &mut self,
684 generation: u64,
685 port: u16,
686 result: Result<ServerHandle, mcp::ServerError>,
687 cx: &mut Context<Self>,
688 ) {
689 if generation != self.generation {
690 if let Ok(server) = result {
691 drop(runtime::spawn(server.shutdown()));
692 }
693 return;
694 }
695 match result {
696 Ok(server) => {
697 if self.demo {
698 println!("mcp: {} token={}", endpoint_url(port), self.token);
699 }
700 self.server = Some(server);
701 self.status = ServerStatus::Running(port);
702 }
703 Err(mcp::ServerError::PortInUse { port }) => {
704 self.status = ServerStatus::PortInUse(port)
705 }
706 Err(error) => self.status = ServerStatus::Failed(error.to_string()),
707 }
708 cx.notify();
709 }
710}
711
712#[cfg(test)]
713mod tests {
714 use super::{agent_label, demo_port};
715
716 #[test]
717 fn demo_port_is_free_unless_configured() {
718 let picked = demo_port(None);
719 assert_ne!(picked, 0);
720 assert!(std::net::TcpListener::bind(("127.0.0.1", picked)).is_ok());
721 assert_ne!(demo_port(Some("not a port".into())), 0);
722 assert_eq!(demo_port(Some("48000".into())), 48000);
723 }
724
725 #[test]
726 fn agent_labels_know_the_common_agents() {
727 assert_eq!(agent_label(Some("claude")), "Claude");
728 assert_eq!(agent_label(Some("Copilot")), "Copilot");
729 assert_eq!(agent_label(Some("codex")), "Codex");
730 assert_eq!(agent_label(Some("other")), "Agent");
731 assert_eq!(agent_label(None), "Agent");
732 }
733}