Skip to content

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

fix: 修复后台服务未启动时的连接失败

Bob847dd06c650f
diff --git a/AGENTS.md b/AGENTS.md
index ba7af3d..0fba9d3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -107,17 +107,19 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,
### 启动与并发边界
-- 共享 app-server 采集由独立 actor 拥有连接和解析状态,不在主 actor 执行阻塞 I/O
+- Codex 后台服务采集由独立 actor 拥有连接和解析状态,不在主 actor 执行阻塞 I/O
- 采集消息和读取时间必须有界,共享数据写入必须加锁
- 普通模式由 App 的统一入口装配长期服务
- 工程默认采用 `MainActor` 隔离,共享可变状态放入 actor,跨 actor 值类型按需声明 `nonisolated`,禁止在主 actor 执行阻塞 I/O
- 类型命名使用 `UpperCamelCase`,成员命名使用 `lowerCamelCase`
+- 设置持久化 key 使用 `UpperCamelCase.lowerCamelCase`,模块名按职责命名,不跟随界面文案变化;总开关使用 `isEnabled`,子开关使用 `is…Enabled` 或 `are…Enabled`,行为布尔值可使用 `keeps…` 等自然谓词;时长以秒保存并带 `Seconds` 后缀,百分比带 `Percent` 后缀
### 数据链路与权限边界
- 保持 app-server 额度与用量、活动历史聚合、实时任务三条数据链路独立
- 账户主链路、活动连接启用与校验必须分别检查当前 app-server 的实际版本是否满足各自最低要求
-- 活动连接只订阅已加载线程,不创建用户轮次、不回答审批、不修改 Codex 配置或管理共享 daemon 生命周期
+- 活动连接只订阅已加载线程,不创建用户轮次、不回答审批、不修改 Codex 配置或管理 Codex 后台服务生命周期
+- App 启动入口允许在 Codex 后台服务缺失时通过官方 `codex app-server daemon start` 命令确保服务启动,能力检测、等待和重试必须有界;禁止停止、重启、更新 Codex 后台服务或修改 Codex 配置
- helper 只能执行固定的睡眠控制和自动重置唤醒计划,不得增加网络、任意命令执行或额外文件访问
- 新增网络访问、日志数据或 CloudKit 字段前先核对隐私边界
- 开启自动重置或防睡眠前必须取得用户确认,打开 helper 授权系统设置必须由用户显式操作触发
diff --git a/CodexBar/Controllers/CodexBarAppDelegate.swift b/CodexBar/Controllers/CodexBarAppDelegate.swift
index 6451bfb..63bfbee 100644
--- a/CodexBar/Controllers/CodexBarAppDelegate.swift
+++ b/CodexBar/Controllers/CodexBarAppDelegate.swift
@@ -1,7 +1,7 @@
import AppKit
import os
-/// 应用级对象装配点, 持有共享服务和 ViewModel 生命周期
+/// 应用级对象装配点, 持有服务和 ViewModel 生命周期
@MainActor
final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
private let codexStatusService = CodexStatusService()
@@ -30,6 +30,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
private var taskGlowController: TaskGlowController?
private var notificationService: NotificationService?
private var autoResetController: AutoResetController?
+ private var startupTask: Task<Void, Never>?
private var terminationPreparationTask: Task<Void, Never>?
private var hasPreparedForTermination = false
@@ -93,13 +94,30 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
)
taskGlowController.start()
self.taskGlowController = taskGlowController
- activityMonitor.start()
keepAliveController.start()
logLaunchState()
+ startupTask = Task { [weak self] in
+ var startupError: String?
+ do {
+ try await AppServerStartup().ensureStarted()
+ } catch is CancellationError {
+ return
+ } catch {
+ startupError = error.localizedDescription
+ AppLog.app.error("Codex 后台服务准备失败")
+ AppServerLogStore.shared.recordFailure(method: "daemon/start", message: error.localizedDescription)
+ }
+ guard let self, !Task.isCancelled else { return }
+ startupTask = nil
+ viewModel.startAutoRefresh(startupError: startupError)
+ activityMonitor.start()
+ }
}
func applicationWillTerminate(_: Notification) {
AppLog.app.notice("App 即将退出: reason=userQuit")
+ startupTask?.cancel()
+ startupTask = nil
terminationPreparationTask?.cancel()
terminationPreparationTask = nil
AppProcessDiagnostics.recordCleanExit()
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index ca13b03..c7bea58 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -152,7 +152,6 @@ final class StatusItemController: NSObject, NSMenuDelegate {
// 订阅时 CombineLatest 会同步发出当前值, 初始图标由订阅路径统一渲染
observeViewModel()
observeSyncState()
- viewModel.startAutoRefresh()
}
func uninstall() {
diff --git a/CodexBar/Models/ActivitySyncRecord.swift b/CodexBar/Models/ActivitySyncRecord.swift
index a5dac4c..68be60c 100644
--- a/CodexBar/Models/ActivitySyncRecord.swift
+++ b/CodexBar/Models/ActivitySyncRecord.swift
@@ -192,9 +192,9 @@ nonisolated enum ActivitySyncError: LocalizedError {
var errorDescription: String? {
switch self {
case let .missingGeneration(date):
- String(localized: "sync.error.activity-generation", defaultValue: "Activity history for \(date) has no valid generation and cannot be synchronized")
+ String(localized: "sync.error.activity-generation", defaultValue: "\(date)")
case .invalidRecordIdentity:
- String(localized: "sync.error.activity-identity", defaultValue: "The activity record identity does not match its device, date and generation")
+ String(localized: "sync.error.activity-identity")
}
}
}
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 6355e38..30bdc4a 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -1046,13 +1046,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "The shared Codex service is unavailable. Start a Codex session with the background service enabled, then reconnect."
+ "value" : "Codex Daemon is unavailable"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex 共享服务不可用, 请启动已启用后台服务的 Codex 会话后重新连接"
+ "value" : "Codex 后台服务不可用"
}
}
}
@@ -1121,18 +1121,82 @@
}
}
},
- "codex.source.error.not-found" : {
+ "codex.daemon.command-failed" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "%@ not found"
+ "value" : "Failed to start Codex Daemon: %d"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "未找到 %@"
+ "value" : "Codex 后台服务启动失败: %d"
+ }
+ }
+ }
+ },
+ "codex.daemon.not-installed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "No usable Codex installation found"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未找到可用的 Codex"
+ }
+ }
+ }
+ },
+ "codex.daemon.not-ready" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Cannot connect to Codex Daemon"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex 后台服务无法连接"
+ }
+ }
+ }
+ },
+ "codex.daemon.timeout" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex Daemon startup timed out"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex 后台服务启动超时"
+ }
+ }
+ }
+ },
+ "codex.daemon.unsupported-command" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex Daemon is not supported"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex 不支持后台服务"
}
}
}
@@ -2332,7 +2396,7 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "开启防止系统睡眠?"
+ "value" : "开启防止睡眠?"
}
}
}
@@ -2657,22 +2721,6 @@
}
}
},
- "log.action.latest" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Latest"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "最新日志"
- }
- }
- }
- },
"log.action.preview-full" : {
"localizations" : {
"en" : {
@@ -3932,7 +3980,7 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex Daemon"
+ "value" : "Codex 后台服务"
}
}
}
@@ -3958,13 +4006,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Data Update Interval"
+ "value" : "Data Update Frequency"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "数据更新间隔"
+ "value" : "数据更新频率"
}
}
}
@@ -4076,7 +4124,7 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "防止系统睡眠"
+ "value" : "防止睡眠"
}
}
}
@@ -4610,35 +4658,33 @@
}
},
"sync.error.activity-generation" : {
- "extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Activity history for %@ has no valid generation and cannot be synchronized"
+ "value" : "Activity history for %@ is missing required information and cannot be synced"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "%@ 的活动历史缺少有效代次, 无法同步"
+ "value" : "%@ 的活动历史信息不完整, 无法同步"
}
}
}
},
"sync.error.activity-identity" : {
- "extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "The activity record identity does not match its device, date and generation"
+ "value" : "Activity history information is inconsistent and cannot be synced"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "活动同步记录身份与设备 日期 代次不一致"
+ "value" : "活动历史信息不一致, 无法同步"
}
}
}
@@ -4696,13 +4742,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Service temporarily unavailable"
+ "value" : "Sync service is temporarily unavailable"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "服务暂时不可用"
+ "value" : "同步服务暂不可用"
}
}
}
diff --git a/CodexBar/Services/Activity/ActivityMonitor.swift b/CodexBar/Services/Activity/ActivityMonitor.swift
index 1b23653..247fc16 100644
--- a/CodexBar/Services/Activity/ActivityMonitor.swift
+++ b/CodexBar/Services/Activity/ActivityMonitor.swift
@@ -3,7 +3,7 @@ import Combine
import Foundation
import os
-/// 从共享 app-server 维护实时任务状态, 是菜单栏, 活动卡片, 通知和触觉反馈的任务来源
+/// 从 Codex 后台服务维护实时任务状态, 是菜单栏, 活动卡片, 通知和触觉反馈的任务来源
@MainActor
final class ActivityMonitor: ObservableObject {
@Published private(set) var snapshot = ActivitySnapshot.empty
diff --git a/CodexBar/Services/Activity/ActivityTask.swift b/CodexBar/Services/Activity/ActivityTask.swift
index ce1c1ab..ca34643 100644
--- a/CodexBar/Services/Activity/ActivityTask.swift
+++ b/CodexBar/Services/Activity/ActivityTask.swift
@@ -239,7 +239,7 @@ struct ActivityTask {
lastProgressAt
}
- /// 隐藏还要求共享服务提供的新鲜生命周期覆盖
+ /// 隐藏还要求 Codex 后台服务提供的新鲜生命周期覆盖
func protectionDeadline(at now: Date, inactivityDuration: TimeInterval) -> Date? {
guard hasFreshLifecycle(at: now) else { return nil }
return protectionReferenceAt.addingTimeInterval(inactivityDuration)
diff --git a/CodexBar/Services/AppServer/AccountSession.swift b/CodexBar/Services/AppServer/AccountSession.swift
index c195682..d149721 100644
--- a/CodexBar/Services/AppServer/AccountSession.swift
+++ b/CodexBar/Services/AppServer/AccountSession.swift
@@ -31,7 +31,7 @@ final nonisolated class AccountSession {
as: InitializeResult.self
)
let version = Self.serverVersion(fromUserAgent: result.userAgent)
- let minimum = CodexMinimumVersion.global
+ let minimum = CodexMinimumVersion.account
// 版本未知不能作为明确的低版本结论
guard let version, let isSupported = CodexVersionReader.isVersion(version, atLeast: minimum) else {
throw CodexStatusError.invalidServerResponse
diff --git a/CodexBar/Services/AppServer/AppServerLogViewModel.swift b/CodexBar/Services/AppServer/AppServerLogViewModel.swift
index 9da967d..62005fb 100644
--- a/CodexBar/Services/AppServer/AppServerLogViewModel.swift
+++ b/CodexBar/Services/AppServer/AppServerLogViewModel.swift
@@ -14,7 +14,7 @@ final class AppServerLogViewModel: ObservableObject {
private let storage: AppServerLogStore
private let pageSize: Int
private let maximumEntries: Int
- @Published private(set) var browsingHistory = false
+ private var browsingHistory = false
private var revision: Int64 = 0
private var generation: Int64 = 0
private var isLoaded = false
@@ -134,12 +134,6 @@ final class AppServerLogViewModel: ObservableObject {
}
}
- func showLatest() async {
- guard !isReading else { return }
- isLoaded = false
- await refresh()
- }
-
func clear() async {
let waitingGeneration = observationGeneration
while isReading {
diff --git a/CodexBar/Services/AppServer/AppServerSession.swift b/CodexBar/Services/AppServer/AppServerSession.swift
index ca26bc0..7e4b96a 100644
--- a/CodexBar/Services/AppServer/AppServerSession.swift
+++ b/CodexBar/Services/AppServer/AppServerSession.swift
@@ -2,7 +2,19 @@ import CryptoKit
import Darwin
import Foundation
-/// 每条连接由所属 actor 独占, 通过 Unix WebSocket 访问共享服务, 不拥有 daemon 生命周期
+nonisolated struct AppServerConnectionError: LocalizedError {
+ let code: Int32
+
+ var serverIsAbsent: Bool {
+ code == ENOENT || code == ECONNREFUSED
+ }
+
+ var errorDescription: String? {
+ String(localized: "codex-status.app-server.error.connection-closed") + " (\(String(cString: strerror(code))), errno=\(code))"
+ }
+}
+
+/// 每条连接由所属 actor 独占, 通过 Unix WebSocket 访问 Codex 后台服务, 不拥有 daemon 生命周期
final nonisolated class AppServerSession {
private var descriptor: Int32 = -1
private var nextID = 0
@@ -25,7 +37,8 @@ final nonisolated class AppServerSession {
let connectionLogID = logStorage?.recordConnection(method: "connection/open", detail: socketPath, connection: connectionName, status: .pending)
do {
descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
- guard descriptor >= 0 else { throw CodexStatusError.serverConnectionClosed }
+ guard descriptor >= 0 else { throw AppServerConnectionError(code: errno) }
+ guard fcntl(descriptor, F_SETFL, O_NONBLOCK) == 0 else { throw AppServerConnectionError(code: errno) }
var address = sockaddr_un()
address.sun_family = sa_family_t(AF_UNIX)
let path = Array(socketURL.path.utf8CString)
@@ -40,10 +53,21 @@ final nonisolated class AppServerSession {
Darwin.connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
}
}
- guard result == 0 else { throw CodexStatusError.serverConnectionClosed }
+ if result != 0 {
+ let code = errno
+ guard code == EINPROGRESS else { throw AppServerConnectionError(code: code) }
+ guard try ready(Int16(POLLOUT), before: Date().addingTimeInterval(2)) else {
+ throw CodexStatusError.serverTimeout
+ }
+ var socketError: Int32 = 0
+ var size = socklen_t(MemoryLayout<Int32>.size)
+ guard getsockopt(descriptor, SOL_SOCKET, SO_ERROR, &socketError, &size) == 0 else {
+ throw AppServerConnectionError(code: errno)
+ }
+ guard socketError == 0 else { throw AppServerConnectionError(code: socketError) }
+ }
var enabled: Int32 = 1
_ = setsockopt(descriptor, SOL_SOCKET, SO_NOSIGPIPE, &enabled, socklen_t(MemoryLayout<Int32>.size))
- _ = fcntl(descriptor, F_SETFL, O_NONBLOCK)
try handshake()
if let connectionLogID {
logStorage?.finishRequest(connectionLogID, response: socketPath)
diff --git a/CodexBar/Services/AppServer/AppServerStartup.swift b/CodexBar/Services/AppServer/AppServerStartup.swift
new file mode 100644
index 0000000..cd503b6
--- /dev/null
+++ b/CodexBar/Services/AppServer/AppServerStartup.swift
@@ -0,0 +1,117 @@
+import Foundation
+import os
+
+/// App 启动入口的一次性准备, 只请求官方启动命令, 不接管 Codex 后台服务生命周期
+actor AppServerStartup {
+ private let environment: [String: String]
+ private let installations: CodexInstallations?
+ private let probeConnection: @Sendable () throws -> Void
+ private let commandTimeout: TimeInterval
+ private let readinessAttempts: Int
+
+ init(
+ socketURL: URL = AppServerActivityReader.defaultSocketURL,
+ environment: [String: String] = CodexPaths.environment,
+ installations: CodexInstallations? = nil,
+ commandTimeout: TimeInterval = 15,
+ readinessAttempts: Int = 10,
+ probeConnection: (@Sendable () throws -> Void)? = nil
+ ) {
+ self.environment = environment
+ self.installations = installations
+ self.commandTimeout = commandTimeout
+ self.readinessAttempts = max(1, readinessAttempts)
+ self.probeConnection = probeConnection ?? {
+ let connection = try AppServerSession(socketURL: socketURL, logStorage: nil, connectionName: "startup")
+ connection.close()
+ }
+ }
+
+ func ensureStarted() async throws {
+ try Task.checkCancellation()
+ do {
+ try probeConnection()
+ AppLog.codex.notice("Codex 后台服务已就绪: source=existing")
+ return
+ } catch let error as AppServerConnectionError where error.serverIsAbsent {
+ // 只有明确缺少监听者才启动, 权限或协议错误不改变服务状态
+ }
+
+ let executable = try supportedExecutable()
+ try Task.checkCancellation()
+ // 能力检测期间其他客户端可能已经启动服务
+ do {
+ try probeConnection()
+ return
+ } catch let error as AppServerConnectionError where error.serverIsAbsent {}
+
+ AppLog.codex.notice("Codex 后台服务启动请求已发送")
+ let result = BoundedProcess.run(
+ executable: executable,
+ arguments: ["app-server", "daemon", "start"],
+ timeout: commandTimeout,
+ environment: environment
+ )
+ try Task.checkCancellation()
+ // 命令失败也探测一次, 允许与其他客户端并发启动后复用已就绪的服务
+ for attempt in 0 ..< readinessAttempts {
+ do {
+ try probeConnection()
+ AppLog.codex.notice("Codex 后台服务已就绪: source=daemonStart")
+ return
+ } catch let error as AppServerConnectionError where error.serverIsAbsent {
+ if result.timedOut {
+ throw StartupError.timeout
+ }
+ guard result.exitCode == 0 else { throw StartupError.commandFailed(result.exitCode) }
+ guard attempt + 1 < readinessAttempts else { throw StartupError.notReady }
+ try await Task.sleep(for: .milliseconds(200))
+ }
+ }
+ }
+
+ private func supportedExecutable() throws -> URL {
+ let installations = installations ?? CodexPaths.resolveInstallations(environment: environment)
+ let paths = [installations.globalPath, installations.bundledPath].compactMap(\.self)
+ guard !paths.isEmpty else { throw StartupError.notInstalled }
+ var checked = Set<String>()
+ for path in paths where checked.insert(CodexPaths.canonicalPath(path)).inserted {
+ try Task.checkCancellation()
+ let executable = URL(fileURLWithPath: path)
+ let result = BoundedProcess.run(
+ executable: executable,
+ arguments: ["app-server", "daemon", "start", "--help"],
+ timeout: 2.5,
+ environment: environment
+ )
+ try Task.checkCancellation()
+ if result.exitCode == 0, result.output.contains("daemon start") {
+ return executable
+ }
+ }
+ throw StartupError.unsupportedCommand
+ }
+
+ nonisolated enum StartupError: LocalizedError {
+ case notInstalled
+ case unsupportedCommand
+ case timeout
+ case commandFailed(Int32)
+ case notReady
+
+ var errorDescription: String? {
+ switch self {
+ case .notInstalled:
+ String(localized: "codex.daemon.not-installed")
+ case .unsupportedCommand:
+ String(localized: "codex.daemon.unsupported-command")
+ case .timeout:
+ String(localized: "codex.daemon.timeout")
+ case let .commandFailed(code):
+ String(localized: "codex.daemon.command-failed", defaultValue: "\(code)")
+ case .notReady:
+ String(localized: "codex.daemon.not-ready")
+ }
+ }
+ }
+}
diff --git a/CodexBar/Services/Codex/CodexPaths.swift b/CodexBar/Services/Codex/CodexPaths.swift
index aea13e0..e19059a 100644
--- a/CodexBar/Services/Codex/CodexPaths.swift
+++ b/CodexBar/Services/Codex/CodexPaths.swift
@@ -14,7 +14,7 @@ nonisolated enum CodexExecutableSource: String, Equatable {
}
}
-/// 当前共享 app-server 的握手信息, 不将安装路径误作服务运行来源
+/// 当前 Codex 后台服务的握手信息, 不将安装路径误作服务运行来源
nonisolated struct CodexServerConnectionInfo: Equatable {
let socketPath: String
/// 来自 initialize 握手, 代表当前 app-server 进程真实运行的版本
@@ -38,7 +38,7 @@ nonisolated enum CodexPaths {
}
/// Codex 配置目录: 优先 CODEX_HOME, 回退真实用户 HOME 下的 .codex
- /// 共享服务 socket 位置统一从这里解析
+ /// Codex 后台服务 socket 位置统一从这里解析
static func codexHomeDirectory(environment: [String: String] = environment) -> URL {
if let codexHome = nonEmptyEnvironmentValue("CODEX_HOME", in: environment) {
return URL(fileURLWithPath: codexHome, isDirectory: true)
diff --git a/CodexBar/Services/Codex/CodexVersionService.swift b/CodexBar/Services/Codex/CodexVersionService.swift
index 7208cb7..934b3d6 100644
--- a/CodexBar/Services/Codex/CodexVersionService.swift
+++ b/CodexBar/Services/Codex/CodexVersionService.swift
@@ -40,27 +40,7 @@ nonisolated struct CodexVersionItem: Equatable, Identifiable {
}
var displayVersion: String {
- if path == nil {
- return String(
- localized: "codex.source.error.not-found",
- defaultValue: "\(source.displayName)"
- )
- }
-
- return version ?? errorMessage ?? String(localized: "codex.version.unknown")
- }
-}
-
-/// 安装版本只描述磁盘文件, 不推断共享服务的运行来源
-nonisolated struct CodexVersionDisplay: Equatable {
- let displayVersion: String
- let hasVersion: Bool
- let path: String?
-
- init(item: CodexVersionItem) {
- displayVersion = item.displayVersion
- hasVersion = item.version != nil
- path = item.path
+ version ?? errorMessage ?? String(localized: "codex.version.unknown")
}
}
@@ -342,8 +322,8 @@ private final nonisolated class ProcessExitWaiter: Sendable {
/// CodexBar 各能力依赖的 app-server 最低版本
nonisolated enum CodexMinimumVersion {
- static let global = "0.160.0"
- static let activity = "0.160.0"
+ static let account = "0.157.0"
+ static let activity = "0.157.0"
}
/// 从 ` codex --version` 的输出中提取用户可读版本号
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index f34eb1b..c266516 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -135,7 +135,7 @@ private nonisolated extension ReadResult {
}
}
-/// 独立持有账户连接, 与活动监听连接同一个共享服务
+/// 独立持有账户连接, 与活动监听连接同一个 Codex 后台服务
actor CodexStatusService {
private var connection: AppServerConnection?
private var supplementalDataCache = SupplementalDataCache()
@@ -161,12 +161,7 @@ actor CodexStatusService {
return connection.connectionInfo
}
- /// 需要以实际运行版本做能力检查时建立或复用连接
- func readyConnectionInfo() throws -> CodexServerConnectionInfo {
- try readyConnection().connectionInfo
- }
-
- /// 只重建当前客户端连接, 不重启共享服务
+ /// 只重建当前客户端连接, 不重启 Codex 后台服务
func reconnect(minimumVersion: String) throws -> CodexServerConnectionInfo {
teardownConnection()
supplementalDataCache = SupplementalDataCache()
@@ -654,7 +649,7 @@ actor CodexStatusService {
}
}
-/// 持有共享服务客户端连接及账户和运行版本信息
+/// 持有 Codex 后台服务客户端连接及账户和运行版本信息
private final nonisolated class AppServerConnection {
let session: AccountSession
let connectionInfo: CodexServerConnectionInfo
diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
index 7c2a05a..9a42e48 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
@@ -71,6 +71,7 @@ final class CodexStatusViewModel: ObservableObject {
private var pendingForcedRefreshTrigger: LogTrigger?
private let refreshCoordinator = RefreshTaskCoordinator()
private var connectionInfoGeneration: UInt64 = 0
+ private var startupErrorMessage: String?
init(service: CodexStatusService = CodexStatusService(), defaults: UserDefaults = .standard) {
self.service = service
@@ -93,12 +94,13 @@ final class CodexStatusViewModel: ObservableObject {
refresh(trigger: trigger)
}
- func startAutoRefresh() {
+ func startAutoRefresh(startupError: String? = nil) {
guard autoRefreshTask == nil else {
return
}
- refreshIfNeeded(trigger: .launch)
+ startupErrorMessage = startupError
+ refreshAfterCurrent(trigger: .launch)
scheduleAutoRefresh()
}
@@ -177,7 +179,10 @@ final class CodexStatusViewModel: ObservableObject {
elapsed: duration.elapsed
)
codexConnectionInfo = result.connectionInfo
- connectionErrorMessage = result.fetch.outcome.connectionErrorMessage
+ if loadState != .initializationFailed {
+ startupErrorMessage = nil
+ }
+ connectionErrorMessage = startupErrorMessage ?? result.fetch.outcome.connectionErrorMessage
autoRefreshCountdownStartedAt = Date()
}
)
@@ -280,9 +285,9 @@ final class CodexStatusViewModel: ObservableObject {
}
}
- func reconnectCodex() async -> Bool {
+ func reconnectCodex() async {
guard !isRefreshing, !isReconnecting else {
- return false
+ return
}
isReconnecting = true
@@ -306,7 +311,6 @@ final class CodexStatusViewModel: ObservableObject {
minimumVersion: CodexMinimumVersion.activity
)
didReconnect = true
- return true
} catch {
loadState = switch error {
case CodexStatusError.notLoggedIn: .notLoggedIn
@@ -314,7 +318,6 @@ final class CodexStatusViewModel: ObservableObject {
default: .initializationFailed
}
connectionErrorMessage = error.localizedDescription
- return false
}
}
diff --git a/CodexBar/Services/Settings/AutoResetSettings.swift b/CodexBar/Services/Settings/AutoResetSettings.swift
index d541caa..4f2f5b7 100644
--- a/CodexBar/Services/Settings/AutoResetSettings.swift
+++ b/CodexBar/Services/Settings/AutoResetSettings.swift
@@ -91,7 +91,7 @@ final class AutoResetSettings: ObservableObject {
return leadTime
}
- private static let enabledKey = "AutoReset.enabled"
+ private static let enabledKey = "AutoReset.isEnabled"
private static let leadTimeKey = "AutoReset.leadTimeSeconds"
private static let defaultLeadTime = AutoResetLeadTime.thirtyMinutes
}
diff --git a/CodexBar/Services/Settings/MainPanelSettings.swift b/CodexBar/Services/Settings/MainPanelSettings.swift
index e007490..5ab1e72 100644
--- a/CodexBar/Services/Settings/MainPanelSettings.swift
+++ b/CodexBar/Services/Settings/MainPanelSettings.swift
@@ -4,8 +4,8 @@ import os
nonisolated enum MainPanelSection: String, CaseIterable, Identifiable, Sendable {
case account
- case activity
case quota
+ case activity
case usage
case status
@@ -197,5 +197,5 @@ final class MainPanelSettings: ObservableObject {
private static let sectionOrderKey = "MainPanel.sectionOrder"
private static let hiddenSectionsKey = "MainPanel.hiddenSections"
- private static let animationsEnabledKey = "MainPanel.entranceAnimationsEnabled"
+ private static let animationsEnabledKey = "MainPanel.areAnimationsEnabled"
}
diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swift
index ddc692e..e2c3dff 100644
--- a/CodexBar/Services/Settings/NotificationSettings.swift
+++ b/CodexBar/Services/Settings/NotificationSettings.swift
@@ -350,16 +350,16 @@ final class NotificationSettings: ObservableObject {
return sound
}
- private static let enabledKey = "Notification.enabled"
- private static let lowQuotaEnabledKey = "Notification.lowQuotaEnabled"
- private static let quotaResetEnabledKey = "Notification.quotaResetEnabled"
- private static let taskCompletionEnabledKey = "Notification.taskCompletionEnabled"
- private static let taskWaitingEnabledKey = "Notification.taskWaitingEnabled"
- private static let taskHapticEnabledKey = "Notification.taskHapticEnabled"
- private static let creditExpiryEnabledKey = "Notification.creditExpiryEnabled"
- private static let autoResetEnabledKey = "Notification.autoResetEnabled"
- private static let lowBatteryEnabledKey = "Notification.lowBatteryEnabled"
- private static let keepAliveLimitEnabledKey = "Notification.keepAliveLimitEnabled"
+ private static let enabledKey = "Notification.isEnabled"
+ private static let lowQuotaEnabledKey = "Notification.isLowQuotaEnabled"
+ private static let quotaResetEnabledKey = "Notification.isQuotaResetEnabled"
+ private static let taskCompletionEnabledKey = "Notification.isTaskCompletionEnabled"
+ private static let taskWaitingEnabledKey = "Notification.isTaskWaitingEnabled"
+ private static let taskHapticEnabledKey = "Notification.isTaskHapticEnabled"
+ private static let creditExpiryEnabledKey = "Notification.isCreditExpiryEnabled"
+ private static let autoResetEnabledKey = "Notification.isAutoResetEnabled"
+ private static let lowBatteryEnabledKey = "Notification.isLowBatteryEnabled"
+ private static let keepAliveLimitEnabledKey = "Notification.isKeepAliveLimitEnabled"
private static let lowQuotaThresholdKey = "Notification.lowQuotaThresholdPercent"
private static let taskCompletionMinimumDurationKey = "Notification.taskCompletionMinimumDurationSeconds"
private static let lowQuotaSoundKey = "Notification.lowQuotaSound"
diff --git a/CodexBar/Services/Settings/ProtectionSettings.swift b/CodexBar/Services/Settings/ProtectionSettings.swift
index 548114c..ae1a0fe 100644
--- a/CodexBar/Services/Settings/ProtectionSettings.swift
+++ b/CodexBar/Services/Settings/ProtectionSettings.swift
@@ -36,12 +36,11 @@ final class ProtectionSettings: ObservableObject {
private static func storedDuration(in defaults: UserDefaults) -> InactivityDuration {
let value = defaults.object(forKey: inactivityDurationKey)
- ?? defaults.object(forKey: "KeepAlive.abnormalTaskInactivitySeconds")
return (value as? Int)
.flatMap(InactivityDuration.init(rawValue:)) ?? .oneHour
}
- private static let inactivityDurationKey = "Protection.inactivityDuration"
+ private static let inactivityDurationKey = "Protection.inactivityDurationSeconds"
}
extension ProtectionSettings {
diff --git a/CodexBar/Services/Settings/SyncSettings.swift b/CodexBar/Services/Settings/SyncSettings.swift
index 29b7dd2..a0bebf9 100644
--- a/CodexBar/Services/Settings/SyncSettings.swift
+++ b/CodexBar/Services/Settings/SyncSettings.swift
@@ -82,11 +82,7 @@ final class SyncSettings: ObservableObject {
}
nonisolated static func isEnabled(defaults: UserDefaults = .standard) -> Bool {
- // 新键优先, 旧设置只作为首次改名后的读取来源
- if defaults.object(forKey: enabledKey) != nil {
- return defaults.bool(forKey: enabledKey)
- }
- return defaults.bool(forKey: "WorkflowSync.isEnabled")
+ defaults.bool(forKey: enabledKey)
}
private func observeSyncNotifications() {
diff --git a/CodexBar/Services/Settings/TaskGlowSettings.swift b/CodexBar/Services/Settings/TaskGlowSettings.swift
index 7dc5fa6..d8006d0 100644
--- a/CodexBar/Services/Settings/TaskGlowSettings.swift
+++ b/CodexBar/Services/Settings/TaskGlowSettings.swift
@@ -97,7 +97,7 @@ final class TaskGlowSettings: ObservableObject {
private let previewSubject = PassthroughSubject<TaskGlowPreviewRequest, Never>()
private static let enabledKey = "TaskGlow.isEnabled"
private static let speedKey = "TaskGlow.animationSpeed"
- private static let durationKey = "TaskGlow.terminalDuration"
+ private static let durationKey = "TaskGlow.terminalDurationSeconds"
private static let brightnessKey = "TaskGlow.brightness"
private static func colorKey(_ role: TaskGlowColorRole) -> String {
diff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swift
index 0e287d5..f721725 100644
--- a/CodexBar/Views/Log/LogView.swift
+++ b/CodexBar/Views/Log/LogView.swift
@@ -47,12 +47,6 @@ struct LogView: View {
Spacer()
- if store.browsingHistory {
- Button("log.action.latest") { Task { await store.showLatest() } }
- .controlSize(.small)
- .disabled(store.isLoading)
- }
-
Button {
Task { await store.clear() }
} label: {
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 51c13e3..b3037f6 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -258,12 +258,9 @@ private extension AppSettingsView {
VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
mainPanelLayoutRow
LiquidGlassDivider()
- MainPanelAnimationsSettingsRow(settings: mainPanelSettings)
+ notificationRow
LiquidGlassDivider()
- TaskGlowSettingsRow(
- settings: taskGlowSettings,
- onOptionsAction: onOptionsAction
- )
+ MainPanelAnimationsSettingsRow(settings: mainPanelSettings)
LiquidGlassDivider()
launchAtLoginRow
LiquidGlassDivider()
@@ -282,7 +279,10 @@ private extension AppSettingsView {
var advancedSettingsPage: some View {
VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
- notificationRow
+ TaskGlowSettingsRow(
+ settings: taskGlowSettings,
+ onOptionsAction: onOptionsAction
+ )
LiquidGlassDivider()
autoResetRow
LiquidGlassDivider()
@@ -935,7 +935,7 @@ private extension AppSettingsView {
errorMessage: statusViewModel.connectionErrorMessage,
onReconnect: {
Task { @MainActor in
- _ = await statusViewModel.reconnectCodex()
+ await statusViewModel.reconnectCodex()
codexVersions.refresh(force: true)
}
}
diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swift
index 0630a17..f865e54 100644
--- a/CodexBar/Views/Settings/CodexVersionSection.swift
+++ b/CodexBar/Views/Settings/CodexVersionSection.swift
@@ -1,7 +1,7 @@
import AppKit
import SwiftUI
-/// 分别展示安装版本和共享服务运行版本, 只重连当前客户端
+/// 分别展示安装版本和 Codex 后台服务运行版本, 只重连当前客户端
struct CodexVersionSection: View {
@EnvironmentObject private var animationState: SettingsWindowAnimationState
let snapshot: CodexVersionSnapshot
@@ -121,8 +121,7 @@ struct CodexVersionSection: View {
}
private func codexVersionRow(icon: String, item: CodexVersionItem) -> some View {
- let row = CodexVersionDisplay(item: item)
- let isUnavailable = snapshot.refreshedAt != .distantPast && item.path == nil
+ let hasVersion = item.version != nil
let isPathCopied = copiedPathResetTasks[item.source.rawValue] != nil
return HStack(alignment: .top, spacing: 10) {
@@ -136,19 +135,14 @@ struct CodexVersionSection: View {
Spacer(minLength: 28)
VStack(alignment: .trailing, spacing: 3) {
- HStack(spacing: 12) {
- if row.hasVersion || !isUnavailable {
- Text(row.displayVersion)
- .font(row.hasVersion ? .body.monospacedDigit() : .body)
- .foregroundStyle(row.hasVersion ? .secondary : .tertiary)
- .lineLimit(1)
- .contentTransition(.opacity)
- .animation(Metrics.statusAnimation, value: row.displayVersion)
- }
- }
- .animation(Metrics.statusAnimation, value: isUnavailable)
-
- if let path = row.path {
+ Text(item.displayVersion)
+ .font(hasVersion ? .body.monospacedDigit() : .body)
+ .foregroundStyle(hasVersion ? .secondary : .tertiary)
+ .lineLimit(1)
+ .contentTransition(.opacity)
+ .animation(Metrics.statusAnimation, value: item.displayVersion)
+
+ if let path = item.path {
CopyablePathText(path: path, isCopied: isPathCopied)
.animation(Metrics.statusAnimation, value: isPathCopied)
.help(
@@ -163,7 +157,7 @@ struct CodexVersionSection: View {
}
}
.frame(maxWidth: Metrics.versionColumnWidth, alignment: .trailing)
- .animation(Metrics.statusAnimation, value: row.path)
+ .animation(Metrics.statusAnimation, value: item.path)
}
}
diff --git a/CodexBarTests/AppServerLogTests.swift b/CodexBarTests/AppServerLogTests.swift
index 76436fa..4a0c9c6 100644
--- a/CodexBarTests/AppServerLogTests.swift
+++ b/CodexBarTests/AppServerLogTests.swift
@@ -262,12 +262,13 @@ extension AppServerLogTests {
visited.formUnion(model.entries.map(\.id))
}
#expect(visited.count == 20)
- #expect(model.browsingHistory)
+ let historyIDs = model.entries.map(\.id)
storage.recordFailure(message: "latest")
await model.refresh()
#expect(model.entries.count <= 6)
- await model.showLatest()
- #expect(!model.browsingHistory)
+ #expect(model.entries.map(\.id) == historyIDs)
+ model.stop()
+ await model.refresh()
#expect(model.entries.first?.detail == "latest")
}
}
diff --git a/CodexBarTests/AppServerSessionTests.swift b/CodexBarTests/AppServerSessionTests.swift
index c4a21a3..2dec0d6 100644
--- a/CodexBarTests/AppServerSessionTests.swift
+++ b/CodexBarTests/AppServerSessionTests.swift
@@ -13,7 +13,7 @@ struct AppServerSessionTests {
let server = try SharedServerFixture { peer in
let initialize = try peer.readMessage()
#expect(initialize["method"] as? String == "initialize")
- try peer.reply(to: initialize, result: ["userAgent": supported ? "codex/0.160.0" : "codex/0.159.0"])
+ try peer.reply(to: initialize, result: ["userAgent": supported ? "codex/0.157.0" : "codex/0.156.0"])
if supported {
#expect(try peer.readMessage()["method"] as? String == "initialized")
for _ in 0 ..< 4 {
@@ -195,7 +195,7 @@ struct AppServerSessionTests {
let initialize = try peer.readMessage()
#expect(initialize["method"] as? String == "initialize")
#expect((initialize["params"] as? [String: Any])?["capabilities"] as? [String: Bool] == ["experimentalApi": true])
- try peer.reply(to: initialize, result: ["userAgent": "codex/0.160.0"])
+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.157.0"])
#expect(try peer.readMessage()["method"] as? String == "initialized")
let account = try peer.readMessage()
#expect(account["method"] as? String == "account/read")
@@ -205,7 +205,7 @@ struct AppServerSessionTests {
defer { server.close() }
let session = try AccountSession(socketURL: server.url, logStorage: nil)
let result = try session.initializeAccount()
- #expect(result.version == "0.160.0")
+ #expect(result.version == "0.157.0")
#expect(result.account.account != nil)
session.close()
#expect(!session.isOpen)
@@ -263,7 +263,7 @@ struct AppServerSessionTests {
@Test func missingSharedSocketFailsWithoutFallback() throws {
let url = URL(fileURLWithPath: "/tmp/\(UUID().uuidString).sock")
- #expect(throws: CodexStatusError.self) {
+ #expect(throws: AppServerConnectionError.self) {
_ = try AccountSession(socketURL: url, logStorage: nil)
}
#expect(!FileManager.default.fileExists(atPath: url.path))
diff --git a/CodexBarTests/AppServerStartupTests.swift b/CodexBarTests/AppServerStartupTests.swift
new file mode 100644
index 0000000..9e8b7c1
--- /dev/null
+++ b/CodexBarTests/AppServerStartupTests.swift
@@ -0,0 +1,179 @@
+import Darwin
+import Foundation
+import os
+import Testing
+
+struct AppServerStartupTests {
+ @Test func reusesRunningServiceWithoutAnInstalledCLI() async throws {
+ let server = try SharedServerFixture { _ in }
+ defer { server.close() }
+ let startup = AppServerStartup(
+ socketURL: server.url, environment: [:],
+ installations: CodexInstallations(globalPath: nil, bundledPath: nil)
+ )
+ try await startup.ensureStarted()
+ try server.finish()
+ }
+
+ @Test func startsMissingServiceWithResolvedEnvironmentAndBundledFallback() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let unsupported = try executable(in: directory, name: "old codex", body: "exit 2")
+ let supported = try executable(in: directory, body: """
+ printf '%s\\n' "$*" >> "$HOME/calls"
+ if [ "$4" = '--help' ]; then
+ printf 'Usage: codex app-server daemon start [OPTIONS]'
+ elif [ "$*" = 'app-server daemon start' ]; then
+ printf '%s' "$CODEX_HOME" > "$HOME/started"
+ else
+ exit 4
+ fi
+ """)
+ let server = try SharedServerFixture { _ in }
+ defer { server.close() }
+ let marker = directory.url.appendingPathComponent("started")
+ let environment = ["HOME": directory.url.path, "CODEX_HOME": directory.url.appendingPathComponent("custom codex").path]
+ let startup = AppServerStartup(
+ environment: environment,
+ installations: CodexInstallations(globalPath: unsupported.path, bundledPath: supported.path),
+ probeConnection: {
+ guard FileManager.default.fileExists(atPath: marker.path) else {
+ throw AppServerConnectionError(code: ENOENT)
+ }
+ let connection = try AppServerSession(socketURL: server.url, logStorage: nil)
+ connection.close()
+ }
+ )
+ try await startup.ensureStarted()
+ #expect(try String(contentsOf: marker, encoding: .utf8) == environment["CODEX_HOME"])
+ #expect(try String(contentsOf: directory.url.appendingPathComponent("calls"), encoding: .utf8) == """
+ app-server daemon start --help
+ app-server daemon start
+
+ """)
+ try server.finish()
+ }
+
+ @Test(arguments: [EACCES, EPERM, ENOTSOCK])
+ func doesNotStartServiceForOtherConnectionErrors(_ code: Int32) async throws {
+ let startup = AppServerStartup(
+ environment: [:], installations: CodexInstallations(globalPath: nil, bundledPath: nil),
+ probeConnection: { throw AppServerConnectionError(code: code) }
+ )
+ do {
+ try await startup.ensureStarted()
+ Issue.record("Expected connection failure")
+ } catch let error as AppServerConnectionError {
+ #expect(error.code == code)
+ }
+ }
+
+ @Test func doesNotStartServiceForHandshakeFailure() async throws {
+ let startup = AppServerStartup(
+ environment: [:], installations: CodexInstallations(globalPath: nil, bundledPath: nil),
+ probeConnection: { throw CodexStatusError.invalidServerResponse }
+ )
+ await #expect(throws: CodexStatusError.self) { try await startup.ensureStarted() }
+ }
+
+ @Test func reportsMissingAndUnsupportedInstallations() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let unsupported = try executable(in: directory, body: "exit 2")
+ for path in [nil, unsupported.path] {
+ let startup = AppServerStartup(
+ environment: [:], installations: CodexInstallations(globalPath: path, bundledPath: nil),
+ probeConnection: { throw AppServerConnectionError(code: ECONNREFUSED) }
+ )
+ do {
+ try await startup.ensureStarted()
+ Issue.record("Expected startup failure")
+ } catch let error as AppServerStartup.StartupError {
+ switch error {
+ case .notInstalled: #expect(path == nil)
+ case .unsupportedCommand: #expect(path != nil)
+ default: Issue.record("Unexpected error: \(error)")
+ }
+ }
+ }
+ }
+
+ @Test(arguments: ["exit 7", "exit 0", "trap '' TERM; while :; do :; done"])
+ func boundsFailedStartsAndReadinessRetries(_ body: String) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let command = try executable(in: directory, body: """
+ if [ "$4" = '--help' ]; then
+ printf 'Usage: codex app-server daemon start [OPTIONS]'
+ exit 0
+ fi
+ printf 'start\\n' >> "$HOME/calls"
+ \(body)
+ """)
+ let startup = AppServerStartup(
+ environment: ["HOME": directory.url.path],
+ installations: CodexInstallations(globalPath: command.path, bundledPath: nil),
+ commandTimeout: 0.3, readinessAttempts: 2,
+ probeConnection: { throw AppServerConnectionError(code: ECONNREFUSED) }
+ )
+ let started = ContinuousClock.now
+ do {
+ try await startup.ensureStarted()
+ Issue.record("Expected startup failure")
+ } catch let error as AppServerStartup.StartupError {
+ switch error {
+ case let .commandFailed(code): #expect(body == "exit 7" && code == 7)
+ case .notReady: #expect(body == "exit 0")
+ case .timeout: #expect(body.hasPrefix("trap"))
+ default: Issue.record("Unexpected error: \(error)")
+ }
+ }
+ #expect(started.duration(to: .now) < .seconds(3))
+ #expect(try String(contentsOf: directory.url.appendingPathComponent("calls"), encoding: .utf8) == "start\n")
+ }
+
+ @Test func rechecksConnectionBeforeIssuingStart() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let command = try executable(in: directory, body: """
+ if [ "$4" != '--help' ]; then
+ printf 'unexpected start' > "$HOME/started"
+ exit 1
+ fi
+ printf 'Usage: codex app-server daemon start [OPTIONS]'
+ """)
+ let probes = OSAllocatedUnfairLock(initialState: 0)
+ let startup = AppServerStartup(
+ environment: ["HOME": directory.url.path],
+ installations: CodexInstallations(globalPath: command.path, bundledPath: nil),
+ probeConnection: {
+ let count = probes.withLock { $0 += 1
+ return $0
+ }
+ if count == 1 {
+ throw AppServerConnectionError(code: ENOENT)
+ }
+ }
+ )
+ try await startup.ensureStarted()
+ #expect(probes.withLock { $0 } == 2)
+ #expect(!FileManager.default.fileExists(atPath: directory.url.appendingPathComponent("started").path))
+ }
+
+ @Test nonisolated func missingSocketPreservesConnectionErrno() throws {
+ let socket = URL(fileURLWithPath: "/tmp/\(UUID().uuidString).sock")
+ do {
+ _ = try AppServerSession(socketURL: socket, logStorage: nil)
+ Issue.record("Expected missing socket")
+ } catch let error as AppServerConnectionError {
+ #expect(error.code == ENOENT)
+ #expect(error.serverIsAbsent)
+ }
+ }
+
+ private func executable(in directory: TestDirectory, name: String = "fake codex", body: String) throws -> URL {
+ let url = try directory.write("#!/bin/sh\n\(body)\n", to: name)
+ try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path)
+ return url
+ }
+}
diff --git a/CodexBarTests/BoundedProcessTests.swift b/CodexBarTests/BoundedProcessTests.swift
index 90746d8..8109ef5 100644
--- a/CodexBarTests/BoundedProcessTests.swift
+++ b/CodexBarTests/BoundedProcessTests.swift
@@ -2,6 +2,23 @@ import Foundation
import Testing
struct BoundedProcessTests {
+ @Test func cancellationTerminatesOnlyTheCommandPromptly() async throws {
+ let task = Task.detached {
+ BoundedProcess.run(
+ executable: URL(fileURLWithPath: "/bin/sh"),
+ arguments: ["-c", "trap '' TERM; while :; do :; done"], timeout: 15
+ )
+ }
+ try await Task.sleep(for: .milliseconds(100))
+ let started = ContinuousClock.now
+ task.cancel()
+ let result = await task.value
+ #expect(result.exitCode != 0)
+ #expect(!result.timedOut)
+ #expect(result.runningProcess == nil)
+ #expect(started.duration(to: .now) < .seconds(3))
+ }
+
@Test nonisolated func processTimeoutKillsUncooperativeChildAndBoundsOutput() {
let started = ContinuousClock.now
let result = BoundedProcess.run(
diff --git a/CodexBarTests/CodexVersionTests.swift b/CodexBarTests/CodexVersionTests.swift
index 5c091e5..32a484f 100644
--- a/CodexBarTests/CodexVersionTests.swift
+++ b/CodexBarTests/CodexVersionTests.swift
@@ -4,14 +4,15 @@ import Testing
struct CodexVersionTests {
@Test(arguments: [
("0.150.0", false),
- ("0.152.1", false),
- ("0.160.0-alpha.2", false),
- ("0.160.0", true),
+ ("0.156.0", false),
+ ("0.157.0-alpha.2", false),
+ ("0.157.0", true),
+ ("0.160.0-alpha.2", true),
("0.160.1", true)
])
func activityRequiresSharedServerProtocol(_ version: String, _ expected: Bool) {
#expect(CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.activity) == expected)
- #expect(CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.global) == expected)
+ #expect(CodexVersionReader.isVersion(version, atLeast: CodexMinimumVersion.account) == expected)
}
@Test(arguments: [
@@ -32,13 +33,6 @@ struct CodexVersionTests {
#expect(CodexVersionReader.isVersion(version, atLeast: "0.150.0") == nil)
}
- @Test func installedVersionDoesNotClaimToBeSharedServerVersion() {
- let item = CodexVersionItem(source: .global, path: "/installed/codex", version: "0.160.1")
- let display = CodexVersionDisplay(item: item)
- #expect(display.displayVersion == "0.160.1")
- #expect(display.path == "/installed/codex")
- }
-
@Test func codexHomeUsesExplicitEnvironmentAndTrimsWhitespace() {
#expect(CodexPaths.codexHomeDirectory(environment: ["CODEX_HOME": " /tmp/custom ", "HOME": "/tmp/home"]).path == "/tmp/custom")
#expect(CodexPaths.codexHomeDirectory(environment: ["CODEX_HOME": " ", "HOME": "/tmp/home"]).path == "/tmp/home/.codex")
diff --git a/CodexBarTests/SettingsTests.swift b/CodexBarTests/SettingsTests.swift
index 76db28a..db15907 100644
--- a/CodexBarTests/SettingsTests.swift
+++ b/CodexBarTests/SettingsTests.swift
@@ -3,30 +3,27 @@ import Testing
struct SettingsTests {
@Test(arguments: [false, true])
- func syncPreferencePreservesOldValueAndPrefersNewKey(_ oldValue: Bool) throws {
+ func syncPreferenceDefaultsOffAndReadsStoredValue(_ enabled: Bool) throws {
let preferences = try TestPreferences()
defer { preferences.remove() }
let defaults = preferences.defaults
#expect(!SyncSettings.isEnabled(defaults: defaults))
- defaults.set(oldValue, forKey: "WorkflowSync.isEnabled")
- #expect(SyncSettings.isEnabled(defaults: defaults) == oldValue)
- defaults.set(!oldValue, forKey: "Sync.isEnabled")
- #expect(SyncSettings.isEnabled(defaults: defaults) == !oldValue)
+ defaults.set(enabled, forKey: "Sync.isEnabled")
+ #expect(SyncSettings.isEnabled(defaults: defaults) == enabled)
}
- @Test func protectionPreferencePreservesOldValueAndWritesNewKey() throws {
+ @Test func protectionPreferencePersistsAndRefreshes() throws {
let preferences = try TestPreferences()
defer { preferences.remove() }
let defaults = preferences.defaults
- defaults.set(7200, forKey: "KeepAlive.abnormalTaskInactivitySeconds")
let settings = ProtectionSettings(defaults: defaults)
- #expect(settings.inactivityDuration == .twoHours)
+ #expect(settings.inactivityDuration == .oneHour)
settings.setInactivityDuration(.thirtyMinutes)
- #expect(defaults.integer(forKey: "Protection.inactivityDuration") == 1800)
- defaults.set(14400, forKey: "KeepAlive.abnormalTaskInactivitySeconds")
+ #expect(defaults.integer(forKey: "Protection.inactivityDurationSeconds") == 1800)
+ defaults.set(14400, forKey: "Protection.inactivityDurationSeconds")
settings.refresh()
- #expect(settings.inactivityDuration == .thirtyMinutes)
- #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .thirtyMinutes)
+ #expect(settings.inactivityDuration == .fourHours)
+ #expect(ProtectionSettings(defaults: defaults).inactivityDuration == .fourHours)
}
@Test(arguments: DataUpdateInterval.allCases)
@@ -77,12 +74,12 @@ struct SettingsTests {
defer { preferences.remove() }
let defaults = preferences.defaults
#expect(MainPanelSettings(defaults: defaults).areAnimationsEnabled)
- defaults.set(false, forKey: "MainPanel.entranceAnimationsEnabled")
+ defaults.set(false, forKey: "MainPanel.areAnimationsEnabled")
let settings = MainPanelSettings(defaults: defaults)
#expect(!settings.areAnimationsEnabled)
settings.setAnimationsEnabled(true)
- #expect(defaults.bool(forKey: "MainPanel.entranceAnimationsEnabled"))
- defaults.set(false, forKey: "MainPanel.entranceAnimationsEnabled")
+ #expect(defaults.bool(forKey: "MainPanel.areAnimationsEnabled"))
+ defaults.set(false, forKey: "MainPanel.areAnimationsEnabled")
settings.refresh()
#expect(!settings.areAnimationsEnabled)
}
@@ -115,12 +112,12 @@ struct SettingsTests {
@Test func protectionFallsBackToOneHourAndReloadsChanges() throws {
let preferences = try TestPreferences()
defer { preferences.remove() }
- preferences.defaults.set("invalid", forKey: "Protection.inactivityDuration")
+ preferences.defaults.set("invalid", forKey: "Protection.inactivityDurationSeconds")
let settings = ProtectionSettings(defaults: preferences.defaults)
#expect(settings.inactivityDuration == .oneHour)
settings.setInactivityDuration(.thirtyMinutes)
#expect(ProtectionSettings(defaults: preferences.defaults).inactivityDuration == .thirtyMinutes)
- preferences.defaults.set(7200, forKey: "Protection.inactivityDuration")
+ preferences.defaults.set(7200, forKey: "Protection.inactivityDurationSeconds")
settings.refresh()
#expect(settings.inactivityDuration == .twoHours)
}
diff --git a/CodexBarTests/TaskGlowTests.swift b/CodexBarTests/TaskGlowTests.swift
index 0867fc1..3c5598a 100644
--- a/CodexBarTests/TaskGlowTests.swift
+++ b/CodexBarTests/TaskGlowTests.swift
@@ -140,7 +140,7 @@ struct TaskGlowTests {
preferences.defaults.set("invalid", forKey: "TaskGlow.color.running")
preferences.defaults.set("FFFFFFF", forKey: "TaskGlow.color.waiting")
preferences.defaults.set("future", forKey: "TaskGlow.animationSpeed")
- preferences.defaults.set(-2, forKey: "TaskGlow.terminalDuration")
+ preferences.defaults.set(-2, forKey: "TaskGlow.terminalDurationSeconds")
preferences.defaults.set(4, forKey: "TaskGlow.brightness")
let settings = TaskGlowSettings(defaults: preferences.defaults)
#expect(settings.appearance == TaskGlowAppearance())
diff --git a/README.en.md b/README.en.md
index 43890fa..1abe284 100644
--- a/README.en.md
+++ b/README.en.md
@@ -81,7 +81,8 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy
- macOS 15.0 or later
- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed
-- A running Codex interactive session with the background service enabled, using shared-service version `0.160.0` or later
+- 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
- Cross-device sync requires an available iCloud account on the Mac
## Quick Start
@@ -89,7 +90,7 @@ Download the latest version from [GitHub Releases](https://github.com/bob-zebedy
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 notifications, sleep prevention, and sync under `Settings > Advanced`
+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.
@@ -101,7 +102,7 @@ Raw activity events and live tasks are processed locally. Enabling cross-device
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; use **Latest** to return from older history to the live list. Database indexes and WAL files add storage overhead.
+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.
## Feedback
diff --git a/README.md b/README.md
index b3913da..e78f3ff 100644
--- a/README.md
+++ b/README.md
@@ -81,7 +81,9 @@ brew install --cask bob-zebedy/tap/codexbar
- macOS 15.0 或更高版本
- 已安装并登录 [Codex CLI](https://github.com/openai/codex) 或安装了内置 Codex 的 ChatGPT App 或 Codex App
-- 已启动启用后台服务的 Codex 交互会话,共享服务版本为 `0.160.0` 或更高版本
+- Codex 后台服务版本为 `0.157.0` 或更高版本
+- CodexBar 启动时连接 Codex 后台服务,未运行时通过已安装 Codex 的 `codex app-server daemon start` 命令启动,退出后保留该进程
+- 若已安装的 Codex 不支持启动命令,需先启动启用后台服务的 Codex 交互会话
- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户
## 快速开始
@@ -89,7 +91,7 @@ brew install --cask bob-zebedy/tap/codexbar
1. 启动 CodexBar,在菜单栏找到 CodexBar 图标
2. 左键点击图标查看账户、额度和 Token 用量
3. 右键或按住 Control 点击图标打开设置、日志或退出菜单
-4. 会话活动和统计随 App 启动;在 `设置 > 高级` 中按需配置通知、防睡眠和同步
+4. 会话活动和统计随 App 启动;在 `设置 > 通用` 中配置系统通知,在 `设置 > 高级` 中配置防睡眠和同步
默认全局快捷键为 `⌘⇧E`,可在设置中重新录制或关闭。
@@ -101,7 +103,7 @@ brew install --cask bob-zebedy/tap/codexbar
活动历史按已记录的事件重建,Token 历史按采集期间保存的原始累计计数观测重新计算。两者保留 210 天的数据;重建无法补回未采集的消耗或已删除的原始记录。跨设备 Token 修正缺少可核对的覆盖关系时,对应日期不生成历史 Token 汇总。
-请求日志最多保留 10,000 条,序列化记录总量不超过 50 MiB,单份请求或响应正文最多保留 64 KiB。超过限制时清理最旧记录,超长正文带截断标记。日志窗口最多缓存 1,000 条,浏览更早记录后可通过“最新日志”返回实时列表。数据库索引和 WAL 会产生额外文件开销。
+请求日志最多保留 10,000 条,序列化记录总量不超过 50 MiB,单份请求或响应正文最多保留 64 KiB。超过限制时清理最旧记录,超长正文带截断标记。日志窗口最多缓存 1,000 条,浏览更早记录后可关闭并重新打开窗口返回实时列表。数据库索引和 WAL 会产生额外文件开销。
## 反馈
diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swift
index d2c0360..9570af5 100755
--- a/Scripts/cleanup.swift
+++ b/Scripts/cleanup.swift
@@ -395,7 +395,7 @@ private final class KeepAliveCleanupCommand {
}
try runChecked(destinationExecutableURL.path, ["--unregister-child", target.plistName])
- for key in ["KeepAlive.isEnabled", "AutoReset.enabled"] {
+ for key in ["KeepAlive.isEnabled", "AutoReset.isEnabled"] {
try runChecked(
"/usr/bin/defaults",
["write", target.bundleIdentifier, key, "-bool", "false"]
diff --git a/Shared/BoundedProcess.swift b/Shared/BoundedProcess.swift
index 6c8428c..ee593ad 100644
--- a/Shared/BoundedProcess.swift
+++ b/Shared/BoundedProcess.swift
@@ -10,10 +10,14 @@ nonisolated enum BoundedProcess {
let runningProcess: Process?
}
- static func run(executable: URL, arguments: [String], timeout: TimeInterval = 2.5) -> Result {
+ static func run(executable: URL, arguments: [String], timeout: TimeInterval = 2.5, environment: [String: String]? = nil) -> Result {
let process = Process()
process.executableURL = executable
process.arguments = arguments
+ process.environment = environment
+ guard !Task.isCancelled else {
+ return Result(exitCode: -1, output: "", timedOut: false, runningProcess: nil)
+ }
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
@@ -26,11 +30,12 @@ nonisolated enum BoundedProcess {
defer { pipe.fileHandleForReading.closeFile() }
let clock = ContinuousClock()
let deadline = clock.now.advanced(by: .seconds(max(0, timeout)))
- let killDeadline = deadline.advanced(by: .milliseconds(250))
- let end = killDeadline.advanced(by: .milliseconds(500))
+ var killDeadline = deadline.advanced(by: .milliseconds(250))
+ var end = killDeadline.advanced(by: .milliseconds(500))
var output = Data()
var buffer = [UInt8](repeating: 0, count: 8192)
var terminated = false
+ var timedOut = false
var killed = false
while true {
// 每轮读取有界, 持续输出不能阻止检查超时
@@ -44,8 +49,11 @@ nonisolated enum BoundedProcess {
if !process.isRunning {
break
}
- if clock.now >= deadline, !terminated {
+ if clock.now >= deadline || Task.isCancelled, !terminated {
+ timedOut = clock.now >= deadline
terminated = true
+ killDeadline = clock.now.advanced(by: .milliseconds(250))
+ end = killDeadline.advanced(by: .milliseconds(500))
process.terminate()
}
if clock.now >= killDeadline, !killed {
@@ -61,7 +69,7 @@ nonisolated enum BoundedProcess {
return Result(
exitCode: terminated || running ? -1 : process.terminationStatus,
output: String(decoding: output, as: UTF8.self),
- timedOut: terminated,
+ timedOut: timedOut,
runningProcess: running ? process : nil
)
}