BlueGit

ict rusty-teams

Files

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

mod.rs

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