context.rs

  1use std::rc::Rc;
  2use std::{ops::Range, path::Path};
  3
  4use file_icons::FileIcons;
  5use gpui::{App, Entity, SharedString};
  6use language::Buffer;
  7use language_model::{LanguageModelRequestMessage, MessageContent};
  8use project::ProjectPath;
  9use serde::{Deserialize, Serialize};
 10use text::{Anchor, BufferId};
 11use ui::IconName;
 12use util::post_inc;
 13
 14use crate::{context_store::buffer_path_log_err, thread::Thread};
 15
 16#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
 17pub struct ContextId(pub(crate) usize);
 18
 19impl ContextId {
 20    pub fn post_inc(&mut self) -> Self {
 21        Self(post_inc(&mut self.0))
 22    }
 23}
 24
 25/// Some context attached to a message in a thread.
 26#[derive(Debug, Clone)]
 27pub struct ContextSnapshot {
 28    pub id: ContextId,
 29    pub name: SharedString,
 30    pub parent: Option<SharedString>,
 31    pub tooltip: Option<SharedString>,
 32    pub icon_path: Option<SharedString>,
 33    pub kind: ContextKind,
 34    /// Joining these strings separated by \n yields text for model. Not refreshed by `snapshot`.
 35    pub text: Box<[SharedString]>,
 36}
 37
 38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 39pub enum ContextKind {
 40    File,
 41    Directory,
 42    Symbol,
 43    FetchedUrl,
 44    Thread,
 45}
 46
 47impl ContextKind {
 48    pub fn icon(&self) -> IconName {
 49        match self {
 50            ContextKind::File => IconName::File,
 51            ContextKind::Directory => IconName::Folder,
 52            ContextKind::Symbol => IconName::Code,
 53            ContextKind::FetchedUrl => IconName::Globe,
 54            ContextKind::Thread => IconName::MessageCircle,
 55        }
 56    }
 57}
 58
 59#[derive(Debug)]
 60pub enum AssistantContext {
 61    File(FileContext),
 62    Directory(DirectoryContext),
 63    Symbol(SymbolContext),
 64    FetchedUrl(FetchedUrlContext),
 65    Thread(ThreadContext),
 66}
 67
 68impl AssistantContext {
 69    pub fn id(&self) -> ContextId {
 70        match self {
 71            Self::File(file) => file.id,
 72            Self::Directory(directory) => directory.snapshot.id,
 73            Self::Symbol(symbol) => symbol.id,
 74            Self::FetchedUrl(url) => url.id,
 75            Self::Thread(thread) => thread.id,
 76        }
 77    }
 78}
 79
 80#[derive(Debug)]
 81pub struct FileContext {
 82    pub id: ContextId,
 83    pub context_buffer: ContextBuffer,
 84}
 85
 86#[derive(Debug)]
 87pub struct DirectoryContext {
 88    pub path: Rc<Path>,
 89    pub context_buffers: Vec<ContextBuffer>,
 90    pub snapshot: ContextSnapshot,
 91}
 92
 93#[derive(Debug)]
 94pub struct SymbolContext {
 95    pub id: ContextId,
 96    pub context_symbol: ContextSymbol,
 97}
 98
 99#[derive(Debug)]
100pub struct FetchedUrlContext {
101    pub id: ContextId,
102    pub url: SharedString,
103    pub text: SharedString,
104}
105
106// TODO: Model<Thread> holds onto the thread even if the thread is deleted. Can either handle this
107// explicitly or have a WeakModel<Thread> and remove during snapshot.
108
109#[derive(Debug)]
110pub struct ThreadContext {
111    pub id: ContextId,
112    pub thread: Entity<Thread>,
113    pub text: SharedString,
114}
115
116// TODO: Model<Buffer> holds onto the buffer even if the file is deleted and closed. Should remove
117// the context from the message editor in this case.
118
119#[derive(Debug, Clone)]
120pub struct ContextBuffer {
121    pub id: BufferId,
122    pub buffer: Entity<Buffer>,
123    pub version: clock::Global,
124    pub text: SharedString,
125}
126
127#[derive(Debug, Clone)]
128pub struct ContextSymbol {
129    pub id: ContextSymbolId,
130    pub buffer: Entity<Buffer>,
131    pub buffer_version: clock::Global,
132    /// The range that the symbol encloses, e.g. for function symbol, this will
133    /// include not only the signature, but also the body
134    pub enclosing_range: Range<Anchor>,
135    pub text: SharedString,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq, Hash)]
139pub struct ContextSymbolId {
140    pub path: ProjectPath,
141    pub name: SharedString,
142    pub range: Range<Anchor>,
143}
144
145impl AssistantContext {
146    pub fn snapshot(&self, cx: &App) -> Option<ContextSnapshot> {
147        match &self {
148            Self::File(file_context) => file_context.snapshot(cx),
149            Self::Directory(directory_context) => Some(directory_context.snapshot()),
150            Self::Symbol(symbol_context) => symbol_context.snapshot(cx),
151            Self::FetchedUrl(fetched_url_context) => Some(fetched_url_context.snapshot()),
152            Self::Thread(thread_context) => Some(thread_context.snapshot(cx)),
153        }
154    }
155}
156
157impl FileContext {
158    pub fn snapshot(&self, cx: &App) -> Option<ContextSnapshot> {
159        let buffer = self.context_buffer.buffer.read(cx);
160        let path = buffer_path_log_err(buffer)?;
161        let full_path: SharedString = path.to_string_lossy().into_owned().into();
162        let name = match path.file_name() {
163            Some(name) => name.to_string_lossy().into_owned().into(),
164            None => full_path.clone(),
165        };
166        let parent = path
167            .parent()
168            .and_then(|p| p.file_name())
169            .map(|p| p.to_string_lossy().into_owned().into());
170
171        let icon_path = FileIcons::get_icon(&path, cx);
172
173        Some(ContextSnapshot {
174            id: self.id,
175            name,
176            parent,
177            tooltip: Some(full_path),
178            icon_path,
179            kind: ContextKind::File,
180            text: Box::new([self.context_buffer.text.clone()]),
181        })
182    }
183}
184
185impl DirectoryContext {
186    pub fn new(
187        id: ContextId,
188        path: &Path,
189        context_buffers: Vec<ContextBuffer>,
190    ) -> DirectoryContext {
191        let full_path: SharedString = path.to_string_lossy().into_owned().into();
192
193        let name = match path.file_name() {
194            Some(name) => name.to_string_lossy().into_owned().into(),
195            None => full_path.clone(),
196        };
197
198        let parent = path
199            .parent()
200            .and_then(|p| p.file_name())
201            .map(|p| p.to_string_lossy().into_owned().into());
202
203        // TODO: include directory path in text?
204        let text = context_buffers
205            .iter()
206            .map(|b| b.text.clone())
207            .collect::<Vec<_>>()
208            .into();
209
210        DirectoryContext {
211            path: path.into(),
212            context_buffers,
213            snapshot: ContextSnapshot {
214                id,
215                name,
216                parent,
217                tooltip: Some(full_path),
218                icon_path: None,
219                kind: ContextKind::Directory,
220                text,
221            },
222        }
223    }
224
225    pub fn snapshot(&self) -> ContextSnapshot {
226        self.snapshot.clone()
227    }
228}
229
230impl SymbolContext {
231    pub fn snapshot(&self, cx: &App) -> Option<ContextSnapshot> {
232        let buffer = self.context_symbol.buffer.read(cx);
233        let name = self.context_symbol.id.name.clone();
234        let path = buffer_path_log_err(buffer)?
235            .to_string_lossy()
236            .into_owned()
237            .into();
238
239        Some(ContextSnapshot {
240            id: self.id,
241            name,
242            parent: Some(path),
243            tooltip: None,
244            icon_path: None,
245            kind: ContextKind::Symbol,
246            text: Box::new([self.context_symbol.text.clone()]),
247        })
248    }
249}
250
251impl FetchedUrlContext {
252    pub fn snapshot(&self) -> ContextSnapshot {
253        ContextSnapshot {
254            id: self.id,
255            name: self.url.clone(),
256            parent: None,
257            tooltip: None,
258            icon_path: None,
259            kind: ContextKind::FetchedUrl,
260            text: Box::new([self.text.clone()]),
261        }
262    }
263}
264
265impl ThreadContext {
266    pub fn snapshot(&self, cx: &App) -> ContextSnapshot {
267        let thread = self.thread.read(cx);
268        ContextSnapshot {
269            id: self.id,
270            name: thread.summary().unwrap_or("New thread".into()),
271            parent: None,
272            tooltip: None,
273            icon_path: None,
274            kind: ContextKind::Thread,
275            text: Box::new([self.text.clone()]),
276        }
277    }
278}
279
280pub fn attach_context_to_message(
281    message: &mut LanguageModelRequestMessage,
282    contexts: impl Iterator<Item = ContextSnapshot>,
283) {
284    let mut file_context = Vec::new();
285    let mut directory_context = Vec::new();
286    let mut symbol_context = Vec::new();
287    let mut fetch_context = Vec::new();
288    let mut thread_context = Vec::new();
289
290    let mut capacity = 0;
291    for context in contexts {
292        capacity += context.text.len();
293        match context.kind {
294            ContextKind::File => file_context.push(context),
295            ContextKind::Directory => directory_context.push(context),
296            ContextKind::Symbol => symbol_context.push(context),
297            ContextKind::FetchedUrl => fetch_context.push(context),
298            ContextKind::Thread => thread_context.push(context),
299        }
300    }
301    if !file_context.is_empty() {
302        capacity += 1;
303    }
304    if !directory_context.is_empty() {
305        capacity += 1;
306    }
307    if !symbol_context.is_empty() {
308        capacity += 1;
309    }
310    if !fetch_context.is_empty() {
311        capacity += 1 + fetch_context.len();
312    }
313    if !thread_context.is_empty() {
314        capacity += 1 + thread_context.len();
315    }
316    if capacity == 0 {
317        return;
318    }
319
320    let mut context_chunks = Vec::with_capacity(capacity);
321
322    if !file_context.is_empty() {
323        context_chunks.push("The following files are available:\n");
324        for context in &file_context {
325            for chunk in &context.text {
326                context_chunks.push(&chunk);
327            }
328        }
329    }
330
331    if !directory_context.is_empty() {
332        context_chunks.push("The following directories are available:\n");
333        for context in &directory_context {
334            for chunk in &context.text {
335                context_chunks.push(&chunk);
336            }
337        }
338    }
339
340    if !symbol_context.is_empty() {
341        context_chunks.push("The following symbols are available:\n");
342        for context in &symbol_context {
343            for chunk in &context.text {
344                context_chunks.push(&chunk);
345            }
346        }
347    }
348
349    if !fetch_context.is_empty() {
350        context_chunks.push("The following fetched results are available:\n");
351        for context in &fetch_context {
352            context_chunks.push(&context.name);
353            for chunk in &context.text {
354                context_chunks.push(&chunk);
355            }
356        }
357    }
358
359    if !thread_context.is_empty() {
360        context_chunks.push("The following previous conversation threads are available:\n");
361        for context in &thread_context {
362            context_chunks.push(&context.name);
363            for chunk in &context.text {
364                context_chunks.push(&chunk);
365            }
366        }
367    }
368
369    debug_assert!(
370        context_chunks.len() == capacity,
371        "attach_context_message calculated capacity of {}, but length was {}",
372        capacity,
373        context_chunks.len()
374    );
375
376    if !context_chunks.is_empty() {
377        message
378            .content
379            .push(MessageContent::Text(context_chunks.join("\n")));
380    }
381}