Skip to content

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

feat: 支持选择 Codex 来源与刷新连接

Bob809741b53c83
diff --git a/CodexBar/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swift
index dc5dbc9..562feb6 100644
--- a/CodexBar/Models/CodexStatusError.swift
+++ b/CodexBar/Models/CodexStatusError.swift
@@ -3,6 +3,7 @@ import Foundation
/// UI 和日志共用的 app-server 错误分类, 保留可重试/需重连判断
nonisolated enum CodexStatusError: LocalizedError {
case executableNotFound
+ case sourceUnavailable(CodexCLIExecutableSource)
case serverTimeout
case serverConnectionClosed
case invalidServerResponse
@@ -16,6 +17,8 @@ nonisolated enum CodexStatusError: LocalizedError {
switch self {
case .executableNotFound:
String(localized: "codex-status.error.executable-not-found")
+ case let .sourceUnavailable(source):
+ "\(source.displayName): \(String(localized: "settings.codex-version.unavailable"))"
case .serverTimeout:
String(localized: "codex-status.error.server-timeout")
case .serverConnectionClosed:
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index ddcc5b1..1e40b2e 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -3473,6 +3473,86 @@
}
}
},
+ "settings.codex-version.reconnect" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Refresh Connection"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "刷新连接"
+ }
+ }
+ }
+ },
+ "settings.codex-version.reconnecting" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Reconnecting…"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在重新连接…"
+ }
+ }
+ }
+ },
+ "settings.codex-version.source.automatic" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Automatic"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自动"
+ }
+ }
+ }
+ },
+ "settings.codex-version.source.select" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Select Source"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "选择来源"
+ }
+ }
+ }
+ },
+ "settings.codex-version.source.title" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Source"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "来源"
+ }
+ }
+ }
+ },
"settings.codex-version.title" : {
"localizations" : {
"en" : {
@@ -3489,6 +3569,22 @@
}
}
},
+ "settings.codex-version.unavailable" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Unavailable"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "不可用"
+ }
+ }
+ }
+ },
"settings.codex-version.updated-to" : {
"localizations" : {
"en" : {
diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
index befd54f..7a2a59e 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift
@@ -1,7 +1,7 @@
import Darwin
import Foundation
-/// CodexBar 支持全局 CLI 优先, 找不到时回退 Codex APP 内置 CLI
+/// 可用于启动 app-server 的安装来源
nonisolated enum CodexCLIExecutableSource: String, Equatable {
case global
case bundled
@@ -14,6 +14,39 @@ nonisolated enum CodexCLIExecutableSource: String, Equatable {
}
}
+/// 自动沿用 CLI 优先的解析规则, 手动选择只使用指定来源
+nonisolated enum CodexCLISourceSelection: String, CaseIterable, Identifiable {
+ case automatic
+ case global
+ case bundled
+
+ var id: Self {
+ self
+ }
+
+ var source: CodexCLIExecutableSource? {
+ switch self {
+ case .automatic: nil
+ case .global: .global
+ case .bundled: .bundled
+ }
+ }
+
+ var title: String {
+ source?.displayName ?? String(localized: "settings.codex-version.source.automatic")
+ }
+
+ static func load(from defaults: UserDefaults) -> Self {
+ defaults.string(forKey: defaultsKey).flatMap(Self.init(rawValue:)) ?? .automatic
+ }
+
+ func save(to defaults: UserDefaults) {
+ defaults.set(rawValue, forKey: Self.defaultsKey)
+ }
+
+ private static let defaultsKey = "CodexCLI.sourceSelection"
+}
+
/// 启动 app-server 所需的可执行文件和固定 stdio 参数
nonisolated struct AppServerCommand: Equatable {
let source: CodexCLIExecutableSource
@@ -62,13 +95,15 @@ nonisolated enum CodexCLIResolver {
]
static let environment = appServerEnvironment()
- static func resolveAppServerCommand(environment: [String: String] = environment) throws -> AppServerCommand {
- try command(from: resolveInstallations(environment: environment))
- }
-
/// 从已解析的安装信息派生命令, 避免重复扫描 PATH
- static func command(from installations: CodexCLIInstallations) throws -> AppServerCommand {
- guard let source = installations.activeSource,
+ static func command(
+ from installations: CodexCLIInstallations,
+ source: CodexCLIExecutableSource? = nil
+ ) throws -> AppServerCommand {
+ if let source, installations.path(for: source) == nil {
+ throw CodexStatusError.sourceUnavailable(source)
+ }
+ guard let source = source ?? installations.activeSource,
let path = installations.path(for: source) else {
throw CodexStatusError.executableNotFound
}
diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
index 4a48698..4ed100e 100644
--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift
@@ -75,35 +75,12 @@ nonisolated struct CodexCLIVersionDisplay: Equatable {
if let runningVersion,
let installed = item.version,
- Self.isInstalledVersionNewer(installed, than: runningVersion) {
+ CodexCLIVersionReader.isVersion(installed, newerThan: runningVersion) == true {
newerInstalledVersion = installed
} else {
newerInstalledVersion = nil
}
}
-
- private static func isInstalledVersionNewer(
- _ installedVersion: String,
- than runningVersion: String
- ) -> Bool {
- guard let installedComponents = normalizedVersionComponents(from: installedVersion),
- let runningComponents = normalizedVersionComponents(from: runningVersion) else {
- return false
- }
-
- return runningComponents.lexicographicallyPrecedes(installedComponents)
- }
-
- private static func normalizedVersionComponents(from version: String) -> [Int]? {
- let components = version
- .components(separatedBy: CharacterSet.decimalDigits.inverted)
- .compactMap { $0.isEmpty ? nil : Int($0) }
- guard !components.isEmpty else {
- return nil
- }
-
- return Array(components.reversed().drop(while: { $0 == 0 }).reversed())
- }
}
/// 并发检测 Codex CLI 与 Codex APP 内置 CLI 的磁盘版本
@@ -407,6 +384,16 @@ nonisolated enum CodexCLIVersionReader {
return parsedVersion >= parsedMinimumVersion
}
+ /// 返回 nil 表示任一版本不可识别, 构建标记不影响版本优先级
+ static func isVersion(_ version: String, newerThan otherVersion: String) -> Bool? {
+ guard let parsedVersion = SemanticVersion(version),
+ let parsedOtherVersion = SemanticVersion(otherVersion) else {
+ return nil
+ }
+
+ return parsedVersion > parsedOtherVersion
+ }
+
private struct SemanticVersion: Comparable {
let core: [Int]
let prerelease: [PrereleaseIdentifier]?
@@ -518,9 +505,9 @@ final class CodexCLIVersionViewModel: ObservableObject {
refreshCoordinator.cancel()
}
- func refresh() {
+ func refresh(force: Bool = false) {
guard !isRefreshing,
- Date().timeIntervalSince(snapshot.refreshedAt) > Self.refreshThrottle else {
+ force || Date().timeIntervalSince(snapshot.refreshedAt) > Self.refreshThrottle else {
return
}
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index 8cecc10..6e13a9e 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -136,6 +136,8 @@ actor CodexStatusService {
private var connection: AppServerConnection?
private var supplementalDataCache = SupplementalDataCache()
private var lastResolvedSource: CodexCLIExecutableSource?
+ private let defaults: UserDefaults
+ private var sourceSelection: CodexCLISourceSelection
/// app-server 退出后继续写管道会触发 SIGPIPE
/// 忽略信号, 让 write 抛错后走重建
@@ -143,7 +145,9 @@ actor CodexStatusService {
signal(SIGPIPE, SIG_IGN)
}()
- init() {
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ sourceSelection = CodexCLISourceSelection.load(from: defaults)
_ = Self.ignoreBrokenPipeSignal
}
@@ -151,7 +155,7 @@ actor CodexStatusService {
func fetchOutcome() async -> CodexFetchResult {
var trace = CodexFetchTrace()
- let outcome = await resolveOutcome(allowRebuild: true, trace: &trace)
+ let outcome = resolveOutcome(allowRebuild: true, trace: &trace)
return CodexFetchResult(outcome: outcome, trace: trace)
}
@@ -163,11 +167,57 @@ actor CodexStatusService {
return connection.commandInfo
}
+ func currentSourceSelection() -> CodexCLISourceSelection {
+ sourceSelection
+ }
+
/// 需要以实际运行版本做能力检查时建立或复用连接
func readyConnectionInfo() throws -> CodexCLIConnectionInfo {
try readyConnection().commandInfo
}
+ /// 新连接完成握手和账户校验后才替换旧连接, 失败时继续保留原会话
+ func reconnect(
+ selection: CodexCLISourceSelection? = nil,
+ minimumVersion: String
+ ) throws -> CodexCLIConnectionInfo {
+ let requestedSelection = selection ?? sourceSelection
+ let command = try CodexCLIResolver.command(
+ from: CodexCLIResolver.resolveInstallations(environment: Self.environment),
+ source: requestedSelection.source
+ )
+ let resolution = Self.openConnection(
+ command: command,
+ environment: Self.environment,
+ clientVersion: Self.clientVersion(),
+ timeout: Self.requestTimeout
+ )
+ switch resolution {
+ case let .ready(candidate, _):
+ guard let version = candidate.commandInfo.version,
+ CodexCLIVersionReader.isVersion(version, atLeast: minimumVersion) == true else {
+ candidate.close()
+ throw CodexStatusError.unsupportedVersion(minimum: minimumVersion)
+ }
+
+ let previous = connection
+ connection = candidate
+ sourceSelection = requestedSelection
+ sourceSelection.save(to: defaults)
+ supplementalDataCache = SupplementalDataCache()
+ lastResolvedSource = command.source
+ previous?.close()
+ AppLog.codexCLI.notice("Codex 连接已切换: source=\(command.source.rawValue, privacy: .public)")
+ return candidate.commandInfo
+ case .notLoggedIn:
+ throw CodexStatusError.notLoggedIn
+ case let .unsupportedVersion(minimum):
+ throw CodexStatusError.unsupportedVersion(minimum: minimum)
+ case .initializationFailed:
+ throw CodexStatusError.serverConnectionClosed
+ }
+ }
+
func readCodexConfig() async throws -> CodexConfigReadResponse {
let connection = try readyConnection()
return try connection.session.request(
@@ -250,7 +300,7 @@ actor CodexStatusService {
private func resolveOutcome(
allowRebuild: Bool,
trace: inout CodexFetchTrace
- ) async -> CodexFetchOutcome {
+ ) -> CodexFetchOutcome {
switch ensureConnection() {
case .notLoggedIn:
trace.failureStage = .connect
@@ -264,7 +314,7 @@ actor CodexStatusService {
case let .ready(connection, reused):
trace.connection = reused ? .reused : .new
do {
- let snapshot = try await fetchData(
+ let snapshot = try fetchData(
using: connection,
refreshAccountInfo: reused,
trace: &trace
@@ -278,7 +328,7 @@ actor CodexStatusService {
teardownConnection()
if reused, allowRebuild {
AppLog.app.notice("codex 连接已失效: reason=transportError")
- return await resolveOutcome(allowRebuild: false, trace: &trace)
+ return resolveOutcome(allowRebuild: false, trace: &trace)
}
return .initializationFailed
} catch {
@@ -365,7 +415,10 @@ actor CodexStatusService {
let command: AppServerCommand
do {
- command = try CodexCLIResolver.resolveAppServerCommand(environment: Self.environment)
+ command = try CodexCLIResolver.command(
+ from: CodexCLIResolver.resolveInstallations(environment: Self.environment),
+ source: sourceSelection.source
+ )
} catch {
let details = LogFields.joined(
"stage=resolveCLI",
@@ -449,7 +502,7 @@ actor CodexStatusService {
using connection: AppServerConnection,
refreshAccountInfo: Bool,
trace: inout CodexFetchTrace
- ) async throws -> CodexQuotaSnapshot {
+ ) throws -> CodexQuotaSnapshot {
var didRefresh = false
func refreshTokenIfNeeded() throws {
diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
index ecd1bbe..298584f 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift
@@ -25,11 +25,19 @@ final class CodexStatusViewModel: ObservableObject {
@Published private(set) var isRefreshing = false
@Published private(set) var loadState: CodexLoadState = .loading
@Published private(set) var codexConnectionInfo: CodexCLIConnectionInfo?
+ @Published private(set) var connectionErrorMessage: String?
+ @Published private(set) var unavailableConnectionSource: CodexCLIExecutableSource?
+ @Published private(set) var codexSourceSelection = CodexCLISourceSelection.automatic
+ @Published private(set) var pendingCodexSourceSelection: CodexCLISourceSelection?
@Published private(set) var autoRefreshCountdownStartedAt: Date?
/// 统计维护挂在额度刷新完成事件上, 由它继承本次刷新的触发来源
private(set) var lastRefreshTrigger: LogTrigger = .launch
+ var isReconnecting: Bool {
+ pendingCodexSourceSelection != nil
+ }
+
var autoRefreshInterval: TimeInterval {
Self.refreshInterval
}
@@ -41,6 +49,7 @@ final class CodexStatusViewModel: ObservableObject {
private var pendingRefreshTask: Task<Void, Never>?
private var pendingForcedRefreshTrigger: LogTrigger?
private let refreshCoordinator = RefreshTaskCoordinator()
+ private var connectionInfoGeneration: UInt64 = 0
init(service: CodexStatusService = CodexStatusService()) {
self.service = service
@@ -81,7 +90,7 @@ final class CodexStatusViewModel: ObservableObject {
}
func refresh(trigger: LogTrigger) {
- guard !isRefreshing else {
+ guard !isRefreshing, !isReconnecting else {
return
}
@@ -92,7 +101,11 @@ final class CodexStatusViewModel: ObservableObject {
refreshCoordinator.run(
setRefreshing: { [weak self] in self?.setRefreshing($0) },
operation: { [service = self.service] in
- await (fetch: service.fetchOutcome(), connectionInfo: service.currentConnectionInfo())
+ await (
+ fetch: service.fetchOutcome(),
+ connectionInfo: service.currentConnectionInfo(),
+ selection: service.currentSourceSelection()
+ )
},
commit: { [weak self] result in
guard let self else {
@@ -122,6 +135,7 @@ final class CodexStatusViewModel: ObservableObject {
elapsed: duration.elapsed
)
codexConnectionInfo = result.connectionInfo
+ codexSourceSelection = result.selection
autoRefreshCountdownStartedAt = Date()
}
)
@@ -129,7 +143,7 @@ final class CodexStatusViewModel: ObservableObject {
/// 自动消费完成后不能因为普通刷新正在运行而丢掉最终对账
func refreshAfterCurrent(trigger: LogTrigger) {
- guard isRefreshing else {
+ guard isRefreshing || isReconnecting else {
refresh(trigger: trigger)
return
}
@@ -211,8 +225,59 @@ final class CodexStatusViewModel: ObservableObject {
}
func refreshCodexConnectionInfo() {
+ guard !isReconnecting else {
+ return
+ }
+ let generation = connectionInfoGeneration
Task {
- self.codexConnectionInfo = await service.currentConnectionInfo()
+ let info = await service.currentConnectionInfo()
+ let selection = await service.currentSourceSelection()
+ guard generation == connectionInfoGeneration, !isReconnecting else {
+ return
+ }
+ codexConnectionInfo = info
+ codexSourceSelection = selection
+ }
+ }
+
+ func reconnectCodex(
+ selection: CodexCLISourceSelection? = nil,
+ requiresHooks: Bool
+ ) async -> Bool {
+ guard !isRefreshing, !isReconnecting else {
+ return false
+ }
+
+ pendingCodexSourceSelection = selection ?? codexSourceSelection
+ connectionErrorMessage = nil
+ unavailableConnectionSource = nil
+ connectionInfoGeneration &+= 1
+ var didReconnect = false
+ defer {
+ pendingCodexSourceSelection = nil
+ let trigger = pendingForcedRefreshTrigger
+ pendingForcedRefreshTrigger = nil
+ if didReconnect || trigger != nil {
+ refresh(trigger: trigger ?? .manual)
+ }
+ }
+
+ do {
+ codexConnectionInfo = try await service.reconnect(
+ selection: selection,
+ minimumVersion: requiresHooks ? CodexCLIMinimumVersion.hook : CodexCLIMinimumVersion.global
+ )
+ codexSourceSelection = await service.currentSourceSelection()
+ snapshot = nil
+ loadState = .loading
+ didReconnect = true
+ return true
+ } catch let CodexStatusError.sourceUnavailable(source) {
+ unavailableConnectionSource = source
+ return false
+ } catch {
+ connectionErrorMessage = error.localizedDescription
+ return false
}
}
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index abe2817..e12b669 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -966,7 +966,20 @@ private extension AppSettingsView {
var codexVersionSection: some View {
CodexVersionSection(
snapshot: codexVersions.snapshot,
- connectionInfo: statusViewModel.codexConnectionInfo
+ connectionInfo: statusViewModel.codexConnectionInfo,
+ sourceSelection: statusViewModel.pendingCodexSourceSelection ?? statusViewModel.codexSourceSelection,
+ isReconnecting: statusViewModel.isReconnecting,
+ isBusy: statusViewModel.isRefreshing || statusViewModel.isReconnecting || codexVersions.isRefreshing,
+ errorMessage: statusViewModel.connectionErrorMessage,
+ unavailableSource: statusViewModel.unavailableConnectionSource,
+ onReconnect: { selection in
+ Task { @MainActor in
+ if await statusViewModel.reconnectCodex(selection: selection, requiresHooks: codexHookSettings.isEnabled) {
+ codexHookSettings.reconcileInstalledHooks()
+ }
+ codexVersions.refresh(force: true)
+ }
+ }
)
}
diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swift
index 65a44d1..577fca8 100644
--- a/CodexBar/Views/Settings/CodexVersionSection.swift
+++ b/CodexBar/Views/Settings/CodexVersionSection.swift
@@ -5,6 +5,12 @@ import SwiftUI
struct CodexVersionSection: View {
let snapshot: CodexCLIVersionSnapshot
let connectionInfo: CodexCLIConnectionInfo?
+ let sourceSelection: CodexCLISourceSelection
+ let isReconnecting: Bool
+ let isBusy: Bool
+ let errorMessage: String?
+ let unavailableSource: CodexCLIExecutableSource?
+ let onReconnect: (CodexCLISourceSelection?) -> Void
@State private var copiedPathResetTasks: [CodexCLIExecutableSource: Task<Void, Never>] = [:]
var body: some View {
@@ -17,25 +23,115 @@ struct CodexVersionSection: View {
Text("settings.codex-version.title")
Spacer()
+
+ sourceSelectionControls
}
- LiquidGlassDivider()
- .padding(.leading, Metrics.iconWidth + 10)
+ if !displayedItems.isEmpty {
+ LiquidGlassDivider()
+ .padding(.leading, Metrics.iconWidth + 10)
- VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
- codexVersionRow(icon: "terminal", item: snapshot.global)
+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
+ ForEach(displayedItems) { item in
+ codexVersionRow(icon: item.source == .global ? "terminal" : "app.badge", item: item)
+ }
+ }
+ .padding(.leading, Metrics.childIndent)
+ }
- codexVersionRow(icon: "app.badge", item: snapshot.bundled)
+ if let message = errorMessage {
+ Text(message)
+ .font(.caption)
+ .foregroundStyle(.red)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.leading, Metrics.childIndent)
}
- .padding(.leading, Metrics.childIndent)
}
.onDisappear {
copiedPathResetTasks.values.forEach { $0.cancel() }
}
}
+ private var sourceSelectionControls: some View {
+ HStack(spacing: SettingsRowMetrics.spacing) {
+ Picker(
+ "settings.codex-version.source.title",
+ selection: Binding(
+ get: { availableSelections.contains(sourceSelection) ? sourceSelection : nil },
+ set: { selection in
+ guard let selection, selection != sourceSelection else { return }
+ onReconnect(selection)
+ }
+ )
+ ) {
+ if !availableSelections.contains(sourceSelection) {
+ Text("settings.codex-version.source.select")
+ .tag(CodexCLISourceSelection?.none)
+ .disabled(true)
+ }
+
+ ForEach(availableSelections) { selection in
+ Text(selection.title)
+ .tag(Optional(selection))
+ }
+ }
+ .labelsHidden()
+ .pickerStyle(.menu)
+ .controlSize(.small)
+ .frame(width: Metrics.sourcePickerWidth, alignment: .trailing)
+ .disabled(isBusy)
+
+ reconnectButton
+ }
+ .frame(minHeight: SettingsRowMetrics.optionsButtonSize)
+ }
+
+ private var reconnectButton: some View {
+ let isEnabled = !isBusy && !isReconnecting && isSourceInstalled(sourceSelection)
+ let label: LocalizedStringKey = isReconnecting
+ ? "settings.codex-version.reconnecting"
+ : "settings.codex-version.reconnect"
+
+ return Button {
+ onReconnect(nil)
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ .symbolEffect(.rotate.byLayer, options: .repeat(.periodic(delay: 0.0)), isActive: isReconnecting)
+ .frame(width: SettingsRowMetrics.optionsButtonSize, height: SettingsRowMetrics.optionsButtonSize)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .controlSize(.small)
+ .foregroundStyle(isEnabled ? Color.accentColor : .secondary)
+ .disabled(!isEnabled)
+ .help(label)
+ }
+
+ private var installedItems: [CodexCLIVersionItem] {
+ [snapshot.global, snapshot.bundled].filter { $0.path != nil }
+ }
+
+ private var displayedItems: [CodexCLIVersionItem] {
+ [snapshot.global, snapshot.bundled].filter {
+ $0.path != nil || $0.source == connectionInfo?.source
+ || (snapshot.refreshedAt != .distantPast
+ && ($0.source == sourceSelection.source || $0.source == unavailableSource))
+ }
+ }
+
+ private var availableSelections: [CodexCLISourceSelection] {
+ CodexCLISourceSelection.allCases.filter { $0 == .automatic || isSourceInstalled($0) }
+ }
+
+ private func isSourceInstalled(_ selection: CodexCLISourceSelection) -> Bool {
+ guard let source = selection.source else { return !installedItems.isEmpty }
+ return installedItems.contains { $0.source == source }
+ }
+
private func codexVersionRow(icon: String, item: CodexCLIVersionItem) -> some View {
let row = CodexCLIVersionDisplay(item: item, connection: connectionInfo)
+ let isUnavailable = snapshot.refreshedAt != .distantPast && item.path == nil
+ let statusColor: Color = isUnavailable ? .orange : .green
let isPathCopied = copiedPathResetTasks[item.source] != nil
return HStack(alignment: .top, spacing: 10) {
@@ -50,24 +146,27 @@ struct CodexVersionSection: View {
VStack(alignment: .trailing, spacing: 3) {
HStack(spacing: 12) {
- if row.isCurrent {
- Text("settings.codex-version.in-use")
+ if row.isCurrent || isUnavailable {
+ Text(isUnavailable ? "settings.codex-version.unavailable" : "settings.codex-version.in-use")
.font(.caption2.weight(.medium))
- .foregroundStyle(.green)
+ .foregroundStyle(statusColor)
.padding(.horizontal, 6)
.padding(.vertical, 2)
- .liquidGlassCapsule(tint: .green)
+ .liquidGlassCapsule(tint: statusColor)
.transition(.opacity)
}
- Text(row.displayVersion)
- .font(row.hasVersion ? .body.monospacedDigit() : .body)
- .foregroundStyle(row.hasVersion ? .secondary : .tertiary)
- .lineLimit(1)
- .contentTransition(.opacity)
- .animation(Metrics.statusAnimation, value: row.displayVersion)
+ 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: row.isCurrent)
+ .animation(Metrics.statusAnimation, value: isUnavailable)
if let newerInstalledVersion = row.newerInstalledVersion {
Text(LocalizedStringResource("settings.codex-version.updated-to", defaultValue: "\(newerInstalledVersion)"))
@@ -113,6 +212,7 @@ struct CodexVersionSection: View {
static let rowSpacing: CGFloat = 14
static let iconWidth = SettingsRowMetrics.iconWidth
static let childIndent: CGFloat = 28
+ static let sourcePickerWidth: CGFloat = 140
static let versionColumnWidth: CGFloat = 270
static let statusAnimation = Animation.codexStatus
}
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index 8ee7157..3048284 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 3.6.14
-CURRENT_PROJECT_VERSION = 81
+MARKETING_VERSION = 3.6.15
+CURRENT_PROJECT_VERSION = 82
diff --git a/Docs/UserGuide/activity-and-hook.md b/Docs/UserGuide/activity-and-hook.md
index 7b42e57..62a4043 100644
--- a/Docs/UserGuide/activity-and-hook.md
+++ b/Docs/UserGuide/activity-and-hook.md
@@ -28,7 +28,7 @@ CodexBar Hook 会在 Codex 的关键事件发生时记录少量结构化字段
版本检查以当前已连接 app-server 的握手版本为准,不是磁盘上刚安装的版本。
-更新 Codex 后如果仍提示版本过低,退出并重新打开 CodexBar 以建立新连接。
+更新 Codex 后如果仍提示版本过低,在“设置 > 关于”中点击“刷新连接”。
## 开启方法
diff --git a/Docs/UserGuide/getting-started.md b/Docs/UserGuide/getting-started.md
index 1b8453b..4cae031 100644
--- a/Docs/UserGuide/getting-started.md
+++ b/Docs/UserGuide/getting-started.md
@@ -10,7 +10,7 @@
- 使用 Hook 相关功能时,当前运行的 Codex app-server 版本需要为 `0.145.0` 或更高版本
- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户
-CodexBar 会优先使用全局安装的 Codex CLI,找不到时再尝试 ChatGPT App 和 Codex App 内置的 Codex。
+CodexBar 默认自动选择来源,优先使用全局安装的 Codex CLI,找不到时再尝试 ChatGPT App 和 Codex App 内置的 Codex。可在“设置 > 关于 > Codex 版本 > 来源”中手动选择。
## 安装
diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.md
index 2259679..1da4486 100644
--- a/Docs/UserGuide/settings.md
+++ b/Docs/UserGuide/settings.md
@@ -165,9 +165,12 @@
| 项目 | 作用 |
| --- | --- |
+| 来源 | 位于 Codex 版本标题右侧,保留自动选项,按检测结果展示已安装的 Codex CLI 或 Codex APP |
+| 刷新连接 | 点击来源选择器右侧的圆形箭头,按所选来源重新建立连接,使用磁盘上已安装的版本 |
| Codex CLI | 展示全局 Codex CLI 的磁盘版本和路径 |
| Codex APP | 展示 ChatGPT App 或 Codex App 内置 CLI 的磁盘版本和路径 |
| 当前使用 | 标记当前 app-server 实际使用的 Codex 来源和运行版本 |
+| 不可用 | 当前、已选或刷新失败的来源已无法检测到时,在原状态标签位置以橙色显示 |
| CodexBar 版本 | 展示当前版本、更新状态和可用更新 |
| GitHub 项目 | 打开 CodexBar 项目页面 |
| 检查更新 | 手动触发 Sparkle 更新检查 |
@@ -175,6 +178,14 @@
磁盘中的 Codex 已更新但当前 app-server 还没有重连时,关于页面会同时提示新安装版本。
+更新提示与最低版本检查共用语义版本解析规则:同一版本的正式版高于预发布版,构建标记不影响版本优先级,无法识别的版本不显示更新提示。
+
+来源默认为自动,优先使用 CLI,未安装 CLI 时使用 App 内置 Codex。来源选项只展示检测到的安装来源。版本行通常只展示已安装来源;当前、已选或刷新失败的来源被卸载后,保留该行并以“不可用”替换“当前使用”,不再在底部重复显示来源不可用提示。此标记表示无法从该来源建立新连接,不代表旧连接已经停止。切换来源后立即建立新连接,成功后保存选择,失败时保留原连接和原选择。之前手动指定的来源被卸载后,选择器显示“选择来源”,不会自动改用其他来源。
+
+自动重连仍然保留:连接使用满 1 小时后,在下一次请求时按所选来源重建。也可以点击“刷新连接”提前使用更新后的版本。旧版 CodexBar 会忽略来源选择,沿用原有自动规则。
+
+悬停圆形箭头可查看“刷新连接”提示。重连期间,箭头持续旋转,来源选择器和重连按钮暂时不可操作;成功后更新“当前使用”标记,来源缺失时显示“不可用”,其他失败在版本区域底部显示原因。
+
点击可执行文件路径可以复制完整路径。
返回 [用户手册](README.md)
diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.md
index 94355cc..b6903c4 100644
--- a/Docs/UserGuide/troubleshooting.md
+++ b/Docs/UserGuide/troubleshooting.md
@@ -16,7 +16,7 @@
3. 双击 CodexBar 主面板中的账户图标刷新
4. 仍然未登录时退出并重新打开 CodexBar
-CodexBar 优先使用全局 Codex CLI,关于页面的 `当前使用` 标记可以确认实际来源。
+自动模式优先使用全局 Codex CLI,关于页面的 `当前使用` 标记可以确认实际来源,也可以通过“来源”选择器切换。
## 主面板显示初始化失败
@@ -41,7 +41,7 @@ CodexBar 优先使用全局 Codex CLI,关于页面的 `当前使用` 标记可
| 提示 | 含义 | 建议处理 |
| --- | --- | --- |
-| 需要更高 Codex 版本 | 当前 app-server 版本不足 | 更新 Codex 后重启 CodexBar |
+| 需要更高 Codex 版本 | 当前 app-server 版本不足 | 更新 Codex 后在关于页面点击“刷新连接” |
| Codex Hook 已全局关闭 | `features.hooks` 已禁用 | 在 Codex 配置中重新启用 Hooks |
| CodexBar Hook 已不完整 | 至少一个必要事件缺少当前 handler | 重新打开设置触发自动补齐,仍未恢复时关闭后重新开启 Hook |
| CodexBar Hook 未被信任 | Codex 仍把 handler 判定为未信任或已修改 | 重新开启 Hook 并检查 Codex 配置 |
@@ -131,7 +131,7 @@ pmset -g sched
当前版本来自已经运行的 app-server 握手,磁盘版本来自重新执行 Codex `--version`
-如果关于页面显示新安装版本但 `当前使用` 仍是旧版本,退出并重新打开 CodexBar。
+如果关于页面显示新安装版本但 `当前使用` 仍是旧版本,点击“刷新连接”。也可以等待当前连接满 1 小时后的下一次请求自动重建。
## 使用日志窗口
diff --git a/Docs/en/UserGuide/activity-and-hook.md b/Docs/en/UserGuide/activity-and-hook.md
index e6a4624..85c74c7 100644
--- a/Docs/en/UserGuide/activity-and-hook.md
+++ b/Docs/en/UserGuide/activity-and-hook.md
@@ -28,7 +28,7 @@ Before enabling CodexBar Hook, make sure that:
The version check uses the handshake version from the connected app-server, not a newly installed version on disk.
-If CodexBar still reports an older version after you update Codex, quit and reopen CodexBar to establish a new connection.
+If CodexBar still reports an older version after you update Codex, click Refresh Connection under Settings > About.
## Enabling the Hook
diff --git a/Docs/en/UserGuide/getting-started.md b/Docs/en/UserGuide/getting-started.md
index 0459aa3..da359b8 100644
--- a/Docs/en/UserGuide/getting-started.md
+++ b/Docs/en/UserGuide/getting-started.md
@@ -10,7 +10,7 @@
- Hook features require the running Codex app-server to be `0.145.0` or later
- Cross-device sync requires an available iCloud account on the Mac
-CodexBar prefers a globally installed Codex CLI. If it cannot find one, it tries the Codex bundled with ChatGPT App and Codex App.
+By default, CodexBar automatically prefers a globally installed Codex CLI. If it cannot find one, it tries the Codex bundled with ChatGPT App and Codex App. You can select a source under Settings > About > Codex Versions > Source.
## Installation
diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.md
index cb1defa..f7a5320 100644
--- a/Docs/en/UserGuide/settings.md
+++ b/Docs/en/UserGuide/settings.md
@@ -165,9 +165,12 @@ See [Data, Sync, and Privacy](sync-data-privacy.md) for details.
| Item | Purpose |
| --- | --- |
+| Source | Located beside the Codex Versions heading; Automatic is always available, while Codex CLI and Codex APP appear only when detected as installed |
+| Refresh Connection | The circular arrow next to the source selector establishes a new connection using the selected source and its installed version |
| Codex CLI | Shows the on-disk version and path of the global Codex CLI |
| Codex APP | Shows the on-disk version and path of the CLI bundled with ChatGPT App or Codex App |
| In Use | Identifies the Codex source and running app-server version currently in use |
+| Unavailable | An orange badge in the status position when the current, selected, or failed refresh source can no longer be detected |
| CodexBar Version | Shows the current version, update status, and any available update |
| GitHub Project | Opens the CodexBar project page |
| Check for Updates | Runs a manual Sparkle update check |
@@ -175,6 +178,14 @@ See [Data, Sync, and Privacy](sync-data-privacy.md) for details.
If Codex has been updated on disk but the current app-server has not reconnected, About shows the newly installed version as well.
+Update hints share the semantic version parser used by minimum-version checks: a stable release takes precedence over its prereleases, build metadata does not affect precedence, and unrecognized versions do not produce an update hint.
+
+The default source is Automatic, which prefers CLI and uses the app's bundled Codex when CLI is not installed. Source options only show detected installations. Version rows normally show installed sources; if the current, selected, or failed refresh source is uninstalled, its row remains with Unavailable replacing In Use, without a duplicate source-unavailable message below. This badge means a new connection cannot be opened from that source, not that the old connection has stopped. Changing the source connects immediately and saves the choice only after success. Failure preserves the previous connection and choice. If a previously selected source is uninstalled, the picker shows “Select Source” without falling back to another source.
+
+Automatic reconnection remains enabled: once a connection is one hour old, the next request rebuilds it using the selected source. Refresh Connection applies an installed update sooner. Older CodexBar versions ignore the source preference and retain their original automatic selection behavior.
+
+Hover over the circular arrow to see Refresh Connection. While reconnecting, the arrow rotates continuously, and both controls are temporarily disabled. Success updates In Use; a missing source shows Unavailable, while other failures display a reason below the version rows.
+
Click an executable path to copy the full path.
Back to the [User Guide](README.md)
diff --git a/Docs/en/UserGuide/troubleshooting.md b/Docs/en/UserGuide/troubleshooting.md
index d5b2f39..41adebd 100644
--- a/Docs/en/UserGuide/troubleshooting.md
+++ b/Docs/en/UserGuide/troubleshooting.md
@@ -16,7 +16,7 @@
3. Double-click the account icon in the CodexBar main panel to refresh
4. If it still says you are not signed in, quit and reopen CodexBar
-CodexBar prefers the global Codex CLI. The `In Use` indicator on the About page identifies the actual source.
+Automatic mode prefers the global Codex CLI. The `In Use` indicator on the About page identifies the actual source, which you can change with the Source selector.
## The Main Panel Says “Initialization Failed”
@@ -41,7 +41,7 @@ Double-click the account icon to retry. If the values remain dimmed, check `acco
| Message | Meaning | Recommended action |
| --- | --- | --- |
-| A newer Codex version is required | The current app-server version is too old | Update Codex, then restart CodexBar |
+| A newer Codex version is required | The current app-server version is too old | Update Codex, then click Refresh Connection on the About page |
| Codex Hook is disabled globally | `features.hooks` is disabled | Re-enable Hooks in the Codex configuration |
| CodexBar Hook is incomplete | At least one required event is missing the current handler | Reopen Settings to trigger automatic repair; if it still fails, turn Hook off and on again |
| CodexBar Hook is not trusted | Codex still considers the handler untrusted or modified | Re-enable the Hook and inspect the Codex configuration |
@@ -131,7 +131,7 @@ A sync failure does not delete local Hook data. A later maintenance run retries
The current version comes from the running app-server handshake. The on-disk version comes from running Codex `--version` again.
-If About shows the new installed version but `In Use` still shows the old one, quit and reopen CodexBar.
+If About shows the new installed version but `In Use` still shows the old one, click Refresh Connection. Alternatively, the next request after the connection is one hour old rebuilds it automatically.
## Using the Logs Window
diff --git a/appcast.xml b/appcast.xml
index 0b473d4..eb61d06 100644
--- a/appcast.xml
+++ b/appcast.xml
@@ -7,6 +7,15 @@
<link>https://codexbar.zabrian.app/appcast.xml</link>
<description>CodexBar appcast feed</description>
<language>zh-CN</language>
+ <item>
+ <title>CodexBar.app 3.6.15</title>
+ <sparkle:version>82</sparkle:version>
+ <sparkle:shortVersionString>3.6.15</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.6.15</sparkle:releaseNotesLink>
+ <pubDate>Sat, 05 Sep 2026 10:30:10 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.6.15.dmg" sparkle:edSignature="WAZhZhbeqXm4o8EMnKB43rDi308owgPLJhGYs1yDmEBdNpfGay0kpvVqHqVmDhLaHL/6sup8vdksP18MB6z5BA==" length="7664898" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.6.14</title>
<sparkle:version>81</sparkle:version>