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, 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_model = open_buffer_task.await?;
83 let buffer_id = this.update(&mut cx, |_, cx| buffer_model.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_model.read(cx);
102 collect_buffer_info_and_text(
103 project_path.path.clone(),
104 buffer_model,
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_model: 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_model.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_model,
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_model) in files.into_iter().zip(buffers) {
211 let buffer_model = buffer_model?;
212 let buffer = buffer_model.read(cx);
213 let (buffer_info, text_task) =
214 collect_buffer_info_and_text(path, buffer_model, 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_model: 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_model,
441 version: info.version,
442 text,
443 }
444}
445
446fn collect_buffer_info_and_text(
447 path: Arc<Path>,
448 buffer_model: Entity<Buffer>,
449 buffer: &Buffer,
450 cx: AsyncApp,
451) -> (BufferInfo, Task<SharedString>) {
452 let buffer_info = BufferInfo {
453 id: buffer.remote_id(),
454 buffer_model,
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
460 .background_executor()
461 .spawn(async move { to_fenced_codeblock(&path, content) });
462 (buffer_info, text_task)
463}
464
465pub fn buffer_path_log_err(buffer: &Buffer) -> Option<Arc<Path>> {
466 if let Some(file) = buffer.file() {
467 Some(file.path().clone())
468 } else {
469 log::error!("Buffer that had a path unexpectedly no longer has a path.");
470 None
471 }
472}
473
474fn to_fenced_codeblock(path: &Path, content: Rope) -> SharedString {
475 let path_extension = path.extension().and_then(|ext| ext.to_str());
476 let path_string = path.to_string_lossy();
477 let capacity = 3
478 + path_extension.map_or(0, |extension| extension.len() + 1)
479 + path_string.len()
480 + 1
481 + content.len()
482 + 5;
483 let mut buffer = String::with_capacity(capacity);
484
485 buffer.push_str("```");
486
487 if let Some(extension) = path_extension {
488 buffer.push_str(extension);
489 buffer.push(' ');
490 }
491 buffer.push_str(&path_string);
492
493 buffer.push('\n');
494 for chunk in content.chunks() {
495 buffer.push_str(&chunk);
496 }
497
498 if !buffer.ends_with('\n') {
499 buffer.push('\n');
500 }
501
502 buffer.push_str("```\n");
503
504 debug_assert!(
505 buffer.len() == capacity - 1 || buffer.len() == capacity,
506 "to_fenced_codeblock calculated capacity of {}, but length was {}",
507 capacity,
508 buffer.len(),
509 );
510
511 buffer.into()
512}
513
514fn collect_files_in_path(worktree: &Worktree, path: &Path) -> Vec<Arc<Path>> {
515 let mut files = Vec::new();
516
517 for entry in worktree.child_entries(path) {
518 if entry.is_dir() {
519 files.extend(collect_files_in_path(worktree, &entry.path));
520 } else if entry.is_file() {
521 files.push(entry.path.clone());
522 }
523 }
524
525 files
526}
527
528pub fn refresh_context_store_text(
529 context_store: Entity<ContextStore>,
530 cx: &App,
531) -> impl Future<Output = ()> {
532 let mut tasks = Vec::new();
533 for context in &context_store.read(cx).context {
534 match context {
535 AssistantContext::File(file_context) => {
536 let context_store = context_store.clone();
537 if let Some(task) = refresh_file_text(context_store, file_context, cx) {
538 tasks.push(task);
539 }
540 }
541 AssistantContext::Directory(directory_context) => {
542 let context_store = context_store.clone();
543 if let Some(task) = refresh_directory_text(context_store, directory_context, cx) {
544 tasks.push(task);
545 }
546 }
547 AssistantContext::Thread(thread_context) => {
548 let context_store = context_store.clone();
549 tasks.push(refresh_thread_text(context_store, thread_context, cx));
550 }
551 // Intentionally omit refreshing fetched URLs as it doesn't seem all that useful,
552 // and doing the caching properly could be tricky (unless it's already handled by
553 // the HttpClient?).
554 AssistantContext::FetchedUrl(_) => {}
555 }
556 }
557
558 future::join_all(tasks).map(|_| ())
559}
560
561fn refresh_file_text(
562 context_store: Entity<ContextStore>,
563 file_context: &FileContext,
564 cx: &App,
565) -> Option<Task<()>> {
566 let id = file_context.id;
567 let task = refresh_context_buffer(&file_context.context_buffer, cx);
568 if let Some(task) = task {
569 Some(cx.spawn(|mut cx| async move {
570 let context_buffer = task.await;
571 context_store
572 .update(&mut cx, |context_store, _| {
573 let new_file_context = FileContext { id, context_buffer };
574 context_store.replace_context(AssistantContext::File(new_file_context));
575 })
576 .ok();
577 }))
578 } else {
579 None
580 }
581}
582
583fn refresh_directory_text(
584 context_store: Entity<ContextStore>,
585 directory_context: &DirectoryContext,
586 cx: &App,
587) -> Option<Task<()>> {
588 let mut stale = false;
589 let futures = directory_context
590 .context_buffers
591 .iter()
592 .map(|context_buffer| {
593 if let Some(refresh_task) = refresh_context_buffer(context_buffer, cx) {
594 stale = true;
595 future::Either::Left(refresh_task)
596 } else {
597 future::Either::Right(future::ready((*context_buffer).clone()))
598 }
599 })
600 .collect::<Vec<_>>();
601
602 if !stale {
603 return None;
604 }
605
606 let context_buffers = future::join_all(futures);
607
608 let id = directory_context.snapshot.id;
609 let path = directory_context.path.clone();
610 Some(cx.spawn(|mut cx| async move {
611 let context_buffers = context_buffers.await;
612 context_store
613 .update(&mut cx, |context_store, _| {
614 let new_directory_context = DirectoryContext::new(id, &path, context_buffers);
615 context_store.replace_context(AssistantContext::Directory(new_directory_context));
616 })
617 .ok();
618 }))
619}
620
621fn refresh_thread_text(
622 context_store: Entity<ContextStore>,
623 thread_context: &ThreadContext,
624 cx: &App,
625) -> Task<()> {
626 let id = thread_context.id;
627 let thread = thread_context.thread.clone();
628 cx.spawn(move |mut cx| async move {
629 context_store
630 .update(&mut cx, |context_store, cx| {
631 let text = thread.read(cx).text().into();
632 context_store.replace_context(AssistantContext::Thread(ThreadContext {
633 id,
634 thread,
635 text,
636 }));
637 })
638 .ok();
639 })
640}
641
642fn refresh_context_buffer(
643 context_buffer: &ContextBuffer,
644 cx: &App,
645) -> Option<impl Future<Output = ContextBuffer>> {
646 let buffer = context_buffer.buffer.read(cx);
647 let path = buffer_path_log_err(buffer)?;
648 if buffer.version.changed_since(&context_buffer.version) {
649 let (buffer_info, text_task) = collect_buffer_info_and_text(
650 path,
651 context_buffer.buffer.clone(),
652 buffer,
653 cx.to_async(),
654 );
655 Some(text_task.map(move |text| make_context_buffer(buffer_info, text)))
656 } else {
657 None
658 }
659}