1use crate::{DbThread, DbThreadMetadata, ThreadsDatabase};
2use acp_thread::MentionUri;
3use agent_client_protocol as acp;
4use anyhow::{Context as _, Result, anyhow};
5use assistant_text_thread::{SavedTextThreadMetadata, TextThread};
6use chrono::{DateTime, Utc};
7use db::kvp::KEY_VALUE_STORE;
8use gpui::{App, AsyncApp, Entity, SharedString, Task, prelude::*};
9use itertools::Itertools;
10use paths::text_threads_dir;
11use project::Project;
12use serde::{Deserialize, Serialize};
13use std::{collections::VecDeque, path::Path, rc::Rc, sync::Arc, time::Duration};
14use ui::ElementId;
15use util::ResultExt as _;
16
17const MAX_RECENTLY_OPENED_ENTRIES: usize = 6;
18const RECENTLY_OPENED_THREADS_KEY: &str = "recent-agent-threads";
19const SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE: Duration = Duration::from_millis(50);
20
21const DEFAULT_TITLE: &SharedString = &SharedString::new_static("New Thread");
22
23//todo: We should remove this function once we support loading all acp thread
24pub fn load_agent_thread(
25 session_id: acp::SessionId,
26 history_store: Entity<HistoryStore>,
27 project: Entity<Project>,
28 cx: &mut App,
29) -> Task<Result<Entity<crate::Thread>>> {
30 use agent_servers::{AgentServer, AgentServerDelegate};
31
32 let server = Rc::new(crate::NativeAgentServer::new(
33 project.read(cx).fs().clone(),
34 history_store,
35 ));
36 let delegate = AgentServerDelegate::new(
37 project.read(cx).agent_server_store().clone(),
38 project.clone(),
39 None,
40 None,
41 );
42 let connection = server.connect(None, delegate, cx);
43 cx.spawn(async move |cx| {
44 let (agent, _) = connection.await?;
45 let agent = agent.downcast::<crate::NativeAgentConnection>().unwrap();
46 cx.update(|cx| agent.load_thread(session_id, cx))?.await
47 })
48}
49
50#[derive(Clone, Debug)]
51pub enum HistoryEntry {
52 AcpThread(DbThreadMetadata),
53 TextThread(SavedTextThreadMetadata),
54}
55
56impl HistoryEntry {
57 pub fn updated_at(&self) -> DateTime<Utc> {
58 match self {
59 HistoryEntry::AcpThread(thread) => thread.updated_at,
60 HistoryEntry::TextThread(text_thread) => text_thread.mtime.to_utc(),
61 }
62 }
63
64 pub fn id(&self) -> HistoryEntryId {
65 match self {
66 HistoryEntry::AcpThread(thread) => HistoryEntryId::AcpThread(thread.id.clone()),
67 HistoryEntry::TextThread(text_thread) => {
68 HistoryEntryId::TextThread(text_thread.path.clone())
69 }
70 }
71 }
72
73 pub fn mention_uri(&self) -> MentionUri {
74 match self {
75 HistoryEntry::AcpThread(thread) => MentionUri::Thread {
76 id: thread.id.clone(),
77 name: thread.title.to_string(),
78 },
79 HistoryEntry::TextThread(text_thread) => MentionUri::TextThread {
80 path: text_thread.path.as_ref().to_owned(),
81 name: text_thread.title.to_string(),
82 },
83 }
84 }
85
86 pub fn title(&self) -> &SharedString {
87 match self {
88 HistoryEntry::AcpThread(thread) => {
89 if thread.title.is_empty() {
90 DEFAULT_TITLE
91 } else {
92 &thread.title
93 }
94 }
95 HistoryEntry::TextThread(text_thread) => &text_thread.title,
96 }
97 }
98}
99
100/// Generic identifier for a history entry.
101#[derive(Clone, PartialEq, Eq, Debug, Hash)]
102pub enum HistoryEntryId {
103 AcpThread(acp::SessionId),
104 TextThread(Arc<Path>),
105}
106
107impl Into<ElementId> for HistoryEntryId {
108 fn into(self) -> ElementId {
109 match self {
110 HistoryEntryId::AcpThread(session_id) => ElementId::Name(session_id.0.into()),
111 HistoryEntryId::TextThread(path) => ElementId::Path(path),
112 }
113 }
114}
115
116#[derive(Serialize, Deserialize, Debug)]
117enum SerializedRecentOpen {
118 AcpThread(String),
119 TextThread(String),
120}
121
122pub struct HistoryStore {
123 threads: Vec<DbThreadMetadata>,
124 entries: Vec<HistoryEntry>,
125 text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
126 recently_opened_entries: VecDeque<HistoryEntryId>,
127 _subscriptions: Vec<gpui::Subscription>,
128 _save_recently_opened_entries_task: Task<()>,
129}
130
131impl HistoryStore {
132 pub fn new(
133 text_thread_store: Entity<assistant_text_thread::TextThreadStore>,
134 cx: &mut Context<Self>,
135 ) -> Self {
136 let subscriptions =
137 vec![cx.observe(&text_thread_store, |this, _, cx| this.update_entries(cx))];
138
139 cx.spawn(async move |this, cx| {
140 let entries = Self::load_recently_opened_entries(cx).await;
141 this.update(cx, |this, cx| {
142 if let Some(entries) = entries.log_err() {
143 this.recently_opened_entries = entries;
144 }
145
146 this.reload(cx);
147 })
148 .ok();
149 })
150 .detach();
151
152 Self {
153 text_thread_store,
154 recently_opened_entries: VecDeque::default(),
155 threads: Vec::default(),
156 entries: Vec::default(),
157 _subscriptions: subscriptions,
158 _save_recently_opened_entries_task: Task::ready(()),
159 }
160 }
161
162 pub fn thread_from_session_id(&self, session_id: &acp::SessionId) -> Option<&DbThreadMetadata> {
163 self.threads.iter().find(|thread| &thread.id == session_id)
164 }
165
166 pub fn load_thread(
167 &mut self,
168 id: acp::SessionId,
169 cx: &mut Context<Self>,
170 ) -> Task<Result<Option<DbThread>>> {
171 let database_future = ThreadsDatabase::connect(cx);
172 cx.background_spawn(async move {
173 let database = database_future.await.map_err(|err| anyhow!(err))?;
174 database.load_thread(id).await
175 })
176 }
177
178 pub fn delete_thread(
179 &mut self,
180 id: acp::SessionId,
181 cx: &mut Context<Self>,
182 ) -> Task<Result<()>> {
183 let database_future = ThreadsDatabase::connect(cx);
184 cx.spawn(async move |this, cx| {
185 let database = database_future.await.map_err(|err| anyhow!(err))?;
186 database.delete_thread(id.clone()).await?;
187 this.update(cx, |this, cx| this.reload(cx))
188 })
189 }
190
191 pub fn delete_text_thread(
192 &mut self,
193 path: Arc<Path>,
194 cx: &mut Context<Self>,
195 ) -> Task<Result<()>> {
196 self.text_thread_store
197 .update(cx, |store, cx| store.delete_local(path, cx))
198 }
199
200 pub fn load_text_thread(
201 &self,
202 path: Arc<Path>,
203 cx: &mut Context<Self>,
204 ) -> Task<Result<Entity<TextThread>>> {
205 self.text_thread_store
206 .update(cx, |store, cx| store.open_local(path, cx))
207 }
208
209 pub fn reload(&self, cx: &mut Context<Self>) {
210 let database_future = ThreadsDatabase::connect(cx);
211 cx.spawn(async move |this, cx| {
212 let threads = database_future
213 .await
214 .map_err(|err| anyhow!(err))?
215 .list_threads()
216 .await?;
217
218 this.update(cx, |this, cx| {
219 if this.recently_opened_entries.len() < MAX_RECENTLY_OPENED_ENTRIES {
220 for thread in threads
221 .iter()
222 .take(MAX_RECENTLY_OPENED_ENTRIES - this.recently_opened_entries.len())
223 .rev()
224 {
225 this.push_recently_opened_entry(
226 HistoryEntryId::AcpThread(thread.id.clone()),
227 cx,
228 )
229 }
230 }
231 this.threads = threads;
232 this.update_entries(cx);
233 })
234 })
235 .detach_and_log_err(cx);
236 }
237
238 fn update_entries(&mut self, cx: &mut Context<Self>) {
239 #[cfg(debug_assertions)]
240 if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
241 return;
242 }
243 let mut history_entries = Vec::new();
244 history_entries.extend(self.threads.iter().cloned().map(HistoryEntry::AcpThread));
245 history_entries.extend(
246 self.text_thread_store
247 .read(cx)
248 .unordered_text_threads()
249 .cloned()
250 .map(HistoryEntry::TextThread),
251 );
252
253 history_entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.updated_at()));
254 self.entries = history_entries;
255 cx.notify()
256 }
257
258 pub fn is_empty(&self, _cx: &App) -> bool {
259 self.entries.is_empty()
260 }
261
262 pub fn recently_opened_entries(&self, cx: &App) -> Vec<HistoryEntry> {
263 #[cfg(debug_assertions)]
264 if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
265 return Vec::new();
266 }
267
268 let thread_entries = self.threads.iter().flat_map(|thread| {
269 self.recently_opened_entries
270 .iter()
271 .enumerate()
272 .flat_map(|(index, entry)| match entry {
273 HistoryEntryId::AcpThread(id) if &thread.id == id => {
274 Some((index, HistoryEntry::AcpThread(thread.clone())))
275 }
276 _ => None,
277 })
278 });
279
280 let context_entries = self
281 .text_thread_store
282 .read(cx)
283 .unordered_text_threads()
284 .flat_map(|text_thread| {
285 self.recently_opened_entries
286 .iter()
287 .enumerate()
288 .flat_map(|(index, entry)| match entry {
289 HistoryEntryId::TextThread(path) if &text_thread.path == path => {
290 Some((index, HistoryEntry::TextThread(text_thread.clone())))
291 }
292 _ => None,
293 })
294 });
295
296 thread_entries
297 .chain(context_entries)
298 // optimization to halt iteration early
299 .take(self.recently_opened_entries.len())
300 .sorted_unstable_by_key(|(index, _)| *index)
301 .map(|(_, entry)| entry)
302 .collect()
303 }
304
305 fn save_recently_opened_entries(&mut self, cx: &mut Context<Self>) {
306 let serialized_entries = self
307 .recently_opened_entries
308 .iter()
309 .filter_map(|entry| match entry {
310 HistoryEntryId::TextThread(path) => path.file_name().map(|file| {
311 SerializedRecentOpen::TextThread(file.to_string_lossy().into_owned())
312 }),
313 HistoryEntryId::AcpThread(id) => {
314 Some(SerializedRecentOpen::AcpThread(id.to_string()))
315 }
316 })
317 .collect::<Vec<_>>();
318
319 self._save_recently_opened_entries_task = cx.spawn(async move |_, cx| {
320 let content = serde_json::to_string(&serialized_entries).unwrap();
321 cx.background_executor()
322 .timer(SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE)
323 .await;
324
325 if cfg!(any(feature = "test-support", test)) {
326 return;
327 }
328 KEY_VALUE_STORE
329 .write_kvp(RECENTLY_OPENED_THREADS_KEY.to_owned(), content)
330 .await
331 .log_err();
332 });
333 }
334
335 fn load_recently_opened_entries(cx: &AsyncApp) -> Task<Result<VecDeque<HistoryEntryId>>> {
336 cx.background_spawn(async move {
337 if cfg!(any(feature = "test-support", test)) {
338 anyhow::bail!("history store does not persist in tests");
339 }
340 let json = KEY_VALUE_STORE
341 .read_kvp(RECENTLY_OPENED_THREADS_KEY)?
342 .unwrap_or("[]".to_string());
343 let entries = serde_json::from_str::<Vec<SerializedRecentOpen>>(&json)
344 .context("deserializing persisted agent panel navigation history")?
345 .into_iter()
346 .take(MAX_RECENTLY_OPENED_ENTRIES)
347 .flat_map(|entry| match entry {
348 SerializedRecentOpen::AcpThread(id) => Some(HistoryEntryId::AcpThread(
349 acp::SessionId(id.as_str().into()),
350 )),
351 SerializedRecentOpen::TextThread(file_name) => Some(
352 HistoryEntryId::TextThread(text_threads_dir().join(file_name).into()),
353 ),
354 })
355 .collect();
356 Ok(entries)
357 })
358 }
359
360 pub fn push_recently_opened_entry(&mut self, entry: HistoryEntryId, cx: &mut Context<Self>) {
361 self.recently_opened_entries
362 .retain(|old_entry| old_entry != &entry);
363 self.recently_opened_entries.push_front(entry);
364 self.recently_opened_entries
365 .truncate(MAX_RECENTLY_OPENED_ENTRIES);
366 self.save_recently_opened_entries(cx);
367 }
368
369 pub fn remove_recently_opened_thread(&mut self, id: acp::SessionId, cx: &mut Context<Self>) {
370 self.recently_opened_entries.retain(
371 |entry| !matches!(entry, HistoryEntryId::AcpThread(thread_id) if thread_id == &id),
372 );
373 self.save_recently_opened_entries(cx);
374 }
375
376 pub fn replace_recently_opened_text_thread(
377 &mut self,
378 old_path: &Path,
379 new_path: &Arc<Path>,
380 cx: &mut Context<Self>,
381 ) {
382 for entry in &mut self.recently_opened_entries {
383 match entry {
384 HistoryEntryId::TextThread(path) if path.as_ref() == old_path => {
385 *entry = HistoryEntryId::TextThread(new_path.clone());
386 break;
387 }
388 _ => {}
389 }
390 }
391 self.save_recently_opened_entries(cx);
392 }
393
394 pub fn remove_recently_opened_entry(&mut self, entry: &HistoryEntryId, cx: &mut Context<Self>) {
395 self.recently_opened_entries
396 .retain(|old_entry| old_entry != entry);
397 self.save_recently_opened_entries(cx);
398 }
399
400 pub fn entries(&self) -> impl Iterator<Item = HistoryEntry> {
401 self.entries.iter().cloned()
402 }
403}