All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
fix(codex): keep every internal Codex thread out of the index
Corey Chiu9e53164b61f6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f59a8e1..07d4fb1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## Unreleased++- Fix: Codex's background threads — the guardian auto-review, `/review`, compaction, memory consolidation and spawned sub-agents — no longer show up as sessions; they were listed as `Untitled` or as a copy of their parent, and reached search, project counts and the MCP tools too. Existing indexes drop them on the next scan+## [0.6.5] — 2026-09-14- New: `wake_get_session` and `wake-cli show` can read a subagent transcript — the main transcript now lists their ids; pass one as `subagent` / `--subagent`, or `*` to list them alldiff --git a/crates/wake-core/src/adapters/codex.rs b/crates/wake-core/src/adapters/codex.rsindex ba3bdc9..c6e7119 100644--- a/crates/wake-core/src/adapters/codex.rs+++ b/crates/wake-core/src/adapters/codex.rs@@ -4,6 +4,7 @@ use super::{units_from_messages, AgentAdapter};use crate::models::*;use anyhow::Result;use rusqlite::Connection;+use serde::Deserialize;use serde_json::Value;use std::collections::HashMap;use std::fmt::Write as _;@@ -42,35 +43,66 @@ fn rollout_file_name(path: &str) -> &str {path.rsplit(['/', '\\']).next().unwrap_or(path)}-/// Codex Desktop 会为内部命令审批启动 guardian reviewer,并把它们写进与用户-/// 会话相同的 rollout 树。Desktop/TUI 不把这类内部线程当会话展示,Wake 也应在-/// adapter 边界排除,而不是让 UI、FTS 与 MCP 各自猜一次。+/// Codex 把它启动的**每一条**线程都写进同一棵 rollout 树:用户线程之外还有+/// guardian auto-review、`/review`、compaction、memory consolidation 与+/// thread_spawn 子代理。它自家的历史只列交互来源(cli/vscode/atlas/chatgpt),+/// Wake 则把"非用户线程"整族挡在 adapter 文件边界——UI、FTS、MCP 共用同一份+/// 索引,不必各猜一次(issue #30)。///-/// `source.subagent.other = "guardian"` 是目前最稳定的结构化标记;早期/过渡格式-/// 也可能只给出 `thread_source = "guardian_review"`。只读首条 session_meta,-/// 解析失败时保守地保留文件,避免因半写入或未来格式变化误伤真实会话。-fn is_guardian_review(path: &Path) -> bool {+/// 判据只读首行 session_meta:`source` 是对象即结构化来源——`subagent` 的+/// review/compact/thread_spawn/memory_consolidation/other,`internal` 的+/// guardian/memory_consolidation——字符串来源(cli/vscode/exec/mcp/unknown/+/// 自定义)才是用户线程;`thread_source` 另认 subagent/guardian_review/+/// memory_consolidation 三个内部值(issue 里的过渡格式只带这个字段)。上游落盘+/// 时把 Internal(Guardian) 改写成 SubAgent(Other("guardian")),两套写法都要认。+/// `thread_source` 的其余值是 `codex exec --thread-source` 给自动化打的 Feature+/// 标签,走 exec 这条 Wake 本就展示的路,照常保留。首行读不出、不是 JSON 或+/// 不是 session_meta(2025 老格式)一律保守放行:半写入或未来格式不能让真实+/// 会话消失。review 子线程的结果本就经 `<user_action>` 注入父会话渲染;+/// thread_spawn 子代理转录暂不展示,日后可走 parent_links 挂回父会话。+fn is_internal_thread(path: &Path) -> bool {let Ok(file) = fs::File::open(path) else {return false;};- let mut first_line = String::new();- if BufReader::new(file).read_line(&mut first_line).ok() == Some(0) {+ // payload 还带 base_instructions:实测首行中位数 18 KB、最大 49 KB+ // (2026-09-15),预留容量免得 read_line 反复倍增+ let mut first_line = String::with_capacity(1 << 16);+ if BufReader::new(file).read_line(&mut first_line).unwrap_or(0) == 0 {return false;}- let Ok(row) = serde_json::from_str::<Value>(&first_line) else {+ let Ok(head) = serde_json::from_str::<SessionMetaHead>(&first_line) else {return false;};- if row.get("type").and_then(Value::as_str) != Some("session_meta") {+ if head.kind != "session_meta" {return false;}- let Some(payload) = row.get("payload") else {+ let Some(payload) = head.payload else {return false;};- payload- .pointer("/source/subagent/other")- .and_then(Value::as_str)- == Some("guardian")- || payload.get("thread_source").and_then(Value::as_str) == Some("guardian_review")+ payload.source.is_some_and(|source| source.is_object())+ || matches!(+ payload.thread_source.as_deref(),+ Some("subagent" | "guardian_review" | "memory_consolidation")+ )+}++/// `is_internal_thread` 只看的两个键。按窄结构反序列化,serde 跳过+/// base_instructions 那几十 KB 而不是整棵 Value 建起来再丢——别换回 Value+#[derive(Deserialize)]+struct SessionMetaHead {+ #[serde(rename = "type")]+ kind: String,+ #[serde(default)]+ payload: Option<SessionMetaPayloadHead>,+}++#[derive(Deserialize)]+struct SessionMetaPayloadHead {+ /// 字符串 = 用户线程来源;对象 = subagent / internal 结构化来源(本身很小)+ #[serde(default)]+ source: Option<Value>,+ #[serde(default)]+ thread_source: Option<String>,}/// rollout 存储本体(用户选中的是数据目录而非 codex home):自身不含@@ -751,20 +783,14 @@ impl AgentAdapter for CodexAdapter {}fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {- let mut refs = if self.scan_sessions {- list_jsonl_refs(&self.sessions_dir, AgentId::Codex, rollout_native_id)- } else {- Vec::new()- };- if self.scan_archived {- refs.extend(list_jsonl_refs(- &self.archived_dir,- AgentId::Codex,- rollout_native_id,- ));- }- refs.retain(|r| !is_guardian_review(Path::new(&r.file_path)));- Ok(refs)+ // 全量枚举与 watcher 同走 file_ref 这一个漏斗(dsh 同款):native id 剥离+ // 与内部线程判定只存在一处,两条入口不可能分家;缺根时 jsonl_entries 给空+ Ok(self+ .data_roots()+ .iter()+ .flat_map(|root| jsonl_entries(root))+ .filter_map(|entry| self.file_ref(entry.path()))+ .collect())}fn quick_meta(&self, refs: &[SessionFileRef]) -> Option<HashMap<String, SessionMeta>> {@@ -830,7 +856,7 @@ impl AgentAdapter for CodexAdapter {fn file_ref(&self, path: &Path) -> Option<SessionFileRef> {let mut r = default_file_ref(self.agent(), path)?;- if is_guardian_review(path) {+ if is_internal_thread(path) {return None;}r.native_id = rollout_native_id(&r.native_id);diff --git a/crates/wake-core/src/adapters/parse_utils.rs b/crates/wake-core/src/adapters/parse_utils.rsindex b969a53..507ae38 100644--- a/crates/wake-core/src/adapters/parse_utils.rs+++ b/crates/wake-core/src/adapters/parse_utils.rs@@ -224,6 +224,19 @@ pub fn usage_tokens(usage: &Value) -> i64 {.sum()}+/// 递归枚举 `dir` 下的 `*.jsonl` 普通文件。file_type 来自 readdir、不额外+/// stat;根不存在或不是目录给空迭代(各家 list_session_files 对缺根自行降级,+/// 不变量 8①)。想在文件边界再加判据的家(codex)拿它喂自己的 `file_ref` 漏斗+pub fn jsonl_entries(dir: &std::path::Path) -> impl Iterator<Item = walkdir::DirEntry> {+ walkdir::WalkDir::new(dir)+ .min_depth(1)+ .into_iter()+ .flatten()+ .filter(|entry| {+ entry.file_type().is_file() && entry.file_name().to_string_lossy().ends_with(".jsonl")+ })+}+/// 递归枚举目录下非空 .jsonl 为 SessionFileRef;`native_id` 从文件 stem 提取/// 会话 id(多数家恒等,codex 需剥 rollout 前缀)pub fn list_jsonl_refs(@@ -232,14 +245,8 @@ pub fn list_jsonl_refs(native_id: impl Fn(&str) -> String,) -> Vec<SessionFileRef> {let mut refs = Vec::new();- if !dir.is_dir() {- return refs;- }- for entry in walkdir::WalkDir::new(dir).into_iter().flatten() {- if !entry.file_type().is_file() {- continue;- }- let name = entry.file_name().to_string_lossy().to_string();+ for entry in jsonl_entries(dir) {+ let name = entry.file_name().to_string_lossy();let Some(stem) = name.strip_suffix(".jsonl") else {continue;};diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rsindex 67dea8d..5766f50 100644--- a/crates/wake-core/tests/adapter_contracts.rs+++ b/crates/wake-core/tests/adapter_contracts.rs@@ -254,7 +254,7 @@ fn codex_inline_images_decode_and_strip_desktop_wrappers() {);assert_eq!(session.meta.title, "这个按钮颜色不对");}-fn codex_subagent_ref() -> SessionFileRef {+fn codex_branch_ref() -> SessionFileRef {fs_ref(AgentId::Codex,&fixture("codex/sessions/2026/08/07/rollout-2026-08-07T12-44-01-33333333-aaaa-bbbb-cccc-000000000003.jsonl"),@@ -460,60 +460,25 @@ fn codex_parse_contract() {);}+/// Codex 把非用户线程与用户会话写进同一棵树;文件边界按首行 session_meta 把+/// 整族挡掉。全量枚举走 file_ref 漏斗,这里两道都断言,守住"不可能分家"。+/// 判不出用途的首行——老写端无 thread_source、exec 的 Feature 标签、2025 老格式、+/// 截断的 JSON——一律保守可见(issue #30)#[test]-fn codex_guardian_reviews_are_excluded_without_hiding_regular_subagents() {+fn codex_internal_threads_are_excluded_at_the_file_boundary() {setup();let home = tempfile::tempdir().unwrap();let day = home.path().join("sessions/2026/09/14");fs::create_dir_all(&day).unwrap();+ let adapter = CodexAdapter::new().with_custom_root(home.path().to_path_buf());- let cases = [- (- "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",- serde_json::json!({- "source": { "subagent": { "other": "guardian" } },- "thread_source": "subagent"- }),- false,- ),- (- "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",- serde_json::json!({- "source": { "subagent": { "other": "guardian" } }- }),- false,- ),- (- "cccccccc-cccc-4ccc-8ccc-cccccccccccc",- serde_json::json!({- "source": "cli",- "thread_source": "guardian_review"- }),- false,- ),- (- "dddddddd-dddd-4ddd-8ddd-dddddddddddd",- serde_json::json!({- "parent_thread_id": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee",- "source": {- "subagent": {- "thread_spawn": {- "parent_thread_id": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee",- "depth": 1,- "agent_path": "/root/research"- }- }- },- "thread_source": "subagent"- }),- true,- ),- ];-- let mut expected = HashSet::new();- for (index, (id, source_fields, visible)) in cases.iter().enumerate() {+ fn id(n: u32) -> String {+ format!("00000000-0000-4000-8000-{n:012}")+ }+ // 一条 session_meta 首行;extra 是要试的 source / thread_source 字段+ let meta = |n: u32, extra: serde_json::Value| {let mut payload = serde_json::json!({- "id": id,+ "id": id(n),"timestamp": "2026-09-14T00:00:00.000Z","cwd": "/work/wake","originator": "codex_work_desktop"@@ -521,33 +486,87 @@ fn codex_guardian_reviews_are_excluded_without_hiding_regular_subagents() {payload.as_object_mut().unwrap()- .extend(source_fields.as_object().unwrap().clone());- let path = day.join(format!("rollout-2026-09-14T00-00-0{index}-{id}.jsonl"));- fs::write(- &path,- format!(- "{}\n",- serde_json::json!({- "timestamp": "2026-09-14T00:00:00.000Z",- "type": "session_meta",- "payload": payload- })- ),- )- .unwrap();+ .extend(extra.as_object().unwrap().clone());+ let line = serde_json::json!({+ "timestamp": "2026-09-14T00:00:00.000Z",+ "type": "session_meta",+ "payload": payload+ });+ (id(n), line.to_string())+ };+ let spawn = serde_json::json!({+ "parent_thread_id": id(99), "depth": 1, "agent_path": "/root/research"+ });+ // 隐藏的那组是上游各种落盘形态的抽样:`source` 是对象这一条就够判,列全是+ // 为了谁把它收窄成按路径取值(pointer("/source/subagent/other"))时立刻红+ let cases = [+ // guardian auto-review:早期写端 thread_source 仍是 subagent;只带对象;+ // issue #30 的过渡格式只带 thread_source;字符串来源 + thread_source=subagent+ (meta(1, serde_json::json!({"source": {"subagent": {"other": "guardian"}}, "thread_source": "subagent"})), false),+ (meta(2, serde_json::json!({"source": {"subagent": {"other": "guardian"}}})), false),+ (meta(3, serde_json::json!({"source": "cli", "thread_source": "guardian_review"})), false),+ (meta(4, serde_json::json!({"source": "exec", "thread_source": "subagent"})), false),+ // `/review`、compaction、thread_spawn 子代理+ (meta(5, serde_json::json!({"source": {"subagent": "review"}, "thread_source": "subagent"})), false),+ (meta(6, serde_json::json!({"source": {"subagent": "compact"}, "thread_source": "subagent"})), false),+ (meta(7, serde_json::json!({"parent_thread_id": id(99), "source": {"subagent": {"thread_spawn": spawn}}, "thread_source": "subagent"})), false),+ // memory consolidation 的 subagent / internal 两种写法;上游今天落盘前会把+ // Internal(Guardian) 改写成 subagent/other,哪天不改写了也要认+ (meta(8, serde_json::json!({"source": {"subagent": "memory_consolidation"}})), false),+ (meta(9, serde_json::json!({"source": {"internal": "memory_consolidation"}, "thread_source": "memory_consolidation"})), false),+ (meta(10, serde_json::json!({"source": {"internal": "guardian"}, "thread_source": "guardian_review"})), false),+ // 用户线程:字符串来源的各种写法,含 `codex exec --thread-source` 的 Feature 标签+ (meta(11, serde_json::json!({"source": "vscode", "thread_source": "user"})), true),+ (meta(12, serde_json::json!({"source": "exec"})), true),+ (meta(13, serde_json::json!({"source": "exec", "thread_source": "nightly_automation"})), true),+ (meta(14, serde_json::json!({"source": "unknown"})), true),+ // 首行不是 session_meta(2025 老格式)或 JSON 截断:判不出用途就保守放行+ ((id(15), format!(r#"{{"id":"{}","timestamp":"2025-09-15T07:46:43.457Z","instructions":null}}"#, id(15))), true),+ ((id(16), r#"{"timestamp":"2026-09-14T00:20:00.000Z","type":"session_meta","payload":{"id":""#.to_string()), true),+ ];- let adapter = CodexAdapter::new().with_custom_root(home.path().to_path_buf());+ let mut expected = HashSet::new();+ for (index, ((id, line), visible)) in cases.into_iter().enumerate() {+ let path = day.join(format!("rollout-2026-09-14T00-{index:02}-00-{id}.jsonl"));+ fs::write(&path, format!("{line}\n")).unwrap();assert_eq!(adapter.file_ref(&path).is_some(),- *visible,+ visible,"watcher file_ref visibility for {id}");- if *visible {- expected.insert((*id).to_string());+ if visible {+ expected.insert(id);+ }+ }++ // archived_sessions(平铺布局)走同一漏斗:内部线程照样挡、用户线程照样进+ let archived = home.path().join("archived_sessions");+ fs::create_dir_all(&archived).unwrap();+ for (n, extra, visible) in [+ (+ 17,+ serde_json::json!({"source": "cli", "thread_source": "user"}),+ true,+ ),+ (+ 18,+ serde_json::json!({"source": {"subagent": "review"}, "thread_source": "subagent"}),+ false,+ ),+ ] {+ let (id, line) = meta(n, extra);+ let path = archived.join(format!("rollout-2026-09-14T01-00-00-{id}.jsonl"));+ fs::write(&path, format!("{line}\n")).unwrap();+ assert_eq!(+ adapter.file_ref(&path).is_some(),+ visible,+ "archived file_ref visibility for {id}"+ );+ if visible {+ expected.insert(id);}}- let adapter = CodexAdapter::new().with_custom_root(home.path().to_path_buf());let actual: HashSet<String> = adapter.list_session_files().unwrap()@@ -2079,18 +2098,26 @@ fn removed_defaults_suppress_instances() {.all(|r| r.starts_with(dir.path())));}+/// 注入模板出现在 role=user 消息里时归 Meta。fixture 3 是从父会话分出来的+/// **用户**线程(forked_from_id、字符串 source),走得到文件边界——guardian+/// 形态已在 codex_internal_threads_are_excluded_at_the_file_boundary 里覆盖,+/// 这里不能再用一个枚举不到的文件当被测对象#[test]-fn codex_subagent_transcript_injection_is_meta() {+fn codex_branch_transcript_injection_is_meta() {setup();let adapter = CodexAdapter::new();- let r = codex_subagent_ref();+ let r = codex_branch_ref();+ assert!(+ adapter.file_ref(Path::new(&r.file_path)).is_some(),+ "用户分支线程在文件边界可见"+ );let t = adapter.parse_transcript(&r)- .expect("codex subagent parse_transcript");+ .expect("codex branch parse_transcript");- // 分支 / subagent 线程把**父会话的整段 transcript** 打包成一条- // role=user 的消息喂进来,里面含父会话的 assistant 输出。不识别的话,- // 父会话里 AI 说的话会显示成这个会话里用户发的+ // 父会话的整段 transcript 被打包成一条 role=user 的消息喂进来,里面含+ // 父会话的 assistant 输出。不识别的话,父会话里 AI 说的话会显示成这个+ // 会话里用户发的let injected = t.mainline.iter()@@ -2125,7 +2152,7 @@ fn codex_subagent_transcript_injection_is_meta() {// Meta 不进 FTS:注入进来的父会话内容不该被搜索命中let s = adapter.parse_session(&r)- .expect("codex subagent parse_session");+ .expect("codex branch parse_session");assert!(!s.units.iter().any(|u| u.text.contains("[2] assistant:")),"注入的父会话 transcript 不得进入检索单元"diff --git a/crates/wake-core/tests/fixtures/codex/sessions/2026/08/07/rollout-2026-08-07T12-44-01-33333333-aaaa-bbbb-cccc-000000000003.jsonl b/crates/wake-core/tests/fixtures/codex/sessions/2026/08/07/rollout-2026-08-07T12-44-01-33333333-aaaa-bbbb-cccc-000000000003.jsonlindex 416d851..e2fa7b2 100644--- a/crates/wake-core/tests/fixtures/codex/sessions/2026/08/07/rollout-2026-08-07T12-44-01-33333333-aaaa-bbbb-cccc-000000000003.jsonl+++ b/crates/wake-core/tests/fixtures/codex/sessions/2026/08/07/rollout-2026-08-07T12-44-01-33333333-aaaa-bbbb-cccc-000000000003.jsonl@@ -1,4 +1,4 @@-{"timestamp":"2026-08-07T12:44:01.000Z","type":"session_meta","payload":{"id":"33333333-aaaa-bbbb-cccc-000000000003","parent_thread_id":"22222222-aaaa-bbbb-cccc-000000000002","thread_source":"subagent","timestamp":"2026-08-07T12:44:01.000Z","cwd":"/Users/tester/Github/wakefx","originator":"codex_cli_rs","cli_version":"0.0.1","source":{"subagent":{"other":"guardian"}}}}+{"timestamp":"2026-08-07T12:44:01.000Z","type":"session_meta","payload":{"id":"33333333-aaaa-bbbb-cccc-000000000003","forked_from_id":"22222222-aaaa-bbbb-cccc-000000000002","thread_source":"user","timestamp":"2026-08-07T12:44:01.000Z","cwd":"/Users/tester/Github/wakefx","originator":"codex_cli_rs","cli_version":"0.0.1","source":"cli"}}{"timestamp":"2026-08-07T12:44:02.000Z","type":"turn_context","payload":{"cwd":"/Users/tester/Github/wakefx","model":"gpt-5.2-codex"}}{"timestamp":"2026-08-07T12:44:03.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"The following is the Codex agent history whose request action you are assessing."},{"type":"input_text","text":">>> TRANSCRIPT START"},{"type":"input_text","text":"[1] user: 扫码登录报错,帮我查一下 useEffect() 依赖数组"},{"type":"input_text","text":"[2] assistant: 依赖数组漏了 token,补上就不会重复触发了。"},{"type":"input_text","text":">>> TRANSCRIPT END"}]}}{"timestamp":"2026-08-07T12:44:04.000Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"这次改动只碰了依赖数组,判定为安全。"}]}}