Skip to content

armgit / Wake

Public Imported from GitHub
0

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

Rust

refactor: simplify the dsh subagent, sessions_in and sidebar changes

Corey Chiub5a2122d5892
diff --git a/DESIGN.md b/DESIGN.md
index d9b3ac6..984e3ec 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -101,7 +101,7 @@ Wake 的目标不是展示技术感,而是让用户在几秒内重新找到并
| 元素 | 常量 | 值 | 推导 |
|---|---|---:|---|
| 容器内边距 | `SIDEBAR_EDGE` | 10 | 行 hover/选中胶囊的左右留白 |
-| 行首槽位 | `LEAD_BOX` | 18 | 最大前导元素(品牌图)尺寸,槽内**居中** |
+| 行首槽位 | `LEAD_BOX` | 18 | 最大前导元素(品牌图)尺寸,槽内**居中**;槽位一律经 `ui::lead_slot(宽, 内容)` 建(侧栏行、设置窗导航、底部状态行),宽度与传给 `axis_inset` 的那个值成对 |
| 行左内边距 | `LEAD_INSET` | 7.75 | 26.75 − 9(槽位半宽) − 10 |
| 组头(Agents / Projects) | `axis_inset(NAV_ICON, SIDEBAR_EDGE)` | 9.25 | 15px 折叠 chevron 按自己的框居中压轴,不占 18px 槽位(2026-09-22 起;原先靠首字母字形宽度反推 `GROUP_HEAD_INSET` = 12.125,已删) |
| 标题 | `sidebar_title(…)` | 现量 | 首字字宽(advance)的一半压轴,字号字重就是标题自己的:主窗 "Wake" / "Memory"、设置窗 "Settings" 共用,换页、换语言都对得上(2026-10-11 起;原先按 "Wake" 的 W 写死 `TITLE_INSET` = 9,Memory 页与设置窗标题都偏) |
diff --git a/crates/wake-core/src/adapters/dsh.rs b/crates/wake-core/src/adapters/dsh.rs
index b88c042..df86ab0 100644
--- a/crates/wake-core/src/adapters/dsh.rs
+++ b/crates/wake-core/src/adapters/dsh.rs
@@ -6,7 +6,7 @@ use std::collections::HashMap;
use std::fs;
use std::io::{BufRead, BufReader, ErrorKind};
use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex};
+use std::sync::Mutex;
/// DeepSeek Harness(dsh):`~/.dsh/sessions/--<cwd转义>--/<id转义>/<日志>`,一目录一会话。
/// 日志文件名带**格式代数**:v0 是 `session.jsonl[.zstd]`,之后每代 `session.vN.jsonl[.zstd]`
@@ -25,10 +25,11 @@ use std::sync::{Arc, Mutex};
/// 事件 last-wins 给标题,model 在 assistant 消息的 source 里。
pub struct DshAdapter {
root: PathBuf,
- /// 会话目录 → 最近一次读出来的(日志引用, 首行)。列表、file_ref 与每批监听都问的 parent_links
- /// 都要每个会话的首行:同一份日志((mtime, size) 没变)不再解压;目录或日志一时读不出(权限、
- /// 锁)交回上次读到的——首行写下就不变,迁移出新一代也是同一个 id / parentSession
- logs: Mutex<HashMap<PathBuf, (SessionFileRef, Arc<DshHeader>)>>,
+ /// 会话目录 → 最近一次读出来的(日志引用, 父会话 id)。列表、file_ref 与每批监听都问的
+ /// parent_links 都要首行里的 id 与 parentSession:首行写下就不变,迁移出的新一代也是同一个
+ /// id / parentSession,所以每个目录只解压一次,之后只 stat 选代;目录一时列不出(权限、锁)
+ /// 交回上次读到的
+ logs: Mutex<HashMap<PathBuf, (SessionFileRef, Option<String>)>>,
}
impl DshAdapter {
@@ -67,7 +68,7 @@ impl DshAdapter {
Some(dirs)
}
- /// 会话目录 → (被读的那一代日志的引用, 它的首行)。日志取 dsh 自己会读的那一份:编号最大的
+ /// 会话目录 → (被读的那一代日志的引用, 父会话 id)。日志取 dsh 自己会读的那一份:编号最大的
/// 一代(迁移只新增、不删旧代,旧代的 mtime 可能更新);同一代压缩与明文并存(换过
/// compression 配置)时 mtime 新者胜、平局 .zstd 胜。list、watcher(经 file_ref)与
/// parent_links 共用这一处裁决——只做在 list 会让 watcher 把旧代的事件当主文件解析。首行
@@ -75,53 +76,45 @@ impl DshAdapter {
/// header);目录列不出、日志打不开(权限、锁)交回上次读到的(见 `logs`),没读到过才报错——
/// parent_links 据此整份交 None。把读不出当成没有,parent_links 会交出缺一截的关系:A 派 B、
/// B 派 C,B 一时读不出,C 就从 A 下面挪到 B 下面(2026-10-11 Codex review)
- fn session_log(&self, dir: &Path) -> std::io::Result<Option<(SessionFileRef, Arc<DshHeader>)>> {
+ fn session_log(&self, dir: &Path) -> std::io::Result<Option<(SessionFileRef, Option<String>)>> {
let last = self.logs.lock().unwrap().get(dir).cloned();
- let unreadable = |e: std::io::Error| last.clone().map(Some).ok_or(e);
let entries = match fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
- Err(e) => return unreadable(e),
+ Err(e) => return last.map(Some).ok_or(e),
};
let Some(((_, mtime, _), path, size)) = entries
.flatten()
.filter_map(|entry| {
let (generation, zstd) = log_generation(&entry.file_name().to_string_lossy())?;
let path = entry.path();
- // fs::metadata 跟随符号链接(DirEntry::metadata 不跟)
- let meta = fs::metadata(&path)
- .ok()
- .filter(|m| m.is_file() && m.len() > 0)?;
- Some(((generation, mtime_ms(&meta), zstd), path, meta.len() as i64))
+ let (mtime, size) = stat_stamp(&path).filter(|(_, size)| *size > 0)?;
+ Some(((generation, mtime, zstd), path, size))
})
.max_by_key(|(rank, ..)| *rank)
else {
return Ok(None);
};
- let file_path = path.to_string_lossy().to_string();
- if let Some((r, _)) = &last {
- if r.file_path == file_path && r.mtime_ms == mtime && r.size == size {
- return Ok(last);
- }
- }
- // 解压不持锁
- let header = match read_header(&path) {
- Ok(Some(header)) => Arc::new(header),
- Ok(None) => return Ok(None),
- Err(e) => return unreadable(e),
+ let (native_id, parent) = match last {
+ Some((r, parent)) => (r.native_id, parent),
+ // 解压不持锁
+ None => match read_header(&path)? {
+ Some(header) => (header.id, header.parent),
+ None => return Ok(None),
+ },
};
let r = SessionFileRef {
agent: AgentId::Dsh,
- native_id: header.id.clone(),
- file_path,
+ native_id,
+ file_path: path.to_string_lossy().into_owned(),
mtime_ms: mtime,
size,
};
self.logs
.lock()
.unwrap()
- .insert(dir.to_path_buf(), (r.clone(), header.clone()));
- Ok(Some((r, header)))
+ .insert(dir.to_path_buf(), (r.clone(), parent.clone()));
+ Ok(Some((r, parent)))
}
}
@@ -147,6 +140,9 @@ struct DshHeader {
/// v0 / v1 的 fork 截点:首行的 seedLength,seq 小于它的事件是从父会话复制来的(上游 v1→v2
/// 迁移同一判法,且要带 parentSession);v2 起换成 `session/end-seed {inherited: true}` 标记
seed_length: Option<i64>,
+ /// 开头带着从父会话复制来的一段:v2 起首行的 isSeeded(上游保证这种会话一定有那个截点标记,
+ /// 继承段是空的也补一个),v0 / v1 有 seedLength
+ seeded: bool,
}
fn parse_header(v: &serde_json::Value) -> Option<DshHeader> {
@@ -159,10 +155,7 @@ fn parse_header(v: &serde_json::Value) -> Option<DshHeader> {
.and_then(|d| d.as_i64())
.unwrap_or(0)
> 0;
- let forked_from = v
- .get("parentSession")
- .and_then(|p| p.as_str())
- .filter(|p| !p.is_empty() && *p != id);
+ let forked_from = text_at(v, "parentSession").filter(|p| *p != id);
let parent = forked_from.filter(|_| subagent).map(String::from);
let seed_length = forked_from
.and(v.get("seedLength"))
@@ -175,6 +168,7 @@ fn parse_header(v: &serde_json::Value) -> Option<DshHeader> {
.unwrap_or_default()
.to_string(),
created_at: v.get("createdAt").and_then(|t| t.as_i64()).unwrap_or(0),
+ seeded: true_at(v, "isSeeded") || seed_length.is_some(),
id,
parent,
seed_length,
@@ -323,6 +317,11 @@ impl DshParse {
self.model = None;
self.tokens_used = None;
}
+
+ /// 还在从父会话复制来的那段里(收尾要折掉):里面的图片不必解码,也别占掉会话自己的解码额度
+ fn in_seed(&self) -> bool {
+ self.inherited.is_none() && self.header.as_ref().is_some_and(|h| h.seeded)
+ }
}
fn parse_dsh_log(path: &Path, decode_images: bool) -> Result<DshParse> {
@@ -380,6 +379,7 @@ fn parse_dsh_log(path: &Path, decode_images: bool) -> Result<DshParse> {
if p.inherited.is_none() && seed_length.is_some_and(|n| seq.is_some_and(|seq| seq >= n)) {
p.cut();
}
+ let decode = decode_images && !p.in_seed();
match ty {
"session" => {
if row
@@ -410,7 +410,7 @@ fn parse_dsh_log(path: &Path, decode_images: bool) -> Result<DshParse> {
"user/message" => {
let parsed = content_parts(
data.get("content").unwrap_or(&serde_json::Value::Null),
- decode_images,
+ decode,
);
if parsed.text.is_empty() && parsed.images.is_empty() {
continue;
@@ -458,7 +458,7 @@ fn parse_dsh_log(path: &Path, decode_images: bool) -> Result<DshParse> {
tools.push(tool_call_view(id.to_string(), name, &input, None, false));
}
_ if is_image_part(b) => {
- let parsed = content_parts(b, decode_images);
+ let parsed = content_parts(b, decode);
parsed_message.append(parsed);
}
_ => {}
@@ -536,7 +536,7 @@ fn parse_dsh_log(path: &Path, decode_images: bool) -> Result<DshParse> {
if let Some(&(mi, ti)) = tool_index.get(call_id) {
let parsed = content_parts(
block.get("content").unwrap_or(&serde_json::Value::Null),
- decode_images,
+ decode,
);
let message = &mut p.messages[mi];
let tc = &mut message.tool_calls[ti];
@@ -554,27 +554,19 @@ fn parse_dsh_log(path: &Path, decode_images: bool) -> Result<DshParse> {
// v2 起的 fork 截点(dsh-session fork.ts 的 buildForkSeed;最后一个带 inherited 的
// 才是本会话的——嵌套 fork 里祖先的标记也在复制来的那段里)
"session/end-seed" => {
- if data.get("inherited").and_then(|v| v.as_bool()) == Some(true) {
+ if true_at(data, "inherited") {
p.cut();
}
}
// 子代理在第一个回合里记下的身份;上游按截点之后的第一个算
"subagent/descriptor" => {
if p.label.is_none() {
- p.label = data
- .get("label")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|label| !label.is_empty())
- .map(clean_title_candidate);
+ p.label = text_at(data, "label").map(clean_title_candidate);
}
}
"session/title" => {
- if let Some(t) = data.get("title").and_then(|v| v.as_str()) {
- let t = t.trim();
- if !t.is_empty() {
- p.title = Some(clean_title_candidate(t));
- }
+ if let Some(t) = text_at(data, "title") {
+ p.title = Some(clean_title_candidate(t));
}
}
"request/context" => {
@@ -648,7 +640,6 @@ impl AgentAdapter for DshAdapter {
}
fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {
- // 根不在是空;在却列不出报错,scanner 把这一家这一轮冻结住
let dirs = self
.session_dirs()
.ok_or_else(|| anyhow!("cannot list {}", self.root.display()))?;
@@ -689,19 +680,23 @@ impl AgentAdapter for DshAdapter {
true
}
- /// 子代理会话首行里的 parentSession。每批监听事件都会问:列目录、每个会话 stat 一次日志,
- /// 首行读过的用缓存;没入库的会话 scanner 自己会丢掉。目录列不出、某个会话读不出又没读到过,
- /// 都给 None,库里的关系原样保留
+ /// 子代理会话首行里的 parentSession。每批监听事件都会问:只列目录,读到过的会话直接用缓存
+ /// (首行不变),新目录才进去读;没入库的会话 scanner 自己会丢掉。目录列不出、某个会话读不出
+ /// 又没读到过,都给 None,库里的关系原样保留
fn parent_links(&self) -> Option<Vec<(String, String)>> {
let key = |id: &str| session_key(AgentId::Dsh, "", id);
let mut links = Vec::new();
for dir in self.session_dirs()? {
- // 读不出又没读到过:不知道,库里的关系这一轮原样保留
- let Some((_, header)) = self.session_log(&dir).ok()? else {
+ let known = self.logs.lock().unwrap().get(&dir).cloned();
+ let entry = match known {
+ Some(known) => Some(known),
+ None => self.session_log(&dir).ok()?,
+ };
+ let Some((r, parent)) = entry else {
continue;
};
- if let Some(parent) = header.parent.as_deref() {
- links.push((key(&header.id), key(parent)));
+ if let Some(parent) = parent {
+ links.push((key(&r.native_id), key(&parent)));
}
}
Some(links)
@@ -760,71 +755,68 @@ impl AgentAdapter for DshAdapter {
#[cfg(test)]
mod tests {
- use super::{log_generation, parse_dsh_log, parse_header, DshAdapter};
+ use super::{log_generation, parse_dsh_log, parse_header, DshAdapter, DshHeader, DshParse};
use crate::adapters::AgentAdapter;
- use crate::models::{MessageKind, Role};
+ use crate::models::{MessageKind, Role, TranscriptMessage};
+
+ /// 首行再加几个字段(`extra` 是接在 createdAt 后面的 JSON 片段)
+ fn header(extra: &str) -> DshHeader {
+ let line = format!(r#"{{"type":"session","version":4,"id":"c1","createdAt":1{extra}}}"#);
+ parse_header(&serde_json::from_str(&line).unwrap()).unwrap()
+ }
+
+ /// 几行日志写进临时文件再解析
+ fn parsed(lines: &[&str], decode_images: bool) -> DshParse {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("session.v4.jsonl");
+ std::fs::write(&path, lines.join("\n")).unwrap();
+ parse_dsh_log(&path, decode_images).unwrap()
+ }
+
+ fn texts(messages: &[TranscriptMessage]) -> Vec<(Role, MessageKind, &str)> {
+ messages
+ .iter()
+ .map(|m| (m.role, m.kind, m.text.as_str()))
+ .collect()
+ }
/// 只有子代理挂到父会话下;用户自己 fork 出来的会话也写 parentSession,是独立的对话
#[test]
fn only_subagents_hang_under_their_parent() {
- let parent = |header: serde_json::Value| parse_header(&header).unwrap().parent;
- let base = |extra: serde_json::Value| {
- let mut header =
- serde_json::json!({"type": "session", "version": 4, "id": "c1", "createdAt": 1});
- header
- .as_object_mut()
- .unwrap()
- .extend(extra.as_object().unwrap().clone());
- header
- };
+ let parent = |extra: &str| header(extra).parent;
assert_eq!(
- parent(base(
- serde_json::json!({"origin": "subagent", "delegationDepth": 1, "parentSession": "p1"})
- )),
+ parent(r#","origin":"subagent","delegationDepth":1,"parentSession":"p1""#),
Some("p1".to_string())
);
assert_eq!(
- parent(base(
- serde_json::json!({"delegationDepth": 2, "parentSession": "p1"})
- )),
+ parent(r#","delegationDepth":2,"parentSession":"p1""#),
Some("p1".to_string())
);
assert_eq!(
- parent(base(
- serde_json::json!({"isSeeded": true, "delegationDepth": 0, "parentSession": "p1"})
- )),
- None
- );
- assert_eq!(
- parent(base(serde_json::json!({"origin": "subagent"}))),
+ parent(r#","isSeeded":true,"delegationDepth":0,"parentSession":"p1""#),
None
);
+ assert_eq!(parent(r#","origin":"subagent""#), None);
}
/// v0 / v1 没有截点标记(那时的 session/end-seed 不带 inherited):截点在首行的 seedLength,
/// seq 小于它的事件是复制来的;只认带 parentSession 的
#[test]
fn a_v0_fork_cuts_at_its_seed_length() {
- let dir = tempfile::tempdir().unwrap();
- let path = dir.path().join("session.jsonl");
- let lines = [
- r#"{"type":"session","version":0,"id":"sub0","createdAt":1,"cwd":"/w","origin":"subagent","delegationDepth":1,"parentSession":"p1","seedLength":3}"#,
- r#"{"type":"user/message","seq":0,"time":10,"data":{"content":[{"type":"text","text":"parent question"}],"source":{"kind":"user"}}}"#,
- r#"{"type":"assistant/message","seq":1,"time":20,"data":{"message":{"content":[{"type":"text","text":"parent answer"}],"source":{"model":"parent-model"}},"usage":{"inputTokens":900,"outputTokens":100}}}"#,
- r#"{"type":"session/title","seq":2,"time":21,"data":{"title":"Parent title"}}"#,
- r#"{"type":"session/end-seed","seq":3,"time":22,"data":{}}"#,
- r#"{"type":"user/message","seq":4,"time":30,"data":{"content":[{"type":"text","text":"child task"}],"source":{"kind":"user"}}}"#,
- r#"{"type":"assistant/message","seq":5,"time":40,"data":{"message":{"content":[{"type":"text","text":"child answer"}],"source":{"model":"child-model"}},"usage":{"inputTokens":40,"outputTokens":2}}}"#,
- ];
- std::fs::write(&path, lines.join("\n")).unwrap();
- let parsed = parse_dsh_log(&path, false).unwrap();
- let texts: Vec<(Role, MessageKind, &str)> = parsed
- .messages
- .iter()
- .map(|m| (m.role, m.kind, m.text.as_str()))
- .collect();
+ let parsed = parsed(
+ &[
+ r#"{"type":"session","version":0,"id":"sub0","createdAt":1,"cwd":"/w","origin":"subagent","delegationDepth":1,"parentSession":"p1","seedLength":3}"#,
+ r#"{"type":"user/message","seq":0,"time":10,"data":{"content":[{"type":"text","text":"parent question"}],"source":{"kind":"user"}}}"#,
+ r#"{"type":"assistant/message","seq":1,"time":20,"data":{"message":{"content":[{"type":"text","text":"parent answer"}],"source":{"model":"parent-model"}},"usage":{"inputTokens":900,"outputTokens":100}}}"#,
+ r#"{"type":"session/title","seq":2,"time":21,"data":{"title":"Parent title"}}"#,
+ r#"{"type":"session/end-seed","seq":3,"time":22,"data":{}}"#,
+ r#"{"type":"user/message","seq":4,"time":30,"data":{"content":[{"type":"text","text":"child task"}],"source":{"kind":"user"}}}"#,
+ r#"{"type":"assistant/message","seq":5,"time":40,"data":{"message":{"content":[{"type":"text","text":"child answer"}],"source":{"model":"child-model"}},"usage":{"inputTokens":40,"outputTokens":2}}}"#,
+ ],
+ false,
+ );
assert_eq!(
- texts,
+ texts(&parsed.messages),
vec![
(
Role::System,
@@ -844,14 +836,11 @@ mod tests {
);
// 没有 parentSession 的 seedLength 不作数(上游迁移同一判法)
- let header = |extra: &str| {
- let line = format!(r#"{{"type":"session","version":0,"id":"s","createdAt":1{extra}}}"#);
- parse_header(&serde_json::from_str(&line).unwrap())
- .unwrap()
- .seed_length
- };
- assert_eq!(header(r#","seedLength":3"#), None);
- assert_eq!(header(r#","seedLength":3,"parentSession":"p1""#), Some(3));
+ assert_eq!(header(r#","seedLength":3"#).seed_length, None);
+ assert_eq!(
+ header(r#","seedLength":3,"parentSession":"p1""#).seed_length,
+ Some(3)
+ );
}
/// 根目录在却列不出(权限):列表报错、parent_links 给 None——当成空的话,全量扫描会把会话
@@ -959,24 +948,18 @@ mod tests {
/// 截点后紧跟着的回复另起一条:并进复制来的最后一条回复,折叠时会被一起折掉
#[test]
fn a_reply_right_after_the_cut_is_its_own() {
- let dir = tempfile::tempdir().unwrap();
- let path = dir.path().join("session.v4.jsonl");
- let lines = [
- r#"{"type":"session","version":4,"id":"f1","createdAt":1,"isSeeded":true,"delegationDepth":0,"parentSession":"p1"}"#,
- r#"{"type":"user/message","seq":0,"time":10,"data":{"content":[{"type":"text","text":"parent question"}],"source":{"kind":"user"}}}"#,
- r#"{"type":"assistant/message","seq":1,"time":20,"data":{"message":{"content":[{"type":"text","text":"parent answer"}]}}}"#,
- r#"{"type":"session/end-seed","seq":2,"time":20,"data":{"inherited":true}}"#,
- r#"{"type":"assistant/message","seq":3,"time":30,"data":{"message":{"content":[{"type":"text","text":"the fork's own answer"}]}}}"#,
- ];
- std::fs::write(&path, lines.join("\n")).unwrap();
- let parsed = parse_dsh_log(&path, false).unwrap();
- let texts: Vec<(Role, MessageKind, &str)> = parsed
- .messages
- .iter()
- .map(|m| (m.role, m.kind, m.text.as_str()))
- .collect();
+ let parsed = parsed(
+ &[
+ r#"{"type":"session","version":4,"id":"f1","createdAt":1,"isSeeded":true,"delegationDepth":0,"parentSession":"p1"}"#,
+ r#"{"type":"user/message","seq":0,"time":10,"data":{"content":[{"type":"text","text":"parent question"}],"source":{"kind":"user"}}}"#,
+ r#"{"type":"assistant/message","seq":1,"time":20,"data":{"message":{"content":[{"type":"text","text":"parent answer"}]}}}"#,
+ r#"{"type":"session/end-seed","seq":2,"time":20,"data":{"inherited":true}}"#,
+ r#"{"type":"assistant/message","seq":3,"time":30,"data":{"message":{"content":[{"type":"text","text":"the fork's own answer"}]}}}"#,
+ ],
+ false,
+ );
assert_eq!(
- texts,
+ texts(&parsed.messages),
vec![
(
Role::System,
@@ -988,6 +971,29 @@ mod tests {
);
}
+ /// 复制来的那段里的图片不解码(收尾要折掉,还占会话自己的解码额度);截点之后照常解码
+ #[test]
+ fn images_after_the_cut_are_decoded() {
+ let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";
+ let user = |seq: u32| {
+ format!(
+ r#"{{"type":"user/message","seq":{seq},"time":{seq},"data":{{"content":[{{"type":"text","text":"look"}},{{"type":"image","media_type":"image/png","data":"{png}"}}],"source":{{"kind":"user"}}}}}}"#
+ )
+ };
+ let (inherited, own) = (user(0), user(2));
+ let parsed = parsed(
+ &[
+ r#"{"type":"session","version":4,"id":"f1","createdAt":1,"isSeeded":true,"parentSession":"p1"}"#,
+ &inherited,
+ r#"{"type":"session/end-seed","seq":1,"time":1,"data":{"inherited":true}}"#,
+ &own,
+ ],
+ true,
+ );
+ assert_eq!(parsed.messages.len(), 2);
+ assert_eq!(parsed.messages[1].images.len(), 1);
+ }
+
#[test]
fn log_names_carry_their_format_generation() {
assert_eq!(log_generation("session.jsonl"), Some((0, false)));
diff --git a/crates/wake-core/src/adapters/grok_bot.rs b/crates/wake-core/src/adapters/grok_bot.rs
index f4414e5..ffa5d2b 100644
--- a/crates/wake-core/src/adapters/grok_bot.rs
+++ b/crates/wake-core/src/adapters/grok_bot.rs
@@ -91,22 +91,19 @@ impl GrokBotAdapter {
/// 路径上那份文件存的是哪一种切片;别的存储文件、不是存储文件的都是 None。`.kblob` 的键在
/// 首行,读出来的记下:文件没了(删除事件)、一时读不出,照样认得出
fn slice_at(&self, path: &Path) -> Option<Slice> {
- let framed = path
- .file_name()
- .and_then(|name| name.to_str())
- .is_some_and(|name| name.ends_with(FRAMED));
- let slice = file_key(path).and_then(|key| slice_of(&key));
- if !framed {
- return slice;
+ if !is_framed(path) {
+ return file_key(path).and_then(|key| slice_of(&key));
}
- let mut seen = self.framed.lock().unwrap();
- match slice {
- Some(slice) => {
- seen.insert(path.to_path_buf(), slice.clone());
- Some(slice)
- }
- None => seen.get(path).cloned(),
+ // `.kblob` 的文件名就是它那个键的摘要:记下的键不会过时,不必每次打开文件
+ if let Some(slice) = self.framed.lock().unwrap().get(path) {
+ return Some(slice.clone());
}
+ let slice = file_key(path).and_then(|key| slice_of(&key))?;
+ self.framed
+ .lock()
+ .unwrap()
+ .insert(path.to_path_buf(), slice.clone());
+ Some(slice)
}
/// 一个账号的列表文件:键编码进文件名的直接算出来,只有编码后太长(`.kblob`)才列目录找——每个
@@ -133,7 +130,7 @@ impl GrokBotAdapter {
/// 不记这个版本,下次再读——记了的话错误过去之后 mtime / size 没变,连全量刷新都不会再读
/// (2026-10-11 Codex review);读出来却解不开(写坏了)才记,同一个版本不再白解析
fn roster(&self, path: &Path) -> Option<Arc<Roster>> {
- let Some(stamp) = file_stamp(path) else {
+ let Some(stamp) = stat_stamp(path) else {
self.rosters.lock().unwrap().remove(path);
return None;
};
@@ -235,7 +232,7 @@ fn file_key(path: &Path) -> Option<String> {
if let Some(stem) = name.strip_suffix(ENCODED) {
return String::from_utf8(base32_decode(stem)?).ok();
}
- if name.ends_with(FRAMED) {
+ if is_framed(path) {
let mut line = String::new();
BufReader::new(fs::File::open(path).ok()?)
.read_line(&mut line)
@@ -249,18 +246,16 @@ fn is_store_file(name: &str) -> bool {
name.ends_with(ENCODED) || name.ends_with(FRAMED)
}
-/// 文件里存的值(`.kblob` 跳过首行的键)
-fn read_value(path: &Path) -> Result<Value> {
- parse_value(path, &fs::read_to_string(path)?)
+/// 编码后太长、改存摘要名的 `.kblob`(首行是键)
+fn is_framed(path: &Path) -> bool {
+ path.file_name()
+ .and_then(|name| name.to_str())
+ .is_some_and(|name| name.ends_with(FRAMED))
}
-/// 读出来的文件内容 → 存的值
+/// 读出来的文件内容 → 存的值(`.kblob` 跳过首行的键)
fn parse_value(path: &Path, raw: &str) -> Result<Value> {
- let framed = path
- .file_name()
- .and_then(|name| name.to_str())
- .is_some_and(|name| name.ends_with(FRAMED));
- let body = if framed {
+ let body = if is_framed(path) {
raw.split_once('\n').map_or("", |(_, value)| value)
} else {
raw
@@ -268,11 +263,6 @@ fn parse_value(path: &Path, raw: &str) -> Result<Value> {
Ok(serde_json::from_str(body)?)
}
-fn file_stamp(path: &Path) -> Option<FileStamp> {
- let meta = fs::metadata(path).ok()?;
- meta.is_file().then(|| (mtime_ms(&meta), meta.len() as i64))
-}
-
/// 与会话有关的两种键。账号段原样保留(app 存的是 URI 编码过的账号,同一账号的副本与列表靠它配对)
#[derive(Debug, PartialEq, Clone)]
enum Slice {
@@ -382,7 +372,7 @@ fn parse_roster(v: &Value) -> Roster {
// ---------------------------------------------------------------- 引用与元数据
fn replica_ref(path: &Path, conversation: &str, row: Option<&Row>) -> Option<SessionFileRef> {
- let (mtime_ms, size) = file_stamp(path).filter(|(_, size)| *size > 0)?;
+ let (mtime_ms, size) = stat_stamp(path).filter(|(_, size)| *size > 0)?;
Some(SessionFileRef {
agent: AgentId::GrokBot,
native_id: conversation.to_string(),
@@ -495,7 +485,7 @@ struct Replica {
}
fn read_replica(path: &Path) -> Result<Replica> {
- replica(&read_value(path)?)
+ replica(&parse_value(path, &fs::read_to_string(path)?)?)
.ok_or_else(|| anyhow!("not a Grok Bot transcript: {}", path.display()))
}
@@ -767,13 +757,10 @@ fn name_of(v: Option<&Value>) -> Option<&str> {
/// `**标签**` 起头的一段:群聊里是谁说的、bot 之间的消息是发给谁的。正文是空的(流式中还没来
/// 内容的占位)整段给空,`push` 才滤得掉——只剩一个名字的消息不是消息(2026-10-11 Codex review)
fn labelled(label: &str, body: &str) -> String {
- if body.trim().is_empty() {
- return String::new();
+ match body.trim() {
+ "" => String::new(),
+ body => format!("**{label}**\n\n{body}"),
}
- let mut text = ParsedContent::default();
- text.push_text(&format!("**{label}**"));
- text.push_text(body);
- text.text
}
fn is_image_name(name: &str) -> bool {
diff --git a/crates/wake-core/src/adapters/parse_utils.rs b/crates/wake-core/src/adapters/parse_utils.rs
index 0d1f836..bd6b4a1 100644
--- a/crates/wake-core/src/adapters/parse_utils.rs
+++ b/crates/wake-core/src/adapters/parse_utils.rs
@@ -120,6 +120,12 @@ pub fn created_ms(meta: &std::fs::Metadata) -> Option<i64> {
meta.created().ok().and_then(system_time_ms)
}
+/// 文件的 (mtime 毫秒, 字节数),跟随符号链接;不是普通文件、读不到元数据给 None
+pub fn stat_stamp(path: &std::path::Path) -> Option<(i64, i64)> {
+ let meta = std::fs::metadata(path).ok()?;
+ meta.is_file().then(|| (mtime_ms(&meta), meta.len() as i64))
+}
+
fn system_time_ms(t: std::time::SystemTime) -> Option<i64> {
t.duration_since(std::time::UNIX_EPOCH)
.ok()
@@ -1286,10 +1292,6 @@ mod tests {
sidecar_fingerprint(&["ab", "c"]),
sidecar_fingerprint(&["a", "bc"])
);
- assert_eq!(
- sidecar_fingerprint(&["Ada", "hidden"]),
- sidecar_fingerprint(&["Ada", "hidden"])
- );
}
#[test]
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index 29965bf..55b7dcd 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -1216,14 +1216,17 @@ impl Store {
.optional()?)
}
- /// file_path 落在 `[from, to)` 里的会话路径。watcher 对账 `sessions_in` 时拿它取挂在一个文件
- /// 名下的虚拟路径(区间由 `sqlite_ro::virtual_path_bounds` 给)
- pub fn file_paths_in(&self, from: &str, to: &str) -> Result<Vec<String>> {
+ /// file_path 落在 `[from, to)` 里的会话 → 它们的变更戳 (file_mtime, file_size)。watcher 对账
+ /// `sessions_in` 时一次取齐挂在一个文件名下的虚拟路径(区间由 `sqlite_ro::virtual_path_bounds` 给)
+ pub fn file_stamps_in(&self, from: &str, to: &str) -> Result<HashMap<String, (i64, i64)>> {
let conn = self.read.lock().unwrap();
let mut stmt = conn.prepare_cached(
- "SELECT file_path FROM sessions WHERE file_path >= ?1 AND file_path < ?2",
+ "SELECT file_path, file_mtime, file_size FROM sessions
+ WHERE file_path >= ?1 AND file_path < ?2",
)?;
- let rows = stmt.query_map(params![from, to], |r| r.get(0))?;
+ let rows = stmt.query_map(params![from, to], |r| {
+ Ok((r.get(0)?, (r.get(1)?, r.get(2)?)))
+ })?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
diff --git a/crates/wake-core/src/scanner.rs b/crates/wake-core/src/scanner.rs
index 129b351..671f791 100644
--- a/crates/wake-core/src/scanner.rs
+++ b/crates/wake-core/src/scanner.rs
@@ -357,8 +357,8 @@ pub fn run_memory_sync(adapters: &[Box<dyn AgentAdapter>], store: &Arc<Store>) -
/// 写事务内副本裁决(`Store::write_session_guarded`)用的位次查询:按 file_path
/// 找拥有它的实例、问它这份副本的 `dedup_rank`;无实例认领的路径落到该家首个
/// 实例——与枚举时的候选排序同一把尺子,全量与增量两条写库路径才给出同一个胜者
-/// (watcher 预判一份副本值不值得交给 scan_files 也用它)
-pub(crate) fn rank_of<'a>(
+/// (`scan_files` 预判一份副本值不值得解析也用它)
+fn rank_of<'a>(
adapters: &'a [Box<dyn AgentAdapter>],
agent: crate::models::AgentId,
) -> impl Fn(&str) -> u8 + 'a {
@@ -1176,6 +1176,14 @@ pub fn scan_files(
if store.is_key_tombstoned(&key) || store.is_key_claimed(&key) {
continue;
}
+ // 同一会话已由位次严格更优的另一份副本代表着:写事务里的副本裁决必判它输,解析也省了
+ // (Grok Bot 的侧栏列表每变一次,有副本的对话的卡片都会来一遍)
+ if let Ok(Some(indexed)) = store.file_path_of(&key) {
+ let rank = rank_of(adapters, r.agent);
+ if indexed != r.file_path && rank(&indexed) < rank(&r.file_path) {
+ continue;
+ }
+ }
by_adapter.entry(ix).or_default().push(r);
}
diff --git a/crates/wake-core/src/watcher.rs b/crates/wake-core/src/watcher.rs
index 584843e..560bbf3 100644
--- a/crates/wake-core/src/watcher.rs
+++ b/crates/wake-core/src/watcher.rs
@@ -1,7 +1,7 @@
use crate::adapters::AgentAdapter;
use crate::db::Store;
use crate::models::*;
-use crate::scanner::{rank_of, refresh_claims, refresh_parent_links, scan_files, ScanEvents};
+use crate::scanner::{refresh_claims, refresh_parent_links, scan_files, ScanEvents};
use notify::{RecursiveMode, Watcher};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
@@ -195,39 +195,26 @@ pub(crate) fn process_batch(
let mut dropped: Vec<String> = Vec::new();
let every_path = present.iter().map(|(path, ix)| (path, *ix));
for (path, ix) in every_path.chain(vanished.iter().copied()) {
- let adapter = &adapters[ix];
- let Some(listed) = adapter.sessions_in(path) else {
+ let Some(listed) = adapters[ix].sessions_in(path) else {
continue;
};
- let rank = rank_of(adapters, adapter.agent());
let (from, to) = crate::adapters::sqlite_ro::virtual_path_bounds(path);
- let Ok(indexed) = store.file_paths_in(&from, &to) else {
+ let Ok(indexed) = store.file_stamps_in(&from, &to) else {
continue;
};
let still_there: HashSet<&str> = listed.iter().map(|r| r.file_path.as_str()).collect();
dropped.extend(
indexed
- .into_iter()
- .filter(|indexed| !still_there.contains(indexed.as_str())),
+ .keys()
+ .filter(|indexed| !still_there.contains(indexed.as_str()))
+ .cloned(),
);
+ // 没入库的也交出去:同一会话已由更优的副本代表着(Grok Bot 有副本的对话)时 scan_files
+ // 解析之前就跳过
dependents.extend(
listed
.into_iter()
- .filter(|r| match store.file_stamp(&r.file_path) {
- Ok(Some(stamp)) => stamp != (r.mtime_ms, r.size),
- // 没入库的:同一会话已由别的文件代表着、那一份的副本位次又严格更优(Grok Bot
- // 有副本的对话),交给 scan_files 也必败;同级的(两个 location 各一张卡片)
- // 交给写事务里的副本裁决按 mtime 定(2026-10-11 Codex review)
- Ok(None) => {
- let key = session_key(r.agent, adapter.host(), &r.native_id);
- match store.file_path_of(&key) {
- Ok(None) => true,
- Ok(Some(indexed)) => rank(&indexed) >= rank(&r.file_path),
- Err(_) => false,
- }
- }
- Err(_) => false,
- }),
+ .filter(|r| indexed.get(&r.file_path) != Some(&(r.mtime_ms, r.size))),
);
}
@@ -601,10 +588,6 @@ mod tests {
self.locations[location].join(crate::adapters::grok_bot::store_file_name(&key).unwrap())
}
- fn file(&self, slice: &str) -> PathBuf {
- self.file_in(0, slice)
- }
-
fn roster_in(&self, location: usize) -> PathBuf {
self.file_in(location, "roster.last-roster")
}
@@ -623,7 +606,7 @@ mod tests {
/// 一条副本,条目原样给
fn write_replica(&self, id: &str, entries: &str) -> PathBuf {
- let path = self.file(&format!("transcript.replicas.{id}"));
+ let path = self.file_in(0, &format!("transcript.replicas.{id}"));
let json = format!(
r#"{{"schemaVersion":1,"value":{{"entries":[{entries}],"persistedAt":1786000000000}}}}"#
);
diff --git a/crates/wake-core/tests/scanner_finale.rs b/crates/wake-core/tests/scanner_finale.rs
index bb1ec52..c6553dd 100644
--- a/crates/wake-core/tests/scanner_finale.rs
+++ b/crates/wake-core/tests/scanner_finale.rs
@@ -1509,19 +1509,18 @@ fn dsh_subagents_nest_under_the_session_that_started_them() {
use wake_core::adapters::dsh::DshAdapter;
let root = tempfile::tempdir().unwrap();
let project = root.path().join("--Users-tester-Github-wakefx--");
- for (dir, fixture) in [
- ("dsh-e2e4-0001", "dsh/session.jsonl"),
- ("dsh-sub-0002", "dsh/subagent.v4.jsonl"),
+ for (dir, fixture, log) in [
+ ("dsh-e2e4-0001", "dsh/session.jsonl", "session.jsonl.zstd"),
+ (
+ "dsh-sub-0002",
+ "dsh/subagent.v4.jsonl",
+ "session.v4.jsonl.zstd",
+ ),
] {
let session = project.join(dir);
std::fs::create_dir_all(&session).unwrap();
let plain = std::fs::read_to_string(common::fixture(fixture)).unwrap();
- let name = if fixture.ends_with(".v4.jsonl") {
- "session.v4.jsonl.zstd"
- } else {
- "session.jsonl.zstd"
- };
- std::fs::write(session.join(name), common::dsh_zstd(&plain)).unwrap();
+ std::fs::write(session.join(log), common::dsh_zstd(&plain)).unwrap();
}
let adapters: Vec<Box<dyn AgentAdapter>> =
vec![DshAdapter::new().with_custom_root(root.path().to_path_buf())];
diff --git a/crates/wake/src/settings.rs b/crates/wake/src/settings.rs
index b62e529..b38cc05 100644
--- a/crates/wake/src/settings.rs
+++ b/crates/wake/src/settings.rs
@@ -13,9 +13,10 @@ use wake_core::models::AgentId;
use crate::format::tilde_path;
use crate::ui::{
- action_button, axis_inset, overlay_layers, rails_factor, show_in_fm, sidebar_title, zpx, Zpx,
- BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY, FONT_LABEL, FONT_TITLE, ICON_TEXT_GAP,
- LEAD_BOX, NAV_ICON, RADIUS_BUTTON, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL, SPACE_XS, SPACE_XXL,
+ action_button, axis_inset, lead_slot, overlay_layers, rails_factor, show_in_fm, sidebar_title,
+ zpx, Zpx, BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY, FONT_LABEL, FONT_TITLE,
+ ICON_TEXT_GAP, LEAD_BOX, NAV_ICON, RADIUS_BUTTON, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL,
+ SPACE_XS, SPACE_XXL,
};
use crate::update::{self, UpdateStatus};
use crate::workbench::{
@@ -409,13 +410,7 @@ impl SettingsView {
.on_click(move |_, _, cx| {
workbench.update(cx, |this, cx| this.select_settings_page(page, cx));
})
- .child(
- h_flex()
- .w(LEAD_BOX)
- .flex_shrink_0()
- .justify_center()
- .child(icon(icon_path).with_size(NAV_ICON)),
- )
+ .child(lead_slot(LEAD_BOX, icon(icon_path).with_size(NAV_ICON)))
// 放大档位下侧栏可能比标签窄:单行截断,行高是定的,换成两行会压到下一项
.child(
div()
diff --git a/crates/wake/src/ui.rs b/crates/wake/src/ui.rs
index df556c6..56075d5 100644
--- a/crates/wake/src/ui.rs
+++ b/crates/wake/src/ui.rs
@@ -285,6 +285,15 @@ pub const NAV_ICON: Zpx = Zpx(15.);
pub const fn axis_inset(lead: Zpx, edge: Zpx) -> Zpx {
Zpx(LEAD_AXIS.0 - lead.0 / 2. - edge.0)
}
+/// 宽 `width` 的行首槽位,内容居中:比槽位小的图标中心也落在槽位中心上。槽位宽与传给
+/// `axis_inset` 的 `lead` 是一对——侧栏行、设置窗导航、底部状态行的行首都经它
+pub fn lead_slot(width: impl Into<Pixels>, child: impl IntoElement) -> Div {
+ h_flex()
+ .w(width.into())
+ .flex_shrink_0()
+ .justify_center()
+ .child(child)
+}
/// 行左内边距 = 26.75(轴) − 9(槽位半宽) − 10(SIDEBAR_EDGE,容器那一半)
pub const LEAD_INSET: Zpx = axis_inset(LEAD_BOX, SIDEBAR_EDGE);
/// 分组项(agent/项目)相对轴的右缩进,表达从属。
diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rs
index 9bc4c48..22444a2 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -5646,50 +5646,39 @@ impl Workbench {
};
bar.into_any_element()
});
- let status: Option<AnyElement> = if let Some(note) = note {
- let lead = if busy {
- div()
- .flex_shrink_0()
- .child(
- Spinner::new()
- .with_size(STATUS_LEAD)
- .color(theme.muted_foreground),
- )
- .into_any_element()
- } else {
+ let status = match note {
+ Some(note) if busy => Some((
+ Spinner::new()
+ .with_size(STATUS_LEAD)
+ .color(theme.muted_foreground)
+ .into_any_element(),
+ note,
+ )),
+ Some(note) => Some((
icon("icons/refresh-cw.svg")
.with_size(STATUS_LEAD)
- .flex_shrink_0()
- .into_any_element()
- };
- Some(
- h_flex()
- .w_full()
- .gap(ICON_TEXT_GAP)
- .text_color(theme.muted_foreground)
- .child(lead)
- .child(div().min_w_0().truncate().child(note))
.into_any_element(),
- )
- } else if self.watcher.is_none() {
- Some(
- h_flex()
- .w_full()
- .gap(ICON_TEXT_GAP)
- .text_color(theme.muted_foreground)
- .child(
- h_flex()
- .w(STATUS_LEAD)
- .flex_shrink_0()
- .justify_center()
- .child(div().size(zpx(7.)).rounded_full().bg(theme.warning)),
- )
- .child(div().min_w_0().truncate().child(t("Live updates off")))
+ note,
+ )),
+ None if self.watcher.is_none() => Some((
+ div()
+ .size(zpx(7.))
+ .rounded_full()
+ .bg(theme.warning)
.into_any_element(),
- )
- } else {
- None
- };
+ t("Live updates off").to_string(),
+ )),
+ None => None,
+ }
+ .map(|(lead, text)| {
+ h_flex()
+ .w_full()
+ .gap(ICON_TEXT_GAP)
+ .text_color(theme.muted_foreground)
+ .child(lead_slot(STATUS_LEAD, lead))
+ .child(div().min_w_0().truncate().child(text))
+ .into_any_element()
+ });
// macOS 恒挂 TitleBar(traffic light 占位 + 拖拽区);Linux/Windows 按
// 运行时装饰状态:系统给了标题栏(Server)就不挂——TitleBar 的非 mac
@@ -9603,7 +9592,8 @@ fn sidebar_footer_width() -> Pixels {
/// 工具条左内边距 = 26.75(侧栏中轴,红绿灯红灯中心)− 14(按钮半宽),工具条贴着侧栏左缘、
/// 没有容器边距:最左那颗图标的中心压在与导航行行首同一条轴上(用户 2026-09-21)
const FOOTER_LEAD_INSET: Zpx = axis_inset(FOOTER_BTN, Zpx(0.));
-/// 侧栏底部状态行的行首框:转圈、出错图标都是这么宽,"Live updates off" 的圆点在框里居中
+/// 侧栏底部状态行的行首槽位(`lead_slot`):转圈、出错图标都是这么宽,"Live updates off" 的
+/// 圆点在里面居中
const STATUS_LEAD: Zpx = Zpx(12.);
/// 状态行左内边距:行首框中心压在侧栏中轴上,与上面的导航行、下面的工具条同一条线
const STATUS_LEAD_INSET: Zpx = axis_inset(STATUS_LEAD, Zpx(0.));
@@ -9690,13 +9680,9 @@ fn sidebar_row(
.child(
// 定宽槽位保证文字起点统一;内部居中,使小图标的中心也落在
// LEAD_AXIS 上(左对齐会让 14/15px 图标的中心偏离轴 1.5~2pt)
- div()
- .w(LEAD_BOX)
- .flex_shrink_0()
- .flex()
- .items_center()
- .justify_center()
- .child(match lead {
+ lead_slot(
+ LEAD_BOX,
+ match lead {
// 线条图标比实心品牌图视觉轻,给它小一档才平衡
RowLead::Icon(ic) => ic
.with_size(if sub { zpx(14.) } else { NAV_ICON.get() })
@@ -9709,7 +9695,8 @@ fn sidebar_row(
// 品牌图不着色:img 走 AssetSource 取内嵌 PNG,原色渲染
// (侧栏单色化试过,用户否决——保持彩色)
RowLead::Brand(path) => img(path).size(LEAD_BOX).into_any_element(),
- }),
+ },
+ ),
)
.child(
div()