1use crate::{
2 AssistantContext, ContextEvent, ContextId, ContextOperation, ContextVersion, SavedContext,
3 SavedContextMetadata,
4};
5use anyhow::{Context as _, Result, anyhow};
6use assistant_slash_command::{SlashCommandId, SlashCommandWorkingSet};
7use client::{Client, TypedEnvelope, proto, telemetry::Telemetry};
8use clock::ReplicaId;
9use collections::HashMap;
10use context_server::ContextServerId;
11use fs::{Fs, RemoveOptions};
12use futures::StreamExt;
13use fuzzy::StringMatchCandidate;
14use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Task, WeakEntity};
15use language::LanguageRegistry;
16use paths::contexts_dir;
17use project::{
18 Project,
19 context_server_store::{ContextServerStatus, ContextServerStore},
20};
21use prompt_store::PromptBuilder;
22use regex::Regex;
23use rpc::AnyProtoClient;
24use std::sync::LazyLock;
25use std::{cmp::Reverse, ffi::OsStr, mem, path::Path, sync::Arc, time::Duration};
26use util::{ResultExt, TryFutureExt};
27
28pub(crate) fn init(client: &AnyProtoClient) {
29 client.add_entity_message_handler(ContextStore::handle_advertise_contexts);
30 client.add_entity_request_handler(ContextStore::handle_open_context);
31 client.add_entity_request_handler(ContextStore::handle_create_context);
32 client.add_entity_message_handler(ContextStore::handle_update_context);
33 client.add_entity_request_handler(ContextStore::handle_synchronize_contexts);
34}
35
36#[derive(Clone)]
37pub struct RemoteContextMetadata {
38 pub id: ContextId,
39 pub summary: Option<String>,
40}
41
42pub struct ContextStore {
43 contexts: Vec<ContextHandle>,
44 contexts_metadata: Vec<SavedContextMetadata>,
45 context_server_slash_command_ids: HashMap<ContextServerId, Vec<SlashCommandId>>,
46 host_contexts: Vec<RemoteContextMetadata>,
47 fs: Arc<dyn Fs>,
48 languages: Arc<LanguageRegistry>,
49 slash_commands: Arc<SlashCommandWorkingSet>,
50 telemetry: Arc<Telemetry>,
51 _watch_updates: Task<Option<()>>,
52 client: Arc<Client>,
53 project: Entity<Project>,
54 project_is_shared: bool,
55 client_subscription: Option<client::Subscription>,
56 _project_subscriptions: Vec<gpui::Subscription>,
57 prompt_builder: Arc<PromptBuilder>,
58}
59
60pub enum ContextStoreEvent {
61 ContextCreated(ContextId),
62}
63
64impl EventEmitter<ContextStoreEvent> for ContextStore {}
65
66enum ContextHandle {
67 Weak(WeakEntity<AssistantContext>),
68 Strong(Entity<AssistantContext>),
69}
70
71impl ContextHandle {
72 fn upgrade(&self) -> Option<Entity<AssistantContext>> {
73 match self {
74 ContextHandle::Weak(weak) => weak.upgrade(),
75 ContextHandle::Strong(strong) => Some(strong.clone()),
76 }
77 }
78
79 fn downgrade(&self) -> WeakEntity<AssistantContext> {
80 match self {
81 ContextHandle::Weak(weak) => weak.clone(),
82 ContextHandle::Strong(strong) => strong.downgrade(),
83 }
84 }
85}
86
87impl ContextStore {
88 pub fn new(
89 project: Entity<Project>,
90 prompt_builder: Arc<PromptBuilder>,
91 slash_commands: Arc<SlashCommandWorkingSet>,
92 cx: &mut App,
93 ) -> Task<Result<Entity<Self>>> {
94 let fs = project.read(cx).fs().clone();
95 let languages = project.read(cx).languages().clone();
96 let telemetry = project.read(cx).client().telemetry().clone();
97 cx.spawn(async move |cx| {
98 const CONTEXT_WATCH_DURATION: Duration = Duration::from_millis(100);
99 let (mut events, _) = fs.watch(contexts_dir(), CONTEXT_WATCH_DURATION).await;
100
101 let this = cx.new(|cx: &mut Context<Self>| {
102 let mut this = Self {
103 contexts: Vec::new(),
104 contexts_metadata: Vec::new(),
105 context_server_slash_command_ids: HashMap::default(),
106 host_contexts: Vec::new(),
107 fs,
108 languages,
109 slash_commands,
110 telemetry,
111 _watch_updates: cx.spawn(async move |this, cx| {
112 async move {
113 while events.next().await.is_some() {
114 this.update(cx, |this, cx| this.reload(cx))?.await.log_err();
115 }
116 anyhow::Ok(())
117 }
118 .log_err()
119 .await
120 }),
121 client_subscription: None,
122 _project_subscriptions: vec![
123 cx.subscribe(&project, Self::handle_project_event),
124 ],
125 project_is_shared: false,
126 client: project.read(cx).client(),
127 project: project.clone(),
128 prompt_builder,
129 };
130 this.handle_project_shared(project.clone(), cx);
131 this.synchronize_contexts(cx);
132 this.register_context_server_handlers(cx);
133 this.reload(cx).detach_and_log_err(cx);
134 this
135 })?;
136
137 Ok(this)
138 })
139 }
140
141 async fn handle_advertise_contexts(
142 this: Entity<Self>,
143 envelope: TypedEnvelope<proto::AdvertiseContexts>,
144 mut cx: AsyncApp,
145 ) -> Result<()> {
146 this.update(&mut cx, |this, cx| {
147 this.host_contexts = envelope
148 .payload
149 .contexts
150 .into_iter()
151 .map(|context| RemoteContextMetadata {
152 id: ContextId::from_proto(context.context_id),
153 summary: context.summary,
154 })
155 .collect();
156 cx.notify();
157 })
158 }
159
160 async fn handle_open_context(
161 this: Entity<Self>,
162 envelope: TypedEnvelope<proto::OpenContext>,
163 mut cx: AsyncApp,
164 ) -> Result<proto::OpenContextResponse> {
165 let context_id = ContextId::from_proto(envelope.payload.context_id);
166 let operations = this.update(&mut cx, |this, cx| {
167 if this.project.read(cx).is_via_collab() {
168 return Err(anyhow!("only the host contexts can be opened"));
169 }
170
171 let context = this
172 .loaded_context_for_id(&context_id, cx)
173 .context("context not found")?;
174 if context.read(cx).replica_id() != ReplicaId::default() {
175 return Err(anyhow!("context must be opened via the host"));
176 }
177
178 anyhow::Ok(
179 context
180 .read(cx)
181 .serialize_ops(&ContextVersion::default(), cx),
182 )
183 })??;
184 let operations = operations.await;
185 Ok(proto::OpenContextResponse {
186 context: Some(proto::Context { operations }),
187 })
188 }
189
190 async fn handle_create_context(
191 this: Entity<Self>,
192 _: TypedEnvelope<proto::CreateContext>,
193 mut cx: AsyncApp,
194 ) -> Result<proto::CreateContextResponse> {
195 let (context_id, operations) = this.update(&mut cx, |this, cx| {
196 if this.project.read(cx).is_via_collab() {
197 return Err(anyhow!("can only create contexts as the host"));
198 }
199
200 let context = this.create(cx);
201 let context_id = context.read(cx).id().clone();
202 cx.emit(ContextStoreEvent::ContextCreated(context_id.clone()));
203
204 anyhow::Ok((
205 context_id,
206 context
207 .read(cx)
208 .serialize_ops(&ContextVersion::default(), cx),
209 ))
210 })??;
211 let operations = operations.await;
212 Ok(proto::CreateContextResponse {
213 context_id: context_id.to_proto(),
214 context: Some(proto::Context { operations }),
215 })
216 }
217
218 async fn handle_update_context(
219 this: Entity<Self>,
220 envelope: TypedEnvelope<proto::UpdateContext>,
221 mut cx: AsyncApp,
222 ) -> Result<()> {
223 this.update(&mut cx, |this, cx| {
224 let context_id = ContextId::from_proto(envelope.payload.context_id);
225 if let Some(context) = this.loaded_context_for_id(&context_id, cx) {
226 let operation_proto = envelope.payload.operation.context("invalid operation")?;
227 let operation = ContextOperation::from_proto(operation_proto)?;
228 context.update(cx, |context, cx| context.apply_ops([operation], cx));
229 }
230 Ok(())
231 })?
232 }
233
234 async fn handle_synchronize_contexts(
235 this: Entity<Self>,
236 envelope: TypedEnvelope<proto::SynchronizeContexts>,
237 mut cx: AsyncApp,
238 ) -> Result<proto::SynchronizeContextsResponse> {
239 this.update(&mut cx, |this, cx| {
240 if this.project.read(cx).is_via_collab() {
241 return Err(anyhow!("only the host can synchronize contexts"));
242 }
243
244 let mut local_versions = Vec::new();
245 for remote_version_proto in envelope.payload.contexts {
246 let remote_version = ContextVersion::from_proto(&remote_version_proto);
247 let context_id = ContextId::from_proto(remote_version_proto.context_id);
248 if let Some(context) = this.loaded_context_for_id(&context_id, cx) {
249 let context = context.read(cx);
250 let operations = context.serialize_ops(&remote_version, cx);
251 local_versions.push(context.version(cx).to_proto(context_id.clone()));
252 let client = this.client.clone();
253 let project_id = envelope.payload.project_id;
254 cx.background_spawn(async move {
255 let operations = operations.await;
256 for operation in operations {
257 client.send(proto::UpdateContext {
258 project_id,
259 context_id: context_id.to_proto(),
260 operation: Some(operation),
261 })?;
262 }
263 anyhow::Ok(())
264 })
265 .detach_and_log_err(cx);
266 }
267 }
268
269 this.advertise_contexts(cx);
270
271 anyhow::Ok(proto::SynchronizeContextsResponse {
272 contexts: local_versions,
273 })
274 })?
275 }
276
277 fn handle_project_shared(&mut self, _: Entity<Project>, cx: &mut Context<Self>) {
278 let is_shared = self.project.read(cx).is_shared();
279 let was_shared = mem::replace(&mut self.project_is_shared, is_shared);
280 if is_shared == was_shared {
281 return;
282 }
283
284 if is_shared {
285 self.contexts.retain_mut(|context| {
286 if let Some(strong_context) = context.upgrade() {
287 *context = ContextHandle::Strong(strong_context);
288 true
289 } else {
290 false
291 }
292 });
293 let remote_id = self.project.read(cx).remote_id().unwrap();
294 self.client_subscription = self
295 .client
296 .subscribe_to_entity(remote_id)
297 .log_err()
298 .map(|subscription| subscription.set_entity(&cx.entity(), &mut cx.to_async()));
299 self.advertise_contexts(cx);
300 } else {
301 self.client_subscription = None;
302 }
303 }
304
305 fn handle_project_event(
306 &mut self,
307 project: Entity<Project>,
308 event: &project::Event,
309 cx: &mut Context<Self>,
310 ) {
311 match event {
312 project::Event::RemoteIdChanged(_) => {
313 self.handle_project_shared(project, cx);
314 }
315 project::Event::Reshared => {
316 self.advertise_contexts(cx);
317 }
318 project::Event::HostReshared | project::Event::Rejoined => {
319 self.synchronize_contexts(cx);
320 }
321 project::Event::DisconnectedFromHost => {
322 self.contexts.retain_mut(|context| {
323 if let Some(strong_context) = context.upgrade() {
324 *context = ContextHandle::Weak(context.downgrade());
325 strong_context.update(cx, |context, cx| {
326 if context.replica_id() != ReplicaId::default() {
327 context.set_capability(language::Capability::ReadOnly, cx);
328 }
329 });
330 true
331 } else {
332 false
333 }
334 });
335 self.host_contexts.clear();
336 cx.notify();
337 }
338 _ => {}
339 }
340 }
341
342 pub fn contexts(&self) -> Vec<SavedContextMetadata> {
343 let mut contexts = self.contexts_metadata.iter().cloned().collect::<Vec<_>>();
344 contexts.sort_unstable_by_key(|thread| std::cmp::Reverse(thread.mtime));
345 contexts
346 }
347
348 pub fn create(&mut self, cx: &mut Context<Self>) -> Entity<AssistantContext> {
349 let context = cx.new(|cx| {
350 AssistantContext::local(
351 self.languages.clone(),
352 Some(self.project.clone()),
353 Some(self.telemetry.clone()),
354 self.prompt_builder.clone(),
355 self.slash_commands.clone(),
356 cx,
357 )
358 });
359 self.register_context(&context, cx);
360 context
361 }
362
363 pub fn create_remote_context(
364 &mut self,
365 cx: &mut Context<Self>,
366 ) -> Task<Result<Entity<AssistantContext>>> {
367 let project = self.project.read(cx);
368 let Some(project_id) = project.remote_id() else {
369 return Task::ready(Err(anyhow!("project was not remote")));
370 };
371
372 let replica_id = project.replica_id();
373 let capability = project.capability();
374 let language_registry = self.languages.clone();
375 let project = self.project.clone();
376 let telemetry = self.telemetry.clone();
377 let prompt_builder = self.prompt_builder.clone();
378 let slash_commands = self.slash_commands.clone();
379 let request = self.client.request(proto::CreateContext { project_id });
380 cx.spawn(async move |this, cx| {
381 let response = request.await?;
382 let context_id = ContextId::from_proto(response.context_id);
383 let context_proto = response.context.context("invalid context")?;
384 let context = cx.new(|cx| {
385 AssistantContext::new(
386 context_id.clone(),
387 replica_id,
388 capability,
389 language_registry,
390 prompt_builder,
391 slash_commands,
392 Some(project),
393 Some(telemetry),
394 cx,
395 )
396 })?;
397 let operations = cx
398 .background_spawn(async move {
399 context_proto
400 .operations
401 .into_iter()
402 .map(ContextOperation::from_proto)
403 .collect::<Result<Vec<_>>>()
404 })
405 .await?;
406 context.update(cx, |context, cx| context.apply_ops(operations, cx))?;
407 this.update(cx, |this, cx| {
408 if let Some(existing_context) = this.loaded_context_for_id(&context_id, cx) {
409 existing_context
410 } else {
411 this.register_context(&context, cx);
412 this.synchronize_contexts(cx);
413 context
414 }
415 })
416 })
417 }
418
419 pub fn open_local_context(
420 &mut self,
421 path: Arc<Path>,
422 cx: &Context<Self>,
423 ) -> Task<Result<Entity<AssistantContext>>> {
424 if let Some(existing_context) = self.loaded_context_for_path(&path, cx) {
425 return Task::ready(Ok(existing_context));
426 }
427
428 let fs = self.fs.clone();
429 let languages = self.languages.clone();
430 let project = self.project.clone();
431 let telemetry = self.telemetry.clone();
432 let load = cx.background_spawn({
433 let path = path.clone();
434 async move {
435 let saved_context = fs.load(&path).await?;
436 SavedContext::from_json(&saved_context)
437 }
438 });
439 let prompt_builder = self.prompt_builder.clone();
440 let slash_commands = self.slash_commands.clone();
441
442 cx.spawn(async move |this, cx| {
443 let saved_context = load.await?;
444 let context = cx.new(|cx| {
445 AssistantContext::deserialize(
446 saved_context,
447 path.clone(),
448 languages,
449 prompt_builder,
450 slash_commands,
451 Some(project),
452 Some(telemetry),
453 cx,
454 )
455 })?;
456 this.update(cx, |this, cx| {
457 if let Some(existing_context) = this.loaded_context_for_path(&path, cx) {
458 existing_context
459 } else {
460 this.register_context(&context, cx);
461 context
462 }
463 })
464 })
465 }
466
467 pub fn delete_local_context(
468 &mut self,
469 path: Arc<Path>,
470 cx: &mut Context<Self>,
471 ) -> Task<Result<()>> {
472 let fs = self.fs.clone();
473
474 cx.spawn(async move |this, cx| {
475 fs.remove_file(
476 &path,
477 RemoveOptions {
478 recursive: false,
479 ignore_if_not_exists: true,
480 },
481 )
482 .await?;
483
484 this.update(cx, |this, cx| {
485 this.contexts.retain(|context| {
486 context
487 .upgrade()
488 .and_then(|context| context.read(cx).path())
489 != Some(&path)
490 });
491 this.contexts_metadata
492 .retain(|context| context.path.as_ref() != path.as_ref());
493 })?;
494
495 Ok(())
496 })
497 }
498
499 fn loaded_context_for_path(&self, path: &Path, cx: &App) -> Option<Entity<AssistantContext>> {
500 self.contexts.iter().find_map(|context| {
501 let context = context.upgrade()?;
502 if context.read(cx).path().map(Arc::as_ref) == Some(path) {
503 Some(context)
504 } else {
505 None
506 }
507 })
508 }
509
510 pub fn loaded_context_for_id(
511 &self,
512 id: &ContextId,
513 cx: &App,
514 ) -> Option<Entity<AssistantContext>> {
515 self.contexts.iter().find_map(|context| {
516 let context = context.upgrade()?;
517 if context.read(cx).id() == id {
518 Some(context)
519 } else {
520 None
521 }
522 })
523 }
524
525 pub fn open_remote_context(
526 &mut self,
527 context_id: ContextId,
528 cx: &mut Context<Self>,
529 ) -> Task<Result<Entity<AssistantContext>>> {
530 let project = self.project.read(cx);
531 let Some(project_id) = project.remote_id() else {
532 return Task::ready(Err(anyhow!("project was not remote")));
533 };
534
535 if let Some(context) = self.loaded_context_for_id(&context_id, cx) {
536 return Task::ready(Ok(context));
537 }
538
539 let replica_id = project.replica_id();
540 let capability = project.capability();
541 let language_registry = self.languages.clone();
542 let project = self.project.clone();
543 let telemetry = self.telemetry.clone();
544 let request = self.client.request(proto::OpenContext {
545 project_id,
546 context_id: context_id.to_proto(),
547 });
548 let prompt_builder = self.prompt_builder.clone();
549 let slash_commands = self.slash_commands.clone();
550 cx.spawn(async move |this, cx| {
551 let response = request.await?;
552 let context_proto = response.context.context("invalid context")?;
553 let context = cx.new(|cx| {
554 AssistantContext::new(
555 context_id.clone(),
556 replica_id,
557 capability,
558 language_registry,
559 prompt_builder,
560 slash_commands,
561 Some(project),
562 Some(telemetry),
563 cx,
564 )
565 })?;
566 let operations = cx
567 .background_spawn(async move {
568 context_proto
569 .operations
570 .into_iter()
571 .map(ContextOperation::from_proto)
572 .collect::<Result<Vec<_>>>()
573 })
574 .await?;
575 context.update(cx, |context, cx| context.apply_ops(operations, cx))?;
576 this.update(cx, |this, cx| {
577 if let Some(existing_context) = this.loaded_context_for_id(&context_id, cx) {
578 existing_context
579 } else {
580 this.register_context(&context, cx);
581 this.synchronize_contexts(cx);
582 context
583 }
584 })
585 })
586 }
587
588 fn register_context(&mut self, context: &Entity<AssistantContext>, cx: &mut Context<Self>) {
589 let handle = if self.project_is_shared {
590 ContextHandle::Strong(context.clone())
591 } else {
592 ContextHandle::Weak(context.downgrade())
593 };
594 self.contexts.push(handle);
595 self.advertise_contexts(cx);
596 cx.subscribe(context, Self::handle_context_event).detach();
597 }
598
599 fn handle_context_event(
600 &mut self,
601 context: Entity<AssistantContext>,
602 event: &ContextEvent,
603 cx: &mut Context<Self>,
604 ) {
605 let Some(project_id) = self.project.read(cx).remote_id() else {
606 return;
607 };
608
609 match event {
610 ContextEvent::SummaryChanged => {
611 self.advertise_contexts(cx);
612 }
613 ContextEvent::Operation(operation) => {
614 let context_id = context.read(cx).id().to_proto();
615 let operation = operation.to_proto();
616 self.client
617 .send(proto::UpdateContext {
618 project_id,
619 context_id,
620 operation: Some(operation),
621 })
622 .log_err();
623 }
624 _ => {}
625 }
626 }
627
628 fn advertise_contexts(&self, cx: &App) {
629 let Some(project_id) = self.project.read(cx).remote_id() else {
630 return;
631 };
632
633 // For now, only the host can advertise their open contexts.
634 if self.project.read(cx).is_via_collab() {
635 return;
636 }
637
638 let contexts = self
639 .contexts
640 .iter()
641 .rev()
642 .filter_map(|context| {
643 let context = context.upgrade()?.read(cx);
644 if context.replica_id() == ReplicaId::default() {
645 Some(proto::ContextMetadata {
646 context_id: context.id().to_proto(),
647 summary: context.summary().map(|summary| summary.text.clone()),
648 })
649 } else {
650 None
651 }
652 })
653 .collect();
654 self.client
655 .send(proto::AdvertiseContexts {
656 project_id,
657 contexts,
658 })
659 .ok();
660 }
661
662 fn synchronize_contexts(&mut self, cx: &mut Context<Self>) {
663 let Some(project_id) = self.project.read(cx).remote_id() else {
664 return;
665 };
666
667 let contexts = self
668 .contexts
669 .iter()
670 .filter_map(|context| {
671 let context = context.upgrade()?.read(cx);
672 if context.replica_id() != ReplicaId::default() {
673 Some(context.version(cx).to_proto(context.id().clone()))
674 } else {
675 None
676 }
677 })
678 .collect();
679
680 let client = self.client.clone();
681 let request = self.client.request(proto::SynchronizeContexts {
682 project_id,
683 contexts,
684 });
685 cx.spawn(async move |this, cx| {
686 let response = request.await?;
687
688 let mut context_ids = Vec::new();
689 let mut operations = Vec::new();
690 this.read_with(cx, |this, cx| {
691 for context_version_proto in response.contexts {
692 let context_version = ContextVersion::from_proto(&context_version_proto);
693 let context_id = ContextId::from_proto(context_version_proto.context_id);
694 if let Some(context) = this.loaded_context_for_id(&context_id, cx) {
695 context_ids.push(context_id);
696 operations.push(context.read(cx).serialize_ops(&context_version, cx));
697 }
698 }
699 })?;
700
701 let operations = futures::future::join_all(operations).await;
702 for (context_id, operations) in context_ids.into_iter().zip(operations) {
703 for operation in operations {
704 client.send(proto::UpdateContext {
705 project_id,
706 context_id: context_id.to_proto(),
707 operation: Some(operation),
708 })?;
709 }
710 }
711
712 anyhow::Ok(())
713 })
714 .detach_and_log_err(cx);
715 }
716
717 pub fn search(&self, query: String, cx: &App) -> Task<Vec<SavedContextMetadata>> {
718 let metadata = self.contexts_metadata.clone();
719 let executor = cx.background_executor().clone();
720 cx.background_spawn(async move {
721 if query.is_empty() {
722 metadata
723 } else {
724 let candidates = metadata
725 .iter()
726 .enumerate()
727 .map(|(id, metadata)| StringMatchCandidate::new(id, &metadata.title))
728 .collect::<Vec<_>>();
729 let matches = fuzzy::match_strings(
730 &candidates,
731 &query,
732 false,
733 100,
734 &Default::default(),
735 executor,
736 )
737 .await;
738
739 matches
740 .into_iter()
741 .map(|mat| metadata[mat.candidate_id].clone())
742 .collect()
743 }
744 })
745 }
746
747 pub fn host_contexts(&self) -> &[RemoteContextMetadata] {
748 &self.host_contexts
749 }
750
751 fn reload(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
752 let fs = self.fs.clone();
753 cx.spawn(async move |this, cx| {
754 fs.create_dir(contexts_dir()).await?;
755
756 let mut paths = fs.read_dir(contexts_dir()).await?;
757 let mut contexts = Vec::<SavedContextMetadata>::new();
758 while let Some(path) = paths.next().await {
759 let path = path?;
760 if path.extension() != Some(OsStr::new("json")) {
761 continue;
762 }
763
764 static ASSISTANT_CONTEXT_REGEX: LazyLock<Regex> =
765 LazyLock::new(|| Regex::new(r" - \d+.zed.json$").unwrap());
766
767 let metadata = fs.metadata(&path).await?;
768 if let Some((file_name, metadata)) = path
769 .file_name()
770 .and_then(|name| name.to_str())
771 .zip(metadata)
772 {
773 // This is used to filter out contexts saved by the new assistant.
774 if !ASSISTANT_CONTEXT_REGEX.is_match(file_name) {
775 continue;
776 }
777
778 if let Some(title) = ASSISTANT_CONTEXT_REGEX
779 .replace(file_name, "")
780 .lines()
781 .next()
782 {
783 contexts.push(SavedContextMetadata {
784 title: title.to_string(),
785 path: path.into(),
786 mtime: metadata.mtime.timestamp_for_user().into(),
787 });
788 }
789 }
790 }
791 contexts.sort_unstable_by_key(|context| Reverse(context.mtime));
792
793 this.update(cx, |this, cx| {
794 this.contexts_metadata = contexts;
795 cx.notify();
796 })
797 })
798 }
799
800 fn register_context_server_handlers(&self, cx: &mut Context<Self>) {
801 cx.subscribe(
802 &self.project.read(cx).context_server_store(),
803 Self::handle_context_server_event,
804 )
805 .detach();
806 }
807
808 fn handle_context_server_event(
809 &mut self,
810 context_server_manager: Entity<ContextServerStore>,
811 event: &project::context_server_store::Event,
812 cx: &mut Context<Self>,
813 ) {
814 let slash_command_working_set = self.slash_commands.clone();
815 match event {
816 project::context_server_store::Event::ServerStatusChanged { server_id, status } => {
817 match status {
818 ContextServerStatus::Running => {
819 if let Some(server) = context_server_manager
820 .read(cx)
821 .get_running_server(server_id)
822 {
823 let context_server_manager = context_server_manager.clone();
824 cx.spawn({
825 let server = server.clone();
826 let server_id = server_id.clone();
827 async move |this, cx| {
828 let Some(protocol) = server.client() else {
829 return;
830 };
831
832 if protocol.capable(context_server::protocol::ServerCapability::Prompts) {
833 if let Some(prompts) = protocol.list_prompts().await.log_err() {
834 let slash_command_ids = prompts
835 .into_iter()
836 .filter(assistant_slash_commands::acceptable_prompt)
837 .map(|prompt| {
838 log::info!(
839 "registering context server command: {:?}",
840 prompt.name
841 );
842 slash_command_working_set.insert(Arc::new(
843 assistant_slash_commands::ContextServerSlashCommand::new(
844 context_server_manager.clone(),
845 server.id(),
846 prompt,
847 ),
848 ))
849 })
850 .collect::<Vec<_>>();
851
852 this.update( cx, |this, _cx| {
853 this.context_server_slash_command_ids
854 .insert(server_id.clone(), slash_command_ids);
855 })
856 .log_err();
857 }
858 }
859 }
860 })
861 .detach();
862 }
863 }
864 ContextServerStatus::Stopped | ContextServerStatus::Error(_) => {
865 if let Some(slash_command_ids) =
866 self.context_server_slash_command_ids.remove(server_id)
867 {
868 slash_command_working_set.remove(&slash_command_ids);
869 }
870 }
871 _ => {}
872 }
873 }
874 }
875 }
876}