Skip to content

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

feat: 完善实时任务状态展示与交互反馈

Bob1b3c3eb485fc
diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swift
index 78ee43b..064ae65 100644
--- a/CodexBar/App/CodexBarApp.swift
+++ b/CodexBar/App/CodexBarApp.swift
@@ -1,5 +1,4 @@
import AppKit
-import Darwin
import SwiftUI
// 测试时禁用应用入口
diff --git a/CodexBar/Controllers/ActivityPanelController.swift b/CodexBar/Controllers/ActivityPanelController.swift
index dad8e7c..7b67e8d 100644
--- a/CodexBar/Controllers/ActivityPanelController.swift
+++ b/CodexBar/Controllers/ActivityPanelController.swift
@@ -1,6 +1,5 @@
import AppKit
import Combine
-import SwiftUI
/// 点击活动卡片后展开的并发任务中心, 复用菜单侧边抽屉定位和动画
@MainActor
diff --git a/CodexBar/Controllers/GlobalHotKeyController.swift b/CodexBar/Controllers/GlobalHotKeyController.swift
index 0490119..5250a7f 100644
--- a/CodexBar/Controllers/GlobalHotKeyController.swift
+++ b/CodexBar/Controllers/GlobalHotKeyController.swift
@@ -1,5 +1,4 @@
import Carbon.HIToolbox
-import Foundation
import os
/// Carbon 全局快捷键注册器, 将系统回调桥接回 MainActor
diff --git a/CodexBar/Controllers/SidePanelPresenter.swift b/CodexBar/Controllers/SidePanelPresenter.swift
index 94fab56..69759a1 100644
--- a/CodexBar/Controllers/SidePanelPresenter.swift
+++ b/CodexBar/Controllers/SidePanelPresenter.swift
@@ -126,7 +126,6 @@ final class SidePanelDrawerAnimator {
/// 热力图详情面板带切边与延迟隐藏 状态机不同 因此不走这里
@MainActor
final class SidePanelDrawerPresenter {
- private let makesKey: Bool
private let usesUntranslatedInitialLayout: Bool
private let drawerAnimator: SidePanelDrawerAnimator
private weak var panel: NSPanel?
@@ -137,11 +136,9 @@ final class SidePanelDrawerPresenter {
init(
animationKey: String,
- makesKey: Bool = false,
usesUntranslatedInitialLayout: Bool = false,
contentViewProvider: @escaping @MainActor () -> NSView?
) {
- self.makesKey = makesKey
self.usesUntranslatedInitialLayout = usesUntranslatedInitialLayout
drawerAnimator = SidePanelDrawerAnimator(
contentViewProvider: contentViewProvider,
@@ -174,9 +171,6 @@ final class SidePanelDrawerPresenter {
self.parentWindow = parentWindow
SidePanelSupport.attach(panel, to: parentWindow)
panel.order(.above, relativeTo: parentWindow.windowNumber)
- if makesKey {
- panel.makeKey()
- }
drawerAnimator.animateEntryAfterInitialLayout(
from: hidden,
panel: panel,
diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swift
index d27286e..d4ebb2e 100644
--- a/CodexBar/Controllers/SidePanelSupport.swift
+++ b/CodexBar/Controllers/SidePanelSupport.swift
@@ -1,6 +1,5 @@
import AppKit
import QuartzCore
-import SwiftUI
/// 侧边详情面板不接收焦点, 只作为菜单面板的跟随子窗口
@MainActor
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index e3bdcc8..bf30709 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -1,6 +1,5 @@
import AppKit
import Combine
-import os
import SwiftUI
/// 菜单栏入口控制器, 统一管理状态图标, 菜单面板, 右键菜单和全局快捷键
@@ -106,7 +105,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private let statusIconPresentation = StatusItemIconPresentation()
private var statusIconHostingView: StatusItemIconHostingView?
private var statusIconExpirationTask: Task<Void, Never>?
- private var statusToolTipTask: Task<Void, Never>?
private var registeredHotKeyShortcut: GlobalHotKeyShortcut?
private var auxiliaryWindowFocusRestoreTask: Task<Void, Never>?
private var activeStatusItemMenu: NSMenu?
@@ -160,7 +158,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
statusIconExpirationTask?.cancel()
statusIconHostingView?.removeFromSuperview()
statusIconHostingView = nil
- statusToolTipTask?.cancel()
syncScheduler.cancel()
setAuxiliaryWindowKeyFocus(true)
globalHotKeyController.uninstall()
@@ -410,9 +407,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
let previousState = statusIconState
guard previousState != state else { return }
statusIconState = state
- if previousState?.hasLiveDuration != state.hasLiveDuration {
- configureStatusToolTipRefresh(for: state)
- }
refreshStatusIconPresentation(animated: previousState != nil)
scheduleStatusIconExpiration()
}
@@ -420,8 +414,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private func refreshStatusIconPresentation(animated: Bool = true) {
guard let state = statusIconState else { return }
let now = Date()
- let toolTip = state.toolTip(at: now)
- statusItem.button?.toolTip = toolTip
statusIconPresentation.update(
symbolName: state.symbolName(at: now),
ordinaryUsageAllowed: state.ordinaryUsageAllowed,
@@ -450,27 +442,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
}
}
- private func configureStatusToolTipRefresh(for state: StatusIconState) {
- statusToolTipTask?.cancel()
- statusToolTipTask = nil
- guard state.hasLiveDuration else {
- return
- }
-
- statusToolTipTask = Task { @MainActor [weak self] in
- while !Task.isCancelled {
- try? await Task.sleep(for: .seconds(60))
- guard let self,
- !Task.isCancelled,
- let state = statusIconState,
- state.hasLiveDuration else {
- return
- }
- refreshStatusIconPresentation()
- }
- }
- }
-
@objc private func statusItemClicked(_ sender: NSStatusBarButton) {
guard let event = NSApplication.shared.currentEvent else {
toggleMenuSurface(relativeTo: sender)
diff --git a/CodexBar/Models/ActivityEventKind.swift b/CodexBar/Models/ActivityEventKind.swift
index afad453..e135e14 100644
--- a/CodexBar/Models/ActivityEventKind.swift
+++ b/CodexBar/Models/ActivityEventKind.swift
@@ -1,5 +1,3 @@
-import Foundation
-
/// app-server 事件映射到业务统计的生命周期阶段, 持久化直接使用枚举名称
nonisolated enum ActivityEventKind: String, CaseIterable, Hashable {
case sessionStarted
diff --git a/CodexBar/Models/ActivityModels.swift b/CodexBar/Models/ActivityModels.swift
index e719352..5affba9 100644
--- a/CodexBar/Models/ActivityModels.swift
+++ b/CodexBar/Models/ActivityModels.swift
@@ -1,29 +1,14 @@
import Foundation
-/// 实时活动管道的共享保留窗口
-/// tail reader 的 bootstrap 回放范围与任务中心的历史保留期是同一个不变量, 必须相等
+/// 活动状态, 任务历史和子 Agent 关联共用的保留窗口
nonisolated enum ActivityRetention {
static let window: TimeInterval = 24 * 60 * 60
}
-/// 活跃任务最近收到的 活动事件, 供活动卡片展示当前执行阶段
-nonisolated enum ActivityPhase: Equatable {
- case promptSubmitted
- case toolStarted
- case toolFinished
- case compactionStarted
- case compactionFinished
- case subagentStarted
- case subagentFinished
- case approvalRequested
- case stopRequested
-}
-
/// 正在运行或等待批准的任务摘要, 不对 UI 暴露原始会话 ID
nonisolated struct ActivityTaskSnapshot: Equatable, Identifiable {
let id: UUID
let isAnonymous: Bool
- let latestEvent: ActivityPhase
let projectName: String?
let modelName: String?
let effort: String?
@@ -35,9 +20,10 @@ nonisolated struct ActivityTaskSnapshot: Equatable, Identifiable {
let activeSubagentCount: Int?
var tokenUsage: TokenUsage?
var itemType: String?
+ var presentation: ActivityLiveSummary?
var toolDisplayName: String? {
- toolName ?? itemType
+ ActivityDisplayFormat.toolActionText(itemType: itemType, toolName: toolName)
}
}
@@ -88,6 +74,7 @@ nonisolated struct ActivityTermination: Equatable, Identifiable {
let terminatedAt: Date
let duration: TimeInterval?
var tokenUsage: TokenUsage?
+ var isFailure = false
}
/// 实时越过静默阈值时交给通知服务的最小信息, 不包含原始 session 或 turn ID
@@ -112,6 +99,24 @@ nonisolated struct ActivitySnapshot: Equatable {
recentTerminations: []
)
+ var panelWaitingTasks: [ActivityTaskSnapshot] {
+ waitingTasks + runningTasks.filter { $0.presentation?.waiting != nil }
+ }
+
+ var panelRunningTasks: [ActivityTaskSnapshot] {
+ runningTasks.filter { $0.presentation?.waiting == nil }
+ }
+
+ var panelPrimaryActivity: CodexPrimaryActivity {
+ if let task = panelWaitingTasks.first {
+ return .waiting(task)
+ }
+ if let task = panelRunningTasks.first {
+ return .running(task)
+ }
+ return primaryActivity
+ }
+
var primaryWaitingTask: ActivityTaskSnapshot? {
waitingTasks.first
}
@@ -201,15 +206,6 @@ nonisolated enum CodexPrimaryActivity: Equatable {
case completed(ActivityCompletion)
case terminated(ActivityTermination)
case idle
-
- var tokenUsage: TokenUsage? {
- switch self {
- case let .completed(completion): completion.tokenUsage
- case let .terminated(termination): termination.tokenUsage
- case let .waiting(task), let .running(task): task.tokenUsage
- case .idle: nil
- }
- }
}
/// 只有 live 事件 或 session 生命周期会发布 transition, bootstrap 永远不会触发历史通知
@@ -226,7 +222,7 @@ nonisolated enum ActivityTransition: Equatable {
}
nonisolated enum CodexDurationFormat {
- static func activityText(for interval: TimeInterval) -> String {
+ static func activityText(for interval: TimeInterval, locale: Locale = .current) -> String {
let totalSeconds = max(0, Int(interval.rounded()))
let duration = Duration.seconds(Double(totalSeconds))
let allowedUnits: Set<Duration.UnitsFormatStyle.Unit> = if totalSeconds >= 3600 {
@@ -236,21 +232,37 @@ nonisolated enum CodexDurationFormat {
} else {
[.seconds]
}
- return abbreviated(duration, allowedUnits: allowedUnits)
+ return abbreviated(duration, allowedUnits: allowedUnits, locale: locale)
}
static func abbreviated(
_ duration: Duration,
- allowedUnits: Set<Duration.UnitsFormatStyle.Unit>
+ allowedUnits: Set<Duration.UnitsFormatStyle.Unit>,
+ locale: Locale = .current
) -> String {
- duration.formatted(
+ let formatted = duration.formatted(
.units(
allowed: allowedUnits,
width: .abbreviated,
zeroValueUnits: .show(length: 1),
fractionalPart: .hide(rounded: .down)
)
+ .locale(locale)
+ .attributed
)
+ var result = ""
+ var previousPart: AttributeScopes.FoundationAttributes.MeasurementAttribute.Value?
+ // 按系统标记的数字和单位补空格, 保留各语言原有的分隔符和单位名称
+ for (part, range) in formatted.runs[\.measurement] {
+ let text = String(formatted[range].characters)
+ if let part, let previousPart, part != previousPart,
+ result.last?.isWhitespace == false, text.first?.isWhitespace == false {
+ result += " "
+ }
+ result += text
+ previousPart = part
+ }
+ return result
}
}
@@ -260,31 +272,6 @@ nonisolated enum ActivityDisplayFormat {
return components.isEmpty ? nil : components.joined(separator: " • ")
}
- static func eventText(for task: ActivityTaskSnapshot) -> String {
- switch task.latestEvent {
- case .promptSubmitted:
- String(localized: "activity.event.thinking")
- case .toolStarted:
- task.toolDisplayName.map { String(localized: "activity.event.using-named-tool", defaultValue: "\($0)") }
- ?? String(localized: "activity.event.using-tool")
- case .toolFinished:
- task.toolDisplayName.map { String(localized: "activity.event.finished-using-tool", defaultValue: "\($0)") }
- ?? String(localized: "activity.event.tool-completed")
- case .compactionStarted:
- String(localized: "activity.event.compacting-context")
- case .compactionFinished:
- String(localized: "activity.event.context-compaction-completed")
- case .subagentStarted:
- String(localized: "activity.event.starting-subagent")
- case .subagentFinished:
- String(localized: "activity.event.subagent-completed")
- case .approvalRequested:
- String(localized: "activity.status.waiting-for-approval")
- case .stopRequested:
- String(localized: "activity.event.finishing")
- }
- }
-
static func completionRelativeText(_ completedAt: Date, now: Date) -> String {
relativeText(since: completedAt, now: now, action: .completed)
}
@@ -293,45 +280,11 @@ nonisolated enum ActivityDisplayFormat {
relativeText(since: terminatedAt, now: now, action: .terminated)
}
- /// 活动卡片, 任务中心, 菜单栏 tooltip 和系统通知共用的时长片段
- static func waitingDurationFragment(since stateChangedAt: Date, now: Date) -> String {
- let duration = CodexDurationFormat.activityText(for: now.timeIntervalSince(stateChangedAt))
- return String(localized: "activity.duration.waiting", defaultValue: "\(duration)")
- }
-
- static func runningDurationFragment(since startedAt: Date, now: Date) -> String {
- let duration = CodexDurationFormat.activityText(for: now.timeIntervalSince(startedAt))
- return String(localized: "activity.duration.running", defaultValue: "\(duration)")
- }
-
static func elapsedDurationFragment(for duration: TimeInterval) -> String {
let durationText = CodexDurationFormat.activityText(for: duration)
return String(localized: "activity.duration.elapsed", defaultValue: "\(durationText)")
}
- /// 活动卡片和任务中心共用同一份文案片段
- static func waitingDetailComponents(
- for task: ActivityTaskSnapshot,
- now: Date
- ) -> [String] {
- [
- task.toolDisplayName ?? String(localized: "activity.event.waiting-next-action"),
- waitingDurationFragment(since: task.stateChangedAt, now: now)
- ]
- }
-
- static func runningDetailComponents(
- for task: ActivityTaskSnapshot,
- now: Date
- ) -> [String] {
- let duration = if task.showsPreciseDuration, let startedAt = task.startedAt {
- runningDurationFragment(since: startedAt, now: now)
- } else {
- String(localized: "activity.status.running")
- }
- return [duration, eventText(for: task)]
- }
-
static func historyDetailComponents(
duration: TimeInterval?,
relativeText: String
diff --git a/CodexBar/Models/CodexAccountModels.swift b/CodexBar/Models/CodexAccountModels.swift
index b1c1883..ea91ce3 100644
--- a/CodexBar/Models/CodexAccountModels.swift
+++ b/CodexBar/Models/CodexAccountModels.swift
@@ -1,5 +1,3 @@
-import Foundation
-
/// app-server account/read 的账号信息, 只保留菜单面板需要展示的字段
nonisolated struct CodexAccount: Decodable, Equatable {
let type: String
diff --git a/CodexBar/Models/CodexDateFormat.swift b/CodexBar/Models/CodexDateFormat.swift
index 2d01ad4..cfa159d 100644
--- a/CodexBar/Models/CodexDateFormat.swift
+++ b/CodexBar/Models/CodexDateFormat.swift
@@ -44,15 +44,6 @@ nonisolated enum CodexDateFormat {
return date
}
- /// yyyy-MM-dd HH:mm:ss.SSS, 归一化活动事件写入本机时间字符串
- static func localTimestampString(from date: Date) -> String {
- localTimestampFormatter.string(from: date)
- }
-
- static func localTimestampDate(from string: String) -> Date? {
- localTimestampFormatter.date(from: string)
- }
-
/// yyyy-MM-dd HH:mm:ss, 设置页与重置次数详情统一的本地时间展示
static func localDisplayString(from date: Date) -> String {
localDisplayFormatter.string(from: date)
@@ -63,11 +54,6 @@ nonisolated enum CodexDateFormat {
dayString(from: date)
}
- /// ISO8601 internet date-time, 带或不带小数秒均可解析
- static func iso8601Date(from string: String) -> Date? {
- try? Date(string, strategy: .iso8601)
- }
-
/// 所有日期计算共用: Codex 落盘的日期键与目录名都是公历
/// 系统区域日历可能是和历/佛历等, 不能用 Calendar.current
static let localGregorianCalendar: Calendar = {
@@ -77,16 +63,8 @@ nonisolated enum CodexDateFormat {
return calendar
}()
- /// 以下格式器配置后不再修改; DateFormatter/ISO8601DateFormatter
+ /// 以下格式器配置后不再修改; DateFormatter
/// 在 macOS 10.9+ 线程安全, 可跨并发域缓存共享
- private static let localTimestampFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.locale = Locale(identifier: "en_US_POSIX")
- formatter.timeZone = .autoupdatingCurrent
- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
- return formatter
- }()
-
private static let localDisplayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
diff --git a/CodexBar/Models/HistorySnapshot.swift b/CodexBar/Models/HistorySnapshot.swift
index 1d2eb5f..36472f3 100644
--- a/CodexBar/Models/HistorySnapshot.swift
+++ b/CodexBar/Models/HistorySnapshot.swift
@@ -1,5 +1,3 @@
-import Foundation
-
// MARK: - 每日聚合指标
/// 热力图详情面板直接消费的每日统计
diff --git a/CodexBar/Models/StatusIconState.swift b/CodexBar/Models/StatusIconState.swift
index d41a3a7..0a0d379 100644
--- a/CodexBar/Models/StatusIconState.swift
+++ b/CodexBar/Models/StatusIconState.swift
@@ -15,86 +15,12 @@ struct StatusIconState: Equatable {
case .idle: usesErrorImage ? "person.slash.fill" : "person.fill"
}
}
-
- var hasLiveDuration: Bool {
- activity.hasActiveTasks
- }
-
- func toolTip(at now: Date) -> String? {
- var lines: [String] = []
- if usesErrorImage {
- lines.append(String(localized: "codex-status.account.unavailable"))
- }
-
- if let activityText = activityToolTip(at: now) {
- lines.append(activityText)
- }
- if activity.activeCount > 1 {
- lines.append(
- String(localized: "status-item.activity-summary", defaultValue: "\(activity.waitingCount, specifier: "%lld")\(activity.runningCount, specifier: "%lld")")
- )
- }
- if let progress {
- lines.append(progress.toolTip)
- }
- return lines.isEmpty ? nil : lines.joined(separator: "\n")
- }
-
- private func activityToolTip(at now: Date) -> String? {
- switch activity.statusItemActivity(at: now) {
- case let .waiting(task):
- var text = String(localized: "activity.status.codex-waiting-for-approval")
- if let projectName = task.projectName {
- text += " • \(projectName)"
- }
- if let toolName = task.toolDisplayName {
- text += " • \(toolName)"
- }
- text += " • \(ActivityDisplayFormat.waitingDurationFragment(since: task.stateChangedAt, now: now))"
- return text
- case let .running(task):
- var text = String(localized: "activity.status.codex-running")
- if let projectName = task.projectName {
- text += " • \(projectName)"
- }
- if task.showsPreciseDuration, let startedAt = task.startedAt {
- text += " • \(ActivityDisplayFormat.runningDurationFragment(since: startedAt, now: now))"
- }
- return text
- case let .completed(completion):
- var text = String(localized: "activity.status.codex-just-completed")
- if let projectName = completion.projectName {
- text += " • \(projectName)"
- }
- if let duration = completion.duration {
- text += " • \(ActivityDisplayFormat.elapsedDurationFragment(for: duration))"
- }
- return text
- case let .terminated(termination):
- var text = String(localized: "activity.status.codex-stopped")
- if let projectName = termination.projectName {
- text += " • \(projectName)"
- }
- if let duration = termination.duration {
- text += " • \(ActivityDisplayFormat.elapsedDurationFragment(for: duration))"
- }
- return text
- case .idle:
- return nil
- }
- }
}
struct StatusIconProgress: Equatable {
- let label: String
let percent: Int
let isStale: Bool
- var toolTip: String {
- let percentText = CodexPercentageFormat.string(from: percent)
- return String(localized: "quota.status.remaining", defaultValue: "\(label)\(percentText)")
- }
-
init?(snapshot: CodexQuotaSnapshot?, selection: MenuBarQuotaSelection) {
guard let targetKind = selection.windowKind,
let snapshot,
@@ -103,7 +29,6 @@ struct StatusIconProgress: Equatable {
return nil
}
- label = window.label
percent = window.remainingPercent
isStale = snapshot.isRateLimitsStale
}
diff --git a/CodexBar/Models/TaskGlowPresentationState.swift b/CodexBar/Models/TaskGlowPresentationState.swift
index 1f51031..2fc51f3 100644
--- a/CodexBar/Models/TaskGlowPresentationState.swift
+++ b/CodexBar/Models/TaskGlowPresentationState.swift
@@ -1,5 +1,4 @@
import AppKit
-import QuartzCore
private extension ActivityTerminalEvent {
var glowState: TaskGlowState {
@@ -55,7 +54,7 @@ struct TaskGlowPresentationState {
acceptsBriefEvents: Bool,
now: Date
) {
- let latestEvent = terminalEvents.max { lhs, rhs in
+ let latestTerminalEvent = terminalEvents.max { lhs, rhs in
if lhs.endedAt != rhs.endedAt {
return lhs.endedAt < rhs.endedAt
}
@@ -66,8 +65,8 @@ struct TaskGlowPresentationState {
}
if isEnabled, let enabledAt, acceptsBriefEvents,
snapshot.hasActiveTasks,
- let latestEvent, latestEvent.endedAt >= enabledAt {
- briefEvent = latestEvent
+ let latestTerminalEvent, latestTerminalEvent.endedAt >= enabledAt {
+ briefEvent = latestTerminalEvent
briefExpiration = (suspendedAt ?? now).addingTimeInterval(3)
}
if !isEnabled || !acceptsBriefEvents || !snapshot.hasActiveTasks {
diff --git a/CodexBar/Models/TokenUsage.swift b/CodexBar/Models/TokenUsage.swift
index 6eeb719..3acc4ef 100644
--- a/CodexBar/Models/TokenUsage.swift
+++ b/CodexBar/Models/TokenUsage.swift
@@ -1,5 +1,3 @@
-import Foundation
-
nonisolated struct TokenUsage: Codable, Equatable {
let inputTokens: Int64
let cachedInputTokens: Int64
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 567bcfc..dd081eb 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -54,13 +54,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Waiting for Approval"
+ "value" : "Waiting"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待确认"
+ "value" : "等待中"
}
}
}
@@ -145,6 +145,262 @@
}
}
},
+ "activity.action.assign-subagent" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Assign subagent task"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "分配子 Agent 任务"
+ }
+ }
+ }
+ },
+ "activity.action.call-tool" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Call tool"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "调用工具"
+ }
+ }
+ }
+ },
+ "activity.action.close-subagent" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Close subagent"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "关闭子 Agent"
+ }
+ }
+ }
+ },
+ "activity.action.command" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Run command"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "执行命令"
+ }
+ }
+ }
+ },
+ "activity.action.coordinate-subagents" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Coordinate subagents"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "协调子 Agent"
+ }
+ }
+ }
+ },
+ "activity.action.edit-files" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Edit files"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "修改文件"
+ }
+ }
+ }
+ },
+ "activity.action.generate-image" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Generate image"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "生成图片"
+ }
+ }
+ }
+ },
+ "activity.action.interrupt-subagent" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Interrupt subagent"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "中断子 Agent 任务"
+ }
+ }
+ }
+ },
+ "activity.action.message-subagent" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Message subagent"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "发送子 Agent 消息"
+ }
+ }
+ }
+ },
+ "activity.action.query-subagent" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Check subagent status"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "查询子 Agent 状态"
+ }
+ }
+ }
+ },
+ "activity.action.resume-subagent" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Resume subagent"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "恢复子 Agent 会话"
+ }
+ }
+ }
+ },
+ "activity.action.search-web" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Search web"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "搜索网页"
+ }
+ }
+ }
+ },
+ "activity.action.start-subagent" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Start subagent"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "启动子 Agent"
+ }
+ }
+ }
+ },
+ "activity.action.view-image" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "View image"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "查看图片"
+ }
+ }
+ }
+ },
+ "activity.action.wait-subagent" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Await subagent results"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待子 Agent 结果"
+ }
+ }
+ }
+ },
+ "activity.action.wait-timer" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Wait for timer"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待计时结束"
+ }
+ }
+ }
+ },
"activity.anonymous.keep-awake-exclusion" : {
"localizations" : {
"en" : {
@@ -166,7 +422,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Duration: %@"
+ "value" : "Duration %@"
}
},
"zh-Hans" : {
@@ -177,466 +433,1842 @@
}
}
},
- "activity.duration.running" : {
+ "activity.live.action-completed" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Running for %@"
+ "value" : "%@ completed"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "已运行 %@"
+ "value" : "%@完成"
}
}
}
},
- "activity.duration.waiting" : {
+ "activity.live.action-declined" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Waiting for %@"
+ "value" : "%@ declined"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "已等待 %@"
+ "value" : "%@被拒绝"
}
}
}
},
- "activity.empty.no-activity" : {
+ "activity.live.action-failed" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "No Codex activity"
+ "value" : "%@ failed"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "暂无 Codex 活动"
+ "value" : "%@失败"
}
}
}
},
- "activity.event.compacting-context" : {
+ "activity.live.actions-listFiles" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Compacting context"
+ "value" : "Browsing"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "压缩上下文"
+ "value" : "浏览目录"
}
}
}
},
- "activity.event.context-compaction-completed" : {
+ "activity.live.actions-listFiles-search" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Context compacted"
+ "value" : "Browsing, Searching"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "上下文压缩完成"
+ "value" : "浏览目录, 搜索内容"
}
}
}
},
- "activity.event.finished-using-tool" : {
+ "activity.live.actions-read" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Finished using %@"
+ "value" : "Reading"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "调用工具 %@ 完成"
+ "value" : "读取文件"
}
}
}
},
- "activity.event.finishing" : {
+ "activity.live.actions-read-listFiles" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Finishing up"
+ "value" : "Reading, Browsing"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "即将结束"
+ "value" : "读取文件, 浏览目录"
}
}
}
},
- "activity.event.starting-subagent" : {
+ "activity.live.actions-read-listFiles-search" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Starting subagent"
+ "value" : "Reading, Browsing, Searching"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "启动子智能体"
+ "value" : "读取文件, 浏览目录, 搜索内容"
}
}
}
},
- "activity.event.subagent-completed" : {
+ "activity.live.actions-read-search" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Subagent completed"
+ "value" : "Reading, Searching"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "子智能体完成"
+ "value" : "读取文件, 搜索内容"
}
}
}
},
- "activity.event.thinking" : {
+ "activity.live.actions-search" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Thinking"
+ "value" : "Searching"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "正在思考"
+ "value" : "搜索内容"
}
}
}
},
- "activity.event.tool-completed" : {
+ "activity.live.agent-assigning" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Tool call completed"
+ "value" : "Delegating to subagent"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "调用工具完成"
+ "value" : "正在向子 Agent 分配任务"
}
}
}
},
- "activity.event.using-named-tool" : {
+ "activity.live.agent-closing" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Using %@"
+ "value" : "Closing subagent"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "调用工具 %@"
+ "value" : "正在关闭子 Agent"
}
}
}
},
- "activity.event.using-tool" : {
+ "activity.live.agent-completed" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Using tool"
+ "value" : "Subagent done"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "调用工具"
+ "value" : "子 Agent 任务已完成"
}
}
}
},
- "activity.event.waiting-next-action" : {
+ "activity.live.agent-contacting" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Waiting for the next action"
+ "value" : "Messaging subagent"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待下一步操作"
+ "value" : "正在向子 Agent 发送消息"
}
}
}
},
- "activity.relative.completed-minutes-ago" : {
+ "activity.live.agent-coordinating" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Completed %lld min ago"
+ "value" : "Coordinating subagents"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "%lld 分钟前完成"
+ "value" : "正在协调子 Agent"
}
}
}
},
- "activity.relative.completed-seconds-ago" : {
+ "activity.live.agent-failed" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Completed %lld sec ago"
+ "value" : "Subagent failed"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "%lld 秒前完成"
+ "value" : "子 Agent 任务执行失败"
}
}
}
},
- "activity.relative.just-completed" : {
+ "activity.live.agent-interrupted" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Just completed"
+ "value" : "Subagent interrupted"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "刚刚完成"
+ "value" : "子 Agent 任务已中断"
}
}
}
},
- "activity.relative.just-stopped" : {
+ "activity.live.agent-interrupting" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Just stopped"
+ "value" : "Interrupting subagent"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "刚刚终止"
+ "value" : "正在中断子 Agent 任务"
}
}
}
},
- "activity.relative.stopped-minutes-ago" : {
+ "activity.live.agent-querying" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Stopped %lld min ago"
+ "value" : "Checking subagent status"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "%lld 分钟前终止"
+ "value" : "正在查询子 Agent 状态"
}
}
}
},
- "activity.relative.stopped-seconds-ago" : {
+ "activity.live.agent-resuming" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Stopped %lld sec ago"
+ "value" : "Resuming subagent"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "%lld 秒前终止"
+ "value" : "正在恢复子 Agent 会话"
+ }
+ }
+ }
+ },
+ "activity.live.agent-started" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Subagent started"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "子 Agent 已启动"
}
}
}
},
- "activity.status.codex-completed" : {
+ "activity.live.agent-starting" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex task completed"
+ "value" : "Starting subagent"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 任务已完成"
+ "value" : "正在启动子 Agent"
}
}
}
},
- "activity.status.codex-just-completed" : {
+ "activity.live.agent-waiting" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex just completed"
+ "value" : "Awaiting subagent results"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 刚刚完成"
+ "value" : "正在等待子 Agent 结果"
}
}
}
},
- "activity.status.codex-running" : {
+ "activity.live.answering" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex is running"
+ "value" : "Answering"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 正在运行"
+ "value" : "正在回答"
}
}
}
},
- "activity.status.codex-stopped" : {
+ "activity.live.approval-aborted" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex task stopped"
+ "value" : "Auto-approval aborted"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 任务已终止"
+ "value" : "自动审批已中止"
}
}
}
},
- "activity.status.codex-waiting-for-approval" : {
+ "activity.live.approval-approved" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex is waiting for approval"
+ "value" : "Auto-approved"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自动审批已通过"
+ }
+ }
+ }
+ },
+ "activity.live.approval-denied" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Auto-denied"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自动审批未通过"
+ }
+ }
+ }
+ },
+ "activity.live.approval-timeout" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Auto-approval timed out"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自动审批已超时"
+ }
+ }
+ }
+ },
+ "activity.live.auth-recovery-ended" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Auth recovery ended"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "认证恢复流程已结束"
+ }
+ }
+ }
+ },
+ "activity.live.auto-approval" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Reviewing"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在自动审批"
+ }
+ }
+ }
+ },
+ "activity.live.buffering" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Buffering"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在缓冲回复"
+ }
+ }
+ }
+ },
+ "activity.live.calling-named-tool" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Calling %@"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在调用 %@"
+ }
+ }
+ }
+ },
+ "activity.live.calling-tool" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Calling tool"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在调用工具"
+ }
+ }
+ }
+ },
+ "activity.live.command" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Running command"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在执行命令"
+ }
+ }
+ }
+ },
+ "activity.live.command-listFiles" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Browsing"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在浏览目录"
+ }
+ }
+ }
+ },
+ "activity.live.command-listFiles-search" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Browsing, Searching"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在浏览目录, 搜索内容"
+ }
+ }
+ }
+ },
+ "activity.live.command-read" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Reading"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在读取文件"
+ }
+ }
+ }
+ },
+ "activity.live.command-read-listFiles" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Reading, Browsing"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在读取文件, 浏览目录"
+ }
+ }
+ }
+ },
+ "activity.live.command-read-listFiles-search" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Reading, Browsing, Searching"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在读取文件, 浏览目录, 搜索内容"
+ }
+ }
+ }
+ },
+ "activity.live.command-read-search" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Reading, Searching"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在读取文件, 搜索内容"
+ }
+ }
+ }
+ },
+ "activity.live.command-search" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Searching"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在搜索内容"
+ }
+ }
+ }
+ },
+ "activity.live.command-with-actions" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Running command (%@)"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在执行命令 (%@)"
+ }
+ }
+ }
+ },
+ "activity.live.commentary" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Updating"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在汇报进度"
+ }
+ }
+ }
+ },
+ "activity.live.compacting" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Compacting"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在压缩上下文"
+ }
+ }
+ }
+ },
+ "activity.live.compaction-completed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Context compacted"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "上下文压缩完成"
+ }
+ }
+ }
+ },
+ "activity.live.connecting" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Connecting to Codex"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在连接 Codex 服务"
+ }
+ }
+ }
+ },
+ "activity.live.connecting-tool" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Starting MCP"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在启动 MCP 服务"
+ }
+ }
+ }
+ },
+ "activity.live.diff-updated" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Diff updated"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "改动详情已更新"
+ }
+ }
+ }
+ },
+ "activity.live.editing" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Editing"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在修改文件"
+ }
+ }
+ }
+ },
+ "activity.live.elapsed-running" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Running for"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已运行"
+ }
+ }
+ }
+ },
+ "activity.live.elapsed-waiting" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Waited"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已等待"
+ }
+ }
+ }
+ },
+ "activity.live.environment-connected" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Environment connected"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已连接执行环境"
+ }
+ }
+ }
+ },
+ "activity.live.environment-disconnected" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Environment disconnected"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已断开执行环境连接"
+ }
+ }
+ }
+ },
+ "activity.live.failed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Failed"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "执行失败"
+ }
+ }
+ }
+ },
+ "activity.live.file-completed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "File edits applied"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "文件修改完成"
+ }
+ }
+ }
+ },
+ "activity.live.file-declined" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "File edits declined"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "文件修改被拒绝"
+ }
+ }
+ }
+ },
+ "activity.live.file-failed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "File edits failed"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "文件修改失败"
+ }
+ }
+ }
+ },
+ "activity.live.finding-web" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Finding in page"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在网页查找内容"
+ }
+ }
+ }
+ },
+ "activity.live.generating-image" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Generating image"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在生成图片"
+ }
+ }
+ }
+ },
+ "activity.live.hook-blocked" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Blocked by hook"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "操作被 Hook 拦截"
+ }
+ }
+ }
+ },
+ "activity.live.hook-completed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hook completed"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hook 执行已完成"
+ }
+ }
+ }
+ },
+ "activity.live.hook-failed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hook failed"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hook 执行已失败"
+ }
+ }
+ }
+ },
+ "activity.live.hook-stopped" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hook stopped"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hook 执行已停止"
+ }
+ }
+ }
+ },
+ "activity.live.idle" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "No tasks"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "暂无任务"
+ }
+ }
+ }
+ },
+ "activity.live.image-completed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Image generated"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "图片生成完成"
+ }
+ }
+ }
+ },
+ "activity.live.image-declined" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Image generation declined"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "图片生成被拒绝"
+ }
+ }
+ }
+ },
+ "activity.live.image-failed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Image generation failed"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "图片生成失败"
+ }
+ }
+ }
+ },
+ "activity.live.interrupted" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Interrupted"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已中断"
+ }
+ }
+ }
+ },
+ "activity.live.model-changed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Model switched"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "模型已切换"
+ }
+ }
+ }
+ },
+ "activity.live.model-changed-detail" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Model switched %@"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "模型已切换 %@"
+ }
+ }
+ }
+ },
+ "activity.live.named-tool-completed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ completed"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 执行完成"
+ }
+ }
+ }
+ },
+ "activity.live.named-tool-declined" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ declined"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 调用被拒绝"
+ }
+ }
+ }
+ },
+ "activity.live.named-tool-failed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ failed"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 执行失败"
+ }
+ }
+ }
+ },
+ "activity.live.opening-web" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Opening page"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在打开网页"
+ }
+ }
+ }
+ },
+ "activity.live.plan-progress" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Steps done"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已完成步骤"
+ }
+ }
+ }
+ },
+ "activity.live.plan-step-completed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Plan step done"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "计划步骤已完成"
+ }
+ }
+ }
+ },
+ "activity.live.plan-updated" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Plan updated"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "计划已更新"
+ }
+ }
+ }
+ },
+ "activity.live.planning" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Planning"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在制定计划"
+ }
+ }
+ }
+ },
+ "activity.live.processing" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Processing"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在处理任务"
+ }
+ }
+ }
+ },
+ "activity.live.recent-event" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Latest event"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "最近事件"
+ }
+ }
+ }
+ },
+ "activity.live.reconnecting" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Reconnecting to Codex"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在重新连接 Codex 服务"
+ }
+ }
+ }
+ },
+ "activity.live.recovering-auth" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Recovering auth"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在恢复认证"
+ }
+ }
+ }
+ },
+ "activity.live.recovering-state" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Syncing task state"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在同步任务状态"
+ }
+ }
+ }
+ },
+ "activity.live.replying" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Replying"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在回复"
+ }
+ }
+ }
+ },
+ "activity.live.request-ended" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Request ended"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "用户操作请求已结束"
+ }
+ }
+ }
+ },
+ "activity.live.retrying" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Retrying"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在重试"
+ }
+ }
+ }
+ },
+ "activity.live.review-mode" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Code review"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "代码审查模式"
+ }
+ }
+ }
+ },
+ "activity.live.running" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Running"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "运行中"
+ }
+ }
+ }
+ },
+ "activity.live.running-hook" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Running hook"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在执行 Hook"
+ }
+ }
+ }
+ },
+ "activity.live.searching-web" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Searching web"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在搜索网页"
+ }
+ }
+ }
+ },
+ "activity.live.sleeping" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Waiting for timer"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在等待计时结束"
+ }
+ }
+ }
+ },
+ "activity.live.subagent-count" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld subagents running"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld 个子 Agent 运行中"
+ }
+ }
+ }
+ },
+ "activity.live.thinking" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Thinking"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在思考"
+ }
+ }
+ }
+ },
+ "activity.live.tool-completed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tool call done"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "工具执行完成"
+ }
+ }
+ }
+ },
+ "activity.live.tool-count" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld active tool calls"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld 个工具正在调用"
+ }
+ }
+ }
+ },
+ "activity.live.tool-declined" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tool call declined"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "工具调用被拒绝"
+ }
+ }
+ }
+ },
+ "activity.live.tool-failed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tool call failed"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "工具执行失败"
+ }
+ }
+ }
+ },
+ "activity.live.unavailable" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Task status unavailable"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "暂时无法获取任务状态"
+ }
+ }
+ }
+ },
+ "activity.live.using-web" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Using web tool"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在使用网页工具"
+ }
+ }
+ }
+ },
+ "activity.live.verification-needed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Verification required"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "需要完成验证"
+ }
+ }
+ }
+ },
+ "activity.live.viewing-image" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Viewing image"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在查看图片"
+ }
+ }
+ }
+ },
+ "activity.live.waiting-approval" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Awaiting approval"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待用户审批"
+ }
+ }
+ }
+ },
+ "activity.live.waiting-external" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Awaiting external action"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待外部操作"
+ }
+ }
+ }
+ },
+ "activity.live.waiting-form" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Awaiting info"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待提供信息"
+ }
+ }
+ }
+ },
+ "activity.live.waiting-input" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Awaiting input"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待用户输入"
+ }
+ }
+ }
+ },
+ "activity.live.waiting-service" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Awaiting response"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待回应服务请求"
+ }
+ }
+ }
+ },
+ "activity.live.waiting-user" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Awaiting user action"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待用户操作"
+ }
+ }
+ }
+ },
+ "activity.live.waiting-verification" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Awaiting verification"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待用户验证"
+ }
+ }
+ }
+ },
+ "activity.relative.completed-minutes-ago" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Completed %lld min ago"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld 分钟前完成"
+ }
+ }
+ }
+ },
+ "activity.relative.completed-seconds-ago" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Completed %lld sec ago"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld 秒前完成"
+ }
+ }
+ }
+ },
+ "activity.relative.just-completed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Just completed"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 等待批准"
+ "value" : "刚刚完成"
}
}
}
},
- "activity.status.running" : {
+ "activity.relative.just-stopped" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Running"
+ "value" : "Just stopped"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "正在运行"
+ "value" : "刚刚终止"
}
}
}
},
- "activity.status.waiting-for-approval" : {
+ "activity.relative.stopped-minutes-ago" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Waiting for approval"
+ "value" : "Stopped %lld min ago"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "等待批准"
+ "value" : "%lld 分钟前终止"
}
}
}
},
- "activity.summary.other-task-count" : {
+ "activity.relative.stopped-seconds-ago" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Other tasks: %lld"
+ "value" : "Stopped %lld sec ago"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "另有 %lld 个任务"
+ "value" : "%lld 秒前终止"
}
}
}
},
- "activity.summary.subagent-count" : {
+ "activity.summary.other-task-count" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Subagents: %lld"
+ "value" : "Other tasks: %lld"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "%lld 个子 Agent"
+ "value" : "另有 %lld 个任务"
}
}
}
@@ -961,22 +2593,6 @@
}
}
},
- "codex-status.account.unavailable" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Codex account unavailable"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Codex 账号异常"
- }
- }
- }
- },
"codex-status.app-server.error.connection-closed" : {
"localizations" : {
"en" : {
@@ -1217,22 +2833,6 @@
}
}
},
- "codex.version.newer-installed" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Installed: %@"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "已安装 %@"
- }
- }
- }
- },
"codex.version.parse-failed" : {
"localizations" : {
"en" : {
@@ -1505,22 +3105,6 @@
}
}
},
- "common.status.completed" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Completed"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "完成"
- }
- }
- }
- },
"common.status.copied" : {
"localizations" : {
"en" : {
@@ -2097,22 +3681,6 @@
}
}
},
- "history.rebuild.error.token-history-already-running" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Session data is already being rebuilt"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "会话数据正在重建中"
- }
- }
- }
- },
"history.rebuild.result.completed" : {
"localizations" : {
"en" : {
@@ -2609,22 +4177,6 @@
}
}
},
- "keep-alive.status.active" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "System sleep is currently prevented"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "已防止系统睡眠"
- }
- }
- }
- },
"keep-alive.status.disabled-by-other-source" : {
"localizations" : {
"en" : {
@@ -2705,70 +4257,6 @@
}
}
},
- "log.action.copy-full" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Copy Full %@"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "复制完整%@"
- }
- }
- }
- },
- "log.action.preview-full" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Preview Full %@"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "预览完整%@"
- }
- }
- }
- },
- "log.app-server.error.exit-timeout-killed" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "app-server exit timed out; process killed"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "app-server 退出超时, 已强制结束"
- }
- }
- }
- },
- "log.app-server.error.exit-timeout-running" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "app-server exit timed out; may still be running"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "app-server 退出超时, 可能仍在后台运行"
- }
- }
- }
- },
"log.app-server.error.initialization-failed" : {
"localizations" : {
"en" : {
@@ -2785,70 +4273,6 @@
}
}
},
- "log.app-server.error.launch-failed" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Failed to launch app-server: %@"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "app-server 启动失败: %@"
- }
- }
- }
- },
- "log.app-server.error.response-connection-closed" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Connection closed while waiting for a response"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "连接已断开, 等待响应失败"
- }
- }
- }
- },
- "log.app-server.error.response-timeout" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Response timed out"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "等待响应超时"
- }
- }
- }
- },
- "log.app-server.error.write-connection-closed" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Connection closed; the request could not be sent"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "连接已断开, 无法发送请求"
- }
- }
- }
- },
"log.app-server.window.title" : {
"localizations" : {
"en" : {
@@ -2865,38 +4289,6 @@
}
}
},
- "log.connection.account" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Account"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "账户"
- }
- }
- }
- },
- "log.connection.activity" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Activity"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "活动"
- }
- }
- }
- },
"log.empty.no-entries" : {
"localizations" : {
"en" : {
@@ -3105,22 +4497,6 @@
}
}
},
- "log.status.in-progress" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "In Progress"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "进行中"
- }
- }
- }
- },
"log.status.waiting-response" : {
"localizations" : {
"en" : {
@@ -3590,13 +4966,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex is waiting for approval to use %@"
+ "value" : "Codex needs approval %@"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 正在等待批准使用 %@"
+ "value" : "Codex 等待批准 %@"
}
}
}
@@ -3606,13 +4982,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "A task in \"%@\" is waiting for action approval"
+ "value" : "A task in \"%@\" is waiting for approval to continue"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "「%@」正在等待批准操作"
+ "value" : "「%@」正在等待批准下一步操作"
}
}
}
@@ -3622,13 +4998,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "A task in \"%1$@\" is waiting for approval to use %2$@"
+ "value" : "\"%1$@\" needs approval %2$@"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "「%1$@」正在等待批准 %2$@ 操作"
+ "value" : "「%1$@」等待批准 %2$@"
}
}
}
@@ -3729,22 +5105,6 @@
}
}
},
- "quota.status.remaining" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "%1$@: %2$@ remaining"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "%1$@ 剩余 %2$@"
- }
- }
- }
- },
"quota.value.unlimited" : {
"localizations" : {
"en" : {
@@ -4641,22 +6001,6 @@
}
}
},
- "status-item.activity-summary" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Waiting: %1$lld • Running: %2$lld"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "等待 %1$lld • 运行 %2$lld"
- }
- }
- }
- },
"sync.error.activity-generation" : {
"localizations" : {
"en" : {
diff --git a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift
new file mode 100644
index 0000000..f1b6fe8
--- /dev/null
+++ b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift
@@ -0,0 +1,231 @@
+import Foundation
+
+nonisolated extension ActivityLiveLabel {
+ var text: String {
+ guard let detail, !detail.isEmpty else { return localizedText }
+ switch key {
+ case "action-completed":
+ return String(localized: "activity.live.action-completed", defaultValue: "\(detail)")
+ case "action-failed":
+ return String(localized: "activity.live.action-failed", defaultValue: "\(detail)")
+ case "action-declined":
+ return String(localized: "activity.live.action-declined", defaultValue: "\(detail)")
+ case "tool-completed":
+ return String(localized: "activity.live.named-tool-completed", defaultValue: "\(detail)")
+ case "tool-failed":
+ return String(localized: "activity.live.named-tool-failed", defaultValue: "\(detail)")
+ case "tool-declined":
+ return String(localized: "activity.live.named-tool-declined", defaultValue: "\(detail)")
+ case "calling-tool":
+ return String(localized: "activity.live.calling-named-tool", defaultValue: "\(detail)")
+ case "command":
+ return String(localized: "activity.live.command-with-actions", defaultValue: "\(detail)")
+ case "model-changed":
+ return String(localized: "activity.live.model-changed-detail", defaultValue: "\(detail)")
+ default:
+ return localizedText
+ }
+ }
+
+ /// 完整键名保留为字面量, 供 Xcode 提取和校验本地化文案
+ var localizedText: String {
+ switch key {
+ case "actions-listFiles":
+ String(localized: "activity.live.actions-listFiles")
+ case "actions-listFiles-search":
+ String(localized: "activity.live.actions-listFiles-search")
+ case "actions-read":
+ String(localized: "activity.live.actions-read")
+ case "actions-read-listFiles":
+ String(localized: "activity.live.actions-read-listFiles")
+ case "actions-read-listFiles-search":
+ String(localized: "activity.live.actions-read-listFiles-search")
+ case "actions-read-search":
+ String(localized: "activity.live.actions-read-search")
+ case "actions-search":
+ String(localized: "activity.live.actions-search")
+ case "agent-assigning":
+ String(localized: "activity.live.agent-assigning")
+ case "agent-closing":
+ String(localized: "activity.live.agent-closing")
+ case "agent-completed":
+ String(localized: "activity.live.agent-completed")
+ case "agent-contacting":
+ String(localized: "activity.live.agent-contacting")
+ case "agent-coordinating":
+ String(localized: "activity.live.agent-coordinating")
+ case "agent-failed":
+ String(localized: "activity.live.agent-failed")
+ case "agent-interrupted":
+ String(localized: "activity.live.agent-interrupted")
+ case "agent-interrupting":
+ String(localized: "activity.live.agent-interrupting")
+ case "agent-querying":
+ String(localized: "activity.live.agent-querying")
+ case "agent-resuming":
+ String(localized: "activity.live.agent-resuming")
+ case "agent-started":
+ String(localized: "activity.live.agent-started")
+ case "agent-starting":
+ String(localized: "activity.live.agent-starting")
+ case "agent-waiting":
+ String(localized: "activity.live.agent-waiting")
+ case "answering":
+ String(localized: "activity.live.answering")
+ case "approval-aborted":
+ String(localized: "activity.live.approval-aborted")
+ case "approval-approved":
+ String(localized: "activity.live.approval-approved")
+ case "approval-denied":
+ String(localized: "activity.live.approval-denied")
+ case "approval-timeout":
+ String(localized: "activity.live.approval-timeout")
+ case "auth-recovery-ended":
+ String(localized: "activity.live.auth-recovery-ended")
+ case "auto-approval":
+ String(localized: "activity.live.auto-approval")
+ case "buffering":
+ String(localized: "activity.live.buffering")
+ case "calling-tool":
+ String(localized: "activity.live.calling-tool")
+ case "command":
+ String(localized: "activity.live.command")
+ case "command-listFiles":
+ String(localized: "activity.live.command-listFiles")
+ case "command-listFiles-search":
+ String(localized: "activity.live.command-listFiles-search")
+ case "command-read":
+ String(localized: "activity.live.command-read")
+ case "command-read-listFiles":
+ String(localized: "activity.live.command-read-listFiles")
+ case "command-read-listFiles-search":
+ String(localized: "activity.live.command-read-listFiles-search")
+ case "command-read-search":
+ String(localized: "activity.live.command-read-search")
+ case "command-search":
+ String(localized: "activity.live.command-search")
+ case "commentary":
+ String(localized: "activity.live.commentary")
+ case "compacting":
+ String(localized: "activity.live.compacting")
+ case "compaction-completed":
+ String(localized: "activity.live.compaction-completed")
+ case "connecting":
+ String(localized: "activity.live.connecting")
+ case "connecting-tool":
+ String(localized: "activity.live.connecting-tool")
+ case "diff-updated":
+ String(localized: "activity.live.diff-updated")
+ case "editing":
+ String(localized: "activity.live.editing")
+ case "elapsed-running":
+ String(localized: "activity.live.elapsed-running")
+ case "elapsed-waiting":
+ String(localized: "activity.live.elapsed-waiting")
+ case "environment-connected":
+ String(localized: "activity.live.environment-connected")
+ case "environment-disconnected":
+ String(localized: "activity.live.environment-disconnected")
+ case "failed":
+ String(localized: "activity.live.failed")
+ case "file-completed":
+ String(localized: "activity.live.file-completed")
+ case "file-declined":
+ String(localized: "activity.live.file-declined")
+ case "file-failed":
+ String(localized: "activity.live.file-failed")
+ case "finding-web":
+ String(localized: "activity.live.finding-web")
+ case "generating-image":
+ String(localized: "activity.live.generating-image")
+ case "hook-blocked":
+ String(localized: "activity.live.hook-blocked")
+ case "hook-completed":
+ String(localized: "activity.live.hook-completed")
+ case "hook-failed":
+ String(localized: "activity.live.hook-failed")
+ case "hook-stopped":
+ String(localized: "activity.live.hook-stopped")
+ case "idle":
+ String(localized: "activity.live.idle")
+ case "image-completed":
+ String(localized: "activity.live.image-completed")
+ case "image-declined":
+ String(localized: "activity.live.image-declined")
+ case "image-failed":
+ String(localized: "activity.live.image-failed")
+ case "interrupted":
+ String(localized: "activity.live.interrupted")
+ case "model-changed":
+ String(localized: "activity.live.model-changed")
+ case "opening-web":
+ String(localized: "activity.live.opening-web")
+ case "plan-progress":
+ String(localized: "activity.live.plan-progress")
+ case "plan-step-completed":
+ String(localized: "activity.live.plan-step-completed")
+ case "plan-updated":
+ String(localized: "activity.live.plan-updated")
+ case "planning":
+ String(localized: "activity.live.planning")
+ case "processing":
+ String(localized: "activity.live.processing")
+ case "recent-event":
+ String(localized: "activity.live.recent-event")
+ case "reconnecting":
+ String(localized: "activity.live.reconnecting")
+ case "recovering-auth":
+ String(localized: "activity.live.recovering-auth")
+ case "recovering-state":
+ String(localized: "activity.live.recovering-state")
+ case "replying":
+ String(localized: "activity.live.replying")
+ case "request-ended":
+ String(localized: "activity.live.request-ended")
+ case "retrying":
+ String(localized: "activity.live.retrying")
+ case "review-mode":
+ String(localized: "activity.live.review-mode")
+ case "running":
+ String(localized: "activity.live.running")
+ case "running-hook":
+ String(localized: "activity.live.running-hook")
+ case "searching-web":
+ String(localized: "activity.live.searching-web")
+ case "sleeping":
+ String(localized: "activity.live.sleeping")
+ case "thinking":
+ String(localized: "activity.live.thinking")
+ case "tool-completed", "action-completed":
+ String(localized: "activity.live.tool-completed")
+ case "tool-declined", "action-declined":
+ String(localized: "activity.live.tool-declined")
+ case "tool-failed", "action-failed":
+ String(localized: "activity.live.tool-failed")
+ case "unavailable":
+ String(localized: "activity.live.unavailable")
+ case "using-web":
+ String(localized: "activity.live.using-web")
+ case "verification-needed":
+ String(localized: "activity.live.verification-needed")
+ case "viewing-image":
+ String(localized: "activity.live.viewing-image")
+ case "waiting-approval":
+ String(localized: "activity.live.waiting-approval")
+ case "waiting-external":
+ String(localized: "activity.live.waiting-external")
+ case "waiting-form":
+ String(localized: "activity.live.waiting-form")
+ case "waiting-input":
+ String(localized: "activity.live.waiting-input")
+ case "waiting-service":
+ String(localized: "activity.live.waiting-service")
+ case "waiting-user":
+ String(localized: "activity.live.waiting-user")
+ case "waiting-verification":
+ String(localized: "activity.live.waiting-verification")
+ default:
+ String(localized: "activity.live.processing")
+ }
+ }
+}
diff --git a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift
new file mode 100644
index 0000000..8c862d1
--- /dev/null
+++ b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift
@@ -0,0 +1,171 @@
+import Foundation
+
+nonisolated extension ActivityItem {
+ var liveLabel: ActivityLiveLabel? {
+ switch type {
+ case "reasoning": ActivityLiveLabel("thinking")
+ case "agentMessage":
+ ActivityLiveLabel(phase == "final_answer" ? "answering" : phase == "commentary" ? "commentary" : "replying")
+ case "plan": ActivityLiveLabel("planning")
+ case "contextCompaction": ActivityLiveLabel("compacting")
+ case "commandExecution": commandLabel
+ case "fileChange": ActivityLiveLabel("editing")
+ case "webSearch": ActivityLiveLabel(webLabel)
+ case "imageView": ActivityLiveLabel("viewing-image")
+ case "imageGeneration": ActivityLiveLabel("generating-image")
+ case "sleep": ActivityLiveLabel("sleeping")
+ case "collabAgentToolCall": ActivityLiveLabel(ActivityDisplayFormat.agentAction(tool: tool).statusKey)
+ case "mcpToolCall", "dynamicToolCall": ActivityLiveLabel("calling-tool", detail: tool)
+ default: nil
+ }
+ }
+
+ private var commandLabel: ActivityLiveLabel {
+ let types = Set((commandActions ?? []).map(\.type))
+ let actions = orderedCommandActions
+ guard !actions.isEmpty else { return ActivityLiveLabel("command") }
+ let key = "command-" + actions.joined(separator: "-")
+ if types.isSubset(of: Set(actions)) {
+ return ActivityLiveLabel(key)
+ }
+ return ActivityLiveLabel("command", detail: commandActionDetail)
+ }
+
+ private var orderedCommandActions: [String] {
+ ActivityDisplayFormat.orderedCommandActions((commandActions ?? []).map(\.type))
+ }
+
+ private var commandActionDetail: String? {
+ ActivityDisplayFormat.commandActionText((commandActions ?? []).map(\.type))
+ }
+
+ private var webLabel: String {
+ switch action?.type {
+ case "search": "searching-web"
+ case "openPage": "opening-web"
+ case "findInPage": "finding-web"
+ default: "using-web"
+ }
+ }
+
+ var liveCompletionLabel: ActivityLiveLabel? {
+ if type == "subAgentActivity" {
+ return ["started": "agent-started", "completed": "agent-completed", "interrupted": "agent-interrupted"][kind ?? ""]
+ .map { ActivityLiveLabel($0) }
+ }
+ if type == "contextCompaction" {
+ return ActivityLiveLabel("compaction-completed")
+ }
+ if type == "collabAgentToolCall", agentsStates?.values.contains(where: { $0.status == "errored" }) == true {
+ return ActivityLiveLabel("agent-failed")
+ }
+ guard isToolCall else { return nil }
+ let prefix = type == "fileChange" ? "file" : type == "imageGeneration" ? "image" : "tool"
+ let outcome: String
+ if status == "declined" {
+ outcome = "declined"
+ } else if status == "failed" || success == false {
+ outcome = "failed"
+ } else if status == "completed" || success == true || ["webSearch", "imageView", "sleep"].contains(type) {
+ outcome = "completed"
+ } else {
+ return nil
+ }
+ let detail = switch type {
+ case "commandExecution": commandActionDetail
+ case "collabAgentToolCall": String(localized: ActivityDisplayFormat.agentAction(tool: tool).action)
+ default: toolDisplayName
+ }
+ if detail != nil, type == "commandExecution" || type == "collabAgentToolCall" {
+ return ActivityLiveLabel("action-" + outcome, detail: detail)
+ }
+ return ActivityLiveLabel(prefix + "-" + outcome, detail: prefix == "tool" ? detail : nil)
+ }
+}
+
+nonisolated extension ActivityDisplayFormat {
+ static func orderedCommandActions(_ types: [String]) -> [String] {
+ let types = Set(types)
+ return ["read", "listFiles", "search"].filter { types.contains($0) }
+ }
+
+ static func commandActionText(_ types: [String]) -> String? {
+ let actions = orderedCommandActions(types)
+ guard !actions.isEmpty else { return nil }
+ return ActivityLiveLabel("actions-" + actions.joined(separator: "-")).text
+ }
+
+ static func agentAction(tool: String?) -> (statusKey: String, action: LocalizedStringResource) {
+ switch tool {
+ case "spawnAgent": ("agent-starting", "activity.action.start-subagent")
+ case "sendInput", "followupTask": ("agent-assigning", "activity.action.assign-subagent")
+ case "sendMessage": ("agent-contacting", "activity.action.message-subagent")
+ case "resumeAgent": ("agent-resuming", "activity.action.resume-subagent")
+ case "wait": ("agent-waiting", "activity.action.wait-subagent")
+ case "interruptAgent": ("agent-interrupting", "activity.action.interrupt-subagent")
+ case "closeAgent": ("agent-closing", "activity.action.close-subagent")
+ case "listAgents": ("agent-querying", "activity.action.query-subagent")
+ default: ("agent-coordinating", "activity.action.coordinate-subagents")
+ }
+ }
+
+ static func toolActionText(itemType: String?, toolName: String?) -> String? {
+ if itemType == "commandExecution" {
+ // 历史事件的 tool 字段保存分类组合, 仅在类型明确时按该格式读取
+ let actions = toolName?.split(separator: "/").map(String.init) ?? []
+ return commandActionText(actions) ?? String(localized: "activity.action.command")
+ }
+ if itemType == "collabAgentToolCall" {
+ return String(localized: agentAction(tool: toolName).action)
+ }
+ if let toolName, !toolName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return toolName
+ }
+ switch itemType {
+ case "fileChange": return String(localized: "activity.action.edit-files")
+ case "webSearch": return String(localized: "activity.action.search-web")
+ case "imageView": return String(localized: "activity.action.view-image")
+ case "imageGeneration": return String(localized: "activity.action.generate-image")
+ case "sleep": return String(localized: "activity.action.wait-timer")
+ case "mcpToolCall", "dynamicToolCall": return String(localized: "activity.action.call-tool")
+ default: return nil
+ }
+ }
+
+ static func liveSummaryComponents(for task: ActivityTaskSnapshot, now: Date, waiting: Bool = false) -> [String] {
+ let live = task.presentation
+ let running = if task.showsPreciseDuration, let started = task.startedAt {
+ ActivityLiveLabel("elapsed-running").text + " " + CodexDurationFormat.activityText(for: now.timeIntervalSince(started))
+ } else {
+ ActivityLiveLabel("running").text
+ }
+ let waitStart = live?.waiting?.since
+ let waitingDuration = waitStart.map {
+ ActivityLiveLabel("elapsed-waiting").text + " " + CodexDurationFormat.activityText(for: now.timeIntervalSince($0))
+ }
+ // 等待起点缺失时只展示等待事实, 不把订阅连接的时间当成请求开始时间
+ if waiting || live?.waiting != nil {
+ return [running, waitingDuration ?? ActivityLiveLabel("waiting-user").text]
+ }
+ let extra: String? = if let count = task.activeSubagentCount, count > 0 {
+ String(localized: "activity.live.subagent-count", defaultValue: "\(count, specifier: "%lld")")
+ } else if let count = live?.toolCount, count > 1 {
+ String(localized: "activity.live.tool-count", defaultValue: "\(count, specifier: "%lld")")
+ } else if let total = live?.planTotal, total > 0, let completed = live?.planCompleted {
+ ActivityLiveLabel("plan-progress").text + " \(completed)/\(total)"
+ } else if live?.isReviewing == true {
+ ActivityLiveLabel("review-mode").text
+ } else {
+ nil
+ }
+ return [running] + (extra.map { [$0] } ?? [])
+ }
+
+ static func liveStatus(for task: ActivityTaskSnapshot, waiting: Bool) -> String {
+ task.presentation?.current.text ?? ActivityLiveLabel(waiting ? "waiting-approval" : "processing").text
+ }
+
+ static func recentEvent(for task: ActivityTaskSnapshot) -> String? {
+ task.presentation?.recent.map { ActivityLiveLabel("recent-event").text + ": " + $0.label.text }
+ }
+}
diff --git a/CodexBar/Services/Activity/ActivityLivePresentation.swift b/CodexBar/Services/Activity/ActivityLivePresentation.swift
new file mode 100644
index 0000000..51c271d
--- /dev/null
+++ b/CodexBar/Services/Activity/ActivityLivePresentation.swift
@@ -0,0 +1,315 @@
+import Foundation
+
+/// 只解码展示所需的协议元数据, 不保留回答, 命令, 路径, 表单或认证正文
+nonisolated struct ActivityLivePayload: Decodable {
+ var threadId: String?
+ var turnId: String?
+ var reviewId: String?
+ var targetItemId: String?
+ var mode: String?
+ var isBlocking: Bool?
+ var plan: [Status]?
+ var review: Status?
+ var run: Hook?
+ var status: String?
+ var server: String?
+ var name: String?
+ var showBufferingUi: Bool?
+ var willRetry: Bool?
+ var fromModel: String?
+ var toModel: String?
+ var verifications: [String]?
+
+ struct Status: Decodable { var status: String? }
+ struct Hook: Decodable {
+ let id: String
+ var status: String?
+ var executionMode: String?
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case threadId, turnId, reviewId, targetItemId, mode, isBlocking, plan, review, run, status, server, name
+ case showBufferingUi, willRetry, fromModel, toModel, verifications
+ }
+
+ init(from decoder: Decoder) throws {
+ let values = try decoder.container(keyedBy: CodingKeys.self)
+ threadId = try values.decodeIfPresent(String.self, forKey: .threadId)
+ turnId = try values.decodeIfPresent(String.self, forKey: .turnId)
+ reviewId = try values.decodeIfPresent(String.self, forKey: .reviewId)
+ targetItemId = try values.decodeIfPresent(String.self, forKey: .targetItemId)
+ mode = try values.decodeIfPresent(String.self, forKey: .mode)
+ isBlocking = try values.decodeIfPresent(Bool.self, forKey: .isBlocking)
+ plan = try values.decodeIfPresent([Status].self, forKey: .plan)
+ review = try values.decodeIfPresent(Status.self, forKey: .review)
+ run = try values.decodeIfPresent(Hook.self, forKey: .run)
+ // thread/status/changed 使用对象, MCP 启动状态使用字符串
+ status = try? values.decode(String.self, forKey: .status)
+ server = try values.decodeIfPresent(String.self, forKey: .server)
+ name = try values.decodeIfPresent(String.self, forKey: .name)
+ showBufferingUi = try values.decodeIfPresent(Bool.self, forKey: .showBufferingUi)
+ willRetry = try values.decodeIfPresent(Bool.self, forKey: .willRetry)
+ fromModel = try values.decodeIfPresent(String.self, forKey: .fromModel)
+ toModel = try values.decodeIfPresent(String.self, forKey: .toModel)
+ verifications = try values.decodeIfPresent([String].self, forKey: .verifications)
+ }
+}
+
+nonisolated struct ActivityLiveLabel: Equatable {
+ let key: String
+ var detail: String?
+
+ init(_ key: String, detail: String? = nil) {
+ self.key = key
+ self.detail = detail.map { String($0.prefix(160)) }
+ }
+}
+
+nonisolated struct ActivityLiveEvent: Equatable {
+ let label: ActivityLiveLabel
+ let at: Date
+}
+
+nonisolated struct ActivityLiveWait: Equatable {
+ let label: ActivityLiveLabel
+ let since: Date?
+}
+
+nonisolated struct ActivityLiveSummary: Equatable {
+ var current: ActivityLiveLabel
+ var waiting: ActivityLiveWait?
+ var recent: ActivityLiveEvent?
+ var toolCount: Int?
+ var planCompleted: Int?
+ var planTotal: Int?
+ var isReviewing = false
+ var updatedAt: Date = .distantPast
+}
+
+/// 与历史统计和审批策略独立的内存状态, 连接失效时整体丢弃
+nonisolated struct ActivityLivePresentation {
+ struct Entry {
+ let label: ActivityLiveLabel
+ let at: Date
+ var isTool = false
+ }
+
+ private var items: [String: Entry] = [:]
+ private var operations: [String: Entry] = [:]
+ private(set) var requests: [String: ActivityLiveWait] = [:]
+ private var flagWait: ActivityLiveWait?
+ private var phase = Entry(label: ActivityLiveLabel("processing"), at: .distantPast)
+ private var phaseItemID: String?
+ private var recent: ActivityLiveEvent?
+ private var planCompleted: Int?
+ private var planTotal: Int?
+ private var isReviewing = false
+ private var inventoryKnown = false
+
+ var summary: ActivityLiveSummary {
+ let waiting = requests.min { lhs, rhs in
+ let left = lhs.value.since ?? .distantFuture
+ let right = rhs.value.since ?? .distantFuture
+ return left == right ? lhs.key < rhs.key : left < right
+ }?.value ?? flagWait
+ let current = operations.values.max { $0.at < $1.at }
+ ?? (Array(items.values) + [phase]).max { $0.at < $1.at } ?? phase
+ return ActivityLiveSummary(
+ current: waiting?.label ?? current.label, waiting: waiting, recent: recent,
+ toolCount: inventoryKnown ? items.values.filter(\.isTool).count : nil,
+ planCompleted: planCompleted, planTotal: planTotal, isReviewing: isReviewing, updatedAt: current.at
+ )
+ }
+
+ mutating func reconcile(status: ActivityThreadStatus?, observedAt: Date? = nil) {
+ guard let status, ["active", "idle"].contains(status.type) else { return }
+ guard let flags = status.type == "idle" ? [] : status.activeFlags else { return }
+ let label: ActivityLiveLabel? = if flags.contains("waitingOnApproval") {
+ ActivityLiveLabel("waiting-approval")
+ } else if flags.contains("waitingOnUserInput") {
+ ActivityLiveLabel("waiting-input")
+ } else {
+ nil
+ }
+ if let label {
+ flagWait = ActivityLiveWait(label: label, since: flagWait?.since ?? observedAt)
+ } else {
+ flagWait = nil
+ requests.removeAll()
+ }
+ }
+
+ mutating func consume(_ notification: ActivityNotification, at date: Date) {
+ let params = notification.params
+ switch notification.method {
+ case "turn/started":
+ inventoryKnown = true
+ case "thread/status/changed":
+ reconcile(status: params.status, observedAt: date)
+ case "item/started", "item/completed":
+ if let item = params.item {
+ consume(item, starting: notification.method == "item/started", at: date)
+ }
+ case "item/agentMessage/delta", "item/plan/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta":
+ let label = if notification.method == "item/agentMessage/delta" {
+ params.itemId.flatMap { items[$0]?.label } ?? ActivityLiveLabel("replying")
+ } else {
+ ActivityLiveLabel(notification.method == "item/plan/delta" ? "planning" : "thinking")
+ }
+ phase = Entry(label: label, at: date)
+ phaseItemID = params.itemId
+ operations.removeValue(forKey: "retry")
+ case "item/commandExecution/outputDelta", "item/fileChange/outputDelta":
+ if let id = params.itemId {
+ // 中途接入可能没有 started, 输出类型足以恢复通用状态, 但不能补全工具清单
+ let label = items[id]?.label ?? ActivityLiveLabel(notification.method == "item/commandExecution/outputDelta" ? "command" : "editing")
+ items[id] = Entry(label: label, at: date, isTool: true)
+ }
+ case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval",
+ "item/tool/requestUserInput", "mcpServer/elicitation/request":
+ consumeRequest(notification, at: date)
+ case "serverRequest/resolved":
+ if let id = params.requestId?.identifier, requests.removeValue(forKey: id) != nil {
+ record("request-ended", at: date)
+ if requests.isEmpty {
+ flagWait = nil
+ }
+ }
+ default:
+ consumeSupplement(notification, at: date)
+ }
+ boundStorage()
+ }
+
+ private mutating func consumeRequest(_ notification: ActivityNotification, at date: Date) {
+ guard let id = notification.id?.identifier else { return }
+ let key: String
+ switch notification.method {
+ case "item/tool/requestUserInput":
+ guard notification.live.isBlocking == true else { return }
+ key = "waiting-input"
+ case "mcpServer/elicitation/request":
+ key = switch notification.live.mode {
+ case "form", "openai/form", "openaiForm": "waiting-form"
+ case "url": "waiting-external"
+ case "openai/userVerification": "waiting-verification"
+ default: "waiting-service"
+ }
+ default:
+ key = "waiting-approval"
+ }
+ requests[id] = requests[id] ?? ActivityLiveWait(label: ActivityLiveLabel(key), since: date)
+ }
+
+ private mutating func consume(_ item: ActivityItem, starting: Bool, at date: Date) {
+ if item.type == "enteredReviewMode" {
+ isReviewing = true
+ }
+ if item.type == "exitedReviewMode" {
+ isReviewing = false
+ }
+ if starting, let label = item.liveLabel {
+ items[item.id] = Entry(label: label, at: date, isTool: item.isToolCall)
+ operations.removeValue(forKey: "retry")
+ } else if !starting {
+ let removed = items.removeValue(forKey: item.id)
+ // 完成是最近事件, 不能覆盖已经到达的回答增量
+ if phaseItemID == item.id || removed.map({ phase.at <= $0.at }) == true {
+ phase = Entry(label: ActivityLiveLabel("processing"), at: items.isEmpty ? date : .distantPast)
+ phaseItemID = nil
+ }
+ if let label = item.liveCompletionLabel {
+ recent = ActivityLiveEvent(label: label, at: date)
+ }
+ }
+ }
+
+ private mutating func consumeSupplement(_ notification: ActivityNotification, at date: Date) {
+ let live = notification.live
+ switch notification.method {
+ case "turn/plan/updated":
+ guard let plan = live.plan else { return }
+ let completed = plan.filter { $0.status == "completed" }.count
+ record(completed > (planCompleted ?? completed) ? "plan-step-completed" : "plan-updated", at: date)
+ planCompleted = completed
+ planTotal = plan.count
+ case "turn/diff/updated": record("diff-updated", at: date)
+ case "model/rerouted":
+ let detail = [live.fromModel, live.toModel].compactMap(\.self).joined(separator: " → ")
+ record("model-changed", detail: detail.isEmpty ? nil : detail, at: date)
+ case "model/verification":
+ if live.verifications?.isEmpty == false {
+ record("verification-needed", at: date)
+ }
+ case "thread/environment/connected": record("environment-connected", at: date)
+ case "thread/environment/disconnected": record("environment-disconnected", at: date)
+ case "error":
+ setOperation("retry", label: "retrying", active: live.willRetry == true, at: date)
+ case "modelProvider/authRecoveryStarted":
+ setOperation("auth", label: "recovering-auth", active: true, at: date)
+ case "modelProvider/authRecoveryCompleted":
+ setOperation("auth", label: "recovering-auth", active: false, at: date)
+ record("auth-recovery-ended", at: date)
+ case "model/safetyBuffering/updated":
+ setOperation("buffer", label: "buffering", active: live.showBufferingUi == true, at: date)
+ case "mcpServer/startupStatus/updated":
+ if let name = live.name ?? live.server {
+ setOperation("mcp:" + name, label: "connecting-tool", active: live.status == "starting", at: date)
+ }
+ case "item/autoApprovalReview/started", "item/autoApprovalReview/completed":
+ consumeReview(notification, at: date)
+ case "hook/started", "hook/completed":
+ consumeHook(notification, at: date)
+ default: break
+ }
+ }
+
+ private mutating func consumeReview(_ notification: ActivityNotification, at date: Date) {
+ guard let id = notification.params.reviewId ?? notification.params.targetItemId else { return }
+ let starting = notification.method == "item/autoApprovalReview/started"
+ setOperation("review:" + id, label: "auto-approval", active: starting, at: date)
+ let outcomes = ["approved": "approval-approved", "denied": "approval-denied", "timedOut": "approval-timeout", "aborted": "approval-aborted"]
+ if !starting, let status = notification.live.review?.status, let key = outcomes[status] {
+ record(key, at: date)
+ }
+ }
+
+ private mutating func consumeHook(_ notification: ActivityNotification, at date: Date) {
+ guard let run = notification.live.run else { return }
+ let starting = notification.method == "hook/started"
+ if !starting || run.executionMode == "sync" {
+ setOperation("hook:" + run.id, label: "running-hook", active: starting, at: date)
+ }
+ let outcomes = ["completed": "hook-completed", "failed": "hook-failed", "blocked": "hook-blocked", "stopped": "hook-stopped"]
+ if !starting, let status = run.status, let key = outcomes[status] {
+ record(key, at: date)
+ }
+ }
+
+ private mutating func setOperation(_ id: String, label: String, active: Bool, at date: Date) {
+ if active {
+ operations[id] = Entry(label: ActivityLiveLabel(label), at: date)
+ } else {
+ operations.removeValue(forKey: id)
+ }
+ }
+
+ private mutating func record(_ key: String, detail: String? = nil, at date: Date) {
+ recent = ActivityLiveEvent(label: ActivityLiveLabel(key, detail: detail), at: date)
+ }
+
+ private mutating func boundStorage() {
+ // 异常服务端不能通过无限未结束的 item 或 request 扩大内存
+ if items.count > 128 {
+ items = Dictionary(uniqueKeysWithValues: items.sorted { $0.value.at > $1.value.at }.prefix(128).map { ($0.key, $0.value) })
+ inventoryKnown = false
+ }
+ if operations.count > 128 {
+ operations = Dictionary(uniqueKeysWithValues: operations.sorted { $0.value.at > $1.value.at }.prefix(128).map { ($0.key, $0.value) })
+ }
+ if requests.count > 128 {
+ flagWait = ActivityLiveWait(label: ActivityLiveLabel("waiting-user"), since: nil)
+ requests = Dictionary(uniqueKeysWithValues: requests.sorted { $0.key < $1.key }.prefix(128).map { ($0.key, $0.value) })
+ }
+ }
+}
diff --git a/CodexBar/Services/Activity/ActivityMonitor+Completion.swift b/CodexBar/Services/Activity/ActivityMonitor+Completion.swift
index 1b615ee..b2f6622 100644
--- a/CodexBar/Services/Activity/ActivityMonitor+Completion.swift
+++ b/CodexBar/Services/Activity/ActivityMonitor+Completion.swift
@@ -46,7 +46,8 @@ extension ActivityMonitor {
effort: event.effort ?? task?.effort,
terminatedAt: event.timestamp,
duration: event.source == nil || event.source?.turnCompletedAt != nil ? task?.preciseDuration(until: event.timestamp) : nil,
- task: task
+ task: task,
+ isFailure: event.source?.turnStatus == "failed"
)
recordTerminalPresentationEvent(.terminated(termination))
recordEndedTask(key, at: event.timestamp)
@@ -142,6 +143,9 @@ extension ActivityMonitor {
into task: inout ActivityTask
) -> Bool {
var didChange = false
+ if state.readStatus == .complete, let status = state.turnStatus {
+ task.terminalFailed = status == "failed"
+ }
if let startedAt = backfilledStartedAt(for: task, state: state) {
task.startedAt = startedAt
didChange = true
@@ -203,7 +207,8 @@ extension ActivityMonitor {
effort: String?,
terminatedAt: Date,
duration: TimeInterval?,
- task: ActivityTask? = nil
+ task: ActivityTask? = nil,
+ isFailure: Bool = false
) -> ActivityTermination {
let termination = ActivityTermination(
id: UUID(),
@@ -212,7 +217,8 @@ extension ActivityMonitor {
modelName: modelName,
effort: effort,
terminatedAt: terminatedAt,
- duration: duration
+ duration: duration,
+ isFailure: isFailure || task?.terminalFailed == true
)
terminations.append(termination)
terminalTaskKeyByID[termination.id] = key
diff --git a/CodexBar/Services/Activity/ActivityMonitor+Subagents.swift b/CodexBar/Services/Activity/ActivityMonitor+Subagents.swift
index 565d186..b7f6247 100644
--- a/CodexBar/Services/Activity/ActivityMonitor+Subagents.swift
+++ b/CodexBar/Services/Activity/ActivityMonitor+Subagents.swift
@@ -51,7 +51,6 @@ extension ActivityMonitor {
into transitions: inout [ActivityTransition]
) -> Bool {
guard state.readStatus == .complete,
- state.recordedThreadID == state.requestedThreadID,
let rootTurnID = state.rootTurnID,
let parentThreadID = state.parentThreadID, parentThreadID != state.requestedThreadID else { return false }
let reference = ActivityTurnReference(threadID: state.requestedThreadID, turnID: state.turnID, startedAt: state.startedAt ?? Date())
@@ -76,7 +75,6 @@ extension ActivityMonitor {
if wasRunning != isRunning {
let observedAt = state.lastProgressAt ?? state.startedAt ?? Date()
task.recordSubagentActivity(agentID: state.requestedThreadID, isStarting: isRunning, at: observedAt)
- task.latestEvent = isRunning ? .subagentStarted : .subagentFinished
}
_ = resolvePendingApprovalIfPossible(for: &task, into: &transitions)
if !terminalOnly {
diff --git a/CodexBar/Services/Activity/ActivityMonitor+Tokens.swift b/CodexBar/Services/Activity/ActivityMonitor+Tokens.swift
index 73905b7..0bf210e 100644
--- a/CodexBar/Services/Activity/ActivityMonitor+Tokens.swift
+++ b/CodexBar/Services/Activity/ActivityMonitor+Tokens.swift
@@ -13,9 +13,9 @@ struct TaskTokenRequest {
var total: TokenUsage?
for reference in references {
guard let state = states.first(where: { $0.requestedThreadID == reference.threadID && $0.turnID == reference.turnID }),
- state.readStatus == .complete, state.recordedThreadID == reference.threadID,
+ state.readStatus == .complete,
state.rootTurnID == root.turnID,
- (state.rootSessionID ?? state.recordedThreadID) == root.threadID,
+ (state.rootSessionID ?? state.requestedThreadID) == root.threadID,
!requiresFinalUsage || reference == root || state.terminal != nil,
let usage = state.tokenUsage else {
if requiresFinalUsage {
@@ -101,11 +101,7 @@ extension ActivityMonitor {
terminalTokenUsageRequests[id] = request
references.formUnion(request.references)
}
- return references.map {
- var reference = $0
- reference.isTerminalUsageOnly = true
- return reference
- }
+ return Array(references)
}
@discardableResult
diff --git a/CodexBar/Services/Activity/ActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swift
index bc50a40..2f60330 100644
--- a/CodexBar/Services/Activity/ActivityMonitor.swift
+++ b/CodexBar/Services/Activity/ActivityMonitor.swift
@@ -57,6 +57,8 @@ final class ActivityMonitor: ObservableObject {
private var isProtectionStateLoaded = false
var isProtectionEnabled = false
@Published var isActivitySourceHealthy = false
+ @Published private(set) var sourcePresentation: ActivityLiveLabel? = ActivityLiveLabel("unavailable")
+ private var hasConnectedActivitySource = false
private var unavailableTurns = Set<ActivityTaskKey>()
var isProtectionRecoveryInProgress = false
var protectionRecoveryGeneration: UInt64 = 0
@@ -215,6 +217,7 @@ final class ActivityMonitor: ObservableObject {
sessionLifecyclePollTask?.cancel()
sessionLifecyclePollTask = nil
cancelInactivityCheck()
+ sourcePresentation = ActivityLiveLabel("unavailable")
isActivitySourceHealthy = false
cleanupTask?.cancel()
cleanupTask = nil
@@ -500,6 +503,7 @@ final class ActivityMonitor: ObservableObject {
case .lifecycleChanged:
refreshSessionLifecycleNow()
case .bootstrapStart:
+ sourcePresentation = ActivityLiveLabel(hasConnectedActivitySource ? "reconnecting" : "connecting")
recoveryTask?.cancel()
recoveryTask = nil
// 重试会重新查询初始快照, 计时从第一次开始算才是用户等到的总时长
@@ -515,11 +519,14 @@ final class ActivityMonitor: ObservableObject {
clearCollectedActivityState()
publishSnapshot(.empty)
case let .bootstrapEvents(events):
+ sourcePresentation = ActivityLiveLabel("recovering-state")
bootstrapEventCount += events.count
for event in events {
_ = apply(event, source: .bootstrap)
}
case .bootstrapEnd:
+ sourcePresentation = ActivityLiveLabel("recovering-state")
+ hasConnectedActivitySource = true
isActivitySourceHealthy = true
sessionTransitionNotBefore = Date()
let completionGeneration = bootstrapCompletionGeneration
@@ -557,6 +564,7 @@ final class ActivityMonitor: ObservableObject {
refreshSessionLifecycleNow()
}
case .sourceUnavailable:
+ sourcePresentation = ActivityLiveLabel("unavailable")
guard isActivitySourceHealthy else {
return
}
@@ -598,6 +606,7 @@ final class ActivityMonitor: ObservableObject {
}
resetTerminalPresentationEvents()
isBootstrapping = false
+ sourcePresentation = isActivitySourceHealthy ? nil : ActivityLiveLabel("unavailable")
if isActivitySourceHealthy, !isSystemSleeping {
if recoveryGeneration == protectionRecoveryGeneration {
finishProtectionRecovery(generation: recoveryGeneration)
@@ -637,31 +646,9 @@ final class ActivityMonitor: ObservableObject {
case .turnStarted:
guard isTopLevelEvent else { return nil }
startTask(from: event, source: source)
- case .toolStarted:
+ case .toolStarted, .toolCompleted, .compactionStarted, .compactionCompleted:
resumeTask(
from: event,
- latestEvent: .toolStarted,
- allowsRecovery: isTopLevelEvent,
- source: source
- )
- case .toolCompleted:
- resumeTask(
- from: event,
- latestEvent: .toolFinished,
- allowsRecovery: isTopLevelEvent,
- source: source
- )
- case .compactionStarted:
- resumeTask(
- from: event,
- latestEvent: .compactionStarted,
- allowsRecovery: isTopLevelEvent,
- source: source
- )
- case .compactionCompleted:
- resumeTask(
- from: event,
- latestEvent: .compactionFinished,
allowsRecovery: isTopLevelEvent,
source: source
)
@@ -771,7 +758,6 @@ final class ActivityMonitor: ObservableObject {
key: key,
event: event,
state: .running,
- latestEvent: .promptSubmitted,
startedAt: event.timestamp,
progressGeneration: (existingTask?.progressGeneration ?? 0) &+ 1
)
@@ -781,7 +767,6 @@ final class ActivityMonitor: ObservableObject {
private func resumeTask(
from event: ActivityRecord,
- latestEvent: ActivityPhase,
allowsRecovery: Bool,
source: ActivityEventSource
) {
@@ -800,7 +785,7 @@ final class ActivityMonitor: ObservableObject {
}
let wasSuppressed = task.state == .suppressed
- task.resumeExecution(from: event, latestEvent: latestEvent)
+ task.resumeExecution(from: event)
task.mergeMetadata(from: event)
task.recordEvent(at: event.timestamp)
tasks[key] = task
@@ -826,7 +811,6 @@ final class ActivityMonitor: ObservableObject {
key: eventKey,
event: event,
state: .running,
- latestEvent: latestEvent,
startedAt: nil,
progressGeneration: 1
)
@@ -866,7 +850,7 @@ final class ActivityMonitor: ObservableObject {
if task.acceptsExecutionEvent(event) {
let wasSuppressed = task.state == .suppressed
- task.resumeExecution(from: event, latestEvent: isStarting ? .subagentStarted : .subagentFinished)
+ task.resumeExecution(from: event)
task.mergeMetadata(from: event)
task.recordEvent(at: event.timestamp)
if wasSuppressed || source == .live {
@@ -924,7 +908,6 @@ final class ActivityMonitor: ObservableObject {
key: eventKey,
event: event,
state: .running,
- latestEvent: .toolStarted,
startedAt: nil,
progressGeneration: 1
)
@@ -964,7 +947,6 @@ final class ActivityMonitor: ObservableObject {
case .active, .none:
resumeTask(
from: event,
- latestEvent: .stopRequested,
allowsRecovery: true,
source: source
)
@@ -1254,7 +1236,7 @@ final class ActivityMonitor: ObservableObject {
private extension ActivityMonitor {
func resumePromptInSameTurn(from event: ActivityRecord, existing: ActivityTask?) -> Bool {
guard var task = existing, let turnID = event.turnID, task.associatedTurnID == turnID else { return false }
- task.resumeExecution(from: event, latestEvent: .promptSubmitted)
+ task.resumeExecution(from: event)
task.mergeMetadata(from: event)
task.recordEvent(at: event.timestamp)
task.startedAt = task.startedAt ?? event.timestamp
diff --git a/CodexBar/Services/Activity/ActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swift
index 0b9df9d..6b4c523 100644
--- a/CodexBar/Services/Activity/ActivityTask.swift
+++ b/CodexBar/Services/Activity/ActivityTask.swift
@@ -122,8 +122,8 @@ struct ActivityTask {
let key: ActivityTaskKey
var associatedTurnID: String?
var lifecycleCoverageCheckedAt: Date?
+ var terminalFailed = false
var state: ActivityTaskState
- var latestEvent: ActivityPhase
var projectName: String?
var modelName: String?
var effort: String?
@@ -144,7 +144,6 @@ struct ActivityTask {
key: ActivityTaskKey,
event: ActivityRecord,
state: ActivityTaskState,
- latestEvent: ActivityPhase,
startedAt: Date?,
progressGeneration: UInt64
) {
@@ -152,7 +151,6 @@ struct ActivityTask {
self.key = key
associatedTurnID = key.turnID
self.state = state
- self.latestEvent = latestEvent
projectName = event.projectDisplayName
modelName = event.model
effort = Self.normalizedEffort(event.effort)
@@ -184,7 +182,6 @@ struct ActivityTask {
ActivityTaskSnapshot(
id: displayID,
isAnonymous: key.isAnonymous,
- latestEvent: displayedApproval == nil ? latestEvent : .approvalRequested,
projectName: projectName,
modelName: modelName,
effort: effort,
@@ -194,10 +191,24 @@ struct ActivityTask {
showsPreciseDuration: showsPreciseDuration,
activeSubagentCount: activeSubagentCount,
tokenUsage: tokenUsage,
- itemType: displayedApproval.map(\.itemType) ?? itemType
+ itemType: displayedApproval.map(\.itemType) ?? itemType,
+ presentation: livePresentation
)
}
+ private var livePresentation: ActivityLiveSummary? {
+ let live = executions.filter { !$0.value.isTerminal }.compactMap { key, value in
+ value.presentation.map { (key, $0.summary) }
+ }
+ guard !live.isEmpty else { return nil }
+ let waiting = live.filter { $0.1.waiting != nil }.min { ($0.1.waiting?.since ?? .distantFuture) < ($1.1.waiting?.since ?? .distantFuture) }
+ let root = live.first { $0.0.agentID == nil }
+ var result = (waiting ?? root ?? live.max { $0.1.updatedAt < $1.1.updatedAt })!.1
+ result.recent = live.compactMap(\.1.recent).max { $0.at < $1.at }
+ result.toolCount = live.allSatisfy { $0.1.toolCount != nil } ? live.reduce(0) { $0 + ($1.1.toolCount ?? 0) } : nil
+ return result
+ }
+
var turnReference: ActivityTurnReference? {
guard let sessionID = key.sessionID, let turnID = associatedTurnID else {
return nil
@@ -223,7 +234,7 @@ struct ActivityTask {
}
mutating func recordLifecycleRead(_ state: SessionLifecycleState, at now: Date) {
- lifecycleCoverageCheckedAt = state.readStatus == .complete && state.hasContext ? now : nil
+ lifecycleCoverageCheckedAt = state.readStatus == .complete ? now : nil
}
/// 阈值调整与隐藏共用计时起点, 恢复不要求读取结果仍在有效期内
@@ -361,7 +372,7 @@ struct ActivityTask {
executions[owner] = execution
}
- mutating func resumeExecution(from event: ActivityRecord, latestEvent: ActivityPhase) {
+ mutating func resumeExecution(from event: ActivityRecord) {
recordExecutionEvent(event)
let owner = executionKey(for: event)
if owner.isReliable, var execution = executions[owner] {
@@ -369,7 +380,6 @@ struct ActivityTask {
execution.lastExecutionProgressAt = max(execution.lastExecutionProgressAt ?? .distantPast, event.timestamp)
executions[owner] = execution
}
- self.latestEvent = latestEvent
refreshApprovalState(at: event.timestamp, restoresRunning: true)
}
@@ -418,6 +428,9 @@ struct ActivityTask {
mutating func mergeExecutionLifecycle(_ lifecycle: SessionLifecycleState, owner: ActivityExecutionKey) {
guard lifecycle.readStatus == .complete else { return }
+ var execution = executions[owner] ?? ActivityExecution()
+ execution.presentation = lifecycle.presentation
+ executions[owner] = execution
if lifecycle.terminal != nil {
finishExecution(owner, at: lifecycle.lastProgressAt ?? lastProgressAt)
} else {
@@ -454,6 +467,7 @@ struct ActivityTask {
var execution = executions[owner] ?? ActivityExecution()
execution.approval = nil
execution.isTerminal = true
+ execution.presentation = nil
executions[owner] = execution
refreshApprovalState(at: timestamp)
}
@@ -509,6 +523,7 @@ struct ActivityExecution {
var lastApprovalRequestedAt: Date?
var approval: ActivityApprovalState?
var isTerminal = false
+ var presentation: ActivityLivePresentation?
mutating func mergeReviewer(_ reviewer: ApprovalReviewer?, at timestamp: Date) {
guard let reviewer, timestamp >= (approvalContextObservedAt ?? .distantPast) else { return }
diff --git a/CodexBar/Services/Activity/AppServerActivityModels.swift b/CodexBar/Services/Activity/AppServerActivityModels.swift
index 5fe251f..6cf233b 100644
--- a/CodexBar/Services/Activity/AppServerActivityModels.swift
+++ b/CodexBar/Services/Activity/AppServerActivityModels.swift
@@ -1,5 +1,3 @@
-import Foundation
-
nonisolated struct ActivityThread: Decodable {
let id: String
var cwd: String?
@@ -125,6 +123,13 @@ nonisolated struct ActivityItem: Decodable {
var agentThreadId: String?
var kind: String?
var commandActions: [CommandAction]?
+ var phase: String?
+ var action: WebAction?
+ var success: Bool?
+ var agentsStates: [String: AgentState]?
+
+ struct WebAction: Decodable { var type: String? }
+ struct AgentState: Decodable { var status: String? }
var toolDisplayName: String? {
guard type == "commandExecution" else { return tool }
@@ -174,6 +179,7 @@ nonisolated struct ActivityNotification: Decodable {
enum Category {
case state
case progress
+ case presentation
case ignored
}
@@ -187,6 +193,12 @@ nonisolated struct ActivityNotification: Decodable {
case "item/agentMessage/delta", "item/plan/delta", "item/reasoning/textDelta", "item/reasoning/summaryTextDelta",
"item/commandExecution/outputDelta", "item/fileChange/outputDelta":
.progress
+ case "item/tool/requestUserInput", "mcpServer/elicitation/request", "item/autoApprovalReview/completed",
+ "turn/plan/updated", "turn/diff/updated", "model/rerouted", "model/verification",
+ "modelProvider/authRecoveryStarted", "modelProvider/authRecoveryCompleted", "model/safetyBuffering/updated",
+ "thread/environment/connected", "thread/environment/disconnected", "hook/started", "hook/completed",
+ "mcpServer/startupStatus/updated", "error":
+ .presentation
default:
.ignored
}
@@ -195,6 +207,22 @@ nonisolated struct ActivityNotification: Decodable {
let id: ActivityJSONValue?
let method: String
let params: Params
+ let live: ActivityLivePayload
+
+ private enum CodingKeys: String, CodingKey { case id, method, params }
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+ id = try container.decodeIfPresent(ActivityJSONValue.self, forKey: .id)
+ method = try container.decode(String.self, forKey: .method)
+ live = try container.decode(ActivityLivePayload.self, forKey: .params)
+ // 展示通知有不同的 status 类型, 不交给线程生命周期解码器解释
+ if Self.category(for: method) == .presentation {
+ params = Params(threadId: live.threadId, turnId: live.turnId, targetItemId: live.targetItemId, reviewId: live.reviewId)
+ } else {
+ params = try container.decode(Params.self, forKey: .params)
+ }
+ }
struct Params: Decodable {
var threadId: String?
diff --git a/CodexBar/Services/Activity/AppServerActivityReader.swift b/CodexBar/Services/Activity/AppServerActivityReader.swift
index e0aa254..13a6a8a 100644
--- a/CodexBar/Services/Activity/AppServerActivityReader.swift
+++ b/CodexBar/Services/Activity/AppServerActivityReader.swift
@@ -1,5 +1,4 @@
import Foundation
-import os
nonisolated enum ActivityEventBatch {
case bootstrapStart
@@ -34,7 +33,6 @@ actor AppServerActivityReader {
private var generation = 0
private var connectedAt = Date.distantFuture
private var reconciledAt = Date.distantPast
- private var persistedTokens: [TokenTurn] = []
private var lastTokenRefresh = Date.distantPast
private var isRunning = false
private var isStopping = false
@@ -168,7 +166,7 @@ actor AppServerActivityReader {
// 存储未准备好时不创建连接, 避免本地故障触发重复初始化
isTokenWriter = try await tokenHistory.acquireRecordingLease()
try await persistPending()
- persistedTokens = try await tokenHistory.refresh()
+ let persistedTokens = try await tokenHistory.refresh()
try checkGeneration(current)
await onBatch(.bootstrapStart)
try checkGeneration(current)
@@ -193,7 +191,7 @@ actor AppServerActivityReader {
do {
if try await tokenHistory.acquireRecordingLease() {
try await persistPending()
- persistedTokens = try await tokenHistory.refresh()
+ let persistedTokens = try await tokenHistory.refresh()
try checkGeneration(current)
reducer.restoreTokenTurns(persistedTokens)
isTokenWriter = true
@@ -415,7 +413,7 @@ actor AppServerActivityReader {
private func consume(_ notification: ActivityNotification) {
stateChanged = true
if let id = notification.params.threadId ?? notification.params.thread?.id,
- ActivityNotification.category(for: notification.method) == .state {
+ ActivityNotification.category(for: notification.method) != .progress {
revisions[id, default: 0] += 1
}
let events = reducer.consume(notification, now: Date())
@@ -454,7 +452,6 @@ actor AppServerActivityReader {
let batch = pendingObservations
let committed = try await tokenHistory.recordObservations(batch)
pendingObservations.removeFirst(batch.count)
- persistedTokens = committed
reducer.acceptTokenTurns(committed)
lastTokenRefresh = Date()
}
diff --git a/CodexBar/Services/Activity/AppServerActivityReducer.swift b/CodexBar/Services/Activity/AppServerActivityReducer.swift
index 4b9def2..6221de4 100644
--- a/CodexBar/Services/Activity/AppServerActivityReducer.swift
+++ b/CodexBar/Services/Activity/AppServerActivityReducer.swift
@@ -24,12 +24,16 @@ nonisolated struct AppServerActivityReducer {
approvals.removeAll()
waitingSince.removeAll()
observingSince = now
+ for key in states.keys {
+ states[key]?.presentation = nil
+ }
}
mutating func invalidateThread(_ id: String) {
threads[id]?.status = ActivityThreadStatus(type: "notLoaded")
for key in states.keys where key.threadID == id && states[key]?.terminal == nil {
states[key]?.readStatus = .unavailable
+ states[key]?.presentation = nil
}
}
@@ -57,12 +61,8 @@ nonisolated struct AppServerActivityReducer {
}
mutating func restoreTokenTurns(_ turns: [TokenTurn]) {
- tokenTurns = turns
threadTotals.removeAll()
- let records = Dictionary(uniqueKeysWithValues: turns.map { ($0.id, $0) })
- for key in states.keys {
- states[key]?.tokenUsage = records[TokenTurn.identifier(thread: key.threadID, turn: key.turnID)]?.usage
- }
+ acceptTokenTurns(turns)
}
mutating func reconcile(thread: ActivityThread, turns: [ActivityTurn], reviewer: ApprovalReviewer?, now: Date, bootstrap: Bool = false) -> [ActivityRecord] {
@@ -81,6 +81,11 @@ nonisolated struct AppServerActivityReducer {
}
}
updateWaiting(threadID: thread.id, status: thread.status, now: now)
+ if let key = activeReference(thread.id) {
+ var live = states[key]?.presentation ?? ActivityLivePresentation()
+ live.reconcile(status: thread.status)
+ states[key]?.presentation = live
+ }
resolveRoots()
return events
}
@@ -157,11 +162,30 @@ nonisolated struct AppServerActivityReducer {
progress(threadID, turnID, at: now)
}
}
+ updatePresentation(notification, threadID: threadID, turnID: turnID, at: date)
resolveRoots()
prune(now: now)
return finish(events, notification: notification, threadID: threadID, turnID: turnID, now: now)
}
+ private mutating func updatePresentation(_ notification: ActivityNotification, threadID: String, turnID: String?, at date: Date) {
+ let requestID = notification.params.requestId?.identifier
+ // resolved 不携带 turnId, 必须先匹配原请求, 不能误清除新轮次的等待
+ let matched = requestID.flatMap { id in
+ states.keys.first { $0.threadID == threadID && states[$0]?.presentation?.requests[id] != nil }
+ }
+ guard let key = matched ?? turnID.map({ reference(threadID, $0, at: date) }),
+ states[key]?.terminal == nil, states[key] != nil else { return }
+ // 独立的 MCP 和 Hook 请求没有明确轮次归属时不挂到当前任务
+ if ["mcpServer/elicitation/request", "hook/started", "hook/completed"].contains(notification.method),
+ notification.live.turnId == nil {
+ return
+ }
+ var live = states[key]?.presentation ?? ActivityLivePresentation()
+ live.consume(notification, at: date)
+ states[key]?.presentation = live
+ }
+
private mutating func finish(
_ events: [ActivityRecord], notification: ActivityNotification,
threadID: String, turnID: String?, now: Date
@@ -303,8 +327,8 @@ nonisolated struct AppServerActivityReducer {
approvalReviewer: reviewer ?? previous?.approvalReviewer,
effort: threads[threadID]?.reasoningEffort, lastProgressAt: previous?.lastProgressAt ?? start,
terminal: terminal, readStatus: terminal == nil && (!isLoaded || turn.status != "inProgress") ? .unavailable : .complete,
- hasContext: true, contextObservedAt: now, rootTurnID: previous?.rootTurnID,
- recordedThreadID: threadID, rootSessionID: previous?.rootSessionID,
+ contextObservedAt: now, rootTurnID: previous?.rootTurnID,
+ rootSessionID: previous?.rootSessionID,
parentThreadID: threads[threadID]?.parentID,
lastExecutionProgressAt: previous?.lastExecutionProgressAt,
tokenUsage: previous?.tokenUsage ?? tokenTurns.first(where: { $0.id == TokenTurn.identifier(thread: threadID, turn: turn.id) })?.usage,
@@ -315,6 +339,11 @@ nonisolated struct AppServerActivityReducer {
state.terminalObservedAt = previous?.terminalObservedAt ?? now
state.lastProgressAt = turn.completedAt.map(Date.init(timeIntervalSince1970:)) ?? state.terminalObservedAt
}
+ state.presentation = previous?.presentation
+ state.turnStatus = turn.status
+ if terminal != nil {
+ state.presentation = nil
+ }
states[reference] = state
}
diff --git a/CodexBar/Services/Activity/SessionLifecycleCache.swift b/CodexBar/Services/Activity/SessionLifecycleCache.swift
index 766c9c4..10e3315 100644
--- a/CodexBar/Services/Activity/SessionLifecycleCache.swift
+++ b/CodexBar/Services/Activity/SessionLifecycleCache.swift
@@ -4,7 +4,6 @@ nonisolated struct ActivityTurnReference: Hashable {
let threadID: String
let turnID: String
let startedAt: Date
- var isTerminalUsageOnly = false
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.threadID == rhs.threadID && lhs.turnID == rhs.turnID
@@ -79,10 +78,8 @@ nonisolated struct SessionLifecycleState {
var lastProgressAt: Date?
let terminal: SessionTerminalState?
var readStatus: SessionReadStatus = .complete
- var hasContext = false
var contextObservedAt: Date?
var rootTurnID: String?
- var recordedThreadID: String?
var rootSessionID: String?
var parentThreadID: String?
var lastExecutionProgressAt: Date?
@@ -91,6 +88,8 @@ nonisolated struct SessionLifecycleState {
var isWaitingApproval: Bool?
var approvalChangedAt: Date?
var terminalObservedAt: Date?
+ var presentation: ActivityLivePresentation?
+ var turnStatus: String?
}
nonisolated enum SessionReadStatus {
diff --git a/CodexBar/Services/AppServer/AppServerConfig.swift b/CodexBar/Services/AppServer/AppServerConfig.swift
index 8a6974b..9dc8ee0 100644
--- a/CodexBar/Services/AppServer/AppServerConfig.swift
+++ b/CodexBar/Services/AppServer/AppServerConfig.swift
@@ -1,5 +1,3 @@
-import Foundation
-
/// config/read 的最小响应模型, 只解出 TUI 通知相关状态
nonisolated struct ConfigReadResponse: Decodable {
let config: AppServerConfig
diff --git a/CodexBar/Services/AppServer/AppServerLogStore.swift b/CodexBar/Services/AppServer/AppServerLogStore.swift
index 5bc840c..c1c951c 100644
--- a/CodexBar/Services/AppServer/AppServerLogStore.swift
+++ b/CodexBar/Services/AppServer/AppServerLogStore.swift
@@ -27,7 +27,7 @@ final nonisolated class AppServerLogStore: @unchecked Sendable {
struct Limits: Sendable {
var entries = 10000
var bytes = 50 * 1024 * 1024
- var bodyBytes = 64 * 1024
+ var bodyBytes = 128 * 1024
var pageEntries = 1000
}
diff --git a/CodexBar/Services/AppServer/AppServerLogViewModel.swift b/CodexBar/Services/AppServer/AppServerLogViewModel.swift
index 62005fb..5308e73 100644
--- a/CodexBar/Services/AppServer/AppServerLogViewModel.swift
+++ b/CodexBar/Services/AppServer/AppServerLogViewModel.swift
@@ -56,11 +56,15 @@ final class AppServerLogViewModel: ObservableObject {
guard !isReading else { return }
let current = observationGeneration
isReading = true
- isLoading = !isLoaded
+ if !isLoaded {
+ isLoading = true
+ }
defer {
if current == observationGeneration {
isReading = false
- isLoading = false
+ if isLoading {
+ isLoading = false
+ }
}
}
do {
@@ -71,30 +75,43 @@ final class AppServerLogViewModel: ObservableObject {
guard current == observationGeneration else { return }
if changes.generation != generation || changes.hasMore {
try await loadFirst(current: current)
- } else {
- if !changes.entries.isEmpty {
- let newest = entries.first?.position ?? 0
- var byID = Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0) })
- for entry in changes.entries where byID[entry.id] != nil || (!browsingHistory && entry.position > newest) {
- byID[entry.id] = entry
- }
- entries = Array(byID.values.sorted { $0.position > $1.position }.prefix(maximumEntries))
- }
- revision = changes.revision
- totalCount = changes.total
+ } else if changes.revision != revision {
+ mergeEntries(changes.entries)
let oldest = try await storage.page(before: entries.last?.position, limit: 1)
guard current == observationGeneration else { return }
- hasMore = !oldest.entries.isEmpty
+ revision = changes.revision
+ if totalCount != changes.total {
+ totalCount = changes.total
+ }
+ let more = !oldest.entries.isEmpty
+ if hasMore != more {
+ hasMore = more
+ }
}
}
- errorMessage = nil
+ if errorMessage != nil {
+ errorMessage = nil
+ }
} catch {
- if current == observationGeneration {
+ if current == observationGeneration, errorMessage != error.localizedDescription {
errorMessage = error.localizedDescription
}
}
}
+ private func mergeEntries(_ updates: [AppServerLogEntry]) {
+ guard !updates.isEmpty else { return }
+ let newest = entries.first?.position ?? 0
+ var byID = Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0) })
+ for entry in updates where byID[entry.id] != nil || (!browsingHistory && entry.position > newest) {
+ byID[entry.id] = entry
+ }
+ let updated = Array(byID.values.sorted { $0.position > $1.position }.prefix(maximumEntries))
+ if entries != updated {
+ entries = updated
+ }
+ }
+
func loadMore() async {
let waitingGeneration = observationGeneration
while isReading {
diff --git a/CodexBar/Services/AppServer/AppServerSession.swift b/CodexBar/Services/AppServer/AppServerSession.swift
index 80f0341..b6c6e9f 100644
--- a/CodexBar/Services/AppServer/AppServerSession.swift
+++ b/CodexBar/Services/AppServer/AppServerSession.swift
@@ -362,19 +362,24 @@ final nonisolated class AppServerSession {
logStorage.recordReceived(method: method, payload: framePayload(data), connection: connectionName)
}
- /// 推送只记录业务使用的状态事件, 错误和异常协议消息保留以便排查
+ /// 推送只记录活动采集使用的状态和展示事件, 跳过高频 delta, 保留错误和异常协议消息
/// 此判断不参与消息路由, 被过滤的消息仍交给业务消费
private static func shouldRecordIncoming(_ object: [String: Any]?) -> Bool {
guard let object, let method = object["method"] as? String else { return true }
if method == "error" || method == "warning" {
return true
}
- guard ActivityNotification.category(for: method) == .state else { return false }
+ switch ActivityNotification.category(for: method) {
+ case .progress, .ignored: return false
+ case .state, .presentation: break
+ }
switch method {
case "item/started", "item/completed":
guard let params = object["params"] as? [String: Any],
let item = params["item"] as? [String: Any], let type = item["type"] as? String else { return true }
- return ActivityItem.isToolType(type) || type == "contextCompaction" || type == "subAgentActivity"
+ return ActivityItem.isToolType(type) || [
+ "contextCompaction", "subAgentActivity", "agentMessage", "reasoning", "plan", "enteredReviewMode", "exitedReviewMode"
+ ].contains(type)
default:
return true
}
diff --git a/CodexBar/Services/Codex/CodexPaths.swift b/CodexBar/Services/Codex/CodexPaths.swift
index b3dc8c7..656856e 100644
--- a/CodexBar/Services/Codex/CodexPaths.swift
+++ b/CodexBar/Services/Codex/CodexPaths.swift
@@ -19,7 +19,6 @@ nonisolated struct CodexServerConnectionInfo: Equatable {
let socketPath: String
/// 来自 initialize 握手, 代表当前 app-server 进程真实运行的版本
let version: String?
- let openedAt: Date
}
/// 一次 PATH 扫描得到的安装结果, 供版本检测使用
diff --git a/CodexBar/Services/Codex/CodexVersionService.swift b/CodexBar/Services/Codex/CodexVersionService.swift
index 3429ff1..263eda7 100644
--- a/CodexBar/Services/Codex/CodexVersionService.swift
+++ b/CodexBar/Services/Codex/CodexVersionService.swift
@@ -1,4 +1,3 @@
-import Combine
import Foundation
import os
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index dbb5163..9332265 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -623,7 +623,7 @@ actor CodexStatusService {
private static func openConnection(socketURL: URL) -> ConnectionResolution {
do {
let session = try AccountSession(socketURL: socketURL)
- return initializeConnection(session: session, socketURL: socketURL, openedAt: Date())
+ return initializeConnection(session: session, socketURL: socketURL)
} catch {
AppServerLogStore.shared.recordFailure(message: error.localizedDescription)
return .initializationFailed(message: String(localized: "codex-status.daemon.error.unavailable"))
@@ -632,15 +632,13 @@ actor CodexStatusService {
private static func initializeConnection(
session: AccountSession,
- socketURL: URL,
- openedAt: Date
+ socketURL: URL
) -> ConnectionResolution {
do {
let initialized = try session.initializeAccount()
let connectionInfo = CodexServerConnectionInfo(
socketPath: socketURL.path,
- version: initialized.version,
- openedAt: openedAt
+ version: initialized.version
)
return .ready(
@@ -676,11 +674,6 @@ private final nonisolated class AppServerConnection {
let session: AccountSession
let connectionInfo: CodexServerConnectionInfo
var accountResponse: AccountReadResponse
- private var isClosed = false
-
- var openedAt: Date {
- connectionInfo.openedAt
- }
init(
session: AccountSession,
@@ -697,11 +690,6 @@ private final nonisolated class AppServerConnection {
}
func close() {
- guard !isClosed else {
- return
- }
-
- isClosed = true
session.close()
}
}
diff --git a/CodexBar/Services/History/HistoryService.swift b/CodexBar/Services/History/HistoryService.swift
index 2cadcd8..7fc2b23 100644
--- a/CodexBar/Services/History/HistoryService.swift
+++ b/CodexBar/Services/History/HistoryService.swift
@@ -1,6 +1,4 @@
-import Combine
import CryptoKit
-import Darwin
import Foundation
import os
diff --git a/CodexBar/Services/History/HistoryStorage.swift b/CodexBar/Services/History/HistoryStorage.swift
index dd5d4c9..3ed24c1 100644
--- a/CodexBar/Services/History/HistoryStorage.swift
+++ b/CodexBar/Services/History/HistoryStorage.swift
@@ -1,7 +1,5 @@
-import CryptoKit
import Darwin
import Foundation
-import os
/// 活动统计文件路径, 保留期和跨进程 flock 都集中在这里
nonisolated enum HistoryStorage {
@@ -43,31 +41,9 @@ nonisolated enum HistoryStorage {
in root: URL = directoryURL(),
_ work: () throws -> T
) throws -> T {
- try FileManager.default.createDirectory(
- at: lockURL(in: root).deletingLastPathComponent(),
- withIntermediateDirectories: true
- )
-
- // 创建与打开必须是同一次调用: 分开做时两个进程可能各自创建,
- // 后创建的会 unlink 掉前者正在锁的 inode, 于是双方都以为自己独占
- let fileDescriptor = open(lockURL(in: root).path, O_RDWR | O_CREAT, 0o600)
- guard fileDescriptor >= 0 else {
- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
- }
- defer {
- close(fileDescriptor)
- }
-
// 采集与维护使用独立服务实例, 文件事务必须共享同一把锁
- guard flock(fileDescriptor, LOCK_EX) == 0 else {
- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
- }
-
- defer {
- flock(fileDescriptor, LOCK_UN)
- }
-
- return try work()
+ let url = lockURL(in: root)
+ return try JSONFileStorage.withLock(in: url.deletingLastPathComponent(), name: url.lastPathComponent, work)
}
static func loadMaintenanceState(in root: URL = directoryURL()) -> HistoryMaintenanceState {
diff --git a/CodexBar/Services/History/TokenHistoryStore.swift b/CodexBar/Services/History/TokenHistoryStore.swift
index 1180fea..4202a79 100644
--- a/CodexBar/Services/History/TokenHistoryStore.swift
+++ b/CodexBar/Services/History/TokenHistoryStore.swift
@@ -1,5 +1,3 @@
-import CryptoKit
-import Darwin
import Foundation
import os
diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swift
index bdd8003..fea474f 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift
@@ -94,11 +94,8 @@ final class KeepAliveController: ObservableObject {
private let durationLimiter: KeepAliveDurationLimiter
/// 不加 @Published: 设置页在根上观察整个控制器, 任务每起停一次都会重算整页 body
/// 需要跟着它刷新的只有派生出去的 isLowBatteryBlocking 与 canShowOptions
- private var hasRunningTasks = false
- /// 保留仍活跃且已经进入过运行态的任务, 避免普通快照刷新被误判成新任务
- private var startedRunningTaskIDs = Set<UUID>()
- /// 最近一份快照中的等待任务, 用于识别等待批准后恢复运行的状态转换
- /// 开着 keepsAwakeWhileWaiting 时它同时是"有没有任务撑着防睡眠"的另一半输入
+ private var runningTaskIDs = Set<UUID>()
+ /// 开着 keepsAwakeWhileWaiting 时, 等待任务也参与防睡眠判定
private var waitingTaskIDs = Set<UUID>()
/// 同一 App 进程内跨 XPC 重连保持不变, helper 据此把连接变化与租约所有权分开
private let helperClientSessionID = UUID().uuidString
@@ -115,7 +112,7 @@ final class KeepAliveController: ObservableObject {
private var retryAttempt = 0
private var helperRegistrationTask: Task<Void, Never>?
private let helperPackageValidation = HelperPackageValidation()
- /// 与 hasRunningTasks 同理: 只经由派生状态影响 UI, 自己不发信号
+ /// 只经由派生状态影响 UI, 自己不发信号
private var isRefreshingHelper = false
private var isAutoResetRequested = false
private let autoResetWakeScheduler = AutoResetWakeScheduler()
@@ -207,7 +204,7 @@ final class KeepAliveController: ObservableObject {
helperPackageValidation.cancel()
autoResetWakeScheduler.stop()
cancelExternalObservation()
- startedRunningTaskIDs.removeAll()
+ runningTaskIDs.removeAll()
waitingTaskIDs.removeAll()
durationLimiter.stop()
powerSourceMonitor.stop()
@@ -478,22 +475,16 @@ final class KeepAliveController: ObservableObject {
}
private func handleActivitySnapshot(_ snapshot: ActivitySnapshot) {
- let runningTaskIDs = keepAliveTaskIDs(in: snapshot.runningTasks)
+ let currentRunningTaskIDs = keepAliveTaskIDs(in: snapshot.runningTasks)
let currentWaitingTaskIDs = keepAliveTaskIDs(in: snapshot.waitingTasks)
- let activeTaskIDs = runningTaskIDs.union(currentWaitingTaskIDs)
-
- startedRunningTaskIDs.formIntersection(activeTaskIDs)
- let newRunningTaskIDs = runningTaskIDs.subtracting(startedRunningTaskIDs)
- let resumedRunningTaskIDs = runningTaskIDs
- .intersection(waitingTaskIDs)
- .subtracting(currentWaitingTaskIDs)
- startedRunningTaskIDs.formUnion(runningTaskIDs)
+ // 运行与等待互斥, 新任务和等待后恢复都表现为运行集合新增成员
+ let hasEnteredRunning = !currentRunningTaskIDs.isSubset(of: runningTaskIDs)
+ runningTaskIDs = currentRunningTaskIDs
waitingTaskIDs = currentWaitingTaskIDs
- hasRunningTasks = !runningTaskIDs.isEmpty
- if activeTaskIDs.isEmpty {
+ if runningTaskIDs.isEmpty, waitingTaskIDs.isEmpty {
durationLimiter.reset()
- } else if !newRunningTaskIDs.isEmpty || !resumedRunningTaskIDs.isEmpty {
+ } else if hasEnteredRunning {
restartMaximumDurationPeriod()
}
reconcileSleepState(trigger: .taskChanged)
@@ -1401,7 +1392,7 @@ final class KeepAliveController: ObservableObject {
/// 等待批准算不算"有任务"由用户开关决定, 快照与设置两条路径共用这一份规则
private var hasKeepAliveTasks: Bool {
- hasRunningTasks || (keepsAwakeWhileWaiting && !waitingTaskIDs.isEmpty)
+ !runningTaskIDs.isEmpty || (keepsAwakeWhileWaiting && !waitingTaskIDs.isEmpty)
}
/// 按顺序返回第一个不满足的条件, 全部满足时为 nil
diff --git a/CodexBar/Services/Support/CountResolution.swift b/CodexBar/Services/Support/CountResolution.swift
index b357ba4..9541bdf 100644
--- a/CodexBar/Services/Support/CountResolution.swift
+++ b/CodexBar/Services/Support/CountResolution.swift
@@ -1,5 +1,3 @@
-import Foundation
-
nonisolated enum CountResolution {
static func preferredCount(
compactedCount: Int?,
diff --git a/CodexBar/Services/Support/JSONFileStorage.swift b/CodexBar/Services/Support/JSONFileStorage.swift
index ed27739..2744aff 100644
--- a/CodexBar/Services/Support/JSONFileStorage.swift
+++ b/CodexBar/Services/Support/JSONFileStorage.swift
@@ -2,16 +2,17 @@ import Darwin
import Foundation
nonisolated enum JSONFileStorage {
- static func withLock<T>(in directory: URL, _ operation: () throws -> T) throws -> T {
- guard let descriptor = try acquireLock(in: directory) else { throw POSIXError(.EIO) }
+ static func withLock<T>(in directory: URL, name: String = "store.lock", _ operation: () throws -> T) throws -> T {
+ guard let descriptor = try acquireLock(in: directory, name: name) else { throw POSIXError(.EIO) }
defer { releaseLock(descriptor) }
return try operation()
}
static func acquireLock(in directory: URL, name: String = "store.lock", nonblocking: Bool = false) throws -> Int32? {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ // 原子创建并打开锁文件, 避免替换其他进程已锁定的 inode
let descriptor = open(directory.appendingPathComponent(name).path, O_RDWR | O_CREAT, 0o600)
- guard descriptor >= 0 else { throw POSIXError(.EIO) }
+ guard descriptor >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
guard flock(descriptor, LOCK_EX | (nonblocking ? LOCK_NB : 0)) == 0 else {
let code = errno
close(descriptor)
diff --git a/CodexBar/Services/Support/RefreshTaskCoordinator.swift b/CodexBar/Services/Support/RefreshTaskCoordinator.swift
index 255d2fa..bb163ac 100644
--- a/CodexBar/Services/Support/RefreshTaskCoordinator.swift
+++ b/CodexBar/Services/Support/RefreshTaskCoordinator.swift
@@ -1,4 +1,3 @@
-import Foundation
import os
/// 小型刷新任务状态机, 由 MainActor ViewModel 持有和调用
diff --git a/CodexBar/Services/Sync/SyncCancellation.swift b/CodexBar/Services/Sync/SyncCancellation.swift
index ba63e35..a4ee3cf 100644
--- a/CodexBar/Services/Sync/SyncCancellation.swift
+++ b/CodexBar/Services/Sync/SyncCancellation.swift
@@ -1,5 +1,3 @@
-import Foundation
-
nonisolated enum SyncCancellation {
/// Task 的取消标记不会随开关重新启用而复活
static func check(isEnabled: () -> Bool) throws {
diff --git a/CodexBar/Services/Sync/SyncScheduler.swift b/CodexBar/Services/Sync/SyncScheduler.swift
index e75c498..6aec422 100644
--- a/CodexBar/Services/Sync/SyncScheduler.swift
+++ b/CodexBar/Services/Sync/SyncScheduler.swift
@@ -12,7 +12,6 @@ final class SyncScheduler {
private let maintenance: (Bool, LogTrigger) async -> HistoryMaintenanceCounts?
private let rebuild: ([String], Bool) async throws -> HistoryDataRebuildSummary
private let syncActivation: () -> SyncActivation
- private var isRunning = false
private var runningTask: Task<Void, Never>?
private var runningSynchronizes = false
private var pendingRebuild: RebuildRequest?
@@ -105,7 +104,7 @@ final class SyncScheduler {
}
private func drain() {
- guard !isRunning else {
+ guard runningTask == nil else {
return
}
@@ -141,7 +140,6 @@ final class SyncScheduler {
private func startMaintenance(synchronize: Bool) {
let trigger = (synchronize ? pendingSyncTrigger : pendingMaintenanceTrigger) ?? .auto
let duration = LogDuration()
- isRunning = true
pendingMaintenanceTrigger = nil
if synchronize {
@@ -177,7 +175,6 @@ final class SyncScheduler {
duration: duration,
counts: counts
)
- isRunning = false
runningTask = nil
runningSynchronizes = false
@@ -194,7 +191,6 @@ final class SyncScheduler {
}
private func startRebuild(_ request: RebuildRequest) {
- isRunning = true
pendingRebuild = nil
let synchronize = syncActivation().isActive
@@ -219,7 +215,6 @@ final class SyncScheduler {
result = .failure(error)
}
- isRunning = false
runningTask = nil
runningSynchronizes = false
if synchronize, !Task.isCancelled {
diff --git a/CodexBar/Services/Updates/AppUpdater.swift b/CodexBar/Services/Updates/AppUpdater.swift
index 4b531dc..4711214 100644
--- a/CodexBar/Services/Updates/AppUpdater.swift
+++ b/CodexBar/Services/Updates/AppUpdater.swift
@@ -2,7 +2,6 @@ import AppKit
import Combine
import os
import Sparkle
-import SwiftUI
/// Sparkle 更新状态桥接层, 同时驱动设置窗和菜单面板的更新提示
@MainActor
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index f721725..69313eb 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -40,7 +40,8 @@ struct LogView: View {
Text(verbatim: "\(store.totalCount)")
.font(.caption.monospacedDigit())
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: store.totalCount, comparison: Double(store.totalCount))
.padding(.horizontal, 7)
.padding(.vertical, 2)
.background(Capsule().fill(.quaternary))
@@ -212,20 +213,16 @@ private struct LogRow: View {
}
if hasText {
- LogHeaderActionButton(
- title: "common.action.preview",
- systemImage: "doc.text.magnifyingglass",
- help: String(localized: "log.action.preview-full", defaultValue: "\(caption)")
- ) {
+ Button {
fullTextItem = FullLogTextItem(title: caption, text: text)
+ } label: {
+ Label("common.action.preview", systemImage: "doc.text.magnifyingglass")
}
- LogHeaderActionButton(
- title: "common.action.copy",
- systemImage: "doc.on.doc",
- help: String(localized: "log.action.copy-full", defaultValue: "\(caption)")
- ) {
+ Button {
PasteboardWriter.copy(text)
+ } label: {
+ Label("common.action.copy", systemImage: "doc.on.doc")
}
}
}
@@ -272,21 +269,6 @@ private struct FullLogTextItem: Identifiable {
let text: String
}
-/// 复制/预览按钮的统一样式入口
-private struct LogHeaderActionButton: View {
- let title: LocalizedStringResource
- let systemImage: String
- let help: String
- let action: () -> Void
-
- var body: some View {
- Button(action: action) {
- Label(title, systemImage: systemImage)
- }
- .help(help)
- }
-}
-
/// 完整请求/响应预览弹窗
private struct FullLogTextView: View {
let item: FullLogTextItem
diff --git a/CodexBar/Views/Menu/ActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swift
index 6fbee22..735dab5 100644
--- a/CodexBar/Views/Menu/ActivityCard.swift
+++ b/CodexBar/Views/Menu/ActivityCard.swift
@@ -32,15 +32,6 @@ struct ActivityCard: View {
keepAliveController.isActivelyPreventingSleep && !showsUnavailableState
}
- private var keepAliveHelp: String {
- switch keepAliveController.sleepPreventionSource {
- case .external:
- String(localized: "keep-alive.status.disabled-by-other-source")
- case .codexBar, .none:
- String(localized: "keep-alive.status.active")
- }
- }
-
// MARK: - 卡片布局
var body: some View {
@@ -63,7 +54,7 @@ struct ActivityCard: View {
let content = content(at: now)
return VStack(alignment: .leading, spacing: 0) {
statusRow(content)
- .frame(height: Metrics.height)
+ .frame(minHeight: content.detail == nil ? nil : Metrics.height)
.id(snapshot.hasTaskCenterContent)
.transition(.opacity)
if let usage = content.tokenUsage {
@@ -80,7 +71,6 @@ struct ActivityCard: View {
}
.padding(.horizontal, MenuMetrics.panelPadding)
.frame(maxWidth: .infinity)
- .modifier(ActivityCardHeight(height: content.tokenUsage == nil ? Metrics.height : Metrics.usageHeight))
.activityStatusParticles(cornerRadius: MenuMetrics.panelCornerRadius)
.liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)
.overlay {
@@ -96,38 +86,79 @@ struct ActivityCard: View {
}
.animation(Metrics.expansionAnimation, value: snapshot.hasTaskCenterContent)
.animation(Metrics.expansionAnimation, value: content.tokenUsage != nil)
+ .animation(Metrics.expansionAnimation, value: content.detail == nil)
}
private func statusRow(_ content: ActivityCardContent) -> some View {
- HStack(spacing: 10) {
+ HStack(alignment: .top, spacing: 10) {
Image(systemName: content.symbolName)
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(content.tint)
.frame(width: 20)
VStack(alignment: .leading, spacing: 3) {
- Text(content.title)
- .font(.caption.weight(.semibold))
- .foregroundStyle(Color.codexLabel)
- .lineLimit(1)
- .truncationMode(.middle)
+ statusHeader(content)
if let detail = content.detail {
ActivityStatusText(
- text: detail,
- tint: content.tint,
- effect: statusTextEffect
+ text: detail, tint: content.tint, effect: statusTextEffect,
+ lineLimit: nil, supplement: content.detailSupplement
)
+ .numericTransition(value: [detail, content.detailSupplement], enabled: allowsAnimations)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ if let recent = content.recent {
+ Text(recent)
+ .font(.caption2)
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: recent, enabled: allowsAnimations)
+ .fixedSize(horizontal: false, vertical: true)
}
}
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .padding(.top, 12)
+ .padding(.bottom, content.detail == nil ? 8 : 12)
+ .animation(.codexStatus, value: showsKeepAliveBadge)
+ .animation(.codexStatus, value: content.isAnonymous)
+ // 徽标只占用标题行的宽度, 下方状态和附加信息可以使用完整文本区域
+ .animation(.codexStatus, value: content.otherTaskCount)
+ }
- Spacer(minLength: 0)
+ private func statusHeader(_ content: ActivityCardContent) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 10) {
+ Text(content.header.joined(separator: " • "))
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(Color.codexLabel)
+ .numericTransition(value: content.header, enabled: allowsAnimations)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if content.isAnonymous || content.otherTaskCount > 0 || showsKeepAliveBadge {
+ statusBadges(content)
+ .fixedSize()
+ }
+ }
+ }
+ private func statusBadges(_ content: ActivityCardContent) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 10) {
if content.isAnonymous {
ActivityAnonymousIcon()
.transition(.opacity)
}
+ if content.otherTaskCount > 0 {
+ Text(verbatim: "+\(content.otherTaskCount)")
+ .font(.caption2.monospacedDigit().weight(.semibold))
+ // 必须是具体 Color, 层级样式在 numericText 的过渡层里会被重新解析成别的层级
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: content.otherTaskCount, comparison: Double(content.otherTaskCount), enabled: allowsAnimations)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 3)
+ .background(.secondary.opacity(0.12), in: Capsule())
+ .transition(.opacity)
+ .help(String(localized: "activity.summary.other-task-count", defaultValue: "\(content.otherTaskCount, specifier: "%lld")"))
+ }
// 防睡眠只在任务运行期间生效, 所以状态挂在活动卡片上而不是单独占一行
if showsKeepAliveBadge {
// 隐藏或关闭动画效果时移除整个旋转视图, 避免保留持续渲染调度
@@ -141,26 +172,8 @@ struct ActivityCard: View {
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(Color.teal)
.transition(.opacity)
- .help(keepAliveHelp)
- }
-
- if content.otherTaskCount > 0 {
- Text(verbatim: "+\(content.otherTaskCount)")
- .font(.caption2.monospacedDigit().weight(.semibold))
- // 必须是具体 Color, 层级样式在 numericText 的过渡层里会被重新解析成别的层级
- .foregroundStyle(Color.codexSecondaryLabel)
- .contentTransition(.numericText(value: Double(content.otherTaskCount)))
- .padding(.horizontal, 6)
- .padding(.vertical, 3)
- .background(.secondary.opacity(0.12), in: Capsule())
- .transition(.opacity)
- .help(String(localized: "activity.summary.other-task-count", defaultValue: "\(content.otherTaskCount, specifier: "%lld")"))
}
}
- .animation(.codexStatus, value: showsKeepAliveBadge)
- .animation(.codexStatus, value: content.isAnonymous)
- // 任务数变化会让 +N 增删, 防睡眠徽标跟着横移; 动画只作用于状态行
- .animation(.codexStatus, value: content.otherTaskCount)
}
private func tokenUsageMetrics(_ usage: TokenUsage) -> some View {
@@ -178,13 +191,13 @@ struct ActivityCard: View {
Text(usage.cacheHitRate.map { $0.formatted(.percent.precision(.fractionLength(0 ... 1))) } ?? "—")
.font(.caption2.monospacedDigit().weight(.semibold))
.foregroundStyle(Color.codexLabel)
- .contentTransition(.numericText(value: usage.cacheHitRate ?? 0))
+ .numericTransition(value: usage.cacheHitRate, comparison: usage.cacheHitRate ?? 0, enabled: allowsAnimations)
}
.frame(minWidth: 0, maxWidth: .infinity)
tokenMetric("usage.tokens.reasoning-output", tokens: usage.reasoningOutputTokens)
}
.lineLimit(1)
- .animation(.codexStatus, value: usage)
+ .animation(allowsAnimations ? .codexStatus : nil, value: usage)
}
private func tokenMetric(_ title: LocalizedStringKey, tokens: Int64) -> some View {
@@ -202,28 +215,20 @@ struct ActivityCard: View {
// MARK: - 展示内容
private func content(at now: Date) -> ActivityCardContent {
- switch snapshot.primaryActivity {
+ switch snapshot.panelPrimaryActivity {
case let .waiting(task):
return activeContent(
for: task,
symbolName: "hand.raised.fill",
tint: .orange,
- fallback: "activity.status.codex-waiting-for-approval",
- detailComponents: ActivityDisplayFormat.waitingDetailComponents(
- for: task,
- now: now
- )
+ waiting: true
)
case let .running(task):
return activeContent(
for: task,
symbolName: "bolt.fill",
tint: .blue,
- fallback: "common.codex",
- detailComponents: ActivityDisplayFormat.runningDetailComponents(
- for: task,
- now: now
- )
+ waiting: false
)
case let .completed(completion):
let details = ActivityDisplayFormat.historyDetailComponents(
@@ -233,16 +238,14 @@ struct ActivityCard: View {
return ActivityCardContent(
symbolName: "checkmark.circle.fill",
tint: .green,
- title: activityTitle(
- modelName: completion.modelName,
- effort: completion.effort,
- projectName: completion.projectName,
- fallback: "activity.status.codex-completed"
- ),
- detail: details.joined(separator: " • "),
+ detail: nil,
otherTaskCount: 0,
isAnonymous: completion.isAnonymous,
- tokenUsage: completion.tokenUsage
+ tokenUsage: completion.tokenUsage,
+ header: [
+ completion.projectName ?? String(localized: "common.codex"),
+ ActivityDisplayFormat.modelMetadata(modelName: completion.modelName, effort: completion.effort)
+ ].compactMap(\.self) + details
)
case let .terminated(termination):
let details = ActivityDisplayFormat.historyDetailComponents(
@@ -252,27 +255,23 @@ struct ActivityCard: View {
return ActivityCardContent(
symbolName: "xmark.circle.fill",
tint: .red,
- title: activityTitle(
- modelName: termination.modelName,
- effort: termination.effort,
- projectName: termination.projectName,
- fallback: "activity.status.codex-stopped"
- ),
- detail: details.joined(separator: " • "),
+ detail: ActivityLiveLabel(termination.isFailure ? "failed" : "interrupted").text,
otherTaskCount: 0,
isAnonymous: termination.isAnonymous,
- tokenUsage: termination.tokenUsage
+ tokenUsage: termination.tokenUsage,
+ header: [
+ termination.projectName ?? String(localized: "common.codex"),
+ ActivityDisplayFormat.modelMetadata(modelName: termination.modelName, effort: termination.effort)
+ ].compactMap(\.self) + details
)
case .idle:
return ActivityCardContent(
symbolName: "moon.zzz.fill",
tint: .secondary,
- title: showsUnavailableState
- ? String(localized: "common.empty.no-data")
- : String(localized: "activity.empty.no-activity"),
- detail: nil,
+ detail: activityMonitor.sourcePresentation?.text ?? ActivityLiveLabel("idle").text,
otherTaskCount: 0,
- isAnonymous: false
+ isAnonymous: false,
+ header: [String(localized: "common.codex")]
)
}
}
@@ -281,62 +280,32 @@ struct ActivityCard: View {
for task: ActivityTaskSnapshot,
symbolName: String,
tint: Color,
- fallback: LocalizedStringResource,
- detailComponents: [String]
+ waiting: Bool
) -> ActivityCardContent {
- let details = activeDetailComponents(detailComponents, task: task)
+ let summary = ActivityDisplayFormat.liveSummaryComponents(for: task, now: timelineDate, waiting: waiting)
return ActivityCardContent(
symbolName: symbolName,
tint: tint,
- title: activityTitle(
- modelName: task.modelName,
- effort: task.effort,
- projectName: task.projectName,
- fallback: fallback
- ),
- detail: details.joined(separator: " • "),
+ detail: ActivityDisplayFormat.liveStatus(for: task, waiting: waiting),
otherTaskCount: otherTaskCount,
isAnonymous: task.isAnonymous,
- tokenUsage: task.tokenUsage
+ tokenUsage: task.tokenUsage,
+ header: [
+ task.projectName ?? String(localized: "common.codex"),
+ ActivityDisplayFormat.modelMetadata(modelName: task.modelName, effort: task.effort)
+ ].compactMap(\.self) + summary.prefix(1),
+ recent: ActivityDisplayFormat.recentEvent(for: task),
+ detailSupplement: summary.dropFirst().first
)
}
- private func activityTitle(
- modelName: String?,
- effort: String?,
- projectName: String?,
- fallback: LocalizedStringResource
- ) -> String {
- [
- ActivityDisplayFormat.modelMetadata(
- modelName: modelName,
- effort: effort
- ),
- projectName ?? String(localized: fallback)
- ]
- .compactMap(\.self)
- .joined(separator: " • ")
- }
-
- private func activeDetailComponents(
- _ components: [String],
- task: ActivityTaskSnapshot
- ) -> [String] {
- guard let count = task.activeSubagentCount, count > 0 else {
- return components
- }
- var result = components
- result.insert(String(localized: "activity.summary.subagent-count", defaultValue: "\(count, specifier: "%lld")"), at: min(1, result.count))
- return result
- }
-
private var otherTaskCount: Int {
max(0, snapshot.activeCount - 1)
}
private var statusTextEffect: ActivityStatusText.Effect {
guard allowsAnimations else { return .none }
- switch snapshot.primaryActivity {
+ switch snapshot.panelPrimaryActivity {
case .running: return .shimmer
case let .waiting(task): return .ionizing(taskID: task.id)
case .completed, .terminated, .idle: return .none
@@ -352,22 +321,6 @@ struct ActivityCard: View {
// MARK: - 动画
-/// 逐帧更新布局高度, 让相邻区块和窗口同步调整
-private struct ActivityCardHeight: AnimatableModifier {
- var height: CGFloat
-
- var animatableData: CGFloat {
- get { height }
- set { height = newValue }
- }
-
- func body(content: Content) -> some View {
- content
- .frame(height: height, alignment: .top)
- .clipped()
- }
-}
-
/// 用展开进度控制显隐, 让动画中途反向时保持连贯
private struct ActivityTokenReveal: AnimatableModifier {
var progress: CGFloat
@@ -407,11 +360,13 @@ private struct ActivityCardButtonStyle: ButtonStyle {
private struct ActivityCardContent {
let symbolName: String
let tint: Color
- let title: String
let detail: String?
let otherTaskCount: Int
let isAnonymous: Bool
var tokenUsage: TokenUsage?
+ let header: [String]
+ var recent: String?
+ var detailSupplement: String?
}
struct ActivityAnonymousIcon: View {
diff --git a/CodexBar/Views/Menu/ActivityCenterView.swift b/CodexBar/Views/Menu/ActivityCenterView.swift
index 1c9a8c6..4d1c7fe 100644
--- a/CodexBar/Views/Menu/ActivityCenterView.swift
+++ b/CodexBar/Views/Menu/ActivityCenterView.swift
@@ -49,6 +49,10 @@ struct ActivityCenterView: View {
@ObservedObject var presentationState: ActivityCenterPresentationState
@ObservedObject var mainPanelSettings: MainPanelSettings
+ private var allowsAnimations: Bool {
+ presentationState.isPresented && mainPanelSettings.areAnimationsEnabled
+ }
+
var body: some View {
content(now: presentationState.timelineDate)
.frame(
@@ -73,8 +77,8 @@ struct ActivityCenterView: View {
snapshot: ActivitySnapshot
) -> CGSize {
let visibleSectionCounts = [
- snapshot.waitingTasks.count,
- snapshot.runningTasks.count,
+ snapshot.panelWaitingTasks.count,
+ snapshot.panelRunningTasks.count,
snapshot.recentCompletions.count,
snapshot.recentTerminations.count
].filter { $0 > 0 }
@@ -100,23 +104,23 @@ struct ActivityCenterView: View {
ScrollView(.vertical) {
VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {
- if !activityMonitor.snapshot.waitingTasks.isEmpty {
+ if !activityMonitor.snapshot.panelWaitingTasks.isEmpty {
taskSection(
title: "activity-center.section.waiting",
symbolName: "hand.raised.fill",
tint: .orange,
- tasks: activityMonitor.snapshot.waitingTasks,
+ tasks: activityMonitor.snapshot.panelWaitingTasks,
now: now,
isWaiting: true
)
}
- if !activityMonitor.snapshot.runningTasks.isEmpty {
+ if !activityMonitor.snapshot.panelRunningTasks.isEmpty {
taskSection(
title: "activity-center.section.running",
symbolName: "bolt.fill",
tint: .blue,
- tasks: activityMonitor.snapshot.runningTasks,
+ tasks: activityMonitor.snapshot.panelRunningTasks,
now: now,
isWaiting: false
)
@@ -130,7 +134,7 @@ struct ActivityCenterView: View {
terminationSection(now: now)
}
}
- .animation(.codexStatus, value: activityMonitor.snapshot)
+ .animation(allowsAnimations ? .codexStatus : nil, value: activityMonitor.snapshot)
.padding(.horizontal, Metrics.horizontalPadding)
.padding(.vertical, Metrics.verticalPadding)
}
@@ -148,7 +152,8 @@ struct ActivityCenterView: View {
Text(headerSummary)
.font(.caption2.monospacedDigit())
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: headerSummary, enabled: allowsAnimations)
.lineLimit(1)
}
.padding(.horizontal, Metrics.horizontalPadding)
@@ -158,11 +163,11 @@ struct ActivityCenterView: View {
private var headerSummary: String {
let snapshot = activityMonitor.snapshot
var components = [String]()
- if snapshot.waitingCount > 0 {
- components.append(String(localized: "activity-center.summary.waiting", defaultValue: "\(snapshot.waitingCount, specifier: "%lld")"))
+ if snapshot.panelWaitingTasks.count > 0 {
+ components.append(String(localized: "activity-center.summary.waiting", defaultValue: "\(snapshot.panelWaitingTasks.count, specifier: "%lld")"))
}
- if snapshot.runningCount > 0 {
- components.append(String(localized: "activity-center.summary.running", defaultValue: "\(snapshot.runningCount, specifier: "%lld")"))
+ if snapshot.panelRunningTasks.count > 0 {
+ components.append(String(localized: "activity-center.summary.running", defaultValue: "\(snapshot.panelRunningTasks.count, specifier: "%lld")"))
}
if snapshot.activeCount == 0 {
if !snapshot.recentCompletions.isEmpty {
@@ -237,7 +242,8 @@ struct ActivityCenterView: View {
Text(verbatim: "\(count)")
.font(.caption2.monospacedDigit())
- .foregroundStyle(.tertiary)
+ .foregroundStyle(Color(nsColor: .tertiaryLabelColor))
+ .numericTransition(value: count, comparison: Double(count), enabled: allowsAnimations)
}
.frame(height: Metrics.sectionHeaderHeight)
@@ -285,7 +291,7 @@ struct ActivityCenterView: View {
private func terminationRow(_ termination: ActivityTermination, now: Date) -> some View {
row(
- symbolName: "xmark.circle.fill",
+ symbolName: termination.isFailure ? "exclamationmark.circle.fill" : "xmark.circle.fill",
tint: .red,
projectName: termination.projectName,
modelName: termination.modelName,
@@ -335,10 +341,9 @@ struct ActivityCenterView: View {
ActivityStatusText(
text: detail,
tint: tint,
- effect: presentationState.isPresented
- && mainPanelSettings.areAnimationsEnabled
- ? effect : .none
+ effect: allowsAnimations ? effect : .none
)
+ .numericTransition(value: detail, enabled: allowsAnimations)
if let tokenUsage {
Spacer(minLength: 0)
TokenUsageText(usage: tokenUsage)
@@ -370,7 +375,8 @@ struct ActivityCenterView: View {
) {
Text(metadata)
.font(.caption2)
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: metadata, enabled: allowsAnimations)
.lineLimit(1)
.truncationMode(.middle)
}
@@ -383,9 +389,7 @@ struct ActivityCenterView: View {
now: Date,
isWaiting: Bool
) -> String {
- let components = isWaiting
- ? ActivityDisplayFormat.waitingDetailComponents(for: task, now: now)
- : ActivityDisplayFormat.runningDetailComponents(for: task, now: now)
+ let components = ActivityDisplayFormat.liveSummaryComponents(for: task, now: now, waiting: isWaiting)
return components.joined(separator: " • ")
}
diff --git a/CodexBar/Views/Menu/ActivityStatusText.swift b/CodexBar/Views/Menu/ActivityStatusText.swift
index f920d37..904809b 100644
--- a/CodexBar/Views/Menu/ActivityStatusText.swift
+++ b/CodexBar/Views/Menu/ActivityStatusText.swift
@@ -10,15 +10,17 @@ struct ActivityStatusText: View {
let text: String
let tint: Color
let effect: Effect
+ var lineLimit: Int? = 1
+ var supplement: String?
var body: some View {
- Text(text)
+ label
.foregroundStyle(tint)
.overlay {
if effect == .shimmer {
ActivityStatusShimmer()
.mask {
- Text(text)
+ label
.foregroundStyle(.white)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
@@ -26,7 +28,7 @@ struct ActivityStatusText: View {
}
}
.font(.caption2)
- .lineLimit(1)
+ .lineLimit(lineLimit)
.truncationMode(.tail)
.anchorPreference(key: ActivityIonizationSourceKey.self, value: .bounds) { bounds in
if case let .ionizing(taskID) = effect {
@@ -35,6 +37,15 @@ struct ActivityStatusText: View {
return []
}
}
+
+ @ViewBuilder
+ private var label: some View {
+ if let supplement {
+ ActivitySummaryText(components: [text, supplement], supplementaryLineLimit: 1)
+ } else {
+ Text(text)
+ }
+ }
}
extension View {
@@ -156,3 +167,25 @@ private struct ActivityStatusShimmer: View {
}
}
}
+
+/// 附加信息放不下时整体换行, 避免分隔点单独留在行首或行尾
+struct ActivitySummaryText: View {
+ let components: [String]
+ var supplementaryLineLimit: Int?
+
+ var body: some View {
+ ViewThatFits(in: .horizontal) {
+ Text(components.joined(separator: " • "))
+ .fixedSize()
+ VStack(alignment: .leading, spacing: 2) {
+ ForEach(Array(components.enumerated()), id: \.offset) { index, component in
+ Text(component)
+ .lineLimit(index == 0 ? nil : supplementaryLineLimit)
+ .truncationMode(.tail)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ }
+ }
+}
diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
index fb28b59..9e8ca8e 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
@@ -147,6 +147,7 @@ struct EmptyDataPanel: View {
/// 多个 limit 的额度区, 使用 stale 透明度标记缓存回退数据
struct QuotaLimitsSection: View {
+ @Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations
let limits: [CodexQuotaLimitSnapshot]
let credits: RateLimitCreditsSnapshot?
let resetCreditsAvailableCount: Int?
@@ -252,6 +253,7 @@ struct QuotaLimitsSection: View {
.font(.caption2.weight(.medium))
.monospacedDigit()
.foregroundStyle(tint)
+ .numericTransition(value: text, enabled: allowsAnimations)
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
.padding(.horizontal, 6)
@@ -262,6 +264,7 @@ struct QuotaLimitsSection: View {
/// 底部更新时间行, 同时承载 Sparkle 被动更新提示
struct UpdatedAtRow: View {
+ @Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations
let snapshot: CodexQuotaSnapshot
let countdownStartedAt: Date
let countdownInterval: TimeInterval
@@ -285,7 +288,7 @@ struct UpdatedAtRow: View {
Text(Self.timeFormatter.string(from: snapshot.generatedAt))
.monospacedDigit()
- .contentTransition(.numericText())
+ .numericTransition(value: snapshot.generatedAt, comparison: snapshot.generatedAt.timeIntervalSinceReferenceDate, enabled: allowsAnimations)
.foregroundStyle(Self.secondaryTextColor)
}
.font(.caption2)
@@ -296,9 +299,9 @@ struct UpdatedAtRow: View {
if let updateMessage {
Text(updateMessage)
.font(.caption2.monospacedDigit())
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
.lineLimit(1)
- .contentTransition(.opacity)
+ .numericTransition(value: updateMessage, enabled: allowsAnimations)
.transition(.opacity)
.onTapGesture(count: 2, perform: startUpdate)
}
diff --git a/CodexBar/Views/Menu/QuotaRow.swift b/CodexBar/Views/Menu/QuotaRow.swift
index b8f6cf8..dccdbe3 100644
--- a/CodexBar/Views/Menu/QuotaRow.swift
+++ b/CodexBar/Views/Menu/QuotaRow.swift
@@ -4,6 +4,7 @@ import SwiftUI
struct QuotaRow: View {
let window: QuotaWindow
@Environment(\.mainPanelEntranceAnimationsEnabled) private var animatesEntrance
+ @Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations
@State private var revealedPercent: Double = 0
var body: some View {
@@ -31,7 +32,8 @@ struct QuotaRow: View {
Text(resetText)
.font(.caption2.monospacedDigit())
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: resetText, comparison: window.resetsAt?.timeIntervalSinceReferenceDate, enabled: allowsAnimations)
.lineLimit(1)
.minimumScaleFactor(0.75)
.allowsTightening(true)
diff --git a/CodexBar/Views/Menu/ResetCreditsPanelView.swift b/CodexBar/Views/Menu/ResetCreditsPanelView.swift
index 485dcb9..ce3a48b 100644
--- a/CodexBar/Views/Menu/ResetCreditsPanelView.swift
+++ b/CodexBar/Views/Menu/ResetCreditsPanelView.swift
@@ -35,7 +35,6 @@ nonisolated struct ResetCreditsPanelContext: Equatable {
/// 重置次数侧边详情, 按过期时间从近到远展示
struct ResetCreditsPanelView: View {
let context: ResetCreditsPanelContext
- @Environment(\.colorScheme) private var colorScheme
var body: some View {
let groups = expirationGroups
@@ -159,6 +158,7 @@ struct ResetCreditsPanelView: View {
Text(text)
.font(.caption2.monospacedDigit().weight(.semibold))
.foregroundStyle(Color.codexLabel)
+ .numericTransition(value: text)
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
}
@@ -175,6 +175,7 @@ struct ResetCreditsPanelView: View {
return Text(LocalizedStringResource("banked-reset.available-count", defaultValue: "\(group.count, specifier: "%lld")"))
.font(.caption2.monospacedDigit().weight(.semibold))
.foregroundStyle(tint)
+ .numericTransition(value: group.count, comparison: Double(group.count))
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
.padding(.horizontal, 6)
diff --git a/CodexBar/Views/Menu/TokenCountText.swift b/CodexBar/Views/Menu/TokenCountText.swift
index 10362bd..4e031f4 100644
--- a/CodexBar/Views/Menu/TokenCountText.swift
+++ b/CodexBar/Views/Menu/TokenCountText.swift
@@ -45,7 +45,7 @@ struct TokenUsageText: View {
Text(verbatim: "tokens")
.font(.caption2)
}
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
.fixedSize()
}
}
diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swift
index 7dae279..c5393d9 100644
--- a/CodexBar/Views/Menu/UsageHeatmap.swift
+++ b/CodexBar/Views/Menu/UsageHeatmap.swift
@@ -30,6 +30,7 @@ struct UsageHeatmap: View {
let onScreenFrameChange: (CGRect?) -> Void
@Binding var selection: UsageHeatmapSelection?
@Environment(\.mainPanelEntranceAnimationsEnabled) private var animatesEntrance
+ @Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations
@State private var areSquaresRevealed = false
@State private var entranceStartedAt: TimeInterval?
@State private var snapSelection: UsageHeatmapSelection?
@@ -77,7 +78,8 @@ struct UsageHeatmap: View {
if let dateRangeText {
Text(dateRangeText)
.font(.caption2.monospacedDigit())
- .foregroundStyle(.tertiary)
+ .foregroundStyle(Color(nsColor: .tertiaryLabelColor))
+ .numericTransition(value: dateRangeText, enabled: allowsAnimations)
.lineLimit(1)
}
}
diff --git a/CodexBar/Views/Menu/UsageSummaryView.swift b/CodexBar/Views/Menu/UsageSummaryView.swift
index d23509e..522f671 100644
--- a/CodexBar/Views/Menu/UsageSummaryView.swift
+++ b/CodexBar/Views/Menu/UsageSummaryView.swift
@@ -4,6 +4,7 @@ import SwiftUI
/// Token 摘要和近期用量热力图的组合区
struct UsageSummaryView: View {
+ @Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations
let usage: CodexUsageSnapshot?
let isStale: Bool
let showsActivity: Bool
@@ -53,8 +54,8 @@ struct UsageSummaryView: View {
.onChange(of: hoverContext) { _, context in
onHoverContextChange(context)
}
- .animation(Metrics.statusAnimation, value: usage)
- .animation(Metrics.statusAnimation, value: days)
+ .animation(allowsAnimations ? Metrics.statusAnimation : nil, value: usage)
+ .animation(allowsAnimations ? Metrics.statusAnimation : nil, value: days)
}
@ViewBuilder
@@ -107,6 +108,7 @@ struct UsageSummaryView: View {
metric(label: label) {
if let value {
TokenCountText(tokens: value)
+ .foregroundStyle(Color.codexLabel)
.minimumScaleFactor(0.8)
} else {
Text(verbatim: "--")
@@ -127,6 +129,8 @@ struct UsageSummaryView: View {
metric(label: label) {
Text(value)
.font(.caption.monospacedDigit().weight(.semibold))
+ .foregroundStyle(Color.codexLabel)
+ .numericTransition(value: value, enabled: allowsAnimations)
.lineLimit(1)
.minimumScaleFactor(0.8)
}
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 6101372..3f3b955 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -5,6 +5,7 @@ import SwiftUI
struct AppSettingsView: View {
@EnvironmentObject private var statusViewModel: CodexStatusViewModel
@EnvironmentObject private var appUpdater: AppUpdater
+ @EnvironmentObject private var animationState: SettingsWindowAnimationState
@StateObject private var loginItemSettings = LoginItemSettings()
@StateObject private var codexVersions = CodexVersionViewModel()
@ObservedObject var syncSettings: SyncSettings
@@ -568,9 +569,9 @@ private extension AppSettingsView {
SettingsIndentedRow(alignment: .top) {
Text(caption.message)
.font(.caption)
- .foregroundStyle(caption.isError ? .red : .secondary)
+ .foregroundStyle(caption.isError ? Color.red : Color.codexSecondaryLabel)
.fixedSize(horizontal: false, vertical: true)
- .contentTransition(.opacity)
+ .numericTransition(value: caption.message, enabled: animationState.allowsAnimations)
Spacer(minLength: 8)
@@ -675,7 +676,8 @@ private extension AppSettingsView {
} else if let lastSyncText {
Text(lastSyncText)
.font(.caption.monospacedDigit())
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: lastSyncText, enabled: animationState.allowsAnimations)
.lineLimit(1)
.transition(.opacity)
}
@@ -892,10 +894,9 @@ private extension AppSettingsView {
Text(status.text)
.font(status.isVersionLabel ? .body.monospacedDigit() : .body)
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
.lineLimit(1)
- .contentTransition(.opacity)
- .animation(Metrics.statusAnimation, value: status.text)
+ .numericTransition(value: status.text, enabled: animationState.allowsAnimations)
if appUpdater.availableUpdateMessage != nil {
Button {
diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swift
index f865e54..a67dc4f 100644
--- a/CodexBar/Views/Settings/CodexVersionSection.swift
+++ b/CodexBar/Views/Settings/CodexVersionSection.swift
@@ -107,7 +107,8 @@ struct CodexVersionSection: View {
Text(info.version ?? String(localized: "codex.version.unknown"))
.monospacedDigit()
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: info.version, enabled: animationState.allowsAnimations)
}
CopyablePathText(path: info.socketPath, isCopied: copiedPathResetTasks["shared"] != nil)
.onTapGesture { copyPathToPasteboard(info.socketPath, key: "shared") }
@@ -137,10 +138,9 @@ struct CodexVersionSection: View {
VStack(alignment: .trailing, spacing: 3) {
Text(item.displayVersion)
.font(hasVersion ? .body.monospacedDigit() : .body)
- .foregroundStyle(hasVersion ? .secondary : .tertiary)
+ .foregroundStyle(Color(nsColor: hasVersion ? .secondaryLabelColor : .tertiaryLabelColor))
.lineLimit(1)
- .contentTransition(.opacity)
- .animation(Metrics.statusAnimation, value: item.displayVersion)
+ .numericTransition(value: item.displayVersion, enabled: animationState.allowsAnimations)
if let path = item.path {
CopyablePathText(path: path, isCopied: isPathCopied)
diff --git a/CodexBar/Views/Settings/RebuildDatePicker.swift b/CodexBar/Views/Settings/RebuildDatePicker.swift
index 27607a7..d8d4e7d 100644
--- a/CodexBar/Views/Settings/RebuildDatePicker.swift
+++ b/CodexBar/Views/Settings/RebuildDatePicker.swift
@@ -48,7 +48,8 @@ struct RebuildDatePicker: View {
}
}
.font(.caption.monospacedDigit().weight(.medium))
- .foregroundStyle(.primary)
+ .foregroundStyle(Color.codexLabel)
+ .numericTransition(value: selection?.displayText)
.lineLimit(1)
.minimumScaleFactor(0.9)
@@ -97,6 +98,8 @@ struct RebuildDatePicker: View {
Text(monthTitle)
.font(.system(.body, design: .rounded).weight(.semibold))
.monospacedDigit()
+ .foregroundStyle(Color.codexLabel)
+ .numericTransition(value: monthTitle, comparison: displayedMonth.timeIntervalSinceReferenceDate)
Spacer()
diff --git a/CodexBar/Views/Settings/TaskGlowOptionsView.swift b/CodexBar/Views/Settings/TaskGlowOptionsView.swift
index 72211f1..9748d75 100644
--- a/CodexBar/Views/Settings/TaskGlowOptionsView.swift
+++ b/CodexBar/Views/Settings/TaskGlowOptionsView.swift
@@ -82,7 +82,8 @@ private struct TaskGlowBrightnessControl: View {
Text(value, format: .percent.precision(.fractionLength(0)))
.font(.system(size: 10, weight: .medium, design: .rounded))
.monospacedDigit()
- .foregroundStyle(.secondary)
+ .foregroundStyle(Color.codexSecondaryLabel)
+ .numericTransition(value: Int((value * 100).rounded()), comparison: value)
.frame(width: 32, alignment: .trailing)
}
.padding(.horizontal, 8)
diff --git a/CodexBar/Views/Shared/LiquidGlassStyle.swift b/CodexBar/Views/Shared/LiquidGlassStyle.swift
index e5631b2..7f4e9c8 100644
--- a/CodexBar/Views/Shared/LiquidGlassStyle.swift
+++ b/CodexBar/Views/Shared/LiquidGlassStyle.swift
@@ -25,6 +25,23 @@ extension Color {
// MARK: - View 修饰符
+extension View {
+ /// 数值比较决定滚动方向, 复合文案按显示内容触发过渡
+ func numericTransition(
+ value: some Equatable,
+ comparison: Double? = nil,
+ enabled: Bool = true
+ ) -> some View {
+ let transition: ContentTransition = if let comparison {
+ .numericText(value: comparison)
+ } else {
+ .numericText()
+ }
+ return contentTransition(enabled ? transition : .identity)
+ .animation(enabled ? .codexStatus : nil, value: value)
+ }
+}
+
/// 自绘 Liquid Glass 背景和 stale 状态修饰
extension View {
func liquidGlassSurface(
diff --git a/CodexBar/Views/Shared/QuotaPalette.swift b/CodexBar/Views/Shared/QuotaPalette.swift
index ad938c8..6288bab 100644
--- a/CodexBar/Views/Shared/QuotaPalette.swift
+++ b/CodexBar/Views/Shared/QuotaPalette.swift
@@ -1,4 +1,3 @@
-import AppKit
import SwiftUI
/// 额度颜色按剩余百分比分档, 菜单栏图标与面板额度条共用同一套阈值和色值
@@ -18,19 +17,4 @@ nonisolated enum QuotaPalette {
static func color(for percent: Int) -> Color {
Color(hex: hex(for: percent))
}
-
- static func nsColor(for percent: Int) -> NSColor {
- NSColor(hex: hex(for: percent))
- }
-}
-
-nonisolated extension NSColor {
- convenience init(hex: Int) {
- self.init(
- red: CGFloat((hex >> 16) & 0xFF) / 255.0,
- green: CGFloat((hex >> 8) & 0xFF) / 255.0,
- blue: CGFloat(hex & 0xFF) / 255.0,
- alpha: 1
- )
- }
}
diff --git a/CodexBarTests/Activity/ActivityLivePresentationTests.swift b/CodexBarTests/Activity/ActivityLivePresentationTests.swift
new file mode 100644
index 0000000..4dc0498
--- /dev/null
+++ b/CodexBarTests/Activity/ActivityLivePresentationTests.swift
@@ -0,0 +1,434 @@
+import Foundation
+import Testing
+
+struct ActivityLivePresentationTests {
+ private let now = TestFixtures.now
+
+ private func message(_ method: String, _ fields: String = "", id: Int? = nil, turn: Bool = true) throws -> ActivityNotification {
+ let identity = id.map { "\"id\":\($0)," } ?? ""
+ let turnField = turn ? #", "turnId":"turn-a""# : ""
+ return try TestFixtures.decode(ActivityNotification.self, """
+ {\(identity)"method":"\(method)","params":{"threadId":"session-a"\(turnField)\(fields.isEmpty ? "" : "," + fields)}}
+ """)
+ }
+
+ private func prepared() throws -> AppServerActivityReducer {
+ var reducer = AppServerActivityReducer()
+ let thread = ActivityThread(id: "session-a", status: ActivityThreadStatus(type: "active", activeFlags: []))
+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: "inProgress")], reviewer: .user, now: now)
+ _ = try reducer.consume(message("turn/started", #""turn":{"id":"turn-a","status":"inProgress"}"#), now: now)
+ return reducer
+ }
+
+ private func summary(_ reducer: AppServerActivityReducer) throws -> ActivityLiveSummary {
+ try #require(reducer.states.values.first?.presentation?.summary)
+ }
+
+ @Test func toolCompletionDoesNotMaskReasoningOrAnswerDeltas() throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/started", #""item":{"id":"cmd","type":"commandExecution","commandActions":[{"type":"read"}]}"#), now: now)
+ #expect(try summary(reducer).current.key == "command-read")
+ _ = try reducer.consume(message("item/completed", """
+ "item":{"id":"cmd","type":"commandExecution","status":"completed","commandActions":[{"type":"read"}]}
+ """), now: now.addingTimeInterval(1))
+ #expect(try summary(reducer).current.key == "processing")
+ let recent = try summary(reducer).recent
+ #expect(recent?.label.key == "action-completed")
+ let events = try reducer.consume(message("item/reasoning/summaryTextDelta", #""itemId":"reason","delta":"private text""#), now: now.addingTimeInterval(2))
+ #expect(events.isEmpty)
+ #expect(try summary(reducer).current.key == "thinking")
+ _ = try reducer.consume(message("item/started", #""item":{"id":"answer","type":"agentMessage","phase":"final_answer"}"#), now: now.addingTimeInterval(3))
+ _ = try reducer.consume(message("item/agentMessage/delta", #""itemId":"answer","delta":"private answer""#), now: now.addingTimeInterval(4))
+ #expect(try summary(reducer).current.key == "answering")
+ #expect(try summary(reducer).recent == recent)
+ }
+
+ @Test func concurrentToolCompletionKeepsOtherToolAndNewerReplyVisible() throws {
+ var live = ActivityLivePresentation()
+ try live.consume(message("turn/started"), at: now)
+ try live.consume(message("item/started", #""item":{"id":"first","type":"fileChange"}"#), at: now)
+ try live.consume(message("item/started", #""item":{"id":"second","type":"imageView"}"#), at: now.addingTimeInterval(1))
+ #expect(live.summary.toolCount == 2)
+ try live.consume(message("item/completed", #""item":{"id":"second","type":"imageView"}"#), at: now.addingTimeInterval(2))
+ #expect(live.summary.current.key == "editing")
+ try live.consume(message("item/agentMessage/delta", #""itemId":"answer""#), at: now.addingTimeInterval(3))
+ try live.consume(message("item/completed", #""item":{"id":"first","type":"fileChange","status":"completed"}"#), at: now.addingTimeInterval(4))
+ #expect(live.summary.current.key == "replying")
+ #expect(live.summary.toolCount == 0)
+ }
+
+ @Test(arguments: [("commandExecution", "command"), ("fileChange", "editing")])
+ func outputAfterReconnectRestoresToolPhaseWithoutInventingInventory(type: String, key: String) throws {
+ var reducer = try prepared()
+ reducer.reconnect(now: now)
+ let thread = ActivityThread(id: "session-a", status: ActivityThreadStatus(type: "active", activeFlags: []))
+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: "inProgress")], reviewer: .user, now: now)
+ let output = try message("item/\(type)/outputDelta", #""itemId":"tool","delta":"output""#)
+ #expect(reducer.consume(output, now: now.addingTimeInterval(1)).isEmpty)
+ #expect(try summary(reducer).current.key == key)
+ #expect(try summary(reducer).toolCount == nil)
+ _ = reducer.consume(output, now: now.addingTimeInterval(2))
+ #expect(try summary(reducer).toolCount == nil)
+ _ = try reducer.consume(message("item/completed", """
+ "item":{"id":"tool","type":"\(type)","status":"completed"}
+ """), now: now.addingTimeInterval(3))
+ #expect(try summary(reducer).current.key == "processing")
+ #expect(try summary(reducer).toolCount == nil)
+ }
+
+ @Test func outputKeepsKnownActionsAndCompletesOnlyItsOwnItem() throws {
+ var live = ActivityLivePresentation()
+ try live.consume(message("turn/started"), at: now)
+ try live.consume(message("item/started", #""item":{"id":"cmd","type":"commandExecution","commandActions":[{"type":"read"}]}"#), at: now)
+ try live.consume(message("item/commandExecution/outputDelta", #""itemId":"cmd""#), at: now.addingTimeInterval(1))
+ #expect(live.summary.current.key == "command-read")
+ try live.consume(message("item/fileChange/outputDelta", #""itemId":"edit""#), at: now.addingTimeInterval(2))
+ try live.consume(message("item/fileChange/outputDelta", #""itemId":"edit""#), at: now.addingTimeInterval(3))
+ #expect(live.summary.toolCount == 2)
+ try live.consume(message("item/completed", #""item":{"id":"cmd","type":"commandExecution","status":"completed"}"#), at: now.addingTimeInterval(4))
+ #expect(live.summary.current.key == "editing")
+ #expect(live.summary.toolCount == 1)
+ try live.consume(message("item/agentMessage/delta", #""itemId":"answer""#), at: now.addingTimeInterval(5))
+ try live.consume(message("item/completed", #""item":{"id":"edit","type":"fileChange","status":"completed"}"#), at: now.addingTimeInterval(6))
+ #expect(live.summary.current.key == "replying")
+ #expect(live.summary.toolCount == 0)
+ }
+
+ @Test func recoveredToolOutputDoesNotClearUserWait() throws {
+ var live = ActivityLivePresentation()
+ try live.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), at: now)
+ try live.consume(message("item/commandExecution/outputDelta", #""itemId":"cmd""#), at: now.addingTimeInterval(1))
+ #expect(live.summary.current.key == "waiting-input")
+ #expect(live.summary.waiting?.since == now)
+ try live.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), at: now.addingTimeInterval(2))
+ #expect(live.summary.current.key == "command")
+ }
+
+ @Test(arguments: [
+ (["read"], "command-read"), (["listFiles"], "command-listFiles"), (["search"], "command-search"),
+ (["search", "read", "read"], "command-read-search"), (["search", "listFiles"], "command-listFiles-search"),
+ (["listFiles", "read"], "command-read-listFiles"), (["search", "listFiles", "read"], "command-read-listFiles-search"),
+ (["read", "unknown"], "command"), (["future"], "command"), ([], "command")
+ ])
+ func commandActionsUseServerClassification(actions: [String], key: String) {
+ let item = ActivityItem(id: "cmd", type: "commandExecution", commandActions: actions.map { .init(type: $0) })
+ #expect(item.liveLabel?.key == key)
+ if actions.contains("read"), actions.contains("unknown") {
+ #expect(item.liveLabel?.detail != nil)
+ }
+ }
+
+ @Test(arguments: [
+ (["search", "read"], "actions-read-search"),
+ (["read", "search"], "actions-read-search"),
+ (["search", "unknown", "read", "read"], "actions-read-search"),
+ (["search", "listFiles", "read", "listFiles"], "actions-read-listFiles-search"),
+ ([], nil), (["unknown", "future"], nil)
+ ] as [([String], String?)])
+ func commandCompletionLocalizesAndOrdersKnownActions(actions: [String], detailKey: String?) {
+ let item = ActivityItem(
+ id: "cmd", type: "commandExecution", status: "failed",
+ commandActions: actions.map { .init(type: $0) }
+ )
+ #expect(item.liveCompletionLabel?.key == (detailKey == nil ? "tool-failed" : "action-failed"))
+ #expect(item.liveCompletionLabel?.detail == detailKey.map { ActivityLiveLabel($0).text })
+ }
+
+ @Test(arguments: ["completed", "failed", "declined"])
+ func recentCommandOutcomesUseLocalizedActionDetails(status: String) throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/completed", """
+ "item":{"id":"cmd","type":"commandExecution","status":"\(status)","commandActions":[{"type":"search"},{"type":"read"},{"type":"read"}]}
+ """), now: now)
+ let recent = try #require(try summary(reducer).recent)
+ #expect(recent.label.key == "action-" + status)
+ #expect(recent.label.detail == String(localized: "activity.live.actions-read-search"))
+ let action = String(localized: "activity.live.actions-read-search")
+ let expected = switch status {
+ case "completed": String(localized: "activity.live.action-completed", defaultValue: "\(action)")
+ case "failed": String(localized: "activity.live.action-failed", defaultValue: "\(action)")
+ default: String(localized: "activity.live.action-declined", defaultValue: "\(action)")
+ }
+ #expect(recent.label.text == expected)
+ #expect(!recent.label.text.contains(" • "))
+ }
+
+ @Test(arguments: ["mcpToolCall", "dynamicToolCall"])
+ func completionPreservesActualToolNames(type: String) {
+ let item = ActivityItem(
+ id: "tool", type: type, status: "failed", tool: "search/read",
+ commandActions: [.init(type: "read")]
+ )
+ #expect(item.liveCompletionLabel?.key == "tool-failed")
+ #expect(item.liveCompletionLabel?.detail == "search/read")
+ let name = "search/read"
+ #expect(item.liveCompletionLabel?.text == String(localized: "activity.live.named-tool-failed", defaultValue: "\(name)"))
+ }
+
+ @Test func currentToolDetailsUseLocalizedTemplates() throws {
+ let name = "web.search"
+ let tool = ActivityItem(id: "tool", type: "mcpToolCall", tool: name)
+ #expect(tool.liveLabel?.text == String(localized: "activity.live.calling-named-tool", defaultValue: "\(name)"))
+ let command = ActivityItem(
+ id: "cmd", type: "commandExecution", commandActions: ["search", "unknown", "read"].map { .init(type: $0) }
+ )
+ let label = try #require(command.liveLabel)
+ let detail = try #require(label.detail)
+ #expect(label.text == String(localized: "activity.live.command-with-actions", defaultValue: "\(detail)"))
+ #expect(!label.text.contains(" • "))
+ }
+
+ @Test func modelChangePreservesRouteDetails() throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("model/rerouted", #""fromModel":"model-a","toModel":"model-b""#), now: now)
+ let label = try #require(try summary(reducer).recent?.label)
+ let route = "model-a → model-b"
+ #expect(label.text == String(localized: "activity.live.model-changed-detail", defaultValue: "\(route)"))
+ #expect(label.key == "model-changed")
+ #expect(label.detail == route)
+ }
+
+ @Test(arguments: ["tool-completed", "tool-failed", "tool-declined", "calling-tool", "command", "model-changed"])
+ func missingDetailsKeepStandaloneLabels(key: String) {
+ #expect(ActivityLiveLabel(key).text == ActivityLiveLabel(key).localizedText)
+ #expect(ActivityLiveLabel(key, detail: "").text == ActivityLiveLabel(key).localizedText)
+ }
+
+ @Test(arguments: [
+ ("spawnAgent", ("agent-starting", "activity.action.start-subagent")),
+ ("sendInput", ("agent-assigning", "activity.action.assign-subagent")),
+ ("followupTask", ("agent-assigning", "activity.action.assign-subagent")),
+ ("sendMessage", ("agent-contacting", "activity.action.message-subagent")),
+ ("resumeAgent", ("agent-resuming", "activity.action.resume-subagent")),
+ ("wait", ("agent-waiting", "activity.action.wait-subagent")),
+ ("interruptAgent", ("agent-interrupting", "activity.action.interrupt-subagent")),
+ ("closeAgent", ("agent-closing", "activity.action.close-subagent")),
+ ("listAgents", ("agent-querying", "activity.action.query-subagent")),
+ ("future", ("agent-coordinating", "activity.action.coordinate-subagents"))
+ ] as [(String, (String, LocalizedStringResource))], ["completed", "failed", "declined"])
+ func subagentOperationOutcomesDescribeTheCall(
+ operation: (tool: String, expected: (statusKey: String, action: LocalizedStringResource)), status: String
+ ) {
+ let item = ActivityItem(
+ id: "agent", type: "collabAgentToolCall", status: status, tool: operation.tool,
+ agentsStates: ["child": .init(status: "running")]
+ )
+ #expect(item.liveLabel?.key == operation.expected.statusKey)
+ #expect(item.liveCompletionLabel?.key == "action-" + status)
+ #expect(item.liveCompletionLabel?.detail == String(localized: operation.expected.action))
+ #expect(ActivityDisplayFormat.toolActionText(itemType: item.type, toolName: operation.tool) == item.liveCompletionLabel?.detail)
+ }
+
+ @Test(arguments: [
+ ("commandExecution", "activity.action.command"), ("fileChange", "activity.action.edit-files"),
+ ("webSearch", "activity.action.search-web"), ("imageView", "activity.action.view-image"),
+ ("imageGeneration", "activity.action.generate-image"), ("sleep", "activity.action.wait-timer"),
+ ("mcpToolCall", "activity.action.call-tool"), ("dynamicToolCall", "activity.action.call-tool"),
+ ("collabAgentToolCall", "activity.action.coordinate-subagents")
+ ] as [(String, LocalizedStringResource)])
+ func namelessToolTypesHaveReadableFallbacks(type: String, action: LocalizedStringResource) {
+ #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: nil) == String(localized: action))
+ #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: " ") == String(localized: action))
+ }
+
+ @Test(arguments: ["mcpToolCall", "dynamicToolCall", "future", nil] as [String?], ["search/read", "spawnAgent", "commandExecution"])
+ func actualToolNamesAreNeverClassifiedByTheirSpelling(type: String?, tool: String) {
+ #expect(ActivityDisplayFormat.toolActionText(itemType: type, toolName: tool) == tool)
+ }
+
+ @Test func unknownUnnamedToolsDoNotExposeInternalTypes() {
+ #expect(ActivityDisplayFormat.toolActionText(itemType: "futureInternalType", toolName: nil) == nil)
+ #expect(ActivityDisplayFormat.toolActionText(itemType: nil, toolName: nil) == nil)
+ }
+
+ @Test(arguments: [
+ ("form", "waiting-form"), ("openai/form", "waiting-form"), ("openaiForm", "waiting-form"),
+ ("url", "waiting-external"), ("openai/userVerification", "waiting-verification"), ("future", "waiting-service")
+ ])
+ func elicitationWaitsAreSpecificAndEndByRequestID(mode: String, key: String) throws {
+ var reducer = try prepared()
+ let events = try reducer.consume(message("mcpServer/elicitation/request", "\"mode\":\"\(mode)\"", id: 7), now: now)
+ #expect(events.isEmpty)
+ #expect(try summary(reducer).waiting?.label.key == key)
+ #expect(try summary(reducer).waiting?.since == now)
+ _ = try reducer.consume(message("serverRequest/resolved", #""requestId":7"#, turn: false), now: now.addingTimeInterval(4))
+ #expect(try summary(reducer).waiting == nil)
+ #expect(try summary(reducer).recent?.label.key == "request-ended")
+ }
+
+ @Test func unrelatedOutputAndResolvedRequestDoNotClearConcurrentWait() throws {
+ var live = ActivityLivePresentation()
+ try live.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), at: now)
+ try live.consume(message("mcpServer/elicitation/request", #""mode":"url""#, id: 2), at: now.addingTimeInterval(1))
+ try live.consume(message("item/agentMessage/delta", #""itemId":"answer""#), at: now.addingTimeInterval(2))
+ try live.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), at: now.addingTimeInterval(3))
+ #expect(live.summary.waiting?.label.key == "waiting-external")
+ try live.consume(message("serverRequest/resolved", #""requestId":999"#, turn: false), at: now.addingTimeInterval(4))
+ #expect(live.summary.waiting?.since == now.addingTimeInterval(1))
+ }
+
+ @Test func nonblockingInputAndUncorrelatedElicitationNeverBecomeWaiting() throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":false"#, id: 1), now: now)
+ #expect(try summary(reducer).waiting == nil)
+ _ = try reducer.consume(message("mcpServer/elicitation/request", #""mode":"url""#, id: 2, turn: false), now: now)
+ #expect(try summary(reducer).waiting == nil)
+ }
+
+ @Test func reconnectDropsUnverifiablePhasesAndWaitingDuration() throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), now: now)
+ reducer.reconnect(now: now.addingTimeInterval(10))
+ #expect(reducer.states.values.first?.presentation == nil)
+ let thread = ActivityThread(id: "session-a", status: ActivityThreadStatus(type: "active", activeFlags: ["waitingOnUserInput"]))
+ _ = reducer.reconcile(thread: thread, turns: [ActivityTurn(id: "turn-a", status: "inProgress")], reviewer: .user, now: now.addingTimeInterval(12))
+ #expect(try summary(reducer).waiting?.label.key == "waiting-input")
+ #expect(try summary(reducer).waiting?.since == nil)
+ #expect(try summary(reducer).toolCount == nil)
+ }
+
+ @Test(arguments: ["approved", "denied", "timedOut", "aborted"])
+ func automaticReviewIsNotUserWaitingAndCompletes(status: String) throws {
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/autoApprovalReview/started", #""reviewId":"review","review":{"status":"inProgress"}"#), now: now)
+ #expect(try summary(reducer).current.key == "auto-approval")
+ #expect(try summary(reducer).waiting == nil)
+ let events = try reducer.consume(message("item/autoApprovalReview/completed", "\"reviewId\":\"review\",\"review\":{\"status\":\"\(status)\"}"), now: now.addingTimeInterval(1))
+ #expect(events.isEmpty)
+ #expect(try summary(reducer).current.key == "processing")
+ #expect(try summary(reducer).recent?.label.key.hasPrefix("approval-") == true)
+ }
+
+ @Test func presentationEventsNeverProduceHistoricalRecords() throws {
+ var reducer = try prepared()
+ let messages = try [
+ message("turn/plan/updated", #""plan":[{"step":"private","status":"completed"}]"#),
+ message("turn/diff/updated", #""diff":"private diff""#),
+ message("mcpServer/startupStatus/updated", #""name":"test","status":"starting""#),
+ message("model/rerouted", #""fromModel":"old","toModel":"new""#),
+ message("modelProvider/authRecoveryStarted"),
+ message("modelProvider/authRecoveryCompleted"),
+ message("model/safetyBuffering/updated", #""showBufferingUi":true"#),
+ message("hook/started", #""run":{"id":"hook","status":"running","executionMode":"sync"}"#)
+ ]
+ for notification in messages {
+ #expect(ActivityNotification.category(for: notification.method) == .presentation)
+ #expect(reducer.consume(notification, now: now).isEmpty)
+ }
+ #expect(try summary(reducer).planCompleted == 1)
+ #expect(try summary(reducer).planTotal == 1)
+ #expect(try summary(reducer).waiting == nil)
+ #expect(reducer.tokenTurns.isEmpty)
+ }
+
+ @Test(arguments: ["completed", "failed", "declined", "unknown"])
+ func toolOutcomeDoesNotAssumeSuccess(status: String) {
+ let item = ActivityItem(id: "image", type: "imageGeneration", status: status)
+ #expect(item.liveCompletionLabel?.key == (status == "unknown" ? nil : "image-" + status))
+ }
+
+ @Test func displayWaitingDoesNotChangeApprovalOrProtectionState() throws {
+ let event = TestFixtures.event()
+ var task = ActivityTask(
+ displayID: UUID(),
+ key: ActivityTaskKey(event: event),
+ event: event,
+ state: .running,
+ startedAt: now,
+ progressGeneration: 0
+ )
+ var reducer = try prepared()
+ _ = try reducer.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), now: now)
+ let state = try #require(reducer.states.values.first)
+ task.mergeExecutionLifecycle(state, owner: ActivityExecutionKey(agentID: nil, turnID: "turn-a"))
+ let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [task.snapshot], recentCompletions: [], recentTerminations: [])
+ #expect(task.state == .running)
+ #expect(snapshot.waitingCount == 0)
+ #expect(snapshot.panelWaitingTasks.count == 1)
+ #expect(snapshot.panelRunningTasks.isEmpty)
+ #expect(snapshot.primaryActivity == .running(task.snapshot))
+ #expect(snapshot.panelPrimaryActivity == .waiting(task.snapshot))
+ let summary = ActivityDisplayFormat.liveSummaryComponents(for: task.snapshot, now: now)
+ #expect(summary.count == 2)
+ #expect(summary.first == ActivityLiveLabel("elapsed-running").text + " " + CodexDurationFormat.activityText(for: 0))
+ #expect(summary.last == ActivityLiveLabel("elapsed-waiting").text + " " + CodexDurationFormat.activityText(for: 0))
+ }
+
+ @Test func authoritativeIdleClearsRequestsWithoutInventingApproval() throws {
+ var live = ActivityLivePresentation()
+ try live.consume(message("mcpServer/elicitation/request", #""mode":"form""#, id: 1), at: now)
+ live.reconcile(status: ActivityThreadStatus(type: "idle"))
+ #expect(live.summary.waiting == nil)
+ #expect(live.summary.recent == nil)
+ }
+
+ @Test func temporaryOperationsEndWithoutClearingOtherOperations() throws {
+ var live = ActivityLivePresentation()
+ try live.consume(message("modelProvider/authRecoveryStarted"), at: now)
+ try live.consume(message("model/safetyBuffering/updated", #""showBufferingUi":true"#), at: now.addingTimeInterval(1))
+ #expect(live.summary.current.key == "buffering")
+ try live.consume(message("model/safetyBuffering/updated", #""showBufferingUi":false"#), at: now.addingTimeInterval(2))
+ #expect(live.summary.current.key == "recovering-auth")
+ try live.consume(message("modelProvider/authRecoveryCompleted"), at: now.addingTimeInterval(3))
+ #expect(live.summary.current.key == "processing")
+ #expect(live.summary.recent?.label.key == "auth-recovery-ended")
+ #expect(live.summary.waiting == nil)
+ }
+
+ @Test func childWaitSurvivesRootOutputUntilChildLifecycleResolvesIt() throws {
+ let event = TestFixtures.event()
+ var task = ActivityTask(
+ displayID: UUID(),
+ key: ActivityTaskKey(event: event),
+ event: event,
+ state: .running,
+ startedAt: now,
+ progressGeneration: 0
+ )
+ var root = ActivityLivePresentation()
+ try root.consume(message("item/agentMessage/delta", #""itemId":"answer""#), at: now.addingTimeInterval(4))
+ var child = ActivityLivePresentation()
+ try child.consume(message("item/tool/requestUserInput", #""isBlocking":true"#, id: 1), at: now)
+ task.executions[ActivityExecutionKey(agentID: nil, turnID: "turn-a")] = ActivityExecution(presentation: root)
+ let childOwner = ActivityExecutionKey(agentID: "child", turnID: "child-turn")
+ task.executions[childOwner] = ActivityExecution(presentation: child)
+ #expect(task.snapshot.presentation?.waiting?.since == now)
+ #expect(task.snapshot.presentation?.current.key == "waiting-input")
+ try child.consume(message("serverRequest/resolved", #""requestId":1"#, turn: false), at: now.addingTimeInterval(5))
+ task.executions[childOwner]?.presentation = child
+ #expect(task.snapshot.presentation?.waiting == nil)
+ #expect(task.snapshot.presentation?.current.key == "replying")
+ }
+
+ @Test func failedTurnKeepsItsOutcomeWithoutChangingTerminalPolicy() throws {
+ var reducer = try prepared()
+ let events = try reducer.consume(message("turn/completed", #""turn":{"id":"turn-a","status":"failed"}"#), now: now)
+ let state = try #require(reducer.states.values.first)
+ #expect(state.turnStatus == "failed")
+ #expect(state.presentation == nil)
+ #expect(events.first?.eventKind == .turnAborted)
+ #expect(events.first?.source?.turnStatus == "failed")
+ let event = TestFixtures.event()
+ var task = ActivityTask(
+ displayID: UUID(),
+ key: ActivityTaskKey(event: event),
+ event: event,
+ state: .running,
+ startedAt: now,
+ progressGeneration: 0
+ )
+ _ = ActivityMonitor.mergeLifecycleBackfill(from: state, into: &task)
+ #expect(task.terminalFailed)
+ }
+
+ @Test func mixedCommandActionsResolveTheExplicitLocalizedKey() {
+ let item = ActivityItem(
+ id: "cmd", type: "commandExecution",
+ commandActions: ["search", "unknown", "read", "read"].map { .init(type: $0) }
+ )
+ #expect(item.liveLabel?.key == "command")
+ #expect(item.liveLabel?.detail == String(localized: "activity.live.actions-read-search"))
+ let actions = String(localized: "activity.live.actions-read-search")
+ #expect(item.liveLabel?.text == String(localized: "activity.live.command-with-actions", defaultValue: "\(actions)"))
+ }
+}
diff --git a/CodexBarTests/Activity/ActivityTaskTests.swift b/CodexBarTests/Activity/ActivityTaskTests.swift
index 730938c..8c72269 100644
--- a/CodexBarTests/Activity/ActivityTaskTests.swift
+++ b/CodexBarTests/Activity/ActivityTaskTests.swift
@@ -29,7 +29,7 @@ struct ActivityTaskTests {
nameless.source = AppServerEventSource(method: "item/started", threadID: "session-a", itemType: "fileChange")
task.mergeMetadata(from: nameless)
#expect(task.snapshot.toolName == nil)
- #expect(task.snapshot.toolDisplayName == "fileChange")
+ #expect(task.snapshot.toolDisplayName == String(localized: "activity.action.edit-files"))
var approval = ActivityRecord(
timestamp: TestFixtures.now.addingTimeInterval(2), name: ActivityEventKind.approvalRequested.rawValue,
@@ -41,8 +41,7 @@ struct ActivityTaskTests {
let enteredWaiting = task.recordApprovalRequest(from: approval)
#expect(enteredWaiting)
#expect(task.snapshot.toolName == nil)
- #expect(task.snapshot.toolDisplayName == "commandExecution")
- #expect(ActivityDisplayFormat.waitingDetailComponents(for: task.snapshot, now: approval.timestamp).first == "commandExecution")
+ #expect(task.snapshot.toolDisplayName == String(localized: "activity.action.command"))
}
@Test func anonymousTaskHasNoProtectionIdentityOrPreciseDuration() {
@@ -141,7 +140,7 @@ struct ActivityTaskTests {
private func healthyLifecycle(startedAt: Date? = nil) -> SessionLifecycleState {
SessionLifecycleState(
requestedThreadID: "session-a", turnID: "turn-a", startedAt: startedAt, approvalReviewer: nil, effort: nil,
- lastProgressAt: nil, terminal: nil, readStatus: .complete, hasContext: true
+ lastProgressAt: nil, terminal: nil, readStatus: .complete
)
}
@@ -295,9 +294,9 @@ struct ActivityTaskTests {
let approval = TestFixtures.event(.approvalRequested, agent: "agent", origin: .auxiliary)
let enteredWaiting = task.recordApprovalRequest(from: approval)
#expect(enteredWaiting)
- task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(1)), latestEvent: .toolFinished)
+ task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(1)))
#expect(task.state == .waitingApproval)
- task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(2), agent: "agent", origin: .auxiliary), latestEvent: .toolFinished)
+ task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: TestFixtures.now.addingTimeInterval(2), agent: "agent", origin: .auxiliary))
#expect(task.state == .running)
}
@@ -318,7 +317,7 @@ struct ActivityTaskTests {
@Test func lateApprovalDoesNotUndoConfirmedExecutionProgress() {
var task = makeTask()
let progress = TestFixtures.now.addingTimeInterval(2)
- task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: progress), latestEvent: .toolFinished)
+ task.resumeExecution(from: TestFixtures.event(.toolCompleted, at: progress))
let lateRequestChanged = task.recordApprovalRequest(from: TestFixtures.event(.approvalRequested))
#expect(!lateRequestChanged)
#expect(task.state == .running)
@@ -339,7 +338,7 @@ struct ActivityTaskTests {
private func makeTask(_ event: ActivityRecord = TestFixtures.event()) -> ActivityTask {
ActivityTask(
displayID: UUID(), key: ActivityTaskKey(event: event), event: event,
- state: .running, latestEvent: .promptSubmitted, startedAt: event.timestamp, progressGeneration: 1
+ state: .running, startedAt: event.timestamp, progressGeneration: 1
)
}
}
diff --git a/CodexBarTests/Activity/ActivityTokenUsageTests.swift b/CodexBarTests/Activity/ActivityTokenUsageTests.swift
index e9380c6..f4154ed 100644
--- a/CodexBarTests/Activity/ActivityTokenUsageTests.swift
+++ b/CodexBarTests/Activity/ActivityTokenUsageTests.swift
@@ -15,13 +15,16 @@ struct ActivityTokenUsageTests {
#expect(outputOnly.cacheHitRate == nil)
}
- @Test func rootAndMultipleChildTurnsAreSummedOnce() throws {
+ @Test(arguments: [true, false])
+ func rootAndMultipleChildTurnsAreSummedOnce(explicitRootSession: Bool) throws {
let root = reference("session-a", "turn-a")
let first = reference("child-a", "child-turn-a")
let second = reference("child-a", "child-turn-b")
let third = reference("child-b", "child-turn-c")
let request = request(root: root, children: [first, second, third, first])
- let states = [state(root, input: 100), state(first, input: 200), state(second, input: 300), state(third, input: 400)]
+ var rootState = state(root, input: 100)
+ rootState.rootSessionID = explicitRootSession ? root.threadID : nil
+ let states = [rootState, state(first, input: 200), state(second, input: 300), state(third, input: 400)]
let usage = try #require(request.usage(from: states))
#expect(usage.inputTokens == 1000)
#expect(usage.outputTokens == 40)
@@ -78,7 +81,7 @@ struct ActivityTokenUsageTests {
switch scenario {
case "other-root": childState.rootTurnID = "other-root"
case "other-session": childState.rootSessionID = "other-session"
- case "other-thread": childState.recordedThreadID = "other-thread"
+ case "other-thread": childState = state(reference("other-thread", child.turnID), terminal: nil)
case "unavailable": childState.readStatus = .unavailable
default: childState.tokenUsage = nil
}
@@ -96,7 +99,7 @@ struct ActivityTokenUsageTests {
let key = ActivityTaskKey(event: event)
monitor.tasks[key] = ActivityTask(
displayID: UUID(), key: key, event: event, state: .running,
- latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1
+ startedAt: TestFixtures.now, progressGeneration: 1
)
let root = reference("session-a", "turn-a")
let child = reference("child-a", "child-turn")
@@ -106,14 +109,14 @@ struct ActivityTokenUsageTests {
let initial = [state(root, terminal: nil)]
#expect(monitor.applyActiveTokenUsage(initial))
let running = try #require(monitor.tasks[key]?.snapshot)
- #expect(CodexPrimaryActivity.running(running).tokenUsage?.totalTokens == 110)
+ #expect(running.tokenUsage?.totalTokens == 110)
#expect(!monitor.applyActiveTokenUsage(initial))
monitor.tasks[key]?.state = .waitingApproval
let updated = [state(root, input: 200, terminal: nil), state(child, input: 300)]
#expect(monitor.applyActiveTokenUsage(updated))
let waiting = try #require(monitor.tasks[key]?.snapshot)
- #expect(CodexPrimaryActivity.waiting(waiting).tokenUsage?.totalTokens == 520)
+ #expect(waiting.tokenUsage?.totalTokens == 520)
#expect(monitor.tasks[key]?.state == .waitingApproval)
#expect(monitor.pendingTerminalPresentationEvents.isEmpty)
#expect(monitor.completions.isEmpty)
@@ -138,7 +141,7 @@ struct ActivityTokenUsageTests {
let key = ActivityTaskKey(event: event)
monitor.tasks[key] = ActivityTask(
displayID: UUID(), key: key, event: event, state: .running,
- latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1
+ startedAt: TestFixtures.now, progressGeneration: 1
)
#expect(!monitor.applyActiveTokenUsage([state(reference("session-a", "turn-a"))]))
#expect(monitor.tasks[key]?.tokenUsage == nil)
@@ -176,7 +179,7 @@ struct ActivityTokenUsageTests {
let key = ActivityTaskKey(event: event)
let task = ActivityTask(
displayID: UUID(), key: key, event: event, state: .running,
- latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1
+ startedAt: TestFixtures.now, progressGeneration: 1
)
var transitions: [ActivityTransition] = []
monitor.resolveTerminal(
@@ -188,7 +191,7 @@ struct ActivityTokenUsageTests {
let otherKey = ActivityTaskKey(event: otherEvent)
monitor.tasks[otherKey] = ActivityTask(
displayID: UUID(), key: otherKey, event: otherEvent, state: .running,
- latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1
+ startedAt: TestFixtures.now, progressGeneration: 1
)
monitor.interruptTask(from: otherEvent, source: .bootstrap)
#expect(monitor.completions.first?.tokenUsage == nil)
@@ -209,9 +212,6 @@ struct ActivityTokenUsageTests {
let queryTime = Date()
let terminalReferences = monitor.prepareTerminalTokenUsageReadBatch(now: queryTime)
#expect(terminalReferences.count == 2)
- for reference in terminalReferences {
- #expect(reference.isTerminalUsageOnly)
- }
#expect(monitor.prepareTerminalTokenUsageReadBatch(now: queryTime.addingTimeInterval(1)).isEmpty)
_ = monitor.prepareTerminalTokenUsageReadBatch(now: Date().addingTimeInterval(31))
#expect(monitor.terminalTokenUsageRequests.isEmpty)
@@ -230,7 +230,7 @@ struct ActivityTokenUsageTests {
let firstKey = ActivityTaskKey(event: first)
let task = ActivityTask(
displayID: UUID(), key: firstKey, event: first, state: .running,
- latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1
+ startedAt: TestFixtures.now, progressGeneration: 1
)
var transitions: [ActivityTransition] = []
monitor.resolveTerminal(.completed(at: TestFixtures.now, duration: 1), task: task, key: firstKey, abortFallback: TestFixtures.now, into: &transitions)
@@ -241,7 +241,7 @@ struct ActivityTokenUsageTests {
let secondKey = ActivityTaskKey(event: second)
monitor.tasks[secondKey] = ActivityTask(
displayID: UUID(), key: secondKey, event: second, state: .running,
- latestEvent: .promptSubmitted, startedAt: second.timestamp, progressGeneration: 2
+ startedAt: second.timestamp, progressGeneration: 2
)
let child = TestFixtures.event(.subagentStarted, at: TestFixtures.now.addingTimeInterval(3), turn: "child-turn-b", agent: "child-b")
#expect(monitor.deferUnassociatedSubagentEvent(child, source: .live))
@@ -278,7 +278,7 @@ struct ActivityTokenUsageTests {
let key = ActivityTaskKey(event: event)
let task = ActivityTask(
displayID: UUID(), key: key, event: event, state: .running,
- latestEvent: .promptSubmitted, startedAt: now, progressGeneration: 1
+ startedAt: now, progressGeneration: 1
)
var transitions: [ActivityTransition] = []
monitor.resolveTerminal(
@@ -315,7 +315,7 @@ struct ActivityTokenUsageTests {
let key = ActivityTaskKey(event: event)
let task = ActivityTask(
displayID: UUID(), key: key, event: event, state: .running,
- latestEvent: .promptSubmitted, startedAt: now, progressGeneration: 1
+ startedAt: now, progressGeneration: 1
)
var transitions: [ActivityTransition] = []
if interrupted {
@@ -355,7 +355,7 @@ struct ActivityTokenUsageTests {
SessionLifecycleState(
requestedThreadID: reference.threadID, turnID: reference.turnID, startedAt: TestFixtures.now,
approvalReviewer: nil, effort: nil, lastProgressAt: TestFixtures.now, terminal: terminal,
- rootTurnID: "turn-a", recordedThreadID: reference.threadID, rootSessionID: "session-a",
+ rootTurnID: "turn-a", rootSessionID: "session-a",
tokenUsage: TokenUsage(
inputTokens: input, cachedInputTokens: 20, cacheWriteInputTokens: 0,
outputTokens: 10, reasoningOutputTokens: 2, totalTokens: input + 10
@@ -390,7 +390,6 @@ extension ActivityTokenUsageTests {
key: key,
event: event,
state: .running,
- latestEvent: .promptSubmitted,
startedAt: now.addingTimeInterval(-60),
progressGeneration: 1
)
diff --git a/CodexBarTests/Activity/AppServerActivityTests.swift b/CodexBarTests/Activity/AppServerActivityTests.swift
index ffd6160..6a32178 100644
--- a/CodexBarTests/Activity/AppServerActivityTests.swift
+++ b/CodexBarTests/Activity/AppServerActivityTests.swift
@@ -114,17 +114,17 @@ struct AppServerActivityTests {
let restored = try #require(AppServerEventRecord.decode(from: data).activity)
var task = ActivityTask(
displayID: UUID(), key: ActivityTaskKey(event: restored), event: restored,
- state: .running, latestEvent: .toolStarted, startedAt: now, progressGeneration: 0
+ state: .running, startedAt: now, progressGeneration: 0
)
- #expect(task.snapshot.toolDisplayName == (expectedTool ?? type))
- #expect(ActivityDisplayFormat.eventText(for: task.snapshot).contains(expectedTool ?? type))
+ let expectedDisplay = try #require(ActivityDisplayFormat.toolActionText(itemType: type, toolName: expectedTool))
+ #expect(task.snapshot.toolDisplayName == expectedDisplay)
try task.mergeMetadata(from: #require(ended.first))
- task.latestEvent = .toolFinished
- #expect(ActivityDisplayFormat.eventText(for: task.snapshot).contains(expectedTool ?? type))
+
+ #expect(task.snapshot.toolDisplayName == expectedDisplay)
}
@Test(arguments: ["item/started", "item/completed"])
- func commandActionsPreserveFirstOccurrenceOrderInDisplayedActivity(_ method: String) throws {
+ func commandActionsKeepRawOrderAndLocalizeDisplay(_ method: String) throws {
var reducer = try prepared()
let events = try reducer.consume(message(method, params: """
{"threadId":"main","turnId":"turn","item":{"id":"command","type":"commandExecution","commandActions":[
@@ -141,11 +141,12 @@ struct AppServerActivityTests {
let restored = try #require(AppServerEventRecord.decode(from: data).activity)
let task = ActivityTask(
displayID: UUID(), key: ActivityTaskKey(event: restored), event: restored,
- state: .running, latestEvent: method == "item/started" ? .toolStarted : .toolFinished,
+ state: .running,
startedAt: now, progressGeneration: 0
)
- #expect(task.snapshot.toolDisplayName == "search/read/listFiles")
- #expect(ActivityDisplayFormat.eventText(for: task.snapshot).contains("search/read/listFiles"))
+ #expect(restored.tool == "search/read/listFiles")
+ let expectedDisplay = String(localized: "activity.live.actions-read-listFiles-search")
+ #expect(task.snapshot.toolDisplayName == expectedDisplay)
#expect(restored.source?.itemType == "commandExecution")
#expect(restored.eventKind == (method == "item/started" ? .toolStarted : .toolCompleted))
}
@@ -159,10 +160,10 @@ struct AppServerActivityTests {
let event = try #require(events.first)
let task = ActivityTask(
displayID: UUID(), key: ActivityTaskKey(event: event), event: event,
- state: .running, latestEvent: .toolStarted, startedAt: now, progressGeneration: 0
+ state: .running, startedAt: now, progressGeneration: 0
)
#expect(event.tool == nil)
- #expect(task.snapshot.toolDisplayName == "commandExecution")
+ #expect(task.snapshot.toolDisplayName == String(localized: "activity.action.command"))
}
@Test func commandActionsDoNotOverrideOtherToolNames() throws {
diff --git a/CodexBarTests/Activity/SessionLifecycleCacheTests.swift b/CodexBarTests/Activity/SessionLifecycleCacheTests.swift
index 7917da6..aa9be4f 100644
--- a/CodexBarTests/Activity/SessionLifecycleCacheTests.swift
+++ b/CodexBarTests/Activity/SessionLifecycleCacheTests.swift
@@ -29,7 +29,7 @@ struct SessionLifecycleCacheTests {
let reference = ActivityTurnReference(threadID: "thread", turnID: "turn", startedAt: now)
let state = SessionLifecycleState(
requestedThreadID: "thread", turnID: "turn", startedAt: now, approvalReviewer: .user,
- effort: "high", lastProgressAt: now, terminal: nil, hasContext: true
+ effort: "high", lastProgressAt: now, terminal: nil
)
await reader.replace([reference: state], verifiedThreads: [reference.threadID: now])
#expect(await reader.lifecycleStates(for: [reference], now: now).first?.readStatus == .complete)
diff --git a/CodexBarTests/AppServer/AppServerLogTests.swift b/CodexBarTests/AppServer/AppServerLogTests.swift
index 4a0c9c6..62e4124 100644
--- a/CodexBarTests/AppServer/AppServerLogTests.swift
+++ b/CodexBarTests/AppServer/AppServerLogTests.swift
@@ -1,8 +1,103 @@
+import Combine
import Foundation
import SQLite3
import Testing
struct AppServerLogTests {
+ @Test(arguments: [0, 5])
+ func unchangedRefreshDoesNotPublishOrChangePaging(entryCount: Int) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ for index in 0 ..< entryCount {
+ storage.recordFailure(message: "entry-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 2)
+ await model.refresh()
+ let entries = model.entries
+ let hasMore = model.hasMore
+ var publications = 0
+ let subscription = model.objectWillChange.sink { publications += 1 }
+ defer { subscription.cancel() }
+
+ for _ in 0 ..< 3 {
+ await model.refresh()
+ }
+ #expect(publications == 0)
+ #expect(model.entries == entries)
+ #expect(model.totalCount == entryCount)
+ #expect(model.hasMore == hasMore)
+ #expect(!model.isLoading)
+
+ let request = storage.beginRequest(method: "new", payload: "{}")
+ await model.refresh()
+ #expect(model.entries.first?.id == request)
+ storage.finishRequest(request, response: "response")
+ await model.refresh()
+ #expect(model.entries.first?.status == .success)
+ #expect(model.entries.first?.detail == "response")
+ #expect(publications > 0)
+ }
+
+ @Test func unchangedRevisionStillClearsRecoveredReadError() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ storage.recordFailure(message: "existing")
+ let model = AppServerLogViewModel(storage: storage)
+ await model.refresh()
+ let entries = model.entries
+ var database: OpaquePointer?
+ #expect(sqlite3_open(directory.url.appendingPathComponent(AppServerLogStore.databaseName).path, &database) == SQLITE_OK)
+ defer { sqlite3_close(database) }
+ #expect(sqlite3_exec(database, "ALTER TABLE metadata RENAME TO hidden_metadata", nil, nil, nil) == SQLITE_OK)
+ await model.refresh()
+ #expect(model.errorMessage != nil)
+ var publications = 0
+ let subscription = model.objectWillChange.sink { publications += 1 }
+ defer { subscription.cancel() }
+
+ await model.refresh()
+ #expect(publications == 0)
+ #expect(sqlite3_exec(database, "ALTER TABLE hidden_metadata RENAME TO metadata", nil, nil, nil) == SQLITE_OK)
+ await model.refresh()
+ #expect(model.errorMessage == nil)
+ #expect(model.entries == entries)
+ #expect(publications == 1)
+ await model.refresh()
+ #expect(publications == 1)
+ }
+
+ @Test func retentionChangeReloadsVisibleHistory() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url, limits: .init(entries: 4))
+ for index in 0 ..< 4 {
+ storage.recordFailure(message: "old-\(index)")
+ }
+ let model = AppServerLogViewModel(storage: storage, pageSize: 2)
+ await model.refresh()
+ await model.loadMore()
+ let previousIDs = Set(model.entries.map(\.id))
+ for index in 0 ..< 8 {
+ storage.recordFailure(message: "new-\(index)")
+ }
+ await model.refresh()
+ #expect(model.entries.count == 2)
+ #expect(model.entries.first?.detail == "new-7")
+ #expect(previousIDs.isDisjoint(with: model.entries.map(\.id)))
+ #expect(model.totalCount <= 4)
+ while model.hasMore {
+ await model.loadMore()
+ }
+ #expect(model.entries.count == model.totalCount)
+ await model.clear()
+ await model.refresh()
+ #expect(model.entries.isEmpty)
+ #expect(!model.hasMore)
+ #expect(model.totalCount == 0)
+ }
+
@Test func corruptPendingRowPreservesPagingAppendAndClear() async throws {
let directory = try TestDirectory()
defer { try? directory.remove() }
@@ -194,6 +289,39 @@ struct AppServerLogTests {
}
extension AppServerLogTests {
+ @Test(arguments: [65537, 131072, 131073])
+ func defaultBodyLimitPreservesLargePayloadsAndTruncatesOverflow(bodyBytes: Int) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let storage = AppServerLogStore(directoryURL: directory.url)
+ let payload = String(repeating: "a", count: bodyBytes - 4) + "🙂"
+ let id = storage.beginRequest(method: "large/request", payload: payload)
+ storage.finishRequest(id, response: payload)
+ storage.recordReceived(method: "large/event", payload: payload, connection: "activity")
+ try await storage.finish()
+
+ let reopened = AppServerLogStore(directoryURL: directory.url)
+ let page = try await reopened.page()
+ let request = try #require(page.entries.first { $0.id == id })
+ let event = try #require(page.entries.first { $0.method == "large/event" })
+ for (text, originalBytes) in [
+ (request.request, request.requestOriginalBytes),
+ (request.detail, request.detailOriginalBytes),
+ (event.detail, event.detailOriginalBytes)
+ ] {
+ let text = try #require(text)
+ if bodyBytes <= 128 * 1024 {
+ #expect(text == payload)
+ #expect(originalBytes == nil)
+ } else {
+ #expect(text.utf8.count <= 128 * 1024)
+ #expect(text.hasSuffix("[Truncated, original: \(bodyBytes) bytes]"))
+ #expect(!text.contains("�"))
+ #expect(originalBytes == bodyBytes)
+ }
+ }
+ }
+
@Test func retentionPrunesOldPendingRequestsAndLateRepliesStayDeleted() async throws {
let directory = try TestDirectory()
defer { try? directory.remove() }
diff --git a/CodexBarTests/AppServer/AppServerSessionTests.swift b/CodexBarTests/AppServer/AppServerSessionTests.swift
index 2dec0d6..1b41439 100644
--- a/CodexBarTests/AppServer/AppServerSessionTests.swift
+++ b/CodexBarTests/AppServer/AppServerSessionTests.swift
@@ -68,42 +68,12 @@ struct AppServerSessionTests {
try server.finish()
}
- @Test(arguments: [true, false])
- func logsOnlyConsumedPushesWithoutChangingNotificationDelivery(_ interleaved: Bool) async throws {
+ @Test(arguments: [true, false], [true, false])
+ func logsStateAndPresentationWithoutDroppingDeltaDelivery(_ interleaved: Bool, _ polled: Bool) async throws {
let directory = try TestDirectory()
defer { try? directory.remove() }
let storage = AppServerLogStore(directoryURL: directory.url)
- let filtered = try unusedNotifications()
- var retained = try [
- "thread/started", "thread/status/changed", "thread/settings/updated", "turn/started", "turn/completed",
- "item/autoApprovalReview/started", "serverRequest/resolved", "error", "warning"
- ].map { try notification($0, params: ["marker": $0]) }
- for count in 1 ... 3 {
- try retained.append(notification("thread/tokenUsage/updated", params: ["total": count]))
- }
- for type in [
- "commandExecution",
- "fileChange",
- "webSearch",
- "imageView",
- "imageGeneration",
- "sleep",
- "mcpToolCall",
- "dynamicToolCall",
- "collabAgentToolCall",
- "contextCompaction",
- "subAgentActivity"
- ] {
- for method in ["item/started", "item/completed"] {
- try retained.append(notification(method, params: ["item": ["type": type, "id": type, "output": "full output"]]))
- }
- }
- for method in ["item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval"] {
- try retained.append(JSONSerialization.data(withJSONObject: [
- "id": "approval", "method": method, "params": ["command": "original"]
- ]))
- }
- try retained.append(notification("item/completed", params: ["item": ["id": "malformed", "type": 123]]))
+ let (filtered, retained) = try logDeliveryMessages()
let messages = filtered + retained
let server = try SharedServerFixture { peer in
let request = try peer.readMessage()
@@ -119,16 +89,33 @@ struct AppServerSessionTests {
}
}
let done = try peer.readMessage()
+ #expect(done["method"] as? String == "done")
try peer.reply(to: done, result: ["value": 8])
}
defer { server.close() }
let session = try AppServerSession(socketURL: server.url, logStorage: storage)
defer { session.close() }
- let response: Value = try session.request("probe")
- #expect(response.value == 7)
- for message in messages {
- #expect(try session.nextEvent() == message)
+ var delivered: [Data] = []
+ if polled {
+ let request = try session.beginRequest("probe", params: [:])
+ receive: while true {
+ switch try session.poll(request) {
+ case .waiting: continue
+ case let .event(data): delivered.append(data)
+ case let .response(data):
+ #expect(try AppServerRPC.decode(data, as: Value.self).value == 7)
+ break receive
+ }
+ }
+ } else {
+ let response: Value = try session.request("probe")
+ #expect(response.value == 7)
}
+ for _ in delivered.count ..< messages.count {
+ let event = try #require(try session.nextEvent())
+ delivered.append(event)
+ }
+ #expect(delivered == messages)
let _: Value = try session.request("done")
session.close()
try server.finish()
@@ -146,6 +133,63 @@ struct AppServerSessionTests {
#expect(try await reopened.page(limit: 200).entries == page.entries)
}
+ private func logDeliveryMessages() throws -> (filtered: [Data], retained: [Data]) {
+ var filtered = try unusedNotifications()
+ var retained = try [
+ "thread/started", "thread/status/changed", "thread/settings/updated", "turn/started", "turn/completed",
+ "item/autoApprovalReview/started", "item/autoApprovalReview/completed", "serverRequest/resolved", "error", "warning",
+ "hook/started", "hook/completed", "mcpServer/startupStatus/updated", "model/rerouted", "model/verification",
+ "modelProvider/authRecoveryStarted", "modelProvider/authRecoveryCompleted", "model/safetyBuffering/updated",
+ "thread/environment/connected", "thread/environment/disconnected"
+ ].map { try notification($0, params: ["marker": $0]) }
+ try retained.append(notification("turn/diff/updated", params: ["diff": "original patch"]))
+ try retained.append(notification("turn/plan/updated", params: ["plan": [["step": "original step", "status": "pending"]]]))
+ for method in [
+ "item/agentMessage/delta", "item/plan/delta", "item/reasoning/summaryTextDelta", "item/reasoning/textDelta",
+ "item/commandExecution/outputDelta", "item/fileChange/outputDelta"
+ ] {
+ try filtered.append(notification(method, params: [
+ "threadId": "thread", "turnId": "turn", "itemId": "item", "delta": "original fragment", "summaryIndex": 0, "contentIndex": 0
+ ]))
+ }
+ try filtered.append(notification("item/agentMessage/delta", params: ["delta": 123]))
+ for count in 1 ... 3 {
+ try retained.append(notification("thread/tokenUsage/updated", params: ["total": count]))
+ }
+ for type in [
+ "commandExecution",
+ "fileChange",
+ "webSearch",
+ "imageView",
+ "imageGeneration",
+ "sleep",
+ "mcpToolCall",
+ "dynamicToolCall",
+ "collabAgentToolCall",
+ "contextCompaction",
+ "subAgentActivity",
+ "agentMessage",
+ "reasoning",
+ "plan",
+ "enteredReviewMode",
+ "exitedReviewMode"
+ ] {
+ for method in ["item/started", "item/completed"] {
+ try retained.append(notification(method, params: ["item": ["type": type, "id": type, "output": "full output"]]))
+ }
+ }
+ for method in [
+ "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval",
+ "item/tool/requestUserInput", "mcpServer/elicitation/request"
+ ] {
+ try retained.append(JSONSerialization.data(withJSONObject: [
+ "id": "approval", "method": method, "params": ["command": "original"]
+ ]))
+ }
+ try retained.append(notification("item/completed", params: ["item": ["id": "malformed", "type": 123]]))
+ return (filtered, retained)
+ }
+
private func notification(_ method: String, params: [String: Any]) throws -> Data {
try JSONSerialization.data(withJSONObject: ["method": method, "params": params])
}
@@ -153,36 +197,18 @@ struct AppServerSessionTests {
private func unusedNotifications() throws -> [Data] {
var messages: [Data] = []
for method in [
- "hook/started", "hook/completed", "hook/futureEvent", "account/updated", "account/rateLimits/updated",
- "mcpServer/startupStatus/updated", "remoteControl/status/changed", "thread/goal/cleared",
- "thread/name/updated", "item/autoApprovalReview/completed", "future/tool/delta"
+ "hook/futureEvent", "account/updated", "account/rateLimits/updated",
+ "remoteControl/status/changed", "thread/goal/cleared", "thread/name/updated", "future/tool/delta"
] {
try messages.append(notification(method, params: ["marker": method]))
}
- for method in ["hook/started", "item/tool/call", "item/tool/requestUserInput", "mcpServer/elicitation/request"] {
- try messages.append(JSONSerialization.data(withJSONObject: ["id": "unused", "method": method, "params": [:]]))
- }
- try messages.append(notification("item/agentMessage/delta", params: ["delta": 123]))
- for method in [
- "item/agentMessage/delta",
- "item/plan/delta",
- "item/reasoning/summaryTextDelta",
- "item/reasoning/textDelta",
- "item/commandExecution/outputDelta",
- "item/fileChange/outputDelta"
- ] {
- try messages.append(notification(method, params: [
- "threadId": "thread", "turnId": "turn", "itemId": "item", "delta": "original fragment", "summaryIndex": 0, "contentIndex": 0
- ]))
- }
+ try messages.append(JSONSerialization.data(withJSONObject: ["id": "unused", "method": "item/tool/call", "params": [:]]))
for method in ["command/exec/outputDelta", "process/outputDelta", "item/future/delta", "item/future/outputDelta", "hook/delta"] {
try messages.append(notification(method, params: ["deltaBase64": "dGVzdA==", "stream": "stdout"]))
}
try messages.append(notification("item/reasoning/summaryPartAdded", params: ["summaryIndex": 0]))
- try messages.append(notification("turn/diff/updated", params: ["diff": "patch"]))
- try messages.append(notification("turn/plan/updated", params: ["plan": [["step": "test", "status": "pending"]]]))
try messages.append(notification("item/mcpToolCall/progress", params: ["message": "working"]))
- for type in ["userMessage", "agentMessage", "reasoning", "plan", "hookPrompt", "functionCallOutput", "enteredReviewMode", "exitedReviewMode", "futureItem"] {
+ for type in ["userMessage", "hookPrompt", "functionCallOutput", "futureItem"] {
for method in ["item/started", "item/completed"] {
try messages.append(notification(method, params: ["item": ["id": type, "type": type, "text": "body"]]))
}
diff --git a/CodexBarTests/History/HistoryMaintenanceTests.swift b/CodexBarTests/History/HistoryMaintenanceTests.swift
index 9b3a98b..d9d49ec 100644
--- a/CodexBarTests/History/HistoryMaintenanceTests.swift
+++ b/CodexBarTests/History/HistoryMaintenanceTests.swift
@@ -92,6 +92,24 @@ extension HistoryMaintenanceTests {
#expect(flock(descriptor, LOCK_UN) == 0)
}
+ @Test func lockFileOpenFailurePreservesPOSIXError() throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ for url in [HistoryStorage.lockURL(in: directory.url), directory.url.appendingPathComponent("store.lock")] {
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ }
+ #expect(throws: POSIXError(.EISDIR)) {
+ try HistoryStorage.withExclusiveLock(in: directory.url) {
+ Issue.record("Lock acquisition should fail before running the operation")
+ }
+ }
+ #expect(throws: POSIXError(.EISDIR)) {
+ try JSONFileStorage.withLock(in: directory.url) {
+ Issue.record("Lock acquisition should fail before running the operation")
+ }
+ }
+ }
+
@Test func legacyMaintenanceStateRequiresRebuildAndNormalizesDateQueues() throws {
let state = try TestFixtures.decode(HistoryMaintenanceState.self, """
{"pending":["2026-09-15","invalid","2026-09-14","2026-09-15"],"dirty":["2026-02-30","2026-09-14"]}
diff --git a/CodexBarTests/Presentation/ActivityCardLayoutTests.swift b/CodexBarTests/Presentation/ActivityCardLayoutTests.swift
new file mode 100644
index 0000000..f0c5c6a
--- /dev/null
+++ b/CodexBarTests/Presentation/ActivityCardLayoutTests.swift
@@ -0,0 +1,50 @@
+import AppKit
+import SwiftUI
+import Testing
+
+struct ActivityCardLayoutTests {
+ @Test func narrowStatusContentExpandsWithoutClipping() {
+ let short = statusSize(width: 300, long: false)
+ let wide = statusSize(width: 480, long: true)
+ let narrow = statusSize(width: 180, long: true)
+ #expect(narrow.width == 180)
+ #expect(narrow.height > wide.height)
+ #expect(narrow.height > short.height)
+ #expect(narrow.height.isFinite)
+ }
+
+ @Test func wrappedSupplementUsesOneLineEvenWhenItIsVeryLong() {
+ let short = supplementarySize("2 个子 Agent 运行中")
+ let long = supplementarySize(String(repeating: "附加信息", count: 40))
+ #expect(long.width == 140)
+ #expect(long.height == short.height)
+ }
+
+ private func supplementarySize(_ supplement: String) -> CGSize {
+ let content = ActivityStatusText(
+ text: "正在读取文件, 浏览目录, 搜索文件内容",
+ tint: .blue, effect: .none, lineLimit: nil, supplement: supplement
+ )
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(width: 140, alignment: .leading)
+ return NSHostingView(rootView: content).fittingSize
+ }
+
+ private func statusSize(width: CGFloat, long: Bool) -> CGSize {
+ let content = VStack(alignment: .leading, spacing: 3) {
+ Text("CodexBar • gpt-6-astra • high • 已运行 1 小时 24 分")
+ .font(.caption.weight(.semibold))
+ .fixedSize(horizontal: false, vertical: true)
+ ActivityStatusText(
+ text: long ? "正在读取文件, 浏览目录, 搜索文件内容" : "正在回答",
+ tint: .blue, effect: .none, lineLimit: nil, supplement: "3 个子 Agent 运行中"
+ )
+ .fixedSize(horizontal: false, vertical: true)
+ Text("最近事件: 读取文件, 浏览目录, 搜索内容完成")
+ .font(.caption2)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .frame(width: width, alignment: .leading)
+ return NSHostingView(rootView: content).fittingSize
+ }
+}
diff --git a/CodexBarTests/Presentation/ActivityPresentationTests.swift b/CodexBarTests/Presentation/ActivityPresentationTests.swift
index 085da27..b0e374c 100644
--- a/CodexBarTests/Presentation/ActivityPresentationTests.swift
+++ b/CodexBarTests/Presentation/ActivityPresentationTests.swift
@@ -3,6 +3,31 @@ import Foundation
import Testing
struct ActivityPresentationTests {
+ @Test(arguments: [
+ (("commandExecution", "search/read/read"), "activity.live.actions-read-search"),
+ (("commandExecution", nil), "activity.action.command"),
+ (("fileChange", nil), "activity.action.edit-files"),
+ (("collabAgentToolCall", "spawnAgent"), "activity.action.start-subagent")
+ ] as [((String, String?), LocalizedStringResource)], [false, true])
+ func waitingSurfacesShareLocalizedActions(
+ operation: (source: (type: String, tool: String?), action: LocalizedStringResource), hasProject: Bool
+ ) {
+ let task = ActivityTaskSnapshot(
+ id: UUID(), isAnonymous: false,
+ projectName: hasProject ? "CodexBar" : nil, modelName: nil, effort: nil, toolName: operation.source.tool,
+ startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,
+ showsPreciseDuration: true, activeSubagentCount: nil, itemType: operation.source.type
+ )
+ let expected = String(localized: operation.action)
+ let notice = NotificationContent.taskWaiting(project: task.projectName, toolName: task.toolDisplayName)
+ #expect(task.toolDisplayName == expected)
+ #expect(notice.body.contains(expected))
+ #expect(!notice.body.contains(operation.source.type))
+ if let raw = operation.source.tool {
+ #expect(!notice.body.contains(raw))
+ }
+ }
+
@Test(arguments: [false, true], ["unavailable", "bootstrap", "stop"])
func clearingActivityAlsoClearsGlow(waiting: Bool, reason: String) throws {
let directory = try TestDirectory()
diff --git a/CodexBarTests/Presentation/DateAndPresentationTests.swift b/CodexBarTests/Presentation/DateAndPresentationTests.swift
index ef3cf9e..b9b5828 100644
--- a/CodexBarTests/Presentation/DateAndPresentationTests.swift
+++ b/CodexBarTests/Presentation/DateAndPresentationTests.swift
@@ -2,6 +2,29 @@ import Foundation
import Testing
struct DateAndPresentationTests {
+ @Test(arguments: [
+ (-1.0, "0 秒"),
+ (0.0, "0 秒"),
+ (21.0, "21 秒"),
+ (59.6, "1 分钟 0 秒"),
+ (80.0, "1 分钟 20 秒"),
+ (3599.6, "1 小时 0 分钟"),
+ (4800.0, "1 小时 20 分钟")
+ ])
+ func chineseDurationSeparatesValuesAndUnits(interval: TimeInterval, expected: String) {
+ #expect(CodexDurationFormat.activityText(for: interval, locale: Locale(identifier: "zh_CN")) == expected)
+ }
+
+ @Test(arguments: ["en_US", "fr_FR"])
+ func durationPreservesExistingLocalizedSeparators(localeIdentifier: String) {
+ let locale = Locale(identifier: localeIdentifier)
+ let expected = Duration.seconds(80).formatted(
+ .units(allowed: [.minutes, .seconds], width: .abbreviated, zeroValueUnits: .show(length: 1), fractionalPart: .hide(rounded: .down))
+ .locale(locale)
+ )
+ #expect(CodexDurationFormat.activityText(for: 80, locale: locale) == expected)
+ }
+
@Test(arguments: ["2026-02-29", "2026-04-31", "2026-00-10", "2026-13-01", "2026-1-01", "2026-01-1", "0000-01-01", "garbage"])
func dateKeysRejectImpossibleOrNoncanonicalDates(_ value: String) {
#expect(CodexDateFormat.dayDate(from: value) == nil)
@@ -60,7 +83,7 @@ struct DateAndPresentationTests {
private func task(isAnonymous: Bool) -> ActivityTaskSnapshot {
ActivityTaskSnapshot(
- id: UUID(), isAnonymous: isAnonymous, latestEvent: .promptSubmitted,
+ id: UUID(), isAnonymous: isAnonymous,
projectName: nil, modelName: nil, effort: nil, toolName: nil,
startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,
showsPreciseDuration: !isAnonymous, activeSubagentCount: nil
@@ -68,7 +91,7 @@ struct DateAndPresentationTests {
}
@Test(arguments: [false, true])
- func accountFailureKeepsLiveTaskIconAndExplainsBothStates(waiting: Bool) {
+ func accountFailureKeepsLiveTaskIcon(waiting: Bool) {
let task = task(isAnonymous: false)
let activity = ActivitySnapshot(
waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task],
@@ -76,8 +99,6 @@ struct DateAndPresentationTests {
)
let state = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: activity)
#expect(state.symbolName(at: TestFixtures.now) == (waiting ? "person.badge.key.fill" : "person.badge.clock.fill"))
- #expect(state.hasLiveDuration)
- #expect(state.toolTip(at: TestFixtures.now)?.contains(String(localized: "codex-status.account.unavailable")) == true)
let idle = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: .empty)
#expect(idle.symbolName(at: TestFixtures.now) == "person.slash.fill")
}
diff --git a/CodexBarTests/Presentation/TaskGlowPreviewTests.swift b/CodexBarTests/Presentation/TaskGlowPreviewTests.swift
index 8aab111..aa1c84c 100644
--- a/CodexBarTests/Presentation/TaskGlowPreviewTests.swift
+++ b/CodexBarTests/Presentation/TaskGlowPreviewTests.swift
@@ -229,7 +229,7 @@ struct TaskGlowPreviewTests {
private func active(waiting: Bool = false) -> ActivitySnapshot {
let task = ActivityTaskSnapshot(
- id: UUID(), isAnonymous: false, latestEvent: .toolStarted, projectName: nil,
+ id: UUID(), isAnonymous: false, projectName: nil,
modelName: nil, effort: nil, toolName: nil, startedAt: now,
stateChangedAt: now, showsPreciseDuration: true, activeSubagentCount: nil
)
diff --git a/CodexBarTests/Presentation/TaskGlowTests.swift b/CodexBarTests/Presentation/TaskGlowTests.swift
index 3c5598a..f4f5188 100644
--- a/CodexBarTests/Presentation/TaskGlowTests.swift
+++ b/CodexBarTests/Presentation/TaskGlowTests.swift
@@ -202,7 +202,7 @@ struct TaskGlowTests {
@Test func concurrentTaskCompletionStillShowsBrieflyThenRestoresRunning() throws {
var presentation = TaskGlowPresentationState()
let running = ActivityTaskSnapshot(
- id: UUID(), isAnonymous: false, latestEvent: .toolStarted, projectName: nil,
+ id: UUID(), isAnonymous: false, projectName: nil,
modelName: nil, effort: nil, toolName: nil, startedAt: TestFixtures.now,
stateChangedAt: TestFixtures.now, showsPreciseDuration: true, activeSubagentCount: nil
)
diff --git a/README.en.md b/README.en.md
index 9ae843f..8d0842b 100644
--- a/README.en.md
+++ b/README.en.md
@@ -14,7 +14,7 @@
[![Downloads](https://img.shields.io/github/downloads/bob-zebedy/CodexBar/total?color=2EA043)](https://github.com/bob-zebedy/CodexBar/releases)
[![License](https://img.shields.io/github/license/bob-zebedy/CodexBar?color=8957E5)](LICENSE)
-[Features](#features) | [Installation](#installation) | [Quick Start](#quick-start) | [Privacy](#privacy) | [Runtime Architecture](https://codexbar.zabrian.app/architecture) | [Performance Report](https://codexbar.zabrian.app/performance)
+[Features](#features) | [Installation](#installation) | [Privacy](#privacy) | [Runtime Architecture](https://codexbar.zabrian.app/architecture) | [Performance Report](https://codexbar.zabrian.app/performance)
<img src="Images/preview.gif" width="640" alt="CodexBar preview">
@@ -24,46 +24,43 @@
CodexBar is a menu bar app for macOS that displays your Codex account information, usage limits, token usage, and real-time task status in one place.
-It can notify you when a task finishes, needs approval, or when your rate limits change. It can also keep your Mac awake while eligible Codex tasks are active.
-
## Features
### Account and rate limits at a glance
-- View your current Codex account and plan
-- See every rate-limit window, its remaining allowance, and reset time
-- Check available credits and banked resets
-- Automatically use banked resets from 15 minutes to 6 hours before they expire, with a default lead time of 30 minutes; CodexBar can wake your Mac at the scheduled time and revalidate availability before use
-- Show the remaining percentage of a selected rate-limit window as a menu bar arc
+- View your account, plan, credits, and the remaining allowance and reset time for each rate-limit window
+- Show your preferred allowance directly in the menu bar
+- Track banked resets and their expiry dates, with automatic use before they expire
+
+### Follow your tasks in real time
+
+- See each task's project, model, reasoning effort, duration, and token usage
+- Follow live states, actions that need your attention, task progress, and recent events
+- Review concurrent tasks and recent completions, failures, and interruptions in Task Center
-### Understand your Codex usage
+### Review your usage
-- Track total tokens, your highest daily usage, and usage streaks
-- See your longest task duration
-- Review recent daily token usage in a heatmap
-- View daily session, turn, tool call, subagent, and other activity metrics
+- Track total usage, daily peaks, usage streaks, and your longest task duration
+- Explore daily token usage and activity statistics in a heatmap
+- Combine usage records across Macs through iCloud
-### Keep track of active tasks
+### Get timely alerts
-- Menu bar person badges distinguish running tasks, tasks waiting for approval, recent completions, and recent terminations
-- The main panel shows the current task, project, model, reasoning effort, and elapsed time
-- Task Center brings concurrent, recently completed, and recently terminated tasks together
-- Receive alerts for completed tasks, approval requests, and stalled tasks
-- Optional task glow along the top of each display shows running, waiting, completed, and terminated states
+- Receive alerts for task completions, approval requests, allowance changes, and protection events
+- Choose notification types, sounds, and task haptic feedback
+- Follow status changes through customizable task glow at the top of your displays
-### Let long-running tasks finish
+### Keep long tasks running
-- Prevent system sleep only while eligible Codex tasks are active
-- Optionally stay awake while waiting for approval or keep the display awake as well
+- Keep your Mac awake while tasks run, then allow normal sleep when they finish
+- Optionally stay awake while waiting for approval or keep the display on as well
- Set a keep-awake time limit, low-battery protection, and stalled task protection
-- Restore normal system sleep automatically when tasks finish or a protection rule is triggered
-### Fit naturally into macOS
+### Make it your own
-- Runs as a menu bar app without taking up space in the Dock
-- Supports a global keyboard shortcut, launch at login, and automatic updates
-- Provides Simplified Chinese and English interfaces
-- Optionally merges daily activity metrics and token usage records across Macs through iCloud
+- Customize main panel section order, visibility, and animations
+- Use a global keyboard shortcut, launch at login, and automatic update checks
+- Choose Simplified Chinese or English and browse logs for troubleshooting
## Installation
@@ -81,28 +78,12 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy
- macOS 15.0 or later
- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed
-- Codex Daemon version `0.157.0` or later. CodexBar reuses an existing service on launch or starts it through an installed Codex that supports `codex app-server daemon start`. Codex Daemon remains running when CodexBar quits
-- If the installed Codex does not support the start command, first start a Codex interactive session with the background service enabled
+- Codex background service version `0.157.0` or later
- Cross-device sync requires an available iCloud account on the Mac
-## Quick Start
-
-1. Launch CodexBar and find its icon in the menu bar
-2. Left-click the icon to view your account, rate limits, and token usage
-3. Right-click or Control-click the icon to open Settings, Logs, or the Quit menu
-4. Activity capture and statistics start with the app; configure system notifications under `Settings > General`, and sleep prevention and sync under `Settings > Advanced`
-
-The default global shortcut is `⌘⇧E`. You can record a different shortcut or disable it in Settings.
-
## Privacy
-Raw activity events and live tasks are processed locally. Enabling cross-device sync uploads daily activity aggregates and per-turn token usage records to your private iCloud database. Account and usage data come through the local Codex app-server, which connects to the service; update checks use Sparkle.
-
-## Local history and logs
-
-Activity history is rebuilt from recorded events. Token history is recomputed from raw cumulative counter observations captured while collection was active. Both retain 210 days of data; rebuilding cannot recover unobserved usage or deleted source records. If cross-device token corrections lack a verifiable coverage relationship, no historical token aggregate is generated for the affected date.
-
-Request logs retain at most 10,000 entries and 50 MiB of serialized records. Each request or response body is limited to 64 KiB and includes a truncation marker when shortened. The oldest entries are removed when limits are exceeded. The log window caches at most 1,000 entries; close and reopen the window to return from older history to the live list. Database indexes and WAL files add storage overhead.
+Raw activity events and live tasks are processed locally. Enabling cross-device sync uploads daily activity aggregates and token usage records to your private iCloud database.
## Feedback
diff --git a/README.md b/README.md
index 42d7fb4..63ff585 100644
--- a/README.md
+++ b/README.md
@@ -24,46 +24,43 @@
CodexBar 是 macOS 的菜单栏 App,用于集中展示 Codex 账户、额度、Token 用量和实时任务状态。
-它可以在任务完成、等待批准或额度变化时提醒你,也能在符合条件的 Codex 任务存在时自动防止系统睡眠。
-
## 功能
### 账户与额度一目了然
-- 展示当前 Codex 账户和套餐
-- 展示全部额度窗口、剩余比例和重置时间
-- 展示可用积分和留存重置
-- 支持自动重置,可设置在留存重置过期前 15 分钟到 6 小时执行,默认提前 30 分钟;计划到点时可唤醒 Mac,并在执行前重新确认可用状态
-- 可通过菜单栏圆弧直接显示所选额度窗口的剩余比例
+- 查看账户、套餐、积分,以及各额度窗口的剩余比例和重置时间
+- 在菜单栏直接显示关注的额度
+- 查看留存重置及到期时间,支持到期前自动使用
+
+### 随时掌握任务进展
+
+- 查看项目、模型、推理强度、任务耗时和 Token 用量
+- 实时显示执行状态、等待操作、任务进度和最近事件
+- 在任务中心集中查看并发任务及最近完成、失败和中断的记录
-### 看见自己的 Codex 使用节奏
+### 回顾使用情况
-- 展示累计 Token、单日峰值和连续使用天数
-- 展示最长任务时长
-- 通过热力图回顾近期每日 Token 用量
-- 可查看会话、对话轮次、工具调用和子 Agent 等每日统计
+- 查看累计用量、单日峰值、连续使用天数和最长任务时长
+- 通过热力图查看每日 Token 用量和活动统计
+- 通过 iCloud 汇总多台 Mac 的使用记录
-### 不错过正在发生的任务
+### 及时收到提醒
-- 菜单栏人物徽章区分运行中、等待批准、最近完成和最近终止任务
-- 主面板展示当前任务、项目、模型、推理强度和持续时间
-- 任务中心集中查看并发任务、最近完成和最近终止记录
-- 支持任务完成、等待批准和异常会话提醒
-- 可在各显示器顶部显示任务流光,用颜色提示运行、等待、完成和终止
+- 接收任务完成、等待审批、额度变化和保护提醒
+- 按需选择通知类型、音效和任务触觉反馈
+- 通过屏幕顶部的任务流光感知状态变化,支持自定义外观
### 让长任务安心运行
-- 只在符合条件的 Codex 任务存在时防止系统睡眠
-- 可选择等待批准期间继续保持,或同时保持屏幕常亮
-- 支持最长防睡眠时间、低电量保护和异常会话保护
-- 任务结束或保护条件触发后自动恢复系统睡眠
+- 任务运行时自动防止 Mac 睡眠,结束后恢复正常睡眠
+- 可在等待审批时继续保持唤醒,或同时保持屏幕常亮
+- 支持防睡眠时限、低电量保护和异常会话保护
-### 融入 macOS 工作流
+### 按你的习惯使用
-- 作为菜单栏 App 运行,不占用 Dock
-- 支持全局快捷键、开机启动和自动更新
-- 支持简体中文和英文界面
-- 可选通过 iCloud 合并多台 Mac 的每日活动统计和 Token 用量记录
+- 自定义主面板区域的顺序、显隐和动画效果
+- 支持全局快捷键、开机启动和自动检查更新
+- 提供简体中文、英文界面,以及便于排查问题的日志查看功能
## 安装
@@ -82,28 +79,11 @@ brew install --cask bob-zebedy/tap/codexbar
- macOS 15.0 或更高版本
- 已安装并登录 [Codex CLI](https://github.com/openai/codex) 或安装了内置 Codex 的 ChatGPT App 或 Codex App
- Codex 后台服务版本为 `0.157.0` 或更高版本
-- CodexBar 启动时连接 Codex 后台服务,未运行时通过已安装 Codex 的 `codex app-server daemon start` 命令启动,退出后保留该进程
-- 若已安装的 Codex 不支持启动命令,需先启动启用后台服务的 Codex 交互会话
- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户
-## 快速开始
-
-1. 启动 CodexBar,在菜单栏找到 CodexBar 图标
-2. 左键点击图标查看账户、额度和 Token 用量
-3. 右键或按住 Control 点击图标打开设置、日志或退出菜单
-4. 会话活动和统计随 App 启动;在 `设置 > 通用` 中配置系统通知,在 `设置 > 高级` 中配置防睡眠和同步
-
-默认全局快捷键为 `⌘⇧E`,可在设置中重新录制或关闭。
-
## 隐私
-活动原始事件和实时任务在本机处理。开启跨设备同步后,日级活动聚合和 Token 用量记录会上传到 iCloud private database。账户和用量通过本机 Codex app-server 获取,由 Codex 连接服务端;更新检查使用 Sparkle。
-
-## 本地历史与日志
-
-活动历史按已记录的事件重建,Token 历史按采集期间保存的原始累计计数观测重新计算。两者保留 210 天的数据;重建无法补回未采集的消耗或已删除的原始记录。跨设备 Token 修正缺少可核对的覆盖关系时,对应日期不生成历史 Token 汇总。
-
-请求日志最多保留 10,000 条,序列化记录总量不超过 50 MiB,单份请求或响应正文最多保留 64 KiB。超过限制时清理最旧记录,超长正文带截断标记。日志窗口最多缓存 1,000 条,浏览更早记录后可关闭并重新打开窗口返回实时列表。数据库索引和 WAL 会产生额外文件开销。
+活动原始事件和实时任务在本机处理。开启跨设备同步后,日级活动聚合和 Token 用量记录会上传到 iCloud private database。
## 反馈