Skip to content

armgit / Wake

Public Imported from GitHub
0

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

Rust

feat: add local session cleanup (#36)

Corey Chiucebefb964d4d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8617361..f22062e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -49,6 +49,12 @@ jobs:
- name: Test wake-core
run: cargo test -p wake-core
+ # Exercise the real OS trash only with uniquely named synthetic fixtures.
+ # Normal local test runs do not touch the system trash.
+ - name: Test system trash round trip
+ if: runner.os == 'Linux' || runner.os == 'Windows'
+ run: cargo test -p wake-core --lib cleanup::tests::system_trash_cleanup_round_trip -- --ignored --exact
+
# UI crate 内不启动窗口的纯逻辑单测;联网测试标为 ignored
- name: Test app logic
run: cargo test -p wake
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 72436dd..5cc44ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## [0.7.0] — Unreleased
+
+- New: clean up local session files from the sidebar. Filter creation and update dates separately, select multiple agents and projects, and sort by age, activity or disk usage. Unavailable sessions stay visible with an explanation; starred and pinned sessions can be excluded through filters.
+- New: preview sessions in the existing reader, review the complete session tree and source files, then move selected files to the system trash. Cleanup rechecks file identity and ownership before deletion and records partial failures in history.
+- New: cleanup history shows affected sessions and original file locations. Restore files through the system trash, then use Check to verify and reindex them. New cleanup records verify file contents, including sidecars; space is freed only after files are removed from the trash.
+- Update: cleanup uses the app's existing page, filter, selection and button styles, with agent icons and Simplified Chinese translations. Windows uses actual disk allocation for sparse and compressed files and explains locations that cannot safely use the Recycle Bin.
+- Fix: Claude Code sessions containing `atis-latch` or `bridge-session` metadata parse correctly. Concurrent cleanup previews and library readers no longer leave sessions loading.
+
## [0.6.7] — 2026-09-15
- New: Cursor's IDE chats — the Chat / Composer panel — are indexed from Cursor's own database next to the CLI transcripts, so chats Wake never showed before are listed and searchable like any other session; a chat that also has a full transcript keeps being read from the transcript, so it stays under the right project. Older chats that Cursor stored without a workspace show under Unknown project (#32, thanks @junqingyongyuanbusi)
diff --git a/Cargo.lock b/Cargo.lock
index 1f3757e..3fe1277 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7776,6 +7776,7 @@ dependencies = [
"rusqlite",
"serde",
"serde_json",
+ "sha2 0.10.9",
"tempfile",
"trash",
"walkdir",
diff --git a/DESIGN.md b/DESIGN.md
index a814bd3..7f5d04e 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -128,12 +128,13 @@ macOS 不设置横跨三栏的自定义 header。主窗口透明标题栏高 44p
- 侧栏顶端按红绿灯、`Wake` 标题和搜索框的可见边界做光学对齐:标题容器上留 4px、下留 16px。窗口控制区和品牌行各高 44px,合计 88px。
- 顶部是唯一的全文搜索入口,文案 "Search sessions",右侧显示 `⌘K`;Search/All Sessions/Starred 固定不随滚动。
- 搜索行必须有防溢出结构:标签文字 `flex_1 + min_w_0 + truncate`,图标与 `⌘K` 徽标显式 `flex_shrink_0`。裸文字子元素的最小宽度被内容锁死,侧栏一窄就会把右侧元素挤出边界裁掉。
+- 侧栏搜索入口与 Filter 来源搜索共用 `ui::search_field_frame`:32px 高、8px 主题圆角、secondary 填充、10px 水平留白、13px 搜索图标和 Caption 字阶。局部搜索在同一外壳内放无外观的 Input,不叠加默认细边框输入框。
- **行分两级**(侧栏纵向层级的来源,不得拉平):主导航 All Sessions/Starred 32px 行高 + Body 14;分组展开项(agent/项目)26px 行高 + Caption 12 + 整行右移 `SUB_INDENT` 12px 表达从属。
- **每行必须有行首元素**,由 `RowLead` 枚举强制(`Icon` 或 `Brand` 两态,无 `None`):主导航用 Lucide 单线图标,agent 行用品牌 PNG,项目行用 `folder.svg`。槽位定宽 `LEAD_BOX` 管右侧文字起点统一,槽内居中管中轴对齐。
- 线条图标比实心品牌图视觉轻,同档里给小一号:分组项 Lucide 14 / 品牌图 18,主导航 Lucide 15。
- 行内容 = 行首元素 + 标题 + 计数;计数一律 Label 档 muted。
- 组头 "Agents"/"Projects" 用 Body 档常规字重 + muted 色(与主导航同字号同字重,仅靠颜色和"无行首图标"区分——加粗会让组头压过它统辖的行),带 13px chevron 可折叠。
-- 底部工具条常驻,总高 44px(含顶部 1px hairline),按钮靠右排列(次要操作区:透明底、hover 才出色,不与导航行选中态抢注意力)——依次为 chart-column "Insights"、齿轮 "Settings"、refresh。Insights 页打开时其图标以 primary 点亮,是工具条里唯一有激活态的按钮。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。
+- 底部工具条常驻,总高 44px(含顶部 1px hairline),按钮靠右排列(次要操作区:透明底、hover 才出色,不与导航行选中态抢注意力)——依次为 chart-column "Insights"、brush-cleaning "Clean Up Sessions"、齿轮 "Settings"、refresh。Insights 或清理页打开时,对应图标以 primary 点亮。Settings 同时进入 Wake 菜单并绑定 `⌘,`(其他平台 `Ctrl+,`),保持单例窗口。
- Settings 默认 820×600,采用 180px 窄侧栏 + 内容页结构,固定为 General / Locations / Remote hosts / Connect / Data / Updates / About 七项(Connect 为 0.5.0 新增,插在 Remote hosts 与 Data 之间——两页都是"把 Wake 接到外部"的集成面,Data 之后是纯本地信息);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 本地存储位置、会话数与磁盘占用并提供文件管理器入口,不重复放刷新或清库动作;常规 Refresh 的唯一入口仍是主侧栏底部。Locations 页按 AgentId 声明序以 agent 分组,品牌名只在组头出现一次;本机有数据的组优先,未检测到的 agent 默认收进可展开区。每条路径以路径为主信息、会话数/不可用状态为 muted 副信息,最右为逐路径开关;停用时只降低文字层级,开关与菜单保持完整对比度。行本身不承担编辑,`…` 菜单集中 Edit / Show in Finder / 自定义 Remove。顶部操作为低强调的 Add location,Restore defaults 收进页级 `…` 菜单且无偏离时禁用。添加/编辑仍复用 agent 下拉 + 可手输路径 + 目录选择表单;关闭 location 后保留配置、停止扫描/监听并从会话与搜索结果排除,重新开启即增量扫回;纯路径管理不做内容校验。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 字体的 `~/…` 路径,右侧 Copy path,不放"Ready"状态行,只在找不到二进制时给一行 danger 文案;「MCP clients」卡三行(Claude Code / Codex / Cursor),17px 品牌图标领行、客户端名为主信息、用法提示为 muted 副信息、右侧是 ghost 的 Show/Hide 切换(chevron 图标 + 文案,muted 前景,用户 2026-09-08 追加)加 Copy command / Copy config;代码块**默认收起**,展开后出现在该行下方、左缘对齐到文字轴(行内边距 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 路径 + Copy path;wake-cli 那张在 Copy path **左侧**多一个 Copy command,复制「把它放进 PATH」的那行命令——右侧留给两张卡同名的 Copy path,纵向才对得齐;deb/tar 已装进 `…/bin` 或 Windows 上没有可粘命令时这个按钮不出现;Skill 是 `npx skills add …` + Copy command),区块标题为「Agents」时看不出这块特指 MCP,故改名 MCP clients 与上方 MCP server 成对。**说明性 caption 一律不放**——那正是"设置窗里塞 README"的复发形态;Setup guide 链接改挂在区块标题右端,规则是**每个面的第一个区块挂自己的文档**:MCP server → docs/mcp.md,Command line → docs/cli.md(MCP clients 与 Skill 分属这两个面的第二块,不重复挂)。四块之后整页**超过一屏、需要滚动**——2026-09-08 那条"一屏放下"的约束随第三、四个区块作废,滚动容器本来就在(`flex_1().min_h_0().overflow_y_scroll()`),卡片记得 `flex_shrink_0` 否则会被压扁。复制反馈是按钮原地变 "Copied"(check 图标)1.6s 后复原,**不弹通知**——gpui-component 的 toast 在窗口失活或被悬停时暂停自动关闭,在 Settings 从属窗里经常就挂着不走(用户 2026-09-08 反馈),且主界面的 Copy Session ID / Copy code 本来就不弹;页面只展示不代写别家配置。
- 工具条内的**状态行"常态沉默"**:仅刷新中或监听不可用时出现在按钮行上方;文案须可 truncate,窄侧栏放不下长句(故为 "Live updates off" 而非带操作建议的整句)。
- 手动 Refresh 始终后台运行;进度复用侧栏状态行,完成后发通知,不用模态框阻断浏览、搜索或阅读。
@@ -172,7 +173,7 @@ macOS 不设置横跨三栏的自定义 header。主窗口透明标题栏高 44p
详情加载失败不得退化为空白阅读面:没有匹配 adapter 时明确说明 agent 与会话路径不匹配,转录解析失败时保留底层错误链;两者共用居中的错误态,并提供“在文件管理器中显示”动作定位原始会话文件。异步解析结果只允许写回仍然选中的同一会话,避免快速切换时旧任务覆盖新详情。
-对话框标题一律 Heading 16 semibold:组件内建 `.title()` 不设字号(实渲窗口默认 14px),必须显式补 `text_size(FONT_HEADING)`。破坏性确认的主按钮点名动作并用 danger 形态("Move to Trash",Windows 上经 trash_copy! 平台文案为 "Move to Recycle Bin",不留裸 "OK");表单弹窗内控件同档取齐(输入框与下拉/浏览钮同高,次级动作行才允许 small)。输入框聚焦态只把边框染成 ring 色,不画框外的聚焦环(theme.rs 关掉了 `focus_ring`):组件的环是元素框外 2px 的绝对定位子元素,弹窗内容层与滚动列表都会裁掉它,染色边框不占空间也不会残缺。
+对话框标题一律 Heading 16 semibold:组件内建 `.title()` 不设字号(实渲窗口默认 14px),必须显式补 `text_size(FONT_HEADING)`。破坏性确认的主按钮点名动作并用 danger 形态(常规删除使用平台化的 Move to Trash/Move to Recycle Bin;清理入口使用 Delete,确认框按用户指定使用 Confirm;正文明确恢复方式及空间回收条件);表单弹窗内控件同档取齐(输入框与下拉/浏览钮同高,次级动作行才允许 small)。输入框聚焦态只把边框染成 ring 色,不画框外的聚焦环(theme.rs 关掉了 `focus_ring`):组件的环是元素框外 2px 的绝对定位子元素,弹窗内容层与滚动列表都会裁掉它,染色边框不占空间也不会残缺。
### 对话阅读面
@@ -220,6 +221,24 @@ emoji 不再承担界面或正文结构图标职责。
- Agents / Projects / Models 三个榜单同构:24px 条形行 = 行首(品牌图 15px 原色 / folder 图标 / 无)+ 名称列定宽 truncate + 6px 圆头轨道条(`muted` 轨、`primary` 填充,按组内峰值归一)+ 右对齐 Label 计数。三个组头都挂 ‹ › 切换度量,循环序与概览行一致:Sessions / Tokens / Prompts;**当前档位名(首字母大写的裸名词)显示在两键中间**——64px 定宽居中,Caption muted,按钮位置不随文本跳动;榜单组头因此为单行(标题与按钮组居中对齐),分布图组头保留 caption 双行、按钮中间无标签(其标题本身就是档位名)。每个榜单各自记忆档位,行按当前度量降序重排后取 top-N(Agents 全量、Projects/Models 各 6;截断在排序之后,换度量不漏项);Tokens 档只列报过用量的组、值用 K/M 缩写,组内无人报 token 时该档不进循环。
- 空态沿用详情空态形制("No activity yet" + "Refresh sessions to see your activity here.");加载用居中 Spinner,已有数据时静默换新不闪烁。
+### 本机会话清理
+
+- Filter 使用 16px 内边距,标题、日期区、来源区与操作栏共用左缘。标题右侧提供「仅显示可清理」多选选项,默认关闭并随其他条件一起记忆、清除。Clear(悬停提示 Clear filters)与 Done 集中到底栏,均为 32px 高、6px 圆角,复用 Settings 的普通/主要按钮样式;常态实色填充,前者 secondary、后者 primary,Done 最小宽度 80px。
+
+- 清理入口 Delete 与最终 Confirm 按钮统一使用现有 danger 样式;取消选择、筛选与排序仍使用各自的普通控件。检查阶段显示已检查数 / 总数并可取消,执行阶段显示已处理数 / 总数并允许完成当前会话后停止。取消检查不产生确认框或清理记录。
+- 确认框标题用 Delete this session?/Delete N sessions?,顶部仅接一行 Caption/muted 的 Local files · About X 体积摘要,随后直接显示会话列表。两条短说明固定在列表下方、按钮上方,与列表共用左缘:先说明可从废纸篓恢复及释放空间的条件,再说明原工具可能无法继续会话。说明区顶部的分隔线固定,清单内仅在会话之间分隔;说明与按钮间距 16px,不随文件列表滚动。移除重复的长段落和清理页中额外的 Codex 说明;文件名使用 12px muted 等宽文字,过长时省略,悬停可见完整路径。只有一项时使用单数文案。结果区把未开始、已移动、需要处理分开,未开始不标红;没有移动文件时不提示空间待回收。
+
+- 入口在侧栏底部工具条,顺序为 Insights / Clean Up Sessions / Settings / Refresh;清理使用 14px `brush-cleaning` 图标,打开时以 primary 表达激活态。
+- 清理页保留侧栏,主区与 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 可显式开启「仅显示可清理」。所有计数均为当前筛选范围;全选只选择可清理会话。
+- 列表头保持 44px 单行:全选(可清理数量)、筛选结果总数、无法清理数量;可清理体积放在未勾选时的底部摘要,不重复状态词。两种会话共用 `cleanup/rows.rs` 的标题/来源两行布局,无法清理原因使用 Label 字阶接在项目徽章后;完整项目名与原因支持悬停查看。项目徽章上限 128px,品牌图保持 15px。每行占 64px,内部高亮面为 60px,上下各留 2px,避免相邻选中行连成大色块。日期列 112px,仅显示当前排序日期(按文件大小排序时,只有创建时间启用则显示创建日期,否则显示更新日期),悬停显示创建和更新的完整时间。体积列 88px,数字右对齐;移除常驻操作列,将空间留给会话标题;不加体积条。行高亮留 16px 外边距,内容内缩 8px,沿用 8px 主题圆角;勾选使用 `list_active`,悬停使用 `list_hover`。
+- 清理记录直接打开主区历史列表,不用时间戳菜单;列表显示会话标题、品牌、时间、会话数、结果与体积。单次详情与列表形成明确返回层级,标题左侧返回按钮和 Esc 均可返回。标题复用 88px 页面头,正文遵循 Insights 的居中 720px 内容宽度;记录列表复用 Settings 的圆角分组面板,88px 行内以品牌、标题和时间为主,体积与轻量状态标记靠右。详情顶部展示结果摘要,下面的会话面板用 40px 整行控件展开文件位置;已还原条目不再显示废纸篓或恢复操作,部分完成、中断与待核对单独表达。纯浏览保留候选列表筛选、勾选和滚动,执行或恢复后回候选页才重新核对文件状态。
+- 清理页、Filter、结果页和确认框的文字操作统一复用 `ui::action_button`:32px 高、左右 12px、6px 圆角,与 Settings 主操作共享尺寸;内部文字、图标和图文间距统一使用 Settings 常规按钮的 Small 档,避免仅改外框却遗留默认字号。页面主操作同排等高;历史页返回按钮为 32px,文件位置使用 40px 整行展开控件,顶部 Filter/Sort/Refresh 沿用 All Sessions 的图标按钮尺寸。
+- 底部与侧栏工具条统一为 44px(包含顶部 hairline),摘要使用 11px Label 字阶。未选择时显示可清理体积及清理记录,无可清理项时显示对应引导;选择后原位显示数量、体积和单词按钮 `Clear`/`Delete`;按钮使用纯文字,未选择时显示纯文字 `History`;悬停分别说明取消全选和移到系统废纸篓。点击会话标题在主区域进入现有正文阅读器,保留侧栏,不使用弹窗或第二列;阅读器来源行增加返回按钮,也可按 Esc 返回,勾选、筛选和列表位置保持。进入清理页不自动加载正文。源文件明细归入清理确认框,每个会话显示品牌、标题、项目、数量与体积,文件数量按钮按需展开文件名、父目录和大小;长路径截断并支持悬停。结果页共用页面标题与 24px 留白;空状态复用现有 `empty_state_card`。
+- `Delete` 先检查所选会话,再打开最终确认清单,只有确认框里的 Confirm 才执行。检查逐项汇总失败原因;部分失败时明确显示将跳过的项及真正将清理的数量与体积,全部失败时展示原因与刷新入口,不提供删除按钮,不用底部裸错误取代确认流程。
+- Sort 与 All Sessions 使用相同菜单结构、180px 最小宽度和右对齐锚点:上半部分为更新时间、创建时间、文件大小,分隔线下方为降序、升序。字段和方向各自勾选,tooltip 沿用“排序:字段 · 方向”。切换字段保留当前方向;切换字段或方向都保留已选会话,改变筛选条件才清空勾选。
+
## 图标、形状与层次
- UI chrome 只使用内嵌 Lucide 单线 SVG,不使用 Unicode 或 emoji 图标;Agent 身份用内嵌品牌 PNG,经 `img()` 渲染并**保持原色**(不得用 `text_color` 着色,选中态也不变色)。
@@ -254,3 +273,25 @@ scripts/build_and_run.sh --verify
```
视觉验收至少覆盖:空态、选中会话、详情阅读、更多菜单、`⌘K` 搜索,以及系统浅色和深色模式。
+
+
+### 清理操作按钮规范(2026-09-16)
+
+- 清理页文字操作统一采用纯文字按钮,包括 Clear、Delete、History、Filter 的 Clear/Done、失败后的 Refresh,以及历史恢复操作。
+- 确认框为 Cancel/Confirm,保留 danger 层级;底部说明也使用纯文字,与列表左缘对齐。
+- 顶部筛选/排序/刷新、返回和文件展开的功能图标,以及 Agent 品牌图标保留。
+- Settings 更新动作沿用 refresh-cw/download 图标。
+
+### 清理来源多选(2026-09-16)
+
+- Filter 的 Agents、Projects 都支持多选,组内取并集、组间以及日期条件取交集;未选任何值表示该组不限。
+- 多选统一采用原 Agents 的轻量选项块:28px 行高、12px 文字,选中时浅蓝底色与右侧勾号,未选中时使用浅中性底色和细边框;不使用方形复选框。Agents、Projects 与 Exclude 共用这一组件。Agent 图标保留在名称左侧,点击已选项可取消;标题显示整组选中数量,来源分组标题右侧的搜索只影响候选项显示。
+- 不另设 All 选项,取消该组所有勾选即恢复不限;Clear 清除全部筛选。筛选在关闭面板、重新进入清理页和重启后保留,旧单选设置自动迁移。
+- 页面摘要单项显示名称,多项显示分组数量;已选但数据暂时不可用的来源仍可取消。
+
+### 清理记录的手动恢复(2026-09-16)
+
+- 不提供应用内自动 Restore。macOS 的废纸篓权限会阻止目录读取,临时测试文件通过不能代表用户已有目录可访问。
+- 顶部结果卡片在说明下方放置纯文字 Trash/Check,保持 32px 高、12px 水平留白和 6px 圆角。说明明确“在废纸篓选择放回原处,再点击检查”;两按钮与说明左对齐,不用页面底栏。
+- Trash 打开系统废纸篓;Check 只验证原位置的会话及关联文件,完整后清除本次删除标记、重新扫描。Check 不读废纸篓、不移动文件。文件尚未放回时给普通操作提示,不显示权限栈或声称已恢复。
+- 旧自动恢复的权限错误不把已经成功的删除显示成部分完成,改用手动恢复说明;其他实际文件或索引错误仍展示。全部重新收录后隐藏操作。
diff --git a/crates/wake-core/Cargo.toml b/crates/wake-core/Cargo.toml
index 881e103..00df417 100644
--- a/crates/wake-core/Cargo.toml
+++ b/crates/wake-core/Cargo.toml
@@ -15,6 +15,7 @@ notify.workspace = true
chrono.workspace = true
zstd.workspace = true
base64.workspace = true
+sha2 = "0.10"
# Linux 废纸篓:freedesktop Trash spec 的纯库实现
# (macOS 走 Finder/osascript,行为已验证不动)
@@ -33,15 +34,20 @@ trash = { version = "5", default-features = false, features = ["coinit_multithre
# codepage 解码 stdin,非 ASCII 命令必乱,不走子进程管道)、进程创建旗标
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
+ "Win32_Storage_FileSystem",
"Win32_System_DataExchange",
"Win32_System_Memory",
"Win32_System_Threading",
+ "Win32_System_WindowsProgramming",
"Win32_UI_WindowsAndMessaging",
] }
[dev-dependencies]
tempfile = "3"
+[target.'cfg(windows)'.dev-dependencies]
+windows-sys = { version = "0.61", features = ["Win32_System_IO", "Win32_System_Ioctl"] }
+
[[bin]]
name = "scan"
path = "src/bin/scan.rs"
diff --git a/crates/wake-core/src/adapters/claude.rs b/crates/wake-core/src/adapters/claude.rs
index 1ab3f2e..35e2dcf 100644
--- a/crates/wake-core/src/adapters/claude.rs
+++ b/crates/wake-core/src/adapters/claude.rs
@@ -20,6 +20,9 @@ const KNOWN_SKIP_TYPES: &[&str] = &[
"frame-link",
"attachment",
"summary",
+ "atis-latch",
+ // Bridge connection bookkeeping, not transcript content.
+ "bridge-session",
];
pub struct ClaudeAdapter {
@@ -609,6 +612,10 @@ impl AgentAdapter for ClaudeAdapter {
v
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
// 选中 `~/.claude` 形态(含 projects/)或直接选中 projects 目录都认
let root = if dir.join("projects").is_dir() {
diff --git a/crates/wake-core/src/adapters/codebuddy.rs b/crates/wake-core/src/adapters/codebuddy.rs
index 8b20c2e..24c4013 100644
--- a/crates/wake-core/src/adapters/codebuddy.rs
+++ b/crates/wake-core/src/adapters/codebuddy.rs
@@ -479,6 +479,10 @@ impl AgentAdapter for CodebuddyAdapter {
paths
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
let root = if dir.join("projects").is_dir() {
dir.join("projects")
diff --git a/crates/wake-core/src/adapters/codex.rs b/crates/wake-core/src/adapters/codex.rs
index c6e7119..b8400b4 100644
--- a/crates/wake-core/src/adapters/codex.rs
+++ b/crates/wake-core/src/adapters/codex.rs
@@ -905,6 +905,10 @@ impl AgentAdapter for CodexAdapter {
})
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
// dir 视作 CODEX_HOME 形态;归一化未上提的孤立数据目录按**目录名**
// 保留角色:空的独立 sessions 目录日后落盘的 rollout 要能被发现,
diff --git a/crates/wake-core/src/adapters/cursor.rs b/crates/wake-core/src/adapters/cursor.rs
index cc2f98e..8a8c535 100644
--- a/crates/wake-core/src/adapters/cursor.rs
+++ b/crates/wake-core/src/adapters/cursor.rs
@@ -485,6 +485,10 @@ impl AgentAdapter for CursorAdapter {
Ok(parse_cursor_jsonl(&file, true)?.messages)
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
// 选中 `~/.cursor` 形态(含 projects/)或直接选中 projects 目录都认
let root = if dir.join("projects").is_dir() {
diff --git a/crates/wake-core/src/adapters/dsh.rs b/crates/wake-core/src/adapters/dsh.rs
index 4674ab3..e61a760 100644
--- a/crates/wake-core/src/adapters/dsh.rs
+++ b/crates/wake-core/src/adapters/dsh.rs
@@ -521,6 +521,10 @@ impl AgentAdapter for DshAdapter {
}
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
let root = if dir.join("sessions").is_dir() {
dir.join("sessions")
diff --git a/crates/wake-core/src/adapters/gemini.rs b/crates/wake-core/src/adapters/gemini.rs
index c489ada..b3bb780 100644
--- a/crates/wake-core/src/adapters/gemini.rs
+++ b/crates/wake-core/src/adapters/gemini.rs
@@ -272,6 +272,10 @@ impl AgentAdapter for GeminiAdapter {
})
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
// `~/.gemini` 形态(含 tmp/)则 projects.json 在其顶层;直接选中 tmp
// 形态则上一层找。侧档必须相对 dir 派生,落回默认家就会拿错 cwd 映射
diff --git a/crates/wake-core/src/adapters/grok.rs b/crates/wake-core/src/adapters/grok.rs
index ecd7fcb..d4dcbe8 100644
--- a/crates/wake-core/src/adapters/grok.rs
+++ b/crates/wake-core/src/adapters/grok.rs
@@ -478,6 +478,10 @@ impl AgentAdapter for GrokAdapter {
})
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
Box::new(Self::from_custom_dir(dir))
}
diff --git a/crates/wake-core/src/adapters/kimi.rs b/crates/wake-core/src/adapters/kimi.rs
index a93d960..15a3ca6 100644
--- a/crates/wake-core/src/adapters/kimi.rs
+++ b/crates/wake-core/src/adapters/kimi.rs
@@ -290,6 +290,10 @@ impl AgentAdapter for KimiAdapter {
})
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
// `~/.kimi-code` 形态(含 sessions/)则 index 在其顶层;直接选中
// sessions 则上一层找。index 相对 dir 派生,落回默认家会拿错 cwd 映射
diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rs
index a5428f4..e63b718 100644
--- a/crates/wake-core/src/adapters/mod.rs
+++ b/crates/wake-core/src/adapters/mod.rs
@@ -91,6 +91,11 @@ pub trait AgentAdapter: Send + Sync {
fn session_paths(&self, meta: &SessionMeta) -> Vec<String> {
vec![meta.file_path.clone()]
}
+ /// Explicit opt-in for independently owned local files. Database and remote
+ /// adapters must leave this unsupported; cleanup also verifies containment.
+ fn cleanup_paths(&self, _meta: &SessionMeta) -> Option<Vec<String>> {
+ None
+ }
/// 一轮扫描开始前刷新 adapter 的跨会话快照。默认 adapter 没有这类状态。
fn begin_scan(&self) {}
/// 此 adapter 是否负责维护会话父子关系。单独的能力位用于区分“当前没有
diff --git a/crates/wake-core/src/adapters/openclaw.rs b/crates/wake-core/src/adapters/openclaw.rs
index 9027d52..9e927b4 100644
--- a/crates/wake-core/src/adapters/openclaw.rs
+++ b/crates/wake-core/src/adapters/openclaw.rs
@@ -656,6 +656,10 @@ impl AgentAdapter for OpenclawAdapter {
})
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
// 选中状态目录(~/.openclaw)或 agents 目录本身都认;目录尚不存在时按
// 名字判:叫 agents 即是根,否则视作状态目录(远程挂载点 `.openclaw/agents`
diff --git a/crates/wake-core/src/adapters/pi.rs b/crates/wake-core/src/adapters/pi.rs
index 5a0082b..604fae1 100644
--- a/crates/wake-core/src/adapters/pi.rs
+++ b/crates/wake-core/src/adapters/pi.rs
@@ -201,6 +201,10 @@ impl AgentAdapter for PiAdapter {
})
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
// 选中 `~/.pi`/`~/.omp` 家目录形态或 sessions 目录本身都认。
// pi 与 omp 布局全同:实例保持自己的 agent,探测时两家都会命中同一目录,
diff --git a/crates/wake-core/src/adapters/qoder.rs b/crates/wake-core/src/adapters/qoder.rs
index 3356661..7f52c91 100644
--- a/crates/wake-core/src/adapters/qoder.rs
+++ b/crates/wake-core/src/adapters/qoder.rs
@@ -683,6 +683,10 @@ impl AgentAdapter for QoderAdapter {
paths
}
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
let root = if dir.join("projects").is_dir() {
dir.join("projects")
diff --git a/crates/wake-core/src/cleanup.rs b/crates/wake-core/src/cleanup.rs
new file mode 100644
index 0000000..b99783b
--- /dev/null
+++ b/crates/wake-core/src/cleanup.rs
@@ -0,0 +1,2348 @@
+//! Local session cleanup: immutable review plans, conservative ownership checks,
+//! per-target Trash results and a durable journal. No source database writes.
+use crate::{
+ adapters::{adapter_for, AgentAdapter},
+ db::Store,
+ models::*,
+ services::terminal,
+};
+use anyhow::{bail, ensure, Context, Result};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::{
+ collections::{BTreeSet, HashMap, HashSet},
+ io::Read,
+ path::{Path, PathBuf},
+ sync::atomic::{AtomicBool, Ordering},
+ time::UNIX_EPOCH,
+};
+
+pub const DAY: i64 = 86_400_000;
+pub const PREFS: &str = "cleanup.options.v1";
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum CleanupSort {
+ Created,
+ Updated,
+ #[default]
+ Size,
+}
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum TimeField {
+ Created,
+ #[default]
+ Updated,
+}
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(from = "SavedCleanupOptions")]
+pub struct CleanupOptions {
+ pub sort: CleanupSort,
+ /// Old preferences used ascending dates and descending size, with no direction field.
+ pub ascending: Option<bool>,
+ pub created_days: i64,
+ pub updated_days: i64,
+ /// Empty source sets mean unrestricted; values within each set are ORed.
+ pub agents: BTreeSet<AgentId>,
+ pub projects: BTreeSet<String>,
+ pub exclude_starred: bool,
+ pub exclude_pinned: bool,
+ pub only_cleanable: bool,
+}
+impl Default for CleanupOptions {
+ fn default() -> Self {
+ Self {
+ sort: CleanupSort::Size,
+ ascending: None,
+ created_days: 0,
+ updated_days: 30,
+ agents: BTreeSet::new(),
+ projects: BTreeSet::new(),
+ exclude_starred: false,
+ exclude_pinned: false,
+ only_cleanable: false,
+ }
+ }
+}
+
+/// The original single-date filter is read only for migration. New preferences
+/// always save both dates, including explicit zeroes for unrestricted dates.
+#[derive(Default, Deserialize)]
+#[serde(default)]
+struct SavedCleanupOptions {
+ sort: CleanupSort,
+ ascending: Option<bool>,
+ created_days: Option<i64>,
+ updated_days: Option<i64>,
+ time: TimeField,
+ days: Option<i64>,
+ agents: Option<BTreeSet<AgentId>>,
+ projects: Option<BTreeSet<String>>,
+ // Legacy single-source preferences, used only when the new sets are absent.
+ agent: Option<AgentId>,
+ project: Option<String>,
+ exclude_starred: bool,
+ exclude_pinned: bool,
+ only_cleanable: bool,
+}
+impl From<SavedCleanupOptions> for CleanupOptions {
+ fn from(saved: SavedCleanupOptions) -> Self {
+ let age = |days, fallback| {
+ if [0, 30, 90, 180, 365].contains(&days) {
+ days
+ } else {
+ fallback
+ }
+ };
+ let (created_days, updated_days) =
+ if saved.created_days.is_some() || saved.updated_days.is_some() {
+ (
+ age(saved.created_days.unwrap_or(0), 0),
+ age(saved.updated_days.unwrap_or(0), 30),
+ )
+ } else {
+ let days = age(saved.days.unwrap_or(30), 30);
+ match saved.time {
+ TimeField::Created => (days, 0),
+ TimeField::Updated => (0, days),
+ }
+ };
+ Self {
+ sort: saved.sort,
+ ascending: saved.ascending,
+ created_days,
+ updated_days,
+ agents: saved
+ .agents
+ .unwrap_or_else(|| saved.agent.into_iter().collect()),
+ projects: saved
+ .projects
+ .unwrap_or_else(|| saved.project.into_iter().collect()),
+ exclude_starred: saved.exclude_starred,
+ exclude_pinned: saved.exclude_pinned,
+ only_cleanable: saved.only_cleanable,
+ }
+ }
+}
+impl CleanupOptions {
+ pub fn sort_ascending(&self) -> bool {
+ self.ascending.unwrap_or(self.sort != CleanupSort::Size)
+ }
+ pub fn matches(&self, item: &CleanupCandidate, now: i64) -> bool {
+ self.matches_metadata(&item.root, item.updated_at, &item.sessions, now)
+ }
+ fn matches_metadata(
+ &self,
+ root: &SessionMeta,
+ updated_at: i64,
+ sessions: &[SessionMeta],
+ now: i64,
+ ) -> bool {
+ let older_than = |ts, days| days == 0 || (ts > 0 && ts <= now - days * DAY);
+ older_than(root.created_at, self.created_days)
+ && older_than(updated_at, self.updated_days)
+ && (!self.exclude_starred || !sessions.iter().any(|s| s.favorite))
+ && (!self.exclude_pinned || !sessions.iter().any(|s| s.pinned))
+ && (self.agents.is_empty() || self.agents.contains(&root.agent))
+ && (self.projects.is_empty() || self.projects.contains(&root.project_path))
+ }
+ pub fn matches_entry(&self, item: &CleanupEntry, now: i64) -> bool {
+ match item {
+ CleanupEntry::Available(candidate) => self.matches(candidate, now),
+ CleanupEntry::Unavailable(item) => {
+ !self.only_cleanable
+ && self.matches_metadata(&item.session, item.updated_at(), &item.sessions, now)
+ }
+ }
+ }
+ pub fn sort_entries(&self, items: &mut [CleanupEntry]) {
+ let value = |entry: &CleanupEntry| match self.sort {
+ CleanupSort::Created => {
+ (entry.session().created_at > 0).then_some(i128::from(entry.session().created_at))
+ }
+ CleanupSort::Updated => {
+ (entry.updated_at() > 0).then_some(i128::from(entry.updated_at()))
+ }
+ CleanupSort::Size => entry.candidate().map(|c| i128::from(c.bytes)),
+ };
+ items.sort_by(|a, b| {
+ let order = match (value(a), value(b)) {
+ (Some(a), Some(b)) if self.sort_ascending() => a.cmp(&b),
+ (Some(a), Some(b)) => b.cmp(&a),
+ // Unknown values remain last in either direction.
+ (Some(_), None) => std::cmp::Ordering::Less,
+ (None, Some(_)) => std::cmp::Ordering::Greater,
+ (None, None) => std::cmp::Ordering::Equal,
+ };
+ order.then_with(|| a.session().key.cmp(&b.session().key))
+ });
+ }
+ pub fn sort(&self, items: &mut [CleanupCandidate]) {
+ items.sort_by(|a, b| {
+ let order = match self.sort {
+ CleanupSort::Created => a.root.created_at.cmp(&b.root.created_at),
+ CleanupSort::Updated => a.updated_at.cmp(&b.updated_at),
+ CleanupSort::Size => a.bytes.cmp(&b.bytes),
+ };
+ (if self.sort_ascending() {
+ order
+ } else {
+ order.reverse()
+ })
+ .then_with(|| a.root.key.cmp(&b.root.key))
+ });
+ }
+}
+
+pub struct IndexedSession {
+ pub meta: SessionMeta,
+ pub parent: String,
+}
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct FileStamp {
+ pub path: PathBuf,
+ pub bytes: u64,
+ pub logical_bytes: u64,
+ pub modified: u64,
+ pub identity: (u64, u64),
+ /// Upper half of Windows' 128-bit file ID (needed on ReFS).
+ #[serde(default)]
+ pub identity_high: u64,
+ pub directory: bool,
+}
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CleanupTarget {
+ pub path: PathBuf,
+ pub files: Vec<FileStamp>,
+}
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct CleanupCandidate {
+ pub root: SessionMeta,
+ pub sessions: Vec<SessionMeta>,
+ pub targets: Vec<CleanupTarget>,
+ pub updated_at: i64,
+ pub bytes: u64,
+ pub prompts: i64,
+ pub empty: bool,
+}
+impl CleanupCandidate {
+ pub fn has_starred(&self) -> bool {
+ self.sessions.iter().any(|s| s.favorite)
+ }
+ pub fn has_pinned(&self) -> bool {
+ self.sessions.iter().any(|s| s.pinned)
+ }
+}
+#[derive(Clone)]
+pub struct UnavailableSession {
+ pub session: SessionMeta,
+ /// Known tree members, used only for filtering and display.
+ pub sessions: Vec<SessionMeta>,
+ pub reason: String,
+}
+impl UnavailableSession {
+ pub fn updated_at(&self) -> i64 {
+ self.sessions
+ .iter()
+ .map(|s| s.updated_at)
+ .max()
+ .unwrap_or(self.session.updated_at)
+ }
+}
+#[derive(Clone)]
+pub enum CleanupEntry {
+ Available(CleanupCandidate),
+ Unavailable(UnavailableSession),
+}
+impl CleanupEntry {
+ pub fn session(&self) -> &SessionMeta {
+ match self {
+ Self::Available(c) => &c.root,
+ Self::Unavailable(item) => &item.session,
+ }
+ }
+ pub fn updated_at(&self) -> i64 {
+ match self {
+ Self::Available(c) => c.updated_at,
+ Self::Unavailable(item) => item.updated_at(),
+ }
+ }
+ pub fn candidate(&self) -> Option<&CleanupCandidate> {
+ match self {
+ Self::Available(c) => Some(c),
+ Self::Unavailable(_) => None,
+ }
+ }
+}
+#[derive(Default)]
+pub struct CleanupInventory {
+ pub candidates: Vec<CleanupCandidate>,
+ pub unavailable: Vec<UnavailableSession>,
+}
+
+#[derive(Default)]
+pub struct CleanupReview {
+ pub ready: Vec<CleanupCandidate>,
+ pub skipped: Vec<UnavailableSession>,
+}
+
+/// Check every selected tree without moving files. A failed tree does not hide
+/// the review of the remaining selection; the UI must present both groups.
+/// Cancellation discards the entire review, so a partial check cannot be confirmed.
+pub fn review(
+ store: &Store,
+ adapters: &[Box<dyn AgentAdapter>],
+ chosen: Vec<CleanupCandidate>,
+ cancel: &AtomicBool,
+ mut progress: impl FnMut(usize),
+) -> Option<CleanupReview> {
+ let mut result = CleanupReview::default();
+ for (i, candidate) in chosen.into_iter().enumerate() {
+ if cancel.load(Ordering::Relaxed) {
+ return None;
+ }
+ match revalidate(store, adapters, &candidate) {
+ Ok(()) => result.ready.push(candidate),
+ Err(error) => result.skipped.push(UnavailableSession {
+ session: candidate.root,
+ sessions: candidate.sessions,
+ reason: error.to_string(),
+ }),
+ }
+ progress(i + 1);
+ }
+ (!cancel.load(Ordering::Relaxed)).then_some(result)
+}
+
+fn stamp(path: &Path) -> Result<FileStamp> {
+ #[cfg(windows)]
+ let crate::services::windows_fs::FileSnapshot {
+ metadata: m,
+ bytes,
+ identity,
+ identity_high,
+ } = crate::services::windows_fs::snapshot(path)?;
+ #[cfg(not(windows))]
+ let m = std::fs::symlink_metadata(path)?;
+ ensure!(
+ !m.file_type().is_symlink(),
+ "Symbolic links are not supported"
+ );
+ ensure!(m.is_file() || m.is_dir(), "Not a regular file or directory");
+ let modified = u64::try_from(m.modified()?.duration_since(UNIX_EPOCH)?.as_nanos())?;
+ #[cfg(unix)]
+ let (bytes, identity) = {
+ use std::os::unix::fs::MetadataExt;
+ ensure!(
+ !m.is_file() || m.nlink() == 1,
+ "Shared hard links are not supported"
+ );
+ (
+ if m.is_file() { m.blocks() * 512 } else { 0 },
+ (m.dev(), m.ino()),
+ )
+ };
+ Ok(FileStamp {
+ path: path.to_path_buf(),
+ bytes,
+ logical_bytes: m.len(),
+ modified,
+ identity,
+ #[cfg(windows)]
+ identity_high,
+ #[cfg(not(windows))]
+ identity_high: 0,
+ directory: m.is_dir(),
+ })
+}
+fn target(path: &Path) -> Result<CleanupTarget> {
+ // Canonical equality rejects links in ancestors as well as the target itself.
+ ensure!(
+ path.is_absolute() && same_canonical_path(path, &path.canonicalize()?),
+ "Source path contains links or is not absolute"
+ );
+ let mut files = vec![];
+ for entry in walkdir::WalkDir::new(path).follow_links(false) {
+ files.push(stamp(entry?.path())?);
+ }
+ files.sort_by(|a, b| a.path.cmp(&b.path));
+ Ok(CleanupTarget {
+ path: path.to_path_buf(),
+ files,
+ })
+}
+
+#[cfg(not(windows))]
+fn same_canonical_path(path: &Path, canonical: &Path) -> bool {
+ path == canonical
+}
+
+#[cfg(windows)]
+fn same_canonical_path(path: &Path, canonical: &Path) -> bool {
+ use std::path::{Component, Prefix};
+ fn normalize(prefix: Prefix<'_>) -> Prefix<'_> {
+ match prefix {
+ Prefix::VerbatimDisk(drive) => Prefix::Disk(drive),
+ Prefix::VerbatimUNC(server, share) => Prefix::UNC(server, share),
+ other => other,
+ }
+ }
+ // Windows canonicalize adds an extended-length prefix even without links.
+ // Only normalize that prefix; a different ancestor or filename still fails.
+ let mut original = path.components();
+ let mut resolved = canonical.components();
+ match (original.next(), resolved.next()) {
+ (Some(Component::Prefix(a)), Some(Component::Prefix(b))) => {
+ normalize(a.kind()) == normalize(b.kind()) && original.eq(resolved)
+ }
+ _ => false,
+ }
+}
+fn supported_adapter<'a>(
+ adapters: &'a [Box<dyn AgentAdapter>],
+ meta: &SessionMeta,
+) -> Result<&'a dyn AgentAdapter> {
+ ensure!(meta.host.is_empty(), "Remote sessions are read-only");
+ let a = adapter_for(adapters, meta.agent, &meta.file_path).context("Source is not enabled")?;
+ ensure!(a.host().is_empty(), "Remote mirrors are read-only");
+ ensure!(
+ a.cleanup_paths(meta).is_some(),
+ "This source does not support independent file cleanup"
+ );
+ let p = Path::new(&meta.file_path);
+ ensure!(
+ a.data_roots()
+ .iter()
+ .any(|r| r.is_dir() && p.starts_with(r) && p != r),
+ "Source is outside the enabled location"
+ );
+ Ok(a)
+}
+/// File ownership and metadata needed for deletion, without display statistics.
+struct CleanupPlan {
+ sessions: Vec<SessionMeta>,
+ targets: Vec<CleanupTarget>,
+}
+
+fn build_plan(
+ root: &IndexedSession,
+ index: &[IndexedSession],
+ adapters: &[Box<dyn AgentAdapter>],
+ ownership: &HashMap<String, Vec<PathBuf>>,
+) -> Result<CleanupPlan> {
+ let mut members = vec![root];
+ let mut keys = HashSet::from([root.meta.key.as_str()]);
+ let mut cursor = 0;
+ while cursor < members.len() {
+ let parent = members[cursor].meta.key.clone();
+ for child in index.iter().filter(|s| s.parent == parent) {
+ ensure!(
+ keys.insert(child.meta.key.as_str()),
+ "Session tree contains a cycle"
+ );
+ members.push(child);
+ }
+ cursor += 1;
+ }
+ let mut paths = vec![];
+ for item in &members {
+ let m = &item.meta;
+ terminal::validate_trash_path(Path::new(&m.file_path))?;
+ let a = supported_adapter(adapters, m)?;
+ let owned = a
+ .cleanup_paths(m)
+ .context("This source does not support independent file cleanup")?;
+ ensure!(!owned.is_empty(), "No independently owned files");
+ for p in owned {
+ let p = PathBuf::from(p);
+ terminal::validate_trash_path(&p)?;
+ ensure!(
+ a.data_roots().iter().any(|r| p.starts_with(r) && p != *r),
+ "Cleanup target is outside the source location"
+ );
+ ensure!(
+ std::fs::symlink_metadata(&p).is_ok(),
+ "Source file is missing"
+ );
+ paths.push(p);
+ }
+ }
+ paths.sort();
+ paths.dedup();
+ let mut roots: Vec<PathBuf> = vec![];
+ for path in paths {
+ if !roots.iter().any(|p| path.starts_with(p)) {
+ roots.push(path);
+ }
+ }
+ for other in index.iter().filter(|s| !keys.contains(s.meta.key.as_str())) {
+ ensure!(
+ !roots
+ .iter()
+ .any(|p| Path::new(&other.meta.file_path).starts_with(p)),
+ "Target also contains another session"
+ );
+ // Sessions outside the current filter still own all of their sidecars.
+ if let Some(paths) = ownership.get(&other.meta.key) {
+ ensure!(
+ !paths.iter().any(|shared| roots
+ .iter()
+ .any(|p| shared.starts_with(p) || p.starts_with(shared))),
+ "Shared cleanup target"
+ );
+ }
+ }
+ let targets = roots
+ .iter()
+ .map(|p| target(p))
+ .collect::<Result<Vec<_>>>()?;
+ Ok(CleanupPlan {
+ sessions: members.iter().map(|s| s.meta.clone()).collect(),
+ targets,
+ })
+}
+
+fn inventory_candidate(
+ root: &SessionMeta,
+ plan: CleanupPlan,
+ prompt_counts: &HashMap<String, i64>,
+ adapters: &[Box<dyn AgentAdapter>],
+) -> Result<CleanupCandidate> {
+ let prompts = plan
+ .sessions
+ .iter()
+ .map(|s| prompt_counts.get(&s.key).copied().unwrap_or(0))
+ .sum();
+ let updated_at = plan
+ .sessions
+ .iter()
+ .map(|s| s.updated_at)
+ .max()
+ .unwrap_or(root.updated_at);
+ let bytes = plan
+ .targets
+ .iter()
+ .flat_map(|t| &t.files)
+ .map(|f| f.bytes)
+ .sum();
+ let mut empty = plan.sessions.iter().all(|s| s.message_count == 0) && prompts == 0;
+ // Empty is a positive parse result, never a missing/failed index entry.
+ if empty {
+ for s in &plan.sessions {
+ let p =
+ supported_adapter(adapters, s)?.parse_transcript(&SessionFileRef::from_meta(s))?;
+ empty &= p.unknown_line_count == 0 && p.mainline.is_empty() && p.sidechains.is_empty();
+ }
+ }
+ Ok(CleanupCandidate {
+ root: root.clone(),
+ sessions: plan.sessions,
+ targets: plan.targets,
+ updated_at,
+ bytes,
+ prompts,
+ empty,
+ })
+}
+
+pub fn inventory(store: &Store, adapters: &[Box<dyn AgentAdapter>]) -> Result<CleanupInventory> {
+ let index = store.cleanup_index()?;
+ let prompt_counts = store.cleanup_prompt_counts()?;
+ let ownership = ownership(&index, adapters);
+ let mut result = CleanupInventory::default();
+ for root in index.iter().filter(|s| s.parent.is_empty()) {
+ match build_plan(root, &index, adapters, &ownership)
+ .and_then(|plan| inventory_candidate(&root.meta, plan, &prompt_counts, adapters))
+ {
+ Ok(c) => result.candidates.push(c),
+ Err(e) => result.unavailable.push(UnavailableSession {
+ session: root.meta.clone(),
+ sessions: known_tree(root, &index),
+ reason: e.to_string(),
+ }),
+ }
+ }
+ // Shared sidecars must not be counted twice or moved with an unselected tree.
+ let mut paths: Vec<_> = result
+ .candidates
+ .iter()
+ .enumerate()
+ .flat_map(|(i, c)| c.targets.iter().map(move |t| (&t.path, i)))
+ .collect();
+ paths.sort();
+ let mut shared = HashSet::new();
+ for (i, (a, ai)) in paths.iter().enumerate() {
+ for (b, bi) in paths.iter().skip(i + 1) {
+ if !b.starts_with(a) {
+ break;
+ }
+ if ai != bi {
+ shared.insert(*ai);
+ shared.insert(*bi);
+ }
+ }
+ }
+ result.candidates = result
+ .candidates
+ .into_iter()
+ .enumerate()
+ .filter_map(|(i, c)| {
+ if shared.contains(&i) {
+ result.unavailable.push(UnavailableSession {
+ session: c.root,
+ sessions: c.sessions,
+ reason: "Shared cleanup target".into(),
+ });
+ None
+ } else {
+ Some(c)
+ }
+ })
+ .collect();
+ for orphan in index
+ .iter()
+ .filter(|s| !s.parent.is_empty() && !index.iter().any(|p| p.meta.key == s.parent))
+ {
+ result.unavailable.push(UnavailableSession {
+ session: orphan.meta.clone(),
+ sessions: known_tree(orphan, &index),
+ reason: "Parent session is unavailable".into(),
+ });
+ }
+ Ok(result)
+}
+
+// Availability failures still need tree-aware dates and flags. This traversal
+// tolerates malformed relationships without granting cleanup ownership.
+fn known_tree(root: &IndexedSession, index: &[IndexedSession]) -> Vec<SessionMeta> {
+ let mut members = vec![root.meta.clone()];
+ let mut keys = HashSet::from([root.meta.key.as_str()]);
+ let mut cursor = 0;
+ while cursor < members.len() {
+ let parent = members[cursor].key.clone();
+ for child in index.iter().filter(|s| s.parent == parent) {
+ if keys.insert(child.meta.key.as_str()) {
+ members.push(child.meta.clone());
+ }
+ }
+ cursor += 1;
+ }
+ members
+}
+
+fn ownership(
+ index: &[IndexedSession],
+ adapters: &[Box<dyn AgentAdapter>],
+) -> HashMap<String, Vec<PathBuf>> {
+ index
+ .iter()
+ .filter(|s| s.meta.host.is_empty())
+ .filter_map(|s| {
+ adapter_for(adapters, s.meta.agent, &s.meta.file_path).map(|a| {
+ (
+ s.meta.key.clone(),
+ a.session_paths(&s.meta)
+ .into_iter()
+ .map(PathBuf::from)
+ .collect(),
+ )
+ })
+ })
+ .collect()
+}
+
+pub fn revalidate(
+ store: &Store,
+ adapters: &[Box<dyn AgentAdapter>],
+ old: &CleanupCandidate,
+) -> Result<()> {
+ let index = store.cleanup_index()?;
+ let root = index
+ .iter()
+ .find(|s| s.meta.key == old.root.key)
+ .context("Session no longer exists")?;
+ ensure!(root.parent.is_empty(), "Session tree changed");
+ let new = build_plan(root, &index, adapters, &ownership(&index, adapters))?;
+ let signature = |sessions: &[SessionMeta]| {
+ let mut values = sessions
+ .iter()
+ .map(|m| {
+ (
+ m.key.clone(),
+ m.file_path.clone(),
+ m.updated_at,
+ m.created_at,
+ m.favorite,
+ m.pinned,
+ )
+ })
+ .collect::<Vec<_>>();
+ values.sort();
+ values
+ };
+ ensure!(
+ signature(&new.sessions) == signature(&old.sessions) && new.targets == old.targets,
+ "Session or files changed since review; refresh and review again"
+ );
+ for meta in &new.sessions {
+ let parsed =
+ supported_adapter(adapters, meta)?.parse_session(&SessionFileRef::from_meta(meta))?;
+ ensure!(
+ parsed.unknown_line_count == 0,
+ "Session has unrecognized content"
+ );
+ }
+ // Parsing can take time; stat again before allowing any move.
+ for old in &new.targets {
+ ensure!(target(&old.path)? == *old, "Source changed while checking");
+ }
+ let index = store.cleanup_index()?;
+ let root = index
+ .iter()
+ .find(|s| s.meta.key == old.root.key)
+ .context("Session no longer exists")?;
+ ensure!(root.parent.is_empty(), "Session tree changed");
+ let checked = build_plan(root, &index, adapters, &ownership(&index, adapters))?;
+ ensure!(
+ signature(&checked.sessions) == signature(&old.sessions) && checked.targets == old.targets,
+ "Session or files changed since review; refresh and review again"
+ );
+ Ok(())
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
+pub enum TargetStatus {
+ Pending,
+ Moving,
+ Moved,
+ Failed(String),
+}
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct CleanupRecord {
+ pub candidate: CleanupCandidate,
+ pub targets: Vec<TargetStatus>,
+ /// Kept when reading old journals; file recovery is handled by the OS.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub trash_paths: Vec<Option<PathBuf>>,
+ /// Captured and journaled before any move, independent of inode/allocation
+ /// changes caused by the OS restoring a file across volumes.
+ #[serde(default)]
+ pub content_hashes: HashMap<PathBuf, String>,
+ pub indexed: bool,
+ pub restored: bool,
+ pub error: Option<String>,
+}
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct CleanupBatch {
+ pub id: String,
+ pub stamp: i64,
+ pub records: Vec<CleanupRecord>,
+ pub finished: bool,
+}
+impl CleanupBatch {
+ pub fn new(candidates: Vec<CleanupCandidate>, stamp: i64) -> Self {
+ let nonce = std::time::SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos();
+ Self {
+ id: format!("{stamp}-{nonce}"),
+ stamp,
+ records: candidates
+ .into_iter()
+ .map(|candidate| CleanupRecord {
+ targets: vec![TargetStatus::Pending; candidate.targets.len()],
+ trash_paths: Vec::new(),
+ content_hashes: HashMap::new(),
+ candidate,
+ indexed: false,
+ restored: false,
+ error: None,
+ })
+ .collect(),
+ finished: false,
+ }
+ }
+ pub fn save(&self, store: &Store) -> Result<()> {
+ store.pref_set(
+ &format!("cleanup.batch.{}", self.id),
+ &serde_json::to_string(self)?,
+ )
+ }
+}
+pub fn history(store: &Store) -> Result<Vec<CleanupBatch>> {
+ store
+ .cleanup_journals()?
+ .iter()
+ .map(|s| serde_json::from_str(s).map_err(Into::into))
+ .collect()
+}
+
+/// Retry only the index transaction for targets durably recorded as moved.
+/// An interrupted `Moving` status remains ambiguous and requires user review.
+pub fn retry_index_updates(store: &Store, batch: &mut CleanupBatch) -> Result<usize> {
+ let mut count = 0;
+ for i in 0..batch.records.len() {
+ let r = &batch.records[i];
+ if r.indexed || r.restored || !r.targets.iter().all(|s| *s == TargetStatus::Moved) {
+ continue;
+ }
+ let result = (|| {
+ for target in &r.candidate.targets {
+ ensure!(
+ !target.path.try_exists()?,
+ "Source is present again; review it before updating the index"
+ );
+ }
+ store.complete_cleanup(&r.candidate.sessions, batch.stamp)
+ })();
+ match result {
+ Ok(()) => {
+ batch.records[i].indexed = true;
+ batch.records[i].error = None;
+ count += 1;
+ }
+ Err(e) => batch.records[i].error = Some(e.to_string()),
+ }
+ batch.save(store)?;
+ }
+ Ok(count)
+}
+pub fn execute(
+ store: &Store,
+ adapters: &[Box<dyn AgentAdapter>],
+ batch: &mut CleanupBatch,
+ cancel: &AtomicBool,
+ progress: impl Fn(usize),
+) -> Result<()> {
+ execute_with(store, adapters, batch, cancel, progress, |path| {
+ terminal::trash_paths(&[path.to_string_lossy().into_owned()])
+ })
+}
+fn execute_with(
+ store: &Store,
+ adapters: &[Box<dyn AgentAdapter>],
+ batch: &mut CleanupBatch,
+ cancel: &AtomicBool,
+ progress: impl Fn(usize),
+ trash: impl Fn(&Path) -> Result<()>,
+) -> Result<()> {
+ batch.save(store)?;
+ for i in 0..batch.records.len() {
+ if cancel.load(Ordering::Relaxed) {
+ break;
+ }
+ let plan = batch.records[i].candidate.clone();
+ if let Err(e) = revalidate(store, adapters, &plan) {
+ batch.records[i].error = Some(e.to_string());
+ batch.save(store)?;
+ progress(i + 1);
+ continue;
+ }
+ match content_hashes(&plan.targets).and_then(|hashes| {
+ // Hashing large trees can take time; recheck source ownership and
+ // user metadata as well as the file snapshots before moving.
+ revalidate(store, adapters, &plan)?;
+ Ok(hashes)
+ }) {
+ Ok(hashes) => batch.records[i].content_hashes = hashes,
+ Err(e) => {
+ batch.records[i].error = Some(e.to_string());
+ batch.save(store)?;
+ progress(i + 1);
+ continue;
+ }
+ }
+ // Recovery evidence must be durable before the first move.
+ batch.save(store)?;
+ for (j, expected) in plan.targets.iter().enumerate() {
+ batch.records[i].targets[j] = TargetStatus::Moving;
+ batch.save(store)?;
+ let result = (|| {
+ ensure!(
+ target(&expected.path)? == *expected,
+ "Source changed before move"
+ );
+ trash(&expected.path)?;
+ ensure!(
+ !expected.path.try_exists()?,
+ "Source is still present after move"
+ );
+ Ok(())
+ })();
+ match result {
+ Ok(()) => batch.records[i].targets[j] = TargetStatus::Moved,
+ Err(e) => {
+ batch.records[i].targets[j] = TargetStatus::Failed(format!("{e:#}"));
+ batch.records[i].error = Some(format!("{e:#}"));
+ batch.save(store)?;
+ break;
+ }
+ }
+ batch.save(store)?;
+ }
+ if batch.records[i]
+ .targets
+ .iter()
+ .all(|s| *s == TargetStatus::Moved)
+ {
+ match store.complete_cleanup(&plan.sessions, batch.stamp) {
+ Ok(()) => batch.records[i].indexed = true,
+ Err(e) => batch.records[i].error = Some(e.to_string()),
+ }
+ }
+ batch.save(store)?;
+ progress(i + 1);
+ }
+ batch.finished = true;
+ batch.save(store)
+}
+
+fn hash_file(path: &Path) -> Result<String> {
+ let mut file = std::fs::File::open(path)?;
+ let mut digest = Sha256::new();
+ let mut buffer = [0; 64 * 1024];
+ loop {
+ let read = file.read(&mut buffer)?;
+ if read == 0 {
+ break;
+ }
+ digest.update(&buffer[..read]);
+ }
+ Ok(format!("{:x}", digest.finalize()))
+}
+
+fn content_hashes(targets: &[CleanupTarget]) -> Result<HashMap<PathBuf, String>> {
+ let mut hashes = HashMap::new();
+ for expected in targets {
+ ensure!(
+ target(&expected.path)? == *expected,
+ "Source changed while checking"
+ );
+ for file in expected.files.iter().filter(|file| !file.directory) {
+ hashes.insert(file.path.clone(), hash_file(&file.path)?);
+ }
+ ensure!(
+ target(&expected.path)? == *expected,
+ "Source changed while checking"
+ );
+ }
+ Ok(hashes)
+}
+
+fn verify_restored_files(record: &CleanupRecord) -> Result<Vec<CleanupTarget>> {
+ let mut checked = Vec::new();
+ for expected in &record.candidate.targets {
+ for file in &expected.files {
+ ensure!(
+ file.path.try_exists()?,
+ "Restored files are still missing from their original locations."
+ );
+ }
+ // This also rejects replaced targets/ancestors that are now symlinks.
+ let current = target(&expected.path)?;
+ let files: HashMap<_, _> = current.files.iter().map(|f| (&f.path, f)).collect();
+ for old in &expected.files {
+ let file = files
+ .get(&old.path)
+ .context("Restored session could not be verified")?;
+ ensure!(
+ file.directory == old.directory,
+ "Restored files do not match the deleted files"
+ );
+ if !old.directory {
+ ensure!(
+ file.logical_bytes == old.logical_bytes,
+ "Restored files do not match the deleted files"
+ );
+ if record.content_hashes.is_empty() {
+ // Legacy journals lack content evidence. Require matching
+ // type, length and modification time, plus session parsing.
+ ensure!(
+ file.modified == old.modified,
+ "Restored files do not match the deleted files"
+ );
+ } else {
+ ensure!(
+ record.content_hashes.get(&old.path) == Some(&hash_file(&old.path)?),
+ "Restored files do not match the deleted files"
+ );
+ }
+ }
+ }
+ ensure!(
+ target(&current.path)? == current,
+ "Restored files changed before verification"
+ );
+ checked.push(current);
+ }
+ Ok(checked)
+}
+
+/// Users restore source files using their OS first. Validate the full tree and
+/// remove only this batch's tombstones. The caller starts a normal rescan.
+pub fn restore(
+ store: &Store,
+ adapters: &[Box<dyn AgentAdapter>],
+ batch: &mut CleanupBatch,
+) -> Result<usize> {
+ let mut count = 0;
+ for i in 0..batch.records.len() {
+ if batch.records[i].restored || !batch.records[i].can_restore() {
+ continue;
+ }
+ let result = (|| {
+ let record = &batch.records[i];
+ store.validate_cleanup_restore(&record.candidate.sessions, batch.stamp)?;
+ let checked = verify_restored_files(record)?;
+ for meta in &record.candidate.sessions {
+ let parsed = supported_adapter(adapters, meta)?
+ .parse_session(&SessionFileRef::from_meta(meta))?;
+ ensure!(
+ parsed.unknown_line_count == 0 && parsed.meta.id == meta.id,
+ "Restored session could not be verified"
+ );
+ }
+ for expected in checked {
+ ensure!(
+ target(&expected.path)? == expected,
+ "Restored files changed before verification"
+ );
+ }
+ store.restore_cleanup(&record.candidate.sessions, batch.stamp)?;
+ Ok(())
+ })();
+ match result {
+ Ok(()) => {
+ batch.records[i].restored = true;
+ batch.records[i].error = None;
+ count += 1;
+ }
+ Err(e) => batch.records[i].error = Some(format!("{e:#}")),
+ }
+ batch.save(store)?;
+ }
+ if count == 0 {
+ bail!("No restored sessions found. Check the file locations below.");
+ }
+ Ok(count)
+}
+
+impl CleanupRecord {
+ pub fn can_restore(&self) -> bool {
+ !self.restored
+ && self.targets.iter().any(|s| {
+ matches!(
+ s,
+ TargetStatus::Moved | TargetStatus::Moving | TargetStatus::Failed(_)
+ )
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::{
+ cell::Cell,
+ fs::{self, File, FileTimes},
+ time::Duration,
+ };
+
+ struct FilesAdapter {
+ root: PathBuf,
+ supported: bool,
+ }
+ impl AgentAdapter for FilesAdapter {
+ fn agent(&self) -> AgentId {
+ AgentId::ClaudeCode
+ }
+ fn data_roots(&self) -> Vec<PathBuf> {
+ vec![self.root.clone()]
+ }
+ fn with_custom_root(&self, root: PathBuf) -> Box<dyn AgentAdapter> {
+ Box::new(Self {
+ root,
+ supported: self.supported,
+ })
+ }
+ fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {
+ Ok(vec![])
+ }
+ fn parse_session(&self, r: &SessionFileRef) -> Result<ParsedSession> {
+ let text = fs::read_to_string(&r.file_path)?;
+ Ok(ParsedSession {
+ meta: meta(&self.root, &r.native_id, 100),
+ units: vec![],
+ unknown_line_count: u32::from(text == "BAD"),
+ })
+ }
+ fn parse_transcript(&self, r: &SessionFileRef) -> Result<ParsedTranscript> {
+ let p = self.parse_session(r)?;
+ Ok(ParsedTranscript {
+ meta: p.meta,
+ mainline: vec![],
+ sidechains: vec![],
+ unknown_line_count: p.unknown_line_count,
+ })
+ }
+ fn session_paths(&self, m: &SessionMeta) -> Vec<String> {
+ let mut paths = vec![m.file_path.clone()];
+ let dir = self.root.join(&m.id);
+ if dir.exists() {
+ paths.push(dir.to_string_lossy().into_owned());
+ }
+ paths
+ }
+ fn cleanup_paths(&self, m: &SessionMeta) -> Option<Vec<String>> {
+ self.supported.then(|| self.session_paths(m))
+ }
+ }
+ fn now() -> i64 {
+ chrono::Utc::now().timestamp_millis()
+ }
+ fn meta(root: &Path, id: &str, age: i64) -> SessionMeta {
+ SessionMeta {
+ key: format!("claude-code:{id}"),
+ id: id.into(),
+ host: String::new(),
+ agent: AgentId::ClaudeCode,
+ title: id.into(),
+ project_path: "/synthetic/project".into(),
+ project_name: "project".into(),
+ file_path: root
+ .join(format!("{id}.jsonl"))
+ .to_string_lossy()
+ .into_owned(),
+ created_at: now() - 400 * DAY,
+ updated_at: now() - age * DAY,
+ message_count: 2,
+ size_bytes: 4,
+ git_branch: None,
+ model: None,
+ tokens_used: None,
+ archived: false,
+ source: None,
+ favorite: false,
+ pinned: false,
+ }
+ }
+ fn age(path: &Path) {
+ #[cfg(windows)]
+ let file = {
+ use std::os::windows::fs::OpenOptionsExt;
+ use windows_sys::Win32::Storage::FileSystem::{
+ FILE_FLAG_BACKUP_SEMANTICS, FILE_WRITE_ATTRIBUTES,
+ };
+ fs::OpenOptions::new()
+ .access_mode(FILE_WRITE_ATTRIBUTES)
+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
+ .open(path)
+ .unwrap()
+ };
+ #[cfg(not(windows))]
+ let file = File::open(path).unwrap();
+ file.set_times(
+ FileTimes::new()
+ .set_modified(UNIX_EPOCH + Duration::from_millis((now() - 100 * DAY) as u64)),
+ )
+ .unwrap();
+ }
+ fn setup() -> (
+ tempfile::TempDir,
+ Store,
+ Vec<Box<dyn AgentAdapter>>,
+ PathBuf,
+ ) {
+ let temp = tempfile::tempdir().unwrap();
+ let root = temp.path().canonicalize().unwrap().join("sessions");
+ fs::create_dir(&root).unwrap();
+ let store = Store::open(&temp.path().join("index.db")).unwrap();
+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(FilesAdapter {
+ root: root.clone(),
+ supported: true,
+ })];
+ (temp, store, adapters, root)
+ }
+ fn insert(store: &Store, root: &Path, id: &str, days: i64) -> SessionMeta {
+ let m = meta(root, id, days);
+ fs::write(&m.file_path, "test").unwrap();
+ age(Path::new(&m.file_path));
+ store
+ .write_session(
+ &m,
+ m.updated_at,
+ &[IndexUnit {
+ seq: 0,
+ sidechain_id: None,
+ role: Role::User,
+ timestamp: Some(m.updated_at),
+ text: "synthetic prompt".into(),
+ }],
+ )
+ .unwrap();
+ m
+ }
+ #[test]
+ fn unavailable_entries_follow_date_source_and_tree_flag_filters() {
+ let (_temp, store, adapters, root) = setup();
+ let parent = insert(&store, &root, "unavailable-parent", 180);
+ let child = insert(&store, &root, "unavailable-child", 60);
+ store
+ .replace_parent_links(
+ AgentId::ClaudeCode,
+ &[(child.key.clone(), parent.key.clone())],
+ )
+ .unwrap();
+ store
+ .set_user_data(&child.key, Some(true), Some(true))
+ .unwrap();
+ fs::remove_file(&parent.file_path).unwrap(); // Synthetic missing source.
+ let entry =
+ CleanupEntry::Unavailable(inventory(&store, &adapters).unwrap().unavailable.remove(0));
+ let mut options = CleanupOptions::default();
+ assert!(options.matches_entry(&entry, now()));
+ options.created_days = 90;
+ options.updated_days = 90;
+ assert!(
+ !options.matches_entry(&entry, now()),
+ "A recent child must affect the update filter"
+ );
+ options.updated_days = 30;
+ assert!(options.matches_entry(&entry, now()));
+ options.exclude_starred = true;
+ assert!(!options.matches_entry(&entry, now()));
+ options.exclude_starred = false;
+ options.exclude_pinned = true;
+ assert!(!options.matches_entry(&entry, now()));
+ options.exclude_pinned = false;
+ options.agents = BTreeSet::from([AgentId::Codex]);
+ assert!(!options.matches_entry(&entry, now()));
+ options.agents = BTreeSet::from([parent.agent]);
+ options.projects = BTreeSet::from(["different-project".into()]);
+ assert!(!options.matches_entry(&entry, now()));
+ options.projects = BTreeSet::from([parent.project_path]);
+ assert!(options.matches_entry(&entry, now()));
+ options.only_cleanable = true;
+ assert!(!options.matches_entry(&entry, now()));
+ assert!(
+ entry.candidate().is_none(),
+ "Unavailable entries never yield a cleanup target"
+ );
+ let restored: CleanupOptions =
+ serde_json::from_value(serde_json::to_value(options).unwrap()).unwrap();
+ assert!(restored.only_cleanable);
+ let old: CleanupOptions = serde_json::from_str(r#"{"days":0}"#).unwrap();
+ assert!(
+ !old.only_cleanable,
+ "Existing preferences must not hide unavailable sessions"
+ );
+ }
+
+ #[test]
+ fn mixed_entries_sort_together_with_unknown_size_last_in_both_directions() {
+ let (_temp, store, adapters, root) = setup();
+ for (id, days) in [("old", 180), ("middle", 90), ("new", 60)] {
+ let mut meta = insert(&store, &root, id, days);
+ // Distinct fixed dates: insertion can occur within one millisecond
+ // on CI, so wall-clock insertion order is not a creation-date order.
+ meta.updated_at = 1_800_000_000_000 - days * DAY;
+ meta.created_at = meta.updated_at - DAY;
+ store.write_session(&meta, meta.updated_at, &[]).unwrap();
+ }
+ fs::remove_file(root.join("middle.jsonl")).unwrap();
+ let inv = inventory(&store, &adapters).unwrap();
+ let mut entries: Vec<_> = inv
+ .candidates
+ .into_iter()
+ .map(|mut c| {
+ c.bytes = if c.root.id == "old" { 0 } else { 128 };
+ CleanupEntry::Available(c)
+ })
+ .chain(inv.unavailable.into_iter().map(CleanupEntry::Unavailable))
+ .collect();
+ let mut options = CleanupOptions::default();
+ for (sort, ascending, expected) in [
+ (CleanupSort::Size, true, ["old", "new", "middle"]),
+ (CleanupSort::Size, false, ["new", "old", "middle"]),
+ (CleanupSort::Created, true, ["old", "middle", "new"]),
+ (CleanupSort::Updated, false, ["new", "middle", "old"]),
+ ] {
+ options.sort = sort;
+ options.ascending = Some(ascending);
+ options.sort_entries(&mut entries);
+ assert_eq!(
+ entries
+ .iter()
+ .map(|e| e.session().id.as_str())
+ .collect::<Vec<_>>(),
+ expected
+ );
+ }
+ assert_eq!(
+ entries.iter().filter_map(CleanupEntry::candidate).count(),
+ 2
+ );
+ }
+
+ #[test]
+ fn snapshot_uses_mainline_prompt_count_and_keeps_archived_children() {
+ let (_temp, store, adapters, root) = setup();
+ let parent = insert(&store, &root, "parent", 120);
+ let mut child = insert(&store, &root, "child", 90);
+ child.archived = true;
+ let units: Vec<_> = [
+ (Role::User, None),
+ (Role::Assistant, None),
+ (Role::User, Some("sidechain")),
+ ]
+ .into_iter()
+ .enumerate()
+ .map(|(seq, (role, sidechain))| IndexUnit {
+ seq: seq as i64,
+ sidechain_id: sidechain.map(str::to_string),
+ role,
+ timestamp: None,
+ text: "synthetic".into(),
+ })
+ .collect();
+ store
+ .write_session(&child, child.updated_at, &units)
+ .unwrap();
+ store
+ .replace_parent_links(
+ AgentId::ClaudeCode,
+ &[(child.key.clone(), parent.key.clone())],
+ )
+ .unwrap();
+ let inv = inventory(&store, &adapters).unwrap();
+ assert_eq!(inv.candidates.len(), 1);
+ let c = &inv.candidates[0];
+ assert_eq!(c.sessions.len(), 2);
+ assert_eq!(c.prompts, 2);
+ assert_eq!(c.updated_at, child.updated_at);
+ let mut options = CleanupOptions::default();
+ store.set_user_data(&child.key, Some(true), None).unwrap();
+ let starred = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ assert!(options.matches(&starred, now()));
+ options.exclude_starred = true;
+ assert!(!options.matches(&starred, now()));
+ options.exclude_starred = false;
+ assert!(options.matches(&starred, now()));
+ store
+ .set_user_data(&child.key, Some(false), Some(true))
+ .unwrap();
+ let pinned = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ assert!(options.matches(&pinned, now()));
+ options.exclude_pinned = true;
+ assert!(!options.matches(&pinned, now()));
+ options.exclude_pinned = false;
+ assert!(options.matches(&pinned, now()));
+ child.updated_at = now() - DAY;
+ store.write_session(&child, child.updated_at, &[]).unwrap();
+ let recent = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ assert!(!options.matches(&recent, now()));
+ options.created_days = 30;
+ assert!(
+ !options.matches(&recent, now()),
+ "Both date filters must match"
+ );
+ options.updated_days = 0;
+ assert!(
+ options.matches(&recent, now()),
+ "Creation can be filtered independently"
+ );
+ options.created_days = 0;
+ assert!(options.matches(&recent, now()));
+ }
+ #[test]
+ fn reviewed_starred_pinned_and_recent_files_can_be_cleaned_up() {
+ let (temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "recent", 1);
+ store.set_user_data(&m.key, Some(true), Some(true)).unwrap();
+ // Fresh file modification time is not an invisible age filter.
+ fs::write(&m.file_path, "recent content").unwrap();
+ let candidate = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ assert!(candidate.has_starred() && candidate.has_pinned());
+ let mut options: CleanupOptions = serde_json::from_str(r#"{"days":0}"#).unwrap();
+ assert!(
+ options.matches(&candidate, now()),
+ "Old preferences do not introduce hidden exclusions"
+ );
+ options.exclude_starred = true;
+ options.exclude_pinned = true;
+ let restored: CleanupOptions =
+ serde_json::from_str(&serde_json::to_string(&options).unwrap()).unwrap();
+ assert!(restored.exclude_starred && restored.exclude_pinned);
+ assert!(!restored.matches(&candidate, now()));
+ let mut batch = CleanupBatch::new(vec![candidate], now());
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ |p| {
+ fs::rename(p, temp.path().join("fake-trash"))?;
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert!(batch.records[0].indexed);
+ assert_eq!(batch.records[0].targets, vec![TargetStatus::Moved]);
+ assert!(store.is_key_tombstoned(&m.key));
+ }
+
+ #[test]
+ fn date_filters_have_independent_boundaries_and_sort_does_not_change_them() {
+ let (_temp, store, adapters, root) = setup();
+ insert(&store, &root, "a", 100);
+ let mut c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ let now = now();
+ let mut options = CleanupOptions::default();
+ for days in [30, 90, 180, 365] {
+ options.updated_days = days;
+ c.updated_at = now - days * DAY;
+ assert!(options.matches(&c, now));
+ c.updated_at += 1;
+ assert!(!options.matches(&c, now));
+ }
+ options.updated_days = 0;
+ for days in [30, 90, 180, 365] {
+ options.created_days = days;
+ c.root.created_at = now - days * DAY;
+ assert!(options.matches(&c, now));
+ c.root.created_at += 1;
+ assert!(!options.matches(&c, now));
+ }
+ options.created_days = 180;
+ options.updated_days = 30;
+ c.root.created_at = now - 180 * DAY;
+ c.updated_at = now - 30 * DAY;
+ assert!(options.matches(&c, now));
+ c.root.created_at += 1;
+ assert!(
+ !options.matches(&c, now),
+ "A matching update date cannot override creation"
+ );
+ c.root.created_at -= 1;
+ c.updated_at += 1;
+ assert!(
+ !options.matches(&c, now),
+ "A matching creation date cannot override updates"
+ );
+ c.root.created_at = 0;
+ c.updated_at = 0;
+ assert!(!options.matches(&c, now));
+ options.updated_days = 0;
+ assert!(!options.matches(&c, now));
+ options.created_days = 0;
+ assert!(options.matches(&c, now));
+ let mut a = c.clone();
+ a.root.key = "a".into();
+ a.root.created_at = 1;
+ a.updated_at = 100;
+ a.bytes = 30;
+ let mut b = c;
+ b.root.key = "b".into();
+ b.root.created_at = 2;
+ b.updated_at = 50;
+ b.bytes = 80;
+ let mut items = vec![a, b];
+ options.sort = CleanupSort::Created;
+ options.sort(&mut items);
+ assert_eq!(items[0].root.key, "a");
+ options.sort = CleanupSort::Updated;
+ options.sort(&mut items);
+ assert_eq!(items[0].root.key, "b");
+ options.sort = CleanupSort::Size;
+ options.sort(&mut items);
+ assert_eq!(items[0].root.key, "b");
+ for (sort, ascending, first) in [
+ (CleanupSort::Created, true, "a"),
+ (CleanupSort::Created, false, "b"),
+ (CleanupSort::Updated, true, "b"),
+ (CleanupSort::Updated, false, "a"),
+ (CleanupSort::Size, true, "a"),
+ (CleanupSort::Size, false, "b"),
+ ] {
+ options.sort = sort;
+ options.ascending = Some(ascending);
+ options.sort(&mut items);
+ assert_eq!(items[0].root.key, first);
+ assert_eq!(options.ascending, Some(ascending));
+ }
+ items[0].bytes = items[1].bytes;
+ options.sort(&mut items);
+ assert_eq!(
+ items[0].root.key, "a",
+ "Ties stay stable in descending order"
+ );
+ assert_eq!((options.created_days, options.updated_days), (0, 0));
+ }
+ #[test]
+ fn independent_date_preferences_migrate_without_extra_restrictions() {
+ for (saved, expected) in [
+ (serde_json::json!({}), (0, 30)),
+ (serde_json::json!({"time":"Created", "days":90}), (90, 0)),
+ (serde_json::json!({"time":"Updated", "days":180}), (0, 180)),
+ (serde_json::json!({"time":"Created"}), (30, 0)),
+ (serde_json::json!({"time":"Created", "days":0}), (0, 0)),
+ (serde_json::json!({"days":0}), (0, 0)),
+ (
+ serde_json::json!({"created_days":180, "updated_days":30}),
+ (180, 30),
+ ),
+ (serde_json::json!({"created_days":90}), (90, 0)),
+ (serde_json::json!({"updated_days":90}), (0, 90)),
+ (
+ serde_json::json!({"created_days":0, "updated_days":0, "time":"Created", "days":90}),
+ (0, 0),
+ ),
+ (
+ serde_json::json!({"created_days":i64::MAX, "updated_days":-1}),
+ (0, 30),
+ ),
+ ] {
+ let mut saved = saved;
+ saved["sort"] = serde_json::json!("Created");
+ saved["ascending"] = serde_json::json!(false);
+ saved["project"] = serde_json::json!("/synthetic/project");
+ saved["exclude_starred"] = serde_json::json!(true);
+ saved["exclude_pinned"] = serde_json::json!(true);
+ let options: CleanupOptions = serde_json::from_value(saved).unwrap();
+ assert_eq!((options.created_days, options.updated_days), expected);
+ assert_eq!(options.sort, CleanupSort::Created);
+ assert_eq!(options.ascending, Some(false));
+ assert_eq!(
+ options.projects,
+ BTreeSet::from(["/synthetic/project".into()])
+ );
+ assert!(options.exclude_starred && options.exclude_pinned);
+ let encoded = serde_json::to_value(&options).unwrap();
+ assert!(encoded.get("time").is_none() && encoded.get("days").is_none());
+ let restored: CleanupOptions = serde_json::from_value(encoded).unwrap();
+ assert_eq!((restored.created_days, restored.updated_days), expected);
+ assert_eq!(restored.ascending, Some(false));
+ assert!(restored.exclude_starred && restored.exclude_pinned);
+ }
+ }
+
+ #[test]
+ fn source_filters_union_each_group_and_intersect_with_other_filters() {
+ let mut options = CleanupOptions {
+ agents: BTreeSet::from([AgentId::ClaudeCode, AgentId::Codex]),
+ projects: BTreeSet::from(["/synthetic/a".into(), "/synthetic/b".into()]),
+ ..CleanupOptions::default()
+ };
+ for agent in [AgentId::ClaudeCode, AgentId::Codex, AgentId::Cursor] {
+ for project in ["/synthetic/a", "/synthetic/b", "/synthetic/c"] {
+ let mut session = meta(Path::new("/synthetic/sessions"), "source-filter", 100);
+ session.agent = agent;
+ session.project_path = project.into();
+ let matches = options.matches_metadata(
+ &session,
+ session.updated_at,
+ std::slice::from_ref(&session),
+ now(),
+ );
+ assert_eq!(
+ matches,
+ agent != AgentId::Cursor && project != "/synthetic/c"
+ );
+ }
+ }
+ let mut session = meta(Path::new("/synthetic/sessions"), "source-filter", 1);
+ session.project_path = "/synthetic/a".into();
+ assert!(
+ !options.matches_metadata(
+ &session,
+ session.updated_at,
+ std::slice::from_ref(&session),
+ now()
+ ),
+ "Date filters still apply to selected sources"
+ );
+ options.updated_days = 0;
+ assert!(options.matches_metadata(
+ &session,
+ session.updated_at,
+ std::slice::from_ref(&session),
+ now()
+ ));
+ options.agents.clear();
+ session.agent = AgentId::Cursor;
+ assert!(
+ options.matches_metadata(
+ &session,
+ session.updated_at,
+ std::slice::from_ref(&session),
+ now()
+ ),
+ "All agents removes only the agent restriction"
+ );
+ session.project_path = "/synthetic/c".into();
+ assert!(!options.matches_metadata(
+ &session,
+ session.updated_at,
+ std::slice::from_ref(&session),
+ now()
+ ));
+ options.projects.clear();
+ assert!(
+ options.matches_metadata(
+ &session,
+ session.updated_at,
+ std::slice::from_ref(&session),
+ now()
+ ),
+ "Empty source sets include every source"
+ );
+ }
+
+ #[test]
+ fn source_preferences_migrate_and_preserve_explicit_clears() {
+ let old: CleanupOptions = serde_json::from_value(serde_json::json!({
+ "agent": "codex", "project": "/synthetic/a"
+ }))
+ .unwrap();
+ assert_eq!(old.agents, BTreeSet::from([AgentId::Codex]));
+ assert_eq!(old.projects, BTreeSet::from(["/synthetic/a".into()]));
+ let selected: CleanupOptions = serde_json::from_value(serde_json::json!({
+ "agents": ["claude-code", "codex", "codex"],
+ "projects": ["/synthetic/a", "/synthetic/b"],
+ "agent": "cursor", "project": "/synthetic/ignored"
+ }))
+ .unwrap();
+ assert_eq!(
+ selected.agents,
+ BTreeSet::from([AgentId::ClaudeCode, AgentId::Codex])
+ );
+ let saved = serde_json::to_value(&selected).unwrap();
+ assert!(saved.get("agent").is_none() && saved.get("project").is_none());
+ let restored: CleanupOptions = serde_json::from_value(saved).unwrap();
+ assert_eq!(restored.agents, selected.agents);
+ assert_eq!(restored.projects, selected.projects);
+ let cleared: CleanupOptions = serde_json::from_value(serde_json::json!({
+ "agents": [], "projects": [], "agent": "codex", "project": "/synthetic/a"
+ }))
+ .unwrap();
+ assert!(cleared.agents.is_empty() && cleared.projects.is_empty());
+ }
+
+ #[test]
+ fn retired_content_preferences_do_not_hide_candidates() {
+ let (_temp, store, adapters, root) = setup();
+ insert(&store, &root, "small-session", 100);
+ let mut candidate = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ candidate.bytes = 1024;
+ candidate.prompts = 5;
+ candidate.empty = false;
+ assert!(CleanupOptions::default().matches(&candidate, now()));
+ for preset in ["All", "Large", "Short", "Empty"] {
+ let options: CleanupOptions = serde_json::from_value(serde_json::json!({
+ "content": preset,
+ "days": 90,
+ "sort": "Created",
+ "ascending": true
+ }))
+ .unwrap();
+ assert!(options.matches(&candidate, now()));
+ assert_eq!((options.created_days, options.updated_days), (0, 90));
+ assert_eq!(options.sort, CleanupSort::Created);
+ assert!(options.sort_ascending());
+ assert!(serde_json::to_value(&options)
+ .unwrap()
+ .get("content")
+ .is_none());
+ }
+ }
+ #[test]
+ fn sort_direction_preferences_preserve_old_order_and_roundtrip() {
+ for (key, old_ascending) in [("Created", true), ("Updated", true), ("Size", false)] {
+ let mut options: CleanupOptions =
+ serde_json::from_value(serde_json::json!({ "sort": key })).unwrap();
+ assert_eq!(options.sort_ascending(), old_ascending);
+ options.ascending = Some(!old_ascending);
+ let saved = serde_json::to_string(&options).unwrap();
+ let restored: CleanupOptions = serde_json::from_str(&saved).unwrap();
+ assert_eq!(restored.sort_ascending(), !old_ascending);
+ assert_eq!(restored.sort, options.sort);
+ }
+ }
+ #[test]
+ fn changed_files_new_children_and_favorites_invalidate_review() {
+ let (_temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ let c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ assert!(revalidate(&store, &adapters, &c).is_ok());
+ store.set_user_data(&m.key, Some(true), None).unwrap();
+ assert!(revalidate(&store, &adapters, &c).is_err());
+ store.set_user_data(&m.key, Some(false), None).unwrap();
+ let child = insert(&store, &root, "child", 100);
+ store
+ .replace_parent_links(AgentId::ClaudeCode, &[(child.key, m.key.clone())])
+ .unwrap();
+ assert!(revalidate(&store, &adapters, &c).is_err());
+ store
+ .replace_parent_links(AgentId::ClaudeCode, &[])
+ .unwrap();
+ fs::write(&m.file_path, "changed").unwrap();
+ assert!(revalidate(&store, &adapters, &c).is_err());
+ }
+ #[test]
+ fn nested_paths_deduplicate_and_shared_session_prevents_cleanup() {
+ let (_temp, store, adapters, root) = setup();
+ let parent = insert(&store, &root, "a", 100);
+ fs::create_dir(root.join("a")).unwrap();
+ fs::write(root.join("a/sidecar"), "sidecar").unwrap();
+ age(&root.join("a/sidecar"));
+ age(&root.join("a"));
+ let c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ assert_eq!(c.targets.len(), 2);
+ assert_eq!(
+ c.targets
+ .iter()
+ .flat_map(|t| &t.files)
+ .filter(|f| !f.directory)
+ .count(),
+ 2
+ );
+ let mut child = insert(&store, &root, "child", 100);
+ let original = child.file_path.clone();
+ child.file_path = root.join("a/child.jsonl").to_string_lossy().into_owned();
+ fs::rename(original, &child.file_path).unwrap();
+ store.remove_session(&child.key, false).unwrap();
+ store.write_session(&child, child.updated_at, &[]).unwrap();
+ age(&root.join("a"));
+ assert!(inventory(&store, &adapters)
+ .unwrap()
+ .candidates
+ .iter()
+ .all(|c| c.root.key != parent.key));
+ store
+ .replace_parent_links(AgentId::ClaudeCode, &[(child.key, parent.key)])
+ .unwrap();
+ let c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ assert_eq!(c.targets.len(), 2);
+ assert_eq!(c.sessions.len(), 2);
+ }
+ #[test]
+ fn review_reports_every_failed_tree_and_preserves_ready_selection() {
+ let (_temp, store, adapters, root) = setup();
+ let good = insert(&store, &root, "good", 100);
+ let bad = insert(&store, &root, "bad", 100);
+ let changed = insert(&store, &root, "changed", 100);
+ fs::write(&bad.file_path, "BAD").unwrap();
+ let mut chosen = inventory(&store, &adapters).unwrap().candidates;
+ // A failure in the first item must not prevent checking later trees.
+ chosen.sort_by_key(|c| c.root.id.clone());
+ fs::write(&changed.file_path, "new content after selection").unwrap();
+ let mut progress = vec![];
+ let checked = review(&store, &adapters, chosen, &AtomicBool::new(false), |n| {
+ progress.push(n);
+ })
+ .unwrap();
+ assert_eq!(progress, vec![1, 2, 3]);
+ assert_eq!(checked.ready.len(), 1);
+ assert_eq!(checked.ready[0].root.key, good.key);
+ assert_eq!(checked.skipped.len(), 2);
+ assert_eq!(checked.skipped[0].session.key, bad.key);
+ assert_eq!(
+ checked.skipped[0].reason,
+ "Session has unrecognized content"
+ );
+ assert_eq!(checked.skipped[1].session.key, changed.key);
+ assert!(checked.skipped[1].reason.contains("changed since review"));
+ for meta in [&good, &bad, &changed] {
+ assert!(Path::new(&meta.file_path).exists());
+ assert!(store.get_session(&meta.key).unwrap().is_some());
+ assert!(!store.is_key_tombstoned(&meta.key));
+ }
+ assert!(
+ history(&store).unwrap().is_empty(),
+ "Review never starts a cleanup batch"
+ );
+ fs::write(&good.file_path, "changed again").unwrap();
+ let all_failed = review(
+ &store,
+ &adapters,
+ checked.ready,
+ &AtomicBool::new(false),
+ |_| {},
+ )
+ .unwrap();
+ assert!(all_failed.ready.is_empty());
+ assert_eq!(all_failed.skipped.len(), 1);
+ }
+
+ #[test]
+ fn cancelled_review_discards_partial_results_without_moving_files() {
+ let (_temp, store, adapters, root) = setup();
+ let first = insert(&store, &root, "first", 100);
+ let second = insert(&store, &root, "second", 100);
+ let chosen = inventory(&store, &adapters).unwrap().candidates;
+ let cancel = AtomicBool::new(true);
+ assert!(review(&store, &adapters, chosen.clone(), &cancel, |_| {
+ panic!("A cancelled review must not start checking");
+ })
+ .is_none());
+ for stop_after in [1, 2] {
+ cancel.store(false, Ordering::Relaxed);
+ let mut checked = 0;
+ assert!(review(&store, &adapters, chosen.clone(), &cancel, |n| {
+ checked = n;
+ if n == stop_after {
+ cancel.store(true, Ordering::Relaxed);
+ }
+ })
+ .is_none());
+ assert_eq!(checked, stop_after);
+ }
+ for meta in [first, second] {
+ assert!(Path::new(&meta.file_path).exists());
+ assert!(store.get_session(&meta.key).unwrap().is_some());
+ assert!(!store.is_key_tombstoned(&meta.key));
+ }
+ assert!(history(&store).unwrap().is_empty());
+ }
+
+ #[test]
+ fn unsupported_remote_missing_and_bad_content_are_not_moved() {
+ let (_temp, store, adapters, root) = setup();
+ let mut m = insert(&store, &root, "a", 100);
+ let unsupported: Vec<Box<dyn AgentAdapter>> = vec![Box::new(FilesAdapter {
+ root: root.clone(),
+ supported: false,
+ })];
+ assert!(inventory(&store, &unsupported)
+ .unwrap()
+ .candidates
+ .is_empty());
+ m.host = "remote".into();
+ store.write_session(&m, m.updated_at, &[]).unwrap();
+ assert!(inventory(&store, &adapters).unwrap().candidates.is_empty());
+ m.host.clear();
+ store.write_session(&m, m.updated_at, &[]).unwrap();
+ fs::write(&m.file_path, "BAD").unwrap();
+ age(Path::new(&m.file_path));
+ let c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ let mut batch = CleanupBatch::new(vec![c], now());
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ |_| panic!("must not move unrecognized content"),
+ )
+ .unwrap();
+ assert!(batch.records[0].error.is_some());
+ assert!(Path::new(&m.file_path).exists());
+ fs::remove_file(&m.file_path).unwrap();
+ assert!(inventory(&store, &adapters).unwrap().candidates.is_empty());
+ }
+ #[test]
+ fn hard_links_are_excluded() {
+ let (_temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ fs::hard_link(&m.file_path, root.join("other")).unwrap();
+ assert!(inventory(&store, &adapters).unwrap().candidates.is_empty());
+ fs::remove_file(root.join("other")).unwrap();
+ assert_eq!(inventory(&store, &adapters).unwrap().candidates.len(), 1);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symbolic_links_are_excluded() {
+ let (_temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ fs::rename(&m.file_path, root.join("actual")).unwrap();
+ std::os::unix::fs::symlink(root.join("actual"), &m.file_path).unwrap();
+ assert!(inventory(&store, &adapters).unwrap().candidates.is_empty());
+ }
+
+ #[test]
+ fn canonical_target_accepts_regular_paths_and_rejects_changed_locations() {
+ let temp = tempfile::tempdir().unwrap();
+ let root = temp.path().canonicalize().unwrap();
+ let path = root.join("session.jsonl");
+ fs::write(&path, "synthetic").unwrap();
+ assert!(target(&path).is_ok());
+ assert!(same_canonical_path(&path, &path.canonicalize().unwrap()));
+ assert!(!same_canonical_path(&root.join("other.jsonl"), &path));
+ assert!(target(Path::new("relative-session.jsonl")).is_err());
+ }
+
+ #[test]
+ fn same_size_and_timestamp_replacement_is_rejected_before_deletion() {
+ let (_temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ let candidate = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ let original = stamp(Path::new(&m.file_path)).unwrap();
+ let replacement = root.join("replacement");
+ fs::write(&replacement, "evil").unwrap();
+ File::options()
+ .write(true)
+ .open(&replacement)
+ .unwrap()
+ .set_times(
+ FileTimes::new().set_modified(UNIX_EPOCH + Duration::from_nanos(original.modified)),
+ )
+ .unwrap();
+ fs::rename(&m.file_path, root.join("old-file")).unwrap();
+ fs::rename(replacement, &m.file_path).unwrap();
+ let replaced = stamp(Path::new(&m.file_path)).unwrap();
+ assert_eq!(original.logical_bytes, replaced.logical_bytes);
+ assert_eq!(original.modified, replaced.modified);
+ assert_ne!(original.identity, replaced.identity);
+ assert!(revalidate(&store, &adapters, &candidate).is_err());
+ let mut batch = CleanupBatch::new(vec![candidate], now());
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ |_| panic!("A replaced file must never be moved"),
+ )
+ .unwrap();
+ assert!(!store.is_key_tombstoned(&m.key));
+ assert!(batch.records[0].error.is_some());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symbolic_link_in_target_ancestor_is_excluded() {
+ let temp = tempfile::tempdir().unwrap();
+ let root = temp.path().canonicalize().unwrap();
+ fs::create_dir(root.join("actual")).unwrap();
+ fs::write(root.join("actual/session.jsonl"), "synthetic").unwrap();
+ std::os::unix::fs::symlink(root.join("actual"), root.join("alias")).unwrap();
+ assert!(target(&root.join("alias/session.jsonl")).is_err());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn windows_canonical_prefixes_do_not_hide_regular_sessions() {
+ use std::path::{Component, Prefix};
+ let temp = tempfile::tempdir().unwrap();
+ let canonical = temp.path().canonicalize().unwrap();
+ let mut components = canonical.components();
+ let mut root = match components.next().unwrap() {
+ Component::Prefix(prefix) => match prefix.kind() {
+ Prefix::VerbatimDisk(drive) => PathBuf::from(format!("{}:", drive as char)),
+ _ => panic!("Test expects a local temporary directory"),
+ },
+ _ => panic!("Test expects an absolute temporary directory"),
+ };
+ for component in components {
+ root.push(component.as_os_str());
+ }
+ root.push("sessions");
+ fs::create_dir(&root).unwrap();
+ let store = Store::open(&temp.path().join("index.db")).unwrap();
+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(FilesAdapter {
+ root: root.clone(),
+ supported: true,
+ })];
+ insert(&store, &root, "ordinary-path", 100);
+ let inv = inventory(&store, &adapters).unwrap();
+ assert_eq!(inv.candidates.len(), 1);
+ revalidate(&store, &adapters, &inv.candidates[0]).unwrap();
+
+ for (ordinary, extended) in [
+ (r"C:\sessions\a.jsonl", r"\\?\C:\sessions\a.jsonl"),
+ (r"\\server\share\a.jsonl", r"\\?\UNC\server\share\a.jsonl"),
+ ] {
+ assert!(same_canonical_path(
+ Path::new(ordinary),
+ Path::new(extended)
+ ));
+ }
+ for different in [r"\\?\D:\sessions\a.jsonl", r"\\?\C:\elsewhere\a.jsonl"] {
+ assert!(!same_canonical_path(
+ Path::new(r"C:\sessions\a.jsonl"),
+ Path::new(different)
+ ));
+ }
+ }
+
+ #[test]
+ fn revalidation_does_not_depend_on_the_message_index() {
+ let (temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ let c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ assert_eq!(c.prompts, 1);
+ // Any accidental transcript-count query now fails deterministically,
+ // without a timing assertion or depending on a contributor's database.
+ rusqlite::Connection::open(temp.path().join("index.db"))
+ .unwrap()
+ .execute_batch("DROP TABLE messages")
+ .unwrap();
+ revalidate(&store, &adapters, &c).unwrap();
+ store.set_user_data(&m.key, None, Some(true)).unwrap();
+ assert!(revalidate(&store, &adapters, &c).is_err());
+ }
+
+ #[test]
+ fn ownership_is_checked_again_after_parsing() {
+ use std::sync::Arc;
+ struct IndexOwnerDuringParse {
+ inner: FilesAdapter,
+ store: Arc<Store>,
+ owner: SessionMeta,
+ }
+ impl AgentAdapter for IndexOwnerDuringParse {
+ fn agent(&self) -> AgentId {
+ self.inner.agent()
+ }
+ fn data_roots(&self) -> Vec<PathBuf> {
+ self.inner.data_roots()
+ }
+ fn with_custom_root(&self, root: PathBuf) -> Box<dyn AgentAdapter> {
+ self.inner.with_custom_root(root)
+ }
+ fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {
+ self.inner.list_session_files()
+ }
+ fn parse_session(&self, r: &SessionFileRef) -> Result<ParsedSession> {
+ let parsed = self.inner.parse_session(r)?;
+ // Simulate a scanner discovering an owner while validation parses
+ // the original tree. The filesystem snapshot does not change.
+ self.store
+ .write_session(&self.owner, self.owner.updated_at, &[])?;
+ Ok(parsed)
+ }
+ fn parse_transcript(&self, r: &SessionFileRef) -> Result<ParsedTranscript> {
+ self.inner.parse_transcript(r)
+ }
+ fn session_paths(&self, m: &SessionMeta) -> Vec<String> {
+ self.inner.session_paths(m)
+ }
+ fn cleanup_paths(&self, m: &SessionMeta) -> Option<Vec<String>> {
+ self.inner.cleanup_paths(m)
+ }
+ }
+ let (_temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ fs::create_dir(root.join("a")).unwrap();
+ let sidecar = root.join("a/sidecar.jsonl");
+ fs::write(&sidecar, "test").unwrap();
+ let c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ let mut owner = meta(&root, "new-owner", 100);
+ owner.file_path = sidecar.to_string_lossy().into_owned();
+ let store = Arc::new(store);
+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![Box::new(IndexOwnerDuringParse {
+ inner: FilesAdapter {
+ root,
+ supported: true,
+ },
+ store: store.clone(),
+ owner,
+ })];
+ let error = revalidate(&store, &adapters, &c).unwrap_err();
+ assert_eq!(error.to_string(), "Target also contains another session");
+ assert!(Path::new(&m.file_path).exists());
+ assert!(!store.is_key_tombstoned(&m.key));
+ }
+ #[test]
+ fn partial_failure_is_journaled_and_restored_files_can_be_reindexed() {
+ let (temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ fs::create_dir(root.join("a")).unwrap();
+ fs::write(root.join("a/sidecar"), "side").unwrap();
+ age(&root.join("a/sidecar"));
+ age(&root.join("a"));
+ let c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ let moved_path = c.targets[0].path.clone();
+ let dest = temp.path().join("fake-trash");
+ let calls = Cell::new(0);
+ let mut batch = CleanupBatch::new(vec![c], now());
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ |p| {
+ calls.set(calls.get() + 1);
+ if calls.get() == 2 {
+ bail!("fake permission failure");
+ }
+ fs::rename(p, &dest)?;
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert_eq!(batch.records[0].targets[0], TargetStatus::Moved);
+ assert!(matches!(
+ batch.records[0].targets[1],
+ TargetStatus::Failed(_)
+ ));
+ assert!(!batch.records[0].indexed);
+ assert!(!store.is_key_tombstoned(&m.key));
+ assert_eq!(history(&store).unwrap().len(), 1);
+ fs::rename(dest, moved_path).unwrap();
+ assert_eq!(restore(&store, &adapters, &mut batch).unwrap(), 1);
+ assert!(batch.records[0].restored);
+ store.rebuild_all().unwrap();
+ assert_eq!(history(&store).unwrap().len(), 1);
+ }
+ #[test]
+ fn watcher_race_still_writes_tombstones_and_restore_respects_later_deletion() {
+ let (temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ let c = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ let dest = temp.path().join("fake-trash");
+ let mut batch = CleanupBatch::new(vec![c], now());
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ |p| {
+ fs::rename(p, &dest)?;
+ store.remove_session(&m.key, false)?;
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert!(batch.records[0].indexed);
+ assert!(store.is_key_tombstoned(&m.key));
+ assert!(store.is_tombstoned(&m.file_path));
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ fs::rename(dest, &m.file_path).unwrap();
+ store
+ .complete_cleanup(std::slice::from_ref(&m), batch.stamp + 1)
+ .unwrap();
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ assert!(store.is_key_tombstoned(&m.key));
+ }
+ #[test]
+ fn cancellation_stops_before_next_tree_and_never_claims_it_moved() {
+ let (temp, store, adapters, root) = setup();
+ insert(&store, &root, "a", 100);
+ insert(&store, &root, "b", 100);
+ let items = inventory(&store, &adapters).unwrap().candidates;
+ let mut batch = CleanupBatch::new(items, now());
+ let cancel = AtomicBool::new(false);
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &cancel,
+ |_| cancel.store(true, Ordering::Relaxed),
+ |p| {
+ fs::rename(p, temp.path().join(p.file_name().unwrap()))?;
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert!(batch.records[0].indexed);
+ assert!(!batch.records[1].indexed);
+ assert_eq!(batch.records[1].targets, vec![TargetStatus::Pending]);
+ }
+
+ #[test]
+ fn index_conflict_can_be_retried_and_complete_restore_clears_only_its_tombstone() {
+ let (temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ let item = inventory(&store, &adapters).unwrap().candidates.remove(0);
+ let dest = temp.path().join("fake-trash");
+ let mut batch = CleanupBatch::new(vec![item], now());
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ |p| {
+ fs::rename(p, &dest)?;
+ store.set_user_data(&m.key, Some(true), None)?;
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert!(!batch.records[0].indexed);
+ assert_eq!(batch.records[0].targets, vec![TargetStatus::Moved]);
+ assert_eq!(retry_index_updates(&store, &mut batch).unwrap(), 0);
+ assert!(store.get_session(&m.key).unwrap().is_some());
+ store.set_user_data(&m.key, Some(false), None).unwrap();
+ assert_eq!(retry_index_updates(&store, &mut batch).unwrap(), 1);
+ assert!(store.is_key_tombstoned(&m.key));
+ fs::rename(dest, &m.file_path).unwrap();
+ assert_eq!(restore(&store, &adapters, &mut batch).unwrap(), 1);
+ assert!(!store.is_key_tombstoned(&m.key));
+ assert!(!store.is_tombstoned(&m.file_path));
+ assert!(history(&store).unwrap()[0].records[0].restored);
+ }
+
+ #[test]
+ fn manual_restore_check_never_moves_files_and_requires_complete_sidecars() {
+ let (temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ fs::create_dir(root.join("a")).unwrap();
+ fs::write(root.join("a/sidecar"), "sidecar").unwrap();
+ let trash = temp.path().join("fake-trash");
+ fs::create_dir(&trash).unwrap();
+ let mut batch = CleanupBatch::new(inventory(&store, &adapters).unwrap().candidates, now());
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ |path| {
+ fs::rename(path, trash.join(path.file_name().unwrap()))?;
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ assert!(trash.join("a.jsonl").exists() && trash.join("a/sidecar").exists());
+ assert!(!Path::new(&m.file_path).exists());
+ assert!(store.is_key_tombstoned(&m.key));
+ // Simulate the user putting back only the main transcript.
+ fs::rename(trash.join("a.jsonl"), &m.file_path).unwrap();
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ assert!(trash.join("a/sidecar").exists());
+ assert!(store.is_key_tombstoned(&m.key));
+ // Only a complete manual restoration clears this batch's tombstones.
+ fs::create_dir(root.join("a")).unwrap();
+ fs::create_dir(root.join("a/sidecar")).unwrap();
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ assert!(store.is_key_tombstoned(&m.key));
+ fs::remove_dir(root.join("a/sidecar")).unwrap();
+ // Equal length and timestamp still must not pass with different content.
+ fs::copy(trash.join("a/sidecar"), root.join("a/sidecar")).unwrap();
+ fs::write(root.join("a/sidecar"), "corrupt").unwrap();
+ let modified = fs::metadata(trash.join("a/sidecar"))
+ .unwrap()
+ .modified()
+ .unwrap();
+ File::options()
+ .write(true)
+ .open(root.join("a/sidecar"))
+ .unwrap()
+ .set_times(FileTimes::new().set_modified(modified))
+ .unwrap();
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ assert!(!batch.records[0].restored);
+ assert!(store.is_key_tombstoned(&m.key));
+ fs::remove_file(root.join("a/sidecar")).unwrap();
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(trash.join("a/sidecar"), root.join("a/sidecar")).unwrap();
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ fs::remove_file(root.join("a/sidecar")).unwrap();
+ }
+ fs::remove_dir(root.join("a")).unwrap();
+ fs::rename(trash.join("a"), root.join("a")).unwrap();
+ assert_eq!(restore(&store, &adapters, &mut batch).unwrap(), 1);
+ assert!(!store.is_key_tombstoned(&m.key));
+ assert!(history(&store).unwrap()[0].records[0].restored);
+ }
+
+ #[test]
+ fn restored_copies_can_have_new_file_identities() {
+ let (temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ let trash = temp.path().join("fake-trash");
+ let mut batch = CleanupBatch::new(inventory(&store, &adapters).unwrap().candidates, now());
+ execute_with(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ |p| {
+ fs::rename(p, &trash)?;
+ Ok(())
+ },
+ )
+ .unwrap();
+ // Reload the journal, proving content evidence was saved before moving.
+ batch = history(&store).unwrap().remove(0);
+ assert_eq!(batch.records[0].content_hashes.len(), 1);
+ fs::copy(&trash, &m.file_path).unwrap();
+ assert_ne!(
+ stamp(&trash).unwrap().identity,
+ stamp(Path::new(&m.file_path)).unwrap().identity
+ );
+ assert_eq!(restore(&store, &adapters, &mut batch).unwrap(), 1);
+ assert!(!store.is_key_tombstoned(&m.key));
+ }
+
+ #[test]
+ fn legacy_journals_require_matching_type_length_and_timestamp() {
+ let (_temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "a", 100);
+ let batch = CleanupBatch::new(inventory(&store, &adapters).unwrap().candidates, now());
+ let mut saved = serde_json::to_value(batch).unwrap();
+ saved["records"][0]
+ .as_object_mut()
+ .unwrap()
+ .remove("content_hashes");
+ let mut batch: CleanupBatch = serde_json::from_value(saved).unwrap();
+ batch.records[0].targets.fill(TargetStatus::Moved);
+ store
+ .complete_cleanup(std::slice::from_ref(&m), batch.stamp)
+ .unwrap();
+ let modified = fs::metadata(&m.file_path).unwrap().modified().unwrap();
+ fs::write(&m.file_path, "truncated").unwrap();
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ fs::write(&m.file_path, "test").unwrap();
+ assert!(restore(&store, &adapters, &mut batch).is_err());
+ File::options()
+ .write(true)
+ .open(&m.file_path)
+ .unwrap()
+ .set_times(FileTimes::new().set_modified(modified))
+ .unwrap();
+ assert_eq!(restore(&store, &adapters, &mut batch).unwrap(), 1);
+ }
+
+ #[cfg(any(target_os = "linux", windows))]
+ #[test]
+ #[ignore = "Uses the system trash for synthetic temporary files; run explicitly in CI"]
+ fn system_trash_cleanup_round_trip() {
+ let (_temp, store, adapters, root) = setup();
+ let m = insert(&store, &root, "会话 with spaces", 100);
+ fs::create_dir(root.join(&m.id)).unwrap();
+ fs::write(root.join(&m.id).join("sidecar.jsonl"), "synthetic sidecar").unwrap();
+ let mut batch = CleanupBatch::new(inventory(&store, &adapters).unwrap().candidates, now());
+ assert_eq!(batch.records.len(), 1);
+ execute(
+ &store,
+ &adapters,
+ &mut batch,
+ &AtomicBool::new(false),
+ |_| {},
+ )
+ .unwrap();
+ assert!(batch.records[0].indexed, "{:?}", batch.records[0].error);
+ assert!(store.is_key_tombstoned(&m.key));
+ assert!(!Path::new(&m.file_path).exists());
+ // Only restore the uniquely named temp tree created by this test. Never
+ // restore or purge unrelated entries in the user's/runner's recycle bin.
+ let paths = &batch.records[0].candidate.targets;
+ let items: Vec<_> = trash::os_limited::list()
+ .unwrap()
+ .into_iter()
+ .filter(|item| {
+ paths
+ .iter()
+ .any(|t| same_canonical_path(&item.original_path(), &t.path))
+ })
+ .collect();
+ assert_eq!(items.len(), paths.len());
+ trash::os_limited::restore_all(items).unwrap();
+ assert_eq!(restore(&store, &adapters, &mut batch).unwrap(), 1);
+ assert_eq!(
+ fs::read_to_string(root.join(&m.id).join("sidecar.jsonl")).unwrap(),
+ "synthetic sidecar"
+ );
+ assert!(!store.is_key_tombstoned(&m.key));
+ }
+}
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index fab1489..7031c95 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -558,9 +558,40 @@ impl Store {
/// 一棵会话树在索引侧原子删除。磁盘路径由调用方先整体移入废纸篓;若
/// 任一索引步骤失败,所有 session/message/FTS/tombstone 改动一起回滚。
pub fn remove_sessions(&self, keys: &[String], tombstone: bool) -> Result<()> {
+ self.remove_sessions_recorded(keys, tombstone, &[], now_ms())
+ }
+
+ /// Keep the reviewed paths even if the watcher already removed a missing
+ /// source row. File moves and watcher delivery cannot share a transaction.
+ pub fn complete_cleanup(&self, sessions: &[SessionMeta], stamp: i64) -> Result<()> {
+ let keys = sessions.iter().map(|s| s.key.clone()).collect::<Vec<_>>();
+ self.remove_sessions_recorded(&keys, true, sessions, stamp)
+ }
+
+ fn remove_sessions_recorded(
+ &self,
+ keys: &[String],
+ tombstone: bool,
+ recorded: &[SessionMeta],
+ stamp: i64,
+ ) -> Result<()> {
let mut conn = self.write.lock().unwrap();
let tx = conn.transaction()?;
for key in keys {
+ if let Some(expected) = recorded.iter().find(|s| s.key == *key) {
+ let sql=format!("SELECT {SESSION_COLS} FROM sessions s LEFT JOIN user_data u ON u.session_key = s.key WHERE s.key = ?1");
+ if let Some(current) = tx.query_row(&sql, params![key], row_to_meta).optional()? {
+ anyhow::ensure!(
+ current.file_path == expected.file_path
+ && current.updated_at == expected.updated_at
+ && current.created_at == expected.created_at
+ && current.favorite == expected.favorite
+ && current.pinned == expected.pinned,
+ "Session changed before index update: {}",
+ current.title
+ );
+ }
+ }
let file_path: Option<String> = tx
.query_row(
"SELECT file_path FROM sessions WHERE key = ?1",
@@ -583,10 +614,15 @@ impl Store {
tx.execute("DELETE FROM titles_fts WHERE key = ?1", params![key])?;
tx.execute("DELETE FROM sessions WHERE key = ?1", params![key])?;
if tombstone {
- if let Some(fp) = file_path {
+ if let Some(fp) = file_path.or_else(|| {
+ recorded
+ .iter()
+ .find(|s| s.key == *key)
+ .map(|s| s.file_path.clone())
+ }) {
tx.execute(
"INSERT OR REPLACE INTO tombstones(file_path, key, deleted_at) VALUES (?1, ?2, ?3)",
- params![fp, key, now_ms()],
+ params![fp, key, stamp],
)?;
}
}
@@ -672,6 +708,66 @@ impl Store {
Ok(())
}
+ /// Cleanup journals survive ordinary index rebuilds, like other user prefs.
+ pub fn cleanup_journals(&self) -> Result<Vec<String>> {
+ let conn = self.read.lock().unwrap();
+ let mut stmt = conn.prepare(
+ "SELECT value FROM prefs WHERE key LIKE 'cleanup.batch.%' ORDER BY key DESC",
+ )?;
+ let rows = stmt.query_map([], |r| r.get(0))?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// Fresh ownership metadata for inventory and each deletion check. Deliberately
+ /// independent of the message index, which can contain millions of rows.
+ pub fn cleanup_index(&self) -> Result<Vec<crate::cleanup::IndexedSession>> {
+ let conn = self.read.lock().unwrap();
+ let sql = format!("SELECT {SESSION_COLS}, s.parent_key FROM sessions s LEFT JOIN user_data u ON u.session_key = s.key");
+ let mut stmt = conn.prepare(&sql)?;
+ let rows = stmt.query_map([], |r| {
+ Ok(crate::cleanup::IndexedSession {
+ meta: row_to_meta(r)?,
+ parent: r.get(19)?,
+ })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// Display-only counts, collected once per cleanup inventory, never per tree
+ /// during review or execution. Sidechain prompts do not belong to the mainline.
+ pub fn cleanup_prompt_counts(&self) -> Result<std::collections::HashMap<String, i64>> {
+ let conn = self.read.lock().unwrap();
+ let mut stmt = conn.prepare("SELECT session_key, COUNT(*) FROM messages WHERE role = 'user' AND sidechain_id IS NULL GROUP BY session_key")?;
+ let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
+ /// Check before moving restored files, then check again in the transaction.
+ pub fn validate_cleanup_restore(&self, sessions: &[SessionMeta], stamp: i64) -> Result<()> {
+ let conn = self.read.lock().unwrap();
+ for s in sessions {
+ let conflict: bool = conn.query_row("SELECT EXISTS(SELECT 1 FROM tombstones WHERE (key = ?1 OR file_path = ?2) AND deleted_at != ?3)", params![s.key, s.file_path, stamp], |r| r.get(0))?;
+ anyhow::ensure!(!conflict, "A newer deletion protects {}", s.file_path);
+ }
+ Ok(())
+ }
+
+ /// Only undo the tombstones written by this cleanup, never later deletions.
+ pub fn restore_cleanup(&self, sessions: &[SessionMeta], stamp: i64) -> Result<()> {
+ let mut conn = self.write.lock().unwrap();
+ let tx = conn.transaction()?;
+ for s in sessions {
+ let conflict: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM tombstones WHERE (key = ?1 OR file_path = ?2) AND deleted_at != ?3)", params![s.key, s.file_path, stamp], |r| r.get(0))?;
+ anyhow::ensure!(!conflict, "A newer deletion protects {}", s.file_path);
+ tx.execute(
+ "DELETE FROM tombstones WHERE key = ?1 AND file_path = ?2 AND deleted_at = ?3",
+ params![s.key, s.file_path, stamp],
+ )?;
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
// ---------- 自定义 location(Session locations 面板的 Add location) ----------
/// 与收藏/置顶同层级的用户数据:索引重扫不动它,只有索引文件本体损坏
diff --git a/crates/wake-core/src/lib.rs b/crates/wake-core/src/lib.rs
index e09a58a..67cbca5 100644
--- a/crates/wake-core/src/lib.rs
+++ b/crates/wake-core/src/lib.rs
@@ -1,4 +1,5 @@
pub mod adapters;
+pub mod cleanup;
pub mod cli;
pub mod db;
pub mod mcp;
diff --git a/crates/wake-core/src/services/mod.rs b/crates/wake-core/src/services/mod.rs
index cc93d41..2e4660c 100644
--- a/crates/wake-core/src/services/mod.rs
+++ b/crates/wake-core/src/services/mod.rs
@@ -1,3 +1,5 @@
pub mod context;
pub mod exporter;
pub mod terminal;
+#[cfg(windows)]
+pub(crate) mod windows_fs;
diff --git a/crates/wake-core/src/services/terminal/mod.rs b/crates/wake-core/src/services/terminal/mod.rs
index b6f8363..24dde0d 100644
--- a/crates/wake-core/src/services/terminal/mod.rs
+++ b/crates/wake-core/src/services/terminal/mod.rs
@@ -394,6 +394,17 @@ fn clipboard_fallback(command: &str) -> String {
}
}
+/// Reject locations for which the OS backend cannot safely recycle files.
+pub(crate) fn validate_trash_path(path: &Path) -> anyhow::Result<()> {
+ #[cfg(windows)]
+ return super::windows_fs::ensure_recyclable(path);
+ #[cfg(not(windows))]
+ {
+ let _ = path;
+ Ok(())
+ }
+}
+
/// 删除会话文件到系统回收站(可恢复)。虚拟路径 `<db>#<id>` 与已消失的
/// 文件在此过滤(不变量 3:SQLite 型只 tombstone),平台原语只收真实路径。
/// 部分失败语义:平台实现可能删到一半报错(macOS 逐文件、Linux/Windows
@@ -404,12 +415,30 @@ pub fn trash_paths(paths: &[String]) -> anyhow::Result<()> {
.map(|s| s.as_str())
.filter(|p| Path::new(p).exists())
.collect();
+ // Preflight the entire batch before moving anything, including callers
+ // outside the cleanup page. Never fall back to permanent deletion.
+ for path in &existing {
+ validate_trash_path(Path::new(path))?;
+ }
if existing.is_empty() {
return Ok(());
}
platform::trash_existing(&existing)
}
+/// Open the system trash for the user to inspect the reviewed batch. Never
+/// empty it here: it can contain unrelated files.
+pub fn open_trash() {
+ #[cfg(target_os = "macos")]
+ if let Some(home) = dirs::home_dir() {
+ platform::open_dir(&home.join(".Trash").to_string_lossy());
+ }
+ #[cfg(target_os = "linux")]
+ platform::open_dir("trash:///");
+ #[cfg(target_os = "windows")]
+ platform::open_dir("shell:RecycleBinFolder");
+}
+
/// 致命错误提示。GPUI 窗口还没起来时这是唯一能让用户看见的通道,
/// 否则应用就是无提示秒退;stderr 始终先落一份。
pub fn show_fatal_alert(message: &str) {
diff --git a/crates/wake-core/src/services/windows_fs.rs b/crates/wake-core/src/services/windows_fs.rs
new file mode 100644
index 0000000..9544f0d
--- /dev/null
+++ b/crates/wake-core/src/services/windows_fs.rs
@@ -0,0 +1,237 @@
+//! Filesystem evidence used by cleanup. Query one open handle rather than using
+//! logical file length or a placeholder identity on Windows.
+use anyhow::{bail, ensure, Context, Result};
+use std::{
+ fs::{Metadata, OpenOptions},
+ os::windows::{ffi::OsStrExt, fs::OpenOptionsExt, io::AsRawHandle},
+ path::{Component, Path, Prefix},
+};
+use windows_sys::Win32::{
+ Storage::FileSystem::{
+ FileCompressionInfo, FileIdInfo, FileStandardInfo, GetDriveTypeW,
+ GetFileInformationByHandle, GetFileInformationByHandleEx, GetVolumePathNameW,
+ BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_COMPRESSED, FILE_ATTRIBUTE_REPARSE_POINT,
+ FILE_ATTRIBUTE_SPARSE_FILE, FILE_COMPRESSION_INFO, FILE_FLAG_BACKUP_SEMANTICS,
+ FILE_FLAG_OPEN_REPARSE_POINT, FILE_ID_INFO, FILE_SHARE_DELETE, FILE_SHARE_READ,
+ FILE_SHARE_WRITE, FILE_STANDARD_INFO,
+ },
+ System::WindowsProgramming::{DRIVE_FIXED, DRIVE_REMOTE},
+};
+
+pub(crate) fn ensure_recyclable(path: &Path) -> Result<()> {
+ // Reject UNC before any I/O, including extended UNC. trash's Shell backend
+ // strips the extended prefix, which would also corrupt an extended UNC path.
+ if matches!(path.components().next(), Some(Component::Prefix(p))
+ if matches!(p.kind(), Prefix::UNC(..) | Prefix::VerbatimUNC(..)))
+ {
+ bail!("Network locations cannot be moved to the Recycle Bin");
+ }
+ ensure!(
+ path.is_absolute(),
+ "Source path contains links or is not absolute"
+ );
+ let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ let mut volume = vec![0; 32_768];
+ // SAFETY: both strings are NUL-terminated, the output buffer is writable,
+ // and its size is supplied in UTF-16 code units.
+ let ok = unsafe { GetVolumePathNameW(wide.as_ptr(), volume.as_mut_ptr(), volume.len() as u32) };
+ if ok == 0 {
+ return Err(std::io::Error::last_os_error()).context("Cannot verify the source volume");
+ }
+ // Includes drive-letter mappings and mounted volumes, not only UNC syntax.
+ match unsafe { GetDriveTypeW(volume.as_ptr()) } {
+ DRIVE_FIXED => Ok(()),
+ DRIVE_REMOTE => bail!("Network locations cannot be moved to the Recycle Bin"),
+ _ => bail!("This location does not support safe recycling"),
+ }
+}
+
+pub(crate) struct FileSnapshot {
+ pub metadata: Metadata,
+ pub bytes: u64,
+ pub identity: (u64, u64),
+ pub identity_high: u64,
+}
+
+pub(crate) fn snapshot(path: &Path) -> Result<FileSnapshot> {
+ let file = OpenOptions::new()
+ .access_mode(0)
+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
+ .open(path)?;
+ let handle = file.as_raw_handle();
+ let mut info = BY_HANDLE_FILE_INFORMATION::default();
+ // SAFETY: the owned File keeps the handle live, and info has the API's layout.
+ if unsafe { GetFileInformationByHandle(handle, &mut info) } == 0 {
+ return Err(std::io::Error::last_os_error()).context("Cannot verify file identity");
+ }
+ ensure!(
+ info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0,
+ "Symbolic links are not supported"
+ );
+ let metadata = file.metadata()?;
+ ensure!(
+ !metadata.is_file() || info.nNumberOfLinks == 1,
+ "Shared hard links are not supported"
+ );
+ // ReFS uses 128-bit IDs; the legacy 64-bit file index is not sufficient.
+ let mut id = FILE_ID_INFO::default();
+ let ok = unsafe {
+ GetFileInformationByHandleEx(
+ handle,
+ FileIdInfo,
+ (&mut id as *mut FILE_ID_INFO).cast(),
+ std::mem::size_of::<FILE_ID_INFO>() as u32,
+ )
+ };
+ if ok == 0 {
+ return Err(std::io::Error::last_os_error()).context("Cannot verify file identity");
+ }
+ ensure!(
+ id.FileId.Identifier != [0; 16],
+ "Cannot verify file identity"
+ );
+ let low = u64::from_le_bytes(id.FileId.Identifier[..8].try_into()?);
+ let high = u64::from_le_bytes(id.FileId.Identifier[8..].try_into()?);
+ let bytes = if metadata.is_dir() {
+ 0
+ } else if info.dwFileAttributes & (FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_SPARSE_FILE) != 0
+ {
+ let mut compression = FILE_COMPRESSION_INFO::default();
+ // Compressed/sparse streams need their actual allocation, not EOF or
+ // the standard-info allocation of their uncompressed logical ranges.
+ let ok = unsafe {
+ GetFileInformationByHandleEx(
+ handle,
+ FileCompressionInfo,
+ (&mut compression as *mut FILE_COMPRESSION_INFO).cast(),
+ std::mem::size_of::<FILE_COMPRESSION_INFO>() as u32,
+ )
+ };
+ if ok == 0 {
+ return Err(std::io::Error::last_os_error()).context("Cannot measure disk usage");
+ }
+ u64::try_from(compression.CompressedFileSize)?
+ } else {
+ let mut standard = FILE_STANDARD_INFO::default();
+ let ok = unsafe {
+ GetFileInformationByHandleEx(
+ handle,
+ FileStandardInfo,
+ (&mut standard as *mut FILE_STANDARD_INFO).cast(),
+ std::mem::size_of::<FILE_STANDARD_INFO>() as u32,
+ )
+ };
+ if ok == 0 {
+ return Err(std::io::Error::last_os_error()).context("Cannot measure disk usage");
+ }
+ u64::try_from(standard.AllocationSize)?
+ };
+ Ok(FileSnapshot {
+ metadata,
+ bytes,
+ identity: (id.VolumeSerialNumber, low),
+ identity_high: high,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn unc_locations_are_rejected_without_accessing_the_share() {
+ for path in [
+ r"\\server\share\session.jsonl",
+ r"\\?\UNC\server\share\session.jsonl",
+ ] {
+ assert_eq!(
+ ensure_recyclable(Path::new(path)).unwrap_err().to_string(),
+ "Network locations cannot be moved to the Recycle Bin"
+ );
+ }
+ }
+
+ #[test]
+ fn local_volume_and_allocated_size_are_available() {
+ let temp = tempfile::tempdir().unwrap();
+ let path = temp.path().join("session.jsonl");
+ std::fs::write(&path, vec![b'a'; 8193]).unwrap();
+ ensure_recyclable(&path).unwrap();
+ let file = snapshot(&path).unwrap();
+ assert!(file.bytes >= file.metadata.len());
+ assert_ne!((file.identity.1, file.identity_high), (0, 0));
+ assert_eq!(snapshot(&path).unwrap().identity, file.identity);
+ }
+
+ #[test]
+ fn sparse_and_compressed_files_use_disk_allocation_not_logical_length() {
+ use windows_sys::Win32::{
+ Storage::FileSystem::COMPRESSION_FORMAT_DEFAULT,
+ System::{
+ Ioctl::{FSCTL_SET_COMPRESSION, FSCTL_SET_SPARSE},
+ IO::DeviceIoControl,
+ },
+ };
+ let temp = tempfile::tempdir().unwrap();
+ for sparse in [true, false] {
+ let path = temp
+ .path()
+ .join(if sparse { "sparse" } else { "compressed" });
+ let file = OpenOptions::new()
+ .create_new(true)
+ .write(true)
+ .read(true)
+ .open(&path)
+ .unwrap();
+ let compression = COMPRESSION_FORMAT_DEFAULT;
+ let mut returned = 0;
+ let ok = unsafe {
+ DeviceIoControl(
+ file.as_raw_handle(),
+ if sparse {
+ FSCTL_SET_SPARSE
+ } else {
+ FSCTL_SET_COMPRESSION
+ },
+ if sparse {
+ std::ptr::null()
+ } else {
+ (&compression as *const u16).cast()
+ },
+ if sparse {
+ 0
+ } else {
+ std::mem::size_of::<u16>() as u32
+ },
+ std::ptr::null_mut(),
+ 0,
+ &mut returned,
+ std::ptr::null_mut(),
+ )
+ };
+ assert_ne!(
+ ok,
+ 0,
+ "NTFS fixture setup failed: {}",
+ std::io::Error::last_os_error()
+ );
+ if sparse {
+ file.set_len(16 * 1024 * 1024).unwrap();
+ } else {
+ use std::io::Write;
+ (&file).write_all(&vec![b'a'; 1024 * 1024]).unwrap();
+ }
+ file.sync_all().unwrap();
+ drop(file);
+ let FileSnapshot {
+ metadata, bytes, ..
+ } = snapshot(&path).unwrap();
+ assert!(
+ bytes < metadata.len() / 2,
+ "logical={}, allocated={bytes}",
+ metadata.len()
+ );
+ }
+ }
+}
diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rs
index 36eb006..ec779bd 100644
--- a/crates/wake-core/tests/adapter_contracts.rs
+++ b/crates/wake-core/tests/adapter_contracts.rs
@@ -341,6 +341,75 @@ fn kimi_ref() -> SessionFileRef {
// ---------------------------------------------------------------- 每家解析
+#[test]
+fn claude_bridge_metadata_can_pass_cleanup_review() {
+ use std::sync::atomic::AtomicBool;
+ use wake_core::{cleanup, db::Store};
+
+ setup(); // All paths below belong to the shared synthetic home.
+ let adapter = ClaudeAdapter::new();
+ let root = adapter.data_roots().remove(0);
+ fs::create_dir_all(&root).unwrap();
+ // macOS temp paths may start with the /var alias; cleanup requires real paths.
+ let root = root.canonicalize().unwrap();
+ let adapter = adapter.with_custom_root(root.clone());
+ let project = tempfile::tempdir_in(&root).unwrap();
+ let path = project.path().join("bridge-cleanup-fixture.jsonl");
+ let original = fs::read_to_string(&claude_ref().file_path).unwrap();
+ let valid = original
+ .lines()
+ .filter(|line| !line.contains("wibble-experimental"))
+ .collect::<Vec<_>>()
+ .join("\n")
+ + "\n";
+ fs::write(&path, &valid).unwrap();
+ let reference = fs_ref(AgentId::ClaudeCode, &path, "bridge-cleanup-fixture");
+ let parsed = adapter.parse_session(&reference).unwrap();
+ assert_eq!(parsed.unknown_line_count, 0);
+ assert_eq!(parsed.meta.message_count, 3);
+ let transcript = adapter.parse_transcript(&reference).unwrap();
+ assert_eq!(transcript.unknown_line_count, 0);
+ assert_eq!(transcript.mainline.len(), 5);
+
+ let db_dir = tempfile::tempdir().unwrap();
+ let store = Store::open(&db_dir.path().join("test.db")).unwrap();
+ store
+ .write_session(&parsed.meta, reference.mtime_ms, &parsed.units)
+ .unwrap();
+ let adapters = vec![adapter];
+ let inventory = cleanup::inventory(&store, &adapters).unwrap();
+ assert_eq!(inventory.candidates.len(), 1);
+ let review = cleanup::review(
+ &store,
+ &adapters,
+ inventory.candidates,
+ &AtomicBool::new(false),
+ |_| {},
+ )
+ .unwrap();
+ assert_eq!(review.ready.len(), 1);
+ assert!(review.skipped.is_empty());
+ cleanup::revalidate(&store, &adapters, &review.ready[0]).unwrap();
+
+ // Supporting known bookkeeping must not allow malformed or unknown records.
+ for invalid in [r#"{"type":"unknown-fixture-record"}"#, "{truncated"] {
+ fs::write(&path, format!("{valid}{invalid}\n")).unwrap();
+ let inventory = cleanup::inventory(&store, &adapters).unwrap();
+ let review = cleanup::review(
+ &store,
+ &adapters,
+ inventory.candidates,
+ &AtomicBool::new(false),
+ |_| {},
+ )
+ .unwrap();
+ assert!(review.ready.is_empty());
+ assert_eq!(review.skipped.len(), 1);
+ assert_eq!(review.skipped[0].reason, "Session has unrecognized content");
+ assert!(path.exists());
+ }
+}
+
#[test]
fn claude_parse_contract() {
setup();
@@ -361,8 +430,9 @@ fn claude_parse_contract() {
assert_eq!(s.meta.message_count, 3);
assert_eq!(s.meta.created_at, ms("2026-08-01T09:59:00Z"));
assert_eq!(s.meta.updated_at, ms("2026-08-01T10:02:00Z"));
- // "wibble-experimental" 计 unknown;"summary" 在已知跳过表内不计
+ // "wibble-experimental" 计 unknown;summary / atis-latch / bridge-session 不计
assert_eq!(s.unknown_line_count, 1);
+ assert_eq!(t.unknown_line_count, 1);
assert_eq!(
roles_kinds(&t.mainline),
@@ -782,6 +852,24 @@ fn cursor_two_sources_route_by_path() {
!targets.iter().any(|t| t.ends_with("globalStorage")),
"删除目标落到 globalStorage 目录就会端掉整个 Cursor IDE 数据"
);
+ assert!(ide.cleanup_paths(&ide_meta).is_none());
+ let cleanup_db = tempfile::tempdir().unwrap();
+ let store = wake_core::db::Store::open(&cleanup_db.path().join("cleanup.db")).unwrap();
+ store
+ .write_session(&ide_meta, ide_meta.updated_at, &[])
+ .unwrap();
+ let inventory = wake_core::cleanup::inventory(&store, &roster).unwrap();
+ assert!(
+ inventory.candidates.is_empty(),
+ "IDE 数据库会话不能进入文件清理候选"
+ );
+ assert_eq!(inventory.unavailable.len(), 1);
+ assert_eq!(inventory.unavailable[0].session.key, ide_meta.key);
+ assert_eq!(
+ inventory.unavailable[0].reason,
+ "This source does not support independent file cleanup"
+ );
+ assert!(env.cursor_ide_db.exists());
// CLI 的真实文件路径 → CLI 实例
let cli_path = fixture(
diff --git a/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/11111111-aaaa-bbbb-cccc-000000000001.jsonl b/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/11111111-aaaa-bbbb-cccc-000000000001.jsonl
index 99d2c75..e4124ed 100644
--- a/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/11111111-aaaa-bbbb-cccc-000000000001.jsonl
+++ b/crates/wake-core/tests/fixtures/claude/projects/-Users-tester-Github-wakefx/11111111-aaaa-bbbb-cccc-000000000001.jsonl
@@ -8,3 +8,5 @@
{"type":"system","subtype":"compact_boundary","content":"Conversation compacted","isMeta":false,"cwd":"/Users/tester/Github/wakefx","sessionId":"11111111-aaaa-bbbb-cccc-000000000001","uuid":"s-0001","timestamp":"2026-08-01T10:02:00.000Z"}
{"type":"custom-title","customTitle":"QR login revamp","sessionId":"11111111-aaaa-bbbb-cccc-000000000001"}
{"type":"wibble-experimental","payload":{"note":"unknown line type, must be counted"}}
+{"type":"atis-latch","sessionId":"11111111-aaaa-bbbb-cccc-000000000001","atis":true}
+{"type":"bridge-session","sessionId":"11111111-aaaa-bbbb-cccc-000000000001","bridgeSessionId":"bridge-fixture","lastSequenceNum":42,"ownerAccountUuid":"account-fixture","ownerOrganizationUuid":"organization-fixture"}
diff --git a/crates/wake/assets/icons/brush-cleaning.svg b/crates/wake/assets/icons/brush-cleaning.svg
new file mode 100644
index 0000000..6888526
--- /dev/null
+++ b/crates/wake/assets/icons/brush-cleaning.svg
@@ -0,0 +1,16 @@
+<svg
+ 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="m16 22-1-4" />
+ <path d="M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1" />
+ <path d="M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z" />
+ <path d="m8 22 1-4" />
+</svg>
diff --git a/crates/wake/assets/icons/sliders-horizontal.svg b/crates/wake/assets/icons/sliders-horizontal.svg
new file mode 100644
index 0000000..819f80c
--- /dev/null
+++ b/crates/wake/assets/icons/sliders-horizontal.svg
@@ -0,0 +1,21 @@
+<svg
+ 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="M10 5H3" />
+ <path d="M12 19H3" />
+ <path d="M14 3v4" />
+ <path d="M16 17v4" />
+ <path d="M21 12h-9" />
+ <path d="M21 19h-5" />
+ <path d="M21 5h-7" />
+ <path d="M8 10v4" />
+ <path d="M8 12H3" />
+</svg>
diff --git a/crates/wake/locales/zh-Hans.json b/crates/wake/locales/zh-Hans.json
index 9133289..5204588 100644
--- a/crates/wake/locales/zh-Hans.json
+++ b/crates/wake/locales/zh-Hans.json
@@ -1,8 +1,7 @@
{
- "$name": "简体中文",
- "({} in remote mirrors)": "(其中远程镜像 {})",
" Copy Session ID": " 拷贝会话 ID",
" Export as Markdown": " 导出为 Markdown",
+ "$name": "简体中文",
"%-I:%M %p": "%H:%M",
"%B": "%-m月",
"%B %Y": "%Y年%-m月",
@@ -10,8 +9,13 @@
"%b %-d": "%-m月%-d日",
"%b %-d, %Y": "%Y年%-m月%-d日",
"%b %Y": "%Y年%-m月",
+ "({} in remote mirrors)": "(其中远程镜像 {})",
+ "1 year ago": "1 年前",
"12 AM": "凌晨 12 点",
"12 PM": "中午 12 点",
+ "180 days ago": "180 天前",
+ "30 days ago": "30 天前",
+ "90 days ago": "90 天前",
"About": "关于",
"About Wake": "关于 Wake",
"Active days": "活跃天数",
@@ -27,6 +31,7 @@
"Agents": "Agent",
"All Sessions": "全部会话",
"All your AI agent sessions, in one place.": "所有 AI agent 会话,集中在一处。",
+ "Any time": "不限",
"Appearance": "外观",
"Ascending": "升序",
"Building your library": "正在建立会话库",
@@ -41,10 +46,13 @@
"Check for Updates": "检查更新",
"Check for Updates…": "检查更新…",
"Checking GitHub Releases…": "正在检查 GitHub Releases…",
+ "Checking local files…": "正在检查本机文件…",
"Checking…": "正在检查…",
"Choose": "选择",
"Choose a folder": "选择文件夹",
"Choose where Wake looks for local agent sessions.": "选择 Wake 查找本地 agent 会话的位置。",
+ "Clean Up Sessions": "清理会话",
+ "Cleanup history": "清理记录",
"Close": "关闭",
"Close Window": "关闭窗口",
"Command line": "命令行",
@@ -79,10 +87,11 @@
"Date updated": "更新时间",
"Delete failed: {}": "删除失败:{}",
"Delete this session tree?": "删除此会话树?",
- "Delete this session?": "删除此会话?",
+ "Delete this session?": "删除此会话?",
"Descending": "降序",
"Disable host": "停用主机",
"Disable location": "停用位置",
+ "Done": "完成",
"Earlier this week": "本周早些时候",
"Edit": "编辑",
"Edit location": "编辑位置",
@@ -92,8 +101,10 @@
"Enter an absolute folder path": "请输入绝对路径",
"Export failed": "导出失败",
"Exported": "已导出",
+ "Failed": "失败",
"Failed to parse {} session data: {}": "解析 {} 会话数据失败:{}",
"File": "文件",
+ "Filter": "筛选",
"First {} characters": "前 {} 个字符",
"Folder": "文件夹",
"Folder not found": "找不到文件夹",
@@ -115,6 +126,7 @@
"Just now": "刚刚",
"Keep Wake up to date.": "保持 Wake 为最新版本。",
"Language": "语言",
+ "File size": "文件大小",
"Last 7 days": "最近 7 天",
"Less": "少",
"Let your coding agents look up your past sessions from Wake.": "让你的 coding agent 从 Wake 查阅过往会话。",
@@ -146,6 +158,7 @@
"Most active on {}": "最常在{}",
"Move to Recycle Bin": "移到回收站",
"Move to Trash": "移到废纸篓",
+ "Needs attention": "需核对",
"New this week": "本周新增",
"Next view": "下一个视图",
"No activity": "没有活动",
@@ -156,12 +169,15 @@
"No remote hosts yet. Add one to mirror its sessions into Wake.": "还没有远程主机。添加一台即可把它的会话镜像进 Wake。",
"No results for \"{}\"": "没有找到 \"{}\"",
"No session selected": "未选择会话",
+ "No sessions match these filters": "没有符合筛选条件的会话",
"No terminal application found on PATH": "PATH 中没有找到终端应用",
"No tool calls": "无工具调用",
"No {} adapter is available for this session path.": "此会话路径没有可用的 {} 适配器。",
"Not detected": "未检测到",
"Not found next to the Wake app — reinstall Wake": "没在 Wake 应用旁边找到 —— 重装 Wake",
+ "Not started": "未开始",
"Only the local file is removed — Codex's own records stay intact.": "只会删除本地文件 —— Codex 自己的记录不受影响。",
+ "Open system trash": "打开系统废纸篓",
"Open this session": "打开此会话",
"Open this session in {}": "在 {} 中打开此会话",
"Open this session in…": "打开此会话于…",
@@ -199,6 +215,7 @@
"Remove {}?": "移除 {}?",
"Restore defaults": "恢复默认",
"Restore failed": "恢复失败",
+ "Restored": "已还原",
"Resume failed": "恢复失败",
"Reveal in File Explorer": "在文件资源管理器中显示",
"Reveal in File Manager": "在文件管理器中显示",
@@ -238,6 +255,7 @@
"Sort by {} · {}": "排序:{} · {}",
"Star": "收藏",
"Starred": "已收藏",
+ "Stop after current session": "完成当前会话后停止",
"Storage": "存储",
"Sun": "周日",
"Sundays": "周日",
@@ -274,6 +292,7 @@
"Unstar": "取消收藏",
"Updated {}": "更新于 {}",
"Updates": "更新",
+ "Verify in system trash": "请在系统废纸篓中核对",
"Version {}": "版本 {}",
"View Update": "查看更新",
"Wake Settings": "Wake 设置",
@@ -316,5 +335,112 @@
"{}% vs last week": "较上周 {}%",
"{}-day streak": "连续 {} 天",
"↑↓ navigate": "↑↓ 切换",
- "↩ open": "↩ 打开"
+ "↩ open": "↩ 打开",
+ "Select sessions to clean up": "选择需要清理的会话",
+ "{} selected · {} sessions · {}": "已选 {} 项 · {} 个会话 · {}",
+ "Exclude": "排除",
+ "Exclude starred": "排除收藏",
+ "Exclude pinned": "排除置顶",
+ "Applies to the session and its nested sessions.": "包含根会话及其子会话。",
+ "Unavailable": "无法清理",
+ "Exclude unavailable": "排除无法清理",
+ "Hide sessions that cannot be deleted.": "隐藏无法删除的会话。",
+ "Select all ({})": "全选({})",
+ "Select all": "全选",
+ "{} unavailable": "{} 个无法清理",
+ "{} available for cleanup": "可清理 {}",
+ "Individual cleanup unsupported": "不支持单独清理",
+ "Remote · read-only": "远程会话仅可读取",
+ "Shared session files": "文件由多个会话共享",
+ "Source file missing": "源文件缺失",
+ "Source disabled": "来源未启用",
+ "Session tree unverified": "父子关系未确认",
+ "File ownership unverified": "文件归属未确认",
+ "Unrecognized session format": "会话格式未识别",
+ "Select all {} cleanable sessions": "全选 {} 个可清理的会话",
+ "File size unavailable": "无法确定独立会话文件的大小",
+ "No cleanable sessions in these results": "当前结果中没有可清理的会话",
+ "Remote sessions are read-only": "远程会话仅支持读取。",
+ "This source does not support independent file cleanup": "此来源不支持独立删除会话文件。",
+ "Files are shared with another session": "文件与其他会话共享,无法独立删除。",
+ "Source file is missing": "原始文件已不存在。",
+ "Source is not enabled": "此来源尚未启用。",
+ "The complete session tree could not be verified": "无法确认完整的父子会话关系。",
+ "File ownership could not be verified": "无法确认文件归属或路径包含链接。",
+ "Includes a starred session": "包含已收藏的会话",
+ "Includes a pinned session": "包含已置顶的会话",
+ "Wake cannot read part of this session's format.": "Wake 暂时无法识别此会话中的部分记录格式。",
+ "This session changed. Refresh the list and try again.": "此会话已发生变化,请刷新列表后重试。",
+ "This session is no longer available. Refresh the list.": "此会话已不存在,请刷新列表。",
+ "Unable to clean up these sessions": "暂时无法清理所选会话",
+ "The selected sessions could not be verified. No files were moved.": "所选会话未通过检查,文件尚未移动。请查看下方原因。",
+ "Will be skipped": "将跳过",
+ "Stopping after the current session…": "完成当前会话后停止…",
+ "Moving files… {} / {}": "正在移动文件… {0} / {1}",
+ "Checking sessions… {} / {}": "正在检查会话… {0} / {1}",
+ "{} selected · {}": "已选 {0} 项 · {1}",
+ "Clear filters": "清除筛选",
+ "{} · {} · approx. {}": "{0} · {1} · 约 {2}",
+ "Search agents or projects": "搜索 Agent 或项目",
+ "Sources": "来源",
+ "Clear search": "清除搜索",
+ "No matching agents or projects": "没有匹配的 Agent 或项目",
+ "Back": "返回",
+ "Back to cleanup list": "返回清理列表",
+ "Source files ({})": "源文件({})",
+ "Moved to Trash": "已移到废纸篓",
+ "Partially restored": "部分已还原",
+ "Partially completed": "部分完成",
+ "Interrupted": "已中断",
+ "Cleanup details": "清理详情",
+ "{} cleanup": "{} 次清理",
+ "{} cleanups": "{} 次清理",
+ "No cleanup history yet": "暂无清理记录",
+ "Your cleanup results will appear here.": "清理完成后,记录会显示在这里。",
+ "{} + {} more": "{},另有 {} 项",
+ "This cleanup was interrupted. Review the file details before continuing.": "这次清理已中断,请先核对下方文件详情。",
+ "Space is freed when the files are removed from Trash.": "从废纸篓中删除这些文件后,才会释放磁盘空间。",
+ "Checking files…": "正在检查文件…",
+ "Check restored files": "检查已还原文件",
+ "Update session list": "更新会话列表",
+ "Files were moved, but Wake could not update its session list.": "文件已移动,但 Wake 未能更新会话列表。",
+ "File locations ({})": "文件位置({})",
+ "These sessions are available in Wake again.": "这些会话已恢复,可在 Wake 中查看。",
+ "Session files were moved to the system trash.": "会话文件已移到系统废纸篓。",
+ "Some sessions have been restored to Wake.": "部分会话已恢复到 Wake。",
+ "Review the affected sessions below.": "请查看下方需要处理的会话。",
+ "No session files were moved.": "没有移动任何会话文件。",
+ "Delete": "删除",
+ "History": "历史记录",
+ "Clear": "清除",
+ "Clear selection": "取消全选",
+ "Delete {} sessions?": "删除 {} 个会话?",
+ "Local files · About {}": "本机文件 · 约 {}",
+ "Agents may no longer resume these sessions.": "原工具可能无法继续这些会话。",
+ "You can restore files from Trash. Space is freed after emptying it.": "可从废纸篓恢复文件,清空后才释放空间。",
+ "You can restore files from the Recycle Bin. Space is freed after emptying it.": "可从回收站恢复文件,清空后才释放空间。",
+ "{} items will be skipped.": "将跳过 {} 项。",
+ "To delete": "将删除",
+ "Confirm": "确认",
+ "Sessions restored": "会话已恢复",
+ "Session list updated": "会话列表已更新",
+ "Some sessions could not be updated. Review the errors below.": "部分会话未能更新,请查看下方原因。",
+ "Files in Trash changed; restore them manually": "废纸篓中的文件已发生变化,请手动恢复。",
+ "File identity is unavailable; restore files manually": "无法确认文件身份,请手动恢复。",
+ "Files are no longer in Trash. They may have been permanently deleted.": "文件已不在废纸篓中,可能已被永久删除。",
+ "Original folder is missing; recreate it before restoring": "原文件夹已不存在,请重新创建后再恢复。",
+ "Original folder contains a symbolic link": "原文件夹包含符号链接,无法安全恢复。",
+ "Some restored files differ from the deleted files. Check the file locations below.": "部分恢复文件与删除前不一致,请检查下方文件位置。",
+ "Network locations cannot be moved to the Recycle Bin": "网络位置的文件无法移入回收站",
+ "This location does not support safe recycling": "此位置不支持安全移入回收站",
+ "Network location": "网络位置",
+ "Recycling unavailable": "不支持回收站",
+ "The original location contains different files. Nothing was overwritten.": "原位置已有其他文件,未覆盖任何文件。",
+ "A file that was not deleted is missing": "未被删除的关联文件丢失,无法恢复完整会话。",
+ "Restored files changed before verification": "恢复的文件在验证前发生了变化。",
+ "No sessions could be restored. Review the errors below.": "未能恢复会话,请查看下方原因。",
+ "Check": "检查",
+ "To restore, choose Put Back in Trash, then click Check.": "要恢复文件,请在废纸篓中选择“放回原处”,然后点击检查。",
+ "Restore the files in your system trash, then click Check.": "在系统回收站中还原文件,然后点击检查。",
+ "No restored sessions found. Check the file locations below.": "未找到已还原的会话,请检查下方文件位置。"
}
diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rs
index 64c3a12..16a9756 100644
--- a/crates/wake/src/assets.rs
+++ b/crates/wake/src/assets.rs
@@ -85,6 +85,8 @@ icons!(
"trash-2",
"search",
"arrow-up-down",
+ "brush-cleaning",
+ "sliders-horizontal",
"check",
"copy",
"pin-filled",
diff --git a/crates/wake/src/i18n.rs b/crates/wake/src/i18n.rs
index 6705143..7f07ac6 100644
--- a/crates/wake/src/i18n.rs
+++ b/crates/wake/src/i18n.rs
@@ -617,6 +617,10 @@ mod tests {
fn packs_have_no_keys_without_a_call_site() {
const SOURCES: &[&str] = &[
include_str!("workbench.rs"),
+ include_str!("workbench/cleanup.rs"),
+ include_str!("workbench/cleanup/filter.rs"),
+ include_str!("workbench/cleanup/history.rs"),
+ include_str!("workbench/cleanup/rows.rs"),
include_str!("settings.rs"),
include_str!("main.rs"),
include_str!("markdown_links.rs"),
@@ -656,6 +660,7 @@ mod tests {
"Session moved to ",
"{} sessions moved to ",
"The session file will be moved to ",
+ "You can restore files from ",
"Show in ",
"Reveal in ",
];
diff --git a/crates/wake/src/settings.rs b/crates/wake/src/settings.rs
index 6152d2d..fbb0f97 100644
--- a/crates/wake/src/settings.rs
+++ b/crates/wake/src/settings.rs
@@ -13,9 +13,9 @@ use wake_core::models::AgentId;
use crate::format::tilde_path;
use crate::ui::{
- overlay_layers, show_in_fm, BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY, FONT_HEADING,
- FONT_LABEL, FONT_TITLE, RADIUS_BUTTON, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL, SPACE_XS,
- SPACE_XXL,
+ action_button, overlay_layers, show_in_fm, BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY,
+ FONT_HEADING, FONT_LABEL, FONT_TITLE, RADIUS_BUTTON, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL,
+ SPACE_XS, SPACE_XXL,
};
use crate::update::{self, UpdateStatus};
use crate::workbench::{DataSourceRow, OpenAbout, OpenSettings, OpenUpdates, Workbench};
@@ -79,7 +79,7 @@ pub(crate) fn settings_button(button: Button, cx: &App) -> Button {
/// 设置页里真正需要用户继续完成的主操作。保持 6px 圆角,但使用中号高度、
/// primary 填充和轻阴影,让它与普通的重试 / 再检查动作拉开层级。
-fn settings_primary_button(button: Button, cx: &App) -> Button {
+pub(crate) fn settings_primary_button(button: Button, cx: &App) -> Button {
let theme = cx.theme();
button
.custom(
@@ -93,6 +93,7 @@ fn settings_primary_button(button: Button, cx: &App) -> Button {
.border_1()
.border_color(theme.primary)
.rounded(RADIUS_BUTTON)
+ .map(action_button)
}
/// Settings 各页顶部的标题 + 一句说明(版式只写一次:SPACE_XXL 边距、
@@ -1084,6 +1085,11 @@ impl SettingsView {
UpdateStatus::Failed => t("Try Again"),
};
let button = Button::new("settings-check-updates")
+ .icon(icon(if update_available {
+ "icons/download.svg"
+ } else {
+ "icons/refresh-cw.svg"
+ }))
.label(button_label)
.disabled(checking);
let mut action = if update_available {
diff --git a/crates/wake/src/theme.rs b/crates/wake/src/theme.rs
index 49aa6ca..7d53cdd 100644
--- a/crates/wake/src/theme.rs
+++ b/crates/wake/src/theme.rs
@@ -244,6 +244,10 @@ pub fn apply_wake_theme(cx: &mut App) {
theme.overlay = gpui::hsla(0., 0., 0., 0.25);
}
+ // Checkbox 的边框和禁用态读取 colors.primary,选中填充读取
+ // tokens.primary;同步背景 token,避免蓝色描边包着组件默认的黑色填充。
+ theme.tokens.primary = theme.primary.into();
+
// 系统字体与 macOS 圆角习惯。`.SystemUIFont` 是 gpui 各平台后端都认的
// 别名(macOS 解到 .AppleSystemUIFont,Windows 的 DirectWrite 后端解到
// 系统 UI 字体);写死 `.AppleSystemUIFont` 会让非 mac 平台每个字重都
diff --git a/crates/wake/src/ui.rs b/crates/wake/src/ui.rs
index f7c761f..7e43d00 100644
--- a/crates/wake/src/ui.rs
+++ b/crates/wake/src/ui.rs
@@ -5,10 +5,12 @@
use std::collections::HashSet;
use gpui::{
- div, px, AnyElement, App, Global, Hsla, InteractiveElement as _, IntoElement, MouseButton,
+ div, px, AnyElement, App, Div, Global, Hsla, InteractiveElement as _, IntoElement, MouseButton,
Pixels, Styled, Window, WindowId,
};
-use gpui_component::{dialog::Dialog, Root, WindowExt as _};
+use gpui_component::{
+ button::Button, dialog::Dialog, h_flex, ActiveTheme as _, Root, Sizable as _, WindowExt as _,
+};
/// 产品展示名(About)——medium
pub const FONT_DISPLAY: Pixels = px(28.);
@@ -68,8 +70,8 @@ file_manager_copy!("File Explorer");
file_manager_copy!("File Manager");
// 系统回收站的平台名词(macOS 与 freedesktop 都叫 Trash,Windows 是
-// Recycle Bin)与由它派生的五句删除文案。名词只写一次、整句由 concat!
-// 拼出:五处分别手写 cfg! 链的话,没有任何东西能拦住它们说不同的词
+// Recycle Bin)与由它派生的删除文案。名词只写一次、整句由 concat!
+// 拼出:各处分别手写 cfg! 链的话,没有任何东西能拦住它们说不同的词
// ——与 wake-core 各平台 trash_existing 的失败文案也得是同一个词。
//
// 确认框内容活在 **dialog builder 闭包**里、对话框开着时每帧重跑,`t()` 是
@@ -92,6 +94,14 @@ macro_rules! trash_copy {
pub fn trash_body() -> &'static str {
crate::i18n::t($body)
}
+ /// 批量清理确认的恢复方式与空间回收条件。
+ pub fn cleanup_trash_hint() -> &'static str {
+ crate::i18n::t(concat!(
+ "You can restore files from ",
+ $body,
+ ". Space is freed after emptying it."
+ ))
+ }
/// 删除确认框正文首句
pub fn trash_confirm_body() -> &'static str {
crate::i18n::t(concat!(
@@ -168,11 +178,42 @@ pub const ROW_HEIGHT: Pixels = px(32.);
/// 配 FONT_CAPTION 形成侧栏纵向层级(macOS 原生侧栏惯例)
pub const ROW_HEIGHT_SUB: Pixels = px(26.);
+/// 侧栏搜索入口与局部搜索输入共用的外壳;文字输入本身不再叠加组件默认边框。
+pub fn search_field_frame(cx: &App) -> Div {
+ let theme = cx.theme();
+ h_flex()
+ .h(ROW_HEIGHT)
+ .px(SIDEBAR_EDGE)
+ .gap(SPACE_SM)
+ .rounded(theme.radius)
+ .bg(theme.secondary)
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .hover(|s| {
+ s.bg(theme.secondary_hover)
+ .text_colored(theme.foreground, FONT_CAPTION)
+ })
+}
+
// ---------------- 圆角 ----------------
// 四档见 DESIGN.md:面板 12 = `theme.radius_lg`,列表与侧栏选择 8 = `theme.radius`
// (这两档走主题 token),其余三档无 token,在此定名以免散成魔法数字。
/// 按钮圆角。**用户钉死 6px,勿改**
pub const RADIUS_BUTTON: Pixels = px(6.);
+
+/// Page and dialog actions use fixed pixels; the library's rem-based Small
+/// preset becomes 21px at Wake's 14px rem size and crowds mixed-size footers.
+/// Normalize the inner label/icon/gap too: Button renders those in a nested
+/// element, so setting the outer text_size alone does not override its size preset.
+pub fn action_button(button: Button) -> Button {
+ button
+ .small()
+ .h(BUTTON_ACTION_H)
+ .px(SPACE_MD)
+ .text_size(FONT_CAPTION)
+ .rounded(RADIUS_BUTTON)
+}
+
/// 快捷键标签
pub const RADIUS_KBD: Pixels = px(5.);
/// 小胶囊 badge(项目名 / model / source / 各处计数共用)
@@ -191,6 +232,8 @@ pub const RADIUS_CELL: Pixels = px(2.);
pub const BUTTON_SM_PX: Pixels = px(10.5);
/// gpui-component `Size::Small` 按钮高度(h_6 = 24),手排胶囊钮取齐用
pub const BUTTON_SM_H: Pixels = px(24.);
+/// 页面与确认框操作按钮的高度,避免与组件的 rem 尺寸混用。
+pub const BUTTON_ACTION_H: Pixels = px(32.);
// ---------------- 交互态文字 ----------------
diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rs
index b259438..70af3bf 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -15,6 +15,7 @@
// finish review, the verdict, and DESIGN.md
// ============================================================================
use crate::i18n::t;
+mod cleanup;
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
@@ -101,6 +102,58 @@ fn icon(path: &'static str) -> Icon {
Icon::empty().path(path)
}
+/// Shared identity header for library and full-page views.
+/// Each view supplies its existing horizontal inset; type, height and action alignment stay shared.
+fn library_header(
+ id: &'static str,
+ title: impl Into<SharedString>,
+ subtitle: impl Into<SharedString>,
+ inset: Pixels,
+ actions: Option<AnyElement>,
+ cx: &App,
+) -> impl IntoElement {
+ let title: SharedString = title.into();
+ let subtitle: SharedString = subtitle.into();
+ v_flex()
+ .id(id)
+ .w_full()
+ .h(LIBRARY_IDENTITY_HEIGHT)
+ .flex_shrink_0()
+ .window_control_area(WindowControlArea::Drag)
+ .px(inset)
+ .justify_center()
+ .child(
+ h_flex()
+ .w_full()
+ .items_start()
+ .justify_between()
+ .gap(SPACE_SM)
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(2.))
+ .child(
+ div()
+ .truncate()
+ .text_size(FONT_TITLE)
+ .font_semibold()
+ .child(title),
+ )
+ .child(
+ div()
+ .truncate()
+ .text_size(FONT_LABEL)
+ .text_color(cx.theme().muted_foreground)
+ .child(subtitle),
+ ),
+ )
+ .when_some(actions, |row, actions| {
+ row.child(div().flex_shrink_0().pt(px(2.)).child(actions))
+ }),
+ )
+}
+
/// 起一条后台扫描线程。启动时的自动扫描(full=false)与用户主动重扫(full=true)
/// 共用;返回的 Result 由 run_scan 的终态事件代为上报,这里只需丢弃。
/// 远程同步不在这条线程上——它走 Workbench::spawn_remote_sync 的独立线程,
@@ -1000,6 +1053,47 @@ mod session_group_tests {
}
}
+ #[test]
+ fn cleanup_preview_completes_both_loads_of_the_same_session() {
+ for preview_first in [false, true] {
+ let mut current = Some(super::DetailState::loading(session("same", 0, false), None));
+ let library_load = current.as_ref().unwrap().load_id;
+ // Enter cleanup before the library transcript finishes, then preview it.
+ let mut saved = current.take();
+ current = Some(super::DetailState::loading(session("same", 0, false), None));
+ let preview_load = current.as_ref().unwrap().load_id;
+ let completions = if preview_first {
+ [preview_load, library_load]
+ } else {
+ [library_load, preview_load]
+ };
+ for load_id in completions {
+ super::detail_for_load(&mut current, &mut saved, "same", load_id)
+ .unwrap()
+ .loading = false;
+ }
+ assert!(!current.as_ref().unwrap().loading);
+ // The cleanup toggle restores the original library state.
+ current = saved.take();
+ assert!(
+ !current.as_ref().unwrap().loading,
+ "Library reader stayed loading"
+ );
+ }
+ }
+
+ #[test]
+ fn replaced_detail_ignores_an_older_load_of_the_same_session() {
+ let old = super::DetailState::loading(session("same", 0, false), None);
+ let mut current = Some(super::DetailState::loading(
+ session("same", 0, false),
+ Some(12),
+ ));
+ let mut saved = None;
+ assert!(super::detail_for_load(&mut current, &mut saved, "same", old.load_id).is_none());
+ assert_eq!(current.as_ref().unwrap().jump_seq, Some(12));
+ }
+
#[test]
fn date_labels_respect_calendar_week_boundaries() {
let wednesday = NaiveDate::from_ymd_opt(2026, 9, 2).unwrap();
@@ -1515,6 +1609,7 @@ fn toggle_expanded_row(rows: &mut HashSet<usize>, ix: usize) {
}
struct DetailState {
+ load_id: u64,
meta: SessionMeta,
/// 过滤后的可见消息。Rc 让行渲染以引用计数克隆代替整条消息深拷贝
transcript: Rc<Vec<TranscriptMessage>>,
@@ -1538,6 +1633,45 @@ struct DetailState {
image_action_feedback: [Option<ImageActionFeedback>; 2],
}
+impl DetailState {
+ fn loading(meta: SessionMeta, jump_seq: Option<i64>) -> Self {
+ static NEXT_LOAD: AtomicU64 = AtomicU64::new(0);
+ Self {
+ load_id: NEXT_LOAD.fetch_add(1, Ordering::Relaxed),
+ meta,
+ transcript: Rc::new(Vec::new()),
+ loading: true,
+ error: None,
+ // Bottom 对齐 = 聊天语义:打开落在最新消息,向上翻历史
+ msg_list: gpui::ListState::new(0, gpui::ListAlignment::Bottom, px(512.)),
+ expanded_tools: HashSet::new(),
+ expanded_thinking: HashSet::new(),
+ jump_seq,
+ images: Vec::new(),
+ zoom: None,
+ image_action_feedback: [None; 2],
+ }
+ }
+}
+
+fn detail_for_load<'a>(
+ current: &'a mut Option<DetailState>,
+ saved: &'a mut Option<DetailState>,
+ key: &str,
+ load_id: u64,
+) -> Option<&'a mut DetailState> {
+ // Library and cleanup may load the same session concurrently. The response
+ // belongs to the state that started it, even after that state moves slots.
+ current
+ .as_mut()
+ .filter(|detail| detail.meta.key == key && detail.load_id == load_id)
+ .or_else(|| {
+ saved
+ .as_mut()
+ .filter(|detail| detail.meta.key == key && detail.load_id == load_id)
+ })
+}
+
#[derive(Clone, Copy, PartialEq, Eq)]
enum ImageAction {
Copy,
@@ -2026,6 +2160,7 @@ pub struct Workbench {
/// Insights 页(侧栏底部入口):打开时替换中栏+右栏。与其他导航目的地
/// 互斥(侧栏单选模型);数据在 open/refresh 时后台重算,Rc 免深拷贝
insights_open: bool,
+ cleanup: cleanup::CleanupState,
insights: Option<Rc<InsightsData>>,
insights_loading: bool,
insights_range: InsightsRange,
@@ -2354,6 +2489,7 @@ impl Workbench {
detail: None,
image_action_feedback_generation: 0,
insights_open: false,
+ cleanup: cleanup::CleanupState::default(),
insights: None,
insights_loading: false,
insights_range: InsightsRange::Hour,
@@ -2367,6 +2503,7 @@ impl Workbench {
_subs: subs,
};
this.load_open_in_prefs();
+ this.load_cleanup_prefs();
this.refresh(cx);
this._calendar_task = Some(cx.spawn(async move |this, cx| loop {
cx.background_executor()
@@ -2526,6 +2663,7 @@ impl Workbench {
/// 侧栏底部入口。再点一次(或点任意导航行)退回会话列表
fn toggle_insights(&mut self, cx: &mut Context<Self>) {
+ self.leave_cleanup(cx);
if self.insights_open {
self.insights_open = false;
cx.notify();
@@ -3854,6 +3992,10 @@ impl Workbench {
window: &mut Window,
cx: &mut Context<Self>,
) {
+ // Hidden library selection restoration must not replace cleanup preview.
+ if self.cleanup.open {
+ return;
+ }
let ix = match ev {
ListEvent::Select(ix) | ListEvent::Confirm(ix) => *ix,
ListEvent::Cancel => return,
@@ -4132,23 +4274,15 @@ impl Workbench {
window: &mut Window,
cx: &mut Context<Self>,
) {
+ if jump_seq.is_some() {
+ self.leave_cleanup(cx);
+ }
let Ok(Some(meta)) = self.store.get_session(key) else {
return;
};
- self.detail = Some(DetailState {
- meta: meta.clone(),
- transcript: Rc::new(Vec::new()),
- loading: true,
- error: None,
- // Bottom 对齐 = 聊天语义:打开落在最新消息,向上翻历史
- msg_list: gpui::ListState::new(0, gpui::ListAlignment::Bottom, px(512.)),
- expanded_tools: HashSet::new(),
- expanded_thinking: HashSet::new(),
- jump_seq,
- images: Vec::new(),
- zoom: None,
- image_action_feedback: [None; 2],
- });
+ let detail = DetailState::loading(meta.clone(), jump_seq);
+ let load_id = detail.load_id;
+ self.detail = Some(detail);
// 搜索路径:中栏列表同步选中并滚到该会话。
// 列表点击路径(jump=None)不走——List 点击自带选中,再滚会跳视口
if jump_seq.is_some() {
@@ -4167,43 +4301,47 @@ impl Workbench {
cx.spawn_in(window, async move |this, cx| {
let (key, result) = task.await;
this.update_in(cx, |this, _window, cx| {
- if let Some(detail) = &mut this.detail {
- if key == detail.meta.key {
- detail.loading = false;
- match result {
- Ok((messages, images)) => {
- detail.msg_list = gpui::ListState::new(
- messages.len(),
- gpui::ListAlignment::Bottom,
- px(512.),
- );
- // 搜索跳转:seq → 可见消息下标,滚到视口顶。
- // FTS 命中的行可能被详情过滤(如空文本),用 >= 落到
- // 其后最近一条;找不到(尾部被滤)则保持默认落底。
- // jump_seq 归一为落点消息的实际 seq——高亮按精确相等
- // 渲染,不归一则命中被滤时滚动与高亮指向不同行
- if let Some(seq) = detail.jump_seq {
- if let Some(ix) = messages.iter().position(|m| m.seq >= seq) {
- detail.jump_seq = Some(messages[ix].seq);
- detail.msg_list.scroll_to(gpui::ListOffset {
- item_ix: ix,
- offset_in_item: px(0.),
- });
- }
+ let detail = detail_for_load(
+ &mut this.detail,
+ &mut this.cleanup.saved_detail,
+ &key,
+ load_id,
+ );
+ if let Some(detail) = detail {
+ detail.loading = false;
+ match result {
+ Ok((messages, images)) => {
+ detail.msg_list = gpui::ListState::new(
+ messages.len(),
+ gpui::ListAlignment::Bottom,
+ px(512.),
+ );
+ // 搜索跳转:seq → 可见消息下标,滚到视口顶。
+ // FTS 命中的行可能被详情过滤(如空文本),用 >= 落到
+ // 其后最近一条;找不到(尾部被滤)则保持默认落底。
+ // jump_seq 归一为落点消息的实际 seq——高亮按精确相等
+ // 渲染,不归一则命中被滤时滚动与高亮指向不同行
+ if let Some(seq) = detail.jump_seq {
+ if let Some(ix) = messages.iter().position(|m| m.seq >= seq) {
+ detail.jump_seq = Some(messages[ix].seq);
+ detail.msg_list.scroll_to(gpui::ListOffset {
+ item_ix: ix,
+ offset_in_item: px(0.),
+ });
}
- detail.transcript = Rc::new(messages);
- detail.images = images;
- detail.zoom = None;
- detail.error = None;
- }
- Err(error) => {
- detail.transcript = Rc::new(Vec::new());
- detail.images.clear();
- detail.zoom = None;
- detail.msg_list =
- gpui::ListState::new(0, gpui::ListAlignment::Bottom, px(512.));
- detail.error = Some(error.into());
}
+ detail.transcript = Rc::new(messages);
+ detail.images = images;
+ detail.zoom = None;
+ detail.error = None;
+ }
+ Err(error) => {
+ detail.transcript = Rc::new(Vec::new());
+ detail.images.clear();
+ detail.zoom = None;
+ detail.msg_list =
+ gpui::ListState::new(0, gpui::ListAlignment::Bottom, px(512.));
+ detail.error = Some(error.into());
}
}
}
@@ -4223,6 +4361,7 @@ impl Workbench {
favorite: bool,
cx: &mut Context<Self>,
) {
+ self.leave_cleanup(cx);
self.selected_agent = agent;
self.selected_project = project;
self.favorite_only = favorite;
@@ -4553,6 +4692,7 @@ impl Workbench {
detail.meta.favorite = v;
self.refresh(cx);
self.select_list_key(&key, false, window, cx);
+ self.refresh_cleanup_flags(&key, window, cx);
}
}
@@ -4564,6 +4704,7 @@ impl Workbench {
detail.meta.pinned = v;
self.refresh(cx);
self.select_list_key(&key, true, window, cx);
+ self.refresh_cleanup_flags(&key, window, cx);
}
}
@@ -4769,7 +4910,8 @@ impl Workbench {
let all_active = self.selected_agent.is_none()
&& self.selected_project.is_none()
&& !self.favorite_only
- && !self.insights_open;
+ && !self.insights_open
+ && !self.cleanup.open;
// 常态沉默,仅刷新中/监听失效时出现;None 时状态栏整行不渲染。
// 文案在此按 scan 现算,不另存字段——存下来就会有第二个写入点要维护
let note = if self.scan.scanning {
@@ -4864,22 +5006,11 @@ impl Workbench {
.child(
div().flex_shrink_0().px(SIDEBAR_EDGE).pb(SPACE_MD).child(
h_flex().gap(SPACE_SM).child(
- h_flex()
+ search_field_frame(cx)
.id("sidebar-search")
.flex_1()
.min_w_0()
- .h(ROW_HEIGHT)
- .px(SIDEBAR_EDGE)
- .gap(SPACE_SM)
- .rounded(theme.radius)
.cursor_pointer()
- .bg(theme.secondary)
- .text_size(FONT_CAPTION)
- .text_color(theme.muted_foreground)
- .hover(|s| {
- s.bg(theme.secondary_hover)
- .text_colored(theme.foreground, FONT_CAPTION)
- })
.active(|s| {
s.bg(theme.secondary_active)
.text_colored(theme.foreground, FONT_CAPTION)
@@ -4933,12 +5064,12 @@ impl Workbench {
} else {
None
},
- self.favorite_only,
+ self.favorite_only && !self.cleanup.open,
RowLevel::Primary,
cx.listener(|this, _, _window, cx| {
// 取消收藏过滤时 agent/project 必已是 None(互斥),
// 两个方向都归 set_scope
- let favorite = !this.favorite_only;
+ let favorite = this.cleanup.open || !this.favorite_only;
this.set_scope(None, None, favorite, cx);
}),
cx,
@@ -4972,10 +5103,12 @@ impl Workbench {
RowLead::Brand(agent.brand_icon(theme.mode.is_dark())),
agent.display_name(),
Some(*count),
- self.selected_agent == Some(agent),
+ self.selected_agent == Some(agent) && !self.cleanup.open,
RowLevel::Sub,
cx.listener(move |this, _, _window, cx| {
- let next = if this.selected_agent == Some(agent) {
+ let next = if this.selected_agent == Some(agent)
+ && !this.cleanup.open
+ {
None
} else {
Some(agent)
@@ -5004,11 +5137,12 @@ impl Workbench {
RowLead::Icon(icon("icons/folder.svg")),
p.name.clone(),
Some(p.session_count),
- self.selected_project.as_deref() == Some(p.path.as_str()),
+ self.selected_project.as_deref() == Some(p.path.as_str())
+ && !self.cleanup.open,
RowLevel::Sub,
cx.listener(move |this, _, _window, cx| {
- let next = if this.selected_project.as_deref()
- == Some(path.as_str())
+ let next = if !this.cleanup.open
+ && this.selected_project.as_deref() == Some(path.as_str())
{
None
} else {
@@ -5061,6 +5195,21 @@ impl Workbench {
cx.listener(|this, _, _window, cx| this.toggle_insights(cx)),
cx,
))
+ .child(sidebar_tool_btn(
+ "cleanup",
+ t("Clean Up Sessions"),
+ true,
+ icon("icons/brush-cleaning.svg")
+ .with_size(px(14.))
+ .text_color(if self.cleanup.open {
+ theme.primary
+ } else {
+ theme.muted_foreground
+ })
+ .into_any_element(),
+ cx.listener(|this, _, window, cx| this.toggle_cleanup(window, cx)),
+ cx,
+ ))
.child(sidebar_tool_btn(
"settings",
t("Settings"),
@@ -5176,41 +5325,14 @@ impl Workbench {
.h_full()
.flex_shrink_0()
.bg(theme.colors.list)
- .child(
- v_flex()
- .id("list-header")
- .w_full()
- .h(LIBRARY_IDENTITY_HEIGHT)
- .flex_shrink_0()
- .window_control_area(WindowControlArea::Drag)
- .px(SPACE_LG)
- .justify_center()
- .child(
- h_flex()
- .w_full()
- .items_start()
- .justify_between()
- .child(
- v_flex()
- .min_w_0()
- .gap(px(2.))
- .child(
- div()
- .truncate()
- .text_size(FONT_TITLE)
- .font_semibold()
- .child(self.context_title()),
- )
- .child(
- div()
- .text_size(FONT_LABEL)
- .text_color(theme.muted_foreground)
- .child(shown_label),
- ),
- )
- .child(div().flex_shrink_0().pt(px(2.)).child(sort_menu)),
- ),
- )
+ .child(library_header(
+ "list-header",
+ self.context_title(),
+ shown_label,
+ SPACE_LG,
+ Some(sort_menu.into_any_element()),
+ cx,
+ ))
.child(if shown == 0 {
if library_empty && self.scan.scanning {
v_flex()
@@ -5805,32 +5927,14 @@ impl Workbench {
.min_w_0()
.h_full()
.bg(theme.background)
- .child(
- v_flex()
- .id("insights-header")
- .w_full()
- .h(LIBRARY_IDENTITY_HEIGHT)
- .flex_shrink_0()
- .window_control_area(WindowControlArea::Drag)
- .px(SPACE_XXL)
- .justify_center()
- .child(
- v_flex()
- .gap(px(2.))
- .child(
- div()
- .text_size(FONT_TITLE)
- .font_semibold()
- .child(t("Insights")),
- )
- .child(
- div()
- .text_size(FONT_LABEL)
- .text_color(theme.muted_foreground)
- .child(subtitle),
- ),
- ),
- )
+ .child(library_header(
+ "insights-header",
+ t("Insights"),
+ subtitle,
+ SPACE_XXL,
+ None,
+ cx,
+ ))
.child(body)
.into_any_element()
}
@@ -6123,7 +6227,7 @@ impl Workbench {
let delete_entity = export_entity.clone();
// 远程会话只读:Delete 项整个不出现(阶段 1 不做远程删除——本地能
// trash 的只有缓存副本,下次 rsync 就复活,语义是骗人的)
- let menu_is_remote = !meta.host.is_empty();
+ let menu_is_remote = !meta.host.is_empty() || self.cleanup.open;
let more_menu = Button::new("more-actions")
.ghost()
.rounded(RADIUS_BUTTON)
@@ -6204,10 +6308,13 @@ impl Workbench {
crate::tf!("Created {}", abs_date(meta.created_at)).into(),
)
});
- let updated_time: Option<(SharedString, SharedString)> = (meta.updated_at > 0).then(|| {
+ let updated_at = self
+ .cleanup_preview()
+ .map_or(meta.updated_at, |c| c.updated_at);
+ let updated_time: Option<(SharedString, SharedString)> = (updated_at > 0).then(|| {
(
- crate::tf!("Updated {}", smart_time(meta.updated_at)).into(),
- crate::tf!("Updated {}", abs_date(meta.updated_at)).into(),
+ crate::tf!("Updated {}", smart_time(updated_at)).into(),
+ crate::tf!("Updated {}", abs_date(updated_at)).into(),
)
});
let branch: Option<SharedString> =
@@ -6263,6 +6370,20 @@ impl Workbench {
.items_center()
.text_size(FONT_LABEL)
.text_color(theme.muted_foreground)
+ .when(self.cleanup.open, |row| row.child(
+ Button::new("cleanup-back")
+ .ghost()
+ .h(px(28.))
+ .px(SPACE_SM)
+ .text_size(FONT_CAPTION)
+ .rounded(RADIUS_BUTTON)
+ .icon(icon("icons/chevron-left.svg").with_size(px(15.)))
+ .label(t("Back"))
+ .tooltip(t("Back to cleanup list"))
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.close_cleanup_preview(window, cx);
+ }))
+ ))
.child(img(meta.agent.brand_icon(theme.mode.is_dark())).size(px(15.)).flex_shrink_0())
.child(div().flex_shrink_0().child(meta.agent.display_name()))
.child(project_badge)
@@ -6568,6 +6689,7 @@ impl Workbench {
)
.child(div().min_w_0().truncate().child(detail_path)),
)
+ .when(self.cleanup.open, |this| this.child(self.render_cleanup_detail_facts(cx)))
.when(created_time.is_some() || updated_time.is_some(), |this| {
this.child(
h_flex()
@@ -8669,6 +8791,20 @@ impl Render for Workbench {
.id("workbench")
.key_context(KEY_CONTEXT)
.track_focus(&self.focus_handle)
+ .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
+ if event.keystroke.key == "escape"
+ && this.cleanup.open
+ && !window.has_active_dialog(cx)
+ && (!this.cleanup.preview_open
+ || this
+ .detail
+ .as_ref()
+ .is_none_or(|detail| detail.zoom.is_none()))
+ && this.navigate_cleanup_back(window, cx)
+ {
+ cx.stop_propagation();
+ }
+ }))
.on_action(cx.listener(Self::toggle_search))
.on_action(cx.listener(|this, _: &RefreshSessions, window, cx| {
this.refresh_sessions(window, cx)
@@ -8692,7 +8828,9 @@ impl Render for Workbench {
.child(self.render_sidebar(window, cx))
// Insights 是整页目的地:替换中栏+右栏,侧栏导航保持在场
.map(|this| {
- if self.insights_open {
+ if self.cleanup.open {
+ this.child(self.render_cleanup(window, cx))
+ } else if self.insights_open {
this.child(self.render_insights(cx))
} else {
this.child(self.render_session_list(cx))
diff --git a/crates/wake/src/workbench/cleanup.rs b/crates/wake/src/workbench/cleanup.rs
new file mode 100644
index 0000000..f8e1e94
--- /dev/null
+++ b/crates/wake/src/workbench/cleanup.rs
@@ -0,0 +1,1495 @@
+//! Cleanup UI shares the existing sidebar, reader, controls and theme.
+use super::*;
+mod filter;
+mod history;
+mod rows;
+use gpui_component::{checkbox::Checkbox, popover::Popover, Disableable as _};
+use std::sync::atomic::AtomicBool;
+use wake_core::cleanup::{
+ self, CleanupBatch, CleanupCandidate, CleanupEntry, CleanupInventory, CleanupOptions,
+ CleanupReview, CleanupSort, TargetStatus, TimeField, UnavailableSession,
+};
+
+pub(super) struct CleanupState {
+ pub open: bool,
+ options: CleanupOptions,
+ inventory: CleanupInventory,
+ shown: Rc<Vec<CleanupEntry>>,
+ selected: HashSet<String>,
+ focus: Option<String>,
+ pub(super) preview_open: bool,
+ pub(super) saved_detail: Option<DetailState>,
+ filter_input: Option<Entity<InputState>>,
+ filter_query: String,
+ filter_scroll: ScrollHandle,
+ now: i64,
+ loading: bool,
+ busy: bool,
+ executing: bool,
+ progress: usize,
+ progress_total: usize,
+ cancel: Arc<AtomicBool>,
+ task: Option<Task<()>>,
+ error: Option<String>,
+ result: Option<CleanupBatch>,
+ history: Vec<CleanupBatch>,
+ history_open: bool,
+ history_scroll: UniformListScrollHandle,
+ result_scroll: ScrollHandle,
+ expanded_results: HashSet<String>,
+ refresh_after_history: bool,
+ scroll: UniformListScrollHandle,
+}
+impl Default for CleanupState {
+ fn default() -> Self {
+ Self {
+ open: false,
+ options: CleanupOptions::default(),
+ inventory: CleanupInventory::default(),
+ shown: Rc::new(vec![]),
+ selected: HashSet::new(),
+ focus: None,
+ preview_open: false,
+ saved_detail: None,
+ filter_input: None,
+ filter_query: String::new(),
+ filter_scroll: ScrollHandle::new(),
+ now: 0,
+ loading: false,
+ busy: false,
+ executing: false,
+ progress: 0,
+ progress_total: 0,
+ cancel: Arc::new(AtomicBool::new(false)),
+ task: None,
+ error: None,
+ result: None,
+ history: vec![],
+ history_open: false,
+ history_scroll: UniformListScrollHandle::new(),
+ result_scroll: ScrollHandle::new(),
+ expanded_results: HashSet::new(),
+ refresh_after_history: false,
+ scroll: UniformListScrollHandle::new(),
+ }
+ }
+}
+const CLEANUP_DATE_WIDTH: Pixels = px(112.);
+const CLEANUP_SIZE_WIDTH: Pixels = px(88.);
+
+fn bytes(n: u64) -> String {
+ if n == 0 {
+ return "0 B".into();
+ }
+ if n >= 1024 * 1024 * 1024 {
+ format!("{:.2} GB", n as f64 / 1073741824.)
+ } else {
+ crate::format::human_bytes(n as usize)
+ }
+}
+fn sort_label(s: CleanupSort) -> &'static str {
+ match s {
+ CleanupSort::Created => t("Date created"),
+ CleanupSort::Updated => t("Date updated"),
+ CleanupSort::Size => t("File size"),
+ }
+}
+fn time_label(ti: TimeField) -> &'static str {
+ match ti {
+ TimeField::Created => t("Date created"),
+ TimeField::Updated => t("Date updated"),
+ }
+}
+fn age_label(days: i64) -> &'static str {
+ match days {
+ 30 => t("30 days ago"),
+ 90 => t("90 days ago"),
+ 180 => t("180 days ago"),
+ 365 => t("1 year ago"),
+ _ => t("Any time"),
+ }
+}
+fn manual_restore_pending(reason: &str) -> bool {
+ reason.starts_with("Finder could not list Trash:")
+ || reason.starts_with("Cannot access Trash:")
+ || ((reason.contains("/.Trash/") || reason.contains("/.Trashes/"))
+ && (reason.contains("Operation not permitted") || reason.contains("Permission denied")))
+ || reason.starts_with("Could not restore this file from Trash: Operation not permitted")
+ || reason.starts_with("Could not restore this file from Trash: Permission denied")
+ || reason == "Restored files are still missing from their original locations."
+ || reason.starts_with("Restore this file first:")
+}
+
+fn manual_restore_hint() -> &'static str {
+ #[cfg(target_os = "macos")]
+ return t("To restore, choose Put Back in Trash, then click Check.");
+ #[cfg(not(target_os = "macos"))]
+ t("Restore the files in your system trash, then click Check.")
+}
+
+fn unavailable_reason(reason: &str) -> &str {
+ match reason {
+ reason if manual_restore_pending(reason) => manual_restore_hint(),
+ "No restored sessions found. Check the file locations below." => {
+ t("No restored sessions found. Check the file locations below.")
+ }
+ "Files in Trash changed; restore them manually" => {
+ t("Files in Trash changed; restore them manually")
+ }
+ "File identity is unavailable; restore files manually" => {
+ t("File identity is unavailable; restore files manually")
+ }
+ "Files are no longer in Trash. They may have been permanently deleted." => {
+ t("Files are no longer in Trash. They may have been permanently deleted.")
+ }
+ "Original folder is missing; recreate it before restoring" => {
+ t("Original folder is missing; recreate it before restoring")
+ }
+ "Original folder contains a symbolic link" => t("Original folder contains a symbolic link"),
+ "The original location contains different files. Nothing was overwritten." => {
+ t("The original location contains different files. Nothing was overwritten.")
+ }
+ "A file that was not deleted is missing" => t("A file that was not deleted is missing"),
+ "Restored files changed before verification" => {
+ t("Restored files changed before verification")
+ }
+ "Restored files do not match the deleted files" => t(
+ "Some restored files differ from the deleted files. Check the file locations below.",
+ ),
+ "No sessions could be restored. Review the errors below." => {
+ t("No sessions could be restored. Review the errors below.")
+ }
+ "Session has unrecognized content" => t("Wake cannot read part of this session's format."),
+ "Session or files changed since review; refresh and review again"
+ | "Source changed while checking"
+ | "Session tree changed" => t("This session changed. Refresh the list and try again."),
+ "Session no longer exists" => t("This session is no longer available. Refresh the list."),
+ "Remote sessions are read-only" | "Remote mirrors are read-only" => {
+ t("Remote sessions are read-only")
+ }
+ "This source does not support independent file cleanup"
+ | "No independently owned files" => {
+ t("This source does not support independent file cleanup")
+ }
+ "Shared cleanup target" | "Target also contains another session" => {
+ t("Files are shared with another session")
+ }
+ "Source file is missing" => t("Source file is missing"),
+ "Source is not enabled" => t("Source is not enabled"),
+ "Network locations cannot be moved to the Recycle Bin" => {
+ t("Network locations cannot be moved to the Recycle Bin")
+ }
+ "This location does not support safe recycling" => {
+ t("This location does not support safe recycling")
+ }
+ "Parent session is unavailable" | "Session tree contains a cycle" => {
+ t("The complete session tree could not be verified")
+ }
+ "Symbolic links are not supported"
+ | "Shared hard links are not supported"
+ | "Source path contains links or is not absolute"
+ | "Source is outside the enabled location"
+ | "Cleanup target is outside the source location" => {
+ t("File ownership could not be verified")
+ }
+ _ => reason,
+ }
+}
+
+fn cleanup_review_issues(items: &[UnavailableSession], cx: &App) -> AnyElement {
+ v_flex()
+ .gap(SPACE_MD)
+ .children(items.iter().map(|item| {
+ v_flex()
+ .gap(SPACE_XS)
+ .child(
+ div()
+ .text_size(FONT_BODY)
+ .font_medium()
+ .child(item.session.title.clone()),
+ )
+ .child(
+ div()
+ .text_size(FONT_LABEL)
+ .text_color(cx.theme().muted_foreground)
+ .child(format!(
+ "{} · {} · {}",
+ item.session.agent.display_name(),
+ item.session.project_name,
+ abs_date(item.session.updated_at)
+ )),
+ )
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(cx.theme().muted_foreground)
+ .child(unavailable_reason(&item.reason).to_string()),
+ )
+ }))
+ .into_any_element()
+}
+
+fn cleanup_path(path: String, id: impl Into<ElementId>, cx: &App) -> AnyElement {
+ let name = std::path::Path::new(&path)
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_else(|| path.clone());
+ div()
+ .id(id)
+ .min_w_0()
+ .truncate()
+ .text_size(FONT_CAPTION)
+ .font_family(cx.theme().mono_font_family.clone())
+ .text_color(cx.theme().muted_foreground)
+ .child(name)
+ .tooltip(move |window, cx| {
+ gpui_component::tooltip::Tooltip::new(path.clone()).build(window, cx)
+ })
+ .into_any_element()
+}
+
+// File details belong to the final review, with session identity visible above them.
+fn cleanup_review_item(
+ item: &CleanupCandidate,
+ expanded: &Rc<std::cell::RefCell<HashSet<String>>>,
+ cx: &App,
+) -> AnyElement {
+ let key = item.root.key.clone();
+ let open = expanded.borrow().contains(&key);
+ let expanded = expanded.clone();
+ let files: Vec<_> = item
+ .targets
+ .iter()
+ .flat_map(|target| &target.files)
+ .filter(|file| !file.directory)
+ .collect();
+ let theme = cx.theme();
+ v_flex()
+ .min_w_0()
+ .py(SPACE_MD)
+ .gap(SPACE_SM)
+ .child(
+ h_flex()
+ .gap(SPACE_SM)
+ .min_w_0()
+ .child(
+ img(item.root.agent.brand_icon(theme.mode.is_dark()))
+ .size(px(16.))
+ .flex_shrink_0(),
+ )
+ .child(div().flex_1().min_w_0().child(cleanup_title(
+ item,
+ SharedString::from(format!("review-title-{key}")),
+ cx,
+ )))
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .flex_shrink_0()
+ .child(bytes(item.bytes)),
+ ),
+ )
+ .child(
+ h_flex()
+ .justify_between()
+ .gap(SPACE_SM)
+ .child(
+ div()
+ .min_w_0()
+ .truncate()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(format!(
+ "{} · {}",
+ item.root.project_name,
+ session_tally(item.sessions.len() as i64)
+ )),
+ )
+ .child(
+ Button::new(SharedString::from(format!("review-files-{key}")))
+ .ghost()
+ .h(px(28.))
+ .px(SPACE_SM)
+ .text_size(FONT_CAPTION)
+ .rounded(RADIUS_BUTTON)
+ .icon(
+ icon(if open {
+ "icons/chevron-down.svg"
+ } else {
+ "icons/chevron-right.svg"
+ })
+ .with_size(px(12.)),
+ )
+ .label(crate::tf!("Source files ({})", files.len()))
+ .on_click(move |_, window, _| {
+ let mut expanded = expanded.borrow_mut();
+ if !expanded.remove(&key) {
+ expanded.insert(key.clone());
+ }
+ window.refresh();
+ }),
+ ),
+ )
+ .when(open, |row| {
+ row.child(
+ v_flex()
+ .pl(SPACE_MD)
+ .gap(SPACE_SM)
+ .border_l_1()
+ .border_color(theme.border)
+ .children(files.iter().enumerate().map(|(ix, file)| {
+ let path = file.path.to_string_lossy().into_owned();
+ let folder = file
+ .path
+ .parent()
+ .map(|p| tilde_path(&p.to_string_lossy()))
+ .unwrap_or_default();
+ h_flex()
+ .min_w_0()
+ .gap(SPACE_MD)
+ .items_center()
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(2.))
+ .child(cleanup_path(
+ path,
+ SharedString::from(format!(
+ "review-file-{}-{ix}",
+ item.root.key
+ )),
+ cx,
+ ))
+ .child(
+ div()
+ .truncate()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(folder),
+ ),
+ )
+ .child(
+ div()
+ .flex_shrink_0()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(bytes(file.bytes)),
+ )
+ })),
+ )
+ })
+ .into_any_element()
+}
+
+fn cleanup_facts(item: &CleanupCandidate) -> String {
+ crate::tf!(
+ "{} · {} · approx. {}",
+ session_tally(item.sessions.len() as i64),
+ crate::tp!("{} prompt", "{} prompts", item.prompts),
+ bytes(item.bytes)
+ )
+}
+
+fn cleanup_title(item: &CleanupCandidate, id: impl Into<ElementId>, cx: &App) -> AnyElement {
+ cleanup_session_title(&item.root, item.has_starred(), item.has_pinned(), id, cx)
+}
+
+fn cleanup_session_title(
+ meta: &SessionMeta,
+ starred: bool,
+ pinned: bool,
+ id: impl Into<ElementId>,
+ cx: &App,
+) -> AnyElement {
+ let mut tooltip = meta.title.clone();
+ if starred {
+ tooltip.push_str(&format!("\n{}", t("Includes a starred session")));
+ }
+ if pinned {
+ tooltip.push_str(&format!("\n{}", t("Includes a pinned session")));
+ }
+ h_flex()
+ .min_w_0()
+ .items_center()
+ .gap(SPACE_XS)
+ .child(
+ div()
+ .id(id)
+ .flex_1()
+ .min_w_0()
+ .truncate()
+ .text_size(FONT_BODY)
+ .font_medium()
+ .child(meta.title.clone())
+ .tooltip(move |window, cx| {
+ gpui_component::tooltip::Tooltip::new(tooltip.clone()).build(window, cx)
+ }),
+ )
+ .when(pinned, |v| {
+ v.child(
+ icon("icons/pin-filled.svg")
+ .with_size(px(11.))
+ .text_color(cx.theme().primary),
+ )
+ })
+ .when(starred, |v| {
+ v.child(
+ icon("icons/star-filled.svg")
+ .with_size(px(11.))
+ .text_color(rgb(crate::theme::STAR_YELLOW)),
+ )
+ })
+ .into_any_element()
+}
+
+impl Workbench {
+ pub(super) fn cleanup_preview(&self) -> Option<&CleanupCandidate> {
+ if !self.cleanup.open {
+ return None;
+ }
+ let key = &self.detail.as_ref()?.meta.key;
+ self.cleanup
+ .shown
+ .iter()
+ .filter_map(CleanupEntry::candidate)
+ .find(|c| c.root.key == *key)
+ }
+ pub(super) fn render_cleanup_detail_facts(&self, cx: &Context<Self>) -> AnyElement {
+ let Some(c) = self.cleanup_preview() else {
+ return div().into_any_element();
+ };
+ h_flex()
+ .w_full()
+ .gap(SPACE_SM)
+ .flex_wrap()
+ .items_center()
+ .text_size(FONT_LABEL)
+ .text_color(cx.theme().muted_foreground)
+ .child(cleanup_facts(c))
+ .into_any_element()
+ }
+ pub(super) fn load_cleanup_prefs(&mut self) {
+ if let Some(options) = self
+ .store
+ .pref_get(cleanup::PREFS)
+ .and_then(|s| serde_json::from_str::<CleanupOptions>(&s).ok())
+ {
+ self.cleanup.options = options;
+ }
+ }
+ pub(super) fn leave_cleanup(&mut self, cx: &mut Context<Self>) {
+ if !self.cleanup.open {
+ return;
+ }
+ self.cleanup.open = false;
+ self.cleanup.preview_open = false;
+ if self.cleanup.busy && !self.cleanup.executing {
+ self.cleanup.cancel.store(true, Ordering::Relaxed);
+ }
+ self.detail = self.cleanup.saved_detail.take();
+ cx.notify();
+ }
+ pub(super) fn toggle_cleanup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.cleanup.open {
+ self.leave_cleanup(cx);
+ return;
+ }
+ self.insights_open = false;
+ self.cleanup.saved_detail = self.detail.take();
+ self.cleanup.open = true;
+ self.cleanup.history_open = false;
+ self.cleanup.result = None;
+ if !self.cleanup.busy {
+ self.reload_cleanup(window, cx);
+ }
+ cx.notify();
+ }
+ fn reload_cleanup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.cleanup.busy {
+ return;
+ }
+ self.cleanup.loading = true;
+ self.cleanup.selected.clear();
+ self.cleanup.error = None;
+ self.cleanup.now = chrono::Utc::now().timestamp_millis();
+ let store = self.store.clone();
+ let adapters = self.adapters.clone();
+ let task = cx.background_spawn(async move {
+ Ok::<_, anyhow::Error>((
+ cleanup::inventory(&store, &adapters)?,
+ cleanup::history(&store)?,
+ ))
+ });
+ self.cleanup.task = Some(cx.spawn_in(window, async move |this, cx| {
+ let result = task.await;
+ this.update_in(cx, |this, window, cx| {
+ this.cleanup.loading = false;
+ match result {
+ Ok((inventory, history)) => {
+ this.cleanup.inventory = inventory;
+ this.cleanup.history = history;
+ this.apply_cleanup_options(false, window, cx);
+ }
+ Err(e) => this.cleanup.error = Some(e.to_string()),
+ }
+ cx.notify();
+ })
+ .ok();
+ }));
+ cx.notify();
+ }
+ fn apply_cleanup_options(&mut self, clear: bool, _window: &mut Window, cx: &mut Context<Self>) {
+ if clear {
+ self.cleanup.selected.clear();
+ self.cleanup.scroll = UniformListScrollHandle::new();
+ }
+ let mut items: Vec<_> = self
+ .cleanup
+ .inventory
+ .candidates
+ .iter()
+ .cloned()
+ .map(CleanupEntry::Available)
+ .chain(
+ self.cleanup
+ .inventory
+ .unavailable
+ .iter()
+ .cloned()
+ .map(CleanupEntry::Unavailable),
+ )
+ .filter(|item| self.cleanup.options.matches_entry(item, self.cleanup.now))
+ .collect();
+ self.cleanup.options.sort_entries(&mut items);
+ self.cleanup.selected.retain(|key| {
+ items
+ .iter()
+ .filter_map(CleanupEntry::candidate)
+ .any(|c| c.root.key == *key)
+ });
+ self.cleanup.focus = self
+ .cleanup
+ .focus
+ .take()
+ .filter(|key| items.iter().any(|item| item.session().key == *key));
+ self.cleanup.shown = Rc::new(items);
+ if self.cleanup.open && self.cleanup.focus.is_none() {
+ self.cleanup.preview_open = false;
+ self.detail = None;
+ }
+ if let Ok(s) = serde_json::to_string(&self.cleanup.options) {
+ let _ = self.store.pref_set(cleanup::PREFS, &s);
+ }
+ cx.notify();
+ }
+ fn cleanup_chosen(&self) -> Vec<CleanupCandidate> {
+ self.cleanup
+ .shown
+ .iter()
+ .filter_map(CleanupEntry::candidate)
+ .filter(|c| self.cleanup.selected.contains(&c.root.key))
+ .cloned()
+ .collect()
+ }
+
+ pub(super) fn refresh_cleanup_flags(
+ &mut self,
+ key: &str,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !self.cleanup.open {
+ return;
+ }
+ let Ok(Some(meta)) = self.store.get_session(key) else {
+ return;
+ };
+ for candidate in &mut self.cleanup.inventory.candidates {
+ if let Some(member) = candidate.sessions.iter_mut().find(|s| s.key == key) {
+ member.favorite = meta.favorite;
+ member.pinned = meta.pinned;
+ if candidate.root.key == key {
+ candidate.root.favorite = meta.favorite;
+ candidate.root.pinned = meta.pinned;
+ }
+ self.cleanup.selected.remove(&candidate.root.key);
+ }
+ }
+ for item in &mut self.cleanup.inventory.unavailable {
+ if let Some(member) = item.sessions.iter_mut().find(|s| s.key == key) {
+ member.favorite = meta.favorite;
+ member.pinned = meta.pinned;
+ if item.session.key == key {
+ item.session.favorite = meta.favorite;
+ item.session.pinned = meta.pinned;
+ }
+ }
+ }
+ self.apply_cleanup_options(false, window, cx);
+ }
+
+ fn review_cleanup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let chosen = self.cleanup_chosen();
+ if chosen.is_empty() || self.cleanup.busy || self.cleanup.loading {
+ return;
+ }
+ self.cleanup.busy = true;
+ self.cleanup.progress = 0;
+ self.cleanup.progress_total = chosen.len();
+ self.cleanup.cancel = Arc::new(AtomicBool::new(false));
+ self.cleanup.error = None;
+ let cancel = self.cleanup.cancel.clone();
+ let store = self.store.clone();
+ let adapters = self.adapters.clone();
+ let (tx, mut rx) = futures::channel::mpsc::unbounded();
+ let task = cx.background_spawn(async move {
+ let review = cleanup::review(&store, &adapters, chosen, &cancel, |n| {
+ let _ = tx.unbounded_send(Ok(n));
+ });
+ let _ = tx.unbounded_send(Err(review));
+ });
+ cx.spawn_in(window, async move |this, cx| {
+ while let Some(event) = rx.next().await {
+ if this
+ .update_in(cx, |this, window, cx| {
+ match event {
+ Ok(n) => this.cleanup.progress = n,
+ Err(review) => {
+ this.cleanup.busy = false;
+ // A cancel can arrive after the worker has finished but before
+ // this UI update; never open a late confirmation in that case.
+ if this.cleanup.open && !this.cleanup.cancel.load(Ordering::Relaxed)
+ {
+ if let Some(review) = review {
+ this.confirm_cleanup(review, window, cx);
+ }
+ }
+ }
+ }
+ cx.notify();
+ })
+ .is_err()
+ {
+ break;
+ }
+ }
+ task.await;
+ })
+ .detach();
+ cx.notify();
+ }
+ fn confirm_cleanup(&self, review: CleanupReview, window: &mut Window, cx: &mut Context<Self>) {
+ if review.ready.is_empty() {
+ let entity = cx.entity();
+ open_closable_dialog(window, cx, move |dialog, window, cx| {
+ let entity = entity.clone();
+ dialog.title(t("Unable to clean up these sessions")).width(px(640.))
+ .child(v_flex().gap(SPACE_MD)
+ .child(div().text_size(FONT_CAPTION).text_color(cx.theme().muted_foreground)
+ .child(t("The selected sessions could not be verified. No files were moved.")))
+ .child(v_flex().id("cleanup-blocked-list")
+ .max_h((window.viewport_size().height - px(380.)).min(px(360.)))
+ .overflow_y_scroll()
+ .child(cleanup_review_issues(&review.skipped, cx)))
+ .child(h_flex().justify_end().child(
+ Button::new("cleanup-review-refresh").map(action_button)
+ .label(t("Refresh"))
+ .on_click(move |_, window, cx| {
+ window.close_dialog(cx);
+ entity.update(cx, |this, cx| this.reload_cleanup(window, cx));
+ })
+ )))
+ });
+ return;
+ }
+ let chosen = Rc::new(review.ready);
+ let skipped = Rc::new(review.skipped);
+ let expanded = Rc::new(std::cell::RefCell::new(HashSet::new()));
+ let entity = cx.entity();
+ window.open_alert_dialog(cx, move |dialog, window, cx| {
+ let items = chosen.clone();
+ let entity = entity.clone();
+ let theme = cx.theme();
+ let count: usize = items.iter().map(|c| c.sessions.len()).sum();
+ let title = if count == 1 {
+ t("Delete this session?").to_string()
+ } else {
+ crate::tf!("Delete {} sessions?", count)
+ };
+ dialog
+ .title(div().text_size(FONT_HEADING).font_semibold().child(title))
+ .width(px(640.))
+ .confirm()
+ .button_props(
+ gpui_component::dialog::DialogButtonProps::default()
+ .show_cancel(true)
+ .cancel_text(t("Cancel"))
+ .ok_text(t("Confirm"))
+ .ok_variant(gpui_component::button::ButtonVariant::Danger),
+ )
+ .footer(
+ v_flex()
+ .w_full()
+ .flex_shrink_0()
+ .border_t_1()
+ .border_color(theme.border)
+ .pt(SPACE_MD)
+ .gap(SPACE_LG)
+ .child(
+ v_flex()
+ .gap(SPACE_XS)
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(cleanup_trash_hint())
+ .child(t("Agents may no longer resume these sessions.")),
+ )
+ .child(
+ gpui_component::dialog::DialogFooter::new()
+ .gap(SPACE_SM)
+ .child(
+ crate::settings::settings_button(
+ Button::new("cleanup-confirm-cancel"),
+ cx,
+ )
+ .map(action_button)
+ .label(t("Cancel"))
+ .on_click(
+ |_, window, cx| {
+ window.dispatch_action(
+ Box::new(gpui_component::dialog::Cancel),
+ cx,
+ )
+ },
+ ),
+ )
+ .child(
+ Button::new("cleanup-confirm-trash")
+ .danger()
+ .map(action_button)
+ .label(t("Confirm"))
+ .on_click(|_, window, cx| {
+ window.dispatch_action(
+ Box::new(gpui_component::dialog::Confirm {
+ secondary: false,
+ }),
+ cx,
+ )
+ }),
+ ),
+ ),
+ )
+ .child(
+ v_flex()
+ .gap(SPACE_MD)
+ .text_size(FONT_BODY)
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(crate::tf!(
+ "Local files · About {}",
+ bytes(items.iter().map(|c| c.bytes).sum())
+ )),
+ )
+ .when(!skipped.is_empty(), |v| {
+ v.child(
+ div()
+ .text_size(FONT_CAPTION)
+ .child(crate::tf!("{} items will be skipped.", skipped.len())),
+ )
+ })
+ .child(
+ v_flex()
+ .id("cleanup-review-files")
+ .max_h((window.viewport_size().height - px(420.)).min(px(300.)))
+ .overflow_y_scroll()
+ .when(!skipped.is_empty(), |v| {
+ v.child(div().font_medium().child(t("To delete")))
+ })
+ .children(items.iter().enumerate().map(|(ix, item)| {
+ div()
+ .when(ix > 0, |row| {
+ row.border_t_1().border_color(theme.border)
+ })
+ .child(cleanup_review_item(item, &expanded, cx))
+ }))
+ .when(!skipped.is_empty(), |v| {
+ v.child(
+ div()
+ .font_medium()
+ .pt(SPACE_SM)
+ .child(t("Will be skipped")),
+ )
+ .child(cleanup_review_issues(&skipped, cx))
+ }),
+ ),
+ )
+ .on_ok(move |_, window, cx| {
+ entity.update(cx, |this, cx| {
+ this.execute_cleanup(items.as_ref().clone(), window, cx)
+ });
+ true
+ })
+ });
+ }
+ fn execute_cleanup(
+ &mut self,
+ items: Vec<CleanupCandidate>,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.cleanup.busy {
+ return;
+ }
+ self.cleanup.busy = true;
+ self.cleanup.executing = true;
+ self.cleanup.progress = 0;
+ self.cleanup.progress_total = items.len();
+ self.cleanup.result = None;
+ self.cleanup.history_open = false;
+ self.cleanup.expanded_results.clear();
+ self.cleanup.result_scroll = ScrollHandle::new();
+ self.cleanup.cancel = Arc::new(AtomicBool::new(false));
+ let cancel = self.cleanup.cancel.clone();
+ let store = self.store.clone();
+ let adapters = self.adapters.clone();
+ let (tx, mut rx) = futures::channel::mpsc::unbounded();
+ std::thread::spawn(move || {
+ let mut batch = CleanupBatch::new(items, chrono::Utc::now().timestamp_millis());
+ let result = cleanup::execute(&store, &adapters, &mut batch, &cancel, |n| {
+ let _ = tx.unbounded_send(Ok(n));
+ });
+ let _ = tx.unbounded_send(Err((batch, result.err().map(|e| e.to_string()))));
+ });
+ cx.spawn(async move |this, cx| {
+ while let Some(event) = rx.next().await {
+ if this
+ .update(cx, |this, cx| {
+ match event {
+ Ok(n) => this.cleanup.progress = n,
+ Err((batch, error)) => {
+ let deleted: HashSet<_> = batch
+ .records
+ .iter()
+ .filter(|r| r.indexed)
+ .flat_map(|r| {
+ r.candidate.sessions.iter().map(|s| s.key.clone())
+ })
+ .collect();
+ this.cleanup
+ .inventory
+ .candidates
+ .retain(|c| !deleted.contains(&c.root.key));
+ this.cleanup.shown = Rc::new(
+ this.cleanup
+ .shown
+ .iter()
+ .filter(|item| !deleted.contains(&item.session().key))
+ .cloned()
+ .collect(),
+ );
+ if this
+ .detail
+ .as_ref()
+ .is_some_and(|d| deleted.contains(&d.meta.key))
+ {
+ this.detail = None;
+ }
+ if this
+ .cleanup
+ .saved_detail
+ .as_ref()
+ .is_some_and(|d| deleted.contains(&d.meta.key))
+ {
+ this.cleanup.saved_detail = None;
+ }
+ this.cleanup.busy = false;
+ this.cleanup.executing = false;
+ this.cleanup.error = error;
+ this.cleanup.selected.clear();
+ this.cleanup.history.insert(0, batch.clone());
+ this.cleanup.result = Some(batch);
+ this.cleanup.refresh_after_history = true;
+ this.refresh(cx);
+ }
+ }
+ cx.notify();
+ })
+ .is_err()
+ {
+ break;
+ }
+ }
+ })
+ .detach();
+ cx.notify();
+ }
+ fn check_cleanup_batch(
+ &mut self,
+ verify_restored_files: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.cleanup.busy {
+ return;
+ }
+ let Some(mut batch) = self.cleanup.result.clone() else {
+ return;
+ };
+ self.cleanup.busy = true;
+ self.cleanup.error = None;
+ let store = self.store.clone();
+ let adapters = self.adapters.clone();
+ let task = cx.background_spawn(async move {
+ let result = if verify_restored_files {
+ cleanup::restore(&store, &adapters, &mut batch)
+ } else {
+ cleanup::retry_index_updates(&store, &mut batch)
+ };
+ (batch, result)
+ });
+ cx.spawn_in(window, async move |this, cx| {
+ let (batch, result) = task.await;
+ this.update_in(cx, |this, window, cx| {
+ this.cleanup.busy = false;
+ this.cleanup.result = Some(batch.clone());
+ this.cleanup.refresh_after_history = true;
+ if let Some(old) = this.cleanup.history.iter_mut().find(|b| b.id == batch.id) {
+ *old = batch.clone();
+ }
+ match result {
+ Ok(_) => {
+ this.cleanup.error = None;
+ let failed = batch.records.iter().any(|r| {
+ !r.restored
+ && r.error
+ .as_deref()
+ .is_some_and(|error| !manual_restore_pending(error))
+ });
+ let notification = if failed {
+ Notification::warning(t(
+ "Some sessions could not be updated. Review the errors below.",
+ ))
+ } else if verify_restored_files
+ && batch.records.iter().any(|r| r.can_restore())
+ {
+ Notification::info(t("Some sessions have been restored to Wake."))
+ } else if verify_restored_files {
+ Notification::success(t("Sessions restored"))
+ } else {
+ Notification::success(t("Session list updated"))
+ };
+ window.push_notification(notification, cx);
+ if verify_restored_files {
+ this.kick_incremental_scan(cx);
+ } else {
+ this.refresh(cx);
+ }
+ }
+ Err(_)
+ if verify_restored_files
+ && batch.records.iter().any(|record| record.can_restore())
+ && batch
+ .records
+ .iter()
+ .filter(|record| record.can_restore())
+ .all(|record| {
+ record.error.as_deref().is_some_and(manual_restore_pending)
+ }) =>
+ {
+ this.cleanup.error = None;
+ window.push_notification(Notification::info(manual_restore_hint()), cx);
+ }
+ Err(e) => this.cleanup.error = Some(e.to_string()),
+ }
+ cx.notify();
+ })
+ .ok();
+ })
+ .detach();
+ cx.notify();
+ }
+
+ pub(super) fn render_cleanup(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
+ if self.cleanup.preview_open {
+ return self.render_detail(window, cx);
+ }
+ if self.cleanup.result.is_some() || self.cleanup.history_open {
+ return self.render_cleanup_history_page(window, cx);
+ }
+ let theme = cx.theme().clone();
+ let state = &self.cleanup;
+ let row_count = state.shown.len();
+ let available_count = state
+ .shown
+ .iter()
+ .filter_map(CleanupEntry::candidate)
+ .count();
+ let unavailable_count = row_count - available_count;
+ let filter = self.cleanup_filter(cx);
+ let current = state.options.sort;
+ let ascending = state.options.sort_ascending();
+ let e = cx.entity();
+ let sort = Button::new("cleanup-sort")
+ .ghost()
+ .disabled(state.busy)
+ .rounded(RADIUS_BUTTON)
+ .icon(icon("icons/arrow-up-down.svg").with_size(px(16.)))
+ .tooltip(crate::tf!(
+ "Sort by {} · {}",
+ sort_label(current),
+ if ascending {
+ t("Ascending")
+ } else {
+ t("Descending")
+ }
+ ))
+ .dropdown_menu(move |mut menu, _, _| {
+ for value in [
+ CleanupSort::Updated,
+ CleanupSort::Created,
+ CleanupSort::Size,
+ ] {
+ let e = e.clone();
+ menu = menu.item(
+ PopupMenuItem::new(sort_label(value))
+ .checked(current == value)
+ .on_click(move |_, window, cx| {
+ e.update(cx, |this, cx| {
+ this.cleanup.options.sort = value;
+ this.cleanup.options.ascending = Some(ascending);
+ this.apply_cleanup_options(false, window, cx);
+ })
+ }),
+ );
+ }
+ menu = menu.separator();
+ for (label, value) in [(t("Descending"), false), (t("Ascending"), true)] {
+ let e = e.clone();
+ menu = menu.item(
+ PopupMenuItem::new(label)
+ .checked(ascending == value)
+ .on_click(move |_, window, cx| {
+ e.update(cx, |this, cx| {
+ this.cleanup.options.ascending = Some(value);
+ this.apply_cleanup_options(false, window, cx);
+ });
+ }),
+ );
+ }
+ menu.min_w(px(180.))
+ })
+ .anchor(Anchor::TopRight);
+ let chosen = self.cleanup_chosen();
+ let selected_bytes: u64 = chosen.iter().map(|c| c.bytes).sum();
+ let selected_sessions: usize = chosen.iter().map(|c| c.sessions.len()).sum();
+ let total_bytes: u64 = state
+ .shown
+ .iter()
+ .filter_map(CleanupEntry::candidate)
+ .map(|c| c.bytes)
+ .sum();
+ let date_field = match state.options.sort {
+ CleanupSort::Created => TimeField::Created,
+ CleanupSort::Updated => TimeField::Updated,
+ CleanupSort::Size
+ if state.options.created_days > 0 && state.options.updated_days == 0 =>
+ {
+ TimeField::Created
+ }
+ CleanupSort::Size => TimeField::Updated,
+ };
+ let mut dates = vec![];
+ for (field, days) in [
+ (TimeField::Created, state.options.created_days),
+ (TimeField::Updated, state.options.updated_days),
+ ] {
+ if days > 0 {
+ dates.push(format!("{} · {}", time_label(field), age_label(days)));
+ }
+ }
+ let mut summary = if dates.is_empty() {
+ t("Any time").to_string()
+ } else {
+ dates.join(" / ")
+ };
+ if state.options.agents.len() == 1 {
+ if let Some(agent) = state.options.agents.first() {
+ summary.push_str(&format!(" · {}", agent.display_name()));
+ }
+ } else if !state.options.agents.is_empty() {
+ summary.push_str(&format!(
+ " · {} ({})",
+ t("Agents"),
+ state.options.agents.len()
+ ));
+ }
+ if state.options.only_cleanable {
+ summary.push_str(&format!(" · {}", t("Exclude unavailable")));
+ }
+ if state.options.exclude_starred {
+ summary.push_str(&format!(" · {}", t("Exclude starred")));
+ }
+ if state.options.exclude_pinned {
+ summary.push_str(&format!(" · {}", t("Exclude pinned")));
+ }
+ if state.options.projects.len() == 1 {
+ let project = state.options.projects.first().unwrap();
+ summary.push_str(&format!(
+ " · {}",
+ self.projects
+ .iter()
+ .find(|p| &p.path == project)
+ .map(|p| p.name.as_str())
+ .unwrap_or(project)
+ ));
+ } else if !state.options.projects.is_empty() {
+ summary.push_str(&format!(
+ " · {} ({})",
+ t("Projects"),
+ state.options.projects.len()
+ ));
+ }
+ let history = Button::new("cleanup-history")
+ .map(action_button)
+ .ghost()
+ .label(t("History"))
+ .tooltip(t("Cleanup history"))
+ .disabled(state.busy)
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.cleanup.history_open = true;
+ this.focus_handle.focus(window, cx);
+ cx.notify();
+ }));
+ let heading = library_header(
+ "cleanup-header",
+ t("Clean Up Sessions"),
+ summary,
+ SPACE_XXL,
+ Some(
+ h_flex()
+ .gap(SPACE_XS)
+ .items_center()
+ .child(filter)
+ .child(sort)
+ .child(
+ Button::new("cleanup-refresh")
+ .ghost()
+ .rounded(RADIUS_BUTTON)
+ .icon(icon("icons/refresh-cw.svg").with_size(px(16.)))
+ .tooltip(t("Refresh"))
+ .disabled(state.loading || state.busy)
+ .on_click(
+ cx.listener(|this, _, window, cx| this.reload_cleanup(window, cx)),
+ ),
+ )
+ .into_any_element(),
+ ),
+ cx,
+ );
+ let list =
+ v_flex()
+ .flex_1()
+ .min_h_0()
+ .child(
+ h_flex()
+ .h(px(44.))
+ .flex_shrink_0()
+ .px(SPACE_XXL)
+ .gap(SPACE_MD)
+ .items_center()
+ .child(
+ h_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(SPACE_MD)
+ .items_center()
+ .child(
+ Checkbox::new("cleanup-all")
+ .label(if state.loading {
+ t("Select all").to_string()
+ } else {
+ crate::tf!("Select all ({})", available_count)
+ })
+ .flex_shrink_0()
+ .text_size(FONT_CAPTION)
+ .tooltip(crate::tf!(
+ "Select all {} cleanable sessions",
+ available_count
+ ))
+ .checked(
+ available_count > 0
+ && state.selected.len() == available_count,
+ )
+ .disabled(
+ state.loading || state.busy || available_count == 0,
+ )
+ .on_click(cx.listener(|this, checked, _, cx| {
+ this.cleanup.selected = if *checked {
+ this.cleanup
+ .shown
+ .iter()
+ .filter_map(CleanupEntry::candidate)
+ .map(|c| c.root.key.clone())
+ .collect()
+ } else {
+ HashSet::new()
+ };
+ cx.notify();
+ })),
+ )
+ .child(
+ div()
+ .min_w_0()
+ .truncate()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(if state.loading {
+ "—".to_string()
+ } else if unavailable_count > 0 {
+ format!(
+ "{} · {}",
+ session_tally(row_count as i64),
+ crate::tf!("{} unavailable", unavailable_count)
+ )
+ } else {
+ session_tally(row_count as i64)
+ }),
+ ),
+ )
+ .child(
+ div()
+ .w(CLEANUP_DATE_WIDTH)
+ .flex_shrink_0()
+ .text_right()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(time_label(date_field)),
+ )
+ .child(
+ div()
+ .w(CLEANUP_SIZE_WIDTH)
+ .flex_shrink_0()
+ .text_right()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(t("File size")),
+ ),
+ )
+ .when(state.loading, |v| {
+ v.child(
+ v_flex()
+ .flex_1()
+ .items_center()
+ .justify_center()
+ .gap(SPACE_MD)
+ .child(Spinner::new())
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(t("Checking local files…")),
+ ),
+ )
+ })
+ .when(!state.loading && row_count == 0, |v| {
+ v.child(v_flex().flex_1().items_center().justify_center().child(
+ empty_state_card(
+ "icons/inbox.svg",
+ px(58.),
+ px(24.),
+ t("No sessions match these filters"),
+ t("Try a different agent, project, or filter."),
+ cx,
+ ),
+ ))
+ })
+ .when(!state.loading && row_count > 0, |v| {
+ v.child(
+ uniform_list(
+ "cleanup-candidates",
+ row_count,
+ cx.processor(move |this, range: Range<usize>, _, cx| {
+ range
+ .map(|ix| this.render_cleanup_row(ix, date_field, cx))
+ .collect()
+ }),
+ )
+ .track_scroll(&state.scroll)
+ .flex_1()
+ .min_h_0(),
+ )
+ });
+ let footer = h_flex()
+ .h(SIDEBAR_FOOTER_ROW_HEIGHT + px(1.))
+ .flex_shrink_0()
+ .px(SPACE_XXL)
+ .gap(SPACE_MD)
+ .items_center()
+ .border_t_1()
+ .border_color(theme.border)
+ .when(state.busy, |v| v.child(Spinner::new().small()))
+ .child(
+ div()
+ .flex_1()
+ .min_w_0()
+ .truncate()
+ .text_size(FONT_LABEL)
+ .text_color(if chosen.is_empty() {
+ theme.muted_foreground
+ } else {
+ theme.foreground
+ })
+ .child(if state.busy && state.cancel.load(Ordering::Relaxed) {
+ t("Stopping after the current session…").to_string()
+ } else if state.executing {
+ crate::tf!(
+ "Moving files… {} / {}",
+ state.progress,
+ state.progress_total
+ )
+ } else if state.busy {
+ crate::tf!(
+ "Checking sessions… {} / {}",
+ state.progress,
+ state.progress_total
+ )
+ } else if chosen.is_empty() && available_count == 0 && row_count > 0 {
+ t("No cleanable sessions in these results").to_string()
+ } else if chosen.is_empty() && available_count > 0 && !state.loading {
+ crate::tf!("{} available for cleanup", bytes(total_bytes))
+ } else if chosen.is_empty() {
+ t("Select sessions to clean up").to_string()
+ } else if chosen.len() == selected_sessions {
+ crate::tf!("{} selected · {}", selected_sessions, bytes(selected_bytes))
+ } else {
+ crate::tf!(
+ "{} selected · {} sessions · {}",
+ chosen.len(),
+ selected_sessions,
+ bytes(selected_bytes)
+ )
+ }),
+ )
+ .when(chosen.is_empty() && !state.busy, |v| v.child(history))
+ .when(state.busy, |v| {
+ v.child(
+ Button::new("cleanup-cancel")
+ .map(action_button)
+ .label(if state.executing {
+ t("Stop after current session")
+ } else {
+ t("Cancel")
+ })
+ .disabled(state.cancel.load(Ordering::Relaxed))
+ .on_click(cx.listener(|this, _, _, cx| {
+ this.cleanup.cancel.store(true, Ordering::Relaxed);
+ cx.notify();
+ })),
+ )
+ })
+ .when(!chosen.is_empty() && !state.busy, |v| {
+ v.child(
+ Button::new("cleanup-clear-selection")
+ .map(action_button)
+ .ghost()
+ .label(t("Clear"))
+ .tooltip(t("Clear selection"))
+ .on_click(cx.listener(|this, _, _, cx| {
+ this.cleanup.selected.clear();
+ cx.notify();
+ })),
+ )
+ .child(
+ Button::new("cleanup-review")
+ .map(action_button)
+ .danger()
+ .label(t("Delete"))
+ .tooltip(move_to_trash())
+ .disabled(state.loading)
+ .on_click(
+ cx.listener(|this, _, window, cx| this.review_cleanup(window, cx)),
+ ),
+ )
+ });
+ let body = v_flex()
+ .flex_1()
+ .min_h_0()
+ .child(heading)
+ .child(list)
+ .child(footer);
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .h_full()
+ .bg(theme.background)
+ .child(body)
+ .when_some(state.error.as_ref(), |v, error| {
+ v.child(
+ div()
+ .px(SPACE_XXL)
+ .py(SPACE_SM)
+ .text_size(FONT_CAPTION)
+ .text_color(theme.danger)
+ .child(error.clone()),
+ )
+ })
+ .into_any_element()
+ }
+ fn show_cleanup_preview(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
+ if self.cleanup.busy {
+ return;
+ }
+ self.open_detail(key, None, window, cx);
+ if self
+ .detail
+ .as_ref()
+ .is_some_and(|detail| detail.meta.key == key)
+ {
+ self.cleanup.focus = Some(key.to_owned());
+ self.cleanup.preview_open = true;
+ self.focus_handle.focus(window, cx);
+ cx.notify();
+ }
+ }
+ pub(super) fn close_cleanup_preview(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.cleanup.preview_open = false;
+ self.stop_detail_selection_auto_scroll();
+ self.focus_handle.focus(window, cx);
+ cx.notify();
+ }
+ pub(super) fn navigate_cleanup_back(
+ &mut self,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> bool {
+ if self.cleanup.busy {
+ return false;
+ }
+ if self.cleanup.preview_open {
+ self.close_cleanup_preview(window, cx);
+ } else if self.cleanup.result.take().is_some() {
+ self.cleanup.expanded_results.clear();
+ self.cleanup.error = None;
+ self.focus_handle.focus(window, cx);
+ cx.notify();
+ } else if self.cleanup.history_open {
+ self.cleanup.history_open = false;
+ self.cleanup.error = None;
+ self.focus_handle.focus(window, cx);
+ cx.notify();
+ } else {
+ return false;
+ }
+ if !self.cleanup.history_open
+ && self.cleanup.result.is_none()
+ && self.cleanup.refresh_after_history
+ {
+ self.cleanup.refresh_after_history = false;
+ self.reload_cleanup(window, cx);
+ }
+ true
+ }
+}
diff --git a/crates/wake/src/workbench/cleanup/filter.rs b/crates/wake/src/workbench/cleanup/filter.rs
new file mode 100644
index 0000000..deb41b7
--- /dev/null
+++ b/crates/wake/src/workbench/cleanup/filter.rs
@@ -0,0 +1,707 @@
+//! A single-level filter popover: stable date controls and searchable sources.
+use super::*;
+use gpui_component::Selectable as _;
+use std::collections::BTreeSet;
+
+const FILTER_WIDTH: Pixels = px(468.);
+const SOURCE_WIDTH: Pixels = px(232.);
+const AGENT_WIDTH: Pixels = px(153.);
+
+fn source_choices(
+ inventory: &CleanupInventory,
+ options: &CleanupOptions,
+) -> (BTreeSet<AgentId>, Vec<(String, String)>) {
+ // Sidebar counts omit archived sessions. Choices must cover the entire
+ // cleanup inventory, including unavailable entries and currently hidden rows.
+ let mut roots: Vec<_> = inventory
+ .candidates
+ .iter()
+ .map(|candidate| (&candidate.root, candidate.updated_at))
+ .chain(
+ inventory
+ .unavailable
+ .iter()
+ .map(|item| (&item.session, item.updated_at())),
+ )
+ .collect();
+ roots.sort_by(|(a, a_time), (b, b_time)| b_time.cmp(a_time).then_with(|| a.key.cmp(&b.key)));
+ let mut agents = options.agents.clone();
+ let mut projects = Vec::new();
+ let mut paths = HashSet::new();
+ for (session, _) in roots {
+ agents.insert(session.agent);
+ if paths.insert(session.project_path.clone()) {
+ projects.push((session.project_path.clone(), session.project_name.clone()));
+ }
+ }
+ // A selected source may disappear after a refresh; keep it removable.
+ for path in &options.projects {
+ if paths.insert(path.clone()) {
+ let name = std::path::Path::new(path)
+ .file_name()
+ .and_then(|name| name.to_str())
+ .unwrap_or(path)
+ .to_string();
+ projects.push((path.clone(), name));
+ }
+ }
+ (agents, projects)
+}
+
+fn has_filters(options: &CleanupOptions) -> bool {
+ options.created_days > 0
+ || options.updated_days > 0
+ || !options.agents.is_empty()
+ || !options.projects.is_empty()
+ || options.exclude_starred
+ || options.exclude_pinned
+ || options.only_cleanable
+}
+
+fn choice_button(id: impl Into<ElementId>, selected: bool, cx: &App) -> Button {
+ let theme = cx.theme();
+ Button::new(id)
+ .small()
+ .h(px(28.))
+ .px(SPACE_SM)
+ .rounded(RADIUS_BUTTON)
+ .custom(
+ ButtonCustomVariant::new(cx)
+ .color(theme.transparent)
+ .foreground(if selected {
+ theme.primary
+ } else {
+ theme.foreground
+ })
+ .hover(if selected {
+ theme.list_active
+ } else {
+ theme.list_hover
+ })
+ .active(theme.list_active),
+ )
+ .selected(selected)
+ .toggled(selected)
+ .text_size(FONT_CAPTION)
+}
+
+fn choice(
+ entity: &Entity<Workbench>,
+ id: impl Into<ElementId>,
+ selected: bool,
+ change: impl Fn(&mut CleanupOptions) + 'static,
+ cx: &App,
+) -> Button {
+ let entity = entity.clone();
+ choice_button(id, selected, cx).on_click(move |_, window, cx| {
+ if !selected {
+ entity.update(cx, |this, cx| {
+ change(&mut this.cleanup.options);
+ this.apply_cleanup_options(true, window, cx);
+ });
+ }
+ })
+}
+
+fn multi_choice(
+ entity: &Entity<Workbench>,
+ id: impl Into<ElementId>,
+ selected: bool,
+ change: impl Fn(&mut CleanupOptions, bool) + 'static,
+ cx: &App,
+) -> Button {
+ let entity = entity.clone();
+ let theme = cx.theme();
+ choice_button(id, selected, cx)
+ .custom(
+ ButtonCustomVariant::new(cx)
+ .color(theme.secondary.opacity(0.45))
+ .foreground(if selected {
+ theme.primary
+ } else {
+ theme.foreground
+ })
+ .hover(if selected {
+ theme.list_active
+ } else {
+ theme.secondary_hover
+ })
+ .active(theme.list_active),
+ )
+ .border_1()
+ .border_color(if selected {
+ theme.primary.opacity(0.3)
+ } else {
+ theme.border
+ })
+ .role(gpui::Role::CheckBox)
+ .on_click(move |_, window, cx| {
+ entity.update(cx, |this, cx| {
+ change(&mut this.cleanup.options, !selected);
+ this.apply_cleanup_options(true, window, cx);
+ });
+ })
+}
+
+fn option_label(button: Button, label: &str, selected: bool, cx: &App) -> Button {
+ button
+ .relative()
+ .pr(px(20.))
+ .label(clip_display(label, 24))
+ .tooltip(label.to_owned())
+ .child(div().flex_1())
+ .child(
+ icon("icons/check.svg")
+ .with_size(px(10.))
+ .absolute()
+ .right(SPACE_XS - px(20.))
+ .top(px(9.))
+ .text_color(if selected {
+ cx.theme().primary
+ } else {
+ cx.theme().transparent
+ }),
+ )
+}
+
+fn agent_label(
+ button: Button,
+ label: &str,
+ leading: impl IntoElement,
+ selected: bool,
+ cx: &App,
+) -> Button {
+ option_label(button, label, selected, cx).pl(px(26.)).child(
+ // The button's content excludes its padding; return the brand icon
+ // to the reserved leading slot without shifting text on selection.
+ div()
+ .absolute()
+ .left(px(6. - 26.))
+ .top(px(6.5))
+ .size(px(15.))
+ .child(leading),
+ )
+}
+
+fn section(title: &'static str, selected: usize, options: Vec<Button>) -> AnyElement {
+ v_flex()
+ .w_full()
+ .gap(SPACE_SM)
+ .child(
+ h_flex()
+ .gap(SPACE_SM)
+ .text_size(FONT_CAPTION)
+ .font_medium()
+ .child(title)
+ .when(selected > 0, |row| row.child(format!("({selected})"))),
+ )
+ .child(
+ h_flex()
+ .w_full()
+ .gap(SPACE_XS)
+ .flex_wrap()
+ .children(options),
+ )
+ .into_any_element()
+}
+
+impl Workbench {
+ fn prepare_cleanup_filter(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(input) = &self.cleanup.filter_input {
+ input.update(cx, |input, cx| input.set_value("", window, cx));
+ } else {
+ let input = cx
+ .new(|cx| InputState::new(window, cx).placeholder(t("Search agents or projects")));
+ cx.subscribe_in(&input, window, |this, input, event, _, cx| {
+ if matches!(event, InputEvent::Change) {
+ this.cleanup.filter_query = input.read(cx).value().trim().to_lowercase();
+ this.cleanup.filter_scroll.set_offset(point(px(0.), px(0.)));
+ cx.notify();
+ }
+ })
+ .detach();
+ self.cleanup.filter_input = Some(input);
+ }
+ self.cleanup.filter_query.clear();
+ self.cleanup.filter_scroll.set_offset(point(px(0.), px(0.)));
+ cx.notify();
+ }
+
+ fn cleanup_date_filter(entity: &Entity<Self>, field: TimeField, cx: &App) -> AnyElement {
+ let theme = cx.theme();
+ let options = &entity.read(cx).cleanup.options;
+ let (id, selected) = match field {
+ TimeField::Created => ("cleanup-created-age", options.created_days),
+ TimeField::Updated => ("cleanup-updated-age", options.updated_days),
+ };
+ v_flex()
+ .gap(SPACE_SM)
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .font_medium()
+ .child(time_label(field)),
+ )
+ .child(
+ h_flex()
+ .w_full()
+ .p(px(2.))
+ .rounded(theme.radius)
+ .bg(theme.secondary)
+ .children(
+ [0, 30, 90, 180, 365]
+ .into_iter()
+ .enumerate()
+ .map(|(i, value)| {
+ choice(
+ entity,
+ (id, i),
+ selected == value,
+ move |options| match field {
+ TimeField::Created => options.created_days = value,
+ TimeField::Updated => options.updated_days = value,
+ },
+ cx,
+ )
+ .flex_1()
+ .min_w_0()
+ .px(SPACE_XS)
+ // 与 Settings 的 Appearance 分段控件同一材质。
+ .custom(
+ ButtonCustomVariant::new(cx)
+ .color(theme.transparent)
+ .foreground(if selected == value {
+ theme.foreground
+ } else {
+ theme.muted_foreground
+ })
+ .hover(theme.secondary_hover)
+ .active(if theme.mode.is_dark() {
+ theme.secondary_active
+ } else {
+ theme.popover
+ }),
+ )
+ .when(selected == value, |button| button.shadow_xs())
+ .text_size(FONT_CAPTION)
+ .label(age_label(value))
+ }),
+ ),
+ )
+ .into_any_element()
+ }
+
+ fn cleanup_filter_sources(entity: &Entity<Self>, window: &Window, cx: &App) -> AnyElement {
+ let this = entity.read(cx);
+ let options = &this.cleanup.options;
+ let query = &this.cleanup.filter_query;
+ let theme = cx.theme();
+ let mut agents = Vec::new();
+ let (available_agents, available_projects) =
+ source_choices(&this.cleanup.inventory, options);
+ for agent in available_agents {
+ let label = agent.display_name();
+ if !query.is_empty() && !label.to_lowercase().contains(query) {
+ continue;
+ }
+ let selected = options.agents.contains(&agent);
+ agents.push(agent_label(
+ multi_choice(
+ entity,
+ SharedString::from(format!("cleanup-agent-{}", agent.as_str())),
+ selected,
+ move |o, checked| {
+ if checked {
+ o.agents.insert(agent);
+ } else {
+ o.agents.remove(&agent);
+ }
+ },
+ cx,
+ )
+ .w(AGENT_WIDTH),
+ label,
+ img(agent.brand_icon(theme.mode.is_dark())).size(px(15.)),
+ selected,
+ cx,
+ ));
+ }
+ let mut projects = Vec::new();
+ for (path, name) in available_projects {
+ if !query.is_empty()
+ && !name.to_lowercase().contains(query)
+ && !path.to_lowercase().contains(query)
+ {
+ continue;
+ }
+ let selected = options.projects.contains(&path);
+ let selection_path = path.clone();
+ projects.push(
+ option_label(
+ multi_choice(
+ entity,
+ SharedString::from(format!("cleanup-project-{path}")),
+ selected,
+ move |o, checked| {
+ if checked {
+ o.projects.insert(selection_path.clone());
+ } else {
+ o.projects.remove(&selection_path);
+ }
+ },
+ cx,
+ )
+ .w(SOURCE_WIDTH),
+ &name,
+ selected,
+ cx,
+ )
+ .tooltip(path),
+ );
+ }
+ let show_agents = !agents.is_empty();
+ let show_projects = !projects.is_empty();
+ let no_matches = !show_agents && !show_projects;
+ v_flex()
+ .id("cleanup-filter-sources")
+ .w_full()
+ .max_h((window.viewport_size().height - px(542.)).clamp(px(100.), px(264.)))
+ .overflow_y_scroll()
+ .track_scroll(&this.cleanup.filter_scroll)
+ .gap(SPACE_LG)
+ .text_color(theme.muted_foreground)
+ .when(show_agents, |v| {
+ v.child(section(t("Agents"), options.agents.len(), agents))
+ })
+ .when(show_projects, |v| {
+ v.child(section(t("Projects"), options.projects.len(), projects))
+ })
+ .when(no_matches, |v| {
+ v.child(
+ v_flex()
+ .w_full()
+ .min_h(px(80.))
+ .items_center()
+ .justify_center()
+ .gap(SPACE_SM)
+ .child(icon("icons/search.svg").with_size(px(20.)))
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .child(t("No matching agents or projects")),
+ ),
+ )
+ })
+ .vertical_scrollbar(&this.cleanup.filter_scroll)
+ .into_any_element()
+ }
+
+ fn cleanup_source_search(
+ entity: &Entity<Self>,
+ input: &Entity<InputState>,
+ cx: &App,
+ ) -> AnyElement {
+ let focus_input = input.clone();
+ let clear_input = input.clone();
+ let clear_entity = entity.clone();
+ search_field_frame(cx)
+ .id("cleanup-source-search")
+ .w_full()
+ .flex_shrink_0()
+ .cursor_text()
+ .on_click(move |_, window, cx| {
+ focus_input.update(cx, |input, cx| input.focus(window, cx));
+ })
+ .child(icon("icons/search.svg").with_size(px(13.)).flex_shrink_0())
+ .child(
+ Input::new(input)
+ .appearance(false)
+ .p_0()
+ .flex_1()
+ .min_w_0()
+ .text_size(FONT_CAPTION),
+ )
+ .when(!input.read(cx).value().is_empty(), |row| {
+ row.child(
+ Button::new("cleanup-clear-source-search")
+ .ghost()
+ .small()
+ .size(px(24.))
+ .p_0()
+ .rounded(RADIUS_BUTTON)
+ .icon(icon("icons/circle-x.svg").with_size(px(14.)))
+ .tooltip(t("Clear search"))
+ .on_click(move |_, window, cx| {
+ clear_input.update(cx, |input, cx| {
+ input.set_value("", window, cx);
+ input.focus(window, cx);
+ });
+ clear_entity.update(cx, |this, cx| {
+ this.cleanup.filter_query.clear();
+ this.cleanup.filter_scroll.set_offset(point(px(0.), px(0.)));
+ cx.notify();
+ });
+ }),
+ )
+ })
+ .into_any_element()
+ }
+
+ pub(super) fn cleanup_filter(&self, cx: &Context<Self>) -> Popover {
+ let entity = cx.entity();
+ let on_open = entity.clone();
+ let theme = cx.theme();
+ Popover::new("cleanup-filter")
+ .anchor(Anchor::TopRight)
+ .p(SPACE_LG)
+ .trigger(
+ Button::new("cleanup-filter-trigger")
+ .ghost()
+ .disabled(self.cleanup.busy)
+ .rounded(RADIUS_BUTTON)
+ .icon(
+ icon("icons/sliders-horizontal.svg")
+ .with_size(px(16.))
+ .text_color(if has_filters(&self.cleanup.options) {
+ theme.primary
+ } else {
+ theme.muted_foreground
+ }),
+ )
+ .tooltip(t("Filter")),
+ )
+ .on_open_change(move |open, window, cx| {
+ if *open {
+ on_open.update(cx, |this, cx| this.prepare_cleanup_filter(window, cx));
+ }
+ })
+ .content(move |_, window, cx| {
+ let this = entity.read(cx);
+ let options = &this.cleanup.options;
+ let popover = cx.entity();
+ let clear_entity = entity.clone();
+ v_flex()
+ .w(FILTER_WIDTH)
+ .gap(SPACE_LG)
+ .child(
+ h_flex().h(px(28.)).items_center().child(
+ div()
+ .text_size(FONT_HEADING)
+ .font_semibold()
+ .child(t("Filter")),
+ ),
+ )
+ .child(
+ v_flex()
+ .gap(SPACE_MD)
+ .child(Self::cleanup_date_filter(&entity, TimeField::Created, cx))
+ .child(Self::cleanup_date_filter(&entity, TimeField::Updated, cx)),
+ )
+ .child(section(
+ t("Exclude"),
+ usize::from(options.exclude_starred)
+ + usize::from(options.exclude_pinned)
+ + usize::from(options.only_cleanable),
+ vec![
+ option_label(
+ multi_choice(
+ &entity,
+ "cleanup-exclude-starred",
+ options.exclude_starred,
+ |options, checked| options.exclude_starred = checked,
+ cx,
+ )
+ .w(AGENT_WIDTH),
+ t("Starred"),
+ options.exclude_starred,
+ cx,
+ )
+ .tooltip(t("Applies to the session and its nested sessions.")),
+ option_label(
+ multi_choice(
+ &entity,
+ "cleanup-exclude-pinned",
+ options.exclude_pinned,
+ |options, checked| options.exclude_pinned = checked,
+ cx,
+ )
+ .w(AGENT_WIDTH),
+ t("Pinned"),
+ options.exclude_pinned,
+ cx,
+ )
+ .tooltip(t("Applies to the session and its nested sessions.")),
+ option_label(
+ multi_choice(
+ &entity,
+ "cleanup-exclude-unavailable",
+ options.only_cleanable,
+ |options, checked| options.only_cleanable = checked,
+ cx,
+ )
+ .w(AGENT_WIDTH),
+ t("Unavailable"),
+ options.only_cleanable,
+ cx,
+ )
+ .tooltip(t("Hide sessions that cannot be deleted.")),
+ ],
+ ))
+ .child(
+ v_flex()
+ .gap(SPACE_MD)
+ .pt(SPACE_LG)
+ .border_t_1()
+ .border_color(cx.theme().border)
+ .child(
+ h_flex()
+ .items_center()
+ .justify_between()
+ .gap(SPACE_LG)
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .font_medium()
+ .child(t("Sources")),
+ )
+ .when_some(this.cleanup.filter_input.as_ref(), |row, input| {
+ row.child(
+ div().w(px(284.)).child(Self::cleanup_source_search(
+ &entity, input, cx,
+ )),
+ )
+ }),
+ )
+ .child(Self::cleanup_filter_sources(&entity, window, cx)),
+ )
+ .child(
+ h_flex()
+ .gap(SPACE_MD)
+ .items_center()
+ .justify_between()
+ .pt(SPACE_LG)
+ .border_t_1()
+ .border_color(cx.theme().border)
+ .child(
+ crate::settings::settings_button(
+ Button::new("cleanup-clear-filters")
+ .label(t("Clear"))
+ .tooltip(t("Clear filters")),
+ cx,
+ )
+ .map(action_button)
+ .bg(cx.theme().secondary)
+ .disabled(
+ !has_filters(options) && this.cleanup.filter_query.is_empty(),
+ )
+ .on_click(move |_, window, cx| {
+ clear_entity.update(cx, |this, cx| {
+ let o = &mut this.cleanup.options;
+ o.created_days = 0;
+ o.updated_days = 0;
+ o.agents.clear();
+ o.projects.clear();
+ o.exclude_starred = false;
+ o.exclude_pinned = false;
+ o.only_cleanable = false;
+ if let Some(input) = &this.cleanup.filter_input {
+ input.update(cx, |input, cx| {
+ input.set_value("", window, cx)
+ });
+ }
+ this.cleanup.filter_query.clear();
+ this.cleanup
+ .filter_scroll
+ .set_offset(point(px(0.), px(0.)));
+ this.apply_cleanup_options(true, window, cx);
+ })
+ }),
+ )
+ .child(
+ crate::settings::settings_primary_button(
+ Button::new("cleanup-filter-done").label(t("Done")),
+ cx,
+ )
+ .map(action_button)
+ .min_w(px(80.))
+ .bg(cx.theme().primary)
+ .on_click(move |_, window, cx| {
+ popover.update(cx, |state, cx| state.dismiss(window, cx))
+ }),
+ ),
+ )
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::source_choices;
+ use std::collections::BTreeSet;
+ use wake_core::{
+ cleanup::{self, CleanupOptions},
+ db::Store,
+ models::{AgentId, SessionMeta},
+ };
+
+ #[test]
+ fn sources_include_archived_unavailable_and_selected_missing_entries() {
+ let temp = tempfile::tempdir().unwrap();
+ let store = Store::open(&temp.path().join("index.db")).unwrap();
+ for (agent, project, archived, updated_at) in [
+ (AgentId::Codex, "archive-only", true, 100),
+ (AgentId::ClaudeCode, "current", false, 200),
+ ] {
+ let meta = SessionMeta {
+ key: format!("{}:{project}", agent.as_str()),
+ id: project.into(),
+ host: String::new(),
+ agent,
+ title: project.into(),
+ project_path: format!("/synthetic/{project}"),
+ project_name: project.into(),
+ file_path: format!("/synthetic/{project}/session.jsonl"),
+ created_at: 0,
+ updated_at,
+ message_count: 1,
+ size_bytes: 0,
+ git_branch: None,
+ model: None,
+ tokens_used: None,
+ archived,
+ source: None,
+ favorite: false,
+ pinned: false,
+ };
+ store.write_session(&meta, updated_at, &[]).unwrap();
+ }
+ // The old sidebar-based source omitted the archived agent and project.
+ assert_eq!(store.agent_counts().unwrap().len(), 1);
+ assert_eq!(store.list_projects(false).unwrap().len(), 1);
+ let inventory = cleanup::inventory(&store, &[]).unwrap();
+ assert_eq!(inventory.unavailable.len(), 2);
+ let options = CleanupOptions {
+ agents: BTreeSet::from([AgentId::Gemini]),
+ projects: BTreeSet::from(["/synthetic/missing".into()]),
+ only_cleanable: true,
+ ..Default::default()
+ };
+ let (agents, projects) = source_choices(&inventory, &options);
+ assert_eq!(
+ agents,
+ BTreeSet::from([AgentId::Codex, AgentId::ClaudeCode, AgentId::Gemini])
+ );
+ assert_eq!(
+ projects,
+ vec![
+ ("/synthetic/current".into(), "current".into()),
+ ("/synthetic/archive-only".into(), "archive-only".into()),
+ ("/synthetic/missing".into(), "missing".into()),
+ ]
+ );
+ // Clearing the selection keeps all real sources, even with unavailable
+ // rows excluded. Options never determine which real sources are offered.
+ let (_, projects) = source_choices(&inventory, &CleanupOptions::default());
+ assert_eq!(projects.len(), 2);
+ }
+}
diff --git a/crates/wake/src/workbench/cleanup/history.rs b/crates/wake/src/workbench/cleanup/history.rs
new file mode 100644
index 0000000..7401ddd
--- /dev/null
+++ b/crates/wake/src/workbench/cleanup/history.rs
@@ -0,0 +1,873 @@
+//! Cleanup history is a navigable list, with file diagnostics disclosed per session.
+use super::*;
+use wake_core::cleanup::CleanupRecord;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Outcome {
+ Restored,
+ Moved,
+ PartlyRestored,
+ Partial,
+ Interrupted,
+ NeedsAttention,
+ NotStarted,
+}
+impl Outcome {
+ fn label(self) -> &'static str {
+ match self {
+ Self::Restored => t("Restored"),
+ Self::Moved => t("Moved to Trash"),
+ Self::PartlyRestored => t("Partially restored"),
+ Self::Partial => t("Partially completed"),
+ Self::Interrupted => t("Interrupted"),
+ Self::NeedsAttention => t("Needs attention"),
+ Self::NotStarted => t("Not started"),
+ }
+ }
+ fn description(self) -> &'static str {
+ match self {
+ Self::Restored => t("These sessions are available in Wake again."),
+ Self::Moved => t("Session files were moved to the system trash."),
+ Self::PartlyRestored => t("Some sessions have been restored to Wake."),
+ Self::Partial | Self::NeedsAttention => t("Review the affected sessions below."),
+ Self::Interrupted => {
+ t("This cleanup was interrupted. Review the file details before continuing.")
+ }
+ Self::NotStarted => t("No session files were moved."),
+ }
+ }
+ fn icon(self) -> &'static str {
+ match self {
+ Self::Restored | Self::PartlyRestored => "icons/refresh-cw.svg",
+ Self::Moved => "icons/check.svg",
+ Self::Partial | Self::Interrupted | Self::NeedsAttention => "icons/info.svg",
+ Self::NotStarted => "icons/brush-cleaning.svg",
+ }
+ }
+ fn color(self, cx: &App) -> Hsla {
+ if self.needs_attention() {
+ cx.theme().danger
+ } else {
+ match self {
+ Self::Restored | Self::PartlyRestored => cx.theme().primary,
+ Self::Moved => cx.theme().success,
+ _ => cx.theme().muted_foreground,
+ }
+ }
+ }
+ fn needs_attention(self) -> bool {
+ matches!(
+ self,
+ Self::Partial | Self::Interrupted | Self::NeedsAttention
+ )
+ }
+}
+
+fn record_outcome(restored: bool, indexed: bool, error: bool, targets: &[TargetStatus]) -> Outcome {
+ if restored {
+ Outcome::Restored
+ } else if !error && indexed && targets.iter().all(|s| *s == TargetStatus::Moved) {
+ Outcome::Moved
+ } else if !error && targets.iter().all(|s| *s == TargetStatus::Pending) {
+ Outcome::NotStarted
+ } else {
+ Outcome::NeedsAttention
+ }
+}
+fn outcome(record: &CleanupRecord) -> Outcome {
+ record_outcome(
+ record.restored,
+ record.indexed,
+ record
+ .error
+ .as_deref()
+ .is_some_and(|error| !manual_restore_pending(error)),
+ &record.targets,
+ )
+}
+fn batch_outcome(finished: bool, states: &[Outcome], any_moved: bool) -> Outcome {
+ if states.is_empty() {
+ return Outcome::NotStarted;
+ }
+ if states.iter().all(|s| *s == Outcome::Restored) {
+ return Outcome::Restored;
+ }
+ if !finished {
+ return Outcome::Interrupted;
+ }
+ if states.contains(&Outcome::NeedsAttention) {
+ return if any_moved || states.contains(&Outcome::Restored) {
+ Outcome::Partial
+ } else {
+ Outcome::NeedsAttention
+ };
+ }
+ if states.iter().all(|s| *s == Outcome::NotStarted) {
+ return Outcome::NotStarted;
+ }
+ if states.contains(&Outcome::NotStarted) {
+ return Outcome::Partial;
+ }
+ if states.contains(&Outcome::Restored) {
+ return Outcome::PartlyRestored;
+ }
+ Outcome::Moved
+}
+fn batch_status(batch: &CleanupBatch) -> Outcome {
+ batch_outcome(
+ batch.finished,
+ &batch.records.iter().map(outcome).collect::<Vec<_>>(),
+ batch
+ .records
+ .iter()
+ .any(|r| r.targets.contains(&TargetStatus::Moved)),
+ )
+}
+fn batch_size(batch: &CleanupBatch) -> u64 {
+ batch.records.iter().map(|r| r.candidate.bytes).sum()
+}
+fn batch_sessions(batch: &CleanupBatch) -> usize {
+ batch
+ .records
+ .iter()
+ .map(|r| r.candidate.sessions.len())
+ .sum()
+}
+
+const HISTORY_ROW_HEIGHT: Pixels = px(88.);
+
+fn history_status(status: Outcome, cx: &App) -> impl IntoElement {
+ let color = status.color(cx);
+ div()
+ .flex_shrink_0()
+ .px(SPACE_SM)
+ .py(px(3.))
+ .rounded(RADIUS_BUTTON)
+ .bg(color.opacity(0.08))
+ .text_size(FONT_LABEL)
+ .text_color(color)
+ .child(status.label())
+}
+
+fn history_date(stamp: i64) -> String {
+ Local
+ .timestamp_millis_opt(stamp)
+ .single()
+ .map(|date| date.format("%Y-%m-%d %H:%M").to_string())
+ .unwrap_or_else(|| abs_date(stamp))
+}
+
+impl Workbench {
+ fn cleanup_history_header(
+ &self,
+ title: &'static str,
+ subtitle: String,
+ cx: &Context<Self>,
+ ) -> AnyElement {
+ let parent = if self.cleanup.history_open && self.cleanup.result.is_some() {
+ t("Cleanup history")
+ } else {
+ t("Clean Up Sessions")
+ };
+ h_flex()
+ .h(LIBRARY_IDENTITY_HEIGHT)
+ .flex_shrink_0()
+ .px(SPACE_XXL)
+ .gap(SPACE_MD)
+ .items_start()
+ .window_control_area(WindowControlArea::Drag)
+ .child(
+ div().pt(px(24.)).child(
+ Button::new("cleanup-history-back")
+ .ghost()
+ .map(action_button)
+ .with_size(gpui_component::Size::Medium)
+ .w(px(32.))
+ .px_0()
+ .icon(icon("icons/chevron-left.svg").with_size(px(16.)))
+ .tooltip(parent)
+ .disabled(self.cleanup.busy)
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.navigate_cleanup_back(window, cx);
+ })),
+ ),
+ )
+ .child(div().flex_1().min_w_0().child(library_header(
+ "cleanup-history-header",
+ title,
+ subtitle,
+ px(0.),
+ None,
+ cx,
+ )))
+ .into_any_element()
+ }
+
+ pub(super) fn render_cleanup_history_page(
+ &self,
+ window: &Window,
+ cx: &mut Context<Self>,
+ ) -> AnyElement {
+ let body = if let Some(batch) = &self.cleanup.result {
+ self.render_cleanup_record(batch, cx)
+ } else {
+ self.render_cleanup_history(window, cx)
+ };
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .h_full()
+ .bg(cx.theme().background)
+ .child(body)
+ .when_some(self.cleanup.error.as_ref(), |view, error| {
+ view.child(
+ div()
+ .px(SPACE_XXL)
+ .py(SPACE_SM)
+ .text_size(FONT_CAPTION)
+ .text_color(cx.theme().danger)
+ .child(unavailable_reason(error).to_owned()),
+ )
+ })
+ .into_any_element()
+ }
+
+ fn render_cleanup_history(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {
+ let count = self.cleanup.history.len();
+ let available_height =
+ (window.viewport_size().height - LIBRARY_IDENTITY_HEIGHT - SPACE_SM - SPACE_XXL)
+ .max(HISTORY_ROW_HEIGHT);
+ let panel_height = (HISTORY_ROW_HEIGHT * count as f32 + px(2.)).min(available_height);
+ v_flex()
+ .flex_1()
+ .min_h_0()
+ .child(self.cleanup_history_header(
+ t("Cleanup history"),
+ crate::tp!("{} cleanup", "{} cleanups", count),
+ cx,
+ ))
+ .when(count == 0, |view| {
+ view.child(div().flex_1().flex().items_center().justify_center().child(
+ empty_state_card(
+ "icons/brush-cleaning.svg",
+ px(58.),
+ px(26.),
+ t("No cleanup history yet"),
+ t("Your cleanup results will appear here."),
+ cx,
+ ),
+ ))
+ })
+ .when(count > 0, |view| {
+ view.child(
+ div()
+ .flex()
+ .justify_center()
+ .px(SPACE_XXL)
+ .pt(SPACE_SM)
+ .pb(SPACE_XXL)
+ .child(
+ div()
+ .w_full()
+ .max_w(READER_MAX_WIDTH)
+ .h(panel_height)
+ .rounded(cx.theme().radius_lg)
+ .border_1()
+ .border_color(cx.theme().border)
+ .bg(cx.theme().popover)
+ .overflow_hidden()
+ .child(
+ uniform_list(
+ "cleanup-history-list",
+ count,
+ cx.processor(|this, range: Range<usize>, _, cx| {
+ range
+ .map(|ix| this.cleanup_history_row(ix, cx))
+ .collect()
+ }),
+ )
+ .track_scroll(&self.cleanup.history_scroll)
+ .size_full(),
+ ),
+ ),
+ )
+ })
+ .into_any_element()
+ }
+
+ fn open_cleanup_record(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
+ if self.cleanup.busy {
+ return;
+ }
+ let Some(batch) = self.cleanup.history.get(ix).cloned() else {
+ return;
+ };
+ self.cleanup.result = Some(batch);
+ self.cleanup.expanded_results.clear();
+ self.cleanup.result_scroll = ScrollHandle::new();
+ self.cleanup.error = None;
+ self.focus_handle.focus(window, cx);
+ cx.notify();
+ }
+
+ fn cleanup_history_row(&self, ix: usize, cx: &Context<Self>) -> AnyElement {
+ let batch = &self.cleanup.history[ix];
+ let status = batch_status(batch);
+ let theme = cx.theme();
+ let first = batch.records.first();
+ let title = first
+ .map(|r| r.candidate.root.title.clone())
+ .unwrap_or_else(|| t("Cleanup details").to_owned());
+ let title = if batch.records.len() > 1 {
+ crate::tf!("{} + {} more", title, batch.records.len() - 1)
+ } else {
+ title
+ };
+ h_flex()
+ .id(("cleanup-history-row", ix))
+ .role(accesskit::Role::Button)
+ .aria_label(format!(
+ "{} · {} · {} · {}",
+ title,
+ abs_date(batch.stamp),
+ status.label(),
+ bytes(batch_size(batch))
+ ))
+ .h(HISTORY_ROW_HEIGHT)
+ .w_full()
+ .px(SPACE_LG)
+ .gap(SPACE_LG)
+ .items_center()
+ .when(ix > 0, |row| row.border_t_1().border_color(theme.border))
+ .cursor_pointer()
+ .focusable()
+ .tab_stop(true)
+ .hover(|style| style.bg(theme.list_hover))
+ .focus(|style| style.bg(theme.list_hover))
+ .on_click(
+ cx.listener(move |this, _, window, cx| this.open_cleanup_record(ix, window, cx)),
+ )
+ .on_key_down(cx.listener(move |this, event: &KeyDownEvent, window, cx| {
+ if event.keystroke.key == "enter" || event.keystroke.key == "space" {
+ this.open_cleanup_record(ix, window, cx);
+ cx.stop_propagation();
+ }
+ }))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .justify_center()
+ .size(px(36.))
+ .flex_shrink_0()
+ .rounded(theme.radius)
+ .bg(theme.background)
+ .when_some(first, |view, record| {
+ view.child(
+ img(record.candidate.root.agent.brand_icon(theme.mode.is_dark()))
+ .size(px(22.)),
+ )
+ }),
+ )
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(6.))
+ .child(
+ div()
+ .id(("cleanup-history-title", ix))
+ .truncate()
+ .text_size(FONT_BODY)
+ .font_medium()
+ .child(title.clone())
+ .tooltip(move |window, cx| {
+ gpui_component::tooltip::Tooltip::new(title.clone())
+ .build(window, cx)
+ }),
+ )
+ .child(
+ div()
+ .truncate()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(format!(
+ "{} · {}",
+ history_date(batch.stamp),
+ session_tally(batch_sessions(batch) as i64)
+ )),
+ ),
+ )
+ .child(
+ v_flex()
+ .flex_shrink_0()
+ .items_end()
+ .gap(px(6.))
+ .child(
+ div()
+ .text_size(FONT_HEADING)
+ .font_medium()
+ .child(bytes(batch_size(batch))),
+ )
+ .child(history_status(status, cx)),
+ )
+ .child(
+ icon("icons/chevron-right.svg")
+ .with_size(px(14.))
+ .text_color(theme.muted_foreground)
+ .flex_shrink_0(),
+ )
+ .into_any_element()
+ }
+
+ fn render_cleanup_record(&self, batch: &CleanupBatch, cx: &Context<Self>) -> AnyElement {
+ let theme = cx.theme();
+ let status = batch_status(batch);
+ let can_restore = batch.records.iter().any(CleanupRecord::can_restore);
+ let can_retry = batch.records.iter().any(|r| {
+ !r.indexed
+ && !r.restored
+ && !r.targets.is_empty()
+ && r.targets.iter().all(|s| *s == TargetStatus::Moved)
+ });
+ v_flex()
+ .flex_1()
+ .min_h_0()
+ .child(self.cleanup_history_header(t("Cleanup details"), abs_date(batch.stamp), cx))
+ .child(
+ div()
+ .id("cleanup-record-sessions")
+ .flex_1()
+ .min_h_0()
+ .overflow_y_scroll()
+ .track_scroll(&self.cleanup.result_scroll)
+ .child(
+ div().flex().justify_center().px(SPACE_XXL).child(
+ v_flex()
+ .w_full()
+ .max_w(READER_MAX_WIDTH)
+ .pt(SPACE_SM)
+ .pb(px(40.))
+ .gap(SPACE_XXL)
+ .child(
+ v_flex()
+ .flex_shrink_0()
+ .rounded(theme.radius_lg)
+ .border_1()
+ .border_color(theme.border)
+ .bg(theme.popover)
+ .child(
+ h_flex()
+ .p(SPACE_XL)
+ .gap(SPACE_LG)
+ .items_center()
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .justify_center()
+ .size(px(36.))
+ .flex_shrink_0()
+ .rounded(theme.radius)
+ .bg(status.color(cx).opacity(0.08))
+ .child(
+ icon(status.icon())
+ .with_size(px(18.))
+ .text_color(status.color(cx)),
+ ),
+ )
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(6.))
+ .child(
+ div()
+ .text_size(FONT_HEADING)
+ .font_medium()
+ .child(status.label()),
+ )
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(status.description()),
+ ),
+ )
+ .child(
+ v_flex()
+ .flex_shrink_0()
+ .items_end()
+ .gap(px(4.))
+ .child(
+ div()
+ .text_size(FONT_TITLE)
+ .font_semibold()
+ .child(bytes(batch_size(batch))),
+ )
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(session_tally(
+ batch_sessions(batch) as i64,
+ )),
+ ),
+ ),
+ )
+ .when(can_restore, |view| {
+ view.child(
+ v_flex()
+ .px(SPACE_XL)
+ .pb(SPACE_LG)
+ .gap(SPACE_SM)
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(manual_restore_hint())
+ .child(t("Space is freed when the files are removed from Trash.")),
+ )
+ })
+ .when(
+ can_restore || can_retry || self.cleanup.busy,
+ |view| {
+ view.child(self.cleanup_record_actions(
+ can_restore,
+ can_retry,
+ cx,
+ ))
+ },
+ ),
+ )
+ .child(
+ v_flex()
+ .gap(SPACE_SM)
+ .child(
+ div()
+ .text_size(FONT_CAPTION)
+ .font_medium()
+ .text_color(theme.muted_foreground)
+ .child(t("Sessions")),
+ )
+ .children(batch.records.iter().enumerate().map(
+ |(ix, record)| self.cleanup_record_row(record, ix, cx),
+ )),
+ ),
+ ),
+ ),
+ )
+ .into_any_element()
+ }
+
+ fn cleanup_record_actions(
+ &self,
+ can_restore: bool,
+ can_retry: bool,
+ cx: &Context<Self>,
+ ) -> AnyElement {
+ let theme = cx.theme();
+ h_flex()
+ .flex_shrink_0()
+ .px(SPACE_XL)
+ .pb(SPACE_XL)
+ .gap(SPACE_SM)
+ .flex_wrap()
+ .when(self.cleanup.busy, |row| {
+ row.child(Spinner::new().small()).child(
+ div()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(t("Checking files…")),
+ )
+ })
+ .when(can_restore, |row| {
+ row.child(
+ crate::settings::settings_button(Button::new("cleanup-open-trash"), cx)
+ .map(action_button)
+ .label(t("Trash"))
+ .tooltip(t("Open system trash"))
+ .disabled(self.cleanup.busy)
+ .on_click(|_, _, _| terminal::open_trash()),
+ )
+ .child(
+ crate::settings::settings_button(Button::new("cleanup-reindex"), cx)
+ .map(action_button)
+ .label(t("Check"))
+ .disabled(self.cleanup.busy)
+ .tooltip(t("Check restored files"))
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.check_cleanup_batch(true, window, cx)
+ })),
+ )
+ })
+ .when(can_retry, |row| {
+ row.child(
+ crate::settings::settings_button(Button::new("cleanup-retry-index"), cx)
+ .map(action_button)
+ .label(t("Update session list"))
+ .disabled(self.cleanup.busy)
+ .tooltip(t(
+ "Files were moved, but Wake could not update its session list.",
+ ))
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.check_cleanup_batch(false, window, cx)
+ })),
+ )
+ })
+ .into_any_element()
+ }
+
+ fn cleanup_record_row(
+ &self,
+ record: &CleanupRecord,
+ ix: usize,
+ cx: &Context<Self>,
+ ) -> AnyElement {
+ let theme = cx.theme();
+ let candidate = &record.candidate;
+ let status = outcome(record);
+ let key = candidate.root.key.clone();
+ let expanded = self.cleanup.expanded_results.contains(&key);
+ let show_error = !record.restored
+ && record
+ .error
+ .as_deref()
+ .is_some_and(|error| !manual_restore_pending(error));
+ let click_key = key.clone();
+ let file_label = crate::tf!("File locations ({})", candidate.targets.len());
+ v_flex()
+ .w_full()
+ .min_w_0()
+ .flex_shrink_0()
+ .rounded(theme.radius_lg)
+ .border_1()
+ .border_color(theme.border)
+ .bg(theme.popover)
+ .overflow_hidden()
+ .child(
+ h_flex()
+ .p(SPACE_LG)
+ .gap(SPACE_MD)
+ .items_center()
+ .child(
+ img(candidate.root.agent.brand_icon(theme.mode.is_dark()))
+ .size(px(24.))
+ .flex_shrink_0(),
+ )
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(px(6.))
+ .child(cleanup_title(candidate, ("history-session-title", ix), cx))
+ .child(
+ div()
+ .truncate()
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .child(format!(
+ "{} · {}",
+ candidate.root.project_name,
+ bytes(candidate.bytes)
+ ))
+ .when(candidate.sessions.len() > 1, |row| {
+ row.child(format!(
+ " · {}",
+ session_tally(candidate.sessions.len() as i64)
+ ))
+ }),
+ ),
+ )
+ .child(history_status(status, cx)),
+ )
+ .when(show_error, |view| {
+ view.child(
+ div()
+ .px(SPACE_LG)
+ .pb(SPACE_LG)
+ .text_size(FONT_CAPTION)
+ .text_color(theme.danger)
+ .child(
+ unavailable_reason(record.error.as_deref().unwrap_or_default())
+ .to_owned(),
+ ),
+ )
+ })
+ .child(
+ h_flex()
+ .id(("cleanup-result-files", ix))
+ .role(accesskit::Role::Button)
+ .aria_label(format!("{} · {}", candidate.root.title, file_label))
+ .h(px(40.))
+ .px(SPACE_LG)
+ .gap(SPACE_SM)
+ .border_t_1()
+ .border_color(theme.border)
+ .text_size(FONT_CAPTION)
+ .text_color(theme.muted_foreground)
+ .cursor_pointer()
+ .focusable()
+ .tab_stop(true)
+ .hover(|style| style.bg(theme.list_hover))
+ .focus(|style| style.bg(theme.list_hover))
+ .on_click(cx.listener(move |this, _, _, cx| {
+ if !this.cleanup.expanded_results.remove(&click_key) {
+ this.cleanup.expanded_results.insert(click_key.clone());
+ }
+ cx.notify();
+ }))
+ .on_key_down(cx.listener(move |this, event: &KeyDownEvent, _, cx| {
+ if event.keystroke.key == "enter" || event.keystroke.key == "space" {
+ if !this.cleanup.expanded_results.remove(&key) {
+ this.cleanup.expanded_results.insert(key.clone());
+ }
+ cx.notify();
+ cx.stop_propagation();
+ }
+ }))
+ .child(icon("icons/folder.svg").with_size(px(14.)))
+ .child(div().flex_1().child(file_label))
+ .child(
+ icon(if expanded {
+ "icons/chevron-down.svg"
+ } else {
+ "icons/chevron-right.svg"
+ })
+ .with_size(px(14.)),
+ ),
+ )
+ .when(expanded, |view| {
+ view.child(
+ v_flex()
+ .min_w_0()
+ .px(SPACE_LG)
+ .pb(SPACE_LG)
+ .pt(SPACE_SM)
+ .gap(SPACE_LG)
+ .children(
+ candidate
+ .targets
+ .iter()
+ .zip(&record.targets)
+ .enumerate()
+ .map(|(target_ix, (target, target_status))| {
+ let path = target.path.to_string_lossy().into_owned();
+ let parent = target
+ .path
+ .parent()
+ .map(|p| tilde_path(&p.to_string_lossy()))
+ .unwrap_or_default();
+ let label = if record.restored {
+ t("Restored")
+ } else {
+ match target_status {
+ TargetStatus::Pending => t("Not started"),
+ TargetStatus::Moving => t("Verify in system trash"),
+ TargetStatus::Moved => t("Moved to Trash"),
+ TargetStatus::Failed(_) => t("Failed"),
+ }
+ };
+ v_flex()
+ .min_w_0()
+ .gap(SPACE_XS)
+ .child(
+ h_flex()
+ .gap(SPACE_MD)
+ .min_w_0()
+ .child(div().flex_1().min_w_0().child(
+ cleanup_path(
+ path,
+ SharedString::from(format!(
+ "history-file-{ix}-{target_ix}"
+ )),
+ cx,
+ ),
+ ))
+ .child(
+ div()
+ .flex_shrink_0()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(label),
+ ),
+ )
+ .child(
+ div()
+ .truncate()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(parent),
+ )
+ }),
+ ),
+ )
+ })
+ .into_any_element()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{batch_outcome, record_outcome, Outcome, TargetStatus};
+ #[test]
+ fn trash_permission_errors_offer_manual_recovery_without_hiding_other_failures() {
+ use super::{manual_restore_hint, manual_restore_pending, unavailable_reason};
+ let expected = manual_restore_hint();
+ for error in [
+ "Cannot access Trash: Operation not permitted (os error 1)",
+ "Finder could not list Trash: Not authorized to send Apple events",
+ "Could not restore this file from Trash: Permission denied (os error 13)",
+ "IO error for operation on /Users/tester/.Trash/session/: Operation not permitted (os error 1): Operation not permitted (os error 1)",
+ "Restored files are still missing from their original locations.",
+ ] {
+ assert_eq!(unavailable_reason(error), expected);
+ assert!(manual_restore_pending(error));
+ }
+ let conflict = "The original location contains different files. Nothing was overwritten.";
+ assert_eq!(unavailable_reason(conflict), conflict);
+ assert!(!manual_restore_pending(conflict));
+ }
+ #[test]
+ fn unfinished_moves_and_failed_indexing_need_attention() {
+ assert_eq!(
+ record_outcome(false, false, false, &[TargetStatus::Moved]),
+ Outcome::NeedsAttention
+ );
+ assert_eq!(
+ record_outcome(false, false, false, &[TargetStatus::Moving]),
+ Outcome::NeedsAttention
+ );
+ assert_eq!(
+ record_outcome(false, true, false, &[TargetStatus::Moved]),
+ Outcome::Moved
+ );
+ assert_eq!(
+ record_outcome(false, true, true, &[TargetStatus::Moved]),
+ Outcome::NeedsAttention
+ );
+ assert_eq!(
+ record_outcome(false, false, false, &[TargetStatus::Pending]),
+ Outcome::NotStarted
+ );
+ assert_eq!(
+ record_outcome(false, false, true, &[TargetStatus::Pending]),
+ Outcome::NeedsAttention
+ );
+ }
+ #[test]
+ fn historical_outcomes_distinguish_partial_work_and_restoration() {
+ use Outcome::*;
+ assert_eq!(batch_outcome(true, &[], false), NotStarted);
+ assert_eq!(batch_outcome(false, &[Moved], true), Interrupted);
+ assert_eq!(batch_outcome(true, &[Moved, NotStarted], true), Partial);
+ assert_eq!(batch_outcome(true, &[NeedsAttention], true), Partial);
+ assert_eq!(
+ batch_outcome(true, &[NeedsAttention], false),
+ NeedsAttention
+ );
+ assert_eq!(
+ batch_outcome(true, &[Moved, Restored], true),
+ PartlyRestored
+ );
+ assert_eq!(batch_outcome(true, &[Restored], true), Restored);
+ }
+}
diff --git a/crates/wake/src/workbench/cleanup/rows.rs b/crates/wake/src/workbench/cleanup/rows.rs
new file mode 100644
index 0000000..b428263
--- /dev/null
+++ b/crates/wake/src/workbench/cleanup/rows.rs
@@ -0,0 +1,248 @@
+//! Both availability states use the same two-line row and column layout.
+use super::*;
+
+fn reason_label(reason: &str) -> &str {
+ match reason {
+ "This source does not support independent file cleanup"
+ | "No independently owned files" => t("Individual cleanup unsupported"),
+ "Remote sessions are read-only" | "Remote mirrors are read-only" => t("Remote · read-only"),
+ "Shared cleanup target" | "Target also contains another session" => {
+ t("Shared session files")
+ }
+ "Source file is missing" => t("Source file missing"),
+ "Source is not enabled" => t("Source disabled"),
+ "Network locations cannot be moved to the Recycle Bin" => t("Network location"),
+ "This location does not support safe recycling" => t("Recycling unavailable"),
+ "Parent session is unavailable" | "Session tree contains a cycle" => {
+ t("Session tree unverified")
+ }
+ "Symbolic links are not supported"
+ | "Shared hard links are not supported"
+ | "Source path contains links or is not absolute"
+ | "Source is outside the enabled location"
+ | "Cleanup target is outside the source location" => t("File ownership unverified"),
+ "Session has unrecognized content" => t("Unrecognized session format"),
+ _ => unavailable_reason(reason),
+ }
+}
+
+impl Workbench {
+ pub(super) fn render_cleanup_row(
+ &self,
+ ix: usize,
+ date_field: TimeField,
+ cx: &Context<Self>,
+ ) -> AnyElement {
+ let item = &self.cleanup.shown[ix];
+ let meta = item.session();
+ let candidate = item.candidate();
+ let (members, reason) = match item {
+ CleanupEntry::Available(c) => (&c.sessions, None),
+ CleanupEntry::Unavailable(item) => (&item.sessions, Some(item.reason.as_str())),
+ };
+ let selectable = candidate.is_some();
+ let theme = cx.theme();
+ let key = meta.key.clone();
+ let preview_key = key.clone();
+ let keyboard_key = key.clone();
+ let selected = selectable && self.cleanup.selected.contains(&key);
+ let entity = cx.entity();
+ let source = format!("{} · {}", meta.agent.display_name(), meta.project_name);
+ let date = match date_field {
+ TimeField::Created => meta.created_at,
+ TimeField::Updated => item.updated_at(),
+ };
+ div()
+ .w_full()
+ .px(SPACE_LG)
+ .py(px(2.))
+ .child(
+ h_flex()
+ .id(SharedString::from(format!("cleanup-{key}")))
+ .w_full()
+ .min_w_0()
+ .h(px(60.))
+ .px(SPACE_SM)
+ .rounded(theme.radius)
+ .gap(SPACE_MD)
+ .items_center()
+ .when(selected, |row| row.bg(theme.list_active))
+ .when(!selected, |row| {
+ row.hover(|style| style.bg(theme.list_hover))
+ })
+ .child(
+ h_flex()
+ .flex_1()
+ .min_w_0()
+ .gap(SPACE_MD)
+ .items_center()
+ .child(
+ Checkbox::new(SharedString::from(format!("select-{key}")))
+ .checked(selected)
+ .disabled(
+ !selectable || self.cleanup.busy || self.cleanup.loading,
+ )
+ .when_some(reason, |checkbox, reason| {
+ checkbox.tooltip(unavailable_reason(reason).to_owned())
+ })
+ .on_click(move |checked, _, cx| {
+ if !selectable {
+ return;
+ }
+ entity.update(cx, |this, cx| {
+ if *checked {
+ this.cleanup.selected.insert(key.clone());
+ } else {
+ this.cleanup.selected.remove(&key);
+ }
+ cx.notify();
+ });
+ }),
+ )
+ .child(
+ v_flex()
+ .id(("cleanup-preview", ix))
+ .focusable()
+ .tab_stop(true)
+ .cursor_pointer()
+ .hover(|style| style.text_color(theme.primary))
+ .focus(|style| {
+ style.bg(theme.list_hover).rounded(RADIUS_BUTTON)
+ })
+ .on_key_down(cx.listener(
+ move |this, event: &KeyDownEvent, window, cx| {
+ if event.keystroke.key == "enter"
+ || event.keystroke.key == "space"
+ {
+ this.show_cleanup_preview(
+ &keyboard_key,
+ window,
+ cx,
+ );
+ cx.stop_propagation();
+ }
+ },
+ ))
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.show_cleanup_preview(&preview_key, window, cx);
+ }))
+ .flex_1()
+ .min_w_0()
+ .gap(SPACE_XS)
+ .child(cleanup_session_title(
+ meta,
+ members.iter().any(|s| s.favorite),
+ members.iter().any(|s| s.pinned),
+ ("cleanup-title", ix),
+ cx,
+ ))
+ .child(
+ h_flex()
+ .min_w_0()
+ .gap(SPACE_XS)
+ .items_center()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(
+ img(meta.agent.brand_icon(theme.mode.is_dark()))
+ .size(px(15.))
+ .flex_shrink_0(),
+ )
+ .child(
+ div()
+ .id(("cleanup-source", ix))
+ .min_w_0()
+ .max_w(px(128.))
+ .child(badge(
+ meta.project_name.clone(),
+ theme.muted,
+ theme.muted_foreground,
+ ))
+ .tooltip(move |window, cx| {
+ gpui_component::tooltip::Tooltip::new(
+ source.clone(),
+ )
+ .build(window, cx)
+ }),
+ )
+ .when_some(reason, |row, reason| {
+ let full_reason =
+ unavailable_reason(reason).to_owned();
+ row.child(div().px(SPACE_XS).child("·")).child(
+ div()
+ .id(("cleanup-reason", ix))
+ .flex_1()
+ .min_w_0()
+ .truncate()
+ .child(reason_label(reason).to_owned())
+ .tooltip(move |window, cx| {
+ gpui_component::tooltip::Tooltip::new(
+ full_reason.clone(),
+ )
+ .build(window, cx)
+ }),
+ )
+ })
+ .when(selectable && members.len() > 1, |row| {
+ row.child(crate::tp!(
+ "{} nested session",
+ "{} nested sessions",
+ members.len() - 1
+ ))
+ }),
+ ),
+ ),
+ )
+ .child(
+ div()
+ .id(("cleanup-date", ix))
+ .w(CLEANUP_DATE_WIDTH)
+ .flex_shrink_0()
+ .text_right()
+ .text_size(FONT_LABEL)
+ .text_color(theme.muted_foreground)
+ .child(if date > 0 {
+ smart_time(date)
+ } else {
+ "—".into()
+ })
+ .tooltip({
+ let dates = format!(
+ "{} · {}\n{} · {}",
+ t("Date created"),
+ abs_date(meta.created_at),
+ t("Date updated"),
+ abs_date(item.updated_at())
+ );
+ move |window, cx| {
+ gpui_component::tooltip::Tooltip::new(dates.clone())
+ .build(window, cx)
+ }
+ }),
+ )
+ .child(
+ div()
+ .id(("cleanup-size", ix))
+ .w(CLEANUP_SIZE_WIDTH)
+ .flex_shrink_0()
+ .text_right()
+ .text_size(FONT_BODY)
+ .when(!selectable, |size| {
+ size.text_color(theme.muted_foreground)
+ .tooltip(|window, cx| {
+ gpui_component::tooltip::Tooltip::new(t(
+ "File size unavailable",
+ ))
+ .build(window, cx)
+ })
+ })
+ .child(
+ candidate
+ .map(|c| bytes(c.bytes))
+ .unwrap_or_else(|| "—".into()),
+ ),
+ ),
+ )
+ .into_any_element()
+ }
+}
diff --git a/docs/session-cleanup-design.md b/docs/session-cleanup-design.md
new file mode 100644
index 0000000..f9aec85
--- /dev/null
+++ b/docs/session-cleanup-design.md
@@ -0,0 +1,71 @@
+# 本机会话文件清理
+
+计划版本:0.7.0,尚未发布。
+
+![清理列表(以 Wake 项目为例)](../imgs/session-cleanup.png)
+
+## 目标与范围
+
+帮助用户按时间和磁盘占用找到不再需要的本机会话,审阅后移入系统回收站。会话是否仍有价值由用户判断,不做自动推荐或后台删除。
+
+只支持 adapter 明确声明可独立清理的主文件、专属关联文件和完整子会话树,包括本地归档。远程会话、远程镜像、共享数据库、全局缓存、模型文件和项目工作目录不属于清理范围。无法清理的会话仍在列表中展示,并说明原因;删除 Wake 索引不算释放源文件空间。
+
+## 页面与筛选
+
+- 入口位于侧栏底部,沿用应用的页面背景、24px 内容留白、标题和两行列表密度,不增加第二列。
+- Filter 与 Sort 独立。创建时间、更新时间分别提供不限、30 天前、90 天前、180 天前和 1 年前,两个时间条件取交集。日期未知时只能匹配“不限”。
+- Agents、Projects 均支持多选:同组取并集,不同组取交集;未选表示不限,不增加 All 选项。来源选项取完整清理清单,包含归档和不可清理项,不随当前过滤结果缩减;已选但暂时消失的来源仍可取消。
+- Exclude 包含 Starred、Pinned、Unavailable,默认均关闭。收藏和置顶是显式筛选条件,不是隐藏的保护规则。标记与更新时间按完整会话树汇总。
+- Exclude、Agents、Projects 共用轻量选项块:浅中性底色和细边框表示未选,浅蓝底色与尾部勾号表示选中;Agent 保留品牌图标。来源搜索放在 Sources 标题旁,只搜索来源选项,不清除已选值。
+- Sort 复用 All Sessions 的菜单结构,分别选择创建时间、更新时间、文件大小及升降序;未知值始终在最后。排序保留选择,修改筛选清空选择。
+- 首次使用默认“更新时间 · 30 天前”。Clear 清空筛选;筛选和排序可保存,旧单日期/单来源偏好自动迁移。
+
+列表顶部显示全选、当前会话数及不可清理数量。不可清理行显示禁用复选框和简短原因,悬停可看完整说明,标题仍可打开阅读器。全选只选择当前范围内可清理的会话。未选择时底部显示可清理文件体积;选择后显示汇总及 Clear/Delete。
+
+点击标题复用现有阅读器。Back/Esc 返回清理页,保留筛选、选择和滚动位置。每次正文加载使用独立请求编号,避免原阅读器和清理预览互相覆盖异步结果。
+
+文字操作统一为纯文字按钮,与应用现有尺寸一致:32px 高、12px 水平留白、6px 圆角。删除采用 danger 样式,最终确认按钮为 Confirm。筛选/排序/刷新、返回和展开仍使用功能图标。
+
+## 审阅和执行
+
+1. Delete 在后台检查所选会话,并显示进度;检查完成后打开确认清单。
+2. 确认清单展示会话、包含的文件数量和体积;文件位置按需展开。失败项逐项说明原因并跳过,全部失败时只提供刷新,不提供执行按钮。
+3. 固定底部说明恢复方式和空间释放条件,操作为 Cancel/Confirm;只有 Confirm 开始移动文件。
+4. 执行以整棵会话树为单位、以独立文件目标为步骤。每步先持久化状态,再调用现有系统 Trash 服务;取消只停止尚未开始的会话树。
+5. 整棵树的目标全部确认移动后,索引事务写入删除标记。部分失败和索引失败分别记录,不能把部分成功当作完整回滚。
+
+移入回收站通常不会立即释放空间。只有用户在系统回收站删除这些文件后,才完成空间回收。Wake 不清空整个回收站,也不在回收失败时改用永久删除。
+
+## 文件归属与复核
+
+`CleanupCandidate` 保存完整会话树、用户标记、目标路径、文件类型、身份、修改时间和大小快照。生成清单时读取完整索引元数据,主线输入统计单独批量聚合;执行复核不重复聚合消息表。
+
+执行前重新检查会话树、收藏/置顶、来源启用状态、路径包含关系和完整文件快照。任何其他会话对目标的所有权都必须纳入考虑,包括当前过滤范围外的会话。符号链接、共享硬链接、路径归属不明和无法完整解析的会话不能清理;解析后再次核对文件与索引元数据。
+
+新删除记录在第一次移动前,为所有普通文件生成 SHA-256 并保存到日志。读取大文件后再次核对归属和快照。日志先于文件移动持久化,异常或中断后可按逐目标状态判断已完成和待处理项。
+
+## 空间统计与平台差异
+
+- Unix 使用设备号/inode 识别文件,以分配块数统计磁盘占用,并排除共享硬链接。
+- Windows 从文件句柄获取卷编号和完整 128 位文件 ID,支持 ReFS 身份;同时核对硬链接数和重解析点。普通文件使用分配空间,压缩/稀疏文件使用压缩信息,不能以逻辑长度或零身份作为回退值。
+- Windows 的 UNC、扩展 UNC、映射网络盘在清单和执行前均说明不可清理原因。非固定卷无法保证安全回收,也不进入候选;服务层在移动整个批次前再核对位置。
+- macOS 使用现有 Finder Trash 服务;Linux 使用 freedesktop Trash 实现;Windows 使用系统 Recycle Bin 服务。新平台必须显式实现服务,不继承其他系统的行为。
+- 大小按目标集合去重,目录本身不重复计入文件内容大小。体积表示所选文件占用,不承诺移动后立即释放同样的空间;共享文件系统块等因素仍由系统决定。
+
+## 历史与恢复
+
+History 是独立页面,按批次展示会话、时间、体积和状态。详情展示结果摘要、各会话的处理状态及可展开的原文件位置。Trash/Check 位于结果卡片内,全部恢复后隐藏无关操作。
+
+恢复由用户在系统回收站完成,再点击 Check。Check 不读取回收站、不移动文件、不覆盖已有内容;它只验证原位置的文件并清除属于本次删除的标记,随后重新扫描。
+
+新记录验证主文件及全部关联文件的路径、类型、逻辑长度与内容摘要,再解析会话并复核快照。缺失文件、目录冒充文件、同长度但内容不同的替换文件都不能标为已恢复。系统跨卷还原产生新 inode/文件 ID 或不同分配量,不影响合法恢复。
+
+旧日志没有内容摘要,兼容检查只能核对类型、长度、修改时间及主会话解析,无法事后证明旧关联文件的逐字节内容。旧自动恢复的权限错误显示手动恢复指引;真正的移动或索引失败仍保留错误信息。不提供应用内自动 Restore:开发目录测试通过无法保证系统允许读取用户已有的回收站目录。
+
+## 验证要求
+
+- 合成文件测试覆盖完整树、源归属、共享文件、同大小同时间的文件替换、取消、部分失败、索引重试和旧日志兼容。
+- 恢复测试覆盖缺失关联文件、错误类型、内容不符、符号链接、跨文件身份还原,以及后续删除标记不能被旧历史清除。
+- Windows 专属测试覆盖路径前缀、本地卷、网络位置以及稀疏/压缩分配量。Cursor CLI 与 IDE 数据库的路由须独立验证;数据库会话不能进入文件候选。
+- CI 在 macOS、Linux、Windows 运行核心测试、应用逻辑测试和构建。Linux/Windows 另显式执行真实系统回收站往返测试,只处理本次唯一临时目录的合成文件,不处理其他条目。
+- UI 验证包含列表、筛选、阅读器返回、确认框和旧历史兼容,不移动真实会话文件。跨目标类型检查不能替代原生系统运行结果。
diff --git a/imgs/session-cleanup.png b/imgs/session-cleanup.png
new file mode 100644
index 0000000..c318464
Binary files /dev/null and b/imgs/session-cleanup.png differ