A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
pub mod cache;
pub mod content;
#[cfg(windows)]
pub(crate) mod hermes_wsl;
pub mod model;
pub mod providers;
pub mod search;
mod search_revision;
pub mod terminal;
use crate::sync_utils::MutexExt;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{Duration, Instant};
// 其余模型类型从 `session_manager::model` 引用
pub use model::SessionMessage;
use providers::{
agy, claude, codebuddy, codex, copilot, dsh, gemini, grokbuild, hermes, kimi, mcode, omp,
openclaw, opencode, pi, qoder, workbuddy, zcode,
};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionMeta {
pub provider_id: String,
pub session_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub project_dir: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub created_at: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_active_at: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resume_command: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteSessionRequest {
pub provider_id: String,
pub session_id: String,
pub source_path: String,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteSessionOutcome {
pub provider_id: String,
pub session_id: String,
pub source_path: String,
pub success: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
pub fn scan_sessions() -> Vec<SessionMeta> {
let scan = scan_sessions_with_status();
let sessions = scan.sessions.clone();
*RECENT_SCAN.lock_recover() = Some((Instant::now(), scan));
sessions
}
// The index request follows list_sessions. Reuse that scan once, including its
// completeness flags; enabling from a cached page or a queued rerun scans afresh.
static RECENT_SCAN: LazyLock<Mutex<Option<(Instant, SessionScan)>>> =
LazyLock::new(|| Mutex::new(None));
const SCAN_REUSE_WINDOW: Duration = Duration::from_secs(5);
pub(crate) fn scan_for_index() -> SessionScan {
take_recent_scan(&RECENT_SCAN, Instant::now()).unwrap_or_else(scan_sessions_with_status)
}
fn take_recent_scan(
slot: &Mutex<Option<(Instant, SessionScan)>>,
now: Instant,
) -> Option<SessionScan> {
slot.lock_recover()
.take()
.filter(|(created, _)| now.saturating_duration_since(*created) <= SCAN_REUSE_WINDOW)
.map(|(_, scan)| scan)
}
pub(crate) struct SessionScan {
pub sessions: Vec<SessionMeta>,
pub complete_providers: HashSet<String>,
}
pub(crate) fn scan_sessions_with_status() -> SessionScan {
use providers::utils::ScanStatus;
type Scanner = fn(&mut ScanStatus) -> Vec<SessionMeta>;
let scanners: [(&str, Scanner); 18] = [
("codex", codex::scan_sessions_with_status),
("claude", claude::scan_sessions_with_status),
("opencode", opencode::scan_sessions_with_status),
("openclaw", openclaw::scan_sessions_with_status),
("gemini", gemini::scan_sessions_with_status),
("hermes", hermes::scan_sessions_with_status),
("grokbuild", grokbuild::scan_sessions_with_status),
("pi", pi::scan_sessions_with_status),
("omp", omp::scan_sessions_with_status),
("mcode", mcode::scan_sessions_with_status),
("copilot", copilot::scan_sessions_with_status),
// 国际版和国内版的会话都归在 qoder 下
("qoder", qoder::scan_sessions_with_status),
// 以下来源的扫描还不报告读取失败,按完整处理
("kimi", |_| kimi::scan_sessions()),
("dsh", |_| dsh::scan_sessions()),
("agy", |_| agy::scan_sessions()),
("workbuddy", |_| workbuddy::scan_sessions()),
("codebuddy", |_| codebuddy::scan_sessions()),
("zcode", |_| zcode::scan_sessions()),
];
let mut scan = SessionScan {
sessions: Vec::new(),
complete_providers: HashSet::new(),
};
std::thread::scope(|scope| {
let handles: Vec<_> = scanners
.into_iter()
.map(|(provider, scanner)| {
(
provider,
scope.spawn(move || {
let mut status = ScanStatus::default();
let sessions = scanner(&mut status);
(sessions, status)
}),
)
})
.collect();
for (provider, handle) in handles {
// A failed worker is not evidence that all its sessions were deleted.
if let Ok((sessions, status)) = handle.join() {
scan.sessions.extend(sessions);
if !status.incomplete {
scan.complete_providers.insert(provider.to_string());
}
}
}
});
scan.sessions.sort_by(|a, b| {
let a_ts = a.last_active_at.or(a.created_at).unwrap_or(0);
let b_ts = b.last_active_at.or(b.created_at).unwrap_or(0);
b_ts.cmp(&a_ts)
});
scan
}
pub fn load_messages(provider_id: &str, source_path: &str) -> Result<Vec<SessionMessage>, String> {
if provider_id == "mcode" {
return mcode::load_messages(source_path);
}
// SQLite sessions use a "sqlite:" prefixed source_path
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
return opencode::load_messages_sqlite(source_path);
}
if provider_id == "hermes" && source_path.starts_with("sqlite:") {
return hermes::load_messages_sqlite(source_path);
}
// ZCode 的会话源形如 `zcode:<sessionId>`,读的是自己的 SQLite
if provider_id == "zcode" {
return zcode::load_messages(source_path);
}
let path = Path::new(source_path);
match provider_id {
"codex" => codex::load_messages(path),
"claude" => claude::load_messages(path),
"opencode" => opencode::load_messages(path),
"openclaw" => openclaw::load_messages(path),
"gemini" => gemini::load_messages(path),
"agy" => agy::load_messages(path),
"grokbuild" => grokbuild::load_messages(path),
"hermes" => hermes::load_messages(path),
"pi" => pi::load_messages(path),
"kimi" => kimi::load_messages(path),
"omp" => omp::load_messages(path),
"copilot" => copilot::load_messages(path),
"codebuddy" => codebuddy::load_messages(path),
"dsh" => dsh::load_messages(path),
"workbuddy" => workbuddy::load_messages(path),
"qoder" => qoder::load_messages(path),
_ => Err(format!("Unsupported provider: {provider_id}")),
}
}
/// 一次读取的结果:解析结果、是否命中缓存、耗时(含校验与指纹)
pub struct LoadedTranscript {
pub transcript: Arc<cache::Transcript>,
pub cached: bool,
pub parse_ms: u64,
}
/// 校验 `source_path` 归属后读取会话,未变化的源直接用 [`cache::TranscriptCache`]。
/// 解析仍走上面的 [`load_messages`] 分发。
pub fn load_transcript(provider_id: &str, source_path: &str) -> Result<LoadedTranscript, String> {
let started = Instant::now();
let source = content::validate_source(provider_id, source_path)?;
let fingerprint = cache::source_fingerprint(&source)
.map_err(|e| format!("Failed to read session source: {e}"))?;
let key = (source.provider_id.clone(), source.raw.clone());
let (transcript, cached) = cache::global().get_or_load(key, fingerprint, || {
load_messages(&source.provider_id, &source.load_path()).map(cache::Transcript::new)
})?;
Ok(LoadedTranscript {
transcript,
cached,
parse_ms: started.elapsed().as_millis() as u64,
})
}
/// 删除成功后同时移除该会话的解析缓存(§5.2)
pub fn delete_session(
provider_id: &str,
session_id: &str,
source_path: &str,
) -> Result<bool, String> {
let deleted = delete_session_source(provider_id, session_id, source_path)?;
if deleted {
cache::global().remove(provider_id, source_path);
search::forget_source(provider_id, source_path);
}
Ok(deleted)
}
fn delete_session_source(
provider_id: &str,
session_id: &str,
source_path: &str,
) -> Result<bool, String> {
if provider_id == "dsh" {
return Err(
"Delete this session in DeepSeek Harness to keep its native history consistent".into(),
);
}
if provider_id == "copilot" {
return Err(
"Delete this session in GitHub Copilot CLI to keep its session store and history consistent"
.into(),
);
}
if provider_id == "workbuddy" {
// WorkBuddy 自己的会话列表在 workbuddy.db 和 sessions/ 里,只删 jsonl 会让它的索引失效。
return Err(
"Delete this session in WorkBuddy to keep its session list and history consistent"
.into(),
);
}
if provider_id == "codebuddy" {
return Err(
"Manage this session in CodeBuddy: background jobs, teammates and file history refer to its transcript"
.into(),
);
}
if provider_id == "mcode" {
return Err(
"Delete this session in MCode so its runtime state and history are removed together"
.into(),
);
}
if provider_id == "qoder" {
return Err(
"Delete this session in Qoder CLI so its session state and history stay consistent"
.into(),
);
}
if provider_id == "zcode" {
return Err(
"Delete this session in ZCode so its history and usage records stay consistent".into(),
);
}
// SQLite sessions bypass the file-based deletion path
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
return opencode::delete_session_sqlite(session_id, source_path);
}
if provider_id == "hermes" && source_path.starts_with("sqlite:") {
return hermes::delete_session_sqlite(session_id, source_path);
}
let roots = provider_roots(provider_id)?;
delete_session_with_roots(provider_id, session_id, Path::new(source_path), &roots)
}
pub fn delete_sessions(requests: &[DeleteSessionRequest]) -> Vec<DeleteSessionOutcome> {
collect_delete_session_outcomes(requests, |request| {
delete_session(
&request.provider_id,
&request.session_id,
&request.source_path,
)
})
}
fn delete_session_with_roots(
provider_id: &str,
session_id: &str,
source_path: &Path,
roots: &[PathBuf],
) -> Result<bool, String> {
let source_path = content::codex_source_or_sibling(provider_id, source_path);
let (validated_root, validated_source) =
content::resolve_under_roots(provider_id, &source_path, roots)?;
match provider_id {
"codex" => codex::delete_session(&validated_root, &validated_source, session_id),
"claude" => claude::delete_session(&validated_root, &validated_source, session_id),
"opencode" => opencode::delete_session(&validated_root, &validated_source, session_id),
"openclaw" => openclaw::delete_session(&validated_root, &validated_source, session_id),
"gemini" => gemini::delete_session(&validated_root, &validated_source, session_id),
"grokbuild" => grokbuild::delete_session(&validated_root, &validated_source, session_id),
"hermes" => hermes::delete_session(&validated_root, &validated_source, session_id),
"pi" => pi::delete_session(&validated_root, &validated_source, session_id),
"omp" => omp::delete_session(&validated_root, &validated_source, session_id),
"kimi" => kimi::delete_session(&validated_root, &validated_source, session_id),
"agy" => agy::delete_session(&validated_root, &validated_source, session_id),
_ => Err(format!("Unsupported provider: {provider_id}")),
}
}
fn provider_roots(provider_id: &str) -> Result<Vec<PathBuf>, String> {
let roots = match provider_id {
"codex" => codex::session_roots(),
"claude" => vec![crate::config::get_claude_config_dir().join("projects")],
"opencode" => vec![opencode::get_opencode_data_dir()],
"openclaw" => vec![crate::openclaw_config::get_openclaw_dir().join("agents")],
"gemini" => vec![crate::gemini_config::get_gemini_dir().join("tmp")],
"grokbuild" => grokbuild::session_roots(),
"hermes" => vec![crate::hermes_config::get_hermes_dir().join("sessions")],
"pi" => pi::session_roots(),
"kimi" => kimi::session_roots(),
"codebuddy" => codebuddy::session_roots(),
"dsh" => dsh::session_roots(),
"workbuddy" => workbuddy::session_roots(),
"agy" => agy::session_roots(),
"omp" => omp::session_roots(),
"copilot" => copilot::session_roots(),
"qoder" => qoder::session_roots(),
_ => return Err(format!("Unsupported provider: {provider_id}")),
};
Ok(roots)
}
fn canonicalize_existing_path(path: &Path, label: &str) -> Result<PathBuf, String> {
if !path.exists() {
return Err(format!("{label} not found: {}", path.display()));
}
path.canonicalize()
.map_err(|e| format!("Failed to resolve {label} {}: {e}", path.display()))
}
fn collect_delete_session_outcomes<F>(
requests: &[DeleteSessionRequest],
mut deleter: F,
) -> Vec<DeleteSessionOutcome>
where
F: FnMut(&DeleteSessionRequest) -> Result<bool, String>,
{
requests
.iter()
.map(|request| match deleter(request) {
Ok(true) => DeleteSessionOutcome {
provider_id: request.provider_id.clone(),
session_id: request.session_id.clone(),
source_path: request.source_path.clone(),
success: true,
error: None,
},
Ok(false) => DeleteSessionOutcome {
provider_id: request.provider_id.clone(),
session_id: request.session_id.clone(),
source_path: request.source_path.clone(),
success: false,
error: Some("Session was not deleted".to_string()),
},
Err(error) => DeleteSessionOutcome {
provider_id: request.provider_id.clone(),
session_id: request.session_id.clone(),
source_path: request.source_path.clone(),
success: false,
error: Some(error),
},
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn index_reuses_a_fresh_scan_once_and_preserves_incomplete_providers() {
let now = Instant::now();
let slot = Mutex::new(Some((
now,
SessionScan {
sessions: Vec::new(),
// Claude failed; Codex really has no sessions. These flags must
// survive reuse so only Codex's old index is eligible for pruning.
complete_providers: HashSet::from(["codex".into()]),
},
)));
let scan = take_recent_scan(&slot, now).unwrap();
assert!(scan.sessions.is_empty());
assert_eq!(scan.complete_providers, HashSet::from(["codex".into()]));
assert!(take_recent_scan(&slot, now).is_none());
*slot.lock().unwrap() = Some((now, scan));
assert!(
take_recent_scan(&slot, now + SCAN_REUSE_WINDOW + Duration::from_secs(1)).is_none()
);
assert!(slot.lock().unwrap().is_none());
}
fn write_codex_session(path: &Path, session_id: &str) {
std::fs::write(
path,
format!(
"{{\"timestamp\":\"2026-03-06T21:50:12Z\",\"type\":\"session_meta\",\"payload\":{{\"id\":\"{session_id}\",\"cwd\":\"/tmp/project\"}}}}\n\
{{\"timestamp\":\"2026-03-06T21:50:13Z\",\"type\":\"response_item\",\"payload\":{{\"type\":\"message\",\"role\":\"user\",\"content\":\"hello\"}}}}\n",
),
)
.expect("write source");
}
#[test]
fn accepts_source_path_under_any_allowed_provider_root() {
let active_root = tempdir().expect("active root");
let archived_root = tempdir().expect("archived root");
let source = archived_root.path().join("session.jsonl");
write_codex_session(&source, "archived-session");
let deleted = delete_session_with_roots(
"codex",
"archived-session",
&source,
&[
active_root.path().to_path_buf(),
archived_root.path().to_path_buf(),
],
)
.expect("delete archived session");
assert!(deleted);
assert!(!source.exists());
}
#[test]
fn rejects_source_path_outside_provider_root() {
let root = tempdir().expect("tempdir");
let outside = tempdir().expect("tempdir");
let source = outside.path().join("session.jsonl");
std::fs::write(&source, "{}").expect("write source");
let err =
delete_session_with_roots("codex", "session-1", &source, &[root.path().to_path_buf()])
.expect_err("expected outside-root path to be rejected");
assert!(err.contains("outside provider roots"));
}
#[test]
fn rejects_missing_source_path() {
let root = tempdir().expect("tempdir");
let missing = root.path().join("missing.jsonl");
let err =
delete_session_with_roots("codex", "session-1", &missing, &[root.path().to_path_buf()])
.expect_err("expected missing source path to fail");
assert!(err.contains("session source not found"));
}
#[test]
fn batch_delete_collects_successes_and_failures_in_order() {
let requests = vec![
DeleteSessionRequest {
provider_id: "codex".to_string(),
session_id: "s1".to_string(),
source_path: "/tmp/s1".to_string(),
},
DeleteSessionRequest {
provider_id: "claude".to_string(),
session_id: "s2".to_string(),
source_path: "/tmp/s2".to_string(),
},
DeleteSessionRequest {
provider_id: "gemini".to_string(),
session_id: "s3".to_string(),
source_path: "/tmp/s3".to_string(),
},
];
let outcomes = collect_delete_session_outcomes(&requests, |request| {
match request.session_id.as_str() {
"s1" => Ok(true),
"s2" => Err("boom".to_string()),
_ => Ok(false),
}
});
assert_eq!(outcomes.len(), 3);
assert!(outcomes[0].success);
assert_eq!(outcomes[0].error, None);
assert!(!outcomes[1].success);
assert_eq!(outcomes[1].error.as_deref(), Some("boom"));
assert!(!outcomes[2].success);
assert_eq!(
outcomes[2].error.as_deref(),
Some("Session was not deleted")
);
}
}