CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 支持自定义任务流光外观与结束时长
Bob09c9ca3d9d22
diff --git a/.swiftlint.yml b/.swiftlint.ymlindex 4bdfdcb..17a4b91 100644--- a/.swiftlint.yml+++ b/.swiftlint.yml@@ -10,9 +10,6 @@ line_length:ignores_function_declarations: trueignores_interpolated_strings: true-# 这两项放宽只为容纳 StatusItemController: 它是文件级 private 类, 拆到别的文件写 extension-# 就得把类和存储属性从 private 放宽到 internal, 为消一条 warning 暴露实现细节不划算-# 余量只留了 4% 左右, 继续变长仍会报; 新文件不要向这个上限看齐file_length:warning: 1300error: 1500diff --git a/CodexBar/Controllers/SettingsOptionsPanelController.swift b/CodexBar/Controllers/SettingsOptionsPanelController.swiftindex c34f3e2..decb3f6 100644--- a/CodexBar/Controllers/SettingsOptionsPanelController.swift+++ b/CodexBar/Controllers/SettingsOptionsPanelController.swift@@ -5,6 +5,7 @@ import SwiftUI/// 设置窗口右侧的子选项面板, 同一时刻只展开一个enum SettingsOptionsPanel: CaseIterable, Hashable {case mainPanel+ case taskGlowcase notificationcase autoResetcase keepAlive@@ -56,9 +57,9 @@ final class SettingsOptionsPanelController {private var panel: NSPanel?private var hostingController: NSViewController?private var cancellables = Set<AnyCancellable>()+ /// 展开时保留主设置窗口的键盘焦点, 用户点击输入框后再由面板接管private lazy var presenter = SidePanelDrawerPresenter(animationKey: animationKey,- makesKey: true,usesUntranslatedInitialLayout: true,contentViewProvider: { [weak self] inself?.hostingController?.view@@ -122,6 +123,8 @@ final class SettingsOptionsPanelController {panelResizeTask?.cancel()panelResizeTask = nilisEntryAnimationRunning = false+ // 原生输入框的焦点环不跟随内容层平移, 收起前结束编辑也避免下次展开恢复旧焦点+ panel?.makeFirstResponder(panel)presenter.hide(immediate: immediate)}diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 76fc4be..a743290 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -193,6 +193,14 @@ final class SettingsWindowController: HostingWindowController {switch panel {case .mainPanel:makeMainPanelOptionsPanelController()+ case .taskGlow:+ SettingsOptionsPanelController(+ animationKey: "CodexBar.taskGlowOptionsDrawerTransform",+ initialPanelSize: TaskGlowOptionsView.initialPanelSize,+ contentProvider: { [taskGlowSettings] in+ TaskGlowOptionsView(settings: taskGlowSettings)+ }+ )case .notification:SettingsOptionsPanelController(animationKey: "CodexBar.notificationOptionsDrawerTransform",diff --git a/CodexBar/Controllers/TaskGlowController.swift b/CodexBar/Controllers/TaskGlowController.swiftindex a299853..e1cb563 100644--- a/CodexBar/Controllers/TaskGlowController.swift+++ b/CodexBar/Controllers/TaskGlowController.swift@@ -8,6 +8,7 @@ final class TaskGlowController {private let settings: TaskGlowSettingsprivate let activityMonitor: CodexActivityMonitorprivate let hookSettings: CodexHookSettings+ private var appearance: TaskGlowAppearanceprivate var cancellables = Set<AnyCancellable>()private var panels: [TaskGlowPanel] = []private let motionClock = TaskGlowMotionClock()@@ -30,6 +31,8 @@ final class TaskGlowController {self.settings = settingsself.activityMonitor = activityMonitorself.hookSettings = hookSettings+ appearance = settings.appearance+ motionClock.setAnimationSpeed(appearance.animationSpeed)}deinit {@@ -62,6 +65,19 @@ final class TaskGlowController {.sink { [weak self] in self?.previewEnabled() }.store(in: &cancellables)+ settings.$appearance+ .removeDuplicates()+ .sink { [weak self] appearance in+ guard let self else { return }+ self.appearance = appearance+ motionClock.setAnimationSpeed(appearance.animationSpeed)+ if isPreviewVisible {+ schedulePreviewEnd()+ }+ refreshPresentation()+ }+ .store(in: &cancellables)+activityMonitor.presentationPublisher.sink { [weak self] update in self?.consume(update) }.store(in: &cancellables)@@ -107,10 +123,17 @@ final class TaskGlowController {removePanels()isPreviewVisible = truemotionClock.setRunning(true)+ schedulePreviewEnd()+ updatePanels()+ }++ private func schedulePreviewEnd() {+ previewTask?.cancel()let startTime = motionClock.startTime()+ let cycleDuration = motionClock.cycleDurationpreviewTask = Task { @MainActor [weak self] indo {- let remaining = max(0, startTime + TaskGlowMotionClock.cycleDuration - CACurrentMediaTime())+ let remaining = max(0, startTime + cycleDuration - CACurrentMediaTime())try await Task.sleep(for: .seconds(remaining))} catch {return@@ -120,7 +143,6 @@ final class TaskGlowController {isPreviewVisible = falserefreshPresentation()}- updatePanels()}private func cancelPreview() {@@ -141,7 +163,7 @@ final class TaskGlowController {}private func refreshPresentation() {- presentation.refresh(now: Date())+ presentation.refresh(now: Date(), terminalDuration: appearance.terminalDuration)let expiration = presentation.terminal?.expiresAtupdatePanels()guard expiration != scheduledExpiration else { return }@@ -192,7 +214,7 @@ final class TaskGlowController {}guard hidePanelsTask == nil else { return }for panel in panels {- panel.indicatorView.update(state: .hidden)+ panel.indicatorView.update(state: .hidden, appearance: appearance)}hidePanelsTask = Task { @MainActor [weak self, closingPanels = panels] infor panel in closingPanels {@@ -212,6 +234,7 @@ final class TaskGlowController {for panel in panels {panel.indicatorView.update(state: state,+ appearance: appearance,terminalPresentation: isPreviewVisible ? nil : presentation.terminal,repeatsMotion: !isPreviewVisible)@@ -246,7 +269,7 @@ private extension CodexActivityTerminalEvent {}/// 短提示只消费开启后新增的结束记录, 到期后按最新快照恢复等待或运行状态-private struct TaskGlowPresentationState {+struct TaskGlowPresentationState {private var snapshot = CodexActivitySnapshot.emptyprivate var enabledAt: Date?private var briefEvent: CodexActivityTerminalEvent?@@ -286,10 +309,9 @@ private struct TaskGlowPresentationState {enabledAt = now}self.snapshot = snapshot- refresh(now: now)}- mutating func refresh(now: Date) {+ mutating func refresh(now: Date, terminalDuration: TimeInterval) {guard enabledAt != nil else {state = .hiddenterminal = nil@@ -308,8 +330,8 @@ private struct TaskGlowPresentationState {} else if snapshot.runningCount > 0 {state = .running} else if let event = snapshot.latestTerminalEvent,- let expiration = snapshot.statusItemActivityExpiration, now < expiration {- show(event, until: expiration, fadeDuration: 1, now: now)+ now < event.endedAt.addingTimeInterval(terminalDuration) {+ show(event, until: event.endedAt.addingTimeInterval(terminalDuration), fadeDuration: 1, now: now)return} else {state = .hidden@@ -318,36 +340,36 @@ private struct TaskGlowPresentationState {}private mutating func show(_ event: CodexActivityTerminalEvent, until expiration: Date, fadeDuration: TimeInterval, now: Date) {- if state != event.glowState || terminal?.eventID != event.id || terminal?.expiresAt != expiration- || terminal?.fadeDuration != fadeDuration {- terminal = TaskGlowTerminalPresentation(- eventID: event.id, startedAt: now, expiresAt: expiration, fadeDuration: fadeDuration- )- }+ terminal = TaskGlowTerminalPresentation(+ eventID: event.id,+ startedAt: terminal.flatMap { $0.eventID == event.id ? $0.startedAt : nil } ?? now,+ expiresAt: expiration,+ fadeDuration: fadeDuration+ )state = event.glowState}}-private enum TaskGlowState {+enum TaskGlowState {case hiddencase runningcase waitingcase completedcase terminated- var color: NSColor {+ func color(in appearance: TaskGlowAppearance) -> NSColor {switch self {case .hidden: .clear- case .running: .systemCyan- case .waiting: .systemOrange- case .completed: .systemGreen- case .terminated: .systemRed+ case .running: appearance.color(for: .running)+ case .waiting: appearance.color(for: .waiting)+ case .completed: appearance.color(for: .completed)+ case .terminated: appearance.color(for: .terminated)}}}/// 终态共用墙上时间, 屏幕重建和唤醒后接续淡出, 不重新提亮-private struct TaskGlowTerminalPresentation: Equatable {+struct TaskGlowTerminalPresentation: Equatable {static let entranceDuration: TimeInterval = 1.2let eventID: UUIDlet startedAt: Date@@ -372,10 +394,22 @@ private final class TaskGlowMotionClock {static let travelDuration = 2.0static let offscreenDuration = 0.2static let centerRetractionDuration = 0.3- static let cycleDuration = travelDuration + offscreenDuration * 2 + centerRetractionDuration+ private static let standardCycleDuration = travelDuration + offscreenDuration * 2 + centerRetractionDuration+ private(set) var cycleDuration = standardCycleDurationprivate var isRunning = falseprivate var startedAt: CFTimeInterval?+ func setAnimationSpeed(_ speed: TaskGlowAnimationSpeed) {+ let duration = Self.standardCycleDuration * speed.durationMultiplier+ guard duration != cycleDuration else { return }+ // 改速时保留当前周期进度, 各屏幕仍共享同一出发时间+ if let startedAt {+ let now = CACurrentMediaTime()+ self.startedAt = now - (now - startedAt) / cycleDuration * duration+ }+ cycleDuration = duration+ }+func setRunning(_ running: Bool) {guard isRunning != running else { return }isRunning = running@@ -453,6 +487,7 @@ private final class TaskGlowView: NSView {private var contentState: TaskGlowState?private var transitionTask: Task<Void, Never>?private var repeatsMotion = true+ private var glowAppearance = TaskGlowAppearance()init(geometry: TaskGlowGeometry,@@ -495,8 +530,17 @@ private final class TaskGlowView: NSView {fatalError("init(coder:) has not been implemented")}- func update(state: TaskGlowState, terminalPresentation: TaskGlowTerminalPresentation? = nil, repeatsMotion: Bool = true) {- guard presentationState != state || self.terminalPresentation != terminalPresentation || self.repeatsMotion != repeatsMotion else { return }+ func update(+ state: TaskGlowState,+ appearance glowAppearance: TaskGlowAppearance,+ terminalPresentation: TaskGlowTerminalPresentation? = nil,+ repeatsMotion: Bool = true+ ) {+ let previousAppearance = applyAppearance(glowAppearance, state: state)+ if presentationState == state, self.terminalPresentation == terminalPresentation, self.repeatsMotion == repeatsMotion {+ refreshStableAppearance(state, previous: previousAppearance)+ return+ }let continuesRunning = presentationState == .running && state == .runninglet continuesTerminal = presentationState == state && self.terminalPresentation != nil && terminalPresentation != nil// 同色提示延长时保留尚未完成的展开, 收尾会读取最新的淡出期限@@ -514,7 +558,7 @@ private final class TaskGlowView: NSView {freezeArtwork()if state != .hidden {contentState = state- animateVisibility(to: 1)+ animateVisibility(to: Float(glowAppearance.brightness))}if continuesRunning {@@ -555,7 +599,7 @@ private final class TaskGlowView: NSView {showStable(.running)fadeInMovingLight()} else {- setCollapsedColor(state.color)+ setCollapsedColor(state.color(in: self.glowAppearance))let duration = animateExtent(expanded: true)try await Task.sleep(for: .seconds(duration))guard !Task.isCancelled else { return }@@ -569,6 +613,21 @@ private final class TaskGlowView: NSView {}}+ private func applyAppearance(_ appearance: TaskGlowAppearance, state: TaskGlowState) -> TaskGlowAppearance {+ let previous = glowAppearance+ glowAppearance = appearance+ if previous.brightness != appearance.brightness, state != .hidden {+ animateVisibility(to: Float(appearance.brightness))+ }+ return previous+ }++ private func refreshStableAppearance(_ state: TaskGlowState, previous: TaskGlowAppearance) {+ guard state != .hidden, transitionTask == nil,+ previous.colors != glowAppearance.colors || previous.animationSpeed != glowAppearance.animationSpeed else { return }+ showStable(state)+ }+/// 面板等待实际收回和淡出结束, 不用独立计时器提前移除仍可见的光带func waitForDismissal() async -> Bool {await transitionTask?.value@@ -627,21 +686,21 @@ private final class TaskGlowView: NSView {stopArtworkAnimations()trackLayer.strokeStart = 0trackLayer.strokeEnd = 1- trackLayer.strokeColor = state.color.withAlphaComponent(Self.stationaryColorAlpha).cgColor- trackLayer.shadowColor = state.color.cgColor+ trackLayer.strokeColor = state.color(in: glowAppearance).withAlphaComponent(Self.stationaryColorAlpha).cgColor+ trackLayer.shadowColor = state.color(in: glowAppearance).cgColortrackLayer.shadowOpacity = 0.8trackLayer.opacity = 1trackLayer.isHidden = state == .runninglightLayer.isHidden = state != .runninglightLayer.opacity = 1- lightLayer.shadowColor = state.color.cgColor+ lightLayer.shadowColor = state.color(in: glowAppearance).cgColorif state == .running {configureMovingLight()} else if state == .waiting {let animation = CAKeyframeAnimation(keyPath: "opacity")animation.values = [1, 0, 0, 1]animation.keyTimes = [0, 0.45, 0.55, 1]- animation.duration = 1.5+ animation.duration = 1.5 * glowAppearance.animationSpeed.durationMultiplieranimation.repeatCount = .infinityanimation.timingFunctions = [CAMediaTimingFunction(name: .easeInEaseOut),@@ -697,7 +756,7 @@ private final class TaskGlowView: NSView {}let position = (Double(depth) + 0.5) / Double(Self.segmentsPerSide)let intensity = pow(sin(position * .pi / 2), 2)- let color = TaskGlowState.running.color+ let color = glowAppearance.color(for: .running)let tint = color.blended(withFraction: pow(intensity, 8) * 0.8, of: .white) ?? colorsegment.strokeColor = tint.withAlphaComponent((intensity - previousIntensity) / (1 - previousIntensity)).cgColorpreviousIntensity = intensity@@ -786,10 +845,11 @@ private final class TaskGlowView: NSView {/// 各屏幕共享出发和掉头时刻, 回程拖尾完全收进中心后才开始下一轮private func animateEmission(_ segment: CAShapeLayer, tailLength: Double, span: Double, isLeft: Bool, startTime: CFTimeInterval) {- let halfCrossing = TaskGlowMotionClock.travelDuration / 2- let offscreen = TaskGlowMotionClock.offscreenDuration+ let multiplier = glowAppearance.animationSpeed.durationMultiplier+ let halfCrossing = TaskGlowMotionClock.travelDuration / 2 * multiplier+ let offscreen = TaskGlowMotionClock.offscreenDuration * multiplierlet outwardDuration = halfCrossing + offscreen- let inwardDuration = halfCrossing + offscreen + TaskGlowMotionClock.centerRetractionDuration+ let inwardDuration = halfCrossing + offscreen + TaskGlowMotionClock.centerRetractionDuration * multiplierlet outward = emissionAnimation(waypoints: [(0, convergencePoint), (halfCrossing, 1), (outwardDuration, 1 + span)],tailLength: tailLength, isLeft: isLeft@@ -805,7 +865,7 @@ private final class TaskGlowView: NSView {// 每个单程独立缓入缓出, 保证两端掉头都平滑let travel = CAAnimationGroup()travel.animations = [outward, inward]- travel.duration = TaskGlowMotionClock.cycleDuration+ travel.duration = motionClock.cycleDurationtravel.beginTime = segment.convertTime(startTime, from: nil)travel.repeatCount = repeatsMotion ? .infinity : 0segment.add(travel, forKey: "emission")diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex bbf1a69..3902885 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -4945,6 +4945,166 @@}}},+ "task-glow.brightness.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Brightness"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "亮度"+ }+ }+ }+ },+ "task-glow.color.completed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Completed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已完成"+ }+ }+ }+ },+ "task-glow.color.running" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Running"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行中"+ }+ }+ }+ },+ "task-glow.color.terminated" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Stopped"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已终止"+ }+ }+ }+ },+ "task-glow.color.waiting" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Waiting for Approval"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "等待批准"+ }+ }+ }+ },+ "task-glow.duration.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "End Duration"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "结束时长"+ }+ }+ }+ },+ "task-glow.speed.fast" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Faster"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "较快"+ }+ }+ }+ },+ "task-glow.speed.slow" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Slower"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "较慢"+ }+ }+ }+ },+ "task-glow.speed.standard" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Standard"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "标准"+ }+ }+ }+ },+ "task-glow.speed.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Animation Speed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "动画速度"+ }+ }+ }+ },"updater.action.check" : {"localizations" : {"en" : {diff --git a/CodexBar/Services/Settings/TaskGlowSettings.swift b/CodexBar/Services/Settings/TaskGlowSettings.swiftindex 9ba5aa3..19b4384 100644--- a/CodexBar/Services/Settings/TaskGlowSettings.swift+++ b/CodexBar/Services/Settings/TaskGlowSettings.swift@@ -1,9 +1,93 @@+import AppKitimport Combineimport Foundation+enum TaskGlowColorRole: String, CaseIterable {+ case running, waiting, completed, terminated++ var title: LocalizedStringResource {+ switch self {+ case .running: "task-glow.color.running"+ case .waiting: "task-glow.color.waiting"+ case .completed: "task-glow.color.completed"+ case .terminated: "task-glow.color.terminated"+ }+ }++ var defaultColor: NSColor {+ switch self {+ case .running: .systemCyan+ case .waiting: .systemOrange+ case .completed: .systemGreen+ case .terminated: .systemRed+ }+ }+}++enum TaskGlowAnimationSpeed: String, CaseIterable {+ case slow, standard, fast++ var title: String {+ switch self {+ case .slow: String(localized: "task-glow.speed.slow")+ case .standard: String(localized: "task-glow.speed.standard")+ case .fast: String(localized: "task-glow.speed.fast")+ }+ }++ var durationMultiplier: Double {+ switch self {+ case .slow: 1.5+ case .standard: 1+ case .fast: 0.7+ }+ }+}++struct TaskGlowAppearance: Equatable {+ var colors: [TaskGlowColorRole: String] = [:]+ var animationSpeed = TaskGlowAnimationSpeed.standard+ var terminalDuration: TimeInterval = 10+ var brightness = 1.0++ func color(for role: TaskGlowColorRole) -> NSColor {+ colors[role].flatMap(Self.decodeColor) ?? role.defaultColor+ }++ static func normalizedColorHex(_ input: String) -> String? {+ var hex = input.trimmingCharacters(in: .whitespacesAndNewlines)+ if hex.hasPrefix("#") {+ hex.removeFirst()+ }+ guard hex.count == 6, hex.allSatisfy(\.isHexDigit), UInt32(hex, radix: 16) != nil else { return nil }+ return hex.uppercased()+ }++ static func decodeColor(_ hex: String) -> NSColor? {+ guard hex.count == 6, hex.allSatisfy(\.isHexDigit), let rgb = UInt32(hex, radix: 16) else { return nil }+ return NSColor(+ displayP3Red: Double((rgb >> 16) & 0xFF) / 255,+ green: Double((rgb >> 8) & 0xFF) / 255,+ blue: Double(rgb & 0xFF) / 255,+ alpha: 1+ )+ }++ static func encodeColor(_ color: NSColor) -> String? {+ guard let rgb = color.usingColorSpace(.displayP3) else { return nil }+ let components = [rgb.redComponent, rgb.greenComponent, rgb.blueComponent]+ guard components.allSatisfy(\.isFinite) else { return nil }+ return components.map { String(format: "%02X", Int((min(1, max(0, $0)) * 255).rounded())) }.joined()+ }+}+@MainActorfinal class TaskGlowSettings: ObservableObject {@Published private(set) var isEnabled: Bool+ @Published private(set) var appearance: TaskGlowAppearance++ nonisolated static let terminalDurationOptions: [TimeInterval] = [3, 5, 10, 15, 30, 60]+ static let brightnessRange = 0.2 ... 1.0var previewRequests: AnyPublisher<Void, Never> {previewSubject.eraseToAnyPublisher()@@ -12,10 +96,18 @@ final class TaskGlowSettings: ObservableObject {private let defaults: UserDefaultsprivate let previewSubject = PassthroughSubject<Void, Never>()private static let enabledKey = "TaskGlow.isEnabled"+ private static let speedKey = "TaskGlow.animationSpeed"+ private static let durationKey = "TaskGlow.terminalDuration"+ private static let brightnessKey = "TaskGlow.brightness"++ private static func colorKey(_ role: TaskGlowColorRole) -> String {+ "TaskGlow.color.\(role.rawValue)"+ }init(defaults: UserDefaults = .standard) {self.defaults = defaultsisEnabled = defaults.bool(forKey: Self.enabledKey)+ appearance = Self.loadAppearance(from: defaults)}func refresh() {@@ -23,6 +115,10 @@ final class TaskGlowSettings: ObservableObject {if enabled != isEnabled {isEnabled = enabled}+ let appearance = Self.loadAppearance(from: defaults)+ if appearance != self.appearance {+ self.appearance = appearance+ }}func setEnabled(_ enabled: Bool) {@@ -33,4 +129,58 @@ final class TaskGlowSettings: ObservableObject {previewSubject.send()}}++ func setColorHex(_ input: String, for role: TaskGlowColorRole) {+ if input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ defaults.removeObject(forKey: Self.colorKey(role))+ appearance.colors[role] = nil+ return+ }+ guard let hex = TaskGlowAppearance.normalizedColorHex(input), appearance.colors[role] != hex else { return }+ defaults.set(hex, forKey: Self.colorKey(role))+ appearance.colors[role] = hex+ }++ func setAnimationSpeed(_ speed: TaskGlowAnimationSpeed) {+ guard appearance.animationSpeed != speed else { return }+ defaults.set(speed.rawValue, forKey: Self.speedKey)+ appearance.animationSpeed = speed+ }++ func setTerminalDuration(_ duration: TimeInterval) {+ guard Self.terminalDurationOptions.contains(duration), appearance.terminalDuration != duration else { return }+ defaults.set(duration, forKey: Self.durationKey)+ appearance.terminalDuration = duration+ }++ func setBrightness(_ brightness: Double) {+ guard brightness.isFinite else { return }+ let value = min(Self.brightnessRange.upperBound, max(Self.brightnessRange.lowerBound, brightness))+ guard appearance.brightness != value else { return }+ defaults.set(value, forKey: Self.brightnessKey)+ appearance.brightness = value+ }++ private static func loadAppearance(from defaults: UserDefaults) -> TaskGlowAppearance {+ var appearance = TaskGlowAppearance()+ for role in TaskGlowColorRole.allCases {+ if let hex = defaults.string(forKey: colorKey(role)), TaskGlowAppearance.decodeColor(hex) != nil {+ appearance.colors[role] = hex+ }+ }+ if let rawSpeed = defaults.string(forKey: speedKey), let speed = TaskGlowAnimationSpeed(rawValue: rawSpeed) {+ appearance.animationSpeed = speed+ }+ let duration = defaults.double(forKey: durationKey)+ if terminalDurationOptions.contains(duration) {+ appearance.terminalDuration = duration+ }+ if defaults.object(forKey: brightnessKey) != nil {+ let brightness = defaults.double(forKey: brightnessKey)+ if brightness.isFinite, brightnessRange.contains(brightness) {+ appearance.brightness = brightness+ }+ }+ return appearance+ }}diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 46e8f26..543a81e 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -255,7 +255,8 @@ private extension AppSettingsView {LiquidGlassDivider()TaskGlowSettingsRow(settings: taskGlowSettings,- codexHookSettings: codexHookSettings+ codexHookSettings: codexHookSettings,+ onOptionsAction: onOptionsAction)LiquidGlassDivider()launchAtLoginRowdiff --git a/CodexBar/Views/Settings/AppearanceSettingsRows.swift b/CodexBar/Views/Settings/AppearanceSettingsRows.swiftindex be64fbd..9a03118 100644--- a/CodexBar/Views/Settings/AppearanceSettingsRows.swift+++ b/CodexBar/Views/Settings/AppearanceSettingsRows.swift@@ -18,6 +18,12 @@ struct MainPanelEntranceAnimationsSettingsRow: View {struct TaskGlowSettingsRow: View {@ObservedObject var settings: TaskGlowSettings@ObservedObject var codexHookSettings: CodexHookSettings+ let onOptionsAction: (SettingsOptionsPanelAction) -> Void+ @State private var anchorProvider = ScreenFrameProvider()++ private var canShowOptions: Bool {+ settings.isEnabled && codexHookSettings.isOperable && !codexHookSettings.isUpdating+ }var body: some View {SettingsToggleRow(@@ -28,6 +34,18 @@ struct TaskGlowSettingsRow: View {set: { settings.setEnabled($0) }),isEnabled: codexHookSettings.isOperable && !codexHookSettings.isUpdating- )+ ) {+ SettingsOptionsButton(isAvailable: canShowOptions) {+ onOptionsAction(.toggle(panel: .taskGlow, anchorProvider: anchorProvider))+ }+ }+ .background {+ ScreenFrameReader(provider: anchorProvider)+ }+ .onChange(of: canShowOptions) { _, available in+ if !available {+ onOptionsAction(.close(panel: .taskGlow))+ }+ }}}diff --git a/CodexBar/Views/Settings/TaskGlowOptionsView.swift b/CodexBar/Views/Settings/TaskGlowOptionsView.swiftnew file mode 100644index 0000000..9c02d3f--- /dev/null+++ b/CodexBar/Views/Settings/TaskGlowOptionsView.swift@@ -0,0 +1,345 @@+import SwiftUI++struct TaskGlowOptionsView: View {+ @ObservedObject var settings: TaskGlowSettings++ var body: some View {+ VStack(spacing: SettingsOptionsPanelMetrics.rowSpacing) {+ ForEach(TaskGlowColorRole.allCases, id: \.self) { role in+ optionRow(role.title) {+ TaskGlowColorHexField(settings: settings, role: role)+ }+ }++ LiquidGlassDivider()+ .padding(.vertical, 4)++ optionRow("task-glow.speed.title") {+ SettingsOptionsPicker(+ title: "task-glow.speed.title",+ selection: Binding(+ get: { settings.appearance.animationSpeed },+ set: { settings.setAnimationSpeed($0) }+ ),+ options: TaskGlowAnimationSpeed.allCases,+ label: { $0.title },+ width: 100,+ alignment: .trailing+ )+ }+ optionRow("task-glow.duration.title") {+ SettingsOptionsPicker(+ title: "task-glow.duration.title",+ selection: Binding(+ get: { settings.appearance.terminalDuration },+ set: { settings.setTerminalDuration($0) }+ ),+ options: TaskGlowSettings.terminalDurationOptions,+ label: { String(localized: "duration.seconds", defaultValue: "\(Int($0), specifier: "%lld")") },+ width: 100,+ alignment: .trailing+ )+ }+ optionRow("task-glow.brightness.title") {+ TaskGlowBrightnessControl(value: Binding(+ get: { settings.appearance.brightness },+ set: { settings.setBrightness($0) }+ ))+ }+ }+ .font(.caption)+ .controlSize(.small)+ .padding(.horizontal, SettingsOptionsPanelMetrics.horizontalPadding)+ .padding(.vertical, SettingsOptionsPanelMetrics.verticalPadding)+ .frame(width: Self.panelWidth)+ .sidePanelChrome(cornerRadius: SettingsOptionsPanelMetrics.cornerRadius)+ }++ private static let panelWidth: CGFloat = 280++ static var initialPanelSize: CGSize {+ CGSize(width: panelWidth, height: 220)+ }++ private func optionRow(_ title: LocalizedStringResource, @ViewBuilder content: () -> some View) -> some View {+ HStack(spacing: SettingsOptionsPanelMetrics.controlSpacing) {+ Text(title)+ .foregroundStyle(.secondary)+ Spacer(minLength: 8)+ content()+ }+ .frame(height: SettingsOptionsPanelMetrics.rowHeight)+ }+}++private struct TaskGlowBrightnessControl: View {+ @Binding var value: Double++ var body: some View {+ HStack(spacing: 7) {+ TaskGlowBrightnessSlider(value: $value)+ .frame(width: 88, height: 22)+ Text(value, format: .percent.precision(.fractionLength(0)))+ .font(.system(size: 10, weight: .medium, design: .rounded))+ .monospacedDigit()+ .foregroundStyle(.secondary)+ .frame(width: 32, alignment: .trailing)+ }+ .padding(.horizontal, 8)+ .frame(height: 22)+ .background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 7))+ }+}++private struct TaskGlowBrightnessSlider: NSViewRepresentable {+ @Binding var value: Double++ func makeCoordinator() -> Coordinator {+ Coordinator(self)+ }++ func makeNSView(context: Context) -> NSSlider {+ let slider = NSSlider()+ slider.cell = BrightnessSliderCell()+ slider.controlSize = .small+ slider.minValue = TaskGlowSettings.brightnessRange.lowerBound+ slider.maxValue = TaskGlowSettings.brightnessRange.upperBound+ slider.isContinuous = true+ slider.target = context.coordinator+ slider.action = #selector(Coordinator.valueChanged(_:))+ return slider+ }++ func updateNSView(_ slider: NSSlider, context: Context) {+ context.coordinator.parent = self+ slider.doubleValue = value+ }++ final class Coordinator: NSObject {+ var parent: TaskGlowBrightnessSlider++ init(_ parent: TaskGlowBrightnessSlider) {+ self.parent = parent+ }++ @objc func valueChanged(_ sender: NSSlider) {+ parent.value = sender.doubleValue+ }+ }++ private final class BrightnessSliderCell: NSSliderCell {+ override var knobThickness: CGFloat {+ 12+ }++ override func drawBar(inside rect: NSRect, flipped: Bool) {+ let knob = knobRect(flipped: flipped)+ let track = NSRect(x: rect.minX + knob.width / 2, y: rect.midY - 2, width: rect.width - knob.width, height: 4)+ NSColor.labelColor.withAlphaComponent(0.1).setFill()+ NSBezierPath(roundedRect: track, xRadius: 2, yRadius: 2).fill()++ let endX = knob.midX+ let filled = NSRect(x: track.minX, y: track.minY, width: max(0, endX - track.minX), height: track.height)+ NSColor.controlAccentColor.setFill()+ NSBezierPath(roundedRect: filled, xRadius: 2, yRadius: 2).fill()+ }++ override func drawKnob(_ knobRect: NSRect) {+ let knob = NSRect(x: knobRect.midX - 6, y: knobRect.midY - 6, width: 12, height: 12)+ NSGraphicsContext.saveGraphicsState()+ let shadow = NSShadow()+ shadow.shadowColor = NSColor.black.withAlphaComponent(0.18)+ shadow.shadowBlurRadius = 2+ shadow.shadowOffset = NSSize(width: 0, height: -0.5)+ shadow.set()+ NSColor.white.setFill()+ NSBezierPath(ovalIn: knob).fill()+ NSGraphicsContext.restoreGraphicsState()+ NSColor.black.withAlphaComponent(0.08).setStroke()+ let outline = NSBezierPath(ovalIn: knob.insetBy(dx: 0.25, dy: 0.25))+ outline.lineWidth = 0.5+ outline.stroke()+ }+ }+}++private struct TaskGlowColorHexField: View {+ @ObservedObject var settings: TaskGlowSettings+ let role: TaskGlowColorRole+ @State private var draft: String+ @State private var isFocused = false++ init(settings: TaskGlowSettings, role: TaskGlowColorRole) {+ self.settings = settings+ self.role = role+ _draft = State(initialValue: settings.appearance.colors[role] ?? "")+ }++ private var isValid: Bool {+ draft.isEmpty || TaskGlowAppearance.normalizedColorHex(draft) != nil+ }++ var body: some View {+ HStack(spacing: SettingsOptionsPanelMetrics.controlSpacing) {+ RoundedRectangle(cornerRadius: 3)+ .fill(Color(nsColor: settings.appearance.color(for: role)))+ .overlay {+ RoundedRectangle(cornerRadius: 3)+ .strokeBorder(.primary.opacity(0.15), lineWidth: 0.5)+ }+ .frame(width: 14, height: 14)++ Text(verbatim: "#")+ .font(.system(.caption, design: .monospaced))+ .foregroundStyle(.secondary)+ .frame(width: 8)++ TaskGlowHexInput(+ text: $draft,+ isFocused: $isFocused,+ placeholder: TaskGlowAppearance.encodeColor(role.defaultColor) ?? "",+ onChange: { settings.setColorHex($0, for: role) },+ onEndEditing: { value in+ let hex = TaskGlowAppearance.normalizedColorHex(value) ?? ""+ settings.setColorHex(hex, for: role)+ return hex+ },+ onCancel: { settings.appearance.colors[role] ?? "" }+ )+ .overlay {+ RoundedRectangle(cornerRadius: 5)+ .strokeBorder(isValid ? .clear : .red, lineWidth: 1)+ .allowsHitTesting(false)+ }+ .frame(width: 74)+ }+ .onChange(of: settings.appearance.colors[role]) { _, _ in+ if !isFocused {+ draft = settings.appearance.colors[role] ?? ""+ }+ }+ }+}++private struct TaskGlowHexInput: NSViewRepresentable {+ @Binding var text: String+ @Binding var isFocused: Bool+ let placeholder: String+ let onChange: (String) -> Void+ let onEndEditing: (String) -> String+ let onCancel: () -> String++ func makeCoordinator() -> Coordinator {+ Coordinator(self)+ }++ func makeNSView(context: Context) -> NSTextField {+ let field = NSTextField()+ field.controlSize = .small+ field.font = .monospacedSystemFont(ofSize: 11, weight: .regular)+ field.alignment = .center+ field.bezelStyle = .roundedBezel+ field.cell?.usesSingleLineMode = true+ field.formatter = TaskGlowHexFormatter()+ field.delegate = context.coordinator+ return field+ }++ func updateNSView(_ field: NSTextField, context: Context) {+ context.coordinator.parent = self+ field.placeholderString = placeholder+ if field.currentEditor() == nil, field.stringValue != text {+ field.stringValue = text+ }+ }++ final class Coordinator: NSObject, NSTextFieldDelegate {+ var parent: TaskGlowHexInput+ init(_ parent: TaskGlowHexInput) {+ self.parent = parent+ }++ func controlTextDidChange(_ notification: Notification) {+ guard let field = notification.object as? NSTextField else { return }+ parent.text = field.stringValue+ parent.onChange(field.stringValue)+ }++ func controlTextDidBeginEditing(_ notification: Notification) {+ parent.isFocused = true+ if let field = notification.object as? NSTextField,+ let editor = field.currentEditor() as? NSTextView {+ editor.isAutomaticTextCompletionEnabled = false+ editor.isAutomaticSpellingCorrectionEnabled = false+ editor.isAutomaticTextReplacementEnabled = false+ editor.isAutomaticQuoteSubstitutionEnabled = false+ editor.isAutomaticDashSubstitutionEnabled = false+ editor.isContinuousSpellCheckingEnabled = false+ }+ }++ func controlTextDidEndEditing(_ notification: Notification) {+ guard let field = notification.object as? NSTextField else { return }+ // 原生结束编辑回调逐次提交, 不依赖 SwiftUI 可能合并的焦点状态变化+ let value = parent.onEndEditing(field.currentEditor()?.string ?? field.stringValue)+ setText(value, in: field)+ parent.isFocused = false+ }++ func control(_ control: NSControl, textView _: NSTextView, doCommandBy commandSelector: Selector) -> Bool {+ guard let field = control as? NSTextField else { return false }+ if commandSelector == #selector(NSResponder.insertNewline(_:)) {+ control.window?.makeFirstResponder(control.window)+ return true+ }+ if commandSelector == #selector(NSResponder.cancelOperation(_:)) {+ setText(parent.onCancel(), in: field)+ control.window?.makeFirstResponder(control.window)+ return true+ }+ return false+ }++ private func setText(_ value: String, in field: NSTextField) {+ // 结束编辑通知发出时 field editor 可能仍存在, 与控件及绑定一起收敛+ field.currentEditor()?.string = value+ field.stringValue = value+ parent.text = value+ }+ }+}++/// 原生编辑器在应用输入前校验文本, 避免 SwiftUI 回写与连续按键争用文本和选区+final nonisolated class TaskGlowHexFormatter: Formatter {+ override func string(for obj: Any?) -> String? {+ obj as? String+ }++ override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription _: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {+ obj?.pointee = string as NSString+ return true+ }++ override func isPartialStringValid(_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString>, proposedSelectedRange proposedSelRangePtr: NSRangePointer?, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription _: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {+ let original = origString as NSString+ let proposed = partialStringPtr.pointee+ let prefix = original.substring(to: origSelRange.location)+ let suffix = original.substring(from: NSMaxRange(origSelRange))+ let insertedLength = proposed.length - (prefix as NSString).length - (suffix as NSString).length+ guard insertedLength >= 0 else { return false }+ var inserted = proposed.substring(with: NSRange(location: origSelRange.location, length: insertedLength))+ .filter { $0.isASCII && ($0.isLetter || $0.isNumber) }+ .uppercased()+ if insertedLength > 0, inserted.isEmpty {+ partialStringPtr.pointee = original+ proposedSelRangePtr?.pointee = origSelRange+ return false+ }+ inserted = String(inserted.prefix(max(0, 6 - prefix.count - suffix.count)))+ let result = prefix + inserted + suffix+ guard result != proposed as String else { return true }+ partialStringPtr.pointee = result as NSString+ proposedSelRangePtr?.pointee = NSRange(location: (prefix as NSString).length + (inserted as NSString).length, length: 0)+ return false+ }+}diff --git a/CodexBarTests/TaskGlowTests.swift b/CodexBarTests/TaskGlowTests.swiftnew file mode 100644index 0000000..b2b8f0b--- /dev/null+++ b/CodexBarTests/TaskGlowTests.swift@@ -0,0 +1,232 @@+import AppKit+import Testing++struct TaskGlowTests {+ @Test(arguments: ["#", " ", "\t\n", "中文", "😀", "éß12", "!@#$%^&*()"])+ func nonAlphanumericInputPreservesSelectedColor(_ input: String) {+ let formatter = TaskGlowHexFormatter()+ let original = "123456"+ let selectedRange = NSRange(location: 2, length: 2)+ var proposed = (original as NSString).replacingCharacters(in: selectedRange, with: input) as NSString+ var proposedRange = NSRange(location: 2 + (input as NSString).length, length: 0)+ #expect(!formatter.isPartialStringValid(+ &proposed,+ proposedSelectedRange: &proposedRange,+ originalString: original,+ originalSelectedRange: selectedRange,+ errorDescription: nil+ ))+ #expect(proposed as String == original)+ #expect(proposedRange == selectedRange)+ }++ @Test func pastedColorFiltersNonAlphanumericCharactersBeforeApplyingLengthLimit() {+ let formatter = TaskGlowHexFormatter()+ var proposed: NSString = " #a b-1😀2\t中e_f!78 "+ var proposedRange = NSRange(location: proposed.length, length: 0)+ #expect(!formatter.isPartialStringValid(+ &proposed,+ proposedSelectedRange: &proposedRange,+ originalString: "",+ originalSelectedRange: NSRange(location: 0, length: 0),+ errorDescription: nil+ ))+ #expect(proposed as String == "AB12EF")+ #expect(proposedRange == NSRange(location: 6, length: 0))+ }++ @Test(arguments: [0, 2, 6])+ func repeatedOverflowPreservesColorAndSelection(_ cursor: Int) {+ let formatter = TaskGlowHexFormatter()+ let original = "123456"+ let originalRange = NSRange(location: cursor, length: 0)+ for _ in 0 ..< 100 {+ var proposed = (original as NSString).replacingCharacters(in: originalRange, with: "a") as NSString+ var proposedRange = NSRange(location: cursor + 1, length: 0)+ let accepted = formatter.isPartialStringValid(+ &proposed,+ proposedSelectedRange: &proposedRange,+ originalString: original,+ originalSelectedRange: originalRange,+ errorDescription: nil+ )+ #expect(!accepted)+ #expect(proposed as String == original)+ #expect(proposedRange == originalRange)+ }+ }++ @Test func colorFormatterLimitsReplacementWithoutChangingSurroundingText() {+ let formatter = TaskGlowHexFormatter()+ var proposed: NSString = "12abcdef56"+ var proposedRange = NSRange(location: 8, length: 0)+ #expect(!formatter.isPartialStringValid(+ &proposed,+ proposedSelectedRange: &proposedRange,+ originalString: "123456",+ originalSelectedRange: NSRange(location: 2, length: 2),+ errorDescription: nil+ ))+ #expect(proposed as String == "12AB56")+ #expect(proposedRange == NSRange(location: 4, length: 0))+ }++ @Test func colorStoragePreservesDisplayP3Components() throws {+ let color = NSColor(displayP3Red: 128.0 / 255, green: 1, blue: 0, alpha: 1)+ let hex = try #require(TaskGlowAppearance.encodeColor(color))+ #expect(hex == "80FF00")+ let restored = try #require(TaskGlowAppearance.decodeColor(hex))+ #expect(restored.colorSpace == .displayP3)+ #expect(abs(restored.redComponent - color.redComponent) < 0.0001)+ #expect(restored.greenComponent == 1)+ #expect(restored.blueComponent == 0)+ }++ @Test func existingEnabledPreferenceKeepsOriginalAppearance() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ preferences.defaults.set(true, forKey: "TaskGlow.isEnabled")+ let settings = TaskGlowSettings(defaults: preferences.defaults)+ #expect(settings.isEnabled)+ #expect(settings.appearance == TaskGlowAppearance())+ #expect(settings.appearance.color(for: .running) == .systemCyan)+ #expect(settings.appearance.color(for: .waiting) == .systemOrange)+ #expect(settings.appearance.color(for: .completed) == .systemGreen)+ #expect(settings.appearance.color(for: .terminated) == .systemRed)+ }++ @Test func appearancePersistsAndRefreshesWithoutChangingEnabledPreference() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let settings = TaskGlowSettings(defaults: preferences.defaults)+ let observer = TaskGlowSettings(defaults: preferences.defaults)+ for (role, hex) in zip(TaskGlowColorRole.allCases, ["123456", "ABCDEF", "00FF00", "FF0000"]) {+ settings.setColorHex(hex, for: role)+ #expect(settings.appearance.colors[role] == hex)+ }+ settings.setAnimationSpeed(.slow)+ settings.setTerminalDuration(15)+ settings.setBrightness(0.45)+ observer.refresh()+ #expect(observer.appearance == settings.appearance)+ #expect(TaskGlowSettings(defaults: preferences.defaults).appearance == settings.appearance)+ #expect(!observer.isEnabled)+ #expect(preferences.defaults.object(forKey: "TaskGlow.isEnabled") == nil)+ }++ @Test func hexInputNormalizesValidColorsAndPreservesSavedColorWhileEditing() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let settings = TaskGlowSettings(defaults: preferences.defaults)+ settings.setColorHex(" #ab12ef\n", for: .running)+ #expect(settings.appearance.colors[.running] == "AB12EF")+ #expect(preferences.defaults.string(forKey: "TaskGlow.color.running") == "AB12EF")+ for invalid in ["#", "#abc", "12345", "1234567", "#12345678", "GGGGGG", "##123456", "12 3456"] {+ settings.setColorHex(invalid, for: .running)+ #expect(settings.appearance.colors[.running] == "AB12EF")+ #expect(preferences.defaults.string(forKey: "TaskGlow.color.running") == "AB12EF")+ }+ settings.setColorHex("12abef", for: .running)+ #expect(TaskGlowSettings(defaults: preferences.defaults).appearance.colors[.running] == "12ABEF")+ settings.setColorHex(" \n", for: .running)+ #expect(settings.appearance.colors[.running] == nil)+ #expect(preferences.defaults.object(forKey: "TaskGlow.color.running") == nil)+ #expect(TaskGlowSettings(defaults: preferences.defaults).appearance.color(for: .running) == .systemCyan)+ }++ @Test func invalidAppearanceValuesFallBackAndInvalidWritesAreIgnored() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ 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(4, forKey: "TaskGlow.brightness")+ let settings = TaskGlowSettings(defaults: preferences.defaults)+ #expect(settings.appearance == TaskGlowAppearance())+ settings.setTerminalDuration(.infinity)+ settings.setTerminalDuration(0)+ settings.setBrightness(.nan)+ #expect(settings.appearance == TaskGlowAppearance())+ settings.setBrightness(-1)+ #expect(settings.appearance.brightness == 0.2)+ settings.setBrightness(2)+ #expect(settings.appearance.brightness == 1)+ #expect(TaskGlowAppearance.decodeColor("-12345") == nil)+ #expect(TaskGlowAppearance.decodeColor("GGGGGG") == nil)+ }++ @Test(arguments: TaskGlowSettings.terminalDurationOptions)+ func terminalDurationOnlyChangesGlowExpiration(_ duration: TimeInterval) {+ let snapshot = completedSnapshot()+ var presentation = TaskGlowPresentationState()+ presentation.update(snapshot: snapshot, terminalEvents: [], isEnabled: true, acceptsBriefEvents: true, now: TestFixtures.now)+ presentation.refresh(now: TestFixtures.now, terminalDuration: duration)+ #expect(presentation.state == .completed)+ #expect(presentation.terminal?.expiresAt == TestFixtures.now.addingTimeInterval(duration))+ #expect(snapshot.statusItemActivityExpiration == TestFixtures.now.addingTimeInterval(10))+ presentation.refresh(now: TestFixtures.now.addingTimeInterval(duration), terminalDuration: duration)+ #expect(presentation.state == .hidden)+ #expect(presentation.terminal == nil)+ }++ @Test func changingDurationPreservesEntranceAndWakeDoesNotReplayExpiredGlow() {+ var presentation = TaskGlowPresentationState()+ presentation.update(snapshot: completedSnapshot(), terminalEvents: [], isEnabled: true, acceptsBriefEvents: true, now: TestFixtures.now)+ presentation.refresh(now: TestFixtures.now, terminalDuration: 10)+ presentation.refresh(now: TestFixtures.now.addingTimeInterval(2), terminalDuration: 15)+ #expect(presentation.terminal?.startedAt == TestFixtures.now)+ #expect(presentation.terminal?.expiresAt == TestFixtures.now.addingTimeInterval(15))+ presentation.refresh(now: TestFixtures.now.addingTimeInterval(16), terminalDuration: 15)+ #expect(presentation.state == .hidden)+ }++ @Test func repeatedTerminalRefreshPreservesPresentationAndNewEventRestartsEntrance() throws {+ let snapshot = completedSnapshot()+ var presentation = TaskGlowPresentationState()+ presentation.update(snapshot: snapshot, terminalEvents: [], isEnabled: true, acceptsBriefEvents: true, now: TestFixtures.now)+ presentation.refresh(now: TestFixtures.now, terminalDuration: 10)+ let original = try #require(presentation.terminal)+ presentation.refresh(now: TestFixtures.now.addingTimeInterval(2), terminalDuration: 10)+ #expect(presentation.terminal == original)++ let nextSnapshot = completedSnapshot()+ let nextPresentationTime = TestFixtures.now.addingTimeInterval(3)+ presentation.update(snapshot: nextSnapshot, terminalEvents: [], isEnabled: true, acceptsBriefEvents: true, now: nextPresentationTime)+ presentation.refresh(now: nextPresentationTime, terminalDuration: 10)+ #expect(presentation.terminal?.eventID == nextSnapshot.latestTerminalEvent?.id)+ #expect(presentation.terminal?.eventID != original.eventID)+ #expect(presentation.terminal?.startedAt == nextPresentationTime)+ }++ @Test func concurrentTaskCompletionStillShowsBrieflyThenRestoresRunning() throws {+ var presentation = TaskGlowPresentationState()+ let running = CodexActivityTaskSnapshot(+ id: UUID(), isAnonymous: false, latestEvent: .toolStarted, projectName: nil,+ modelName: nil, effort: nil, toolName: nil, startedAt: TestFixtures.now,+ stateChangedAt: TestFixtures.now, showsPreciseDuration: true, activeSubagentCount: nil+ )+ let snapshot = CodexActivitySnapshot(+ waitingTasks: [], runningTasks: [running],+ recentCompletions: completedSnapshot().recentCompletions, recentTerminations: []+ )+ presentation.update(snapshot: snapshot, terminalEvents: [], isEnabled: true, acceptsBriefEvents: true, now: TestFixtures.now)+ try presentation.update(+ snapshot: snapshot, terminalEvents: [#require(snapshot.latestTerminalEvent)],+ isEnabled: true, acceptsBriefEvents: true, now: TestFixtures.now+ )+ presentation.refresh(now: TestFixtures.now, terminalDuration: 15)+ #expect(presentation.state == .completed)+ #expect(presentation.terminal?.expiresAt == TestFixtures.now.addingTimeInterval(3))+ presentation.refresh(now: TestFixtures.now.addingTimeInterval(3), terminalDuration: 15)+ #expect(presentation.state == .running)+ }++ private func completedSnapshot() -> CodexActivitySnapshot {+ let completion = CodexActivityCompletion(+ id: UUID(), isAnonymous: false, projectName: nil, modelName: nil,+ effort: nil, completedAt: TestFixtures.now, duration: 60+ )+ return CodexActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])+ }+}diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex dd19f11..788a3d1 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 4.0.4-CURRENT_PROJECT_VERSION = 104+MARKETING_VERSION = 4.0.5+CURRENT_PROJECT_VERSION = 105diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.mdindex 5ee15ae..4d6e591 100644--- a/Docs/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md@@ -51,17 +51,17 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。| 场景 | 展示规则 || --- | --- |-| 存在活跃任务 | 橙色等待批准优先于青色运行 |+| 存在活跃任务 | 等待批准优先于运行 || 其他任务仍活跃时确认结束事件 | 最新事件覆盖活动状态 3 秒,最后 0.5 秒淡出;新事件替换提示并重新计时 |-| 无活跃任务 | 快照中的最新终态显示到结束后 10 秒,最后 1 秒淡出 |+| 无活跃任务 | 快照中的最新终态按设置的结束时长显示,默认结束后 10 秒到期,最后 1 秒淡出 |-完成使用绿色,终止使用红色;结束时间相同优先终止。所有计时包含进场动画,到期后按最新快照恢复展示。+颜色、速度、亮度和结束时长由 `TaskGlowSettings.appearance` 提供。默认运行使用青色,等待批准使用橙色,完成使用绿色,终止使用红色;结束时间相同优先终止。所有计时包含进场动画,到期后按最新快照恢复展示。-设置从关闭切换为开启且 Hook 可用时,`TaskGlowSettings.previewRequests` 请求一次青色运行预览,完成一个 2.7 秒往返周期后恢复实际状态。启动和设置刷新只恢复开关值,不触发预览。预览覆盖期间继续接收真实任务更新,不产生任务事件。+设置从关闭切换为开启且 Hook 可用时,`TaskGlowSettings.previewRequests` 请求一次使用当前外观设置的运行预览,完成一个往返周期后恢复实际状态,标准速度下周期为 2.7 秒。启动和设置刷新只恢复开关值,不触发预览。预览覆盖期间继续接收真实任务更新,不产生任务事件。播放和收尾期间忽略新的预览请求。关闭开关通过光带已有的退场流程快速收回到中心并淡出;所有屏幕实际收尾完成后释放预览占用。Hook 不可用、系统睡眠、屏幕休眠或会话不活跃时取消预览。-光带使用不激活、穿透鼠标的 `NSPanel`,跨 Space 和全屏显示。系统睡眠、屏幕休眠或用户会话不活跃时移除窗口,恢复后按当前时间接续有效状态。屏幕配置变化时重建窗口,各显示器共享运动时钟。+光带使用不激活、穿透鼠标的 `NSPanel`,跨 Space 和全屏显示。系统睡眠、屏幕休眠或用户会话不活跃时移除窗口,恢复后按当前时间接续有效状态。屏幕配置变化时重建窗口,各显示器共享运动时钟。运动时钟根据分段时长和速度计算周期,改速时保留当前进度。## 状态栏图标@@ -222,15 +222,16 @@ fallback panel 在展示前根据 SwiftUI fitting size 和目标屏幕可见区SwiftUI 可能在窗口创建完成前上报高度。`SettingsWindowController` 缓存最近一次有效测量,在 `HostingWindowController.window` 就绪后应用。-主面板布局、通知、自动重置和防睡眠的二级设置面板在首次打开时创建,之后复用内容及必要的高度变化订阅。+主面板布局、流光、通知、自动重置和防睡眠的二级设置面板在首次打开时创建,之后复用内容及必要的高度变化订阅。-这四个设置子面板包含交互控件,因此使用可获得键盘焦点的 `KeyableBorderlessPanel`。主面板的热力图、Reset Credits 和活动中心详情使用不会激活的 `NonactivatingSidePanel`。收起设置子面板时,`SidePanelSupport.orderOut` 只在该子面板仍是 key window 时恢复父窗口焦点;如果焦点已经主动转移到主面板或其他窗口,则不能再抢回,否则新打开的交互表面可能因失焦立即关闭。+这些设置子面板使用可获得键盘焦点的 `KeyableBorderlessPanel`,展开时保留主设置窗口的焦点,点击输入框后进入编辑。收起面板前结束原生编辑,颜色输入在结束编辑回调中完成校验并同步显示。主面板的热力图、Reset Credits 和活动中心详情使用不会激活的 `NonactivatingSidePanel`。收起设置子面板时,`SidePanelSupport.orderOut` 只在该子面板仍是 key window 时恢复父窗口焦点;焦点已转移到其他窗口时不恢复父窗口焦点。自动重置与防睡眠从关闭切换为开启时,`AppSettingsView` 使用 `HelperFeatureConfirmation` 显示统一确认框。确认框按 `KeepAliveController.HelperStatus` 组合 Helper 提示与对应功能说明,用户确认后才调用设置对象写入开启状态。已开启设置行在 `.requiresApproval` 状态显示 `打开系统设置` 按钮。二级设置入口使用各自的可用性结论:- 主面板布局入口始终可用+- 流光要求 `TaskGlowSettings.isEnabled`、Hook 的 `isOperable` 为 `true`,且 Hook 未在更新- 通知读取 `NotificationSettings.canShowOptions`- 自动重置要求 `AutoResetSettings.isEnabled` 且 `KeepAliveController.helperStatus == .enabled`- 防睡眠读取 `KeepAliveController.canShowOptions`@@ -241,7 +242,7 @@ SwiftUI 可能在窗口创建完成前上报高度。`SettingsWindowController`布局排序使用手柄上的自定义 `DragGesture`。拖动项通过悬浮副本跟随指针,其他行在跨过半行距离时按视图内预览顺序实时让位,松手后才调用 `setSectionOrder(_:)` 一次性持久化最终顺序。-`SettingsWindowController` 持有这一窗口组唯一的 `UndoManager`。设置主窗口通过 `AuxiliaryHostingWindow` 暴露它,四个设置子面板展示时从父窗口取得同一实例,因此焦点位于设置主窗口或任一子面板时,`⌘Z` 和 `⌘⇧Z` 都作用于同一份布局历史。Hook 状态变化引起的任务中心自动显隐不进入用户撤销历史。+`SettingsWindowController` 持有这一窗口组唯一的 `UndoManager`。设置主窗口通过 `AuxiliaryHostingWindow` 暴露它,各设置子面板展示时从父窗口取得同一实例,因此焦点位于设置主窗口或任一子面板时,`⌘Z` 和 `⌘⇧Z` 都作用于同一份布局历史。Hook 状态变化引起的任务中心自动显隐不进入用户撤销历史。### 代理配置对话框@@ -305,8 +306,8 @@ app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完## 手动验证- 左键打开主面板,右键和 Control 点击打开上下文菜单-- 多任务运行或等待批准期间,完成和终止触发 3 秒流光提示;连续结束及全部任务结束时颜色与到期时间正确-- 开启流光播放一次预览,关闭时收回并淡出,收尾期间不重播,收尾后可再次开启预览;预览期间任务状态变化后正确接续实际状态+- 多任务运行或等待批准期间,完成和终止触发 3 秒流光提示;颜色跟随配置,全部任务结束后按所选结束时长到期+- 开启流光按当前颜色、速度和亮度播放一次预览,关闭时收回并淡出,收尾期间不重播,收尾后可再次开启预览;预览期间任务状态变化后正确接续实际状态- 历史重读及唤醒对账不补播旧终态短提示,恢复后的真实结束仍有提示;多显示器和屏幕配置变化后运动与到期时间一致- 菜单栏符号随任务状态切换,最新终态在结束 10 秒后恢复空闲,跨睡眠唤醒后按当前时间显示- 普通人物与四种任务徽章之间切换时过渡完整,快速连续切换后显示最新状态;带徽章时反复切换额度显隐仍保持流畅,首次显示和唤醒重算不播放过渡@@ -321,7 +322,8 @@ app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完- 设置窗口首次打开、关闭和再次打开时焦点正确- 关于页刷新或重连期间,关闭、最小化、完全遮挡设置窗口或切离关于页后,重连图标不再持续绘制或摆动;恢复展示后仅在仍忙碌时恢复动画,窗口失焦但仍可见时行为正常- 冷启动后首次打开设置时通用页直接使用完整内容高度;切换三个 tab 时窗口高度自适应,屏幕空间充足时均不显示滚动条-- 主面板布局、通知、自动重置和防睡眠子面板互斥,顶边对齐对应设置行,内容变化后高度正确+- 主面板布局、流光、通知、自动重置和防睡眠子面板互斥,顶边对齐对应设置行,内容变化后高度正确+- 流光子面板展开时颜色输入框不自动聚焦;六位输入限制、粘贴过滤和大写转换正确;无效颜色在回车、失焦及收起时恢复默认,显示与实际颜色一致- 设置子面板展开时从菜单栏打开主面板,主面板保持打开,设置子面板收起且不把焦点抢回设置窗口- 主面板区域拖动时悬浮行跟随指针,跨过半行后其他行实时让位,松手后平滑落位并只保存最终顺序;拖拽和显隐操作可以通过 `⌘Z` 逐步撤销并通过 `⌘⇧Z` 重做,焦点在设置主窗口或任一设置子面板时均有效;重启后保持配置,最后一个可见区域无法关闭;Hook 关闭时任务中心自动关闭、开关置灰但仍可拖动,任务中心为唯一可见区域时账户自动开启;重新开启 Hook 后任务中心自动显示,手动隐藏后重启仍保持隐藏,自动联动不进入用户撤销历史- 上下文菜单打开设置或日志时没有焦点丢失diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.mdindex 6a26285..9d689d1 100644--- a/Docs/UserGuide/settings.md+++ b/Docs/UserGuide/settings.md@@ -24,18 +24,20 @@ Hook 关闭时任务区域自动关闭,从关闭切换到开启时自动显示### 流光效果-在各显示器顶部显示任务状态,需要 CodexBar Hook 开启且校验通过。此开关默认关闭,与主面板的“动画效果”独立。+在各显示器顶部显示任务状态,需要 CodexBar Hook 开启且校验通过。此开关默认关闭,与主面板的“动画效果”独立。开启后,点击右侧选项按钮可调整各状态颜色、动画速度、亮度和结束时长。-开启时会播放一次青色往返预览,随后显示实际任务状态。关闭时光带快速收回到屏幕中心并淡出。预览播放或收尾期间反复开关不会重播;收尾完成后再次开启可以重新预览。+开启时按当前运行颜色、速度和亮度播放一次往返预览,随后显示实际任务状态。关闭时光带快速收回到屏幕中心并淡出。预览播放或收尾期间反复开关不会重播;收尾完成后再次开启可以重新预览。-| 颜色 | 含义 |+| 默认颜色 | 含义 || --- | --- || 青色往返流光 | 任务运行中 || 橙色呼吸光带 | 等待批准,优先于运行状态 || 绿色 | 任务完成 || 红色 | 任务终止,包括中断 |-并发任务中有任务结束时,显示 3 秒的完成或终止提示,再恢复当前任务状态。全部任务结束后,显示最新结束记录,直到其结束后的 10 秒。+颜色使用 Display P3 六位十六进制值,字母自动转为大写,空输入框显示默认颜色值。无效颜色以红框提示,按回车、移开焦点或收起面板时恢复默认颜色。动画速度可选较慢、标准和较快,默认标准;亮度可调范围为 20%–100%,默认 100%。++并发任务中有任务结束时,显示 3 秒的完成或终止提示,再恢复当前任务状态。全部任务结束后,从最新记录的结束时间起,按所选“结束时长”显示提示;可选 3、5、10、15、30 或 60 秒,默认 10 秒。Hook 不可用时隐藏光带并保留开关选择。系统睡眠、屏幕休眠或用户会话不活跃时也会隐藏;恢复后显示当前状态,已过期的结束提示不会重播。diff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.mdindex 3022b5a..2ac740e 100644--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md@@ -51,17 +51,17 @@ Shutdown reverses the order, except for helper-owned system state. AppDelegate f| Scenario | Presentation rule || --- | --- |-| Active tasks exist | Orange approval waiting takes priority over cyan running |+| Active tasks exist | Approval waiting takes priority over running || A task ending is confirmed while others remain active | The latest event overrides activity for 3 seconds, fading during the final 0.5 seconds; a new event replaces it and restarts the timer |-| No active tasks | The snapshot's latest terminal state remains until 10 seconds after its end time, fading during the final second |+| No active tasks | The snapshot's latest terminal state uses the configured end duration, defaulting to 10 seconds after its end time, fading during the final second |-Completion is green and termination is red, with termination taking priority on equal end times. Durations include entrance animations. The latest snapshot determines the state after expiration.+`TaskGlowSettings.appearance` supplies colors, speed, brightness, and end duration. The default colors are cyan for running, orange for approval waiting, green for completion, and red for termination. Termination takes priority on equal end times. Durations include entrance animations. The latest snapshot determines the state after expiration.-Switching the setting from off to on while Hook is available sends a `TaskGlowSettings.previewRequests` event for one cyan running preview. After one 2.7-second round trip, presentation returns to the actual state. Startup and settings refresh restore the switch value without requesting a preview. Real task updates continue during the preview, which produces no task events.+Switching the setting from off to on while Hook is available sends a `TaskGlowSettings.previewRequests` event for one running preview using the current appearance settings. After one round trip, presentation returns to the actual state; the cycle lasts 2.7 seconds at Standard speed. Startup and settings refresh restore the switch value without requesting a preview. Real task updates continue during the preview, which produces no task events.New preview requests are ignored during playback and dismissal. Turning the switch off uses the glow's existing dismissal path to retract quickly to the center and fade out. Preview occupancy clears once every display finishes dismissal. Hook unavailability, system sleep, display sleep, or an inactive session cancels the preview.-The glow uses nonactivating, mouse-transparent `NSPanel` windows across Spaces and full-screen apps. System sleep, display sleep, or an inactive user session removes the windows. On return, valid state resumes according to the current time. Screen configuration changes rebuild the windows; all displays share a motion clock.+The glow uses nonactivating, mouse-transparent `NSPanel` windows across Spaces and full-screen apps. System sleep, display sleep, or an inactive user session removes the windows. On return, valid state resumes according to the current time. Screen configuration changes rebuild the windows; all displays share a motion clock. The clock calculates the cycle from segment durations and speed, preserving progress when speed changes.## Status Bar Icon@@ -222,15 +222,16 @@ The Settings window sizes to the current tab, keeps its top edge fixed, and staySwiftUI may report height before window creation finishes. `SettingsWindowController` caches the latest valid measurement and applies it once `HostingWindowController.window` is ready.-Secondary panels for main-panel layout, notifications, Automatic Reset, and sleep prevention are created on first use, then reuse their content and required height subscriptions.+Secondary panels for main-panel layout, task glow, notifications, Automatic Reset, and sleep prevention are created on first use, then reuse their content and required height subscriptions.-These four settings child panels contain interactive controls, so they use a keyable `KeyableBorderlessPanel`. The main panel's Heatmap, Reset Credits, and Task Center details use a nonactivating `NonactivatingSidePanel`. When a settings child panel closes, `SidePanelSupport.orderOut` restores focus to its parent only if that child panel is still the key window. If focus has already moved intentionally to the main panel or another window, it must not be taken back, or the newly opened interaction surface may close immediately after losing focus.+These settings child panels use a keyable `KeyableBorderlessPanel`. Opening a panel preserves focus in the Settings window; clicking a text field begins editing. Closing a panel ends native editing, and the color field validates and synchronizes its display in the end-editing callback. The main panel's Heatmap, Reset Credits, and Task Center details use a nonactivating `NonactivatingSidePanel`. When a settings child panel closes, `SidePanelSupport.orderOut` restores focus to its parent only if that child panel is still the key window. If focus has moved to another window, parent focus is not restored.When Automatic Reset or Prevent System Sleep changes from off to on, `AppSettingsView` presents a shared confirmation through `HelperFeatureConfirmation`. It combines guidance from `KeepAliveController.HelperStatus` with the feature description and writes enabled state only after user confirmation. An enabled settings row in `.requiresApproval` shows `Open System Settings`.Each secondary-settings entry uses its own availability decision:- Main Panel Layout is always available+- Task Glow requires `TaskGlowSettings.isEnabled` and Hook's `isOperable` to be `true`, with no Hook update in progress- Notifications reads `NotificationSettings.canShowOptions`- Automatic Reset requires `AutoResetSettings.isEnabled` and `KeepAliveController.helperStatus == .enabled`- Sleep prevention reads `KeepAliveController.canShowOptions`@@ -241,7 +242,7 @@ When a condition becomes false, Settings sends the corresponding `close` actionLayout sorting uses a custom `DragGesture` on the handle. A floating copy follows the pointer, other rows move when it crosses half a row, and releasing calls `setSectionOrder(_:)` once to persist the final order.-`SettingsWindowController` owns the only `UndoManager` for this window group. The Settings window exposes it through `AuxiliaryHostingWindow`, and each of the four settings child panels obtains the same instance from its parent when shown. `Command-Z` and `Command-Shift-Z` therefore operate on one layout history while focus is in either the Settings window or any child panel. Automatic Task Center changes caused by Hook state do not enter the user's undo history.+`SettingsWindowController` owns the only `UndoManager` for this window group. The Settings window exposes it through `AuxiliaryHostingWindow`, and each settings child panel obtains the same instance from its parent when shown. `Command-Z` and `Command-Shift-Z` therefore operate on one layout history while focus is in either the Settings window or any child panel. Automatic Task Center changes caused by Hook state do not enter the user's undo history.### Proxy Configuration Dialog@@ -305,8 +306,8 @@ Release scripts require Developer ID, signing, and notarization credentials and## Manual Validation Matrix- Left-click opens the main panel; right-click and Control-click open the context menu-- Enabling Task Glow plays one preview; disabling retracts and fades it out. Dismissal blocks replay, and enabling again after dismissal can preview again. Task changes during preview resume with the actual state-- During concurrent running or approval waiting, completion and termination trigger a 3-second glow indicator; consecutive endings and the end of all tasks use the correct color and expiration+- Enabling Task Glow plays one preview using the current color, speed, and brightness; disabling retracts and fades it out. Dismissal blocks replay, and enabling again after dismissal can preview again. Task changes during preview resume with the actual state+- During concurrent running or approval waiting, completion and termination trigger a 3-second glow indicator; colors follow the settings, and the selected end duration applies once all tasks end- History reloads and wake reconciliation do not replay old terminal hints; subsequent real task endings still produce hints, and motion and expiry stay aligned across displays and screen configuration changes- Menu bar symbols follow task state; terminal feedback expires 10 seconds after the task ends and is recalculated on wake- Transitions between the plain person and all four task badges complete correctly, rapid changes settle on the latest state, and toggling quota visibility stays smooth with badges; initial presentation and wake reconciliation do not animate@@ -321,7 +322,8 @@ Release scripts require Developer ID, signing, and notarization credentials and- Focus is correct when opening Settings for the first time, closing it, and reopening it- During refresh or reconnection in About, closing, minimizing, fully occluding Settings, or switching away from About stops the reconnect icon's continuous drawing or wiggle; showing it again resumes animation only if still busy, and losing focus while visible preserves normal behavior- On the first Settings open after a cold launch, General immediately uses its full content height; switching among all three tabs adapts the window height, with no scrollbar when screen space is sufficient-- Main Panel Layout, Notification, Automatic Reset, and sleep-prevention child panels remain mutually exclusive, align their top edges with their setting rows, and resize correctly when content changes+- Main Panel Layout, Task Glow, Notification, Automatic Reset, and sleep-prevention child panels remain mutually exclusive, align their top edges with their setting rows, and resize correctly when content changes+- Opening the task-glow panel does not focus a color field automatically; the six-character limit, paste filtering, and uppercase conversion work; invalid colors revert to the default on Return, focus loss, and panel dismissal, with displayed and applied colors matching- With a settings child panel open, opening the main panel from the menu bar keeps the main panel open, closes the settings child panel, and does not steal focus back to Settings- While reordering the main panel, the floating row follows the pointer, other rows make room after the drag crosses half a row, and release settles smoothly while persisting only the final order; reordering and visibility changes can be undone step by step with `Command-Z` and redone with `Command-Shift-Z` while either the Settings window or any settings child panel has focus; the result persists across relaunches; the last visible section cannot be hidden; disabling Hook turns Task Center off and disables its switch without blocking drag, enables Account if Task Center was the only visible section; re-enabling Hook shows Task Center automatically, while a manual hide survives relaunch; automatic Hook changes do not enter user undo history- Opening Settings or Logs from the context menu does not lose focusdiff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.mdindex 2efc794..3882c8c 100644--- a/Docs/en/UserGuide/settings.md+++ b/Docs/en/UserGuide/settings.md@@ -24,18 +24,20 @@ Disabling Hook hides Tasks; switching Hook from off to on shows Tasks automatica### Glow Effect-Shows task status along the top of each display. CodexBar Hook must be enabled and verified. The switch is off by default and independent of the main panel's Animation Effects setting.+Shows task status along the top of each display. CodexBar Hook must be enabled and verified. The switch is off by default and independent of the main panel's Animation Effects setting. Once enabled, click the options button to adjust status colors, animation speed, brightness, and end duration.-Turning it on plays one cyan round-trip preview, then shows actual task status. Turning it off quickly retracts the glow to the screen center and fades it out. Repeated toggles during preview playback or dismissal do not replay it; turning it on after dismissal finishes can start another preview.+Turning it on plays one round-trip preview using the current running color, speed, and brightness, then shows actual task status. Turning it off quickly retracts the glow to the screen center and fades it out. Repeated toggles during preview playback or dismissal do not replay it; turning it on after dismissal finishes can start another preview.-| Color | Meaning |+| Default color | Meaning || --- | --- || Cyan moving glow | Tasks are running || Orange pulsing glow | Waiting for approval; takes priority over running || Green | Task completed || Red | Task terminated, including interruptions |-When a task ends while others remain active, its completion or termination appears for 3 seconds before returning to the current task state. Once all tasks end, the latest ending is shown until 10 seconds after its end time.+Colors use six-digit Display P3 hexadecimal values. Letters are converted to uppercase, and empty fields show the default color as a placeholder. Invalid colors have a red border and revert to the default on Return, focus loss, or panel dismissal. Animation Speed offers Slower, Standard, and Faster, with Standard as the default. Brightness ranges from 20% to 100%, defaulting to 100%.++When a task ends while others remain active, its completion or termination appears for 3 seconds before returning to the current task state. Once all tasks end, the latest ending is shown for the selected End Duration, measured from its end time. Choices are 3, 5, 10, 15, 30, or 60 seconds; the default is 10 seconds.The glow is hidden while Hook is unavailable, preserving your switch preference. System sleep, display sleep, or an inactive user session also hides it. On return, it shows the current state without replaying expired terminal indicators.diff --git a/appcast.xml b/appcast.xmlindex 1b363db..daa66b2 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 4.0.5</title>+ <sparkle:version>105</sparkle:version>+ <sparkle:shortVersionString>4.0.5</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#4.0.5</sparkle:releaseNotesLink>+ <pubDate>Tue, 22 Sep 2026 18:30:39 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v4.0.5.dmg" sparkle:edSignature="1LP+QiJ6Ay/biCUfS+xzl2UTibj4Z4juM2RxCbuyAeQEYnCXiztHZp0QcemkPilUsxa+jcOymgvIZGMrmUNABw==" length="8369664" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 4.0.4</title><sparkle:version>104</sparkle:version>