context_store.rs

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