BlueGit

ict rusty-teams

Files

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

mod.rs

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