BlueGit

ict rusty-teams

Files

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

mod.rs

mod.rs 13.0 KiB Download Raw
1mod bridge;
2mod source;
3
4use std::collections::{BTreeSet, HashMap};
5use std::sync::Arc;
6
7use chrono::{DateTime, Local};
8use gpui_kit::*;
9use mcp::install::{Homes, Location};
10use mcp::{Access, AgentHub, AgentPolicy, McpEndpoint, Outcome, Proposal, ServerHandle};
11use store::Store;
12
13use crate::backend::Engine;
14use crate::runtime;
15use source::AppSource;
16
17#[derive(Debug, Clone, PartialEq)]
18pub enum ProposalStatus {
19 Pending,
20 Stale { answered_at: DateTime<Local> },
21 Failed { reason: String },
22}
23
24#[derive(Debug, Clone, PartialEq)]
25pub struct ProposalEntry {
26 pub proposal: Proposal,
27 pub status: ProposalStatus,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum ServerStatus {
32 Off,
33 Starting,
34 Running(u16),
35 PortInUse(u16),
36 Failed(String),
37}
38
39pub struct AgentApi {
40 hub: Arc<AgentHub>,
41 source: Arc<AppSource>,
42 store: Arc<Store>,
43 token: String,
44 proposals: HashMap<String, ProposalEntry>,
45 server: Option<ServerHandle>,
46 status: ServerStatus,
47 generation: u64,
48 reinstall_note: Option<String>,
49 demo: bool,
50}
51
52struct AgentApiHandle(Entity<AgentApi>);
53
54impl Global for AgentApiHandle {}
55
56const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";
57
58pub fn endpoint_url(port: u16) -> String {
59 format!("http://127.0.0.1:{port}/mcp")
60}
61
62fn demo_port(configured: Option<String>) -> u16 {
63 configured
64 .and_then(|value| value.parse().ok())
65 .or_else(|| {
66 std::net::TcpListener::bind(("127.0.0.1", 0))
67 .and_then(|listener| listener.local_addr())
68 .map(|addr| addr.port())
69 .ok()
70 })
71 .unwrap_or_default()
72}
73
74pub fn is_demo(cx: &App) -> bool {
75 handle(cx).is_some_and(|api| api.read(cx).demo)
76}
77
78pub fn agent_homes(demo: bool) -> Homes {
79 if demo {
80 Homes {
81 entries: vec![(
82 Location::Native,
83 std::env::temp_dir().join("rusty-teams-demo-home"),
84 )],
85 }
86 } else {
87 Homes::detect()
88 }
89}
90
91pub fn agent_label(agent: Option<&str>) -> &'static str {
92 match agent.map(str::to_ascii_lowercase).as_deref() {
93 Some("claude") => "Claude",
94 Some("copilot") => "Copilot",
95 Some("codex") => "Codex",
96 _ => "Agent",
97 }
98}
99
100pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
101 let (ui, receiver) = tokio::sync::mpsc::unbounded_channel();
102 let mut policy = mcp::load_policy(&store);
103 if demo {
104 policy.port = demo_port(std::env::var(DEMO_PORT_ENV).ok());
105 }
106 let hub = AgentHub::new(store.clone(), policy, ui);
107 let token = mcp::load_or_create_token(&store).unwrap_or_default();
108 let source = Arc::new(AppSource::new(store.clone()));
109 let api = cx.new(|_| AgentApi {
110 hub,
111 source,
112 store,
113 token,
114 proposals: HashMap::new(),
115 server: None,
116 status: ServerStatus::Off,
117 generation: 0,
118 reinstall_note: None,
119 demo,
120 });
121 bridge::drain_ui_events(receiver, api.downgrade(), cx);
122 api.update(cx, |api, cx| {
123 let _ = api.hub.restore_pending();
124 api.reconcile(cx);
125 });
126 cx.set_global(AgentApiHandle(api));
127}
128
129pub fn engine_ready(engine: Arc<Engine>, cx: &mut App) {
130 let Some(api) = handle(cx) else {
131 return;
132 };
133 let api = api.read(cx);
134 if api.source.set_engine(engine.clone()) {
135 bridge::spawn_message_bridge(engine, api.hub.clone(), api.source.clone());
136 }
137}
138
139pub fn handle(cx: &App) -> Option<Entity<AgentApi>> {
140 cx.try_global::<AgentApiHandle>()
141 .map(|handle| handle.0.clone())
142}
143
144pub fn mcp_endpoint(cx: &App) -> Option<McpEndpoint> {
145 let api = handle(cx)?.read(cx);
146 match api.status {
147 ServerStatus::Running(port) => Some(McpEndpoint {
148 url: endpoint_url(port),
149 token: api.token.clone(),
150 }),
151 _ => None,
152 }
153}
154
155pub fn configured_endpoint(cx: &App) -> Option<McpEndpoint> {
156 let api = handle(cx)?.read(cx);
157 Some(McpEndpoint {
158 url: endpoint_url(api.hub.policy().port),
159 token: api.token.clone(),
160 })
161}
162
163pub fn policy(cx: &App) -> AgentPolicy {
164 handle(cx)
165 .map(|api| api.read(cx).hub.policy())
166 .unwrap_or_default()
167}
168
169pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {
170 let Some(api) = handle(cx) else {
171 return false;
172 };
173 let api = api.read(cx);
174 let policy = api.hub.policy();
175 policy.propose && policy.can_read_any_kind(conversation_id)
176}
177
178pub fn allow_chat(conversation_id: &str, cx: &mut App) {
179 let Some(api) = handle(cx) else {
180 return;
181 };
182 let conversation_id = conversation_id.to_owned();
183 api.update(cx, |api, cx| {
184 let is_channel = api.store.channel(&conversation_id).ok().flatten().is_some();
185 api.update_policy(
186 move |policy| {
187 policy.enabled = true;
188 policy.propose = true;
189 let access = if is_channel {
190 &mut policy.channels
191 } else {
192 &mut policy.chats
193 };
194 match access {
195 Access::All => {}
196 Access::Selected(ids) => {
197 ids.insert(conversation_id);
198 }
199 Access::None => *access = Access::Selected(BTreeSet::from([conversation_id])),
200 }
201 },
202 cx,
203 );
204 });
205}
206
207pub fn update_policy(cx: &mut App, change: impl FnOnce(&mut AgentPolicy)) {
208 if let Some(api) = handle(cx) {
209 api.update(cx, |api, cx| api.update_policy(change, cx));
210 }
211}
212
213pub fn proposal(conversation_id: &str, cx: &App) -> Option<ProposalEntry> {
214 handle(cx)?.read(cx).proposals.get(conversation_id).cloned()
215}
216
217pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
218 let Some(api) = handle(cx) else {
219 return HashMap::new();
220 };
221 api.read(cx)
222 .proposals
223 .iter()
224 .filter(|(_, entry)| !matches!(entry.status, ProposalStatus::Stale { .. }))
225 .map(|(conversation_id, entry)| {
226 (
227 conversation_id.clone(),
228 agent_label(entry.proposal.agent.as_deref()),
229 )
230 })
231 .collect()
232}
233
234pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
235 if let Some(api) = handle(cx) {
236 api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
237 }
238}
239
240pub fn fail_proposal(conversation_id: &str, reason: String, cx: &mut App) {
241 if let Some(api) = handle(cx) {
242 api.update(cx, |api, cx| {
243 if let Some(entry) = api.proposals.get_mut(conversation_id) {
244 entry.status = ProposalStatus::Failed { reason };
245 cx.notify();
246 }
247 });
248 }
249}
250
251pub fn user_typing(conversation_id: &str, cx: &App) {
252 if let Some(api) = handle(cx) {
253 api.read(cx).hub.user_typing(conversation_id);
254 }
255}
256
257pub fn user_sent(conversation_id: &str, cx: &App) {
258 if let Some(api) = handle(cx) {
259 api.read(cx).hub.user_sent(conversation_id);
260 }
261}
262
263pub fn note_caption(meeting_chat_id: &str, caption_id: &str, speaker: &str, text: &str, cx: &App) {
264 let Some(api) = handle(cx) else {
265 return;
266 };
267 let hub = &api.read(cx).hub;
268 let policy = hub.policy();
269 if policy.enabled && policy.transcripts {
270 hub.push_caption(meeting_chat_id, caption_id, speaker, text);
271 }
272}
273
274pub fn clear_captions(meeting_chat_id: &str, cx: &App) {
275 if let Some(api) = handle(cx) {
276 api.read(cx).hub.clear_captions(meeting_chat_id);
277 }
278}
279
280impl AgentApi {
281 pub fn status(&self) -> &ServerStatus {
282 &self.status
283 }
284
285 pub fn token(&self) -> &str {
286 &self.token
287 }
288
289 pub fn regenerate_token(&mut self, cx: &mut Context<Self>) {
290 if let Ok(token) = mcp::regenerate_token(&self.store) {
291 self.token = token;
292 self.reinstall_agent_configs(cx);
293 if self.hub.policy().enabled {
294 self.start_server(cx);
295 }
296 cx.notify();
297 }
298 }
299
300 pub fn reinstall_note(&self) -> Option<&str> {
301 self.reinstall_note.as_deref()
302 }
303
304 fn reinstall_agent_configs(&mut self, cx: &mut Context<Self>) {
305 let endpoint = McpEndpoint {
306 url: endpoint_url(self.hub.policy().port),
307 token: self.token.clone(),
308 };
309 let demo = self.demo;
310 let task = cx.background_spawn(async move {
311 mcp::install::reinstall_all(&endpoint, &agent_homes(demo))
312 });
313 cx.spawn(async move |this, cx| {
314 let results = task.await;
315 this.update(cx, |this, cx| {
316 this.reinstall_note = results.into_iter().find_map(|(target, result)| {
317 result
318 .err()
319 .map(|error| format!("Could not update {}: {error}", target.label()))
320 });
321 cx.notify();
322 })
323 .ok();
324 })
325 .detach();
326 }
327
328 pub fn update_policy(&mut self, change: impl FnOnce(&mut AgentPolicy), cx: &mut Context<Self>) {
329 let mut policy = self.hub.policy();
330 let previous_port = policy.port;
331 change(&mut policy);
332 let port_changed = policy.port != previous_port;
333 mcp::save_policy(&self.store, &policy);
334 self.hub.set_policy(policy);
335 self.reconcile(cx);
336 if port_changed {
337 self.reinstall_agent_configs(cx);
338 }
339 cx.notify();
340 }
341
342 fn apply_ui_event(&mut self, event: mcp::UiEvent, cx: &mut Context<Self>) {
343 bridge::apply(&mut self.proposals, event);
344 cx.notify();
345 }
346
347 fn resolve(&mut self, conversation_id: &str, outcome: Outcome, cx: &mut Context<Self>) {
348 let Some(entry) = self.proposals.remove(conversation_id) else {
349 return;
350 };
351 if !matches!(entry.status, ProposalStatus::Stale { .. }) {
352 self.hub.resolve(&entry.proposal.id, outcome);
353 }
354 cx.notify();
355 }
356
357 fn reconcile(&mut self, cx: &mut Context<Self>) {
358 let policy = self.hub.policy();
359 let wanted = policy.enabled;
360 match (wanted, &self.status) {
361 (false, ServerStatus::Off) => {}
362 (false, _) => self.stop_server(cx),
363 (true, ServerStatus::Running(port)) if *port == policy.port => {}
364 (true, _) => self.start_server(cx),
365 }
366 }
367
368 fn stop_server(&mut self, cx: &mut Context<Self>) {
369 self.generation += 1;
370 if let Some(server) = self.server.take() {
371 drop(runtime::spawn(server.shutdown()));
372 }
373 self.status = ServerStatus::Off;
374 cx.notify();
375 }
376
377 fn start_server(&mut self, cx: &mut Context<Self>) {
378 self.generation += 1;
379 let generation = self.generation;
380 let previous = self.server.take();
381 let (hub, source, token) = (self.hub.clone(), self.source.clone(), self.token.clone());
382 let port = self.hub.policy().port;
383 self.status = ServerStatus::Starting;
384 let receiver = runtime::spawn(async move {
385 if let Some(previous) = previous {
386 previous.shutdown().await;
387 }
388 mcp::start(hub, source, port, token).await
389 });
390 cx.spawn(async move |this, cx| {
391 let Ok(result) = receiver.await else {
392 return;
393 };
394 this.update(cx, |this, cx| {
395 this.finish_start(generation, port, result, cx)
396 })
397 .ok();
398 })
399 .detach();
400 cx.notify();
401 }
402
403 fn finish_start(
404 &mut self,
405 generation: u64,
406 port: u16,
407 result: Result<ServerHandle, mcp::ServerError>,
408 cx: &mut Context<Self>,
409 ) {
410 if generation != self.generation {
411 if let Ok(server) = result {
412 drop(runtime::spawn(server.shutdown()));
413 }
414 return;
415 }
416 match result {
417 Ok(server) => {
418 if self.demo {
419 println!("mcp: {} token={}", endpoint_url(port), self.token);
420 }
421 self.server = Some(server);
422 self.status = ServerStatus::Running(port);
423 }
424 Err(mcp::ServerError::PortInUse { port }) => {
425 self.status = ServerStatus::PortInUse(port)
426 }
427 Err(error) => self.status = ServerStatus::Failed(error.to_string()),
428 }
429 cx.notify();
430 }
431}
432
433#[cfg(test)]
434mod tests {
435 use super::{agent_label, demo_port};
436
437 #[test]
438 fn demo_port_is_free_unless_configured() {
439 let picked = demo_port(None);
440 assert_ne!(picked, 0);
441 assert!(std::net::TcpListener::bind(("127.0.0.1", picked)).is_ok());
442 assert_ne!(demo_port(Some("not a port".into())), 0);
443 assert_eq!(demo_port(Some("48000".into())), 48000);
444 }
445
446 #[test]
447 fn agent_labels_know_the_common_agents() {
448 assert_eq!(agent_label(Some("claude")), "Claude");
449 assert_eq!(agent_label(Some("Copilot")), "Copilot");
450 assert_eq!(agent_label(Some("codex")), "Codex");
451 assert_eq!(agent_label(Some("other")), "Agent");
452 assert_eq!(agent_label(None), "Agent");
453 }
454}