persistence.rs

   1pub mod model;
   2
   3use std::{
   4    borrow::Cow,
   5    collections::BTreeMap,
   6    path::{Path, PathBuf},
   7    str::FromStr,
   8    sync::Arc,
   9};
  10
  11use chrono::{DateTime, NaiveDateTime, Utc};
  12use fs::Fs;
  13
  14use anyhow::{Context as _, Result, bail};
  15use collections::{HashMap, HashSet, IndexSet};
  16use db::{
  17    kvp::KeyValueStore,
  18    query,
  19    sqlez::{connection::Connection, domain::Domain},
  20    sqlez_macros::sql,
  21};
  22use gpui::{Axis, Bounds, Task, WindowBounds, WindowId, point, size};
  23use project::{
  24    debugger::breakpoint_store::{BreakpointState, SourceBreakpoint},
  25    trusted_worktrees::{DbTrustedPaths, RemoteHostLocation},
  26};
  27
  28use language::{LanguageName, Toolchain, ToolchainScope};
  29use remote::{
  30    DockerConnectionOptions, RemoteConnectionOptions, SshConnectionOptions, WslConnectionOptions,
  31};
  32use serde::{Deserialize, Serialize};
  33use sqlez::{
  34    bindable::{Bind, Column, StaticColumnCount},
  35    statement::Statement,
  36    thread_safe_connection::ThreadSafeConnection,
  37};
  38
  39use ui::{App, SharedString, px};
  40use util::{ResultExt, maybe, rel_path::RelPath};
  41use uuid::Uuid;
  42
  43use crate::{
  44    WorkspaceId,
  45    path_list::{PathList, SerializedPathList},
  46    persistence::model::RemoteConnectionKind,
  47};
  48
  49use model::{
  50    GroupId, ItemId, PaneId, RemoteConnectionId, SerializedItem, SerializedPane,
  51    SerializedPaneGroup, SerializedWorkspace,
  52};
  53
  54use self::model::{DockStructure, SerializedWorkspaceLocation, SessionWorkspace};
  55
  56// https://www.sqlite.org/limits.html
  57// > <..> the maximum value of a host parameter number is SQLITE_MAX_VARIABLE_NUMBER,
  58// > which defaults to <..> 32766 for SQLite versions after 3.32.0.
  59const MAX_QUERY_PLACEHOLDERS: usize = 32000;
  60
  61fn parse_timestamp(text: &str) -> DateTime<Utc> {
  62    NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S")
  63        .map(|naive| naive.and_utc())
  64        .unwrap_or_else(|_| Utc::now())
  65}
  66
  67#[derive(Copy, Clone, Debug, PartialEq)]
  68pub(crate) struct SerializedAxis(pub(crate) gpui::Axis);
  69impl sqlez::bindable::StaticColumnCount for SerializedAxis {}
  70impl sqlez::bindable::Bind for SerializedAxis {
  71    fn bind(
  72        &self,
  73        statement: &sqlez::statement::Statement,
  74        start_index: i32,
  75    ) -> anyhow::Result<i32> {
  76        match self.0 {
  77            gpui::Axis::Horizontal => "Horizontal",
  78            gpui::Axis::Vertical => "Vertical",
  79        }
  80        .bind(statement, start_index)
  81    }
  82}
  83
  84impl sqlez::bindable::Column for SerializedAxis {
  85    fn column(
  86        statement: &mut sqlez::statement::Statement,
  87        start_index: i32,
  88    ) -> anyhow::Result<(Self, i32)> {
  89        String::column(statement, start_index).and_then(|(axis_text, next_index)| {
  90            Ok((
  91                match axis_text.as_str() {
  92                    "Horizontal" => Self(Axis::Horizontal),
  93                    "Vertical" => Self(Axis::Vertical),
  94                    _ => anyhow::bail!("Stored serialized item kind is incorrect"),
  95                },
  96                next_index,
  97            ))
  98        })
  99    }
 100}
 101
 102#[derive(Copy, Clone, Debug, PartialEq, Default)]
 103pub(crate) struct SerializedWindowBounds(pub(crate) WindowBounds);
 104
 105impl StaticColumnCount for SerializedWindowBounds {
 106    fn column_count() -> usize {
 107        5
 108    }
 109}
 110
 111impl Bind for SerializedWindowBounds {
 112    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
 113        match self.0 {
 114            WindowBounds::Windowed(bounds) => {
 115                let next_index = statement.bind(&"Windowed", start_index)?;
 116                statement.bind(
 117                    &(
 118                        SerializedPixels(bounds.origin.x),
 119                        SerializedPixels(bounds.origin.y),
 120                        SerializedPixels(bounds.size.width),
 121                        SerializedPixels(bounds.size.height),
 122                    ),
 123                    next_index,
 124                )
 125            }
 126            WindowBounds::Maximized(bounds) => {
 127                let next_index = statement.bind(&"Maximized", start_index)?;
 128                statement.bind(
 129                    &(
 130                        SerializedPixels(bounds.origin.x),
 131                        SerializedPixels(bounds.origin.y),
 132                        SerializedPixels(bounds.size.width),
 133                        SerializedPixels(bounds.size.height),
 134                    ),
 135                    next_index,
 136                )
 137            }
 138            WindowBounds::Fullscreen(bounds) => {
 139                let next_index = statement.bind(&"FullScreen", start_index)?;
 140                statement.bind(
 141                    &(
 142                        SerializedPixels(bounds.origin.x),
 143                        SerializedPixels(bounds.origin.y),
 144                        SerializedPixels(bounds.size.width),
 145                        SerializedPixels(bounds.size.height),
 146                    ),
 147                    next_index,
 148                )
 149            }
 150        }
 151    }
 152}
 153
 154impl Column for SerializedWindowBounds {
 155    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
 156        let (window_state, next_index) = String::column(statement, start_index)?;
 157        let ((x, y, width, height), _): ((i32, i32, i32, i32), _) =
 158            Column::column(statement, next_index)?;
 159        let bounds = Bounds {
 160            origin: point(px(x as f32), px(y as f32)),
 161            size: size(px(width as f32), px(height as f32)),
 162        };
 163
 164        let status = match window_state.as_str() {
 165            "Windowed" | "Fixed" => SerializedWindowBounds(WindowBounds::Windowed(bounds)),
 166            "Maximized" => SerializedWindowBounds(WindowBounds::Maximized(bounds)),
 167            "FullScreen" => SerializedWindowBounds(WindowBounds::Fullscreen(bounds)),
 168            _ => bail!("Window State did not have a valid string"),
 169        };
 170
 171        Ok((status, next_index + 4))
 172    }
 173}
 174
 175const DEFAULT_WINDOW_BOUNDS_KEY: &str = "default_window_bounds";
 176
 177pub fn read_default_window_bounds(kvp: &KeyValueStore) -> Option<(Uuid, WindowBounds)> {
 178    let json_str = kvp
 179        .read_kvp(DEFAULT_WINDOW_BOUNDS_KEY)
 180        .log_err()
 181        .flatten()?;
 182
 183    let (display_uuid, persisted) =
 184        serde_json::from_str::<(Uuid, WindowBoundsJson)>(&json_str).ok()?;
 185    Some((display_uuid, persisted.into()))
 186}
 187
 188pub async fn write_default_window_bounds(
 189    kvp: &KeyValueStore,
 190    bounds: WindowBounds,
 191    display_uuid: Uuid,
 192) -> anyhow::Result<()> {
 193    let persisted = WindowBoundsJson::from(bounds);
 194    let json_str = serde_json::to_string(&(display_uuid, persisted))?;
 195    kvp.write_kvp(DEFAULT_WINDOW_BOUNDS_KEY.to_string(), json_str)
 196        .await?;
 197    Ok(())
 198}
 199
 200#[derive(Serialize, Deserialize)]
 201pub enum WindowBoundsJson {
 202    Windowed {
 203        x: i32,
 204        y: i32,
 205        width: i32,
 206        height: i32,
 207    },
 208    Maximized {
 209        x: i32,
 210        y: i32,
 211        width: i32,
 212        height: i32,
 213    },
 214    Fullscreen {
 215        x: i32,
 216        y: i32,
 217        width: i32,
 218        height: i32,
 219    },
 220}
 221
 222impl From<WindowBounds> for WindowBoundsJson {
 223    fn from(b: WindowBounds) -> Self {
 224        match b {
 225            WindowBounds::Windowed(bounds) => {
 226                let origin = bounds.origin;
 227                let size = bounds.size;
 228                WindowBoundsJson::Windowed {
 229                    x: f32::from(origin.x).round() as i32,
 230                    y: f32::from(origin.y).round() as i32,
 231                    width: f32::from(size.width).round() as i32,
 232                    height: f32::from(size.height).round() as i32,
 233                }
 234            }
 235            WindowBounds::Maximized(bounds) => {
 236                let origin = bounds.origin;
 237                let size = bounds.size;
 238                WindowBoundsJson::Maximized {
 239                    x: f32::from(origin.x).round() as i32,
 240                    y: f32::from(origin.y).round() as i32,
 241                    width: f32::from(size.width).round() as i32,
 242                    height: f32::from(size.height).round() as i32,
 243                }
 244            }
 245            WindowBounds::Fullscreen(bounds) => {
 246                let origin = bounds.origin;
 247                let size = bounds.size;
 248                WindowBoundsJson::Fullscreen {
 249                    x: f32::from(origin.x).round() as i32,
 250                    y: f32::from(origin.y).round() as i32,
 251                    width: f32::from(size.width).round() as i32,
 252                    height: f32::from(size.height).round() as i32,
 253                }
 254            }
 255        }
 256    }
 257}
 258
 259impl From<WindowBoundsJson> for WindowBounds {
 260    fn from(n: WindowBoundsJson) -> Self {
 261        match n {
 262            WindowBoundsJson::Windowed {
 263                x,
 264                y,
 265                width,
 266                height,
 267            } => WindowBounds::Windowed(Bounds {
 268                origin: point(px(x as f32), px(y as f32)),
 269                size: size(px(width as f32), px(height as f32)),
 270            }),
 271            WindowBoundsJson::Maximized {
 272                x,
 273                y,
 274                width,
 275                height,
 276            } => WindowBounds::Maximized(Bounds {
 277                origin: point(px(x as f32), px(y as f32)),
 278                size: size(px(width as f32), px(height as f32)),
 279            }),
 280            WindowBoundsJson::Fullscreen {
 281                x,
 282                y,
 283                width,
 284                height,
 285            } => WindowBounds::Fullscreen(Bounds {
 286                origin: point(px(x as f32), px(y as f32)),
 287                size: size(px(width as f32), px(height as f32)),
 288            }),
 289        }
 290    }
 291}
 292
 293fn read_multi_workspace_state(window_id: WindowId, cx: &App) -> model::MultiWorkspaceState {
 294    let kvp = KeyValueStore::global(cx);
 295    kvp.scoped("multi_workspace_state")
 296        .read(&window_id.as_u64().to_string())
 297        .log_err()
 298        .flatten()
 299        .and_then(|json| serde_json::from_str(&json).ok())
 300        .unwrap_or_default()
 301}
 302
 303pub async fn write_multi_workspace_state(
 304    kvp: &KeyValueStore,
 305    window_id: WindowId,
 306    state: model::MultiWorkspaceState,
 307) {
 308    if let Ok(json_str) = serde_json::to_string(&state) {
 309        kvp.scoped("multi_workspace_state")
 310            .write(window_id.as_u64().to_string(), json_str)
 311            .await
 312            .log_err();
 313    }
 314}
 315
 316pub fn read_serialized_multi_workspaces(
 317    session_workspaces: Vec<model::SessionWorkspace>,
 318    cx: &App,
 319) -> Vec<model::SerializedMultiWorkspace> {
 320    let mut window_groups: Vec<Vec<model::SessionWorkspace>> = Vec::new();
 321    let mut window_id_to_group: HashMap<WindowId, usize> = HashMap::default();
 322
 323    for session_workspace in session_workspaces {
 324        match session_workspace.window_id {
 325            Some(window_id) => {
 326                let group_index = *window_id_to_group.entry(window_id).or_insert_with(|| {
 327                    window_groups.push(Vec::new());
 328                    window_groups.len() - 1
 329                });
 330                window_groups[group_index].push(session_workspace);
 331            }
 332            None => {
 333                window_groups.push(vec![session_workspace]);
 334            }
 335        }
 336    }
 337
 338    window_groups
 339        .into_iter()
 340        .filter_map(|group| {
 341            let window_id = group.first().and_then(|sw| sw.window_id);
 342            let state = window_id
 343                .map(|wid| read_multi_workspace_state(wid, cx))
 344                .unwrap_or_default();
 345            let active_workspace = state
 346                .active_workspace_id
 347                .and_then(|id| group.iter().position(|ws| ws.workspace_id == id))
 348                .or(Some(0))
 349                .and_then(|index| group.into_iter().nth(index))?;
 350            Some(model::SerializedMultiWorkspace {
 351                active_workspace,
 352                state,
 353            })
 354        })
 355        .collect()
 356}
 357
 358const DEFAULT_DOCK_STATE_KEY: &str = "default_dock_state";
 359
 360pub fn read_default_dock_state(kvp: &KeyValueStore) -> Option<DockStructure> {
 361    let json_str = kvp.read_kvp(DEFAULT_DOCK_STATE_KEY).log_err().flatten()?;
 362
 363    serde_json::from_str::<DockStructure>(&json_str).ok()
 364}
 365
 366pub async fn write_default_dock_state(
 367    kvp: &KeyValueStore,
 368    docks: DockStructure,
 369) -> anyhow::Result<()> {
 370    let json_str = serde_json::to_string(&docks)?;
 371    kvp.write_kvp(DEFAULT_DOCK_STATE_KEY.to_string(), json_str)
 372        .await?;
 373    Ok(())
 374}
 375
 376#[derive(Debug)]
 377pub struct Breakpoint {
 378    pub position: u32,
 379    pub message: Option<Arc<str>>,
 380    pub condition: Option<Arc<str>>,
 381    pub hit_condition: Option<Arc<str>>,
 382    pub state: BreakpointState,
 383}
 384
 385/// Wrapper for DB type of a breakpoint
 386struct BreakpointStateWrapper<'a>(Cow<'a, BreakpointState>);
 387
 388impl From<BreakpointState> for BreakpointStateWrapper<'static> {
 389    fn from(kind: BreakpointState) -> Self {
 390        BreakpointStateWrapper(Cow::Owned(kind))
 391    }
 392}
 393
 394impl StaticColumnCount for BreakpointStateWrapper<'_> {
 395    fn column_count() -> usize {
 396        1
 397    }
 398}
 399
 400impl Bind for BreakpointStateWrapper<'_> {
 401    fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
 402        statement.bind(&self.0.to_int(), start_index)
 403    }
 404}
 405
 406impl Column for BreakpointStateWrapper<'_> {
 407    fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
 408        let state = statement.column_int(start_index)?;
 409
 410        match state {
 411            0 => Ok((BreakpointState::Enabled.into(), start_index + 1)),
 412            1 => Ok((BreakpointState::Disabled.into(), start_index + 1)),
 413            _ => anyhow::bail!("Invalid BreakpointState discriminant {state}"),
 414        }
 415    }
 416}
 417
 418impl sqlez::bindable::StaticColumnCount for Breakpoint {
 419    fn column_count() -> usize {
 420        // Position, log message, condition message, and hit condition message
 421        4 + BreakpointStateWrapper::column_count()
 422    }
 423}
 424
 425impl sqlez::bindable::Bind for Breakpoint {
 426    fn bind(
 427        &self,
 428        statement: &sqlez::statement::Statement,
 429        start_index: i32,
 430    ) -> anyhow::Result<i32> {
 431        let next_index = statement.bind(&self.position, start_index)?;
 432        let next_index = statement.bind(&self.message, next_index)?;
 433        let next_index = statement.bind(&self.condition, next_index)?;
 434        let next_index = statement.bind(&self.hit_condition, next_index)?;
 435        statement.bind(
 436            &BreakpointStateWrapper(Cow::Borrowed(&self.state)),
 437            next_index,
 438        )
 439    }
 440}
 441
 442impl Column for Breakpoint {
 443    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
 444        let position = statement
 445            .column_int(start_index)
 446            .with_context(|| format!("Failed to read BreakPoint at index {start_index}"))?
 447            as u32;
 448        let (message, next_index) = Option::<String>::column(statement, start_index + 1)?;
 449        let (condition, next_index) = Option::<String>::column(statement, next_index)?;
 450        let (hit_condition, next_index) = Option::<String>::column(statement, next_index)?;
 451        let (state, next_index) = BreakpointStateWrapper::column(statement, next_index)?;
 452
 453        Ok((
 454            Breakpoint {
 455                position,
 456                message: message.map(Arc::from),
 457                condition: condition.map(Arc::from),
 458                hit_condition: hit_condition.map(Arc::from),
 459                state: state.0.into_owned(),
 460            },
 461            next_index,
 462        ))
 463    }
 464}
 465
 466#[derive(Clone, Debug, PartialEq)]
 467struct SerializedPixels(gpui::Pixels);
 468impl sqlez::bindable::StaticColumnCount for SerializedPixels {}
 469
 470impl sqlez::bindable::Bind for SerializedPixels {
 471    fn bind(
 472        &self,
 473        statement: &sqlez::statement::Statement,
 474        start_index: i32,
 475    ) -> anyhow::Result<i32> {
 476        let this: i32 = u32::from(self.0) as _;
 477        this.bind(statement, start_index)
 478    }
 479}
 480
 481pub struct WorkspaceDb(ThreadSafeConnection);
 482
 483impl Domain for WorkspaceDb {
 484    const NAME: &str = stringify!(WorkspaceDb);
 485
 486    const MIGRATIONS: &[&str] = &[
 487        sql!(
 488            CREATE TABLE workspaces(
 489                workspace_id INTEGER PRIMARY KEY,
 490                workspace_location BLOB UNIQUE,
 491                dock_visible INTEGER, // Deprecated. Preserving so users can downgrade Zed.
 492                dock_anchor TEXT, // Deprecated. Preserving so users can downgrade Zed.
 493                dock_pane INTEGER, // Deprecated.  Preserving so users can downgrade Zed.
 494                left_sidebar_open INTEGER, // Boolean
 495                timestamp TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,
 496                FOREIGN KEY(dock_pane) REFERENCES panes(pane_id)
 497            ) STRICT;
 498
 499            CREATE TABLE pane_groups(
 500                group_id INTEGER PRIMARY KEY,
 501                workspace_id INTEGER NOT NULL,
 502                parent_group_id INTEGER, // NULL indicates that this is a root node
 503                position INTEGER, // NULL indicates that this is a root node
 504                axis TEXT NOT NULL, // Enum: 'Vertical' / 'Horizontal'
 505                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
 506                ON DELETE CASCADE
 507                ON UPDATE CASCADE,
 508                FOREIGN KEY(parent_group_id) REFERENCES pane_groups(group_id) ON DELETE CASCADE
 509            ) STRICT;
 510
 511            CREATE TABLE panes(
 512                pane_id INTEGER PRIMARY KEY,
 513                workspace_id INTEGER NOT NULL,
 514                active INTEGER NOT NULL, // Boolean
 515                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
 516                ON DELETE CASCADE
 517                ON UPDATE CASCADE
 518            ) STRICT;
 519
 520            CREATE TABLE center_panes(
 521                pane_id INTEGER PRIMARY KEY,
 522                parent_group_id INTEGER, // NULL means that this is a root pane
 523                position INTEGER, // NULL means that this is a root pane
 524                FOREIGN KEY(pane_id) REFERENCES panes(pane_id)
 525                ON DELETE CASCADE,
 526                FOREIGN KEY(parent_group_id) REFERENCES pane_groups(group_id) ON DELETE CASCADE
 527            ) STRICT;
 528
 529            CREATE TABLE items(
 530                item_id INTEGER NOT NULL, // This is the item's view id, so this is not unique
 531                workspace_id INTEGER NOT NULL,
 532                pane_id INTEGER NOT NULL,
 533                kind TEXT NOT NULL,
 534                position INTEGER NOT NULL,
 535                active INTEGER NOT NULL,
 536                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
 537                ON DELETE CASCADE
 538                ON UPDATE CASCADE,
 539                FOREIGN KEY(pane_id) REFERENCES panes(pane_id)
 540                ON DELETE CASCADE,
 541                PRIMARY KEY(item_id, workspace_id)
 542            ) STRICT;
 543        ),
 544        sql!(
 545            ALTER TABLE workspaces ADD COLUMN window_state TEXT;
 546            ALTER TABLE workspaces ADD COLUMN window_x REAL;
 547            ALTER TABLE workspaces ADD COLUMN window_y REAL;
 548            ALTER TABLE workspaces ADD COLUMN window_width REAL;
 549            ALTER TABLE workspaces ADD COLUMN window_height REAL;
 550            ALTER TABLE workspaces ADD COLUMN display BLOB;
 551        ),
 552        // Drop foreign key constraint from workspaces.dock_pane to panes table.
 553        sql!(
 554            CREATE TABLE workspaces_2(
 555                workspace_id INTEGER PRIMARY KEY,
 556                workspace_location BLOB UNIQUE,
 557                dock_visible INTEGER, // Deprecated. Preserving so users can downgrade Zed.
 558                dock_anchor TEXT, // Deprecated. Preserving so users can downgrade Zed.
 559                dock_pane INTEGER, // Deprecated.  Preserving so users can downgrade Zed.
 560                left_sidebar_open INTEGER, // Boolean
 561                timestamp TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,
 562                window_state TEXT,
 563                window_x REAL,
 564                window_y REAL,
 565                window_width REAL,
 566                window_height REAL,
 567                display BLOB
 568            ) STRICT;
 569            INSERT INTO workspaces_2 SELECT * FROM workspaces;
 570            DROP TABLE workspaces;
 571            ALTER TABLE workspaces_2 RENAME TO workspaces;
 572        ),
 573        // Add panels related information
 574        sql!(
 575            ALTER TABLE workspaces ADD COLUMN left_dock_visible INTEGER; //bool
 576            ALTER TABLE workspaces ADD COLUMN left_dock_active_panel TEXT;
 577            ALTER TABLE workspaces ADD COLUMN right_dock_visible INTEGER; //bool
 578            ALTER TABLE workspaces ADD COLUMN right_dock_active_panel TEXT;
 579            ALTER TABLE workspaces ADD COLUMN bottom_dock_visible INTEGER; //bool
 580            ALTER TABLE workspaces ADD COLUMN bottom_dock_active_panel TEXT;
 581        ),
 582        // Add panel zoom persistence
 583        sql!(
 584            ALTER TABLE workspaces ADD COLUMN left_dock_zoom INTEGER; //bool
 585            ALTER TABLE workspaces ADD COLUMN right_dock_zoom INTEGER; //bool
 586            ALTER TABLE workspaces ADD COLUMN bottom_dock_zoom INTEGER; //bool
 587        ),
 588        // Add pane group flex data
 589        sql!(
 590            ALTER TABLE pane_groups ADD COLUMN flexes TEXT;
 591        ),
 592        // Add fullscreen field to workspace
 593        // Deprecated, `WindowBounds` holds the fullscreen state now.
 594        // Preserving so users can downgrade Zed.
 595        sql!(
 596            ALTER TABLE workspaces ADD COLUMN fullscreen INTEGER; //bool
 597        ),
 598        // Add preview field to items
 599        sql!(
 600            ALTER TABLE items ADD COLUMN preview INTEGER; //bool
 601        ),
 602        // Add centered_layout field to workspace
 603        sql!(
 604            ALTER TABLE workspaces ADD COLUMN centered_layout INTEGER; //bool
 605        ),
 606        sql!(
 607            CREATE TABLE remote_projects (
 608                remote_project_id INTEGER NOT NULL UNIQUE,
 609                path TEXT,
 610                dev_server_name TEXT
 611            );
 612            ALTER TABLE workspaces ADD COLUMN remote_project_id INTEGER;
 613            ALTER TABLE workspaces RENAME COLUMN workspace_location TO local_paths;
 614        ),
 615        sql!(
 616            DROP TABLE remote_projects;
 617            CREATE TABLE dev_server_projects (
 618                id INTEGER NOT NULL UNIQUE,
 619                path TEXT,
 620                dev_server_name TEXT
 621            );
 622            ALTER TABLE workspaces DROP COLUMN remote_project_id;
 623            ALTER TABLE workspaces ADD COLUMN dev_server_project_id INTEGER;
 624        ),
 625        sql!(
 626            ALTER TABLE workspaces ADD COLUMN local_paths_order BLOB;
 627        ),
 628        sql!(
 629            ALTER TABLE workspaces ADD COLUMN session_id TEXT DEFAULT NULL;
 630        ),
 631        sql!(
 632            ALTER TABLE workspaces ADD COLUMN window_id INTEGER DEFAULT NULL;
 633        ),
 634        sql!(
 635            ALTER TABLE panes ADD COLUMN pinned_count INTEGER DEFAULT 0;
 636        ),
 637        sql!(
 638            CREATE TABLE ssh_projects (
 639                id INTEGER PRIMARY KEY,
 640                host TEXT NOT NULL,
 641                port INTEGER,
 642                path TEXT NOT NULL,
 643                user TEXT
 644            );
 645            ALTER TABLE workspaces ADD COLUMN ssh_project_id INTEGER REFERENCES ssh_projects(id) ON DELETE CASCADE;
 646        ),
 647        sql!(
 648            ALTER TABLE ssh_projects RENAME COLUMN path TO paths;
 649        ),
 650        sql!(
 651            CREATE TABLE toolchains (
 652                workspace_id INTEGER,
 653                worktree_id INTEGER,
 654                language_name TEXT NOT NULL,
 655                name TEXT NOT NULL,
 656                path TEXT NOT NULL,
 657                PRIMARY KEY (workspace_id, worktree_id, language_name)
 658            );
 659        ),
 660        sql!(
 661            ALTER TABLE toolchains ADD COLUMN raw_json TEXT DEFAULT "{}";
 662        ),
 663        sql!(
 664            CREATE TABLE breakpoints (
 665                workspace_id INTEGER NOT NULL,
 666                path TEXT NOT NULL,
 667                breakpoint_location INTEGER NOT NULL,
 668                kind INTEGER NOT NULL,
 669                log_message TEXT,
 670                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
 671                ON DELETE CASCADE
 672                ON UPDATE CASCADE
 673            );
 674        ),
 675        sql!(
 676            ALTER TABLE workspaces ADD COLUMN local_paths_array TEXT;
 677            CREATE UNIQUE INDEX local_paths_array_uq ON workspaces(local_paths_array);
 678            ALTER TABLE workspaces ADD COLUMN local_paths_order_array TEXT;
 679        ),
 680        sql!(
 681            ALTER TABLE breakpoints ADD COLUMN state INTEGER DEFAULT(0) NOT NULL
 682        ),
 683        sql!(
 684            ALTER TABLE breakpoints DROP COLUMN kind
 685        ),
 686        sql!(ALTER TABLE toolchains ADD COLUMN relative_worktree_path TEXT DEFAULT "" NOT NULL),
 687        sql!(
 688            ALTER TABLE breakpoints ADD COLUMN condition TEXT;
 689            ALTER TABLE breakpoints ADD COLUMN hit_condition TEXT;
 690        ),
 691        sql!(CREATE TABLE toolchains2 (
 692            workspace_id INTEGER,
 693            worktree_id INTEGER,
 694            language_name TEXT NOT NULL,
 695            name TEXT NOT NULL,
 696            path TEXT NOT NULL,
 697            raw_json TEXT NOT NULL,
 698            relative_worktree_path TEXT NOT NULL,
 699            PRIMARY KEY (workspace_id, worktree_id, language_name, relative_worktree_path)) STRICT;
 700            INSERT INTO toolchains2
 701                SELECT * FROM toolchains;
 702            DROP TABLE toolchains;
 703            ALTER TABLE toolchains2 RENAME TO toolchains;
 704        ),
 705        sql!(
 706            CREATE TABLE ssh_connections (
 707                id INTEGER PRIMARY KEY,
 708                host TEXT NOT NULL,
 709                port INTEGER,
 710                user TEXT
 711            );
 712
 713            INSERT INTO ssh_connections (host, port, user)
 714            SELECT DISTINCT host, port, user
 715            FROM ssh_projects;
 716
 717            CREATE TABLE workspaces_2(
 718                workspace_id INTEGER PRIMARY KEY,
 719                paths TEXT,
 720                paths_order TEXT,
 721                ssh_connection_id INTEGER REFERENCES ssh_connections(id),
 722                timestamp TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,
 723                window_state TEXT,
 724                window_x REAL,
 725                window_y REAL,
 726                window_width REAL,
 727                window_height REAL,
 728                display BLOB,
 729                left_dock_visible INTEGER,
 730                left_dock_active_panel TEXT,
 731                right_dock_visible INTEGER,
 732                right_dock_active_panel TEXT,
 733                bottom_dock_visible INTEGER,
 734                bottom_dock_active_panel TEXT,
 735                left_dock_zoom INTEGER,
 736                right_dock_zoom INTEGER,
 737                bottom_dock_zoom INTEGER,
 738                fullscreen INTEGER,
 739                centered_layout INTEGER,
 740                session_id TEXT,
 741                window_id INTEGER
 742            ) STRICT;
 743
 744            INSERT
 745            INTO workspaces_2
 746            SELECT
 747                workspaces.workspace_id,
 748                CASE
 749                    WHEN ssh_projects.id IS NOT NULL THEN ssh_projects.paths
 750                    ELSE
 751                        CASE
 752                            WHEN workspaces.local_paths_array IS NULL OR workspaces.local_paths_array = "" THEN
 753                                NULL
 754                            ELSE
 755                                replace(workspaces.local_paths_array, ',', CHAR(10))
 756                        END
 757                END as paths,
 758
 759                CASE
 760                    WHEN ssh_projects.id IS NOT NULL THEN ""
 761                    ELSE workspaces.local_paths_order_array
 762                END as paths_order,
 763
 764                CASE
 765                    WHEN ssh_projects.id IS NOT NULL THEN (
 766                        SELECT ssh_connections.id
 767                        FROM ssh_connections
 768                        WHERE
 769                            ssh_connections.host IS ssh_projects.host AND
 770                            ssh_connections.port IS ssh_projects.port AND
 771                            ssh_connections.user IS ssh_projects.user
 772                    )
 773                    ELSE NULL
 774                END as ssh_connection_id,
 775
 776                workspaces.timestamp,
 777                workspaces.window_state,
 778                workspaces.window_x,
 779                workspaces.window_y,
 780                workspaces.window_width,
 781                workspaces.window_height,
 782                workspaces.display,
 783                workspaces.left_dock_visible,
 784                workspaces.left_dock_active_panel,
 785                workspaces.right_dock_visible,
 786                workspaces.right_dock_active_panel,
 787                workspaces.bottom_dock_visible,
 788                workspaces.bottom_dock_active_panel,
 789                workspaces.left_dock_zoom,
 790                workspaces.right_dock_zoom,
 791                workspaces.bottom_dock_zoom,
 792                workspaces.fullscreen,
 793                workspaces.centered_layout,
 794                workspaces.session_id,
 795                workspaces.window_id
 796            FROM
 797                workspaces LEFT JOIN
 798                ssh_projects ON
 799                workspaces.ssh_project_id = ssh_projects.id;
 800
 801            DELETE FROM workspaces_2
 802            WHERE workspace_id NOT IN (
 803                SELECT MAX(workspace_id)
 804                FROM workspaces_2
 805                GROUP BY ssh_connection_id, paths
 806            );
 807
 808            DROP TABLE ssh_projects;
 809            DROP TABLE workspaces;
 810            ALTER TABLE workspaces_2 RENAME TO workspaces;
 811
 812            CREATE UNIQUE INDEX ix_workspaces_location ON workspaces(ssh_connection_id, paths);
 813        ),
 814        // Fix any data from when workspaces.paths were briefly encoded as JSON arrays
 815        sql!(
 816            UPDATE workspaces
 817            SET paths = CASE
 818                WHEN substr(paths, 1, 2) = '[' || '"' AND substr(paths, -2, 2) = '"' || ']' THEN
 819                    replace(
 820                        substr(paths, 3, length(paths) - 4),
 821                        '"' || ',' || '"',
 822                        CHAR(10)
 823                    )
 824                ELSE
 825                    replace(paths, ',', CHAR(10))
 826            END
 827            WHERE paths IS NOT NULL
 828        ),
 829        sql!(
 830            CREATE TABLE remote_connections(
 831                id INTEGER PRIMARY KEY,
 832                kind TEXT NOT NULL,
 833                host TEXT,
 834                port INTEGER,
 835                user TEXT,
 836                distro TEXT
 837            );
 838
 839            CREATE TABLE workspaces_2(
 840                workspace_id INTEGER PRIMARY KEY,
 841                paths TEXT,
 842                paths_order TEXT,
 843                remote_connection_id INTEGER REFERENCES remote_connections(id),
 844                timestamp TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,
 845                window_state TEXT,
 846                window_x REAL,
 847                window_y REAL,
 848                window_width REAL,
 849                window_height REAL,
 850                display BLOB,
 851                left_dock_visible INTEGER,
 852                left_dock_active_panel TEXT,
 853                right_dock_visible INTEGER,
 854                right_dock_active_panel TEXT,
 855                bottom_dock_visible INTEGER,
 856                bottom_dock_active_panel TEXT,
 857                left_dock_zoom INTEGER,
 858                right_dock_zoom INTEGER,
 859                bottom_dock_zoom INTEGER,
 860                fullscreen INTEGER,
 861                centered_layout INTEGER,
 862                session_id TEXT,
 863                window_id INTEGER
 864            ) STRICT;
 865
 866            INSERT INTO remote_connections
 867            SELECT
 868                id,
 869                "ssh" as kind,
 870                host,
 871                port,
 872                user,
 873                NULL as distro
 874            FROM ssh_connections;
 875
 876            INSERT
 877            INTO workspaces_2
 878            SELECT
 879                workspace_id,
 880                paths,
 881                paths_order,
 882                ssh_connection_id as remote_connection_id,
 883                timestamp,
 884                window_state,
 885                window_x,
 886                window_y,
 887                window_width,
 888                window_height,
 889                display,
 890                left_dock_visible,
 891                left_dock_active_panel,
 892                right_dock_visible,
 893                right_dock_active_panel,
 894                bottom_dock_visible,
 895                bottom_dock_active_panel,
 896                left_dock_zoom,
 897                right_dock_zoom,
 898                bottom_dock_zoom,
 899                fullscreen,
 900                centered_layout,
 901                session_id,
 902                window_id
 903            FROM
 904                workspaces;
 905
 906            DROP TABLE workspaces;
 907            ALTER TABLE workspaces_2 RENAME TO workspaces;
 908
 909            CREATE UNIQUE INDEX ix_workspaces_location ON workspaces(remote_connection_id, paths);
 910        ),
 911        sql!(CREATE TABLE user_toolchains (
 912            remote_connection_id INTEGER,
 913            workspace_id INTEGER NOT NULL,
 914            worktree_id INTEGER NOT NULL,
 915            relative_worktree_path TEXT NOT NULL,
 916            language_name TEXT NOT NULL,
 917            name TEXT NOT NULL,
 918            path TEXT NOT NULL,
 919            raw_json TEXT NOT NULL,
 920
 921            PRIMARY KEY (workspace_id, worktree_id, relative_worktree_path, language_name, name, path, raw_json)
 922        ) STRICT;),
 923        sql!(
 924            DROP TABLE ssh_connections;
 925        ),
 926        sql!(
 927            ALTER TABLE remote_connections ADD COLUMN name TEXT;
 928            ALTER TABLE remote_connections ADD COLUMN container_id TEXT;
 929        ),
 930        sql!(
 931            CREATE TABLE IF NOT EXISTS trusted_worktrees (
 932                trust_id INTEGER PRIMARY KEY AUTOINCREMENT,
 933                absolute_path TEXT,
 934                user_name TEXT,
 935                host_name TEXT
 936            ) STRICT;
 937        ),
 938        sql!(CREATE TABLE toolchains2 (
 939            workspace_id INTEGER,
 940            worktree_root_path TEXT NOT NULL,
 941            language_name TEXT NOT NULL,
 942            name TEXT NOT NULL,
 943            path TEXT NOT NULL,
 944            raw_json TEXT NOT NULL,
 945            relative_worktree_path TEXT NOT NULL,
 946            PRIMARY KEY (workspace_id, worktree_root_path, language_name, relative_worktree_path)) STRICT;
 947            INSERT OR REPLACE INTO toolchains2
 948                // The `instr(paths, '\n') = 0` part allows us to find all
 949                // workspaces that have a single worktree, as `\n` is used as a
 950                // separator when serializing the workspace paths, so if no `\n` is
 951                // found, we know we have a single worktree.
 952                SELECT toolchains.workspace_id, paths, language_name, name, path, raw_json, relative_worktree_path FROM toolchains INNER JOIN workspaces ON toolchains.workspace_id = workspaces.workspace_id AND instr(paths, '\n') = 0;
 953            DROP TABLE toolchains;
 954            ALTER TABLE toolchains2 RENAME TO toolchains;
 955        ),
 956        sql!(CREATE TABLE user_toolchains2 (
 957            remote_connection_id INTEGER,
 958            workspace_id INTEGER NOT NULL,
 959            worktree_root_path TEXT NOT NULL,
 960            relative_worktree_path TEXT NOT NULL,
 961            language_name TEXT NOT NULL,
 962            name TEXT NOT NULL,
 963            path TEXT NOT NULL,
 964            raw_json TEXT NOT NULL,
 965
 966            PRIMARY KEY (workspace_id, worktree_root_path, relative_worktree_path, language_name, name, path, raw_json)) STRICT;
 967            INSERT OR REPLACE INTO user_toolchains2
 968                // The `instr(paths, '\n') = 0` part allows us to find all
 969                // workspaces that have a single worktree, as `\n` is used as a
 970                // separator when serializing the workspace paths, so if no `\n` is
 971                // found, we know we have a single worktree.
 972                SELECT user_toolchains.remote_connection_id, user_toolchains.workspace_id, paths, relative_worktree_path, language_name, name, path, raw_json  FROM user_toolchains INNER JOIN workspaces ON user_toolchains.workspace_id = workspaces.workspace_id AND instr(paths, '\n') = 0;
 973            DROP TABLE user_toolchains;
 974            ALTER TABLE user_toolchains2 RENAME TO user_toolchains;
 975        ),
 976        sql!(
 977            ALTER TABLE remote_connections ADD COLUMN use_podman BOOLEAN;
 978        ),
 979        sql!(
 980            ALTER TABLE remote_connections ADD COLUMN remote_env TEXT;
 981        ),
 982    ];
 983
 984    // Allow recovering from bad migration that was initially shipped to nightly
 985    // when introducing the ssh_connections table.
 986    fn should_allow_migration_change(_index: usize, old: &str, new: &str) -> bool {
 987        old.starts_with("CREATE TABLE ssh_connections")
 988            && new.starts_with("CREATE TABLE ssh_connections")
 989    }
 990}
 991
 992db::static_connection!(WorkspaceDb, []);
 993
 994impl WorkspaceDb {
 995    /// Returns a serialized workspace for the given worktree_roots. If the passed array
 996    /// is empty, the most recent workspace is returned instead. If no workspace for the
 997    /// passed roots is stored, returns none.
 998    pub(crate) fn workspace_for_roots<P: AsRef<Path>>(
 999        &self,
1000        worktree_roots: &[P],
1001    ) -> Option<SerializedWorkspace> {
1002        self.workspace_for_roots_internal(worktree_roots, None)
1003    }
1004
1005    pub(crate) fn remote_workspace_for_roots<P: AsRef<Path>>(
1006        &self,
1007        worktree_roots: &[P],
1008        remote_project_id: RemoteConnectionId,
1009    ) -> Option<SerializedWorkspace> {
1010        self.workspace_for_roots_internal(worktree_roots, Some(remote_project_id))
1011    }
1012
1013    pub(crate) fn workspace_for_roots_internal<P: AsRef<Path>>(
1014        &self,
1015        worktree_roots: &[P],
1016        remote_connection_id: Option<RemoteConnectionId>,
1017    ) -> Option<SerializedWorkspace> {
1018        // paths are sorted before db interactions to ensure that the order of the paths
1019        // doesn't affect the workspace selection for existing workspaces
1020        let root_paths = PathList::new(worktree_roots);
1021
1022        // Empty workspaces cannot be matched by paths (all empty workspaces have paths = "").
1023        // They should only be restored via workspace_for_id during session restoration.
1024        if root_paths.is_empty() && remote_connection_id.is_none() {
1025            return None;
1026        }
1027
1028        // Note that we re-assign the workspace_id here in case it's empty
1029        // and we've grabbed the most recent workspace
1030        let (
1031            workspace_id,
1032            paths,
1033            paths_order,
1034            window_bounds,
1035            display,
1036            centered_layout,
1037            docks,
1038            window_id,
1039        ): (
1040            WorkspaceId,
1041            String,
1042            String,
1043            Option<SerializedWindowBounds>,
1044            Option<Uuid>,
1045            Option<bool>,
1046            DockStructure,
1047            Option<u64>,
1048        ) = self
1049            .select_row_bound(sql! {
1050                SELECT
1051                    workspace_id,
1052                    paths,
1053                    paths_order,
1054                    window_state,
1055                    window_x,
1056                    window_y,
1057                    window_width,
1058                    window_height,
1059                    display,
1060                    centered_layout,
1061                    left_dock_visible,
1062                    left_dock_active_panel,
1063                    left_dock_zoom,
1064                    right_dock_visible,
1065                    right_dock_active_panel,
1066                    right_dock_zoom,
1067                    bottom_dock_visible,
1068                    bottom_dock_active_panel,
1069                    bottom_dock_zoom,
1070                    window_id
1071                FROM workspaces
1072                WHERE
1073                    paths IS ? AND
1074                    remote_connection_id IS ?
1075                LIMIT 1
1076            })
1077            .and_then(|mut prepared_statement| {
1078                (prepared_statement)((
1079                    root_paths.serialize().paths,
1080                    remote_connection_id.map(|id| id.0 as i32),
1081                ))
1082            })
1083            .context("No workspaces found")
1084            .warn_on_err()
1085            .flatten()?;
1086
1087        let paths = PathList::deserialize(&SerializedPathList {
1088            paths,
1089            order: paths_order,
1090        });
1091
1092        let remote_connection_options = if let Some(remote_connection_id) = remote_connection_id {
1093            self.remote_connection(remote_connection_id)
1094                .context("Get remote connection")
1095                .log_err()
1096        } else {
1097            None
1098        };
1099
1100        Some(SerializedWorkspace {
1101            id: workspace_id,
1102            location: match remote_connection_options {
1103                Some(options) => SerializedWorkspaceLocation::Remote(options),
1104                None => SerializedWorkspaceLocation::Local,
1105            },
1106            paths,
1107            center_group: self
1108                .get_center_pane_group(workspace_id)
1109                .context("Getting center group")
1110                .log_err()?,
1111            window_bounds,
1112            centered_layout: centered_layout.unwrap_or(false),
1113            display,
1114            docks,
1115            session_id: None,
1116            breakpoints: self.breakpoints(workspace_id),
1117            window_id,
1118            user_toolchains: self.user_toolchains(workspace_id, remote_connection_id),
1119        })
1120    }
1121
1122    /// Returns the workspace with the given ID, loading all associated data.
1123    pub(crate) fn workspace_for_id(
1124        &self,
1125        workspace_id: WorkspaceId,
1126    ) -> Option<SerializedWorkspace> {
1127        let (
1128            paths,
1129            paths_order,
1130            window_bounds,
1131            display,
1132            centered_layout,
1133            docks,
1134            window_id,
1135            remote_connection_id,
1136        ): (
1137            String,
1138            String,
1139            Option<SerializedWindowBounds>,
1140            Option<Uuid>,
1141            Option<bool>,
1142            DockStructure,
1143            Option<u64>,
1144            Option<i32>,
1145        ) = self
1146            .select_row_bound(sql! {
1147                SELECT
1148                    paths,
1149                    paths_order,
1150                    window_state,
1151                    window_x,
1152                    window_y,
1153                    window_width,
1154                    window_height,
1155                    display,
1156                    centered_layout,
1157                    left_dock_visible,
1158                    left_dock_active_panel,
1159                    left_dock_zoom,
1160                    right_dock_visible,
1161                    right_dock_active_panel,
1162                    right_dock_zoom,
1163                    bottom_dock_visible,
1164                    bottom_dock_active_panel,
1165                    bottom_dock_zoom,
1166                    window_id,
1167                    remote_connection_id
1168                FROM workspaces
1169                WHERE workspace_id = ?
1170            })
1171            .and_then(|mut prepared_statement| (prepared_statement)(workspace_id))
1172            .context("No workspace found for id")
1173            .warn_on_err()
1174            .flatten()?;
1175
1176        let paths = PathList::deserialize(&SerializedPathList {
1177            paths,
1178            order: paths_order,
1179        });
1180
1181        let remote_connection_id = remote_connection_id.map(|id| RemoteConnectionId(id as u64));
1182        let remote_connection_options = if let Some(remote_connection_id) = remote_connection_id {
1183            self.remote_connection(remote_connection_id)
1184                .context("Get remote connection")
1185                .log_err()
1186        } else {
1187            None
1188        };
1189
1190        Some(SerializedWorkspace {
1191            id: workspace_id,
1192            location: match remote_connection_options {
1193                Some(options) => SerializedWorkspaceLocation::Remote(options),
1194                None => SerializedWorkspaceLocation::Local,
1195            },
1196            paths,
1197            center_group: self
1198                .get_center_pane_group(workspace_id)
1199                .context("Getting center group")
1200                .log_err()?,
1201            window_bounds,
1202            centered_layout: centered_layout.unwrap_or(false),
1203            display,
1204            docks,
1205            session_id: None,
1206            breakpoints: self.breakpoints(workspace_id),
1207            window_id,
1208            user_toolchains: self.user_toolchains(workspace_id, remote_connection_id),
1209        })
1210    }
1211
1212    fn breakpoints(&self, workspace_id: WorkspaceId) -> BTreeMap<Arc<Path>, Vec<SourceBreakpoint>> {
1213        let breakpoints: Result<Vec<(PathBuf, Breakpoint)>> = self
1214            .select_bound(sql! {
1215                SELECT path, breakpoint_location, log_message, condition, hit_condition, state
1216                FROM breakpoints
1217                WHERE workspace_id = ?
1218            })
1219            .and_then(|mut prepared_statement| (prepared_statement)(workspace_id));
1220
1221        match breakpoints {
1222            Ok(bp) => {
1223                if bp.is_empty() {
1224                    log::debug!("Breakpoints are empty after querying database for them");
1225                }
1226
1227                let mut map: BTreeMap<Arc<Path>, Vec<SourceBreakpoint>> = Default::default();
1228
1229                for (path, breakpoint) in bp {
1230                    let path: Arc<Path> = path.into();
1231                    map.entry(path.clone()).or_default().push(SourceBreakpoint {
1232                        row: breakpoint.position,
1233                        path,
1234                        message: breakpoint.message,
1235                        condition: breakpoint.condition,
1236                        hit_condition: breakpoint.hit_condition,
1237                        state: breakpoint.state,
1238                    });
1239                }
1240
1241                for (path, bps) in map.iter() {
1242                    log::info!(
1243                        "Got {} breakpoints from database at path: {}",
1244                        bps.len(),
1245                        path.to_string_lossy()
1246                    );
1247                }
1248
1249                map
1250            }
1251            Err(msg) => {
1252                log::error!("Breakpoints query failed with msg: {msg}");
1253                Default::default()
1254            }
1255        }
1256    }
1257
1258    fn user_toolchains(
1259        &self,
1260        workspace_id: WorkspaceId,
1261        remote_connection_id: Option<RemoteConnectionId>,
1262    ) -> BTreeMap<ToolchainScope, IndexSet<Toolchain>> {
1263        type RowKind = (WorkspaceId, String, String, String, String, String, String);
1264
1265        let toolchains: Vec<RowKind> = self
1266            .select_bound(sql! {
1267                SELECT workspace_id, worktree_root_path, relative_worktree_path,
1268                language_name, name, path, raw_json
1269                FROM user_toolchains WHERE remote_connection_id IS ?1 AND (
1270                      workspace_id IN (0, ?2)
1271                )
1272            })
1273            .and_then(|mut statement| {
1274                (statement)((remote_connection_id.map(|id| id.0), workspace_id))
1275            })
1276            .unwrap_or_default();
1277        let mut ret = BTreeMap::<_, IndexSet<_>>::default();
1278
1279        for (
1280            _workspace_id,
1281            worktree_root_path,
1282            relative_worktree_path,
1283            language_name,
1284            name,
1285            path,
1286            raw_json,
1287        ) in toolchains
1288        {
1289            // INTEGER's that are primary keys (like workspace ids, remote connection ids and such) start at 1, so we're safe to
1290            let scope = if _workspace_id == WorkspaceId(0) {
1291                debug_assert_eq!(worktree_root_path, String::default());
1292                debug_assert_eq!(relative_worktree_path, String::default());
1293                ToolchainScope::Global
1294            } else {
1295                debug_assert_eq!(workspace_id, _workspace_id);
1296                debug_assert_eq!(
1297                    worktree_root_path == String::default(),
1298                    relative_worktree_path == String::default()
1299                );
1300
1301                let Some(relative_path) = RelPath::unix(&relative_worktree_path).log_err() else {
1302                    continue;
1303                };
1304                if worktree_root_path != String::default()
1305                    && relative_worktree_path != String::default()
1306                {
1307                    ToolchainScope::Subproject(
1308                        Arc::from(worktree_root_path.as_ref()),
1309                        relative_path.into(),
1310                    )
1311                } else {
1312                    ToolchainScope::Project
1313                }
1314            };
1315            let Ok(as_json) = serde_json::from_str(&raw_json) else {
1316                continue;
1317            };
1318            let toolchain = Toolchain {
1319                name: SharedString::from(name),
1320                path: SharedString::from(path),
1321                language_name: LanguageName::from_proto(language_name),
1322                as_json,
1323            };
1324            ret.entry(scope).or_default().insert(toolchain);
1325        }
1326
1327        ret
1328    }
1329
1330    /// Saves a workspace using the worktree roots. Will garbage collect any workspaces
1331    /// that used this workspace previously
1332    pub(crate) async fn save_workspace(&self, workspace: SerializedWorkspace) {
1333        let paths = workspace.paths.serialize();
1334        log::debug!("Saving workspace at location: {:?}", workspace.location);
1335        self.write(move |conn| {
1336            conn.with_savepoint("update_worktrees", || {
1337                let remote_connection_id = match workspace.location.clone() {
1338                    SerializedWorkspaceLocation::Local => None,
1339                    SerializedWorkspaceLocation::Remote(connection_options) => {
1340                        Some(Self::get_or_create_remote_connection_internal(
1341                            conn,
1342                            connection_options
1343                        )?.0)
1344                    }
1345                };
1346
1347                // Clear out panes and pane_groups
1348                conn.exec_bound(sql!(
1349                    DELETE FROM pane_groups WHERE workspace_id = ?1;
1350                    DELETE FROM panes WHERE workspace_id = ?1;))?(workspace.id)
1351                    .context("Clearing old panes")?;
1352
1353                conn.exec_bound(
1354                    sql!(
1355                        DELETE FROM breakpoints WHERE workspace_id = ?1;
1356                    )
1357                )?(workspace.id).context("Clearing old breakpoints")?;
1358
1359                for (path, breakpoints) in workspace.breakpoints {
1360                    for bp in breakpoints {
1361                        let state = BreakpointStateWrapper::from(bp.state);
1362                        match conn.exec_bound(sql!(
1363                            INSERT INTO breakpoints (workspace_id, path, breakpoint_location,  log_message, condition, hit_condition, state)
1364                            VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7);))?
1365
1366                        ((
1367                            workspace.id,
1368                            path.as_ref(),
1369                            bp.row,
1370                            bp.message,
1371                            bp.condition,
1372                            bp.hit_condition,
1373                            state,
1374                        )) {
1375                            Ok(_) => {
1376                                log::debug!("Stored breakpoint at row: {} in path: {}", bp.row, path.to_string_lossy())
1377                            }
1378                            Err(err) => {
1379                                log::error!("{err}");
1380                                continue;
1381                            }
1382                        }
1383                    }
1384                }
1385
1386                conn.exec_bound(
1387                    sql!(
1388                        DELETE FROM user_toolchains WHERE workspace_id = ?1;
1389                    )
1390                )?(workspace.id).context("Clearing old user toolchains")?;
1391
1392                for (scope, toolchains) in workspace.user_toolchains {
1393                    for toolchain in toolchains {
1394                        let query = sql!(INSERT OR REPLACE INTO user_toolchains(remote_connection_id, workspace_id, worktree_root_path, relative_worktree_path, language_name, name, path, raw_json) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8));
1395                        let (workspace_id, worktree_root_path, relative_worktree_path) = match scope {
1396                            ToolchainScope::Subproject(ref worktree_root_path, ref path) => (Some(workspace.id), Some(worktree_root_path.to_string_lossy().into_owned()), Some(path.as_unix_str().to_owned())),
1397                            ToolchainScope::Project => (Some(workspace.id), None, None),
1398                            ToolchainScope::Global => (None, None, None),
1399                        };
1400                        let args = (remote_connection_id, workspace_id.unwrap_or(WorkspaceId(0)), worktree_root_path.unwrap_or_default(), relative_worktree_path.unwrap_or_default(),
1401                        toolchain.language_name.as_ref().to_owned(), toolchain.name.to_string(), toolchain.path.to_string(), toolchain.as_json.to_string());
1402                        if let Err(err) = conn.exec_bound(query)?(args) {
1403                            log::error!("{err}");
1404                            continue;
1405                        }
1406                    }
1407                }
1408
1409                // Clear out old workspaces with the same paths.
1410                // Skip this for empty workspaces - they are identified by workspace_id, not paths.
1411                // Multiple empty workspaces with different content should coexist.
1412                if !paths.paths.is_empty() {
1413                    conn.exec_bound(sql!(
1414                        DELETE
1415                        FROM workspaces
1416                        WHERE
1417                            workspace_id != ?1 AND
1418                            paths IS ?2 AND
1419                            remote_connection_id IS ?3
1420                    ))?((
1421                        workspace.id,
1422                        paths.paths.clone(),
1423                        remote_connection_id,
1424                    ))
1425                    .context("clearing out old locations")?;
1426                }
1427
1428                // Upsert
1429                let query = sql!(
1430                    INSERT INTO workspaces(
1431                        workspace_id,
1432                        paths,
1433                        paths_order,
1434                        remote_connection_id,
1435                        left_dock_visible,
1436                        left_dock_active_panel,
1437                        left_dock_zoom,
1438                        right_dock_visible,
1439                        right_dock_active_panel,
1440                        right_dock_zoom,
1441                        bottom_dock_visible,
1442                        bottom_dock_active_panel,
1443                        bottom_dock_zoom,
1444                        session_id,
1445                        window_id,
1446                        timestamp
1447                    )
1448                    VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, CURRENT_TIMESTAMP)
1449                    ON CONFLICT DO
1450                    UPDATE SET
1451                        paths = ?2,
1452                        paths_order = ?3,
1453                        remote_connection_id = ?4,
1454                        left_dock_visible = ?5,
1455                        left_dock_active_panel = ?6,
1456                        left_dock_zoom = ?7,
1457                        right_dock_visible = ?8,
1458                        right_dock_active_panel = ?9,
1459                        right_dock_zoom = ?10,
1460                        bottom_dock_visible = ?11,
1461                        bottom_dock_active_panel = ?12,
1462                        bottom_dock_zoom = ?13,
1463                        session_id = ?14,
1464                        window_id = ?15,
1465                        timestamp = CURRENT_TIMESTAMP
1466                );
1467                let mut prepared_query = conn.exec_bound(query)?;
1468                let args = (
1469                    workspace.id,
1470                    paths.paths.clone(),
1471                    paths.order.clone(),
1472                    remote_connection_id,
1473                    workspace.docks,
1474                    workspace.session_id,
1475                    workspace.window_id,
1476                );
1477
1478                prepared_query(args).context("Updating workspace")?;
1479
1480                // Save center pane group
1481                Self::save_pane_group(conn, workspace.id, &workspace.center_group, None)
1482                    .context("save pane group in save workspace")?;
1483
1484                Ok(())
1485            })
1486            .log_err();
1487        })
1488        .await;
1489    }
1490
1491    pub(crate) async fn get_or_create_remote_connection(
1492        &self,
1493        options: RemoteConnectionOptions,
1494    ) -> Result<RemoteConnectionId> {
1495        self.write(move |conn| Self::get_or_create_remote_connection_internal(conn, options))
1496            .await
1497    }
1498
1499    fn get_or_create_remote_connection_internal(
1500        this: &Connection,
1501        options: RemoteConnectionOptions,
1502    ) -> Result<RemoteConnectionId> {
1503        let kind;
1504        let user: Option<String>;
1505        let mut host = None;
1506        let mut port = None;
1507        let mut distro = None;
1508        let mut name = None;
1509        let mut container_id = None;
1510        let mut use_podman = None;
1511        let mut remote_env = None;
1512        match options {
1513            RemoteConnectionOptions::Ssh(options) => {
1514                kind = RemoteConnectionKind::Ssh;
1515                host = Some(options.host.to_string());
1516                port = options.port;
1517                user = options.username;
1518            }
1519            RemoteConnectionOptions::Wsl(options) => {
1520                kind = RemoteConnectionKind::Wsl;
1521                distro = Some(options.distro_name);
1522                user = options.user;
1523            }
1524            RemoteConnectionOptions::Docker(options) => {
1525                kind = RemoteConnectionKind::Docker;
1526                container_id = Some(options.container_id);
1527                name = Some(options.name);
1528                use_podman = Some(options.use_podman);
1529                user = Some(options.remote_user);
1530                remote_env = serde_json::to_string(&options.remote_env).ok();
1531            }
1532            #[cfg(any(test, feature = "test-support"))]
1533            RemoteConnectionOptions::Mock(options) => {
1534                kind = RemoteConnectionKind::Ssh;
1535                host = Some(format!("mock-{}", options.id));
1536                user = Some(format!("mock-user-{}", options.id));
1537            }
1538        }
1539        Self::get_or_create_remote_connection_query(
1540            this,
1541            kind,
1542            host,
1543            port,
1544            user,
1545            distro,
1546            name,
1547            container_id,
1548            use_podman,
1549            remote_env,
1550        )
1551    }
1552
1553    fn get_or_create_remote_connection_query(
1554        this: &Connection,
1555        kind: RemoteConnectionKind,
1556        host: Option<String>,
1557        port: Option<u16>,
1558        user: Option<String>,
1559        distro: Option<String>,
1560        name: Option<String>,
1561        container_id: Option<String>,
1562        use_podman: Option<bool>,
1563        remote_env: Option<String>,
1564    ) -> Result<RemoteConnectionId> {
1565        if let Some(id) = this.select_row_bound(sql!(
1566            SELECT id
1567            FROM remote_connections
1568            WHERE
1569                kind IS ? AND
1570                host IS ? AND
1571                port IS ? AND
1572                user IS ? AND
1573                distro IS ? AND
1574                name IS ? AND
1575                container_id IS ?
1576            LIMIT 1
1577        ))?((
1578            kind.serialize(),
1579            host.clone(),
1580            port,
1581            user.clone(),
1582            distro.clone(),
1583            name.clone(),
1584            container_id.clone(),
1585        ))? {
1586            Ok(RemoteConnectionId(id))
1587        } else {
1588            let id = this.select_row_bound(sql!(
1589                INSERT INTO remote_connections (
1590                    kind,
1591                    host,
1592                    port,
1593                    user,
1594                    distro,
1595                    name,
1596                    container_id,
1597                    use_podman,
1598                    remote_env
1599                    ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
1600                RETURNING id
1601            ))?((
1602                kind.serialize(),
1603                host,
1604                port,
1605                user,
1606                distro,
1607                name,
1608                container_id,
1609                use_podman,
1610                remote_env,
1611            ))?
1612            .context("failed to insert remote project")?;
1613            Ok(RemoteConnectionId(id))
1614        }
1615    }
1616
1617    query! {
1618        pub async fn next_id() -> Result<WorkspaceId> {
1619            INSERT INTO workspaces DEFAULT VALUES RETURNING workspace_id
1620        }
1621    }
1622
1623    fn recent_workspaces(
1624        &self,
1625    ) -> Result<
1626        Vec<(
1627            WorkspaceId,
1628            PathList,
1629            Option<RemoteConnectionId>,
1630            DateTime<Utc>,
1631        )>,
1632    > {
1633        Ok(self
1634            .recent_workspaces_query()?
1635            .into_iter()
1636            .map(|(id, paths, order, remote_connection_id, timestamp)| {
1637                (
1638                    id,
1639                    PathList::deserialize(&SerializedPathList { paths, order }),
1640                    remote_connection_id.map(RemoteConnectionId),
1641                    parse_timestamp(&timestamp),
1642                )
1643            })
1644            .collect())
1645    }
1646
1647    query! {
1648        fn recent_workspaces_query() -> Result<Vec<(WorkspaceId, String, String, Option<u64>, String)>> {
1649            SELECT workspace_id, paths, paths_order, remote_connection_id, timestamp
1650            FROM workspaces
1651            WHERE
1652                paths IS NOT NULL OR
1653                remote_connection_id IS NOT NULL
1654            ORDER BY timestamp DESC
1655        }
1656    }
1657
1658    fn session_workspaces(
1659        &self,
1660        session_id: String,
1661    ) -> Result<
1662        Vec<(
1663            WorkspaceId,
1664            PathList,
1665            Option<u64>,
1666            Option<RemoteConnectionId>,
1667        )>,
1668    > {
1669        Ok(self
1670            .session_workspaces_query(session_id)?
1671            .into_iter()
1672            .map(
1673                |(workspace_id, paths, order, window_id, remote_connection_id)| {
1674                    (
1675                        WorkspaceId(workspace_id),
1676                        PathList::deserialize(&SerializedPathList { paths, order }),
1677                        window_id,
1678                        remote_connection_id.map(RemoteConnectionId),
1679                    )
1680                },
1681            )
1682            .collect())
1683    }
1684
1685    query! {
1686        fn session_workspaces_query(session_id: String) -> Result<Vec<(i64, String, String, Option<u64>, Option<u64>)>> {
1687            SELECT workspace_id, paths, paths_order, window_id, remote_connection_id
1688            FROM workspaces
1689            WHERE session_id = ?1
1690            ORDER BY timestamp DESC
1691        }
1692    }
1693
1694    query! {
1695        pub fn breakpoints_for_file(workspace_id: WorkspaceId, file_path: &Path) -> Result<Vec<Breakpoint>> {
1696            SELECT breakpoint_location
1697            FROM breakpoints
1698            WHERE  workspace_id= ?1 AND path = ?2
1699        }
1700    }
1701
1702    query! {
1703        pub fn clear_breakpoints(file_path: &Path) -> Result<()> {
1704            DELETE FROM breakpoints
1705            WHERE file_path = ?2
1706        }
1707    }
1708
1709    fn remote_connections(&self) -> Result<HashMap<RemoteConnectionId, RemoteConnectionOptions>> {
1710        Ok(self.select(sql!(
1711            SELECT
1712                id, kind, host, port, user, distro, container_id, name, use_podman, remote_env
1713            FROM
1714                remote_connections
1715        ))?()?
1716        .into_iter()
1717        .filter_map(
1718            |(id, kind, host, port, user, distro, container_id, name, use_podman, remote_env)| {
1719                Some((
1720                    RemoteConnectionId(id),
1721                    Self::remote_connection_from_row(
1722                        kind,
1723                        host,
1724                        port,
1725                        user,
1726                        distro,
1727                        container_id,
1728                        name,
1729                        use_podman,
1730                        remote_env,
1731                    )?,
1732                ))
1733            },
1734        )
1735        .collect())
1736    }
1737
1738    pub(crate) fn remote_connection(
1739        &self,
1740        id: RemoteConnectionId,
1741    ) -> Result<RemoteConnectionOptions> {
1742        let (kind, host, port, user, distro, container_id, name, use_podman, remote_env) =
1743            self.select_row_bound(sql!(
1744                SELECT kind, host, port, user, distro, container_id, name, use_podman, remote_env
1745                FROM remote_connections
1746                WHERE id = ?
1747            ))?(id.0)?
1748            .context("no such remote connection")?;
1749        Self::remote_connection_from_row(
1750            kind,
1751            host,
1752            port,
1753            user,
1754            distro,
1755            container_id,
1756            name,
1757            use_podman,
1758            remote_env,
1759        )
1760        .context("invalid remote_connection row")
1761    }
1762
1763    fn remote_connection_from_row(
1764        kind: String,
1765        host: Option<String>,
1766        port: Option<u16>,
1767        user: Option<String>,
1768        distro: Option<String>,
1769        container_id: Option<String>,
1770        name: Option<String>,
1771        use_podman: Option<bool>,
1772        remote_env: Option<String>,
1773    ) -> Option<RemoteConnectionOptions> {
1774        match RemoteConnectionKind::deserialize(&kind)? {
1775            RemoteConnectionKind::Wsl => Some(RemoteConnectionOptions::Wsl(WslConnectionOptions {
1776                distro_name: distro?,
1777                user: user,
1778            })),
1779            RemoteConnectionKind::Ssh => Some(RemoteConnectionOptions::Ssh(SshConnectionOptions {
1780                host: host?.into(),
1781                port,
1782                username: user,
1783                ..Default::default()
1784            })),
1785            RemoteConnectionKind::Docker => {
1786                let remote_env: BTreeMap<String, String> =
1787                    serde_json::from_str(&remote_env?).ok()?;
1788                Some(RemoteConnectionOptions::Docker(DockerConnectionOptions {
1789                    container_id: container_id?,
1790                    name: name?,
1791                    remote_user: user?,
1792                    upload_binary_over_docker_exec: false,
1793                    use_podman: use_podman?,
1794                    remote_env,
1795                }))
1796            }
1797        }
1798    }
1799
1800    query! {
1801        pub async fn delete_workspace_by_id(id: WorkspaceId) -> Result<()> {
1802            DELETE FROM workspaces
1803            WHERE workspace_id IS ?
1804        }
1805    }
1806
1807    async fn all_paths_exist_with_a_directory(
1808        paths: &[PathBuf],
1809        fs: &dyn Fs,
1810        timestamp: Option<DateTime<Utc>>,
1811    ) -> bool {
1812        let mut any_dir = false;
1813        for path in paths {
1814            match fs.metadata(path).await.ok().flatten() {
1815                None => {
1816                    return timestamp.is_some_and(|t| Utc::now() - t < chrono::Duration::days(7));
1817                }
1818                Some(meta) => {
1819                    if meta.is_dir {
1820                        any_dir = true;
1821                    }
1822                }
1823            }
1824        }
1825        any_dir
1826    }
1827
1828    // Returns the recent locations which are still valid on disk and deletes ones which no longer
1829    // exist.
1830    pub async fn recent_workspaces_on_disk(
1831        &self,
1832        fs: &dyn Fs,
1833    ) -> Result<
1834        Vec<(
1835            WorkspaceId,
1836            SerializedWorkspaceLocation,
1837            PathList,
1838            DateTime<Utc>,
1839        )>,
1840    > {
1841        let mut result = Vec::new();
1842        let mut delete_tasks = Vec::new();
1843        let remote_connections = self.remote_connections()?;
1844
1845        for (id, paths, remote_connection_id, timestamp) in self.recent_workspaces()? {
1846            if let Some(remote_connection_id) = remote_connection_id {
1847                if let Some(connection_options) = remote_connections.get(&remote_connection_id) {
1848                    result.push((
1849                        id,
1850                        SerializedWorkspaceLocation::Remote(connection_options.clone()),
1851                        paths,
1852                        timestamp,
1853                    ));
1854                } else {
1855                    delete_tasks.push(self.delete_workspace_by_id(id));
1856                }
1857                continue;
1858            }
1859
1860            let has_wsl_path = if cfg!(windows) {
1861                paths
1862                    .paths()
1863                    .iter()
1864                    .any(|path| util::paths::WslPath::from_path(path).is_some())
1865            } else {
1866                false
1867            };
1868
1869            // Delete the workspace if any of the paths are WSL paths.
1870            // If a local workspace points to WSL, this check will cause us to wait for the
1871            // WSL VM and file server to boot up. This can block for many seconds.
1872            // Supported scenarios use remote workspaces.
1873            if !has_wsl_path
1874                && Self::all_paths_exist_with_a_directory(paths.paths(), fs, Some(timestamp)).await
1875            {
1876                result.push((id, SerializedWorkspaceLocation::Local, paths, timestamp));
1877            } else {
1878                delete_tasks.push(self.delete_workspace_by_id(id));
1879            }
1880        }
1881
1882        futures::future::join_all(delete_tasks).await;
1883        Ok(result)
1884    }
1885
1886    pub async fn last_workspace(
1887        &self,
1888        fs: &dyn Fs,
1889    ) -> Result<
1890        Option<(
1891            WorkspaceId,
1892            SerializedWorkspaceLocation,
1893            PathList,
1894            DateTime<Utc>,
1895        )>,
1896    > {
1897        Ok(self.recent_workspaces_on_disk(fs).await?.into_iter().next())
1898    }
1899
1900    // Returns the locations of the workspaces that were still opened when the last
1901    // session was closed (i.e. when Zed was quit).
1902    // If `last_session_window_order` is provided, the returned locations are ordered
1903    // according to that.
1904    pub async fn last_session_workspace_locations(
1905        &self,
1906        last_session_id: &str,
1907        last_session_window_stack: Option<Vec<WindowId>>,
1908        fs: &dyn Fs,
1909    ) -> Result<Vec<SessionWorkspace>> {
1910        let mut workspaces = Vec::new();
1911
1912        for (workspace_id, paths, window_id, remote_connection_id) in
1913            self.session_workspaces(last_session_id.to_owned())?
1914        {
1915            let window_id = window_id.map(WindowId::from);
1916
1917            if let Some(remote_connection_id) = remote_connection_id {
1918                workspaces.push(SessionWorkspace {
1919                    workspace_id,
1920                    location: SerializedWorkspaceLocation::Remote(
1921                        self.remote_connection(remote_connection_id)?,
1922                    ),
1923                    paths,
1924                    window_id,
1925                });
1926            } else if paths.is_empty() {
1927                // Empty workspace with items (drafts, files) - include for restoration
1928                workspaces.push(SessionWorkspace {
1929                    workspace_id,
1930                    location: SerializedWorkspaceLocation::Local,
1931                    paths,
1932                    window_id,
1933                });
1934            } else {
1935                if Self::all_paths_exist_with_a_directory(paths.paths(), fs, None).await {
1936                    workspaces.push(SessionWorkspace {
1937                        workspace_id,
1938                        location: SerializedWorkspaceLocation::Local,
1939                        paths,
1940                        window_id,
1941                    });
1942                }
1943            }
1944        }
1945
1946        if let Some(stack) = last_session_window_stack {
1947            workspaces.sort_by_key(|workspace| {
1948                workspace
1949                    .window_id
1950                    .and_then(|id| stack.iter().position(|&order_id| order_id == id))
1951                    .unwrap_or(usize::MAX)
1952            });
1953        }
1954
1955        Ok(workspaces)
1956    }
1957
1958    fn get_center_pane_group(&self, workspace_id: WorkspaceId) -> Result<SerializedPaneGroup> {
1959        Ok(self
1960            .get_pane_group(workspace_id, None)?
1961            .into_iter()
1962            .next()
1963            .unwrap_or_else(|| {
1964                SerializedPaneGroup::Pane(SerializedPane {
1965                    active: true,
1966                    children: vec![],
1967                    pinned_count: 0,
1968                })
1969            }))
1970    }
1971
1972    fn get_pane_group(
1973        &self,
1974        workspace_id: WorkspaceId,
1975        group_id: Option<GroupId>,
1976    ) -> Result<Vec<SerializedPaneGroup>> {
1977        type GroupKey = (Option<GroupId>, WorkspaceId);
1978        type GroupOrPane = (
1979            Option<GroupId>,
1980            Option<SerializedAxis>,
1981            Option<PaneId>,
1982            Option<bool>,
1983            Option<usize>,
1984            Option<String>,
1985        );
1986        self.select_bound::<GroupKey, GroupOrPane>(sql!(
1987            SELECT group_id, axis, pane_id, active, pinned_count, flexes
1988                FROM (SELECT
1989                        group_id,
1990                        axis,
1991                        NULL as pane_id,
1992                        NULL as active,
1993                        NULL as pinned_count,
1994                        position,
1995                        parent_group_id,
1996                        workspace_id,
1997                        flexes
1998                      FROM pane_groups
1999                    UNION
2000                      SELECT
2001                        NULL,
2002                        NULL,
2003                        center_panes.pane_id,
2004                        panes.active as active,
2005                        pinned_count,
2006                        position,
2007                        parent_group_id,
2008                        panes.workspace_id as workspace_id,
2009                        NULL
2010                      FROM center_panes
2011                      JOIN panes ON center_panes.pane_id = panes.pane_id)
2012                WHERE parent_group_id IS ? AND workspace_id = ?
2013                ORDER BY position
2014        ))?((group_id, workspace_id))?
2015        .into_iter()
2016        .map(|(group_id, axis, pane_id, active, pinned_count, flexes)| {
2017            let maybe_pane = maybe!({ Some((pane_id?, active?, pinned_count?)) });
2018            if let Some((group_id, axis)) = group_id.zip(axis) {
2019                let flexes = flexes
2020                    .map(|flexes: String| serde_json::from_str::<Vec<f32>>(&flexes))
2021                    .transpose()?;
2022
2023                Ok(SerializedPaneGroup::Group {
2024                    axis,
2025                    children: self.get_pane_group(workspace_id, Some(group_id))?,
2026                    flexes,
2027                })
2028            } else if let Some((pane_id, active, pinned_count)) = maybe_pane {
2029                Ok(SerializedPaneGroup::Pane(SerializedPane::new(
2030                    self.get_items(pane_id)?,
2031                    active,
2032                    pinned_count,
2033                )))
2034            } else {
2035                bail!("Pane Group Child was neither a pane group or a pane");
2036            }
2037        })
2038        // Filter out panes and pane groups which don't have any children or items
2039        .filter(|pane_group| match pane_group {
2040            Ok(SerializedPaneGroup::Group { children, .. }) => !children.is_empty(),
2041            Ok(SerializedPaneGroup::Pane(pane)) => !pane.children.is_empty(),
2042            _ => true,
2043        })
2044        .collect::<Result<_>>()
2045    }
2046
2047    fn save_pane_group(
2048        conn: &Connection,
2049        workspace_id: WorkspaceId,
2050        pane_group: &SerializedPaneGroup,
2051        parent: Option<(GroupId, usize)>,
2052    ) -> Result<()> {
2053        if parent.is_none() {
2054            log::debug!("Saving a pane group for workspace {workspace_id:?}");
2055        }
2056        match pane_group {
2057            SerializedPaneGroup::Group {
2058                axis,
2059                children,
2060                flexes,
2061            } => {
2062                let (parent_id, position) = parent.unzip();
2063
2064                let flex_string = flexes
2065                    .as_ref()
2066                    .map(|flexes| serde_json::json!(flexes).to_string());
2067
2068                let group_id = conn.select_row_bound::<_, i64>(sql!(
2069                    INSERT INTO pane_groups(
2070                        workspace_id,
2071                        parent_group_id,
2072                        position,
2073                        axis,
2074                        flexes
2075                    )
2076                    VALUES (?, ?, ?, ?, ?)
2077                    RETURNING group_id
2078                ))?((
2079                    workspace_id,
2080                    parent_id,
2081                    position,
2082                    *axis,
2083                    flex_string,
2084                ))?
2085                .context("Couldn't retrieve group_id from inserted pane_group")?;
2086
2087                for (position, group) in children.iter().enumerate() {
2088                    Self::save_pane_group(conn, workspace_id, group, Some((group_id, position)))?
2089                }
2090
2091                Ok(())
2092            }
2093            SerializedPaneGroup::Pane(pane) => {
2094                Self::save_pane(conn, workspace_id, pane, parent)?;
2095                Ok(())
2096            }
2097        }
2098    }
2099
2100    fn save_pane(
2101        conn: &Connection,
2102        workspace_id: WorkspaceId,
2103        pane: &SerializedPane,
2104        parent: Option<(GroupId, usize)>,
2105    ) -> Result<PaneId> {
2106        let pane_id = conn.select_row_bound::<_, i64>(sql!(
2107            INSERT INTO panes(workspace_id, active, pinned_count)
2108            VALUES (?, ?, ?)
2109            RETURNING pane_id
2110        ))?((workspace_id, pane.active, pane.pinned_count))?
2111        .context("Could not retrieve inserted pane_id")?;
2112
2113        let (parent_id, order) = parent.unzip();
2114        conn.exec_bound(sql!(
2115            INSERT INTO center_panes(pane_id, parent_group_id, position)
2116            VALUES (?, ?, ?)
2117        ))?((pane_id, parent_id, order))?;
2118
2119        Self::save_items(conn, workspace_id, pane_id, &pane.children).context("Saving items")?;
2120
2121        Ok(pane_id)
2122    }
2123
2124    fn get_items(&self, pane_id: PaneId) -> Result<Vec<SerializedItem>> {
2125        self.select_bound(sql!(
2126            SELECT kind, item_id, active, preview FROM items
2127            WHERE pane_id = ?
2128                ORDER BY position
2129        ))?(pane_id)
2130    }
2131
2132    fn save_items(
2133        conn: &Connection,
2134        workspace_id: WorkspaceId,
2135        pane_id: PaneId,
2136        items: &[SerializedItem],
2137    ) -> Result<()> {
2138        let mut insert = conn.exec_bound(sql!(
2139            INSERT INTO items(workspace_id, pane_id, position, kind, item_id, active, preview) VALUES (?, ?, ?, ?, ?, ?, ?)
2140        )).context("Preparing insertion")?;
2141        for (position, item) in items.iter().enumerate() {
2142            insert((workspace_id, pane_id, position, item))?;
2143        }
2144
2145        Ok(())
2146    }
2147
2148    query! {
2149        pub async fn update_timestamp(workspace_id: WorkspaceId) -> Result<()> {
2150            UPDATE workspaces
2151            SET timestamp = CURRENT_TIMESTAMP
2152            WHERE workspace_id = ?
2153        }
2154    }
2155
2156    query! {
2157        pub(crate) async fn set_window_open_status(workspace_id: WorkspaceId, bounds: SerializedWindowBounds, display: Uuid) -> Result<()> {
2158            UPDATE workspaces
2159            SET window_state = ?2,
2160                window_x = ?3,
2161                window_y = ?4,
2162                window_width = ?5,
2163                window_height = ?6,
2164                display = ?7
2165            WHERE workspace_id = ?1
2166        }
2167    }
2168
2169    query! {
2170        pub(crate) async fn set_centered_layout(workspace_id: WorkspaceId, centered_layout: bool) -> Result<()> {
2171            UPDATE workspaces
2172            SET centered_layout = ?2
2173            WHERE workspace_id = ?1
2174        }
2175    }
2176
2177    query! {
2178        pub(crate) async fn set_session_id(workspace_id: WorkspaceId, session_id: Option<String>) -> Result<()> {
2179            UPDATE workspaces
2180            SET session_id = ?2
2181            WHERE workspace_id = ?1
2182        }
2183    }
2184
2185    query! {
2186        pub(crate) async fn set_session_binding(workspace_id: WorkspaceId, session_id: Option<String>, window_id: Option<u64>) -> Result<()> {
2187            UPDATE workspaces
2188            SET session_id = ?2, window_id = ?3
2189            WHERE workspace_id = ?1
2190        }
2191    }
2192
2193    pub(crate) async fn toolchains(
2194        &self,
2195        workspace_id: WorkspaceId,
2196    ) -> Result<Vec<(Toolchain, Arc<Path>, Arc<RelPath>)>> {
2197        self.write(move |this| {
2198            let mut select = this
2199                .select_bound(sql!(
2200                    SELECT
2201                        name, path, worktree_root_path, relative_worktree_path, language_name, raw_json
2202                    FROM toolchains
2203                    WHERE workspace_id = ?
2204                ))
2205                .context("select toolchains")?;
2206
2207            let toolchain: Vec<(String, String, String, String, String, String)> =
2208                select(workspace_id)?;
2209
2210            Ok(toolchain
2211                .into_iter()
2212                .filter_map(
2213                    |(name, path, worktree_root_path, relative_worktree_path, language, json)| {
2214                        Some((
2215                            Toolchain {
2216                                name: name.into(),
2217                                path: path.into(),
2218                                language_name: LanguageName::new(&language),
2219                                as_json: serde_json::Value::from_str(&json).ok()?,
2220                            },
2221                           Arc::from(worktree_root_path.as_ref()),
2222                            RelPath::from_proto(&relative_worktree_path).log_err()?,
2223                        ))
2224                    },
2225                )
2226                .collect())
2227        })
2228        .await
2229    }
2230
2231    pub async fn set_toolchain(
2232        &self,
2233        workspace_id: WorkspaceId,
2234        worktree_root_path: Arc<Path>,
2235        relative_worktree_path: Arc<RelPath>,
2236        toolchain: Toolchain,
2237    ) -> Result<()> {
2238        log::debug!(
2239            "Setting toolchain for workspace, worktree: {worktree_root_path:?}, relative path: {relative_worktree_path:?}, toolchain: {}",
2240            toolchain.name
2241        );
2242        self.write(move |conn| {
2243            let mut insert = conn
2244                .exec_bound(sql!(
2245                    INSERT INTO toolchains(workspace_id, worktree_root_path, relative_worktree_path, language_name, name, path, raw_json) VALUES (?, ?, ?, ?, ?,  ?, ?)
2246                    ON CONFLICT DO
2247                    UPDATE SET
2248                        name = ?5,
2249                        path = ?6,
2250                        raw_json = ?7
2251                ))
2252                .context("Preparing insertion")?;
2253
2254            insert((
2255                workspace_id,
2256                worktree_root_path.to_string_lossy().into_owned(),
2257                relative_worktree_path.as_unix_str(),
2258                toolchain.language_name.as_ref(),
2259                toolchain.name.as_ref(),
2260                toolchain.path.as_ref(),
2261                toolchain.as_json.to_string(),
2262            ))?;
2263
2264            Ok(())
2265        }).await
2266    }
2267
2268    pub(crate) async fn save_trusted_worktrees(
2269        &self,
2270        trusted_worktrees: HashMap<Option<RemoteHostLocation>, HashSet<PathBuf>>,
2271    ) -> anyhow::Result<()> {
2272        use anyhow::Context as _;
2273        use db::sqlez::statement::Statement;
2274        use itertools::Itertools as _;
2275
2276        self.clear_trusted_worktrees()
2277            .await
2278            .context("clearing previous trust state")?;
2279
2280        let trusted_worktrees = trusted_worktrees
2281            .into_iter()
2282            .flat_map(|(host, abs_paths)| {
2283                abs_paths
2284                    .into_iter()
2285                    .map(move |abs_path| (Some(abs_path), host.clone()))
2286            })
2287            .collect::<Vec<_>>();
2288        let mut first_worktree;
2289        let mut last_worktree = 0_usize;
2290        for (count, placeholders) in std::iter::once("(?, ?, ?)")
2291            .cycle()
2292            .take(trusted_worktrees.len())
2293            .chunks(MAX_QUERY_PLACEHOLDERS / 3)
2294            .into_iter()
2295            .map(|chunk| {
2296                let mut count = 0;
2297                let placeholders = chunk
2298                    .inspect(|_| {
2299                        count += 1;
2300                    })
2301                    .join(", ");
2302                (count, placeholders)
2303            })
2304            .collect::<Vec<_>>()
2305        {
2306            first_worktree = last_worktree;
2307            last_worktree = last_worktree + count;
2308            let query = format!(
2309                r#"INSERT INTO trusted_worktrees(absolute_path, user_name, host_name)
2310VALUES {placeholders};"#
2311            );
2312
2313            let trusted_worktrees = trusted_worktrees[first_worktree..last_worktree].to_vec();
2314            self.write(move |conn| {
2315                let mut statement = Statement::prepare(conn, query)?;
2316                let mut next_index = 1;
2317                for (abs_path, host) in trusted_worktrees {
2318                    let abs_path = abs_path.as_ref().map(|abs_path| abs_path.to_string_lossy());
2319                    next_index = statement.bind(
2320                        &abs_path.as_ref().map(|abs_path| abs_path.as_ref()),
2321                        next_index,
2322                    )?;
2323                    next_index = statement.bind(
2324                        &host
2325                            .as_ref()
2326                            .and_then(|host| Some(host.user_name.as_ref()?.as_str())),
2327                        next_index,
2328                    )?;
2329                    next_index = statement.bind(
2330                        &host.as_ref().map(|host| host.host_identifier.as_str()),
2331                        next_index,
2332                    )?;
2333                }
2334                statement.exec()
2335            })
2336            .await
2337            .context("inserting new trusted state")?;
2338        }
2339        Ok(())
2340    }
2341
2342    pub fn fetch_trusted_worktrees(&self) -> Result<DbTrustedPaths> {
2343        let trusted_worktrees = self.trusted_worktrees()?;
2344        Ok(trusted_worktrees
2345            .into_iter()
2346            .filter_map(|(abs_path, user_name, host_name)| {
2347                let db_host = match (user_name, host_name) {
2348                    (None, Some(host_name)) => Some(RemoteHostLocation {
2349                        user_name: None,
2350                        host_identifier: SharedString::new(host_name),
2351                    }),
2352                    (Some(user_name), Some(host_name)) => Some(RemoteHostLocation {
2353                        user_name: Some(SharedString::new(user_name)),
2354                        host_identifier: SharedString::new(host_name),
2355                    }),
2356                    _ => None,
2357                };
2358                Some((db_host, abs_path?))
2359            })
2360            .fold(HashMap::default(), |mut acc, (remote_host, abs_path)| {
2361                acc.entry(remote_host)
2362                    .or_insert_with(HashSet::default)
2363                    .insert(abs_path);
2364                acc
2365            }))
2366    }
2367
2368    query! {
2369        fn trusted_worktrees() -> Result<Vec<(Option<PathBuf>, Option<String>, Option<String>)>> {
2370            SELECT absolute_path, user_name, host_name
2371            FROM trusted_worktrees
2372        }
2373    }
2374
2375    query! {
2376        pub async fn clear_trusted_worktrees() -> Result<()> {
2377            DELETE FROM trusted_worktrees
2378        }
2379    }
2380}
2381
2382type WorkspaceEntry = (
2383    WorkspaceId,
2384    SerializedWorkspaceLocation,
2385    PathList,
2386    DateTime<Utc>,
2387);
2388
2389/// Resolves workspace entries whose paths are git linked worktree checkouts
2390/// to their main repository paths.
2391///
2392/// For each workspace entry:
2393/// - If any path is a linked worktree checkout, all worktree paths in that
2394///   entry are resolved to their main repository paths, producing a new
2395///   `PathList`.
2396/// - The resolved entry is then deduplicated against existing entries: if a
2397///   workspace with the same paths already exists, the entry with the most
2398///   recent timestamp is kept.
2399pub async fn resolve_worktree_workspaces(
2400    workspaces: impl IntoIterator<Item = WorkspaceEntry>,
2401    fs: &dyn Fs,
2402) -> Vec<WorkspaceEntry> {
2403    // First pass: resolve worktree paths to main repo paths concurrently.
2404    let resolved = futures::future::join_all(workspaces.into_iter().map(|entry| async move {
2405        let paths = entry.2.paths();
2406        if paths.is_empty() {
2407            return entry;
2408        }
2409
2410        // Resolve each path concurrently
2411        let resolved_paths = futures::future::join_all(
2412            paths
2413                .iter()
2414                .map(|path| project::git_store::resolve_git_worktree_to_main_repo(fs, path)),
2415        )
2416        .await;
2417
2418        // If no paths were resolved, this entry is not a worktree — keep as-is
2419        if resolved_paths.iter().all(|r| r.is_none()) {
2420            return entry;
2421        }
2422
2423        // Build new path list, substituting resolved paths
2424        let new_paths: Vec<PathBuf> = paths
2425            .iter()
2426            .zip(resolved_paths.iter())
2427            .map(|(original, resolved)| {
2428                resolved
2429                    .as_ref()
2430                    .cloned()
2431                    .unwrap_or_else(|| original.clone())
2432            })
2433            .collect();
2434
2435        let new_path_refs: Vec<&Path> = new_paths.iter().map(|p| p.as_path()).collect();
2436        (entry.0, entry.1, PathList::new(&new_path_refs), entry.3)
2437    }))
2438    .await;
2439
2440    // Second pass: deduplicate by PathList.
2441    // When two entries resolve to the same paths, keep the one with the
2442    // more recent timestamp.
2443    let mut seen: collections::HashMap<Vec<PathBuf>, usize> = collections::HashMap::default();
2444    let mut result: Vec<WorkspaceEntry> = Vec::new();
2445
2446    for entry in resolved {
2447        let key: Vec<PathBuf> = entry.2.paths().to_vec();
2448        if let Some(&existing_idx) = seen.get(&key) {
2449            // Keep the entry with the more recent timestamp
2450            if entry.3 > result[existing_idx].3 {
2451                result[existing_idx] = entry;
2452            }
2453        } else {
2454            seen.insert(key, result.len());
2455            result.push(entry);
2456        }
2457    }
2458
2459    result
2460}
2461
2462pub fn delete_unloaded_items(
2463    alive_items: Vec<ItemId>,
2464    workspace_id: WorkspaceId,
2465    table: &'static str,
2466    db: &ThreadSafeConnection,
2467    cx: &mut App,
2468) -> Task<Result<()>> {
2469    let db = db.clone();
2470    cx.spawn(async move |_| {
2471        let placeholders = alive_items
2472            .iter()
2473            .map(|_| "?")
2474            .collect::<Vec<&str>>()
2475            .join(", ");
2476
2477        let query = format!(
2478            "DELETE FROM {table} WHERE workspace_id = ? AND item_id NOT IN ({placeholders})"
2479        );
2480
2481        db.write(move |conn| {
2482            let mut statement = Statement::prepare(conn, query)?;
2483            let mut next_index = statement.bind(&workspace_id, 1)?;
2484            for id in alive_items {
2485                next_index = statement.bind(&id, next_index)?;
2486            }
2487            statement.exec()
2488        })
2489        .await
2490    })
2491}
2492
2493#[cfg(test)]
2494mod tests {
2495    use super::*;
2496    use crate::{
2497        multi_workspace::MultiWorkspace,
2498        persistence::{
2499            model::{
2500                SerializedItem, SerializedPane, SerializedPaneGroup, SerializedWorkspace,
2501                SessionWorkspace,
2502            },
2503            read_multi_workspace_state,
2504        },
2505    };
2506    use feature_flags::FeatureFlagAppExt;
2507    use gpui::AppContext as _;
2508    use pretty_assertions::assert_eq;
2509    use project::{Project, ProjectGroupKey};
2510    use remote::SshConnectionOptions;
2511    use serde_json::json;
2512    use std::{thread, time::Duration};
2513
2514    /// Creates a unique directory in a FakeFs, returning the path.
2515    /// Uses a UUID suffix to avoid collisions with other tests sharing the global DB.
2516    async fn unique_test_dir(fs: &fs::FakeFs, prefix: &str) -> PathBuf {
2517        let dir = PathBuf::from(format!("/test-dirs/{}-{}", prefix, uuid::Uuid::new_v4()));
2518        fs.insert_tree(&dir, json!({})).await;
2519        dir
2520    }
2521
2522    #[gpui::test]
2523    async fn test_multi_workspace_serializes_on_add_and_remove(cx: &mut gpui::TestAppContext) {
2524        crate::tests::init_test(cx);
2525
2526        cx.update(|cx| {
2527            cx.set_staff(true);
2528            cx.update_flags(true, vec!["agent-v2".to_string()]);
2529        });
2530
2531        let fs = fs::FakeFs::new(cx.executor());
2532        let project1 = Project::test(fs.clone(), [], cx).await;
2533        let project2 = Project::test(fs.clone(), [], cx).await;
2534
2535        let (multi_workspace, cx) =
2536            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project1.clone(), window, cx));
2537
2538        multi_workspace.update(cx, |mw, cx| {
2539            mw.open_sidebar(cx);
2540        });
2541
2542        multi_workspace.update_in(cx, |mw, _, cx| {
2543            mw.set_random_database_id(cx);
2544        });
2545
2546        let window_id =
2547            multi_workspace.update_in(cx, |_, window, _cx| window.window_handle().window_id());
2548
2549        // --- Add a second workspace ---
2550        let workspace2 = multi_workspace.update_in(cx, |mw, window, cx| {
2551            let workspace = cx.new(|cx| crate::Workspace::test_new(project2.clone(), window, cx));
2552            workspace.update(cx, |ws, _cx| ws.set_random_database_id());
2553            mw.activate(workspace.clone(), window, cx);
2554            workspace
2555        });
2556
2557        // Run background tasks so serialize has a chance to flush.
2558        cx.run_until_parked();
2559
2560        // Read back the persisted state and check that the active workspace ID was written.
2561        let state_after_add = cx.update(|_, cx| read_multi_workspace_state(window_id, cx));
2562        let active_workspace2_db_id = workspace2.read_with(cx, |ws, _| ws.database_id());
2563        assert_eq!(
2564            state_after_add.active_workspace_id, active_workspace2_db_id,
2565            "After adding a second workspace, the serialized active_workspace_id should match \
2566             the newly activated workspace's database id"
2567        );
2568
2569        // --- Remove the second workspace (index 1) ---
2570        multi_workspace.update_in(cx, |mw, window, cx| {
2571            let ws = mw.workspaces().nth(1).unwrap().clone();
2572            mw.remove(&ws, window, cx);
2573        });
2574
2575        cx.run_until_parked();
2576
2577        let state_after_remove = cx.update(|_, cx| read_multi_workspace_state(window_id, cx));
2578        let remaining_db_id =
2579            multi_workspace.read_with(cx, |mw, cx| mw.workspace().read(cx).database_id());
2580        assert_eq!(
2581            state_after_remove.active_workspace_id, remaining_db_id,
2582            "After removing a workspace, the serialized active_workspace_id should match \
2583             the remaining active workspace's database id"
2584        );
2585    }
2586
2587    #[gpui::test]
2588    async fn test_breakpoints() {
2589        zlog::init_test();
2590
2591        let db = WorkspaceDb::open_test_db("test_breakpoints").await;
2592        let id = db.next_id().await.unwrap();
2593
2594        let path = Path::new("/tmp/test.rs");
2595
2596        let breakpoint = Breakpoint {
2597            position: 123,
2598            message: None,
2599            state: BreakpointState::Enabled,
2600            condition: None,
2601            hit_condition: None,
2602        };
2603
2604        let log_breakpoint = Breakpoint {
2605            position: 456,
2606            message: Some("Test log message".into()),
2607            state: BreakpointState::Enabled,
2608            condition: None,
2609            hit_condition: None,
2610        };
2611
2612        let disable_breakpoint = Breakpoint {
2613            position: 578,
2614            message: None,
2615            state: BreakpointState::Disabled,
2616            condition: None,
2617            hit_condition: None,
2618        };
2619
2620        let condition_breakpoint = Breakpoint {
2621            position: 789,
2622            message: None,
2623            state: BreakpointState::Enabled,
2624            condition: Some("x > 5".into()),
2625            hit_condition: None,
2626        };
2627
2628        let hit_condition_breakpoint = Breakpoint {
2629            position: 999,
2630            message: None,
2631            state: BreakpointState::Enabled,
2632            condition: None,
2633            hit_condition: Some(">= 3".into()),
2634        };
2635
2636        let workspace = SerializedWorkspace {
2637            id,
2638            paths: PathList::new(&["/tmp"]),
2639            location: SerializedWorkspaceLocation::Local,
2640            center_group: Default::default(),
2641            window_bounds: Default::default(),
2642            display: Default::default(),
2643            docks: Default::default(),
2644            centered_layout: false,
2645            breakpoints: {
2646                let mut map = collections::BTreeMap::default();
2647                map.insert(
2648                    Arc::from(path),
2649                    vec![
2650                        SourceBreakpoint {
2651                            row: breakpoint.position,
2652                            path: Arc::from(path),
2653                            message: breakpoint.message.clone(),
2654                            state: breakpoint.state,
2655                            condition: breakpoint.condition.clone(),
2656                            hit_condition: breakpoint.hit_condition.clone(),
2657                        },
2658                        SourceBreakpoint {
2659                            row: log_breakpoint.position,
2660                            path: Arc::from(path),
2661                            message: log_breakpoint.message.clone(),
2662                            state: log_breakpoint.state,
2663                            condition: log_breakpoint.condition.clone(),
2664                            hit_condition: log_breakpoint.hit_condition.clone(),
2665                        },
2666                        SourceBreakpoint {
2667                            row: disable_breakpoint.position,
2668                            path: Arc::from(path),
2669                            message: disable_breakpoint.message.clone(),
2670                            state: disable_breakpoint.state,
2671                            condition: disable_breakpoint.condition.clone(),
2672                            hit_condition: disable_breakpoint.hit_condition.clone(),
2673                        },
2674                        SourceBreakpoint {
2675                            row: condition_breakpoint.position,
2676                            path: Arc::from(path),
2677                            message: condition_breakpoint.message.clone(),
2678                            state: condition_breakpoint.state,
2679                            condition: condition_breakpoint.condition.clone(),
2680                            hit_condition: condition_breakpoint.hit_condition.clone(),
2681                        },
2682                        SourceBreakpoint {
2683                            row: hit_condition_breakpoint.position,
2684                            path: Arc::from(path),
2685                            message: hit_condition_breakpoint.message.clone(),
2686                            state: hit_condition_breakpoint.state,
2687                            condition: hit_condition_breakpoint.condition.clone(),
2688                            hit_condition: hit_condition_breakpoint.hit_condition.clone(),
2689                        },
2690                    ],
2691                );
2692                map
2693            },
2694            session_id: None,
2695            window_id: None,
2696            user_toolchains: Default::default(),
2697        };
2698
2699        db.save_workspace(workspace.clone()).await;
2700
2701        let loaded = db.workspace_for_roots(&["/tmp"]).unwrap();
2702        let loaded_breakpoints = loaded.breakpoints.get(&Arc::from(path)).unwrap();
2703
2704        assert_eq!(loaded_breakpoints.len(), 5);
2705
2706        // normal breakpoint
2707        assert_eq!(loaded_breakpoints[0].row, breakpoint.position);
2708        assert_eq!(loaded_breakpoints[0].message, breakpoint.message);
2709        assert_eq!(loaded_breakpoints[0].condition, breakpoint.condition);
2710        assert_eq!(
2711            loaded_breakpoints[0].hit_condition,
2712            breakpoint.hit_condition
2713        );
2714        assert_eq!(loaded_breakpoints[0].state, breakpoint.state);
2715        assert_eq!(loaded_breakpoints[0].path, Arc::from(path));
2716
2717        // enabled breakpoint
2718        assert_eq!(loaded_breakpoints[1].row, log_breakpoint.position);
2719        assert_eq!(loaded_breakpoints[1].message, log_breakpoint.message);
2720        assert_eq!(loaded_breakpoints[1].condition, log_breakpoint.condition);
2721        assert_eq!(
2722            loaded_breakpoints[1].hit_condition,
2723            log_breakpoint.hit_condition
2724        );
2725        assert_eq!(loaded_breakpoints[1].state, log_breakpoint.state);
2726        assert_eq!(loaded_breakpoints[1].path, Arc::from(path));
2727
2728        // disable breakpoint
2729        assert_eq!(loaded_breakpoints[2].row, disable_breakpoint.position);
2730        assert_eq!(loaded_breakpoints[2].message, disable_breakpoint.message);
2731        assert_eq!(
2732            loaded_breakpoints[2].condition,
2733            disable_breakpoint.condition
2734        );
2735        assert_eq!(
2736            loaded_breakpoints[2].hit_condition,
2737            disable_breakpoint.hit_condition
2738        );
2739        assert_eq!(loaded_breakpoints[2].state, disable_breakpoint.state);
2740        assert_eq!(loaded_breakpoints[2].path, Arc::from(path));
2741
2742        // condition breakpoint
2743        assert_eq!(loaded_breakpoints[3].row, condition_breakpoint.position);
2744        assert_eq!(loaded_breakpoints[3].message, condition_breakpoint.message);
2745        assert_eq!(
2746            loaded_breakpoints[3].condition,
2747            condition_breakpoint.condition
2748        );
2749        assert_eq!(
2750            loaded_breakpoints[3].hit_condition,
2751            condition_breakpoint.hit_condition
2752        );
2753        assert_eq!(loaded_breakpoints[3].state, condition_breakpoint.state);
2754        assert_eq!(loaded_breakpoints[3].path, Arc::from(path));
2755
2756        // hit condition breakpoint
2757        assert_eq!(loaded_breakpoints[4].row, hit_condition_breakpoint.position);
2758        assert_eq!(
2759            loaded_breakpoints[4].message,
2760            hit_condition_breakpoint.message
2761        );
2762        assert_eq!(
2763            loaded_breakpoints[4].condition,
2764            hit_condition_breakpoint.condition
2765        );
2766        assert_eq!(
2767            loaded_breakpoints[4].hit_condition,
2768            hit_condition_breakpoint.hit_condition
2769        );
2770        assert_eq!(loaded_breakpoints[4].state, hit_condition_breakpoint.state);
2771        assert_eq!(loaded_breakpoints[4].path, Arc::from(path));
2772    }
2773
2774    #[gpui::test]
2775    async fn test_remove_last_breakpoint() {
2776        zlog::init_test();
2777
2778        let db = WorkspaceDb::open_test_db("test_remove_last_breakpoint").await;
2779        let id = db.next_id().await.unwrap();
2780
2781        let singular_path = Path::new("/tmp/test_remove_last_breakpoint.rs");
2782
2783        let breakpoint_to_remove = Breakpoint {
2784            position: 100,
2785            message: None,
2786            state: BreakpointState::Enabled,
2787            condition: None,
2788            hit_condition: None,
2789        };
2790
2791        let workspace = SerializedWorkspace {
2792            id,
2793            paths: PathList::new(&["/tmp"]),
2794            location: SerializedWorkspaceLocation::Local,
2795            center_group: Default::default(),
2796            window_bounds: Default::default(),
2797            display: Default::default(),
2798            docks: Default::default(),
2799            centered_layout: false,
2800            breakpoints: {
2801                let mut map = collections::BTreeMap::default();
2802                map.insert(
2803                    Arc::from(singular_path),
2804                    vec![SourceBreakpoint {
2805                        row: breakpoint_to_remove.position,
2806                        path: Arc::from(singular_path),
2807                        message: None,
2808                        state: BreakpointState::Enabled,
2809                        condition: None,
2810                        hit_condition: None,
2811                    }],
2812                );
2813                map
2814            },
2815            session_id: None,
2816            window_id: None,
2817            user_toolchains: Default::default(),
2818        };
2819
2820        db.save_workspace(workspace.clone()).await;
2821
2822        let loaded = db.workspace_for_roots(&["/tmp"]).unwrap();
2823        let loaded_breakpoints = loaded.breakpoints.get(&Arc::from(singular_path)).unwrap();
2824
2825        assert_eq!(loaded_breakpoints.len(), 1);
2826        assert_eq!(loaded_breakpoints[0].row, breakpoint_to_remove.position);
2827        assert_eq!(loaded_breakpoints[0].message, breakpoint_to_remove.message);
2828        assert_eq!(
2829            loaded_breakpoints[0].condition,
2830            breakpoint_to_remove.condition
2831        );
2832        assert_eq!(
2833            loaded_breakpoints[0].hit_condition,
2834            breakpoint_to_remove.hit_condition
2835        );
2836        assert_eq!(loaded_breakpoints[0].state, breakpoint_to_remove.state);
2837        assert_eq!(loaded_breakpoints[0].path, Arc::from(singular_path));
2838
2839        let workspace_without_breakpoint = SerializedWorkspace {
2840            id,
2841            paths: PathList::new(&["/tmp"]),
2842            location: SerializedWorkspaceLocation::Local,
2843            center_group: Default::default(),
2844            window_bounds: Default::default(),
2845            display: Default::default(),
2846            docks: Default::default(),
2847            centered_layout: false,
2848            breakpoints: collections::BTreeMap::default(),
2849            session_id: None,
2850            window_id: None,
2851            user_toolchains: Default::default(),
2852        };
2853
2854        db.save_workspace(workspace_without_breakpoint.clone())
2855            .await;
2856
2857        let loaded_after_remove = db.workspace_for_roots(&["/tmp"]).unwrap();
2858        let empty_breakpoints = loaded_after_remove
2859            .breakpoints
2860            .get(&Arc::from(singular_path));
2861
2862        assert!(empty_breakpoints.is_none());
2863    }
2864
2865    #[gpui::test]
2866    async fn test_next_id_stability() {
2867        zlog::init_test();
2868
2869        let db = WorkspaceDb::open_test_db("test_next_id_stability").await;
2870
2871        db.write(|conn| {
2872            conn.migrate(
2873                "test_table",
2874                &[sql!(
2875                    CREATE TABLE test_table(
2876                        text TEXT,
2877                        workspace_id INTEGER,
2878                        FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
2879                        ON DELETE CASCADE
2880                    ) STRICT;
2881                )],
2882                &mut |_, _, _| false,
2883            )
2884            .unwrap();
2885        })
2886        .await;
2887
2888        let id = db.next_id().await.unwrap();
2889        // Assert the empty row got inserted
2890        assert_eq!(
2891            Some(id),
2892            db.select_row_bound::<WorkspaceId, WorkspaceId>(sql!(
2893                SELECT workspace_id FROM workspaces WHERE workspace_id = ?
2894            ))
2895            .unwrap()(id)
2896            .unwrap()
2897        );
2898
2899        db.write(move |conn| {
2900            conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
2901                .unwrap()(("test-text-1", id))
2902            .unwrap()
2903        })
2904        .await;
2905
2906        let test_text_1 = db
2907            .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
2908            .unwrap()(1)
2909        .unwrap()
2910        .unwrap();
2911        assert_eq!(test_text_1, "test-text-1");
2912    }
2913
2914    #[gpui::test]
2915    async fn test_workspace_id_stability() {
2916        zlog::init_test();
2917
2918        let db = WorkspaceDb::open_test_db("test_workspace_id_stability").await;
2919
2920        db.write(|conn| {
2921            conn.migrate(
2922                "test_table",
2923                &[sql!(
2924                        CREATE TABLE test_table(
2925                            text TEXT,
2926                            workspace_id INTEGER,
2927                            FOREIGN KEY(workspace_id)
2928                                REFERENCES workspaces(workspace_id)
2929                            ON DELETE CASCADE
2930                        ) STRICT;)],
2931                &mut |_, _, _| false,
2932            )
2933        })
2934        .await
2935        .unwrap();
2936
2937        let mut workspace_1 = SerializedWorkspace {
2938            id: WorkspaceId(1),
2939            paths: PathList::new(&["/tmp", "/tmp2"]),
2940            location: SerializedWorkspaceLocation::Local,
2941            center_group: Default::default(),
2942            window_bounds: Default::default(),
2943            display: Default::default(),
2944            docks: Default::default(),
2945            centered_layout: false,
2946            breakpoints: Default::default(),
2947            session_id: None,
2948            window_id: None,
2949            user_toolchains: Default::default(),
2950        };
2951
2952        let workspace_2 = SerializedWorkspace {
2953            id: WorkspaceId(2),
2954            paths: PathList::new(&["/tmp"]),
2955            location: SerializedWorkspaceLocation::Local,
2956            center_group: Default::default(),
2957            window_bounds: Default::default(),
2958            display: Default::default(),
2959            docks: Default::default(),
2960            centered_layout: false,
2961            breakpoints: Default::default(),
2962            session_id: None,
2963            window_id: None,
2964            user_toolchains: Default::default(),
2965        };
2966
2967        db.save_workspace(workspace_1.clone()).await;
2968
2969        db.write(|conn| {
2970            conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
2971                .unwrap()(("test-text-1", 1))
2972            .unwrap();
2973        })
2974        .await;
2975
2976        db.save_workspace(workspace_2.clone()).await;
2977
2978        db.write(|conn| {
2979            conn.exec_bound(sql!(INSERT INTO test_table(text, workspace_id) VALUES (?, ?)))
2980                .unwrap()(("test-text-2", 2))
2981            .unwrap();
2982        })
2983        .await;
2984
2985        workspace_1.paths = PathList::new(&["/tmp", "/tmp3"]);
2986        db.save_workspace(workspace_1.clone()).await;
2987        db.save_workspace(workspace_1).await;
2988        db.save_workspace(workspace_2).await;
2989
2990        let test_text_2 = db
2991            .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
2992            .unwrap()(2)
2993        .unwrap()
2994        .unwrap();
2995        assert_eq!(test_text_2, "test-text-2");
2996
2997        let test_text_1 = db
2998            .select_row_bound::<_, String>(sql!(SELECT text FROM test_table WHERE workspace_id = ?))
2999            .unwrap()(1)
3000        .unwrap()
3001        .unwrap();
3002        assert_eq!(test_text_1, "test-text-1");
3003    }
3004
3005    fn group(axis: Axis, children: Vec<SerializedPaneGroup>) -> SerializedPaneGroup {
3006        SerializedPaneGroup::Group {
3007            axis: SerializedAxis(axis),
3008            flexes: None,
3009            children,
3010        }
3011    }
3012
3013    #[gpui::test]
3014    async fn test_full_workspace_serialization() {
3015        zlog::init_test();
3016
3017        let db = WorkspaceDb::open_test_db("test_full_workspace_serialization").await;
3018
3019        //  -----------------
3020        //  | 1,2   | 5,6   |
3021        //  | - - - |       |
3022        //  | 3,4   |       |
3023        //  -----------------
3024        let center_group = group(
3025            Axis::Horizontal,
3026            vec![
3027                group(
3028                    Axis::Vertical,
3029                    vec![
3030                        SerializedPaneGroup::Pane(SerializedPane::new(
3031                            vec![
3032                                SerializedItem::new("Terminal", 5, false, false),
3033                                SerializedItem::new("Terminal", 6, true, false),
3034                            ],
3035                            false,
3036                            0,
3037                        )),
3038                        SerializedPaneGroup::Pane(SerializedPane::new(
3039                            vec![
3040                                SerializedItem::new("Terminal", 7, true, false),
3041                                SerializedItem::new("Terminal", 8, false, false),
3042                            ],
3043                            false,
3044                            0,
3045                        )),
3046                    ],
3047                ),
3048                SerializedPaneGroup::Pane(SerializedPane::new(
3049                    vec![
3050                        SerializedItem::new("Terminal", 9, false, false),
3051                        SerializedItem::new("Terminal", 10, true, false),
3052                    ],
3053                    false,
3054                    0,
3055                )),
3056            ],
3057        );
3058
3059        let workspace = SerializedWorkspace {
3060            id: WorkspaceId(5),
3061            paths: PathList::new(&["/tmp", "/tmp2"]),
3062            location: SerializedWorkspaceLocation::Local,
3063            center_group,
3064            window_bounds: Default::default(),
3065            breakpoints: Default::default(),
3066            display: Default::default(),
3067            docks: Default::default(),
3068            centered_layout: false,
3069            session_id: None,
3070            window_id: Some(999),
3071            user_toolchains: Default::default(),
3072        };
3073
3074        db.save_workspace(workspace.clone()).await;
3075
3076        let round_trip_workspace = db.workspace_for_roots(&["/tmp2", "/tmp"]);
3077        assert_eq!(workspace, round_trip_workspace.unwrap());
3078
3079        // Test guaranteed duplicate IDs
3080        db.save_workspace(workspace.clone()).await;
3081        db.save_workspace(workspace.clone()).await;
3082
3083        let round_trip_workspace = db.workspace_for_roots(&["/tmp", "/tmp2"]);
3084        assert_eq!(workspace, round_trip_workspace.unwrap());
3085    }
3086
3087    #[gpui::test]
3088    async fn test_workspace_assignment() {
3089        zlog::init_test();
3090
3091        let db = WorkspaceDb::open_test_db("test_basic_functionality").await;
3092
3093        let workspace_1 = SerializedWorkspace {
3094            id: WorkspaceId(1),
3095            paths: PathList::new(&["/tmp", "/tmp2"]),
3096            location: SerializedWorkspaceLocation::Local,
3097            center_group: Default::default(),
3098            window_bounds: Default::default(),
3099            breakpoints: Default::default(),
3100            display: Default::default(),
3101            docks: Default::default(),
3102            centered_layout: false,
3103            session_id: None,
3104            window_id: Some(1),
3105            user_toolchains: Default::default(),
3106        };
3107
3108        let mut workspace_2 = SerializedWorkspace {
3109            id: WorkspaceId(2),
3110            paths: PathList::new(&["/tmp"]),
3111            location: SerializedWorkspaceLocation::Local,
3112            center_group: Default::default(),
3113            window_bounds: Default::default(),
3114            display: Default::default(),
3115            docks: Default::default(),
3116            centered_layout: false,
3117            breakpoints: Default::default(),
3118            session_id: None,
3119            window_id: Some(2),
3120            user_toolchains: Default::default(),
3121        };
3122
3123        db.save_workspace(workspace_1.clone()).await;
3124        db.save_workspace(workspace_2.clone()).await;
3125
3126        // Test that paths are treated as a set
3127        assert_eq!(
3128            db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
3129            workspace_1
3130        );
3131        assert_eq!(
3132            db.workspace_for_roots(&["/tmp2", "/tmp"]).unwrap(),
3133            workspace_1
3134        );
3135
3136        // Make sure that other keys work
3137        assert_eq!(db.workspace_for_roots(&["/tmp"]).unwrap(), workspace_2);
3138        assert_eq!(db.workspace_for_roots(&["/tmp3", "/tmp2", "/tmp4"]), None);
3139
3140        // Test 'mutate' case of updating a pre-existing id
3141        workspace_2.paths = PathList::new(&["/tmp", "/tmp2"]);
3142
3143        db.save_workspace(workspace_2.clone()).await;
3144        assert_eq!(
3145            db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
3146            workspace_2
3147        );
3148
3149        // Test other mechanism for mutating
3150        let mut workspace_3 = SerializedWorkspace {
3151            id: WorkspaceId(3),
3152            paths: PathList::new(&["/tmp2", "/tmp"]),
3153            location: SerializedWorkspaceLocation::Local,
3154            center_group: Default::default(),
3155            window_bounds: Default::default(),
3156            breakpoints: Default::default(),
3157            display: Default::default(),
3158            docks: Default::default(),
3159            centered_layout: false,
3160            session_id: None,
3161            window_id: Some(3),
3162            user_toolchains: Default::default(),
3163        };
3164
3165        db.save_workspace(workspace_3.clone()).await;
3166        assert_eq!(
3167            db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
3168            workspace_3
3169        );
3170
3171        // Make sure that updating paths differently also works
3172        workspace_3.paths = PathList::new(&["/tmp3", "/tmp4", "/tmp2"]);
3173        db.save_workspace(workspace_3.clone()).await;
3174        assert_eq!(db.workspace_for_roots(&["/tmp2", "tmp"]), None);
3175        assert_eq!(
3176            db.workspace_for_roots(&["/tmp2", "/tmp3", "/tmp4"])
3177                .unwrap(),
3178            workspace_3
3179        );
3180    }
3181
3182    #[gpui::test]
3183    async fn test_session_workspaces() {
3184        zlog::init_test();
3185
3186        let db = WorkspaceDb::open_test_db("test_serializing_workspaces_session_id").await;
3187
3188        let workspace_1 = SerializedWorkspace {
3189            id: WorkspaceId(1),
3190            paths: PathList::new(&["/tmp1"]),
3191            location: SerializedWorkspaceLocation::Local,
3192            center_group: Default::default(),
3193            window_bounds: Default::default(),
3194            display: Default::default(),
3195            docks: Default::default(),
3196            centered_layout: false,
3197            breakpoints: Default::default(),
3198            session_id: Some("session-id-1".to_owned()),
3199            window_id: Some(10),
3200            user_toolchains: Default::default(),
3201        };
3202
3203        let workspace_2 = SerializedWorkspace {
3204            id: WorkspaceId(2),
3205            paths: PathList::new(&["/tmp2"]),
3206            location: SerializedWorkspaceLocation::Local,
3207            center_group: Default::default(),
3208            window_bounds: Default::default(),
3209            display: Default::default(),
3210            docks: Default::default(),
3211            centered_layout: false,
3212            breakpoints: Default::default(),
3213            session_id: Some("session-id-1".to_owned()),
3214            window_id: Some(20),
3215            user_toolchains: Default::default(),
3216        };
3217
3218        let workspace_3 = SerializedWorkspace {
3219            id: WorkspaceId(3),
3220            paths: PathList::new(&["/tmp3"]),
3221            location: SerializedWorkspaceLocation::Local,
3222            center_group: Default::default(),
3223            window_bounds: Default::default(),
3224            display: Default::default(),
3225            docks: Default::default(),
3226            centered_layout: false,
3227            breakpoints: Default::default(),
3228            session_id: Some("session-id-2".to_owned()),
3229            window_id: Some(30),
3230            user_toolchains: Default::default(),
3231        };
3232
3233        let workspace_4 = SerializedWorkspace {
3234            id: WorkspaceId(4),
3235            paths: PathList::new(&["/tmp4"]),
3236            location: SerializedWorkspaceLocation::Local,
3237            center_group: Default::default(),
3238            window_bounds: Default::default(),
3239            display: Default::default(),
3240            docks: Default::default(),
3241            centered_layout: false,
3242            breakpoints: Default::default(),
3243            session_id: None,
3244            window_id: None,
3245            user_toolchains: Default::default(),
3246        };
3247
3248        let connection_id = db
3249            .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
3250                host: "my-host".into(),
3251                port: Some(1234),
3252                ..Default::default()
3253            }))
3254            .await
3255            .unwrap();
3256
3257        let workspace_5 = SerializedWorkspace {
3258            id: WorkspaceId(5),
3259            paths: PathList::default(),
3260            location: SerializedWorkspaceLocation::Remote(
3261                db.remote_connection(connection_id).unwrap(),
3262            ),
3263            center_group: Default::default(),
3264            window_bounds: Default::default(),
3265            display: Default::default(),
3266            docks: Default::default(),
3267            centered_layout: false,
3268            breakpoints: Default::default(),
3269            session_id: Some("session-id-2".to_owned()),
3270            window_id: Some(50),
3271            user_toolchains: Default::default(),
3272        };
3273
3274        let workspace_6 = SerializedWorkspace {
3275            id: WorkspaceId(6),
3276            paths: PathList::new(&["/tmp6c", "/tmp6b", "/tmp6a"]),
3277            location: SerializedWorkspaceLocation::Local,
3278            center_group: Default::default(),
3279            window_bounds: Default::default(),
3280            breakpoints: Default::default(),
3281            display: Default::default(),
3282            docks: Default::default(),
3283            centered_layout: false,
3284            session_id: Some("session-id-3".to_owned()),
3285            window_id: Some(60),
3286            user_toolchains: Default::default(),
3287        };
3288
3289        db.save_workspace(workspace_1.clone()).await;
3290        thread::sleep(Duration::from_millis(1000)); // Force timestamps to increment
3291        db.save_workspace(workspace_2.clone()).await;
3292        db.save_workspace(workspace_3.clone()).await;
3293        thread::sleep(Duration::from_millis(1000)); // Force timestamps to increment
3294        db.save_workspace(workspace_4.clone()).await;
3295        db.save_workspace(workspace_5.clone()).await;
3296        db.save_workspace(workspace_6.clone()).await;
3297
3298        let locations = db.session_workspaces("session-id-1".to_owned()).unwrap();
3299        assert_eq!(locations.len(), 2);
3300        assert_eq!(locations[0].0, WorkspaceId(2));
3301        assert_eq!(locations[0].1, PathList::new(&["/tmp2"]));
3302        assert_eq!(locations[0].2, Some(20));
3303        assert_eq!(locations[1].0, WorkspaceId(1));
3304        assert_eq!(locations[1].1, PathList::new(&["/tmp1"]));
3305        assert_eq!(locations[1].2, Some(10));
3306
3307        let locations = db.session_workspaces("session-id-2".to_owned()).unwrap();
3308        assert_eq!(locations.len(), 2);
3309        assert_eq!(locations[0].0, WorkspaceId(5));
3310        assert_eq!(locations[0].1, PathList::default());
3311        assert_eq!(locations[0].2, Some(50));
3312        assert_eq!(locations[0].3, Some(connection_id));
3313        assert_eq!(locations[1].0, WorkspaceId(3));
3314        assert_eq!(locations[1].1, PathList::new(&["/tmp3"]));
3315        assert_eq!(locations[1].2, Some(30));
3316
3317        let locations = db.session_workspaces("session-id-3".to_owned()).unwrap();
3318        assert_eq!(locations.len(), 1);
3319        assert_eq!(locations[0].0, WorkspaceId(6));
3320        assert_eq!(
3321            locations[0].1,
3322            PathList::new(&["/tmp6c", "/tmp6b", "/tmp6a"]),
3323        );
3324        assert_eq!(locations[0].2, Some(60));
3325    }
3326
3327    fn default_workspace<P: AsRef<Path>>(
3328        paths: &[P],
3329        center_group: &SerializedPaneGroup,
3330    ) -> SerializedWorkspace {
3331        SerializedWorkspace {
3332            id: WorkspaceId(4),
3333            paths: PathList::new(paths),
3334            location: SerializedWorkspaceLocation::Local,
3335            center_group: center_group.clone(),
3336            window_bounds: Default::default(),
3337            display: Default::default(),
3338            docks: Default::default(),
3339            breakpoints: Default::default(),
3340            centered_layout: false,
3341            session_id: None,
3342            window_id: None,
3343            user_toolchains: Default::default(),
3344        }
3345    }
3346
3347    #[gpui::test]
3348    async fn test_last_session_workspace_locations(cx: &mut gpui::TestAppContext) {
3349        let dir1 = tempfile::TempDir::with_prefix("dir1").unwrap();
3350        let dir2 = tempfile::TempDir::with_prefix("dir2").unwrap();
3351        let dir3 = tempfile::TempDir::with_prefix("dir3").unwrap();
3352        let dir4 = tempfile::TempDir::with_prefix("dir4").unwrap();
3353
3354        let fs = fs::FakeFs::new(cx.executor());
3355        fs.insert_tree(dir1.path(), json!({})).await;
3356        fs.insert_tree(dir2.path(), json!({})).await;
3357        fs.insert_tree(dir3.path(), json!({})).await;
3358        fs.insert_tree(dir4.path(), json!({})).await;
3359
3360        let db =
3361            WorkspaceDb::open_test_db("test_serializing_workspaces_last_session_workspaces").await;
3362
3363        let workspaces = [
3364            (1, vec![dir1.path()], 9),
3365            (2, vec![dir2.path()], 5),
3366            (3, vec![dir3.path()], 8),
3367            (4, vec![dir4.path()], 2),
3368            (5, vec![dir1.path(), dir2.path(), dir3.path()], 3),
3369            (6, vec![dir4.path(), dir3.path(), dir2.path()], 4),
3370        ]
3371        .into_iter()
3372        .map(|(id, paths, window_id)| SerializedWorkspace {
3373            id: WorkspaceId(id),
3374            paths: PathList::new(paths.as_slice()),
3375            location: SerializedWorkspaceLocation::Local,
3376            center_group: Default::default(),
3377            window_bounds: Default::default(),
3378            display: Default::default(),
3379            docks: Default::default(),
3380            centered_layout: false,
3381            session_id: Some("one-session".to_owned()),
3382            breakpoints: Default::default(),
3383            window_id: Some(window_id),
3384            user_toolchains: Default::default(),
3385        })
3386        .collect::<Vec<_>>();
3387
3388        for workspace in workspaces.iter() {
3389            db.save_workspace(workspace.clone()).await;
3390        }
3391
3392        let stack = Some(Vec::from([
3393            WindowId::from(2), // Top
3394            WindowId::from(8),
3395            WindowId::from(5),
3396            WindowId::from(9),
3397            WindowId::from(3),
3398            WindowId::from(4), // Bottom
3399        ]));
3400
3401        let locations = db
3402            .last_session_workspace_locations("one-session", stack, fs.as_ref())
3403            .await
3404            .unwrap();
3405        assert_eq!(
3406            locations,
3407            [
3408                SessionWorkspace {
3409                    workspace_id: WorkspaceId(4),
3410                    location: SerializedWorkspaceLocation::Local,
3411                    paths: PathList::new(&[dir4.path()]),
3412                    window_id: Some(WindowId::from(2u64)),
3413                },
3414                SessionWorkspace {
3415                    workspace_id: WorkspaceId(3),
3416                    location: SerializedWorkspaceLocation::Local,
3417                    paths: PathList::new(&[dir3.path()]),
3418                    window_id: Some(WindowId::from(8u64)),
3419                },
3420                SessionWorkspace {
3421                    workspace_id: WorkspaceId(2),
3422                    location: SerializedWorkspaceLocation::Local,
3423                    paths: PathList::new(&[dir2.path()]),
3424                    window_id: Some(WindowId::from(5u64)),
3425                },
3426                SessionWorkspace {
3427                    workspace_id: WorkspaceId(1),
3428                    location: SerializedWorkspaceLocation::Local,
3429                    paths: PathList::new(&[dir1.path()]),
3430                    window_id: Some(WindowId::from(9u64)),
3431                },
3432                SessionWorkspace {
3433                    workspace_id: WorkspaceId(5),
3434                    location: SerializedWorkspaceLocation::Local,
3435                    paths: PathList::new(&[dir1.path(), dir2.path(), dir3.path()]),
3436                    window_id: Some(WindowId::from(3u64)),
3437                },
3438                SessionWorkspace {
3439                    workspace_id: WorkspaceId(6),
3440                    location: SerializedWorkspaceLocation::Local,
3441                    paths: PathList::new(&[dir4.path(), dir3.path(), dir2.path()]),
3442                    window_id: Some(WindowId::from(4u64)),
3443                },
3444            ]
3445        );
3446    }
3447
3448    #[gpui::test]
3449    async fn test_last_session_workspace_locations_remote(cx: &mut gpui::TestAppContext) {
3450        let fs = fs::FakeFs::new(cx.executor());
3451        let db =
3452            WorkspaceDb::open_test_db("test_serializing_workspaces_last_session_workspaces_remote")
3453                .await;
3454
3455        let remote_connections = [
3456            ("host-1", "my-user-1"),
3457            ("host-2", "my-user-2"),
3458            ("host-3", "my-user-3"),
3459            ("host-4", "my-user-4"),
3460        ]
3461        .into_iter()
3462        .map(|(host, user)| async {
3463            let options = RemoteConnectionOptions::Ssh(SshConnectionOptions {
3464                host: host.into(),
3465                username: Some(user.to_string()),
3466                ..Default::default()
3467            });
3468            db.get_or_create_remote_connection(options.clone())
3469                .await
3470                .unwrap();
3471            options
3472        })
3473        .collect::<Vec<_>>();
3474
3475        let remote_connections = futures::future::join_all(remote_connections).await;
3476
3477        let workspaces = [
3478            (1, remote_connections[0].clone(), 9),
3479            (2, remote_connections[1].clone(), 5),
3480            (3, remote_connections[2].clone(), 8),
3481            (4, remote_connections[3].clone(), 2),
3482        ]
3483        .into_iter()
3484        .map(|(id, remote_connection, window_id)| SerializedWorkspace {
3485            id: WorkspaceId(id),
3486            paths: PathList::default(),
3487            location: SerializedWorkspaceLocation::Remote(remote_connection),
3488            center_group: Default::default(),
3489            window_bounds: Default::default(),
3490            display: Default::default(),
3491            docks: Default::default(),
3492            centered_layout: false,
3493            session_id: Some("one-session".to_owned()),
3494            breakpoints: Default::default(),
3495            window_id: Some(window_id),
3496            user_toolchains: Default::default(),
3497        })
3498        .collect::<Vec<_>>();
3499
3500        for workspace in workspaces.iter() {
3501            db.save_workspace(workspace.clone()).await;
3502        }
3503
3504        let stack = Some(Vec::from([
3505            WindowId::from(2), // Top
3506            WindowId::from(8),
3507            WindowId::from(5),
3508            WindowId::from(9), // Bottom
3509        ]));
3510
3511        let have = db
3512            .last_session_workspace_locations("one-session", stack, fs.as_ref())
3513            .await
3514            .unwrap();
3515        assert_eq!(have.len(), 4);
3516        assert_eq!(
3517            have[0],
3518            SessionWorkspace {
3519                workspace_id: WorkspaceId(4),
3520                location: SerializedWorkspaceLocation::Remote(remote_connections[3].clone()),
3521                paths: PathList::default(),
3522                window_id: Some(WindowId::from(2u64)),
3523            }
3524        );
3525        assert_eq!(
3526            have[1],
3527            SessionWorkspace {
3528                workspace_id: WorkspaceId(3),
3529                location: SerializedWorkspaceLocation::Remote(remote_connections[2].clone()),
3530                paths: PathList::default(),
3531                window_id: Some(WindowId::from(8u64)),
3532            }
3533        );
3534        assert_eq!(
3535            have[2],
3536            SessionWorkspace {
3537                workspace_id: WorkspaceId(2),
3538                location: SerializedWorkspaceLocation::Remote(remote_connections[1].clone()),
3539                paths: PathList::default(),
3540                window_id: Some(WindowId::from(5u64)),
3541            }
3542        );
3543        assert_eq!(
3544            have[3],
3545            SessionWorkspace {
3546                workspace_id: WorkspaceId(1),
3547                location: SerializedWorkspaceLocation::Remote(remote_connections[0].clone()),
3548                paths: PathList::default(),
3549                window_id: Some(WindowId::from(9u64)),
3550            }
3551        );
3552    }
3553
3554    #[gpui::test]
3555    async fn test_get_or_create_ssh_project() {
3556        let db = WorkspaceDb::open_test_db("test_get_or_create_ssh_project").await;
3557
3558        let host = "example.com".to_string();
3559        let port = Some(22_u16);
3560        let user = Some("user".to_string());
3561
3562        let connection_id = db
3563            .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
3564                host: host.clone().into(),
3565                port,
3566                username: user.clone(),
3567                ..Default::default()
3568            }))
3569            .await
3570            .unwrap();
3571
3572        // Test that calling the function again with the same parameters returns the same project
3573        let same_connection = db
3574            .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
3575                host: host.clone().into(),
3576                port,
3577                username: user.clone(),
3578                ..Default::default()
3579            }))
3580            .await
3581            .unwrap();
3582
3583        assert_eq!(connection_id, same_connection);
3584
3585        // Test with different parameters
3586        let host2 = "otherexample.com".to_string();
3587        let port2 = None;
3588        let user2 = Some("otheruser".to_string());
3589
3590        let different_connection = db
3591            .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
3592                host: host2.clone().into(),
3593                port: port2,
3594                username: user2.clone(),
3595                ..Default::default()
3596            }))
3597            .await
3598            .unwrap();
3599
3600        assert_ne!(connection_id, different_connection);
3601    }
3602
3603    #[gpui::test]
3604    async fn test_get_or_create_ssh_project_with_null_user() {
3605        let db = WorkspaceDb::open_test_db("test_get_or_create_ssh_project_with_null_user").await;
3606
3607        let (host, port, user) = ("example.com".to_string(), None, None);
3608
3609        let connection_id = db
3610            .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
3611                host: host.clone().into(),
3612                port,
3613                username: None,
3614                ..Default::default()
3615            }))
3616            .await
3617            .unwrap();
3618
3619        let same_connection_id = db
3620            .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions {
3621                host: host.clone().into(),
3622                port,
3623                username: user.clone(),
3624                ..Default::default()
3625            }))
3626            .await
3627            .unwrap();
3628
3629        assert_eq!(connection_id, same_connection_id);
3630    }
3631
3632    #[gpui::test]
3633    async fn test_get_remote_connections() {
3634        let db = WorkspaceDb::open_test_db("test_get_remote_connections").await;
3635
3636        let connections = [
3637            ("example.com".to_string(), None, None),
3638            (
3639                "anotherexample.com".to_string(),
3640                Some(123_u16),
3641                Some("user2".to_string()),
3642            ),
3643            ("yetanother.com".to_string(), Some(345_u16), None),
3644        ];
3645
3646        let mut ids = Vec::new();
3647        for (host, port, user) in connections.iter() {
3648            ids.push(
3649                db.get_or_create_remote_connection(RemoteConnectionOptions::Ssh(
3650                    SshConnectionOptions {
3651                        host: host.clone().into(),
3652                        port: *port,
3653                        username: user.clone(),
3654                        ..Default::default()
3655                    },
3656                ))
3657                .await
3658                .unwrap(),
3659            );
3660        }
3661
3662        let stored_connections = db.remote_connections().unwrap();
3663        assert_eq!(
3664            stored_connections,
3665            [
3666                (
3667                    ids[0],
3668                    RemoteConnectionOptions::Ssh(SshConnectionOptions {
3669                        host: "example.com".into(),
3670                        port: None,
3671                        username: None,
3672                        ..Default::default()
3673                    }),
3674                ),
3675                (
3676                    ids[1],
3677                    RemoteConnectionOptions::Ssh(SshConnectionOptions {
3678                        host: "anotherexample.com".into(),
3679                        port: Some(123),
3680                        username: Some("user2".into()),
3681                        ..Default::default()
3682                    }),
3683                ),
3684                (
3685                    ids[2],
3686                    RemoteConnectionOptions::Ssh(SshConnectionOptions {
3687                        host: "yetanother.com".into(),
3688                        port: Some(345),
3689                        username: None,
3690                        ..Default::default()
3691                    }),
3692                ),
3693            ]
3694            .into_iter()
3695            .collect::<HashMap<_, _>>(),
3696        );
3697    }
3698
3699    #[gpui::test]
3700    async fn test_simple_split() {
3701        zlog::init_test();
3702
3703        let db = WorkspaceDb::open_test_db("simple_split").await;
3704
3705        //  -----------------
3706        //  | 1,2   | 5,6   |
3707        //  | - - - |       |
3708        //  | 3,4   |       |
3709        //  -----------------
3710        let center_pane = group(
3711            Axis::Horizontal,
3712            vec![
3713                group(
3714                    Axis::Vertical,
3715                    vec![
3716                        SerializedPaneGroup::Pane(SerializedPane::new(
3717                            vec![
3718                                SerializedItem::new("Terminal", 1, false, false),
3719                                SerializedItem::new("Terminal", 2, true, false),
3720                            ],
3721                            false,
3722                            0,
3723                        )),
3724                        SerializedPaneGroup::Pane(SerializedPane::new(
3725                            vec![
3726                                SerializedItem::new("Terminal", 4, false, false),
3727                                SerializedItem::new("Terminal", 3, true, false),
3728                            ],
3729                            true,
3730                            0,
3731                        )),
3732                    ],
3733                ),
3734                SerializedPaneGroup::Pane(SerializedPane::new(
3735                    vec![
3736                        SerializedItem::new("Terminal", 5, true, false),
3737                        SerializedItem::new("Terminal", 6, false, false),
3738                    ],
3739                    false,
3740                    0,
3741                )),
3742            ],
3743        );
3744
3745        let workspace = default_workspace(&["/tmp"], &center_pane);
3746
3747        db.save_workspace(workspace.clone()).await;
3748
3749        let new_workspace = db.workspace_for_roots(&["/tmp"]).unwrap();
3750
3751        assert_eq!(workspace.center_group, new_workspace.center_group);
3752    }
3753
3754    #[gpui::test]
3755    async fn test_cleanup_panes() {
3756        zlog::init_test();
3757
3758        let db = WorkspaceDb::open_test_db("test_cleanup_panes").await;
3759
3760        let center_pane = group(
3761            Axis::Horizontal,
3762            vec![
3763                group(
3764                    Axis::Vertical,
3765                    vec![
3766                        SerializedPaneGroup::Pane(SerializedPane::new(
3767                            vec![
3768                                SerializedItem::new("Terminal", 1, false, false),
3769                                SerializedItem::new("Terminal", 2, true, false),
3770                            ],
3771                            false,
3772                            0,
3773                        )),
3774                        SerializedPaneGroup::Pane(SerializedPane::new(
3775                            vec![
3776                                SerializedItem::new("Terminal", 4, false, false),
3777                                SerializedItem::new("Terminal", 3, true, false),
3778                            ],
3779                            true,
3780                            0,
3781                        )),
3782                    ],
3783                ),
3784                SerializedPaneGroup::Pane(SerializedPane::new(
3785                    vec![
3786                        SerializedItem::new("Terminal", 5, false, false),
3787                        SerializedItem::new("Terminal", 6, true, false),
3788                    ],
3789                    false,
3790                    0,
3791                )),
3792            ],
3793        );
3794
3795        let id = &["/tmp"];
3796
3797        let mut workspace = default_workspace(id, &center_pane);
3798
3799        db.save_workspace(workspace.clone()).await;
3800
3801        workspace.center_group = group(
3802            Axis::Vertical,
3803            vec![
3804                SerializedPaneGroup::Pane(SerializedPane::new(
3805                    vec![
3806                        SerializedItem::new("Terminal", 1, false, false),
3807                        SerializedItem::new("Terminal", 2, true, false),
3808                    ],
3809                    false,
3810                    0,
3811                )),
3812                SerializedPaneGroup::Pane(SerializedPane::new(
3813                    vec![
3814                        SerializedItem::new("Terminal", 4, true, false),
3815                        SerializedItem::new("Terminal", 3, false, false),
3816                    ],
3817                    true,
3818                    0,
3819                )),
3820            ],
3821        );
3822
3823        db.save_workspace(workspace.clone()).await;
3824
3825        let new_workspace = db.workspace_for_roots(id).unwrap();
3826
3827        assert_eq!(workspace.center_group, new_workspace.center_group);
3828    }
3829
3830    #[gpui::test]
3831    async fn test_empty_workspace_window_bounds() {
3832        zlog::init_test();
3833
3834        let db = WorkspaceDb::open_test_db("test_empty_workspace_window_bounds").await;
3835        let id = db.next_id().await.unwrap();
3836
3837        // Create a workspace with empty paths (empty workspace)
3838        let empty_paths: &[&str] = &[];
3839        let display_uuid = Uuid::new_v4();
3840        let window_bounds = SerializedWindowBounds(WindowBounds::Windowed(Bounds {
3841            origin: point(px(100.0), px(200.0)),
3842            size: size(px(800.0), px(600.0)),
3843        }));
3844
3845        let workspace = SerializedWorkspace {
3846            id,
3847            paths: PathList::new(empty_paths),
3848            location: SerializedWorkspaceLocation::Local,
3849            center_group: Default::default(),
3850            window_bounds: None,
3851            display: None,
3852            docks: Default::default(),
3853            breakpoints: Default::default(),
3854            centered_layout: false,
3855            session_id: None,
3856            window_id: None,
3857            user_toolchains: Default::default(),
3858        };
3859
3860        // Save the workspace (this creates the record with empty paths)
3861        db.save_workspace(workspace.clone()).await;
3862
3863        // Save window bounds separately (as the actual code does via set_window_open_status)
3864        db.set_window_open_status(id, window_bounds, display_uuid)
3865            .await
3866            .unwrap();
3867
3868        // Empty workspaces cannot be retrieved by paths (they'd all match).
3869        // They must be retrieved by workspace_id.
3870        assert!(db.workspace_for_roots(empty_paths).is_none());
3871
3872        // Retrieve using workspace_for_id instead
3873        let retrieved = db.workspace_for_id(id).unwrap();
3874
3875        // Verify window bounds were persisted
3876        assert_eq!(retrieved.id, id);
3877        assert!(retrieved.window_bounds.is_some());
3878        assert_eq!(retrieved.window_bounds.unwrap().0, window_bounds.0);
3879        assert!(retrieved.display.is_some());
3880        assert_eq!(retrieved.display.unwrap(), display_uuid);
3881    }
3882
3883    #[gpui::test]
3884    async fn test_last_session_workspace_locations_groups_by_window_id(
3885        cx: &mut gpui::TestAppContext,
3886    ) {
3887        let dir1 = tempfile::TempDir::with_prefix("dir1").unwrap();
3888        let dir2 = tempfile::TempDir::with_prefix("dir2").unwrap();
3889        let dir3 = tempfile::TempDir::with_prefix("dir3").unwrap();
3890        let dir4 = tempfile::TempDir::with_prefix("dir4").unwrap();
3891        let dir5 = tempfile::TempDir::with_prefix("dir5").unwrap();
3892
3893        let fs = fs::FakeFs::new(cx.executor());
3894        fs.insert_tree(dir1.path(), json!({})).await;
3895        fs.insert_tree(dir2.path(), json!({})).await;
3896        fs.insert_tree(dir3.path(), json!({})).await;
3897        fs.insert_tree(dir4.path(), json!({})).await;
3898        fs.insert_tree(dir5.path(), json!({})).await;
3899
3900        let db =
3901            WorkspaceDb::open_test_db("test_last_session_workspace_locations_groups_by_window_id")
3902                .await;
3903
3904        // Simulate two MultiWorkspace windows each containing two workspaces,
3905        // plus one single-workspace window:
3906        //   Window 10: workspace 1, workspace 2
3907        //   Window 20: workspace 3, workspace 4
3908        //   Window 30: workspace 5 (only one)
3909        //
3910        // On session restore, the caller should be able to group these by
3911        // window_id to reconstruct the MultiWorkspace windows.
3912        let workspaces_data: Vec<(i64, &Path, u64)> = vec![
3913            (1, dir1.path(), 10),
3914            (2, dir2.path(), 10),
3915            (3, dir3.path(), 20),
3916            (4, dir4.path(), 20),
3917            (5, dir5.path(), 30),
3918        ];
3919
3920        for (id, dir, window_id) in &workspaces_data {
3921            db.save_workspace(SerializedWorkspace {
3922                id: WorkspaceId(*id),
3923                paths: PathList::new(&[*dir]),
3924                location: SerializedWorkspaceLocation::Local,
3925                center_group: Default::default(),
3926                window_bounds: Default::default(),
3927                display: Default::default(),
3928                docks: Default::default(),
3929                centered_layout: false,
3930                session_id: Some("test-session".to_owned()),
3931                breakpoints: Default::default(),
3932                window_id: Some(*window_id),
3933                user_toolchains: Default::default(),
3934            })
3935            .await;
3936        }
3937
3938        let locations = db
3939            .last_session_workspace_locations("test-session", None, fs.as_ref())
3940            .await
3941            .unwrap();
3942
3943        // All 5 workspaces should be returned with their window_ids.
3944        assert_eq!(locations.len(), 5);
3945
3946        // Every entry should have a window_id so the caller can group them.
3947        for session_workspace in &locations {
3948            assert!(
3949                session_workspace.window_id.is_some(),
3950                "workspace {:?} missing window_id",
3951                session_workspace.workspace_id
3952            );
3953        }
3954
3955        // Group by window_id, simulating what the restoration code should do.
3956        let mut by_window: HashMap<WindowId, Vec<WorkspaceId>> = HashMap::default();
3957        for session_workspace in &locations {
3958            if let Some(window_id) = session_workspace.window_id {
3959                by_window
3960                    .entry(window_id)
3961                    .or_default()
3962                    .push(session_workspace.workspace_id);
3963            }
3964        }
3965
3966        // Should produce 3 windows, not 5.
3967        assert_eq!(
3968            by_window.len(),
3969            3,
3970            "Expected 3 window groups, got {}: {:?}",
3971            by_window.len(),
3972            by_window
3973        );
3974
3975        // Window 10 should contain workspaces 1 and 2.
3976        let window_10 = by_window.get(&WindowId::from(10u64)).unwrap();
3977        assert_eq!(window_10.len(), 2);
3978        assert!(window_10.contains(&WorkspaceId(1)));
3979        assert!(window_10.contains(&WorkspaceId(2)));
3980
3981        // Window 20 should contain workspaces 3 and 4.
3982        let window_20 = by_window.get(&WindowId::from(20u64)).unwrap();
3983        assert_eq!(window_20.len(), 2);
3984        assert!(window_20.contains(&WorkspaceId(3)));
3985        assert!(window_20.contains(&WorkspaceId(4)));
3986
3987        // Window 30 should contain only workspace 5.
3988        let window_30 = by_window.get(&WindowId::from(30u64)).unwrap();
3989        assert_eq!(window_30.len(), 1);
3990        assert!(window_30.contains(&WorkspaceId(5)));
3991    }
3992
3993    #[gpui::test]
3994    async fn test_read_serialized_multi_workspaces_with_state(cx: &mut gpui::TestAppContext) {
3995        use crate::persistence::model::MultiWorkspaceState;
3996
3997        // Write multi-workspace state for two windows via the scoped KVP.
3998        let window_10 = WindowId::from(10u64);
3999        let window_20 = WindowId::from(20u64);
4000
4001        let kvp = cx.update(|cx| KeyValueStore::global(cx));
4002
4003        write_multi_workspace_state(
4004            &kvp,
4005            window_10,
4006            MultiWorkspaceState {
4007                active_workspace_id: Some(WorkspaceId(2)),
4008                project_group_keys: vec![],
4009                sidebar_open: true,
4010                sidebar_state: None,
4011            },
4012        )
4013        .await;
4014
4015        write_multi_workspace_state(
4016            &kvp,
4017            window_20,
4018            MultiWorkspaceState {
4019                active_workspace_id: Some(WorkspaceId(3)),
4020                project_group_keys: vec![],
4021                sidebar_open: false,
4022                sidebar_state: None,
4023            },
4024        )
4025        .await;
4026
4027        // Build session workspaces: two in window 10, one in window 20, one with no window.
4028        let session_workspaces = vec![
4029            SessionWorkspace {
4030                workspace_id: WorkspaceId(1),
4031                location: SerializedWorkspaceLocation::Local,
4032                paths: PathList::new(&["/a"]),
4033                window_id: Some(window_10),
4034            },
4035            SessionWorkspace {
4036                workspace_id: WorkspaceId(2),
4037                location: SerializedWorkspaceLocation::Local,
4038                paths: PathList::new(&["/b"]),
4039                window_id: Some(window_10),
4040            },
4041            SessionWorkspace {
4042                workspace_id: WorkspaceId(3),
4043                location: SerializedWorkspaceLocation::Local,
4044                paths: PathList::new(&["/c"]),
4045                window_id: Some(window_20),
4046            },
4047            SessionWorkspace {
4048                workspace_id: WorkspaceId(4),
4049                location: SerializedWorkspaceLocation::Local,
4050                paths: PathList::new(&["/d"]),
4051                window_id: None,
4052            },
4053        ];
4054
4055        let results = cx.update(|cx| read_serialized_multi_workspaces(session_workspaces, cx));
4056
4057        // Should produce 3 results: window 10, window 20, and the orphan.
4058        assert_eq!(results.len(), 3);
4059
4060        // Window 10: active_workspace_id = 2 picks workspace 2 (paths /b), sidebar open.
4061        let group_10 = &results[0];
4062        assert_eq!(group_10.active_workspace.workspace_id, WorkspaceId(2));
4063        assert_eq!(group_10.state.active_workspace_id, Some(WorkspaceId(2)));
4064        assert_eq!(group_10.state.sidebar_open, true);
4065
4066        // Window 20: active_workspace_id = 3 picks workspace 3 (paths /c), sidebar closed.
4067        let group_20 = &results[1];
4068        assert_eq!(group_20.active_workspace.workspace_id, WorkspaceId(3));
4069        assert_eq!(group_20.state.active_workspace_id, Some(WorkspaceId(3)));
4070        assert_eq!(group_20.state.sidebar_open, false);
4071
4072        // Orphan: no active_workspace_id, falls back to first workspace (id 4).
4073        let group_none = &results[2];
4074        assert_eq!(group_none.active_workspace.workspace_id, WorkspaceId(4));
4075        assert_eq!(group_none.state.active_workspace_id, None);
4076        assert_eq!(group_none.state.sidebar_open, false);
4077    }
4078
4079    #[gpui::test]
4080    async fn test_flush_serialization_completes_before_quit(cx: &mut gpui::TestAppContext) {
4081        crate::tests::init_test(cx);
4082
4083        cx.update(|cx| {
4084            cx.set_staff(true);
4085            cx.update_flags(true, vec!["agent-v2".to_string()]);
4086        });
4087
4088        let fs = fs::FakeFs::new(cx.executor());
4089        let project = Project::test(fs.clone(), [], cx).await;
4090
4091        let (multi_workspace, cx) =
4092            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4093
4094        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
4095
4096        let db = cx.update(|_, cx| WorkspaceDb::global(cx));
4097
4098        // Assign a database_id so serialization will actually persist.
4099        let workspace_id = db.next_id().await.unwrap();
4100        workspace.update(cx, |ws, _cx| {
4101            ws.set_database_id(workspace_id);
4102        });
4103
4104        // Mutate some workspace state.
4105        db.set_centered_layout(workspace_id, true).await.unwrap();
4106
4107        // Call flush_serialization and await the returned task directly
4108        // (without run_until_parked — the point is that awaiting the task
4109        // alone is sufficient).
4110        let task = multi_workspace.update_in(cx, |mw, window, cx| {
4111            mw.workspace()
4112                .update(cx, |ws, cx| ws.flush_serialization(window, cx))
4113        });
4114        task.await;
4115
4116        // Read the workspace back from the DB and verify serialization happened.
4117        let serialized = db.workspace_for_id(workspace_id);
4118        assert!(
4119            serialized.is_some(),
4120            "flush_serialization should have persisted the workspace to DB"
4121        );
4122    }
4123
4124    #[gpui::test]
4125    async fn test_create_workspace_serialization(cx: &mut gpui::TestAppContext) {
4126        crate::tests::init_test(cx);
4127
4128        cx.update(|cx| {
4129            cx.set_staff(true);
4130            cx.update_flags(true, vec!["agent-v2".to_string()]);
4131        });
4132
4133        let fs = fs::FakeFs::new(cx.executor());
4134        let project = Project::test(fs.clone(), [], cx).await;
4135
4136        let (multi_workspace, cx) =
4137            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4138
4139        // Give the first workspace a database_id.
4140        multi_workspace.update_in(cx, |mw, _, cx| {
4141            mw.set_random_database_id(cx);
4142        });
4143
4144        let window_id =
4145            multi_workspace.update_in(cx, |_, window, _cx| window.window_handle().window_id());
4146
4147        // Create a new workspace via the MultiWorkspace API (triggers next_id()).
4148        multi_workspace.update_in(cx, |mw, window, cx| {
4149            mw.create_test_workspace(window, cx).detach();
4150        });
4151
4152        // Let the async next_id() and re-serialization tasks complete.
4153        cx.run_until_parked();
4154
4155        // The new workspace should now have a database_id.
4156        let new_workspace_db_id =
4157            multi_workspace.read_with(cx, |mw, cx| mw.workspace().read(cx).database_id());
4158        assert!(
4159            new_workspace_db_id.is_some(),
4160            "New workspace should have a database_id after run_until_parked"
4161        );
4162
4163        // The multi-workspace state should record it as the active workspace.
4164        let state = cx.update(|_, cx| read_multi_workspace_state(window_id, cx));
4165        assert_eq!(
4166            state.active_workspace_id, new_workspace_db_id,
4167            "Serialized active_workspace_id should match the new workspace's database_id"
4168        );
4169
4170        // The individual workspace row should exist with real data
4171        // (not just the bare DEFAULT VALUES row from next_id).
4172        let workspace_id = new_workspace_db_id.unwrap();
4173        let db = cx.update(|_, cx| WorkspaceDb::global(cx));
4174        let serialized = db.workspace_for_id(workspace_id);
4175        assert!(
4176            serialized.is_some(),
4177            "Newly created workspace should be fully serialized in the DB after database_id assignment"
4178        );
4179    }
4180
4181    #[gpui::test]
4182    async fn test_remove_workspace_clears_session_binding(cx: &mut gpui::TestAppContext) {
4183        crate::tests::init_test(cx);
4184
4185        cx.update(|cx| {
4186            cx.set_staff(true);
4187            cx.update_flags(true, vec!["agent-v2".to_string()]);
4188        });
4189
4190        let fs = fs::FakeFs::new(cx.executor());
4191        let dir = unique_test_dir(&fs, "remove").await;
4192        let project1 = Project::test(fs.clone(), [], cx).await;
4193        let project2 = Project::test(fs.clone(), [], cx).await;
4194
4195        let (multi_workspace, cx) =
4196            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project1.clone(), window, cx));
4197
4198        multi_workspace.update(cx, |mw, cx| {
4199            mw.open_sidebar(cx);
4200        });
4201
4202        multi_workspace.update_in(cx, |mw, _, cx| {
4203            mw.set_random_database_id(cx);
4204        });
4205
4206        let db = cx.update(|_, cx| WorkspaceDb::global(cx));
4207
4208        // Get a real DB id for workspace2 so the row actually exists.
4209        let workspace2_db_id = db.next_id().await.unwrap();
4210
4211        multi_workspace.update_in(cx, |mw, window, cx| {
4212            let workspace = cx.new(|cx| crate::Workspace::test_new(project2.clone(), window, cx));
4213            workspace.update(cx, |ws: &mut crate::Workspace, _cx| {
4214                ws.set_database_id(workspace2_db_id)
4215            });
4216            mw.activate(workspace.clone(), window, cx);
4217        });
4218
4219        // Save a full workspace row to the DB directly.
4220        let session_id = format!("remove-test-session-{}", Uuid::new_v4());
4221        db.save_workspace(SerializedWorkspace {
4222            id: workspace2_db_id,
4223            paths: PathList::new(&[&dir]),
4224            location: SerializedWorkspaceLocation::Local,
4225            center_group: Default::default(),
4226            window_bounds: Default::default(),
4227            display: Default::default(),
4228            docks: Default::default(),
4229            centered_layout: false,
4230            session_id: Some(session_id.clone()),
4231            breakpoints: Default::default(),
4232            window_id: Some(99),
4233            user_toolchains: Default::default(),
4234        })
4235        .await;
4236
4237        assert!(
4238            db.workspace_for_id(workspace2_db_id).is_some(),
4239            "Workspace2 should exist in DB before removal"
4240        );
4241
4242        // Remove workspace at index 1 (the second workspace).
4243        multi_workspace.update_in(cx, |mw, window, cx| {
4244            let ws = mw.workspaces().nth(1).unwrap().clone();
4245            mw.remove(&ws, window, cx);
4246        });
4247
4248        cx.run_until_parked();
4249
4250        // The row should still exist so it continues to appear in recent
4251        // projects, but the session binding should be cleared so it is not
4252        // restored as part of any future session.
4253        assert!(
4254            db.workspace_for_id(workspace2_db_id).is_some(),
4255            "Removed workspace's DB row should be preserved for recent projects"
4256        );
4257
4258        let session_workspaces = db
4259            .last_session_workspace_locations("remove-test-session", None, fs.as_ref())
4260            .await
4261            .unwrap();
4262        let restored_ids: Vec<WorkspaceId> = session_workspaces
4263            .iter()
4264            .map(|sw| sw.workspace_id)
4265            .collect();
4266        assert!(
4267            !restored_ids.contains(&workspace2_db_id),
4268            "Removed workspace should not appear in session restoration"
4269        );
4270    }
4271
4272    #[gpui::test]
4273    async fn test_remove_workspace_not_restored_as_zombie(cx: &mut gpui::TestAppContext) {
4274        crate::tests::init_test(cx);
4275
4276        cx.update(|cx| {
4277            cx.set_staff(true);
4278            cx.update_flags(true, vec!["agent-v2".to_string()]);
4279        });
4280
4281        let fs = fs::FakeFs::new(cx.executor());
4282        let dir1 = tempfile::TempDir::with_prefix("zombie_test1").unwrap();
4283        let dir2 = tempfile::TempDir::with_prefix("zombie_test2").unwrap();
4284        fs.insert_tree(dir1.path(), json!({})).await;
4285        fs.insert_tree(dir2.path(), json!({})).await;
4286
4287        let project1 = Project::test(fs.clone(), [], cx).await;
4288        let project2 = Project::test(fs.clone(), [], cx).await;
4289
4290        let db = cx.update(|cx| WorkspaceDb::global(cx));
4291
4292        // Get real DB ids so the rows actually exist.
4293        let ws1_id = db.next_id().await.unwrap();
4294        let ws2_id = db.next_id().await.unwrap();
4295
4296        let (multi_workspace, cx) =
4297            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project1.clone(), window, cx));
4298
4299        multi_workspace.update(cx, |mw, cx| {
4300            mw.open_sidebar(cx);
4301        });
4302
4303        multi_workspace.update_in(cx, |mw, _, cx| {
4304            mw.workspace().update(cx, |ws, _cx| {
4305                ws.set_database_id(ws1_id);
4306            });
4307        });
4308
4309        multi_workspace.update_in(cx, |mw, window, cx| {
4310            let workspace = cx.new(|cx| crate::Workspace::test_new(project2.clone(), window, cx));
4311            workspace.update(cx, |ws: &mut crate::Workspace, _cx| {
4312                ws.set_database_id(ws2_id)
4313            });
4314            mw.activate(workspace.clone(), window, cx);
4315        });
4316
4317        let session_id = "test-zombie-session";
4318        let window_id_val: u64 = 42;
4319
4320        db.save_workspace(SerializedWorkspace {
4321            id: ws1_id,
4322            paths: PathList::new(&[dir1.path()]),
4323            location: SerializedWorkspaceLocation::Local,
4324            center_group: Default::default(),
4325            window_bounds: Default::default(),
4326            display: Default::default(),
4327            docks: Default::default(),
4328            centered_layout: false,
4329            session_id: Some(session_id.to_owned()),
4330            breakpoints: Default::default(),
4331            window_id: Some(window_id_val),
4332            user_toolchains: Default::default(),
4333        })
4334        .await;
4335
4336        db.save_workspace(SerializedWorkspace {
4337            id: ws2_id,
4338            paths: PathList::new(&[dir2.path()]),
4339            location: SerializedWorkspaceLocation::Local,
4340            center_group: Default::default(),
4341            window_bounds: Default::default(),
4342            display: Default::default(),
4343            docks: Default::default(),
4344            centered_layout: false,
4345            session_id: Some(session_id.to_owned()),
4346            breakpoints: Default::default(),
4347            window_id: Some(window_id_val),
4348            user_toolchains: Default::default(),
4349        })
4350        .await;
4351
4352        // Remove workspace2 (index 1).
4353        multi_workspace.update_in(cx, |mw, window, cx| {
4354            let ws = mw.workspaces().nth(1).unwrap().clone();
4355            mw.remove(&ws, window, cx);
4356        });
4357
4358        cx.run_until_parked();
4359
4360        // The removed workspace should NOT appear in session restoration.
4361        let locations = db
4362            .last_session_workspace_locations(session_id, None, fs.as_ref())
4363            .await
4364            .unwrap();
4365
4366        let restored_ids: Vec<WorkspaceId> = locations.iter().map(|sw| sw.workspace_id).collect();
4367        assert!(
4368            !restored_ids.contains(&ws2_id),
4369            "Removed workspace should not appear in session restoration list. Found: {:?}",
4370            restored_ids
4371        );
4372        assert!(
4373            restored_ids.contains(&ws1_id),
4374            "Remaining workspace should still appear in session restoration list"
4375        );
4376    }
4377
4378    #[gpui::test]
4379    async fn test_pending_removal_tasks_drained_on_flush(cx: &mut gpui::TestAppContext) {
4380        crate::tests::init_test(cx);
4381
4382        cx.update(|cx| {
4383            cx.set_staff(true);
4384            cx.update_flags(true, vec!["agent-v2".to_string()]);
4385        });
4386
4387        let fs = fs::FakeFs::new(cx.executor());
4388        let dir = unique_test_dir(&fs, "pending-removal").await;
4389        let project1 = Project::test(fs.clone(), [], cx).await;
4390        let project2 = Project::test(fs.clone(), [], cx).await;
4391
4392        let db = cx.update(|cx| WorkspaceDb::global(cx));
4393
4394        // Get a real DB id for workspace2 so the row actually exists.
4395        let workspace2_db_id = db.next_id().await.unwrap();
4396
4397        let (multi_workspace, cx) =
4398            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project1.clone(), window, cx));
4399
4400        multi_workspace.update(cx, |mw, cx| {
4401            mw.open_sidebar(cx);
4402        });
4403
4404        multi_workspace.update_in(cx, |mw, _, cx| {
4405            mw.set_random_database_id(cx);
4406        });
4407
4408        multi_workspace.update_in(cx, |mw, window, cx| {
4409            let workspace = cx.new(|cx| crate::Workspace::test_new(project2.clone(), window, cx));
4410            workspace.update(cx, |ws: &mut crate::Workspace, _cx| {
4411                ws.set_database_id(workspace2_db_id)
4412            });
4413            mw.activate(workspace.clone(), window, cx);
4414        });
4415
4416        // Save a full workspace row to the DB directly and let it settle.
4417        let session_id = format!("pending-removal-session-{}", Uuid::new_v4());
4418        db.save_workspace(SerializedWorkspace {
4419            id: workspace2_db_id,
4420            paths: PathList::new(&[&dir]),
4421            location: SerializedWorkspaceLocation::Local,
4422            center_group: Default::default(),
4423            window_bounds: Default::default(),
4424            display: Default::default(),
4425            docks: Default::default(),
4426            centered_layout: false,
4427            session_id: Some(session_id.clone()),
4428            breakpoints: Default::default(),
4429            window_id: Some(88),
4430            user_toolchains: Default::default(),
4431        })
4432        .await;
4433        cx.run_until_parked();
4434
4435        // Remove workspace2 — this pushes a task to pending_removal_tasks.
4436        multi_workspace.update_in(cx, |mw, window, cx| {
4437            let ws = mw.workspaces().nth(1).unwrap().clone();
4438            mw.remove(&ws, window, cx);
4439        });
4440
4441        // Simulate the quit handler pattern: collect flush tasks + pending
4442        // removal tasks and await them all.
4443        let all_tasks = multi_workspace.update_in(cx, |mw, window, cx| {
4444            let mut tasks: Vec<Task<()>> = mw
4445                .workspaces()
4446                .map(|workspace| {
4447                    workspace.update(cx, |workspace, cx| {
4448                        workspace.flush_serialization(window, cx)
4449                    })
4450                })
4451                .collect();
4452            let mut removal_tasks = mw.take_pending_removal_tasks();
4453            // Note: removal_tasks may be empty if the background task already
4454            // completed (take_pending_removal_tasks filters out ready tasks).
4455            tasks.append(&mut removal_tasks);
4456            tasks.push(mw.flush_serialization());
4457            tasks
4458        });
4459        futures::future::join_all(all_tasks).await;
4460
4461        // The row should still exist (for recent projects), but the session
4462        // binding should have been cleared by the pending removal task.
4463        assert!(
4464            db.workspace_for_id(workspace2_db_id).is_some(),
4465            "Workspace row should be preserved for recent projects"
4466        );
4467
4468        let session_workspaces = db
4469            .last_session_workspace_locations("pending-removal-session", None, fs.as_ref())
4470            .await
4471            .unwrap();
4472        let restored_ids: Vec<WorkspaceId> = session_workspaces
4473            .iter()
4474            .map(|sw| sw.workspace_id)
4475            .collect();
4476        assert!(
4477            !restored_ids.contains(&workspace2_db_id),
4478            "Pending removal task should have cleared the session binding"
4479        );
4480    }
4481
4482    #[gpui::test]
4483    async fn test_create_workspace_bounds_observer_uses_fresh_id(cx: &mut gpui::TestAppContext) {
4484        crate::tests::init_test(cx);
4485
4486        cx.update(|cx| {
4487            cx.set_staff(true);
4488            cx.update_flags(true, vec!["agent-v2".to_string()]);
4489        });
4490
4491        let fs = fs::FakeFs::new(cx.executor());
4492        let project = Project::test(fs.clone(), [], cx).await;
4493
4494        let (multi_workspace, cx) =
4495            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4496
4497        multi_workspace.update_in(cx, |mw, _, cx| {
4498            mw.set_random_database_id(cx);
4499        });
4500
4501        let task =
4502            multi_workspace.update_in(cx, |mw, window, cx| mw.create_test_workspace(window, cx));
4503        task.await;
4504
4505        let new_workspace_db_id =
4506            multi_workspace.read_with(cx, |mw, cx| mw.workspace().read(cx).database_id());
4507        assert!(
4508            new_workspace_db_id.is_some(),
4509            "After run_until_parked, the workspace should have a database_id"
4510        );
4511
4512        let workspace_id = new_workspace_db_id.unwrap();
4513
4514        let db = cx.update(|_, cx| WorkspaceDb::global(cx));
4515
4516        assert!(
4517            db.workspace_for_id(workspace_id).is_some(),
4518            "The workspace row should exist in the DB"
4519        );
4520
4521        cx.simulate_resize(gpui::size(px(1024.0), px(768.0)));
4522
4523        // Advance the clock past the 100ms debounce timer so the bounds
4524        // observer task fires
4525        cx.executor().advance_clock(Duration::from_millis(200));
4526        cx.run_until_parked();
4527
4528        let serialized = db
4529            .workspace_for_id(workspace_id)
4530            .expect("workspace row should still exist");
4531        assert!(
4532            serialized.window_bounds.is_some(),
4533            "The bounds observer should write bounds for the workspace's real DB ID, \
4534             even when the workspace was created via create_workspace (where the ID \
4535             is assigned asynchronously after construction)."
4536        );
4537    }
4538
4539    #[gpui::test]
4540    async fn test_flush_serialization_writes_bounds(cx: &mut gpui::TestAppContext) {
4541        crate::tests::init_test(cx);
4542
4543        cx.update(|cx| {
4544            cx.set_staff(true);
4545            cx.update_flags(true, vec!["agent-v2".to_string()]);
4546        });
4547
4548        let fs = fs::FakeFs::new(cx.executor());
4549        let dir = tempfile::TempDir::with_prefix("flush_bounds_test").unwrap();
4550        fs.insert_tree(dir.path(), json!({})).await;
4551
4552        let project = Project::test(fs.clone(), [dir.path()], cx).await;
4553
4554        let (multi_workspace, cx) =
4555            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
4556
4557        let db = cx.update(|_, cx| WorkspaceDb::global(cx));
4558        let workspace_id = db.next_id().await.unwrap();
4559        multi_workspace.update_in(cx, |mw, _, cx| {
4560            mw.workspace().update(cx, |ws, _cx| {
4561                ws.set_database_id(workspace_id);
4562            });
4563        });
4564
4565        let task = multi_workspace.update_in(cx, |mw, window, cx| {
4566            mw.workspace()
4567                .update(cx, |ws, cx| ws.flush_serialization(window, cx))
4568        });
4569        task.await;
4570
4571        let after = db
4572            .workspace_for_id(workspace_id)
4573            .expect("workspace row should exist after flush_serialization");
4574        assert!(
4575            !after.paths.is_empty(),
4576            "flush_serialization should have written paths via save_workspace"
4577        );
4578        assert!(
4579            after.window_bounds.is_some(),
4580            "flush_serialization should ensure window bounds are persisted to the DB \
4581             before the process exits."
4582        );
4583    }
4584
4585    #[gpui::test]
4586    async fn test_resolve_worktree_workspaces(cx: &mut gpui::TestAppContext) {
4587        let fs = fs::FakeFs::new(cx.executor());
4588
4589        // Main repo with a linked worktree entry
4590        fs.insert_tree(
4591            "/repo",
4592            json!({
4593                ".git": {
4594                    "worktrees": {
4595                        "feature": {
4596                            "commondir": "../../",
4597                            "HEAD": "ref: refs/heads/feature"
4598                        }
4599                    }
4600                },
4601                "src": { "main.rs": "" }
4602            }),
4603        )
4604        .await;
4605
4606        // Linked worktree checkout pointing back to /repo
4607        fs.insert_tree(
4608            "/worktree",
4609            json!({
4610                ".git": "gitdir: /repo/.git/worktrees/feature",
4611                "src": { "main.rs": "" }
4612            }),
4613        )
4614        .await;
4615
4616        // A plain non-git project
4617        fs.insert_tree(
4618            "/plain-project",
4619            json!({
4620                "src": { "main.rs": "" }
4621            }),
4622        )
4623        .await;
4624
4625        // Another normal git repo (used in mixed-path entry)
4626        fs.insert_tree(
4627            "/other-repo",
4628            json!({
4629                ".git": {},
4630                "src": { "lib.rs": "" }
4631            }),
4632        )
4633        .await;
4634
4635        let t0 = Utc::now() - chrono::Duration::hours(4);
4636        let t1 = Utc::now() - chrono::Duration::hours(3);
4637        let t2 = Utc::now() - chrono::Duration::hours(2);
4638        let t3 = Utc::now() - chrono::Duration::hours(1);
4639
4640        let workspaces = vec![
4641            // 1: Main checkout of /repo (opened earlier)
4642            (
4643                WorkspaceId(1),
4644                SerializedWorkspaceLocation::Local,
4645                PathList::new(&["/repo"]),
4646                t0,
4647            ),
4648            // 2: Linked worktree of /repo (opened more recently)
4649            //    Should dedup with #1; more recent timestamp wins.
4650            (
4651                WorkspaceId(2),
4652                SerializedWorkspaceLocation::Local,
4653                PathList::new(&["/worktree"]),
4654                t1,
4655            ),
4656            // 3: Mixed-path workspace: one root is a linked worktree,
4657            //    the other is a normal repo. The worktree path should be
4658            //    resolved; the normal path kept as-is.
4659            (
4660                WorkspaceId(3),
4661                SerializedWorkspaceLocation::Local,
4662                PathList::new(&["/other-repo", "/worktree"]),
4663                t2,
4664            ),
4665            // 4: Non-git project — passed through unchanged.
4666            (
4667                WorkspaceId(4),
4668                SerializedWorkspaceLocation::Local,
4669                PathList::new(&["/plain-project"]),
4670                t3,
4671            ),
4672        ];
4673
4674        let result = resolve_worktree_workspaces(workspaces, fs.as_ref()).await;
4675
4676        // Should have 3 entries: #1 and #2 deduped into one, plus #3 and #4.
4677        assert_eq!(result.len(), 3);
4678
4679        // First entry: /repo — deduplicated from #1 and #2.
4680        // Keeps the position of #1 (first seen), but with #2's later timestamp.
4681        assert_eq!(result[0].2.paths(), &[PathBuf::from("/repo")]);
4682        assert_eq!(result[0].3, t1);
4683
4684        // Second entry: mixed-path workspace with worktree resolved.
4685        // /worktree → /repo, so paths become [/other-repo, /repo] (sorted).
4686        assert_eq!(
4687            result[1].2.paths(),
4688            &[PathBuf::from("/other-repo"), PathBuf::from("/repo")]
4689        );
4690        assert_eq!(result[1].0, WorkspaceId(3));
4691
4692        // Third entry: non-git project, unchanged.
4693        assert_eq!(result[2].2.paths(), &[PathBuf::from("/plain-project")]);
4694        assert_eq!(result[2].0, WorkspaceId(4));
4695    }
4696
4697    #[gpui::test]
4698    async fn test_restore_window_with_linked_worktree_and_multiple_project_groups(
4699        cx: &mut gpui::TestAppContext,
4700    ) {
4701        crate::tests::init_test(cx);
4702
4703        cx.update(|cx| {
4704            cx.set_staff(true);
4705            cx.update_flags(true, vec!["agent-v2".to_string()]);
4706        });
4707
4708        let fs = fs::FakeFs::new(cx.executor());
4709
4710        // Main git repo at /repo
4711        fs.insert_tree(
4712            "/repo",
4713            json!({
4714                ".git": {
4715                    "HEAD": "ref: refs/heads/main",
4716                    "worktrees": {
4717                        "feature": {
4718                            "commondir": "../../",
4719                            "HEAD": "ref: refs/heads/feature"
4720                        }
4721                    }
4722                },
4723                "src": { "main.rs": "" }
4724            }),
4725        )
4726        .await;
4727
4728        // Linked worktree checkout pointing back to /repo
4729        fs.insert_tree(
4730            "/worktree-feature",
4731            json!({
4732                ".git": "gitdir: /repo/.git/worktrees/feature",
4733                "src": { "lib.rs": "" }
4734            }),
4735        )
4736        .await;
4737
4738        // --- Phase 1: Set up the original multi-workspace window ---
4739
4740        let project_1 = Project::test(fs.clone(), ["/repo".as_ref()], cx).await;
4741        let project_1_linked_worktree =
4742            Project::test(fs.clone(), ["/worktree-feature".as_ref()], cx).await;
4743
4744        // Wait for git discovery to finish.
4745        cx.run_until_parked();
4746
4747        // Create a second, unrelated project so we have two distinct project groups.
4748        fs.insert_tree(
4749            "/other-project",
4750            json!({
4751                ".git": { "HEAD": "ref: refs/heads/main" },
4752                "readme.md": ""
4753            }),
4754        )
4755        .await;
4756        let project_2 = Project::test(fs.clone(), ["/other-project".as_ref()], cx).await;
4757        cx.run_until_parked();
4758
4759        // Create the MultiWorkspace with project_2, then add the main repo
4760        // and its linked worktree. The linked worktree is added last and
4761        // becomes the active workspace.
4762        let (multi_workspace, cx) = cx
4763            .add_window_view(|window, cx| MultiWorkspace::test_new(project_2.clone(), window, cx));
4764
4765        multi_workspace.update(cx, |mw, cx| {
4766            mw.open_sidebar(cx);
4767        });
4768
4769        multi_workspace.update_in(cx, |mw, window, cx| {
4770            mw.test_add_workspace(project_1.clone(), window, cx);
4771        });
4772
4773        let workspace_worktree = multi_workspace.update_in(cx, |mw, window, cx| {
4774            mw.test_add_workspace(project_1_linked_worktree.clone(), window, cx)
4775        });
4776
4777        // Assign database IDs and set up session bindings so serialization
4778        // writes real rows.
4779        multi_workspace.update_in(cx, |mw, _, cx| {
4780            for workspace in mw.workspaces() {
4781                workspace.update(cx, |ws, _cx| {
4782                    ws.set_random_database_id();
4783                });
4784            }
4785        });
4786
4787        // Flush serialization for each individual workspace (writes to SQLite)
4788        // and for the MultiWorkspace (writes to KVP).
4789        let tasks = multi_workspace.update_in(cx, |mw, window, cx| {
4790            let session_id = mw.workspace().read(cx).session_id();
4791            let window_id_u64 = window.window_handle().window_id().as_u64();
4792
4793            let mut tasks: Vec<Task<()>> = Vec::new();
4794            for workspace in mw.workspaces() {
4795                tasks.push(workspace.update(cx, |ws, cx| ws.flush_serialization(window, cx)));
4796                if let Some(db_id) = workspace.read(cx).database_id() {
4797                    let db = WorkspaceDb::global(cx);
4798                    let session_id = session_id.clone();
4799                    tasks.push(cx.background_spawn(async move {
4800                        db.set_session_binding(db_id, session_id, Some(window_id_u64))
4801                            .await
4802                            .log_err();
4803                    }));
4804                }
4805            }
4806            mw.serialize(cx);
4807            tasks
4808        });
4809        cx.run_until_parked();
4810        for task in tasks {
4811            task.await;
4812        }
4813        cx.run_until_parked();
4814
4815        let active_db_id = workspace_worktree.read_with(cx, |ws, _| ws.database_id());
4816        assert!(
4817            active_db_id.is_some(),
4818            "Active workspace should have a database ID"
4819        );
4820
4821        // --- Phase 2: Read back and verify the serialized state ---
4822
4823        let session_id = multi_workspace
4824            .read_with(cx, |mw, cx| mw.workspace().read(cx).session_id())
4825            .unwrap();
4826        let db = cx.update(|_, cx| WorkspaceDb::global(cx));
4827        let session_workspaces = db
4828            .last_session_workspace_locations(&session_id, None, fs.as_ref())
4829            .await
4830            .expect("should load session workspaces");
4831        assert!(
4832            !session_workspaces.is_empty(),
4833            "Should have at least one session workspace"
4834        );
4835
4836        let multi_workspaces =
4837            cx.update(|_, cx| read_serialized_multi_workspaces(session_workspaces, cx));
4838        assert_eq!(
4839            multi_workspaces.len(),
4840            1,
4841            "All workspaces share one window, so there should be exactly one multi-workspace"
4842        );
4843
4844        let serialized = &multi_workspaces[0];
4845        assert_eq!(
4846            serialized.active_workspace.workspace_id,
4847            active_db_id.unwrap(),
4848        );
4849        assert_eq!(serialized.state.project_group_keys.len(), 2,);
4850
4851        // Verify the serialized project group keys round-trip back to the
4852        // originals.
4853        let restored_keys: Vec<ProjectGroupKey> = serialized
4854            .state
4855            .project_group_keys
4856            .iter()
4857            .cloned()
4858            .map(Into::into)
4859            .collect();
4860        let expected_keys = vec![
4861            ProjectGroupKey::new(None, PathList::new(&["/other-project"])),
4862            ProjectGroupKey::new(None, PathList::new(&["/repo"])),
4863        ];
4864        assert_eq!(
4865            restored_keys, expected_keys,
4866            "Deserialized project group keys should match the originals"
4867        );
4868
4869        // --- Phase 3: Restore the window and verify the result ---
4870
4871        let app_state =
4872            multi_workspace.read_with(cx, |mw, cx| mw.workspace().read(cx).app_state().clone());
4873
4874        let serialized_mw = multi_workspaces.into_iter().next().unwrap();
4875        let restored_handle: gpui::WindowHandle<MultiWorkspace> = cx
4876            .update(|_, cx| {
4877                cx.spawn(async move |mut cx| {
4878                    crate::restore_multiworkspace(serialized_mw, app_state, &mut cx).await
4879                })
4880            })
4881            .await
4882            .expect("restore_multiworkspace should succeed");
4883
4884        cx.run_until_parked();
4885
4886        // The restored window should have the same project group keys.
4887        let restored_keys: Vec<ProjectGroupKey> = restored_handle
4888            .read_with(cx, |mw: &MultiWorkspace, _cx| {
4889                mw.project_group_keys().cloned().collect()
4890            })
4891            .unwrap();
4892        assert_eq!(
4893            restored_keys, expected_keys,
4894            "Restored window should have the same project group keys as the original"
4895        );
4896
4897        // The active workspace in the restored window should have the linked
4898        // worktree paths.
4899        let active_paths: Vec<PathBuf> = restored_handle
4900            .read_with(cx, |mw: &MultiWorkspace, cx| {
4901                mw.workspace()
4902                    .read(cx)
4903                    .root_paths(cx)
4904                    .into_iter()
4905                    .map(|p: Arc<Path>| p.to_path_buf())
4906                    .collect()
4907            })
4908            .unwrap();
4909        assert_eq!(
4910            active_paths,
4911            vec![PathBuf::from("/worktree-feature")],
4912            "The restored active workspace should be the linked worktree project"
4913        );
4914    }
4915}