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

86.7 KB
Raw Blame
//! 会话正文搜索索引(issue #7420)。
//!
//! 会话页的元数据搜索(标题、目录、首末消息)在前端完成;消息正文太大,
//! 放不进前端内存,这里在 Rust 侧维护一份 SQLite FTS5 索引:
//!
//! - 独立文件 `~/.cc-switch/session-index.db`,不进主库,不参与备份与云同步。它只是
//!   缓存,删掉后下次打开会话页会重建;关掉「搜索消息正文」时整个文件一起删除
//! - 每条消息一行,只收用户与 Agent 的正文(Text 块);思考、工具参数与输出、
//!   注入内容(AGENTS.md、system-reminder…)不收
//! - trigram 支持长词子串匹配;无正文、无位置信息的短词索引收录一字/两字,避免正文扫描
//! - 增量:文件使用 `(mtime, len)`,SQLite 使用会话原始行 revision;没变的会话不再解析
//!
//! FTS 行的 rowid 由「源 id × 2^24 + 消息序号」组成,重建一个会话时按 rowid 区间删除,
//! 不必扫全表。

use crate::sync_utils::MutexExt;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock, Mutex, RwLock};
use std::time::UNIX_EPOCH;

use rusqlite::{params, params_from_iter, Connection, OpenFlags, OptionalExtension};
use serde::Serialize;

use super::cache::{self, Fingerprint};
use super::content;
use super::model::{SessionBlock, SessionMessage};

const INDEX_FILE: &str = "session-index.db";
/// 索引格式版本;表结构或收录规则变了就加一,旧索引整体重建
const INDEX_VERSION: i64 = 4;
/// rowid 里留给消息序号的位数(单个会话最多 1600 万条消息,超出部分不收)
const ROW_SHIFT: u32 = 24;
const MAX_MESSAGES_PER_SOURCE: usize = 1 << ROW_SHIFT;
/// 单条消息收录的最大字符数
const MAX_ROW_CHARS: usize = 20_000;
/// 一次查询最多取的命中行数(按会话聚合前)
const MAX_HIT_ROWS: i64 = 20_000;
/// 一次查询最多返回的会话数
pub const DEFAULT_LIMIT: usize = 200;
/// 每个会话最多给几条摘录
const MAX_SNIPPETS_PER_SESSION: usize = 3;
/// trigram 能用上索引的最短查询(字符数)
const MIN_MATCH_CHARS: usize = 3;
/// 摘录里命中词前后保留的字符数
const SNIPPET_BEFORE: usize = 30;
const SNIPPET_AFTER: usize = 90;
/// 同步时每处理多少个会话上报一次进度
const PROGRESS_EVERY: usize = 25;
/// 首次建库收录了这么多会话后整理索引(合并 FTS 段、VACUUM);
/// 实测 1600 多个会话首次建库后,整理能把文件从约 170MB 缩到约 100MB
const COMPACT_AFTER_CHANGES: usize = 50;

/// 一条命中消息的摘录
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ContentSnippet {
    /// 摘录所在消息在会话里的序号(与 `load_messages` 的下标一致)
    pub message_index: usize,
    /// 命中词附近的一段正文(纯文本,空白已压缩)
    pub text: String,
    /// 摘录内的高亮范围,UTF-16 半开区间;来自完整正文,不能对裁剪后的文本重新匹配。
    pub highlights: Vec<ContentHighlight>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ContentHighlight {
    pub start: usize,
    pub end: usize,
}

/// 一个会话的命中:最相关的几条消息的摘录(第一条最相关)与命中消息数
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ContentHit {
    pub provider_id: String,
    pub source_path: String,
    pub snippets: Vec<ContentSnippet>,
    /// 命中的消息条数
    pub match_count: usize,
}

/// 索引进度;`running` 为 false 时 `processed == total` 表示索引已是最新
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexStatus {
    pub running: bool,
    pub processed: usize,
    pub total: usize,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ContentSearchResult {
    pub hits: Vec<ContentHit>,
    pub status: IndexStatus,
}

/// 存进索引的指纹:mtime(纳秒,取不到为 None)+ 长度
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StoredFingerprint {
    pub modified_ns: Option<i64>,
    pub len: i64,
}

impl From<Fingerprint> for StoredFingerprint {
    fn from(fp: Fingerprint) -> Self {
        Self {
            modified_ns: fp
                .modified
                .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
                .map(|d| d.as_nanos().min(i64::MAX as u128) as i64),
            len: fp.len.min(i64::MAX as u64) as i64,
        }
    }
}

/// 一条消息的收录文本:用户与 Agent 的 Text 块,跳过注入内容
pub fn message_rows(messages: &[SessionMessage]) -> Vec<(usize, String)> {
    messages
        .iter()
        .enumerate()
        .take(MAX_MESSAGES_PER_SOURCE)
        .filter(|(_, message)| {
            !message.injected && matches!(message.role.as_str(), "user" | "assistant")
        })
        .filter_map(|(index, message)| {
            let text = if message.blocks.is_empty() {
                message.content.clone()
            } else {
                message
                    .blocks
                    .iter()
                    .filter_map(|block| match block {
                        SessionBlock::Text { text, .. } => Some(text.as_str()),
                        _ => None,
                    })
                    .collect::<Vec<_>>()
                    .join("\n")
            };
            let text = text.trim();
            if text.is_empty() {
                return None;
            }
            Some((index, truncate_chars(text, MAX_ROW_CHARS)))
        })
        .collect()
}

fn truncate_chars(text: &str, max: usize) -> String {
    match text.char_indices().nth(max) {
        Some((cut, _)) => text[..cut].to_string(),
        None => text.to_string(),
    }
}

/// 取命中词附近的一段原文,并保留完整正文匹配产生的 UTF-16 高亮范围。
/// 裁剪上下文或压缩空白后重新查找会改变结果(例如词尾 Σ 的大小写规则)。
fn make_highlighted_snippet(text: &str, query: &str) -> (String, Vec<ContentHighlight>) {
    let hay: Vec<char> = text.chars().collect();
    let normalized = text.to_lowercase();
    let needle = query.to_lowercase();
    // 小写展开(如 İ → i + combining dot)会改变下标。按展开字符数映射回原文;
    // 默认 Unicode 小写唯一的上下文规则 Final_Sigma 不改变字符数。
    let original_positions: Vec<usize> = hay
        .iter()
        .enumerate()
        .flat_map(|(index, c)| std::iter::repeat_n(index, c.to_lowercase().count()))
        .collect();
    let mut matched = vec![false; hay.len()];
    let mut first = None;
    if !needle.is_empty() {
        let needle_chars = needle.chars().count();
        let mut previous_byte = 0;
        let mut normalized_at = 0;
        for (byte, _) in normalized.match_indices(&needle) {
            normalized_at += normalized[previous_byte..byte].chars().count();
            previous_byte = byte;
            let start = original_positions[normalized_at];
            let end = original_positions[normalized_at + needle_chars - 1] + 1;
            first.get_or_insert((start, end));
            matched[start..end].fill(true);
        }
    }
    let (start, end) = match first {
        Some((start, end)) => (
            start.saturating_sub(SNIPPET_BEFORE),
            (end + SNIPPET_AFTER).min(hay.len()),
        ),
        None => (0, (SNIPPET_BEFORE + SNIPPET_AFTER).min(hay.len())),
    };

    let mut snippet = String::new();
    let mut highlights: Vec<ContentHighlight> = Vec::new();
    let mut utf16_at = 0;
    let mut append = |c: char, highlighted: bool| {
        let end = utf16_at + c.len_utf16();
        snippet.push(c);
        if highlighted {
            if let Some(previous) = highlights.last_mut().filter(|range| range.end == utf16_at) {
                previous.end = end;
            } else {
                highlights.push(ContentHighlight {
                    start: utf16_at,
                    end,
                });
            }
        }
        utf16_at = end;
    };
    if start > 0 {
        append('…', false);
    }
    // 连续空白压成一个空格;开头的空白直接丢掉。范围跟随实际输出,
    // 一个压缩空格只要包含命中的原始空白,就保留高亮。
    let mut pending_space = false;
    let mut pending_highlight = false;
    let mut started = false;
    for index in start..end {
        let c = hay[index];
        if c.is_whitespace() {
            pending_space = started;
            pending_highlight |= matched[index];
            continue;
        }
        if pending_space {
            append(' ', pending_highlight);
        }
        pending_space = false;
        pending_highlight = false;
        append(c, matched[index]);
        started = true;
    }
    if end < hay.len() {
        append('…', false);
    }
    (snippet, highlights)
}

#[cfg(test)]
fn make_snippet(text: &str, query: &str) -> String {
    make_highlighted_snippet(text, query).0
}

/// FTS5 短语查询:整段查询按子串匹配
fn match_expression(query: &str) -> String {
    format!("\"{}\"", query.replace('"', "\"\""))
}

// Encode code points into ASCII terms so whitespace, punctuation and emoji
// retain literal substring semantics. Deduplicate postings within each message.
fn short_grams(normalized: &str) -> String {
    let mut terms = HashSet::new();
    let mut previous = None;
    for c in normalized.chars() {
        terms.insert((c, None));
        if let Some(p) = previous {
            terms.insert((p, Some(c)));
        }
        previous = Some(c);
    }
    let mut encoded = String::new();
    for (a, b) in terms {
        match b {
            Some(b) => {
                write!(encoded, "b{:x}z{:x} ", a as u32, b as u32).unwrap();
            }
            None => {
                write!(encoded, "u{:x} ", a as u32).unwrap();
            }
        }
    }
    encoded
}

fn short_query(query: &str) -> String {
    let mut chars = query.chars();
    let a = chars.next().expect("nonempty query") as u32;
    match chars.next() {
        Some(b) => format!("b{a:x}z{:x}", b as u32),
        None => format!("u{a:x}"),
    }
}

pub struct SessionIndex {
    conn: Connection,
    generation: Arc<()>,
}

impl SessionIndex {
    pub fn open(path: &Path) -> rusqlite::Result<Self> {
        let conn = Connection::open(path)?;
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "synchronous", "NORMAL")?;
        Self::init(conn)
    }

    fn open_reader(path: &Path) -> rusqlite::Result<Self> {
        let conn = Connection::open_with_flags(
            path,
            OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
        )?;
        conn.busy_timeout(std::time::Duration::from_millis(100))?;
        Ok(Self {
            conn,
            generation: Arc::new(()),
        })
    }

    #[cfg(test)]
    pub fn open_in_memory() -> rusqlite::Result<Self> {
        Self::init(Connection::open_in_memory()?)
    }

    fn init(conn: Connection) -> rusqlite::Result<Self> {
        let version: i64 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
        if version != INDEX_VERSION {
            conn.execute_batch(
                "DROP TABLE IF EXISTS message_short;
                 DROP TABLE IF EXISTS message_text;
                 DROP TABLE IF EXISTS indexed_sources;",
            )?;
        }
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS indexed_sources (
                 id INTEGER PRIMARY KEY,
                 provider_id TEXT NOT NULL,
                 source_path TEXT NOT NULL,
                 modified_ns INTEGER,
                 len INTEGER NOT NULL,
                 UNIQUE (provider_id, source_path)
             );
             CREATE VIRTUAL TABLE IF NOT EXISTS message_text
                 USING fts5(text UNINDEXED, normalized, tokenize = 'trigram case_sensitive 1');
             CREATE VIRTUAL TABLE IF NOT EXISTS message_short USING fts5(
                 grams, content='', contentless_delete=1, detail=none, tokenize='ascii');",
        )?;
        conn.pragma_update(None, "user_version", INDEX_VERSION)?;
        Ok(Self {
            conn,
            generation: Arc::new(()),
        })
    }

    pub fn stored_fingerprint(
        &self,
        provider_id: &str,
        source_path: &str,
    ) -> rusqlite::Result<Option<StoredFingerprint>> {
        self.conn
            .query_row(
                "SELECT modified_ns, len FROM indexed_sources
                 WHERE provider_id = ?1 AND source_path = ?2",
                params![provider_id, source_path],
                |row| {
                    Ok(StoredFingerprint {
                        modified_ns: row.get(0)?,
                        len: row.get(1)?,
                    })
                },
            )
            .optional()
    }

    /// 用新解析的正文替换一个会话的全部索引行
    pub fn replace_source(
        &mut self,
        provider_id: &str,
        source_path: &str,
        fingerprint: StoredFingerprint,
        rows: &[(usize, String)],
    ) -> rusqlite::Result<()> {
        let tx = self.conn.transaction()?;
        let existing: Option<i64> = tx
            .query_row(
                "SELECT id FROM indexed_sources WHERE provider_id = ?1 AND source_path = ?2",
                params![provider_id, source_path],
                |row| row.get(0),
            )
            .optional()?;
        let id = match existing {
            Some(id) => {
                delete_rows(&tx, id)?;
                tx.execute(
                    "UPDATE indexed_sources SET modified_ns = ?1, len = ?2 WHERE id = ?3",
                    params![fingerprint.modified_ns, fingerprint.len, id],
                )?;
                id
            }
            None => {
                tx.execute(
                    "INSERT INTO indexed_sources (provider_id, source_path, modified_ns, len)
                     VALUES (?1, ?2, ?3, ?4)",
                    params![
                        provider_id,
                        source_path,
                        fingerprint.modified_ns,
                        fingerprint.len
                    ],
                )?;
                tx.last_insert_rowid()
            }
        };
        {
            let mut insert = tx.prepare(
                "INSERT INTO message_text (rowid, text, normalized) VALUES (?1, ?2, ?3)",
            )?;
            let mut short_insert =
                tx.prepare("INSERT INTO message_short (rowid, grams) VALUES (?1, ?2)")?;
            for (index, text) in rows {
                let rowid = (id << ROW_SHIFT) + *index as i64;
                let normalized = text.to_lowercase();
                insert.execute(params![rowid, text, normalized])?;
                short_insert.execute(params![rowid, short_grams(&normalized)])?;
            }
        }
        tx.commit()
    }

    /// 合并 FTS 段并 VACUUM(会持锁数秒,只在大批量重建后调用)
    pub fn compact(&self) -> rusqlite::Result<()> {
        self.conn.execute(
            "INSERT INTO message_text (message_text) VALUES ('optimize')",
            [],
        )?;
        self.conn.execute(
            "INSERT INTO message_short (message_short) VALUES ('optimize')",
            [],
        )?;
        self.conn.execute_batch("VACUUM;")?;
        self.checkpoint()
    }

    /// 把 WAL 写回主库并截断,免得 `-wal` 文件留在磁盘上占空间
    pub fn checkpoint(&self) -> rusqlite::Result<()> {
        self.conn
            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
    }

    pub fn remove_source(&mut self, provider_id: &str, source_path: &str) -> rusqlite::Result<()> {
        let tx = self.conn.transaction()?;
        let existing: Option<i64> = tx
            .query_row(
                "SELECT id FROM indexed_sources WHERE provider_id = ?1 AND source_path = ?2",
                params![provider_id, source_path],
                |row| row.get(0),
            )
            .optional()?;
        if let Some(id) = existing {
            delete_rows(&tx, id)?;
            tx.execute("DELETE FROM indexed_sources WHERE id = ?1", params![id])?;
        }
        tx.commit()
    }

    /// 删掉已经不在会话列表里的源(会话在外部被删、移走);扫描不完整的提供商保留旧正文和指纹。
    pub fn retain_sources(
        &mut self,
        keep: &HashSet<(String, String)>,
        complete_providers: &HashSet<String>,
    ) -> rusqlite::Result<()> {
        let stale: Vec<(String, String)> = {
            let mut stmt = self
                .conn
                .prepare("SELECT provider_id, source_path FROM indexed_sources")?;
            let rows = stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
            rows.filter_map(Result::ok)
                .filter(|key| complete_providers.contains(&key.0) && !keep.contains(key))
                .collect()
        };
        for (provider_id, source_path) in stale {
            self.remove_source(&provider_id, &source_path)?;
        }
        Ok(())
    }

    /// 按会话聚合的正文命中。`providers` 为 None 时不按应用过滤。
    #[cfg(test)]
    pub fn search(
        &self,
        query: &str,
        providers: Option<&HashSet<String>>,
        limit: usize,
    ) -> rusqlite::Result<Vec<ContentHit>> {
        self.search_cancellable(query, providers, limit, &SearchTask::default())
    }

    fn search_cancellable(
        &self,
        query: &str,
        providers: Option<&HashSet<String>>,
        limit: usize,
        task: &SearchTask,
    ) -> rusqlite::Result<Vec<ContentHit>> {
        task.check()?;
        let query = query.trim();
        if query.is_empty() || limit == 0 {
            return Ok(Vec::new());
        }

        if providers.is_some_and(HashSet::is_empty) {
            return Ok(Vec::new());
        }
        // A read transaction keeps row IDs, source metadata and snippets on the
        // same WAL snapshot while replace_source commits on the writer.
        let snapshot = self.conn.unchecked_transaction()?;
        let normalized = query.to_lowercase();
        let short = normalized.chars().count() < MIN_MATCH_CHARS;
        let table = if short {
            "message_short"
        } else {
            "message_text"
        };
        let expression = if short {
            short_query(&normalized)
        } else {
            match_expression(&normalized)
        };
        let mut arguments: Vec<rusqlite::types::Value> =
            vec![expression.into(), MAX_HIT_ROWS.into()];
        let filter = if let Some(providers) = providers {
            arguments.extend(providers.iter().cloned().map(Into::into));
            format!(
                "AND s.provider_id IN ({})",
                (3..3 + providers.len())
                    .map(|i| format!("?{i}"))
                    .collect::<Vec<_>>()
                    .join(",")
            )
        } else {
            String::new()
        };
        let ordering = if short { "m.rowid DESC" } else { "m.rank" };
        let sql = format!(
            "SELECT m.rowid FROM {table} m JOIN indexed_sources s ON s.id = (m.rowid >> {ROW_SHIFT})
             WHERE {table} MATCH ?1 {filter} ORDER BY {ordering} LIMIT ?2"
        );
        let rowids = {
            let mut stmt = snapshot.prepare(&sql)?;
            let rows = stmt.query_map(params_from_iter(arguments.iter()), |row| {
                row.get::<_, i64>(0)
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        if rowids.is_empty() {
            return Ok(Vec::new());
        }

        // 按会话聚合:保留最先出现(最相关)的几行,累计命中条数
        let mut order: Vec<i64> = Vec::new();
        let mut best: HashMap<i64, (Vec<i64>, usize)> = HashMap::new();
        for rowid in rowids {
            task.check()?;
            let source_id = rowid >> ROW_SHIFT;
            let (top, count) = best.entry(source_id).or_insert_with(|| {
                order.push(source_id);
                (Vec::new(), 0)
            });
            *count += 1;
            if top.len() < MAX_SNIPPETS_PER_SESSION {
                top.push(rowid);
            }
        }

        order.truncate(limit);
        let selected: Vec<i64> = order
            .iter()
            .flat_map(|id| best[id].0.iter().copied())
            .collect();
        let mut snippets_by_row = HashMap::with_capacity(selected.len());
        let mut sources = HashMap::with_capacity(order.len());
        // DEFAULT_LIMIT needs <=600 parameters. Chunk larger internal callers
        // too, so this also works with SQLite's conservative variable limit.
        for chunk in selected.chunks(900) {
            task.check()?;
            let sql = format!(
                "SELECT m.rowid, m.text, s.id, s.provider_id, s.source_path
                 FROM message_text m JOIN indexed_sources s ON s.id = (m.rowid >> {ROW_SHIFT})
                 WHERE m.rowid IN ({})",
                vec!["?"; chunk.len()].join(",")
            );
            let mut stmt = snapshot.prepare(&sql)?;
            let mut rows = stmt.query(params_from_iter(chunk))?;
            loop {
                task.check()?;
                let Some(row) = rows.next()? else { break };
                let rowid: i64 = row.get(0)?;
                // Build the small snippet before advancing the batch cursor;
                // do not retain up to 600 complete 20,000-character messages.
                let raw: String = row.get(1)?;
                task.check()?;
                let (text, highlights) = make_highlighted_snippet(&raw, query);
                snippets_by_row.insert(
                    rowid,
                    ContentSnippet {
                        message_index: (rowid & ((1 << ROW_SHIFT) - 1)) as usize,
                        text,
                        highlights,
                    },
                );
                if let std::collections::hash_map::Entry::Vacant(entry) =
                    sources.entry(row.get::<_, i64>(2)?)
                {
                    entry.insert((row.get::<_, String>(3)?, row.get::<_, String>(4)?));
                }
            }
        }
        let mut hits = Vec::new();
        for source_id in order {
            let (top, match_count) = &best[&source_id];
            let (provider_id, source_path) = sources
                .get(&source_id)
                .ok_or(rusqlite::Error::QueryReturnedNoRows)?;
            let snippets = top
                .iter()
                .map(|rowid| {
                    snippets_by_row
                        .remove(rowid)
                        .ok_or(rusqlite::Error::QueryReturnedNoRows)
                })
                .collect::<rusqlite::Result<_>>()?;
            hits.push(ContentHit {
                provider_id: provider_id.clone(),
                source_path: source_path.clone(),
                snippets,
                match_count: *match_count,
            });
        }
        Ok(hits)
    }
}

fn delete_rows(conn: &Connection, source_id: i64) -> rusqlite::Result<()> {
    conn.execute(
        "DELETE FROM message_short WHERE rowid >= ?1 AND rowid < ?2",
        params![source_id << ROW_SHIFT, (source_id + 1) << ROW_SHIFT],
    )?;
    conn.execute(
        "DELETE FROM message_text WHERE rowid >= ?1 AND rowid < ?2",
        params![source_id << ROW_SHIFT, (source_id + 1) << ROW_SHIFT],
    )?;
    Ok(())
}

// ── 全局索引与后台同步 ───────────────────────────────────────────────

// Ordinary readers/writers share this guard. Initialization and deletion take
// it exclusively, so Windows can close readers before unlinking the cache and its WAL files.
static INDEX_LIFETIME: RwLock<()> = RwLock::new(());

const SEARCH_CANCELLED: &str = "Session content search cancelled";
const SEARCH_PROGRESS_OPS: i32 = 1_000;
const MAX_EARLY_CANCELLATIONS: usize = 128;

#[derive(Default)]
struct SearchTask {
    cancelled: Arc<AtomicBool>,
}

impl SearchTask {
    fn cancel(&self) {
        self.cancelled.store(true, Ordering::Relaxed);
    }

    fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::Relaxed)
    }

    fn check(&self) -> rusqlite::Result<()> {
        if self.is_cancelled() {
            return Err(rusqlite::Error::SqliteFailure(
                rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_INTERRUPT),
                None,
            ));
        }
        Ok(())
    }

    fn run<T>(
        &self,
        conn: &Connection,
        f: impl FnOnce() -> rusqlite::Result<T>,
    ) -> rusqlite::Result<Option<T>> {
        let cancelled = Arc::clone(&self.cancelled);
        conn.progress_handler(
            SEARCH_PROGRESS_OPS,
            Some(move || cancelled.load(Ordering::Relaxed)),
        );
        // Keep the callback scoped to this search on every exit, including
        // errors and unwinding, before the reader connection is released.
        let _progress = SearchProgress(conn);
        let result = self.check().and_then(|()| f()).and_then(|value| {
            self.check()?;
            Ok(value)
        });
        match result {
            Err(error)
                if self.is_cancelled()
                    && error.sqlite_error_code()
                        == Some(rusqlite::ErrorCode::OperationInterrupted) =>
            {
                Ok(None)
            }
            // A concurrent cancellation must never hide an open/SQL error (#9512).
            other => other.map(Some),
        }
    }
}

struct SearchProgress<'a>(&'a Connection);

impl Drop for SearchProgress<'_> {
    fn drop(&mut self) {
        self.0.progress_handler(0, None::<fn() -> bool>);
    }
}

#[derive(Default)]
struct SearchRequests {
    active: HashMap<String, Arc<SearchTask>>,
    // Cancellation can overtake the async search command's first poll.
    // Late cancellations use the same bounded queue; request IDs are unique.
    cancelled: VecDeque<String>,
}

impl SearchRequests {
    fn begin(&mut self, id: &str) -> Arc<SearchTask> {
        let task = Arc::new(SearchTask::default());
        if let Some(at) = self.cancelled.iter().position(|pending| pending == id) {
            self.cancelled.remove(at);
            task.cancel();
        }
        if let Some(previous) = self.active.insert(id.to_string(), Arc::clone(&task)) {
            previous.cancel();
        }
        task
    }

    fn cancel(&mut self, id: &str) {
        if let Some(task) = self.active.get(id) {
            task.cancel();
        } else if !self.cancelled.iter().any(|pending| pending == id) {
            if self.cancelled.len() == MAX_EARLY_CANCELLATIONS {
                self.cancelled.pop_front();
            }
            self.cancelled.push_back(id.to_string());
        }
    }
}

static SEARCH_REQUESTS: LazyLock<Mutex<SearchRequests>> =
    LazyLock::new(|| Mutex::new(SearchRequests::default()));

pub struct SearchRequest {
    id: String,
    task: Arc<SearchTask>,
}

impl Drop for SearchRequest {
    fn drop(&mut self) {
        let mut requests = SEARCH_REQUESTS.lock_recover();
        if requests
            .active
            .get(&self.id)
            .is_some_and(|task| Arc::ptr_eq(task, &self.task))
        {
            requests.active.remove(&self.id);
        }
    }
}

pub fn begin_search(id: String) -> SearchRequest {
    let task = SEARCH_REQUESTS.lock_recover().begin(&id);
    SearchRequest { id, task }
}

pub fn cancel_search(id: &str) {
    SEARCH_REQUESTS.lock_recover().cancel(id);
}

static INDEX: LazyLock<Mutex<Option<SessionIndex>>> = LazyLock::new(|| Mutex::new(None));
static STATUS: LazyLock<Mutex<IndexStatus>> = LazyLock::new(|| Mutex::new(IndexStatus::default()));
static RUNNING: AtomicBool = AtomicBool::new(false);
static RERUN: AtomicBool = AtomicBool::new(false);

/// [`with_index_in`] 在持锁后再次检查开关时返回的哨兵:功能被关掉不是失败。
const DISABLED: &str = "Session content search is disabled";

pub fn index_path() -> PathBuf {
    crate::config::get_app_config_dir().join(INDEX_FILE)
}

pub fn enabled() -> bool {
    crate::settings::get_settings().session_content_search_enabled
}

pub fn status() -> IndexStatus {
    *STATUS.lock_recover()
}

/// 打开(必要时创建)索引后执行 `f`;功能关闭时不碰磁盘
fn with_index<T>(f: impl FnOnce(&mut SessionIndex) -> rusqlite::Result<T>) -> Result<T, String> {
    with_index_in(&INDEX, &index_path(), enabled, f)
}

/// [`with_index`] 的实现,索引槽、路径、开关可替换(测试用)。
///
/// 开关必须在持有锁之后检查:关闭功能时 [`clear`] 在同一把锁里删除索引文件,
/// 锁外检查的话,已经通过检查、正在等锁的后台写入会在清理之后把文件重新建出来
fn with_index_in<T>(
    slot: &Mutex<Option<SessionIndex>>,
    path: &Path,
    is_enabled: impl Fn() -> bool,
    f: impl FnOnce(&mut SessionIndex) -> rusqlite::Result<T>,
) -> Result<T, String> {
    let mut shared = Some(
        INDEX_LIFETIME
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner),
    );
    let exclusive = if slot.lock_recover().is_none() {
        drop(shared.take());
        // Initial schema setup may replace the file. Ordinary writes and
        // compaction keep sharing the lifetime guard with independent readers.
        Some(
            INDEX_LIFETIME
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        )
    } else {
        None
    };
    let mut guard = slot.lock_recover();
    if !is_enabled() {
        return Err(DISABLED.to_string());
    }
    if guard.is_none() {
        if let Some(dir) = path.parent() {
            let _ = fs::create_dir_all(dir);
        }
        let open =
            || SessionIndex::open(path).map_err(|e| format!("Failed to open session index: {e}"));
        let index = open().or_else(|first| {
            // 索引只是缓存:打不开(损坏、格式不认识)就删掉重建
            log::warn!("会话正文索引无法打开,重建: {first}");
            remove_index_files(path).map_err(|e| e.to_string())?;
            open()
        });
        *guard = Some(index?);
    }
    let index = guard.as_mut().expect("index opened above");
    let generation = Arc::clone(&index.generation);
    let result = f(index);
    drop(guard);
    drop(shared);
    drop(exclusive);
    if result.as_ref().err().is_some_and(is_corruption) {
        discard_corrupt_index(slot, path, Some(generation));
    }
    result.map_err(|error| format!("Session index error: {error}"))
}

fn is_corruption(error: &rusqlite::Error) -> bool {
    matches!(
        error.sqlite_error_code(),
        Some(rusqlite::ErrorCode::DatabaseCorrupt | rusqlite::ErrorCode::NotADatabase)
    )
}

fn discard_corrupt_index(
    slot: &Mutex<Option<SessionIndex>>,
    path: &Path,
    generation: Option<Arc<()>>,
) {
    // Both readers and writers must close before unlinking the cache or its WAL.
    let _lifetime = INDEX_LIFETIME
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let mut guard = slot.lock_recover();
    let same_generation = match (guard.as_ref(), generation.as_ref()) {
        (Some(index), Some(generation)) => Arc::ptr_eq(&index.generation, generation),
        (None, None) => true,
        _ => false,
    };
    // Another failed query may already have removed and rebuilt this cache
    // while we were waiting for the exclusive guard.
    if same_generation {
        *guard = None;
        if let Err(cleanup) = remove_index_files(path) {
            log::warn!("清理损坏的会话正文索引失败: {cleanup}");
        }
    }
}

fn remove_index_files(path: &Path) -> std::io::Result<()> {
    remove_index_files_with(path, |file| fs::remove_file(file))
}

fn remove_index_files_with(
    path: &Path,
    mut remove: impl FnMut(&Path) -> std::io::Result<()>,
) -> std::io::Result<()> {
    let mut first_error = None;
    for suffix in ["", "-wal", "-shm"] {
        let mut file = path.as_os_str().to_owned();
        file.push(suffix);
        if let Err(error) = remove(Path::new(&file)) {
            // 文件不存在说明已经清理;其他失败要上报,但仍尝试清理剩余文件。
            if error.kind() != std::io::ErrorKind::NotFound && first_error.is_none() {
                first_error = Some(error);
            }
        }
    }
    match first_error {
        Some(error) => Err(error),
        None => Ok(()),
    }
}

/// 删除整个索引文件(关闭功能时调用)
pub fn clear() -> Result<(), String> {
    for task in SEARCH_REQUESTS.lock_recover().active.values() {
        task.cancel();
    }
    let _lifetime = INDEX_LIFETIME
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    clear_in(&INDEX, &STATUS, &index_path())
}

fn clear_in(
    slot: &Mutex<Option<SessionIndex>>,
    status: &Mutex<IndexStatus>,
    path: &Path,
) -> Result<(), String> {
    let mut guard = slot.lock_recover();
    *guard = None;
    let result = remove_index_files(path);
    *status.lock_recover() = IndexStatus::default();
    result.map_err(|e| e.to_string())
}

/// 会话删除后同步移除索引行;索引没开或功能关闭时什么也不做
pub fn forget_source(provider_id: &str, source_path: &str) {
    if !enabled() {
        return;
    }
    if let Err(e) = with_index(|index| index.remove_source(provider_id, source_path)) {
        log::warn!("移除会话正文索引失败: {e}");
    }
}

/// 在消息正文里搜索。索引打不开或查询失败时上报错误,不返回空结果:
/// 空结果会被界面当成「正文里没有这个词」,而索引只是缓存,坏了是可以修的。
pub fn search(
    query: &str,
    providers: Option<Vec<String>>,
    limit: usize,
    request: SearchRequest,
) -> Result<ContentSearchResult, String> {
    search_in_with_task(
        &INDEX,
        &index_path(),
        enabled,
        query,
        providers,
        limit,
        &request.task,
    )
}

/// [`search`] 的实现,索引槽、路径、开关可替换(测试用)。
#[cfg(test)]
fn search_in(
    slot: &Mutex<Option<SessionIndex>>,
    path: &Path,
    is_enabled: impl Fn() -> bool,
    query: &str,
    providers: Option<Vec<String>>,
    limit: usize,
) -> Result<ContentSearchResult, String> {
    search_in_with_task(
        slot,
        path,
        is_enabled,
        query,
        providers,
        limit,
        &SearchTask::default(),
    )
}

fn search_in_with_task(
    slot: &Mutex<Option<SessionIndex>>,
    path: &Path,
    is_enabled: impl Fn() -> bool,
    query: &str,
    providers: Option<Vec<String>>,
    limit: usize,
    task: &SearchTask,
) -> Result<ContentSearchResult, String> {
    if task.is_cancelled() {
        return Err(SEARCH_CANCELLED.to_string());
    }
    let mut lifetime = INDEX_LIFETIME
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let status = status();
    let empty = || ContentSearchResult {
        hits: Vec::new(),
        status,
    };
    if !is_enabled() || query.trim().is_empty() {
        return Ok(empty());
    }
    // Initialize or rebuild before opening a reader, but never wait for a
    // running writer just to check whether the index is already open.
    let needs_open = match slot.try_lock() {
        Ok(guard) => guard.is_none(),
        Err(std::sync::TryLockError::Poisoned(error)) => error.into_inner().is_none(),
        Err(std::sync::TryLockError::WouldBlock) => false,
    };
    if needs_open || !path.exists() {
        drop(lifetime);
        if let Err(error) = with_index_in(slot, path, &is_enabled, |_| Ok(())) {
            if error == DISABLED {
                return Ok(empty());
            }
            log::warn!("会话正文搜索失败: {error}");
            return Err(error);
        }
        lifetime = INDEX_LIFETIME
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if !is_enabled() {
            return Ok(empty());
        }
    }
    if task.is_cancelled() {
        return Err(SEARCH_CANCELLED.to_string());
    }
    let providers: Option<HashSet<String>> = providers.map(|list| list.into_iter().collect());
    let result = SessionIndex::open_reader(path).and_then(|index| {
        task.run(&index.conn, || {
            index.search_cancellable(query, providers.as_ref(), limit.min(DEFAULT_LIMIT), task)
        })
    });
    if result.as_ref().err().is_some_and(is_corruption) {
        let generation = slot
            .lock_recover()
            .as_ref()
            .map(|index| Arc::clone(&index.generation));
        drop(lifetime);
        discard_corrupt_index(slot, path, generation);
    }
    let hits = result
        .map_err(|error| {
            let error = format!("Session index error: {error}");
            log::warn!("会话正文搜索失败: {error}");
            error
        })?
        .ok_or_else(|| SEARCH_CANCELLED.to_string())?;
    Ok(ContentSearchResult { hits, status })
}

/// 在后台线程里把索引同步到当前的会话列表;已经在跑时只记一次「跑完再来一遍」。
/// `on_status` 在开始、每处理一批、结束时各调用一次。
pub fn start_sync<F>(on_status: F) -> IndexStatus
where
    F: Fn(IndexStatus) + Send + 'static,
{
    if !enabled() {
        return status();
    }
    if RUNNING.swap(true, Ordering::SeqCst) {
        RERUN.store(true, Ordering::SeqCst);
        return status();
    }
    std::thread::spawn(move || loop {
        RERUN.store(false, Ordering::SeqCst);
        run_sync(&on_status);
        if RERUN.load(Ordering::SeqCst) {
            continue;
        }
        RUNNING.store(false, Ordering::SeqCst);
        // 收尾的这一刻又有人请求同步:自己接着跑,别把请求丢掉
        if RERUN.load(Ordering::SeqCst) && !RUNNING.swap(true, Ordering::SeqCst) {
            continue;
        }
        break;
    });
    status()
}

fn set_status(status: IndexStatus, on_status: &dyn Fn(IndexStatus)) {
    *STATUS.lock_recover() = status;
    on_status(status);
}

fn run_sync(on_status: &dyn Fn(IndexStatus)) {
    let mut seen = HashSet::new();
    let scan = super::scan_for_index();
    let sources: Vec<(String, String)> = scan
        .sessions
        .into_iter()
        .filter_map(|session| Some((session.provider_id, session.source_path?)))
        .filter(|key| seen.insert(key.clone()))
        .collect();
    let total = sources.len();
    let mut status = IndexStatus {
        running: true,
        processed: 0,
        total,
    };
    set_status(status, on_status);

    let initially_empty = with_index(|index| {
        index.conn.query_row(
            "SELECT NOT EXISTS(SELECT 1 FROM indexed_sources)",
            [],
            |row| row.get(0),
        )
    })
    .unwrap_or(false);
    if let Err(e) = with_index(|index| index.retain_sources(&seen, &scan.complete_providers)) {
        log::warn!("清理会话正文索引失败: {e}");
    }

    let mut changed = 0;
    let mut revisions = super::search_revision::SqliteRevisions::default();
    for (provider_id, source_path) in &sources {
        if !enabled() {
            break;
        }
        if index_source(provider_id, source_path, &mut revisions) {
            changed += 1;
        }
        status.processed += 1;
        if status.processed % PROGRESS_EVERY == 0 {
            set_status(status, on_status);
        }
    }

    let tidy = if should_compact(initially_empty, changed) {
        with_index(|index| index.compact())
    } else {
        with_index(|index| index.checkpoint())
    };
    if let Err(e) = tidy {
        log::warn!("整理会话正文索引失败: {e}");
    }

    status.running = false;
    set_status(status, on_status);
}

/// 仅首次批量建库后压缩,常规增量同步不触发全库 VACUUM。
fn should_compact(initially_empty: bool, changed: usize) -> bool {
    initially_empty && changed >= COMPACT_AFTER_CHANGES
}

/// 指纹没变就跳过;变了(或从没收录过)就重新解析并替换。返回是否重建过
fn index_source(
    provider_id: &str,
    source_path: &str,
    revisions: &mut super::search_revision::SqliteRevisions,
) -> bool {
    let Ok(source) = content::validate_source(provider_id, source_path) else {
        return false;
    };
    let fingerprint = match &source.location {
        content::SourceLocation::Sqlite { .. } => revisions.fingerprint(&source),
        _ => cache::source_fingerprint(&source)
            .map(StoredFingerprint::from)
            .map_err(|e| e.to_string()),
    };
    let Ok(fingerprint) = fingerprint else {
        return false;
    };
    let stored = with_index(|index| index.stored_fingerprint(provider_id, source_path))
        .ok()
        .flatten();
    index_changed_source(
        stored,
        fingerprint,
        || super::load_messages(&source.provider_id, &source.load_path()),
        |rows| {
            with_index(|index| index.replace_source(provider_id, source_path, fingerprint, rows))
        },
    )
}

fn index_changed_source(
    stored: Option<StoredFingerprint>,
    fingerprint: StoredFingerprint,
    load: impl FnOnce() -> Result<Vec<SessionMessage>, String>,
    replace: impl FnOnce(&[(usize, String)]) -> Result<(), String>,
) -> bool {
    if stored == Some(fingerprint) {
        return false;
    }
    // 读取失败可能只是暂时的:保留旧索引和指纹,让下次同步重试。
    let messages = match load() {
        Ok(messages) => messages,
        Err(e) => {
            log::warn!("读取会话正文索引源失败: {e}");
            return false;
        }
    };
    let rows = message_rows(&messages);
    match replace(&rows) {
        Ok(()) => true,
        Err(e) => {
            log::warn!("写入会话正文索引失败: {e}");
            false
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session_manager::model::EventKind;

    mod cancellation;

    fn fp(len: i64) -> StoredFingerprint {
        StoredFingerprint {
            modified_ns: Some(1),
            len,
        }
    }

    fn rows(texts: &[&str]) -> Vec<(usize, String)> {
        texts
            .iter()
            .enumerate()
            .map(|(i, text)| (i, text.to_string()))
            .collect()
    }

    fn sync_source(
        index: &mut SessionIndex,
        fingerprint: StoredFingerprint,
        load: impl FnOnce() -> Result<Vec<SessionMessage>, String>,
    ) -> bool {
        let stored = index.stored_fingerprint("codex", "/a.jsonl").unwrap();
        index_changed_source(stored, fingerprint, load, |rows| {
            index
                .replace_source("codex", "/a.jsonl", fingerprint, rows)
                .map_err(|e| e.to_string())
        })
    }

    #[test]
    fn sqlite_sync_only_rebuilds_the_changed_session() {
        if crate::config::sqlite_unsupported_in_temp_dir() {
            return;
        }
        for (provider, table) in [
            ("opencode", "part"),
            ("hermes", "messages"),
            ("mcode", "local_runtime_messages"),
        ] {
            let dir = tempfile::tempdir().unwrap();
            let db = dir.path().join("sessions.db");
            let conn = Connection::open(&db).unwrap();
            conn.execute_batch(&format!(
                "PRAGMA journal_mode=WAL;
                 CREATE TABLE {table}(session_id TEXT, content TEXT, timestamp INTEGER);"
            ))
            .unwrap();
            for i in 0..50 {
                conn.execute(
                    &format!("INSERT INTO {table} VALUES (?1, 'original', NULL)"),
                    [i.to_string()],
                )
                .unwrap();
            }
            let mut index = SessionIndex::open_in_memory().unwrap();
            for (pass, expected) in [50, 0, 1, 0].into_iter().enumerate() {
                if pass == 2 {
                    // The source DB/WAL fingerprint changes for all 50 sessions,
                    // but only one session changed; no activity timestamp changes.
                    conn.execute(
                        &format!("UPDATE {table} SET content='edited' WHERE session_id='7'"),
                        [],
                    )
                    .unwrap();
                }
                let mut revisions = super::super::search_revision::SqliteRevisions::default();
                let mut loads = 0;
                let mut changed = 0;
                for i in 0..50 {
                    let id = i.to_string();
                    let source = content::ValidatedSource {
                        provider_id: provider.into(),
                        raw: id.clone(),
                        location: content::SourceLocation::Sqlite {
                            db: db.clone(),
                            session_id: id.clone(),
                        },
                    };
                    let fingerprint = revisions.fingerprint(&source).unwrap();
                    let stored = index.stored_fingerprint(provider, &id).unwrap();
                    changed += usize::from(index_changed_source(
                        stored,
                        fingerprint,
                        || {
                            loads += 1;
                            let body: String = conn
                                .query_row(
                                    &format!("SELECT content FROM {table} WHERE session_id=?1"),
                                    [&id],
                                    |row| row.get(0),
                                )
                                .unwrap();
                            Ok(vec![SessionMessage::from_blocks(
                                "user",
                                None,
                                vec![SessionBlock::text(body)],
                            )])
                        },
                        |rows| {
                            index
                                .replace_source(provider, &id, fingerprint, rows)
                                .map_err(|e| e.to_string())
                        },
                    ));
                }
                assert_eq!(
                    (loads, changed),
                    (expected, expected),
                    "{provider} pass {pass}"
                );
                assert_eq!(
                    revisions.opened_databases(),
                    usize::from(pass == 0 || pass == 2),
                    "unchanged databases must not be opened or rehashed"
                );
                assert_eq!(should_compact(pass == 0, changed), pass == 0);
            }
            assert_eq!(index.search("edited", None, 10).unwrap().len(), 1);
        }
        assert!(!should_compact(false, 50));
        assert!(!should_compact(true, 49));
    }

    fn retain_scanned_claude(index: &mut SessionIndex, root: &Path) -> (usize, bool) {
        let mut status = super::super::providers::utils::ScanStatus::default();
        let sessions = super::super::providers::claude::scan_sessions_in_root(root, &mut status);
        let count = sessions.len();
        let seen = sessions
            .into_iter()
            .filter_map(|session| Some((session.provider_id, session.source_path?)))
            .collect();
        let complete = if status.incomplete {
            HashSet::new()
        } else {
            HashSet::from(["claude".into()])
        };
        index.retain_sources(&seen, &complete).unwrap();
        (count, !status.incomplete)
    }

    #[test]
    #[cfg(unix)]
    fn unreadable_session_directory_preserves_index_until_successful_scan() {
        use std::os::unix::fs::PermissionsExt;

        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("projects");
        std::fs::create_dir(&root).unwrap();
        let path = root.join("session.jsonl");
        std::fs::write(&path, r#"{"sessionId":"session","type":"user","message":{"role":"user","content":"recovered body"}}"#).unwrap();
        let source = path.to_string_lossy().into_owned();
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source("claude", &source, fp(1), &rows(&["cached body"]))
            .unwrap();

        let permissions = std::fs::metadata(&root).unwrap().permissions();
        std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o0)).unwrap();
        let read_error = std::fs::read_dir(&root).err();
        // Both the list refresh and the background sync encounter the outage.
        let list = super::super::providers::claude::scan_sessions_in_root(
            &root,
            &mut super::super::providers::utils::ScanStatus::default(),
        );
        let failed_scan = retain_scanned_claude(&mut index, &root);
        std::fs::set_permissions(&root, permissions).unwrap();
        assert!(
            read_error.is_some(),
            "regression requires an unprivileged test process"
        );
        assert!(list.is_empty());
        assert_eq!(failed_scan, (0, false));
        assert_eq!(index.search("cached body", None, 10).unwrap().len(), 1);
        assert_eq!(
            index.stored_fingerprint("claude", &source).unwrap(),
            Some(fp(1))
        );
        assert!(path.exists(), "raw session files must never be removed");

        // A fresh scan recovers normally, without losing the old fingerprint first.
        assert_eq!(retain_scanned_claude(&mut index, &root), (1, true));
        let stored = index.stored_fingerprint("claude", &source).unwrap();
        assert!(!index_changed_source(
            stored,
            fp(1),
            || panic!("unchanged source must not be reparsed"),
            |_| panic!("unchanged source must not be rewritten")
        ));
        assert!(index_changed_source(
            stored,
            fp(2),
            || super::super::providers::claude::load_messages(&path),
            |rows| index
                .replace_source("claude", &source, fp(2), rows)
                .map_err(|error| error.to_string())
        ));
        assert_eq!(index.search("recovered body", None, 10).unwrap().len(), 1);

        // A real external deletion, including deletion of the final session, still prunes.
        std::fs::remove_file(&path).unwrap();
        assert_eq!(retain_scanned_claude(&mut index, &root), (0, true));
        assert!(index.search("body", None, 10).unwrap().is_empty());
        assert_eq!(index.stored_fingerprint("claude", &source).unwrap(), None);
    }

    #[test]
    fn incomplete_provider_does_not_block_successful_empty_provider_cleanup() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source(
                "claude",
                "/unreadable.jsonl",
                fp(1),
                &rows(&["keep this body"]),
            )
            .unwrap();
        index
            .replace_source("claude", "/visible.jsonl", fp(2), &rows(&["visible body"]))
            .unwrap();
        index
            .replace_source("codex", "/deleted.jsonl", fp(3), &rows(&["deleted body"]))
            .unwrap();
        let seen = HashSet::from([("claude".into(), "/visible.jsonl".into())]);
        index
            .retain_sources(&seen, &HashSet::from(["codex".into()]))
            .unwrap();
        assert_eq!(index.search("body", None, 10).unwrap().len(), 2);
        assert_eq!(
            index
                .stored_fingerprint("claude", "/unreadable.jsonl")
                .unwrap(),
            Some(fp(1))
        );
        assert_eq!(
            index.stored_fingerprint("codex", "/deleted.jsonl").unwrap(),
            None
        );
        index
            .retain_sources(&seen, &HashSet::from(["claude".into(), "codex".into()]))
            .unwrap();
        assert_eq!(index.search("body", None, 10).unwrap().len(), 1);
        assert_eq!(
            index
                .stored_fingerprint("claude", "/unreadable.jsonl")
                .unwrap(),
            None
        );
    }

    #[test]
    fn invalid_directory_is_not_a_successful_empty_scan() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("projects");
        std::fs::write(&root, "not a directory").unwrap();
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source("claude", "/old.jsonl", fp(1), &rows(&["cached body"]))
            .unwrap();
        assert_eq!(retain_scanned_claude(&mut index, &root), (0, false));
        assert_eq!(
            index.stored_fingerprint("claude", "/old.jsonl").unwrap(),
            Some(fp(1))
        );
        std::fs::remove_file(&root).unwrap();
        assert_eq!(retain_scanned_claude(&mut index, &root), (0, true));
        assert_eq!(
            index.stored_fingerprint("claude", "/old.jsonl").unwrap(),
            None
        );
    }

    #[test]
    fn failed_initial_load_retries_unchanged_source() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        let mut attempts = 0;
        let mut load = || {
            attempts += 1;
            if attempts == 1 {
                Err("temporary read failure".to_string())
            } else {
                Ok(vec![SessionMessage::from_blocks(
                    "user",
                    None,
                    vec![SessionBlock::text("retry searchable content")],
                )])
            }
        };

        let first = sync_source(&mut index, fp(1), &mut load);
        let second = sync_source(&mut index, fp(1), &mut load);
        assert_eq!(attempts, 2, "failed loads must not cache the fingerprint");
        assert!(!first);
        assert!(second);
        assert_eq!(index.search("searchable", None, 10).unwrap().len(), 1);
        assert!(!sync_source(&mut index, fp(1), || {
            panic!("successfully indexed sources should still be skipped")
        }));
    }

    #[test]
    fn failed_refresh_preserves_previous_rows_and_fingerprint() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source("codex", "/a.jsonl", fp(1), &rows(&["previous content"]))
            .unwrap();

        let changed = sync_source(&mut index, fp(2), || Err("temporary read failure".into()));
        assert_eq!(index.search("previous", None, 10).unwrap().len(), 1);
        assert_eq!(
            index.stored_fingerprint("codex", "/a.jsonl").unwrap(),
            Some(fp(1))
        );
        assert!(!changed);

        // A successful empty source must still replace the old rows and fingerprint.
        assert!(sync_source(&mut index, fp(2), || Ok(Vec::new())));
        assert!(index.search("previous", None, 10).unwrap().is_empty());
        assert_eq!(
            index.stored_fingerprint("codex", "/a.jsonl").unwrap(),
            Some(fp(2))
        );
    }

    #[test]
    fn message_rows_keeps_user_and_assistant_text_only() {
        let mut injected =
            SessionMessage::from_blocks("user", None, vec![SessionBlock::text("AGENTS.md 内容")]);
        injected.injected = true;
        let messages = vec![
            SessionMessage::from_blocks("user", None, vec![SessionBlock::text("问一下跑马灯")]),
            injected,
            SessionMessage::from_blocks(
                "assistant",
                None,
                vec![
                    SessionBlock::Thinking {
                        text: "内部思考".into(),
                        summary: None,
                        redacted: false,
                        duration_ms: None,
                        full: None,
                    },
                    SessionBlock::text("第一段"),
                    SessionBlock::event(EventKind::Info, Some("事件".into()), None),
                    SessionBlock::text("第二段"),
                ],
            ),
            SessionMessage {
                role: "tool".into(),
                content: "工具输出".into(),
                ..SessionMessage::default()
            },
            SessionMessage {
                role: "assistant".into(),
                content: "旧格式正文".into(),
                ..SessionMessage::default()
            },
            SessionMessage::from_blocks("user", None, vec![SessionBlock::text("   ")]),
        ];

        assert_eq!(
            message_rows(&messages),
            vec![
                (0, "问一下跑马灯".to_string()),
                (2, "第一段\n第二段".to_string()),
                (4, "旧格式正文".to_string()),
            ]
        );
    }

    #[test]
    fn message_rows_truncates_long_text() {
        let long = "字".repeat(MAX_ROW_CHARS + 10);
        let messages = vec![SessionMessage::from_blocks(
            "user",
            None,
            vec![SessionBlock::text(long)],
        )];
        assert_eq!(message_rows(&messages)[0].1.chars().count(), MAX_ROW_CHARS);
    }

    #[test]
    fn unicode_search_uses_whole_string_lowercase_for_every_query_length() {
        for (text, query, expected) in [
            ("ςabc", "σab", false),
            ("ſabc", "sab", false),
            ("ΟΣ", "ος", true),
            ("ΟΣΑ", "οσα", true),
            ("ΟΣΑ", "ος", false),
            ("İabc", "i\u{307}a", true),
            ("İabc", "ia", false),
            ("İabc", "i", true),
            ("😀中文跑马灯", "中文", true),
            ("😀中文跑马灯", "跑马灯", true),
            ("a%_b", "%_", true),
            ("plain", "%_", false),
        ] {
            let mut index = SessionIndex::open_in_memory().unwrap();
            index
                .replace_source("codex", "/synthetic", fp(1), &rows(&[text]))
                .unwrap();
            assert_eq!(
                !index.search(query, None, 10).unwrap().is_empty(),
                expected,
                "text={text:?}, query={query:?}"
            );
        }
    }

    #[test]
    fn unicode_nonmatches_do_not_exhaust_the_hit_budget() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        let mut messages: Vec<(usize, String)> = (0..MAX_HIT_ROWS as usize)
            .map(|i| (i, "ſabc".into()))
            .collect();
        messages.push((MAX_HIT_ROWS as usize, "sab target".into()));
        index
            .replace_source("codex", "/synthetic", fp(1), &messages)
            .unwrap();
        for query in ["sab", "sa"] {
            let hits = index.search(query, None, 10).unwrap();
            assert_eq!(hits.len(), 1);
            assert_eq!(hits[0].match_count, 1);
            assert_eq!(hits[0].snippets[0].message_index, MAX_HIT_ROWS as usize);
        }
    }

    #[test]
    fn unicode_index_rebuilds_the_previous_tokenizer_schema() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE VIRTUAL TABLE message_text USING fts5(text, tokenize='trigram');
            INSERT INTO message_text(text) VALUES ('stale'); PRAGMA user_version=1;",
        )
        .unwrap();
        let mut index = SessionIndex::init(conn).unwrap();
        assert_eq!(
            index
                .conn
                .query_row("SELECT count(*) FROM message_text", [], |r| r
                    .get::<_, i64>(0))
                .unwrap(),
            0
        );
        index
            .replace_source("codex", "/synthetic", fp(1), &rows(&["ΟΣ"]))
            .unwrap();
        assert_eq!(index.search("ος", None, 10).unwrap().len(), 1);
    }

    #[test]
    fn unicode_snippet_highlights_preserve_full_source_case_context() {
        let text = format!("A{}Σ", "\u{301}".repeat(100));
        let (snippet, highlights) = make_highlighted_snippet(&text, "ς");
        assert!(!snippet.to_lowercase().contains('ς'));
        assert_eq!(highlights, vec![ContentHighlight { start: 31, end: 32 }]);
        assert_eq!(
            snippet.encode_utf16().nth(highlights[0].start),
            Some('Σ' as u16)
        );
    }

    #[test]
    fn unicode_snippet_highlights_survive_whitespace_and_emoji() {
        let (snippet, highlights) =
            make_highlighted_snippet("😀 İ\n\t  X and İ\n\t  X", "i\u{307}\n\t  x");
        assert_eq!(snippet, "😀 İ X and İ X");
        assert_eq!(
            highlights,
            vec![
                ContentHighlight { start: 3, end: 6 },
                ContentHighlight { start: 11, end: 14 }
            ]
        );
    }

    #[test]
    fn unicode_snippet_ranges_keep_supplementary_and_overlapping_expansions_intact() {
        let (snippet, highlights) = make_highlighted_snippet("😀𐐀 x𐐨", "𐐨");
        assert_eq!(snippet, "😀𐐀 x𐐨");
        assert_eq!(
            highlights,
            vec![
                ContentHighlight { start: 2, end: 4 },
                ContentHighlight { start: 6, end: 8 }
            ]
        );
        let (snippet, highlights) = make_highlighted_snippet("İİİ", "\u{307}i");
        assert_eq!(snippet, "İİİ");
        assert_eq!(highlights, vec![ContentHighlight { start: 0, end: 3 }]);
    }

    #[test]
    fn unicode_snippets_map_expanded_lowercase_back_to_original_characters() {
        for (prefix, text, query) in [
            ("İ".repeat(140), "😀ΟΣ", "ος"),
            ("中".repeat(140), "İabc", "i\u{307}a"),
        ] {
            let original = format!("{prefix}{text}{}", "尾".repeat(140));
            let snippet = make_snippet(&original, query);
            assert!(snippet.contains(text), "{snippet:?}");
            assert!(snippet.starts_with('…'));
        }
    }

    #[test]
    fn search_matches_chinese_substrings_including_two_char_queries() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source(
                "codex",
                "/a.jsonl",
                fp(1),
                &rows(&["开头", "中间讨论了跑马灯的滚动速度", "结尾"]),
            )
            .unwrap();
        index
            .replace_source(
                "claude",
                "/b.jsonl",
                fp(1),
                &rows(&["排版时注意正交的布局"]),
            )
            .unwrap();

        let hits = index.search("跑马灯", None, 10).unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].provider_id, "codex");
        assert_eq!(hits[0].source_path, "/a.jsonl");
        assert_eq!(hits[0].snippets.len(), 1);
        assert_eq!(hits[0].snippets[0].message_index, 1);
        assert!(hits[0].snippets[0].text.contains("跑马灯"));

        // 两个字:走无正文的短词索引
        let hits = index.search("正交", None, 10).unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].source_path, "/b.jsonl");

        assert!(index.search("不存在的词", None, 10).unwrap().is_empty());
    }

    #[test]
    fn search_is_case_insensitive_and_escapes_special_characters() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source(
                "claude",
                "/a.jsonl",
                fp(1),
                &rows(&[
                    "call useSessionSearch() here",
                    "100% done",
                    "a \"quoted\" word",
                ]),
            )
            .unwrap();

        assert_eq!(index.search("USESESSIONSEARCH", None, 10).unwrap().len(), 1);
        assert_eq!(index.search("0%", None, 10).unwrap().len(), 1);
        assert_eq!(index.search("%", None, 10).unwrap().len(), 1);
        assert_eq!(index.search("_", None, 10).unwrap().len(), 0);
        assert_eq!(index.search("\"quoted\"", None, 10).unwrap().len(), 1);
        assert_eq!(index.search("AND OR NOT", None, 10).unwrap().len(), 0);
    }

    #[test]
    fn search_folds_non_ascii_case_for_long_and_short_queries() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source(
                "claude",
                "/a.jsonl",
                fp(1),
                &rows(&["Ordered an Éclair", "Привет мир"]),
            )
            .unwrap();

        // trigram 路径
        assert_eq!(index.search("éclair", None, 10).unwrap().len(), 1);
        assert_eq!(index.search("ÉCLAIR", None, 10).unwrap().len(), 1);
        assert_eq!(index.search("ПРИВЕТ", None, 10).unwrap().len(), 1);
        // 不足 3 个字符:在规范化短词索引上匹配
        let hits = index.search("éc", None, 10).unwrap();
        assert_eq!(hits.len(), 1);
        assert!(hits[0].snippets[0].text.contains("Éclair"));
        assert_eq!(index.search("ПР", None, 10).unwrap().len(), 1);
        assert_eq!(index.search("ÉX", None, 10).unwrap().len(), 0);
    }

    #[test]
    fn search_aggregates_per_session_and_filters_providers() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source(
                "codex",
                "/a.jsonl",
                fp(1),
                &rows(&["deploy one", "nothing", "deploy two"]),
            )
            .unwrap();
        index
            .replace_source("claude", "/b.jsonl", fp(1), &rows(&["deploy three"]))
            .unwrap();

        let hits = index.search("deploy", None, 10).unwrap();
        assert_eq!(hits.len(), 2);
        let codex = hits.iter().find(|hit| hit.provider_id == "codex").unwrap();
        assert_eq!(codex.match_count, 2);
        let mut indexes: Vec<usize> = codex.snippets.iter().map(|s| s.message_index).collect();
        indexes.sort_unstable();
        assert_eq!(indexes, vec![0, 2]);

        let only_claude: HashSet<String> = ["claude".to_string()].into_iter().collect();
        let hits = index.search("deploy", Some(&only_claude), 10).unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].provider_id, "claude");

        assert_eq!(index.search("deploy", None, 1).unwrap().len(), 1);
    }

    #[test]
    fn search_caps_snippets_per_session_but_counts_every_match() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        let texts: Vec<String> = (0..5).map(|i| format!("deploy step {i}")).collect();
        let texts: Vec<&str> = texts.iter().map(String::as_str).collect();
        index
            .replace_source("codex", "/a.jsonl", fp(1), &rows(&texts))
            .unwrap();

        let hits = index.search("deploy", None, 10).unwrap();
        assert_eq!(hits[0].match_count, 5);
        assert_eq!(hits[0].snippets.len(), MAX_SNIPPETS_PER_SESSION);
    }

    #[test]
    fn provider_filter_applies_before_the_hit_row_cap() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        // 先插入选中应用的唯一命中,再让其他应用占满候选上限(短词路径按 rowid 倒序)
        index
            .replace_source(
                "codex",
                "/codex.jsonl",
                fp(1),
                &rows(&["needle xy Éclair target"]),
            )
            .unwrap();
        let noise: Vec<(usize, String)> = (0..MAX_HIT_ROWS as usize + 5)
            .map(|i| (i, "needle xy Éclair".to_string()))
            .collect();
        index
            .replace_source("claude", "/claude.jsonl", fp(1), &noise)
            .unwrap();

        let only_codex: HashSet<String> = ["codex".to_string()].into_iter().collect();
        for query in ["needle", "xy", "éc"] {
            let hits = index.search(query, Some(&only_codex), 10).unwrap();
            assert_eq!(hits.len(), 1, "query {query}");
            assert_eq!(hits[0].provider_id, "codex", "query {query}");
        }
        let nobody: HashSet<String> = ["gemini".to_string()].into_iter().collect();
        assert!(index
            .search("needle", Some(&nobody), 10)
            .unwrap()
            .is_empty());
    }

    #[test]
    fn removing_index_files_ignores_only_missing_files_and_attempts_every_file() {
        use std::io::{Error, ErrorKind};

        for failure in [
            None,
            Some(ErrorKind::PermissionDenied),
            Some(ErrorKind::Other),
        ] {
            for failed_file in 0..3 {
                let path = Path::new(INDEX_FILE);
                let mut attempted = Vec::new();
                let result = remove_index_files_with(path, |file| {
                    let position = attempted.len();
                    attempted.push(file.to_path_buf());
                    if position == failed_file {
                        if let Some(kind) = failure {
                            return Err(Error::from(kind));
                        }
                    }
                    Err(Error::from(ErrorKind::NotFound))
                });
                assert_eq!(result.err().map(|e| e.kind()), failure);
                assert_eq!(
                    attempted,
                    [
                        INDEX_FILE.to_string(),
                        format!("{INDEX_FILE}-wal"),
                        format!("{INDEX_FILE}-shm")
                    ]
                    .map(PathBuf::from),
                );
            }
        }
    }

    #[test]
    fn clear_failure_drops_index_resets_status_and_keeps_disabled_writers_out() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        // 目录无法用 remove_file 删除,避免依赖 chmod 或测试进程的权限。
        fs::create_dir(&path).unwrap();
        for suffix in ["-wal", "-shm"] {
            fs::write(dir.path().join(format!("{INDEX_FILE}{suffix}")), b"fixture").unwrap();
        }
        let slot = Mutex::new(Some(SessionIndex::open_in_memory().unwrap()));
        let status = Mutex::new(IndexStatus {
            running: true,
            processed: 1,
            total: 2,
        });
        let enabled = AtomicBool::new(false);

        assert!(clear_in(&slot, &status, &path).is_err());
        assert!(slot.lock_recover().is_none());
        assert_eq!(*status.lock_recover(), IndexStatus::default());
        assert!(!dir.path().join(format!("{INDEX_FILE}-wal")).exists());
        assert!(!dir.path().join(format!("{INDEX_FILE}-shm")).exists());
        assert!(
            with_index_in(&slot, &path, || enabled.load(Ordering::SeqCst), |_| Ok(())).is_err()
        );
        assert!(!enabled.load(Ordering::SeqCst));
        assert!(path.is_dir());
    }

    #[test]
    fn non_corruption_errors_preserve_the_index() {
        let index = SessionIndex::open_in_memory().unwrap();
        let slot = Mutex::new(Some(index));
        let result: Result<(), String> = with_index_in(
            &slot,
            Path::new("unused-index-path"),
            || true,
            |_| Err(rusqlite::Error::InvalidQuery),
        );
        assert!(result.is_err());
        assert!(slot.lock_recover().is_some());
    }

    #[test]
    fn search_recovers_from_corrupt_fts_segments() {
        if crate::config::sqlite_unsupported_in_temp_dir() {
            return;
        }
        for (table, query) in [
            ("message_text_data", "needle"),
            ("message_short_data", "代"),
        ] {
            assert_search_recovers_from_corrupt_fts_segments(table, query);
        }
    }

    fn assert_search_recovers_from_corrupt_fts_segments(table: &str, query: &str) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        {
            let mut index = SessionIndex::open(&path).unwrap();
            index
                .replace_source("codex", "/synthetic", fp(1), &rows(&["代理 needle"]))
                .unwrap();
            index
                .conn
                .execute(
                    &format!("UPDATE {table} SET block = x'00' WHERE id > 10"),
                    [],
                )
                .unwrap();
        }
        // Opening succeeds even though reading the FTS segment fails.
        let index = SessionIndex::open(&path).unwrap();
        assert_eq!(
            index
                .search(query, None, 10)
                .unwrap_err()
                .sqlite_error_code(),
            Some(rusqlite::ErrorCode::DatabaseCorrupt)
        );
        let slot = Mutex::new(Some(index));
        assert!(search_in(&slot, &path, || true, query, None, 10).is_err());
        assert!(slot.lock_recover().is_none());
        assert!(
            !path.exists(),
            "corrupt cache must be removed before releasing the lock"
        );
        with_index_in(
            &slot,
            &path,
            || true,
            |index| index.replace_source("codex", "/synthetic", fp(1), &rows(&["代理 needle"])),
        )
        .unwrap();
        assert_eq!(
            search_in(&slot, &path, || true, query, None, 10)
                .unwrap()
                .hits
                .len(),
            1
        );
    }

    #[test]
    fn stale_corruption_cleanup_preserves_a_rebuilt_index() {
        if crate::config::sqlite_unsupported_in_temp_dir() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        let index = SessionIndex::open(&path).unwrap();
        let generation = Arc::clone(&index.generation);
        let slot = Mutex::new(Some(index));
        discard_corrupt_index(&slot, &path, Some(Arc::clone(&generation)));
        with_index_in(
            &slot,
            &path,
            || true,
            |index| index.replace_source("codex", "/synthetic", fp(1), &rows(&["needle"])),
        )
        .unwrap();
        discard_corrupt_index(&slot, &path, Some(generation));
        assert!(path.exists());
        assert_eq!(
            search_in(&slot, &path, || true, "needle", None, 10)
                .unwrap()
                .hits
                .len(),
            1
        );
    }

    #[test]
    fn search_reports_reader_open_failures_instead_of_empty_hits() {
        let dir = tempfile::tempdir().unwrap();
        // An already-initialized writer must not hide failures on the independent reader.
        let slot = Mutex::new(Some(SessionIndex::open_in_memory().unwrap()));
        let error = search_in(&slot, dir.path(), || true, "needle", None, 10)
            .expect_err("opening a directory as a read-only index must report an error");
        assert!(!error.trim().is_empty());
        assert!(slot.lock_recover().is_some());
    }

    #[test]
    fn search_reports_candidate_and_snippet_sql_failures_instead_of_empty_hits() {
        if crate::config::sqlite_unsupported_in_temp_dir() {
            return;
        }
        for table in ["message_short", "message_text"] {
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join(INDEX_FILE);
            let mut index = SessionIndex::open(&path).unwrap();
            index
                .replace_source("codex", "/synthetic", fp(1), &rows(&["代理 needle"]))
                .unwrap();
            // Missing short postings fail candidate selection; missing text fails
            // the later snippet batch after the short-query candidates were found.
            index
                .conn
                .execute_batch(&format!("DROP TABLE {table}"))
                .unwrap();
            let slot = Mutex::new(Some(index));
            let error = search_in(&slot, &path, || true, "代", None, 10)
                .expect_err("SQL failures must not look like an ordinary empty result");
            assert!(error.contains(table), "{error}");
            assert!(slot.lock_recover().is_some());
            assert!(
                path.exists(),
                "non-corruption errors must preserve the cache"
            );
        }
    }

    #[test]
    fn search_reports_missing_snippet_rows_instead_of_partial_hits() {
        if crate::config::sqlite_unsupported_in_temp_dir() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        let mut index = SessionIndex::open(&path).unwrap();
        index
            .replace_source(
                "codex",
                "/synthetic",
                fp(1),
                &rows(&["代理 first", "代理 second"]),
            )
            .unwrap();
        // Simulate inconsistent short postings: the batch finds one text row,
        // but must report the missing row just as a per-row query would.
        index
            .conn
            .execute(
                "DELETE FROM message_text WHERE rowid = (SELECT MAX(rowid) FROM message_text)",
                [],
            )
            .unwrap();
        assert!(matches!(
            index.search("代", None, 10),
            Err(rusqlite::Error::QueryReturnedNoRows)
        ));
        let slot = Mutex::new(Some(index));
        let error = search_in(&slot, &path, || true, "代", None, 10)
            .expect_err("a missing snippet row must not produce partial or empty hits");
        assert!(error.contains(&rusqlite::Error::QueryReturnedNoRows.to_string()));
    }

    #[test]
    fn search_reports_index_failures_instead_of_empty_hits() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        // 索引文件位置被一个目录占着:打不开,也删不掉
        fs::create_dir(&path).unwrap();
        let slot = Mutex::new(None);
        let enabled = AtomicBool::new(true);

        let result = search_in(
            &slot,
            &path,
            || enabled.load(Ordering::SeqCst),
            "needle",
            None,
            10,
        );
        // 空命中会被界面当成「正文里没有这个词」,这里必须报错
        let error = result.expect_err("an unreadable index must not look empty");
        assert!(!error.trim().is_empty(), "the failure needs a reason");

        // 索引只是缓存:挡路的目录挪开后,界面上的「重试」要能自愈
        if crate::config::sqlite_unsupported_in_temp_dir() {
            return;
        }
        fs::remove_dir(&path).unwrap();
        let recovered = search_in(
            &slot,
            &path,
            || enabled.load(Ordering::SeqCst),
            "needle",
            None,
            10,
        )
        .expect("the retry must rebuild the index");
        assert!(recovered.hits.is_empty());

        // 功能关着时不算失败:没有索引是正常状态
        enabled.store(false, Ordering::SeqCst);
        let empty = search_in(
            &slot,
            &path,
            || enabled.load(Ordering::SeqCst),
            "needle",
            None,
            10,
        )
        .expect("a disabled search is not a failure");
        assert!(empty.hits.is_empty());
    }

    #[test]
    fn removing_index_files_deletes_existing_files_and_can_be_repeated() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        for suffix in ["", "-wal", "-shm"] {
            fs::write(dir.path().join(format!("{INDEX_FILE}{suffix}")), b"fixture").unwrap();
        }
        remove_index_files(&path).unwrap();
        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 0);
        remove_index_files(&path).unwrap();
    }

    #[test]
    fn disabling_while_a_writer_waits_for_the_lock_keeps_the_index_deleted() {
        use std::sync::atomic::AtomicBool;
        use std::sync::Arc;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        let slot: Arc<Mutex<Option<SessionIndex>>> = Arc::new(Mutex::new(None));
        let enabled = Arc::new(AtomicBool::new(true));

        // 模拟 clear:持锁期间关闭开关、删文件;写入线程此时已经在等锁
        let guard = slot.lock_recover();
        let writer = {
            let slot = Arc::clone(&slot);
            let enabled = Arc::clone(&enabled);
            let path = path.clone();
            std::thread::spawn(move || {
                with_index_in(
                    &slot,
                    &path,
                    || enabled.load(Ordering::SeqCst),
                    |index| index.replace_source("codex", "/a.jsonl", fp(1), &rows(&["secret"])),
                )
            })
        };
        std::thread::sleep(std::time::Duration::from_millis(50));
        enabled.store(false, Ordering::SeqCst);
        remove_index_files(&path).unwrap();
        drop(guard);

        assert!(writer.join().unwrap().is_err());
        assert!(!path.exists());
    }

    #[test]
    fn replace_and_remove_only_touch_one_source() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source("codex", "/a.jsonl", fp(1), &rows(&["old words"]))
            .unwrap();
        index
            .replace_source("codex", "/b.jsonl", fp(1), &rows(&["old words too"]))
            .unwrap();

        index
            .replace_source("codex", "/a.jsonl", fp(2), &rows(&["new words"]))
            .unwrap();
        assert_eq!(
            index.stored_fingerprint("codex", "/a.jsonl").unwrap(),
            Some(fp(2))
        );
        let hits = index.search("old words", None, 10).unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].source_path, "/b.jsonl");

        index.remove_source("codex", "/b.jsonl").unwrap();
        assert!(index.search("old words", None, 10).unwrap().is_empty());
        assert_eq!(index.stored_fingerprint("codex", "/b.jsonl").unwrap(), None);

        let keep: HashSet<(String, String)> = HashSet::new();
        index
            .retain_sources(&keep, &HashSet::from(["claude".into(), "codex".into()]))
            .unwrap();
        assert!(index.search("new words", None, 10).unwrap().is_empty());
    }

    #[test]
    fn reopening_with_another_version_rebuilds_the_index() {
        if crate::config::sqlite_unsupported_in_temp_dir() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        {
            let mut index = SessionIndex::open(&path).unwrap();
            index
                .replace_source("codex", "/a.jsonl", fp(1), &rows(&["persisted text"]))
                .unwrap();
            index.compact().unwrap();
        }
        {
            let index = SessionIndex::open(&path).unwrap();
            assert_eq!(index.search("persisted", None, 10).unwrap().len(), 1);
            index
                .conn
                .pragma_update(None, "user_version", INDEX_VERSION + 1)
                .unwrap();
        }
        let index = SessionIndex::open(&path).unwrap();
        assert!(index.search("persisted", None, 10).unwrap().is_empty());
        assert_eq!(index.stored_fingerprint("codex", "/a.jsonl").unwrap(), None);
    }

    #[test]
    fn snippet_centers_on_the_match_and_collapses_whitespace() {
        let text = format!(
            "{}\n\n关键词 出现在这里{}",
            "前".repeat(50),
            "后".repeat(200)
        );
        let snippet = make_snippet(&text, "关键词");
        assert!(snippet.starts_with('…'));
        assert!(snippet.ends_with('…'));
        assert!(snippet.contains(" 关键词 出现在这里"));
        assert!(!snippet.contains('\n'));

        assert_eq!(make_snippet("Hello World", "world"), "Hello World");
        assert_eq!(make_snippet("short", "missing"), "short");
    }

    #[test]
    fn short_postings_are_literal_and_follow_replacement_and_deletion() {
        let mut index = SessionIndex::open_in_memory().unwrap();
        index
            .replace_source(
                "codex",
                "/short",
                fp(1),
                &rows(&["代理 报错 路由 😀x 0% _ İ ΟΣ"]),
            )
            .unwrap();
        for query in [
            "代", "代理", "报错", "路由", "😀", "😀x", "0%", "_", "i", "ς",
        ] {
            assert_eq!(index.search(query, None, 10).unwrap().len(), 1, "{query}");
        }
        for query in ["理代", "%_", "x😀", "δ"] {
            assert!(index.search(query, None, 10).unwrap().is_empty());
        }
        index
            .replace_source("codex", "/short", fp(2), &rows(&["新词"]))
            .unwrap();
        assert!(index.search("代理", None, 10).unwrap().is_empty());
        assert_eq!(index.search("新词", None, 10).unwrap().len(), 1);
        index.remove_source("codex", "/short").unwrap();
        assert!(index.search("新词", None, 10).unwrap().is_empty());
    }

    #[test]
    fn wal_reader_searches_while_writer_holds_uncommitted_changes() {
        if crate::config::sqlite_unsupported_in_temp_dir() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(INDEX_FILE);
        let mut writer = SessionIndex::open(&path).unwrap();
        writer
            .replace_source("codex", "/a", fp(1), &rows(&["代理 needle"]))
            .unwrap();
        let slot = Arc::new(Mutex::new(Some(writer)));
        let mut guard = slot.lock_recover();
        let writer = guard.as_mut().unwrap();
        let tx = writer.conn.transaction().unwrap();
        tx.execute("UPDATE indexed_sources SET source_path='/uncommitted'", [])
            .unwrap();
        let (send, recv) = std::sync::mpsc::channel();
        let reader_slot = Arc::clone(&slot);
        let reader = std::thread::spawn(move || {
            let hits = search_in(&reader_slot, &path, || true, "代理", None, 10)
                .unwrap()
                .hits;
            assert_eq!(hits[0].source_path, "/a");
            send.send(()).unwrap();
        });
        let completed = recv.recv_timeout(std::time::Duration::from_secs(2));
        tx.rollback().unwrap();
        drop(guard);
        reader.join().unwrap();
        completed.expect("reader must finish before writer releases its transaction");
    }

    #[test]
    #[ignore = "manual synthetic search benchmark"]
    fn benchmark_short_search() {
        use std::time::Instant;
        let mut index = SessionIndex::open_in_memory().unwrap();
        let rows: Vec<_> = (0..5000)
            .map(|i| {
                (
                    i,
                    format!(
                        "{} {}",
                        "普通对话 metadata and code ".repeat(100),
                        if i % 1000 == 0 { "代理" } else { "结束" }
                    ),
                )
            })
            .collect();
        index
            .replace_source("codex", "/bench", fp(1), &rows)
            .unwrap();
        let start = Instant::now();
        for _ in 0..20 {
            assert_eq!(index.search("代理", None, 10).unwrap()[0].match_count, 5);
        }
        let indexed = start.elapsed() / 20;
        let start = Instant::now();
        for _ in 0..20 {
            let count: i64 = index
                .conn
                .query_row(
                    "SELECT count(*) FROM message_text WHERE instr(normalized, '代理') > 0",
                    [],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(count, 5);
        }
        eprintln!(
            "5000 messages: indexed search+snippets {indexed:?}; original instr scan {:?}",
            start.elapsed() / 20
        );
        index.compact().unwrap();
        let pages = || {
            index
                .conn
                .query_row("PRAGMA page_count", [], |row| row.get::<_, u64>(0))
                .unwrap()
        };
        let with_short = pages();
        index
            .conn
            .execute_batch("DROP TABLE message_short; VACUUM;")
            .unwrap();
        eprintln!(
            "compacted pages (4096 bytes): with short index {with_short}, trigram only {}",
            pages()
        );
    }
}