All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
feat: read archive state, nesting and names from the Claude desktop app
Corey Chiu989c883f3344
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1c7abba..e2f6532 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## [Unreleased]++- New: Sessions you start from another session in the Claude desktop app are listed under that session, as they are in the app+- Fix: Claude Code sessions you archive in the Claude desktop app are archived in Wake too+- Fix: Claude Code sessions left as "New session" take the name you gave them in the Claude desktop app, or else their first message+## [0.9.4] — 2026-10-15- Fix: Refresh picks up sessions you deleted in OpenCode while it was still running, instead of listing them until Wake restarts (#70, thanks @lin-code-world)diff --git a/crates/wake-core/src/adapters/claude.rs b/crates/wake-core/src/adapters/claude.rsindex e64f6bf..87ccf19 100644--- a/crates/wake-core/src/adapters/claude.rs+++ b/crates/wake-core/src/adapters/claude.rs@@ -1,3 +1,4 @@+use super::claude_desktop::{DesktopIndex, Owned, PLACEHOLDER_TITLE};use super::parse_utils::*;use super::AgentAdapter;use crate::models::*;@@ -44,6 +45,9 @@ pub struct ClaudeAdapter {decoded: Mutex<HashMap<String, Option<String>>>,/// 分支识别的缓存(见 `BranchCache`)branches: Mutex<BranchCache>,+ /// Claude 桌面端的会话记录(归档位在那里,见 `claude_desktop`)。只给默认根:记录里的+ /// CLI 会话 id 指的是本机 ~/.claude 里的转录+ desktop: Option<DesktopIndex>,}// ---------------- 分支(续接)识别 ----------------@@ -203,6 +207,12 @@ fn read_head(path: &Path, born: Option<i64>) -> Head {head}+/// `custom-title` 行里的名字。桌面端的占位名不算名字:它写在会话刚建好的时候,之后起的名字+/// 只写进当时那一条 CLI 会话,/clear、resume 之前的那几条就一直顶着它+fn custom_title_of(v: Option<&Value>) -> Option<String> {+ optional_string(v).filter(|t| t != PLACEHOLDER_TITLE)+}+/// 读整份文件的 uuid 集合与最后一条自定义标题。逐行只反序列化这三个字段;坏行跳过,/// 读错误整份失败(读不全就宁可不折)fn read_lineage(path: &Path) -> Result<Lineage> {@@ -221,9 +231,9 @@ fn read_lineage(path: &Path) -> Result<Lineage> {if let Some(uuid) = row.uuid.filter(|u| !u.is_empty()) {uuids.insert(uuid);}- // 与解析同一个取法(optional_string),分支标题与原件标题才比得上+ // 与解析同一个取法(custom_title_of),分支标题与原件标题才比得上if row.typ.as_deref() == Some("custom-title") {- title = optional_string(row.custom_title.as_ref()).or(title);+ title = custom_title_of(row.custom_title.as_ref()).or(title);}}Ok(Lineage {@@ -235,7 +245,10 @@ fn read_lineage(path: &Path) -> Result<Lineage> {impl ClaudeAdapter {pub fn new() -> Self {let home = super::home_dir().unwrap_or_default().join(".claude");- Self::at(home.join("projects"), Some(home), true)+ Self {+ desktop: Some(DesktopIndex::new(super::claude_desktop::sessions_root())),+ ..Self::at(home.join("projects"), Some(home), true)+ }}fn at(root: PathBuf, home: Option<PathBuf>, local: bool) -> Self {@@ -246,9 +259,27 @@ impl ClaudeAdapter {memories: super::MemoryCache::new(),decoded: Mutex::new(HashMap::new()),branches: Mutex::new(BranchCache::default()),+ desktop: None,}}+ /// 测试用:桌面端记录放在给定目录+ #[cfg(test)]+ pub(crate) fn with_desktop(root: PathBuf, desktop: PathBuf) -> Self {+ Self {+ desktop: Some(DesktopIndex::new(desktop)),+ ..Self::at(root, None, false)+ }+ }++ /// Claude 桌面端记着的 CLI 会话:归档位与标题(没有桌面端记录的实例恒空)+ fn desktop_owned(&self) -> HashMap<String, Owned> {+ self.desktop+ .as_ref()+ .map(DesktopIndex::owned)+ .unwrap_or_default()+ }+/// 一个项目目录里的分支(见 `DirBranches`)。目录没变就直接用上次的分组,一次 stat;/// 变了只读新来文件的头。文件 I/O 不持锁——扫描、watcher、GUI 打开详情、导出可能同时问fn branches_in(&self, dir: &Path) -> Arc<HashMap<PathBuf, Branch>> {@@ -315,6 +346,43 @@ impl ClaudeAdapter {Some(r)}+ /// `file_ref` 去掉桌面端那几位:子代理转录(及边车)或会话主文件+ fn own_ref(&self, path: &Path) -> Option<SessionFileRef> {+ // 子代理转录与它的边车。会话目录得在数据根下的项目目录里+ let in_project =+ |session: &Path| session.parent().and_then(Path::parent) == Some(self.root.as_path());+ if let Some(r) = subagent_event_ref(AgentId::ClaudeCode, path, in_project) {+ return Some(r);+ }+ // 会话主文件只在 `<projects>/<项目目录>/` 这一层:更深的(memory 边车、Workflow 的+ // 运行日志 journal.jsonl)都不是。按路径分段比,Windows 的反斜杠路径一样认+ let dir = path.parent()?;+ if dir.parent() != Some(self.root.as_path()) {+ return None;+ }+ self.session_ref(path, &self.branches_in(dir))+ }++ /// 桌面端一份会话记录名下的转录(连同子代理的):watcher 看到记录变了,交它们按引用重比+ fn transcripts_of(&self, ids: &[String]) -> Vec<PathBuf> {+ let Ok(projects) = fs::read_dir(&self.root) else {+ return Vec::new();+ };+ let mut transcripts = Vec::new();+ for project in projects.flatten() {+ let dir = project.path();+ for id in ids {+ let transcript = dir.join(format!("{id}.jsonl"));+ if transcript.is_file() {+ transcripts.push(transcript);+ }+ // 主转录被清掉、会话目录还在时,里面的子代理照样在索引里+ transcripts.extend(subagent_transcripts(&dir.join(id)));+ }+ }+ transcripts+ }+/// 一份文件的 uuid 集合(按 mtime + size 缓存;读文件不持锁)fn lineage(&self, path: &Path) -> Result<Lineage> {let meta = fs::metadata(path)?;@@ -374,6 +442,14 @@ impl ClaudeAdapter {let parsed = parse_claude_jsonl(path, subagent, decode_images, inherited.as_ref())?;let mut meta = build_meta(r, &parsed);mark_subagent(&mut meta, path);+ let desktop = self.desktop_owned();+ meta.archived = archived_in(&desktop, r);+ // 转录里没起过名字(或只有桌面端的占位名):用桌面会话的名字,再退回首条提问+ if !parsed.titled {+ if let Some(title) = desktop_title(&desktop, r) {+ meta.title = title.to_string();+ }+ }Ok((meta, parsed))}@@ -454,6 +530,8 @@ fn decode_project_dir(name: &str) -> Option<String> {struct ParseResult {messages: Vec<TranscriptMessage>,title: String,+ /// 标题是转录里起的名字(`custom-title`),不是退回来的首条提问+ titled: bool,cwd: String,git_branch: Option<String>,model: Option<String>,@@ -577,7 +655,7 @@ fn parse_claude_jsonl(}if typ == "custom-title" {- if let Some(t) = optional_string(row.get("customTitle")) {+ if let Some(t) = custom_title_of(row.get("customTitle")) {custom_title = t;}continue;@@ -819,6 +897,7 @@ fn parse_claude_jsonl(assign_seq(&mut messages);Ok(ParseResult {+ titled: !custom_title.is_empty(),title: if !custom_title.is_empty() {custom_title} else if !fallback_title.is_empty() {@@ -860,6 +939,37 @@ fn mk_msg(role: Role, kind: MessageKind, text: &str, ts: i64) -> TranscriptMessa}}+/// 这份转录在 Claude 桌面端归档了没有。子代理跟着派它的会话:父会话归档了、子代理还开着,+/// 列表会把子代理当成没有父会话的顶层会话列出来+fn archived_in(desktop: &HashMap<String, Owned>, r: &SessionFileRef) -> bool {+ let parent = subagent_parent(Path::new(&r.file_path));+ desktop+ .get(parent.as_deref().unwrap_or(&r.native_id))+ .is_some_and(|owned| owned.archived)+}++/// 桌面会话的名字(子代理不用它,它的标题是派活时的任务说明)+fn desktop_title<'a>(desktop: &'a HashMap<String, Owned>, r: &SessionFileRef) -> Option<&'a str> {+ if is_subagent_transcript(&r.file_path) {+ return None;+ }+ desktop.get(&r.native_id)?.title.as_deref()+}++/// 桌面端记的归档位与标题合起来取指纹,并进引用的 size:在桌面端归档、取消归档、改名时转录+/// 未必动,全量扫描按引用认出它变了、重解析。不是 +1:分支的引用也往 size 里加着更早的同根+/// 文件数,两样同时变(删掉中间那份分支、又归档了它的分支)会正好抵消。列表与 file_ref 各在+/// 出口盖一次+fn stamp_desktop(mut r: SessionFileRef, desktop: &HashMap<String, Owned>) -> SessionFileRef {+ let archived = archived_in(desktop, &r);+ let title = desktop_title(desktop, &r);+ if archived || title.is_some() {+ let archived = if archived { "archived" } else { "" };+ r.size += sidecar_fingerprint(&[archived, title.unwrap_or("")]);+ }+ r+}+fn build_meta(r: &SessionFileRef, p: &ParseResult) -> SessionMeta {let project_name = project_name_of(&p.cwd);SessionMeta {@@ -947,7 +1057,11 @@ impl AgentAdapter for ClaudeAdapter {}}}- Ok(refs)+ let desktop = self.desktop_owned();+ Ok(refs+ .into_iter()+ .map(|r| stamp_desktop(r, &desktop))+ .collect())}fn parse_session(&self, r: &SessionFileRef) -> Result<ParsedSession> {@@ -980,8 +1094,13 @@ impl AgentAdapter for ClaudeAdapter {}/// 项目目录里的会话文件进出(原件被删、被放回)会改变同目录分支的引用(`session_ref`- /// 数着更早的同根文件):交出同目录的其余会话文件,watcher 按引用重比、变了的重解析+ /// 数着更早的同根文件):交出同目录的其余会话文件,watcher 按引用重比、变了的重解析。+ /// 桌面端的会话记录变了(在桌面端归档、改名)同理:交出它名下的转录。记录从不入库,它的+ /// 每次改动 watcher 都会来问,而桌面端每次聚焦都重写它——Wake 用得上的内容没变就不交fn ref_dependents(&self, path: &Path) -> Vec<PathBuf> {+ if let Some(ids) = self.desktop.as_ref().and_then(|d| d.take_change(path)) {+ return self.transcripts_of(&ids);+ }let Some(dir) = path.parent().filter(|dir| dir.parent() == Some(self.root.as_path()))@@ -1003,24 +1122,14 @@ impl AgentAdapter for ClaudeAdapter {}fn file_ref(&self, path: &Path) -> Option<SessionFileRef> {- // 子代理转录与它的边车。会话目录得在数据根下的项目目录里- let in_project =- |session: &Path| session.parent().and_then(Path::parent) == Some(self.root.as_path());- if let Some(r) = subagent_event_ref(AgentId::ClaudeCode, path, in_project) {- return Some(r);- }- // 会话主文件只在 `<projects>/<项目目录>/` 这一层:更深的(memory 边车、Workflow 的- // 运行日志 journal.jsonl)都不是。按路径分段比,Windows 的反斜杠路径一样认- let dir = path.parent()?;- if dir.parent() != Some(self.root.as_path()) {- return None;- }- self.session_ref(path, &self.branches_in(dir))+ let r = self.own_ref(path)?;+ Some(stamp_desktop(r, &self.desktop_owned()))}- /// 分支挂到原件下面(见本文件「分支识别」),子代理挂到派它的会话下面(`parent_in_path`)。- /// 分支的关系由它自己的文件头与同目录里更早的同根文件推出,所以算"写在子会话里"(多- /// location 下按子会话的胜出副本认边)+ /// 分支挂到原件下面(见本文件「分支识别」),子代理挂到派它的会话下面(`parent_in_path`),+ /// 桌面端派出去的会话挂到派它的会话下面(`claude_desktop`)。分支的关系由它自己的文件头与+ /// 同目录里更早的同根文件推出,派生关系记在子会话自己的桌面端记录里,所以都算"写在子会话+ /// 里"(多 location 下按子会话的胜出副本认边)fn manages_parent_links(&self) -> bool {true}@@ -1037,8 +1146,8 @@ impl AgentAdapter for ClaudeAdapter {/// 全量快照只用文件头(不读 uuid 集合):每个分支 → 它所在同根组里最早的那份。分支/// 的分支也直接挂到原件上——scanner 本来就把链压平到根。目录没变的,分组直接复用- /// (每批 watcher 事件都会问一遍,每个目录一次 stat)。projects 目录不在 = 确定没有- /// 关系;在却列不出来是"不知道",交 None 让 scanner 保留库里的关系+ /// (每批 watcher 事件都会问一遍,每个目录一次 stat)。再加上桌面端侧栏的嵌套。projects+ /// 目录不在 = 确定没有关系;在却列不出来是"不知道",交 None 让 scanner 保留库里的关系fn parent_links(&self) -> Option<Vec<(String, String)>> {let projects = match fs::read_dir(&self.root) {Ok(projects) => projects,@@ -1057,9 +1166,33 @@ impl AgentAdapter for ClaudeAdapter {}}}+ // 桌面端侧栏的嵌套:同一个会话既是分支又是派出去的(fork 了上下文的侧会话)时,以转录里+ // 看得见的分支关系为准+ let spawned = self+ .desktop+ .as_ref()+ .map(DesktopIndex::spawn_links)+ .unwrap_or_default();+ let branched: HashSet<String> = links.iter().map(|(child, _)| child.clone()).collect();+ links.extend(+ super::link_keys(+ AgentId::ClaudeCode,+ spawned+ .iter()+ .map(|(child, parent)| (child.as_str(), parent.as_str())),+ )+ .into_iter()+ .filter(|(child, _)| !branched.contains(child)),+ );Some(links)}+ /// 桌面端的会话记录变了(新派出一个会话、派它的会话 /clear 换了当前那条):父子关系跟着+ /// 刷新。记录里的转录没动,收不到别的事件;只是聚焦一下重写了记录不算+ fn is_snapshot_event(&self, path: &Path) -> bool {+ self.desktop.as_ref().is_some_and(|d| d.changed(path))+ }+/// 子代理挂到派它的会话:所在会话目录的名字就是那个会话的 idfn parent_in_path(&self) -> Option<super::ParentInPath> {Some(subagent_parent)@@ -1130,11 +1263,24 @@ impl AgentAdapter for ClaudeAdapter {fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ /// 数据根之外再听桌面端的会话记录:在桌面端归档、取消归档只改那份记录,转录不动,+ /// 不听它就要等下一轮全量扫描(`ref_dependents` 把记录换成它名下的转录)。记录不是会话+ /// 文件,不进 data_roots+ fn watch_paths(&self) -> Vec<PathBuf> {+ let desktop = self.desktop.as_ref().map(|d| d.root().to_path_buf());+ self.data_roots()+ .into_iter()+ .chain(desktop)+ .filter(|p| p.is_dir())+ .collect()+ }}#[cfg(test)]mod tests {use super::*;+ use crate::adapters::claude_desktop::write_test_record;fn head(root: &str, first_ts: i64, born: Option<i64>) -> Head {Head {@@ -1246,6 +1392,148 @@ mod tests {);}+ /// 在 Claude 桌面端归档:归档位并进引用(列表与 file_ref 一致)、解析出来的会话标成归档,+ /// 子代理跟着派它的会话;记录变了交出名下的转录让 watcher 重比;取消归档原样退回+ #[test]+ fn archiving_in_the_desktop_app_reaches_refs_and_meta() {+ let tmp = tempfile::tempdir().unwrap();+ let projects = tmp.path().join("projects");+ let dir = projects.join("-w");+ let subagents = dir.join("sess-a").join("subagents");+ fs::create_dir_all(&subagents).unwrap();+ let line = |id: &str, sidechain: bool| {+ format!(+ r#"{{"type":"user","uuid":"u-{id}","isSidechain":{sidechain},"timestamp":"2026-09-01T08:00:01.000Z","sessionId":"{id}","message":{{"role":"user","content":"hello"}}}}"#+ ) + "\n"+ };+ let main = dir.join("sess-a.jsonl");+ let agent = subagents.join("agent-a1.jsonl");+ let other = dir.join("sess-b.jsonl");+ fs::write(&main, line("sess-a", false)).unwrap();+ fs::write(&agent, line("sess-a", true)).unwrap();+ fs::write(&other, line("sess-b", false)).unwrap();++ let desktop = tmp.path().join("desktop");+ let write_record = |archived: bool| {+ let fields = serde_json::json!({ "cliSessionId": "sess-a", "isArchived": archived });+ write_test_record(&desktop, "d", fields)+ };+ let record = write_record(true);++ let adapter = ClaudeAdapter::with_desktop(projects.clone(), desktop.clone());+ assert!(adapter.watch_paths().contains(&desktop));++ let state = |adapter: &ClaudeAdapter| {+ let listed = adapter.list_session_files().unwrap();+ [&main, &agent, &other].map(|path| {+ let r = adapter.file_ref(path).unwrap();+ let from_list = listed.iter().find(|l| l.file_path == r.file_path).unwrap();+ assert_eq!((from_list.mtime_ms, from_list.size), (r.mtime_ms, r.size));+ let stamped = r.size != fs::metadata(path).unwrap().len() as i64;+ (stamped, adapter.parse_session(&r).unwrap().meta.archived)+ })+ };+ assert_eq!(+ state(&adapter),+ [(true, true), (true, true), (false, false)]+ );++ let mut dependents = adapter.ref_dependents(&record);+ dependents.sort();+ assert_eq!(dependents, vec![agent.clone(), main.clone()]);++ write_record(false);+ assert_eq!(+ state(&adapter),+ [(false, false), (false, false), (false, false)]+ );++ fs::remove_file(&main).unwrap();+ assert_eq!(+ adapter.ref_dependents(&record),+ vec![agent.clone()],+ "主转录没了,会话目录里的子代理照样交出去"+ );+ }++ /// 归档位不能被分支计数抵消:分支的引用往 size 里加着更早的同根文件数,删掉中间那份分支+ /// 让它减 1,同时归档就不能正好加 1+ #[test]+ fn the_archive_stamp_is_not_a_unit_step() {+ let r = SessionFileRef {+ agent: AgentId::ClaudeCode,+ native_id: "s".to_string(),+ file_path: "/p/-w/s.jsonl".to_string(),+ mtime_ms: 1,+ size: 100,+ };+ let owned = |archived: bool, title: Option<&str>| {+ let facts = Owned {+ archived,+ title: title.map(str::to_string),+ };+ HashMap::from([("s".to_string(), facts)])+ };+ for title in [None, Some("图片下载")] {+ let open = stamp_desktop(r.clone(), &owned(false, title)).size;+ let archived = stamp_desktop(r.clone(), &owned(true, title)).size;+ assert!(+ (archived - open).abs() > 1_000,+ "{title:?}: {open} → {archived}"+ );+ }+ }++ /// 标题:转录里起过的名字照用;桌面端的占位名 "New session" 不算名字——有桌面会话的名字+ /// 用它(改名并进引用),没有就退回首条提问+ #[test]+ fn desktop_titles_replace_the_placeholder() {+ let tmp = tempfile::tempdir().unwrap();+ let projects = tmp.path().join("projects");+ let dir = projects.join("-w");+ fs::create_dir_all(&dir).unwrap();+ let write = |id: &str, title: &str| {+ let lines = [+ format!(r#"{{"type":"custom-title","customTitle":"{title}","sessionId":"{id}"}}"#),+ format!(+ r#"{{"type":"user","uuid":"u-{id}","timestamp":"2026-09-01T08:00:01.000Z","sessionId":"{id}","message":{{"role":"user","content":"why does login time out"}}}}"#+ ),+ ];+ let path = dir.join(format!("{id}.jsonl"));+ fs::write(&path, lines.join("\n") + "\n").unwrap();+ path+ };+ let renamed_later = write("prior", PLACEHOLDER_TITLE);+ let no_record = write("lone", PLACEHOLDER_TITLE);+ let named = write("named", "Real name");++ let desktop = tmp.path().join("desktop");+ let write_record = |title: &str| {+ let fields = serde_json::json!({+ "cliSessionId": "current", "priorCliSessionIds": ["prior", "named"], "title": title,+ });+ write_test_record(&desktop, "d", fields);+ };+ write_record("图片下载");+ let adapter = ClaudeAdapter::with_desktop(projects, desktop.clone());+ let title = |path: &Path| {+ let r = adapter.file_ref(path).unwrap();+ let listed = adapter.list_session_files().unwrap();+ let from_list = listed.iter().find(|l| l.file_path == r.file_path).unwrap();+ assert_eq!(from_list.size, r.size, "列表与 file_ref 一致");+ (r.size, adapter.parse_session(&r).unwrap().meta.title)+ };+ let (before, renamed) = title(&renamed_later);+ assert_eq!(renamed, "图片下载");+ assert_eq!(title(&no_record).1, "why does login time out");+ assert_eq!(title(&named).1, "Real name", "转录里起过的名字照用");++ write_record("Image downloads");+ let (after, renamed) = title(&renamed_later);+ assert_eq!(renamed, "Image downloads");+ assert_ne!(before, after, "桌面端改名,引用跟着变");+ }+/// 把目录的 mtime 定在给定时刻(只在 unix 上能对目录开文件句柄)#[cfg(unix)]fn pin_mtime(dir: &Path, when: std::time::SystemTime) {diff --git a/crates/wake-core/src/adapters/claude_desktop.rs b/crates/wake-core/src/adapters/claude_desktop.rsnew file mode 100644index 0000000..274d704--- /dev/null+++ b/crates/wake-core/src/adapters/claude_desktop.rs@@ -0,0 +1,505 @@+//! Claude 桌面端(Code tab)给每个会话记的一份 `local_<uuid>.json`:+//! `<userData>/claude-code-sessions/<账号>/<组织>/local_<uuid>.json`。一个桌面会话名下是一串+//! Claude Code 会话(当前的 `cliSessionId`,/clear、取消归档之后留下的旧 id),它们的转录照常+//! 在 `~/.claude/projects` 里。Wake 只读、只借这几样:归档位 `isArchived`、派生关系+//! `spawnedFrom` 与标题 `title`(Claude Code 的转录里没有前两样,标题只写进当时那一条:在桌面端+//! 归档了、侧栏里嵌在别的会话下面、改了名,Wake 原先都看不出来),以及"哪个桌面会话拥有这条+//! CLI 会话"——深链 `claude://resume` 要发桌面会话自己的 id(`services::terminal` 的 macOS 一支)++use super::parse_utils::{stat_stamp, text_at, true_at};+use serde_json::Value;+use std::collections::{BTreeMap, HashMap};+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};++/// 桌面端新建会话时先往转录里写的占位标题(`custom-title`),之后起的名字只写进当时那一条+/// CLI 会话——/clear、resume 之前的那几条就一直叫这个。它不是标题+pub(crate) const PLACEHOLDER_TITLE: &str = "New session";++/// 桌面端记的一条 CLI 会话:归档了没有、桌面会话叫什么+#[derive(Debug)]+pub(crate) struct Owned {+ pub archived: bool,+ pub title: Option<String>,+}++/// 桌面端会话记录的根目录。只做路径推导、不探存在性+pub(crate) fn sessions_root() -> PathBuf {+ super::electron_user_data("Claude").join("claude-code-sessions")+}++/// 一份桌面会话记录里 Wake 用得上的部分。只有这几样:桌面端每次聚焦、每一轮都重写整份记录,+/// 别的字段变了对 Wake 就是没变(`DesktopIndex::changed` 按它比)+#[derive(Debug, PartialEq)]+pub(crate) struct Record {+ /// `sessionId` 去掉 `local_` 前缀+ pub stem: Option<String>,+ /// 当前的 Claude Code 会话(`cliSessionId`):从这个桌面会话派出去的会话挂在它下面+ pub current: Option<String>,+ /// 这个桌面会话名下的 Claude Code 会话 id:标量三字段 + 历史数组(多次 clear / resume 之后+ /// 旧 id 留在 priorCliSessionIds 里)+ pub cli_ids: Vec<String>,+ pub archived: bool,+ /// 桌面会话的名字(用户改的或自动起的;占位名不算)+ pub title: Option<String>,+ /// 派出这个会话的桌面会话(`spawnedFrom.sessionId` 去掉 `local_`):桌面端侧栏把它嵌在+ /// 那个会话下面+ pub spawned_from: Option<String>,+}++impl Record {+ pub fn parse(data: &[u8]) -> Option<Self> {+ let v: Value = serde_json::from_slice(data).ok()?;+ let text = |key: &str| text_at(&v, key).map(str::to_string);+ let local = |id: Option<&str>| id?.strip_prefix("local_").map(str::to_string);+ let mut cli_ids: Vec<String> = [+ "cliSessionId",+ "unarchivedCliSessionId",+ "preClearCliSessionId",+ ]+ .into_iter()+ .filter_map(text)+ .collect();+ if let Some(prior) = v.get("priorCliSessionIds").and_then(Value::as_array) {+ cli_ids.extend(prior.iter().filter_map(Value::as_str).map(str::to_string));+ }+ Some(Self {+ stem: local(text_at(&v, "sessionId")),+ current: text("cliSessionId"),+ cli_ids,+ archived: true_at(&v, "isArchived"),+ title: text("title").filter(|t| t != PLACEHOLDER_TITLE),+ spawned_from: local(v.pointer("/spawnedFrom/sessionId").and_then(Value::as_str)),+ })+ }+}++/// 根目录下的全部会话记录(`<账号>/<组织>/local_*.json`)。根不在 = 没有;某一层列不出来是+/// "不知道",报错——归档位与派生关系据此保留上次读到的,不当成记录都没了+pub(crate) fn record_files(root: &Path) -> std::io::Result<Vec<PathBuf>> {+ walk_records(root, true)+}++/// 同上,只是列不出来的那一层跳过:深链找拥有某条 CLI 会话的桌面会话,读得出的那几份里有就够+pub(crate) fn readable_record_files(root: &Path) -> Vec<PathBuf> {+ walk_records(root, false).unwrap_or_default()+}++fn walk_records(root: &Path, strict: bool) -> std::io::Result<Vec<PathBuf>> {+ // 不在(根不在,或列到一半被删了)就是没有+ let children = |dir: &Path| -> std::io::Result<Vec<PathBuf>> {+ let listed = match std::fs::read_dir(dir) {+ Ok(entries) => entries.map(|entry| entry.map(|e| e.path())).collect(),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),+ Err(e) => Err(e),+ };+ match listed {+ Err(_) if !strict => Ok(Vec::new()),+ listed => listed,+ }+ };+ let mut files = Vec::new();+ for account in children(root)?.iter().filter(|p| p.is_dir()) {+ for org in children(account)?.iter().filter(|p| p.is_dir()) {+ files.extend(children(org)?.into_iter().filter(|p| is_record_name(p)));+ }+ }+ Ok(files)+}++fn is_record_name(path: &Path) -> bool {+ path.file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("local_") && name.ends_with(".json"))+}++/// 读一份记录;读不出、写到一半(桌面端随时在改它)给 None+fn read_record(path: &Path) -> Option<Record> {+ Record::parse(&std::fs::read(path).ok()?)+}++/// 每条 CLI 会话在桌面端的样子。同一条被两个桌面会话认领(少见):名下有它的都归档了才算+/// 归档,标题取还开着的那个的(都开着取路径排在后面的那份,次次一样)+fn owned_of(records: &[Arc<Record>]) -> HashMap<String, Owned> {+ let mut owned: HashMap<String, Owned> = HashMap::new();+ for record in records {+ for id in &record.cli_ids {+ let entry = owned.entry(id.clone()).or_insert(Owned {+ archived: true,+ title: None,+ });+ entry.archived &= record.archived;+ if record.title.is_some() && (entry.title.is_none() || !record.archived) {+ entry.title = record.title.clone();+ }+ }+ }+ owned+}++/// 桌面端侧栏的嵌套,落到 CLI 会话上:派出去的会话名下每一条 → 派它的桌面会话当前那一条。+/// 派它的会话记录不在了(删掉了)就不挂+fn spawn_links_of(records: &[Arc<Record>]) -> Vec<(String, String)> {+ let current: HashMap<&str, &str> = records+ .iter()+ .filter_map(|r| Some((r.stem.as_deref()?, r.current.as_deref()?)))+ .collect();+ records+ .iter()+ .filter_map(|r| Some((r, *current.get(r.spawned_from.as_deref()?)?)))+ .flat_map(|(r, parent)| {+ r.cli_ids+ .iter()+ .map(move |child| (child.clone(), parent.to_string()))+ })+ .collect()+}++type Stamped = ((i64, i64), Arc<Record>);++/// 桌面端会话记录的缓存:按每份文件的 (mtime, size) 记住读到的,没变的不重读+pub(crate) struct DesktopIndex {+ root: PathBuf,+ records: Mutex<BTreeMap<PathBuf, Stamped>>,+ /// watcher 上次按哪一版对过账(`take_change`)。与 `records` 分开记:扫描随时会刷新+ /// records,拿它当基准会把扫描先读到、watcher 还没对过账的改动当成没变+ settled: Mutex<HashMap<PathBuf, Arc<Record>>>,+ /// 刷新 records 时已经不在的记录,留到 watcher 对完账:一批里删掉好几份时,处理头一份的+ /// 重比就会刷新 records,后面几份原先名下有哪些会话就只有这里还知道+ vanished: Mutex<HashMap<PathBuf, Arc<Record>>>,+}++impl DesktopIndex {+ pub fn new(root: PathBuf) -> Self {+ Self {+ root,+ records: Mutex::new(BTreeMap::new()),+ settled: Mutex::new(HashMap::new()),+ vanished: Mutex::new(HashMap::new()),+ }+ }++ pub fn root(&self) -> &Path {+ &self.root+ }++ /// 桌面端记着的每条 CLI 会话:归档位与标题+ pub fn owned(&self) -> HashMap<String, Owned> {+ owned_of(&self.records())+ }++ /// 桌面端侧栏的嵌套:(派出去的 CLI 会话, 派它的 CLI 会话)+ pub fn spawn_links(&self) -> Vec<(String, String)> {+ spawn_links_of(&self.records())+ }++ /// 是不是一份桌面会话记录(`<根>/<账号>/<组织>/local_*.json`)+ pub fn is_record(&self, path: &Path) -> bool {+ is_record_name(path)+ && path.parent().and_then(Path::parent).and_then(Path::parent)+ == Some(self.root.as_path())+ }++ /// watcher 事件落在一份记录上:Wake 用得上的内容比上次对账时变了没有(只看、不记账)+ pub fn changed(&self, path: &Path) -> bool {+ self.diff(path, false).is_some()+ }++ /// 同上,变了就记账、交出变化前后名下的 CLI 会话;没变、不是记录给 None+ pub fn take_change(&self, path: &Path) -> Option<Vec<String>> {+ self.diff(path, true)+ }++ /// 没对过账的记录(Wake 刚起来)算变了;删掉了也算,交出它原先名下的+ fn diff(&self, path: &Path, settle: bool) -> Option<Vec<String>> {+ if !self.is_record(path) {+ return None;+ }+ let after = self.entry(path).map(|(_, record)| record);+ let mut settled = self.settled.lock().unwrap();+ let before = match (settled.get(path), &after) {+ (Some(before), Some(after)) if before == after => return None,+ (Some(before), _) => Some(before.clone()),+ // 删掉了、之前没对过账:扫描读到过的那份(两把锁分开拿,`records()` 是先 records+ // 后 vanished)+ (None, None) => {+ let vanished = self.vanished.lock().unwrap().get(path).cloned();+ vanished.or_else(|| {+ self.records+ .lock()+ .unwrap()+ .get(path)+ .map(|(_, r)| r.clone())+ })+ }+ (None, Some(_)) => None,+ };+ if before.is_none() && after.is_none() {+ return None;+ }+ if settle {+ self.vanished.lock().unwrap().remove(path);+ match &after {+ Some(record) => {+ settled.insert(path.to_path_buf(), record.clone());+ }+ // 删掉的记录对完账,缓存里那份也不留:不然下一次问还会把它当成刚删掉+ None => {+ settled.remove(path);+ self.records.lock().unwrap().remove(path);+ }+ }+ }+ let mut ids: Vec<String> = before+ .iter()+ .chain(&after)+ .flat_map(|r| r.cli_ids.iter().cloned())+ .collect();+ ids.sort();+ ids.dedup();+ Some(ids)+ }++ /// 全部记录(按路径排),现列现比(几十份,一份一次 stat;变了的才重读)。根列不出来用上次+ /// 读到的+ fn records(&self) -> Vec<Arc<Record>> {+ if let Ok(files) = record_files(&self.root) {+ let fresh: BTreeMap<PathBuf, Stamped> = files+ .into_iter()+ .filter_map(|path| Some((path.clone(), self.entry(&path)?)))+ .collect();+ let mut records = self.records.lock().unwrap();+ let before = std::mem::replace(&mut *records, fresh);+ let gone = before+ .into_iter()+ .filter(|(path, _)| !records.contains_key(path))+ .map(|(path, (_, record))| (path, record));+ self.vanished.lock().unwrap().extend(gone);+ }+ let records = self.records.lock().unwrap();+ records.values().map(|(_, record)| record.clone()).collect()+ }++ /// 一份记录此刻的内容:戳没变用缓存,变了重读、记进缓存。读不出(写到一半)交上次读到的、+ /// 记着旧戳(下次戳对不上还会再读);不在、没读到过给 None。文件 I/O 不持锁——扫描、+ /// watcher、打开详情可能同时问+ fn entry(&self, path: &Path) -> Option<Stamped> {+ let stamp = stat_stamp(path)?;+ let cached = self.records.lock().unwrap().get(path).cloned();+ match cached {+ Some((seen, record)) if seen == stamp => Some((seen, record)),+ cached => match read_record(path) {+ Some(record) => {+ let entry = (stamp, Arc::new(record));+ let mut records = self.records.lock().unwrap();+ records.insert(path.to_path_buf(), entry.clone());+ Some(entry)+ }+ None => cached,+ },+ }+ }+}++/// 测试用:在 `root` 下按桌面端的布局写一份记录(`sessionId` 由 stem 补上),返回路径+#[cfg(test)]+pub(crate) fn write_test_record(root: &Path, stem: &str, mut fields: Value) -> PathBuf {+ let org = root.join("acct").join("org");+ std::fs::create_dir_all(&org).unwrap();+ fields["sessionId"] = Value::from(format!("local_{stem}"));+ let path = org.join(format!("local_{stem}.json"));+ std::fs::write(&path, fields.to_string()).unwrap();+ path+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ use std::collections::HashSet;+ use std::fs;++ fn archived(index: &DesktopIndex) -> HashSet<String> {+ index+ .owned()+ .into_iter()+ .filter(|(_, owned)| owned.archived)+ .map(|(id, _)| id)+ .collect()+ }++ fn write(root: &Path, stem: &str, archived: bool, cli: &str, prior: &[&str]) -> PathBuf {+ let fields =+ json!({ "cliSessionId": cli, "priorCliSessionIds": prior, "isArchived": archived });+ write_test_record(root, stem, fields)+ }++ fn ids(ids: &[&str]) -> Option<Vec<String>> {+ Some(ids.iter().map(|id| id.to_string()).collect())+ }++ #[test]+ fn a_record_lists_its_current_and_earlier_cli_sessions() {+ let record = Record::parse(+ br#"{"sessionId":"local_s","cliSessionId":"c2","preClearCliSessionId":"c1",+ "priorCliSessionIds":["c0"],"isArchived":true}"#,+ )+ .unwrap();+ assert_eq!(record.stem.as_deref(), Some("s"));+ assert_eq!(record.current.as_deref(), Some("c2"));+ assert!(record.archived);+ assert_eq!(record.cli_ids, ["c2", "c1", "c0"]);+ assert!(+ Record::parse(b"{\"sessionId\":").is_none(),+ "写到一半的不算"+ );+ }++ /// 归档以桌面会话为单位,名下的 CLI 会话一起算;还有开着的桌面会话认领它就不算。+ /// 取消归档、记录删掉,下一次问就跟上+ #[test]+ fn archived_ids_follow_the_records() {+ let tmp = tempfile::tempdir().unwrap();+ let index = DesktopIndex::new(tmp.path().to_path_buf());+ assert!(archived(&index).is_empty(), "根不在 = 没有");++ let a = write(tmp.path(), "a", true, "cli-a", &["cli-a0", "shared"]);+ write(tmp.path(), "b", false, "cli-b", &["shared"]);+ assert_eq!(+ archived(&index),+ HashSet::from(["cli-a".to_string(), "cli-a0".to_string()])+ );++ write(tmp.path(), "a", false, "cli-a", &["cli-a0", "shared"]);+ assert!(archived(&index).is_empty(), "取消归档");++ write(tmp.path(), "a", true, "cli-a", &[]);+ assert!(archived(&index).contains("cli-a"));+ fs::remove_file(&a).unwrap();+ assert!(archived(&index).is_empty(), "记录删了");+ }++ /// 写到一半的记录沿用上次读到的,不当成没归档+ #[test]+ fn a_half_written_record_keeps_what_was_read_before() {+ let tmp = tempfile::tempdir().unwrap();+ let index = DesktopIndex::new(tmp.path().to_path_buf());+ let a = write(tmp.path(), "a", true, "cli-a", &[]);+ assert!(archived(&index).contains("cli-a"));+ fs::write(&a, "{\"sessionId\":\"local_a\",\"isArch").unwrap();+ assert!(archived(&index).contains("cli-a"));+ write(tmp.path(), "a", false, "cli-a", &[]);+ assert!(archived(&index).is_empty(), "写完了照常读");+ }++ /// 桌面会话的名字记到它名下的每条 CLI 会话上;占位名不算名字。同一条被两个桌面会话认领时+ /// 取还开着的那个的+ #[test]+ fn titles_reach_every_cli_session_of_the_desktop_session() {+ let tmp = tempfile::tempdir().unwrap();+ let index = DesktopIndex::new(tmp.path().to_path_buf());+ let record = |stem: &str, title: &str, archived: bool, ids: &[&str]| {+ let fields = json!({+ "cliSessionId": ids[0], "priorCliSessionIds": &ids[1..],+ "isArchived": archived, "title": title,+ });+ write_test_record(tmp.path(), stem, fields);+ };+ record("a", "图片下载", false, &["cli-a", "cli-a0"]);+ record("b", PLACEHOLDER_TITLE, false, &["cli-b"]);+ record("c", "Old name", true, &["cli-c", "cli-a0"]);+ let owned = index.owned();+ let title = |id: &str| owned[id].title.as_deref();+ assert_eq!(title("cli-a"), Some("图片下载"));+ assert_eq!(title("cli-a0"), Some("图片下载"), "开着的那个的");+ assert_eq!(title("cli-b"), None, "占位名不算");+ assert_eq!(title("cli-c"), Some("Old name"));+ assert!(!owned["cli-a0"].archived && owned["cli-c"].archived);+ }++ /// 派出去的会话名下每条 CLI 会话都挂到派它的桌面会话当前那条上;派它的记录不在就不挂+ #[test]+ fn spawned_sessions_hang_under_the_current_cli_session_of_their_parent() {+ let tmp = tempfile::tempdir().unwrap();+ let index = DesktopIndex::new(tmp.path().to_path_buf());+ write(tmp.path(), "p", false, "cli-p", &["cli-p0"]);+ let spawned = |parent: &str| json!({ "sessionId": parent, "taskId": "task_1" });+ let child = json!({+ "cliSessionId": "cli-c", "priorCliSessionIds": ["cli-c0"],+ "spawnedFrom": spawned("local_p"),+ });+ write_test_record(tmp.path(), "c", child);+ let orphan = json!({ "cliSessionId": "cli-o", "spawnedFrom": spawned("local_gone") });+ write_test_record(tmp.path(), "o", orphan);++ let mut links = index.spawn_links();+ links.sort();+ let link = |c: &str, p: &str| (c.to_string(), p.to_string());+ assert_eq!(links, vec![link("cli-c", "cli-p"), link("cli-c0", "cli-p")]);+ }++ /// 同一批删掉两份记录:处理头一份时的重比会刷新缓存,第二份原先名下有哪些会话照样交得出来+ #[test]+ fn records_deleted_together_are_each_settled() {+ let tmp = tempfile::tempdir().unwrap();+ let index = DesktopIndex::new(tmp.path().to_path_buf());+ let a = write(tmp.path(), "a", true, "cli-a", &[]);+ let b = write(tmp.path(), "b", true, "cli-b", &[]);+ index.owned(); // 启动扫描读过,watcher 还没对过账+ fs::remove_file(&a).unwrap();+ fs::remove_file(&b).unwrap();+ assert_eq!(index.take_change(&a), ids(&["cli-a"]));+ index.owned(); // 头一份名下转录的重比+ assert_eq!(index.take_change(&b), ids(&["cli-b"]));+ assert_eq!(index.take_change(&b), None);+ }++ /// 某个账号目录读不出来:归档索引要的是"不知道"(报错),深链要的是读得出的那几份+ #[cfg(unix)]+ #[test]+ fn an_unreadable_account_fails_the_index_but_not_the_deep_link() {+ use std::os::unix::fs::PermissionsExt;+ let tmp = tempfile::tempdir().unwrap();+ let a = write(tmp.path(), "a", false, "cli-a", &[]);+ let locked = tmp.path().join("other");+ fs::create_dir_all(locked.join("org")).unwrap();+ fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();+ if fs::read_dir(&locked).is_ok() {+ return; // root 读得动任何目录,这条测不了+ }+ assert!(record_files(tmp.path()).is_err());+ assert_eq!(readable_record_files(tmp.path()), vec![a]);+ fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).unwrap();+ }++ /// watcher 的对账:没对过账的算变了;桌面端只是重写了 Wake 不看的字段(聚焦一下)不算;+ /// 归档变了、记录删了算,交出名下的 CLI 会话。只看(`changed`)不记账+ #[test]+ fn only_changes_wake_reads_reach_the_watcher() {+ let tmp = tempfile::tempdir().unwrap();+ let index = DesktopIndex::new(tmp.path().to_path_buf());+ let focus = |at: i64| {+ let fields = json!({ "cliSessionId": "cli-a", "lastFocusedAt": at });+ write_test_record(tmp.path(), "a", fields)+ };+ let a = focus(1);+ assert!(index.changed(&a));+ assert!(index.changed(&a), "只看不记账");+ assert_eq!(index.take_change(&a), ids(&["cli-a"]));+ focus(22);+ assert!(!index.changed(&a), "聚焦一下不算");+ assert_eq!(index.take_change(&a), None);++ write(tmp.path(), "a", true, "cli-a", &["cli-a0"]);+ assert_eq!(index.take_change(&a), ids(&["cli-a", "cli-a0"]));+ fs::remove_file(&a).unwrap();+ assert!(index.changed(&a));+ assert_eq!(index.take_change(&a), ids(&["cli-a", "cli-a0"]), "删掉了");+ assert_eq!(index.take_change(&a), None);++ let elsewhere = tmp.path().join("acct").join("local_x.json");+ fs::write(&elsewhere, "{}").unwrap();+ assert!(!index.changed(&elsewhere), "不在 <账号>/<组织>/ 这一层");+ assert!(!index.changed(&tmp.path().join("acct/org/scheduled-tasks.json")));+ }+}diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rsindex d41ecf6..b368655 100644--- a/crates/wake-core/src/adapters/mod.rs+++ b/crates/wake-core/src/adapters/mod.rs@@ -23,6 +23,7 @@ pub mod zcode;pub mod remote;+pub(crate) mod claude_desktop;pub(crate) mod grok_group;pub(crate) mod parse_utils;pub(crate) mod pi_format;diff --git a/crates/wake-core/src/adapters/parse_utils.rs b/crates/wake-core/src/adapters/parse_utils.rsindex 88f7270..36a3820 100644--- a/crates/wake-core/src/adapters/parse_utils.rs+++ b/crates/wake-core/src/adapters/parse_utils.rs@@ -319,8 +319,8 @@ pub fn subagent_parent(path: &std::path::Path) -> Option<String> {)}-/// 一个会话目录里全部子代理转录的引用(Task / Agent 派的与 Workflow 跑出来的),读不出的目录跳过-pub fn subagent_refs(agent: AgentId, session_dir: &std::path::Path) -> Vec<SessionFileRef> {+/// 一个会话目录里全部子代理转录(Task / Agent 派的与 Workflow 跑出来的),读不出的目录跳过+pub fn subagent_transcripts(session_dir: &std::path::Path) -> Vec<std::path::PathBuf> {let files = |dir: &std::path::Path| -> Vec<std::path::PathBuf> {std::fs::read_dir(dir).map(|entries| entries.flatten().map(|entry| entry.path()).collect())@@ -334,9 +334,14 @@ pub fn subagent_refs(agent: AgentId, session_dir: &std::path::Path) -> Vec<Sessitranscripts.push(path);}}+ transcripts.retain(|path| subagent_session_dir(path).is_some());transcripts+}++/// 一个会话目录里全部子代理转录的引用+pub fn subagent_refs(agent: AgentId, session_dir: &std::path::Path) -> Vec<SessionFileRef> {+ subagent_transcripts(session_dir).iter()- .filter(|path| subagent_session_dir(path).is_some()).filter_map(|path| subagent_ref(agent, path)).collect()}diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rsindex ea26b93..664cc81 100644--- a/crates/wake-core/src/db.rs+++ b/crates/wake-core/src/db.rs@@ -242,8 +242,10 @@ CREATE TABLE IF NOT EXISTS claimed_sessions (/// 它),老行靠这轮重解析写对;/// "16" = 会话目录里的子代理转录(Claude Code 含 Workflow、Cursor CLI、CodeBuddy / WorkBuddy、/// Qoder、Kimi)作为子会话入库、标 spawned,`<git-context>` 不进标题;旧版监听当顶层会话收进来-/// 的 Workflow 转录(sidechain 行被滤掉、零消息)文件没变、引用也没变,靠这轮重解析写对。-pub const FTS_FORMAT: &str = "16";+/// 的 Workflow 转录(sidechain 行被滤掉、零消息)文件没变、引用也没变,靠这轮重解析写对;+/// "17" = Claude Code 转录里桌面端的占位标题 "New session" 不算名字(退回桌面会话的名字或首条+/// 提问);桌面端已经没有记录的老会话引用不变,靠这轮重解析写对。+pub const FTS_FORMAT: &str = "17";/// FTS 压缩的节奏(见 `Store::compact_fts`):距上次压缩满一天、或从没压过才压。没有记录/// 就算到期——老库升级后、新建库首轮扫描收尾各压一次;`FTS_FORMAT` 换代时 open_conn 把diff --git a/crates/wake-core/src/services/terminal/macos.rs b/crates/wake-core/src/services/terminal/macos.rsindex 32159c1..bf7ed57 100644--- a/crates/wake-core/src/services/terminal/macos.rs+++ b/crates/wake-core/src/services/terminal/macos.rs@@ -6,6 +6,7 @@ use super::{cli_not_found_error, percent_encode, pipe_to, resolve_cli, resume_args, session_bin, sh_quote,spawn_and_reap, ResumeOutcome,};+use crate::adapters::claude_desktop;use crate::models::{AgentId, SessionMeta};use std::collections::HashMap;use std::path::Path;@@ -501,25 +502,21 @@ fn launch_claude_desktop(meta: &SessionMeta) -> ResumeOutcome {}/// 在 desktop 会话索引里找拥有 `cli_id` 的会话,返回其 stem uuid。-/// 索引是数百个 KB 级 json,每次点击现扫(读几 ms,别缓存——desktop-/// 侧随时在写)。解析失败/结构不符的文件跳过,扫不到回 None 走原 id。+/// 每次点击现扫(几十份 KB 级 json,读几 ms,别缓存——desktop 侧随时在写)。+/// 解析失败/结构不符的文件跳过,扫不到回 None 走原 id。记录的读法与归档位共用+/// `adapters::claude_desktop`fn claude_desktop_owned_stem(cli_id: &str) -> Option<String> {- // home_dir 走 adapters 的 WAKE_HOME 改道,fixture 测试可以铺假索引- let root = crate::adapters::home_dir()?- .join("Library/Application Support/Claude/claude-code-sessions");- let sub = |d: std::fs::DirEntry| std::fs::read_dir(d.path()).into_iter().flatten().flatten();+ // sessions_root 走 adapters 的 WAKE_HOME 改道,fixture 测试可以铺假索引+ // 读不出的账号 / 组织目录跳过,别让它连累读得出的那几份+ let files = claude_desktop::readable_record_files(&claude_desktop::sessions_root());// desktop 可能留有多个 <acct>/<org> 目录,而 claude://resume 只在当前// 登录账户下找 local_<stem>;当前账户 Wake 无从得知,多份命中时取// mtime 最新的记录(基本即活跃账户),别听目录枚举顺序的- std::fs::read_dir(root)- .ok()?- .flatten()- .flat_map(sub)- .flat_map(sub)- .filter_map(|f| {- let p = f.path();- let stem = owned_stem_in(&p, cli_id)?;- let mtime = std::fs::metadata(&p).and_then(|m| m.modified()).ok();+ files+ .iter()+ .filter_map(|p| {+ let stem = owned_stem_in(p, cli_id)?;+ let mtime = crate::adapters::parse_utils::stat_stamp(p).map(|(mtime, _)| mtime);Some((mtime, stem))}).max_by_key(|(mtime, _)| *mtime)@@ -530,35 +527,16 @@ fn claude_desktop_owned_stem(cli_id: &str) -> Option<String> {/// 省掉整篇 json 解析(命中的通常恰一份)。调用方保证 cli_id 非空/// (空 needle 会 panic)fn owned_stem_in(p: &Path, cli_id: &str) -> Option<String> {- if p.extension().and_then(|e| e.to_str()) != Some("json") {- return None;- }let data = std::fs::read(p).ok()?;let needle = cli_id.as_bytes();if !data.windows(needle.len()).any(|w| w == needle) {return None;}- let v = serde_json::from_slice::<serde_json::Value>(&data).ok()?;- // 标量三字段 + 历史数组(多次 clear/resume 后旧 CLI id 归档在- // priorCliSessionIds 里,漏了它老会话又会被重复导入)- let owns = [- "cliSessionId",- "unarchivedCliSessionId",- "preClearCliSessionId",- ]- .iter()- .any(|k| v.get(k).and_then(|x| x.as_str()) == Some(cli_id))- || v.get("priorCliSessionIds")- .and_then(|x| x.as_array())- .is_some_and(|a| a.iter().any(|x| x.as_str() == Some(cli_id)));- owns.then(|| {- v.get("sessionId")?- .as_str()?- .strip_prefix("local_")- .filter(|s| is_uuid(s))- .map(str::to_string)- })- .flatten()+ let record = claude_desktop::Record::parse(&data)?;+ if !record.cli_ids.iter().any(|id| id == cli_id) {+ return None;+ }+ record.stem.filter(|s| is_uuid(s))}fn launch_desktop_id(id: &str, prefix: &str, term: TerminalApp) -> ResumeOutcome {diff --git a/crates/wake-core/src/watcher.rs b/crates/wake-core/src/watcher.rsindex 9ece98f..de6fdaa 100644--- a/crates/wake-core/src/watcher.rs+++ b/crates/wake-core/src/watcher.rs@@ -337,6 +337,7 @@ pub fn start_watcher(#[cfg(test)]mod tests {use super::*;+ use crate::adapters::claude_desktop::write_test_record;use crate::adapters::craft::CraftAdapter;use crate::scanner::NullEvents;use notify::event::{CreateKind, EventKind, ModifyKind, RemoveKind, RenameMode};@@ -449,6 +450,127 @@ mod tests {assert!(!claimed.contains("claude-code:sdk-1"), "{claimed:?}");}+ /// 在 Claude 桌面端归档、取消归档、删掉桌面会话:只有桌面端那份记录变了,转录没动。+ /// watcher 听着记录所在的目录,经 `ref_dependents` 把名下的转录补进同一批,库里那行当场跟上+ #[test]+ fn claude_desktop_archive_reaches_the_index_live() {+ use crate::adapters::claude::ClaudeAdapter;+ let tmp = tempfile::tempdir().unwrap();+ let projects = tmp.path().join("projects");+ let dir = projects.join("-w");+ std::fs::create_dir_all(&dir).unwrap();+ let id = "c1a0de00-0000-4000-8000-0000000000c3";+ let row = serde_json::json!({+ "type": "user", "uuid": "u1", "isSidechain": false, "cwd": "/w", "sessionId": id,+ "timestamp": "2026-09-01T08:00:01.000Z",+ "message": { "role": "user", "content": "Why does login time out?" },+ });+ std::fs::write(dir.join(format!("{id}.jsonl")), row.to_string() + "\n").unwrap();++ let desktop = tmp.path().join("desktop");+ let write_record = |archived: bool| {+ let fields = serde_json::json!({ "cliSessionId": id, "isArchived": archived });+ write_test_record(&desktop, "d", fields)+ };+ let record = write_record(false);++ let store = Arc::new(Store::open(&tmp.path().join("wake.db")).unwrap());+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(ClaudeAdapter::with_desktop(+ projects,+ desktop.clone(),+ ))];+ let roots: Vec<(PathBuf, usize)> = adapters[0]+ .watch_paths()+ .into_iter()+ .map(|p| (p, 0))+ .collect();+ crate::scanner::run_scan(&adapters, &store, &NullEvents, true).unwrap();+ let key = format!("claude-code:{id}");+ let archived = || store.get_session(&key).unwrap().unwrap().archived;+ let event = |kind: EventKind| {+ let batch = vec![Ok(notify::Event::new(kind).add_path(record.clone()))];+ process_batch(&adapters, &store, &NullEvents, &roots, batch);+ };+ assert!(!archived());++ write_record(true);+ event(EventKind::Modify(ModifyKind::Any));+ assert!(archived(), "在桌面端归档");++ write_record(false);+ event(EventKind::Modify(ModifyKind::Any));+ assert!(!archived(), "取消归档");++ write_record(true);+ event(EventKind::Modify(ModifyKind::Any));+ std::fs::remove_file(&record).unwrap();+ event(EventKind::Remove(RemoveKind::File));+ assert!(!archived(), "桌面会话删掉了,转录还在");+ }++ /// Claude 桌面端从一个会话派出去的会话(侧栏里嵌在它下面):挂到派它的会话下面、跟着它+ /// 的项目;记录里的 spawnedFrom 没了(或派它的会话没了),当场解挂、回到自己的项目+ #[test]+ fn claude_desktop_side_sessions_nest_under_the_session_that_started_them() {+ use crate::adapters::claude::ClaudeAdapter;+ let tmp = tempfile::tempdir().unwrap();+ let projects = tmp.path().join("projects");+ let (parent, child) = (+ "c1a0de00-0000-4000-8000-0000000000d4",+ "c1a0de00-0000-4000-8000-0000000000e5",+ );+ for (id, dir, cwd) in [(parent, "-w", "/w"), (child, "-w-wt", "/w/wt")] {+ let dir = projects.join(dir);+ std::fs::create_dir_all(&dir).unwrap();+ let row = serde_json::json!({+ "type": "user", "uuid": format!("u-{id}"), "isSidechain": false, "cwd": cwd,+ "sessionId": id, "timestamp": "2026-09-01T08:00:01.000Z",+ "message": { "role": "user", "content": "Why does login time out?" },+ });+ std::fs::write(dir.join(format!("{id}.jsonl")), row.to_string() + "\n").unwrap();+ }++ let desktop = tmp.path().join("desktop");+ write_test_record(&desktop, "p", serde_json::json!({ "cliSessionId": parent }));+ let write_child = |spawned: bool| {+ let mut fields = serde_json::json!({ "cliSessionId": child });+ if spawned {+ fields["spawnedFrom"] =+ serde_json::json!({ "sessionId": "local_p", "taskId": "t" });+ }+ write_test_record(&desktop, "c", fields)+ };+ let record = write_child(true);++ let store = Arc::new(Store::open(&tmp.path().join("wake.db")).unwrap());+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(ClaudeAdapter::with_desktop(+ projects,+ desktop.clone(),+ ))];+ let roots: Vec<(PathBuf, usize)> = adapters[0]+ .watch_paths()+ .into_iter()+ .map(|p| (p, 0))+ .collect();+ crate::scanner::run_scan(&adapters, &store, &NullEvents, true).unwrap();+ let (parent_key, child_key) = (+ format!("claude-code:{parent}"),+ format!("claude-code:{child}"),+ );+ let state = || {+ let project = store.get_session(&child_key).unwrap().unwrap().project_path;+ (store.parent_key_of(&child_key).unwrap(), project)+ };+ assert_eq!(state(), (Some(parent_key.clone()), "/w".to_string()));++ write_child(false);+ let batch = vec![Ok(+ notify::Event::new(EventKind::Modify(ModifyKind::Any)).add_path(record.clone())+ )];+ process_batch(&adapters, &store, &NullEvents, &roots, batch);+ assert_eq!(state(), (None, "/w/wt".to_string()));+ }+/// Claude Code 的分支 B 开头原样复制了原件 A 的第一轮。A 在 Wake 之外消失(Claude 按/// cleanupPeriodDays 清掉、在 Finder 里删掉)或者被放回时,B 的文件没动、没有它的事件——/// watcher 经 `ref_dependents` 把它补进同一批:A 没了,B 展开完整历史、变回顶层;diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rsindex 8b12e07..893e2dc 100644--- a/crates/wake-core/tests/adapter_contracts.rs+++ b/crates/wake-core/tests/adapter_contracts.rs@@ -3240,7 +3240,9 @@ fn watch_paths_derive_from_data_roots() {let tag = a.agent().as_str();let watched = a.watch_paths();// 唯一的例外:Kilo 旧版扩展的任务目录不进监听(每个任务里一整份 checkpoints 影子- // git 仓库,见 adapters::kilo);它的新版实例是库文件,本来就没有监听目录+ // git 仓库,见 adapters::kilo);它的新版实例是库文件,本来就没有监听目录。+ // Claude Code 的默认实例另听桌面端的会话记录(见 adapters::claude_desktop),假 HOME+ // 里没有那个目录,所以这里照常相等;它由 claude.rs 的单测卡着let expect: Vec<std::path::PathBuf> = if a.agent() == AgentId::Kilo {Vec::new()} else {