Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

6.0 KB
Raw Blame
//! Locating Codex's per-thread state SQLite databases.
//!
//! Codex stores thread metadata in `state_5.sqlite`, normally inside the Codex
//! config dir (`CODEX_HOME` / `~/.codex`). The SQLite location can be moved with
//! the `sqlite_home` key in `config.toml` or the `CODEX_SQLITE_HOME` env var;
//! when set, a second DB lives there. Both history migration and the session
//! list's title lookup need the same resolution, so it lives here once.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

use toml_edit::DocumentMut;

use crate::config::{get_home_dir, is_wsl_path};

/// Filename of Codex's per-thread state database. Codex bumps the version
/// number across releases; update this single source of truth when a new state
/// DB version ships.
pub(crate) const CODEX_STATE_DB_FILENAME: &str = "state_5.sqlite";

/// Env var that overrides the Codex SQLite state directory.
const CODEX_SQLITE_HOME_ENV: &str = "CODEX_SQLITE_HOME";

/// Resolve every candidate `state_5.sqlite` path: the config-dir DB plus, when
/// Codex is configured to keep its SQLite state elsewhere, that DB too.
///
/// `config_dir` is the Codex config dir (`~/.codex`); `config_text` is the raw
/// `config.toml` contents, used to detect a `sqlite_home` override.
pub(crate) fn codex_state_db_paths(config_dir: &Path, config_text: &str) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    push_unique_path(&mut paths, config_dir.join(CODEX_STATE_DB_FILENAME));
    // Codex lets SQLite state move away from CODEX_HOME; config takes precedence.
    if let Some(sqlite_home) = sqlite_home_from_codex_config(config_text) {
        push_unique_path(&mut paths, sqlite_home.join(CODEX_STATE_DB_FILENAME));
    } else if let Some(sqlite_home) = sqlite_home_from_env() {
        push_unique_path(&mut paths, sqlite_home.join(CODEX_STATE_DB_FILENAME));
    }
    paths
}

/// How many threads the state DBs record under `provider_id`.
///
/// `None` when no state DB could be read at all (none on disk, all on WSL
/// paths, or no `threads.model_provider` column), so callers can tell "nothing
/// to do" apart from "can't tell".
pub(crate) fn count_threads_with_model_provider(
    config_dir: &Path,
    config_text: &str,
    provider_id: &str,
) -> Option<usize> {
    let mut total = None;
    for path in codex_state_db_paths(config_dir, config_text) {
        if !path.exists() || !codex_state_db_is_lockable(&path) {
            continue;
        }
        // 普通方式打开(只做 SELECT):Codex 退出后 WAL 库的 -shm 会被清掉,
        // 只读连接在这种状态下能不能打开取决于 SQLite 版本,别赌。
        let Ok(conn) = rusqlite::Connection::open(&path) else {
            continue;
        };
        let _ = conn.busy_timeout(std::time::Duration::from_secs(2));
        let count: rusqlite::Result<i64> = conn.query_row(
            "SELECT COUNT(*) FROM threads WHERE model_provider = ?1",
            [provider_id],
            |row| row.get(0),
        );
        if let Ok(count) = count {
            *total.get_or_insert(0) += usize::try_from(count).unwrap_or(0);
        }
    }
    total
}

/// Whether CC Switch can open this state DB with SQLite locking intact.
///
/// Windows reaches a WSL distro's files through the `\\wsl$` /
/// `\\wsl.localhost` 9P redirector, which has no byte-range locks: every open
/// waits out the busy timeout and then fails with "database is locked". Such
/// DBs are skipped (migration counts zero rows, titles fall back to the
/// session index) instead of blocking each startup and session scan.
pub(crate) fn codex_state_db_is_lockable(path: &Path) -> bool {
    if !is_wsl_path(path) {
        return true;
    }
    static WARNED: AtomicBool = AtomicBool::new(false);
    if !WARNED.swap(true, Ordering::Relaxed) {
        log::warn!(
            "Skipping Codex state DB on a WSL path (Windows cannot lock it): {}",
            path.display()
        );
    }
    false
}

fn push_unique_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
    if !paths.contains(&path) {
        paths.push(path);
    }
}

fn sqlite_home_from_codex_config(config_text: &str) -> Option<PathBuf> {
    let doc = config_text.parse::<DocumentMut>().ok()?;
    let raw = doc.get("sqlite_home")?.as_str()?.trim();
    if raw.is_empty() {
        return None;
    }
    Some(resolve_user_path(raw))
}

fn sqlite_home_from_env() -> Option<PathBuf> {
    let raw = std::env::var(CODEX_SQLITE_HOME_ENV).ok()?;
    let raw = raw.trim();
    if raw.is_empty() {
        return None;
    }
    Some(resolve_user_path(raw))
}

fn resolve_user_path(raw: &str) -> PathBuf {
    if raw == "~" {
        return get_home_dir();
    }
    if let Some(rest) = raw.strip_prefix("~/") {
        return get_home_dir().join(rest);
    }
    if let Some(rest) = raw.strip_prefix("~\\") {
        return get_home_dir().join(rest);
    }
    PathBuf::from(raw)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn includes_config_sqlite_home() {
        let temp = tempdir().expect("tempdir");
        let sqlite_home = temp.path().join("sqlite-home");
        // 用 TOML 字面量字符串(单引号)承载路径:Windows 路径含反斜杠,basic string(双引号)
        // 会把 `\U`/`\s` 等当作非法转义导致解析失败。
        let config_text = format!("sqlite_home = '{}'\n", sqlite_home.display());

        let paths = codex_state_db_paths(temp.path(), &config_text);

        assert_eq!(
            paths,
            vec![
                temp.path().join(CODEX_STATE_DB_FILENAME),
                sqlite_home.join(CODEX_STATE_DB_FILENAME),
            ]
        );
    }

    #[cfg(windows)]
    #[test]
    fn state_db_on_wsl_share_is_not_lockable() {
        assert!(!codex_state_db_is_lockable(Path::new(
            r"\\wsl.localhost\Ubuntu\home\user\.codex\state_5.sqlite"
        )));
        assert!(!codex_state_db_is_lockable(Path::new(
            r"\\wsl$\Ubuntu\home\user\.codex\state_5.sqlite"
        )));
        assert!(codex_state_db_is_lockable(Path::new(
            r"C:\Users\user\.codex\state_5.sqlite"
        )));
    }
}