Skip to content

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

feat: 优化菜单栏任务状态与额度展示

Bob20156539cc9f
diff --git a/CLAUDE.md b/CLAUDE.md
index dd94dfa..b45cabf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -177,8 +177,8 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 首次读取在 `start()` 里单独判一次并记 `stage=start` 这条,不能改走 `refresh()` 那条路:后者按变化过滤,而读数初始值就是 `unreadable` 本身,首读失败会被静默吞掉,之后只留下一条没有配对失败行的恢复日志
- 防睡眠上限累计的是**真正挡住睡眠**的那段时间,`begin` 起表 `pause` 收表,收表之后机器睡着或被低电量拦下都不占用户的上限
- 上限计时用 `SuspendingClock` 而不是 `Date`,后者受系统时间调整影响且系统睡眠期间照走;排计时器的 `Task.sleep` 同样要传 `SuspendingClock`,否则睡一夜醒来会当场判定到期
-- 低电量是**纯条件**判定,不设“低过电”的粘滞标志:电量会回升,充上电就该自动恢复防睡眠;`hasReachedMaximumDuration` 之所以是粘滞标志只因为累计只增不减,两者不要照抄
-- 低电量必须同时满足在用电池与电量低于阈值,只看百分比会让“剩 5% 插上电再跑任务”当场被判低电量;判定用 `Power Source State`,不能用 `Is Charging`(接电停充时它也是 `false`)
+- 低电量判断使用 `isLowBatteryActive` 记录滞回状态;电池供电且电量不高于阈值时进入,达到阈值加 5 个百分点或接通电源时解除。时长上限由 `hasReachedMaximumDuration` 保持到下一轮任务或设置变化
+- 供电来源读取 `Power Source State`;接电停充时 `Is Charging` 为 `false`,不能用于判断是否正在使用电池
- 电量读不到时维持上一次的判定,从没读到过就是不触发:误触发会当场断掉用户任务,漏触发最坏也有系统强制睡眠兜底
- 已经在低电量保护中时读数失败不清零,否则一次瞬时失败会绕过滞回,让防睡眠反复开关并重发通知
- 低电量通知只在 `isActivelyPreventingSleep` 为真且来源是 `codexBar` 时排队,外部来源不说“已恢复系统睡眠”;日志无条件记并用 `action=release|none` 区分,百分比只有那一条能看到
@@ -189,16 +189,15 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 触发与解除用 `阈值` 与 `阈值 + 5%` 两道门槛,否则电量在阈值附近抖动会反复切 pmset,合盖时还会反复补发 `IOPMSleepSystem`
- 一轮低电量通知的终点是电量回到 `阈值 + 5%` 或者用户改了阈值,由 `hasNotifiedLowBattery` 记住;只看是否接电会让适配器接触不良时每翻一次供电状态就重发一条
- `hasNotifiedLowBattery` 只在通知真的提交成功之后才置位,打在入队处或提交前都会让没送达的那一条吃掉整轮配额,使这一轮之后真正触发的低电量再也提醒不了
-- `hasNotifiedLowBattery` 只管通知不管判定,与上面“纯条件”不冲突:电量回到解除门槛以下再跌破仍算同一轮,不会重复提醒
- `SleepConditions` 里只放 `battery` 布尔,放电量百分比会让每掉 1% 刷一条变化日志;真实电量只在触发那一条单独记
-- 状态只呈现在主面板活动卡片右侧的咖啡杯标记(带 tooltip),由 `KeepAliveController.isActivelyPreventingSleep` 驱动,`sleepPreventionSource` 区分外部来源与 CodexBar 所有权,卡片折叠成“暂无数据”时标记要跟着一起收
+- 防睡眠生效且活动卡片数据可用时,右侧显示青绿色 `sun.max.fill`,使用 `.symbolEffect(.rotate.byLayer, options: .repeat(.continuous))` 持续旋转;tooltip 按 `sleepPreventionSource` 区分外部来源与 CodexBar
- 设置页那一行说明只在异常、外部来源、低电量生效或达到上限时出现,CodexBar 自己正常持有所有权时整行收起,`keepAliveCaption` 返回 `nil` 即代表收起
- 最长防睡眠时间、异常会话保护阈值与低电量阈值都在防睡眠子面板里,台式机读不到电池时低电量那一行整行隐藏而不是置灰
- 保持屏幕常亮跟 `isActivelyPreventingSleep` 走,由 `reconcileDisplayAwake` 单点切换,于是低电量拦下、达到上限、任务结束时屏幕都跟着放开
- 显示断言只保证屏幕不睡,屏保与闲置锁屏跟的是系统 idle 计时,要靠 30 秒一次的 `IOPMAssertionDeclareUserActivity` 压住,两者缺一不可
- 声明用户活动复用同一个 assertion ID,每次传 `null` 会新建一条,`pmset -g assertions` 里会堆成一串同名断言
- 逐次声明不记日志,建立与释放各一条就够还原状态;两条断言都是进程级的,App 退出或崩溃时系统自动收回,不经过 helper
-- **菜单栏图标不承载防睡眠状态**,它要保持模板渲染让系统按菜单栏外观着色,自行着色在深浅和带染色的菜单栏下都会失控
+- 菜单栏由 `StatusItemIconView` 绘制人物符号和额度圆弧,并挂载在原生 `NSStatusBarButton` 中。人物使用系统前景色,圆弧使用 `QuotaPalette`;防睡眠状态只显示在活动卡片
### 自动重置
@@ -257,7 +256,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 成对的操作要留成对的日志,例如 XPC 的发送与回复各记一条并带同一个 `generation`,缺一条就说明请求丢在途中
- 耗时用 `LogDuration` 取,只加在收尾那一条上
- `Logger` 的插值是 autoclosure,里面直接访问属性会被要求显式 `self`,而 `.swiftformat` 配了 `--self remove`,两边会打架;把属性先取到局部常量再插值即可,不需要 lint 豁免
-- 账号有效时 `rate limits` 和 `usage` 允许单独失败,复用同账号旧缓存并标记 `stale`,UI 显示为半透明,无缓存则该区域不显示;账号变化时整体丢弃缓存避免串号
+- 账户有效时,额度和用量请求可以分别失败;同账户缓存标为 `stale` 并降低透明度。可见的数据区域均无数据时,在其中第一个区域显示“暂无数据”;Hook 开启时用量区域可保留本地统计。账户变化时清空补充缓存
- 各 Settings 类把读取类错误与操作类错误分开存储,定时 `refresh` 不能抹掉用户操作或校验的结论,参见 `CodexHookSettings` 与 `KeepAliveController`
- Hook 子进程任何失败都静默退出,优先保证不拖慢 Codex
@@ -289,8 +288,8 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 设置子面板的内容工厂必须走 `SettingsOptionsPanelController.makeContentController(_:rebuiltBy:)`,否则首次展开时原生 Switch 只剩一条空轨道;重建信号由它接在内容外面,内容视图不必知道 `SidePanelEntryCue`
- 原因是 thumb 由 `WindowPortal` 投射而不是画在开关上,面板首次布局那一轮 portal 建不起来,而且不会自愈,只有一次内容重建才补得上;第二次展开正常是因为 hosting controller 常驻,复用了已经建好的那份
- 开关首次绘制由内容重建处理;`SidePanelSupport` 中的 `@_optimize(none)` 用于规避编译器崩溃
-- 主面板的账户、任务中心、额度、Token 用量和底部状态由 `MainPanelSettings.layout` 统一保存顺序与显隐,模型始终保留至少一个区域;Hook 关闭时 `StatusItemController` 调用 `updateHookEnabled(_:)` 持久化关闭任务中心,任务中心原本是唯一可见区域时同步开启账户;设置面板只禁用任务中心开关,不能连带禁用拖拽手柄
-- 主面板布局排序由手柄上的自定义 `DragGesture` 驱动,悬浮副本跟手移动,其他行按预览顺序实时让位,松手后才通过 `setSectionOrder(_:)` 保存最终顺序;不要改回只在落点命中后换位的 `.draggable` 和 `.dropDestination`
+- `MainPanelSettings.layout` 保存主面板区域顺序与显隐,至少保留一个区域。`updateHookEnabled(_:)` 在 Hook 关闭时隐藏任务区域,必要时开启账户;从关闭切换为开启时显示任务区域,启动恢复开启状态时保留用户布局。Hook 关闭时任务开关禁用,拖拽手柄可用
+- 主面板布局排序由手柄上的自定义 `DragGesture` 驱动,悬浮副本跟手移动,其他行按预览顺序实时让位,松手后才通过 `setSectionOrder(_:)` 保存最终顺序
- 热力图详情面板跟随包含标题和方格矩阵的完整热力图区域定位,优先让两者顶边对齐;详情面板过高时通过 `SidePanelSupport.anchoredPosition` 上移到与主面板底边对齐,不能恢复为固定贴住主面板底边
- `SettingsWindowController` 持有窗口组唯一的 `UndoManager`,设置主窗口和四个可聚焦子面板必须共享这一撤销栈,保证焦点切换后 `⌘Z` 与 `⌘⇧Z` 仍然有效;Hook 自动联动不注册为用户操作
- 设置窗口高度跟随当前 tab 的完整内容,只在内容超过屏幕可见高度时允许滚动;首次构造时 SwiftUI 可能早于 `HostingWindowController.window` 赋值上报高度,`SettingsWindowController` 必须缓存最近测量并在窗口就绪后应用,不能用初始高度或延迟掩盖
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index 8cfd017..b1d63d7 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -274,7 +274,7 @@ final class SettingsWindowController: HostingWindowController {
optionsDismissedByClick = (panel, event)
}
handleOptionsAction(.closeAll)
- // 保留到本次 mouseUp 分发完成, 避免影响之后的辅助功能按钮动作
+ // 保留到本次 mouseUp 分发完成, 避免影响之后的按钮动作
DispatchQueue.main.async { [weak self] in
if self?.optionsDismissedByClick?.event === event {
self?.optionsDismissedByClick = nil
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 1dc411c..ff680bb 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -105,7 +105,9 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private var menuSurfaceState = MenuSurfaceState.hidden
private var cancellables = Set<AnyCancellable>()
private var statusIconState: StatusIconState?
- private var statusIconAnimationTask: Task<Void, Never>?
+ private let statusIconPresentation = StatusItemIconPresentation()
+ private var statusIconHostingView: StatusItemIconHostingView?
+ private var statusIconExpirationTask: Task<Void, Never>?
private var statusToolTipTask: Task<Void, Never>?
private var registeredHotKeyShortcut: GlobalHotKeyShortcut?
private var auxiliaryWindowFocusRestoreTask: Task<Void, Never>?
@@ -145,195 +147,22 @@ final class StatusItemController: NSObject, NSMenuDelegate {
super.init()
}
- /// 无状态点和额度条时使用模板渲染, 由系统按菜单栏外观着色
- private static func makeStatusImage(
- _ symbolName: String,
- indicatorTint: NSColor?,
- indicatorVisibility: CGFloat = 1,
- progress: StatusIconProgress?,
- progressVisibility: CGFloat = 1
- ) -> NSImage? {
- guard let symbolImage = makeStatusSymbolImage(symbolName) else {
- return nil
- }
-
- let usesTemplateRendering = indicatorTint == nil && progress == nil
- let statusImage = NSImage(size: Metrics.progressStatusImageSize, flipped: false) { _ in
- Self.drawStatusSymbol(
- symbolImage,
- in: Metrics.progressStatusSymbolRect,
- tint: usesTemplateRendering ? .black : .labelColor,
- alpha: progress?.isStale == true ? Metrics.staleIconAlpha : 1
- )
- if let progress {
- Self.drawProgress(
- progress,
- visibility: progressVisibility
- )
- }
- if let indicatorTint {
- Self.drawStatusIndicator(
- tint: indicatorTint,
- visibility: indicatorVisibility
- )
- }
- return true
- }
- statusImage.isTemplate = usesTemplateRendering
- statusImage.alignmentRect = Self.statusImageAlignmentRect(for: symbolImage)
- return statusImage
- }
-
- private static func makeStatusSymbolImage(_ symbolName: String) -> NSImage? {
- let configuration = NSImage.SymbolConfiguration(
- pointSize: 16,
- weight: .regular,
- scale: .medium
- )
- return NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)?
- .withSymbolConfiguration(configuration)
- }
-
- private static func drawStatusSymbol(
- _ image: NSImage,
- in rect: NSRect,
- tint: NSColor,
- alpha: CGFloat
- ) {
- NSGraphicsContext.saveGraphicsState()
- tint.withAlphaComponent(alpha).setFill()
- rect.fill()
- image.draw(
- in: rect,
- from: .zero,
- operation: .destinationIn,
- fraction: 1
- )
- NSGraphicsContext.restoreGraphicsState()
- }
-
- private static func drawStatusIndicator(
- tint: NSColor,
- visibility: CGFloat
- ) {
- let visibility = clampedVisibility(visibility)
- guard visibility > 0 else {
- return
- }
-
- tint.withAlphaComponent(visibility).setFill()
- NSBezierPath(ovalIn: Metrics.statusIndicatorRect).fill()
- }
-
- private static func statusImageAlignmentRect(for symbolImage: NSImage) -> NSRect {
- NSRect(
- x: 0,
- y: symbolImage.alignmentRect.minY,
- width: Metrics.progressStatusImageSize.width,
- height: symbolImage.alignmentRect.height
- )
- }
-
- private static func drawProgress(
- _ progress: StatusIconProgress,
- visibility: CGFloat
- ) {
- let visibility = clampedVisibility(visibility)
- guard visibility > 0 else {
- return
- }
-
- let trackRect = Metrics.progressTrackRect
- let cornerRadius = Metrics.progressTrackCornerRadius
- let progressAlpha = (progress.isStale ? Metrics.staleProgressAlpha : 1) * visibility
- NSColor.tertiaryLabelColor
- .withAlphaComponent(Metrics.progressTrackAlpha * progressAlpha)
- .setFill()
- NSBezierPath(
- roundedRect: trackRect,
- xRadius: cornerRadius,
- yRadius: cornerRadius
- )
- .fill()
-
- let fillHeight = trackRect.height * CGFloat(progress.percent) / 100
- guard fillHeight > 0 else {
- return
- }
-
- let fillRect = NSRect(
- x: trackRect.minX,
- y: trackRect.minY,
- width: trackRect.width,
- height: fillHeight
- )
- QuotaPalette.nsColor(for: progress.percent)
- .withAlphaComponent(progressAlpha)
- .setFill()
- NSBezierPath(
- roundedRect: fillRect,
- xRadius: cornerRadius,
- yRadius: cornerRadius
- )
- .fill()
- }
-
- private static func clampedVisibility(_ value: CGFloat) -> CGFloat {
- min(max(value, 0), 1)
- }
-
- /// 色彩空间转换失败时 blended 返回 nil, 统一退到较近的一端
- private static func blendedColor(
- _ source: NSColor,
- _ destination: NSColor,
- progress: CGFloat
- ) -> NSColor {
- let progress = clampedVisibility(progress)
- return source.blended(withFraction: progress, of: destination)
- ?? (progress < 0.5 ? source : destination)
- }
-
- /// 图标动画中一条 0↔1 的过渡: 起止由布尔状态决定, 按动画进度取中间值
- private static func transitionValue(
- from source: Bool,
- to destination: Bool,
- progress: CGFloat
- ) -> CGFloat {
- let start: CGFloat = source ? 1 : 0
- let end: CGFloat = destination ? 1 : 0
- return start + (end - start) * progress
- }
-
- private static func easedVisibility(_ value: CGFloat) -> CGFloat {
- let value = clampedVisibility(value)
- return value * value * (3 - 2 * value)
- }
-
private struct StatusIconState: Equatable {
let usesErrorImage: Bool
let progress: StatusIconProgress?
let activity: CodexActivitySnapshot
- var symbolName: String {
- usesErrorImage ? Metrics.errorStatusSymbolName : Metrics.normalStatusSymbolName
- }
-
- var indicator: ActivityIndicator? {
- switch activity.primaryActivity {
- case .waiting:
- .waiting
- case .running:
- .running
- case .completed(_, highlighted: true):
- .completed
- case .completed, .terminated, .idle:
- nil
+ func symbolName(at now: Date) -> String {
+ if usesErrorImage {
+ return "person.slash.fill"
+ }
+ switch activity.statusItemActivity(at: now) {
+ case .waiting: return "person.badge.key.fill"
+ case .running: return "person.badge.clock.fill"
+ case .completed: return "person.badge.shield.checkmark.fill"
+ case .terminated: return "person.badge.shield.exclamationmark.fill"
+ case .idle: return "person.fill"
}
- }
-
- /// 只包含影响图像像素的字段; tooltip 文本变化不应触发重绘
- var renderState: StatusIconRenderState {
- StatusIconRenderState(symbolName: symbolName, indicator: indicator, progress: progress)
}
var hasLiveDuration: Bool {
@@ -361,7 +190,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
}
private func activityToolTip(at now: Date) -> String? {
- switch activity.primaryActivity {
+ switch activity.statusItemActivity(at: now) {
case let .waiting(task):
var text = String(localized: "activity.status.codex-waiting-for-approval")
if let projectName = task.projectName {
@@ -381,7 +210,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
text += " • \(CodexActivityDisplayFormat.runningDurationFragment(since: startedAt, now: now))"
}
return text
- case .completed(let completion, highlighted: true):
+ case let .completed(completion):
var text = String(localized: "activity.status.codex-just-completed")
if let projectName = completion.projectName {
text += " • \(projectName)"
@@ -390,33 +219,21 @@ final class StatusItemController: NSObject, NSMenuDelegate {
text += " • \(CodexActivityDisplayFormat.elapsedDurationFragment(for: duration))"
}
return text
- case .completed, .terminated, .idle:
+ case let .terminated(termination):
+ var text = String(localized: "activity.status.codex-stopped")
+ if let projectName = termination.projectName {
+ text += " • \(projectName)"
+ }
+ if let duration = termination.duration {
+ text += " • \(CodexActivityDisplayFormat.elapsedDurationFragment(for: duration))"
+ }
+ return text
+ case .idle:
return nil
}
}
}
- /// 状态图标中影响像素的渲染子状态, 用于跳过 tooltip-only 变化引发的重绘
- private struct StatusIconRenderState: Equatable {
- let symbolName: String
- let indicator: ActivityIndicator?
- let progress: StatusIconProgress?
- }
-
- private enum ActivityIndicator: Equatable {
- case waiting
- case running
- case completed
-
- var color: NSColor {
- switch self {
- case .waiting: .systemOrange
- case .running: .systemBlue
- case .completed: .systemGreen
- }
- }
- }
-
private struct StatusIconProgress: Equatable {
let label: String
let percent: Int
@@ -458,7 +275,9 @@ final class StatusItemController: NSObject, NSMenuDelegate {
func uninstall() {
closeMenuSurface(animated: false)
auxiliaryWindowFocusRestoreTask?.cancel()
- statusIconAnimationTask?.cancel()
+ statusIconExpirationTask?.cancel()
+ statusIconHostingView?.removeFromSuperview()
+ statusIconHostingView = nil
statusToolTipTask?.cancel()
workflowSyncScheduler.cancel()
setAuxiliaryWindowKeyFocus(true)
@@ -491,6 +310,27 @@ final class StatusItemController: NSObject, NSMenuDelegate {
button.imagePosition = .imageOnly
button.imageScaling = .scaleNone
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
+
+ // 让系统按图像宽度计算留白, 固定 statusItem 长度会额外扩大实际占位
+ button.image = NSImage(size: StatusItemIconView.size, flipped: false) { _ in true }
+ let hostingView = StatusItemIconHostingView(rootView: StatusItemIconView(presentation: statusIconPresentation))
+ hostingView.translatesAutoresizingMaskIntoConstraints = false
+ button.addSubview(hostingView)
+ NSLayoutConstraint.activate([
+ hostingView.centerXAnchor.constraint(equalTo: button.centerXAnchor),
+ hostingView.centerYAnchor.constraint(equalTo: button.centerYAnchor),
+ hostingView.widthAnchor.constraint(equalToConstant: StatusItemIconView.size.width),
+ hostingView.heightAnchor.constraint(equalToConstant: StatusItemIconView.size.height)
+ ])
+ statusIconHostingView = hostingView
+
+ NSWorkspace.shared.notificationCenter.publisher(for: NSWorkspace.didWakeNotification)
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] _ in
+ self?.refreshStatusIconPresentation(animated: false)
+ self?.scheduleStatusIconExpiration()
+ }
+ .store(in: &cancellables)
}
private func configurePopover() {
@@ -714,94 +554,45 @@ final class StatusItemController: NSObject, NSMenuDelegate {
// MARK: - 菜单栏图标
private func updateStatusImage(_ state: StatusIconState) {
- statusItem.button?.toolTip = state.toolTip(at: Date())
-
- guard state != statusIconState else {
- return
- }
-
let previousState = statusIconState
+ guard previousState != state else { return }
statusIconState = state
if previousState?.hasLiveDuration != state.hasLiveDuration {
configureStatusToolTipRefresh(for: state)
}
-
- guard let previousState else {
- statusIconAnimationTask?.cancel()
- renderStatusImage(state)
- return
- }
- // tooltip-only 变化不重绘, 也不打断进行中的图标动画
- guard previousState.renderState != state.renderState else {
- return
- }
- statusIconAnimationTask?.cancel()
-
- let progressVisibilityChanged = (previousState.progress == nil) != (state.progress == nil)
- if previousState.indicator != state.indicator || progressVisibilityChanged {
- animateStatusImage(from: previousState, to: state)
- return
- }
-
- renderStatusImage(state)
+ refreshStatusIconPresentation(animated: previousState != nil)
+ scheduleStatusIconExpiration()
}
- private func renderStatusImage(_ state: StatusIconState) {
- statusItem.button?.image = Self.makeStatusImage(
- state.symbolName,
- indicatorTint: state.indicator?.color,
- progress: state.progress
+ private func refreshStatusIconPresentation(animated: Bool = true) {
+ guard let state = statusIconState else { return }
+ let now = Date()
+ let toolTip = state.toolTip(at: now)
+ statusItem.button?.toolTip = toolTip
+ statusIconPresentation.update(
+ symbolName: state.symbolName(at: now),
+ percent: state.progress?.percent,
+ isStale: state.progress?.isStale ?? false,
+ animated: animated
)
}
- private func animateStatusImage(from previousState: StatusIconState, to finalState: StatusIconState) {
- let renderedProgress = finalState.progress ?? previousState.progress
-
- statusIconAnimationTask = Task { @MainActor [weak self] in
- for frame in 0 ... Metrics.statusIconAnimationFrameCount {
- guard let self,
- !Task.isCancelled,
- statusIconState?.renderState == finalState.renderState else {
- return
- }
-
- let rawProgress = CGFloat(frame) / CGFloat(Metrics.statusIconAnimationFrameCount)
- let easedProgress = Self.easedVisibility(rawProgress)
- statusItem.button?.image = Self.makeStatusImage(
- finalState.symbolName,
- indicatorTint: Self.interpolatedIndicatorTint(
- from: previousState.indicator,
- to: finalState.indicator,
- progress: easedProgress
- ),
- indicatorVisibility: Self.transitionValue(
- from: previousState.indicator != nil,
- to: finalState.indicator != nil,
- progress: easedProgress
- ),
- progress: renderedProgress,
- progressVisibility: Self.transitionValue(
- from: previousState.progress != nil,
- to: finalState.progress != nil,
- progress: easedProgress
- )
- )
-
- if frame < Metrics.statusIconAnimationFrameCount {
- try? await Task.sleep(
- nanoseconds: Metrics.statusIconAnimationFrameDelayNanoseconds
- )
- }
- }
-
- guard let self,
- !Task.isCancelled,
- statusIconState?.renderState == finalState.renderState else {
+ /// 终态提示按墙上时间到期, 即使没有后续 Hook 事件也会恢复普通图标
+ private func scheduleStatusIconExpiration() {
+ statusIconExpirationTask?.cancel()
+ statusIconExpirationTask = nil
+ guard let expiration = statusIconState?.activity.statusItemActivityExpiration else { return }
+ let delay = expiration.timeIntervalSinceNow
+ guard delay > 0 else { return }
+ statusIconExpirationTask = Task { @MainActor [weak self] in
+ do {
+ try await Task.sleep(for: .seconds(delay))
+ } catch {
return
}
-
- renderStatusImage(finalState)
- statusIconAnimationTask = nil
+ guard let self, !Task.isCancelled else { return }
+ refreshStatusIconPresentation()
+ scheduleStatusIconExpiration()
}
}
@@ -821,27 +612,11 @@ final class StatusItemController: NSObject, NSMenuDelegate {
state.hasLiveDuration else {
return
}
- statusItem.button?.toolTip = state.toolTip(at: Date())
+ refreshStatusIconPresentation()
}
}
}
- private static func interpolatedIndicatorTint(
- from source: ActivityIndicator?,
- to destination: ActivityIndicator?,
- progress: CGFloat
- ) -> NSColor? {
- switch (source, destination) {
- case let (source?, destination?):
- // 只在两端都有指示点时混色; 单端的显隐交给 indicatorVisibility
- blendedColor(source.color, destination.color, progress: progress)
- case let (indicator?, nil), let (nil, indicator?):
- indicator.color
- case (nil, nil):
- nil
- }
- }
-
@objc private func statusItemClicked(_ sender: NSStatusBarButton) {
guard let event = NSApplication.shared.currentEvent else {
toggleMenuSurface(relativeTo: sender)
@@ -1361,44 +1136,11 @@ final class StatusItemController: NSObject, NSMenuDelegate {
}
private enum Metrics {
- static let normalStatusSymbolName = "person.fill.checkmark"
- static let errorStatusSymbolName = "person.fill.xmark"
static let fadeInDuration: TimeInterval = 0.24
static let fadeOutDuration: TimeInterval = 0.18
static let auxiliaryWindowKeyFocusRestoreDelayMilliseconds: UInt64 = 120
static let minimumTrustedAnchorLength: CGFloat = 1
static let anchorScreenTolerance: CGFloat = 1
- static let progressStatusSymbolSize = NSSize(width: 24, height: 17)
- static let progressStatusExtraWidth: CGFloat = 3
- static let progressStatusContentOffsetX: CGFloat = 1
- static let progressStatusImageSize = NSSize(
- width: progressStatusSymbolSize.width + progressStatusExtraWidth,
- height: progressStatusSymbolSize.height
- )
- static let progressStatusSymbolRect = NSRect(
- x: progressStatusExtraWidth + progressStatusContentOffsetX,
- y: 0,
- width: progressStatusSymbolSize.width,
- height: progressStatusSymbolSize.height
- )
- static let progressTrackRect = NSRect(
- x: 0.5 + progressStatusContentOffsetX,
- y: 1,
- width: 2,
- height: 15
- )
- static let progressTrackCornerRadius: CGFloat = 1
- static let progressTrackAlpha: CGFloat = 0.34
- static let statusIndicatorRect = NSRect(x: 21.5, y: 1, width: 5, height: 5)
- static let staleIconAlpha: CGFloat = 0.75
- static let staleProgressAlpha: CGFloat = 0.55
- static let statusIconAnimationDuration: TimeInterval = 0.18
- static let statusIconAnimationFrameCount = 10
- static let statusIconAnimationFrameDelayNanoseconds = UInt64(
- statusIconAnimationDuration
- / Double(statusIconAnimationFrameCount)
- * 1000000000
- )
}
private enum MenuSurfaceState {
diff --git a/CodexBar/Models/CodexActivityModels.swift b/CodexBar/Models/CodexActivityModels.swift
index 24475a6..a891208 100644
--- a/CodexBar/Models/CodexActivityModels.swift
+++ b/CodexBar/Models/CodexActivityModels.swift
@@ -78,14 +78,12 @@ nonisolated struct CodexActivitySnapshot: Equatable {
let runningTasks: [CodexActivityTaskSnapshot]
let recentCompletions: [CodexActivityCompletion]
let recentTerminations: [CodexActivityTermination]
- let isCompletionHighlighted: Bool
static let empty = CodexActivitySnapshot(
waitingTasks: [],
runningTasks: [],
recentCompletions: [],
- recentTerminations: [],
- isCompletionHighlighted: false
+ recentTerminations: []
)
var primaryWaitingTask: CodexActivityTaskSnapshot? {
@@ -124,7 +122,7 @@ nonisolated struct CodexActivitySnapshot: Equatable {
hasActiveTasks || !recentCompletions.isEmpty || !recentTerminations.isEmpty
}
- /// 等待批准 > 运行中 > 最近完成 > 最近终止 > 空闲; 菜单栏图标, tooltip 和活动卡片共用同一判定
+ /// 活动卡片优先展示等待批准和运行中任务, 空闲时保留最近完成或终止记录
var primaryActivity: CodexPrimaryActivity {
if let task = primaryWaitingTask {
return .waiting(task)
@@ -133,20 +131,49 @@ nonisolated struct CodexActivitySnapshot: Equatable {
return .running(task)
}
if let completion = mostRecentCompletion {
- return .completed(completion, highlighted: isCompletionHighlighted)
+ return .completed(completion)
}
if let termination = mostRecentTermination {
return .terminated(termination)
}
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)
+ }
+ return .idle
+ }
+
+ var statusItemActivityExpiration: Date? {
+ guard !hasActiveTasks else { return nil }
+ return [mostRecentCompletion?.completedAt, mostRecentTermination?.terminatedAt]
+ .compactMap(\.self)
+ .max()?
+ .addingTimeInterval(30)
+ }
}
-/// 快照归一后的主活动状态, highlighted 表示完成仍处于高亮时间窗内
+/// 快照归一后的主活动状态
nonisolated enum CodexPrimaryActivity: Equatable {
case waiting(CodexActivityTaskSnapshot)
case running(CodexActivityTaskSnapshot)
- case completed(CodexActivityCompletion, highlighted: Bool)
+ case completed(CodexActivityCompletion)
case terminated(CodexActivityTermination)
case idle
}
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index cf707de..5094854 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -1766,7 +1766,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "CodexBar Helper must be installed and authorized to run in the background"
+ "value" : "Install CodexBar Helper and allow background activity"
}
},
"zh-Hans" : {
@@ -1782,7 +1782,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "CodexBar Helper is installed but still needs authorization to run in the background"
+ "value" : "CodexBar Helper installed. Allow background activity"
}
},
"zh-Hans" : {
@@ -1862,7 +1862,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex Hook was disabled, but its trust state could not be cleared"
+ "value" : "Codex Hook disabled. Trust cleanup failed"
}
},
"zh-Hans" : {
@@ -2262,7 +2262,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "CodexBar Helper has invalid components or configuration. Please reinstall CodexBar"
+ "value" : "Helper validation failed. Reinstall CodexBar"
}
},
"zh-Hans" : {
@@ -2278,7 +2278,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "CodexBar Helper is missing components or configuration. Please reinstall CodexBar"
+ "value" : "Helper incomplete. Reinstall CodexBar"
}
},
"zh-Hans" : {
@@ -3206,13 +3206,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "A task in \"%@\" is waiting for approval to continue"
+ "value" : "A task in \"%@\" is waiting for action approval"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "「%@」正在等待批准下一步操作"
+ "value" : "「%@」正在等待批准操作"
}
}
}
@@ -3782,7 +3782,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "app-server did not exit in time and was force-quit"
+ "value" : "app-server exit timed out; process killed"
}
},
"zh-Hans" : {
@@ -3798,7 +3798,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "app-server did not exit in time and may still be running"
+ "value" : "app-server exit timed out; may still be running"
}
},
"zh-Hans" : {
diff --git a/CodexBar/Services/Settings/MainPanelSettings.swift b/CodexBar/Services/Settings/MainPanelSettings.swift
index aae57f9..335e52e 100644
--- a/CodexBar/Services/Settings/MainPanelSettings.swift
+++ b/CodexBar/Services/Settings/MainPanelSettings.swift
@@ -97,17 +97,24 @@ final class MainPanelSettings: ObservableObject {
}
func updateHookEnabled(_ isEnabled: Bool) {
+ let wasEnabled = isHookEnabled
isHookEnabled = isEnabled
- guard !isEnabled else {
- return
+ let updatedLayout: MainPanelLayout
+ if isEnabled {
+ // 首次恢复 Hook 状态时保留布局, 只有关闭到开启的转换才自动显示任务
+ guard wasEnabled == false else { return }
+ updatedLayout = MainPanelLayout(
+ orderedSections: layout.orderedSections,
+ hiddenSections: layout.hiddenSections.subtracting([.activity])
+ )
+ } else {
+ updatedLayout = layout.disablingActivitySection()
}
-
- let updatedLayout = layout.disablingActivitySection()
guard updatedLayout != layout else {
return
}
- AppLog.settings.notice("Hook 关闭已同步主面板任务中心")
+ AppLog.settings.notice("Hook 开关已同步主面板任务中心")
saveAndPublish(updatedLayout)
}
diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
index 8563ca3..36959c9 100644
--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift
+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
@@ -1167,22 +1167,18 @@ final class CodexActivityMonitor: ObservableObject {
let runningTasks = sortedTasks(in: .running)
let recentCompletions = completions.sorted(by: Self.recentFirst(\.completedAt, \.id))
let recentTerminations = terminations.sorted(by: Self.recentFirst(\.terminatedAt, \.id))
- let mostRecentCompletion = recentCompletions.first
let newSnapshot = CodexActivitySnapshot(
waitingTasks: waitingTasks.map(\.snapshot),
runningTasks: runningTasks.map(\.snapshot),
recentCompletions: recentCompletions,
- recentTerminations: recentTerminations,
- isCompletionHighlighted: mostRecentCompletion.map {
- now < $0.completedAt.addingTimeInterval(Self.completionHighlightDuration)
- } ?? false
+ recentTerminations: recentTerminations
)
if newSnapshot != snapshot {
snapshot = newSnapshot
}
- scheduleNextCleanup(now: now, mostRecentCompletion: mostRecentCompletion)
+ scheduleNextCleanup(now: now)
scheduleNextInactivityCheck(now: now)
}
@@ -1241,10 +1237,7 @@ final class CodexActivityMonitor: ObservableObject {
}
}
- private func scheduleNextCleanup(
- now: Date,
- mostRecentCompletion: CodexActivityCompletion?
- ) {
+ private func scheduleNextCleanup(now: Date) {
var deadlines = tasks.values.map {
$0.lastActivityAt.addingTimeInterval(Self.activityRetention)
}
@@ -1265,13 +1258,6 @@ final class CodexActivityMonitor: ObservableObject {
$0.addingTimeInterval(Self.activityRetention)
})
deadlines.append(contentsOf: activityProtectionRecords.values.map(\.expiresAt))
- if let mostRecentCompletion {
- let highlightDeadline = mostRecentCompletion.completedAt
- .addingTimeInterval(Self.completionHighlightDuration)
- if highlightDeadline > now {
- deadlines.append(highlightDeadline)
- }
- }
guard let nextDeadline = deadlines.filter({ $0 > now }).min() else {
cleanupTask?.cancel()
@@ -1296,7 +1282,6 @@ final class CodexActivityMonitor: ObservableObject {
}
}
- private static let completionHighlightDuration: TimeInterval = 30
private static let recentHistoryRetention: TimeInterval = 10 * 60
static let completedTaskRetention: TimeInterval = 24 * 60 * 60
static let activityRetention = CodexActivityRetention.window
diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swift
index 838f851..5f3cfa4 100644
--- a/CodexBar/Views/Menu/CodexActivityCard.swift
+++ b/CodexBar/Views/Menu/CodexActivityCard.swift
@@ -92,9 +92,10 @@ struct CodexActivityCard: View {
if showsKeepAliveBadge {
// 防睡眠只在任务运行期间生效, 所以状态挂在活动卡片上而不是单独占一行
- Image(systemName: "cup.and.saucer.fill")
+ Image(systemName: "sun.max.fill")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(Color.teal)
+ .symbolEffect(.rotate.byLayer, options: .repeat(.continuous))
.transition(.opacity)
.help(keepAliveHelp)
}
@@ -114,7 +115,7 @@ struct CodexActivityCard: View {
}
.animation(.codexStatus, value: showsKeepAliveBadge)
.animation(.codexStatus, value: content.isAnonymous)
- // 任务数变化会让 +N 增删, 咖啡杯跟着横移; 两者一起纳入动画上下文才不会跳
+ // 任务数变化会让 +N 增删, 防睡眠徽标跟着横移; 两者一起纳入动画上下文才不会跳
.animation(.codexStatus, value: content.otherTaskCount)
.padding(.horizontal, MenuMetrics.panelPadding)
.frame(maxWidth: .infinity, minHeight: Metrics.height, maxHeight: Metrics.height)
@@ -156,7 +157,7 @@ struct CodexActivityCard: View {
now: now
)
)
- case let .completed(completion, _):
+ case let .completed(completion):
let details = CodexActivityDisplayFormat.historyDetailComponents(
duration: completion.duration,
relativeText: CodexActivityDisplayFormat.completionRelativeText(completion.completedAt, now: now)
diff --git a/CodexBar/Views/Menu/StatusItemIconView.swift b/CodexBar/Views/Menu/StatusItemIconView.swift
new file mode 100644
index 0000000..29de963
--- /dev/null
+++ b/CodexBar/Views/Menu/StatusItemIconView.swift
@@ -0,0 +1,118 @@
+import AppKit
+import Combine
+import SwiftUI
+
+final class StatusItemIconPresentation: ObservableObject {
+ struct State: Equatable {
+ var symbolName = "person.fill"
+ var remainingPercent = 0
+ var showsQuota = false
+ var isStale = false
+ }
+
+ @Published private(set) var state = State()
+
+ func update(symbolName: String, percent: Int?, isStale: Bool, animated: Bool) {
+ let next = State(
+ symbolName: symbolName,
+ remainingPercent: percent.map { min(max($0, 0), 100) } ?? state.remainingPercent,
+ showsQuota: percent != nil,
+ isStale: percent == nil ? state.isStale : isStale
+ )
+ guard next != state else { return }
+ var transaction = Transaction()
+ transaction.disablesAnimations = !animated
+ withTransaction(transaction) {
+ state = next
+ }
+ }
+}
+
+final class StatusItemIconHostingView: NSHostingView<StatusItemIconView> {
+ /// 图标不接管点击和焦点, 继续由原生菜单栏按钮处理左右键
+ override func hitTest(_: NSPoint) -> NSView? {
+ nil
+ }
+
+ override var acceptsFirstResponder: Bool {
+ false
+ }
+}
+
+struct StatusItemIconView: View {
+ @ObservedObject var presentation: StatusItemIconPresentation
+
+ static let size = NSSize(width: 26, height: 22)
+
+ var body: some View {
+ let state = presentation.state
+ ZStack {
+ ZStack {
+ StatusItemQuotaArc()
+ .stroke(
+ Color(nsColor: .tertiaryLabelColor).opacity(0.34),
+ style: StrokeStyle(lineWidth: 2, lineCap: .round)
+ )
+ .opacity(state.showsQuota ? 1 : 0)
+ StatusItemQuotaArc(percent: state.showsQuota ? CGFloat(state.remainingPercent) : 0)
+ .stroke(
+ QuotaPalette.color(for: state.remainingPercent),
+ style: StrokeStyle(lineWidth: 2, lineCap: .round)
+ )
+ }
+ .opacity(state.isStale ? 0.55 : 1)
+ .animation(.easeInOut(duration: 0.3), value: state.showsQuota)
+
+ // 基线固定人物主体, 徽章的下伸部分不参与居中计算
+ Color.clear
+ .frame(width: Self.size.width, height: Self.size.height)
+ .alignmentGuide(.firstTextBaseline) { _ in 18 }
+ .overlay(alignment: .centerFirstTextBaseline) {
+ Image(systemName: state.symbolName)
+ .font(.system(size: 14, weight: .regular))
+ .symbolRenderingMode(.monochrome)
+ .foregroundStyle(.primary)
+ .contentTransition(.symbolEffect(
+ .replace.magic(fallback: .downUp.byLayer),
+ options: .nonRepeating
+ ))
+ .animation(.default, value: state.symbolName)
+ }
+ .scaleEffect(
+ state.showsQuota ? 1 : 16.0 / 14.0,
+ anchor: UnitPoint(x: 0.5, y: 18.0 / 22.0)
+ )
+ .offset(y: state.showsQuota ? 0 : -1)
+ .opacity(state.showsQuota && state.isStale ? 0.75 : 1)
+ }
+ .animation(.easeInOut(duration: 0.2), value: state.showsQuota)
+ .frame(width: Self.size.width, height: Self.size.height)
+ .allowsHitTesting(false)
+ }
+}
+
+private nonisolated struct StatusItemQuotaArc: Shape {
+ var percent: CGFloat = 100
+
+ var animatableData: CGFloat {
+ get { percent }
+ set { percent = newValue }
+ }
+
+ func path(in _: CGRect) -> Path {
+ guard percent > 0 else { return Path() }
+ let radius: CGFloat = 11
+ let extraAngle = asin(CGFloat(5) / radius) * 180 / .pi
+ let startAngle = 180 + extraAngle
+ let endAngle = startAngle - (180 + 2 * extraAngle) * min(percent, 100) / 100
+ var path = Path()
+ path.addArc(
+ center: CGPoint(x: 13, y: 14),
+ radius: radius,
+ startAngle: .degrees(-Double(startAngle)),
+ endAngle: .degrees(-Double(endAngle)),
+ clockwise: false
+ )
+ return path
+ }
+}
diff --git a/CodexBar/Views/Settings/ProxyPasswordField.swift b/CodexBar/Views/Settings/ProxyPasswordField.swift
index 1d5c27d..e2fee17 100644
--- a/CodexBar/Views/Settings/ProxyPasswordField.swift
+++ b/CodexBar/Views/Settings/ProxyPasswordField.swift
@@ -96,13 +96,11 @@ struct ProxyPasswordField: NSViewRepresentable {
// 两个原生控件保持挂载, 在同一轮更新中交接编辑器和选区
// 淡化仅作用于文字所在的图层, 外部边框和焦点环不参与动画
- if !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
- let transition = CATransition()
- transition.type = .fade
- transition.duration = 0.1
- transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
- layer?.add(transition, forKey: "passwordVisibility")
- }
+ let transition = CATransition()
+ transition.type = .fade
+ transition.duration = 0.1
+ transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
+ layer?.add(transition, forKey: "passwordVisibility")
// 安全编辑器不能继续输入法组合, 交接时确认现有文字并保留完整内容
if hasMarkedText {
editor?.unmarkText()
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index 3653356..244163e 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 3.7.2
-CURRENT_PROJECT_VERSION = 86
+MARKETING_VERSION = 3.7.3
+CURRENT_PROJECT_VERSION = 87
diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.md
index 507404d..14d65b3 100644
--- a/Docs/DeveloperGuide/activity-monitor.md
+++ b/Docs/DeveloperGuide/activity-monitor.md
@@ -270,7 +270,7 @@ JSONL 中缺少 `origin` 或来源枚举无法识别时,来源字段先解码
### 等待批准的两阶段确认
-`PermissionRequest` 说明进入审批流程,但 reviewer 可能是 user, policy 或 auto review。
+`PermissionRequest` 的 reviewer 接受 `user`、`auto_review` 和 `guardian_subagent`。
Hook event 到达时如果已经带有 reviewer,task 可以立即确认。reviewer 缺失时先保存 `pendingApprovalRequestedAt`,rollout poll 补齐后再决定是否进入 `waitingApproval`
@@ -290,17 +290,17 @@ subagent 的 turn ID 属于 subagent 自己,父任务只能通过共享 sessio
## 快照优先级
-多个任务和短时状态同时存在时,对外快照按以下优先级表达:
+活动卡片的 `primaryActivity` 按以下优先级选择内容:
```text
等待批准 > 运行中 > 最近完成 > 最近中断 > 空闲
```
-完成状态在菜单栏保留 30 秒绿色提示。活动中心保留最近 10 分钟任务,terminal 去重记忆保留 24 小时。
+菜单栏同样优先展示等待批准和运行中任务;没有活跃任务时,从完成与终止记录中选择最新一条,显示到结束时间后 30 秒。任务中心的终态记录保留 10 分钟,terminal 去重记忆保留 24 小时。
快照由以下模块消费:
-- 菜单栏状态点
+- 菜单栏人物图标
- 主面板任务卡片
- 活动中心
- 通知系统
@@ -308,7 +308,7 @@ subagent 的 turn ID 属于 subagent 自己,父任务只能通过共享 sessio
### 快照发布
-monitor 每秒 poll rollout,还会按多个 deadline 自行刷新。如果每轮都给 `@Published` 赋相同值,SwiftUI 和所有 Combine 消费者会重复计算。
+monitor 每秒检查 rollout,并在清理 deadline 到达时刷新。
新快照先与当前值比较,只有结构变化才发布。运行时长文案由 View 使用当前时间格式化,不要求每秒修改任务对象。
@@ -320,11 +320,9 @@ monitor 每秒 poll rollout,还会按多个 deadline 自行刷新。如果每
### 清理采用最近 deadline
-monitor 同时管理完成高亮、terminal grace、活动保留、历史保留、terminal 去重和保护记录过期。
+monitor 管理 terminal grace、活动保留、历史保留、terminal 去重和保护记录过期。菜单栏完成或终止提示的 30 秒到期由 `StatusItemController` 独立管理,不为提示到期重新发布活动快照。
-它不使用固定高频 timer 扫描所有状态,而是收集所有未来 deadline,只为最近一项安排 Task。到点刷新后再计算下一项。
-
-这种实现减少常驻菜单栏 App 的无意义唤醒,也保证每种保留期都能在没有新 Hook 事件时准时生效。
+清理任务只等待最近的未来 deadline,到点处理后安排下一次。
## 系统睡眠与唤醒
@@ -350,7 +348,7 @@ rollout 对账必须发生在 Hook drain 成功之后。
如果先读 rollout,此时 monitor 中可能还没有睡眠期间刚追加的任务 key,lifecycle 结果无法关联。如果先恢复保护判定,则会基于睡前 last progress 误隐藏任务。
-`readerGeneration` 防止唤醒 Task 返回时 reader 已因 Hook 设置变化被替换。`recoveryGeneration` 防止两次睡眠或设置变化交错后,较早恢复流程提前解除暂停。
+`tailReaderGeneration` 防止唤醒 Task 返回时 reader 已因 Hook 设置变化被替换。`activityProtectionRecoveryGeneration` 防止两次睡眠或设置变化交错后,较早恢复流程提前解除暂停。
## 异常会话保护
@@ -406,7 +404,7 @@ rollout 对账必须发生在 Hook drain 成功之后。
阈值变短时,已经超过新阈值的 running 任务会立即重新判定。
-阈值变长时,尚未超过新阈值的 suppressed 任务会静默恢复,清除对应保护记录和通知。已经仍超过新阈值的任务继续 suppressed,不制造重复通知。
+阈值变长时,未超过新阈值的 suppressed 任务会静默恢复,并清除保护记录和通知;仍超过阈值的任务继续隐藏。
关闭防睡眠主开关会停用异常保护,并恢复当前进程内所有 suppressed 任务。
diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.md
index 95b8e10..10292a8 100644
--- a/Docs/DeveloperGuide/app-server.md
+++ b/Docs/DeveloperGuide/app-server.md
@@ -29,7 +29,7 @@ CodexCLIResolver
`CodexStatusService` 拥有连接和同账户缓存。`CodexStatusViewModel` 只拥有 UI 级加载状态、自动刷新节奏和最后一次连接信息。
-这个分工让设置页可以复用同一个 app-server session 读写 Hook 与 TUI 配置,同时不让 View 直接持有 `Process` 或 pipe。
+设置页复用该 session 读写 Hook 与 TUI 配置。
## Codex CLI 定位
@@ -238,8 +238,6 @@ ready
`fetchData` 内部用同一个 `didRefresh` 锁存本轮刷新资格。第一个认证失败触发 `account/read(refreshToken: true)`,后续接口复用刷新结果。再次需要认证时直接归类为未登录。
-这避免一轮 UI 刷新对同一凭据连续触发多次 token refresh。
-
## 刷新模型
状态 ViewModel 默认每 60 秒刷新。用户也可以在主面板双击账户图标立即触发。
@@ -267,8 +265,6 @@ ready
rate limits 与 usage 是补充数据。只要账户有效,即使两个接口都没有数据,仍然生成快照让 UI 展示账户和明确的“暂无数据”。
-如果因为补充接口缺失就把整轮标成未登录,用户会看到身份状态在真实登录和错误之间抖动,也无法区分认证问题与单个新接口不支持。
-
### 缓存决策表
| 当前结果 | 同账户有缓存 | 输出 | stale |
@@ -410,8 +406,8 @@ namespace、UUID 版本、原始 UTF-8 输入和小写输出共同构成跨版
Hook 设置也复用 app-server 链路,但采用独立的可用性状态:
-- `isEnabled` 表示目标 handler 已安装
-- `isVerified` 表示最近一次 app-server 显式校验通过
+- `isEnabled` 表示当前进程中的开启状态,首次从已有 handler 恢复;运行期间配置缺失时触发自愈
+- `isVerified` 默认 `true`,随后保存最近一次明确校验结论
- `isOperable` 只有在两者都为 `true` 时成立
- 短暂 RPC 失败保留上一次明确校验结果
@@ -428,8 +424,6 @@ Hook 设置也复用 app-server 链路,但采用独立的可用性状态:
- 从 handshake user agent 解析运行版本
- 无法解析版本时按不支持处理,不乐观放行
-这是能力安全边界。如果未来新增依赖某个 app-server 方法的功能,应把最低版本判断放在实际连接能力入口,不能只在“关于”页面展示磁盘版本。
-
## 请求日志
[`RequestLog.swift`](../../CodexBar/Services/CodexStatus/RequestLog.swift) 在内存中保留最近 500 条请求日志,用于 App 内日志窗口诊断。
diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.md
index e19a555..401cdee 100644
--- a/Docs/DeveloperGuide/architecture.md
+++ b/Docs/DeveloperGuide/architecture.md
@@ -118,7 +118,7 @@ Hook handler 在 Codex 的关键路径上,它需要的是接近命令行工具
## 3 条独立数据链路
-CodexBar 不使用一个聚合服务承载所有状态。3 条链路的输入、时效和失败语义不同:
+三条数据链路分别管理不同的输入、时效和失败状态:
| 链路 | 输入 | 输出 | 主要消费者 |
| --- | --- | --- | --- |
@@ -197,7 +197,7 @@ Hook + rollout --------> CodexActivityMonitor --------> UI
## 模型分层
-项目没有让 app-server DTO、持久化模型和 View 直接共用同一个大对象:
+模型按外部输入、持久化、领域状态和展示职责分层:
| 模型类型 | 作用 | 设计要求 |
| --- | --- | --- |
@@ -211,14 +211,14 @@ Hook + rollout --------> CodexActivityMonitor --------> UI
## 生命周期与保留时间
-不同状态有不同的生命周期,不能用一个统一缓存期限替代:
+各类状态的生命周期如下:
| 状态 | 生命周期 | 原因 |
| --- | --- | --- |
| app-server connection | 请求时检查 1 小时复用上限 | 后续请求重建连接时使用磁盘上的 binary |
| app-server supplemental cache | 当前账户内 | 避免跨账户串值 |
| Hook live bootstrap window | 24 小时 | 覆盖可能仍在运行的长任务 |
-| 完成高亮 | 30 秒 | 菜单栏短时反馈 |
+| 菜单栏完成或终止提示 | 30 秒 | 最新终态的短时反馈 |
| 任务中心 terminal 历史 | 10 分钟 | 提供近期上下文但不长期占用 UI |
| terminal 去重记忆 | 24 小时 | 防止迟到 Hook 或 rollout 复活旧任务 |
| Hook 原始和日聚合 | 210 天 | 支持长期统计和重建 |
diff --git a/Docs/DeveloperGuide/design-decisions.md b/Docs/DeveloperGuide/design-decisions.md
index ef5f362..8c59d86 100644
--- a/Docs/DeveloperGuide/design-decisions.md
+++ b/Docs/DeveloperGuide/design-decisions.md
@@ -26,7 +26,7 @@
| --- | --- |
| app-server 补充接口暂时失败 | 使用同账户缓存并标记 stale,降低 UI 透明度,不触发额度通知或自动消费 |
| method unsupported | 当前 session 缓存能力缺失,重建连接后重新探测 |
-| 历史 Hook 计数字段缺失 | 持久化和同步模型保留 `nil`;当前展示投影仍会按规则回退为计数 |
+| 历史 Hook 计数字段缺失 | 持久化和同步模型保留 `nil`,展示投影按指标规则回退 |
| 实时 reader 无法取得稳定边界 | 发布 degraded health,暂停异常会话保护 |
这些状态由来源层给出,消费方按用途决定是否展示或执行副作用。计数投影见 [Hook 聚合](hook-and-aggregation.md),账户缓存见 [app-server](app-server.md)
diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.md
index fea9f64..ef257ca 100644
--- a/Docs/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/DeveloperGuide/hook-and-aggregation.md
@@ -39,7 +39,7 @@ Codex Hook
- 禁用时只移除精确匹配的 CodexBar handler
- 无法识别的配置保持原样
-`isEnabled` 表示当前进程中的 Hook 开启状态,首次从现有 CodexBar handler 恢复。`isVerified` 表示最近一次 app-server 校验通过。UI 只有在 `isOperable` 成立时把 Hook 当作可工作数据源。
+`isEnabled` 表示当前进程中的开启状态,首次从已有 CodexBar handler 恢复。`isVerified` 默认 `true`,随后保存最近一次明确校验结论。实时任务和相关功能使用两者合取的 `isOperable`;历史聚合和同步按 `isEnabled` 消费已落盘数据。
### 校验状态
@@ -47,7 +47,7 @@ Codex Hook
### 已开启 Hook 的对账
-App 启动、设置状态刷新、菜单面板打开以及每轮额度刷新完成后,都会对账已开启的 CodexBar Hook。额度自动刷新正常每 60 秒完成一轮,因此配置和信任数据通常会在 60 秒内自动收敛:
+App 启动、设置状态刷新、主面板打开和每轮额度刷新完成时,都会对账已开启的 Hook。自动刷新间隔为上一轮完成后 60 秒:
- 只有已确认的实际 app-server 版本低于当前 Hook 最低版本时,才按手动关闭流程移除 CodexBar handler 和对应信任项
- 版本无法确认或 RPC 临时失败时保留用户配置
@@ -56,7 +56,7 @@ App 启动、设置状态刷新、菜单面板打开以及每轮额度刷新完
- 信任项缺失或哈希变化时,只修复 `command`、`sourcePath` 和 `event` 都属于当前 CodexBar 的条目
- 必需事件全部存在时不写 `hooks.json`
-对账以当前必需事件集合和文件实际内容为依据,不保存一次性迁移标记。因此未来新增事件或用户手动删除必需 handler 时都会走同一条自愈路径。如果 App 启动前已经没有可识别的 CodexBar handler,首次读取无法恢复开启状态,Hook 保持关闭。
+对账比较必需事件集合与配置文件,补齐缺失 handler。启动时没有可识别的 CodexBar handler 则保持关闭。
### 启用事务的顺序
@@ -142,13 +142,9 @@ handler 超时由事件决定:
锁等待预算为 handler 超时减 2 秒。获取锁时从 1 ms 开始指数退避,单次等待最多 20 ms。
-stdin 无效、文件锁超时或写入失败都会被吞掉。Hook 子进程不能因为统计失败而阻断 Codex。
-
### 失败退出
-Hook 统计是 CodexBar 的辅助能力,不是 Codex 完成任务的必要步骤。如果 recorder 把解析或磁盘错误作为非零退出码返回,一次统计故障就可能让用户的 Codex 流程失败。
-
-因此显式进入 `--hook-event` 后,无论输入是否有效都返回已处理并退出成功。失败只意味着少一条统计,不升级为上游任务故障。
+进入 `--hook-event` 后,无效输入、锁超时和写入错误均以成功状态退出,避免采集失败阻断 Codex。
### 事件与维护状态的锁内事务
@@ -166,14 +162,6 @@ Hook 统计是 CodexBar 的辅助能力,不是 Codex 完成任务的必要步
锁内联合提交让“文件已经增长”和“维护知道需要读取”保持一致。
-### 锁等待预算
-
-Codex 对 `SessionEnd` 最多等待 3 秒,其他事件最多 5 秒。recorder 把锁等待限制为总预算减 2 秒。
-
-预留时间用于编码、append、保存维护状态和进程退出。如果把全部预算花在等锁上,Codex 可能正好在写入中途终止进程,留下半行或未配对的维护状态。
-
-等待从 1 ms 指数退避到最多 20 ms。主 App 的正常持锁区很短,小步起始能在锁刚释放时迅速继续,上限则避免高竞争时 busy loop。
-
### 锁文件创建
不能先判断文件不存在,创建后再打开。两个进程可能分别创建不同 inode,后创建的一方替换目录项后,双方会各自锁住不同文件并都认为自己独占。
@@ -408,7 +396,7 @@ compaction 和 subagent 成对事件使用相同规则。
- 去重规则变化
- 来源代际合并语义变化
-升级后统一从 210 天保留期内的原始 JSONL 完整重建,不做字段级历史迁移。这种策略让聚合缓存始终能够由同一套当前算法生成。
+schema 不一致时,从 210 天保留期内的原始 JSONL 完整重建,不执行字段级历史迁移。
用户手动重建时也走同一条完整重算路径,并向同步层标记需要替换的日期。
diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.md
index 86f408a..a7502ba 100644
--- a/Docs/DeveloperGuide/notifications.md
+++ b/Docs/DeveloperGuide/notifications.md
@@ -96,7 +96,7 @@ App 激活、设置窗口重新获得焦点或显式打开时会重新读取系
### 阈值穿越判定
-“当前低于 10%”是一个持续状态,“刚刚低于 10%”才是通知事件。服务为每个 `account + limit + window` 保存上一帧剩余比例:
+服务为每个 `account + limit + window` 保存上一帧剩余比例,按以下规则判定通知:
- 上一帧高于阈值且当前不高于阈值时发送
- 会话内第一帧已经不高于阈值时发送一次
@@ -177,13 +177,14 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正
低电量或最长时长导致防睡眠停止时,`KeepAliveController` 先撤销 CodexBarHelper 租约。只有回复确认来源为 `.codexBar` 且 `SleepDisabled=0` 时,才提交对应通知;其他结果会清除本轮待发通知。
-确认后才提交通知。App idle assertion 会保留到通知提交结束,避免合盖机器在通知交给系统前立即睡下。随后 controller 释放 assertion 并按需补发合盖睡眠。
+App idle assertion 保留到通知提交结束,随后释放,并按需补发合盖睡眠。
## 声音
-[`NotificationSoundOption.swift`](../../CodexBar/Services/Notifications/NotificationSoundOption.swift) 汇总 3 类选择:
+[`NotificationSoundOption.swift`](../../CodexBar/Services/Notifications/NotificationSoundOption.swift) 提供以下声音选择:
-- 无声音
+- 系统默认通知音
+- 静音
- macOS 可用系统声音
- App bundle 内置声音
@@ -210,8 +211,6 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正
触觉是系统通知之外的独立本地反馈。它响应非匿名任务的完成或等待 transition,服从通知总开关和触觉开关,但不依赖系统通知授权、分类通知开关或完成时长阈值。
-这种分离让用户可以关闭 banner 仍保留统一的任务触觉。上游 transition 仍必须真实有效,bootstrap 历史和匿名任务不会触发。
-
## 提交与去重
通知通过 `UNUserNotificationCenter` 提交:
@@ -273,7 +272,7 @@ App 是 `LSUIElement`,通知中心 delegate 明确允许 App 在前台时继
- 首次开启总开关时正确请求系统权限
- 系统拒绝权限时设置页展示可理解状态
-- 低额度只在向下跨越阈值时通知
+- 首次读数不高于低额度阈值或向下跨越阈值时提醒,同一重置周期去重
- 初次加载 100% 额度不误报重置
- 自动重置明确返回 `reset` 时发送“自动重置”,后续额度归零时仍可独立发送“额度已重置”
- 自动重置明确返回 `alreadyRedeemed` 时按成功通知并停止重试
diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.md
index 1c3a977..5deeeaf 100644
--- a/Docs/DeveloperGuide/sleep-prevention.md
+++ b/Docs/DeveloperGuide/sleep-prevention.md
@@ -106,7 +106,7 @@ App 和 helper 都使用单调递增 generation:
[`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift) 只有在以下条件全部成立时才建立防睡眠:
- 防睡眠主开关已开启
-- Hook 已启用且校验通过
+- Hook 的 `isOperable` 为 `true`
- 至少存在一个符合设置的实时任务
- CodexBarHelper 已安装并可连接
- 未触发低电量阈值
@@ -170,7 +170,7 @@ CodexBarHelper 通过 `SMAppService` 注册为 LaunchDaemon。App 和 CodexBarHe
- 确认组件缺失、配置异常或签名无效时显示“不可用”,即使系统仍返回 `.enabled`;后续包校验成功后清除该异常
- 安装前发现组件缺失时只更新包异常并发起新校验,不另存一份注册错误;旧校验结果不能覆盖新发现的缺失,关闭功能后修复组件也能通过再次校验恢复显示
- 待授权和已授权状态不会被历史注册错误覆盖;未注册且安装失败时显示“不可用”
-- 校验结果只保存在内存中,不证明 Helper 的每次运行都成功;XPC 超时和具体电源操作失败仍按原操作错误处理
+- 包校验结果只保存在内存中;XPC 超时和电源操作失败由操作错误单独表示
唤醒计划采用系统状态收敛而不是只依赖正常退出清理:
@@ -269,8 +269,6 @@ CodexBarHelper 把系统所有权记录保存在:
- 使用临时文件、full sync 和原子 rename 提交
- 启动时记录缺失则写入 idle;记录为 owned 或 restoring 时恢复 `disablesleep 0`;记录无法读取或不可信时也尝试恢复为 `0`
-该文件记录 CodexBar 对系统睡眠设置的所有权。
-
自动重置唤醒事件不写入该文件。它由 macOS 电源管理保存,身份固定为当前 Debug 或 Release helper 的 mach service 名加 `.auto-reset`,类型固定为 `wake`。
## 租约与故障恢复
diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.md
index da7a3bf..9abd4ac 100644
--- a/Docs/DeveloperGuide/sync.md
+++ b/Docs/DeveloperGuide/sync.md
@@ -71,8 +71,6 @@ zone 确认和账户 salt 在 actor 内跨轮次缓存;同步失败时使两
原始 `IOPlatformUUID` 不会上传。同一设备在同一 iCloud 账户中得到稳定 pseudonym,不同账户得到不同结果。
-账户私有 salt 使同一设备在不同 iCloud 账户中得到不同 pseudonym。
-
salt 存在同一个 private custom zone 中。多台设备先后创建时通过 CloudKit 冲突后回读现有记录收敛到同一份 salt,而不是让每台设备各自产生不兼容身份。
本地状态记录最近解析出的 `deviceId`。如果它变化,同步会清除旧游标和远端缓存,但保留待 replacement 日期。设备身份变化意味着缓存的账户作用域已经不可信,不能继续增量套用。
@@ -154,7 +152,7 @@ salt 存在同一个 private custom zone 中。多台设备先后创建时通过
### 同设备同日的多来源记录
-早期记录名只包含 `deviceId + date`。新鲜来源可额外使用 `deviceId + date + sourceGeneration`
+记录名支持 `deviceId + date`,以及带来源代际的 `deviceId + date + sourceGeneration` 两种形式。
generation 记录用于表达某一份原始来源的身份。同源的本地和云端结果是替换关系,明确不同的来源则可能是同一天先后产生的独立贡献。
@@ -205,7 +203,7 @@ CloudKit 解码及持久化模型保留可选计数字段。当前 `WorkflowDail
replacement 进行中时,快照会临时过滤当前设备该日期的云端缓存,同时展示本机最新聚合。即使 App 在删除和重传之间退出,UI 也不会把旧云端贡献与新本地贡献相加。
-先全量拉取是这一事务最关键的小细节。增量 cursor 只保证从游标之后的变化完整,不保证本地缓存从未因旧版本或手动删除丢过记录。删除前全量枚举才能避免遗留幽灵 generation。
+replacement 删除前全量拉取当前设备同日记录,覆盖本地增量缓存中缺失的 generation。
## 增量游标与本地缓存
@@ -233,7 +231,7 @@ replacement 进行中时,快照会临时过滤当前设备该日期的云端
`cursor.data` 使用 secure coding 保存 CloudKit opaque token。代码不解析其内部结构。全量拉取后还要建立新的 cursor baseline,否则下一轮可能从空游标重复消费刚拉取的全部变化。
-本地 schema `3 -> 4` 的读取路径会先重建远端缓存再提交新状态。未知 schema 则回到空同步状态,因为错误解释上传确认信息比重新同步更危险。
+读取本地 schema `3` 时先重建远端缓存,再保存为 schema `4`;未知 schema 按空同步状态重新同步。
任何 record 字段、identity 或 schema 的变化都是兼容性决策。需要同时考虑旧 App 仍在写入、新 App 如何读取旧字段,以及降级后是否会覆盖新记录,不能只递增一个常量。
diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.md
index 918cf5a..dec7d41 100644
--- a/Docs/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md
@@ -48,26 +48,29 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。
状态图标综合 app-server 加载状态、菜单栏额度设置和任务活动快照。
-任务状态点的优先级是:
+图标优先级是:
```text
-等待批准(橙色) > 运行中(蓝色) > 完成后 30 秒内(绿色)
+账户异常 > 等待批准 > 运行中 > 最近 30 秒内的完成或终止 > 空闲
```
-最近中断、空闲和完成高亮过期后均不显示任务状态点。图标生成结果按输入状态缓存,非激活或不可用状态通过 alpha 表达。
+`CodexActivitySnapshot.statusItemActivity(at:)` 在没有活跃任务时按结束时间选择最新终态。`StatusItemController` 按结束时间加 30 秒安排到期任务,到期后恢复普通人形;系统唤醒时按当前时间重算,状态变化和卸载时取消旧任务。
-### 图像状态与 tooltip 状态分离
+### 分离图标与 tooltip 状态
-`StatusIconState` 同时含图像输入和 tooltip 输入,但 `renderState` 只保留真正影响像素的字段:
+`StatusIconState` 保存活动和额度输入。`StatusItemIconPresentation` 只发布影响图像的符号名称、额度、显隐和缓存标记,相同渲染状态不会重复发布:
- 活跃任务持续时间每分钟变化,只更新 tooltip
- 额度过期但仍展示缓存时,图标和进度使用降低后的 alpha
-- 指示点或额度条显隐变化时才启动约 0.18 秒的 10 帧动画
-- 新渲染状态到达时取消旧动画,每帧再次确认目标状态仍是当前状态
+- `StatusItemIconView` 在符号名称变化时使用 `.replace.magic(fallback: .downUp.byLayer)` 非重复替换动画
+- 额度显隐在 0.3 秒内将彩色圆弧从零绘制到当前额度,或从当前额度收回到零,底轨独立淡入淡出
+- 人物按符号基线对齐,隐藏额度时恢复正常大小;大小和位置在 0.2 秒内过渡
+- 关闭额度时保留最后的额度和配色供收回动画使用,零额度与缺失额度保持不同语义
+- 初次渲染和唤醒重算时不播放过渡动画
-无状态点和额度条时图标保持 template image,让系统根据浅色、深色和菜单栏状态自动着色。一旦加入自定义颜色或进度条就使用显式颜色绘制。
+SwiftUI 视图持续挂载在原生 `NSStatusBarButton` 中,透明图片用于系统自适应占位。图标使用系统前景色,宿主视图不接受焦点或鼠标命中,左右键仍交给原按钮处理。
-tooltip 只在存在实时任务持续时间时启动 60 秒计时器,空闲时不保留永久 timer。App 还把 `NSInitialToolTipDelay` 调整为 500 ms,让菜单栏这种小点击目标的状态解释更容易被发现。
+tooltip 在存在活跃任务时每 60 秒更新,空闲时停止计时。`NSInitialToolTipDelay` 为 500 ms。
左键打开主面板。右键或按住 Control 点击打开上下文菜单。
@@ -128,6 +131,10 @@ popover 和备用面板分别持有 `MenuSurfaceAnimationState`。展示前将 `
`MenuSurfaceVisibilityState` 在面板展示后开启,在关闭开始时结束。每次展示递增 `presentationGeneration`,额度和用量区域以该值作为视图身份,重新执行入场动画。
+### 活动卡片
+
+`CodexActivityCard` 使用 `primaryActivity`,优先级为等待批准、运行中、最近完成、最近终止。`isActivelyPreventingSleep` 为 `true` 且卡片数据可用时显示青绿色 `sun.max.fill`,通过 `.symbolEffect(.rotate.byLayer, options: .repeat(.continuous))` 持续旋转。tooltip 按 `sleepPreventionSource` 显示来源。
+
## Fallback panel
全局快捷键触发时,状态栏按钮的屏幕位置可能不可用或不可信。此时 [`FallbackPanelController.swift`](../../CodexBar/Controllers/FallbackPanelController.swift) 在鼠标所在屏幕显示浮动面板。
@@ -189,11 +196,11 @@ fallback panel 在展示前根据 SwiftUI fitting size 和目标屏幕可见区
- 优先在 status item 所在屏幕居中,再退到 window screen 或 main screen
- miniaturized 窗口先 deminiaturize 再激活
-设置窗口的高度随当前 tab 的完整内容变化,但固定上边缘并限制到屏幕 visible frame。内容未超过屏幕限制时,窗口应完整容纳当前页面且不产生滚动条;只有内容物理上放不进可见区域时,`ScrollView` 才作为安全降级。固定上边缘可以减少切换 tab 时整窗上下漂移,让标题栏保持稳定视觉锚点。
+设置窗口按当前 tab 的完整内容调整高度,固定上边缘,并限制到屏幕可见区域。内容超出屏幕高度时使用 `ScrollView`。
-首次构造窗口时,SwiftUI 可能在 `HostingWindowController` 保存 `window` 之前就上报页面高度。`SettingsWindowController` 会先缓存最近一次有效测量,并在窗口就绪后应用;否则唯一一次高度回调会被丢弃,窗口停留在初始尺寸,直到切换 tab 再次触发测量。
+SwiftUI 可能在窗口创建完成前上报高度。`SettingsWindowController` 缓存最近一次有效测量,在 `HostingWindowController.window` 就绪后应用。
-主面板布局、通知、自动重置和防睡眠的二级设置面板按需创建。控制器一旦创建就会长期持有内容及必要的高度变化订阅,如果 App 启动时预建所有面板,从未使用的 UI 也会一直参与更新。
+主面板布局、通知、自动重置和防睡眠的二级设置面板在首次打开时创建,之后复用内容及必要的高度变化订阅。
这四个设置子面板包含交互控件,因此使用可获得键盘焦点的 `KeyableBorderlessPanel`。主面板的热力图、Reset Credits 和活动中心详情使用不会激活的 `NonactivatingSidePanel`。收起设置子面板时,`SidePanelSupport.orderOut` 只在该子面板仍是 key window 时恢复父窗口焦点;如果焦点已经主动转移到主面板或其他窗口,则不能再抢回,否则新打开的交互表面可能因失焦立即关闭。
@@ -208,11 +215,11 @@ fallback panel 在展示前根据 SwiftUI fitting size 和目标屏幕可见区
入口条件失效时设置页发送对应的 `close` 动作,避免不可用的子面板继续显示。主开关关闭时,自动重置和防睡眠设置行不显示状态说明。
-`MainPanelSettings` 使用稳定区域标识保存账户、任务中心、额度、Token 用量和底部状态的顺序与显隐。布局归一化会去重、忽略无效值、补齐缺失区域,并保证至少保留一个可见区域。`StatusItemController` 在读取到 Hook 关闭状态后调用 `updateHookEnabled(_:)`,持久化关闭任务中心;如果任务中心原本是唯一可见区域,则同时开启账户区域。设置面板只禁用任务中心开关,拖拽手柄仍保持可用。其他数据链路的临时可用性只影响当次渲染。
+`MainPanelSettings` 使用稳定区域标识保存账户、任务中心、额度、Token 用量和底部状态的顺序与显隐。布局归一化会去重、忽略无效值、补齐缺失区域,并保证至少保留一个可见区域。`StatusItemController` 在读取到 Hook 关闭状态后调用 `updateHookEnabled(_:)`,持久化关闭任务中心;如果任务中心原本是唯一可见区域,则同时开启账户区域。从关闭切换到开启时自动显示任务中心,首次恢复开启状态和重复开启通知均保留用户布局。设置面板只禁用任务中心开关,拖拽手柄仍保持可用。其他数据链路的临时可用性只影响当次渲染。
布局排序使用手柄上的自定义 `DragGesture`。拖动项通过悬浮副本跟随指针,其他行在跨过半行距离时按视图内预览顺序实时让位,松手后才调用 `setSectionOrder(_:)` 一次性持久化最终顺序。
-`SettingsWindowController` 持有这一窗口组唯一的 `UndoManager`。设置主窗口通过 `AuxiliaryHostingWindow` 暴露它,四个设置子面板展示时从父窗口取得同一实例,因此焦点位于设置主窗口或任一子面板时,`⌘Z` 和 `⌘⇧Z` 都作用于同一份布局历史。Hook 状态变化引起的任务中心自动关闭不进入用户撤销历史。
+`SettingsWindowController` 持有这一窗口组唯一的 `UndoManager`。设置主窗口通过 `AuxiliaryHostingWindow` 暴露它,四个设置子面板展示时从父窗口取得同一实例,因此焦点位于设置主窗口或任一子面板时,`⌘Z` 和 `⌘⇧Z` 都作用于同一份布局历史。Hook 状态变化引起的任务中心自动显隐不进入用户撤销历史。
### 代理配置对话框
@@ -252,7 +259,7 @@ app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调
普通刷新在刷新或重连进行中被忽略。需要在当前请求后补刷的操作通过 `refreshAfterCurrent` 保存一个待执行触发,当前请求结束后再执行。
-面板打开时立即刷新本地 Hook 统计;延迟任务还会对账已安装的 Hook 配置。面板在等待期间关闭时会取消该任务。
+面板打开时立即对账 Hook 配置,并在 Hook 开启时请求本地统计刷新。延迟任务只检查账户、额度和用量是否需要刷新;面板提前关闭时取消该任务。
## 本地化和格式化
@@ -274,6 +281,10 @@ app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调
## 手动验证矩阵
- 左键打开主面板,右键和 Control 点击打开上下文菜单
+- 菜单栏符号随任务状态切换,最新终态在结束 30 秒后恢复空闲,跨睡眠唤醒后按当前时间显示
+- 切换额度圆弧显隐时动画完整,零额度保留底轨,缓存额度变淡
+- 防睡眠生效时太阳徽标持续旋转,结束后消失,重开面板后状态正确
+- 代理密码显隐切换时淡化正常,输入内容、选区和焦点保留
- 点击主面板外部正确关闭,点击侧边面板不误关闭
- 热力图、Reset Credits 和活动中心保持互斥
- Token 用量区域处于不同排序位置时,热力图详情优先与完整热力图区域顶边对齐;详情高度放不下时与主面板底边对齐
@@ -283,7 +294,7 @@ app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调
- 冷启动后首次打开设置时通用页直接使用完整内容高度;切换三个 tab 时窗口高度自适应,屏幕空间充足时均不显示滚动条
- 主面板布局、通知、自动重置和防睡眠子面板互斥,顶边对齐对应设置行,内容变化后高度正确
- 设置子面板展开时从菜单栏打开主面板,主面板保持打开,设置子面板收起且不把焦点抢回设置窗口
-- 主面板区域拖动时悬浮行跟随指针,跨过半行后其他行实时让位,松手后平滑落位并只保存最终顺序;拖拽和显隐操作可以通过 `⌘Z` 逐步撤销并通过 `⌘⇧Z` 重做,焦点在设置主窗口或任一设置子面板时均有效;重启后保持配置,最后一个可见区域无法关闭;Hook 关闭时任务中心自动关闭、开关置灰但仍可拖动,任务中心为唯一可见区域时账户自动开启,自动联动不进入用户撤销历史
+- 主面板区域拖动时悬浮行跟随指针,跨过半行后其他行实时让位,松手后平滑落位并只保存最终顺序;拖拽和显隐操作可以通过 `⌘Z` 逐步撤销并通过 `⌘⇧Z` 重做,焦点在设置主窗口或任一设置子面板时均有效;重启后保持配置,最后一个可见区域无法关闭;Hook 关闭时任务中心自动关闭、开关置灰但仍可拖动,任务中心为唯一可见区域时账户自动开启;重新开启 Hook 后任务中心自动显示,手动隐藏后重启仍保持隐藏,自动联动不进入用户撤销历史
- 上下文菜单打开设置或日志时没有焦点丢失
- 多显示器和不同菜单栏位置下 fallback panel 位于鼠标屏幕
- 快捷键冲突后原快捷键仍可用
@@ -300,3 +311,5 @@ app-server 状态默认每 60 秒检查刷新。主面板打开后约 160 ms 调
- [`SettingsWindowController.swift`](../../CodexBar/Controllers/SettingsWindowController.swift)
- [`LogWindowController.swift`](../../CodexBar/Controllers/LogWindowController.swift)
- [`CodexStatusMenuView.swift`](../../CodexBar/Views/Menu/CodexStatusMenuView.swift)
+- [`StatusItemIconView.swift`](../../CodexBar/Views/Menu/StatusItemIconView.swift)
+- [`CodexActivityCard.swift`](../../CodexBar/Views/Menu/CodexActivityCard.swift)
diff --git a/Docs/UserGuide/main-panel.md b/Docs/UserGuide/main-panel.md
index d359418..d90e071 100644
--- a/Docs/UserGuide/main-panel.md
+++ b/Docs/UserGuide/main-panel.md
@@ -4,22 +4,25 @@
## 菜单栏图标
-CodexBar 用图标、状态点和可选额度条同时表达账户、任务和额度状态:
+CodexBar 用人物图标和可选额度圆弧表达账户、任务和额度状态:
| 外观 | 含义 |
| --- | --- |
-| 正常账户图标 | 账户数据可用 |
-| 错误账户图标 | 未登录、初始化失败或缺少可信额度与用量数据 |
-| 蓝色状态点 | 至少有一个任务正在运行 |
-| 橙色状态点 | 至少有一个任务正在等待用户批准 |
-| 绿色状态点 | 任务刚刚完成,高亮持续 30 秒 |
-| 图标旁额度条 | 所选额度窗口的剩余比例 |
+| 普通人形 | 默认或空闲状态 |
+| 斜杠人形 | 未登录、初始化失败或缺少可信额度与用量数据 |
+| 时钟徽章 | 至少有一个任务正在运行 |
+| 钥匙徽章 | 至少有一个任务正在等待用户批准 |
+| 盾牌勾徽章 | 任务刚刚完成,显示 30 秒 |
+| 盾牌感叹号徽章 | 任务刚刚被终止,显示 30 秒 |
+| 人物上方的缺口圆弧 | 所选额度窗口的剩余比例,颜色与面板百分比一致 |
-多个状态同时存在时,等待批准优先于运行中,运行中优先于最近完成。
+多个状态同时存在时,账户异常优先,其次是等待批准、运行中,最后是最近 30 秒内的完成或终止;两种结束记录按时间选择最新的一条。
+
+隐藏额度圆弧时,人物图标会放大。
鼠标悬停在菜单栏图标上可以查看当前任务状态、项目名、持续时间、并发任务数量和额度窗口剩余比例。
-额度数据来自缓存时,图标和进度条会降低透明度,表示当前看到的不是最新快照。
+显示缓存额度时,图标和圆弧变淡。额度为零时保留底轨;没有额度数据或关闭显示时隐藏圆弧。
## 自定义布局
@@ -98,7 +101,7 @@ CodexBar Hook 开启且当天有数据时,日期详情还会显示以下统计
- 其他并发任务数
- 匿名任务图标
-防睡眠实际生效时,活动卡片右侧会显示咖啡杯标记。
+防睡眠实际生效时,活动卡片右侧显示持续旋转的青绿色太阳徽标,悬停可查看防睡眠来源。
无法识别会话的任务带有橙色匿名图标,悬停显示 `匿名任务不参与防睡眠`
@@ -115,9 +118,7 @@ CodexBar Hook 开启且当天有数据时,日期详情还会显示以下统计
- 最近完成
- 最近终止
-最近完成和最近终止记录保留 10 分钟。完成表示一轮任务结束;终止表示被中断,不触发完成通知。
-
-完成不代表结果一定成功。
+最近完成和最近终止记录保留 10 分钟。完成表示一轮任务结束,不代表执行成功;终止表示被中断,不触发完成通知。
## 底部状态
diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.md
index b7387c0..c97a091 100644
--- a/Docs/UserGuide/settings.md
+++ b/Docs/UserGuide/settings.md
@@ -19,7 +19,7 @@
点击右侧选项按钮后,可拖动排序或切换区域开关,至少保留一个区域。使用 `⌘Z` 撤销、`⌘⇧Z` 重做。隐藏区域不会停止相关功能。
-Hook 关闭时任务区域自动关闭,重新开启 Hook 后需手动恢复;如果任务是唯一可见区域,账户区域会自动开启。
+Hook 关闭时任务区域自动关闭,从关闭切换到开启时自动显示。开启后仍可手动隐藏任务区域,重启 App 会保留这一选择。如果任务是唯一可见区域,关闭 Hook 时账户区域会自动开启。
### 菜单栏额度指示
@@ -92,7 +92,7 @@ CodexBar Helper 状态始终显示在关于页面,不受自动重置和防睡
| --- | --- |
| 未安装 | 尚未注册,且未发现组件或安装异常;首次使用时属于正常状态 |
| 未授权 | 已注册,仍需允许后台运行 |
-| 已授权 | 系统已允许后台运行,当前未发现组件异常;具体操作仍可能失败 |
+| 已授权 | 系统已允许后台运行,当前未发现组件异常 |
| 不可用 | 组件缺失、配置或签名异常,或未注册且安装失败 |
发现组件异常时,即使之前已授权,也会显示“不可用”。处理方式见 [CodexBarHelper 无法注册](troubleshooting.md#codexbarhelper-无法注册)
diff --git a/Docs/UserGuide/sleep-prevention.md b/Docs/UserGuide/sleep-prevention.md
index 54fdd9d..22b9ebe 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/sync-data-privacy.md b/Docs/UserGuide/sync-data-privacy.md
index 3f98b48..b4d03c6 100644
--- a/Docs/UserGuide/sync-data-privacy.md
+++ b/Docs/UserGuide/sync-data-privacy.md
@@ -29,7 +29,7 @@
- App 设置、代理配置和密码
- 日志、实时任务状态和异常会话保护记录
-**项目显示名会上传** 如果项目名包含不希望存入 iCloud 的信息,请关闭跨设备同步。
+项目显示名会上传。若不希望将项目名存入 iCloud,请关闭跨设备同步。
## 本机数据
diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.md
index da8d457..610bee7 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 22ac0c2..e91f0f7 100644
--- a/Docs/en/DeveloperGuide/activity-monitor.md
+++ b/Docs/en/DeveloperGuide/activity-monitor.md
@@ -270,7 +270,7 @@ Terminal signals reconcile by reliability:
### Two-Stage Approval Confirmation
-`PermissionRequest` indicates an approval flow, but reviewer may be user, policy, or automatic review.
+`PermissionRequest` accepts reviewers `user`, `auto_review`, and `guardian_subagent`.
If the Hook event includes reviewer, the task can confirm immediately. If reviewer is missing, it saves `pendingApprovalRequestedAt` and waits for rollout polling to fill it in.
@@ -290,17 +290,17 @@ With missing IDs, stop-before-start, or several candidates in one session, the m
## Snapshot Priority
-When several tasks and temporary states coexist, the outward snapshot uses this priority:
+The activity card selects content through `primaryActivity` in this order:
```text
Waiting for approval > Running > Recently completed > Recently terminated > Idle
```
-Completion remains green in the menu bar for 30 seconds. Task Center retains recent tasks for 10 minutes, while terminal deduplication memory lasts 24 hours.
+The menu bar also prioritizes waiting and running tasks. With no active tasks, it selects the latest completion or termination until 30 seconds after the end timestamp. Task Center retains terminal records for 10 minutes; terminal deduplication memory lasts 24 hours.
The snapshot feeds:
-- Menu bar status dot
+- Menu bar person symbol
- Main-panel task card
- Task Center
- Notification system
@@ -308,7 +308,7 @@ The snapshot feeds:
### Snapshot Publication
-The monitor polls rollout each second and also updates itself at several deadlines. Assigning the same value to `@Published` on every cycle would make SwiftUI and all Combine consumers recalculate unnecessarily.
+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.
@@ -320,11 +320,9 @@ All lists sort by most recent time first and then display UUID string. Stable or
### Cleanup Uses the Nearest Deadline
-The monitor manages completion highlight, terminal grace, activity retention, history retention, terminal deduplication, and protection-record expiration.
+The monitor manages terminal grace, activity retention, history retention, terminal deduplication, and protection-record expiration. `StatusItemController` independently manages the 30-second completion or termination indication; its expiration does not republish the activity snapshot.
-It does not scan everything on a fixed high-frequency timer. It gathers future deadlines and schedules one `Task` for the nearest. After it fires, it recalculates the next.
-
-This reduces meaningless wakeups for a resident menu bar app and lets every retention period take effect on time even without a new Hook event.
+The cleanup task waits for the nearest future deadline, processes it, then schedules the next.
## System Sleep and Wake
@@ -350,7 +348,7 @@ Rollout reconciliation must occur after a successful Hook drain.
Reading rollout first may find lifecycle data whose task key has not yet been added to the monitor from Hook events written during sleep. Resuming protection first could hide tasks from a pre-sleep last-progress time.
-`readerGeneration` prevents a returning wake task from using a reader replaced by a Hook settings change. `recoveryGeneration` prevents an older recovery from unpausing evaluation after two overlapping sleep or settings changes.
+`tailReaderGeneration` prevents a returning wake task from using a reader replaced by a Hook settings change. `activityProtectionRecoveryGeneration` prevents an older recovery from unpausing evaluation after two overlapping sleep or settings changes.
## Stalled Task Protection
@@ -406,7 +404,7 @@ Saved records restore protection during the next bootstrap. Hiding does not wait
Shortening the threshold immediately reevaluates running tasks already past it.
-Lengthening it silently restores suppressed tasks that no longer exceed the new threshold and clears their records and notifications. Tasks still beyond the new threshold remain suppressed without duplicate alerts.
+Increasing the threshold silently restores suppressed tasks that no longer exceed it and clears their records and notifications. Tasks still beyond the threshold remain hidden.
Turning off the sleep-prevention switch disables Activity Protection and restores all suppressed tasks in the current process.
diff --git a/Docs/en/DeveloperGuide/app-server.md b/Docs/en/DeveloperGuide/app-server.md
index 9889e5e..7be1af3 100644
--- a/Docs/en/DeveloperGuide/app-server.md
+++ b/Docs/en/DeveloperGuide/app-server.md
@@ -29,7 +29,7 @@ CodexCLIResolver
`CodexStatusService` owns the connection and same-account cache. `CodexStatusViewModel` owns only UI loading state, automatic-refresh timing, and the latest connection information.
-This division lets Settings reuse the same app-server session to read and write Hook and TUI configuration without giving a view direct ownership of `Process` or pipes.
+Settings reuses this session for Hook and TUI configuration.
## Locating Codex CLI
@@ -238,8 +238,6 @@ One refresh reads account, rate limits, and usage; Reset Credits details are inc
`fetchData` uses one `didRefresh` latch for the entire cycle. The first authentication failure triggers `account/read(refreshToken: true)`, and later methods reuse that result. A second authentication requirement is classified as signed out.
-This avoids repeatedly refreshing the same credential during one UI refresh.
-
## Refresh Model
The status view model refreshes every 60 seconds by default. Users can double-click the account icon in the main panel to request an immediate refresh.
@@ -267,8 +265,6 @@ Confirm or create connection
Rate limits and usage are supplemental. As long as the account is valid, CodexBar still creates a snapshot when both interfaces return no data so the UI can show the account and an explicit “No Data.”
-Treating missing supplemental interfaces as signed out would make identity flicker between real sign-in and error and would hide the difference between authentication problems and one unsupported new method.
-
### Cache Decision Table
| Current result | Same-account cache | Output | stale |
@@ -410,8 +406,8 @@ When Automatic Reset requests a full rate-limit refresh while an ordinary refres
Hook settings reuse the app-server flow but maintain independent availability state:
-- `isEnabled` means the target handler is installed
-- `isVerified` means the latest explicit app-server validation passed
+- `isEnabled` tracks enabled state for the current process, initially restored from an existing handler; configuration lost during runtime triggers repair
+- `isVerified` defaults to `true`, then retains the latest explicit validation result
- `isOperable` is true only when both are `true`
- A transient RPC failure preserves the last explicit validation result
@@ -428,8 +424,6 @@ Enabling or validating Hook calls `readyConnectionInfo()`:
- It parses the running version from the handshake user agent
- An unparseable version is treated as unsupported rather than allowed optimistically
-This is a capability-safety boundary. A future feature depending on an app-server method must place its minimum-version check at the actual connection-capability entry point, not merely show an on-disk version on About.
-
## Request Logs
[`RequestLog.swift`](../../../CodexBar/Services/CodexStatus/RequestLog.swift) keeps the latest 500 request records in memory for the in-app Logs window.
diff --git a/Docs/en/DeveloperGuide/architecture.md b/Docs/en/DeveloperGuide/architecture.md
index fa3d455..ddfd42c 100644
--- a/Docs/en/DeveloperGuide/architecture.md
+++ b/Docs/en/DeveloperGuide/architecture.md
@@ -118,7 +118,7 @@ Releasing asynchronously in `applicationWillTerminate` is too late because that
## Three Independent Data Flows
-CodexBar does not use a single aggregation service for all state. The three flows have different inputs, freshness needs, and failure semantics:
+Three data flows manage distinct inputs, freshness requirements, and failure states:
| Flow | Input | Output | Main consumers |
| --- | --- | --- | --- |
@@ -197,7 +197,7 @@ The monitor must not perform blocking file reads directly. `HookEventTailReader`
## Model Layers
-The project does not reuse one large object directly across app-server DTOs, persistence, and views:
+Models separate external input, persistence, domain state, and presentation:
| Model type | Role | Design requirement |
| --- | --- | --- |
@@ -211,14 +211,14 @@ For example, `CodexQuotaSnapshot` can carry both a current value and a stale mar
## Lifecycles and Retention
-Different states have different lifetimes and cannot share one cache duration:
+State lifetimes are:
| State | Lifetime | Reason |
| --- | --- | --- |
| app-server connection | A 1-hour reuse limit checked on requests | Later requests rebuild with the binary on disk |
| app-server supplemental cache | Current account only | Prevents values from leaking across accounts |
| Hook live bootstrap window | 24 hours | Covers long-running tasks that may still be active |
-| Completion highlight | 30 seconds | Short menu bar feedback |
+| Menu bar completion or termination | 30 seconds | Brief feedback for the latest terminal state |
| Task Center terminal history | 10 minutes | Provides recent context without occupying the UI indefinitely |
| Terminal deduplication memory | 24 hours | Prevents late Hook or rollout data from reviving old tasks |
| Raw Hook data and daily aggregations | 210 days | Supports long-term metrics and rebuilding |
diff --git a/Docs/en/DeveloperGuide/design-decisions.md b/Docs/en/DeveloperGuide/design-decisions.md
index beec1b9..15b8670 100644
--- a/Docs/en/DeveloperGuide/design-decisions.md
+++ b/Docs/en/DeveloperGuide/design-decisions.md
@@ -26,7 +26,7 @@ Sleep prevention represents these layers with `isEnabled`, `sleepBlockReason`, a
| --- | --- |
| Temporary app-server supplemental failure | Use same-account stale cache with reduced UI opacity; do not trigger quota alerts or automatic redemption |
| Unsupported method | Cache missing capability for the session and probe again after rebuilding the connection |
-| Missing historical Hook count | Retain `nil` in persisted and sync models; current display projection still falls back to counts |
+| Missing historical Hook count | Persisted and sync models retain `nil`; display projection applies each metric’s fallback rule |
| Live reader cannot obtain a stable boundary | Publish degraded health and pause Activity Protection |
The source layer supplies these states; consumers determine whether to display data or perform effects. See [Hook Aggregation](hook-and-aggregation.md) for count projection and [app-server](app-server.md) for account caches.
diff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.md
index 76a0732..35fe5df 100644
--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md
@@ -39,7 +39,7 @@ Installation adds the CodexBar handler as a separate command within the existing
- On disable, remove only an exact CodexBar handler match
- Preserve unrecognized configuration unchanged
-`isEnabled` is the Hook's enabled state for the current process and is initially restored from an existing CodexBar handler. `isVerified` means the most recent app-server validation passed. The UI treats Hook as a working source only when `isOperable` is true.
+`isEnabled` tracks enabled state for the current process, initially restored from an existing CodexBar handler. `isVerified` defaults to `true`, then retains the latest explicit validation result. Live tasks and related features use their conjunction, `isOperable`; historical aggregation and sync use `isEnabled` to consume stored data.
### Validation State
@@ -47,7 +47,7 @@ A handler in `hooks.json` does not prove Codex will execute it. `isOperable` com
### Reconciliation of an Enabled Hook
-CodexBar reconciles an enabled Hook at app launch, when Settings refreshes, whenever the menu panel opens, and after each quota refresh. Automatic quota refresh normally completes every 60 seconds, so configuration and trust state usually converge within 60 seconds:
+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
- An unknown version or transient RPC failure preserves the user's configuration
@@ -56,7 +56,7 @@ CodexBar reconciles an enabled Hook at app launch, when Settings refreshes, when
- Missing trust entries or changed hashes are repaired only for entries whose command, `sourcePath`, and event belong to the current CodexBar
- A complete required event set leaves `hooks.json` unchanged
-Reconciliation derives its work from the current required event set and actual file contents; it stores no one-time migration marker. Future required events and manually removed handlers therefore use the same repair path. If no recognizable CodexBar handler remains before app launch, the initial read cannot restore the enabled state, so Hook remains off.
+Reconciliation compares the required event set with the configuration and restores missing handlers. If no recognizable CodexBar handler exists at startup, Hook remains off.
### Enable Transaction Order
@@ -142,13 +142,9 @@ Timeout depends on event:
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.
-Invalid stdin, lock timeout, or write failure is swallowed. A statistics failure in the Hook subprocess must never block Codex.
-
### Failure Exit
-Hook metrics are supplemental to CodexBar and not required for Codex to finish a task. Returning a nonzero exit code after a parsing or disk error could turn one statistics failure into a user's Codex failure.
-
-After explicitly entering `--hook-event` mode, the process therefore reports handled and exits successfully regardless of input validity. Failure loses one statistic but never escalates into an upstream task failure.
+In `--hook-event` mode, invalid input, lock timeouts, and write errors all exit successfully so capture failures do not block Codex.
### Locked Event and Maintenance Transaction
@@ -166,14 +162,6 @@ If append and pending were separate lock transactions, the app could finish main
The joint commit keeps “the file grew” consistent with “maintenance knows it must read.”
-### Lock-Wait Budget
-
-Codex waits at most 3 seconds for `SessionEnd` and 5 seconds for other events. The recorder caps lock waiting at total budget minus 2 seconds.
-
-The reserve covers encoding, append, saving maintenance state, and process exit. Spending the whole budget on the lock could let Codex terminate the process mid-write, leaving a partial line or unmatched maintenance state.
-
-Waiting backs off exponentially from 1 ms to 20 ms. Normal app critical sections are short, so a small start resumes quickly after release, while the cap avoids busy looping under contention.
-
### Lock File Creation
Code must not check for absence, create, then reopen. Two processes could create different inodes; after one replaces the directory entry, both would lock separate files and each believe it has exclusivity.
@@ -408,7 +396,7 @@ Increment the schema for:
- Changed deduplication rules
- Changed source-generation merge semantics
-After upgrade, CodexBar fully rebuilds from raw JSONL within the 210-day retention period instead of performing field-level historical migration. Every aggregation under one schema is then generated by the same current algorithm.
+A schema mismatch triggers a full rebuild from raw JSONL within the 210-day retention period, without field-level historical migration.
User-requested rebuilding uses the same full-recalculation path and marks dates for replacement in sync.
diff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.md
index 1e6947e..2d5d7b4 100644
--- a/Docs/en/DeveloperGuide/notifications.md
+++ b/Docs/en/DeveloperGuide/notifications.md
@@ -96,7 +96,7 @@ Returning above the threshold rearms crossing detection, but one reset cycle sti
### Threshold Crossing
-“Currently below 10%” is a persistent state. “Just dropped below 10%” is the notification event. For each `account + limit + window`, the service stores the previous remaining percentage:
+For each `account + limit + window`, the service stores the previous remaining percentage and applies these notification rules:
- Notify when the previous value was above the threshold and the current value is not
- Notify once when the first in-session value is already at or below the threshold
@@ -177,13 +177,14 @@ Protection notifications use the system default sound and a `retryCount` of `0`
When low battery or the duration limit stops sleep prevention, `KeepAliveController` first releases its helper lease. It submits the notification only if the reply reports source `.codexBar` and `SleepDisabled=0`; other results clear the pending notice for that cycle.
-It submits the notification only after confirmation. The app idle assertion remains until notification submission completes, preventing a closed-lid Mac from sleeping before the notification reaches the system. The controller then releases the assertion and, if needed, issues a compensating lid-close sleep.
+The app idle assertion remains until notification submission finishes, then is released before any compensating lid-close sleep.
## Sounds
-[`NotificationSoundOption.swift`](../../../CodexBar/Services/Notifications/NotificationSoundOption.swift) combines three option groups:
+[`NotificationSoundOption.swift`](../../../CodexBar/Services/Notifications/NotificationSoundOption.swift) provides these sound choices:
-- No sound
+- System default notification sound
+- Silence
- System sounds available on macOS
- Sounds bundled with the app
@@ -210,8 +211,6 @@ Haptic feedback is off by default. When enabled, it uses 10 pulses roughly 100 m
Haptics are a separate local feedback channel from system notifications. They respond to completion or waiting transitions for non-anonymous tasks and follow the notification master switch and haptics switch, but do not depend on system authorization, a category switch, or the completion-duration threshold.
-This separation lets a user disable banners while keeping consistent task haptics. The upstream transition must still be valid; bootstrap history and anonymous tasks never trigger it.
-
## Submission and Deduplication
Notifications are submitted through `UNUserNotificationCenter`:
@@ -273,7 +272,7 @@ It is completely independent of CodexBar system notifications:
- Enabling the master switch for the first time requests system permission correctly
- Settings presents an understandable state when permission is denied
-- Low-rate-limit alerts occur only on downward threshold crossings
+- Low-quota alerts fire on a first reading at or below the threshold or a downward threshold crossing, with deduplication within each reset cycle
- An initial 100% rate limit does not produce a false reset alert
- Explicit Automatic Reset `reset` sends “Automatic Reset”; a later return to zero can independently send “Rate Limit Reset”
- Explicit `alreadyRedeemed` is treated as success and stops retries
diff --git a/Docs/en/DeveloperGuide/sleep-prevention.md b/Docs/en/DeveloperGuide/sleep-prevention.md
index fb6571e..feb0be7 100644
--- a/Docs/en/DeveloperGuide/sleep-prevention.md
+++ b/Docs/en/DeveloperGuide/sleep-prevention.md
@@ -106,7 +106,7 @@ Both app and helper use monotonically increasing generations:
[`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift) establishes sleep prevention only when all conditions hold:
- Prevent System Sleep is enabled
-- Hook is enabled and validated
+- Hook’s `isOperable` is `true`
- At least one live task qualifies under settings
- CodexBarHelper is installed and connectable
- The low-battery threshold is not active
@@ -170,7 +170,7 @@ The About row and both feature captions use `helperInstallationStatus`. System r
- Missing components, invalid configuration, or invalid signatures display Unavailable even when macOS still returns `.enabled`; a later successful package check clears the issue
- Missing components found before registration update only the package issue and start a fresh check, without storing a duplicate registration error; older results cannot overwrite the new issue, and revalidation can restore the display after repairs even with both features off
- Historical registration errors do not override pending approval or authorization; an unregistered helper with a failed installation displays Unavailable
-- Validation results stay in memory and do not guarantee successful execution; XPC timeouts and individual power-operation failures retain their existing error handling
+- Package validation results stay in memory; separate operation errors report XPC timeouts and power-operation failures
Wake schedules converge from actual system state rather than depending only on normal-exit cleanup:
@@ -269,8 +269,6 @@ Security and reliability requirements are:
- Commits use a temporary file, full sync, and atomic rename
- At startup, a missing record creates idle state; owned or restoring records restore `disablesleep 0`; unreadable or untrusted records also trigger restoration to `0`
-The file records CodexBar's ownership of system sleep settings.
-
Automatic Reset wake events are not stored there. macOS power management persists them under an identity formed from the current Debug or Release helper mach service plus `.auto-reset`, with fixed type `wake`.
## Leases and Failure Recovery
diff --git a/Docs/en/DeveloperGuide/sync.md b/Docs/en/DeveloperGuide/sync.md
index 72ac82b..00ba3c1 100644
--- a/Docs/en/DeveloperGuide/sync.md
+++ b/Docs/en/DeveloperGuide/sync.md
@@ -71,8 +71,6 @@ Sync must distinguish device contributions without uploading a raw hardware iden
The raw `IOPlatformUUID` is never uploaded. One device receives a stable pseudonym within one iCloud account and a different value in another account.
-The private account salt gives the same device a different pseudonym in each iCloud account.
-
The salt lives in the same private custom zone. If several devices attempt initial creation, they converge on the existing record by reading it after a CloudKit conflict instead of keeping incompatible salts.
Local state records the most recently resolved `deviceId`. If it changes, sync clears the old cursor and remote cache while retaining pending replacement dates. A device-identity change means the cached account scope is untrusted and cannot continue incrementally.
@@ -154,7 +152,7 @@ Merge rules are:
### Multiple Sources for One Device and Date
-Legacy record names contain only `deviceId + date`. New source records may use `deviceId + date + sourceGeneration`.
+Record names support both `deviceId + date` and `deviceId + date + sourceGeneration`.
A generation record identifies one raw source. Same-source local and cloud results replace one another, while clearly distinct sources may represent independent contributions created on the same day.
@@ -205,7 +203,7 @@ For each replacement date, sync:
While replacement is in progress, the snapshot filters the current device's cloud cache for that date and shows the latest local aggregation. Even if the app quits between deletion and reupload, the UI does not add the old cloud contribution to the new local contribution.
-The full fetch before deletion is the crucial detail. An incremental cursor guarantees completeness only after its position; it cannot prove that an older app or manual deletion never caused the local cache to miss records. Full enumeration prevents ghost generations from remaining.
+Before replacement deletes records, a full fetch finds every generation for the device and date, including records missing from the incremental cache.
## Incremental Cursor and Local Cache
@@ -233,7 +231,7 @@ The three files have different recovery costs:
`cursor.data` stores the opaque CloudKit token with secure coding; code does not inspect its structure. After a full fetch, sync must also create a new cursor baseline, or the next cycle may consume all recently fetched changes again from an empty cursor.
-The local `3 -> 4` read path rebuilds the remote cache before committing new state. An unknown schema falls back to empty sync state because misinterpreting upload confirmations is more dangerous than resynchronizing.
+Reading local schema `3` rebuilds the remote cache before saving schema `4`; unknown schemas resynchronize from empty local state.
Any change to record fields, identity, or schema is a compatibility decision. It must account for old apps still writing, new apps reading old fields, and whether downgrade can overwrite new records—not merely increment a constant.
diff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
index 086c389..f239c17 100644
--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
@@ -48,26 +48,29 @@ Shutdown reverses the order, except for helper-owned system state. AppDelegate f
The status icon combines app-server loading state, the menu bar rate-limit setting, and the task-activity snapshot.
-Task-status priority is:
+Icon priority is:
```text
-Waiting for approval (orange) > Running (blue) > Within 30 seconds of completion (green)
+Account error > Waiting for approval > Running > Latest completion or termination within 30 seconds > Idle
```
-Recent termination, idle state, and expired completion highlights show no task dot. Icon output is cached by input state; inactive or unavailable states use reduced alpha.
+When no tasks are active, `CodexActivitySnapshot.statusItemActivity(at:)` selects the latest terminal timestamp. `StatusItemController` schedules expiration 30 seconds after that timestamp, then restores the plain person. It recalculates on wake and cancels the old task on state changes or uninstall.
-### Separating Image State from Tooltip State
+### Separating Icon State from Tooltip State
-`StatusIconState` contains both image and tooltip inputs, but `renderState` retains only fields that change pixels:
+`StatusIconState` retains activity and quota inputs. `StatusItemIconPresentation` publishes only changes to symbol name, quota, visibility, and stale state:
-- Active-task duration changes every minute and updates only the tooltip
-- When expired rate-limit data remains visible from cache, the icon and progress indicator use reduced alpha
-- A roughly 0.18-second, 10-frame animation starts only when the indicator dot or rate-limit bar appears or disappears
-- A new render state cancels the previous animation; every frame confirms that its target is still current
+- Minute-by-minute duration updates affect only the tooltip
+- Cached quota dims the symbol and arc
+- Symbol-name changes use nonrepeating `.replace.magic(fallback: .downUp.byLayer)` transitions
+- Showing or hiding quota animates the colored arc between zero and the current percentage over 0.3 seconds; the track fades independently
+- Symbols share a baseline; hiding quota restores normal size with a 0.2-second size and position transition
+- Hiding quota retains its last percentage and color for retraction; zero and unavailable quota remain distinct
+- Initial rendering and wake reconciliation disable transitions
-With no status dot or rate-limit bar, the icon remains a template image so the system colors it for light mode, dark mode, and menu bar state. Adding custom colors or a progress bar switches to explicit color rendering.
+A persistent SwiftUI view lives inside the native `NSStatusBarButton`, with a transparent image preserving automatic spacing. Symbols use the system foreground color. The hosting view rejects focus and hit testing, leaving mouse actions with the original button.
-The tooltip starts a 60-second timer only when a live task duration exists; it does not retain a permanent timer while idle. The app also sets `NSInitialToolTipDelay` to 500 ms so the status explanation for this small click target is easier to discover.
+The tooltip updates every 60 seconds while tasks are active and stops its timer when idle. `NSInitialToolTipDelay` is 500 ms.
Left-click opens the main panel. Right-click or Control-click opens the context menu.
@@ -128,6 +131,10 @@ When animations are disabled, `CodexStatusMenuView` sets the root transaction's
`MenuSurfaceVisibilityState` begins after the panel is shown and ends when closing starts. Each presentation increments `presentationGeneration`; the rate-limit and usage sections use that value as their view identity and run their entrance animations again.
+### 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` with continuous `.symbolEffect(.rotate.byLayer, options: .repeat(.continuous))` animation. The tooltip identifies `sleepPreventionSource`.
+
## Fallback Panel
The status-bar button's screen position may be unavailable or untrusted when a global shortcut fires. [`FallbackPanelController.swift`](../../../CodexBar/Controllers/FallbackPanelController.swift) then presents a floating panel on the screen under the pointer.
@@ -189,11 +196,11 @@ Context-menu actions wait until menu tracking finishes before running, avoiding
- Placement prefers centering on the status item's screen, then falls back to the window screen or main screen
- A minimized window is deminiaturized before activation
-Settings-window height follows the complete content of the current tab while pinning the top edge and constraining the window to the visible screen frame. When the content fits within that screen limit, the window must contain the entire page without a scrollbar; `ScrollView` is only a safety fallback when the content physically cannot fit in the visible area. The pinned top prevents the entire window from drifting vertically between tabs and keeps the title bar as a stable visual anchor.
+The Settings window sizes to the current tab, keeps its top edge fixed, and stays within the visible screen. `ScrollView` handles content taller than the available screen height.
-During initial construction, SwiftUI may report the page height before `HostingWindowController` stores `window`. `SettingsWindowController` caches the latest valid measurement and applies it once the window is ready. Otherwise, the only height callback can be discarded, leaving the window at its initial size until a tab switch triggers another measurement.
+SwiftUI may report height before window creation finishes. `SettingsWindowController` caches the latest valid measurement and applies it once `HostingWindowController.window` is ready.
-Secondary panels for main-panel layout, notifications, Automatic Reset, and sleep prevention are created on demand. Once created, a controller retains its content and any required content-height subscriptions for its lifetime. Prebuilding every panel at app launch would keep unused UI participating in updates.
+Secondary panels for main-panel layout, notifications, Automatic Reset, and sleep prevention are created on first use, then reuse their content and required height subscriptions.
These four settings child panels contain interactive controls, so they use a keyable `KeyableBorderlessPanel`. The main panel's Heatmap, Reset Credits, and Task Center details use a nonactivating `NonactivatingSidePanel`. When a settings child panel closes, `SidePanelSupport.orderOut` restores focus to its parent only if that child panel is still the key window. If focus has already moved intentionally to the main panel or another window, it must not be taken back, or the newly opened interaction surface may close immediately after losing focus.
@@ -208,7 +215,7 @@ Each secondary-settings entry uses its own availability decision:
When a condition becomes false, Settings sends the corresponding `close` action so an unavailable child panel does not remain visible. Automatic Reset and sleep-prevention rows show no status explanation while their main switches are off.
-`MainPanelSettings` stores the order and visibility of Account, Task Center, Quota, Token Usage, and Footer Status with stable section identifiers. Layout normalization removes duplicates, ignores invalid values, appends missing sections, and keeps at least one section visible. After reading a disabled Hook state, `StatusItemController` calls `updateHookEnabled(_:)` to persist Task Center as hidden. If Task Center was the only visible section, Account is enabled at the same time. The settings panel disables only the Task Center switch, so its drag handle remains available. Temporary availability of other data sources affects only the current rendering.
+`MainPanelSettings` stores the order and visibility of Account, Task Center, Quota, Token Usage, and Footer Status with stable section identifiers. Layout normalization removes duplicates, ignores invalid values, appends missing sections, and keeps at least one section visible. After reading a disabled Hook state, `StatusItemController` calls `updateHookEnabled(_:)` to persist Task Center as hidden. If Task Center was the only visible section, Account is enabled at the same time. Switching Hook from off to on automatically shows Task Center; initial restoration of an enabled Hook and repeated enabled notifications preserve the saved layout. The settings panel disables only the Task Center switch, so its drag handle remains available. Temporary availability of other data sources affects only the current rendering.
Layout sorting uses a custom `DragGesture` on the handle. A floating copy follows the pointer, other rows move when it crosses half a row, and releasing calls `setSectionOrder(_:)` once to persist the final order.
@@ -252,7 +259,7 @@ The main panel shows a refresh countdown. Double-clicking the account icon reque
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 refreshes local Hook statistics. The delayed task also reconciles installed Hook configuration and is canceled if the panel closes while it waits.
+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.
## Localization and Formatting
@@ -274,6 +281,10 @@ 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
+- Menu bar symbols follow task state; terminal feedback expires 30 seconds after the task ends and is recalculated on wake
+- Quota-arc visibility animates, zero quota retains the track, and cached quota dims
+- The sun badge rotates while sleep prevention is active, disappears when it ends, and shows the correct state when reopening
+- Password reveal transitions preserve text, selection, and focus
- Clicking outside the main panel dismisses it; clicking a side panel does not
- Heatmap, Reset Credits, and Task Center panels remain mutually exclusive
- With Token Usage at different positions in the main-panel order, heatmap details align to the complete heatmap area's top edge when possible and fall back to the main panel's bottom edge when the detail height does not fit
@@ -283,7 +294,7 @@ Release scripts require Developer ID, signing, and notarization credentials and
- On the first Settings open after a cold launch, General immediately uses its full content height; switching among all three tabs adapts the window height, with no scrollbar when screen space is sufficient
- Main Panel Layout, Notification, Automatic Reset, and sleep-prevention child panels remain mutually exclusive, align their top edges with their setting rows, and resize correctly when content changes
- With a settings child panel open, opening the main panel from the menu bar keeps the main panel open, closes the settings child panel, and does not steal focus back to Settings
-- While reordering the main panel, the floating row follows the pointer, other rows make room after the drag crosses half a row, and release settles smoothly while persisting only the final order; reordering and visibility changes can be undone step by step with `Command-Z` and redone with `Command-Shift-Z` while either the Settings window or any settings child panel has focus; the result persists across relaunches; the last visible section cannot be hidden; disabling Hook turns Task Center off and disables its switch without blocking drag, enables Account if Task Center was the only visible section, and does not enter automatic Hook changes into user undo history
+- While reordering the main panel, the floating row follows the pointer, other rows make room after the drag crosses half a row, and release settles smoothly while persisting only the final order; reordering and visibility changes can be undone step by step with `Command-Z` and redone with `Command-Shift-Z` while either the Settings window or any settings child panel has focus; the result persists across relaunches; the last visible section cannot be hidden; disabling Hook turns Task Center off and disables its switch without blocking drag, enables Account if Task Center was the only visible section; re-enabling Hook shows Task Center automatically, while a manual hide survives relaunch; automatic Hook changes do not enter user undo history
- Opening Settings or Logs from the context menu does not lose focus
- 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
@@ -300,3 +311,5 @@ Release scripts require Developer ID, signing, and notarization credentials and
- [`SettingsWindowController.swift`](../../../CodexBar/Controllers/SettingsWindowController.swift)
- [`LogWindowController.swift`](../../../CodexBar/Controllers/LogWindowController.swift)
- [`CodexStatusMenuView.swift`](../../../CodexBar/Views/Menu/CodexStatusMenuView.swift)
+- [`StatusItemIconView.swift`](../../../CodexBar/Views/Menu/StatusItemIconView.swift)
+- [`CodexActivityCard.swift`](../../../CodexBar/Views/Menu/CodexActivityCard.swift)
diff --git a/Docs/en/UserGuide/main-panel.md b/Docs/en/UserGuide/main-panel.md
index 4fb0cb7..e2d9fbe 100644
--- a/Docs/en/UserGuide/main-panel.md
+++ b/Docs/en/UserGuide/main-panel.md
@@ -4,22 +4,25 @@
## Menu Bar Icon
-CodexBar combines its icon, a status dot, and an optional rate-limit bar to show account, task, and rate-limit status:
+CodexBar combines a person symbol with an optional circular rate-limit arc:
| Appearance | Meaning |
| --- | --- |
-| Normal account icon | Account data is available |
-| Error account icon | You are signed out, initialization failed, or trusted rate-limit and usage data is unavailable |
-| Blue status dot | At least one task is running |
-| Orange status dot | At least one task is waiting for your approval |
-| Green status dot | A task has just finished; the highlight remains for 30 seconds |
-| Rate-limit bar beside the icon | Remaining percentage in the selected rate-limit window |
+| Plain person | Default or idle state |
+| Slashed person | You are signed out, initialization failed, or trusted rate-limit and usage data is unavailable |
+| Clock badge | At least one task is running |
+| Key badge | At least one task is waiting for approval |
+| Shield with a checkmark | A task finished within the last 30 seconds |
+| Shield with an exclamation mark | A task was terminated within the last 30 seconds |
+| Circular arc with a bottom gap | Remaining percentage in the selected rate-limit window, using the same colors as the panel |
-When several states exist at once, waiting for approval takes priority over running, and running takes priority over recently completed.
+Account errors take priority, followed by waiting for approval, running, and the latest completion or termination within 30 seconds. The most recent timestamp determines which terminal state appears.
+
+The person symbol grows when the quota arc is hidden.
Hover over the menu bar icon to see the current task state, project name, elapsed time, number of concurrent tasks, and remaining percentage in the selected rate-limit window.
-When rate-limit data comes from cache, the icon and progress bar become translucent to indicate that the visible data is not the latest snapshot.
+Cached rate-limit data dims the icon and arc. Zero quota retains the empty track; unavailable or disabled quota hides the arc.
## Layout Customization
@@ -98,7 +101,7 @@ The card shows the following fields when available:
- Number of other concurrent tasks
- Anonymous-task icon
-When sleep prevention is actively engaged, a coffee-cup indicator appears on the right side of the activity card.
+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.
Tasks whose session cannot be identified show an orange anonymous icon with the tooltip `Anonymous tasks do not prevent sleep`.
@@ -115,9 +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; termination means it was interrupted and does not trigger a completion notification.
-
-Completion does not guarantee a successful result.
+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.
## Footer Status
diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.md
index 0948ad6..f858152 100644
--- a/Docs/en/UserGuide/settings.md
+++ b/Docs/en/UserGuide/settings.md
@@ -19,7 +19,7 @@ Right-click or Control-click the menu bar icon and choose `Settings`, or press `
Click the options button to drag sections into order or toggle visibility, keeping at least one section visible. Use `⌘Z` to undo and `⌘⇧Z` to redo. Hiding a section does not stop its features.
-Disabling Hook turns off Tasks; enable it manually after re-enabling Hook. If Tasks was the only visible section, Account is enabled automatically.
+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.
### Menu Bar Quota Indicator
@@ -92,7 +92,7 @@ CodexBar Helper status always appears in About, regardless of the Automatic Rese
| --- | --- |
| Not Installed | Not yet registered, with no detected component or installation issue; normal on first use |
| Not Authorized | Registered, but still needs permission to run in the background |
-| Authorized | Background execution is approved and no component issue is currently detected; individual operations can still fail |
+| Authorized | Background execution is approved and no component issue is currently detected |
| Unavailable | Components are missing, configuration or signatures are invalid, or installation failed while unregistered |
A detected component issue displays Unavailable even if authorization was previously granted. See [CodexBarHelper Cannot Be Registered](troubleshooting.md#codexbarhelper-cannot-be-registered).
diff --git a/Docs/en/UserGuide/sleep-prevention.md b/Docs/en/UserGuide/sleep-prevention.md
index a4750a5..d86db8a 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 coffee cup in the main panel 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 rotating 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/sync-data-privacy.md b/Docs/en/UserGuide/sync-data-privacy.md
index ca7f05a..b555533 100644
--- a/Docs/en/UserGuide/sync-data-privacy.md
+++ b/Docs/en/UserGuide/sync-data-privacy.md
@@ -29,7 +29,7 @@ The following are not synced:
- App settings, proxy configuration, and passwords
- Logs, live task state, and Stalled Task Protection records
-**Project display names are uploaded.** Disable cross-device sync if a project name contains information you do not want stored in iCloud.
+Project display names are uploaded. Disable cross-device sync if you do not want those names stored in iCloud.
## Local Data
diff --git a/Docs/en/UserGuide/troubleshooting.md b/Docs/en/UserGuide/troubleshooting.md
index fef9258..e113787 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 coffee cup indicates that system sleep is actually being prevented. An enabled switch without a coffee cup is not necessarily an error.
+The rotating sun badge appears only while sleep prevention is active and activity-card data is available.
If Settings says `System sleep is disabled by another source`, CodexBar does not overwrite that source.
@@ -95,7 +95,7 @@ If Settings says `System sleep is disabled by another source`, CodexBar does not
- Not Installed is normal on first use; the app attempts installation and registration after you enable `Automatic Reset` or `Prevent System Sleep` and confirm
- For Not Authorized, click `Open System Settings` below an enabled feature's settings row and allow CodexBar to run in the background
- Confirm that CodexBar is in Applications and that the app bundle is complete
-- `CodexBar Helper is missing components or configuration. Please reinstall CodexBar` means required bundle components or configuration are absent; `CodexBar Helper has invalid components or configuration. Please reinstall CodexBar` means configuration or signature validation failed; reinstall the complete CodexBar app in either case
+- `Helper incomplete. Reinstall CodexBar` means required bundle components or configuration are absent; `Helper validation failed. Reinstall CodexBar` means configuration or signature validation failed; reinstall the complete CodexBar app in either case
- After repairing the app bundle, restart or reactivate the app to recheck it; a successful check automatically clears the component issue without requiring either feature to be enabled
- If failures continue after an update, quit CodexBar, reopen it, and check authorization again
diff --git a/README.en.md b/README.en.md
index 8b2e4ae..7b25061 100644
--- a/README.en.md
+++ b/README.en.md
@@ -33,7 +33,7 @@ It can notify you when a task finishes, needs approval, or when your rate limits
- See every rate-limit window, its remaining allowance, and reset time
- Check available credits and banked resets
- Automatically use banked resets from 15 minutes to 6 hours before they expire, with a default lead time of 30 minutes; CodexBar can wake your Mac at the scheduled time and revalidate availability before use
-- Show a selected rate-limit window directly beside the menu bar icon
+- Show the remaining percentage of a selected rate-limit window as a menu bar arc
### Understand your Codex usage
@@ -44,7 +44,7 @@ It can notify you when a task finishes, needs approval, or when your rate limits
### Keep track of active tasks
-- Menu bar status dots distinguish running tasks, tasks waiting for approval, and recently completed tasks
+- Menu bar person badges distinguish running tasks, tasks waiting for approval, recent completions, and recent terminations
- 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
diff --git a/README.md b/README.md
index e629abb..7d4afce 100644
--- a/README.md
+++ b/README.md
@@ -33,7 +33,7 @@ CodexBar 是面向 macOS 15 及更高版本的菜单栏 App,用于集中展示
- 展示全部额度窗口、剩余比例和重置时间
- 展示可用积分和留存重置
- 支持自动重置,可设置在留存重置过期前 15 分钟到 6 小时执行,默认提前 30 分钟;计划到点时可唤醒 Mac,并在执行前重新确认可用状态
-- 可在菜单栏图标旁直接显示所选额度窗口
+- 可通过菜单栏圆弧直接显示所选额度窗口的剩余比例
### 看见自己的 Codex 使用节奏
@@ -44,7 +44,7 @@ CodexBar 是面向 macOS 15 及更高版本的菜单栏 App,用于集中展示
### 不错过正在发生的任务
-- 菜单栏状态点区分运行中、等待批准和刚完成任务
+- 菜单栏人物徽章区分运行中、等待批准、最近完成和最近终止任务
- 主面板展示当前任务、项目、模型、推理强度和持续时间
- 任务中心集中查看并发任务、最近完成和最近终止记录
- 支持任务完成、等待批准和异常会话提醒
@@ -99,7 +99,7 @@ brew install --cask bob-zebedy/tap/codexbar
| --- | --- |
| [用户指南](Docs/UserGuide/README.md) | 安装、主面板、Hook、通知、防睡眠、同步、全部设置和问题排查 |
| [开发者指南](Docs/DeveloperGuide/README.md) | 架构、数据链路、核心状态机、存储、隐私边界和开发验证 |
-| [文档导航](Docs/README.md) | 文档导航 |
+| [文档导航](Docs/README.md) | 全部文档入口 |
## 隐私
diff --git a/Scripts/performance/README.md b/Scripts/performance/README.md
index 1293a36..5b2cc50 100644
--- a/Scripts/performance/README.md
+++ b/Scripts/performance/README.md
@@ -117,7 +117,7 @@ python3 -B Scripts/performance/run.py \
脚本核对 App 的 bundle ID、系统、芯片、架构、核心数、内存容量、电源来源、Instruments、场景说明、预设、预算、数据格式和阶段计划。两次采集均完整且上述条件一致时,报告展示各阶段平均 CPU 差值和 footprint 中位数差值;条件不匹配时列出差异字段。App 版本可以不同。
-预设的采集轮次或时长调整后,需要按新配置重新采集基线。旧结果仍可打开和重新生成报告,但与新阶段计划比较时会标记为条件不匹配。
+基线必须使用相同的阶段计划;轮次或时长不同会标记为条件不匹配。
## 输出文件与重新生成报告
diff --git a/Scripts/performance/report.html b/Scripts/performance/report.html
index 1fac5d2..203d209 100644
--- a/Scripts/performance/report.html
+++ b/Scripts/performance/report.html
@@ -1076,7 +1076,7 @@
<aside class="sidebar">
<div class="brand">PERFORMANCE LAB</div>
<strong>@@APP@@</strong>
- <nav aria-label="报告目录">
+ <nav>
<a href="#overview"><span>01</span>数据总览</a>
<a href="#comparison"><span>02</span>阶段对比</a>
<a href="#io"><span>03</span>唤醒与磁盘</a>
@@ -1094,8 +1094,7 @@
<div class="actions">
<button
id="theme"
- type="button"
- aria-label="切换深浅主题">
+ type="button">
切换主题
</button>
<button
@@ -1256,7 +1255,6 @@
cursor.setAttribute('x2', x);
output.textContent = `${t.toFixed(2)} s · ${value === null ? 'N/A' : value.toFixed(2) + ' ' + unit}`;
input.value = index;
- input.setAttribute('aria-valuetext', output.textContent);
}
input.addEventListener('input', () => select(Number(input.value)));
diff --git a/Scripts/performance/report.py b/Scripts/performance/report.py
index a75155c..90bbfec 100644
--- a/Scripts/performance/report.py
+++ b/Scripts/performance/report.py
@@ -34,7 +34,7 @@ def chart(series, key, label, color, unit, phase_index, ceiling=None, step=False
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}" role="img" aria-label="{escape(label)} 趋势, 单位 {escape(unit)}">']
+ f'<svg viewBox="0 0 {width} {height}">']
for index in range(5):
value = maximum * index / 4
yy = y(value)
@@ -68,7 +68,7 @@ def chart(series, key, label, color, unit, phase_index, ceiling=None, step=False
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" aria-label="{escape(label)} 采样时间"><output aria-live="polite"></output></div></div>')
+ 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)
@@ -88,7 +88,7 @@ def bars(groups, unit="", digits=2):
low, high = min([0] + values), max([0] + values)
extent = high - low or 1
zero = -low / extent * 100
- parts = [f'<div class="bar-chart" role="img" aria-label="{escape(unit)} 柱状图">']
+ 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:
@@ -116,7 +116,7 @@ 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" role="img" aria-label="主线程 {ratio:.1f}%, 其他线程 {100 - ratio:.1f}%"><i style="width:{ratio:.4f}%;background:{COLORS[0]}"></i><i style="width:{100 - ratio:.4f}%;background:{COLORS[1]}"></i></div>
+ 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>'''
@@ -135,7 +135,7 @@ def interval_chart(rows, paired=False):
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" role="img" aria-label="{escape(description)}"><i class="interval-line" style="left:{x(min(first, last)):.4f}%;width:{x(abs(last - first)):.4f}%"></i>')
+ 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>')
diff --git a/appcast.xml b/appcast.xml
index c901810..f8a4126 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 3.7.3</title>
+ <sparkle:version>87</sparkle:version>
+ <sparkle:shortVersionString>3.7.3</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.7.3</sparkle:releaseNotesLink>
+ <pubDate>Fri, 11 Sep 2026 10:54:05 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.7.3.dmg" sparkle:edSignature="flVY9wzxdXofkq6V49wbXltcNxvsNa5+6cuQLwntiu2xNZZE51sO6DcP+A6Q6ZthgeeRAG6hMbTzCAkPGKHpBw==" length="7927637" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.7.2</title>
<sparkle:version>86</sparkle:version>