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: aggregate remote agent sessions over SSH (issue #21)

Corey Chiu7a234043d00a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 67a064e..654f049 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,11 @@
## Unreleased
+- New: remote hosts — mirror agent sessions from other machines over SSH into the index. Add a host in Settings → Remote hosts (an alias from `~/.ssh/config` or `user@host`); sessions sync on launch, refresh, and Sync now, then browse and search them alongside local ones with an `@host` badge
+- New: remote sessions offer "Copy SSH command" — a ready-to-paste `ssh -t` command that resumes the session in its original project directory on the remote machine
+- Update: remote mirroring is strictly read-only — only session data is synced (never credentials), nothing on the remote host is ever written, and remote sessions can't be deleted from Wake
+- Credits: remote sessions over SSH were requested in [issue #21](https://github.com/iAmCorey/Wake/issues/21). Thanks to [@megrxu](https://github.com/megrxu) for the proposal and workflow sketch
+
## [0.3.6] — 2026-09-02
- New: standard macOS Edit and Window menus, so Cut, Copy and Paste work inside system dialogs and Hide, Minimize, Zoom and Full Screen shortcuts do what they should
diff --git a/PRODUCT.md b/PRODUCT.md
index 81c8a2b..8d49cd4 100644
--- a/PRODUCT.md
+++ b/PRODUCT.md
@@ -28,13 +28,13 @@ Corey 本人(独立开发者,主力工具 Claude Code 与 Codex,中文为主)。
## Capabilities and Constraints
-已实现:十四家 adapter、FTS5 trigram 搜索(<3 码点 LIKE 降级)、**搜索跳转定位**(2026-08-18:⌘K 命中直达详情页对应消息并高亮,seq 契约保证)、详情页逐消息渲染(气泡/工具折叠簇/thinking/tree-sitter 高亮;2026-08-17 由整篇 markdown 方案升级)、恢复/收藏/置顶/导出/删除(废纸篓+墓碑)、文件监听增量、Insights 统计页(0.3.0:活跃热力图与 streak、时段/星期/月份分布、Agents·Projects·Models 三榜单按 sessions/tokens/prompts 切换;口径=主线用户消息,规格见 DESIGN.md)、Updates 页与 macOS Wake 菜单手动检查 GitHub 最新正式版并打开 Release 页更新(不后台联网、不自动替换应用包)、测试套件(adapter 契约、DB 往返、scanner 回归 + CI 三平台 + pre-commit,合成 fixture)、三端桌面(macOS 主平台;Linux/Windows experimental,终端恢复/废纸篓·回收站/剪贴板按平台原生实现,发版 CI 自动出六产物)、窗口记忆(0.3.6:记住所在屏幕/屏内位置/最大化/全屏,重启与 Dock 重开都回到原处,Settings 开在主窗所在屏)、完整 macOS 菜单栏(0.3.6:标准 Edit/Window 菜单、⌘W、Window → Main Window,主窗关闭后 About/Settings/Updates 仍可用)、导出 Markdown 与保存图片走系统「另存为」并记住上次目录(0.3.6,issue #25)。
+已实现:十四家 adapter、FTS5 trigram 搜索(<3 码点 LIKE 降级)、**搜索跳转定位**(2026-08-18:⌘K 命中直达详情页对应消息并高亮,seq 契约保证)、详情页逐消息渲染(气泡/工具折叠簇/thinking/tree-sitter 高亮;2026-08-17 由整篇 markdown 方案升级)、恢复/收藏/置顶/导出/删除(废纸篓+墓碑)、文件监听增量、Insights 统计页(0.3.0:活跃热力图与 streak、时段/星期/月份分布、Agents·Projects·Models 三榜单按 sessions/tokens/prompts 切换;口径=主线用户消息,规格见 DESIGN.md)、Updates 页与 macOS Wake 菜单手动检查 GitHub 最新正式版并打开 Release 页更新(不后台联网、不自动替换应用包)、测试套件(adapter 契约、DB 往返、scanner 回归 + CI 三平台 + pre-commit,合成 fixture)、三端桌面(macOS 主平台;Linux/Windows experimental,终端恢复/废纸篓·回收站/剪贴板按平台原生实现,发版 CI 自动出六产物)、窗口记忆(0.3.6:记住所在屏幕/屏内位置/最大化/全屏,重启与 Dock 重开都回到原处,Settings 开在主窗所在屏)、完整 macOS 菜单栏(0.3.6:标准 Edit/Window 菜单、⌘W、Window → Main Window,主窗关闭后 About/Settings/Updates 仍可用)、导出 Markdown 与保存图片走系统「另存为」并记住上次目录(0.3.6,issue #25)、远程 host(Unreleased,issue #21:Settings → Remote hosts 配 SSH 目标,rsync 白名单镜像会话数据到本地缓存后与本地会话同列同搜,`@host` 徽章标识;阶段 1 只读——不动远端文件、远程会话禁删,resume 以 Copy SSH command 形态提供;分期计划见 CLAUDE.md「远程 host」节)。
约束:对 agent 数据目录只读;绝不写 Codex 的 SQLite;不读凭证;GPUI 无 SF Symbols(图标用 lucide SVG 自备)。
已支持十四家 agent:Claude Code、Codex、Qoder CLI(`~/.qoder/projects` JSONL,active-leaf 分支恢复、tool result 回挂、`QODER_CONFIG_DIR`)、Copilot CLI、Cursor(CLI transcripts)、OpenCode(含 OpenCode 2 next,stable 的 `opencode.db` 与 next 的 `opencode-next.db` 同时扫描;逐会话兼容 `message+part`、真实 `session+session_message` 及早期 `session_v2` schema;preview 会话标 opencode2 徽章)、Kiro、Gemini CLI(2026-08-17 P1 五家落地)+ Pi、Oh My Pi、Grok Build、Kimi Code、Antigravity CLI(2026-08-19 对齐 kooky 内置 roster;Antigravity 正文加密仅元数据卡片)+ DeepSeek Harness(dsh,2026-08-20,zstd 事件日志透明解压;格式由源码推断,当天用户跑出真实会话完成首验)。做不了的:Cursor IDE chats 正文加密,Windsurf/Trae 加密,Amp/Factory(Droid)/Warp 云端无本地数据,Reasonix 本机零会话格式未实测。
## Brand Commitments
-名称 Wake(2026-08-14 由 Vibex 更名;取「船迹」——agent 驶过的痕迹,兼「唤醒」恢复会话之意)。界面语言英文(2026-08-14 由中文切换,用户反馈中文 UI 词汇观感生硬)。视觉基准(用户 2026-08-14 确认):现代 macOS 原生规范,工艺对标 Things / Bear(优雅轻盈的原生感);支持跟随系统或固定浅/深外观。agent 品牌色作为功能性识别色保留(Claude 橙 #D97757、Codex 绿 #12A06B 等,见 models.rs)。Session locations 自 0.2.9 起归入独立 Settings 窗口,主界面只保留齿轮入口;Settings 固定为 General / Locations / Data / Updates / About,不提供默认 “Open In” 终端选择。
+名称 Wake(2026-08-14 由 Vibex 更名;取「船迹」——agent 驶过的痕迹,兼「唤醒」恢复会话之意)。界面语言英文(2026-08-14 由中文切换,用户反馈中文 UI 词汇观感生硬)。视觉基准(用户 2026-08-14 确认):现代 macOS 原生规范,工艺对标 Things / Bear(优雅轻盈的原生感);支持跟随系统或固定浅/深外观。agent 品牌色作为功能性识别色保留(Claude 橙 #D97757、Codex 绿 #12A06B 等,见 models.rs)。Session locations 自 0.2.9 起归入独立 Settings 窗口,主界面只保留齿轮入口;Settings 固定为 General / Locations / Remote hosts / Data / Updates / About(Remote hosts 为 Unreleased 新增),不提供默认 “Open In” 终端选择。
## Evidence on Hand
diff --git a/crates/wake-core/src/adapters/antigravity.rs b/crates/wake-core/src/adapters/antigravity.rs
index 926ceec..c73495c 100644
--- a/crates/wake-core/src/adapters/antigravity.rs
+++ b/crates/wake-core/src/adapters/antigravity.rs
@@ -30,9 +30,7 @@ impl AntigravityAdapter {
}
fn rows(&self) -> Option<Vec<AgRow>> {
- let mtime = std::fs::metadata(&self.db)
- .map(|m| mtime_ms(&m))
- .unwrap_or(0);
+ let mtime = super::sqlite_ro::db_cache_stamp(&self.db);
self.rows_cache.get_or_try_build(mtime, || {
let ro = open_sqlite_ro(&self.db, "antigravity")?;
let mut stmt = ro
@@ -74,6 +72,7 @@ impl AntigravityAdapter {
};
SessionMeta {
key: format!("antigravity:{}", row.id),
+ host: String::new(),
id: row.id.clone(),
agent: AgentId::Antigravity,
title,
diff --git a/crates/wake-core/src/adapters/claude.rs b/crates/wake-core/src/adapters/claude.rs
index 9c9afb8..1ab3f2e 100644
--- a/crates/wake-core/src/adapters/claude.rs
+++ b/crates/wake-core/src/adapters/claude.rs
@@ -420,6 +420,7 @@ fn build_meta(r: &SessionFileRef, p: &ParseResult) -> SessionMeta {
let project_name = project_name_of(&p.cwd);
SessionMeta {
key: format!("claude-code:{}", r.native_id),
+ host: String::new(),
id: r.native_id.clone(),
agent: AgentId::ClaudeCode,
title: p.title.clone(),
diff --git a/crates/wake-core/src/adapters/codex.rs b/crates/wake-core/src/adapters/codex.rs
index 603942a..f6478a4 100644
--- a/crates/wake-core/src/adapters/codex.rs
+++ b/crates/wake-core/src/adapters/codex.rs
@@ -35,6 +35,26 @@ impl CodexAdapter {
scan_archived: true,
}
}
+
+ /// state DB 的 threads.rollout_path 是**写库那台机器**上的绝对路径——
+ /// 远程缓存与自定义根下和本实例枚举出的 file_path 对不上,按
+ /// sessions/archived_sessions 尾段重定位到本实例目录(默认根下恒等)。
+ /// 认不出形状(如 Windows 反斜杠路径)原样返回,退回全路径精确匹配。
+ fn remap_rollout_path(&self, raw: &str) -> String {
+ for (marker, base) in [
+ ("/archived_sessions/", &self.archived_dir),
+ ("/sessions/", &self.sessions_dir),
+ ] {
+ if let Some(pos) = raw.rfind(marker) {
+ let mut p = base.clone();
+ for seg in raw[pos + marker.len()..].split('/') {
+ p.push(seg);
+ }
+ return p.to_string_lossy().into_owned();
+ }
+ }
+ raw.to_string()
+ }
}
/// rollout 存储本体(用户选中的是数据目录而非 codex home):自身不含
@@ -670,6 +690,7 @@ fn build_meta(r: &SessionFileRef, p: &CodexParse, archived_dir: &Path) -> Sessio
let project_name = project_name_of(&p.cwd);
SessionMeta {
key: format!("codex:{}", r.native_id),
+ host: String::new(),
id: r.native_id.clone(),
agent: AgentId::Codex,
title,
@@ -731,8 +752,10 @@ impl AgentAdapter for CodexAdapter {
fn quick_meta(&self, refs: &[SessionFileRef]) -> Option<HashMap<String, SessionMeta>> {
let rows = read_threads(&self.state_db)?;
- let by_path: HashMap<&str, &ThreadRow> =
- rows.iter().map(|r| (r.rollout_path.as_str(), r)).collect();
+ let by_path: HashMap<String, &ThreadRow> = rows
+ .iter()
+ .map(|r| (self.remap_rollout_path(&r.rollout_path), r))
+ .collect();
let mut out = HashMap::new();
for r in refs {
let Some(row) = by_path.get(r.file_path.as_str()) else {
@@ -761,6 +784,7 @@ impl AgentAdapter for CodexAdapter {
r.file_path.clone(),
SessionMeta {
key: format!("codex:{}", row.id),
+ host: String::new(),
id: row.id.clone(),
agent: AgentId::Codex,
title,
diff --git a/crates/wake-core/src/adapters/copilot.rs b/crates/wake-core/src/adapters/copilot.rs
index b15e679..79ecc18 100644
--- a/crates/wake-core/src/adapters/copilot.rs
+++ b/crates/wake-core/src/adapters/copilot.rs
@@ -30,9 +30,7 @@ impl CopilotAdapter {
}
fn db_mtime(&self) -> i64 {
- std::fs::metadata(&self.db)
- .map(|m| mtime_ms(&m))
- .unwrap_or(0)
+ super::sqlite_ro::db_cache_stamp(&self.db)
}
fn rows(&self) -> Option<Vec<CopilotRow>> {
@@ -80,6 +78,7 @@ impl CopilotAdapter {
let title = clean_title_candidate(&row.summary);
SessionMeta {
key: format!("copilot:{}", row.id),
+ host: String::new(),
id: row.id.clone(),
agent: AgentId::Copilot,
title: if title.is_empty() {
diff --git a/crates/wake-core/src/adapters/cursor.rs b/crates/wake-core/src/adapters/cursor.rs
index 183e7e1..718d33d 100644
--- a/crates/wake-core/src/adapters/cursor.rs
+++ b/crates/wake-core/src/adapters/cursor.rs
@@ -267,6 +267,7 @@ fn build_meta(r: &SessionFileRef, p: &CursorParse) -> SessionMeta {
let title = title_from_messages(&p.messages).unwrap_or_else(|| UNTITLED.to_string());
SessionMeta {
key: format!("cursor:{}", r.native_id),
+ host: String::new(),
id: r.native_id.clone(),
agent: AgentId::Cursor,
title,
diff --git a/crates/wake-core/src/adapters/dsh.rs b/crates/wake-core/src/adapters/dsh.rs
index 5029bf7..4674ab3 100644
--- a/crates/wake-core/src/adapters/dsh.rs
+++ b/crates/wake-core/src/adapters/dsh.rs
@@ -399,6 +399,7 @@ fn build_meta(r: &SessionFileRef, p: &DshParse) -> SessionMeta {
.unwrap_or_else(|| UNTITLED.to_string());
SessionMeta {
key: format!("dsh:{native}"),
+ host: String::new(),
id: native,
agent: AgentId::Dsh,
title,
diff --git a/crates/wake-core/src/adapters/gemini.rs b/crates/wake-core/src/adapters/gemini.rs
index 1c13fe0..c489ada 100644
--- a/crates/wake-core/src/adapters/gemini.rs
+++ b/crates/wake-core/src/adapters/gemini.rs
@@ -157,6 +157,7 @@ fn build_meta(r: &SessionFileRef, p: &GeminiParse, cwd: &str) -> SessionMeta {
let title = title_from_messages(&p.messages).unwrap_or_else(|| UNTITLED.to_string());
SessionMeta {
key: format!("gemini:{native}"),
+ host: String::new(),
id: native,
agent: AgentId::Gemini,
title,
diff --git a/crates/wake-core/src/adapters/grok.rs b/crates/wake-core/src/adapters/grok.rs
index 2380da7..ecd7fcb 100644
--- a/crates/wake-core/src/adapters/grok.rs
+++ b/crates/wake-core/src/adapters/grok.rs
@@ -360,6 +360,7 @@ fn build_meta(
grok_group::canonical_project(&side.cwd, &side.git_remotes, grok_home, &r.native_id, group);
SessionMeta {
key: format!("grok:{}", r.native_id),
+ host: String::new(),
id: r.native_id.clone(),
agent: AgentId::Grok,
title,
diff --git a/crates/wake-core/src/adapters/kimi.rs b/crates/wake-core/src/adapters/kimi.rs
index d86a65c..a93d960 100644
--- a/crates/wake-core/src/adapters/kimi.rs
+++ b/crates/wake-core/src/adapters/kimi.rs
@@ -180,6 +180,7 @@ fn build_meta(
.unwrap_or_else(|| UNTITLED.to_string());
SessionMeta {
key: format!("kimi:{}", r.native_id),
+ host: String::new(),
id: r.native_id.clone(),
agent: AgentId::Kimi,
title,
diff --git a/crates/wake-core/src/adapters/kiro.rs b/crates/wake-core/src/adapters/kiro.rs
index 07d7780..55ddd43 100644
--- a/crates/wake-core/src/adapters/kiro.rs
+++ b/crates/wake-core/src/adapters/kiro.rs
@@ -128,6 +128,7 @@ fn build_meta(r: &SessionFileRef, side: &Sidecar, messages: &[TranscriptMessage]
.unwrap_or(0);
SessionMeta {
key: format!("kiro:{}", r.native_id),
+ host: String::new(),
id: r.native_id.clone(),
agent: AgentId::Kiro,
title,
diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rs
index d063575..411a52a 100644
--- a/crates/wake-core/src/adapters/mod.rs
+++ b/crates/wake-core/src/adapters/mod.rs
@@ -12,6 +12,8 @@ pub mod opencode;
pub mod pi;
pub mod qoder;
+pub mod remote;
+
pub(crate) mod grok_group;
pub(crate) mod parse_utils;
pub(crate) mod sqlite_ro;
@@ -24,6 +26,12 @@ use std::path::Path;
/// 保证 FTS 的 seq 与详情页消息序号一致(搜索跳转依赖)。
pub trait AgentAdapter: Send + Sync {
fn agent(&self) -> AgentId;
+ /// 实例服务的远程 host;空 = 本地。只有 remote::RemoteAdapter 覆写。
+ /// scanner 的同家同 ID 去重按 (host, agent, native_id) 分域——两台机器
+ /// 各自续跑过的同 UUID 会话是两条会话,不能按 mtime 互吞
+ fn host(&self) -> &str {
+ ""
+ }
/// 本机是否有这家的数据。由 data_roots 派生,**不要覆写**——它必须与
/// 面板逐路径的 exists() 同一判据,手写版本(is_dir/is_file)与之打架
/// 正是 2026-08-24 数轮 review 反复修的源头之一
@@ -204,15 +212,18 @@ pub fn create_adapters_with(
custom_roots: &[(AgentId, std::path::PathBuf)],
removed_defaults: &[AgentId],
) -> Vec<Box<dyn AgentAdapter>> {
- create_adapters_with_root_overrides(custom_roots, removed_defaults, &[])
+ create_adapters_with_root_overrides(create_adapters(), custom_roots, removed_defaults, &[])
}
+/// `base` 由调用方传入而非内部再造:create_adapter_roster_for 要把同一批
+/// 模板先借给远程实例构造——整个 roster 组装保持**单次** create_adapters(),
+/// 不变量 8 的"唯一构造时刻"不开例外
fn create_adapters_with_root_overrides(
+ base: Vec<Box<dyn AgentAdapter>>,
custom_roots: &[(AgentId, std::path::PathBuf)],
removed_defaults: &[AgentId],
removed_default_roots: &[(AgentId, std::path::PathBuf)],
) -> Vec<Box<dyn AgentAdapter>> {
- let base = create_adapters();
let customs: Vec<Box<dyn AgentAdapter>> = custom_roots
.iter()
.filter_map(|(agent, root)| {
@@ -265,9 +276,23 @@ pub struct AdapterRoster {
/// 按索引库配置同时构造“全部 location 快照”和“仅启用的扫描 roster”。停用
/// 记录按 (agent, 真实数据根) 精确匹配,因此同一 Agent 的多个 location 可独立
/// 控制;单根 adapter 全关后直接移出 active,多根 adapter 走局部裁剪。
+///
+/// 启用的远程 host 以装饰器实例(adapters::remote)追加在 active **尾部**:
+/// 顺序契约不变("按 agent 找第一个"的兜底仍落默认实例);远程实例不进
+/// `locations`——Session locations 面板只管本地路径,远程在 Remote hosts 页。
pub fn create_adapter_roster_for(store: &crate::db::Store) -> AdapterRoster {
let (customs, removed, removed_roots) = store.location_overrides();
- let configured = create_adapters_with_root_overrides(&customs, &removed, &removed_roots);
+ let base = create_adapters();
+ // 远程实例先借同一批模板构造(未经 location 覆盖的原始形态),base 随后
+ // move 进 overrides——全函数只有一次 create_adapters()
+ let mut remote_instances: Vec<Box<dyn AgentAdapter>> = Vec::new();
+ if let Some(db_dir) = store.db_dir() {
+ for host in store.enabled_remote_host_names() {
+ let host_cache = crate::remote::host_cache_dir(&db_dir, &host);
+ remote_instances.extend(remote::create_remote_adapters(&base, &host, &host_cache));
+ }
+ }
+ let configured = create_adapters_with_root_overrides(base, &customs, &removed, &removed_roots);
let disabled: std::collections::HashSet<(AgentId, std::path::PathBuf)> =
store.disabled_locations().into_iter().collect();
@@ -302,6 +327,11 @@ pub fn create_adapter_roster_for(store: &crate::db::Store) -> AdapterRoster {
}
}
+ // 远程实例无条件追加(缓存树可能还没同步下来——各家挂载点选的是"目录
+ // 不存在也整形正确"的那层,缺根由 list_session_files 降级为空),同步
+ // 落盘后 watcher/补扫自然收编
+ active.extend(remote_instances);
+
AdapterRoster { active, locations }
}
diff --git a/crates/wake-core/src/adapters/opencode.rs b/crates/wake-core/src/adapters/opencode.rs
index dd793d7..cb14a85 100644
--- a/crates/wake-core/src/adapters/opencode.rs
+++ b/crates/wake-core/src/adapters/opencode.rs
@@ -219,9 +219,7 @@ impl OpencodeAdapter {
}
fn rows(db: &OcDb) -> Option<Vec<OcRow>> {
- let mtime = std::fs::metadata(&db.path)
- .map(|m| mtime_ms(&m))
- .unwrap_or(0);
+ let mtime = super::sqlite_ro::db_cache_stamp(&db.path);
db.rows_cache.get_or_try_build(mtime, || {
let ro = Self::open(&db.path)?;
query_rows(&ro.conn, None).ok()
@@ -246,6 +244,7 @@ impl OpencodeAdapter {
.and_then(|m| m.get("id").and_then(|v| v.as_str()).map(String::from));
SessionMeta {
key: format!("opencode:{}", row.id),
+ host: String::new(),
id: row.id.clone(),
agent: AgentId::Opencode,
title: if title.is_empty() {
diff --git a/crates/wake-core/src/adapters/pi.rs b/crates/wake-core/src/adapters/pi.rs
index 2c1ecdb..e4f26d4 100644
--- a/crates/wake-core/src/adapters/pi.rs
+++ b/crates/wake-core/src/adapters/pi.rs
@@ -225,6 +225,7 @@ fn build_meta(agent: AgentId, r: &SessionFileRef, p: &PiParse) -> SessionMeta {
let title = title_from_messages(&p.messages).unwrap_or_else(|| UNTITLED.to_string());
SessionMeta {
key: format!("{}:{native}", agent.as_str()),
+ host: String::new(),
id: native,
agent,
title,
diff --git a/crates/wake-core/src/adapters/qoder.rs b/crates/wake-core/src/adapters/qoder.rs
index f0e41e8..d535225 100644
--- a/crates/wake-core/src/adapters/qoder.rs
+++ b/crates/wake-core/src/adapters/qoder.rs
@@ -672,6 +672,7 @@ fn build_meta(r: &SessionFileRef, parsed: &QoderParse) -> SessionMeta {
.unwrap_or_else(|| UNTITLED.to_string());
SessionMeta {
key: format!("qoder:{}", r.native_id),
+ host: String::new(),
id: r.native_id.clone(),
agent: AgentId::Qoder,
title,
diff --git a/crates/wake-core/src/adapters/remote.rs b/crates/wake-core/src/adapters/remote.rs
new file mode 100644
index 0000000..29c9edc
--- /dev/null
+++ b/crates/wake-core/src/adapters/remote.rs
@@ -0,0 +1,186 @@
+//! 远程会话的 adapter 装饰器。
+//!
+//! `RemoteAdapter` 包一个 `with_custom_root(缓存内数据目录)` 的常规实例,
+//! 在**每个产出 `SessionMeta` 的出口**(parse_session / parse_transcript /
+//! quick_meta / parent_links)统一做两件事:key 在 agent 段之后插入 host 段
+//! (`agent:native` → `agent:host:native`,经 models::session_key 单点)、
+//! `meta.host` 赋值。inner 对远程零感知,merge_quick_meta 只在两个已改写的
+//! meta 之间搬运字段(codex 的 `parsed.key = quick.key` 语义因此透明成立);
+//! 各家的解析/枚举逻辑零改动(构造点仅机械补了 `host: String::new()`)。
+//!
+//! **必须逐方法显式转发**:trait 的默认实现一旦被装饰器"继承",inner 的
+//! 覆写(codex 的 quick_meta、dsh 的 file_ref、grok 的 parent_links)就被
+//! 静默绕过——新增 trait 方法时这里必须跟着补转发。
+
+use super::AgentAdapter;
+use crate::models::*;
+use anyhow::Result;
+use std::path::Path;
+
+pub struct RemoteAdapter {
+ inner: Box<dyn AgentAdapter>,
+ host: String,
+}
+
+impl RemoteAdapter {
+ pub fn new(inner: Box<dyn AgentAdapter>, host: impl Into<String>) -> Self {
+ Self {
+ inner,
+ host: host.into(),
+ }
+ }
+
+ /// `agent:native` → `agent:host:native`(经 models::session_key 单点)。
+ /// agent 恒为首段——scanner 的易主检测(`key.split(':').next()`)依赖。
+ fn rewrite_key(&self, local_key: &str) -> String {
+ // inner 生产的 key 恒为 `agent:` 前缀;万一不是,整串当 native 仍唯一
+ let native = local_key
+ .split_once(':')
+ .map(|(_, rest)| rest)
+ .unwrap_or(local_key);
+ session_key(self.inner.agent(), &self.host, native)
+ }
+
+ /// 装饰器契约的唯一实现:每个产出 SessionMeta 的出口做且只做这两件事。
+ /// &mut 签名让四个出口(含 quick_meta 的 values_mut 循环)共用同一份,
+ /// 出口再加改写字段时不存在漏改其一的第二副本
+ fn rewrite_meta(&self, meta: &mut SessionMeta) {
+ meta.key = self.rewrite_key(&meta.key);
+ meta.host = self.host.clone();
+ }
+}
+
+/// 对一个 host 构造整组远程实例:十四家模板 × `with_custom_root`(缓存内
+/// 挂载点,见 remote::REMOTE_LAYOUTS)× 装饰器。追加进 roster 的 active 尾部
+/// (不进 Session locations 面板)。`templates` 由 roster 唯一构造点传入
+/// (不变量 8:本模块不得自行二次 create_adapters());产物的数据根 100%
+/// 派生自 `host_cache`,不携带模板的 env/文件系统快照。
+pub fn create_remote_adapters(
+ templates: &[Box<dyn AgentAdapter>],
+ host: &str,
+ host_cache: &Path,
+) -> Vec<Box<dyn AgentAdapter>> {
+ let mut out: Vec<Box<dyn AgentAdapter>> = Vec::new();
+ for layout in crate::remote::REMOTE_LAYOUTS {
+ let Some(template) = templates.iter().find(|a| a.agent() == layout.agent) else {
+ continue;
+ };
+ let inner = template.with_custom_root(host_cache.join(layout.mount));
+ out.push(Box::new(RemoteAdapter::new(inner, host)));
+ }
+ out
+}
+
+impl AgentAdapter for RemoteAdapter {
+ fn agent(&self) -> AgentId {
+ self.inner.agent()
+ }
+
+ fn host(&self) -> &str {
+ &self.host
+ }
+
+ fn detect(&self) -> bool {
+ self.inner.detect()
+ }
+
+ fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {
+ self.inner.list_session_files()
+ }
+
+ fn file_ref(&self, path: &Path) -> Option<SessionFileRef> {
+ self.inner.file_ref(path)
+ }
+
+ fn quick_meta(
+ &self,
+ refs: &[SessionFileRef],
+ ) -> Option<std::collections::HashMap<String, SessionMeta>> {
+ // 原地改值:map 的键(file_path)不变,重建整表是纯浪费——这张表
+ // 是"整家会话"量级,每轮扫描都过一次
+ let mut map = self.inner.quick_meta(refs)?;
+ for meta in map.values_mut() {
+ self.rewrite_meta(meta);
+ }
+ Some(map)
+ }
+
+ fn merge_quick_meta(&self, parsed: SessionMeta, quick: &SessionMeta) -> SessionMeta {
+ // 两个输入都已在各自出口改写;inner 只搬运字段(codex 会整体取
+ // quick.key),结果无需再套一层
+ self.inner.merge_quick_meta(parsed, quick)
+ }
+
+ fn parse_session(&self, r: &SessionFileRef) -> Result<ParsedSession> {
+ let mut parsed = self.inner.parse_session(r)?;
+ self.rewrite_meta(&mut parsed.meta);
+ Ok(parsed)
+ }
+
+ fn parse_transcript(&self, r: &SessionFileRef) -> Result<ParsedTranscript> {
+ let mut parsed = self.inner.parse_transcript(r)?;
+ self.rewrite_meta(&mut parsed.meta);
+ Ok(parsed)
+ }
+
+ fn load_sidechain(
+ &self,
+ r: &SessionFileRef,
+ sidechain_id: &str,
+ ) -> Result<Vec<TranscriptMessage>> {
+ self.inner.load_sidechain(r, sidechain_id)
+ }
+
+ fn session_paths(&self, meta: &SessionMeta) -> Vec<String> {
+ // 远程会话 UI 禁删;这里如实返回缓存内路径,消费方(若有)拿到的
+ // 是本地副本而非远端文件
+ self.inner.session_paths(meta)
+ }
+
+ fn begin_scan(&self) {
+ self.inner.begin_scan();
+ }
+
+ fn manages_parent_links(&self) -> bool {
+ self.inner.manages_parent_links()
+ }
+
+ fn parent_links(&self) -> Vec<(String, String)> {
+ self.inner
+ .parent_links()
+ .into_iter()
+ .map(|(child, parent)| (self.rewrite_key(&child), self.rewrite_key(&parent)))
+ .collect()
+ }
+
+ fn is_parent_link_event(&self, path: &Path) -> bool {
+ self.inner.is_parent_link_event(path)
+ }
+
+ fn data_roots(&self) -> Vec<std::path::PathBuf> {
+ self.inner.data_roots()
+ }
+
+ fn watch_paths(&self) -> Vec<std::path::PathBuf> {
+ self.inner.watch_paths()
+ }
+
+ fn with_custom_root(&self, dir: std::path::PathBuf) -> Box<dyn AgentAdapter> {
+ // 远程实例没有自定义 location 的产品入口;保持装饰不变量以防未来误用
+ Box::new(Self {
+ inner: self.inner.with_custom_root(dir),
+ host: self.host.clone(),
+ })
+ }
+
+ fn supports_individual_root_removal(&self) -> bool {
+ self.inner.supports_individual_root_removal()
+ }
+
+ fn excluding_data_roots(&self, roots: &[std::path::PathBuf]) -> Option<Box<dyn AgentAdapter>> {
+ Some(Box::new(Self {
+ inner: self.inner.excluding_data_roots(roots)?,
+ host: self.host.clone(),
+ }))
+ }
+}
diff --git a/crates/wake-core/src/adapters/sqlite_ro.rs b/crates/wake-core/src/adapters/sqlite_ro.rs
index 3e34dcc..9e62fda 100644
--- a/crates/wake-core/src/adapters/sqlite_ro.rs
+++ b/crates/wake-core/src/adapters/sqlite_ro.rs
@@ -61,3 +61,17 @@ pub fn strip_virtual_path(path: &str) -> &str {
path.rsplit_once('#').map(|(db, _)| db).unwrap_or(path)
}
}
+
+/// 行缓存的失效戳:主库与 `-wal` 的 mtime 取新者。WAL 库的新写入往往只落
+/// `-wal`(写端尚未 checkpoint;远程 rsync 镜像更是永远没人 checkpoint 主库),
+/// 只看主库 mtime 会让缓存抱着旧快照不放、新会话直到重启才出现。
+pub fn db_cache_stamp(db: &Path) -> i64 {
+ let stamp = |p: &Path| {
+ std::fs::metadata(p)
+ .map(|m| super::parse_utils::mtime_ms(&m))
+ .unwrap_or(0)
+ };
+ let mut wal = db.as_os_str().to_owned();
+ wal.push("-wal");
+ stamp(db).max(stamp(Path::new(&wal)))
+}
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index 4575d06..d2012ba 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -11,6 +11,16 @@ pub type LocationOverrides = (
Vec<(AgentId, std::path::PathBuf)>,
);
+/// remote_hosts 表的一行(Settings → Remote hosts / roster 组装共用)
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RemoteHost {
+ pub name: String,
+ pub enabled: bool,
+ /// epoch ms;None = 从未成功同步过
+ pub last_sync_at: Option<i64>,
+ pub last_sync_error: Option<String>,
+}
+
const DDL: &str = r#"
CREATE TABLE IF NOT EXISTS schema_meta (key TEXT PRIMARY KEY, value TEXT);
@@ -33,7 +43,8 @@ CREATE TABLE IF NOT EXISTS sessions (
file_size INTEGER DEFAULT 0,
file_mtime INTEGER DEFAULT 0,
unknown_lines INTEGER DEFAULT 0,
- parent_key TEXT NOT NULL DEFAULT ''
+ parent_key TEXT NOT NULL DEFAULT '',
+ host TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_sessions_agent ON sessions(agent_id, updated_at DESC);
@@ -101,6 +112,14 @@ CREATE TABLE IF NOT EXISTS disabled_locations (
disabled_at INTEGER,
PRIMARY KEY (agent, path)
);
+
+CREATE TABLE IF NOT EXISTS remote_hosts (
+ name TEXT PRIMARY KEY,
+ enabled INTEGER DEFAULT 1,
+ added_at INTEGER,
+ last_sync_at INTEGER,
+ last_sync_error TEXT
+);
"#;
fn open_conn(path: &Path) -> Result<Connection> {
@@ -141,6 +160,20 @@ fn open_conn(path: &Path) -> Result<Connection> {
"CREATE INDEX IF NOT EXISTS idx_sessions_parent ON sessions(parent_key)",
[],
)?;
+ // host 迁移(2026-09-01 远程会话加列;空串 = 本地)。老库首扫时既有行
+ // 全部落 '',与远程装饰器生产的非空 host 天然分域,无需回填
+ if !table_has_column(&conn, "sessions", "host")? {
+ conn.execute(
+ "ALTER TABLE sessions ADD COLUMN host TEXT NOT NULL DEFAULT ''",
+ [],
+ )?;
+ }
+ // 部分索引须在 host 列就位后建(放 DDL 里对未迁移老库会 no such column):
+ // host_counts 的 GROUP BY 从全表扫降为远小于全表的索引扫
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_sessions_host ON sessions(host) WHERE host != ''",
+ [],
+ )?;
Ok(conn)
}
@@ -628,6 +661,103 @@ impl Store {
Ok(())
}
+ // ---------- 远程 host(Settings → Remote hosts,SSH 会话聚合) ----------
+
+ /// 与 location 配置同层级的用户数据:重扫不动,索引重建才丢。
+ /// name 即 ssh 目标(`~/.ssh/config` 的 Host 别名或 user@host),
+ /// 字符集校验在 add_remote_host 那道门
+ pub fn list_remote_hosts(&self) -> Result<Vec<RemoteHost>> {
+ let conn = self.read.lock().unwrap();
+ let mut stmt = conn.prepare_cached(
+ "SELECT name, enabled, last_sync_at, last_sync_error
+ FROM remote_hosts ORDER BY added_at, name",
+ )?;
+ let rows = stmt.query_map([], |r| {
+ Ok(RemoteHost {
+ name: r.get(0)?,
+ enabled: r.get::<_, i64>(1)? != 0,
+ last_sync_at: r.get(2)?,
+ last_sync_error: r.get(3)?,
+ })
+ })?;
+ Ok(rows.flatten().collect())
+ }
+
+ /// roster 组装(create_adapter_roster_for)与 UI 起同步共用——远程实例
+ /// 集合与同步目标集合必须同源,别各自 filter 一遍。
+ pub fn enabled_remote_host_names(&self) -> Vec<String> {
+ self.list_remote_hosts()
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|h| h.enabled)
+ .map(|h| h.name)
+ .collect()
+ }
+
+ pub fn add_remote_host(&self, name: &str) -> Result<()> {
+ // 校验在写库这道门(而非各入口自记):host 名进 session key 作中段、
+ // 直接当 ssh/rsync 参数,任何未来入口(CLI/导入)都不得绕过
+ if !crate::remote::valid_host_name(name) {
+ return Err(anyhow::anyhow!("invalid host name: {name:?}"));
+ }
+ let conn = self.write.lock().unwrap();
+ conn.execute(
+ "INSERT OR IGNORE INTO remote_hosts(name, enabled, added_at) VALUES (?1, 1, ?2)",
+ params![name, now_ms()],
+ )?;
+ Ok(())
+ }
+
+ /// 移除 host 配置本身。缓存目录与已入库会话由调用方另行清理
+ /// (Workbench 删缓存目录后补扫,run_scan 的删除检测出清库内行)
+ pub fn remove_remote_host(&self, name: &str) -> Result<()> {
+ let conn = self.write.lock().unwrap();
+ conn.execute("DELETE FROM remote_hosts WHERE name = ?1", params![name])?;
+ Ok(())
+ }
+
+ pub fn set_remote_host_enabled(&self, name: &str, enabled: bool) -> Result<()> {
+ let conn = self.write.lock().unwrap();
+ conn.execute(
+ "UPDATE remote_hosts SET enabled = ?2 WHERE name = ?1",
+ params![name, enabled as i64],
+ )?;
+ Ok(())
+ }
+
+ /// 同步收尾统一写状态:成功清 error,失败保留上次成功时间
+ pub fn record_remote_sync(&self, name: &str, error: Option<&str>) -> Result<()> {
+ let conn = self.write.lock().unwrap();
+ match error {
+ None => conn.execute(
+ "UPDATE remote_hosts SET last_sync_at = ?2, last_sync_error = NULL WHERE name = ?1",
+ params![name, now_ms()],
+ )?,
+ Some(e) => conn.execute(
+ "UPDATE remote_hosts SET last_sync_error = ?2 WHERE name = ?1",
+ params![name, e],
+ )?,
+ };
+ Ok(())
+ }
+
+ /// 每个远程 host 的库内会话数(Remote hosts 面板;不滤 archived,
+ /// 与 locations 面板的 counts_by_path_prefix 同口径)
+ pub fn host_counts(&self) -> Result<HashMap<String, i64>> {
+ let conn = self.read.lock().unwrap();
+ let mut stmt = conn
+ .prepare_cached("SELECT host, COUNT(*) FROM sessions WHERE host != '' GROUP BY host")?;
+ let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?;
+ Ok(rows.flatten().collect())
+ }
+
+ /// 索引库文件所在目录(远程缓存 `remotes/<host>` 挂在它下面)。
+ /// 打开哪个库就用哪个库旁边的缓存——GUI 与 scan CLI 的 --tmp 隔离库
+ /// 由此天然分开,互不读写对方的缓存树
+ pub fn db_dir(&self) -> Option<std::path::PathBuf> {
+ self.path.parent().map(|p| p.to_path_buf())
+ }
+
/// 恢复初始:清空全部 location 偏离(自定义、被移除预设与停用状态)。
pub fn clear_location_overrides(&self) -> Result<()> {
let conn = self.write.lock().unwrap();
@@ -1315,7 +1445,7 @@ impl Store {
const SESSION_COLS: &str =
"s.key, s.agent_id, s.native_id, s.title, s.project_path, s.project_name,
s.git_branch, s.created_at, s.updated_at, s.message_count, s.tokens_used, s.model, s.source,
- s.archived, s.file_path, s.file_size, COALESCE(u.favorite,0), COALESCE(u.pinned,0)";
+ s.archived, s.file_path, s.file_size, COALESCE(u.favorite,0), COALESCE(u.pinned,0), s.host";
const ROOT_WHEN_HIDING_ARCHIVED: &str = "(s.parent_key = '' OR NOT EXISTS (
SELECT 1 FROM sessions p WHERE p.key = s.parent_key AND p.archived = 0
@@ -1342,7 +1472,7 @@ const ROOT_SESSION_COLS_ACTIVE: &str =
s.message_count + COALESCE((SELECT SUM(c.message_count) FROM sessions c
WHERE c.parent_key = s.key AND c.archived = 0), 0),
s.tokens_used, s.model, s.source, s.archived, s.file_path, s.file_size,
- COALESCE(u.favorite,0), COALESCE(u.pinned,0)";
+ COALESCE(u.favorite,0), COALESCE(u.pinned,0), s.host";
const ROOT_SESSION_COLS_ALL: &str =
"s.key, s.agent_id, s.native_id, s.title, s.project_path, s.project_name,
s.git_branch, s.created_at,
@@ -1351,7 +1481,7 @@ const ROOT_SESSION_COLS_ALL: &str =
s.message_count + COALESCE((SELECT SUM(c.message_count) FROM sessions c
WHERE c.parent_key = s.key), 0),
s.tokens_used, s.model, s.source, s.archived, s.file_path, s.file_size,
- COALESCE(u.favorite,0), COALESCE(u.pinned,0)";
+ COALESCE(u.favorite,0), COALESCE(u.pinned,0), s.host";
fn child_filter_sql(
filter: &SessionFilter,
@@ -1423,6 +1553,7 @@ fn row_to_meta(r: &rusqlite::Row<'_>) -> rusqlite::Result<SessionMeta> {
size_bytes: r.get(15)?,
favorite: r.get::<_, i64>(16)? == 1,
pinned: r.get::<_, i64>(17)? == 1,
+ host: r.get(18)?,
})
}
@@ -1476,8 +1607,8 @@ fn upsert_session(tx: &rusqlite::Transaction<'_>, m: &SessionMeta, file_mtime: i
tx.execute(
"INSERT INTO sessions(key, agent_id, native_id, title, project_path, project_name,
git_branch, created_at, updated_at, message_count, tokens_used, model, source,
- archived, file_path, file_size, file_mtime, unknown_lines)
- VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,0)
+ archived, file_path, file_size, file_mtime, unknown_lines, host)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,0,?18)
ON CONFLICT(key) DO UPDATE SET
title=excluded.title, project_path=excluded.project_path,
project_name=excluded.project_name, git_branch=excluded.git_branch,
@@ -1485,7 +1616,7 @@ fn upsert_session(tx: &rusqlite::Transaction<'_>, m: &SessionMeta, file_mtime: i
message_count=excluded.message_count, tokens_used=excluded.tokens_used,
model=excluded.model, source=excluded.source, archived=excluded.archived,
file_path=excluded.file_path, file_size=excluded.file_size,
- file_mtime=excluded.file_mtime",
+ file_mtime=excluded.file_mtime, host=excluded.host",
params![
m.key,
m.agent.as_str(),
@@ -1504,6 +1635,7 @@ fn upsert_session(tx: &rusqlite::Transaction<'_>, m: &SessionMeta, file_mtime: i
m.file_path,
m.size_bytes,
file_mtime,
+ m.host,
],
)?;
Ok(())
diff --git a/crates/wake-core/src/lib.rs b/crates/wake-core/src/lib.rs
index 704ba9c..0b51c76 100644
--- a/crates/wake-core/src/lib.rs
+++ b/crates/wake-core/src/lib.rs
@@ -1,6 +1,7 @@
pub mod adapters;
pub mod db;
pub mod models;
+pub mod remote;
pub mod scanner;
pub mod services;
pub mod watcher;
diff --git a/crates/wake-core/src/models.rs b/crates/wake-core/src/models.rs
index 647c716..d5013b6 100644
--- a/crates/wake-core/src/models.rs
+++ b/crates/wake-core/src/models.rs
@@ -171,10 +171,17 @@ impl AgentId {
/// 会话元数据 —— 列表页/索引库统一模型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMeta {
- /// 全局唯一键: `{agent}:{native_id}`
+ /// 全局唯一键: 本地 `{agent}:{native_id}`,远程 `{agent}:{host}:{native_id}`。
+ /// agent 恒为首段(scanner 的易主检测按 `split(':').next()` 取 agent);
+ /// host 段只由 adapters::remote 的装饰器在解析出口插入,adapter 本体
+ /// 永远生产本地格式
pub key: String,
- /// 原生会话 id(resume 用)
+ /// 原生会话 id(resume 用;不含 host 段)
pub id: String,
+ /// 远程 host 名(Settings 里配置的 SSH 目标);空 = 本地会话。
+ /// 只由 RemoteAdapter 装饰器填充,各家 adapter 构造时一律留空
+ #[serde(default)]
+ pub host: String,
pub agent: AgentId,
pub title: String,
pub project_path: String,
@@ -439,3 +446,70 @@ pub const MAX_TITLE: usize = 80;
/// 无标题会话的占位标题(quickMeta 守卫与 adapters 共用,防半/全角漂移)
pub const UNTITLED: &str = "Untitled";
+
+/// 会话 key 的唯一构造点:本地 `{agent}:{native_id}`,远程
+/// `{agent}:{host}:{native_id}`。scanner 的墓碑查询、watcher 的幸存者反查、
+/// 远程装饰器的 key 改写都走这里——"远程 key 长什么样"只此一处知识。
+/// (十四家 adapter 的本地两段构造保留各自 `format!`,它们从不涉及 host。)
+pub fn session_key(agent: AgentId, host: &str, native_id: &str) -> String {
+ if host.is_empty() {
+ format!("{}:{native_id}", agent.as_str())
+ } else {
+ format!("{}:{host}:{native_id}", agent.as_str())
+ }
+}
+
+/// session_key 的逆:key 属于该 (agent, host) 实例时返回 native_id,否则
+/// None。watcher 的幸存者反查用它按实例过滤,零分配。
+pub fn strip_key_prefix<'a>(key: &'a str, agent: AgentId, host: &str) -> Option<&'a str> {
+ let rest = key.strip_prefix(agent.as_str())?.strip_prefix(':')?;
+ if host.is_empty() {
+ // 本地两段 key;含 ':' 的余段是别的 host 的三段 key,不归本实例。
+ // (native_id 自身带 ':' 的 agent 当前不存在,UUID/时间戳系文件名)
+ (!rest.contains(':')).then_some(rest)
+ } else {
+ rest.strip_prefix(host)?.strip_prefix(':')
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn session_key_roundtrip() {
+ let local = session_key(AgentId::ClaudeCode, "", "u1");
+ assert_eq!(local, "claude-code:u1");
+ assert_eq!(
+ strip_key_prefix(&local, AgentId::ClaudeCode, ""),
+ Some("u1")
+ );
+
+ let remote = session_key(AgentId::ClaudeCode, "devbox", "u1");
+ assert_eq!(remote, "claude-code:devbox:u1");
+ assert_eq!(
+ strip_key_prefix(&remote, AgentId::ClaudeCode, "devbox"),
+ Some("u1")
+ );
+ }
+
+ #[test]
+ fn strip_key_prefix_rejects_wrong_instance() {
+ // 本地实例不认远程 key(余段带 host 冒号)
+ assert_eq!(
+ strip_key_prefix("claude-code:devbox:u1", AgentId::ClaudeCode, ""),
+ None
+ );
+ // 远程实例不认本地 key,也不认别家 host——含 host 是另一 host 前缀的
+ assert_eq!(
+ strip_key_prefix("claude-code:u1", AgentId::ClaudeCode, "devbox"),
+ None
+ );
+ assert_eq!(
+ strip_key_prefix("claude-code:devbox2:u1", AgentId::ClaudeCode, "devbox"),
+ None
+ );
+ // agent 段不匹配
+ assert_eq!(strip_key_prefix("codex:u1", AgentId::ClaudeCode, ""), None);
+ }
+}
diff --git a/crates/wake-core/src/remote.rs b/crates/wake-core/src/remote.rs
new file mode 100644
index 0000000..fb964a6
--- /dev/null
+++ b/crates/wake-core/src/remote.rs
@@ -0,0 +1,325 @@
+//! 远程 host 的会话聚合(SSH,2026-09-01 阶段 1)。
+//!
+//! 形态:**同步到本地缓存,而不是远程直读**——`rsync` 把远程 home 下的会话
+//! 数据树按白名单镜像到 `<索引库目录>/remotes/<host>/`,缓存树保持远程 home
+//! 的相对布局,由 `adapters::remote::RemoteAdapter`(装饰器)以各家
+//! `with_custom_root` 挂进 roster。adapter/解析器/FTS 对远程零感知。
+//!
+//! shell out 到系统 `ssh`/`rsync` 而不用 SSH 库:`~/.ssh/config` 的别名、
+//! ProxyJump、IdentityAgent、ControlMaster 全部免费继承。`BatchMode=yes`
+//! 确保 GUI 进程(无 TTY)绝不挂在交互认证上——密钥要么已在 agent 里,
+//! 要么明确失败并把 stderr 记进 `remote_hosts.last_sync_error`。
+//!
+//! 同步跑在**独立于扫描的线程**(Workbench::spawn_remote_sync):本地扫描
+//! 不等网络,不可达 host 只拖慢自己;缓存落盘由 watcher 增量收编,同步
+//! 完成事件再补一轮增量兜底。
+//!
+//! 白名单只含**会话数据与其侧档**,绝不同步凭证(`.claude` 顶层、
+//! `.codex/auth.json`、`.gemini/oauth_creds.json`、opencode 的 auth.json
+//! 都不在名单上)。新增 adapter 必须在 `REMOTE_LAYOUTS` 补一行,契约测试
+//! 卡全家覆盖。
+
+use crate::db::Store;
+use crate::models::AgentId;
+use std::path::{Path, PathBuf};
+
+/// 一家 agent 在远程 home 下的数据布局。
+pub struct RemoteAgentLayout {
+ pub agent: AgentId,
+ /// 缓存树内交给 `with_custom_root` 的目录(相对缓存根 = 相对远程 home)。
+ /// 必须选"整形判据在目录**不存在**时也落到正确形态"的那一层——同步是
+ /// 异步的,实例构造时缓存树可能还没落盘(各家判据见其 with_custom_root)
+ pub mount: &'static str,
+ /// rsync 白名单源(相对远程 home 的 POSIX 路径;目录整树,文件单拉)。
+ /// SQLite 库连 `-wal` 一起拉(数据在 wal 里),`-shm` 是运行时产物不拉
+ ///(缺了 sqlite_ro 的 copy 梯度兜底)
+ pub sync_paths: &'static [&'static str],
+}
+
+/// 十四家的远程布局。远程主机按 Linux/macOS 默认路径假设(两平台一致,
+/// 均为 home 相对;OpenCode 的 XDG 变体、CODEX_HOME 这类 env 覆盖在远端
+/// 探测不到,阶段 1 不支持非默认远程布局)。
+pub const REMOTE_LAYOUTS: &[RemoteAgentLayout] = &[
+ RemoteAgentLayout {
+ agent: AgentId::ClaudeCode,
+ mount: ".claude/projects",
+ sync_paths: &[".claude/projects"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Codex,
+ // home 形态:sessions/archived_sessions/state_5.sqlite 全相对派生
+ mount: ".codex",
+ sync_paths: &[
+ ".codex/sessions",
+ ".codex/archived_sessions",
+ ".codex/state_5.sqlite",
+ ".codex/state_5.sqlite-wal",
+ ],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Qoder,
+ mount: ".qoder/projects",
+ sync_paths: &[".qoder/projects"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Copilot,
+ // 目录层:db = <mount>/session-store.db(is_file 判据对未同步目录失真)
+ mount: ".copilot",
+ sync_paths: &[".copilot/session-store.db", ".copilot/session-store.db-wal"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Cursor,
+ mount: ".cursor/projects",
+ sync_paths: &[".cursor/projects"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Opencode,
+ // custom_db_paths 对目录给出 stable + next 两个固定候选
+ mount: ".local/share/opencode",
+ sync_paths: &[
+ ".local/share/opencode/opencode.db",
+ ".local/share/opencode/opencode.db-wal",
+ ".local/share/opencode/opencode-next.db",
+ ".local/share/opencode/opencode-next.db-wal",
+ ],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Kiro,
+ mount: ".kiro/sessions/cli",
+ sync_paths: &[".kiro/sessions/cli"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Gemini,
+ // tmp 层:projects.json 由 parent 派生(.gemini 顶层有凭证,不整树同步)
+ mount: ".gemini/tmp",
+ sync_paths: &[".gemini/tmp", ".gemini/projects.json"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Pi,
+ mount: ".pi/agent/sessions",
+ sync_paths: &[".pi/agent/sessions"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Omp,
+ mount: ".omp/agent/sessions",
+ sync_paths: &[".omp/agent/sessions"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Grok,
+ // sessions 目录名判据 → home=parent,summary/chat_history 都在树内
+ mount: ".grok/sessions",
+ sync_paths: &[".grok/sessions"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Kimi,
+ mount: ".kimi-code/sessions",
+ sync_paths: &[".kimi-code/sessions", ".kimi-code/session_index.jsonl"],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Antigravity,
+ // 库所在目录层(is_file 判据对未同步目录失真,目录层恒正确)
+ mount: ".gemini/antigravity-cli",
+ sync_paths: &[
+ ".gemini/antigravity-cli/conversation_summaries.db",
+ ".gemini/antigravity-cli/conversation_summaries.db-wal",
+ ],
+ },
+ RemoteAgentLayout {
+ agent: AgentId::Dsh,
+ mount: ".dsh/sessions",
+ sync_paths: &[".dsh/sessions"],
+ },
+];
+
+/// host 名合法性:进 session key 作中段(不能有 ':')、直接作为 ssh/rsync
+/// 目标(不能以 '-' 开头——那会被当作命令行选项,是参数注入面)。允许
+/// `user@host`、别名、IPv4;IPv6 字面量请在 `~/.ssh/config` 里包一个别名。
+pub fn valid_host_name(name: &str) -> bool {
+ name.starts_with(|c: char| c.is_ascii_alphanumeric())
+ && name
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '@'))
+}
+
+/// 删掉 `remotes/` 下不再对应任何已配置 host 的缓存目录。同步进行中被
+/// Remove 的 host,其 rsync 无法取消、会把刚删的目录写回——每轮同步收工
+/// 后按配置表裁决一次,幂等自愈(该目录树只有 Wake 自己写)。
+pub fn purge_orphan_caches(store: &Store) {
+ let Some(db_dir) = store.db_dir() else { return };
+ let known: std::collections::HashSet<String> = store
+ .list_remote_hosts()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|h| h.name)
+ .collect();
+ let Ok(entries) = std::fs::read_dir(db_dir.join("remotes")) else {
+ return;
+ };
+ for entry in entries.flatten() {
+ let name = entry.file_name();
+ if name.to_str().is_none_or(|n| !known.contains(n)) {
+ let _ = std::fs::remove_dir_all(entry.path());
+ }
+ }
+}
+
+/// 单 host 的缓存树(各 host 挂在 `<索引库目录>/remotes/<host>/` 下)。
+pub fn host_cache_dir(db_dir: &Path, host: &str) -> PathBuf {
+ db_dir.join("remotes").join(host)
+}
+
+/// 单 host 的 rsync 参数(不含程序名)。纯函数,单测卡命令形状。
+/// `-R`(--relative)让 `host:./<相对路径>` 在目标重建相对布局;
+/// `--delete` 让远程删除传播到缓存(watcher 收 Remove 后清库内行);
+/// 缺失的源(该家没装)由 rsync 跳过并以 exit 23 报部分传输,视为软成功。
+pub fn rsync_args(host: &str, dest: &Path) -> Vec<String> {
+ let mut args = vec![
+ "-az".to_string(),
+ "-R".to_string(),
+ "--delete".to_string(),
+ // Grok 自家的搜索索引库,量大且 Wake 不读
+ "--exclude=session_search.sqlite*".to_string(),
+ "--timeout=120".to_string(),
+ "-e".to_string(),
+ "ssh -oBatchMode=yes -oConnectTimeout=10".to_string(),
+ ];
+ for layout in REMOTE_LAYOUTS {
+ for path in layout.sync_paths {
+ args.push(format!("{host}:./{path}"));
+ }
+ }
+ args.push(dest.to_string_lossy().to_string());
+ args
+}
+
+/// 同步指定 host(调用方给"全部启用的"或单个新加的)。**绝不 panic、绝不
+/// Err**——任何失败只记进 `remote_hosts.last_sync_error`,面板展示,后续
+/// 扫描照常消费既有缓存。各 host 的 rsync 彼此独立(纯网络等待),并行跑,
+/// 总耗时 = 最慢一台而非各台之和;状态写库经 write Mutex 天然串行。
+pub fn sync_hosts(store: &Store, names: &[String]) {
+ let Some(db_dir) = store.db_dir() else {
+ return;
+ };
+ std::thread::scope(|scope| {
+ for name in names {
+ let dest = host_cache_dir(&db_dir, name);
+ scope.spawn(move || {
+ // 已入库的 host 也再卡一道:老库可能被未来版本写入过更宽的名字
+ let error = if valid_host_name(name) {
+ run_rsync(name, &dest).err()
+ } else {
+ Some("invalid host name".to_string())
+ };
+ let _ = store.record_remote_sync(name, error.as_deref());
+ });
+ }
+ });
+}
+
+/// 起 rsync 并归类退出码。0 = 全量成功;23(部分源缺失,该家远端没装)与
+/// 24(传输中源文件消失)是多源白名单同步的常态,同样算成功。
+fn run_rsync(host: &str, dest: &Path) -> Result<(), String> {
+ if let Err(e) = std::fs::create_dir_all(dest) {
+ return Err(format!("cannot create cache dir {}: {e}", dest.display()));
+ }
+ let output = std::process::Command::new("rsync")
+ .args(rsync_args(host, dest))
+ .stdin(std::process::Stdio::null())
+ .output();
+ let output = match output {
+ Ok(o) => o,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ return Err("rsync not found on PATH — install rsync to sync remote hosts".into());
+ }
+ Err(e) => return Err(format!("failed to run rsync: {e}")),
+ };
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ match output.status.code() {
+ // 24 = 传输中源文件消失(agent 正在写,下轮自愈)
+ Some(0) | Some(24) => Ok(()),
+ // 23 是"部分传输失败"泛码:白名单里的源在远端不存在(那台只装了
+ // 部分 agent)是常态,豁免;但权限/读写错误同样报 23,把它们记成功
+ // 会隐藏真实缺数据——只有 stderr 里的错误行**全部**是 ENOENT 才算软
+ // 成功(总结行不算错误行;openrsync/rsync 的缺源消息都带这句话)
+ Some(23)
+ if stderr
+ .lines()
+ .filter(|l| l.contains("rsync") && (l.contains("error") || l.contains("failed")))
+ .filter(|l| !l.contains("some files/attrs were not transferred"))
+ .all(|l| l.contains("No such file or directory")) =>
+ {
+ Ok(())
+ }
+ code => {
+ // 取末几行(rsync 把决定性错误留在最后),字符封顶防单行巨量输出
+ let mut lines: Vec<&str> = stderr.trim().lines().rev().take(3).collect();
+ lines.reverse();
+ let tail: String = lines.join("; ").chars().take(500).collect();
+ Err(match code {
+ Some(c) => format!("rsync exited with {c}: {tail}"),
+ None => format!("rsync terminated by signal: {tail}"),
+ })
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn layouts_cover_every_agent_exactly_once() {
+ // 新增 agent 忘了补远程布局表,这里就是第一道报警
+ let mut seen = std::collections::HashSet::new();
+ for layout in REMOTE_LAYOUTS {
+ assert!(
+ seen.insert(layout.agent),
+ "duplicate layout {:?}",
+ layout.agent
+ );
+ assert!(!layout.sync_paths.is_empty());
+ for path in layout.sync_paths {
+ assert!(!path.starts_with('/'), "sync path must be home-relative");
+ assert!(!path.contains(".."));
+ }
+ assert!(!layout.mount.starts_with('/'));
+ }
+ for agent in AgentId::ALL {
+ assert!(seen.contains(&agent), "missing remote layout for {agent:?}");
+ }
+ }
+
+ #[test]
+ fn host_name_validation_blocks_injection() {
+ assert!(valid_host_name("devbox"));
+ assert!(valid_host_name("[email protected]"));
+ assert!(valid_host_name("my-host.example.com"));
+ assert!(valid_host_name("a"));
+ // 选项注入与 key 分隔符
+ assert!(!valid_host_name("-oProxyCommand=evil"));
+ assert!(!valid_host_name(""));
+ assert!(!valid_host_name("host:22"));
+ assert!(!valid_host_name("host name"));
+ assert!(!valid_host_name("host/../x"));
+ assert!(!valid_host_name(".hidden"));
+ }
+
+ #[test]
+ fn rsync_args_shape() {
+ let args = rsync_args("devbox", Path::new("/tmp/cache/devbox"));
+ assert_eq!(args[0], "-az");
+ assert!(args.contains(&"-R".to_string()));
+ assert!(args.contains(&"--delete".to_string()));
+ assert!(args
+ .iter()
+ .any(|a| a == "ssh -oBatchMode=yes -oConnectTimeout=10"));
+ // 源都是 host:./ 锚定的 home 相对路径
+ assert!(args.contains(&"devbox:./.claude/projects".to_string()));
+ assert!(args.contains(&"devbox:./.codex/state_5.sqlite".to_string()));
+ // 目标在最后
+ assert_eq!(args.last().unwrap(), "/tmp/cache/devbox");
+ // 凭证绝不在名单上
+ assert!(!args.iter().any(|a| a.contains("auth.json")));
+ assert!(!args.iter().any(|a| a.contains("oauth_creds")));
+ }
+}
diff --git a/crates/wake-core/src/scanner.rs b/crates/wake-core/src/scanner.rs
index ee1decb..69375d7 100644
--- a/crates/wake-core/src/scanner.rs
+++ b/crates/wake-core/src/scanner.rs
@@ -135,10 +135,11 @@ fn run_scan_inner(
.into_iter()
// 墓碑双轨:物理路径之外还按逻辑会话(key)屏蔽——多 location 下
// 删除只 trash 了胜者文件,别的 location 里的副本不得复活它
- //(2026-08-24 Codex review P1)
+ //(2026-08-24 Codex review P1)。key 按实例 host 构造(远程三段)
+ // ——阶段 1 远程禁删故无远程墓碑,但格式先写对,放开时不欠债
.filter(|r| {
!store.is_tombstoned(&r.file_path)
- && !store.is_key_tombstoned(&format!("{}:{}", r.agent.as_str(), r.native_id))
+ && !store.is_key_tombstoned(&session_key(r.agent, adapter.host(), &r.native_id))
})
// 无任何根认领的引用(越界枚举或合成测试)保守放行给枚举者;
// 过滤只裁决"确有更深的根拥有它"的情形
@@ -149,13 +150,16 @@ fn run_scan_inner(
// 同家同 ID 去重:同一会话在默认根与自定义根各有一份副本时,两个文件会
// 每轮轮流改写同一行(key 相同,file_path 摇摆)。候选按 (mtime 新者,
// 平局路径字典序小者) 排序,首位入队,其余留作**解析失败的回退顺位**
- // ——胜者副本截断/损坏时,不能让整个会话从索引消失(Codex review P2)
- let mut candidates: std::collections::HashMap<(AgentId, String), Vec<(usize, SessionFileRef)>> =
+ // ——胜者副本截断/损坏时,不能让整个会话从索引消失(Codex review P2)。
+ // 去重域即 session_key(agent, 实例 host, native_id)——直接以它为键,
+ // "去重域与最终 key 的分段一致"就结构性成立:两台机器各自续跑过的
+ // 同 UUID 会话是两条独立会话,跨 host 按 mtime 互吞会让一台的凭空消失
+ let mut candidates: std::collections::HashMap<String, Vec<(usize, SessionFileRef)>> =
std::collections::HashMap::new();
for (ix, refs) in per_adapter.iter().enumerate() {
for r in refs {
candidates
- .entry((r.agent, r.native_id.clone()))
+ .entry(session_key(r.agent, adapters[ix].host(), &r.native_id))
.or_default()
.push((ix, r.clone()));
}
@@ -167,10 +171,10 @@ fn run_scan_inner(
.then_with(|| a.file_path.cmp(&b.file_path))
});
}
- for refs in &mut per_adapter {
+ for (ix, refs) in per_adapter.iter_mut().enumerate() {
refs.retain(|r| {
candidates
- .get(&(r.agent, r.native_id.clone()))
+ .get(&session_key(r.agent, adapters[ix].host(), &r.native_id))
.is_none_or(|v| v[0].1.file_path == r.file_path)
});
}
@@ -237,7 +241,7 @@ fn run_scan_inner(
.as_ref()
.and_then(|m| m.get(&r.file_path).cloned());
let fallbacks = candidates
- .get(&(r.agent, r.native_id.clone()))
+ .get(&session_key(r.agent, adapter.host(), &r.native_id))
.filter(|v| v.len() > 1)
.map(|v| v[1..].to_vec())
.unwrap_or_default();
@@ -529,18 +533,20 @@ pub fn scan_files(
}
// 按**实例**分组,不是按 agent:自定义 location 让同 agent 有多实例,
// 文件必须交给拥有其根的那个(gemini/kimi 的 cwd 反查、codex 的 state DB
- // 都是实例相对侧档);quick_meta 是整库查询,每组只查一次,不能逐文件调
+ // 都是实例相对侧档);quick_meta 是整库查询,每组只查一次,不能逐文件调。
+ // 先路由再查 key 墓碑——墓碑 key 按归属实例的 host 构造(与全量扫描同式)
let mut by_adapter: std::collections::HashMap<usize, Vec<SessionFileRef>> =
std::collections::HashMap::new();
for r in refs {
- if store.is_tombstoned(&r.file_path)
- || store.is_key_tombstoned(&format!("{}:{}", r.agent.as_str(), r.native_id))
- {
+ if store.is_tombstoned(&r.file_path) {
continue;
}
let Some(ix) = crate::adapters::adapter_ix_for(adapters, r.agent, &r.file_path) else {
continue;
};
+ if store.is_key_tombstoned(&session_key(r.agent, adapters[ix].host(), &r.native_id)) {
+ continue;
+ }
by_adapter.entry(ix).or_default().push(r);
}
diff --git a/crates/wake-core/src/services/terminal/macos.rs b/crates/wake-core/src/services/terminal/macos.rs
index cc99654..f25e38b 100644
--- a/crates/wake-core/src/services/terminal/macos.rs
+++ b/crates/wake-core/src/services/terminal/macos.rs
@@ -3,8 +3,8 @@
//! 策略(dir/file 分发、路径过滤、线程化)在 mod.rs,这里只做动作本身。
use super::{
- cli_not_found_error, percent_encode, pipe_to, posix_quote, resolve_cli, resume_args,
- session_bin, spawn_and_reap, ResumeOutcome,
+ cli_not_found_error, percent_encode, pipe_to, resolve_cli, resume_args, session_bin, sh_quote,
+ spawn_and_reap, ResumeOutcome,
};
use crate::models::{AgentId, SessionMeta};
use std::collections::HashMap;
@@ -382,23 +382,19 @@ fn launch_kooky_cli(meta: &SessionMeta) -> ResumeOutcome {
let Some(exe) = resolve_cli(bin) else {
return fail(String::new(), cli_not_found_error(meta.agent, bin));
};
- let cmd = std::iter::once(exe.as_str())
- .chain(args.iter().map(|s| s.as_str()))
- .map(posix_quote)
- .collect::<Vec<_>>()
- .join(" ");
+ let cmd = super::sh_command_line(exe.as_str(), &args, None);
let shown = format!(
"kooky-cli open --cwd {} -e {}",
- posix_quote(&meta.project_path),
- posix_quote(&cmd)
+ sh_quote(&meta.project_path),
+ sh_quote(&cmd)
);
// 手动兜底的是能直接粘进任何终端跑的那条(kooky 的 --cwd 得自己 cd 回来)
let cwd_ok = !meta.project_path.is_empty() && Path::new(&meta.project_path).is_dir();
- let manual = if cwd_ok {
- format!("cd {} && {cmd}", posix_quote(&meta.project_path))
- } else {
- cmd.clone()
- };
+ let manual = super::sh_command_line(
+ exe.as_str(),
+ &args,
+ cwd_ok.then_some(meta.project_path.as_str()),
+ );
let bail = |reason: String| {
fail(
shown.clone(),
@@ -671,6 +667,7 @@ mod tests {
let meta = crate::models::SessionMeta {
key: "claude-code:not-a-uuid".into(),
id: "not-a-uuid".into(),
+ host: String::new(),
agent: crate::models::AgentId::ClaudeCode,
title: String::new(),
project_path: String::new(),
diff --git a/crates/wake-core/src/services/terminal/mod.rs b/crates/wake-core/src/services/terminal/mod.rs
index 18aa54a..c9843ad 100644
--- a/crates/wake-core/src/services/terminal/mod.rs
+++ b/crates/wake-core/src/services/terminal/mod.rs
@@ -4,7 +4,7 @@
//! 导出同形接口(TerminalApp 变体集合各异,UI 只遍历不点名)。
//!
//! POSIX 双端(macOS/Linux)的共享层在 posix.rs(login shell 探测、
-//! posix_quote 拼装);Windows 的这些前提全不成立(无 login shell、引号
+//! sh_quote 拼装);Windows 的这些前提全不成立(无 login shell、引号
//! 不是 POSIX 规则、命令方言按终端宿主分 cmd/PowerShell 两派),故
//! probe_clis / compose_command / launch_shell 三个接缝按平台各取一份,
//! 策略流程本身不分叉。
@@ -33,9 +33,6 @@ mod posix;
use posix::{compose_command, probe_clis};
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub(crate) use posix::{percent_encode, pipe_to};
-// posix_quote 只有 macos.rs 消费(kooky CLI 的命令拼装),Linux 上中转会空挂
-#[cfg(target_os = "macos")]
-pub(crate) use posix::posix_quote;
#[cfg(target_os = "windows")]
mod windows;
@@ -169,6 +166,115 @@ fn resume_args(agent: AgentId, id: &str) -> Option<(Vec<String>, bool)> {
}
}
+/// POSIX 单引号 quote 的唯一实现,不设平台 cfg:本地侧 posix.rs/macos.rs
+/// 拼终端命令用它,远程侧 ssh_resume_command 拼**发给远端 shell** 的命令也
+/// 用它(远端恒 POSIX,与本地平台无关,Windows 构建同样编译)。安全字符集
+/// 含 `@` 只为 `user@host` 免引号展示——加引号同样合法,纯观感。
+pub(crate) fn sh_quote(s: &str) -> String {
+ if !s.is_empty()
+ && s.chars()
+ .all(|c| c.is_ascii_alphanumeric() || "_-./:=@".contains(c))
+ {
+ return s.to_string();
+ }
+ format!("'{}'", s.replace('\'', r"'\''"))
+}
+
+/// `cd <cwd> && <bin> <args…>` 全 quote 的一条 POSIX 命令行——本地终端启动
+/// (posix::compose_command)、kooky CLI 管道、远程 ssh 内层命令共用的唯一
+/// 拼装点。与 sh_quote 同理不设 cfg。
+pub(crate) fn sh_command_line(bin: &str, args: &[String], cwd: Option<&str>) -> String {
+ let core = std::iter::once(bin)
+ .chain(args.iter().map(|s| s.as_str()))
+ .map(sh_quote)
+ .collect::<Vec<_>>()
+ .join(" ");
+ match cwd {
+ Some(dir) => format!("cd {} && {core}", sh_quote(dir)),
+ None => core,
+ }
+}
+
+/// 远程会话的 resume 命令(阶段 1 只复制到剪贴板,不代起终端):
+/// `ssh -t <host> 'cd <远程cwd> && <agent CLI> <resume args>'`。
+/// CLI 用**裸名**交远端 PATH 解析——本地 resolve_cli 的绝对路径对远端无意义,
+/// 远端没装该 CLI 时由远端 shell 报 command not found(本地无从探测)。
+/// 内层永远是 POSIX 方言;外层整条给用户贴进本地终端(POSIX/PowerShell 的
+/// 单引号语义都兼容,cmd.exe 不支持)。
+pub fn ssh_resume_command(meta: &SessionMeta) -> Option<String> {
+ if meta.host.is_empty() {
+ return None;
+ }
+ let (args, _requires_cwd) = resume_args(meta.agent, &meta.id)?;
+ let bin = session_bin(meta)?;
+ // cwd 是远程路径,本地 is_dir 判据无意义:非空就 cd,空则落 ssh 默认 home
+ let cwd = (!meta.project_path.is_empty()).then_some(meta.project_path.as_str());
+ let inner = sh_command_line(bin, &args, cwd);
+ Some(format!(
+ "ssh -t {} {}",
+ sh_quote(&meta.host),
+ sh_quote(&inner)
+ ))
+}
+
+/// 一个会话的可用恢复目标。"这个会话能怎么恢复"的知识只在这一层:本地是
+/// 按 agent 过滤的终端/深链 app,远程(阶段 1)只有复制 ssh 命令一项——
+/// 阶段 2 加一键 ssh 直开时在 resume_targets 里多返回一项,UI 零改动。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ResumeTarget {
+ App(TerminalApp),
+ /// 把 `ssh -t <host> '…resume…'` 整条放进剪贴板(远端 CLI 是否存在
+ /// 本地无从探测,贴到终端后由远端 shell 裁决)
+ CopySshCommand,
+}
+
+pub fn resume_targets(meta: &SessionMeta) -> Vec<ResumeTarget> {
+ if meta.host.is_empty() {
+ terminals_for(meta.agent)
+ .into_iter()
+ .map(ResumeTarget::App)
+ .collect()
+ } else {
+ vec![ResumeTarget::CopySshCommand]
+ }
+}
+
+pub fn resume_target(meta: &SessionMeta, target: ResumeTarget) -> ResumeOutcome {
+ match target {
+ ResumeTarget::App(term) => resume_session_in(meta, term),
+ ResumeTarget::CopySshCommand => copy_ssh_outcome(meta),
+ }
+}
+
+fn copy_ssh_outcome(meta: &SessionMeta) -> ResumeOutcome {
+ let Some(command) = ssh_resume_command(meta) else {
+ // 十四家全有 resume_args,此臂当前不可达;护栏语义同 resume_session_in
+ return ResumeOutcome {
+ ok: false,
+ command: String::new(),
+ error: Some(format!(
+ "Resume isn't supported for {} yet",
+ meta.agent.display_name()
+ )),
+ };
+ };
+ if platform::copy_to_clipboard(&command) {
+ ResumeOutcome {
+ ok: true,
+ command,
+ error: None,
+ }
+ } else {
+ ResumeOutcome {
+ ok: false,
+ command: command.clone(),
+ error: Some(format!(
+ "Couldn't write to clipboard. Run manually: {command}"
+ )),
+ }
+ }
+}
+
pub fn resume_session_in(meta: &SessionMeta, term: TerminalApp) -> ResumeOutcome {
// 深链类目标(macOS 的 Kooky / Claude Desktop / Codex Desktop)由平台
// 整锅接管,不走 shell 命令构建;新增非 shell 目标在平台的
@@ -361,4 +467,60 @@ mod tests {
"Agent CLI `opencode2` for OpenCode was not found on PATH — is it installed and available to Wake?"
);
}
+
+ fn remote_meta(agent: AgentId, id: &str, cwd: &str) -> crate::models::SessionMeta {
+ crate::models::SessionMeta {
+ key: format!("{}:devbox:{id}", agent.as_str()),
+ id: id.into(),
+ host: "devbox".into(),
+ agent,
+ title: String::new(),
+ project_path: cwd.into(),
+ project_name: String::new(),
+ file_path: String::new(),
+ created_at: 0,
+ updated_at: 0,
+ message_count: 0,
+ size_bytes: 0,
+ git_branch: None,
+ model: None,
+ tokens_used: None,
+ archived: false,
+ source: None,
+ favorite: false,
+ pinned: false,
+ }
+ }
+
+ #[test]
+ fn ssh_resume_command_quotes_nested_layers() {
+ let meta = remote_meta(AgentId::Codex, "abc-123", "/home/dev/my project");
+ let cmd = super::ssh_resume_command(&meta).unwrap();
+ // 内层 cd 的单引号在外层被 '\'' 转义,整条可直接贴 POSIX shell
+ assert_eq!(
+ cmd,
+ r"ssh -t devbox 'cd '\''/home/dev/my project'\'' && codex resume abc-123'"
+ );
+ }
+
+ #[test]
+ fn ssh_resume_command_variants() {
+ // 无 cwd:落 ssh 默认 home,不产出空 cd
+ let meta = remote_meta(AgentId::ClaudeCode, "u-1", "");
+ assert_eq!(
+ super::ssh_resume_command(&meta).unwrap(),
+ "ssh -t devbox 'claude --resume u-1'"
+ );
+ // opencode2 会话换二进制,与本地 resume 同一分流
+ let mut meta = remote_meta(AgentId::Opencode, "s1", "/w");
+ meta.source = Some("opencode2".into());
+ assert_eq!(
+ super::ssh_resume_command(&meta).unwrap(),
+ "ssh -t devbox 'cd /w && opencode2 --session s1'"
+ );
+ // 本地会话不产出 ssh 命令
+ let mut meta = remote_meta(AgentId::Codex, "abc", "/w");
+ meta.host = String::new();
+ assert!(super::ssh_resume_command(&meta).is_none());
+ }
}
diff --git a/crates/wake-core/src/services/terminal/posix.rs b/crates/wake-core/src/services/terminal/posix.rs
index bd85081..d931751 100644
--- a/crates/wake-core/src/services/terminal/posix.rs
+++ b/crates/wake-core/src/services/terminal/posix.rs
@@ -65,35 +65,17 @@ fn parse_probe_output(stdout: &[u8], requested: &[&str]) -> HashMap<String, Stri
found
}
-/// POSIX 单引号 quote
-pub(crate) fn posix_quote(s: &str) -> String {
- if !s.is_empty()
- && s.chars()
- .all(|c| c.is_ascii_alphanumeric() || "_-./:=".contains(c))
- {
- return s.to_string();
- }
- format!("'{}'", s.replace('\'', r"'\''"))
-}
-
/// 展示/剪贴板/启动共用的一条可执行命令。POSIX 双端只有一种 shell 方言,
/// 与宿主无关,`_term` 只为对齐 Windows 的同名接缝(那边按宿主分
-/// cmd/PowerShell 两派,见 windows.rs)
+/// cmd/PowerShell 两派,见 windows.rs);拼装本体在 mod.rs 的
+/// sh_command_line(quote 与连接规则的唯一实现,远程 ssh 同用)
pub(super) fn compose_command(
_term: super::TerminalApp,
cli: &str,
args: &[String],
cwd: Option<&str>,
) -> String {
- let core = std::iter::once(cli)
- .chain(args.iter().map(|s| s.as_str()))
- .map(posix_quote)
- .collect::<Vec<_>>()
- .join(" ");
- match cwd {
- Some(dir) => format!("cd {} && {core}", posix_quote(dir)),
- None => core,
- }
+ super::sh_command_line(cli, args, cwd)
}
/// 保守 percent-encode(RFC 3986 unreserved 之外全编;keep_slash 供
diff --git a/crates/wake-core/src/services/terminal/windows.rs b/crates/wake-core/src/services/terminal/windows.rs
index 3450d68..58315ad 100644
--- a/crates/wake-core/src/services/terminal/windows.rs
+++ b/crates/wake-core/src/services/terminal/windows.rs
@@ -1,7 +1,7 @@
//! Windows 平台原语:终端宿主(Windows Terminal / PowerShell / cmd /
//! Alacritty / WezTerm)、回收站(trash crate → IFileOperation)、资源管理器
//! 进入/选中、Win32 剪贴板与 MessageBox。接口与 macos.rs / linux.rs 同形,
-//! 策略在 mod.rs;mod.rs 的三个 POSIX 前提(login shell、posix_quote、单一
+//! 策略在 mod.rs;mod.rs 的三个 POSIX 前提(login shell、sh_quote 方言、单一
//! shell 方言)在本端由 probe_clis / compose_command / launch_shell 接管。
//!
//! 方言分两派:cmd 宿主用 cmd 方言内联注入(raw_arg 直达,无 argv 引号层);
diff --git a/crates/wake-core/src/watcher.rs b/crates/wake-core/src/watcher.rs
index dbdca09..4167959 100644
--- a/crates/wake-core/src/watcher.rs
+++ b/crates/wake-core/src/watcher.rs
@@ -17,6 +17,15 @@ use std::time::Duration;
pub struct SessionWatcher {
watcher: Option<notify::RecommendedWatcher>,
thread: Option<std::thread::JoinHandle<()>>,
+ watched: std::collections::BTreeSet<PathBuf>,
+}
+
+impl SessionWatcher {
+ /// 实际 watch 成功的根(缺目录等失败被静默跳过的不在内)——"挂了哪些"
+ /// 的唯一真话。远程同步收工后据此判断缓存树是否长出了监听外的新根。
+ pub fn watched_roots(&self) -> &std::collections::BTreeSet<PathBuf> {
+ &self.watched
+ }
}
impl Drop for SessionWatcher {
@@ -44,6 +53,7 @@ pub fn resolve_watch_agent<T: Copy>(roots: &[(PathBuf, T)], path: &Path) -> Opti
/// 胜者副本被删后的幸存者上位:按被删 key 反查同家实例枚举里的同 native_id
/// 引用,交常规增量收编(该 key 已无既有行,scan_files 的副本裁决自然放行)。
+/// 期望 key 经 session_key 按实例 host 构造——远程三段 key 也走名字快路径。
/// codex 经 state DB 改写过的 key(thread-id ≠ 文件 native_id)反查不到,由
/// 下一次全量扫描兜底;删除事件罕见,逐家枚举(纯 stat)代价可忽略
pub fn promote_survivors(
@@ -58,23 +68,22 @@ pub fn promote_survivors(
if !seen.insert(key.as_str()) {
continue;
}
- let Some((agent_str, native_id)) = key.split_once(':') else {
- continue;
- };
- let Some(agent) = AgentId::from_str(agent_str) else {
+ let Some(agent) = key.split(':').next().and_then(AgentId::from_str) else {
continue;
};
let mut agent_refs: Vec<SessionFileRef> = Vec::new();
+ let mut by_name: Vec<SessionFileRef> = Vec::new();
for a in adapters.iter().filter(|a| a.agent() == agent) {
+ // host 段对不上的实例整个跳过(本地实例对远程 key、A 机对 B 机):
+ // 名字与解析比对都不可能命中——实例出口的 key 恒带自己的 host
+ let Some(native_id) = strip_key_prefix(key, agent, a.host()) else {
+ continue;
+ };
if let Ok(refs) = a.list_session_files() {
+ by_name.extend(refs.iter().filter(|r| r.native_id == native_id).cloned());
agent_refs.extend(refs);
}
}
- let by_name: Vec<SessionFileRef> = agent_refs
- .iter()
- .filter(|r| r.native_id == native_id)
- .cloned()
- .collect();
if !by_name.is_empty() {
survivors.extend(by_name);
continue;
@@ -122,8 +131,12 @@ pub fn start_watcher(
let (tx, rx) = mpsc::channel::<notify::Result<notify::Event>>();
let mut watcher = notify::recommended_watcher(tx).ok()?;
+ let mut watched = std::collections::BTreeSet::new();
for (root, _) in &roots {
- let _ = watcher.watch(root, RecursiveMode::Recursive);
+ // 失败(常见:目录还不存在,如未同步的远程缓存)跳过不算挂上
+ if watcher.watch(root, RecursiveMode::Recursive).is_ok() {
+ watched.insert(root.clone());
+ }
}
let thread = std::thread::spawn(move || {
@@ -211,5 +224,6 @@ pub fn start_watcher(
Some(SessionWatcher {
watcher: Some(watcher),
thread: Some(thread),
+ watched,
})
}
diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rs
index d200bca..5284dd9 100644
--- a/crates/wake-core/tests/adapter_contracts.rs
+++ b/crates/wake-core/tests/adapter_contracts.rs
@@ -1662,6 +1662,7 @@ fn seq_contract_holds_for_all_agents() {
fn mk_meta(agent: AgentId, key: &str, id: &str, title: &str, source: Option<&str>) -> SessionMeta {
SessionMeta {
+ host: String::new(),
key: key.to_string(),
id: id.to_string(),
agent,
@@ -2170,3 +2171,263 @@ fn adapter_ix_for_routes_to_owning_instance() {
"无根命中回退该 agent 首个实例"
);
}
+
+// ---------------------------------------------------------------- 远程装饰器
+
+/// 远程实例 = 各家 with_custom_root(缓存内挂载点) 包 RemoteAdapter。
+/// 断言两件事:①挂载点整形在**目录不存在时**也不越界——十四家的数据根
+/// 必须全部落在缓存树内,落回真实 home 就会把本地会话错标成远程;
+/// ②key/host 在解析出口统一改写,native id 保持纯净(resume 用)。
+#[test]
+fn remote_adapters_stay_inside_cache_and_rewrite_keys() {
+ let env = setup();
+
+ // ① 空缓存目录(尚未同步)——整形判据全走"不存在"分支。
+ // 模板由调用方传入(roster 唯一构造点的契约,生产侧同式)
+ let templates = wake_core::adapters::create_adapters();
+ let empty = tempfile::tempdir().unwrap();
+ let adapters =
+ wake_core::adapters::remote::create_remote_adapters(&templates, "devbox", empty.path());
+ assert_eq!(adapters.len(), 14, "每家一个远程实例");
+ let cache_prefix = empty.path().to_string_lossy().to_string();
+ for adapter in &adapters {
+ assert_eq!(adapter.host(), "devbox");
+ for root in adapter.data_roots() {
+ let root = root.to_string_lossy();
+ assert!(
+ root.starts_with(&cache_prefix),
+ "{:?} 的远程数据根越界: {root}",
+ adapter.agent()
+ );
+ }
+ // 缺根必须降级为空枚举,不能 Err 截断整轮扫描(契约同默认实例)
+ assert!(adapter
+ .list_session_files()
+ .expect("degrade to empty")
+ .is_empty());
+ }
+
+ // ② 假 HOME 本身就是"远程 home 镜像"的形状——直接当缓存用,
+ // SQLite 型/侧档型(copilot/opencode/antigravity/kimi/dsh)都有数据
+ let home = env._home.path();
+ let adapters = wake_core::adapters::remote::create_remote_adapters(&templates, "devbox", home);
+ let by_agent = |a: AgentId| {
+ adapters
+ .iter()
+ .find(|x| x.agent() == a)
+ .expect("remote instance")
+ };
+
+ let copilot = by_agent(AgentId::Copilot);
+ let refs = copilot.list_session_files().expect("copilot remote list");
+ assert_eq!(refs.len(), 2);
+ let r = refs.iter().find(|r| r.native_id == "cop-0001").unwrap();
+ let parsed = copilot.parse_session(r).expect("copilot remote parse");
+ assert_eq!(parsed.meta.key, "copilot:devbox:cop-0001");
+ assert_eq!(parsed.meta.host, "devbox");
+ assert_eq!(parsed.meta.id, "cop-0001", "native id 不得带 host 段");
+
+ // dsh 的 file_ref 要读首行(zstd 首帧)——装饰器转发后行为不变,
+ // 解析出口再打 host 标
+ let dsh = by_agent(AgentId::Dsh);
+ let r = dsh
+ .file_ref(&env.dsh_log)
+ .expect("dsh remote file_ref reads header");
+ let parsed = dsh.parse_session(&r).expect("dsh remote parse");
+ assert_eq!(parsed.meta.key, "dsh:devbox:dsh-e2e4-0001");
+ assert_eq!(parsed.meta.host, "devbox");
+
+ // transcript 出口同样改写(详情页/导出消费)
+ let t = dsh.parse_transcript(&r).expect("dsh remote transcript");
+ assert_eq!(t.meta.key, "dsh:devbox:dsh-e2e4-0001");
+
+ // opencode 双库经装饰器仍然齐全
+ let oc = by_agent(AgentId::Opencode);
+ let refs = oc.list_session_files().expect("opencode remote list");
+ assert!(refs.iter().any(|r| r.native_id == "oc-0001"));
+ assert!(refs.iter().any(|r| r.native_id == "ocnext-0001"));
+
+ // quick_meta 出口(整 map)也要改写——write_meta_only 是第三条写库路径,
+ // 漏改写会让远程行先以本地 key 落库、随后被全量解析改名成双行
+ if let Some(map) = oc.quick_meta(&refs) {
+ for meta in map.values() {
+ assert_eq!(meta.host, "devbox");
+ assert!(
+ meta.key.starts_with("opencode:devbox:"),
+ "quick 出口未改写: {}",
+ meta.key
+ );
+ }
+ }
+}
+
+/// merge_quick_meta 在两个已改写的 meta 间搬运字段:codex 的 key 覆写
+/// (state thread-id)经装饰器转发后仍保持远程格式。
+#[test]
+fn remote_codex_merge_keeps_host_key() {
+ setup();
+ let cache = tempfile::tempdir().unwrap();
+ let templates = wake_core::adapters::create_adapters();
+ let adapters =
+ wake_core::adapters::remote::create_remote_adapters(&templates, "devbox", cache.path());
+ let codex = adapters
+ .iter()
+ .find(|a| a.agent() == AgentId::Codex)
+ .unwrap();
+
+ // 复用 quickMeta 节的 mk_meta,只补远程差异字段
+ let mk = |key: &str, id: &str, title: &str| {
+ let mut meta = mk_meta(AgentId::Codex, key, id, title, None);
+ meta.host = "devbox".to_string();
+ meta
+ };
+ // parse 侧 key 是文件 native id,quick 侧是 state thread-id(可以不同);
+ // 两者都已在各自出口带上 host 段
+ let parsed = mk("codex:devbox:file-uuid", "file-uuid", "derived title");
+ let quick = mk("codex:devbox:thread-1", "thread-1", "user renamed");
+ let merged = codex.merge_quick_meta(parsed, &quick);
+ assert_eq!(
+ merged.key, "codex:devbox:thread-1",
+ "state key 优先且保持远程格式"
+ );
+ assert_eq!(merged.id, "thread-1");
+ assert_eq!(merged.title, "user renamed");
+ assert_eq!(merged.host, "devbox");
+}
+
+/// state DB 的 rollout_path 是**写库那台机器**上的绝对路径(rsync 原样
+/// 镜像过来)——远程缓存下必须按 sessions 尾段重映射到实例目录再匹配,
+/// 否则远程 Codex 的手工标题与 thread-key 全部静默丢失(2026-09-02 review)
+#[test]
+fn remote_codex_state_matches_despite_foreign_rollout_path() {
+ setup();
+ let cache = tempfile::tempdir().unwrap();
+ let codex_home = cache.path().join(".codex");
+ let day = codex_home.join("sessions/2026/09/01");
+ fs::create_dir_all(&day).unwrap();
+ let uuid = "0199535a-40b3-7ac2-921b-d5de1a3a8e15";
+ let file = format!("rollout-2026-09-01T10-00-00-{uuid}.jsonl");
+ fs::write(
+ day.join(&file),
+ b"{\"timestamp\":\"t\",\"type\":\"x\",\"payload\":{}}\n",
+ )
+ .unwrap();
+
+ let conn = rusqlite::Connection::open(codex_home.join("state_5.sqlite")).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE threads (id TEXT, rollout_path TEXT, cwd TEXT, title TEXT, name TEXT,
+ tokens_used INTEGER, archived INTEGER, git_branch TEXT, model TEXT, source TEXT,
+ created_at_ms INTEGER, updated_at_ms INTEGER);",
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO threads VALUES (?1, ?2, '/work/proj', 'raw', 'Renamed by user',
+ 5, 0, NULL, NULL, NULL, 1, 2)",
+ rusqlite::params![
+ uuid,
+ format!("/home/alice/.codex/sessions/2026/09/01/{file}")
+ ],
+ )
+ .unwrap();
+ drop(conn);
+
+ let templates = wake_core::adapters::create_adapters();
+ let adapters =
+ wake_core::adapters::remote::create_remote_adapters(&templates, "devbox", cache.path());
+ let codex = adapters
+ .iter()
+ .find(|a| a.agent() == AgentId::Codex)
+ .unwrap();
+ let refs = codex.list_session_files().unwrap();
+ assert_eq!(refs.len(), 1);
+ let quick = codex.quick_meta(&refs).expect("state db readable");
+ let meta = quick
+ .get(&refs[0].file_path)
+ .expect("state row must match via remapped rollout_path");
+ assert_eq!(meta.title, "Renamed by user", "手工标题不得因路径失配丢失");
+ assert_eq!(meta.key, format!("codex:devbox:{uuid}"));
+ assert_eq!(meta.host, "devbox");
+}
+
+/// roster 组装的真实路径(GUI 与 scan CLI 都走 create_adapter_roster_for):
+/// 启用的 host 每家追加一个远程实例到 active 尾部,禁用即整组回落;
+/// 远程实例不进 locations 面板快照。
+#[test]
+fn roster_appends_remote_instances_for_enabled_hosts() {
+ setup();
+ let dir = tempfile::tempdir().unwrap();
+ let store = wake_core::db::Store::open(&dir.path().join("roster.db")).unwrap();
+
+ let baseline = wake_core::adapters::create_adapter_roster_for(&store);
+ let local_n = baseline.active.len();
+ let locations_n = baseline.locations.len();
+
+ store.add_remote_host("devbox").unwrap();
+ let roster = wake_core::adapters::create_adapter_roster_for(&store);
+ assert_eq!(roster.active.len(), local_n + 14, "每家一个远程实例");
+ assert_eq!(
+ roster.locations.len(),
+ locations_n,
+ "远程实例不进 Session locations 面板"
+ );
+ let remote_count = roster
+ .active
+ .iter()
+ .filter(|a| a.host() == "devbox")
+ .count();
+ assert_eq!(remote_count, 14);
+ // 顺序契约:默认实例在前,"按 agent 找第一个"的兜底不受远程影响
+ assert!(roster.active[..local_n].iter().all(|a| a.host().is_empty()));
+
+ store.set_remote_host_enabled("devbox", false).unwrap();
+ let roster = wake_core::adapters::create_adapter_roster_for(&store);
+ assert_eq!(roster.active.len(), local_n, "禁用的 host 整组移出 roster");
+}
+
+/// REMOTE_LAYOUTS 的 mount 契约:整形在"缓存尚未同步"(目录不存在)与
+/// "缓存已落盘"两种状态下必须给出**同一组数据根**——远程实例是构造时刻
+/// 快照,roster 不随同步重建;若某家 mount 选在会随目录出现而改判的层级,
+/// 首次同步前后就会各指一棵树,先构造的实例读不到后落盘的数据。
+#[test]
+fn remote_mount_shaping_is_stable_across_sync_states() {
+ setup();
+ let templates = wake_core::adapters::create_adapters();
+
+ let empty = tempfile::tempdir().unwrap();
+ let synced = tempfile::tempdir().unwrap();
+ // 按白名单把"已同步"缓存的目录结构造出来(目录源建树,文件源 touch)
+ for layout in wake_core::remote::REMOTE_LAYOUTS {
+ for path in layout.sync_paths {
+ let dest = synced.path().join(path);
+ if std::path::Path::new(path).extension().is_some() {
+ fs::create_dir_all(dest.parent().unwrap()).unwrap();
+ fs::write(dest, b"").unwrap();
+ } else {
+ fs::create_dir_all(dest).unwrap();
+ }
+ }
+ }
+
+ let before = wake_core::adapters::remote::create_remote_adapters(&templates, "h", empty.path());
+ let after = wake_core::adapters::remote::create_remote_adapters(&templates, "h", synced.path());
+ for (a, b) in before.iter().zip(&after) {
+ assert_eq!(a.agent(), b.agent());
+ let rel = |adapter: &Box<dyn AgentAdapter>, root: &std::path::Path| -> Vec<PathBuf> {
+ adapter
+ .data_roots()
+ .iter()
+ .map(|p| {
+ p.strip_prefix(root)
+ .expect("root inside cache")
+ .to_path_buf()
+ })
+ .collect()
+ };
+ assert_eq!(
+ rel(a, empty.path()),
+ rel(b, synced.path()),
+ "{:?} 的 mount 整形随缓存落盘而漂移",
+ a.agent()
+ );
+ }
+}
diff --git a/crates/wake-core/tests/db_roundtrip.rs b/crates/wake-core/tests/db_roundtrip.rs
index 030c832..7871b3c 100644
--- a/crates/wake-core/tests/db_roundtrip.rs
+++ b/crates/wake-core/tests/db_roundtrip.rs
@@ -12,6 +12,7 @@ fn temp_store() -> (tempfile::TempDir, Store) {
fn meta(key: &str, title: &str) -> SessionMeta {
SessionMeta {
+ host: String::new(),
key: key.to_string(),
id: key.split(':').nth(1).unwrap_or(key).to_string(),
agent: AgentId::ClaudeCode,
@@ -313,11 +314,10 @@ fn removing_a_session_tree_writes_every_tombstone_atomically() {
assert!(store.is_tombstoned(&child.file_path));
}
-#[test]
-fn old_database_marks_grok_backfill_until_scan_finishes() {
- let dir = tempfile::tempdir().unwrap();
- let path = dir.path().join("old.db");
- let conn = rusqlite::Connection::open(&path).unwrap();
+/// 最老的 sessions schema(无 parent_key、无 host):迁移类测试共用,
+/// 再加列时别再抄第三份 DDL
+fn create_legacy_db(path: &std::path::Path) -> rusqlite::Connection {
+ let conn = rusqlite::Connection::open(path).unwrap();
conn.execute_batch(
"CREATE TABLE sessions (
key TEXT PRIMARY KEY, agent_id TEXT NOT NULL, native_id TEXT NOT NULL,
@@ -329,7 +329,14 @@ fn old_database_marks_grok_backfill_until_scan_finishes() {
);",
)
.unwrap();
- drop(conn);
+ conn
+}
+
+#[test]
+fn old_database_marks_grok_backfill_until_scan_finishes() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("old.db");
+ drop(create_legacy_db(&path));
let store = Store::open(&path).unwrap();
assert!(store.needs_grok_parent_backfill());
@@ -717,3 +724,69 @@ fn insights_snapshot_and_streaks() {
let d = store.insights(far).unwrap();
assert_eq!((d.current_streak, d.longest_streak), (0, 3));
}
+
+/// 老库(无 host 列)打开即迁移;既有行落 ''(本地域),写入远程行后
+/// host_counts 只统计非空 host。remote_hosts 配置与同步状态可往返。
+#[test]
+fn host_column_migration_and_remote_host_roundtrip() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("old.db");
+ let conn = create_legacy_db(&path);
+ conn.execute(
+ "INSERT INTO sessions (key, agent_id, native_id, file_path)
+ VALUES ('claude-code:legacy', 'claude-code', 'legacy', '/tmp/legacy.jsonl')",
+ [],
+ )
+ .unwrap();
+ drop(conn);
+
+ let store = Store::open(&path).unwrap();
+ // 老行读出来 host 为空(本地)
+ let legacy = store.get_session("claude-code:legacy").unwrap().unwrap();
+ assert!(legacy.host.is_empty());
+
+ // 远程行写入/读出 host 往返
+ let mut remote = meta("claude-code:devbox:r1", "远程会话");
+ remote.key = "claude-code:devbox:r1".into();
+ remote.id = "r1".into();
+ remote.host = "devbox".into();
+ remote.file_path = "/cache/devbox/.claude/projects/p/r1.jsonl".into();
+ store
+ .write_session(&remote, remote.updated_at, &[])
+ .unwrap();
+ let row = store.get_session("claude-code:devbox:r1").unwrap().unwrap();
+ assert_eq!(row.host, "devbox");
+ assert_eq!(row.id, "r1");
+
+ let counts = store.host_counts().unwrap();
+ assert_eq!(counts.get("devbox"), Some(&1));
+ assert!(!counts.contains_key(""), "本地行不进 host 榜");
+
+ // remote_hosts 配置往返:add → enabled 开关 → 同步状态 → remove
+ store.add_remote_host("devbox").unwrap();
+ store.add_remote_host("devbox").unwrap(); // 幂等
+ let hosts = store.list_remote_hosts().unwrap();
+ assert_eq!(hosts.len(), 1);
+ assert!(hosts[0].enabled && hosts[0].last_sync_at.is_none());
+
+ store.set_remote_host_enabled("devbox", false).unwrap();
+ assert!(!store.list_remote_hosts().unwrap()[0].enabled);
+
+ store
+ .record_remote_sync("devbox", Some("ssh: permission denied"))
+ .unwrap();
+ let host = &store.list_remote_hosts().unwrap()[0];
+ assert_eq!(
+ host.last_sync_error.as_deref(),
+ Some("ssh: permission denied")
+ );
+ assert!(host.last_sync_at.is_none(), "失败不得伪造成功时间");
+
+ store.record_remote_sync("devbox", None).unwrap();
+ let host = &store.list_remote_hosts().unwrap()[0];
+ assert!(host.last_sync_error.is_none(), "成功清掉上次错误");
+ assert!(host.last_sync_at.is_some());
+
+ store.remove_remote_host("devbox").unwrap();
+ assert!(store.list_remote_hosts().unwrap().is_empty());
+}
diff --git a/crates/wake-core/tests/scanner_finale.rs b/crates/wake-core/tests/scanner_finale.rs
index 1129a8c..d65a5af 100644
--- a/crates/wake-core/tests/scanner_finale.rs
+++ b/crates/wake-core/tests/scanner_finale.rs
@@ -465,6 +465,7 @@ fn seed(agent: AgentId, root: &str, path: &str, native_id: &str, mtime: i64) ->
size: 1,
},
meta: SessionMeta {
+ host: String::new(),
key: format!("{}:{native_id}", agent.as_str()),
id: native_id.into(),
agent,
@@ -498,6 +499,7 @@ fn tombstoned_session_does_not_resurrect_on_rescan() {
let dir = tempfile::tempdir().unwrap();
let store = temp_store(dir.path());
let meta = SessionMeta {
+ host: String::new(),
key: "codex:ghost".into(),
id: "ghost".into(),
agent: AgentId::Codex,
@@ -865,3 +867,63 @@ fn survivor_promotion_matches_content_keys() {
"内容 key 的幸存副本未被上位"
);
}
+
+/// 跨 host 去重分域(不变量 8⑦ 的远程扩展):同 native_id 的会话在本地与
+/// 远程各有一份(rsync 过项目后各自续跑是真实场景),按 mtime 的全局去重
+/// 会吞掉一台的——去重域必须含实例 host,两行(本地 key / host key)并存。
+#[test]
+fn local_and_remote_copies_of_same_native_id_both_survive() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = temp_store(dir.path());
+
+ // 同一份 Claude fixture 摆进"本地自定义根"与"远程缓存"两棵树
+ let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures/claude/projects/-Users-tester-Github-wakefx/11111111-aaaa-bbbb-cccc-000000000001.jsonl");
+ let native = "11111111-aaaa-bbbb-cccc-000000000001";
+ let local_root = dir.path().join("local-claude");
+ let remote_cache = dir.path().join("remotes/devbox");
+ for tree in [&local_root, &remote_cache] {
+ let proj = if tree == &local_root {
+ tree.join("projects/-Users-tester-Github-wakefx")
+ } else {
+ tree.join(".claude/projects/-Users-tester-Github-wakefx")
+ };
+ std::fs::create_dir_all(&proj).unwrap();
+ std::fs::copy(&fixture, proj.join(format!("{native}.jsonl"))).unwrap();
+ }
+
+ let base = wake_core::adapters::create_adapters();
+ let claude_template = base
+ .iter()
+ .find(|a| a.agent() == AgentId::ClaudeCode)
+ .unwrap();
+ let local = claude_template.with_custom_root(local_root);
+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![local]
+ .into_iter()
+ .chain(wake_core::adapters::remote::create_remote_adapters(
+ &base,
+ "devbox",
+ &remote_cache,
+ ))
+ .collect();
+
+ let events = Recorder::new();
+ run_scan(&adapters, &store, &events, true).expect("scan ok");
+
+ let local_key = format!("claude-code:{native}");
+ let remote_key = format!("claude-code:devbox:{native}");
+ let local_row = store.get_session(&local_key).unwrap();
+ let remote_row = store.get_session(&remote_key).unwrap();
+ assert!(local_row.is_some(), "本地副本被跨 host 去重吞掉");
+ assert!(remote_row.is_some(), "远程副本被跨 host 去重吞掉");
+ let remote_row = remote_row.unwrap();
+ assert_eq!(remote_row.host, "devbox");
+ assert_eq!(remote_row.id, native, "native id 保持纯净");
+ assert!(local_row.unwrap().host.is_empty());
+
+ // 再跑一轮(模拟下一次刷新):两行都不摇摆、不互删
+ let events = Recorder::new();
+ run_scan(&adapters, &store, &events, false).expect("rescan ok");
+ assert!(store.get_session(&local_key).unwrap().is_some());
+ assert!(store.get_session(&remote_key).unwrap().is_some());
+}
diff --git a/crates/wake/assets/icons/server.svg b/crates/wake/assets/icons/server.svg
new file mode 100644
index 0000000..44adf3f
--- /dev/null
+++ b/crates/wake/assets/icons/server.svg
@@ -0,0 +1,18 @@
+<!-- @license lucide-static v0.462.0 - ISC -->
+<svg
+ class="lucide lucide-server"
+ 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"
+>
+ <rect width="20" height="8" x="2" y="2" rx="2" ry="2" />
+ <rect width="20" height="8" x="2" y="14" rx="2" ry="2" />
+ <line x1="6" x2="6.01" y1="6" y2="6" />
+ <line x1="6" x2="6.01" y1="18" y2="18" />
+</svg>
diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rs
index 42d6702..7a96926 100644
--- a/crates/wake/src/assets.rs
+++ b/crates/wake/src/assets.rs
@@ -100,6 +100,7 @@ icons!(
"file-text",
"more-horizontal",
"hard-drive",
+ "server",
"database",
"settings",
"plus",
diff --git a/crates/wake/src/settings.rs b/crates/wake/src/settings.rs
index df59b91..66e56ff 100644
--- a/crates/wake/src/settings.rs
+++ b/crates/wake/src/settings.rs
@@ -1,6 +1,7 @@
use gpui::prelude::FluentBuilder as _;
use gpui::*;
use gpui_component::button::{Button, ButtonCustomVariant, ButtonVariants as _};
+use gpui_component::input::{Input, InputEvent, InputState};
use gpui_component::menu::{DropdownMenu as _, PopupMenuItem};
use gpui_component::switch::Switch;
use gpui_component::{
@@ -46,6 +47,7 @@ fn format_storage_size(bytes: u64) -> String {
pub(crate) enum SettingsPage {
General,
Locations,
+ Remotes,
Data,
Updates,
About,
@@ -53,7 +55,8 @@ pub(crate) enum SettingsPage {
/// Settings 内常规文字按钮共用一套尺寸和材质;避免页面各自混用
/// outline / primary / 默认 ButtonGroup 后形成多套视觉语言。
-fn settings_button(button: Button, cx: &App) -> Button {
+/// pub(crate):详情页的单段 Open In 按钮(workbench)用同一配方。
+pub(crate) fn settings_button(button: Button, cx: &App) -> Button {
let theme = cx.theme();
button
.custom(
@@ -92,7 +95,10 @@ pub(crate) struct SettingsView {
workbench: Entity<Workbench>,
appearance: AppearancePreference,
show_unavailable: bool,
+ /// Remote hosts 页的 Add host 输入框(页面内嵌,回车/按钮提交)
+ host_input: Entity<InputState>,
_workbench_observer: Option<Subscription>,
+ _host_input_subscription: Subscription,
}
impl SettingsView {
@@ -108,13 +114,36 @@ impl SettingsView {
cx.on_next_frame(window, move |this, _, cx| {
this._workbench_observer = Some(cx.observe(&observed, |_, _, cx| cx.notify()));
});
+ let host_input = cx.new(|cx| {
+ InputState::new(window, cx).placeholder("SSH alias from ~/.ssh/config, or user@host")
+ });
+ let host_input_subscription =
+ cx.subscribe_in(&host_input, window, |this, _, event, window, cx| {
+ if matches!(event, InputEvent::PressEnter { .. }) {
+ this.submit_add_host(window, cx);
+ }
+ });
Self {
focus_handle: cx.focus_handle(),
workbench,
appearance: theme::appearance_preference(),
show_unavailable: false,
+ host_input,
_workbench_observer: None,
+ _host_input_subscription: host_input_subscription,
+ }
+ }
+
+ fn submit_add_host(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let name = self.host_input.read(cx).value().trim().to_string();
+ if name.is_empty() {
+ return;
}
+ self.workbench.update(cx, |workbench, cx| {
+ workbench.add_remote_host(&name, window, cx)
+ });
+ self.host_input
+ .update(cx, |state, cx| state.set_value("", window, cx));
}
fn render_nav_item(
@@ -195,6 +224,13 @@ impl SettingsView {
SettingsPage::Locations,
cx,
))
+ .child(self.render_nav_item(
+ "settings-remotes-nav",
+ "Remote hosts",
+ "icons/server.svg",
+ SettingsPage::Remotes,
+ cx,
+ ))
.child(self.render_nav_item(
"settings-data-nav",
"Data",
@@ -991,6 +1027,207 @@ impl SettingsView {
}),
)
}
+
+ /// Settings → Remote hosts:SSH 会话聚合(阶段 1:只读镜像)。
+ /// 行结构仿 Locations:名称 + 状态行 + Switch + Remove。
+ fn render_remotes(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
+ let theme = cx.theme();
+ let rows = self.workbench.read(cx).remote_hosts_snapshot();
+ let syncing = self.workbench.read(cx).remote_sync_in_progress();
+ let sync_workbench = self.workbench.clone();
+ let has_hosts = !rows.is_empty();
+
+ let row_elements: Vec<AnyElement> = rows
+ .into_iter()
+ .enumerate()
+ .map(|(ix, row)| {
+ let toggle_workbench = self.workbench.clone();
+ let remove_workbench = self.workbench.clone();
+ let toggle_name = row.name.clone();
+ let remove_name = row.name.clone();
+ let row_fg = if row.enabled {
+ theme.foreground
+ } else {
+ theme.muted_foreground
+ };
+ h_flex()
+ .id(SharedString::from(format!("remote-host-{ix}")))
+ .w_full()
+ .px(SPACE_MD)
+ .py(SPACE_SM)
+ .gap(SPACE_MD)
+ .items_center()
+ .rounded(theme.radius)
+ .border_1()
+ .border_color(theme.border)
+ .child(
+ icon("icons/server.svg")
+ .with_size(px(15.))
+ .flex_shrink_0()
+ .text_color(row_fg),
+ )
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(2.))
+ .child(
+ div()
+ .text_size(FONT_BODY)
+ .font_medium()
+ .text_color(row_fg)
+ .child(row.name.clone()),
+ )
+ .child(
+ div()
+ .min_w_0()
+ .truncate()
+ .text_size(FONT_CAPTION)
+ .text_color(if row.failed {
+ theme.danger
+ } else {
+ theme.muted_foreground
+ })
+ .child(row.status.clone()),
+ ),
+ )
+ .child(
+ Switch::new(SharedString::from(format!("remote-host-toggle-{ix}")))
+ .checked(row.enabled)
+ .on_click(move |checked, window, cx| {
+ let enabled = *checked;
+ toggle_workbench.update(cx, |this, cx| {
+ this.set_remote_host_enabled(
+ toggle_name.as_ref(),
+ enabled,
+ window,
+ cx,
+ );
+ });
+ }),
+ )
+ .child(
+ Button::new(SharedString::from(format!("remote-host-remove-{ix}")))
+ .ghost()
+ .small()
+ .rounded(RADIUS_BUTTON)
+ .icon(icon("icons/trash-2.svg").with_size(px(14.)))
+ .on_click(move |_, window, cx| {
+ remove_workbench.update(cx, |this, cx| {
+ this.confirm_remove_remote_host(
+ remove_name.clone(),
+ window,
+ cx,
+ );
+ });
+ }),
+ )
+ .into_any_element()
+ })
+ .collect();
+
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .h_full()
+ .bg(theme.background)
+ .child(
+ h_flex()
+ .flex_shrink_0()
+ .px(SPACE_XXL)
+ .pt(SETTINGS_PAGE_TOP)
+ .pb(SPACE_XL)
+ .gap(SPACE_LG)
+ .items_start()
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(5.))
+ .child(
+ div()
+ .text_size(FONT_TITLE)
+ .font_semibold()
+ .text_color(theme.foreground)
+ .child("Remote hosts"),
+ )
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(
+ "Mirror agent sessions from other machines over SSH. \
+ Read-only: nothing on the remote is ever written.",
+ ),
+ ),
+ )
+ .when(has_hosts, |this| {
+ this.child(
+ settings_button(
+ Button::new("settings-sync-remotes")
+ .icon(icon("icons/refresh-cw.svg").with_size(px(13.)))
+ .label(if syncing { "Syncing…" } else { "Sync now" }),
+ cx,
+ )
+ .disabled(syncing)
+ .on_click(move |_, _, cx| {
+ sync_workbench
+ .update(cx, |this, cx| this.sync_all_remote_hosts(cx));
+ }),
+ )
+ }),
+ )
+ .child(
+ v_flex()
+ .id("settings-remote-list")
+ .flex_1()
+ .min_h_0()
+ .overflow_y_scroll()
+ .px(SPACE_XXL)
+ .pb(px(40.))
+ .gap(SPACE_LG)
+ .child(
+ h_flex()
+ .w_full()
+ .gap(SPACE_SM)
+ .child(div().flex_1().min_w_0().child(Input::new(&self.host_input)))
+ .child(
+ settings_button(
+ Button::new("settings-add-remote-host")
+ .icon(icon("icons/plus.svg").with_size(px(13.)))
+ .label("Add host"),
+ cx,
+ )
+ .on_click(cx.listener(
+ |this, _, window, cx| {
+ this.submit_add_host(window, cx);
+ },
+ )),
+ ),
+ )
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(
+ "Needs non-interactive SSH (key in your agent) and rsync on both \
+ ends — connect once from a terminal first to trust the host key. \
+ Sessions sync on launch, refresh, and Sync now.",
+ ),
+ )
+ .children(row_elements)
+ .when(!has_hosts, |this| {
+ this.child(
+ div()
+ .pt(SPACE_LG)
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child("No remote hosts yet."),
+ )
+ }),
+ )
+ .into_any_element()
+ }
}
impl Focusable for SettingsView {
@@ -1008,6 +1245,7 @@ impl Render for SettingsView {
let content = match selected_page {
SettingsPage::General => self.render_general(cx),
SettingsPage::Locations => self.render_locations(cx).into_any_element(),
+ SettingsPage::Remotes => self.render_remotes(window, 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 39f9336..48147b1 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -102,6 +102,8 @@ fn icon(path: &'static str) -> Icon {
/// 起一条后台扫描线程。启动时的自动扫描(full=false)与用户主动重扫(full=true)
/// 共用;返回的 Result 由 run_scan 的终态事件代为上报,这里只需丢弃。
+/// 远程同步不在这条线程上——它走 Workbench::spawn_remote_sync 的独立线程,
+/// 本地扫描不等网络(不可达 host 的 ConnectTimeout 不该拖住启动索引)。
fn spawn_scan(
adapters: SharedAdapters,
store: Arc<Store>,
@@ -113,6 +115,27 @@ fn spawn_scan(
});
}
+/// 起远程同步线程(names 空则不起)。进行中状态由调用方记 `syncing_hosts`
+/// (存事实不存文案,展示句在 render 现算——不变量 6 的教训);线程收工经
+/// bg_tx 发 RemoteSyncDone,成败都在 remote_hosts 表里。
+fn spawn_remote_sync_thread(
+ store: &Arc<Store>,
+ bg_tx: futures::channel::mpsc::UnboundedSender<BgEvent>,
+ names: Vec<String>,
+) {
+ if names.is_empty() {
+ return;
+ }
+ let store = store.clone();
+ std::thread::spawn(move || {
+ wake_core::remote::sync_hosts(&store, &names);
+ // 同步期间被 Remove 的 host:rsync 取消不了,收工后按配置表把孤儿
+ // 缓存目录清掉(含它刚写回的),Remove 的"缓存已删"承诺自此闭合
+ wake_core::remote::purge_orphan_caches(&store);
+ let _ = bg_tx.unbounded_send(BgEvent::RemoteSyncDone);
+ });
+}
+
// ---------------- 后台事件桥 ----------------
enum BgEvent {
@@ -120,6 +143,8 @@ enum BgEvent {
Changed,
/// 监听后端丢过事件,需要一轮增量兜底
RescanNeeded,
+ /// 远程 rsync 线程收工(成败都发;状态在 remote_hosts 表里)
+ RemoteSyncDone,
}
struct ChannelEvents(futures::channel::mpsc::UnboundedSender<BgEvent>);
@@ -723,6 +748,13 @@ impl ListDelegate for SessionsDelegate {
theme.muted,
theme.muted_foreground,
))
+ .when(!s.host.is_empty(), |this| {
+ // 远程会话的 host 徽章:@ 前缀一眼与项目名区分
+ this.child(outline_badge(
+ format!("@{}", s.host),
+ theme.muted_foreground,
+ ))
+ })
.when(show_chevron, |this| {
this.child(
div()
@@ -916,6 +948,7 @@ mod session_group_tests {
SessionMeta {
key: key.to_string(),
id: key.to_string(),
+ host: String::new(),
agent: AgentId::Codex,
title: key.to_string(),
project_path: "/tmp/wake-test".to_string(),
@@ -1923,6 +1956,15 @@ pub struct Workbench {
/// 新根不收录、被移根不出清,要等手动 ⌘R(2026-08-24 Codex review)。
/// 终态事件到达后由 on_bg_event 消费,用新 roster 补一轮增量
pending_rescan: bool,
+ /// rsync 线程正在同步的 host(空 = 空闲);与 scan 正交。侧栏文案与
+ /// Sync now 的 busy 态都从这个**事实**派生,render 现算文案——不变量 6
+ /// 的教训:别把展示句存成状态
+ syncing_hosts: Vec<String>,
+ /// 同步进行中又被请求的 host(如 rsync 未收工就 add host):收工后只补
+ /// 这几台(不升级成全量),不并发两组 rsync 打同一缓存树
+ pending_sync: Vec<String>,
+ /// 远程同步线程直发事件用(ChannelEvents 只覆盖 ScanEvents 两个方法)
+ bg_tx: futures::channel::mpsc::UnboundedSender<BgEvent>,
/// Settings 是单例窗口;句柄不保活,关闭后下次点击会检测失败并重建。
settings_window: Option<AnyWindowHandle>,
settings_page: SettingsPage,
@@ -2123,6 +2165,16 @@ pub(crate) struct DataSettingsSnapshot {
pub(crate) session_count: i64,
}
+/// Settings → Remote hosts 的一行(库表 remote_hosts + 会话计数拼装)
+#[derive(Clone)]
+pub(crate) struct RemoteHostRow {
+ pub(crate) name: SharedString,
+ pub(crate) enabled: bool,
+ /// "12 sessions · synced 5 min ago" / "Never synced" / 错误摘要
+ pub(crate) status: SharedString,
+ pub(crate) failed: bool,
+}
+
/// location 表单的语义目标。预设行的“编辑”落库为**压制默认 + 记自定义**;
/// 真正的 Remove 只对自定义 location 出现,预设行由开关启停。
#[derive(Clone)]
@@ -2183,10 +2235,13 @@ impl Workbench {
InputState::new(window, cx).placeholder("Search everything \u{2014} prose or code")
});
- // 后台:全量扫描线程 + 文件监听
+ // 后台:全量扫描线程 + 文件监听 + 远程同步(彼此独立并行)
let (tx, mut rx) = futures::channel::mpsc::unbounded::<BgEvent>();
+ let bg_tx = tx.clone();
let events: Arc<dyn ScanEvents> = Arc::new(ChannelEvents(tx));
spawn_scan(adapters.clone(), store.clone(), events.clone(), false);
+ let syncing_hosts = store.enabled_remote_host_names();
+ spawn_remote_sync_thread(&store, bg_tx.clone(), syncing_hosts.clone());
let watcher = start_watcher(adapters.clone(), store.clone(), events.clone());
let scan_events = events.clone();
@@ -2240,6 +2295,9 @@ impl Workbench {
},
refreshing: false,
pending_rescan: false,
+ syncing_hosts,
+ pending_sync: Vec::new(),
+ bg_tx,
settings_window: None,
settings_page: SettingsPage::General,
update_status: UpdateStatus::Idle,
@@ -2468,6 +2526,7 @@ impl Workbench {
self.scan_events.clone(),
true,
);
+ self.sync_all_remote_hosts(cx);
}
/// Settings/Locations 页的数据快照。路径与 active roster 来自同一次
@@ -2510,10 +2569,7 @@ impl Workbench {
display: tilde_path(&raw).into(),
raw: raw.clone().into(),
tally: if exists {
- match count {
- 1 => "1 session".into(),
- n => format!("{n} sessions").into(),
- }
+ session_tally(count).into()
} else {
"Folder not found".into()
},
@@ -2688,16 +2744,22 @@ impl Workbench {
/// 新旧两份实例不共存(不变量 8 的运行时补充:"单实例"指任一时刻只有一份
/// 在服务,换代必须整体换、所有消费方跟随新 Arc)
fn rebuild_roster(&mut self, cx: &mut Context<Self>) {
- // 先撤旧 watcher 并等它退出(SessionWatcher::Drop 内 join):旧线程持
- // 旧 roster,不等收尾,已移除根的会话可能在补扫后被写回复活
self.watcher = None;
(self.adapters, self.data_locations) = Self::build_roster(&self.store);
+ self.remount_watcher();
+ cx.notify();
+ }
+
+ /// watcher 生命周期的唯一操作点(rebuild_roster 与 RemoteSyncDone 共用):
+ /// 先 drop 并等旧线程退出(SessionWatcher::Drop 内 join)——旧线程持旧
+ /// roster 在写库,不等收尾,已移除根的会话可能在补扫后被写回复活
+ fn remount_watcher(&mut self) {
+ self.watcher = None;
self.watcher = start_watcher(
self.adapters.clone(),
self.store.clone(),
self.scan_events.clone(),
);
- cx.notify();
}
/// location 表单(添加/编辑共用一套 UI,2026-08-24 定稿):agent 下拉 +
@@ -3210,7 +3272,7 @@ impl Workbench {
FormTarget::Add => "Location added",
FormTarget::Edit { .. } => "Location updated",
};
- self.apply_location_change(Ok(()), "", Notification::success(note), window, cx);
+ self.apply_roster_change(Ok(()), "", Notification::success(note), window, cx);
false
}
@@ -3226,7 +3288,7 @@ impl Workbench {
let res = self
.store
.remove_custom_root(agent.as_str(), stored.as_ref());
- self.apply_location_change(
+ self.apply_roster_change(
res,
"Remove failed",
Notification::info("Location removed"),
@@ -3243,7 +3305,7 @@ impl Workbench {
cx: &mut Context<Self>,
) {
let res = self.store.clear_location_overrides();
- self.apply_location_change(
+ self.apply_roster_change(
res,
"Restore failed",
Notification::info("Locations restored to defaults"),
@@ -3287,7 +3349,9 @@ impl Workbench {
/// location 变更的统一收尾(删/恢复/表单提交成功共用)。Settings 页
/// 观察 Workbench 的 notify 并重读快照,不需要关闭/重开管理面板。
- fn apply_location_change(
+ /// 配置写库后的统一收尾:失败弹错,成功走"roster 换代 + 补扫 + 提示"
+ /// ——location 增删改、开关与远程 host 开关同一条时序,别各自手写
+ fn apply_roster_change(
&mut self,
res: anyhow::Result<()>,
err_prefix: &'static str,
@@ -3307,6 +3371,182 @@ impl Workbench {
}
}
+ // ---------- 远程 host(Settings → Remote hosts) ----------
+
+ /// Settings 的 Sync now 按钮 busy 态(rsync 线程运行中)
+ pub(crate) fn remote_sync_in_progress(&self) -> bool {
+ !self.syncing_hosts.is_empty()
+ }
+
+ pub(crate) fn remote_hosts_snapshot(&self) -> Vec<RemoteHostRow> {
+ let counts = self.store.host_counts().unwrap_or_default();
+ self.store
+ .list_remote_hosts()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|host| {
+ let tally = session_tally(counts.get(&host.name).copied().unwrap_or(0));
+ let (status, failed) = match (&host.last_sync_error, host.last_sync_at) {
+ (Some(err), _) => (format!("Sync failed: {err}"), true),
+ (None, Some(ts)) => (format!("{tally} · synced {}", smart_time(ts)), false),
+ (None, None) => (format!("{tally} · never synced"), false),
+ };
+ RemoteHostRow {
+ name: host.name.into(),
+ enabled: host.enabled,
+ status: status.into(),
+ failed,
+ }
+ })
+ .collect()
+ }
+
+ pub(crate) fn add_remote_host(
+ &mut self,
+ name: &str,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !wake_core::remote::valid_host_name(name) {
+ window.push_notification(
+ Notification::error(
+ "Host must be an SSH alias or user@host (letters, digits, . _ - @)",
+ ),
+ cx,
+ );
+ return;
+ }
+ match self.store.add_remote_host(name) {
+ Err(e) => window.push_notification(
+ Notification::error(format!("Couldn't add remote host: {e}")),
+ cx,
+ ),
+ Ok(()) => {
+ self.rebuild_roster(cx);
+ // 只拉新加的这台(别把既有 host 的整棵树再协商一遍):
+ // BatchMode 的 rsync 失败会记进 last_sync_error,面板下一帧
+ // 就能给出"密钥不在 agent 里"这类反馈
+ self.spawn_remote_sync(vec![name.to_string()], cx);
+ window.push_notification(
+ Notification::info(format!("Syncing sessions from {name}…")),
+ cx,
+ );
+ }
+ }
+ }
+
+ pub(crate) fn set_remote_host_enabled(
+ &mut self,
+ name: &str,
+ enabled: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ // 与 location 停用同语义:禁用 → roster 移除实例 → 补扫把该 host
+ // 的行按"磁盘已删"出清;缓存保留,重新启用即收编回来
+ let res = self.store.set_remote_host_enabled(name, enabled);
+ let note = Notification::info(if enabled {
+ "Remote host enabled"
+ } else {
+ "Remote host disabled"
+ });
+ self.apply_roster_change(res, "Couldn't update remote host", note, window, cx);
+ }
+
+ /// Remove 按确认流程走:索引行与本地缓存一并清掉,远端文件不动。
+ pub(crate) fn confirm_remove_remote_host(
+ &mut self,
+ name: SharedString,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let entity = cx.entity();
+ window.open_alert_dialog(cx, move |dialog, _window, cx| {
+ let name = name.clone();
+ let entity = entity.clone();
+ let theme = cx.theme();
+ dialog
+ .title(
+ div()
+ .text_size(FONT_HEADING)
+ .font_semibold()
+ .child(format!("Remove {name}?")),
+ )
+ .width(px(440.))
+ .confirm()
+ .button_props(
+ gpui_component::dialog::DialogButtonProps::default()
+ .ok_text("Remove")
+ .ok_variant(gpui_component::button::ButtonVariant::Danger),
+ )
+ .child(
+ div()
+ .text_size(FONT_BODY)
+ .text_color(theme.foreground)
+ .child(
+ "Its sessions leave the index and the local cache is deleted. \
+ Nothing on the remote host is touched.",
+ ),
+ )
+ .on_ok(move |_, window, cx| {
+ entity.update(cx, |this, cx| {
+ this.remove_remote_host(name.as_ref(), window, cx);
+ });
+ true
+ })
+ });
+ }
+
+ fn remove_remote_host(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
+ if let Err(e) = self.store.remove_remote_host(name) {
+ window.push_notification(
+ Notification::error(format!("Couldn't remove remote host: {e}")),
+ cx,
+ );
+ return;
+ }
+ // 排队中的同步请求剔除该 host,别在删除后又把 transcripts 拉回来;
+ // 正在跑的 rsync 取消不了(阻塞在 Command::output),它写回的目录由
+ // RemoteSyncDone 的孤儿缓存清理兜底(那里按配置表裁决,幂等)
+ self.pending_sync.retain(|n| n != name);
+ // 先换代(旧 watcher drop 后不再监听该缓存),再删缓存目录,最后补扫
+ // 出清库内行——删目录放独立线程,大缓存树的删除不该冻住 UI
+ self.rebuild_roster(cx);
+ if let Some(db_dir) = self.store.db_dir() {
+ let cache = wake_core::remote::host_cache_dir(&db_dir, name);
+ std::thread::spawn(move || {
+ let _ = std::fs::remove_dir_all(cache);
+ });
+ }
+ self.kick_incremental_scan(cx);
+ window.push_notification(Notification::info("Remote host removed"), cx);
+ }
+
+ /// 起远程同步(add host / Sync now / ⌘R 共用)。rsync 在独立线程,
+ /// 与扫描并行;进行中再来请求则把这几台排队,收工后只补它们。
+ /// 完成经 RemoteSyncDone 事件收编缓存,扫描侧完全不感知。
+ pub(crate) fn spawn_remote_sync(&mut self, names: Vec<String>, cx: &mut Context<Self>) {
+ if names.is_empty() {
+ return;
+ }
+ if !self.syncing_hosts.is_empty() {
+ for n in names {
+ if !self.pending_sync.contains(&n) {
+ self.pending_sync.push(n);
+ }
+ }
+ return;
+ }
+ spawn_remote_sync_thread(&self.store, self.bg_tx.clone(), names.clone());
+ self.syncing_hosts = names;
+ cx.notify();
+ }
+
+ pub(crate) fn sync_all_remote_hosts(&mut self, cx: &mut Context<Self>) {
+ let names = self.store.enabled_remote_host_names();
+ self.spawn_remote_sync(names, cx);
+ }
+
/// roster 换代后补一轮增量:新根收录、被移根出清。撞上进行中的扫描
/// 撞上进行中的扫描则排队,由终态事件补扫。
fn kick_incremental_scan(&mut self, cx: &mut Context<Self>) {
@@ -3363,6 +3603,31 @@ impl Workbench {
self.kick_incremental_scan(cx);
None
}
+ BgEvent::RemoteSyncDone => {
+ self.syncing_hosts.clear();
+ // 同步期间被排队的 host(如 add host)接着跑;与下面的收编
+ // 并行,互不等待
+ let queued = std::mem::take(&mut self.pending_sync);
+ self.spawn_remote_sync(queued, cx);
+ // 首次同步会创建 watcher 挂载时还不存在的缓存目录——磁盘上
+ // 出现了监听集(watcher 报的真实挂载根)之外的新根才重挂;
+ // 稳态下 rsync 落盘由现有监听收编,不白付 drop+join(watcher
+ // 正忙时是一整个去抖批次)的等待
+ let watched = self.watcher.as_ref().map(|w| w.watched_roots());
+ let grown = self
+ .adapters
+ .iter()
+ .flat_map(|a| a.watch_paths())
+ .any(|p| p.is_dir() && watched.is_none_or(|w| !w.contains(&p)));
+ if grown {
+ self.remount_watcher();
+ }
+ // 补扫不能省:SQLite 型侧档(copilot/opencode/antigravity)
+ // watcher 只认 .jsonl,远程缓存里这些库的更新只有扫描能收
+ self.kick_incremental_scan(cx);
+ cx.notify();
+ None
+ }
}
}
@@ -4027,28 +4292,39 @@ impl Workbench {
}
}
- /// per-agent 记忆任何点击都写(只影响本 agent,收敛到用户实际用的);
+ /// per-agent 记忆任何 App 点击都写(只影响本 agent,收敛到用户实际用的);
/// 全局 last_terminal 只在 explicit(下拉显式选择)时写——左段点的可能
- /// 是回退值,写进全局会让一个 dsh 会话把 Kooky 偏好冲成 Terminal
+ /// 是回退值,写进全局会让一个 dsh 会话把 Kooky 偏好冲成 Terminal。
+ /// 非 App 目标(Copy SSH command)不进记忆:远程/本地列表不相交,记了
+ /// 也没有可回放的场景。
fn do_resume(
&mut self,
- term: terminal::TerminalApp,
+ target: terminal::ResumeTarget,
explicit: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(detail) = &self.detail else { return };
- self.preferred_terminal.insert(detail.meta.agent, term);
- if explicit {
- self.last_terminal = Some(term);
+ if let terminal::ResumeTarget::App(term) = target {
+ self.preferred_terminal.insert(detail.meta.agent, term);
+ if explicit {
+ self.last_terminal = Some(term);
+ }
+ self.save_open_in_prefs();
+ cx.notify(); // split 按钮左段立即切到本次选择
}
- self.save_open_in_prefs();
- cx.notify(); // split 按钮左段立即切到本次选择
let meta = detail.meta.clone();
- let task = cx.background_spawn(async move { terminal::resume_session_in(&meta, term) });
- Self::notify_when_done(window, cx, task, |outcome| {
+ let task = cx.background_spawn(async move { terminal::resume_target(&meta, target) });
+ Self::notify_when_done(window, cx, task, move |outcome| {
if outcome.ok {
- Notification::success(format!("Opened in terminal: {}", outcome.command))
+ Notification::success(match target {
+ terminal::ResumeTarget::App(_) => {
+ format!("Opened in terminal: {}", outcome.command)
+ }
+ terminal::ResumeTarget::CopySshCommand => {
+ format!("SSH command copied: {}", outcome.command)
+ }
+ })
} else {
Notification::error(outcome.error.unwrap_or_else(|| "Resume failed".into()))
}
@@ -4155,6 +4431,15 @@ impl Workbench {
fn confirm_delete(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(detail) = &self.detail else { return };
+ // 远程会话只读(菜单项已隐藏,这里兜住快捷键等其余入口):本地只有
+ // 缓存副本,trash 它下次同步就复活;动远端文件是阶段 3 的产品决定
+ if !detail.meta.host.is_empty() {
+ window.push_notification(
+ Notification::info("Remote sessions are read-only — files stay on the remote host"),
+ cx,
+ );
+ return;
+ }
let meta = detail.meta.clone();
let mut sessions = vec![meta.clone()];
sessions.extend(self.store.all_descendants(&meta.key).unwrap_or_default());
@@ -4280,6 +4565,14 @@ impl Workbench {
0 => "Refreshing…".to_string(),
total => format!("Refreshing {}/{}", self.scan.done, total),
})
+ } else if let [only] = self.syncing_hosts.as_slice() {
+ // rsync 与扫描并行;扫描先收工时这里接着展示同步状态
+ Some(format!("Syncing {only}…"))
+ } else if !self.syncing_hosts.is_empty() {
+ Some(format!(
+ "Syncing {} remote hosts…",
+ self.syncing_hosts.len()
+ ))
} else {
self.scan
.error
@@ -5606,6 +5899,9 @@ impl Workbench {
let export_entity = cx.entity();
let reveal_entity = export_entity.clone();
let delete_entity = export_entity.clone();
+ // 远程会话只读:Delete 项整个不出现(阶段 1 不做远程删除——本地能
+ // trash 的只有缓存副本,下次 rsync 就复活,语义是骗人的)
+ let menu_is_remote = !meta.host.is_empty();
let more_menu = Button::new("more-actions")
.ghost()
.rounded(RADIUS_BUTTON)
@@ -5645,22 +5941,23 @@ impl Workbench {
}
}),
)
- .separator()
- .item(
- PopupMenuItem::element(|_, cx| {
- div().text_color(cx.theme().danger).child(MOVE_TO_TRASH)
- })
- .icon(
- icon("icons/trash-2.svg")
- .with_size(px(15.))
- .text_color(cx.theme().danger),
+ .when(!menu_is_remote, |menu| {
+ menu.separator().item(
+ PopupMenuItem::element(|_, cx| {
+ div().text_color(cx.theme().danger).child(MOVE_TO_TRASH)
+ })
+ .icon(
+ icon("icons/trash-2.svg")
+ .with_size(px(15.))
+ .text_color(cx.theme().danger),
+ )
+ .on_click(move |_, window, cx| {
+ delete_entity.update(cx, |this, cx| {
+ this.confirm_delete(window, cx);
+ });
+ }),
)
- .on_click(move |_, window, cx| {
- delete_entity.update(cx, |this, cx| {
- this.confirm_delete(window, cx);
- });
- }),
- )
+ })
})
.anchor(Anchor::TopRight);
@@ -5761,7 +6058,37 @@ impl Workbench {
h_flex()
.flex_shrink_0()
.gap(SPACE_XS)
- .child({
+ .child(if let [single] =
+ terminal::resume_targets(&meta).as_slice()
+ {
+ // 单目标(阶段 1 的远程会话只有 Copy SSH command):
+ // 单段控件用现成 Button,无 chevron 无记忆(split
+ // 按钮手搓只因它要双段共壳)
+ let target = *single;
+ let (label, tip) = match target {
+ terminal::ResumeTarget::App(t) => (
+ format!("Open in {}", t.display_name()),
+ "Open this session".to_string(),
+ ),
+ terminal::ResumeTarget::CopySshCommand => (
+ "Copy SSH command".to_string(),
+ "Copy the SSH command that resumes this session on its host"
+ .to_string(),
+ ),
+ };
+ crate::settings::settings_button(
+ Button::new("open-in-single"),
+ cx,
+ )
+ .h(px(28.))
+ .icon(icon("icons/terminal.svg").with_size(px(13.)))
+ .label(label)
+ .tooltip(tip)
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.do_resume(target, false, window, cx);
+ }))
+ .into_any_element()
+ } else {
// Open In split 按钮(Codex/kooky 风):左段 = 上次
// 目标的应用图标,点击直开;右段 chevron 展开列表。
// 目标列表按 agent 过滤(Kooky 深链不认 dsh);
@@ -5815,7 +6142,12 @@ impl Workbench {
})
.on_click(cx.listener(move |this, _, window, cx| {
if let Some(term) = current {
- this.do_resume(term, false, window, cx);
+ this.do_resume(
+ terminal::ResumeTarget::App(term),
+ false,
+ window,
+ cx,
+ );
} else {
// 空列表在 macOS 不可能(Terminal.app 恒在),
// Windows/Linux 上 PATH 被启动器改写时会发生
@@ -5871,7 +6203,12 @@ impl Workbench {
})
.on_click(move |_, window, cx| {
entity.update(cx, |this, cx| {
- this.do_resume(term, true, window, cx);
+ this.do_resume(
+ terminal::ResumeTarget::App(term),
+ true,
+ window,
+ cx,
+ );
});
}),
);
@@ -5880,6 +6217,7 @@ impl Workbench {
})
.anchor(Anchor::TopRight),
)
+ .into_any_element()
})
.child(tool_btn(
"fav",
@@ -5971,6 +6309,12 @@ impl Workbench {
this.child(outline_badge(source, color))
},
)
+ .when(!meta.host.is_empty(), |this| {
+ this.child(outline_badge(
+ format!("@{}", meta.host),
+ theme.muted_foreground,
+ ))
+ })
.when(has_detail_facts, |this| {
this.child(
div()
@@ -7571,6 +7915,15 @@ fn custom_owner<'a>(
.map(|(_, p)| p)
}
+/// "1 session / N sessions" 单复数文案(Locations 与 Remote hosts 两个
+/// 设置页共用,别让两处各自漂移)
+fn session_tally(n: i64) -> String {
+ match n {
+ 1 => "1 session".to_string(),
+ n => format!("{n} sessions"),
+ }
+}
+
fn badge(name: impl Into<SharedString>, bg: Hsla, fg: Hsla) -> impl IntoElement {
div()
.min_w_0()