Skip to content

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

refactor: 精简共享逻辑并优化状态处理

Bob8c7bfc39d40d
diff --git a/CodexBar/Controllers/ActivityCenterPanelController.swift b/CodexBar/Controllers/ActivityCenterPanelController.swift
index d1c74b9..d927b9d 100644
--- a/CodexBar/Controllers/ActivityCenterPanelController.swift
+++ b/CodexBar/Controllers/ActivityCenterPanelController.swift
@@ -7,8 +7,12 @@ import SwiftUI
final class ActivityCenterPanelController {
private let activityMonitor: CodexActivityMonitor
private let presentationState: CodexActivityCenterPresentationState
- private var panel: NSPanel?
- private var hostingController: NSHostingController<CodexActivityCenterView>?
+ private let contentHost = SidePanelContentHost<CodexActivityCenterView>(
+ initialSize: CodexActivityCenterView.initialPanelSize,
+ ignoresMouseEvents: false,
+ sizingOptions: [],
+ cornerRadius: CodexActivityCenterView.panelCornerRadius
+ )
private var currentContext: CodexActivityCenterPanelContext?
private weak var menuSurfaceWindow: NSWindow?
private weak var menuContentView: NSView?
@@ -19,7 +23,7 @@ final class ActivityCenterPanelController {
private lazy var presenter = SidePanelDrawerPresenter(
animationKey: Metrics.drawerTransformAnimationKey,
contentViewProvider: { [weak self] in
- self?.hostingController?.view
+ self?.contentHost.contentView
}
)
@@ -46,10 +50,7 @@ final class ActivityCenterPanelController {
}
func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {
- guard let panel, panel.isVisible else {
- return false
- }
- return panel.frame.contains(screenPoint)
+ contentHost.containsScreenPoint(screenPoint)
}
func toggle(
@@ -128,7 +129,7 @@ final class ActivityCenterPanelController {
return
}
- let panel = ensurePanel()
+ let panel = contentHost.ensurePanel()
cancelScheduledPanelUpdate()
currentContext = context
self.menuSurfaceWindow = menuSurfaceWindow
@@ -199,7 +200,7 @@ final class ActivityCenterPanelController {
}
private func updateVisibleLayout(for snapshot: CodexActivitySnapshot) {
- guard let panel,
+ guard let panel = contentHost.panel,
panel.isVisible,
let currentContext,
let menuSurfaceWindow else {
@@ -256,40 +257,14 @@ final class ActivityCenterPanelController {
panelUpdateTask = nil
}
- private func ensurePanel() -> NSPanel {
- if let panel {
- return panel
- }
-
- let panel = SidePanelSupport.makePanel(
- initialSize: CodexActivityCenterView.initialPanelSize,
- ignoresMouseEvents: false
- )
- self.panel = panel
- return panel
- }
-
private func updateContent(panelSize: CGSize) {
- let rootView = CodexActivityCenterView(
- activityMonitor: activityMonitor,
- presentationState: presentationState
- )
-
- if let hostingController {
- hostingController.rootView = rootView
- } else {
- let hostingController = NSHostingController(rootView: rootView)
- hostingController.sizingOptions = []
- panel?.contentViewController = hostingController
- self.hostingController = hostingController
- }
-
- SidePanelSupport.configureLayers(
- hostingView: hostingController?.view,
- contentView: panel?.contentView,
- cornerRadius: CodexActivityCenterView.panelCornerRadius
+ contentHost.updateContent(
+ CodexActivityCenterView(
+ activityMonitor: activityMonitor,
+ presentationState: presentationState
+ ),
+ size: panelSize
)
- panel?.setContentSize(panelSize)
}
private enum Metrics {
diff --git a/CodexBar/Controllers/FallbackPanelController.swift b/CodexBar/Controllers/FallbackPanelController.swift
index c965d65..bcac4ab 100644
--- a/CodexBar/Controllers/FallbackPanelController.swift
+++ b/CodexBar/Controllers/FallbackPanelController.swift
@@ -34,9 +34,7 @@ final class FallbackPanelController {
return
}
- panel.orderFrontRegardless()
- NSRunningApplication.current.activate(options: [])
- panel.makeKeyAndOrderFront(nil)
+ panel.bringToFrontActivatingApp()
}
func orderOut() {
@@ -68,16 +66,7 @@ final class FallbackPanelController {
}
private func contentSize(for panel: NSPanel) -> NSSize {
- guard let contentView = panel.contentViewController?.view else {
- return Metrics.fallbackSize
- }
-
- contentView.layoutSubtreeIfNeeded()
- let fittingSize = contentView.fittingSize
- guard fittingSize.width.isFinite,
- fittingSize.height.isFinite,
- fittingSize.width > 0,
- fittingSize.height > 0 else {
+ guard let fittingSize = panel.contentViewController?.view.validFittingSize else {
return Metrics.fallbackSize
}
diff --git a/CodexBar/Controllers/HeatmapDetailPanelController.swift b/CodexBar/Controllers/HeatmapDetailPanelController.swift
index c33a19b..33be624 100644
--- a/CodexBar/Controllers/HeatmapDetailPanelController.swift
+++ b/CodexBar/Controllers/HeatmapDetailPanelController.swift
@@ -5,11 +5,15 @@ import SwiftUI
/// 热力图 hover 详情控制器, 负责左右贴边定位和抽屉式切换动画
@MainActor
final class HeatmapDetailPanelController {
- private var panel: NSPanel?
- private var hostingController: NSHostingController<UsageHeatmapDayDetailView>?
+ private let contentHost = SidePanelContentHost<UsageHeatmapDayDetailView>(
+ initialSize: UsageHeatmapDayDetailView.panelSize(showsWorkflow: true),
+ ignoresMouseEvents: true,
+ sizingOptions: [.preferredContentSize],
+ cornerRadius: UsageHeatmapDayDetailView.panelCornerRadius
+ )
private lazy var drawerAnimator = SidePanelDrawerAnimator(
contentViewProvider: { [weak self] in
- self?.hostingController?.view
+ self?.contentHost.contentView
},
animationKey: Metrics.drawerTransformAnimationKey,
overscan: SidePanelSupport.Metrics.drawerOverscan
@@ -22,11 +26,7 @@ final class HeatmapDetailPanelController {
private weak var menuSurfaceWindow: NSWindow?
func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {
- guard let panel, panel.isVisible else {
- return false
- }
-
- return panel.frame.contains(screenPoint)
+ contentHost.containsScreenPoint(screenPoint)
}
func update(
@@ -53,7 +53,7 @@ final class HeatmapDetailPanelController {
drawerTransition = .idle
pendingSideSwitchRequest = nil
- guard let panel, panel.isVisible else {
+ guard let panel = contentHost.panel, panel.isVisible else {
return
}
@@ -71,7 +71,7 @@ final class HeatmapDetailPanelController {
guard let self,
!Task.isCancelled,
generation == visibilityGeneration,
- let panel = self.panel,
+ let panel = contentHost.panel,
panel.isVisible else {
return
}
@@ -105,7 +105,7 @@ final class HeatmapDetailPanelController {
) {
cancelHideTask()
- let panel = ensurePanel()
+ let panel = contentHost.ensurePanel()
let wasVisible = panel.isVisible
if wasVisible {
attach(panel, to: menuSurfaceWindow)
@@ -280,19 +280,6 @@ final class HeatmapDetailPanelController {
}
}
- private func ensurePanel() -> NSPanel {
- if let panel {
- return panel
- }
-
- let panel = SidePanelSupport.makePanel(
- initialSize: UsageHeatmapDayDetailView.panelSize(showsWorkflow: true),
- ignoresMouseEvents: true
- )
- self.panel = panel
- return panel
- }
-
private func attach(_ panel: NSPanel, to parentWindow: NSWindow) {
menuSurfaceWindow = parentWindow
SidePanelSupport.attach(panel, to: parentWindow)
@@ -303,24 +290,10 @@ final class HeatmapDetailPanelController {
}
private func updateContent(_ context: UsageHeatmapHoverContext) {
- let rootView = UsageHeatmapDayDetailView(context: context)
- let size = UsageHeatmapDayDetailView.panelSize(showsWorkflow: context.showsWorkflow)
-
- if let hostingController {
- hostingController.rootView = rootView
- } else {
- let hostingController = NSHostingController(rootView: rootView)
- hostingController.sizingOptions = [.preferredContentSize]
- panel?.contentViewController = hostingController
- self.hostingController = hostingController
- }
-
- SidePanelSupport.configureLayers(
- hostingView: hostingController?.view,
- contentView: panel?.contentView,
- cornerRadius: UsageHeatmapDayDetailView.panelCornerRadius
+ contentHost.updateContent(
+ UsageHeatmapDayDetailView(context: context),
+ size: UsageHeatmapDayDetailView.panelSize(showsWorkflow: context.showsWorkflow)
)
- panel?.setContentSize(size)
}
private func apply(_ request: PanelRequest, to panel: NSPanel) {
diff --git a/CodexBar/Controllers/HostingWindowController.swift b/CodexBar/Controllers/HostingWindowController.swift
index 9dc12c2..c7b7e1d 100644
--- a/CodexBar/Controllers/HostingWindowController.swift
+++ b/CodexBar/Controllers/HostingWindowController.swift
@@ -64,9 +64,7 @@ class HostingWindowController {
}
(window as? AuxiliaryHostingWindow)?.allowsKeyFocus = true
- window.orderFrontRegardless()
- NSRunningApplication.current.activate(options: [])
- window.makeKeyAndOrderFront(nil)
+ window.bringToFrontActivatingApp()
}
func setAllowsKeyFocus(_ allowsKeyFocus: Bool) {
diff --git a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
index 162a185..eb0e7db 100644
--- a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
+++ b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift
@@ -171,9 +171,7 @@ final class MenuSurfaceDismissMonitor {
return
}
- activeMenuSurfaceWindow.orderFrontRegardless()
- NSRunningApplication.current.activate(options: [])
- activeMenuSurfaceWindow.makeKeyAndOrderFront(nil)
+ activeMenuSurfaceWindow.bringToFrontActivatingApp()
}
private func removeEventMonitor(_ monitor: inout Any?) {
diff --git a/CodexBar/Controllers/NotificationOptionsPanelController.swift b/CodexBar/Controllers/NotificationOptionsPanelController.swift
index 37549e3..5c49ee4 100644
--- a/CodexBar/Controllers/NotificationOptionsPanelController.swift
+++ b/CodexBar/Controllers/NotificationOptionsPanelController.swift
@@ -182,20 +182,7 @@ final class NotificationOptionsPanelController {
}
private func measuredPanelSize() -> CGSize {
- guard let hostingView = hostingController?.view else {
- return NotificationOptionsView.initialPanelSize
- }
-
- hostingView.layoutSubtreeIfNeeded()
- let fittingSize = hostingView.fittingSize
- guard fittingSize.width.isFinite,
- fittingSize.height.isFinite,
- fittingSize.width > 0,
- fittingSize.height > 0 else {
- return NotificationOptionsView.initialPanelSize
- }
-
- return fittingSize
+ hostingController?.view.validFittingSize ?? NotificationOptionsView.initialPanelSize
}
private enum Metrics {
diff --git a/CodexBar/Controllers/ResetCreditsPanelController.swift b/CodexBar/Controllers/ResetCreditsPanelController.swift
index e63bd69..209aa4c 100644
--- a/CodexBar/Controllers/ResetCreditsPanelController.swift
+++ b/CodexBar/Controllers/ResetCreditsPanelController.swift
@@ -4,12 +4,16 @@ import SwiftUI
/// 重置次数详情控制器, 复用共享侧边抽屉定位和动画
@MainActor
final class ResetCreditsPanelController {
- private var panel: NSPanel?
- private var hostingController: NSHostingController<ResetCreditsPanelView>?
+ private let contentHost = SidePanelContentHost<ResetCreditsPanelView>(
+ initialSize: ResetCreditsPanelView.initialPanelSize,
+ ignoresMouseEvents: false,
+ sizingOptions: [.preferredContentSize],
+ cornerRadius: ResetCreditsPanelView.panelCornerRadius
+ )
private lazy var presenter = SidePanelDrawerPresenter(
animationKey: Metrics.drawerTransformAnimationKey,
contentViewProvider: { [weak self] in
- self?.hostingController?.view
+ self?.contentHost.contentView
}
)
@@ -18,11 +22,7 @@ final class ResetCreditsPanelController {
}
func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {
- guard let panel, panel.isVisible else {
- return false
- }
-
- return panel.frame.contains(screenPoint)
+ contentHost.containsScreenPoint(screenPoint)
}
func toggle(
@@ -56,7 +56,7 @@ final class ResetCreditsPanelController {
return
}
- let panel = ensurePanel()
+ let panel = contentHost.ensurePanel()
let menuSurfaceFrame = SidePanelSupport.contentScreenFrame(for: contentView, in: menuSurfaceWindow) ?? menuSurfaceWindow.frame
let alignmentScreenFrame = SidePanelSupport.validatedAlignmentScreenFrame(
context.alignmentScreenFrame,
@@ -83,43 +83,10 @@ final class ResetCreditsPanelController {
SidePanelSupport.restoreMenuSurfaceKeyWindow(menuSurfaceWindow)
}
- updateContent(resolvedContext, size: panelSize)
+ contentHost.updateContent(ResetCreditsPanelView(context: resolvedContext), size: panelSize)
presenter.present(panel, at: position, relativeTo: menuSurfaceWindow)
}
- private func ensurePanel() -> NSPanel {
- if let panel {
- return panel
- }
-
- let panel = SidePanelSupport.makePanel(
- initialSize: ResetCreditsPanelView.initialPanelSize,
- ignoresMouseEvents: false
- )
- self.panel = panel
- return panel
- }
-
- private func updateContent(_ context: ResetCreditsPanelContext, size: CGSize) {
- let rootView = ResetCreditsPanelView(context: context)
-
- if let hostingController {
- hostingController.rootView = rootView
- } else {
- let hostingController = NSHostingController(rootView: rootView)
- hostingController.sizingOptions = [.preferredContentSize]
- panel?.contentViewController = hostingController
- self.hostingController = hostingController
- }
-
- SidePanelSupport.configureLayers(
- hostingView: hostingController?.view,
- contentView: panel?.contentView,
- cornerRadius: ResetCreditsPanelView.panelCornerRadius
- )
- panel?.setContentSize(size)
- }
-
private func panelPosition(
for panelSize: CGSize,
menuSurfaceFrame: CGRect,
diff --git a/CodexBar/Controllers/ScreenGeometry.swift b/CodexBar/Controllers/ScreenGeometry.swift
index 2b2b4ea..57e61bd 100644
--- a/CodexBar/Controllers/ScreenGeometry.swift
+++ b/CodexBar/Controllers/ScreenGeometry.swift
@@ -23,3 +23,30 @@ nonisolated extension CGRect {
&& height > 0
}
}
+
+extension NSWindow {
+ /// LSUIElement 应用无 Dock 图标, 把窗口可靠拉到最前依赖这套固定激活序列
+ @MainActor
+ func bringToFrontActivatingApp() {
+ orderFrontRegardless()
+ NSRunningApplication.current.activate(options: [])
+ makeKeyAndOrderFront(nil)
+ }
+}
+
+extension NSView {
+ /// SwiftUI hosting 视图的 fittingSize 可能给出非有限或非正尺寸, 校验通过才能用于窗口布局
+ @MainActor
+ var validFittingSize: NSSize? {
+ layoutSubtreeIfNeeded()
+ let size = fittingSize
+ guard size.width.isFinite,
+ size.height.isFinite,
+ size.width > 0,
+ size.height > 0 else {
+ return nil
+ }
+
+ return size
+ }
+}
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index 9a8feca..abb6f9a 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -70,11 +70,8 @@ final class SettingsWindowController: HostingWindowController {
}
override func prepareForDisplay(_ window: NSWindow) {
- window.contentViewController?.view.layoutSubtreeIfNeeded()
-
- if let fittingSize = window.contentViewController?.view.fittingSize,
- let contentSize = clampedContentSize(fittingSize, for: window) {
- window.setContentSize(contentSize)
+ if let fittingSize = window.contentViewController?.view.validFittingSize {
+ window.setContentSize(clampedContentSize(fittingSize, for: window))
}
super.prepareForDisplay(window)
@@ -131,14 +128,7 @@ final class SettingsWindowController: HostingWindowController {
)
}
- private func clampedContentSize(_ fittingSize: NSSize, for window: NSWindow) -> NSSize? {
- guard fittingSize.width.isFinite,
- fittingSize.height.isFinite,
- fittingSize.width > 0,
- fittingSize.height > 0 else {
- return nil
- }
-
+ private func clampedContentSize(_ fittingSize: NSSize, for window: NSWindow) -> NSSize {
let maximumContentSize = maximumContentSize(for: window)
return NSSize(
width: clampedContentDimension(
diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swift
index aeec1c4..8e6ceb6 100644
--- a/CodexBar/Controllers/SidePanelSupport.swift
+++ b/CodexBar/Controllers/SidePanelSupport.swift
@@ -1,5 +1,6 @@
import AppKit
import QuartzCore
+import SwiftUI
/// 侧边详情面板不接收焦点, 只作为菜单面板的跟随子窗口
@MainActor
@@ -177,7 +178,6 @@ final class SidePanelDrawerPresenter {
visibilityGeneration += 1
isExitAnimationRunning = false
panel.setFrame(position.frame, display: true)
- panel.alphaValue = 1
currentSide = position.side
let generation = visibilityGeneration
@@ -248,6 +248,74 @@ final class SidePanelDrawerPresenter {
}
}
+/// 侧边面板的内容宿主: 懒建 panel + hostingController, 统一「替换 rootView →
+/// configureLayers → setContentSize」的更新序列
+/// ⚠️ 每次更新都整树替换 rootView 是刻意行为 (见 CLAUDE.md 热力图详情面板的说明), 不要改成常驻状态推送
+@MainActor
+final class SidePanelContentHost<Root: View> {
+ private(set) var panel: NSPanel?
+ private var hostingController: NSHostingController<Root>?
+ private let initialSize: CGSize
+ private let ignoresMouseEvents: Bool
+ private let sizingOptions: NSHostingSizingOptions
+ private let cornerRadius: CGFloat
+
+ init(
+ initialSize: CGSize,
+ ignoresMouseEvents: Bool,
+ sizingOptions: NSHostingSizingOptions,
+ cornerRadius: CGFloat
+ ) {
+ self.initialSize = initialSize
+ self.ignoresMouseEvents = ignoresMouseEvents
+ self.sizingOptions = sizingOptions
+ self.cornerRadius = cornerRadius
+ }
+
+ var contentView: NSView? {
+ hostingController?.view
+ }
+
+ func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {
+ guard let panel, panel.isVisible else {
+ return false
+ }
+
+ return panel.frame.contains(screenPoint)
+ }
+
+ func ensurePanel() -> NSPanel {
+ if let panel {
+ return panel
+ }
+
+ let panel = SidePanelSupport.makePanel(
+ initialSize: initialSize,
+ ignoresMouseEvents: ignoresMouseEvents
+ )
+ self.panel = panel
+ return panel
+ }
+
+ func updateContent(_ rootView: Root, size: CGSize) {
+ if let hostingController {
+ hostingController.rootView = rootView
+ } else {
+ let hostingController = NSHostingController(rootView: rootView)
+ hostingController.sizingOptions = sizingOptions
+ panel?.contentViewController = hostingController
+ self.hostingController = hostingController
+ }
+
+ SidePanelSupport.configureLayers(
+ hostingView: hostingController?.view,
+ contentView: panel?.contentView,
+ cornerRadius: cornerRadius
+ )
+ panel?.setContentSize(size)
+ }
+}
+
@MainActor
enum SidePanelSupport {
/// 侧边面板共用的几何与抽屉动画常量
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index cf09267..972e5d5 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -369,7 +369,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
if let toolName = task.toolName {
text += " • \(toolName)"
}
- text += " • 已等待 \(CodexActivityDurationFormat.text(for: now.timeIntervalSince(task.stateChangedAt)))"
+ text += " • \(CodexActivityDisplayFormat.waitingDurationFragment(since: task.stateChangedAt, now: now))"
return text
case let .running(task):
var text = "Codex 正在运行"
@@ -377,7 +377,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
text += " • \(projectName)"
}
if task.showsPreciseDuration, let startedAt = task.startedAt {
- text += " • 已运行 \(CodexActivityDurationFormat.text(for: now.timeIntervalSince(startedAt)))"
+ text += " • \(CodexActivityDisplayFormat.runningDurationFragment(since: startedAt, now: now))"
}
return text
case .completed(let completion, highlighted: true):
@@ -386,7 +386,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
text += " • \(projectName)"
}
if let duration = completion.duration {
- text += " • 耗时 \(CodexActivityDurationFormat.text(for: duration))"
+ text += " • \(CodexActivityDisplayFormat.elapsedDurationFragment(for: duration))"
}
return text
case .completed, .terminated, .idle:
@@ -426,11 +426,9 @@ private final class StatusItemController: NSObject, NSMenuDelegate {
}
init?(snapshot: CodexQuotaSnapshot?, selection: MenuBarQuotaSelection) {
- guard let targetWindowId = selection.windowId,
+ guard let targetKind = selection.windowKind,
let snapshot,
- let window = snapshot.codexLimit?.windows.first(where: {
- $0.id == targetWindowId
- }),
+ let window = snapshot.codexLimit?.window(ofKind: targetKind),
window.hasData else {
return nil
}
diff --git a/CodexBar/Models/CodexActivityModels.swift b/CodexBar/Models/CodexActivityModels.swift
index 855e94a..1a7080d 100644
--- a/CodexBar/Models/CodexActivityModels.swift
+++ b/CodexBar/Models/CodexActivityModels.swift
@@ -1,5 +1,11 @@
import Foundation
+/// 实时活动管道的共享保留窗口。
+/// tail reader 的 bootstrap 回放范围与任务中心的历史保留期是同一个不变量,必须相等。
+nonisolated enum CodexActivityRetention {
+ static let window: TimeInterval = 24 * 60 * 60
+}
+
/// 活跃任务最近收到的 Hook 事件,供活动卡片展示当前执行阶段。
nonisolated enum CodexActivityEvent: Equatable {
case promptSubmitted
@@ -178,6 +184,19 @@ nonisolated enum CodexActivityDisplayFormat {
relativeText(since: terminatedAt, now: now, action: "终止")
}
+ /// 活动卡片、任务中心、菜单栏 tooltip 和系统通知共用的时长片段。
+ static func waitingDurationFragment(since stateChangedAt: Date, now: Date) -> String {
+ "已等待 \(CodexActivityDurationFormat.text(for: now.timeIntervalSince(stateChangedAt)))"
+ }
+
+ static func runningDurationFragment(since startedAt: Date, now: Date) -> String {
+ "已运行 \(CodexActivityDurationFormat.text(for: now.timeIntervalSince(startedAt)))"
+ }
+
+ static func elapsedDurationFragment(for duration: TimeInterval) -> String {
+ "耗时 \(CodexActivityDurationFormat.text(for: duration))"
+ }
+
/// 活动卡片和任务中心共用同一份文案片段,各自决定连接符。
static func waitingDetailComponents(
for task: CodexActivityTaskSnapshot,
@@ -185,7 +204,7 @@ nonisolated enum CodexActivityDisplayFormat {
) -> [String] {
[
task.toolName ?? "等待下一步操作",
- "已等待 \(CodexActivityDurationFormat.text(for: now.timeIntervalSince(task.stateChangedAt)))"
+ waitingDurationFragment(since: task.stateChangedAt, now: now)
]
}
@@ -194,7 +213,7 @@ nonisolated enum CodexActivityDisplayFormat {
now: Date
) -> [String] {
let duration = if task.showsPreciseDuration, let startedAt = task.startedAt {
- "已运行 \(CodexActivityDurationFormat.text(for: now.timeIntervalSince(startedAt)))"
+ runningDurationFragment(since: startedAt, now: now)
} else {
"正在运行"
}
@@ -207,7 +226,7 @@ nonisolated enum CodexActivityDisplayFormat {
) -> [String] {
var components = [String]()
if let duration {
- components.append("耗时 \(CodexActivityDurationFormat.text(for: duration))")
+ components.append(elapsedDurationFragment(for: duration))
}
components.append(relativeText)
return components
diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swift
index d8bd4fb..79ae3e1 100644
--- a/CodexBar/Models/CodexQuotaModels.swift
+++ b/CodexBar/Models/CodexQuotaModels.swift
@@ -49,6 +49,10 @@ nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {
limitId
}
+ func window(ofKind kind: QuotaWindowKind) -> QuotaWindow? {
+ windows.first { $0.kind == kind }
+ }
+
var title: String {
if let limitName, !limitName.isEmpty {
return limitName.capitalizingFirstLetter()
@@ -68,13 +72,24 @@ private nonisolated extension String {
}
}
+/// primary/secondary 窗口的稳定标识; 这组词汇由模型层拥有
+/// 菜单栏额度指示偏好 (MenuBarQuotaSelection) 与窗口查找都经它互转
+nonisolated enum QuotaWindowKind: String, Equatable {
+ case primary
+ case secondary
+}
+
/// primary/secondary 窗口的 UI 友好表示, 统一计算剩余额度百分比
nonisolated struct QuotaWindow: Equatable, Identifiable {
- let id: String
+ let kind: QuotaWindowKind
let windowDurationMins: Int?
let usedPercent: Int?
let resetsAt: Date?
+ var id: String {
+ kind.rawValue
+ }
+
var label: String {
Self.windowLabel(for: windowDurationMins)
}
@@ -212,9 +227,9 @@ nonisolated extension CodexQuotaSnapshot {
nonisolated extension CodexQuotaLimitSnapshot {
init?(limitId: String, snapshot: RateLimitSnapshot) {
- let windows = [("primary", snapshot.primary), ("secondary", snapshot.secondary)]
- .compactMap { id, window in
- window.map { QuotaWindow(id: id, window: $0) }
+ let windows = [(QuotaWindowKind.primary, snapshot.primary), (.secondary, snapshot.secondary)]
+ .compactMap { kind, window in
+ window.map { QuotaWindow(kind: kind, window: $0) }
}
guard !windows.isEmpty else {
@@ -230,9 +245,9 @@ nonisolated extension CodexQuotaLimitSnapshot {
}
nonisolated extension QuotaWindow {
- init(id: String, window: RateLimitWindow) {
+ init(kind: QuotaWindowKind, window: RateLimitWindow) {
self.init(
- id: id,
+ kind: kind,
windowDurationMins: window.windowDurationMins,
usedPercent: window.usedPercent,
resetsAt: window.resetDate
diff --git a/CodexBar/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swift
index 55face9..c20068e 100644
--- a/CodexBar/Models/CodexUsageModels.swift
+++ b/CodexBar/Models/CodexUsageModels.swift
@@ -29,6 +29,20 @@ nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {
nonisolated struct CodexUsageSnapshot: Equatable {
let summary: UsageSummary
let dailyBuckets: [DailyUsageBucket]
+ /// 构造时聚合一次; 该快照在菜单面板每次渲染中被反复查询
+ 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
+ }
+ }
+
+ static func == (lhs: CodexUsageSnapshot, rhs: CodexUsageSnapshot) -> Bool {
+ lhs.summary == rhs.summary && lhs.dailyBuckets == rhs.dailyBuckets
+ }
func tokenCount(on date: Date) -> Int? {
let startDate = CodexDateFormat.dayString(from: date)
@@ -37,8 +51,7 @@ nonisolated struct CodexUsageSnapshot: Equatable {
/// 给热力图生成按周排列的最近日期网格, 每列从周日开始
func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [DailyUsageBucket?] {
- let tokenCountsByDate = tokensByDate
- return CodexWeekGrid.dates(
+ CodexWeekGrid.dates(
columnCount: columnCount,
endingDaysAgo: endingDaysAgo,
today: today
@@ -48,15 +61,9 @@ nonisolated struct CodexUsageSnapshot: Equatable {
let startDate = CodexDateFormat.dayString(from: $0)
return DailyUsageBucket(
startDate: startDate,
- tokens: tokenCountsByDate[startDate] ?? 0
+ tokens: tokensByDate[startDate] ?? 0
)
}
}
}
-
- private var tokensByDate: [String: Int] {
- dailyBuckets.reduce(into: [String: Int]()) { result, bucket in
- result[bucket.startDate, default: 0] += bucket.tokens
- }
- }
}
diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swift
index c16e1f4..1cee031 100644
--- a/CodexBar/Models/CodexWorkflowModels.swift
+++ b/CodexBar/Models/CodexWorkflowModels.swift
@@ -289,17 +289,17 @@ nonisolated struct WorkflowSnapshot: Equatable {
self.dailyMetrics = dailyMetrics
}
+ /// syncedRecords 由 WorkflowSyncService 保证不含本机设备的记录
init(
localAggregates: [WorkflowDailyAggregate],
- syncedRecords: [WorkflowSyncedDailyRecord],
- currentDeviceId: String?
+ syncedRecords: [WorkflowSyncedDailyRecord]
) {
var metricsByDate = [String: WorkflowDailyMetrics]()
for aggregate in localAggregates {
Self.merge(aggregate.metrics, into: &metricsByDate)
}
- for record in syncedRecords where record.deviceId != currentDeviceId {
+ for record in syncedRecords {
Self.merge(record.daily.metrics, into: &metricsByDate)
}
@@ -466,7 +466,7 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
turnIds = nil
}
- // 只有正数压缩计数或非空 ID 集合是有效去重结果, 否则使用起止事件计数兜底
+ /// 只有正数压缩计数或非空 ID 集合是有效去重结果, 否则使用起止事件计数兜底
private var resolvedSessionCount: Int {
WorkflowCountResolution.resolvedCount(
compactedCount: sessionCount,
@@ -519,10 +519,6 @@ nonisolated struct WorkflowDailyAggregate: Codable, Equatable, Identifiable {
.sorted { $0.date < $1.date }
}
- static func decodeJSONLines(from data: Data) -> [WorkflowDailyAggregate] {
- JSONLines.decode(from: data)
- }
-
static func encodeJSONLines(_ aggregates: [WorkflowDailyAggregate]) throws -> Data {
try aggregates.reduce(into: Data()) { result, aggregate in
try result.append(aggregate.jsonLineData())
diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
index 3e60f9f..3a8831f 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
@@ -176,8 +176,10 @@ nonisolated enum CodexCLIResolver {
canonicalPath(lhs) == canonicalPath(rhs)
}
- private static func canonicalPath(_ path: String) -> String {
- URL(fileURLWithPath: path)
+ /// 「两个路径是否指向同一文件」的统一口径, Hook 配置匹配也复用它
+ static func canonicalPath(_ path: String, expandingTilde: Bool = false) -> String {
+ let expandedPath = expandingTilde ? (path as NSString).expandingTildeInPath : path
+ return URL(fileURLWithPath: expandedPath)
.resolvingSymlinksInPath()
.standardizedFileURL
.path
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index bf3f7f6..41aa7eb 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -342,26 +342,11 @@ final class CodexCLIVersionViewModel: ObservableObject {
Date().timeIntervalSince(snapshot.refreshedAt) > Self.refreshThrottle else {
return
}
- isRefreshing = true
- refreshCoordinator.start { [weak self] generation in
- guard let self else {
- return
- }
-
- defer {
- self.refreshCoordinator.finish(generation) {
- self.isRefreshing = false
- }
- }
-
- let snapshot = await service.fetchSnapshot()
-
- guard refreshCoordinator.canCommit(generation) else {
- return
- }
-
- self.snapshot = snapshot
- }
+ refreshCoordinator.run(
+ setRefreshing: { [weak self] in self?.isRefreshing = $0 },
+ operation: { [service = self.service] in await service.fetchSnapshot() },
+ commit: { [weak self] snapshot in self?.snapshot = snapshot }
+ )
}
}
diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swift
index 9332227..06da35b 100644
--- a/CodexBar/Services/CodexStatus/AppServerSession.swift
+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift
@@ -211,17 +211,16 @@ final nonisolated class AppServerSession {
token: UUID,
decoder: JSONDecoder
) throws -> Response {
- if let errorEnvelope = try? decoder.decode(RPCErrorEnvelope.self, from: line.data),
- let error = errorEnvelope.error {
- try failRequest(token, message: line.text, error: .serverError(error.message))
- }
-
- guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: line.data),
- let result = envelope.result else {
- try failRequest(token, message: line.text, error: .invalidServerResponse)
+ 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
+ }
}
- return result
+ try failRequest(token, message: line.text, error: .invalidServerResponse)
}
private func failRequest(_ token: UUID, message: String, error: CodexStatusError) throws -> Never {
@@ -235,12 +234,10 @@ private nonisolated struct RPCIDEnvelope: Decodable {
let id: Int?
}
+/// error 与 result 合并在同一个信封里一次解码; 大响应行只完整解析一次
private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {
- let result: Response?
-}
-
-private nonisolated struct RPCErrorEnvelope: Decodable {
let error: RPCError?
+ let result: Response?
}
private nonisolated struct RPCError: Decodable {
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index 5d4de75..c64d070 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -102,7 +102,11 @@ actor CodexStatusService {
}
func currentConnectionInfo() async -> CodexCLIConnectionInfo? {
- currentConnectionInfoSnapshot()
+ guard let connection, connection.session.process.isRunning else {
+ return nil
+ }
+
+ return connection.commandInfo
}
func readCodexConfig() async throws -> CodexConfigReadResponse {
@@ -209,14 +213,6 @@ actor CodexStatusService {
connection = nil
}
- private func currentConnectionInfoSnapshot() -> CodexCLIConnectionInfo? {
- guard let connection, connection.session.process.isRunning else {
- return nil
- }
-
- return connection.commandInfo
- }
-
/// 额度与用量独立读取
/// 认证失败全程只刷新一次 token
/// 传输故障交给外层重建连接
diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
index fd88a30..8352b16 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
@@ -77,42 +77,32 @@ final class CodexStatusViewModel: ObservableObject {
return
}
- isRefreshing = true
-
- refreshCoordinator.start { [weak self] generation in
- guard let self else {
- return
- }
-
- defer {
- self.refreshCoordinator.finish(generation) {
- self.isRefreshing = false
+ refreshCoordinator.run(
+ setRefreshing: { [weak self] in self?.isRefreshing = $0 },
+ operation: { [service = self.service] in
+ await (outcome: service.fetchOutcome(), connectionInfo: service.currentConnectionInfo())
+ },
+ commit: { [weak self] result in
+ guard let self else {
+ return
}
- }
-
- let outcome = await service.fetchOutcome()
- let connectionInfo = await service.currentConnectionInfo()
- // 过期刷新结果直接丢弃, 避免慢请求覆盖后启动的新状态
- guard refreshCoordinator.canCommit(generation) else {
- return
- }
+ switch result.outcome {
+ case let .data(snapshot):
+ self.snapshot = snapshot
+ loadState = .loaded
+ case .notLoggedIn:
+ snapshot = nil
+ loadState = .notLoggedIn
+ case .initializationFailed:
+ snapshot = nil
+ loadState = .initializationFailed
+ }
- switch outcome {
- case let .data(snapshot):
- self.snapshot = snapshot
- loadState = .loaded
- case .notLoggedIn:
- snapshot = nil
- loadState = .notLoggedIn
- case .initializationFailed:
- snapshot = nil
- loadState = .initializationFailed
+ codexConnectionInfo = result.connectionInfo
+ autoRefreshCountdownStartedAt = Date()
}
-
- codexConnectionInfo = connectionInfo
- autoRefreshCountdownStartedAt = Date()
- }
+ )
}
func refreshCodexConnectionInfo() {
diff --git a/CodexBar/Services/CodexStatus/RequestLog.swift b/CodexBar/Services/CodexStatus/RequestLog.swift
index b22fe0a..172c33b 100644
--- a/CodexBar/Services/CodexStatus/RequestLog.swift
+++ b/CodexBar/Services/CodexStatus/RequestLog.swift
@@ -66,6 +66,7 @@ final nonisolated class RequestLogStorage: Sendable {
private init() {}
+ /// payload 由 AppServerSession 用相同的稳定序列化选项生成, 无需再做一轮归一化
func beginRequest(method: String, payload: String) -> UUID {
let id = UUID()
append(
@@ -75,7 +76,7 @@ final nonisolated class RequestLogStorage: Sendable {
respondedAt: nil,
kind: .pending,
method: method,
- request: Self.normalized(payload),
+ request: payload,
detail: nil
)
)
@@ -106,7 +107,7 @@ final nonisolated class RequestLogStorage: Sendable {
respondedAt: nil,
kind: .emptyResponse,
method: method,
- request: Self.normalized(payload),
+ request: payload,
detail: ""
)
)
diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swift
index b9d6909..d6ca366 100644
--- a/CodexBar/Services/Notifications/CodexNotificationService.swift
+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift
@@ -567,7 +567,7 @@ nonisolated struct CodexNotificationContent: Equatable {
let projectText = project.map { "「\($0)」" } ?? "Codex"
return CodexNotificationContent(
title: "Codex 任务完成",
- body: "\(projectText) 任务完成, 耗时 \(CodexActivityDurationFormat.text(for: duration))"
+ body: "\(projectText) 任务完成, \(CodexActivityDisplayFormat.elapsedDurationFragment(for: duration))"
)
}
diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swift
index c1a48d5..9a5480d 100644
--- a/CodexBar/Services/Settings/CodexHookSettings.swift
+++ b/CodexBar/Services/Settings/CodexHookSettings.swift
@@ -759,9 +759,6 @@ private extension CodexHookSettings {
}
static func normalizedPath(_ path: String) -> String {
- URL(fileURLWithPath: (path as NSString).expandingTildeInPath)
- .standardizedFileURL
- .resolvingSymlinksInPath()
- .path
+ CodexCLIResolver.canonicalPath(path, expandingTilde: true)
}
}
diff --git a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift b/CodexBar/Services/Settings/MenuBarQuotaSettings.swift
index f6508c1..ec30851 100644
--- a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift
+++ b/CodexBar/Services/Settings/MenuBarQuotaSettings.swift
@@ -113,7 +113,7 @@ final class MenuBarQuotaSettings: ObservableObject {
private static let lastWindowSelectionKey = "MenuBarQuota.lastWindowSelection"
}
-nonisolated enum MenuBarQuotaSelection: String, CaseIterable, Identifiable {
+nonisolated enum MenuBarQuotaSelection: String, Identifiable {
case off
case primary
case secondary
@@ -122,36 +122,20 @@ nonisolated enum MenuBarQuotaSelection: String, CaseIterable, Identifiable {
rawValue
}
- init?(windowId: String) {
- switch windowId {
- case "primary":
+ init(windowKind: QuotaWindowKind) {
+ switch windowKind {
+ case .primary:
self = .primary
- case "secondary":
+ case .secondary:
self = .secondary
- default:
- return nil
}
}
var fallbackTitle: String {
- switch self {
- case .off:
- "off"
- case .primary:
- "primary"
- case .secondary:
- "secondary"
- }
+ rawValue
}
- var windowId: String? {
- switch self {
- case .off:
- nil
- case .primary:
- "primary"
- case .secondary:
- "secondary"
- }
+ var windowKind: QuotaWindowKind? {
+ QuotaWindowKind(rawValue: rawValue)
}
}
diff --git a/CodexBar/Services/Support/RefreshTaskCoordinator.swift b/CodexBar/Services/Support/RefreshTaskCoordinator.swift
index 9febbd1..255d2fa 100644
--- a/CodexBar/Services/Support/RefreshTaskCoordinator.swift
+++ b/CodexBar/Services/Support/RefreshTaskCoordinator.swift
@@ -24,6 +24,31 @@ final nonisolated class RefreshTaskCoordinator: Sendable {
return generation
}
+ /// ViewModel 共用的刷新样板: 置位刷新标记 → 取数 → 仅当代际未过期时提交
+ /// 过期刷新结果直接丢弃, 避免慢请求覆盖后启动的新状态
+ @MainActor
+ func run<Value>(
+ setRefreshing: @escaping @MainActor @Sendable (Bool) -> Void,
+ operation: @escaping @MainActor @Sendable () async -> Value,
+ commit: @escaping @MainActor @Sendable (Value) -> Void
+ ) {
+ setRefreshing(true)
+ start { [self] generation in
+ defer {
+ finish(generation) {
+ setRefreshing(false)
+ }
+ }
+
+ let value = await operation()
+ guard canCommit(generation) else {
+ return
+ }
+
+ commit(value)
+ }
+ }
+
private func begin() -> Int {
let (task, generation) = state.withLock {
let task = $0.task
diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
index c81a227..baa3f31 100644
--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift
+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
@@ -696,7 +696,7 @@ final class CodexActivityMonitor: ObservableObject {
private static let completionHighlightDuration: TimeInterval = 30
private static let recentHistoryRetention: TimeInterval = 10 * 60
private static let completedTaskRetention: TimeInterval = 24 * 60 * 60
- private static let activityRetention: TimeInterval = 24 * 60 * 60
+ private static let activityRetention = CodexActivityRetention.window
private static let supersededTerminalGracePeriod: TimeInterval = 5
private static let sessionLifecyclePollInterval: TimeInterval = 1
}
diff --git a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift
index 56d028f..ecc7131 100644
--- a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift
+++ b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift
@@ -189,7 +189,7 @@ actor CodexSessionLifecycleReader {
guard (try? handle.seek(toOffset: cursor.offset)) != nil,
let data = try? handle.readToEnd(),
!data.isEmpty,
- let lastNewlineIndex = data.lastIndex(of: Self.newlineByte) else {
+ let lastNewlineIndex = data.lastIndex(of: JSONLines.newlineByte) else {
return
}
@@ -197,18 +197,17 @@ actor CodexSessionLifecycleReader {
cursor.offset += UInt64(consumedCount)
cursor.fileIdentifier = identifier
- var firstCompleteIndex = data.startIndex
+ var completeData = Data(data[data.startIndex ... lastNewlineIndex])
if cursor.discardsLeadingPartialLine {
- firstCompleteIndex = data.index(after: data.firstIndex(of: Self.newlineByte) ?? lastNewlineIndex)
+ completeData = JSONLines.droppingLeadingPartialLine(completeData)
cursor.discardsLeadingPartialLine = false
}
- guard firstCompleteIndex <= lastNewlineIndex else {
+ guard !completeData.isEmpty else {
return
}
- let completeData = Data(data[firstCompleteIndex ... lastNewlineIndex])
- for envelope in JSONLines.decode(CodexSessionLifecycleEnvelope.self, from: completeData) {
+ for envelope in JSONLines.decode(CodexRolloutLineEnvelope.self, from: completeData) {
guard let event = envelope.lifecycleEvent else {
continue
}
@@ -220,7 +219,6 @@ actor CodexSessionLifecycleReader {
private static let bootstrapByteLimit: UInt64 = 512 * 1024
private static let fileResolutionRetryInterval: TimeInterval = 10
- private static let newlineByte: UInt8 = 0x0A
}
private nonisolated struct SessionFileCursor {
@@ -231,11 +229,33 @@ private nonisolated struct SessionFileCursor {
var lifecycleByTurnId: [String: SessionTurnLifecycle]
}
-private nonisolated struct CodexSessionLifecycleEnvelope: Decodable {
+/// Codex rollout JSONL 单行的共享解码模型
+/// Hook 子进程 (WorkflowTurnContextReader) 与 lifecycle reader 共用同一份 schema
+nonisolated struct CodexRolloutLineEnvelope: Decodable {
let timestamp: String?
let type: String
- let payload: CodexSessionLifecyclePayload?
+ let payload: CodexRolloutLinePayload?
+}
+
+nonisolated struct CodexRolloutLinePayload: Decodable {
+ let type: String?
+ let turnId: String?
+ let startedAt: Double?
+ let completedAt: Double?
+ let durationMilliseconds: Double?
+ let approvalReviewer: CodexApprovalReviewer?
+
+ private enum CodingKeys: String, CodingKey {
+ case type
+ case turnId = "turn_id"
+ case startedAt = "started_at"
+ case completedAt = "completed_at"
+ case durationMilliseconds = "duration_ms"
+ case approvalReviewer = "approvals_reviewer"
+ }
+}
+private nonisolated extension CodexRolloutLineEnvelope {
var lifecycleEvent: SessionLifecycleEvent? {
guard let payload,
let turnId = payload.turnId,
@@ -287,24 +307,6 @@ private nonisolated struct CodexSessionLifecycleEnvelope: Decodable {
}
}
-private nonisolated struct CodexSessionLifecyclePayload: Decodable {
- let type: String?
- let turnId: String?
- let startedAt: Double?
- let completedAt: Double?
- let durationMilliseconds: Double?
- let approvalReviewer: CodexApprovalReviewer?
-
- private enum CodingKeys: String, CodingKey {
- case type
- case turnId = "turn_id"
- case startedAt = "started_at"
- case completedAt = "completed_at"
- case durationMilliseconds = "duration_ms"
- case approvalReviewer = "approvals_reviewer"
- }
-}
-
private nonisolated struct SessionLifecycleEvent {
let turnId: String
let change: SessionLifecycleChange
diff --git a/CodexBar/Services/Workflow/HookEventTailReader.swift b/CodexBar/Services/Workflow/HookEventTailReader.swift
index 163c788..2b575e2 100644
--- a/CodexBar/Services/Workflow/HookEventTailReader.swift
+++ b/CodexBar/Services/Workflow/HookEventTailReader.swift
@@ -256,7 +256,7 @@ actor HookEventTailReader {
readOffset += UInt64(chunk.count)
pending.append(chunk)
- guard let lastNewlineIndex = pending.lastIndex(of: Self.newlineByte) else {
+ guard let lastNewlineIndex = pending.lastIndex(of: JSONLines.newlineByte) else {
await Task.yield()
continue
}
@@ -314,13 +314,7 @@ actor HookEventTailReader {
}
remainingBytes -= UInt64(data.count)
- var completeData = data
- if readOffset > 0, let firstNewlineIndex = data.firstIndex(of: Self.newlineByte) {
- let firstCompleteIndex = data.index(after: firstNewlineIndex)
- completeData = firstCompleteIndex < data.endIndex
- ? Data(data[firstCompleteIndex...])
- : Data()
- }
+ let completeData = readOffset > 0 ? JSONLines.droppingLeadingPartialLine(data) : data
for event in JSONLines.decode(WorkflowHookEvent.self, from: completeData)
where event.hookEvent == .userPromptSubmit && event.timestamp < cutoff {
@@ -386,11 +380,10 @@ actor HookEventTailReader {
}
private static let pollInterval: TimeInterval = 2
- private static let activityRetention: TimeInterval = 24 * 60 * 60
+ private static let activityRetention = CodexActivityRetention.window
private static let readChunkByteCount = 512 * 1024
private static let promptSearchByteLimit: UInt64 = 8 * 1024 * 1024
private static let bootstrapAttemptLimit = 3
- private static let newlineByte: UInt8 = 0x0A
}
private nonisolated struct HookFileBoundary {
diff --git a/CodexBar/Services/Workflow/JSONLines.swift b/CodexBar/Services/Workflow/JSONLines.swift
index 0ba9de6..e09145e 100644
--- a/CodexBar/Services/Workflow/JSONLines.swift
+++ b/CodexBar/Services/Workflow/JSONLines.swift
@@ -2,6 +2,8 @@ import Foundation
/// 简单 JSONL 工具, 读取时跳过坏行以保护历史统计可用性
nonisolated enum JSONLines {
+ static let newlineByte: UInt8 = 0x0A
+
/// 落盘 JSON 统一的稳定输出配置, 保证文件可 diff 且格式一致
/// 配置后不再修改, encode 可重入, 可跨并发域缓存共享
static let stableEncoder: JSONEncoder = {
@@ -10,6 +12,17 @@ nonisolated enum JSONLines {
return encoder
}()
+ /// 从文件中部 seek 读取时首行必然残缺: 丢弃首个换行(含)之前的内容
+ /// 找不到换行时原样返回, 交给按行解码当坏行跳过
+ static func droppingLeadingPartialLine(_ data: Data) -> Data {
+ guard let firstNewlineIndex = data.firstIndex(of: newlineByte) else {
+ return data
+ }
+
+ let firstCompleteIndex = data.index(after: firstNewlineIndex)
+ return firstCompleteIndex < data.endIndex ? Data(data[firstCompleteIndex...]) : Data()
+ }
+
/// 按行解码 JSONL: 切分换行, trim, 跳过空行与解码失败的行
static func decode<T: Decodable>(_ type: T.Type = T.self, from data: Data) -> [T] {
decodeWithFailures(type, from: data).values
diff --git a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
index ea40510..5d2002b 100644
--- a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
+++ b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
@@ -144,17 +144,9 @@ private nonisolated enum WorkflowTurnContextReader {
return nil
}
- let completeData: Data
- if offset > 0, let firstNewlineIndex = data.firstIndex(of: newlineByte) {
- let firstCompleteIndex = data.index(after: firstNewlineIndex)
- completeData = firstCompleteIndex < data.endIndex
- ? Data(data[firstCompleteIndex...])
- : Data()
- } else {
- completeData = data
- }
+ let completeData = offset > 0 ? JSONLines.droppingLeadingPartialLine(data) : data
- for envelope in JSONLines.decode(WorkflowTurnContextEnvelope.self, from: completeData)
+ for envelope in JSONLines.decode(CodexRolloutLineEnvelope.self, from: completeData)
.reversed()
where envelope.type == "turn_context"
&& envelope.payload?.turnId == turnId {
@@ -164,22 +156,6 @@ private nonisolated enum WorkflowTurnContextReader {
}
private static let searchByteLimit: UInt64 = 512 * 1024
- private static let newlineByte: UInt8 = 0x0A
-}
-
-private nonisolated struct WorkflowTurnContextEnvelope: Decodable {
- let type: String
- let payload: WorkflowTurnContextPayload?
-}
-
-private nonisolated struct WorkflowTurnContextPayload: Decodable {
- let turnId: String?
- let approvalReviewer: CodexApprovalReviewer?
-
- private enum CodingKeys: String, CodingKey {
- case turnId = "turn_id"
- case approvalReviewer = "approvals_reviewer"
- }
}
/// Codex Hook payload 字段存在版本差异, 这里集中做宽松类型归一化
diff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swift
index addc8eb..de626a7 100644
--- a/CodexBar/Services/Workflow/WorkflowService.swift
+++ b/CodexBar/Services/Workflow/WorkflowService.swift
@@ -7,6 +7,8 @@ actor WorkflowService {
private let eventsDirectoryURL: URL
private let dailyLogURL: URL
private let syncService: WorkflowSyncService
+ /// 上次归一化时 daily.jsonl 的 stat 与当天日期键
+ private var lastNormalizedDailyLog: WorkflowDailyLogStamp?
private static let eventReadChunkSize = 64 * 1024
init(
@@ -47,8 +49,7 @@ actor WorkflowService {
return WorkflowSnapshot(
localAggregates: aggregates,
- syncedRecords: syncSnapshot.records,
- currentDeviceId: syncSnapshot.currentDeviceId
+ syncedRecords: syncSnapshot.records
)
}
@@ -57,7 +58,7 @@ actor WorkflowService {
return nil
}
- let aggregates = WorkflowDailyAggregate.decodeJSONLines(from: data)
+ let aggregates: [WorkflowDailyAggregate] = JSONLines.decode(from: data)
guard !aggregates.isEmpty else {
return nil
}
@@ -70,8 +71,11 @@ actor WorkflowService {
do {
let tasks = try prepareMaintenanceTasks()
- perform(tasks)
- try normalizeDailyAggregatesIfNeeded()
+ let didWriteDailyLog = perform(tasks)
+ // 每次落盘前都已整体归一化, 写入过就不必再做一轮全量解码比对
+ if !didWriteDailyLog {
+ try normalizeDailyAggregatesIfNeeded()
+ }
try pruneExpiredEventFiles()
} catch {
return []
@@ -84,15 +88,24 @@ actor WorkflowService {
return changedSyncPayloadDates(before: beforePayloads, after: syncPayloadByDate())
}
- private func perform(_ tasks: [WorkflowMaintenanceTask]) {
+ /// 返回是否写入过 daily.jsonl; 批次内共享同一份内存聚合, 避免每个任务重新读盘
+ private func perform(_ tasks: [WorkflowMaintenanceTask]) -> Bool {
+ guard !tasks.isEmpty else {
+ return false
+ }
+
+ var aggregates = loadDailyAggregates() ?? []
+ var didWrite = false
for task in tasks {
do {
let result = try buildDailyAggregate(for: task)
- try commit(result)
+ didWrite = try commit(result, aggregates: &aggregates) || didWrite
} catch {
markDirty(task.dateKey)
}
}
+
+ return didWrite
}
private func prepareMaintenanceTasks() throws -> [WorkflowMaintenanceTask] {
@@ -240,7 +253,7 @@ actor WorkflowService {
}
private func eventLogURL(for dateKey: String) -> URL {
- eventsDirectoryURL.appendingPathComponent("\(dateKey).jsonl", isDirectory: false)
+ WorkflowStorage.eventLogURL(for: dateKey, in: eventsDirectoryURL)
}
private func eventLogSize(for dateKey: String) -> UInt64 {
@@ -320,7 +333,7 @@ actor WorkflowService {
remainingBytes -= UInt64(chunk.count)
buffer.append(chunk)
- while let newlineIndex = buffer.firstIndex(of: 0x0A) {
+ while let newlineIndex = buffer.firstIndex(of: JSONLines.newlineByte) {
let lineData = buffer[..<newlineIndex]
corrupt += decode(lineData, using: decoder, record: record)
buffer.removeSubrange(...newlineIndex)
@@ -357,15 +370,20 @@ actor WorkflowService {
return 0
}
- private func commit(_ result: WorkflowMaintenanceResult) throws {
+ /// 返回是否写入了 daily.jsonl
+ private func commit(
+ _ result: WorkflowMaintenanceResult,
+ aggregates: inout [WorkflowDailyAggregate]
+ ) throws -> Bool {
guard try eventLogHasNotShrunk(for: result) else {
- return
+ return false
}
// daily.jsonl 和 maintenance.json 分开写
// 每次提交前后都检查事件文件是否被并发追加
- try writeDailyAggregate(result.aggregate)
+ try writeDailyAggregate(result.aggregate, into: &aggregates)
try commitMaintenanceState(result)
+ return true
}
private func eventLogHasNotShrunk(for result: WorkflowMaintenanceResult) throws -> Bool {
@@ -390,13 +408,15 @@ actor WorkflowService {
return currentSize
}
- private func writeDailyAggregate(_ aggregate: WorkflowDailyAggregate) throws {
+ private func writeDailyAggregate(
+ _ aggregate: WorkflowDailyAggregate,
+ into aggregates: inout [WorkflowDailyAggregate]
+ ) throws {
try FileManager.default.createDirectory(
at: dailyLogURL.deletingLastPathComponent(),
withIntermediateDirectories: true
)
- var aggregates = loadDailyAggregates() ?? []
upsert(aggregate, into: &aggregates)
aggregates = WorkflowDailyAggregate.normalized(aggregates: aggregates)
let data = try WorkflowDailyAggregate.encodeJSONLines(aggregates)
@@ -404,6 +424,16 @@ actor WorkflowService {
}
private func normalizeDailyAggregatesIfNeeded() throws {
+ guard let stat = WorkflowStorage.fileStat(at: dailyLogURL), stat.size > 0 else {
+ return
+ }
+
+ // 稳态下文件与日期都没变, 跳过全量解码与重编码比对
+ let dayKey = WorkflowStorage.dateKey(for: Date())
+ if lastNormalizedDailyLog == WorkflowDailyLogStamp(size: stat.size, identifier: stat.identifier, dayKey: dayKey) {
+ return
+ }
+
guard let data = try? Data(contentsOf: dailyLogURL), !data.isEmpty else {
return
}
@@ -415,15 +445,21 @@ actor WorkflowService {
let normalizedAggregates = WorkflowDailyAggregate.normalized(aggregates: decodeResult.values)
let normalizedData = try WorkflowDailyAggregate.encodeJSONLines(normalizedAggregates)
- guard normalizedData != data else {
- return
+ if normalizedData != data {
+ try FileManager.default.createDirectory(
+ at: dailyLogURL.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ try normalizedData.write(to: dailyLogURL, options: .atomic)
}
- try FileManager.default.createDirectory(
- at: dailyLogURL.deletingLastPathComponent(),
- withIntermediateDirectories: true
- )
- try normalizedData.write(to: dailyLogURL, options: .atomic)
+ if let latestStat = WorkflowStorage.fileStat(at: dailyLogURL) {
+ lastNormalizedDailyLog = WorkflowDailyLogStamp(
+ size: latestStat.size,
+ identifier: latestStat.identifier,
+ dayKey: dayKey
+ )
+ }
}
private func syncPayloadByDate() -> [String: String] {
@@ -531,9 +567,8 @@ nonisolated enum WorkflowStorage {
.appendingPathComponent("events", isDirectory: true)
}
- static func eventLogURL(for dateKey: String) -> URL {
- eventsDirectoryURL()
- .appendingPathComponent("\(dateKey).jsonl", isDirectory: false)
+ static func eventLogURL(for dateKey: String, in directoryURL: URL = eventsDirectoryURL()) -> URL {
+ directoryURL.appendingPathComponent("\(dateKey).jsonl", isDirectory: false)
}
static func dailyURL() -> URL {
@@ -806,6 +841,13 @@ nonisolated struct WorkflowMaintenanceState: Codable, Equatable {
}
}
+/// daily.jsonl 某一时刻的 stat 快照与当天日期键, 用于跳过稳态下的重复归一化
+private nonisolated struct WorkflowDailyLogStamp: Equatable {
+ let size: UInt64
+ let identifier: UInt64?
+ let dayKey: String
+}
+
// 单次维护任务: 从 startOffset 读到 size, 可基于已有聚合继续追加
private nonisolated struct WorkflowMaintenanceTask {
let dateKey: String
@@ -856,28 +898,14 @@ final class WorkflowViewModel: ObservableObject {
return
}
- isRefreshing = true
-
- refreshCoordinator.start { [weak self] generation in
- guard let self else {
- return
+ refreshCoordinator.run(
+ setRefreshing: { [weak self] in self?.isRefreshing = $0 },
+ operation: { [service = self.service] in await service.loadSnapshot() },
+ commit: { [weak self] snapshot in
+ self?.snapshot = snapshot
+ self?.lastRefreshedAt = Date()
}
-
- defer {
- self.refreshCoordinator.finish(generation) {
- self.isRefreshing = false
- }
- }
-
- let snapshot = await service.loadSnapshot()
-
- guard refreshCoordinator.canCommit(generation) else {
- return
- }
-
- self.snapshot = snapshot
- lastRefreshedAt = Date()
- }
+ )
}
/// 由 WorkflowSyncScheduler 串行调度, 无需自行判断并发, 只执行一次明确的维护刷新
diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swift
index 54eb47b..83d3bc4 100644
--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift
+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift
@@ -119,7 +119,6 @@ actor WorkflowSyncService {
private func snapshot(from state: WorkflowSyncState) -> WorkflowSyncSnapshot {
WorkflowSyncSnapshot(
- currentDeviceId: state.deviceId,
records: state.deviceId == nil
? []
: Self.filteredRetained(records: loadCachedRecords(), excluding: state.deviceId)
@@ -184,10 +183,14 @@ private extension WorkflowSyncService {
CKRecord.ID(recordName: Self.accountSaltRecordName, zoneID: syncZoneID)
}
- var stateURL: URL {
+ nonisolated static func stateURL(in directoryURL: URL) -> URL {
directoryURL.appendingPathComponent("state.json", isDirectory: false)
}
+ var stateURL: URL {
+ Self.stateURL(in: directoryURL)
+ }
+
var cacheURL: URL {
directoryURL.appendingPathComponent("cache.jsonl", isDirectory: false)
}
@@ -674,9 +677,7 @@ private extension WorkflowSyncService {
extension WorkflowSyncService {
/// 设置页读取最近上传时间, 与内部 loadState 使用同一 schema 校验口径
nonisolated static func loadLastUploadAt() -> Date? {
- let stateURL = WorkflowStorage.syncDirectoryURL()
- .appendingPathComponent("state.json", isDirectory: false)
- return loadState(at: stateURL).lastUploadAt
+ loadState(at: stateURL(in: WorkflowStorage.syncDirectoryURL())).lastUploadAt
}
}
@@ -909,11 +910,11 @@ private extension WorkflowSyncService {
}
}
+/// records 永不包含本机设备的记录: 写缓存与读取时都经 filteredRetained(excluding:) 过滤
nonisolated struct WorkflowSyncSnapshot: Equatable {
- let currentDeviceId: String?
let records: [WorkflowSyncedDailyRecord]
- static let disabled = WorkflowSyncSnapshot(currentDeviceId: nil, records: [])
+ static let disabled = WorkflowSyncSnapshot(records: [])
}
private nonisolated struct WorkflowSyncState: Codable, Equatable {
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index abb2aa4..9ed56b0 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -197,7 +197,7 @@ private struct LogRow: View {
systemImage: "doc.on.doc",
help: "复制完整\(caption)"
) {
- LogClipboard.copy(text)
+ PasteboardWriter.copy(text)
}
}
}
@@ -255,14 +255,6 @@ private struct LogHeaderActionButton: View {
}
}
-/// 统一收口剪贴板写入
-private enum LogClipboard {
- static func copy(_ text: String) {
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(text, forType: .string)
- }
-}
-
/// 完整请求/响应预览弹窗
private struct FullLogTextView: View {
let item: FullLogTextItem
@@ -299,7 +291,7 @@ private struct FullLogTextView: View {
Spacer()
Button {
- LogClipboard.copy(item.text)
+ PasteboardWriter.copy(item.text)
} label: {
Label("复制", systemImage: "doc.on.doc")
}
diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swift
index 132cb86..7280810 100644
--- a/CodexBar/Views/Menu/CodexActivityCard.swift
+++ b/CodexBar/Views/Menu/CodexActivityCard.swift
@@ -1,11 +1,11 @@
import SwiftUI
/// Hook 开启时常驻的固定高度活动摘要,使用菜单面板共享的逐秒时间。
+/// 在卡片内部观察 activityMonitor 与逐秒时间, 让 1Hz 失效范围只覆盖本卡片而不是整个菜单树。
struct CodexActivityCard: View {
@ObservedObject var activityMonitor: CodexActivityMonitor
- let timelineDate: Date
+ @ObservedObject var presentationState: CodexActivityCenterPresentationState
let showsUnavailableState: Bool
- let isTaskCenterPresented: Bool
let onTaskCenterTap: (ScreenFrameProvider) -> Void
@State private var frameProvider = ScreenFrameProvider()
@State private var isHovered = false
@@ -14,6 +14,14 @@ struct CodexActivityCard: View {
showsUnavailableState ? .empty : activityMonitor.snapshot
}
+ private var timelineDate: Date {
+ presentationState.timelineDate
+ }
+
+ private var isTaskCenterPresented: Bool {
+ presentationState.isPresented
+ }
+
var body: some View {
Group {
if snapshot.hasTaskCenterContent {
diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swift
index aa5482a..42bd076 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift
@@ -14,10 +14,11 @@ struct CodexStatusMenuView: View {
@ObservedObject var viewModel: CodexStatusViewModel
@ObservedObject var workflowViewModel: WorkflowViewModel
@ObservedObject var codexHookSettings: CodexHookSettings
- @ObservedObject var activityMonitor: CodexActivityMonitor
+ // 活动状态与逐秒时间只被活动卡片消费, 由卡片自行观察, 避免 1Hz tick 让整个菜单树每秒重算
+ let activityMonitor: CodexActivityMonitor
@ObservedObject var syncSettings: WorkflowSyncSettings
@ObservedObject var menuSurfaceVisibility: MenuSurfaceVisibilityState
- @ObservedObject var activityCenterPresentationState: CodexActivityCenterPresentationState
+ let activityCenterPresentationState: CodexActivityCenterPresentationState
let onUsageHeatmapHoverChange: (UsageHeatmapHoverContext?) -> Void
let onResetCreditsTap: (ResetCreditsPanelContext) -> Void
let onActivityCenterTap: (CodexActivityCenterPanelContext) -> Void
@@ -74,12 +75,10 @@ private extension CodexStatusMenuView {
@ViewBuilder
var activityCard: some View {
if codexHookSettings.isEnabled {
- let hasQuotaSnapshot = viewModel.snapshot != nil
CodexActivityCard(
activityMonitor: activityMonitor,
- timelineDate: activityCenterPresentationState.timelineDate,
- showsUnavailableState: !hasQuotaSnapshot,
- isTaskCenterPresented: activityCenterPresentationState.isPresented,
+ presentationState: activityCenterPresentationState,
+ showsUnavailableState: viewModel.snapshot == nil,
onTaskCenterTap: { anchorProvider in
onActivityCenterTap(
CodexActivityCenterPanelContext(
diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swift
index 5416bef..4cb463c 100644
--- a/CodexBar/Views/Menu/UsageHeatmap.swift
+++ b/CodexBar/Views/Menu/UsageHeatmap.swift
@@ -100,13 +100,13 @@ struct UsageSummaryView: View {
}
private func tokenMetric(label: String, value: Int) -> some View {
- metric(label: label, alignment: .center) {
+ metric(label: label) {
TokenCountText(tokens: value)
}
}
private func textMetric(label: String, value: String) -> some View {
- metric(label: label, alignment: .center) {
+ metric(label: label) {
Text(value)
.font(.caption.monospacedDigit().weight(.semibold))
.lineLimit(1)
@@ -116,17 +116,16 @@ struct UsageSummaryView: View {
private func metric(
label: String,
- alignment: Alignment,
@ViewBuilder value: () -> some View
) -> some View {
VStack(alignment: .leading, spacing: 2) {
Text(label)
.font(.caption2)
.foregroundStyle(.secondary)
- .frame(maxWidth: .infinity, alignment: alignment)
+ .frame(maxWidth: .infinity, alignment: .center)
value()
- .frame(maxWidth: .infinity, alignment: alignment)
+ .frame(maxWidth: .infinity, alignment: .center)
}
.frame(maxWidth: .infinity)
}
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 3bf197e..a02aa30 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -90,7 +90,6 @@ private extension AppSettingsView {
static let panelPadding: CGFloat = 12
static let surfaceCornerRadius: CGFloat = 16
static let panelCornerRadius: CGFloat = 10
- static let iconWidth: CGFloat = 18
static let notificationOptionsButtonSize: CGFloat = 22
static let menuBarQuotaPickerWidth: CGFloat = 72
static let statusAnimation = Animation.codexStatus
@@ -126,15 +125,14 @@ private extension AppSettingsView {
var menuBarQuotaRow: some View {
let isEnabled = isMenuBarQuotaEnabled
- return HStack(spacing: 10) {
- Image(systemName: "gauge.with.dots.needle.50percent")
- .frame(width: Metrics.iconWidth)
- .foregroundStyle(.tint)
-
- Text("菜单栏额度指示")
-
- Spacer()
-
+ return SettingsToggleRow(
+ icon: "gauge.with.dots.needle.50percent",
+ title: "菜单栏额度指示",
+ isOn: Binding(
+ get: { isMenuBarQuotaEnabled },
+ set: { menuBarQuotaSettings.setEnabled($0) }
+ )
+ ) {
if isEnabled {
Picker(
"额度窗口",
@@ -153,29 +151,17 @@ private extension AppSettingsView {
.frame(width: Metrics.menuBarQuotaPickerWidth)
.transition(.opacity.combined(with: .move(edge: .trailing)))
}
-
- Toggle(
- "菜单栏额度指示",
- isOn: Binding(
- get: { isMenuBarQuotaEnabled },
- set: { menuBarQuotaSettings.setEnabled($0) }
- )
- )
- .labelsHidden()
- .toggleStyle(.switch)
- .controlSize(.small)
}
.animation(Metrics.statusAnimation, value: isEnabled)
}
var menuBarQuotaWindowOptions: [MenuBarQuotaOption] {
var options = (statusViewModel.snapshot?.codexLimit?.windows ?? [])
- .compactMap { window -> MenuBarQuotaOption? in
- guard let selection = MenuBarQuotaSelection(windowId: window.id) else {
- return nil
- }
-
- return MenuBarQuotaOption(selection: selection, title: window.label)
+ .map { window in
+ MenuBarQuotaOption(
+ selection: MenuBarQuotaSelection(windowKind: window.kind),
+ title: window.label
+ )
}
let selectedWindow = menuBarQuotaSettings.activeWindowSelection
@@ -262,9 +248,9 @@ private extension AppSettingsView {
var syncRowState: SyncRowState {
SyncRowState(
+ isActive: syncSettings.isEffectivelyActive(isHookEnabled: codexHookSettings.isEnabled),
isHookEnabled: codexHookSettings.isEnabled,
isHookUpdating: codexHookSettings.isUpdating,
- isSyncEnabled: syncSettings.isEnabled,
isSyncAvailable: syncSettings.isSyncAvailable,
isSyncing: syncSettings.isSyncing
)
@@ -273,15 +259,14 @@ private extension AppSettingsView {
/// 主开关行保留在设置窗口内, 子选项在右侧子面板中展开
var notificationRow: some View {
VStack(alignment: .leading, spacing: 4) {
- HStack(spacing: 10) {
- Image(systemName: "bell.badge")
- .frame(width: Metrics.iconWidth)
- .foregroundStyle(.tint)
-
- Text("系统通知")
-
- Spacer()
-
+ SettingsToggleRow(
+ icon: "bell.badge",
+ title: "系统通知",
+ isOn: Binding(
+ get: { notificationSettings.isEnabled },
+ set: { setNotificationsEnabled($0) }
+ )
+ ) {
Button {
onNotificationOptionsAction(.toggle(alignmentScreenFrame: notificationRowFrame))
} label: {
@@ -299,17 +284,6 @@ private extension AppSettingsView {
.accessibilityHidden(!notificationSettings.canShowOptions)
.help("通知选项")
.animation(Metrics.statusAnimation, value: notificationSettings.canShowOptions)
-
- Toggle(
- "系统通知",
- isOn: Binding(
- get: { notificationSettings.isEnabled },
- set: { setNotificationsEnabled($0) }
- )
- )
- .labelsHidden()
- .toggleStyle(.switch)
- .controlSize(.small)
}
.background(
ScreenFrameReader { frame in
@@ -370,9 +344,9 @@ private extension AppSettingsView {
var versionRow: some View {
let status = versionStatus
- return HStack(spacing: 10) {
+ return HStack(spacing: SettingsRowMetrics.spacing) {
Image(systemName: "info.circle")
- .frame(width: Metrics.iconWidth)
+ .frame(width: SettingsRowMetrics.iconWidth)
.foregroundStyle(.tint)
Text("CodexBar 版本")
@@ -457,16 +431,13 @@ private extension AppSettingsView {
}
private struct SyncRowState {
+ /// 由 WorkflowSyncSettings.isEffectivelyActive 统一判定, 视图层不再拼接业务谓词
+ let isActive: Bool
let isHookEnabled: Bool
let isHookUpdating: Bool
- let isSyncEnabled: Bool
let isSyncAvailable: Bool
let isSyncing: Bool
- var isActive: Bool {
- isHookEnabled && isSyncEnabled && isSyncAvailable
- }
-
var canToggle: Bool {
isHookEnabled && !isHookUpdating && isSyncAvailable
}
diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swift
index f67464c..8f67d45 100644
--- a/CodexBar/Views/Settings/CodexVersionSection.swift
+++ b/CodexBar/Views/Settings/CodexVersionSection.swift
@@ -94,8 +94,7 @@ struct CodexVersionSection: View {
}
private func copyPathToPasteboard(_ path: String, source: CodexCLIExecutableSource) {
- NSPasteboard.general.clearContents()
- NSPasteboard.general.setString(path, forType: .string)
+ PasteboardWriter.copy(path)
copiedPathResetTasks[source]?.cancel()
copiedPathResetTasks[source] = Task { @MainActor in
@@ -108,7 +107,7 @@ struct CodexVersionSection: View {
private enum Metrics {
static let rowSpacing: CGFloat = 14
- static let iconWidth: CGFloat = 18
+ static let iconWidth = SettingsRowMetrics.iconWidth
static let childIndent: CGFloat = 28
static let versionColumnWidth: CGFloat = 270
static let statusAnimation = Animation.codexStatus
diff --git a/CodexBar/Views/Settings/HotKeyRecorderRow.swift b/CodexBar/Views/Settings/HotKeyRecorderRow.swift
index 64acbbb..059042a 100644
--- a/CodexBar/Views/Settings/HotKeyRecorderRow.swift
+++ b/CodexBar/Views/Settings/HotKeyRecorderRow.swift
@@ -9,9 +9,9 @@ struct HotKeyRecorderRow: View {
var body: some View {
VStack(alignment: .leading, spacing: 4) {
- HStack(spacing: 10) {
+ HStack(spacing: SettingsRowMetrics.spacing) {
Image(systemName: "keyboard")
- .frame(width: Metrics.iconWidth)
+ .frame(width: SettingsRowMetrics.iconWidth)
.foregroundStyle(.tint)
Text("使用快捷键")
@@ -144,7 +144,6 @@ struct HotKeyRecorderRow: View {
}
private enum Metrics {
- static let iconWidth: CGFloat = 18
static let shortcutButtonMinWidth: CGFloat = 78
}
}
diff --git a/CodexBar/Views/Settings/SettingsIndentedRow.swift b/CodexBar/Views/Settings/SettingsIndentedRow.swift
index c356f0c..df7f8b4 100644
--- a/CodexBar/Views/Settings/SettingsIndentedRow.swift
+++ b/CodexBar/Views/Settings/SettingsIndentedRow.swift
@@ -3,8 +3,8 @@ import SwiftUI
/// 设置页中与主行标题对齐的缩进辅助行
struct SettingsIndentedRow<Content: View>: View {
var alignment: VerticalAlignment = .center
- var iconWidth: CGFloat = 18
- var spacing: CGFloat = 10
+ var iconWidth: CGFloat = SettingsRowMetrics.iconWidth
+ var spacing: CGFloat = SettingsRowMetrics.spacing
@ViewBuilder var content: () -> Content
var body: some View {
diff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swift
index d22e25b..e8561e6 100644
--- a/CodexBar/Views/Settings/SettingsToggleRow.swift
+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift
@@ -1,22 +1,45 @@
import SwiftUI
-/// 设置页通用开关行
-struct SettingsToggleRow: View {
+/// 设置页行布局共享常量: 各行的图标列宽与行内间距必须一致才能对齐
+enum SettingsRowMetrics {
+ static let iconWidth: CGFloat = 18
+ static let spacing: CGFloat = 10
+}
+
+/// 设置页通用开关行, accessory 插入在开关左侧
+struct SettingsToggleRow<Accessory: View>: View {
let icon: String
let title: String
let isOn: Binding<Bool>
- var isEnabled = true
+ let isEnabled: Bool
+ private let accessory: Accessory
+
+ init(
+ icon: String,
+ title: String,
+ isOn: Binding<Bool>,
+ isEnabled: Bool = true,
+ @ViewBuilder accessory: () -> Accessory
+ ) {
+ self.icon = icon
+ self.title = title
+ self.isOn = isOn
+ self.isEnabled = isEnabled
+ self.accessory = accessory()
+ }
var body: some View {
- HStack(spacing: 10) {
+ HStack(spacing: SettingsRowMetrics.spacing) {
Image(systemName: icon)
- .frame(width: Metrics.iconWidth)
+ .frame(width: SettingsRowMetrics.iconWidth)
.foregroundStyle(.tint)
Text(title)
Spacer()
+ accessory
+
Toggle(title, isOn: isOn)
.labelsHidden()
.toggleStyle(.switch)
@@ -24,8 +47,17 @@ struct SettingsToggleRow: View {
.disabled(!isEnabled)
}
}
+}
- private enum Metrics {
- static let iconWidth: CGFloat = 18
+extension SettingsToggleRow where Accessory == EmptyView {
+ init(
+ icon: String,
+ title: String,
+ isOn: Binding<Bool>,
+ isEnabled: Bool = true
+ ) {
+ self.init(icon: icon, title: title, isOn: isOn, isEnabled: isEnabled) {
+ EmptyView()
+ }
}
}
diff --git a/CodexBar/Views/Shared/LiquidGlassStyle.swift b/CodexBar/Views/Shared/LiquidGlassStyle.swift
index 76fd636..1701377 100644
--- a/CodexBar/Views/Shared/LiquidGlassStyle.swift
+++ b/CodexBar/Views/Shared/LiquidGlassStyle.swift
@@ -253,19 +253,20 @@ private struct LiquidGlassFrostedTexture: View {
let columns = max(Int((size.width / step).rounded(.up)), 0)
let rows = max(Int((size.height / step).rounded(.up)), 0)
let baseOpacity = colorScheme == .dark ? 0.035 : 0.045
- let outerScale = isOuterSurface ? 0.75 : 1
+ let outerScale = isOuterSurface ? 0.75 : 1.0
+ let shadowFactor = colorScheme == .dark ? 0.24 : 0.16
+
+ // 按强度分桶合并同色点, 把上万次单点 fill 压缩成每桶一次路径填充
+ // 桶内取中值不透明度, 与逐点绘制的偏差不超过 baseOpacity / (2 * bucketCount)
+ var highlightPaths = [Path](repeating: Path(), count: Self.bucketCount)
+ var shadowPaths = [Path](repeating: Path(), count: Self.bucketCount)
for row in 0 ..< rows {
for column in 0 ..< columns {
let sample = Self.noise(column: column, row: row)
let isHighlight = sample >= 0.5
let strength = isHighlight ? (sample - 0.5) * 2 : (0.5 - sample) * 2
- let opacity = baseOpacity * strength * outerScale
- let color = if isHighlight {
- Color.white.opacity(opacity)
- } else {
- Color.black.opacity(opacity * (colorScheme == .dark ? 0.24 : 0.16))
- }
+ let bucket = min(Int(strength * Double(Self.bucketCount)), Self.bucketCount - 1)
let rect = CGRect(
x: CGFloat(column) * step,
y: CGFloat(row) * step,
@@ -273,13 +274,26 @@ private struct LiquidGlassFrostedTexture: View {
height: 1
)
- context.fill(Path(rect), with: .color(color))
+ if isHighlight {
+ highlightPaths[bucket].addRect(rect)
+ } else {
+ shadowPaths[bucket].addRect(rect)
+ }
}
}
+
+ for bucket in 0 ..< Self.bucketCount {
+ let strength = (Double(bucket) + 0.5) / Double(Self.bucketCount)
+ let opacity = baseOpacity * strength * outerScale
+ context.fill(highlightPaths[bucket], with: .color(.white.opacity(opacity)))
+ context.fill(shadowPaths[bucket], with: .color(.black.opacity(opacity * shadowFactor)))
+ }
}
.allowsHitTesting(false)
}
+ private static let bucketCount = 16
+
private nonisolated static func noise(column: Int, row: Int) -> Double {
var value = UInt64(column) &* 0x9E3779B185EBCA87
value ^= UInt64(row) &* 0xC2B2AE3D27D4EB4F
diff --git a/CodexBar/Views/Shared/PasteboardWriter.swift b/CodexBar/Views/Shared/PasteboardWriter.swift
new file mode 100644
index 0000000..c2693a1
--- /dev/null
+++ b/CodexBar/Views/Shared/PasteboardWriter.swift
@@ -0,0 +1,9 @@
+import AppKit
+
+/// 统一收口剪贴板写入
+enum PasteboardWriter {
+ static func copy(_ text: String) {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ }
+}
diff --git a/Docs/AppServer.md b/Docs/AppServer.md
index 248f053..50b62a6 100644
--- a/Docs/AppServer.md
+++ b/Docs/AppServer.md
@@ -125,6 +125,6 @@ UI 只展示「未登录」和「初始化失败」两类特殊状态;具体
- 带 id 的 JSON-RPC 请求先记录为进行,响应或错误到达后回填到同一条。
- `initialized` 这类无 id 请求记录为空响应。
- 日志容量上限 500 条,`RequestLogEntry` 完整保存 request/detail;日志窗口列表和行内展开只渲染单行短预览,非空请求/响应标题行提供完整预览和复制,预览视图对 JSON 做格式化和高亮。
-- 合法 JSON 通过 `JSONSerialization` 重新序列化,使用 `.sortedKeys` 和 `.withoutEscapingSlashes`。
-- 非 JSON 错误消息保持原样。
+- `AppServerSession` 生成请求时已经通过 `JSONSerialization` 使用 `.sortedKeys` 和 `.withoutEscapingSlashes` 稳定序列化;`RequestLogStorage` 直接保存同一份 request 文本,不再二次解析。
+- 响应和 JSON 错误详情进入日志时仍通过 `JSONSerialization` 使用相同选项稳定化;非 JSON 错误消息保持原样。
- 不要把子进程 stderr 直接展示给用户。
diff --git a/Docs/CodexHook.md b/Docs/CodexHook.md
index f3828f2..e37097b 100644
--- a/Docs/CodexHook.md
+++ b/Docs/CodexHook.md
@@ -173,7 +173,7 @@ Hook 写入路径不更新 `daily.jsonl`,也不执行重建或清理旧文件
`WorkflowService` 是 actor,只在现有自动刷新或手动刷新触发工作流统计刷新时检查 `maintenance.json`。打开菜单面板时只读取现有 `daily.jsonl`。如果没有 `pending` 或 `dirty`,服务不会执行维护。
-维护时优先处理 `dirty`,从对应日期文件第一行开始流式重建当天聚合;再处理 `pending`,从 `days[date].offset` 开始流式读取新增事件并合并到已有当天聚合。每条坏行会被跳过并计入 `days[date].corrupt`。处理完成后先在 `stats.lock` 外原子写回 `daily.jsonl`,再短暂持有 `stats.lock` 更新 `maintenance.json`,避免主 App 写 daily 时阻塞 Hook 追加事件。
+维护时优先处理 `dirty`,从对应日期文件第一行开始流式重建当天聚合;再处理 `pending`,从 `days[date].offset` 开始流式读取新增事件并合并到已有当天聚合。同一维护批次只读取一次现有 `daily.jsonl`,所有日期任务共享并逐步更新同一份内存聚合集合,每次落盘前仍对整份集合执行当前保留策略的归一化。每条坏行会被跳过并计入 `days[date].corrupt`。处理完成后先在 `stats.lock` 外原子写回 `daily.jsonl`,再短暂持有 `stats.lock` 更新 `maintenance.json`,避免主 App 写 daily 时阻塞 Hook 追加事件。批次没有写入时,服务使用文件 size、identifier 和当天日期键组成的进程内 stamp 跳过未变化文件的重复全量归一化;日期跨天或文件变化后会重新检查并在需要时原子改写。
## 保留策略
diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.md
index 4b04621..ad1a82e 100644
--- a/Docs/DevelopmentGuide.md
+++ b/Docs/DevelopmentGuide.md
@@ -104,7 +104,7 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall
Hook 开启时,账号卡片下方始终显示固定高度 `CodexActivityCard`。`CodexQuotaSnapshot` 为 `nil` 时,卡片显示「暂无数据」且不开放任务中心;Monitor 继续维护实时状态。快照可用时,卡片按等待、运行、最近完成、最近终止、空闲的顺序展示项目最后一级名称、模型或工具、耗时及其他活动任务数量;只有终止历史时显示最近一项灰色终止状态。存在任务中心内容时,卡片可点击,其他活动任务数量使用右侧 `+N` 徽标,hover 和选中反馈作用于卡片描边。
-`ActivityCenterPanelController` 展示 `CodexActivitySnapshot` 的完整等待、运行、最近完成和最近终止列表。等待和运行按最后活动时间倒序,完成和终止按各自结束时间倒序;列表身份使用进程内 opaque UUID,不向 UI 暴露 session/turn ID。最近完成和最近终止保留 10 分钟。卡片与任务中心直接观察同一个 Monitor,并在菜单可见、额度快照可用且存在任务中心内容时使用 `CodexActivityCenterPresentationState` 的共享逐秒时间。任务中心打开期间额度快照变为 `nil` 时立即关闭。
+`ActivityCenterPanelController` 展示 `CodexActivitySnapshot` 的完整等待、运行、最近完成和最近终止列表。等待和运行按最后活动时间倒序,完成和终止按各自结束时间倒序;列表身份使用进程内 opaque UUID,不向 UI 暴露 session/turn ID。最近完成和最近终止保留 10 分钟。活动 Monitor 和 `CodexActivityCenterPresentationState` 作为普通引用传入菜单根视图,再由活动卡片自身观察;这样共享逐秒时间只让卡片失效,不会带动整个菜单树每秒重算。卡片与任务中心观察同一个 Monitor,并在菜单可见、额度快照可用且存在任务中心内容时使用 presentation state 的共享逐秒时间。任务中心打开期间额度快照变为 `nil` 时立即关闭。
错误图标触发条件:
@@ -167,13 +167,13 @@ Command-Space 不直接关闭菜单面板, 只短暂抑制 600 ms 内的 active
热力图详情面板、重置次数详情面板和并发任务中心都会通过 `containsScreenPoint(_:)` 告诉关闭监听器自己的屏幕区域, 因此点击这些 child panel 内部不会触发主菜单面板关闭。重置次数详情面板和并发任务中心可接收鼠标事件用于滚动; 热力图详情面板不接收鼠标事件。并发任务中心是点击后保持打开的面板;出现有效的热力图方块 hover context 时会自动收回任务中心并展示当天详情,点击重置次数也会显式切换并关闭任务中心。
-侧边面板的共同行为集中在 `CodexBar/Controllers/SidePanelSupport.swift`。`NonactivatingSidePanel` 不能成为 key/main window;`KeyableBorderlessPanel` 用于需要键盘焦点的通知子选项面板和 fallback 面板;`SidePanelDrawerAnimator` 管理横向抽屉 transform;`SidePanelDrawerPresenter` 管理重置次数、并发任务中心和通知子选项面板的显隐状态、generation、入退场动画及 child window 挂载。`SidePanelSupport` 统一提供 panel 创建、左右侧选择、屏幕边界夹紧、锚点行校验与对齐、菜单面板 key window 恢复、圆角 layer 配置和屏幕坐标换算。侧边面板视图的玻璃底、背板、描边和圆角裁剪共用 `LiquidGlassStyle.swift` 的 `sidePanelChrome(cornerRadius:)`。
+侧边面板的共同行为集中在 `CodexBar/Controllers/SidePanelSupport.swift`。`NonactivatingSidePanel` 不能成为 key/main window;`KeyableBorderlessPanel` 用于需要键盘焦点的通知子选项面板和 fallback 面板;`SidePanelDrawerAnimator` 管理横向抽屉 transform;`SidePanelDrawerPresenter` 管理重置次数、并发任务中心和通知子选项面板的显隐状态、generation、入退场动画及 child window 挂载;`SidePanelContentHost` 统一三个侧边详情面板的内容宿主行为——懒建 panel + hostingController、每次更新替换 rootView、圆角 layer 重配、内容尺寸同步与屏幕点命中检测。`SidePanelSupport` 统一提供 panel 创建、左右侧选择、屏幕边界夹紧、锚点行校验与对齐、菜单面板 key window 恢复、圆角 layer 配置和屏幕坐标换算。侧边面板视图的玻璃底、背板、描边和圆角裁剪共用 `LiquidGlassStyle.swift` 的 `sidePanelChrome(cornerRadius:)`。
`HeatmapDetailPanelController` 管理 hover 请求、Y 轴策略、侧边切换队列和 token/workflow 内容更新;`ResetCreditsPanelController` 管理重置次数内容、最大高度和点击切换;`ActivityCenterPanelController` 观察常驻 Monitor 快照并更新列表与窗口布局。任务中心宽度固定,高度由标题、分区、固定行高、间距和底部留白计算,并受屏幕可见高度及活动卡片顶边到主面板底边的范围限制。活动卡片把 `ScreenFrameProvider` 作为锚点交给控制器,控制器每次布局都只读取属于当前菜单窗口的实时 frame;首次读取失败时等待一个 MainActor 调度点重试,仍无有效锚点才回退主面板垂直居中。锚点有效时,面板顶边与卡片顶边对齐,底边最低与主面板底边齐平;达到高度上限后列表内部滚动。
任务中心列表使用普通 `VStack` 和单层条目 transition。快照变化后,SwiftUI 提交列表布局,AppKit 在下一个 MainActor 调度点用 0.20 秒 ease-in-ease-out 曲线更新 panel frame;新的快照会取消尚未执行的布局更新。任务中心内容变空时等待 0.20 秒再执行抽屉收起,期间出现新内容会取消收起。
-设置窗口和日志窗口都继承 `HostingWindowController` 的行为: 懒创建, 关闭后不释放, 重新打开复用, 按当前屏幕居中, 重新打开对应入口时只移动和置前对应窗口。窗口 level 保持 `.normal`; 置前时先恢复 `AuxiliaryHostingWindow.allowsKeyFocus`, 再 `orderFrontRegardless()`, `NSRunningApplication.current.activate(options: [])` 和 `makeKeyAndOrderFront(nil)`, 只做一次性置前, 不持续置顶。CodexBar 是 `LSUIElement` 菜单栏 App, 首次懒创建辅助窗口时需要通过当前运行中应用激活, 避免设置或日志窗口第一次打开时没有稳定拉到最前。
+设置窗口和日志窗口都继承 `HostingWindowController` 的行为: 懒创建, 关闭后不释放, 重新打开复用, 按当前屏幕居中, 重新打开对应入口时只移动和置前对应窗口。窗口 level 保持 `.normal`; 置前时先恢复 `AuxiliaryHostingWindow.allowsKeyFocus`, 再执行 `NSWindow.bringToFrontActivatingApp()` (`ScreenGeometry.swift`, 即 `orderFrontRegardless()` → `NSRunningApplication.current.activate(options: [])` → `makeKeyAndOrderFront(nil)` 的固定序列, fallback 面板和菜单面板聚焦共用), 只做一次性置前, 不持续置顶。CodexBar 是 `LSUIElement` 菜单栏 App, 首次懒创建辅助窗口时需要通过当前运行中应用激活, 避免设置或日志窗口第一次打开时没有稳定拉到最前。
设置窗口和日志窗口使用 `AuxiliaryHostingWindow`; 窗口可以成为 key window, 但不能成为 main window。关闭菜单面板期间会临时禁止成为 key window, 避免菜单面板收起时抢焦点。通过快捷键打开或关闭菜单面板时, 只激活并置前当前面板, 不主动置前已有的设置窗口或日志窗口。
@@ -353,9 +353,10 @@ codex app-server --listen stdio://
`AppServerSession` 负责 JSON-RPC 读写:
- 每个带 id 的请求先写入 `RequestLogStorage.beginRequest`
-- 请求 JSON 使用 sorted keys 和不转义斜杠序列化
+- 请求 JSON 使用 sorted keys 和不转义斜杠序列化,同一份稳定文本直接写入请求日志
- 写入 stdin 时追加换行
- `JSONLineReader` 从 stdout 读取按行 JSON, 只处理 id 匹配的响应, 其他行忽略
+- id 匹配后用同时包含 `error` 和 `result` 的统一响应信封完成一次完整解码,避免大响应行重复解析
- 收到 JSON-RPC error 时转成 `CodexStatusError.serverError(message)`
- 响应不能解析成期望类型时归为 `.invalidServerResponse`
- `initialized` 是无 id 通知, 不等待响应, 但记录为"请求"
@@ -377,7 +378,7 @@ codex app-server --listen stdio://
- `RequestLogEntry` 完整保存 request/detail
- 列表摘要和行内展开只使用 `RequestLogEntry` 生成的单行短预览
- 非空请求和响应标题行提供完整预览和复制; 预览视图对 JSON 做格式化和高亮
-- 合法 JSON 会稳定化显示, 非 JSON 错误消息保持原样
+- request 直接保存 `AppServerSession` 已稳定序列化的文本;响应和 JSON 错误详情由 storage 使用相同选项稳定化,非 JSON 错误消息保持原样
- storage 用 `OSAllocatedUnfairLock` 保护, 后台请求路径可以同步写入并立即拿到请求 token
- 写入后通过 `Task { @MainActor ... }` 刷新 `RequestLogStore.shared`
- 日志窗口关闭不会清空日志
@@ -427,16 +428,16 @@ app-server 与状态刷新错误:
日志错误处理:
-| 场景 | 行为 |
-| ------------------------ | ------------------------------------ |
-| 请求发送后等待响应 | 日志先显示"进行" |
-| 收到正常响应 | 回填同一条日志为"完成" |
-| 请求失败或响应解析失败 | 回填同一条日志为"错误" |
-| `initialized` 无 id 通知 | 记录为"请求", 不等待响应 |
-| 进程级错误没有 method | 日志行直接预览错误文本 |
-| 合法 JSON 内容 | 重新序列化为稳定顺序并保留未转义斜杠 |
-| 请求 payload | 存完整内容, UI 行内只渲染单行短预览 |
-| 响应或错误详情 | 存完整内容, 通过预览视图查看或复制 |
+| 场景 | 行为 |
+| ------------------------ | ------------------------------------------------------------- |
+| 请求发送后等待响应 | 日志先显示"进行" |
+| 收到正常响应 | 回填同一条日志为"完成" |
+| 请求失败或响应解析失败 | 回填同一条日志为"错误" |
+| `initialized` 无 id 通知 | 记录为"请求", 不等待响应 |
+| 进程级错误没有 method | 日志行直接预览错误文本 |
+| 响应或 JSON 错误详情 | 重新序列化为稳定顺序并保留未转义斜杠 |
+| 请求 payload | 直接保存已稳定序列化的完整内容, UI 行内只渲染单行短预览 |
+| 响应或错误详情 | 存完整内容, 通过预览视图查看或复制 |
设置, Hook 和更新错误:
@@ -592,7 +593,7 @@ flowchart TD
热力图详情面板是菜单面板的 borderless nonactivating child panel, 不接收鼠标事件, 按悬停列优先显示在菜单面板左侧或右侧; 左右空间不足时尝试另一侧, 最终在当前屏幕可见区域内保留 8 px 边距。侧边切换时先以 0.12 秒抽屉动画收起, 再以 0.18 秒展开。热力图详情面板和重置次数详情面板互斥, hover 热力图会立即隐藏重置次数详情面板。nonactivating panel、抽屉 transform、child window 挂载和圆角 layer 配置复用 `SidePanelSupport.swift`。
-`HeatmapDetailPanelController` 会复用同一个 `NSPanel` 和 `NSHostingController`, 但每次 hover 内容变化时必须替换 `hostingController.rootView` 并同步 `setContentSize`。不要用常驻 `ObservableObject` model 持续推送 `UsageHeatmapHoverContext`; Hook 开关会让详情面板在 `212 x 84` 和 `212 x 208` 两种布局之间切换, 复用同一棵 SwiftUI 布局树容易触发 AppKit constraint/layout 递归。相关回归路径是: 先 hover 出详情面板, 打开设置切换 Hook, 再回到主面板 hover 热力图。
+`HeatmapDetailPanelController` 会复用同一个 `NSPanel` 和 `NSHostingController`, 但每次 hover 内容变化时必须替换 `hostingController.rootView` 并同步 `setContentSize` (该更新序列由 `SidePanelContentHost` 统一执行)。不要用常驻 `ObservableObject` model 持续推送 `UsageHeatmapHoverContext`; Hook 开关会让详情面板在 `212 x 84` 和 `212 x 208` 两种布局之间切换, 复用同一棵 SwiftUI 布局树容易触发 AppKit constraint/layout 递归。相关回归路径是: 先 hover 出详情面板, 打开设置切换 Hook, 再回到主面板 hover 热力图。
详情面板分两种:
@@ -863,6 +864,8 @@ flowchart TD
| dirty | schema 变化, daily 缺失或坏行, events 状态不一致, 文件缩小 | 从当天 events 文件开头重建 |
| pending | Hook 新增事件或 events 文件变大 | 从 `days[date].offset` 增量读取 |
+同一维护批次只读取一次现有 `daily.jsonl`,随后让所有 dirty/pending 日期任务共享并逐步更新同一份内存聚合集合;每次落盘前仍对整份集合执行当前保留策略的归一化。批次没有写入时,服务用文件 size、identifier 和当天日期键组成的进程内 stamp 跳过未变化文件的重复全量解码;日期跨天或文件发生变化后会重新检查并在需要时原子改写。
+
聚合规则:
- 事件名先去掉 `_` 和 `-`, 再转小写