1use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent};
2use acp_thread::UserMessageId;
3use agent::{thread::DetailedSummaryState, 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 = 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 detailed_summary: Option<SharedString>,
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 detailed_summary: match thread.detailed_summary_state {
189 DetailedSummaryState::NotGenerated | DetailedSummaryState::Generating { .. } => {
190 None
191 }
192 DetailedSummaryState::Generated { text, .. } => Some(text),
193 },
194 initial_project_snapshot: thread.initial_project_snapshot,
195 cumulative_token_usage: thread.cumulative_token_usage,
196 request_token_usage,
197 model: thread.model,
198 completion_mode: thread.completion_mode,
199 profile: thread.profile,
200 })
201 }
202}
203
204pub static ZED_STATELESS: std::sync::LazyLock<bool> =
205 std::sync::LazyLock::new(|| std::env::var("ZED_STATELESS").is_ok_and(|v| !v.is_empty()));
206
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208pub enum DataType {
209 #[serde(rename = "json")]
210 Json,
211 #[serde(rename = "zstd")]
212 Zstd,
213}
214
215impl Bind for DataType {
216 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
217 let value = match self {
218 DataType::Json => "json",
219 DataType::Zstd => "zstd",
220 };
221 value.bind(statement, start_index)
222 }
223}
224
225impl Column for DataType {
226 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
227 let (value, next_index) = String::column(statement, start_index)?;
228 let data_type = match value.as_str() {
229 "json" => DataType::Json,
230 "zstd" => DataType::Zstd,
231 _ => anyhow::bail!("Unknown data type: {}", value),
232 };
233 Ok((data_type, next_index))
234 }
235}
236
237pub(crate) struct ThreadsDatabase {
238 executor: BackgroundExecutor,
239 connection: Arc<Mutex<Connection>>,
240}
241
242struct GlobalThreadsDatabase(Shared<Task<Result<Arc<ThreadsDatabase>, Arc<anyhow::Error>>>>);
243
244impl Global for GlobalThreadsDatabase {}
245
246impl ThreadsDatabase {
247 pub fn connect(cx: &mut App) -> Shared<Task<Result<Arc<ThreadsDatabase>, Arc<anyhow::Error>>>> {
248 if cx.has_global::<GlobalThreadsDatabase>() {
249 return cx.global::<GlobalThreadsDatabase>().0.clone();
250 }
251 let executor = cx.background_executor().clone();
252 let task = executor
253 .spawn({
254 let executor = executor.clone();
255 async move {
256 match ThreadsDatabase::new(executor) {
257 Ok(db) => Ok(Arc::new(db)),
258 Err(err) => Err(Arc::new(err)),
259 }
260 }
261 })
262 .shared();
263
264 cx.set_global(GlobalThreadsDatabase(task.clone()));
265 task
266 }
267
268 pub fn new(executor: BackgroundExecutor) -> Result<Self> {
269 let connection = if *ZED_STATELESS || cfg!(any(feature = "test-support", test)) {
270 Connection::open_memory(Some("THREAD_FALLBACK_DB"))
271 } else {
272 let threads_dir = paths::data_dir().join("threads");
273 std::fs::create_dir_all(&threads_dir)?;
274 let sqlite_path = threads_dir.join("threads.db");
275 Connection::open_file(&sqlite_path.to_string_lossy())
276 };
277
278 connection.exec(indoc! {"
279 CREATE TABLE IF NOT EXISTS threads (
280 id TEXT PRIMARY KEY,
281 summary TEXT NOT NULL,
282 updated_at TEXT NOT NULL,
283 data_type TEXT NOT NULL,
284 data BLOB NOT NULL
285 )
286 "})?()
287 .map_err(|e| anyhow!("Failed to create threads table: {}", e))?;
288
289 let db = Self {
290 executor,
291 connection: Arc::new(Mutex::new(connection)),
292 };
293
294 Ok(db)
295 }
296
297 fn save_thread_sync(
298 connection: &Arc<Mutex<Connection>>,
299 id: acp::SessionId,
300 thread: DbThread,
301 ) -> Result<()> {
302 const COMPRESSION_LEVEL: i32 = 3;
303
304 #[derive(Serialize)]
305 struct SerializedThread {
306 #[serde(flatten)]
307 thread: DbThread,
308 version: &'static str,
309 }
310
311 let title = thread.title.to_string();
312 let updated_at = thread.updated_at.to_rfc3339();
313 let json_data = serde_json::to_string(&SerializedThread {
314 thread,
315 version: DbThread::VERSION,
316 })?;
317
318 let connection = connection.lock();
319
320 let compressed = zstd::encode_all(json_data.as_bytes(), COMPRESSION_LEVEL)?;
321 let data_type = DataType::Zstd;
322 let data = compressed;
323
324 let mut insert = connection.exec_bound::<(Arc<str>, String, String, DataType, Vec<u8>)>(indoc! {"
325 INSERT OR REPLACE INTO threads (id, summary, updated_at, data_type, data) VALUES (?, ?, ?, ?, ?)
326 "})?;
327
328 insert((id.0, title, updated_at, data_type, data))?;
329
330 Ok(())
331 }
332
333 pub fn list_threads(&self) -> Task<Result<Vec<DbThreadMetadata>>> {
334 let connection = self.connection.clone();
335
336 self.executor.spawn(async move {
337 let connection = connection.lock();
338
339 let mut select =
340 connection.select_bound::<(), (Arc<str>, String, String)>(indoc! {"
341 SELECT id, summary, updated_at FROM threads ORDER BY updated_at DESC
342 "})?;
343
344 let rows = select(())?;
345 let mut threads = Vec::new();
346
347 for (id, summary, updated_at) in rows {
348 threads.push(DbThreadMetadata {
349 id: acp::SessionId(id),
350 title: summary.into(),
351 updated_at: DateTime::parse_from_rfc3339(&updated_at)?.with_timezone(&Utc),
352 });
353 }
354
355 Ok(threads)
356 })
357 }
358
359 pub fn load_thread(&self, id: acp::SessionId) -> Task<Result<Option<DbThread>>> {
360 let connection = self.connection.clone();
361
362 self.executor.spawn(async move {
363 let connection = connection.lock();
364 let mut select = connection.select_bound::<Arc<str>, (DataType, Vec<u8>)>(indoc! {"
365 SELECT data_type, data FROM threads WHERE id = ? LIMIT 1
366 "})?;
367
368 let rows = select(id.0)?;
369 if let Some((data_type, data)) = rows.into_iter().next() {
370 let json_data = match data_type {
371 DataType::Zstd => {
372 let decompressed = zstd::decode_all(&data[..])?;
373 String::from_utf8(decompressed)?
374 }
375 DataType::Json => String::from_utf8(data)?,
376 };
377 let thread = DbThread::from_json(json_data.as_bytes())?;
378 Ok(Some(thread))
379 } else {
380 Ok(None)
381 }
382 })
383 }
384
385 pub fn save_thread(&self, id: acp::SessionId, thread: DbThread) -> Task<Result<()>> {
386 let connection = self.connection.clone();
387
388 self.executor
389 .spawn(async move { Self::save_thread_sync(&connection, id, thread) })
390 }
391
392 pub fn delete_thread(&self, id: acp::SessionId) -> Task<Result<()>> {
393 let connection = self.connection.clone();
394
395 self.executor.spawn(async move {
396 let connection = connection.lock();
397
398 let mut delete = connection.exec_bound::<Arc<str>>(indoc! {"
399 DELETE FROM threads WHERE id = ?
400 "})?;
401
402 delete(id.0)?;
403
404 Ok(())
405 })
406 }
407}
408
409#[cfg(test)]
410mod tests {
411
412 use super::*;
413 use agent::MessageSegment;
414 use agent::context::LoadedContext;
415 use client::Client;
416 use fs::FakeFs;
417 use gpui::AppContext;
418 use gpui::TestAppContext;
419 use http_client::FakeHttpClient;
420 use language_model::Role;
421 use project::Project;
422 use settings::SettingsStore;
423
424 fn init_test(cx: &mut TestAppContext) {
425 env_logger::try_init().ok();
426 cx.update(|cx| {
427 let settings_store = SettingsStore::test(cx);
428 cx.set_global(settings_store);
429 Project::init_settings(cx);
430 language::init(cx);
431
432 let http_client = FakeHttpClient::with_404_response();
433 let clock = Arc::new(clock::FakeSystemClock::new());
434 let client = Client::new(clock, http_client, cx);
435 agent::init(cx);
436 agent_settings::init(cx);
437 language_model::init(client, cx);
438 });
439 }
440
441 #[gpui::test]
442 async fn test_retrieving_old_thread(cx: &mut TestAppContext) {
443 init_test(cx);
444 let fs = FakeFs::new(cx.executor());
445 let project = Project::test(fs, [], cx).await;
446
447 // Save a thread using the old agent.
448 let thread_store = cx.new(|cx| agent::ThreadStore::fake(project, cx));
449 let thread = thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx));
450 thread.update(cx, |thread, cx| {
451 thread.insert_message(
452 Role::User,
453 vec![MessageSegment::Text("Hey!".into())],
454 LoadedContext::default(),
455 vec![],
456 false,
457 cx,
458 );
459 thread.insert_message(
460 Role::Assistant,
461 vec![MessageSegment::Text("How're you doing?".into())],
462 LoadedContext::default(),
463 vec![],
464 false,
465 cx,
466 )
467 });
468 thread_store
469 .update(cx, |thread_store, cx| thread_store.save_thread(&thread, cx))
470 .await
471 .unwrap();
472
473 // Open that same thread using the new agent.
474 let db = cx.update(ThreadsDatabase::connect).await.unwrap();
475 let threads = db.list_threads().await.unwrap();
476 assert_eq!(threads.len(), 1);
477 let thread = db
478 .load_thread(threads[0].id.clone())
479 .await
480 .unwrap()
481 .unwrap();
482 assert_eq!(thread.messages[0].to_markdown(), "## User\n\nHey!\n");
483 assert_eq!(
484 thread.messages[1].to_markdown(),
485 "## Assistant\n\nHow're you doing?\n"
486 );
487 }
488}