Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

fix: keep OpenCode and OpenClaw parent links on the copy that is listed

Corey Chiu5346d0e36838
diff --git a/crates/wake-core/src/adapters/openclaw.rs b/crates/wake-core/src/adapters/openclaw.rs
index 9598269..7d0ade1 100644
--- a/crates/wake-core/src/adapters/openclaw.rs
+++ b/crates/wake-core/src/adapters/openclaw.rs
@@ -417,6 +417,56 @@ fn query_rows(conn: &rusqlite::Connection) -> Option<Vec<ClawRow>> {
rows
}
+/// 旧版会话目录里列得出来的转录:(主干, 路径, metadata)。归档 / 检查点、空文件与不是普通
+/// 文件的不算——列表与关系里的 id 映射都按这一份,两边才不会对不上
+fn legacy_transcripts(sessions_dir: &Path) -> Vec<(String, PathBuf, fs::Metadata)> {
+ let Ok(entries) = fs::read_dir(sessions_dir) else {
+ return Vec::new();
+ };
+ entries
+ .flatten()
+ .filter_map(|entry| {
+ let name = entry.file_name().to_string_lossy().to_string();
+ if !is_legacy_transcript(&name) {
+ return None;
+ }
+ let meta = entry.metadata().ok()?;
+ if !meta.is_file() || meta.len() == 0 {
+ return None;
+ }
+ let stem = name.strip_suffix(".jsonl").unwrap_or(&name).to_string();
+ Some((stem, entry.path(), meta))
+ })
+ .collect()
+}
+
+/// 每个会话 id 对应的列出来的转录主干:带话题的会话转录叫 `<id>-topic-<话题>.jsonl`
+/// (上游 resolveSessionTranscriptPathInDir),枚举时 native id 是整个主干;有裸文件名的用它
+fn legacy_stems(listed: impl IntoIterator<Item = String>) -> HashMap<String, String> {
+ let mut stems = HashMap::new();
+ for stem in listed {
+ let id = stem.split("-topic-").next().unwrap_or(&stem).to_string();
+ if id == stem {
+ stems.insert(id, stem);
+ } else {
+ stems.entry(id).or_insert(stem);
+ }
+ }
+ stems
+}
+
+/// 会话在 Wake 里的 id:库里有的用库里的,旧版的换成实际列出来的转录主干
+fn listed_id<'a>(
+ id: &'a str,
+ in_db: &HashSet<&str>,
+ stems: &'a HashMap<String, String>,
+) -> &'a str {
+ if in_db.contains(id) {
+ return id;
+ }
+ stems.get(id).map_or(id, String::as_str)
+}
+
/// 旧版转录文件名过滤:归档/回滚快照/压缩检查点都不是活会话
fn is_legacy_transcript(name: &str) -> bool {
name.ends_with(".jsonl")
@@ -628,28 +678,15 @@ impl AgentAdapter for OpenclawAdapter {
}
}));
}
- let sessions = dir.join("sessions");
- let Ok(entries) = fs::read_dir(&sessions) else {
- continue;
- };
- for e in entries.flatten() {
- let name = e.file_name().to_string_lossy().to_string();
- if !is_legacy_transcript(&name) {
- continue;
- }
- let Ok(meta) = e.metadata() else { continue };
- if !meta.is_file() || meta.len() == 0 {
- continue;
- }
- let stem = name.strip_suffix(".jsonl").unwrap_or(&name);
- out.push(SessionFileRef {
+ out.extend(legacy_transcripts(&dir.join("sessions")).into_iter().map(
+ |(stem, path, meta)| SessionFileRef {
agent: AgentId::Openclaw,
- native_id: stem.to_string(),
- file_path: e.path().to_string_lossy().to_string(),
+ native_id: stem,
+ file_path: path.to_string_lossy().to_string(),
mtime_ms: mtime_ms(&meta),
size: meta.len() as i64,
- });
- }
+ },
+ ));
}
Ok(out)
}
@@ -681,18 +718,34 @@ impl AgentAdapter for OpenclawAdapter {
// 期间被写过时按戳重读就是把整个枚举查询再跑一遍)
let mut snapshots = Vec::new();
let mut legacy = Vec::new();
+ let mut transcripts = Vec::new();
for dir in self.agent_dirs() {
let db = dir.join("agent").join(DB_NAME);
if db.is_file() {
snapshots.push(self.rows_cache_of(&db).latest()?);
}
- legacy.push(self.legacy_index(&dir.join("sessions"))?);
+ let sessions = dir.join("sessions");
+ legacy.push(self.legacy_index(&sessions)?);
+ transcripts.extend(
+ legacy_transcripts(&sessions)
+ .into_iter()
+ .map(|(stem, ..)| stem),
+ );
}
- let db_rows = || snapshots.iter().flat_map(|rows| rows.iter());
+ // 各 agent 目录收齐了再定:裸文件名优先得在全集上成立,不能看目录先后
+ let stems = legacy_stems(transcripts);
+ let all_rows = || snapshots.iter().flat_map(|rows| rows.iter());
+ // 没有事件的窗口不列(列表同一条),不算"库里那份"——迁进库时没带上事件、旧版 jsonl 还在的
+ // 会话,列出来的是旧版那份。时间线上照样留着它(下面的 windows)
let legacy_entries = || legacy.iter().flat_map(|index| index.iter());
- // 会话键 → 库里它的窗口(创建时间, 会话 id);旧版只知道每个键眼下那一条
+ let in_db: HashSet<&str> = all_rows()
+ .filter(|row| row.event_count > 0)
+ .map(|row| row.session_id.as_str())
+ .collect();
+ // 会话键 → 库里它的全部窗口(创建时间, 会话 id),空的也算:它在时间线上占着一段,拿掉的话
+ // 这段里派出的子代理会被挂到更早的那一窗。挑中的是空窗口时,`listed_id` 换成列出来的那份
let mut windows: HashMap<&str, Vec<(i64, &str)>> = HashMap::new();
- for row in db_rows() {
+ for row in all_rows() {
windows
.entry(&row.session_key)
.or_default()
@@ -722,30 +775,41 @@ impl AgentAdapter for OpenclawAdapter {
.copied()
.or_else(|| windows.get(key)?.last().map(|(_, id)| *id))
};
- let db_links = db_rows().filter_map(|row| {
- let parent = match row.parent.as_ref()? {
- ParentRef::Session(id) => id.as_str(),
- ParentRef::Key(key) => db_parent(key, row.hint.created_ms)?,
+ // 子会话(列出来的 id)→ 父会话(列出来的 id)。先放库里每一窗记的,再拿旧版索引里的盖上:
+ // 库里那份列出来的会话以库为准(旧版只记了父会话的键,下面不碰它);库里那份没事件、列出来
+ // 的是旧版那份时,旧版索引里有这条会话的关系就用它,没有(子会话键 reset 后索引换成了新的
+ // 那一条)就留着库里那一行记的
+ let mut links: HashMap<&str, &str> = HashMap::new();
+ for row in all_rows() {
+ let parent = match row.parent.as_ref() {
+ Some(ParentRef::Session(id)) => Some(id.as_str()),
+ Some(ParentRef::Key(key)) => db_parent(key, row.hint.created_ms),
+ None => None,
};
- Some((row.session_id.as_str(), parent))
- });
- // 同一会话两代都有(迁进库后旧 jsonl 还在)时关系以库里的为准:旧版只记了父会话的键
- let in_db: HashSet<&str> = db_rows().map(|row| row.session_id.as_str()).collect();
+ if let Some(parent) = parent {
+ links.insert(
+ listed_id(&row.session_id, &in_db, &stems),
+ listed_id(parent, &in_db, &stems),
+ );
+ }
+ }
let legacy_children: Vec<(&str, ParentRef)> = legacy_entries()
.filter(|(id, _)| !in_db.contains(id.as_str()))
.filter_map(|(id, (_, entry))| Some((id.as_str(), ParentRef::of(Some(entry), None)?)))
.collect();
- let legacy_links = legacy_children.iter().filter_map(|(id, parent)| {
+ for (id, parent) in &legacy_children {
let parent = match parent {
- ParentRef::Session(parent) => parent.as_str(),
- ParentRef::Key(key) => legacy_parent(key)?,
+ ParentRef::Session(parent) => Some(parent.as_str()),
+ ParentRef::Key(key) => legacy_parent(key),
};
- Some((*id, parent))
- });
- Some(super::link_keys(
- AgentId::Openclaw,
- db_links.chain(legacy_links),
- ))
+ if let Some(parent) = parent {
+ links.insert(
+ listed_id(id, &in_db, &stems),
+ listed_id(parent, &in_db, &stems),
+ );
+ }
+ }
+ Some(super::link_keys(AgentId::Openclaw, links))
}
/// 关系记在子会话自己的条目里:多 location 下按子会话的胜出副本认边
@@ -753,6 +817,19 @@ impl AgentAdapter for OpenclawAdapter {
true
}
+ /// 旧版的父子关系记在 `agents/<x>/sessions/sessions.json` 里,关系里的 id 又按会话目录里
+ /// 列得出来的转录换算(`listed_id`):两样单独变了(删除也算)都要重取关系
+ fn is_snapshot_event(&self, path: &Path) -> bool {
+ path.parent()
+ .and_then(Path::file_name)
+ .is_some_and(|name| name == "sessions")
+ && path.ancestors().nth(3) == Some(self.root.as_path())
+ && path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .is_some_and(|name| name == "sessions.json" || is_legacy_transcript(name))
+ }
+
// quick_meta 不覆写:库行给不出标题的可靠来源(名字在 session_info 事件里),
// 走全解析
diff --git a/crates/wake-core/src/adapters/opencode.rs b/crates/wake-core/src/adapters/opencode.rs
index 2d6d593..5c40f37 100644
--- a/crates/wake-core/src/adapters/opencode.rs
+++ b/crates/wake-core/src/adapters/opencode.rs
@@ -849,7 +849,8 @@ impl AgentAdapter for OpencodeAdapter {
// 位次相同:更新时间新的,平局虚拟路径小的);每个库各报一遍的话,后报的说了算
let mut chosen: HashMap<&str, (&OcDb, &OcRow)> = HashMap::new();
for (db, rows) in &snapshots {
- for row in rows.iter() {
+ // 没有正文的副本不列(list_session_files 同一条),scanner 用的是另一份,也就不参与裁决
+ for row in rows.iter().filter(|row| row.content_len > 0) {
let wins = chosen.get(row.id.as_str()).is_none_or(|(best_db, best)| {
row.updated_ms > best.updated_ms
|| (row.updated_ms == best.updated_ms
diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rs
index de3d760..2597780 100644
--- a/crates/wake-core/tests/adapter_contracts.rs
+++ b/crates/wake-core/tests/adapter_contracts.rs
@@ -3760,19 +3760,26 @@ fn unreadable_session_databases_freeze_instead_of_emptying() {
assert_eq!(openclaw.parent_links(), None);
}
-/// 旧版的子代理取父会话键眼下那一条,与时间无关:旧版条目常常只有会变的 updatedAt,拿它当
-/// 开始时间的话,父会话再写一轮(updatedAt 晚于子代理)归属就跑到库里更早的窗口去了
-#[test]
-fn openclaw_legacy_children_ignore_update_times() {
- setup();
- let tmp = tempfile::tempdir().unwrap();
- let main = tmp.path().join("agents").join("main");
+/// OpenClaw 的检入 fixture(旧版 jsonl + 现版库)拷进临时目录,返回 `agents/main`;要改文件的
+/// 测试用它,共用的假 HOME 只读
+fn openclaw_copy(tmp: &Path) -> PathBuf {
+ let main = tmp.join("agents").join("main");
common::copy_tree(
&fixture("openclaw/agents/main/sessions"),
&main.join("sessions"),
);
fs::create_dir_all(main.join("agent")).unwrap();
common::build_openclaw_db(&main.join("agent").join("openclaw-agent.sqlite"));
+ main
+}
+
+/// 旧版的子代理取父会话键眼下那一条,与时间无关:旧版条目常常只有会变的 updatedAt,拿它当
+/// 开始时间的话,父会话再写一轮(updatedAt 晚于子代理)归属就跑到库里更早的窗口去了
+#[test]
+fn openclaw_legacy_children_ignore_update_times() {
+ setup();
+ let tmp = tempfile::tempdir().unwrap();
+ let main = openclaw_copy(tmp.path());
let index = main.join("sessions").join("sessions.json");
let later = fs::read_to_string(&index)
.unwrap()
@@ -3786,41 +3793,182 @@ fn openclaw_legacy_children_ignore_update_times() {
)));
}
-/// 同一会话在 stable 与 next 两个库里各有一份时,父子关系跟 scanner 选中的那份走(更新时间新
-/// 的),而不是后读的那个库说了算
+/// 库里没有事件的窗口(迁进库时没带上事件、旧版 jsonl 还在)照样占着时间线上那一段:那段里
+/// 派出的子代理挂到它——列出来的是旧版那份——不能因为它不列就落到更早的那一窗。子会话自己
+/// 的窗口这样空着、旧版索引里又没有它(子会话键 reset 后索引换成了新的那一条)时,关系退回
+/// 库里那一行记的
#[test]
-fn opencode_copies_in_both_databases_follow_the_winning_copy() {
+fn openclaw_empty_windows_still_bound_the_timeline() {
setup();
let tmp = tempfile::tempdir().unwrap();
- let dir = tmp.path().join("opencode");
- fs::create_dir_all(&dir).unwrap();
- let build = |name: &str, child_updated: i64, parent: &str| {
- let conn = rusqlite::Connection::open(dir.join(name)).unwrap();
- conn.execute_batch(
- "CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT, title TEXT,
- time_created INTEGER, time_updated INTEGER, model TEXT, tokens_input INTEGER,
- tokens_output INTEGER, tokens_reasoning INTEGER, time_archived INTEGER,
- version TEXT, parent_id TEXT);
- INSERT INTO session (id, directory, title, time_created, time_updated, version)
- VALUES ('ses_a', '/w', 'a', 1, 1, '1'), ('ses_b', '/w', 'b', 1, 1, '1');",
+ let main = openclaw_copy(tmp.path());
+ rusqlite::Connection::open(main.join("agent").join("openclaw-agent.sqlite"))
+ .unwrap()
+ .execute_batch(
+ "DELETE FROM transcript_events WHERE session_id IN ('claw-0001', 'claw-0005');
+ DELETE FROM session_transcript_active_events
+ WHERE session_id IN ('claw-0001', 'claw-0005');",
)
.unwrap();
- conn.execute(
- "INSERT INTO session (id, directory, title, time_created, time_updated, version, parent_id)
- VALUES ('ses_child', '/w', 'child', 1, ?1, '1', ?2)",
- rusqlite::params![child_updated, parent],
+ for id in ["claw-0001", "claw-0005"] {
+ let header = format!(
+ r#"{{"type":"session","version":3,"id":"{id}","timestamp":"2026-08-08T09:00:00.000Z","cwd":"/Users/tester/Github/wakefx"}}"#
+ );
+ let message = r#"{"type":"message","id":"u1","parentId":null,"timestamp":"2026-08-08T09:00:05.000Z","message":{"role":"user","content":"kept in the old transcript","timestamp":1786266005000}}"#;
+ fs::write(
+ main.join("sessions").join(format!("{id}.jsonl")),
+ format!("{header}\n{message}\n"),
)
.unwrap();
+ }
+ let adapter = OpenclawAdapter::new().with_custom_root(tmp.path().join("agents"));
+ let listed: Vec<(String, String)> = adapter
+ .list_session_files()
+ .unwrap()
+ .into_iter()
+ .map(|r| (r.native_id, r.file_path))
+ .collect();
+ assert!(listed
+ .iter()
+ .any(|(id, path)| id == "claw-0001" && path.ends_with("claw-0001.jsonl")));
+ let links = sorted_links(adapter.as_ref());
+ assert!(links.contains(&edge("openclaw:claw-0002", "openclaw:claw-0001")));
+ assert!(links.contains(&edge("openclaw:claw-0005", "openclaw:claw-0001")));
+}
+
+/// 同一会话在一个 agent 目录里有裸文件名、在另一个目录里只有话题转录:裸的那份列着,关系里的
+/// id 就是它,不能看哪个目录后读
+#[test]
+fn openclaw_bare_transcripts_win_across_agent_dirs() {
+ setup();
+ let tmp = tempfile::tempdir().unwrap();
+ let main = openclaw_copy(tmp.path());
+ let work = tmp.path().join("agents").join("work").join("sessions");
+ fs::create_dir_all(&work).unwrap();
+ fs::copy(
+ main.join("sessions")
+ .join("cccccccc-aaaa-bbbb-cccc-000000000017.jsonl"),
+ work.join("cccccccc-aaaa-bbbb-cccc-000000000017-topic-42.jsonl"),
+ )
+ .unwrap();
+ let adapter = OpenclawAdapter::new().with_custom_root(tmp.path().join("agents"));
+ adapter.list_session_files().unwrap();
+ assert!(sorted_links(adapter.as_ref()).contains(&edge(
+ "openclaw:dddddddd-aaaa-bbbb-cccc-000000000018",
+ "openclaw:cccccccc-aaaa-bbbb-cccc-000000000017"
+ )));
+}
+
+/// 同一会话在 stable 与 next 两个库里各有一份时,父子关系跟 scanner 选中的那份走(更新时间新
+/// 的),而不是后读的那个库说了算;没有正文的副本不列,也不参与
+#[test]
+fn opencode_copies_in_both_databases_follow_the_winning_copy() {
+ setup();
+ let tmp = tempfile::tempdir().unwrap();
+ // 两个库里各一份 ses_child:(更新时间, 父会话, 有没有正文)
+ let links = |stable: (i64, &str, bool), next: (i64, &str, bool)| {
+ let dir = tmp.path().join(format!("case-{}-{}", stable.0, next.0));
+ fs::create_dir_all(&dir).unwrap();
+ for (name, (updated, parent, content)) in
+ [("opencode.db", stable), ("opencode-next.db", next)]
+ {
+ let conn = rusqlite::Connection::open(dir.join(name)).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT, title TEXT,
+ time_created INTEGER, time_updated INTEGER, model TEXT, tokens_input INTEGER,
+ tokens_output INTEGER, tokens_reasoning INTEGER, time_archived INTEGER,
+ version TEXT, parent_id TEXT);
+ CREATE TABLE part (id TEXT PRIMARY KEY, session_id TEXT, data TEXT);
+ INSERT INTO session (id, directory, title, time_created, time_updated, version)
+ VALUES ('ses_a', '/w', 'a', 1, 1, '1'), ('ses_b', '/w', 'b', 1, 1, '1');
+ INSERT INTO part VALUES ('pa', 'ses_a', 'a'), ('pb', 'ses_b', 'b');",
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO session (id, directory, title, time_created, time_updated, version, parent_id)
+ VALUES ('ses_child', '/w', 'child', 1, ?1, '1', ?2)",
+ rusqlite::params![updated, parent],
+ )
+ .unwrap();
+ if content {
+ conn.execute_batch("INSERT INTO part VALUES ('pc', 'ses_child', 'child')")
+ .unwrap();
+ }
+ }
+ let adapter = OpencodeAdapter::new().with_custom_root(dir);
+ adapter.list_session_files().unwrap();
+ sorted_links(adapter.as_ref())
};
// stable 那份更新、先读;next 那份旧、后读
- build("opencode.db", 200, "ses_a");
- build("opencode-next.db", 100, "ses_b");
- let adapter = OpencodeAdapter::new().with_custom_root(dir.clone());
- adapter.list_session_files().unwrap();
assert_eq!(
- sorted_links(adapter.as_ref()),
+ links((200, "ses_a", true), (100, "ses_b", true)),
vec![edge("opencode:ses_child", "opencode:ses_a")]
);
+ // 更新的那份没有正文:列表不收它,scanner 用的是 next 那份
+ assert_eq!(
+ links((300, "ses_a", false), (100, "ses_b", true)),
+ vec![edge("opencode:ses_child", "opencode:ses_b")]
+ );
+}
+
+/// 旧版带话题的会话,转录叫 `<id>-topic-<话题>.jsonl`、列出来的 id 是整个主干:父会话只有
+/// 话题转录时,子代理要挂到列出来的那个 id 上,不是索引里的裸 id
+#[test]
+fn openclaw_legacy_topic_transcripts_keep_their_links() {
+ setup();
+ let tmp = tempfile::tempdir().unwrap();
+ let sessions = openclaw_copy(tmp.path()).join("sessions");
+ fs::rename(
+ sessions.join("cccccccc-aaaa-bbbb-cccc-000000000017.jsonl"),
+ sessions.join("cccccccc-aaaa-bbbb-cccc-000000000017-topic-42.jsonl"),
+ )
+ .unwrap();
+ let adapter = OpenclawAdapter::new().with_custom_root(tmp.path().join("agents"));
+ let ids: Vec<String> = adapter
+ .list_session_files()
+ .unwrap()
+ .into_iter()
+ .map(|r| r.native_id)
+ .collect();
+ assert!(ids.contains(&"cccccccc-aaaa-bbbb-cccc-000000000017-topic-42".to_string()));
+ assert!(sorted_links(adapter.as_ref()).contains(&edge(
+ "openclaw:dddddddd-aaaa-bbbb-cccc-000000000018",
+ "openclaw:cccccccc-aaaa-bbbb-cccc-000000000017-topic-42"
+ )));
+ // 空的话题文件列表不收,也不拿来改写 id:子代理记着的确切父会话这里只剩一个空的话题
+ // 文件时,关系仍指向它原本的 id(那条会话可能在别的 location 里)
+ let index = sessions.join("sessions.json");
+ let mut entries: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(&index).unwrap()).unwrap();
+ entries["agent:main:subagent:ffff"] = serde_json::json!({
+ "sessionId": "ffffffff-aaaa-bbbb-cccc-000000000019",
+ "updatedAt": 1786183300000_i64,
+ "parentSessionId": "99999999-aaaa-bbbb-cccc-000000000099"
+ });
+ fs::write(&index, entries.to_string()).unwrap();
+ fs::copy(
+ sessions.join("dddddddd-aaaa-bbbb-cccc-000000000018.jsonl"),
+ sessions.join("ffffffff-aaaa-bbbb-cccc-000000000019.jsonl"),
+ )
+ .unwrap();
+ fs::write(
+ sessions.join("99999999-aaaa-bbbb-cccc-000000000099-topic-42.jsonl"),
+ "",
+ )
+ .unwrap();
+ adapter.list_session_files().unwrap();
+ assert!(sorted_links(adapter.as_ref()).contains(&edge(
+ "openclaw:ffffffff-aaaa-bbbb-cccc-000000000019",
+ "openclaw:99999999-aaaa-bbbb-cccc-000000000099"
+ )));
+ // 父子关系记在 sessions.json 里、关系里的 id 按列得出来的转录换算:这两样单独变了(删除也
+ // 算)都是快照事件,监听会重取关系;检查点与库文件不是
+ assert!(adapter.is_snapshot_event(&sessions.join("sessions.json")));
+ assert!(adapter.is_snapshot_event(&sessions.join("dddddddd-aaaa-bbbb-cccc-000000000018.jsonl")));
+ assert!(!adapter.is_snapshot_event(
+ &sessions.join("cccccccc-aaaa-bbbb-cccc-000000000017.checkpoint.1.jsonl")
+ ));
+ assert!(!adapter.is_snapshot_event(&tmp.path().join("agents/main/agent/openclaw-agent.sqlite")));
}
/// 自定义 location:构造器只认 home 与孤立的库文件两种形状,且只按路径整形不看