All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
feat: read-only Skills page (#62)
Corey Chiu82069dd14752
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1c7abba..9f16229 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## [Unreleased]++- New: A Skills page lists the skills your agents have installed, which agents share each one, and where copies of the same skill have drifted apart (#62, thanks @ICEY4040727)+## [0.9.4] — 2026-10-15- Fix: Refresh picks up sessions you deleted in OpenCode while it was still running, instead of listing them until Wake restarts (#70, thanks @lin-code-world)diff --git a/DESIGN.md b/DESIGN.mdindex 9a5bdd1..629787e 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -46,7 +46,7 @@ Wake 的目标不是展示技术感,而是让用户在几秒内重新找到并## 颜色-所有颜色必须来自 `theme.rs` 的语义 token(含 MODEL_BADGE_BG/STAR_YELLOW 两个专用常量);其他 UI 文件禁止颜色字面量。Agent 品牌资产只能来自 `AgentId::brand_icon(dark)`(内嵌 PNG 路径,定义在 `wake-core/src/models.rs`),加新 agent 时一处改完。+所有颜色必须来自 `theme.rs` 的语义 token(含 MODEL_BADGE_BG/STAR_YELLOW 两个专用常量与 Skills 页 plugin 徽章的 `plugin_badge_color`);其他 UI 文件禁止颜色字面量。Agent 品牌资产只能来自 `AgentId::brand_icon(dark)`(内嵌 PNG 路径,定义在 `wake-core/src/models.rs`),加新 agent 时一处改完。### 主要材质@@ -137,7 +137,7 @@ macOS 不设置横跨三栏的自定义 header。主窗口透明标题栏高 44p- 线条图标比实心品牌图视觉轻,同档里给小一号:分组项 Lucide 14 / 品牌图 18,主导航 Lucide 15。- 行内容 = 行首元素 + 标题 + 计数;计数一律 Label 档 muted。- 组头 "Agents"/"Projects" 用 Body 档常规字重 + muted 色(与主导航同字号同字重,仅靠颜色区分——加粗会让组头压过它统辖的行)。行首是 15px 的折叠 chevron(收起指右、展开指下;与导航行图标同档,描边粗细一致),中心压 26.75 轴(用户 2026-09-22 定:箭头放到开头,对准上面菜单的图标与红绿灯的红灯;原先 chevron 跟在文字后),**不占 18px 槽位、按自己的框居中压轴**,再接统一的 `ICON_TEXT_GAP`——槽位居中再接同一间距,墨迹到文字会比导航行空出一截(chevron 墨迹只有约 5px 宽,用户同日"间隔太大");按框压轴后墨迹到文字视觉约 10.9px 与导航行相当,文字起点比导航行标签左 1.5px。组头与主导航行**同高(`ROW_HEIGHT` 32px,文字居中)、同 4px 间距**,导航块到组头之间也只隔这 4px:收起时 All Sessions / Starred / Agents / Projects 等距 36px(用户 2026-10-12 定;原先组头上留 12、下留 4,再加两块之间多出的 4px,下面明显更疏)。-- 底部工具条常驻,总高 44px(含顶部 1px hairline),两端分置的**纯图标条**(2026-09-21 三轮定稿:六个一样的 ghost 图标挤一排分不出层级;带边框底色的分段盒子放在侧栏里像一个走错地方的表单控件——参照 Zed 状态栏 / Xcode 导航条,不带盒子):按钮统一 28×28、6px 圆角、14px 图标、2px 间距;**左端**——Sessions(messages-square,双气泡;单气泡的 message-square 留给消息级用途)/ Memory(brain)/ Insights(chart-column)三颗页切换,再接 brush-cleaning "Clean Up Sessions"(它是叠在会话视图上的模式,也靠左),当前页(或打开中的清理)那颗用侧栏行的选中色(`sidebar_accent` 底 + `sidebar_accent_foreground` 图标)做圆角底,与导航行选中态同一套语言;**右端只有齿轮 "Settings"**。左内边距 12.75 = 26.75(侧栏中轴)− 14(按钮半宽):最左那颗图标的中心与红绿灯红灯中心、导航行行首在同一条轴上。未选中的一律透明底、muted 图标,hover 才出色。**Refresh 不在工具条**:它住在每页页头右端(All Sessions 页头在 Sort 左侧,Memory / Insights 页头单独一个;tooltip 就叫 "Refresh"),会话页与 Insights 走整库重扫(Insights 的数据是扫描收尾派生的),Memory 页只同步记忆(读 Settings → Memory locations 的当下配置,不重扫会话;用户 2026-09-22 定各刷各的);进行中转圈并禁用,⌘R 恒为刷会话。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。+- 底部工具条常驻,总高 44px(含顶部 1px hairline),两端分置的**纯图标条**(2026-09-21 三轮定稿:六个一样的 ghost 图标挤一排分不出层级;带边框底色的分段盒子放在侧栏里像一个走错地方的表单控件——参照 Zed 状态栏 / Xcode 导航条,不带盒子):按钮统一 28×28、6px 圆角、14px 图标、2px 间距;**左端**——Sessions(messages-square,双气泡;单气泡的 message-square 留给消息级用途)/ Memory(brain)/ Skills(puzzle,2026-10-15)/ Insights(chart-column)四颗页切换,再接 brush-cleaning "Clean Up Sessions"(它是叠在会话视图上的模式,也靠左),当前页(或打开中的清理)那颗用侧栏行的选中色(`sidebar_accent` 底 + `sidebar_accent_foreground` 图标)做圆角底,与导航行选中态同一套语言;**右端只有齿轮 "Settings"**。左内边距 12.75 = 26.75(侧栏中轴)− 14(按钮半宽):最左那颗图标的中心与红绿灯红灯中心、导航行行首在同一条轴上。未选中的一律透明底、muted 图标,hover 才出色。**Refresh 不在工具条**:它住在每页页头右端(All Sessions 页头在 Sort 左侧,Memory / Skills / Insights 页头单独一个;tooltip 就叫 "Refresh"),会话页与 Insights 走整库重扫(Insights 的数据是扫描收尾派生的),Memory 页只同步记忆(读 Settings → Memory locations 的当下配置,不重扫会话;用户 2026-09-22 定各刷各的),Skills 页只重扫 skill;进行中转圈并禁用,⌘R 恒为刷会话。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。- Settings 默认 820×600,采用 180px 窄侧栏 + 内容页结构,固定为 General / Session locations / Memory locations / Remote hosts / Connect / Data / Updates / About 八项(侧栏项原叫 Locations,有了 Memory locations 后改成与页标题一致的 Session locations,用户 2026-09-21 定)(Connect 为 0.5.0 新增,插在 Remote hosts 与 Data 之间——两页都是"把 Wake 接到外部"的集成面,Data 之后是纯本地信息;Memory locations 是记忆可见层二期加的,紧挨 Locations——两页都是"Wake 读哪里");About 与功能设置分离并钉在侧栏底部,Wake 菜单的 About Wake 直达同一页。About 沿用 Kooky/Birth 的信息顺序:产品图标、名称、版本、tagline、GitHub、短分隔线、版权/许可证与作者署名。Updates 是独立功能页,仅在用户点击页面按钮或 macOS Wake 菜单的 Check for Updates 时读取 GitHub 最新正式 Release 元数据,明确呈现检查中/最新版/有新版/失败四种状态;有新版时打开 Release 页供用户下载,不后台检查、不自行覆盖应用包。内部常规文字按钮统一沿用主界面的 24px 高、6px 圆角和主题交互色,普通页面动作使用 muted 填充 + hairline;发现新版后的 View Update 是需要用户继续完成的主操作,使用 32px 高 primary 填充和轻阴影。Appearance 分段选择器也使用同一材质。General 只放真实可用的全局偏好,当前为持久化的 System / Light / Dark 外观选择与 Language(跟随系统或固定某个语言包,0.5.2 起);不提供默认 “Open In” 终端。Data 只展示 Wake 本地存储位置、会话数与磁盘占用并提供文件管理器入口,不重复放刷新或清库动作;下面一块「Hidden sessions」(2026-10-13 用户定"先加吧":删除存在别家自己数据里的会话其实是隐藏,原先隐藏了就再也找不回来),小标题与 Storage 同款,一张 popover 底圆角卡,一次隐藏一行(连同随它一起藏的子会话):17px 品牌图 + 会话标题为主信息、项目 · N 个子会话 · Hidden <日期> 为 muted 副信息,右端 24px 的 Unhide 按钮(进行中转圈、其余禁用),行间 hairline;对照中写 Checking…、没有时写 No hidden sessions;不弹通知,取消隐藏后那一行消失、会话回到主窗口列表;常规 Refresh 的唯一入口仍是主侧栏底部。Locations 页按 AgentId 声明序以 agent 分组,品牌名只在组头出现一次;本机有数据的组优先,未检测到的 agent 默认收进可展开区。每条路径以路径为主信息、会话数/不可用状态为 muted 副信息,最右为逐路径开关;停用时只降低文字层级,开关与菜单保持完整对比度。行本身不承担编辑,`…` 菜单集中 Edit / Show in Finder / 自定义 Remove。顶部操作为低强调的 Add location,Restore defaults 收进页级 `…` 菜单且无偏离时禁用。添加/编辑仍复用 agent 下拉 + 可手输路径 + 目录选择表单;关闭 location 后保留配置、停止扫描/监听并从会话与搜索结果排除,重新开启即增量扫回;纯路径管理不做内容校验。**Memory locations 页与 Locations 同版式**(2026-09-21 记忆可见层二期):标题 "Memory locations" + 一句说明 + 右侧 Add location + 页级 `…` 里的 Restore defaults;按 AgentId 声明序分组,一行一个记忆来源——各家默认的(Claude 的 auto-memory 树与 `~/.claude/CLAUDE.md`、Codex 的 memories 目录、逐线程库、`~/.codex/AGENTS.md` 与 `rules/`、Gemini 的 `~/.gemini/GEMINI.md`、ZCode 的记忆树)、项目根模式(`<project>/CLAUDE.md`、`<project>/.cursor/rules` 一类,原样显示占位符)与用户加的自定义目录/文件;路径为主信息、文件数(或 "Not found")为 muted 副信息,最右逐来源开关;`…` 菜单:默认来源只有 Show in Finder(项目模式连这个也没有),自定义来源多 Edit / Remove。添加/编辑与 Session locations 是同一个表单(`open_path_form`),差别是字段叫 "Folder or file"、选择器也收文件。改动不换 roster,只补一轮增量扫描,记忆流随之更新。Remote hosts 页沿用 Locations 的版式:标题 + 说明,右侧低强调的 Sync now / Add host;host 列表为单张 popover 底圆角卡,一行一台(名字为主信息、同步状态为 muted 副信息,失败用 danger),`…` 菜单集中 Sync now / Remove,最右为开关;添加走与 location 同材质的单字段表单弹窗,SSH 前提说明放在字段下方。列表与详情页的远程会话以 `@host` 徽章标识:列表行为 primary 淡底填充胶囊(与 muted 项目胶囊区分),详情页与 model/source 同排用 primary 描边。Connect 页沿用 Data 页的版式,**只放状态与动作,不放文档**(用户 2026-09-08 三轮定稿:平级双卡带代码块、嵌套同卡、缩进从属卡都试过,根源是设置窗里塞了 README 内容,怎么排都像教程):标题 + 一句说明(不点名 MCP、不写 read-only 声明);「MCP server」卡 84px 一行显示 wake-mcp 名称与 mono 字体的 `~/…` 路径,右侧复制钮,不放"Ready"状态行,只在找不到二进制时给一行 danger 文案;「MCP clients」卡三行(Claude Code / Codex / Cursor),17px 品牌图标领行、客户端名为主信息、用法提示为 muted 副信息、右侧是 ghost 的 Show/Hide 切换(chevron 图标 + 文案,muted 前景,用户 2026-09-08 追加)加复制钮;代码块**默认收起**,展开后出现在该行下方、左缘对齐到文字轴(行内边距 16 + 图标 17 + 间距 12),secondary 填充 + 主题圆角的 mono 逐行渲染,Settings 重开即复位。0.6.x 起页面是**四个区块**(用户 2026-09-11 定稿):MCP server / MCP clients / Command line / Skill——MCP server / Command line / Skill 各一张 84px 信息卡、MCP clients 仍是三行客户端列表(wake-mcp、wake-cli 是二进制名与 mono 路径 + 复制路径的钮;wake-cli 那张在它**左侧**多一个终端图标的复制钮,复制「把它放进 PATH」的那行命令——两颗一样的复制图标并排分不清,所以换字形;最右留给两张卡同为复制路径的那颗,纵向才对得齐;deb/tar 已装进 `…/bin` 或 Windows 上没有可粘命令时这个按钮不出现;Skill 是 `npx skills add …` + 复制钮),区块标题为「Agents」时看不出这块特指 MCP,故改名 MCP clients 与上方 MCP server 成对。**说明性 caption 一律不放**——那正是"设置窗里塞 README"的复发形态;Setup guide 链接改挂在区块标题右端,规则是**每个面的第一个区块挂自己的文档**:MCP server → docs/mcp.md,Command line → docs/cli.md(MCP clients 与 Skill 分属这两个面的第二块,不重复挂)。最上面另有两块 **Claude Code plugin** / **Codex plugin**(新会话开场就知道各个 agent 停在哪,并装上 Wake 的 MCP 工具;标题用各家正名,用户 2026-10-09 定——Codex 那块起初是它官方的 hooks 配置,2026-10-10 有了 Codex 插件后改名),各是一个面、各挂自己的 Setup guide(docs/cli.md 的两节);卡是 48px 一行,只有一句用法(正文字号、前景色,与卡片标题行同一种字)+ 右端复制钮,不摆等宽命令、不加品牌图与名字行(区块标题已点名);Windows 上两块都不画。四块之后整页**超过一屏、需要滚动**——2026-09-08 那条"一屏放下"的约束随第三、四个区块作废,滚动容器本来就在(`flex_1().min_h_0().overflow_y_scroll()`),卡片记得 `flex_shrink_0` 否则会被压扁。**复制钮一律只有图标**(用户 2026-10-09 定:卡上已经摆着要复制的东西或一句用法,按钮上再写 Copy path / Copy command 是重复):与文字按钮同材质、同 24px 高的方钮,13px 图标,说明在 tooltip;复制反馈是图标原地变 check(tooltip 变 Copied)1.6s 后复原,**不弹通知**——gpui-component 的 toast 在窗口失活或被悬停时暂停自动关闭,在 Settings 从属窗里经常就挂着不走(用户 2026-09-08 反馈),且主界面的 Copy Session ID / Copy code 本来就不弹;页面只展示不代写别家配置。- 工具条内的**状态行"常态沉默"**:仅刷新中或监听不可用时出现在按钮行上方;文案须可 truncate,窄侧栏放不下长句(故为 "Live updates off" 而非带操作建议的整句)。刷新中行首是与页头 Refresh 按钮 loading 态同一个 Spinner(12px、muted 色),文字下方 8px 处一条 3px 进度条(`Progress`,primary 色、轨道同色 20%;会话扫描按 done/total 定值,总数未知 / 记忆同步 / 远程同步走不定值滑动;2026-09-22 用户要的),出错时行首回到静态 refresh-cw 图标。- 手动 Refresh 始终后台运行;进度复用侧栏状态行,完成后发通知("Sessions refreshed" / "Memory refreshed"),不用模态框阻断浏览、搜索或阅读。@@ -234,6 +234,15 @@ emoji 不再承担界面或正文结构图标职责。- 阅读面头部是详情头部同款:44px 上下文行(品牌图 15 + agent 名 + 可点击的归属徽章(在文件管理器中打开项目),右端 Reveal / Copy path 两个 16px ghost 图标钮)→ 22px semibold 标题(可换行,最小 44px)→ Label 11 muted 两行元信息(file-text 图标 + `~` 折叠的文件路径;calendar 图标 + "Updated …",Hover 精确时间),`background` 底、hairline 收底、兼窗口拖拽区;正文 `popover` 底、720px 阅读宽居中、24px 阅读轴、上留 16 下留 24(与消息流首末条同数),与消息正文同一套 Markdown 渲染(相对链接按记忆文件所在目录解析)。- 列表非空时恒有选中项(重载落到第一份),正文后台读磁盘、读到前居中 Spinner,文件被 agent 改过重读。空库时左列只有页头,右侧 `empty_state_card`("No memory files yet" + 一句说明它们从哪来)。+### Skills++侧栏底部工具条的 Skills 钮(puzzle 图标,Memory 与 Insights 之间)进入;与 Memory 同为**整页目的地**,版式与 Memory 页同形(2026-10-15,issue #62)。只读:各家 agent 的 skill(`<目录>/<名字>/SKILL.md`)按名字归拢,看出装在哪几家、几份真实拷贝、哪些是链接、拷贝之间有没有分叉;不安装、不拷贝、不链接、不同步、不删除,动作只有 Reveal / Copy path。页头 Refresh **只重扫 skill**(不重扫会话);进页时也自动扫一次,几十毫秒。++- **侧栏**:标题换成 "Skills";All Skills(puzzle)+ Duplicated(copy,会话侧栏 Starred 的同位:两份及以上真实拷贝的,符号链接不算;为零不挂计数)两行,再接 Agents / Projects 两组(会话、记忆侧栏同一套组件与单选模型)。Agents 组第一行是 **Shared**(layers 图标,多家共读的 `~/.agents/skills`,它不是一家 agent,悬停显示路径),其余按 AgentId 序;Projects 只列有项目级 skill 的项目,按项目名排。计数是 skill 数(一个 skill 在 Claude 的用户级、插件、项目级各有一份,Claude 行只算一个)。+- **列表**:按名字排(不分大小写),不按时间分组——skill 是一份目录,不是时间线。行盒与记忆行同一套(16/12 内缩、选中 `list_active`、悬停 `list_hover`),三层:Body 14 medium 名字(按显示宽度截断、悬停全名)→ Caption 12 muted 的 description 一行(没有就不占这一行)→ Label 11:归属图标(品牌图 15px,Shared 用 layers 线条图标;最多五个,其余 "+N")+ 徽章("plugin" 为紫色淡底 + 紫字的填充胶囊——theme.rs `plugin_badge_color`,深浅两档,界面里别处不用这个色,用户 2026-10-23 定要比灰胶囊亮、又不和 `@host` 的蓝撞;"N copies" / "linked" 为 muted 胶囊,"differs" 为 muted 描边胶囊——是提醒不是错误,不用 danger;插件自带的 skill 只挂 "plugin" 徽章、侧栏不设 Plugins 入口:插件是一个包,skill 只是它可能带的一样东西,在 Skills 页侧栏放 Plugins 读起来像插件是 skill 的一种,用户 2026-10-23 定;以后做插件全貌的整页时再讲插件)+ 右对齐更新时间(各处 SKILL.md 里最新的)。读不出的位置(权限等,不是"没有")在页头下各一行 Label 提示(triangle-alert 12px + "Couldn't read ~/…",悬停看错误原文)。+- **阅读面**:头部是详情头部同款,说的是**当前显示的那一处**:品牌图 + 归属名 + 层级(项目胶囊可点开项目目录 / 插件名胶囊,用户级不挂)→ 22px 标题 = skill 名 → SKILL.md 路径与更新时间两行元信息;右端 Reveal / Copy path。正文 `popover` 底、720 阅读宽:description(13px muted)→ 位置表(Label 组头 "N locations";一行一处,32px 行高:18px 槽位里的归属图标 + 归属名 + 层级 + `~` 折叠路径(截断,悬停全路径)+ 标签 "link" / "disabled"(停用的插件)/ 有分叉时标 "same" 或描边的 "different"(相对当前显示的那份)+ 14px Reveal 钮;当前那行 `list_active`,点一行就换成显示那一份)→ 有两份及以上拷贝时一句 Caption muted 提示 "To keep one copy and link it into several agents, use npx skills add."(Wake 只看不装)→ hairline → 去掉 frontmatter 的 SKILL.md,与消息正文同一套 Markdown 渲染(相对链接按该 skill 目录解析)。+- 默认显示哪一处:侧栏点了某家 / 某项目就先显示那一处,否则最近改过的那份;重扫后按路径找回,文件改过重读。空库时右侧 `empty_state_card`("No skills found" + 一句说明 skill 是什么、在哪)。+### 本机会话清理- Filter 使用 16px 内边距,标题、日期区、来源区与操作栏共用左缘。标题右侧提供「仅显示可清理」多选选项,默认关闭并随其他条件一起记忆、清除。Clear(悬停提示 Clear filters)与 Done 集中到底栏,均为 32px 高、6px 圆角,复用 Settings 的普通/主要按钮样式;常态实色填充,前者 secondary、后者 primary,Done 最小宽度 80px。@@ -241,7 +250,7 @@ emoji 不再承担界面或正文结构图标职责。- 清理入口 Delete 与最终 Confirm 按钮统一使用现有 danger 样式;取消选择、筛选与排序仍使用各自的普通控件。检查阶段显示已检查数 / 总数并可取消,执行阶段显示已处理数 / 总数并允许完成当前会话后停止。取消检查不产生确认框或清理记录。- 确认框标题用 Delete this session?/Delete N sessions?,顶部仅接一行 Caption/muted 的 Local files · About X 体积摘要,随后直接显示会话列表。两条短说明固定在列表下方、按钮上方,与列表共用左缘:先说明可从废纸篓恢复及释放空间的条件,再说明原工具可能无法继续会话。说明区顶部的分隔线固定,清单内仅在会话之间分隔;说明与按钮间距 16px,不随文件列表滚动。移除重复的长段落和清理页中额外的 Codex 说明;文件名使用 12px muted 等宽文字,过长时省略,悬停可见完整路径。只有一项时使用单数文案。结果区把未开始、已移动、需要处理分开,未开始不标红;没有移动文件时不提示空间待回收。-- 入口在侧栏底部工具条左端,排在 Sessions / Memory / Insights 三颗页切换之后(见「资料库侧栏」);清理使用 14px `brush-cleaning` 图标,打开时用侧栏选中色做圆角底表达激活态。+- 入口在侧栏底部工具条左端,排在 Sessions / Memory / Skills / Insights 四颗页切换之后(见「资料库侧栏」);清理使用 14px `brush-cleaning` 图标,打开时用侧栏选中色做圆角底表达激活态。- 清理页保留侧栏,主区与 Insights 共用 `background` 页面底色及 24px 水平留白。标题通过 `library_header` 与 All Sessions、Insights 共用:88px 高、22px 标题、11px 副行、2px 行间距并支持窗口拖拽,Filter、Sort、刷新对齐标题首行右侧;不放装饰图标、独立体积大字或嵌套卡片。- 标题下直接进入列表,不设置内容分类标签或独立工具栏。Filter 内容宽 468px,使用单层弹出面板:两项日期各用一行完整时长选项,沿用 Appearance 的中性分段控件,选中项用 popover 底色与轻阴影;Exclude 以独立标题与下方等宽选项呈现收藏/置顶/无法清理排除,标题右侧不放筛选条件。日期与排除条件固定可见。Agent、项目与 Exclude 统一使用原 Agents 的选项块样式:28px 行高、12px 文字,选中时浅蓝底色与右侧勾号,未选中时使用浅中性底色和细边框,不使用方形复选框。Agent 的 15px 品牌图标位于名称左侧。来源区域以分隔线分组,Sources 标题右侧放 284px 宽搜索框,来源选项单独滚动。输入来源搜索词不改变会话范围,点选后立即生效且面板保持打开。创建时间与更新时间各自提供完整时长快捷项,组合时取交集;副标题同时显示生效条件。旧单日期偏好迁移到对应项,另一项不限。候选无预设大小或对话轮数门槛,旧内容分类偏好加载时忽略。- 收藏与置顶默认不排除,选中的排除条件同步显示在页面副标题;时间门槛完全由时间筛选决定,不另设隐藏的 7 天保护。可清理和无法清理的会话统一显示,参与同一套创建/更新日期、来源、收藏和置顶筛选以及排序。无法清理项禁用勾选,标题与品牌图保持正常显示,来源信息后直接呈现简短原因,完整说明通过悬停查看,保留预览;不再提供额外展开入口或原因弹窗。大小未知显示「—」,按大小升降序均排在最后,统计只累加可清理体积。Filter 可显式开启「仅显示可清理」。所有计数均为当前筛选范围;全选只选择可清理会话。diff --git a/PRODUCT.md b/PRODUCT.mdindex 7b3e157..6c0ef59 100644--- a/PRODUCT.md+++ b/PRODUCT.md@@ -28,7 +28,7 @@ Corey 本人(独立开发者,主力工具 Claude Code 与 Codex,中文为主)。## Capabilities and Constraints-已实现:二十三家 adapter、FTS5 trigram 搜索(<3 码点 LIKE 降级)、**搜索跳转定位**(2026-08-18:⌘K 命中直达详情页对应消息并高亮,seq 契约保证)、详情页逐消息渲染(气泡/工具折叠簇/thinking/tree-sitter 高亮;2026-08-17 由整篇 markdown 方案升级)、恢复/收藏/置顶/导出/删除(废纸篓+墓碑)、**子代理即子会话**(2026-10-12:各家 agent 派出去的子代理一律作为子会话挂在派它的会话下;Claude Code、Cursor、CodeBuddy / WorkBuddy、Qoder、Kimi Code 放在会话目录里的子代理转录也各自入库,能单独搜索、打开,Claude Code 的 Workflow 步骤同样;列表最多两层嵌套(原件 → 分支 → 分支派的子代理);详情页里派活的工具调用上有"打开子代理会话"、子会话头部有回到父会话的链接,对得上派活调用的家才有按钮;子代理随父会话一起删除,Claude Code 的分支不随原件删;子代理不能单独恢复,不给 Open In)、文件监听增量、Insights 统计页(0.3.0:活跃热力图与 streak、时段/星期/月份分布、Agents·Projects·Models 三榜单按 sessions/tokens/prompts 切换;2026-09-03 加 Last 7 days 周对比行与 Over time 近 53 周按 agent 堆叠的每周 prompts 趋势图;口径=主线用户消息,agent 派出去的子会话不算会话与提问、token 照算(2026-10-12),规格见 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(0.4.0,issue #21:Settings → Remote hosts 配 SSH 目标,rsync 白名单镜像会话数据到本地缓存后与本地会话同列同搜,`@host` 徽章标识;阶段 1 只读——不动远端文件、远程会话禁删,resume 以 Copy SSH command 形态提供;分期计划见 CLAUDE.md「远程 host」节)、**MCP 接入**(0.5.0:随应用打包的只读 `wake-mcp` stdio server,四个工具 wake_search / wake_list_sessions / wake_get_session / wake_list_projects,Claude Code / Codex / Cursor 等任何 MCP 客户端可搜历史、按项目列会话、分页读转录;Settings → Connect 展示路径与可复制配置片段,只展示不代写别家配置;零 LLM、零网络、不写库;完整参考 docs/mcp.md)、**命令行与 Skill**(0.6.0:并排打包的只读 `wake-cli`,四个子命令 search / sessions / show / projects 加 setup,给"能跑 shell 但不说 MCP"的 agent 和真人用——它不新写查询逻辑,argv 翻成 JSON 喂同一批工具,输出与 MCP 客户端看到的**逐字节相同**(仅 CLI 末尾补一个换行)并由测试卡住,所以文档只需描述一份格式;`skills/wake/SKILL.md` 是可一行安装的 skill(`npx skills add iAmCorey/Wake`),用触发条件而非名词解释写 description,让 agent 自己想得起来去翻会话历史;完整参考 docs/cli.md;0.6.3 加 `wake-cli index`——装了 Wake 却从没启动过时,agent 自己跑一条就能把索引建起来继续干活,而不是停下来问人。它**只建不存在的索引**,已有的库原样交给 GUI:扫描落在旁边的临时库、扫完才原子占位,所以被中途杀掉可重试、撞上 GUI 首扫就退让;2026-09-22 加 `wake-cli refresh`,issue #43:app 不开时增量刷新已有索引,给靠 MCP / CLI 用 Wake、只在浏览时开 app 的人用 launch agent / systemd timer 定时跑,Wake 开着窗或还有扫描在写就退让——GUI 与两个写命令共用一把索引写锁,锁跟 Workbench 与写线程走、关窗即放,GUI 启动会等正在跑的 refresh 收尾)、Connect 页四区块(0.6.1:MCP server / MCP clients / Command line / Skill,每个面的第一块挂自己的文档链接)、**记忆可见层**(2026-09-17 起,只读:把各家 agent 自己写下的记忆——Claude Code 的按项目 auto-memory、Codex 的 memories 与逐会话摘要、ZCode 的按项目记忆——按项目聚合;GUI 的 Memory 页是侧栏底部的整页目的地,侧栏在这一页换成按记忆计数的 All Memory / Agents / Projects 导航;MCP 加第五个工具 `wake_list_memories`,`wake_get_session` 认 `wake://memory/…` 引用现场读文件,`wake_search` 末尾附记忆命中;CLI 加 `memories`;记忆的项目归属按它挂的会话在读时解析,永远跟着索引走。二期(2026-09-21)把用户写给 agent 的指令文件也收进来:各家 home 里的 CLAUDE.md / AGENTS.md(与 `rules/*.rules`)/ GEMINI.md,以及已索引项目根下的 CLAUDE.md / AGENTS.md / GEMINI.md / `.cursor/rules` / `.cursorrules` / `.kiro/steering` / `.github/copilot-instructions.md`,与记忆同列同搜、不另作区分;Settings 加 Memory locations 页,与 Session locations 同形制:逐来源开关、添加自定义目录或文件、Restore defaults。不编辑、不同步、不删除——写别家数据破铁律,要改一个 Reveal 就到;也不做"把会话自动写成记忆")。后续边界(2026-09-07 定):摘要层(需 LLM、opt-in、明示会把会话正文发给用户配置的端点)只在 MCP 接入有真实使用之后再做;Timeline / Profile 一类视图建立在摘要之上;不做 ChatGPT / Claude.ai 导出导入主线、不做实体本体与知识图谱、不做 Chrome 扩展注入。+已实现:二十三家 adapter、FTS5 trigram 搜索(<3 码点 LIKE 降级)、**搜索跳转定位**(2026-08-18:⌘K 命中直达详情页对应消息并高亮,seq 契约保证)、详情页逐消息渲染(气泡/工具折叠簇/thinking/tree-sitter 高亮;2026-08-17 由整篇 markdown 方案升级)、恢复/收藏/置顶/导出/删除(废纸篓+墓碑)、**子代理即子会话**(2026-10-12:各家 agent 派出去的子代理一律作为子会话挂在派它的会话下;Claude Code、Cursor、CodeBuddy / WorkBuddy、Qoder、Kimi Code 放在会话目录里的子代理转录也各自入库,能单独搜索、打开,Claude Code 的 Workflow 步骤同样;列表最多两层嵌套(原件 → 分支 → 分支派的子代理);详情页里派活的工具调用上有"打开子代理会话"、子会话头部有回到父会话的链接,对得上派活调用的家才有按钮;子代理随父会话一起删除,Claude Code 的分支不随原件删;子代理不能单独恢复,不给 Open In)、文件监听增量、Insights 统计页(0.3.0:活跃热力图与 streak、时段/星期/月份分布、Agents·Projects·Models 三榜单按 sessions/tokens/prompts 切换;2026-09-03 加 Last 7 days 周对比行与 Over time 近 53 周按 agent 堆叠的每周 prompts 趋势图;口径=主线用户消息,agent 派出去的子会话不算会话与提问、token 照算(2026-10-12),规格见 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(0.4.0,issue #21:Settings → Remote hosts 配 SSH 目标,rsync 白名单镜像会话数据到本地缓存后与本地会话同列同搜,`@host` 徽章标识;阶段 1 只读——不动远端文件、远程会话禁删,resume 以 Copy SSH command 形态提供;分期计划见 CLAUDE.md「远程 host」节)、**MCP 接入**(0.5.0:随应用打包的只读 `wake-mcp` stdio server,四个工具 wake_search / wake_list_sessions / wake_get_session / wake_list_projects,Claude Code / Codex / Cursor 等任何 MCP 客户端可搜历史、按项目列会话、分页读转录;Settings → Connect 展示路径与可复制配置片段,只展示不代写别家配置;零 LLM、零网络、不写库;完整参考 docs/mcp.md)、**命令行与 Skill**(0.6.0:并排打包的只读 `wake-cli`,四个子命令 search / sessions / show / projects 加 setup,给"能跑 shell 但不说 MCP"的 agent 和真人用——它不新写查询逻辑,argv 翻成 JSON 喂同一批工具,输出与 MCP 客户端看到的**逐字节相同**(仅 CLI 末尾补一个换行)并由测试卡住,所以文档只需描述一份格式;`skills/wake/SKILL.md` 是可一行安装的 skill(`npx skills add iAmCorey/Wake`),用触发条件而非名词解释写 description,让 agent 自己想得起来去翻会话历史;完整参考 docs/cli.md;0.6.3 加 `wake-cli index`——装了 Wake 却从没启动过时,agent 自己跑一条就能把索引建起来继续干活,而不是停下来问人。它**只建不存在的索引**,已有的库原样交给 GUI:扫描落在旁边的临时库、扫完才原子占位,所以被中途杀掉可重试、撞上 GUI 首扫就退让;2026-09-22 加 `wake-cli refresh`,issue #43:app 不开时增量刷新已有索引,给靠 MCP / CLI 用 Wake、只在浏览时开 app 的人用 launch agent / systemd timer 定时跑,Wake 开着窗或还有扫描在写就退让——GUI 与两个写命令共用一把索引写锁,锁跟 Workbench 与写线程走、关窗即放,GUI 启动会等正在跑的 refresh 收尾)、Connect 页四区块(0.6.1:MCP server / MCP clients / Command line / Skill,每个面的第一块挂自己的文档链接)、**记忆可见层**(2026-09-17 起,只读:把各家 agent 自己写下的记忆——Claude Code 的按项目 auto-memory、Codex 的 memories 与逐会话摘要、ZCode 的按项目记忆——按项目聚合;GUI 的 Memory 页是侧栏底部的整页目的地,侧栏在这一页换成按记忆计数的 All Memory / Agents / Projects 导航;MCP 加第五个工具 `wake_list_memories`,`wake_get_session` 认 `wake://memory/…` 引用现场读文件,`wake_search` 末尾附记忆命中;CLI 加 `memories`;记忆的项目归属按它挂的会话在读时解析,永远跟着索引走。二期(2026-09-21)把用户写给 agent 的指令文件也收进来:各家 home 里的 CLAUDE.md / AGENTS.md(与 `rules/*.rules`)/ GEMINI.md,以及已索引项目根下的 CLAUDE.md / AGENTS.md / GEMINI.md / `.cursor/rules` / `.cursorrules` / `.kiro/steering` / `.github/copilot-instructions.md`,与记忆同列同搜、不另作区分;Settings 加 Memory locations 页,与 Session locations 同形制:逐来源开关、添加自定义目录或文件、Restore defaults。不编辑、不同步、不删除——写别家数据破铁律,要改一个 Reveal 就到;也不做"把会话自动写成记忆")、**Skills 只读总览**(2026-10-15,issue #62:各家 agent 把 skill 各自收在自己的目录里,同一个 skill 在几家各装一份、慢慢改得不一样,没处看全。Skills 页是侧栏底部的第四个整页目的地:按名字列出本机所有 skill——各家的用户级目录、多家共读的 `~/.agents/skills`、已索引项目里的项目级目录、Claude Code 插件自带的——每个 skill 标出装在哪几家、几份真实拷贝、哪些是符号链接、拷贝之间 SKILL.md 有没有分叉;侧栏是 All Skills / Duplicated / Agents(共享目录排第一)/ Projects;阅读面先列各处位置(点一处看那一份、标出与它相同还是不同、逐处 Reveal),再渲染 SKILL.md。只读:不安装、不拷贝、不链接、不同步、不删除——跨 agent 装同一份交给 `npx skills add`,Wake 只在有多份拷贝时提一句;不进索引库、不进 MCP / CLI(agent 本来就读自己的 skill))。后续边界(2026-09-07 定):摘要层(需 LLM、opt-in、明示会把会话正文发给用户配置的端点)只在 MCP 接入有真实使用之后再做;Timeline / Profile 一类视图建立在摘要之上;不做 ChatGPT / Claude.ai 导出导入主线、不做实体本体与知识图谱、不做 Chrome 扩展注入。约束:对 agent 数据目录只读;绝不写 Codex 的 SQLite;不读凭证;GPUI 无 SF Symbols(图标用 lucide SVG 自备)。已支持二十三家 agent:Claude Code、Codex(0.6.6 起排除可识别的内部线程:guardian auto-review、`/review`、compaction、memory consolidation 与用户会话同树,adapter 文件边界按首行 session_meta 的 source / thread_source 认出即不枚举;老格式或读不出的首行保守放行,`codex exec --thread-source` 打了标签的自动化线程照常收录,issue #30。`spawn_agent` 子代理是其中唯一的例外,issue #42:那是用户自己派出去的活,收录后挂在派它的会话下面、以任务名为标题,fork 进来的父线程历史折成一条不入库的占位,父会话的对话不会被索引两遍)、Qoder CLI(`~/.qoder/projects` JSONL,active-leaf 分支恢复、tool result 回挂、`QODER_CONFIG_DIR`)、Copilot CLI、Cursor(CLI 转录 + 0.6.7 起 IDE Chat/Composer 历史,PR #32:`globalStorage/state.vscdb` 明文 KV 库,composerData 给顺序、bubbleId 行给正文;转录带正文的会话归转录源,库只补转录缺失或只剩 turn_ended 空壳的会话;库里多数老会话没存工作区路径,落 Unknown project)、OpenCode(含 OpenCode 2 next,stable 的 `opencode.db` 与 next 的 `opencode-next.db` 同时扫描;逐会话兼容 `message+part`、真实 `session+session_message` 及早期 `session_v2` schema;preview 会话标 opencode2 徽章;2026-10-12 起 task 工具派出的子代理会话也收录,挂在派它的会话下)、Kiro、Gemini CLI(2026-08-17 P1 五家落地)+ Pi、Oh My Pi、Grok Build、Kimi Code、Antigravity(2026-08-19 对齐 kooky 内置 roster,起初只有 `antigravity-cli` 会话索引里的元数据卡片——正文是加密 .pb;2026-10-08 起读新版本桌面端与 IDE 写在 `~/.gemini/antigravity/brain`、`~/.gemini/antigravity-ide/brain` 的明文转录,含工具输出、模型与用户贴图,IDE 会话挂 via 徽章,同一会话转录与卡片按 id 只出一份、没有转录的仍列卡片;显示名由 Antigravity CLI 改为 Antigravity;2026-10-12 起索引里记了父会话的子会话挂在父会话下。格式取自 PR #52 @iroha3 对真实数据的整理,本机 brain 目录还没有转录,未经真机验证)+ DeepSeek Harness(dsh,2026-08-20,zstd 事件日志透明解压;格式由源码推断,当天用户跑出真实会话完成首验;2026-10-11 起委派出去的子代理会话也收录,挂在派它的会话下、以任务名为标题,issue #63,fork 出来的会话开头复制的父会话历史折成一条,token 只算自己的)+ Hermes Agent(2026-09-03,多档案 state.db,无 cwd 故 project 留空)、OpenClaw(2026-09-03,两代存储同扫;2026-10-12 起派生的子代理与面板上开的子会话挂在父会话下;本机零会话,格式由源码推断未经真机验证)、CodeBuddy(2026-09-14,issue #27:`~/.codebuddy/projects` 的 Responses 形 JSONL,custom / ai / topic 三级标题,`CODEBUDDY_CONFIG_DIR`;本机零会话,格式由官方 CLI 文档与三家第三方实现交叉推断、未经真机验证)、WorkBuddy(同日,CodeBuddy 的孪生实例:同一解析核心,`~/.workbuddy/projects`、`WORKBUDDY_CONFIG_DIR`;桌面 app 无 CLI,不提供 resume;同构只有 cc-switch 一家佐证)、ZCode(2026-09-21:Z.ai 的 GLM-5.3 官方 harness,桌面 app;运行时是 OpenCode 衍生物——`~/.zcode/cli/db/db.sqlite` 的 session/message/part 与 OpenCode v1 同形、part 解码复用,但 session 表没有 model/tokens 列故另起一家;`v2/tasks-index.sqlite` 只借 deleted / migration_source 两个过滤位;照桌面端自己的分法列:任务列表里的 interactive / fork / workflow_parent 顶层列出,辅助对话、子代理与工作流的子会话挂在父任务下(2026-10-12);分叉开头从父任务复制来的历史折成一条,辅助对话以首条提问为标题;`semantics.transcriptVisibility == hidden` 与用户消息 `origin != real_user` 归 Meta、compact_summary 折成一条、字段缺席放行;`ZCODE_STORAGE_DIR`;桌面 app 无 CLI、`zcode://` 没有按会话打开的深链,不提供 resume;本机 3.14.0 真会话首验通过,同日开源(Apache-2.0)后语义全部按源码核对)、Craft Agents(2026-09-24,issue #44:Craft Docs 的开源桌面 app,自己不带引擎——Anthropic 连接跑 Claude Agent SDK、其余连接(ChatGPT / Codex 订阅、Copilot、Google)跑 Pi SDK,另记一份给用户看的 `~/.craft-agent/workspaces/<工作区>/sessions/<id>/session.jsonl`,Wake 读这一份;子任务与分支挂回原会话,分支从父会话复制来的那段折成一条;Claude 连接在 `~/.claude/projects` 留下的引擎副本由通用的"认领"机制藏掉,原件还在才藏;工作区可建在任意位置,但登记表带 server token 不读,别处的工作区走 Session locations;桌面 app 无 CLI,不提供 resume;本机 0.13.5 真会话首验通过,ChatGPT 与 Claude 连接各一条)、Devin(2026-09-24,issue #46:`~/.local/share/devin/cli/sessions.db` 单库两表,message_nodes 森林按 `main_chain_id` 叶子沿 `parent_node_id` 取主链,hidden 会话与零正文不列,逐消息 `generation_model` 与 `metrics` 按主链累计;`XDG_DATA_HOME`;`devin --resume <id>` 按 cwd 分桶 resume;格式按本机真库验证)、Kilo Code(2026-10-07,issue #59:一家两源——2026-04 起的新版 VS Code 扩展、`kilo` CLI 与 JetBrains 插件是 OpenCode 分支,三端共用 `~/.local/share/kilo/kilo.db`,表与 OpenCode 同形、按 OpenCode 的孪生实例读,子代理会话同样挂在父会话下;session_message 里只有实验开关零星双写的 shell 一类记录时读 message + part(OpenCode 同一条规则);旧版扩展(Roo / Cline 系)每个任务一个目录,在各个 VS Code 系编辑器的 `globalStorage/kilocode.kilo-code/tasks` 里,正文是 Anthropic 消息数组,`<task>` / `<feedback>` / `<answer>` 才是人打的字、编辑器快照丢掉,旧任务用新版导入时给的 `ses_migrated_` id,导入过的那份 kilo.db 胜出;新版 `kilo --session` 在原项目目录续,旧任务没有 Open In、也不实时监听(任务目录里有整份 checkpoints 影子仓库);kilo.db 里同库存着凭证,远程只同步 vscode-server 下的旧任务;本机零会话,新版的表结构按源码的建库语句核过,数据形状由源码推断、未经真机验证)、Grok Bot(2026-10-11:xAI 的常驻 agent,桌面 app 由 Cursor 出品,bot 跑在云端电脑上,对话也存在那里;本机只有桌面端的滚动缓存 `<userData>/sand-client-persistence`——每个对话只留最近 200 条、最多 24 个对话、7 天没写过的被 app 自己清掉。用户定"跟着缓存走":缓存里有的对话出完整消息(你的话、bot 的话、群聊里标出是哪个 bot、bot 之间互发的消息、提问卡片与你的回答、邮件草稿、审批),被清出缓存的退成侧栏列表里的一张卡片(描述 + 最后一条预览),不会从 Wake 里消失;对话本体在云端,删除只隐藏、不动缓存文件;没有命令行,不提供 resume;不做远程同步;格式按 0.68.1 的 app 源码与本机 14 个真实对话核对)。做不了的:Windsurf/Trae 加密,Amp/Factory(Droid)/Warp 云端无本地数据,Reasonix 本机零会话格式未实测。diff --git a/README.md b/README.mdindex e4c7cb6..38b41be 100644--- a/README.md+++ b/README.md@@ -26,6 +26,7 @@ Your agent history is scattered across `~/.claude`, `~/.codex` and many other fo- **Manage** — star, pin, export to Markdown, hand a session to another agent, delete to the Trash- **Clean up** — find the sessions eating your disk and clear them out in one go- **Memory** — the notes and instruction files your agents keep (`CLAUDE.md`, `AGENTS.md`, auto-memory, Cursor rules, …), by agent and project+- **Skills** — every skill your agents have installed, which agents share each one, and which copies have drifted apart- **Insights** — activity heatmap, streaks, weekly trends, and your top agents, projects and models- **Remote hosts** — mirror the sessions on your other machines over SSH- **MCP and CLI** — `wake-mcp` and `wake-cli` let any agent search your history and read transcripts@@ -215,6 +216,7 @@ crates/│ ├── remote.rs # remote hosts: ssh probe + rsync whitelist mirror into <data dir>/remotes/<host>/│ ├── scanner.rs # single-pass scan: meta + FTS in one go, mtime incremental│ ├── watcher.rs # notify-based file watching → per-file incremental updates+│ ├── skills.rs # read-only skills overview: each agent's skill folders, grouped by skill│ ├── db.rs # rusqlite (WAL): sessions, the full-text index, memories, stars/pins, tombstones, settings│ ├── mcp/ # wake-mcp: read-only MCP server over stdio (hand-written JSON-RPC, five tools)│ ├── cli.rs # wake-cli: argv → the same five tools, same text out as MCPdiff --git a/crates/wake-core/src/adapters/claude.rs b/crates/wake-core/src/adapters/claude.rsindex e64f6bf..37e1724 100644--- a/crates/wake-core/src/adapters/claude.rs+++ b/crates/wake-core/src/adapters/claude.rs@@ -1084,6 +1084,10 @@ impl AgentAdapter for ClaudeAdapter {Some(self.session_paths(meta))}+ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }+fn memory_sources(&self) -> Vec<MemorySource> {// auto-memory 树(agent 记的、按项目)+ 全局 CLAUDE.md(用户写的指令,对每个// 项目都成立);项目根下的 CLAUDE.md 由 project_instruction_sources 给diff --git a/crates/wake-core/src/adapters/codebuddy.rs b/crates/wake-core/src/adapters/codebuddy.rsindex b5c9ee4..43ebddc 100644--- a/crates/wake-core/src/adapters/codebuddy.rs+++ b/crates/wake-core/src/adapters/codebuddy.rs@@ -39,6 +39,8 @@ use std::path::{Path, PathBuf};pub struct CodebuddyAdapter {agent: AgentId,root: PathBuf,+ /// 配置目录(`~/.codebuddy` / `*_CONFIG_DIR`);直接选中 projects 目录的自定义根没有+ home: Option<PathBuf>,}impl CodebuddyAdapter {@@ -52,17 +54,17 @@ impl CodebuddyAdapter {}fn twin(agent: AgentId, home_dir_name: &str, env_key: &str) -> Self {- let default = super::home_dir()- .unwrap_or_default()- .join(home_dir_name)- .join("projects");- let root = super::env_dir(env_key)- .map(|dir| dir.join("projects"))+ let default = super::home_dir().unwrap_or_default().join(home_dir_name);+ let home = super::env_dir(env_key)// 与其他 env override 一致:存在但没有任何会话的候选不能遮掉默认根// (Dock 启动与 shell 启动看到的环境经常不同)- .filter(|dir| project_tree_has_session(dir, agent))+ .filter(|dir| project_tree_has_session(&dir.join("projects"), agent)).unwrap_or(default);- Self { agent, root }+ Self {+ agent,+ root: home.join("projects"),+ home: Some(home),+ }}}@@ -503,18 +505,23 @@ impl AgentAdapter for CodebuddyAdapter {}fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {- let root = if dir.join("projects").is_dir() {- dir.join("projects")+ let (root, home) = if dir.join("projects").is_dir() {+ (dir.join("projects"), Some(dir))} else {- dir+ (dir, None)};Box::new(Self {agent: self.agent,root,+ home,})}fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}diff --git a/crates/wake-core/src/adapters/codex.rs b/crates/wake-core/src/adapters/codex.rsindex 42ba282..035e29b 100644--- a/crates/wake-core/src/adapters/codex.rs+++ b/crates/wake-core/src/adapters/codex.rs@@ -1302,6 +1302,10 @@ impl AgentAdapter for CodexAdapter {Some(self.session_paths(meta))}+ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }+fn memory_sources(&self) -> Vec<MemorySource> {// memories/ 与 memories_1.sqlite(agent 记的)、AGENTS.md 与 rules/*.rules(用户// 写的指令)都是 CODEX_HOME 直属;只选了 sessions 目录或裸 rollout 拷贝的自定义diff --git a/crates/wake-core/src/adapters/copilot.rs b/crates/wake-core/src/adapters/copilot.rsindex f531414..fd96e02 100644--- a/crates/wake-core/src/adapters/copilot.rs+++ b/crates/wake-core/src/adapters/copilot.rs@@ -18,17 +18,18 @@ pub struct CopilotAdapter {rows_cache: Mutex<Option<(i64, Vec<CopilotRow>)>>,/// 指令文件(项目根下的)与自定义来源按指纹缓存,每轮扫描只 statmemories: super::MemoryCache,+ /// `~/.copilot`;自定义根直接给了库文件的没有+ home: Option<PathBuf>,}impl CopilotAdapter {pub fn new() -> Self {+ let home = super::home_dir().unwrap_or_default().join(".copilot");Self {- db: super::home_dir()- .unwrap_or_default()- .join(".copilot")- .join("session-store.db"),+ db: home.join("session-store.db"),rows_cache: Mutex::new(None),memories: super::MemoryCache::new(),+ home: Some(home),}}@@ -263,19 +264,24 @@ impl AgentAdapter for CopilotAdapter {fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// 手输/预填的就是库文件路径时直接认,不再往下拼(Codex review)- let db = if dir.is_file() {- dir+ let (db, home) = if dir.is_file() {+ (dir, None)} else {- dir.join("session-store.db")+ (dir.join("session-store.db"), Some(dir))};Box::new(Self {db,rows_cache: Mutex::new(None),memories: super::MemoryCache::new(),+ home,})}fn data_roots(&self) -> Vec<PathBuf> {vec![self.db.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}diff --git a/crates/wake-core/src/adapters/craft.rs b/crates/wake-core/src/adapters/craft.rsindex a242495..35126ef 100644--- a/crates/wake-core/src/adapters/craft.rs+++ b/crates/wake-core/src/adapters/craft.rs@@ -38,16 +38,17 @@ pub struct CraftAdapter {root: PathBuf,heads: HeadCache,workspaces: WorkspaceIds,+ /// `~/.craft-agent`;直接选中工作区集合或单个工作区的自定义根没有+ home: Option<PathBuf>,}impl CraftAdapter {pub fn new() -> Self {- Self::at(- super::home_dir()- .unwrap_or_default()- .join(".craft-agent")- .join("workspaces"),- )+ let home = super::home_dir().unwrap_or_default().join(".craft-agent");+ Self {+ home: Some(home.clone()),+ ..Self::at(home.join("workspaces"))+ }}fn at(root: PathBuf) -> Self {@@ -55,6 +56,7 @@ impl CraftAdapter {root,heads: HeadCache::default(),workspaces: WorkspaceIds::default(),+ home: None,}}@@ -696,15 +698,20 @@ impl AgentAdapter for CraftAdapter {fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// 选中的是 `.craft-agent` 本身就下到它的 workspaces/;工作区集合与单个工作区// 两种形态 session_files 都认- let root = if dir.join("workspaces").is_dir() {- dir.join("workspaces")- } else {- dir- };- Box::new(Self::at(root))+ if dir.join("workspaces").is_dir() {+ return Box::new(Self {+ home: Some(dir.clone()),+ ..Self::at(dir.join("workspaces"))+ });+ }+ Box::new(Self::at(dir))}fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}diff --git a/crates/wake-core/src/adapters/cursor.rs b/crates/wake-core/src/adapters/cursor.rsindex 3ac28f4..287fe15 100644--- a/crates/wake-core/src/adapters/cursor.rs+++ b/crates/wake-core/src/adapters/cursor.rs@@ -24,17 +24,18 @@ pub struct CursorAdapter {metadata_db: Option<PathBuf>,/// 指令文件(项目根下的 .cursor/rules、.cursorrules)与自定义来源按指纹缓存,每轮扫描只 statmemories: super::MemoryCache,+ /// `~/.cursor`;直接选中 projects 目录的自定义根没有+ home: Option<PathBuf>,}impl CursorAdapter {pub fn new() -> Self {+ let home = super::home_dir().unwrap_or_default().join(".cursor");Self {- root: super::home_dir()- .unwrap_or_default()- .join(".cursor")- .join("projects"),+ root: home.join("projects"),metadata_db: Some(cursor_ide::default_db_path()),memories: super::MemoryCache::new(),+ home: Some(home),}}@@ -703,19 +704,24 @@ impl AgentAdapter for CursorAdapter {fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// 选中 `~/.cursor` 形态(含 projects/)或直接选中 projects 目录都认- let root = if dir.join("projects").is_dir() {- dir.join("projects")+ let (root, home) = if dir.join("projects").is_dir() {+ (dir.join("projects"), Some(dir))} else {- dir+ (dir, None)};Box::new(Self {root,// 自定义目录也用于远程缓存,不能混用本机 IDE 元数据。metadata_db: None,memories: super::MemoryCache::new(),+ home,})}+ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }+fn data_roots(&self) -> Vec<PathBuf> {// 空根 = 本条 location 已被用户移除(见 excluding_data_roots)if self.root.as_os_str().is_empty() {@@ -767,6 +773,7 @@ impl AgentAdapter for CursorAdapter {root: PathBuf::new(),metadata_db: None,memories: super::MemoryCache::new(),+ home: None,}))} else {None@@ -809,6 +816,7 @@ mod tests {root,metadata_db: Some(db),memories: crate::adapters::MemoryCache::new(),+ home: None,};let r = adapter.file_ref(&file).unwrap();(dir, adapter, r)@@ -1012,6 +1020,7 @@ mod tests {root,metadata_db: Some(metadata_db),memories: crate::adapters::MemoryCache::new(),+ home: None,})];let events = Events::default();run_scan(&adapters, &store, &events, false).unwrap();diff --git a/crates/wake-core/src/adapters/dsh.rs b/crates/wake-core/src/adapters/dsh.rsindex 8de19d1..1144f24 100644--- a/crates/wake-core/src/adapters/dsh.rs+++ b/crates/wake-core/src/adapters/dsh.rs@@ -30,22 +30,24 @@ pub struct DshAdapter {/// 之后只 stat 选代;换了一代、换了压缩格式才再读一次。目录一时列不出、新的那份一时打不开/// (权限、锁)交回上次读到的logs: Mutex<HashMap<PathBuf, (SessionFileRef, Option<String>)>>,+ /// `~/.dsh`;直接选中 sessions 目录的自定义根没有+ home: Option<PathBuf>,}impl DshAdapter {pub fn new() -> Self {- Self::at(- super::home_dir()- .unwrap_or_default()- .join(".dsh")- .join("sessions"),- )+ let home = super::home_dir().unwrap_or_default().join(".dsh");+ Self {+ home: Some(home.clone()),+ ..Self::at(home.join("sessions"))+ }}fn at(root: PathBuf) -> Self {Self {root,logs: Mutex::new(HashMap::new()),+ home: None,}}@@ -764,17 +766,22 @@ impl AgentAdapter for DshAdapter {}fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {- let root = if dir.join("sessions").is_dir() {- dir.join("sessions")- } else {- dir- };- Box::new(Self::at(root))+ if dir.join("sessions").is_dir() {+ return Box::new(Self {+ home: Some(dir.clone()),+ ..Self::at(dir.join("sessions"))+ });+ }+ Box::new(Self::at(dir))}fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}#[cfg(test)]diff --git a/crates/wake-core/src/adapters/gemini.rs b/crates/wake-core/src/adapters/gemini.rsindex 133981d..b59047a 100644--- a/crates/wake-core/src/adapters/gemini.rs+++ b/crates/wake-core/src/adapters/gemini.rs@@ -302,6 +302,10 @@ impl AgentAdapter for GeminiAdapter {vec![self.root.clone()]}+ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }+fn memory_sources(&self) -> Vec<MemorySource> {// Gemini 没有 agent 自己记的记忆目录;`save_memory` 工具追加的 "Gemini Added// Memories" 段就在全局 GEMINI.md 里,整个文件按用户写的指令列。项目根下的diff --git a/crates/wake-core/src/adapters/grok.rs b/crates/wake-core/src/adapters/grok.rsindex 793be9c..78db7b6 100644--- a/crates/wake-core/src/adapters/grok.rs+++ b/crates/wake-core/src/adapters/grok.rs@@ -20,6 +20,10 @@ pub struct GrokAdapter {root: PathBuf,grok_home: PathBuf,group: Mutex<Option<Arc<GroupCtx>>>,+ /// 确认过的 home(`homes()`):默认实例与选中 home 形态(里面有 sessions/)的自定义根才有。+ /// 与 `grok_home` 不同——直接选了名叫 sessions 的目录时,读边车会按名字去父目录找,+ /// 但那不是用户选的范围,skill 不往那里看(Codex review 2026-10-15)+ home: Option<PathBuf>,}impl GrokAdapter {@@ -27,26 +31,28 @@ impl GrokAdapter {let grok_home = super::home_dir().unwrap_or_default().join(".grok");Self {root: grok_home.join("sessions"),+ home: Some(grok_home.clone()),grok_home,group: Mutex::new(None),}}fn from_custom_dir(dir: PathBuf) -> Self {- let (root, grok_home) = if dir.join("sessions").is_dir() {- (dir.join("sessions"), dir)+ let (root, grok_home, home) = if dir.join("sessions").is_dir() {+ (dir.join("sessions"), dir.clone(), Some(dir))} else if dir.file_name().is_some_and(|name| name == "sessions") {- let home = dir.parent().unwrap_or(&dir).to_path_buf();- (dir, home)+ let parent = dir.parent().unwrap_or(&dir).to_path_buf();+ (dir, parent, None)} else {// 保留旧行为:自定义目录也可以直接就是 sessions root。// 此时没有结构证据允许越过用户选择的边界去父目录读 sidecar。- (dir.clone(), dir)+ (dir.clone(), dir, None)};Self {root,grok_home,group: Mutex::new(None),+ home,}}@@ -538,4 +544,8 @@ impl AgentAdapter for GrokAdapter {fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}diff --git a/crates/wake-core/src/adapters/hermes.rs b/crates/wake-core/src/adapters/hermes.rsindex 2b85c6e..e549133 100644--- a/crates/wake-core/src/adapters/hermes.rs+++ b/crates/wake-core/src/adapters/hermes.rs@@ -22,6 +22,9 @@ use std::sync::OnceLock;/// 无每会话文件,SessionFileRef 用虚拟路径 `<db>#<id>`;多库结构与 opencode 同款。pub struct HermesAdapter {dbs: Vec<HermesDb>,+ /// 库是从一个目录(Hermes home 或档案目录)找出来的:各库所在目录就是确认过的 home。+ /// 自定义根直接给了一份 state.db 文件的没有 home,不往它旁边看(Codex review 2026-10-15)+ from_dir: bool,}struct HermesDb {@@ -106,12 +109,13 @@ impl HermesAdapter {let root = super::env_dir("HERMES_HOME").filter(|d| d.join("state.db").is_file()).unwrap_or_else(|| home.join(".hermes"));- Self::with_paths(dbs_under(&root))+ Self::with_paths(dbs_under(&root), true)}- fn with_paths(paths: Vec<PathBuf>) -> Self {+ fn with_paths(paths: Vec<PathBuf>, from_dir: bool) -> Self {Self {dbs: paths.into_iter().map(HermesDb::new).collect(),+ from_dir,}}@@ -517,18 +521,27 @@ impl AgentAdapter for HermesAdapter {fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// 选中库文件本身、Hermes home(连同其 profiles/*)或单个档案目录都认;// 整形判据只看 dir 内结构,目录不存在时也落到 <dir>/state.db(远程挂载点契约)- let paths = if dir.is_file() {- vec![dir]- } else {- dbs_under(&dir)- };- Box::new(Self::with_paths(paths))+ if dir.is_file() {+ return Box::new(Self::with_paths(vec![dir], false));+ }+ Box::new(Self::with_paths(dbs_under(&dir), true))}fn data_roots(&self) -> Vec<PathBuf> {self.dbs.iter().map(|db| db.path.clone()).collect()}+ /// 每个档案(HERMES_HOME 与 profiles/<名字>)各一个:state.db 所在的目录+ fn homes(&self) -> Vec<PathBuf> {+ if !self.from_dir {+ return Vec::new();+ }+ self.dbs+ .iter()+ .filter_map(|db| db.path.parent().map(Path::to_path_buf))+ .collect()+ }+fn supports_individual_root_removal(&self) -> bool {self.dbs.len() > 1}@@ -540,6 +553,6 @@ impl AgentAdapter for HermesAdapter {.filter(|db| !roots.contains(&db.path)).map(|db| db.path.clone()).collect();- Some(Box::new(Self::with_paths(kept)))+ Some(Box::new(Self::with_paths(kept, self.from_dir)))}}diff --git a/crates/wake-core/src/adapters/kiro.rs b/crates/wake-core/src/adapters/kiro.rsindex 9e01b85..951c4ee 100644--- a/crates/wake-core/src/adapters/kiro.rs+++ b/crates/wake-core/src/adapters/kiro.rs@@ -14,17 +14,17 @@ pub struct KiroAdapter {root: PathBuf,/// 指令文件(项目根下的)与自定义来源按指纹缓存,每轮扫描只 statmemories: super::MemoryCache,+ /// `~/.kiro`;选中 sessions 或 sessions/cli 的自定义根没有+ home: Option<PathBuf>,}impl KiroAdapter {pub fn new() -> Self {+ let home = super::home_dir().unwrap_or_default().join(".kiro");Self {- root: super::home_dir()- .unwrap_or_default()- .join(".kiro")- .join("sessions")- .join("cli"),+ root: home.join("sessions").join("cli"),memories: super::MemoryCache::new(),+ home: Some(home),}}}@@ -194,20 +194,25 @@ impl AgentAdapter for KiroAdapter {fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {// `~/.kiro`/`~/.kiro/sessions`/`~/.kiro/sessions/cli` 三层都认- let root = if dir.join("sessions").join("cli").is_dir() {- dir.join("sessions").join("cli")+ let (root, home) = if dir.join("sessions").join("cli").is_dir() {+ (dir.join("sessions").join("cli"), Some(dir))} else if dir.join("cli").is_dir() {- dir.join("cli")+ (dir.join("cli"), None)} else {- dir+ (dir, None)};Box::new(Self {root,memories: super::MemoryCache::new(),+ home,})}fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rsindex d41ecf6..f8d8b12 100644--- a/crates/wake-core/src/adapters/mod.rs+++ b/crates/wake-core/src/adapters/mod.rs@@ -165,6 +165,13 @@ pub trait AgentAdapter: Send + Sync {fn memory_sources(&self) -> Vec<MemorySource> {Vec::new()}+ /// 本实例确认过的 home(装着这家配置与会话的目录:`~/.claude`、`$CODEX_HOME`……)。+ /// 只在构造时有结构证据才给——默认实例,或自定义根选的是 home 形态(里面有这家的数据+ /// 子目录);直接选了数据目录本身的给空,不越界摸父目录(不变量 8⑨)。Hermes 每个档案+ /// 一个。Skills 总览按它找各家的 skill 文件夹(`skills::scan`)。默认空;远程实例给空+ fn homes(&self) -> Vec<std::path::PathBuf> {+ Vec::new()+ }/// 一轮扫描开始前刷新 adapter 的跨会话快照。默认 adapter 没有这类状态。fn begin_scan(&self) {}/// 此 adapter 是否负责维护会话父子关系。单独的能力位用于区分“当前没有@@ -1250,9 +1257,22 @@ pub fn memory_body(doc: &MemoryDoc) -> String {}/// YAML frontmatter(文件开头 `---` 围起的几行)里一个顶层 `key: 值`。不做完整-/// YAML:只认顶格的 `key:`,值去首尾引号;块标量(`key: >` / `|`,值在下面缩进的几行)-/// 把那几行折成一行——否则标题就是一个字面的 ">"。没有 frontmatter 或没这个键给 None+/// YAML:只认顶格的 `key:`;引号值取到配对的引号;块标量(`key: >` / `|`,值在下面缩进的+/// 几行)把那几行折成一行——否则标题就是一个字面的 ">"。普通值**原样**:`description` 一类+/// 自由文本里的 ` #`(`(PR #17)`)是正文,记忆标题就从它来;要按名字归组的用+/// `frontmatter_ident`。没有 frontmatter 或没这个键给 Nonepub(crate) fn frontmatter_field(body: &str, key: &str) -> Option<String> {+ frontmatter_value(body, key, false)+}++/// `frontmatter_field` 的标识符版(skill 的 `name`):普通值在行尾注释(` #`)处截断——+/// `name: review # 备注` 是 review,带上注释 Skills 就把它和别处的 review 分成两组(Codex+/// review 2026-10-15);只截标识符,自由文本截了会把记忆标题砍成 "…(PR"(/simplify 同月)+pub(crate) fn frontmatter_ident(body: &str, key: &str) -> Option<String> {+ frontmatter_value(body, key, true)+}++fn frontmatter_value(body: &str, key: &str, comments: bool) -> Option<String> {let mut lines = body.lines();if lines.next()?.trim() != "---" {return None;@@ -1269,7 +1289,14 @@ pub(crate) fn frontmatter_field(body: &str, key: &str) -> Option<String> {continue;};let value = value.trim();- let value = if matches!(value, ">" | "|" | ">-" | "|-" | ">+" | "|+") {+ // 标识符:`key: # 注释` 是空值+ let value = if comments && value.starts_with('#') {+ ""+ } else {+ value+ };+ let indicator = value.split(" #").next().unwrap_or_default().trim();+ let value = if matches!(indicator, ">" | "|" | ">-" | "|-" | ">+" | "|+") {let mut folded = Vec::new();while let Some(next) = lines.peek() {if !next.starts_with([' ', '\t']) || next.trim() == "---" {@@ -1280,13 +1307,69 @@ pub(crate) fn frontmatter_field(body: &str, key: &str) -> Option<String> {}folded.join(" ")} else {- value.trim_matches('"').trim_matches('\'').to_string()+ yaml_scalar(value, comments)};return (!value.is_empty()).then_some(value);}None}+/// 一行里的 YAML 标量:双引号取到下一个未转义的 `"`(`\x` 取 x),单引号取到配对的 `'`(`''` 是+/// 转义的单引号);普通值 `comments` 时在行尾注释(` #`)处截断,否则原样+fn yaml_scalar(value: &str, comments: bool) -> String {+ let mut out = String::new();+ if let Some(rest) = value.strip_prefix('"') {+ let mut chars = rest.chars();+ while let Some(c) = chars.next() {+ match c {+ '"' => break,+ '\\' => out.extend(chars.next()),+ c => out.push(c),+ }+ }+ return out;+ }+ if let Some(rest) = value.strip_prefix('\'') {+ let mut chars = rest.chars().peekable();+ while let Some(c) = chars.next() {+ if c != '\'' {+ out.push(c);+ } else if chars.next_if_eq(&'\'').is_some() {+ out.push('\'');+ } else {+ break;+ }+ }+ return out;+ }+ if !comments {+ return value.to_string();+ }+ value+ .split(" #")+ .next()+ .unwrap_or_default()+ .trim_end()+ .to_string()+}++/// 去掉开头的 YAML frontmatter,给阅读面渲染正文(Skills 页);认法与 `frontmatter_field`+/// 同一套——首行、收尾行都按 trim 后等于 `---` 算。没有或没收尾就原样+pub fn strip_frontmatter(body: &str) -> &str {+ let mut lines = body.split_inclusive('\n');+ let Some(first) = lines.next().filter(|l| l.trim() == "---") else {+ return body;+ };+ let mut offset = first.len();+ for line in lines {+ offset += line.len();+ if line.trim() == "---" {+ return body[offset..].trim_start_matches(['\r', '\n']);+ }+ }+ body+}+/// 手输路径的 `~` 前缀展开(仅前缀;边界落在分隔符上,Windows 用户手输/// `~\foo` 同样认)。HOME 与 adapter 同源(`home_dir` 的 WAKE_HOME 开关);/// UI 的 `format::expand_tilde` 与 wake-mcp 的 project 参数都走这里@@ -1368,6 +1451,46 @@ fn names_binary(preview: &str, bin: &str) -> bool {mod tests {use super::*;+ #[test]+ fn frontmatter_values_follow_yaml_quoting_and_comments() {+ let fm = |line: &str| frontmatter_ident(&format!("---\n{line}\n---\nbody"), "name");+ assert_eq!(fm("name: review # 本地备注").as_deref(), Some("review"));+ assert_eq!(fm("name: a#b").as_deref(), Some("a#b"));+ assert_eq!(+ fm(r#"name: "x # not a comment" # but this is"#).as_deref(),+ Some("x # not a comment")+ );+ assert_eq!(fm(r#"name: "say \"hi\"""#).as_deref(), Some(r#"say "hi""#));+ assert_eq!(fm("name: 'it''s' # c").as_deref(), Some("it's"));+ assert_eq!(fm("name: # nothing"), None);+ let folded = "---\nname: > # folded\n one\n two\n---\n";+ assert_eq!(+ frontmatter_field(folded, "name").as_deref(),+ Some("one two")+ );+ // 自由文本不截:记忆标题从 description 来,`(PR #17)` 是正文+ let free = "---\ndescription: removed moment.js (PR #17, see notes)\n---\n";+ assert_eq!(+ frontmatter_field(free, "description").as_deref(),+ Some("removed moment.js (PR #17, see notes)")+ );+ }++ #[test]+ fn frontmatter_is_stripped_for_the_reader() {+ let text = "---\nname: x\ndescription: >\n folded\n---\n\n# Title\nbody\n";+ assert_eq!(strip_frontmatter(text), "# Title\nbody\n");+ assert_eq!(+ strip_frontmatter("# No frontmatter\n"),+ "# No frontmatter\n"+ );+ // 没收尾的不算 frontmatter,原样+ assert_eq!(strip_frontmatter("---\nname: x\n"), "---\nname: x\n");+ assert_eq!(strip_frontmatter("---\r\nname: x\r\n---\r\nbody"), "body");+ // 分隔行带尾随空格:与 frontmatter_field 同一个认法(trim 后是 ---)+ assert_eq!(strip_frontmatter("--- \nname: x\n--- \nbody"), "body");+ }+fn tc(name: &str, preview: &str, input: Option<&str>) -> ToolCallView {ToolCallView {id: String::new(),diff --git a/crates/wake-core/src/adapters/openclaw.rs b/crates/wake-core/src/adapters/openclaw.rsindex 72e38a8..1d94f42 100644--- a/crates/wake-core/src/adapters/openclaw.rs+++ b/crates/wake-core/src/adapters/openclaw.rs@@ -42,6 +42,8 @@ pub struct OpenclawAdapter {rows_cache: Mutex<HashMap<PathBuf, Arc<MtimeCache<Arc<Vec<ClawRow>>>>>>,/// 旧版 sessions.json 索引,每个 sessions 目录一份,按文件 mtime 失效index_cache: Mutex<HashMap<PathBuf, Arc<MtimeCache<LegacyIndex>>>>,+ /// 状态目录(`~/.openclaw` / OPENCLAW_STATE_DIR);直接选中 agents 目录的自定义根没有+ home: Option<PathBuf>,}/// sessions.json 解析结果:sessionId → (会话键, 条目)@@ -74,7 +76,10 @@ impl OpenclawAdapter {new}});- Self::with_root(state.join("agents"))+ Self {+ home: Some(state.clone()),+ ..Self::with_root(state.join("agents"))+ }}fn with_root(root: PathBuf) -> Self {@@ -82,6 +87,7 @@ impl OpenclawAdapter {root,rows_cache: Mutex::new(HashMap::new()),index_cache: Mutex::new(HashMap::new()),+ home: None,}}@@ -876,13 +882,22 @@ impl AgentAdapter for OpenclawAdapter {// 同步前就落在正确形态)let is_agents = dir.file_name().and_then(|n| n.to_str()) == Some("agents")|| (!dir.join("agents").is_dir() && looks_like_agents(&dir));- let root = if is_agents { dir } else { dir.join("agents") };- Box::new(Self::with_root(root))+ if is_agents {+ return Box::new(Self::with_root(dir));+ }+ Box::new(Self {+ home: Some(dir.clone()),+ ..Self::with_root(dir.join("agents"))+ })}fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}/// 目录里已有 `<x>/sessions` 或 `<x>/agent/openclaw-agent.sqlite` 形态的子目录diff --git a/crates/wake-core/src/adapters/pi.rs b/crates/wake-core/src/adapters/pi.rsindex b35cb36..06a71fa 100644--- a/crates/wake-core/src/adapters/pi.rs+++ b/crates/wake-core/src/adapters/pi.rs@@ -16,29 +16,29 @@ use std::path::{Path, PathBuf};pub struct PiAdapter {agent: AgentId,root: PathBuf,+ /// `~/.pi/agent`(`~/.omp/agent`);直接选中 sessions 目录的自定义根没有+ home: Option<PathBuf>,}impl PiAdapter {pub fn new() -> Self {- Self {- agent: AgentId::Pi,- root: super::home_dir()- .unwrap_or_default()- .join(".pi")- .join("agent")- .join("sessions"),- }+ Self::at_home(AgentId::Pi, ".pi")}/// Oh My Pi 变体:`~/.omp/agent/sessions`,解析核心完全共用pub fn omp() -> Self {+ Self::at_home(AgentId::Omp, ".omp")+ }++ fn at_home(agent: AgentId, dir_name: &str) -> Self {+ let home = super::home_dir()+ .unwrap_or_default()+ .join(dir_name)+ .join("agent");Self {- agent: AgentId::Omp,- root: super::home_dir()- .unwrap_or_default()- .join(".omp")- .join("agent")- .join("sessions"),+ agent,+ root: home.join("sessions"),+ home: Some(home),}}}@@ -203,14 +203,26 @@ impl AgentAdapter for PiAdapter {// pi 与 omp 布局全同:实例保持自己的 agent,探测时两家都会命中同一目录,// 取舍交 UI(用户知道自己装的是哪个 CLI)let nested = dir.join("agent").join("sessions");- let root = if nested.is_dir() { nested } else { dir };+ let (root, home) = if nested.is_dir() {+ (nested, Some(dir.join("agent")))+ } else {+ // 直接选了 agent 那一层(`~/.pi/agent`,里面有 sessions/):它自己就是 home,会话照旧+ // 从选中的目录往下找(Codex review 2026-10-23)+ let home = dir.join("sessions").is_dir().then(|| dir.clone());+ (dir, home)+ };Box::new(Self {agent: self.agent,root,+ home,})}fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}diff --git a/crates/wake-core/src/adapters/qoder.rs b/crates/wake-core/src/adapters/qoder.rsindex b84f494..9743d00 100644--- a/crates/wake-core/src/adapters/qoder.rs+++ b/crates/wake-core/src/adapters/qoder.rs@@ -16,21 +16,22 @@ use std::path::{Path, PathBuf};/// 子代理(整份都是 `isSidechain: true` 的行),作为子会话挂在派它的会话下面。pub struct QoderAdapter {root: PathBuf,+ /// 配置目录(`~/.qoder` / QODER_CONFIG_DIR);直接选中 projects 目录的自定义根没有+ home: Option<PathBuf>,}impl QoderAdapter {pub fn new() -> Self {- let default = super::home_dir()- .unwrap_or_default()- .join(".qoder")- .join("projects");- let root = super::env_dir("QODER_CONFIG_DIR")- .map(|dir| dir.join("projects"))+ let default = super::home_dir().unwrap_or_default().join(".qoder");+ let home = super::env_dir("QODER_CONFIG_DIR")// 与其他 env override 一致:存在但没有任何会话的候选不能遮掉// 默认根(Dock 启动与 shell 启动看到的环境经常不同)。- .filter(|dir| project_tree_has_session(dir, AgentId::Qoder))+ .filter(|dir| project_tree_has_session(&dir.join("projects"), AgentId::Qoder)).unwrap_or(default);- Self { root }+ Self {+ root: home.join("projects"),+ home: Some(home),+ }}}@@ -697,15 +698,19 @@ impl AgentAdapter for QoderAdapter {}fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {- let root = if dir.join("projects").is_dir() {- dir.join("projects")+ let (root, home) = if dir.join("projects").is_dir() {+ (dir.join("projects"), Some(dir))} else {- dir+ (dir, None)};- Box::new(Self { root })+ Box::new(Self { root, home })}fn data_roots(&self) -> Vec<PathBuf> {vec![self.root.clone()]}++ fn homes(&self) -> Vec<PathBuf> {+ self.home.iter().cloned().collect()+ }}diff --git a/crates/wake-core/src/adapters/remote.rs b/crates/wake-core/src/adapters/remote.rsindex 7922e85..da880dc 100644--- a/crates/wake-core/src/adapters/remote.rs+++ b/crates/wake-core/src/adapters/remote.rs@@ -153,6 +153,11 @@ impl AgentAdapter for RemoteAdapter {self.inner.session_paths(meta)}+ fn homes(&self) -> Vec<std::path::PathBuf> {+ // 镜像白名单不含 skill 目录,远程实例没有可看的 home+ Vec::new()+ }+fn memory_sources(&self) -> Vec<MemorySource> {// inner 按缓存挂载点构造,它报的路径已经是缓存内的self.inner.memory_sources()diff --git a/crates/wake-core/src/lib.rs b/crates/wake-core/src/lib.rsindex 67cbca5..26d25d5 100644--- a/crates/wake-core/src/lib.rs+++ b/crates/wake-core/src/lib.rs@@ -7,5 +7,6 @@ pub mod models;pub mod remote;pub mod scanner;pub mod services;+pub mod skills;pub mod text;pub mod watcher;diff --git a/crates/wake-core/src/skills.rs b/crates/wake-core/src/skills.rsnew file mode 100644index 0000000..11c9018--- /dev/null+++ b/crates/wake-core/src/skills.rs@@ -0,0 +1,882 @@+//! 本机 agent skill 的只读总览(issue #62)。skill 是 `<目录>/<名字>/SKILL.md`(YAML+//! frontmatter + Markdown 正文),各家 agent 各收在自己的目录里(`~/.claude/skills`、+//! `~/.codex/skills`……),另有多家共读的 `~/.agents/skills`(vercel-labs 的 `npx skills`+//! 把它当正本、往各家目录里链)。这里只做"看":按名字把各处的安装归拢成一个 skill,看出+//! 哪些是同一份(符号链接到同一个真实目录)、哪些是各自的拷贝、拷贝之间 SKILL.md 有没有+//! 分叉。**只读**(不变量 2):不安装、不拷贝、不链接、不同步、不删除——跨 agent 装 skill+//! 是 `npx skills add` 的事(用户 2026-10-15 定)。+//!+//! 取舍:+//! - 不进索引库、不建 FTS:skill 只有几百份,进页与 Refresh 时现扫,SKILL.md 的解析结果按+//! (mtime, size) 缓存在 `SkillCache`。+//! - **只读每个条目顶层的 SKILL.md,绝不往 skill 目录里递归**:有的 skill 是整个仓库的检出+//! (本机 `~/.claude/skills/gstack` 1.3 GB)。"内容一致"因此只比 SKILL.md 的哈希,有意不比+//! 整个目录;点开头的条目(`.system` 一类)也不看。唯一的下探是 Hermes 的分类目录。+//! - 目录从 roster 派生(不变量 8,不另建名单):各家用户级目录挂在本地实例**确认过的 home**+//! 下(`AgentAdapter::homes`,`CODEX_HOME` / `QODER_CONFIG_DIR` 这类在构造时已解析;直接选了+//! 数据目录的自定义根没有 home,不越界摸父目录),远程实例不看;家目录 / 配置目录下的固定+//! 位置与项目级目录是各家静态的事实,与 roster 无关(该家会话 location 全停用了照样列)。+//! 归属指"文件夹是谁家的",不推算"谁读得到"——十几家都读 `~/.agents/skills`、好几家读+//! `~/.claude/skills`,各家读哪些随版本在变。+//! - "读不出" ≠ "没有":目录或 SKILL.md 不存在(NotFound / 不是目录)就是没有;别的 I/O+//! 错误记进 `SkillScan::errors`,界面照实提示,不当成空。++use crate::adapters::parse_utils::{mtime_ms, project_name_of};+use crate::adapters::{self, AgentAdapter};+use crate::models::AgentId;+use sha2::{Digest, Sha256};+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};+use std::io::ErrorKind;+use std::path::{Path, PathBuf};+use std::sync::Mutex;++/// skill 的入口文件名(Agent Skills 规范)+const SKILL_MD: &str = "SKILL.md";++/// 多家共读的 skill 文件夹:家目录下(`~/.agents/skills`)与每个项目根下同一个相对路径+pub const SHARED_DIR: &str = ".agents/skills";+/// `npx skills` 新版的落点:`$XDG_CONFIG_HOME/agents/skills`+const SHARED_CONFIG_DIR: &str = "agents/skills";++/// 一个 skill 文件夹归谁:共享目录(`.agents/skills`,多家共读),或某一家 agent 自己的+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub enum SkillOwner {+ Shared,+ Agent(AgentId),+}++/// 一处安装的层级。派生的 Ord 即展示序:用户级、插件、项目级+#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub enum SkillScope {+ /// home 下的(`~/.claude/skills`、`~/.agents/skills`……)+ User,+ /// Claude Code 插件自带的;`id` 是 `installed_plugins.json` 的键(`<插件>@<市场>`),+ /// `enabled` 读自 settings.json 的 `enabledPlugins`(没写的算开着)+ Plugin { id: String, enabled: bool },+ /// 已索引项目根下的(`<项目>/.claude/skills`……)+ Project { root: PathBuf },+}++impl SkillScope {+ /// 插件名(`id` 里 `@` 前那段),skill 在 Claude Code 里叫 `<插件>:<名字>`+ pub fn plugin_name(&self) -> Option<&str> {+ match self {+ SkillScope::Plugin { id, .. } => Some(id.split('@').next().unwrap_or(id)),+ _ => None,+ }+ }+}++/// 一处安装:某个 skill 文件夹里的一个条目+#[derive(Debug, Clone)]+pub struct SkillInstall {+ pub owner: SkillOwner,+ pub scope: SkillScope,+ /// 列出来的条目目录 `<skill 文件夹>/<条目名>`+ pub path: PathBuf,+ /// 解析掉符号链接后的真实目录:"同一份" = 同一个它+ pub real_path: PathBuf,+ /// 条目本身或它所在的 skill 文件夹是符号链接+ pub linked: bool,+ /// SKILL.md 的 sha256 前 8 字节:"内容一致" = 它相等(只比 SKILL.md,见模块文档)+ pub content_hash: u64,+ /// frontmatter 的 `name`,没有就用目录名;插件的加 `<插件>:` 前缀+ pub name: String,+ /// frontmatter 的 `description`,没有给空串+ pub description: String,+ /// SKILL.md 的修改时间(epoch ms)+ pub updated_at: i64,+}++impl SkillInstall {+ pub fn skill_md(&self) -> PathBuf {+ self.path.join(SKILL_MD)+ }+}++/// 同名的安装归成一个 skill。汇总字段在扫描时算好一次(列表每帧都要读)+#[derive(Debug, Clone)]+pub struct Skill {+ pub name: String,+ /// 按 (归属, 层级, 路径) 排好+ pub installs: Vec<SkillInstall>,+ /// 几份真实拷贝(符号链接指向同一处的算一份)+ pub copies: usize,+ /// 各处 SKILL.md 内容不全一样+ pub differs: bool,+ /// 有一处是符号链接+ pub linked: bool,+ /// 有它的各方(去重、按 SkillOwner 序)+ pub owners: Vec<SkillOwner>,+ /// 有一处是插件自带的(列表行挂 "plugin" 徽章)+ pub plugin: bool,+ /// 最近改过的那处(`installs` 下标,平局取靠前的);列表的说明与阅读面默认显示它+ pub newest: usize,+}++impl Skill {+ fn new(name: String, mut installs: Vec<SkillInstall>) -> Self {+ installs.sort_by(|a, b| (a.owner, &a.scope, &a.path).cmp(&(b.owner, &b.scope, &b.path)));+ let mut newest = 0;+ for (ix, install) in installs.iter().enumerate() {+ if install.updated_at > installs[newest].updated_at {+ newest = ix;+ }+ }+ // installs 先按归属排,相邻去重就是各方+ let mut owners: Vec<SkillOwner> = installs.iter().map(|i| i.owner).collect();+ owners.dedup();+ Self {+ copies: installs+ .iter()+ .map(|i| &i.real_path)+ .collect::<HashSet<_>>()+ .len(),+ differs: installs+ .iter()+ .any(|i| i.content_hash != installs[0].content_hash),+ linked: installs.iter().any(|i| i.linked),+ plugin: installs+ .iter()+ .any(|i| matches!(i.scope, SkillScope::Plugin { .. })),+ owners,+ newest,+ name,+ installs,+ }+ }++ pub fn description(&self) -> &str {+ &self.installs[self.newest].description+ }++ pub fn updated_at(&self) -> i64 {+ self.installs[self.newest].updated_at+ }+}++/// 读不出来的位置(不是"没有"):路径 + 英文错误+#[derive(Debug, Clone)]+pub struct SkillError {+ pub path: PathBuf,+ pub message: String,+}++impl SkillError {+ fn new(path: &Path, e: impl std::fmt::Display) -> Self {+ Self {+ path: path.to_path_buf(),+ message: e.to_string(),+ }+ }+}++#[derive(Debug, Clone, Default)]+pub struct SkillScan {+ /// 按名字排(不分大小写)+ pub skills: Vec<Skill>,+ pub errors: Vec<SkillError>,+}++/// 侧栏导航的计数(都是 skill 数,不是安装数)+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct SkillCounts {+ pub total: usize,+ /// 有两份及以上真实拷贝的+ pub duplicated: usize,+ /// 按 SkillOwner 序+ pub owners: Vec<(SkillOwner, usize)>,+ /// 有项目级 skill 的项目,按项目名排+ pub projects: Vec<(PathBuf, usize)>,+}++impl SkillScan {+ pub fn counts(&self) -> SkillCounts {+ let mut owners: BTreeMap<SkillOwner, usize> = BTreeMap::new();+ let mut projects: BTreeMap<&Path, usize> = BTreeMap::new();+ for skill in &self.skills {+ for &owner in &skill.owners {+ *owners.entry(owner).or_default() += 1;+ }+ let roots: BTreeSet<&Path> = skill+ .installs+ .iter()+ .filter_map(|i| match &i.scope {+ SkillScope::Project { root } => Some(root.as_path()),+ _ => None,+ })+ .collect();+ for root in roots {+ *projects.entry(root).or_default() += 1;+ }+ }+ let mut projects: Vec<(PathBuf, usize)> = projects+ .into_iter()+ .map(|(root, n)| (root.to_path_buf(), n))+ .collect();+ projects.sort_by_cached_key(|(root, _)| (project_name(root).to_lowercase(), root.clone()));+ SkillCounts {+ total: self.skills.len(),+ duplicated: self.skills.iter().filter(|s| s.copies > 1).count(),+ owners: owners.into_iter().collect(),+ projects,+ }+ }+}++/// 项目根的显示名(与会话、记忆的项目名同一个取法)+pub fn project_name(root: &Path) -> String {+ project_name_of(&root.to_string_lossy())+}++// ---------------- 位置:各家的 skill 文件夹在哪 ----------------++/// 一家的用户级 skill 文件夹怎么推。依据各家官方文档 / 源码(2026-10-15 核对),只收 Wake+/// 名单里的 agent 自己的文件夹;没核实的(Kimi Code 文档写 `~/.kimi/skills`,而 Wake 读的+/// Kimi Code 数据在 `~/.kimi-code`,对不上;WorkBuddy 只有第三方说法;Grok Bot 没有本地目录)+/// 不猜+enum UserDirs {+ /// 本地实例确认过的 home(`AgentAdapter::homes`)下的相对路径;里面的 `*` 段是"每个+ /// 子目录"(Craft 的每个工作区)+ FromHome(&'static str),+ /// 固定位置:该家没有改 home 的开关,或 skill 不随它走(ZCode 的 skill 恒在+ /// `homedir()/.zcode/skills`,`ZCODE_STORAGE_DIR` 只挪数据)+ Fixed(Base, &'static [&'static str]),+}++#[derive(Clone, Copy)]+enum Base {+ Home,+ /// `$XDG_CONFIG_HOME`(缺省 `~/.config`)+ Config,+ /// 应用配置目录:Windows 是 `%APPDATA%`,其余同 Config(Devin)+ AppConfig,+}++fn user_dirs(agent: AgentId) -> Option<UserDirs> {+ use UserDirs::*;+ Some(match agent {+ // `$CODEX_HOME/skills` 官方已标弃用(改读 ~/.agents/skills)但仍读;`.system` 是+ // Codex 自带的,点开头的条目不看+ AgentId::ClaudeCode+ | AgentId::Codex+ | AgentId::Qoder+ | AgentId::Cursor+ | AgentId::Codebuddy+ | AgentId::Grok+ | AgentId::Dsh+ | AgentId::Pi+ | AgentId::Omp+ | AgentId::Kiro+ | AgentId::Gemini+ | AgentId::Copilot+ // HERMES_HOME 与各 profile 各一个+ | AgentId::Hermes+ | AgentId::Openclaw => FromHome("skills"),+ // 每个工作区一个+ AgentId::CraftAgents => FromHome("workspaces/*/skills"),+ // 新版桌面端 / IDE、CLI,与旧版(本机还有)+ AgentId::Antigravity => Fixed(+ Base::Home,+ &[+ ".gemini/config/skills",+ ".gemini/antigravity-cli/skills",+ ".gemini/antigravity/skills",+ ],+ ),+ AgentId::Zcode => Fixed(Base::Home, &[".zcode/skills"]),+ // 新版与旧版扩展+ AgentId::Kilo => Fixed(Base::Home, &[".kilo/skills", ".kilocode/skills"]),+ AgentId::Opencode => Fixed(Base::Config, &["opencode/skills"]),+ AgentId::Devin => Fixed(Base::AppConfig, &["devin/skills"]),+ AgentId::Kimi | AgentId::GrokBot | AgentId::Workbuddy => return None,+ })+}++/// 一家在项目根下的 skill 文件夹(相对路径)。共享的 `.agents/skills` 单列(`SHARED_DIR`)+fn project_dirs(agent: AgentId) -> &'static [&'static str] {+ match agent {+ AgentId::ClaudeCode => &[".claude/skills"],+ AgentId::Codex => &[".codex/skills"],+ AgentId::Qoder => &[".qoder/skills"],+ AgentId::Copilot => &[".github/skills"],+ AgentId::Cursor => &[".cursor/skills"],+ AgentId::Opencode => &[".opencode/skills"],+ AgentId::Kiro => &[".kiro/skills"],+ AgentId::Gemini => &[".gemini/skills"],+ AgentId::Pi => &[".pi/skills"],+ AgentId::Omp => &[".omp/skills"],+ AgentId::Grok => &[".grok/skills"],+ // 旧版;新版读的是共享的 .agents/skills+ AgentId::Antigravity => &[".agent/skills"],+ AgentId::Dsh => &[".dsh/skills"],+ AgentId::Hermes => &[".hermes/skills"],+ AgentId::Codebuddy => &[".codebuddy/skills"],+ AgentId::Zcode => &[".zcode/skills"],+ AgentId::Devin => &[".devin/skills"],+ AgentId::Kilo => &[".kilo/skills"],+ AgentId::Openclaw+ | AgentId::CraftAgents+ | AgentId::Kimi+ | AgentId::GrokBot+ | AgentId::Workbuddy => &[],+ }+}++/// 这家的 skill 文件夹是分类目录布局:没有 SKILL.md 的条目是一个分类,往下找(Hermes 的+/// `<分类>/<skill>/SKILL.md`,它自己按 os.walk 发现;mlops 下还有一层)+fn has_categories(owner: SkillOwner) -> bool {+ owner == SkillOwner::Agent(AgentId::Hermes)+}++/// 分类目录最多往下找几层(到有 SKILL.md 的目录即停,绝不进 skill 目录里面)+const CATEGORY_DEPTH: usize = 3;++/// 推固定位置用的两个根。`current()` 读进程环境;测试用 `at(假 home)`,不碰环境变量+#[derive(Debug, Clone)]+pub struct SkillHomes {+ home: PathBuf,+ /// `$XDG_CONFIG_HOME`,缺省 `<home>/.config`+ config: PathBuf,+}++impl SkillHomes {+ pub fn current() -> Self {+ let home = adapters::home_dir().unwrap_or_default();+ let config = adapters::env_dir("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config"));+ Self { home, config }+ }++ pub fn at(home: &Path) -> Self {+ Self {+ home: home.to_path_buf(),+ config: home.join(".config"),+ }+ }++ fn base(&self, base: Base) -> PathBuf {+ match base {+ Base::Home => self.home.clone(),+ Base::Config => self.config.clone(),+ // Windows `%APPDATA%`:与 adapters 同一约定,从 home 派生+ Base::AppConfig if cfg!(windows) => self.home.join("AppData").join("Roaming"),+ Base::AppConfig => self.config.clone(),+ }+ }+}++/// `a/b` 形式的相对路径按段拼(Windows 上也对)+fn join_rel(base: &Path, rel: &str) -> PathBuf {+ rel.split('/')+ .fold(base.to_path_buf(), |p, seg| p.join(seg))+}++/// 读不读得出:不存在(含"中间某段不是目录")是没有,别的是读不出+fn absent(e: &std::io::Error) -> bool {+ matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory)+}++/// 一个待读的 skill 文件夹+struct Location {+ owner: SkillOwner,+ scope: SkillScope,+ dir: PathBuf,+ /// `dir` 的真实路径:里面不是链接的条目,真实路径就是它接上条目名,不必逐个 canonicalize+ real: PathBuf,+ /// `dir` 本身就是一个 skill(插件清单直接点名的 skill 目录),不是装 skill 的文件夹+ single: bool,+ /// `dir` 自己是符号链接(里面每一项都算链接)+ linked: bool,+}++/// 收集位置:同一归属、同一层级下同一个真实文件夹只读一次(Codex 的 sessions 与 archived 同一个+/// home、一家多个实例);不同归属或不同项目指到同一处(整个文件夹是符号链接)各列各的——那正是+/// "链接"+#[derive(Default)]+struct Plan {+ locations: Vec<Location>,+ seen: HashSet<(SkillOwner, SkillScope, PathBuf)>,+ /// 已列的用户级 / 插件文件夹的**逻辑路径**(父目录解析掉链接、末段原样):项目级展开出+ /// 同一个路径时跳过——家目录被索引成项目时,`~/.claude/skills` 不能再当一份项目级来一遍。+ /// 按真实路径比会把"项目里的 skills 目录链到 ~/.agents/skills"这种真安装也吞掉(Codex+ /// review 2026-10-15)+ covered: HashSet<PathBuf>,+ errors: Vec<SkillError>,+}++/// 父目录解析掉链接、末段原样:同一个文件夹换个写法(经由链接的家目录)认得出,而一个本身+/// 是链接的 skills 目录仍是它自己+fn logical_path(dir: &Path) -> PathBuf {+ match (dir.parent(), dir.file_name()) {+ (Some(parent), Some(name)) => std::fs::canonicalize(parent)+ .map(|p| p.join(name))+ .unwrap_or_else(|_| dir.to_path_buf()),+ _ => dir.to_path_buf(),+ }+}++impl Plan {+ fn add(&mut self, owner: SkillOwner, scope: SkillScope, dir: PathBuf) {+ self.add_location(owner, scope, dir, false);+ }++ fn add_location(&mut self, owner: SkillOwner, scope: SkillScope, dir: PathBuf, single: bool) {+ // 先 lstat:项目级展开问的大多是不存在的路径,一次系统调用就够,是不是链接顺带知道;+ // canonicalize 只给真有的+ let meta = match std::fs::symlink_metadata(&dir) {+ Ok(meta) => meta,+ Err(e) if absent(&e) => return,+ Err(e) => return self.errors.push(SkillError::new(&dir, e)),+ };+ let linked = meta.file_type().is_symlink();+ if !linked && !meta.is_dir() {+ return;+ }+ let real = match std::fs::canonicalize(&dir) {+ Ok(real) if real.is_dir() => real,+ Ok(_) => return,+ Err(e) if absent(&e) => return,+ Err(e) => return self.errors.push(SkillError::new(&dir, e)),+ };+ // 不是链接的文件夹,逻辑路径就是真实路径+ let logical = if linked {+ logical_path(&dir)+ } else {+ real.clone()+ };+ let project = matches!(scope, SkillScope::Project { .. });+ if project && self.covered.contains(&logical) {+ return;+ }+ if !self.seen.insert((owner, scope.clone(), real.clone())) {+ return;+ }+ if !project {+ self.covered.insert(logical);+ }+ self.locations.push(Location {+ owner,+ scope,+ dir,+ real,+ single,+ linked,+ });+ }++ /// `rel` 里的 `*` 段展开成每个子目录(不看点开头的)+ fn add_under_home(&mut self, owner: SkillOwner, home: &Path, rel: &str) {+ let Some((parent, rest)) = rel.split_once("/*/") else {+ return self.add(owner, SkillScope::User, join_rel(home, rel));+ };+ let parent = join_rel(home, parent);+ match sorted_entries(&parent) {+ Ok(names) => {+ for (name, _) in names {+ self.add(owner, SkillScope::User, join_rel(&parent.join(name), rest));+ }+ }+ Err(e) if absent(&e) => {}+ Err(e) => self.errors.push(SkillError::new(&parent, e)),+ }+ }+}++/// 目录里不以点开头的条目(名字, 是不是符号链接),按名字排。链接与否取自目录项本身+/// (Unix 的 d_type),不再逐个 lstat+fn sorted_entries(dir: &Path) -> std::io::Result<Vec<(std::ffi::OsString, bool)>> {+ let mut names = Vec::new();+ for entry in std::fs::read_dir(dir)? {+ let entry = entry?;+ let name = entry.file_name();+ if name.to_string_lossy().starts_with('.') {+ continue;+ }+ names.push((name, entry.file_type()?.is_symlink()));+ }+ names.sort();+ Ok(names)+}++/// Claude Code 插件自带的 skill 文件夹:`<home>/plugins/installed_plugins.json` 里每个插件+/// 的 `installPath` 下的 `skills/`,外加清单(`.claude-plugin/plugin.json`)`skills` 字段+/// 列的路径。**只认 installPath**:插件缓存里堆着几十个旧版本(带 `.orphaned_at`),扫缓存+/// 目录会把它们全算进来+fn add_claude_plugins(plan: &mut Plan, home: &Path) {+ let index = home.join("plugins").join("installed_plugins.json");+ let text = match std::fs::read_to_string(&index) {+ Ok(text) => text,+ Err(e) if absent(&e) => return,+ Err(e) => return plan.errors.push(SkillError::new(&index, e)),+ };+ let json: serde_json::Value = match serde_json::from_str(&text) {+ Ok(json) => json,+ Err(e) => return plan.errors.push(SkillError::new(&index, e)),+ };+ let Some(plugins) = json.get("plugins").and_then(|p| p.as_object()) else {+ return;+ };+ // 开关在 settings.json 的 enabledPlugins;读不出就当都开着(只是少标一个 disabled)+ let enabled: HashMap<String, bool> = std::fs::read_to_string(home.join("settings.json"))+ .ok()+ .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())+ .and_then(|s| {+ s.get("enabledPlugins")?.as_object().map(|m| {+ m.iter()+ .filter_map(|(k, v)| Some((k.clone(), v.as_bool()?)))+ .collect()+ })+ })+ .unwrap_or_default();+ for (id, entries) in plugins {+ let Some(entries) = entries.as_array() else {+ continue;+ };+ let scope = SkillScope::Plugin {+ id: id.clone(),+ enabled: enabled.get(id).copied().unwrap_or(true),+ };+ for entry in entries {+ let Some(install) = entry.get("installPath").and_then(|p| p.as_str()) else {+ continue;+ };+ for (dir, single) in plugin_skill_dirs(Path::new(install), &mut plan.errors) {+ let owner = SkillOwner::Agent(AgentId::ClaudeCode);+ plan.add_location(owner, scope.clone(), dir, single);+ }+ }+ }+}++/// (目录, 它本身是不是一个 skill):默认的 `skills/` 与清单里列的,既可以是装 skill 的文件夹,+/// 也可以直接是一个 skill 的目录——里面就有 SKILL.md 的按单个 skill 读(Codex review+/// 2026-10-15;同一个目录先按文件夹登记、再按单个 skill 来就会被去重吞掉,所以一律按内容判)+/// 清单不在就只有默认目录;在却读不出、JSON 坏了要报出来(它列的目录就看不到了),不当成+/// 没有(Codex review 2026-10-15)+fn plugin_skill_dirs(install: &Path, errors: &mut Vec<SkillError>) -> Vec<(PathBuf, bool)> {+ let mut dirs = vec![install.join("skills")];+ let manifest = install.join(".claude-plugin").join("plugin.json");+ let parsed = match std::fs::read_to_string(&manifest) {+ Ok(text) => serde_json::from_str::<serde_json::Value>(&text)+ .map_err(|e| errors.push(SkillError::new(&manifest, e)))+ .ok(),+ Err(e) if absent(&e) => None,+ Err(e) => {+ errors.push(SkillError::new(&manifest, e));+ None+ }+ };+ if let Some(listed) = parsed.and_then(|m| m.get("skills").cloned()) {+ let rels: Vec<String> = match listed {+ serde_json::Value::String(s) => vec![s],+ serde_json::Value::Array(a) => a+ .into_iter()+ .filter_map(|v| v.as_str().map(str::to_string))+ .collect(),+ _ => Vec::new(),+ };+ dirs.extend(+ rels.iter()+ .map(|r| join_rel(install, r.trim_start_matches("./").trim_end_matches('/'))),+ );+ }+ dirs.into_iter()+ .map(|dir| {+ let single = dir.join(SKILL_MD).is_file();+ (dir, single)+ })+ .collect()+}++/// 各位置的先后:共享目录、各家用户级(按 AgentId 序)、Claude Code 插件、各项目。`roster`+/// 是每个本地实例的 (agent, 确认过的 homes)+fn plan(roster: &[(AgentId, Vec<PathBuf>)], homes: &SkillHomes, projects: &[PathBuf]) -> Plan {+ let homes_of = |agent: AgentId| {+ roster+ .iter()+ .filter(move |(a, _)| *a == agent)+ .flat_map(|(_, homes)| homes)+ };+ let mut plan = Plan::default();+ plan.add(+ SkillOwner::Shared,+ SkillScope::User,+ join_rel(&homes.home, SHARED_DIR),+ );+ plan.add(+ SkillOwner::Shared,+ SkillScope::User,+ join_rel(&homes.config, SHARED_CONFIG_DIR),+ );+ for agent in AgentId::ALL {+ let owner = SkillOwner::Agent(agent);+ match user_dirs(agent) {+ Some(UserDirs::FromHome(rel)) => {+ for home in homes_of(agent) {+ plan.add_under_home(owner, home, rel);+ }+ }+ Some(UserDirs::Fixed(base, rels)) => {+ let base = homes.base(base);+ for rel in rels {+ plan.add(owner, SkillScope::User, join_rel(&base, rel));+ }+ }+ None => {}+ }+ }+ for home in homes_of(AgentId::ClaudeCode) {+ add_claude_plugins(&mut plan, home);+ }+ let roots: BTreeSet<&PathBuf> = projects.iter().filter(|p| p.is_absolute()).collect();+ for root in roots {+ let scope = SkillScope::Project { root: root.clone() };+ plan.add(+ SkillOwner::Shared,+ scope.clone(),+ join_rel(root, SHARED_DIR),+ );+ for agent in AgentId::ALL {+ for rel in project_dirs(agent) {+ plan.add(SkillOwner::Agent(agent), scope.clone(), join_rel(root, rel));+ }+ }+ }+ plan+}++// ---------------- 读 ----------------++/// SKILL.md 解析结果的缓存:键是真实路径(多处链到同一份只读一次),戳是 (mtime, size)。+/// 每轮扫描后只留这轮见过的+#[derive(Default)]+pub struct SkillCache(Mutex<HashMap<PathBuf, ParsedSkillMd>>);++#[derive(Clone)]+struct ParsedSkillMd {+ stamp: (i64, u64),+ name: Option<String>,+ description: Option<String>,+ hash: u64,+}++impl SkillCache {+ pub fn new() -> Self {+ Self::default()+ }++ fn get_or_read(&self, md: &Path, meta: &std::fs::Metadata) -> std::io::Result<ParsedSkillMd> {+ let stamp = (mtime_ms(meta), meta.len());+ if let Some(hit) = self.0.lock().unwrap().get(md).filter(|p| p.stamp == stamp) {+ return Ok(hit.clone());+ }+ let bytes = std::fs::read(md)?;+ let text = String::from_utf8_lossy(&bytes);+ let digest = Sha256::digest(&bytes);+ let mut prefix = [0u8; 8];+ prefix.copy_from_slice(&digest[..8]);+ let parsed = ParsedSkillMd {+ stamp,+ name: adapters::frontmatter_ident(&text, "name"),+ description: adapters::frontmatter_field(&text, "description"),+ hash: u64::from_be_bytes(prefix),+ };+ self.0+ .lock()+ .unwrap()+ .insert(md.to_path_buf(), parsed.clone());+ Ok(parsed)+ }++ fn retain(&self, seen: &HashSet<PathBuf>) {+ self.0.lock().unwrap().retain(|k, _| seen.contains(k));+ }+}++/// 读各个 skill 文件夹:每个条目只 stat / 读它顶层的 SKILL.md+struct Reader<'a> {+ cache: &'a SkillCache,+ /// 这轮读到的 SKILL.md(真实路径),扫完按它修剪缓存+ seen: HashSet<PathBuf>,+ /// 已记下的安装 (归属, 层级, 条目路径):插件清单点名的 skill 也在它列的(或默认的)+ /// 文件夹里时,两条读法读到同一处,只记一次。在读的时候按实际条目去重,与清单里的先后+ /// 无关——/simplify 2026-10-23 曾挪到规划阶段按文件夹判,清单写成+ /// `["./extra/deploy", "./extra"]` 就读两遍、`skills/` 本身是 skill 时又漏掉点名的那个+ /// (Codex review 同日),改回来+ listed: HashSet<(SkillOwner, SkillScope, PathBuf)>,+ installs: Vec<SkillInstall>,+ errors: Vec<SkillError>,+}++impl Reader<'_> {+ /// `dir` 里的每个条目:有 SKILL.md 就是一个 skill;没有、而这家是分类布局就当分类往下找。+ /// `real` 是 `dir` 的真实路径,`dir_linked` 是这一路上有没有经过符号链接+ fn read_dir(+ &mut self,+ loc: &Location,+ dir: &Path,+ real: &Path,+ dir_linked: bool,+ depth: usize,+ ) {+ let names = match sorted_entries(dir) {+ Ok(names) => names,+ Err(e) if absent(&e) => return,+ Err(e) => return self.errors.push(SkillError::new(dir, e)),+ };+ for (entry, entry_link) in names {+ let path = dir.join(&entry);+ // 条目自身是不是链接单独判:文件夹是链接、里面的条目又链到别处时,真实路径得现+ // 解析(Codex review 2026-10-15);不是链接的条目,真实路径就是所在文件夹的真实+ // 路径接上条目名+ let real_path = if entry_link {+ match std::fs::canonicalize(&path) {+ Ok(real_path) => real_path,+ Err(e) if absent(&e) => continue,+ Err(e) => {+ self.errors.push(SkillError::new(&path, e));+ continue;+ }+ }+ } else {+ real.join(&entry)+ };+ let linked = dir_linked || entry_link;+ let missing = self.read_entry(loc, &path, &real_path, linked);+ if missing && has_categories(loc.owner) && depth + 1 < CATEGORY_DEPTH && path.is_dir() {+ self.read_dir(loc, &path, &real_path, linked, depth + 1);+ }+ }+ }++ /// 一个条目:有 SKILL.md 就记一处安装。返回"这里没有 SKILL.md"(NotFound;分类目录布局+ /// 据此往下找)+ fn read_entry(&mut self, loc: &Location, path: &Path, real_path: &Path, linked: bool) -> bool {+ let key = (loc.owner, loc.scope.clone(), path.to_path_buf());+ if self.listed.contains(&key) {+ return false;+ }+ let md = path.join(SKILL_MD);+ let meta = match std::fs::metadata(&md) {+ Ok(meta) if meta.is_file() => meta,+ Ok(_) => return false,+ Err(e) if e.kind() == ErrorKind::NotFound => return true,+ Err(e) if absent(&e) => return false,+ Err(e) => {+ self.errors.push(SkillError::new(&md, e));+ return false;+ }+ };+ let real_md = real_path.join(SKILL_MD);+ let parsed = match self.cache.get_or_read(&real_md, &meta) {+ Ok(parsed) => parsed,+ Err(e) if absent(&e) => return false,+ Err(e) => {+ self.errors.push(SkillError::new(&md, e));+ return false;+ }+ };+ self.seen.insert(real_md);+ self.listed.insert(key);+ let base = parsed.name.unwrap_or_else(|| {+ path.file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default()+ });+ let name = match loc.scope.plugin_name() {+ Some(plugin) => format!("{plugin}:{base}"),+ None => base,+ };+ self.installs.push(SkillInstall {+ owner: loc.owner,+ scope: loc.scope.clone(),+ linked,+ path: path.to_path_buf(),+ real_path: real_path.to_path_buf(),+ content_hash: parsed.hash,+ name,+ description: parsed.description.unwrap_or_default(),+ updated_at: mtime_ms(&meta),+ });+ false+ }+}++/// 扫一遍:各家本地实例的 home、固定位置与共享目录、Claude Code 插件,加上各项目的项目级+/// 目录。`projects` 是已索引的本地项目根(`Store::local_project_roots`)+pub fn scan(+ adapters: &[Box<dyn AgentAdapter>],+ projects: &[PathBuf],+ cache: &SkillCache,+) -> SkillScan {+ let roster: Vec<(AgentId, Vec<PathBuf>)> = adapters+ .iter()+ .filter(|a| a.host().is_empty())+ .map(|a| (a.agent(), a.homes()))+ .collect();+ scan_in(&roster, &SkillHomes::current(), projects, cache)+}++/// `scan` 的本体:roster 只要 (agent, 确认过的 homes),homes 显式给——测试在临时目录里搭+/// 假 home,不碰环境变量+pub fn scan_in(+ roster: &[(AgentId, Vec<PathBuf>)],+ homes: &SkillHomes,+ projects: &[PathBuf],+ cache: &SkillCache,+) -> SkillScan {+ let plan = plan(roster, homes, projects);+ let mut reader = Reader {+ cache,+ seen: HashSet::new(),+ listed: HashSet::new(),+ installs: Vec::new(),+ errors: plan.errors,+ };+ for loc in &plan.locations {+ if loc.single {+ reader.read_entry(loc, &loc.dir, &loc.real, loc.linked);+ } else {+ reader.read_dir(loc, &loc.dir, &loc.real, loc.linked, 0);+ }+ }+ cache.retain(&reader.seen);+ let mut groups: BTreeMap<(String, String), Vec<SkillInstall>> = BTreeMap::new();+ for install in reader.installs {+ groups+ .entry((install.name.to_lowercase(), install.name.clone()))+ .or_default()+ .push(install);+ }+ SkillScan {+ skills: groups+ .into_iter()+ .map(|((_, name), installs)| Skill::new(name, installs))+ .collect(),+ errors: reader.errors,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_star_segment_expands_to_every_subdirectory() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ for ws in ["alpha", "beta", ".hidden"] {+ std::fs::create_dir_all(home.join("workspaces").join(ws).join("skills")).unwrap();+ }+ let mut plan = Plan::default();+ plan.add_under_home(SkillOwner::Shared, home, "workspaces/*/skills");+ let dirs: Vec<PathBuf> = plan.locations.iter().map(|l| l.dir.clone()).collect();+ assert_eq!(+ dirs,+ vec![+ home.join("workspaces/alpha/skills"),+ home.join("workspaces/beta/skills"),+ ]+ );+ }+}diff --git a/crates/wake-core/tests/skills.rs b/crates/wake-core/tests/skills.rsnew file mode 100644index 0000000..5ea0ef8--- /dev/null+++ b/crates/wake-core/tests/skills.rs@@ -0,0 +1,768 @@+//! skills 只读总览(issue #62):各家 skill 文件夹的归拢、拷贝 / 链接 / 分叉判定、项目级+//! 展开、Claude Code 插件。fixture 全在各自的临时目录里现搭(合成内容),不碰真实数据,+//! 也不用 adapter_contracts 那份只读的共用假 HOME。++mod common;++use std::collections::BTreeMap;+use std::fs;+use std::path::{Path, PathBuf};++use wake_core::models::AgentId;+use wake_core::skills::{+ scan_in, Skill, SkillCache, SkillHomes, SkillOwner, SkillScan, SkillScope,+};++fn write(path: &Path, text: &str) {+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, text).unwrap();+}++fn skill_md(name: &str, description: &str) -> String {+ format!("---\nname: {name}\ndescription: {description}\n---\n\n# {name}\n\nBody.\n")+}++/// `<dir>/<name>/SKILL.md`+fn put_skill(dir: &Path, name: &str, text: &str) -> PathBuf {+ let path = dir.join(name);+ write(&path.join("SKILL.md"), text);+ path+}++/// 默认布局下各家实例确认过的 home(与 create_adapters 构造出来的同形):skill 目录挂在它下面+fn roster(home: &Path, agents: &[AgentId]) -> Vec<(AgentId, Vec<PathBuf>)> {+ agents+ .iter()+ .map(|&agent| {+ let dir = match agent {+ AgentId::ClaudeCode => ".claude",+ AgentId::Codex => ".codex",+ AgentId::Cursor => ".cursor",+ AgentId::Kiro => ".kiro",+ AgentId::Hermes => ".hermes",+ AgentId::Gemini => ".gemini",+ other => panic!("no fixture layout for {other:?}"),+ };+ (agent, vec![home.join(dir)])+ })+ .collect()+}++fn run(home: &Path, agents: &[AgentId], projects: &[PathBuf]) -> SkillScan {+ scan_in(+ &roster(home, agents),+ &SkillHomes::at(home),+ projects,+ &SkillCache::new(),+ )+}++fn by_name(scan: &SkillScan) -> BTreeMap<&str, &Skill> {+ scan.skills.iter().map(|s| (s.name.as_str(), s)).collect()+}++fn names(scan: &SkillScan) -> Vec<&str> {+ scan.skills.iter().map(|s| s.name.as_str()).collect()+}++/// roster 里这一家的默认实例(用来调 `with_custom_root`)+fn adapter(agent: AgentId) -> Box<dyn wake_core::adapters::AgentAdapter> {+ wake_core::adapters::create_adapters()+ .into_iter()+ .find(|a| a.agent() == agent)+ .unwrap()+}++#[test]+fn identical_copies_across_agents_group_into_one_skill() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let text = skill_md("deploy", "Ship it");+ put_skill(&home.join(".claude/skills"), "deploy", &text);+ put_skill(&home.join(".codex/skills"), "deploy", &text);+ put_skill(&home.join(".kiro/skills"), "deploy", &text);+ put_skill(+ &home.join(".claude/skills"),+ "solo",+ &skill_md("solo", "Only here"),+ );++ let scan = run(+ home,+ &[AgentId::ClaudeCode, AgentId::Codex, AgentId::Kiro],+ &[],+ );+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ let skills = by_name(&scan);+ assert_eq!(skills.len(), 2);+ let deploy = skills["deploy"];+ assert_eq!(deploy.installs.len(), 3);+ assert_eq!(deploy.copies, 3);+ assert!(!deploy.differs);+ assert!(!deploy.linked);+ assert_eq!(deploy.description(), "Ship it");+ assert_eq!(+ deploy.owners,+ vec![+ SkillOwner::Agent(AgentId::ClaudeCode),+ SkillOwner::Agent(AgentId::Codex),+ SkillOwner::Agent(AgentId::Kiro),+ ]+ );+ assert!(deploy.installs.iter().all(|i| i.scope == SkillScope::User));++ let counts = scan.counts();+ assert_eq!(counts.total, 2);+ assert_eq!(counts.duplicated, 1);+ assert_eq!(+ counts.owners,+ vec![+ (SkillOwner::Agent(AgentId::ClaudeCode), 2),+ (SkillOwner::Agent(AgentId::Codex), 1),+ (SkillOwner::Agent(AgentId::Kiro), 1),+ ]+ );+}++#[test]+fn diverged_copies_are_flagged() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ put_skill(+ &home.join(".claude/skills"),+ "lint",+ &skill_md("lint", "Old"),+ );+ put_skill(+ &home.join(".cursor/skills"),+ "lint",+ &skill_md("lint", "New"),+ );+ // 只差在 SKILL.md 以外的文件:按设计只比 SKILL.md,不算分叉+ put_skill(&home.join(".claude/skills"), "same", &skill_md("same", "x"));+ let other = put_skill(&home.join(".cursor/skills"), "same", &skill_md("same", "x"));+ write(&other.join("scripts/run.sh"), "echo different\n");++ let scan = run(home, &[AgentId::ClaudeCode, AgentId::Cursor], &[]);+ let skills = by_name(&scan);+ assert!(skills["lint"].differs);+ assert!(!skills["same"].differs);+ assert_eq!(skills["same"].copies, 2);+}++#[cfg(unix)]+#[test]+fn a_symlinked_install_is_the_same_copy() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let shared = put_skill(+ &home.join(".agents/skills"),+ "find",+ &skill_md("find", "Find"),+ );+ fs::create_dir_all(home.join(".claude/skills")).unwrap();+ // `npx skills add` 的形态:相对链接回共享目录+ std::os::unix::fs::symlink(+ "../../.agents/skills/find",+ home.join(".claude/skills/find"),+ )+ .unwrap();+ // 整个文件夹链过去的一家:里面每一项都算链接+ fs::create_dir_all(home.join(".codex")).unwrap();+ std::os::unix::fs::symlink(home.join(".agents/skills"), home.join(".codex/skills")).unwrap();++ let scan = run(home, &[AgentId::ClaudeCode, AgentId::Codex], &[]);+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ let find = by_name(&scan)["find"];+ assert_eq!(find.installs.len(), 3);+ assert_eq!(find.copies, 1);+ assert!(find.linked);+ let linked: BTreeMap<SkillOwner, bool> =+ find.installs.iter().map(|i| (i.owner, i.linked)).collect();+ assert_eq!(linked[&SkillOwner::Shared], false);+ assert_eq!(linked[&SkillOwner::Agent(AgentId::ClaudeCode)], true);+ assert_eq!(linked[&SkillOwner::Agent(AgentId::Codex)], true);+ let real = fs::canonicalize(shared).unwrap();+ assert!(find.installs.iter().all(|i| i.real_path == real));+ assert_eq!(scan.counts().duplicated, 0, "links are not duplicates");+}++#[test]+fn entries_without_a_skill_md_are_ignored() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let dir = home.join(".claude/skills");+ put_skill(&dir, "real", &skill_md("real", "Yes"));+ fs::create_dir_all(dir.join("empty")).unwrap();+ write(&dir.join("notes/README.md"), "not a skill\n");+ write(&dir.join("loose-file.md"), "---\nname: loose\n---\n");+ // 点开头的条目(Codex 的 .system 自带 skill)不看+ put_skill(+ &dir.join(".system"),+ "builtin",+ &skill_md("builtin", "Hidden"),+ );+ put_skill(&dir, ".hidden", &skill_md("hidden", "Hidden"));+ // 不是 Hermes 的位置不按分类目录往下找+ put_skill(+ &dir.join("category"),+ "nested",+ &skill_md("nested", "Too deep"),+ );++ let scan = run(home, &[AgentId::ClaudeCode], &[]);+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ assert_eq!(names(&scan), vec!["real"]);+}++#[cfg(unix)]+#[test]+fn only_the_top_level_skill_md_is_ever_opened() {+ use std::os::unix::fs::PermissionsExt;+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let skill = put_skill(+ &home.join(".claude/skills"),+ "big",+ &skill_md("big", "Huge repo"),+ );+ // 一个 1.3 GB 的检出的替身:打不开的兄弟文件与目录。扫描若读它们或往里递归,就会报错+ let blob = skill.join("node_modules.bin");+ write(&blob, "x");+ fs::set_permissions(&blob, fs::Permissions::from_mode(0o000)).unwrap();+ let deep = skill.join("vendor");+ put_skill(&deep, "inner", &skill_md("inner", "Must not be listed"));+ fs::set_permissions(&deep, fs::Permissions::from_mode(0o000)).unwrap();++ let scan = run(home, &[AgentId::ClaudeCode], &[]);+ fs::set_permissions(&deep, fs::Permissions::from_mode(0o755)).unwrap();+ fs::set_permissions(&blob, fs::Permissions::from_mode(0o644)).unwrap();+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ assert_eq!(names(&scan), vec!["big"]);+}++#[cfg(unix)]+#[test]+fn an_unreadable_folder_is_an_error_not_an_empty_list() {+ use std::os::unix::fs::PermissionsExt;+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let dir = home.join(".claude/skills");+ put_skill(&dir, "a", &skill_md("a", "A"));+ fs::set_permissions(&dir, fs::Permissions::from_mode(0o000)).unwrap();+ let scan = run(home, &[AgentId::ClaudeCode], &[]);+ fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();+ assert!(scan.skills.is_empty());+ assert_eq!(scan.errors.len(), 1, "{:?}", scan.errors);+}++#[test]+fn project_folders_expand_under_every_indexed_project() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ let alpha = tmp.path().join("work/alpha");+ let beta = tmp.path().join("work/beta");+ let text = skill_md("review", "Review a diff");+ put_skill(&alpha.join(".claude/skills"), "review", &text);+ put_skill(&beta.join(".agents/skills"), "review", &text);+ put_skill(+ &beta.join(".codex/skills"),+ "only-beta",+ &skill_md("only-beta", "B"),+ );+ put_skill(+ &home.join(".claude/skills"),+ "global",+ &skill_md("global", "G"),+ );+ // 一个没有 skill 的项目,以及家目录本身也被索引成了项目:`~/.claude/skills` 已是+ // 用户级,不能再当项目级列一遍+ let gamma = tmp.path().join("work/gamma");+ fs::create_dir_all(&gamma).unwrap();+ let projects = vec![alpha.clone(), beta.clone(), gamma, home.clone()];++ let scan = run(&home, &[AgentId::ClaudeCode, AgentId::Codex], &projects);+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ let skills = by_name(&scan);+ let review = skills["review"];+ let scopes: Vec<(SkillOwner, &SkillScope)> = review+ .installs+ .iter()+ .map(|i| (i.owner, &i.scope))+ .collect();+ assert_eq!(+ scopes,+ vec![+ (+ SkillOwner::Shared,+ &SkillScope::Project { root: beta.clone() }+ ),+ (+ SkillOwner::Agent(AgentId::ClaudeCode),+ &SkillScope::Project {+ root: alpha.clone()+ }+ ),+ ]+ );+ assert_eq!(skills["global"].installs.len(), 1);+ assert_eq!(skills["global"].installs[0].scope, SkillScope::User);+ assert_eq!(+ scan.counts().projects,+ vec![(alpha.clone(), 1), (beta.clone(), 2)]+ );+}++#[test]+fn frontmatter_gives_name_and_description() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let dir = home.join(".claude/skills");+ put_skill(+ &dir,+ "folded",+ "---\nname: folded\ndescription: >\n Use when the user\n asks for it.\nversion: 1\n---\nbody\n",+ );+ put_skill(+ &dir,+ "quoted",+ "---\nname: \"quoted\"\ndescription: \"Has: a colon\"\n---\n",+ );+ // 没有 name 用目录名;没有 description 给空串+ put_skill(&dir, "dir-name", "---\ndescription: From the dir\n---\n");+ put_skill(&dir, "bare", "# No frontmatter at all\n");+ // frontmatter 里的名字与目录名不同:按 frontmatter 归组+ put_skill(+ &dir,+ "renamed-dir",+ &skill_md("canonical", "Named in frontmatter"),+ );++ let scan = run(home, &[AgentId::ClaudeCode], &[]);+ let skills = by_name(&scan);+ assert_eq!(+ skills["folded"].description(),+ "Use when the user asks for it."+ );+ assert_eq!(skills["quoted"].description(), "Has: a colon");+ assert_eq!(skills["dir-name"].description(), "From the dir");+ assert_eq!(skills["bare"].description(), "");+ assert!(skills["canonical"].installs[0]+ .path+ .ends_with("renamed-dir"));+ assert!(!skills.contains_key("renamed-dir"));+}++#[test]+fn hermes_category_folders_are_walked_down_to_the_skill() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let dir = home.join(".hermes/skills");+ put_skill(&dir, "top", &skill_md("top", "Top level"));+ write(&dir.join("mlops/DESCRIPTION.md"), "Category\n");+ put_skill(+ &dir.join("mlops"),+ "axolotl",+ &skill_md("axolotl", "Fine-tune"),+ );+ put_skill(+ &dir.join("mlops/cloud"),+ "modal",+ &skill_md("modal", "Deeper"),+ );+ // 封顶:再深一层不找+ put_skill(&dir.join("a/b/c"), "too-deep", &skill_md("too-deep", "No"));++ let scan = run(home, &[AgentId::Hermes], &[]);+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ assert_eq!(names(&scan), vec!["axolotl", "modal", "top"]);+}++#[test]+fn claude_plugin_skills_come_from_the_installed_version_only() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let plugins = home.join(".claude/plugins");+ let current = plugins.join("cache/market/tools/2.0.0");+ let stale = plugins.join("cache/market/tools/1.0.0");+ let off = plugins.join("cache/market/stripe/0.1.0");+ put_skill(+ ¤t.join("skills"),+ "lint",+ &skill_md("lint", "Current"),+ );+ put_skill(+ ¤t.join("extra"),+ "fmt",+ &skill_md("fmt", "Listed in the manifest"),+ );+ write(+ ¤t.join(".claude-plugin/plugin.json"),+ r#"{"name": "tools", "skills": ["./extra/", "./solo"]}"#,+ );+ // 清单直接点名一个 skill 的目录(里面就有 SKILL.md)+ write(+ ¤t.join("solo/SKILL.md"),+ &skill_md("solo", "A single skill dir"),+ );+ put_skill(&stale.join("skills"), "lint", &skill_md("lint", "Stale"));+ put_skill(+ &stale.join("skills"),+ "gone",+ &skill_md("gone", "Only in the stale copy"),+ );+ put_skill(+ &off.join("skills"),+ "pay",+ &skill_md("pay", "Disabled plugin"),+ );+ let index = serde_json::json!({+ "version": 2,+ "plugins": {+ "tools@market": [{"scope": "user", "installPath": current, "version": "2.0.0"}],+ "stripe@market": [{"scope": "user", "installPath": off, "version": "0.1.0"}],+ }+ });+ write(&plugins.join("installed_plugins.json"), &index.to_string());+ write(+ &home.join(".claude/settings.json"),+ r#"{"enabledPlugins": {"tools@market": true, "stripe@market": false}}"#,+ );+ // 用户级同名的 lint:与插件的 `tools:lint` 是两个 skill+ put_skill(+ &home.join(".claude/skills"),+ "lint",+ &skill_md("lint", "User"),+ );++ let scan = run(home, &[AgentId::ClaudeCode], &[]);+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ let skills = by_name(&scan);+ let names: Vec<&str> = skills.keys().copied().collect();+ assert_eq!(+ names,+ vec![+ "lint",+ "stripe:pay",+ "tools:fmt",+ "tools:lint",+ "tools:solo"+ ]+ );+ assert_eq!(skills["tools:lint"].description(), "Current");+ assert_eq!(+ skills["tools:lint"].installs[0].scope,+ SkillScope::Plugin {+ id: "tools@market".into(),+ enabled: true+ }+ );+ assert_eq!(+ skills["stripe:pay"].installs[0].scope,+ SkillScope::Plugin {+ id: "stripe@market".into(),+ enabled: false+ }+ );+ assert_eq!(skills["lint"].description(), "User");+ assert_eq!(+ (skills["stripe:pay"].plugin, skills["lint"].plugin),+ (true, false)+ );+}++#[test]+fn edits_are_picked_up_and_the_scan_writes_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let skill = put_skill(+ &home.join(".claude/skills"),+ "doc",+ &skill_md("doc", "First"),+ );+ let snapshot = |root: &Path| -> Vec<(PathBuf, u64, Option<std::time::SystemTime>)> {+ let mut out: Vec<_> = walkdir::WalkDir::new(root)+ .into_iter()+ .map(|e| {+ let e = e.unwrap();+ let m = e.metadata().unwrap();+ (e.path().to_path_buf(), m.len(), m.modified().ok())+ })+ .collect();+ out.sort();+ out+ };+ let cache = SkillCache::new();+ let roster = roster(home, &[AgentId::ClaudeCode]);+ let homes = SkillHomes::at(home);+ let before = snapshot(home);+ let first = scan_in(&roster, &homes, &[], &cache);+ assert_eq!(snapshot(home), before, "a scan must not write anything");+ assert_eq!(first.skills[0].description(), "First");+ // 内容换了(大小也变了):缓存不能交旧的+ write(&skill.join("SKILL.md"), &skill_md("doc", "Second, longer"));+ let second = scan_in(&roster, &homes, &[], &cache);+ assert_eq!(second.skills[0].description(), "Second, longer");+ assert_ne!(+ first.skills[0].installs[0].content_hash,+ second.skills[0].installs[0].content_hash+ );+}++#[test]+fn agent_folders_outside_the_roster_still_count() {+ // 会话 location 全停用的家(roster 里没有实例):固定位置与项目级目录照样列,只有挂在+ // 实例 home 下的那份跟着消失+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ let project = tmp.path().join("work/app");+ put_skill(+ &home.join(".kilo/skills"),+ "fixed",+ &skill_md("fixed", "Kilo"),+ );+ put_skill(+ &home.join(".claude/skills"),+ "rooted",+ &skill_md("rooted", "Claude"),+ );+ put_skill(+ &project.join(".claude/skills"),+ "local",+ &skill_md("local", "Project"),+ );+ let scan = run(&home, &[], &[project]);+ assert_eq!(names(&scan), vec!["fixed", "local"]);+}++#[test]+fn adapter_homes_need_structural_evidence() {+ let tmp = tempfile::tempdir().unwrap();+ let base = tmp.path();+ // 默认实例的构造会探 env 根与家目录(Hermes 列 profiles):先把它们指到空的假 HOME+ let fake_home = base.join("home");+ fs::create_dir_all(&fake_home).unwrap();+ common::isolate_home(&fake_home);+ // 每家都拿一个空目录当自定义根:报出来的 home 必须是数据根的上层(或就是它的目录),+ // 不能凭名字往外摸+ for adapter in wake_core::adapters::create_adapters() {+ let dir = base.join(format!("bare-{}", adapter.agent().as_str()));+ fs::create_dir_all(&dir).unwrap();+ let custom = adapter.with_custom_root(dir);+ let roots = custom.data_roots();+ for home in custom.homes() {+ assert!(+ roots.iter().all(|r| r.starts_with(&home)),+ "{:?}: home {home:?} is not above {roots:?}",+ adapter.agent()+ );+ }+ }+ // 选的是 home 形态 → home 就是它;直接选了数据目录本身 → 没有 home(不越界摸父目录)+ let cases: &[(AgentId, &str)] = &[+ (AgentId::ClaudeCode, "projects"),+ (AgentId::Codex, "sessions"),+ (AgentId::Qoder, "projects"),+ (AgentId::Cursor, "projects"),+ (AgentId::Codebuddy, "projects"),+ (AgentId::Dsh, "sessions"),+ (AgentId::Kiro, "sessions/cli"),+ (AgentId::Pi, "agent/sessions"),+ (AgentId::CraftAgents, "workspaces"),+ // 读边车时 Grok 会按名字去 sessions 的父目录找,但那不是用户选的范围+ (AgentId::Grok, "sessions"),+ ];+ for &(agent, data) in cases {+ let home = base.join(format!("home-{}", agent.as_str()));+ let data_dir = data.split('/').fold(home.clone(), |p, seg| p.join(seg));+ fs::create_dir_all(&data_dir).unwrap();+ if agent == AgentId::Codex {+ // Codex 认 home 要独立证据(state DB 或兄弟目录),见 normalize_custom_root+ fs::create_dir_all(home.join("archived_sessions")).unwrap();+ }+ let adapter = adapter(agent);+ let expected = if agent == AgentId::Pi {+ home.join("agent")+ } else {+ home.clone()+ };+ assert_eq!(+ adapter.with_custom_root(home.clone()).homes(),+ vec![expected],+ "{agent:?} home form"+ );+ let bare = adapter.with_custom_root(data_dir.clone());+ assert!(bare.homes().is_empty(), "{agent:?} bare {data_dir:?}");+ }+ // Pi / Oh My Pi:直接选了 agent 那一层(里面就有 sessions/),它自己就是 home+ let agent_dir = base.join("pi-agent");+ fs::create_dir_all(agent_dir.join("sessions")).unwrap();+ for agent in [AgentId::Pi, AgentId::Omp] {+ assert_eq!(+ adapter(agent).with_custom_root(agent_dir.clone()).homes(),+ vec![agent_dir.clone()],+ "{agent:?} agent dir"+ );+ }+ // Hermes:选目录(home 或档案目录)就是 home;直接给一份 state.db 文件则没有+ let hermes = adapter(AgentId::Hermes);+ let dir = base.join("hermes-home");+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("state.db"), b"").unwrap();+ assert_eq!(+ hermes.with_custom_root(dir.clone()).homes(),+ vec![dir.clone()]+ );+ assert!(hermes+ .with_custom_root(dir.join("state.db"))+ .homes()+ .is_empty());+}++#[cfg(unix)]+#[test]+fn a_project_folder_linked_to_the_shared_one_is_still_an_install() {+ // `<repo>/.claude/skills` 链到 ~/.agents/skills:真实路径与共享目录相同,但它是项目里+ // 的一处安装,不能当成"家目录被索引成项目"那种重复丢掉+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ let repo = tmp.path().join("work/repo");+ put_skill(+ &home.join(".agents/skills"),+ "shared",+ &skill_md("shared", "S"),+ );+ fs::create_dir_all(repo.join(".claude")).unwrap();+ std::os::unix::fs::symlink(home.join(".agents/skills"), repo.join(".claude/skills")).unwrap();+ let scan = run(&home, &[AgentId::ClaudeCode], &[repo.clone(), home.clone()]);+ let shared = by_name(&scan)["shared"];+ let scopes: Vec<(SkillOwner, &SkillScope)> = shared+ .installs+ .iter()+ .map(|i| (i.owner, &i.scope))+ .collect();+ assert_eq!(+ scopes,+ vec![+ (SkillOwner::Shared, &SkillScope::User),+ (+ SkillOwner::Agent(AgentId::ClaudeCode),+ &SkillScope::Project { root: repo.clone() }+ ),+ ],+ "the home-as-project copy of ~/.agents/skills is still skipped"+ );+ assert_eq!(shared.copies, 1);+ assert!(shared.installs[1].linked);+}++#[cfg(unix)]+#[test]+fn a_linked_entry_inside_a_linked_folder_is_still_one_copy() {+ // .codex/skills 整个链到 .agents/skills,后者的 deploy 又链到外部目录:三处是同一份+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path().join("home");+ let external = put_skill(+ &tmp.path().join("vendor"),+ "deploy",+ &skill_md("deploy", "D"),+ );+ fs::create_dir_all(home.join(".agents/skills")).unwrap();+ std::os::unix::fs::symlink(&external, home.join(".agents/skills/deploy")).unwrap();+ fs::create_dir_all(home.join(".codex")).unwrap();+ std::os::unix::fs::symlink(home.join(".agents/skills"), home.join(".codex/skills")).unwrap();+ let scan = run(&home, &[AgentId::Codex], &[]);+ let deploy = by_name(&scan)["deploy"];+ assert_eq!(deploy.installs.len(), 2);+ assert_eq!(deploy.copies, 1);+ assert_eq!(scan.counts().duplicated, 0);+}++#[test]+fn plugin_manifest_paths_that_overlap_or_point_at_one_skill() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let plugins = home.join(".claude/plugins");+ // a:清单列了默认 skills/ 下的一个 skill(两条读法读到同一处,只记一次)+ let a = plugins.join("cache/m/a/1.0.0");+ put_skill(&a.join("skills"), "deploy", &skill_md("deploy", "A"));+ write(+ &a.join(".claude-plugin/plugin.json"),+ r#"{"skills": ["./skills/deploy"]}"#,+ );+ // b:清单说 skills 在 ./skills,而 SKILL.md 就直接放在 skills/ 里(本身是一个 skill)+ let b = plugins.join("cache/m/b/1.0.0");+ write(&b.join("skills/SKILL.md"), &skill_md("whole", "B"));+ write(+ &b.join(".claude-plugin/plugin.json"),+ r#"{"skills": "./skills"}"#,+ );+ let index = serde_json::json!({+ "plugins": {+ "a@m": [{"installPath": a}],+ "b@m": [{"installPath": b}],+ }+ });+ write(&plugins.join("installed_plugins.json"), &index.to_string());+ let scan = run(home, &[AgentId::ClaudeCode], &[]);+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ let skills = by_name(&scan);+ assert_eq!(+ skills.keys().copied().collect::<Vec<_>>(),+ vec!["a:deploy", "b:whole"]+ );+ assert_eq!(skills["a:deploy"].installs.len(), 1);+}++#[test]+fn a_broken_plugin_manifest_is_reported_not_ignored() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let plugins = home.join(".claude/plugins");+ let install = plugins.join("cache/m/p/1.0.0");+ put_skill(+ &install.join("skills"),+ "kept",+ &skill_md("kept", "Default dir still read"),+ );+ write(&install.join(".claude-plugin/plugin.json"), "{ not json");+ let index = serde_json::json!({"plugins": {"p@m": [{"installPath": install}]}});+ write(&plugins.join("installed_plugins.json"), &index.to_string());+ let scan = run(home, &[AgentId::ClaudeCode], &[]);+ assert_eq!(scan.errors.len(), 1, "{:?}", scan.errors);+ assert!(scan.errors[0].path.ends_with("plugin.json"));+ assert!(by_name(&scan).contains_key("p:kept"));+}++#[test]+fn overlapping_plugin_paths_are_read_once_whatever_the_order() {+ let tmp = tempfile::tempdir().unwrap();+ let home = tmp.path();+ let plugins = home.join(".claude/plugins");+ // c:清单先点名 extra 里的一个 skill、再列整个 extra——同一处只记一次+ let c = plugins.join("cache/m/c/1.0.0");+ put_skill(&c.join("extra"), "deploy", &skill_md("deploy", "C"));+ write(+ &c.join(".claude-plugin/plugin.json"),+ r#"{"skills": ["./extra/deploy", "./extra"]}"#,+ );+ // d:`skills/` 本身是一个 skill,清单又点名了它下面的 deploy——两个都在+ let d = plugins.join("cache/m/d/1.0.0");+ write(&d.join("skills/SKILL.md"), &skill_md("whole", "D"));+ put_skill(&d.join("skills"), "deploy", &skill_md("deploy", "D2"));+ write(+ &d.join(".claude-plugin/plugin.json"),+ r#"{"skills": ["./skills/deploy"]}"#,+ );+ let index = serde_json::json!({+ "plugins": {+ "c@m": [{"installPath": c}],+ "d@m": [{"installPath": d}],+ }+ });+ write(&plugins.join("installed_plugins.json"), &index.to_string());+ let scan = run(home, &[AgentId::ClaudeCode], &[]);+ assert!(scan.errors.is_empty(), "{:?}", scan.errors);+ assert_eq!(names(&scan), vec!["c:deploy", "d:deploy", "d:whole"]);+ assert_eq!(by_name(&scan)["c:deploy"].installs.len(), 1);+}diff --git a/crates/wake/assets/icons/puzzle.svg b/crates/wake/assets/icons/puzzle.svgnew file mode 100644index 0000000..c49d589--- /dev/null+++ b/crates/wake/assets/icons/puzzle.svg@@ -0,0 +1,15 @@+<!-- @license lucide-static v0.462.0 - ISC -->+<svg+ class="lucide lucide-puzzle"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z" />+</svg>diff --git a/crates/wake/assets/icons/triangle-alert.svg b/crates/wake/assets/icons/triangle-alert.svgnew file mode 100644index 0000000..b048845--- /dev/null+++ b/crates/wake/assets/icons/triangle-alert.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v0.462.0 - ISC -->+<svg+ class="lucide lucide-triangle-alert"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" />+ <path d="M12 9v4" />+ <path d="M12 17h.01" />+</svg>diff --git a/crates/wake/locales/zh-Hans.json b/crates/wake/locales/zh-Hans.jsonindex d93e239..e7aca61 100644--- a/crates/wake/locales/zh-Hans.json+++ b/crates/wake/locales/zh-Hans.json@@ -508,5 +508,33 @@"Unhide": "取消隐藏","Hidden {}": "隐藏于 {}","Couldn't list hidden sessions: {}": "列不出已隐藏的会话:{}",- "Couldn't unhide: {}": "取消隐藏失败:{}"+ "Couldn't unhide: {}": "取消隐藏失败:{}",+ "Skills": "技能",+ "All Skills": "全部技能",+ "Duplicated": "多份拷贝",+ "Shared": "共享",+ "User": "用户级",+ "Plugin {}": "插件 {}",+ "Skills refreshed": "技能已刷新",+ "Could not read this skill: {}": "读不出这个技能:{}",+ "{} skill": "{} 个技能",+ "{} skills": "{} 个技能",+ "No skills found": "没有找到技能",+ "Skills are folders with a SKILL.md that agents load when a task calls for them, like ~/.claude/skills or ~/.agents/skills. They show up here once installed.": "技能是带 SKILL.md 的文件夹,agent 在任务用得上时加载,比如 ~/.claude/skills 或 ~/.agents/skills。装好后就会出现在这里。",+ "Couldn't read {}": "读不出 {}",+ "{} location": "{} 处位置",+ "{} locations": "{} 处位置",+ "link": "链接",+ "disabled": "已停用",+ "same": "相同",+ "different": "不同",+ "To keep one copy and link it into several agents, use npx skills add.": "想只留一份、链接给多个 agent,可以用 npx skills add。",+ "{} copy": "{} 份拷贝",+ "{} copies": "{} 份拷贝",+ "linked": "有链接",+ "differs": "内容不一致",+ "Couldn't read {} location": "{} 处位置读不出",+ "Couldn't read {} locations": "{} 处位置读不出",+ "and {} more": "还有 {} 处",+ "plugin": "插件"}diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rsindex fbabf42..3c8e89e 100644--- a/crates/wake/src/assets.rs+++ b/crates/wake/src/assets.rs@@ -88,6 +88,9 @@ icons!("messages-square",// Memory 页(侧栏模式标题与底部工具条入口)"brain",+ // Skills 页(底部工具条入口与 All Skills 行);列表上方"读不出来"的提示行+ "puzzle",+ "triangle-alert","star","pin","download",diff --git a/crates/wake/src/i18n.rs b/crates/wake/src/i18n.rsindex e7b45fa..07d239d 100644--- a/crates/wake/src/i18n.rs+++ b/crates/wake/src/i18n.rs@@ -622,6 +622,7 @@ mod tests {include_str!("workbench/cleanup/history.rs"),include_str!("workbench/cleanup/rows.rs"),include_str!("workbench/memory.rs"),+ include_str!("workbench/skills.rs"),include_str!("settings.rs"),include_str!("main.rs"),include_str!("ui_zoom.rs"),diff --git a/crates/wake/src/theme.rs b/crates/wake/src/theme.rsindex c31019f..11d98d5 100644--- a/crates/wake/src/theme.rs+++ b/crates/wake/src/theme.rs@@ -81,6 +81,13 @@ pub const MODEL_BADGE_BG: u32 = CLAUDE_ORANGE;/// 收藏星选中色——macOS systemYellow(Finder/Mail 星标惯例),两模式通用pub const STAR_YELLOW: u32 = 0xFFCC00;+/// Skills 页 "plugin" 徽章色(淡底 + 同色字):紫——界面里别处没用过,与 primary 蓝(`@host`)、+/// Claude 橙(model)、成功绿、危险红、收藏黄都分得开(用户 2026-10-23 要"跟其他不一样");+/// 字色对列表底的对比度浅色 6.1:1、深色 6.6:1+pub fn plugin_badge_color(dark: bool) -> Hsla {+ c(if dark { 0xB794F6 } else { 0x7C3AED })+}+/// Insights 趋势图的 agent 序列色:有彩色品牌的家取品牌色(从内嵌 PNG 取主色,/// 与侧栏图标同调),单色字形的家(Copilot/Cursor/OpenCode/Pi/Grok/Kimi)/// 给固定备选色——同一家在任何机器上颜色都不变,相邻常见组合(Claude/Codex/diff --git a/crates/wake/src/ui.rs b/crates/wake/src/ui.rsindex 3f7ef29..9a67cd8 100644--- a/crates/wake/src/ui.rs+++ b/crates/wake/src/ui.rs@@ -572,10 +572,15 @@ mod tests {#[test]fn bare_pixel_sizes_do_not_creep_back() {const FILES: &[(&str, &str, usize)] = &[- ("workbench.rs", include_str!("workbench.rs"), 17),+ ("workbench.rs", include_str!("workbench.rs"), 18),("workbench/memory.rs",include_str!("workbench/memory.rs"),+ 0,+ ),+ (+ "workbench/skills.rs",+ include_str!("workbench/skills.rs"),1,),(diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rsindex 7d0504a..55630d5 100644--- a/crates/wake/src/workbench.rs+++ b/crates/wake/src/workbench.rs@@ -17,6 +17,7 @@use crate::i18n::t;mod cleanup;mod memory;+mod skills;use std::cell::Cell;use std::collections::{HashMap, HashSet};use std::ops::Range;@@ -2168,6 +2169,7 @@ enum Page {Sessions,Insights,Memory,+ Skills,}pub struct Workbench {@@ -2254,6 +2256,8 @@ pub struct Workbench {cleanup: cleanup::CleanupState,/// Memory 页的数据与选中态(agent 自己写的记忆文档)memory: memory::MemoryState,+ /// Skills 页的扫描结果与选中态(各家 agent 的 skill,只读总览)+ skills: skills::SkillsState,/// Insights 页数据,Rc 免深拷贝insights: Option<Rc<InsightsData>>,insights_loading: bool,@@ -2738,6 +2742,7 @@ impl Workbench {page: Page::Sessions,cleanup: cleanup::CleanupState::default(),memory: memory::MemoryState::default(),+ skills: skills::SkillsState::default(),insights: None,insights_loading: false,insights_range: InsightsRange::Hour,@@ -2918,6 +2923,7 @@ impl Workbench {detail.msg_list.remeasure();}self.memory.remeasure();+ self.skills.remeasure();}fn refresh_session_group_date(&mut self, cx: &mut Context<Self>) {@@ -2964,13 +2970,17 @@ impl Workbench {self.reset_memory_scope();}self.refresh(cx);+ if page == Page::Skills {+ self.enter_skills(cx);+ }}/// 打开着的整页目的地顺带重载(refresh 与扫描终态都走这里);各页自己按住/// "扫描中且已有数据"的情形fn reload_page(&mut self, cx: &mut Context<Self>) {match self.page {- Page::Sessions => {}+ // Skills:skill 与会话无关,会话扫描的事件不重扫,进页与页头 Refresh 才扫+ Page::Sessions | Page::Skills => {}Page::Insights => self.reload_insights(cx),Page::Memory => self.reload_memories(cx),}@@ -3358,6 +3368,8 @@ impl Workbench {self.watcher = None;(self.adapters, self.data_locations) = Self::build_roster(&self.store);self.remount_watcher();+ // skill 目录从 roster 推:页开着就重扫(没开着下次进页本来就会扫)+ self.rescan_open_skills(cx);cx.notify();}@@ -5829,10 +5841,10 @@ impl Workbench {fn render_sidebar(&self, window: &Window, cx: &Context<Self>) -> impl IntoElement {let theme = cx.theme();// Memory 页标题换成 Memory:侧栏顶上就说明现在管的是什么,不另加模式标题行(用户 2026-09-21)- let title = if self.page == Page::Memory {- t("Memory")- } else {- "Wake"+ let title = match self.page {+ Page::Memory => t("Memory"),+ Page::Skills => t("Skills"),+ _ => "Wake",};let all_active = self.selected_agent.is_none()&& self.selected_project.is_none()@@ -5948,6 +5960,7 @@ impl Workbench {// 计数),其余是会话的(搜索框 + All Sessions / Starred + Agents / Projects).child(match self.page {Page::Memory => self.render_memory_nav(cx),+ Page::Skills => self.render_skills_nav(cx),_ => self.render_sessions_nav(all_active, cx),})// 底部工具条:次要操作(数据源、刷新)与扫描状态同处一区,与上方@@ -6076,6 +6089,7 @@ impl Workbench {).child(self.sidebar_groups("sidebar-scroll",+ None,self.agent_counts.iter().map(|(agent, count)| {(*agent,@@ -6099,12 +6113,14 @@ impl Workbench {.into_any_element()}- /// 侧栏的 Agents / Projects 两组(会话导航与 Memory 导航同一套行组件、同一个单选- /// 模型,折叠状态两页共用)。每行给 (身份, 计数, 是否当前);点击回调收到切换后的- /// 目标——点当前项就是 None(回全部)+ /// 侧栏的 Agents / Projects 两组(会话、Memory、Skills 三页的导航同一套行组件、同一个+ /// 单选模型,折叠状态共用)。每行给 (身份, 计数, 是否当前);点击回调收到切换后的+ /// 目标——点当前项就是 None(回全部)。`lead_agent_row` 排在 agent 行之前(Skills 页+ /// 的共享目录那一行,它不是一家 agent)fn sidebar_groups(&self,id: &'static str,+ lead_agent_row: Option<AnyElement>,agents: impl IntoIterator<Item = (AgentId, i64, bool)>,projects: impl IntoIterator<Item = (String, SharedString, i64, bool)>,on_agent: fn(&mut Self, Option<AgentId>, &mut Context<Self>),@@ -6133,20 +6149,21 @@ impl Workbench {cx,)).when(!self.agents_collapsed, |this| {- this.children(agents.into_iter().map(|(agent, count, active)| {- sidebar_row(- agent.as_str(),- RowLead::Brand(agent.brand_icon(dark)),- agent.display_name(),- Some(count),- active,- RowLevel::Sub,- cx.listener(move |this, _, _window, cx| {- on_agent(this, (!active).then_some(agent), cx)- }),- cx,- )- }))+ this.children(lead_agent_row)+ .children(agents.into_iter().map(|(agent, count, active)| {+ sidebar_row(+ agent.as_str(),+ RowLead::Brand(agent.brand_icon(dark)),+ agent.display_name(),+ Some(count),+ active,+ RowLevel::Sub,+ cx.listener(move |this, _, _window, cx| {+ on_agent(this, (!active).then_some(agent), cx)+ }),+ cx,+ )+ }))}).child(group_header("projects-header",@@ -6178,9 +6195,9 @@ impl Workbench {})}- /// 侧栏底部左端的一组:三颗页切换 + Clean up,同尺寸图标钮,当前页那颗 `active`+ /// 侧栏底部左端的一组:四颗页切换 + Clean up,同尺寸图标钮,当前页那颗 `active`/// (侧栏选中色圆角底)。Sessions 也是一颗——否则从 Memory 回来只能"再点一次- /// Memory"。Clean up 打开时三颗页都不亮、它自己亮(它是叠在会话视图上的模式,+ /// Memory"。Clean up 打开时四颗页都不亮、它自己亮(它是叠在会话视图上的模式,/// 不是页;用户 2026-09-21 定它也靠左,右端只留 Settings)fn render_page_switch(&self, cx: &Context<Self>) -> AnyElement {let current = (!self.cleanup.open).then_some(self.page);@@ -6208,6 +6225,12 @@ impl Workbench {"icons/brain.svg",Page::Memory,))+ .child(button(+ "page-skills",+ t("Skills"),+ "icons/puzzle.svg",+ Page::Skills,+ )).child(button("page-insights",t("Insights"),@@ -9802,6 +9825,247 @@ fn outline_badge(name: impl Into<SharedString>, color: Hsla) -> impl IntoElement.child(div().truncate().child(name.into()))}+/// 记忆流与 Skills 列表的行盒(逐项照会话行:ListItem 自带 px_3 / py_1(12 / 4)再套行内容的+/// SPACE_XS / SPACE_SM(4 / 8),高亮面 mx = SPACE_SM——这里没有 ListItem,两层加成一层写死同样+/// 的数);选中 `list_active`、悬停 `list_hover`,内容由调用方给+fn library_row(+ id: impl Into<ElementId>,+ selected: bool,+ on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,+ children: impl IntoIterator<Item = AnyElement>,+ theme: &gpui_component::Theme,+) -> AnyElement {+ div()+ .w_full()+ .px(SPACE_SM)+ .child(+ v_flex()+ .id(id)+ .w_full()+ .min_w_0()+ .rounded(theme.radius)+ .px(SPACE_MD + SPACE_XS)+ .py(SPACE_XS + SPACE_SM)+ .gap(SPACE_XS)+ .cursor_pointer()+ .when(selected, |row| row.bg(theme.list_active))+ .when(!selected, |row| {+ row.hover(|style| style.bg(theme.list_hover))+ })+ .on_click(on_click)+ .children(children),+ )+ .into_any_element()+}++/// 行盒里的标题:Body 14 medium 一行,按显示宽度截断,悬停看全名+fn library_row_title(+ id: impl Into<ElementId>,+ title: &str,+ theme: &gpui_component::Theme,+) -> AnyElement {+ let full: SharedString = title.to_string().into();+ div()+ .id(id)+ .w_full()+ .min_w_0()+ .overflow_hidden()+ .whitespace_nowrap()+ .text_size(FONT_BODY)+ .font_medium()+ .text_color(theme.foreground)+ .child(clip_display(title, SESSION_TITLE_MAX_WIDTH))+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(full.clone()).build(window, cx)+ })+ .into_any_element()+}++/// 行盒元信息行右端的时间:智能时间,悬停看精确时间(悬停时才格式化)+fn library_row_time(id: impl Into<ElementId>, ts: i64) -> AnyElement {+ div()+ .id(id)+ .flex_shrink_0()+ .child(smart_time(ts))+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(abs_date(ts)).build(window, cx)+ })+ .into_any_element()+}++/// 记忆流与 Skills 列表的虚拟化外壳(gpui::list,行高不等):行由 `row` 现画+fn library_list(+ state: &gpui::ListState,+ row: fn(&mut Workbench, usize, &mut Context<Workbench>) -> AnyElement,+ cx: &Context<Workbench>,+) -> AnyElement {+ let entity = cx.entity().downgrade();+ div()+ .flex_1()+ .min_h_0()+ .w_full()+ .relative()+ .child(+ gpui::list(state.clone(), move |ix, _window, cx| {+ entity+ .upgrade()+ .map(|e| e.update(cx, |this, cx| row(this, ix, cx)))+ .unwrap_or_else(|| div().into_any_element())+ })+ .size_full(),+ )+ .vertical_scrollbar(state)+ .into_any_element()+}++/// 列表整段换成 `new_len` 行:重载保滚动位置,`to_top` 回到顶部。splice 整段会把落在段内的+/// 滚动锚点归零(gpui 只保段外的锚点),所以先记下再恢复+fn replace_list_rows(state: &gpui::ListState, old_len: usize, new_len: usize, to_top: bool) {+ let top = if to_top {+ gpui::ListOffset {+ item_ix: 0,+ offset_in_item: px(0.),+ }+ } else {+ state.logical_scroll_top()+ };+ state.splice(0..old_len, new_len);+ state.scroll_to(top);+}++/// 阅读面头部右端的 Reveal / Copy path,与路径、更新时间两行元信息(记忆与 Skills 阅读面+/// 共用;两页从不同时渲染,元素 id 共用一套)+fn file_reader_parts(path: &str, updated_at: i64) -> (Vec<AnyElement>, Vec<AnyElement>) {+ let reveal_path = path.to_string();+ let copy_path = path.to_string();+ let updated: SharedString = crate::tf!("Updated {}", smart_time(updated_at)).into();+ let actions = vec![+ Button::new("reader-reveal")+ .ghost()+ .rounded(RADIUS_BUTTON)+ .icon(icon("icons/folder.svg").with_size(zpx(16.)))+ .tooltip(reveal_in_fm())+ .on_click(move |_, _, _| {+ terminal::reveal_in_file_manager(&reveal_path);+ })+ .into_any_element(),+ Button::new("reader-copy-path")+ .ghost()+ .rounded(RADIUS_BUTTON)+ .icon(icon("icons/copy.svg").with_size(zpx(16.)))+ .tooltip(t("Copy path"))+ .on_click(move |_, _, cx| {+ cx.write_to_clipboard(ClipboardItem::new_string(copy_path.clone()));+ })+ .into_any_element(),+ ];+ let meta_rows = vec![+ h_flex()+ .min_w_0()+ .gap(ICON_TEXT_GAP)+ .child(+ icon("icons/file-text.svg")+ .with_size(zpx(12.))+ .flex_shrink_0(),+ )+ .child(div().min_w_0().truncate().child(tilde_path(path)))+ .into_any_element(),+ h_flex()+ .min_w_0()+ .gap(ICON_TEXT_GAP)+ .items_center()+ .child(+ icon("icons/calendar.svg")+ .with_size(zpx(12.))+ .flex_shrink_0(),+ )+ .child(+ div()+ .id("reader-updated")+ .min_w_0()+ .truncate()+ .child(updated)+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(crate::tf!(+ "Updated {}",+ abs_date(updated_at)+ ))+ .build(window, cx)+ }),+ )+ .into_any_element(),+ ];+ (actions, meta_rows)+}++/// 记忆与 Skills 页右侧没有选中项时:列表还在读就转圈,读完是空的就给空态卡+fn reader_placeholder(+ loading: bool,+ icon_path: &'static str,+ title: &'static str,+ caption: &'static str,+ cx: &App,+) -> AnyElement {+ v_flex()+ .flex_1()+ .h_full()+ .items_center()+ .justify_center()+ .bg(cx.theme().background)+ .child(if loading {+ Spinner::new().into_any_element()+ } else {+ empty_state_card(icon_path, zpx(58.), zpx(24.), title, caption, cx).into_any_element()+ })+ .into_any_element()+}++/// 阅读面正文读到之前的转圈(记忆与 Skills 共用)+fn reader_loading() -> AnyElement {+ div()+ .w_full()+ .flex()+ .justify_center()+ .py(SPACE_XXL)+ .child(Spinner::new())+ .into_any_element()+}++/// 记忆与 Skills 的阅读面:详情页同款头部 + popover 底的正文,720 阅读宽居中,与详情正文+/// 同一组数(24px 阅读轴,上留 16、下留 24)+fn reader_pane(+ id: &'static str,+ header: impl IntoElement,+ content: impl IntoElement,+ theme: &gpui_component::Theme,+) -> AnyElement {+ v_flex()+ .flex_1()+ .min_w_0()+ .h_full()+ .bg(theme.background)+ .child(header)+ .child(+ div()+ .id(id)+ .flex_1()+ .min_h_0()+ .overflow_y_scroll()+ .bg(theme.popover)+ .px(SPACE_XXL)+ .pt(SPACE_LG)+ .pb(SPACE_XXL)+ .child(+ div()+ .w_full()+ .flex()+ .justify_center()+ .child(div().w_full().max_w(READER_MAX_WIDTH).child(content)),+ ),+ )+ .into_any_element()+}+/// 列表流里的分组头(会话流的时间分割线、记忆流的项目组头共用):Label 11 medium/// muted 的标签 + 右侧低对比度 hairline,32px 高、px 12fn section_header_row(label: impl Into<SharedString>, theme: &gpui_component::Theme) -> Div {@@ -9928,7 +10192,7 @@ const FOOTER_BTN: Zpx = Zpx(28.);/// 至少一个 SPACE_SM + 右内边距。100% 档约 177,侧栏 224 绰绰有余;放大后侧栏收窄时/// 以它为下限(`Workbench::columns`)fn sidebar_footer_width() -> Pixels {- FOOTER_LEAD_INSET + FOOTER_BTN * 5. + zpx(2.) * 3. + SPACE_SM + SIDEBAR_EDGE+ FOOTER_LEAD_INSET + FOOTER_BTN * 6. + zpx(2.) * 4. + SPACE_SM + SIDEBAR_EDGE}/// 工具条左内边距 = 26.75(侧栏中轴,红绿灯红灯中心)− 14(按钮半宽),工具条贴着侧栏左缘、/// 没有容器边距:最左那颗图标的中心压在与导航行行首同一条轴上(用户 2026-09-21)@@ -10178,6 +10442,7 @@ impl Render for Workbench {}match self.page {Page::Memory => this.child(self.render_memory(cx)),+ Page::Skills => this.child(self.render_skills(cx)),Page::Insights => this.child(self.render_insights(cx)),Page::Sessions => this.child(self.render_session_list(cx))diff --git a/crates/wake/src/workbench/memory.rs b/crates/wake/src/workbench/memory.rsindex 34b18d3..c3a8d9d 100644--- a/crates/wake/src/workbench/memory.rs+++ b/crates/wake/src/workbench/memory.rs@@ -237,21 +237,13 @@ impl Workbench {});let pin_user = this.memory_pins_user();let rows = memory_rows(&docs, Local::now().date_naive(), pin_user);- // 重载来自每轮扫描,滚动位置要留住:splice 整段会把落在段内的- // 滚动锚点归零(gpui 的 splice 只保段外的锚点),所以先记下再恢复;- // 筛选刚换过则回到顶部- let top = if this.memory.scope_changed {- gpui::ListOffset {- item_ix: 0,- offset_in_item: px(0.),- }- } else {- this.memory.list.logical_scroll_top()- };- this.memory.scope_changed = false;- let old = this.memory.rows.len();- this.memory.list.splice(0..old, rows.len());- this.memory.list.scroll_to(top);+ // 重载来自每轮扫描,滚动位置要留住;筛选刚换过则回到顶部+ replace_list_rows(+ &this.memory.list,+ this.memory.rows.len(),+ rows.len(),+ std::mem::take(&mut this.memory.scope_changed),+ );// 选中项:还在且没变就不动;正文被 agent 改过(时间或大小变了)// 重读,否则新标题配旧正文;没了就落到第一份let stamp = |docs: &[MemoryDoc], key: &str| {@@ -354,26 +346,13 @@ impl Workbench {.and_then(|k| self.memory.docs.iter().find(|d| &d.key == k));let pane: AnyElement = match selected {Some(doc) => self.render_memory_reader(doc, cx),- None => v_flex()- .flex_1()- .h_full()- .items_center()- .justify_center()- .bg(theme.background)- .child(if self.memory.loading {- Spinner::new().into_any_element()- } else {- empty_state_card(- "icons/file-text.svg",- zpx(58.),- zpx(24.),- t("No memory files yet"),- t("Agents write these as they work: Claude Code's auto-memory, Codex's memories, ZCode's project memory. They show up here once they exist."),- cx,- )- .into_any_element()- })- .into_any_element(),+ None => reader_placeholder(+ self.memory.loading,+ "icons/file-text.svg",+ t("No memory files yet"),+ t("Agents write these as they work: Claude Code's auto-memory, Codex's memories, ZCode's project memory. They show up here once they exist."),+ cx,+ ),};h_flex().flex_1()@@ -423,23 +402,7 @@ impl Workbench {/// 记忆流:gpui::list 虚拟化(行高不等:分组头与两行的文档行)fn render_memory_list(&self, cx: &Context<Self>) -> AnyElement {- let entity = cx.entity().downgrade();- div()- .flex_1()- .min_h_0()- .w_full()- .relative()- .child(- gpui::list(self.memory.list.clone(), move |ix, _window, cx| {- entity- .upgrade()- .map(|e| e.update(cx, |this, cx| this.render_memory_row(ix, cx)))- .unwrap_or_else(|| div().into_any_element())- })- .size_full(),- )- .vertical_scrollbar(&self.memory.list)- .into_any_element()+ library_list(&self.memory.list, Self::render_memory_row, cx)}/// 一行:分组头(会话流的时间分割线同款),或两行的文档行(会话行同款:Body 14@@ -468,85 +431,36 @@ impl Workbench {};let selected = self.memory.selected.as_deref() == Some(d.key.as_str());let key = d.key.clone();- let title: SharedString = clip_display(&d.title, SESSION_TITLE_MAX_WIDTH).into();- let title_tooltip: SharedString = d.title.clone().into();- let shown_time: SharedString = smart_time(d.updated_at).into();- let shown_tooltip: SharedString = abs_date(d.updated_at).into();- // 盒模型逐项照会话行:ListItem 自带 px_3 / py_1(12 / 4)再套行内容的- // SPACE_XS / SPACE_SM(4 / 8),高亮面 mx = SPACE_SM——这里没有 ListItem,- // 把两层加成一层写死同样的数。不缩进、不画竖线(树的子行形制试过,用户- // 2026-09-21 定没必要)- div()- .w_full()- .px(SPACE_SM)+ // 不缩进、不画竖线(树的子行形制试过,用户 2026-09-21 定没必要)+ let meta = h_flex()+ .gap(ICON_TEXT_GAP)+ .text_size(FONT_LABEL)+ .text_color(theme.muted_foreground).child(- v_flex()- .id(("memory-row", ix))- .w_full()- .min_w_0()- .rounded(theme.radius)- .px(SPACE_MD + SPACE_XS)- .py(SPACE_XS + SPACE_SM)- .gap(SPACE_XS)- .cursor_pointer()- .when(selected, |row| row.bg(theme.list_active))- .when(!selected, |row| {- row.hover(|style| style.bg(theme.list_hover))- })- .on_click(cx.listener(move |this, _, _window, cx| {- this.select_memory(key.clone(), cx)- }))- .child(- div()- .id(("memory-title", ix))- .w_full()- .min_w_0()- .overflow_hidden()- .whitespace_nowrap()- .text_size(FONT_BODY)- .font_medium()- .text_color(theme.foreground)- .child(title)- .tooltip(move |window, cx| {- gpui_component::tooltip::Tooltip::new(title_tooltip.clone())- .build(window, cx)- }),- )- .child(- h_flex()- .gap(ICON_TEXT_GAP)- .text_size(FONT_LABEL)- .text_color(theme.muted_foreground)- .child(- img(d.agent.brand_icon(theme.mode.is_dark()))- .size(zpx(15.))- .flex_shrink_0(),- )- // 项目徽章与会话行同款(muted 胶囊;用户级 / 没归属的- // 也用组头同一套文案),用户 2026-09-21 定:组头说明了- // 也要挂,和会话列表看起来一致- .child(badge(- memory_group_label(d),- theme.muted,- theme.muted_foreground,- ))- .children(memory_badges(d, &theme))- .child(div().flex_1())- .child(- div()- .id(("memory-time", ix))- .flex_shrink_0()- .child(shown_time)- .tooltip(move |window, cx| {- gpui_component::tooltip::Tooltip::new(- shown_tooltip.clone(),- )- .build(window, cx)- }),- ),- ),+ img(d.agent.brand_icon(theme.mode.is_dark()))+ .size(zpx(15.))+ .flex_shrink_0(),)- .into_any_element()+ // 项目徽章与会话行同款(muted 胶囊;用户级 / 没归属的也用组头同一套+ // 文案),用户 2026-09-21 定:组头说明了也要挂,和会话列表看起来一致+ .child(badge(+ memory_group_label(d),+ theme.muted,+ theme.muted_foreground,+ ))+ .children(memory_badges(d, &theme))+ .child(div().flex_1())+ .child(library_row_time(("memory-time", ix), d.updated_at));+ library_row(+ ("memory-row", ix),+ selected,+ cx.listener(move |this, _, _window, cx| this.select_memory(key.clone(), cx)),+ [+ library_row_title(("memory-title", ix), &d.title, &theme),+ meta.into_any_element(),+ ],+ &theme,+ )}}}@@ -565,8 +479,6 @@ impl Workbench {.as_ref().map(|l| l.source_path.clone()).unwrap_or_else(|| memory_display_path(doc));- let reveal_path = source_path.clone();- let copy_path = source_path.clone();// 相对链接按记忆文件所在目录解析(MEMORY.md 链接的是同目录的主题文件),// 不是项目根;SQLite 型没有目录,退项目路径let link_base = if source_path == doc.path {@@ -577,9 +489,6 @@ impl Workbench {} else {doc.project_path.clone()};- let updated: SharedString = crate::tf!("Updated {}", smart_time(doc.updated_at)).into();- let updated_tooltip: SharedString =- crate::tf!("Updated {}", abs_date(doc.updated_at)).into();let mut lead: Vec<AnyElement> = vec![img(doc.agent.brand_icon(dark)).size(zpx(15.))@@ -597,59 +506,7 @@ impl Workbench {),];lead.extend(memory_badges(doc, &theme));- let actions: Vec<AnyElement> = vec![- Button::new("memory-reveal")- .ghost()- .rounded(RADIUS_BUTTON)- .icon(icon("icons/folder.svg").with_size(zpx(16.)))- .tooltip(reveal_in_fm())- .on_click(move |_, _, _| {- terminal::reveal_in_file_manager(&reveal_path);- })- .into_any_element(),- Button::new("memory-copy-path")- .ghost()- .rounded(RADIUS_BUTTON)- .icon(icon("icons/copy.svg").with_size(zpx(16.)))- .tooltip(t("Copy path"))- .on_click(move |_, _, cx| {- cx.write_to_clipboard(ClipboardItem::new_string(copy_path.clone()));- })- .into_any_element(),- ];- let meta_rows: Vec<AnyElement> = vec![- h_flex()- .min_w_0()- .gap(ICON_TEXT_GAP)- .child(- icon("icons/file-text.svg")- .with_size(zpx(12.))- .flex_shrink_0(),- )- .child(div().min_w_0().truncate().child(tilde_path(&source_path)))- .into_any_element(),- h_flex()- .min_w_0()- .gap(ICON_TEXT_GAP)- .items_center()- .child(- icon("icons/calendar.svg")- .with_size(zpx(12.))- .flex_shrink_0(),- )- .child(- div()- .id("memory-updated")- .min_w_0()- .truncate()- .child(updated)- .tooltip(move |window, cx| {- gpui_component::tooltip::Tooltip::new(updated_tooltip.clone())- .build(window, cx)- }),- )- .into_any_element(),- ];+ let (actions, meta_rows) = file_reader_parts(&source_path, doc.updated_at);let header = detail_header_frame("memory-detail-header",lead,@@ -670,40 +527,9 @@ impl Workbench {cx,).into_any_element(),- None => div()- .w_full()- .flex()- .justify_center()- .py(SPACE_XXL)- .child(Spinner::new())- .into_any_element(),+ None => reader_loading(),};- v_flex()- .flex_1()- .min_w_0()- .h_full()- .bg(theme.background)- .child(header)- .child(- div()- .id("memory-reader")- .flex_1()- .min_h_0()- .overflow_y_scroll()- .bg(theme.popover)- // 与详情正文同一组数:24px 阅读轴,首条上留 16、末条下留 24- .px(SPACE_XXL)- .pt(SPACE_LG)- .pb(SPACE_XXL)- .child(- div()- .w_full()- .flex()- .justify_center()- .child(div().w_full().max_w(READER_MAX_WIDTH).child(content)),- ),- )- .into_any_element()+ reader_pane("memory-reader", header, content, &theme)}/// Memory 页的侧栏导航,替换会话导航(搜索框、All Sessions / Starred、Agents /@@ -757,6 +583,7 @@ impl Workbench {).child(self.sidebar_groups("memory-sidebar-scroll",+ None,counts.agents.iter().map(|(agent, count)| {(*agent,diff --git a/crates/wake/src/workbench/skills.rs b/crates/wake/src/workbench/skills.rsnew file mode 100644index 0000000..53b2fe9--- /dev/null+++ b/crates/wake/src/workbench/skills.rs@@ -0,0 +1,818 @@+//! Skills 页(issue #62):各家 agent 的 skill 只读总览——哪些 skill 装在哪些 agent 里、+//! 哪些是同一份(链接)、哪些是各自的拷贝、拷贝之间有没有分叉。侧栏底部入口,整页目的地,+//! 与 Memory 页同形制:左列列表 + 右侧阅读面(位置表 + 渲染后的 SKILL.md)。数据来自+//! `wake_core::skills::scan`,不进索引库:进页与页头 Refresh 时后台现扫(几十毫秒)。+//! 只看不改:动作只有 Reveal 与 Copy path——跨 agent 装 skill 是 `npx skills add` 的事,+//! 写别家的目录破只读铁律(用户 2026-10-15 定)++use super::*;+use wake_core::adapters::strip_frontmatter;+use wake_core::skills::{+ self as core_skills, Skill, SkillCache, SkillCounts, SkillInstall, SkillOwner, SkillScan,+ SkillScope,+};++/// 侧栏导航的筛选(单选互斥,与会话 / 记忆侧栏同一模型:再点当前项回到 All)+#[derive(Debug, Clone, PartialEq, Eq)]+enum SkillNav {+ All,+ /// 有两份及以上真实拷贝的(链接不算)+ Duplicated,+ Owner(SkillOwner),+ Project(PathBuf),+}++/// 阅读面正在显示的那份 SKILL.md(后台读好、去掉 frontmatter);`content_hash` 是扫描时+/// 那份的内容指纹——重扫后变了就重读,不让新说明配旧正文(按 mtime 比会漏掉保留原+/// 修改时间的改写,Codex review 2026-10-15)+struct LoadedSkill {+ /// 这一处安装的目录(`SkillInstall::path`)+ dir: PathBuf,+ content_hash: u64,+ body: SharedString,+ /// 读失败了(正文是错误提示):不算"没变",再点 / 重扫时重读(Codex review 2026-10-15)+ failed: bool,+}++pub(super) struct SkillsState {+ scan: SkillScan,+ counts: SkillCounts,+ /// 当前筛选下列表里的 skill(`scan.skills` 的下标),交 gpui::list 虚拟化+ rows: Vec<usize>,+ list: gpui::ListState,+ nav: SkillNav,+ /// 选中的 skill(`scan.skills` 的下标;重扫后按名字找回)与阅读面显示的那处安装+ /// (`installs` 的下标)+ selected: Option<usize>,+ shown: usize,+ loaded: Option<LoadedSkill>,+ scanning: bool,+ cache: Arc<SkillCache>,+ scan_task: Option<Task<()>>,+ body_task: Option<Task<()>>,+}++impl Default for SkillsState {+ fn default() -> Self {+ Self {+ scan: SkillScan::default(),+ counts: SkillCounts::default(),+ rows: Vec::new(),+ list: gpui::ListState::new(0, gpui::ListAlignment::Top, zpx(200.)),+ nav: SkillNav::All,+ selected: None,+ shown: 0,+ loaded: None,+ scanning: false,+ cache: Arc::new(SkillCache::new()),+ scan_task: None,+ body_task: None,+ }+ }+}++impl SkillsState {+ /// 换过缩放档位:行高按旧倍数量过,按比例重量(见 Workbench::sync_zoom)+ pub(super) fn remeasure(&self) {+ self.list.remeasure();+ }++ fn selected_skill(&self) -> Option<&Skill> {+ self.scan.skills.get(self.selected?)+ }+}++/// 筛选谓词:侧栏一行对应的那组 skill+fn skill_matches(skill: &Skill, nav: &SkillNav) -> bool {+ match nav {+ SkillNav::All => true,+ SkillNav::Duplicated => skill.copies > 1,+ _ => skill.installs.iter().any(|i| install_matches(i, nav)),+ }+}++/// 这一处安装是不是筛选点名的那方 / 那个项目里的(All 与 Duplicated 不点名)+fn install_matches(install: &SkillInstall, nav: &SkillNav) -> bool {+ match nav {+ SkillNav::Owner(owner) => install.owner == *owner,+ SkillNav::Project(root) => {+ matches!(&install.scope, SkillScope::Project { root: r } if r == root)+ }+ SkillNav::All | SkillNav::Duplicated => false,+ }+}++/// 选中一个 skill 时默认显示哪处:筛选点名的那方(点了 Codex 就先看 Codex 那份),+/// 否则最近改过的那份+fn default_install(skill: &Skill, nav: &SkillNav) -> usize {+ skill+ .installs+ .iter()+ .position(|i| install_matches(i, nav))+ .unwrap_or(skill.newest)+}++/// 归属的显示名:共享目录叫 Shared(译),agent 是产品名(不译)+fn owner_label(owner: SkillOwner) -> &'static str {+ match owner {+ SkillOwner::Shared => t("Shared"),+ SkillOwner::Agent(agent) => agent.display_name(),+ }+}++/// 归属的图标:agent 是品牌图(原色),共享目录是 layers 线条图标+fn owner_icon(owner: SkillOwner, size: Pixels, dark: bool) -> AnyElement {+ match owner {+ SkillOwner::Shared => icon("icons/layers.svg")+ .with_size(size)+ .flex_shrink_0()+ .into_any_element(),+ SkillOwner::Agent(agent) => img(agent.brand_icon(dark))+ .size(size)+ .flex_shrink_0()+ .into_any_element(),+ }+}++/// 一处安装的层级文案:用户级 / 项目名 / 插件名+fn scope_label(scope: &SkillScope) -> String {+ match scope {+ SkillScope::User => t("User").to_string(),+ SkillScope::Project { root } => core_skills::project_name(root),+ SkillScope::Plugin { .. } => crate::tf!("Plugin {}", scope.plugin_name().unwrap_or("")),+ }+}++impl Workbench {+ /// 进 Skills 页(`show_page`):筛选从"全部"开始、回顶部,先拿上次的结果马上画,再重扫+ /// 一次——装了新 skill 进页就看得到。会话扫描的事件不触发重扫(skill 与会话无关)+ pub(super) fn enter_skills(&mut self, cx: &mut Context<Self>) {+ self.skills.nav = SkillNav::All;+ self.apply_skill_rows(true, cx);+ self.start_skill_scan(None, cx);+ }++ /// roster 换代(location 增删、停用):skill 目录从它推,页开着就重扫;没开着下次进页本来+ /// 就会扫+ pub(super) fn rescan_open_skills(&mut self, cx: &mut Context<Self>) {+ if self.page == Page::Skills {+ self.start_skill_scan(None, cx);+ }+ }++ /// 侧栏导航行的唯一写入点:不重扫,按已有结果重新筛、回顶部+ fn set_skill_scope(&mut self, nav: SkillNav, cx: &mut Context<Self>) {+ self.skills.nav = nav;+ self.apply_skill_rows(true, cx);+ }++ /// 侧栏 Starred 式的行:点当前项回到 All,否则切到它+ fn toggle_skill_scope(&mut self, nav: SkillNav, cx: &mut Context<Self>) {+ let next = if self.skills.nav == nav {+ SkillNav::All+ } else {+ nav+ };+ self.set_skill_scope(next, cx);+ }++ /// 页头的 Refresh:只重扫 skill(各刷各的,与 Memory 页同规矩),跑完弹 "Skills refreshed"+ fn refresh_skills(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ self.start_skill_scan(+ Some((+ window.window_handle(),+ Notification::success(t("Skills refreshed")),+ )),+ cx,+ );+ }++ /// 后台扫一遍:roster 的本地实例 + 已索引的本地项目根。新的一轮覆盖旧任务(旧结果丢弃)+ fn start_skill_scan(+ &mut self,+ done: Option<(gpui::AnyWindowHandle, Notification)>,+ cx: &mut Context<Self>,+ ) {+ self.skills.scanning = true;+ cx.notify();+ let adapters = self.adapters.clone();+ let store = self.store.clone();+ let cache = self.skills.cache.clone();+ let task = cx.background_spawn(async move {+ let projects = store.local_project_roots().unwrap_or_default();+ let scan = core_skills::scan(&adapters, &projects, &cache);+ let counts = scan.counts();+ (scan, counts)+ });+ self.skills.scan_task = Some(cx.spawn(async move |this, cx| {+ let (scan, counts) = task.await;+ this.update(cx, |this, cx| {+ let state = &mut this.skills;+ let selected = state.selected_skill().map(|s| s.name.clone());+ state.scanning = false;+ state.counts = counts;+ state.scan = scan;+ state.selected =+ selected.and_then(|name| state.scan.skills.iter().position(|s| s.name == name));+ this.apply_skill_rows(false, cx);+ })+ .ok();+ if let Some((window, note)) = done {+ cx.update_window(window, |_, window, cx| window.push_notification(note, cx))+ .ok();+ }+ }));+ }++ /// 按当前筛选重排列表;选中项还在就留着,否则落到第一个。重扫(`to_top` 为假)保滚动+ /// 位置、显示的那处按路径找回(文件变了重读正文);换筛选回顶部,显示的那处按新筛选+ /// 重新挑(点了 Codex 就换成 Codex 那份,Codex review 2026-10-15)+ fn apply_skill_rows(&mut self, to_top: bool, cx: &mut Context<Self>) {+ let state = &mut self.skills;+ let rows: Vec<usize> = state+ .scan+ .skills+ .iter()+ .enumerate()+ .filter(|(_, s)| skill_matches(s, &state.nav))+ .map(|(ix, _)| ix)+ .collect();+ replace_list_rows(&state.list, state.rows.len(), rows.len(), to_top);+ state.rows = rows;+ match state.selected.filter(|ix| state.rows.contains(ix)) {+ Some(ix) => {+ let shown_dir = state+ .loaded+ .as_ref()+ .filter(|_| !to_top)+ .map(|l| l.dir.clone());+ self.select_skill(ix, shown_dir, cx);+ }+ None => {+ state.selected = None;+ state.loaded = None;+ if let Some(&first) = state.rows.first() {+ self.select_skill(first, None, cx);+ }+ }+ }+ cx.notify();+ }++ /// 选中第 `ix` 个 skill;`shown_dir` 是想继续显示的那一处(重扫后按目录找回),找不到就按+ /// 筛选给默认的那处+ fn select_skill(&mut self, ix: usize, shown_dir: Option<PathBuf>, cx: &mut Context<Self>) {+ let Some(skill) = self.skills.scan.skills.get(ix) else {+ return;+ };+ let shown = shown_dir+ .and_then(|d| skill.installs.iter().position(|i| i.path == d))+ .unwrap_or_else(|| default_install(skill, &self.skills.nav));+ self.skills.selected = Some(ix);+ self.show_install(shown, cx);+ }++ /// 阅读面换到选中 skill 的第 `ix` 处安装:后台现读它的 SKILL.md(agent 刚改过也看得到)+ fn show_install(&mut self, ix: usize, cx: &mut Context<Self>) {+ let Some(install) = self+ .skills+ .selected_skill()+ .and_then(|s| s.installs.get(ix))+ else {+ return;+ };+ let dir = install.path.clone();+ let md = install.skill_md();+ let content_hash = install.content_hash;+ self.skills.shown = ix;+ let unchanged = self+ .skills+ .loaded+ .as_ref()+ .is_some_and(|l| !l.failed && l.dir == dir && l.content_hash == content_hash)+ && self.skills.body_task.is_none();+ if unchanged {+ cx.notify();+ return;+ }+ self.skills.loaded = None;+ let task = {+ cx.background_spawn(async move {+ match std::fs::read(&md) {+ Ok(bytes) => (+ SharedString::from(+ strip_frontmatter(&String::from_utf8_lossy(&bytes)).to_string(),+ ),+ false,+ ),+ Err(e) => (+ crate::tf!("Could not read this skill: {}", e.to_string()).into(),+ true,+ ),+ }+ })+ };+ self.skills.body_task = Some(cx.spawn(async move |this, cx| {+ let (body, failed) = task.await;+ this.update(cx, |this, cx| {+ this.skills.body_task = None;+ // 只写回仍在显示的那份,快速切换时旧任务不覆盖新选择+ let current = this+ .skills+ .selected_skill()+ .and_then(|s| s.installs.get(this.skills.shown));+ if current.is_some_and(|i| i.path == dir) {+ this.skills.loaded = Some(LoadedSkill {+ dir,+ content_hash,+ body,+ failed,+ });+ cx.notify();+ }+ })+ .ok();+ }));+ cx.notify();+ }++ /// 与 Memory 页同一形制:左列 = 列内页头 + 列表,右侧 = 阅读面+ pub(super) fn render_skills(&self, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme().clone();+ let count = self.skills.rows.len();+ let subtitle: SharedString = crate::tp!("{} skill", "{} skills", count).into();+ let column: AnyElement = if self.skills.rows.is_empty() {+ div().flex_1().into_any_element()+ } else {+ library_list(&self.skills.list, Self::render_skill_row, cx)+ };+ let pane: AnyElement = match self.skills.selected_skill() {+ Some(skill) => self.render_skill_reader(skill, cx),+ None => reader_placeholder(+ self.skills.scanning,+ "icons/puzzle.svg",+ t("No skills found"),+ t("Skills are folders with a SKILL.md that agents load when a task calls for them, like ~/.claude/skills or ~/.agents/skills. They show up here once installed."),+ cx,+ ),+ };+ h_flex()+ .flex_1()+ .min_w_0()+ .h_full()+ .child(+ v_flex()+ .w(self.columns().1)+ .h_full()+ .flex_shrink_0()+ .bg(theme.colors.list)+ .child(library_header(+ "skills-header",+ self.skill_context_title(),+ subtitle,+ SPACE_LG,+ Some(self.refresh_button(self.skills.scanning, Self::refresh_skills, cx)),+ cx,+ ))+ .children(self.render_skill_errors(&theme))+ .child(column),+ )+ .child(pane)+ .into_any_element()+ }++ /// 左列页头的标题 = 当前侧栏筛选+ fn skill_context_title(&self) -> String {+ match &self.skills.nav {+ SkillNav::All => t("All Skills").to_string(),+ SkillNav::Duplicated => t("Duplicated").to_string(),+ SkillNav::Owner(owner) => owner_label(*owner).to_string(),+ SkillNav::Project(root) => core_skills::project_name(root),+ }+ }++ /// 读不出来的位置(不是"没有"):列表上方**一行**——只有一处写出它的路径,多处写个数;+ /// 悬停看明细(最多 10 条)。逐条各占一行的话,几十个项目目录读不出就会把列表挤没+ /// (Codex review 2026-10-15)+ fn render_skill_errors(&self, theme: &gpui_component::Theme) -> Option<AnyElement> {+ const MAX_LISTED: usize = 10;+ let errors = &self.skills.scan.errors;+ let label = match errors.as_slice() {+ [] => return None,+ [only] => crate::tf!("Couldn't read {}", tilde_path(&only.path.to_string_lossy())),+ many => crate::tp!(+ "Couldn't read {} location",+ "Couldn't read {} locations",+ many.len()+ ),+ };+ let mut detail: Vec<String> = errors+ .iter()+ .take(MAX_LISTED)+ .map(|e| format!("{}: {}", tilde_path(&e.path.to_string_lossy()), e.message))+ .collect();+ if errors.len() > MAX_LISTED {+ detail.push(crate::tf!("and {} more", errors.len() - MAX_LISTED));+ }+ let detail: SharedString = detail.join("\n").into();+ Some(+ h_flex()+ .id("skill-errors")+ .flex_shrink_0()+ .mx(SPACE_LG)+ .mb(SPACE_XS)+ .gap(ICON_TEXT_GAP)+ .text_size(FONT_LABEL)+ .text_color(theme.muted_foreground)+ .child(+ icon("icons/triangle-alert.svg")+ .with_size(zpx(12.))+ .flex_shrink_0(),+ )+ .child(div().min_w_0().truncate().child(label))+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(detail.clone()).build(window, cx)+ })+ .into_any_element(),+ )+ }++ /// 一行(记忆行同一个行盒):Body 14 medium 名字;Caption 的说明一行(没有就不占);Label+ /// 的归属图标 + 拷贝 / 链接 / 分叉徽章 + 右对齐更新时间+ fn render_skill_row(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme().clone();+ let dark = theme.mode.is_dark();+ let Some((si, skill)) = self+ .skills+ .rows+ .get(ix)+ .and_then(|&si| Some((si, self.skills.scan.skills.get(si)?)))+ else {+ return div().into_any_element();+ };+ // 同一行最多五个归属图标,其余折成 +N(会话行的品牌图同一尺寸)+ const MAX_OWNER_ICONS: usize = 5;+ let more = skill.owners.len().saturating_sub(MAX_OWNER_ICONS);+ let description = skill.description();+ let meta = h_flex()+ .gap(ICON_TEXT_GAP)+ .text_size(FONT_LABEL)+ .text_color(theme.muted_foreground)+ .children(+ skill+ .owners+ .iter()+ .take(MAX_OWNER_ICONS)+ .map(|&o| owner_icon(o, zpx(15.), dark)),+ )+ .when(more > 0, |row| {+ row.child(div().flex_shrink_0().child(format!("+{more}")))+ })+ .children(skill_badges(skill, &theme))+ .child(div().flex_1())+ .child(library_row_time(("skill-time", ix), skill.updated_at()));+ let mut children = vec![library_row_title(("skill-title", ix), &skill.name, &theme)];+ if !description.is_empty() {+ children.push(+ div()+ .w_full()+ .min_w_0()+ .truncate()+ .text_size(FONT_CAPTION)+ .text_color(theme.muted_foreground)+ .child(description.to_string())+ .into_any_element(),+ );+ }+ children.push(meta.into_any_element());+ library_row(+ ("skill-row", ix),+ self.skills.selected == Some(si),+ cx.listener(move |this, _, _window, cx| this.select_skill(si, None, cx)),+ children,+ &theme,+ )+ }++ /// 阅读面:详情页同款头部(显示的那处安装:归属 + 层级、Reveal / Copy path、SKILL.md+ /// 路径与更新时间),正文先是位置表,再是去掉 frontmatter 的 SKILL.md+ fn render_skill_reader(&self, skill: &Skill, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme().clone();+ let dark = theme.mode.is_dark();+ let shown = self.skills.shown;+ let Some(install) = skill.installs.get(shown) else {+ return div().flex_1().into_any_element();+ };+ let md_path = install.skill_md().to_string_lossy().into_owned();+ let mut lead: Vec<AnyElement> = vec![+ owner_icon(install.owner, zpx(15.), dark),+ div()+ .flex_shrink_0()+ .child(owner_label(install.owner))+ .into_any_element(),+ ];+ match &install.scope {+ SkillScope::User => {}+ SkillScope::Project { root } => lead.push(project_badge(+ "skill-project",+ &root.to_string_lossy(),+ core_skills::project_name(root),+ &theme,+ )),+ SkillScope::Plugin { .. } => lead.push(+ badge(+ scope_label(&install.scope),+ theme.muted,+ theme.muted_foreground,+ )+ .into_any_element(),+ ),+ }+ let (actions, meta_rows) = file_reader_parts(&md_path, install.updated_at);+ let header = detail_header_frame(+ "skill-detail-header",+ lead,+ actions,+ skill.name.clone().into(),+ meta_rows,+ &theme,+ );+ let body: AnyElement = match &self.skills.loaded {+ Some(loaded) => markdown_body(+ format!("skill-{}", loaded.dir.to_string_lossy()).into(),+ loaded.body.clone(),+ "",+ // 相对链接(references/ 一类)按这一份 skill 的目录解析+ &install.path.to_string_lossy(),+ FONT_MSG_BODY,+ gpui::rems(0.5),+ dark,+ cx,+ )+ .into_any_element(),+ None => reader_loading(),+ };+ let content = v_flex()+ .w_full()+ .gap(SPACE_LG)+ .when(!install.description.is_empty(), |col| {+ col.child(+ div()+ .text_size(FONT_MSG_BODY)+ .text_color(theme.muted_foreground)+ .child(install.description.clone()),+ )+ })+ .child(self.render_skill_locations(skill, shown, cx))+ .child(div().h(px(1.)).w_full().bg(theme.border))+ .child(body);+ reader_pane("skill-reader", header, content, &theme)+ }++ /// 位置表:这个 skill 装在哪些地方。一行一处:归属图标 + 名字、层级、路径,右端标出+ /// 链接 / 与当前显示的那份是否一致 / 插件停用,再一个 Reveal;点一行就显示那份。+ /// 有多份拷贝时末尾一句 `npx skills add` 的提示(Wake 只看不装)+ fn render_skill_locations(&self, skill: &Skill, shown: usize, cx: &Context<Self>) -> Div {+ let theme = cx.theme();+ let dark = theme.mode.is_dark();+ let shown_hash = skill.installs.get(shown).map(|i| i.content_hash);+ let heading = crate::tp!("{} location", "{} locations", skill.installs.len());+ v_flex()+ .w_full()+ .gap(SPACE_XS)+ .child(+ div()+ .text_size(FONT_LABEL)+ .font_medium()+ .text_color(theme.muted_foreground)+ .child(heading),+ )+ .children(skill.installs.iter().enumerate().map(|(ix, install)| {+ let active = ix == shown;+ let path = install.path.to_string_lossy().into_owned();+ let full_path: SharedString = path.clone().into();+ let reveal = path.clone();+ let mut tags: Vec<AnyElement> = Vec::new();+ if install.linked {+ tags.push(+ badge(t("link"), theme.muted, theme.muted_foreground).into_any_element(),+ );+ }+ if let SkillScope::Plugin { enabled: false, .. } = install.scope {+ tags.push(+ badge(t("disabled"), theme.muted, theme.muted_foreground)+ .into_any_element(),+ );+ }+ if skill.differs && !active {+ tags.push(if Some(install.content_hash) == shown_hash {+ badge(t("same"), theme.muted, theme.muted_foreground).into_any_element()+ } else {+ outline_badge(t("different"), theme.muted_foreground).into_any_element()+ });+ }+ h_flex()+ .id(("skill-location", ix))+ .w_full()+ .min_w_0()+ .h(ROW_HEIGHT)+ .px(SPACE_SM)+ .gap(ICON_TEXT_GAP)+ .rounded(theme.radius)+ .text_size(FONT_CAPTION)+ .cursor_pointer()+ .when(active, |row| row.bg(theme.list_active))+ .when(!active, |row| row.hover(|style| style.bg(theme.list_hover)))+ .on_click(cx.listener(move |this, _, _window, cx| this.show_install(ix, cx)))+ .child(lead_slot(+ LEAD_BOX,+ owner_icon(install.owner, zpx(15.), dark),+ ))+ .child(+ div()+ .flex_shrink_0()+ .text_color(theme.foreground)+ .child(owner_label(install.owner)),+ )+ // 层级与路径都可收缩(窄栏、放大档位下行不能撑出去),层级最多 160+ .child(+ div()+ .min_w_0()+ .max_w(zpx(160.))+ .truncate()+ .text_color(theme.muted_foreground)+ .child(scope_label(&install.scope)),+ )+ .child(+ div()+ .id(("skill-location-path", ix))+ .flex_1()+ .min_w_0()+ .truncate()+ .text_color(theme.muted_foreground)+ .child(tilde_path(&path))+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(full_path.clone())+ .build(window, cx)+ }),+ )+ .child(+ h_flex()+ .flex_shrink_0()+ .gap(SPACE_XS)+ .text_size(FONT_LABEL)+ .children(tags),+ )+ .child(+ Button::new(("skill-location-reveal", ix))+ .ghost()+ .xsmall()+ .rounded(RADIUS_BUTTON)+ .icon(icon("icons/folder.svg").with_size(zpx(14.)))+ .tooltip(reveal_in_fm())+ .on_click(move |_, _, cx| {+ cx.stop_propagation();+ terminal::reveal_in_file_manager(&reveal);+ }),+ )+ }))+ .when(skill.copies > 1, |col| {+ col.child(+ div()+ .pt(SPACE_XS)+ .text_size(FONT_CAPTION)+ .text_color(theme.muted_foreground)+ .child(t(+ "To keep one copy and link it into several agents, use npx skills add.",+ )),+ )+ })+ }++ /// Skills 页的侧栏导航,替换会话导航:All Skills / Duplicated 两行,再接 Agents(共享+ /// 目录排第一)/ Projects 两组(`sidebar_groups`,与会话、记忆侧栏同一套组件与单选模型),+ /// 计数是 skill 数+ pub(super) fn render_skills_nav(&self, cx: &Context<Self>) -> AnyElement {+ let counts = &self.skills.counts;+ let nav = &self.skills.nav;+ let to_i64 = |n: usize| i64::try_from(n).unwrap_or(i64::MAX);+ let shared_row = counts+ .owners+ .iter()+ .find(|(o, _)| *o == SkillOwner::Shared)+ .map(|&(_, n)| {+ let active = *nav == SkillNav::Owner(SkillOwner::Shared);+ let path: SharedString = format!("~/{}", core_skills::SHARED_DIR).into();+ sidebar_row(+ "skills-shared",+ RowLead::Icon(icon("icons/layers.svg")),+ t("Shared"),+ Some(to_i64(n)),+ active,+ RowLevel::Sub,+ cx.listener(|this, _, _window, cx| {+ this.toggle_skill_scope(SkillNav::Owner(SkillOwner::Shared), cx);+ }),+ cx,+ )+ .tooltip(move |window, cx| {+ gpui_component::tooltip::Tooltip::new(path.clone()).build(window, cx)+ })+ .into_any_element()+ });+ v_flex()+ .flex_1()+ .min_h_0()+ .child(+ v_flex()+ .flex_shrink_0()+ .px(SIDEBAR_EDGE)+ .pb(SPACE_XS)+ .gap(SPACE_XS)+ .child(sidebar_row(+ "skills-all",+ RowLead::Icon(icon("icons/puzzle.svg")),+ t("All Skills"),+ Some(to_i64(counts.total)),+ *nav == SkillNav::All,+ RowLevel::Primary,+ cx.listener(|this, _, _window, cx| {+ this.set_skill_scope(SkillNav::All, cx);+ }),+ cx,+ ))+ // 会话侧栏 Starred 的同位:再点一次回到全部,计数为零不挂徽章+ .child(sidebar_row(+ "skills-duplicated",+ RowLead::Icon(icon("icons/copy.svg")),+ t("Duplicated"),+ (counts.duplicated > 0).then(|| to_i64(counts.duplicated)),+ *nav == SkillNav::Duplicated,+ RowLevel::Primary,+ cx.listener(|this, _, _window, cx| {+ this.toggle_skill_scope(SkillNav::Duplicated, cx);+ }),+ cx,+ )),+ )+ .child(self.sidebar_groups(+ "skills-sidebar-scroll",+ shared_row,+ counts.owners.iter().filter_map(|&(owner, n)| match owner {+ SkillOwner::Agent(agent) => {+ Some((agent, to_i64(n), *nav == SkillNav::Owner(owner)))+ }+ SkillOwner::Shared => None,+ }),+ counts.projects.iter().map(|(root, n)| {+ let path = root.to_string_lossy().into_owned();+ let label: SharedString = core_skills::project_name(root).into();+ let active = matches!(nav, SkillNav::Project(sel) if sel == root);+ (path, label, to_i64(*n), active)+ }),+ |this, next, cx| {+ this.set_skill_scope(+ next.map_or(SkillNav::All, |a| SkillNav::Owner(SkillOwner::Agent(a))),+ cx,+ )+ },+ |this, next, cx| {+ this.set_skill_scope(+ next.map_or(SkillNav::All, |p| SkillNav::Project(PathBuf::from(p))),+ cx,+ )+ },+ cx,+ ))+ .into_any_element()+ }+}++/// 列表行的徽章:插件自带、几份拷贝(两份及以上)、有链接、内容分叉。插件自带的只挂徽章、+/// 不单设侧栏入口——插件是一个包(skill 之外还有命令、子 agent、钩子、MCP),在 Skills 页的+/// 侧栏放 "Plugins" 读起来像插件是 skill 的一种(用户 2026-10-23 定)+fn skill_badges(skill: &Skill, theme: &gpui_component::Theme) -> Vec<AnyElement> {+ let mut out = Vec::with_capacity(4);+ // 比灰胶囊亮一档、又不和别的徽章撞色(用户 2026-10-23):专用的紫,淡底 + 同色字+ if skill.plugin {+ let color = crate::theme::plugin_badge_color(theme.mode.is_dark());+ out.push(badge(t("plugin"), color.opacity(0.14), color).into_any_element());+ }+ if skill.copies > 1 {+ out.push(+ badge(+ crate::tp!("{} copy", "{} copies", skill.copies),+ theme.muted,+ theme.muted_foreground,+ )+ .into_any_element(),+ );+ }+ if skill.linked {+ out.push(badge(t("linked"), theme.muted, theme.muted_foreground).into_any_element());+ }+ if skill.differs {+ out.push(outline_badge(t("differs"), theme.muted_foreground).into_any_element());+ }+ out+}