context_store.rs

  1use std::ops::Range;
  2use std::path::{Path, PathBuf};
  3use std::sync::Arc;
  4
  5use anyhow::{anyhow, bail, Result};
  6use collections::{BTreeMap, HashMap, HashSet};
  7use futures::{self, future, Future, FutureExt};
  8use gpui::{App, AppContext as _, AsyncApp, Context, Entity, SharedString, Task, WeakEntity};
  9use language::Buffer;
 10use project::{ProjectItem, ProjectPath, Worktree};
 11use rope::Rope;
 12use text::{Anchor, BufferId, OffsetRangeExt};
 13use util::maybe;
 14use workspace::Workspace;
 15
 16use crate::context::{
 17    AssistantContext, ContextBuffer, ContextId, ContextSnapshot, ContextSymbol, ContextSymbolId,
 18    DirectoryContext, FetchedUrlContext, FileContext, SymbolContext, ThreadContext,
 19};
 20use crate::context_strip::SuggestedContext;
 21use crate::thread::{Thread, ThreadId};
 22
 23pub struct ContextStore {
 24    workspace: WeakEntity<Workspace>,
 25    context: Vec<AssistantContext>,
 26    // TODO: If an EntityId is used for all context types (like BufferId), can remove ContextId.
 27    next_context_id: ContextId,
 28    files: BTreeMap<BufferId, ContextId>,
 29    directories: HashMap<PathBuf, ContextId>,
 30    symbols: HashMap<ContextSymbolId, ContextId>,
 31    symbol_buffers: HashMap<ContextSymbolId, Entity<Buffer>>,
 32    symbols_by_path: HashMap<ProjectPath, Vec<ContextSymbolId>>,
 33    threads: HashMap<ThreadId, ContextId>,
 34    fetched_urls: HashMap<String, ContextId>,
 35}
 36
 37impl ContextStore {
 38    pub fn new(workspace: WeakEntity<Workspace>) -> Self {
 39        Self {
 40            workspace,
 41            context: Vec::new(),
 42            next_context_id: ContextId(0),
 43            files: BTreeMap::default(),
 44            directories: HashMap::default(),
 45            symbols: HashMap::default(),
 46            symbol_buffers: HashMap::default(),
 47            symbols_by_path: HashMap::default(),
 48            threads: HashMap::default(),
 49            fetched_urls: HashMap::default(),
 50        }
 51    }
 52
 53    pub fn snapshot<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ContextSnapshot> + 'a {
 54        self.context()
 55            .iter()
 56            .flat_map(|context| context.snapshot(cx))
 57    }
 58
 59    pub fn context(&self) -> &Vec<AssistantContext> {
 60        &self.context
 61    }
 62
 63    pub fn context_for_id(&self, id: ContextId) -> Option<&AssistantContext> {
 64        self.context().iter().find(|context| context.id() == id)
 65    }
 66
 67    pub fn clear(&mut self) {
 68        self.context.clear();
 69        self.files.clear();
 70        self.directories.clear();
 71        self.threads.clear();
 72        self.fetched_urls.clear();
 73    }
 74
 75    pub fn add_file_from_path(
 76        &mut self,
 77        project_path: ProjectPath,
 78        remove_if_exists: bool,
 79        cx: &mut Context<Self>,
 80    ) -> Task<Result<()>> {
 81        let workspace = self.workspace.clone();
 82
 83        let Some(project) = workspace
 84            .upgrade()
 85            .map(|workspace| workspace.read(cx).project().clone())
 86        else {
 87            return Task::ready(Err(anyhow!("failed to read project")));
 88        };
 89
 90        cx.spawn(async move |this, cx| {
 91            let open_buffer_task = project.update(cx, |project, cx| {
 92                project.open_buffer(project_path.clone(), cx)
 93            })?;
 94
 95            let buffer_entity = open_buffer_task.await?;
 96            let buffer_id = this.update(cx, |_, cx| buffer_entity.read(cx).remote_id())?;
 97
 98            let already_included = this.update(cx, |this, _cx| {
 99                match this.will_include_buffer(buffer_id, &project_path.path) {
100                    Some(FileInclusion::Direct(context_id)) => {
101                        if remove_if_exists {
102                            this.remove_context(context_id);
103                        }
104                        true
105                    }
106                    Some(FileInclusion::InDirectory(_)) => true,
107                    None => false,
108                }
109            })?;
110
111            if already_included {
112                return anyhow::Ok(());
113            }
114
115            let (buffer_info, text_task) = this.update(cx, |_, cx| {
116                let buffer = buffer_entity.read(cx);
117                collect_buffer_info_and_text(
118                    project_path.path.clone(),
119                    buffer_entity,
120                    buffer,
121                    None,
122                    cx.to_async(),
123                )
124            })?;
125
126            let text = text_task.await;
127
128            this.update(cx, |this, _cx| {
129                this.insert_file(make_context_buffer(buffer_info, text));
130            })?;
131
132            anyhow::Ok(())
133        })
134    }
135
136    pub fn add_file_from_buffer(
137        &mut self,
138        buffer_entity: Entity<Buffer>,
139        cx: &mut Context<Self>,
140    ) -> Task<Result<()>> {
141        cx.spawn(async move |this, cx| {
142            let (buffer_info, text_task) = this.update(cx, |_, cx| {
143                let buffer = buffer_entity.read(cx);
144                let Some(file) = buffer.file() else {
145                    return Err(anyhow!("Buffer has no path."));
146                };
147                Ok(collect_buffer_info_and_text(
148                    file.path().clone(),
149                    buffer_entity,
150                    buffer,
151                    None,
152                    cx.to_async(),
153                ))
154            })??;
155
156            let text = text_task.await;
157
158            this.update(cx, |this, _cx| {
159                this.insert_file(make_context_buffer(buffer_info, text))
160            })?;
161
162            anyhow::Ok(())
163        })
164    }
165
166    fn insert_file(&mut self, context_buffer: ContextBuffer) {
167        let id = self.next_context_id.post_inc();
168        self.files.insert(context_buffer.id, id);
169        self.context
170            .push(AssistantContext::File(FileContext { id, context_buffer }));
171    }
172
173    pub fn add_directory(
174        &mut self,
175        project_path: ProjectPath,
176        remove_if_exists: bool,
177        cx: &mut Context<Self>,
178    ) -> Task<Result<()>> {
179        let workspace = self.workspace.clone();
180        let Some(project) = workspace
181            .upgrade()
182            .map(|workspace| workspace.read(cx).project().clone())
183        else {
184            return Task::ready(Err(anyhow!("failed to read project")));
185        };
186
187        let already_included = if let Some(context_id) = self.includes_directory(&project_path.path)
188        {
189            if remove_if_exists {
190                self.remove_context(context_id);
191            }
192            true
193        } else {
194            false
195        };
196        if already_included {
197            return Task::ready(Ok(()));
198        }
199
200        let worktree_id = project_path.worktree_id;
201        cx.spawn(async move |this, cx| {
202            let worktree = project.update(cx, |project, cx| {
203                project
204                    .worktree_for_id(worktree_id, cx)
205                    .ok_or_else(|| anyhow!("no worktree found for {worktree_id:?}"))
206            })??;
207
208            let files = worktree.update(cx, |worktree, _cx| {
209                collect_files_in_path(worktree, &project_path.path)
210            })?;
211
212            let open_buffers_task = project.update(cx, |project, cx| {
213                let tasks = files.iter().map(|file_path| {
214                    project.open_buffer(
215                        ProjectPath {
216                            worktree_id,
217                            path: file_path.clone(),
218                        },
219                        cx,
220                    )
221                });
222                future::join_all(tasks)
223            })?;
224
225            let buffers = open_buffers_task.await;
226
227            let mut buffer_infos = Vec::new();
228            let mut text_tasks = Vec::new();
229            this.update(cx, |_, cx| {
230                for (path, buffer_entity) in files.into_iter().zip(buffers) {
231                    // Skip all binary files and other non-UTF8 files
232                    if let Ok(buffer_entity) = buffer_entity {
233                        let buffer = buffer_entity.read(cx);
234                        let (buffer_info, text_task) = collect_buffer_info_and_text(
235                            path,
236                            buffer_entity,
237                            buffer,
238                            None,
239                            cx.to_async(),
240                        );
241                        buffer_infos.push(buffer_info);
242                        text_tasks.push(text_task);
243                    }
244                }
245                anyhow::Ok(())
246            })??;
247
248            let buffer_texts = future::join_all(text_tasks).await;
249            let context_buffers = buffer_infos
250                .into_iter()
251                .zip(buffer_texts)
252                .map(|(info, text)| make_context_buffer(info, text))
253                .collect::<Vec<_>>();
254
255            if context_buffers.is_empty() {
256                bail!("No text files found in {}", &project_path.path.display());
257            }
258
259            this.update(cx, |this, _| {
260                this.insert_directory(project_path, context_buffers);
261            })?;
262
263            anyhow::Ok(())
264        })
265    }
266
267    fn insert_directory(&mut self, project_path: ProjectPath, context_buffers: Vec<ContextBuffer>) {
268        let id = self.next_context_id.post_inc();
269        self.directories.insert(project_path.path.to_path_buf(), id);
270
271        self.context
272            .push(AssistantContext::Directory(DirectoryContext::new(
273                id,
274                project_path,
275                context_buffers,
276            )));
277    }
278
279    pub fn add_symbol(
280        &mut self,
281        buffer: Entity<Buffer>,
282        symbol_name: SharedString,
283        symbol_range: Range<Anchor>,
284        symbol_enclosing_range: Range<Anchor>,
285        remove_if_exists: bool,
286        cx: &mut Context<Self>,
287    ) -> Task<Result<bool>> {
288        let buffer_ref = buffer.read(cx);
289        let Some(file) = buffer_ref.file() else {
290            return Task::ready(Err(anyhow!("Buffer has no path.")));
291        };
292
293        let Some(project_path) = buffer_ref.project_path(cx) else {
294            return Task::ready(Err(anyhow!("Buffer has no project path.")));
295        };
296
297        if let Some(symbols_for_path) = self.symbols_by_path.get(&project_path) {
298            let mut matching_symbol_id = None;
299            for symbol in symbols_for_path {
300                if &symbol.name == &symbol_name {
301                    let snapshot = buffer_ref.snapshot();
302                    if symbol.range.to_offset(&snapshot) == symbol_range.to_offset(&snapshot) {
303                        matching_symbol_id = self.symbols.get(symbol).cloned();
304                        break;
305                    }
306                }
307            }
308
309            if let Some(id) = matching_symbol_id {
310                if remove_if_exists {
311                    self.remove_context(id);
312                }
313                return Task::ready(Ok(false));
314            }
315        }
316
317        let (buffer_info, collect_content_task) = collect_buffer_info_and_text(
318            file.path().clone(),
319            buffer,
320            buffer_ref,
321            Some(symbol_enclosing_range.clone()),
322            cx.to_async(),
323        );
324
325        cx.spawn(async move |this, cx| {
326            let content = collect_content_task.await;
327
328            this.update(cx, |this, _cx| {
329                this.insert_symbol(make_context_symbol(
330                    buffer_info,
331                    project_path,
332                    symbol_name,
333                    symbol_range,
334                    symbol_enclosing_range,
335                    content,
336                ))
337            })?;
338            anyhow::Ok(true)
339        })
340    }
341
342    fn insert_symbol(&mut self, context_symbol: ContextSymbol) {
343        let id = self.next_context_id.post_inc();
344        self.symbols.insert(context_symbol.id.clone(), id);
345        self.symbols_by_path
346            .entry(context_symbol.id.path.clone())
347            .or_insert_with(Vec::new)
348            .push(context_symbol.id.clone());
349        self.symbol_buffers
350            .insert(context_symbol.id.clone(), context_symbol.buffer.clone());
351        self.context.push(AssistantContext::Symbol(SymbolContext {
352            id,
353            context_symbol,
354        }));
355    }
356
357    pub fn add_thread(
358        &mut self,
359        thread: Entity<Thread>,
360        remove_if_exists: bool,
361        cx: &mut Context<Self>,
362    ) {
363        if let Some(context_id) = self.includes_thread(&thread.read(cx).id()) {
364            if remove_if_exists {
365                self.remove_context(context_id);
366            }
367        } else {
368            self.insert_thread(thread, cx);
369        }
370    }
371
372    fn insert_thread(&mut self, thread: Entity<Thread>, cx: &App) {
373        let id = self.next_context_id.post_inc();
374        let text = thread.read(cx).text().into();
375
376        self.threads.insert(thread.read(cx).id().clone(), id);
377        self.context
378            .push(AssistantContext::Thread(ThreadContext { id, thread, text }));
379    }
380
381    pub fn add_fetched_url(&mut self, url: String, text: impl Into<SharedString>) {
382        if self.includes_url(&url).is_none() {
383            self.insert_fetched_url(url, text);
384        }
385    }
386
387    fn insert_fetched_url(&mut self, url: String, text: impl Into<SharedString>) {
388        let id = self.next_context_id.post_inc();
389
390        self.fetched_urls.insert(url.clone(), id);
391        self.context
392            .push(AssistantContext::FetchedUrl(FetchedUrlContext {
393                id,
394                url: url.into(),
395                text: text.into(),
396            }));
397    }
398
399    pub fn accept_suggested_context(
400        &mut self,
401        suggested: &SuggestedContext,
402        cx: &mut Context<ContextStore>,
403    ) -> Task<Result<()>> {
404        match suggested {
405            SuggestedContext::File {
406                buffer,
407                icon_path: _,
408                name: _,
409            } => {
410                if let Some(buffer) = buffer.upgrade() {
411                    return self.add_file_from_buffer(buffer, cx);
412                };
413            }
414            SuggestedContext::Thread { thread, name: _ } => {
415                if let Some(thread) = thread.upgrade() {
416                    self.insert_thread(thread, cx);
417                };
418            }
419        }
420        Task::ready(Ok(()))
421    }
422
423    pub fn remove_context(&mut self, id: ContextId) {
424        let Some(ix) = self.context.iter().position(|context| context.id() == id) else {
425            return;
426        };
427
428        match self.context.remove(ix) {
429            AssistantContext::File(_) => {
430                self.files.retain(|_, context_id| *context_id != id);
431            }
432            AssistantContext::Directory(_) => {
433                self.directories.retain(|_, context_id| *context_id != id);
434            }
435            AssistantContext::Symbol(symbol) => {
436                if let Some(symbols_in_path) =
437                    self.symbols_by_path.get_mut(&symbol.context_symbol.id.path)
438                {
439                    symbols_in_path.retain(|s| {
440                        self.symbols
441                            .get(s)
442                            .map_or(false, |context_id| *context_id != id)
443                    });
444                }
445                self.symbol_buffers.remove(&symbol.context_symbol.id);
446                self.symbols.retain(|_, context_id| *context_id != id);
447            }
448            AssistantContext::FetchedUrl(_) => {
449                self.fetched_urls.retain(|_, context_id| *context_id != id);
450            }
451            AssistantContext::Thread(_) => {
452                self.threads.retain(|_, context_id| *context_id != id);
453            }
454        }
455    }
456
457    /// Returns whether the buffer is already included directly in the context, or if it will be
458    /// included in the context via a directory. Directory inclusion is based on paths rather than
459    /// buffer IDs as the directory will be re-scanned.
460    pub fn will_include_buffer(&self, buffer_id: BufferId, path: &Path) -> Option<FileInclusion> {
461        if let Some(context_id) = self.files.get(&buffer_id) {
462            return Some(FileInclusion::Direct(*context_id));
463        }
464
465        self.will_include_file_path_via_directory(path)
466    }
467
468    /// Returns whether this file path is already included directly in the context, or if it will be
469    /// included in the context via a directory.
470    pub fn will_include_file_path(&self, path: &Path, cx: &App) -> Option<FileInclusion> {
471        if !self.files.is_empty() {
472            let found_file_context = self.context.iter().find(|context| match &context {
473                AssistantContext::File(file_context) => {
474                    let buffer = file_context.context_buffer.buffer.read(cx);
475                    if let Some(file_path) = buffer_path_log_err(buffer) {
476                        *file_path == *path
477                    } else {
478                        false
479                    }
480                }
481                _ => false,
482            });
483            if let Some(context) = found_file_context {
484                return Some(FileInclusion::Direct(context.id()));
485            }
486        }
487
488        self.will_include_file_path_via_directory(path)
489    }
490
491    fn will_include_file_path_via_directory(&self, path: &Path) -> Option<FileInclusion> {
492        if self.directories.is_empty() {
493            return None;
494        }
495
496        let mut buf = path.to_path_buf();
497
498        while buf.pop() {
499            if let Some(_) = self.directories.get(&buf) {
500                return Some(FileInclusion::InDirectory(buf));
501            }
502        }
503
504        None
505    }
506
507    pub fn includes_directory(&self, path: &Path) -> Option<ContextId> {
508        self.directories.get(path).copied()
509    }
510
511    pub fn included_symbol(&self, symbol_id: &ContextSymbolId) -> Option<ContextId> {
512        self.symbols.get(symbol_id).copied()
513    }
514
515    pub fn included_symbols_by_path(&self) -> &HashMap<ProjectPath, Vec<ContextSymbolId>> {
516        &self.symbols_by_path
517    }
518
519    pub fn buffer_for_symbol(&self, symbol_id: &ContextSymbolId) -> Option<Entity<Buffer>> {
520        self.symbol_buffers.get(symbol_id).cloned()
521    }
522
523    pub fn includes_thread(&self, thread_id: &ThreadId) -> Option<ContextId> {
524        self.threads.get(thread_id).copied()
525    }
526
527    pub fn includes_url(&self, url: &str) -> Option<ContextId> {
528        self.fetched_urls.get(url).copied()
529    }
530
531    /// Replaces the context that matches the ID of the new context, if any match.
532    fn replace_context(&mut self, new_context: AssistantContext) {
533        let id = new_context.id();
534        for context in self.context.iter_mut() {
535            if context.id() == id {
536                *context = new_context;
537                break;
538            }
539        }
540    }
541
542    pub fn file_paths(&self, cx: &App) -> HashSet<PathBuf> {
543        self.context
544            .iter()
545            .filter_map(|context| match context {
546                AssistantContext::File(file) => {
547                    let buffer = file.context_buffer.buffer.read(cx);
548                    buffer_path_log_err(buffer).map(|p| p.to_path_buf())
549                }
550                AssistantContext::Directory(_)
551                | AssistantContext::Symbol(_)
552                | AssistantContext::FetchedUrl(_)
553                | AssistantContext::Thread(_) => None,
554            })
555            .collect()
556    }
557
558    pub fn thread_ids(&self) -> HashSet<ThreadId> {
559        self.threads.keys().cloned().collect()
560    }
561}
562
563pub enum FileInclusion {
564    Direct(ContextId),
565    InDirectory(PathBuf),
566}
567
568// ContextBuffer without text.
569struct BufferInfo {
570    buffer_entity: Entity<Buffer>,
571    id: BufferId,
572    version: clock::Global,
573}
574
575fn make_context_buffer(info: BufferInfo, text: SharedString) -> ContextBuffer {
576    ContextBuffer {
577        id: info.id,
578        buffer: info.buffer_entity,
579        version: info.version,
580        text,
581    }
582}
583
584fn make_context_symbol(
585    info: BufferInfo,
586    path: ProjectPath,
587    name: SharedString,
588    range: Range<Anchor>,
589    enclosing_range: Range<Anchor>,
590    text: SharedString,
591) -> ContextSymbol {
592    ContextSymbol {
593        id: ContextSymbolId { name, range, path },
594        buffer_version: info.version,
595        enclosing_range,
596        buffer: info.buffer_entity,
597        text,
598    }
599}
600
601fn collect_buffer_info_and_text(
602    path: Arc<Path>,
603    buffer_entity: Entity<Buffer>,
604    buffer: &Buffer,
605    range: Option<Range<Anchor>>,
606    cx: AsyncApp,
607) -> (BufferInfo, Task<SharedString>) {
608    let buffer_info = BufferInfo {
609        id: buffer.remote_id(),
610        buffer_entity,
611        version: buffer.version(),
612    };
613    // Important to collect version at the same time as content so that staleness logic is correct.
614    let content = if let Some(range) = range {
615        buffer.text_for_range(range).collect::<Rope>()
616    } else {
617        buffer.as_rope().clone()
618    };
619    let text_task = cx.background_spawn(async move { to_fenced_codeblock(&path, content) });
620    (buffer_info, text_task)
621}
622
623pub fn buffer_path_log_err(buffer: &Buffer) -> Option<Arc<Path>> {
624    if let Some(file) = buffer.file() {
625        Some(file.path().clone())
626    } else {
627        log::error!("Buffer that had a path unexpectedly no longer has a path.");
628        None
629    }
630}
631
632fn to_fenced_codeblock(path: &Path, content: Rope) -> SharedString {
633    let path_extension = path.extension().and_then(|ext| ext.to_str());
634    let path_string = path.to_string_lossy();
635    let capacity = 3
636        + path_extension.map_or(0, |extension| extension.len() + 1)
637        + path_string.len()
638        + 1
639        + content.len()
640        + 5;
641    let mut buffer = String::with_capacity(capacity);
642
643    buffer.push_str("```");
644
645    if let Some(extension) = path_extension {
646        buffer.push_str(extension);
647        buffer.push(' ');
648    }
649    buffer.push_str(&path_string);
650
651    buffer.push('\n');
652    for chunk in content.chunks() {
653        buffer.push_str(&chunk);
654    }
655
656    if !buffer.ends_with('\n') {
657        buffer.push('\n');
658    }
659
660    buffer.push_str("```\n");
661
662    debug_assert!(
663        buffer.len() == capacity - 1 || buffer.len() == capacity,
664        "to_fenced_codeblock calculated capacity of {}, but length was {}",
665        capacity,
666        buffer.len(),
667    );
668
669    buffer.into()
670}
671
672fn collect_files_in_path(worktree: &Worktree, path: &Path) -> Vec<Arc<Path>> {
673    let mut files = Vec::new();
674
675    for entry in worktree.child_entries(path) {
676        if entry.is_dir() {
677            files.extend(collect_files_in_path(worktree, &entry.path));
678        } else if entry.is_file() {
679            files.push(entry.path.clone());
680        }
681    }
682
683    files
684}
685
686pub fn refresh_context_store_text(
687    context_store: Entity<ContextStore>,
688    changed_buffers: &HashSet<Entity<Buffer>>,
689    cx: &App,
690) -> impl Future<Output = Vec<ContextId>> + use<> {
691    let mut tasks = Vec::new();
692
693    for context in &context_store.read(cx).context {
694        let id = context.id();
695
696        let task = maybe!({
697            match context {
698                AssistantContext::File(file_context) => {
699                    if changed_buffers.is_empty()
700                        || changed_buffers.contains(&file_context.context_buffer.buffer)
701                    {
702                        let context_store = context_store.clone();
703                        return refresh_file_text(context_store, file_context, cx);
704                    }
705                }
706                AssistantContext::Directory(directory_context) => {
707                    let should_refresh = changed_buffers.is_empty()
708                        || changed_buffers.iter().any(|buffer| {
709                            let buffer = buffer.read(cx);
710
711                            buffer_path_log_err(&buffer).map_or(false, |path| {
712                                path.starts_with(&directory_context.path.path)
713                            })
714                        });
715
716                    if should_refresh {
717                        let context_store = context_store.clone();
718                        return refresh_directory_text(context_store, directory_context, cx);
719                    }
720                }
721                AssistantContext::Symbol(symbol_context) => {
722                    if changed_buffers.is_empty()
723                        || changed_buffers.contains(&symbol_context.context_symbol.buffer)
724                    {
725                        let context_store = context_store.clone();
726                        return refresh_symbol_text(context_store, symbol_context, cx);
727                    }
728                }
729                AssistantContext::Thread(thread_context) => {
730                    if changed_buffers.is_empty() {
731                        let context_store = context_store.clone();
732                        return Some(refresh_thread_text(context_store, thread_context, cx));
733                    }
734                }
735                // Intentionally omit refreshing fetched URLs as it doesn't seem all that useful,
736                // and doing the caching properly could be tricky (unless it's already handled by
737                // the HttpClient?).
738                AssistantContext::FetchedUrl(_) => {}
739            }
740
741            None
742        });
743
744        if let Some(task) = task {
745            tasks.push(task.map(move |_| id));
746        }
747    }
748
749    future::join_all(tasks)
750}
751
752fn refresh_file_text(
753    context_store: Entity<ContextStore>,
754    file_context: &FileContext,
755    cx: &App,
756) -> Option<Task<()>> {
757    let id = file_context.id;
758    let task = refresh_context_buffer(&file_context.context_buffer, cx);
759    if let Some(task) = task {
760        Some(cx.spawn(async move |cx| {
761            let context_buffer = task.await;
762            context_store
763                .update(cx, |context_store, _| {
764                    let new_file_context = FileContext { id, context_buffer };
765                    context_store.replace_context(AssistantContext::File(new_file_context));
766                })
767                .ok();
768        }))
769    } else {
770        None
771    }
772}
773
774fn refresh_directory_text(
775    context_store: Entity<ContextStore>,
776    directory_context: &DirectoryContext,
777    cx: &App,
778) -> Option<Task<()>> {
779    let mut stale = false;
780    let futures = directory_context
781        .context_buffers
782        .iter()
783        .map(|context_buffer| {
784            if let Some(refresh_task) = refresh_context_buffer(context_buffer, cx) {
785                stale = true;
786                future::Either::Left(refresh_task)
787            } else {
788                future::Either::Right(future::ready((*context_buffer).clone()))
789            }
790        })
791        .collect::<Vec<_>>();
792
793    if !stale {
794        return None;
795    }
796
797    let context_buffers = future::join_all(futures);
798
799    let id = directory_context.snapshot.id;
800    let path = directory_context.path.clone();
801    Some(cx.spawn(async move |cx| {
802        let context_buffers = context_buffers.await;
803        context_store
804            .update(cx, |context_store, _| {
805                let new_directory_context = DirectoryContext::new(id, path, context_buffers);
806                context_store.replace_context(AssistantContext::Directory(new_directory_context));
807            })
808            .ok();
809    }))
810}
811
812fn refresh_symbol_text(
813    context_store: Entity<ContextStore>,
814    symbol_context: &SymbolContext,
815    cx: &App,
816) -> Option<Task<()>> {
817    let id = symbol_context.id;
818    let task = refresh_context_symbol(&symbol_context.context_symbol, cx);
819    if let Some(task) = task {
820        Some(cx.spawn(async move |cx| {
821            let context_symbol = task.await;
822            context_store
823                .update(cx, |context_store, _| {
824                    let new_symbol_context = SymbolContext { id, context_symbol };
825                    context_store.replace_context(AssistantContext::Symbol(new_symbol_context));
826                })
827                .ok();
828        }))
829    } else {
830        None
831    }
832}
833
834fn refresh_thread_text(
835    context_store: Entity<ContextStore>,
836    thread_context: &ThreadContext,
837    cx: &App,
838) -> Task<()> {
839    let id = thread_context.id;
840    let thread = thread_context.thread.clone();
841    cx.spawn(async move |cx| {
842        context_store
843            .update(cx, |context_store, cx| {
844                let text = thread.read(cx).text().into();
845                context_store.replace_context(AssistantContext::Thread(ThreadContext {
846                    id,
847                    thread,
848                    text,
849                }));
850            })
851            .ok();
852    })
853}
854
855fn refresh_context_buffer(
856    context_buffer: &ContextBuffer,
857    cx: &App,
858) -> Option<impl Future<Output = ContextBuffer> + use<>> {
859    let buffer = context_buffer.buffer.read(cx);
860    let path = buffer_path_log_err(buffer)?;
861    if buffer.version.changed_since(&context_buffer.version) {
862        let (buffer_info, text_task) = collect_buffer_info_and_text(
863            path,
864            context_buffer.buffer.clone(),
865            buffer,
866            None,
867            cx.to_async(),
868        );
869        Some(text_task.map(move |text| make_context_buffer(buffer_info, text)))
870    } else {
871        None
872    }
873}
874
875fn refresh_context_symbol(
876    context_symbol: &ContextSymbol,
877    cx: &App,
878) -> Option<impl Future<Output = ContextSymbol> + use<>> {
879    let buffer = context_symbol.buffer.read(cx);
880    let path = buffer_path_log_err(buffer)?;
881    let project_path = buffer.project_path(cx)?;
882    if buffer.version.changed_since(&context_symbol.buffer_version) {
883        let (buffer_info, text_task) = collect_buffer_info_and_text(
884            path,
885            context_symbol.buffer.clone(),
886            buffer,
887            Some(context_symbol.enclosing_range.clone()),
888            cx.to_async(),
889        );
890        let name = context_symbol.id.name.clone();
891        let range = context_symbol.id.range.clone();
892        let enclosing_range = context_symbol.enclosing_range.clone();
893        Some(text_task.map(move |text| {
894            make_context_symbol(
895                buffer_info,
896                project_path,
897                name,
898                range,
899                enclosing_range,
900                text,
901            )
902        }))
903    } else {
904        None
905    }
906}