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