Skip to content

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

fix: 修正用量兼容与每日统计口径

Bobf69c7680df44
diff --git a/CodexBar/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swift
index 2ba94c5..dc5dbc9 100644
--- a/CodexBar/Models/CodexStatusError.swift
+++ b/CodexBar/Models/CodexStatusError.swift
@@ -6,6 +6,7 @@ nonisolated enum CodexStatusError: LocalizedError {
case serverTimeout
case serverConnectionClosed
case invalidServerResponse
+ case invalidResponsePayload
case serverError(String)
case unsupportedMethod
case unsupportedVersion(minimum: String)
@@ -19,7 +20,7 @@ nonisolated enum CodexStatusError: LocalizedError {
String(localized: "codex-status.error.server-timeout")
case .serverConnectionClosed:
String(localized: "codex-status.error.connection-closed")
- case .invalidServerResponse:
+ case .invalidServerResponse, .invalidResponsePayload:
String(localized: "codex-status.error.invalid-response")
case let .serverError(message):
message
@@ -63,7 +64,7 @@ nonisolated enum CodexStatusError: LocalizedError {
/// 参数或协议形状不正确时继续用同一请求重试不会恢复
var isProtocolOrParameterFailure: Bool {
switch self {
- case .unsupportedMethod, .unsupportedVersion:
+ case .invalidResponsePayload, .unsupportedMethod, .unsupportedVersion:
true
case .serverError:
serverErrorMessageContains("invalid params")
@@ -76,7 +77,7 @@ nonisolated enum CodexStatusError: LocalizedError {
}
}
- /// 连接断开, 超时, 无法解析都需要重建 app-server 会话
+ /// 连接断开, 超时或 JSON-RPC 信封无效时需要重建 app-server 会话
var isTransportFailure: Bool {
switch self {
case .serverConnectionClosed, .serverTimeout, .invalidServerResponse:
diff --git a/CodexBar/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swift
index 6f407da..2fe3899 100644
--- a/CodexBar/Models/CodexUsageModels.swift
+++ b/CodexBar/Models/CodexUsageModels.swift
@@ -3,20 +3,28 @@ import Foundation
/// app-server account/usage 的原始响应, summary 和按日 bucket 分开使用
nonisolated struct AccountUsageResponse: Decodable {
let summary: UsageSummary
- let dailyUsageBuckets: [DailyUsageBucket]
+ let dailyUsageBuckets: [DailyUsageBucket]?
}
/// token 区域展示的汇总指标
nonisolated struct UsageSummary: Decodable, Equatable {
let currentStreakDays: Int?
- let lifetimeTokens: Int
+ let lifetimeTokens: Int?
let longestRunningTurnSec: Int?
let longestStreakDays: Int?
- let peakDailyTokens: Int
+ let peakDailyTokens: Int?
+
+ var hasAvailableMetrics: Bool {
+ currentStreakDays != nil
+ || lifetimeTokens != nil
+ || longestRunningTurnSec != nil
+ || longestStreakDays != nil
+ || peakDailyTokens != nil
+ }
}
/// 单日 token bucket, startDate 使用 yyyy-MM-dd 作为稳定键
-nonisolated struct DailyUsageBucket: Decodable, Equatable {
+nonisolated struct DailyUsageBucket: Decodable {
let startDate: String
let tokens: Int
}
@@ -24,24 +32,28 @@ nonisolated struct DailyUsageBucket: Decodable, Equatable {
/// token 热力图使用的只读快照, 负责按日期聚合重复 bucket
nonisolated struct CodexUsageSnapshot: Equatable {
let summary: UsageSummary
- let dailyBuckets: [DailyUsageBucket]
/// 构造时聚合一次; 该快照在菜单面板每次渲染中被反复查询
- private let tokensByDate: [String: Int]
+ private let tokensByDate: [String: Int]?
- init(summary: UsageSummary, dailyBuckets: [DailyUsageBucket]) {
- self.summary = summary
- self.dailyBuckets = dailyBuckets
- tokensByDate = dailyBuckets.reduce(into: [String: Int]()) { result, bucket in
- result[bucket.startDate, default: 0] += bucket.tokens
- }
+ var hasDailyUsageBuckets: Bool {
+ tokensByDate != nil
}
- static func == (lhs: CodexUsageSnapshot, rhs: CodexUsageSnapshot) -> Bool {
- lhs.summary == rhs.summary && lhs.dailyBuckets == rhs.dailyBuckets
+ var hasAppServerData: Bool {
+ summary.hasAvailableMetrics || hasDailyUsageBuckets
+ }
+
+ init(summary: UsageSummary, dailyBuckets: [DailyUsageBucket]?) {
+ self.summary = summary
+ tokensByDate = dailyBuckets.map { buckets in
+ buckets.reduce(into: [String: Int]()) { result, bucket in
+ result[bucket.startDate, default: 0] += bucket.tokens
+ }
+ }
}
func tokenCount(on date: Date) -> Int? {
let startDate = CodexDateFormat.dayString(from: date)
- return tokensByDate[startDate]
+ return tokensByDate?[startDate]
}
}
diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swift
index c222ba7..548b977 100644
--- a/CodexBar/Models/CodexWorkflowModels.swift
+++ b/CodexBar/Models/CodexWorkflowModels.swift
@@ -49,7 +49,7 @@ private nonisolated enum WorkflowCountResolution {
return compactedCount
}
- if let identifiers, !identifiers.isEmpty {
+ if let identifiers {
return Set(identifiers).count
}
@@ -489,10 +489,11 @@ nonisolated struct WorkflowDailyAccumulator {
case .none: break
}
- if let sessionId = event.sessionId {
+ // SessionEnd 只关闭会话, Stop 只关闭轮次, 不单独构成对应的当日活跃记录
+ if event.hookEvent != .sessionEnd, let sessionId = event.sessionId {
sessionIds.insert(sessionId)
}
- if let turnId = event.turnId {
+ if event.hookEvent != .stop, let turnId = event.turnId {
turnIds.insert(turnId)
}
@@ -513,12 +514,8 @@ nonisolated struct WorkflowDailyAccumulator {
aggregate.sessionIds = Self.normalizedIdentifiers(sessionIds)
aggregate.turnIds = Self.normalizedIdentifiers(turnIds)
case .compacted:
- aggregate.sessionCount = sessionIds.isEmpty
- ? aggregate.sessionStartCount
- : sessionIds.count
- aggregate.turnCount = turnIds.isEmpty
- ? aggregate.stopCount
- : turnIds.count
+ aggregate.sessionCount = sessionIds.count
+ aggregate.turnCount = turnIds.count
aggregate.sessionIds = nil
aggregate.turnIds = nil
}
@@ -529,9 +526,8 @@ nonisolated struct WorkflowDailyAccumulator {
count = (count ?? 0) + 1
}
- private static func normalizedIdentifiers(_ identifiers: Set<String>) -> [String]? {
- let normalized = identifiers.sorted()
- return normalized.isEmpty ? nil : normalized
+ private static func normalizedIdentifiers(_ identifiers: Set<String>) -> [String] {
+ identifiers.sorted()
}
}
@@ -666,7 +662,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
turnIds = nil
}
- /// 正数压缩计数和非空 ID 集合优先, 明确的 0 在没有 ID 时同样有效
+ /// 正数压缩计数和可用 ID 集合优先, 空集合保留明确的 0
private var resolvedSessionCount: Int {
WorkflowCountResolution.resolvedCount(
compactedCount: sessionCount,
@@ -821,8 +817,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable {
}
private static func normalizedIdentifiers(_ identifiers: [String]?) -> [String]? {
- let normalized = Set(identifiers ?? []).sorted()
- return normalized.isEmpty ? nil : normalized
+ identifiers.map { Set($0).sorted() }
}
private static func date(from string: String) -> Date? {
diff --git a/CodexBar/Models/UsageHeatmapDay.swift b/CodexBar/Models/UsageHeatmapDay.swift
index ec607f8..d537a76 100644
--- a/CodexBar/Models/UsageHeatmapDay.swift
+++ b/CodexBar/Models/UsageHeatmapDay.swift
@@ -15,13 +15,14 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {
}
static func grid(
- usage: CodexUsageSnapshot,
+ usage: CodexUsageSnapshot?,
workflow: WorkflowSnapshot,
showsWorkflow: Bool,
columnCount: Int,
today: Date
) -> [UsageHeatmapDay?] {
- let todayTokenCount = usage.tokenCount(on: today)
+ let todayTokenCount = usage?.tokenCount(on: today)
+ let hasDailyUsageBuckets = usage?.hasDailyUsageBuckets == true
// Hook 开启时当天工作流统计可见
// Hook 关闭时只在 token bucket 已返回时展示今天
let endingDaysAgo = showsWorkflow || todayTokenCount != nil ? 0 : 1
@@ -35,17 +36,22 @@ nonisolated struct UsageHeatmapDay: Equatable, Identifiable {
endingDaysAgo: endingDaysAgo,
today: today
)
- .map { date in
+ .map { date -> UsageHeatmapDay? in
guard let date else {
return nil
}
let startDate = CodexDateFormat.dayString(from: date)
+ let tokenCount: Int? = if !hasDailyUsageBuckets {
+ nil
+ } else if startDate == todayString {
+ todayTokenCount
+ } else {
+ usage?.tokenCount(on: date) ?? 0
+ }
return UsageHeatmapDay(
startDate: startDate,
- tokenCount: startDate == todayString
- ? todayTokenCount
- : usage.tokenCount(on: date) ?? 0,
+ tokenCount: tokenCount,
workflow: workflowByDate[startDate] ?? .empty(startDate: startDate)
)
}
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index b258cf2..ddcc5b1 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -4417,6 +4417,22 @@
}
}
},
+ "usage.heatmap.no-data" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "No daily usage data"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "暂无日用量数据"
+ }
+ }
+ }
+ },
"usage.heatmap.past-weeks" : {
"localizations" : {
"en" : {
diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swift
index 9497815..0de5223 100644
--- a/CodexBar/Services/CodexStatus/AppServerSession.swift
+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift
@@ -215,13 +215,20 @@ final nonisolated class AppServerSession {
token: UUID,
decoder: JSONDecoder
) throws -> Response {
- if let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: line.data) {
- if let error = envelope.error {
- try failRequest(token, message: line.text, error: .serverError(error.message))
- }
- if let result = envelope.result {
- return result
- }
+ let envelope: RPCResponseEnvelope<Response>
+ do {
+ envelope = try decoder.decode(RPCResponseEnvelope<Response>.self, from: line.data)
+ } catch is RPCResponsePayloadDecodingError {
+ try failRequest(token, message: line.text, error: .invalidResponsePayload)
+ } catch {
+ try failRequest(token, message: line.text, error: .invalidServerResponse)
+ }
+
+ if let error = envelope.error {
+ try failRequest(token, message: line.text, error: .serverError(error.message))
+ }
+ if let result = envelope.result {
+ return result
}
try failRequest(token, message: line.text, error: .invalidServerResponse)
@@ -238,12 +245,35 @@ private nonisolated struct RPCIDEnvelope: Decodable {
let id: Int?
}
-/// error 与 result 合并在同一个信封里一次解码; 大响应行只完整解析一次
+/// error 与 result 合并在同一个信封里一次解码
+/// result 形状不匹配时单独分类, 响应行已消费不会破坏会话边界
private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {
let error: RPCError?
let result: Response?
+
+ private enum CodingKeys: String, CodingKey {
+ case error
+ case result
+ }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ error = try container.decodeIfPresent(RPCError.self, forKey: .error)
+ guard error == nil else {
+ result = nil
+ return
+ }
+
+ do {
+ result = try container.decodeIfPresent(Response.self, forKey: .result)
+ } catch {
+ throw RPCResponsePayloadDecodingError()
+ }
+ }
}
+private nonisolated struct RPCResponsePayloadDecodingError: Error {}
+
private nonisolated struct RPCError: Decodable {
let message: String
}
diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swift
index 63cc322..67bfc4a 100644
--- a/CodexBar/Services/Workflow/WorkflowService.swift
+++ b/CodexBar/Services/Workflow/WorkflowService.swift
@@ -1239,7 +1239,7 @@ nonisolated struct WorkflowDayMaintenanceState: Codable, Equatable {
/// maintenance.json 的全局状态, pending 表示可增量, dirty 表示需全量重建
nonisolated struct WorkflowMaintenanceState: Codable, Equatable {
/// 原始事件到每日聚合的算法版本, 变化时统一从原始 JSONL 重建
- static let currentAggregationSchema = 5
+ static let currentAggregationSchema = 6
var schema: Int
var pending: [String]
diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swift
index 0867a76..a3e9def 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift
@@ -164,9 +164,10 @@ private extension CodexStatusMenuView {
@ViewBuilder
func usageSection(dataPlaceholderSection: MainPanelSection?) -> some View {
- if let snapshot = viewModel.snapshot, let usage = snapshot.usage {
+ if let snapshot = viewModel.snapshot,
+ snapshot.usage != nil || codexHookSettings.isEnabled {
UsageSummaryView(
- usage: usage,
+ usage: snapshot.usage,
workflow: workflowViewModel.snapshot,
showsWorkflow: codexHookSettings.isEnabled,
isStale: snapshot.isUsageStale,
@@ -206,6 +207,7 @@ private extension CodexStatusMenuView {
viewModel.snapshot?.limits.isEmpty == false
case .usage:
viewModel.snapshot?.usage != nil
+ || (viewModel.snapshot != nil && codexHookSettings.isEnabled)
case .account, .activity, .status:
false
}
diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swift
index df9de2e..081ea44 100644
--- a/CodexBar/Views/Menu/UsageHeatmap.swift
+++ b/CodexBar/Views/Menu/UsageHeatmap.swift
@@ -26,7 +26,7 @@ nonisolated struct UsageHeatmapSelection: Equatable {
/// token 摘要和近 30 周热力图的组合区
struct UsageSummaryView: View {
- let usage: CodexUsageSnapshot
+ let usage: CodexUsageSnapshot?
let isStale: Bool
let showsWorkflow: Bool
let onHoverContextChange: (UsageHeatmapHoverContext?) -> Void
@@ -36,7 +36,7 @@ struct UsageSummaryView: View {
@State private var heatmapScreenFrame: CGRect?
init(
- usage: CodexUsageSnapshot,
+ usage: CodexUsageSnapshot?,
workflow: WorkflowSnapshot,
showsWorkflow: Bool,
isStale: Bool = false,
@@ -59,62 +59,91 @@ struct UsageSummaryView: View {
}
var body: some View {
- VStack(alignment: .leading, spacing: 8) {
- metricsGrid
-
- UsageHeatmap(
- days: days,
- selection: $hoverSelection,
- peakTokens: peakTokens,
- onScreenFrameChange: { frame in
- heatmapScreenFrame = frame
+ content
+ .markStale(isStale)
+ .padding(MenuMetrics.panelPadding)
+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)
+ .onAppear {
+ clearHover()
+ }
+ .onDisappear {
+ clearHover()
+ }
+ .onChange(of: days) { _, newDays in
+ refreshHoveredDay(from: newDays)
+ }
+ .onChange(of: hoverContext) { _, context in
+ onHoverContextChange(context)
+ }
+ .animation(Metrics.statusAnimation, value: usage)
+ .animation(Metrics.statusAnimation, value: days)
+ }
+
+ @ViewBuilder
+ private var content: some View {
+ if usage?.hasAppServerData == true || showsWorkflow {
+ VStack(alignment: .leading, spacing: 8) {
+ metricsGrid
+
+ if usage?.hasDailyUsageBuckets == true || showsWorkflow {
+ UsageHeatmap(
+ days: days,
+ selection: $hoverSelection,
+ peakTokens: peakTokens,
+ onScreenFrameChange: { frame in
+ heatmapScreenFrame = frame
+ }
+ )
+ } else {
+ dailyUsageUnavailable
}
- )
- }
- .markStale(isStale)
- .padding(MenuMetrics.panelPadding)
- .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)
- .onAppear {
- clearHover()
- }
- .onDisappear {
- clearHover()
- }
- .onChange(of: days) { _, newDays in
- refreshHoveredDay(from: newDays)
- }
- .onChange(of: hoverContext) { _, context in
- onHoverContextChange(context)
+ }
+ } else {
+ Text("common.empty.no-data")
+ .foregroundStyle(.secondary)
+ .frame(maxWidth: .infinity, alignment: .center)
+ .padding(.vertical, MenuMetrics.loadingVerticalPadding)
}
- .animation(Metrics.statusAnimation, value: usage)
- .animation(Metrics.statusAnimation, value: days)
}
private var metricsGrid: some View {
HStack(alignment: .firstTextBaseline, spacing: Metrics.metricSpacing) {
- tokenMetric(label: "usage.summary.lifetime-tokens", value: usage.summary.lifetimeTokens)
- tokenMetric(label: "usage.summary.peak-tokens", value: usage.summary.peakDailyTokens)
+ tokenMetric(label: "usage.summary.lifetime-tokens", value: usage?.summary.lifetimeTokens)
+ tokenMetric(label: "usage.summary.peak-tokens", value: usage?.summary.peakDailyTokens)
textMetric(
label: "usage.summary.current-streak",
- value: Self.dayText(usage.summary.currentStreakDays)
+ value: Self.dayText(usage?.summary.currentStreakDays)
)
textMetric(
label: "usage.summary.longest-streak",
- value: Self.dayText(usage.summary.longestStreakDays)
+ value: Self.dayText(usage?.summary.longestStreakDays)
)
textMetric(
label: "usage.summary.longest-chat",
- value: Self.durationText(seconds: usage.summary.longestRunningTurnSec)
+ value: Self.durationText(seconds: usage?.summary.longestRunningTurnSec)
)
}
}
- private func tokenMetric(label: LocalizedStringResource, value: Int) -> some View {
+ private func tokenMetric(label: LocalizedStringResource, value: Int?) -> some View {
metric(label: label) {
- TokenCountText(tokens: value)
+ if let value {
+ TokenCountText(tokens: value)
+ } else {
+ Text(verbatim: "--")
+ .font(.caption.monospacedDigit().weight(.semibold))
+ }
}
}
+ private var dailyUsageUnavailable: some View {
+ Text("usage.heatmap.no-data")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .frame(maxWidth: .infinity, alignment: .center)
+ .frame(height: UsageHeatmap.Metrics.height)
+ }
+
private func textMetric(label: LocalizedStringResource, value: String) -> some View {
metric(label: label) {
Text(value)
@@ -253,6 +282,8 @@ struct UsageHeatmap: View {
}
.onDisappear {
cancelHoverClearTask()
+ snapSelection = nil
+ selection = nil
onScreenFrameChange(nil)
}
}
@@ -494,7 +525,7 @@ extension UsageHeatmap {
// MARK: - 单元格
-/// 单个热力图方块, 蓝色透明度表示当天 token 强度
+/// 单个热力图方块, 蓝色透明度表示当天 token 强度, 中性色表示 token 数据不可用
private struct UsageHeatmapSquare: View {
let day: UsageHeatmapDay
let percent: Double
@@ -507,7 +538,7 @@ private struct UsageHeatmapSquare: View {
RoundedRectangle(cornerRadius: 4, style: .continuous)
.stroke(borderColor, lineWidth: isHovered ? 1.2 : 0.7)
}
- .shadow(color: .blue.opacity(0.22), radius: isHovered ? 5 : 0, y: isHovered ? 2 : 0)
+ .shadow(color: shadowColor, radius: isHovered ? 5 : 0, y: isHovered ? 2 : 0)
.scaleEffect(isHovered ? 1.08 : 1)
.frame(width: UsageHeatmap.Metrics.squareSize, height: UsageHeatmap.Metrics.squareSize)
.contentShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
@@ -519,6 +550,9 @@ private struct UsageHeatmapSquare: View {
}
private var fillColor: Color {
+ guard day.tokenCount != nil else {
+ return Color.secondary.opacity(isHovered ? 0.12 : 0.05)
+ }
guard day.tokensForHeatmap > 0 else {
return Color.blue.opacity(isHovered ? 0.16 : 0.08)
}
@@ -529,12 +563,19 @@ private struct UsageHeatmapSquare: View {
}
private var borderColor: Color {
+ guard day.tokenCount != nil else {
+ return Color.secondary.opacity(isHovered ? 0.42 : 0.12)
+ }
if isHovered {
return Color.blue.opacity(0.78)
}
return Color.blue.opacity(day.tokensForHeatmap > 0 ? 0.18 : 0.10)
}
+
+ private var shadowColor: Color {
+ day.tokenCount == nil ? .clear : .blue.opacity(0.22)
+ }
}
struct UsageHeatmapDayDetailView: View {
@@ -627,7 +668,7 @@ struct UsageHeatmapDayDetailView: View {
Spacer(minLength: 8)
- tokenIntensityStrip
+ tokenIntensityValue
.frame(width: Metrics.tokenIntensityStripWidth)
}
}
@@ -639,7 +680,7 @@ struct UsageHeatmapDayDetailView: View {
.foregroundStyle(.secondary)
.frame(width: Metrics.metricLabelWidth, alignment: .leading)
- tokenIntensityStrip
+ tokenIntensityValue
.frame(width: Metrics.tokenIntensityStripWidth)
.frame(maxWidth: .infinity, alignment: .trailing)
}
@@ -683,6 +724,19 @@ struct UsageHeatmapDayDetailView: View {
.frame(height: Metrics.tokenIntensityStripHeight)
}
+ @ViewBuilder
+ private var tokenIntensityValue: some View {
+ if context.day.tokenCount != nil {
+ tokenIntensityStrip
+ } else {
+ Text(verbatim: "--")
+ .foregroundStyle(Color.codexLabel)
+ .fontWeight(.semibold)
+ .monospacedDigit()
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ }
+ }
+
private var workflowMetricRows: [WorkflowMetricRow] {
[
WorkflowMetricRow(
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index 850aed7..5545941 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 3.6.12
-CURRENT_PROJECT_VERSION = 79
+MARKETING_VERSION = 3.6.13
+CURRENT_PROJECT_VERSION = 80
diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.md
index 8c28e73..865c2b5 100644
--- a/Docs/DeveloperGuide/app-server.md
+++ b/Docs/DeveloperGuide/app-server.md
@@ -296,7 +296,9 @@ stale 是数据可信度的一部分,新增展示时不能只复制数值而
`CodexUsageSnapshot` 构造时把可能重复的 daily bucket 聚合成 `tokensByDate`
-热力图在一次渲染中会反复查询日期。提前构造索引避免每个方块都线性扫描原始 bucket,同时保留原始数组用于快照相等比较。
+热力图在一次渲染中会反复查询日期。提前构造可选索引避免每个方块都线性扫描原始 bucket,并让快照相等比较只关注汇总指标、每日数据可用性和聚合后的每日 Token。原始 bucket 的顺序或拆分方式不影响展示结果,也不单独触发动画。
+
+`account/usage/read` 的 `summary` 必须存在,但汇总指标和 `dailyUsageBuckets` 均可为空。模型保留空值语义:汇总指标缺失时显示 `--`;`dailyUsageBuckets == nil` 表示每日数据不可用,空数组才表示已成功读取但没有记录。合法的部分响应不使用旧值填充;业务 payload 解码失败则按补充接口失败处理,不重建 app-server 会话或清空额度数据。
额度 limit 的展示顺序也在模型层统一:
diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.md
index 80ff15f..658dc84 100644
--- a/Docs/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/DeveloperGuide/hook-and-aggregation.md
@@ -421,6 +421,8 @@ inode 与 size 能发现替换和截断,boundary hash 能发现保持相同长
- project 分布
- model 分布
+session 数使用当天除 `SessionEnd` 外所有事件中的非空 session ID 去重计算。turn 数使用当天除 `Stop` 外所有事件中的非空 turn ID 去重计算。跨天 session 或 turn 只要当天仍有未被排除的事件,就计入当天;当天只有 `SessionEnd` 的 session 和只有 `Stop` 的 turn 不计入。
+
成对事件可能只有一侧成功落盘。因此计数使用能够避免重复且允许缺失的规则:
- tool call 使用 `max(PreToolUse, PostToolUse)`
@@ -460,7 +462,7 @@ compaction 和 subagent 成对事件使用相同规则。
## Schema 演进与重建
-当前聚合 schema 为 `5`,由 `WorkflowMaintenanceState.currentAggregationSchema` 管理。
+当前聚合 schema 为 `6`,由 `WorkflowMaintenanceState.currentAggregationSchema` 管理。
以下变化必须递增 schema:
diff --git a/Docs/UserGuide/activity-and-hook.md b/Docs/UserGuide/activity-and-hook.md
index d6a2be0..7b42e57 100644
--- a/Docs/UserGuide/activity-and-hook.md
+++ b/Docs/UserGuide/activity-and-hook.md
@@ -83,8 +83,8 @@ Hook 事件缺少 session ID 时,CodexBar 会按项目显示匿名任务。匿
| 事件 | 主要用途 |
| --- | --- |
-| `SessionStart` 和 `SessionEnd` | 会话生命周期、会话统计和任务收尾 |
-| `UserPromptSubmit` 和 `Stop` | 对话轮次、任务开始和完成候选 |
+| `SessionStart` 和 `SessionEnd` | 会话生命周期和任务收尾 |
+| `UserPromptSubmit` 和 `Stop` | 轮次生命周期、任务开始和完成候选 |
| `PreToolUse` 和 `PostToolUse` | 工具调用统计和任务进展 |
| `PermissionRequest` | 用户等待状态和权限请求统计 |
| `PreCompact` 和 `PostCompact` | 上下文压缩统计和任务进展 |
@@ -94,14 +94,16 @@ Hook 事件缺少 session ID 时,CodexBar 会按项目显示匿名任务。匿
| 指标 | 含义 |
| --- | --- |
-| 会话 | 当天不同 Codex session 的数量 |
-| 对话轮次 | 当天不同 turn 的数量 |
+| 会话 | 除 `SessionEnd` 外,当天其他事件中不同 session 的数量 |
+| 对话轮次 | 除 `Stop` 外,当天其他事件中不同 turn 的数量 |
| 工具调用 | `PreToolUse` 和 `PostToolUse` 两类计数中的较大值 |
| 权限请求 | `PermissionRequest` 事件数量 |
| 上下文压缩 | `PreCompact` 和 `PostCompact` 两类计数中的较大值 |
| 子 Agent | `SubagentStart` 和 `SubagentStop` 两类计数中的较大值 |
| 最常用模型 | 当天 Hook 事件中出现次数最多的模型 |
+session 和 turn 只统计非空 ID,并分别在当天去重。跨天 session 或 turn 如果当天仍有其他事件会计入当天;当天只有 `SessionEnd` 的 session 和只有 `Stop` 的 turn 不计入。
+
使用较大值可以在成对事件缺少一端时保留已经观察到的操作数量。
Auto-review 只从实时任务链路中排除,其 Hook 事件仍参与上述每日统计。
diff --git a/Docs/en/DeveloperGuide/app-server.md b/Docs/en/DeveloperGuide/app-server.md
index 50d4a71..62ef0ee 100644
--- a/Docs/en/DeveloperGuide/app-server.md
+++ b/Docs/en/DeveloperGuide/app-server.md
@@ -296,7 +296,9 @@ Automatic refresh waits for the remaining interval since the last completion. Af
`CodexUsageSnapshot` aggregates potentially repeated daily buckets into `tokensByDate` during initialization.
-A heatmap queries dates repeatedly during one render. Building the index up front avoids a linear scan for every cell while preserving the raw array for snapshot equality.
+A heatmap queries dates repeatedly during one render. Building an optional index up front avoids a linear scan for every cell and limits snapshot equality to summary metrics, daily-data availability, and aggregated daily tokens. Raw bucket ordering or partitioning does not affect the rendered result or independently trigger animation.
+
+The `summary` object from `account/usage/read` is required, but every summary metric and `dailyUsageBuckets` may be absent or null. The model preserves those states: a missing summary metric renders as `--`; `dailyUsageBuckets == nil` means daily data is unavailable, while an empty array means the read succeeded with no records. A valid partial response is not filled from older values. A business payload decoding failure is handled as a supplemental-read failure without rebuilding the app-server session or clearing rate-limit data.
Rate-limit ordering is also centralized in the model:
diff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.md
index 9fcae2f..86e0908 100644
--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md
@@ -421,6 +421,8 @@ Daily results include:
- Project distribution
- Model distribution
+The session count deduplicates nonempty session IDs from all events except `SessionEnd` on that day. The turn count deduplicates nonempty turn IDs from all events except `Stop` on that day. A session or turn spanning multiple days contributes to each day with a nonexcluded event; a session observed only through `SessionEnd` and a turn observed only through `Stop` do not contribute.
+
Only one side of a paired event may persist. Counts therefore use rules that avoid duplicates while tolerating missing data:
- Tool calls use `max(PreToolUse, PostToolUse)`
@@ -460,7 +462,7 @@ The UI can therefore distinguish:
## Schema Evolution and Rebuild
-The current aggregation schema is `5`, managed by `WorkflowMaintenanceState.currentAggregationSchema`.
+The current aggregation schema is `6`, managed by `WorkflowMaintenanceState.currentAggregationSchema`.
Increment the schema for:
diff --git a/Docs/en/UserGuide/activity-and-hook.md b/Docs/en/UserGuide/activity-and-hook.md
index 64f1b1e..e6a4624 100644
--- a/Docs/en/UserGuide/activity-and-hook.md
+++ b/Docs/en/UserGuide/activity-and-hook.md
@@ -83,8 +83,8 @@ The activity card and Task Center mark these tasks with an orange anonymous icon
| Event | Primary use |
| --- | --- |
-| `SessionStart` and `SessionEnd` | Session lifecycle, session metrics, and task finalization |
-| `UserPromptSubmit` and `Stop` | Turn metrics, task start, and completion candidates |
+| `SessionStart` and `SessionEnd` | Session lifecycle and task finalization |
+| `UserPromptSubmit` and `Stop` | Turn lifecycle, task start, and completion candidates |
| `PreToolUse` and `PostToolUse` | Tool-call metrics and task progress |
| `PermissionRequest` | User-waiting state and permission-request metrics |
| `PreCompact` and `PostCompact` | Context-compaction metrics and task progress |
@@ -94,14 +94,16 @@ The activity card and Task Center mark these tasks with an orange anonymous icon
| Metric | Meaning |
| --- | --- |
-| Sessions | Number of distinct Codex sessions on that day |
-| Turns | Number of distinct turns on that day |
+| Sessions | Distinct sessions in the day's events other than `SessionEnd` |
+| Turns | Distinct turns in the day's events other than `Stop` |
| Tool calls | The larger of the `PreToolUse` and `PostToolUse` counts |
| Permission requests | Number of `PermissionRequest` events |
| Context compactions | The larger of the `PreCompact` and `PostCompact` counts |
| Subagents | The larger of the `SubagentStart` and `SubagentStop` counts |
| Most-used model | The model that appears most often in Hook events for that day |
+Only nonempty session and turn IDs are counted and deduplicated within each day. A session or turn spanning multiple days contributes when that day contains another event; a session observed only through `SessionEnd` and a turn observed only through `Stop` do not contribute.
+
Using the larger count preserves observed operations when one side of an event pair is missing.
Auto-review is excluded only from the live-task pipeline; its Hook events still contribute to these daily metrics.
diff --git a/appcast.xml b/appcast.xml
index 6c0f7ed..66f8c7d 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.6.13</title>
+ <sparkle:version>80</sparkle:version>
+ <sparkle:shortVersionString>3.6.13</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.6.13</sparkle:releaseNotesLink>
+ <pubDate>Fri, 04 Sep 2026 12:32:29 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.6.13.dmg" sparkle:edSignature="mJtHp+TE/y1RSFiFVWvGjDVMe6VjWBKFGMQsIsCmpc2vBQtR9zeAPJBDeIMsabra5CxVKrpVcYosly3PAUKcAQ==" length="7636794" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.6.12</title>
<sparkle:version>79</sparkle:version>