thread_store.rs

   1use crate::{
   2    context_server_tool::ContextServerTool,
   3    thread::{
   4        DetailedSummaryState, ExceededWindowError, MessageId, ProjectSnapshot, ThreadId, ZedAgentThread,
   5    },
   6};
   7use agent_settings::{AgentProfileId, CompletionMode};
   8use anyhow::{Context as _, Result, anyhow};
   9use assistant_tool::{ToolId, ToolWorkingSet};
  10use chrono::{DateTime, Utc};
  11use collections::HashMap;
  12use context_server::ContextServerId;
  13use futures::{
  14    FutureExt as _, StreamExt as _,
  15    channel::{mpsc, oneshot},
  16    future::{self, BoxFuture, Shared},
  17};
  18use gpui::{
  19    App, BackgroundExecutor, Context, Entity, EventEmitter, Global, ReadGlobal, SharedString,
  20    Subscription, Task, Window, prelude::*,
  21};
  22use indoc::indoc;
  23use language_model::{LanguageModelToolResultContent, LanguageModelToolUseId, Role, TokenUsage};
  24use project::context_server_store::{ContextServerStatus, ContextServerStore};
  25use project::{Project, ProjectItem, ProjectPath, Worktree};
  26use prompt_store::{
  27    ProjectContext, PromptBuilder, PromptId, PromptStore, PromptsUpdatedEvent, RulesFileContext,
  28    UserRulesContext, WorktreeContext,
  29};
  30use serde::{Deserialize, Serialize};
  31use sqlez::{
  32    bindable::{Bind, Column},
  33    connection::Connection,
  34    statement::Statement,
  35};
  36use std::{
  37    cell::{Ref, RefCell},
  38    path::{Path, PathBuf},
  39    rc::Rc,
  40    sync::{Arc, Mutex},
  41};
  42use util::ResultExt as _;
  43
  44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  45pub enum DataType {
  46    #[serde(rename = "json")]
  47    Json,
  48    #[serde(rename = "zstd")]
  49    Zstd,
  50}
  51
  52impl Bind for DataType {
  53    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  54        let value = match self {
  55            DataType::Json => "json",
  56            DataType::Zstd => "zstd",
  57        };
  58        value.bind(statement, start_index)
  59    }
  60}
  61
  62impl Column for DataType {
  63    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  64        let (value, next_index) = String::column(statement, start_index)?;
  65        let data_type = match value.as_str() {
  66            "json" => DataType::Json,
  67            "zstd" => DataType::Zstd,
  68            _ => anyhow::bail!("Unknown data type: {}", value),
  69        };
  70        Ok((data_type, next_index))
  71    }
  72}
  73
  74const RULES_FILE_NAMES: [&'static str; 9] = [
  75    ".rules",
  76    ".cursorrules",
  77    ".windsurfrules",
  78    ".clinerules",
  79    ".github/copilot-instructions.md",
  80    "CLAUDE.md",
  81    "AGENT.md",
  82    "AGENTS.md",
  83    "GEMINI.md",
  84];
  85
  86pub fn init(cx: &mut App) {
  87    ThreadsDatabase::init(cx);
  88}
  89
  90/// A system prompt shared by all threads created by this ThreadStore
  91#[derive(Clone, Default)]
  92pub struct SharedProjectContext(Rc<RefCell<Option<ProjectContext>>>);
  93
  94impl SharedProjectContext {
  95    pub fn borrow(&self) -> Ref<'_, Option<ProjectContext>> {
  96        self.0.borrow()
  97    }
  98}
  99
 100pub type TextThreadStore = assistant_context::ContextStore;
 101
 102pub struct ThreadStore {
 103    project: Entity<Project>,
 104    tools: Entity<ToolWorkingSet>,
 105    prompt_builder: Arc<PromptBuilder>,
 106    prompt_store: Option<Entity<PromptStore>>,
 107    context_server_tool_ids: HashMap<ContextServerId, Vec<ToolId>>,
 108    threads: Vec<SerializedThreadMetadata>,
 109    project_context: SharedProjectContext,
 110    reload_system_prompt_tx: mpsc::Sender<()>,
 111    _reload_system_prompt_task: Task<()>,
 112    _subscriptions: Vec<Subscription>,
 113}
 114
 115pub struct RulesLoadingError {
 116    pub message: SharedString,
 117}
 118
 119impl EventEmitter<RulesLoadingError> for ThreadStore {}
 120
 121impl ThreadStore {
 122    pub fn load(
 123        project: Entity<Project>,
 124        tools: Entity<ToolWorkingSet>,
 125        prompt_store: Option<Entity<PromptStore>>,
 126        prompt_builder: Arc<PromptBuilder>,
 127        cx: &mut App,
 128    ) -> Task<Result<Entity<Self>>> {
 129        cx.spawn(async move |cx| {
 130            let (thread_store, ready_rx) = cx.update(|cx| {
 131                let mut option_ready_rx = None;
 132                let thread_store = cx.new(|cx| {
 133                    let (thread_store, ready_rx) =
 134                        Self::new(project, tools, prompt_builder, prompt_store, cx);
 135                    option_ready_rx = Some(ready_rx);
 136                    thread_store
 137                });
 138                (thread_store, option_ready_rx.take().unwrap())
 139            })?;
 140            ready_rx.await?;
 141            Ok(thread_store)
 142        })
 143    }
 144
 145    fn new(
 146        project: Entity<Project>,
 147        tools: Entity<ToolWorkingSet>,
 148        prompt_builder: Arc<PromptBuilder>,
 149        prompt_store: Option<Entity<PromptStore>>,
 150        cx: &mut Context<Self>,
 151    ) -> (Self, oneshot::Receiver<()>) {
 152        let mut subscriptions = vec![cx.subscribe(&project, Self::handle_project_event)];
 153
 154        if let Some(prompt_store) = prompt_store.as_ref() {
 155            subscriptions.push(cx.subscribe(
 156                prompt_store,
 157                |this, _prompt_store, PromptsUpdatedEvent, _cx| {
 158                    this.enqueue_system_prompt_reload();
 159                },
 160            ))
 161        }
 162
 163        // This channel and task prevent concurrent and redundant loading of the system prompt.
 164        let (reload_system_prompt_tx, mut reload_system_prompt_rx) = mpsc::channel(1);
 165        let (ready_tx, ready_rx) = oneshot::channel();
 166        let mut ready_tx = Some(ready_tx);
 167        let reload_system_prompt_task = cx.spawn({
 168            let prompt_store = prompt_store.clone();
 169            async move |thread_store, cx| {
 170                loop {
 171                    let Some(reload_task) = thread_store
 172                        .update(cx, |thread_store, cx| {
 173                            thread_store.reload_system_prompt(prompt_store.clone(), cx)
 174                        })
 175                        .ok()
 176                    else {
 177                        return;
 178                    };
 179                    reload_task.await;
 180                    if let Some(ready_tx) = ready_tx.take() {
 181                        ready_tx.send(()).ok();
 182                    }
 183                    reload_system_prompt_rx.next().await;
 184                }
 185            }
 186        });
 187
 188        let this = Self {
 189            project,
 190            tools,
 191            prompt_builder,
 192            prompt_store,
 193            context_server_tool_ids: HashMap::default(),
 194            threads: Vec::new(),
 195            project_context: SharedProjectContext::default(),
 196            reload_system_prompt_tx,
 197            _reload_system_prompt_task: reload_system_prompt_task,
 198            _subscriptions: subscriptions,
 199        };
 200        this.register_context_server_handlers(cx);
 201        this.reload(cx).detach_and_log_err(cx);
 202        (this, ready_rx)
 203    }
 204
 205    fn handle_project_event(
 206        &mut self,
 207        _project: Entity<Project>,
 208        event: &project::Event,
 209        _cx: &mut Context<Self>,
 210    ) {
 211        match event {
 212            project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
 213                self.enqueue_system_prompt_reload();
 214            }
 215            project::Event::WorktreeUpdatedEntries(_, items) => {
 216                if items.iter().any(|(path, _, _)| {
 217                    RULES_FILE_NAMES
 218                        .iter()
 219                        .any(|name| path.as_ref() == Path::new(name))
 220                }) {
 221                    self.enqueue_system_prompt_reload();
 222                }
 223            }
 224            _ => {}
 225        }
 226    }
 227
 228    fn enqueue_system_prompt_reload(&mut self) {
 229        self.reload_system_prompt_tx.try_send(()).ok();
 230    }
 231
 232    // Note that this should only be called from `reload_system_prompt_task`.
 233    fn reload_system_prompt(
 234        &self,
 235        prompt_store: Option<Entity<PromptStore>>,
 236        cx: &mut Context<Self>,
 237    ) -> Task<()> {
 238        let worktrees = self
 239            .project
 240            .read(cx)
 241            .visible_worktrees(cx)
 242            .collect::<Vec<_>>();
 243        let worktree_tasks = worktrees
 244            .into_iter()
 245            .map(|worktree| {
 246                Self::load_worktree_info_for_system_prompt(worktree, self.project.clone(), cx)
 247            })
 248            .collect::<Vec<_>>();
 249        let default_user_rules_task = match prompt_store {
 250            None => Task::ready(vec![]),
 251            Some(prompt_store) => prompt_store.read_with(cx, |prompt_store, cx| {
 252                let prompts = prompt_store.default_prompt_metadata();
 253                let load_tasks = prompts.into_iter().map(|prompt_metadata| {
 254                    let contents = prompt_store.load(prompt_metadata.id, cx);
 255                    async move { (contents.await, prompt_metadata) }
 256                });
 257                cx.background_spawn(future::join_all(load_tasks))
 258            }),
 259        };
 260
 261        cx.spawn(async move |this, cx| {
 262            let (worktrees, default_user_rules) =
 263                future::join(future::join_all(worktree_tasks), default_user_rules_task).await;
 264
 265            let worktrees = worktrees
 266                .into_iter()
 267                .map(|(worktree, rules_error)| {
 268                    if let Some(rules_error) = rules_error {
 269                        this.update(cx, |_, cx| cx.emit(rules_error)).ok();
 270                    }
 271                    worktree
 272                })
 273                .collect::<Vec<_>>();
 274
 275            let default_user_rules = default_user_rules
 276                .into_iter()
 277                .flat_map(|(contents, prompt_metadata)| match contents {
 278                    Ok(contents) => Some(UserRulesContext {
 279                        uuid: match prompt_metadata.id {
 280                            PromptId::User { uuid } => uuid,
 281                            PromptId::EditWorkflow => return None,
 282                        },
 283                        title: prompt_metadata.title.map(|title| title.to_string()),
 284                        contents,
 285                    }),
 286                    Err(err) => {
 287                        this.update(cx, |_, cx| {
 288                            cx.emit(RulesLoadingError {
 289                                message: format!("{err:?}").into(),
 290                            });
 291                        })
 292                        .ok();
 293                        None
 294                    }
 295                })
 296                .collect::<Vec<_>>();
 297
 298            this.update(cx, |this, _cx| {
 299                *this.project_context.0.borrow_mut() =
 300                    Some(ProjectContext::new(worktrees, default_user_rules));
 301            })
 302            .ok();
 303        })
 304    }
 305
 306    fn load_worktree_info_for_system_prompt(
 307        worktree: Entity<Worktree>,
 308        project: Entity<Project>,
 309        cx: &mut App,
 310    ) -> Task<(WorktreeContext, Option<RulesLoadingError>)> {
 311        let tree = worktree.read(cx);
 312        let root_name = tree.root_name().into();
 313        let abs_path = tree.abs_path();
 314
 315        let mut context = WorktreeContext {
 316            root_name,
 317            abs_path,
 318            rules_file: None,
 319        };
 320
 321        let rules_task = Self::load_worktree_rules_file(worktree, project, cx);
 322        let Some(rules_task) = rules_task else {
 323            return Task::ready((context, None));
 324        };
 325
 326        cx.spawn(async move |_| {
 327            let (rules_file, rules_file_error) = match rules_task.await {
 328                Ok(rules_file) => (Some(rules_file), None),
 329                Err(err) => (
 330                    None,
 331                    Some(RulesLoadingError {
 332                        message: format!("{err}").into(),
 333                    }),
 334                ),
 335            };
 336            context.rules_file = rules_file;
 337            (context, rules_file_error)
 338        })
 339    }
 340
 341    fn load_worktree_rules_file(
 342        worktree: Entity<Worktree>,
 343        project: Entity<Project>,
 344        cx: &mut App,
 345    ) -> Option<Task<Result<RulesFileContext>>> {
 346        let worktree = worktree.read(cx);
 347        let worktree_id = worktree.id();
 348        let selected_rules_file = RULES_FILE_NAMES
 349            .into_iter()
 350            .filter_map(|name| {
 351                worktree
 352                    .entry_for_path(name)
 353                    .filter(|entry| entry.is_file())
 354                    .map(|entry| entry.path.clone())
 355            })
 356            .next();
 357
 358        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 359        // supported. This doesn't seem to occur often in GitHub repositories.
 360        selected_rules_file.map(|path_in_worktree| {
 361            let project_path = ProjectPath {
 362                worktree_id,
 363                path: path_in_worktree.clone(),
 364            };
 365            let buffer_task =
 366                project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 367            let rope_task = cx.spawn(async move |cx| {
 368                buffer_task.await?.read_with(cx, |buffer, cx| {
 369                    let project_entry_id = buffer.entry_id(cx).context("buffer has no file")?;
 370                    anyhow::Ok((project_entry_id, buffer.as_rope().clone()))
 371                })?
 372            });
 373            // Build a string from the rope on a background thread.
 374            cx.background_spawn(async move {
 375                let (project_entry_id, rope) = rope_task.await?;
 376                anyhow::Ok(RulesFileContext {
 377                    path_in_worktree,
 378                    text: rope.to_string().trim().to_string(),
 379                    project_entry_id: project_entry_id.to_usize(),
 380                })
 381            })
 382        })
 383    }
 384
 385    pub fn prompt_store(&self) -> &Option<Entity<PromptStore>> {
 386        &self.prompt_store
 387    }
 388
 389    pub fn tools(&self) -> Entity<ToolWorkingSet> {
 390        self.tools.clone()
 391    }
 392
 393    /// Returns the number of threads.
 394    pub fn thread_count(&self) -> usize {
 395        self.threads.len()
 396    }
 397
 398    pub fn reverse_chronological_threads(&self) -> impl Iterator<Item = &SerializedThreadMetadata> {
 399        // ordering is from "ORDER BY" in `list_threads`
 400        self.threads.iter()
 401    }
 402
 403    pub fn create_thread(&mut self, cx: &mut Context<Self>) -> Entity<ZedAgentThread> {
 404        cx.new(|cx| {
 405            ZedAgentThread::new(
 406                self.project.clone(),
 407                self.tools.clone(),
 408                self.prompt_builder.clone(),
 409                self.project_context.clone(),
 410                cx,
 411            )
 412        })
 413    }
 414
 415    pub fn create_thread_from_serialized(
 416        &mut self,
 417        serialized: SerializedThread,
 418        cx: &mut Context<Self>,
 419    ) -> Entity<ZedAgentThread> {
 420        cx.new(|cx| {
 421            ZedAgentThread::deserialize(
 422                ThreadId::new(),
 423                serialized,
 424                self.project.clone(),
 425                self.tools.clone(),
 426                self.prompt_builder.clone(),
 427                self.project_context.clone(),
 428                None,
 429                cx,
 430            )
 431        })
 432    }
 433
 434    pub fn open_thread(
 435        &self,
 436        id: &ThreadId,
 437        window: &mut Window,
 438        cx: &mut Context<Self>,
 439    ) -> Task<Result<Entity<ZedAgentThread>>> {
 440        let id = id.clone();
 441        let database_future = ThreadsDatabase::global_future(cx);
 442        let this = cx.weak_entity();
 443        window.spawn(cx, async move |cx| {
 444            let database = database_future.await.map_err(|err| anyhow!(err))?;
 445            let thread = database
 446                .try_find_thread(id.clone())
 447                .await?
 448                .with_context(|| format!("no thread found with ID: {id:?}"))?;
 449
 450            let thread = this.update_in(cx, |this, window, cx| {
 451                cx.new(|cx| {
 452                    ZedAgentThread::deserialize(
 453                        id.clone(),
 454                        thread,
 455                        this.project.clone(),
 456                        this.tools.clone(),
 457                        this.prompt_builder.clone(),
 458                        this.project_context.clone(),
 459                        Some(window),
 460                        cx,
 461                    )
 462                })
 463            })?;
 464
 465            Ok(thread)
 466        })
 467    }
 468
 469    pub fn save_thread(
 470        &self,
 471        thread: &Entity<ZedAgentThread>,
 472        cx: &mut Context<Self>,
 473    ) -> Task<Result<()>> {
 474        let (metadata, serialized_thread) = thread.update(cx, |thread, cx| {
 475            (thread.id().clone(), thread.serialize(cx))
 476        });
 477
 478        let database_future = ThreadsDatabase::global_future(cx);
 479        cx.spawn(async move |this, cx| {
 480            let serialized_thread = serialized_thread.await?;
 481            let database = database_future.await.map_err(|err| anyhow!(err))?;
 482            database.save_thread(metadata, serialized_thread).await?;
 483
 484            this.update(cx, |this, cx| this.reload(cx))?.await
 485        })
 486    }
 487
 488    pub fn delete_thread(&mut self, id: &ThreadId, cx: &mut Context<Self>) -> Task<Result<()>> {
 489        let id = id.clone();
 490        let database_future = ThreadsDatabase::global_future(cx);
 491        cx.spawn(async move |this, cx| {
 492            let database = database_future.await.map_err(|err| anyhow!(err))?;
 493            database.delete_thread(id.clone()).await?;
 494
 495            this.update(cx, |this, cx| {
 496                this.threads.retain(|thread| thread.id != id);
 497                cx.notify();
 498            })
 499        })
 500    }
 501
 502    pub fn reload(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 503        let database_future = ThreadsDatabase::global_future(cx);
 504        cx.spawn(async move |this, cx| {
 505            let threads = database_future
 506                .await
 507                .map_err(|err| anyhow!(err))?
 508                .list_threads()
 509                .await?;
 510
 511            this.update(cx, |this, cx| {
 512                this.threads = threads;
 513                cx.notify();
 514            })
 515        })
 516    }
 517
 518    fn register_context_server_handlers(&self, cx: &mut Context<Self>) {
 519        let context_server_store = self.project.read(cx).context_server_store();
 520        cx.subscribe(&context_server_store, Self::handle_context_server_event)
 521            .detach();
 522
 523        // Check for any servers that were already running before the handler was registered
 524        for server in context_server_store.read(cx).running_servers() {
 525            self.load_context_server_tools(server.id(), context_server_store.clone(), cx);
 526        }
 527    }
 528
 529    fn handle_context_server_event(
 530        &mut self,
 531        context_server_store: Entity<ContextServerStore>,
 532        event: &project::context_server_store::Event,
 533        cx: &mut Context<Self>,
 534    ) {
 535        let tool_working_set = self.tools.clone();
 536        match event {
 537            project::context_server_store::Event::ServerStatusChanged { server_id, status } => {
 538                match status {
 539                    ContextServerStatus::Starting => {}
 540                    ContextServerStatus::Running => {
 541                        self.load_context_server_tools(server_id.clone(), context_server_store, cx);
 542                    }
 543                    ContextServerStatus::Stopped | ContextServerStatus::Error(_) => {
 544                        if let Some(tool_ids) = self.context_server_tool_ids.remove(server_id) {
 545                            tool_working_set.update(cx, |tool_working_set, _| {
 546                                tool_working_set.remove(&tool_ids);
 547                            });
 548                        }
 549                    }
 550                }
 551            }
 552        }
 553    }
 554
 555    fn load_context_server_tools(
 556        &self,
 557        server_id: ContextServerId,
 558        context_server_store: Entity<ContextServerStore>,
 559        cx: &mut Context<Self>,
 560    ) {
 561        let Some(server) = context_server_store.read(cx).get_running_server(&server_id) else {
 562            return;
 563        };
 564        let tool_working_set = self.tools.clone();
 565        cx.spawn(async move |this, cx| {
 566            let Some(protocol) = server.client() else {
 567                return;
 568            };
 569
 570            if protocol.capable(context_server::protocol::ServerCapability::Tools) {
 571                if let Some(response) = protocol
 572                    .request::<context_server::types::requests::ListTools>(())
 573                    .await
 574                    .log_err()
 575                {
 576                    let tool_ids = tool_working_set
 577                        .update(cx, |tool_working_set, _| {
 578                            response
 579                                .tools
 580                                .into_iter()
 581                                .map(|tool| {
 582                                    log::info!("registering context server tool: {:?}", tool.name);
 583                                    tool_working_set.insert(Arc::new(ContextServerTool::new(
 584                                        context_server_store.clone(),
 585                                        server.id(),
 586                                        tool,
 587                                    )))
 588                                })
 589                                .collect::<Vec<_>>()
 590                        })
 591                        .log_err();
 592
 593                    if let Some(tool_ids) = tool_ids {
 594                        this.update(cx, |this, _| {
 595                            this.context_server_tool_ids.insert(server_id, tool_ids);
 596                        })
 597                        .log_err();
 598                    }
 599                }
 600            }
 601        })
 602        .detach();
 603    }
 604}
 605
 606#[derive(Debug, Clone, Serialize, Deserialize)]
 607pub struct SerializedThreadMetadata {
 608    pub id: ThreadId,
 609    pub summary: SharedString,
 610    pub updated_at: DateTime<Utc>,
 611}
 612
 613#[derive(Serialize, Deserialize, Debug, PartialEq)]
 614pub struct SerializedThread {
 615    pub version: String,
 616    pub summary: SharedString,
 617    pub updated_at: DateTime<Utc>,
 618    pub messages: Vec<SerializedMessage>,
 619    #[serde(default)]
 620    pub initial_project_snapshot: Option<Arc<ProjectSnapshot>>,
 621    #[serde(default)]
 622    pub cumulative_token_usage: TokenUsage,
 623    #[serde(default)]
 624    pub request_token_usage: Vec<TokenUsage>,
 625    #[serde(default)]
 626    pub detailed_summary_state: DetailedSummaryState,
 627    #[serde(default)]
 628    pub exceeded_window_error: Option<ExceededWindowError>,
 629    #[serde(default)]
 630    pub model: Option<SerializedLanguageModel>,
 631    #[serde(default)]
 632    pub completion_mode: Option<CompletionMode>,
 633    #[serde(default)]
 634    pub tool_use_limit_reached: bool,
 635    #[serde(default)]
 636    pub profile: Option<AgentProfileId>,
 637}
 638
 639#[derive(Serialize, Deserialize, Debug, PartialEq)]
 640pub struct SerializedLanguageModel {
 641    pub provider: String,
 642    pub model: String,
 643}
 644
 645impl SerializedThread {
 646    pub const VERSION: &'static str = "0.2.0";
 647
 648    pub fn from_json(json: &[u8]) -> Result<Self> {
 649        let saved_thread_json = serde_json::from_slice::<serde_json::Value>(json)?;
 650        match saved_thread_json.get("version") {
 651            Some(serde_json::Value::String(version)) => match version.as_str() {
 652                SerializedThreadV0_1_0::VERSION => {
 653                    let saved_thread =
 654                        serde_json::from_value::<SerializedThreadV0_1_0>(saved_thread_json)?;
 655                    Ok(saved_thread.upgrade())
 656                }
 657                SerializedThread::VERSION => Ok(serde_json::from_value::<SerializedThread>(
 658                    saved_thread_json,
 659                )?),
 660                _ => anyhow::bail!("unrecognized serialized thread version: {version:?}"),
 661            },
 662            None => {
 663                let saved_thread =
 664                    serde_json::from_value::<LegacySerializedThread>(saved_thread_json)?;
 665                Ok(saved_thread.upgrade())
 666            }
 667            version => anyhow::bail!("unrecognized serialized thread version: {version:?}"),
 668        }
 669    }
 670}
 671
 672#[derive(Serialize, Deserialize, Debug)]
 673pub struct SerializedThreadV0_1_0(
 674    // The structure did not change, so we are reusing the latest SerializedThread.
 675    // When making the next version, make sure this points to SerializedThreadV0_2_0
 676    SerializedThread,
 677);
 678
 679impl SerializedThreadV0_1_0 {
 680    pub const VERSION: &'static str = "0.1.0";
 681
 682    pub fn upgrade(self) -> SerializedThread {
 683        debug_assert_eq!(SerializedThread::VERSION, "0.2.0");
 684
 685        let mut messages: Vec<SerializedMessage> = Vec::with_capacity(self.0.messages.len());
 686
 687        for message in self.0.messages {
 688            if message.role == Role::User && !message.tool_results.is_empty() {
 689                if let Some(last_message) = messages.last_mut() {
 690                    debug_assert!(last_message.role == Role::Assistant);
 691
 692                    last_message.tool_results = message.tool_results;
 693                    continue;
 694                }
 695            }
 696
 697            messages.push(message);
 698        }
 699
 700        SerializedThread {
 701            messages,
 702            version: SerializedThread::VERSION.to_string(),
 703            ..self.0
 704        }
 705    }
 706}
 707
 708#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
 709pub struct SerializedMessage {
 710    pub id: MessageId,
 711    pub role: Role,
 712    #[serde(default)]
 713    pub segments: Vec<SerializedMessageSegment>,
 714    #[serde(default)]
 715    pub tool_uses: Vec<SerializedToolUse>,
 716    #[serde(default)]
 717    pub tool_results: Vec<SerializedToolResult>,
 718    #[serde(default)]
 719    pub context: String,
 720    #[serde(default)]
 721    pub creases: Vec<SerializedCrease>,
 722}
 723
 724#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
 725#[serde(tag = "type")]
 726pub enum SerializedMessageSegment {
 727    #[serde(rename = "text")]
 728    Text {
 729        text: String,
 730    },
 731    #[serde(rename = "thinking")]
 732    Thinking {
 733        text: String,
 734        #[serde(skip_serializing_if = "Option::is_none")]
 735        signature: Option<String>,
 736    },
 737    RedactedThinking {
 738        data: String,
 739    },
 740}
 741
 742#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
 743pub struct SerializedToolUse {
 744    pub id: LanguageModelToolUseId,
 745    pub name: SharedString,
 746    pub input: serde_json::Value,
 747}
 748
 749#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
 750pub struct SerializedToolResult {
 751    pub tool_use_id: LanguageModelToolUseId,
 752    pub is_error: bool,
 753    pub content: LanguageModelToolResultContent,
 754    pub output: Option<serde_json::Value>,
 755}
 756
 757#[derive(Serialize, Deserialize)]
 758struct LegacySerializedThread {
 759    pub summary: SharedString,
 760    pub updated_at: DateTime<Utc>,
 761    pub messages: Vec<LegacySerializedMessage>,
 762    #[serde(default)]
 763    pub initial_project_snapshot: Option<Arc<ProjectSnapshot>>,
 764}
 765
 766impl LegacySerializedThread {
 767    pub fn upgrade(self) -> SerializedThread {
 768        SerializedThread {
 769            version: SerializedThread::VERSION.to_string(),
 770            summary: self.summary,
 771            updated_at: self.updated_at,
 772            messages: self.messages.into_iter().map(|msg| msg.upgrade()).collect(),
 773            initial_project_snapshot: self.initial_project_snapshot,
 774            cumulative_token_usage: TokenUsage::default(),
 775            request_token_usage: Vec::new(),
 776            detailed_summary_state: DetailedSummaryState::default(),
 777            exceeded_window_error: None,
 778            model: None,
 779            completion_mode: None,
 780            tool_use_limit_reached: false,
 781            profile: None,
 782        }
 783    }
 784}
 785
 786#[derive(Debug, Serialize, Deserialize)]
 787struct LegacySerializedMessage {
 788    pub id: MessageId,
 789    pub role: Role,
 790    pub text: String,
 791    #[serde(default)]
 792    pub tool_uses: Vec<SerializedToolUse>,
 793    #[serde(default)]
 794    pub tool_results: Vec<SerializedToolResult>,
 795}
 796
 797impl LegacySerializedMessage {
 798    fn upgrade(self) -> SerializedMessage {
 799        SerializedMessage {
 800            id: self.id,
 801            role: self.role,
 802            segments: vec![SerializedMessageSegment::Text { text: self.text }],
 803            tool_uses: self.tool_uses,
 804            tool_results: self.tool_results,
 805            context: String::new(),
 806            creases: Vec::new(),
 807        }
 808    }
 809}
 810
 811#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
 812pub struct SerializedCrease {
 813    pub start: usize,
 814    pub end: usize,
 815    pub icon_path: SharedString,
 816    pub label: SharedString,
 817}
 818
 819struct GlobalThreadsDatabase(
 820    Shared<BoxFuture<'static, Result<Arc<ThreadsDatabase>, Arc<anyhow::Error>>>>,
 821);
 822
 823impl Global for GlobalThreadsDatabase {}
 824
 825pub(crate) struct ThreadsDatabase {
 826    executor: BackgroundExecutor,
 827    connection: Arc<Mutex<Connection>>,
 828}
 829
 830impl ThreadsDatabase {
 831    fn connection(&self) -> Arc<Mutex<Connection>> {
 832        self.connection.clone()
 833    }
 834
 835    const COMPRESSION_LEVEL: i32 = 3;
 836}
 837
 838impl Bind for ThreadId {
 839    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
 840        self.to_string().bind(statement, start_index)
 841    }
 842}
 843
 844impl Column for ThreadId {
 845    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
 846        let (id_str, next_index) = String::column(statement, start_index)?;
 847        Ok((ThreadId::from(id_str.as_str()), next_index))
 848    }
 849}
 850
 851impl ThreadsDatabase {
 852    fn global_future(
 853        cx: &mut App,
 854    ) -> Shared<BoxFuture<'static, Result<Arc<ThreadsDatabase>, Arc<anyhow::Error>>>> {
 855        GlobalThreadsDatabase::global(cx).0.clone()
 856    }
 857
 858    fn init(cx: &mut App) {
 859        let executor = cx.background_executor().clone();
 860        let database_future = executor
 861            .spawn({
 862                let executor = executor.clone();
 863                let threads_dir = paths::data_dir().join("threads");
 864                async move { ThreadsDatabase::new(threads_dir, executor) }
 865            })
 866            .then(|result| future::ready(result.map(Arc::new).map_err(Arc::new)))
 867            .boxed()
 868            .shared();
 869
 870        cx.set_global(GlobalThreadsDatabase(database_future));
 871    }
 872
 873    pub fn new(threads_dir: PathBuf, executor: BackgroundExecutor) -> Result<Self> {
 874        std::fs::create_dir_all(&threads_dir)?;
 875
 876        let sqlite_path = threads_dir.join("threads.db");
 877        let mdb_path = threads_dir.join("threads-db.1.mdb");
 878
 879        let needs_migration_from_heed = mdb_path.exists();
 880
 881        let connection = Connection::open_file(&sqlite_path.to_string_lossy());
 882
 883        connection.exec(indoc! {"
 884                CREATE TABLE IF NOT EXISTS threads (
 885                    id TEXT PRIMARY KEY,
 886                    summary TEXT NOT NULL,
 887                    updated_at TEXT NOT NULL,
 888                    data_type TEXT NOT NULL,
 889                    data BLOB NOT NULL
 890                )
 891            "})?()
 892        .map_err(|e| anyhow!("Failed to create threads table: {}", e))?;
 893
 894        let db = Self {
 895            executor: executor.clone(),
 896            connection: Arc::new(Mutex::new(connection)),
 897        };
 898
 899        if needs_migration_from_heed {
 900            let db_connection = db.connection();
 901            let executor_clone = executor.clone();
 902            executor
 903                .spawn(async move {
 904                    log::info!("Starting threads.db migration");
 905                    Self::migrate_from_heed(&mdb_path, db_connection, executor_clone)?;
 906                    std::fs::remove_dir_all(mdb_path)?;
 907                    log::info!("threads.db migrated to sqlite");
 908                    Ok::<(), anyhow::Error>(())
 909                })
 910                .detach();
 911        }
 912
 913        Ok(db)
 914    }
 915
 916    // Remove this migration after 2025-09-01
 917    fn migrate_from_heed(
 918        mdb_path: &Path,
 919        connection: Arc<Mutex<Connection>>,
 920        _executor: BackgroundExecutor,
 921    ) -> Result<()> {
 922        use heed::types::SerdeBincode;
 923        struct SerializedThreadHeed(SerializedThread);
 924
 925        impl heed::BytesEncode<'_> for SerializedThreadHeed {
 926            type EItem = SerializedThreadHeed;
 927
 928            fn bytes_encode(
 929                item: &Self::EItem,
 930            ) -> Result<std::borrow::Cow<'_, [u8]>, heed::BoxedError> {
 931                serde_json::to_vec(&item.0)
 932                    .map(std::borrow::Cow::Owned)
 933                    .map_err(Into::into)
 934            }
 935        }
 936
 937        impl<'a> heed::BytesDecode<'a> for SerializedThreadHeed {
 938            type DItem = SerializedThreadHeed;
 939
 940            fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, heed::BoxedError> {
 941                SerializedThread::from_json(bytes)
 942                    .map(SerializedThreadHeed)
 943                    .map_err(Into::into)
 944            }
 945        }
 946
 947        const ONE_GB_IN_BYTES: usize = 1024 * 1024 * 1024;
 948
 949        let env = unsafe {
 950            heed::EnvOpenOptions::new()
 951                .map_size(ONE_GB_IN_BYTES)
 952                .max_dbs(1)
 953                .open(mdb_path)?
 954        };
 955
 956        let txn = env.write_txn()?;
 957        let threads: heed::Database<SerdeBincode<ThreadId>, SerializedThreadHeed> = env
 958            .open_database(&txn, Some("threads"))?
 959            .ok_or_else(|| anyhow!("threads database not found"))?;
 960
 961        for result in threads.iter(&txn)? {
 962            let (thread_id, thread_heed) = result?;
 963            Self::save_thread_sync(&connection, thread_id, thread_heed.0)?;
 964        }
 965
 966        Ok(())
 967    }
 968
 969    fn save_thread_sync(
 970        connection: &Arc<Mutex<Connection>>,
 971        id: ThreadId,
 972        thread: SerializedThread,
 973    ) -> Result<()> {
 974        let json_data = serde_json::to_string(&thread)?;
 975        let summary = thread.summary.to_string();
 976        let updated_at = thread.updated_at.to_rfc3339();
 977
 978        let connection = connection.lock().unwrap();
 979
 980        let compressed = zstd::encode_all(json_data.as_bytes(), Self::COMPRESSION_LEVEL)?;
 981        let data_type = DataType::Zstd;
 982        let data = compressed;
 983
 984        let mut insert = connection.exec_bound::<(ThreadId, String, String, DataType, Vec<u8>)>(indoc! {"
 985            INSERT OR REPLACE INTO threads (id, summary, updated_at, data_type, data) VALUES (?, ?, ?, ?, ?)
 986        "})?;
 987
 988        insert((id, summary, updated_at, data_type, data))?;
 989
 990        Ok(())
 991    }
 992
 993    pub fn list_threads(&self) -> Task<Result<Vec<SerializedThreadMetadata>>> {
 994        let connection = self.connection.clone();
 995
 996        self.executor.spawn(async move {
 997            let connection = connection.lock().unwrap();
 998            let mut select =
 999                connection.select_bound::<(), (ThreadId, String, String)>(indoc! {"
1000                SELECT id, summary, updated_at FROM threads ORDER BY updated_at DESC
1001            "})?;
1002
1003            let rows = select(())?;
1004            let mut threads = Vec::new();
1005
1006            for (id, summary, updated_at) in rows {
1007                threads.push(SerializedThreadMetadata {
1008                    id,
1009                    summary: summary.into(),
1010                    updated_at: DateTime::parse_from_rfc3339(&updated_at)?.with_timezone(&Utc),
1011                });
1012            }
1013
1014            Ok(threads)
1015        })
1016    }
1017
1018    pub fn try_find_thread(&self, id: ThreadId) -> Task<Result<Option<SerializedThread>>> {
1019        let connection = self.connection.clone();
1020
1021        self.executor.spawn(async move {
1022            let connection = connection.lock().unwrap();
1023            let mut select = connection.select_bound::<ThreadId, (DataType, Vec<u8>)>(indoc! {"
1024                SELECT data_type, data FROM threads WHERE id = ? LIMIT 1
1025            "})?;
1026
1027            let rows = select(id)?;
1028            if let Some((data_type, data)) = rows.into_iter().next() {
1029                let json_data = match data_type {
1030                    DataType::Zstd => {
1031                        let decompressed = zstd::decode_all(&data[..])?;
1032                        String::from_utf8(decompressed)?
1033                    }
1034                    DataType::Json => String::from_utf8(data)?,
1035                };
1036
1037                let thread = SerializedThread::from_json(json_data.as_bytes())?;
1038                Ok(Some(thread))
1039            } else {
1040                Ok(None)
1041            }
1042        })
1043    }
1044
1045    pub fn save_thread(&self, id: ThreadId, thread: SerializedThread) -> Task<Result<()>> {
1046        let connection = self.connection.clone();
1047
1048        self.executor
1049            .spawn(async move { Self::save_thread_sync(&connection, id, thread) })
1050    }
1051
1052    pub fn delete_thread(&self, id: ThreadId) -> Task<Result<()>> {
1053        let connection = self.connection.clone();
1054
1055        self.executor.spawn(async move {
1056            let connection = connection.lock().unwrap();
1057
1058            let mut delete = connection.exec_bound::<ThreadId>(indoc! {"
1059                DELETE FROM threads WHERE id = ?
1060            "})?;
1061
1062            delete(id)?;
1063
1064            Ok(())
1065        })
1066    }
1067}
1068
1069#[cfg(test)]
1070mod tests {
1071    use super::*;
1072    use crate::thread::{DetailedSummaryState, MessageId};
1073    use chrono::Utc;
1074    use language_model::{Role, TokenUsage};
1075    use pretty_assertions::assert_eq;
1076
1077    #[test]
1078    fn test_legacy_serialized_thread_upgrade() {
1079        let updated_at = Utc::now();
1080        let legacy_thread = LegacySerializedThread {
1081            summary: "Test conversation".into(),
1082            updated_at,
1083            messages: vec![LegacySerializedMessage {
1084                id: MessageId(1),
1085                role: Role::User,
1086                text: "Hello, world!".to_string(),
1087                tool_uses: vec![],
1088                tool_results: vec![],
1089            }],
1090            initial_project_snapshot: None,
1091        };
1092
1093        let upgraded = legacy_thread.upgrade();
1094
1095        assert_eq!(
1096            upgraded,
1097            SerializedThread {
1098                summary: "Test conversation".into(),
1099                updated_at,
1100                messages: vec![SerializedMessage {
1101                    id: MessageId(1),
1102                    role: Role::User,
1103                    segments: vec![SerializedMessageSegment::Text {
1104                        text: "Hello, world!".to_string()
1105                    }],
1106                    tool_uses: vec![],
1107                    tool_results: vec![],
1108                    context: "".to_string(),
1109                    creases: vec![],
1110                }],
1111                version: SerializedThread::VERSION.to_string(),
1112                initial_project_snapshot: None,
1113                cumulative_token_usage: TokenUsage::default(),
1114                request_token_usage: vec![],
1115                detailed_summary_state: DetailedSummaryState::default(),
1116                exceeded_window_error: None,
1117                model: None,
1118                completion_mode: None,
1119                tool_use_limit_reached: false,
1120                profile: None
1121            }
1122        )
1123    }
1124
1125    #[test]
1126    fn test_serialized_threadv0_1_0_upgrade() {
1127        let updated_at = Utc::now();
1128        let thread_v0_1_0 = SerializedThreadV0_1_0(SerializedThread {
1129            summary: "Test conversation".into(),
1130            updated_at,
1131            messages: vec![
1132                SerializedMessage {
1133                    id: MessageId(1),
1134                    role: Role::User,
1135                    segments: vec![SerializedMessageSegment::Text {
1136                        text: "Use tool_1".to_string(),
1137                    }],
1138                    tool_uses: vec![],
1139                    tool_results: vec![],
1140                    context: "".to_string(),
1141                    creases: vec![],
1142                },
1143                SerializedMessage {
1144                    id: MessageId(2),
1145                    role: Role::Assistant,
1146                    segments: vec![SerializedMessageSegment::Text {
1147                        text: "I want to use a tool".to_string(),
1148                    }],
1149                    tool_uses: vec![SerializedToolUse {
1150                        id: "abc".into(),
1151                        name: "tool_1".into(),
1152                        input: serde_json::Value::Null,
1153                    }],
1154                    tool_results: vec![],
1155                    context: "".to_string(),
1156                    creases: vec![],
1157                },
1158                SerializedMessage {
1159                    id: MessageId(1),
1160                    role: Role::User,
1161                    segments: vec![SerializedMessageSegment::Text {
1162                        text: "Here is the tool result".to_string(),
1163                    }],
1164                    tool_uses: vec![],
1165                    tool_results: vec![SerializedToolResult {
1166                        tool_use_id: "abc".into(),
1167                        is_error: false,
1168                        content: LanguageModelToolResultContent::Text("abcdef".into()),
1169                        output: Some(serde_json::Value::Null),
1170                    }],
1171                    context: "".to_string(),
1172                    creases: vec![],
1173                },
1174            ],
1175            version: SerializedThreadV0_1_0::VERSION.to_string(),
1176            initial_project_snapshot: None,
1177            cumulative_token_usage: TokenUsage::default(),
1178            request_token_usage: vec![],
1179            detailed_summary_state: DetailedSummaryState::default(),
1180            exceeded_window_error: None,
1181            model: None,
1182            completion_mode: None,
1183            tool_use_limit_reached: false,
1184            profile: None,
1185        });
1186        let upgraded = thread_v0_1_0.upgrade();
1187
1188        assert_eq!(
1189            upgraded,
1190            SerializedThread {
1191                summary: "Test conversation".into(),
1192                updated_at,
1193                messages: vec![
1194                    SerializedMessage {
1195                        id: MessageId(1),
1196                        role: Role::User,
1197                        segments: vec![SerializedMessageSegment::Text {
1198                            text: "Use tool_1".to_string()
1199                        }],
1200                        tool_uses: vec![],
1201                        tool_results: vec![],
1202                        context: "".to_string(),
1203                        creases: vec![],
1204                    },
1205                    SerializedMessage {
1206                        id: MessageId(2),
1207                        role: Role::Assistant,
1208                        segments: vec![SerializedMessageSegment::Text {
1209                            text: "I want to use a tool".to_string(),
1210                        }],
1211                        tool_uses: vec![SerializedToolUse {
1212                            id: "abc".into(),
1213                            name: "tool_1".into(),
1214                            input: serde_json::Value::Null,
1215                        }],
1216                        tool_results: vec![SerializedToolResult {
1217                            tool_use_id: "abc".into(),
1218                            is_error: false,
1219                            content: LanguageModelToolResultContent::Text("abcdef".into()),
1220                            output: Some(serde_json::Value::Null),
1221                        }],
1222                        context: "".to_string(),
1223                        creases: vec![],
1224                    },
1225                ],
1226                version: SerializedThread::VERSION.to_string(),
1227                initial_project_snapshot: None,
1228                cumulative_token_usage: TokenUsage::default(),
1229                request_token_usage: vec![],
1230                detailed_summary_state: DetailedSummaryState::default(),
1231                exceeded_window_error: None,
1232                model: None,
1233                completion_mode: None,
1234                tool_use_limit_reached: false,
1235                profile: None
1236            }
1237        )
1238    }
1239}