context_store.rs

  1use std::path::{Path, PathBuf};
  2use std::sync::Arc;
  3
  4use anyhow::{anyhow, bail, Result};
  5use collections::{BTreeMap, HashMap, HashSet};
  6use futures::{self, future, Future, FutureExt};
  7use gpui::{App, AppContext as _, AsyncApp, Context, Entity, SharedString, Task, WeakEntity};
  8use language::Buffer;
  9use project::{ProjectPath, Worktree};
 10use rope::Rope;
 11use text::BufferId;
 12use workspace::Workspace;
 13
 14use crate::context::{
 15    AssistantContext, ContextBuffer, ContextId, ContextSnapshot, DirectoryContext,
 16    FetchedUrlContext, FileContext, ThreadContext,
 17};
 18use crate::context_strip::SuggestedContext;
 19use crate::thread::{Thread, ThreadId};
 20
 21pub struct ContextStore {
 22    workspace: WeakEntity<Workspace>,
 23    context: Vec<AssistantContext>,
 24    // TODO: If an EntityId is used for all context types (like BufferId), can remove ContextId.
 25    next_context_id: ContextId,
 26    files: BTreeMap<BufferId, ContextId>,
 27    directories: HashMap<PathBuf, ContextId>,
 28    threads: HashMap<ThreadId, ContextId>,
 29    fetched_urls: HashMap<String, ContextId>,
 30}
 31
 32impl ContextStore {
 33    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
 34        Self {
 35            workspace,
 36            context: Vec::new(),
 37            next_context_id: ContextId(0),
 38            files: BTreeMap::default(),
 39            directories: HashMap::default(),
 40            threads: HashMap::default(),
 41            fetched_urls: HashMap::default(),
 42        }
 43    }
 44
 45    pub fn snapshot<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ContextSnapshot> + 'a {
 46        self.context()
 47            .iter()
 48            .flat_map(|context| context.snapshot(cx))
 49    }
 50
 51    pub fn context(&self) -> &Vec<AssistantContext> {
 52        &self.context
 53    }
 54
 55    pub fn clear(&mut self) {
 56        self.context.clear();
 57        self.files.clear();
 58        self.directories.clear();
 59        self.threads.clear();
 60        self.fetched_urls.clear();
 61    }
 62
 63    pub fn add_file_from_path(
 64        &mut self,
 65        project_path: ProjectPath,
 66        cx: &mut Context<Self>,
 67    ) -> Task<Result<()>> {
 68        let workspace = self.workspace.clone();
 69
 70        let Some(project) = workspace
 71            .upgrade()
 72            .map(|workspace| workspace.read(cx).project().clone())
 73        else {
 74            return Task::ready(Err(anyhow!("failed to read project")));
 75        };
 76
 77        cx.spawn(|this, mut cx| async move {
 78            let open_buffer_task = project.update(&mut cx, |project, cx| {
 79                project.open_buffer(project_path.clone(), cx)
 80            })?;
 81
 82            let buffer_entity = open_buffer_task.await?;
 83            let buffer_id = this.update(&mut cx, |_, cx| buffer_entity.read(cx).remote_id())?;
 84
 85            let already_included = this.update(&mut cx, |this, _cx| {
 86                match this.will_include_buffer(buffer_id, &project_path.path) {
 87                    Some(FileInclusion::Direct(context_id)) => {
 88                        this.remove_context(context_id);
 89                        true
 90                    }
 91                    Some(FileInclusion::InDirectory(_)) => true,
 92                    None => false,
 93                }
 94            })?;
 95
 96            if already_included {
 97                return anyhow::Ok(());
 98            }
 99
100            let (buffer_info, text_task) = this.update(&mut cx, |_, cx| {
101                let buffer = buffer_entity.read(cx);
102                collect_buffer_info_and_text(
103                    project_path.path.clone(),
104                    buffer_entity,
105                    buffer,
106                    cx.to_async(),
107                )
108            })?;
109
110            let text = text_task.await;
111
112            this.update(&mut cx, |this, _cx| {
113                this.insert_file(make_context_buffer(buffer_info, text));
114            })?;
115
116            anyhow::Ok(())
117        })
118    }
119
120    pub fn add_file_from_buffer(
121        &mut self,
122        buffer_entity: Entity<Buffer>,
123        cx: &mut Context<Self>,
124    ) -> Task<Result<()>> {
125        cx.spawn(|this, mut cx| async move {
126            let (buffer_info, text_task) = this.update(&mut cx, |_, cx| {
127                let buffer = buffer_entity.read(cx);
128                let Some(file) = buffer.file() else {
129                    return Err(anyhow!("Buffer has no path."));
130                };
131                Ok(collect_buffer_info_and_text(
132                    file.path().clone(),
133                    buffer_entity,
134                    buffer,
135                    cx.to_async(),
136                ))
137            })??;
138
139            let text = text_task.await;
140
141            this.update(&mut cx, |this, _cx| {
142                this.insert_file(make_context_buffer(buffer_info, text))
143            })?;
144
145            anyhow::Ok(())
146        })
147    }
148
149    fn insert_file(&mut self, context_buffer: ContextBuffer) {
150        let id = self.next_context_id.post_inc();
151        self.files.insert(context_buffer.id, id);
152        self.context
153            .push(AssistantContext::File(FileContext { id, context_buffer }));
154    }
155
156    pub fn add_directory(
157        &mut self,
158        project_path: ProjectPath,
159        cx: &mut Context<Self>,
160    ) -> Task<Result<()>> {
161        let workspace = self.workspace.clone();
162        let Some(project) = workspace
163            .upgrade()
164            .map(|workspace| workspace.read(cx).project().clone())
165        else {
166            return Task::ready(Err(anyhow!("failed to read project")));
167        };
168
169        let already_included = if let Some(context_id) = self.includes_directory(&project_path.path)
170        {
171            self.remove_context(context_id);
172            true
173        } else {
174            false
175        };
176        if already_included {
177            return Task::ready(Ok(()));
178        }
179
180        let worktree_id = project_path.worktree_id;
181        cx.spawn(|this, mut cx| async move {
182            let worktree = project.update(&mut cx, |project, cx| {
183                project
184                    .worktree_for_id(worktree_id, cx)
185                    .ok_or_else(|| anyhow!("no worktree found for {worktree_id:?}"))
186            })??;
187
188            let files = worktree.update(&mut cx, |worktree, _cx| {
189                collect_files_in_path(worktree, &project_path.path)
190            })?;
191
192            let open_buffers_task = project.update(&mut cx, |project, cx| {
193                let tasks = files.iter().map(|file_path| {
194                    project.open_buffer(
195                        ProjectPath {
196                            worktree_id,
197                            path: file_path.clone(),
198                        },
199                        cx,
200                    )
201                });
202                future::join_all(tasks)
203            })?;
204
205            let buffers = open_buffers_task.await;
206
207            let mut buffer_infos = Vec::new();
208            let mut text_tasks = Vec::new();
209            this.update(&mut cx, |_, cx| {
210                for (path, buffer_entity) in files.into_iter().zip(buffers) {
211                    let buffer_entity = buffer_entity?;
212                    let buffer = buffer_entity.read(cx);
213                    let (buffer_info, text_task) =
214                        collect_buffer_info_and_text(path, buffer_entity, buffer, cx.to_async());
215                    buffer_infos.push(buffer_info);
216                    text_tasks.push(text_task);
217                }
218                anyhow::Ok(())
219            })??;
220
221            let buffer_texts = future::join_all(text_tasks).await;
222            let context_buffers = buffer_infos
223                .into_iter()
224                .zip(buffer_texts)
225                .map(|(info, text)| make_context_buffer(info, text))
226                .collect::<Vec<_>>();
227
228            if context_buffers.is_empty() {
229                bail!("No text files found in {}", &project_path.path.display());
230            }
231
232            this.update(&mut cx, |this, _| {
233                this.insert_directory(&project_path.path, context_buffers);
234            })?;
235
236            anyhow::Ok(())
237        })
238    }
239
240    fn insert_directory(&mut self, path: &Path, context_buffers: Vec<ContextBuffer>) {
241        let id = self.next_context_id.post_inc();
242        self.directories.insert(path.to_path_buf(), id);
243
244        self.context
245            .push(AssistantContext::Directory(DirectoryContext::new(
246                id,
247                path,
248                context_buffers,
249            )));
250    }
251
252    pub fn add_thread(&mut self, thread: Entity<Thread>, cx: &mut Context<Self>) {
253        if let Some(context_id) = self.includes_thread(&thread.read(cx).id()) {
254            self.remove_context(context_id);
255        } else {
256            self.insert_thread(thread, cx);
257        }
258    }
259
260    fn insert_thread(&mut self, thread: Entity<Thread>, cx: &App) {
261        let id = self.next_context_id.post_inc();
262        let text = thread.read(cx).text().into();
263
264        self.threads.insert(thread.read(cx).id().clone(), id);
265        self.context
266            .push(AssistantContext::Thread(ThreadContext { id, thread, text }));
267    }
268
269    pub fn add_fetched_url(&mut self, url: String, text: impl Into<SharedString>) {
270        if self.includes_url(&url).is_none() {
271            self.insert_fetched_url(url, text);
272        }
273    }
274
275    fn insert_fetched_url(&mut self, url: String, text: impl Into<SharedString>) {
276        let id = self.next_context_id.post_inc();
277
278        self.fetched_urls.insert(url.clone(), id);
279        self.context
280            .push(AssistantContext::FetchedUrl(FetchedUrlContext {
281                id,
282                url: url.into(),
283                text: text.into(),
284            }));
285    }
286
287    pub fn accept_suggested_context(
288        &mut self,
289        suggested: &SuggestedContext,
290        cx: &mut Context<ContextStore>,
291    ) -> Task<Result<()>> {
292        match suggested {
293            SuggestedContext::File {
294                buffer,
295                icon_path: _,
296                name: _,
297            } => {
298                if let Some(buffer) = buffer.upgrade() {
299                    return self.add_file_from_buffer(buffer, cx);
300                };
301            }
302            SuggestedContext::Thread { thread, name: _ } => {
303                if let Some(thread) = thread.upgrade() {
304                    self.insert_thread(thread, cx);
305                };
306            }
307        }
308        Task::ready(Ok(()))
309    }
310
311    pub fn remove_context(&mut self, id: ContextId) {
312        let Some(ix) = self.context.iter().position(|context| context.id() == id) else {
313            return;
314        };
315
316        match self.context.remove(ix) {
317            AssistantContext::File(_) => {
318                self.files.retain(|_, context_id| *context_id != id);
319            }
320            AssistantContext::Directory(_) => {
321                self.directories.retain(|_, context_id| *context_id != id);
322            }
323            AssistantContext::FetchedUrl(_) => {
324                self.fetched_urls.retain(|_, context_id| *context_id != id);
325            }
326            AssistantContext::Thread(_) => {
327                self.threads.retain(|_, context_id| *context_id != id);
328            }
329        }
330    }
331
332    /// Returns whether the buffer is already included directly in the context, or if it will be
333    /// included in the context via a directory. Directory inclusion is based on paths rather than
334    /// buffer IDs as the directory will be re-scanned.
335    pub fn will_include_buffer(&self, buffer_id: BufferId, path: &Path) -> Option<FileInclusion> {
336        if let Some(context_id) = self.files.get(&buffer_id) {
337            return Some(FileInclusion::Direct(*context_id));
338        }
339
340        self.will_include_file_path_via_directory(path)
341    }
342
343    /// Returns whether this file path is already included directly in the context, or if it will be
344    /// included in the context via a directory.
345    pub fn will_include_file_path(&self, path: &Path, cx: &App) -> Option<FileInclusion> {
346        if !self.files.is_empty() {
347            let found_file_context = self.context.iter().find(|context| match &context {
348                AssistantContext::File(file_context) => {
349                    let buffer = file_context.context_buffer.buffer.read(cx);
350                    if let Some(file_path) = buffer_path_log_err(buffer) {
351                        *file_path == *path
352                    } else {
353                        false
354                    }
355                }
356                _ => false,
357            });
358            if let Some(context) = found_file_context {
359                return Some(FileInclusion::Direct(context.id()));
360            }
361        }
362
363        self.will_include_file_path_via_directory(path)
364    }
365
366    fn will_include_file_path_via_directory(&self, path: &Path) -> Option<FileInclusion> {
367        if self.directories.is_empty() {
368            return None;
369        }
370
371        let mut buf = path.to_path_buf();
372
373        while buf.pop() {
374            if let Some(_) = self.directories.get(&buf) {
375                return Some(FileInclusion::InDirectory(buf));
376            }
377        }
378
379        None
380    }
381
382    pub fn includes_directory(&self, path: &Path) -> Option<ContextId> {
383        self.directories.get(path).copied()
384    }
385
386    pub fn includes_thread(&self, thread_id: &ThreadId) -> Option<ContextId> {
387        self.threads.get(thread_id).copied()
388    }
389
390    pub fn includes_url(&self, url: &str) -> Option<ContextId> {
391        self.fetched_urls.get(url).copied()
392    }
393
394    /// Replaces the context that matches the ID of the new context, if any match.
395    fn replace_context(&mut self, new_context: AssistantContext) {
396        let id = new_context.id();
397        for context in self.context.iter_mut() {
398            if context.id() == id {
399                *context = new_context;
400                break;
401            }
402        }
403    }
404
405    pub fn file_paths(&self, cx: &App) -> HashSet<PathBuf> {
406        self.context
407            .iter()
408            .filter_map(|context| match context {
409                AssistantContext::File(file) => {
410                    let buffer = file.context_buffer.buffer.read(cx);
411                    buffer_path_log_err(buffer).map(|p| p.to_path_buf())
412                }
413                AssistantContext::Directory(_)
414                | AssistantContext::FetchedUrl(_)
415                | AssistantContext::Thread(_) => None,
416            })
417            .collect()
418    }
419
420    pub fn thread_ids(&self) -> HashSet<ThreadId> {
421        self.threads.keys().cloned().collect()
422    }
423}
424
425pub enum FileInclusion {
426    Direct(ContextId),
427    InDirectory(PathBuf),
428}
429
430// ContextBuffer without text.
431struct BufferInfo {
432    buffer_entity: Entity<Buffer>,
433    id: BufferId,
434    version: clock::Global,
435}
436
437fn make_context_buffer(info: BufferInfo, text: SharedString) -> ContextBuffer {
438    ContextBuffer {
439        id: info.id,
440        buffer: info.buffer_entity,
441        version: info.version,
442        text,
443    }
444}
445
446fn collect_buffer_info_and_text(
447    path: Arc<Path>,
448    buffer_entity: Entity<Buffer>,
449    buffer: &Buffer,
450    cx: AsyncApp,
451) -> (BufferInfo, Task<SharedString>) {
452    let buffer_info = BufferInfo {
453        id: buffer.remote_id(),
454        buffer_entity,
455        version: buffer.version(),
456    };
457    // Important to collect version at the same time as content so that staleness logic is correct.
458    let content = buffer.as_rope().clone();
459    let text_task = cx.background_spawn(async move { to_fenced_codeblock(&path, content) });
460    (buffer_info, text_task)
461}
462
463pub fn buffer_path_log_err(buffer: &Buffer) -> Option<Arc<Path>> {
464    if let Some(file) = buffer.file() {
465        Some(file.path().clone())
466    } else {
467        log::error!("Buffer that had a path unexpectedly no longer has a path.");
468        None
469    }
470}
471
472fn to_fenced_codeblock(path: &Path, content: Rope) -> SharedString {
473    let path_extension = path.extension().and_then(|ext| ext.to_str());
474    let path_string = path.to_string_lossy();
475    let capacity = 3
476        + path_extension.map_or(0, |extension| extension.len() + 1)
477        + path_string.len()
478        + 1
479        + content.len()
480        + 5;
481    let mut buffer = String::with_capacity(capacity);
482
483    buffer.push_str("```");
484
485    if let Some(extension) = path_extension {
486        buffer.push_str(extension);
487        buffer.push(' ');
488    }
489    buffer.push_str(&path_string);
490
491    buffer.push('\n');
492    for chunk in content.chunks() {
493        buffer.push_str(&chunk);
494    }
495
496    if !buffer.ends_with('\n') {
497        buffer.push('\n');
498    }
499
500    buffer.push_str("```\n");
501
502    debug_assert!(
503        buffer.len() == capacity - 1 || buffer.len() == capacity,
504        "to_fenced_codeblock calculated capacity of {}, but length was {}",
505        capacity,
506        buffer.len(),
507    );
508
509    buffer.into()
510}
511
512fn collect_files_in_path(worktree: &Worktree, path: &Path) -> Vec<Arc<Path>> {
513    let mut files = Vec::new();
514
515    for entry in worktree.child_entries(path) {
516        if entry.is_dir() {
517            files.extend(collect_files_in_path(worktree, &entry.path));
518        } else if entry.is_file() {
519            files.push(entry.path.clone());
520        }
521    }
522
523    files
524}
525
526pub fn refresh_context_store_text(
527    context_store: Entity<ContextStore>,
528    cx: &App,
529) -> impl Future<Output = ()> {
530    let mut tasks = Vec::new();
531    for context in &context_store.read(cx).context {
532        match context {
533            AssistantContext::File(file_context) => {
534                let context_store = context_store.clone();
535                if let Some(task) = refresh_file_text(context_store, file_context, cx) {
536                    tasks.push(task);
537                }
538            }
539            AssistantContext::Directory(directory_context) => {
540                let context_store = context_store.clone();
541                if let Some(task) = refresh_directory_text(context_store, directory_context, cx) {
542                    tasks.push(task);
543                }
544            }
545            AssistantContext::Thread(thread_context) => {
546                let context_store = context_store.clone();
547                tasks.push(refresh_thread_text(context_store, thread_context, cx));
548            }
549            // Intentionally omit refreshing fetched URLs as it doesn't seem all that useful,
550            // and doing the caching properly could be tricky (unless it's already handled by
551            // the HttpClient?).
552            AssistantContext::FetchedUrl(_) => {}
553        }
554    }
555
556    future::join_all(tasks).map(|_| ())
557}
558
559fn refresh_file_text(
560    context_store: Entity<ContextStore>,
561    file_context: &FileContext,
562    cx: &App,
563) -> Option<Task<()>> {
564    let id = file_context.id;
565    let task = refresh_context_buffer(&file_context.context_buffer, cx);
566    if let Some(task) = task {
567        Some(cx.spawn(|mut cx| async move {
568            let context_buffer = task.await;
569            context_store
570                .update(&mut cx, |context_store, _| {
571                    let new_file_context = FileContext { id, context_buffer };
572                    context_store.replace_context(AssistantContext::File(new_file_context));
573                })
574                .ok();
575        }))
576    } else {
577        None
578    }
579}
580
581fn refresh_directory_text(
582    context_store: Entity<ContextStore>,
583    directory_context: &DirectoryContext,
584    cx: &App,
585) -> Option<Task<()>> {
586    let mut stale = false;
587    let futures = directory_context
588        .context_buffers
589        .iter()
590        .map(|context_buffer| {
591            if let Some(refresh_task) = refresh_context_buffer(context_buffer, cx) {
592                stale = true;
593                future::Either::Left(refresh_task)
594            } else {
595                future::Either::Right(future::ready((*context_buffer).clone()))
596            }
597        })
598        .collect::<Vec<_>>();
599
600    if !stale {
601        return None;
602    }
603
604    let context_buffers = future::join_all(futures);
605
606    let id = directory_context.snapshot.id;
607    let path = directory_context.path.clone();
608    Some(cx.spawn(|mut cx| async move {
609        let context_buffers = context_buffers.await;
610        context_store
611            .update(&mut cx, |context_store, _| {
612                let new_directory_context = DirectoryContext::new(id, &path, context_buffers);
613                context_store.replace_context(AssistantContext::Directory(new_directory_context));
614            })
615            .ok();
616    }))
617}
618
619fn refresh_thread_text(
620    context_store: Entity<ContextStore>,
621    thread_context: &ThreadContext,
622    cx: &App,
623) -> Task<()> {
624    let id = thread_context.id;
625    let thread = thread_context.thread.clone();
626    cx.spawn(move |mut cx| async move {
627        context_store
628            .update(&mut cx, |context_store, cx| {
629                let text = thread.read(cx).text().into();
630                context_store.replace_context(AssistantContext::Thread(ThreadContext {
631                    id,
632                    thread,
633                    text,
634                }));
635            })
636            .ok();
637    })
638}
639
640fn refresh_context_buffer(
641    context_buffer: &ContextBuffer,
642    cx: &App,
643) -> Option<impl Future<Output = ContextBuffer>> {
644    let buffer = context_buffer.buffer.read(cx);
645    let path = buffer_path_log_err(buffer)?;
646    if buffer.version.changed_since(&context_buffer.version) {
647        let (buffer_info, text_task) = collect_buffer_info_and_text(
648            path,
649            context_buffer.buffer.clone(),
650            buffer,
651            cx.to_async(),
652        );
653        Some(text_task.map(move |text| make_context_buffer(buffer_info, text)))
654    } else {
655        None
656    }
657}