context_store.rs

  1use std::ops::Range;
  2use std::path::{Path, PathBuf};
  3use std::sync::Arc;
  4
  5use anyhow::{Context as _, Result, anyhow};
  6use assistant_context_editor::AssistantContext;
  7use collections::{HashSet, IndexSet};
  8use futures::{self, FutureExt};
  9use gpui::{App, Context, Entity, EventEmitter, Image, SharedString, Task, WeakEntity};
 10use language::Buffer;
 11use language_model::LanguageModelImage;
 12use project::image_store::is_image_file;
 13use project::{Project, ProjectItem, ProjectPath, Symbol};
 14use prompt_store::UserPromptId;
 15use ref_cast::RefCast as _;
 16use text::{Anchor, OffsetRangeExt};
 17
 18use crate::ThreadStore;
 19use crate::context::{
 20    AgentContextHandle, AgentContextKey, ContextId, DirectoryContextHandle, FetchedUrlContext,
 21    FileContextHandle, ImageContext, RulesContextHandle, SelectionContextHandle,
 22    SymbolContextHandle, TextThreadContextHandle, ThreadContextHandle,
 23};
 24use crate::context_strip::SuggestedContext;
 25use crate::thread::{MessageId, Thread, ThreadId};
 26
 27pub struct ContextStore {
 28    project: WeakEntity<Project>,
 29    thread_store: Option<WeakEntity<ThreadStore>>,
 30    next_context_id: ContextId,
 31    context_set: IndexSet<AgentContextKey>,
 32    context_thread_ids: HashSet<ThreadId>,
 33    context_text_thread_paths: HashSet<Arc<Path>>,
 34}
 35
 36pub enum ContextStoreEvent {
 37    ContextRemoved(AgentContextKey),
 38}
 39
 40impl EventEmitter<ContextStoreEvent> for ContextStore {}
 41
 42impl ContextStore {
 43    pub fn new(
 44        project: WeakEntity<Project>,
 45        thread_store: Option<WeakEntity<ThreadStore>>,
 46    ) -> Self {
 47        Self {
 48            project,
 49            thread_store,
 50            next_context_id: ContextId::zero(),
 51            context_set: IndexSet::default(),
 52            context_thread_ids: HashSet::default(),
 53            context_text_thread_paths: HashSet::default(),
 54        }
 55    }
 56
 57    pub fn context(&self) -> impl Iterator<Item = &AgentContextHandle> {
 58        self.context_set.iter().map(|entry| entry.as_ref())
 59    }
 60
 61    pub fn clear(&mut self, cx: &mut Context<Self>) {
 62        self.context_set.clear();
 63        self.context_thread_ids.clear();
 64        cx.notify();
 65    }
 66
 67    pub fn new_context_for_thread(
 68        &self,
 69        thread: &Thread,
 70        exclude_messages_from_id: Option<MessageId>,
 71    ) -> Vec<AgentContextHandle> {
 72        let existing_context = thread
 73            .messages()
 74            .take_while(|message| exclude_messages_from_id.is_none_or(|id| message.id != id))
 75            .flat_map(|message| {
 76                message
 77                    .loaded_context
 78                    .contexts
 79                    .iter()
 80                    .map(|context| AgentContextKey(context.handle()))
 81            })
 82            .collect::<HashSet<_>>();
 83        self.context_set
 84            .iter()
 85            .filter(|context| !existing_context.contains(context))
 86            .map(|entry| entry.0.clone())
 87            .collect::<Vec<_>>()
 88    }
 89
 90    pub fn add_file_from_path(
 91        &mut self,
 92        project_path: ProjectPath,
 93        remove_if_exists: bool,
 94        cx: &mut Context<Self>,
 95    ) -> Task<Result<Option<AgentContextHandle>>> {
 96        let Some(project) = self.project.upgrade() else {
 97            return Task::ready(Err(anyhow!("failed to read project")));
 98        };
 99
100        if is_image_file(&project, &project_path, cx) {
101            self.add_image_from_path(project_path, remove_if_exists, cx)
102        } else {
103            cx.spawn(async move |this, cx| {
104                let open_buffer_task = project.update(cx, |project, cx| {
105                    project.open_buffer(project_path.clone(), cx)
106                })?;
107                let buffer = open_buffer_task.await?;
108                this.update(cx, |this, cx| {
109                    this.add_file_from_buffer(&project_path, buffer, remove_if_exists, cx)
110                })
111            })
112        }
113    }
114
115    pub fn add_file_from_buffer(
116        &mut self,
117        project_path: &ProjectPath,
118        buffer: Entity<Buffer>,
119        remove_if_exists: bool,
120        cx: &mut Context<Self>,
121    ) -> Option<AgentContextHandle> {
122        let context_id = self.next_context_id.post_inc();
123        let context = AgentContextHandle::File(FileContextHandle { buffer, context_id });
124
125        if let Some(key) = self.context_set.get(AgentContextKey::ref_cast(&context)) {
126            if remove_if_exists {
127                self.remove_context(&context, cx);
128                None
129            } else {
130                Some(key.as_ref().clone())
131            }
132        } else if self.path_included_in_directory(project_path, cx).is_some() {
133            None
134        } else {
135            self.insert_context(context.clone(), cx);
136            Some(context)
137        }
138    }
139
140    pub fn add_directory(
141        &mut self,
142        project_path: &ProjectPath,
143        remove_if_exists: bool,
144        cx: &mut Context<Self>,
145    ) -> Result<Option<AgentContextHandle>> {
146        let project = self.project.upgrade().context("failed to read project")?;
147        let entry_id = project
148            .read(cx)
149            .entry_for_path(project_path, cx)
150            .map(|entry| entry.id)
151            .context("no entry found for directory context")?;
152
153        let context_id = self.next_context_id.post_inc();
154        let context = AgentContextHandle::Directory(DirectoryContextHandle {
155            entry_id,
156            context_id,
157        });
158
159        let context =
160            if let Some(existing) = self.context_set.get(AgentContextKey::ref_cast(&context)) {
161                if remove_if_exists {
162                    self.remove_context(&context, cx);
163                    None
164                } else {
165                    Some(existing.as_ref().clone())
166                }
167            } else {
168                self.insert_context(context.clone(), cx);
169                Some(context)
170            };
171
172        anyhow::Ok(context)
173    }
174
175    pub fn add_symbol(
176        &mut self,
177        buffer: Entity<Buffer>,
178        symbol: SharedString,
179        range: Range<Anchor>,
180        enclosing_range: Range<Anchor>,
181        remove_if_exists: bool,
182        cx: &mut Context<Self>,
183    ) -> (Option<AgentContextHandle>, bool) {
184        let context_id = self.next_context_id.post_inc();
185        let context = AgentContextHandle::Symbol(SymbolContextHandle {
186            buffer,
187            symbol,
188            range,
189            enclosing_range,
190            context_id,
191        });
192
193        if let Some(key) = self.context_set.get(AgentContextKey::ref_cast(&context)) {
194            let handle = if remove_if_exists {
195                self.remove_context(&context, cx);
196                None
197            } else {
198                Some(key.as_ref().clone())
199            };
200            return (handle, false);
201        }
202
203        let included = self.insert_context(context.clone(), cx);
204        (Some(context), included)
205    }
206
207    pub fn add_thread(
208        &mut self,
209        thread: Entity<Thread>,
210        remove_if_exists: bool,
211        cx: &mut Context<Self>,
212    ) -> Option<AgentContextHandle> {
213        let context_id = self.next_context_id.post_inc();
214        let context = AgentContextHandle::Thread(ThreadContextHandle { thread, context_id });
215
216        if let Some(existing) = self.context_set.get(AgentContextKey::ref_cast(&context)) {
217            if remove_if_exists {
218                self.remove_context(&context, cx);
219                None
220            } else {
221                Some(existing.as_ref().clone())
222            }
223        } else {
224            self.insert_context(context.clone(), cx);
225            Some(context)
226        }
227    }
228
229    pub fn add_text_thread(
230        &mut self,
231        context: Entity<AssistantContext>,
232        remove_if_exists: bool,
233        cx: &mut Context<Self>,
234    ) -> Option<AgentContextHandle> {
235        let context_id = self.next_context_id.post_inc();
236        let context = AgentContextHandle::TextThread(TextThreadContextHandle {
237            context,
238            context_id,
239        });
240
241        if let Some(existing) = self.context_set.get(AgentContextKey::ref_cast(&context)) {
242            if remove_if_exists {
243                self.remove_context(&context, cx);
244                None
245            } else {
246                Some(existing.as_ref().clone())
247            }
248        } else {
249            self.insert_context(context.clone(), cx);
250            Some(context)
251        }
252    }
253
254    pub fn add_rules(
255        &mut self,
256        prompt_id: UserPromptId,
257        remove_if_exists: bool,
258        cx: &mut Context<ContextStore>,
259    ) -> Option<AgentContextHandle> {
260        let context_id = self.next_context_id.post_inc();
261        let context = AgentContextHandle::Rules(RulesContextHandle {
262            prompt_id,
263            context_id,
264        });
265
266        if let Some(existing) = self.context_set.get(AgentContextKey::ref_cast(&context)) {
267            if remove_if_exists {
268                self.remove_context(&context, cx);
269                None
270            } else {
271                Some(existing.as_ref().clone())
272            }
273        } else {
274            self.insert_context(context.clone(), cx);
275            Some(context)
276        }
277    }
278
279    pub fn add_fetched_url(
280        &mut self,
281        url: String,
282        text: impl Into<SharedString>,
283        cx: &mut Context<ContextStore>,
284    ) -> AgentContextHandle {
285        let context = AgentContextHandle::FetchedUrl(FetchedUrlContext {
286            url: url.into(),
287            text: text.into(),
288            context_id: self.next_context_id.post_inc(),
289        });
290
291        self.insert_context(context.clone(), cx);
292        context
293    }
294
295    pub fn add_image_from_path(
296        &mut self,
297        project_path: ProjectPath,
298        remove_if_exists: bool,
299        cx: &mut Context<ContextStore>,
300    ) -> Task<Result<Option<AgentContextHandle>>> {
301        let project = self.project.clone();
302        cx.spawn(async move |this, cx| {
303            let open_image_task = project.update(cx, |project, cx| {
304                project.open_image(project_path.clone(), cx)
305            })?;
306            let image_item = open_image_task.await?;
307            let image = image_item.read_with(cx, |image_item, _| image_item.image.clone())?;
308            this.update(cx, |this, cx| {
309                this.insert_image(
310                    Some(image_item.read(cx).project_path(cx)),
311                    image,
312                    remove_if_exists,
313                    cx,
314                )
315            })
316        })
317    }
318
319    pub fn add_image_instance(&mut self, image: Arc<Image>, cx: &mut Context<ContextStore>) {
320        self.insert_image(None, image, false, cx);
321    }
322
323    fn insert_image(
324        &mut self,
325        project_path: Option<ProjectPath>,
326        image: Arc<Image>,
327        remove_if_exists: bool,
328        cx: &mut Context<ContextStore>,
329    ) -> Option<AgentContextHandle> {
330        let image_task = LanguageModelImage::from_image(image.clone(), cx).shared();
331        let context = AgentContextHandle::Image(ImageContext {
332            project_path,
333            original_image: image,
334            image_task,
335            context_id: self.next_context_id.post_inc(),
336        });
337        if self.has_context(&context) {
338            if remove_if_exists {
339                self.remove_context(&context, cx);
340                return None;
341            }
342        }
343
344        self.insert_context(context.clone(), cx);
345        Some(context)
346    }
347
348    pub fn add_selection(
349        &mut self,
350        buffer: Entity<Buffer>,
351        range: Range<Anchor>,
352        cx: &mut Context<ContextStore>,
353    ) {
354        let context_id = self.next_context_id.post_inc();
355        let context = AgentContextHandle::Selection(SelectionContextHandle {
356            buffer,
357            range,
358            context_id,
359        });
360        self.insert_context(context, cx);
361    }
362
363    pub fn add_suggested_context(
364        &mut self,
365        suggested: &SuggestedContext,
366        cx: &mut Context<ContextStore>,
367    ) {
368        match suggested {
369            SuggestedContext::File {
370                buffer,
371                icon_path: _,
372                name: _,
373            } => {
374                if let Some(buffer) = buffer.upgrade() {
375                    let context_id = self.next_context_id.post_inc();
376                    self.insert_context(
377                        AgentContextHandle::File(FileContextHandle { buffer, context_id }),
378                        cx,
379                    );
380                };
381            }
382            SuggestedContext::Thread { thread, name: _ } => {
383                if let Some(thread) = thread.upgrade() {
384                    let context_id = self.next_context_id.post_inc();
385                    self.insert_context(
386                        AgentContextHandle::Thread(ThreadContextHandle { thread, context_id }),
387                        cx,
388                    );
389                }
390            }
391            SuggestedContext::TextThread { context, name: _ } => {
392                if let Some(context) = context.upgrade() {
393                    let context_id = self.next_context_id.post_inc();
394                    self.insert_context(
395                        AgentContextHandle::TextThread(TextThreadContextHandle {
396                            context,
397                            context_id,
398                        }),
399                        cx,
400                    );
401                }
402            }
403        }
404    }
405
406    fn insert_context(&mut self, context: AgentContextHandle, cx: &mut Context<Self>) -> bool {
407        match &context {
408            AgentContextHandle::Thread(thread_context) => {
409                if let Some(thread_store) = self.thread_store.clone() {
410                    thread_context.thread.update(cx, |thread, cx| {
411                        thread.start_generating_detailed_summary_if_needed(thread_store, cx);
412                    });
413                    self.context_thread_ids
414                        .insert(thread_context.thread.read(cx).id().clone());
415                } else {
416                    return false;
417                }
418            }
419            AgentContextHandle::TextThread(text_thread_context) => {
420                self.context_text_thread_paths
421                    .extend(text_thread_context.context.read(cx).path().cloned());
422            }
423            _ => {}
424        }
425        let inserted = self.context_set.insert(AgentContextKey(context));
426        if inserted {
427            cx.notify();
428        }
429        inserted
430    }
431
432    pub fn remove_context(&mut self, context: &AgentContextHandle, cx: &mut Context<Self>) {
433        if let Some((_, key)) = self
434            .context_set
435            .shift_remove_full(AgentContextKey::ref_cast(context))
436        {
437            match context {
438                AgentContextHandle::Thread(thread_context) => {
439                    self.context_thread_ids
440                        .remove(thread_context.thread.read(cx).id());
441                }
442                AgentContextHandle::TextThread(text_thread_context) => {
443                    if let Some(path) = text_thread_context.context.read(cx).path() {
444                        self.context_text_thread_paths.remove(path);
445                    }
446                }
447                _ => {}
448            }
449            cx.emit(ContextStoreEvent::ContextRemoved(key));
450            cx.notify();
451        }
452    }
453
454    pub fn has_context(&mut self, context: &AgentContextHandle) -> bool {
455        self.context_set
456            .contains(AgentContextKey::ref_cast(context))
457    }
458
459    /// Returns whether this file path is already included directly in the context, or if it will be
460    /// included in the context via a directory.
461    pub fn file_path_included(&self, path: &ProjectPath, cx: &App) -> Option<FileInclusion> {
462        let project = self.project.upgrade()?.read(cx);
463        self.context().find_map(|context| match context {
464            AgentContextHandle::File(file_context) => {
465                FileInclusion::check_file(file_context, path, cx)
466            }
467            AgentContextHandle::Image(image_context) => {
468                FileInclusion::check_image(image_context, path)
469            }
470            AgentContextHandle::Directory(directory_context) => {
471                FileInclusion::check_directory(directory_context, path, project, cx)
472            }
473            _ => None,
474        })
475    }
476
477    pub fn path_included_in_directory(
478        &self,
479        path: &ProjectPath,
480        cx: &App,
481    ) -> Option<FileInclusion> {
482        let project = self.project.upgrade()?.read(cx);
483        self.context().find_map(|context| match context {
484            AgentContextHandle::Directory(directory_context) => {
485                FileInclusion::check_directory(directory_context, path, project, cx)
486            }
487            _ => None,
488        })
489    }
490
491    pub fn includes_symbol(&self, symbol: &Symbol, cx: &App) -> bool {
492        self.context().any(|context| match context {
493            AgentContextHandle::Symbol(context) => {
494                if context.symbol != symbol.name {
495                    return false;
496                }
497                let buffer = context.buffer.read(cx);
498                let Some(context_path) = buffer.project_path(cx) else {
499                    return false;
500                };
501                if context_path != symbol.path {
502                    return false;
503                }
504                let context_range = context.range.to_point_utf16(&buffer.snapshot());
505                context_range.start == symbol.range.start.0
506                    && context_range.end == symbol.range.end.0
507            }
508            _ => false,
509        })
510    }
511
512    pub fn includes_thread(&self, thread_id: &ThreadId) -> bool {
513        self.context_thread_ids.contains(thread_id)
514    }
515
516    pub fn includes_text_thread(&self, path: &Arc<Path>) -> bool {
517        self.context_text_thread_paths.contains(path)
518    }
519
520    pub fn includes_user_rules(&self, prompt_id: UserPromptId) -> bool {
521        self.context_set
522            .contains(&RulesContextHandle::lookup_key(prompt_id))
523    }
524
525    pub fn includes_url(&self, url: impl Into<SharedString>) -> bool {
526        self.context_set
527            .contains(&FetchedUrlContext::lookup_key(url.into()))
528    }
529
530    pub fn get_url_context(&self, url: SharedString) -> Option<AgentContextHandle> {
531        self.context_set
532            .get(&FetchedUrlContext::lookup_key(url))
533            .map(|key| key.as_ref().clone())
534    }
535
536    pub fn file_paths(&self, cx: &App) -> HashSet<ProjectPath> {
537        self.context()
538            .filter_map(|context| match context {
539                AgentContextHandle::File(file) => {
540                    let buffer = file.buffer.read(cx);
541                    buffer.project_path(cx)
542                }
543                AgentContextHandle::Directory(_)
544                | AgentContextHandle::Symbol(_)
545                | AgentContextHandle::Selection(_)
546                | AgentContextHandle::FetchedUrl(_)
547                | AgentContextHandle::Thread(_)
548                | AgentContextHandle::TextThread(_)
549                | AgentContextHandle::Rules(_)
550                | AgentContextHandle::Image(_) => None,
551            })
552            .collect()
553    }
554
555    pub fn thread_ids(&self) -> &HashSet<ThreadId> {
556        &self.context_thread_ids
557    }
558}
559
560pub enum FileInclusion {
561    Direct,
562    InDirectory { full_path: PathBuf },
563}
564
565impl FileInclusion {
566    fn check_file(file_context: &FileContextHandle, path: &ProjectPath, cx: &App) -> Option<Self> {
567        let file_path = file_context.buffer.read(cx).project_path(cx)?;
568        if path == &file_path {
569            Some(FileInclusion::Direct)
570        } else {
571            None
572        }
573    }
574
575    fn check_image(image_context: &ImageContext, path: &ProjectPath) -> Option<Self> {
576        let image_path = image_context.project_path.as_ref()?;
577        if path == image_path {
578            Some(FileInclusion::Direct)
579        } else {
580            None
581        }
582    }
583
584    fn check_directory(
585        directory_context: &DirectoryContextHandle,
586        path: &ProjectPath,
587        project: &Project,
588        cx: &App,
589    ) -> Option<Self> {
590        let worktree = project
591            .worktree_for_entry(directory_context.entry_id, cx)?
592            .read(cx);
593        let entry = worktree.entry_for_id(directory_context.entry_id)?;
594        let directory_path = ProjectPath {
595            worktree_id: worktree.id(),
596            path: entry.path.clone(),
597        };
598        if path.starts_with(&directory_path) {
599            if path == &directory_path {
600                Some(FileInclusion::Direct)
601            } else {
602                Some(FileInclusion::InDirectory {
603                    full_path: worktree.full_path(&entry.path),
604                })
605            }
606        } else {
607            None
608        }
609    }
610}