BlueGit

ict rusty-teams

Files

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

mod.rs

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