1use std::{collections::VecDeque, path::Path};
2
3use anyhow::{Context as _, anyhow};
4use assistant_context_editor::{AssistantContext, SavedContextMetadata};
5use chrono::{DateTime, Utc};
6use futures::future::{TryFutureExt as _, join_all};
7use gpui::{Entity, Task, prelude::*};
8use serde::{Deserialize, Serialize};
9use smol::future::FutureExt;
10use std::time::Duration;
11use ui::{App, SharedString};
12use util::ResultExt as _;
13
14use crate::{
15 Thread,
16 thread::ThreadId,
17 thread_store::{SerializedThreadMetadata, ThreadStore},
18};
19
20const MAX_RECENTLY_OPENED_ENTRIES: usize = 6;
21const NAVIGATION_HISTORY_PATH: &str = "agent-navigation-history.json";
22const SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE: Duration = Duration::from_millis(50);
23
24#[derive(Clone, Debug)]
25pub enum HistoryEntry {
26 Thread(SerializedThreadMetadata),
27 Context(SavedContextMetadata),
28}
29
30impl HistoryEntry {
31 pub fn updated_at(&self) -> DateTime<Utc> {
32 match self {
33 HistoryEntry::Thread(thread) => thread.updated_at,
34 HistoryEntry::Context(context) => context.mtime.to_utc(),
35 }
36 }
37}
38
39#[derive(Clone, Debug)]
40pub(crate) enum RecentEntry {
41 Thread(ThreadId, Entity<Thread>),
42 Context(Entity<AssistantContext>),
43}
44
45impl PartialEq for RecentEntry {
46 fn eq(&self, other: &Self) -> bool {
47 match (self, other) {
48 (Self::Thread(l0, _), Self::Thread(r0, _)) => l0 == r0,
49 (Self::Context(l0), Self::Context(r0)) => l0 == r0,
50 _ => false,
51 }
52 }
53}
54
55impl Eq for RecentEntry {}
56
57impl RecentEntry {
58 pub(crate) fn summary(&self, cx: &App) -> SharedString {
59 match self {
60 RecentEntry::Thread(_, thread) => thread.read(cx).summary_or_default(),
61 RecentEntry::Context(context) => context.read(cx).summary_or_default(),
62 }
63 }
64}
65
66#[derive(Serialize, Deserialize)]
67enum SerializedRecentEntry {
68 Thread(String),
69 Context(String),
70}
71
72pub struct HistoryStore {
73 thread_store: Entity<ThreadStore>,
74 context_store: Entity<assistant_context_editor::ContextStore>,
75 recently_opened_entries: VecDeque<RecentEntry>,
76 _subscriptions: Vec<gpui::Subscription>,
77 _save_recently_opened_entries_task: Task<()>,
78}
79
80impl HistoryStore {
81 pub fn new(
82 thread_store: Entity<ThreadStore>,
83 context_store: Entity<assistant_context_editor::ContextStore>,
84 initial_recent_entries: impl IntoIterator<Item = RecentEntry>,
85 cx: &mut Context<Self>,
86 ) -> Self {
87 let subscriptions = vec![
88 cx.observe(&thread_store, |_, _, cx| cx.notify()),
89 cx.observe(&context_store, |_, _, cx| cx.notify()),
90 ];
91
92 cx.spawn({
93 let thread_store = thread_store.downgrade();
94 let context_store = context_store.downgrade();
95 async move |this, cx| {
96 let path = paths::data_dir().join(NAVIGATION_HISTORY_PATH);
97 let contents = cx
98 .background_spawn(async move { std::fs::read_to_string(path) })
99 .await
100 .context("reading persisted agent panel navigation history")?;
101 let entries = serde_json::from_str::<Vec<SerializedRecentEntry>>(&contents)
102 .context("deserializing persisted agent panel navigation history")?
103 .into_iter()
104 .take(MAX_RECENTLY_OPENED_ENTRIES)
105 .map(|serialized| match serialized {
106 SerializedRecentEntry::Thread(id) => thread_store
107 .update(cx, |thread_store, cx| {
108 let thread_id = ThreadId::from(id.as_str());
109 thread_store
110 .open_thread(&thread_id, cx)
111 .map_ok(|thread| RecentEntry::Thread(thread_id, thread))
112 .boxed()
113 })
114 .unwrap_or_else(|_| async { Err(anyhow!("no thread store")) }.boxed()),
115 SerializedRecentEntry::Context(id) => context_store
116 .update(cx, |context_store, cx| {
117 context_store
118 .open_local_context(Path::new(&id).into(), cx)
119 .map_ok(RecentEntry::Context)
120 .boxed()
121 })
122 .unwrap_or_else(|_| async { Err(anyhow!("no context store")) }.boxed()),
123 });
124 let entries = join_all(entries)
125 .await
126 .into_iter()
127 .filter_map(|result| result.log_err())
128 .collect::<VecDeque<_>>();
129
130 this.update(cx, |this, _| {
131 this.recently_opened_entries.extend(entries);
132 this.recently_opened_entries
133 .truncate(MAX_RECENTLY_OPENED_ENTRIES);
134 })
135 .ok();
136
137 anyhow::Ok(())
138 }
139 })
140 .detach_and_log_err(cx);
141
142 Self {
143 thread_store,
144 context_store,
145 recently_opened_entries: initial_recent_entries.into_iter().collect(),
146 _subscriptions: subscriptions,
147 _save_recently_opened_entries_task: Task::ready(()),
148 }
149 }
150
151 pub fn entries(&self, cx: &mut Context<Self>) -> Vec<HistoryEntry> {
152 let mut history_entries = Vec::new();
153
154 #[cfg(debug_assertions)]
155 if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
156 return history_entries;
157 }
158
159 for thread in self
160 .thread_store
161 .update(cx, |this, _cx| this.reverse_chronological_threads())
162 {
163 history_entries.push(HistoryEntry::Thread(thread));
164 }
165
166 for context in self.context_store.update(cx, |this, _cx| this.contexts()) {
167 history_entries.push(HistoryEntry::Context(context));
168 }
169
170 history_entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.updated_at()));
171 history_entries
172 }
173
174 pub fn recent_entries(&self, limit: usize, cx: &mut Context<Self>) -> Vec<HistoryEntry> {
175 self.entries(cx).into_iter().take(limit).collect()
176 }
177
178 fn save_recently_opened_entries(&mut self, cx: &mut Context<Self>) {
179 let serialized_entries = self
180 .recently_opened_entries
181 .iter()
182 .filter_map(|entry| match entry {
183 RecentEntry::Context(context) => Some(SerializedRecentEntry::Context(
184 context.read(cx).path()?.to_str()?.to_owned(),
185 )),
186 RecentEntry::Thread(id, _) => Some(SerializedRecentEntry::Thread(id.to_string())),
187 })
188 .collect::<Vec<_>>();
189
190 self._save_recently_opened_entries_task = cx.spawn(async move |_, cx| {
191 cx.background_executor()
192 .timer(SAVE_RECENTLY_OPENED_ENTRIES_DEBOUNCE)
193 .await;
194 cx.background_spawn(async move {
195 let path = paths::data_dir().join(NAVIGATION_HISTORY_PATH);
196 let content = serde_json::to_string(&serialized_entries)?;
197 std::fs::write(path, content)?;
198 anyhow::Ok(())
199 })
200 .await
201 .log_err();
202 });
203 }
204
205 pub fn push_recently_opened_entry(&mut self, entry: RecentEntry, cx: &mut Context<Self>) {
206 self.recently_opened_entries
207 .retain(|old_entry| old_entry != &entry);
208 self.recently_opened_entries.push_front(entry);
209 self.recently_opened_entries
210 .truncate(MAX_RECENTLY_OPENED_ENTRIES);
211 self.save_recently_opened_entries(cx);
212 }
213
214 pub fn remove_recently_opened_thread(&mut self, id: ThreadId, cx: &mut Context<Self>) {
215 self.recently_opened_entries.retain(|entry| match entry {
216 RecentEntry::Thread(thread_id, _) if thread_id == &id => false,
217 _ => true,
218 });
219 self.save_recently_opened_entries(cx);
220 }
221
222 pub fn remove_recently_opened_entry(&mut self, entry: &RecentEntry, cx: &mut Context<Self>) {
223 self.recently_opened_entries
224 .retain(|old_entry| old_entry != entry);
225 self.save_recently_opened_entries(cx);
226 }
227
228 pub fn recently_opened_entries(&self, _cx: &mut Context<Self>) -> VecDeque<RecentEntry> {
229 #[cfg(debug_assertions)]
230 if std::env::var("ZED_SIMULATE_NO_THREAD_HISTORY").is_ok() {
231 return VecDeque::new();
232 }
233
234 self.recently_opened_entries.clone()
235 }
236}