Skip to content

armgit / Wake

Public Imported from GitHub
0

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

Rust

feat(mcp): read-only MCP server wake-mcp and Settings → Connect

Corey Chiuf2f6a85952f0
diff --git a/crates/wake-core/Cargo.toml b/crates/wake-core/Cargo.toml
index 2558ae5..244e679 100644
--- a/crates/wake-core/Cargo.toml
+++ b/crates/wake-core/Cargo.toml
@@ -45,3 +45,8 @@ tempfile = "3"
[[bin]]
name = "scan"
path = "src/bin/scan.rs"
+
+# 只读 MCP server(stdio),随 Wake 一起打包、与主程序并排;见 src/mcp/
+[[bin]]
+name = "wake-mcp"
+path = "src/bin/wake_mcp.rs"
diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rs
index 9b93787..a18b529 100644
--- a/crates/wake-core/src/adapters/mod.rs
+++ b/crates/wake-core/src/adapters/mod.rs
@@ -440,3 +440,18 @@ pub(crate) fn units_from_messages(messages: &[TranscriptMessage]) -> Vec<IndexUn
})
.collect()
}
+
+/// 手输路径的 `~` 前缀展开(仅前缀;边界落在分隔符上,Windows 用户手输
+/// `~\foo` 同样认)。HOME 与 adapter 同源(`home_dir` 的 WAKE_HOME 开关);
+/// UI 的 `format::expand_tilde` 与 wake-mcp 的 project 参数都走这里
+pub fn expand_tilde(p: &str) -> String {
+ match p.strip_prefix('~') {
+ Some(rest) if rest.is_empty() || rest.starts_with(std::path::is_separator) => {
+ match home_dir() {
+ Some(h) => format!("{}{rest}", h.to_string_lossy()),
+ None => p.to_string(),
+ }
+ }
+ _ => p.to_string(),
+ }
+}
diff --git a/crates/wake-core/src/bin/wake_mcp.rs b/crates/wake-core/src/bin/wake_mcp.rs
new file mode 100644
index 0000000..7147c34
--- /dev/null
+++ b/crates/wake-core/src/bin/wake_mcp.rs
@@ -0,0 +1,161 @@
+//! wake-mcp:Wake 索引的只读 MCP server(stdio)。
+//!
+//! wake-mcp [--db PATH] 以 MCP server 身份服务 stdin/stdout(客户端这样起它)
+//! wake-mcp setup [--db PATH] 打印接入 Claude Code / Codex / Cursor 的配置片段
+//! wake-mcp call TOOL [JSON] 跑一次工具调用、打印文本(调试用)
+//! wake-mcp --version | --help
+//!
+//! 索引库默认取 GUI 同一份(`db::default_db_path`),只读打开;库不存在或太老
+//! 直接以清晰的 stderr 错误退出(非零),让客户端的日志说明白"先启动一次 Wake"。
+use std::io::{self, Write as _};
+use std::path::PathBuf;
+use std::process::ExitCode;
+use std::sync::Arc;
+
+use wake_core::adapters::create_adapters_for;
+use wake_core::db::Store;
+use wake_core::mcp::{self, McpServer};
+
+const USAGE: &str = "wake-mcp — read-only MCP server for your Wake session index
+
+USAGE:
+ wake-mcp [--db PATH] serve MCP over stdio (what MCP clients run)
+ wake-mcp setup [--db PATH] print config snippets for Claude Code / Codex / Cursor
+ wake-mcp call TOOL [JSON] run one tool call and print its text (debugging)
+ wake-mcp --version | --help
+
+OPTIONS:
+ --db PATH index database (default: Wake's own, e.g. ~/Library/Application Support/wake/wake.db)";
+
+struct Args {
+ db: Option<PathBuf>,
+ command: Vec<String>,
+}
+
+fn parse_args() -> Result<Args, String> {
+ let mut db = None;
+ let mut command = Vec::new();
+ let mut it = std::env::args().skip(1);
+ while let Some(a) = it.next() {
+ match a.as_str() {
+ "--db" => {
+ db = Some(PathBuf::from(
+ it.next().ok_or("--db needs a path".to_string())?,
+ ))
+ }
+ "--help" | "-h" => {
+ println!("{USAGE}");
+ std::process::exit(0);
+ }
+ "--version" | "-V" => {
+ println!("wake-mcp {}", mcp::SERVER_VERSION);
+ std::process::exit(0);
+ }
+ s if s.starts_with("--db=") => db = Some(PathBuf::from(&s[5..])),
+ s if s.starts_with('-') => return Err(format!("unknown option {s}\n\n{USAGE}")),
+ _ => command.push(a),
+ }
+ }
+ Ok(Args { db, command })
+}
+
+fn db_path(db: &Option<PathBuf>) -> PathBuf {
+ db.clone().unwrap_or_else(wake_core::db::default_db_path)
+}
+
+fn open(db: &Option<PathBuf>) -> Result<McpServer, String> {
+ let store = Store::open_read_only(&db_path(db)).map_err(|e| format!("{e:#}"))?;
+ let store = Arc::new(store);
+ // 必须带上库里的 location / remote host 配置(不变量 8⑥),否则自定义根
+ // 与远程缓存里的会话找不到能读它的 adapter
+ let adapters = create_adapters_for(&store);
+ Ok(McpServer::new(store, adapters))
+}
+
+fn main() -> ExitCode {
+ let args = match parse_args() {
+ Ok(a) => a,
+ Err(e) => {
+ eprintln!("wake-mcp: {e}");
+ return ExitCode::from(2);
+ }
+ };
+ match args.command.first().map(String::as_str) {
+ None => {
+ let server = match open(&args.db) {
+ Ok(s) => s,
+ Err(e) => {
+ eprintln!("wake-mcp: {e}");
+ return ExitCode::from(2);
+ }
+ };
+ let stdin = io::stdin();
+ let stdout = io::stdout();
+ match server.serve(stdin.lock(), stdout.lock()) {
+ Ok(()) => ExitCode::SUCCESS,
+ // 客户端先走一步、管道断开是正常收场
+ Err(e) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
+ Err(e) => {
+ eprintln!("wake-mcp: {e}");
+ ExitCode::from(1)
+ }
+ }
+ }
+ Some("setup") => {
+ let bin = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("wake-mcp"));
+ let mut out = io::stdout().lock();
+ let _ = writeln!(out, "wake-mcp binary: {}\n", bin.display());
+ for s in mcp::setup_snippets(&bin) {
+ let _ = writeln!(out, "## {} — {}\n\n{}\n", s.client, s.hint, s.text);
+ }
+ // 只探库,不必为一行提示把十六家 roster 建起来
+ if let Err(e) = Store::open_read_only(&db_path(&args.db)) {
+ let _ = writeln!(out, "Note: {e:#}");
+ }
+ ExitCode::SUCCESS
+ }
+ Some("call") => {
+ let Some(tool) = args.command.get(1) else {
+ eprintln!("wake-mcp: call needs a tool name\n\n{USAGE}");
+ return ExitCode::from(2);
+ };
+ let json_args = args.command.get(2).map(String::as_str).unwrap_or("{}");
+ let params: serde_json::Value = match serde_json::from_str(json_args) {
+ Ok(v) => v,
+ Err(e) => {
+ eprintln!("wake-mcp: arguments are not valid JSON: {e}");
+ return ExitCode::from(2);
+ }
+ };
+ let server = match open(&args.db) {
+ Ok(s) => s,
+ Err(e) => {
+ eprintln!("wake-mcp: {e}");
+ return ExitCode::from(2);
+ }
+ };
+ let request = serde_json::json!({
+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": { "name": tool, "arguments": params },
+ });
+ let reply = server.handle_line(&request.to_string()).unwrap_or_default();
+ let reply: serde_json::Value = serde_json::from_str(&reply).unwrap_or_default();
+ if let Some(err) = reply.get("error") {
+ eprintln!("wake-mcp: {}", err["message"].as_str().unwrap_or("error"));
+ return ExitCode::from(1);
+ }
+ let text = reply["result"]["content"][0]["text"]
+ .as_str()
+ .unwrap_or_default();
+ println!("{text}");
+ if reply["result"]["isError"].as_bool().unwrap_or(false) {
+ return ExitCode::from(1);
+ }
+ ExitCode::SUCCESS
+ }
+ Some(other) => {
+ eprintln!("wake-mcp: unknown command {other}\n\n{USAGE}");
+ ExitCode::from(2)
+ }
+ }
+}
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index d5afbd1..9293d01 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -162,7 +162,7 @@ fn open_conn(path: &Path) -> Result<Connection> {
)?;
// host 迁移(2026-09-01 远程会话加列;空串 = 本地)。老库首扫时既有行
// 全部落 '',与远程装饰器生产的非空 host 天然分域,无需回填
- if !table_has_column(&conn, "sessions", "host")? {
+ if !table_has_column(&conn, NEWEST_COLUMN.0, NEWEST_COLUMN.1)? {
conn.execute(
"ALTER TABLE sessions ADD COLUMN host TEXT NOT NULL DEFAULT ''",
[],
@@ -177,6 +177,21 @@ fn open_conn(path: &Path) -> Result<Connection> {
Ok(conn)
}
+/// 最近一次迁移加的列——`open_read_only` 用它判断库够不够新。**加新迁移时把
+/// 这里改成新列**,否则只读入口会放行老库、深处查询才报 no such column
+const NEWEST_COLUMN: (&str, &str) = ("sessions", "host");
+
+/// 只读连接:不建表、不迁移、不改 journal_mode(旁路进程用;`open_read_only`
+/// 与只读 Store 的 insights 临时连接共用,别的入口不要直开)
+fn open_conn_ro(path: &Path) -> Result<Connection> {
+ let conn = Connection::open_with_flags(
+ path,
+ rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )?;
+ conn.busy_timeout(std::time::Duration::from_millis(3000))?;
+ Ok(conn)
+}
+
fn table_has_column(conn: &Connection, table: &str, column: &str) -> Result<bool> {
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
let names = stmt.query_map([], |row| row.get::<_, String>(1))?;
@@ -222,6 +237,9 @@ pub struct Store {
/// insights() 开临时连接用:统计要连扫 messages 几十毫秒,共用唯一
/// 读连接会让 UI 线程的列表查询排队等它(2026-08-27 Codex review)
path: std::path::PathBuf,
+ /// `open_read_only` 建的实例:所有连接(含 insights 的临时连接)都只读,
+ /// 写方法在运行期报 SQLITE_READONLY
+ read_only: bool,
}
impl Store {
@@ -230,9 +248,47 @@ impl Store {
write: Mutex::new(open_conn(path)?),
read: Mutex::new(open_conn(path)?),
path: path.to_path_buf(),
+ read_only: false,
+ })
+ }
+
+ /// 只读打开既有索引库(wake-mcp 这类旁路读者用):不建表、不迁移、不改
+ /// journal_mode;库不存在或 schema 太老直接报错——重建权只归 GUI 的
+ /// `open_or_rebuild`,旁路进程绝不能把正在被 GUI 写的库挪走重建。
+ /// WAL 下读者不阻塞 GUI 写入;只读连接要能建 -shm,同用户下目录可写即可
+ pub fn open_read_only(path: &Path) -> Result<Self> {
+ if !path.is_file() {
+ anyhow::bail!(
+ "no Wake index at {} — launch Wake once to build it",
+ path.display()
+ );
+ }
+ let read = open_conn_ro(path)?;
+ if !table_has_column(&read, NEWEST_COLUMN.0, NEWEST_COLUMN.1)? {
+ anyhow::bail!(
+ "Wake index at {} is empty or from an older version — launch Wake once to upgrade it",
+ path.display()
+ );
+ }
+ Ok(Self {
+ // Store 的形状要求有 write 连接;这里给的同样是只读句柄
+ write: Mutex::new(open_conn_ro(path)?),
+ read: Mutex::new(read),
+ path: path.to_path_buf(),
+ read_only: true,
})
}
+ /// 索引覆盖到的最新会话活动时间(epoch ms;空库 None)。wake-mcp 把它随
+ /// 每次工具返回带给 agent,让对方知道索引有多新——GUI 没跑时 watcher 不在,
+ /// 搜索/列表只反映到这个时刻(读会话是现场解析,不受影响)
+ pub fn latest_activity(&self) -> Result<Option<i64>> {
+ let conn = self.read.lock().unwrap();
+ let latest: Option<i64> =
+ conn.query_row("SELECT MAX(updated_at) FROM sessions", [], |r| r.get(0))?;
+ Ok(latest.filter(|t| *t > 0))
+ }
+
// ---------- 写路径(扫描器/用户操作) ----------
pub fn write_session(
@@ -892,29 +948,14 @@ impl Store {
let mut wheres: Vec<String> = Vec::new();
let mut args: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
- if !f.agents.is_empty() {
- let ph = f.agents.iter().map(|_| "?").collect::<Vec<_>>().join(",");
- wheres.push(format!("s.agent_id IN ({ph})"));
- for a in &f.agents {
- args.push(Box::new(a.as_str().to_string()));
- }
- }
- if let Some(p) = &f.project_path {
- wheres.push("s.project_path = ?".into());
- args.push(Box::new(p.clone()));
- }
- if f.favorite_only {
- wheres.push("COALESCE(u.favorite, 0) = 1".into());
- }
- if !f.include_archived {
- wheres.push("s.archived = 0".into());
- }
- if let Some(q) = f.title_query.as_deref().filter(|q| !q.trim().is_empty()) {
- wheres.push("(s.title LIKE ? ESCAPE '\\' OR s.project_name LIKE ? ESCAPE '\\')".into());
- let like = format!("%{}%", escape_like(q.trim()));
- args.push(Box::new(like.clone()));
- args.push(Box::new(like));
- }
+ // 根会话的"活动时间"是连子会话一起聚合的(排序、返回值都如此),since
+ // 过滤必须用同一口径——只看父行会把"父旧子新"的整棵树滤掉
+ let updated_col = match (f.roots_only, f.include_archived) {
+ (true, false) => ROOT_UPDATED_ACTIVE,
+ (true, true) => ROOT_UPDATED_ALL,
+ _ => "s.updated_at",
+ };
+ push_session_filters(f, updated_col, &mut wheres, &mut args);
if f.roots_only {
wheres.push(if f.include_archived {
ROOT_IGNORING_ARCHIVED.into()
@@ -937,6 +978,7 @@ impl Store {
(_, SortKey::Messages, _) => "s.message_count",
};
let order_dir = if f.ascending { "ASC" } else { "DESC" };
+ let pin_order = pin_order(f);
let conn = self.read.lock().unwrap();
let total: i64 = conn.query_row(
@@ -959,7 +1001,7 @@ impl Store {
let sql = format!(
"SELECT {selected_cols} FROM sessions s LEFT JOIN user_data u ON u.session_key = s.key
{where_sql}
- ORDER BY COALESCE(u.pinned,0) DESC, {order_col} {order_dir}, s.key ASC LIMIT ? OFFSET ?"
+ ORDER BY {pin_order}{order_col} {order_dir}, s.key ASC LIMIT ? OFFSET ?"
);
let mut stmt = conn.prepare_cached(&sql)?;
let limit = if f.limit > 0 { f.limit } else { 500 };
@@ -1009,12 +1051,13 @@ impl Store {
SortKey::Messages => "s.message_count",
};
let order_dir = if f.ascending { "ASC" } else { "DESC" };
+ let pin_order = pin_order(f);
let conn = self.read.lock().unwrap();
let sql = format!(
"SELECT {SESSION_COLS}
FROM sessions s LEFT JOIN user_data u ON u.session_key = s.key
{where_sql}
- ORDER BY COALESCE(u.pinned,0) DESC, {order_col} {order_dir}, s.key ASC"
+ ORDER BY {pin_order}{order_col} {order_dir}, s.key ASC"
);
let mut stmt = conn.prepare_cached(&sql)?;
let rows = stmt.query_map(
@@ -1066,20 +1109,39 @@ impl Store {
Ok(conn.query_row(&sql, params![key], row_to_meta).optional()?)
}
- pub fn list_projects(&self) -> Result<Vec<ProjectInfo>> {
+ /// 按原生 id 反查(wake-mcp 的 key 兜底:对方常只拿到 resume 用的那个 id)。
+ /// 同 UUID 在多台 host 各续跑过会多于一行,由调用方裁决
+ pub fn find_by_native_id(&self, native_id: &str) -> Result<Vec<SessionMeta>> {
let conn = self.read.lock().unwrap();
- let mut stmt = conn.prepare_cached(
- "SELECT s.project_path, s.project_name, COUNT(*),
- MAX(MAX(s.updated_at, COALESCE((
- SELECT MAX(c.updated_at) FROM sessions c
- WHERE c.parent_key = s.key AND c.archived = 0
- ), 0))) AS activity
+ let sql = format!(
+ "SELECT {SESSION_COLS} FROM sessions s LEFT JOIN user_data u ON u.session_key = s.key
+ WHERE s.native_id = ?1 ORDER BY s.key"
+ );
+ let mut stmt = conn.prepare_cached(&sql)?;
+ let rows = stmt.query_map(params![native_id], row_to_meta)?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// 项目清单(根会话按 project_path 聚合)。GUI 侧栏与 wake_list_projects 传
+ /// false 只算未归档;wake-mcp 解析 `project` 参数时传 true——搜索本身覆盖
+ /// 归档会话,只剩归档会话的项目不能在解析这一步就被挡掉
+ pub fn list_projects(&self, include_archived: bool) -> Result<Vec<ProjectInfo>> {
+ let (root_updated, root_cond, archived) = if include_archived {
+ (ROOT_UPDATED_ALL, ROOT_IGNORING_ARCHIVED, "")
+ } else {
+ (
+ ROOT_UPDATED_ACTIVE,
+ ROOT_WHEN_HIDING_ARCHIVED,
+ "s.archived = 0 AND ",
+ )
+ };
+ let conn = self.read.lock().unwrap();
+ let mut stmt = conn.prepare_cached(&format!(
+ "SELECT s.project_path, s.project_name, COUNT(*), MAX({root_updated}) AS activity
FROM sessions s
- WHERE s.archived = 0 AND (s.parent_key = '' OR NOT EXISTS (
- SELECT 1 FROM sessions p WHERE p.key = s.parent_key AND p.archived = 0
- ))
- GROUP BY s.project_path ORDER BY activity DESC",
- )?;
+ WHERE {archived}{root_cond}
+ GROUP BY s.project_path ORDER BY activity DESC"
+ ))?;
let rows = stmt.query_map([], |r| {
Ok(ProjectInfo {
path: r.get(0)?,
@@ -1169,7 +1231,11 @@ impl Store {
// 临时连接,不与 UI 的 read 连接抢锁:WAL 多读并发,几十毫秒的
// 统计扫描不该让导航点击的列表查询排队(2026-08-27 Codex review)
- let conn = open_conn(&self.path)?;
+ let conn = if self.read_only {
+ open_conn_ro(&self.path)?
+ } else {
+ open_conn(&self.path)?
+ };
let mut data = InsightsData {
as_of: today,
..Default::default()
@@ -1356,24 +1422,52 @@ impl Store {
project_path: Option<&str>,
limit: i64,
) -> Result<(Vec<SearchHit>, bool)> {
+ self.search_with(
+ q,
+ &SearchFilter {
+ agents: agents.to_vec(),
+ project_paths: project_path
+ .map(|p| vec![p.to_string()])
+ .unwrap_or_default(),
+ updated_since: None,
+ limit,
+ },
+ )
+ }
+
+ /// 全文搜索的完整筛选形态(多项目并集 + 时间下界);`search` 是它的便捷壳。
+ /// 命中按 bm25 排序、消息级一行一条;archived 会话不排除(meta.archived 标出)
+ pub fn search_with(&self, q: &str, f: &SearchFilter) -> Result<(Vec<SearchHit>, bool)> {
let segs: Vec<&str> = q.split_whitespace().filter(|s| !s.is_empty()).collect();
if segs.is_empty() {
return Ok((Vec::new(), false));
}
let degraded = segs.iter().any(|s| s.chars().count() < 3);
+ let limit = if f.limit > 0 { f.limit } else { 60 };
let mut filter_sql = String::new();
let mut filter_args: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
- if !agents.is_empty() {
- let ph = agents.iter().map(|_| "?").collect::<Vec<_>>().join(",");
- filter_sql.push_str(&format!(" AND s.agent_id IN ({ph})"));
- for a in agents {
+ if !f.agents.is_empty() {
+ filter_sql.push_str(&format!(
+ " AND s.agent_id IN ({})",
+ placeholders(f.agents.len())
+ ));
+ for a in &f.agents {
filter_args.push(Box::new(a.as_str().to_string()));
}
}
- if let Some(p) = project_path {
- filter_sql.push_str(" AND s.project_path = ?");
- filter_args.push(Box::new(p.to_string()));
+ if !f.project_paths.is_empty() {
+ filter_sql.push_str(&format!(
+ " AND s.project_path IN ({})",
+ placeholders(f.project_paths.len())
+ ));
+ for p in &f.project_paths {
+ filter_args.push(Box::new(p.clone()));
+ }
+ }
+ if let Some(t) = f.updated_since {
+ filter_sql.push_str(" AND s.updated_at >= ?");
+ filter_args.push(Box::new(t));
}
let conn = self.read.lock().unwrap();
@@ -1463,13 +1557,23 @@ impl Store {
}
}
- // 补齐 session meta
+ // 补齐 session meta:按会话只查一次(一个会话常占几十行命中),语句走
+ // prepare_cached——Connection::query_row 每次都是裸 prepare
let mut hits = Vec::new();
+ let mut metas: HashMap<String, Option<SessionMeta>> = HashMap::new();
let sql = format!(
"SELECT {SESSION_COLS} FROM sessions s LEFT JOIN user_data u ON u.session_key = s.key WHERE s.key = ?1"
);
+ let mut stmt = conn.prepare_cached(&sql)?;
for (key, seq, sidechain_id, role, ts, snippet) in raw {
- if let Some(session) = conn.query_row(&sql, params![key], row_to_meta).optional()? {
+ let session = if let Some(cached) = metas.get(&key) {
+ cached.clone()
+ } else {
+ let meta = stmt.query_row(params![key], row_to_meta).optional()?;
+ metas.insert(key.clone(), meta.clone());
+ meta
+ };
+ if let Some(session) = session {
hits.push(SearchHit {
session,
seq,
@@ -1538,40 +1642,71 @@ fn child_filter_sql(
}
None => wheres.push("s.parent_key != ''".to_string()),
}
- if !filter.agents.is_empty() {
- let placeholders = filter
- .agents
- .iter()
- .map(|_| "?")
- .collect::<Vec<_>>()
- .join(",");
- wheres.push(format!("s.agent_id IN ({placeholders})"));
- for agent in &filter.agents {
- args.push(Box::new(agent.as_str().to_string()));
+ push_session_filters(filter, "s.updated_at", &mut wheres, &mut args);
+ (format!("WHERE {}", wheres.join(" AND ")), args)
+}
+
+/// ORDER BY 里置顶优先的那一段;`ignore_pins` 时为空,纯按排序键
+fn pin_order(f: &SessionFilter) -> &'static str {
+ if f.ignore_pins {
+ ""
+ } else {
+ "COALESCE(u.pinned,0) DESC, "
+ }
+}
+
+/// `?,?,?` 占位串
+fn placeholders(n: usize) -> String {
+ vec!["?"; n].join(",")
+}
+
+/// SessionFilter 里作用于会话行本身的谓词(agents / 项目并集 / 时间下界 /
+/// 收藏 / 归档 / 标题词)。list_sessions 与 child_filter_sql 共用这一份,
+/// roots_only 与 parent 谓词由各自追加——新增筛选字段只改这里(再教会
+/// workbench 的两面镜子,见 models.rs SessionFilter 注释)。
+/// `updated_col` 是时间下界作用的表达式:根会话列表传聚合后的活动时间
+fn push_session_filters(
+ f: &SessionFilter,
+ updated_col: &str,
+ wheres: &mut Vec<String>,
+ args: &mut Vec<Box<dyn rusqlite::ToSql>>,
+) {
+ if !f.agents.is_empty() {
+ wheres.push(format!("s.agent_id IN ({})", placeholders(f.agents.len())));
+ for a in &f.agents {
+ args.push(Box::new(a.as_str().to_string()));
}
}
- if let Some(project) = &filter.project_path {
- wheres.push("s.project_path = ?".to_string());
- args.push(Box::new(project.clone()));
+ if !f.project_paths.is_empty() {
+ wheres.push(format!(
+ "s.project_path IN ({})",
+ placeholders(f.project_paths.len())
+ ));
+ for p in &f.project_paths {
+ args.push(Box::new(p.clone()));
+ }
}
- if filter.favorite_only {
- wheres.push("COALESCE(u.favorite, 0) = 1".to_string());
+ if let Some(t) = f.updated_since {
+ wheres.push(format!("{updated_col} >= ?"));
+ args.push(Box::new(t));
}
- if !filter.include_archived {
- wheres.push("s.archived = 0".to_string());
+ if f.favorite_only {
+ wheres.push("COALESCE(u.favorite, 0) = 1".into());
}
- if let Some(query) = filter
+ if !f.include_archived {
+ wheres.push("s.archived = 0".into());
+ }
+ if let Some(q) = f
.title_query
.as_deref()
.map(str::trim)
- .filter(|query| !query.is_empty())
+ .filter(|q| !q.is_empty())
{
wheres.push("(s.title LIKE ? ESCAPE '\\' OR s.project_name LIKE ? ESCAPE '\\')".into());
- let like = format!("%{}%", escape_like(query));
+ let like = format!("%{}%", escape_like(q));
args.push(Box::new(like.clone()));
args.push(Box::new(like));
}
- (format!("WHERE {}", wheres.join(" AND ")), args)
}
fn row_to_meta(r: &rusqlite::Row<'_>) -> rusqlite::Result<SessionMeta> {
diff --git a/crates/wake-core/src/lib.rs b/crates/wake-core/src/lib.rs
index 0b51c76..4c5598e 100644
--- a/crates/wake-core/src/lib.rs
+++ b/crates/wake-core/src/lib.rs
@@ -1,7 +1,9 @@
pub mod adapters;
pub mod db;
+pub mod mcp;
pub mod models;
pub mod remote;
pub mod scanner;
pub mod services;
+pub mod text;
pub mod watcher;
diff --git a/crates/wake-core/src/mcp/mod.rs b/crates/wake-core/src/mcp/mod.rs
new file mode 100644
index 0000000..06d392c
--- /dev/null
+++ b/crates/wake-core/src/mcp/mod.rs
@@ -0,0 +1,316 @@
+//! wake-mcp:把 Wake 的索引以 MCP(stdio 传输、JSON-RPC 2.0)**只读**暴露给别的
+//! coding agent(Claude Code / Codex / Cursor …)。目标是"换一个 agent 不用重新
+//! 解释自己做到哪了":对方按项目列最近会话、全文搜、读一段转录,全部来自本机
+//! 索引与磁盘上的会话文件,零 LLM、零网络、不写库。
+//!
+//! 协议层手写而不引 rmcp:wake-core 全同步、没有 tokio,server 端真正要实现的
+//! 只有 initialize / notifications/initialized / ping / tools/list / tools/call
+//! 五个方法。消息按行分隔(stdio 传输规范:一行一条 JSON,不含裸换行),
+//! stdout 只写协议,日志一律 stderr。需要 resources / prompts / sampling
+//! 全家桶时再考虑换库。
+//!
+//! 索引库经 `Store::open_read_only` 打开——旁路进程绝不 `open_or_rebuild`,
+//! 也不扫描;新鲜度靠 GUI 常驻的 watcher,每个工具返回都带"索引覆盖到的最新
+//! 活动时间"。读会话是现场解析磁盘文件,不受索引新旧影响。
+
+pub mod tools;
+
+use std::io::{BufRead, Write};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, OnceLock};
+
+use serde_json::{json, Value};
+
+use crate::adapters::AgentAdapter;
+use crate::db::Store;
+use crate::models::AgentId;
+
+/// 本方声明的协议版本(客户端请求的版本在 SUPPORTED 内就回显它,否则回这个)
+pub const PROTOCOL_VERSION: &str = "2025-06-18";
+/// 已知且工具子集完全兼容的版本
+const SUPPORTED: [&str; 4] = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
+pub const SERVER_NAME: &str = "wake";
+pub const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
+
+/// 随 initialize 下发给客户端的使用说明(LLM 会读)
+const INSTRUCTIONS: &str = "Wake indexes the coding-agent sessions on this machine \
+(Claude Code, Codex, Cursor, Gemini CLI, OpenCode and more) and exposes them read-only. \
+Use wake_list_projects or wake_list_sessions to orient (pass your working directory as \
+`project` to scope to the current repo), wake_search for full-text search across every \
+agent's transcripts (CJK text and code substrings both work), and wake_get_session to read \
+a transcript page by page. Nothing here can modify sessions.";
+
+const JSONRPC_PARSE_ERROR: i64 = -32700;
+const JSONRPC_INVALID_REQUEST: i64 = -32600;
+const JSONRPC_METHOD_NOT_FOUND: i64 = -32601;
+const JSONRPC_INVALID_PARAMS: i64 = -32602;
+const JSONRPC_INTERNAL_ERROR: i64 = -32603;
+
+/// 一个 MCP server 实例:持有只读 Store 与按库配置构造的 roster
+pub struct McpServer {
+ store: Arc<Store>,
+ adapters: Vec<Box<dyn AgentAdapter>>,
+ transcripts: tools::TranscriptCache,
+}
+
+impl McpServer {
+ pub fn new(store: Arc<Store>, adapters: Vec<Box<dyn AgentAdapter>>) -> Self {
+ Self {
+ store,
+ adapters,
+ transcripts: tools::TranscriptCache::default(),
+ }
+ }
+
+ /// 阻塞服务到 stdin EOF。每行一条消息;写失败(客户端已退出)即返回
+ pub fn serve(&self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
+ for line in input.lines() {
+ let line = line?;
+ if line.trim().is_empty() {
+ continue;
+ }
+ if let Some(reply) = self.handle_line(&line) {
+ output.write_all(reply.as_bytes())?;
+ output.write_all(b"\n")?;
+ output.flush()?;
+ }
+ }
+ Ok(())
+ }
+
+ /// 一行进、至多一行出(通知无回包)。批量数组逐条处理、按数组回;
+ /// 测试与 `wake-mcp call` 直接用它,不经 stdio
+ pub fn handle_line(&self, line: &str) -> Option<String> {
+ let msg: Value = match serde_json::from_str(line) {
+ Ok(v) => v,
+ Err(e) => {
+ return Some(
+ error_response(
+ Value::Null,
+ JSONRPC_PARSE_ERROR,
+ &format!("Parse error: {e}"),
+ )
+ .to_string(),
+ )
+ }
+ };
+ match msg {
+ Value::Array(items) => {
+ if items.is_empty() {
+ return Some(
+ error_response(Value::Null, JSONRPC_INVALID_REQUEST, "Invalid Request")
+ .to_string(),
+ );
+ }
+ let replies: Vec<Value> = items
+ .iter()
+ .filter_map(|m| self.handle_message(m))
+ .collect();
+ (!replies.is_empty()).then(|| Value::Array(replies).to_string())
+ }
+ other => self.handle_message(&other).map(|v| v.to_string()),
+ }
+ }
+
+ fn handle_message(&self, msg: &Value) -> Option<Value> {
+ let obj = match msg.as_object() {
+ Some(o) => o,
+ None => {
+ return Some(error_response(
+ Value::Null,
+ JSONRPC_INVALID_REQUEST,
+ "Invalid Request",
+ ))
+ }
+ };
+ let id = obj.get("id").cloned();
+ let method = match obj.get("method").and_then(Value::as_str) {
+ Some(m) => m,
+ // 没有 method 的是"响应":本 server 从不向客户端发请求,静默丢弃
+ None => {
+ return id.filter(|id| !id.is_null()).and_then(|id| {
+ (!obj.contains_key("result") && !obj.contains_key("error"))
+ .then(|| error_response(id, JSONRPC_INVALID_REQUEST, "Invalid Request"))
+ })
+ }
+ };
+ let params = obj.get("params").cloned().unwrap_or(Value::Null);
+ // 通知(无 id)不回包,不管认不认识
+ let id = match id {
+ Some(id) if !id.is_null() => id,
+ _ => {
+ if method == "notifications/initialized" {
+ eprintln!("wake-mcp: client initialized");
+ }
+ return None;
+ }
+ };
+ let result = match method {
+ "initialize" => Ok(self.initialize(&params)),
+ "ping" => Ok(json!({})),
+ "tools/list" => Ok(json!({ "tools": tools::definitions() })),
+ "tools/call" => self.call_tool(&params),
+ _ => Err((
+ JSONRPC_METHOD_NOT_FOUND,
+ format!("Method not found: {method}"),
+ )),
+ };
+ Some(match result {
+ Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
+ Err((code, message)) => error_response(id, code, &message),
+ })
+ }
+
+ fn initialize(&self, params: &Value) -> Value {
+ let requested = params
+ .get("protocolVersion")
+ .and_then(Value::as_str)
+ .unwrap_or("");
+ let version = if SUPPORTED.contains(&requested) {
+ requested
+ } else {
+ PROTOCOL_VERSION
+ };
+ json!({
+ "protocolVersion": version,
+ "capabilities": { "tools": { "listChanged": false } },
+ "serverInfo": { "name": SERVER_NAME, "title": "Wake", "version": SERVER_VERSION },
+ "instructions": INSTRUCTIONS,
+ })
+ }
+
+ fn call_tool(&self, params: &Value) -> Result<Value, (i64, String)> {
+ let name = params.get("name").and_then(Value::as_str).ok_or((
+ JSONRPC_INVALID_PARAMS,
+ "tools/call needs a string `name`".to_string(),
+ ))?;
+ let empty = json!({});
+ let args = params.get("arguments").unwrap_or(&empty);
+ if !args.is_object() && !args.is_null() {
+ return Err((
+ JSONRPC_INVALID_PARAMS,
+ "`arguments` must be an object".to_string(),
+ ));
+ }
+ let ctx = tools::ToolContext {
+ store: &self.store,
+ adapters: &self.adapters,
+ now_ms: crate::db::now_ms(),
+ cache: &self.transcripts,
+ };
+ match tools::call(&ctx, name, args) {
+ Ok(text) => Ok(tool_result(text, false)),
+ // 参数形状错(含未知工具名)是协议错误;执行失败(坏 key、解析失败)
+ // 是给 LLM 看的结果
+ Err(tools::ToolError::InvalidParams(m)) => Err((JSONRPC_INVALID_PARAMS, m)),
+ Err(tools::ToolError::Failed(m)) => Ok(tool_result(m, true)),
+ Err(tools::ToolError::Internal(m)) => Err((JSONRPC_INTERNAL_ERROR, m)),
+ }
+ }
+}
+
+fn tool_result(text: String, is_error: bool) -> Value {
+ json!({
+ "content": [{ "type": "text", "text": text }],
+ "isError": is_error,
+ })
+}
+
+fn error_response(id: Value, code: i64, message: &str) -> Value {
+ json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
+}
+
+// ---------------------------------------------------------------- 安装辅助
+
+/// 与本进程同目录的 wake-mcp 可执行文件(GUI 的 Settings → Connect 展示用;
+/// 打包时 bin 与 Wake 主程序并排:macOS 在 Contents/MacOS,Linux/Windows 同目录)。
+/// current_exe 进程内不变,算一次缓存住——调用方可能在 render 里问
+pub fn sibling_binary() -> Option<PathBuf> {
+ static BIN: OnceLock<Option<PathBuf>> = OnceLock::new();
+ BIN.get_or_init(|| {
+ let exe = std::env::current_exe().ok()?;
+ let name = if cfg!(target_os = "windows") {
+ "wake-mcp.exe"
+ } else {
+ "wake-mcp"
+ };
+ Some(exe.parent()?.join(name))
+ })
+ .clone()
+}
+
+/// 一段可复制的接入配置
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SetupSnippet {
+ /// 客户端名("Claude Code")
+ pub client: &'static str,
+ /// 对应的 agent(UI 取品牌图标用)
+ pub agent: AgentId,
+ /// 怎么用这段("Run in a terminal" / "Add to ~/.codex/config.toml")
+ pub hint: &'static str,
+ /// 复制按钮文案("Copy command" / "Copy config")——UI 只给按钮不展示片段
+ pub copy_label: &'static str,
+ pub text: String,
+}
+
+/// 三家客户端的接入片段(UI 的 Connect 页与 `wake-mcp setup` 同源)。路径一律
+/// 按 JSON 字符串转义——TOML basic string 与 JSON 的转义子集兼容,Windows 的
+/// 反斜杠与含空格路径都安全
+pub fn setup_snippets(bin: &Path) -> Vec<SetupSnippet> {
+ let quoted = serde_json::to_string(&bin.to_string_lossy()).unwrap_or_default();
+ vec![
+ SetupSnippet {
+ client: "Claude Code",
+ agent: AgentId::ClaudeCode,
+ hint: "Run in a terminal",
+ copy_label: "Copy command",
+ text: format!("claude mcp add --scope user wake -- {quoted}"),
+ },
+ SetupSnippet {
+ client: "Codex",
+ agent: AgentId::Codex,
+ hint: "Add to ~/.codex/config.toml",
+ copy_label: "Copy config",
+ text: format!("[mcp_servers.wake]\ncommand = {quoted}"),
+ },
+ SetupSnippet {
+ client: "Cursor",
+ agent: AgentId::Cursor,
+ hint: "Merge into ~/.cursor/mcp.json",
+ copy_label: "Copy config",
+ text: format!(
+ "{{\n \"mcpServers\": {{\n \"wake\": {{ \"command\": {quoted} }}\n }}\n}}"
+ ),
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn snippets_quote_paths_for_every_client() {
+ let snippets = setup_snippets(Path::new(
+ "/Applications/My Apps/Wake.app/Contents/MacOS/wake-mcp",
+ ));
+ assert_eq!(snippets.len(), 3);
+ assert_eq!(
+ snippets[0].text,
+ "claude mcp add --scope user wake -- \"/Applications/My Apps/Wake.app/Contents/MacOS/wake-mcp\""
+ );
+ assert!(snippets[1]
+ .text
+ .starts_with("[mcp_servers.wake]\ncommand = \"/Applications/My Apps/"));
+ let cursor: Value =
+ serde_json::from_str(&snippets[2].text).expect("cursor snippet is valid JSON");
+ assert_eq!(
+ cursor["mcpServers"]["wake"]["command"],
+ "/Applications/My Apps/Wake.app/Contents/MacOS/wake-mcp"
+ );
+ let win = setup_snippets(Path::new(r"C:\Program Files\Wake\wake-mcp.exe"));
+ assert!(win[1]
+ .text
+ .contains(r#"command = "C:\\Program Files\\Wake\\wake-mcp.exe""#));
+ }
+}
diff --git a/crates/wake-core/src/mcp/tools.rs b/crates/wake-core/src/mcp/tools.rs
new file mode 100644
index 0000000..56dcdb5
--- /dev/null
+++ b/crates/wake-core/src/mcp/tools.rs
@@ -0,0 +1,879 @@
+//! wake-mcp 的四个只读工具:定义(JSON Schema)与执行。输出全是 Markdown 文本,
+//! 给 LLM 直接读;结构化输出(structuredContent)不做。
+//!
+//! 错误分两类:参数形状不对是协议错误(`InvalidParams` → JSON-RPC -32602);
+//! 执行失败(坏 key、文件解析失败)是给 LLM 看的结果(`Failed` → isError)。
+//! "没匹配上项目""没有结果"都不是错误,照常返回带提示的文本。
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use serde_json::{json, Value};
+
+use crate::adapters::{adapter_for, AgentAdapter};
+use crate::db::Store;
+use crate::models::*;
+use crate::services::context::{parse_since, resolve_project_paths};
+use crate::services::exporter::{fmt_time, render_compact, CompactOptions};
+use crate::text::{one_line, plural};
+
+pub struct ToolContext<'a> {
+ pub store: &'a Store,
+ pub adapters: &'a [Box<dyn AgentAdapter>],
+ pub now_ms: i64,
+ pub cache: &'a TranscriptCache,
+}
+
+/// 单槽转录缓存:分页读同一会话时不必每页整文件重解析(默认 20k 字符一页,
+/// 大会话几十页)。键是 scanner 同款的脏判据 (file_path, mtime, size),文件一
+/// 变即失效;server 进程随客户端会话长驻,连续翻页总是同一文件
+#[derive(Default)]
+pub struct TranscriptCache(Mutex<Option<(String, i64, i64, Arc<ParsedTranscript>)>>);
+
+impl TranscriptCache {
+ fn get_or_parse(
+ &self,
+ adapter: &dyn AgentAdapter,
+ meta: &SessionMeta,
+ ) -> anyhow::Result<Arc<ParsedTranscript>> {
+ let r = SessionFileRef::from_meta(meta);
+ // SQLite 型会话的 `<db>#<id>` 虚拟路径 stat 不到,from_meta 退回索引里的
+ // 时间——源库变了、Wake 没重扫时键不会变。改用库文件与 -wal 的 mtime
+ // 作戳(sqlite_ro 行缓存同款判据),源库一写就失效
+ let stamp = if std::path::Path::new(&r.file_path).exists() {
+ r.mtime_ms
+ } else {
+ 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());
+ }
+ }
+ let t = Arc::new(adapter.parse_transcript(&r)?);
+ *self.0.lock().unwrap() = Some((r.file_path.clone(), stamp, r.size, t.clone()));
+ Ok(t)
+ }
+}
+
+#[derive(Debug)]
+pub enum ToolError {
+ InvalidParams(String),
+ Failed(String),
+ Internal(String),
+}
+
+impl From<anyhow::Error> for ToolError {
+ fn from(e: anyhow::Error) -> Self {
+ ToolError::Internal(format!("{e:#}"))
+ }
+}
+
+type ToolResult = Result<String, ToolError>;
+
+pub const SEARCH: &str = "wake_search";
+pub const LIST_SESSIONS: &str = "wake_list_sessions";
+pub const GET_SESSION: &str = "wake_get_session";
+pub const LIST_PROJECTS: &str = "wake_list_projects";
+
+const MAX_SEARCH_SESSIONS: i64 = 30;
+const MAX_LIST_SESSIONS: i64 = 100;
+const MAX_LIST_PROJECTS: i64 = 200;
+const SNIPPETS_PER_SESSION: usize = 3;
+
+fn read_only_annotations() -> Value {
+ json!({
+ "readOnlyHint": true,
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": false,
+ })
+}
+
+fn project_param() -> Value {
+ json!({
+ "type": "string",
+ "description": "Scope to one project. Pass an absolute path — your current working directory is ideal: Wake matches the enclosing indexed project, or every project below a parent directory — or a project name. Omit to cover all projects.",
+ })
+}
+
+fn agents_param() -> Value {
+ json!({
+ "type": "array",
+ "items": { "type": "string", "enum": AgentId::ALL.iter().map(|a| a.as_str()).collect::<Vec<_>>() },
+ "description": "Only sessions from these agents (ids as listed). Omit for all agents.",
+ })
+}
+
+fn since_param() -> Value {
+ json!({
+ "type": "string",
+ "description": "Only sessions updated at or after this time: relative (30m, 24h, 7d, 2w) or an ISO date/time (2026-09-01, 2026-09-01T09:30:00Z).",
+ })
+}
+
+/// tools/list 的内容。名字、参数名是对外契约,改了别人的配置就失效
+pub fn definitions() -> Vec<Value> {
+ vec![
+ json!({
+ "name": SEARCH,
+ "title": "Search session history",
+ "description": "Full-text search across every indexed coding-agent session on this machine (user prompts, assistant replies, tool names and inputs). Terms are ANDed; CJK text and code substrings like `useEffect(` work. Returns matching sessions with up to three snippets each, plus a `wake://session/<key>#<seq>` reference per snippet that you can read with wake_get_session.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "query": { "type": "string", "description": "Search terms. Terms shorter than 3 characters fall back to a slower substring scan." },
+ "project": project_param(),
+ "agents": agents_param(),
+ "since": since_param(),
+ "limit": { "type": "integer", "minimum": 1, "maximum": MAX_SEARCH_SESSIONS, "default": 10, "description": "Maximum sessions to return." },
+ },
+ "required": ["query"],
+ },
+ "annotations": read_only_annotations(),
+ }),
+ json!({
+ "name": LIST_SESSIONS,
+ "title": "List recent sessions",
+ "description": "Most recently updated sessions, optionally scoped to a project, to some agents, to a time window, or to starred sessions. Use it to see what was worked on recently (\"what did I do in this repo yesterday?\") and to get session keys for wake_get_session. Subagent sessions are folded into their parents; archived sessions are excluded.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "project": project_param(),
+ "agents": agents_param(),
+ "since": since_param(),
+ "starred": { "type": "boolean", "default": false, "description": "Only sessions the user starred in Wake." },
+ "limit": { "type": "integer", "minimum": 1, "maximum": MAX_LIST_SESSIONS, "default": 20 },
+ },
+ },
+ "annotations": read_only_annotations(),
+ }),
+ json!({
+ "name": GET_SESSION,
+ "title": "Read a session transcript",
+ "description": "Read one session's transcript, parsed live from the agent's own files, as compact Markdown: user and assistant messages with `[seq N]` markers, tool calls folded to one line each, injected context omitted. Paginated — when the reply ends with a `from_seq` hint, call again with it to continue. Accepts a session key (from wake_search / wake_list_sessions) or a `wake://session/<key>#<seq>` reference (the seq becomes the starting point).",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "key": { "type": "string", "description": "Session key such as `claude-code:1b2c…`, or a wake://session/… reference." },
+ "from_seq": { "type": "integer", "minimum": 0, "description": "Start at this message seq (inclusive). Default: the beginning." },
+ "max_messages": { "type": "integer", "minimum": 1, "maximum": 200, "default": 60, "description": "Messages per page." },
+ "max_chars": { "type": "integer", "minimum": 200, "maximum": 100000, "default": 20000, "description": "Character budget per page." },
+ "max_message_chars": { "type": "integer", "minimum": 100, "maximum": 50000, "default": 4000, "description": "Longer messages are truncated to this many characters." },
+ "include_tools": { "type": "boolean", "default": false, "description": "Include tool-call inputs and outputs (verbose)." },
+ "include_thinking": { "type": "boolean", "default": false, "description": "Include the assistant's thinking/reasoning text where the agent recorded it." },
+ },
+ "required": ["key"],
+ },
+ "annotations": read_only_annotations(),
+ }),
+ json!({
+ "name": LIST_PROJECTS,
+ "title": "List indexed projects",
+ "description": "Projects (working directories) that have indexed sessions, most recently active first, with session counts. Useful to find the right `project` value or to see what the user has been working on.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "since": since_param(),
+ "limit": { "type": "integer", "minimum": 1, "maximum": MAX_LIST_PROJECTS, "default": 50 },
+ },
+ },
+ "annotations": read_only_annotations(),
+ }),
+ ]
+}
+
+pub fn call(ctx: &ToolContext, name: &str, args: &Value) -> ToolResult {
+ match name {
+ SEARCH => search(ctx, args),
+ LIST_SESSIONS => list_sessions(ctx, args),
+ GET_SESSION => get_session(ctx, args),
+ LIST_PROJECTS => list_projects(ctx, args),
+ other => Err(ToolError::InvalidParams(format!("Unknown tool: {other}"))),
+ }
+}
+
+// ---------------------------------------------------------------- 参数读取
+
+fn str_arg<'a>(args: &'a Value, name: &str) -> Result<Option<&'a str>, ToolError> {
+ match args.get(name) {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::String(s)) => Ok(Some(s.as_str())),
+ Some(_) => Err(ToolError::InvalidParams(format!(
+ "`{name}` must be a string"
+ ))),
+ }
+}
+
+fn int_arg(args: &Value, name: &str, default: i64, min: i64, max: i64) -> Result<i64, ToolError> {
+ let v = match args.get(name) {
+ None | Some(Value::Null) => return Ok(default),
+ Some(Value::Number(n)) => n
+ .as_i64()
+ .or_else(|| n.as_f64().filter(|f| f.fract() == 0.0).map(|f| f as i64))
+ .ok_or_else(|| ToolError::InvalidParams(format!("`{name}` must be an integer")))?,
+ // 有的客户端把数字当字符串传
+ Some(Value::String(s)) => s
+ .trim()
+ .parse::<i64>()
+ .map_err(|_| ToolError::InvalidParams(format!("`{name}` must be an integer")))?,
+ Some(_) => {
+ return Err(ToolError::InvalidParams(format!(
+ "`{name}` must be an integer"
+ )))
+ }
+ };
+ Ok(v.clamp(min, max))
+}
+
+fn bool_arg(args: &Value, name: &str, default: bool) -> Result<bool, ToolError> {
+ match args.get(name) {
+ None | Some(Value::Null) => Ok(default),
+ Some(Value::Bool(b)) => Ok(*b),
+ Some(Value::String(s)) if s == "true" || s == "false" => Ok(s == "true"),
+ Some(_) => Err(ToolError::InvalidParams(format!(
+ "`{name}` must be a boolean"
+ ))),
+ }
+}
+
+fn agents_arg(args: &Value) -> Result<Vec<AgentId>, ToolError> {
+ let raw: Vec<String> = match args.get("agents") {
+ None | Some(Value::Null) => return Ok(Vec::new()),
+ Some(Value::String(s)) => s.split(',').map(|s| s.to_string()).collect(),
+ Some(Value::Array(items)) => items
+ .iter()
+ .map(|v| {
+ v.as_str().map(str::to_string).ok_or_else(|| {
+ ToolError::InvalidParams("`agents` must be an array of agent ids".into())
+ })
+ })
+ .collect::<Result<_, _>>()?,
+ Some(_) => {
+ return Err(ToolError::InvalidParams(
+ "`agents` must be an array of agent ids".into(),
+ ))
+ }
+ };
+ let mut out = Vec::new();
+ for s in raw {
+ let s = s.trim();
+ if s.is_empty() {
+ continue;
+ }
+ let agent = parse_agent(s).ok_or_else(|| {
+ ToolError::InvalidParams(format!(
+ "unknown agent `{s}`; valid ids: {}",
+ AgentId::ALL
+ .iter()
+ .map(|a| a.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ ))
+ })?;
+ if !out.contains(&agent) {
+ out.push(agent);
+ }
+ }
+ Ok(out)
+}
+
+/// agent 名宽松解析:正式 id 优先,其次展示名(大小写/空格/连字符不敏感),
+/// 再加几个常见简称
+fn parse_agent(s: &str) -> Option<AgentId> {
+ if let Some(a) = AgentId::from_str(s) {
+ return Some(a);
+ }
+ let norm: String = s
+ .to_lowercase()
+ .chars()
+ .filter(|c| c.is_alphanumeric())
+ .collect();
+ AgentId::ALL
+ .iter()
+ .copied()
+ .find(|a| {
+ let id: String = a.as_str().chars().filter(|c| c.is_alphanumeric()).collect();
+ let name: String = a
+ .display_name()
+ .to_lowercase()
+ .chars()
+ .filter(|c| c.is_alphanumeric())
+ .collect();
+ id == norm || name == norm
+ })
+ .or(match norm.as_str() {
+ "claude" => Some(AgentId::ClaudeCode),
+ "deepseek" => Some(AgentId::Dsh),
+ "opencode2" | "opencodenext" => Some(AgentId::Opencode),
+ _ => None,
+ })
+}
+
+fn since_arg(ctx: &ToolContext, args: &Value) -> Result<Option<i64>, ToolError> {
+ match str_arg(args, "since")? {
+ None => Ok(None),
+ Some(s) if s.trim().is_empty() => Ok(None),
+ Some(s) => parse_since(s, ctx.now_ms).map(Some).ok_or_else(|| {
+ ToolError::InvalidParams(format!(
+ "`since` not understood: `{s}` (use 30m / 24h / 7d / 2w or an ISO date/time)"
+ ))
+ }),
+ }
+}
+
+/// `project` 参数的三种结局。`NoMatch` 带的是给 LLM 的完整回复(含已知项目
+/// 清单)——没匹配上不是错误,照常返回文本
+enum ProjectScope {
+ All,
+ Paths(Vec<String>),
+ NoMatch(String),
+}
+
+fn project_arg(ctx: &ToolContext, args: &Value) -> Result<ProjectScope, ToolError> {
+ let Some(arg) = str_arg(args, "project")?
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ else {
+ return Ok(ProjectScope::All);
+ };
+ // 含归档:搜索覆盖归档会话,只剩归档会话的项目不能在这一步被挡掉
+ let projects = ctx.store.list_projects(true)?;
+ let paths = resolve_project_paths(arg, &projects);
+ if !paths.is_empty() {
+ return Ok(ProjectScope::Paths(paths));
+ }
+ let mut text = format!("No indexed project matches `{arg}`.\n\n");
+ if projects.is_empty() {
+ text.push_str("The index has no projects yet.");
+ } else {
+ text.push_str("Known projects (most recently active first):\n");
+ for p in projects.iter().filter(|p| !p.path.is_empty()).take(15) {
+ text.push_str(&format!(
+ "- {} — {} · {} session{}\n",
+ p.path,
+ p.name,
+ p.session_count,
+ plural(p.session_count)
+ ));
+ }
+ text.push_str("\nPass one of these paths (or the project name), or omit `project` to cover everything.");
+ }
+ Ok(ProjectScope::NoMatch(text))
+}
+
+/// 两个列表工具共用的 project 解包:没匹配上时直接把提示文本当结果返回
+macro_rules! project_scope {
+ ($ctx:expr, $args:expr) => {
+ match project_arg($ctx, $args)? {
+ ProjectScope::All => None,
+ ProjectScope::Paths(p) => Some(p),
+ ProjectScope::NoMatch(text) => return Ok(text),
+ }
+ };
+}
+
+// ---------------------------------------------------------------- 输出小工具
+
+fn index_note(store: &Store) -> String {
+ match store.latest_activity() {
+ Ok(Some(t)) => format!(
+ "Index covers activity up to {} (local time); Wake keeps it fresh while it is running.",
+ fmt_time(Some(t))
+ ),
+ Ok(None) => "The index is empty — launch Wake to build it.".to_string(),
+ Err(e) => format!("Index freshness unknown: {e:#}"),
+ }
+}
+
+fn scope_note(
+ project: &Option<Vec<String>>,
+ agents: &[AgentId],
+ since: Option<i64>,
+ starred: bool,
+) -> String {
+ let mut parts = Vec::new();
+ if let Some(paths) = project {
+ parts.push(match paths.as_slice() {
+ [one] => format!("project {one}"),
+ many => format!("{} projects", many.len()),
+ });
+ }
+ if !agents.is_empty() {
+ parts.push(format!(
+ "agents {}",
+ agents
+ .iter()
+ .map(|a| a.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ ));
+ }
+ if let Some(t) = since {
+ parts.push(format!("since {}", fmt_time(Some(t))));
+ }
+ if starred {
+ parts.push("starred".to_string());
+ }
+ if parts.is_empty() {
+ String::new()
+ } else {
+ format!(" ({})", parts.join(", "))
+ }
+}
+
+fn session_line(s: &SessionMeta) -> String {
+ let mut tags = Vec::new();
+ if !s.host.is_empty() {
+ tags.push(format!("@{}", s.host));
+ }
+ if let Some(src) = s.source.as_deref().filter(|v| !v.is_empty()) {
+ tags.push(format!("via {src}"));
+ }
+ if s.favorite {
+ tags.push("★ starred".to_string());
+ }
+ if s.archived {
+ tags.push("archived".to_string());
+ }
+ let tags = if tags.is_empty() {
+ String::new()
+ } else {
+ format!(" · {}", tags.join(" · "))
+ };
+ let project = if s.project_path.is_empty() {
+ "(unknown project)".to_string()
+ } else {
+ s.project_path.clone()
+ };
+ let model = s
+ .model
+ .as_deref()
+ .filter(|m| !m.is_empty())
+ .map(|m| format!(" · {m}"))
+ .unwrap_or_default();
+ format!(
+ "`{}` · {} · \"{}\"\n {} · updated {} · {} message{}{}{}\n",
+ s.key,
+ s.agent.display_name(),
+ one_line(&s.title, 120),
+ project,
+ fmt_time(Some(s.updated_at)),
+ s.message_count,
+ plural(s.message_count),
+ model,
+ tags
+ )
+}
+
+fn clean_snippet(s: &str) -> String {
+ let marked = s
+ .replace(HL_OPEN, "**")
+ .replace(HL_CLOSE, "**")
+ .replace("****", "");
+ one_line(&marked, 240)
+}
+
+fn session_ref(key: &str, seq: i64) -> String {
+ format!("wake://session/{key}#{seq}")
+}
+
+// ---------------------------------------------------------------- 工具实现
+
+fn search(ctx: &ToolContext, args: &Value) -> ToolResult {
+ let query = str_arg(args, "query")?
+ .map(str::trim)
+ .filter(|q| !q.is_empty())
+ .ok_or_else(|| ToolError::InvalidParams("`query` is required".into()))?;
+ let agents = agents_arg(args)?;
+ let since = since_arg(ctx, args)?;
+ let limit = int_arg(args, "limit", 10, 1, MAX_SEARCH_SESSIONS)?;
+ let project = project_scope!(ctx, args);
+ // 命中是消息级、按 bm25 排;一个会话能占掉前几十行,多取一些再按会话归组
+ let fetch = (limit * 8).clamp(60, 400);
+ let (hits, degraded) = ctx.store.search_with(
+ query,
+ &SearchFilter {
+ agents: agents.clone(),
+ project_paths: project.clone().unwrap_or_default(),
+ updated_since: since,
+ limit: fetch,
+ },
+ )?;
+ let mut order: Vec<String> = Vec::new();
+ let mut groups: HashMap<String, (SessionMeta, Vec<&SearchHit>)> = HashMap::new();
+ for h in &hits {
+ let entry = groups.entry(h.session.key.clone()).or_insert_with(|| {
+ order.push(h.session.key.clone());
+ (h.session.clone(), Vec::new())
+ });
+ if entry.1.len() < SNIPPETS_PER_SESSION {
+ entry.1.push(h);
+ }
+ }
+ let scope = scope_note(&project, &agents, since, false);
+ let mut out = String::new();
+ if order.is_empty() {
+ out.push_str(&format!("No matches for `{query}`{scope}.\n"));
+ if degraded {
+ out.push_str("Note: terms shorter than 3 characters use a substring scan; try a longer or more specific term.\n");
+ }
+ out.push_str("Try fewer or different terms, drop the project/agent/since filters, or list sessions with wake_list_sessions.\n\n");
+ out.push_str(&index_note(ctx.store));
+ return Ok(out);
+ }
+ let shown = order.len().min(limit as usize);
+ out.push_str(&format!(
+ "{} session{} match `{query}`{scope}{} — showing {shown}, best matches first.\n",
+ order.len(),
+ plural(order.len() as i64),
+ if hits.len() as i64 >= fetch {
+ " (more may exist)"
+ } else {
+ ""
+ }
+ ));
+ if degraded {
+ out.push_str("Note: terms shorter than 3 characters use a slower substring scan.\n");
+ }
+ out.push('\n');
+ for (ix, key) in order.iter().take(shown).enumerate() {
+ let (meta, snippets) = &groups[key];
+ out.push_str(&format!("{}. {}", ix + 1, session_line(meta)));
+ for h in snippets {
+ let when = h
+ .timestamp
+ .filter(|t| *t > 0)
+ .map(|t| format!(", {}", fmt_time(Some(t))))
+ .unwrap_or_default();
+ out.push_str(&format!(
+ " - seq {} ({}{}): {}\n ref: {}\n",
+ h.seq,
+ h.role,
+ when,
+ clean_snippet(&h.snippet),
+ session_ref(&meta.key, h.seq)
+ ));
+ }
+ out.push('\n');
+ }
+ out.push_str(
+ "Read a session with wake_get_session (pass the key, or a ref to start at that message).\n",
+ );
+ out.push_str(&index_note(ctx.store));
+ Ok(out)
+}
+
+fn list_sessions(ctx: &ToolContext, args: &Value) -> ToolResult {
+ let agents = agents_arg(args)?;
+ let since = since_arg(ctx, args)?;
+ let starred = bool_arg(args, "starred", false)?;
+ let limit = int_arg(args, "limit", 20, 1, MAX_LIST_SESSIONS)?;
+ let project = project_scope!(ctx, args);
+ // 字段全列、不带 ..Default:新增筛选字段时这里必须表态(与 workbench
+ // current_filter 同一约定)
+ let (sessions, total) = ctx.store.list_sessions(&SessionFilter {
+ agents: agents.clone(),
+ favorite_only: starred,
+ include_archived: false,
+ roots_only: true,
+ title_query: None,
+ sort: SortKey::Updated,
+ ascending: false,
+ limit,
+ offset: 0,
+ updated_since: since,
+ project_paths: project.clone().unwrap_or_default(),
+ // "最近"就是最近:GUI 的置顶优先在这里会让 limit 先被旧置顶会话占掉
+ ignore_pins: true,
+ })?;
+ let scope = scope_note(&project, &agents, since, starred);
+ let mut out = String::new();
+ if sessions.is_empty() {
+ out.push_str(&format!("No sessions{scope}.\n\n"));
+ out.push_str(&index_note(ctx.store));
+ return Ok(out);
+ }
+ out.push_str(&format!(
+ "{total} session{}{scope} — showing the {} most recently updated.\n\n",
+ plural(total),
+ sessions.len()
+ ));
+ for s in &sessions {
+ out.push_str("- ");
+ out.push_str(&session_line(s));
+ }
+ out.push_str("\nRead one with wake_get_session using its key.\n");
+ out.push_str(&index_note(ctx.store));
+ Ok(out)
+}
+
+fn list_projects(ctx: &ToolContext, args: &Value) -> ToolResult {
+ let since = since_arg(ctx, args)?;
+ let limit = int_arg(args, "limit", 50, 1, MAX_LIST_PROJECTS)? as usize;
+ let projects: Vec<ProjectInfo> = ctx
+ .store
+ .list_projects(false)?
+ .into_iter()
+ .filter(|p| since.is_none_or(|t| p.last_active >= t))
+ .collect();
+ let window = since
+ .map(|t| format!(" active since {}", fmt_time(Some(t))))
+ .unwrap_or_default();
+ let mut out = String::new();
+ if projects.is_empty() {
+ out.push_str(&format!("No projects{window}.\n\n"));
+ out.push_str(&index_note(ctx.store));
+ return Ok(out);
+ }
+ out.push_str(&format!(
+ "{} project{}{window} — most recently active first{}.\n\n",
+ projects.len(),
+ plural(projects.len() as i64),
+ if projects.len() > limit {
+ format!(", showing {limit}")
+ } else {
+ String::new()
+ }
+ ));
+ for p in projects.iter().take(limit) {
+ let path = if p.path.is_empty() {
+ "(unknown project)".to_string()
+ } else {
+ p.path.clone()
+ };
+ out.push_str(&format!(
+ "- {} — {} · {} session{} · last active {}\n",
+ path,
+ if p.name.is_empty() { "?" } else { &p.name },
+ p.session_count,
+ plural(p.session_count),
+ fmt_time(Some(p.last_active))
+ ));
+ }
+ out.push_str("\nUse a path as `project` in wake_list_sessions or wake_search.\n");
+ out.push_str(&index_note(ctx.store));
+ Ok(out)
+}
+
+/// `key` 也接受 `wake://session/<key>#<seq>` 引用(seq 成为默认起点)
+fn parse_key_arg(raw: &str) -> (String, Option<i64>) {
+ let s = raw.trim();
+ let s = s.strip_prefix("wake://session/").unwrap_or(s);
+ match s.rsplit_once('#') {
+ Some((key, seq)) if seq.parse::<i64>().is_ok() => (key.to_string(), seq.parse().ok()),
+ _ => (s.to_string(), None),
+ }
+}
+
+fn find_session(store: &Store, key: &str) -> Result<Result<SessionMeta, String>, ToolError> {
+ if let Some(meta) = store.get_session(key)? {
+ return Ok(Ok(meta));
+ }
+ // 兜底:对方只拿到原生 id(resume 用的那个),按列反查;同 UUID 跨 host 会多于一条
+ let candidates = store.find_by_native_id(key)?;
+ Ok(match candidates.as_slice() {
+ [one] => Ok(one.clone()),
+ [] => Err(format!(
+ "No session with key `{key}`. Keys look like `claude-code:<id>` (or `<agent>:<host>:<id>` for remote hosts); get one from wake_search or wake_list_sessions."
+ )),
+ many => Err(format!(
+ "`{key}` is ambiguous — {} sessions share that id:\n{}",
+ many.len(),
+ many.iter()
+ .map(|s| format!("- `{}` ({}{})", s.key, s.agent.display_name(), if s.host.is_empty() { String::new() } else { format!(" @{}", s.host) }))
+ .collect::<Vec<_>>()
+ .join("\n")
+ )),
+ })
+}
+
+fn get_session(ctx: &ToolContext, args: &Value) -> ToolResult {
+ let raw_key = str_arg(args, "key")?
+ .map(str::trim)
+ .filter(|k| !k.is_empty())
+ .ok_or_else(|| ToolError::InvalidParams("`key` is required".into()))?;
+ let (key, ref_seq) = parse_key_arg(raw_key);
+ let from_seq = int_arg(args, "from_seq", ref_seq.unwrap_or(0), 0, i64::MAX)?;
+ let opts = CompactOptions {
+ from_seq,
+ max_messages: int_arg(args, "max_messages", 60, 1, 200)? as usize,
+ max_chars: int_arg(args, "max_chars", 20_000, 200, 100_000)? as usize,
+ max_message_chars: int_arg(args, "max_message_chars", 4_000, 100, 50_000)? as usize,
+ include_tools: bool_arg(args, "include_tools", false)?,
+ include_thinking: bool_arg(args, "include_thinking", false)?,
+ };
+ let meta = match find_session(ctx.store, &key)? {
+ Ok(m) => m,
+ Err(text) => return Err(ToolError::Failed(text)),
+ };
+ let adapter = adapter_for(ctx.adapters, meta.agent, &meta.file_path).ok_or_else(|| {
+ ToolError::Failed(format!(
+ "No adapter can read `{}` ({}) — its data location may be disabled in Wake's settings.",
+ meta.key,
+ meta.agent.display_name()
+ ))
+ })?;
+ let transcript = ctx.cache.get_or_parse(adapter, &meta).map_err(|e| {
+ ToolError::Failed(format!(
+ "Could not read the transcript of `{}` from {}: {e:#}",
+ meta.key, meta.file_path
+ ))
+ })?;
+ let live = &transcript.meta;
+ let total_visible = transcript
+ .mainline
+ .iter()
+ .filter(|m| m.kind != MessageKind::Meta)
+ .count();
+ let last_seq = transcript.mainline.last().map(|m| m.seq);
+ let page = render_compact(&transcript.mainline, &opts);
+
+ let mut out = String::new();
+ let title = if live.title.is_empty() {
+ UNTITLED
+ } else {
+ &live.title
+ };
+ out.push_str(&format!("# {title}\n"));
+ let mut facts = vec![
+ format!("key: `{}`", meta.key),
+ format!("agent: {}", meta.agent.display_name()),
+ ];
+ if !meta.host.is_empty() {
+ facts.push(format!("host: @{}", meta.host));
+ }
+ if !live.project_path.is_empty() {
+ facts.push(format!(
+ "project: {}{}",
+ live.project_path,
+ live.git_branch
+ .as_deref()
+ .filter(|b| !b.is_empty())
+ .map(|b| format!(" ({b})"))
+ .unwrap_or_default()
+ ));
+ }
+ if let Some(m) = live.model.as_deref().filter(|m| !m.is_empty()) {
+ facts.push(format!("model: {m}"));
+ }
+ if let Some(src) = meta.source.as_deref().filter(|v| !v.is_empty()) {
+ facts.push(format!("via {src}"));
+ }
+ facts.push(format!(
+ "{} – {}",
+ fmt_time(Some(live.created_at)),
+ fmt_time(Some(live.updated_at))
+ ));
+ facts.push(format!(
+ "{total_visible} message{}",
+ plural(total_visible as i64)
+ ));
+ out.push_str(&facts.join(" · "));
+ out.push_str("\n\n");
+
+ if page.rendered == 0 {
+ out.push_str(&match last_seq {
+ Some(last) => format!(
+ "No messages at or after seq {from_seq} (the transcript ends at seq {last}).\n"
+ ),
+ None => "This transcript has no messages.\n".to_string(),
+ });
+ return Ok(out);
+ }
+ out.push_str(&page.text);
+ out.push_str("—\n");
+ let (first, last) = page.seq_range.unwrap_or((from_seq, from_seq));
+ let mut summary = format!(
+ "Showing seq {first}–{last}: {} message{}",
+ page.rendered,
+ plural(page.rendered as i64)
+ );
+ if page.skipped_meta > 0 {
+ summary.push_str(&format!(
+ "; {} injected-context message{} omitted",
+ page.skipped_meta,
+ plural(page.skipped_meta as i64)
+ ));
+ }
+ if !transcript.sidechains.is_empty() {
+ summary.push_str(&format!(
+ "; {} subagent transcript{} not included",
+ transcript.sidechains.len(),
+ plural(transcript.sidechains.len() as i64)
+ ));
+ }
+ out.push_str(&summary);
+ out.push_str(".\n");
+ match page.next_seq {
+ Some(next) => out.push_str(&format!(
+ "More follows — call {GET_SESSION} again with from_seq={next}.\n"
+ )),
+ None => out.push_str("End of transcript.\n"),
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn agent_names_parse_leniently() {
+ assert_eq!(parse_agent("claude-code"), Some(AgentId::ClaudeCode));
+ assert_eq!(parse_agent("Claude Code"), Some(AgentId::ClaudeCode));
+ assert_eq!(parse_agent("claude"), Some(AgentId::ClaudeCode));
+ assert_eq!(parse_agent("Gemini CLI"), Some(AgentId::Gemini));
+ assert_eq!(parse_agent("oh-my-pi"), Some(AgentId::Omp));
+ assert_eq!(parse_agent("DeepSeek"), Some(AgentId::Dsh));
+ assert_eq!(parse_agent("opencode2"), Some(AgentId::Opencode));
+ assert_eq!(parse_agent("chatgpt"), None);
+ }
+
+ #[test]
+ fn key_arg_accepts_wake_refs() {
+ assert_eq!(
+ parse_key_arg("wake://session/claude-code:abc#12"),
+ ("claude-code:abc".to_string(), Some(12))
+ );
+ assert_eq!(
+ parse_key_arg("codex:devbox:0195-xyz"),
+ ("codex:devbox:0195-xyz".to_string(), None)
+ );
+ assert_eq!(
+ parse_key_arg(" claude-code:abc "),
+ ("claude-code:abc".to_string(), None)
+ );
+ }
+
+ #[test]
+ fn int_args_clamp_and_accept_numeric_strings() {
+ let args = json!({ "limit": 500, "n": "7", "f": 3.0, "bad": "x" });
+ assert_eq!(int_arg(&args, "limit", 10, 1, 30).unwrap(), 30);
+ assert_eq!(int_arg(&args, "n", 10, 1, 30).unwrap(), 7);
+ assert_eq!(int_arg(&args, "f", 10, 1, 30).unwrap(), 3);
+ assert_eq!(int_arg(&args, "missing", 10, 1, 30).unwrap(), 10);
+ assert!(matches!(
+ int_arg(&args, "bad", 10, 1, 30),
+ Err(ToolError::InvalidParams(_))
+ ));
+ }
+
+ #[test]
+ fn snippets_drop_highlight_sentinels() {
+ let raw = format!("前文 {HL_OPEN}二维码{HL_CLOSE} 后文\n换行");
+ assert_eq!(clean_snippet(&raw), "前文 **二维码** 后文 换行");
+ }
+
+ #[test]
+ fn definitions_are_stable() {
+ let defs = definitions();
+ let names: Vec<&str> = defs.iter().map(|d| d["name"].as_str().unwrap()).collect();
+ assert_eq!(names, [SEARCH, LIST_SESSIONS, GET_SESSION, LIST_PROJECTS]);
+ for d in &defs {
+ assert_eq!(d["inputSchema"]["type"], "object");
+ assert_eq!(d["annotations"]["readOnlyHint"], true);
+ }
+ }
+}
diff --git a/crates/wake-core/src/models.rs b/crates/wake-core/src/models.rs
index ee88ae4..a016228 100644
--- a/crates/wake-core/src/models.rs
+++ b/crates/wake-core/src/models.rs
@@ -251,6 +251,15 @@ pub enum Role {
}
impl Role {
+ /// 人读标题(导出与 wake-mcp 的消息头共用;`as_str` 是落库/传输用的小写)
+ pub fn title(&self) -> &'static str {
+ match self {
+ Role::User => "User",
+ Role::Assistant => "Assistant",
+ Role::System => "System",
+ }
+ }
+
pub fn as_str(&self) -> &'static str {
match self {
Role::User => "user",
@@ -355,7 +364,6 @@ pub struct ParsedSession {
#[derive(Debug, Clone, Default)]
pub struct SessionFilter {
pub agents: Vec<AgentId>,
- pub project_path: Option<String>,
pub favorite_only: bool,
pub include_archived: bool,
/// 只返回会话树的可见根节点。父节点不存在或被当前归档口径隐藏时,
@@ -367,6 +375,16 @@ pub struct SessionFilter {
pub ascending: bool,
pub limit: i64,
pub offset: i64,
+ /// 只要 updated_at ≥ 此刻(epoch ms)的会话;None = 不限(wake-mcp 的 since)
+ pub updated_since: Option<i64>,
+ /// 项目路径并集;空 = 不限。UI 的单选项目给一个元素,wake-mcp 的 monorepo
+ /// 匹配给多个——只此一个字段,别再加"单个项目"的孪生。
+ /// 新增筛选字段要同时教会 db.rs `push_session_filters` 与 workbench 的两面
+ /// 镜子(`same_session_query` / `session_matches_filter`)
+ pub project_paths: Vec<String>,
+ /// true = 排序不把置顶提前(wake-mcp 的"最近会话"要的是真按时间;GUI 列表
+ /// 保持置顶优先,默认 false)
+ pub ignore_pins: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -395,6 +413,19 @@ pub struct SearchHit {
pub timestamp: Option<i64>,
}
+/// 全文搜索的筛选面(`Store::search_with`)。`Store::search(q, agents, project,
+/// limit)` 是它的便捷形态,UI 用;wake-mcp 需要多项目并集与时间下界
+#[derive(Debug, Clone, Default)]
+pub struct SearchFilter {
+ pub agents: Vec<AgentId>,
+ /// 项目路径并集;空 = 不限
+ pub project_paths: Vec<String>,
+ /// 只要 updated_at ≥ 此刻(epoch ms)的会话
+ pub updated_since: Option<i64>,
+ /// 命中行上限(消息级);0 = 默认 60
+ pub limit: i64,
+}
+
/// Insights 页统计快照(`Store::insights` 一次算好)。口径与主 UI 一致:
/// 全部 `archived = 0`;"prompts" = 主线用户消息(role=user 且非 sidechain)。
/// daily 是**全时段**活跃日谱(仅含有时间戳的行,升序)——热力图窗口、
diff --git a/crates/wake-core/src/services/context.rs b/crates/wake-core/src/services/context.rs
new file mode 100644
index 0000000..39d6886
--- /dev/null
+++ b/crates/wake-core/src/services/context.rs
@@ -0,0 +1,258 @@
+//! agent 取上下文用的纯函数(wake-mcp 工具层调用;无 UI、无 IO)。
+//! 项目参数的三级匹配与 `since` 解析都在这里,单测卡住语义——工具层只管拼装。
+
+use crate::adapters::path_owns;
+use crate::models::ProjectInfo;
+use chrono::{Local, NaiveDate, NaiveDateTime, TimeZone as _};
+
+/// 把 agent 给的 project 参数解析成索引里的项目路径集合(交给
+/// `SessionFilter::project_paths` / `SearchFilter::project_paths`)。
+///
+/// 绝对路径三级:①完全相等;②该路径是某项目路径的后代(agent 的 cwd 在
+/// 子目录里)→ 取最长的那个祖先;③项目路径是该路径的后代(monorepo 根、或
+/// `~/Github` 这类上层目录)→ 并集。边界判定用 `path_owns`,`wake-old` 不算
+/// `wake` 的后代。非绝对路径按项目名匹配(大小写不敏感;`project_name` 就是
+/// 各 adapter 经 `project_name_of` 取的路径尾段,不必再自己切一遍)。
+/// 返回空 = 没匹配上,调用方据此报"未知项目",**不要退化成不过滤**。
+pub fn resolve_project_paths(arg: &str, projects: &[ProjectInfo]) -> Vec<String> {
+ let arg = crate::adapters::expand_tilde(arg.trim());
+ let wanted = strip_trailing_sep(&arg);
+ if wanted.is_empty() {
+ return Vec::new();
+ }
+ if looks_like_path(wanted) {
+ if let Some(p) = projects
+ .iter()
+ .find(|p| strip_trailing_sep(&p.path) == wanted)
+ {
+ return vec![p.path.clone()];
+ }
+ let mut best: Option<&ProjectInfo> = None;
+ for p in projects.iter().filter(|p| !p.path.is_empty()) {
+ if path_owns(&p.path, wanted) && best.is_none_or(|b| p.path.len() > b.path.len()) {
+ best = Some(p);
+ }
+ }
+ if let Some(b) = best {
+ return vec![b.path.clone()];
+ }
+ let mut inside: Vec<String> = projects
+ .iter()
+ .filter(|p| !p.path.is_empty() && path_owns(wanted, &p.path))
+ .map(|p| p.path.clone())
+ .collect();
+ inside.sort();
+ inside.dedup();
+ return inside;
+ }
+ let lower = wanted.to_lowercase();
+ let mut matched: Vec<String> = projects
+ .iter()
+ .filter(|p| !p.path.is_empty() && p.name.to_lowercase() == lower)
+ .map(|p| p.path.clone())
+ .collect();
+ matched.sort();
+ matched.dedup();
+ matched
+}
+
+/// 是"路径"而非"项目名"的判据。不能只看 `Path::is_absolute`:Windows 上它对
+/// `/Users/…` 返回 false,而索引里的远程镜像会话(以及 CI 上的 fixture)全是
+/// POSIX 路径;反过来 Unix 上也认 `C:\…` 形态,一个盘符串不可能是项目名
+fn looks_like_path(s: &str) -> bool {
+ let bytes = s.as_bytes();
+ let drive = bytes.len() >= 3
+ && bytes[0].is_ascii_alphabetic()
+ && bytes[1] == b':'
+ && (bytes[2] == b'\\' || bytes[2] == b'/');
+ std::path::Path::new(s).is_absolute() || s.starts_with(std::path::is_separator) || drive
+}
+
+fn strip_trailing_sep(s: &str) -> &str {
+ let trimmed = s.trim_end_matches(std::path::is_separator);
+ // 文件系统根("/")剥光了会变空串,保留原样
+ if trimmed.is_empty() && !s.is_empty() {
+ s
+ } else {
+ trimmed
+ }
+}
+
+/// `since` 参数 → epoch ms。接受:相对量 `30m` / `24h` / `7d` / `2w`(以
+/// `now_ms` 为基准);RFC 3339(`2026-09-01T00:00:00Z`);无时区的日期时间
+/// (`2026-09-01 09:30`、`2026-09-01T09:30:00`,按本地时区);裸日期
+/// (`2026-09-01`,本地当天 00:00)。解析不了返回 None,调用方报参数错误
+pub fn parse_since(arg: &str, now_ms: i64) -> Option<i64> {
+ let s = arg.trim();
+ if s.is_empty() {
+ return None;
+ }
+ if let Some(ms) = parse_relative(s) {
+ return Some(now_ms - ms);
+ }
+ if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(s) {
+ return Some(dt.timestamp_millis());
+ }
+ for fmt in [
+ "%Y-%m-%dT%H:%M:%S",
+ "%Y-%m-%d %H:%M:%S",
+ "%Y-%m-%dT%H:%M",
+ "%Y-%m-%d %H:%M",
+ ] {
+ if let Ok(ndt) = NaiveDateTime::parse_from_str(s, fmt) {
+ return local_ms(ndt);
+ }
+ }
+ if let Ok(d) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
+ return local_ms(d.and_hms_opt(0, 0, 0)?);
+ }
+ None
+}
+
+fn parse_relative(s: &str) -> Option<i64> {
+ // 按最后一个**字符**切,不是最后一个字节:`7天` 的末字节落在多字节字符
+ // 中间,split_at 会 panic 把整个 server 带走
+ let unit = s.chars().last()?;
+ let unit_ms = match unit {
+ 'm' => 60_000,
+ 'h' => 3_600_000,
+ 'd' => 86_400_000,
+ 'w' => 7 * 86_400_000,
+ _ => return None,
+ };
+ let num = &s[..s.len() - unit.len_utf8()];
+ let n: i64 = num.parse().ok().filter(|n| *n >= 0)?;
+ n.checked_mul(unit_ms)
+}
+
+fn local_ms(ndt: NaiveDateTime) -> Option<i64> {
+ Local
+ .from_local_datetime(&ndt)
+ .earliest()
+ .map(|dt| dt.timestamp_millis())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn project(path: &str, name: &str) -> ProjectInfo {
+ ProjectInfo {
+ path: path.to_string(),
+ name: name.to_string(),
+ session_count: 1,
+ last_active: 0,
+ }
+ }
+
+ fn fixtures() -> Vec<ProjectInfo> {
+ vec![
+ project("/Users/t/Github/wake", "wake"),
+ project("/Users/t/Github/wake/crates/wake-core", "wake-core"),
+ project("/Users/t/Github/wake-old", "wake-old"),
+ project("/Users/t/Work/api", "api"),
+ project("", ""),
+ ]
+ }
+
+ #[test]
+ fn exact_match_wins_and_ignores_trailing_separator() {
+ let p = fixtures();
+ assert_eq!(
+ resolve_project_paths("/Users/t/Github/wake/", &p),
+ vec!["/Users/t/Github/wake".to_string()]
+ );
+ }
+
+ #[test]
+ fn cwd_inside_project_picks_longest_ancestor() {
+ let p = fixtures();
+ assert_eq!(
+ resolve_project_paths("/Users/t/Github/wake/src/db", &p),
+ vec!["/Users/t/Github/wake".to_string()]
+ );
+ assert_eq!(
+ resolve_project_paths("/Users/t/Github/wake/crates/wake-core/src", &p),
+ vec!["/Users/t/Github/wake/crates/wake-core".to_string()]
+ );
+ }
+
+ #[test]
+ fn ancestor_dir_unions_projects_below_it() {
+ let p = fixtures();
+ assert_eq!(
+ resolve_project_paths("/Users/t/Github", &p),
+ vec![
+ "/Users/t/Github/wake".to_string(),
+ "/Users/t/Github/wake-old".to_string(),
+ "/Users/t/Github/wake/crates/wake-core".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn sibling_with_shared_prefix_is_not_a_descendant() {
+ let p = vec![project("/Users/t/Github/wake", "wake")];
+ assert!(resolve_project_paths("/Users/t/Github/wake-old", &p).is_empty());
+ assert!(resolve_project_paths("/nope", &p).is_empty());
+ assert!(resolve_project_paths(" ", &p).is_empty());
+ }
+
+ #[test]
+ fn drive_letter_paths_are_paths_on_every_platform() {
+ let p = vec![project(r"C:\Users\t\Github\wake", "wake")];
+ assert_eq!(
+ resolve_project_paths(r"C:\Users\t\Github\wake", &p),
+ vec![r"C:\Users\t\Github\wake".to_string()]
+ );
+ // Unix 上 `\` 不是分隔符,后代匹配只在 Windows 成立;但盘符串在任何
+ // 平台都不该被当成项目名去比
+ assert!(resolve_project_paths(r"D:\elsewhere", &p).is_empty());
+ #[cfg(windows)]
+ assert_eq!(
+ resolve_project_paths(r"C:\Users\t\Github\wake\src", &p),
+ vec![r"C:\Users\t\Github\wake".to_string()]
+ );
+ }
+
+ #[test]
+ fn bare_name_matches_project_name_case_insensitively() {
+ let p = fixtures();
+ assert_eq!(
+ resolve_project_paths("Wake", &p),
+ vec!["/Users/t/Github/wake".to_string()]
+ );
+ assert!(resolve_project_paths("billing", &p).is_empty());
+ }
+
+ #[test]
+ fn since_relative_and_absolute_forms() {
+ let now = 1_800_000_000_000;
+ assert_eq!(parse_since("7d", now), Some(now - 7 * 86_400_000));
+ assert_eq!(parse_since("90m", now), Some(now - 90 * 60_000));
+ assert_eq!(parse_since("2w", now), Some(now - 14 * 86_400_000));
+ assert_eq!(
+ parse_since("2026-09-01T00:00:00Z", now),
+ Some(1_788_220_800_000)
+ );
+ let midnight = Local
+ .from_local_datetime(
+ &NaiveDate::from_ymd_opt(2026, 9, 1)
+ .unwrap()
+ .and_hms_opt(0, 0, 0)
+ .unwrap(),
+ )
+ .earliest()
+ .unwrap()
+ .timestamp_millis();
+ assert_eq!(parse_since("2026-09-01", now), Some(midnight));
+ assert_eq!(parse_since("2026-09-01 00:00", now), Some(midnight));
+ assert_eq!(parse_since("yesterday", now), None);
+ assert_eq!(parse_since("-3d", now), None);
+ assert_eq!(parse_since("", now), None);
+ // 非 ASCII 收尾只能是 None,绝不能 panic
+ assert_eq!(parse_since("7天", now), None);
+ assert_eq!(parse_since("昨天", now), None);
+ assert_eq!(parse_since("天", now), None);
+ }
+}
diff --git a/crates/wake-core/src/services/exporter.rs b/crates/wake-core/src/services/exporter.rs
index 3dd2118..ab832bc 100644
--- a/crates/wake-core/src/services/exporter.rs
+++ b/crates/wake-core/src/services/exporter.rs
@@ -2,7 +2,8 @@ use crate::adapters::AgentAdapter;
use crate::models::*;
use chrono::{Local, TimeZone};
-fn fmt_time(ts: Option<i64>) -> String {
+/// 本地时区 `YYYY-MM-DD HH:MM:SS`;0/None 为空串(导出与 wake-mcp 共用)
+pub fn fmt_time(ts: Option<i64>) -> String {
match ts {
Some(t) if t > 0 => Local
.timestamp_millis_opt(t)
@@ -23,12 +24,13 @@ pub fn fmt_tokens(n: Option<i64>) -> String {
}
}
-fn role_label(role: Role) -> &'static str {
- match role {
- Role::User => "👤 User",
- Role::Assistant => "🤖 Assistant",
- Role::System => "⚙️ System",
- }
+fn role_label(role: Role) -> String {
+ let emoji = match role {
+ Role::User => "👤",
+ Role::Assistant => "🤖",
+ Role::System => "⚙️",
+ };
+ format!("{emoji} {}", role.title())
}
fn render_message(m: &TranscriptMessage, out: &mut String) {
@@ -202,3 +204,382 @@ pub fn render_markdown(adapter: &dyn AgentAdapter, meta: &SessionMeta) -> anyhow
.collect();
Ok(to_markdown(&t.meta, &t.mainline, &sidechains))
}
+
+// ---------------------------------------------------------------- 精简渲染(wake-mcp)
+
+/// `render_compact` 的参数。默认值按"喂给另一个 agent 当上下文"调:不带工具
+/// 输出与 thinking,单条与整页都有字符硬顶,免得一个大会话吃光对方的窗口
+#[derive(Debug, Clone)]
+pub struct CompactOptions {
+ /// 从该 seq 起(含)
+ pub from_seq: i64,
+ /// 本页最多输出多少条消息(Meta 不计)
+ pub max_messages: usize,
+ /// 本页正文字符上限(至少给出一条,超出即停并给 next_seq)
+ pub max_chars: usize,
+ /// 单条消息正文字符上限,超出截断并标注
+ pub max_message_chars: usize,
+ /// 带工具调用的输入/输出正文(默认只留一行名称加输入预览)
+ pub include_tools: bool,
+ /// 带 thinking
+ pub include_thinking: bool,
+}
+
+impl Default for CompactOptions {
+ fn default() -> Self {
+ Self {
+ from_seq: 0,
+ max_messages: 60,
+ max_chars: 20_000,
+ max_message_chars: 4_000,
+ include_tools: false,
+ include_thinking: false,
+ }
+ }
+}
+
+/// 一页精简转录
+#[derive(Debug, Clone)]
+pub struct CompactPage {
+ pub text: String,
+ /// 下一页起点 seq;None = 已到主线末尾
+ pub next_seq: Option<i64>,
+ /// 本页输出的消息数
+ pub rendered: usize,
+ /// 本页范围内被跳过的注入上下文(Meta)条数
+ pub skipped_meta: usize,
+ /// 本页首/末条消息的 seq(rendered = 0 时 None)
+ pub seq_range: Option<(i64, i64)>,
+}
+
+/// 一条消息最多列出多少条工具调用(pi 系把一整轮助手回复合并成一条,里面可能
+/// 有上百次调用);超出的只报条数
+const MAX_TOOL_LINES: usize = 40;
+
+/// 省 token 的转录渲染:只出 user/assistant 正文,工具调用折成一行,Meta(注入
+/// 上下文)跳过并计数,CompactSummary 保留为引用块,图片略去;按 seq 分页。
+/// `max_message_chars` 是**整条消息**的预算:正文、thinking、工具行与工具
+/// 输入输出共用一份——分页对本页首条消息不查总量(保证前进),单条消息自身
+/// 必须有界,否则一轮上百次工具调用能撑爆对方上下文
+/// 与 `to_markdown`(全量导出)并存,seq 编号同源(`TranscriptMessage::seq`),
+/// 搜索命中的 `wake://session/<key>#<seq>` 引用直接对得上这里的 `[seq N]`
+pub fn render_compact(messages: &[TranscriptMessage], o: &CompactOptions) -> CompactPage {
+ let mut text = String::new();
+ let mut rendered = 0usize;
+ let mut skipped_meta = 0usize;
+ let mut chars = 0usize;
+ let mut next_seq = None;
+ let mut first_seq = None;
+ let mut last_seq = None;
+ for m in messages.iter().filter(|m| m.seq >= o.from_seq) {
+ if m.kind == MessageKind::Meta {
+ skipped_meta += 1;
+ continue;
+ }
+ let block = compact_block(m, o);
+ let block_chars = block.chars().count();
+ if rendered > 0 && (rendered >= o.max_messages || chars + block_chars > o.max_chars) {
+ next_seq = Some(m.seq);
+ break;
+ }
+ text.push_str(&block);
+ chars += block_chars;
+ rendered += 1;
+ first_seq.get_or_insert(m.seq);
+ last_seq = Some(m.seq);
+ }
+ CompactPage {
+ text,
+ next_seq,
+ rendered,
+ skipped_meta,
+ seq_range: first_seq.zip(last_seq),
+ }
+}
+
+fn compact_block(m: &TranscriptMessage, o: &CompactOptions) -> String {
+ let role = m.role.title();
+ let when = m
+ .timestamp
+ .map(|t| format!(" · {}", fmt_time(Some(t))))
+ .unwrap_or_default();
+ let mut out = format!("### [seq {}] {role}{when}\n", m.seq);
+ let mut budget = o.max_message_chars;
+ if m.kind == MessageKind::CompactSummary {
+ out.push_str("> [compacted summary] ");
+ out.push_str(&spend(&m.text, &mut budget).replace('\n', "\n> "));
+ out.push_str("\n\n");
+ return out;
+ }
+ // 正文优先于 thinking 拿预算,输出顺序仍是 thinking 在前
+ let body = spend(m.text.trim(), &mut budget);
+ let thinking = if o.include_thinking {
+ m.thinking
+ .as_deref()
+ .filter(|t| !t.trim().is_empty())
+ .map(|t| spend(t, &mut budget))
+ } else {
+ None
+ };
+ if let Some(th) = thinking {
+ out.push_str("> [thinking] ");
+ out.push_str(&th.replace('\n', "\n> "));
+ out.push_str("\n\n");
+ }
+ if !body.is_empty() {
+ out.push_str(&body);
+ out.push_str("\n\n");
+ } else if m.tool_calls.is_empty() {
+ out.push_str("(empty)\n\n");
+ }
+ if !m.images.is_empty() {
+ out.push_str(&format!(
+ "({} image attachment{} omitted)\n\n",
+ m.images.len(),
+ if m.images.len() == 1 { "" } else { "s" }
+ ));
+ }
+ let mut shown = 0usize;
+ for tc in &m.tool_calls {
+ // input_preview 由 parse_utils::make_preview 生产,已折行并封顶 200 字符
+ let status = if tc.is_error { " ✗" } else { "" };
+ let line = format!("- 🔧 {}{status}: {}\n", tc.name, tc.input_preview);
+ let line_chars = line.chars().count();
+ // 首条工具行无论如何给出(读者要知道这条消息动过工具),之后按预算
+ if shown >= MAX_TOOL_LINES || (shown > 0 && line_chars > budget) {
+ break;
+ }
+ out.push_str(&line);
+ budget = budget.saturating_sub(line_chars);
+ shown += 1;
+ if o.include_tools && budget > 0 {
+ if let Some(input) = tc.input.as_deref().filter(|s| !s.trim().is_empty()) {
+ out.push_str(&format!(
+ " input:\n ```\n{}\n ```\n",
+ indent(&spend(input, &mut budget))
+ ));
+ }
+ if let Some(output) = tc.output.as_deref().filter(|s| !s.trim().is_empty()) {
+ out.push_str(&format!(
+ " output:\n ```\n{}\n ```\n",
+ indent(&spend(output, &mut budget))
+ ));
+ }
+ }
+ }
+ let hidden = m.tool_calls.len() - shown;
+ if hidden > 0 {
+ out.push_str(&format!(
+ "- … {hidden} more tool call{} not shown\n",
+ if hidden == 1 { "" } else { "s" }
+ ));
+ }
+ if !m.tool_calls.is_empty() {
+ out.push('\n');
+ }
+ out
+}
+
+/// 从消息预算里扣着截:返回按剩余预算截断的文本,并把用掉的字符数记账
+fn spend(s: &str, budget: &mut usize) -> String {
+ let clipped = clip_chars(s, *budget);
+ *budget = budget.saturating_sub(clipped.chars().count());
+ clipped
+}
+
+/// 按字符截断并标注(字节切会切坏 CJK)。字节数 ≤ max 时字符数必 ≤ max,
+/// 先按字节放行,免得每条消息都整段数一遍字符
+fn clip_chars(s: &str, max: usize) -> String {
+ if s.len() <= max {
+ return s.to_string();
+ }
+ match s.char_indices().nth(max) {
+ Some((ix, _)) => format!("{}… [truncated]", &s[..ix]),
+ None => s.to_string(),
+ }
+}
+
+fn indent(s: &str) -> String {
+ s.lines()
+ .map(|l| format!(" {l}"))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+#[cfg(test)]
+mod compact_tests {
+ use super::*;
+
+ fn msg(seq: i64, role: Role, kind: MessageKind, text: &str) -> TranscriptMessage {
+ TranscriptMessage {
+ seq,
+ role,
+ kind,
+ text: text.to_string(),
+ truncated: false,
+ tool_calls: Vec::new(),
+ thinking: None,
+ timestamp: Some(1_754_042_400_000 + seq * 1000),
+ model: None,
+ images: Vec::new(),
+ }
+ }
+
+ fn transcript() -> Vec<TranscriptMessage> {
+ let mut tool = msg(
+ 2,
+ Role::Assistant,
+ MessageKind::Text,
+ "Let me edit the file.",
+ );
+ tool.tool_calls.push(ToolCallView {
+ id: "t1".into(),
+ name: "Edit".into(),
+ input_preview: "src/db.rs".into(),
+ input: Some("{\"path\":\"src/db.rs\"}".into()),
+ output: Some("ok, 3 lines changed".into()),
+ is_error: false,
+ sidechain_ref: None,
+ });
+ tool.thinking = Some("私下想一想".into());
+ vec![
+ msg(0, Role::User, MessageKind::Text, "帮我实现二维码扫描登录"),
+ msg(
+ 1,
+ Role::User,
+ MessageKind::Meta,
+ "<system-reminder>injected</system-reminder>",
+ ),
+ tool,
+ msg(
+ 3,
+ Role::Assistant,
+ MessageKind::Text,
+ &"很长的回答。".repeat(50),
+ ),
+ msg(
+ 4,
+ Role::System,
+ MessageKind::CompactSummary,
+ "Conversation compacted",
+ ),
+ msg(5, Role::User, MessageKind::Text, "继续"),
+ ]
+ }
+
+ #[test]
+ fn default_page_skips_meta_and_keeps_tool_names_only() {
+ let page = render_compact(&transcript(), &CompactOptions::default());
+ assert_eq!(page.rendered, 5);
+ assert_eq!(page.skipped_meta, 1);
+ assert_eq!(page.next_seq, None);
+ assert_eq!(page.seq_range, Some((0, 5)));
+ assert!(page.text.contains("### [seq 0] User"));
+ assert!(!page.text.contains("injected"));
+ assert!(page.text.contains("🔧 Edit: src/db.rs"));
+ assert!(!page.text.contains("3 lines changed"), "工具输出默认不带");
+ assert!(!page.text.contains("私下想一想"), "thinking 默认不带");
+ assert!(page
+ .text
+ .contains("> [compacted summary] Conversation compacted"));
+ }
+
+ #[test]
+ fn include_flags_add_tool_io_and_thinking() {
+ let o = CompactOptions {
+ include_tools: true,
+ include_thinking: true,
+ ..Default::default()
+ };
+ let page = render_compact(&transcript(), &o);
+ assert!(page.text.contains("3 lines changed"));
+ assert!(page.text.contains("[thinking] 私下想一想"));
+ }
+
+ #[test]
+ fn pagination_by_messages_and_chars_hands_back_next_seq() {
+ let o = CompactOptions {
+ max_messages: 2,
+ ..Default::default()
+ };
+ let page = render_compact(&transcript(), &o);
+ assert_eq!(page.rendered, 2);
+ assert_eq!(page.next_seq, Some(3), "第三条非 Meta 消息的 seq");
+ let o = CompactOptions {
+ from_seq: 3,
+ max_chars: 1,
+ ..Default::default()
+ };
+ let page = render_compact(&transcript(), &o);
+ assert_eq!(page.rendered, 1, "字符上限再小也至少给一条");
+ assert_eq!(page.seq_range, Some((3, 3)));
+ assert_eq!(page.next_seq, Some(4));
+ let o = CompactOptions {
+ from_seq: 5,
+ ..Default::default()
+ };
+ let page = render_compact(&transcript(), &o);
+ assert_eq!(page.rendered, 1);
+ assert_eq!(page.next_seq, None);
+ }
+
+ #[test]
+ fn tool_calls_share_the_message_budget() {
+ let mut m = msg(
+ 7,
+ Role::Assistant,
+ MessageKind::Text,
+ "Running the whole suite.",
+ );
+ for i in 0..120 {
+ m.tool_calls.push(ToolCallView {
+ id: format!("t{i}"),
+ name: "Bash".into(),
+ input_preview: format!("cargo test --test case_{i:03}"),
+ input: Some(format!("cargo test --test case_{i:03}")),
+ output: Some("ok. 12 passed; 0 failed\n".repeat(40)),
+ is_error: false,
+ sidechain_ref: None,
+ });
+ }
+ let o = CompactOptions {
+ max_message_chars: 400,
+ include_tools: true,
+ ..Default::default()
+ };
+ let page = render_compact(std::slice::from_ref(&m), &o);
+ let tool_lines = page.text.matches("🔧").count();
+ assert!(
+ tool_lines >= 1 && tool_lines < 120,
+ "{tool_lines} tool lines"
+ );
+ assert!(
+ page.text.contains("more tool calls not shown"),
+ "{}",
+ page.text
+ );
+ assert!(
+ page.text.chars().count() < 400 + 300,
+ "block must stay near the per-message budget, got {} chars",
+ page.text.chars().count()
+ );
+ // 预算充足时也不超过 MAX_TOOL_LINES 条
+ let roomy = CompactOptions {
+ max_message_chars: 100_000,
+ ..Default::default()
+ };
+ let page = render_compact(std::slice::from_ref(&m), &roomy);
+ assert_eq!(page.text.matches("🔧").count(), MAX_TOOL_LINES);
+ assert!(page.text.contains("80 more tool calls not shown"));
+ }
+
+ #[test]
+ fn long_messages_are_clipped_on_char_boundaries() {
+ let o = CompactOptions {
+ max_message_chars: 10,
+ ..Default::default()
+ };
+ let page = render_compact(&transcript(), &o);
+ assert!(page.text.contains("很长的回答。很长的回… [truncated]"));
+ }
+}
diff --git a/crates/wake-core/src/services/mod.rs b/crates/wake-core/src/services/mod.rs
index 43c80ef..cc93d41 100644
--- a/crates/wake-core/src/services/mod.rs
+++ b/crates/wake-core/src/services/mod.rs
@@ -1,2 +1,3 @@
+pub mod context;
pub mod exporter;
pub mod terminal;
diff --git a/crates/wake-core/src/text.rs b/crates/wake-core/src/text.rs
new file mode 100644
index 0000000..850d159
--- /dev/null
+++ b/crates/wake-core/src/text.rs
@@ -0,0 +1,40 @@
+//! 跨数据层与 UI 共用的文本小工具。wake crate 的 `format::one_line` 转发到
+//! 这里——同一条"折行截断"规则只写一次(曾在两个 crate 各有一份、同名不同义)
+
+/// 折成一行:空白压成单空格,超过 `max_chars` 个字符截断并加 `…`
+/// (按字符数计,CJK 安全)
+pub fn one_line(s: &str, max_chars: usize) -> String {
+ let flat = s.split_whitespace().collect::<Vec<_>>().join(" ");
+ match flat.char_indices().nth(max_chars) {
+ Some((ix, _)) => format!("{}…", &flat[..ix]),
+ None => flat,
+ }
+}
+
+/// 英文复数后缀:1 → ""、其余 → "s"
+pub fn plural(n: i64) -> &'static str {
+ if n == 1 {
+ ""
+ } else {
+ "s"
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn one_line_flattens_and_clips_by_chars() {
+ assert_eq!(one_line(" a\n\n b\tc ", 10), "a b c");
+ assert_eq!(one_line("二维码扫描登录", 3), "二维码…");
+ assert_eq!(one_line("abc", 3), "abc", "恰好等长不截");
+ }
+
+ #[test]
+ fn plural_suffix() {
+ assert_eq!(plural(1), "");
+ assert_eq!(plural(0), "s");
+ assert_eq!(plural(2), "s");
+ }
+}
diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rs
index cd8fe9b..9edda5e 100644
--- a/crates/wake-core/tests/adapter_contracts.rs
+++ b/crates/wake-core/tests/adapter_contracts.rs
@@ -63,18 +63,7 @@ fn setup() -> &'static TestEnv {
// home 复用同一份,两边不会各自漂移)
let sc = common::stage_sidecars(home.path());
- // WAKE_HOME 是 adapter 侧的统一改道开关,三端一致;HOME 仍设一份供
- // 其他 POSIX 依赖使用(Windows 上 dirs 不看 HOME,单设它等于没设)
- std::env::set_var("WAKE_HOME", home.path());
- std::env::set_var("HOME", home.path());
- // 测试只受这个假 HOME 支配:opencode 认 XDG_DATA_HOME、codex 认
- // CODEX_HOME,开发者或 CI 机器上设了它们,adapter 就会绕过 fixture
- // 去读真实库(实测 opencode 的两个契约测试会因此挂掉)
- std::env::remove_var("XDG_DATA_HOME");
- std::env::remove_var("CODEX_HOME");
- std::env::remove_var("QODER_CONFIG_DIR");
- std::env::remove_var("HERMES_HOME");
- std::env::remove_var("OPENCLAW_STATE_DIR");
+ common::isolate_home(home.path());
TestEnv {
copilot_db: sc.copilot_db,
opencode_db: sc.opencode_db,
diff --git a/crates/wake-core/tests/common/mod.rs b/crates/wake-core/tests/common/mod.rs
index 296f906..cdf4187 100644
--- a/crates/wake-core/tests/common/mod.rs
+++ b/crates/wake-core/tests/common/mod.rs
@@ -434,3 +434,27 @@ pub fn build_antigravity_db(path: &Path) {
)
.expect("populate antigravity fixture db");
}
+
+/// 让本进程(及其子进程)的全部 adapter 只看这个假 HOME:WAKE_HOME 是 adapter
+/// 侧的统一改道开关,三端一致;HOME 仍设一份供其他 POSIX 依赖(Windows 上 dirs
+/// 不看 HOME,单设它等于没设)。再清掉各家的 env 根覆盖——开发机或 CI 上设了
+/// CODEX_HOME / XDG_DATA_HOME 之类,adapter 就会绕过 fixture 去读真实库(实测
+/// opencode 的两个契约测试会因此挂掉)。新增带 env 根的 agent 只改这里
+pub fn isolate_home(home: &Path) {
+ std::env::set_var("WAKE_HOME", home);
+ std::env::set_var("HOME", home);
+ clear_agent_env_overrides();
+}
+
+/// 只清 env 根覆盖、不动 HOME(live 远程用例要保留 ~/.ssh)
+pub fn clear_agent_env_overrides() {
+ for var in [
+ "XDG_DATA_HOME",
+ "CODEX_HOME",
+ "QODER_CONFIG_DIR",
+ "HERMES_HOME",
+ "OPENCLAW_STATE_DIR",
+ ] {
+ std::env::remove_var(var);
+ }
+}
diff --git a/crates/wake-core/tests/db_roundtrip.rs b/crates/wake-core/tests/db_roundtrip.rs
index a797b35..42fadee 100644
--- a/crates/wake-core/tests/db_roundtrip.rs
+++ b/crates/wake-core/tests/db_roundtrip.rs
@@ -144,7 +144,6 @@ fn list_sessions_filters_and_counts() {
let all = SessionFilter {
agents: vec![],
- project_path: None,
favorite_only: false,
include_archived: false,
roots_only: false,
@@ -153,6 +152,9 @@ fn list_sessions_filters_and_counts() {
ascending: false,
limit: 10,
offset: 0,
+ updated_since: None,
+ project_paths: Vec::new(),
+ ignore_pins: false,
};
let (sessions, total) = store.list_sessions(&all).unwrap();
assert_eq!(total, 2);
@@ -261,7 +263,7 @@ fn nested_sessions_are_aggregated_but_starred_stays_flat() {
assert_eq!(store.agent_counts().unwrap()["grok"], 2);
assert_eq!(
store
- .list_projects()
+ .list_projects(false)
.unwrap()
.iter()
.find(|project| project.path == parent.project_path)
@@ -285,6 +287,102 @@ fn nested_sessions_are_aggregated_but_starred_stays_flat() {
);
}
+#[test]
+fn since_on_root_lists_uses_aggregated_child_activity() {
+ let (_dir, store) = temp_store();
+ let mut parent = meta("grok:since-parent", "parent");
+ parent.agent = AgentId::Grok;
+ parent.file_path = "/tmp/grok/s/parent/updates.jsonl".into();
+ parent.updated_at = 100;
+ let mut child = meta("grok:since-child", "child");
+ child.agent = AgentId::Grok;
+ child.file_path = "/tmp/grok/s/child/updates.jsonl".into();
+ child.updated_at = 500;
+ store
+ .write_meta_only(&[
+ (parent.clone(), parent.updated_at),
+ (child.clone(), child.updated_at),
+ ])
+ .unwrap();
+ store
+ .replace_parent_links(AgentId::Grok, &[(child.key.clone(), parent.key.clone())])
+ .unwrap();
+
+ // 父旧子新:根列表按聚合活动时间过滤,父会话必须还在(否则父子都消失)
+ let roots = SessionFilter {
+ roots_only: true,
+ updated_since: Some(300),
+ limit: 20,
+ ..Default::default()
+ };
+ let (rows, total) = store.list_sessions(&roots).unwrap();
+ assert_eq!(total, 1);
+ assert_eq!(rows[0].key, parent.key);
+ assert_eq!(rows[0].updated_at, 500, "返回的时间同样是聚合值");
+ // 平铺列表仍按自身时间过滤
+ let flat = SessionFilter {
+ updated_since: Some(300),
+ limit: 20,
+ ..Default::default()
+ };
+ let (rows, _) = store.list_sessions(&flat).unwrap();
+ assert_eq!(
+ rows.iter().map(|s| s.key.as_str()).collect::<Vec<_>>(),
+ [child.key.as_str()]
+ );
+}
+
+#[test]
+fn ignore_pins_gives_true_recency_order() {
+ let (_dir, store) = temp_store();
+ let mut old = meta("claude-code:old-pinned", "old");
+ old.updated_at = 100;
+ let mut new = meta("claude-code:newest", "new");
+ new.updated_at = 900;
+ store
+ .write_meta_only(&[(old.clone(), 100), (new.clone(), 900)])
+ .unwrap();
+ store.set_user_data(&old.key, None, Some(true)).unwrap();
+
+ let gui = SessionFilter {
+ limit: 1,
+ ..Default::default()
+ };
+ let (rows, _) = store.list_sessions(&gui).unwrap();
+ assert_eq!(rows[0].key, old.key, "GUI 列表置顶优先");
+ let mcp = SessionFilter {
+ limit: 1,
+ ignore_pins: true,
+ ..Default::default()
+ };
+ let (rows, _) = store.list_sessions(&mcp).unwrap();
+ assert_eq!(rows[0].key, new.key, "ignore_pins 后 limit 内是真最近");
+}
+
+#[test]
+fn archived_only_projects_are_listed_only_when_asked() {
+ let (_dir, store) = temp_store();
+ let mut archived = meta("codex:archived-only", "old work");
+ archived.agent = AgentId::Codex;
+ archived.archived = true;
+ archived.project_path = "/work/retired".into();
+ archived.project_name = "retired".into();
+ archived.file_path = "/tmp/codex/archived_sessions/r.jsonl".into();
+ store
+ .write_meta_only(&[(archived.clone(), archived.updated_at)])
+ .unwrap();
+ let paths = |include: bool| {
+ store
+ .list_projects(include)
+ .unwrap()
+ .into_iter()
+ .map(|p| p.path)
+ .collect::<Vec<_>>()
+ };
+ assert!(paths(false).is_empty(), "GUI 项目列表不含归档");
+ assert_eq!(paths(true), ["/work/retired".to_string()]);
+}
+
#[test]
fn removing_a_session_tree_writes_every_tombstone_atomically() {
let (_dir, store) = temp_store();
@@ -755,7 +853,9 @@ fn insights_snapshot_and_streaks() {
store
.write_session(&bad, bad.updated_at, &[at(0, Role::User, Some(ts(12, 8)))])
.unwrap();
- let d2 = store.insights(today).expect("bad created_at must not abort insights");
+ let d2 = store
+ .insights(today)
+ .expect("bad created_at must not abort insights");
assert_eq!(d2.sessions, d.sessions + 1);
assert_eq!(d2.daily_sessions, vec![(created_day, 2)]);
diff --git a/crates/wake-core/tests/mcp_stdio.rs b/crates/wake-core/tests/mcp_stdio.rs
new file mode 100644
index 0000000..864f354
--- /dev/null
+++ b/crates/wake-core/tests/mcp_stdio.rs
@@ -0,0 +1,359 @@
+//! wake-mcp 的端到端契约:合成 fixtures 建临时库 → 以真实 bin 起子进程 → 走
+//! stdio JSON-RPC。卡住:工具清单稳定;search 命中的 seq 等于 parse_transcript
+//! 的序号(seq 契约延伸到 MCP);get_session 分页的 next_seq 逐页衔接、覆盖全部
+//! 非 Meta 消息;全程只读(库文件字节不变);坏 key 是 isError 而非崩溃;未知
+//! 方法 -32601;库不存在时进程以清晰错误退出。
+//!
+//! WAKE_HOME 是进程级环境且子进程继承它,整个文件只有一个用例。
+
+use std::io::{BufRead, BufReader, Write};
+use std::path::Path;
+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
+use std::sync::Arc;
+
+use serde_json::{json, Value};
+use wake_core::adapters::{adapter_for, create_adapter_roster_for};
+use wake_core::db::Store;
+use wake_core::models::*;
+use wake_core::scanner::{run_scan, NullEvents};
+
+mod common;
+
+const CLAUDE_KEY: &str = "claude-code:11111111-aaaa-bbbb-cccc-000000000001";
+const CLAUDE_PROJECT: &str = "/Users/tester/Github/wakefx";
+
+struct Client {
+ child: Child,
+ stdin: Option<ChildStdin>,
+ stdout: BufReader<ChildStdout>,
+ next_id: i64,
+}
+
+impl Client {
+ fn spawn(db: &Path) -> Client {
+ let mut child = Command::new(env!("CARGO_BIN_EXE_wake-mcp"))
+ .arg("--db")
+ .arg(db)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .expect("spawn wake-mcp");
+ let stdin = child.stdin.take().unwrap();
+ let stdout = BufReader::new(child.stdout.take().unwrap());
+ Client {
+ child,
+ stdin: Some(stdin),
+ stdout,
+ next_id: 0,
+ }
+ }
+
+ fn send_raw(&mut self, line: &str) {
+ let stdin = self.stdin.as_mut().unwrap();
+ stdin.write_all(line.as_bytes()).unwrap();
+ stdin.write_all(b"\n").unwrap();
+ stdin.flush().unwrap();
+ }
+
+ fn read_reply(&mut self) -> Value {
+ let mut line = String::new();
+ let n = self.stdout.read_line(&mut line).expect("read reply");
+ assert!(n > 0, "wake-mcp closed stdout unexpectedly");
+ serde_json::from_str(&line).unwrap_or_else(|e| panic!("reply is not JSON: {e}: {line}"))
+ }
+
+ fn request(&mut self, method: &str, params: Value) -> Value {
+ self.next_id += 1;
+ let id = self.next_id;
+ self.send_raw(
+ &json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }).to_string(),
+ );
+ let reply = self.read_reply();
+ assert_eq!(reply["jsonrpc"], "2.0");
+ assert_eq!(reply["id"], id, "reply id mismatch: {reply}");
+ reply
+ }
+
+ fn notify(&mut self, method: &str) {
+ self.send_raw(&json!({ "jsonrpc": "2.0", "method": method }).to_string());
+ }
+
+ /// tools/call → (text, isError);协议错误直接 panic
+ fn call(&mut self, tool: &str, args: Value) -> (String, bool) {
+ let reply = self.request("tools/call", json!({ "name": tool, "arguments": args }));
+ assert!(
+ reply.get("error").is_none(),
+ "{tool} returned a protocol error: {}",
+ reply["error"]
+ );
+ let result = &reply["result"];
+ let text = result["content"][0]["text"]
+ .as_str()
+ .unwrap_or_else(|| panic!("{tool} result has no text content: {result}"))
+ .to_string();
+ (text, result["isError"].as_bool().unwrap_or(false))
+ }
+
+ fn finish(mut self) {
+ drop(self.stdin.take());
+ let status = self.child.wait().expect("wait wake-mcp");
+ assert!(status.success(), "wake-mcp exited with {status}");
+ }
+}
+
+/// `### [seq N]` 标题里的 seq,按出现顺序
+fn seqs_in(text: &str) -> Vec<i64> {
+ text.lines()
+ .filter_map(|l| l.strip_prefix("### [seq "))
+ .filter_map(|rest| rest.split(']').next()?.parse().ok())
+ .collect()
+}
+
+fn next_seq_hint(text: &str) -> Option<i64> {
+ text.lines()
+ .find_map(|l| l.split("from_seq=").nth(1))
+ .and_then(|rest| rest.trim_end_matches('.').trim().parse().ok())
+}
+
+#[test]
+fn stdio_contract_end_to_end() {
+ let tmp = tempfile::Builder::new()
+ .prefix("wake-mcp-e2e-")
+ .tempdir()
+ .unwrap();
+ let home = tmp.path().join("home");
+ common::stage_dir_fixtures(&home);
+ common::stage_sidecars(&home);
+ // 子进程继承这些:它的 roster 也要指向 fixture home,别读到开发机的真实数据
+ common::isolate_home(&home);
+
+ // 1. 建库 + 全量扫描,并从本进程算出 seq 契约的参照
+ let db = tmp.path().join("wake.db");
+ let expected_seqs: Vec<i64>;
+ let qr_seq: i64;
+ let total_sessions: i64;
+ {
+ let store = Arc::new(Store::open(&db).unwrap());
+ let roster = create_adapter_roster_for(&store);
+ run_scan(&roster.active, &store, &NullEvents, true).expect("scan ok");
+ let (_, total) = store
+ .list_sessions(&SessionFilter {
+ limit: 1,
+ ..Default::default()
+ })
+ .unwrap();
+ total_sessions = total;
+ let meta = store
+ .get_session(CLAUDE_KEY)
+ .unwrap()
+ .expect("claude fixture indexed");
+ assert_eq!(meta.project_path, CLAUDE_PROJECT);
+ let adapter = adapter_for(&roster.active, meta.agent, &meta.file_path).unwrap();
+ let t = adapter
+ .parse_transcript(&SessionFileRef::from_meta(&meta))
+ .unwrap();
+ expected_seqs = t
+ .mainline
+ .iter()
+ .filter(|m| m.kind != MessageKind::Meta)
+ .map(|m| m.seq)
+ .collect();
+ qr_seq = t
+ .mainline
+ .iter()
+ .find(|m| m.text.contains("二维码"))
+ .map(|m| m.seq)
+ .expect("fixture has the 二维码 prompt");
+ // Store 在这里关闭:最后一个连接落盘 checkpoint 之后再拍库文件快照
+ }
+ assert!(
+ total_sessions > 10,
+ "fixture home should index many sessions"
+ );
+ let before = std::fs::read(&db).unwrap();
+
+ // 2. 握手与协议面
+ let mut c = Client::spawn(&db);
+ let init = c.request(
+ "initialize",
+ json!({
+ "protocolVersion": "2025-06-18",
+ "capabilities": {},
+ "clientInfo": { "name": "wake-test", "version": "0" }
+ }),
+ );
+ assert_eq!(init["result"]["protocolVersion"], "2025-06-18");
+ assert_eq!(init["result"]["serverInfo"]["name"], "wake");
+ assert!(init["result"]["capabilities"]["tools"].is_object());
+ assert!(init["result"]["instructions"]
+ .as_str()
+ .unwrap()
+ .contains("wake_search"));
+ c.notify("notifications/initialized");
+ assert_eq!(c.request("ping", json!({}))["result"], json!({}));
+
+ let tools = c.request("tools/list", json!({}));
+ let names: Vec<&str> = tools["result"]["tools"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|t| t["name"].as_str().unwrap())
+ .collect();
+ assert_eq!(
+ names,
+ [
+ "wake_search",
+ "wake_list_sessions",
+ "wake_get_session",
+ "wake_list_projects"
+ ]
+ );
+
+ let unknown = c.request("resources/list", json!({}));
+ assert_eq!(unknown["error"]["code"], -32601);
+ let bad_tool = c.request(
+ "tools/call",
+ json!({ "name": "wake_delete_everything", "arguments": {} }),
+ );
+ assert_eq!(bad_tool["error"]["code"], -32602);
+ let bad_since = c.request(
+ "tools/call",
+ json!({ "name": "wake_list_sessions", "arguments": { "since": "yesterday" } }),
+ );
+ assert_eq!(bad_since["error"]["code"], -32602, "参数形状错是协议错误");
+ // 非 ASCII 收尾的 since 曾让 split_at 在字符中间 panic、整个 server 退出
+ let cjk_since = c.request(
+ "tools/call",
+ json!({ "name": "wake_list_sessions", "arguments": { "since": "7天" } }),
+ );
+ assert_eq!(cjk_since["error"]["code"], -32602, "{cjk_since}");
+ c.send_raw("{not json");
+ let parse_err = c.read_reply();
+ assert_eq!(parse_err["error"]["code"], -32700);
+ assert!(parse_err["id"].is_null());
+
+ // 3. search 命中的 seq 与 parse_transcript 的序号一致(seq 契约)。fixture
+ // home 里十几家都有 "二维码" 提示词,按 agent 收窄让断言不依赖 bm25 排位
+ let (everywhere, is_err) = c.call("wake_search", json!({ "query": "二维码", "limit": 30 }));
+ assert!(!is_err, "{everywhere}");
+ assert!(
+ everywhere.contains("sessions match `二维码`"),
+ "{everywhere}"
+ );
+ let (text, is_err) = c.call(
+ "wake_search",
+ json!({ "query": "二维码", "agents": ["claude"], "project": CLAUDE_PROJECT }),
+ );
+ assert!(!is_err, "{text}");
+ assert!(text.contains(CLAUDE_KEY), "{text}");
+ let expected_ref = format!("ref: wake://session/{CLAUDE_KEY}#{qr_seq}");
+ assert!(
+ text.contains(&expected_ref),
+ "search hit must cite seq {qr_seq}:\n{text}"
+ );
+ assert!(text.contains("Index covers activity up to"));
+
+ // 4. get_session:引用形态起点、分页衔接、覆盖全部非 Meta 消息
+ let (page, is_err) = c.call(
+ "wake_get_session",
+ json!({ "key": format!("wake://session/{CLAUDE_KEY}#{qr_seq}"), "max_messages": 1 }),
+ );
+ assert!(!is_err, "{page}");
+ assert_eq!(seqs_in(&page), vec![qr_seq]);
+ assert!(page.contains("二维码"));
+ assert!(page.contains("key: `claude-code:"));
+
+ let mut visited = Vec::new();
+ let mut from = 0;
+ for _ in 0..50 {
+ let (page, is_err) = c.call(
+ "wake_get_session",
+ json!({ "key": CLAUDE_KEY, "from_seq": from, "max_messages": 2 }),
+ );
+ assert!(!is_err, "{page}");
+ let seqs = seqs_in(&page);
+ assert!(
+ !seqs.is_empty(),
+ "page from {from} rendered nothing:\n{page}"
+ );
+ assert_eq!(seqs[0], *seqs.iter().min().unwrap());
+ visited.extend(seqs);
+ match next_seq_hint(&page) {
+ Some(next) => {
+ assert!(next > from, "next_seq must advance: {from} → {next}");
+ from = next;
+ }
+ None => {
+ assert!(page.contains("End of transcript."), "{page}");
+ break;
+ }
+ }
+ }
+ assert_eq!(
+ visited, expected_seqs,
+ "paging must cover every non-Meta message exactly once"
+ );
+
+ let (tools_page, _) = c.call(
+ "wake_get_session",
+ json!({ "key": CLAUDE_KEY, "include_tools": true }),
+ );
+ assert!(
+ tools_page.contains("output:"),
+ "include_tools should add tool output:\n{tools_page}"
+ );
+ let (plain_page, _) = c.call("wake_get_session", json!({ "key": CLAUDE_KEY }));
+ assert!(!plain_page.contains("output:"));
+ assert!(
+ plain_page.contains("🔧"),
+ "tool calls fold to one line by default"
+ );
+
+ // 5. 项目匹配:cwd 在项目子目录里、没匹配上、项目清单
+ let (listed, is_err) = c.call(
+ "wake_list_sessions",
+ json!({ "project": format!("{CLAUDE_PROJECT}/src/deep"), "agents": ["claude"] }),
+ );
+ assert!(!is_err);
+ assert!(listed.contains(CLAUDE_KEY), "{listed}");
+ let (nowhere, is_err) = c.call(
+ "wake_list_sessions",
+ json!({ "project": "/nowhere/at/all" }),
+ );
+ assert!(!is_err, "没匹配上项目不是错误");
+ assert!(nowhere.contains("No indexed project matches"), "{nowhere}");
+ assert!(
+ nowhere.contains(CLAUDE_PROJECT),
+ "should list known projects:\n{nowhere}"
+ );
+ let (projects, _) = c.call("wake_list_projects", json!({}));
+ assert!(projects.contains(CLAUDE_PROJECT));
+ let (since_none, _) = c.call("wake_list_sessions", json!({ "since": "1m" }));
+ assert!(since_none.starts_with("No sessions"), "{since_none}");
+
+ // 6. 坏 key 是给 LLM 看的失败结果,不是协议错误、更不是崩溃
+ let (missing, is_err) = c.call("wake_get_session", json!({ "key": "claude-code:nope" }));
+ assert!(is_err);
+ assert!(missing.contains("No session with key"), "{missing}");
+
+ c.finish();
+
+ // 7. 全程只读
+ let after = std::fs::read(&db).unwrap();
+ assert!(before == after, "wake-mcp must never write the index");
+}
+
+#[test]
+fn missing_index_exits_with_a_clear_error() {
+ let tmp = tempfile::tempdir().unwrap();
+ let out = Command::new(env!("CARGO_BIN_EXE_wake-mcp"))
+ .arg("--db")
+ .arg(tmp.path().join("nope.db"))
+ .stdin(Stdio::null())
+ .output()
+ .unwrap();
+ assert!(!out.status.success());
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert!(stderr.contains("launch Wake once"), "{stderr}");
+}
diff --git a/crates/wake-core/tests/remote_sync.rs b/crates/wake-core/tests/remote_sync.rs
index 97f4f5e..b5ee47f 100644
--- a/crates/wake-core/tests/remote_sync.rs
+++ b/crates/wake-core/tests/remote_sync.rs
@@ -119,17 +119,7 @@ fn remote_pipeline_end_to_end() {
);
// 本地 roster 指向一个空 home:库里出现的只能是远程行,也不会读到这台
// 开发机的真实数据;env 根覆盖一并清掉
- std::env::set_var("WAKE_HOME", &local_home);
- std::env::set_var("HOME", &local_home);
- for var in [
- "XDG_DATA_HOME",
- "CODEX_HOME",
- "QODER_CONFIG_DIR",
- "HERMES_HOME",
- "OPENCLAW_STATE_DIR",
- ] {
- std::env::remove_var(var);
- }
+ common::isolate_home(&local_home);
build_remote_home(&home);
let store = Arc::new(Store::open(&tmp.path().join("wake.db")).unwrap());
@@ -322,15 +312,7 @@ fn live_remote_host() {
fs::create_dir_all(&local_home).unwrap();
// 本地 roster 指向空 home(HOME 保留,ssh 要读 ~/.ssh)
std::env::set_var("WAKE_HOME", &local_home);
- for var in [
- "XDG_DATA_HOME",
- "CODEX_HOME",
- "QODER_CONFIG_DIR",
- "HERMES_HOME",
- "OPENCLAW_STATE_DIR",
- ] {
- std::env::remove_var(var);
- }
+ common::clear_agent_env_overrides();
let store = Arc::new(Store::open(&tmp.path().join("wake.db")).unwrap());
store.add_remote_host(&host).unwrap();
let cache = wake_core::remote::host_cache_dir(&store.db_dir().unwrap(), &host);
diff --git a/crates/wake/assets/icons/plug.svg b/crates/wake/assets/icons/plug.svg
new file mode 100644
index 0000000..af8276e
--- /dev/null
+++ b/crates/wake/assets/icons/plug.svg
@@ -0,0 +1,18 @@
+<!-- @license lucide-static v0.462.0 - ISC -->
+<svg
+ class="lucide lucide-plug"
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M12 22v-5" />
+ <path d="M9 8V2" />
+ <path d="M15 8V2" />
+ <path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z" />
+</svg>
diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rs
index 37c1ed0..7351c35 100644
--- a/crates/wake/src/assets.rs
+++ b/crates/wake/src/assets.rs
@@ -109,6 +109,7 @@ icons!(
"plus",
"info",
"chart-column",
+ "plug",
);
impl AssetSource for Assets {
diff --git a/crates/wake/src/format.rs b/crates/wake/src/format.rs
index e16a0e4..61177de 100644
--- a/crates/wake/src/format.rs
+++ b/crates/wake/src/format.rs
@@ -114,8 +114,7 @@ pub fn fmt_tokens(n: Option<i64>) -> String {
}
}
-/// 进程内不变的 HOME,缓存住:数据源路径折叠与手输展开(expand_tilde)
-/// 共用同一份。
+/// 进程内不变的 HOME,缓存住:数据源路径折叠(tilde_path)每帧都要用。
fn cached_home() -> Option<&'static str> {
static HOME: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
HOME.get_or_init(|| {
@@ -148,18 +147,10 @@ pub fn tilde_path(p: &str) -> String {
}
}
-/// 手输路径的 `~` 前缀展开(tilde_path 的逆;仅前缀,边界同样落在分隔符上
-/// ——Windows 用户手输 `~\foo` 同样认)
+/// 手输路径的 `~` 前缀展开(tilde_path 的逆)。实现在 wake-core,与 adapter
+/// 的 HOME 同源;这里只是转发,UI 调用点不必知道 wake_core::adapters
pub fn expand_tilde(p: &str) -> String {
- match p.strip_prefix('~') {
- Some(rest) if rest.is_empty() || rest.starts_with(std::path::is_separator) => {
- match cached_home() {
- Some(h) => format!("{h}{rest}"),
- None => p.to_string(),
- }
- }
- _ => p.to_string(),
- }
+ wake_core::adapters::expand_tilde(p)
}
/// 图片字节数的人读格式;详情预览只需要 KB/MB 两档。
@@ -174,17 +165,9 @@ pub fn human_bytes(bytes: usize) -> String {
}
}
-/// 首行截断预览
+/// 首行截断预览(实现在 wake-core text 模块,wake-mcp 的会话行同一条规则)
pub fn one_line(s: &str, max_chars: usize) -> String {
- let joined = s.split_whitespace().collect::<Vec<_>>().join(" ");
- let chars: Vec<char> = joined.chars().collect();
- if chars.len() > max_chars {
- let mut t: String = chars[..max_chars].iter().collect();
- t.push('…');
- t
- } else {
- joined
- }
+ wake_core::text::one_line(s, max_chars)
}
#[cfg(test)]
diff --git a/crates/wake/src/settings.rs b/crates/wake/src/settings.rs
index 52e2a17..932cce5 100644
--- a/crates/wake/src/settings.rs
+++ b/crates/wake/src/settings.rs
@@ -2,6 +2,7 @@ use gpui::prelude::FluentBuilder as _;
use gpui::*;
use gpui_component::button::{Button, ButtonCustomVariant, ButtonVariants as _};
use gpui_component::menu::{DropdownMenu as _, PopupMenuItem};
+use gpui_component::notification::Notification;
use gpui_component::switch::Switch;
use gpui_component::{
h_flex, v_flex, ActiveTheme as _, Disableable as _, Icon, Selectable as _, Sizable as _,
@@ -10,6 +11,7 @@ use gpui_component::{
use wake_core::models::AgentId;
+use crate::format::tilde_path;
use crate::ui::{
overlay_layers, BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY, FONT_HEADING, FONT_LABEL,
FONT_TITLE, RADIUS_BUTTON, SHOW_IN_FM, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL, SPACE_XS,
@@ -21,6 +23,8 @@ use crate::{theme, theme::AppearancePreference};
const SETTINGS_SIDEBAR_W: Pixels = px(180.);
const SETTINGS_PAGE_TOP: Pixels = px(38.);
+/// Settings → Connect 页尾 Setup guide 的去处:仓库里的 MCP 完整文档
+const CONNECT_GUIDE_URL: &str = "https://github.com/iAmCorey/Wake/blob/main/docs/mcp.md";
fn icon(path: &'static str) -> Icon {
Icon::empty().path(path)
@@ -47,6 +51,7 @@ pub(crate) enum SettingsPage {
General,
Locations,
Remotes,
+ Connect,
Data,
Updates,
About,
@@ -89,11 +94,106 @@ fn settings_primary_button(button: Button, cx: &App) -> Button {
.rounded(RADIUS_BUTTON)
}
+/// Settings 各页顶部的标题 + 一句说明(版式只写一次:SPACE_XXL 边距、
+/// SETTINGS_PAGE_TOP 顶距、FONT_TITLE semibold + FONT_CAPTION muted)
+fn settings_page_header(title: &'static str, subtitle: &'static str, cx: &App) -> Div {
+ let theme = cx.theme();
+ v_flex()
+ .flex_shrink_0()
+ .px(SPACE_XXL)
+ .pt(SETTINGS_PAGE_TOP)
+ .pb(SPACE_XL)
+ .gap(px(5.))
+ .child(
+ div()
+ .text_size(FONT_TITLE)
+ .font_semibold()
+ .text_color(theme.foreground)
+ .child(title),
+ )
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(subtitle),
+ )
+}
+
+/// "一张卡一行"的信息卡(Data 的 Storage、Connect 的 MCP server 共用):popover
+/// 底圆角卡,84px 行,主信息 FONT_BODY,副行由调用方给(caption 级),右侧一个操作
+fn settings_info_card(
+ primary: &'static str,
+ details: Vec<AnyElement>,
+ trailing: AnyElement,
+ cx: &App,
+) -> Div {
+ let theme = cx.theme();
+ // overflow_hidden 让 taffy 把这张卡的 min-height 当 0,放进滚动列里会被
+ // 压扁到只剩一行;固定内容的卡必须 flex_shrink_0(CLAUDE.md 的 flex 陷阱)
+ v_flex()
+ .w_full()
+ .flex_shrink_0()
+ .overflow_hidden()
+ .rounded(theme.radius_lg)
+ .border_1()
+ .border_color(theme.border)
+ .bg(theme.popover)
+ .child(
+ h_flex()
+ .min_h(px(84.))
+ .px(SPACE_LG)
+ .gap(SPACE_LG)
+ .items_center()
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(3.))
+ .child(
+ div()
+ .text_size(FONT_BODY)
+ .text_color(theme.foreground)
+ .child(primary),
+ )
+ .children(details),
+ )
+ .child(trailing),
+ )
+}
+
+/// Connect 页展示的 wake-mcp 事实,开窗时算一次:current_exe/stat/片段拼装都
+/// 不该跑在每帧的 render 里(CLAUDE.md:render 里的路径探测必须缓存)
+struct ConnectInfo {
+ bin_path: String,
+ bin_display: SharedString,
+ bin_exists: bool,
+ snippets: Vec<wake_core::mcp::SetupSnippet>,
+}
+
+impl ConnectInfo {
+ fn probe() -> Self {
+ let bin = wake_core::mcp::sibling_binary();
+ let bin_exists = bin.as_ref().is_some_and(|p| p.is_file());
+ let bin_path = bin
+ .map(|p| p.to_string_lossy().to_string())
+ .unwrap_or_else(|| "wake-mcp".to_string());
+ Self {
+ bin_display: tilde_path(&bin_path).into(),
+ bin_exists,
+ snippets: wake_core::mcp::setup_snippets(std::path::Path::new(&bin_path)),
+ bin_path,
+ }
+ }
+}
+
pub(crate) struct SettingsView {
focus_handle: FocusHandle,
workbench: Entity<Workbench>,
appearance: AppearancePreference,
show_unavailable: bool,
+ connect: ConnectInfo,
+ /// Connect 页里展开了代码片段的行(按 snippets 下标);Settings 重开即复位
+ connect_shown: std::collections::HashSet<usize>,
_workbench_observer: Option<Subscription>,
}
@@ -115,6 +215,8 @@ impl SettingsView {
workbench,
appearance: theme::appearance_preference(),
show_unavailable: false,
+ connect: ConnectInfo::probe(),
+ connect_shown: Default::default(),
_workbench_observer: None,
}
}
@@ -204,6 +306,13 @@ impl SettingsView {
SettingsPage::Remotes,
cx,
))
+ .child(self.render_nav_item(
+ "settings-connect-nav",
+ "Connect",
+ "icons/plug.svg",
+ SettingsPage::Connect,
+ cx,
+ ))
.child(self.render_nav_item(
"settings-data-nav",
"Data",
@@ -371,14 +480,10 @@ impl SettingsView {
fn render_data(&mut self, cx: &mut Context<Self>) -> AnyElement {
let theme = cx.theme();
let snapshot = self.workbench.read(cx).data_settings_snapshot();
- let session_word = if snapshot.session_count == 1 {
- "session"
- } else {
- "sessions"
- };
let summary: SharedString = format!(
- "{} {session_word} · {}",
+ "{} session{} · {}",
snapshot.session_count,
+ wake_core::text::plural(snapshot.session_count),
format_storage_size(snapshot.size_bytes)
)
.into();
@@ -392,88 +497,277 @@ impl SettingsView {
.on_click(move |_, _, _| {
wake_core::services::terminal::open_in_file_manager(reveal_path.as_ref())
});
+ let details = vec![
+ div()
+ .w_full()
+ .truncate()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(snapshot.display_path)
+ .into_any_element(),
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(summary)
+ .into_any_element(),
+ ];
v_flex()
.flex_1()
.min_w_0()
.h_full()
.bg(theme.background)
+ .child(settings_page_header(
+ "Data",
+ "See where Wake stores local data. Sessions refresh automatically.",
+ cx,
+ ))
.child(
v_flex()
- .flex_shrink_0()
.px(SPACE_XXL)
- .pt(SETTINGS_PAGE_TOP)
- .pb(SPACE_XL)
- .gap(px(5.))
+ .gap(SPACE_SM)
.child(
div()
- .text_size(FONT_TITLE)
+ .text_size(FONT_CAPTION)
.font_semibold()
.text_color(theme.foreground)
- .child("Data"),
+ .child("Storage"),
)
+ .child(settings_info_card(
+ "Wake data",
+ details,
+ show_in_finder.into_any_element(),
+ cx,
+ )),
+ )
+ .into_any_element()
+ }
+
+ /// Settings → Connect 的复制按钮:写剪贴板 + 一条成功通知
+ fn copy_button(
+ &self,
+ id: SharedString,
+ label: &'static str,
+ text: String,
+ cx: &Context<Self>,
+ ) -> Button {
+ settings_button(
+ Button::new(id)
+ .icon(icon("icons/copy.svg").with_size(px(13.)))
+ .label(label),
+ cx,
+ )
+ .on_click(move |_, window, cx| {
+ cx.write_to_clipboard(ClipboardItem::new_string(text.clone()));
+ window.push_notification(Notification::success("Copied to clipboard"), cx);
+ })
+ }
+
+ /// Settings → Connect:把 Wake 的索引以 MCP 只读暴露给 coding agent。页面只放
+ /// **状态与动作**:server 卡(路径 + Copy path)、Agents 卡(每家一行一个
+ /// Copy 钮)、一句 caption 加 Setup guide 链接。代码块与工具表都不放——那是
+ /// README 的内容,塞进设置窗怎么排都像教程(用户 2026-09-08 三轮定稿)。
+ /// 只展示与复制,不代写别家配置;片段与 `wake-mcp setup` 同源(wake-core mcp)
+ fn render_connect(&mut self, cx: &mut Context<Self>) -> AnyElement {
+ let theme = cx.theme();
+ let dark = theme.mode.is_dark();
+ let info = &self.connect;
+ let mono = theme.mono_font_family.clone();
+ let count = info.snippets.len();
+
+ let agent_rows: Vec<AnyElement> = info
+ .snippets
+ .iter()
+ .enumerate()
+ .map(|(ix, s)| {
+ let shown = self.connect_shown.contains(&ix);
+ let copy = self.copy_button(
+ format!("connect-copy-{ix}").into(),
+ s.copy_label,
+ s.text.clone(),
+ cx,
+ );
+ // 低强调的展开切换:片段默认收起,想核对再看
+ let toggle = Button::new(SharedString::from(format!("connect-show-{ix}")))
+ .custom(
+ ButtonCustomVariant::new(cx)
+ .color(theme.transparent)
+ .foreground(theme.muted_foreground)
+ .hover(theme.secondary_hover)
+ .active(theme.popover),
+ )
+ .small()
+ .rounded(RADIUS_BUTTON)
+ .icon(
+ icon(if shown {
+ "icons/chevron-down.svg"
+ } else {
+ "icons/chevron-right.svg"
+ })
+ .with_size(px(13.)),
+ )
+ .label(if shown { "Hide" } else { "Show" })
+ .on_click(cx.listener(move |this, _, _, cx| {
+ if !this.connect_shown.remove(&ix) {
+ this.connect_shown.insert(ix);
+ }
+ cx.notify();
+ }));
+ let lines: Vec<AnyElement> = s
+ .text
+ .lines()
+ .map(|l| div().child(l.to_string()).into_any_element())
+ .collect();
+ v_flex()
+ .w_full()
+ .when(ix + 1 < count, |this| {
+ this.border_b_1().border_color(theme.border)
+ })
.child(
- div()
- .text_size(FONT_CAPTION)
- .text_color(theme.muted_foreground)
+ h_flex()
+ .w_full()
+ .min_h(px(52.))
+ .px(SPACE_LG)
+ .py(SPACE_SM)
+ .gap(SPACE_MD)
+ .items_center()
+ .child(img(s.agent.brand_icon(dark)).size(px(17.)).flex_shrink_0())
.child(
- "See where Wake stores local data. Sessions refresh automatically.",
- ),
- ),
- )
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(2.))
+ .child(
+ div()
+ .text_size(FONT_BODY)
+ .text_color(theme.foreground)
+ .child(s.client),
+ )
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(s.hint),
+ ),
+ )
+ .child(toggle)
+ .child(copy),
+ )
+ .when(shown, |this| {
+ this.child(
+ // 左缘对齐到文字轴:行内边距 + 图标 17 + 间距 12
+ v_flex()
+ .ml(SPACE_LG + px(17.) + SPACE_MD)
+ .mr(SPACE_LG)
+ .mb(SPACE_MD)
+ .px(SPACE_MD)
+ .py(SPACE_SM)
+ .rounded(theme.radius)
+ .bg(theme.secondary)
+ .font_family(mono.clone())
+ .text_size(FONT_CAPTION)
+ .text_color(theme.foreground)
+ .children(lines),
+ )
+ })
+ .into_any_element()
+ })
+ .collect();
+
+ let copy_path = self.copy_button(
+ "connect-copy-path".into(),
+ "Copy path",
+ info.bin_path.clone(),
+ cx,
+ );
+ let mut details = vec![div()
+ .w_full()
+ .truncate()
+ .text_size(FONT_CAPTION)
+ .font_family(mono.clone())
+ .text_color(theme.muted_foreground)
+ .child(info.bin_display.clone())
+ .into_any_element()];
+ if !info.bin_exists {
+ details.push(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.danger)
+ .child("Not found next to the Wake app — reinstall Wake, or build it with `cargo build -p wake-core --bin wake-mcp`")
+ .into_any_element(),
+ );
+ }
+
+ let section = |label: &'static str| {
+ div()
+ .flex_shrink_0()
+ .text_size(FONT_CAPTION)
+ .font_semibold()
+ .text_color(theme.foreground)
+ .child(label)
+ };
+ let guide = div()
+ .id("connect-setup-guide")
+ .cursor_pointer()
+ .flex_shrink_0()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.primary)
+ .on_click(|_, _, cx| cx.open_url(CONNECT_GUIDE_URL))
+ .child("Setup guide");
+
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .h_full()
+ .bg(theme.background)
+ .child(settings_page_header(
+ "Connect",
+ "Let your coding agents look up your past sessions from Wake.",
+ cx,
+ ))
.child(
v_flex()
+ .id("settings-connect-scroll")
+ .flex_1()
+ .min_h_0()
+ .overflow_y_scroll()
.px(SPACE_XXL)
+ .pb(SPACE_XXL)
.gap(SPACE_SM)
- .child(
- div()
- .text_size(FONT_CAPTION)
- .font_semibold()
- .text_color(theme.foreground)
- .child("Storage"),
- )
+ .child(section("MCP server"))
+ .child(settings_info_card(
+ "wake-mcp",
+ details,
+ copy_path.into_any_element(),
+ cx,
+ ))
+ .child(section("Agents").pt(SPACE_LG))
.child(
v_flex()
.w_full()
+ .flex_shrink_0()
.overflow_hidden()
.rounded(theme.radius_lg)
.border_1()
.border_color(theme.border)
.bg(theme.popover)
+ .children(agent_rows),
+ )
+ .child(
+ h_flex()
+ .flex_shrink_0()
+ .pt(SPACE_SM)
+ .gap(SPACE_SM)
+ .items_center()
.child(
- h_flex()
- .min_h(px(84.))
- .px(SPACE_LG)
- .gap(SPACE_LG)
- .items_center()
- .child(
- v_flex()
- .flex_1()
- .min_w_0()
- .gap(px(3.))
- .child(
- div()
- .text_size(FONT_BODY)
- .text_color(theme.foreground)
- .child("Wake data"),
- )
- .child(
- div()
- .w_full()
- .truncate()
- .text_size(FONT_CAPTION)
- .text_color(theme.muted_foreground)
- .child(snapshot.display_path),
- )
- .child(
- div()
- .text_size(FONT_CAPTION)
- .text_color(theme.muted_foreground)
- .child(summary),
- ),
- )
- .child(show_in_finder),
- ),
+ div()
+ .flex_1()
+ .min_w_0()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child("Agents get four read-only tools: search, recent sessions, transcripts, projects."),
+ )
+ .child(guide),
),
)
.into_any_element()
@@ -1196,6 +1490,9 @@ impl SettingsView {
this.child(
v_flex()
.w_full()
+ // 同 Connect 页:overflow_hidden 的卡在滚动列里 min-height
+ // 视为 0,host 一多会被压扁裁切而不是滚动
+ .flex_shrink_0()
.overflow_hidden()
.rounded(theme.radius_lg)
.border_1()
@@ -1233,6 +1530,7 @@ impl Render for SettingsView {
SettingsPage::General => self.render_general(cx),
SettingsPage::Locations => self.render_locations(cx).into_any_element(),
SettingsPage::Remotes => self.render_remotes(cx),
+ SettingsPage::Connect => self.render_connect(cx),
SettingsPage::Data => self.render_data(cx),
SettingsPage::Updates => self.render_updates(cx),
SettingsPage::About => self.render_about(cx),
diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rs
index d3a3536..ddea05d 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -271,7 +271,9 @@ fn build_row_groups_at(
fn same_session_query(left: &SessionFilter, right: &SessionFilter) -> bool {
left.agents == right.agents
- && left.project_path == right.project_path
+ && left.project_paths == right.project_paths
+ && left.updated_since == right.updated_since
+ && left.ignore_pins == right.ignore_pins
&& left.favorite_only == right.favorite_only
&& left.include_archived == right.include_archived
&& left.roots_only == right.roots_only
@@ -282,10 +284,10 @@ fn same_session_query(left: &SessionFilter, right: &SessionFilter) -> bool {
fn session_matches_filter(session: &SessionMeta, filter: &SessionFilter) -> bool {
(filter.agents.is_empty() || filter.agents.contains(&session.agent))
+ && (filter.project_paths.is_empty() || filter.project_paths.contains(&session.project_path))
&& filter
- .project_path
- .as_ref()
- .is_none_or(|project| project == &session.project_path)
+ .updated_since
+ .is_none_or(|since| session.updated_at >= since)
&& (!filter.favorite_only || session.favorite)
&& (filter.include_archived || !session.archived)
&& filter
@@ -2372,7 +2374,6 @@ impl Workbench {
fn current_filter(&self) -> SessionFilter {
SessionFilter {
agents: self.selected_agent.into_iter().collect(),
- project_path: self.selected_project.clone(),
favorite_only: self.favorite_only,
include_archived: false,
roots_only: !self.favorite_only,
@@ -2381,6 +2382,9 @@ impl Workbench {
ascending: self.sort_ascending,
limit: SESSION_PAGE_SIZE,
offset: 0,
+ updated_since: None,
+ project_paths: self.selected_project.clone().into_iter().collect(),
+ ignore_pins: false,
}
}
@@ -2434,7 +2438,7 @@ impl Workbench {
// (HashMap 迭代无序),每次刷新侧栏顺序都会跳
counts.sort_by_key(|&(a, _)| a);
self.agent_counts = counts;
- self.projects = self.store.list_projects().unwrap_or_default();
+ self.projects = self.store.list_projects(false).unwrap_or_default();
self.starred_count = self.store.starred_count().unwrap_or(0);
// Insights 打开着就顺带重算:扫描增量/收藏变更等一切走 refresh 的
// 路径都会让页面数据跟上,不设第二条失效通道
@@ -2602,10 +2606,15 @@ impl Workbench {
display_path: tilde_path(&raw).into(),
raw_path: raw.into(),
size_bytes,
- session_count: self.agent_counts.iter().map(|(_, count)| count).sum(),
+ session_count: self.session_total(),
}
}
+ /// 库内会话总数(各 agent 计数之和;侧栏 All Sessions、Data / Connect 页共用)
+ pub(crate) fn session_total(&self) -> i64 {
+ self.agent_counts.iter().map(|(_, n)| n).sum()
+ }
+
pub(crate) fn settings_page(&self) -> SettingsPage {
self.settings_page
}
@@ -4828,7 +4837,7 @@ impl Workbench {
"all",
RowLead::Icon(icon("icons/layers.svg")),
"All Sessions",
- Some(self.agent_counts.iter().map(|(_, n)| n).sum()),
+ Some(self.session_total()),
all_active,
RowLevel::Primary,
cx.listener(|this, _, window, cx| {
@@ -5006,7 +5015,7 @@ impl Workbench {
fn render_session_list(&self, cx: &Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let shown = self.list_state.read(cx).delegate().rows.len();
- let library_empty = self.agent_counts.iter().map(|(_, n)| *n).sum::<i64>() == 0;
+ let library_empty = self.session_total() == 0;
let listed_count = self.total_sessions.max(0);
let shown_label: SharedString = format!(
"{} {}",
diff --git a/scripts/make-app.sh b/scripts/make-app.sh
index c098ce1..b04011f 100755
--- a/scripts/make-app.sh
+++ b/scripts/make-app.sh
@@ -35,24 +35,37 @@ iconutil -c icns "$ICONSET" -o dist/wake.icns
# 2. release 构建。Universal 模式在同一 macOS SDK 上交叉编译两个 Rust
# target,再用 lipo 合并;目标标准库由调用方预先通过 rustup 安装。
+# 发行二进制清单:主程序 Wake + 并排的辅助可执行文件(只读 MCP server
+# wake-mcp,Settings → Connect 按同目录找它)。两者 cargo 包不同,构建各写一行;
+# lipo / 拷贝 / 签名 / 架构核对按清单循环,再加一个辅助 bin 只改 SIDE_BINS
+SIDE_BINS=(wake-mcp)
+BINS=(Wake "${SIDE_BINS[@]}")
+build_bins() {
+ cargo build --release -p wake "$@"
+ cargo build --release -p wake-core --bin wake-mcp "$@"
+}
if $UNIVERSAL; then
ARM_TARGET=aarch64-apple-darwin
INTEL_TARGET=x86_64-apple-darwin
- cargo build --release -p wake --target "$ARM_TARGET"
- cargo build --release -p wake --target "$INTEL_TARGET"
+ build_bins --target "$ARM_TARGET"
+ build_bins --target "$INTEL_TARGET"
mkdir -p "$BUILD"
- lipo -create \
- "$TARGET_DIR/$ARM_TARGET/release/Wake" \
- "$TARGET_DIR/$INTEL_TARGET/release/Wake" \
- -output "$BUILD/Wake"
+ for bin in "${BINS[@]}"; do
+ lipo -create \
+ "$TARGET_DIR/$ARM_TARGET/release/$bin" \
+ "$TARGET_DIR/$INTEL_TARGET/release/$bin" \
+ -output "$BUILD/$bin"
+ done
else
- cargo build --release -p wake
+ build_bins
fi
# 3. bundle 组装
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
-cp "$BUILD/Wake" "$APP/Contents/MacOS/Wake"
+for bin in "${BINS[@]}"; do
+ cp "$BUILD/$bin" "$APP/Contents/MacOS/$bin"
+done
cp dist/wake.icns "$APP/Contents/Resources/wake.icns"
# 版本号从 workspace Cargo.toml 单一来源读取,勿在此硬编码
VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
@@ -81,17 +94,27 @@ cat > "$APP/Contents/Info.plist" <<PLIST
</plist>
PLIST
-# 4. ad-hoc 签名(本机运行足够;分发需开发者证书 + notarize)
+# 4. ad-hoc 签名(本机运行足够;分发需开发者证书 + notarize)。--deep 只递归
+# 标准嵌套位置(Frameworks/PlugIns/XPCServices…),MacOS/ 里并排的辅助可执行
+# 文件不算,先单独签它们,否则 Gatekeeper 会拦 MCP 客户端起的 wake-mcp
+for bin in "${SIDE_BINS[@]}"; do
+ codesign --force -s - "$APP/Contents/MacOS/$bin"
+done
codesign --force --deep -s - "$APP"
codesign --verify --deep --strict "$APP"
+for bin in "${SIDE_BINS[@]}"; do
+ codesign --verify --strict "$APP/Contents/MacOS/$bin"
+done
if $UNIVERSAL; then
- ARCHS=$(lipo -archs "$APP/Contents/MacOS/Wake")
- if [[ "$ARCHS" != *arm64* || "$ARCHS" != *x86_64* ]]; then
- echo "Universal build is missing an architecture: $ARCHS" >&2
- exit 1
- fi
- echo "✓ architectures: $ARCHS"
+ for bin in "${BINS[@]}"; do
+ ARCHS=$(lipo -archs "$APP/Contents/MacOS/$bin")
+ if [[ "$ARCHS" != *arm64* || "$ARCHS" != *x86_64* ]]; then
+ echo "Universal build of $bin is missing an architecture: $ARCHS" >&2
+ exit 1
+ fi
+ echo "✓ $bin architectures: $ARCHS"
+ done
fi
echo "✓ $APP"
diff --git a/scripts/make-linux.sh b/scripts/make-linux.sh
index adf3aea..326e475 100755
--- a/scripts/make-linux.sh
+++ b/scripts/make-linux.sh
@@ -14,10 +14,13 @@ ARCH=$(dpkg --print-architecture 2>/dev/null || uname -m)
# 1. release 构建(二进制名 Wake 来自 [[bin]],macOS 菜单栏需要;
# Linux 装成小写 wake,CLI 惯例)
cargo build --release -p wake
+cargo build --release -p wake-core --bin wake-mcp
STAGE=$(mktemp -d)/wake-${VERSION}-linux-${ARCH}
mkdir -p "$STAGE"
cp "$TARGET_DIR/release/Wake" "$STAGE/wake"
+# 只读 MCP server,装在主程序旁边(Settings → Connect 按同目录找它)
+cp "$TARGET_DIR/release/wake-mcp" "$STAGE/wake-mcp"
cp "$ASSETS/icon.svg" "$STAGE/wake.svg"
# 2. .desktop(StartupWMClass 对齐 main.rs 的 app_id = "wake")
@@ -39,6 +42,7 @@ cat > "$STAGE/install.sh" <<'INSTALL'
set -euo pipefail
cd "$(dirname "$0")"
install -Dm755 wake "$HOME/.local/bin/wake"
+install -Dm755 wake-mcp "$HOME/.local/bin/wake-mcp"
# 桌面项写绝对路径:~/.local/bin 若是本次新建的,图形会话的 PATH 里还没有它,
# Exec=wake 会找不到程序直到重新登录(deb 装 /usr/bin 不受此累,保持裸名)
sed "s|^Exec=wake$|Exec=\"$HOME/.local/bin/wake\"|" wake.desktop \
@@ -59,6 +63,7 @@ if command -v dpkg-deb >/dev/null; then
DEB=$(mktemp -d)/wake_deb
mkdir -p "$DEB/DEBIAN"
install -Dm755 "$STAGE/wake" "$DEB/usr/bin/wake"
+ install -Dm755 "$STAGE/wake-mcp" "$DEB/usr/bin/wake-mcp"
install -Dm644 "$STAGE/wake.desktop" "$DEB/usr/share/applications/wake.desktop"
install -Dm644 "$STAGE/wake.svg" "$DEB/usr/share/icons/hicolor/scalable/apps/wake.svg"
cat > "$DEB/DEBIAN/control" <<CONTROL
diff --git a/scripts/make-windows.ps1 b/scripts/make-windows.ps1
index 01d124e..d3420e1 100644
--- a/scripts/make-windows.ps1
+++ b/scripts/make-windows.ps1
@@ -20,6 +20,8 @@ $targetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { "target
cargo build --release -p wake
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+cargo build --release -p wake-core --bin wake-mcp
+if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# 二进制名 Wake.exe 来自 [[bin]](macOS 菜单栏取进程名所需);Windows 惯例
# 首字母大写正好同形,不再改名
@@ -27,6 +29,8 @@ $stage = Join-Path ([System.IO.Path]::GetTempPath()) "wake-stage\wake-$version-w
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
New-Item -ItemType Directory -Path $stage -Force | Out-Null
Copy-Item (Join-Path $targetDir "release/Wake.exe") (Join-Path $stage "Wake.exe")
+# 只读 MCP server,与主程序并排(Settings → Connect 按同目录找它)
+Copy-Item (Join-Path $targetDir "release/wake-mcp.exe") (Join-Path $stage "wake-mcp.exe")
New-Item -ItemType Directory -Path dist -Force | Out-Null
$zip = "dist/wake-$version-windows-$arch.zip"
diff --git a/scripts/test.sh b/scripts/test.sh
index 433d1e9..d673fd4 100755
--- a/scripts/test.sh
+++ b/scripts/test.sh
@@ -7,7 +7,7 @@
set -euo pipefail
cd "$(dirname "$0")/.."
-echo "── cargo test -p wake-core(adapter 契约 / seq 一致性 / FTS / 扫描终态)"
+echo "── cargo test -p wake-core(adapter 契约 / seq 一致性 / FTS / 扫描终态 / wake-mcp stdio)"
cargo test -p wake-core --quiet
echo "── cargo test -p wake(UI 单元逻辑;联网测试默认忽略)"