1use std::fmt::Write;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::time::Duration;
5
6use anyhow::{anyhow, Result};
7use fs::Fs;
8use gpui::{AsyncAppContext, ModelContext, Task, WeakModel};
9use project::{Project, ProjectPath};
10use util::ResultExt;
11
12use crate::ambient_context::ContextUpdated;
13use crate::assistant_panel::Conversation;
14use crate::{LanguageModelRequestMessage, Role};
15
16/// Ambient context about the current project.
17pub struct CurrentProjectContext {
18 pub enabled: bool,
19 pub message: String,
20 pub pending_message: Option<Task<()>>,
21}
22
23#[allow(clippy::derivable_impls)]
24impl Default for CurrentProjectContext {
25 fn default() -> Self {
26 Self {
27 enabled: false,
28 message: String::new(),
29 pending_message: None,
30 }
31 }
32}
33
34impl CurrentProjectContext {
35 /// Returns the [`CurrentProjectContext`] as a message to the language model.
36 pub fn to_message(&self) -> Option<LanguageModelRequestMessage> {
37 self.enabled.then(|| LanguageModelRequestMessage {
38 role: Role::System,
39 content: self.message.clone(),
40 })
41 }
42
43 /// Updates the [`CurrentProjectContext`] for the given [`Project`].
44 pub fn update(
45 &mut self,
46 fs: Arc<dyn Fs>,
47 project: WeakModel<Project>,
48 cx: &mut ModelContext<Conversation>,
49 ) -> ContextUpdated {
50 if !self.enabled {
51 self.message.clear();
52 self.pending_message = None;
53 cx.notify();
54 return ContextUpdated::Disabled;
55 }
56
57 self.pending_message = Some(cx.spawn(|conversation, mut cx| async move {
58 const DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
59 cx.background_executor().timer(DEBOUNCE_TIMEOUT).await;
60
61 let Some(path_to_cargo_toml) = Self::path_to_cargo_toml(project, &mut cx).log_err()
62 else {
63 return;
64 };
65
66 let Some(path_to_cargo_toml) = path_to_cargo_toml
67 .ok_or_else(|| anyhow!("no Cargo.toml"))
68 .log_err()
69 else {
70 return;
71 };
72
73 let message_task = cx
74 .background_executor()
75 .spawn(async move { Self::build_message(fs, &path_to_cargo_toml).await });
76
77 if let Some(message) = message_task.await.log_err() {
78 conversation
79 .update(&mut cx, |conversation, cx| {
80 conversation.ambient_context.current_project.message = message;
81 conversation.count_remaining_tokens(cx);
82 cx.notify();
83 })
84 .log_err();
85 }
86 }));
87
88 ContextUpdated::Updating
89 }
90
91 async fn build_message(fs: Arc<dyn Fs>, path_to_cargo_toml: &Path) -> Result<String> {
92 let buffer = fs.load(path_to_cargo_toml).await?;
93 let cargo_toml: cargo_toml::Manifest = toml::from_str(&buffer)?;
94
95 let mut message = String::new();
96 writeln!(message, "You are in a Rust project.")?;
97
98 if let Some(workspace) = cargo_toml.workspace {
99 writeln!(
100 message,
101 "The project is a Cargo workspace with the following members:"
102 )?;
103 for member in workspace.members {
104 writeln!(message, "- {member}")?;
105 }
106
107 if !workspace.default_members.is_empty() {
108 writeln!(message, "The default members are:")?;
109 for member in workspace.default_members {
110 writeln!(message, "- {member}")?;
111 }
112 }
113
114 if !workspace.dependencies.is_empty() {
115 writeln!(
116 message,
117 "The following workspace dependencies are installed:"
118 )?;
119 for dependency in workspace.dependencies.keys() {
120 writeln!(message, "- {dependency}")?;
121 }
122 }
123 } else if let Some(package) = cargo_toml.package {
124 writeln!(
125 message,
126 "The project name is \"{name}\".",
127 name = package.name
128 )?;
129
130 let description = package
131 .description
132 .as_ref()
133 .and_then(|description| description.get().ok().cloned());
134 if let Some(description) = description.as_ref() {
135 writeln!(message, "It describes itself as \"{description}\".")?;
136 }
137
138 if !cargo_toml.dependencies.is_empty() {
139 writeln!(message, "The following dependencies are installed:")?;
140 for dependency in cargo_toml.dependencies.keys() {
141 writeln!(message, "- {dependency}")?;
142 }
143 }
144 }
145
146 Ok(message)
147 }
148
149 fn path_to_cargo_toml(
150 project: WeakModel<Project>,
151 cx: &mut AsyncAppContext,
152 ) -> Result<Option<PathBuf>> {
153 cx.update(|cx| {
154 let worktree = project.update(cx, |project, _cx| {
155 project
156 .worktrees()
157 .next()
158 .ok_or_else(|| anyhow!("no worktree"))
159 })??;
160
161 let path_to_cargo_toml = worktree.update(cx, |worktree, _cx| {
162 let cargo_toml = worktree.entry_for_path("Cargo.toml")?;
163 Some(ProjectPath {
164 worktree_id: worktree.id(),
165 path: cargo_toml.path.clone(),
166 })
167 });
168 let path_to_cargo_toml = path_to_cargo_toml.and_then(|path| {
169 project
170 .update(cx, |project, cx| project.absolute_path(&path, cx))
171 .ok()
172 .flatten()
173 });
174
175 Ok(path_to_cargo_toml)
176 })?
177 }
178}