db.rs

  1use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent};
  2use acp_thread::UserMessageId;
  3use agent::thread_store;
  4use agent_client_protocol as acp;
  5use agent_settings::{AgentProfileId, CompletionMode};
  6use anyhow::{Result, anyhow};
  7use chrono::{DateTime, Utc};
  8use collections::{HashMap, IndexMap};
  9use futures::{FutureExt, future::Shared};
 10use gpui::{BackgroundExecutor, Global, Task};
 11use indoc::indoc;
 12use parking_lot::Mutex;
 13use serde::{Deserialize, Serialize};
 14use sqlez::{
 15    bindable::{Bind, Column},
 16    connection::Connection,
 17    statement::Statement,
 18};
 19use std::sync::Arc;
 20use ui::{App, SharedString};
 21
 22pub type DbMessage = crate::Message;
 23pub type DbSummary = agent::thread::DetailedSummaryState;
 24pub type DbLanguageModel = thread_store::SerializedLanguageModel;
 25
 26#[derive(Debug, Clone, Serialize, Deserialize)]
 27pub struct DbThreadMetadata {
 28    pub id: acp::SessionId,
 29    #[serde(alias = "summary")]
 30    pub title: SharedString,
 31    pub updated_at: DateTime<Utc>,
 32}
 33
 34#[derive(Debug, Serialize, Deserialize)]
 35pub struct DbThread {
 36    pub title: SharedString,
 37    pub messages: Vec<DbMessage>,
 38    pub updated_at: DateTime<Utc>,
 39    #[serde(default)]
 40    pub summary: DbSummary,
 41    #[serde(default)]
 42    pub initial_project_snapshot: Option<Arc<agent::thread::ProjectSnapshot>>,
 43    #[serde(default)]
 44    pub cumulative_token_usage: language_model::TokenUsage,
 45    #[serde(default)]
 46    pub request_token_usage: HashMap<acp_thread::UserMessageId, language_model::TokenUsage>,
 47    #[serde(default)]
 48    pub model: Option<DbLanguageModel>,
 49    #[serde(default)]
 50    pub completion_mode: Option<CompletionMode>,
 51    #[serde(default)]
 52    pub profile: Option<AgentProfileId>,
 53}
 54
 55impl DbThread {
 56    pub const VERSION: &'static str = "0.3.0";
 57
 58    pub fn from_json(json: &[u8]) -> Result<Self> {
 59        let saved_thread_json = serde_json::from_slice::<serde_json::Value>(json)?;
 60        match saved_thread_json.get("version") {
 61            Some(serde_json::Value::String(version)) => match version.as_str() {
 62                Self::VERSION => Ok(serde_json::from_value(saved_thread_json)?),
 63                _ => Self::upgrade_from_agent_1(agent::SerializedThread::from_json(json)?),
 64            },
 65            _ => Self::upgrade_from_agent_1(agent::SerializedThread::from_json(json)?),
 66        }
 67    }
 68
 69    fn upgrade_from_agent_1(thread: agent::SerializedThread) -> Result<Self> {
 70        let mut messages = Vec::new();
 71        let mut request_token_usage = HashMap::default();
 72
 73        let mut last_user_message_id = None;
 74        for (ix, msg) in thread.messages.into_iter().enumerate() {
 75            let message = match msg.role {
 76                language_model::Role::User => {
 77                    let mut content = Vec::new();
 78
 79                    // Convert segments to content
 80                    for segment in msg.segments {
 81                        match segment {
 82                            thread_store::SerializedMessageSegment::Text { text } => {
 83                                content.push(UserMessageContent::Text(text));
 84                            }
 85                            thread_store::SerializedMessageSegment::Thinking { text, .. } => {
 86                                // User messages don't have thinking segments, but handle gracefully
 87                                content.push(UserMessageContent::Text(text));
 88                            }
 89                            thread_store::SerializedMessageSegment::RedactedThinking { .. } => {
 90                                // User messages don't have redacted thinking, skip.
 91                            }
 92                        }
 93                    }
 94
 95                    // If no content was added, add context as text if available
 96                    if content.is_empty() && !msg.context.is_empty() {
 97                        content.push(UserMessageContent::Text(msg.context));
 98                    }
 99
100                    let id = UserMessageId::new();
101                    last_user_message_id = Some(id.clone());
102
103                    crate::Message::User(UserMessage {
104                        // MessageId from old format can't be meaningfully converted, so generate a new one
105                        id,
106                        content,
107                    })
108                }
109                language_model::Role::Assistant => {
110                    let mut content = Vec::new();
111
112                    // Convert segments to content
113                    for segment in msg.segments {
114                        match segment {
115                            thread_store::SerializedMessageSegment::Text { text } => {
116                                content.push(AgentMessageContent::Text(text));
117                            }
118                            thread_store::SerializedMessageSegment::Thinking {
119                                text,
120                                signature,
121                            } => {
122                                content.push(AgentMessageContent::Thinking { text, signature });
123                            }
124                            thread_store::SerializedMessageSegment::RedactedThinking { data } => {
125                                content.push(AgentMessageContent::RedactedThinking(data));
126                            }
127                        }
128                    }
129
130                    // Convert tool uses
131                    let mut tool_names_by_id = HashMap::default();
132                    for tool_use in msg.tool_uses {
133                        tool_names_by_id.insert(tool_use.id.clone(), tool_use.name.clone());
134                        content.push(AgentMessageContent::ToolUse(
135                            language_model::LanguageModelToolUse {
136                                id: tool_use.id,
137                                name: tool_use.name.into(),
138                                raw_input: serde_json::to_string(&tool_use.input)
139                                    .unwrap_or_default(),
140                                input: tool_use.input,
141                                is_input_complete: true,
142                            },
143                        ));
144                    }
145
146                    // Convert tool results
147                    let mut tool_results = IndexMap::default();
148                    for tool_result in msg.tool_results {
149                        let name = tool_names_by_id
150                            .remove(&tool_result.tool_use_id)
151                            .unwrap_or_else(|| SharedString::from("unknown"));
152                        tool_results.insert(
153                            tool_result.tool_use_id.clone(),
154                            language_model::LanguageModelToolResult {
155                                tool_use_id: tool_result.tool_use_id,
156                                tool_name: name.into(),
157                                is_error: tool_result.is_error,
158                                content: tool_result.content,
159                                output: tool_result.output,
160                            },
161                        );
162                    }
163
164                    if let Some(last_user_message_id) = &last_user_message_id
165                        && let Some(token_usage) = thread.request_token_usage.get(ix).copied()
166                    {
167                        request_token_usage.insert(last_user_message_id.clone(), token_usage);
168                    }
169
170                    crate::Message::Agent(AgentMessage {
171                        content,
172                        tool_results,
173                    })
174                }
175                language_model::Role::System => {
176                    // Skip system messages as they're not supported in the new format
177                    continue;
178                }
179            };
180
181            messages.push(message);
182        }
183
184        Ok(Self {
185            title: thread.summary,
186            messages,
187            updated_at: thread.updated_at,
188            summary: thread.detailed_summary_state,
189            initial_project_snapshot: thread.initial_project_snapshot,
190            cumulative_token_usage: thread.cumulative_token_usage,
191            request_token_usage,
192            model: thread.model,
193            completion_mode: thread.completion_mode,
194            profile: thread.profile,
195        })
196    }
197}
198
199pub static ZED_STATELESS: std::sync::LazyLock<bool> =
200    std::sync::LazyLock::new(|| std::env::var("ZED_STATELESS").is_ok_and(|v| !v.is_empty()));
201
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub enum DataType {
204    #[serde(rename = "json")]
205    Json,
206    #[serde(rename = "zstd")]
207    Zstd,
208}
209
210impl Bind for DataType {
211    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
212        let value = match self {
213            DataType::Json => "json",
214            DataType::Zstd => "zstd",
215        };
216        value.bind(statement, start_index)
217    }
218}
219
220impl Column for DataType {
221    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
222        let (value, next_index) = String::column(statement, start_index)?;
223        let data_type = match value.as_str() {
224            "json" => DataType::Json,
225            "zstd" => DataType::Zstd,
226            _ => anyhow::bail!("Unknown data type: {}", value),
227        };
228        Ok((data_type, next_index))
229    }
230}
231
232pub(crate) struct ThreadsDatabase {
233    executor: BackgroundExecutor,
234    connection: Arc<Mutex<Connection>>,
235}
236
237struct GlobalThreadsDatabase(Shared<Task<Result<Arc<ThreadsDatabase>, Arc<anyhow::Error>>>>);
238
239impl Global for GlobalThreadsDatabase {}
240
241impl ThreadsDatabase {
242    pub fn connect(cx: &mut App) -> Shared<Task<Result<Arc<ThreadsDatabase>, Arc<anyhow::Error>>>> {
243        if cx.has_global::<GlobalThreadsDatabase>() {
244            return cx.global::<GlobalThreadsDatabase>().0.clone();
245        }
246        let executor = cx.background_executor().clone();
247        let task = executor
248            .spawn({
249                let executor = executor.clone();
250                async move {
251                    match ThreadsDatabase::new(executor) {
252                        Ok(db) => Ok(Arc::new(db)),
253                        Err(err) => Err(Arc::new(err)),
254                    }
255                }
256            })
257            .shared();
258
259        cx.set_global(GlobalThreadsDatabase(task.clone()));
260        task
261    }
262
263    pub fn new(executor: BackgroundExecutor) -> Result<Self> {
264        let connection = if *ZED_STATELESS || cfg!(any(feature = "test-support", test)) {
265            Connection::open_memory(Some("THREAD_FALLBACK_DB"))
266        } else {
267            let threads_dir = paths::data_dir().join("threads");
268            std::fs::create_dir_all(&threads_dir)?;
269            let sqlite_path = threads_dir.join("threads.db");
270            Connection::open_file(&sqlite_path.to_string_lossy())
271        };
272
273        connection.exec(indoc! {"
274            CREATE TABLE IF NOT EXISTS threads (
275                id TEXT PRIMARY KEY,
276                summary TEXT NOT NULL,
277                updated_at TEXT NOT NULL,
278                data_type TEXT NOT NULL,
279                data BLOB NOT NULL
280            )
281        "})?()
282        .map_err(|e| anyhow!("Failed to create threads table: {}", e))?;
283
284        let db = Self {
285            executor: executor.clone(),
286            connection: Arc::new(Mutex::new(connection)),
287        };
288
289        Ok(db)
290    }
291
292    fn save_thread_sync(
293        connection: &Arc<Mutex<Connection>>,
294        id: acp::SessionId,
295        thread: DbThread,
296    ) -> Result<()> {
297        const COMPRESSION_LEVEL: i32 = 3;
298
299        #[derive(Serialize)]
300        struct SerializedThread {
301            #[serde(flatten)]
302            thread: DbThread,
303            version: &'static str,
304        }
305
306        let title = thread.title.to_string();
307        let updated_at = thread.updated_at.to_rfc3339();
308        let json_data = serde_json::to_string(&SerializedThread {
309            thread,
310            version: DbThread::VERSION,
311        })?;
312
313        let connection = connection.lock();
314
315        let compressed = zstd::encode_all(json_data.as_bytes(), COMPRESSION_LEVEL)?;
316        let data_type = DataType::Zstd;
317        let data = compressed;
318
319        let mut insert = connection.exec_bound::<(Arc<str>, String, String, DataType, Vec<u8>)>(indoc! {"
320            INSERT OR REPLACE INTO threads (id, summary, updated_at, data_type, data) VALUES (?, ?, ?, ?, ?)
321        "})?;
322
323        insert((id.0.clone(), title, updated_at, data_type, data))?;
324
325        Ok(())
326    }
327
328    pub fn list_threads(&self) -> Task<Result<Vec<DbThreadMetadata>>> {
329        let connection = self.connection.clone();
330
331        self.executor.spawn(async move {
332            let connection = connection.lock();
333
334            let mut select =
335                connection.select_bound::<(), (Arc<str>, String, String)>(indoc! {"
336                SELECT id, summary, updated_at FROM threads ORDER BY updated_at DESC
337            "})?;
338
339            let rows = select(())?;
340            let mut threads = Vec::new();
341
342            for (id, summary, updated_at) in rows {
343                threads.push(DbThreadMetadata {
344                    id: acp::SessionId(id),
345                    title: summary.into(),
346                    updated_at: DateTime::parse_from_rfc3339(&updated_at)?.with_timezone(&Utc),
347                });
348            }
349
350            Ok(threads)
351        })
352    }
353
354    pub fn load_thread(&self, id: acp::SessionId) -> Task<Result<Option<DbThread>>> {
355        let connection = self.connection.clone();
356
357        self.executor.spawn(async move {
358            let connection = connection.lock();
359            let mut select = connection.select_bound::<Arc<str>, (DataType, Vec<u8>)>(indoc! {"
360                SELECT data_type, data FROM threads WHERE id = ? LIMIT 1
361            "})?;
362
363            let rows = select(id.0)?;
364            if let Some((data_type, data)) = rows.into_iter().next() {
365                let json_data = match data_type {
366                    DataType::Zstd => {
367                        let decompressed = zstd::decode_all(&data[..])?;
368                        String::from_utf8(decompressed)?
369                    }
370                    DataType::Json => String::from_utf8(data)?,
371                };
372                let thread = DbThread::from_json(json_data.as_bytes())?;
373                Ok(Some(thread))
374            } else {
375                Ok(None)
376            }
377        })
378    }
379
380    pub fn save_thread(&self, id: acp::SessionId, thread: DbThread) -> Task<Result<()>> {
381        let connection = self.connection.clone();
382
383        self.executor
384            .spawn(async move { Self::save_thread_sync(&connection, id, thread) })
385    }
386
387    pub fn delete_thread(&self, id: acp::SessionId) -> Task<Result<()>> {
388        let connection = self.connection.clone();
389
390        self.executor.spawn(async move {
391            let connection = connection.lock();
392
393            let mut delete = connection.exec_bound::<Arc<str>>(indoc! {"
394                DELETE FROM threads WHERE id = ?
395            "})?;
396
397            delete(id.0)?;
398
399            Ok(())
400        })
401    }
402}
403
404#[cfg(test)]
405mod tests {
406
407    use super::*;
408    use agent::MessageSegment;
409    use agent::context::LoadedContext;
410    use client::Client;
411    use fs::FakeFs;
412    use gpui::AppContext;
413    use gpui::TestAppContext;
414    use http_client::FakeHttpClient;
415    use language_model::Role;
416    use project::Project;
417    use settings::SettingsStore;
418
419    fn init_test(cx: &mut TestAppContext) {
420        env_logger::try_init().ok();
421        cx.update(|cx| {
422            let settings_store = SettingsStore::test(cx);
423            cx.set_global(settings_store);
424            Project::init_settings(cx);
425            language::init(cx);
426
427            let http_client = FakeHttpClient::with_404_response();
428            let clock = Arc::new(clock::FakeSystemClock::new());
429            let client = Client::new(clock, http_client, cx);
430            agent::init(cx);
431            agent_settings::init(cx);
432            language_model::init(client.clone(), cx);
433        });
434    }
435
436    #[gpui::test]
437    async fn test_retrieving_old_thread(cx: &mut TestAppContext) {
438        init_test(cx);
439        let fs = FakeFs::new(cx.executor());
440        let project = Project::test(fs, [], cx).await;
441
442        // Save a thread using the old agent.
443        let thread_store = cx.new(|cx| agent::ThreadStore::fake(project, cx));
444        let thread = thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx));
445        thread.update(cx, |thread, cx| {
446            thread.insert_message(
447                Role::User,
448                vec![MessageSegment::Text("Hey!".into())],
449                LoadedContext::default(),
450                vec![],
451                false,
452                cx,
453            );
454            thread.insert_message(
455                Role::Assistant,
456                vec![MessageSegment::Text("How're you doing?".into())],
457                LoadedContext::default(),
458                vec![],
459                false,
460                cx,
461            )
462        });
463        thread_store
464            .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
465            .await
466            .unwrap();
467
468        // Open that same thread using the new agent.
469        let db = cx.update(ThreadsDatabase::connect).await.unwrap();
470        let threads = db.list_threads().await.unwrap();
471        assert_eq!(threads.len(), 1);
472        let thread = db
473            .load_thread(threads[0].id.clone())
474            .await
475            .unwrap()
476            .unwrap();
477        assert_eq!(thread.messages[0].to_markdown(), "## User\n\nHey!\n");
478        assert_eq!(
479            thread.messages[1].to_markdown(),
480            "## Assistant\n\nHow're you doing?\n"
481        );
482    }
483}