history_store.rs

  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_threads(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
192        let database_future = ThreadsDatabase::connect(cx);
193        cx.spawn(async move |this, cx| {
194            let database = database_future.await.map_err(|err| anyhow!(err))?;
195            database.delete_threads().await?;
196            this.update(cx, |this, cx| this.reload(cx))
197        })
198    }
199
200    pub fn delete_text_thread(
201        &mut self,
202        path: Arc<Path>,
203        cx: &mut Context<Self>,
204    ) -> Task<Result<()>> {
205        self.text_thread_store
206            .update(cx, |store, cx| store.delete_local(path, cx))
207    }
208
209    pub fn load_text_thread(
210        &self,
211        path: Arc<Path>,
212        cx: &mut Context<Self>,
213    ) -> Task<Result<Entity<TextThread>>> {
214        self.text_thread_store
215            .update(cx, |store, cx| store.open_local(path, cx))
216    }
217
218    pub fn reload(&self, cx: &mut Context<Self>) {
219        let database_future = ThreadsDatabase::connect(cx);
220        cx.spawn(async move |this, cx| {
221            let threads = database_future
222                .await
223                .map_err(|err| anyhow!(err))?
224                .list_threads()
225                .await?;
226
227            this.update(cx, |this, cx| {
228                if this.recently_opened_entries.len() < MAX_RECENTLY_OPENED_ENTRIES {
229                    for thread in threads
230                        .iter()
231                        .take(MAX_RECENTLY_OPENED_ENTRIES - this.recently_opened_entries.len())
232                        .rev()
233                    {
234                        this.push_recently_opened_entry(
235                            HistoryEntryId::AcpThread(thread.id.clone()),
236                            cx,
237                        )
238                    }
239                }
240                this.threads = threads;
241                this.update_entries(cx);
242            })
243        })
244        .detach_and_log_err(cx);
245    }
246
247    fn update_entries(&mut self, cx: &mut Context<Self>) {
248        #[cfg(debug_assertions)]
249        if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
250            return;
251        }
252        let mut history_entries = Vec::new();
253        history_entries.extend(self.threads.iter().cloned().map(HistoryEntry::AcpThread));
254        history_entries.extend(
255            self.text_thread_store
256                .read(cx)
257                .unordered_text_threads()
258                .cloned()
259                .map(HistoryEntry::TextThread),
260        );
261
262        history_entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.updated_at()));
263        self.entries = history_entries;
264        cx.notify()
265    }
266
267    pub fn is_empty(&self, _cx: &App) -> bool {
268        self.entries.is_empty()
269    }
270
271    pub fn recently_opened_entries(&self, cx: &App) -> Vec<HistoryEntry> {
272        #[cfg(debug_assertions)]
273        if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
274            return Vec::new();
275        }
276
277        let thread_entries = self.threads.iter().flat_map(|thread| {
278            self.recently_opened_entries
279                .iter()
280                .enumerate()
281                .flat_map(|(index, entry)| match entry {
282                    HistoryEntryId::AcpThread(id) if &thread.id == id => {
283                        Some((index, HistoryEntry::AcpThread(thread.clone())))
284                    }
285                    _ => None,
286                })
287        });
288
289        let context_entries = self
290            .text_thread_store
291            .read(cx)
292            .unordered_text_threads()
293            .flat_map(|text_thread| {
294                self.recently_opened_entries
295                    .iter()
296                    .enumerate()
297                    .flat_map(|(index, entry)| match entry {
298                        HistoryEntryId::TextThread(path) if &text_thread.path == path => {
299                            Some((index, HistoryEntry::TextThread(text_thread.clone())))
300                        }
301                        _ => None,
302                    })
303            });
304
305        thread_entries
306            .chain(context_entries)
307            // optimization to halt iteration early
308            .take(self.recently_opened_entries.len())
309            .sorted_unstable_by_key(|(index, _)| *index)
310            .map(|(_, entry)| entry)
311            .collect()
312    }
313
314    fn save_recently_opened_entries(&mut self, cx: &mut Context<Self>) {
315        let serialized_entries = self
316            .recently_opened_entries
317            .iter()
318            .filter_map(|entry| match entry {
319                HistoryEntryId::TextThread(path) => path.file_name().map(|file| {
320                    SerializedRecentOpen::TextThread(file.to_string_lossy().into_owned())
321                }),
322                HistoryEntryId::AcpThread(id) => {
323                    Some(SerializedRecentOpen::AcpThread(id.to_string()))
324                }
325            })
326            .collect::<Vec<_>>();
327
328        self._save_recently_opened_entries_task = cx.spawn(async move |_, cx| {
329            let content = serde_json::to_string(&serialized_entries).unwrap();
330            cx.background_executor()
331                .timer(SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE)
332                .await;
333
334            if cfg!(any(feature = "test-support", test)) {
335                return;
336            }
337            KEY_VALUE_STORE
338                .write_kvp(RECENTLY_OPENED_THREADS_KEY.to_owned(), content)
339                .await
340                .log_err();
341        });
342    }
343
344    fn load_recently_opened_entries(cx: &AsyncApp) -> Task<Result<VecDeque<HistoryEntryId>>> {
345        cx.background_spawn(async move {
346            if cfg!(any(feature = "test-support", test)) {
347                anyhow::bail!("history store does not persist in tests");
348            }
349            let json = KEY_VALUE_STORE
350                .read_kvp(RECENTLY_OPENED_THREADS_KEY)?
351                .unwrap_or("[]".to_string());
352            let entries = serde_json::from_str::<Vec<SerializedRecentOpen>>(&json)
353                .context("deserializing persisted agent panel navigation history")?
354                .into_iter()
355                .take(MAX_RECENTLY_OPENED_ENTRIES)
356                .flat_map(|entry| match entry {
357                    SerializedRecentOpen::AcpThread(id) => Some(HistoryEntryId::AcpThread(
358                        acp::SessionId(id.as_str().into()),
359                    )),
360                    SerializedRecentOpen::TextThread(file_name) => Some(
361                        HistoryEntryId::TextThread(text_threads_dir().join(file_name).into()),
362                    ),
363                })
364                .collect();
365            Ok(entries)
366        })
367    }
368
369    pub fn push_recently_opened_entry(&mut self, entry: HistoryEntryId, cx: &mut Context<Self>) {
370        self.recently_opened_entries
371            .retain(|old_entry| old_entry != &entry);
372        self.recently_opened_entries.push_front(entry);
373        self.recently_opened_entries
374            .truncate(MAX_RECENTLY_OPENED_ENTRIES);
375        self.save_recently_opened_entries(cx);
376    }
377
378    pub fn remove_recently_opened_thread(&mut self, id: acp::SessionId, cx: &mut Context<Self>) {
379        self.recently_opened_entries.retain(
380            |entry| !matches!(entry, HistoryEntryId::AcpThread(thread_id) if thread_id == &id),
381        );
382        self.save_recently_opened_entries(cx);
383    }
384
385    pub fn replace_recently_opened_text_thread(
386        &mut self,
387        old_path: &Path,
388        new_path: &Arc<Path>,
389        cx: &mut Context<Self>,
390    ) {
391        for entry in &mut self.recently_opened_entries {
392            match entry {
393                HistoryEntryId::TextThread(path) if path.as_ref() == old_path => {
394                    *entry = HistoryEntryId::TextThread(new_path.clone());
395                    break;
396                }
397                _ => {}
398            }
399        }
400        self.save_recently_opened_entries(cx);
401    }
402
403    pub fn remove_recently_opened_entry(&mut self, entry: &HistoryEntryId, cx: &mut Context<Self>) {
404        self.recently_opened_entries
405            .retain(|old_entry| old_entry != entry);
406        self.save_recently_opened_entries(cx);
407    }
408
409    pub fn entries(&self) -> impl Iterator<Item = HistoryEntry> {
410        self.entries.iter().cloned()
411    }
412}