All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
fix: preserve Cursor workspace paths and refresh metadata (#38)
Corey Chiu9053c41b874f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c51ca8d..b09bb43 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,7 @@- New: session cleanup from the sidebar — filter by date, agent or project, sort by size, and preview before moving session files to the system trash. Includes cleanup history.- New: Copy Session Path in the session detail toolbar copies the source file path directly, with inline confirmation. Database-backed sessions copy the shared database path; remote sessions copy the local mirror path, as indicated in the tooltip (#33, thanks @ItsRyanWu)- Fix: Pi and Oh My Pi token usage now adds up each assistant call instead of keeping only the last one, including calls with no visible reply. The shared OpenClaw reader also adds up the calls in its active transcript. Existing indexes are recalculated once after upgrading (#34, thanks @AwadYoo for the report and proposed fix in #35)+- Fix: Cursor transcript sessions preserve spaces in project paths, using workspace metadata and filesystem matching. Git roots no longer override subdirectory workspaces, and later metadata updates refresh project grouping even when the transcript is unchanged (#38, based on #39 by @YTwsy)## [0.6.7] — 2026-09-15diff --git a/README.md b/README.mdindex 595f94c..75bd75f 100644--- a/README.md+++ b/README.md@@ -55,7 +55,7 @@ Your agent history is scattered across `~/.claude`, `~/.codex`, and a dozen otheCodex writes its background threads — the guardian auto-review, `/review`, compaction, memory consolidation and spawned sub-agents — into the same `sessions` directory as your conversations. Wake recognises them from the metadata on their first line and skips them; a file it cannot identify stays visible rather than risk hiding a real conversation.-Cursor keeps two stores. A chat that has a full transcript under `~/.cursor/projects` is read from there (the transcript knows the project folder); chats that only live in Cursor's own database — older ones, or Cursor versions that leave nothing but a `turn_ended` marker in the transcript — are read from `state.vscdb`. Older IDE chats that Cursor stored without a workspace show up under *Unknown project*.+Cursor keeps two stores. A chat that has a full transcript under `~/.cursor/projects` is read from there; local workspace metadata and filesystem matching restore its project path, including spaces. Project metadata is refreshed on each scan even if the transcript is unchanged. Chats that only live in Cursor's own database — older ones, or Cursor versions that leave nothing but a `turn_ended` marker in the transcript — are read from `state.vscdb`. Older IDE chats that Cursor stored without a workspace show up under *Unknown project*.Token statistics depend on the usage recorded by each agent. Qoder CLI transcripts that contain only zero token counts leave token usage unknown in Wake, even when they include Credits or a context usage ratio. Those values measure different things and are not converted into tokens; the sessions remain visible in the Sessions and Prompts views of Insights.diff --git a/crates/wake-core/src/adapters/cursor.rs b/crates/wake-core/src/adapters/cursor.rsindex 8a8c535..1d1079d 100644--- a/crates/wake-core/src/adapters/cursor.rs+++ b/crates/wake-core/src/adapters/cursor.rs@@ -1,5 +1,5 @@use super::parse_utils::*;-use super::{units_from_messages, AgentAdapter};+use super::{cursor_ide, units_from_messages, AgentAdapter};use crate::models::*;use anyhow::Result;use serde_json::Value;@@ -10,16 +10,16 @@ use std::path::{Path, PathBuf};/// Cursor CLI:`~/.cursor/projects/<slug>/agent-transcripts/<uuid>/<uuid>.jsonl` 明文。/// 行结构 {role, message:{content:[{type:text|tool_use}]}} + {type:"turn_ended"}。/// user 正文包在 <timestamp>/<user_query> 壳里;transcript 不含 cwd,-/// 从有损 slug 目录名 DFS 反推真实路径。+/// 优先从同一会话的 IDE 元数据读取路径,缺失时从 slug 目录名还原。////// **同一家的另一个源**:IDE 面板(Chat/Composer)的会话正文在/// `globalStorage/state.vscdb`,由 cursor_ide.rs 读。某些 Cursor 版本的 IDE/// 会话在本源只留 `{"type":"turn_ended"}` 空壳,枚举时按 `is_turn_marker_only`/// 跳过;转录带正文时两源各有一份,scanner 的副本裁决按 `dedup_rank` 固定让-/// 本源胜出——本源有 slug 可反推项目,IDE 库里多数会话没有工作区路径,按写盘-/// 先后轮流胜出会让同一会话在项目之间跳(2026-09-15 实测,Cursor 3.18)。+/// 本源胜出,正文仍从转录读取。pub struct CursorAdapter {root: PathBuf,+ metadata_db: Option<PathBuf>,}impl CursorAdapter {@@ -29,15 +29,21 @@ impl CursorAdapter {.unwrap_or_default().join(".cursor").join("projects"),+ metadata_db: Some(cursor_ide::default_db_path()),}}++ fn project_path(&self, r: &SessionFileRef) -> String {+ let metadata = self+ .metadata_db+ .as_deref()+ .and_then(|db| cursor_ide::project_metadata(db, std::iter::once(r.native_id.as_str())));+ resolve_project_path(r, metadata.as_ref().and_then(|m| m.get(&r.native_id)))+ }}-/// "Users-corey-Github-image-translate" → "/Users/corey/Github/image-translate"。-/// '-' 既可能是路径分隔也可能是目录名字符,按磁盘真实存在的目录 DFS(优先短段);-/// 项目目录已删时回退直译。-fn decode_slug(slug: &str) -> String {- let parts: Vec<&str> = slug.split('-').collect();+/// Cursor 用 `-` 表示分隔符、连字符和空格;优先保留原有路径匹配。+fn decode_existing_slug(base: PathBuf, slug: &str) -> Option<PathBuf> {fn dfs(base: PathBuf, parts: &[&str]) -> Option<PathBuf> {if parts.is_empty() {return Some(base);@@ -48,16 +54,57 @@ fn decode_slug(slug: &str) -> String {seg.push('-');}seg.push_str(parts[i]);- let cand = base.join(&seg);- if cand.is_dir() {- if let Some(hit) = dfs(cand, &parts[i + 1..]) {+ let path = base.join(&seg);+ if path.is_dir() {+ if let Some(hit) = dfs(path, &parts[i + 1..]) {return Some(hit);}}}None}- dfs(PathBuf::from("/"), &parts)++ if slug.is_empty() {+ return Some(base);+ }+ let parts: Vec<&str> = slug.split('-').collect();+ if let Some(path) = dfs(base.clone(), &parts) {+ return Some(path);+ }++ let entries = fs::read_dir(&base).ok()?;+ let mut candidates = Vec::new();+ for entry in entries.flatten() {+ let raw = entry.file_name().to_string_lossy().to_string();+ let encoded = raw.replace(' ', "-");+ let rest = if slug == encoded {+ Some("")+ } else {+ slug.strip_prefix(&encoded)+ .and_then(|s| s.strip_prefix('-'))+ };+ if let Some(rest) = rest {+ let path = entry.path();+ if path.is_dir() {+ candidates.push((encoded.len(), raw.contains(' '), raw, path, rest));+ }+ }+ }+ candidates.sort_by(|a, b| {+ a.0.cmp(&b.0)+ .then_with(|| a.1.cmp(&b.1))+ .then_with(|| a.2.cmp(&b.2))+ });+ for (_, _, _, path, rest) in candidates {+ if let Some(hit) = decode_existing_slug(path, rest) {+ return Some(hit);+ }+ }+ None+}++fn decode_slug(slug: &str) -> String {+ decode_existing_slug(PathBuf::from("/"), slug).map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|| format!("/{}", slug.replace('-', "/")))}@@ -274,14 +321,37 @@ fn subagents_dir(r: &SessionFileRef) -> PathBuf {.join("subagents")}-fn build_meta(r: &SessionFileRef, p: &CursorParse) -> SessionMeta {+fn resolve_project_path(+ r: &SessionFileRef,+ metadata: Option<&cursor_ide::ProjectMetadata>,+) -> String {+ if let Some(workspace) = metadata.and_then(|m| m.workspace.as_ref()) {+ return workspace.clone();+ }// …/projects/<slug>/agent-transcripts/<uuid>/<uuid>.jsonl → slug- let cwd = Path::new(&r.file_path)+ let Some(slug) = Path::new(&r.file_path).ancestors().nth(3).and_then(|d| d.file_name())- .map(|s| decode_slug(&s.to_string_lossy()))- .unwrap_or_default();+ else {+ return String::new();+ };+ let slug = slug.to_string_lossy();+ // A Git root is not necessarily the workspace. Only let it disambiguate+ // spaces/hyphens when the entire path encodes to this transcript's slug.+ if let Some(repo) = metadata.and_then(|m| {+ m.repositories.iter().find(|path| {+ path.trim_start_matches(['/', '\\'])+ .replace(['/', '\\', ' '], "-")+ == slug+ })+ }) {+ return repo.clone();+ }+ decode_slug(&slug)+}++fn build_meta(r: &SessionFileRef, p: &CursorParse, cwd: String) -> SessionMeta {let title = title_from_messages(&p.messages).unwrap_or_else(|| UNTITLED.to_string());SessionMeta {key: format!("cursor:{}", r.native_id),@@ -437,7 +507,7 @@ impl AgentAdapter for CursorAdapter {fn parse_session(&self, r: &SessionFileRef) -> Result<ParsedSession> {let parsed = parse_cursor_jsonl(Path::new(&r.file_path), false)?;- let meta = build_meta(r, &parsed);+ let meta = build_meta(r, &parsed, self.project_path(r));let units = units_from_messages(&parsed.messages);Ok(ParsedSession {meta,@@ -466,7 +536,7 @@ impl AgentAdapter for CursorAdapter {}}Ok(ParsedTranscript {- meta: build_meta(r, &parsed),+ meta: build_meta(r, &parsed, self.project_path(r)),mainline: parsed.messages,sidechains,unknown_line_count: parsed.unknown_lines,@@ -496,7 +566,11 @@ impl AgentAdapter for CursorAdapter {} else {dir};- Box::new(Self { root })+ Box::new(Self {+ root,+ // 自定义目录也用于远程缓存,不能混用本机 IDE 元数据。+ metadata_db: None,+ })}fn data_roots(&self) -> Vec<PathBuf> {@@ -508,6 +582,27 @@ impl AgentAdapter for CursorAdapter {}}+ fn project_path_updates(+ &self,+ refs: &[SessionFileRef],+ ) -> std::collections::HashMap<String, String> {+ if refs.is_empty() {+ return Default::default();+ }+ let metadata = self.metadata_db.as_deref().and_then(|db| {+ cursor_ide::project_metadata(db, refs.iter().map(|r| r.native_id.as_str()))+ });+ let Some(metadata) = metadata else {+ return Default::default();+ };+ refs.iter()+ .filter_map(|r| {+ let project = metadata.get(&r.native_id)?;+ Some((r.file_path.clone(), resolve_project_path(r, Some(project))))+ })+ .collect()+ }+/// Cursor 一家两源(本实例的 agent-transcripts 与 cursor_ide 的 state.vscdb),/// 彼此独立:移除其一不该连带关掉另一个。与 cursor_ide 成对,两边必须同时/// 开启——只开一边的话,面板对另一边的 Remove 仍会按 agent 整家压制@@ -521,6 +616,7 @@ impl AgentAdapter for CursorAdapter {if roots.contains(&self.root) {Some(Box::new(Self {root: PathBuf::new(),+ metadata_db: None,}))} else {None@@ -540,6 +636,422 @@ mod tests {p}+ fn metadata_fixture(data: &str) -> (tempfile::TempDir, CursorAdapter, SessionFileRef) {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path().join("projects");+ let session_dir = root.join("wakefx-My-Project/agent-transcripts/session");+ fs::create_dir_all(&session_dir).unwrap();+ let file = write(+ &session_dir,+ "session.jsonl",+ r#"{"role":"user","message":{"content":[{"type":"text","text":"Transcript body"}]}}"#,+ );+ let db = dir.path().join("state.vscdb");+ let conn = rusqlite::Connection::open(&db).unwrap();+ conn.execute_batch("CREATE TABLE cursorDiskKV (key TEXT PRIMARY KEY, value BLOB)")+ .unwrap();+ conn.execute(+ "INSERT INTO cursorDiskKV VALUES ('composerData:session', ?1)",+ [data],+ )+ .unwrap();+ let adapter = CursorAdapter {+ root,+ metadata_db: Some(db),+ };+ let r = adapter.file_ref(&file).unwrap();+ (dir, adapter, r)+ }++ #[test]+ fn transcript_prefers_matching_metadata_and_keeps_its_body() {+ for data in [+ r#"{"workspaceIdentifier":{"uri":{"fsPath":"/wakefx/My Project"}},"trackedGitRepos":[{"repoPath":"/wrong/repo"}]}"#,+ r#"{"workspaceIdentifier":{"uri":{"fsPath":""}},"trackedGitRepos":[{"repoPath":"/wakefx/My Project"}]}"#,+ r#"{"trackedGitRepos":[{"repoPath":"/wakefx/My Project"}]}"#,+ r#"{"trackedGitRepos":[{"repoPath":"/other/repo"},{"repoPath":"/wakefx/My Project"}]}"#,+ ] {+ let (_dir, adapter, r) = metadata_fixture(data);+ let session = adapter.parse_session(&r).unwrap();+ let transcript = adapter.parse_transcript(&r).unwrap();+ for meta in [&session.meta, &transcript.meta] {+ assert_eq!(meta.project_path, "/wakefx/My Project");+ assert_eq!(meta.project_name, "My Project");+ assert_eq!(meta.file_path, r.file_path);+ assert_eq!(meta.title, "Transcript body");+ }+ assert_eq!(session.units.len(), 1);+ assert_eq!(transcript.mainline.len(), 1);+ assert_eq!(transcript.mainline[0].text, "Transcript body");+ }+ }++ #[test]+ fn transcript_falls_back_when_metadata_is_unavailable() {+ for data in [+ "{}",+ r#"{"workspaceIdentifier":{"uri":{"fsPath":""}}}"#,+ r#"{"trackedGitRepos":[{"repoPath":"/wakefx"}]}"#,+ "{broken",+ ] {+ let (_dir, adapter, r) = metadata_fixture(data);+ assert_eq!(+ adapter.parse_session(&r).unwrap().meta.project_path,+ "/wakefx/My/Project"+ );+ }++ let (dir, mut adapter, mut r) =+ metadata_fixture(r#"{"workspaceIdentifier":{"uri":{"fsPath":"/wrong/session"}}}"#);+ r.native_id = "unmapped".into();+ assert_eq!(+ adapter.parse_session(&r).unwrap().meta.project_path,+ "/wakefx/My/Project"+ );+ r.native_id = "session".into();+ adapter.metadata_db = Some(dir.path().join("missing.vscdb"));+ assert_eq!(+ adapter.parse_transcript(&r).unwrap().meta.project_path,+ "/wakefx/My/Project"+ );+ }++ #[cfg(unix)]+ #[test]+ fn repository_root_does_not_replace_existing_subdirectory_workspace() {+ let (dir, adapter, mut r) = metadata_fixture("{}");+ let repo = dir.path().join("repo");+ let project = repo.join("apps/client");+ fs::create_dir_all(&project).unwrap();+ let slug = project+ .to_str()+ .unwrap()+ .trim_start_matches('/')+ .replace('/', "-");+ let session_dir = adapter.root.join(slug).join("agent-transcripts/session");+ fs::create_dir_all(&session_dir).unwrap();+ let file = session_dir.join("session.jsonl");+ fs::rename(&r.file_path, &file).unwrap();+ r = adapter.file_ref(&file).unwrap();+ let conn = rusqlite::Connection::open(adapter.metadata_db.as_ref().unwrap()).unwrap();+ conn.execute(+ "UPDATE cursorDiskKV SET value = ?1 WHERE key = 'composerData:session'",+ [serde_json::json!({"trackedGitRepos": [{"repoPath": repo}]}).to_string()],+ )+ .unwrap();++ assert_eq!(+ adapter.parse_session(&r).unwrap().meta.project_path,+ project.to_str().unwrap()+ );+ assert_eq!(+ adapter.parse_transcript(&r).unwrap().meta.project_path,+ project.to_str().unwrap()+ );+ }++ #[test]+ fn metadata_updates_refresh_index_without_reparsing_transcript() {+ use crate::db::Store;+ use crate::mcp::tools::{self, TranscriptCache};+ use crate::scanner::{run_scan, NullEvents, ScanEvents, ScanProgress};+ use std::sync::{Arc, Mutex};++ #[derive(Default)]+ struct Events(Mutex<usize>, Mutex<usize>);+ impl ScanEvents for Events {+ fn on_progress(&self, progress: &ScanProgress) {+ *self.0.lock().unwrap() = progress.total;+ }+ fn on_sessions_changed(&self) {+ *self.1.lock().unwrap() += 1;+ }+ }++ let (dir, adapter, r) = metadata_fixture("{}");+ let metadata_db = adapter.metadata_db.clone().unwrap();+ let root = adapter.root.clone();+ let index = dir.path().join("wake.db");+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(adapter)];+ let store = Arc::new(Store::open(&index).unwrap());+ run_scan(&adapters, &store, &NullEvents, false).unwrap();+ let before = store.get_session("cursor:session").unwrap().unwrap();+ assert_eq!(before.project_path, "/wakefx/My/Project");+ let known = store.known_files().unwrap();+ let cache = TranscriptCache::default();+ let args = serde_json::json!({"key": "cursor:session"});+ assert!(+ tools::invoke(&store, &adapters, &cache, tools::GET_SESSION, &args)+ .unwrap()+ .contains("/wakefx/My/Project")+ );++ // Keep the writer open: the new metadata exists only in WAL, while the+ // transcript and the main database's modification time stay unchanged.+ let writer = rusqlite::Connection::open(&metadata_db).unwrap();+ writer.pragma_update(None, "journal_mode", "WAL").unwrap();+ let db_mtime = fs::metadata(&metadata_db).unwrap().modified().unwrap();+ writer+ .execute(+ "UPDATE cursorDiskKV SET value = ?1 WHERE key = 'composerData:session'",+ [r#"{"workspaceIdentifier":{"uri":{"fsPath":"/wakefx/My Project"}}}"#],+ )+ .unwrap();+ assert_eq!(+ fs::metadata(&metadata_db).unwrap().modified().unwrap(),+ db_mtime+ );+ assert_eq!(+ adapters[0]+ .file_ref(Path::new(&r.file_path))+ .unwrap()+ .mtime_ms,+ r.mtime_ms+ );+ let events = Events::default();+ run_scan(&adapters, &store, &events, false).unwrap();+ let after = store.get_session("cursor:session").unwrap().unwrap();+ assert_eq!(after.project_path, "/wakefx/My Project");+ assert_eq!(after.project_name, "My Project");+ assert_eq!(after.title, before.title);+ assert_eq!(after.message_count, before.message_count);+ assert_eq!(after.file_path, before.file_path);+ assert_eq!(store.known_files().unwrap(), known);+ let shown = tools::invoke(&store, &adapters, &cache, tools::GET_SESSION, &args).unwrap();+ assert!(+ shown.contains("/wakefx/My Project"),+ "cached query still has old project: {shown}"+ );+ assert!(!shown.contains("/wakefx/My/Project"));+ assert_eq!(*events.0.lock().unwrap(), 0, "no transcript reparsing");+ assert_eq!(+ *events.1.lock().unwrap(),+ 1,+ "notify the UI of the new project"+ );+ let conn = rusqlite::Connection::open(&index).unwrap();+ assert_eq!(+ conn.query_row(+ "SELECT text FROM messages_fts WHERE messages_fts MATCH 'Transcript'",+ [],+ |row| row.get::<_, String>(0),+ )+ .unwrap(),+ "Transcript body"+ );++ let unchanged = Events::default();+ run_scan(&adapters, &store, &unchanged, false).unwrap();+ assert_eq!(+ *unchanged.1.lock().unwrap(),+ 0,+ "unchanged metadata is a no-op"+ );+ drop(store);++ // A new process/adapter must also notice later metadata changes.+ writer+ .execute(+ "UPDATE cursorDiskKV SET value = ?1 WHERE key = 'composerData:session'",+ [r#"{"workspaceIdentifier":{"uri":{"fsPath":"/wakefx/Relocated Project"}}}"#],+ )+ .unwrap();+ let store = Arc::new(Store::open(&index).unwrap());+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(CursorAdapter {+ root,+ metadata_db: Some(metadata_db),+ })];+ let events = Events::default();+ run_scan(&adapters, &store, &events, false).unwrap();+ assert_eq!(+ store+ .get_session("cursor:session")+ .unwrap()+ .unwrap()+ .project_path,+ "/wakefx/Relocated Project"+ );+ assert_eq!(*events.0.lock().unwrap(), 0);+ // A temporary read/JSON failure must not erase a known project path.+ writer+ .execute("UPDATE cursorDiskKV SET value = '{broken'", [])+ .unwrap();+ run_scan(&adapters, &store, &NullEvents, false).unwrap();+ assert_eq!(+ store+ .get_session("cursor:session")+ .unwrap()+ .unwrap()+ .project_path,+ "/wakefx/Relocated Project"+ );+ }++ #[test]+ fn upgrade_refreshes_existing_cursor_project_without_source_changes() {+ use crate::db::Store;+ use crate::scanner::{run_scan, NullEvents};+ use std::sync::Arc;++ let (dir, adapter, r) =+ metadata_fixture(r#"{"workspaceIdentifier":{"uri":{"fsPath":"/wakefx/My Project"}}}"#);+ let index = dir.path().join("upgrade.db");+ let mut old = adapter.parse_session(&r).unwrap();+ old.meta.project_path = "/wakefx/My/Project".into();+ old.meta.project_name = "Project".into();+ {+ let store = Store::open(&index).unwrap();+ store+ .write_session(&old.meta, r.mtime_ms, &old.units)+ .unwrap();+ }+ rusqlite::Connection::open(&index)+ .unwrap()+ .execute(+ "UPDATE schema_meta SET value = '3' WHERE key = 'fts_format'",+ [],+ )+ .unwrap();+ let store = Arc::new(Store::open(&index).unwrap());+ assert!(store.needs_fts_reindex());+ run_scan(&[Box::new(adapter)], &store, &NullEvents, false).unwrap();+ assert_eq!(+ store+ .get_session("cursor:session")+ .unwrap()+ .unwrap()+ .project_path,+ "/wakefx/My Project"+ );+ assert!(!store.needs_fts_reindex());+ }++ #[test]+ fn project_refresh_only_updates_the_unchanged_winning_copy() {+ use crate::db::Store;++ let (dir, adapter, r) =+ metadata_fixture(r#"{"workspaceIdentifier":{"uri":{"fsPath":"/wakefx/My Project"}}}"#);+ let parsed = adapter.parse_session(&r).unwrap();+ let updates = adapter.project_path_updates(std::slice::from_ref(&r));+ for case in ["unchanged", "newer", "resized", "other-copy", "child"] {+ let index = dir.path().join(format!("{case}.db"));+ let store = Store::open(&index).unwrap();+ let mut saved = parsed.meta.clone();+ saved.project_path = "/saved/project".into();+ saved.project_name = "project".into();+ let mtime = if case == "newer" {+ r.mtime_ms + 1+ } else {+ r.mtime_ms+ };+ if case == "resized" {+ saved.size_bytes += 1;+ }+ if case == "other-copy" {+ saved.file_path.push_str(".copy");+ }+ store.write_session(&saved, mtime, &parsed.units).unwrap();+ if case == "child" {+ rusqlite::Connection::open(&index)+ .unwrap()+ .execute("UPDATE sessions SET parent_key = 'cursor:parent'", [])+ .unwrap();+ }+ let changed = store+ .update_project_paths(std::slice::from_ref(&r), &updates)+ .unwrap();+ assert_eq!(changed, case == "unchanged", "{case}");+ let after = store.get_session(&saved.key).unwrap().unwrap();+ assert_eq!(+ after.project_path,+ if changed {+ "/wakefx/My Project"+ } else {+ "/saved/project"+ },+ "{case}"+ );+ assert_eq!(after.file_path, saved.file_path);+ }+ }++ #[test]+ fn custom_root_does_not_use_default_project_metadata() {+ let (_dir, adapter, r) =+ metadata_fixture(r#"{"workspaceIdentifier":{"uri":{"fsPath":"/local/My Project"}}}"#);+ let custom = adapter.with_custom_root(adapter.root.clone());+ assert_eq!(+ custom.parse_session(&r).unwrap().meta.project_path,+ "/wakefx/My/Project"+ );+ assert_eq!(+ custom.parse_transcript(&r).unwrap().meta.project_path,+ "/wakefx/My/Project"+ );+ assert!(custom+ .project_path_updates(std::slice::from_ref(&r))+ .is_empty());+ }++ #[test]+ fn slug_decoder_recovers_existing_directory_with_spaces() {+ let dir = tempfile::tempdir().expect("tempdir");+ for (name, slug) in [+ ("My Project", "My-Project"),+ ("My Project/source-code", "My-Project-source-code"),+ ] {+ let project = dir.path().join(name);+ fs::create_dir_all(&project).unwrap();+ assert_eq!(+ decode_existing_slug(dir.path().to_path_buf(), slug),+ Some(project)+ );+ }+ }++ #[test]+ fn slug_decoder_prefers_literal_hyphen_when_ambiguous() {+ for (slug, alternative) in [+ ("image-translate", "image translate"),+ ("image-translate-src", "image translate/src"),+ ] {+ let dir = tempfile::tempdir().unwrap();+ let literal = dir.path().join(slug);+ fs::create_dir(&literal).unwrap();+ fs::create_dir_all(dir.path().join(alternative)).unwrap();+ assert_eq!(+ decode_existing_slug(dir.path().to_path_buf(), slug),+ Some(literal)+ );+ }+ }++ #[test]+ fn slug_decoder_respects_filesystem_case_matching() {+ let dir = tempfile::tempdir().unwrap();+ fs::create_dir(dir.path().join("Mixed-Case")).unwrap();+ let path = dir.path().join("mixed-case");+ assert_eq!(+ decode_existing_slug(dir.path().to_path_buf(), "mixed-case"),+ path.is_dir().then_some(path)+ );+ }++ #[cfg(unix)]+ #[test]+ fn slug_decoder_does_not_require_parent_read_permission() {+ use std::os::unix::fs::PermissionsExt;++ let dir = tempfile::tempdir().unwrap();+ let project = dir.path().join("my-project");+ fs::create_dir(&project).unwrap();+ fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o111)).unwrap();+ let decoded = decode_existing_slug(dir.path().to_path_buf(), "my-project");+ fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o700)).unwrap();+ assert_eq!(decoded, Some(project));+ }+/// 判据必须与文件大小无关。曾经的实现对 >64KB 的文件直接判"有正文"/// 早退——空壳按每回合一行增长,约 1600 轮后就会越过这条线,于是/// **恰好最长最活跃**的那些 IDE 会话重新落回 0 消息(2026-09-14 review)diff --git a/crates/wake-core/src/adapters/cursor_ide.rs b/crates/wake-core/src/adapters/cursor_ide.rsindex 421debc..3a221a2 100644--- a/crates/wake-core/src/adapters/cursor_ide.rs+++ b/crates/wake-core/src/adapters/cursor_ide.rs@@ -5,16 +5,16 @@ use crate::models::*;use anyhow::{anyhow, Result};use serde_json::Value;use std::collections::HashMap;-use std::path::PathBuf;+use std::path::{Path, PathBuf};/// Cursor IDE 内的 Chat/Composer 历史:`~/Library/Application Support/Cursor/-/// User/globalStorage/state.vscdb`(Linux/Windows 换用户数据根,见 storage_dir)。+/// User/globalStorage/state.vscdb`(Linux/Windows 换用户数据根,见 default_db_path)。/// **与 cursor.rs 是同一家的两个数据源**:CLI(`cursor-agent`)把完整对话写/// `~/.cursor/.../agent-transcripts/*.jsonl`,IDE 面板只把回合标记/// (`{"type":"turn_ended"}`)写进那里、正文全留在本库——所以 IDE 会话在只读/// JSONL 的旧实现里是空壳。两源同 native_id 的重叠交 scanner 的副本裁决,-/// 本源以 `dedup_rank` 排在 CLI 源之后:转录带正文时 CLI 那份胜出(它有 slug-/// 可反推项目,本库多数会话没有工作区路径),本源那份留作解析失败的回退;+/// 本源以 `dedup_rank` 排在 CLI 源之后:转录带正文时 CLI 那份胜出,+/// 并可从本库补充项目路径;本源那份正文留作解析失败的回退;/// 只有转录缺失或只剩空壳的会话才由本源胜出。不按 mtime 定胜负——两边写盘/// 先后不固定,同一会话会在项目之间跳(2026-09-15 实测)。///@@ -47,13 +47,13 @@ pub struct CursorIdeAdapter {links_cache: MtimeCache<Vec<(String, String)>>,}-/// `globalStorage/state.vscdb` 的宿主目录。VS Code 系三平台的用户数据根不同:+/// `globalStorage/state.vscdb` 的默认路径。VS Code 系三平台的用户数据根不同:/// macOS 在 `~/Library/Application Support`,Windows 在 `%APPDATA%`,/// Linux 在 `$XDG_CONFIG_HOME`(缺省 `~/.config`)。这里只做路径推导、/// 不探测存在性——缺根由 list_session_files 降级为空(roster 契约)。/// 三平台都从 `home_dir()` 派生而非 `dirs::config_dir()`:后者在 Windows 上/// 走 SHGetKnownFolderPath,`WAKE_HOME` 改道对它无效(见 mod.rs 的 home_dir)-fn storage_dir() -> PathBuf {+pub(super) fn default_db_path() -> PathBuf {let home = super::home_dir().unwrap_or_default();let base = if cfg!(target_os = "macos") {home.join("Library").join("Application Support")@@ -62,12 +62,78 @@ fn storage_dir() -> PathBuf {} else {super::env_dir("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config"))};- base.join("Cursor").join("User").join("globalStorage")+ base.join("Cursor")+ .join("User")+ .join("globalStorage")+ .join(DB_NAME)+}++fn project_path_from_data(data: &Value) -> Option<&str> {+ [+ "/workspaceIdentifier/uri/fsPath",+ "/trackedGitRepos/0/repoPath",+ ]+ .iter()+ .find_map(|path| data.pointer(path)?.as_str().filter(|s| !s.is_empty()))+}++pub(super) struct ProjectMetadata {+ pub workspace: Option<String>,+ pub repositories: Vec<String>,+}++/// Read only the requested composers, sharing one connection across a scan.+/// Keep workspace and repository paths distinct: a repo may contain the actual+/// workspace, or be one of several repos inside it.+pub(super) fn project_metadata<'a>(+ db: &Path,+ ids: impl Iterator<Item = &'a str>,+) -> Option<HashMap<String, ProjectMetadata>> {+ let ro = open_sqlite_ro(db, "cursor-project")?;+ let mut stmt = ro+ .conn+ .prepare("SELECT CAST(value AS TEXT) FROM cursorDiskKV WHERE key = ?1")+ .ok()?;+ let mut paths = HashMap::new();+ for id in ids {+ let Ok(raw) = stmt.query_row([format!("{COMPOSER_PREFIX}{id}")], |r| {+ r.get::<_, String>(0)+ }) else {+ continue;+ };+ let Ok(data) = serde_json::from_str::<Value>(&raw) else {+ continue;+ };+ let workspace = data+ .pointer("/workspaceIdentifier/uri/fsPath")+ .and_then(Value::as_str)+ .filter(|s| !s.is_empty())+ .map(str::to_string);+ let repositories = data+ .get("trackedGitRepos")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|repo| repo.get("repoPath")?.as_str())+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .collect::<Vec<_>>();+ if workspace.is_some() || !repositories.is_empty() {+ paths.insert(+ id.to_string(),+ ProjectMetadata {+ workspace,+ repositories,+ },+ );+ }+ }+ Some(paths)}impl CursorIdeAdapter {pub fn new() -> Self {- Self::at(storage_dir().join(DB_NAME))+ Self::at(default_db_path())}fn at(db: PathBuf) -> Self {@@ -417,14 +483,7 @@ impl IdeRow {.get("lastUpdatedAt").and_then(|v| v.as_i64()).unwrap_or(0);- let cwd = data- .pointer("/workspaceIdentifier/uri/fsPath")- .and_then(|v| v.as_str())- .or_else(|| {- data.pointer("/trackedGitRepos/0/repoPath")- .and_then(|v| v.as_str())- })- .unwrap_or_default();+ let cwd = project_path_from_data(data).unwrap_or_default();Self {id: id.to_string(),name: datadiff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rsindex ab66e8f..fda6584 100644--- a/crates/wake-core/src/adapters/mod.rs+++ b/crates/wake-core/src/adapters/mod.rs@@ -64,6 +64,15 @@ pub trait AgentAdapter: Send + Sync {) -> Option<std::collections::HashMap<String, SessionMeta>> {None}+ /// Refresh project metadata from sidecars even when the transcript did not+ /// change. Keys are source file paths; only existing, unchanged winning+ /// copies are updated, without replacing their body or source timestamps.+ fn project_path_updates(+ &self,+ _refs: &[SessionFileRef],+ ) -> std::collections::HashMap<String, String> {+ Default::default()+ }/// quick 与 parsed 的合并策略:默认 parsed 为准、quick 补缺。/// Codex 覆写(state DB 的 title 是用户手动命名,优先级更高)。fn merge_quick_meta(&self, mut parsed: SessionMeta, quick: &SessionMeta) -> SessionMeta {diff --git a/crates/wake-core/src/adapters/remote.rs b/crates/wake-core/src/adapters/remote.rsindex 4933870..76e6a0e 100644--- a/crates/wake-core/src/adapters/remote.rs+++ b/crates/wake-core/src/adapters/remote.rs@@ -111,6 +111,13 @@ impl AgentAdapter for RemoteAdapter {self.inner.merge_quick_meta(parsed, quick)}+ fn project_path_updates(+ &self,+ refs: &[SessionFileRef],+ ) -> std::collections::HashMap<String, String> {+ self.inner.project_path_updates(refs)+ }+fn parse_session(&self, r: &SessionFileRef) -> Result<ParsedSession> {let mut parsed = self.inner.parse_session(r)?;self.rewrite_meta(&mut parsed.meta);diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rsindex 984baca..111d62b 100644--- a/crates/wake-core/src/db.rs+++ b/crates/wake-core/src/db.rs@@ -133,8 +133,9 @@ CREATE VIRTUAL TABLE IF NOT EXISTS titles_fts USING fts5(/// 会话元数据和 FTS 单元的派生规则版本(`adapters::units_from_messages` 及其上游解析)。改了派生/// 规则就换个值:旧库首开时挂 fts_reindex 旗子,下一轮扫描强制重解析全部文件。/// "1" = 2026-09-14 前(工具段不过滤 Wake 自指),"2" = 过滤自指回声,-/// "3" = Pi / omp / OpenClaw 累计每次 assistant 调用的 token。-pub const FTS_FORMAT: &str = "3";+/// "3" = Pi / omp / OpenClaw 累计每次 assistant 调用的 token,+/// "4" = Cursor 项目路径优先读取工作区元数据,并恢复 slug 中的空格。+pub const FTS_FORMAT: &str = "4";fn open_conn(path: &Path) -> Result<Connection> {if let Some(dir) = path.parent() {@@ -431,6 +432,36 @@ impl Store {Ok(())}+ /// Sidecar-only updates must not replace transcript contents or steal a+ /// session from another copy. Changed files go through normal parsing;+ /// children inherit their project through replace_parent_links instead.+ pub(crate) fn update_project_paths(+ &self,+ refs: &[SessionFileRef],+ paths: &HashMap<String, String>,+ ) -> Result<bool> {+ if paths.is_empty() {+ return Ok(false);+ }+ let mut conn = self.write.lock().unwrap();+ let tx = conn.transaction()?;+ let mut changed = false;+ for r in refs {+ let Some(project) = paths.get(&r.file_path).filter(|p| !p.is_empty()) else {+ continue;+ };+ let name = crate::adapters::parse_utils::project_name_of(project);+ changed |= tx.execute(+ "UPDATE sessions SET project_path = ?1, project_name = ?2+ WHERE file_path = ?3 AND file_mtime = ?4 AND file_size = ?5+ AND parent_key = '' AND (project_path <> ?1 OR project_name <> ?2)",+ params![project, name, r.file_path, r.mtime_ms, r.size],+ )? > 0;+ }+ tx.commit()?;+ Ok(changed)+ }+/// schema_meta 里的一次性旗子(升级后要补做的事),做完由 scanner 清掉fn has_meta_flag(&self, key: &str) -> bool {let conn = self.read.lock().unwrap();diff --git a/crates/wake-core/src/mcp/tools.rs b/crates/wake-core/src/mcp/tools.rsindex 3138506..a1ff0a1 100644--- a/crates/wake-core/src/mcp/tools.rs+++ b/crates/wake-core/src/mcp/tools.rs@@ -25,10 +25,18 @@ struct ToolContext<'a> {}/// 单槽转录缓存:分页读同一会话时不必每页整文件重解析(默认 20k 字符一页,-/// 大会话几十页)。键是 scanner 同款的脏判据 (file_path, mtime, size),文件一-/// 变即失效;server 进程随客户端会话长驻,连续翻页总是同一文件+/// 大会话几十页)。源文件或索引中的项目归属变化即失效;server 进程随客户端+/// 会话长驻,连续翻页总是同一文件。项目归属可由边车更新,不必修改正文。#[derive(Default)]-pub struct TranscriptCache(Mutex<Option<(String, i64, i64, Arc<ParsedTranscript>)>>);+pub struct TranscriptCache(Mutex<Option<CachedTranscript>>);++struct CachedTranscript {+ path: String,+ mtime: i64,+ size: i64,+ indexed_project: String,+ transcript: Arc<ParsedTranscript>,+}impl TranscriptCache {fn get_or_parse(@@ -46,13 +54,23 @@ impl TranscriptCache {let db = crate::adapters::sqlite_ro::strip_virtual_path(&r.file_path);crate::adapters::sqlite_ro::db_cache_stamp(std::path::Path::new(db))};- if let Some((path, mtime, size, t)) = self.0.lock().unwrap().as_ref() {- if *path == r.file_path && *mtime == stamp && *size == r.size {- return Ok(t.clone());+ if let Some(cached) = self.0.lock().unwrap().as_ref() {+ if cached.path == r.file_path+ && cached.mtime == stamp+ && cached.size == r.size+ && cached.indexed_project == meta.project_path+ {+ return Ok(cached.transcript.clone());}}let t = Arc::new(adapter.parse_transcript(&r)?);- *self.0.lock().unwrap() = Some((r.file_path.clone(), stamp, r.size, t.clone()));+ *self.0.lock().unwrap() = Some(CachedTranscript {+ path: r.file_path,+ mtime: stamp,+ size: r.size,+ indexed_project: meta.project_path.clone(),+ transcript: t.clone(),+ });Ok(t)}}diff --git a/crates/wake-core/src/scanner.rs b/crates/wake-core/src/scanner.rsindex e93c56d..8568ff4 100644--- a/crates/wake-core/src/scanner.rs+++ b/crates/wake-core/src/scanner.rs@@ -297,6 +297,12 @@ fn run_scan_inner(seen_paths.insert(r.file_path.clone());}+ // Sidecar metadata can arrive after the transcript's final write.+ // Refresh it independently of the mtime/size gate and notify the UI.+ if store.update_project_paths(&refs, &adapter.project_path_updates(&refs))? {+ events.on_sessions_changed();+ }+// 快路径:新/变化的先写 meta 让列表立即可见let quick_map = adapter.quick_meta(&refs);if let Some(map) = &quick_map {