Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

feat: 新增任务流光并完善任务生命周期识别

Bob4f2a6c9a983b
diff --git a/.gitignore b/.gitignore
index bc74d60..1c8bc82 100644
--- a/.gitignore
+++ b/.gitignore
@@ -38,6 +38,9 @@ codesign2
# Logs
*.log
+# Performance reports
+/Performance/
+
# Editor
.zed/
diff --git a/AGENTS.md b/AGENTS.md
index 316c9d6..f1321aa 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -45,14 +45,15 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,
- 如果一行以 Markdown 格式的链接或行内代码结尾,后面不加任何标点;链接或行内代码位于句中时仍按句子结构使用中文标点
- Markdown 语法、代码块、命令、路径、URL、版本号和程序标识符内部的符号保持原样
- 如果某句话的作用只是防止被质疑,而不是推进论证,请删除这句话
+- 文档只描述当前行为,不记录或者强调变更过程,同时删除没有实质信息的防御性表述
## 架构与编码约定
-启动时必须先调用 `WorkflowHookEventRecorder.handleIfRequested()` 方法。`--hook-event` 模式从 `stdin` 接收事件,按需有界读取 rollout 元数据,加锁写入 JSONL 并立即退出,不初始化 UI,失败也不能阻断 Codex。Handler 超时按事件从 `hookTimeoutSeconds(for:)` 取得,`SessionEnd` 为 3 秒,其他事件为 5 秒。普通模式由 `CodexBarAppDelegate` 统一装配长期服务。
+启动时必须先调用 `WorkflowHookEventRecorder.handleIfRequested()` 方法。`--hook-event` 模式从 `stdin` 接收事件,按需有界读取 rollout 元数据,加锁写入 JSONL 并立即退出,不初始化 UI,失败也不能阻断 Codex。Handler 超时按事件从 `hookTimeoutSeconds(for:)` 取得,`SessionEnd` 和 `Interrupt` 为 3 秒,其他事件为 5 秒。普通模式由 `CodexBarAppDelegate` 统一装配长期服务。
工程默认采用 `MainActor` 隔离。UI, Controller, ViewModel 和 Settings 依赖默认隔离,共享可变状态放入 actor,DTO 和跨 actor 值类型按需添加 `nonisolated` 标记,禁止在主 actor 执行阻塞 I/O。类型命名使用 `UpperCamelCase` 风格,成员命名使用 `lowerCamelCase` 风格。注释只解释非显然的生命周期、焦点、actor 或系统 API 约束。
-保持三条数据链路独立:app-server 额度与用量、Hook 历史聚合、`CodexActivityMonitor` 实时任务。helper 只能执行固定的睡眠控制和自动重置唤醒计划,不得增加网络、任意命令执行或额外文件访问。账户主链路必须检查当前 app-server 的实际版本不低于 `0.143.0`。修改 Hook 配置时必须保留用户和其他应用已有的 handler。启用和校验 Hook 必须额外检查当前 app-server 的实际版本不低于 `0.145.0`。新增网络访问、日志数据或 CloudKit 字段前先核对隐私边界。
+保持三条数据链路独立:app-server 额度与用量、Hook 历史聚合、`CodexActivityMonitor` 实时任务。helper 只能执行固定的睡眠控制和自动重置唤醒计划,不得增加网络、任意命令执行或额外文件访问。账户主链路必须检查当前 app-server 的实际版本不低于 `0.145.0`。修改 Hook 配置时必须保留用户和其他应用已有的 handler。启用和校验 Hook 必须额外检查当前 app-server 的实际版本不低于 `0.150.0`。新增网络访问、日志数据或 CloudKit 字段前先核对隐私边界。
自动重置默认关闭,提前量可选 15 分钟、30 分钟、1 小时、2 小时、4 小时或 6 小时,默认 30 分钟。状态机只处理新鲜响应明确列出的 `available + codexRateLimits + expiresAt` 凭证,每轮连续重试最多 5 分钟。CodexBarHelper 只接收有限时间戳,使用固定 owner 和固定 `wake` 类型维护一个系统事件;目标变化、功能关闭、App 退出、对应 XPC 连接断开或 helper 启动时必须收敛并清理该事件。修改 owner 或事件类型属于清理兼容性问题。
diff --git a/CLAUDE.md b/CLAUDE.md
index b45cabf..2ae4354 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -62,7 +62,7 @@ Debug 与 Release 使用不同 bundle ID,分别是 `app.zabrian.codexbar.debug
`CodexBar/App/CodexBarApp.swift` 的 `init()` 最先调用 `WorkflowHookEventRecorder.handleIfRequested()`
- 带 `--hook-event` 启动 -> **Hook 子进程模式**:从 `stdin` 读取 JSON payload,按需有界读取 rollout 元数据,在 `flock` 锁内追加一行 JSONL 后立即调用 `exit(EXIT_SUCCESS)` 退出,绝不初始化菜单栏 UI;写入失败时静默吞掉,不阻断 Codex
-- Hook handler 超时统一由 `WorkflowHookEventRecorder.hookTimeoutSeconds(for:)` 提供,`SessionEnd` 是 3 秒,其他事件是 5 秒;等锁预算固定比对应事件超时少 2 秒,当前分别是 1 秒和 3 秒
+- Hook handler 超时统一由 `WorkflowHookEventRecorder.hookTimeoutSeconds(for:)` 提供,`SessionEnd` 和 `Interrupt` 是 3 秒,其他事件是 5 秒;等锁预算固定比对应事件超时少 2 秒,当前分别是 1 秒和 3 秒
- 普通启动 -> `Controllers/CodexBarAppDelegate.swift` 中的 `CodexBarAppDelegate` 创建全部长期对象,再由 `StatusItemController.install()` 装配菜单栏;AppDelegate 是唯一的装配点,新增服务在这里注入
### 三条数据链路
@@ -97,17 +97,17 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
**链路三:实时任务,由 `CodexActivityMonitor` 驱动**
-`CodexActivityMonitor` 是菜单栏图标、活动卡片、通知、触觉反馈和防睡眠的**唯一任务状态来源**,由两个 reader 供料。
+`CodexActivityMonitor` 为菜单栏、活动卡片、任务流光、通知、触觉反馈和防睡眠提供统一任务状态,由两个 reader 读取数据。
- `HookEventTailReader`(actor)的 bootstrap 覆盖滚动 24 小时并作为单次事务发送,之后按当日文件 offset 增量 tail,同时向下游报告数据源健康状态
- `CodexSessionLifecycleReader`(actor)增量读取 `~/.codex/sessions` 与 `archived_sessions` 下的 rollout JSONL,只提取 turn 生命周期与最近进展时间,不解码会话或工具内容
- 任务监控只在 `codexHookSettings.isOperable` 为 `true` 时运行,即本地已安装且最近一次明确校验没有失败;链路失效时立即停 reader 并清空实时状态
-- `SessionEnd` 没有 `turn_id`,收到后按 session 把对应任务立即移出活跃列表并放进 5 秒终态确认窗口;rollout 在窗口内补回准确的完成或终止分类,超时后按终止处理
+- `Stop` 保留正在收尾的任务,rollout 确认后才记录完成;`Interrupt` 结束匹配轮次;新 turn 或 `SessionEnd` 将旧任务移入 5 秒终态确认窗口。来源过滤、终态去重和恢复规则见 [实时任务监控](Docs/DeveloperGuide/activity-monitor.md)
- `HookEventTailReader.drainNow()` 是读取屏障,每个调用方等待一轮在本次请求之后开始的读取,返回 `completed`、`sourceUnavailable` 或 `cancelled`
- 缺少 session ID 的 Hook 事件使用匿名 project key,`isAnonymous` 会保留到活动快照、完成记录和终止记录;活动卡片和任务中心显示橙色 `person.crop.circle.dashed` 图标,`help` 为 `匿名任务不参与防睡眠`,`+N` 只显示其他活跃任务总数
- 匿名任务不向通知消费者发布等待或完成 transition,不触发触觉反馈,不参与 KeepAlive 或异常会话保护,`activityProtectionIdentifier` 为 `nil`
-系统唤醒时,`NSWorkspace.didWakeNotification` 先暂停异常会话保护。读取屏障成功时重置生命周期解析回退,并在完成 rollout 对账后恢复判定;数据源不可用时继续由 source health 门槛暂停,reader generation 变化时直接丢弃旧结果。
+系统睡眠前暂停异常会话保护。`NSWorkspace.didWakeNotification` 触发新的读取屏障,成功后重置生命周期解析回退,完成 rollout 对账后恢复判定;数据源不可用时继续暂停,reader generation 变化时丢弃旧结果。
#### 异常会话保护
@@ -139,9 +139,9 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- `shouldDisableSleep` 由 `sleepBlockReason == nil` 派生,要求服务已启动、App 未退出、主开关与 Hook 可用、存在符合条件的任务、helper 已批准且未刷新、低电量与时长上限均未阻断;依赖变化保留用户保存的 `isEnabled`
- `hasRunningTasks` 只表示非匿名且仍可见的运行中任务;`hasKeepAliveTasks` 在此基础上纳入 `keepsAwakeWhileWaiting` 开启时的非匿名等待任务,被异常会话保护隐藏的任务不参与防睡眠
-- Hook 状态在类内只认 `isHookEnabled` 这份镜像,它跟的是 `codexHookSettings.isOperable`;不要回读那个属性,订阅回调跑在 `willSet`,那一刻它的两个输入里正在变的那一项还是旧值,只能认 `CombineLatest` 给的闭包参数
+- Hook 状态在类内只认 `isHookEnabled` 这份镜像,它跟的是 `codexHookSettings.isOperable`;不要回读那个属性,订阅回调跑在 `willSet`,此时正在变更的属性仍是旧值,使用 `CombineLatest` 传入的新值
- 新增拦截条件一律加进 `sleepBlockReason` 的顺序判断里,它和 `shouldDisableSleep` 同源,顺带保证日志的 `reason=` 不会漏项
-- UI 用的 `isLowBatteryBlocking` 与 `canShowOptions` 由 `reconcileSleepState` 从 `sleepBlockReason` 单点派生,新增拦截条件时 `allowsOptions` 那个穷举 `switch` 会强制表态,于是不会出现入口亮着却点不动
+- UI 用的 `isLowBatteryBlocking` 与 `canShowOptions` 由 `reconcileSleepState` 从 `sleepBlockReason` 单点派生,`allowsOptions` 的穷尽 `switch` 定义各阻断条件下的选项入口状态
- `hasRunningTasks` 与 `isRefreshingHelper` 都不带 `@Published` 标注,它们变得比结论频繁,各自发信号会把整个设置页拖着一起重算
- helper 只做固定的系统电源操作;不要给 root helper 增加网络、任意命令执行或其他文件访问能力
- helper 注册需求由防睡眠主开关与自动重置请求共同决定;自动重置开启时即使防睡眠关闭也要完成 `SMAppService` 注册和系统批准,设置行复用注册错误并单独展示唤醒计划同步错误
@@ -163,7 +163,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 异常断连后租约宽限 15 秒;同一 App 在宽限内重连会续上原租约,watchdog 只会释放仍处于断连状态的那一个 client session
- helper 以 `owned` 或 `restoring` 启动时先恢复为 0 再接受新接管;以 `idle` 启动时不修改当前值,因为那个值可能属于其他来源
- 更新 helper 前 App 冻结新防睡眠请求和自动重置唤醒同步,确认固定唤醒事件已取消后执行 unregister/register;旧 helper 终止时负责恢复 owned 睡眠状态,新 helper 就绪后对当前指纹执行一次 `resetSleepAfterUpdate` 并收到状态回复才完成更新,系统仍在等待首次批准时除外
-- 切换失败按 2/4/8...256 秒重试,列表耗尽即放弃(延时累计约 8.5 分钟,每轮再等一次超时约 10 分钟),瞬时抖动能自愈,权限类故障不该无限重试
+- 切换失败按 2/4/8…256 秒重试,重试次数耗尽后保留错误状态
- XPC 请求带超时并汇进同一条重试路径;launchd 拉不起 helper 时 XPC 方法既不回复也不触发 `errorHandler`,没有它界面会显示防睡眠开着而实际没生效,日志里只剩没有配对回复的 `Helper XPC 请求已发送`
- 超时取值放在 `CodexBarHelperIPC.requestTimeoutSeconds` 而不是控制器里,它与 `watchdogGraceSeconds` 是一对:必须更小,App 先放手 helper 才能靠 watchdog 兜底,分处两个 module 会让人改了一边不知道另一边
- 开发期间用 `xcodebuild` 覆盖正在运行的 App bundle 可能使 launchd 注册信息与磁盘上的 helper 不一致;重启 App 后通过 `KeepAliveHelperConfiguration.registrationNeedsRefresh(defaults:)` 检查指纹并刷新注册
@@ -179,10 +179,10 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 上限计时用 `SuspendingClock` 而不是 `Date`,后者受系统时间调整影响且系统睡眠期间照走;排计时器的 `Task.sleep` 同样要传 `SuspendingClock`,否则睡一夜醒来会当场判定到期
- 低电量判断使用 `isLowBatteryActive` 记录滞回状态;电池供电且电量不高于阈值时进入,达到阈值加 5 个百分点或接通电源时解除。时长上限由 `hasReachedMaximumDuration` 保持到下一轮任务或设置变化
- 供电来源读取 `Power Source State`;接电停充时 `Is Charging` 为 `false`,不能用于判断是否正在使用电池
-- 电量读不到时维持上一次的判定,从没读到过就是不触发:误触发会当场断掉用户任务,漏触发最坏也有系统强制睡眠兜底
+- 电量不可读时维持上一次判定,从未取得有效读数时不触发低电量保护
- 已经在低电量保护中时读数失败不清零,否则一次瞬时失败会绕过滞回,让防睡眠反复开关并重发通知
- 低电量通知只在 `isActivelyPreventingSleep` 为真且来源是 `codexBar` 时排队,外部来源不说“已恢复系统睡眠”;日志无条件记并用 `action=release|none` 区分,百分比只有那一条能看到
-- 排队的通知要等 helper 恢复睡眠的 XPC 回复确认成功才发得出去,恢复失败走重试直至放弃,提前说“已恢复系统睡眠”会把用户骗去合盖然后把电耗干
+- 恢复睡眠的通知在 helper 的 XPC 回复确认成功后提交;恢复失败时进入有界重试
- 补发 `IOPMSleepSystem` 之前还要 `await` 到通知真的提交完成,只把提交排进下一个 MainActor job 的话同一个 job 里的补发会抢在它前面
- 那次 `await` 之后要重认一次 `generation` 再走 `finishSleepRestore` 这一步,挂起期间可能已有新的禁用请求接管,否则会释放掉刚建立的空闲断言
- 设置页那句低电量说明看 `isLowBatteryBlocking` 而不是 `isLowBatteryActive`,后者在没有任务时也成立,那时无话可说
@@ -190,7 +190,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 一轮低电量通知的终点是电量回到 `阈值 + 5%` 或者用户改了阈值,由 `hasNotifiedLowBattery` 记住;只看是否接电会让适配器接触不良时每翻一次供电状态就重发一条
- `hasNotifiedLowBattery` 只在通知真的提交成功之后才置位,打在入队处或提交前都会让没送达的那一条吃掉整轮配额,使这一轮之后真正触发的低电量再也提醒不了
- `SleepConditions` 里只放 `battery` 布尔,放电量百分比会让每掉 1% 刷一条变化日志;真实电量只在触发那一条单独记
-- 防睡眠生效且活动卡片数据可用时,右侧显示青绿色 `sun.max.fill`,使用 `.symbolEffect(.rotate.byLayer, options: .repeat(.continuous))` 持续旋转;tooltip 按 `sleepPreventionSource` 区分外部来源与 CodexBar
+- 防睡眠生效且活动卡片数据可用时,右侧显示青绿色 `sun.max.fill`;主面板可见且“动画效果”开启时每 2 秒匀速旋转一圈,关闭动画时显示静态图标。tooltip 按 `sleepPreventionSource` 显示来源
- 设置页那一行说明只在异常、外部来源、低电量生效或达到上限时出现,CodexBar 自己正常持有所有权时整行收起,`keepAliveCaption` 返回 `nil` 即代表收起
- 最长防睡眠时间、异常会话保护阈值与低电量阈值都在防睡眠子面板里,台式机读不到电池时低电量那一行整行隐藏而不是置灰
- 保持屏幕常亮跟 `isActivelyPreventingSleep` 走,由 `reconcileDisplayAwake` 单点切换,于是低电量拦下、达到上限、任务结束时屏幕都跟着放开
@@ -242,7 +242,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- app-server 之外的模块走 `Services/Support/AppLog.swift` 写系统日志,用户可见文案只留步骤名,错误码与 `localizedDescription` 这类细节进 `os_log`;现有 `category` 为 `app`、`keepalive`、`activity`、`workflow`、`sync`、`hooks`、`codexcli`、`settings`、`notification`,helper 进程另用 `helper`
- 日志的目标是出问题时能从中重建当时的状态,所以不只记失败,状态转换、关键操作与决策依据同样要记;启动时由 `logLaunchState` 记一条含全部开关的基线,后续变更日志都是相对它的增量
- 进程终止靠 `AppProcessDiagnostics` 补线索,它和 `logLaunchState` 一样挂在 `app` category 下,ObjC 异常当场留痕,其余终止方式靠下次启动补记一条 `App 上次非正常退出`
-- 那条补记只能用 `.notice` 级别,因为 kill 与强制退出和真崩溃无法区分,用 `.error` 会让按级别筛的排查开局就追一个不存在的故障
+- 非正常退出补记使用 `.notice`,该记录无法区分强制退出与崩溃
- **级别只用 `.notice` 与 `.error`**,状态转换和降级决策用 `.notice`,失败用 `.error`;`.info` 与 `.debug` 只落在内存环形缓冲里,事后 `log show` 捞不全,一律不用
- 详细度靠**结果字段化**而不是多记几条:一次操作只留开始与收尾两条,每一步的成功结果压成收尾那条里的一个字段,只有失败才单独发一条 `.error` 带 `stage=` 与 `detail=`;逐事件与逐快照这类高频路径仍然一律不记,例如两个 Reader 的 `try?` 文件 IO 失败是预期常态,记了会刷屏
- 文案骨架是 `<主体><动作>: 字段=值; 字段=值`,标题只说发生了什么,理由进 `reason=`,处置进 `action=`;起止用 `开始` `完成` `失败`,中间状态用 `已<动作>`
@@ -255,7 +255,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 设置项的变更日志照抄设置页那一行的标题,例如 `菜单栏额度指示变更`、`开机自动启动变更`,用户说“我改了那个开关”时能直接对上;只有本身带完整链路的才用链路词根,例如 Hook、同步、通知、KeepAlive、快捷键
- 成对的操作要留成对的日志,例如 XPC 的发送与回复各记一条并带同一个 `generation`,缺一条就说明请求丢在途中
- 耗时用 `LogDuration` 取,只加在收尾那一条上
-- `Logger` 的插值是 autoclosure,里面直接访问属性会被要求显式 `self`,而 `.swiftformat` 配了 `--self remove`,两边会打架;把属性先取到局部常量再插值即可,不需要 lint 豁免
+- `Logger` 的插值是 autoclosure,里面直接访问属性会被要求显式 `self`,而 `.swiftformat` 配了 `--self remove`,两者要求冲突;先将属性保存为局部常量再插值
- 账户有效时,额度和用量请求可以分别失败;同账户缓存标为 `stale` 并降低透明度。可见的数据区域均无数据时,在其中第一个区域显示“暂无数据”;Hook 开启时用量区域可保留本地统计。账户变化时清空补充缓存
- 各 Settings 类把读取类错误与操作类错误分开存储,定时 `refresh` 不能抹掉用户操作或校验的结论,参见 `CodexHookSettings` 与 `KeepAliveController`
- Hook 子进程任何失败都静默退出,优先保证不拖慢 Codex
@@ -267,6 +267,8 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- `MenuSurfaceDismissMonitor` 将鼠标、键盘和激活事件汇总为关闭请求,`StatusItemController.popoverDidClose` 接收 AppKit 实际关闭回调;主动关闭容器前将 `activeMenuSurface` 设为 `none`,回调只对仍为当前容器的 popover 执行完整收尾
- `MenuSurfaceFadeCoordinator` 同时调整内容视图和窗口透明度,淡入 0.24 秒、淡出 0.18 秒,只保留一个完成任务,新动画取消旧任务
- popover 和备用面板分别持有 `MenuSurfaceAnimationState`,展示前允许动画,淡出期间保持开启,实际关闭后禁用;根视图在禁用时设置 `transaction.animation = nil` 和 `transaction.disablesAnimations = true`,后台刷新继续执行
+- 主面板淡入完成且仍可见时,检查 Hook 配置、本地统计和账户数据是否需要刷新;淡入完成前关闭面板会取消该回调
+- 任务流光消费独立展示更新,开关与主面板动画独立;多屏、焦点和终态时限见 [任务流光](Docs/DeveloperGuide/ui-and-lifecycle.md#任务流光)
- 主面板的热力图详情、重置次数和任务中心使用 `borderless nonactivating child panel`;设置窗口的主面板布局、通知、自动重置和防睡眠选项使用可获得键盘焦点的 `borderless child panel`
- 设置窗口的子面板占同一位置,展开一个必须先 `hide(immediate: true)` 收掉其余的;动作走 `SettingsOptionsPanelAction` 并带上目标 `SettingsOptionsPanel`,互斥与 `closeAll` 都只写在 `SettingsWindowController.handleOptionsAction` 一处,新增面板不会漏配对
- 面板控制器只在首次展开时构造,收起动作走 `existingOptionsPanelController` 而不触发构造:`NSHostingController` 与动态面板订阅会常驻到 App 结束,而用户可能一次子面板都没开过
@@ -302,7 +304,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 只识别并移除 command 同时包含当前 CodexBar 可执行路径与 `--hook-event` 的 handler,必须保留用户已有 Hook 以及其他 App 的 Hook 和同事件下的其他 handler
- 每个 `CodexHookEvent.allCases` 事件追加一个独立 group,handler 超时从 `WorkflowHookEventRecorder.hookTimeoutSeconds(for:)` 取得;新增事件时不得复制一份超时常量
-- 启用和校验 Hook 前要求当前 app-server 握手版本至少为 `0.145.0`;必须检查 `readyConnectionInfo()` 返回的实际连接版本,不能用磁盘版本代替,否则升级后尚未重连的旧进程会被误判为可用
+- 账户主链路要求当前 app-server 至少为 `0.145.0`,Hook 启用和校验要求至少为 `0.150.0`;版本依据为握手返回的实际连接信息
- 写入前通过 app-server `config/read` 确认全局未禁用 Hook,写入后用 `hooks/list` 验证;两处读取共用 `readGlobalHookDisabled`,开关流程与校验流程对“全局禁用”的判断不会分叉
- 读取失败(I/O 或 JSON 格式错误)不提供 Hook 装没装的信息,必须保留上次已知值,不能当成用户关闭了 Hook
- `isEnabled` 表示当前进程中的 Hook 开启状态,首次从已有 handler 恢复;开启后配置缺失会触发自愈。`isVerified` 保存最近一次校验的明确结论,`isOperable` 为两者的合取
diff --git a/CodexBar/Controllers/CodexBarAppDelegate.swift b/CodexBar/Controllers/CodexBarAppDelegate.swift
index 6d84650..257585a 100644
--- a/CodexBar/Controllers/CodexBarAppDelegate.swift
+++ b/CodexBar/Controllers/CodexBarAppDelegate.swift
@@ -25,11 +25,13 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
let globalHotKeySettings = GlobalHotKeySettings()
let menuBarQuotaSettings = MenuBarQuotaSettings()
let mainPanelSettings = MainPanelSettings()
+ let taskGlowSettings = TaskGlowSettings()
let notificationSettings = NotificationSettings()
let autoResetSettings = AutoResetSettings()
let appUpdater = AppUpdater()
private var statusItemController: StatusItemController?
+ private var taskGlowController: TaskGlowController?
private var notificationService: CodexNotificationService?
private var autoResetController: AutoResetController?
private var terminationPreparationTask: Task<Void, Never>?
@@ -50,6 +52,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
globalHotKeySettings: globalHotKeySettings,
menuBarQuotaSettings: menuBarQuotaSettings,
mainPanelSettings: mainPanelSettings,
+ taskGlowSettings: taskGlowSettings,
notificationSettings: notificationSettings,
autoResetSettings: autoResetSettings,
keepAliveController: keepAliveController,
@@ -91,6 +94,13 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
activityMonitor.onInactivityProtectionInvalidated = { [weak notificationService] taskID, attemptID in
notificationService?.invalidateActivityProtectionNotification(taskID: taskID, attemptID: attemptID)
}
+ let taskGlowController = TaskGlowController(
+ settings: taskGlowSettings,
+ activityMonitor: activityMonitor,
+ hookSettings: codexHookSettings
+ )
+ taskGlowController.start()
+ self.taskGlowController = taskGlowController
activityMonitor.start()
keepAliveController.start()
logLaunchState()
@@ -104,6 +114,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
statusItemController?.uninstall()
autoResetController?.stop()
keepAliveController.stop()
+ taskGlowController?.stop()
activityMonitor.stop()
}
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index f5fafe1..76fc4be 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -14,6 +14,7 @@ final class SettingsWindowController: HostingWindowController {
private let globalHotKeySettings: GlobalHotKeySettings
private let menuBarQuotaSettings: MenuBarQuotaSettings
private let mainPanelSettings: MainPanelSettings
+ private let taskGlowSettings: TaskGlowSettings
private let notificationSettings: NotificationSettings
private let autoResetSettings: AutoResetSettings
private let activityProtectionSettings: ActivityProtectionSettings
@@ -42,6 +43,7 @@ final class SettingsWindowController: HostingWindowController {
globalHotKeySettings: GlobalHotKeySettings,
menuBarQuotaSettings: MenuBarQuotaSettings,
mainPanelSettings: MainPanelSettings,
+ taskGlowSettings: TaskGlowSettings,
notificationSettings: NotificationSettings,
autoResetSettings: AutoResetSettings,
activityProtectionSettings: ActivityProtectionSettings,
@@ -59,6 +61,7 @@ final class SettingsWindowController: HostingWindowController {
self.globalHotKeySettings = globalHotKeySettings
self.menuBarQuotaSettings = menuBarQuotaSettings
self.mainPanelSettings = mainPanelSettings
+ self.taskGlowSettings = taskGlowSettings
self.notificationSettings = notificationSettings
self.autoResetSettings = autoResetSettings
self.activityProtectionSettings = activityProtectionSettings
@@ -87,6 +90,7 @@ final class SettingsWindowController: HostingWindowController {
globalHotKeySettings: globalHotKeySettings,
menuBarQuotaSettings: menuBarQuotaSettings,
mainPanelSettings: mainPanelSettings,
+ taskGlowSettings: taskGlowSettings,
notificationSettings: notificationSettings,
autoResetSettings: autoResetSettings,
keepAliveController: keepAliveController,
@@ -158,6 +162,7 @@ final class SettingsWindowController: HostingWindowController {
syncSettings.refresh()
menuBarQuotaSettings.refresh()
mainPanelSettings.refresh()
+ taskGlowSettings.refresh()
autoResetSettings.refresh()
activityProtectionSettings.refresh()
keepAliveController.refresh()
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index ff680bb..475bdab 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -15,6 +15,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private let globalHotKeySettings: GlobalHotKeySettings
private let menuBarQuotaSettings: MenuBarQuotaSettings
private let mainPanelSettings: MainPanelSettings
+ private let taskGlowSettings: TaskGlowSettings
private let notificationSettings: NotificationSettings
private let autoResetSettings: AutoResetSettings
private let keepAliveController: KeepAliveController
@@ -51,6 +52,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
globalHotKeySettings: globalHotKeySettings,
menuBarQuotaSettings: menuBarQuotaSettings,
mainPanelSettings: mainPanelSettings,
+ taskGlowSettings: taskGlowSettings,
notificationSettings: notificationSettings,
autoResetSettings: autoResetSettings,
activityProtectionSettings: activityMonitor.activityProtectionSettings,
@@ -101,7 +103,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
self?.isPointInDetailPanel(screenPoint) == true
}
)
- private var delayedStatusRefreshTask: Task<Void, Never>?
private var menuSurfaceState = MenuSurfaceState.hidden
private var cancellables = Set<AnyCancellable>()
private var statusIconState: StatusIconState?
@@ -124,6 +125,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
globalHotKeySettings: GlobalHotKeySettings,
menuBarQuotaSettings: MenuBarQuotaSettings,
mainPanelSettings: MainPanelSettings,
+ taskGlowSettings: TaskGlowSettings,
notificationSettings: NotificationSettings,
autoResetSettings: AutoResetSettings,
keepAliveController: KeepAliveController,
@@ -139,6 +141,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
self.globalHotKeySettings = globalHotKeySettings
self.menuBarQuotaSettings = menuBarQuotaSettings
self.mainPanelSettings = mainPanelSettings
+ self.taskGlowSettings = taskGlowSettings
self.notificationSettings = notificationSettings
self.autoResetSettings = autoResetSettings
self.keepAliveController = keepAliveController
@@ -709,14 +712,8 @@ final class StatusItemController: NSObject, NSMenuDelegate {
return trustedScreenFrame.intersects(buttonScreenRect)
}
- private func cancelMenuSurfaceTasks() {
- delayedStatusRefreshTask?.cancel()
- delayedStatusRefreshTask = nil
- menuSurfaceFadeCoordinator.cancel()
- }
-
private func openPopover(relativeTo button: NSStatusBarButton) {
- cancelMenuSurfaceTasks()
+ menuSurfaceFadeCoordinator.cancel()
menuSurfaceState = .opening
activeMenuSurface = .popover
@@ -728,7 +725,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
}
private func openFallbackPanel(on screen: NSScreen?) {
- cancelMenuSurfaceTasks()
+ menuSurfaceFadeCoordinator.cancel()
fallbackPanelAnimationState.allowsAnimations = true
fallbackPanelController.prepareForDisplay(on: screen)
@@ -742,7 +739,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private func completeMenuSurfaceOpen() {
menuSurfaceVisibility.beginPresentation()
- refreshWorkflowIfHookEnabled(performMaintenance: false)
menuSurfaceDismissMonitor.install(
onDismiss: { [weak self] in
self?.closeMenuSurface()
@@ -753,10 +749,12 @@ final class StatusItemController: NSObject, NSMenuDelegate {
)
menuSurfaceFadeCoordinator.fadeIn(duration: Metrics.fadeInDuration) { [weak self] in
- self?.menuSurfaceState = .shown
+ guard let self, isActiveMenuSurfaceVisible else { return }
+ menuSurfaceState = .shown
+ // 展开完成后再刷新共享状态, 避免主面板与设置窗口在淡入期间一起重算
+ refreshWorkflowIfHookEnabled(performMaintenance: false)
+ viewModel.refreshIfNeeded(trigger: .panelOpen)
}
-
- scheduleDelayedStatusRefresh()
}
// MARK: - 右键菜单
@@ -894,7 +892,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
return
}
- cancelMenuSurfaceTasks()
+ menuSurfaceFadeCoordinator.cancel()
hideSideDetailPanels()
menuSurfaceDismissMonitor.remove()
menuSurfaceVisibility.endPresentation()
@@ -929,7 +927,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
}
private func completeMenuSurfaceClose(hidesDetailPanel: Bool = true) {
- cancelMenuSurfaceTasks()
+ menuSurfaceFadeCoordinator.cancel()
if hidesDetailPanel {
hideSideDetailPanels()
}
@@ -988,18 +986,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
// MARK: - 刷新与同步
- private func scheduleDelayedStatusRefresh() {
- delayedStatusRefreshTask?.cancel()
- delayedStatusRefreshTask = Task { @MainActor [weak self] in
- try? await Task.sleep(for: .milliseconds(160))
- guard let self, !Task.isCancelled, isActiveMenuSurfaceVisible else {
- return
- }
-
- viewModel.refreshIfNeeded(trigger: .panelOpen)
- }
- }
-
private func refreshWorkflowIfHookEnabled(performMaintenance: Bool) {
// Hook 与额度使用同一刷新节奏, 配置和信任状态损坏后都能自动收敛
codexHookSettings.reconcileInstalledHooks()
diff --git a/CodexBar/Controllers/TaskGlowController.swift b/CodexBar/Controllers/TaskGlowController.swift
new file mode 100644
index 0000000..6cabb75
--- /dev/null
+++ b/CodexBar/Controllers/TaskGlowController.swift
@@ -0,0 +1,793 @@
+import AppKit
+import Combine
+import QuartzCore
+
+/// 只消费实时任务的展示更新, 不参与任务通知或防睡眠判定
+@MainActor
+final class TaskGlowController {
+ private let settings: TaskGlowSettings
+ private let activityMonitor: CodexActivityMonitor
+ private let hookSettings: CodexHookSettings
+ private var cancellables = Set<AnyCancellable>()
+ private var panels: [TaskGlowPanel] = []
+ private let motionClock = TaskGlowMotionClock()
+ private var presentation = TaskGlowPresentationState()
+ private var isEnabled = false
+ private var expirationTask: Task<Void, Never>?
+ private var scheduledExpiration: Date?
+ private var hidePanelsTask: Task<Void, Never>?
+ private var isSystemSleeping = false
+ private var isDisplaySleeping = false
+ private var isSessionActive = true
+
+ init(
+ settings: TaskGlowSettings,
+ activityMonitor: CodexActivityMonitor,
+ hookSettings: CodexHookSettings
+ ) {
+ self.settings = settings
+ self.activityMonitor = activityMonitor
+ self.hookSettings = hookSettings
+ }
+
+ deinit {
+ expirationTask?.cancel()
+ hidePanelsTask?.cancel()
+ }
+
+ func start() {
+ guard cancellables.isEmpty else { return }
+ Publishers.CombineLatest3(
+ settings.$isEnabled,
+ hookSettings.$isEnabled,
+ hookSettings.$isVerified
+ )
+ .sink { [weak self] enabled, hookEnabled, hookVerified in
+ guard let self else { return }
+ isEnabled = enabled && hookEnabled && hookVerified
+ consume(CodexActivityPresentationUpdate(snapshot: activityMonitor.snapshot, terminalEvents: []))
+ }
+ .store(in: &cancellables)
+
+ activityMonitor.presentationPublisher
+ .sink { [weak self] update in self?.consume(update) }
+ .store(in: &cancellables)
+
+ NotificationCenter.default.publisher(for: NSApplication.didChangeScreenParametersNotification)
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] _ in
+ self?.removePanels(preservingMotion: true)
+ self?.refreshPresentation()
+ }
+ .store(in: &cancellables)
+
+ let workspaceNotifications = [
+ NSWorkspace.willSleepNotification, NSWorkspace.didWakeNotification,
+ NSWorkspace.screensDidSleepNotification, NSWorkspace.screensDidWakeNotification,
+ NSWorkspace.sessionDidResignActiveNotification, NSWorkspace.sessionDidBecomeActiveNotification
+ ]
+ Publishers.MergeMany(workspaceNotifications.map {
+ NSWorkspace.shared.notificationCenter.publisher(for: $0)
+ })
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] notification in
+ self?.handleWorkspaceNotification(notification)
+ }
+ .store(in: &cancellables)
+ }
+
+ func stop() {
+ cancellables.removeAll()
+ expirationTask?.cancel()
+ expirationTask = nil
+ scheduledExpiration = nil
+ presentation = TaskGlowPresentationState()
+ isEnabled = false
+ removePanels()
+ }
+
+ private func consume(_ update: CodexActivityPresentationUpdate) {
+ presentation.update(
+ snapshot: update.snapshot,
+ terminalEvents: update.terminalEvents,
+ isEnabled: isEnabled,
+ acceptsBriefEvents: !isSystemSleeping && !isDisplaySleeping && isSessionActive,
+ now: Date()
+ )
+ refreshPresentation()
+ }
+
+ private func refreshPresentation() {
+ presentation.refresh(now: Date())
+ let expiration = presentation.terminal?.expiresAt
+ updatePanels()
+ guard expiration != scheduledExpiration else { return }
+ expirationTask?.cancel()
+ expirationTask = nil
+ scheduledExpiration = expiration
+ guard let expiration else { return }
+ let delay = expiration.timeIntervalSinceNow
+ expirationTask = Task { @MainActor [weak self] in
+ do {
+ try await Task.sleep(for: .seconds(max(0, delay)))
+ } catch {
+ return
+ }
+ guard let self, !Task.isCancelled else { return }
+ scheduledExpiration = nil
+ expirationTask = nil
+ refreshPresentation()
+ }
+ }
+
+ private func handleWorkspaceNotification(_ notification: Notification) {
+ switch notification.name {
+ case NSWorkspace.willSleepNotification: isSystemSleeping = true
+ case NSWorkspace.didWakeNotification: isSystemSleeping = false
+ case NSWorkspace.screensDidSleepNotification: isDisplaySleeping = true
+ case NSWorkspace.screensDidWakeNotification: isDisplaySleeping = false
+ case NSWorkspace.sessionDidResignActiveNotification: isSessionActive = false
+ case NSWorkspace.sessionDidBecomeActiveNotification: isSessionActive = true
+ default: break
+ }
+ // 唤醒时按墙上时间重算, 不恢复已经过期的终态光带
+ refreshPresentation()
+ }
+
+ private func updatePanels() {
+ guard !isSystemSleeping, !isDisplaySleeping, isSessionActive else {
+ removePanels()
+ return
+ }
+ let state = presentation.state
+ motionClock.setRunning(state == .running)
+ if state == .hidden {
+ guard !panels.isEmpty, hidePanelsTask == nil else { return }
+ for panel in panels {
+ panel.indicatorView.update(state: .hidden)
+ }
+ hidePanelsTask = Task { @MainActor [weak self] in
+ do {
+ try await Task.sleep(for: .seconds(TaskGlowView.dismissalDuration))
+ } catch {
+ return
+ }
+ guard let self, !Task.isCancelled, presentation.state == .hidden else { return }
+ removePanels()
+ }
+ return
+ }
+ hidePanelsTask?.cancel()
+ hidePanelsTask = nil
+ if panels.isEmpty {
+ panels = NSScreen.screens.map { TaskGlowPanel(screen: $0, motionClock: motionClock) }
+ }
+ for panel in panels {
+ panel.indicatorView.update(state: state, terminalPresentation: presentation.terminal)
+ if !panel.isVisible {
+ panel.orderFrontRegardless()
+ }
+ }
+ }
+
+ private func removePanels(preservingMotion: Bool = false) {
+ if !preservingMotion {
+ motionClock.setRunning(false)
+ }
+ hidePanelsTask?.cancel()
+ hidePanelsTask = nil
+ for panel in panels {
+ panel.indicatorView.stopAnimating()
+ panel.orderOut(nil)
+ panel.close()
+ }
+ panels.removeAll()
+ }
+}
+
+private extension CodexActivityTerminalEvent {
+ var glowState: TaskGlowState {
+ switch self {
+ case .completed: .completed
+ case .terminated: .terminated
+ }
+ }
+}
+
+/// 短提示只消费开启后新增的结束记录, 到期后按最新快照恢复等待或运行状态
+private struct TaskGlowPresentationState {
+ private var snapshot = CodexActivitySnapshot.empty
+ private var enabledAt: Date?
+ private var briefEvent: CodexActivityTerminalEvent?
+ private var briefExpiration: Date?
+ private(set) var state = TaskGlowState.hidden
+ private(set) var terminal: TaskGlowTerminalPresentation?
+
+ mutating func update(
+ snapshot: CodexActivitySnapshot,
+ terminalEvents: [CodexActivityTerminalEvent],
+ isEnabled: Bool,
+ acceptsBriefEvents: Bool,
+ now: Date
+ ) {
+ let latestEvent = terminalEvents.max { lhs, rhs in
+ if lhs.endedAt != rhs.endedAt {
+ return lhs.endedAt < rhs.endedAt
+ }
+ if lhs.glowState != rhs.glowState {
+ return rhs.glowState == .terminated
+ }
+ return lhs.id.uuidString < rhs.id.uuidString
+ }
+ if isEnabled, let enabledAt, acceptsBriefEvents,
+ snapshot.hasActiveTasks,
+ let latestEvent, latestEvent.endedAt >= enabledAt {
+ briefEvent = latestEvent
+ briefExpiration = now.addingTimeInterval(3)
+ }
+ if !isEnabled || !acceptsBriefEvents || !snapshot.hasActiveTasks {
+ briefEvent = nil
+ briefExpiration = nil
+ }
+ if !isEnabled {
+ enabledAt = nil
+ } else if enabledAt == nil {
+ enabledAt = now
+ }
+ self.snapshot = snapshot
+ refresh(now: now)
+ }
+
+ mutating func refresh(now: Date) {
+ guard enabledAt != nil else {
+ state = .hidden
+ terminal = nil
+ return
+ }
+ if let briefExpiration, now >= briefExpiration {
+ briefEvent = nil
+ self.briefExpiration = nil
+ }
+ if snapshot.hasActiveTasks, let briefEvent, let briefExpiration {
+ show(briefEvent, until: briefExpiration, fadeDuration: 0.5, now: now)
+ return
+ }
+ if snapshot.waitingCount > 0 {
+ state = .waiting
+ } else if snapshot.runningCount > 0 {
+ state = .running
+ } else if let event = snapshot.latestTerminalEvent,
+ let expiration = snapshot.statusItemActivityExpiration, now < expiration {
+ show(event, until: expiration, fadeDuration: 1, now: now)
+ return
+ } else {
+ state = .hidden
+ }
+ terminal = nil
+ }
+
+ private mutating func show(_ event: CodexActivityTerminalEvent, until expiration: Date, fadeDuration: TimeInterval, now: Date) {
+ if state != event.glowState || terminal?.eventID != event.id || terminal?.expiresAt != expiration
+ || terminal?.fadeDuration != fadeDuration {
+ terminal = TaskGlowTerminalPresentation(
+ eventID: event.id, startedAt: now, expiresAt: expiration, fadeDuration: fadeDuration
+ )
+ }
+ state = event.glowState
+ }
+}
+
+private enum TaskGlowState {
+ case hidden
+ case running
+ case waiting
+ case completed
+ case terminated
+
+ var color: NSColor {
+ switch self {
+ case .hidden: .clear
+ case .running: .systemCyan
+ case .waiting: .systemOrange
+ case .completed: .systemGreen
+ case .terminated: .systemRed
+ }
+ }
+}
+
+/// 终态共用墙上时间, 屏幕重建和唤醒后接续淡出, 不重新提亮
+private struct TaskGlowTerminalPresentation: Equatable {
+ static let entranceDuration: TimeInterval = 1.2
+ let eventID: UUID
+ let startedAt: Date
+ let expiresAt: Date
+ let fadeDuration: TimeInterval
+
+ var duration: TimeInterval {
+ max(0, expiresAt.timeIntervalSince(startedAt))
+ }
+
+ var entranceDuration: TimeInterval {
+ min(Self.entranceDuration, duration / 4)
+ }
+
+ var holdDuration: TimeInterval {
+ max(0, duration - fadeDuration)
+ }
+}
+
+/// 所有屏幕共享同一运动周期, 新窗口直接加入当前进度
+private final class TaskGlowMotionClock {
+ static let travelDuration = 2.0
+ static let offscreenDuration = 0.2
+ static let centerRetractionDuration = 0.3
+ private var isRunning = false
+ private var startedAt: CFTimeInterval?
+
+ func setRunning(_ running: Bool) {
+ guard isRunning != running else { return }
+ isRunning = running
+ startedAt = nil
+ }
+
+ func startTime() -> CFTimeInterval {
+ if let startedAt {
+ return startedAt
+ }
+ let time = CACurrentMediaTime()
+ startedAt = time
+ return time
+ }
+}
+
+private final class TaskGlowPanel: NSPanel {
+ let indicatorView: TaskGlowView
+
+ override var canBecomeKey: Bool {
+ false
+ }
+
+ override var canBecomeMain: Bool {
+ false
+ }
+
+ init(screen: NSScreen, motionClock: TaskGlowMotionClock) {
+ let geometry = TaskGlowGeometry(screenFrame: screen.frame)
+ indicatorView = TaskGlowView(geometry: geometry, scale: screen.backingScaleFactor, motionClock: motionClock)
+ super.init(contentRect: geometry.frame, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
+ isReleasedWhenClosed = false
+ isOpaque = false
+ backgroundColor = .clear
+ hasShadow = false
+ ignoresMouseEvents = true
+ hidesOnDeactivate = false
+ isFloatingPanel = true
+ // iTerm2 等 App 的顶部窗口使用 statusBar + 1, 光带必须在其上方才能露出菜单栏顶边
+ level = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue + 2)
+ // 非激活面板跨 Space 和全屏显示, 不加入窗口循环或抢走当前 App 的焦点
+ collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle, .stationary]
+ animationBehavior = .none
+ contentView = indicatorView
+ }
+}
+
+/// 移动路径贯穿屏幕, 中心部分由屏幕刘海自然遮挡
+private struct TaskGlowGeometry {
+ let frame: NSRect
+ let path: CGPath
+
+ init(screenFrame: NSRect) {
+ let height: CGFloat = 12
+ frame = NSRect(x: screenFrame.minX, y: screenFrame.maxY - height, width: screenFrame.width, height: height)
+ let path = CGMutablePath()
+ path.move(to: CGPoint(x: 0, y: height - 1.5))
+ path.addLine(to: CGPoint(x: screenFrame.width, y: height - 1.5))
+ self.path = path
+ }
+}
+
+private final class TaskGlowView: NSView {
+ private let trackLayer = CAShapeLayer()
+ private let lightLayer = CALayer()
+ private var lightSegments: [CAShapeLayer] = []
+ static let visibilityDuration = 0.24
+ private static let edgeTraversalDuration = 0.7
+ static let dismissalDuration = edgeTraversalDuration / 2 + visibilityDuration
+ private static let segmentsPerSide = 32
+ private static let stationaryColorAlpha: CGFloat = 0.9
+ private let convergencePoint = 0.5
+ private let motionClock: TaskGlowMotionClock
+ private var presentationState: TaskGlowState?
+ private var terminalPresentation: TaskGlowTerminalPresentation?
+ private var contentState: TaskGlowState?
+ private var transitionTask: Task<Void, Never>?
+
+ init(
+ geometry: TaskGlowGeometry,
+ scale: CGFloat,
+ motionClock: TaskGlowMotionClock
+ ) {
+ self.motionClock = motionClock
+ super.init(frame: NSRect(origin: .zero, size: geometry.frame.size))
+ wantsLayer = true
+ layer?.opacity = 0
+ trackLayer.frame = bounds
+ trackLayer.path = geometry.path
+ trackLayer.fillColor = nil
+ trackLayer.lineWidth = 3
+ trackLayer.contentsScale = scale
+ trackLayer.shadowRadius = 4
+ trackLayer.shadowOffset = .zero
+ lightLayer.frame = bounds
+ lightLayer.shadowOpacity = 0.8
+ lightLayer.shadowRadius = 4
+ lightLayer.shadowOffset = .zero
+ layer?.addSublayer(trackLayer)
+ layer?.addSublayer(lightLayer)
+ // 嵌套描边让渐变沿弧长移动, 重叠区域避免相邻短线的抗锯齿接缝
+ for _ in 0 ..< Self.segmentsPerSide * 2 {
+ let segment = CAShapeLayer()
+ segment.frame = bounds
+ segment.path = geometry.path
+ segment.fillColor = nil
+ segment.lineWidth = 3
+ segment.contentsScale = scale
+ lightLayer.addSublayer(segment)
+ lightSegments.append(segment)
+ }
+ setAccessibilityElement(false)
+ }
+
+ @available(*, unavailable)
+ required init?(coder _: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+ func update(state: TaskGlowState, terminalPresentation: TaskGlowTerminalPresentation? = nil) {
+ guard presentationState != state || self.terminalPresentation != terminalPresentation else { return }
+ let continuesTerminal = presentationState == state && self.terminalPresentation != nil && terminalPresentation != nil
+ // 同色提示延长时保留尚未完成的展开, 收尾会读取最新的淡出期限
+ if continuesTerminal, transitionTask != nil {
+ self.terminalPresentation = terminalPresentation
+ return
+ }
+ let terminalOpacity = continuesTerminal ? (trackLayer.presentation() ?? trackLayer).opacity : nil
+ let hasArtwork = contentState != nil && (layer?.presentation()?.opacity ?? layer?.opacity ?? 0) > 0.001
+ presentationState = state
+ self.terminalPresentation = terminalPresentation
+ transitionTask?.cancel()
+ transitionTask = nil
+ freezeArtwork()
+ if state != .hidden {
+ contentState = state
+ }
+
+ if state != .hidden {
+ animateVisibility(to: 1)
+ }
+
+ if let terminalOpacity {
+ showStable(state, initialTerminalOpacity: terminalOpacity)
+ return
+ }
+
+ if let terminalPresentation,
+ Date().timeIntervalSince(terminalPresentation.startedAt) >= terminalPresentation.entranceDuration {
+ showStable(state)
+ return
+ }
+
+ transitionTask = Task { @MainActor [weak self] in
+ guard let self, !Task.isCancelled else { return }
+ do {
+ if hasArtwork {
+ let duration = animateExtent(expanded: false)
+ try await Task.sleep(for: .seconds(duration))
+ guard !Task.isCancelled else { return }
+ }
+ if state == .hidden {
+ contentState = nil
+ animateVisibility(to: 0)
+ } else {
+ if hasArtwork {
+ try await Task.sleep(for: .seconds(0.06))
+ guard !Task.isCancelled else { return }
+ }
+ if state == .running {
+ showStable(.running)
+ fadeInMovingLight()
+ } else {
+ setCollapsedColor(state.color)
+ let duration = animateExtent(expanded: true)
+ try await Task.sleep(for: .seconds(duration))
+ guard !Task.isCancelled else { return }
+ showStable(state)
+ }
+ }
+ transitionTask = nil
+ } catch {
+ return
+ }
+ }
+ }
+
+ func stopAnimating() {
+ transitionTask?.cancel()
+ transitionTask = nil
+ stopArtworkAnimations()
+ layer?.removeAllAnimations()
+ }
+
+ private struct SegmentAppearance {
+ let start: CGFloat
+ let end: CGFloat
+ let color: CGColor?
+ }
+
+ /// 先冻结合成器当前帧, 再移除动画, 防止中途改目标时跳到上一段的终点
+ private func freezeArtwork() {
+ let usesTrack = !trackLayer.isHidden
+ let track = trackLayer.presentation() ?? trackLayer
+ let light = lightLayer.presentation() ?? lightLayer
+ let opacity = usesTrack ? track.opacity : light.opacity
+ let appearances = lightSegments.enumerated().map { index, segment -> SegmentAppearance in
+ if usesTrack {
+ return SegmentAppearance(
+ start: index < Self.segmentsPerSide ? 0 : convergencePoint,
+ end: index < Self.segmentsPerSide ? convergencePoint : 1,
+ color: distributedColor(track.strokeColor)
+ )
+ }
+ let current = segment.presentation() ?? segment
+ return SegmentAppearance(start: current.strokeStart, end: current.strokeEnd, color: current.strokeColor)
+ }
+ let shadowColor = usesTrack ? track.shadowColor : light.shadowColor
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ stopArtworkAnimations()
+ trackLayer.isHidden = true
+ lightLayer.isHidden = false
+ lightLayer.opacity = opacity
+ lightLayer.shadowColor = shadowColor
+ for (segment, appearance) in zip(lightSegments, appearances) {
+ segment.strokeStart = appearance.start
+ segment.strokeEnd = appearance.end
+ segment.strokeColor = appearance.color
+ }
+ CATransaction.commit()
+ }
+
+ private func showStable(_ state: TaskGlowState, initialTerminalOpacity: Float? = nil) {
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ stopArtworkAnimations()
+ trackLayer.strokeStart = 0
+ trackLayer.strokeEnd = 1
+ trackLayer.strokeColor = state.color.withAlphaComponent(Self.stationaryColorAlpha).cgColor
+ trackLayer.shadowColor = state.color.cgColor
+ trackLayer.shadowOpacity = 0.8
+ trackLayer.opacity = 1
+ trackLayer.isHidden = state == .running
+ lightLayer.isHidden = state != .running
+ lightLayer.opacity = 1
+ lightLayer.shadowColor = state.color.cgColor
+ if state == .running {
+ configureMovingLight()
+ } else if state == .waiting {
+ let animation = CAKeyframeAnimation(keyPath: "opacity")
+ animation.values = [1, 0, 0, 1]
+ animation.keyTimes = [0, 0.45, 0.55, 1]
+ animation.duration = 1.5
+ animation.repeatCount = .infinity
+ animation.timingFunctions = [
+ CAMediaTimingFunction(name: .easeInEaseOut),
+ CAMediaTimingFunction(name: .linear),
+ CAMediaTimingFunction(name: .easeInEaseOut)
+ ]
+ trackLayer.add(animation, forKey: "breathe")
+ } else if let terminalPresentation {
+ animateTerminalFade(terminalPresentation, initialOpacity: initialTerminalOpacity)
+ }
+ CATransaction.commit()
+ }
+
+ private func animateTerminalFade(_ presentation: TaskGlowTerminalPresentation, initialOpacity: Float?) {
+ trackLayer.opacity = 0
+ let elapsed = max(0, Date().timeIntervalSince(presentation.startedAt))
+ guard presentation.duration > elapsed else { return }
+ let animation = CAKeyframeAnimation(keyPath: "opacity")
+ if presentation.holdDuration > 0 {
+ var values: [Float] = [initialOpacity ?? 1]
+ var times: [NSNumber] = [0]
+ var timingFunctions: [CAMediaTimingFunction] = []
+ if let initialOpacity, initialOpacity < 1 {
+ let recovery = min(Self.visibilityDuration, presentation.holdDuration / 2)
+ values.append(1)
+ times.append(NSNumber(value: recovery / presentation.duration))
+ timingFunctions.append(CAMediaTimingFunction(name: .easeInEaseOut))
+ }
+ animation.values = values + [1, 0]
+ animation.keyTimes = times + [NSNumber(value: presentation.holdDuration / presentation.duration), 1]
+ animation.timingFunctions = timingFunctions + [
+ CAMediaTimingFunction(name: .linear),
+ CAMediaTimingFunction(name: .easeInEaseOut)
+ ]
+ } else {
+ animation.values = [initialOpacity ?? 1, 0]
+ animation.keyTimes = [0, 1]
+ animation.timingFunctions = [CAMediaTimingFunction(name: .easeInEaseOut)]
+ }
+ animation.duration = presentation.duration
+ animation.beginTime = trackLayer.convertTime(CACurrentMediaTime(), from: nil) - elapsed
+ trackLayer.add(animation, forKey: "terminalFade")
+ }
+
+ private func configureMovingLight() {
+ let span = min(0.336, max(0.096, 300 / bounds.width))
+ let startTime = motionClock.startTime()
+ var previousIntensity = 0.0
+ for (index, segment) in lightSegments.enumerated() {
+ let depth = index % Self.segmentsPerSide
+ if depth == 0 {
+ previousIntensity = 0
+ }
+ let position = (Double(depth) + 0.5) / Double(Self.segmentsPerSide)
+ let intensity = pow(sin(position * .pi / 2), 2)
+ let color = TaskGlowState.running.color
+ let tint = color.blended(withFraction: pow(intensity, 8) * 0.8, of: .white) ?? color
+ segment.strokeColor = tint.withAlphaComponent((intensity - previousIntensity) / (1 - previousIntensity)).cgColor
+ previousIntensity = intensity
+ let tailLength = span * (1 - Double(depth) / Double(Self.segmentsPerSide))
+ let isLeft = index < Self.segmentsPerSide
+ segment.strokeStart = convergencePoint
+ segment.strokeEnd = convergencePoint
+ animateEmission(segment, tailLength: tailLength, span: span, isLeft: isLeft, startTime: startTime)
+ }
+ }
+
+ private func animateExtent(expanded: Bool) -> TimeInterval {
+ let targets = lightSegments.indices.map { index in
+ (
+ start: expanded && index < Self.segmentsPerSide ? 0.0 : convergencePoint,
+ end: expanded && index >= Self.segmentsPerSide ? 1.0 : convergencePoint
+ )
+ }
+ let distance = zip(lightSegments, targets).map { segment, target in
+ max(abs(segment.strokeStart - target.start), abs(segment.strokeEnd - target.end))
+ }.max() ?? 0
+ let duration = max(0.001, Double(distance) * Self.edgeTraversalDuration)
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ for (segment, target) in zip(lightSegments, targets) {
+ animateValue(segment, keyPath: "strokeStart", from: segment.strokeStart, to: target.start, duration: duration)
+ animateValue(segment, keyPath: "strokeEnd", from: segment.strokeEnd, to: target.end, duration: duration)
+ segment.strokeStart = target.start
+ segment.strokeEnd = target.end
+ }
+ CATransaction.commit()
+ return duration
+ }
+
+ private func setCollapsedColor(_ color: NSColor) {
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ stopArtworkAnimations()
+ lightLayer.opacity = 1
+ lightLayer.shadowColor = color.cgColor
+ for segment in lightSegments {
+ segment.strokeStart = convergencePoint
+ segment.strokeEnd = convergencePoint
+ segment.strokeColor = distributedColor(color.withAlphaComponent(Self.stationaryColorAlpha).cgColor)
+ }
+ CATransaction.commit()
+ }
+
+ private func distributedColor(_ color: CGColor?) -> CGColor? {
+ guard let color, let base = NSColor(cgColor: color) else { return color }
+ let alpha = 1 - pow(1 - base.alphaComponent, 1 / Double(Self.segmentsPerSide))
+ return base.withAlphaComponent(alpha).cgColor
+ }
+
+ private func animateVisibility(to opacity: Float) {
+ guard let layer else { return }
+ let current = layer.presentation()?.opacity ?? layer.opacity
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ layer.removeAnimation(forKey: "visibility")
+ layer.opacity = opacity
+ animateValue(layer, keyPath: "opacity", from: current, to: opacity, duration: Self.visibilityDuration, key: "visibility")
+ CATransaction.commit()
+ }
+
+ private func fadeInMovingLight() {
+ animateValue(lightLayer, keyPath: "opacity", from: Float(0), to: Float(1), duration: 0.18)
+ }
+
+ private func animateValue(_ layer: CALayer, keyPath: String, from: Any?, to: Any?, duration: TimeInterval, key: String? = nil) {
+ let animation = CABasicAnimation(keyPath: keyPath)
+ animation.fromValue = from
+ animation.toValue = to
+ animation.duration = duration
+ animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ layer.add(animation, forKey: key ?? keyPath)
+ }
+
+ private func stopArtworkAnimations() {
+ trackLayer.removeAllAnimations()
+ lightLayer.removeAllAnimations()
+ for segment in lightSegments {
+ segment.removeAllAnimations()
+ }
+ }
+
+ /// 各屏幕共享出发和掉头时刻, 回程拖尾完全收进中心后才开始下一轮
+ private func animateEmission(_ segment: CAShapeLayer, tailLength: Double, span: Double, isLeft: Bool, startTime: CFTimeInterval) {
+ let halfCrossing = TaskGlowMotionClock.travelDuration / 2
+ let offscreen = TaskGlowMotionClock.offscreenDuration
+ let outwardDuration = halfCrossing + offscreen
+ let inwardDuration = halfCrossing + offscreen + TaskGlowMotionClock.centerRetractionDuration
+ let outward = emissionAnimation(
+ waypoints: [(0, convergencePoint), (halfCrossing, 1), (outwardDuration, 1 + span)],
+ tailLength: tailLength, isLeft: isLeft
+ )
+ let inward = emissionAnimation(
+ waypoints: [
+ (0, 1 + span), (offscreen, 1),
+ (offscreen + halfCrossing, convergencePoint), (inwardDuration, convergencePoint - span)
+ ],
+ tailLength: tailLength, isLeft: isLeft
+ )
+ inward.beginTime = outwardDuration
+ // 每个单程独立缓入缓出, 保证两端掉头都平滑
+ let travel = CAAnimationGroup()
+ travel.animations = [outward, inward]
+ travel.duration = outwardDuration + inwardDuration
+ travel.beginTime = segment.convertTime(startTime, from: nil)
+ travel.repeatCount = .infinity
+ segment.add(travel, forKey: "emission")
+ }
+
+ /// 在描边进入和离开屏幕的拐点插入关键帧, 屏幕外掉头时同时翻转拖尾方向
+ private func emissionAnimation(
+ waypoints: [(time: Double, head: Double)],
+ tailLength: Double,
+ isLeft: Bool
+ ) -> CAAnimationGroup {
+ let duration = waypoints.last!.time
+ var times: [Double] = []
+ var starts: [Double] = []
+ var ends: [Double] = []
+ for (from, to) in zip(waypoints, waypoints.dropFirst()) {
+ let distance = to.head - from.head
+ let tailOffset = distance > 0 ? -tailLength : tailLength
+ let crossings = [convergencePoint, 1].flatMap { boundary in
+ [0, tailOffset].map { (boundary - from.head - $0) / distance }
+ }
+ let progress = Array(Set([0.0, 1.0] + crossings.filter { $0 > 0 && $0 < 1 })).sorted()
+ for fraction in progress {
+ let time = from.time + (to.time - from.time) * fraction
+ if times.last == time {
+ continue
+ }
+ let head = from.head + distance * fraction
+ let tail = head + tailOffset
+ let start = min(1, max(convergencePoint, min(head, tail)))
+ let end = min(1, max(convergencePoint, max(head, tail)))
+ times.append(time)
+ starts.append(isLeft ? 1 - end : start)
+ ends.append(isLeft ? 1 - start : end)
+ }
+ }
+ let startAnimation = CAKeyframeAnimation(keyPath: "strokeStart")
+ startAnimation.keyTimes = times.map { NSNumber(value: $0 / duration) }
+ startAnimation.values = starts
+ let endAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")
+ endAnimation.keyTimes = startAnimation.keyTimes
+ endAnimation.values = ends
+ let animation = CAAnimationGroup()
+ animation.animations = [startAnimation, endAnimation]
+ animation.duration = duration
+ animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ return animation
+ }
+}
diff --git a/CodexBar/Models/CodexActivityModels.swift b/CodexBar/Models/CodexActivityModels.swift
index cd1de9a..b2f7033 100644
--- a/CodexBar/Models/CodexActivityModels.swift
+++ b/CodexBar/Models/CodexActivityModels.swift
@@ -16,6 +16,7 @@ nonisolated enum CodexActivityEvent: Equatable {
case subagentStarted
case subagentFinished
case approvalRequested
+ case stopRequested
}
/// bootstrap 后需要向更早日期定向查找 Prompt 起点的精确任务引用
@@ -51,7 +52,32 @@ nonisolated struct CodexActivityCompletion: Equatable, Identifiable {
let duration: TimeInterval?
}
-/// 最近确认终止的任务; 终止不会被视为完成, 也不会触发完成提醒
+/// 本轮确认的终态和快照一起发布, 历史恢复只发布快照
+nonisolated struct CodexActivityPresentationUpdate {
+ let snapshot: CodexActivitySnapshot
+ let terminalEvents: [CodexActivityTerminalEvent]
+}
+
+nonisolated enum CodexActivityTerminalEvent: Equatable {
+ case completed(CodexActivityCompletion)
+ case terminated(CodexActivityTermination)
+
+ var id: UUID {
+ switch self {
+ case let .completed(completion): completion.id
+ case let .terminated(termination): termination.id
+ }
+ }
+
+ var endedAt: Date {
+ switch self {
+ case let .completed(completion): completion.completedAt
+ case let .terminated(termination): termination.terminatedAt
+ }
+ }
+}
+
+/// 最近确认终止的任务; 中断和其他终止都不会触发完成提醒
nonisolated struct CodexActivityTermination: Equatable, Identifiable {
let id: UUID
let isAnonymous: Bool
@@ -102,6 +128,14 @@ nonisolated struct CodexActivitySnapshot: Equatable {
recentTerminations.first
}
+ var latestTerminalEvent: CodexActivityTerminalEvent? {
+ if let termination = mostRecentTermination,
+ mostRecentCompletion.map({ termination.terminatedAt >= $0.completedAt }) ?? true {
+ return .terminated(termination)
+ }
+ return mostRecentCompletion.map(CodexActivityTerminalEvent.completed)
+ }
+
var waitingCount: Int {
waitingTasks.count
}
@@ -130,42 +164,33 @@ nonisolated struct CodexActivitySnapshot: Equatable {
if let task = primaryRunningTask {
return .running(task)
}
- if let completion = mostRecentCompletion {
- return .completed(completion)
- }
- if let termination = mostRecentTermination {
+ switch latestTerminalEvent {
+ case let .terminated(termination):
return .terminated(termination)
+ case let .completed(completion):
+ return .completed(completion)
+ case nil:
+ return .idle
}
- return .idle
}
/// 菜单栏只短暂显示最新终态, 不改变活动卡片的历史展示规则
func statusItemActivity(at now: Date) -> CodexPrimaryActivity {
- if let task = primaryWaitingTask {
- return .waiting(task)
- }
- if let task = primaryRunningTask {
- return .running(task)
- }
- guard let expiration = statusItemActivityExpiration, now < expiration else {
- return .idle
- }
- if let termination = mostRecentTermination,
- mostRecentCompletion.map({ termination.terminatedAt >= $0.completedAt }) ?? true {
- return .terminated(termination)
- }
- if let completion = mostRecentCompletion {
- return .completed(completion)
+ let activity = primaryActivity
+ switch activity {
+ case .completed, .terminated:
+ guard let expiration = statusItemActivityExpiration, now < expiration else {
+ return .idle
+ }
+ return activity
+ case .waiting, .running, .idle:
+ return activity
}
- return .idle
}
var statusItemActivityExpiration: Date? {
guard !hasActiveTasks else { return nil }
- return [mostRecentCompletion?.completedAt, mostRecentTermination?.terminatedAt]
- .compactMap(\.self)
- .max()?
- .addingTimeInterval(10)
+ return latestTerminalEvent?.endedAt.addingTimeInterval(10)
}
}
@@ -246,6 +271,8 @@ nonisolated enum CodexActivityDisplayFormat {
String(localized: "activity.event.subagent-completed")
case .approvalRequested:
String(localized: "activity.status.waiting-for-approval")
+ case .stopRequested:
+ String(localized: "activity.event.finishing")
}
}
diff --git a/CodexBar/Models/CodexHookEvent.swift b/CodexBar/Models/CodexHookEvent.swift
index 284e872..1000785 100644
--- a/CodexBar/Models/CodexHookEvent.swift
+++ b/CodexBar/Models/CodexHookEvent.swift
@@ -11,6 +11,7 @@ nonisolated enum CodexHookEvent: String, CaseIterable, Hashable {
case preCompact = "PreCompact"
case postCompact = "PostCompact"
case stop = "Stop"
+ case interrupt = "Interrupt"
case subagentStart = "SubagentStart"
case subagentStop = "SubagentStop"
diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swift
index 548b977..cccb5d5 100644
--- a/CodexBar/Models/CodexWorkflowModels.swift
+++ b/CodexBar/Models/CodexWorkflowModels.swift
@@ -249,6 +249,7 @@ nonisolated struct WorkflowDailyMetrics: Equatable {
let contextCompactionCount: Int
let subagentCount: Int
let modelCounts: [String: Int]
+ let interruptCount: Int?
var mostUsedModel: String? {
modelCounts
@@ -267,7 +268,8 @@ nonisolated struct WorkflowDailyMetrics: Equatable {
permissionRequestCount: Int,
contextCompactionCount: Int,
subagentCount: Int,
- modelCounts: [String: Int] = [:]
+ modelCounts: [String: Int] = [:],
+ interruptCount: Int? = nil
) {
self.startDate = startDate
self.sessionCount = sessionCount
@@ -277,6 +279,7 @@ nonisolated struct WorkflowDailyMetrics: Equatable {
self.contextCompactionCount = contextCompactionCount
self.subagentCount = subagentCount
self.modelCounts = modelCounts
+ self.interruptCount = interruptCount
}
static func empty(startDate: String) -> WorkflowDailyMetrics {
@@ -302,7 +305,8 @@ nonisolated struct WorkflowDailyMetrics: Equatable {
postCompactCount: Int,
subagentStartCount: Int,
subagentStopCount: Int,
- modelCounts: [String: Int]
+ modelCounts: [String: Int],
+ interruptCount: Int? = nil
) {
self.startDate = startDate
self.sessionCount = sessionCount
@@ -312,6 +316,7 @@ nonisolated struct WorkflowDailyMetrics: Equatable {
contextCompactionCount = max(preCompactCount, postCompactCount)
subagentCount = max(subagentStartCount, subagentStopCount)
self.modelCounts = modelCounts
+ self.interruptCount = interruptCount
}
func adding(_ other: WorkflowDailyMetrics) -> WorkflowDailyMetrics {
@@ -323,7 +328,8 @@ nonisolated struct WorkflowDailyMetrics: Equatable {
permissionRequestCount: permissionRequestCount + other.permissionRequestCount,
contextCompactionCount: contextCompactionCount + other.contextCompactionCount,
subagentCount: subagentCount + other.subagentCount,
- modelCounts: Self.mergedCounts(modelCounts, other.modelCounts)
+ modelCounts: Self.mergedCounts(modelCounts, other.modelCounts),
+ interruptCount: interruptCount.flatMap { lhs in other.interruptCount.map { lhs + $0 } }
)
}
@@ -479,6 +485,7 @@ nonisolated struct WorkflowDailyAccumulator {
case .sessionEnd: Self.increment(&aggregate.sessionEndCount)
case .userPromptSubmit: Self.increment(&aggregate.userPromptSubmitCount)
case .stop: Self.increment(&aggregate.stopCount)
+ case .interrupt: Self.increment(&aggregate.interruptCount)
case .preToolUse: Self.increment(&aggregate.preToolUseCount)
case .postToolUse: Self.increment(&aggregate.postToolUseCount)
case .permissionRequest: Self.increment(&aggregate.permissionRequestCount)
@@ -489,11 +496,11 @@ nonisolated struct WorkflowDailyAccumulator {
case .none: break
}
- // SessionEnd 只关闭会话, Stop 只关闭轮次, 不单独构成对应的当日活跃记录
+ // 终态事件不单独构成对应的当日活跃轮次
if event.hookEvent != .sessionEnd, let sessionId = event.sessionId {
sessionIds.insert(sessionId)
}
- if event.hookEvent != .stop, let turnId = event.turnId {
+ if event.hookEvent != .stop, event.hookEvent != .interrupt, let turnId = event.turnId {
turnIds.insert(turnId)
}
@@ -538,6 +545,11 @@ nonisolated struct WorkflowHookCountAvailability {
events: Set(CodexHookEvent.allCases)
)
+ static let legacy = WorkflowHookCountAvailability(
+ includesEventCount: true,
+ events: Set(CodexHookEvent.allCases.filter { $0 != .interrupt })
+ )
+
private let includesEventCount: Bool
private let events: Set<CodexHookEvent>
@@ -570,6 +582,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
var sessionEndCount: Int?
var userPromptSubmitCount: Int?
var stopCount: Int?
+ var interruptCount: Int?
var preToolUseCount: Int?
var postToolUseCount: Int?
var permissionRequestCount: Int?
@@ -603,6 +616,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
sessionEndCount = hookCountAvailability.initialCount(for: .sessionEnd)
userPromptSubmitCount = hookCountAvailability.initialCount(for: .userPromptSubmit)
stopCount = hookCountAvailability.initialCount(for: .stop)
+ interruptCount = hookCountAvailability.initialCount(for: .interrupt)
preToolUseCount = hookCountAvailability.initialCount(for: .preToolUse)
postToolUseCount = hookCountAvailability.initialCount(for: .postToolUse)
permissionRequestCount = hookCountAvailability.initialCount(for: .permissionRequest)
@@ -628,6 +642,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
sessionEndCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndCount)
userPromptSubmitCount = try container.decodeIfPresent(Int.self, forKey: .userPromptSubmitCount)
stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount)
+ interruptCount = try container.decodeIfPresent(Int.self, forKey: .interruptCount)
preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount)
postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount)
permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount)
@@ -662,37 +677,8 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
turnIds = nil
}
- /// 正数压缩计数和可用 ID 集合优先, 空集合保留明确的 0
- private var resolvedSessionCount: Int {
- WorkflowCountResolution.resolvedCount(
- compactedCount: sessionCount,
- identifiers: sessionIds,
- fallback: sessionStartCount ?? 0
- )
- }
-
- private var resolvedTurnCount: Int {
- WorkflowCountResolution.resolvedCount(
- compactedCount: turnCount,
- identifiers: turnIds,
- fallback: stopCount ?? 0
- )
- }
-
var metrics: WorkflowDailyMetrics {
- WorkflowDailyMetrics(
- startDate: date,
- sessionCount: resolvedSessionCount,
- turnCount: resolvedTurnCount,
- preToolUseCount: preToolUseCount ?? 0,
- postToolUseCount: postToolUseCount ?? 0,
- permissionRequestCount: permissionRequestCount ?? 0,
- preCompactCount: preCompactCount ?? 0,
- postCompactCount: postCompactCount ?? 0,
- subagentStartCount: subagentStartCount ?? 0,
- subagentStopCount: subagentStopCount ?? 0,
- modelCounts: modelCounts
- )
+ syncedAggregate.metrics
}
static func normalized(
@@ -752,6 +738,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
case .sessionEnd: sessionEndCount
case .userPromptSubmit: userPromptSubmitCount
case .stop: stopCount
+ case .interrupt: interruptCount
case .preToolUse: preToolUseCount
case .postToolUse: postToolUseCount
case .permissionRequest: permissionRequestCount
@@ -771,6 +758,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
sessionEndCount: sessionEndCount,
userPromptSubmitCount: userPromptSubmitCount,
stopCount: stopCount,
+ interruptCount: interruptCount,
preToolUseCount: preToolUseCount,
postToolUseCount: postToolUseCount,
permissionRequestCount: permissionRequestCount,
@@ -806,6 +794,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
("sessionEndCount", sessionEndCount),
("userPromptSubmitCount", userPromptSubmitCount),
("stopCount", stopCount),
+ ("interruptCount", interruptCount),
("preToolUseCount", preToolUseCount),
("postToolUseCount", postToolUseCount),
("permissionRequestCount", permissionRequestCount),
@@ -833,6 +822,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
case sessionEndCount
case userPromptSubmitCount
case stopCount
+ case interruptCount
case preToolUseCount
case postToolUseCount
case permissionRequestCount
@@ -858,6 +848,7 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable {
var sessionEndCount: Int?
var userPromptSubmitCount: Int?
var stopCount: Int?
+ var interruptCount: Int?
var preToolUseCount: Int?
var postToolUseCount: Int?
var permissionRequestCount: Int?
@@ -888,7 +879,8 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable {
postCompactCount: postCompactCount ?? 0,
subagentStartCount: subagentStartCount ?? 0,
subagentStopCount: subagentStopCount ?? 0,
- modelCounts: modelCounts
+ modelCounts: modelCounts,
+ interruptCount: interruptCount
)
}
@@ -915,6 +907,7 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable {
("sessionEndCount", sessionEndCount),
("userPromptSubmitCount", userPromptSubmitCount),
("stopCount", stopCount),
+ ("interruptCount", interruptCount),
("preToolUseCount", preToolUseCount),
("postToolUseCount", postToolUseCount),
("permissionRequestCount", permissionRequestCount),
@@ -949,6 +942,7 @@ nonisolated struct WorkflowSyncedDailyAggregate: Codable, Equatable {
case sessionEndCount
case userPromptSubmitCount
case stopCount
+ case interruptCount
case preToolUseCount
case postToolUseCount
case permissionRequestCount
@@ -973,6 +967,7 @@ extension WorkflowSyncedDailyAggregate {
sessionEndCount = try container.decodeIfPresent(Int.self, forKey: .sessionEndCount)
userPromptSubmitCount = try container.decodeIfPresent(Int.self, forKey: .userPromptSubmitCount)
stopCount = try container.decodeIfPresent(Int.self, forKey: .stopCount)
+ interruptCount = try container.decodeIfPresent(Int.self, forKey: .interruptCount)
preToolUseCount = try container.decodeIfPresent(Int.self, forKey: .preToolUseCount)
postToolUseCount = try container.decodeIfPresent(Int.self, forKey: .postToolUseCount)
permissionRequestCount = try container.decodeIfPresent(Int.self, forKey: .permissionRequestCount)
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 5094854..99e63f3 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -337,6 +337,22 @@
}
}
},
+ "activity.event.finishing" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Finishing up"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "即将结束"
+ }
+ }
+ }
+ },
"activity.event.starting-subagent" : {
"localizations" : {
"en" : {
@@ -1857,18 +1873,18 @@
}
}
},
- "hook.error.trust-cleanup-failed" : {
+ "hook.error.trust-cleanup-unavailable" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex Hook disabled. Trust cleanup failed"
+ "value" : "Codex Hook disabled. Cannot clear trust"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "已关闭 Codex Hook, 清理信任状态失败"
+ "value" : "已关闭 Codex Hook, 无法清理信任状态"
}
}
}
@@ -4673,6 +4689,22 @@
}
}
},
+ "settings.screen-edge-indicator.title" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Glow Effect"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "流光效果"
+ }
+ }
+ }
+ },
"settings.sync.title" : {
"localizations" : {
"en" : {
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index 4ed100e..8a1c509 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -361,8 +361,8 @@ private final nonisolated class ProcessExitWaiter: Sendable {
/// CodexBar 各能力依赖的 app-server 最低版本
nonisolated enum CodexCLIMinimumVersion {
- static let global = "0.143.0"
- static let hook = "0.145.0"
+ static let global = "0.145.0"
+ static let hook = "0.150.0"
}
/// 从 ` codex --version` 的输出中提取用户可读版本号
diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swift
index 2ecad8e..c80f438 100644
--- a/CodexBar/Services/CodexStatus/AppServerSession.swift
+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift
@@ -114,10 +114,14 @@ final nonisolated class AppServerSession {
)
let version = Self.serverVersion(fromUserAgent: result.userAgent)
let minimum = CodexCLIMinimumVersion.global
- guard let version, CodexCLIVersionReader.isVersion(version, atLeast: minimum) == true else {
+ // 版本未知不能作为明确的低版本结论, 否则 Hook 对账会误删现有配置
+ guard let version, let isSupported = CodexCLIVersionReader.isVersion(version, atLeast: minimum) else {
+ throw CodexStatusError.invalidServerResponse
+ }
+ guard isSupported else {
let error = CodexStatusError.unsupportedVersion(minimum: minimum)
if let logStorage {
- let details = LogFields.joined("current=\(version ?? "unknown")", "minimum=\(minimum)")
+ let details = LogFields.joined("current=\(version)", "minimum=\(minimum)")
AppLog.codexCLI.notice("Codex 版本不支持: \(details, privacy: .public)")
logStorage.recordFailure(message: error.localizedDescription)
}
diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swift
index bfc3347..afb55c5 100644
--- a/CodexBar/Services/Notifications/CodexNotificationService.swift
+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift
@@ -22,7 +22,6 @@ final class CodexNotificationService: NSObject {
private var cancellables = Set<AnyCancellable>()
private var taskHapticFeedbackTask: Task<Void, Never>?
private var taskWaitingNotificationIdentifiers = Set<String>()
- private var activityProtectionNotificationIdentifiers = Set<String>()
private let creditExpiryReminderScheduler = ReminderCheckScheduler()
private var latestQuotaSnapshot: CodexQuotaSnapshot?
@@ -226,7 +225,6 @@ final class CodexNotificationService: NSObject {
taskID: notice.taskID,
attemptID: notice.attemptID
)
- activityProtectionNotificationIdentifiers.insert(identifier)
let deliveryTask = send(
.activityProtection(
project: notice.projectName,
@@ -242,16 +240,9 @@ final class CodexNotificationService: NSObject {
inactivityDurationSeconds: notice.inactivityDurationSeconds
) ?? false
},
- onSubmissionFailure: { [weak self] in
- self?.activityProtectionNotificationIdentifiers.remove(identifier)
- },
retryCount: 0
)
- let wasSubmitted = await deliveryTask?.value ?? false
- if !wasSubmitted {
- activityProtectionNotificationIdentifiers.remove(identifier)
- }
- return wasSubmitted
+ return await deliveryTask?.value ?? false
}
func invalidateActivityProtectionNotification(taskID: UUID, attemptID: UUID) {
@@ -259,9 +250,6 @@ final class CodexNotificationService: NSObject {
taskID: taskID,
attemptID: attemptID
)
- guard activityProtectionNotificationIdentifiers.remove(identifier) != nil else {
- return
- }
removeNotifications(withIdentifiers: [identifier])
}
diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swift
index 270d8be..cde9631 100644
--- a/CodexBar/Services/Settings/CodexHookSettings.swift
+++ b/CodexBar/Services/Settings/CodexHookSettings.swift
@@ -59,7 +59,7 @@ final class CodexHookSettings: ObservableObject {
in: config,
executablePath: currentExecutablePath
)
- if installed {
+ if installed, !isEnabled {
isEnabled = true
}
let isComplete = Self.containsAllCodexBarHooks(
@@ -76,7 +76,9 @@ final class CodexHookSettings: ObservableObject {
if isEnabled, !isComplete {
assignVerified(false, reason: .configurationDamaged)
}
- readErrorMessage = nil
+ if readErrorMessage != nil {
+ readErrorMessage = nil
+ }
} catch {
// 只有 I/O 失败和 JSON 格式错误会走到这里, 它们对「Hook 装没装」不提供信息
// 文件不存在或配置里没有 CodexBar 都由 readConfigIfPresent 正常返回
@@ -132,13 +134,22 @@ final class CodexHookSettings: ObservableObject {
}
/// 与手动关闭共用同一事务, 自动关闭也不会遗留另一套清理语义
- private func disableCodexBarHooks(generation: Int) async throws {
+ private func disableCodexBarHooks(generation: Int, cleanupTrust: Bool = true) async throws {
// 关闭前先通过 hooks/list 拿到 key
// hooks.json 删除后 app-server 就无法再反查这些 key
- let cleanupPlan = try await hookTrustCleanupPlan(generation: generation)
+ let cleanupPlan: CodexHookTrustCleanupPlan? = if cleanupTrust {
+ try await hookTrustCleanupPlan(generation: generation)
+ } else {
+ nil
+ }
+ try ensureCurrentUpdate(generation)
try writeCodexBarHookConfig(enabled: false)
try ensureCurrentUpdate(generation)
isEnabled = false
+ operationErrorMessage = nil
+ guard let cleanupPlan else {
+ return
+ }
await cleanupCodexHookTrust(
removing: cleanupPlan.keys,
discoveryError: cleanupPlan.discoveryError,
@@ -152,6 +163,14 @@ final class CodexHookSettings: ObservableObject {
try ensureCurrentUpdate(generation)
} catch is CancellationError {
return
+ } catch CodexStatusError.unsupportedVersion(minimum: _) {
+ // 低于全局门槛的连接已关闭, 无法通过 app-server 查询或删除信任项
+ await disableUnsupportedCodexBarHooks(
+ error: .unsupportedCodexVersion(minimum: CodexCLIMinimumVersion.hook),
+ generation: generation,
+ cleanupTrust: false
+ )
+ return
} catch let error as HookConfigError {
guard case .unsupportedCodexVersion = error else {
handleVerificationError(error, generation: generation)
@@ -181,7 +200,9 @@ final class CodexHookSettings: ObservableObject {
try await validateInstalledHooksWithAppServer()
try ensureCurrentUpdate(generation)
assignVerified(true, reason: .verified)
- operationErrorMessage = nil
+ if operationErrorMessage != nil {
+ operationErrorMessage = nil
+ }
} catch is CancellationError {
return
} catch {
@@ -189,11 +210,15 @@ final class CodexHookSettings: ObservableObject {
}
}
- private func disableUnsupportedCodexBarHooks(error: HookConfigError, generation: Int) async {
- assignVerified(false, reason: .unsupportedVersion)
-
+ private func disableUnsupportedCodexBarHooks(
+ error: HookConfigError,
+ generation: Int,
+ cleanupTrust: Bool = true
+ ) async {
do {
- try await disableCodexBarHooks(generation: generation)
+ try ensureCurrentUpdate(generation)
+ assignVerified(false, reason: .unsupportedVersion)
+ try await disableCodexBarHooks(generation: generation, cleanupTrust: cleanupTrust)
try ensureCurrentUpdate(generation)
if operationErrorMessage == nil {
operationErrorMessage = error.localizedDescription
@@ -566,8 +591,8 @@ private extension CodexHookSettings {
"stage=discovery",
"detail=\(discoveryError.localizedDescription)"
)
- AppLog.hooks.error("Hook 信任清理失败: \(details, privacy: .public)")
- operationErrorMessage = String(localized: "hook.error.trust-cleanup-failed")
+ AppLog.hooks.error("无法清理 Hook 信任状态: \(details, privacy: .public)")
+ operationErrorMessage = String(localized: "hook.error.trust-cleanup-unavailable")
} else {
operationErrorMessage = nil
}
@@ -582,8 +607,8 @@ private extension CodexHookSettings {
"stage=remove",
"detail=\(error.localizedDescription)"
)
- AppLog.hooks.error("Hook 信任清理失败: \(details, privacy: .public)")
- operationErrorMessage = String(localized: "hook.error.trust-cleanup-failed")
+ AppLog.hooks.error("无法清理 Hook 信任状态: \(details, privacy: .public)")
+ operationErrorMessage = String(localized: "hook.error.trust-cleanup-unavailable")
}
}
diff --git a/CodexBar/Services/Settings/TaskGlowSettings.swift b/CodexBar/Services/Settings/TaskGlowSettings.swift
new file mode 100644
index 0000000..e2479e7
--- /dev/null
+++ b/CodexBar/Services/Settings/TaskGlowSettings.swift
@@ -0,0 +1,28 @@
+import Combine
+import Foundation
+
+@MainActor
+final class TaskGlowSettings: ObservableObject {
+ @Published private(set) var isEnabled: Bool
+
+ private let defaults: UserDefaults
+ private static let enabledKey = "TaskGlow.isEnabled"
+
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ isEnabled = defaults.bool(forKey: Self.enabledKey)
+ }
+
+ func refresh() {
+ let enabled = defaults.bool(forKey: Self.enabledKey)
+ if enabled != isEnabled {
+ isEnabled = enabled
+ }
+ }
+
+ func setEnabled(_ enabled: Bool) {
+ guard enabled != isEnabled else { return }
+ defaults.set(enabled, forKey: Self.enabledKey)
+ isEnabled = enabled
+ }
+}
diff --git a/CodexBar/Services/Settings/WorkflowSyncSettings.swift b/CodexBar/Services/Settings/WorkflowSyncSettings.swift
index fcf9505..4f5681c 100644
--- a/CodexBar/Services/Settings/WorkflowSyncSettings.swift
+++ b/CodexBar/Services/Settings/WorkflowSyncSettings.swift
@@ -8,7 +8,6 @@ import os
final class WorkflowSyncSettings: ObservableObject {
@Published private(set) var isEnabled: Bool
@Published private(set) var isSyncing = false
- @Published private(set) var hasSyncFailure = false
@Published private(set) var syncFailureMessage: String?
@Published private(set) var lastUploadAt: Date?
@Published private(set) var syncAvailability = WorkflowSyncAvailability.unknown
@@ -57,6 +56,10 @@ final class WorkflowSyncSettings: ObservableObject {
syncAvailability.isAvailable
}
+ var hasSyncFailure: Bool {
+ syncFailureMessage != nil
+ }
+
/// "同步是否实际生效"的唯一判定: Hook 已启用且同步开关打开且 iCloud 可用
/// 按顺序返回第一个不满足的项, 日志的 reason= 直接取它的 rawValue
func activation(isHookEnabled: Bool) -> WorkflowSyncActivation {
@@ -169,12 +172,10 @@ final class WorkflowSyncSettings: ObservableObject {
}
private func clearSyncFailure() {
- hasSyncFailure = false
syncFailureMessage = nil
}
private func applySyncFailure(_ message: String?) {
- hasSyncFailure = isEnabled
syncFailureMessage = isEnabled
? message ?? WorkflowSyncFailureReason.retryLater.message
: nil
diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
index 36959c9..d030404 100644
--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift
+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
@@ -12,6 +12,10 @@ final class CodexActivityMonitor: ObservableObject {
transitionSubject.eraseToAnyPublisher()
}
+ var presentationPublisher: AnyPublisher<CodexActivityPresentationUpdate, Never> {
+ presentationSubject.eraseToAnyPublisher()
+ }
+
var onInactivityProtectionTriggered: ((CodexActivityProtectionNotice) async -> Bool)?
var onInactivityProtectionInvalidated: ((UUID, UUID) -> Void)?
@@ -20,14 +24,16 @@ final class CodexActivityMonitor: ObservableObject {
let activityProtectionStateStore: ActivityProtectionStateStore
private let sessionLifecycleReader = CodexSessionLifecycleReader()
let transitionSubject = PassthroughSubject<CodexActivityTransition, Never>()
+ private let presentationSubject = PassthroughSubject<CodexActivityPresentationUpdate, Never>()
+ var pendingTerminalPresentationEvents: [CodexActivityTerminalEvent] = []
+ var terminalPresentationNotBefore = Date()
var tasks: [CodexActivityTaskKey: CodexActivityTask] = [:]
var pendingTerminalTasks: [CodexActivityTaskKey: PendingTerminalTask] = [:]
var completions: [CodexActivityCompletion] = []
var terminations: [CodexActivityTermination] = []
- var recentlyCompletedTaskAt: [CodexActivityTaskKey: Date] = [:]
- var recentlyTerminatedTaskAt: [CodexActivityTaskKey: Date] = [:]
+ var recentlyEndedTaskAt: [CodexActivityTaskKey: Date] = [:]
var terminalTaskKeyByID: [UUID: CodexActivityTaskKey] = [:]
- var ignoredAutoReviewTaskAt: [CodexActivityTaskKey: Date] = [:]
+ var activityTaskOrigins: [CodexActivityTaskKey: (origin: WorkflowEventOrigin, observedAt: Date)] = [:]
var tailReader: HookEventTailReader?
private var tailReaderControlTask: Task<Void, Never>?
private var tailReaderGeneration: UInt64 = 0
@@ -334,15 +340,6 @@ final class CodexActivityMonitor: ObservableObject {
if let terminal = state.terminal {
tasks.removeValue(forKey: key)
- if case .completed = terminal, recentCompletionDate(for: key) != nil {
- // 迟到事件恢复出的任务不能被 rollout 再次完成
- clearActivityProtection(
- for: key,
- taskID: task.displayID,
- reason: .terminal
- )
- return true
- }
resolveTerminal(
terminal,
task: task,
@@ -416,6 +413,8 @@ final class CodexActivityMonitor: ObservableObject {
!isBootstrapping else {
return
}
+ let bootstrapGeneration = bootstrapCompletionGeneration
+ let recoveryGeneration = activityProtectionRecoveryGeneration
let references = tasks.values.compactMap(\.turnReference)
+ pendingTerminalTasks.values.compactMap(\.task.turnReference)
guard !references.isEmpty else {
@@ -424,6 +423,8 @@ final class CodexActivityMonitor: ObservableObject {
let states = await sessionLifecycleReader.lifecycleStates(for: references)
guard !Task.isCancelled,
generation == tailReaderGeneration,
+ bootstrapGeneration == bootstrapCompletionGeneration,
+ recoveryGeneration == activityProtectionRecoveryGeneration,
tailReader != nil,
!isBootstrapping,
!states.isEmpty else {
@@ -479,38 +480,41 @@ final class CodexActivityMonitor: ObservableObject {
case let .live(events):
let pendingKeysBefore = Set(pendingTerminalTasks.keys)
let activeCountBefore = snapshot.activeCount
- var transitions: [CodexActivityLiveTransition] = []
+ var waitingTaskKeys: [CodexActivityTaskKey] = []
for event in events {
- if let transition = apply(event, source: .live) {
- transitions.append(transition)
+ if let key = apply(event, source: .live) {
+ waitingTaskKeys.append(key)
}
}
refreshSnapshot(now: Date())
- // 活跃数变化覆盖任务起止, transitions 覆盖等待批准
+ // 活跃数变化覆盖任务起止, waitingTaskKeys 覆盖等待批准
// 只看活跃数会漏掉 running 转 waitingApproval, 那一进一出恒抵消为零
let activeCountAfter = snapshot.activeCount
- if activeCountAfter != activeCountBefore || !transitions.isEmpty {
+ if activeCountAfter != activeCountBefore || !waitingTaskKeys.isEmpty {
let details = LogFields.joined(
"from=\(activeCountBefore)",
"to=\(activeCountAfter)",
- "transitions=\(transitions.count)"
+ "transitions=\(waitingTaskKeys.count)"
)
AppLog.activity.notice("任务数变化: \(details, privacy: .public)")
}
- publishLiveTransitions(transitions)
+ publishWaitingApprovalTransitions(waitingTaskKeys)
if !pendingTerminalTasks.isEmpty {
// 只有刚进入终态确认窗口的任务需要重置解析缓存重试定位 rollout
// 窗口期内的后续批次只做即时查询, 避免反复递归扫描 sessions
let hasNewPendingTasks = !Set(pendingTerminalTasks.keys)
.subtracting(pendingKeysBefore).isEmpty
refreshSessionLifecycleNow(resetsResolutionFallbacks: hasNewPendingTasks)
+ } else if events.contains(where: { $0.hookEvent == .stop }) {
+ refreshSessionLifecycleNow()
}
case let .sourceHealthChanged(isHealthy):
guard isHealthy != isActivitySourceHealthy else {
return
}
isActivitySourceHealthy = isHealthy
+ resetTerminalPresentationEvents()
if isHealthy {
reconcileActivityProtection(now: Date(), sendsNotification: false)
} else {
@@ -548,6 +552,7 @@ final class CodexActivityMonitor: ObservableObject {
tailReader != nil else {
return
}
+ resetTerminalPresentationEvents()
isBootstrapping = false
let now = Date()
applyPersistedActivityProtection(now: now)
@@ -620,7 +625,7 @@ final class CodexActivityMonitor: ObservableObject {
private func apply(
_ event: WorkflowHookEvent,
source: CodexActivityEventSource
- ) -> CodexActivityLiveTransition? {
+ ) -> CodexActivityTaskKey? {
guard !shouldIgnoreForActivity(event, source: source) else {
return nil
}
@@ -668,7 +673,12 @@ final class CodexActivityMonitor: ObservableObject {
guard isTopLevelEvent else {
return nil
}
- return completeTask(from: event)
+ observeStop(from: event, source: source)
+ case .interrupt:
+ guard isTopLevelEvent else {
+ return nil
+ }
+ interruptTask(from: event, source: source)
case .sessionEnd:
terminateSession(from: event)
case .sessionStart, .none:
@@ -686,13 +696,13 @@ final class CodexActivityMonitor: ObservableObject {
let key = CodexActivityTaskKey(event: event)
let existingTask = tasks[key]
let displayID = existingTask?.displayID ?? UUID()
- if let completedAt = recentCompletionDate(for: key),
- event.timestamp <= completedAt {
- return
- }
- if let terminatedAt = recentTerminationDate(for: key),
- event.timestamp <= terminatedAt {
- return
+ if let endedAt = recentEndedDate(for: key) {
+ if case .turn = key {
+ return
+ }
+ if event.timestamp <= endedAt {
+ return
+ }
}
if let existing = tasks[key], event.timestamp < existing.lastActivityAt {
return
@@ -731,12 +741,10 @@ final class CodexActivityMonitor: ObservableObject {
)
}
- recentlyCompletedTaskAt.removeValue(forKey: key)
- recentlyTerminatedTaskAt.removeValue(forKey: key)
+ recentlyEndedTaskAt.removeValue(forKey: key)
if let sessionId = key.sessionId {
- // 缺少 turn 的 Stop 会使用 session 键; 新 turn 开始后允许该键再次完成
- recentlyCompletedTaskAt.removeValue(forKey: .session(sessionId))
- recentlyTerminatedTaskAt.removeValue(forKey: .session(sessionId))
+ // 缺少 turn 的事件复用 session 键; 新 turn 开始后清除上一轮的终态记忆
+ recentlyEndedTaskAt.removeValue(forKey: .session(sessionId))
}
tasks[key] = CodexActivityTask(
@@ -762,8 +770,7 @@ final class CodexActivityMonitor: ObservableObject {
: matchingSubagentParentTaskKey(for: event)
if let key = matchedKey, var task = tasks[key] {
- guard recentCompletionDate(for: key) == nil,
- recentTerminationDate(for: key) == nil,
+ guard recentEndedDate(for: key) == nil,
pendingTerminalTasks[key] == nil else {
return
}
@@ -792,8 +799,7 @@ final class CodexActivityMonitor: ObservableObject {
}
guard allowsRecovery,
- recentCompletionDate(for: eventKey) == nil,
- recentTerminationDate(for: eventKey) == nil,
+ recentEndedDate(for: eventKey) == nil,
pendingTerminalTasks[eventKey] == nil else {
return
}
@@ -823,8 +829,7 @@ final class CodexActivityMonitor: ObservableObject {
source: CodexActivityEventSource
) {
guard let key = matchingSubagentParentTaskKey(for: event),
- recentCompletionDate(for: key) == nil,
- recentTerminationDate(for: key) == nil,
+ recentEndedDate(for: key) == nil,
pendingTerminalTasks[key] == nil,
var task = tasks[key] else {
return
@@ -865,15 +870,14 @@ final class CodexActivityMonitor: ObservableObject {
private func waitForApproval(
from event: WorkflowHookEvent,
source: CodexActivityEventSource
- ) -> CodexActivityLiveTransition? {
+ ) -> CodexActivityTaskKey? {
let eventKey = CodexActivityTaskKey(event: event)
let matchedKey = event.agentId == nil
? matchingActiveTaskKey(for: event)
: matchingSubagentParentTaskKey(for: event)
if let key = matchedKey, var task = tasks[key] {
- guard recentCompletionDate(for: key) == nil,
- recentTerminationDate(for: key) == nil,
+ guard recentEndedDate(for: key) == nil,
pendingTerminalTasks[key] == nil else {
return nil
}
@@ -895,12 +899,11 @@ final class CodexActivityMonitor: ObservableObject {
reason: .progress
)
}
- return enteredWaiting ? .waitingApproval(key) : nil
+ return enteredWaiting ? key : nil
}
guard event.agentId == nil,
- recentCompletionDate(for: eventKey) == nil,
- recentTerminationDate(for: eventKey) == nil,
+ recentEndedDate(for: eventKey) == nil,
pendingTerminalTasks[eventKey] == nil else {
return nil
}
@@ -923,95 +926,41 @@ final class CodexActivityMonitor: ObservableObject {
reason: .progress
)
}
- return enteredWaiting ? .waitingApproval(eventKey) : nil
+ return enteredWaiting ? eventKey : nil
}
- private func completeTask(from event: WorkflowHookEvent) -> CodexActivityLiveTransition? {
+ /// Stop handler 仍可要求同一 turn 继续执行, 完成只由 rollout terminal 确认
+ private func observeStop(from event: WorkflowHookEvent, source: CodexActivityEventSource) {
let eventKey = CodexActivityTaskKey(event: event)
- guard recentCompletionDate(for: eventKey) == nil else {
- // 清掉旧版本或异常顺序留下的同键恢复任务
+ guard recentEndedDate(for: eventKey) == nil else {
discardStaleTerminalTask(for: eventKey)
- return nil
- }
- guard recentTerminationDate(for: eventKey) == nil else {
- discardStaleTerminalTask(for: eventKey)
- return nil
- }
-
- let match = matchingTerminalTask(for: event)
- if case .ambiguous = match {
- AppLog.activity.error(
- "任务终态已延后: reason=ambiguousStop"
- )
- return nil
- }
-
- if case let .pending(key) = match,
- let pending = pendingTerminalTasks[key] {
- guard event.timestamp >= pending.task.lastActivityAt else {
- return nil
- }
- pendingTerminalTasks.removeValue(forKey: key)
- clearActivityProtection(
- for: key,
- taskID: pending.task.displayID,
- reason: .terminal
- )
- let completion = storeResolvedCompletion(
- pending.task,
- key: key,
- completedAt: event.timestamp,
- reportedDuration: nil,
- projectName: event.projectDisplayName,
- modelName: event.modelName,
- effort: event.effort
- )
- recordCompletedTask(eventKey, at: event.timestamp)
- return .completed(completion)
- }
-
- let matchedKey: CodexActivityTaskKey? = switch match {
- case let .active(key): key
- default: nil
- }
- let task = matchedKey.flatMap { tasks[$0] }
- if let task, event.timestamp < task.lastActivityAt {
- return nil
+ return
}
- let key = matchedKey ?? eventKey
- guard recentCompletionDate(for: key) == nil else {
- if let matchedKey {
- tasks.removeValue(forKey: matchedKey)
+ let match = matchingTerminalTask(for: event, allowsAnonymousFallback: event.sessionId == nil)
+ switch match {
+ case .ambiguous:
+ AppLog.activity.error("任务终态已延后: reason=ambiguousStop")
+ case let .pending(key):
+ guard var pending = pendingTerminalTasks[key],
+ event.timestamp >= pending.task.lastActivityAt else {
+ return
}
- return nil
- }
-
- if let matchedKey {
- tasks.removeValue(forKey: matchedKey)
- clearActivityProtection(
- for: matchedKey,
- taskID: task?.displayID,
- reason: .terminal
+ // 新 turn 或 SessionEnd 已确定旧任务退出活动列表, Stop 不恢复它或重置 grace
+ pending.task.mergeMetadata(from: event)
+ pending.task.recordProgress(at: event.timestamp)
+ pendingTerminalTasks[key] = pending
+ case .active, .none:
+ resumeTask(
+ from: event,
+ latestEvent: .stopRequested,
+ allowsRecovery: true,
+ source: source
)
}
-
- let duration = task?.preciseDuration(until: event.timestamp)
-
- let completion = storeCompletion(
- for: key,
- projectName: event.projectDisplayName ?? task?.projectName,
- modelName: event.modelName ?? task?.modelName,
- effort: event.effort ?? task?.effort,
- completedAt: event.timestamp,
- duration: duration
- )
- recordCompletedTask(eventKey, at: event.timestamp)
- recordCompletedTask(key, at: event.timestamp)
- return .completed(completion)
}
- private func discardStaleTerminalTask(for key: CodexActivityTaskKey) {
+ func discardStaleTerminalTask(for key: CodexActivityTaskKey) {
if let task = tasks.removeValue(forKey: key) {
clearActivityProtection(
for: key,
@@ -1108,8 +1057,9 @@ final class CodexActivityMonitor: ObservableObject {
return candidates[0].key
}
- private func matchingTerminalTask(
- for event: WorkflowHookEvent
+ func matchingTerminalTask(
+ for event: WorkflowHookEvent,
+ allowsAnonymousFallback: Bool = true
) -> CodexTerminalTaskMatch {
let exactKey = CodexActivityTaskKey(event: event)
if pendingTerminalTasks[exactKey] != nil {
@@ -1146,6 +1096,9 @@ final class CodexActivityMonitor: ObservableObject {
}
}
+ guard allowsAnonymousFallback else {
+ return .none
+ }
let anonymousKey = CodexActivityTaskKey.anonymous(
project: CodexActivityTaskKey.projectIdentifier(event.projectDisplayName)
)
@@ -1174,9 +1127,15 @@ final class CodexActivityMonitor: ObservableObject {
recentCompletions: recentCompletions,
recentTerminations: recentTerminations
)
- if newSnapshot != snapshot {
+ let events = pendingTerminalPresentationEvents.filter { terminalTaskKeyByID[$0.id] != nil }
+ pendingTerminalPresentationEvents.removeAll()
+ let didChange = newSnapshot != snapshot
+ if didChange {
snapshot = newSnapshot
}
+ if didChange || !events.isEmpty {
+ presentationSubject.send(CodexActivityPresentationUpdate(snapshot: newSnapshot, terminalEvents: events))
+ }
scheduleNextCleanup(now: now)
scheduleNextInactivityCheck(now: now)
@@ -1225,15 +1184,12 @@ final class CodexActivityMonitor: ObservableObject {
retainedTerminalIDs.contains($0.key)
}
- let completedTaskCutoff = now.addingTimeInterval(-Self.completedTaskRetention)
- recentlyCompletedTaskAt = recentlyCompletedTaskAt.filter {
- $0.value > completedTaskCutoff
- }
- recentlyTerminatedTaskAt = recentlyTerminatedTaskAt.filter {
- $0.value > completedTaskCutoff
+ let endedTaskCutoff = now.addingTimeInterval(-Self.endedTaskRetention)
+ recentlyEndedTaskAt = recentlyEndedTaskAt.filter {
+ $0.value > endedTaskCutoff
}
- ignoredAutoReviewTaskAt = ignoredAutoReviewTaskAt.filter {
- $0.value > activityCutoff
+ activityTaskOrigins = activityTaskOrigins.filter {
+ $0.value.observedAt > activityCutoff
}
}
@@ -1248,14 +1204,11 @@ final class CodexActivityMonitor: ObservableObject {
$0.terminatedAt.addingTimeInterval(Self.recentHistoryRetention)
})
deadlines.append(contentsOf: pendingTerminalTasks.values.map(\.deadline))
- deadlines.append(contentsOf: recentlyCompletedTaskAt.values.map {
- $0.addingTimeInterval(Self.completedTaskRetention)
- })
- deadlines.append(contentsOf: recentlyTerminatedTaskAt.values.map {
- $0.addingTimeInterval(Self.completedTaskRetention)
+ deadlines.append(contentsOf: recentlyEndedTaskAt.values.map {
+ $0.addingTimeInterval(Self.endedTaskRetention)
})
- deadlines.append(contentsOf: ignoredAutoReviewTaskAt.values.map {
- $0.addingTimeInterval(Self.activityRetention)
+ deadlines.append(contentsOf: activityTaskOrigins.values.map {
+ $0.observedAt.addingTimeInterval(Self.activityRetention)
})
deadlines.append(contentsOf: activityProtectionRecords.values.map(\.expiresAt))
@@ -1283,7 +1236,7 @@ final class CodexActivityMonitor: ObservableObject {
}
private static let recentHistoryRetention: TimeInterval = 10 * 60
- static let completedTaskRetention: TimeInterval = 24 * 60 * 60
+ static let endedTaskRetention: TimeInterval = 24 * 60 * 60
static let activityRetention = CodexActivityRetention.window
static let activityProtectionNotificationSubmissionGrace: Duration = .seconds(3)
private static let supersededTerminalGracePeriod: TimeInterval = 5
diff --git a/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift b/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift
index 675519f..381595e 100644
--- a/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift
+++ b/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift
@@ -2,7 +2,7 @@ import Foundation
import os
extension CodexActivityMonitor {
- /// Auto-review 事件只影响实时活动链路, 原始事件仍由历史聚合完整消费
+ /// 来源过滤只影响实时活动链路, 原始事件仍由历史聚合完整消费
func shouldIgnoreForActivity(
_ event: WorkflowHookEvent,
source: CodexActivityEventSource
@@ -14,37 +14,47 @@ extension CodexActivityMonitor {
return true
}
- let now = Date()
- let observedAt = min(event.timestamp, now)
- let wasAlreadyIgnored = ignoredAutoReviewTaskAt[exactKey] != nil
- ignoredAutoReviewTaskAt[exactKey] = max(
- ignoredAutoReviewTaskAt[exactKey] ?? .distantPast,
- observedAt
- )
- discardAutoReviewActivity(for: exactKey)
+ let wasAlreadyIgnored = activityTaskOrigins[exactKey]?.origin == .autoReview
+ rememberActivityOrigin(event.origin, for: exactKey, at: event.timestamp)
+ discardExcludedActivity(for: exactKey)
if !wasAlreadyIgnored, source == .live {
AppLog.activity.notice("Auto-review 任务已过滤")
}
return true
case .main, .auxiliary:
if let exactKey {
- ignoredAutoReviewTaskAt.removeValue(forKey: exactKey)
+ rememberActivityOrigin(event.origin, for: exactKey, at: event.timestamp)
}
return false
case .unknown:
guard let exactKey,
- let ignoredAt = ignoredAutoReviewTaskAt[exactKey] else {
- return false
+ let knownOrigin = activityTaskOrigins[exactKey] else {
+ return true
}
- let cutoff = Date().addingTimeInterval(-Self.activityRetention)
- guard ignoredAt > cutoff else {
- ignoredAutoReviewTaskAt.removeValue(forKey: exactKey)
- return false
+ guard knownOrigin.observedAt > Date().addingTimeInterval(-Self.activityRetention) else {
+ activityTaskOrigins.removeValue(forKey: exactKey)
+ return true
}
- return true
+ guard knownOrigin.origin == .main || knownOrigin.origin == .auxiliary else {
+ return true
+ }
+ // 一次读取失败不推翻已确认来源, 迟到事件仍交给状态机检查时间顺序
+ rememberActivityOrigin(knownOrigin.origin, for: exactKey, at: event.timestamp)
+ return false
}
}
+ private func rememberActivityOrigin(
+ _ origin: WorkflowEventOrigin,
+ for key: CodexActivityTaskKey,
+ at timestamp: Date
+ ) {
+ activityTaskOrigins[key] = (
+ origin: origin,
+ observedAt: max(activityTaskOrigins[key]?.observedAt ?? .distantPast, min(timestamp, Date()))
+ )
+ }
+
private static func exactTurnKey(for event: WorkflowHookEvent) -> CodexActivityTaskKey? {
guard let sessionId = event.sessionId,
let turnId = event.turnId else {
@@ -53,7 +63,7 @@ extension CodexActivityMonitor {
return .turn(session: sessionId, turn: turnId)
}
- private func discardAutoReviewActivity(for key: CodexActivityTaskKey) {
+ private func discardExcludedActivity(for key: CodexActivityTaskKey) {
var taskIDs = Set<UUID>()
if let task = tasks.removeValue(forKey: key) {
taskIDs.insert(task.displayID)
@@ -74,24 +84,20 @@ extension CodexActivityMonitor {
terminations.removeAll { terminalTaskKeyByID[$0.id] == key }
terminalTaskKeyByID = terminalTaskKeyByID.filter { $0.value != key }
- Self.removeTerminalMemory(for: key, storedIn: &recentlyCompletedTaskAt)
- Self.removeTerminalMemory(for: key, storedIn: &recentlyTerminatedTaskAt)
+ removeTerminalMemory(for: key)
}
- private static func removeTerminalMemory(
- for key: CodexActivityTaskKey,
- storedIn dates: inout [CodexActivityTaskKey: Date]
- ) {
- guard let removedAt = dates.removeValue(forKey: key),
+ private func removeTerminalMemory(for key: CodexActivityTaskKey) {
+ guard let removedAt = recentlyEndedTaskAt.removeValue(forKey: key),
let sessionId = key.sessionId else {
return
}
let sessionKey = CodexActivityTaskKey.session(sessionId)
- guard dates[sessionKey] == removedAt else {
+ guard recentlyEndedTaskAt[sessionKey] == removedAt else {
return
}
- let remainingSessionDate = dates.compactMap { candidateKey, date -> Date? in
+ let remainingSessionDate = recentlyEndedTaskAt.compactMap { candidateKey, date -> Date? in
guard candidateKey != sessionKey,
candidateKey.sessionId == sessionId else {
return nil
@@ -99,9 +105,9 @@ extension CodexActivityMonitor {
return date
}.max()
if let remainingSessionDate {
- dates[sessionKey] = remainingSessionDate
+ recentlyEndedTaskAt[sessionKey] = remainingSessionDate
} else {
- dates.removeValue(forKey: sessionKey)
+ recentlyEndedTaskAt.removeValue(forKey: sessionKey)
}
}
}
diff --git a/CodexBar/Services/Workflow/CodexActivityProtection.swift b/CodexBar/Services/Workflow/CodexActivityProtection.swift
index 6b50d6b..df928a6 100644
--- a/CodexBar/Services/Workflow/CodexActivityProtection.swift
+++ b/CodexBar/Services/Workflow/CodexActivityProtection.swift
@@ -43,6 +43,7 @@ extension CodexActivityMonitor {
func beginActivityProtectionRecovery() -> UInt64 {
activityProtectionRecoveryGeneration &+= 1
isActivityProtectionRecoveryInProgress = true
+ resetTerminalPresentationEvents()
cancelInactivityCheck()
cancelAllActivityProtectionAttempts()
return activityProtectionRecoveryGeneration
@@ -52,6 +53,7 @@ extension CodexActivityMonitor {
guard generation == activityProtectionRecoveryGeneration else {
return
}
+ resetTerminalPresentationEvents()
isActivityProtectionRecoveryInProgress = false
reconcileActivityProtection(now: Date(), sendsNotification: false)
}
diff --git a/CodexBar/Services/Workflow/CodexActivityTask.swift b/CodexBar/Services/Workflow/CodexActivityTask.swift
index 906863b..5606c7b 100644
--- a/CodexBar/Services/Workflow/CodexActivityTask.swift
+++ b/CodexBar/Services/Workflow/CodexActivityTask.swift
@@ -58,11 +58,6 @@ enum CodexActivityTaskKey: Hashable {
}
}
-enum CodexActivityLiveTransition {
- case waitingApproval(CodexActivityTaskKey)
- case completed(CodexActivityCompletion)
-}
-
enum CodexActivityEventSource {
case bootstrap
case live
diff --git a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift b/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift
index af4ba3f..8379723 100644
--- a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift
+++ b/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift
@@ -1,7 +1,59 @@
import Combine
import Foundation
+import os
extension CodexActivityMonitor {
+ /// Interrupt 只结束匹配的 turn, 不清空同 session 的新任务
+ func interruptTask(from event: WorkflowHookEvent, source: CodexActivityEventSource) {
+ let eventKey = CodexActivityTaskKey(event: event)
+ if recentEndedDate(for: eventKey) != nil {
+ discardStaleTerminalTask(for: eventKey)
+ return
+ }
+
+ let match = matchingTerminalTask(for: event, allowsAnonymousFallback: event.sessionId == nil)
+ let key: CodexActivityTaskKey
+ let task: CodexActivityTask?
+ switch match {
+ case let .active(matchedKey):
+ key = matchedKey
+ task = tasks[key]
+ case let .pending(matchedKey):
+ key = matchedKey
+ task = pendingTerminalTasks[key]?.task
+ case .ambiguous:
+ AppLog.activity.error("任务中断未关联: reason=ambiguousInterrupt")
+ return
+ case .none:
+ key = eventKey
+ task = nil
+ }
+ guard task.map({ event.timestamp >= $0.lastActivityAt }) ?? true else {
+ return
+ }
+ if recentEndedDate(for: key) != nil {
+ discardStaleTerminalTask(for: key)
+ return
+ }
+
+ tasks.removeValue(forKey: key)
+ pendingTerminalTasks.removeValue(forKey: key)
+ clearActivityProtection(for: key, taskID: task?.displayID, reason: .terminal)
+ storeTermination(
+ for: key,
+ projectName: event.projectDisplayName ?? task?.projectName,
+ modelName: event.modelName ?? task?.modelName,
+ effort: event.effort ?? task?.effort,
+ terminatedAt: event.timestamp,
+ duration: task?.preciseDuration(until: event.timestamp)
+ )
+ recordEndedTask(key, at: event.timestamp)
+ recordEndedTask(eventKey, at: event.timestamp)
+ if source == .live {
+ AppLog.activity.notice("任务已终止: source=interruptHook")
+ }
+ }
+
// MARK: - 终态判定与记录
/// PermissionRequest 表示进入审批流程; 只有 rollout 明确把审批路由给 user 时才是 UI 等待
@@ -31,7 +83,7 @@ extension CodexActivityMonitor {
}
/// rollout 终态归类的唯一入口; 活动任务和等待终态确认任务只有 abort 兜底时间不同
- /// 终止记录只供任务中心展示, 不发布 transition, 也不产生绿色状态或通知
+ /// 终止记录供任务中心和流光展示, 不发布通知 transition
func resolveTerminal(
_ terminal: CodexSessionTaskTerminalState,
task: CodexActivityTask,
@@ -44,11 +96,14 @@ extension CodexActivityMonitor {
taskID: task.displayID,
reason: .terminal
)
+ guard recentEndedDate(for: key) == nil else {
+ return
+ }
switch terminal {
case let .aborted(reportedAt):
let terminatedAt = max(reportedAt ?? abortFallback, task.lastActivityAt)
storeTermination(task, at: terminatedAt, includesDuration: reportedAt != nil)
- recordTerminatedTask(key, at: terminatedAt)
+ recordEndedTask(key, at: terminatedAt)
case let .completed(completedAt, duration):
let completion = storeResolvedCompletion(
task,
@@ -91,48 +146,27 @@ extension CodexActivityMonitor {
return didChange
}
- func storeResolvedCompletion(
+ private func storeResolvedCompletion(
_ task: CodexActivityTask,
key: CodexActivityTaskKey,
completedAt: Date,
- reportedDuration: TimeInterval?,
- projectName: String? = nil,
- modelName: String? = nil,
- effort: String? = nil
+ reportedDuration: TimeInterval?
) -> CodexActivityCompletion {
// rollout 时间戳是整秒, 避免因为同一秒内的 Hook 毫秒时间戳而把完成时间记在最后活动之前
let recordedCompletedAt = max(completedAt, task.lastActivityAt)
- let completion = storeCompletion(
- for: key,
- projectName: projectName ?? task.projectName,
- modelName: modelName ?? task.modelName,
- effort: effort ?? task.effort,
- completedAt: recordedCompletedAt,
- duration: reportedDuration ?? task.preciseDuration(until: recordedCompletedAt)
- )
- recordCompletedTask(key, at: recordedCompletedAt)
- return completion
- }
-
- func storeCompletion(
- for key: CodexActivityTaskKey,
- projectName: String?,
- modelName: String?,
- effort: String?,
- completedAt: Date,
- duration: TimeInterval?
- ) -> CodexActivityCompletion {
let completion = CodexActivityCompletion(
id: UUID(),
isAnonymous: key.isAnonymous,
- projectName: projectName,
- modelName: modelName,
- effort: effort,
- completedAt: completedAt,
- duration: duration
+ projectName: task.projectName,
+ modelName: task.modelName,
+ effort: task.effort,
+ completedAt: recordedCompletedAt,
+ duration: reportedDuration ?? task.preciseDuration(until: recordedCompletedAt)
)
completions.append(completion)
terminalTaskKeyByID[completion.id] = key
+ recordTerminalPresentationEvent(.completed(completion))
+ recordEndedTask(key, at: recordedCompletedAt)
return completion
}
@@ -141,58 +175,76 @@ extension CodexActivityMonitor {
at terminatedAt: Date,
includesDuration: Bool
) {
- let termination = CodexActivityTermination(
- id: UUID(),
- isAnonymous: task.key.isAnonymous,
+ storeTermination(
+ for: task.key,
projectName: task.projectName,
modelName: task.modelName,
effort: task.effort,
terminatedAt: terminatedAt,
duration: includesDuration ? task.preciseDuration(until: terminatedAt) : nil
)
- terminations.append(termination)
- terminalTaskKeyByID[termination.id] = task.key
}
- func recentCompletionDate(
+ private func storeTermination(
for key: CodexActivityTaskKey,
- now: Date = Date()
- ) -> Date? {
- Self.recentTerminalDate(
- for: key,
- storedIn: &recentlyCompletedTaskAt,
- now: now
+ projectName: String?,
+ modelName: String?,
+ effort: String?,
+ terminatedAt: Date,
+ duration: TimeInterval?
+ ) {
+ let termination = CodexActivityTermination(
+ id: UUID(),
+ isAnonymous: key.isAnonymous,
+ projectName: projectName,
+ modelName: modelName,
+ effort: effort,
+ terminatedAt: terminatedAt,
+ duration: duration
)
+ terminations.append(termination)
+ terminalTaskKeyByID[termination.id] = key
+ recordTerminalPresentationEvent(.terminated(termination))
+ }
+
+ func recordTerminalPresentationEvent(_ event: CodexActivityTerminalEvent) {
+ guard !isBootstrapping, !isActivityProtectionRecoveryInProgress, isActivitySourceHealthy,
+ event.endedAt >= terminalPresentationNotBefore else {
+ return
+ }
+ pendingTerminalPresentationEvents.append(event)
}
- func recentTerminationDate(
+ func resetTerminalPresentationEvents() {
+ pendingTerminalPresentationEvents.removeAll()
+ // 延迟确认仍使用原始结束时间, 恢复前的旧终态不能在恢复后补播
+ terminalPresentationNotBefore = Date()
+ }
+
+ func recentEndedDate(
for key: CodexActivityTaskKey,
now: Date = Date()
) -> Date? {
- Self.recentTerminalDate(
- for: key,
- storedIn: &recentlyTerminatedTaskAt,
- now: now
- )
- }
-
- func recordCompletedTask(_ key: CodexActivityTaskKey, at completedAt: Date) {
- Self.recordTerminalTask(
- key,
- at: completedAt,
- storedIn: &recentlyCompletedTaskAt
- )
+ guard let date = recentlyEndedTaskAt[key] else {
+ return nil
+ }
+ guard date > now.addingTimeInterval(-Self.endedTaskRetention) else {
+ recentlyEndedTaskAt.removeValue(forKey: key)
+ return nil
+ }
+ return date
}
- func recordTerminatedTask(_ key: CodexActivityTaskKey, at terminatedAt: Date) {
- Self.recordTerminalTask(
- key,
- at: terminatedAt,
- storedIn: &recentlyTerminatedTaskAt
- )
+ func recordEndedTask(_ key: CodexActivityTaskKey, at date: Date) {
+ recentlyEndedTaskAt[key] = max(recentlyEndedTaskAt[key] ?? .distantPast, date)
+ if let sessionId = key.sessionId {
+ let sessionKey = CodexActivityTaskKey.session(sessionId)
+ recentlyEndedTaskAt[sessionKey] = max(recentlyEndedTaskAt[sessionKey] ?? .distantPast, date)
+ }
}
func clearCollectedActivityState() {
+ resetTerminalPresentationEvents()
cancelAllActivityProtectionAttempts()
let taskIDs = Set(tasks.values.map(\.displayID))
.union(pendingTerminalTasks.values.map(\.task.displayID))
@@ -203,37 +255,9 @@ extension CodexActivityMonitor {
pendingTerminalTasks.removeAll()
completions.removeAll()
terminations.removeAll()
- recentlyCompletedTaskAt.removeAll()
- recentlyTerminatedTaskAt.removeAll()
+ recentlyEndedTaskAt.removeAll()
terminalTaskKeyByID.removeAll()
- ignoredAutoReviewTaskAt.removeAll()
- }
-
- static func recentTerminalDate(
- for key: CodexActivityTaskKey,
- storedIn dates: inout [CodexActivityTaskKey: Date],
- now: Date
- ) -> Date? {
- guard let date = dates[key] else {
- return nil
- }
- guard date > now.addingTimeInterval(-completedTaskRetention) else {
- dates.removeValue(forKey: key)
- return nil
- }
- return date
- }
-
- static func recordTerminalTask(
- _ key: CodexActivityTaskKey,
- at date: Date,
- storedIn dates: inout [CodexActivityTaskKey: Date]
- ) {
- dates[key] = max(dates[key] ?? .distantPast, date)
- if let sessionId = key.sessionId {
- let sessionKey = CodexActivityTaskKey.session(sessionId)
- dates[sessionKey] = max(dates[sessionKey] ?? .distantPast, date)
- }
+ activityTaskOrigins.removeAll()
}
func finalizeExpiredPendingTerminalTasks(now: Date) {
@@ -248,7 +272,7 @@ extension CodexActivityMonitor {
if pending.task.state != .suppressed {
storeTermination(pending.task, at: terminatedAt, includesDuration: true)
}
- recordTerminatedTask(key, at: terminatedAt)
+ recordEndedTask(key, at: terminatedAt)
clearActivityProtection(
for: key,
taskID: pending.task.displayID,
@@ -257,33 +281,20 @@ extension CodexActivityMonitor {
}
}
- func publishLiveTransitions(_ transitions: [CodexActivityLiveTransition]) {
+ func publishWaitingApprovalTransitions(_ taskKeys: [CodexActivityTaskKey]) {
var lastWaitingIndexByKey: [CodexActivityTaskKey: Int] = [:]
- for (index, transition) in transitions.enumerated() {
- if case let .waitingApproval(key) = transition {
- lastWaitingIndexByKey[key] = index
- }
+ for (index, key) in taskKeys.enumerated() {
+ lastWaitingIndexByKey[key] = index
}
- var publishedCompletionIDs = Set<UUID>()
- for (index, transition) in transitions.enumerated() {
- switch transition {
- case let .waitingApproval(key):
- guard !key.isAnonymous,
- lastWaitingIndexByKey[key] == index,
- let task = tasks[key],
- task.state == .waitingApproval else {
- continue
- }
- transitionSubject.send(.waitingApproval(task.snapshot))
- case let .completed(completion):
- guard !completion.isAnonymous,
- terminalTaskKeyByID[completion.id] != nil,
- publishedCompletionIDs.insert(completion.id).inserted else {
- continue
- }
- transitionSubject.send(.completed(completion))
+ for (index, key) in taskKeys.enumerated() {
+ guard !key.isAnonymous,
+ lastWaitingIndexByKey[key] == index,
+ let task = tasks[key],
+ task.state == .waitingApproval else {
+ continue
}
+ transitionSubject.send(.waitingApproval(task.snapshot))
}
}
}
diff --git a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
index e4dc56e..cfd1408 100644
--- a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
+++ b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
@@ -5,13 +5,16 @@ import Foundation
nonisolated enum WorkflowHookEventRecorder {
static let hookArgument = "--hook-event"
- /// SessionEnd 在 Codex 中最多允许 3 秒, 其他事件沿用 5 秒
+ /// SessionEnd 和 Interrupt 在 Codex 中最多允许 3 秒, 其他事件沿用 5 秒
/// 超时定义在这里而不是 CodexHookSettings: 写配置与下面的等锁预算必须同源
private static let defaultHookTimeoutSeconds = 5
- private static let sessionEndHookTimeoutSeconds = 3
+ private static let terminalHookTimeoutSeconds = 3
static func hookTimeoutSeconds(for event: CodexHookEvent) -> Int {
- event == .sessionEnd ? sessionEndHookTimeoutSeconds : defaultHookTimeoutSeconds
+ switch event {
+ case .sessionEnd, .interrupt: terminalHookTimeoutSeconds
+ default: defaultHookTimeoutSeconds
+ }
}
static func handleIfRequested() -> Bool {
diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swift
index 67bfc4a..1ca4d9c 100644
--- a/CodexBar/Services/Workflow/WorkflowService.swift
+++ b/CodexBar/Services/Workflow/WorkflowService.swift
@@ -200,7 +200,7 @@ actor WorkflowService {
var aggregates = loadDailyAggregates() ?? []
let hookCountAvailability = aggregates
.first(where: { $0.date == dateKey })?
- .hookCountAvailability ?? .all
+ .hookCountAvailability ?? .legacy
let task = try prepareRebuildTask(
for: dateKey,
hookCountAvailability: hookCountAvailability
@@ -508,7 +508,7 @@ actor WorkflowService {
for: dateKey,
day: day,
hookCountAvailability: dailyByDate[dateKey]?
- .hookCountAvailability ?? .all
+ .hookCountAvailability ?? .legacy
)
}
@@ -531,7 +531,7 @@ actor WorkflowService {
day: day,
size: size,
hookCountAvailability: existingAggregate?
- .hookCountAvailability ?? .all
+ .hookCountAvailability ?? .legacy
))
continue
}
@@ -568,7 +568,7 @@ actor WorkflowService {
for dateKey: String,
day: WorkflowDayMaintenanceState,
size: UInt64? = nil,
- hookCountAvailability: WorkflowHookCountAvailability = .all
+ hookCountAvailability: WorkflowHookCountAvailability = .legacy
) -> WorkflowMaintenanceTask {
let stat = WorkflowStorage.fileStat(at: eventLogURL(for: dateKey))
return WorkflowMaintenanceTask(
@@ -1239,7 +1239,7 @@ nonisolated struct WorkflowDayMaintenanceState: Codable, Equatable {
/// maintenance.json 的全局状态, pending 表示可增量, dirty 表示需全量重建
nonisolated struct WorkflowMaintenanceState: Codable, Equatable {
/// 原始事件到每日聚合的算法版本, 变化时统一从原始 JSONL 重建
- static let currentAggregationSchema = 6
+ static let currentAggregationSchema = 9
var schema: Int
var pending: [String]
diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swift
index 03597a7..e186953 100644
--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift
+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift
@@ -313,7 +313,7 @@ private extension WorkflowSyncService {
}
enum Metrics {
- static let syncSchemaVersion = 5
+ static let syncSchemaVersion = 6
static let syncZoneName = "CodexBarZone"
static let saltByteCount = 32
static let recordFetchLimit = 200
@@ -338,6 +338,7 @@ private extension WorkflowSyncService {
static let sessionEndCount = "sessionEndCount"
static let userPromptSubmitCount = "userPromptSubmitCount"
static let stopCount = "stopCount"
+ static let interruptCount = "interruptCount"
static let preToolUseCount = "preToolUseCount"
static let postToolUseCount = "postToolUseCount"
static let permissionRequestCount = "permissionRequestCount"
@@ -1036,6 +1037,7 @@ private extension WorkflowSyncService {
record[FieldKeys.sessionEndCount] = aggregate.sessionEndCount as CKRecordValue?
record[FieldKeys.userPromptSubmitCount] = aggregate.userPromptSubmitCount as CKRecordValue?
record[FieldKeys.stopCount] = aggregate.stopCount as CKRecordValue?
+ record[FieldKeys.interruptCount] = aggregate.interruptCount as CKRecordValue?
record[FieldKeys.preToolUseCount] = aggregate.preToolUseCount as CKRecordValue?
record[FieldKeys.postToolUseCount] = aggregate.postToolUseCount as CKRecordValue?
record[FieldKeys.permissionRequestCount] = aggregate.permissionRequestCount as CKRecordValue?
@@ -1237,6 +1239,7 @@ private extension WorkflowSyncService {
sessionEndCount: optionalIntValue(record[FieldKeys.sessionEndCount]),
userPromptSubmitCount: optionalIntValue(record[FieldKeys.userPromptSubmitCount]),
stopCount: optionalIntValue(record[FieldKeys.stopCount]),
+ interruptCount: optionalIntValue(record[FieldKeys.interruptCount]),
preToolUseCount: optionalIntValue(record[FieldKeys.preToolUseCount]),
postToolUseCount: optionalIntValue(record[FieldKeys.postToolUseCount]),
permissionRequestCount: optionalIntValue(record[FieldKeys.permissionRequestCount]),
diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swift
index f88a393..2bf01ab 100644
--- a/CodexBar/Views/Menu/CodexActivityCard.swift
+++ b/CodexBar/Views/Menu/CodexActivityCard.swift
@@ -112,7 +112,7 @@ struct CodexActivityCard: View {
.font(.caption2.monospacedDigit().weight(.semibold))
// 必须是具体 Color, 层级样式在 numericText 的过渡层里会被重新解析成别的层级
.foregroundStyle(Color.codexSecondaryLabel)
- .numericRollTransition(value: Double(content.otherTaskCount))
+ .contentTransition(.numericText(value: Double(content.otherTaskCount)))
.padding(.horizontal, 6)
.padding(.vertical, 3)
.background(.secondary.opacity(0.12), in: Capsule())
@@ -189,7 +189,7 @@ struct CodexActivityCard: View {
)
return ActivityCardContent(
symbolName: "xmark.circle.fill",
- tint: .secondary,
+ tint: .red,
title: activityTitle(
modelName: termination.modelName,
effort: termination.effort,
diff --git a/CodexBar/Views/Menu/CodexActivityCenterView.swift b/CodexBar/Views/Menu/CodexActivityCenterView.swift
index b685e7d..59a42c5 100644
--- a/CodexBar/Views/Menu/CodexActivityCenterView.swift
+++ b/CodexBar/Views/Menu/CodexActivityCenterView.swift
@@ -281,7 +281,7 @@ struct CodexActivityCenterView: View {
private func terminationRow(_ termination: CodexActivityTermination, now: Date) -> some View {
row(
symbolName: "xmark.circle.fill",
- tint: .secondary,
+ tint: .red,
projectName: termination.projectName,
modelName: termination.modelName,
effort: termination.effort,
diff --git a/CodexBar/Views/Menu/QuotaRow.swift b/CodexBar/Views/Menu/QuotaRow.swift
index ec89093..2cf4b0f 100644
--- a/CodexBar/Views/Menu/QuotaRow.swift
+++ b/CodexBar/Views/Menu/QuotaRow.swift
@@ -138,7 +138,7 @@ private struct AnimatedQuotaPercentageText: View, Animatable {
targetPercent: targetPercent
)
)
- .numericRollTransition(value: Double(roundedPercent))
+ .contentTransition(.numericText(value: Double(roundedPercent)))
}
private var roundedPercent: Int {
diff --git a/CodexBar/Views/Menu/TokenCountText.swift b/CodexBar/Views/Menu/TokenCountText.swift
index 7f6ee59..f16a964 100644
--- a/CodexBar/Views/Menu/TokenCountText.swift
+++ b/CodexBar/Views/Menu/TokenCountText.swift
@@ -11,7 +11,6 @@ struct TokenCountText: View {
content
.font(font)
.lineLimit(1)
- .minimumScaleFactor(0.8)
}
@ViewBuilder
@@ -21,7 +20,8 @@ struct TokenCountText: View {
if let reservedNumericWidth {
HStack(spacing: 0) {
Text(parts.number)
- .numericRollTransition(value: Double(tokens))
+ .contentTransition(.numericText(value: Double(tokens)))
+ .truncationMode(.tail)
.frame(minWidth: reservedNumericWidth, alignment: .trailing)
if let unit = parts.unit {
@@ -35,33 +35,6 @@ struct TokenCountText: View {
}
}
-/// 根据新旧数值方向选择 numericText 的滚动方向
-private struct NumericRollTransition: ViewModifier {
- let value: Double
- @State private var previous: Double?
-
- func body(content: Content) -> some View {
- content
- .contentTransition(.numericText(countsDown: countsDown))
- .onChange(of: value) { _, newValue in
- previous = newValue
- }
- }
-
- private var countsDown: Bool {
- guard let previous else {
- return false
- }
- return value < previous
- }
-}
-
-extension View {
- func numericRollTransition(value: Double) -> some View {
- modifier(NumericRollTransition(value: value))
- }
-}
-
/// 1K 以下显示完整整数, 1K 起使用 K/M/B
private enum TokenCountFormatter {
static func parts(from tokens: Int) -> TokenCountParts {
diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swift
index dbcfcb9..35fad77 100644
--- a/CodexBar/Views/Menu/UsageHeatmap.swift
+++ b/CodexBar/Views/Menu/UsageHeatmap.swift
@@ -129,6 +129,7 @@ struct UsageSummaryView: View {
metric(label: label) {
if let value {
TokenCountText(tokens: value)
+ .minimumScaleFactor(0.8)
} else {
Text(verbatim: "--")
.font(.caption.monospacedDigit().weight(.semibold))
@@ -607,7 +608,7 @@ struct UsageHeatmapDayDetailView: View {
}
private var header: some View {
- HStack(alignment: .center, spacing: Metrics.headerSpacing) {
+ HStack(alignment: .center, spacing: 0) {
dateText
.padding(.horizontal, 7)
.padding(.vertical, 3)
@@ -616,7 +617,6 @@ struct UsageHeatmapDayDetailView: View {
Spacer(minLength: 8)
tokenText
- .frame(minWidth: Metrics.tokenMinimumWidth, alignment: .trailing)
}
}
@@ -819,7 +819,7 @@ struct UsageHeatmapDayDetailView: View {
private func fittingMetricValue(_ value: String, comparison: Double) -> some View {
fittingValueContent(value)
- .numericRollTransition(value: comparison)
+ .contentTransition(.numericText(value: comparison))
.layoutPriority(1)
.frame(maxWidth: .infinity, alignment: .trailing)
}
@@ -864,7 +864,6 @@ struct UsageHeatmapDayDetailView: View {
static let workflowPanelHeight: CGFloat = 208
static let tokenPanelHeight: CGFloat = 84
static let sectionSpacing: CGFloat = 8
- static let headerSpacing: CGFloat = 10
static let horizontalPadding: CGFloat = 12
static let verticalPadding: CGFloat = 10
static let cornerRadius: CGFloat = 12
@@ -894,7 +893,6 @@ private struct HeatmapTokenText: View {
@State private var displayedTokenState: UsageHeatmapTokenState
@State private var isVisible = true
- @State private var fadeTask: Task<Void, Never>?
init(
tokenState: UsageHeatmapTokenState,
@@ -912,12 +910,9 @@ private struct HeatmapTokenText: View {
var body: some View {
content
.opacity(isVisible ? 1 : 0)
- .frame(width: width, alignment: .trailing)
- .onChange(of: tokenState) { _, newTokenState in
- updateDisplayedTokenState(newTokenState)
- }
- .onDisappear {
- fadeTask?.cancel()
+ .frame(minWidth: width, alignment: .trailing)
+ .task(id: tokenState) {
+ await updateDisplayedTokenState(tokenState)
}
}
@@ -945,9 +940,7 @@ private struct HeatmapTokenText: View {
}
}
- private func updateDisplayedTokenState(_ newTokenState: UsageHeatmapTokenState) {
- fadeTask?.cancel()
-
+ private func updateDisplayedTokenState(_ newTokenState: UsageHeatmapTokenState) async {
guard displayedTokenState != newTokenState || !isVisible else {
return
}
@@ -959,7 +952,7 @@ private struct HeatmapTokenText: View {
isVisible = true
}
} else {
- fadeToTokenState(newTokenState)
+ await fadeToTokenState(newTokenState)
}
}
@@ -970,23 +963,19 @@ private struct HeatmapTokenText: View {
}
}
- private func fadeToTokenState(_ newTokenState: UsageHeatmapTokenState) {
- fadeTask = Task { @MainActor in
- withAnimation(Metrics.fadeAnimation) {
- isVisible = false
- }
-
- try? await Task.sleep(for: .milliseconds(Metrics.fadeDelayMilliseconds))
- guard !Task.isCancelled else {
- return
- }
+ private func fadeToTokenState(_ newTokenState: UsageHeatmapTokenState) async {
+ withAnimation(Metrics.fadeAnimation) {
+ isVisible = false
+ }
- displayedTokenState = newTokenState
- withAnimation(Metrics.fadeAnimation) {
- isVisible = true
- }
+ try? await Task.sleep(for: .milliseconds(Metrics.fadeDelayMilliseconds))
+ guard !Task.isCancelled else {
+ return
+ }
- fadeTask = nil
+ displayedTokenState = newTokenState
+ withAnimation(Metrics.fadeAnimation) {
+ isVisible = true
}
}
@@ -1016,7 +1005,7 @@ private struct AnimatedDateText: View {
Text(verbatim: components.day)
}
.font(font)
- .numericRollTransition(value: dateValue(components))
+ .contentTransition(.numericText(value: dateValue(components)))
} else {
Text(verbatim: startDate)
.font(font)
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 5d257eb..46e8f26 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -13,7 +13,8 @@ struct AppSettingsView: View {
@ObservedObject var syncSettings: WorkflowSyncSettings
@ObservedObject var globalHotKeySettings: GlobalHotKeySettings
@ObservedObject var menuBarQuotaSettings: MenuBarQuotaSettings
- @ObservedObject var mainPanelSettings: MainPanelSettings
+ let mainPanelSettings: MainPanelSettings
+ let taskGlowSettings: TaskGlowSettings
@ObservedObject var notificationSettings: NotificationSettings
@ObservedObject var autoResetSettings: AutoResetSettings
@ObservedObject var keepAliveController: KeepAliveController
@@ -83,6 +84,7 @@ struct AppSettingsView: View {
syncSettings.refresh()
menuBarQuotaSettings.refresh()
mainPanelSettings.refresh()
+ taskGlowSettings.refresh()
autoResetSettings.refresh()
appUpdater.refreshAutomaticCheckSetting()
refreshStatusRows()
@@ -92,6 +94,7 @@ struct AppSettingsView: View {
syncSettings.refresh()
menuBarQuotaSettings.refresh()
mainPanelSettings.refresh()
+ taskGlowSettings.refresh()
autoResetSettings.refresh()
refreshStatusRows()
}
@@ -248,7 +251,12 @@ private extension AppSettingsView {
VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
mainPanelLayoutRow
LiquidGlassDivider()
- mainPanelEntranceAnimationsRow
+ MainPanelEntranceAnimationsSettingsRow(settings: mainPanelSettings)
+ LiquidGlassDivider()
+ TaskGlowSettingsRow(
+ settings: taskGlowSettings,
+ codexHookSettings: codexHookSettings
+ )
LiquidGlassDivider()
launchAtLoginRow
LiquidGlassDivider()
@@ -408,17 +416,6 @@ private extension AppSettingsView {
}
}
- var mainPanelEntranceAnimationsRow: some View {
- SettingsToggleRow(
- icon: "sparkles",
- title: "settings.main-panel.entrance-animations",
- isOn: Binding(
- get: { mainPanelSettings.areEntranceAnimationsEnabled },
- set: { mainPanelSettings.setEntranceAnimationsEnabled($0) }
- )
- )
- }
-
// MARK: - 高级页各行
var codexHookRow: some View {
diff --git a/CodexBar/Views/Settings/AppearanceSettingsRows.swift b/CodexBar/Views/Settings/AppearanceSettingsRows.swift
new file mode 100644
index 0000000..be64fbd
--- /dev/null
+++ b/CodexBar/Views/Settings/AppearanceSettingsRows.swift
@@ -0,0 +1,33 @@
+import SwiftUI
+
+struct MainPanelEntranceAnimationsSettingsRow: View {
+ @ObservedObject var settings: MainPanelSettings
+
+ var body: some View {
+ SettingsToggleRow(
+ icon: "sparkles",
+ title: "settings.main-panel.entrance-animations",
+ isOn: Binding(
+ get: { settings.areEntranceAnimationsEnabled },
+ set: { settings.setEntranceAnimationsEnabled($0) }
+ )
+ )
+ }
+}
+
+struct TaskGlowSettingsRow: View {
+ @ObservedObject var settings: TaskGlowSettings
+ @ObservedObject var codexHookSettings: CodexHookSettings
+
+ var body: some View {
+ SettingsToggleRow(
+ icon: "light.max",
+ title: "settings.screen-edge-indicator.title",
+ isOn: Binding(
+ get: { codexHookSettings.isOperable && settings.isEnabled },
+ set: { settings.setEnabled($0) }
+ ),
+ isEnabled: codexHookSettings.isOperable && !codexHookSettings.isUpdating
+ )
+ }
+}
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index 33901fe..e3a06ab 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 3.7.6
-CURRENT_PROJECT_VERSION = 90
+MARKETING_VERSION = 4.0.0
+CURRENT_PROJECT_VERSION = 100
diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.md
index 4e0ce35..bfe3751 100644
--- a/Docs/DeveloperGuide/activity-monitor.md
+++ b/Docs/DeveloperGuide/activity-monitor.md
@@ -8,10 +8,10 @@
- 当前是否有任务正在运行
- 当前是否在等待用户批准
-- 最近任务是完成还是中断
+- 最近任务是完成还是终止
- 哪些运行任务已经长时间没有进展
-Hook 事件提供低延迟信号,rollout 文件提供权威生命周期补充。[`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) 合并两者并发布唯一任务快照:
+Hook 事件提供实时进展和中断信号,rollout 文件补充生命周期信息。[`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) 合并两者并发布唯一任务快照:
```text
Hook JSONL -> HookEventTailReader ---------+
@@ -27,10 +27,11 @@ rollout JSONL -> CodexSessionLifecycleReader+
| 用户审批候选 | `PermissionRequest` | rollout reviewer 确认 |
| turn 起点 | `UserPromptSubmit` | rollout startedAt 或历史回查 |
| 完成候选 | `Stop` | rollout terminal |
-| 完成与中断分类 | rollout terminal | grace 到期 fallback |
+| 明确的 turn 中断 | `Interrupt` | rollout terminal |
+| 其他终态确认 | rollout terminal | grace 到期 fallback |
| effort | Hook recorder 回查 | rollout lifecycle backfill |
-Hook 优先解决低延迟,rollout 优先解决语义准确性。两者不是简单按时间戳覆盖,每个字段都有自己的可信来源。
+各字段按上表中的来源解析。Hook 每轮读取后等待 2 秒,rollout 每轮对账后等待 1 秒。
### 快照与转场
@@ -131,7 +132,15 @@ actor 在 `await` 期间可以重入,因此 `isProcessingReads` 和 `hasPendin
- 只解析生命周期、turn, progress, effort 和 reviewer
- 不读取或保存对话内容用于产品展示
-Hook 的 `Stop` 只是完成候选。rollout 中的 terminal 状态用于区分真正完成、用户取消和异常中断。
+Hook 的 `Stop` 将任务标记为“正在收尾”,保留在活动列表。后续工具、审批等进展继续更新同一任务,rollout 确认 `task_complete` 后才记录完成并发布完成转场。
+
+rollout 暂时不可读或无法关联 session、turn 时,任务继续等待对账。`Stop` 不启动终态超时;新 turn 或 `SessionEnd` 将旧任务移出活动列表,开启 5 秒终态确认窗口。迟到的 `Stop` 只更新待确认任务的元数据与进展,不恢复展示或重置窗口。
+
+### 明确中断
+
+`Interrupt` 结束匹配的顶层 turn,清理保护状态和通知,并保存终止记录。运行、等待批准、已隐藏和待确认终态的任务均可匹配;同一 session 的新 turn 保持活跃。身份有歧义时忽略该事件。
+
+同一任务的 Hook 和 rollout 终态共用去重记录,先确认的完成或终止结果保留。终止记录用于展示,不触发完成通知或触觉反馈。
### session 文件如何定位
@@ -179,24 +188,22 @@ subagent 事件更新父任务的 subagent 活动,不创建独立顶层任务
完全没有 session ID 时只能使用 project key。这个 key 可能把同项目并发匿名任务合并,所以匿名任务只承担可撤销的 UI 展示,不驱动通知、防睡眠或持久化保护。
-### Auto-review 来源过滤
-
-`CodexActivityMonitor.apply` 在任何状态转换之前检查 `WorkflowHookEvent.origin`。`WorkflowHookEvent` 在构造和解码边界优先使用明确来源,只有来源为 `unknown` 时才以精确匹配的 `model == "codex-auto-review"` 作为 `.autoReview` 后备判定。`autoReview` 不进入实时任务状态机,因此不会出现在菜单栏、活动卡片、任务中心和任务计数中,也不会产生通知、触觉反馈、等待批准、异常会话保护或防睡眠贡献。
-
-过滤使用精确的 `session ID + turn ID`,因为 Codex 的 subagent Hook 复用父 session ID。只按 session 过滤会连同真正的主任务一起隐藏。
+### 实时任务来源过滤
-当一条精确 Auto-review 事件到达时,monitor 会:
+`CodexActivityMonitor.apply` 先检查 `WorkflowHookEvent.origin`,再执行任务状态转换。来源归一化规则见 [Hook 来源归一化](hook-and-aggregation.md#来源归一化)
-- 删除同 key 的活动任务和 terminal grace 候选
-- 删除同 key 的最近完成、最近终止和 terminal 去重记忆
-- 取消异常会话保护尝试、持久化记录和待处理通知
-- 在 24 小时有界表中记住该精确 key,让同一任务后续 `unknown` 事件无法恢复它
+monitor 按精确的 `session ID + turn ID` 在内存中保存来源,保留 24 小时。Codex 的 subagent Hook 复用父 session ID,因此来源判定不扩大到整个 session。
-明确的 `main` 或 `auxiliary` 事件随后命中同一 key 时,来源事实优先并清除这条忽略记忆。Auto-review 事件缺少 turn ID 时只忽略当前事件,不建立 session 级黑名单。
+| 事件来源 | 实时处理 |
+| --- | --- |
+| `main`、`auxiliary` | 记录明确来源,并按正常状态机处理 |
+| `autoReview` | 忽略事件,清理同 key 的活动任务、待确认终态、展示记录和异常保护;保留来源记忆 |
+| `unknown`,同 key 有有效的 `main` 或 `auxiliary` 来源 | 沿用已确认来源,继续处理事件 |
+| `unknown`,没有有效的正常来源记忆 | 忽略事件 |
-其他 subagent(包括 Memories)归类为 `auxiliary`,按辅助任务事件参与关联。原始 Hook 事件仍进入历史聚合,实时 Auto-review 过滤不改变统计或 CloudKit 数据。
+缺少 session ID 或 turn ID 时不保存来源记忆,`unknown` 和 `autoReview` 事件直接忽略。来源已确认的任务不会因一次 rollout 读取失败被移除;迟到事件仍须通过状态机的时间和终态去重检查。
-JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码为 `unknown`。同一记录的 model 精确匹配 `codex-auto-review` 时,事件模型将来源归一化为 `.autoReview`;其他记录保持 `.unknown`。这一步只使用记录已有字段,不为来源分类额外扫描历史 rollout,也不回写原始 Hook 记录。
+这些规则同时用于 bootstrap 和实时读取。其他 subagent(包括 Memories)归类为 `auxiliary`,按辅助任务规则关联。历史聚合仍消费全部原始事件,来源记忆不持久化或上传。
### 新 prompt 与终态宽限
@@ -216,10 +223,12 @@ JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码
### 迟到事件如何被拒绝
-任务保存 `lastActivityAt`,terminal 记忆保存完成或中断时间:
+任务保存 `lastActivityAt`,完成和终止共用内存中的 `recentlyEndedTaskAt` 记录结束时间。展示记录仍分别保存在完成和终止列表,保留 10 分钟;去重记忆保留 24 小时,不随展示记录一起删除。来源过滤移除记录时,从剩余终态记忆重新计算对应 session 别名的最新时间。
+
+迟到事件按以下规则处理:
- 早于当前任务最后活动的事件不覆盖新状态
-- 不晚于已记录 terminal 的新 prompt 不会复活旧任务
+- 精确 turn 在终态记忆保留期间不允许重新创建;session 和匿名键只允许时间更新的新 prompt 复用
- `Stop` 命中多个候选时不猜测
- 已进入 terminal 去重记忆的 key 会清除异常顺序留下的恢复任务
@@ -247,12 +256,12 @@ JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码
`PermissionRequest` 只有在 reviewer 是用户时才进入 `waitingApproval`。自动审批或策略审批不会被视为用户等待。
-终止信号按可靠性对账:
+任务结束按以下信号处理:
-- `SessionEnd` 结束 session
-- rollout terminal 区分完成和中断
-- `Stop` 在缺少更强信号时形成完成候选
-- 新 prompt 可以结束旧 turn 的展示生命周期
+- `Stop` 将任务标记为正在收尾,继续保留在活动列表
+- `Interrupt` 将匹配的 turn 记录为终止
+- rollout terminal 确认完成或终止
+- 新 turn 或 `SessionEnd` 将旧任务移入 5 秒终态确认窗口,到期仍无终态时记录终止;已隐藏任务只记录去重状态
### 事件到状态的主要转换
@@ -263,8 +272,9 @@ JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码
| running | tool, compact, subagent progress | running | 更新 last progress 和 generation |
| running | `PermissionRequest` + reviewer user | waitingApproval | 发布 live waiting transition |
| waitingApproval | 新进展 | running | 清除 pending approval 和保护记录 |
-| running 或 waiting | `Stop` | terminal candidate | 保存完成或等待 rollout 对账 |
+| running 或 waiting | `Stop` | running | 显示正在收尾,保留任务直到 rollout 确认终态 |
| active | 新 prompt 或 `SessionEnd` | pending terminal | 从快照移除并开启 5 秒 grace |
+| active、suppressed 或 pending terminal | `Interrupt` | terminated | 移除匹配任务、记录终止并清理保护状态和通知 |
| running | 静默超过阈值 | suppressed | 隐藏并退出防睡眠贡献 |
| suppressed | 新进展 | running | 清除持久化保护与旧通知 |
@@ -293,16 +303,17 @@ subagent 的 turn ID 属于 subagent 自己,父任务只能通过共享 sessio
活动卡片的 `primaryActivity` 按以下优先级选择内容:
```text
-等待批准 > 运行中 > 最近完成 > 最近中断 > 空闲
+等待批准 > 运行中 > 最新的完成或终止 > 空闲
```
-菜单栏同样优先展示等待批准和运行中任务;没有活跃任务时,从完成与终止记录中选择最新一条,显示到结束时间后 10 秒。任务中心的终态记录保留 10 分钟,terminal 去重记忆保留 24 小时。
+`latestTerminalEvent` 按结束时间选择最新的完成或终止,时间相同优先终止。活动卡片、菜单栏和空闲时的任务流光共用该结果。菜单栏在 `primaryActivity` 的基础上限制终态显示到结束时间后 10 秒。任务中心的终态记录保留 10 分钟,terminal 去重记忆保留 24 小时。
快照由以下模块消费:
- 菜单栏人物图标
- 主面板任务卡片
- 活动中心
+- 任务流光
- 通知系统
- 防睡眠控制器
@@ -312,6 +323,12 @@ monitor 每秒检查 rollout,并在清理 deadline 到达时刷新。
新快照先与当前值比较,只有结构变化才发布。运行时长文案由 View 使用当前时间格式化,不要求每秒修改任务对象。
+### 展示更新
+
+`presentationPublisher` 发布当前快照和本轮仍有效的 `terminalEvents`,供任务流光使用。展示事件包含匿名任务;通知使用独立的 `transitionPublisher`
+
+历史重读、睡眠恢复和数据源健康状态变化时清空待发布事件,并更新 `terminalPresentationNotBefore`。bootstrap、唤醒对账和数据源不健康期间暂停收集;结束时间早于恢复界限的记录不产生短提示,恢复后结束的任务正常发布。
+
### 稳定排序
同一 batch 中多个任务可能具有相同时间戳,仅按时间比较无法确定它们之间的顺序。
@@ -320,7 +337,7 @@ monitor 每秒检查 rollout,并在清理 deadline 到达时刷新。
### 清理采用最近 deadline
-monitor 管理 terminal grace、活动保留、历史保留、terminal 去重和保护记录过期。菜单栏完成或终止提示的 10 秒到期由 `StatusItemController` 独立管理,不为提示到期重新发布活动快照。
+monitor 管理 terminal grace、活动保留、历史保留、terminal 去重和保护记录过期。菜单栏终态提示和任务流光分别由 `StatusItemController`、`TaskGlowController` 管理到期时间。提示到期不重新发布活动快照。
清理任务只等待最近的未来 deadline,到点处理后安排下一次。
@@ -454,14 +471,22 @@ Monitor 为 reader 和异步恢复任务维护 generation:
| generation | 保护的异步路径 |
| --- | --- |
| `tailReaderGeneration` | reader batch, rollout poll 和 prompt backfill |
-| `bootstrapCompletionGeneration` | 多次 bootstrap 重试后的异步 lifecycle 补齐 |
-| `activityProtectionRecoveryGeneration` | 睡眠、唤醒和数据源恢复 |
+| `bootstrapCompletionGeneration` | bootstrap 的异步 lifecycle 补齐,以及跨 bootstrap 的 rollout 对账结果 |
+| `activityProtectionRecoveryGeneration` | 睡眠、唤醒恢复流程,以及跨恢复批次的 rollout 对账结果 |
| task `progressGeneration` | 通知宽限期间的保护候选 |
每一项都对应不同的“当前性”问题,不能合并成一个全局计数。例如 reader 没变但任务有新进展时,只需要让 protection attempt 失效,不应丢弃整个 reader。
## 建议验证的故障场景
+- Stop handler 要求继续后完成或中断,确认没有提前完成提醒
+- Stop handler 执行期间中断,只产生一条终止记录和红色提示
+- rollout 不可读超过 5 秒仍不判定完成,恢复后只确认一次
+- Stop 后继续请求用户批准,等待状态和中断清理正常
+- 中断运行、等待批准和隐藏任务,确认状态、耗时、保护清理且无完成通知
+- Hook 与 rollout 终止以两种顺序到达,确认单条记录和单次提示
+- 新 turn 开始后收到旧 turn 中断,新任务保持活跃
+- 重复 Interrupt 和迟到工具或 prompt 事件不能恢复已结束的 turn
- App 在任务已运行时启动,bootstrap 展示任务但不补发通知
- bootstrap 文件持续追加时能重试并最终获得稳定边界
- 连续 3 次不稳定后进入 degraded,不启动异常静默判断
diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.md
index 10292a8..7f68142 100644
--- a/Docs/DeveloperGuide/app-server.md
+++ b/Docs/DeveloperGuide/app-server.md
@@ -110,7 +110,7 @@ codex app-server --listen stdio://
```text
启动子进程
-> initialize(clientInfo)
- -> 校验实际版本 >= 0.143.0
+ -> 校验实际版本 >= 0.145.0
-> initialized
-> account/read
-> account/rateLimits/read
@@ -127,14 +127,14 @@ stdout 可能包含非 JSON 输出。pipe reader 会持续读取完整行,只
-> 启动 Process
-> initialize(clientInfo)
-> 从 userAgent 保存实际版本
- -> 校验实际版本 >= 0.143.0
+ -> 校验实际版本 >= 0.145.0
-> initialized notification
-> account/read(refreshToken: false)
-> account 存在: 提交 connection
-> account 缺失: 关闭进程并返回 notLoggedIn
```
-只有实际版本满足全局门槛,并且 handshake 与首次账户读取都成功,connection 才进入 service 状态。版本低于 `0.143.0` 或无法解析时按不支持处理,关闭半初始化 session,不继续发送账户请求。
+只有实际版本满足全局门槛,并且 handshake 与首次账户读取都成功,connection 才进入 service 状态。明确低于 `0.145.0` 时返回版本不支持;版本缺失或无法解析时返回无效响应,不能作为 Hook 自动清理的低版本依据。两种情况都会关闭半初始化 session,不继续发送账户请求。
### Stdout 分行与响应匹配
@@ -411,7 +411,7 @@ Hook 设置也复用 app-server 链路,但采用独立的可用性状态:
- `isOperable` 只有在两者都为 `true` 时成立
- 短暂 RPC 失败保留上一次明确校验结果
-启用或校验 Hook 时必须确认实际 app-server 版本不低于 `0.145.0`
+启用或校验 Hook 时必须确认实际 app-server 版本不低于 `0.150.0`
详细配置流程见 [Hook 采集与历史聚合](hook-and-aggregation.md)
@@ -422,7 +422,7 @@ Hook 设置也复用 app-server 链路,但采用独立的可用性状态:
- 没有连接时先建立连接
- 有连接时复用当前真实进程
- 从 handshake user agent 解析运行版本
-- 无法解析版本时按不支持处理,不乐观放行
+- 无法解析版本时拒绝连接,但不触发低版本 Hook 自动清理
## 请求日志
@@ -448,9 +448,9 @@ Reset Credits 明细包含 opaque credit ID。系统日志不能记录 ID 或原
- stderr 持续输出时请求不会因 pipe 背压卡住
- 复用连接的 transport failure 只重建一次
- 磁盘 CLI 升级后,当前连接版本与磁盘版本能被区分
-- app-server 低于 `0.143.0` 时阻断账户主链路并提示升级
-- app-server 为 `0.143.x` 或 `0.144.x` 时账户主链路可用,但 Hook 仍提示需要 `0.145.0`
-- app-server 不低于 `0.145.0` 时账户主链路和 Hook 校验均可用
+- app-server 低于 `0.145.0` 时阻断账户主链路并提示升级
+- app-server 不低于 `0.145.0` 且低于 `0.150.0` 时账户主链路可用,但 Hook 仍提示需要 `0.150.0`
+- app-server 不低于 `0.150.0` 时账户主链路和 Hook 校验均可用
- rate limits 失败但同账户有缓存时展示 stale,通知不误触发
- 账户切换后旧额度和用量立即清空
- unsupported method 不会每分钟重复请求
diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.md
index dab1b23..3630f23 100644
--- a/Docs/DeveloperGuide/architecture.md
+++ b/Docs/DeveloperGuide/architecture.md
@@ -124,7 +124,7 @@ Hook handler 在 Codex 的关键路径上,它需要的是接近命令行工具
| --- | --- | --- | --- |
| app-server | `codex app-server` JSON-RPC | 账户、额度、token 用量、Reset Credit 使用、Hook 配置能力 | 主面板、菜单栏额度、设置、自动重置状态机 |
| Hook 历史 | Hook JSONL | 日级事件、session, turn, tool, model 聚合 | 活跃度热力图、历史统计、CloudKit |
-| 实时任务 | Hook 增量事件加 rollout 生命周期 | 运行、等待批准、完成、中断 | 菜单栏状态、任务中心、通知、防睡眠 |
+| 实时任务 | Hook 增量事件加 rollout 生命周期 | 运行、等待批准、完成、终止 | 菜单栏状态、任务中心、任务流光、通知、防睡眠 |
### 依赖方向
@@ -238,7 +238,7 @@ Hook + rollout --------> CodexActivityMonitor --------> UI
| 自动重置唤醒时间同步 | `AutoResetWakeScheduler` | `AutoResetController` 只提交下一次时间,`KeepAliveController` 只提交 helper 就绪状态 |
| Hook 安装与验证 | `CodexHookSettings` | 读取 `isOperable` |
| 历史聚合和维护游标 | `WorkflowService` | 请求快照或重建 |
-| 实时任务 | `CodexActivityMonitor` | 读取 snapshot 或 transition |
+| 实时任务 | `CodexActivityMonitor` | 读取快照、通知转场或包含新增终态的展示更新 |
| 同步游标与远端缓存 | `WorkflowSyncService` | 请求合并快照 |
| 防睡眠策略与 App assertion | `KeepAliveController` | 读取派生状态或调用设置入口 |
| root 睡眠所有权 | `CodexBarHelper` | 通过 XPC 请求和查询 |
diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.md
index ef257ca..44cc4d0 100644
--- a/Docs/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/DeveloperGuide/hook-and-aggregation.md
@@ -24,7 +24,7 @@ Codex Hook
启用流程检查以下条件,其中来源、信任和事件完整性在写入后校验:
- 当前可执行文件路径可解析
-- 实际 app-server 版本不低于 `0.145.0`
+- 实际 app-server 版本不低于 `0.150.0`
- `features.hooks` 可用
- `hooks/list` 返回可信来源
- 所需事件集合完整
@@ -49,7 +49,7 @@ Codex Hook
App 启动、设置状态刷新、主面板打开和每轮额度刷新完成时,都会对账已开启的 Hook。自动刷新间隔为上一轮完成后 60 秒:
-- 只有已确认的实际 app-server 版本低于当前 Hook 最低版本时,才按手动关闭流程移除 CodexBar handler 和对应信任项
+- 只有已确认的实际 app-server 版本低于当前 Hook 最低版本时,才移除 CodexBar handler 并尽力清理对应信任项;低于全局最低版本时也执行本地移除
- 版本无法确认或 RPC 临时失败时保留用户配置
- 配置在当前进程中丢失不会关闭开关,而是标记配置损坏并触发自愈
- 版本受支持时遍历 `CodexHookEvent.allCases`,为缺失或非标准事件重建独立 group,然后复用信任和完整性校验
@@ -61,7 +61,7 @@ App 启动、设置状态刷新、主面板打开和每轮额度刷新完成时
### 启用事务的顺序
```text
-确认运行中 app-server >= 0.145.0
+确认运行中 app-server >= 0.150.0
-> 确认 features.hooks 没有全局关闭
-> 读取现有 hooks.json
-> 只移除当前 executable 的旧 CodexBar handler
@@ -80,7 +80,7 @@ app-server 的 Hook key 来自它当前解析到的 handler。如果先从 `hook
因此禁用流程先保存精确匹配条目的 key、再删 handler、最后从 `hooks.state` 中清理这些 key。清理时先读取完整 state 再 replace,保留用户和其他工具的信任项。
-信任清理失败不会把 handler 重新装回去。UI 会表达“Hook 已关闭,但清理未完成”,因为停止采集的用户意图已经成功。
+低于全局最低版本时,app-server 连接已被拒绝,禁用流程直接移除本地 handler,保留无法查询和删除的信任项,不额外显示信任清理提示。其他情况下,信任查询或清理失败显示无法清理信任状态的提示,Hook 保持关闭。本地配置移除失败仍显示错误,并在后续对账时重试。
### 事件分组
@@ -109,6 +109,7 @@ CodexBar 订阅以下 Hook 事件:
| `PreCompact` | 记录上下文压缩开始 |
| `PostCompact` | 记录上下文压缩结束 |
| `Stop` | 形成任务完成候选 |
+| `Interrupt` | 结束对应 turn 并记录中断统计 |
| `SubagentStart` | 记录 subagent 启动 |
| `SubagentStop` | 记录 subagent 结束 |
@@ -137,7 +138,7 @@ handler 超时由事件决定:
| 事件 | 超时 |
| --- | --- |
-| `SessionEnd` | 3 秒 |
+| `SessionEnd`、`Interrupt` | 3 秒 |
| 其他事件 | 5 秒 |
锁等待预算为 handler 超时减 2 秒。获取锁时从 1 ms 开始指数退避,单次等待最多 20 ms。
@@ -206,7 +207,7 @@ recorder 在写入前完成来源解析,JSONL 的来源字段只保存上述
JSONL 中缺少 `origin`,或枚举值无法识别时,来源字段先解码为 `unknown`。`WorkflowHookEvent` 解码器随后应用相同的精确 model 后备判定,因此 `model == "codex-auto-review"` 的事件在内存中的 `origin` 为 `autoReview`。读取过程不会回填或重写原始 JSONL。
-来源分类只改变实时活动过滤,不改变历史统计输入。Auto-review 事件仍参与 session、turn、model、tool、project 和事件计数;聚合 schema 和 CloudKit 投影不包含来源分类。
+历史聚合按全部 Hook 事件统计,包含 `autoReview` 和 `unknown` 来源;聚合结果和 CloudKit 投影不包含来源字段。
### 输入归一化
@@ -350,7 +351,7 @@ inode 与 size 能发现替换和截断,boundary hash 能发现保持相同长
- project 分布
- model 分布
-session 数使用当天除 `SessionEnd` 外所有事件中的非空 session ID 去重计算。turn 数使用当天除 `Stop` 外所有事件中的非空 turn ID 去重计算。跨天 session 或 turn 只要当天仍有未被排除的事件,就计入当天;当天只有 `SessionEnd` 的 session 和只有 `Stop` 的 turn 不计入。
+session 数使用当天除 `SessionEnd` 外所有事件中的非空 session ID 去重计算。turn 数使用当天除 `Stop` 和 `Interrupt` 外所有事件中的非空 turn ID 去重计算。跨天 session 或 turn 只要当天仍有未被排除的事件,就计入当天;当天只有 `SessionEnd` 的 session 和只有 `Stop` 或 `Interrupt` 的 turn 不计入。
成对事件可能只有一侧成功落盘。因此计数使用能够避免重复且允许缺失的规则:
@@ -363,7 +364,7 @@ session 数使用当天除 `SessionEnd` 外所有事件中的非空 session ID
- 缺失表示该日期的历史来源无法提供该指标
- `0` 表示来源可用且明确没有发生
-解码和持久化保留可选值。展示层通过 `WorkflowDailyMetrics` 把缺失的单项事件计数转换为 `0`;session 和 turn 计数优先使用 ID 去重结果或已压缩计数,再回退到对应事件计数。
+解码和持久化保留可选值。`WorkflowDailyMetrics` 保留 `interruptCount` 的缺失值,其他单项事件计数缺失时显示为 `0`;session 和 turn 计数优先使用 ID 去重结果或已压缩计数,再回退到对应事件计数。
### 成对事件计数
@@ -376,17 +377,15 @@ session 数使用当天除 `SessionEnd` 外所有事件中的非空 session ID
compaction 和 subagent 成对事件使用相同规则。
-### 可用性如何穿过旧数据
+### 计数可用性
-旧版本聚合可能没有某类 Hook count。重建时不能因为当前代码认识该事件,就假定旧来源也采集过。
+`WorkflowHookCountAvailability` 保存每类计数的来源可用性。重建继承已有日期的可用性;没有聚合时使用 `.legacy`,其中 `interruptCount` 为不可用,其他事件计数从 `0` 开始。实际读到 `Interrupt` 后,中断计数从缺失变为正数;其他事件保留其缺失值。
-`WorkflowHookCountAvailability` 保存每类计数是否有来源。重建会继承现有日期对旧字段的可用性,新鲜来源则可以声明当前字段全部可用。
-
-这种可用性保留在聚合和同步字段中,当前 UI 不逐项展示历史字段是否缺失。
+`interruptCount` 在展示投影中仍为可选值,同日任一贡献缺失时合计也不可用。热力图详情不展示此指标。
## Schema 演进与重建
-当前聚合 schema 为 `6`,由 `WorkflowMaintenanceState.currentAggregationSchema` 管理。
+当前聚合 schema 为 `9`,由 `WorkflowMaintenanceState.currentAggregationSchema` 管理。
以下变化必须递增 schema:
@@ -433,7 +432,7 @@ schema 变化通常把保留期内所有事件日期标脏。source generation
维护默认跟随 60 秒刷新。空闲机器一天会执行上千次没有变化的检查。
-`WorkflowService` 累计连续 idle 轮数,只有真正写入、跳过、失败或清理时才输出一条摘要,并附带之前空转次数。这样日志既能证明维护一直在运行,又不会淹没真正故障。
+`WorkflowService` 累计连续 idle 轮数,在写入、跳过、失败或清理时输出摘要,并附带累计空转次数。
### scheduler 如何合并请求
diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.md
index a7502ba..39e011d 100644
--- a/Docs/DeveloperGuide/notifications.md
+++ b/Docs/DeveloperGuide/notifications.md
@@ -135,9 +135,10 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正
任务通知只响应 monitor 发布的新 terminal 转场,不扫描历史列表推导:
- bootstrap 建立的历史任务不发送通知
-- terminal ID 在活动监控层保留 24 小时去重
+- 终态任务键在活动监控层保留 24 小时去重
- 通知服务还维护自己的已发送 key
-- 同一 turn 的 `Stop` 和 rollout terminal 对账后只发送一次
+- `Stop` 保留正在收尾的任务,rollout 确认完成后只发布一次完成转场
+- `Interrupt` 和其他终止记录不触发完成通知或任务触觉反馈
匿名任务不会发布给任务通知消费者。通知服务在 transition 入口再次过滤 `isAnonymous`,因此匿名任务不发送完成或等待批准通知,也不触发任务触觉反馈。
@@ -169,7 +170,7 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正
非匿名运行任务静默达到阈值时,Activity Protection 先更新内存保护记录并安排异步保存,再并行启动通知提交和 3 秒宽限。通知处理返回或宽限到期后,monitor 重新校验候选,仍有效时才隐藏任务。隐藏不等待磁盘写入或通知成功。
-通知使用 `taskID + attemptID` 作为 identifier,提交前后校验 progress generation 和静默时长。新进展会使保护尝试失效,并撤回对应通知。
+通知使用 `taskID + attemptID` 作为 identifier,有效性由 monitor 的当前保护尝试决定。提交前后校验 attempt ID、progress generation 和静默时长。保护尝试失效时,通知服务按该 identifier 移除 delivered 和 pending notification。
保护通知使用系统默认声音,`retryCount` 为 `0`,避免重试已经失效的候选。
diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.md
index 9abd4ac..9c8b69f 100644
--- a/Docs/DeveloperGuide/sync.md
+++ b/Docs/DeveloperGuide/sync.md
@@ -176,7 +176,9 @@ generation 记录用于表达某一份原始来源的身份。同源的本地和
CloudKit record schema 演进时,旧记录可能没有新计数字段。`nil` 表示该设备那天无法提供这项统计,`0` 表示明确观察到零次。
-CloudKit 解码及持久化模型保留可选计数字段。当前 `WorkflowDailyMetrics` 展示投影会把缺失的单项事件计数转换为 `0`;session 和 turn 计数先回退到对应的开始或停止事件计数,再回退为 `0`。UI 中整日统计不可用与单个计数字段缺失是不同情况。
+CloudKit 解码及持久化模型保留可选计数字段。本地与远端聚合共用 `WorkflowDailyMetrics` 展示投影:保留 `interruptCount` 的缺失值,其他单项事件计数缺失时转换为 `0`;session 和 turn 计数缺失时先回退到对应的开始或停止事件计数,再回退为 `0`。
+
+CloudKit 使用可选整数字段 `interruptCount` 保存中断次数。同日合并的任一贡献缺少该字段时,中断次数合计保持不可用。
## 来源替换与重建
@@ -219,7 +221,7 @@ replacement 删除前全量拉取当前设备同日记录,覆盖本地增量
| `cache.jsonl` | 远端设备日聚合缓存 |
| `cursor.data` | CloudKit zone change token |
-当前 CloudKit record schema 为 `5`。本地同步状态 schema 为 `4`,能读取上一版 schema `3`
+当前 CloudKit record schema 为 `6`。本地同步状态 schema 为 `4`,能读取上一版 schema `3`
3 个文件有不同的可恢复等级:
@@ -293,6 +295,7 @@ CloudKit 记录保留期与本地 Hook 历史一致,最长 210 天:
- 首次启用后上传保留期内本机聚合
- 第二台设备能够合并显示,不重复当前设备贡献
+- 包含和缺少 `interruptCount` 的设备记录合并后,该指标保持不可用
- 关闭同步后只显示本地统计
- iCloud 未登录时显示明确状态,本地统计继续工作
- 网络断开后使用最后缓存,恢复后完成增量同步
diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.md
index 8949513..87a8101 100644
--- a/Docs/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md
@@ -37,6 +37,7 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。
-> 对账 Hook 并启动周期刷新
-> 启动通知与自动重置
-> 连接异常会话保护回调
+ -> 启动任务流光订阅
-> 启动 activity monitor 与 keep-alive 协调
```
@@ -44,6 +45,20 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。
终止时顺序反转,但 helper 系统状态是例外。AppDelegate 先异步确认自动重置唤醒计划已经取消,并确认防睡眠 lease 已释放,全部成功后才允许进程终止。详细事务见 [防睡眠系统](sleep-prevention.md)
+## 任务流光
+
+`TaskGlowController` 在 `TaskGlowSettings.isEnabled` 和 Hook 的 `isOperable` 均为 `true` 时显示任务状态,与主面板动画开关独立。输入来自 `CodexActivityMonitor.presentationPublisher`,包含当前快照与本轮结束事件,见[展示更新](activity-monitor.md#展示更新)
+
+| 场景 | 展示规则 |
+| --- | --- |
+| 存在活跃任务 | 橙色等待批准优先于青色运行 |
+| 其他任务仍活跃时确认结束事件 | 最新事件覆盖活动状态 3 秒,最后 0.5 秒淡出;新事件替换提示并重新计时 |
+| 无活跃任务 | 快照中的最新终态显示到结束后 10 秒,最后 1 秒淡出 |
+
+完成使用绿色,终止使用红色;结束时间相同优先终止。所有计时包含进场动画,到期后按最新快照恢复展示。
+
+光带使用不激活、穿透鼠标的 `NSPanel`,跨 Space 和全屏显示。系统睡眠、屏幕休眠或用户会话不活跃时移除窗口,恢复后按当前时间接续有效状态。屏幕配置变化时重建窗口,各显示器共享运动时钟。
+
## 状态栏图标
状态图标综合 app-server 加载状态、菜单栏额度设置和任务活动快照。
@@ -93,7 +108,7 @@ hidden -> opening -> shown -> closing -> hidden
- `opening` 或 `shown` 时再次 toggle 进入关闭
- `closing` 时再次 toggle 先完成旧关闭,再打开新表面
-- 关闭开始后取消延迟刷新和旧动画
+- 关闭开始后取消未完成的淡入任务
- 非动画关闭直接完成状态清理
`activeMenuSurface` 记录当前容器,取值为 `none`、`popover` 或 `fallbackPanel`。主动关闭容器前先将其设为 `none`
@@ -134,7 +149,7 @@ popover 和备用面板分别持有 `MenuSurfaceAnimationState`。展示前将 `
### 活动卡片
-`CodexActivityCard` 使用 `primaryActivity`,优先级为等待批准、运行中、最近完成、最近终止。`isActivelyPreventingSleep` 为 `true` 且卡片数据可用时显示青绿色 `sun.max.fill`。所属宿主的 `mainPanelAnimationsEnabled` 开启时创建独立的旋转视图,以线性动画每 2 秒顺时针旋转一圈,不使用系统符号效果的启动加速阶段。关闭许可后移除旋转视图并切回静态图标;重新展示时仅在“动画效果”开启的情况下恢复旋转。popover 与 fallback 宿主各自控制,不互相激活动画。tooltip 按 `sleepPreventionSource` 显示来源。
+`CodexActivityCard` 使用 `primaryActivity`,优先显示等待批准,其次是运行中;无活跃任务时按结束时间选择最新的完成或终止,时间相同优先终止。`isActivelyPreventingSleep` 为 `true` 且卡片数据可用时显示青绿色 `sun.max.fill`。所属宿主的 `mainPanelAnimationsEnabled` 开启时创建独立的旋转视图,以线性动画每 2 秒顺时针旋转一圈,不使用系统符号效果的启动加速阶段。关闭许可后移除旋转视图并切回静态图标;重新展示时仅在“动画效果”开启的情况下恢复旋转。popover 与 fallback 宿主各自控制,不互相激活动画。tooltip 按 `sleepPreventionSource` 显示来源。
## Fallback panel
@@ -173,6 +188,8 @@ fallback panel 在展示前根据 SwiftUI fitting size 和目标屏幕可见区
热力图详情面板以包含标题、日期范围和方格矩阵的完整热力图区域作为垂直锚点,因此主面板区域重排后仍优先保持两者顶边对齐。如果详情面板从该位置向下会超过主面板底边,则定位逻辑将它整体上移到与主面板底边对齐。
+主面板可见时,数字随数据变化滚动,Token 数字与待查询或不可用占位之间淡入淡出。“动画效果”控制入场动画和太阳徽标旋转,数字更新不受此开关控制。
+
相关控制器包括:
- [`HeatmapDetailPanelController.swift`](../../CodexBar/Controllers/HeatmapDetailPanelController.swift)
@@ -256,13 +273,13 @@ Carbon API 适合无 Dock 菜单栏 App,不需要安装全局键盘事件 tap
## 自动刷新与面板打开
-app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调用 `refreshIfNeeded`,倒计时起点为空或距上次刷新结果提交超过 60 秒时才发起请求。成功和失败的结果提交都会重置倒计时;该检查可能发生在淡入动画结束之前。
+app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完成且面板仍可见时,调用 `refreshIfNeeded`;倒计时起点为空或距上次刷新结果提交超过 60 秒时才发起请求。成功和失败的结果提交都会重置倒计时。
主面板显示刷新倒计时,双击账户图标可立即手动刷新。
普通刷新在刷新或重连进行中被忽略。需要在当前请求后补刷的操作通过 `refreshAfterCurrent` 保存一个待执行触发,当前请求结束后再执行。
-面板打开时立即对账 Hook 配置,并在 Hook 开启时请求本地统计刷新。延迟任务只检查账户、额度和用量是否需要刷新;面板提前关闭时取消该任务。
+淡入完成回调依次触发 Hook 配置对账、Hook 开启时的本地统计刷新检查,以及账户、额度和用量刷新检查。面板在淡入完成前关闭时,取消完成任务及其尚未触发的刷新。
## 本地化和格式化
@@ -284,6 +301,8 @@ app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调
## 手动验证矩阵
- 左键打开主面板,右键和 Control 点击打开上下文菜单
+- 多任务运行或等待批准期间,完成和终止触发 3 秒流光提示;连续结束及全部任务结束时颜色与到期时间正确
+- 历史重读及唤醒对账不补播旧终态短提示,恢复后的真实结束仍有提示;多显示器和屏幕配置变化后运动与到期时间一致
- 菜单栏符号随任务状态切换,最新终态在结束 10 秒后恢复空闲,跨睡眠唤醒后按当前时间显示
- 普通人物与四种任务徽章之间切换时过渡完整,快速连续切换后显示最新状态;带徽章时反复切换额度显隐仍保持流畅,首次显示和唤醒重算不播放过渡
- 切换额度圆弧显隐时动画完整,零额度保留底轨,缓存额度变淡
@@ -304,6 +323,7 @@ app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调
- 多显示器和不同菜单栏位置下 fallback panel 位于鼠标屏幕
- 快捷键冲突后原快捷键仍可用
- 面板打开刷新不会造成动画卡顿或重复请求
+- 数字首次递减、连续增减、Token 单位切换和日期跨月时方向正确,主面板关闭后停止数字动画
## 关键源码
diff --git a/Docs/UserGuide/activity-and-hook.md b/Docs/UserGuide/activity-and-hook.md
index d63cbe3..2c1d611 100644
--- a/Docs/UserGuide/activity-and-hook.md
+++ b/Docs/UserGuide/activity-and-hook.md
@@ -10,9 +10,9 @@ CodexBar Hook 用于显示实时任务,并支持任务通知、触觉反馈、
2. 开启 `CodexBar Hook` 并等待校验完成
3. 开始一轮 Codex 任务,在主面板查看状态
-Hook 要求当前使用的 Codex 为 `0.145.0` 或更高版本。更新后仍提示版本过低时,在 `设置 > 关于` 点击 `重新建立连接`。其他错误见 [常见问题与排查](troubleshooting.md#hook-无法开启或校验失败)
+Hook 要求当前使用的 Codex 为 `0.150.0` 或更高版本。更新后仍提示版本过低时,在 `设置 > 关于` 点击 `重新建立连接`。其他错误见 [常见问题与排查](troubleshooting.md#hook-无法开启或校验失败)
-CodexBar 会自动检查和修复已开启的 Hook 配置。开启或关闭时,会保留用户和其他 App 已有的 Hook。
+CodexBar 自动检查和修复已开启的 Hook 配置,保留用户和其他 App 的 handler。确认 Codex 低于最低版本时,会关闭 Hook 并移除自己的 handler;更新 Codex 后需要重新开启 Hook。暂时无法连接或确认版本时保留配置,等待下次校验。
## 任务状态
@@ -21,11 +21,15 @@ CodexBar 会自动检查和修复已开启的 Hook 配置。开启或关闭时
| 运行中 | Codex 正在处理任务 |
| 等待批准 | 需要你批准下一步操作 |
| 最近完成 | 一轮任务已结束,不代表结果一定成功 |
-| 最近终止 | 任务被中断,不发送完成通知 |
+| 最近终止 | 中断或其他终态信号确认任务终止,不发送完成通知 |
-子 Agent 的活动合并到所属任务中。内部自动审核任务不显示为独立任务,也不触发任务提醒或防睡眠;它的活动仍计入每日统计。
+收到 `Stop` 后会先显示“正在收尾”,确认本轮完成且满足通知设置后才发送完成提醒。如果其他 Hook 让任务继续执行,状态会继续更新;期间中断则显示已终止。
-无法识别会话的任务会带有橙色匿名图标。这类任务可以查看,但不触发通知或触觉反馈,也不参与防睡眠和异常会话保护。
+中断只结束对应轮次,同一会话随后开始的新任务保持活跃。全部符合条件的任务结束后,按任务防睡眠会释放。
+
+子 Agent 的活动合并到所属任务中。内部自动审核任务和来源始终无法确认的任务不显示为实时任务,也不触发流光、任务提醒或防睡眠;它们的活动仍计入每日统计。同一会话和轮次已确认是正常任务后,后续暂时无法识别来源的事件仍会更新任务状态。
+
+来源明确但无法识别会话的任务会带有橙色匿名图标。这类任务可以查看,但不触发通知或触觉反馈,也不参与防睡眠和异常会话保护。
长时间没有进展的运行任务可能被 [异常会话保护](sleep-prevention.md#异常会话保护) 隐藏,恢复进展后重新显示。
@@ -33,7 +37,7 @@ CodexBar 会自动检查和修复已开启的 Hook 配置。开启或关闭时
在主面板热力图上悬停日期,可查看当天的会话数、对话轮次、工具调用、权限请求、上下文压缩、子 Agent 和最常用模型。
-会话和轮次按天去重,跨天继续活动会计入新的一天。工具调用等成对记录可能不完整,因此统计反映 CodexBar 实际观察到的活动。
+会话和轮次按天去重,跨天继续活动会计入新的一天。当天只有会话结束事件的会话,以及只有完成候选或中断事件的轮次,不计入当天活跃数。工具调用按开始和结束事件数的较大值统计。
## 关闭 Hook
diff --git a/Docs/UserGuide/getting-started.md b/Docs/UserGuide/getting-started.md
index 2afeee1..1478851 100644
--- a/Docs/UserGuide/getting-started.md
+++ b/Docs/UserGuide/getting-started.md
@@ -6,8 +6,8 @@
- macOS 15.0 或更高版本
- 已安装并登录 [Codex CLI](https://github.com/openai/codex),或安装了内置 Codex 的 ChatGPT App 或 Codex App
-- 当前使用的 Codex 版本需要为 `0.143.0` 或更高版本
-- 使用 Hook 相关功能时,当前使用的 Codex 版本需要为 `0.145.0` 或更高版本
+- 当前使用的 Codex 版本需要为 `0.145.0` 或更高版本
+- 使用 Hook 相关功能时,当前使用的 Codex 版本需要为 `0.150.0` 或更高版本
- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户
CodexBar 默认自动选择来源,优先使用全局安装的 Codex CLI,找不到时再尝试 ChatGPT App 和 Codex App 内置的 Codex。可在“设置 > 关于 > Codex 版本 > 来源”中手动选择。
diff --git a/Docs/UserGuide/main-panel.md b/Docs/UserGuide/main-panel.md
index 2e14596..ec79b14 100644
--- a/Docs/UserGuide/main-panel.md
+++ b/Docs/UserGuide/main-panel.md
@@ -89,7 +89,7 @@ CodexBar Hook 开启且当天有数据时,日期详情还会显示以下统计
## 活动卡片
-活动卡片的状态优先级为等待批准、运行中、最近完成、最近终止。
+活动卡片优先显示等待批准,其次是运行中任务。没有活跃任务时,显示结束时间最新的完成或终止记录;时间相同优先显示终止。
卡片会按实际可用字段展示以下内容:
@@ -101,7 +101,7 @@ CodexBar Hook 开启且当天有数据时,日期详情还会显示以下统计
- 其他并发任务数
- 匿名任务图标
-防睡眠实际生效时,活动卡片右侧显示持续旋转的青绿色太阳徽标,悬停可查看防睡眠来源。
+防睡眠实际生效时,活动卡片右侧显示青绿色太阳徽标,悬停可查看防睡眠来源。开启“动画效果”时徽标持续旋转,关闭时静态显示。
无法识别会话的任务带有橙色匿名图标,悬停显示 `匿名任务不参与防睡眠`
@@ -118,7 +118,7 @@ CodexBar Hook 开启且当天有数据时,日期详情还会显示以下统计
- 最近完成
- 最近终止
-最近完成和最近终止记录保留 10 分钟。完成表示一轮任务结束,不代表执行成功;终止表示被中断,不触发完成通知。
+最近完成和最近终止记录保留 10 分钟。完成表示一轮任务结束,不代表执行成功;终止记录包括中断及其他终止情况,不触发完成通知。
## 底部状态
diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.md
index c97a091..8d2989b 100644
--- a/Docs/UserGuide/settings.md
+++ b/Docs/UserGuide/settings.md
@@ -10,6 +10,7 @@
| --- | --- | --- |
| 主面板布局 | 调整账户、任务、额度、用量和状态的顺序与显隐 | 全部显示;Hook 关闭时任务区域关闭 |
| 动画效果 | 打开主面板时播放额度条和热力图动画 | 开启 |
+| 流光效果 | 在各显示器顶部用颜色显示任务状态 | 关闭 |
| 开机自动启动 | 登录 Mac 后启动 CodexBar | 跟随系统登录项状态 |
| 自动检查更新 | 定期检查 CodexBar 更新 | 跟随当前更新设置 |
| 菜单栏额度指示 | 显示所选额度窗口的剩余比例 | 主额度 |
@@ -21,6 +22,21 @@
Hook 关闭时任务区域自动关闭,从关闭切换到开启时自动显示。开启后仍可手动隐藏任务区域,重启 App 会保留这一选择。如果任务是唯一可见区域,关闭 Hook 时账户区域会自动开启。
+### 流光效果
+
+在各显示器顶部显示任务状态,需要 CodexBar Hook 开启且校验通过。此开关默认关闭,与主面板的“动画效果”独立。
+
+| 颜色 | 含义 |
+| --- | --- |
+| 青色往返流光 | 任务运行中 |
+| 橙色呼吸光带 | 等待批准,优先于运行状态 |
+| 绿色 | 任务完成 |
+| 红色 | 任务终止,包括中断 |
+
+并发任务中有任务结束时,显示 3 秒的完成或终止提示,再恢复当前任务状态。全部任务结束后,显示最新结束记录,直到其结束后的 10 秒。
+
+Hook 不可用时隐藏光带并保留开关选择。系统睡眠、屏幕休眠或用户会话不活跃时也会隐藏;恢复后显示当前状态,已过期的结束提示不会重播。
+
### 菜单栏额度指示
选择要显示的额度窗口。关闭后再开启,会恢复上次选择;数据变淡表示显示的是缓存额度。
diff --git a/Docs/UserGuide/sleep-prevention.md b/Docs/UserGuide/sleep-prevention.md
index 22b9ebe..6523d8f 100644
--- a/Docs/UserGuide/sleep-prevention.md
+++ b/Docs/UserGuide/sleep-prevention.md
@@ -10,7 +10,7 @@ CodexBar 可以在任务运行时保持 Mac 唤醒,任务结束或保护条件
2. 开启 `防止系统睡眠` 并确认
3. 如需后台授权,点击 `打开系统设置` 并允许 CodexBar 后台运行
-防睡眠需要 CodexBar 正在运行、Hook 和后台服务可用,并有符合条件的任务。低电量或时长上限触发时会停止,条件恢复后按任务状态重新生效。活动卡片上的旋转太阳徽标表示防睡眠已生效。
+防睡眠需要 CodexBar 正在运行、Hook 和后台服务可用,并有符合条件的任务。低电量或时长上限触发时会停止,条件恢复后按任务状态重新生效。活动卡片上的太阳徽标表示防睡眠已生效。
匿名任务和被异常会话保护隐藏的任务不参与防睡眠。
diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.md
index 610bee7..349c41b 100644
--- a/Docs/UserGuide/troubleshooting.md
+++ b/Docs/UserGuide/troubleshooting.md
@@ -85,7 +85,7 @@
6. 是否正在触发低电量保护
7. 是否已经达到最长防睡眠时间
-旋转太阳徽标只在防睡眠实际生效且活动卡片有可用数据时显示。
+太阳徽标只在防睡眠实际生效且活动卡片有可用数据时显示;关闭“动画效果”后静态显示。
如果设置页显示 `系统睡眠已由其他来源关闭`,CodexBar 不会覆盖该来源。
diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.md
index 8c3ab5d..7e54cfe 100644
--- a/Docs/en/DeveloperGuide/activity-monitor.md
+++ b/Docs/en/DeveloperGuide/activity-monitor.md
@@ -11,7 +11,7 @@ The live-task flow answers four questions:
- Did a recent task complete or terminate?
- Which running tasks have made no progress for too long?
-Hook events provide low-latency signals, and rollout files provide authoritative lifecycle context. [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) merges both into the sole task snapshot:
+Hook events provide live progress and interruption signals, while rollout files supply lifecycle context. [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) merges both into the sole task snapshot:
```text
Hook JSONL -> HookEventTailReader ---------+
@@ -27,10 +27,11 @@ rollout JSONL -> CodexSessionLifecycleReader+
| User-approval candidate | `PermissionRequest` | Rollout reviewer confirmation |
| Turn start | `UserPromptSubmit` | Rollout `startedAt` or historical lookup |
| Completion candidate | `Stop` | Rollout terminal |
-| Completion versus termination | Rollout terminal | Grace-expiration fallback |
+| Explicit turn interruption | `Interrupt` | Rollout terminal |
+| Other terminal resolution | Rollout terminal | Grace-expiration fallback |
| Effort | Hook-recorder lookup | Rollout lifecycle backfill |
-Hook prioritizes low latency; rollout prioritizes semantic accuracy. They do not simply overwrite by timestamp. Every field has its own trusted source.
+Each field is resolved from the sources listed above. Hook polling waits 2 seconds after each read, and rollout polling waits 1 second after each reconciliation round.
### Snapshots and Transitions
@@ -131,7 +132,15 @@ Rules are:
- Parse only lifecycle, turn, progress, effort, and reviewer
- Never read or store conversation content for product presentation
-Hook `Stop` is only a completion candidate. Rollout terminal state distinguishes actual completion, user cancellation, and abnormal termination.
+Hook `Stop` marks the task as “Finishing up” and keeps it active. Tools, approvals, and other progress continue updating the same task. Rollout `task_complete` confirms completion and emits a completion transition.
+
+If rollout is temporarily unreadable or the session or turn cannot be matched, the task continues waiting for reconciliation. `Stop` does not start a terminal timeout. A new turn or `SessionEnd` removes the old task from the active list and opens a five-second terminal-confirmation window. A late `Stop` updates only the pending task's metadata and progress, without restoring its presentation or resetting the deadline.
+
+### Explicit Interruptions
+
+`Interrupt` ends the matching top-level turn, clears protection state and notifications, and stores a termination record. It can match running, approval-waiting, suppressed, and pending-terminal tasks; a newer turn in the same session stays active. Ambiguous matches are ignored.
+
+Hook and rollout terminal signals share deduplication records, retaining the first confirmed completion or termination. Terminations are displayed without triggering completion notifications or haptics.
### Locating Session Files
@@ -179,24 +188,22 @@ Some events contain only session ID. A session key still participates in state,
Without a session ID, only a project key remains. It may merge concurrent anonymous tasks in one project, so anonymous tasks provide reversible UI visibility but cannot drive notifications, sleep prevention, or persisted protection.
-### Auto-review Origin Filtering
-
-`CodexActivityMonitor.apply` checks `WorkflowHookEvent.origin` before any state transition. At construction and decoding boundaries, `WorkflowHookEvent` prefers an explicit origin and uses an exact `model == "codex-auto-review"` match as the `.autoReview` fallback only when that origin is `unknown`. An `autoReview` event never enters the live-task state machine, so it cannot appear in the menu bar, activity card, Task Center, or task counts and cannot produce notifications, haptics, approval waiting, Stalled Task Protection, or sleep-prevention contribution.
-
-Filtering uses the exact `session ID + turn ID` because Codex subagent Hooks reuse the parent session ID. Filtering by session alone would also hide the real main task.
+### Live Task Origin Filtering
-When an exact Auto-review event arrives, the monitor:
+`CodexActivityMonitor.apply` checks `WorkflowHookEvent.origin` before task-state transitions. See [Origin Normalization](hook-and-aggregation.md#origin-normalization) for input classification.
-- Removes the active task and terminal-grace candidate for that key
-- Removes recent completion, recent termination, and terminal-deduplication memory for that key
-- Cancels Stalled Task Protection attempts, persisted records, and pending notifications
-- Remembers the exact key in a 24-hour bounded table so later `unknown` events cannot revive the same task
+The monitor remembers origins in memory for 24 hours by exact `session ID + turn ID`. Codex subagent Hooks reuse the parent session ID, so origin decisions do not apply to an entire session.
-If an explicit `main` or `auxiliary` event later matches the same key, source truth wins and clears that ignored-key inference. An Auto-review event without a turn ID is ignored only for that event and never creates a session-wide blacklist.
+| Event origin | Live processing |
+| --- | --- |
+| `main`, `auxiliary` | Remember the explicit origin and apply normal state-machine rules |
+| `autoReview` | Ignore the event and remove the same key's activity, pending terminals, display records, and stalled-task protection; retain origin memory |
+| `unknown` with a valid remembered `main` or `auxiliary` origin for the same key | Continue processing with the confirmed origin |
+| `unknown` without valid normal-origin memory | Ignore the event |
-Other subagents, including Memories, are classified as `auxiliary` and participate in auxiliary-task association. Raw Hook events still enter historical aggregation; live Auto-review filtering does not change statistics or CloudKit data.
+Events missing a session ID or turn ID do not create origin memory; `unknown` and `autoReview` events are ignored. A task with a confirmed origin survives a temporary rollout read failure. Late events still pass the state machine's timestamp and terminal-deduplication checks.
-A missing or unrecognized JSONL `origin` first decodes as `unknown`. An exact `codex-auto-review` model match normalizes it to `.autoReview`; other records remain `.unknown`. This step uses existing record fields, performs no additional historical rollout scan for origin classification, and does not rewrite raw Hook records.
+These rules apply to bootstrap and live reads. Other subagents, including Memories, are classified as `auxiliary` and follow auxiliary-task association rules. Historical aggregation still consumes all raw events. Origin memory is neither persisted nor uploaded.
### New Prompts and Terminal Grace
@@ -216,10 +223,12 @@ The old turn therefore moves to `pendingTerminalTasks`:
### Rejecting Late Events
-Tasks store `lastActivityAt`, and terminal memory stores completion or termination time:
+Tasks store `lastActivityAt`. Completion and termination share the in-memory `recentlyEndedTaskAt` map of end times. Their display records remain separate and expire after 10 minutes; deduplication memory lasts 24 hours independently. Removing a record through origin filtering recomputes its session alias from the remaining terminal timestamps.
+
+Late events follow these rules:
- An event older than current last activity cannot overwrite newer state
-- A new prompt no later than a remembered terminal cannot revive the old task
+- An exact turn cannot be recreated while terminal memory is retained; session and anonymous keys can be reused only by a newer prompt
- A `Stop` matching several candidates is not guessed
- A key already in terminal deduplication memory clears recovery tasks left by abnormal ordering
@@ -247,12 +256,12 @@ Active tasks mainly use these internal states:
`PermissionRequest` enters `waitingApproval` only when the reviewer is the user. Automatic or policy approval does not count as user waiting.
-Terminal signals reconcile by reliability:
+Task endings are handled by signal:
-- `SessionEnd` ends the session
-- Rollout terminal distinguishes completion from termination
-- `Stop` creates a completion candidate without stronger evidence
-- A new prompt may end the display lifecycle of the old turn
+- `Stop` marks the task as finishing while retaining it in the active list
+- `Interrupt` records the matching turn as terminated
+- Rollout terminal confirms completion or termination
+- A new turn or `SessionEnd` moves the old task into a five-second terminal-confirmation window; expiration without a terminal result records termination, while suppressed tasks only retain deduplication state
### Main Event-to-State Transitions
@@ -263,8 +272,9 @@ Terminal signals reconcile by reliability:
| running | Tool, compact, or subagent progress | running | Update last progress and generation |
| running | `PermissionRequest` + reviewer user | waitingApproval | Publish live waiting transition |
| waitingApproval | New progress | running | Clear pending approval and protection record |
-| running or waiting | `Stop` | terminal candidate | Retain completion or wait for rollout reconciliation |
+| running or waiting | `Stop` | running | Show Finishing up and retain the task until rollout confirms its terminal state |
| active | New prompt or `SessionEnd` | pending terminal | Remove from snapshot and begin 5-second grace |
+| active, suppressed, or pending terminal | `Interrupt` | terminated | Remove the matching task, record termination, and clear protection state and notifications |
| running | Silence exceeds threshold | suppressed | Hide and remove sleep-prevention contribution |
| suppressed | New progress | running | Clear persisted protection and old notification |
@@ -293,16 +303,17 @@ With missing IDs, stop-before-start, or several candidates in one session, the m
The activity card selects content through `primaryActivity` in this order:
```text
-Waiting for approval > Running > Recently completed > Recently terminated > Idle
+Waiting for approval > Running > Latest completion or termination > Idle
```
-The menu bar also prioritizes waiting and running tasks. With no active tasks, it selects the latest completion or termination until 10 seconds after the end timestamp. Task Center retains terminal records for 10 minutes; terminal deduplication memory lasts 24 hours.
+`latestTerminalEvent` selects the latest completion or termination by end time, with termination taking precedence on ties. The activity card, menu bar, and idle task glow share this result. The menu bar uses `primaryActivity` and limits terminal display to 10 seconds after the end timestamp. Task Center retains terminal records for 10 minutes; terminal deduplication memory lasts 24 hours.
The snapshot feeds:
- Menu bar person symbol
- Main-panel task card
- Task Center
+- Task glow, receiving snapshots and new terminal events through `presentationPublisher`
- Notification system
- Sleep-prevention controller
@@ -312,6 +323,12 @@ The monitor checks rollout each second and refreshes at cleanup deadlines.
A candidate snapshot is compared with the current value and published only after structural change. Views format elapsed time from the current clock and do not require per-second mutation of task objects.
+### Presentation Updates
+
+`presentationPublisher` publishes the current snapshot and the batch's still-valid `terminalEvents` for Task Glow. Presentation events include anonymous tasks; notifications use the separate `transitionPublisher`.
+
+History reloads, sleep recovery, and source health changes clear pending events and update `terminalPresentationNotBefore`. Collection pauses during bootstrap, wake reconciliation, and unhealthy source state. Records ending before the recovery boundary do not produce brief indicators; tasks ending after recovery publish normally.
+
### Stable Ordering
Several tasks in one batch can share a timestamp; comparing timestamps alone does not determine their relative order.
@@ -320,7 +337,7 @@ All lists sort by most recent time first and then display UUID string. Stable or
### Cleanup Uses the Nearest Deadline
-The monitor manages terminal grace, activity retention, history retention, terminal deduplication, and protection-record expiration. `StatusItemController` independently manages the 10-second completion or termination indication; its expiration does not republish the activity snapshot.
+The monitor manages terminal grace, activity retention, history retention, terminal deduplication, and protection-record expiration. Menu bar terminal hints and task glow have their expiry managed by `StatusItemController` and `TaskGlowController`, respectively. Hint expiry does not republish activity snapshots.
The cleanup task waits for the nearest future deadline, processes it, then schedules the next.
@@ -454,14 +471,22 @@ These constraints prevent false completion alerts and incorrect release during s
| Generation | Protected asynchronous path |
| --- | --- |
| `tailReaderGeneration` | Reader batch, rollout polling, and prompt backfill |
-| `bootstrapCompletionGeneration` | Asynchronous lifecycle completion after repeated bootstrap attempts |
-| `activityProtectionRecoveryGeneration` | Sleep, wake, and data-source recovery |
+| `bootstrapCompletionGeneration` | Bootstrap lifecycle completion and rollout reconciliation results spanning a bootstrap |
+| `activityProtectionRecoveryGeneration` | Sleep/wake recovery and rollout reconciliation results spanning recovery generations |
| Task `progressGeneration` | Protection candidate during notification grace |
Each answers a different “is this current?” question and cannot become one global counter. A task making progress without a reader change should invalidate only its protection attempt, not the entire reader.
## Suggested Failure-Scenario Tests
+- Continue from a Stop handler, then complete or interrupt, without premature completion notifications
+- Interrupt while a Stop handler is running and confirm one termination record and red hint
+- Keep rollout unreadable for more than five seconds, then recover and confirm completion once
+- Request approval after Stop continuation, then interrupt and clear the waiting task
+- Interrupt running, waiting, and suppressed tasks; verify state, duration, protection cleanup, and no completion notification
+- Deliver Hook and rollout termination in both orders; verify one record and one hint
+- Interrupt an old turn after starting a new one; keep the new turn active
+- Replay duplicate Interrupt and late tool/prompt events without restoring the ended turn
- Starting the app while a task is running shows it through bootstrap without replaying notifications
- Bootstrap retries while files continuously append and eventually obtains a stable boundary
- Three unstable attempts enter degraded state without starting silence evaluation
diff --git a/Docs/en/DeveloperGuide/app-server.md b/Docs/en/DeveloperGuide/app-server.md
index 7be1af3..e060560 100644
--- a/Docs/en/DeveloperGuide/app-server.md
+++ b/Docs/en/DeveloperGuide/app-server.md
@@ -110,7 +110,7 @@ The protocol is line-delimited JSON-RPC. A connection sends `initialize`, then `
```text
Start subprocess
-> initialize(clientInfo)
- -> Validate actual version >= 0.143.0
+ -> Validate actual version >= 0.145.0
-> initialized
-> account/read
-> account/rateLimits/read
@@ -127,14 +127,14 @@ Resolve executable
-> Start Process
-> initialize(clientInfo)
-> Save actual version from userAgent
- -> Validate actual version >= 0.143.0
+ -> Validate actual version >= 0.145.0
-> initialized notification
-> account/read(refreshToken: false)
-> Account exists: commit connection
-> Account missing: close process and return notLoggedIn
```
-A connection enters service state only after the actual version passes the global threshold and both handshake and first account read succeed. A version below `0.143.0` or an unparseable version is treated as unsupported; the half-initialized session closes without further account requests.
+A connection enters service state only after the actual version passes the global threshold and both handshake and first account read succeed. A confirmed version below `0.145.0` returns an unsupported-version error. A missing or unparseable version returns an invalid-response error and cannot trigger Hook removal for an unsupported version. Both cases close the half-initialized session without further account requests.
### Stdout Framing and Response Matching
@@ -411,7 +411,7 @@ Hook settings reuse the app-server flow but maintain independent availability st
- `isOperable` is true only when both are `true`
- A transient RPC failure preserves the last explicit validation result
-Enabling or validating Hook requires the actual app-server version to be at least `0.145.0`.
+Enabling or validating Hook requires the actual app-server version to be at least `0.150.0`.
See [Hook Capture and Historical Aggregation](hook-and-aggregation.md) for the full configuration flow.
@@ -422,7 +422,7 @@ Enabling or validating Hook calls `readyConnectionInfo()`:
- If no connection exists, it establishes one first
- If a connection exists, it reuses the actual current process
- It parses the running version from the handshake user agent
-- An unparseable version is treated as unsupported rather than allowed optimistically
+- An unparseable version rejects the connection without triggering Hook removal for an unsupported version
## Request Logs
@@ -448,9 +448,9 @@ Reset Credits details include opaque credit IDs. Unified logs must not record ID
- Continuous stderr output does not stall requests through pipe backpressure
- A transport failure on a reused connection rebuilds only once
- After an on-disk CLI upgrade, the current connection version remains distinct from the disk version
-- app-server below `0.143.0` blocks the primary account flow and asks for an upgrade
-- app-server `0.143.x` or `0.144.x` supports the primary account flow while Hook still requires `0.145.0`
-- app-server `0.145.0` or later supports both the account flow and Hook validation
+- app-server below `0.145.0` blocks the primary account flow and asks for an upgrade
+- app-server from `0.145.0` up to but excluding `0.150.0` supports the primary account flow while Hook still requires `0.150.0`
+- app-server `0.150.0` or later supports both the account flow and Hook validation
- A failed rate-limit read with same-account cache displays stale data without triggering notifications
- An account switch clears old rate-limit and usage data immediately
- An unsupported method is not retried every minute
diff --git a/Docs/en/DeveloperGuide/architecture.md b/Docs/en/DeveloperGuide/architecture.md
index 9c23622..c99700a 100644
--- a/Docs/en/DeveloperGuide/architecture.md
+++ b/Docs/en/DeveloperGuide/architecture.md
@@ -124,7 +124,7 @@ Three data flows manage distinct inputs, freshness requirements, and failure sta
| --- | --- | --- | --- |
| app-server | `codex app-server` JSON-RPC | Account, rate limits, token usage, Reset Credit use, Hook configuration capabilities | Main panel, menu bar rate limit, Settings, Automatic Reset state machine |
| Hook history | Hook JSONL | Daily event, session, turn, tool, and model aggregations | Activity heatmap, historical metrics, CloudKit |
-| Live tasks | Incremental Hook events plus rollout lifecycle | Running, waiting for approval, completed, terminated | Menu bar status, Task Center, notifications, sleep prevention |
+| Live tasks | Incremental Hook events plus rollout lifecycle | Running, waiting for approval, completed, terminated | Menu bar status, Task Center, task glow, notifications, sleep prevention |
### Dependency Direction
@@ -238,7 +238,7 @@ Before changing one time window, check for paired invariants. For example, the t
| Automatic Reset wake-time synchronization | `AutoResetWakeScheduler` | `AutoResetController` submits only the next time; `KeepAliveController` submits only helper readiness |
| Hook installation and validation | `CodexHookSettings` | Read `isOperable` |
| Historical aggregation and maintenance cursor | `WorkflowService` | Request snapshots or rebuilds |
-| Live tasks | `CodexActivityMonitor` | Read snapshots or transitions |
+| Live tasks | `CodexActivityMonitor` | Read snapshots, notification transitions, or presentation updates containing new terminal events |
| Sync cursors and remote cache | `WorkflowSyncService` | Request merged snapshots |
| Sleep-prevention policy and app assertion | `KeepAliveController` | Read derived state or invoke settings entry points |
| Root sleep ownership | `CodexBarHelper` | Request and query through XPC |
diff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.md
index 35fe5df..74c1deb 100644
--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md
@@ -24,7 +24,7 @@ Raw events are the fact source; daily aggregation is a rebuildable cache. A chan
The enable flow checks the following conditions, validating source, trust, and event completeness after writing:
- A resolvable current executable path
-- Actual app-server version `0.145.0` or later
+- Actual app-server version `0.150.0` or later
- Available `features.hooks`
- A trusted source returned by `hooks/list`
- A complete required event set
@@ -49,7 +49,7 @@ A handler in `hooks.json` does not prove Codex will execute it. `isOperable` com
An enabled Hook is reconciled at app launch, when Settings refreshes, when the main panel opens, and after each quota refresh. Automatic refresh waits 60 seconds after the previous round completes:
-- Only a confirmed running app-server version below the current Hook minimum triggers the normal disable flow, which removes CodexBar handlers and their matching trust entries
+- Only a confirmed running app-server version below the current Hook minimum triggers removal of CodexBar handlers and best-effort cleanup of matching trust entries; versions below the global minimum also trigger local removal
- An unknown version or transient RPC failure preserves the user's configuration
- Configuration lost during the current process does not turn off the switch; CodexBar marks it damaged and starts repair
- A supported version traverses `CodexHookEvent.allCases`, rebuilds a separate group for every missing or noncanonical event, then reuses trust and completeness validation
@@ -61,7 +61,7 @@ Reconciliation compares the required event set with the configuration and restor
### Enable Transaction Order
```text
-Confirm running app-server >= 0.145.0
+Confirm running app-server >= 0.150.0
-> Confirm features.hooks is not globally disabled
-> Read existing hooks.json
-> Remove only old CodexBar handlers for this executable
@@ -80,7 +80,7 @@ An app-server Hook key comes from the handler it currently parsed. Removing the
Disable therefore saves keys for exact matches, removes handlers, then removes those keys from `hooks.state`. Cleanup reads and replaces the complete state so trust entries belonging to users and other tools survive.
-A failed trust cleanup does not reinstall the handler. The UI reports that Hook is off but cleanup is incomplete because the user's intent to stop capture succeeded.
+Below the global minimum, the app-server connection has already been rejected, so disabling directly removes local handlers and preserves trust entries that cannot be queried or deleted, without an additional trust-cleanup warning. In other cases, trust discovery or cleanup failures report that trust cannot be cleared, while Hook remains disabled. Failure to remove local configuration still displays an error and is retried during subsequent reconciliation.
### Event Groups
@@ -109,6 +109,7 @@ CodexBar subscribes to:
| `PreCompact` | Record context-compaction start |
| `PostCompact` | Record context-compaction end |
| `Stop` | Create a task-completion candidate |
+| `Interrupt` | Ends the matching turn and records interruption statistics |
| `SubagentStart` | Record subagent start |
| `SubagentStop` | Record subagent end |
@@ -137,7 +138,7 @@ Timeout depends on event:
| Event | Timeout |
| --- | --- |
-| `SessionEnd` | 3 seconds |
+| `SessionEnd`, `Interrupt` | 3 seconds |
| Other events | 5 seconds |
The lock-wait budget is the handler timeout minus 2 seconds. Lock acquisition starts with 1 ms exponential backoff capped at 20 ms per wait.
@@ -206,7 +207,7 @@ The recorder resolves origin before writing, and the JSONL origin field stores o
When JSONL omits `origin` or contains an unrecognized enum value, the origin field first decodes as `unknown`. The `WorkflowHookEvent` decoder then applies the same exact model fallback, so an event with `model == "codex-auto-review"` has `origin` equal to `autoReview` in memory. Reading never backfills or rewrites raw JSONL.
-Origin classification changes only live-activity filtering, not historical aggregation input. Auto-review events still contribute to session, turn, model, tool, project, and event counts; neither the aggregation schema nor the CloudKit projection contains origin classification.
+Historical aggregation counts all Hook events, including `autoReview` and `unknown` origins. Aggregates and CloudKit projections do not contain an origin field.
### Input Normalization
@@ -350,7 +351,7 @@ Daily results include:
- Project distribution
- Model distribution
-The session count deduplicates nonempty session IDs from all events except `SessionEnd` on that day. The turn count deduplicates nonempty turn IDs from all events except `Stop` on that day. A session or turn spanning multiple days contributes to each day with a nonexcluded event; a session observed only through `SessionEnd` and a turn observed only through `Stop` do not contribute.
+The session count deduplicates nonempty session IDs from all events except `SessionEnd` on that day. The turn count deduplicates nonempty turn IDs from all events except `Stop` and `Interrupt` on that day. A session or turn spanning multiple days contributes to each day with a nonexcluded event; a session observed only through `SessionEnd` and a turn observed only through `Stop` or `Interrupt` do not contribute.
Only one side of a paired event may persist. Counts therefore use rules that avoid duplicates while tolerating missing data:
@@ -363,7 +364,7 @@ A missing field differs from numeric `0`:
- Missing means the historical source cannot provide this metric for the date
- `0` means the source is available and explicitly observed none
-Decoding and persistence retain optional values. The `WorkflowDailyMetrics` display projection converts missing individual event counts to `0`; session and turn counts use deduplicated IDs or compacted counts first, then fall back to corresponding event counts.
+Decoding and persistence retain optional values. The `WorkflowDailyMetrics` display projection preserves a missing `interruptCount` and converts other missing individual event counts to `0`; session and turn counts use deduplicated IDs or compacted counts first, then fall back to corresponding event counts.
### Paired Event Counts
@@ -376,17 +377,15 @@ Decoding and persistence retain optional values. The `WorkflowDailyMetrics` disp
Compaction and subagent pairs follow the same rule.
-### Carrying Availability Through Old Data
+### Count Availability
-Older aggregations may not have a newer Hook count. Rebuild cannot assume that an old source captured an event merely because current code understands it.
+`WorkflowHookCountAvailability` records source availability for each count. Rebuild inherits availability from the existing date's aggregate. Without an aggregate, it uses `.legacy`, where `interruptCount` is unavailable and other event counts start at `0`. Reading an `Interrupt` changes a missing interruption count to a positive value; other events preserve its absence.
-`WorkflowHookCountAvailability` records source availability for each count. Rebuild inherits an existing date's availability for old fields, while a fresh source can declare all current fields available.
-
-This availability is retained in aggregate and sync fields; the current UI does not display missing historical fields individually.
+`interruptCount` remains optional in the display projection. If any contribution for a day lacks it, the total is unavailable. Heatmap details do not display this metric.
## Schema Evolution and Rebuild
-The current aggregation schema is `6`, managed by `WorkflowMaintenanceState.currentAggregationSchema`.
+The current aggregation schema is `9`, managed by `WorkflowMaintenanceState.currentAggregationSchema`.
Increment the schema for:
@@ -433,7 +432,7 @@ Maintenance coordinates with the rate-limit refresh cycle but has no data depend
Maintenance normally follows the 60-second refresh. An idle machine would otherwise emit more than a thousand no-change checks per day.
-`WorkflowService` accumulates consecutive idle cycles and logs one summary only after a write, skip, failure, or cleanup, including the preceding idle count. Logs can prove that maintenance runs without burying real failures.
+`WorkflowService` accumulates consecutive idle cycles and emits a summary on a write, skip, failure, or cleanup, including the accumulated idle count.
### How the Scheduler Coalesces Requests
diff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.md
index 2d5d7b4..3e3015c 100644
--- a/Docs/en/DeveloperGuide/notifications.md
+++ b/Docs/en/DeveloperGuide/notifications.md
@@ -135,9 +135,10 @@ Date classification uses seconds remaining until expiration, with separate dedup
Task notifications respond only to new terminal transitions published by the monitor and never infer them by scanning historical lists:
- Tasks established during bootstrap do not notify
-- The activity monitor retains terminal IDs for 24-hour deduplication
+- The activity monitor retains terminal task keys for 24-hour deduplication
- The notification service also tracks its own sent keys
-- `Stop` and rollout terminal data for the same turn reconcile into one notification
+- `Stop` retains the finishing task; rollout confirmation emits one completion transition
+- `Interrupt` and other termination records do not trigger completion notifications or task haptics
Anonymous tasks are not published to task-notification consumers. The notification service filters `isAnonymous` again at the transition boundary, so anonymous tasks cannot send completion or approval notifications or trigger task haptics.
@@ -169,7 +170,7 @@ Relevance checks both before and after submission cover the asynchronous window.
When a non-anonymous running task reaches its silence threshold, Activity Protection updates its in-memory record and schedules an asynchronous save, then starts notification submission and a 3-second grace period together. After notification handling returns or grace expires, the monitor revalidates the candidate before hiding it. Hiding waits for neither disk commit nor notification success.
-The notification identifier uses `taskID + attemptID`. Checks before and after submission compare progress generation and silence duration. New progress invalidates the protection attempt and withdraws its notification.
+The notification identifier uses `taskID + attemptID`, and relevance is determined by the monitor's current protection attempt. Checks before and after submission validate the attempt ID, progress generation, and silence duration. When the attempt becomes invalid, the notification service removes delivered and pending notifications with that identifier.
Protection notifications use the system default sound and a `retryCount` of `0` to avoid retrying an obsolete candidate.
diff --git a/Docs/en/DeveloperGuide/sync.md b/Docs/en/DeveloperGuide/sync.md
index 00ba3c1..eb4cd80 100644
--- a/Docs/en/DeveloperGuide/sync.md
+++ b/Docs/en/DeveloperGuide/sync.md
@@ -176,7 +176,9 @@ Upload targets follow these rules:
As the CloudKit record schema evolves, an old record may lack a new count field. `nil` means that device cannot provide the metric for that day; `0` means it explicitly observed zero occurrences.
-CloudKit decoding and persisted models preserve optional counts. The current `WorkflowDailyMetrics` display projection converts missing individual event counts to `0`; session and turn counts first fall back to their start or stop event counts, then to `0`. Unavailable daily statistics and a missing individual count are different UI cases.
+CloudKit decoding and persisted models preserve optional counts. Local and remote aggregates share the `WorkflowDailyMetrics` display projection: a missing `interruptCount` stays unavailable, while other missing individual event counts become `0`. Missing session and turn counts fall back to the corresponding start or stop event counts, then to `0`.
+
+CloudKit stores interruption counts in the optional integer field `interruptCount`. If any contribution for a combined date lacks this field, the total interruption count remains unavailable.
## Source Replacement and Rebuild
@@ -219,7 +221,7 @@ Sync state lives at:
| `cache.jsonl` | Cached daily aggregates from remote devices |
| `cursor.data` | CloudKit zone change token |
-The current CloudKit record schema is `5`. The local sync-state schema is `4` and can read the previous schema `3`.
+The current CloudKit record schema is `6`. The local sync-state schema is `4` and can read the previous schema `3`.
The three files have different recovery costs:
@@ -293,6 +295,7 @@ Transient errors preserve the last usable remote cache. After account switching
- First enable uploads local aggregations within retention
- A second device merges contributions without duplicating the current device
+- Merging device records with and without `interruptCount` preserves its unavailable state
- Disabling sync shows local metrics only
- When iCloud is signed out, the app shows a clear state and local metrics keep working
- After network loss, the app uses the last cache and completes incremental sync on recovery
diff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
index bd47ee9..4085221 100644
--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
@@ -37,6 +37,7 @@ Create settings, data services, view models, and updater
-> Reconcile Hook and start periodic refresh
-> Start notifications and automatic reset
-> Connect Activity Protection callbacks
+ -> Start the task-glow subscription
-> Start the activity monitor and keep-alive coordination
```
@@ -44,6 +45,20 @@ Notifications and sleep prevention consume only snapshots or transitions already
Shutdown reverses the order, except for helper-owned system state. AppDelegate first confirms asynchronously that the Automatic Reset wake schedule is canceled and the sleep-prevention lease is released, then allows process termination. See [Sleep Prevention System](sleep-prevention.md) for the transaction.
+## Task Glow
+
+`TaskGlowController` presents activity while both `TaskGlowSettings.isEnabled` and Hook's `isOperable` are `true`, independently of the main panel's animation setting. It consumes snapshots and terminal events from `CodexActivityMonitor.presentationPublisher`; see [Presentation Updates](activity-monitor.md#presentation-updates).
+
+| Scenario | Presentation rule |
+| --- | --- |
+| Active tasks exist | Orange approval waiting takes priority over cyan running |
+| A task ending is confirmed while others remain active | The latest event overrides activity for 3 seconds, fading during the final 0.5 seconds; a new event replaces it and restarts the timer |
+| No active tasks | The snapshot's latest terminal state remains until 10 seconds after its end time, fading during the final second |
+
+Completion is green and termination is red, with termination taking priority on equal end times. Durations include entrance animations. The latest snapshot determines the state after expiration.
+
+The glow uses nonactivating, mouse-transparent `NSPanel` windows across Spaces and full-screen apps. System sleep, display sleep, or an inactive user session removes the windows. On return, valid state resumes according to the current time. Screen configuration changes rebuild the windows; all displays share a motion clock.
+
## Status Bar Icon
The status icon combines app-server loading state, the menu bar rate-limit setting, and the task-activity snapshot.
@@ -93,7 +108,7 @@ Operations follow these rules:
- Toggling in `opening` or `shown` starts closing
- Toggling in `closing` finishes the old close, then opens a new surface
-- Starting a close cancels delayed refresh and old animations
+- Starting a close cancels the pending fade-in completion task
- A nonanimated close completes state cleanup immediately
`activeMenuSurface` identifies the current container as `none`, `popover`, or `fallbackPanel`. An explicit container close sets it to `none` before closing the window.
@@ -134,7 +149,7 @@ When host animation permission is disabled, `CodexStatusMenuView` sets the root
### Activity Card
-`CodexActivityCard` uses `primaryActivity`, prioritizing waiting for approval, running, recently completed, and recently terminated tasks. When `isActivelyPreventingSleep` is `true` and card data is available, it shows a teal `sun.max.fill`. While the host's `mainPanelAnimationsEnabled` is true, a separate rotating view uses linear animation for one clockwise revolution every 2 seconds, without the system symbol effect's acceleration phase. Disabling permission removes the rotating view and restores a static icon. Reopening restores rotation only when Animation Effects is enabled. Popover and fallback hosts control their animations independently. The tooltip identifies `sleepPreventionSource`.
+`CodexActivityCard` uses `primaryActivity`, prioritizing waiting for approval, then running, then the latest completion or termination by end time, with termination taking precedence on ties. When `isActivelyPreventingSleep` is `true` and card data is available, it shows a teal `sun.max.fill`. While the host's `mainPanelAnimationsEnabled` is true, a separate rotating view uses linear animation for one clockwise revolution every 2 seconds, without the system symbol effect's acceleration phase. Disabling permission removes the rotating view and restores a static icon. Reopening restores rotation only when Animation Effects is enabled. Popover and fallback hosts control their animations independently. The tooltip identifies `sleepPreventionSource`.
## Fallback Panel
@@ -173,6 +188,8 @@ Heatmap squares enter with staggered delays based on their column and row. With
The heatmap detail panel uses the complete heatmap area, including its heading, date range, and square grid, as its vertical anchor. Reordering main-panel sections therefore still keeps their top edges aligned whenever possible. If the detail panel would extend below the main panel from that position, placement shifts it upward until their bottom edges align.
+While the main panel is visible, digits roll as values change and Token values fade when switching to or from pending or unavailable placeholders. Animation Effects controls entrance animations and sun-badge rotation; it does not control numeric updates.
+
Related controllers include:
- [`HeatmapDetailPanelController.swift`](../../../CodexBar/Controllers/HeatmapDetailPanelController.swift)
@@ -256,13 +273,13 @@ Registration uses try-before-swap:
## Automatic Refresh and Panel Opening
-App-server state is checked for refresh every 60 seconds by default. About 160 ms after the main panel opens, `refreshIfNeeded` requests data if no countdown origin exists or more than 60 seconds have passed since the last refresh result was committed. Both successful and failed results reset the countdown; this check can occur before fade-in finishes.
+App-server state is checked for refresh every 60 seconds by default. Once the main panel's 0.24-second fade-in finishes and the panel is still visible, `refreshIfNeeded` requests data if no countdown origin exists or more than 60 seconds have passed since the last refresh result was committed. Both successful and failed results reset the countdown.
The main panel shows a refresh countdown. Double-clicking the account icon requests an immediate manual refresh.
Ordinary refreshes are ignored while a refresh or reconnect is in progress. Operations requiring a follow-up use `refreshAfterCurrent` to retain one pending trigger and run it after the current request finishes.
-Opening the panel immediately reconciles Hook configuration and requests local statistics when Hook is enabled. The delayed task only checks whether account, rate-limit, and usage data need refreshing; closing the panel cancels it.
+The fade-in completion callback triggers Hook configuration reconciliation, a local-statistics refresh check when Hook is enabled, and an account, rate-limit, and usage refresh check in that order. Closing the panel before fade-in finishes cancels the completion task and its pending refresh work.
## Localization and Formatting
@@ -284,6 +301,8 @@ Release scripts require Developer ID, signing, and notarization credentials and
## Manual Validation Matrix
- Left-click opens the main panel; right-click and Control-click open the context menu
+- During concurrent running or approval waiting, completion and termination trigger a 3-second glow indicator; consecutive endings and the end of all tasks use the correct color and expiration
+- History reloads and wake reconciliation do not replay old terminal hints; subsequent real task endings still produce hints, and motion and expiry stay aligned across displays and screen configuration changes
- Menu bar symbols follow task state; terminal feedback expires 10 seconds after the task ends and is recalculated on wake
- Transitions between the plain person and all four task badges complete correctly, rapid changes settle on the latest state, and toggling quota visibility stays smooth with badges; initial presentation and wake reconciliation do not animate
- Quota-arc visibility animates, zero quota retains the track, and cached quota dims
@@ -304,6 +323,7 @@ Release scripts require Developer ID, signing, and notarization credentials and
- On multiple displays and with different menu bar locations, the fallback panel appears on the pointer's screen
- The old shortcut still works after a new shortcut conflicts
- Panel-open refresh does not stall animation or issue duplicate requests
+- Initial numeric decreases, consecutive changes, Token unit changes, and month boundaries roll in the correct direction; numeric animations stop when the main panel closes
## Key Source Files
diff --git a/Docs/en/UserGuide/activity-and-hook.md b/Docs/en/UserGuide/activity-and-hook.md
index 2ad4d64..37d304d 100644
--- a/Docs/en/UserGuide/activity-and-hook.md
+++ b/Docs/en/UserGuide/activity-and-hook.md
@@ -10,9 +10,9 @@ CodexBar Hook provides live task status, task notifications, haptics, task-based
2. Enable `CodexBar Hook` and wait for validation
3. Start a Codex task and check its status in the main panel
-Hook requires the Codex currently in use to be `0.145.0` or later. If the version warning remains after upgrading, click `Reconnect` in `Settings > About`. For other errors, see [Troubleshooting](troubleshooting.md#codexbar-hook-cannot-be-enabled-or-validated).
+Hook requires the Codex currently in use to be `0.150.0` or later. If the version warning remains after upgrading, click `Reconnect` in `Settings > About`. For other errors, see [Troubleshooting](troubleshooting.md#codexbar-hook-cannot-be-enabled-or-validated).
-CodexBar automatically checks and repairs enabled Hook configuration. Enabling or disabling it preserves Hooks belonging to you and other apps.
+CodexBar automatically checks and repairs enabled Hook configuration, preserving handlers belonging to users and other apps. If Codex is confirmed to be below the minimum version, Hook is disabled and CodexBar removes its handlers; enable Hook again after upgrading Codex. Configuration is retained for the next check if the connection or version is temporarily unavailable.
## Task States
@@ -21,11 +21,15 @@ CodexBar automatically checks and repairs enabled Hook configuration. Enabling o
| Running | Codex is processing the task |
| Waiting for Approval | You need to approve the next action |
| Recently Completed | A turn ended; its result is not necessarily successful |
-| Recently Terminated | The task was interrupted; no completion notification is sent |
+| Recently Terminated | An interruption or other terminal signal confirmed termination; no completion notification is sent |
-Subagent activity is combined with its parent task. Internal automatic-review tasks do not appear separately or trigger task alerts or sleep prevention; their activity still contributes to daily statistics.
+After `Stop`, the task first shows “Finishing up”. A completion notification is sent after the turn is confirmed complete and the notification settings are satisfied. If another Hook continues the task, progress keeps updating; an interruption during that time is shown as terminated.
-Tasks whose session cannot be identified show an orange anonymous icon. You can view them, but they do not trigger notifications or haptics, prevent sleep, or participate in Stalled Task Protection.
+Interruption ends only the matching turn; a newer turn in the same session stays active. Task-based sleep prevention releases once all eligible tasks end.
+
+Subagent activity is combined with its parent task. Internal automatic-review tasks and tasks whose origin remains unconfirmed do not appear as live tasks or trigger Task Glow, task alerts, or sleep prevention; their activity still contributes to daily statistics. Once the same session and turn have been confirmed as a normal task, later events with a temporarily unknown origin continue updating its state.
+
+Tasks with a known origin whose session cannot be identified show an orange anonymous icon. You can view them, but they do not trigger notifications or haptics, prevent sleep, or participate in Stalled Task Protection.
[Stalled Task Protection](sleep-prevention.md#stalled-task-protection) may hide running tasks that stop making progress. They reappear when progress resumes.
@@ -33,7 +37,7 @@ Tasks whose session cannot be identified show an orange anonymous icon. You can
Hover over a day in the main panel heatmap to view sessions, turns, tool calls, permission requests, context compactions, subagents, and the most-used model.
-Sessions and turns are deduplicated within each day; activity continuing into another day counts toward that day. Paired records such as tool-call events may be incomplete, so statistics reflect the activity CodexBar actually observed.
+Sessions and turns are deduplicated within each day; activity continuing into another day counts toward that day. Sessions with only a session-end event and turns with only completion-candidate or interruption events do not count as active that day. Tool calls use the larger of the start and end event counts.
## Disable Hook
diff --git a/Docs/en/UserGuide/getting-started.md b/Docs/en/UserGuide/getting-started.md
index d1d13f8..1d8e505 100644
--- a/Docs/en/UserGuide/getting-started.md
+++ b/Docs/en/UserGuide/getting-started.md
@@ -6,8 +6,8 @@
- macOS 15.0 or later
- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed
-- The Codex currently in use must be `0.143.0` or later
-- Hook features require the Codex currently in use to be `0.145.0` or later
+- The Codex currently in use must be `0.145.0` or later
+- Hook features require the Codex currently in use to be `0.150.0` or later
- Cross-device sync requires an available iCloud account on the Mac
By default, CodexBar automatically prefers a globally installed Codex CLI. If it cannot find one, it tries the Codex bundled with ChatGPT App and Codex App. You can select a source under Settings > About > Codex Versions > Source.
diff --git a/Docs/en/UserGuide/main-panel.md b/Docs/en/UserGuide/main-panel.md
index 9a705b2..e523ea5 100644
--- a/Docs/en/UserGuide/main-panel.md
+++ b/Docs/en/UserGuide/main-panel.md
@@ -89,7 +89,7 @@ When CodexBar Hook is enabled and data exists for that day, the details also inc
## Activity Card
-Activity-card states are prioritized as waiting for approval, running, recently completed, then recently terminated.
+The activity card prioritizes tasks waiting for approval, then running tasks. With no active tasks, it shows the latest completion or termination by end time, with termination taking precedence on ties.
The card shows the following fields when available:
@@ -101,7 +101,7 @@ The card shows the following fields when available:
- Number of other concurrent tasks
- Anonymous-task icon
-While sleep prevention is active, a teal sun badge rotates continuously on the right side of the activity card. Hover over it to see the sleep-prevention source.
+While sleep prevention is active, a teal sun badge appears on the right side of the activity card. Hover over it to see the sleep-prevention source. The badge rotates while Animation Effects is enabled and stays static when it is disabled.
Tasks whose session cannot be identified show an orange anonymous icon with the tooltip `Anonymous tasks do not prevent sleep`.
@@ -118,7 +118,7 @@ Task Center groups tasks into:
- Recently Completed
- Recently Terminated
-Recently completed and terminated records remain for 10 minutes. Completion means a turn ended, without implying success. Termination means it was interrupted and does not trigger a completion notification.
+Recently completed and terminated records remain for 10 minutes. Completion means a turn ended, without implying success. Termination records include interruptions and other task terminations, and do not trigger completion notifications.
## Footer Status
diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.md
index f858152..0fa1bd3 100644
--- a/Docs/en/UserGuide/settings.md
+++ b/Docs/en/UserGuide/settings.md
@@ -10,6 +10,7 @@ Right-click or Control-click the menu bar icon and choose `Settings`, or press `
| --- | --- | --- |
| Main Panel Layout | Reorder and show or hide Account, Tasks, Quota, Usage, and Status | All visible; Tasks is off when Hook is disabled |
| Animation Effects | Animate quota bars and the heatmap when opening the panel | On |
+| Glow Effect | Show task status with colors along the top of each display; requires Hook to be enabled and verified | Off |
| Launch at Login | Start CodexBar when you sign in to your Mac | Follows the system login-item state |
| Automatically Check for Updates | Periodically check for CodexBar updates | Follows the current update setting |
| Menu Bar Quota Indicator | Show the remaining allowance in a selected window | Primary quota |
@@ -21,6 +22,21 @@ Click the options button to drag sections into order or toggle visibility, keepi
Disabling Hook hides Tasks; switching Hook from off to on shows Tasks automatically. You can still hide Tasks manually while Hook is enabled, and restarting the app preserves that choice. If Tasks was the only visible section, disabling Hook enables Account automatically.
+### Glow Effect
+
+Shows task status along the top of each display. CodexBar Hook must be enabled and verified. The switch is off by default and independent of the main panel's Animation Effects setting.
+
+| Color | Meaning |
+| --- | --- |
+| Cyan moving glow | Tasks are running |
+| Orange pulsing glow | Waiting for approval; takes priority over running |
+| Green | Task completed |
+| Red | Task terminated, including interruptions |
+
+When a task ends while others remain active, its completion or termination appears for 3 seconds before returning to the current task state. Once all tasks end, the latest ending is shown until 10 seconds after its end time.
+
+The glow is hidden while Hook is unavailable, preserving your switch preference. System sleep, display sleep, or an inactive user session also hides it. On return, it shows the current state without replaying expired terminal indicators.
+
### Menu Bar Quota Indicator
Choose the quota window to display. Turning the indicator off and back on restores the last choice. Faded data indicates cached quota.
diff --git a/Docs/en/UserGuide/sleep-prevention.md b/Docs/en/UserGuide/sleep-prevention.md
index d86db8a..cc6c229 100644
--- a/Docs/en/UserGuide/sleep-prevention.md
+++ b/Docs/en/UserGuide/sleep-prevention.md
@@ -10,7 +10,7 @@ CodexBar can keep your Mac awake while tasks run and restore sleep when tasks fi
2. Enable `Prevent System Sleep` and confirm
3. If background approval is required, click `Open System Settings` and allow CodexBar to run in the background
-Sleep prevention requires CodexBar to be running, Hook and its background service to be available, and an eligible task to exist. Low battery or the duration limit stops it; when conditions recover, task state determines whether it resumes. The rotating sun badge on the activity card indicates that sleep prevention is active.
+Sleep prevention requires CodexBar to be running, Hook and its background service to be available, and an eligible task to exist. Low battery or the duration limit stops it; when conditions recover, task state determines whether it resumes. The sun badge on the activity card indicates that sleep prevention is active.
Anonymous tasks and tasks hidden by Stalled Task Protection do not prevent sleep.
diff --git a/Docs/en/UserGuide/troubleshooting.md b/Docs/en/UserGuide/troubleshooting.md
index e113787..023265d 100644
--- a/Docs/en/UserGuide/troubleshooting.md
+++ b/Docs/en/UserGuide/troubleshooting.md
@@ -85,7 +85,7 @@ Check in this order:
6. Low Battery Protection is not active
7. The Keep-Awake Limit has not been reached
-The rotating sun badge appears only while sleep prevention is active and activity-card data is available.
+The sun badge appears only while sleep prevention is active and activity-card data is available. It stays static when Animation Effects is disabled.
If Settings says `System sleep is disabled by another source`, CodexBar does not overwrite that source.
diff --git a/README.en.md b/README.en.md
index 7b25061..14cad42 100644
--- a/README.en.md
+++ b/README.en.md
@@ -48,6 +48,7 @@ It can notify you when a task finishes, needs approval, or when your rate limits
- The main panel shows the current task, project, model, reasoning effort, and elapsed time
- Task Center brings concurrent, recently completed, and recently terminated tasks together
- Receive alerts for completed tasks, approval requests, and stalled tasks
+- Optional task glow along the top of each display shows running, waiting, completed, and terminated states
### Let long-running tasks finish
@@ -80,8 +81,8 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy
- macOS 15.0 or later
- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed
-- The running Codex version must be `0.143.0` or later
-- Live tasks and other Hook features require the running Codex version to be `0.145.0` or later
+- The running Codex version must be `0.145.0` or later
+- Live tasks and other Hook features require the running Codex version to be `0.150.0` or later
- Cross-device sync requires an available iCloud account on the Mac
## Quick Start
diff --git a/README.md b/README.md
index 7d4afce..0f08247 100644
--- a/README.md
+++ b/README.md
@@ -48,6 +48,7 @@ CodexBar 是面向 macOS 15 及更高版本的菜单栏 App,用于集中展示
- 主面板展示当前任务、项目、模型、推理强度和持续时间
- 任务中心集中查看并发任务、最近完成和最近终止记录
- 支持任务完成、等待批准和异常会话提醒
+- 可在各显示器顶部显示任务流光,用颜色提示运行、等待、完成和终止
### 让长任务安心运行
@@ -80,8 +81,8 @@ brew install --cask bob-zebedy/tap/codexbar
- macOS 15.0 或更高版本
- 已安装并登录 [Codex CLI](https://github.com/openai/codex) 或安装了内置 Codex 的 ChatGPT App 或 Codex App
-- 当前运行的 Codex 版本需要为 `0.143.0` 或更高版本
-- 使用实时任务等 Hook 功能时,当前运行的 Codex 版本需要为 `0.145.0` 或更高版本
+- 当前运行的 Codex 版本需要为 `0.145.0` 或更高版本
+- 使用实时任务等 Hook 功能时,当前运行的 Codex 版本需要为 `0.150.0` 或更高版本
- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户
## 快速开始
diff --git a/Scripts/performance/.gitignore b/Scripts/performance/.gitignore
new file mode 100644
index 0000000..c18dd8d
--- /dev/null
+++ b/Scripts/performance/.gitignore
@@ -0,0 +1 @@
+__pycache__/
diff --git a/Scripts/performance/README.md b/Scripts/performance/README.md
index 5b2cc50..2d89a4e 100644
--- a/Scripts/performance/README.md
+++ b/Scripts/performance/README.md
@@ -1,179 +1,125 @@
-# App 性能测试与报告
+# 性能测试使用说明
-通过 Instruments 采集运行中 macOS App 主进程的 CPU、调用栈、内存、线程、唤醒、磁盘活动和热状态,自动生成单文件 HTML 报告。默认测试 `/Applications/CodexBar.app`,通过 `--app` 可指定其他 App。
+## 开始测试
-## 快速开始
-
-准备好以下环境:
-
-- macOS、完整 Xcode、Python `3.11+`
-- `xcode-select -p` 指向 Xcode 的 `Contents/Developer` 目录
-- 被测 App 已启动,终端具备 Instruments 采集权限
+准备 macOS、完整 Xcode 和 Python `3.11+`,启动待测试的 App。`xcode-select -p` 应指向 Xcode 的 `Contents/Developer` 目录,终端需具备 Instruments 采集权限。
在仓库根目录运行:
```sh
-python3 -B Scripts/performance/run.py --preset standard
+python3 -m Scripts.performance --preset quick
```
-脚本完成预检、预热、分阶段采集、数据解析和报告生成,结束后在终端打印 `report.html` 路径。采集直接附加到现有 App 进程。按 `Ctrl-C` 可停止采集并保存已有结果,App 继续运行。
-
-默认输出目录为 `Build/Performance/YYYYMMDD-HHMMSS`。`Scripts/build.sh` 会清理 `Build`,需要长期保留的结果请指定其他目录:
+默认测试 `/Applications/CodexBar.app`。采集期间按测试场景操作 App,用 `--workload` 记录操作内容:
```sh
-python3 -B Scripts/performance/run.py \
+python3 -m Scripts.performance \
--preset standard \
- --output PerformanceResults/idle-01 \
- --workload '闲置:面板关闭,无手动操作,接通电源'
+ --workload '反复打开面板、切换页面和滚动列表'
```
-采集输出目录必须尚未存在。测试期间保持单个 Instruments 采集任务,并将构建等高负载工作安排在采集结束后。
-
-## 选择测试时长
-
-| 预设 | 预热 | CPU 采集 | 资源观察 | 后续观察 | 累计采集 |
-|---|---:|---:|---:|---:|---:|
-| `quick` | 5 秒 | 2 × 30 秒 | 90 秒 | 30 秒 | 3 分钟 |
-| `standard` | 20 秒 | 4 × 60 秒 | 300 秒 | 60 秒 | 10 分钟 |
-| `extended` | 30 秒 | 5 × 120 秒 | 900 秒 | 300 秒 | 30 分钟 |
+完成后打开终端打印的 `performance.html` 路径查看报告。
-- `quick`:检查采集流程,快速观察操作时的资源变化
-- `standard`:日常性能评估,观察重复采样与后台活动
-- `extended`:观察更长时间的内存变化和周期性任务
+## 测试时长
-累计采集不含预热时间。实际运行时间还包括 Instruments 初始化、保存和导出。`cpu-*` 阶段使用 `Time Profiler + Activity Monitor`,同时采集调用栈、资源指标和 Hangs;`soak`、`settle` 阶段使用 `Activity Monitor` 继续观察资源变化。
+| 预设 | 采集时长 | 用途 |
+|---|---:|---|
+| `quick` | 3 分钟 | 快速检查 |
+| `standard` | 10 分钟 | 日常测试,默认预设 |
+| `extended` | 30 分钟 | 长时间观察 |
-后续观察阶段不会自动停止工作负载。若要观察操作后的恢复情况,需要手动停止操作并记录时间。
-
-## 组织测试场景
-
-采集和报告由脚本自动执行,界面操作由测试者执行。用 `--workload` 记录场景、操作步骤、活动任务和电源状态。
-
-| 场景 | 执行方式 | 重点观察 |
-|---|---|---|
-| 闲置 | 关闭面板,保持后台设置一致,采集期间不手动操作 | CPU 常态与突增、唤醒频率、内存基线 |
-| 高频操作 | 按固定顺序反复打开面板、切换页面和滚动列表 | 主线程热点、CPU 峰值、Hangs、内存峰值 |
-| 操作后闲置 | 记录停止操作的时间,随后保持面板关闭 | CPU 回落、内存释放、后台活动 |
-
-比较两个版本时,使用相同的预设和操作步骤,并记录各次结果。比较闲置与高频操作时,分别保存报告,按阶段查看差异。
+时长为各阶段的计划采集时间之和,不含预热、Instruments 启停和数据导出;实际运行时间更长。
## 参数
-| 参数 | 用途 |
+| 参数 | 用法 |
|---|---|
-| `--app` | 被测 App 路径,默认 `/Applications/CodexBar.app` |
-| `--pid` | 指定进程;存在多个匹配实例时使用 |
-| `--preset` | `quick`、`standard` 或 `extended`,默认 `standard` |
-| `--output` | 采集模式指定新目录;`--render` 模式指定 HTML 文件路径 |
-| `--workload` | 写入报告的测试场景说明 |
-| `--baseline` | 指定同场景历史 `results.json`,采集后计算阶段差值 |
-| `--cpu-mean-budget` | 各阶段平均 CPU 上限,单位为 `%` |
-| `--footprint-budget` | 各阶段内存 footprint 峰值上限,单位为 `MiB` |
-| `--render` | 从已有 JSON 生成 HTML |
-
-例如,将平均 CPU 上限设为 `5%`、内存峰值上限设为 `512 MiB`:
+| `--app PATH` | App 路径,默认 `/Applications/CodexBar.app` |
+| `--pid PID` | 指定待测试进程,存在多个 App 实例时使用 |
+| `--preset NAME` | 选择 `quick`、`standard` 或 `extended` |
+| `--output PATH` | 采集时指定新目录,重新生成报告时指定 HTML 文件 |
+| `--workload TEXT` | 记录测试场景说明 |
+| `--baseline PATH` | 指定基线 `performance.json` |
+| `--cpu-mean-budget NUMBER` | 各阶段平均 CPU 上限,单位为 `%` |
+| `--footprint-budget NUMBER` | 各阶段 Footprint 峰值上限,单位为 `MiB` |
+| `--render PATH` | 从指定 JSON 重新生成报告 |
+| `-h`、`--help` | 查看命令帮助 |
+
+## 输出位置
+
+默认输出到仓库根目录下的 `Performance/YYYYMMDD/HHMMSS-{preset}/`,日期和时间取测试启动时的本地时间。例如:
+
+```text
+Performance/20260912/103000-quick/
+├── performance.html
+├── performance.json
+├── schemas.json
+├── tool-source/
+├── *.trace
+├── *.xml
+└── *.log
+```
+
+`performance.html` 用于查看报告,`performance.json` 用于基线比较和重新生成报告,`*.trace` 可用 Instruments 打开。目录内同时保存采样 XML、命令日志和工具源码快照。
```sh
-python3 -B Scripts/performance/run.py \
- --cpu-mean-budget 5 \
- --footprint-budget 512
+python3 -m Scripts.performance --preset quick --output Performance/idle-01
```
-上限值须为有限正数。脚本逐阶段检查预算,超出项写入报告。
+## 基线比较
-## 阅读报告
+先采集基线:
-报告按数据总览、阶段对比、唤醒与磁盘、运行曲线、CPU 热点、事件与热状态、采集记录组织。
+```sh
+python3 -m Scripts.performance \
+ --preset quick \
+ --output Performance/idle-01
+```
-| 数据 | 图表与读数方式 |
-|---|---|
-| CPU、footprint、RSS、压缩内存 | 分别绘制趋势图;同一指标各阶段共用纵轴,标注峰值 |
-| 线程数量 | 阶梯图 |
-| 内存最小值、中位数、峰值 | 区间图 |
-| 内存首尾窗口中位数 | 哑铃图,标注增减量 |
-| 主线程采样占比 | 百分比堆叠条 |
-| 调用栈热点 | 按采样权重排列的横向条形图 |
+再次测试时指定基线文件:
+
+```sh
+python3 -m Scripts.performance \
+ --preset quick \
+ --baseline Performance/idle-01/performance.json
+```
-趋势图支持鼠标游标和键盘滑块读数,采样间隔超过 5 秒时断开连线。报告支持深浅主题、展开热点、导出 JSON 和打印,可离线打开。中文使用苹果系统字体,英文和数字使用本机安装的 `MesloLGS NF`。
+两个报告均完整,且应用标识、格式、测试配置与环境条件匹配时,报告计算各阶段的 CPU 均值和 Footprint 中位数差值;条件不匹配时列出原因。
-### 指标含义
+CPU 使用 Instruments 导出的 `cpu-percent`,均值按同一采样行的 `duration` 加权;报告总均值按各阶段有效 CPU 采样时长加权。P50、P95 和峰值基于有效采样值计算,缺失值不计为零。CPU 采样覆盖率为有效区间总时长除以完整采样区间跨度。
-- **CPU**:累计 CPU 时间增量除以观测时长,`100%` 表示占用一个逻辑核心。平均值按有效观测时长加权,P50、P95 为区间 CPU 使用率样本的线性插值分位数,峰值为区间使用率最大值
-- **内存**:分别展示 physical footprint、RSS 和压缩内存,单位为 `MiB`。趋势斜率由阶段样本作最小二乘拟合,单位为 `MiB/min`。首尾窗口长度取 60 秒与阶段跨度四分之一中的较小值
-- **唤醒与磁盘**:累计计数取阶段末值减去初值,平均速率除以阶段资源观测时长
-- **CPU 热点**:按调用栈采样权重统计,单位为 `ms`。叶节点表示栈顶函数,调用链权重包含子调用,同一调用栈中的递归符号计一次
-- **Hangs**:按导出的事件计数,检测配置保存在阶段数据的 `hang_settings` 中。空表记为 `0`,缺失数据展示为 `N/A`
-- **App 文件指纹**:被测 App 主可执行文件的 SHA-256;`Mach-O UUID` 标识各架构二进制,用于匹配 dSYM
+## 性能预算
-### 与历史结果比较
+将平均 CPU 上限设为 `5%`,Footprint 峰值上限设为 `512 MiB`:
```sh
-python3 -B Scripts/performance/run.py \
- --preset standard \
- --output PerformanceResults/idle-02 \
- --workload '闲置:面板关闭,无手动操作,接通电源' \
- --baseline PerformanceResults/idle-01/results.json
+python3 -m Scripts.performance \
+ --cpu-mean-budget 5 \
+ --footprint-budget 512
```
-脚本核对 App 的 bundle ID、系统、芯片、架构、核心数、内存容量、电源来源、Instruments、场景说明、预设、预算、数据格式和阶段计划。两次采集均完整且上述条件一致时,报告展示各阶段平均 CPU 差值和 footprint 中位数差值;条件不匹配时列出差异字段。App 版本可以不同。
-
-基线必须使用相同的阶段计划;轮次或时长不同会标记为条件不匹配。
-
-## 输出文件与重新生成报告
+预算值须为有限正数。超限阶段会写入报告。
-| 文件 | 内容 |
+| 退出码 | 含义 |
|---|---|
-| `report.html` | 内嵌样式、图表、交互脚本和统计 JSON 的报告 |
-| `results.json` | 完整统计结果、采集状态、命令及日志索引 |
-| `schemas.json` | 当前 Xcode 的 XML 列定义 |
-| `tool-source/` | 采集启动时的工具源码快照,文件哈希保存在 `results.json` |
-| `*.trace` | 可用 Instruments 打开的原始记录 |
-| `*-toc.xml`、各 schema 的 XML | trace 目录信息与导出的采样数据 |
-| `*.log` | 各条采集、导出命令的日志 |
+| `0` | 采集完成且预算检查通过,或重新生成报告成功 |
+| `1` | 重新生成报告时,读取、解析 JSON 或生成 HTML 失败 |
+| `2` | 参数错误,或采集及结果保存失败 |
+| `3` | 采集完成,存在预算超限 |
+| `130` | 用户中止采集 |
+
+## 重新生成报告
-修改报告模板后,用已有结果重新生成 HTML:
+从已有 JSON 重新生成 HTML 报告:
```sh
-python3 -B Scripts/performance/run.py \
- --render PerformanceResults/idle-01/results.json
+python3 -m Scripts.performance --render Performance/idle-01/performance.json
```
-默认更新 JSON 同目录的 `report.html`。指定另一个文件可保留原报告:
+默认更新 JSON 同目录的 `performance.html`。使用 `--output` 指定另一个 HTML 文件:
```sh
-python3 -B Scripts/performance/run.py \
- --render PerformanceResults/idle-01/results.json \
- --output PerformanceResults/idle-01/report-updated.html
+python3 -m Scripts.performance \
+ --render Performance/idle-01/performance.json \
+ --output Performance/idle-01/performance-updated.html
```
-
-报告页面导出的统计 JSON 也可传给 `--render`。
-
-## 采集检查与排错
-
-阶段有效须满足以下条件:
-
-- 被测可执行文件、PID 和进程启动时间保持一致
-- 记录成功,时长达到计划的 `90%`
-- 至少 3 个资源样本,资源观测跨度达到计划的 `80%`
-- 最大资源采样间隔不超过 5 秒
-- CPU 计数覆盖率至少 `95%`,累计计数不回退
-- 成功取得 footprint;CPU 阶段成功解析 `time-profile` 表
-
-| 退出码 | 含义 |
-|---|---|
-| `0` | 采集完整,已配置的预算检查通过 |
-| `2` | 参数、环境、采集、解析、质量检查或结果保存失败 |
-| `3` | 采集完整,超过配置预算 |
-| `130` | 操作者中断采集 |
-
-根据终端输出、报告中的错误信息和对应阶段日志排查:
-
-| 现象 | 处理方式 |
-|---|---|
-| 找不到 App 进程或匹配到多个实例 | 启动目标 App,核对 `--app`,必要时指定 `--pid` |
-| 缺少模板或列定义 | 检查 `xcode-select -p`,确认使用完整 Xcode |
-| Instruments 附加失败 | 查看 `*-record.log` 中的权限或进程错误,处理后重新采集 |
-| 输出目录不存在或被替换 | 查看是否执行了构建清理,将后续输出放到 `Build` 以外 |
-| 热点只显示地址 | 使用与 `Mach-O UUID` 匹配的 dSYM,在 Instruments 中符号化 |
-
-最终保存失败时,脚本会尝试将内存中已有的统计数据和原始错误写入系统临时目录 `codexbar-performance-recovery-*`,并打印报告路径;若恢复保存也失败,终端会输出对应错误。
diff --git a/Scripts/performance/__init__.py b/Scripts/performance/__init__.py
new file mode 100644
index 0000000..1055a1a
--- /dev/null
+++ b/Scripts/performance/__init__.py
@@ -0,0 +1 @@
+"""Instruments performance capture and self-contained reporting"""
diff --git a/Scripts/performance/run.py b/Scripts/performance/__main__.py
similarity index 60%
rename from Scripts/performance/run.py
rename to Scripts/performance/__main__.py
index 21e5911..ed34f3c 100644
--- a/Scripts/performance/run.py
+++ b/Scripts/performance/__main__.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python3
"""Non-invasive profiling of an already running macOS app, using xctrace"""
import argparse
@@ -20,8 +19,14 @@ from pathlib import Path
sys.dont_write_bytecode = True
-from analyze import Table, event_summary, profile_summary, resource_summary, system_summary
-from report import write_report
+from .analyze import (
+ Table,
+ event_summary,
+ profile_summary,
+ resource_summary,
+ system_summary,
+)
+from .performance import write_report
VERSION = "1"
ROOT = Path(__file__).resolve().parents[2]
@@ -31,12 +36,12 @@ SCHEMAS = (
"potential-hangs",
"hang-risks",
"device-thermal-state-intervals",
- "activity-monitor-system"
+ "activity-monitor-system",
)
PRESETS = {
"quick": (5, 30, 2, 90, 30),
"standard": (20, 60, 4, 300, 60),
- "extended": (30, 120, 5, 900, 300)
+ "extended": (30, 120, 5, 900, 300),
}
@@ -51,7 +56,9 @@ def status(message):
def capture(args, timeout=20):
result = subprocess.run(args, capture_output=True, timeout=timeout)
if result.returncode:
- raise RuntimeError(f"{args[0]} exited {result.returncode}: {result.stderr.decode(errors='replace')[-1000:]}")
+ raise RuntimeError(
+ f"{args[0]} exited {result.returncode}: {result.stderr.decode(errors='replace')[-1000:]}"
+ )
return result.stdout.decode(errors="replace").strip()
@@ -86,29 +93,41 @@ def inspect_target(app, pid):
candidates = [int(p) for p in capture(["/bin/ps", "-A", "-o", "pid="]).split()]
matches = [p for p in candidates if process_path(p) == executable]
if len(matches) != 1:
- raise ValueError(f"Expected one running instance of {app.name}, found {len(matches)}; specify --pid")
+ raise ValueError(
+ f"Expected one running instance of {app.name}, found {len(matches)}; specify --pid"
+ )
pid = matches[0]
original = identity(pid)
if original["path"] != str(executable) or not original["started"]:
raise ValueError("PID does not match the requested app executable")
- entitlements = subprocess.run(["/usr/bin/codesign", "-d", "--entitlements", ":-", str(app)],
- capture_output=True, timeout=20)
+ entitlements = subprocess.run(
+ ["/usr/bin/codesign", "-d", "--entitlements", ":-", str(app)],
+ capture_output=True,
+ timeout=20,
+ )
ent = None
for stream in (entitlements.stdout, entitlements.stderr):
start = stream.find(b"<?xml")
end = stream.find(b"</plist>")
if 0 <= start <= end:
- ent = plistlib.loads(stream[start:end + len(b"</plist>")])
+ ent = plistlib.loads(stream[start : end + len(b"</plist>")])
break
uuids = optional(["/usr/bin/xcrun", "dwarfdump", "--uuid", str(executable)])
uuid_list = re.findall(r"UUID: ([A-Fa-f0-9-]+) \(([^)]+)\)", uuids or "")
with executable.open("rb") as file:
binary_hash = hashlib.file_digest(file, "sha256").hexdigest()
- return {"name": app.stem, "bundle_id": info.get("CFBundleIdentifier"),
- "version": info.get("CFBundleShortVersionString"), "build": info.get("CFBundleVersion"),
- "binary_sha256": binary_hash, "uuids": uuid_list,
- "get_task_allow": bool(ent.get("com.apple.security.get-task-allow")) if ent is not None else None,
- "identity": original}
+ return {
+ "name": app.stem,
+ "bundle_id": info.get("CFBundleIdentifier"),
+ "version": info.get("CFBundleShortVersionString"),
+ "build": info.get("CFBundleVersion"),
+ "binary_sha256": binary_hash,
+ "uuids": uuid_list,
+ "get_task_allow": bool(ent.get("com.apple.security.get-task-allow"))
+ if ent is not None
+ else None,
+ "identity": original,
+ }
def load_schemas(developer):
@@ -117,9 +136,13 @@ def load_schemas(developer):
for path in base.rglob("schemas.xml"):
for schema in ET.parse(path).getroot().findall("schema"):
if schema.get("name") in SCHEMAS:
- found[schema.get("name")] = [c.get("mnemonic") for c in schema.findall("column")]
+ found[schema.get("name")] = [
+ c.get("mnemonic") for c in schema.findall("column")
+ ]
if "activity-monitor-process-live" not in found:
- raise RuntimeError("No Activity Monitor column schema found in the selected Xcode")
+ raise RuntimeError(
+ "No Activity Monitor column schema found in the selected Xcode"
+ )
return found
@@ -136,10 +159,14 @@ def run_command(args, logfile, timeout, expected=None):
return
except FileNotFoundError:
pass
- raise RuntimeError(f"Output directory removed or replaced during capture: {logfile.parent}")
+ raise RuntimeError(
+ f"Output directory removed or replaced during capture: {logfile.parent}"
+ )
with logfile.open("w") as log:
- process = subprocess.Popen(args, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ process = subprocess.Popen(
+ args, stdout=log, stderr=subprocess.STDOUT, start_new_session=True
+ )
try:
while process.poll() is None:
check_output()
@@ -162,8 +189,12 @@ def run_command(args, logfile, timeout, expected=None):
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=10)
check_output()
- result = {"argv": args, "exit_code": process.returncode,
- "elapsed_s": round(time.monotonic() - began, 2), "log": logfile.name}
+ result = {
+ "argv": args,
+ "exit_code": process.returncode,
+ "elapsed_s": round(time.monotonic() - began, 2),
+ "log": logfile.name,
+ }
if failure:
result["error"] = failure
if interrupted:
@@ -172,10 +203,12 @@ def run_command(args, logfile, timeout, expected=None):
def save(data, output):
- temporary = output / "results.json.tmp"
- temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
- temporary.replace(output / "results.json")
- write_report(data, output / "report.html")
+ temporary = output / "performance.json.tmp"
+ temporary.write_text(
+ json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
+ )
+ temporary.replace(output / "performance.json")
+ write_report(data, output / "performance.html")
def analyze_phase(phase, output, schemas, pid):
@@ -192,7 +225,9 @@ def analyze_phase(phase, output, schemas, pid):
elif name == "activity-monitor-system":
phase["system"] = system_summary(table)
else:
- phase[name] = event_summary(table, pid if name in ("potential-hangs", "hang-risks") else None)
+ phase[name] = event_summary(
+ table, pid if name in ("potential-hangs", "hang-risks") else None
+ )
except (ValueError, KeyError, ET.ParseError, TypeError) as error:
phase["errors"].append(f"{name}: {error}")
@@ -203,15 +238,30 @@ def record_phase(phase, data, output, schemas):
raise RuntimeError("Target process changed before recording")
phase.update(started=now(), errors=[], commands=[], exported=[])
phase["trace"] = phase["id"] + ".trace"
- args = ["/usr/bin/xcrun", "xctrace", "record", "--template", phase["template"],
- "--attach", str(target["pid"]), "--time-limit", f"{phase['seconds']}s",
- "--output", str(output / phase["trace"]), "--no-prompt"]
+ args = [
+ "/usr/bin/xcrun",
+ "xctrace",
+ "record",
+ "--template",
+ phase["template"],
+ "--attach",
+ str(target["pid"]),
+ "--time-limit",
+ f"{phase['seconds']}s",
+ "--output",
+ str(output / phase["trace"]),
+ "--no-prompt",
+ ]
if phase["template"] == "Time Profiler":
args.extend(["--instrument", "Activity Monitor"])
- command = run_command(args, output / f"{phase['id']}-record.log", phase["seconds"] + 150, target)
+ command = run_command(
+ args, output / f"{phase['id']}-record.log", phase["seconds"] + 150, target
+ )
phase["commands"].append(command)
if command["exit_code"] or command.get("error"):
- phase["errors"].append(command.get("error", "xctrace recording failed; see record log"))
+ phase["errors"].append(
+ command.get("error", "xctrace recording failed; see record log")
+ )
elif "[Error]" in (output / command["log"]).read_text(errors="replace"):
phase["errors"].append("xctrace reported an error despite a zero exit code")
if identity(target["pid"]) != target:
@@ -221,8 +271,20 @@ def record_phase(phase, data, output, schemas):
phase["errors"].append("No trace artifact was created")
return
toc = output / f"{phase['id']}-toc.xml"
- cmd = run_command(["/usr/bin/xcrun", "xctrace", "export", "--input", str(trace),
- "--toc", "--output", str(toc)], output / f"{phase['id']}-toc.log", 120)
+ cmd = run_command(
+ [
+ "/usr/bin/xcrun",
+ "xctrace",
+ "export",
+ "--input",
+ str(trace),
+ "--toc",
+ "--output",
+ str(toc),
+ ],
+ output / f"{phase['id']}-toc.log",
+ 120,
+ )
phase["commands"].append(cmd)
if cmd["exit_code"] or cmd.get("error"):
phase["errors"].append("TOC export failed")
@@ -230,17 +292,31 @@ def record_phase(phase, data, output, schemas):
root = ET.parse(toc).getroot()
phase["recorded_s"] = float(root.findtext(".//summary/duration", "0"))
phase["trace_started"] = root.findtext(".//summary/start-date")
- phase["hang_settings"] = [e.text for e in root.findall(".//instrument[@name='Hangs']//key")]
+ phase["hang_settings"] = [
+ e.text for e in root.findall(".//instrument[@name='Hangs']//key")
+ ]
phase["tables"] = [e.get("schema") for e in root.findall(".//data/table")]
- if phase["recorded_s"] < phase["seconds"] * .9:
+ if phase["recorded_s"] < phase["seconds"] * 0.9:
phase["errors"].append("Recording duration below 90% of requested duration")
for name in SCHEMAS:
if name not in phase["tables"] or name not in schemas:
continue
xml = output / f"{phase['id']}-{name}.xml"
- cmd = run_command(["/usr/bin/xcrun", "xctrace", "export", "--input", str(trace),
- "--xpath", f'/trace-toc/run[@number="1"]/data/table[@schema="{name}"]',
- "--output", str(xml)], output / f"{phase['id']}-{name}.log", 120)
+ cmd = run_command(
+ [
+ "/usr/bin/xcrun",
+ "xctrace",
+ "export",
+ "--input",
+ str(trace),
+ "--xpath",
+ f'/trace-toc/run[@number="1"]/data/table[@schema="{name}"]',
+ "--output",
+ str(xml),
+ ],
+ output / f"{phase['id']}-{name}.log",
+ 120,
+ )
phase["commands"].append(cmd)
if cmd["exit_code"] or cmd.get("error"):
phase["errors"].append(f"{name}: export failed")
@@ -252,12 +328,12 @@ def record_phase(phase, data, output, schemas):
else:
resource = phase["resources"]
phase["errors"].extend(resource["errors"])
- if resource["span_s"] < phase["seconds"] * .8:
+ if resource["span_s"] < phase["seconds"] * 0.8:
phase["errors"].append("Resource coverage below 80% of requested duration")
if resource["max_gap_s"] > 5:
phase["errors"].append("Resource sample gap exceeds 5 seconds")
- if resource["cpu_coverage"] < .95:
- phase["errors"].append("CPU counter coverage below 95%")
+ if resource["cpu_coverage"] < 0.95:
+ phase["errors"].append("CPU sample coverage below 95%")
if resource.get("footprint") is None:
phase["errors"].append("Physical footprint was not available")
if phase["template"] == "Time Profiler" and "profile" not in phase:
@@ -267,63 +343,111 @@ def record_phase(phase, data, output, schemas):
def compare(data, path):
previous = json.loads(path.read_text())
- keys = [("target", "bundle_id"), ("environment", "os"), ("environment", "chip"),
- ("environment", "arch"), ("environment", "cores"), ("environment", "memory_bytes"),
- ("environment", "power_source"),
- ("environment", "instruments"), ("config", "workload"), ("config", "preset"),
- ("config", "cpu_mean_budget"), ("config", "footprint_budget")]
- differences = [f"{a}.{b}" for a, b in keys if data.get(a, {}).get(b) != previous.get(a, {}).get(b)]
+ keys = [
+ ("target", "bundle_id"),
+ ("environment", "os"),
+ ("environment", "chip"),
+ ("environment", "arch"),
+ ("environment", "cores"),
+ ("environment", "memory_bytes"),
+ ("environment", "power_source"),
+ ("environment", "instruments"),
+ ("config", "workload"),
+ ("config", "preset"),
+ ("config", "cpu_mean_budget"),
+ ("config", "footprint_budget"),
+ ]
+ differences = [
+ f"{a}.{b}"
+ for a, b in keys
+ if data.get(a, {}).get(b) != previous.get(a, {}).get(b)
+ ]
if data.get("format_version") != previous.get("format_version"):
differences.append("format_version")
if previous.get("state") != "complete":
differences.append("baseline.state")
if data.get("state") != "complete":
differences.append("current.state")
- if [(p["id"], p["seconds"]) for p in data["phases"]] != [(p["id"], p["seconds"]) for p in previous.get("phases", [])]:
+ if [(p["id"], p["seconds"]) for p in data["phases"]] != [
+ (p["id"], p["seconds"]) for p in previous.get("phases", [])
+ ]:
differences.append("phase_plan")
- result = {"baseline_version": previous.get("target", {}).get("version"),
- "compatible": not differences, "differences": differences, "deltas": []}
+ result = {
+ "baseline_version": previous.get("target", {}).get("version"),
+ "compatible": not differences,
+ "differences": differences,
+ "deltas": [],
+ }
if not differences:
for current, old in zip(data["phases"], previous["phases"]):
a, b = current.get("resources"), old.get("resources")
if a and b and not current.get("errors") and not old.get("errors"):
- result["deltas"].append({"phase": current["id"], "cpu_pp": a["cpu_mean"] - b["cpu_mean"],
- "footprint_mib": a["footprint"]["median"] - b["footprint"]["median"]})
+ result["deltas"].append(
+ {
+ "phase": current["id"],
+ "cpu_pp": a["cpu_mean"] - b["cpu_mean"],
+ "footprint_mib": a["footprint"]["median"]
+ - b["footprint"]["median"],
+ }
+ )
return result
def main():
- parser = argparse.ArgumentParser(description=__doc__)
+ parser = argparse.ArgumentParser(
+ prog="python3 -m Scripts.performance", description=__doc__
+ )
parser.add_argument("--app", type=Path, default=Path("/Applications/CodexBar.app"))
parser.add_argument("--pid", type=int)
parser.add_argument("--preset", choices=PRESETS, default="standard")
parser.add_argument("--output", type=Path)
- parser.add_argument("--workload", default="Natural workload; UI and active tasks uncontrolled")
+ parser.add_argument(
+ "--workload", default="Natural workload; UI and active tasks uncontrolled"
+ )
parser.add_argument("--baseline", type=Path)
parser.add_argument("--cpu-mean-budget", type=float)
- parser.add_argument("--footprint-budget", type=float, help="Physical footprint budget in MiB")
- parser.add_argument("--render", type=Path, help="Regenerate HTML from an existing results.json without profiling")
+ parser.add_argument(
+ "--footprint-budget", type=float, help="Physical footprint budget in MiB"
+ )
+ parser.add_argument(
+ "--render",
+ type=Path,
+ help="Regenerate HTML from an existing performance.json without profiling",
+ )
args = parser.parse_args()
if args.render:
data = json.loads(args.render.read_text())
- destination = args.output or args.render.parent / "report.html"
+ destination = args.output or args.render.parent / "performance.html"
write_report(data, destination)
print(destination)
return 0
for value in (args.cpu_mean_budget, args.footprint_budget):
if value is not None and (not 0 < value < float("inf")):
parser.error("Budgets must be finite positive numbers")
- output = (args.output or ROOT / "Build/Performance" / dt.datetime.now().strftime("%Y%m%d-%H%M%S")).resolve()
+ timestamp = dt.datetime.now().strftime("%Y%m%d/%H%M%S")
+ output = (
+ args.output or ROOT / "Performance" / f"{timestamp}-{args.preset}"
+ ).resolve()
try:
output.mkdir(parents=True, exist_ok=False)
except OSError as error:
parser.error(f"Cannot create a new output directory: {error}")
os.chmod(output, 0o700)
- data = {"format_version": VERSION, "started": now(), "state": "running", "errors": [],
- "config": {"preset": args.preset, "workload": args.workload,
- "cpu_mean_budget": args.cpu_mean_budget, "footprint_budget": args.footprint_budget},
- "phases": [], "environment": {"os": platform.mac_ver()[0], "arch": platform.machine()},
- "target": {"name": args.app.stem}}
+ data = {
+ "format_version": VERSION,
+ "started": now(),
+ "state": "running",
+ "errors": [],
+ "config": {
+ "preset": args.preset,
+ "workload": args.workload,
+ "cpu_mean_budget": args.cpu_mean_budget,
+ "footprint_budget": args.footprint_budget,
+ },
+ "phases": [],
+ "environment": {"os": platform.mac_ver()[0], "arch": platform.machine()},
+ "target": {"name": args.app.stem},
+ }
exit_code = 0
def stop(signum, frame):
@@ -336,7 +460,13 @@ def main():
data["tool_sha256"] = {}
source_directory = output / "tool-source"
source_directory.mkdir()
- for name in ("run.py", "analyze.py", "report.py", "report.html"):
+ for name in (
+ "__init__.py",
+ "__main__.py",
+ "analyze.py",
+ "performance.py",
+ "performance.html",
+ ):
source = Path(__file__).with_name(name).read_bytes()
(source_directory / name).write_bytes(source)
data["tool_sha256"][name] = hashlib.sha256(source).hexdigest()
@@ -350,7 +480,9 @@ def main():
env["power"] = optional(["/usr/bin/pmset", "-g", "batt"])
env["power_source"] = (env["power"] or "Unknown").splitlines()[0]
env["load_before"] = list(os.getloadavg())
- templates = capture(["/usr/bin/xcrun", "xctrace", "list", "templates"], timeout=60)
+ templates = capture(
+ ["/usr/bin/xcrun", "xctrace", "list", "templates"], timeout=60
+ )
for template in ("Time Profiler", "Activity Monitor"):
if template not in templates.splitlines():
raise RuntimeError(f"Missing Instruments template: {template}")
@@ -358,21 +490,49 @@ def main():
(output / "schemas.json").write_text(json.dumps(schemas, indent=2))
warmup, sample, repeats, soak, settle = PRESETS[args.preset]
data["config"]["warmup_s"] = warmup
- data["plan"] = [{"id": f"cpu-{i + 1}", "label": f"CPU repeat {i + 1}", "seconds": sample,
- "template": "Time Profiler"} for i in range(repeats)] + [
- {"id": "soak", "label": "Resource observation", "seconds": soak, "template": "Activity Monitor"},
- {"id": "settle", "label": "Follow-up observation", "seconds": settle, "template": "Activity Monitor"}]
+ data["plan"] = [
+ {
+ "id": f"cpu-{i + 1}",
+ "label": f"CPU repeat {i + 1}",
+ "seconds": sample,
+ "template": "Time Profiler",
+ }
+ for i in range(repeats)
+ ] + [
+ {
+ "id": "soak",
+ "label": "Resource observation",
+ "seconds": soak,
+ "template": "Activity Monitor",
+ },
+ {
+ "id": "settle",
+ "label": "Follow-up observation",
+ "seconds": settle,
+ "template": "Activity Monitor",
+ },
+ ]
save(data, output)
- status(f"Warm-up {warmup}s; target PID {data['target']['identity']['pid']}; output {output}")
+ status(
+ f"Warm-up {warmup}s; target PID {data['target']['identity']['pid']}; output {output}"
+ )
time.sleep(warmup)
for planned in data["plan"]:
phase = dict(planned)
data["phases"].append(phase)
- status(f"Recording {phase['id']} ({phase['template']}, {phase['seconds']}s)")
+ status(
+ f"Recording {phase['id']} ({phase['template']}, {phase['seconds']}s)"
+ )
record_phase(phase, data, output, schemas)
- status(f"Finished {phase['id']}: {'incomplete' if phase['errors'] else 'valid'}")
+ status(
+ f"Finished {phase['id']}: {'incomplete' if phase['errors'] else 'valid'}"
+ )
save(data, output)
- data["state"] = "complete" if all(not p.get("errors") for p in data["phases"]) else "incomplete"
+ data["state"] = (
+ "complete"
+ if all(not p.get("errors") for p in data["phases"])
+ else "incomplete"
+ )
data["environment"]["load_after"] = list(os.getloadavg())
if args.baseline:
data["comparison"] = compare(data, args.baseline)
@@ -381,9 +541,15 @@ def main():
resource = phase.get("resources", {})
if phase.get("errors"):
continue
- if args.cpu_mean_budget is not None and resource.get("cpu_mean", 0) > args.cpu_mean_budget:
+ if (
+ args.cpu_mean_budget is not None
+ and resource.get("cpu_mean", 0) > args.cpu_mean_budget
+ ):
breached.append(phase["id"] + ": cpu_mean")
- if args.footprint_budget is not None and resource.get("footprint", {}).get("max", 0) > args.footprint_budget:
+ if (
+ args.footprint_budget is not None
+ and resource.get("footprint", {}).get("max", 0) > args.footprint_budget
+ ):
breached.append(phase["id"] + ": footprint_peak")
data["budget_breaches"] = breached
exit_code = 2 if data["state"] != "complete" else 3 if breached else 0
@@ -401,7 +567,9 @@ def main():
try:
save(data, output)
except Exception as error:
- data["errors"].append(f"Saving results failed: {type(error).__name__}: {error}")
+ data["errors"].append(
+ f"Saving results failed: {type(error).__name__}: {error}"
+ )
data["state"] = "incomplete"
exit_code = data["exit_code"] = 2
for message in data["errors"]:
@@ -410,10 +578,12 @@ def main():
output = Path(tempfile.mkdtemp(prefix="codexbar-performance-recovery-"))
save(data, output)
except Exception as recovery_error:
- status(f"Recovery save failed: {type(recovery_error).__name__}: {recovery_error}")
+ status(
+ f"Recovery save failed: {type(recovery_error).__name__}: {recovery_error}"
+ )
output = None
if output is not None:
- status(f"Report: {output / 'report.html'}; exit {exit_code}")
+ status(f"Report: {output / 'performance.html'}; exit {exit_code}")
return exit_code
diff --git a/Scripts/performance/analyze.py b/Scripts/performance/analyze.py
index f6bd000..1d43c49 100644
--- a/Scripts/performance/analyze.py
+++ b/Scripts/performance/analyze.py
@@ -60,7 +60,7 @@ def resource_summary(table, pid):
if len(points) < 3:
raise ValueError("Fewer than 3 target resource samples")
series, errors = [], []
- previous = None
+ interval_end = points[0]["start"]
for point in points:
timestamp = point["start"] / 1e9
item = {"t": timestamp, "cpu": None, "dt": None}
@@ -69,26 +69,30 @@ def resource_summary(table, pid):
value = point.get(source)
item[destination] = value / 2 ** 20 if value is not None else None
item["threads"] = point.get("thread-count")
- if previous is not None:
- dt = (point["start"] - previous["start"]) / 1e9
- current_cpu, last_cpu = point.get("cpu-total"), previous.get("cpu-total")
- if dt > 0 and current_cpu is not None and last_cpu is not None:
- delta = (current_cpu - last_cpu) / 1e9
- if delta < 0:
- errors.append("CPU counter decreased; possible process reset or invalid data")
+ duration, cpu = point.get("duration"), point.get("cpu-percent")
+ if duration is None or duration <= 0:
+ errors.append("Resource sample duration is missing or nonpositive")
+ elif point["start"] < interval_end:
+ errors.append("Resource sample intervals overlap")
+ else:
+ interval_end = point["start"] + duration
+ # Instruments pairs each CPU percentage with the duration in the same row
+ if cpu is not None:
+ if cpu < 0:
+ errors.append("CPU percentage is negative")
else:
- item.update(cpu=100 * delta / dt, dt=dt)
+ item.update(cpu=cpu, dt=duration / 1e9)
series.append(item)
- previous = point
span = series[-1]["t"] - series[0]["t"]
if span <= 0:
raise ValueError("Resource sample time did not advance")
cpu_points = [p for p in series if p["cpu"] is not None]
observed_seconds = sum(p["dt"] for p in cpu_points)
+ cpu_span = (max(interval_end, points[-1]["start"]) - points[0]["start"]) / 1e9
cpu = [p["cpu"] for p in cpu_points]
result = {"samples": len(series), "span_s": span, "series": series, "errors": errors,
"max_gap_s": max(b["t"] - a["t"] for a, b in zip(series, series[1:])),
- "cpu_coverage": observed_seconds / span,
+ "cpu_coverage": observed_seconds / cpu_span,
"cpu_mean": sum(p["cpu"] * p["dt"] for p in cpu_points) / observed_seconds if observed_seconds else None,
"cpu_p50": percentile(cpu, .5), "cpu_p95": percentile(cpu, .95),
"cpu_peak": max(cpu) if cpu else None}
diff --git a/Scripts/performance/report.html b/Scripts/performance/performance.html
similarity index 55%
rename from Scripts/performance/report.html
rename to Scripts/performance/performance.html
index 203d209..92308e0 100644
--- a/Scripts/performance/report.html
+++ b/Scripts/performance/performance.html
@@ -2,657 +2,587 @@
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
- <meta
- name="viewport"
- content="width=device-width,initial-scale=1" />
- <meta
- name="color-scheme"
- content="light dark" />
- <meta
- http-equiv="Content-Security-Policy"
- content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <meta name="color-scheme" content="light dark" />
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'" />
<title>@@TITLE@@</title>
<style>
@font-face {
font-family: 'Report Latin';
src: local('MesloLGS NF Regular'), local('MesloLGS-NF-Regular');
- font-style: normal;
font-weight: 400;
unicode-range: U+0000-024F, U+1E00-1EFF;
}
-
@font-face {
font-family: 'Report Latin';
src: local('MesloLGS NF Bold'), local('MesloLGS-NF-Bold');
- font-style: normal;
font-weight: 700;
unicode-range: U+0000-024F, U+1E00-1EFF;
}
-
- @font-face {
- font-family: 'Report Latin';
- src: local('MesloLGS NF Italic'), local('MesloLGS-NF-Italic');
- font-style: italic;
- font-weight: 400;
- unicode-range: U+0000-024F, U+1E00-1EFF;
- }
-
- @font-face {
- font-family: 'Report Latin';
- src: local('MesloLGS NF Bold Italic'), local('MesloLGS-NF-Bold-Italic');
- font-style: italic;
- font-weight: 700;
- unicode-range: U+0000-024F, U+1E00-1EFF;
- }
-
:root {
- --bg: #f2f4f3;
- --card: #fff;
- --ink: #172b31;
- --muted: #607177;
- --line: #dfe6e4;
- --teal: #168c80;
- --nav: #0e2930;
- --warn: #a76412;
- --soft: #e8f4f0;
- --report-font: 'Report Latin', -apple-system, BlinkMacSystemFont, 'PingFang SC', sans-serif;
- --mono: var(--report-font);
+ color-scheme: light;
+ --bg: #eef2f6;
+ --card: #ffffff;
+ --surface: #f5f7fa;
+ --ink: #1b293d;
+ --muted: #5d6b80;
+ --line: #d8e0eb;
+ --teal: #087e83;
+ --violet: #7055d0;
+ --warn: #956017;
+ --rose: #bd4264;
+ --soft: #e7f3f3;
+ --nav: #f7f9fc;
+ --report-font: -apple-system, BlinkMacSystemFont, 'PingFang SC', sans-serif;
+ --mono: 'Report Latin', 'SFMono-Regular', Consolas, var(--report-font);
}
-
* {
box-sizing: border-box;
}
-
html {
scroll-behavior: smooth;
- scroll-padding-top: 30px;
+ scroll-padding-top: 24px;
}
-
body {
margin: 0;
background: var(--bg);
color: var(--ink);
- font: 15px/1.75 var(--report-font);
+ font: 13px/1.6 var(--report-font);
+ -webkit-font-smoothing: antialiased;
}
-
body.dark {
- --bg: #122128;
- --card: #1a2b32;
- --ink: #e5eeeb;
- --muted: #a8baba;
- --line: #31434a;
- --soft: #203c3a;
- --warn: #f0b45f;
+ color-scheme: dark;
+ --bg: #080d18;
+ --card: #111a2b;
+ --surface: #0d1524;
+ --ink: #e8eef9;
+ --muted: #9baac1;
+ --line: #253249;
+ --teal: #51ddd2;
+ --violet: #ae9aff;
+ --warn: #f3be6b;
+ --rose: #f28da9;
+ --soft: #152e37;
+ --nav: #0b1120;
}
-
a {
color: var(--teal);
text-decoration: none;
}
-
a:hover {
text-decoration: underline;
}
-
- button {
+ button,
+ input {
font: inherit;
+ }
+ button {
cursor: pointer;
}
-
- button:focus-visible,
- a:focus-visible,
- summary:focus-visible {
- outline: 3px solid #cc9a45;
+ :is(button, a, summary, input):focus-visible {
+ outline: 2px solid var(--teal);
outline-offset: 4px;
}
-
+ [hidden] {
+ display: none !important;
+ }
.shell {
display: grid;
- grid-template-columns: 228px minmax(0, 1fr);
- max-width: 1800px;
+ grid-template-columns: 190px minmax(0, 1fr);
+ max-width: 1920px;
margin: auto;
}
-
.sidebar {
background: var(--nav);
- color: #b6cbcc;
- padding: 40px 25px;
+ color: var(--muted);
+ padding: 28px 16px;
position: sticky;
top: 0;
height: 100vh;
+ overflow-y: auto;
+ border-right: 1px solid var(--line);
+ display: flex;
+ flex-direction: column;
}
-
.brand {
- font-size: 12px;
- letter-spacing: 0.2em;
- color: #e4c180;
- font-weight: 700;
+ font: 10px var(--mono);
+ letter-spacing: 0.16em;
+ color: var(--teal);
+ }
+ .brand::before {
+ content: '';
+ display: inline-block;
+ width: 6px;
+ height: 6px;
+ margin-right: 7px;
+ background: var(--teal);
+ box-shadow: 0 0 12px var(--teal);
}
-
.sidebar strong {
- display: block;
font-size: 24px;
- color: white;
- margin: 10px 0 36px;
+ letter-spacing: -0.04em;
+ color: var(--ink);
+ margin: 8px 0 32px;
}
-
.sidebar nav a {
- display: block;
- color: #b6cbcc;
- padding: 9px 0;
- font-size: 13px;
+ display: flex;
+ align-items: center;
+ color: var(--muted);
+ padding: 10px 9px;
+ margin: 3px 0;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ font-size: 12px;
+ }
+ .sidebar nav a:hover,
+ .sidebar nav a.active {
+ color: var(--teal);
+ background: var(--soft);
+ border-color: var(--line);
+ text-decoration: none;
}
-
.sidebar nav span {
- display: inline-block;
- width: 28px;
- color: #709292;
- font-family: var(--mono);
+ width: 27px;
+ font: 10px var(--mono);
+ opacity: 0.6;
}
-
.side-note {
- border-top: 1px solid #365158;
- margin-top: 45px;
- padding-top: 22px;
- font-size: 12px;
+ border-top: 1px solid var(--line);
+ margin-top: auto;
+ padding-top: 20px;
+ font: 11px/2 var(--mono);
+ }
+ .side-note span {
+ display: block;
+ color: var(--muted);
+ font-size: 9px;
+ letter-spacing: 0.13em;
}
-
.main {
- padding: 46px 5vw 64px;
+ padding: 26px 30px 32px;
min-width: 0;
}
-
- .topline {
+ .topline,
+ .section-head {
display: flex;
justify-content: space-between;
align-items: center;
- gap: 15px;
- flex-wrap: wrap;
+ gap: 16px;
}
-
.eyebrow {
- font-size: 11px;
- letter-spacing: 0.13em;
- font-weight: 700;
+ font: 10px var(--mono);
+ letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--teal);
}
-
.actions {
display: flex;
- gap: 8px;
+ gap: 6px;
+ flex-wrap: wrap;
}
-
.actions button {
+ padding: 5px 10px;
border: 1px solid var(--line);
- border-radius: 7px;
+ border-radius: 5px;
background: var(--card);
+ color: var(--muted);
+ font-size: 11px;
+ }
+ .actions button:hover {
+ border-color: var(--teal);
color: var(--ink);
- padding: 6px 12px;
- font-size: 12px;
}
-
h1 {
- font-size: clamp(32px, 4vw, 54px);
- line-height: 1.18;
+ font-size: clamp(26px, 3vw, 38px);
+ line-height: 1.3;
letter-spacing: -0.045em;
- margin: 23px 0 14px;
+ margin: 16px 0 8px;
+ }
+ h1 span {
+ color: var(--muted);
+ font-weight: 400;
+ font-size: 0.62em;
+ letter-spacing: 0;
+ margin-left: 12px;
}
-
h2 {
- font-size: 25px;
+ font-size: 19px;
+ letter-spacing: -0.02em;
margin: 0;
- letter-spacing: -0.025em;
}
-
h3 {
- font-size: 18px;
+ font-size: 13px;
line-height: 1.5;
- margin: 7px 0 10px;
+ margin: 0 0 10px;
}
-
h4 {
- font-size: 14px;
- margin: 23px 0 12px;
+ font-size: 12px;
+ margin: 0 0 12px;
}
-
p {
- margin: 10px 0 17px;
+ margin: 8px 0 12px;
}
-
- .lead {
- font-size: 16px;
+ .muted {
color: var(--muted);
- max-width: 740px;
+ font-size: 11px;
}
-
.meta {
display: flex;
- gap: 12px;
align-items: center;
+ gap: 14px;
flex-wrap: wrap;
- font-size: 12px;
color: var(--muted);
- margin: 23px 0 28px;
+ font-size: 11px;
+ margin: 10px 0 16px;
}
-
.badge {
display: inline-flex;
align-items: center;
- border-radius: 30px;
- padding: 4px 11px;
- font-size: 11px;
+ gap: 6px;
+ padding: 3px 9px;
+ border-radius: 4px;
+ font-size: 10px;
white-space: nowrap;
}
-
+ .badge::before {
+ content: '';
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: currentColor;
+ }
.badge.ok {
- background: var(--soft);
color: var(--teal);
+ background: var(--soft);
}
-
.badge.warn {
- background: #f4e7d5;
- color: #976022;
+ color: var(--warn);
+ background: var(--surface);
+ box-shadow: inset 0 0 0 1px var(--warn);
}
-
.hero-rule {
- height: 2px;
- background: linear-gradient(90deg, var(--teal) 0 22%, var(--line) 22% 100%);
- margin: 22px 0 30px;
+ height: 1px;
+ background: linear-gradient(90deg, var(--teal), var(--violet) 45%, var(--line));
+ margin: 16px 0;
}
-
.kpis {
display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 13px;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 10px;
}
-
.kpi {
- background: var(--card);
+ position: relative;
+ overflow: hidden;
+ background: linear-gradient(125deg, var(--card), var(--surface));
border: 1px solid var(--line);
- padding: 21px;
- border-radius: 10px;
+ border-radius: 8px;
+ padding: 13px 16px 11px;
}
-
- .kpi .value {
- font-family: var(--mono);
- font-size: 34px;
- letter-spacing: -0.06em;
- margin: 11px 0 4px;
+ .kpi::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 16px;
+ width: 28px;
+ height: 2px;
+ background: var(--accent);
+ box-shadow: 0 0 14px var(--accent);
}
-
- .kpi small {
- font-size: 12px;
- line-height: 1.5;
+ .kpi:nth-child(4n + 1) {
+ --accent: var(--teal);
+ }
+ .kpi:nth-child(4n + 2) {
+ --accent: var(--violet);
+ }
+ .kpi:nth-child(4n + 3) {
+ --accent: var(--warn);
+ }
+ .kpi:nth-child(4n + 4) {
+ --accent: var(--rose);
+ }
+ .kpi .label {
+ font-size: 11px;
color: var(--muted);
}
-
+ .kpi .value {
+ font: 29px/1.45 var(--mono);
+ letter-spacing: -0.055em;
+ margin: 4px 0 0;
+ }
.kpi .unit {
- font: 12px var(--mono);
- color: var(--muted);
+ font-size: 11px;
+ color: var(--accent);
margin-left: 6px;
+ letter-spacing: 0;
}
-
- .kpi .label {
- font-size: 12px;
- font-weight: 600;
+ .kpi small {
+ font-size: 10px;
+ color: var(--muted);
}
-
- .section {
- margin-top: 48px;
+ .overview-matrix {
+ margin-top: 8px;
}
-
- .section-head {
+ .matrix-head {
display: flex;
justify-content: space-between;
align-items: center;
- gap: 20px;
- margin-bottom: 20px;
+ gap: 10px;
+ margin-bottom: 8px;
}
-
- .section-index {
- font: 12px var(--mono);
- color: var(--muted);
- margin-bottom: 6px;
+ .matrix-head h3 {
+ margin: 0;
}
-
- .muted {
+ .phase-buttons {
+ display: none;
+ gap: 7px;
+ flex-wrap: wrap;
+ margin: 12px 0 0;
+ }
+ .js .phase-buttons {
+ display: flex;
+ }
+ .phase-button {
+ display: flex;
+ gap: 18px;
+ justify-content: space-between;
+ flex: 1 1 130px;
+ padding: 7px 10px;
+ border: 1px solid var(--line);
+ border-left: 2px solid var(--teal);
+ border-radius: 4px;
+ background: var(--surface);
+ color: var(--teal);
+ text-align: left;
+ font: 10px var(--mono);
+ }
+ .phase-button:hover {
+ border-color: var(--teal);
+ background: var(--soft);
+ }
+ .phase-button:active {
+ transform: translateY(1px);
+ box-shadow: inset 0 1px 3px #0003;
+ }
+ .phase-button.warn {
+ border-left-color: var(--warn);
+ }
+ .phase-button b {
+ font-weight: 400;
color: var(--muted);
- font-size: 13px;
}
-
+ .section {
+ margin-top: 28px;
+ }
+ .section-head {
+ margin-bottom: 12px;
+ }
+ .section-index {
+ color: var(--teal);
+ font: 9px var(--mono);
+ letter-spacing: 0.13em;
+ margin-bottom: 3px;
+ }
.panel,
.phase {
+ min-width: 0;
background: var(--card);
border: 1px solid var(--line);
- border-radius: 10px;
- padding: 25px;
+ border-radius: 8px;
+ padding: 16px;
}
-
.phase {
- margin-bottom: 22px;
+ margin-bottom: 14px;
}
-
.phase .section-head {
- margin-bottom: 4px;
+ margin-bottom: 2px;
+ }
+ .phase .section-head h3 {
+ font: 17px var(--mono);
+ margin: 5px 0 0;
+ }
+ .two,
+ .chart-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px;
+ }
+ #comparison > .two {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ }
+ .section > .two {
+ margin-top: 12px;
+ }
+ .panel p {
+ color: var(--muted);
+ font-size: 11px;
}
-
.table-scroll {
overflow-x: auto;
border: 1px solid var(--line);
- border-radius: 8px;
+ border-radius: 6px;
background: var(--card);
}
-
table {
width: 100%;
border-collapse: collapse;
- font-size: 12px;
+ font-size: 11px;
text-align: left;
+ font-variant-numeric: tabular-nums;
}
-
th {
- font-weight: 600;
+ font-weight: 500;
color: var(--muted);
- background: var(--bg);
- padding: 12px 14px;
+ background: var(--surface);
+ padding: 8px 10px;
white-space: nowrap;
}
-
td {
- padding: 12px 14px;
+ padding: 8px 10px;
border-top: 1px solid var(--line);
vertical-align: top;
overflow-wrap: anywhere;
}
-
td:first-child {
- font-weight: 550;
- }
-
- .environment-panel th:first-child,
- .environment-panel td:first-child {
- width: 140px;
- min-width: 140px;
- white-space: nowrap;
+ font-weight: 600;
}
-
tr:hover td {
background: var(--soft);
}
-
+ .overview-matrix table {
+ font: 10px/1.6 var(--mono);
+ }
+ .overview-matrix td {
+ white-space: nowrap;
+ text-align: right;
+ }
+ .overview-matrix th {
+ text-align: right;
+ }
+ .overview-matrix :is(td, th):first-child {
+ text-align: left;
+ position: sticky;
+ left: 0;
+ background: var(--surface);
+ }
+ .environment-panel :is(td, th):first-child {
+ width: 125px;
+ white-space: nowrap;
+ }
.notice {
- padding: 17px 20px;
- border-left: 3px solid var(--teal);
+ padding: 10px 14px;
+ border-left: 2px solid var(--teal);
background: var(--soft);
- font-size: 13px;
- margin: 18px 0;
+ font-size: 12px;
+ margin: 12px 0;
+ overflow-wrap: anywhere;
}
-
.notice.warn {
- border-left-color: var(--warn);
- }
-
- .two {
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- gap: 18px;
- }
-
- .panel p {
- font-size: 13px;
+ border-color: var(--warn);
}
-
svg {
width: 100%;
height: auto;
display: block;
overflow: visible;
}
-
svg text {
- font: 11px var(--mono);
+ font: 13px var(--mono);
fill: var(--muted);
}
-
svg .grid {
stroke: var(--line);
stroke-width: 1;
+ stroke-dasharray: 3 5;
+ }
+ svg path {
+ vector-effect: non-scaling-stroke;
}
-
details {
border-top: 1px solid var(--line);
- padding: 14px 0;
- margin-top: 15px;
+ padding: 10px 0;
+ margin-top: 12px;
+ }
+ details.panel {
+ padding: 13px 16px;
}
-
summary {
- font-size: 13px;
+ font-size: 12px;
font-weight: 600;
cursor: pointer;
+ overflow-wrap: anywhere;
}
-
details p {
- font-size: 12px;
color: var(--muted);
+ font-size: 11px;
+ }
+ details .table-scroll {
+ margin-top: 10px;
}
-
.empty {
- padding: 40px;
+ padding: 24px 12px;
color: var(--muted);
text-align: center;
+ font-size: 11px;
}
-
.footer {
- margin-top: 48px;
+ margin-top: 28px;
+ padding-top: 14px;
border-top: 1px solid var(--line);
- padding-top: 20px;
display: flex;
justify-content: space-between;
- gap: 20px;
+ gap: 12px;
+ font: 9px/1.8 var(--mono);
color: var(--muted);
- font-size: 11px;
- }
-
- @media (min-width: 1450px) {
- .main {
- padding-left: 70px;
- padding-right: 70px;
- }
- }
-
- @media (max-width: 1100px) {
- .shell {
- grid-template-columns: 180px minmax(0, 1fr);
- }
-
- .sidebar {
- padding: 30px 18px;
- }
-
- .main {
- padding: 32px 28px;
- }
-
- .kpi {
- padding: 16px;
- }
-
- .kpi .value {
- font-size: 27px;
- }
- }
-
- @media (max-width: 800px) {
- .shell {
- display: block;
- }
-
- .sidebar {
- display: none;
- }
-
- .main {
- padding: 25px 18px;
- }
-
- .kpis {
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
-
- .two {
- grid-template-columns: 1fr;
- }
-
- .phase,
- .panel {
- padding: 19px;
- }
-
- .section {
- margin-top: 34px;
- }
-
- .actions button {
- padding: 5px 9px;
- }
-
- .section-head {
- gap: 10px;
- }
-
- .footer {
- display: block;
- }
-
- h1 {
- font-size: 38px;
- }
}
-
- @media print {
- body,
- body.dark {
- --bg: #fff;
- --card: #fff;
- --ink: #111;
- --muted: #555;
- --line: #ddd;
- --soft: #f4f8f6;
- background: white;
- color: #111;
- font-size: 11px;
- }
-
- .sidebar,
- .actions {
- display: none !important;
- }
-
- .shell {
- display: block;
- }
-
- .main {
- padding: 0;
- }
-
- .section {
- margin-top: 24px;
- }
-
- .phase,
- .panel {
- break-inside: avoid;
- }
-
- .kpi {
- padding: 12px;
- }
-
- .kpi .value {
- font-size: 24px;
- }
-
- .table-scroll {
- overflow: visible;
- }
-
- th,
- td {
- padding: 8px;
- }
-
- svg {
- max-height: 220px;
- }
-
- .footer {
- margin-top: 20px;
- }
-
- h1 {
- font-size: 34px;
- }
-
- a {
- color: inherit;
- }
-
- details {
- break-inside: auto;
- }
- }
-
.bar-chart {
- margin-top: 16px;
+ margin-top: 12px;
}
-
.bar-group {
- margin: 0 0 16px;
+ margin-bottom: 10px;
+ }
+ .bar-group:last-child {
+ margin-bottom: 0;
}
-
.bar-label {
- font: 12px/1.5 var(--mono);
+ font: 10px/1.6 var(--mono);
overflow-wrap: anywhere;
- margin-bottom: 6px;
color: var(--ink);
+ margin-bottom: 3px;
}
-
.bar-entry {
display: grid;
- grid-template-columns: 48px minmax(30px, 1fr) 104px;
- gap: 8px;
+ grid-template-columns: 34px minmax(20px, 1fr) 90px;
align-items: center;
- margin: 5px 0;
+ gap: 6px;
+ margin: 3px 0;
}
-
.bar-series {
- font-size: 11px;
color: var(--muted);
+ font-size: 10px;
+ }
+ .bar-series:empty {
+ display: none;
+ }
+ .bar-entry:has(.bar-series:empty) {
+ grid-template-columns: minmax(20px, 1fr) 90px;
}
-
.bar-track {
- height: 10px;
- background: var(--bg);
position: relative;
- border-radius: 3px;
+ height: 8px;
+ border-radius: 2px;
overflow: hidden;
+ background: var(--surface);
}
-
.bar-track i {
position: absolute;
top: 0;
height: 100%;
border-radius: 2px;
- min-width: 0;
}
-
.bar-track.missing {
background: repeating-linear-gradient(90deg, var(--line) 0 4px, transparent 4px 8px);
height: 2px;
}
-
.zero {
position: absolute;
top: 0;
@@ -661,412 +591,450 @@
background: var(--muted);
opacity: 0.5;
}
-
.bar-value {
- font: 11px var(--mono);
+ font: 10px var(--mono);
text-align: right;
white-space: nowrap;
- color: var(--ink);
}
-
.bar-value small {
- font-size: 10px;
+ font-size: 9px;
color: var(--muted);
}
-
- .hotspot {
- margin-top: 18px;
- }
-
.hotspot > .two {
- margin-top: 22px;
+ margin-top: 14px;
}
-
.hotspot .panel {
- padding: 16px;
- border: 0;
- background: var(--bg);
+ padding: 12px;
+ background: var(--surface);
}
-
.hotspot .bar-track {
background: var(--line);
}
-
.metric-strip {
display: grid;
- grid-template-columns: repeat(4, 1fr);
+ grid-template-columns: repeat(6, minmax(0, 1fr));
gap: 12px;
- padding-top: 20px;
- border-top: 1px solid var(--line);
+ margin: 12px 0;
+ padding: 12px 0;
+ border-block: 1px solid var(--line);
}
-
.metric-strip span {
display: block;
color: var(--muted);
- font-size: 11px;
+ font-size: 10px;
}
-
.metric-strip b {
- font: 18px var(--mono);
+ font: 13px/1.8 var(--mono);
}
-
.thermal-phase {
display: grid;
- grid-template-columns: 64px 1fr;
- gap: 10px;
+ grid-template-columns: 55px 1fr;
+ gap: 7px;
align-items: center;
- margin-top: 14px;
- font: 12px var(--mono);
+ margin-top: 10px;
+ font: 10px var(--mono);
}
-
.thermal-state {
display: flex;
- justify-content: space-between;
align-items: center;
- gap: 10px;
- border-radius: 5px;
- padding: 9px 12px;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 6px;
+ padding: 7px 9px;
+ border-radius: 4px;
grid-column: 2;
+ background: var(--surface);
}
-
- .thermal-phase > b + .thermal-state {
- grid-column: auto;
- }
-
- .thermal-state span {
- font-size: 10px;
- }
-
- .thermal-state.nominal {
- background: var(--soft);
- color: var(--teal);
- }
-
- .thermal-state.elevated {
- background: #f4e7d5;
- color: #976022;
- }
-
- .section > .two {
- margin-top: 18px;
- }
-
- .two > .panel {
- min-width: 0;
- }
-
- .hotspot summary {
- font-size: 15px;
- }
-
- details.panel {
- padding: 20px 25px;
- }
-
- @media (max-width: 800px) {
- .bar-entry {
- grid-template-columns: 40px minmax(25px, 1fr) 90px;
- }
-
- .metric-strip {
- grid-template-columns: repeat(2, 1fr);
- }
-
- .thermal-state {
- flex-wrap: wrap;
- }
-
- .section-head {
- align-items: flex-start;
- flex-direction: column;
- }
-
- .hotspot .panel {
- padding: 12px;
- }
-
- .hotspot {
- padding: 16px !important;
- }
- }
-
- @media print {
- .phase {
- break-inside: auto;
- }
-
- .bar-group,
- .metric-strip,
- .thermal-phase {
- break-inside: avoid;
- }
-
- .bar-track,
- .bar-track i,
- .thermal-state,
- svg {
- -webkit-print-color-adjust: exact;
- print-color-adjust: exact;
- }
-
- .bar-label {
- font-size: 10px;
- }
-
- .bar-group {
- margin-bottom: 10px;
- }
+ .thermal-phase > b + .thermal-state {
+ grid-column: auto;
}
-
- .trend-chart {
- margin: 22px 0 28px;
- padding-top: 15px;
- border-top: 1px solid var(--line);
+ .thermal-state span {
+ font-size: 9px;
+ color: var(--muted);
+ }
+ .thermal-state.nominal {
+ color: var(--teal);
+ background: var(--soft);
+ }
+ .thermal-state.elevated {
+ color: var(--warn);
+ border: 1px solid var(--warn);
+ }
+ .trend-chart,
+ .sample-summary {
+ min-width: 0;
+ padding: 12px;
+ background: var(--surface);
+ border: 1px solid var(--line);
+ border-radius: 6px;
}
-
.trend-stats {
display: flex;
justify-content: space-between;
- gap: 12px;
flex-wrap: wrap;
+ align-items: baseline;
+ gap: 4px 10px;
}
-
.trend-stats b {
- font-size: 14px;
+ font-size: 12px;
}
-
.trend-stats span {
- font-size: 12px;
color: var(--muted);
+ font: 10px var(--mono);
}
-
.trend-chart svg {
touch-action: pan-y;
}
-
.cursor {
stroke: var(--ink);
stroke-width: 1;
stroke-dasharray: 4 4;
pointer-events: none;
}
-
- .cursor[hidden] {
- display: none;
- }
-
.chart-control {
display: none;
align-items: center;
- gap: 18px;
- padding: 0 3% 0 7%;
+ gap: 10px;
}
-
.js .chart-control {
display: flex;
}
-
.chart-control input {
- width: 45%;
+ width: 38%;
+ min-width: 50px;
accent-color: var(--teal);
cursor: ew-resize;
}
-
.chart-control output {
- font: 12px var(--mono);
- color: var(--ink);
+ font: 10px var(--mono);
+ white-space: nowrap;
+ }
+ .sample-summary {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ }
+ .sample-summary p {
+ margin-bottom: 0;
}
-
.share-track {
display: flex;
- height: 30px;
- border-radius: 6px;
+ height: 18px;
+ border-radius: 4px;
overflow: hidden;
- margin: 30px 0 20px;
+ margin: 18px 0;
}
-
.share-track i {
display: block;
height: 100%;
}
-
.share-values {
display: grid;
grid-template-columns: 1fr 1fr;
- gap: 25px;
+ gap: 18px;
}
-
.share-values span,
.share-values small {
display: block;
- font-size: 12px;
color: var(--muted);
+ font-size: 11px;
}
-
.share-values b {
- font: 28px/1.8 var(--mono);
+ font: 30px/1.8 var(--mono);
}
-
.share-values > div {
- border-top: 3px solid #168c80;
- padding-top: 10px;
+ border-top: 2px solid var(--teal);
+ padding-top: 8px;
}
-
.share-values > div + div {
- border-color: #5668cb;
+ border-color: var(--violet);
}
-
.interval-axis {
display: flex;
justify-content: space-between;
color: var(--muted);
- font: 11px var(--mono);
- margin: 20px 0 10px;
+ font: 9px var(--mono);
+ margin: 12px 0 6px;
}
-
.interval-row {
- padding: 12px 0;
+ padding: 7px 0;
border-bottom: 1px solid var(--line);
}
-
.interval-row > b {
- font: 12px var(--mono);
+ font: 10px var(--mono);
}
-
.interval-track {
position: relative;
- height: 24px;
- margin: 8px 6px;
+ height: 16px;
+ margin: 4px 6px;
background: linear-gradient(var(--line), var(--line)) center/100% 1px no-repeat;
}
-
.interval-line {
position: absolute;
- top: 10px;
+ top: 6px;
height: 4px;
- background: #168c80;
+ background: var(--teal);
opacity: 0.55;
}
-
.interval-point {
position: absolute;
- top: 6px;
+ top: 3px;
transform: translateX(-50%);
- width: 12px;
- height: 12px;
- background: #168c80;
- border: 2px solid #168c80;
+ width: 10px;
+ height: 10px;
+ border: 2px solid var(--teal);
+ background: var(--teal);
border-radius: 50%;
}
-
.interval-point.bound {
width: 2px;
border: 0;
border-radius: 0;
- top: 5px;
- height: 14px;
+ top: 2px;
+ height: 12px;
}
-
.interval-point.head {
background: var(--card);
}
-
.interval-point.tail {
- background: #5668cb;
- border-color: #5668cb;
+ background: var(--violet);
+ border-color: var(--violet);
}
-
.interval-values,
.interval-key {
- font: 11px/1.8 var(--mono);
- color: var(--muted);
display: block;
+ font: 9px/1.8 var(--mono);
+ color: var(--muted);
}
-
.interval-key {
- margin-top: 15px;
- }
-
- .bar-track {
- height: 16px;
- border-radius: 2px;
- }
-
- .bar-entry {
- grid-template-columns: 48px minmax(30px, 1fr) 110px;
- }
-
- .bar-series:empty {
- display: none;
- }
-
- .bar-entry:has(.bar-series:empty) {
- grid-template-columns: minmax(30px, 1fr) 110px;
- }
-
- .bar-label {
- line-height: 1.65;
+ margin-top: 8px;
}
-
- .hotspot > .two {
- grid-template-columns: 1fr;
- }
-
- .hotspot .bar-group {
- margin-bottom: 18px;
+ @media (min-width: 1650px) {
+ .main {
+ padding-inline: 40px;
+ }
+ .kpis {
+ grid-template-columns: repeat(8, minmax(0, 1fr));
+ }
+ .kpi {
+ padding-inline: 12px;
+ }
+ .kpi .value {
+ font-size: 25px;
+ }
}
-
- .hotspot .bar-entry {
- max-width: 100%;
+ @media (max-width: 1200px) {
+ .shell {
+ grid-template-columns: 166px minmax(0, 1fr);
+ }
+ .main {
+ padding: 22px;
+ }
+ .sidebar {
+ padding-inline: 12px;
+ }
+ #comparison > .two {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+ .metric-strip {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ }
}
-
- @media (max-width: 800px) {
- .trend-stats {
+ @media (max-width: 850px) {
+ .shell {
display: block;
}
-
- .trend-stats span {
+ .sidebar {
+ position: static;
+ height: auto;
+ padding: 12px 18px;
+ }
+ .sidebar strong,
+ .side-note {
+ display: none;
+ }
+ .sidebar nav {
+ display: flex;
+ gap: 6px;
+ overflow-x: auto;
+ margin-top: 8px;
+ }
+ .sidebar nav a {
+ flex: 0 0 auto;
+ padding: 6px 8px;
+ margin: 0;
+ }
+ .sidebar nav span {
+ width: 21px;
+ }
+ .main {
+ padding: 18px;
+ }
+ .footer {
+ flex-wrap: wrap;
+ }
+ }
+ @media (max-width: 600px) {
+ .main {
+ padding: 14px;
+ }
+ .topline {
+ align-items: flex-start;
+ flex-direction: column;
+ gap: 10px;
+ }
+ h1 {
+ font-size: 29px;
+ }
+ h1 span {
display: block;
- margin-top: 5px;
+ margin: 4px 0 0;
}
-
- .chart-control {
- padding: 0;
+ .meta {
+ gap: 8px 12px;
+ }
+ .kpis {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
-
- .chart-control output {
- font-size: 10px;
+ .kpi {
+ padding: 12px;
}
-
- .trend-chart svg text {
- font-size: 16px;
+ .kpi .value {
+ font-size: 26px;
}
-
- .interval-values {
- font-size: 10px;
+ .two,
+ .chart-grid,
+ #comparison > .two {
+ grid-template-columns: 1fr;
+ }
+ .section-head {
+ align-items: flex-start;
+ flex-direction: column;
+ gap: 5px;
+ }
+ .phase .section-head {
+ flex-direction: row;
+ }
+ .panel,
+ .phase {
+ padding: 12px;
+ }
+ .metric-strip {
+ gap: 8px;
+ }
+ .metric-strip b {
+ font-size: 11px;
+ }
+ .matrix-head {
+ align-items: flex-start;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .trend-chart {
+ padding: 9px;
}
-
.share-values b {
- font-size: 24px;
+ font-size: 26px;
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ html {
+ scroll-behavior: auto;
}
}
-
@media print {
+ body,
+ body.dark {
+ color-scheme: light;
+ --bg: #fff;
+ --card: #fff;
+ --surface: #f5f7fa;
+ --ink: #111;
+ --muted: #505967;
+ --line: #ccd2da;
+ --teal: #087e83;
+ --violet: #7055d0;
+ --warn: #956017;
+ --rose: #bd4264;
+ --soft: #e7f3f3;
+ background: #fff;
+ font-size: 10px;
+ }
+ .sidebar,
+ .actions,
+ .phase-buttons,
.chart-control {
display: none !important;
}
-
- .trend-chart {
+ .shell {
+ display: block;
+ }
+ .main {
+ padding: 0;
+ }
+ .kpis {
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ }
+ .kpi {
+ padding: 10px;
+ background: #fff;
+ }
+ .kpi::before {
+ box-shadow: none;
+ }
+ .kpi .value {
+ font-size: 24px;
+ }
+ .section {
+ margin-top: 20px;
+ }
+ .table-scroll {
+ overflow: visible;
+ }
+ .overview-matrix table {
+ font-size: 8px;
+ }
+ th,
+ td {
+ padding: 5px;
+ }
+ .overview-matrix :is(td, th):first-child {
+ position: static;
+ }
+ .two,
+ .chart-grid,
+ #comparison > .two {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+ .metric-strip {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ }
+ .panel,
+ .trend-chart,
+ .sample-summary,
+ .kpi,
+ .bar-group,
+ tr {
break-inside: avoid;
}
-
+ .phase,
+ details.panel {
+ break-inside: auto;
+ }
+ .trend-stats span {
+ font-size: 9px;
+ }
+ .bar-track,
.share-track,
- .share-values,
.interval-track,
- .interval-point {
- -webkit-print-color-adjust: exact;
+ .interval-point,
+ svg {
print-color-adjust: exact;
+ -webkit-print-color-adjust: exact;
+ }
+ a {
+ color: inherit;
}
}
</style>
@@ -1076,7 +1044,7 @@
<aside class="sidebar">
<div class="brand">PERFORMANCE LAB</div>
<strong>@@APP@@</strong>
- <nav>
+ <nav aria-label="报告章节">
<a href="#overview"><span>01</span>数据总览</a>
<a href="#comparison"><span>02</span>阶段对比</a>
<a href="#io"><span>03</span>唤醒与磁盘</a>
@@ -1085,34 +1053,20 @@
<a href="#events"><span>06</span>事件与热状态</a>
<a href="#environment"><span>07</span>采集记录</a>
</nav>
- <div class="side-note">@@PRESET@@<br />@@VERSION@@<br />Instruments</div>
+ <div class="side-note"><span>CAPTURE PROFILE</span>@@PRESET@@<br />@@VERSION@@<br />Instruments</div>
</aside>
<main class="main">
<header id="overview">
<div class="topline">
<span class="eyebrow">Runtime performance / @@PRESET@@</span>
<div class="actions">
- <button
- id="theme"
- type="button">
- 切换主题
- </button>
- <button
- id="download"
- type="button">
- 导出 JSON
- </button>
- <button
- id="print"
- type="button">
- 打印报告
- </button>
+ <button id="theme" type="button">深色主题</button>
+ <button id="download" type="button">导出 JSON</button>
+ <button id="print" type="button">打印报告</button>
</div>
</div>
- <h1>@@APP@@<br />性能数据报告</h1>
- <div class="meta">
- <span class="badge @@STATE_TONE@@">@@STATE@@</span><span>版本 @@VERSION@@</span><span>有效阶段 @@VALID@@ / @@PLANNED@@</span><span>@@STARTED@@</span>
- </div>
+ <h1>@@APP@@<span>性能数据报告</span></h1>
+ <div class="meta"><span class="badge @@STATE_TONE@@">@@STATE@@</span><span>@@STARTED@@</span></div>
<div class="hero-rule"></div>
<div class="kpis">
<div class="kpi">
@@ -1133,14 +1087,21 @@
<div class="kpi">
<div class="label">Hangs 记录</div>
<div class="value">@@HANGS@@<span class="unit">条</span></div>
- <small>采集阶段数:@@HANG_PHASES@@</small>
+ <small>覆盖 @@HANG_PHASES@@ 个阶段</small>
</div>
+ @@EXTRA_KPIS@@
</div>
+ <div class="overview-matrix">
+ <div class="matrix-head">
+ <h3>阶段指标矩阵</h3>
+ <span class="muted">FP = Footprint · N/A = 无数据 · CPU 100% = 1 个逻辑核心</span>
+ </div>
+ @@MATRIX@@
+ </div>
+ <div class="phase-buttons" role="group" aria-label="跳转至阶段曲线">@@PHASE_BUTTONS@@</div>
@@ERRORS@@
</header>
- <section
- id="comparison"
- class="section">
+ <section id="comparison" class="section">
<div class="section-head">
<div>
<div class="section-index">02 / COMPARISON</div>
@@ -1150,9 +1111,7 @@
</div>
<div class="two">@@COMPARISONS@@</div>
</section>
- <section
- id="io"
- class="section">
+ <section id="io" class="section">
<div class="section-head">
<div>
<div class="section-index">03 / RESOURCES</div>
@@ -1161,9 +1120,7 @@
</div>
<div class="two">@@IO_CHARTS@@</div>
</section>
- <section
- id="measurements"
- class="section">
+ <section id="measurements" class="section">
<div class="section-head">
<div>
<div class="section-index">04 / TIME SERIES</div>
@@ -1173,9 +1130,7 @@
</div>
@@PHASES@@
</section>
- <section
- id="hotspots"
- class="section">
+ <section id="hotspots" class="section">
<div class="section-head">
<div>
<div class="section-index">05 / CPU PROFILE</div>
@@ -1186,9 +1141,7 @@
<div class="two">@@HOT_OVERVIEW@@</div>
@@HOTSPOTS@@
</section>
- <section
- id="events"
- class="section">
+ <section id="events" class="section">
<div class="section-head">
<div>
<div class="section-index">06 / EVENTS</div>
@@ -1199,9 +1152,7 @@
@@EVENT_DETAILS@@
</section>
@@OPTIONAL@@
- <section
- id="environment"
- class="section">
+ <section id="environment" class="section">
<div class="section-head">
<div>
<div class="section-index">07 / RECORDS</div>
@@ -1227,9 +1178,7 @@
<footer class="footer"><span>@@APP@@ · Instruments</span><span>@@STARTED@@ — @@ENDED@@</span></footer>
</main>
</div>
- <script
- id="report-data"
- type="application/json">
+ <script id="report-data" type="application/json">
@@PAYLOAD@@
</script>
<script>
@@ -1241,6 +1190,8 @@
unit = chart.dataset.unit;
const svg = chart.querySelector('svg'),
input = chart.querySelector('input');
+ const plotLeft = Number(svg.dataset.plotLeft),
+ plotWidth = Number(svg.dataset.plotWidth);
const output = chart.querySelector('output'),
cursor = chart.querySelector('.cursor');
const start = points[0].t,
@@ -1249,7 +1200,7 @@
function select(index) {
const t = points[index].t,
value = points[index][key] ?? null,
- x = 68 + ((t - start) / Math.max(end - start, 1)) * 864;
+ x = plotLeft + ((t - start) / Math.max(end - start, 1)) * plotWidth;
cursor.removeAttribute('hidden');
cursor.setAttribute('x1', x);
cursor.setAttribute('x2', x);
@@ -1260,19 +1211,56 @@
input.addEventListener('input', () => select(Number(input.value)));
svg.addEventListener('pointermove', (event) => {
const rect = svg.getBoundingClientRect();
- const time = start + Math.max(0, Math.min(1, (((event.clientX - rect.left) / rect.width) * 960 - 68) / 864)) * (end - start);
+ const time = start + Math.max(0, Math.min(1, (((event.clientX - rect.left) / rect.width) * svg.viewBox.baseVal.width - plotLeft) / plotWidth)) * (end - start);
let index = 0;
for (let i = 1; i < points.length; i++) if (Math.abs(points[i].t - time) < Math.abs(points[index].t - time)) index = i;
select(index);
});
select(0);
});
- document.getElementById('theme').addEventListener('click', () => document.body.classList.toggle('dark'));
+ document.querySelectorAll('.phase-button').forEach((button) => {
+ button.addEventListener('click', () => {
+ const phase = document.getElementById(button.getAttribute('aria-controls'));
+ phase.focus({ preventScroll: true });
+ phase.scrollIntoView({ block: 'start' });
+ });
+ });
+ document.getElementById('theme').addEventListener('click', (event) => {
+ const dark = document.body.classList.toggle('dark');
+ event.currentTarget.textContent = dark ? '浅色主题' : '深色主题';
+ });
+ const navigation = [...document.querySelectorAll('.sidebar nav a')];
+ const sections = navigation.map((link) => document.querySelector(link.getAttribute('href')));
+ function updateNavigation() {
+ let active = 0;
+ sections.forEach((section, index) => {
+ if (section.getBoundingClientRect().top <= 100) active = index;
+ });
+ navigation.forEach((link, index) => {
+ link.classList.toggle('active', index === active);
+ if (index === active) link.setAttribute('aria-current', 'location');
+ else link.removeAttribute('aria-current');
+ });
+ }
+ let navigationPending = false;
+ window.addEventListener(
+ 'scroll',
+ () => {
+ if (navigationPending) return;
+ navigationPending = true;
+ requestAnimationFrame(() => {
+ updateNavigation();
+ navigationPending = false;
+ });
+ },
+ { passive: true },
+ );
+ updateNavigation();
document.getElementById('download').addEventListener('click', () => {
const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }));
const link = document.createElement('a');
link.href = url;
- link.download = 'performance-summary.json';
+ link.download = 'performance.json';
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
});
diff --git a/Scripts/performance/performance.py b/Scripts/performance/performance.py
new file mode 100644
index 0000000..7f68424
--- /dev/null
+++ b/Scripts/performance/performance.py
@@ -0,0 +1,797 @@
+"""Render a self-contained report with no remote resources or runtime dependencies"""
+
+import html
+import json
+import math
+from pathlib import Path
+
+
+def escape(value):
+ return html.escape(str(value))
+
+
+def number(value, digits=2, suffix=""):
+ return "N/A" if value is None else f"{value:,.{digits}f}{suffix}"
+
+
+def table(headers, rows):
+ head = "".join(f"<th>{escape(h)}</th>" for h in headers)
+ body = "".join(
+ "<tr>" + "".join(f"<td>{escape(c)}</td>" for c in row) + "</tr>" for row in rows
+ )
+ if not body:
+ body = f'<tr><td colspan="{len(headers)}" class="muted">无可用数据</td></tr>'
+ return f'<div class="table-scroll"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>'
+
+
+def chart(series, key, label, color, unit, phase_index, ceiling=None, step=False):
+ width, height, left, right, top, bottom = 640, 240, 60, 24, 32, 40
+ points = [p for p in series if p.get(key) is not None]
+ if not points:
+ return '<div class="empty">无可用采样数据</div>'
+ start, end = min(p["t"] for p in series), max(p["t"] for p in series)
+ peak = max(points, key=lambda p: p[key])
+ maximum = ceiling or nice_max(peak[key])
+ x = lambda t: left + (t - start) / max(end - start, 1) * (width - left - right)
+ y = lambda v: top + (1 - v / maximum) * (height - top - bottom)
+ parts = [
+ f'<div class="trend-chart" data-phase="{phase_index}" data-key="{escape(key)}" data-unit="{escape(unit)}">',
+ f'<div class="trend-stats"><b>{escape(label)}</b><span>最低 {number(min(p[key] for p in points))} · 峰值 {number(peak[key])} {escape(unit)}</span></div>',
+ f'<svg viewBox="0 0 {width} {height}" data-plot-left="{left}" data-plot-width="{width - left - right}" role="img" aria-label="{escape(label)}运行曲线">',
+ ]
+ for index in range(5):
+ value = maximum * index / 4
+ yy = y(value)
+ parts.append(
+ f'<line class="grid" x1="{left}" x2="{width - right}" y1="{yy:.2f}" y2="{yy:.2f}"/>'
+ )
+ parts.append(
+ f'<text x="{left - 10}" y="{yy + 4:.2f}" text-anchor="end">{value:g}</text>'
+ )
+ for index in range(6):
+ t = start + (end - start) * index / 5
+ parts.append(
+ f'<text x="{x(t):.2f}" y="{height - 10}" text-anchor="middle">{t:.0f}s</text>'
+ )
+ segments, current = [], []
+ previous = None
+ for point in series:
+ if point.get(key) is None or (
+ previous is not None and point["t"] - previous > 5
+ ):
+ if current:
+ segments.append(current)
+ current = []
+ if point.get(key) is not None:
+ current.append(point)
+ previous = point["t"]
+ if current:
+ segments.append(current)
+ for segment in segments:
+ path = f"M {x(segment[0]['t']):.2f} {y(segment[0][key]):.2f}"
+ for point in segment[1:]:
+ path += (
+ f" H {x(point['t']):.2f} V {y(point[key]):.2f}"
+ if step
+ else f" L {x(point['t']):.2f} {y(point[key]):.2f}"
+ )
+ parts.append(
+ f'<path d="{path} L {x(segment[-1]["t"]):.2f} {y(0):.2f} L {x(segment[0]["t"]):.2f} {y(0):.2f} Z" fill="{color}" opacity=".10"/>'
+ )
+ parts.append(
+ f'<path d="{path}" fill="none" stroke="{color}" stroke-width="2"/>'
+ )
+ if len(segment) == 1:
+ parts.append(
+ f'<circle cx="{x(segment[0]["t"]):.2f}" cy="{y(segment[0][key]):.2f}" r="3" fill="{color}"/>'
+ )
+ anchor = "end" if x(peak["t"]) > width / 2 else "start"
+ parts.append(
+ f'<circle cx="{x(peak["t"]):.2f}" cy="{y(peak[key]):.2f}" r="4" fill="{color}"/>'
+ )
+ parts.append(
+ f'<text x="{x(peak["t"]):.2f}" y="{y(peak[key]) - 10:.2f}" text-anchor="{anchor}">峰值 {peak[key]:.2f}</text>'
+ )
+ parts.append(
+ f'<line class="cursor" x1="{left}" x2="{left}" y1="{top}" y2="{height - bottom}" hidden/></svg>'
+ )
+ parts.append(
+ f'<div class="chart-control"><input aria-label="{escape(label)}采样点" type="range" min="0" max="{len(series) - 1}" value="0"><output></output></div></div>'
+ )
+ return "".join(parts)
+
+
+def nice_max(value):
+ if value <= 0:
+ return 1
+ magnitude = 10 ** math.floor(math.log10(value))
+ step = magnitude / 2
+ return math.ceil(value * 1.1 / step) * step
+
+
+COLORS = ["var(--teal)", "var(--violet)", "var(--warn)", "var(--rose)"]
+
+
+def bars(groups, unit="", digits=2):
+ values = [
+ value for _, entries in groups for _, value, _ in entries if value is not None
+ ]
+ low, high = min([0] + values), max([0] + values)
+ extent = high - low or 1
+ zero = -low / extent * 100
+ parts = ['<div class="bar-chart">']
+ for label, entries in groups:
+ parts.append(
+ f'<div class="bar-group"><div class="bar-label">{escape(label)}</div>'
+ )
+ for name, value, color in entries:
+ parts.append(
+ f'<div class="bar-entry"><span class="bar-series">{escape(name)}</span>'
+ )
+ if value is None:
+ parts.append(
+ '<div class="bar-track missing"></div><b class="bar-value">N/A</b>'
+ )
+ else:
+ position = (min(0, value) - low) / extent * 100
+ width = abs(value) / extent * 100
+ parts.append(
+ f'<div class="bar-track"><span class="zero" style="left:{zero:.4f}%"></span><i style="left:{position:.4f}%;width:{width:.4f}%;background:{color}" data-value="{value}"></i></div><b class="bar-value">{number(value, digits)} <small>{escape(unit)}</small></b>'
+ )
+ parts.append("</div>")
+ parts.append("</div>")
+ return (
+ "".join(parts)
+ + ('<div class="empty">无采集数据</div>' if not groups else "")
+ + "</div>"
+ )
+
+
+def ranked(items, unit="ms", color=COLORS[0], digits=0):
+ return bars([(label, [("", value, color)]) for label, value in items], unit, digits)
+
+
+def panel(title, content, note=""):
+ return (
+ '<article class="panel"><h3>'
+ + escape(title)
+ + "</h3>"
+ + ('<p class="muted">' + escape(note) + "</p>" if note else "")
+ + content
+ + "</article>"
+ )
+
+
+def distribution(main, total):
+ if not total:
+ return '<div class="empty">无 CPU 样本</div>'
+ ratio = main / total * 100
+ return f"""<div class="share-chart"><div class="share-track"><i style="width:{ratio:.4f}%;background:{COLORS[0]}"></i><i style="width:{100 - ratio:.4f}%;background:{COLORS[1]}"></i></div>
+<div class="share-values"><div><span>主线程</span><b>{ratio:.1f}%</b><small>{main:,.0f} ms</small></div><div><span>其他线程</span><b>{100 - ratio:.1f}%</b><small>{total - main:,.0f} ms</small></div></div></div>"""
+
+
+def interval_chart(rows, paired=False):
+ values = [v for _, entries in rows for v in entries if v is not None]
+ if not values:
+ return '<div class="empty">无可用数据</div>'
+ maximum = nice_max(max(values))
+ x = lambda value: 100 * value / maximum
+ parts = [
+ '<div class="interval-chart">',
+ '<div class="interval-axis"><span>0</span><span>'
+ + number(maximum, 0)
+ + " MiB</span></div>",
+ ]
+ for label, values in rows:
+ parts.append(f'<div class="interval-row"><b>{escape(label)}</b>')
+ if any(v is None for v in values):
+ parts.append('<span class="muted">N/A</span></div>')
+ continue
+ first, last = values[0], values[-1]
+ description = (
+ f"首段 {first:.1f} → 尾段 {last:.1f} MiB · 变化 {last - first:+.1f} MiB"
+ if paired
+ else f"最小 {first:.1f} · 中位 {values[1]:.1f} · 峰值 {last:.1f} MiB"
+ )
+ parts.append(
+ f'<div class="interval-track"><i class="interval-line" style="left:{x(min(first, last)):.4f}%;width:{x(abs(last - first)):.4f}%"></i>'
+ )
+ for i, value in enumerate(values):
+ kind = (
+ ("head" if i == 0 else "tail")
+ if paired
+ else ("median" if i == 1 else "bound")
+ )
+ parts.append(
+ f'<i class="interval-point {kind}" style="left:{x(value):.4f}%" title="{value:.2f} MiB"></i>'
+ )
+ parts.append(
+ '</div><span class="interval-values">' + description + "</span></div>"
+ )
+ parts.append(
+ '<div class="interval-key">'
+ + ("○ 首段 ● 尾段" if paired else "┃ 最小值 / 峰值 ● 中位数")
+ + "</div></div>"
+ )
+ return "".join(parts)
+
+
+def write_report(data, destination):
+ import collections
+ import re
+
+ phases = data.get("phases", [])
+ valid = [p for p in phases if p.get("resources") and not p.get("errors")]
+ target, env = data.get("target", {}), data.get("environment", {})
+ measured = sum(p.get("recorded_s", 0) for p in phases)
+ cpu_phases = [p for p in valid if p["resources"].get("cpu_mean") is not None]
+ cpu_durations = [
+ sum(point["dt"] for point in p["resources"]["series"] if point.get("cpu") is not None)
+ for p in cpu_phases
+ ]
+ span = sum(cpu_durations)
+ cpu_mean = (
+ sum(p["resources"]["cpu_mean"] * duration for p, duration in zip(cpu_phases, cpu_durations))
+ / span
+ if span
+ else None
+ )
+ footprints = [
+ p["resources"]["footprint"]["max"]
+ for p in valid
+ if p["resources"].get("footprint")
+ ]
+ hang_phases = [p for p in valid if "potential-hangs" in p]
+ hangs = (
+ sum(p["potential-hangs"]["count"] for p in hang_phases) if hang_phases else None
+ )
+ state = {
+ "complete": "采集完成",
+ "incomplete": "采集不完整",
+ "running": "采集中",
+ "interrupted": "采集已中断",
+ }.get(data.get("state"), "状态未知")
+ tone = "ok" if data.get("state") == "complete" else "warn"
+ if data.get("budget_breaches"):
+ state, tone = "超过配置预算", "warn"
+
+ def resource_peak(key, nested=None):
+ values = [
+ (p["resources"].get(key) or {}).get(nested)
+ if nested
+ else p["resources"].get(key)
+ for p in valid
+ ]
+ return max((value for value in values if value is not None), default=None)
+
+ extra_kpis = [
+ ("CPU 采样峰值", number(resource_peak("cpu_peak")), "%", "有效阶段最高采样值"),
+ ("RSS 峰值", number(resource_peak("rss", "max"), 1), "MiB", "驻留物理内存"),
+ (
+ "线程峰值",
+ number(resource_peak("threads", "max"), 0),
+ "个",
+ "有效阶段最大线程数",
+ ),
+ (
+ "资源采样点",
+ number(sum(p["resources"].get("samples", 0) for p in valid), 0),
+ "个",
+ "有效阶段累计样本",
+ ),
+ ]
+ extra_kpis_html = "".join(
+ f'<div class="kpi"><div class="label">{label}</div><div class="value">{value}<span class="unit">{unit}</span></div><small>{note}</small></div>'
+ for label, value, unit, note in extra_kpis
+ )
+ matrix_rows = []
+ phase_buttons = []
+ for index, phase in enumerate(phases):
+ r = phase.get("resources", {})
+ matrix_rows.append(
+ [
+ phase["id"],
+ number(r.get("cpu_mean")),
+ number(r.get("cpu_p50")),
+ number(r.get("cpu_p95")),
+ number(r.get("cpu_peak")),
+ number((r.get("footprint") or {}).get("max"), 1),
+ number((r.get("rss") or {}).get("max"), 1),
+ number((r.get("threads") or {}).get("max"), 0),
+ number(r.get("wakeups_per_s")),
+ number(
+ r.get("written_bytes") / 1024
+ if r.get("written_bytes") is not None
+ else None,
+ 1,
+ ),
+ "有效" if phase in valid else "部分数据",
+ ]
+ )
+ phase_buttons.append(
+ f'<button type="button" class="phase-button {"ok" if phase in valid else "warn"}" aria-controls="phase-{index}"><span>{escape(phase["id"])}</span><b>{number(phase.get("recorded_s"), 1)} s</b></button>'
+ )
+ matrix = table(
+ [
+ "阶段",
+ "CPU 均值 %",
+ "P50 %",
+ "P95 %",
+ "峰值 %",
+ "FP 峰值 MiB",
+ "RSS 峰值 MiB",
+ "线程峰值",
+ "唤醒 /s",
+ "写入 KiB",
+ "状态",
+ ],
+ matrix_rows,
+ )
+
+ def resource_groups(specification, scale=1):
+ groups = []
+ for phase in valid:
+ r = phase["resources"]
+ entries = []
+ for index, (label, key) in enumerate(specification):
+ value = r.get(key)
+ entries.append(
+ (label, value / scale if value is not None else None, COLORS[index])
+ )
+ groups.append((phase["id"], entries))
+ return groups
+
+ comparisons = [
+ panel("平均 CPU", bars(resource_groups([("均值", "cpu_mean")]), "%")),
+ panel(
+ "CPU P95 与峰值",
+ bars(resource_groups([("P95", "cpu_p95"), ("峰值", "cpu_peak")]), "%"),
+ ),
+ ]
+ memory_rows = [
+ (
+ p["id"],
+ [
+ (p["resources"].get("footprint") or {}).get(key)
+ for key in ("min", "median", "max")
+ ],
+ )
+ for p in valid
+ ]
+ comparisons.append(panel("内存 footprint 分布", interval_chart(memory_rows)))
+ trends = [
+ (p["id"], p["resources"]["memory_trend"])
+ for p in valid
+ if p["resources"].get("memory_trend")
+ ]
+ comparisons.append(
+ panel(
+ "footprint 首尾变化",
+ interval_chart(
+ [(name, [t["head_median"], t["tail_median"]]) for name, t in trends],
+ paired=True,
+ ),
+ "窗口长度为 60 秒与阶段跨度四分之一中的较小值",
+ )
+ )
+ comparisons.append(
+ panel(
+ "footprint 变化斜率",
+ ranked(
+ [(name, t["slope_mib_min"]) for name, t in trends], "MiB/min", digits=2
+ ),
+ "按阶段样本作最小二乘拟合",
+ )
+ )
+ comparisons.append(
+ panel(
+ "footprint 首尾差值",
+ ranked([(name, t["delta_mib"]) for name, t in trends], "MiB", digits=2),
+ "尾段窗口中位数减去首段窗口中位数",
+ )
+ )
+ io_charts = [
+ panel(
+ "Idle Wake Ups 速率",
+ bars(resource_groups([("均值", "wakeups_per_s")]), "次/s"),
+ ),
+ panel(
+ "磁盘读取与写入",
+ bars(
+ resource_groups(
+ [("读取", "read_bytes"), ("写入", "written_bytes")], 1024
+ ),
+ "KiB",
+ 1,
+ ),
+ ),
+ panel(
+ "磁盘平均吞吐",
+ bars(
+ resource_groups(
+ [("读取", "read_bytes_per_s"), ("写入", "written_bytes_per_s")],
+ 1024,
+ ),
+ "KiB/s",
+ ),
+ ),
+ panel(
+ "系统 CPU",
+ bars(
+ [
+ (
+ p["id"],
+ [
+ ("均值", p["system"].get("cpu_load_mean"), COLORS[0]),
+ ("峰值", p["system"].get("cpu_load_peak"), COLORS[1]),
+ ],
+ )
+ for p in valid
+ if p.get("system")
+ ],
+ "%",
+ 1,
+ ),
+ "各逻辑核心合计",
+ ),
+ ]
+ profiles = [p for p in valid if p.get("profile")]
+ total = sum(p["profile"]["sampled_ms"] for p in profiles)
+ main = sum(p["profile"]["main_ms"] for p in profiles)
+ libraries = collections.Counter()
+ for p in profiles:
+ for name, weight in p["profile"].get("binaries", []):
+ libraries[name] += weight
+ hot_overview = panel("主线程 CPU 样本分布", distribution(main, total)) + panel(
+ "叶节点所属库 · 已导出 Top 10", ranked(libraries.most_common(10))
+ )
+ phase_html, hotspot_html, record_rows, event_rows = [], [], [], []
+ ceilings = {
+ key: nice_max(
+ max(
+ [
+ point[key]
+ for p in phases
+ for point in p.get("resources", {}).get("series", [])
+ if point.get(key) is not None
+ ]
+ or [0]
+ )
+ )
+ for key in ("cpu", "footprint", "rss", "compressed", "threads")
+ }
+ for index, phase in enumerate(phases):
+ r = phase.get("resources", {})
+ content = f'<article class="phase" id="phase-{index}" tabindex="-1"><div class="section-head"><div><span class="eyebrow">{escape(phase["template"])}</span><h3>{escape(phase["id"])}</h3></div><span class="badge {"ok" if phase in valid else "warn"}">{"已采集" if phase in valid else "部分数据"}</span></div>'
+ content += f'<p class="muted">{escape(phase.get("trace_started", phase.get("started", "N/A")))} · {number(phase.get("recorded_s"), 2)} s</p>'
+ if r:
+ metrics = [
+ ("CPU 均值", number(r.get("cpu_mean"), 2, "%")),
+ (
+ "CPU P50 / P95",
+ number(r.get("cpu_p50"), 2)
+ + " / "
+ + number(r.get("cpu_p95"), 2, "%"),
+ ),
+ ("唤醒次数", number(r.get("wakeups"), 0)),
+ ("资源样本", number(r.get("samples"), 0)),
+ (
+ "CPU 采样覆盖",
+ number(
+ r.get("cpu_coverage") * 100
+ if r.get("cpu_coverage") is not None
+ else None,
+ 1,
+ "%",
+ ),
+ ),
+ ("最大采样间隔", number(r.get("max_gap_s"), 2, " s")),
+ ]
+ content += (
+ '<div class="metric-strip">'
+ + "".join(
+ f"<div><span>{escape(label)}</span><b>{escape(value)}</b></div>"
+ for label, value in metrics
+ )
+ + "</div>"
+ )
+ content += '<div class="chart-grid">' + chart(
+ r["series"], "cpu", "CPU", COLORS[0], "%", index, ceilings["cpu"]
+ )
+ for key, label, color in zip(
+ ["footprint", "rss", "compressed"],
+ ["Footprint", "RSS", "压缩内存"],
+ COLORS,
+ ):
+ content += chart(
+ r["series"], key, label, color, "MiB", index, ceilings[key]
+ )
+ content += chart(
+ r["series"],
+ "threads",
+ "线程数",
+ COLORS[1],
+ "个",
+ index,
+ ceilings["threads"],
+ step=True,
+ )
+ detail_rows = []
+ for key, label in [
+ ("footprint", "Footprint"),
+ ("rss", "RSS"),
+ ("compressed", "压缩内存"),
+ ]:
+ values = r.get(key) or {}
+ detail_rows.append(
+ [label]
+ + [number(values.get(k), 2) for k in ("first", "last", "median")]
+ )
+ content += (
+ '<div class="sample-summary"><h4>内存采样明细 <span class="muted">MiB</span></h4>'
+ + table(["指标", "首值", "尾值", "中位数"], detail_rows)
+ )
+ content += '<p class="muted">CPU 为区间使用率. 内存与线程为采样时刻值. 拖动滑块或移动指针查看单点数据</p></div></div>'
+ if phase.get("errors"):
+ content += (
+ '<div class="notice warn">'
+ + "<br>".join(escape(e) for e in phase["errors"])
+ + "</div>"
+ )
+ phase_html.append(content + "</article>")
+ profile = phase.get("profile")
+ if profile:
+ hot = f'<details class="panel hotspot" {"open" if index == 0 else ""}><summary>{escape(phase["id"])} · CPU 采样权重 {profile["sampled_ms"]:,.0f} ms</summary>'
+ hot += '<div class="two">' + panel(
+ "叶节点热点 · Top 12", ranked(profile["leaf"][:12])
+ )
+ hot += (
+ panel(
+ "调用链热点 · Top 12",
+ ranked(profile["inclusive"][:12], color=COLORS[1]),
+ "权重包含子调用",
+ )
+ + "</div>"
+ )
+ hot += '<div class="two">' + panel(
+ "高 CPU 采样权重的 1 秒区间",
+ ranked(
+ [
+ (f"{t}–{t + 1} s", value)
+ for t, value in profile["busiest_seconds"]
+ ]
+ ),
+ )
+ hot += (
+ panel(
+ "调用栈采样记录",
+ ranked(
+ [
+ (
+ "有调用栈",
+ profile["sampled_ms"] - profile["missing_stack_ms"],
+ ),
+ ("缺失调用栈", profile["missing_stack_ms"]),
+ ("含 App 帧", profile["app_stack_ms"]),
+ ("含命名 App 帧", profile["app_named_stack_ms"]),
+ ],
+ color=COLORS[2],
+ ),
+ )
+ + "</div>"
+ )
+ hot += "<details><summary>全部已导出热点</summary>" + table(
+ ["叶节点", "权重 / ms"],
+ [(name, number(weight, 0)) for name, weight in profile["leaf"]],
+ )
+ hot += (
+ table(
+ ["调用链", "权重 / ms"],
+ [
+ (name, number(weight, 0))
+ for name, weight in profile["inclusive"]
+ ],
+ )
+ + "</details></details>"
+ )
+ hotspot_html.append(hot)
+ record_rows.append(
+ [
+ phase["id"],
+ phase["template"],
+ number(phase.get("recorded_s"), 2, " s"),
+ r.get("samples", "N/A"),
+ number(r.get("max_gap_s"), 2, " s"),
+ number(
+ r.get("cpu_coverage") * 100
+ if r.get("cpu_coverage") is not None
+ else None,
+ 1,
+ "%",
+ ),
+ "已采集" if phase in valid else "部分数据",
+ ]
+ )
+ for key, label in [("potential-hangs", "Hangs"), ("hang-risks", "Hang risks")]:
+ for event in phase.get(key, {}).get("events", []):
+ event_rows.append(
+ [
+ phase["id"],
+ label,
+ " · ".join(f"{k}: {v}" for k, v in event.items()),
+ ]
+ )
+ events_chart = bars(
+ [
+ (
+ p["id"],
+ [
+ ("Hangs", p.get("potential-hangs", {}).get("count"), COLORS[0]),
+ ("Hang risks", p.get("hang-risks", {}).get("count"), COLORS[2]),
+ ],
+ )
+ for p in phases
+ ],
+ "条",
+ 0,
+ )
+ thermal = '<div class="thermal-grid">'
+ for p in phases:
+ events = p.get("device-thermal-state-intervals", {}).get("events", [])
+ thermal += f'<div class="thermal-phase"><b>{escape(p["id"])}</b>'
+ if not events:
+ thermal += '<span class="muted">N/A</span>'
+ for event in events:
+ state_name = event.get("thermal-state", "N/A")
+ thermal += f'<div class="thermal-state {"nominal" if state_name.lower() == "nominal" else "elevated"}"><b>{escape(state_name)}</b><span>{escape(event.get("start", ""))} → {escape(event.get("end", ""))}</span></div>'
+ thermal += "</div>"
+ thermal += "</div>"
+ metadata = [
+ ["App", target.get("name", "N/A")],
+ ["Bundle ID", target.get("bundle_id", "N/A")],
+ [
+ "版本 / 构建",
+ f"{target.get('version', 'N/A')} / {target.get('build', 'N/A')}",
+ ],
+ ["macOS / 架构", f"{env.get('os', 'N/A')} / {env.get('arch', 'N/A')}"],
+ ["芯片 / 逻辑核心", f"{env.get('chip', 'N/A')} / {env.get('cores', 'N/A')}"],
+ [
+ "内存",
+ number(int(env["memory_bytes"]) / 2**30, 0, " GiB")
+ if env.get("memory_bytes")
+ else "N/A",
+ ],
+ ["Instruments", env.get("instruments", "N/A")],
+ ["电源", env.get("power", "N/A")],
+ ["工作负载", data.get("config", {}).get("workload", "N/A")],
+ ]
+ fingerprint = [
+ ["App 文件指纹", target.get("binary_sha256", "N/A")],
+ [
+ "Mach-O UUID",
+ "; ".join(f"{arch}: {uuid}" for uuid, arch in target.get("uuids", [])),
+ ],
+ ]
+ load_groups = [
+ (
+ label,
+ [
+ ("开始", env.get("load_before", [None] * 3)[i], COLORS[0]),
+ ("结束", env.get("load_after", [None] * 3)[i], COLORS[1]),
+ ],
+ )
+ for i, label in enumerate(["1 分钟", "5 分钟", "15 分钟"])
+ ]
+ optional = ""
+ comparison = data.get("comparison")
+ if comparison:
+ optional += '<section class="section"><h2>历史基线差值</h2>'
+ if comparison.get("deltas"):
+ optional += '<div class="two">' + panel(
+ "平均 CPU 差值",
+ ranked(
+ [(r["phase"], r["cpu_pp"]) for r in comparison["deltas"]],
+ "百分点",
+ digits=2,
+ ),
+ )
+ optional += (
+ panel(
+ "footprint 中位数差值",
+ ranked(
+ [
+ (r["phase"], r["footprint_mib"])
+ for r in comparison["deltas"]
+ ],
+ "MiB",
+ digits=2,
+ ),
+ )
+ + "</div>"
+ )
+ else:
+ optional += table(
+ ["比较状态", "字段"],
+ [["条件不匹配", ", ".join(comparison.get("differences", []))]],
+ )
+ optional += "</section>"
+ budgets = data.get("config", {})
+ if (
+ budgets.get("cpu_mean_budget") is not None
+ or budgets.get("footprint_budget") is not None
+ ):
+ optional += (
+ '<section class="section"><h2>配置预算</h2>'
+ + table(
+ ["平均 CPU 上限", "footprint 峰值上限", "超出项"],
+ [
+ [
+ number(budgets.get("cpu_mean_budget"), 2, "%"),
+ number(budgets.get("footprint_budget"), 1, " MiB"),
+ ", ".join(data.get("budget_breaches", [])) or "0",
+ ]
+ ],
+ )
+ + "</section>"
+ )
+ portable = json.loads(json.dumps(data))
+ portable.get("target", {}).get("identity", {}).pop("path", None)
+ for phase in portable.get("phases", []):
+ phase.pop("commands", None)
+ payload = (
+ json.dumps(portable, ensure_ascii=False, allow_nan=False)
+ .replace("&", "\\u0026")
+ .replace("<", "\\u003c")
+ .replace(">", "\\u003e")
+ )
+ errors = data.get("errors", [])
+ replacements = {
+ "TITLE": escape(target.get("name", "App")) + " · 性能数据",
+ "APP": escape(target.get("name", "App")),
+ "STATE": state,
+ "STATE_TONE": tone,
+ "STARTED": escape(data.get("started", "N/A")),
+ "ENDED": escape(data.get("ended", "采集中")),
+ "PRESET": escape(data.get("config", {}).get("preset", "N/A")),
+ "VERSION": escape(
+ f"{target.get('version', 'N/A')} ({target.get('build', 'N/A')})"
+ ),
+ "MINUTES": number(measured / 60, 1),
+ "CPU": number(cpu_mean, 2),
+ "MEMORY": number(max(footprints) if footprints else None, 1),
+ "HANGS": str(hangs) if hangs is not None else "N/A",
+ "EXTRA_KPIS": extra_kpis_html,
+ "MATRIX": matrix,
+ "PHASE_BUTTONS": "".join(phase_buttons),
+ "HANG_PHASES": str(len(hang_phases)),
+ "ERRORS": '<div class="notice warn">'
+ + "<br>".join(escape(e) for e in errors)
+ + "</div>"
+ if errors
+ else "",
+ "COMPARISONS": "".join(comparisons),
+ "IO_CHARTS": "".join(io_charts),
+ "PHASES": "".join(phase_html),
+ "HOT_OVERVIEW": hot_overview,
+ "HOTSPOTS": "".join(hotspot_html),
+ "EVENTS": panel("Hangs / Hang risks", events_chart) + panel("热状态", thermal),
+ "EVENT_DETAILS": table(["阶段", "事件", "记录"], event_rows)
+ if event_rows
+ else "",
+ "RECORDS": table(
+ ["阶段", "模板", "记录时长", "样本数", "最大间隔", "CPU 采样覆盖", "状态"],
+ record_rows,
+ ),
+ "METADATA": table(["项目", "值"], metadata),
+ "FINGERPRINT": table(["字段", "值"], fingerprint),
+ "LOAD": bars(load_groups, "", 2),
+ "OPTIONAL": optional,
+ "PAYLOAD": payload,
+ }
+ template = Path(__file__).with_name("performance.html").read_text()
+ document = re.sub(r"@@([A-Z_]+)@@", lambda match: replacements[match[1]], template)
+ destination = Path(destination)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ temporary = destination.with_suffix(".html.tmp")
+ temporary.write_text(document)
+ temporary.replace(destination)
diff --git a/Scripts/performance/report.py b/Scripts/performance/report.py
deleted file mode 100644
index 90bbfec..0000000
--- a/Scripts/performance/report.py
+++ /dev/null
@@ -1,308 +0,0 @@
-"""Render a self-contained report with no remote resources or runtime dependencies"""
-
-import html
-import json
-import math
-from pathlib import Path
-
-
-def escape(value):
- return html.escape(str(value))
-
-
-def number(value, digits=2, suffix=""):
- return "N/A" if value is None else f"{value:,.{digits}f}{suffix}"
-
-
-def table(headers, rows):
- head = "".join(f"<th>{escape(h)}</th>" for h in headers)
- body = "".join("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in row) + "</tr>" for row in rows)
- if not body:
- body = f'<tr><td colspan="{len(headers)}" class="muted">无可用数据</td></tr>'
- return f'<div class="table-scroll"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>'
-
-
-def chart(series, key, label, color, unit, phase_index, ceiling=None, step=False):
- width, height, left, right, top, bottom = 960, 250, 68, 28, 32, 40
- points = [p for p in series if p.get(key) is not None]
- if not points:
- return '<div class="empty">无可用采样数据</div>'
- start, end = min(p["t"] for p in series), max(p["t"] for p in series)
- peak = max(points, key=lambda p: p[key])
- maximum = ceiling or nice_max(peak[key])
- x = lambda t: left + (t - start) / max(end - start, 1) * (width - left - right)
- y = lambda v: top + (1 - v / maximum) * (height - top - bottom)
- parts = [f'<div class="trend-chart" data-phase="{phase_index}" data-key="{escape(key)}" data-unit="{escape(unit)}">',
- f'<div class="trend-stats"><b>{escape(label)}</b><span>最低 {number(min(p[key] for p in points))} · 峰值 {number(peak[key])} {escape(unit)}</span></div>',
- f'<svg viewBox="0 0 {width} {height}">']
- for index in range(5):
- value = maximum * index / 4
- yy = y(value)
- parts.append(f'<line class="grid" x1="{left}" x2="{width - right}" y1="{yy:.2f}" y2="{yy:.2f}"/>')
- parts.append(f'<text x="{left - 10}" y="{yy + 4:.2f}" text-anchor="end">{value:g}</text>')
- for index in range(6):
- t = start + (end - start) * index / 5
- parts.append(f'<text x="{x(t):.2f}" y="{height - 10}" text-anchor="middle">{t:.0f}s</text>')
- segments, current = [], []
- previous = None
- for point in series:
- if point.get(key) is None or (previous is not None and point["t"] - previous > 5):
- if current:
- segments.append(current)
- current = []
- if point.get(key) is not None:
- current.append(point)
- previous = point["t"]
- if current:
- segments.append(current)
- for segment in segments:
- path = f'M {x(segment[0]["t"]):.2f} {y(segment[0][key]):.2f}'
- for point in segment[1:]:
- path += (f' H {x(point["t"]):.2f} V {y(point[key]):.2f}' if step else
- f' L {x(point["t"]):.2f} {y(point[key]):.2f}')
- parts.append(f'<path d="{path} L {x(segment[-1]["t"]):.2f} {y(0):.2f} L {x(segment[0]["t"]):.2f} {y(0):.2f} Z" fill="{color}" opacity=".10"/>')
- parts.append(f'<path d="{path}" fill="none" stroke="{color}" stroke-width="2"/>')
- if len(segment) == 1:
- parts.append(f'<circle cx="{x(segment[0]["t"]):.2f}" cy="{y(segment[0][key]):.2f}" r="3" fill="{color}"/>')
- anchor = "end" if x(peak["t"]) > width / 2 else "start"
- parts.append(f'<circle cx="{x(peak["t"]):.2f}" cy="{y(peak[key]):.2f}" r="4" fill="{color}"/>')
- parts.append(f'<text x="{x(peak["t"]):.2f}" y="{y(peak[key]) - 10:.2f}" text-anchor="{anchor}">峰值 {peak[key]:.2f}</text>')
- parts.append(f'<line class="cursor" x1="{left}" x2="{left}" y1="{top}" y2="{height - bottom}" hidden/></svg>')
- parts.append(f'<div class="chart-control"><input type="range" min="0" max="{len(series) - 1}" value="0"><output></output></div></div>')
- return "".join(parts)
-
-
-def nice_max(value):
- if value <= 0:
- return 1
- magnitude = 10 ** math.floor(math.log10(value))
- step = magnitude / 2
- return math.ceil(value * 1.1 / step) * step
-
-
-COLORS = ["#168c80", "#5668cb", "#bd812e", "#c96675"]
-
-
-def bars(groups, unit="", digits=2):
- values = [value for _, entries in groups for _, value, _ in entries if value is not None]
- low, high = min([0] + values), max([0] + values)
- extent = high - low or 1
- zero = -low / extent * 100
- parts = ['<div class="bar-chart">']
- for label, entries in groups:
- parts.append(f'<div class="bar-group"><div class="bar-label">{escape(label)}</div>')
- for name, value, color in entries:
- parts.append(f'<div class="bar-entry"><span class="bar-series">{escape(name)}</span>')
- if value is None:
- parts.append('<div class="bar-track missing"></div><b class="bar-value">N/A</b>')
- else:
- position = (min(0, value) - low) / extent * 100
- width = abs(value) / extent * 100
- parts.append(f'<div class="bar-track"><span class="zero" style="left:{zero:.4f}%"></span><i style="left:{position:.4f}%;width:{width:.4f}%;background:{color}" data-value="{value}"></i></div><b class="bar-value">{number(value, digits)} <small>{escape(unit)}</small></b>')
- parts.append('</div>')
- parts.append('</div>')
- return ''.join(parts) + ('<div class="empty">无采集数据</div>' if not groups else '') + '</div>'
-
-
-def ranked(items, unit="ms", color=COLORS[0], digits=0):
- return bars([(label, [("", value, color)]) for label, value in items], unit, digits)
-
-
-def panel(title, content, note=""):
- return '<article class="panel"><h3>' + escape(title) + '</h3>' + ('<p class="muted">' + escape(note) + '</p>' if note else '') + content + '</article>'
-
-
-def distribution(main, total):
- if not total:
- return '<div class="empty">无 CPU 样本</div>'
- ratio = main / total * 100
- return f'''<div class="share-chart"><div class="share-track"><i style="width:{ratio:.4f}%;background:{COLORS[0]}"></i><i style="width:{100 - ratio:.4f}%;background:{COLORS[1]}"></i></div>
-<div class="share-values"><div><span>主线程</span><b>{ratio:.1f}%</b><small>{main:,.0f} ms</small></div><div><span>其他线程</span><b>{100 - ratio:.1f}%</b><small>{total - main:,.0f} ms</small></div></div></div>'''
-
-
-def interval_chart(rows, paired=False):
- values = [v for _, entries in rows for v in entries if v is not None]
- if not values:
- return '<div class="empty">无可用数据</div>'
- maximum = nice_max(max(values))
- x = lambda value: 100 * value / maximum
- parts = ['<div class="interval-chart">', '<div class="interval-axis"><span>0</span><span>' + number(maximum, 0) + ' MiB</span></div>']
- for label, values in rows:
- parts.append(f'<div class="interval-row"><b>{escape(label)}</b>')
- if any(v is None for v in values):
- parts.append('<span class="muted">N/A</span></div>')
- continue
- first, last = values[0], values[-1]
- description = (f'首段 {first:.1f} → 尾段 {last:.1f} MiB · 变化 {last - first:+.1f} MiB' if paired else
- f'最小 {first:.1f} · 中位 {values[1]:.1f} · 峰值 {last:.1f} MiB')
- parts.append(f'<div class="interval-track"><i class="interval-line" style="left:{x(min(first, last)):.4f}%;width:{x(abs(last - first)):.4f}%"></i>')
- for i, value in enumerate(values):
- kind = ("head" if i == 0 else "tail") if paired else ("median" if i == 1 else "bound")
- parts.append(f'<i class="interval-point {kind}" style="left:{x(value):.4f}%" title="{value:.2f} MiB"></i>')
- parts.append('</div><span class="interval-values">' + description + '</span></div>')
- parts.append('<div class="interval-key">' + ('○ 首段 ● 尾段' if paired else '┃ 最小值 / 峰值 ● 中位数') + '</div></div>')
- return ''.join(parts)
-
-
-def write_report(data, destination):
- import collections
- import re
- phases = data.get("phases", [])
- valid = [p for p in phases if p.get("resources") and not p.get("errors")]
- target, env = data.get("target", {}), data.get("environment", {})
- measured = sum(p.get("recorded_s", 0) for p in phases)
- cpu_phases = [p for p in valid if p["resources"].get("cpu_mean") is not None]
- span = sum(p["resources"]["span_s"] for p in cpu_phases)
- cpu_mean = sum(p["resources"]["cpu_mean"] * p["resources"]["span_s"] for p in cpu_phases) / span if span else None
- footprints = [p["resources"]["footprint"]["max"] for p in valid if p["resources"].get("footprint")]
- hang_phases = [p for p in valid if "potential-hangs" in p]
- hangs = sum(p["potential-hangs"]["count"] for p in hang_phases) if hang_phases else None
- state = {"complete": "采集完成", "incomplete": "采集不完整", "running": "采集中", "interrupted": "采集已中断"}.get(data.get("state"), "状态未知")
- tone = "ok" if data.get("state") == "complete" else "warn"
- if data.get("budget_breaches"):
- state, tone = "超过配置预算", "warn"
-
- def resource_groups(specification, scale=1):
- groups = []
- for phase in valid:
- r = phase["resources"]
- entries = []
- for index, (label, key) in enumerate(specification):
- value = r.get(key)
- entries.append((label, value / scale if value is not None else None, COLORS[index]))
- groups.append((phase["id"], entries))
- return groups
-
- comparisons = [panel("平均 CPU", bars(resource_groups([("均值", "cpu_mean")]), "%")),
- panel("CPU P95 与峰值", bars(resource_groups([("P95", "cpu_p95"), ("峰值", "cpu_peak")]), "%"))]
- memory_rows = [(p["id"], [(p["resources"].get("footprint") or {}).get(key)
- for key in ("min", "median", "max")]) for p in valid]
- comparisons.append(panel("内存 footprint 分布", interval_chart(memory_rows)))
- trends = [(p["id"], p["resources"]["memory_trend"]) for p in valid if p["resources"].get("memory_trend")]
- comparisons.append(panel("footprint 首尾变化", interval_chart([(name, [t["head_median"], t["tail_median"]])
- for name, t in trends], paired=True),
- "窗口长度为 60 秒与阶段跨度四分之一中的较小值"))
- comparisons.append(panel("footprint 变化斜率", ranked([(name, t["slope_mib_min"]) for name, t in trends], "MiB/min", digits=2),
- "按阶段样本作最小二乘拟合"))
- comparisons.append(panel("footprint 首尾差值", ranked([(name, t["delta_mib"]) for name, t in trends], "MiB", digits=2),
- "尾段窗口中位数减去首段窗口中位数"))
- io_charts = [panel("Idle Wake Ups 速率", bars(resource_groups([("均值", "wakeups_per_s")]), "次/s")),
- panel("磁盘读取与写入", bars(resource_groups([("读取", "read_bytes"), ("写入", "written_bytes")], 1024), "KiB", 1)),
- panel("磁盘平均吞吐", bars(resource_groups([("读取", "read_bytes_per_s"), ("写入", "written_bytes_per_s")], 1024), "KiB/s")),
- panel("系统 CPU", bars([(p["id"], [("均值", p["system"].get("cpu_load_mean"), COLORS[0]),
- ("峰值", p["system"].get("cpu_load_peak"), COLORS[1])])
- for p in valid if p.get("system")], "%", 1), "各逻辑核心合计")]
- profiles = [p for p in valid if p.get("profile")]
- total = sum(p["profile"]["sampled_ms"] for p in profiles)
- main = sum(p["profile"]["main_ms"] for p in profiles)
- libraries = collections.Counter()
- for p in profiles:
- for name, weight in p["profile"].get("binaries", []):
- libraries[name] += weight
- hot_overview = panel("主线程 CPU 样本分布", distribution(main, total)) + panel("叶节点所属库 · 已导出 Top 10", ranked(libraries.most_common(10)))
- phase_html, hotspot_html, record_rows, event_rows = [], [], [], []
- ceilings = {key: nice_max(max([point[key] for p in phases for point in p.get("resources", {}).get("series", [])
- if point.get(key) is not None] or [0]))
- for key in ("cpu", "footprint", "rss", "compressed", "threads")}
- for index, phase in enumerate(phases):
- r = phase.get("resources", {})
- content = f'<article class="phase" id="phase-{index}"><div class="section-head"><div><span class="eyebrow">{escape(phase["template"])}</span><h3>{escape(phase["id"])}</h3></div><span class="badge {"ok" if phase in valid else "warn"}">{"已采集" if phase in valid else "部分数据"}</span></div>'
- content += f'<p class="muted">{escape(phase.get("trace_started", phase.get("started", "N/A")))} · {number(phase.get("recorded_s"), 2)} s</p>'
- if r:
- content += chart(r["series"], "cpu", "CPU", COLORS[0], "%", index, ceilings["cpu"])
- for key, label, color in zip(["footprint", "rss", "compressed"], ["Footprint", "RSS", "压缩内存"], COLORS):
- content += chart(r["series"], key, label, color, "MiB", index, ceilings[key])
- content += chart(r["series"], "threads", "线程数", COLORS[1], "个", index, ceilings["threads"], step=True)
- metrics = [("CPU P50", number(r.get("cpu_p50"), 2, "%")), ("CPU P95", number(r.get("cpu_p95"), 2, "%")),
- ("唤醒次数", number(r.get("wakeups"), 0)), ("资源样本", str(r["samples"]))]
- content += '<div class="metric-strip">' + ''.join(f'<div><span>{escape(label)}</span><b>{escape(value)}</b></div>' for label, value in metrics) + '</div>'
- if phase.get("errors"):
- content += '<div class="notice warn">' + '<br>'.join(escape(e) for e in phase["errors"]) + '</div>'
- phase_html.append(content + '</article>')
- profile = phase.get("profile")
- if profile:
- hot = f'<details class="panel hotspot" {"open" if index == 0 else ""}><summary>{escape(phase["id"])} · CPU 采样权重 {profile["sampled_ms"]:,.0f} ms</summary>'
- hot += '<div class="two">' + panel("叶节点热点 · Top 12", ranked(profile["leaf"][:12]))
- hot += panel("调用链热点 · Top 12", ranked(profile["inclusive"][:12], color=COLORS[1]), "权重包含子调用") + '</div>'
- hot += '<div class="two">' + panel("高 CPU 采样权重的 1 秒区间", ranked([(f"{t}–{t + 1} s", value) for t, value in profile["busiest_seconds"]]))
- hot += panel("调用栈采样记录", ranked([("有调用栈", profile["sampled_ms"] - profile["missing_stack_ms"]),
- ("缺失调用栈", profile["missing_stack_ms"]),
- ("含 App 帧", profile["app_stack_ms"]),
- ("含命名 App 帧", profile["app_named_stack_ms"])], color=COLORS[2])) + '</div>'
- hot += '<details><summary>全部已导出热点</summary>' + table(["叶节点", "权重 / ms"], [(name, number(weight, 0)) for name, weight in profile["leaf"]])
- hot += table(["调用链", "权重 / ms"], [(name, number(weight, 0)) for name, weight in profile["inclusive"]]) + '</details></details>'
- hotspot_html.append(hot)
- record_rows.append([phase["id"], phase["template"], number(phase.get("recorded_s"), 2, " s"),
- r.get("samples", "N/A"), number(r.get("max_gap_s"), 2, " s"),
- number(r.get("cpu_coverage") * 100 if r.get("cpu_coverage") is not None else None, 1, "%"),
- "已采集" if phase in valid else "部分数据"])
- for key, label in [("potential-hangs", "Hangs"), ("hang-risks", "Hang risks")]:
- for event in phase.get(key, {}).get("events", []):
- event_rows.append([phase["id"], label, ' · '.join(f'{k}: {v}' for k, v in event.items())])
- events_chart = bars([(p["id"], [("Hangs", p.get("potential-hangs", {}).get("count"), COLORS[0]),
- ("Hang risks", p.get("hang-risks", {}).get("count"), COLORS[2])]) for p in phases], "条", 0)
- thermal = '<div class="thermal-grid">'
- for p in phases:
- events = p.get("device-thermal-state-intervals", {}).get("events", [])
- thermal += f'<div class="thermal-phase"><b>{escape(p["id"])}</b>'
- if not events:
- thermal += '<span class="muted">N/A</span>'
- for event in events:
- state_name = event.get("thermal-state", "N/A")
- thermal += f'<div class="thermal-state {"nominal" if state_name.lower() == "nominal" else "elevated"}"><b>{escape(state_name)}</b><span>{escape(event.get("start", ""))} → {escape(event.get("end", ""))}</span></div>'
- thermal += '</div>'
- thermal += '</div>'
- metadata = [["App", target.get("name", "N/A")], ["Bundle ID", target.get("bundle_id", "N/A")],
- ["版本 / 构建", f'{target.get("version", "N/A")} / {target.get("build", "N/A")}'],
- ["macOS / 架构", f'{env.get("os", "N/A")} / {env.get("arch", "N/A")}'],
- ["芯片 / 逻辑核心", f'{env.get("chip", "N/A")} / {env.get("cores", "N/A")}'],
- ["内存", number(int(env["memory_bytes"]) / 2 ** 30, 0, " GiB") if env.get("memory_bytes") else "N/A"],
- ["Instruments", env.get("instruments", "N/A")], ["电源", env.get("power", "N/A")],
- ["工作负载", data.get("config", {}).get("workload", "N/A")]]
- fingerprint = [["App 文件指纹", target.get("binary_sha256", "N/A")],
- ["Mach-O UUID", '; '.join(f'{arch}: {uuid}' for uuid, arch in target.get("uuids", []))]]
- load_groups = [(label, [("开始", env.get("load_before", [None] * 3)[i], COLORS[0]),
- ("结束", env.get("load_after", [None] * 3)[i], COLORS[1])])
- for i, label in enumerate(["1 分钟", "5 分钟", "15 分钟"])]
- optional = ''
- comparison = data.get("comparison")
- if comparison:
- optional += '<section class="section"><h2>历史基线差值</h2>'
- if comparison.get("deltas"):
- optional += '<div class="two">' + panel("平均 CPU 差值", ranked([(r["phase"], r["cpu_pp"]) for r in comparison["deltas"]], "百分点", digits=2))
- optional += panel("footprint 中位数差值", ranked([(r["phase"], r["footprint_mib"]) for r in comparison["deltas"]], "MiB", digits=2)) + '</div>'
- else:
- optional += table(["比较状态", "字段"], [["条件不匹配", ', '.join(comparison.get("differences", []))]])
- optional += '</section>'
- budgets = data.get("config", {})
- if budgets.get("cpu_mean_budget") is not None or budgets.get("footprint_budget") is not None:
- optional += '<section class="section"><h2>配置预算</h2>' + table(["平均 CPU 上限", "footprint 峰值上限", "超出项"], [[
- number(budgets.get("cpu_mean_budget"), 2, "%"), number(budgets.get("footprint_budget"), 1, " MiB"), ', '.join(data.get("budget_breaches", [])) or "0"]]) + '</section>'
- portable = json.loads(json.dumps(data))
- portable.get("target", {}).get("identity", {}).pop("path", None)
- for phase in portable.get("phases", []):
- phase.pop("commands", None)
- payload = json.dumps(portable, ensure_ascii=False, allow_nan=False).replace("&", "\\u0026").replace("<", "\\u003c").replace(">", "\\u003e")
- errors = data.get("errors", [])
- replacements = {"TITLE": escape(target.get("name", "App")) + " · 性能数据", "APP": escape(target.get("name", "App")),
- "STATE": state, "STATE_TONE": tone, "STARTED": escape(data.get("started", "N/A")),
- "ENDED": escape(data.get("ended", "采集中")), "PRESET": escape(data.get("config", {}).get("preset", "N/A")),
- "VERSION": escape(f'{target.get("version", "N/A")} ({target.get("build", "N/A")})'),
- "MINUTES": number(measured / 60, 1), "CPU": number(cpu_mean, 2),
- "MEMORY": number(max(footprints) if footprints else None, 1), "HANGS": str(hangs) if hangs is not None else "N/A",
- "HANG_PHASES": str(len(hang_phases)), "VALID": str(len(valid)), "PLANNED": str(len(data.get("plan", []))),
- "ERRORS": '<div class="notice warn">' + '<br>'.join(escape(e) for e in errors) + '</div>' if errors else '',
- "COMPARISONS": ''.join(comparisons), "IO_CHARTS": ''.join(io_charts), "PHASES": ''.join(phase_html),
- "HOT_OVERVIEW": hot_overview, "HOTSPOTS": ''.join(hotspot_html),
- "EVENTS": panel("Hangs / Hang risks", events_chart) + panel("热状态", thermal),
- "EVENT_DETAILS": table(["阶段", "事件", "记录"], event_rows) if event_rows else '',
- "RECORDS": table(["阶段", "模板", "记录时长", "样本数", "最大间隔", "CPU 计数覆盖", "状态"], record_rows),
- "METADATA": table(["项目", "值"], metadata), "FINGERPRINT": table(["字段", "值"], fingerprint),
- "LOAD": bars(load_groups, "", 2), "OPTIONAL": optional, "PAYLOAD": payload}
- template = Path(__file__).with_name("report.html").read_text()
- document = re.sub(r"@@([A-Z_]+)@@", lambda match: replacements[match[1]], template)
- destination = Path(destination)
- destination.parent.mkdir(parents=True, exist_ok=True)
- temporary = destination.with_suffix(".html.tmp")
- temporary.write_text(document)
- temporary.replace(destination)
diff --git a/Scripts/performance/test_analyze.py b/Scripts/performance/test_analyze.py
new file mode 100644
index 0000000..5ae0f86
--- /dev/null
+++ b/Scripts/performance/test_analyze.py
@@ -0,0 +1,92 @@
+"""Regression checks for interval-based CPU measurements"""
+
+import tempfile
+import unittest
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+from .analyze import Table, resource_summary
+from .performance import write_report
+
+
+class ResourceSummaryTests(unittest.TestCase):
+ def summarize(self, samples):
+ root = ET.Element("trace-query-result")
+ for start, duration, cpu in samples:
+ row = ET.SubElement(root, "row")
+ for tag, value in [("pid", 42), ("start-time", start * 1e9),
+ ("duration", duration * 1e9 if duration is not None else None),
+ ("system-cpu-percent", cpu)]:
+ cell = ET.SubElement(row, tag if value is not None else "sentinel")
+ if value is not None:
+ cell.text = str(value)
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "resources.xml"
+ ET.ElementTree(root).write(path)
+ return resource_summary(Table(path, ["pid", "start", "duration", "cpu-percent"]), 42)
+
+ def test_unequal_intervals_use_native_cpu_and_current_duration(self):
+ result = self.summarize([(0, .5, None), (.5, 2, 20), (2.5, .5, 80)])
+ self.assertEqual(result["cpu_mean"], 32)
+ self.assertEqual(result["cpu_p50"], 50)
+ self.assertEqual(result["cpu_p95"], 77)
+ self.assertEqual(result["cpu_peak"], 80)
+ self.assertEqual(result["series"][1]["dt"], 2)
+ self.assertAlmostEqual(result["cpu_coverage"], 2.5 / 3)
+ self.assertEqual(result["errors"], [])
+
+ def test_first_sample_and_multicore_cpu_are_retained(self):
+ result = self.summarize([(0, 1, 200), (1, 1, 0), (2, 1, 100)])
+ self.assertEqual(result["cpu_mean"], 100)
+ self.assertEqual(result["cpu_peak"], 200)
+ self.assertEqual(result["cpu_coverage"], 1)
+
+ def test_missing_and_nonfinite_cpu_are_not_zero(self):
+ for missing in [None, float("nan"), float("inf")]:
+ with self.subTest(missing=missing):
+ result = self.summarize([(0, 1, 20), (1, 2, missing), (3, 1, 40)])
+ self.assertEqual(result["cpu_mean"], 30)
+ self.assertEqual(result["cpu_coverage"], .5)
+ self.assertIsNone(result["series"][1]["cpu"])
+
+ def test_gap_reduces_coverage(self):
+ result = self.summarize([(0, 1, 20), (2, 1, 20), (3, 1, 20)])
+ self.assertEqual(result["cpu_coverage"], .75)
+
+ def test_invalid_duration_is_rejected(self):
+ for duration in [None, 0, -1, float("inf")]:
+ with self.subTest(duration=duration):
+ result = self.summarize([(0, 1, 20), (1, duration, 90), (2, 1, 20)])
+ self.assertEqual(result["cpu_mean"], 20)
+ self.assertIsNone(result["series"][1]["cpu"])
+ self.assertTrue(result["errors"])
+
+ def test_overlapping_intervals_and_negative_cpu_are_rejected(self):
+ for middle in [(1, 2, 90), (2, 1, -10)]:
+ with self.subTest(middle=middle):
+ result = self.summarize([(0, 2, 20), middle, (3, 1, 20)])
+ self.assertEqual(result["cpu_mean"], 20)
+ self.assertIsNone(result["series"][1]["cpu"])
+ self.assertTrue(result["errors"])
+
+ def test_all_missing_cpu_stays_unavailable(self):
+ result = self.summarize([(0, 1, None), (1, 1, None), (2, 1, None)])
+ self.assertIsNone(result["cpu_mean"])
+ self.assertIsNone(result["cpu_peak"])
+ self.assertEqual(result["cpu_coverage"], 0)
+
+ def test_report_mean_uses_valid_cpu_duration(self):
+ phases = [
+ {"id": "a", "template": "Activity Monitor", "resources":
+ self.summarize([(0, 1, None), (1, 1, 10), (2, 1, 10)])},
+ {"id": "b", "template": "Activity Monitor", "resources":
+ self.summarize([(0, 1, None), (1, 2, 20), (3, 2, 20)])},
+ ]
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "report.html"
+ write_report({"state": "complete", "phases": phases}, path)
+ self.assertIn('16.67<span class="unit">%</span>', path.read_text())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/appcast.xml b/appcast.xml
index 3441e03..0508d35 100644
--- a/appcast.xml
+++ b/appcast.xml
@@ -7,6 +7,15 @@
<link>https://codexbar.zabrian.app/appcast.xml</link>
<description>CodexBar appcast feed</description>
<language>zh-CN</language>
+ <item>
+ <title>CodexBar.app 4.0.0</title>
+ <sparkle:version>100</sparkle:version>
+ <sparkle:shortVersionString>4.0.0</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#4.0.0</sparkle:releaseNotesLink>
+ <pubDate>Mon, 14 Sep 2026 12:00:04 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v4.0.0.dmg" sparkle:edSignature="xokwKgzxP89UUEoIUopS+Xz6ENBQXcCYTyFwghnnYMGhAMXCCiYFCbIBwTGvf6hCFJ2SB5xe32kTNlKRJOzCBQ==" length="8031904" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.7.6</title>
<sparkle:version>90</sparkle:version>