CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 完善活动恢复核对并排除内部标题线程
Bob26653b82118b
diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.mdindex 9cd78c7..107ce37 100644--- a/.github/ISSUE_TEMPLATE/bug.md+++ b/.github/ISSUE_TEMPLATE/bug.md@@ -1,35 +1,49 @@----name: Bug 报告-about: 报告 CodexBar 中可复现的问题+name: Bug 报告 / Bug report+about: 报告 CodexBar 中可复现的问题 / Report a reproducible problem in CodexBartitle: '[Bug] 'labels: bugassignees: ''----**问题描述**-请清晰, 简洁地描述遇到的问题+## 问题描述 / Description-**复现步骤**-请按顺序列出复现该问题的步骤:+描述遇到的问题。-1. 打开 "..."-2. 点击 "..."-3. 滚动或切换到 "..."-4. 看到错误 "..."+Describe the problem you encountered.-**预期行为**-请描述你原本预期会发生什么+## 复现步骤 / Steps to reproduce-**截图或录屏**-如果适用, 请添加截图或录屏来帮助说明问题+按顺序填写操作步骤:-**运行环境**-请填写以下信息:+List the steps in order:-- macOS 版本:-- CodexBar 版本:-- Codex CLI 版本:-- Codex App 版本:+1. 打开“...” / Open "..."+2. 点击“...” / Click "..."+3. 滚动或切换到“...” / Scroll or switch to "..."+4. 看到错误“...” / See the error "..."-**补充信息**-请添加其他有助于定位问题的上下文, 例如日志窗口中的相关记录, 问题是否稳定复现, 最近是否升级过 CodexBar 或 Codex+## 预期行为 / Expected behavior++描述你预期的结果。++Describe what you expected to happen.++## 截图或录屏 / Screenshots or recordings++可附上能说明问题的截图或录屏。++You can attach screenshots or screen recordings that help illustrate the problem.++## 运行环境 / Environment++- macOS 版本 / macOS version:+- CodexBar 版本 / CodexBar version:+- Codex CLI 版本 / Codex CLI version:+- Codex App 版本 / Codex App version:++## 补充信息 / Additional information++可补充日志窗口中的相关记录、问题是否稳定复现,以及最近是否升级过 CodexBar 或 Codex。++You can include relevant entries from the log window, whether the problem occurs consistently, and whether you recently updated CodexBar or Codex.diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.mdindex 295b64a..e05272d 100644--- a/.github/ISSUE_TEMPLATE/feature.md+++ b/.github/ISSUE_TEMPLATE/feature.md@@ -1,22 +1,37 @@----name: 功能请求-about: 提出 CodexBar 的新功能, 改进建议或体验优化+name: 功能请求 / Feature request+about: 提出 CodexBar 的新功能, 改进建议或体验优化 / Suggest a new feature, improvement, or usability enhancement for CodexBartitle: '[Feature] 'labels: enhancementassignees: ''----**需求描述**-请清晰, 简洁地描述你希望新增或改进的功能+## 需求描述 / Description-**使用场景**-请说明这个功能会在什么场景下使用, 以及希望它解决什么问题+描述希望新增或改进的功能。-**期望方案**-请描述你希望 CodexBar 如何实现或呈现这个功能+Describe the feature you would like to add or improve.-**替代方案**-如果你考虑过其他方案或临时解决办法, 请在这里说明+## 使用场景 / Use case-**补充信息**-请添加其他有助于理解需求的上下文, 例如截图, 录屏, 相关配置, 相似产品参考或具体工作流+说明使用场景和要解决的问题。++Explain when you would use this feature and the problem it would solve.++## 期望方案 / Proposed solution++说明你希望 CodexBar 如何实现或呈现这个功能。++Describe how you would like this feature to work or appear in CodexBar.++## 替代方案 / Alternatives considered++如果考虑过其他方案或临时解决办法,请在这里说明。++Describe any alternatives or workarounds you have considered.++## 补充信息 / Additional information++可补充截图、录屏、相关配置、相似产品参考或具体工作流。++You can include screenshots, screen recordings, relevant settings, examples from similar products, or specific workflows that help explain your request.diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.mdindex 6402c85..7d153c9 100644--- a/.github/ISSUE_TEMPLATE/question.md+++ b/.github/ISSUE_TEMPLATE/question.md@@ -1,27 +1,42 @@----name: 一般问题-about: 询问 CodexBar 的使用方式, 配置, 兼容性或排查思路+name: 一般问题 / General question+about: 询问 CodexBar 的使用方式, 配置, 兼容性或排查思路 / Ask about using, configuring, or troubleshooting CodexBar, or about compatibilitytitle: '[Question] 'labels: questionassignees: ''----**问题**-请清晰, 简洁地描述你想咨询的问题+## 问题 / Question-**相关背景**-请说明你正在做什么, 遇到了什么现象, 以及你已经尝试过哪些操作+写下你想咨询的问题。-**截图或录屏**-如果适用, 请添加截图或录屏来帮助说明问题+Describe what you would like to know.-**运行环境**-如果问题和环境有关, 请填写以下信息:+## 相关背景 / Background-- macOS 版本:-- CodexBar 版本:-- Codex CLI 版本:-- Codex App 版本:+说明你正在做什么、遇到了什么现象,以及已经尝试过哪些操作。-**补充信息**-请添加其他有助于回答问题的上下文, 例如截图, 日志窗口中的相关记录, Codex Hook 或跨设备同步是否开启+Explain what you are trying to do, what you have observed, and what you have already tried.++## 截图或录屏 / Screenshots or recordings++可附上能说明问题的截图或录屏。++You can attach screenshots or screen recordings that help illustrate your question.++## 运行环境 / Environment++如果问题与环境有关,请填写:++If your question depends on your environment, provide the following:++- macOS 版本 / macOS version:+- CodexBar 版本 / CodexBar version:+- Codex CLI 版本 / Codex CLI version:+- Codex App 版本 / Codex App version:++## 补充信息 / Additional information++可补充截图、日志窗口中的相关记录,以及 Codex Hook 或跨设备同步是否开启。++You can include screenshots, relevant entries from the log window, and whether Codex Hook or cross-device sync is enabled.diff --git a/AGENTS.md b/AGENTS.mdindex cf5c4ad..8f843fb 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,4 +1,4 @@-# Repository Guidelines+# Repository guidelines## 语言要求@@ -6,10 +6,10 @@## 实现原则-在目标和约束明确的前提下,优先选择全生命周期综合成本最低的方案,兼顾当前实现、后续维护、可扩展性和未来调整的自由度。+目标和约束明确后,优先选择全生命周期综合成本最低的方案,兼顾实现和维护成本、扩展能力及未来调整空间。- 评估技术债务、路径依赖、维护复杂度和未来重构成本,必要时承担合理的一次性结构调整成本-- 保持实现简单、清晰、实用,以尽可能少的概念、状态、依赖和特殊规则解决问题+- 用尽可能少的概念、状态、依赖和特殊规则解决问题,保持实现清晰、实用- 保持核心逻辑易于理解和验证,模块边界明确、职责合理,优先复用已有能力- 处理必要的边界条件和异常场景,为可预见的变化保留空间- 对生命周期短、影响范围小或需求高度不确定的问题控制前期投入,不为假设中的需求设计复杂架构@@ -19,10 +19,10 @@### 从目标和事实出发-运用第一性原理分析目标、约束和因果关系。经验、惯例和既有路径可以作为参考,不能替代事实和推理。+从目标、约束和因果关系分析问题,用事实检验经验、惯例和既有做法。- 识别用户真正的目标、问题的事实依据、已知约束、未知信息、隐含前提和验收标准,不默认用户已完整定义问题-- 信息可以从现有代码、文档、工具或环境获得时,先自行验证,不把可自行解决的问题交还给用户+- 能从现有代码、文档、工具或环境取得的信息,先自行验证- 区分已确认事实、基于事实的推断、尚待验证的假设和无法确定的部分,不把推测表达为事实- 关键前提不成立时,先指出事实依据及其对结论的影响,再给出可落地的替代方案- 证据不足时,明确缺失信息、不确定性及验证方式@@ -48,9 +48,9 @@- 仅在手段偏离目标、关键前提或约束缺失、存在隐藏的长期成本、有明显更优的替代方案,或涉及安全、合规、数据损失及不可逆后果时,审慎挑战原始需求- 挑战时说明事实依据、推导和实际影响,并给出可执行的替代方案;不机械质疑,不揣测用户动机-- 忠于事实和可验证的推理,不迎合预期,不为表面中立回避判断,不把观点分歧升级为立场对抗+- 根据事实和可验证的推理作出判断,不因用户预期或表面中立改变结论;讨论具体分歧,避免立场对抗- 保持尊重、直接和坚定;用户提供更可靠的事实或推导后,及时修正结论并说明依据,不作无意义的辩护-- 以共同得到准确、低成本且能落地的结果为目标,不以证明谁正确为目标+- 讨论应有助于得到准确、成本合理且能落地的结果## 项目结构与模块组织@@ -161,7 +161,7 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi不要主动 push,不要回滚、覆盖或丢弃他人的未提交修改。用户只要求提交时,不要顺带格式化或修改文件。-提交信息应从完整代码差异中提炼变更的核心用途和目的,说明解决了什么问题、带来了什么行为或能力变化,而不是逐项罗列代码改动:+提交信息应根据完整代码差异,说明解决的问题及行为或能力变化:- 标题概括本次提交最主要的问题或目标,不用次要交互细节或局部实现代替核心目的- body 围绕核心目的解释必要的原因、关键行为变化和影响;实现细节仅在有助于理解目的或评估影响时保留@@ -170,21 +170,20 @@ CodexBar 是面向 macOS 的 `LSUIElement` 菜单栏应用,使用 Swift 6, Swi提交标题使用 `<type>: <中文描述>` 格式:- 常用 type 包括 `feat` `fix` `chore` `refactor` `docs`-- message 里不要出现版本号或发布字样,只描述改动本身,版本信息由 tag 承载+- message 只描述改动,不写版本号、Release 标记或其他发布相关内容;版本信息写在 tag 中- 修复和发布提交需要 body- 标题与 body 之间空一行- body 中的 bullet 连续排列,每条缩进 4 个空格-- commit message 中不要出现版本号,Release 标记或其他发布版本相关内容Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读取,使用附注 tag `git tag -a v3.x.y -m "Release v3.x.y"`## 代码修改原则- 优先结合现有文件结构和类型职责,不为小改动新建抽象-- **内部逻辑与界面需求分开处理**:修复数据完整性、错误处理、重试或恢复等内部问题时,默认保持现有界面。内部区分成功、失败或部分恢复,不代表需要增加界面标注。未经用户明确要求或同意,不新增提示、标签、状态文案或其他展示内容;确需调整界面时,先说明必要性和具体改动,取得同意后再实施+- **内部逻辑与界面需求分开处理**:修复数据完整性、错误处理、重试或恢复等内部问题时,默认保持现有界面,包括内部新增成功、失败或部分恢复状态的情况。未经用户明确要求或同意,不新增提示、标签、状态文案或其他展示内容;确需调整界面时,先说明必要性和具体改动,取得同意后再实施- 改 shared controller、shared service、模型解析或持久化 key 时,要考虑旧数据和降级路径;用户设置要保持默认值;持久化 key 和旧版本迁移兼容- **任何兼容性问题都必须主动询问用户,不要自行决定**;只要改动会影响新旧共存就适用,不限于旧数据迁移或丢弃、持久化 key 改名或改结构、老版本升上来的降级路径、最低系统版本与 API 可用性取舍、云端记录格式变更、内部版本变化;先说清影响面和几种做法的代价,等用户选定再动手- 处理窗口、菜单、快捷键、App 激活或事件监听时,特别注意 `LSUIElement` 应用特有的焦点行为- 不做辅助功能(Accessibility)适配,不新增辅助功能标签、特征或操作-- 注释保持克制,只解释非显然的生命周期、焦点、actor 或系统 API 约束;现有注释多为解释为什么的类型,沿用同样风格+- 注释只解释代码中不明显的生命周期、焦点、actor 或系统 API 约束及其原因- 改动涉及菜单面板、窗口焦点、活动采集、同步、通知、自动重置唤醒或防睡眠时,构建通过之外还要说明应手动覆盖的交互场景;helper 相关改动额外要验证 App 包内 helper 与 plist 位置、签名、首次系统授权、运行/等待切换、唤醒计划替换与清理和异常退出后的恢复diff --git a/CodexBar/App/CodexBarAppDelegate.swift b/CodexBar/App/CodexBarAppDelegate.swiftindex 0823887..dafe34f 100644--- a/CodexBar/App/CodexBarAppDelegate.swift+++ b/CodexBar/App/CodexBarAppDelegate.swift@@ -2,7 +2,7 @@ import AppKitimport Combineimport os-/// 应用级对象装配点, 持有服务和 ViewModel 生命周期+/// 创建并持有应用级服务和 ViewModel@MainActorfinal class CodexBarAppDelegate: NSObject, NSApplicationDelegate {private lazy var codexStatusService = CodexStatusService(logStorage: .shared, startup: appServerStartup)@@ -200,7 +200,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {return .terminateLater}- /// 启动时把各开关的初始值记成一条基线, 之后的变更日志都是相对这条基线的增量+ /// 启动时记录各开关的初始值, 后续日志只记录变化private func logLaunchState() {// 先拼成普通字符串再交给 Logger, 避免在日志 autoclosure 中直接捕获属性let state = LogFields.joined(diff --git a/CodexBar/Controllers/ActivityPanelController.swift b/CodexBar/Controllers/ActivityPanelController.swiftindex 7b67e8d..d611606 100644--- a/CodexBar/Controllers/ActivityPanelController.swift+++ b/CodexBar/Controllers/ActivityPanelController.swift@@ -73,7 +73,7 @@ final class ActivityPanelController {func hide(immediate: Bool = false) {cancelScheduledPresentation()- // 热力图 hover 等高频路径会盲调 hide; 已隐藏时跳过 @Published 写入, 避免整个菜单重算+ // 热力图 hover 等高频路径会反复调用 hide, 已隐藏时跳过 @Published 写入以免整个菜单重算if presentationState.isPresented || presenter.isVisible {cancelScheduledPanelUpdate()presentationState.isPresented = falsediff --git a/CodexBar/Controllers/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swiftindex 07efe17..1186c86 100644--- a/CodexBar/Controllers/GlobalHotKeyController.swift+++ b/CodexBar/Controllers/GlobalHotKeyController.swift@@ -44,7 +44,7 @@ final class GlobalHotKeyController {)guard status == noErr else {- // 最常见的原因是快捷键已被其他 App 占用, 用户只会看到"按了没反应"+ // 注册失败最常见的原因是快捷键被其他 App 占用, 此时按键不会触发操作let details = LogFields.joined("stage=register","code=\(status)"diff --git a/CodexBar/Controllers/OptionsPanelController.swift b/CodexBar/Controllers/OptionsPanelController.swiftindex a8fd2f9..d11d032 100644--- a/CodexBar/Controllers/OptionsPanelController.swift+++ b/CodexBar/Controllers/OptionsPanelController.swift@@ -12,17 +12,17 @@ enum SettingsOptionsPanel: CaseIterable, Hashable {}/// 子选项面板动作, 由 AppSettingsView 发出并在 SettingsWindowController 中路由-/// 展开时带上主开关行的 anchor, 面板顶边要对齐那一行而不是设置窗口底边+/// 展开时传入主开关行的 anchor, 用于对齐面板顶边enum SettingsOptionsPanelAction {case toggle(panel: SettingsOptionsPanel, anchorProvider: ScreenFrameProvider)case close(panel: SettingsOptionsPanel)- /// 切换分页时一次收掉全部; 视图不必知道一共有几个面板+ /// 切换分页时收起全部子面板, 视图无需逐个处理case closeAll}/// 子面板入场时的内容重建信号-/// 原生 Switch 的 thumb 由 WindowPortal 投射, 面板首次布局那一轮建不起来也不会自愈, 只有重建补得上-/// bump 排在 present 之后, 那时动画效果已经把内容 translation 到可视区外, 重建才看不见+/// 原生 Switch 的 thumb 由 WindowPortal 投射, 首次布局失败后需要重建内容才能显示+/// bump 在 present 之后执行, 此时动画已将内容移出可视区, 重建过程不可见@MainActorprivate final class SidePanelEntryCue: ObservableObject {@Published private(set) var pass = 0@@ -32,7 +32,7 @@ private final class SidePanelEntryCue: ObservableObject {}}-/// 把重建信号接到内容外面, 于是内容视图不必为这个宿主层的问题多带一个属性+/// 在内容外层接收重建信号, 内容视图无需保存宿主的重建状态private struct SidePanelEntryRebuildHost<Content: View>: View {@ObservedObject var cue: SidePanelEntryCuelet content: Content@@ -44,12 +44,12 @@ private struct SidePanelEntryRebuildHost<Content: View>: View {/// 设置窗口右侧子选项面板的公共装配/// 各子面板只差内容视图与高度变化来源, 窗口组关闭规则由 SettingsWindowController 统一维护-/// 与重置次数面板不同: 内容是交互控件, 用常驻 hosting controller + ObservableObject 驱动更新, 不替换 rootView+/// 设置面板包含交互控件, 使用常驻 hosting controller 和 ObservableObject 更新, 不像重置次数面板那样替换 rootView@MainActorfinal class OptionsPanelController {private let animationKey: Stringprivate let initialPanelSize: CGSize- /// 展开前的准备动作, 例如刷新只在这个面板里露面的设置项+ /// 展开前的准备动作, 例如刷新仅在此面板显示的设置项private let willShow: (() -> Void)?private let willHide: (() -> Void)?private let contentControllerProvider: (SidePanelEntryCue) -> NSViewController@@ -137,7 +137,7 @@ final class OptionsPanelController {}private func scheduleResize() {- // isVisible 也在同步守卫里: 收着的面板不必为每次内容变化排一个 Task 再让出两轮 runloop+ // 同步检查 isVisible, 隐藏时跳过 Task 创建及两轮 runloop 等待guard panel?.isVisible == true, !isEntryAnimationRunning else {return}@@ -170,12 +170,12 @@ final class OptionsPanelController {}willShow?()- // 只有刚构造出来的那一次需要重建, hosting controller 之后常驻, portal 已经建好+ // 仅首次构造后需要重建, 后续复用常驻 hosting controller 和已创建的 portallet needsEntryRebuild = panel == nillet panel = ensurePanel()(panel as? KeyableBorderlessPanel)?.sharedUndoManager = window.undoManager- // 这里不必先布局: 下面 measuredPanelSize 走的 validFittingSize 第一句就是 layoutSubtreeIfNeeded- // 而中间两句只碰设置窗口那棵树, 不会把面板弄脏+ // measuredPanelSize 会通过 validFittingSize 调用 layoutSubtreeIfNeeded, 无需提前布局+ // 此前的操作只影响设置窗口, 不会使面板布局失效let windowSurfaceFrame = SidePanelSupport.contentScreenFrame(for: contentView, in: window) ?? window.framelet screen = window.screen ?? NSScreen.mainlet visibleFrame = screen?.visibleFrame ?? windowSurfaceFrame@@ -184,7 +184,7 @@ final class OptionsPanelController {menuSurfaceFrame: windowSurfaceFrame)let panelSize = measuredPanelSize()- // clampsToSurfaceBottom 传 false: 顶边要对齐主开关行, 放不下时底边探出窗口也不能把整个面板上推+ // clampsToSurfaceBottom 设为 false, 保持顶边对齐主开关行, 允许底边超出设置窗口let position = SidePanelSupport.anchoredPosition(panelSize: panelSize,menuSurfaceFrame: windowSurfaceFrame,@@ -206,7 +206,7 @@ final class OptionsPanelController {isEntryAnimationRunning = falsescheduleResize()}- // 排在 present 之后: 动画效果先把内容 translation 到可视区外, 这一次重建落在那段里, 看不见+ // present 已将内容移出可视区, 此时重建不会出现在画面中if needsEntryRebuild {entryCue.bump()}@@ -243,14 +243,14 @@ final class OptionsPanelController {return}- // 面板顶边对齐主开关行, 所以增删内容行时要向下生长- // 直接改 size 会保持底边不动而把顶边顶上去, 那样就跟主开关行错开了+ // 增删内容时固定顶边, 让高度向下变化, 保持与主开关行对齐+ // 直接修改 size 会固定底边, 导致顶边偏移var targetFrame = panel.framelet topEdge = targetFrame.maxYtargetFrame.size = sizetargetFrame.origin.y = topEdge - targetFrame.heightif let visibleFrame = panel.screen?.visibleFrame {- // 与初次展开走同一条夹紧规则, 否则放不下时重算的位置会和 position 给的位置对不上+ // 复用初次展开的夹紧规则, 保持重算位置与 position 的结果一致targetFrame = SidePanelSupport.clampedVertically(targetFrame, in: visibleFrame)}diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 8130727..4b1aab5 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -24,7 +24,7 @@ final class SettingsWindowController: HostingWindowController {private let animationState = SettingsWindowAnimationState()private var windowFocusObserver: AnyCancellable?private var windowVisibilityObserver: AnyCancellable?- /// 只在真的要展开时构造: hosting controller 与动态面板订阅会常驻到 App 结束, 而用户可能一次子面板都没开过+ /// 首次展开时才构造, 避免未使用的子面板持有 hosting controller 和订阅直到 App 退出private var optionsPanelControllers: [SettingsOptionsPanel: OptionsPanelController] = [:]private var optionsDismissEventMonitor: Any?private var optionsDismissFocusObserver: AnyCancellable?@@ -176,7 +176,7 @@ final class SettingsWindowController: HostingWindowController {return controller}- /// 没建过就说明它不可能开着, 收起动作不必为此把它构造出来+ /// 收起时只处理已创建的子面板private func existingOptionsPanelController(_ panel: SettingsOptionsPanel) -> OptionsPanelController? {@@ -344,9 +344,8 @@ final class SettingsWindowController: HostingWindowController {optionsDismissedByClick = nil}- /// 子面板占设置窗口右侧同一位置, 展开一个必须先收掉其余的- /// 收旧面板用 immediate, 否则滑回与滑出在同一处交叠- /// 互斥规则只写在这里, 再加一个面板也不会漏掉某一对+ /// 子面板共用设置窗口右侧的位置, 展开前用 immediate 收起其他面板, 避免出入场动画交叠+ /// 所有子面板共用此互斥规则private func handleOptionsAction(_ action: SettingsOptionsPanelAction) {switch action {case let .toggle(panel, anchorProvider):diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swiftindex f46df00..7a76c96 100644--- a/CodexBar/Controllers/SidePanelSupport.swift+++ b/CodexBar/Controllers/SidePanelSupport.swift@@ -100,7 +100,7 @@ enum SidePanelSupport {/// 水平方向优先贴在请求侧, 空间不足时换边, 最后夹紧到屏幕可见区域/// 纵向由调用方给出期望位置, 这里统一夹紧/// clampsToSurfaceBottom 为 true 时面板底边不低于宿主内容区底边, 适合锚点行随内容滚动的菜单面板- /// 设置窗口的子面板要严格贴住主开关行, 放不下时宁可让底边探出窗口, 所以传 false+ /// 设置子面板传 false, 固定顶边与主开关行对齐, 允许底边超出窗口static func position(panelSize: CGSize,menuSurfaceFrame: CGRect,@@ -299,7 +299,7 @@ enum SidePanelSupport {}/// 面板竖向夹回可见区域, 与 position 用同一条内边距和越界规则- /// 高度变化后重新定位要走这里, 否则重算出的位置会和初次展开的位置对不上+ /// 高度变化后也调用此方法, 保持重算位置与初次展开一致static func clampedVertically(_ frame: CGRect, in visibleFrame: CGRect) -> CGRect {var frame = frameframe.origin.y = clamped(diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex b7f7317..6c8f710 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -59,7 +59,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {) { [weak self] inself?.statusItem.button?.window?.screen} onSyncChanged: { [weak self] _ in- // setEnabled 在回调之前已经写回属性, 现场求值就是新结论+ // setEnabled 在回调前已更新属性, 此时可以读取新值self?.syncScheduler.requestSync(trigger: .settings)} onRebuildHistoryData: { [weak self] dateKeys, completion inguard let self else {@@ -779,7 +779,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {scheduleAuxiliaryWindowKeyFocusRestore()}- /// 侧边面板互斥名册: 新增面板只需要加入这里, 显隐与点击区域判定即可覆盖+ /// 侧边面板列表, 新增面板后共用互斥显隐和点击区域判定private var sideDetailPanels: [MenuSideDetailPanel] {[heatmapDetailPanelController, resetCreditsPanelController, activityCenterPanelController]}@@ -981,7 +981,7 @@ extension StatusItemController: NSPopoverDelegate {}}-/// 菜单侧边面板的互斥名册接口; 面板间互斥和点击区域判定统一走名册遍历+/// 菜单侧边面板接口, 供列表遍历时处理互斥显隐和点击区域判定private protocol MenuSideDetailPanel: AnyObject {func hide(immediate: Bool)func containsScreenPoint(_ screenPoint: NSPoint) -> Booldiff --git a/CodexBar/Models/ActivityInput.swift b/CodexBar/Models/ActivityInput.swiftindex a98945c..c4d50bd 100644--- a/CodexBar/Models/ActivityInput.swift+++ b/CodexBar/Models/ActivityInput.swift@@ -91,6 +91,7 @@ nonisolated struct ActivityThread {var origin: ActivityDataOrigin = .unknownvar parentThreadID: String?var createdAt: Date?+ var threadSource: String?}nonisolated struct ActivityThreadStatus {diff --git a/CodexBar/Models/AppServerEventRecord.swift b/CodexBar/Models/AppServerEventRecord.swiftindex 7589190..fe674eb 100644--- a/CodexBar/Models/AppServerEventRecord.swift+++ b/CodexBar/Models/AppServerEventRecord.swift@@ -70,15 +70,7 @@ nonisolated struct AppServerEventRecord: Codable, Equatable {}static func decode(from data: Data) throws -> Self {- try decode(Self.self, from: data)- }-- static func decode<Value: Decodable>(_ type: Value.Type, from data: Data) throws -> Value {- try decoder.decode(type, from: data)- }-- static func encode(_ value: some Encodable) throws -> Data {- try encoder.encode(value)+ try decoder.decode(Self.self, from: data)}private static let encoder = JSONLines.stableEncoderdiff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swiftindex b37f342..5846b34 100644--- a/CodexBar/Models/CodexQuotaModels.swift+++ b/CodexBar/Models/CodexQuotaModels.swift@@ -86,8 +86,7 @@ private nonisolated extension String {}}-/// primary/secondary 窗口的稳定标识; 这组词汇由模型层拥有-/// 菜单栏额度指示偏好 (MenuBarQuotaSelection) 与窗口查找都经它互转+/// 模型层定义的 primary/secondary 窗口标识, 用于转换菜单栏额度偏好 (MenuBarQuotaSelection) 和查找窗口nonisolated enum QuotaWindowKind: String, Equatable {case primarycase secondarydiff --git a/CodexBar/Models/StorageVersion.swift b/CodexBar/Models/StorageVersion.swiftindex 10e5bf4..939833a 100644--- a/CodexBar/Models/StorageVersion.swift+++ b/CodexBar/Models/StorageVersion.swift@@ -5,7 +5,6 @@ nonisolated enum StorageCompatibilityError: Error, Equatable {case unsupportedFormat(String, Int)case unsupportedAlgorithm(String, Int)case incompleteSource- case sourceConflict}nonisolated enum StorageVersion {diff --git a/CodexBar/Services/Activity/ActivityMonitor+Protection.swift b/CodexBar/Services/Activity/ActivityMonitor+Protection.swiftindex a4aa0a5..90ca68b 100644--- a/CodexBar/Services/Activity/ActivityMonitor+Protection.swift+++ b/CodexBar/Services/Activity/ActivityMonitor+Protection.swift@@ -28,7 +28,7 @@ extension ActivityMonitor {let now = Date()guard enabled else {- restoreAllSuppressedActivityTasks(restoredAt: now)+ restoreAllSuppressedActivityTasks()refreshSnapshot(now: now)return}@@ -41,30 +41,26 @@ extension ActivityMonitor {reconcileProtection(now: Date(), sendsNotification: false)}- @discardableResult- func beginProtectionRecovery() -> UInt64 {- protectionRecoveryGeneration &+= 1- isProtectionRecoveryInProgress = true+ func beginProtectionRecovery(generation: UUID = UUID()) {+ activeRecoveryID = generationturnTransitionNotBefore = nilresetTerminalPresentationCutoff()cancelInactivityCheck()cancelAllProtectionAttempts()- return protectionRecoveryGeneration}- func finishProtectionRecovery(generation: UInt64) {- guard generation == protectionRecoveryGeneration else {+ func finishProtectionRecovery(generation: UUID) {+ guard generation == activeRecoveryID else {return}resetTerminalPresentationCutoff()- isProtectionRecoveryInProgress = false+ activeRecoveryID = nilturnTransitionNotBefore = Date()reconcileProtection(now: Date(), sendsNotification: false)}func resetProtectionRecovery() {- protectionRecoveryGeneration &+= 1- isProtectionRecoveryInProgress = false+ activeRecoveryID = nilcancelAllProtectionAttempts()}@@ -90,7 +86,7 @@ extension ActivityMonitor {continue}- suppressedTasks[key] = record.markedAt+ suppressedTasks.insert(key)}}@@ -111,18 +107,18 @@ extension ActivityMonitor {let threshold = protectionSettings.inactivityDuration.timeIntervallet restorableKeys = tasks.compactMap { key, task -> ActivityTaskKey? in- guard suppressedTasks[key] != nil,+ guard suppressedTasks.contains(key),task.protectionReferenceAt.addingTimeInterval(threshold) > now else {return nil}return key}for key in restorableKeys {- restoreActivityTaskForCurrentThreshold(key, restoredAt: now)+ restoreActivityTaskForCurrentThreshold(key)}let overdueKeys = tasks.compactMap { key, task -> ActivityTaskKey? in- guard task.state == .running, suppressedTasks[key] == nil,+ guard task.state == .running, !suppressedTasks.contains(key),let deadline = task.protectionDeadline(at: now, inactivityDuration: threshold),deadline <= now else {return nil@@ -143,7 +139,7 @@ extension ActivityMonitor {let threshold = protectionSettings.inactivityDuration.timeIntervallet nextDeadline = tasks.compactMap { key, task -> Date? in- guard task.state == .running, suppressedTasks[key] == nil,+ guard task.state == .running, !suppressedTasks.contains(key),protectionAttempts[key] == nil else {return nil}@@ -187,7 +183,7 @@ extension ActivityMonitor {let threshold = protectionSettings.inactivityDuration.timeIntervallet candidates = tasks.compactMap { key, task -> ProtectionCandidate? in- guard task.state == .running, suppressedTasks[key] == nil,+ guard task.state == .running, !suppressedTasks.contains(key),protectionAttempts[key] == nil,let deadline = task.protectionDeadline(at: now, inactivityDuration: threshold),deadline <= now else {@@ -292,7 +288,7 @@ extension ActivityMonitor {}guard tasks[key] != nil else { return }- suppressedTasks[key] = attempt.markedAt+ suppressedTasks.insert(key)AppLog.activity.notice("异常任务已隐藏: thresholdMinutes=\(attempt.candidate.inactivityDuration.loggedMinutes)")@@ -314,7 +310,7 @@ extension ActivityMonitor {lastProgressAt: task.lastProgressAt,markedAt: markedAt)- suppressedTasks[key] = markedAt+ suppressedTasks.insert(key)AppLog.activity.notice("异常任务已静默隐藏: reason=reconcile")}@@ -324,7 +320,7 @@ extension ActivityMonitor {) {guard canEvaluateProtection,let task = tasks[key],- task.state == .running, suppressedTasks[key] == nil,+ task.state == .running, !suppressedTasks.contains(key),let deadline = task.protectionDeadline(at: now, inactivityDuration: protectionSettings.inactivityDuration.timeInterval),deadline <= now else {return@@ -332,11 +328,8 @@ extension ActivityMonitor {suppressActivityTaskSilently(key, markedAt: now)}- func restoreActivityTaskForCurrentThreshold(- _ key: ActivityTaskKey,- restoredAt _: Date- ) {- guard let task = tasks[key], suppressedTasks[key] != nil else {+ func restoreActivityTaskForCurrentThreshold(_ key: ActivityTaskKey) {+ guard let task = tasks[key], suppressedTasks.contains(key) else {return}@@ -348,15 +341,15 @@ extension ActivityMonitor {AppLog.activity.notice("异常任务已静默恢复: reason=thresholdChange")}- func restoreAllSuppressedActivityTasks(restoredAt _: Date) {+ func restoreAllSuppressedActivityTasks() {let suppressedKeys = tasks.compactMap { key, _ in- suppressedTasks[key] != nil ? key : nil+ suppressedTasks.contains(key) ? key : nil}for key in suppressedKeys {guard let task = tasks[key] else {continue}- suppressedTasks.removeValue(forKey: key)+ suppressedTasks.remove(key)invalidateProtectionNotification(for: task.displayID)}for (taskID, attemptID) in Array(protectionNoticeAttemptIDs) {@@ -377,7 +370,7 @@ extension ActivityMonitor {protectionSettings.inactivityDuration == candidate.inactivityDuration,let task = tasks[candidate.key],task.displayID == candidate.taskID,- task.state == .running, suppressedTasks[candidate.key] == nil,+ task.state == .running, !suppressedTasks.contains(candidate.key),task.lastProgressAt == candidate.lastProgressAt,task.progressGeneration == candidate.progressGeneration else {return false@@ -415,7 +408,7 @@ extension ActivityMonitor {taskID: UUID?,reason: ProtectionClearReason) {- suppressedTasks.removeValue(forKey: key)+ suppressedTasks.remove(key)cancelProtectionAttempt(for: key)let identifier = key.protectionIdentifierif let record = protectionRecords.removeValue(forKey: identifier) {diff --git a/CodexBar/Services/Activity/ActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swiftindex 49efcbe..579cd24 100644--- a/CodexBar/Services/Activity/ActivityMonitor.swift+++ b/CodexBar/Services/Activity/ActivityMonitor.swift@@ -52,7 +52,7 @@ final class ActivityMonitor: ObservableObject {var activityReader: AppServerActivityReader?private var activityReaderControlTask: Task<Void, Never>?private var activityReaderGeneration: UInt64 = 0- private var recoveryTask: Task<Void, Never>?+ private(set) var recoveryTask: Task<Void, Never>?private var recoveryTaskID: UUID?private var isSystemSleeping = falseprivate var recoveryRetryTask: Task<Void, Never>?@@ -60,7 +60,7 @@ final class ActivityMonitor: ObservableObject {private var cleanupDeadline: Date?var inactivityCheckTask: Task<Void, Never>?var inactivityCheckDeadline: Date?- var suppressedTasks: [ActivityTaskKey: Date] = [:]+ var suppressedTasks: Set<ActivityTaskKey> = []var protectionAttempts: [ActivityTaskKey: ProtectionAttempt] = [:]var protectionNoticeAttemptIDs: [UUID: UUID] = [:]var protectionRecords: [String: ProtectionRecord] = [:]@@ -77,8 +77,11 @@ final class ActivityMonitor: ObservableObject {@Published var isActivitySourceHealthy = false@Published private(set) var sourcePresentation: ActivityLiveLabel? = ActivityLiveLabel("unavailable")private var hasConnectedActivitySource = false- var isProtectionRecoveryInProgress = false- var protectionRecoveryGeneration: UInt64 = 0+ var activeRecoveryID: UUID?+ var isProtectionRecoveryInProgress: Bool {+ activeRecoveryID != nil+ }+private var cancellables = Set<AnyCancellable>()private var isPreparingForTermination = falsevar isStarted = false@@ -142,6 +145,7 @@ final class ActivityMonitor: ObservableObject {"事件重读已触发: trigger=\(LogTrigger.wake.rawValue, privacy: .public)")isSystemSleeping = false+ beginProtectionRecovery()requestActivityRecovery()}.store(in: &cancellables)@@ -324,15 +328,14 @@ final class ActivityMonitor: ObservableObject {}/// 恢复结果携带屏障之后发布的同一份快照, 不再跨 actor 查询第二份状态- private func requestActivityRecovery() {- guard !isSystemSleeping, let reader = activityReader, !isBootstrapping else { return }+ func requestActivityRecovery() {+ guard !isSystemSleeping, let reader = activityReader, !isBootstrapping, let recoveryGeneration = activeRecoveryID else { return }recoveryTask?.cancel()- let recoveryGeneration = beginProtectionRecovery()let generation = activityReaderGenerationlet taskID = UUID()recoveryTaskID = taskIDrecoveryTask = Task { @MainActor [weak self] in- let result = await reader.drainNow()+ let result = await reader.drainForRecovery(generation: recoveryGeneration)guard let self else { return }defer {if recoveryTaskID == taskID {@@ -341,14 +344,13 @@ final class ActivityMonitor: ObservableObject {}}guard !Task.isCancelled, generation == activityReaderGeneration,- recoveryGeneration == protectionRecoveryGeneration, !isSystemSleeping else { return }+ recoveryGeneration == activeRecoveryID, !isSystemSleeping else { return }switch result {- case let .completed(update):+ case let .update(update):consume(update)- guard isActivitySourceHealthy, !isBootstrapping else { return }+ guard update.isComplete, isActivitySourceHealthy, !isBootstrapping, graph.unavailableTurns.isEmpty,+ update.recoveryID == recoveryGeneration else { return }finishProtectionRecovery(generation: recoveryGeneration)- case let .partial(update):- consume(update)case .sourceUnavailable, .cancelled: break}}@@ -391,7 +393,7 @@ final class ActivityMonitor: ObservableObject {turnTransitionNotBefore = nilisActivitySourceHealthy = falseresetTerminalPresentationCutoff()- beginProtectionRecovery()+ beginProtectionRecovery(generation: update.recoveryID)publishSnapshot(.empty)case .snapshotEvents:if isBootstrapping {@@ -405,7 +407,7 @@ final class ActivityMonitor: ObservableObject {turnTransitionNotBefore = Date()resetTerminalPresentationCutoff()if !isSystemSleeping, update.isComplete, graph.unavailableTurns.isEmpty {- finishProtectionRecovery(generation: protectionRecoveryGeneration)+ finishProtectionRecovery(generation: update.recoveryID)}applyPersistedProtection(now: Date())reconcileProtection(now: Date(), sendsNotification: false)@@ -483,7 +485,7 @@ final class ActivityMonitor: ObservableObject {private func sortedTasks(in state: ActivityTaskState) -> [ActivityTask] {tasks.values- .filter { $0.state == state && suppressedTasks[$0.key] == nil && !graph.unavailableTurns.contains($0.key) }+ .filter { $0.state == state && !suppressedTasks.contains($0.key) && !graph.unavailableTurns.contains($0.key) }.sorted(by: Self.recentFirst(\.lastActivityAt, \.displayID))}diff --git a/CodexBar/Services/Activity/AppServerActivityModels.swift b/CodexBar/Services/Activity/AppServerActivityModels.swiftindex b5d7122..dd7ea98 100644--- a/CodexBar/Services/Activity/AppServerActivityModels.swift+++ b/CodexBar/Services/Activity/AppServerActivityModels.swift@@ -9,6 +9,7 @@ private nonisolated struct WireActivityThread: Decodable {var source: WireActivityThreadSource?var parentThreadId: String?var createdAt: Double?+ var threadSource: String?var origin: ActivityDataOrigin {source?.origin ?? .unknown@@ -22,9 +23,6 @@ private nonisolated struct WireActivityThread: Decodable {private nonisolated struct WireActivityThreadStatus: Decodable {let type: Stringvar activeFlags: [String]?- var isWaiting: Bool {- activeFlags?.contains("waitingOnApproval") == true- }}private nonisolated struct WireActivityThreadSource: Decodable {@@ -366,7 +364,8 @@ private nonisolated extension WireActivityThread {status: status.map(ActivityThread.status),origin: origin,parentThreadID: parentThreadID,- createdAt: createdAt.map(Date.init(timeIntervalSince1970:))+ createdAt: createdAt.map(Date.init(timeIntervalSince1970:)),+ threadSource: threadSource)}}diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swiftindex a1b00c6..a1d5a0d 100644--- a/CodexBar/Services/Activity/AppServerActivityReader.swift+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift@@ -18,28 +18,20 @@ nonisolated struct ActivityUpdate {let terminalEvents: [ActivityTerminalEvent]let backfilledTasks: Set<ActivityTaskKey>var isComplete = true+ let recoveryID: UUID}nonisolated enum ActivityEventDrainResult: Sendable {- case completed(ActivityUpdate)- case partial(ActivityUpdate)+ case update(ActivityUpdate)case sourceUnavailablecase cancelled-- enum Status { case completed, partial, sourceUnavailable, cancelled }-- var status: Status {- switch self {- case .completed: .completed- case .partial: .partial- case .sourceUnavailable: .sourceUnavailable- case .cancelled: .cancelled- }- }}/// actor 独占连接与解析状态, UI 仅消费任务图和本次状态变化actor AppServerActivityReader {+ /// 只排除已确认无需采集的来源, 缺失或未知来源继续正常处理+ private static let ignoredThreadSources: Set<String> = ["thread_title"]+nonisolated static var defaultSocketURL: URL {CodexPaths.codexHomeDirectory().appendingPathComponent("app-server-control/app-server-control.sock")}@@ -60,6 +52,7 @@ actor AppServerActivityReader {private var connectedAt = Date.distantFutureprivate var reducer = AppServerActivityReducer()private var subscribed = Set<String>()+ private var ignoredThreads = Set<String>()private var loop: Task<Void, Never>?private var storageTask: Task<Void, Never>?private var tokenUsageRefreshTask: Task<[TokenUsageAggregate], Error>?@@ -73,7 +66,8 @@ actor AppServerActivityReader {private var lastPublished = Date.distantPastprivate var isTokenUsageWriter = falseprivate var writerRetryAfter = Date.distantPast- private var drainWaiters: [CheckedContinuation<ActivityEventDrainResult, Never>] = []+ private var drainWaiters: [DrainWaiter] = []+ private var recoveryID = UUID()private var pendingEvents: [(event: ActivityDataRecord, bytes: Int)] = []private var pendingPublication: [ActivityDataRecord] = []private var pendingSamples: [(sample: TokenUsageSample, bytes: Int)] = []@@ -104,6 +98,48 @@ actor AppServerActivityReader {let turns: [ActivityTurnReference: Int]}+ private struct DrainWaiter {+ let recoveryID: UUID+ let continuation: CheckedContinuation<ActivityEventDrainResult, Never>+ }++ private struct ThreadCheck {+ var checkedAt: ContinuousClock.Instant+ var verifiedRevision: Int?+ var recoveryID: UUID?+ var failures = 0+ var failureStartedAt: ContinuousClock.Instant?+ var retryAfter: ContinuousClock.Instant?++ mutating func record(verifiedRevision: Int?, failed: Bool, recoveryID: UUID, now: ContinuousClock.Instant) {+ checkedAt = now+ self.verifiedRevision = verifiedRevision+ if self.recoveryID != recoveryID {+ failures = 0+ failureStartedAt = nil+ }+ self.recoveryID = recoveryID+ guard failed else {+ failures = 0+ failureStartedAt = nil+ retryAfter = verifiedRevision == nil ? now.advanced(by: .seconds(5)) : nil+ return+ }+ failures = min(failures + 1, 4)+ let started = failureStartedAt ?? now+ failureStartedAt = started+ // 快速重试同时受次数和时间限制, 随后保留低频探测以发现延迟落盘的线程+ let delays: [Duration] = [.seconds(5), .seconds(15), .seconds(30), .seconds(60)]+ let delay = now - started < .seconds(60) ? delays[failures - 1] : .seconds(60)+ retryAfter = now.advanced(by: delay)+ }++ mutating func expedite(at now: ContinuousClock.Instant) {+ guard let retryAfter else { return }+ self.retryAfter = min(retryAfter, max(now, checkedAt.advanced(by: .seconds(5))))+ }+ }+private struct BackfillScan {var completed = falsevar cursor: String?@@ -114,7 +150,7 @@ actor AppServerActivityReader {var checkedAt = Date.distantPast}- private var checkedThreads: [String: Date] = [:]+ private var threadChecks: [String: ThreadCheck] = [:]private var revisions: [String: Int] = [:]private var preparingThread: String?private var invalidThreads = Set<String>()@@ -125,6 +161,7 @@ actor AppServerActivityReader {private let maximumPendingBytes: Intprivate let maximumLoadedPages: Intprivate let reconciliationTimeout: TimeInterval+ private let reconciliationClock: @Sendable () -> ContinuousClock.Instantinit(socketURL: URL = AppServerActivityReader.defaultSocketURL,@@ -135,6 +172,7 @@ actor AppServerActivityReader {maximumPendingBytes: Int = 8 * 1024 * 1024,maximumLoadedPages: Int = 100,reconciliationTimeout: TimeInterval = 30,+ reconciliationClock: @escaping @Sendable () -> ContinuousClock.Instant = { .now },onAccountChange: @escaping @MainActor @Sendable (AccountChange) -> Void = { _ in },onBatch: @escaping @MainActor @Sendable (ActivityUpdate) -> Void) {@@ -147,6 +185,7 @@ actor AppServerActivityReader {self.maximumPendingBytes = maximumPendingBytesself.maximumLoadedPages = maximumLoadedPagesself.reconciliationTimeout = reconciliationTimeout+ self.reconciliationClock = reconciliationClockself.onAccountChange = onAccountChangeself.onBatch = onBatch}@@ -185,6 +224,7 @@ actor AppServerActivityReader {session = nilsubscribed.removeAll()await previous?.value+ ignoredThreads.removeAll()pendingAccountChange = nilpendingPublication.removeAll()deferredNotifications.removeAll()@@ -192,7 +232,7 @@ actor AppServerActivityReader {turnScans.removeAll()turnRevisions.removeAll()cancelBackfill()- checkedThreads.removeAll()+ threadChecks.removeAll()invalidThreads.removeAll()if storageTask == nil, !pendingEvents.isEmpty || !pendingSamples.isEmpty {startStorageWorker()@@ -209,10 +249,13 @@ actor AppServerActivityReader {}/// 每次调用执行本次请求之后的查询, 不复用正在进行的旧快照- func drainNow() async -> ActivityEventDrainResult {+ /// 同一轮恢复只补读未核对成功的线程, 新一轮恢复仍执行完整读取屏障+ func drainForRecovery(generation: UUID) async -> ActivityEventDrainResult {guard isRunning, !Task.isCancelled else { return .cancelled }guard session != nil else { return .sourceUnavailable }- let result = await withCheckedContinuation { drainWaiters.append($0) }+ let result = await withCheckedContinuation {+ drainWaiters.append(DrainWaiter(recoveryID: generation, continuation: $0))+ }return Task.isCancelled ? .cancelled : result}@@ -226,26 +269,27 @@ actor AppServerActivityReader {if !drainWaiters.isEmpty || Date().timeIntervalSince(reconciledAt) >= 2 {let waiters = drainWaitersdrainWaiters.removeAll()+ let requestedRecovery = waiters.last?.recoveryID+ let forced = requestedRecovery != nil && requestedRecovery != recoveryID+ if forced, let requestedRecovery {+ recoveryID = requestedRecovery+ }do {- let covered = try await reconcile(bootstrap: false, forced: !waiters.isEmpty, generation: current)+ try await reconcile(bootstrap: false, forced: forced, recovering: requestedRecovery != nil, generation: current)try await consumeAvailable(generation: current)let result: ActivityEventDrainResult = if !isRunning || generation != current || Task.isCancelled {.cancelled} else if let latestUpdate {- if covered {- .completed(latestUpdate)- } else {- .partial(latestUpdate)- }+ .update(latestUpdate)} else {.sourceUnavailable}for waiter in waiters {- waiter.resume(returning: result)+ waiter.continuation.resume(returning: result)}} catch {for waiter in waiters {- waiter.resume(returning: .sourceUnavailable)+ waiter.continuation.resume(returning: .sourceUnavailable)}throw error}@@ -266,6 +310,7 @@ actor AppServerActivityReader {// 首批通知到达前确认采集租约, 避免连接和存储任务的启动顺序决定是否记账try acquireTokenUsageWriter(generation: current)isReconciliationComplete = false+ recoveryID = UUID()reducer.reconnect()reducer.setTokenUsageRecordingEnabled(isTokenUsageWriter && !isHistoryRecordingPaused)try checkGeneration(current)@@ -280,7 +325,7 @@ actor AppServerActivityReader {}session = connectionconnectedAt = Date()- _ = try await reconcile(bootstrap: true, forced: true, generation: current)+ try await reconcile(bootstrap: true, forced: true, generation: current)try checkGeneration(current)await publish(.bootstrapEnd)}@@ -319,7 +364,7 @@ actor AppServerActivityReader {let pending = drainWaitersdrainWaiters.removeAll()for waiter in pending {- waiter.resume(returning: result)+ waiter.continuation.resume(returning: result)}}@@ -328,6 +373,7 @@ actor AppServerActivityReader {session?.close()session = nilsubscribed.removeAll()+ ignoredThreads.removeAll()deferredNotifications.removeAll()pendingAccountChange = nilverifiedTurns.removeAll()@@ -335,14 +381,14 @@ actor AppServerActivityReader {turnRevisions.removeAll()cancelBackfill()invalidThreads.removeAll()- checkedThreads.removeAll()+ threadChecks.removeAll()await publish(.sourceUnavailable)}- private func reconcile(bootstrap: Bool, forced: Bool, generation current: Int) async throws -> Bool {+ private func reconcile(bootstrap: Bool, forced: Bool, recovering: Bool = false, generation current: Int) async throws {let budget = AppServerRequestBudget(deadline: Date().addingTimeInterval(reconciliationTimeout))- return try await AppServerRequestBudget.$current.withValue(budget) {- try await reconcileWithinBudget(bootstrap: bootstrap, forced: forced, generation: current)+ try await AppServerRequestBudget.$current.withValue(budget) {+ try await reconcileWithinBudget(bootstrap: bootstrap, forced: forced, recovering: recovering, generation: current)}}@@ -362,43 +408,52 @@ actor AppServerActivityReader {throw CodexStatusError.invalidServerResponse}- private func reconcileWithinBudget(bootstrap: Bool, forced: Bool, generation current: Int) async throws -> Bool {+ private func reconcileWithinBudget(bootstrap: Bool, forced: Bool, recovering: Bool, generation current: Int) async throws {let loaded = try await loadThreads(generation: current)+ ignoredThreads.formIntersection(loaded)let knownActive = Set(reducer.states.keys.filter {reducer.states[$0]?.terminal == nil && reducer.threads[$0.threadID]?.status?.type != .notLoaded}.map(\.threadID))- let now = Date()- let dependencies = Set(reducer.missingRootTurns(liveOnly: forced).keys)- .union(reducer.missingSubagentParents(liveOnly: forced)).union(backfillThreads)- let required = loaded.union(knownActive).union(reducer.missingRootTurns(liveOnly: true).keys)+ let now = reconciliationClock()+ let dependencies = Set(reducer.missingRootTurns(liveOnly: forced || recovering).keys)+ .union(reducer.missingSubagentParents(liveOnly: forced || recovering)).union(backfillThreads)+ // 历史关联保留补读资格, 只有实时依赖需要快速核对+ let liveDependencies = Set(reducer.missingRootTurns(liveOnly: true).keys).union(reducer.missingSubagentParents(liveOnly: true))- let candidates = loaded.union(knownActive).union(dependencies).filter { id in+ let required = loaded.union(knownActive).union(liveDependencies)+ let candidates = loaded.union(knownActive).union(dependencies).subtracting(ignoredThreads).filter { id inlet interval: TimeInterval = invalidThreads.contains(id) || knownActive.contains(id)- || dependencies.contains(id) || reducer.threads[id]?.status?.type == .active ? 5 : 60- return forced || now.timeIntervalSince(checkedThreads[id] ?? .distantPast) >= interval+ || liveDependencies.contains(id) || reducer.threads[id]?.status?.type == .active ? 5 : 60+ guard !forced, let check = threadChecks[id] else { return true }+ if let retryAfter = check.retryAfter {+ return now >= retryAfter+ }+ if recovering, !isThreadVerified(id) {+ return true+ }+ return now - check.checkedAt >= .seconds(interval)}.sorted {if required.contains($0) != required.contains($1) {return required.contains($0)}- return (checkedThreads[$0] ?? .distantPast, $0) < (checkedThreads[$1] ?? .distantPast, $1)+ if (threadChecks[$0] == nil) != (threadChecks[$1] == nil) {+ return threadChecks[$0] == nil+ }+ return (threadChecks[$0]?.checkedAt ?? now, $0) < (threadChecks[$1]?.checkedAt ?? now, $1)}let deadline = ContinuousClock.now.advanced(by: .seconds(1))- var covered = truefor id in candidates {try checkGeneration(current)- let verified = try await reconcileThread(id, loaded: loaded, bootstrap: bootstrap, forced: forced, generation: current)- if loaded.contains(id) || knownActive.contains(id) {- covered = covered && verified- }+ try await reconcileThread(id, loaded: loaded, bootstrap: bootstrap, forced: forced || (recovering && !isThreadVerified(id)), generation: current)// 日常核对分轮执行, 强制排空则等待本轮完整覆盖if !forced, ContinuousClock.now >= deadline {break}}- reducer.maintain(loadedThreads: loaded, now: Date())+ reducer.maintain(loadedThreads: loaded.subtracting(ignoredThreads), now: Date())subscribed.formIntersection(loaded)- let retained = loaded.union(knownActive).union(dependencies)- checkedThreads = checkedThreads.filter { retained.contains($0.key) }+ let retained = loaded.union(knownActive).union(dependencies).subtracting(ignoredThreads)+ threadChecks = threadChecks.filter { retained.contains($0.key) }revisions = revisions.filter { retained.contains($0.key) }verifiedTurns = verifiedTurns.filter { reducer.states[$0.key] != nil && retained.contains($0.key.threadID) }turnScans = turnScans.filter { retained.contains($0.key) }@@ -408,16 +463,22 @@ actor AppServerActivityReader {invalidThreads.formIntersection(retained)reconciledAt = Date()try checkGeneration(current)- isReconciliationComplete = covered && !reducer.states.values.contains {- $0.terminal == nil && ($0.rootThreadID == nil || $0.rootTurnID == nil)- }+ isReconciliationComplete = loaded.union(knownActive).subtracting(ignoredThreads).allSatisfy(isThreadVerified)+ && !reducer.states.values.contains {+ $0.terminal == nil && ($0.rootThreadID == nil || $0.rootTurnID == nil)+ }if !bootstrap {await publish(.lifecycleChanged)}- return isReconciliationComplete}- private func reconcileThread(_ id: String, loaded: Set<String>, bootstrap: Bool, forced: Bool, generation current: Int) async throws -> Bool {+ private func isThreadVerified(_ id: String) -> Bool {+ guard let check = threadChecks[id] else { return false }+ return check.verifiedRevision == revisions[id, default: 0] && check.recoveryID == recoveryID+ }++ private func reconcileThread(_ id: String, loaded: Set<String>, bootstrap: Bool, forced: Bool, generation current: Int) async throws {+ guard !ignoredThreads.contains(id) else { return }let checkpoint = ReadCheckpoint(threadRevision: revisions[id, default: 0], turns: turnRevisions)let active = Set(reducer.states.keys.filter { $0.threadID == id && reducer.states[$0]?.terminal == nil }.map(\.turnID))var remaining = active.union(reducer.missingRootTurns(liveOnly: forced)[id] ?? [])@@ -427,12 +488,19 @@ actor AppServerActivityReader {}defer { preparingThread = nil }var covered = false+ var failed = truedo {let read: ActivityThreadRead = try await request(ActivityRequests.thread(id), generation: current)var thread = read.thread+ if ignoreIfNeeded(thread) {+ return+ }if loaded.contains(id), newSubscription, thread.status?.type != .notLoaded {let joined: ActivityThreadResume = try await request(ActivityRequests.subscribe(id), generation: current)thread = joined.thread+ if ignoreIfNeeded(thread) {+ return+ }subscribed.insert(id)}if newSubscription {@@ -468,6 +536,7 @@ actor AppServerActivityReader {reducer.invalidateThread(id)}covered = unchanged && remaining.isDisjoint(with: active) && thread.status?.type != .notLoaded+ failed = thread.status?.type == .notLoaded || (result.exhausted && !remaining.isDisjoint(with: active))try await flushPending(generation: current)} catch CodexStatusError.invalidResponsePayload {consumeDeferred(for: id)@@ -483,8 +552,11 @@ actor AppServerActivityReader {consumeDeferred(for: id)throw error}- checkedThreads[id] = checkpoint.started- return covered+ try checkGeneration(current)+ let now = reconciliationClock()+ var check = threadChecks[id] ?? ThreadCheck(checkedAt: now)+ check.record(verifiedRevision: covered ? checkpoint.threadRevision : nil, failed: failed, recoveryID: recoveryID, now: now)+ threadChecks[id] = check}private func readRemainingTurns(@@ -732,10 +804,20 @@ actor AppServerActivityReader {notification = try JSONDecoder().decode(ActivityInput.self, from: data)} catch is DecodingError {guard let threadID = AppServerActivityProtocol.recoveryThreadID(from: data) else { throw CodexStatusError.invalidServerResponse }+ guard !ignoredThreads.contains(threadID) else { return }invalidateThread(threadID, method: method)return}let id = notification.params.threadId ?? notification.params.thread?.id+ if let thread = notification.params.thread, ignoreIfNeeded(thread) {+ return+ }+ if let id, ignoredThreads.contains(id) {+ return+ }+ if let id, preparingThread != id {+ expediteRetry(for: notification, threadID: id)+ }if let id, preparingThread == id || (reducer.threads[id] == nil && notification.params.thread == nil) {guard deferredNotifications.count < 4096 else { throw CodexStatusError.invalidServerResponse }deferredNotifications.append(notification)@@ -744,6 +826,33 @@ actor AppServerActivityReader {consume(notification)}+ private func expediteRetry(for notification: ActivityInput, threadID: String) {+ guard threadChecks[threadID]?.retryAfter != nil else { return }+ let hasActivity: Bool = switch notification.kind {+ case .threadDiscovered: notification.params.thread?.status?.type == .active+ case .threadStatusChanged: notification.params.status?.type == .active+ case .turnStarted, .turnFinished: notification.params.turn?.id.isEmpty == false+ case .itemStarted, .itemFinished, .usageUpdated, .replyProgress, .reasoningProgress, .reasoningSummaryProgress, .commandProgress:+ notification.params.turnId?.isEmpty == false+ default: false+ }+ guard hasActivity else { return }+ let now = reconciliationClock()+ // 有效活动可提前触发单线程探测, 重复通知不重置失败预算且重试至少间隔 5 秒+ threadChecks[threadID]?.expedite(at: now)+ if let retryAfter = threadChecks[threadID]?.retryAfter, retryAfter <= now {+ reconciledAt = .distantPast+ }+ }++ private func ignoreIfNeeded(_ thread: ActivityThread) -> Bool {+ guard let source = thread.threadSource, Self.ignoredThreadSources.contains(source) else { return ignoredThreads.contains(thread.id) }+ ignoredThreads.insert(thread.id)+ invalidThreads.remove(thread.id)+ deferredNotifications.removeAll { ($0.params.threadId ?? $0.params.thread?.id) == thread.id }+ return true+ }+private func consume(_ notification: ActivityInput) {stateChanged = truerecordStateChange(notification)@@ -758,6 +867,7 @@ actor AppServerActivityReader {private func recordStateChange(_ notification: ActivityInput) {guard let id = notification.params.threadId ?? notification.params.thread?.id else { return }+ let previousRevision = revisions[id, default: 0]switch notification.kind {case .threadDiscovered, .threadStatusChanged, .turnStarted, .turnFinished,.commandApprovalRequested, .fileApprovalRequested, .permissionsRequested, .inputRequested, .userInputRequested, .requestResolved:@@ -768,6 +878,9 @@ actor AppServerActivityReader {}default: break}+ if previousRevision != revisions[id, default: 0] {+ isReconciliationComplete = false+ }if notification.kind == .turnStarted, let turn = notification.params.turn, turn.startedAt.map({ $0 >= connectedAt }) ?? true {liveStartedTurns.insert(ActivityTurnReference(threadID: id, turnID: turn.id))}@@ -929,7 +1042,8 @@ actor AppServerActivityReader {transitions: transitions,terminalEvents: terminalEvents,backfilledTasks: backfilledTasks,- isComplete: isReconciliationComplete+ isComplete: isReconciliationComplete,+ recoveryID: recoveryID)latestUpdate = updateawait onBatch(update)@@ -969,6 +1083,7 @@ actor AppServerActivityReader {}private func invalidateThread(_ id: String, method: String) {+ isReconciliationComplete = falselet firstFailure = invalidThreads.insert(id).insertedverifiedTurns = verifiedTurns.filter { $0.key.threadID != id }turnScans[id] = nildiff --git a/CodexBar/Services/AppServer/AppServerConfig.swift b/CodexBar/Services/AppServer/AppServerConfig.swiftindex 9dc8ee0..1e269c0 100644--- a/CodexBar/Services/AppServer/AppServerConfig.swift+++ b/CodexBar/Services/AppServer/AppServerConfig.swift@@ -41,30 +41,4 @@ nonisolated enum AppServerTUINotifications: Decodable {}}-/// config/batchWrite 的单条编辑, 直接转成 app-server 期望的 JSON 对象-nonisolated struct ConfigBatchEdit: Sendable {- let keyPath: String- let mergeStrategy: String-- private let value: Bool-- init(- keyPath: String,- value: Bool,- mergeStrategy: String- ) {- self.keyPath = keyPath- self.value = value- self.mergeStrategy = mergeStrategy- }-- var appServerObject: [String: Any] {- [- "keyPath": keyPath,- "value": value,- "mergeStrategy": mergeStrategy- ]- }-}-nonisolated struct ConfigWriteResponse: Decodable {}diff --git a/CodexBar/Services/AppServer/AppServerRequests.swift b/CodexBar/Services/AppServer/AppServerRequests.swiftindex 987d069..44b670b 100644--- a/CodexBar/Services/AppServer/AppServerRequests.swift+++ b/CodexBar/Services/AppServer/AppServerRequests.swift@@ -29,8 +29,10 @@ nonisolated enum AccountRequests {}static func setTUINotifications(_ enabled: Bool) -> AppServerRequest<ConfigWriteResponse> {- let edit = ConfigBatchEdit(keyPath: "tui.notifications", value: enabled, mergeStrategy: "upsert")- return AppServerRequest(method: "config/batchWrite", params: ["edits": [edit.appServerObject], "reloadUserConfig": true])+ AppServerRequest(method: "config/batchWrite", params: [+ "edits": [["keyPath": "tui.notifications", "value": enabled, "mergeStrategy": "upsert"]],+ "reloadUserConfig": true+ ])}}diff --git a/CodexBar/Services/Codex/CodexPaths.swift b/CodexBar/Services/Codex/CodexPaths.swiftindex 37e2b68..3bb5790 100644--- a/CodexBar/Services/Codex/CodexPaths.swift+++ b/CodexBar/Services/Codex/CodexPaths.swift@@ -154,7 +154,7 @@ nonisolated enum CodexPaths {canonicalPath(lhs) == canonicalPath(rhs)}- /// "两个路径是否指向同一文件"的统一口径+ /// 归一化路径, 用于判断两个路径是否指向同一文件static func canonicalPath(_ path: String) -> String {URL(fileURLWithPath: path).resolvingSymlinksInPath()diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 5991df9..abafd4a 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -11,7 +11,7 @@ nonisolated enum CodexFetchOutcome {}/// 一次刷新里各步的结果分类, 只用于日志-/// 成功路径压进收尾那一条, 不为每步单独记一行+/// 成功时将各步结果合并为一条收尾日志nonisolated struct CodexFetchTrace {enum ConnectionMode: String {case reused@@ -51,7 +51,7 @@ private nonisolated struct CachedSupplementalRead<Value> {let value: Value?let step: CodexFetchTrace.StepResult- /// 只驱动 UI 的半透明展示; 新增 step 分支时要确认它算不算"给出的是旧数据"+ /// 仅控制 UI 的半透明展示, 新增 step 分支时需判断是否使用了缓存数据var isStale: Bool {step == .cached}@@ -389,7 +389,7 @@ actor CodexStatusService {// 新建连接已读过 account; 复用连接才刷新账户状态- // 失败定位随流程推进, 不靠事后从别的字段反推+ // 随流程更新当前步骤, 供失败日志定位trace.failureStage = .accountif refreshAccountInfo {let response = try readWithAuthRefresh {diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 5ce3f80..60586bc 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -276,7 +276,7 @@ final class CodexStatusViewModel: ObservableObject {}}- /// 成功路径把各步结果压进一条, 失败才带上定位到哪一步+ /// 成功时合并各步结果为一条日志, 失败时附上出错步骤private func logRefreshOutcome(trigger: LogTrigger,trace: CodexFetchTrace,diff --git a/CodexBar/Services/History/HistoryService.swift b/CodexBar/Services/History/HistoryService.swiftindex 9a67dcd..0c07848 100644--- a/CodexBar/Services/History/HistoryService.swift+++ b/CodexBar/Services/History/HistoryService.swift@@ -4,18 +4,17 @@ import osnonisolated struct HistoryMaintenanceCounts {var events = 0var written = 0- var skipped = 0var failed = 0var pruned = 0var dateRange = "-"- /// 这条之前连续空转了多少轮, 用来确认静默期是没事干而不是没跑+ /// 此前连续无变化的轮数, 用于确认日志静默期间维护仍在执行var idle = 0var dates: Int {- written + skipped + failed+ written + failed}- /// 这一轮有没有真的改变过状态+ /// 本轮是否改变了状态var hasWork: Bool {dates > 0 || pruned > 0}diff --git a/CodexBar/Services/History/HistoryViewModel.swift b/CodexBar/Services/History/HistoryViewModel.swiftindex fdbc2af..204ee36 100644--- a/CodexBar/Services/History/HistoryViewModel.swift+++ b/CodexBar/Services/History/HistoryViewModel.swift@@ -44,8 +44,8 @@ final class HistoryViewModel: ObservableObject {)}- /// 由 SyncScheduler 串行调度, 无需自行判断并发, 只执行一次明确的维护刷新- /// 返回这一轮的维护计数, 空转为 nil; 收尾日志由调用方按它决定记不记+ /// SyncScheduler 串行调度每次维护刷新, 此处无需检查并发+ /// 返回本轮维护计数, 无变化时返回 nil, 调用方据此决定是否记录收尾日志func refreshMaintenance(synchronize: Bool,trigger: LogTriggerdiff --git a/CodexBar/Services/History/TokenUsageHistoryStore.swift b/CodexBar/Services/History/TokenUsageHistoryStore.swiftindex 771da31..d51b0cc 100644--- a/CodexBar/Services/History/TokenUsageHistoryStore.swift+++ b/CodexBar/Services/History/TokenUsageHistoryStore.swift@@ -130,6 +130,7 @@ nonisolated struct TokenUsageRebuildResult {static let empty = Self()}+/// 调用方持有文件锁, 每次核对磁盘字节后复用解码结果, 不依赖 mtime 判断跨进程修改nonisolated struct TokenUsageFileCache<Value: Codable & Equatable> {let url: URLprivate var data: Data?@@ -139,7 +140,7 @@ nonisolated struct TokenUsageFileCache<Value: Codable & Equatable> {self.url = url}- mutating func load(validate: (Data) throws -> Void = { _ in }) throws -> Value? {+ mutating func load() throws -> Value? {guard FileManager.default.fileExists(atPath: url.path) else {data = nilvalue = nil@@ -149,7 +150,6 @@ nonisolated struct TokenUsageFileCache<Value: Codable & Equatable> {if current == data {return value}- try validate(current)let decoded = try JSONLines.decoder.decode(Value.self, from: current)data = currentvalue = decodeddiff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex d2c13a8..39564df 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -39,7 +39,7 @@ final class KeepAliveController: ObservableObject {/// 与注册类错误分开存储: refreshPowerHelperStatus 每次 App 激活都会跑, 不能抹掉操作结果@Published private var operationErrorMessage: String?- /// 注册不成功时操作类错误只是下游噪音, 优先展示注册问题+ /// 注册失败时优先展示注册错误, 操作错误可能由此引起var errorMessage: String? {(isEnabled ? powerHelperRegistrationErrorMessage : nil) ?? operationErrorMessage}@@ -84,8 +84,8 @@ final class KeepAliveController: ObservableObject {private let systemSleepService = SystemSleepService()private let powerSourceMonitor = PowerSourceMonitor()private let durationLimiter: KeepAliveDurationLimiter- /// 不加 @Published: 设置页在根上观察整个控制器, 任务每起停一次都会重算整页 body- /// 需要跟着它刷新的只有派生出去的 isLowBatteryBlocking 与 canShowOptions+ /// 设置页观察整个控制器, 加 @Published 会让每次任务起停都重算整页 body+ /// 只需发布派生状态 isLowBatteryBlocking 与 canShowOptions 的变化private var runningTaskIDs = Set<UUID>()/// 开着 keepsAwakeWhileWaiting 时, 等待任务也参与防睡眠判定private var waitingTaskIDs = Set<UUID>()@@ -108,16 +108,15 @@ final class KeepAliveController: ObservableObject {private var retryAttempt = 0private var powerHelperRegistrationTask: Task<Void, Never>?private let powerHelperPackageValidation = PowerHelperPackageValidation()- /// 只经由派生状态影响 UI, 自己不发信号+ /// 仅通过派生状态更新 UI, 此属性不发布变化private var isRefreshingPowerHelper = falseprivate var isAutoResetRequested = falseprivate let autoResetWakeScheduler = AutoResetWakeScheduler()/// 已排队但还没发出的低电量通知, 值是触及阈值时的电量- /// 恢复睡眠真的成功才发得出去: 恢复失败时机器仍不会睡, 那时说已恢复会把用户骗去合盖+ /// 仅在睡眠恢复成功后发送, 避免用户在机器仍不允许睡眠时误以为可以合盖private var pendingLowBatteryPercent: Int?- /// 本轮低电量已经通知过- /// 只看是否接电不足以收口: 适配器接触不良时供电状态会反复翻转, 每翻一次都会重发一条- /// 由电量回到解除门槛以上清除, 也就是电量真的回来了才算下一轮+ /// 本轮低电量是否已通知, 电量回到解除门槛以上才清除+ /// 按供电状态重置会在适配器接触不良时重复提醒private var hasNotifiedLowBattery = false/// 达到时长上限后等待睡眠恢复成功再发送, 恢复失败时保留给重试路径private var pendingKeepAliveLimit: MaximumDuration?@@ -141,7 +140,7 @@ final class KeepAliveController: ObservableObject {.flatMap(LowBatteryThreshold.init(rawValue:)) ?? .off// 默认关闭: 等待回应可能持续到用户返回, 避免无人值守时持续防睡眠keepsAwakeWhileWaiting = defaults.bool(forKey: Self.keepsAwakeWhileWaitingKey)- // 默认关闭: 它会让人离开后机器一直停在解锁状态, 这个取舍只能由用户自己做+ // 默认关闭, 保持屏幕常亮会让用户离开后机器仍处于解锁状态, 需由用户自行开启keepsDisplayAwake = defaults.bool(forKey: Self.keepsDisplayAwakeKey)activityMonitor.setProtectionEnabled(isEnabled)powerHelperPackageValidation.onValidated = { [weak self] in@@ -177,7 +176,7 @@ final class KeepAliveController: ObservableObject {durationLimiter.onStateChanged = { [weak self] trigger inself?.reconcileSleepState(trigger: trigger)}- // duration 与 hasReached 由计算属性转发, 变化要接力发出去才能刷新 UI+ // duration 与 hasReached 由计算属性转发, 需同时转发变化通知才能刷新 UIdurationLimiter.objectWillChange.sink { [weak self] inself?.objectWillChange.send()@@ -292,8 +291,8 @@ final class KeepAliveController: ObservableObject {publishNotificationDependencies()}- /// 只改"哪些任务算数", 不参与拦截判定- /// 所以它不进 sleepBlockReason: 关着它时等待中的任务报的仍然是 noTasks, 与没有任务同一回事+ /// 仅决定等待任务是否计入防睡眠, 不新增 sleepBlockReason+ /// 关闭时, 只有等待任务与没有任务均返回 noTasksfunc setKeepsAwakeWhileWaiting(_ enabled: Bool) {guard enabled != keepsAwakeWhileWaiting else {return@@ -306,7 +305,7 @@ final class KeepAliveController: ObservableObject {reconcileSleepState(trigger: .settings)}- /// 与防睡眠的实际效果绑在一起: 只在真的挡住睡眠时留住屏幕, 低电量或达到上限解除时一并放开+ /// 仅在防睡眠生效时保持屏幕常亮, 低电量或达到时限解除防睡眠时一并停止func setKeepsDisplayAwake(_ enabled: Bool) {guard enabled != keepsDisplayAwake else {return@@ -328,8 +327,7 @@ final class KeepAliveController: ObservableObject {)lowBatteryThreshold = thresholddefaults.set(threshold.rawValue, forKey: Self.lowBatteryThresholdKey)- // 换了阈值就是新的一轮: 旧阈值下打的锁存对新阈值不成立- // 留着它会让提高阈值后第一次真正触发的低电量不提醒+ // 更换阈值后重置去重状态, 避免旧记录阻止提高阈值后的首次低电量提醒clearPendingLowBatteryNotification()updateBatteryState()reconcileSleepState(trigger: .settings)@@ -358,7 +356,7 @@ final class KeepAliveController: ObservableObject {// 电池状态可能单独变化, 不能等到低电量阻断状态变化后才刷新派生值publishNotificationDependencies()- // 保护关掉了就没有可维持的状态, 这一条要排在读数判断之前+ // 保护关闭后立即清除状态, 不受电量读数是否有效影响guard let threshold = lowBatteryThreshold.percent else {assign(false, to: \.isLowBatteryActive)clearPendingLowBatteryNotification()@@ -470,7 +468,7 @@ final class KeepAliveController: ObservableObject {reconcileSleepState(trigger: .taskChanged)}- /// 还没真正挡住睡眠时只清零不起表, 等禁用成功后由 begin 补上+ /// 防睡眠未生效时只清零, 禁用睡眠成功后再由 begin 开始计时private func restartMaximumDurationPeriod() {guard isEnabled else {return@@ -600,10 +598,9 @@ final class KeepAliveController: ObservableObject {}}- /// @Published 在 willSet 无条件发信号, 不比较新旧值- /// refreshPowerHelperStatus 每次 App 激活跑, releaseSleepPrevention 每条活动快照都会经过- /// 同值赋值会让菜单面板和设置页反复空转, 所以反复求值路径上的写入都走这里- /// 用户动作与一次性的操作结果本来就不会重复, 直接赋值即可+ /// @Published 在 willSet 无条件发布变化, 同值赋值也会刷新菜单面板和设置页+ /// refreshPowerHelperStatus 每次 App 激活时执行, releaseSleepPrevention 每条活动快照都会调用+ /// 这些重复求值路径通过此方法跳过同值写入, 用户动作和一次性操作结果仍直接赋值private func assign<Value: Equatable>(_ value: Value,to keyPath: ReferenceWritableKeyPath<KeepAliveController, Value>@@ -635,7 +632,7 @@ final class KeepAliveController: ObservableObject {isPowerHelperStatusAvailable = truelet previousStatus = powerHelperStatusassign(PowerHelperStatus(status), to: \.powerHelperStatus)- // 每次 App 激活都会跑, 只记真正的迁移, 否则日志会被无变化的求值淹没+ // 每次 App 激活都会查询, 仅记录状态变化// 取局部量再插值: Logger 的插值是 autoclosure, 直接写属性会被要求显式 self, 与 --self remove 冲突let currentStatus = powerHelperStatusif currentStatus != previousStatus {@@ -646,7 +643,7 @@ final class KeepAliveController: ObservableObject {AppLog.keepAlive.notice("Power Helper 注册状态变化: \(details, privacy: .public)")}if powerHelperStatus == .enabled {- // 注册已正常, 只撤回注册类抱怨+ // 注册恢复正常后只清除注册错误// 操作类结果 (例如重试耗尽) 必须留到下一次操作有结论为止assign(nil, to: \.registrationErrorMessage)} else {@@ -670,7 +667,7 @@ final class KeepAliveController: ObservableObject {let wantsSleepDisabled = blockReason == nilupdatePendingKeepAliveLimitNotification(for: blockReason)publishDerivedState(blockReason: blockReason)- // 挂在这条所有输入都会经过的路上, 否则关掉防睡眠开关要等 XPC 回复绕回来才放开屏幕+ // 所有输入变化都经过此处, 关闭防睡眠后立即解除屏幕常亮, 无需等待 XPC 回复reconcileDisplayAwake()logSleepConditionsIfChanged(blockReason: blockReason, trigger: trigger)@@ -1190,7 +1187,7 @@ final class KeepAliveController: ObservableObject {connection?.interruptionHandler = nilconnection?.invalidate()completePendingRequest(success: false)- // 无连接时也会走到这里, 只记真的断掉了一条, 避免空转刷屏+ // 无连接时也可能调用, 仅在断开已有连接时记日志if connection != nil {let mayHaveLease = mayHavePowerHelperLease ? 1 : 0AppLog.keepAlive.notice("Power Helper XPC 已断开: mayHaveLease=\(mayHaveLease)")@@ -1374,7 +1371,7 @@ final class KeepAliveController: ObservableObject {}/// 按顺序返回第一个不满足的条件, 全部满足时为 nil- /// 判定与日志共用这一份顺序, 新增条件不会漏进日志+ /// 判定与日志共用此顺序, 新增条件也参与日志记录private var sleepBlockReason: SleepBlockReason? {if !isStarted {return .notStarteddiff --git a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swiftindex c98b247..46bae42 100644--- a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift@@ -18,11 +18,11 @@ final class KeepAliveDurationLimiter: ObservableObject {private let defaults: UserDefaultsprivate var task: Task<Void, Never>?- /// 已经收表的累计时长+ /// 已结束计时段的累计时长private var accumulated: TimeInterval = 0/// 当前这一段的起点, nil 表示没在累加private var runningSince: SuspendingClock.Instant?- /// 避免 stop 之后在途回调又把计时器支起来+ /// 防止在途回调在 stop 后重新启动计时器private var isRunning = falseinit(defaults: UserDefaults = .standard) {@@ -49,13 +49,12 @@ final class KeepAliveDurationLimiter: ObservableObject {self.duration = durationdefaults.set(duration.rawValue, forKey: Self.durationKey)- // 这一轮没累计过就没有可解除的状态, 条件没变也就不必让外面重新求值+ // 本轮未计时则没有可解除的上限状态, 无需触发外部重新求值guard hasAccumulated else {return}- // 走 fireReached 而不是直接 markReached: 这一轮可能已经达过上限- // 把上限调大但仍然不够时不该再记一条已达上限, 也不该重复通知外面+ // fireReached 会检查本轮是否已达上限, 避免调大后仍超限时重复记日志和通知外部if let limit = duration.timeInterval, elapsed >= limit {fireReached()return@@ -66,7 +65,7 @@ final class KeepAliveDurationLimiter: ObservableObject {onStateChanged?(.settings)}- /// 防睡眠真正生效后起表; 已经在走就保持这一段不变+ /// 防睡眠生效后开始计时, 已在计时则保留当前段func begin() {if runningSince == nil {runningSince = .now@@ -75,8 +74,8 @@ final class KeepAliveDurationLimiter: ObservableObject {schedule()}- /// 防睡眠解除时收表, 把这一段并进累计值- /// 收表之后的时间一律不算: 机器睡着, 低电量拦着, Power Helper 断开都不该占用户的上限+ /// 防睡眠解除时停止计时, 将当前段计入累计值+ /// 系统睡眠, 低电量阻断或 Power Helper 断开期间不累计时长func pause() {guard let runningSince else {return@@ -88,7 +87,7 @@ final class KeepAliveDurationLimiter: ObservableObject {}/// 有新任务或等待任务恢复运行时重新计时- /// isPreventingSleep 由调用方给出: 还没真正挡住睡眠时只清零, 等 begin 起表+ /// 调用方传入 isPreventingSleep, 尚未生效时只清零, 等 begin 开始计时func restart(isPreventingSleep: Bool) {cancelTask()accumulated = 0@@ -108,8 +107,8 @@ final class KeepAliveDurationLimiter: ObservableObject {clearReached()}- /// @Published 在 willSet 无条件发信号, 而这里的 objectWillChange 被转发进 KeepAliveController- /// 同值赋值会让整个高级设置页和活动卡片跟着空转, 所以 hasReached 的清零都走这里+ /// objectWillChange 会转发给 KeepAliveController, @Published 同值赋值也会刷新高级设置页和活动卡片+ /// 重置 hasReached 时跳过同值写入private func clearReached() {guard hasReached else {return@@ -118,7 +117,7 @@ final class KeepAliveDurationLimiter: ObservableObject {hasReached = false}- /// 这一轮已经挡住睡眠的总时长, 含当前还没收表的这一段+ /// 本轮防睡眠总时长, 包括当前计时段private var elapsed: TimeInterval {guard let runningSince else {return accumulated@@ -127,7 +126,7 @@ final class KeepAliveDurationLimiter: ObservableObject {return accumulated + TimeInterval(runningSince.duration(to: .now))}- /// 这一轮有没有真的累计过, 没累计过就没有可解除的上限状态+ /// 本轮是否累计过时长, 未累计则没有可解除的上限状态private var hasAccumulated: Bool {runningSince != nil || accumulated > 0}@@ -148,7 +147,7 @@ final class KeepAliveDurationLimiter: ObservableObject {return}- // 计时器同样走 SuspendingClock, 否则机器睡一夜醒来会当场判定到期+ // 计时器也使用 SuspendingClock, 避免将系统睡眠时间计入上限let deadline = SuspendingClock.Instant.now.advanced(by: .seconds(remaining))task = Task { @MainActor [weak self] intry? await Task.sleep(until: deadline, clock: SuspendingClock())diff --git a/CodexBar/Services/KeepAlive/KeepAliveModels.swift b/CodexBar/Services/KeepAlive/KeepAliveModels.swiftindex 6cace4b..397d69a 100644--- a/CodexBar/Services/KeepAlive/KeepAliveModels.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveModels.swift@@ -52,7 +52,7 @@ extension KeepAliveController {)}- /// 日志用的小时数, 与 LowBatteryThreshold 的百分比同一种可读形式, 无限制同样记 -1+ /// 日志以小时记录时限, 与 LowBatteryThreshold 一样用 -1 表示无限制或未启用/// rawValue 使用秒数, 日志转换为小时便于阅读var loggedHours: Int {self == .unlimited ? -1 : rawValue / 3600@@ -112,7 +112,7 @@ extension KeepAliveController {}}- /// 防睡眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值+ /// 防睡眠未生效的原因, 同时用作日志中的 reason= 取值enum SleepBlockReason: String {case notStartedcase userOff@@ -125,7 +125,7 @@ extension KeepAliveController {}/// shouldDisableSleep 的求值结果与它依赖的各项, 只用于变化检测与日志- /// blockReason 与 shouldDisableSleep 同源, 不会出现"字段都满足却报某项缺失"+ /// blockReason 与 shouldDisableSleep 共用判定规则, 保持结果与依赖状态一致/// battery 只保存布尔状态, 避免电量每次变化都触发日志struct SleepConditions: Equatable {let blockReason: SleepBlockReason?diff --git a/CodexBar/Services/KeepAlive/PowerHelperConfiguration.swift b/CodexBar/Services/KeepAlive/PowerHelperConfiguration.swiftindex 2a3a977..addbc83 100644--- a/CodexBar/Services/KeepAlive/PowerHelperConfiguration.swift+++ b/CodexBar/Services/KeepAlive/PowerHelperConfiguration.swift@@ -118,7 +118,7 @@ enum PowerHelperConfiguration {requiresSleepReset: Bool,fingerprint: String) -> String {- // 待完成重置是跨 Power Helper 版本的欠账, 后续更新只能转交给新指纹, 不能清除+ // 待完成重置必须跨 Power Helper 版本保留, 后续更新只能转交给新指纹let hasPendingSleepReset = defaults.string(forKey: pendingUpdateIdentifierKey) != nilif requiresSleepReset || hasPendingSleepReset {defaults.set(fingerprint, forKey: pendingUpdateIdentifierKey)diff --git a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swiftindex ac789c6..739c2ff 100644--- a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift+++ b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift@@ -4,7 +4,7 @@ import IOKit.psimport os/// 一次电源读取的结果-/// 三态而不是可选值: 把读取失败折叠进"没有电池"会让设置项凭空消失, 保护也静默失效+/// 区分读取成功, 失败和无电池, 避免读取失败时隐藏设置项并解除保护nonisolated enum BatteryReading: Equatable {/// 确认这台机器没有内置电池 (台式机)case unavailable@@ -24,7 +24,7 @@ nonisolated enum BatteryReading: Equatable {self != .unavailable}- /// 日志用的状态标识; 不带电量, 那个只在触及阈值那一条里记+ /// 日志使用的状态标识, 电量仅在触及阈值时记录var loggedState: String {switch self {case .unavailable: "unavailable"@@ -40,8 +40,8 @@ nonisolated struct BatteryStatus: Equatable {let isOnBattery: Bool}-/// 只读系统电源状态并在变化时通知外部, 不知道阈值也不知道防睡眠-/// IOKit 的 C 接口和内存管理约定全部收在这里, 不漏到调用方+/// 读取系统电源状态并在变化时通知调用方, 阈值和防睡眠由调用方处理+/// 封装 IOKit 的 C 接口及内存管理@MainActorfinal class PowerSourceMonitor {private(set) var reading = BatteryReading.unreadable@@ -50,7 +50,7 @@ final class PowerSourceMonitor {private var runLoopSource: CFRunLoopSource?private var wakeObserver: NSObjectProtocol?private var pollTask: Task<Void, Never>?- /// 重入守卫; 不能拿 runLoopSource 顶替: 注册失败时它是 nil, 而唤醒观察者已经装上了+ /// 独立记录启动状态, 注册失败时 runLoopSource 为 nil, 但唤醒观察者已安装private var isMonitoring = false/// 这台机器确认装着内置电池/// 硬件不会中途消失, 所以见过之后再读到空列表只能是枚举缺口, 不能当成台式机@@ -80,15 +80,15 @@ final class PowerSourceMonitor {}isMonitoring = trueself.onChange = onChange- // 不走 refresh: 它按变化过滤, 而初始值就是 unreadable, 首读失败会被静默吞掉- // 那之后低电量判定一直冻着, 却只在恢复时留下一条没有配对失败行的日志+ // refresh 会跳过与初始 unreadable 相同的结果, 因此首次读取单独处理+ // 首读失败也要记录, 才能与恢复日志配对, 确认低电量判定暂停的时段let initialReading = currentReading()if initialReading == .unreadable {AppLog.keepAlive.error("电源监听读取失败: stage=start")}reading = initialReading- // 装在 source 之前: 注册失败时它已经就位, 与那条路的轮询兜底叠着用+ // 先安装唤醒观察者, source 注册失败后仍可与轮询一起补读// 睡眠期间电量可能变化很大, 而系统不一定为此补发电源通知wakeObserver = NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification,@@ -112,7 +112,7 @@ final class PowerSourceMonitor {.refresh()}}, context)?.takeRetainedValue() else {- // action= 记的是降级后还剩什么, 否则只知道注册失败, 不知道保护是不是全没了+ // action= 记录注册失败后仍可用的监测方式let details = LogFields.joined("stage=createRunLoopSource","action=poll"@@ -132,7 +132,7 @@ final class PowerSourceMonitor {return}- // 降级与恢复成对记: 判定在整个 unreadable 窗口里被冻结, 只记进不记出就看不出冻了多久+ // 成对记录降级和恢复, 用于确认 unreadable 期间低电量判定暂停了多久if case .unreadable = newReading {AppLog.keepAlive.error("电源监听读取失败: stage=refresh")} else if case .unreadable = reading {@@ -144,7 +144,7 @@ final class PowerSourceMonitor {}/// 注册失败后的兜底轮询- /// 只靠唤醒补读不够: 防睡眠正在生效的机器按定义就不会睡, 那条通知永远不来+ /// 防睡眠生效期间没有唤醒通知, 需通过轮询继续读取电源状态private func startPolling() {pollTask?.cancel()pollTask = Task { @MainActor [weak self] in@@ -159,7 +159,7 @@ final class PowerSourceMonitor {}}- /// 电量取 Current/Max 的比例而不是直接用 Current+ /// 电量按 Current/Max 的比例计算/// 实测两者都是百分比 (Max=100), 但历史上某些路径下是 mAh, 按比例算两种情况都对private func currentReading() -> BatteryReading {guard let blob = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),@@ -184,8 +184,7 @@ final class PowerSourceMonitor {}let percent = Int((Double(current) / Double(maximum) * 100).rounded())- // 只有 Battery Power 才是真的在耗电池- // 不能用 Is Charging: 接电但停充时它也是 false, 而那时电量并没有在掉+ // Battery Power 表示电池供电, Is Charging 在接电但停充时也为 false, 不能用于判断供电方式let isOnBattery = description[kIOPSPowerSourceStateKey] as? String== kIOPSBatteryPowerValuereturn .present(@@ -197,7 +196,7 @@ final class PowerSourceMonitor {}// 走到这里既可能是台式机, 也可能是 IOKit 正在重新枚举而列表暂时为空- // 见过电池就只能算这一次读不到, 交给调用方维持上一次判定, 否则一次缺口会当场撤掉保护+ // 已确认有电池时按读取失败处理, 调用方保留上次判定, 避免枚举缺口解除保护return hasSeenBattery ? .unreadable : .unavailable}diff --git a/CodexBar/Services/KeepAlive/SystemSleepService.swift b/CodexBar/Services/KeepAlive/SystemSleepService.swiftindex 8772a9e..76d2a61 100644--- a/CodexBar/Services/KeepAlive/SystemSleepService.swift+++ b/CodexBar/Services/KeepAlive/SystemSleepService.swift@@ -60,7 +60,7 @@ final class SystemSleepService {/// 复用同一个 ID 重新触发, 每次传 null 会新建一条, pmset -g assertions 里会堆成一串同名断言private var userActivityAssertionID = IOPMAssertionID(kIOPMNullAssertionID)private var userActivityTask: Task<Void, Never>?- /// 上一拍声明成功没有, 用来只在成败翻转时记日志; 每轮起表时归位成"成功"+ /// 上次声明是否成功, 仅在结果变化时记日志, 每轮计时开始时重置为成功private var didDeclareUserActivity = truevar isPreventingDisplaySleep: Bool {@@ -101,7 +101,7 @@ final class SystemSleepService {sleepAssertion.end(release: releaseAssertion)}- /// 屏幕不睡与不进屏保是两件事, 后者要靠节拍声明用户活动, 所以两者收在同一对方法里+ /// 保持屏幕常亮还需要定期声明用户活动来阻止屏保, 两者在同一对方法中启停func beginPreventingDisplaySleep() -> IOReturn {displayReleaseRetryTask?.cancel()displayReleaseRetryTask = nil@@ -158,7 +158,7 @@ final class SystemSleepService {/// 屏保与闲置锁屏跟的是系统 idle 计时, 显示断言只保证屏幕不睡, 挡不住它们private func startUserActivityTicks() {- // 断言已在而节拍断了的那一轮会重新走到这里, 不先收掉旧的会留下一个空转的 Task+ // 断言仍有效但定时声明中断时也会重新调用, 先取消旧 Task 以免空转userActivityTask?.cancel()userActivityTask = Task { @MainActor [weak self] inwhile !Task.isCancelled {diff --git a/CodexBar/Services/Notifications/NotificationService.swift b/CodexBar/Services/Notifications/NotificationService.swiftindex cce3eae..5d207ee 100644--- a/CodexBar/Services/Notifications/NotificationService.swift+++ b/CodexBar/Services/Notifications/NotificationService.swift@@ -50,14 +50,13 @@ final class NotificationService: NSObject {private var lowQuotaObservations: [String: LowQuotaObservation] = [:]/// 低额度判定依据的两个设置项- /// 订阅回调跑在 @Published 的 willSet, 那时属性还是旧值, 只有回调参数是新的- /// 所以由调用方给出而不是在判定处回读 settings+ /// @Published 在 willSet 中回调, settings 属性尚未更新, 需使用调用方传入的回调参数private struct LowQuotaConditions {let isEnabled: Boollet thresholdPercent: Int}- /// 额度刷新那条路径上设置没有在变, 现场取值就是最新的+ /// 额度刷新期间设置不变, 可以直接读取当前值private var currentLowQuotaConditions: LowQuotaConditions {LowQuotaConditions(isEnabled: settings.isLowQuotaEnabled,@@ -313,7 +312,7 @@ final class NotificationService: NSObject {}/// 设置刚变就按新值重判一次, 不必等下一个刷新周期- /// 清掉上一帧观察是为了让新阈值能立刻穿越, 所以这里必须用新值判断, 否则清了也白清+ /// 清除上次观察后使用新阈值判定, 使当前额度达到新阈值时立即触发提醒private func reevaluateLowQuota(_ conditions: LowQuotaConditions) {guard settings.canDeliver,conditions.isEnabled,@@ -365,7 +364,7 @@ final class NotificationService: NSObject {return}- // 阈值是用户设置值不是用量数据, 记它才能解释这条通知为什么会发出来+ // 记录用户设置的阈值以说明通知原因, 不记录用量数据let threshold = lowQuota.thresholdPercentlet details = LogFields.joined("kind=lowQuota",@@ -468,9 +467,9 @@ final class NotificationService: NSObject {// MARK: - 低电量保护/// 由 KeepAliveController 在低电量导致睡眠恢复成功之后调用, 恢复失败不会走到这里- /// 不做去重: 调用方自己保证同一轮低电量只发一次, 电量回到解除门槛以上才算下一轮+ /// 调用方保证同一轮低电量只发一次, 电量回到解除门槛以上才开始下一轮, 此处无需再次去重/// 调用方在提交完成前保留空闲断言, 避免系统先进入空闲睡眠- /// 返回是否真的发出去了: 调用方据此决定这一轮算不算已通知, 提交失败就不该占掉这一轮+ /// 返回提交结果, 调用方仅在成功时标记本轮已通知func notifyLowBatteryProtection(percent: Int) async -> Bool {guard settings.canDeliver, settings.isLowBatteryEnabled else {return false@@ -638,7 +637,7 @@ final class NotificationService: NSObject {}}- /// 返回值是"这条通知真的提交出去了", 调用方据此决定要不要记下已通知+ /// 返回通知是否提交成功, 调用方据此标记已通知private func deliver(_ request: UNNotificationRequest,kind: String,diff --git a/CodexBar/Services/Notifications/NotificationSoundOption.swift b/CodexBar/Services/Notifications/NotificationSoundOption.swiftindex 262dcd9..a7f30ad 100644--- a/CodexBar/Services/Notifications/NotificationSoundOption.swift+++ b/CodexBar/Services/Notifications/NotificationSoundOption.swift@@ -167,8 +167,8 @@ struct NotificationSoundOption: Identifiable, Hashable {/// 系统声音列表只在首次访问时加载并缓存private static let systemSounds: [NotificationSoundOption] = loadSystemSounds()- /// 打包声音的 id 先占位, 系统同名文件不再生成第二个同 id 的选项- /// 否则用户在 System 组里选中的声音, 下次读取会被解析成打包组里那个同名资源+ /// 打包声音优先占用 id, 跳过同 id 的系统声音+ /// 避免 System 组选项在下次读取时被解析为同名打包资源private static let reservedIDs: Set<String> = Set((modernSounds + materialSounds).map(\.id))private static func bundled(diff --git a/CodexBar/Services/Settings/SyncSettings.swift b/CodexBar/Services/Settings/SyncSettings.swiftindex 9d3bdc6..5001f24 100644--- a/CodexBar/Services/Settings/SyncSettings.swift+++ b/CodexBar/Services/Settings/SyncSettings.swift@@ -218,7 +218,7 @@ final class SyncSettings: ObservableObject {private nonisolated static let enabledKey = "Sync.isEnabled"}-/// 同步没生效时缺的是哪一项, 同时充当日志里的 reason= 取值+/// 同步未生效的原因, 同时用作日志中的 reason= 取值nonisolated enum SyncActivation: String {case activecase syncOffdiff --git a/CodexBar/Services/Settings/TUINotificationSettings.swift b/CodexBar/Services/Settings/TUINotificationSettings.swiftindex 860f0f3..5e5cbc4 100644--- a/CodexBar/Services/Settings/TUINotificationSettings.swift+++ b/CodexBar/Services/Settings/TUINotificationSettings.swift@@ -47,8 +47,7 @@ final class TUINotificationSettings: ObservableObject {}}- /// 一次操作的用户文案与日志标题由它一处派生, 不在调用点各写一份- /// 两者都是固定字面量, 日志标题仍然能直接 grep+ /// 集中定义操作文案与日志标题, 两者使用固定字面量, 便于直接 grep 日志标题private enum ConfigOperation {case readcase writediff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swiftindex 0a3a72c..09ce8a4 100644--- a/CodexBar/Services/Support/AppLog.swift+++ b/CodexBar/Services/Support/AppLog.swift@@ -1,9 +1,9 @@import Foundationimport os-/// App 侧统一的系统日志出口, 与 app-server 链路的日志窗口分工明确+/// 记录 App 系统日志, app-server 交互详情由日志窗口处理/// 用户可见的错误文案只留步骤名, 定位问题需要的细节写到这里-/// subsystem 取 bundle identifier, Debug 与 Release 两套装置的日志因此天然分开+/// subsystem 使用 bundle identifier 区分 Debug 与 Release 日志nonisolated enum AppLog {/// App 生命周期, Sparkle 更新, 额度刷新结果与重置次数查询static let app = Logger(subsystem: subsystem, category: "app")diff --git a/CodexBar/Services/Support/AppProcessDiagnostics.swift b/CodexBar/Services/Support/AppProcessDiagnostics.swiftindex d1cb1f8..cb5ea4c 100644--- a/CodexBar/Services/Support/AppProcessDiagnostics.swift+++ b/CodexBar/Services/Support/AppProcessDiagnostics.swift@@ -1,21 +1,20 @@import Foundationimport os-/// 崩溃时进程直接消失, 日志会停在最后一条正常记录上, 事后分不清是崩了还是被退出-/// 这里补两条线索: ObjC 异常当场留痕, 其余终止方式 (Swift trap, kill, 断电) 靠下次启动补记-/// 干净退出标志由 install 与 recordCleanExit 成对维护, 两侧都在这里, 不散到调用方+/// 正常日志无法区分崩溃与退出, ObjC 异常发生时立即记录, Swift trap, kill 或断电在下次启动时补记+/// install 与 recordCleanExit 成对维护正常退出标志nonisolated enum AppProcessDiagnostics {static func install(defaults: UserDefaults = .standard) {// 首次运行没有这个键, 不能当成崩溃过// kill, 活动监视器强制退出和 Xcode 停止按钮都到不了 recordCleanExit, 与崩溃无法区分- // 因此只记 notice: 这条是线索不是结论, 用 error 会让按级别筛的排查开局就追一个不存在的故障+ // 无法确认是故障, 使用 notice 级别记录if let didExitCleanly = defaults.object(forKey: didExitCleanlyKey) as? Bool,!didExitCleanly {AppLog.app.notice("App 上次非正常退出: reason=unknown")}defaults.set(false, forKey: didExitCleanlyKey)- // 只兜得住 ObjC 异常; Swift 的 fatalError 与越界是 trap, 到不了这里, 由上面那条补记+ // 此处理器仅接收 ObjC 异常, Swift 的 fatalError 和越界触发 trap, 在下次启动时补记NSSetUncaughtExceptionHandler { exception inlet name = exception.name.rawValuelet reason = exception.reason ?? "-"diff --git a/CodexBar/Services/Support/JSONFileStorage.swift b/CodexBar/Services/Support/JSONFileStorage.swiftindex 6356813..8a368c3 100644--- a/CodexBar/Services/Support/JSONFileStorage.swift+++ b/CodexBar/Services/Support/JSONFileStorage.swift@@ -29,11 +29,6 @@ nonisolated enum JSONFileStorage {close(descriptor)}- static func load<T: Decodable>(_: T.Type, from url: URL) throws -> T? {- guard FileManager.default.fileExists(atPath: url.path) else { return nil }- return try JSONLines.decoder.decode(T.self, from: Data(contentsOf: url))- }-static func save(_ value: some Encodable, to url: URL) throws {let data = try JSONLines.stableEncoder.encode(value)guard (try? Data(contentsOf: url)) != data else { return }@@ -41,5 +36,3 @@ nonisolated enum JSONFileStorage {try data.write(to: url, options: .atomic)}}--// 调用方持有文件锁, 每次核对磁盘字节后复用解码结果, 不依赖 mtime 判断跨进程修改diff --git a/CodexBar/Services/Support/RefreshTaskCoordinator.swift b/CodexBar/Services/Support/RefreshTaskCoordinator.swiftindex bb163ac..4189fa3 100644--- a/CodexBar/Services/Support/RefreshTaskCoordinator.swift+++ b/CodexBar/Services/Support/RefreshTaskCoordinator.swift@@ -23,7 +23,7 @@ final nonisolated class RefreshTaskCoordinator: Sendable {return generation}- /// ViewModel 共用的刷新样板: 置位刷新标记 → 取数 → 仅当代际未过期时提交+ /// ViewModel 共用的刷新流程: 设置刷新标记后取数, 仅在代际未过期时提交/// 过期刷新结果直接丢弃, 避免慢请求覆盖后启动的新状态@MainActorfunc run<Value>(diff --git a/CodexBar/Services/Sync/SyncScheduler.swift b/CodexBar/Services/Sync/SyncScheduler.swiftindex 6aec422..cf51367 100644--- a/CodexBar/Services/Sync/SyncScheduler.swift+++ b/CodexBar/Services/Sync/SyncScheduler.swift@@ -17,8 +17,8 @@ final class SyncScheduler {private var pendingRebuild: RebuildRequest?private var cooldownTask: Task<Void, Never>?private var lastSyncFinishedAt: Date?- /// 请求会被合并成一次执行, 触发来源跟着一起排队, 非 nil 即代表有一个请求在等- /// 合并时保留先到的那个, 它才是这一轮真正的起因+ /// 待执行请求的触发来源, 非 nil 表示已有请求排队+ /// 多个请求合并执行时保留最早的触发来源private var pendingSyncTrigger: LogTrigger?private var pendingMaintenanceTrigger: LogTrigger?@@ -226,7 +226,7 @@ final class SyncScheduler {}/// 空转轮次不记录日志, 避免周期刷新产生重复信息- /// 同步自身的起止由 SyncService 记, 这里只承载维护结果, 不给 sync 开后门+ /// 此处只记录维护结果, 同步起止由 SyncService 记录private func logMaintenanceOutcome(synchronize: Bool,trigger: LogTrigger,@@ -249,7 +249,6 @@ final class SyncScheduler {"range=\(range)","events=\(counts.events)","written=\(counts.written)",- "skipped=\(counts.skipped)","failed=\(counts.failed)","pruned=\(counts.pruned)","elapsed=\(elapsed)"@@ -266,9 +265,8 @@ final class SyncScheduler {return max(0, Self.syncCooldown - elapsed)}- /// 冷却延后只在真的排上队时记一条- /// drain 一轮会被多个入口调用, 无条件记会把一次延后刷成好几条- /// 标题与 requestSync 的 已跳过 分开: 这里的请求冷却结束后照常执行, 不是被丢弃+ /// 冷却延后仅在入队时记录, 避免多个入口调用 drain 产生重复日志+ /// 请求会在冷却结束后执行, 日志标题需与 requestSync 的 已跳过 区分private func scheduleCooldownDrain(after delay: TimeInterval) {guard cooldownTask == nil else {returndiff --git a/CodexBar/Services/Updates/AppUpdater.swift b/CodexBar/Services/Updates/AppUpdater.swiftindex 456a8e5..2cc30bb 100644--- a/CodexBar/Services/Updates/AppUpdater.swift+++ b/CodexBar/Services/Updates/AppUpdater.swift@@ -127,7 +127,7 @@ final class AppUpdater: NSObject, ObservableObject {}}- /// 手动与自动检查共用 Sparkle 的几个回调, 触发来源只能从当前是不是手动态推出来+ /// 手动与自动检查共用 Sparkle 回调, 触发来源由当前手动检查状态判断private var checkTrigger: LogTrigger {isManualCheckInProgress ? .manual : .auto}diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex eef2394..0197ef5 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -666,14 +666,12 @@ private extension AppSettingsView {}}- /// 判定收在 KeepAliveController 里由 sleepBlockReason 派生, 这里只读结论- /// 在 View 里手抄那几个条件会漏掉后来新增的阻断项, 入口会亮着但点开不生效+ /// 使用 KeepAliveController 从 sleepBlockReason 派生的结果, 避免视图重复判定时漏掉新增阻断条件var canShowKeepAliveOptions: Bool {keepAliveController.canShowOptions}- /// 返回 nil 表示这一行整个收起- /// 正常运行时不必占一行说"一切正常", 是否正在防睡眠由主面板的太阳标记呈现+ /// 返回 nil 时隐藏此行, 正常防睡眠状态由主面板的太阳标记显示var keepAliveCaption: SettingsStatusCaption? {guard keepAliveController.isEnabled else {return nil@@ -692,15 +690,15 @@ private extension AppSettingsView {)}- // 低电量拦下时开关开着却不防睡眠, 不留一句无从解释- // 判定用 isLowBatteryBlocking 而不是 isLowBatteryActive: 后者在没有任务时也成立, 那时无话可说- // 它成立即意味着 Power Helper 已就绪, 所以排在下面那个 switch 之前不影响 Power Helper 类问题的呈现+ // 低电量阻断时说明开关已开启但防睡眠未生效的原因+ // 使用 isLowBatteryBlocking, 避免 isLowBatteryActive 在无任务时也显示阻断提示+ // 此状态要求 Power Helper 已就绪, 不会遮住后续 switch 中的 Power Helper 错误// 提示不写具体电量, 因为滞回会让保护持续到电量超过恢复阈值if keepAliveController.isLowBatteryBlocking {return SettingsStatusCaption(message: String(localized: "keep-alive.status.low-battery"))}- // 上限之外的运行态都收起; 达到上限要留一句, 否则开关开着却没生效无从解释+ // 仅在达到时限时解释防睡眠未生效的原因, 其他运行状态隐藏此行guard keepAliveController.hasReachedMaximumDuration else {return nil}@@ -836,8 +834,8 @@ private extension AppSettingsView {}}- /// 防睡眠不在这里刷: 控制器自己订阅了 didBecomeActive, 窗口打开也走 refreshSettingsState- /// 再调一次会让每次激活都多跑一遍电源读取 Power Helper 状态查询和 Power Helper 二进制哈希+ /// 防睡眠控制器通过 didBecomeActive 和窗口打开时的 refreshSettingsState 刷新+ /// 此处再次调用会重复读取电源, 查询 Power Helper 状态并计算其二进制哈希func refreshStatusRows() {refreshCodexVersionSection()refreshRebuildableDates()@@ -941,7 +939,7 @@ private extension AppSettingsView {.background {ScreenFrameReader(provider: notificationAnchorProvider)}- // 关掉总开关或被系统拒绝授权都会让 canShowOptions 转假, 收面板只需要认这一个信号+ // canShowOptions 已包含总开关和系统授权状态, 变为 false 时收起面板.onChange(of: notificationSettings.canShowOptions) { _, canShowOptions inguard !canShowOptions else {return@@ -1128,7 +1126,7 @@ private struct SettingsPageHeightPreferenceKey: PreferenceKey {}private struct SyncRowState {- /// 由 SyncSettings.isEffectivelyActive 统一判定, 视图层不再拼接业务谓词+ /// 同步可用性由 SyncSettings.isEffectivelyActive 判定let isActive: Boollet isSyncAvailable: Boollet isSyncing: Booldiff --git a/CodexBar/Views/Settings/HotKeyRecorderRow.swift b/CodexBar/Views/Settings/HotKeyRecorderRow.swiftindex a41e00d..577e5af 100644--- a/CodexBar/Views/Settings/HotKeyRecorderRow.swift+++ b/CodexBar/Views/Settings/HotKeyRecorderRow.swift@@ -2,7 +2,7 @@ import AppKitimport Carbon.HIToolboximport SwiftUI-/// 快捷键录制行, 隐藏 NSView 负责真正捕获 keyDown+/// 快捷键录制行, 由隐藏的 NSView 捕获 keyDownstruct HotKeyRecorderRow: View {@ObservedObject var settings: GlobalHotKeySettings@State private var isRecording = falsediff --git a/CodexBar/Views/Settings/KeepAliveOptionsView.swift b/CodexBar/Views/Settings/KeepAliveOptionsView.swiftindex d2ecfff..feaded4 100644--- a/CodexBar/Views/Settings/KeepAliveOptionsView.swift+++ b/CodexBar/Views/Settings/KeepAliveOptionsView.swift@@ -13,7 +13,7 @@ struct KeepAliveOptionsView: View {maximumDurationRowprotectionRow- // 台式机读不到电池, 这一行整个收起而不是置灰+ // 无内置电池时隐藏低电量保护行if keepAliveController.hasBattery {lowBatteryRow}@@ -60,7 +60,7 @@ struct KeepAliveOptionsView: View {)}- /// 只改"哪些任务算数", 没有额外依赖, 所以不置灰也不隐藏+ /// 仅决定等待任务是否计入防睡眠, 无额外依赖, 始终可用private var waitingApprovalRow: some View {toggleRow(title: "keep-alive.waiting.title",@@ -72,7 +72,7 @@ struct KeepAliveOptionsView: View {)}- /// 只在防睡眠真的生效时留住屏幕, 所以和上面那一行一样没有额外依赖+ /// 屏幕常亮随防睡眠生效, 此选项无额外依赖, 始终可用private var displayAwakeRow: some View {toggleRow(title: "keep-alive.display.title",@@ -116,7 +116,7 @@ struct KeepAliveOptionsView: View {}}- /// 开关的修饰链与通知子面板的 optionRow 保持一致, 两个面板才是同一套控件+ /// 开关沿用通知子面板 optionRow 的修饰链, 保持样式一致private func toggleRow(title: LocalizedStringResource,help: LocalizedStringResource,diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swiftindex c68729a..aa19290 100644--- a/CodexBar/Views/Settings/NotificationOptionsView.swift+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift@@ -175,9 +175,9 @@ struct NotificationOptionsView: View {}/// 防睡眠关着或低电量保护关着时显示为关闭并置灰, 不修改持久化的 isLowBatteryEnabled- /// 保护默认就是关的, 不置灰会让这一行在任何默认安装上都亮着, 而对应通知永远发不出来- /// "保护是不是真的在起作用"由 KeepAliveController 判定, 这里只读结论- /// 它同时覆盖了台式机: 那时防睡眠面板整行隐藏低电量保护, 而阈值可能是从笔记本迁移过来的非 off 值+ /// 保护默认关闭, 此时通知无法触发, 选项也应置灰+ /// 可用性由 KeepAliveController 判定, 包括台式机从笔记本迁入非 off 阈值的情况+ /// 台式机的防睡眠面板隐藏低电量保护行private var lowBatteryRow: some View {let isProtectionOn = keepAliveController.isLowBatteryProtectionEnabledlet isDisplayedOn = isProtectionOn && notificationSettings.isLowBatteryEnabled@@ -198,7 +198,7 @@ struct NotificationOptionsView: View {}/// 防睡眠关着或选了无限制时显示为关闭并置灰, 不修改持久化的 isKeepAliveLimitEnabled- /// 与低电量那一行同一个做法, "上限会不会到点"由 KeepAliveController 判定, 这里只读结论+ /// 与低电量通知一样, 可用性由 KeepAliveController 判定private var keepAliveLimitRow: some View {let hasLimit = keepAliveController.isMaximumDurationEnabledlet isDisplayedOn = hasLimit && notificationSettings.isKeepAliveLimitEnableddiff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swiftindex 7f546f9..9400c7d 100644--- a/CodexBar/Views/Settings/SettingsToggleRow.swift+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift@@ -42,8 +42,7 @@ struct SettingsOptionsButton: View {}}-/// 设置窗口右侧子选项面板共用的度量-/// 各面板要看起来是同一套控件, 所以除了面板宽度和 picker 宽度以外都从这里取+/// 设置子选项面板共用的尺寸, 仅面板和 picker 的宽度由各面板定义enum SettingsOptionsPanelMetrics {static let horizontalPadding: CGFloat = 12static let verticalPadding: CGFloat = 10@@ -56,7 +55,7 @@ enum SettingsOptionsPanelMetrics {}/// 子选项面板共用的下拉选择器-/// 只有宽度和对齐各自定义, 其余样式必须同源, 否则各面板看起来就不是同一套控件+/// 各面板仅定义宽度和对齐方式, 其余样式共用struct SettingsOptionsPicker<Option: Hashable>: View {let title: LocalizedStringResource@Binding var selection: Optiondiff --git a/CodexBar/Views/Shared/PasteboardWriter.swift b/CodexBar/Views/Shared/PasteboardWriter.swiftindex c2693a1..000d474 100644--- a/CodexBar/Views/Shared/PasteboardWriter.swift+++ b/CodexBar/Views/Shared/PasteboardWriter.swift@@ -1,6 +1,6 @@import AppKit-/// 统一收口剪贴板写入+/// 共用的剪贴板写入方法enum PasteboardWriter {static func copy(_ text: String) {NSPasteboard.general.clearContents()diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex affd830..cb75d7f 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 5.1.0-CURRENT_PROJECT_VERSION = 209+MARKETING_VERSION = 5.1.1+CURRENT_PROJECT_VERSION = 210diff --git a/Protocol.en.md b/Protocol.en.mdindex fa01545..cec7cbe 100644--- a/Protocol.en.md+++ b/Protocol.en.md@@ -1,8 +1,8 @@-# app-server API Inventory+# app-server API inventoryCodex version: `0.162.0`-## Outgoing Requests+## Outgoing requests| API | Purpose || --- | --- |@@ -19,22 +19,22 @@ Codex version: `0.162.0`| `thread/turns/list` | Read paginated turn information for a thread; `threadId` identifies the thread, and `itemsView: "notLoaded"` omits item content || `thread/items/list` | Read paginated items for a turn; `threadId` and `turnId` identify the target turn |-## Outgoing Notifications+## Outgoing notifications| API | Purpose || --- | --- || `initialized` | Notify the server that initialization is complete |-## Incoming Notifications+## Incoming notifications-### Account Notifications+### Account notifications| API | Purpose || --- | --- || `account/updated` | Receive account change notifications || `account/rateLimits/updated` | Receive rate limit change notifications |-### Threads, Turns, and Items+### Threads, turns, and items| API | Purpose || --- | --- |@@ -46,7 +46,7 @@ Codex version: `0.162.0`| `item/started` | Receive item start notifications, including asynchronous questions and user responses || `item/completed` | Receive item end notifications, including asynchronous questions and user responses |-### Progress Notifications+### Progress notifications| API | Purpose || --- | --- |@@ -55,7 +55,7 @@ Codex version: `0.162.0`| `item/reasoning/summaryTextDelta` | Track reasoning summary output progress || `item/commandExecution/outputDelta` | Track command output progress |-### Status and Presentation Notifications+### Status and presentation notifications| API | Purpose || --- | --- |@@ -72,7 +72,7 @@ Codex version: `0.162.0`| `error` | Receive error notifications || `warning` | Log server warnings |-## Server Requests+## Server requests| API | Purpose || --- | --- |diff --git a/README.en.md b/README.en.mdindex db85c2a..e90396a 100644--- a/README.en.md+++ b/README.en.md@@ -4,7 +4,7 @@# CodexBar-**Codex at a glance, right from your macOS menu bar**+View Codex status in your macOS menu bar[简体中文](README.md) | English@@ -15,49 +15,46 @@[](https://github.com/bob-zebedy/CodexBar/releases)[](LICENSE)-[Features](#features) | [Installation](#installation) | [Privacy](#privacy) | [Runtime Architecture](https://codexbar.zabrian.app/architecture) | [Performance Report](https://codexbar.zabrian.app/performance) | [Protocol](Protocol.en.md)+[Features](#features) | [Installation](#installation) | [Privacy](#privacy) | [Runtime architecture](https://codexbar.zabrian.app/architecture) | [Performance report](https://codexbar.zabrian.app/performance) | [Protocol](Protocol.en.md)<img src="Images/preview.gif" width="640" alt="CodexBar preview"></div>------CodexBar is a menu bar app for macOS that displays your Codex account information, usage limits, token usage, and real-time task status in one place.+CodexBar is a macOS menu bar app for viewing your Codex account, rate limits, token usage, and live task status.## Features-### Account and rate limits at a glance+### Account and rate limits- View your account, plan, credits, and the remaining percentage and reset time for each rate-limit window- Show your preferred allowance directly in the menu bar- Track banked resets and their expiry dates, with automatic use before they expire-### Follow your tasks in real time+### Task progress- See each task's project, model, reasoning effort, duration, and token usage- Track execution states, tasks awaiting a response, task progress, and recent events- Review concurrent tasks and recent completions, failures, and interruptions in Task Center-### Review your usage+### Usage statistics- Track total usage, daily peaks, usage streaks, and your longest task duration-- Explore daily token usage and activity statistics in a heatmap+- View daily token usage and activity statistics in a heatmap- Combine usage records across Macs through iCloud-### Get timely alerts+### Notifications and task glow- Receive alerts for task completions, tasks awaiting a response, allowance changes, and protection events- Choose notification types, sounds, and task haptic feedback- Follow status changes through customizable task glow at the top of your displays-### Keep long tasks running+### Keep awake- Keep your Mac awake while tasks run, then allow normal sleep when they finish- Optionally stay awake while awaiting a response or keep the display on as well- Set a keep-awake time limit, low-battery protection, and stalled task protection-## Installation### Homebrew@@ -79,7 +76,7 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy## Privacy-Raw activity events and live tasks are processed locally. Enabling cross-device sync uploads daily activity aggregates and token usage records to your private iCloud database.+CodexBar processes raw activity events and live tasks on your Mac. When you enable cross-device sync, it uploads daily activity aggregates and token usage records to your private iCloud database.## Feedbackdiff --git a/README.md b/README.mdindex 08c9f6e..b1c435d 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@# CodexBar-**在 macOS 菜单栏看清 Codex**+在 macOS 菜单栏查看 Codex 状态简体中文 | [English](README.en.md)@@ -21,43 +21,40 @@</div>------CodexBar 是 macOS 的菜单栏 App,用于集中展示 Codex 账户、额度、Token 用量和实时任务状态。+CodexBar 是 macOS 菜单栏 App,可查看 Codex 账户、额度、Token 用量和实时任务状态。## 功能-### 账户与额度一目了然+### 账户与额度- 查看账户、套餐、积分,以及各额度窗口的剩余比例和重置时间- 在菜单栏直接显示关注的额度- 查看留存重置及到期时间,支持到期前自动使用-### 随时掌握任务进展+### 任务进展- 查看项目、模型、推理强度、任务耗时和 Token 用量- 实时显示执行状态、等待回应、任务进度和最近事件- 在任务中心集中查看并发任务及最近完成、失败和中断的记录-### 回顾使用情况+### 使用统计- 查看累计用量、单日峰值、连续使用天数和最长任务时长- 通过热力图查看每日 Token 用量和活动统计- 通过 iCloud 汇总多台 Mac 的使用记录-### 及时收到提醒+### 通知与任务流光- 接收任务完成、等待回应、额度变化和保护提醒- 按需选择通知类型、音效和任务触觉反馈-- 通过屏幕顶部的任务流光感知状态变化,支持自定义外观+- 用屏幕顶部的任务流光显示状态变化,支持自定义外观-### 让长任务安心运行+### 防睡眠- 任务运行时自动防止 Mac 睡眠,结束后恢复正常睡眠- 可在等待回应时继续保持唤醒,或同时保持屏幕常亮- 支持防睡眠时限、低电量保护和异常任务保护-## 安装### Homebrew@@ -83,7 +80,7 @@ brew install --cask bob-zebedy/tap/codexbar@5## 反馈-Bug、功能建议或使用问题欢迎通过 [GitHub Issues](https://github.com/bob-zebedy/CodexBar/issues) 反馈。+通过 [GitHub Issues](https://github.com/bob-zebedy/CodexBar/issues) 报告 Bug、提出功能建议或询问使用问题。## 许可证diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swiftindex 67ad278..e93cdbf 100755--- a/Scripts/cleanup.swift+++ b/Scripts/cleanup.swift@@ -246,13 +246,11 @@ private final class KeepAliveCleanupCommand {candidates.append(projectURL.appending(path: "Build/CodexBar.app"))}- for candidate in candidates {- if try appBundleIdentifier(at: candidate) == bundleIdentifier {- return candidate- }+ for candidate in candidates where try appBundleIdentifier(at: candidate) == bundleIdentifier {+ return candidate}- // xcodebuild 定位不到是"查不到"而不是数据损坏, 保持非致命+ // xcodebuild 未找到目标不表示数据损坏, 按非致命失败处理guard let builtAppURL = try? resolveBuiltAppURL(configuration: configuration) else {return nil}diff --git a/Scripts/dmg.sh b/Scripts/dmg.shindex b2afe61..1fbb7d1 100755--- a/Scripts/dmg.sh+++ b/Scripts/dmg.sh@@ -161,8 +161,8 @@ tell application "Finder"set arrangement of theViewOptions to not arrangedset icon size of theViewOptions to 96set text size of theViewOptions to 13- set position of item "${APP_NAME}.app" of mountFolder to {170, 80}- set position of item "Applications" of mountFolder to {350, 80}+ set position of item "${APP_NAME}.app" of mountFolder to {170, 110}+ set position of item "Applications" of mountFolder to {350, 110}update mountFolder without registering applicationsdelay 2trydiff --git a/Scripts/performance/README.md b/Scripts/performance/README.mdindex 679bb1c..e57d09c 100644--- a/Scripts/performance/README.md+++ b/Scripts/performance/README.md@@ -28,7 +28,7 @@ python3 -m Scripts.performance \| `standard` | 10 分钟 | 日常测试,默认预设 || `extended` | 30 分钟 | 长时间观察 |-时长为各阶段的计划采集时间之和,不含预热、Instruments 启停和数据导出;实际运行时间更长。+时长是各阶段计划采集时间之和。预热、Instruments 启停和数据导出需要额外时间。## 参数@@ -63,7 +63,7 @@ Performance/4.1.1(111)-extended-20261024140000/`performance.html` 用于查看报告,`performance.json` 用于基线比较和重新生成报告,`*.trace` 可用 Instruments 打开。目录内同时保存采样 XML、命令日志和工具源码快照。-已有同名目录时,脚本会报错而不覆盖已有结果。采集时可用 `--label` 为本次测试添加标签,在默认目录名后追加 `-{标签}`,标签不能为空或包含 `/`:+已有同名目录时,脚本会报错,保留已有结果。用 `--label` 添加测试标签,脚本会在默认目录名后追加 `-{标签}`。标签不能为空或包含 `/`:```shpython3 -m Scripts.performance --preset quick --label idlediff --git a/Scripts/performance/models.py b/Scripts/performance/models.pyindex 10f2a5f..09096ac 100644--- a/Scripts/performance/models.py+++ b/Scripts/performance/models.py@@ -1,4 +1,4 @@-"""Types for the existing capture and report dictionaries"""+"""Types for capture and report dictionaries"""from typing import Literal, NotRequired, TypedDictdiff --git a/Tests/App/Activity/ActivityBackfillTests.swift b/Tests/App/Activity/ActivityBackfillTests.swiftindex 6cd5e3e..9f593e5 100644--- a/Tests/App/Activity/ActivityBackfillTests.swift+++ b/Tests/App/Activity/ActivityBackfillTests.swift@@ -120,7 +120,7 @@ struct ActivityBackfillTests {}#expect(ready)#expect(probe.graph.tasks[key]?.tokenUsage?.totalTokens == 50)- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(!unavailable)#expect(probe.graph.tasks[key]?.state == .running)let progress = probe.graph.tasks[key]?.progressGeneration@@ -153,7 +153,7 @@ struct ActivityBackfillTests {#expect(probe.graph.tasks[key]?.progressGeneration == progress)#expect(probe.graph.tasks[key]?.state == .running)#expect(probe.graph.tasks[key]?.tokenUsage?.totalTokens == 50)- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(!unavailable)try await Self.waitForItemReads(logs, count: 2)await reader.stop()@@ -562,7 +562,7 @@ extension ActivityBackfillTests {}#expect(ready)startTask.withLock { $0 = true }- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(probe.graph.tasks[.init(thread: "main", turn: "root")]?.state == .running)#expect(await reader.stop())#expect(try await !logs.page().entries.contains { $0.method == "thread/items/list" })diff --git a/Tests/App/Activity/ActivityIsolationTests.swift b/Tests/App/Activity/ActivityIsolationTests.swiftindex 7384839..a46e12e 100644--- a/Tests/App/Activity/ActivityIsolationTests.swift+++ b/Tests/App/Activity/ActivityIsolationTests.swift@@ -124,7 +124,7 @@ struct ActivityIsolationTests {#expect(lifecycle.graph.tasks[keys[1]]?.lifecycleCoverageCheckedAt != nil)#expect(lifecycle.graph.tasks[keys[0]]?.lifecycleCoverageCheckedAt == nil)repaired.withLock { $0 = true }- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(keys.allSatisfy { lifecycle.graph.tasks[$0]?.lifecycleCoverageCheckedAt != nil })#expect(lifecycle.graph.unavailableTurns.isDisjoint(with: keys))#expect(!disconnected)@@ -182,7 +182,7 @@ struct ActivityIsolationTests {}#expect(failures == 0)#expect(observed == 3)- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)try FileManager.default.removeItem(at: blocker)await reader.stop()let recorded = try directory.historyRecords().filter { $0.activityData != nil }.count@@ -230,7 +230,7 @@ extension ActivityIsolationTests {#expect(observed == 1)phase.withLock { $0 = 1 }let started = ContinuousClock.now- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(ContinuousClock.now - started < .seconds(1))#expect(observed == 2 && !disconnected)try database.execute("COMMIT")@@ -333,11 +333,11 @@ extension ActivityIsolationTests {try corruptHistory()}phase.withLock { $0 = 1 }- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(observed == 2)// 给周期缓存刷新一次触发机会, 失败不能使实时连接失效try await Task.sleep(for: .milliseconds(1200))- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(!disconnected)let key = ActivityTaskKey(thread: "healthy", turn: "turn")#expect(lifecycle.graph.tasks[key]?.lifecycleCoverageCheckedAt != nil)@@ -437,15 +437,15 @@ extension ActivityIsolationTests {}#expect(observed == 1)phase.withLock { $0 = 1 }- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(observed == 2)try FileManager.default.removeItem(at: blocker)for _ in 0 ..< 200 where !FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("event.db").path) {try await Task.sleep(for: .milliseconds(10))}- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)phase.withLock { $0 = 2 }- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(observed == 3)#expect(!disconnected)#expect(await reader.stop())diff --git a/Tests/App/Activity/ActivityLiveLabelTests.swift b/Tests/App/Activity/ActivityLiveLabelTests.swiftnew file mode 100644index 0000000..c5c5c99--- /dev/null+++ b/Tests/App/Activity/ActivityLiveLabelTests.swift@@ -0,0 +1,141 @@+import Foundation+import Testing++struct ActivityLiveLabelTests {+ @Test(arguments: [+ (["read"], .init("command-read")), (["listFiles"], .init("command-listfiles")), (["search"], .init("command-search")),+ (["search", "read", "read"], .init("command-read-search")), (["search", "listFiles"], .init("command-listfiles-search")),+ (["listFiles", "read"], .init("command-read-listfiles")), (["search", "listFiles", "read"], .init("command-read-listfiles-search")),+ (["read", "unknown"], .init("command", detail: String(localized: "activity.live.actions-read"))),+ (["search", "unknown", "read"], .init("command", detail: String(localized: "activity.live.actions-read-search"))),+ (["search", "unknown", "read", "read"], .init("command", detail: String(localized: "activity.live.actions-read-search"))),+ (["future"], .init("command")), ([], .init("command"))+ ] as [([String], ActivityLiveLabel)])+ func commandActionsUseServerClassification(actions: [String], expected: ActivityLiveLabel) throws {+ let item = ActivityItem(id: "cmd", type: .commandExecution, commandActions: actions.map { .init(type: $0) })+ let label = try #require(item.liveLabel)+ #expect(label == expected)+ if let detail = expected.detail {+ #expect(label.text == String(localized: "activity.live.command-with-actions", defaultValue: "\(detail)"))+ #expect(!label.text.contains(" • "))+ }+ }++ @Test(arguments: [+ (["search", "read"], "actions-read-search"),+ (["read", "search"], "actions-read-search"),+ (["search", "unknown", "read", "read"], "actions-read-search"),+ (["search", "listFiles", "read", "listFiles"], "actions-read-listfiles-search"),+ ([], nil), (["unknown", "future"], nil)+ ] as [([String], String?)])+ func commandCompletionLocalizesAndOrdersKnownActions(actions: [String], detailKey: String?) {+ let item = ActivityItem(+ id: "cmd", type: .commandExecution, status: "failed",+ commandActions: actions.map { .init(type: $0) }+ )+ #expect(item.liveCompletionLabel?.key == (detailKey == nil ? "command-failed" : "action-failed"))+ #expect(item.liveCompletionLabel?.detail == detailKey.map { ActivityLiveLabel($0).text })+ }++ @Test func knownCommandClassificationsTakePrecedenceOverParsing() throws {+ let item = try TestFixtures.decode(ActivityItem.self, #"""+ {"id":"cmd","type":"commandExecution","status":"completed","commandActions":[+ {"type":"read","command":"cat file"},{"type":"unknown","command":"pwd; git status"}]}+ """#)+ #expect(item.commandSummary == nil)+ #expect(item.liveLabel == ActivityLiveLabel("command", detail: ActivityLiveLabel("actions-read").text))+ #expect(item.liveCompletionLabel == ActivityLiveLabel("action-completed", detail: ActivityLiveLabel("actions-read").text))+ }++ @Test(arguments: ["git", "git, ls"])+ func parsedCommandLabelsAreLocalized(names: String) {+ #expect(ActivityLiveLabel("executing-tool", detail: "python3").text == String(localized: "activity.live.executing-named-tool", defaultValue: "\("python3")"))+ #expect(ActivityLiveLabel("executing-tool", detail: names).text == String(localized: "activity.live.executing-named-tool", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("command-completed", detail: names).text == String(localized: "activity.live.named-command-completed", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("command-failed", detail: names).text == String(localized: "activity.live.named-command-failed", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("command-declined", detail: names).text == String(localized: "activity.live.named-command-declined", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("executing-tools", detail: names).text == String(localized: "activity.live.executing-tools", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("tools-completed", detail: names).text == String(localized: "activity.live.tools-completed", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("tools-failed", detail: names).text == String(localized: "activity.live.tools-failed", defaultValue: "\(names)"))+ #expect(ActivityLiveLabel("tools-declined", detail: names).text == String(localized: "activity.live.tools-declined", defaultValue: "\(names)"))+ }++ @Test(arguments: ["mcpToolCall", "dynamicToolCall"], [nil, "server"] as [String?])+ func completionPreservesActualToolNames(type: String, server: String?) {+ let item = ActivityItem(+ id: "tool", type: ActivityItem.ItemType(rawValue: type) ?? .unknown, status: "failed", tool: "search/read", server: server,+ commandActions: [.init(type: "read")]+ )+ #expect(item.liveCompletionLabel?.key == "tool-failed")+ let name = type == "mcpToolCall" ? server.map { $0 + ".search/read" } ?? "search/read" : "search/read"+ #expect(item.liveCompletionLabel?.detail == name)+ #expect(item.liveCompletionLabel?.text == String(localized: "activity.live.named-tool-failed", defaultValue: "\(name)"))+ }++ @Test(arguments: ["tool-completed", "tool-failed", "tool-declined", "command-completed", "command-failed", "command-declined", "calling-tool", "command", "model-changed"])+ func missingDetailsKeepStandaloneLabels(key: String) {+ #expect(ActivityLiveLabel(key).text == ActivityLiveLabel(key).localizedText)+ #expect(ActivityLiveLabel(key, detail: "").text == ActivityLiveLabel(key).localizedText)+ }++ @Test(arguments: [+ ("spawnAgent", ("agent-starting", "activity.action.start-subagent")),+ ("sendInput", ("agent-assigning", "activity.action.assign-subagent")),+ ("followupTask", ("agent-assigning", "activity.action.assign-subagent")),+ ("sendMessage", ("agent-contacting", "activity.action.message-subagent")),+ ("resumeAgent", ("agent-resuming", "activity.action.resume-subagent")),+ ("wait", ("agent-waiting", "activity.action.wait-subagent")),+ ("interruptAgent", ("agent-interrupting", "activity.action.interrupt-subagent")),+ ("closeAgent", ("agent-closing", "activity.action.close-subagent")),+ ("listAgents", ("agent-querying", "activity.action.query-subagent")),+ ("future", ("agent-coordinating", "activity.action.coordinate-subagents"))+ ] as [(String, (String, LocalizedStringResource))])+ func subagentOperationsDescribeTheCall(operation: (tool: String, expected: (statusKey: String, action: LocalizedStringResource))) {+ let item = ActivityItem(+ id: "agent", type: .collabAgentToolCall, status: "completed", tool: operation.tool,+ agentsStates: ["child": .init(status: "running")]+ )+ #expect(item.liveLabel?.key == operation.expected.statusKey)+ #expect(item.liveCompletionLabel?.key == "action-completed")+ #expect(item.liveCompletionLabel?.detail == String(localized: operation.expected.action))+ #expect(ActivityDisplayFormat.toolActionText(itemType: item.type.rawValue, toolName: operation.tool) == item.liveCompletionLabel?.detail)+ }++ @Test(arguments: ["completed", "failed", "declined", "interrupted"])+ func subagentCompletionPreservesOutcome(status: String) {+ let item = ActivityItem(+ id: "agent", type: .collabAgentToolCall, status: status, tool: "spawnAgent",+ agentsStates: ["child": .init(status: "running")]+ )+ #expect(item.liveCompletionLabel?.key == "action-" + status)+ #expect(item.liveCompletionLabel?.detail == String(localized: "activity.action.start-subagent"))+ }++ @Test(arguments: [+ ("commandExecution", "activity.action.command"), ("fileChange", "activity.action.edit-files"),+ ("webSearch", "activity.action.search-web"), ("imageView", "activity.action.view-image"),+ ("imageGeneration", "activity.action.generate-image"), ("sleep", "activity.action.wait-timer"),+ ("mcpToolCall", "activity.action.call-tool"), ("dynamicToolCall", "activity.action.call-tool"),+ ("collabAgentToolCall", "activity.action.coordinate-subagents")+ ] as [(String, LocalizedStringResource)])+ func namelessToolTypesHaveReadableFallbacks(type: String, action: LocalizedStringResource) {+ #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: nil) == String(localized: action))+ #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: " ") == String(localized: action))+ }++ @Test(arguments: ["mcpToolCall", "dynamicToolCall", "future", nil] as [String?], ["search/read", "spawnAgent", "commandExecution"])+ func actualToolNamesAreNeverClassifiedByTheirSpelling(type: String?, tool: String) {+ #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: tool) == tool)+ }++ @Test func unknownUnnamedToolsDoNotExposeInternalTypes() {+ #expect(ActivityDisplayFormat.toolActionText(itemType: "futureInternalType", toolName: nil) == nil)+ #expect(ActivityDisplayFormat.toolActionText(itemType: nil, toolName: nil) == nil)+ }++ @Test(arguments: ["completed", "failed", "declined", "unknown"])+ func toolOutcomeDoesNotAssumeSuccess(status: String) {+ let item = ActivityItem(id: "image", type: .imageGeneration, status: status)+ #expect(item.liveCompletionLabel?.key == (status == "unknown" ? nil : "image-" + status))+ }+}diff --git a/Tests/App/Activity/ActivityLivePresentationTests.swift b/Tests/App/Activity/ActivityLivePresentationTests.swiftindex 8160319..925fcff 100644--- a/Tests/App/Activity/ActivityLivePresentationTests.swift+++ b/Tests/App/Activity/ActivityLivePresentationTests.swift@@ -308,41 +308,6 @@ struct ActivityLivePresentationTests {#expect(live.summary.current.key == "command")}- @Test(arguments: [- (["read"], .init("command-read")), (["listFiles"], .init("command-listfiles")), (["search"], .init("command-search")),- (["search", "read", "read"], .init("command-read-search")), (["search", "listFiles"], .init("command-listfiles-search")),- (["listFiles", "read"], .init("command-read-listfiles")), (["search", "listFiles", "read"], .init("command-read-listfiles-search")),- (["read", "unknown"], .init("command", detail: String(localized: "activity.live.actions-read"))),- (["search", "unknown", "read"], .init("command", detail: String(localized: "activity.live.actions-read-search"))),- (["search", "unknown", "read", "read"], .init("command", detail: String(localized: "activity.live.actions-read-search"))),- (["future"], .init("command")), ([], .init("command"))- ] as [([String], ActivityLiveLabel)])- func commandActionsUseServerClassification(actions: [String], expected: ActivityLiveLabel) throws {- let item = ActivityItem(id: "cmd", type: .commandExecution, commandActions: actions.map { .init(type: $0) })- let label = try #require(item.liveLabel)- #expect(label == expected)- if let detail = expected.detail {- #expect(label.text == String(localized: "activity.live.command-with-actions", defaultValue: "\(detail)"))- #expect(!label.text.contains(" • "))- }- }-- @Test(arguments: [- (["search", "read"], "actions-read-search"),- (["read", "search"], "actions-read-search"),- (["search", "unknown", "read", "read"], "actions-read-search"),- (["search", "listFiles", "read", "listFiles"], "actions-read-listfiles-search"),- ([], nil), (["unknown", "future"], nil)- ] as [([String], String?)])- func commandCompletionLocalizesAndOrdersKnownActions(actions: [String], detailKey: String?) {- let item = ActivityItem(- id: "cmd", type: .commandExecution, status: "failed",- commandActions: actions.map { .init(type: $0) }- )- #expect(item.liveCompletionLabel?.key == (detailKey == nil ? "command-failed" : "action-failed"))- #expect(item.liveCompletionLabel?.detail == detailKey.map { ActivityLiveLabel($0).text })- }-@Test(arguments: ["completed", "failed", "declined"])func recentCommandOutcomesUseLocalizedActionDetails(status: String) throws {var reducer = try prepared()@@ -398,41 +363,6 @@ struct ActivityLivePresentationTests {#expect(try summary(reducer).current.key == "processing")}- @Test func knownCommandClassificationsTakePrecedenceOverParsing() throws {- let item = try TestFixtures.decode(ActivityItem.self, #"""- {"id":"cmd","type":"commandExecution","status":"completed","commandActions":[- {"type":"read","command":"cat file"},{"type":"unknown","command":"pwd; git status"}]}- """#)- #expect(item.commandSummary == nil)- #expect(item.liveLabel == ActivityLiveLabel("command", detail: ActivityLiveLabel("actions-read").text))- #expect(item.liveCompletionLabel == ActivityLiveLabel("action-completed", detail: ActivityLiveLabel("actions-read").text))- }-- @Test(arguments: ["git", "git, ls"])- func parsedCommandLabelsAreLocalized(names: String) {- #expect(ActivityLiveLabel("executing-tool", detail: "python3").text == String(localized: "activity.live.executing-named-tool", defaultValue: "\("python3")"))- #expect(ActivityLiveLabel("executing-tool", detail: names).text == String(localized: "activity.live.executing-named-tool", defaultValue: "\(names)"))- #expect(ActivityLiveLabel("command-completed", detail: names).text == String(localized: "activity.live.named-command-completed", defaultValue: "\(names)"))- #expect(ActivityLiveLabel("command-failed", detail: names).text == String(localized: "activity.live.named-command-failed", defaultValue: "\(names)"))- #expect(ActivityLiveLabel("command-declined", detail: names).text == String(localized: "activity.live.named-command-declined", defaultValue: "\(names)"))- #expect(ActivityLiveLabel("executing-tools", detail: names).text == String(localized: "activity.live.executing-tools", defaultValue: "\(names)"))- #expect(ActivityLiveLabel("tools-completed", detail: names).text == String(localized: "activity.live.tools-completed", defaultValue: "\(names)"))- #expect(ActivityLiveLabel("tools-failed", detail: names).text == String(localized: "activity.live.tools-failed", defaultValue: "\(names)"))- #expect(ActivityLiveLabel("tools-declined", detail: names).text == String(localized: "activity.live.tools-declined", defaultValue: "\(names)"))- }-- @Test(arguments: ["mcpToolCall", "dynamicToolCall"], [nil, "server"] as [String?])- func completionPreservesActualToolNames(type: String, server: String?) {- let item = ActivityItem(- id: "tool", type: ActivityItem.ItemType(rawValue: type) ?? .unknown, status: "failed", tool: "search/read", server: server,- commandActions: [.init(type: "read")]- )- #expect(item.liveCompletionLabel?.key == "tool-failed")- let name = type == "mcpToolCall" ? server.map { $0 + ".search/read" } ?? "search/read" : "search/read"- #expect(item.liveCompletionLabel?.detail == name)- #expect(item.liveCompletionLabel?.text == String(localized: "activity.live.named-tool-failed", defaultValue: "\(name)"))- }-@Test func currentToolDetailsUseLocalizedTemplates() throws {let name = "server.tools"var reducer = try prepared()@@ -456,45 +386,6 @@ struct ActivityLivePresentationTests {#expect(label.detail == route)}- @Test(arguments: ["tool-completed", "tool-failed", "tool-declined", "command-completed", "command-failed", "command-declined", "calling-tool", "command", "model-changed"])- func missingDetailsKeepStandaloneLabels(key: String) {- #expect(ActivityLiveLabel(key).text == ActivityLiveLabel(key).localizedText)- #expect(ActivityLiveLabel(key, detail: "").text == ActivityLiveLabel(key).localizedText)- }-- @Test(arguments: [- ("spawnAgent", ("agent-starting", "activity.action.start-subagent")),- ("sendInput", ("agent-assigning", "activity.action.assign-subagent")),- ("followupTask", ("agent-assigning", "activity.action.assign-subagent")),- ("sendMessage", ("agent-contacting", "activity.action.message-subagent")),- ("resumeAgent", ("agent-resuming", "activity.action.resume-subagent")),- ("wait", ("agent-waiting", "activity.action.wait-subagent")),- ("interruptAgent", ("agent-interrupting", "activity.action.interrupt-subagent")),- ("closeAgent", ("agent-closing", "activity.action.close-subagent")),- ("listAgents", ("agent-querying", "activity.action.query-subagent")),- ("future", ("agent-coordinating", "activity.action.coordinate-subagents"))- ] as [(String, (String, LocalizedStringResource))])- func subagentOperationsDescribeTheCall(operation: (tool: String, expected: (statusKey: String, action: LocalizedStringResource))) {- let item = ActivityItem(- id: "agent", type: .collabAgentToolCall, status: "completed", tool: operation.tool,- agentsStates: ["child": .init(status: "running")]- )- #expect(item.liveLabel?.key == operation.expected.statusKey)- #expect(item.liveCompletionLabel?.key == "action-completed")- #expect(item.liveCompletionLabel?.detail == String(localized: operation.expected.action))- #expect(ActivityDisplayFormat.toolActionText(itemType: item.type.rawValue, toolName: operation.tool) == item.liveCompletionLabel?.detail)- }-- @Test(arguments: ["completed", "failed", "declined", "interrupted"])- func subagentCompletionPreservesOutcome(status: String) {- let item = ActivityItem(- id: "agent", type: .collabAgentToolCall, status: status, tool: "spawnAgent",- agentsStates: ["child": .init(status: "running")]- )- #expect(item.liveCompletionLabel?.key == "action-" + status)- #expect(item.liveCompletionLabel?.detail == String(localized: "activity.action.start-subagent"))- }-@Test(arguments: ["spawnAgent", "wait", "sendInput", "future"], ["running", "errored"])func interruptedCollabUpdatesRecentEvent(tool: String, childStatus: String) throws {var reducer = try prepared()@@ -513,28 +404,6 @@ struct ActivityLivePresentationTests {#expect(ActivityItem(id: "child", type: .subAgentActivity, kind: "interrupted").liveCompletionLabel?.key == "agent-interrupted")}- @Test(arguments: [- ("commandExecution", "activity.action.command"), ("fileChange", "activity.action.edit-files"),- ("webSearch", "activity.action.search-web"), ("imageView", "activity.action.view-image"),- ("imageGeneration", "activity.action.generate-image"), ("sleep", "activity.action.wait-timer"),- ("mcpToolCall", "activity.action.call-tool"), ("dynamicToolCall", "activity.action.call-tool"),- ("collabAgentToolCall", "activity.action.coordinate-subagents")- ] as [(String, LocalizedStringResource)])- func namelessToolTypesHaveReadableFallbacks(type: String, action: LocalizedStringResource) {- #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: nil) == String(localized: action))- #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: " ") == String(localized: action))- }-- @Test(arguments: ["mcpToolCall", "dynamicToolCall", "future", nil] as [String?], ["search/read", "spawnAgent", "commandExecution"])- func actualToolNamesAreNeverClassifiedByTheirSpelling(type: String?, tool: String) {- #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: tool) == tool)- }-- @Test func unknownUnnamedToolsDoNotExposeInternalTypes() {- #expect(ActivityDisplayFormat.toolActionText(itemType: "futureInternalType", toolName: nil) == nil)- #expect(ActivityDisplayFormat.toolActionText(itemType: nil, toolName: nil) == nil)- }-@Test(arguments: [("form", "waiting-form"), ("openai/form", "waiting-form"), ("openaiForm", "waiting-form"),("url", "waiting-external"), ("future", "waiting-service")@@ -711,12 +580,6 @@ struct ActivityLivePresentationTests {#expect(reducer.tokenUsageTurns.isEmpty)}- @Test(arguments: ["completed", "failed", "declined", "unknown"])- func toolOutcomeDoesNotAssumeSuccess(status: String) {- let item = ActivityItem(id: "image", type: .imageGeneration, status: status)- #expect(item.liveCompletionLabel?.key == (status == "unknown" ? nil : "image-" + status))- }-@Test(arguments: [("thread/status/changed", false), ("mcpServer/elicitation/request", false),("item/tool/requestUserInput", false), ("item/tool/requestUserInput", true), ("item/completed", false)diff --git a/Tests/App/Activity/ActivityReaderBoundsTests.swift b/Tests/App/Activity/ActivityReaderBoundsTests.swiftindex f3d8fed..8c4ffc1 100644--- a/Tests/App/Activity/ActivityReaderBoundsTests.swift+++ b/Tests/App/Activity/ActivityReaderBoundsTests.swift@@ -82,7 +82,7 @@ struct ActivityReaderBoundsTests {}#expect(ready)let start = Date()- #expect(await reader.drainNow().status == .sourceUnavailable)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .sourceUnavailable)#expect(Date().timeIntervalSince(start) < 2)await reader.stop()release.signal()@@ -155,7 +155,7 @@ struct ActivityReaderBoundsTests {try await Task.sleep(for: .milliseconds(5))}#expect(ready)- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)for _ in 0 ..< 200 {let current = await reader.lifecycleSnapshot.lifecycleStates(for: [.init(threadID: "child", turnID: "child-turn")])if current.first?.effort == "low" {@@ -233,7 +233,7 @@ extension ActivityReaderBoundsTests {try await Task.sleep(for: .milliseconds(5))}#expect(ready)- let result = await reader.drainNow()+ let result = await reader.drainForRecovery(generation: UUID())let key = ActivityTaskKey(thread: "healthy", turn: "healthy-turn")#expect(lifecycle.graph.tasks[key]?.lifecycleCoverageCheckedAt != nil)#expect(!lifecycle.graph.unavailableTurns.contains(key))diff --git a/Tests/App/Activity/ActivityReconciliationTests.swift b/Tests/App/Activity/ActivityReconciliationTests.swiftnew file mode 100644index 0000000..7ab491b--- /dev/null+++ b/Tests/App/Activity/ActivityReconciliationTests.swift@@ -0,0 +1,467 @@+import Foundation+import Synchronization+import Testing++@MainActor+struct ActivityReconciliationTests {+ @Test(arguments: [false, true])+ func bootstrapCannotFinishARecoveryStartedAfterItsBarrier(restarted: Bool) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url),+ activityDataDirectoryURL: directory.url+ )+ let recovery = UUID()+ let readerID = UUID()+ monitor.consume(ActivityUpdate(+ readerID: readerID,+ revision: 1,+ phase: .bootstrapStart,+ graph: ActivityTaskGraph(),+ transitions: [],+ terminalEvents: [],+ backfilledTasks: [],+ recoveryID: recovery+ ))+ #expect(monitor.activeRecoveryID == recovery)+ if restarted {+ monitor.beginProtectionRecovery()+ }+ monitor.consume(ActivityUpdate(+ readerID: readerID,+ revision: 2,+ phase: .bootstrapEnd,+ graph: ActivityTaskGraph(),+ transitions: [],+ terminalEvents: [],+ backfilledTasks: [],+ recoveryID: recovery+ ))+ #expect(monitor.isProtectionRecoveryInProgress == restarted)+ monitor.stop()+ }++ @Test func recoveryRetriesOnlyUnfinishedThreadsAndNewRecoveryReadsAllThreads() async throws {+ let directory = try TestDirectory()+ var readerStopped = true+ defer {+ if readerStopped {+ await #expect(throws: Never.self) { try await directory.removeAfterClosingHistory() }+ }+ }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let state = Mutex(Scenario())+ let initial = ContinuousClock.now+ let clock = Mutex(initial)+ let server = try SharedServerFixture { try Self.serve($0, state: state) }+ defer { server.close() }+ let monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url),+ activityDataDirectoryURL: directory.url+ )+ var ready = false+ let reader = AppServerActivityReader(+ socketURL: server.url, logStorage: nil,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url),+ reconciliationClock: { clock.withLock { $0 } },+ onBatch: { update in+ monitor.consume(update)+ if case .bootstrapEnd = update.phase {+ ready = true+ }+ }+ )+ defer {+ let pendingRecovery = monitor.recoveryTask+ pendingRecovery?.cancel()+ monitor.activityReader = nil+ readerStopped = await reader.stop()+ await pendingRecovery?.value+ #expect(readerStopped)+ }+ monitor.activityReader = reader+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(ready)+ let recovery = try #require(monitor.activeRecoveryID)+ for _ in 0 ..< 3 {+ monitor.requestActivityRecovery()+ await monitor.recoveryTask?.value+ #expect(monitor.isProtectionRecoveryInProgress)+ }+ #expect(monitor.activeRecoveryID == recovery)+ #expect(state.withLock { $0.reads } == ["missing": 1, "normal": 1])+ monitor.beginProtectionRecovery()+ monitor.requestActivityRecovery()+ await monitor.recoveryTask?.value+ #expect(state.withLock { $0.reads } == ["missing": 2, "normal": 2])+ #expect(monitor.isProtectionRecoveryInProgress)+ let nextRecovery = try #require(monitor.activeRecoveryID)+ state.withLock { $0.missing = false }+ clock.withLock { $0 = initial.advanced(by: .seconds(5)) }+ #expect(await reader.drainForRecovery(generation: nextRecovery).status == .completed)+ #expect(state.withLock { $0.reads } == ["missing": 3, "normal": 2])+ #expect(monitor.isProtectionRecoveryInProgress)+ monitor.requestActivityRecovery()+ await monitor.recoveryTask?.value+ #expect(!monitor.isProtectionRecoveryInProgress)+ #expect(monitor.canPublishActivityTransitions)+ #expect(await reader.stop())+ try server.finish()+ }++ @Test(arguments: [false, true])+ func boundedRetriesKeepIdleRefreshIntervalsAndEventuallyRecoverWithoutNotifications(delayedRetry: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let state = Mutex(Scenario())+ let initial = ContinuousClock.now+ let recovery = UUID()+ let clock = Mutex(initial)+ let server = try SharedServerFixture { try Self.serve($0, state: state) }+ defer { server.close() }+ var ready = false+ var disconnected = false+ let reader = AppServerActivityReader(+ socketURL: server.url, logStorage: nil,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url),+ reconciliationClock: { clock.withLock { $0 } },+ onBatch: {+ if $0.phase == .bootstrapEnd {+ ready = true+ }+ if $0.phase == .sourceUnavailable {+ disconnected = true+ }+ }+ )+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(ready)+ // 首次恢复读取后, 失败线程在 5, 20, 50 秒重试, 此后每 60 秒探测+ let schedule = delayedRetry ? [(0, 2, 2), (70, 3, 3), (75, 3, 3), (129, 3, 3)]+ : [(0, 2, 2), (4, 2, 2), (5, 3, 2), (19, 3, 2), (20, 4, 2), (49, 4, 2), (50, 5, 2), (60, 5, 3), (109, 5, 3)]+ for (seconds, missingReads, normalReads) in schedule {+ clock.withLock { $0 = initial.advanced(by: .seconds(seconds)) }+ let result = await reader.drainForRecovery(generation: recovery)+ #expect(result.status == .partial)+ if case let .update(update) = result {+ #expect(!update.isComplete)+ }+ #expect(state.withLock { $0.reads } == ["missing": missingReads, "normal": normalReads])+ }+ state.withLock { $0.missing = false }+ clock.withLock { $0 = initial.advanced(by: .seconds(delayedRetry ? 130 : 110)) }+ let recoveredReads = delayedRetry ? ["missing": 4, "normal": 4] : ["missing": 6, "normal": 3]+ #expect(await reader.drainForRecovery(generation: recovery).status == .completed)+ #expect(state.withLock { $0.reads } == recoveredReads)+ // 新一轮恢复重新执行完整屏障, 后续读取沿用这轮恢复的重试预算+ let nextRecovery = UUID()+ #expect(await reader.drainForRecovery(generation: nextRecovery).status == .completed)+ #expect(state.withLock { $0.reads } == recoveredReads.mapValues { $0 + 1 })+ state.withLock { $0.loaded = false }+ #expect(await reader.drainForRecovery(generation: nextRecovery).status == .completed)+ state.withLock { $0.loaded = true+ $0.missing = true+ }+ #expect(await reader.drainForRecovery(generation: nextRecovery).status == .partial)+ #expect(state.withLock { $0.reads } == recoveredReads.mapValues { $0 + 2 })+ #expect(!disconnected)+ #expect(await reader.stop())+ try server.finish()+ }++ @Test func liveThreadChangesInvalidateOnlyItsRecoveryResult() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let state = Mutex(Scenario())+ let clock = ContinuousClock.now+ let recovery = UUID()+ let server = try SharedServerFixture { try Self.serve($0, state: state) }+ defer { server.close() }+ var ready = false+ var publishedStates = [ActivityTaskState]()+ let reader = AppServerActivityReader(+ socketURL: server.url, logStorage: nil,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url),+ reconciliationClock: { clock },+ onBatch: {+ if $0.phase == .bootstrapEnd {+ ready = true+ }+ if let task = $0.graph.tasks[.init(thread: "normal", turn: "turn")] {+ publishedStates.append(task.state)+ }+ }+ )+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(ready)+ #expect(await reader.drainForRecovery(generation: recovery).status == .partial)+ for stage in 1 ... 3 {+ state.withLock { $0.stage = stage }+ let result = await reader.drainForRecovery(generation: recovery)+ #expect(result.status == .partial)+ if case let .update(update) = result {+ let key = ActivityTaskKey(thread: "normal", turn: "turn")+ if stage == 3 {+ #expect(update.graph.tasks[key] == nil)+ #expect(update.graph.recentlyEndedTaskAt[key] != nil)+ } else {+ #expect(update.graph.tasks[key]?.state == (stage == 1 ? .running : .waitingApproval))+ }+ }+ #expect(state.withLock { $0.reads } == ["missing": 2, "normal": 2 + stage])+ }+ #expect(publishedStates.contains(.running))+ #expect(publishedStates.contains(.waitingApproval))+ #expect(await reader.stop())+ try server.finish()+ }++ @Test func protocolFailureStillReconnectsAndDiscardsPreviousChecks() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let state = Mutex(Scenario())+ let server = try SharedServerFixture(connections: 2) { try Self.serve($0, state: state) }+ defer { server.close() }+ var bootstraps = [ActivityUpdate]()+ var disconnected = false+ let reader = AppServerActivityReader(+ socketURL: server.url, logStorage: nil,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url)+ ) {+ if $0.phase == .bootstrapEnd {+ bootstraps.append($0)+ }+ if $0.phase == .sourceUnavailable {+ disconnected = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where bootstraps.isEmpty {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(bootstraps.count == 1)+ state.withLock { $0.protocolFailure = true }+ #expect(await reader.drainForRecovery(generation: UUID()).status == .sourceUnavailable)+ for _ in 0 ..< 500 where bootstraps.count < 2 {+ try await Task.sleep(for: .milliseconds(10))+ }+ try #require(bootstraps.count == 2)+ #expect(disconnected)+ #expect(bootstraps[0].recoveryID != bootstraps[1].recoveryID)+ #expect(bootstraps[1].isComplete)+ #expect(state.withLock { $0.reads } == ["missing": 3, "normal": 3])+ #expect(await reader.stop())+ try server.finish()+ }++ @Test func notificationDuringLastRetryPreventsCompletingWithStaleSuccess() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let state = Mutex(Scenario())+ let initial = ContinuousClock.now+ let clock = Mutex(initial)+ let recovery = UUID()+ let server = try SharedServerFixture { try Self.serve($0, state: state) }+ defer { server.close() }+ var ready = false+ let reader = AppServerActivityReader(+ socketURL: server.url, logStorage: nil,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url),+ reconciliationClock: { clock.withLock { $0 } },+ onBatch: {+ if $0.phase == .bootstrapEnd {+ ready = true+ }+ }+ )+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(ready)+ #expect(await reader.drainForRecovery(generation: recovery).status == .partial)+ state.withLock { $0.missing = false+ $0.lateStage = 1+ }+ clock.withLock { $0 = initial.advanced(by: .seconds(5)) }+ #expect(await reader.drainForRecovery(generation: recovery).status == .partial)+ #expect(state.withLock { $0.reads } == ["missing": 3, "normal": 2])+ let result = await reader.drainForRecovery(generation: recovery)+ #expect(result.status == .completed)+ if case let .update(update) = result {+ #expect(update.graph.tasks[.init(thread: "normal", turn: "turn")]?.state == .running)+ }+ #expect(state.withLock { $0.reads } == ["missing": 3, "normal": 3])+ #expect(await reader.stop())+ try server.finish()+ }++ @Test(arguments: ["turn/started", "item/agentMessage/delta"])+ func activityExpeditesFailedThreadButDuplicateNotificationsRemainBounded(method: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let state = Mutex(Scenario())+ let initial = ContinuousClock.now+ let clock = Mutex(initial)+ let recovery = UUID()+ let server = try SharedServerFixture { try Self.serve($0, state: state) }+ defer { server.close() }+ var ready = false+ let reader = AppServerActivityReader(+ socketURL: server.url, logStorage: nil,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url),+ reconciliationClock: { clock.withLock { $0 } },+ onBatch: {+ if $0.phase == .bootstrapEnd {+ ready = true+ }+ }+ )+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ try #require(ready)+ for seconds in [0, 5, 20, 50] {+ clock.withLock { $0 = initial.advanced(by: .seconds(seconds)) }+ #expect(await reader.drainForRecovery(generation: recovery).status == .partial)+ }+ #expect(state.withLock { $0.reads } == ["missing": 5, "normal": 2])+ for seconds in 80 ... 84 {+ clock.withLock { $0 = initial.advanced(by: .seconds(seconds)) }+ state.withLock {+ $0.missingNotification = method+ $0.hasMissingActivity = true+ $0.timestamp = Date().addingTimeInterval(1).timeIntervalSince1970+ }+ #expect(await reader.drainForRecovery(generation: recovery).status == .partial)+ // 每轮 20 条通知只提前一次探测, 持续失败时仍保留最小间隔+ #expect(state.withLock { $0.reads } == ["missing": 6, "normal": 3])+ }+ clock.withLock { $0 = initial.advanced(by: .seconds(85)) }+ state.withLock { $0.missing = false }+ let result = await reader.drainForRecovery(generation: recovery)+ switch result {+ case let .update(update):+ #expect(update.graph.tasks[.init(thread: "missing", turn: "turn")]?.state == .running)+ default: Issue.record("Activity notification did not restore the failed thread")+ }+ #expect(state.withLock { $0.reads } == ["missing": 7, "normal": 3])+ clock.withLock { $0 = initial.advanced(by: .seconds(90)) }+ #expect(await reader.drainForRecovery(generation: recovery).status == .completed)+ #expect(state.withLock { $0.reads } == ["missing": 8, "normal": 3])+ #expect(await reader.stop())+ try server.finish()+ }++ private nonisolated struct Scenario {+ var reads: [String: Int] = [:]+ var missing = true+ var loaded = true+ var stage = 0+ var sentStage = 0+ var protocolFailure = false+ var lateStage: Int?+ var missingNotification: String?+ var hasMissingActivity = false+ var timestamp = Date().timeIntervalSince1970++ func thread(_ id: String) -> [String: Any] {+ let active = (id == "normal" && (stage == 1 || stage == 2)) || (id == "missing" && hasMissingActivity)+ return ["id": id, "source": "cli", "threadSource": "user", "status": [+ "type": active ? "active" : "idle", "activeFlags": active && stage == 2 ? ["waitingOnApproval"] : []+ ]]+ }++ var turn: [String: Any] {+ [+ "id": "turn",+ "rootTurnId": "turn",+ "status": stage == 3 ? "completed" : "inProgress",+ "startedAt": timestamp,+ "completedAt": stage == 3 ? timestamp + 1 : NSNull()+ ]+ }+ }++ private nonisolated static func serve(_ peer: SharedServerFixture.Peer, state: borrowing Mutex<Scenario>) throws {+ while let request = try? peer.readMessage() {+ let method = request["method"] as? String ?? ""+ let id = (request["params"] as? [String: Any])?["threadId"] as? String ?? ""+ let snapshot = state.withLock {+ if method == "thread/read" {+ $0.reads[id, default: 0] += 1+ }+ return $0+ }+ switch method {+ case "initialize": try peer.reply(to: request, result: ["userAgent": "codex/0.165.0"])+ case "initialized": break+ case "thread/loaded/list":+ if let method = snapshot.missingNotification {+ for _ in 0 ..< 20 {+ try peer.send(["method": method, "params": ["threadId": "missing", "turnId": "turn", "turn": snapshot.turn, "itemId": "answer", "delta": "text"]])+ }+ state.withLock { $0.missingNotification = nil }+ }+ if snapshot.stage != snapshot.sentStage {+ try sendStage(peer, snapshot: snapshot)+ state.withLock { $0.sentStage = snapshot.stage }+ }+ try peer.reply(to: request, result: ["data": snapshot.loaded ? ["missing", "normal"] : []])+ case "thread/read", "thread/resume":+ if id == "missing", method == "thread/resume", let stage = snapshot.lateStage {+ let changed = state.withLock {+ $0.stage = stage+ $0.sentStage = stage+ $0.lateStage = nil+ return $0+ }+ try sendStage(peer, snapshot: changed)+ }+ if id == "normal", snapshot.protocolFailure {+ state.withLock { $0.protocolFailure = false+ $0.missing = false+ }+ try peer.send(["id": #require(request["id"]), "error": ["code": -32602, "message": "invalid params"]])+ } else if id == "missing", snapshot.missing, method == "thread/resume" {+ try peer.send(["id": #require(request["id"]), "error": ["code": -32600, "message": "no rollout found for thread id missing"]])+ } else {+ try peer.reply(to: request, result: ["thread": snapshot.thread(id)])+ }+ case "thread/turns/list":+ let hasTurn = (id == "normal" && snapshot.stage > 0) || (id == "missing" && snapshot.hasMissingActivity)+ try peer.reply(to: request, result: ["data": hasTurn ? [snapshot.turn] : []])+ default: Issue.record("Unexpected request: \(method)")+ }+ }+ }++ private nonisolated static func sendStage(_ peer: SharedServerFixture.Peer, snapshot: Scenario) throws {+ if snapshot.stage == 1 || snapshot.stage == 3 {+ try peer.send(["method": snapshot.stage == 1 ? "turn/started" : "turn/completed", "params": ["threadId": "normal", "turn": snapshot.turn]])+ }+ try peer.send(["method": "thread/status/changed", "params": ["threadId": "normal", "status": #require(snapshot.thread("normal")["status"])]])+ }+}diff --git a/Tests/App/Activity/ActivitySchedulingTests.swift b/Tests/App/Activity/ActivitySchedulingTests.swiftindex 568128f..d1a2b08 100644--- a/Tests/App/Activity/ActivitySchedulingTests.swift+++ b/Tests/App/Activity/ActivitySchedulingTests.swift@@ -46,7 +46,7 @@ struct ActivitySchedulingTests {try await Task.sleep(for: .milliseconds(5))}#expect(ready)- #expect(await reader.drainNow().status == .partial)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .partial)#expect(lifecycle.graph.tasks[.init(thread: "thread", turn: "turn")]?.state == .waitingApproval)await reader.stop()release.signal()@@ -123,6 +123,62 @@ struct ActivitySchedulingTests {try server.finish()}+ @Test(arguments: [false, true])+ func historicalParentsUseIdleCadenceUntilAChildStarts(parentLoaded: Bool) async throws {+ let directory = try TestDirectory()+ defer { await #expect(throws: Never.self) { try await directory.removeAfterClosingHistory() } }+ let state = Mutex(ParentScheduleScenario())+ let initial = ContinuousClock.now+ let clock = Mutex(initial)+ let server = try SharedServerFixture { try Self.serveParentSchedule($0, parentLoaded: parentLoaded, state: state) }+ defer { server.close() }+ var ready = false+ let reader = AppServerActivityReader(+ socketURL: server.url, logStorage: nil,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url),+ reconciliationClock: { clock.withLock { $0 } },+ onBatch: { update in+ if update.phase == .bootstrapEnd {+ ready = true+ }+ }+ )+ defer { await reader.stop() }+ await reader.start()+ try #require(await waitForCondition(timeout: .seconds(5), pollInterval: .milliseconds(10)) { ready })++ func advance(to seconds: Int) async throws {+ let previous = state.withLock { $0.discoveries }+ clock.withLock { $0 = initial.advanced(by: .seconds(seconds)) }+ // 下一轮发现到达时, 上一轮核对及其读取计数已经完成+ try #require(await waitForCondition(timeout: .seconds(6), pollInterval: .milliseconds(10)) {+ state.withLock { $0.discoveries >= previous + 2 }+ })+ }++ // 通过日常发现触发调度, 强制排空和恢复读取会跳过已结束任务的历史依赖+ for seconds in [0, 5, 59, 60] {+ try await advance(to: seconds)+ let expected = seconds == 60 ? 2 : 1+ #expect(state.withLock { $0.reads } == ["parent": expected, "child": expected])+ }+ state.withLock { $0.startsChild = true }+ try await advance(to: 61)+ let child = await reader.lifecycleSnapshot.lifecycleStates(for: [.init(threadID: "child", turnID: "new-child-turn")]).first+ #expect(child?.turnStatus == .running)+ #expect(state.withLock { $0.reads } == ["parent": 2, "child": 2])+ // 父线程仍为 idle, 但运行中的子任务使父关联重新采用快速核对+ try await advance(to: 65)+ #expect(state.withLock { $0.reads } == ["parent": 3, "child": 3])+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)+ #expect(state.withLock { $0.reads } == ["parent": 4, "child": 4])+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)+ #expect(state.withLock { $0.reads } == ["parent": 5, "child": 5])+ #expect(await reader.stop())+ try server.finish()+ }+@Test func missingRolloutDoesNotDisconnectOtherThreadsAndCanRecover() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -164,7 +220,7 @@ struct ActivitySchedulingTests {#expect(tools == 1)#expect(discoveries.withLock { $0 } == 2)if ready, !disconnected {- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)let key = ActivityTaskKey(thread: "a-missing", turn: "turn")#expect(lifecycle.graph.tasks[key]?.lifecycleCoverageCheckedAt != nil)#expect(!lifecycle.graph.unavailableTurns.contains(key))@@ -221,6 +277,71 @@ struct ActivitySchedulingTests {#expect(recorded == 1)}+ private nonisolated struct ParentScheduleScenario {+ var reads: [String: Int] = [:]+ var discoveries = 0+ var startsChild = false+ var childStartedAt: Double?+ let timestamp = Date().addingTimeInterval(-60).timeIntervalSince1970++ func turns(_ id: String) -> [[String: Any]] {+ var result: [[String: Any]] = [[+ "id": id == "parent" ? "root-turn" : "child-turn", "rootTurnId": "root-turn",+ "status": "completed", "startedAt": timestamp, "completedAt": timestamp + 1+ ]]+ if id == "child", let childStartedAt {+ result.insert([+ "id": "new-child-turn", "rootTurnId": "root-turn", "status": "inProgress", "startedAt": childStartedAt+ ], at: 0)+ }+ return result+ }+ }++ private nonisolated static func serveParentSchedule(+ _ peer: SharedServerFixture.Peer, parentLoaded: Bool, state: borrowing Mutex<ParentScheduleScenario>+ ) throws {+ while let request = try? peer.readMessage() {+ let method = request["method"] as? String ?? ""+ let params = request["params"] as? [String: Any] ?? [:]+ let id = params["threadId"] as? String ?? ""+ let snapshot = state.withLock {+ if method == "thread/read" {+ $0.reads[id, default: 0] += 1+ }+ if method == "thread/loaded/list" {+ $0.discoveries += 1+ if $0.startsChild {+ $0.childStartedAt = Date().timeIntervalSince1970+ }+ }+ return $0+ }+ switch method {+ case "initialize": try peer.reply(to: request, result: ["userAgent": "codex/0.165.0"])+ case "initialized": break+ case "thread/loaded/list":+ if snapshot.startsChild {+ try peer.send(["method": "turn/started", "params": ["threadId": "child", "turn": snapshot.turns("child")[0]]])+ state.withLock { $0.startsChild = false }+ }+ try peer.reply(to: request, result: ["data": parentLoaded ? ["parent", "child"] : ["child"]])+ case "thread/read", "thread/resume":+ var thread: [String: Any] = [+ "id": id, "source": "vscode", "status": ["type": id == "child" && snapshot.childStartedAt != nil ? "active" : "idle"]+ ]+ if id == "child" {+ thread["parentThreadId"] = "parent"+ }+ try peer.reply(to: request, result: ["thread": thread])+ case "thread/turns/list":+ #expect(params["itemsView"] as? String == "notLoaded")+ try peer.reply(to: request, result: ["data": snapshot.turns(id)])+ default: Issue.record("Unexpected request: \(method)")+ }+ }+ }+private nonisolated static func serveMissingRollout(_ peer: SharedServerFixture.Peer,timestamp: Double,@@ -341,7 +462,7 @@ extension ActivitySchedulingTests {for _ in 0 ..< 200 where !ready {try await Task.sleep(for: .milliseconds(5))}- #expect(await reader.drainNow().status == .partial)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .partial)let state = await reader.lifecycleSnapshot.lifecycleStates(for: [.init(threadID: "thread", turnID: "turn")]).first#expect(state?.presentation?.summary.waiting != nil)await reader.stop()@@ -389,7 +510,7 @@ extension ActivitySchedulingTests {try await Task.sleep(for: .milliseconds(5))}#expect(ready)- #expect(await reader.drainNow().status == .partial)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .partial)#expect(probe.graph.tasks[.init(thread: "thread", turn: "turn")] == nil)#expect(probe.graph.tasks[.init(thread: "thread", turn: "new-turn")]?.state == .running)#expect(probe.graph.completions.count == 1)@@ -443,7 +564,7 @@ extension ActivitySchedulingTests {try await Task.sleep(for: .milliseconds(5))}for _ in 0 ..< 3 {- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)}for _ in 0 ..< 100 where probe.graph.tasks[.init(thread: "thread", turn: "turn")]?.tokenUsage?.totalTokens != 80 {try await Task.sleep(for: .milliseconds(5))@@ -515,9 +636,9 @@ extension ActivitySchedulingTests {}try #require(ready)let key = ActivityTaskKey(thread: "thread", turn: "turn")- #expect(await reader.drainNow().status == .partial)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .partial)#expect(cache.graph.unavailableTurns.contains(key))- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)#expect(cache.graph.tasks[key] == nil)#expect(cache.graph.completions.count == 1)#expect(cache.graph.recentlyEndedTaskAt[key] != nil)diff --git a/Tests/App/Activity/ActivityTaskTests.swift b/Tests/App/Activity/ActivityTaskTests.swiftindex c708bab..56af751 100644--- a/Tests/App/Activity/ActivityTaskTests.swift+++ b/Tests/App/Activity/ActivityTaskTests.swift@@ -416,7 +416,7 @@ struct ActivityTaskTests {monitor.acceptFixtureGraph(graph, phase: .live, transitions: transitions)#expect(monitor.isProtectionCandidateRelevant(candidate, now: now) == (offset <= 0))monitor.finishProtectionAttempt(task.key, attemptID: attemptID, taskID: task.displayID, notificationWasSubmitted: false)- #expect((monitor.suppressedTasks[task.key] != nil) == (offset <= 0))+ #expect(monitor.suppressedTasks.contains(task.key) == (offset <= 0))#expect(monitor.protectionAttempts.isEmpty)}@@ -454,7 +454,7 @@ struct ActivityTaskTests {)monitor.finishProtectionAttempt(task.key, attemptID: attemptID, taskID: task.displayID, notificationWasSubmitted: false)#expect(monitor.graph.tasks[task.key]?.state == .running)- #expect((monitor.suppressedTasks[task.key] != nil) == (scenario == "unchanged"))+ #expect(monitor.suppressedTasks.contains(task.key) == (scenario == "unchanged"))#expect(monitor.protectionAttempts.isEmpty)}@@ -482,7 +482,7 @@ struct ActivityTaskTests {monitor.protectionSettings.setInactivityDuration(previousDuration)monitor.reconcileProtection(now: hiddenAt, sendsNotification: false)#expect(monitor.graph.tasks[key]?.state == .running)- #expect(monitor.suppressedTasks[key] != nil)+ #expect(monitor.suppressedTasks.contains(key))#expect(monitor.protectionRecords[identifier] != nil)let checkedAt = expiredObservation ? changedAt.addingTimeInterval(-5) : changedAt@@ -491,7 +491,7 @@ struct ActivityTaskTests {monitor.handleProtectionTimingChange()#expect(monitor.graph.tasks[key]?.state == .running)#expect(monitor.protectionRecords[identifier] == nil)- #expect(monitor.suppressedTasks[key] == nil)+ #expect(!monitor.suppressedTasks.contains(key))#expect(monitor.graph.tasks[key]?.lastProgressAt == task.lastProgressAt)#expect(monitor.graph.tasks[key]?.hasFreshLifecycle(at: changedAt) == !expiredObservation)@@ -502,7 +502,7 @@ struct ActivityTaskTests {#expect(monitor.graph.tasks[key]?.state == .running)monitor.reconcileProtection(now: newDeadline, sendsNotification: false)#expect(monitor.graph.tasks[key]?.state == .running)- #expect(monitor.suppressedTasks[key] != nil)+ #expect(monitor.suppressedTasks.contains(key))#expect(monitor.protectionRecords[identifier] != nil)monitor.cancelInactivityCheck()await monitor.protectionPersistenceTask?.valuediff --git a/Tests/App/Activity/ActivityThreadFilteringTests.swift b/Tests/App/Activity/ActivityThreadFilteringTests.swiftnew file mode 100644index 0000000..21685e5--- /dev/null+++ b/Tests/App/Activity/ActivityThreadFilteringTests.swift@@ -0,0 +1,213 @@+import Foundation+import Synchronization+import Testing++struct ActivityThreadFilteringTests {+ @Test(arguments: [false, true])+ func titleThreadsDoNotBlockRecoveryOrProduceActivity(discoveredByNotification: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let requests = Mutex([String: Int]())+ let server = try SharedServerFixture { peer in+ try Self.initialize(peer)+ var discovery = 0+ while let request = try? peer.readMessage() {+ let method = request["method"] as? String ?? ""+ let id = (request["params"] as? [String: Any])?["threadId"] as? String ?? ""+ requests.withLock { $0[method + ":" + id, default: 0] += 1 }+ switch method {+ case "thread/loaded/list":+ discovery += 1+ if discoveredByNotification, discovery == 1 {+ try peer.send(["method": "thread/started", "params": ["thread": Self.thread("title", source: "thread_title")]])+ try Self.sendTitleActivity(peer)+ }+ try peer.reply(to: request, result: ["data": ["title", "normal"]])+ case "thread/read":+ if id == "title" {+ // 在元数据返回前到达的通知也必须随过滤结果丢弃+ try Self.sendTitleActivity(peer)+ }+ try peer.reply(to: request, result: ["thread": Self.thread(id, source: id == "title" ? "thread_title" : "future_source")])+ case "thread/resume":+ if id == "title" {+ try peer.send(["id": #require(request["id"]), "error": ["code": -32600, "message": "no rollout found for thread id title"]])+ } else {+ try peer.reply(to: request, result: ["thread": Self.thread(id, source: "future_source")])+ }+ case "thread/turns/list":+ try peer.reply(to: request, result: ["data": []])+ default:+ Issue.record("Unexpected method: \(method)")+ }+ }+ }+ defer { server.close() }+ var ready = false+ var complete = false+ var disconnected = false+ let probe = ActivityReaderProbe()+ let reader = AppServerActivityReader(+ probe: probe, socketURL: server.url,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url)+ ) { update in+ if update.phase == .bootstrapEnd {+ ready = true+ complete = update.isComplete+ }+ if update.phase == .sourceUnavailable {+ disconnected = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !ready && !disconnected {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(ready)+ #expect(complete)+ for _ in 0 ..< 3 where ready {+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)+ }+ await reader.stop()+ try server.finish()+ #expect(!disconnected)+ #expect(probe.graph.tasks.isEmpty)+ #expect(try directory.historyRecords().isEmpty)+ let counts = requests.withLock { $0 }+ #expect(counts["thread/read:title", default: 0] == (discoveredByNotification ? 0 : 1))+ #expect(counts["thread/resume:title", default: 0] == 0)+ #expect(counts["thread/turns/list:title", default: 0] == 0)+ #expect(counts["thread/resume:normal"] == 1)+ #expect(counts["thread/turns/list:normal"] == 4)+ }++ @Test(arguments: ["missing", "null", "future_source", "THREAD_TITLE"])+ func otherSourcesKeepNormalSubscription(source: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let requests = Mutex([String: Int]())+ let server = try SharedServerFixture { peer in+ try Self.initialize(peer)+ while let request = try? peer.readMessage() {+ let method = request["method"] as? String ?? ""+ requests.withLock { $0[method, default: 0] += 1 }+ switch method {+ case "thread/loaded/list": try peer.reply(to: request, result: ["data": ["normal"]])+ case "thread/read", "thread/resume": try peer.reply(to: request, result: ["thread": Self.thread("normal", source: source)])+ case "thread/turns/list": try peer.reply(to: request, result: ["data": []])+ default: Issue.record("Unexpected method: \(method)")+ }+ }+ }+ defer { server.close() }+ var ready = false+ let reader = AppServerActivityReader(+ probe: ActivityReaderProbe(), socketURL: server.url,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url)+ ) { update in+ if update.phase == .bootstrapEnd {+ ready = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(ready)+ if ready {+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)+ }+ await reader.stop()+ try server.finish()+ #expect(requests.withLock { $0["thread/resume"] } == 1)+ #expect(requests.withLock { $0["thread/turns/list"] } == 2)+ }++ @Test(arguments: [false, true])+ func ignoredThreadIsReconsideredAfterItsLoadingEnds(reconnect: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let stage = Mutex(0)+ let requests = Mutex([String: Int]())+ let server = try SharedServerFixture(connections: reconnect ? 2 : 1) { peer in+ try Self.initialize(peer)+ while let request = try? peer.readMessage() {+ let method = request["method"] as? String ?? ""+ requests.withLock { $0[method, default: 0] += 1 }+ let current = stage.withLock { $0 }+ switch method {+ case "thread/loaded/list":+ try peer.reply(to: request, result: ["data": current == 1 ? [] : ["thread"]])+ case "thread/read", "thread/resume":+ try peer.reply(to: request, result: ["thread": Self.thread("thread", source: current == 0 ? "thread_title" : "future_source")])+ case "thread/turns/list":+ try peer.reply(to: request, result: ["data": []])+ default:+ Issue.record("Unexpected method: \(method)")+ }+ }+ }+ defer { server.close() }+ var ready = false+ let reader = AppServerActivityReader(+ probe: ActivityReaderProbe(), socketURL: server.url,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: directory.url),+ activityDataRecorder: ActivityDataRecorder(directoryURL: directory.url)+ ) { update in+ if update.phase == .bootstrapEnd {+ ready = true+ }+ }+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(ready)+ #expect(requests.withLock { $0["thread/resume", default: 0] } == 0)+ if reconnect {+ await reader.stop()+ stage.withLock { $0 = 2 }+ ready = false+ await reader.start()+ for _ in 0 ..< 200 where !ready {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(ready)+ } else {+ stage.withLock { $0 = 1 }+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)+ stage.withLock { $0 = 2 }+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)+ }+ await reader.stop()+ try server.finish()+ #expect(requests.withLock { $0["thread/read"] } == 2)+ #expect(requests.withLock { $0["thread/resume"] } == 1)+ #expect(requests.withLock { $0["thread/turns/list"] } == 1)+ }++ private nonisolated static func initialize(_ peer: SharedServerFixture.Peer) throws {+ let request = try peer.readMessage()+ try peer.reply(to: request, result: ["userAgent": "codex/0.165.0"])+ _ = try peer.readMessage()+ }++ private nonisolated static func thread(_ id: String, source: String) -> [String: Any] {+ var thread: [String: Any] = ["id": id, "source": "vscode", "status": ["type": "idle"]]+ if source != "missing" {+ thread["threadSource"] = source == "null" ? NSNull() : source+ }+ return thread+ }++ private nonisolated static func sendTitleActivity(_ peer: SharedServerFixture.Peer) throws {+ try peer.send(["method": "turn/started", "params": [+ "threadId": "title", "turn": ["id": "title-turn", "status": "inProgress", "startedAt": Date().timeIntervalSince1970]+ ]])+ try peer.send(["method": "thread/tokenUsage/updated", "params": [+ "threadId": "title", "turnId": "title-turn", "tokenUsage": ["total": ["totalTokens": 10], "last": ["totalTokens": 10]]+ ]])+ }+}diff --git a/Tests/App/Activity/ActivityUpdateTests.swift b/Tests/App/Activity/ActivityUpdateTests.swiftindex 3eea810..cc876e2 100644--- a/Tests/App/Activity/ActivityUpdateTests.swift+++ b/Tests/App/Activity/ActivityUpdateTests.swift@@ -256,26 +256,30 @@ struct ActivityUpdateTests {try await Task.sleep(for: .milliseconds(5))}try #require(ready)- let first = Task { await reader.drainNow() }+ let firstRecovery = UUID()+ let first = Task { await reader.drainForRecovery(generation: firstRecovery) }for _ in 0 ..< 200 where !entered.withLock({ $0 }) {try await Task.sleep(for: .milliseconds(5))}try #require(entered.withLock { $0 })- let second = Task { await reader.drainNow() }+ let secondRecovery = UUID()+ let second = Task { await reader.drainForRecovery(generation: secondRecovery) }try await Task.sleep(for: .milliseconds(20))release.signal()let firstResult = await first.valuelet secondResult = await second.value#expect(firstResult.status == .completed)#expect(secondResult.status == .completed)- if case let .completed(a) = firstResult, case let .completed(b) = secondResult {+ if case let .update(a) = firstResult, case let .update(b) = secondResult {#expect(a.readerID == b.readerID && a.revision < b.revision)+ #expect(a.recoveryID == firstRecovery)+ #expect(b.recoveryID == secondRecovery)#expect(a.graph.tasks.keys.map(\.turnID) == ["turn-2"])#expect(b.graph.tasks.keys.map(\.turnID) == ["turn-3"])#expect(published.contains { $0.readerID == b.readerID && $0.revision == b.revision })}#expect(await reader.stop())- #expect(await reader.drainNow().status == .cancelled)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .cancelled)try server.finish()}@@ -371,7 +375,9 @@ struct ActivityUpdateTests {let now = Date()monitor.isActivitySourceHealthy = scenario != "unavailable"monitor.isBootstrapping = scenario == "bootstrap"- monitor.isProtectionRecoveryInProgress = scenario == "recovery"+ if scenario == "recovery" {+ monitor.beginProtectionRecovery()+ }monitor.turnTransitionNotBefore = now.addingTimeInterval(scenario == "before-cutoff" ? 0 : -60)var reducer = try approvalReducer(at: now)var graph = ActivityTaskGraph()@@ -444,7 +450,8 @@ struct ActivityUpdateTests {graph: graph,transitions: transitions,terminalEvents: graph.terminalEvents,- backfilledTasks: graph.backfilledTasks+ backfilledTasks: graph.backfilledTasks,+ recoveryID: readerID)}}diff --git a/Tests/App/Activity/AppServerActivityTests.swift b/Tests/App/Activity/AppServerActivityTests.swiftindex 71d4439..956df37 100644--- a/Tests/App/Activity/AppServerActivityTests.swift+++ b/Tests/App/Activity/AppServerActivityTests.swift@@ -388,53 +388,6 @@ struct AppServerActivityTests {#expect(stored.count == 1)}- @Test func incrementalTokenStorageRetainsAllCountersAcrossRestart() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let store = TokenUsageHistoryStore(directoryURL: directory.url)- let tokenUsage = TokenUsage(- inputTokens: 100,- cachedInputTokens: 50,- cacheWriteInputTokens: 10,- outputTokens: 20,- reasoningOutputTokens: 5,- totalTokens: 120- )- let observation = TestFixtures.tokenUsageObservation(- id: "stream", at: now, tokenUsage: tokenUsage- )- _ = try await store.recordObservations([observation, observation], now: now)- let restarted = TokenUsageHistoryStore(directoryURL: directory.url)- let records = try await restarted.refresh(now: now)- #expect(records.count == 1)- #expect(records.first?.tokenUsage == tokenUsage)- }-- @Test func rebuildUsesObservedRecordsAndContinuesCollecting() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let store = TokenUsageHistoryStore(directoryURL: directory.url)- let tokenUsage = TokenUsage(- inputTokens: 100,- cachedInputTokens: 30,- cacheWriteInputTokens: 10,- outputTokens: 20,- reasoningOutputTokens: 5,- totalTokens: 120- )- let first = TestFixtures.tokenUsageObservation(id: "stream", at: now, tokenUsage: tokenUsage)- _ = try await store.recordObservations([first], now: now)- let rebuilt = try await store.rebuild(for: [CodexDateFormat.dayString(from: now)])- #expect(rebuilt.eventCount == 1)- let second = TestFixtures.tokenUsageObservation(- id: "second", at: now,- tokenUsage: tokenUsage- )- _ = try await store.recordObservations([second], now: now.addingTimeInterval(2))- let records = try await store.refresh(now: now.addingTimeInterval(2))- #expect(records.first?.tokenUsage == tokenUsage.adding(tokenUsage))- }-@Test func multipleApprovalRequestsResolveIndependently() throws {var reducer = try prepared()let event = TestFixtures.event(at: now, thread: "main", turn: "turn")diff --git a/Tests/App/Activity/ProtectionRecoveryTests.swift b/Tests/App/Activity/ProtectionRecoveryTests.swiftindex b7e56f4..2b203d5 100644--- a/Tests/App/Activity/ProtectionRecoveryTests.swift+++ b/Tests/App/Activity/ProtectionRecoveryTests.swift@@ -12,11 +12,11 @@ struct ProtectionRecoveryTests {let monitor = makeMonitor(directory: directory, preferences: preferences)monitor.isStarted = truemonitor.loadProtectionState()- try await wait { monitor.protectionLoadState == .blocked }+ #expect(try await waitForCondition(timeout: .seconds(2), pollInterval: .milliseconds(10)) { monitor.protectionLoadState == .blocked })#expect(!monitor.isProtectionStoreAvailable)try FileManager.default.removeItem(at: bad)monitor.setProtectionEnabled(true)- try await wait { monitor.isProtectionStoreAvailable }+ #expect(try await waitForCondition(timeout: .seconds(2), pollInterval: .milliseconds(10)) { monitor.isProtectionStoreAvailable })#expect(monitor.isProtectionRecoveryInProgress)monitor.stop()}@@ -31,9 +31,9 @@ struct ProtectionRecoveryTests {let monitor = makeMonitor(directory: directory, preferences: preferences)monitor.isStarted = truemonitor.loadProtectionState()- try await wait { monitor.protectionLoadState == .retryableFailure }+ #expect(try await waitForCondition(timeout: .seconds(2), pollInterval: .milliseconds(10)) { monitor.protectionLoadState == .retryableFailure })try FileManager.default.removeItem(at: path)- try await wait { monitor.isProtectionStoreAvailable }+ #expect(try await waitForCondition(timeout: .seconds(2), pollInterval: .milliseconds(10)) { monitor.isProtectionStoreAvailable })monitor.stop()monitor.protectionLoadState = .idlemonitor.isStarted = true@@ -58,14 +58,4 @@ struct ProtectionRecoveryTests {monitor.isBootstrapping = truereturn monitor}-- private func wait(until condition: () -> Bool) async throws {- for _ in 0 ..< 200 {- if condition() {- return- }- try await Task.sleep(for: .milliseconds(10))- }- #expect(condition())- }}diff --git a/Tests/App/Activity/TurnTokenCumulativeTests.swift b/Tests/App/Activity/TurnTokenCumulativeTests.swiftindex d378e3e..9357e6f 100644--- a/Tests/App/Activity/TurnTokenCumulativeTests.swift+++ b/Tests/App/Activity/TurnTokenCumulativeTests.swift@@ -1,16 +1,6 @@import Foundationimport Testing-extension TestFixtures {- static func tokenUsage(_ total: Int64) -> TokenUsage {- TokenUsage(inputTokens: total, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: total)- }-- static func tokenSample(_ total: Int64, thread: String = "main", turn: String = "root", at: Date = now, start: Date? = nil) -> TokenUsageSample {- TokenUsageSample(observedAt: at, threadID: thread, turnID: turn, turnStartedAt: start, current: TokenUsageUpdate(total: tokenUsage(total), last: tokenUsage(1)))- }-}-struct TurnTokenCumulativeTests {private let now = TestFixtures.nowdiff --git a/Tests/App/AppServer/AppServerLogTests.swift b/Tests/App/AppServer/AppServerLogTests.swiftindex b386dea..1d65f37 100644--- a/Tests/App/AppServer/AppServerLogTests.swift+++ b/Tests/App/AppServer/AppServerLogTests.swift@@ -14,6 +14,8 @@ struct AppServerLogTests {_ = try await storage.page()#expect(try !directory.openFilePaths().isEmpty)storage.recordFailure(message: "queued before cleanup")+ let requestID = storage.beginRequest(method: "last", payload: "{}")+ storage.finishRequest(requestID, response: "saved")try await storage.close()try await storage.close()#expect(try directory.openFilePaths().isEmpty)@@ -26,7 +28,9 @@ struct AppServerLogTests {let reopened = AppServerLogStore(directoryURL: directory.url)defer { await #expect(throws: Never.self) { try await reopened.close() } }let page = try await reopened.page()- #expect(page.entries.map(\.detail) == ["queued before cleanup", "before cleanup"])+ #expect(page.total == 3)+ #expect(page.entries.first { $0.id == requestID }?.detail == "saved")+ #expect(page.entries.filter { $0.id != requestID }.map(\.detail) == ["queued before cleanup", "before cleanup"])}@Test func closePersistsSkippedWriteCountBeforeReleasingConnection() async throws {@@ -408,22 +412,6 @@ struct AppServerLogTests {#expect(store.entries.count == 1)}- @Test func terminationDrainsQueuedWritesAndRejectsLateCallbacks() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let storage = AppServerLogStore(directoryURL: directory.url)- defer { await #expect(throws: Never.self) { try await storage.close() } }- let id = storage.beginRequest(method: "last", payload: "{}")- storage.finishRequest(id, response: "saved")- try await storage.close()- storage.recordFailure(message: "after shutdown")- let reopened = AppServerLogStore(directoryURL: directory.url)- defer { await #expect(throws: Never.self) { try await reopened.close() } }- let page = try await reopened.page()- #expect(page.total == 1)- #expect(page.entries.first?.detail == "saved")- }-@Test func storageFailureIsVisibleAndDoesNotBreakRequestRecordingCallers() async throws {let directory = try TestDirectory()defer { try? directory.remove() }diff --git a/Tests/App/AppServer/AppServerSessionTests.swift b/Tests/App/AppServer/AppServerSessionTests.swiftindex 273d0d1..f7a817c 100644--- a/Tests/App/AppServer/AppServerSessionTests.swift+++ b/Tests/App/AppServer/AppServerSessionTests.swift@@ -214,7 +214,7 @@ struct AppServerSessionTests {if supported {#expect(bootstrapped)for _ in 0 ..< 3 {- #expect(await reader.drainNow().status == .completed)+ #expect(await reader.drainForRecovery(generation: UUID()).status == .completed)}#expect(!disconnected)} else {diff --git a/Tests/App/CodexStatus/AccountNotificationTests.swift b/Tests/App/CodexStatus/AccountNotificationTests.swiftindex 8b23ef5..2e83da0 100644--- a/Tests/App/CodexStatus/AccountNotificationTests.swift+++ b/Tests/App/CodexStatus/AccountNotificationTests.swift@@ -106,15 +106,15 @@ struct AccountNotificationTests {let service = CodexStatusService(socketURL: server.url, logStorage: nil)let model = CodexStatusViewModel(service: service, defaults: defaults)model.startAutoRefresh()- try await eventually { model.loadState == .notLoggedIn && !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) { model.loadState == .notLoggedIn && !model.isRefreshing })let maintenanceClock = model.autoRefreshCountdownStartedAt#expect(await service.currentConnectionInfo()?.version == "0.162.0")login.signal()- try await eventually { model.snapshot != nil && !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) { model.snapshot != nil && !model.isRefreshing })#expect(model.lastRefreshTrigger == .accountNotification)#expect(model.autoRefreshCountdownStartedAt == maintenanceClock)logout.signal()- try await eventually { model.loadState == .notLoggedIn && !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) { model.loadState == .notLoggedIn && !model.isRefreshing })#expect(model.snapshot == nil)#expect(model.autoRefreshCountdownStartedAt == maintenanceClock)#expect(await service.currentConnectionInfo()?.version == "0.162.0")@@ -148,15 +148,15 @@ struct AccountNotificationTests {defer { defaults.removePersistentDomain(forName: suite) }let model = CodexStatusViewModel(service: CodexStatusService(socketURL: server.url, logStorage: nil), defaults: defaults)model.refresh(trigger: .manual)- try await eventually { entered.withLock { $0 } }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) { entered.withLock { $0 } })for _ in 0 ..< 20 {model.receiveAccountChange(.rateLimits)model.receiveAccountChange(.account)}respond.signal()- try await eventually { !model.isRefreshing && model.autoRefreshCountdownStartedAt != nil }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) { !model.isRefreshing && model.autoRefreshCountdownStartedAt != nil })let maintenanceClock = model.autoRefreshCountdownStartedAt- try await eventually { model.lastRefreshTrigger == .accountNotification && !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) { model.lastRefreshTrigger == .accountNotification && !model.isRefreshing })#expect(model.autoRefreshCountdownStartedAt == maintenanceClock)#expect(model.loadState == .notLoggedIn)release.signal()@@ -207,7 +207,7 @@ struct AccountNotificationTests {onBatch: { updates.append($0) })await reader.start()- try await eventually { changes.contains(.account) }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) { changes.contains(.account) })await reader.stop()#expect(!updates.isEmpty)#expect(updates.allSatisfy {@@ -219,367 +219,5 @@ struct AccountNotificationTests {try server.finish()}- private func eventually(_ condition: () -> Bool) async throws {- for _ in 0 ..< 300 {- if condition() {- return- }- try await Task.sleep(for: .milliseconds(10))- }- Issue.record("Condition was not reached")- }-private nonisolated struct Value: Decodable { let value: Int }}--extension AccountNotificationTests {- @Test(arguments: ["business", "unsupported", "invalidPayload"], [false, true])- func supplementalFailurePreservesCacheAndUnsupportedMethodPolicy(failure: String, hasCache: Bool) async throws {- let server = try SharedServerFixture { peer in- let initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])- _ = try peer.readMessage()- let rounds = hasCache ? 2 : 1- for round in 0 ..< rounds {- let account = try peer.readMessage()- #expect(account["method"] as? String == "account/read")- try peer.reply(to: account, result: ["account": ["type": "apiKey"]])- let fails = round == rounds - 1- for method in ["account/rateLimits/read", "account/usage/read"] {- let attempts = fails && failure == "business" && method == "account/rateLimits/read" ? 2 : 1- for _ in 0 ..< attempts {- let request = try peer.readMessage()- #expect(request["method"] as? String == method)- if !fails {- let result: [String: Any] = method == "account/rateLimits/read"- ? ["rateLimits": [:], "ordinaryUsageAllowed": true]- : ["summary": ["lifetimeTokens": 123], "dailyUsageBuckets": []]- try peer.reply(to: request, result: result)- } else if failure == "invalidPayload" {- try peer.reply(to: request, result: [:])- } else {- try peer.send(["id": #require(request["id"]), "error": [- "code": failure == "unsupported" ? -32601 : -32000,- "message": failure == "unsupported" ? "unsupported" : "upstream network request failed"- ]])- }- }- }- }- }- defer { server.close() }- let service = CodexStatusService(socketURL: server.url, logStorage: nil)- if hasCache {- guard case .data = await service.fetchOutcome().outcome else {- Issue.record("Initial read did not populate the cache")- return- }- }- let result = await service.fetchOutcome()- guard case let .data(snapshot) = result.outcome else {- Issue.record("Supplemental failure discarded the account snapshot")- return- }- let usesCache = hasCache && failure != "unsupported"- let step: CodexFetchTrace.StepResult = failure == "unsupported" ? .skipped : (usesCache ? .cached : .failed)- #expect(result.trace.rateLimits == step && result.trace.usage == step)- #expect(result.trace.failureStage == nil)- #expect(snapshot.isRateLimitsStale == usesCache && snapshot.isUsageStale == usesCache)- #expect(snapshot.ordinaryUsageAllowed == (usesCache ? true : nil))- #expect(snapshot.usage?.summary.lifetimeTokens == (usesCache ? 123 : nil))- try server.finish()- }-- @Test(arguments: ["account/rateLimits/read", "account/usage/read"], ["none", "account/rateLimits/read", "account/usage/read"])- func accountChangeDuringAuthRefreshDiscardsOldData(authMethod: String, failedRead: String) async throws {- let server = try SharedServerFixture { peer in- func respond(_ method: String, _ result: [String: Any]) throws {- let request = try peer.readMessage()- try #require(request["method"] as? String == method)- try peer.reply(to: request, result: result)- }- try respond("initialize", ["userAgent": "codex/0.162.0"])- _ = try peer.readMessage()- let firstAccount: [String: Any] = ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]]- let secondAccount: [String: Any] = ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]]- try respond("account/read", firstAccount)- try respond("account/rateLimits/read", ["rateLimits": [:], "ordinaryUsageAllowed": true])- try respond("account/usage/read", ["summary": ["lifetimeTokens": 123]])- try respond("account/read", firstAccount)- if authMethod == "account/usage/read" {- try respond("account/rateLimits/read", ["rateLimits": [:], "ordinaryUsageAllowed": true])- }- let unauthorized = try peer.readMessage()- try #require(unauthorized["method"] as? String == authMethod)- try peer.send(["id": #require(unauthorized["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])- let refresh = try peer.readMessage()- try #require(refresh["method"] as? String == "account/read")- #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)- try peer.reply(to: refresh, result: secondAccount)- try respond("account/rateLimits/read", failedRead == "account/rateLimits/read" ? [:] : ["rateLimits": [:], "ordinaryUsageAllowed": false])- try respond("account/usage/read", failedRead == "account/usage/read" ? [:] : ["summary": ["lifetimeTokens": 456]])- try respond("account/read", secondAccount)- try respond("account/rateLimits/read", [:])- try respond("account/usage/read", [:])- }- defer { server.close() }- let service = CodexStatusService(socketURL: server.url, logStorage: nil)- guard case .data = await service.fetchOutcome().outcome else {- Issue.record("Initial read did not populate the cache")- return- }- let result = await service.fetchOutcome()- guard case let .data(snapshot) = result.outcome else {- Issue.record("Account change did not restart supplemental reads")- return- }- #expect(snapshot.account.email == "[email protected]")- #expect(snapshot.ordinaryUsageAllowed == (failedRead == "account/rateLimits/read" ? nil : false))- #expect(snapshot.usage?.summary.lifetimeTokens == (failedRead == "account/usage/read" ? nil : 456))- #expect(!snapshot.isRateLimitsStale && !snapshot.isUsageStale)- #expect(result.trace.account == .refreshed)- #expect(result.trace.rateLimits == (failedRead == "account/rateLimits/read" ? .failed : .ok))- #expect(result.trace.usage == (failedRead == "account/usage/read" ? .failed : .ok))- guard case let .data(cached) = await service.fetchOutcome().outcome else {- Issue.record("New account cache was unavailable")- return- }- #expect(cached.account == snapshot.account)- #expect(cached.ordinaryUsageAllowed == snapshot.ordinaryUsageAllowed)- #expect(cached.usage?.summary.lifetimeTokens == snapshot.usage?.summary.lifetimeTokens)- #expect(cached.isRateLimitsStale == (failedRead != "account/rateLimits/read"))- #expect(cached.isUsageStale == (failedRead != "account/usage/read"))- try server.finish()- }-- @Test(arguments: ["account/rateLimits/read", "account/usage/read"])- func accountChangeDoesNotRenewAuthenticationBudget(authMethod: String) async throws {- let server = try SharedServerFixture { peer in- try peer.reply(to: peer.readMessage(), result: ["userAgent": "codex/0.162.0"])- _ = try peer.readMessage()- try peer.reply(to: peer.readMessage(), result: ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]])- if authMethod == "account/usage/read" {- try peer.reply(to: peer.readMessage(), result: ["rateLimits": [:], "ordinaryUsageAllowed": true])- }- let unauthorized = try peer.readMessage()- try #require(unauthorized["method"] as? String == authMethod)- let error: [String: Any] = ["code": -32000, "message": "codex account authentication required"]- try peer.send(["id": #require(unauthorized["id"]), "error": error])- let refresh = try peer.readMessage()- try #require(refresh["method"] as? String == "account/read")- #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)- try peer.reply(to: refresh, result: ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]])- let retried = try peer.readMessage()- try #require(retried["method"] as? String == "account/rateLimits/read")- try peer.send(["id": #require(retried["id"]), "error": error])- }- defer { server.close() }- let result = await CodexStatusService(socketURL: server.url, logStorage: nil).fetchOutcome()- guard case .authenticationRequired = result.outcome else {- Issue.record("Account change renewed the authentication budget")- return- }- #expect(result.trace.account == .refreshed)- #expect(result.trace.failureStage == .snapshot)- #expect(result.trace.rateLimits == nil && result.trace.usage == nil && result.trace.resetCredits == nil)- try server.finish()- }-- @Test(arguments: [false, true])- func quotaReadsShareOneAuthenticationRefreshBudget(repeatsOnSameMethod: Bool) async throws {- let server = try SharedServerFixture { peer in- let initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])- _ = try peer.readMessage()- let account = try peer.readMessage()- try peer.reply(to: account, result: ["account": ["type": "apiKey"]])- let limits = try peer.readMessage()- #expect(limits["method"] as? String == "account/rateLimits/read")- try peer.send(["id": #require(limits["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])- let refresh = try peer.readMessage()- #expect(refresh["method"] as? String == "account/read")- #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)- try peer.reply(to: refresh, result: ["account": ["type": "apiKey"]])- let retried = try peer.readMessage()- #expect(retried["method"] as? String == "account/rateLimits/read")- let secondFailure: [String: Any]- if repeatsOnSameMethod {- secondFailure = retried- } else {- try peer.reply(to: retried, result: ["rateLimits": [:]])- secondFailure = try peer.readMessage()- #expect(secondFailure["method"] as? String == "account/usage/read")- }- try peer.send(["id": #require(secondFailure["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])- }- defer { server.close() }- let result = await CodexStatusService(socketURL: server.url, logStorage: nil).fetchOutcome()- guard case .authenticationRequired = result.outcome else {- Issue.record("Repeated authentication failure was not propagated")- return- }- #expect(result.trace.failureStage == .snapshot)- #expect(result.trace.rateLimits == (repeatsOnSameMethod ? nil : .ok))- #expect(result.trace.usage == nil)- try server.finish()- }-- @Test(arguments: [- ("serverError", true), ("invalidPayload", true), ("signedOut", true),- ("signedOut", false), ("authentication", false), ("serverError", false),- ("invalidPayload", false), ("connectionClosed", false)- ])- func authenticationRefreshFailurePreservesOutcomeAndRejectsCache(failure: String, hasCache: Bool) async throws {- let server = try SharedServerFixture { peer in- let initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])- _ = try peer.readMessage()- let rounds = hasCache ? 2 : 1- for round in 0 ..< rounds {- let account = try peer.readMessage()- #expect(account["method"] as? String == "account/read")- try peer.reply(to: account, result: ["account": ["type": "apiKey"]])- let limits = try peer.readMessage()- #expect(limits["method"] as? String == "account/rateLimits/read")- if round < rounds - 1 {- try peer.reply(to: limits, result: ["rateLimits": [:], "ordinaryUsageAllowed": true])- let usage = try peer.readMessage()- #expect(usage["method"] as? String == "account/usage/read")- try peer.reply(to: usage, result: ["summary": ["lifetimeTokens": 123]])- } else {- try peer.send(["id": #require(limits["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])- for _ in 0 ..< (failure == "serverError" ? 2 : 1) {- let refresh = try peer.readMessage()- #expect(refresh["method"] as? String == "account/read")- #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)- switch failure {- case "signedOut": try peer.reply(to: refresh, result: ["account": NSNull()])- case "invalidPayload": try peer.reply(to: refresh, result: [:])- case "connectionClosed": return- default:- try peer.send(["id": #require(refresh["id"]), "error": [- "code": -32000, "message": failure == "authentication" ? "codex account authentication required" : "upstream network request failed"- ]])- }- }- }- }- }- defer { server.close() }- let service = CodexStatusService(socketURL: server.url, logStorage: nil)- if hasCache {- guard case .data = await service.fetchOutcome().outcome else {- Issue.record("Initial read did not populate the cache")- return- }- }- let result = await service.fetchOutcome()- #expect(result.trace.rateLimits == nil && result.trace.usage == nil)- #expect(result.trace.failureStage == .snapshot)- if !hasCache {- #expect(result.trace.connection == .new)- }- switch result.outcome {- case .notLoggedIn: #expect(failure == "signedOut")- case .authenticationRequired: #expect(failure == "authentication")- case .initializationFailed: #expect(["serverError", "invalidPayload", "connectionClosed"].contains(failure))- default: Issue.record("Authentication refresh failure was hidden or misclassified")- }- try server.finish()- }-- @Test(arguments: ["authentication", "invalidPayload", "unsupportedVersion"], [false, true])- func connectionFailurePreservesFetchStageAndOperationError(failure: String, readsConfiguration: Bool) async throws {- let server = try SharedServerFixture { peer in- let initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": failure == "unsupportedVersion" ? "codex/0.161.0" : "codex/0.162.0"])- guard failure != "unsupportedVersion" else { return }- #expect(try peer.readMessage()["method"] as? String == "initialized")- let account = try peer.readMessage()- #expect(account["method"] as? String == "account/read")- if failure == "authentication" {- try peer.send(["id": #require(account["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])- } else {- try peer.reply(to: account, result: [:])- }- }- defer { server.close() }- let service = CodexStatusService(socketURL: server.url, logStorage: nil)- if readsConfiguration {- do {- _ = try await service.areTUINotificationsEnabled()- Issue.record("Configuration read accepted an uninitialized connection")- } catch let error as CodexStatusError {- switch error {- case .authenticationRequired: #expect(failure == "authentication")- case .unsupportedVersion: #expect(failure == "unsupportedVersion")- case .serverConnectionClosed: #expect(failure == "invalidPayload")- default: Issue.record("Unexpected connection error")- }- }- } else {- let result = await service.fetchOutcome()- switch result.outcome {- case .authenticationRequired: #expect(failure == "authentication")- case .unsupportedVersion: #expect(failure == "unsupportedVersion")- case .initializationFailed: #expect(failure == "invalidPayload")- default: Issue.record("Unexpected fetch outcome")- }- #expect(result.trace.failureStage == (failure == "authentication" ? .account : .connect))- #expect(result.trace.connection == nil)- }- #expect(await service.currentConnectionInfo() == nil)- try server.finish()- }-- @Test func autoResetAuthenticationRetryKeepsCreditIdentityAndFreshAccountCheck() async throws {- let server = try SharedServerFixture { peer in- let initialize = try peer.readMessage()- try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])- #expect(try peer.readMessage()["method"] as? String == "initialized")- for refreshToken in [false, false] {- let account = try peer.readMessage()- #expect(account["method"] as? String == "account/read")- #expect((account["params"] as? [String: Any])?["refreshToken"] as? Bool == refreshToken)- try peer.reply(to: account, result: ["account": ["type": "apiKey"]])- }- let first = try peer.readMessage()- #expect(first["method"] as? String == "account/rateLimitResetCredit/consume")- try peer.send(["id": #require(first["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])- for refreshToken in [true, false] {- let account = try peer.readMessage()- #expect(account["method"] as? String == "account/read")- #expect((account["params"] as? [String: Any])?["refreshToken"] as? Bool == refreshToken)- try peer.reply(to: account, result: ["account": ["type": "apiKey"]])- }- let retried = try peer.readMessage()- #expect(retried["method"] as? String == "account/rateLimitResetCredit/consume")- for request in [first, retried] {- let params = try #require(request["params"] as? [String: String])- #expect(params == ["creditId": "credit", "idempotencyKey": "same-key"])- }- try peer.reply(to: retried, result: ["outcome": "reset"])- let account = try peer.readMessage()- #expect(account["method"] as? String == "account/read")- try peer.reply(to: account, result: ["account": ["type": "apiKey"]])- let limits = try peer.readMessage()- #expect(limits["method"] as? String == "account/rateLimits/read")- try peer.reply(to: limits, result: ["rateLimits": [:], "rateLimitResetCredits": ["availableCount": 0, "credits": []]])- }- defer { server.close() }- let service = CodexStatusService(socketURL: server.url, logStorage: nil)- let result = try await service.consumeResetCredit(- id: "credit", idempotencyKey: "same-key", expectedAccountIdentity: "apiKey\u{0}",- expirationDate: Date().addingTimeInterval(600),- budget: AppServerRequestBudget(deadline: Date().addingTimeInterval(5))- )- #expect(result.outcome == .reset)- #expect(result.refreshedRead?.availableCount == 0)- try server.finish()- }-- @Test func missingAccountFieldIsNotSignedOut() throws {- #expect(throws: DecodingError.self) { try TestFixtures.decode(AccountReadResponse.self, "{}") }- #expect(try TestFixtures.decode(AccountReadResponse.self, "{\"account\":null}").account == nil)- }-}diff --git a/Tests/App/CodexStatus/AutoResetControllerTests.swift b/Tests/App/CodexStatus/AutoResetControllerTests.swiftindex b674a9a..79132dc 100644--- a/Tests/App/CodexStatus/AutoResetControllerTests.swift+++ b/Tests/App/CodexStatus/AutoResetControllerTests.swift@@ -14,7 +14,9 @@ struct AutoResetControllerTests {try fixture.outcomes.send(.data(fixture.snapshot()))for (index, offset) in [0.0, 15, 45, 105, 225].enumerated() {fixture.clock.advance(to: fixture.start.addingTimeInterval(offset))- try await eventually { fixture.controller.scheduledDate != nil && fixture.state.readCount >= index + 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) {+ fixture.controller.scheduledDate != nil && fixture.state.readCount >= index + 1+ })for _ in 0 ..< 10 {try fixture.outcomes.send(.data(fixture.snapshot()))}@@ -35,7 +37,7 @@ struct AutoResetControllerTests {let newConsume = ResetGate<ResetCreditConsumeResult>()fixture.state.readOverride = { await oldRead.wait() }fixture.controller.start()- try await eventually { fixture.state.readCount == 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.readCount == 1 })#expect(fixture.state.activeAssertions.count == 1)fixture.settings.setEnabled(false)fixture.state.readOverride = nil@@ -44,11 +46,11 @@ struct AutoResetControllerTests {await settle()#expect(fixture.state.readCount == 1)oldRead.release(fixture.state.read)- try await eventually { fixture.state.consumeCount == 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.consumeCount == 1 })#expect(fixture.state.createdAssertions == 2)#expect(fixture.state.activeAssertions == [2])newConsume.release(ResetCreditConsumeResult(outcome: .nothingToReset, refreshedRead: fixture.state.read))- try await eventually { fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.activeAssertions.isEmpty })#expect(fixture.state.releasedAssertions == [1, 2])}@@ -58,15 +60,15 @@ struct AutoResetControllerTests {let consume = ResetGate<ResetCreditConsumeResult>()fixture.state.consumeOverride = { await consume.wait() }fixture.controller.start()- try await eventually { fixture.state.consumeCount == 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.consumeCount == 1 })fixture.settings.setEnabled(false)consume.release(ResetCreditConsumeResult(outcome: .reset, refreshedRead: fixture.state.read))- try await eventually { fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.activeAssertions.isEmpty })#expect(fixture.state.successes == 1)#expect(fixture.controller.scheduledDate == nil)#expect(fixture.controller.wakeDate == nil)fixture.settings.setEnabled(true)- try await eventually { fixture.state.readCount >= 2 && fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.readCount >= 2 && fixture.state.activeAssertions.isEmpty })#expect(fixture.state.consumeCount == 1)}@@ -74,7 +76,7 @@ struct AutoResetControllerTests {let fixture = try ResetFixture()defer { fixture.stop() }fixture.controller.start()- try await eventually { fixture.controller.scheduledDate != nil }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.controller.scheduledDate != nil })#expect(fixture.controller.scheduledDate == fixture.start.addingTimeInterval(300))#expect(fixture.controller.wakeDate == fixture.start.addingTimeInterval(720))fixture.controller.handleSleep()@@ -83,7 +85,7 @@ struct AutoResetControllerTests {#expect(fixture.state.consumeCount == 1)#expect(fixture.controller.scheduledDate == nil)fixture.controller.handleWake()- try await eventually { fixture.state.consumeCount == 2 && fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.consumeCount == 2 && fixture.state.activeAssertions.isEmpty })#expect(fixture.controller.scheduledDate == nil)#expect(fixture.controller.wakeDate == nil)for _ in 0 ..< 10 {@@ -98,7 +100,7 @@ struct AutoResetControllerTests {defer { fixture.stop() }fixture.clock.advance(to: fixture.expiration.addingTimeInterval(-50))fixture.controller.start()- try await eventually { fixture.state.readCount == 1 && fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.readCount == 1 && fixture.state.activeAssertions.isEmpty })#expect(fixture.state.consumeCount == 0)#expect(fixture.controller.scheduledDate == nil)}@@ -110,13 +112,13 @@ struct AutoResetControllerTests {fixture.state.readOverride = { await gate.wait() }try fixture.outcomes.send(.data(fixture.snapshot()))fixture.controller.start()- try await eventually { fixture.state.readCount == 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.readCount == 1 })fixture.controller.handleSleep()fixture.clock.advance(to: fixture.start.addingTimeInterval(730))fixture.state.readOverride = nilfixture.controller.handleWake()gate.release(fixture.state.read)- try await eventually { fixture.state.consumeCount == 1 && fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.consumeCount == 1 && fixture.state.activeAssertions.isEmpty })#expect(fixture.controller.scheduledDate == nil)}@@ -124,7 +126,7 @@ struct AutoResetControllerTests {let fixture = try ResetFixture()defer { fixture.stop() }fixture.controller.start()- try await eventually { fixture.controller.scheduledDate != nil }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.controller.scheduledDate != nil })fixture.controller.prepareForTermination()fixture.clock.advance(to: fixture.start.addingTimeInterval(400))try fixture.outcomes.send(.data(fixture.snapshot()))@@ -132,7 +134,7 @@ struct AutoResetControllerTests {#expect(fixture.state.consumeCount == 1)#expect(fixture.controller.wakeDate == nil)fixture.controller.resumeAfterTerminationCancellation()- try await eventually { fixture.state.consumeCount == 2 && fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.consumeCount == 2 && fixture.state.activeAssertions.isEmpty })}@Test(arguments: [false, true])@@ -144,12 +146,12 @@ struct AutoResetControllerTests {try fixture.outcomes.send(.data(fixture.snapshot()))fixture.state.readOverride = { await gate.wait() }fixture.controller.start()- try await eventually { fixture.state.readCount == 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.readCount == 1 })fixture.state.account = CodexAccount(type: "chatgpt", email: "[email protected]", planType: "plus")fixture.state.readOverride = niltry fixture.outcomes.send(.data(fixture.snapshot(isStale: stale)))gate.release(old)- try await eventually { fixture.state.consumeCount == 1 && fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.consumeCount == 1 && fixture.state.activeAssertions.isEmpty })#expect(fixture.state.consumedAccounts == [AutoResetIdentity.accountIdentity(for: fixture.state.account)])}@@ -161,28 +163,28 @@ struct AutoResetControllerTests {try fixture.outcomes.send(.data(fixture.snapshot()))fixture.state.readOverride = { await gate.wait() }fixture.controller.start()- try await eventually { fixture.state.readCount == 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.readCount == 1 })#expect(fixture.controller.wakeDate != nil)fixture.outcomes.send(signedOut ? .notLoggedIn : .authenticationRequired)#expect(fixture.controller.wakeDate == nil)#expect(fixture.controller.scheduledDate == nil)fixture.controller.handleWake()gate.release(fixture.state.read)- try await eventually { fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.activeAssertions.isEmpty })#expect(fixture.state.consumeCount == 0)#expect(fixture.controller.wakeDate == nil)fixture.state.readOverride = niltry fixture.outcomes.send(.data(fixture.snapshot()))let retry = try #require(fixture.controller.scheduledDate)fixture.clock.advance(to: retry)- try await eventually { fixture.state.consumeCount == 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.consumeCount == 1 })}@Test func failedAccountReadPreservesExistingPlan() async throws {let fixture = try ResetFixture()defer { fixture.stop() }fixture.controller.start()- try await eventually { fixture.controller.scheduledDate != nil }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.controller.scheduledDate != nil })let wake = fixture.controller.wakeDatelet scheduled = fixture.controller.scheduledDatefixture.outcomes.send(.initializationFailed)@@ -197,28 +199,20 @@ struct AutoResetControllerTests {let consume = ResetGate<ResetCreditConsumeResult>()fixture.state.consumeOverride = { await consume.wait() }fixture.controller.start()- try await eventually { fixture.state.consumeCount == 1 }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.consumeCount == 1 })fixture.outcomes.send(.notLoggedIn)consume.release(ResetCreditConsumeResult(outcome: .reset, refreshedRead: fixture.state.read))- try await eventually { fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.activeAssertions.isEmpty })#expect(fixture.state.successes == 1)#expect(fixture.controller.wakeDate == nil)fixture.state.consumeOverride = niltry fixture.outcomes.send(.data(fixture.snapshot()))fixture.controller.handleWake()- try await eventually { fixture.state.readCount >= 2 && fixture.state.activeAssertions.isEmpty }+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(1)) { fixture.state.readCount >= 2 && fixture.state.activeAssertions.isEmpty })#expect(fixture.state.consumeCount == 1)}}-private func eventually(_ predicate: () -> Bool) async throws {- let deadline = ContinuousClock.now.advanced(by: .seconds(3))- while !predicate(), ContinuousClock.now < deadline {- try await Task.sleep(for: .milliseconds(1))- }- try #require(predicate())-}-private func settle() async {for _ in 0 ..< 30 {await Task.yield()diff --git a/Tests/App/CodexStatus/CodexServiceStatusTests.swift b/Tests/App/CodexStatus/CodexServiceStatusTests.swiftindex 7b23b9b..b785950 100644--- a/Tests/App/CodexStatus/CodexServiceStatusTests.swift+++ b/Tests/App/CodexStatus/CodexServiceStatusTests.swift@@ -130,7 +130,7 @@ struct CodexServiceStatusTests {defer { monitor.setEnabled(false) }monitor.setEnabled(true)let first = Task { await monitor.refresh() }- try await wait { await probe.calls == 1 }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { await probe.calls == 1 })let second = Task { await monitor.refresh() }try await Task.sleep(for: .milliseconds(20))#expect(await probe.calls == 1)@@ -164,7 +164,7 @@ struct CodexServiceStatusTests {defer { monitor.setEnabled(false) }monitor.setEnabled(true)let first = Task { await monitor.refresh() }- try await wait { await probe.calls == 1 }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { await probe.calls == 1 })monitor.setEnabled(false)monitor.setEnabled(true)await monitor.refresh()@@ -189,12 +189,12 @@ struct CodexServiceStatusTests {defaults: preferences.defaults)model.refresh(trigger: .manual)- try await wait { await probe.calls == 1 }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { await probe.calls == 1 })#expect(model.isRefreshing)#expect(model.autoRefreshCountdownStartedAt == nil)model.refresh(trigger: .manual)await probe.releaseFirst()- try await wait { !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { !model.isRefreshing })#expect(monitor.state == .available(.operational))#expect(model.autoRefreshCountdownStartedAt != nil)#expect(await probe.calls == 1)@@ -203,7 +203,7 @@ struct CodexServiceStatusTests {let observation = monitor.$state.sink { states.append($0) }defer { observation.cancel() }model.refresh(trigger: .manual)- try await wait { !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { !model.isRefreshing })let outage = CodexServiceStatus(level: .fullOutage, componentNames: ["CLI"])#expect(states == [.available(.operational), .checking, .available(outage)])#expect(await probe.calls == 2)@@ -221,16 +221,16 @@ struct CodexServiceStatusTests {defaults: preferences.defaults)model.refresh(trigger: .manual)- try await wait { !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { !model.isRefreshing })let updatedAt = try #require(model.autoRefreshCountdownStartedAt)await probe.fail()model.refresh(trigger: .accountNotification)- try await wait { !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { !model.isRefreshing })#expect(model.autoRefreshCountdownStartedAt == updatedAt)#expect(monitor.state == .available(.operational))#expect(await probe.calls == 1)model.refresh(trigger: .manual)- try await wait { !model.isRefreshing }+ #expect(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(5)) { !model.isRefreshing })#expect(try #require(model.autoRefreshCountdownStartedAt) > updatedAt)#expect(monitor.state == .unavailable)#expect(await probe.calls == 2)@@ -249,14 +249,6 @@ struct CodexServiceStatusTests {}}- private func wait(_ condition: () async -> Bool) async throws {- let deadline = ContinuousClock.now.advanced(by: .seconds(3))- while await !condition(), ContinuousClock.now < deadline {- try await Task.sleep(for: .milliseconds(5))- }- #expect(await condition())- }-fileprivate nonisolated static func response(affected: [(id: String, status: String)] = [],groupName: String = "Codex",diff --git a/Tests/App/CodexStatus/CodexStatusServiceTests.swift b/Tests/App/CodexStatus/CodexStatusServiceTests.swiftnew file mode 100644index 0000000..3e3ae33--- /dev/null+++ b/Tests/App/CodexStatus/CodexStatusServiceTests.swift@@ -0,0 +1,356 @@+import Foundation+import os+import Testing++@Suite(.timeLimit(.minutes(1)))+struct CodexStatusServiceTests {+ @Test(arguments: ["business", "unsupported", "invalidPayload"], [false, true])+ func supplementalFailurePreservesCacheAndUnsupportedMethodPolicy(failure: String, hasCache: Bool) async throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let rounds = hasCache ? 2 : 1+ for round in 0 ..< rounds {+ let account = try peer.readMessage()+ #expect(account["method"] as? String == "account/read")+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ let fails = round == rounds - 1+ for method in ["account/rateLimits/read", "account/usage/read"] {+ let attempts = fails && failure == "business" && method == "account/rateLimits/read" ? 2 : 1+ for _ in 0 ..< attempts {+ let request = try peer.readMessage()+ #expect(request["method"] as? String == method)+ if !fails {+ let result: [String: Any] = method == "account/rateLimits/read"+ ? ["rateLimits": [:], "ordinaryUsageAllowed": true]+ : ["summary": ["lifetimeTokens": 123], "dailyUsageBuckets": []]+ try peer.reply(to: request, result: result)+ } else if failure == "invalidPayload" {+ try peer.reply(to: request, result: [:])+ } else {+ try peer.send(["id": #require(request["id"]), "error": [+ "code": failure == "unsupported" ? -32601 : -32000,+ "message": failure == "unsupported" ? "unsupported" : "upstream network request failed"+ ]])+ }+ }+ }+ }+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ if hasCache {+ guard case .data = await service.fetchOutcome().outcome else {+ Issue.record("Initial read did not populate the cache")+ return+ }+ }+ let result = await service.fetchOutcome()+ guard case let .data(snapshot) = result.outcome else {+ Issue.record("Supplemental failure discarded the account snapshot")+ return+ }+ let usesCache = hasCache && failure != "unsupported"+ let step: CodexFetchTrace.StepResult = failure == "unsupported" ? .skipped : (usesCache ? .cached : .failed)+ #expect(result.trace.rateLimits == step && result.trace.usage == step)+ #expect(result.trace.failureStage == nil)+ #expect(snapshot.isRateLimitsStale == usesCache && snapshot.isUsageStale == usesCache)+ #expect(snapshot.ordinaryUsageAllowed == (usesCache ? true : nil))+ #expect(snapshot.usage?.summary.lifetimeTokens == (usesCache ? 123 : nil))+ try server.finish()+ }++ @Test(arguments: ["account/rateLimits/read", "account/usage/read"], ["none", "account/rateLimits/read", "account/usage/read"])+ func accountChangeDuringAuthRefreshDiscardsOldData(authMethod: String, failedRead: String) async throws {+ let server = try SharedServerFixture { peer in+ func respond(_ method: String, _ result: [String: Any]) throws {+ let request = try peer.readMessage()+ try #require(request["method"] as? String == method)+ try peer.reply(to: request, result: result)+ }+ try respond("initialize", ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let firstAccount: [String: Any] = ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]]+ let secondAccount: [String: Any] = ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]]+ try respond("account/read", firstAccount)+ try respond("account/rateLimits/read", ["rateLimits": [:], "ordinaryUsageAllowed": true])+ try respond("account/usage/read", ["summary": ["lifetimeTokens": 123]])+ try respond("account/read", firstAccount)+ if authMethod == "account/usage/read" {+ try respond("account/rateLimits/read", ["rateLimits": [:], "ordinaryUsageAllowed": true])+ }+ let unauthorized = try peer.readMessage()+ try #require(unauthorized["method"] as? String == authMethod)+ try peer.send(["id": #require(unauthorized["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])+ let refresh = try peer.readMessage()+ try #require(refresh["method"] as? String == "account/read")+ #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)+ try peer.reply(to: refresh, result: secondAccount)+ try respond("account/rateLimits/read", failedRead == "account/rateLimits/read" ? [:] : ["rateLimits": [:], "ordinaryUsageAllowed": false])+ try respond("account/usage/read", failedRead == "account/usage/read" ? [:] : ["summary": ["lifetimeTokens": 456]])+ try respond("account/read", secondAccount)+ try respond("account/rateLimits/read", [:])+ try respond("account/usage/read", [:])+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ guard case .data = await service.fetchOutcome().outcome else {+ Issue.record("Initial read did not populate the cache")+ return+ }+ let result = await service.fetchOutcome()+ guard case let .data(snapshot) = result.outcome else {+ Issue.record("Account change did not restart supplemental reads")+ return+ }+ #expect(snapshot.account.email == "[email protected]")+ #expect(snapshot.ordinaryUsageAllowed == (failedRead == "account/rateLimits/read" ? nil : false))+ #expect(snapshot.usage?.summary.lifetimeTokens == (failedRead == "account/usage/read" ? nil : 456))+ #expect(!snapshot.isRateLimitsStale && !snapshot.isUsageStale)+ #expect(result.trace.account == .refreshed)+ #expect(result.trace.rateLimits == (failedRead == "account/rateLimits/read" ? .failed : .ok))+ #expect(result.trace.usage == (failedRead == "account/usage/read" ? .failed : .ok))+ guard case let .data(cached) = await service.fetchOutcome().outcome else {+ Issue.record("New account cache was unavailable")+ return+ }+ #expect(cached.account == snapshot.account)+ #expect(cached.ordinaryUsageAllowed == snapshot.ordinaryUsageAllowed)+ #expect(cached.usage?.summary.lifetimeTokens == snapshot.usage?.summary.lifetimeTokens)+ #expect(cached.isRateLimitsStale == (failedRead != "account/rateLimits/read"))+ #expect(cached.isUsageStale == (failedRead != "account/usage/read"))+ try server.finish()+ }++ @Test(arguments: ["account/rateLimits/read", "account/usage/read"])+ func accountChangeDoesNotRenewAuthenticationBudget(authMethod: String) async throws {+ let server = try SharedServerFixture { peer in+ try peer.reply(to: peer.readMessage(), result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ try peer.reply(to: peer.readMessage(), result: ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]])+ if authMethod == "account/usage/read" {+ try peer.reply(to: peer.readMessage(), result: ["rateLimits": [:], "ordinaryUsageAllowed": true])+ }+ let unauthorized = try peer.readMessage()+ try #require(unauthorized["method"] as? String == authMethod)+ let error: [String: Any] = ["code": -32000, "message": "codex account authentication required"]+ try peer.send(["id": #require(unauthorized["id"]), "error": error])+ let refresh = try peer.readMessage()+ try #require(refresh["method"] as? String == "account/read")+ #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)+ try peer.reply(to: refresh, result: ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]])+ let retried = try peer.readMessage()+ try #require(retried["method"] as? String == "account/rateLimits/read")+ try peer.send(["id": #require(retried["id"]), "error": error])+ }+ defer { server.close() }+ let result = await CodexStatusService(socketURL: server.url, logStorage: nil).fetchOutcome()+ guard case .authenticationRequired = result.outcome else {+ Issue.record("Account change renewed the authentication budget")+ return+ }+ #expect(result.trace.account == .refreshed)+ #expect(result.trace.failureStage == .snapshot)+ #expect(result.trace.rateLimits == nil && result.trace.usage == nil && result.trace.resetCredits == nil)+ try server.finish()+ }++ @Test(arguments: [false, true])+ func quotaReadsShareOneAuthenticationRefreshBudget(repeatsOnSameMethod: Bool) async throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let account = try peer.readMessage()+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ let limits = try peer.readMessage()+ #expect(limits["method"] as? String == "account/rateLimits/read")+ try peer.send(["id": #require(limits["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])+ let refresh = try peer.readMessage()+ #expect(refresh["method"] as? String == "account/read")+ #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)+ try peer.reply(to: refresh, result: ["account": ["type": "apiKey"]])+ let retried = try peer.readMessage()+ #expect(retried["method"] as? String == "account/rateLimits/read")+ let secondFailure: [String: Any]+ if repeatsOnSameMethod {+ secondFailure = retried+ } else {+ try peer.reply(to: retried, result: ["rateLimits": [:]])+ secondFailure = try peer.readMessage()+ #expect(secondFailure["method"] as? String == "account/usage/read")+ }+ try peer.send(["id": #require(secondFailure["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])+ }+ defer { server.close() }+ let result = await CodexStatusService(socketURL: server.url, logStorage: nil).fetchOutcome()+ guard case .authenticationRequired = result.outcome else {+ Issue.record("Repeated authentication failure was not propagated")+ return+ }+ #expect(result.trace.failureStage == .snapshot)+ #expect(result.trace.rateLimits == (repeatsOnSameMethod ? nil : .ok))+ #expect(result.trace.usage == nil)+ try server.finish()+ }++ @Test(arguments: [+ ("serverError", true), ("invalidPayload", true), ("signedOut", true),+ ("signedOut", false), ("authentication", false), ("serverError", false),+ ("invalidPayload", false), ("connectionClosed", false)+ ])+ func authenticationRefreshFailurePreservesOutcomeAndRejectsCache(failure: String, hasCache: Bool) async throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let rounds = hasCache ? 2 : 1+ for round in 0 ..< rounds {+ let account = try peer.readMessage()+ #expect(account["method"] as? String == "account/read")+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ let limits = try peer.readMessage()+ #expect(limits["method"] as? String == "account/rateLimits/read")+ if round < rounds - 1 {+ try peer.reply(to: limits, result: ["rateLimits": [:], "ordinaryUsageAllowed": true])+ let usage = try peer.readMessage()+ #expect(usage["method"] as? String == "account/usage/read")+ try peer.reply(to: usage, result: ["summary": ["lifetimeTokens": 123]])+ } else {+ try peer.send(["id": #require(limits["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])+ for _ in 0 ..< (failure == "serverError" ? 2 : 1) {+ let refresh = try peer.readMessage()+ #expect(refresh["method"] as? String == "account/read")+ #expect((refresh["params"] as? [String: Any])?["refreshToken"] as? Bool == true)+ switch failure {+ case "signedOut": try peer.reply(to: refresh, result: ["account": NSNull()])+ case "invalidPayload": try peer.reply(to: refresh, result: [:])+ case "connectionClosed": return+ default:+ try peer.send(["id": #require(refresh["id"]), "error": [+ "code": -32000, "message": failure == "authentication" ? "codex account authentication required" : "upstream network request failed"+ ]])+ }+ }+ }+ }+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ if hasCache {+ guard case .data = await service.fetchOutcome().outcome else {+ Issue.record("Initial read did not populate the cache")+ return+ }+ }+ let result = await service.fetchOutcome()+ #expect(result.trace.rateLimits == nil && result.trace.usage == nil)+ #expect(result.trace.failureStage == .snapshot)+ if !hasCache {+ #expect(result.trace.connection == .new)+ }+ switch result.outcome {+ case .notLoggedIn: #expect(failure == "signedOut")+ case .authenticationRequired: #expect(failure == "authentication")+ case .initializationFailed: #expect(["serverError", "invalidPayload", "connectionClosed"].contains(failure))+ default: Issue.record("Authentication refresh failure was hidden or misclassified")+ }+ try server.finish()+ }++ @Test(arguments: ["authentication", "invalidPayload", "unsupportedVersion"], [false, true])+ func connectionFailurePreservesFetchStageAndOperationError(failure: String, readsConfiguration: Bool) async throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": failure == "unsupportedVersion" ? "codex/0.161.0" : "codex/0.162.0"])+ guard failure != "unsupportedVersion" else { return }+ #expect(try peer.readMessage()["method"] as? String == "initialized")+ let account = try peer.readMessage()+ #expect(account["method"] as? String == "account/read")+ if failure == "authentication" {+ try peer.send(["id": #require(account["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])+ } else {+ try peer.reply(to: account, result: [:])+ }+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ if readsConfiguration {+ do {+ _ = try await service.areTUINotificationsEnabled()+ Issue.record("Configuration read accepted an uninitialized connection")+ } catch let error as CodexStatusError {+ switch error {+ case .authenticationRequired: #expect(failure == "authentication")+ case .unsupportedVersion: #expect(failure == "unsupportedVersion")+ case .serverConnectionClosed: #expect(failure == "invalidPayload")+ default: Issue.record("Unexpected connection error")+ }+ }+ } else {+ let result = await service.fetchOutcome()+ switch result.outcome {+ case .authenticationRequired: #expect(failure == "authentication")+ case .unsupportedVersion: #expect(failure == "unsupportedVersion")+ case .initializationFailed: #expect(failure == "invalidPayload")+ default: Issue.record("Unexpected fetch outcome")+ }+ #expect(result.trace.failureStage == (failure == "authentication" ? .account : .connect))+ #expect(result.trace.connection == nil)+ }+ #expect(await service.currentConnectionInfo() == nil)+ try server.finish()+ }++ @Test func autoResetAuthenticationRetryKeepsCreditIdentityAndFreshAccountCheck() async throws {+ let server = try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ #expect(try peer.readMessage()["method"] as? String == "initialized")+ for refreshToken in [false, false] {+ let account = try peer.readMessage()+ #expect(account["method"] as? String == "account/read")+ #expect((account["params"] as? [String: Any])?["refreshToken"] as? Bool == refreshToken)+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ }+ let first = try peer.readMessage()+ #expect(first["method"] as? String == "account/rateLimitResetCredit/consume")+ try peer.send(["id": #require(first["id"]), "error": ["code": -32000, "message": "codex account authentication required"]])+ for refreshToken in [true, false] {+ let account = try peer.readMessage()+ #expect(account["method"] as? String == "account/read")+ #expect((account["params"] as? [String: Any])?["refreshToken"] as? Bool == refreshToken)+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ }+ let retried = try peer.readMessage()+ #expect(retried["method"] as? String == "account/rateLimitResetCredit/consume")+ for request in [first, retried] {+ let params = try #require(request["params"] as? [String: String])+ #expect(params == ["creditId": "credit", "idempotencyKey": "same-key"])+ }+ try peer.reply(to: retried, result: ["outcome": "reset"])+ let account = try peer.readMessage()+ #expect(account["method"] as? String == "account/read")+ try peer.reply(to: account, result: ["account": ["type": "apiKey"]])+ let limits = try peer.readMessage()+ #expect(limits["method"] as? String == "account/rateLimits/read")+ try peer.reply(to: limits, result: ["rateLimits": [:], "rateLimitResetCredits": ["availableCount": 0, "credits": []]])+ }+ defer { server.close() }+ let service = CodexStatusService(socketURL: server.url, logStorage: nil)+ let result = try await service.consumeResetCredit(+ id: "credit", idempotencyKey: "same-key", expectedAccountIdentity: "apiKey\u{0}",+ expirationDate: Date().addingTimeInterval(600),+ budget: AppServerRequestBudget(deadline: Date().addingTimeInterval(5))+ )+ #expect(result.outcome == .reset)+ #expect(result.refreshedRead?.availableCount == 0)+ try server.finish()+ }++ @Test func missingAccountFieldIsNotSignedOut() throws {+ #expect(throws: DecodingError.self) { try TestFixtures.decode(AccountReadResponse.self, "{}") }+ #expect(try TestFixtures.decode(AccountReadResponse.self, "{\"account\":null}").account == nil)+ }+}diff --git a/Tests/App/CodexStatus/StatusRefreshIntervalTests.swift b/Tests/App/CodexStatus/StatusRefreshIntervalTests.swiftnew file mode 100644index 0000000..e9e36e4--- /dev/null+++ b/Tests/App/CodexStatus/StatusRefreshIntervalTests.swift@@ -0,0 +1,47 @@+import Foundation+import Testing++struct StatusRefreshIntervalTests {+ @Test(arguments: DataUpdateInterval.allCases)+ func dataUpdateIntervalPersistsAndUpdatesCountdown(_ interval: DataUpdateInterval) throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let service = makeStatusService(suiteName: preferences.suite)+ let model = CodexStatusViewModel(service: service, defaults: preferences.defaults)+ #expect(model.dataUpdateInterval == .oneMinute)+ model.setDataUpdateInterval(interval)+ #expect(model.autoRefreshInterval == interval.duration)+ let restored = CodexStatusViewModel(service: service, defaults: preferences.defaults)+ #expect(restored.dataUpdateInterval == interval)+ #expect(restored.autoRefreshInterval == interval.duration)+ #expect(!model.isRefreshing)+ #expect(model.autoRefreshCountdownStartedAt == nil)+ }++ @Test(arguments: [0, -60, 90, 1200])+ func invalidDataUpdateIntervalUsesDefault(_ seconds: Int) throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ preferences.defaults.set(seconds, forKey: "DataUpdate.intervalSeconds")+ let model = CodexStatusViewModel(+ service: makeStatusService(suiteName: preferences.suite),+ defaults: preferences.defaults+ )+ #expect(model.dataUpdateInterval == .oneMinute)+ }++ @Test func dataUpdateIntervalRespectsElapsedTimeAndNewRefreshOrigin() {+ let start = TestFixtures.now+ let now = start.addingTimeInterval(150)+ #expect(DataUpdateInterval.tenMinutes.remainingTime(since: start, now: now) == 450)+ #expect(DataUpdateInterval.threeMinutes.remainingTime(since: start, now: now) == 30)+ #expect(DataUpdateInterval.twoMinutes.remainingTime(since: start, now: now) == 0)+ #expect(DataUpdateInterval.oneMinute.remainingTime(since: nil, now: now) == 0)+ #expect(DataUpdateInterval.oneMinute.remainingTime(since: start, now: start.addingTimeInterval(60)) == 0)+ #expect(DataUpdateInterval.fiveMinutes.remainingTime(since: now, now: now) == 300)+ }++ private nonisolated func makeStatusService(suiteName: String) -> CodexStatusService {+ CodexStatusService(socketURL: URL(fileURLWithPath: "/tmp/\(suiteName).sock"), logStorage: nil)+ }+}diff --git a/Tests/App/History/AggregationPolicyTests.swift b/Tests/App/History/AggregationPolicyTests.swiftindex 1576f9c..2cc1d08 100644--- a/Tests/App/History/AggregationPolicyTests.swift+++ b/Tests/App/History/AggregationPolicyTests.swift@@ -35,15 +35,4 @@ struct AggregationPolicyTests {#expect(throws: StorageCompatibilityError.self) { try AggregationVersion.require(3, current: 2, name: "test") }#expect(throws: StorageCompatibilityError.self) { try AggregationVersion.require(0, current: 2, name: "test") }}-- @Test func partialSourcesKeepKnownValuesVisible() {- let now = Date()- let date = HistoryStorage.dateKey(for: now)- var aggregate = ActivityDataAggregate(date: date)- aggregate.turnCount = 3- var snapshot = HistorySnapshot(activityData: [aggregate.metrics])- snapshot.isActivityDataComplete = false- let day = UsageHeatmapDay.grid(usage: nil, history: snapshot, columnCount: 1, today: now).compactMap(\.self).first { $0.startDate == date }- #expect(day?.activityData.turnCount == 3)- }}diff --git a/Tests/App/History/HistoryAggregationTests.swift b/Tests/App/History/HistoryAggregationTests.swiftindex acceed8..4f08ce4 100644--- a/Tests/App/History/HistoryAggregationTests.swift+++ b/Tests/App/History/HistoryAggregationTests.swift@@ -1,4 +1,3 @@-import CloudKitimport Foundationimport Testing@@ -217,77 +216,6 @@ struct HistoryAggregationTests {#expect(!text.contains("thread-a"))}- @Test func cloudDailyCountsRoundTripWithEventNames() throws {- let counts = [- "threadCount": 2, "turnCount": 3,- "turnStartedCount": 3,- "turnCompletedCount": 4, "turnAbortedCount": 5, "toolStartedCount": 6,- "toolCompletedCount": 7, "approvalRequestedCount": 8, "compactionStartedCount": 9,- "compactionCompletedCount": 10, "subagentStartedCount": 11, "subagentEndedCount": 12- ]- var fields: [String: Any] = counts- fields["schemaVersion"] = 1- fields["aggregationVersion"] = 1- fields["date"] = "2026-09-15"- let aggregate = try JSONDecoder().decode(- SyncedActivityData.self, from: JSONSerialization.data(withJSONObject: fields)- )- let record = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_device-a_2026-09-15"))- try ActivityDataRecordCodec.apply(aggregate, deviceID: "device-a", to: record)- #expect(Set(record.allKeys()) == [- "schemaVersion", "aggregationVersion", "deviceID", "date", "activityData", "updatedAt"- ])- let payload = try #require(record["activityData"] as? Data)- let encodedCounts = try #require(JSONSerialization.jsonObject(with: payload) as? [String: Any])- #expect(Set(encodedCounts.keys) == Set(counts.keys).union(["eventCount", "projectCounts", "modelCounts"]))- for (name, count) in counts {- #expect(encodedCounts[name] as? Int == count)- }- #expect(encodedCounts["eventCount"] is NSNull)- let restored = try #require(try ActivityDataRecordCodec.remoteDailyRecord(from: record))- #expect(restored.deviceID == "device-a")- #expect(restored.activityData == aggregate)-- var changed = aggregate- changed.turnAbortedCount = nil- changed.toolStartedCount = 0- try ActivityDataRecordCodec.apply(changed, deviceID: "device-a", to: record)- let changedData = try #require(record["activityData"] as? Data)- let changedCounts = try #require(JSONSerialization.jsonObject(with: changedData) as? [String: Any])- #expect(changedCounts["turnAbortedCount"] is NSNull)- #expect(changedCounts["toolStartedCount"] as? Int == 0)- let missing = try #require(try ActivityDataRecordCodec.remoteDailyRecord(from: record))- #expect(missing.activityData.turnAbortedCount == nil)- #expect(missing.activityData.toolStartedCount == 0)- }-- @Test(arguments: [nil, ""]) func cloudActivityDataRejectsMissingDevice(deviceID: String?) {- let record = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_device_2026-09-15"))- record["schemaVersion"] = 1 as CKRecordValue- record["aggregationVersion"] = 1 as CKRecordValue- record["activityData"] = Data(#"{"projectCounts":{},"modelCounts":{}}"#.utf8) as CKRecordValue- record["deviceID"] = deviceID as CKRecordValue?- record["date"] = "2026-09-15" as CKRecordValue- #expect(throws: ActivityDataSyncError.self) { try ActivityDataRecordCodec.remoteDailyRecord(from: record) }- }-- @Test func cloudAndCachedActivityDataRejectMismatchedIdentity() throws {- let daily = SyncedActivityData(- date: "2026-09-15",- projectCounts: [:],- modelCounts: [:]- )- let record = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_other_2026-09-15"))- try ActivityDataRecordCodec.apply(daily, deviceID: "device", to: record)- #expect(throws: ActivityDataSyncError.self) { try ActivityDataRecordCodec.remoteDailyRecord(from: record) }- #expect(throws: DecodingError.self) {- try TestFixtures.decode(- ActivityDataSyncRecord.self,- #"{"deviceID":"device","recordName":"activityData_other_2026-09-15","schemaVersion":1,"aggregationVersion":1,"date":"2026-09-15","activityData":{}}"#- )- }- }-private func makeAccumulator() -> ActivityDataAccumulator {ActivityDataAccumulator(rebuilding: "2026-09-15")}diff --git a/Tests/App/History/HistoryDatabaseTests.swift b/Tests/App/History/HistoryDatabaseTests.swiftindex b638053..9077e8f 100644--- a/Tests/App/History/HistoryDatabaseTests.swift+++ b/Tests/App/History/HistoryDatabaseTests.swift@@ -187,18 +187,6 @@ struct HistoryDatabaseTests {#expect(try database.pendingActivityDataDates() == [HistoryStorage.dateKey(for: yesterday)])}- @Test func recordingLeaseTransfersWithoutTwoWriters() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let first = TokenUsageHistoryStore(directoryURL: directory.url)- let second = TokenUsageHistoryStore(directoryURL: directory.url)- #expect(try first.acquireRecordingLease())- #expect(try !second.acquireRecordingLease())- first.releaseRecordingLease()- #expect(try second.acquireRecordingLease())- second.releaseRecordingLease()- }-@Test func actualTaskCancellationRollsBackAndReleasesDatabaseLock() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -254,9 +242,7 @@ struct HistoryDatabaseTests {toolName: "read", commandActionTypes: commandActionTypes, model: nil, effort: nil, threadID: "thread", turnID: "turn", agentThreadID: nil, id: id), recordedAt: date)}-}-extension HistoryDatabaseTests {@Test func aggregateColumnsStoreProgressWithEachResultAndLeaveMissingUsageNull() throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -422,194 +408,4 @@ extension HistoryDatabaseTests {#expect(try await store.refresh(now: now) == recovered.aggregates)#expect(try database.activityDataAggregates().first?.eventCount == 1)}-- @Test func dailyTokenUsageDeduplicateRetriesAndRebuildAfterCacheDamage() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = Date()- let store = TokenUsageHistoryStore(directoryURL: directory.url)- let first = TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(20))- let second = TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(30), previous: tokenUsage(20))- let initial = try await store.recordObservations([first, first, second], now: now)- #expect(initial.first?.tokenUsage == tokenUsage(50))- #expect(initial.first?.eventCount == 2)- #expect(try await TokenUsageHistoryStore(directoryURL: directory.url).refresh(now: now) == initial)- let database = try HistoryDatabase(directoryURL: directory.url)- try database.execute("UPDATE aggregates SET tokenUsage = ?", [.data(Data("broken".utf8))])- #expect(try await store.refresh(now: now) == initial)- try database.execute("UPDATE aggregates SET tokenUsage = ?", [.data(Data("broken".utf8))])- let rebuilt = try await store.rebuild(for: [HistoryStorage.dateKey(for: now)])- #expect(rebuilt.eventCount == 2)- #expect(try await store.persistedAggregates(now: now) == initial)- try database.execute("UPDATE aggregates SET tokenUsage = NULL")- #expect(try await store.refresh(now: now) == initial)- }-- @Test func tokenRebuildChecksOnlyRequestedDatesWithSourceEvents() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let database = try HistoryDatabase(directoryURL: directory.url)- let now = TestFixtures.now- let dates = (0 ..< 5).map { now.addingTimeInterval(Double($0) * 86400) }- let keys = dates.map(HistoryStorage.dateKey(for:))- for index in [0, 1, 2] {- try database.append(AppServerEventRecord(- tokenUsage: TestFixtures.tokenUsageObservation(at: dates[index], tokenUsage: tokenUsage(10)), recordedAt: now- ))- }- try database.append(event("activity-only", at: dates[3]))- try database.append(event("mixed", at: dates[0]))- let requested = [keys[2], keys[0], keys[3], keys[4], keys[2]]- #expect(try database.tokenUsageAggregates().isEmpty)- #expect(try database.tokenUsageDates(in: requested) == [keys[0], keys[2]])- #expect(try database.tokenUsageDates(in: []).isEmpty)-- let store = TokenUsageHistoryStore(directoryURL: directory.url)- let rebuilt = try await store.rebuild(for: requested)- #expect(rebuilt.dateKeys == [keys[0], keys[2]])- #expect(rebuilt.eventCount == 2)- #expect(rebuilt.failedDateKeys.isEmpty)- #expect(try database.tokenUsageAggregates().map(\.date) == [keys[0], keys[2]])- #expect(try database.pendingTokenUsageDates() == [keys[1]])- }-- @Test func observedDateSurvivesDelayedWriteAcrossMidnight() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = Date()- let midnight = Calendar.current.startOfDay(for: now)- let before = midnight.addingTimeInterval(-1)- let store = TokenUsageHistoryStore(directoryURL: directory.url)- let first = TestFixtures.tokenUsageObservation(at: before, tokenUsage: tokenUsage(20))- let second = TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(30), previous: tokenUsage(20))- let result = try await store.recordObservations([first, second], now: now)- #expect(TokenUsageAggregate.tokenUsageByDate(result, now: now) == [HistoryStorage.dateKey(for: before): tokenUsage(20), HistoryStorage.dateKey(for: now): tokenUsage(30)])- let database = try HistoryDatabase(directoryURL: directory.url)- try database.execute("""- UPDATE aggregates SET tokenUsage = NULL- """)- #expect(try await store.refresh(now: now) == result)- }-- @Test(arguments: [-1, 1])- func storedTokenDatesSurviveLocalDateChanges(dayOffset: Int) async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = TestFixtures.now- let localDate = HistoryStorage.dateKey(for: now)- let storedDate = HistoryStorage.dateKey(for: now.addingTimeInterval(Double(dayOffset) * 86400))- func sample(_ id: String, _ count: Int64) -> TokenUsageSample {- let usage = tokenUsage(count)- return TokenUsageSample(- id: id, observedAt: now, threadID: "thread", turnID: "turn", turnStartedAt: now,- current: TokenUsageUpdate(total: usage, last: usage)- )- }- do {- let database = try HistoryDatabase(directoryURL: directory.url)- try database.appendTokenUsage(sample("baseline", 0))- try database.appendTokenUsage(sample("first", 100))- let initial = try database.aggregateTokenUsage(date: localDate)- try database.appendTokenUsage(sample("pending", 130))- // 模拟在另一时区保存的日期, 避免修改并行测试共享的系统时区- var stored = TokenUsageAggregate(date: storedDate, tokenUsage: initial.tokenUsage, eventCount: initial.eventCount)- stored.position = initial.position- try database.transaction {- try database.execute("INSERT INTO days(date) VALUES (?)", [.text(storedDate)])- try database.execute("UPDATE events SET date = ?", [.text(storedDate)])- try database.execute("INSERT INTO aggregates(date, tokenUsage) VALUES (?, ?)", [.text(storedDate), .data(JSONLines.stableEncoder.encode(stored))])- try database.execute("DELETE FROM days WHERE date = ?", [.text(localDate)])- }- }-- let database = try HistoryDatabase(directoryURL: directory.url)- let latest = sample("after-switch", 150)- try database.appendTokenUsage(latest)- try database.appendTokenUsage(latest)- let store = TokenUsageHistoryStore(directoryURL: directory.url)- let snapshot = try await store.loadSnapshot(now: now)- #expect(snapshot.coverage == .complete)- #expect(Dictionary(uniqueKeysWithValues: snapshot.aggregates.map { ($0.date, $0.tokenUsage.totalTokens) }) == [storedDate: 130, localDate: 20])- #expect(snapshot.aggregates.reduce(0) { $0 + $1.eventCount } == 4)- #expect(try database.pendingTokenUsageDates().isEmpty)- #expect(try database.tokenUsageSnapshot(threadID: "thread").turns["turn"]?.totalTokens == 150)-- let rebuilt = try await store.rebuild(for: [storedDate, localDate])- #expect(rebuilt.failedDateKeys.isEmpty)- #expect(rebuilt.dateKeys == [storedDate, localDate].sorted())- #expect(rebuilt.eventCount == 4)- #expect(try await store.persistedAggregates(now: now) == snapshot.aggregates)- let expectedDates = dayOffset > 0 ? [localDate] : [storedDate, localDate].sorted()- #expect(TokenUsageAggregate.tokenUsageByDate(snapshot.aggregates, now: now).keys.sorted() == expectedDates)- #expect(try TokenUsageSyncRecord.dailyRecords(local: snapshot.aggregates, deviceID: "device", now: now).map(\.date) == expectedDates)- let later = now.addingTimeInterval(86400)- #expect(TokenUsageAggregate.tokenUsageByDate(snapshot.aggregates, now: later).values.reduce(0) { $0 + $1.totalTokens } == 150)- }-- @Test func unchangedSnapshotReadsSavedDailyTotalsWithoutReplayingEventsOrWriting() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = Date()- let store = TokenUsageHistoryStore(directoryURL: directory.url)- let saved = try await store.recordObservations([TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(20))], now: now)- let database = try HistoryDatabase(directoryURL: directory.url)- try database.execute("UPDATE events SET payload = ? WHERE kind = 'tokenUsage'", [.data(Data("broken".utf8))])- try database.execute("CREATE TRIGGER reject_tokenUsage BEFORE UPDATE OF tokenUsage ON aggregates BEGIN SELECT RAISE(ABORT, 'unexpected rewrite'); END")- let snapshot = try await store.loadSnapshot(now: now)- #expect(snapshot.coverage == .complete)- #expect(snapshot.aggregates == saved)- }-- @Test func failedTokenUsageDayPreservesTotalAndHealthyDayStillAdvances() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = Date()- let yesterday = now.addingTimeInterval(-86400)- let store = TokenUsageHistoryStore(directoryURL: directory.url)- _ = try await store.recordObservations([TestFixtures.tokenUsageObservation(at: yesterday, tokenUsage: tokenUsage(10))], now: now)- let bad = TestFixtures.tokenUsageObservation(at: yesterday, tokenUsage: tokenUsage(30))- try await store.appendObservation(bad, now: now)- try await store.appendObservation(TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(20)), now: now)- let database = try HistoryDatabase(directoryURL: directory.url)- try database.execute("UPDATE events SET payload = ? WHERE identity = ?", [.data(Data("broken".utf8)), .text("tokenUsage:" + bad.id)])- for _ in 0 ..< 2 {- let snapshot = try await store.loadSnapshot(now: now)- #expect(snapshot.coverage == .partial)- #expect(TokenUsageAggregate.tokenUsageByDate(snapshot.aggregates, now: now) == [- HistoryStorage.dateKey(for: yesterday): tokenUsage(10), HistoryStorage.dateKey(for: now): tokenUsage(20)- ])- }- let rebuilt = try await store.rebuild(for: [HistoryStorage.dateKey(for: yesterday)])- #expect(rebuilt.eventCount == 0)- #expect(rebuilt.failedDateKeys == [HistoryStorage.dateKey(for: yesterday)])- }-- @Test func missingObservationCannotReplaceSavedDailyTotalDuringRebuild() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = Date()- let store = TokenUsageHistoryStore(directoryURL: directory.url)- let second = TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(20))- let before = try await store.recordObservations([TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(10)), second], now: now)- try HistoryDatabase(directoryURL: directory.url).execute("DELETE FROM events WHERE identity = ?", [.text("tokenUsage:" + second.id)])- let rebuilt = try await store.rebuild(for: [HistoryStorage.dateKey(for: now)])- #expect(rebuilt.failedDateKeys == [HistoryStorage.dateKey(for: now)])- #expect(try await store.persistedAggregates(now: now) == before)- }-- @Test func tokenUsageRetentionRemovesDailyAggregateWithItsObservedEvents() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = Date()- let expired = HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400)- let store = TokenUsageHistoryStore(directoryURL: directory.url)- _ = try await store.recordObservations([- TestFixtures.tokenUsageObservation(at: expired, tokenUsage: tokenUsage(20)),- TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(30))- ], now: now)- let database = try HistoryDatabase(directoryURL: directory.url)- #expect(try database.prune(now: now) == 1)- #expect(try database.tokenUsageAggregates().count == 1)- #expect(try database.tokenUsageAggregates().first?.tokenUsage == tokenUsage(30))- }}diff --git a/Tests/App/History/HistoryServiceTests.swift b/Tests/App/History/HistoryServiceTests.swiftnew file mode 100644index 0000000..1b7ecc7--- /dev/null+++ b/Tests/App/History/HistoryServiceTests.swift@@ -0,0 +1,303 @@+import CloudKit+import Foundation+import Testing++struct HistoryServiceTests {+ @Test func sameSourceRecalculationCanReduceCountsWithoutDeletingRecord() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let before = try #require(await fixture.database.activityDataRecords().first)+ let result = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ let after = try #require(await fixture.database.activityDataRecords().first)+ #expect(before.recordID == after.recordID)+ #expect(try SyncTestFixtures.activityDataEventCount(before) == 9)+ #expect(try SyncTestFixtures.activityDataEventCount(after) == 1)+ #expect(!result.summary.isSyncPending)+ #expect(await fixture.database.deletedIDs.isEmpty)+ }++ @Test func recreatedJournalReplacesSameDeviceDateInsteadOfAddingAnotherBatch() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let previous = try #require(await fixture.database.activityDataRecords().first)+ let event = TestFixtures.event(.toolStarted, at: Date(), turn: "different")+ try fixture.directory.replaceHistory(+ AppServerEventRecord(activityData: event).jsonLineData(),+ date: fixture.date+ )+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ let updated = try #require(await fixture.database.activityDataRecords().first)+ #expect(updated.recordID == previous.recordID)+ let counts = try #require(try ActivityDataRecordCodec.remoteDailyRecord(from: updated)?.activityData)+ #expect(counts.eventCount == 1)+ #expect(counts.turnStartedCount == 0)+ #expect(counts.toolStartedCount == 1)+ #expect(await fixture.database.activityDataRecords().count == 1)+ #expect(await fixture.database.deletedIDs.isEmpty)+ }++ @Test func unknownCloudVersionPreservesCacheAndPreventsActivityDataUpload() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let cacheURL = fixture.directory.url.appendingPathComponent("Sync/activityData.json")+ let before = try Data(contentsOf: cacheURL)+ let unsupported = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "future", zoneID: SyncTestFixtures.zone))+ unsupported["schemaVersion"] = 999 as CKRecordValue+ await fixture.database.injectChangesRecord(unsupported)+ let result = await fixture.history.loadSnapshot(synchronize: true)+ #expect(!result.isActivityDataComplete)+ #expect(try Data(contentsOf: cacheURL) == before)+ #expect(try await SyncTestFixtures.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)+ #expect(await fixture.database.deletedIDs.isEmpty)+ }++ @Test func failedUploadPreservesRemoteAndRetriesAfterRestart() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)+ #expect(outcome.summary.isSyncPending)+ await fixture.database.failActivityDataUpload(on: fixture.date)+ _ = await fixture.history.loadSnapshot(synchronize: true)+ #expect(try await SyncTestFixtures.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)+ #expect(await fixture.database.deletedIDs.isEmpty)+ await fixture.database.repair()+ let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)+ #expect(try await SyncTestFixtures.activityDataEventCount(fixture.database.activityDataRecords().first) == 1)+ #expect(await fixture.database.activityDataRecords().count == 1)+ }++ @Test func repeatedRebuildKeepsSourceAndNeedsNoSeparateAcknowledgement() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let initial = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)+ #expect(initial.summary.failedTokenUsageDateKeys.isEmpty)+ #expect(!initial.summary.didFailTokenUsageRebuild)+ _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ let state = try HistoryDatabase(directoryURL: fixture.directory.url)+ #expect(try state.activityDataAggregates().first == fixture.local)+ #expect(try state.pendingActivityDataDates().isEmpty)+ #expect(await fixture.database.activityDataRecords().count == 1)+ #expect(await fixture.database.deletedIDs.isEmpty)+ }++ @Test func unavailableSourceCannotOverwriteRemoteAndRecoversAfterRepair() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let local = try HistoryDatabase(directoryURL: fixture.directory.url)+ let original = try local.exportJSONLines(date: fixture.date)+ try local.execute("UPDATE events SET payload = ?", [.data(Data("broken".utf8))])+ try local.execute("UPDATE aggregates SET activityData = CAST(json_set(CAST(activityData AS TEXT), '$.aggregationVersion', 0) AS BLOB)")+ await #expect(throws: (any Error).self) {+ try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ }+ let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)+ #expect(try await SyncTestFixtures.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)+ #expect(await fixture.database.deletedIDs.isEmpty)+ try fixture.directory.replaceHistory(original, date: fixture.date)+ _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)+ #expect(try await SyncTestFixtures.activityDataEventCount(fixture.database.activityDataRecords().first) == 1)+ }++ @Test func requestSaveFailureDoesNotModifyAggregateOrCloud() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let local = try HistoryDatabase(directoryURL: fixture.directory.url)+ let original = try local.activityDataAggregates()+ try local.execute("CREATE TRIGGER reject_aggregate BEFORE UPDATE ON aggregates BEGIN SELECT RAISE(ABORT, 'injected failure'); END")+ await #expect(throws: (any Error).self) {+ try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ }+ #expect(try local.activityDataAggregates() == original)+ #expect(await fixture.database.deletedIDs.isEmpty)+ }++ @Test func disabledSyncKeepsUpdatedAggregateForNextEnabledRun() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let disabled = SyncService(database: fixture.database, directoryURL: fixture.directory.url, isEnabled: { false })+ let history = HistoryService(directoryURL: fixture.directory.url, syncService: disabled)+ _ = try await history.rebuildData(for: [fixture.date], synchronize: true)+ #expect(try await SyncTestFixtures.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)+ _ = await fixture.history.loadSnapshot(synchronize: true)+ #expect(try await SyncTestFixtures.activityDataEventCount(fixture.database.activityDataRecords().first) == 1)+ }++ @Test func appendedEventsUpdateSameDeviceDailyCounts() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let activityDataRecorder = ActivityDataRecorder(directoryURL: fixture.directory.url)+ let event = ActivityDataRecord(+ timestamp: Date(),+ name: ActivityDataEventKind.toolStarted.rawValue,+ origin: .main,+ cwd: nil,+ toolName: "exec_command",+ model: nil,+ effort: nil,+ threadID: "thread-a",+ turnID: "turn-a",+ agentThreadID: nil,+ id: "appended-tool"+ )+ try await activityDataRecorder.record(event: event)+ _ = await fixture.history.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)+ let remote = try #require(await fixture.database.activityDataRecords().first)+ #expect(try SyncTestFixtures.activityDataEventCount(remote) == 2)+ #expect(remote["sourceCheckpoint"] == nil)+ #expect(await fixture.database.activityDataRecords().count == 1)+ }++ @Test func unavailableTokenUsageHistoryMarksAllRequestedDatesFailed() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let brokenDirectory = try TestDirectory()+ defer { try? brokenDirectory.remove() }+ _ = try brokenDirectory.write(Data("broken".utf8), to: "event.db")+ let history = HistoryService(+ directoryURL: fixture.directory.url, syncService: fixture.sync,+ tokenUsageHistory: TokenUsageHistoryStore(directoryURL: brokenDirectory.url)+ )+ let date = try #require(CodexDateFormat.dayDate(from: fixture.date))+ let dates = [fixture.date, HistoryStorage.dateKey(for: date.addingTimeInterval(-86400))]+ let result = try await history.rebuildData(for: dates, synchronize: false)+ #expect(result.summary.failedTokenUsageDateKeys == dates.sorted())+ #expect(result.summary.didFailTokenUsageRebuild)+ #expect(result.summary.rebuiltDateCount == 0)+ #expect(result.summary.eventCount == 1)+ #expect(result.summary.tokenUsageEventCount == 0)+ #expect(result.summary.failedDateKeys.isEmpty)+ #expect(try await SyncTestFixtures.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)+ }++ @Test func partialTokenUsageFailureIsReportedWithoutClaimingWholeDaySuccess() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ let now = Date()+ let good = TestFixtures.tokenUsageObservation(id: "good", at: now, tokenUsage: .zero)+ let bad = TokenUsageObservation(id: "bad", observedAt: now, previous: SyncTestFixtures.counts(10), current: TokenUsageUpdate(total: .zero, last: .zero))+ let local = try HistoryDatabase(directoryURL: fixture.directory.url)+ try local.append(AppServerEventRecord(tokenUsage: good, recordedAt: now))+ try local.append(AppServerEventRecord(tokenUsage: bad, recordedAt: now))+ let result = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)+ #expect(result.summary.rebuiltDateCount == 0)+ #expect(result.summary.eventCount == 1)+ #expect(result.summary.tokenUsageEventCount == 0)+ #expect(result.summary.failedTokenUsageDateKeys == [fixture.date])+ #expect(result.summary.didFailTokenUsageRebuild)+ #expect(result.summary.failedDateKeys.isEmpty)+ }++ @Test func rebuildUploadsAlgorithmVersionEvenWhenCountsAreUnchanged() async throws {+ let fixture = try await HistoryRebuildFixture()+ defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }+ var previous = fixture.local+ previous.aggregationVersion = 1+ try HistoryDatabase(directoryURL: fixture.directory.url).execute(+ "UPDATE aggregates SET activityData = ? WHERE date = ?",+ [.data(JSONLines.stableEncoder.encode(previous)), .text(fixture.date)]+ )+ let remote = try #require(await fixture.database.activityDataRecords().first)+ try ActivityDataRecordCodec.apply(previous.syncedAggregate, deviceID: #require(remote["deviceID"] as? String), to: remote)+ _ = try await fixture.database.modifyRecords(saving: [remote], deleting: [], savePolicy: .ifServerRecordUnchanged, atomically: false)+ _ = await fixture.sync.synchronizeIfEnabled(localActivityDataAggregates: [previous], trigger: .manual)+ let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)+ let updated = try #require(await fixture.database.activityDataRecords().first)+ #expect(try SyncTestFixtures.activityDataEventCount(updated) == previous.eventCount)+ #expect(updated["aggregationVersion"] as? Int == AggregationVersion.activityData)+ #expect(!outcome.summary.isSyncPending)+ #expect(await fixture.database.activityDataRecords().count == 1)+ }++ @Test func remoteDateDoesNotHideMissingLocalContribution() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let date = HistoryStorage.dateKey(for: now)+ var remote = ActivityDataAggregate(date: date)+ remote.turnCount = 8+ let record = try ActivityDataSyncRecord(+ deviceID: "other", activityData: remote.syncedAggregate,+ recordName: ActivityDataSyncRecord.recordName(deviceID: "other", date: date)+ )+ let root = directory.url+ let store = ActivityDataSyncStore(directoryURL: root)+ try store.saveState(ActivityDataSyncState(deviceID: "local"))+ try store.saveFetchedRecords([record.id: record], cursor: nil)+ try HistoryDatabase(directoryURL: directory.url).append(AppServerEventRecord(activityData: TestFixtures.event(at: now)))+ let sync = SyncService(database: SyncDatabaseFixture(), directoryURL: root, isEnabled: { true })+ let history = HistoryService(directoryURL: directory.url, syncService: sync)+ let snapshot = await history.loadSnapshot()+ let day = UsageHeatmapDay.grid(usage: nil, history: snapshot, columnCount: 1, today: now).compactMap(\.self).first { $0.startDate == date }+ #expect(snapshot.unavailableActivityDataDates.contains(date))+ #expect(day?.activityData.turnCount == nil)+ }++ @Test func incompleteLocalHistoryPreservesCloudDailyUsageUntilSourceIsRepaired() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = SyncDatabaseFixture()+ let sync = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ let history = HistoryService(directoryURL: directory.url, syncService: sync)+ let now = Date()+ let date = HistoryStorage.dateKey(for: now)+ func entry(_ name: String, count: Int64) throws -> Data {+ let observation = TestFixtures.tokenUsageObservation(id: name, at: now, tokenUsage: SyncTestFixtures.counts(count))+ return try AppServerEventRecord(tokenUsage: observation, recordedAt: now).jsonLineData()+ }+ try directory.replaceHistory(entry("first", count: 100) + entry("second", count: 200), date: date)+ let initial = await history.loadSnapshot(synchronize: true)+ #expect(initial.tokenUsageByDate[date] == SyncTestFixtures.counts(300))+ let deviceID = try #require(ActivityDataSyncStore(directoryURL: directory.url).loadState().deviceID)+ let recordID = TokenUsageSync.recordID("tokenUsage_\(deviceID)_\(date)", zoneID: SyncTestFixtures.zone)+ try HistoryDatabase(directoryURL: directory.url).execute("""+ UPDATE aggregates SET tokenUsage = NULL+ """)+ try directory.replaceHistory(entry("first", count: 80) + entry("second", count: 200), date: date)+ try HistoryDatabase(directoryURL: directory.url).execute("UPDATE events SET payload = ? WHERE identity = 'tokenUsage:second'", [.data(Data("broken".utf8))])++ for _ in 0 ..< 2 {+ let partial = await history.loadSnapshot(synchronize: true)+ #expect(partial.tokenUsageByDate[date] == SyncTestFixtures.counts(300))+ let saved = try #require(try await database.records(for: [recordID], desiredKeys: nil)[recordID]?.get())+ #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == SyncTestFixtures.counts(300))+ }+ #expect(await database.savedTypes.filter { $0 == "TokenUsage" }.count == 1)++ try HistoryDatabase(directoryURL: directory.url).execute("""+ UPDATE aggregates SET tokenUsage = NULL+ """)+ try directory.replaceHistory(entry("first", count: 80) + entry("second", count: 200), date: date)+ let repaired = await history.loadSnapshot(synchronize: true)+ #expect(repaired.tokenUsageByDate[date] == SyncTestFixtures.counts(280))+ let saved = try #require(try await database.records(for: [recordID], desiredKeys: nil)[recordID]?.get())+ #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == SyncTestFixtures.counts(280))+ #expect(await database.savedTypes.filter { $0 == "TokenUsage" }.count == 2)+ }+}++private struct HistoryRebuildFixture {+ let directory: TestDirectory+ let database: SyncDatabaseFixture+ let sync: SyncService+ let history: HistoryService+ let date: String+ let local: ActivityDataAggregate++ init() async throws {+ directory = try TestDirectory()+ database = SyncDatabaseFixture()+ sync = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })+ history = HistoryService(directoryURL: directory.url, syncService: sync)+ let now = Date()+ date = HistoryStorage.dateKey(for: now)+ try directory.replaceHistory(AppServerEventRecord(activityData: TestFixtures.event(at: now), recordedAt: now).jsonLineData(), date: date)+ _ = await history.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)+ local = try #require(HistoryDatabase(directoryURL: directory.url).activityDataAggregates().first)+ var remote = local+ remote.eventCount = 9+ _ = await sync.synchronizeIfEnabled(localActivityDataAggregates: [remote], trigger: .manual)+ #expect(await database.activityDataRecords().count == 1)+ }+}diff --git a/Tests/App/History/TokenUsageHistoryStoreTests.swift b/Tests/App/History/TokenUsageHistoryStoreTests.swiftnew file mode 100644index 0000000..41dc2d3--- /dev/null+++ b/Tests/App/History/TokenUsageHistoryStoreTests.swift@@ -0,0 +1,266 @@+import Foundation+import Testing++struct TokenUsageHistoryStoreTests {+ @Test func recordingLeaseTransfersWithoutTwoWriters() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let first = TokenUsageHistoryStore(directoryURL: directory.url)+ let second = TokenUsageHistoryStore(directoryURL: directory.url)+ #expect(try first.acquireRecordingLease())+ #expect(try !second.acquireRecordingLease())+ first.releaseRecordingLease()+ #expect(try second.acquireRecordingLease())+ second.releaseRecordingLease()+ }++ @Test func dailyTokenUsageDeduplicateRetriesAndRebuildAfterCacheDamage() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let first = TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(20))+ let second = TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(30), previous: tokenUsage(20))+ let initial = try await store.recordObservations([first, first, second], now: now)+ #expect(initial.first?.tokenUsage == tokenUsage(50))+ #expect(initial.first?.eventCount == 2)+ #expect(try await TokenUsageHistoryStore(directoryURL: directory.url).refresh(now: now) == initial)+ let database = try HistoryDatabase(directoryURL: directory.url)+ try database.execute("UPDATE aggregates SET tokenUsage = ?", [.data(Data("broken".utf8))])+ #expect(try await store.refresh(now: now) == initial)+ try database.execute("UPDATE aggregates SET tokenUsage = ?", [.data(Data("broken".utf8))])+ let rebuilt = try await store.rebuild(for: [HistoryStorage.dateKey(for: now)])+ #expect(rebuilt.eventCount == 2)+ #expect(try await store.persistedAggregates(now: now) == initial)+ try database.execute("UPDATE aggregates SET tokenUsage = NULL")+ #expect(try await store.refresh(now: now) == initial)+ }++ @Test func tokenRebuildChecksOnlyRequestedDatesWithSourceEvents() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let database = try HistoryDatabase(directoryURL: directory.url)+ let now = TestFixtures.now+ let dates = (0 ..< 5).map { now.addingTimeInterval(Double($0) * 86400) }+ let keys = dates.map(HistoryStorage.dateKey(for:))+ for index in [0, 1, 2] {+ try database.append(AppServerEventRecord(+ tokenUsage: TestFixtures.tokenUsageObservation(at: dates[index], tokenUsage: tokenUsage(10)), recordedAt: now+ ))+ }+ try database.append(event("activity-only", at: dates[3]))+ try database.append(event("mixed", at: dates[0]))+ let requested = [keys[2], keys[0], keys[3], keys[4], keys[2]]+ #expect(try database.tokenUsageAggregates().isEmpty)+ #expect(try database.tokenUsageDates(in: requested) == [keys[0], keys[2]])+ #expect(try database.tokenUsageDates(in: []).isEmpty)++ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let rebuilt = try await store.rebuild(for: requested)+ #expect(rebuilt.dateKeys == [keys[0], keys[2]])+ #expect(rebuilt.eventCount == 2)+ #expect(rebuilt.failedDateKeys.isEmpty)+ #expect(try database.tokenUsageAggregates().map(\.date) == [keys[0], keys[2]])+ #expect(try database.pendingTokenUsageDates() == [keys[1]])+ }++ @Test func observedDateSurvivesDelayedWriteAcrossMidnight() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let midnight = Calendar.current.startOfDay(for: now)+ let before = midnight.addingTimeInterval(-1)+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let first = TestFixtures.tokenUsageObservation(at: before, tokenUsage: tokenUsage(20))+ let second = TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(30), previous: tokenUsage(20))+ let result = try await store.recordObservations([first, second], now: now)+ #expect(TokenUsageAggregate.tokenUsageByDate(result, now: now) == [HistoryStorage.dateKey(for: before): tokenUsage(20), HistoryStorage.dateKey(for: now): tokenUsage(30)])+ let database = try HistoryDatabase(directoryURL: directory.url)+ try database.execute("""+ UPDATE aggregates SET tokenUsage = NULL+ """)+ #expect(try await store.refresh(now: now) == result)+ }++ @Test(arguments: [-1, 1])+ func storedTokenDatesSurviveLocalDateChanges(dayOffset: Int) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = TestFixtures.now+ let localDate = HistoryStorage.dateKey(for: now)+ let storedDate = HistoryStorage.dateKey(for: now.addingTimeInterval(Double(dayOffset) * 86400))+ func sample(_ id: String, _ count: Int64) -> TokenUsageSample {+ let usage = tokenUsage(count)+ return TokenUsageSample(+ id: id, observedAt: now, threadID: "thread", turnID: "turn", turnStartedAt: now,+ current: TokenUsageUpdate(total: usage, last: usage)+ )+ }+ do {+ let database = try HistoryDatabase(directoryURL: directory.url)+ try database.appendTokenUsage(sample("baseline", 0))+ try database.appendTokenUsage(sample("first", 100))+ let initial = try database.aggregateTokenUsage(date: localDate)+ try database.appendTokenUsage(sample("pending", 130))+ // 模拟在另一时区保存的日期, 避免修改并行测试共享的系统时区+ var stored = TokenUsageAggregate(date: storedDate, tokenUsage: initial.tokenUsage, eventCount: initial.eventCount)+ stored.position = initial.position+ try database.transaction {+ try database.execute("INSERT INTO days(date) VALUES (?)", [.text(storedDate)])+ try database.execute("UPDATE events SET date = ?", [.text(storedDate)])+ try database.execute("INSERT INTO aggregates(date, tokenUsage) VALUES (?, ?)", [.text(storedDate), .data(JSONLines.stableEncoder.encode(stored))])+ try database.execute("DELETE FROM days WHERE date = ?", [.text(localDate)])+ }+ }++ let database = try HistoryDatabase(directoryURL: directory.url)+ let latest = sample("after-switch", 150)+ try database.appendTokenUsage(latest)+ try database.appendTokenUsage(latest)+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let snapshot = try await store.loadSnapshot(now: now)+ #expect(snapshot.coverage == .complete)+ #expect(Dictionary(uniqueKeysWithValues: snapshot.aggregates.map { ($0.date, $0.tokenUsage.totalTokens) }) == [storedDate: 130, localDate: 20])+ #expect(snapshot.aggregates.reduce(0) { $0 + $1.eventCount } == 4)+ #expect(try database.pendingTokenUsageDates().isEmpty)+ #expect(try database.tokenUsageSnapshot(threadID: "thread").turns["turn"]?.totalTokens == 150)++ let rebuilt = try await store.rebuild(for: [storedDate, localDate])+ #expect(rebuilt.failedDateKeys.isEmpty)+ #expect(rebuilt.dateKeys == [storedDate, localDate].sorted())+ #expect(rebuilt.eventCount == 4)+ #expect(try await store.persistedAggregates(now: now) == snapshot.aggregates)+ let expectedDates = dayOffset > 0 ? [localDate] : [storedDate, localDate].sorted()+ #expect(TokenUsageAggregate.tokenUsageByDate(snapshot.aggregates, now: now).keys.sorted() == expectedDates)+ #expect(try TokenUsageSyncRecord.dailyRecords(local: snapshot.aggregates, deviceID: "device", now: now).map(\.date) == expectedDates)+ let later = now.addingTimeInterval(86400)+ #expect(TokenUsageAggregate.tokenUsageByDate(snapshot.aggregates, now: later).values.reduce(0) { $0 + $1.totalTokens } == 150)+ }++ @Test func unchangedSnapshotReadsSavedDailyTotalsWithoutReplayingEventsOrWriting() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let saved = try await store.recordObservations([TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(20))], now: now)+ let database = try HistoryDatabase(directoryURL: directory.url)+ try database.execute("UPDATE events SET payload = ? WHERE kind = 'tokenUsage'", [.data(Data("broken".utf8))])+ try database.execute("CREATE TRIGGER reject_tokenUsage BEFORE UPDATE OF tokenUsage ON aggregates BEGIN SELECT RAISE(ABORT, 'unexpected rewrite'); END")+ let snapshot = try await store.loadSnapshot(now: now)+ #expect(snapshot.coverage == .complete)+ #expect(snapshot.aggregates == saved)+ }++ @Test func failedTokenUsageDayPreservesTotalAndHealthyDayStillAdvances() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let yesterday = now.addingTimeInterval(-86400)+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ _ = try await store.recordObservations([TestFixtures.tokenUsageObservation(at: yesterday, tokenUsage: tokenUsage(10))], now: now)+ let bad = TestFixtures.tokenUsageObservation(at: yesterday, tokenUsage: tokenUsage(30))+ try await store.appendObservation(bad, now: now)+ try await store.appendObservation(TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(20)), now: now)+ let database = try HistoryDatabase(directoryURL: directory.url)+ try database.execute("UPDATE events SET payload = ? WHERE identity = ?", [.data(Data("broken".utf8)), .text("tokenUsage:" + bad.id)])+ for _ in 0 ..< 2 {+ let snapshot = try await store.loadSnapshot(now: now)+ #expect(snapshot.coverage == .partial)+ #expect(TokenUsageAggregate.tokenUsageByDate(snapshot.aggregates, now: now) == [+ HistoryStorage.dateKey(for: yesterday): tokenUsage(10), HistoryStorage.dateKey(for: now): tokenUsage(20)+ ])+ }+ let rebuilt = try await store.rebuild(for: [HistoryStorage.dateKey(for: yesterday)])+ #expect(rebuilt.eventCount == 0)+ #expect(rebuilt.failedDateKeys == [HistoryStorage.dateKey(for: yesterday)])+ }++ @Test func missingObservationCannotReplaceSavedDailyTotalDuringRebuild() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let second = TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(20))+ let before = try await store.recordObservations([TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(10)), second], now: now)+ try HistoryDatabase(directoryURL: directory.url).execute("DELETE FROM events WHERE identity = ?", [.text("tokenUsage:" + second.id)])+ let rebuilt = try await store.rebuild(for: [HistoryStorage.dateKey(for: now)])+ #expect(rebuilt.failedDateKeys == [HistoryStorage.dateKey(for: now)])+ #expect(try await store.persistedAggregates(now: now) == before)+ }++ @Test func tokenUsageRetentionRemovesDailyAggregateWithItsObservedEvents() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let now = Date()+ let expired = HistoryStorage.retentionCutoffDate(today: now).addingTimeInterval(-86400)+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ _ = try await store.recordObservations([+ TestFixtures.tokenUsageObservation(at: expired, tokenUsage: tokenUsage(20)),+ TestFixtures.tokenUsageObservation(at: now, tokenUsage: tokenUsage(30))+ ], now: now)+ let database = try HistoryDatabase(directoryURL: directory.url)+ #expect(try database.prune(now: now) == 1)+ #expect(try database.tokenUsageAggregates().count == 1)+ #expect(try database.tokenUsageAggregates().first?.tokenUsage == tokenUsage(30))+ }++ private func tokenUsage(_ count: Int64) -> TokenUsage {+ TokenUsage(inputTokens: count, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: count)+ }++ private func event(_ id: String, at date: Date) -> AppServerEventRecord {+ AppServerEventRecord(activityData: ActivityDataRecord(+ timestamp: date, name: ActivityDataEventKind.toolStarted.rawValue, origin: .main, cwd: "/test",+ toolName: "read", commandActionTypes: nil, model: nil, effort: nil, threadID: "thread", turnID: "turn", agentThreadID: nil, id: id+ ), recordedAt: date)+ }++ @Test func incrementalTokenStorageRetainsAllCountersAcrossRestart() async throws {+ let now = TestFixtures.now+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let tokenUsage = TokenUsage(+ inputTokens: 100,+ cachedInputTokens: 50,+ cacheWriteInputTokens: 10,+ outputTokens: 20,+ reasoningOutputTokens: 5,+ totalTokens: 120+ )+ let observation = TestFixtures.tokenUsageObservation(+ id: "stream", at: now, tokenUsage: tokenUsage+ )+ _ = try await store.recordObservations([observation, observation], now: now)+ let restarted = TokenUsageHistoryStore(directoryURL: directory.url)+ let records = try await restarted.refresh(now: now)+ #expect(records.count == 1)+ #expect(records.first?.tokenUsage == tokenUsage)+ }++ @Test func rebuildUsesObservedRecordsAndContinuesCollecting() async throws {+ let now = TestFixtures.now+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = TokenUsageHistoryStore(directoryURL: directory.url)+ let tokenUsage = TokenUsage(+ inputTokens: 100,+ cachedInputTokens: 30,+ cacheWriteInputTokens: 10,+ outputTokens: 20,+ reasoningOutputTokens: 5,+ totalTokens: 120+ )+ let first = TestFixtures.tokenUsageObservation(id: "stream", at: now, tokenUsage: tokenUsage)+ _ = try await store.recordObservations([first], now: now)+ let rebuilt = try await store.rebuild(for: [CodexDateFormat.dayString(from: now)])+ #expect(rebuilt.eventCount == 1)+ let second = TestFixtures.tokenUsageObservation(+ id: "second", at: now,+ tokenUsage: tokenUsage+ )+ _ = try await store.recordObservations([second], now: now.addingTimeInterval(2))+ let records = try await store.refresh(now: now.addingTimeInterval(2))+ #expect(records.first?.tokenUsage == tokenUsage.adding(tokenUsage))+ }+}diff --git a/Tests/App/History/TokenUsageHistoryTests.swift b/Tests/App/History/TokenUsageHistoryTests.swiftindex f87dce3..00c7d9e 100644--- a/Tests/App/History/TokenUsageHistoryTests.swift+++ b/Tests/App/History/TokenUsageHistoryTests.swift@@ -37,16 +37,6 @@ struct TokenUsageHistoryTests {#expect(try second.load() == ["cursor": 3])}- @Test func heatmapSeparatesAccountIntensityFromLocalDailyMetrics() throws {- var history = HistorySnapshot.empty- history.tokenUsageByDate = [day: tokenUsage(input: 100)]- let grid = UsageHeatmapDay.grid(usage: nil, history: history, columnCount: 2, today: TestFixtures.now)- let today = try #require(grid.compactMap(\.self).first { $0.startDate == day })- #expect(today.tokenState == .unavailable)- #expect(today.tokenUsage?.totalTokens == 110)- #expect(today.activityData.turnCount == 0)- }-private func tokenUsage(input: Int64, cached: Int64 = 20) -> TokenUsage {TokenUsage(inputTokens: input, cachedInputTokens: cached, cacheWriteInputTokens: 5, outputTokens: 10, reasoningOutputTokens: 2, totalTokens: input + 10)}diff --git a/Tests/App/KeepAlive/PowerHelperPackageValidationTests.swift b/Tests/App/KeepAlive/PowerHelperPackageValidationTests.swiftindex fc7350f..19f62a8 100644--- a/Tests/App/KeepAlive/PowerHelperPackageValidationTests.swift+++ b/Tests/App/KeepAlive/PowerHelperPackageValidationTests.swift@@ -13,9 +13,7 @@ struct PowerHelperPackageValidationTests {try await probe.waitForRequests(1)#expect(validation.fingerprint == nil)await probe.finish(0, fingerprint: "current")- for _ in 0 ..< 100 where completions == 0 {- try await Task.sleep(for: .milliseconds(5))- }+ #expect(try await waitForCondition(timeout: .milliseconds(500), pollInterval: .milliseconds(5)) { completions != 0 })#expect(await probe.count == 1)#expect(completions == 1)#expect(validation.fingerprint == "current")@@ -33,9 +31,7 @@ struct PowerHelperPackageValidationTests {validation.refresh()try await probe.waitForRequests(2)await probe.finish(1, fingerprint: "new")- for _ in 0 ..< 100 where completions == 0 {- try await Task.sleep(for: .milliseconds(5))- }+ #expect(try await waitForCondition(timeout: .milliseconds(500), pollInterval: .milliseconds(5)) { completions != 0 })await probe.finish(0, fingerprint: "old")try await Task.sleep(for: .milliseconds(20))#expect(validation.fingerprint == "new")@@ -49,17 +45,13 @@ struct PowerHelperPackageValidationTests {validation.refresh()try await probe.waitForRequests(1)await probe.finish(0, fingerprint: "valid")- for _ in 0 ..< 100 where validation.fingerprint == nil {- try await Task.sleep(for: .milliseconds(5))- }+ #expect(try await waitForCondition(timeout: .milliseconds(500), pollInterval: .milliseconds(5)) { validation.fingerprint != nil })#expect(validation.fingerprint == "valid")validation.refresh()#expect(validation.fingerprint == nil)try await probe.waitForRequests(2)await probe.finish(1, fingerprint: "invalid", issue: .invalid)- for _ in 0 ..< 100 where validation.issue == nil {- try await Task.sleep(for: .milliseconds(5))- }+ #expect(try await waitForCondition(timeout: .milliseconds(500), pollInterval: .milliseconds(5)) { validation.issue != nil })#expect(validation.issue == .invalid)#expect(validation.fingerprint == nil)}diff --git a/Tests/App/KeepAlive/PowerHelperStatusMonitorTests.swift b/Tests/App/KeepAlive/PowerHelperStatusMonitorTests.swiftindex 10b9a25..717e5d7 100644--- a/Tests/App/KeepAlive/PowerHelperStatusMonitorTests.swift+++ b/Tests/App/KeepAlive/PowerHelperStatusMonitorTests.swift@@ -6,7 +6,7 @@ struct PowerHelperStatusMonitorTests {@Test func observationCanRestartAfterCancellationBeforeFirstTick() async {let monitor = PowerHelperStatusMonitor()defer { monitor.cancelObservation() }- let finished = MonitorCheckpoint()+ let finished = TestCheckpoint()monitor.startObservation(interval: .seconds(60)) {Issue.record("Cancelled observation ran")}@@ -21,10 +21,10 @@ struct PowerHelperStatusMonitorTests {@Test func cancelledObservationCannotClearReplacementWhileItsActionFinishes() async {let monitor = PowerHelperStatusMonitor()defer { monitor.cancelObservation() }- let oldEntered = MonitorCheckpoint()- let oldRelease = MonitorCheckpoint()- let oldReturned = MonitorCheckpoint()- let replacementFinished = MonitorCheckpoint()+ let oldEntered = TestCheckpoint()+ let oldRelease = TestCheckpoint()+ let oldReturned = TestCheckpoint()+ let replacementFinished = TestCheckpoint()var replacementTicks = 0monitor.startObservation(interval: .zero) {oldEntered.signal()@@ -130,8 +130,8 @@ private final nonisolated class MonitorConnection: NSXPCConnection {@MainActorprivate final class MonitorPowerHelper: NSObject, CodexBarPowerHelperProtocol {- let statusRequested = MonitorCheckpoint()- let wakeRequested = MonitorCheckpoint()+ let statusRequested = TestCheckpoint()+ let wakeRequested = TestCheckpoint()var statusReply: (@Sendable (Int32, Int, Int, Bool) -> Void)?var wakeReply: (@Sendable (Int32) -> Void)?@@ -164,19 +164,3 @@ private final class MonitorPowerHelper: NSObject, CodexBarPowerHelperProtocol {reply(-1)}}--private final class MonitorCheckpoint {- private var isSignaled = false- private var waiter: CheckedContinuation<Void, Never>?-- func wait() async {- guard !isSignaled else { return }- await withCheckedContinuation { waiter = $0 }- }-- func signal() {- isSignaled = true- waiter?.resume()- waiter = nil- }-}diff --git a/Tests/App/KeepAlive/SystemSleepServiceTests.swift b/Tests/App/KeepAlive/SystemSleepServiceTests.swiftindex fb7eb18..b707208 100644--- a/Tests/App/KeepAlive/SystemSleepServiceTests.swift+++ b/Tests/App/KeepAlive/SystemSleepServiceTests.swift@@ -24,16 +24,12 @@ struct SystemSleepServiceTests {displayReleaseRetryDelays: [.milliseconds(1)])#expect(service.beginPreventingDisplaySleep() == kIOReturnSuccess)- for _ in 0 ..< 100 where !didDeclare {- try await Task.sleep(for: .milliseconds(1))- }+ #expect(try await waitForCondition(timeout: .milliseconds(100), pollInterval: .milliseconds(1)) { didDeclare })#expect(didDeclare)#expect(service.endPreventingDisplaySleep() == kIOReturnError)#expect(!service.isPreventingDisplaySleep)#expect(service.hasDisplaySleepResources)- for _ in 0 ..< 100 where service.hasDisplaySleepResources {- try await Task.sleep(for: .milliseconds(1))- }+ #expect(try await waitForCondition(timeout: .milliseconds(100), pollInterval: .milliseconds(1)) { !service.hasDisplaySleepResources })#expect(!service.hasDisplaySleepResources)#expect(releaseCounts[failedID] == 2)#expect(releaseCounts[userActivityFails ? 1 : 2] == 1)@@ -54,9 +50,7 @@ struct SystemSleepServiceTests {)#expect(service.beginPreventingDisplaySleep() == kIOReturnSuccess)#expect(service.endPreventingDisplaySleep() == kIOReturnError)- for _ in 0 ..< 100 where releases < 3 {- try await Task.sleep(for: .milliseconds(1))- }+ #expect(try await waitForCondition(timeout: .milliseconds(100), pollInterval: .milliseconds(1)) { releases >= 3 })try await Task.sleep(for: .milliseconds(10))#expect(releases == 3)#expect(service.hasDisplaySleepResources)diff --git a/Tests/App/Notifications/TaskWaitingNotificationTests.swift b/Tests/App/Notifications/TaskWaitingNotificationTests.swiftindex 4cbbb03..36d82ba 100644--- a/Tests/App/Notifications/TaskWaitingNotificationTests.swift+++ b/Tests/App/Notifications/TaskWaitingNotificationTests.swift@@ -9,7 +9,9 @@ struct TaskWaitingNotificationTests {defer { fixture.cleanUp() }try await fixture.start()try fixture.publishWaiting(blockingInput: blockingInput)- try await waitUntil { fixture.delivery.delivered == [fixture.identifier] }+ try #require(try await waitForCondition(timeout: .seconds(2), pollInterval: .milliseconds(5)) {+ fixture.delivery.delivered == [fixture.identifier]+ }, "Notification operation did not reach the expected state")#expect(fixture.delivery.attempts == [fixture.identifier])try fixture.resolveWaiting()#expect(fixture.delivery.delivered.isEmpty)@@ -40,7 +42,9 @@ struct TaskWaitingNotificationTests {try await fixture.start()fixture.delivery.suspendsSubmissions = truelet submission = try fixture.enterWaiting(blockingInput: blockingInput)- try await waitUntil { fixture.delivery.hasPendingSubmission }+ try #require(try await waitForCondition(timeout: .seconds(2), pollInterval: .milliseconds(5)) {+ fixture.delivery.hasPendingSubmission+ }, "Notification operation did not reach the expected state")try fixture.resolveWaiting()#expect(fixture.delivery.removals == [[fixture.identifier]])@@ -94,14 +98,6 @@ struct TaskWaitingNotificationTests {}}-private func waitUntil(_ condition: () -> Bool) async throws {- let deadline = ContinuousClock.now.advanced(by: .seconds(2))- while !condition(), ContinuousClock.now < deadline {- try await Task.sleep(for: .milliseconds(5))- }- try #require(condition(), "Notification operation did not reach the expected state")-}-private final class Fixture {let directory: TestDirectorylet preferences: TestPreferences@@ -146,7 +142,9 @@ private final class Fixture {func start() async throws {service.start()- try await waitUntil { self.settings.canDeliver }+ try #require(try await waitForCondition(timeout: .seconds(2), pollInterval: .milliseconds(5)) {+ self.settings.canDeliver+ }, "Notification operation did not reach the expected state")}func enterWaiting(blockingInput: Bool) throws -> Task<Bool, Never> {diff --git a/Tests/App/Presentation/ActivityPresentationTests.swift b/Tests/App/Presentation/ActivityPresentationTests.swiftindex 9554027..2c2a669 100644--- a/Tests/App/Presentation/ActivityPresentationTests.swift+++ b/Tests/App/Presentation/ActivityPresentationTests.swift@@ -32,7 +32,9 @@ struct ActivityPresentationTests {monitor.isActivitySourceHealthy = truemonitor.turnTransitionNotBefore = startedAtmonitor.terminalPresentationNotBefore = startedAt- monitor.isProtectionRecoveryInProgress = scenario == "recovering"+ if scenario == "recovering" {+ monitor.beginProtectionRecovery()+ }var notices = 0let subscription = monitor.transitionPublisher.sink { transition inif case .completed = transition {@@ -166,4 +168,45 @@ struct ActivityPresentationTests {#expect(glow.state != .hidden)}}++ @Test func statusItemTerminalExpiresAtTenSecondsWhileCardKeepsHistory() {+ let completion = ActivityCompletion(id: UUID(), projectName: nil, modelName: nil, effort: nil, completedAt: TestFixtures.now, duration: 30)+ let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])+ #expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(9.999)) == .completed(completion))+ #expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(10)) == .idle)+ #expect(snapshot.primaryActivity == .completed(completion))+ #expect(snapshot.hasTaskCenterContent)+ #expect(!snapshot.hasActiveTasks)+ }++ @Test func waitingTaskTakesPriorityOverRunningTask() {+ let waiting = task()+ let running = task()+ let snapshot = ActivitySnapshot(waitingTasks: [waiting], runningTasks: [running], recentCompletions: [], recentTerminations: [])+ #expect(snapshot.primaryActivity == .waiting(waiting))+ #expect(snapshot.activeCount == 2)+ #expect(snapshot.statusItemActivityExpiration == nil)+ }++ @Test(arguments: [false, true])+ func accountFailureKeepsLiveTaskIcon(waiting: Bool) {+ let task = task()+ let activity = ActivitySnapshot(+ waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task],+ recentCompletions: [], recentTerminations: []+ )+ let state = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: activity)+ #expect(state.symbolName(at: TestFixtures.now) == (waiting ? "person.badge.key.fill" : "person.badge.clock.fill"))+ let idle = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: .empty)+ #expect(idle.symbolName(at: TestFixtures.now) == "person.slash.fill")+ }++ private func task() -> ActivityTaskSnapshot {+ ActivityTaskSnapshot(+ id: UUID(),+ projectName: nil, modelName: nil, effort: nil,+ startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,+ activeSubagentCount: nil+ )+ }}diff --git a/Tests/App/Presentation/DateAndPresentationTests.swift b/Tests/App/Presentation/DateAndPresentationTests.swiftdeleted file mode 100644index bcdd31a..0000000--- a/Tests/App/Presentation/DateAndPresentationTests.swift+++ /dev/null@@ -1,139 +0,0 @@-import Foundation-import Testing--struct DateAndPresentationTests {- @Test(arguments: [- (1000, 1.0, "K"),- (1049, 1.0, "K"),- (1050, 1.1, "K"),- (999949, 999.9, "K"),- (999950, 1000.0, "K"),- (1000000, 1.0, "M"),- (554400000, 554.4, "M"),- (999950000, 1000.0, "M"),- (1000000000, 1.0, "B"),- (1100000000, 1.1, "B")- ])- func tokenCountsPreserveUnitThresholdsAndJoinLocalizedNumbers(tokens: Int, number: Double, unit: String) {- let expectedNumber = number.formatted(.number.precision(.fractionLength(0 ... 1)).locale(.autoupdatingCurrent))- #expect(TokenCountFormatter.text(from: tokens) == expectedNumber + unit)- }-- @Test(arguments: [Int.min, -1000, -1, 0, 999])- func tokenCountsBelowAbbreviationThresholdStayPlainIntegers(tokens: Int) {- #expect(TokenCountFormatter.text(from: tokens) == String(tokens))- }-- @Test(arguments: [- (-1.0, "0 秒"),- (0.0, "0 秒"),- (21.0, "21 秒"),- (59.6, "1 分钟 0 秒"),- (80.0, "1 分钟 20 秒"),- (3599.6, "1 小时 0 分钟"),- (4800.0, "1 小时 20 分钟")- ])- func chineseDurationSeparatesValuesAndUnits(interval: TimeInterval, expected: String) {- #expect(CodexDurationFormat.activityText(for: interval, locale: Locale(identifier: "zh_CN")) == expected)- }-- @Test(arguments: ["en_US", "fr_FR"])- func durationPreservesExistingLocalizedSeparators(localeIdentifier: String) {- let locale = Locale(identifier: localeIdentifier)- let expected = Duration.seconds(80).formatted(- .units(allowed: [.minutes, .seconds], width: .abbreviated, zeroValueUnits: .show(length: 1), fractionalPart: .hide(rounded: .down))- .locale(locale)- )- #expect(CodexDurationFormat.activityText(for: 80, locale: locale) == expected)- }-- @Test(arguments: ["2026-02-29", "2026-04-31", "2026-00-10", "2026-13-01", "2026-1-01", "2026-01-1", "0000-01-01", "garbage"])- func dateKeysRejectImpossibleOrNoncanonicalDates(_ value: String) {- #expect(CodexDateFormat.dayDate(from: value) == nil)- }-- @Test func leapDayRoundTrips() throws {- let date = try #require(CodexDateFormat.dayDate(from: "2024-02-29"))- #expect(CodexDateFormat.dayString(from: date) == "2024-02-29")- }-- @Test func weekGridStartsSundayAndLeavesFutureDaysBlankAcrossDST() throws {- var calendar = Calendar(identifier: .gregorian)- calendar.timeZone = try #require(TimeZone(identifier: "America/Los_Angeles"))- calendar.firstWeekday = 2- let today = try #require(calendar.date(from: DateComponents(year: 2026, month: 3, day: 10, hour: 12)))- let grid = CodexWeekGrid.dates(columnCount: 2, today: today, calendar: calendar)- #expect(grid.count == 14)- #expect(grid.compactMap(\.self).count == 10)- #expect(try calendar.component(.weekday, from: #require(grid[0])) == 1)- #expect(try calendar.component(.weekday, from: #require(grid[7])) == 1)- #expect(grid.suffix(4).allSatisfy { $0 == nil })- #expect(CodexWeekGrid.dates(columnCount: 0, today: today, calendar: calendar).isEmpty)- }-- @Test func heatmapDistinguishesTodayPendingFromUnavailableAndHistoricalZero() throws {- let today = try #require(CodexDateFormat.dayDate(from: "2026-09-15"))- let summary = try TestFixtures.decode(UsageSummary.self, "{}")- let usage = CodexUsageSnapshot(summary: summary, dailyBuckets: [])- let grid = UsageHeatmapDay.grid(usage: usage, history: .empty, columnCount: 2, today: today).compactMap(\.self)- #expect(grid.last?.tokenState == .pending)- #expect(grid.first?.tokenState == .available(0))- let unavailable = UsageHeatmapDay.grid(usage: nil, history: .empty, columnCount: 2, today: today).compactMap(\.self)- #expect(unavailable.allSatisfy { $0.tokenState == .unavailable })- }-- @Test func heatmapSelectionReadsLatestDayDataByDate() {- let date = "2026-09-15"- let selection = UsageHeatmapSelection(dateID: date)- let initial = UsageHeatmapDay(startDate: date, tokenState: .pending, activityData: .empty(startDate: date))- let updated = UsageHeatmapDay(- startDate: date, tokenState: .available(120), activityData: .unavailable(startDate: date), tokenUsage: .zero- )- let unrelated = UsageHeatmapDay(startDate: "2026-09-14", tokenState: .available(5), activityData: .empty(startDate: "2026-09-14"))- #expect(selection.day(in: [initial, unrelated]) == initial)- #expect(selection.day(in: [nil, unrelated, updated]) == updated)- #expect(selection.day(in: [nil, unrelated]) == nil)- #expect(selection.day(in: []) == nil)- }-- @Test func statusItemTerminalExpiresAtTenSecondsWhileCardKeepsHistory() {- let completion = ActivityCompletion(id: UUID(), projectName: nil, modelName: nil, effort: nil, completedAt: TestFixtures.now, duration: 30)- let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])- #expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(9.999)) == .completed(completion))- #expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(10)) == .idle)- #expect(snapshot.primaryActivity == .completed(completion))- #expect(snapshot.hasTaskCenterContent)- #expect(!snapshot.hasActiveTasks)- }-- @Test func waitingTaskTakesPriorityOverRunningTask() {- let waiting = task()- let running = task()- let snapshot = ActivitySnapshot(waitingTasks: [waiting], runningTasks: [running], recentCompletions: [], recentTerminations: [])- #expect(snapshot.primaryActivity == .waiting(waiting))- #expect(snapshot.activeCount == 2)- #expect(snapshot.statusItemActivityExpiration == nil)- }-- private func task() -> ActivityTaskSnapshot {- ActivityTaskSnapshot(- id: UUID(),- projectName: nil, modelName: nil, effort: nil,- startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,- activeSubagentCount: nil- )- }-- @Test(arguments: [false, true])- func accountFailureKeepsLiveTaskIcon(waiting: Bool) {- let task = task()- let activity = ActivitySnapshot(- waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task],- recentCompletions: [], recentTerminations: []- )- let state = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: activity)- #expect(state.symbolName(at: TestFixtures.now) == (waiting ? "person.badge.key.fill" : "person.badge.clock.fill"))- let idle = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: .empty)- #expect(idle.symbolName(at: TestFixtures.now) == "person.slash.fill")- }-}diff --git a/Tests/App/Presentation/DisplayFormattingTests.swift b/Tests/App/Presentation/DisplayFormattingTests.swiftnew file mode 100644index 0000000..97a3403--- /dev/null+++ b/Tests/App/Presentation/DisplayFormattingTests.swift@@ -0,0 +1,59 @@+import Foundation+import Testing++struct DisplayFormattingTests {+ @Test(arguments: [+ (1000, 1.0, "K"),+ (1049, 1.0, "K"),+ (1050, 1.1, "K"),+ (999949, 999.9, "K"),+ (999950, 1000.0, "K"),+ (1000000, 1.0, "M"),+ (554400000, 554.4, "M"),+ (999950000, 1000.0, "M"),+ (1000000000, 1.0, "B"),+ (1100000000, 1.1, "B")+ ])+ func tokenCountsPreserveUnitThresholdsAndJoinLocalizedNumbers(tokens: Int, number: Double, unit: String) {+ let expectedNumber = number.formatted(.number.precision(.fractionLength(0 ... 1)).locale(.autoupdatingCurrent))+ #expect(TokenCountFormatter.text(from: tokens) == expectedNumber + unit)+ }++ @Test(arguments: [Int.min, -1000, -1, 0, 999])+ func tokenCountsBelowAbbreviationThresholdStayPlainIntegers(tokens: Int) {+ #expect(TokenCountFormatter.text(from: tokens) == String(tokens))+ }++ @Test(arguments: [+ (-1.0, "0 秒"),+ (0.0, "0 秒"),+ (21.0, "21 秒"),+ (59.6, "1 分钟 0 秒"),+ (80.0, "1 分钟 20 秒"),+ (3599.6, "1 小时 0 分钟"),+ (4800.0, "1 小时 20 分钟")+ ])+ func chineseDurationSeparatesValuesAndUnits(interval: TimeInterval, expected: String) {+ #expect(CodexDurationFormat.activityText(for: interval, locale: Locale(identifier: "zh_CN")) == expected)+ }++ @Test(arguments: ["en_US", "fr_FR"])+ func durationPreservesExistingLocalizedSeparators(localeIdentifier: String) {+ let locale = Locale(identifier: localeIdentifier)+ let expected = Duration.seconds(80).formatted(+ .units(allowed: [.minutes, .seconds], width: .abbreviated, zeroValueUnits: .show(length: 1), fractionalPart: .hide(rounded: .down))+ .locale(locale)+ )+ #expect(CodexDurationFormat.activityText(for: 80, locale: locale) == expected)+ }++ @Test(arguments: ["2026-02-29", "2026-04-31", "2026-00-10", "2026-13-01", "2026-1-01", "2026-01-1", "0000-01-01", "garbage"])+ func dateKeysRejectImpossibleOrNoncanonicalDates(_ value: String) {+ #expect(CodexDateFormat.dayDate(from: value) == nil)+ }++ @Test func leapDayRoundTrips() throws {+ let date = try #require(CodexDateFormat.dayDate(from: "2024-02-29"))+ #expect(CodexDateFormat.dayString(from: date) == "2024-02-29")+ }+}diff --git a/Tests/App/Presentation/UsageHeatmapTests.swift b/Tests/App/Presentation/UsageHeatmapTests.swiftindex c0fb170..ac42fed 100644--- a/Tests/App/Presentation/UsageHeatmapTests.swift+++ b/Tests/App/Presentation/UsageHeatmapTests.swift@@ -275,4 +275,68 @@ struct UsageHeatmapTests {totalTokens: input + output)}++ @Test func weekGridStartsSundayAndLeavesFutureDaysBlankAcrossDST() throws {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = try #require(TimeZone(identifier: "America/Los_Angeles"))+ calendar.firstWeekday = 2+ let today = try #require(calendar.date(from: DateComponents(year: 2026, month: 3, day: 10, hour: 12)))+ let grid = CodexWeekGrid.dates(columnCount: 2, today: today, calendar: calendar)+ #expect(grid.count == 14)+ #expect(grid.compactMap(\.self).count == 10)+ #expect(try calendar.component(.weekday, from: #require(grid[0])) == 1)+ #expect(try calendar.component(.weekday, from: #require(grid[7])) == 1)+ #expect(grid.suffix(4).allSatisfy { $0 == nil })+ #expect(CodexWeekGrid.dates(columnCount: 0, today: today, calendar: calendar).isEmpty)+ }++ @Test func heatmapDistinguishesTodayPendingFromUnavailableAndHistoricalZero() throws {+ let today = try #require(CodexDateFormat.dayDate(from: "2026-09-15"))+ let summary = try TestFixtures.decode(UsageSummary.self, "{}")+ let usage = CodexUsageSnapshot(summary: summary, dailyBuckets: [])+ let grid = UsageHeatmapDay.grid(usage: usage, history: .empty, columnCount: 2, today: today).compactMap(\.self)+ #expect(grid.last?.tokenState == .pending)+ #expect(grid.first?.tokenState == .available(0))+ let unavailable = UsageHeatmapDay.grid(usage: nil, history: .empty, columnCount: 2, today: today).compactMap(\.self)+ #expect(unavailable.allSatisfy { $0.tokenState == .unavailable })+ }++ @Test func heatmapSelectionReadsLatestDayDataByDate() {+ let date = "2026-09-15"+ let selection = UsageHeatmapSelection(dateID: date)+ let initial = UsageHeatmapDay(startDate: date, tokenState: .pending, activityData: .empty(startDate: date))+ let updated = UsageHeatmapDay(+ startDate: date, tokenState: .available(120), activityData: .unavailable(startDate: date), tokenUsage: .zero+ )+ let unrelated = UsageHeatmapDay(startDate: "2026-09-14", tokenState: .available(5), activityData: .empty(startDate: "2026-09-14"))+ #expect(selection.day(in: [initial, unrelated]) == initial)+ #expect(selection.day(in: [nil, unrelated, updated]) == updated)+ #expect(selection.day(in: [nil, unrelated]) == nil)+ #expect(selection.day(in: []) == nil)+ }++ @Test func partialSourcesKeepKnownValuesVisible() {+ let now = Date()+ let date = HistoryStorage.dateKey(for: now)+ var aggregate = ActivityDataAggregate(date: date)+ aggregate.turnCount = 3+ var snapshot = HistorySnapshot(activityData: [aggregate.metrics])+ snapshot.isActivityDataComplete = false+ let day = UsageHeatmapDay.grid(usage: nil, history: snapshot, columnCount: 1, today: now).compactMap(\.self).first { $0.startDate == date }+ #expect(day?.activityData.turnCount == 3)+ }++ @Test func heatmapSeparatesAccountIntensityFromLocalDailyMetrics() throws {+ let day = HistoryStorage.dateKey(for: TestFixtures.now)+ var history = HistorySnapshot.empty+ history.tokenUsageByDate = [day: TokenUsage(+ inputTokens: 100, cachedInputTokens: 20, cacheWriteInputTokens: 5,+ outputTokens: 10, reasoningOutputTokens: 2, totalTokens: 110+ )]+ let grid = UsageHeatmapDay.grid(usage: nil, history: history, columnCount: 2, today: TestFixtures.now)+ let today = try #require(grid.compactMap(\.self).first { $0.startDate == day })+ #expect(today.tokenState == .unavailable)+ #expect(today.tokenUsage?.totalTokens == 110)+ #expect(today.activityData.turnCount == 0)+ }}diff --git a/Tests/App/Presentation/SettingsTests.swift b/Tests/App/Settings/MainPanelSettingsTests.swiftsimilarity index 52%rename from Tests/App/Presentation/SettingsTests.swiftrename to Tests/App/Settings/MainPanelSettingsTests.swiftindex 5623843..9dbeab4 100644--- a/Tests/App/Presentation/SettingsTests.swift+++ b/Tests/App/Settings/MainPanelSettingsTests.swift@@ -1,79 +1,7 @@import Foundationimport Testing-struct SettingsTests {- @Test(arguments: [false, true])- func syncPreferenceDefaultsOffAndReadsStoredValue(_ enabled: Bool) throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- let defaults = preferences.defaults- #expect(!SyncSettings.isEnabled(defaults: defaults))- defaults.set(enabled, forKey: "Sync.isEnabled")- #expect(SyncSettings.isEnabled(defaults: defaults) == enabled)- }-- @Test func protectionPreferenceFallsBackPersistsAndRefreshes() throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- let defaults = preferences.defaults- #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .oneHour)- defaults.set("invalid", forKey: "Protection.inactivityDurationSeconds")- let settings = ProtectionSettings(defaults: defaults)- #expect(settings.inactivityDuration == .oneHour)- settings.setInactivityDuration(.thirtyMinutes)- #expect(defaults.integer(forKey: "Protection.inactivityDurationSeconds") == 1800)- #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .thirtyMinutes)- for duration in [ProtectionSettings.InactivityDuration.twoHours, .fourHours] {- defaults.set(duration.rawValue, forKey: "Protection.inactivityDurationSeconds")- settings.refresh()- #expect(settings.inactivityDuration == duration)- #expect(ProtectionSettings(defaults: defaults).inactivityDuration == duration)- }- }-- @Test(arguments: DataUpdateInterval.allCases)- func dataUpdateIntervalPersistsAndUpdatesCountdown(_ interval: DataUpdateInterval) throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- let service = makeStatusService(suiteName: preferences.suite)- let model = CodexStatusViewModel(service: service, defaults: preferences.defaults)- #expect(model.dataUpdateInterval == .oneMinute)- model.setDataUpdateInterval(interval)- #expect(model.autoRefreshInterval == interval.duration)- let restored = CodexStatusViewModel(service: service, defaults: preferences.defaults)- #expect(restored.dataUpdateInterval == interval)- #expect(restored.autoRefreshInterval == interval.duration)- #expect(!model.isRefreshing)- #expect(model.autoRefreshCountdownStartedAt == nil)- }-- @Test(arguments: [0, -60, 90, 1200])- func invalidDataUpdateIntervalUsesDefault(_ seconds: Int) throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- preferences.defaults.set(seconds, forKey: "DataUpdate.intervalSeconds")- let model = CodexStatusViewModel(- service: makeStatusService(suiteName: preferences.suite),- defaults: preferences.defaults- )- #expect(model.dataUpdateInterval == .oneMinute)- }-- @Test func dataUpdateIntervalRespectsElapsedTimeAndNewRefreshOrigin() {- let start = TestFixtures.now- let now = start.addingTimeInterval(150)- #expect(DataUpdateInterval.tenMinutes.remainingTime(since: start, now: now) == 450)- #expect(DataUpdateInterval.threeMinutes.remainingTime(since: start, now: now) == 30)- #expect(DataUpdateInterval.twoMinutes.remainingTime(since: start, now: now) == 0)- #expect(DataUpdateInterval.oneMinute.remainingTime(since: nil, now: now) == 0)- #expect(DataUpdateInterval.oneMinute.remainingTime(since: start, now: start.addingTimeInterval(60)) == 0)- #expect(DataUpdateInterval.fiveMinutes.remainingTime(since: now, now: now) == 300)- }-- private nonisolated func makeStatusService(suiteName: String) -> CodexStatusService {- CodexStatusService(socketURL: URL(fileURLWithPath: "/tmp/\(suiteName).sock"), logStorage: nil)- }-+struct MainPanelSettingsTests {@Test func mainPanelAnimationsPreserveStoredPreferenceAndDefault() throws {let preferences = try TestPreferences()defer { preferences.remove() }@@ -126,31 +54,6 @@ struct SettingsTests {#expect(settings.usageHeatmapMode == .daily)}- @Test func rebuildRangeIncludesDatesWithoutActivityEvents() {- let range = RebuildDateRange.starting(at: "2026-09-15").completing(with: "2026-09-17")- #expect(range.dateKeys == ["2026-09-15", "2026-09-16", "2026-09-17"])- #expect(RebuildDateRange.starting(at: "2026-09-15").dateKeys.isEmpty)- #expect(RebuildDateRange.starting(at: "2026-09-15").completing(with: "2026-09-15").dateKeys == ["2026-09-15"])- }-- @Test func autoResetDefaultsOffAndRepairsInvalidLeadTime() throws {- let preferences = try TestPreferences()- defer { preferences.remove() }- let defaults = preferences.defaults- let initial = AutoResetSettings(defaults: defaults)- #expect(!initial.isEnabled)- #expect(initial.leadTime == .thirtyMinutes)- defaults.set(123, forKey: "AutoReset.leadTimeSeconds")- let repaired = AutoResetSettings(defaults: defaults)- #expect(repaired.leadTime == .thirtyMinutes)- #expect(defaults.integer(forKey: "AutoReset.leadTimeSeconds") == 1800)- repaired.setEnabled(true)- repaired.setLeadTime(.sixHours)- initial.refresh()- #expect(initial.isEnabled)- #expect(initial.leadTime == .sixHours)- }-@Test func layoutRepairsDuplicateOrderAndAlwaysKeepsAVisibleSection() {let layout = MainPanelLayout(orderedSections: [.usage, .usage, .activity], hiddenSections: Set(MainPanelSection.allCases))#expect(layout.orderedSections == [.usage, .activity, .account, .quota, .serviceStatus, .status])diff --git a/Tests/App/Settings/SettingsTests.swift b/Tests/App/Settings/SettingsTests.swiftnew file mode 100644index 0000000..6d05a32--- /dev/null+++ b/Tests/App/Settings/SettingsTests.swift@@ -0,0 +1,58 @@+import Foundation+import Testing++struct SettingsTests {+ @Test(arguments: [false, true])+ func syncPreferenceDefaultsOffAndReadsStoredValue(_ enabled: Bool) throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let defaults = preferences.defaults+ #expect(!SyncSettings.isEnabled(defaults: defaults))+ defaults.set(enabled, forKey: "Sync.isEnabled")+ #expect(SyncSettings.isEnabled(defaults: defaults) == enabled)+ }++ @Test func protectionPreferenceFallsBackPersistsAndRefreshes() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let defaults = preferences.defaults+ #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .oneHour)+ defaults.set("invalid", forKey: "Protection.inactivityDurationSeconds")+ let settings = ProtectionSettings(defaults: defaults)+ #expect(settings.inactivityDuration == .oneHour)+ settings.setInactivityDuration(.thirtyMinutes)+ #expect(defaults.integer(forKey: "Protection.inactivityDurationSeconds") == 1800)+ #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .thirtyMinutes)+ for duration in [ProtectionSettings.InactivityDuration.twoHours, .fourHours] {+ defaults.set(duration.rawValue, forKey: "Protection.inactivityDurationSeconds")+ settings.refresh()+ #expect(settings.inactivityDuration == duration)+ #expect(ProtectionSettings(defaults: defaults).inactivityDuration == duration)+ }+ }++ @Test func rebuildRangeIncludesDatesWithoutActivityEvents() {+ let range = RebuildDateRange.starting(at: "2026-09-15").completing(with: "2026-09-17")+ #expect(range.dateKeys == ["2026-09-15", "2026-09-16", "2026-09-17"])+ #expect(RebuildDateRange.starting(at: "2026-09-15").dateKeys.isEmpty)+ #expect(RebuildDateRange.starting(at: "2026-09-15").completing(with: "2026-09-15").dateKeys == ["2026-09-15"])+ }++ @Test func autoResetDefaultsOffAndRepairsInvalidLeadTime() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let defaults = preferences.defaults+ let initial = AutoResetSettings(defaults: defaults)+ #expect(!initial.isEnabled)+ #expect(initial.leadTime == .thirtyMinutes)+ defaults.set(123, forKey: "AutoReset.leadTimeSeconds")+ let repaired = AutoResetSettings(defaults: defaults)+ #expect(repaired.leadTime == .thirtyMinutes)+ #expect(defaults.integer(forKey: "AutoReset.leadTimeSeconds") == 1800)+ repaired.setEnabled(true)+ repaired.setLeadTime(.sixHours)+ initial.refresh()+ #expect(initial.isEnabled)+ #expect(initial.leadTime == .sixHours)+ }+}diff --git a/Tests/App/Support/ActivityUpdateFixtures.swift b/Tests/App/Support/ActivityUpdateFixtures.swiftindex 18ecfe0..1ceff8b 100644--- a/Tests/App/Support/ActivityUpdateFixtures.swift+++ b/Tests/App/Support/ActivityUpdateFixtures.swift@@ -6,6 +6,18 @@ import Foundationvar graph = ActivityTaskGraph()}+extension ActivityEventDrainResult {+ enum Status { case completed, partial, sourceUnavailable, cancelled }++ var status: Status {+ switch self {+ case let .update(update): update.isComplete ? .completed : .partial+ case .sourceUnavailable: .sourceUnavailable+ case .cancelled: .cancelled+ }+ }+}+@MainActorextension AppServerActivityReader {init(@@ -61,6 +73,7 @@ enum ActivityFixtureBatch {extension ActivityMonitor {private static var fixtureRevision: UInt64 = 0private static let fixtureReaderID = UUID()+ private static let fixtureRecoveryID = UUID()/// 展示和保护测试从任务图产生真实 update, 每次经过 monitor 的正式消费接口func acceptFixtureGraph(_ graph: ActivityTaskGraph, phase: ActivityUpdate.Phase = .lifecycleChanged, transitions: [ActivityTransition] = []) {@@ -72,7 +85,8 @@ extension ActivityMonitor {graph: graph,transitions: transitions,terminalEvents: graph.terminalEvents,- backfilledTasks: graph.backfilledTasks+ backfilledTasks: graph.backfilledTasks,+ recoveryID: Self.fixtureRecoveryID))self.graph.terminalEvents.removeAll()self.graph.backfilledTasks.removeAll()diff --git a/Tests/App/Support/AsyncTestSupport.swift b/Tests/App/Support/AsyncTestSupport.swiftnew file mode 100644index 0000000..7a0b3e0--- /dev/null+++ b/Tests/App/Support/AsyncTestSupport.swift@@ -0,0 +1,32 @@+import Foundation++@MainActor+func waitForCondition(+ timeout: Duration,+ pollInterval: Duration,+ _ condition: () async -> Bool+) async throws -> Bool {+ let deadline = ContinuousClock.now.advanced(by: timeout)+ while await !condition(), ContinuousClock.now < deadline {+ try await Task.sleep(for: pollInterval)+ }+ return await condition()+}++@MainActor+final class TestCheckpoint {+ private var isSignaled = false+ private var waiters: [CheckedContinuation<Void, Never>] = []++ func wait() async {+ guard !isSignaled else { return }+ await withCheckedContinuation { waiters.append($0) }+ }++ func signal() {+ isSignaled = true+ let pending = waiters+ waiters.removeAll()+ pending.forEach { $0.resume() }+ }+}diff --git a/Tests/App/Support/RefreshTaskCoordinatorTests.swift b/Tests/App/Support/RefreshTaskCoordinatorTests.swiftindex f0f199e..d404ce1 100644--- a/Tests/App/Support/RefreshTaskCoordinatorTests.swift+++ b/Tests/App/Support/RefreshTaskCoordinatorTests.swift@@ -6,12 +6,12 @@ struct RefreshTaskCoordinatorTests {@Test func supersededResultCannotCommitOrEndNewerRefresh() async {let coordinator = RefreshTaskCoordinator()defer { coordinator.cancel() }- let oldEntered = RefreshCheckpoint()- let oldRelease = RefreshCheckpoint()- let oldReturned = RefreshCheckpoint()- let newEntered = RefreshCheckpoint()- let newRelease = RefreshCheckpoint()- let newFinished = RefreshCheckpoint()+ let oldEntered = TestCheckpoint()+ let oldRelease = TestCheckpoint()+ let oldReturned = TestCheckpoint()+ let newEntered = TestCheckpoint()+ let newRelease = TestCheckpoint()+ let newFinished = TestCheckpoint()var committed: [Int] = []var refreshing: [Bool] = []coordinator.run(@@ -52,9 +52,9 @@ struct RefreshTaskCoordinatorTests {@Test func cancellationInvalidatesGenerationEvenIfOperationReturns() async {let coordinator = RefreshTaskCoordinator()- let entered = RefreshCheckpoint()- let release = RefreshCheckpoint()- let returned = RefreshCheckpoint()+ let entered = TestCheckpoint()+ let release = TestCheckpoint()+ let returned = TestCheckpoint()var committed = falselet generation = coordinator.start { generation inentered.signal()@@ -74,21 +74,3 @@ struct RefreshTaskCoordinatorTests {#expect(!finished)}}--@MainActor-private final class RefreshCheckpoint {- private var isSignaled = false- private var waiters: [CheckedContinuation<Void, Never>] = []-- func wait() async {- guard !isSignaled else { return }- await withCheckedContinuation { waiters.append($0) }- }-- func signal() {- isSignaled = true- let pending = waiters- waiters.removeAll()- pending.forEach { $0.resume() }- }-}diff --git a/Tests/App/Support/TestSupport.swift b/Tests/App/Support/TestSupport.swiftindex 8953e95..97d8685 100644--- a/Tests/App/Support/TestSupport.swift+++ b/Tests/App/Support/TestSupport.swift@@ -57,6 +57,14 @@ nonisolated enum TestFixtures {aggregate.turnIDs = nilreturn aggregate}++ static func tokenUsage(_ total: Int64) -> TokenUsage {+ TokenUsage(inputTokens: total, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: total)+ }++ static func tokenSample(_ total: Int64, thread: String = "main", turn: String = "root", at: Date = now, start: Date? = nil) -> TokenUsageSample {+ TokenUsageSample(observedAt: at, threadID: thread, turnID: turn, turnStartedAt: start, current: TokenUsageUpdate(total: tokenUsage(total), last: tokenUsage(1)))+ }}nonisolated struct TestDirectory {diff --git a/Tests/App/Sync/ActivityDataSyncStoreTests.swift b/Tests/App/Sync/ActivityDataSyncStoreTests.swiftnew file mode 100644index 0000000..71b9c29--- /dev/null+++ b/Tests/App/Sync/ActivityDataSyncStoreTests.swift@@ -0,0 +1,97 @@+import Foundation+import Testing++struct ActivityDataSyncStoreTests {+ @Test func activityDataCacheCommitsRecordsAndCursorTogether() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = ActivityDataSyncStore(directoryURL: directory.url)+ let state = ActivityDataSyncState(deviceID: "device")+ try store.saveState(state)+ let url = directory.url.appendingPathComponent("Sync/activityData.json")+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ json["cursor"] = Data("previous cursor".utf8).base64EncodedString()+ try JSONSerialization.data(withJSONObject: json).write(to: url)+ var updated = state+ updated.lastPrunedDate = "2026-10-05"+ try store.saveState(updated)+ #expect(try store.load().cursor == Data("previous cursor".utf8))+ let daily = SyncedActivityData(date: "2026-10-05", eventCount: 2, projectCounts: [:], modelCounts: [:])+ let record = try ActivityDataSyncRecord(deviceID: "device", activityData: daily, recordName: "activityData_device_2026-10-05")+ let uploadedAt = JSONLines.storageDate(Date())+ try store.saveConfirmedRecords([record], lastUploadAt: uploadedAt)+ let confirmed = try store.load()+ #expect(confirmed.cursor == Data("previous cursor".utf8))+ #expect(confirmed.sortedRecords == [record])+ #expect(confirmed.state.lastUploadAt == uploadedAt)+ updated.lastUploadAt = uploadedAt+ try store.saveFetchedRecords([record.id: record], cursor: nil)+ let reopened = try ActivityDataSyncStore(directoryURL: directory.url).load()+ #expect(reopened.state == updated)+ #expect(reopened.sortedRecords == [record])+ #expect(reopened.cursor == nil)+ let files = try FileManager.default.contentsOfDirectory(atPath: url.deletingLastPathComponent().path)+ #expect(Set(files) == ["activityData.json"])+ try store.reset(state: ActivityDataSyncState())+ #expect(try store.load() == ActivityDataSyncCache(state: ActivityDataSyncState()))+ }++ @Test(arguments: ["missingFields", "missingDate", "mismatchedIdentity"])+ func damagedActivityDataRecordsInvalidateCursorAndUploadState(_ damage: String) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = ActivityDataSyncStore(directoryURL: directory.url)+ try store.saveState(ActivityDataSyncState(deviceID: "device"))+ let url = directory.url.appendingPathComponent("Sync/activityData.json")+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ json["cursor"] = Data("stale cursor".utf8).base64EncodedString()+ var record: [String: Any] = [+ "schemaVersion": 1, "aggregationVersion": 1, "date": "2026-10-05",+ "deviceID": "device", "recordName": "activityData_device_2026-10-05", "activityData": [:]+ ]+ switch damage {+ case "missingFields": record = ["invalid": true]+ case "missingDate": record.removeValue(forKey: "date")+ default: record["recordName"] = "activityData_device_2026-10-05_other"+ }+ json["records"] = [record]+ try JSONSerialization.data(withJSONObject: json).write(to: url)+ #expect(try store.load() == ActivityDataSyncCache(state: ActivityDataSyncState()))+ try store.saveState(ActivityDataSyncState(deviceID: "new"))+ #expect(try store.load().sortedRecords.isEmpty)+ #expect(try store.load().cursor == nil)+ #expect(try store.load().state.deviceID == "new")+ }++ @Test func unsupportedActivityDataCacheIsNotOverwritten() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let original = Data(#"{"schemaVersion":999,"futureField":"unsupported"}"#.utf8)+ let url = try directory.write(original, to: "Sync/activityData.json")+ let store = ActivityDataSyncStore(directoryURL: directory.url)+ #expect(throws: SyncRecovery.Failure.self) { try store.saveState(ActivityDataSyncState()) }+ #expect(throws: SyncRecovery.Failure.self) { try store.reset(state: ActivityDataSyncState()) }+ #expect(try Data(contentsOf: url) == original)+ }++ @Test func failedActivityDataSavePreservesCacheAndCursor() throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let store = ActivityDataSyncStore(directoryURL: directory.url)+ try store.saveState(ActivityDataSyncState(deviceID: "device"))+ let url = directory.url.appendingPathComponent("Sync/activityData.json")+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ json["cursor"] = Data("previous cursor".utf8).base64EncodedString()+ let original = try JSONSerialization.data(withJSONObject: json)+ try original.write(to: url)+ let daily = SyncedActivityData(date: "2026-10-05", eventCount: 2, projectCounts: [:], modelCounts: [:])+ let record = try ActivityDataSyncRecord(+ deviceID: "device", activityData: daily, updatedAt: Date(timeIntervalSince1970: .infinity),+ recordName: "activityData_device_2026-10-05"+ )+ #expect(throws: EncodingError.self) {+ try store.saveFetchedRecords([record.id: record], cursor: nil)+ }+ #expect(try Data(contentsOf: url) == original)+ }+}diff --git a/Tests/App/Sync/SyncRecordCodecTests.swift b/Tests/App/Sync/SyncRecordCodecTests.swiftnew file mode 100644index 0000000..03c5887--- /dev/null+++ b/Tests/App/Sync/SyncRecordCodecTests.swift@@ -0,0 +1,116 @@+import CloudKit+import Foundation+import Testing++struct SyncRecordCodecTests {+ @Test func cloudDailyCountsRoundTripWithEventNames() throws {+ let counts = [+ "threadCount": 2, "turnCount": 3,+ "turnStartedCount": 3,+ "turnCompletedCount": 4, "turnAbortedCount": 5, "toolStartedCount": 6,+ "toolCompletedCount": 7, "approvalRequestedCount": 8, "compactionStartedCount": 9,+ "compactionCompletedCount": 10, "subagentStartedCount": 11, "subagentEndedCount": 12+ ]+ var fields: [String: Any] = counts+ fields["schemaVersion"] = 1+ fields["aggregationVersion"] = 1+ fields["date"] = "2026-09-15"+ let aggregate = try JSONDecoder().decode(+ SyncedActivityData.self, from: JSONSerialization.data(withJSONObject: fields)+ )+ let record = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_device-a_2026-09-15"))+ try ActivityDataRecordCodec.apply(aggregate, deviceID: "device-a", to: record)+ #expect(Set(record.allKeys()) == [+ "schemaVersion", "aggregationVersion", "deviceID", "date", "activityData", "updatedAt"+ ])+ let payload = try #require(record["activityData"] as? Data)+ let encodedCounts = try #require(JSONSerialization.jsonObject(with: payload) as? [String: Any])+ #expect(Set(encodedCounts.keys) == Set(counts.keys).union(["eventCount", "projectCounts", "modelCounts"]))+ for (name, count) in counts {+ #expect(encodedCounts[name] as? Int == count)+ }+ #expect(encodedCounts["eventCount"] is NSNull)+ let restored = try #require(try ActivityDataRecordCodec.remoteDailyRecord(from: record))+ #expect(restored.deviceID == "device-a")+ #expect(restored.activityData == aggregate)++ var changed = aggregate+ changed.turnAbortedCount = nil+ changed.toolStartedCount = 0+ try ActivityDataRecordCodec.apply(changed, deviceID: "device-a", to: record)+ let changedData = try #require(record["activityData"] as? Data)+ let changedCounts = try #require(JSONSerialization.jsonObject(with: changedData) as? [String: Any])+ #expect(changedCounts["turnAbortedCount"] is NSNull)+ #expect(changedCounts["toolStartedCount"] as? Int == 0)+ let missing = try #require(try ActivityDataRecordCodec.remoteDailyRecord(from: record))+ #expect(missing.activityData.turnAbortedCount == nil)+ #expect(missing.activityData.toolStartedCount == 0)+ }++ @Test(arguments: [nil, ""]) func cloudActivityDataRejectsMissingDevice(deviceID: String?) {+ let record = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_device_2026-09-15"))+ record["schemaVersion"] = 1 as CKRecordValue+ record["aggregationVersion"] = 1 as CKRecordValue+ record["activityData"] = Data(#"{"projectCounts":{},"modelCounts":{}}"#.utf8) as CKRecordValue+ record["deviceID"] = deviceID as CKRecordValue?+ record["date"] = "2026-09-15" as CKRecordValue+ #expect(throws: ActivityDataSyncError.self) { try ActivityDataRecordCodec.remoteDailyRecord(from: record) }+ }++ @Test func cloudAndCachedActivityDataRejectMismatchedIdentity() throws {+ let daily = SyncedActivityData(+ date: "2026-09-15",+ projectCounts: [:],+ modelCounts: [:]+ )+ let record = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_other_2026-09-15"))+ try ActivityDataRecordCodec.apply(daily, deviceID: "device", to: record)+ #expect(throws: ActivityDataSyncError.self) { try ActivityDataRecordCodec.remoteDailyRecord(from: record) }+ #expect(throws: DecodingError.self) {+ try TestFixtures.decode(+ ActivityDataSyncRecord.self,+ #"{"deviceID":"device","recordName":"activityData_other_2026-09-15","schemaVersion":1,"aggregationVersion":1,"date":"2026-09-15","activityData":{}}"#+ )+ }+ }++ @Test(arguments: [nil, TokenUsage.zero, TokenUsage(+ inputTokens: 100, cachedInputTokens: 20, cacheWriteInputTokens: 5,+ outputTokens: 10, reasoningOutputTokens: 2, totalTokens: 110+ )])+ func cloudDailyTokenUsageAlwaysEncodeAllQuantityKeys(tokenUsage: TokenUsage?) throws {+ let daily = TokenUsageSyncRecord(deviceID: "device", date: "2026-10-12", tokenUsage: tokenUsage)+ let record = try SyncTestFixtures.tokenUsageRecord(daily)+ #expect(record.recordID.recordName == "tokenUsage_device_2026-10-12")+ #expect(Set(record.allKeys()) == ["schemaVersion", "aggregationVersion", "deviceID", "date", "tokenUsage", "updatedAt"])+ let data = try #require(record["tokenUsage"] as? Data)+ let counts = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ #expect(Set(counts.keys) == ["inputTokens", "cachedInputTokens", "cacheWriteInputTokens", "outputTokens", "reasoningOutputTokens", "totalTokens"])+ if let tokenUsage {+ #expect(try JSONDecoder().decode(TokenUsage.self, from: data) == tokenUsage)+ } else {+ #expect(counts.values.allSatisfy { $0 is NSNull })+ }+ let restored = try #require(try TokenUsageSync.dailyRecord(from: record))+ #expect(restored.hasSameData(as: daily))+ #expect(restored.updatedAt == record["updatedAt"] as? Date)+ record["deviceID"] = "other" as CKRecordValue+ #expect(throws: StorageCompatibilityError.self) { try TokenUsageSync.dailyRecord(from: record) }+ }++ @Test func cloudDailyTokenUsageRejectIncompleteKeysAndInvalidQuantities() throws {+ let daily = TokenUsageSyncRecord(deviceID: "device", date: "2026-10-12", tokenUsage: .zero)+ let record = try SyncTestFixtures.tokenUsageRecord(daily)+ let data = try #require(record["tokenUsage"] as? Data)+ var counts = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ counts.removeValue(forKey: "outputTokens")+ record["tokenUsage"] = try JSONSerialization.data(withJSONObject: counts) as CKRecordValue+ #expect(throws: StorageCompatibilityError.self) { try TokenUsageSync.dailyRecord(from: record) }+ counts["outputTokens"] = -1+ record["tokenUsage"] = try JSONSerialization.data(withJSONObject: counts) as CKRecordValue+ #expect(throws: StorageCompatibilityError.self) { try TokenUsageSync.dailyRecord(from: record) }+ counts["outputTokens"] = NSNull()+ record["tokenUsage"] = try JSONSerialization.data(withJSONObject: counts) as CKRecordValue+ #expect(try TokenUsageSync.dailyRecord(from: record)?.tokenUsage == nil)+ }+}diff --git a/Tests/App/Sync/SyncRecoveryTests.swift b/Tests/App/Sync/SyncRecoveryTests.swiftindex 2b404d1..680a89d 100644--- a/Tests/App/Sync/SyncRecoveryTests.swift+++ b/Tests/App/Sync/SyncRecoveryTests.swift@@ -11,7 +11,7 @@ struct SyncRecoveryTests {var expiredIDs: [CKRecord.ID] = []for index in 1 ... 2 {let daily = TokenUsageSyncRecord(deviceID: "device", date: HistoryStorage.dateKey(for: expiredAt.addingTimeInterval(Double(-index) * 86400)), tokenUsage: .zero)- let record = CKRecord(recordType: TokenUsageSync.recordType, recordID: TokenUsageSync.recordID(daily.id, zoneID: Self.zone))+ let record = CKRecord(recordType: TokenUsageSync.recordType, recordID: TokenUsageSync.recordID(daily.id, zoneID: SyncTestFixtures.zone))try TokenUsageSync.apply(daily, to: record)await database.storeRecord(record)expiredIDs.append(record.recordID)@@ -19,11 +19,11 @@ struct SyncRecoveryTests {await database.failNextDeletion()let service = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })await #expect(throws: (any Error).self) {- try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)}#expect(try Self.cachedDailyCount(in: directory.url) == 1)let reopened = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })- try await reopened.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await reopened.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)#expect(try Self.cachedDailyCount(in: directory.url) == 1)let remaining = try await database.records(for: expiredIDs, desiredKeys: nil)for id in expiredIDs {@@ -54,7 +54,7 @@ struct SyncRecoveryTests {let restarted = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })_ = await restarted.synchronizeIfEnabled(localActivityDataAggregates: [local], trigger: .manual)#expect(await database.savedTypes.filter { $0 == "ActivityData" }.count == 2)- #expect(try await Self.activityDataEventCount(database.activityDataRecords().first) == 1)+ #expect(try await SyncTestFixtures.activityDataEventCount(database.activityDataRecords().first) == 1)let cache = try ActivityDataSyncStore(directoryURL: directory.url).load()#expect(cache.sortedRecords.map(\.activityData) == [local.syncedAggregate])#expect(await restarted.hasPendingActivityDataUpdates(local: [local]) == false)@@ -66,8 +66,6 @@ struct SyncRecoveryTests {#expect(try ActivityDataSyncStore(directoryURL: directory.url).load().state.lastUploadAt == cache.state.lastUploadAt)}- private static let zone = CKRecordZone.ID(zoneName: SyncCloudKit.zoneName, ownerName: CKCurrentUserDefaultName)-@Test func damagedActivityDataCursorRebuildsWithoutBlockingTokenUsage() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -110,16 +108,16 @@ struct SyncRecoveryTests {try store.saveFetchedRecords([stale.id: stale], cursor: nil)let url = directory.url.appendingPathComponent("Sync/activityData.json")let original = try Data(contentsOf: url)- let remote = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_remote_\(date)", zoneID: Self.zone))+ let remote = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_remote_\(date)", zoneID: SyncTestFixtures.zone))try ActivityDataRecordCodec.apply(daily, deviceID: "remote", to: remote)remote["updatedAt"] = Date(timeIntervalSince1970: Date().timeIntervalSince1970.rounded(.down)) as CKRecordValue- let deleted = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_deleted_\(date)", zoneID: Self.zone))+ let deleted = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_deleted_\(date)", zoneID: SyncTestFixtures.zone))try ActivityDataRecordCodec.apply(daily, deviceID: "deleted", to: deleted)let expiredDate = HistoryStorage.dateKey(for: HistoryStorage.retentionCutoffDate().addingTimeInterval(-86400))let expiredDaily = TestFixtures.activityDataAggregate(date: expiredDate).syncedAggregate- let expired = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_remote_\(expiredDate)", zoneID: Self.zone))+ let expired = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "activityData_remote_\(expiredDate)", zoneID: SyncTestFixtures.zone))try ActivityDataRecordCodec.apply(expiredDaily, deviceID: "remote", to: expired)- let metadata = CKRecord(recordType: "Metadata", recordID: CKRecord.ID(recordName: "ignored", zoneID: Self.zone))+ let metadata = CKRecord(recordType: "Metadata", recordID: CKRecord.ID(recordName: "ignored", zoneID: SyncTestFixtures.zone))let first = SyncChanges(records: [remote.recordID: .success(remote), deleted.recordID: .success(deleted), expired.recordID: .success(expired), metadata.recordID: .success(metadata)],deletions: [], token: nil, moreComing: true@@ -148,7 +146,7 @@ struct SyncRecoveryTests {defer { try? directory.remove() }let database = SyncDatabaseFixture()let service = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })- try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)let url = directory.url.appendingPathComponent("Sync/tokenUsage.json")if cursorOnly {var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])@@ -158,7 +156,7 @@ struct SyncRecoveryTests {try Data("broken cache".utf8).write(to: url)}let reopened = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })- try await reopened.synchronize(local: [], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await reopened.synchronize(local: [], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)#expect(try Self.cachedDailyCount(in: directory.url) == 1)}@@ -170,7 +168,7 @@ struct SyncRecoveryTests {let database = SyncDatabaseFixture(changesFail: true)let service = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })await #expect(throws: (any Error).self) {- try await service.synchronize(local: [], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)}#expect(try Data(contentsOf: url) == original)}@@ -238,12 +236,12 @@ struct SyncRecoveryTests {let database = SyncDatabaseFixture(failingName: badID, readFailure: readFailure)let service = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })await #expect(throws: (any Error).self) {- try await service.synchronize(local: aggregates, accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: aggregates, accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)}#expect(await database.savedTypes.filter { $0 == TokenUsageSync.recordType }.count == 29)#expect(try Self.cachedDailyCount(in: directory.url) == 29)await database.repair()- try await service.synchronize(local: aggregates, accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: aggregates, accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)#expect(await database.savedTypes.filter { $0 == TokenUsageSync.recordType }.count == 30)}@@ -302,12 +300,12 @@ struct SyncRecoveryTests {defer { try? directory.remove() }let database = SyncDatabaseFixture()let service = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })- try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [Self.turn(0)], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)let url = directory.url.appendingPathComponent("Sync/tokenUsage.json")let original = try Data(contentsOf: url)await database.failChangesRecord()await #expect(throws: (any Error).self) {- try await service.synchronize(local: [Self.turn(1)], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [Self.turn(1)], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)}#expect(try Data(contentsOf: url) == original)}@@ -317,122 +315,16 @@ struct SyncRecoveryTests {defer { try? directory.remove() }let database = SyncDatabaseFixture()let service = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })- try await service.synchronize(local: [], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)let url = directory.url.appendingPathComponent("Sync/tokenUsage.json")let original = Data(#"{"schemaVersion":999,"futureField":"unsupported"}"#.utf8)try original.write(to: url)await #expect(throws: (any Error).self) {- try await service.synchronize(local: [], accountScopedDeviceID: "device", zoneID: Self.zone)- }- #expect(try Data(contentsOf: url) == original)- }-- @Test func activityDataCacheCommitsRecordsAndCursorTogether() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let store = ActivityDataSyncStore(directoryURL: directory.url)- let state = ActivityDataSyncState(deviceID: "device")- try store.saveState(state)- let url = directory.url.appendingPathComponent("Sync/activityData.json")- var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])- json["cursor"] = Data("previous cursor".utf8).base64EncodedString()- try JSONSerialization.data(withJSONObject: json).write(to: url)- var updated = state- updated.lastPrunedDate = "2026-10-05"- try store.saveState(updated)- #expect(try store.load().cursor == Data("previous cursor".utf8))- let daily = SyncedActivityData(date: "2026-10-05", eventCount: 2, projectCounts: [:], modelCounts: [:])- let record = try ActivityDataSyncRecord(deviceID: "device", activityData: daily, recordName: "activityData_device_2026-10-05")- let uploadedAt = JSONLines.storageDate(Date())- try store.saveConfirmedRecords([record], lastUploadAt: uploadedAt)- let confirmed = try store.load()- #expect(confirmed.cursor == Data("previous cursor".utf8))- #expect(confirmed.sortedRecords == [record])- #expect(confirmed.state.lastUploadAt == uploadedAt)- updated.lastUploadAt = uploadedAt- try store.saveFetchedRecords([record.id: record], cursor: nil)- let reopened = try ActivityDataSyncStore(directoryURL: directory.url).load()- #expect(reopened.state == updated)- #expect(reopened.sortedRecords == [record])- #expect(reopened.cursor == nil)- let files = try FileManager.default.contentsOfDirectory(atPath: url.deletingLastPathComponent().path)- #expect(Set(files) == ["activityData.json"])- try store.reset(state: ActivityDataSyncState())- #expect(try store.load() == ActivityDataSyncCache(state: ActivityDataSyncState()))- }-- @Test(arguments: ["missingFields", "missingDate", "mismatchedIdentity"])- func damagedActivityDataRecordsInvalidateCursorAndUploadState(_ damage: String) throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let store = ActivityDataSyncStore(directoryURL: directory.url)- try store.saveState(ActivityDataSyncState(deviceID: "device"))- let url = directory.url.appendingPathComponent("Sync/activityData.json")- var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])- json["cursor"] = Data("stale cursor".utf8).base64EncodedString()- var record: [String: Any] = [- "schemaVersion": 1, "aggregationVersion": 1, "date": "2026-10-05",- "deviceID": "device", "recordName": "activityData_device_2026-10-05", "activityData": [:]- ]- switch damage {- case "missingFields": record = ["invalid": true]- case "missingDate": record.removeValue(forKey: "date")- default: record["recordName"] = "activityData_device_2026-10-05_other"- }- json["records"] = [record]- try JSONSerialization.data(withJSONObject: json).write(to: url)- #expect(try store.load() == ActivityDataSyncCache(state: ActivityDataSyncState()))- try store.saveState(ActivityDataSyncState(deviceID: "new"))- #expect(try store.load().sortedRecords.isEmpty)- #expect(try store.load().cursor == nil)- #expect(try store.load().state.deviceID == "new")- }-- @Test func unsupportedActivityDataCacheIsNotOverwritten() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let original = Data(#"{"schemaVersion":999,"futureField":"unsupported"}"#.utf8)- let url = try directory.write(original, to: "Sync/activityData.json")- let store = ActivityDataSyncStore(directoryURL: directory.url)- #expect(throws: SyncRecovery.Failure.self) { try store.saveState(ActivityDataSyncState()) }- #expect(throws: SyncRecovery.Failure.self) { try store.reset(state: ActivityDataSyncState()) }- #expect(try Data(contentsOf: url) == original)- }-- @Test func failedActivityDataSavePreservesCacheAndCursor() throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let store = ActivityDataSyncStore(directoryURL: directory.url)- try store.saveState(ActivityDataSyncState(deviceID: "device"))- let url = directory.url.appendingPathComponent("Sync/activityData.json")- var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])- json["cursor"] = Data("previous cursor".utf8).base64EncodedString()- let original = try JSONSerialization.data(withJSONObject: json)- try original.write(to: url)- let daily = SyncedActivityData(date: "2026-10-05", eventCount: 2, projectCounts: [:], modelCounts: [:])- let record = try ActivityDataSyncRecord(- deviceID: "device", activityData: daily, updatedAt: Date(timeIntervalSince1970: .infinity),- recordName: "activityData_device_2026-10-05"- )- #expect(throws: EncodingError.self) {- try store.saveFetchedRecords([record.id: record], cursor: nil)+ try await service.synchronize(local: [], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)}#expect(try Data(contentsOf: url) == original)}- @Test func sameSourceRecalculationCanReduceCountsWithoutDeletingRecord() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let before = try #require(await fixture.database.activityDataRecords().first)- let result = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)- let after = try #require(await fixture.database.activityDataRecords().first)- #expect(before.recordID == after.recordID)- #expect(try Self.activityDataEventCount(before) == 9)- #expect(try Self.activityDataEventCount(after) == 1)- #expect(!result.summary.isSyncPending)- #expect(await fixture.database.deletedIDs.isEmpty)- }-@Test func dailyActivityDataUploadDoesNotRequireLocalSourceMetadata() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -451,7 +343,7 @@ struct SyncRecoveryTests {#expect(await database.deletedIDs.isEmpty)#expect(await database.activityDataRecords().map(\.recordID) == before)#expect(result.activityData.count == before.count)- #expect(try await Self.activityDataEventCount(database.activityDataRecords().first) == 3)+ #expect(try await SyncTestFixtures.activityDataEventCount(database.activityDataRecords().first) == 3)}@Test func invalidRecordDuringCursorBaselineStopsActivityDataUpload() async throws {@@ -475,41 +367,6 @@ struct SyncRecoveryTests {#expect(try ActivityDataSyncStore(directoryURL: directory.url).load().records.isEmpty)}- @Test func recreatedJournalReplacesSameDeviceDateInsteadOfAddingAnotherBatch() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let previous = try #require(await fixture.database.activityDataRecords().first)- let event = TestFixtures.event(.toolStarted, at: Date(), turn: "different")- try fixture.directory.replaceHistory(- AppServerEventRecord(activityData: event).jsonLineData(),- date: fixture.date- )- _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)- let updated = try #require(await fixture.database.activityDataRecords().first)- #expect(updated.recordID == previous.recordID)- let counts = try #require(try ActivityDataRecordCodec.remoteDailyRecord(from: updated)?.activityData)- #expect(counts.eventCount == 1)- #expect(counts.turnStartedCount == 0)- #expect(counts.toolStartedCount == 1)- #expect(await fixture.database.activityDataRecords().count == 1)- #expect(await fixture.database.deletedIDs.isEmpty)- }-- @Test func unknownCloudVersionPreservesCacheAndPreventsActivityDataUpload() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let cacheURL = fixture.directory.url.appendingPathComponent("Sync/activityData.json")- let before = try Data(contentsOf: cacheURL)- let unsupported = CKRecord(recordType: "ActivityData", recordID: CKRecord.ID(recordName: "future", zoneID: Self.zone))- unsupported["schemaVersion"] = 999 as CKRecordValue- await fixture.database.injectChangesRecord(unsupported)- let result = await fixture.history.loadSnapshot(synchronize: true)- #expect(!result.isActivityDataComplete)- #expect(try Data(contentsOf: cacheURL) == before)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)- #expect(await fixture.database.deletedIDs.isEmpty)- }-@Test func unknownLocalSyncCacheFailsBeforeCloudMutation() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -524,11 +381,6 @@ struct SyncRecoveryTests {#expect(try Data(contentsOf: url) == original)}- private static func activityDataEventCount(_ record: CKRecord?) throws -> Int? {- guard let record else { return nil }- return try ActivityDataRecordCodec.remoteDailyRecord(from: record)?.activityData.eventCount- }-private static func cachedDailyCount(in directory: URL) throws -> Int {let data = try Data(contentsOf: directory.appendingPathComponent("Sync/tokenUsage.json"))let json = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])@@ -541,376 +393,6 @@ struct SyncRecoveryTests {}}-private actor SyncDatabaseFixture: SyncDatabase {- private var stored: [CKRecord.ID: CKRecord] = [:]- private var nextChangesError: CKError.Code?- private let changesFail: Bool- private var changesRecordFails = false- private var changesPages: [Result<SyncChanges, Error>] = []-- private var failingName: String?- private var failingDate: String?- private var omittedReadName: String?- private let readFailure: Bool- private let uploadFailure: CKError.Code- private(set) var queryCount = 0- private(set) var changesSinceNil: [Bool] = []- private(set) var savedTypes: [String] = []- private(set) var requestedIDs: [CKRecord.ID] = []- private(set) var deletedIDs: [CKRecord.ID] = []- private var changesRecord: CKRecord?- private var deletionFails = false-- var remainingChangesPages: Int {- changesPages.count- }-- func setChangesPages(_ pages: [Result<SyncChanges, Error>]) {- changesPages = pages- }-- func failNextDeletion() {- deletionFails = true- }-- func failActivityDataUpload(on date: String) {- failingDate = date- }-- func activityDataRecords() -> [CKRecord] {- stored.values.filter { $0.recordType == "ActivityData" }.map(Self.copy)- }-- func removeRecord(_ id: CKRecord.ID) {- stored[id] = nil- }-- func storeRecord(_ record: CKRecord) {- stored[record.recordID] = Self.copy(record)- }-- func injectChangesRecord(_ record: CKRecord) {- changesRecord = Self.copy(record)- }-- init(nextChangesError: CKError.Code? = nil, changesFail: Bool = false, failingName: String? = nil, failingDate: String? = nil, readFailure: Bool = false, uploadFailure: CKError.Code = .constraintViolation) {- self.nextChangesError = nextChangesError- self.changesFail = changesFail- self.failingName = failingName- self.failingDate = failingDate- self.readFailure = readFailure- self.uploadFailure = uploadFailure- }-- private nonisolated static func copy(_ record: CKRecord) -> CKRecord {- record.copy() as? CKRecord ?? record- }-- func failChangesRecord() {- changesRecordFails = true- }-- func omitReadResult(named name: String) {- omittedReadName = name- }-- func repair() {- failingName = nil- failingDate = nil- omittedReadName = nil- }-- func records(for ids: [CKRecord.ID], desiredKeys _: [CKRecord.FieldKey]?) async throws -> Records {- requestedIDs.append(contentsOf: ids)- return Dictionary(uniqueKeysWithValues: ids.filter { $0.recordName != omittedReadName }.map { id in- if readFailure, id.recordName == failingName {- return (id, .failure(CKError(.constraintViolation)))- }- return (id, stored[id].map { .success(Self.copy($0)) } ?? .failure(CKError(.unknownItem)))- })- }-- func modifyRecords(- saving records: [CKRecord],- deleting ids: [CKRecord.ID],- savePolicy _: CKModifyRecordsOperation.RecordSavePolicy,- atomically _: Bool- ) async throws -> Modification {- var saved: Records = [:]- for record in records {- if record.recordID.recordName == failingName || (record.recordType == "ActivityData" && failingDate != nil && record["date"] as? String == failingDate) {- saved[record.recordID] = .failure(CKError(uploadFailure))- } else {- stored[record.recordID] = record.copy() as? CKRecord- saved[record.recordID] = .success(record)- savedTypes.append(record.recordType)- }- }- deletedIDs.append(contentsOf: ids)- for id in ids {- stored[id] = nil- if deletionFails {- deletionFails = false- throw CKError(.networkFailure)- }- }- return (saved, Dictionary(uniqueKeysWithValues: ids.map { ($0, .success(())) }))- }-- func records(matching query: CKQuery, inZoneWith _: CKRecordZone.ID?, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {- queryCount += 1- return (stored.values.filter { $0.recordType == query.recordType }.map { ($0.recordID, .success(Self.copy($0))) }, nil)- }-- func records(continuingMatchFrom _: CKQueryOperation.Cursor, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {- ([], nil)- }-- func recordZone(for id: CKRecordZone.ID) async throws -> CKRecordZone {- CKRecordZone(zoneID: id)- }-- func modifyRecordZones(saving zones: [CKRecordZone], deleting _: [CKRecordZone.ID]) async throws -> ZoneModification {- (Dictionary(uniqueKeysWithValues: zones.map { ($0.zoneID, .success($0)) }), [:])- }-- func fetchChanges(inZoneWith _: CKRecordZone.ID, since token: CKServerChangeToken?, resultsLimit _: Int) async throws -> SyncChanges {- changesSinceNil.append(token == nil)- if !changesPages.isEmpty {- return try changesPages.removeFirst().get()- }- if let error = nextChangesError {- nextChangesError = nil- throw CKError(error)- }- if changesFail {- throw CKError(.networkFailure)- }- var records = stored.mapValues { Result<CKRecord, Error>.success(Self.copy($0)) }- if let changesRecord {- records[changesRecord.recordID] = .success(Self.copy(changesRecord))- }- if changesRecordFails {- records[CKRecord.ID(recordName: "failed-record")] = .failure(CKError(.constraintViolation))- }- return SyncChanges(records: records, deletions: [], token: nil, moreComing: false)- }-}--extension SyncRecoveryTests {- @Test func failedUploadPreservesRemoteAndRetriesAfterRestart() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)- #expect(outcome.summary.isSyncPending)- await fixture.database.failActivityDataUpload(on: fixture.date)- _ = await fixture.history.loadSnapshot(synchronize: true)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)- #expect(await fixture.database.deletedIDs.isEmpty)- await fixture.database.repair()- let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)- _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 1)- #expect(await fixture.database.activityDataRecords().count == 1)- }-- @Test func repeatedRebuildKeepsSourceAndNeedsNoSeparateAcknowledgement() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let initial = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)- #expect(initial.summary.failedTokenUsageDateKeys.isEmpty)- #expect(!initial.summary.didFailTokenUsageRebuild)- _ = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)- let state = try HistoryDatabase(directoryURL: fixture.directory.url)- #expect(try state.activityDataAggregates().first == fixture.local)- #expect(try state.pendingActivityDataDates().isEmpty)- #expect(await fixture.database.activityDataRecords().count == 1)- #expect(await fixture.database.deletedIDs.isEmpty)- }-- @Test func unavailableSourceCannotOverwriteRemoteAndRecoversAfterRepair() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let local = try HistoryDatabase(directoryURL: fixture.directory.url)- let original = try local.exportJSONLines(date: fixture.date)- try local.execute("UPDATE events SET payload = ?", [.data(Data("broken".utf8))])- try local.execute("UPDATE aggregates SET activityData = CAST(json_set(CAST(activityData AS TEXT), '$.aggregationVersion', 0) AS BLOB)")- await #expect(throws: (any Error).self) {- try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)- }- let restarted = HistoryService(directoryURL: fixture.directory.url, syncService: fixture.sync)- _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)- #expect(await fixture.database.deletedIDs.isEmpty)- try fixture.directory.replaceHistory(original, date: fixture.date)- _ = await restarted.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 1)- }-- @Test func requestSaveFailureDoesNotModifyAggregateOrCloud() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let local = try HistoryDatabase(directoryURL: fixture.directory.url)- let original = try local.activityDataAggregates()- try local.execute("CREATE TRIGGER reject_aggregate BEFORE UPDATE ON aggregates BEGIN SELECT RAISE(ABORT, 'injected failure'); END")- await #expect(throws: (any Error).self) {- try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)- }- #expect(try local.activityDataAggregates() == original)- #expect(await fixture.database.deletedIDs.isEmpty)- }-- @Test func disabledSyncKeepsUpdatedAggregateForNextEnabledRun() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let disabled = SyncService(database: fixture.database, directoryURL: fixture.directory.url, isEnabled: { false })- let history = HistoryService(directoryURL: fixture.directory.url, syncService: disabled)- _ = try await history.rebuildData(for: [fixture.date], synchronize: true)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)- _ = await fixture.history.loadSnapshot(synchronize: true)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 1)- }-- @Test func appendedEventsUpdateSameDeviceDailyCounts() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let activityDataRecorder = ActivityDataRecorder(directoryURL: fixture.directory.url)- let event = ActivityDataRecord(- timestamp: Date(),- name: ActivityDataEventKind.toolStarted.rawValue,- origin: .main,- cwd: nil,- toolName: "exec_command",- model: nil,- effort: nil,- threadID: "thread-a",- turnID: "turn-a",- agentThreadID: nil,- id: "appended-tool"- )- try await activityDataRecorder.record(event: event)- _ = await fixture.history.loadSnapshotWithMaintenance(synchronize: true, trigger: .auto)- let remote = try #require(await fixture.database.activityDataRecords().first)- #expect(try Self.activityDataEventCount(remote) == 2)- #expect(remote["sourceCheckpoint"] == nil)- #expect(await fixture.database.activityDataRecords().count == 1)- }-- @Test func unavailableTokenUsageHistoryMarksAllRequestedDatesFailed() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let brokenDirectory = try TestDirectory()- defer { try? brokenDirectory.remove() }- _ = try brokenDirectory.write(Data("broken".utf8), to: "event.db")- let history = HistoryService(- directoryURL: fixture.directory.url, syncService: fixture.sync,- tokenUsageHistory: TokenUsageHistoryStore(directoryURL: brokenDirectory.url)- )- let date = try #require(CodexDateFormat.dayDate(from: fixture.date))- let dates = [fixture.date, HistoryStorage.dateKey(for: date.addingTimeInterval(-86400))]- let result = try await history.rebuildData(for: dates, synchronize: false)- #expect(result.summary.failedTokenUsageDateKeys == dates.sorted())- #expect(result.summary.didFailTokenUsageRebuild)- #expect(result.summary.rebuiltDateCount == 0)- #expect(result.summary.eventCount == 1)- #expect(result.summary.tokenUsageEventCount == 0)- #expect(result.summary.failedDateKeys.isEmpty)- #expect(try await Self.activityDataEventCount(fixture.database.activityDataRecords().first) == 9)- }-- @Test func partialTokenUsageFailureIsReportedWithoutClaimingWholeDaySuccess() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- let now = Date()- let good = TestFixtures.tokenUsageObservation(id: "good", at: now, tokenUsage: .zero)- let bad = TokenUsageObservation(id: "bad", observedAt: now, previous: Self.counts(10), current: TokenUsageUpdate(total: .zero, last: .zero))- let local = try HistoryDatabase(directoryURL: fixture.directory.url)- try local.append(AppServerEventRecord(tokenUsage: good, recordedAt: now))- try local.append(AppServerEventRecord(tokenUsage: bad, recordedAt: now))- let result = try await fixture.history.rebuildData(for: [fixture.date], synchronize: false)- #expect(result.summary.rebuiltDateCount == 0)- #expect(result.summary.eventCount == 1)- #expect(result.summary.tokenUsageEventCount == 0)- #expect(result.summary.failedTokenUsageDateKeys == [fixture.date])- #expect(result.summary.didFailTokenUsageRebuild)- #expect(result.summary.failedDateKeys.isEmpty)- }-}--private struct HistoryRebuildFixture {- let directory: TestDirectory- let database: SyncDatabaseFixture- let sync: SyncService- let history: HistoryService- let date: String- let local: ActivityDataAggregate-- init() async throws {- directory = try TestDirectory()- database = SyncDatabaseFixture()- sync = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })- history = HistoryService(directoryURL: directory.url, syncService: sync)- let now = Date()- date = HistoryStorage.dateKey(for: now)- try directory.replaceHistory(AppServerEventRecord(activityData: TestFixtures.event(at: now), recordedAt: now).jsonLineData(), date: date)- _ = await history.loadSnapshotWithMaintenance(synchronize: false, trigger: .manual)- local = try #require(HistoryDatabase(directoryURL: directory.url).activityDataAggregates().first)- var remote = local- remote.eventCount = 9- _ = await sync.synchronizeIfEnabled(localActivityDataAggregates: [remote], trigger: .manual)- #expect(await database.activityDataRecords().count == 1)- }-}--extension SyncRecoveryTests {- @Test func rebuildUploadsAlgorithmVersionEvenWhenCountsAreUnchanged() async throws {- let fixture = try await HistoryRebuildFixture()- defer { await #expect(throws: Never.self) { try await fixture.directory.removeAfterClosingHistory() } }- var previous = fixture.local- previous.aggregationVersion = 1- try HistoryDatabase(directoryURL: fixture.directory.url).execute(- "UPDATE aggregates SET activityData = ? WHERE date = ?",- [.data(JSONLines.stableEncoder.encode(previous)), .text(fixture.date)]- )- let remote = try #require(await fixture.database.activityDataRecords().first)- try ActivityDataRecordCodec.apply(previous.syncedAggregate, deviceID: #require(remote["deviceID"] as? String), to: remote)- _ = try await fixture.database.modifyRecords(saving: [remote], deleting: [], savePolicy: .ifServerRecordUnchanged, atomically: false)- _ = await fixture.sync.synchronizeIfEnabled(localActivityDataAggregates: [previous], trigger: .manual)- let outcome = try await fixture.history.rebuildData(for: [fixture.date], synchronize: true)- let updated = try #require(await fixture.database.activityDataRecords().first)- #expect(try Self.activityDataEventCount(updated) == previous.eventCount)- #expect(updated["aggregationVersion"] as? Int == AggregationVersion.activityData)- #expect(!outcome.summary.isSyncPending)- #expect(await fixture.database.activityDataRecords().count == 1)- }-}--extension SyncRecoveryTests {- @Test func remoteDateDoesNotHideMissingLocalContribution() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let now = Date()- let date = HistoryStorage.dateKey(for: now)- var remote = ActivityDataAggregate(date: date)- remote.turnCount = 8- let record = try ActivityDataSyncRecord(- deviceID: "other", activityData: remote.syncedAggregate,- recordName: ActivityDataSyncRecord.recordName(deviceID: "other", date: date)- )- let root = directory.url- let store = ActivityDataSyncStore(directoryURL: root)- try store.saveState(ActivityDataSyncState(deviceID: "local"))- try store.saveFetchedRecords([record.id: record], cursor: nil)- try HistoryDatabase(directoryURL: directory.url).append(AppServerEventRecord(activityData: TestFixtures.event(at: now)))- let sync = SyncService(database: SyncDatabaseFixture(), directoryURL: root, isEnabled: { true })- let history = HistoryService(directoryURL: directory.url, syncService: sync)- let snapshot = await history.loadSnapshot()- let day = UsageHeatmapDay.grid(usage: nil, history: snapshot, columnCount: 1, today: now).compactMap(\.self).first { $0.startDate == date }- #expect(snapshot.unavailableActivityDataDates.contains(date))- #expect(day?.activityData.turnCount == nil)- }-}-extension SyncRecoveryTests {@Test func activityDataAndTokenUsageKeepSeparateDailyRecordsAndMergeOtherDevicesOnlyForDisplay() async throws {let directory = try TestDirectory()@@ -921,11 +403,11 @@ extension SyncRecoveryTests {var local = ActivityDataAggregate(date: date)local.turnCount = 2var turn = Self.turn(0)- turn.tokenUsage = Self.counts(100)+ turn.tokenUsage = SyncTestFixtures.counts(100)let initial = await sync.synchronizeIfEnabled(localActivityDataAggregates: [local], localTokenUsageAggregates: [turn], trigger: .manual)let deviceID = try #require(initial.currentDeviceID)- let activityDataID = CKRecord.ID(recordName: ActivityDataSyncRecord.recordName(deviceID: deviceID, date: date), zoneID: Self.zone)- let tokenUsageID = TokenUsageSync.recordID("tokenUsage_\(deviceID)_\(date)", zoneID: Self.zone)+ let activityDataID = CKRecord.ID(recordName: ActivityDataSyncRecord.recordName(deviceID: deviceID, date: date), zoneID: SyncTestFixtures.zone)+ let tokenUsageID = TokenUsageSync.recordID("tokenUsage_\(deviceID)_\(date)", zoneID: SyncTestFixtures.zone)#expect(activityDataID != tokenUsageID)let own = try await database.records(for: [activityDataID, tokenUsageID], desiredKeys: nil)#expect(try own[activityDataID]?.get().recordType == "ActivityData")@@ -935,102 +417,52 @@ extension SyncRecoveryTests {other.turnCount = 3let otherActivityData = CKRecord(recordType: "ActivityData",- recordID: CKRecord.ID(recordName: ActivityDataSyncRecord.recordName(deviceID: "other", date: date), zoneID: Self.zone)+ recordID: CKRecord.ID(recordName: ActivityDataSyncRecord.recordName(deviceID: "other", date: date), zoneID: SyncTestFixtures.zone))try ActivityDataRecordCodec.apply(other.syncedAggregate, deviceID: "other", to: otherActivityData)await database.storeRecord(otherActivityData)- try await database.storeRecord(Self.tokenUsageRecord(TokenUsageSyncRecord(deviceID: "other", date: date, tokenUsage: Self.counts(900))))+ try await database.storeRecord(SyncTestFixtures.tokenUsageRecord(TokenUsageSyncRecord(deviceID: "other", date: date, tokenUsage: SyncTestFixtures.counts(900))))let combined = await sync.synchronizeIfEnabled(localActivityDataAggregates: [local], localTokenUsageAggregates: [turn], trigger: .manual)let snapshot = HistorySnapshot(localActivityDataAggregates: [local], syncedActivityDataRecords: combined.activityData, currentDeviceID: combined.currentDeviceID)#expect(snapshot.activityData.first?.turnCount == 5)- #expect(combined.tokenUsageByDate?[date] == Self.counts(1000))+ #expect(combined.tokenUsageByDate?[date] == SyncTestFixtures.counts(1000))#expect(await database.savedTypes.filter { $0 == "ActivityData" }.count == 1)#expect(await database.savedTypes.filter { $0 == "TokenUsage" }.count == 1)local.turnCount = 1- turn.tokenUsage = Self.counts(50)+ turn.tokenUsage = SyncTestFixtures.counts(50)let reduced = await sync.synchronizeIfEnabled(localActivityDataAggregates: [local], localTokenUsageAggregates: [turn], trigger: .manual)let updated = HistorySnapshot(localActivityDataAggregates: [local], syncedActivityDataRecords: reduced.activityData, currentDeviceID: reduced.currentDeviceID)#expect(updated.activityData.first?.turnCount == 4)- #expect(reduced.tokenUsageByDate?[date] == Self.counts(950))+ #expect(reduced.tokenUsageByDate?[date] == SyncTestFixtures.counts(950))#expect(await database.activityDataRecords().count == 2)let saved = try #require(try await database.records(for: [activityDataID], desiredKeys: nil)[activityDataID]?.get())#expect(try ActivityDataRecordCodec.remoteDailyRecord(from: saved)?.activityData.turnCount == 1)}- private static func counts(_ input: Int64) -> TokenUsage {- TokenUsage(inputTokens: input, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: input)- }-- private static func tokenUsageRecord(_ daily: TokenUsageSyncRecord) throws -> CKRecord {- let record = CKRecord(recordType: TokenUsageSync.recordType, recordID: TokenUsageSync.recordID(daily.id, zoneID: zone))- try TokenUsageSync.apply(daily, to: record)- return record- }-- @Test(arguments: [nil, TokenUsage.zero, TokenUsage(- inputTokens: 100, cachedInputTokens: 20, cacheWriteInputTokens: 5,- outputTokens: 10, reasoningOutputTokens: 2, totalTokens: 110- )])- func cloudDailyTokenUsageAlwaysEncodeAllQuantityKeys(tokenUsage: TokenUsage?) throws {- let daily = TokenUsageSyncRecord(deviceID: "device", date: "2026-10-12", tokenUsage: tokenUsage)- let record = try Self.tokenUsageRecord(daily)- #expect(record.recordID.recordName == "tokenUsage_device_2026-10-12")- #expect(Set(record.allKeys()) == ["schemaVersion", "aggregationVersion", "deviceID", "date", "tokenUsage", "updatedAt"])- let data = try #require(record["tokenUsage"] as? Data)- let counts = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])- #expect(Set(counts.keys) == ["inputTokens", "cachedInputTokens", "cacheWriteInputTokens", "outputTokens", "reasoningOutputTokens", "totalTokens"])- if let tokenUsage {- #expect(try JSONDecoder().decode(TokenUsage.self, from: data) == tokenUsage)- } else {- #expect(counts.values.allSatisfy { $0 is NSNull })- }- let restored = try #require(try TokenUsageSync.dailyRecord(from: record))- #expect(restored.hasSameData(as: daily))- #expect(restored.updatedAt == record["updatedAt"] as? Date)- record["deviceID"] = "other" as CKRecordValue- #expect(throws: StorageCompatibilityError.self) { try TokenUsageSync.dailyRecord(from: record) }- }-- @Test func cloudDailyTokenUsageRejectIncompleteKeysAndInvalidQuantities() throws {- let daily = TokenUsageSyncRecord(deviceID: "device", date: "2026-10-12", tokenUsage: .zero)- let record = try Self.tokenUsageRecord(daily)- let data = try #require(record["tokenUsage"] as? Data)- var counts = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])- counts.removeValue(forKey: "outputTokens")- record["tokenUsage"] = try JSONSerialization.data(withJSONObject: counts) as CKRecordValue- #expect(throws: StorageCompatibilityError.self) { try TokenUsageSync.dailyRecord(from: record) }- counts["outputTokens"] = -1- record["tokenUsage"] = try JSONSerialization.data(withJSONObject: counts) as CKRecordValue- #expect(throws: StorageCompatibilityError.self) { try TokenUsageSync.dailyRecord(from: record) }- counts["outputTokens"] = NSNull()- record["tokenUsage"] = try JSONSerialization.data(withJSONObject: counts) as CKRecordValue- #expect(try TokenUsageSync.dailyRecord(from: record)?.tokenUsage == nil)- }-@Test func dailyTokenUsageReplaceOneDeviceDateIncludingDecreasesAndZero() async throws {let directory = try TestDirectory()defer { try? directory.remove() }let database = SyncDatabaseFixture()let service = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })var daily = Self.turn(0)- daily.tokenUsage = Self.counts(300)- let recordID = TokenUsageSync.recordID("tokenUsage_device_\(daily.date)", zoneID: Self.zone)- try await service.synchronize(local: [daily], accountScopedDeviceID: "device", zoneID: Self.zone)+ daily.tokenUsage = SyncTestFixtures.counts(300)+ let recordID = TokenUsageSync.recordID("tokenUsage_device_\(daily.date)", zoneID: SyncTestFixtures.zone)+ try await service.synchronize(local: [daily], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)#expect(await database.savedTypes == ["TokenUsage"])- #expect(try await service.snapshot(local: [daily], accountScopedDeviceID: "device")[daily.date] == Self.counts(300))+ #expect(try await service.snapshot(local: [daily], accountScopedDeviceID: "device")[daily.date] == SyncTestFixtures.counts(300))#expect(await service.hasPendingUpdates(local: [daily], accountScopedDeviceID: "device") == false)- try await service.synchronize(local: [daily], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [daily], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)#expect(await database.savedTypes == ["TokenUsage"])- daily.tokenUsage = Self.counts(250)+ daily.tokenUsage = SyncTestFixtures.counts(250)#expect(await service.hasPendingUpdates(local: [daily], accountScopedDeviceID: "device"))- try await service.synchronize(local: [daily], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [daily], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)let saved = try #require(try await database.records(for: [recordID], desiredKeys: nil)[recordID]?.get())- #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == Self.counts(250))+ #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == SyncTestFixtures.counts(250))#expect(try Self.cachedDailyCount(in: directory.url) == 1)daily.tokenUsage = .zero- try await service.synchronize(local: [daily], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await service.synchronize(local: [daily], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)#expect(try await service.snapshot(local: [daily], accountScopedDeviceID: "device")[daily.date] == .zero)}@@ -1040,103 +472,59 @@ extension SyncRecoveryTests {defer { try? directory.remove() }let database = SyncDatabaseFixture()var local = Self.turn(0)- local.tokenUsage = Self.counts(100)+ local.tokenUsage = SyncTestFixtures.counts(100)let date = local.date- let other = TokenUsageSyncRecord(deviceID: "other", date: date, tokenUsage: Self.counts(otherCount))- let otherRecord = try Self.tokenUsageRecord(other)+ let other = TokenUsageSyncRecord(deviceID: "other", date: date, tokenUsage: SyncTestFixtures.counts(otherCount))+ let otherRecord = try SyncTestFixtures.tokenUsageRecord(other)await database.storeRecord(otherRecord)let service = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })- try await service.synchronize(local: [local], accountScopedDeviceID: "device", zoneID: Self.zone)- #expect(try await service.snapshot(local: [local], accountScopedDeviceID: "device")[date] == Self.counts(100 + otherCount))- let localID = TokenUsageSync.recordID("tokenUsage_device_\(date)", zoneID: Self.zone)+ try await service.synchronize(local: [local], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)+ #expect(try await service.snapshot(local: [local], accountScopedDeviceID: "device")[date] == SyncTestFixtures.counts(100 + otherCount))+ let localID = TokenUsageSync.recordID("tokenUsage_device_\(date)", zoneID: SyncTestFixtures.zone)let saved = try #require(try await database.records(for: [localID], desiredKeys: nil)[localID]?.get())- #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == Self.counts(100))+ #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == SyncTestFixtures.counts(100))let cacheURL = directory.url.appendingPathComponent("Sync/tokenUsage.json")let cache = try JSONLines.decoder.decode(TokenUsageSyncCache.self, from: Data(contentsOf: cacheURL))let before = try #require(cache.records[localID.recordName])#expect(before.updatedAt != nil)let restarted = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })#expect(await restarted.hasPendingUpdates(local: [local], accountScopedDeviceID: "device") == false)- try await restarted.synchronize(local: [local], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await restarted.synchronize(local: [local], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)let after = try JSONLines.decoder.decode(TokenUsageSyncCache.self, from: Data(contentsOf: cacheURL))#expect(after.records[before.id] == before)#expect(await database.savedTypes == ["TokenUsage"])- #expect(try await restarted.snapshot(local: [local], accountScopedDeviceID: "new-account")[date] == Self.counts(100))- #expect(try await restarted.snapshot(local: [], accountScopedDeviceID: "device")[date] == Self.counts(100 + otherCount))+ #expect(try await restarted.snapshot(local: [local], accountScopedDeviceID: "new-account")[date] == SyncTestFixtures.counts(100))+ #expect(try await restarted.snapshot(local: [], accountScopedDeviceID: "device")[date] == SyncTestFixtures.counts(100 + otherCount))}@Test func rebuiltLocalObservationsReplaceCloudDailyTotalsWithoutCloudTurnState() async throws {let directory = try TestDirectory()defer { try? directory.remove() }let now = Date()- let observation = TestFixtures.tokenUsageObservation(at: now, tokenUsage: Self.counts(100))+ let observation = TestFixtures.tokenUsageObservation(at: now, tokenUsage: SyncTestFixtures.counts(100))let store = TokenUsageHistoryStore(directoryURL: directory.url)var old = try #require(try await store.recordObservations([observation], now: now).first)- old.tokenUsage = Self.counts(120)+ old.tokenUsage = SyncTestFixtures.counts(120)try directory.seedTokenUsageAggregates([old])let database = SyncDatabaseFixture()let sync = TokenUsageSync(database: database, directoryURL: directory.url, isEnabled: { true })- try await sync.synchronize(local: [old], accountScopedDeviceID: "device", zoneID: Self.zone)+ try await sync.synchronize(local: [old], accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)let date = HistoryStorage.dateKey(for: now)_ = try await store.rebuild(for: [date])let aggregates = try await store.persistedAggregates(now: now)- try await sync.synchronize(local: aggregates, accountScopedDeviceID: "device", zoneID: Self.zone)- let recordID = TokenUsageSync.recordID("tokenUsage_device_\(date)", zoneID: Self.zone)+ try await sync.synchronize(local: aggregates, accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)+ let recordID = TokenUsageSync.recordID("tokenUsage_device_\(date)", zoneID: SyncTestFixtures.zone)let saved = try #require(try await database.records(for: [recordID], desiredKeys: nil)[recordID]?.get())- #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == Self.counts(100))+ #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == SyncTestFixtures.counts(100))#expect(await sync.hasPendingUpdates(local: aggregates, accountScopedDeviceID: "device") == false)try HistoryDatabase(directoryURL: directory.url).execute("""UPDATE aggregates SET tokenUsage = NULL""")let recovered = try await TokenUsageHistoryStore(directoryURL: directory.url).refresh(now: now)- try await sync.synchronize(local: recovered, accountScopedDeviceID: "device", zoneID: Self.zone)+ try await sync.synchronize(local: recovered, accountScopedDeviceID: "device", zoneID: SyncTestFixtures.zone)#expect(await database.savedTypes == ["TokenUsage", "TokenUsage"])}- @Test func incompleteLocalHistoryPreservesCloudDailyUsageUntilSourceIsRepaired() async throws {- let directory = try TestDirectory()- defer { try? directory.remove() }- let database = SyncDatabaseFixture()- let sync = SyncService(database: database, directoryURL: directory.url, isEnabled: { true })- let history = HistoryService(directoryURL: directory.url, syncService: sync)- let now = Date()- let date = HistoryStorage.dateKey(for: now)- func entry(_ name: String, count: Int64) throws -> Data {- let observation = TestFixtures.tokenUsageObservation(id: name, at: now, tokenUsage: Self.counts(count))- return try AppServerEventRecord(tokenUsage: observation, recordedAt: now).jsonLineData()- }- try directory.replaceHistory(entry("first", count: 100) + entry("second", count: 200), date: date)- let initial = await history.loadSnapshot(synchronize: true)- #expect(initial.tokenUsageByDate[date] == Self.counts(300))- let deviceID = try #require(ActivityDataSyncStore(directoryURL: directory.url).loadState().deviceID)- let recordID = TokenUsageSync.recordID("tokenUsage_\(deviceID)_\(date)", zoneID: Self.zone)- try HistoryDatabase(directoryURL: directory.url).execute("""- UPDATE aggregates SET tokenUsage = NULL- """)- try directory.replaceHistory(entry("first", count: 80) + entry("second", count: 200), date: date)- try HistoryDatabase(directoryURL: directory.url).execute("UPDATE events SET payload = ? WHERE identity = 'tokenUsage:second'", [.data(Data("broken".utf8))])-- for _ in 0 ..< 2 {- let partial = await history.loadSnapshot(synchronize: true)- #expect(partial.tokenUsageByDate[date] == Self.counts(300))- let saved = try #require(try await database.records(for: [recordID], desiredKeys: nil)[recordID]?.get())- #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == Self.counts(300))- }- #expect(await database.savedTypes.filter { $0 == "TokenUsage" }.count == 1)-- try HistoryDatabase(directoryURL: directory.url).execute("""- UPDATE aggregates SET tokenUsage = NULL- """)- try directory.replaceHistory(entry("first", count: 80) + entry("second", count: 200), date: date)- let repaired = await history.loadSnapshot(synchronize: true)- #expect(repaired.tokenUsageByDate[date] == Self.counts(280))- let saved = try #require(try await database.records(for: [recordID], desiredKeys: nil)[recordID]?.get())- #expect(try TokenUsageSync.dailyRecord(from: saved)?.tokenUsage == Self.counts(280))- #expect(await database.savedTypes.filter { $0 == "TokenUsage" }.count == 2)- }-}--extension SyncRecoveryTests {@Test func bothSyncCachesPersistTheSameCloudRecordEnvelope() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -1160,7 +548,7 @@ extension SyncRecoveryTests {#expect(Set(record.keys) == ["schemaVersion", "aggregationVersion", "deviceID", "date", "recordName", "updatedAt", kind])#expect(record["date"] as? String == date)let recordName = try #require(record["recordName"] as? String)- let id = CKRecord.ID(recordName: recordName, zoneID: Self.zone)+ let id = CKRecord.ID(recordName: recordName, zoneID: SyncTestFixtures.zone)let remote = try #require(try await database.records(for: [id], desiredKeys: nil)[id]?.get())let remoteUpdatedAt = try #require(remote["updatedAt"] as? Date)let cachedUpdatedAt = try #require(record["updatedAt"] as? Double)diff --git a/Tests/App/Sync/SyncTestSupport.swift b/Tests/App/Sync/SyncTestSupport.swiftnew file mode 100644index 0000000..6119a0a--- /dev/null+++ b/Tests/App/Sync/SyncTestSupport.swift@@ -0,0 +1,177 @@+import CloudKit+import Foundation++enum SyncTestFixtures {+ static let zone = CKRecordZone.ID(zoneName: SyncCloudKit.zoneName, ownerName: CKCurrentUserDefaultName)++ static func activityDataEventCount(_ record: CKRecord?) throws -> Int? {+ guard let record else { return nil }+ return try ActivityDataRecordCodec.remoteDailyRecord(from: record)?.activityData.eventCount+ }++ static func counts(_ input: Int64) -> TokenUsage {+ TokenUsage(inputTokens: input, cachedInputTokens: 0, cacheWriteInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0, totalTokens: input)+ }++ static func tokenUsageRecord(_ daily: TokenUsageSyncRecord) throws -> CKRecord {+ let record = CKRecord(recordType: TokenUsageSync.recordType, recordID: TokenUsageSync.recordID(daily.id, zoneID: zone))+ try TokenUsageSync.apply(daily, to: record)+ return record+ }+}++actor SyncDatabaseFixture: SyncDatabase {+ private var stored: [CKRecord.ID: CKRecord] = [:]+ private var nextChangesError: CKError.Code?+ private let changesFail: Bool+ private var changesRecordFails = false+ private var changesPages: [Result<SyncChanges, Error>] = []++ private var failingName: String?+ private var failingDate: String?+ private var omittedReadName: String?+ private let readFailure: Bool+ private let uploadFailure: CKError.Code+ private(set) var queryCount = 0+ private(set) var changesSinceNil: [Bool] = []+ private(set) var savedTypes: [String] = []+ private(set) var requestedIDs: [CKRecord.ID] = []+ private(set) var deletedIDs: [CKRecord.ID] = []+ private var changesRecord: CKRecord?+ private var deletionFails = false++ var remainingChangesPages: Int {+ changesPages.count+ }++ func setChangesPages(_ pages: [Result<SyncChanges, Error>]) {+ changesPages = pages+ }++ func failNextDeletion() {+ deletionFails = true+ }++ func failActivityDataUpload(on date: String) {+ failingDate = date+ }++ func activityDataRecords() -> [CKRecord] {+ stored.values.filter { $0.recordType == "ActivityData" }.map(Self.copy)+ }++ func removeRecord(_ id: CKRecord.ID) {+ stored[id] = nil+ }++ func storeRecord(_ record: CKRecord) {+ stored[record.recordID] = Self.copy(record)+ }++ func injectChangesRecord(_ record: CKRecord) {+ changesRecord = Self.copy(record)+ }++ init(nextChangesError: CKError.Code? = nil, changesFail: Bool = false, failingName: String? = nil, failingDate: String? = nil, readFailure: Bool = false, uploadFailure: CKError.Code = .constraintViolation) {+ self.nextChangesError = nextChangesError+ self.changesFail = changesFail+ self.failingName = failingName+ self.failingDate = failingDate+ self.readFailure = readFailure+ self.uploadFailure = uploadFailure+ }++ private nonisolated static func copy(_ record: CKRecord) -> CKRecord {+ record.copy() as? CKRecord ?? record+ }++ func failChangesRecord() {+ changesRecordFails = true+ }++ func omitReadResult(named name: String) {+ omittedReadName = name+ }++ func repair() {+ failingName = nil+ failingDate = nil+ omittedReadName = nil+ }++ func records(for ids: [CKRecord.ID], desiredKeys _: [CKRecord.FieldKey]?) async throws -> Records {+ requestedIDs.append(contentsOf: ids)+ return Dictionary(uniqueKeysWithValues: ids.filter { $0.recordName != omittedReadName }.map { id in+ if readFailure, id.recordName == failingName {+ return (id, .failure(CKError(.constraintViolation)))+ }+ return (id, stored[id].map { .success(Self.copy($0)) } ?? .failure(CKError(.unknownItem)))+ })+ }++ func modifyRecords(+ saving records: [CKRecord],+ deleting ids: [CKRecord.ID],+ savePolicy _: CKModifyRecordsOperation.RecordSavePolicy,+ atomically _: Bool+ ) async throws -> Modification {+ var saved: Records = [:]+ for record in records {+ if record.recordID.recordName == failingName || (record.recordType == "ActivityData" && failingDate != nil && record["date"] as? String == failingDate) {+ saved[record.recordID] = .failure(CKError(uploadFailure))+ } else {+ stored[record.recordID] = record.copy() as? CKRecord+ saved[record.recordID] = .success(record)+ savedTypes.append(record.recordType)+ }+ }+ deletedIDs.append(contentsOf: ids)+ for id in ids {+ stored[id] = nil+ if deletionFails {+ deletionFails = false+ throw CKError(.networkFailure)+ }+ }+ return (saved, Dictionary(uniqueKeysWithValues: ids.map { ($0, .success(())) }))+ }++ func records(matching query: CKQuery, inZoneWith _: CKRecordZone.ID?, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {+ queryCount += 1+ return (stored.values.filter { $0.recordType == query.recordType }.map { ($0.recordID, .success(Self.copy($0))) }, nil)+ }++ func records(continuingMatchFrom _: CKQueryOperation.Cursor, desiredKeys _: [CKRecord.FieldKey]?, resultsLimit _: Int) async throws -> QueryPage {+ ([], nil)+ }++ func recordZone(for id: CKRecordZone.ID) async throws -> CKRecordZone {+ CKRecordZone(zoneID: id)+ }++ func modifyRecordZones(saving zones: [CKRecordZone], deleting _: [CKRecordZone.ID]) async throws -> ZoneModification {+ (Dictionary(uniqueKeysWithValues: zones.map { ($0.zoneID, .success($0)) }), [:])+ }++ func fetchChanges(inZoneWith _: CKRecordZone.ID, since token: CKServerChangeToken?, resultsLimit _: Int) async throws -> SyncChanges {+ changesSinceNil.append(token == nil)+ if !changesPages.isEmpty {+ return try changesPages.removeFirst().get()+ }+ if let error = nextChangesError {+ nextChangesError = nil+ throw CKError(error)+ }+ if changesFail {+ throw CKError(.networkFailure)+ }+ var records = stored.mapValues { Result<CKRecord, Error>.success(Self.copy($0)) }+ if let changesRecord {+ records[changesRecord.recordID] = .success(Self.copy(changesRecord))+ }+ if changesRecordFails {+ records[CKRecord.ID(recordName: "failed-record")] = .failure(CKError(.constraintViolation))+ }+ return SyncChanges(records: records, deletions: [], token: nil, moreComing: false)+ }+}diff --git a/appcast.xml b/appcast.xmlindex 4e6c1f2..237d78b 100644--- a/appcast.xml+++ b/appcast.xml@@ -5,6 +5,20 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar.app 5.1.1</title>+ <sparkle:version>210</sparkle:version>+ <sparkle:shortVersionString>5.1.1</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:minimumAutoupdateVersion>200</sparkle:minimumAutoupdateVersion>+ <sparkle:informationalUpdate><sparkle:belowVersion>200</sparkle:belowVersion></sparkle:informationalUpdate>+ <link xml:lang="en-US">https://codexbar.zabrian.app/notes?lang=en-US#5.0.0-Guide</link>+ <link xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.0.0-Guide</link>+ <sparkle:releaseNotesLink xml:lang="en-US">https://codexbar.zabrian.app/notes?lang=en-US#5.1.1</sparkle:releaseNotesLink>+ <sparkle:releaseNotesLink xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.1.1</sparkle:releaseNotesLink>+ <pubDate>Wed, 28 Oct 2026 19:46:02 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v5.1.1.dmg" sparkle:edSignature="IhFgMVU4rgNvI5qDWiD7wSkFTiDnn98zkH/h1jQf2pvlfgCfMBEj70zqhZBbwJhTqhZmALFDuHsobU1ESkzFDw==" length="11062272" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 5.1.0</title><sparkle:version>209</sparkle:version>