1use std::ops::Range;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4
5use anyhow::{Result, anyhow, bail};
6use collections::{BTreeMap, HashMap, HashSet};
7use futures::{self, Future, FutureExt, future};
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, cx) {
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, cx).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, cx: &App) -> Option<Arc<Path>> {
624 if let Some(file) = buffer.file() {
625 let mut path = file.path().clone();
626
627 if path.as_os_str().is_empty() {
628 path = file.full_path(cx).into();
629 }
630 Some(path)
631 } else {
632 log::error!("Buffer that had a path unexpectedly no longer has a path.");
633 None
634 }
635}
636
637fn to_fenced_codeblock(path: &Path, content: Rope) -> SharedString {
638 let path_extension = path.extension().and_then(|ext| ext.to_str());
639 let path_string = path.to_string_lossy();
640 let capacity = 3
641 + path_extension.map_or(0, |extension| extension.len() + 1)
642 + path_string.len()
643 + 1
644 + content.len()
645 + 5;
646 let mut buffer = String::with_capacity(capacity);
647
648 buffer.push_str("```");
649
650 if let Some(extension) = path_extension {
651 buffer.push_str(extension);
652 buffer.push(' ');
653 }
654 buffer.push_str(&path_string);
655
656 buffer.push('\n');
657 for chunk in content.chunks() {
658 buffer.push_str(&chunk);
659 }
660
661 if !buffer.ends_with('\n') {
662 buffer.push('\n');
663 }
664
665 buffer.push_str("```\n");
666
667 debug_assert!(
668 buffer.len() == capacity - 1 || buffer.len() == capacity,
669 "to_fenced_codeblock calculated capacity of {}, but length was {}",
670 capacity,
671 buffer.len(),
672 );
673
674 buffer.into()
675}
676
677fn collect_files_in_path(worktree: &Worktree, path: &Path) -> Vec<Arc<Path>> {
678 let mut files = Vec::new();
679
680 for entry in worktree.child_entries(path) {
681 if entry.is_dir() {
682 files.extend(collect_files_in_path(worktree, &entry.path));
683 } else if entry.is_file() {
684 files.push(entry.path.clone());
685 }
686 }
687
688 files
689}
690
691pub fn refresh_context_store_text(
692 context_store: Entity<ContextStore>,
693 changed_buffers: &HashSet<Entity<Buffer>>,
694 cx: &App,
695) -> impl Future<Output = Vec<ContextId>> + use<> {
696 let mut tasks = Vec::new();
697
698 for context in &context_store.read(cx).context {
699 let id = context.id();
700
701 let task = maybe!({
702 match context {
703 AssistantContext::File(file_context) => {
704 if changed_buffers.is_empty()
705 || changed_buffers.contains(&file_context.context_buffer.buffer)
706 {
707 let context_store = context_store.clone();
708 return refresh_file_text(context_store, file_context, cx);
709 }
710 }
711 AssistantContext::Directory(directory_context) => {
712 let should_refresh = changed_buffers.is_empty()
713 || changed_buffers.iter().any(|buffer| {
714 let buffer = buffer.read(cx);
715
716 buffer_path_log_err(&buffer, cx).map_or(false, |path| {
717 path.starts_with(&directory_context.path.path)
718 })
719 });
720
721 if should_refresh {
722 let context_store = context_store.clone();
723 return refresh_directory_text(context_store, directory_context, cx);
724 }
725 }
726 AssistantContext::Symbol(symbol_context) => {
727 if changed_buffers.is_empty()
728 || changed_buffers.contains(&symbol_context.context_symbol.buffer)
729 {
730 let context_store = context_store.clone();
731 return refresh_symbol_text(context_store, symbol_context, cx);
732 }
733 }
734 AssistantContext::Thread(thread_context) => {
735 if changed_buffers.is_empty() {
736 let context_store = context_store.clone();
737 return Some(refresh_thread_text(context_store, thread_context, cx));
738 }
739 }
740 // Intentionally omit refreshing fetched URLs as it doesn't seem all that useful,
741 // and doing the caching properly could be tricky (unless it's already handled by
742 // the HttpClient?).
743 AssistantContext::FetchedUrl(_) => {}
744 }
745
746 None
747 });
748
749 if let Some(task) = task {
750 tasks.push(task.map(move |_| id));
751 }
752 }
753
754 future::join_all(tasks)
755}
756
757fn refresh_file_text(
758 context_store: Entity<ContextStore>,
759 file_context: &FileContext,
760 cx: &App,
761) -> Option<Task<()>> {
762 let id = file_context.id;
763 let task = refresh_context_buffer(&file_context.context_buffer, cx);
764 if let Some(task) = task {
765 Some(cx.spawn(async move |cx| {
766 let context_buffer = task.await;
767 context_store
768 .update(cx, |context_store, _| {
769 let new_file_context = FileContext { id, context_buffer };
770 context_store.replace_context(AssistantContext::File(new_file_context));
771 })
772 .ok();
773 }))
774 } else {
775 None
776 }
777}
778
779fn refresh_directory_text(
780 context_store: Entity<ContextStore>,
781 directory_context: &DirectoryContext,
782 cx: &App,
783) -> Option<Task<()>> {
784 let mut stale = false;
785 let futures = directory_context
786 .context_buffers
787 .iter()
788 .map(|context_buffer| {
789 if let Some(refresh_task) = refresh_context_buffer(context_buffer, cx) {
790 stale = true;
791 future::Either::Left(refresh_task)
792 } else {
793 future::Either::Right(future::ready((*context_buffer).clone()))
794 }
795 })
796 .collect::<Vec<_>>();
797
798 if !stale {
799 return None;
800 }
801
802 let context_buffers = future::join_all(futures);
803
804 let id = directory_context.snapshot.id;
805 let path = directory_context.path.clone();
806 Some(cx.spawn(async move |cx| {
807 let context_buffers = context_buffers.await;
808 context_store
809 .update(cx, |context_store, _| {
810 let new_directory_context = DirectoryContext::new(id, path, context_buffers);
811 context_store.replace_context(AssistantContext::Directory(new_directory_context));
812 })
813 .ok();
814 }))
815}
816
817fn refresh_symbol_text(
818 context_store: Entity<ContextStore>,
819 symbol_context: &SymbolContext,
820 cx: &App,
821) -> Option<Task<()>> {
822 let id = symbol_context.id;
823 let task = refresh_context_symbol(&symbol_context.context_symbol, cx);
824 if let Some(task) = task {
825 Some(cx.spawn(async move |cx| {
826 let context_symbol = task.await;
827 context_store
828 .update(cx, |context_store, _| {
829 let new_symbol_context = SymbolContext { id, context_symbol };
830 context_store.replace_context(AssistantContext::Symbol(new_symbol_context));
831 })
832 .ok();
833 }))
834 } else {
835 None
836 }
837}
838
839fn refresh_thread_text(
840 context_store: Entity<ContextStore>,
841 thread_context: &ThreadContext,
842 cx: &App,
843) -> Task<()> {
844 let id = thread_context.id;
845 let thread = thread_context.thread.clone();
846 cx.spawn(async move |cx| {
847 context_store
848 .update(cx, |context_store, cx| {
849 let text = thread.read(cx).text().into();
850 context_store.replace_context(AssistantContext::Thread(ThreadContext {
851 id,
852 thread,
853 text,
854 }));
855 })
856 .ok();
857 })
858}
859
860fn refresh_context_buffer(
861 context_buffer: &ContextBuffer,
862 cx: &App,
863) -> Option<impl Future<Output = ContextBuffer> + use<>> {
864 let buffer = context_buffer.buffer.read(cx);
865 let path = buffer_path_log_err(buffer, cx)?;
866 if buffer.version.changed_since(&context_buffer.version) {
867 let (buffer_info, text_task) = collect_buffer_info_and_text(
868 path,
869 context_buffer.buffer.clone(),
870 buffer,
871 None,
872 cx.to_async(),
873 );
874 Some(text_task.map(move |text| make_context_buffer(buffer_info, text)))
875 } else {
876 None
877 }
878}
879
880fn refresh_context_symbol(
881 context_symbol: &ContextSymbol,
882 cx: &App,
883) -> Option<impl Future<Output = ContextSymbol> + use<>> {
884 let buffer = context_symbol.buffer.read(cx);
885 let path = buffer_path_log_err(buffer, cx)?;
886 let project_path = buffer.project_path(cx)?;
887 if buffer.version.changed_since(&context_symbol.buffer_version) {
888 let (buffer_info, text_task) = collect_buffer_info_and_text(
889 path,
890 context_symbol.buffer.clone(),
891 buffer,
892 Some(context_symbol.enclosing_range.clone()),
893 cx.to_async(),
894 );
895 let name = context_symbol.id.name.clone();
896 let range = context_symbol.id.range.clone();
897 let enclosing_range = context_symbol.enclosing_range.clone();
898 Some(text_task.map(move |text| {
899 make_context_symbol(
900 buffer_info,
901 project_path,
902 name,
903 range,
904 enclosing_range,
905 text,
906 )
907 }))
908 } else {
909 None
910 }
911}