BlueGit

ict rusty-teams

Files

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

mod.rs

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