Skip to content

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

fix: 修正多 Agent 任务状态并补充回归测试

Bob4aee4b933af8
diff --git a/.gitignore b/.gitignore
index 1c8bc82..de81f0b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,6 +6,7 @@ DerivedData/
Build/
*.xcarchive
*.xcresult
+*.profraw
*.dSYM
*.moved-aside
diff --git a/.swiftlint.yml b/.swiftlint.yml
index af0398a..4bdfdcb 100644
--- a/.swiftlint.yml
+++ b/.swiftlint.yml
@@ -1,5 +1,6 @@
included:
- CodexBar
+ - CodexBarTests
line_length:
warning: 180
diff --git a/AGENTS.md b/AGENTS.md
index f1321aa..5444dc1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,13 +2,14 @@
## 项目结构与模块组织
-CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVVM。工程只有 `CodexBar` scheme,包含主 App 与 `CodexBarHelper` 两个 target。
+CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVVM。工程只有 `CodexBar` scheme,包含主 App、`CodexBarHelper` 和 `CodexBarTests` 三个 target。
`CodexBar/` 按 `App/` `Views/` `Controllers/` `Models/` `Services/` 和 `Resources/` 分层。root LaunchDaemon 位于 `CodexBarHelper/` 目录,跨 target XPC 接口位于 `Shared/` 目录。`Scripts/` 提供发布和 helper 清理工具,`Images/` 存放 README 资源。
## 构建、测试与开发命令
- `xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build` 执行代码变更后的构建验证
+- `xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' test` 执行无宿主单元测试
- `swiftformat .` 按 `.swiftformat` 格式化全部 Swift,使用 Swift 6 和 4 空格缩进
- `swiftlint` 按 `.swiftlint.yml` 检查
- `/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact` 查看系统日志,Debug 版 subsystem 带 `.debug` 后缀
@@ -71,7 +72,9 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,
## 测试规范
-仓库没有 XCTest target 或覆盖率门槛。每次改动至少应完成构建,运行 `swiftformat` 和 `swiftlint` 两项检查,并手动验证受影响流程。菜单、窗口焦点、Hook、同步、通知和防睡眠改动必须说明手动验证场景。Debug 与 Release 使用不同 App 和 helper bundle ID,排查时不要混用。
+`CodexBarTests` 使用 Swift Testing,无 App 宿主,直接编译 `CodexBar/` 与 `Shared/` 源码。测试 target 独有的 `CODEXBAR_TESTING` 条件只移除 `@main`,不启动 App、Codex、CloudKit 或 helper。文件测试使用独立临时目录,偏好测试使用独立 `UserDefaults` suite,禁止读写真实用户数据。仓库没有覆盖率门槛。
+
+每次代码改动至少应完成构建和单元测试,运行 `swiftformat` 和 `swiftlint` 两项检查,并手动验证受影响流程。菜单、窗口焦点、Hook、同步、通知和防睡眠改动必须说明手动验证场景。Debug 与 Release 使用不同 App 和 helper bundle ID,排查时不要混用。
## Git 规范
diff --git a/CLAUDE.md b/CLAUDE.md
index 2ae4354..916eff7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6,9 +6,9 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## 项目概述
-CodexBar 是一个 macOS 菜单栏应用,以 `LSUIElement` 方式运行,没有 Dock 图标,展示本机 Codex 的账号状态、额度、Token 用量、实时任务和工作流统计。技术栈为 Swift 6 + SwiftUI + AppKit + MVVM,唯一外部依赖是 Sparkle `2.9.6+`(SwiftPM)。最低系统版本为 macOS `15.0`
+CodexBar 是一个 macOS 菜单栏应用,以 `LSUIElement` 方式运行,没有 Dock 图标,展示本机 Codex 的账号状态、额度、Token 用量、实时任务和工作流统计。技术栈为 Swift 6 + SwiftUI + AppKit + MVVM,唯一外部依赖是 Sparkle `2.10.0+`(SwiftPM)。最低系统版本为 macOS `15.0`
-Xcode 工程有两个 target:主 App `CodexBar` 和随 App 嵌入的 root helper `CodexBarHelper`(command-line tool + LaunchDaemon)。**没有测试 target**,验证依靠构建通过和实际运行。
+Xcode 工程有三个 target:主 App `CodexBar`、随 App 嵌入的 root helper `CodexBarHelper`(command-line tool + LaunchDaemon),以及使用 Swift Testing 的无宿主单元测试 `CodexBarTests`。测试直接编译 App 与 `Shared/` 源码,通过测试 target 独有的 `CODEXBAR_TESTING` 条件移除可执行入口。
App Sandbox 未开启,entitlements 只声明 iCloud/CloudKit,因为需要启动本机 `codex` 进程、读取用户 Codex 登录状态、写入用户级 Hook 配置。
@@ -18,10 +18,13 @@ App Sandbox 未开启,entitlements 只声明 iCloud/CloudKit,因为需要启
# 日常编译验证 (唯一 scheme 是 CodexBar)
xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
+# 单元测试: 使用独立临时目录和 UserDefaults suite
+xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' test
+
# 格式化: 配置在 .swiftformat, 覆盖整个仓库 (Swift 6 语言模式, 4 空格缩进)
swiftformat .
-# Lint: 配置在 .swiftlint.yml, included 只有 CodexBar/
+# Lint: 配置在 .swiftlint.yml, included 包含 CodexBar/ 和 CodexBarTests/
# 即 Shared/ CodexBarHelper/ Scripts/ 不在 lint 范围内
swiftlint
@@ -99,10 +102,10 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
`CodexActivityMonitor` 为菜单栏、活动卡片、任务流光、通知、触觉反馈和防睡眠提供统一任务状态,由两个 reader 读取数据。
-- `HookEventTailReader`(actor)的 bootstrap 覆盖滚动 24 小时并作为单次事务发送,之后按当日文件 offset 增量 tail,同时向下游报告数据源健康状态
-- `CodexSessionLifecycleReader`(actor)增量读取 `~/.codex/sessions` 与 `archived_sessions` 下的 rollout JSONL,只提取 turn 生命周期与最近进展时间,不解码会话或工具内容
+- `HookEventTailReader`(actor)的 bootstrap 覆盖滚动 24 小时并作为单次事务发送,之后按窗口内各日期文件的 offset 增量 tail,同时向下游报告数据源健康状态
+- `CodexSessionLifecycleReader`(actor)增量读取 Codex 目录中 `sessions` 与 `archived_sessions` 下的 rollout JSONL,提取线程归属、turn 生命周期、执行进展和审批上下文,不解码会话或工具内容
- 任务监控只在 `codexHookSettings.isOperable` 为 `true` 时运行,即本地已安装且最近一次明确校验没有失败;链路失效时立即停 reader 并清空实时状态
-- `Stop` 保留正在收尾的任务,rollout 确认后才记录完成;`Interrupt` 结束匹配轮次;新 turn 或 `SessionEnd` 将旧任务移入 5 秒终态确认窗口。来源过滤、终态去重和恢复规则见 [实时任务监控](Docs/DeveloperGuide/activity-monitor.md)
+- `Stop` 保留正在收尾的任务,其他 Agent 等待审批时优先展示等待;rollout 确认后才记录完成。`Interrupt` 结束匹配轮次;新 turn 或 `SessionEnd` 将旧任务移出活动列表,前 5 秒快速查询终态,之后每 30 秒补查,最长保留 24 小时。审批归属、来源过滤和恢复规则见 [实时任务监控](Docs/DeveloperGuide/activity-monitor.md)
- `HookEventTailReader.drainNow()` 是读取屏障,每个调用方等待一轮在本次请求之后开始的读取,返回 `completed`、`sourceUnavailable` 或 `cancelled`
- 缺少 session ID 的 Hook 事件使用匿名 project key,`isAnonymous` 会保留到活动快照、完成记录和终止记录;活动卡片和任务中心显示橙色 `person.crop.circle.dashed` 图标,`help` 为 `匿名任务不参与防睡眠`,`+N` 只显示其他活跃任务总数
- 匿名任务不向通知消费者发布等待或完成 transition,不触发触觉反馈,不参与 KeepAlive 或异常会话保护,`activityProtectionIdentifier` 为 `nil`
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index a2fbb24..011fa96 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -9,6 +9,7 @@
/* Begin PBXBuildFile section */
B10000000000000000000005 /* CodexBarHelper in Embed CodexBar Helper */ = {isa = PBXBuildFile; fileRef = B10000000000000000000014 /* CodexBarHelper */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
C42A52F12FDACDEC004A2B53 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = C42A52F02FDACDEC004A2B53 /* Sparkle */; };
+ D10000000000000000000001 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = C42A52F02FDACDEC004A2B53 /* Sparkle */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -45,6 +46,7 @@
B10000000000000000000014 /* CodexBarHelper */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CodexBarHelper; sourceTree = BUILT_PRODUCTS_DIR; };
C449FB5030203E0000ED2123 /* Version.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Version.xcconfig; sourceTree = "<group>"; };
C4A0FD952FD9302E000263A7 /* CodexBar Debug.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "CodexBar Debug.app"; sourceTree = BUILT_PRODUCTS_DIR; };
+ D10000000000000000000002 /* CodexBarTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CodexBarTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
@@ -55,6 +57,14 @@
);
target = C4A0FD942FD9302E000263A7 /* CodexBar */;
};
+ D10000000000000000000003 /* Exceptions for "CodexBar" folder in "CodexBarTests" target */ = {
+ isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
+ membershipExceptions = (
+ Resources/AppIcon.icon,
+ Resources/Info.plist,
+ );
+ target = D10000000000000000000010 /* CodexBarTests */;
+ };
/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedGroupBuildPhaseMembershipExceptionSet section */
@@ -72,6 +82,7 @@
9E664A4C2FDD47530016B96E /* CodexBar */ = {
isa = PBXFileSystemSynchronizedRootGroup;
exceptions = (
+ D10000000000000000000003 /* Exceptions for "CodexBar" folder in "CodexBarTests" target */,
9E664A582FDD47540016B96E /* Exceptions for "CodexBar" folder in "CodexBar" target */,
);
path = CodexBar;
@@ -90,6 +101,11 @@
path = Shared;
sourceTree = "<group>";
};
+ D10000000000000000000004 /* CodexBarTests */ = {
+ isa = PBXFileSystemSynchronizedRootGroup;
+ path = CodexBarTests;
+ sourceTree = "<group>";
+ };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
@@ -104,6 +120,12 @@
C42A52F12FDACDEC004A2B53 /* Sparkle in Frameworks */,
);
};
+ D10000000000000000000005 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ files = (
+ D10000000000000000000001 /* Sparkle in Frameworks */,
+ );
+ };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -119,6 +141,7 @@
isa = PBXGroup;
children = (
9E664A4C2FDD47530016B96E /* CodexBar */,
+ D10000000000000000000004 /* CodexBarTests */,
C449FB4E30203A1100ED2123 /* Shared */,
C449FB3A3020367500ED2123 /* CodexBarHelper */,
C449FB5130203E0000ED2123 /* Config */,
@@ -130,6 +153,7 @@
isa = PBXGroup;
children = (
C4A0FD952FD9302E000263A7 /* CodexBar Debug.app */,
+ D10000000000000000000002 /* CodexBarTests.xctest */,
B10000000000000000000014 /* CodexBarHelper */,
);
name = Products;
@@ -183,6 +207,29 @@
productReference = C4A0FD952FD9302E000263A7 /* CodexBar Debug.app */;
productType = "com.apple.product-type.application";
};
+ D10000000000000000000010 /* CodexBarTests */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = D10000000000000000000011 /* Build configuration list for PBXNativeTarget "CodexBarTests" */;
+ buildPhases = (
+ D10000000000000000000006 /* Sources */,
+ D10000000000000000000005 /* Frameworks */,
+ D10000000000000000000007 /* Resources */,
+ );
+ buildRules = (
+ );
+ fileSystemSynchronizedGroups = (
+ 9E664A4C2FDD47530016B96E /* CodexBar */,
+ C449FB4E30203A1100ED2123 /* Shared */,
+ D10000000000000000000004 /* CodexBarTests */,
+ );
+ name = CodexBarTests;
+ packageProductDependencies = (
+ C42A52F02FDACDEC004A2B53 /* Sparkle */,
+ );
+ productName = CodexBarTests;
+ productReference = D10000000000000000000002 /* CodexBarTests.xctest */;
+ productType = "com.apple.product-type.bundle.unit-test";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -219,6 +266,7 @@
projectDirPath = "";
projectRoot = "";
targets = (
+ D10000000000000000000010 /* CodexBarTests */,
C4A0FD942FD9302E000263A7 /* CodexBar */,
B10000000000000000000031 /* CodexBarHelper */,
);
@@ -231,6 +279,11 @@
files = (
);
};
+ D10000000000000000000007 /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ files = (
+ );
+ };
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -244,6 +297,11 @@
files = (
);
};
+ D10000000000000000000006 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ files = (
+ );
+ };
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
@@ -482,6 +540,50 @@
};
name = Release;
};
+ D10000000000000000000012 /* Debug configuration for PBXNativeTarget "CodexBarTests" */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ CODE_SIGN_STYLE = Automatic;
+ ENABLE_APP_SANDBOX = NO;
+ GENERATE_INFOPLIST_FILE = YES;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@loader_path/../Frameworks",
+ "@executable_path/../Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.tests;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SKIP_INSTALL = YES;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) CODEXBAR_TESTING";
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
+ SWIFT_EMIT_LOC_STRINGS = NO;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
+ };
+ name = Debug;
+ };
+ D10000000000000000000013 /* Release configuration for PBXNativeTarget "CodexBarTests" */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ CODE_SIGN_STYLE = Automatic;
+ ENABLE_APP_SANDBOX = NO;
+ GENERATE_INFOPLIST_FILE = YES;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@loader_path/../Frameworks",
+ "@executable_path/../Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.tests;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SKIP_INSTALL = YES;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) CODEXBAR_TESTING";
+ SWIFT_APPROACHABLE_CONCURRENCY = YES;
+ SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
+ SWIFT_EMIT_LOC_STRINGS = NO;
+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
+ };
+ name = Release;
+ };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -509,6 +611,14 @@
);
defaultConfigurationName = Release;
};
+ D10000000000000000000011 /* Build configuration list for PBXNativeTarget "CodexBarTests" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ D10000000000000000000012 /* Debug configuration for PBXNativeTarget "CodexBarTests" */,
+ D10000000000000000000013 /* Release configuration for PBXNativeTarget "CodexBarTests" */,
+ );
+ defaultConfigurationName = Release;
+ };
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
@@ -517,7 +627,7 @@
repositoryURL = "https://github.com/sparkle-project/Sparkle";
requirement = {
kind = upToNextMajorVersion;
- minimumVersion = 2.9.6;
+ minimumVersion = 2.10.0;
};
};
/* End XCRemoteSwiftPackageReference section */
diff --git a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme
index 7237ed6..28ee613 100644
--- a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme
+++ b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme
@@ -8,7 +8,7 @@
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
- buildForTesting = "YES"
+ buildForTesting = "NO"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
@@ -29,6 +29,19 @@
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
+ <Testables>
+ <TestableReference
+ skipped = "NO"
+ parallelizable = "NO">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "D10000000000000000000010"
+ BuildableName = "CodexBarTests.xctest"
+ BlueprintName = "CodexBarTests"
+ ReferencedContainer = "container:CodexBar.xcodeproj">
+ </BuildableReference>
+ </TestableReference>
+ </Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swift
index 931a592..058c6fa 100644
--- a/CodexBar/App/CodexBarApp.swift
+++ b/CodexBar/App/CodexBarApp.swift
@@ -2,8 +2,11 @@ import AppKit
import Darwin
import SwiftUI
+// 无宿主测试编译同一份源码, 仅移除可执行入口以避免启动常驻服务
+#if !CODEXBAR_TESTING
+ @main
+#endif
/// 应用入口; Hook 子进程模式会在初始化阶段记录事件并退出
-@main
struct CodexBarApp: App {
@NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegate
diff --git a/CodexBar/Controllers/TaskGlowController.swift b/CodexBar/Controllers/TaskGlowController.swift
index 6cabb75..a299853 100644
--- a/CodexBar/Controllers/TaskGlowController.swift
+++ b/CodexBar/Controllers/TaskGlowController.swift
@@ -16,6 +16,8 @@ final class TaskGlowController {
private var expirationTask: Task<Void, Never>?
private var scheduledExpiration: Date?
private var hidePanelsTask: Task<Void, Never>?
+ private var previewTask: Task<Void, Never>?
+ private var isPreviewVisible = false
private var isSystemSleeping = false
private var isDisplaySleeping = false
private var isSessionActive = true
@@ -33,6 +35,7 @@ final class TaskGlowController {
deinit {
expirationTask?.cancel()
hidePanelsTask?.cancel()
+ previewTask?.cancel()
}
func start() {
@@ -44,11 +47,21 @@ final class TaskGlowController {
)
.sink { [weak self] enabled, hookEnabled, hookVerified in
guard let self else { return }
+ if !hookEnabled || !hookVerified {
+ cancelPreview()
+ }
+ if !enabled {
+ isPreviewVisible = false
+ }
isEnabled = enabled && hookEnabled && hookVerified
consume(CodexActivityPresentationUpdate(snapshot: activityMonitor.snapshot, terminalEvents: []))
}
.store(in: &cancellables)
+ settings.previewRequests
+ .sink { [weak self] in self?.previewEnabled() }
+ .store(in: &cancellables)
+
activityMonitor.presentationPublisher
.sink { [weak self] update in self?.consume(update) }
.store(in: &cancellables)
@@ -81,11 +94,41 @@ final class TaskGlowController {
expirationTask?.cancel()
expirationTask = nil
scheduledExpiration = nil
+ cancelPreview()
presentation = TaskGlowPresentationState()
isEnabled = false
removePanels()
}
+ private func previewEnabled() {
+ guard previewTask == nil, hidePanelsTask == nil, isEnabled, hookSettings.isOperable,
+ !isSystemSleeping, !isDisplaySleeping, isSessionActive else { return }
+ // 播放和收尾期间不重播, 提前关闭时由实际收尾完成释放预览
+ removePanels()
+ isPreviewVisible = true
+ motionClock.setRunning(true)
+ let startTime = motionClock.startTime()
+ previewTask = Task { @MainActor [weak self] in
+ do {
+ let remaining = max(0, startTime + TaskGlowMotionClock.cycleDuration - CACurrentMediaTime())
+ try await Task.sleep(for: .seconds(remaining))
+ } catch {
+ return
+ }
+ guard let self, !Task.isCancelled else { return }
+ previewTask = nil
+ isPreviewVisible = false
+ refreshPresentation()
+ }
+ updatePanels()
+ }
+
+ private func cancelPreview() {
+ previewTask?.cancel()
+ previewTask = nil
+ isPreviewVisible = false
+ }
+
private func consume(_ update: CodexActivityPresentationUpdate) {
presentation.update(
snapshot: update.snapshot,
@@ -136,23 +179,27 @@ final class TaskGlowController {
private func updatePanels() {
guard !isSystemSleeping, !isDisplaySleeping, isSessionActive else {
+ cancelPreview()
removePanels()
return
}
- let state = presentation.state
+ let state: TaskGlowState = isPreviewVisible ? .running : presentation.state
motionClock.setRunning(state == .running)
if state == .hidden {
- guard !panels.isEmpty, hidePanelsTask == nil else { return }
+ guard !panels.isEmpty else {
+ cancelPreview()
+ return
+ }
+ guard hidePanelsTask == nil else { return }
for panel in panels {
panel.indicatorView.update(state: .hidden)
}
- hidePanelsTask = Task { @MainActor [weak self] in
- do {
- try await Task.sleep(for: .seconds(TaskGlowView.dismissalDuration))
- } catch {
- return
+ hidePanelsTask = Task { @MainActor [weak self, closingPanels = panels] in
+ for panel in closingPanels {
+ guard await panel.indicatorView.waitForDismissal() else { return }
}
- guard let self, !Task.isCancelled, presentation.state == .hidden else { return }
+ guard let self, !Task.isCancelled, !isPreviewVisible, presentation.state == .hidden else { return }
+ cancelPreview()
removePanels()
}
return
@@ -163,7 +210,11 @@ final class TaskGlowController {
panels = NSScreen.screens.map { TaskGlowPanel(screen: $0, motionClock: motionClock) }
}
for panel in panels {
- panel.indicatorView.update(state: state, terminalPresentation: presentation.terminal)
+ panel.indicatorView.update(
+ state: state,
+ terminalPresentation: isPreviewVisible ? nil : presentation.terminal,
+ repeatsMotion: !isPreviewVisible
+ )
if !panel.isVisible {
panel.orderFrontRegardless()
}
@@ -321,6 +372,7 @@ private final class TaskGlowMotionClock {
static let travelDuration = 2.0
static let offscreenDuration = 0.2
static let centerRetractionDuration = 0.3
+ static let cycleDuration = travelDuration + offscreenDuration * 2 + centerRetractionDuration
private var isRunning = false
private var startedAt: CFTimeInterval?
@@ -392,7 +444,6 @@ private final class TaskGlowView: NSView {
private var lightSegments: [CAShapeLayer] = []
static let visibilityDuration = 0.24
private static let edgeTraversalDuration = 0.7
- static let dismissalDuration = edgeTraversalDuration / 2 + visibilityDuration
private static let segmentsPerSide = 32
private static let stationaryColorAlpha: CGFloat = 0.9
private let convergencePoint = 0.5
@@ -401,6 +452,7 @@ private final class TaskGlowView: NSView {
private var terminalPresentation: TaskGlowTerminalPresentation?
private var contentState: TaskGlowState?
private var transitionTask: Task<Void, Never>?
+ private var repeatsMotion = true
init(
geometry: TaskGlowGeometry,
@@ -443,8 +495,9 @@ private final class TaskGlowView: NSView {
fatalError("init(coder:) has not been implemented")
}
- func update(state: TaskGlowState, terminalPresentation: TaskGlowTerminalPresentation? = nil) {
- guard presentationState != state || self.terminalPresentation != terminalPresentation else { return }
+ func update(state: TaskGlowState, terminalPresentation: TaskGlowTerminalPresentation? = nil, repeatsMotion: Bool = true) {
+ guard presentationState != state || self.terminalPresentation != terminalPresentation || self.repeatsMotion != repeatsMotion else { return }
+ let continuesRunning = presentationState == .running && state == .running
let continuesTerminal = presentationState == state && self.terminalPresentation != nil && terminalPresentation != nil
// 同色提示延长时保留尚未完成的展开, 收尾会读取最新的淡出期限
if continuesTerminal, transitionTask != nil {
@@ -455,15 +508,18 @@ private final class TaskGlowView: NSView {
let hasArtwork = contentState != nil && (layer?.presentation()?.opacity ?? layer?.opacity ?? 0) > 0.001
presentationState = state
self.terminalPresentation = terminalPresentation
+ self.repeatsMotion = repeatsMotion
transitionTask?.cancel()
transitionTask = nil
freezeArtwork()
if state != .hidden {
contentState = state
+ animateVisibility(to: 1)
}
- if state != .hidden {
- animateVisibility(to: 1)
+ if continuesRunning {
+ showStable(.running)
+ return
}
if let terminalOpacity {
@@ -488,6 +544,8 @@ private final class TaskGlowView: NSView {
if state == .hidden {
contentState = nil
animateVisibility(to: 0)
+ try await Task.sleep(for: .seconds(Self.visibilityDuration))
+ try Task.checkCancellation()
} else {
if hasArtwork {
try await Task.sleep(for: .seconds(0.06))
@@ -511,6 +569,12 @@ private final class TaskGlowView: NSView {
}
}
+ /// 面板等待实际收回和淡出结束, 不用独立计时器提前移除仍可见的光带
+ func waitForDismissal() async -> Bool {
+ await transitionTask?.value
+ return !Task.isCancelled && presentationState == .hidden && transitionTask == nil
+ }
+
func stopAnimating() {
transitionTask?.cancel()
transitionTask = nil
@@ -741,9 +805,9 @@ private final class TaskGlowView: NSView {
// 每个单程独立缓入缓出, 保证两端掉头都平滑
let travel = CAAnimationGroup()
travel.animations = [outward, inward]
- travel.duration = outwardDuration + inwardDuration
+ travel.duration = TaskGlowMotionClock.cycleDuration
travel.beginTime = segment.convertTime(startTime, from: nil)
- travel.repeatCount = .infinity
+ travel.repeatCount = repeatsMotion ? .infinity : 0
segment.add(travel, forKey: "emission")
}
diff --git a/CodexBar/Services/Settings/TaskGlowSettings.swift b/CodexBar/Services/Settings/TaskGlowSettings.swift
index e2479e7..9ba5aa3 100644
--- a/CodexBar/Services/Settings/TaskGlowSettings.swift
+++ b/CodexBar/Services/Settings/TaskGlowSettings.swift
@@ -5,7 +5,12 @@ import Foundation
final class TaskGlowSettings: ObservableObject {
@Published private(set) var isEnabled: Bool
+ var previewRequests: AnyPublisher<Void, Never> {
+ previewSubject.eraseToAnyPublisher()
+ }
+
private let defaults: UserDefaults
+ private let previewSubject = PassthroughSubject<Void, Never>()
private static let enabledKey = "TaskGlow.isEnabled"
init(defaults: UserDefaults = .standard) {
@@ -24,5 +29,8 @@ final class TaskGlowSettings: ObservableObject {
guard enabled != isEnabled else { return }
defaults.set(enabled, forKey: Self.enabledKey)
isEnabled = enabled
+ if enabled {
+ previewSubject.send()
+ }
}
}
diff --git a/CodexBar/Services/Workflow/ActivityProtectionStateStore.swift b/CodexBar/Services/Workflow/ActivityProtectionStateStore.swift
index 5494c44..6f87b17 100644
--- a/CodexBar/Services/Workflow/ActivityProtectionStateStore.swift
+++ b/CodexBar/Services/Workflow/ActivityProtectionStateStore.swift
@@ -26,7 +26,7 @@ actor ActivityProtectionStateStore {
private let lockURL: URL
private let fileManager: FileManager
- init(fileManager: FileManager = .default) {
+ init(directoryURL: URL? = nil, fileManager: FileManager = .default) {
self.fileManager = fileManager
let applicationSupportURL = fileManager.urls(
for: .applicationSupportDirectory,
@@ -34,11 +34,11 @@ actor ActivityProtectionStateStore {
).first ?? URL(fileURLWithPath: NSHomeDirectory())
.appendingPathComponent("Library", isDirectory: true)
.appendingPathComponent("Application Support", isDirectory: true)
- directoryURL = applicationSupportURL
+ self.directoryURL = directoryURL ?? applicationSupportURL
.appendingPathComponent("CodexBar", isDirectory: true)
.appendingPathComponent("ActivityProtection", isDirectory: true)
- stateURL = directoryURL.appendingPathComponent("state.json", isDirectory: false)
- lockURL = directoryURL.appendingPathComponent("state.lock", isDirectory: false)
+ stateURL = self.directoryURL.appendingPathComponent("state.json", isDirectory: false)
+ lockURL = self.directoryURL.appendingPathComponent("state.lock", isDirectory: false)
}
func load(now: Date = Date()) -> [String: ActivityProtectionRecord] {
diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
index d39a6db..f2b213c 100644
--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift
+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift
@@ -28,6 +28,8 @@ final class CodexActivityMonitor: ObservableObject {
var pendingTerminalPresentationEvents: [CodexActivityTerminalEvent] = []
var terminalPresentationNotBefore = Date()
var tasks: [CodexActivityTaskKey: CodexActivityTask] = [:]
+ var subagentTurnLinks: [CodexActivityTurnReference: CodexActivityTaskKey] = [:]
+ var pendingSubagentEvents: [CodexPendingSubagentEvent] = []
var pendingTerminalTasks: [CodexActivityTaskKey: PendingTerminalTask] = [:]
var completions: [CodexActivityCompletion] = []
var terminations: [CodexActivityTermination] = []
@@ -353,14 +355,7 @@ final class CodexActivityMonitor: ObservableObject {
return true
}
- if let approvalReviewer = state.approvalReviewer,
- state.readStatus == .complete,
- let observedAt = state.contextObservedAt,
- observedAt >= (task.approvalContextObservedAt ?? .distantPast),
- task.approvalReviewer != approvalReviewer {
- task.approvalReviewer = approvalReviewer
- task.approvalContextObservedAt = observedAt
- }
+ task.mergeExecutionLifecycle(state, owner: CodexActivityExecutionKey(agentId: nil, turnId: state.turnId))
let wasSuppressedBeforeApproval = task.state == .suppressed
if resolvePendingApprovalIfPossible(
@@ -383,7 +378,7 @@ final class CodexActivityMonitor: ObservableObject {
return true
}
- private func mergeLifecycleProgress(
+ func mergeLifecycleProgress(
from state: CodexSessionTaskLifecycleState,
key: CodexActivityTaskKey,
into task: inout CodexActivityTask
@@ -447,6 +442,7 @@ final class CodexActivityMonitor: ObservableObject {
private func lifecycleReferences(now: Date, includeAll: Bool) -> [CodexActivityTurnReference] {
var references = tasks.values.compactMap(\.turnReference)
+ references.append(contentsOf: subagentLifecycleReferences())
let due = pendingTerminalTasks.filter { includeAll || $0.value.nextPollAt <= now }
.sorted { $0.value.nextPollAt < $1.value.nextPollAt }
for (key, var pending) in due.prefix(16) {
@@ -483,13 +479,21 @@ final class CodexActivityMonitor: ObservableObject {
var didChange = false
var transitions: [CodexActivityTransition] = []
for state in states {
+ didChange = applySubagentLifecycle(state, terminalOnly: terminalOnly, into: &transitions) || didChange
didChange = applyLifecycleState(state, terminalOnly: terminalOnly, into: &transitions) || didChange
}
+ if !terminalOnly {
+ didChange = replayAssociatedSubagentEvents(into: &transitions) || didChange
+ }
if didChange {
refreshSnapshot(now: Date())
}
if canPublishActivityTransitions {
for transition in transitions {
+ if case let .waitingApproval(snapshot) = transition,
+ !tasks.values.contains(where: { $0.displayID == snapshot.id && $0.state == .waitingApproval }) {
+ continue
+ }
transitionSubject.send(transition)
}
}
@@ -692,17 +696,21 @@ final class CodexActivityMonitor: ObservableObject {
}
}
- private func apply(
+ func apply(
_ event: WorkflowHookEvent,
source: CodexActivityEventSource
) -> CodexActivityTaskKey? {
- guard !shouldIgnoreForActivity(event, source: source) else {
+ guard let event = activityEvent(from: event, source: source) else {
return nil
}
+ if deferUnassociatedSubagentEvent(event, source: source) {
+ return nil
+ }
let isTopLevelEvent = event.agentId == nil
switch event.hookEvent {
case .userPromptSubmit:
+ guard isTopLevelEvent else { return nil }
startTask(from: event, source: source)
case .preToolUse:
resumeTask(
@@ -750,6 +758,7 @@ final class CodexActivityMonitor: ObservableObject {
}
interruptTask(from: event, source: source)
case .sessionEnd:
+ guard isTopLevelEvent else { return nil }
terminateSession(from: event)
case .sessionStart, .none:
break
@@ -786,7 +795,7 @@ final class CodexActivityMonitor: ObservableObject {
return
}
}
- if let existing = tasks[key], event.timestamp < existing.lastHookEventAt {
+ if let existing = tasks[key], event.timestamp < existing.lastMainHookEventAt {
return
}
@@ -794,7 +803,7 @@ final class CodexActivityMonitor: ObservableObject {
// 同一 session 的 turn 按顺序执行. 新 prompt 让旧 turn 立即退出活动列表
// 但保留短暂终态确认窗口, 避免把迟到的正常完成误记为终止
guard !tasks.values.contains(where: {
- $0.key.sessionId == sessionId && $0.lastHookEventAt > event.timestamp
+ $0.key.sessionId == sessionId && $0.lastMainHookEventAt > event.timestamp
}) else {
return
}
@@ -828,6 +837,10 @@ final class CodexActivityMonitor: ObservableObject {
recentlyEndedTaskAt.removeValue(forKey: .session(sessionId))
}
+ if resumePromptInSameTurn(from: event, existing: existingTask) {
+ return
+ }
+
var task = CodexActivityTask(
displayID: displayID,
key: key,
@@ -837,9 +850,7 @@ final class CodexActivityMonitor: ObservableObject {
startedAt: event.timestamp,
progressGeneration: (existingTask?.progressGeneration ?? 0) &+ 1
)
- if let existingTask {
- task.lastProgressAt = max(task.lastProgressAt, existingTask.lastProgressAt)
- }
+ task.lastProgressAt = max(task.lastProgressAt, existingTask?.lastProgressAt ?? .distantPast)
tasks[key] = task
}
@@ -859,17 +870,12 @@ final class CodexActivityMonitor: ObservableObject {
pendingTerminalTasks[key] == nil else {
return
}
- guard event.timestamp >= task.lastHookEventAt else {
+ guard task.acceptsExecutionEvent(event) else {
return
}
let wasSuppressed = task.state == .suppressed
- if task.state != .running {
- task.state = .running
- task.stateChangedAt = event.timestamp
- }
- task.pendingApprovalRequestedAt = nil
- task.latestEvent = latestEvent
+ task.resumeExecution(from: event, latestEvent: latestEvent)
task.mergeMetadata(from: event)
task.recordHookEvent(at: event.timestamp)
tasks[key] = task
@@ -921,7 +927,7 @@ final class CodexActivityMonitor: ObservableObject {
return
}
- // 子 Agent 只能按 session 关联父任务, 忽略上一 turn 延迟到达的事件
+ // 归属已精确关联, 仍拒绝早于根任务起点的事件
if let startedAt = task.startedAt, event.timestamp < startedAt {
return
}
@@ -929,25 +935,17 @@ final class CodexActivityMonitor: ObservableObject {
task.recordSubagentActivity(
agentId: event.agentId,
isStarting: isStarting,
+ hasEnded: task.executions[task.executionKey(for: event)]?.isTerminal == true,
at: event.timestamp
)
- if event.timestamp >= task.lastHookEventAt {
+ if task.acceptsExecutionEvent(event) {
let wasSuppressed = task.state == .suppressed
- if task.state != .running {
- task.state = .running
- task.stateChangedAt = event.timestamp
- }
- task.pendingApprovalRequestedAt = nil
- task.latestEvent = isStarting ? .subagentStarted : .subagentFinished
+ task.resumeExecution(from: event, latestEvent: isStarting ? .subagentStarted : .subagentFinished)
task.mergeMetadata(from: event)
task.recordHookEvent(at: event.timestamp)
if wasSuppressed || source == .live {
- clearActivityProtection(
- for: key,
- taskID: task.displayID,
- reason: .progress
- )
+ clearActivityProtection(for: key, taskID: task.displayID, reason: .progress)
}
}
tasks[key] = task
@@ -967,7 +965,7 @@ final class CodexActivityMonitor: ObservableObject {
pendingTerminalTasks[key] == nil else {
return nil
}
- guard event.timestamp >= task.lastHookEventAt else {
+ guard task.acceptsExecutionEvent(event) else {
return nil
}
@@ -976,7 +974,7 @@ final class CodexActivityMonitor: ObservableObject {
// 权限事件描述当前请求; 缺失工具名时不能沿用上一条工具事件
task.toolName = event.toolName
task.recordHookEvent(at: event.timestamp)
- let enteredWaiting = task.recordApprovalRequest(at: event.timestamp)
+ let enteredWaiting = task.recordApprovalRequest(from: event)
tasks[key] = task
if wasSuppressed || source == .live {
clearActivityProtection(
@@ -1004,7 +1002,7 @@ final class CodexActivityMonitor: ObservableObject {
startedAt: nil,
progressGeneration: 1
)
- let enteredWaiting = task.recordApprovalRequest(at: event.timestamp)
+ let enteredWaiting = task.recordApprovalRequest(from: event)
tasks[eventKey] = task
if source == .live {
clearActivityProtection(
@@ -1030,7 +1028,7 @@ final class CodexActivityMonitor: ObservableObject {
AppLog.activity.error("任务终态已延后: reason=ambiguousStop")
case let .pending(key):
guard var pending = pendingTerminalTasks[key],
- event.timestamp >= pending.task.lastHookEventAt else {
+ event.timestamp >= pending.task.lastMainHookEventAt else {
return
}
// 新 turn 或 SessionEnd 已确定旧任务退出活动列表, Stop 不恢复它或重置 grace
@@ -1073,7 +1071,7 @@ final class CodexActivityMonitor: ObservableObject {
let deadline = Date().addingTimeInterval(Self.supersededTerminalGracePeriod)
let matchingPendingTasks = pendingTerminalTasks.filter { key, pending in
- key.sessionId == sessionId && pending.task.lastHookEventAt <= event.timestamp
+ key.sessionId == sessionId && pending.task.lastMainHookEventAt <= event.timestamp
}
for (key, pending) in matchingPendingTasks {
pendingTerminalTasks[key] = PendingTerminalTask(
@@ -1084,7 +1082,7 @@ final class CodexActivityMonitor: ObservableObject {
}
let matchingActiveTasks = tasks.filter { key, task in
- key.sessionId == sessionId && task.lastHookEventAt <= event.timestamp
+ key.sessionId == sessionId && task.lastMainHookEventAt <= event.timestamp
}
for (key, task) in matchingActiveTasks {
tasks.removeValue(forKey: key)
@@ -1129,21 +1127,6 @@ final class CodexActivityMonitor: ObservableObject {
return tasks[anonymousKey] == nil ? nil : anonymousKey
}
- /// 子 Agent 的 turn_id 属于它自己, 只能在没有待确认旧 turn 时关联同 session 唯一父任务
- private func matchingSubagentParentTaskKey(
- for event: WorkflowHookEvent
- ) -> CodexActivityTaskKey? {
- guard let sessionId = event.sessionId else { return nil }
- let candidates = tasks.values.filter { $0.key.sessionId == sessionId }
- guard candidates.count == 1 else { return nil }
- if pendingTerminalTasks.values.contains(where: { $0.task.key.sessionId == sessionId }),
- event.hookEvent != .subagentStart,
- event.agentId.flatMap({ candidates[0].subagentsByID[$0] }) == nil {
- return nil
- }
- return candidates[0].key
- }
-
func matchingTerminalTask(
for event: WorkflowHookEvent,
allowsAnonymousFallback: Bool = true
@@ -1166,7 +1149,7 @@ final class CodexActivityMonitor: ObservableObject {
if let sessionId = event.sessionId {
let pendingCandidates = pendingTerminalTasks.filter {
$0.value.task.key.sessionId == sessionId
- && $0.value.task.lastHookEventAt <= event.timestamp
+ && $0.value.task.lastMainHookEventAt <= event.timestamp
&& (event.turnId == nil || $0.value.task.associatedTurnId == nil)
}
if pendingCandidates.count == 1, let key = pendingCandidates.keys.first {
@@ -1178,7 +1161,7 @@ final class CodexActivityMonitor: ObservableObject {
let activeCandidates = tasks.values.filter {
$0.key.sessionId == sessionId
- && $0.lastHookEventAt <= event.timestamp
+ && $0.lastMainHookEventAt <= event.timestamp
&& (event.turnId == nil || $0.associatedTurnId == nil)
}
if activeCandidates.count == 1 {
@@ -1337,6 +1320,16 @@ final class CodexActivityMonitor: ObservableObject {
}
private extension CodexActivityMonitor {
+ func resumePromptInSameTurn(from event: WorkflowHookEvent, existing: CodexActivityTask?) -> Bool {
+ guard var task = existing, let turnId = event.turnId, task.associatedTurnId == turnId else { return false }
+ task.resumeExecution(from: event, latestEvent: .promptSubmitted)
+ task.mergeMetadata(from: event)
+ task.recordHookEvent(at: event.timestamp)
+ task.startedAt = task.startedAt ?? event.timestamp
+ tasks[task.key] = task
+ return true
+ }
+
func preserveSupersededSessionTask(from event: WorkflowHookEvent, key: CodexActivityTaskKey) {
if let existing = tasks[key], key.isSessionOnly,
let resolved = existing.resolvedTurnKey,
@@ -1353,9 +1346,10 @@ private extension CodexActivityMonitor {
guard let existing = tasks.values.first(where: { $0.resolvedTurnKey == key && $0.key != key }) else {
return false
}
- guard event.timestamp >= existing.lastHookEventAt else { return true }
+ guard event.timestamp >= existing.lastMainHookEventAt else { return true }
var task = existing
task.mergeMetadata(from: event)
+ task.recordExecutionEvent(event)
task.recordHookEvent(at: event.timestamp)
tasks[existing.key] = task
return true
diff --git a/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift b/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift
index 381595e..6055e0f 100644
--- a/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift
+++ b/CodexBar/Services/Workflow/CodexActivityOriginFiltering.swift
@@ -2,16 +2,27 @@ import Foundation
import os
extension CodexActivityMonitor {
- /// 来源过滤只影响实时活动链路, 原始事件仍由历史聚合完整消费
- func shouldIgnoreForActivity(
- _ event: WorkflowHookEvent,
+ /// 仅为实时链路归一化事件副本, 来源过滤和执行身份使用同一判断
+ func activityEvent(from event: WorkflowHookEvent, source: CodexActivityEventSource) -> WorkflowHookEvent? {
+ guard let origin = activityOrigin(for: event, source: source) else { return nil }
+ guard origin != event.origin else { return event }
+ return WorkflowHookEvent(
+ timestamp: event.timestamp, name: event.name, origin: origin,
+ directoryPath: event.directoryPath, toolName: event.toolName, modelName: event.modelName,
+ effort: event.effort, permissionMode: event.permissionMode, approvalReviewer: event.approvalReviewer,
+ sessionId: event.sessionId, turnId: event.turnId, agentId: event.agentId
+ )
+ }
+
+ private func activityOrigin(
+ for event: WorkflowHookEvent,
source: CodexActivityEventSource
- ) -> Bool {
+ ) -> WorkflowEventOrigin? {
let exactKey = Self.exactTurnKey(for: event)
switch event.origin {
case .autoReview:
guard let exactKey else {
- return true
+ return nil
}
let wasAlreadyIgnored = activityTaskOrigins[exactKey]?.origin == .autoReview
@@ -20,27 +31,27 @@ extension CodexActivityMonitor {
if !wasAlreadyIgnored, source == .live {
AppLog.activity.notice("Auto-review 任务已过滤")
}
- return true
+ return nil
case .main, .auxiliary:
if let exactKey {
rememberActivityOrigin(event.origin, for: exactKey, at: event.timestamp)
}
- return false
+ return event.origin
case .unknown:
guard let exactKey,
let knownOrigin = activityTaskOrigins[exactKey] else {
- return true
+ return nil
}
guard knownOrigin.observedAt > Date().addingTimeInterval(-Self.activityRetention) else {
activityTaskOrigins.removeValue(forKey: exactKey)
- return true
+ return nil
}
guard knownOrigin.origin == .main || knownOrigin.origin == .auxiliary else {
- return true
+ return nil
}
// 一次读取失败不推翻已确认来源, 迟到事件仍交给状态机检查时间顺序
rememberActivityOrigin(knownOrigin.origin, for: exactKey, at: event.timestamp)
- return false
+ return knownOrigin.origin
}
}
diff --git a/CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift b/CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift
new file mode 100644
index 0000000..21859c8
--- /dev/null
+++ b/CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift
@@ -0,0 +1,107 @@
+import Foundation
+
+struct CodexPendingSubagentEvent {
+ let event: WorkflowHookEvent
+ let source: CodexActivityEventSource
+}
+
+extension CodexActivityMonitor {
+ /// 生命周期和工具 Hook 都携带子轮次, 已结束或未确认的归属不回退到当前根任务
+ func matchingSubagentParentTaskKey(
+ for event: WorkflowHookEvent
+ ) -> CodexActivityTaskKey? {
+ guard let reference = subagentReference(for: event),
+ let rootKey = subagentTurnLinks[reference], rootKey.sessionId == event.sessionId else { return nil }
+ return tasks.first(where: { $0.value.resolvedTurnKey == rootKey })?.key
+ }
+
+ func subagentReference(for event: WorkflowHookEvent) -> CodexActivityTurnReference? {
+ guard let agentId = event.agentId, let turnId = event.turnId else { return nil }
+ // 引用的相等性只由线程和轮次决定, 时间只用于文件定位
+ return CodexActivityTurnReference(sessionId: agentId, turnId: turnId, startedAt: event.timestamp)
+ }
+
+ func deferUnassociatedSubagentEvent(_ event: WorkflowHookEvent, source: CodexActivityEventSource) -> Bool {
+ guard let reference = subagentReference(for: event), subagentTurnLinks[reference] == nil else { return false }
+ guard event.sessionId != nil else { return true }
+ if !pendingSubagentEvents.contains(where: { $0.event == event }) {
+ pendingSubagentEvents.append(CodexPendingSubagentEvent(event: event, source: source))
+ }
+ return true
+ }
+
+ func subagentLifecycleReferences() -> [CodexActivityTurnReference] {
+ let cutoff = Date().addingTimeInterval(-CodexActivityRetention.window)
+ pendingSubagentEvents.removeAll { $0.event.timestamp <= cutoff }
+ // 结束后的关联也保留一个回放窗口, 用于拒绝旧 Agent 的迟到生命周期 Hook
+ subagentTurnLinks = subagentTurnLinks.filter { $0.key.startedAt > cutoff }
+ var references = pendingSubagentEvents.compactMap { subagentReference(for: $0.event) }
+ for task in tasks.values {
+ for (owner, execution) in task.executions where !execution.isTerminal {
+ guard let agentId = owner.agentId, let turnId = owner.turnId else { continue }
+ references.append(CodexActivityTurnReference(sessionId: agentId, turnId: turnId, startedAt: execution.lastHookEventAt))
+ }
+ }
+ return Array(Set(references))
+ }
+
+ func applySubagentLifecycle(
+ _ state: CodexSessionTaskLifecycleState,
+ terminalOnly: Bool,
+ into transitions: inout [CodexActivityTransition]
+ ) -> Bool {
+ guard state.readStatus == .complete,
+ state.threadId == state.sessionId,
+ let rootTurnId = state.rootTurnId,
+ let parentThreadId = state.parentThreadId, parentThreadId != state.sessionId else { return false }
+ let reference = CodexActivityTurnReference(sessionId: state.sessionId, turnId: state.turnId, startedAt: state.startedAt ?? Date())
+ let hookSessions = Set(pendingSubagentEvents.compactMap { pending -> String? in
+ subagentReference(for: pending.event) == reference ? pending.event.sessionId : nil
+ })
+ let rootSessionId = state.rootSessionId ?? subagentTurnLinks[reference]?.sessionId
+ ?? (hookSessions.count == 1 ? hookSessions.first : nil)
+ guard let rootSessionId, rootSessionId != state.sessionId,
+ hookSessions.isEmpty || hookSessions == [rootSessionId] else { return false }
+ let rootKey = CodexActivityTaskKey.turn(session: rootSessionId, turn: rootTurnId)
+ guard subagentTurnLinks[reference].map({ $0 == rootKey }) ?? true else { return false }
+ subagentTurnLinks[reference] = rootKey
+ guard !terminalOnly || state.terminal != nil,
+ let key = tasks.first(where: { $0.value.resolvedTurnKey == rootKey })?.key,
+ var task = tasks[key] else { return false }
+ let owner = CodexActivityExecutionKey(agentId: state.sessionId, turnId: state.turnId)
+ let wasWaiting = task.state == .waitingApproval
+ task.mergeExecutionLifecycle(state, owner: owner)
+ _ = resolvePendingApprovalIfPossible(for: &task, into: &transitions)
+ if !terminalOnly {
+ _ = mergeLifecycleProgress(from: state, key: key, into: &task)
+ }
+ tasks[key] = task
+ if !terminalOnly, wasWaiting != (task.state == .waitingApproval) {
+ clearActivityProtection(for: key, taskID: task.displayID, reason: .progress)
+ }
+ return true
+ }
+
+ func replayAssociatedSubagentEvents(into transitions: inout [CodexActivityTransition]) -> Bool {
+ var remaining: [CodexPendingSubagentEvent] = []
+ var ready: [CodexPendingSubagentEvent] = []
+ for pending in pendingSubagentEvents {
+ if let reference = subagentReference(for: pending.event), subagentTurnLinks[reference] != nil {
+ ready.append(pending)
+ } else {
+ remaining.append(pending)
+ }
+ }
+ pendingSubagentEvents = remaining
+ var waitingKeys: [CodexActivityTaskKey] = []
+ for pending in ready {
+ guard let reference = subagentReference(for: pending.event),
+ subagentTurnLinks[reference]?.sessionId == pending.event.sessionId else { continue }
+ if let key = apply(pending.event, source: pending.source), pending.source == .live {
+ waitingKeys.append(key)
+ }
+ }
+ transitions.append(contentsOf: waitingApprovalTransitions(waitingKeys))
+ return !ready.isEmpty
+ }
+}
diff --git a/CodexBar/Services/Workflow/CodexActivityTask.swift b/CodexBar/Services/Workflow/CodexActivityTask.swift
index 7420ffa..e1c8e6b 100644
--- a/CodexBar/Services/Workflow/CodexActivityTask.swift
+++ b/CodexBar/Services/Workflow/CodexActivityTask.swift
@@ -121,7 +121,6 @@ struct CodexActivityTask {
let key: CodexActivityTaskKey
var associatedTurnId: String?
var lifecycleCoverageCheckedAt: Date?
- var approvalContextObservedAt: Date?
var state: CodexActivityTaskState
var latestEvent: CodexActivityEvent
var projectName: String?
@@ -133,8 +132,7 @@ struct CodexActivityTask {
var lastHookEventAt: Date
var lastProgressAt: Date
var progressGeneration: UInt64
- var approvalReviewer: CodexApprovalReviewer?
- var pendingApprovalRequestedAt: Date?
+ var executions: [CodexActivityExecutionKey: CodexActivityExecution] = [:]
var subagentsByID: [String: CodexSubagentObservation]
var isSubagentCountReliable: Bool
@@ -161,11 +159,9 @@ struct CodexActivityTask {
lastHookEventAt = event.timestamp
lastProgressAt = event.timestamp
self.progressGeneration = progressGeneration
- approvalReviewer = event.approvalReviewer
- approvalContextObservedAt = event.approvalReviewer == nil ? nil : event.timestamp
- pendingApprovalRequestedAt = nil
subagentsByID = [:]
isSubagentCountReliable = startedAt != nil
+ recordExecutionEvent(event)
}
var showsPreciseDuration: Bool {
@@ -184,11 +180,11 @@ struct CodexActivityTask {
CodexActivityTaskSnapshot(
id: displayID,
isAnonymous: key.isAnonymous,
- latestEvent: latestEvent,
+ latestEvent: displayedApproval == nil ? latestEvent : .approvalRequested,
projectName: projectName,
modelName: modelName,
effort: effort,
- toolName: toolName,
+ toolName: displayedApproval.map(\.toolName) ?? toolName,
startedAt: startedAt,
stateChangedAt: stateChangedAt,
showsPreciseDuration: showsPreciseDuration,
@@ -236,11 +232,6 @@ struct CodexActivityTask {
modelName = event.modelName ?? modelName
_ = mergeEffort(event.effort)
toolName = event.toolName ?? toolName
- if let reviewer = event.approvalReviewer,
- event.timestamp >= (approvalContextObservedAt ?? .distantPast) {
- approvalReviewer = reviewer
- approvalContextObservedAt = event.timestamp
- }
}
/// Hook 顺序独立于 rollout 进展, 避免用量记录使稍早的状态事件失效
@@ -273,6 +264,7 @@ struct CodexActivityTask {
mutating func recordSubagentActivity(
agentId: String?,
isStarting: Bool,
+ hasEnded: Bool = false,
at timestamp: Date
) {
guard let agentId else {
@@ -288,7 +280,7 @@ struct CodexActivityTask {
isSubagentCountReliable = false
}
subagentsByID[agentId] = CodexSubagentObservation(
- isRunning: isStarting,
+ isRunning: isStarting && !hasEnded,
timestamp: timestamp
)
}
@@ -312,28 +304,182 @@ struct CodexActivityTask {
return value.isEmpty ? nil : value
}
- /// 记录审批候选; 返回值只表示任务是否刚刚进入用户等待状态
- mutating func recordApprovalRequest(at requestedAt: Date) -> Bool {
- pendingApprovalRequestedAt = requestedAt
- guard approvalReviewer == .user else {
- return false
+ var displayedApproval: CodexActivityApproval? {
+ executions.values.compactMap { execution -> CodexActivityApproval? in
+ guard case let .waiting(approval)? = execution.approval else { return nil }
+ return approval
+ }.min {
+ if $0.requestedAt != $1.requestedAt {
+ return $0.requestedAt < $1.requestedAt
+ }
+ return $0.sequence < $1.sequence
}
+ }
+
+ func executionKey(for event: WorkflowHookEvent) -> CodexActivityExecutionKey {
+ CodexActivityExecutionKey(
+ agentId: event.agentId,
+ turnId: event.turnId,
+ isUnattributed: event.agentId == nil && event.origin != .main
+ )
+ }
- let enteredWaiting = state != .waitingApproval
- confirmPendingApproval()
- return enteredWaiting
+ var lastMainHookEventAt: Date {
+ executions.filter { $0.key.agentId == nil && !$0.key.isUnattributed }
+ .values.map(\.lastHookEventAt).max() ?? startedAt ?? .distantPast
}
- mutating func confirmPendingApproval() {
- guard let requestedAt = pendingApprovalRequestedAt else {
- return
+ func acceptsExecutionEvent(_ event: WorkflowHookEvent) -> Bool {
+ let execution = executions[executionKey(for: event)]
+ return execution?.isTerminal != true && event.timestamp >= (execution?.lastHookEventAt ?? .distantPast)
+ }
+
+ mutating func recordExecutionEvent(_ event: WorkflowHookEvent) {
+ let owner = executionKey(for: event)
+ var execution = executions[owner] ?? CodexActivityExecution()
+ execution.lastHookEventAt = max(execution.lastHookEventAt, event.timestamp)
+ execution.mergeReviewer(event.approvalReviewer, at: event.timestamp)
+ executions[owner] = execution
+ }
+
+ mutating func resumeExecution(from event: WorkflowHookEvent, latestEvent: CodexActivityEvent) {
+ recordExecutionEvent(event)
+ let owner = executionKey(for: event)
+ if owner.isReliable, var execution = executions[owner] {
+ execution.approval = nil
+ execution.lastExecutionProgressAt = max(execution.lastExecutionProgressAt ?? .distantPast, event.timestamp)
+ executions[owner] = execution
+ }
+ self.latestEvent = latestEvent
+ refreshApprovalState(at: event.timestamp, restoresRunning: true)
+ }
+
+ /// 审批路由未知时只保存候选, 后续上下文只能确认同一执行归属
+ mutating func recordApprovalRequest(from event: WorkflowHookEvent) -> Bool {
+ let wasWaiting = state == .waitingApproval
+ let owner = executionKey(for: event)
+ guard event.timestamp > (executions[owner]?.lastApprovalRequestedAt ?? .distantPast),
+ event.timestamp >= (executions[owner]?.lastExecutionProgressAt ?? .distantPast) else { return false }
+ recordExecutionEvent(event)
+ executions[owner]?.lastApprovalRequestedAt = event.timestamp
+ if executions[owner]?.approval == nil {
+ executions[owner]?.approval = .pending(CodexActivityApproval(
+ requestedAt: event.timestamp, toolName: event.toolName, sequence: progressGeneration
+ ))
+ }
+ _ = resolvePendingApprovals()
+ return !wasWaiting && state == .waitingApproval
+ }
+
+ @discardableResult
+ mutating func resolvePendingApprovals() -> Bool {
+ var changed = false
+ for owner in executions.keys {
+ guard var execution = executions[owner], case let .pending(pending)? = execution.approval,
+ let reviewer = execution.approvalReviewer else { continue }
+ execution.approval = reviewer == .user ? .waiting(pending) : nil
+ executions[owner] = execution
+ changed = true
+ }
+ if changed {
+ refreshApprovalState(at: displayedApproval?.requestedAt ?? lastProgressAt)
+ }
+ return changed
+ }
+
+ mutating func mergeApprovalContext(
+ reviewer: CodexApprovalReviewer?, observedAt: Date?, owner: CodexActivityExecutionKey
+ ) {
+ guard let observedAt else { return }
+ var execution = executions[owner] ?? CodexActivityExecution()
+ execution.mergeReviewer(reviewer, at: observedAt)
+ executions[owner] = execution
+ }
+
+ mutating func mergeExecutionLifecycle(_ lifecycle: CodexSessionTaskLifecycleState, owner: CodexActivityExecutionKey) {
+ guard lifecycle.readStatus == .complete else { return }
+ if lifecycle.terminal != nil {
+ finishExecution(owner, at: lifecycle.lastProgressAt ?? lastProgressAt)
+ } else {
+ mergeApprovalContext(reviewer: lifecycle.approvalReviewer, observedAt: lifecycle.contextObservedAt, owner: owner)
+ mergeExecutionProgress(at: lifecycle.lastExecutionProgressAt, owner: owner)
+ }
+ }
+
+ mutating func mergeExecutionProgress(at timestamp: Date?, owner: CodexActivityExecutionKey) {
+ guard owner.isReliable, let timestamp else { return }
+ var execution = executions[owner] ?? CodexActivityExecution()
+ execution.lastExecutionProgressAt = max(execution.lastExecutionProgressAt ?? .distantPast, timestamp)
+ if let approval = execution.approval, timestamp > approval.request.requestedAt {
+ execution.approval = nil
+ }
+ executions[owner] = execution
+ refreshApprovalState(at: timestamp)
+ }
+
+ mutating func finishExecution(_ owner: CodexActivityExecutionKey, at timestamp: Date) {
+ var execution = executions[owner] ?? CodexActivityExecution()
+ execution.approval = nil
+ execution.isTerminal = true
+ executions[owner] = execution
+ refreshApprovalState(at: timestamp)
+ }
+
+ private mutating func refreshApprovalState(at timestamp: Date, restoresRunning: Bool = false) {
+ if let approval = displayedApproval {
+ if state != .waitingApproval {
+ state = .waitingApproval
+ stateChangedAt = approval.requestedAt
+ }
+ } else if state == .waitingApproval || restoresRunning {
+ if state != .running {
+ state = .running
+ stateChangedAt = timestamp
+ }
}
- pendingApprovalRequestedAt = nil
- if state != .waitingApproval {
- state = .waitingApproval
- stateChangedAt = requestedAt
+ }
+}
+
+struct CodexActivityExecutionKey: Hashable {
+ let agentId: String?
+ let turnId: String?
+ var isUnattributed = false
+
+ var isReliable: Bool {
+ turnId != nil && !isUnattributed
+ }
+}
+
+struct CodexActivityApproval {
+ let requestedAt: Date
+ let toolName: String?
+ let sequence: UInt64
+}
+
+enum CodexActivityApprovalState {
+ case pending(CodexActivityApproval)
+ case waiting(CodexActivityApproval)
+
+ var request: CodexActivityApproval {
+ switch self {
+ case let .pending(request), let .waiting(request): request
}
- latestEvent = .approvalRequested
+ }
+}
+
+struct CodexActivityExecution {
+ var lastHookEventAt: Date = .distantPast
+ var approvalReviewer: CodexApprovalReviewer?
+ var approvalContextObservedAt: Date?
+ var lastExecutionProgressAt: Date?
+ var lastApprovalRequestedAt: Date?
+ var approval: CodexActivityApprovalState?
+ var isTerminal = false
+
+ mutating func mergeReviewer(_ reviewer: CodexApprovalReviewer?, at timestamp: Date) {
+ guard let reviewer, timestamp >= (approvalContextObservedAt ?? .distantPast) else { return }
+ approvalReviewer = reviewer
+ approvalContextObservedAt = timestamp
}
}
diff --git a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift b/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift
index fcd4ad5..1d7cb1c 100644
--- a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift
+++ b/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift
@@ -28,7 +28,7 @@ extension CodexActivityMonitor {
key = eventKey
task = nil
}
- guard task.map({ event.timestamp >= $0.lastHookEventAt }) ?? true else {
+ guard task.map({ event.timestamp >= $0.lastMainHookEventAt }) ?? true else {
return
}
if recentEndedDate(for: key) != nil {
@@ -64,23 +64,13 @@ extension CodexActivityMonitor {
for task: inout CodexActivityTask,
into transitions: inout [CodexActivityTransition]
) -> Bool {
- guard let requestedAt = task.pendingApprovalRequestedAt,
- let approvalReviewer = task.approvalReviewer else {
- return false
- }
-
- switch approvalReviewer {
- case .user:
- let wasWaiting = task.state == .waitingApproval
- task.confirmPendingApproval()
- if !wasWaiting, canPublishActivityTransitions,
- !task.key.isAnonymous,
- let sessionTransitionNotBefore,
- requestedAt >= sessionTransitionNotBefore {
- transitions.append(.waitingApproval(task.snapshot))
- }
- case .autoReview, .guardianSubagent:
- task.pendingApprovalRequestedAt = nil
+ let wasWaiting = task.state == .waitingApproval
+ guard task.resolvePendingApprovals() else { return false }
+ if !wasWaiting, task.state == .waitingApproval, canPublishActivityTransitions,
+ !task.key.isAnonymous, let sessionTransitionNotBefore,
+ task.stateChangedAt >= sessionTransitionNotBefore,
+ Date().timeIntervalSince(task.stateChangedAt) <= 10 {
+ transitions.append(.waitingApproval(task.snapshot))
}
return true
}
@@ -271,6 +261,8 @@ extension CodexActivityMonitor {
recentlyEndedTaskAt.removeAll()
terminalTaskKeyByID.removeAll()
activityTaskOrigins.removeAll()
+ pendingSubagentEvents.removeAll()
+ subagentTurnLinks.removeAll()
}
func finalizeExpiredPendingTerminalTasks(now: Date) {
@@ -290,7 +282,14 @@ extension CodexActivityMonitor {
}
func publishWaitingApprovalTransitions(_ taskKeys: [CodexActivityTaskKey]) {
- guard canPublishActivityTransitions else { return }
+ for transition in waitingApprovalTransitions(taskKeys) {
+ transitionSubject.send(transition)
+ }
+ }
+
+ func waitingApprovalTransitions(_ taskKeys: [CodexActivityTaskKey]) -> [CodexActivityTransition] {
+ guard canPublishActivityTransitions else { return [] }
+ var transitions: [CodexActivityTransition] = []
var lastWaitingIndexByKey: [CodexActivityTaskKey: Int] = [:]
for (index, key) in taskKeys.enumerated() {
lastWaitingIndexByKey[key] = index
@@ -306,7 +305,8 @@ extension CodexActivityMonitor {
Date().timeIntervalSince(task.stateChangedAt) <= 10 else {
continue
}
- transitionSubject.send(.waitingApproval(task.snapshot))
+ transitions.append(.waitingApproval(task.snapshot))
}
+ return transitions
}
}
diff --git a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift
index e6ebe3e..505c460 100644
--- a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift
+++ b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift
@@ -5,6 +5,15 @@ nonisolated struct CodexActivityTurnReference: Hashable {
let sessionId: String
let turnId: String
let startedAt: Date
+
+ static func == (lhs: Self, rhs: Self) -> Bool {
+ lhs.sessionId == rhs.sessionId && lhs.turnId == rhs.turnId
+ }
+
+ func hash(into hasher: inout Hasher) {
+ hasher.combine(sessionId)
+ hasher.combine(turnId)
+ }
}
/// 文件读取结果包含覆盖状态, 缓存事实不能替代本轮读取成功
@@ -42,6 +51,9 @@ actor CodexSessionLifecycleReader {
var status = CodexSessionReadStatus.notFound
if var cursor = cursor(for: latest) {
status = scan(into: &cursor, limit: min(Self.incrementalByteLimit, budget))
+ if cursor.metadata?.id != sessionId {
+ status = .unavailable
+ }
budget -= min(budget, cursor.lastReadByteCount)
let needsContext = sessionReferences.contains {
let known = cursor.lifecycleByTurnId[$0.turnId]
@@ -70,7 +82,12 @@ actor CodexSessionLifecycleReader {
approvalReviewer: known?.approvalReviewer, effort: known?.effort,
lastProgressAt: known?.lastProgressAt, terminal: turnStatus == .complete ? known?.terminal : nil,
readStatus: turnStatus, hasContext: known?.hasContext == true,
- contextObservedAt: known?.contextObservedAt
+ contextObservedAt: known?.contextObservedAt,
+ rootTurnId: known?.rootTurnId,
+ threadId: cursor?.metadata?.id,
+ rootSessionId: cursor?.metadata?.sessionId,
+ parentThreadId: cursor?.metadata?.parentThreadId,
+ lastExecutionProgressAt: known?.lastExecutionProgressAt
))
}
}
@@ -83,7 +100,8 @@ actor CodexSessionLifecycleReader {
}
private func cursor(for reference: CodexActivityTurnReference) -> SessionFileCursor? {
- if let cursor = cursorsBySession[reference.sessionId], fileManager.fileExists(atPath: cursor.url.path) {
+ if let cursor = cursorsBySession[reference.sessionId],
+ matchingFile(in: cursor.url.deletingLastPathComponent(), threadId: reference.sessionId) == cursor.url {
return cursor
}
if cursorsBySession.removeValue(forKey: reference.sessionId) != nil {
@@ -95,10 +113,12 @@ actor CodexSessionLifecycleReader {
return nil
}
lastResolutionAttemptBySession[reference.sessionId] = now
- let suffix = "-\(reference.sessionId).jsonl"
for directory in [sessionDirectory(for: reference.startedAt), sessionDirectory(for: now), archivedSessionsRootURL] {
- if let url = matchingFile(in: directory, suffix: suffix) {
- return initialCursor(for: url)
+ if let url = matchingFile(in: directory, threadId: reference.sessionId) {
+ let cursor = initialCursor(for: url)
+ if cursor.metadata?.id == reference.sessionId {
+ return cursor
+ }
}
}
if let last = lastRecursiveAttemptBySession[reference.sessionId], now.timeIntervalSince(last) < 60 {
@@ -109,15 +129,27 @@ actor CodexSessionLifecycleReader {
at: sessionsRootURL, includingPropertiesForKeys: [.isRegularFileKey],
options: [.skipsHiddenFiles, .skipsPackageDescendants]
) else { return nil }
- for case let url as URL in enumerator where url.lastPathComponent.hasSuffix(suffix) {
- return initialCursor(for: url)
- }
- return nil
+ let matches = enumerator.compactMap { $0 as? URL }.filter { Self.matchesFile($0, threadId: reference.sessionId) }
+ guard matches.count == 1, let url = matches.first else { return nil }
+ let cursor = initialCursor(for: url)
+ return cursor.metadata?.id == reference.sessionId ? cursor : nil
}
- private func matchingFile(in directory: URL, suffix: String) -> URL? {
- (try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]))?
- .first { $0.lastPathComponent.hasSuffix(suffix) }
+ private func matchingFile(in directory: URL, threadId: String) -> URL? {
+ let matches = (try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]))?
+ .filter { Self.matchesFile($0, threadId: threadId) } ?? []
+ return matches.count == 1 ? matches.first : nil
+ }
+
+ private static func matchesFile(_ url: URL, threadId: String) -> Bool {
+ let name = url.lastPathComponent
+ guard name.hasPrefix("rollout-"), name.hasSuffix(".jsonl") else { return false }
+ let stem = String(name.dropLast(6))
+ if stem.hasSuffix("-\(threadId)") {
+ return true
+ }
+ guard let separator = stem.lastIndex(of: "_"), UUID(uuidString: String(stem[stem.index(after: separator)...])) != nil else { return false }
+ return stem[..<separator].hasSuffix("-\(threadId)")
}
private func sessionDirectory(for date: Date) -> URL {
@@ -129,7 +161,11 @@ actor CodexSessionLifecycleReader {
let stat = WorkflowStorage.fileStat(at: url)
let size = stat?.size ?? 0
let offset = size > Self.bootstrapByteLimit ? size - Self.bootstrapByteLimit : 0
- return SessionFileCursor(url: url, fileIdentifier: stat?.identifier, offset: offset, historicalOffset: offset, discardsLeadingPartialLine: offset > 0)
+ return SessionFileCursor(
+ url: url, fileIdentifier: stat?.identifier, offset: offset, historicalOffset: offset,
+ discardsLeadingPartialLine: offset > 0,
+ metadata: WorkflowRolloutMetadataReader.metadata(transcriptPath: url.path)
+ )
}
private func backfillContext(into cursor: inout SessionFileCursor) -> CodexSessionReadStatus {
@@ -140,7 +176,8 @@ actor CodexSessionLifecycleReader {
fileIdentifier: cursor.fileIdentifier,
offset: start,
historicalOffset: start,
- discardsLeadingPartialLine: start > 0
+ discardsLeadingPartialLine: start > 0,
+ metadata: cursor.metadata
)
let status = scan(into: &restored, limit: Self.contextByteLimit, through: end)
guard status == .complete else { return status }
@@ -197,6 +234,7 @@ private nonisolated struct SessionFileCursor {
var offset: UInt64
let historicalOffset: UInt64
var discardsLeadingPartialLine: Bool
+ var metadata: WorkflowRolloutMetadataPayload?
var currentTurnId: String?
var lifecycleByTurnId: [String: SessionTurnLifecycle] = [:]
var didBackfill = false
@@ -216,6 +254,11 @@ private nonisolated struct SessionFileCursor {
mutating func apply(_ envelope: CodexRolloutLineEnvelope) {
if envelope.startsTurnContext {
currentTurnId = envelope.payload?.turnId.flatMap { $0.isEmpty ? nil : $0 }
+ if let turnId = currentTurnId, let rootTurnId = envelope.payload?.rootTurnId, !rootTurnId.isEmpty {
+ var state = lifecycleByTurnId[turnId] ?? SessionTurnLifecycle()
+ state.rootTurnId = rootTurnId
+ lifecycleByTurnId[turnId] = state
+ }
}
if let event = envelope.progressEvent(currentTurnId: currentTurnId) {
apply(event)
@@ -253,6 +296,9 @@ nonisolated struct CodexRolloutLineEnvelope: Decodable {
nonisolated struct CodexRolloutLinePayload: Decodable {
let type: String?
let turnId: String?
+ let rootTurnId: String?
+ let messageMetadata: CodexRolloutMessageMetadata?
+ let role: String?
let startedAt: Double?
let completedAt: Double?
let durationMilliseconds: Double?
@@ -268,8 +314,10 @@ nonisolated struct CodexRolloutLinePayload: Decodable {
}
private enum CodingKeys: String, CodingKey {
- case type
+ case type, role
case turnId = "turn_id"
+ case rootTurnId = "root_turn_id"
+ case messageMetadata = "internal_chat_message_metadata_passthrough"
case startedAt = "started_at"
case completedAt = "completed_at"
case durationMilliseconds = "duration_ms"
@@ -278,17 +326,28 @@ nonisolated struct CodexRolloutLinePayload: Decodable {
}
}
+nonisolated struct CodexRolloutMessageMetadata: Decodable {
+ let turnId: String?
+
+ private enum CodingKeys: String, CodingKey {
+ case turnId = "turn_id"
+ }
+}
+
private nonisolated extension CodexRolloutLineEnvelope {
var startsTurnContext: Bool {
- type == "turn_context" || (type == "event_msg" && payload?.type == "task_started")
+ type == "turn_context" || (type == "event_msg" && ["task_started", "turn_started"].contains(payload?.type ?? ""))
}
var endsTurnContext: Bool {
- type == "event_msg" && (payload?.type == "task_complete" || payload?.type == "turn_aborted")
+ type == "event_msg" && ["task_complete", "turn_complete", "turn_aborted"].contains(payload?.type ?? "")
}
func progressEvent(currentTurnId: String?) -> SessionLifecycleEvent? {
- let progressTypes: Set = ["token_count", "item_completed", "agent_message", "agent_reasoning", "task_started", "task_complete", "turn_aborted"]
+ let progressTypes: Set = [
+ "token_count", "item_completed", "agent_message", "agent_reasoning",
+ "task_started", "turn_started", "task_complete", "turn_complete", "turn_aborted"
+ ]
guard type == "response_item" || type == "token_usage_record"
|| (type == "event_msg" && payload?.type.map(progressTypes.contains) == true) else {
return nil
@@ -300,10 +359,16 @@ private nonisolated extension CodexRolloutLineEnvelope {
return nil
}
- guard let turnId = payload?.turnId ?? currentTurnId, !turnId.isEmpty else {
+ let explicitTurnId = type == "response_item" ? payload?.messageMetadata?.turnId : payload?.turnId
+ guard let turnId = explicitTurnId ?? currentTurnId, !turnId.isEmpty else {
return nil
}
- return SessionLifecycleEvent(turnId: turnId, change: .progress(at: eventDate))
+ let isExecutionProgress = if type == "response_item" {
+ payload?.role == "assistant" || ["function_call_output", "custom_tool_call_output", "tool_search_output"].contains(payload?.type ?? "")
+ } else {
+ type == "event_msg" && ["agent_message", "agent_reasoning"].contains(payload?.type ?? "")
+ }
+ return SessionLifecycleEvent(turnId: turnId, change: .progress(at: eventDate, resumesApproval: isExecutionProgress))
}
var lifecycleEvent: SessionLifecycleEvent? {
@@ -333,13 +398,13 @@ private nonisolated extension CodexRolloutLineEnvelope {
}
switch payload.type {
- case "task_started":
+ case "task_started", "turn_started":
guard let startedAt = payload.startedAt.flatMap(Self.date) else {
return nil
}
return SessionLifecycleEvent(turnId: turnId, change: .started(at: startedAt))
- case "task_complete":
- guard let completedAt = payload.completedAt.flatMap(Self.date) else {
+ case "task_complete", "turn_complete":
+ guard let completedAt = payload.completedAt.flatMap(Self.date) ?? timestamp.flatMap(CodexDateFormat.iso8601Date) else {
return nil
}
let duration = payload.durationMilliseconds.flatMap { milliseconds in
@@ -370,7 +435,7 @@ private nonisolated struct SessionLifecycleEvent {
}
private nonisolated enum SessionLifecycleChange {
- case progress(at: Date)
+ case progress(at: Date, resumesApproval: Bool)
case started(at: Date)
case context(approvalReviewer: CodexApprovalReviewer?, effort: String?, observedAt: Date?)
case completed(at: Date, duration: TimeInterval?)
@@ -378,6 +443,7 @@ private nonisolated enum SessionLifecycleChange {
}
private nonisolated struct SessionTurnLifecycle {
+ var rootTurnId: String?
var hasReadGap = false
var contextObservedAt: Date?
var hasContext = false
@@ -385,12 +451,16 @@ private nonisolated struct SessionTurnLifecycle {
var approvalReviewer: CodexApprovalReviewer?
var effort: String?
var lastProgressAt: Date?
+ var lastExecutionProgressAt: Date?
var terminal: CodexSessionTaskTerminalState?
mutating func apply(_ change: SessionLifecycleChange) {
switch change {
- case let .progress(at):
+ case let .progress(at, resumesApproval):
lastProgressAt = max(lastProgressAt ?? .distantPast, at)
+ if resumesApproval {
+ lastExecutionProgressAt = max(lastExecutionProgressAt ?? .distantPast, at)
+ }
case let .started(at):
if let currentStartedAt = startedAt {
startedAt = min(currentStartedAt, at)
@@ -421,6 +491,11 @@ nonisolated struct CodexSessionTaskLifecycleState {
var readStatus: CodexSessionReadStatus = .complete
var hasContext = false
var contextObservedAt: Date?
+ var rootTurnId: String?
+ var threadId: String?
+ var rootSessionId: String?
+ var parentThreadId: String?
+ var lastExecutionProgressAt: Date?
}
nonisolated enum CodexSessionReadStatus {
diff --git a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
index cc0d0f6..2ced919 100644
--- a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
+++ b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift
@@ -46,7 +46,9 @@ nonisolated enum WorkflowHookEventRecorder {
let turnId = payload.string(for: "turn_id")
let agentId = payload.string(for: "agent_id")
let transcriptPath = payload.string(for: "transcript_path")
- let origin = WorkflowEventOriginReader.origin(transcriptPath: transcriptPath)
+ let sourcePath = hookEvent == .subagentStop
+ ? payload.string(for: "agent_transcript_path") : transcriptPath
+ let origin = WorkflowRolloutMetadataReader.origin(transcriptPath: sourcePath)
let turnContext = readTurnContext(
transcriptPath: transcriptPath,
hookEvent: hookEvent,
@@ -191,15 +193,19 @@ nonisolated enum WorkflowHookEventRecorder {
}
/// Codex 把来源写在大型指令字段之前, 在固定预算内读取已完成的元数据字段
-private nonisolated enum WorkflowEventOriginReader {
+nonisolated enum WorkflowRolloutMetadataReader {
static func origin(transcriptPath: String?) -> WorkflowEventOrigin {
+ metadata(transcriptPath: transcriptPath)?.source?.origin ?? .unknown
+ }
+
+ static func metadata(transcriptPath: String?) -> WorkflowRolloutMetadataPayload? {
guard let transcriptPath else {
- return .unknown
+ return nil
}
let url = URL(fileURLWithPath: transcriptPath)
guard let handle = try? FileHandle(forReadingFrom: url) else {
- return .unknown
+ return nil
}
defer {
try? handle.close()
@@ -210,28 +216,28 @@ private nonisolated enum WorkflowEventOriginReader {
let readCount = min(readChunkByteCount, firstLineByteLimit - data.count)
guard let chunk = try? handle.read(upToCount: readCount),
!chunk.isEmpty else {
- return .unknown
+ return nil
}
data.append(chunk)
if let newlineIndex = data.firstIndex(of: JSONLines.newlineByte) {
- return decodedOrigin(from: Data(data[..<newlineIndex])) ?? .unknown
+ return decodedMetadata(from: Data(data[..<newlineIndex]))
}
if let prefix = metadataPrefix(from: data),
- let origin = decodedOrigin(from: prefix) {
- return origin
+ let metadata = decodedMetadata(from: prefix), metadata.source != nil {
+ return metadata
}
}
- return .unknown
+ return nil
}
- private static func decodedOrigin(from data: Data) -> WorkflowEventOrigin? {
+ private static func decodedMetadata(from data: Data) -> WorkflowRolloutMetadataPayload? {
guard let envelope = try? JSONDecoder().decode(WorkflowRolloutMetadataEnvelope.self, from: data),
envelope.type == "session_meta" else {
return nil
}
- return envelope.payload?.source?.origin
+ return envelope.payload
}
/// 只在外层或 payload 的完整字段边界补齐对象, 字符串和嵌套值交给 JSONDecoder 验证
@@ -293,12 +299,26 @@ private nonisolated struct WorkflowRolloutMetadataEnvelope: Decodable {
let payload: WorkflowRolloutMetadataPayload?
}
-private nonisolated struct WorkflowRolloutMetadataPayload: Decodable {
+nonisolated struct WorkflowRolloutMetadataPayload: Decodable {
+ let id: String?
+ let sessionId: String?
+ private let explicitParentThreadId: String?
+ var parentThreadId: String? {
+ explicitParentThreadId ?? source?.parentThreadId
+ }
+
let source: WorkflowRolloutSource?
+
+ private enum CodingKeys: String, CodingKey {
+ case id, source
+ case sessionId = "session_id"
+ case explicitParentThreadId = "parent_thread_id"
+ }
}
-private nonisolated struct WorkflowRolloutSource: Decodable {
+nonisolated struct WorkflowRolloutSource: Decodable {
let origin: WorkflowEventOrigin
+ var parentThreadId: String?
init(from decoder: Decoder) throws {
if let name = try? decoder.singleValueContainer().decode(String.self) {
@@ -311,10 +331,9 @@ private nonisolated struct WorkflowRolloutSource: Decodable {
return
}
if let subagentKey = container.allKeys.first(where: { $0.stringValue == "subagent" }) {
- origin = (try? container.decode(
- WorkflowRolloutSubagentSource.self,
- forKey: subagentKey
- ))?.origin ?? .unknown
+ let subagent = try? container.decode(WorkflowRolloutSubagentSource.self, forKey: subagentKey)
+ origin = subagent?.origin ?? .unknown
+ parentThreadId = subagent?.parentThreadId
return
}
if let customKey = container.allKeys.first(where: { $0.stringValue == "custom" }),
@@ -336,6 +355,7 @@ private nonisolated struct WorkflowRolloutSource: Decodable {
private nonisolated struct WorkflowRolloutSubagentSource: Decodable {
let origin: WorkflowEventOrigin
+ var parentThreadId: String?
init(from decoder: Decoder) throws {
if let name = try? decoder.singleValueContainer().decode(String.self) {
@@ -348,6 +368,11 @@ private nonisolated struct WorkflowRolloutSubagentSource: Decodable {
origin = .unknown
return
}
+ if let spawnKey = container.allKeys.first(where: { $0.stringValue == "thread_spawn" }),
+ let spawn = try? container.nestedContainer(keyedBy: WorkflowRolloutSourceKey.self, forKey: spawnKey),
+ let parentKey = spawn.allKeys.first(where: { $0.stringValue == "parent_thread_id" }) {
+ parentThreadId = try? spawn.decode(String.self, forKey: parentKey)
+ }
if let otherKey = container.allKeys.first(where: { $0.stringValue == "other" }) {
guard let name = try? container.decode(String.self, forKey: otherKey),
!name.isEmpty else {
diff --git a/CodexBarTests/ActivityProtectionStateStoreTests.swift b/CodexBarTests/ActivityProtectionStateStoreTests.swift
new file mode 100644
index 0000000..4009a51
--- /dev/null
+++ b/CodexBarTests/ActivityProtectionStateStoreTests.swift
@@ -0,0 +1,74 @@
+import Foundation
+import Testing
+
+struct ActivityProtectionStateStoreTests {
+ @Test func expiredRecordsArePrunedAtExactDeadline() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let store = ActivityProtectionStateStore(directoryURL: directory.url)
+ let record = makeRecord("task", markedAfter: 0, expiresAfter: 10)
+ try await store.apply(upserts: [record], now: TestFixtures.now)
+ #expect(await store.load(now: TestFixtures.now.addingTimeInterval(9))["task"] == record)
+ #expect(await store.load(now: TestFixtures.now.addingTimeInterval(10)).isEmpty)
+ let reopened = ActivityProtectionStateStore(directoryURL: directory.url)
+ #expect(await reopened.load(now: TestFixtures.now).isEmpty)
+ }
+
+ @Test func olderUpsertAndStaleRemovalCannotOverwriteNewerRecord() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let first = ActivityProtectionStateStore(directoryURL: directory.url)
+ let second = ActivityProtectionStateStore(directoryURL: directory.url)
+ let older = makeRecord("task", markedAfter: 0)
+ let newer = makeRecord("task", markedAfter: 5)
+ try await first.apply(upserts: [newer], now: TestFixtures.now)
+ try await second.apply(upserts: [older], removals: [ActivityProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: older.markedAt)], now: TestFixtures.now)
+ #expect(await first.load(now: TestFixtures.now)["task"] == newer)
+ try await second.apply(removals: [ActivityProtectionRemoval(taskIdentifier: "task", matchingMarkedAt: newer.markedAt)], now: TestFixtures.now)
+ #expect(await first.load(now: TestFixtures.now).isEmpty)
+ }
+
+ @Test func concurrentStoreInstancesPreserveIndependentRecords() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let first = ActivityProtectionStateStore(directoryURL: directory.url)
+ let second = ActivityProtectionStateStore(directoryURL: directory.url)
+ async let firstWrite: Void = first.apply(upserts: [makeRecord("first", markedAfter: 0)], now: TestFixtures.now)
+ async let secondWrite: Void = second.apply(upserts: [makeRecord("second", markedAfter: 0)], now: TestFixtures.now)
+ _ = try await (firstWrite, secondWrite)
+ #expect(await Set(first.load(now: TestFixtures.now).keys) == ["first", "second"])
+ }
+
+ @Test(arguments: ["not-json", #"{"schemaVersion":999,"records":[]}"#])
+ func invalidStateLoadsEmptyAndCanBeReplaced(_ content: String) async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ _ = try directory.write(content, to: "state.json")
+ let store = ActivityProtectionStateStore(directoryURL: directory.url)
+ #expect(await store.load(now: TestFixtures.now).isEmpty)
+ let record = makeRecord("task", markedAfter: 0)
+ try await store.apply(upserts: [record], now: TestFixtures.now)
+ #expect(await store.load(now: TestFixtures.now)["task"] == record)
+ }
+
+ @Test func duplicateStoredIdentifiersChooseLatestMarkAndFileIsPrivate() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let older = makeRecord("task", markedAfter: 0)
+ let newer = makeRecord("task", markedAfter: 5)
+ let records = try #require(String(data: JSONEncoder().encode([newer, older]), encoding: .utf8))
+ let url = try directory.write("{\"schemaVersion\":1,\"records\":\(records)}", to: "state.json")
+ let store = ActivityProtectionStateStore(directoryURL: directory.url)
+ #expect(await store.load(now: TestFixtures.now)["task"] == newer)
+ try await store.apply(now: TestFixtures.now)
+ let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
+ #expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o600)
+ }
+
+ private nonisolated func makeRecord(_ identifier: String, markedAfter: TimeInterval, expiresAfter: TimeInterval = 60) -> ActivityProtectionRecord {
+ ActivityProtectionRecord(
+ taskIdentifier: identifier, lastProgressAt: TestFixtures.now.addingTimeInterval(-3600),
+ markedAt: TestFixtures.now.addingTimeInterval(markedAfter), expiresAt: TestFixtures.now.addingTimeInterval(expiresAfter)
+ )
+ }
+}
diff --git a/CodexBarTests/CodexActivityTaskTests.swift b/CodexBarTests/CodexActivityTaskTests.swift
new file mode 100644
index 0000000..aed2a62
--- /dev/null
+++ b/CodexBarTests/CodexActivityTaskTests.swift
@@ -0,0 +1,151 @@
+import Foundation
+import Testing
+
+struct CodexActivityTaskTests {
+ @Test func anonymousTaskHasNoProtectionIdentityOrPreciseDuration() {
+ let task = makeTask(TestFixtures.event(session: nil))
+ #expect(task.key.isAnonymous)
+ #expect(task.key.activityProtectionIdentifier == nil)
+ #expect(!task.snapshot.showsPreciseDuration)
+ #expect(task.preciseDuration(until: TestFixtures.now.addingTimeInterval(60)) == nil)
+ }
+
+ @Test func taskIdentitySeparatesSessionsTurnsAndAnonymousProjects() {
+ #expect(CodexActivityTaskKey(event: TestFixtures.event()).sessionId == "session-a")
+ #expect(CodexActivityTaskKey(event: TestFixtures.event(turn: nil)).isSessionOnly)
+ let first = CodexActivityTaskKey.turn(session: "ab", turn: "c").activityProtectionIdentifier
+ let second = CodexActivityTaskKey.turn(session: "a", turn: "bc").activityProtectionIdentifier
+ #expect(first != second)
+ #expect(first?.count == 64)
+ #expect(first != CodexActivityTaskKey.session("ab").activityProtectionIdentifier)
+ }
+
+ @Test func preciseDurationRequiresKnownStartAndNonnegativeInterval() {
+ let task = makeTask()
+ #expect(task.preciseDuration(until: TestFixtures.now.addingTimeInterval(42)) == 42)
+ #expect(task.preciseDuration(until: TestFixtures.now.addingTimeInterval(-1)) == nil)
+ var restored = task
+ restored.startedAt = nil
+ #expect(restored.preciseDuration(until: TestFixtures.now) == nil)
+ }
+
+ @Test func mixedEffortIsStickyAndEmptyMetadataIsIgnored() {
+ var task = makeTask()
+ let sameEffortChanged = task.mergeEffort(" high ")
+ #expect(!sameEffortChanged)
+ let emptyEffortChanged = task.mergeEffort(" \n")
+ #expect(!emptyEffortChanged)
+ let differentEffortChanged = task.mergeEffort("low")
+ #expect(differentEffortChanged)
+ #expect(task.effort == "mixed")
+ let mixedEffortChanged = task.mergeEffort("high")
+ #expect(!mixedEffortChanged)
+ }
+
+ @Test func rolloutProgressDoesNotMoveHookOrderingBarrier() {
+ var task = makeTask()
+ task.recordProgress(at: TestFixtures.now.addingTimeInterval(30))
+ task.recordHookEvent(at: TestFixtures.now.addingTimeInterval(10))
+ #expect(task.lastHookEventAt == TestFixtures.now.addingTimeInterval(10))
+ #expect(task.lastProgressAt == TestFixtures.now.addingTimeInterval(30))
+ #expect(task.progressGeneration == 3)
+ }
+
+ @Test func subagentCountDeduplicatesAndRejectsOlderEvents() {
+ var task = makeTask()
+ #expect(task.snapshot.activeSubagentCount == 0)
+ task.recordSubagentActivity(agentId: "agent", isStarting: true, at: TestFixtures.now)
+ task.recordSubagentActivity(agentId: "agent", isStarting: true, at: TestFixtures.now)
+ #expect(task.snapshot.activeSubagentCount == 1)
+ task.recordSubagentActivity(agentId: "agent", isStarting: false, at: TestFixtures.now.addingTimeInterval(2))
+ task.recordSubagentActivity(agentId: "agent", isStarting: true, at: TestFixtures.now.addingTimeInterval(1))
+ #expect(task.snapshot.activeSubagentCount == 0)
+ }
+
+ @Test func missingSubagentIdentityAndUnmatchedStopMakeCountUnavailable() {
+ var missing = makeTask()
+ missing.recordSubagentActivity(agentId: nil, isStarting: true, at: TestFixtures.now)
+ #expect(missing.snapshot.activeSubagentCount == nil)
+ var unmatched = makeTask()
+ unmatched.recordSubagentActivity(agentId: "unknown", isStarting: false, at: TestFixtures.now)
+ #expect(unmatched.snapshot.activeSubagentCount == nil)
+ }
+
+ @Test func onlyUserApprovalTransitionsToWaiting() {
+ for reviewer in [CodexApprovalReviewer.user, .autoReview, .guardianSubagent] {
+ var task = makeTask(TestFixtures.event(reviewer: reviewer))
+ let transitioned = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest, reviewer: reviewer))
+ #expect(transitioned == (reviewer == .user))
+ #expect(task.state == (reviewer == .user ? .waitingApproval : .running))
+ }
+ }
+
+ @Test func unknownApprovalWaitsForContextOfSameExecution() {
+ var task = makeTask(TestFixtures.event(reviewer: nil))
+ let requestedWaiting = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest, reviewer: nil))
+ #expect(!requestedWaiting)
+ let otherOwner = CodexActivityExecutionKey(agentId: "other", turnId: "turn-a")
+ task.mergeApprovalContext(reviewer: .user, observedAt: TestFixtures.now, owner: otherOwner)
+ let resolvedOtherExecution = task.resolvePendingApprovals()
+ #expect(!resolvedOtherExecution)
+ #expect(task.state == .running)
+ let owner = CodexActivityExecutionKey(agentId: nil, turnId: "turn-a")
+ task.mergeApprovalContext(reviewer: .user, observedAt: TestFixtures.now, owner: owner)
+ let resolvedOwner = task.resolvePendingApprovals()
+ #expect(resolvedOwner)
+ #expect(task.state == .waitingApproval)
+ }
+
+ @Test func mainProgressCannotDismissSubagentApproval() {
+ var task = makeTask()
+ let approval = TestFixtures.event(.permissionRequest, agent: "agent", origin: .auxiliary)
+ let enteredWaiting = task.recordApprovalRequest(from: approval)
+ #expect(enteredWaiting)
+ task.resumeExecution(from: TestFixtures.event(.postToolUse, at: TestFixtures.now.addingTimeInterval(1)), latestEvent: .toolFinished)
+ #expect(task.state == .waitingApproval)
+ task.resumeExecution(from: TestFixtures.event(.postToolUse, at: TestFixtures.now.addingTimeInterval(2), agent: "agent", origin: .auxiliary), latestEvent: .toolFinished)
+ #expect(task.state == .running)
+ }
+
+ @Test func resolvingOneApprovalKeepsOtherExecutionWaiting() {
+ var task = makeTask()
+ let mainEnteredWaiting = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest))
+ #expect(mainEnteredWaiting)
+ let agentRequest = TestFixtures.event(.permissionRequest, at: TestFixtures.now.addingTimeInterval(1), agent: "agent", origin: .auxiliary)
+ let agentEnteredWaiting = task.recordApprovalRequest(from: agentRequest)
+ #expect(!agentEnteredWaiting)
+ task.finishExecution(CodexActivityExecutionKey(agentId: nil, turnId: "turn-a"), at: TestFixtures.now.addingTimeInterval(2))
+ #expect(task.state == .waitingApproval)
+ #expect(task.displayedApproval?.requestedAt == TestFixtures.now.addingTimeInterval(1))
+ task.finishExecution(CodexActivityExecutionKey(agentId: "agent", turnId: "turn-a"), at: TestFixtures.now.addingTimeInterval(3))
+ #expect(task.state == .running)
+ }
+
+ @Test func lateApprovalDoesNotUndoConfirmedExecutionProgress() {
+ var task = makeTask()
+ let progress = TestFixtures.now.addingTimeInterval(2)
+ task.resumeExecution(from: TestFixtures.event(.postToolUse, at: progress), latestEvent: .toolFinished)
+ let lateRequestChanged = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest))
+ #expect(!lateRequestChanged)
+ #expect(task.state == .running)
+ task.finishExecution(CodexActivityExecutionKey(agentId: nil, turnId: "turn-a"), at: progress)
+ #expect(!task.acceptsExecutionEvent(TestFixtures.event(.preToolUse, at: progress.addingTimeInterval(1))))
+ }
+
+ @Test func equalTimestampRolloutProgressDoesNotDismissApproval() {
+ var task = makeTask()
+ _ = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest))
+ let owner = CodexActivityExecutionKey(agentId: nil, turnId: "turn-a")
+ task.mergeExecutionProgress(at: TestFixtures.now, owner: owner)
+ #expect(task.state == .waitingApproval)
+ task.mergeExecutionProgress(at: TestFixtures.now.addingTimeInterval(0.001), owner: owner)
+ #expect(task.state == .running)
+ }
+
+ private func makeTask(_ event: WorkflowHookEvent = TestFixtures.event()) -> CodexActivityTask {
+ CodexActivityTask(
+ displayID: UUID(), key: CodexActivityTaskKey(event: event), event: event,
+ state: .running, latestEvent: .promptSubmitted, startedAt: event.timestamp, progressGeneration: 1
+ )
+ }
+}
diff --git a/CodexBarTests/CodexQuotaAndIdentityTests.swift b/CodexBarTests/CodexQuotaAndIdentityTests.swift
new file mode 100644
index 0000000..f014316
--- /dev/null
+++ b/CodexBarTests/CodexQuotaAndIdentityTests.swift
@@ -0,0 +1,92 @@
+import Foundation
+import Testing
+
+struct CodexQuotaAndIdentityTests {
+ @Test func resetCandidatesRequireExplicitStatusTypeAndExpiration() throws {
+ let summary = try TestFixtures.decode(RateLimitResetCreditsSummary.self, """
+ {"availableCount":5,"credits":[
+ {"id":"valid","status":"available","resetType":"codexRateLimits","expiresAt":200},
+ {"id":"used","status":"redeemed","resetType":"codexRateLimits","expiresAt":300},
+ {"id":"other","status":"available","resetType":"other","expiresAt":400},
+ {"id":"missing-expiration","status":"available","resetType":"codexRateLimits"},
+ {"id":"expired","status":"available","resetType":"codexRateLimits","expiresAt":100}
+ ]}
+ """)
+ #expect(summary.autoResetCandidates?.map(\.id) == ["valid", "expired"])
+ #expect(summary.availableExpirationDates(now: Date(timeIntervalSince1970: 100)) == [200, 400].map { Date(timeIntervalSince1970: $0) })
+ }
+
+ @Test func unavailableCreditDetailsDifferFromExplicitEmptyList() throws {
+ let missing = try TestFixtures.decode(RateLimitResetCreditsSummary.self, #"{"availableCount":1}"#)
+ let empty = try TestFixtures.decode(RateLimitResetCreditsSummary.self, #"{"availableCount":0,"credits":[]}"#)
+ #expect(missing.autoResetCandidates == nil)
+ #expect(empty.autoResetCandidates == [])
+ #expect(empty.availableExpirationDates(now: TestFixtures.now) == nil)
+ }
+
+ @Test func quotaWindowsClampPercentageAndKeepMissingDistinctFromZero() {
+ for (used, remaining) in [(-10, 100), (0, 100), (35, 65), (100, 0), (125, 0)] {
+ let window = QuotaWindow(kind: .primary, windowDurationMins: 300, usedPercent: used, resetsAt: nil)
+ #expect(window.remainingPercent == remaining)
+ #expect(window.hasData)
+ }
+ #expect(!QuotaWindow(kind: .primary, windowDurationMins: nil, usedPercent: nil, resetsAt: nil).hasData)
+ }
+
+ @Test func primaryLimitPrecedesAlphabeticalLimitsAndUsesMatchingCredits() throws {
+ let response = try TestFixtures.decode(AccountRateLimitsResponse.self, """
+ {"rateLimits":{"limitId":"codex","primary":{"usedPercent":99}},
+ "rateLimitsByLimitId":{
+ "alpha":{"primary":{"usedPercent":10}},
+ "codex":{"primary":{"usedPercent":20},"credits":{"balance":"12","hasCredits":true,"unlimited":false}},
+ "empty":{},
+ "zeta":{"secondary":{"usedPercent":30}}
+ }}
+ """)
+ let snapshot = try CodexQuotaSnapshot(accountResponse: accountResponse, rateLimitsResponse: response)
+ #expect(snapshot.limits.map(\.limitId) == ["codex", "alpha", "zeta"])
+ #expect(snapshot.codexLimit?.window(ofKind: .primary)?.usedPercent == 20)
+ #expect(snapshot.credits?.balance == "12")
+ }
+
+ @Test func validAccountWithoutQuotaIsDisplayableButNotTrusted() throws {
+ let snapshot = try CodexQuotaSnapshot(accountResponse: accountResponse, rateLimitsResponse: nil)
+ #expect(snapshot.limits.isEmpty)
+ #expect(!snapshot.hasTrustedData)
+ #expect(throws: (any Error).self) {
+ try CodexQuotaSnapshot(accountResponse: AccountReadResponse(account: nil), rateLimitsResponse: nil)
+ }
+ }
+
+ @Test func staleQuotaCannotCountAsTrustedData() throws {
+ let response = try TestFixtures.decode(AccountRateLimitsResponse.self, #"{"rateLimits":{"primary":{"usedPercent":10}}}"#)
+ #expect(try CodexQuotaSnapshot(accountResponse: accountResponse, rateLimitsResponse: response).hasTrustedData)
+ #expect(try !CodexQuotaSnapshot(accountResponse: accountResponse, rateLimitsResponse: response, isRateLimitsStale: true).hasTrustedData)
+ }
+
+ @Test func usageBucketsSumDuplicatesAndPreserveUnavailableState() throws {
+ let summary = try TestFixtures.decode(UsageSummary.self, "{}")
+ let date = try #require(CodexDateFormat.dayDate(from: "2026-09-15"))
+ let usage = CodexUsageSnapshot(summary: summary, dailyBuckets: [DailyUsageBucket(startDate: "2026-09-15", tokens: 2), DailyUsageBucket(startDate: "2026-09-15", tokens: 3)])
+ #expect(usage.tokenCount(on: date) == 5)
+ #expect(!CodexUsageSnapshot(summary: summary, dailyBuckets: nil).hasAppServerData)
+ #expect(CodexUsageSnapshot(summary: summary, dailyBuckets: []).hasAppServerData)
+ }
+
+ @Test func autoResetUUIDMatchesIndependentUUIDv5Vector() {
+ #expect(AutoResetIdentity.idempotencyKey(forCreditID: "credit-123") == "d0a84206-ba45-5a3b-9287-d1e14138cc5d")
+ #expect(AutoResetIdentity.idempotencyKey(forCreditID: "credit-123") != AutoResetIdentity.idempotencyKey(forCreditID: "credit-124"))
+ }
+
+ @Test func accountIdentityNormalizesEmailAndSeparatesAccountTypes() {
+ let first = CodexAccount(type: "chatgpt", email: " [email protected] \n", planType: "plus")
+ let second = CodexAccount(type: "chatgpt", email: "[email protected]", planType: "pro")
+ #expect(AutoResetIdentity.accountIdentity(for: first) == AutoResetIdentity.accountIdentity(for: second))
+ #expect(AutoResetIdentity.accountIdentity(for: first) == "chatgpt\u{0}[email protected]")
+ #expect(AutoResetIdentity.notificationToken(accountIdentity: "ab", creditID: "c") != AutoResetIdentity.notificationToken(accountIdentity: "a", creditID: "bc"))
+ }
+
+ private var accountResponse: AccountReadResponse {
+ AccountReadResponse(account: CodexAccount(type: "chatgpt", email: "[email protected]", planType: "plus"))
+ }
+}
diff --git a/CodexBarTests/CodexSessionLifecycleReaderTests.swift b/CodexBarTests/CodexSessionLifecycleReaderTests.swift
new file mode 100644
index 0000000..0f1d828
--- /dev/null
+++ b/CodexBarTests/CodexSessionLifecycleReaderTests.swift
@@ -0,0 +1,137 @@
+import Foundation
+import Testing
+
+struct CodexSessionLifecycleReaderTests {
+ @Test func completionHasStartDurationContextAndProgress() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ _ = try writeRollout(in: directory, lines: [context, start, completion])
+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)
+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(state.readStatus == .complete)
+ #expect(state.threadId == "session-a")
+ #expect(state.startedAt == Date(timeIntervalSince1970: 1789459200))
+ #expect(state.approvalReviewer == .user)
+ #expect(state.effort == "high")
+ guard case let .completed(at, duration) = state.terminal else {
+ Issue.record("Expected a completed turn")
+ return
+ }
+ #expect(at == Date(timeIntervalSince1970: 1789459260))
+ #expect(duration == 60)
+ }
+
+ @Test func partialCompletionIsNotPublishedUntilLineIsComplete() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let url = try writeRollout(in: directory, lines: [context, start])
+ try append(completion, to: url)
+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)
+ let partial = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(partial.readStatus == .incomplete)
+ #expect(partial.terminal == nil)
+ try append("\n", to: url)
+ let complete = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(complete.readStatus == .complete)
+ #expect(complete.terminal != nil)
+ }
+
+ @Test func corruptGapBlocksInactivityButExplicitTerminalStillResolves() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let url = try writeRollout(in: directory, lines: [context, start, "broken"])
+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)
+ let partial = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(partial.readStatus == .incomplete)
+ try append(completion + "\n", to: url)
+ let resolved = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(resolved.readStatus == .complete)
+ #expect(resolved.terminal != nil)
+ }
+
+ @Test func tokenUsageDoesNotResumeApprovalButAssistantOutputDoes() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let usage = #"{"timestamp":"2026-09-15T08:00:30Z","type":"token_usage_record","payload":{"turn_id":"turn-a"}}"#
+ let output = #"{"timestamp":"2026-09-15T08:00:40Z","type":"response_item","payload":{"type":"message","role":"assistant","#
+ + #""internal_chat_message_metadata_passthrough":{"turn_id":"turn-a"}}}"#
+ let url = try writeRollout(in: directory, lines: [context, start, usage])
+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)
+ let usageState = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(usageState.lastProgressAt != nil)
+ #expect(usageState.lastExecutionProgressAt == nil)
+ try append(output + "\n", to: url)
+ let outputState = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(outputState.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:00:40Z"))
+ }
+
+ @Test func missingOrMismatchedRolloutCannotSupplyCachedTerminal() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let url = try writeRollout(in: directory, lines: [context, start, completion])
+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)
+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)
+ try FileManager.default.removeItem(at: url)
+ let missing = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(missing.readStatus == .notFound)
+ #expect(missing.terminal == nil)
+ _ = try writeRollout(in: directory, lines: [context, completion], session: "other-session")
+ let freshReader = CodexSessionLifecycleReader(codexHomeURL: directory.url)
+ let mismatch = try #require(await freshReader.lifecycleStates(for: [reference]).first)
+ #expect(mismatch.readStatus == .notFound)
+ #expect(mismatch.terminal == nil)
+ }
+
+ @Test func fileReplacementDiscardsPriorTerminal() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let url = try writeRollout(in: directory, lines: [context, start, completion])
+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)
+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)
+ try Data((metadata(session: "session-a") + "\n" + context + "\n" + start + "\n").utf8).write(to: url, options: .atomic)
+ let replacement = try #require(await reader.lifecycleStates(for: [reference]).first)
+ #expect(replacement.readStatus == .complete)
+ #expect(replacement.terminal == nil)
+ }
+
+ @Test func archivedRolloutAndAlternateFilenameAreRecognized() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let filename = "archived_sessions/rollout-test-session-a_00000000-0000-0000-0000-000000000001.jsonl"
+ _ = try directory.write(metadata(session: "session-a") + "\n" + completion + "\n", to: filename)
+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)
+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)
+ }
+
+ private var reference: CodexActivityTurnReference {
+ CodexActivityTurnReference(sessionId: "session-a", turnId: "turn-a", startedAt: TestFixtures.now)
+ }
+
+ private var context: String {
+ #"{"timestamp":"2026-09-15T08:00:00Z","type":"turn_context","payload":{"turn_id":"turn-a","approvals_reviewer":"user","effort":" high "}}"#
+ }
+
+ private var start: String {
+ #"{"type":"event_msg","payload":{"type":"task_started","turn_id":"turn-a","started_at":1789459200}}"#
+ }
+
+ private var completion: String {
+ #"{"type":"event_msg","payload":{"type":"task_complete","turn_id":"turn-a","completed_at":1789459260,"duration_ms":60000}}"#
+ }
+
+ private func metadata(session: String) -> String {
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"\(session)\",\"source\":\"cli\"}}"
+ }
+
+ private func writeRollout(in directory: TestDirectory, lines: [String], session: String = "session-a") throws -> URL {
+ let datePath = CodexDateFormat.dayString(from: TestFixtures.now).replacingOccurrences(of: "-", with: "/")
+ return try directory.write(([metadata(session: session)] + lines).joined(separator: "\n") + "\n", to: "sessions/\(datePath)/rollout-test-session-a.jsonl")
+ }
+
+ private func append(_ text: String, to url: URL) throws {
+ let handle = try FileHandle(forWritingTo: url)
+ defer { try? handle.close() }
+ try handle.seekToEnd()
+ try handle.write(contentsOf: Data(text.utf8))
+ }
+}
diff --git a/CodexBarTests/CodexVersionAndProxyTests.swift b/CodexBarTests/CodexVersionAndProxyTests.swift
new file mode 100644
index 0000000..46f90da
--- /dev/null
+++ b/CodexBarTests/CodexVersionAndProxyTests.swift
@@ -0,0 +1,80 @@
+import Foundation
+import Testing
+
+struct CodexVersionAndProxyTests {
+ @Test(arguments: [
+ ("0.149.9", "0.150.0", false),
+ ("0.150.0", "0.150.0", true),
+ ("0.150.0-alpha.2", "0.150.0", false),
+ ("0.150.0-alpha.10", "0.150.0-alpha.2", true),
+ ("0.150.0-beta", "0.150.0-alpha.10", true),
+ ("1.0.0", "0.150.0", true),
+ ("codex-cli 0.150.0+build1", "0.150.0+build2", true)
+ ])
+ func minimumVersionComparesNumericAndPrereleaseComponents(_ version: String, _ minimum: String, _ expected: Bool) {
+ #expect(CodexCLIVersionReader.isVersion(version, atLeast: minimum) == expected)
+ }
+
+ @Test(arguments: ["unknown", "0.150", "0.150.x", "0.150.0-", "0.150.0-alpha..1"])
+ func unrecognizedVersionHasNoOrdering(_ version: String) {
+ #expect(CodexCLIVersionReader.isVersion(version, atLeast: "0.150.0") == nil)
+ }
+
+ @Test func installedUpgradeDoesNotReplaceActualRunningVersion() {
+ let item = CodexCLIVersionItem(source: .global, path: "/new/codex", version: "0.151.0")
+ let connection = CodexCLIConnectionInfo(source: .global, executablePath: "/running/codex", version: "0.149.0", openedAt: TestFixtures.now)
+ let display = CodexCLIVersionDisplay(item: item, connection: connection)
+ #expect(display.displayVersion == "0.149.0")
+ #expect(display.path == "/running/codex")
+ #expect(display.newerInstalledVersion == "0.151.0")
+ }
+
+ @Test func explicitMissingCLISourceDoesNotSilentlyFallback() throws {
+ let installations = CodexCLIInstallations(globalPath: nil, bundledPath: "/app/codex")
+ #expect(try CodexCLIResolver.command(from: installations).source == .bundled)
+ #expect(throws: (any Error).self) {
+ try CodexCLIResolver.command(from: installations, source: .global)
+ }
+ }
+
+ @Test func codexHomeUsesExplicitEnvironmentAndTrimsWhitespace() {
+ #expect(CodexCLIResolver.codexHomeDirectory(environment: ["CODEX_HOME": " /tmp/custom ", "HOME": "/tmp/home"]).path == "/tmp/custom")
+ #expect(CodexCLIResolver.codexHomeDirectory(environment: ["CODEX_HOME": " ", "HOME": "/tmp/home"]).path == "/tmp/home/.codex")
+ }
+
+ @Test(arguments: ["https://proxy.example", "host/path", "user@host", "host?query", "host#fragment", "host name", "[invalid]", "fe80::1%en0"])
+ func proxyRejectsAmbiguousHostInput(_ host: String) {
+ let configuration = CodexProxyConfiguration(host: host, port: "8080")
+ #expect(throws: (any Error).self) { try configuration.validated() }
+ }
+
+ @Test(arguments: ["0", "65536", "-1", "abc", "1.5"])
+ func proxyRejectsInvalidPorts(_ port: String) {
+ #expect(throws: (any Error).self) { try CodexProxyConfiguration(host: "localhost", port: port).validated() }
+ }
+
+ @Test func proxyNormalizesIPv6AndPortAndEncodesCredentials() throws {
+ let configuration = CodexProxyConfiguration(isEnabled: true, transport: .https, host: " ::1 ", port: " 08080 ", usesAuthentication: true, username: "user@name")
+ let validated = try configuration.validated()
+ #expect(validated.host == "[::1]")
+ #expect(validated.port == "8080")
+ let environment = try configuration.environment(overriding: ["PATH": "/bin", "NO_PROXY": "*"], password: "p:@/#")
+ for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "WS_PROXY", "WSS_PROXY"] {
+ #expect(environment[key] == "https://user%40name:p%3A%40%2F%23@[::1]:8080")
+ #expect(environment[key.lowercased()] == environment[key])
+ }
+ #expect(environment["NO_PROXY"] == "localhost,127.0.0.1,::1")
+ #expect(environment["PATH"] == "/bin")
+ }
+
+ @Test func disabledInvalidProxyPreservesInheritedEnvironment() throws {
+ let base = ["HTTPS_PROXY": "http://inherited:80", "NO_PROXY": "example.com"]
+ #expect(try CodexProxyConfiguration().environment(overriding: base, password: "") == base)
+ }
+
+ @Test(arguments: ["", "name:password", "name\n"])
+ func proxyRejectsInvalidAuthenticationUsernames(_ username: String) {
+ let configuration = CodexProxyConfiguration(host: "localhost", port: "80", usesAuthentication: true, username: username)
+ #expect(configuration.validationIssues.contains { $0.field == .username })
+ }
+}
diff --git a/CodexBarTests/DateAndPresentationTests.swift b/CodexBarTests/DateAndPresentationTests.swift
new file mode 100644
index 0000000..7ff794b
--- /dev/null
+++ b/CodexBarTests/DateAndPresentationTests.swift
@@ -0,0 +1,69 @@
+import Foundation
+import Testing
+
+struct DateAndPresentationTests {
+ @Test(arguments: ["2026-02-29", "2026-04-31", "2026-00-10", "2026-13-01", "2026-1-01", "2026-01-1", "0000-01-01", "garbage"])
+ func dateKeysRejectImpossibleOrNoncanonicalDates(_ value: String) {
+ #expect(CodexDateFormat.dayDate(from: value) == nil)
+ }
+
+ @Test func leapDayRoundTrips() throws {
+ let date = try #require(CodexDateFormat.dayDate(from: "2024-02-29"))
+ #expect(CodexDateFormat.dayString(from: date) == "2024-02-29")
+ }
+
+ @Test func weekGridStartsSundayAndLeavesFutureDaysBlankAcrossDST() throws {
+ var calendar = Calendar(identifier: .gregorian)
+ calendar.timeZone = try #require(TimeZone(identifier: "America/Los_Angeles"))
+ calendar.firstWeekday = 2
+ let today = try #require(calendar.date(from: DateComponents(year: 2026, month: 3, day: 10, hour: 12)))
+ let grid = CodexWeekGrid.dates(columnCount: 2, today: today, calendar: calendar)
+ #expect(grid.count == 14)
+ #expect(grid.compactMap(\.self).count == 10)
+ #expect(try calendar.component(.weekday, from: #require(grid[0])) == 1)
+ #expect(try calendar.component(.weekday, from: #require(grid[7])) == 1)
+ #expect(grid.suffix(4).allSatisfy { $0 == nil })
+ #expect(CodexWeekGrid.dates(columnCount: 0, today: today, calendar: calendar).isEmpty)
+ }
+
+ @Test func heatmapDistinguishesTodayPendingFromUnavailableAndHistoricalZero() throws {
+ let today = try #require(CodexDateFormat.dayDate(from: "2026-09-15"))
+ let summary = try TestFixtures.decode(UsageSummary.self, "{}")
+ let usage = CodexUsageSnapshot(summary: summary, dailyBuckets: [])
+ let grid = UsageHeatmapDay.grid(usage: usage, workflow: .empty, showsWorkflow: true, columnCount: 2, today: today).compactMap(\.self)
+ #expect(grid.last?.tokenState == .pending)
+ #expect(grid.first?.tokenState == .available(0))
+ let unavailable = UsageHeatmapDay.grid(usage: nil, workflow: .empty, showsWorkflow: true, columnCount: 2, today: today).compactMap(\.self)
+ #expect(unavailable.allSatisfy { $0.tokenState == .unavailable })
+ let hiddenToday = UsageHeatmapDay.grid(usage: usage, workflow: .empty, showsWorkflow: false, columnCount: 2, today: today).compactMap(\.self)
+ #expect(!hiddenToday.contains { $0.startDate == "2026-09-15" })
+ }
+
+ @Test func statusItemTerminalExpiresAtTenSecondsWhileCardKeepsHistory() {
+ let completion = CodexActivityCompletion(id: UUID(), isAnonymous: false, projectName: nil, modelName: nil, effort: nil, completedAt: TestFixtures.now, duration: 30)
+ let snapshot = CodexActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])
+ #expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(9.999)) == .completed(completion))
+ #expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(10)) == .idle)
+ #expect(snapshot.primaryActivity == .completed(completion))
+ #expect(snapshot.hasTaskCenterContent)
+ #expect(!snapshot.hasActiveTasks)
+ }
+
+ @Test func waitingTaskTakesPriorityAndAnonymousTasksRemainVisible() {
+ let waiting = task(isAnonymous: true)
+ let running = task(isAnonymous: false)
+ let snapshot = CodexActivitySnapshot(waitingTasks: [waiting], runningTasks: [running], recentCompletions: [], recentTerminations: [])
+ #expect(snapshot.primaryActivity == .waiting(waiting))
+ #expect(snapshot.activeCount == 2)
+ #expect(snapshot.statusItemActivityExpiration == nil)
+ }
+
+ private func task(isAnonymous: Bool) -> CodexActivityTaskSnapshot {
+ CodexActivityTaskSnapshot(
+ id: UUID(), isAnonymous: isAnonymous, latestEvent: .promptSubmitted,
+ projectName: nil, modelName: nil, effort: nil, toolName: nil,
+ startedAt: TestFixtures.now, stateChangedAt: TestFixtures.now,
+ showsPreciseDuration: !isAnonymous, activeSubagentCount: nil
+ )
+ }
+}
diff --git a/CodexBarTests/HookEventTailReaderTests.swift b/CodexBarTests/HookEventTailReaderTests.swift
new file mode 100644
index 0000000..1df8bb8
--- /dev/null
+++ b/CodexBarTests/HookEventTailReaderTests.swift
@@ -0,0 +1,131 @@
+import Foundation
+import Testing
+
+struct HookEventTailReaderTests {
+ @Test func bootstrapFiltersRetentionAndLiveDrainDoesNotReplayOldEvents() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let recorder = HookBatchRecorder()
+ let now = TestFixtures.now
+ let old = TestFixtures.event(at: now.addingTimeInterval(-86401), turn: "old")
+ let current = TestFixtures.event(at: now, turn: "current")
+ let path = "\(WorkflowStorage.dateKey(for: now)).jsonl"
+ let url = try directory.write(old.jsonLineData() + current.jsonLineData(), to: path)
+ let reader = HookEventTailReader(eventsDirectoryURL: directory.url, now: { now }, onBatch: recorder.receive)
+ await reader.start()
+ #expect(recorder.bootstrapEvents.map(\.turnId) == ["current"])
+ #expect(recorder.liveEvents.isEmpty)
+ let live = TestFixtures.event(.preToolUse, at: now.addingTimeInterval(1), turn: "live")
+ try append(live.jsonLineData(), to: url)
+ let first = await reader.drainNow()
+ let second = await reader.drainNow()
+ await reader.stop()
+ #expect(first == .completed)
+ #expect(second == .completed)
+ #expect(recorder.liveEvents.map(\.turnId) == ["live"])
+ }
+
+ @Test func partialLiveLineWaitsForNewlineAndIsDeliveredOnce() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let recorder = HookBatchRecorder()
+ let now = TestFixtures.now
+ let reader = HookEventTailReader(eventsDirectoryURL: directory.url, now: { now }, onBatch: recorder.receive)
+ await reader.start()
+ let line = try TestFixtures.event().jsonLineData()
+ let url = try directory.write(Data(line.dropLast()), to: "\(WorkflowStorage.dateKey(for: now)).jsonl")
+ let partial = await reader.drainNow()
+ #expect(recorder.liveEvents.isEmpty)
+ try append(Data([JSONLines.newlineByte]), to: url)
+ let completed = await reader.drainNow()
+ await reader.stop()
+ #expect(partial == .sourceUnavailable)
+ #expect(completed == .completed)
+ #expect(recorder.liveEvents.count == 1)
+ }
+
+ @Test func replacingEventFileRebootstrapsInsteadOfPublishingHistoricalTransitions() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let recorder = HookBatchRecorder()
+ let now = TestFixtures.now
+ let url = try directory.write(TestFixtures.event().jsonLineData(), to: "\(WorkflowStorage.dateKey(for: now)).jsonl")
+ let reader = HookEventTailReader(eventsDirectoryURL: directory.url, now: { now }, onBatch: recorder.receive)
+ await reader.start()
+ try TestFixtures.event(turn: "replacement").jsonLineData().write(to: url, options: .atomic)
+ let result = await reader.drainNow()
+ await reader.stop()
+ #expect(result == .completed)
+ #expect(recorder.bootstrapCount == 2)
+ #expect(recorder.bootstrapEvents.map(\.turnId) == ["replacement"])
+ #expect(recorder.liveEvents.isEmpty)
+ }
+
+ @Test func corruptedLineReportsUnhealthyWhilePreservingValidEvents() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let recorder = HookBatchRecorder()
+ let now = TestFixtures.now
+ _ = try directory.write(Data("broken\n".utf8) + TestFixtures.event().jsonLineData(), to: "\(WorkflowStorage.dateKey(for: now)).jsonl")
+ let reader = HookEventTailReader(eventsDirectoryURL: directory.url, now: { now }, onBatch: recorder.receive)
+ await reader.start()
+ let result = await reader.drainNow()
+ await reader.stop()
+ #expect(recorder.bootstrapEvents.count == 1)
+ #expect(recorder.degraded == true)
+ #expect(recorder.health.last == false)
+ #expect(result == .sourceUnavailable)
+ }
+
+ @Test func stoppedReaderRejectsDrainRequests() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let reader = HookEventTailReader(eventsDirectoryURL: directory.url, onBatch: { _ in })
+ #expect(await reader.drainNow() == .cancelled)
+ await reader.start()
+ await reader.stop()
+ #expect(await reader.drainNow() == .cancelled)
+ }
+
+ @Test func missingDirectoryReportsUnavailableDuringRetryBackoff() async throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let missing = directory.url.appendingPathComponent("missing")
+ let recorder = HookBatchRecorder()
+ let reader = HookEventTailReader(eventsDirectoryURL: missing, now: { TestFixtures.now }, onBatch: recorder.receive)
+ await reader.start()
+ let result = await reader.drainNow()
+ await reader.stop()
+ #expect(result == .sourceUnavailable)
+ #expect(recorder.degraded == true)
+ #expect(recorder.bootstrapEvents.isEmpty)
+ }
+
+ private func append(_ data: Data, to url: URL) throws {
+ let handle = try FileHandle(forWritingTo: url)
+ defer { try? handle.close() }
+ try handle.seekToEnd()
+ try handle.write(contentsOf: data)
+ }
+}
+
+@MainActor
+private final class HookBatchRecorder {
+ var bootstrapEvents: [WorkflowHookEvent] = []
+ var liveEvents: [WorkflowHookEvent] = []
+ var bootstrapCount = 0
+ var degraded: Bool?
+ var health: [Bool] = []
+
+ func receive(_ batch: HookEventBatch) {
+ switch batch {
+ case .bootstrapStart:
+ bootstrapCount += 1
+ bootstrapEvents.removeAll()
+ case let .bootstrapEvents(events): bootstrapEvents.append(contentsOf: events)
+ case let .bootstrapEnd(degraded, _): self.degraded = degraded
+ case let .live(events): liveEvents.append(contentsOf: events)
+ case let .sourceHealthChanged(healthy): health.append(healthy)
+ }
+ }
+}
diff --git a/CodexBarTests/JSONLinesAndHookTests.swift b/CodexBarTests/JSONLinesAndHookTests.swift
new file mode 100644
index 0000000..e3296e4
--- /dev/null
+++ b/CodexBarTests/JSONLinesAndHookTests.swift
@@ -0,0 +1,101 @@
+import Foundation
+import Testing
+
+struct JSONLinesAndHookTests {
+ @Test func corruptUTF8DoesNotDiscardNeighboringJSONLines() {
+ let data = Data("1\n \t\r\n".utf8) + Data([0xFF, 0x0A]) + Data("{broken}\n2\n3".utf8)
+ let result = JSONLines.decodeWithFailures(Int.self, from: data)
+ #expect(result.values == [1, 2, 3])
+ #expect(result.failedLineCount == 2)
+ }
+
+ @Test func leadingPartialLineIsDroppedAtByteBoundary() {
+ #expect(JSONLines.droppingLeadingPartialLine(Data("partial\n1\n2\n".utf8)) == Data("1\n2\n".utf8))
+ #expect(JSONLines.droppingLeadingPartialLine(Data("partial\n".utf8)).isEmpty)
+ #expect(JSONLines.droppingLeadingPartialLine(Data("partial".utf8)) == Data("partial".utf8))
+ }
+
+ @Test(arguments: ["PermissionRequest", "permissionRequest", "permission_request", "permission-request"])
+ func hookNamesNormalizeAcrossWireFormats(_ name: String) {
+ #expect(CodexHookEvent(eventName: name) == .permissionRequest)
+ }
+
+ @Test func unknownHookNamesAreNotGuessed() {
+ #expect(CodexHookEvent(eventName: "future_event") == nil)
+ }
+
+ @Test func hookDecodingToleratesMissingMetadataAndUnknownOrigins() throws {
+ let event = try TestFixtures.decode(WorkflowHookEvent.self, """
+ {"timestamp":"2026-09-15 12:00:00.000","event":" UserPromptSubmit ","origin":"future","session":" ","tool":123}
+ """)
+ #expect(event.hookEvent == .userPromptSubmit)
+ #expect(event.origin == .unknown)
+ #expect(event.sessionId == nil)
+ #expect(event.toolName == nil)
+ }
+
+ @Test(arguments: [#"{"event":"Stop"}"#, #"{"timestamp":"invalid","event":"Stop"}"#, #"{"timestamp":"2026-09-15 12:00:00.000","event":" "}"#])
+ func hookDecodingRequiresTimestampAndEvent(_ json: String) {
+ #expect(throws: (any Error).self) {
+ try TestFixtures.decode(WorkflowHookEvent.self, json)
+ }
+ }
+
+ @Test func hookSerializationRoundTripsEscapedMetadata() throws {
+ let event = WorkflowHookEvent(
+ timestamp: TestFixtures.now, name: "PreToolUse", origin: .main,
+ directoryPath: "/projects/a\"b", toolName: "line\nbreak", modelName: nil,
+ effort: nil, permissionMode: nil, approvalReviewer: nil,
+ sessionId: "session", turnId: "turn", agentId: "agent"
+ )
+ let data = try event.jsonLineData()
+ #expect(data.filter { $0 == JSONLines.newlineByte }.count == 1)
+ #expect(try JSONDecoder().decode(WorkflowHookEvent.self, from: data) == event)
+ }
+
+ @Test func guardianModelOnlyFillsUnknownOrigin() throws {
+ let unknown = try TestFixtures.decode(WorkflowHookEvent.self, #"{"timestamp":"2026-09-15 12:00:00.000","event":"Stop","model":"codex-auto-review"}"#)
+ let explicit = try TestFixtures.decode(WorkflowHookEvent.self, #"{"timestamp":"2026-09-15 12:00:00.000","event":"Stop","model":"codex-auto-review","origin":"main"}"#)
+ #expect(unknown.origin == .autoReview)
+ #expect(explicit.origin == .main)
+ }
+
+ @Test func terminalHookTimeoutsRespectCodexDeadline() {
+ for event in CodexHookEvent.allCases {
+ #expect(WorkflowHookEventRecorder.hookTimeoutSeconds(for: event) == ([.sessionEnd, .interrupt].contains(event) ? 3 : 5))
+ }
+ }
+
+ @Test(arguments: [
+ (#""cli""#, WorkflowEventOrigin.main),
+ (#"{"custom":"integration"}"#, .main),
+ (#"{"subagent":{"other":"guardian"}}"#, .autoReview),
+ (#"{"subagent":{"thread_spawn":{"parent_thread_id":"parent"}}}"#, .auxiliary),
+ (#"{"subagent":"review"}"#, .auxiliary),
+ (#""future""#, .unknown),
+ (#"{"subagent":{"other":""}}"#, .unknown)
+ ])
+ func rolloutSourcesAreClassifiedConservatively(_ json: String, _ expected: WorkflowEventOrigin) throws {
+ #expect(try TestFixtures.decode(WorkflowRolloutSource.self, json).origin == expected)
+ }
+
+ @Test func metadataReaderExtractsSourceBeforeLargeInstructions() throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let prefix = #"{"type":"session_meta","payload":{"id":"thread","source":"cli","instructions":""#
+ let url = try directory.write(prefix + String(repeating: "x", count: 300000) + "\"}}\n", to: "large.jsonl")
+ #expect(WorkflowRolloutMetadataReader.origin(transcriptPath: url.path) == .main)
+ #expect(WorkflowRolloutMetadataReader.metadata(transcriptPath: url.path)?.id == "thread")
+ }
+
+ @Test func metadataReaderDoesNotSearchOtherLinesOrBeyondBudget() throws {
+ let directory = try TestDirectory()
+ defer { try? directory.remove() }
+ let late = #"{"type":"session_meta","payload":{"source":"cli"}}"#
+ let wrongFirstLine = try directory.write("{}\n" + late + "\n", to: "wrong.jsonl")
+ #expect(WorkflowRolloutMetadataReader.origin(transcriptPath: wrongFirstLine.path) == .unknown)
+ let oversized = try directory.write(String(repeating: " ", count: 256 * 1024) + late + "\n", to: "oversized.jsonl")
+ #expect(WorkflowRolloutMetadataReader.origin(transcriptPath: oversized.path) == .unknown)
+ #expect(WorkflowRolloutMetadataReader.origin(transcriptPath: nil) == .unknown)
+ }
+}
diff --git a/CodexBarTests/RefreshTaskCoordinatorTests.swift b/CodexBarTests/RefreshTaskCoordinatorTests.swift
new file mode 100644
index 0000000..f0f199e
--- /dev/null
+++ b/CodexBarTests/RefreshTaskCoordinatorTests.swift
@@ -0,0 +1,94 @@
+import Foundation
+import Testing
+
+@Suite(.timeLimit(.minutes(1)))
+struct RefreshTaskCoordinatorTests {
+ @Test func supersededResultCannotCommitOrEndNewerRefresh() async {
+ let coordinator = RefreshTaskCoordinator()
+ defer { coordinator.cancel() }
+ let oldEntered = RefreshCheckpoint()
+ let oldRelease = RefreshCheckpoint()
+ let oldReturned = RefreshCheckpoint()
+ let newEntered = RefreshCheckpoint()
+ let newRelease = RefreshCheckpoint()
+ let newFinished = RefreshCheckpoint()
+ var committed: [Int] = []
+ var refreshing: [Bool] = []
+ coordinator.run(
+ setRefreshing: { refreshing.append($0) },
+ operation: {
+ oldEntered.signal()
+ await oldRelease.wait()
+ oldReturned.signal()
+ return 1
+ },
+ commit: { committed.append($0) }
+ )
+ await oldEntered.wait()
+ coordinator.run(
+ setRefreshing: {
+ refreshing.append($0)
+ if !$0 {
+ newFinished.signal()
+ }
+ },
+ operation: {
+ newEntered.signal()
+ await newRelease.wait()
+ return 2
+ },
+ commit: { committed.append($0) }
+ )
+ await newEntered.wait()
+ oldRelease.signal()
+ await oldReturned.wait()
+ #expect(committed.isEmpty)
+ #expect(refreshing == [true, true])
+ newRelease.signal()
+ await newFinished.wait()
+ #expect(committed == [2])
+ #expect(refreshing == [true, true, false])
+ }
+
+ @Test func cancellationInvalidatesGenerationEvenIfOperationReturns() async {
+ let coordinator = RefreshTaskCoordinator()
+ let entered = RefreshCheckpoint()
+ let release = RefreshCheckpoint()
+ let returned = RefreshCheckpoint()
+ var committed = false
+ let generation = coordinator.start { generation in
+ entered.signal()
+ await release.wait()
+ committed = coordinator.canCommit(generation)
+ returned.signal()
+ }
+ await entered.wait()
+ coordinator.cancel()
+ #expect(!coordinator.canCommit(generation))
+ release.signal()
+ await returned.wait()
+ #expect(!committed)
+ var finished = false
+ let didFinish = coordinator.finish(generation) { finished = true }
+ #expect(!didFinish)
+ #expect(!finished)
+ }
+}
+
+@MainActor
+private final class RefreshCheckpoint {
+ private var isSignaled = false
+ private var waiters: [CheckedContinuation<Void, Never>] = []
+
+ func wait() async {
+ guard !isSignaled else { return }
+ await withCheckedContinuation { waiters.append($0) }
+ }
+
+ func signal() {
+ isSignaled = true
+ let pending = waiters
+ waiters.removeAll()
+ pending.forEach { $0.resume() }
+ }
+}
diff --git a/CodexBarTests/SettingsAndMaintenanceTests.swift b/CodexBarTests/SettingsAndMaintenanceTests.swift
new file mode 100644
index 0000000..23e2309
--- /dev/null
+++ b/CodexBarTests/SettingsAndMaintenanceTests.swift
@@ -0,0 +1,130 @@
+import Foundation
+import Testing
+
+struct SettingsAndMaintenanceTests {
+ @Test func autoResetDefaultsOffAndRepairsInvalidLeadTime() throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ let defaults = preferences.defaults
+ let initial = AutoResetSettings(defaults: defaults)
+ #expect(!initial.isEnabled)
+ #expect(initial.leadTime == .thirtyMinutes)
+ defaults.set(123, forKey: "AutoReset.leadTimeSeconds")
+ let repaired = AutoResetSettings(defaults: defaults)
+ #expect(repaired.leadTime == .thirtyMinutes)
+ #expect(defaults.integer(forKey: "AutoReset.leadTimeSeconds") == 1800)
+ repaired.setEnabled(true)
+ repaired.setLeadTime(.sixHours)
+ initial.refresh()
+ #expect(initial.isEnabled)
+ #expect(initial.leadTime == .sixHours)
+ }
+
+ @Test func activityProtectionFallsBackToOneHourAndReloadsChanges() throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ preferences.defaults.set("invalid", forKey: "KeepAlive.abnormalTaskInactivitySeconds")
+ let settings = ActivityProtectionSettings(defaults: preferences.defaults)
+ #expect(settings.inactivityDuration == .oneHour)
+ settings.setInactivityDuration(.thirtyMinutes)
+ #expect(ActivityProtectionSettings(defaults: preferences.defaults).inactivityDuration == .thirtyMinutes)
+ preferences.defaults.set(7200, forKey: "KeepAlive.abnormalTaskInactivitySeconds")
+ settings.refresh()
+ #expect(settings.inactivityDuration == .twoHours)
+ }
+
+ @Test func disabledProxyCanStoreInvalidDraftAndUnauthenticatedPasswordIsDiscarded() throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ let configuration = CodexProxyConfiguration(host: "invalid/address", port: "")
+ try CodexProxyStore.save(configuration, password: "unused-secret", to: preferences.defaults)
+ let loaded = try CodexProxyStore.load(from: preferences.defaults)
+ let stored = try #require(loaded)
+ #expect(stored.configuration == configuration)
+ #expect(stored.password.isEmpty)
+ try CodexProxyStore.save(nil, password: "", to: preferences.defaults)
+ #expect(!CodexProxyStore.containsConfiguration(in: preferences.defaults))
+ }
+
+ @Test func invalidEnabledProxyDoesNotOverwriteLastSavedConfiguration() throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ let valid = CodexProxyConfiguration(isEnabled: true, host: "localhost", port: "8080")
+ try CodexProxyStore.save(valid, password: "", to: preferences.defaults)
+ #expect(throws: (any Error).self) {
+ try CodexProxyStore.save(CodexProxyConfiguration(isEnabled: true), password: "", to: preferences.defaults)
+ }
+ #expect(try CodexProxyStore.load(from: preferences.defaults)?.configuration == valid)
+ }
+
+ @Test func corruptStoredProxyIsReportedInsteadOfTreatedAsMissing() throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ preferences.defaults.set("broken", forKey: "CodexProxy.configuration")
+ #expect(CodexProxyStore.containsConfiguration(in: preferences.defaults))
+ #expect(throws: (any Error).self) { try CodexProxyStore.load(from: preferences.defaults) }
+ }
+
+ @Test func layoutRepairsDuplicateOrderAndAlwaysKeepsAVisibleSection() {
+ let layout = MainPanelLayout(orderedSections: [.usage, .usage, .activity], hiddenSections: Set(MainPanelSection.allCases))
+ #expect(layout.orderedSections == [.usage, .activity, .account, .quota, .status])
+ #expect(layout.visibleSections == [.usage])
+ let activityOnly = MainPanelLayout(orderedSections: [.activity], hiddenSections: Set(MainPanelSection.allCases).subtracting([.activity]))
+ #expect(activityOnly.disablingActivitySection().visibleSections == [.account])
+ }
+
+ @Test func hookDisableHidesActivityAndExplicitReenableRestoresIt() throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ let settings = MainPanelSettings(defaults: preferences.defaults)
+ settings.updateHookEnabled(false)
+ #expect(!settings.layout.isVisible(.activity))
+ settings.updateHookEnabled(true)
+ #expect(settings.layout.isVisible(.activity))
+ let undo = UndoManager()
+ settings.setSection(.activity, isVisible: false, undoManager: undo)
+ let restored = MainPanelSettings(defaults: preferences.defaults)
+ restored.updateHookEnabled(true)
+ #expect(!restored.layout.isVisible(.activity))
+ }
+
+ @Test func legacyMaintenanceStateRequiresRebuildAndNormalizesDateQueues() throws {
+ let state = try TestFixtures.decode(WorkflowMaintenanceState.self, #"{"pending":["2026-09-15","invalid","2026-09-14","2026-09-15"],"dirty":["2026-02-30","2026-09-14"]}"#)
+ #expect(state.schema == 0)
+ #expect(state.pending == ["2026-09-14", "2026-09-15"])
+ #expect(state.dirty == ["2026-09-14"])
+ }
+
+ @Test func fileReplacementResetsOffsetsHashesAndMarksDayDirty() throws {
+ let date = "2026-09-15"
+ var state = WorkflowMaintenanceState(days: [date: WorkflowDayMaintenanceState(
+ offset: 50, size: 60, corrupt: 2, sourceGeneration: "old", sourceIsFresh: false,
+ fileIdentifier: 1, boundaryHash: "old-hash", boundaryVerifiedAtNanoseconds: 42
+ )])
+ state.startNewSourceGeneration(for: date, isFresh: true, fileIdentifier: 2)
+ let day = try #require(state.days[date])
+ #expect(day.offset == 0)
+ #expect(day.corrupt == 0)
+ #expect(day.sourceGeneration != "old")
+ #expect(day.sourceIsFresh)
+ #expect(day.fileIdentifier == 2)
+ #expect(day.boundaryHash == nil)
+ #expect(day.boundaryVerifiedAtNanoseconds == nil)
+ #expect(state.dirty == [date])
+ }
+
+ @Test func repeatedPendingAndSourceUpdatesAreIdempotent() throws {
+ var state = WorkflowMaintenanceState()
+ let firstPending = state.markPending("2026-09-15")
+ let secondPending = state.markPending("2026-09-15")
+ #expect(firstPending)
+ #expect(!secondPending)
+ let firstSource = state.ensureSourceGeneration(for: "2026-09-15", fileIdentifier: 1)
+ let generation = try #require(state.days["2026-09-15"]?.sourceGeneration)
+ let secondSource = state.ensureSourceGeneration(for: "2026-09-15", fileIdentifier: 1)
+ #expect(firstSource)
+ #expect(!secondSource)
+ #expect(state.days["2026-09-15"]?.sourceGeneration == generation)
+ #expect(state.days["2026-09-15"]?.sourceIsFresh == false)
+ }
+}
diff --git a/CodexBarTests/TestSupport.swift b/CodexBarTests/TestSupport.swift
new file mode 100644
index 0000000..73df5b3
--- /dev/null
+++ b/CodexBarTests/TestSupport.swift
@@ -0,0 +1,79 @@
+import Foundation
+import Testing
+
+nonisolated enum TestFixtures {
+ static let now = Date(timeIntervalSince1970: 1789459200)
+
+ static func decode<T: Decodable>(_ type: T.Type, _ json: String) throws -> T {
+ try JSONDecoder().decode(type, from: Data(json.utf8))
+ }
+
+ static func event(
+ _ name: CodexHookEvent = .userPromptSubmit,
+ at timestamp: Date = now,
+ session: String? = "session-a",
+ turn: String? = "turn-a",
+ agent: String? = nil,
+ origin: WorkflowEventOrigin = .main,
+ reviewer: CodexApprovalReviewer? = .user
+ ) -> WorkflowHookEvent {
+ WorkflowHookEvent(
+ timestamp: timestamp, name: name.rawValue, origin: origin,
+ directoryPath: "/projects/example", toolName: "exec_command", modelName: "gpt-5",
+ effort: "high", permissionMode: nil, approvalReviewer: reviewer,
+ sessionId: session, turnId: turn, agentId: agent
+ )
+ }
+
+ static func aggregate(
+ generation: String? = "generation-a",
+ fresh: Bool = false,
+ events: Int = 2,
+ turns: Int = 1
+ ) -> WorkflowDailyAggregate {
+ var aggregate = WorkflowDailyAggregate(date: "2026-09-15", sourceGeneration: generation, sourceIsFresh: fresh)
+ aggregate.eventCount = events
+ aggregate.turnCount = turns
+ aggregate.sessionCount = 1
+ aggregate.sessionIds = nil
+ aggregate.turnIds = nil
+ return aggregate
+ }
+}
+
+nonisolated struct TestDirectory {
+ let url: URL
+
+ init() throws {
+ url = FileManager.default.temporaryDirectory.appendingPathComponent("CodexBarTests-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ }
+
+ func write(_ data: Data, to relativePath: String) throws -> URL {
+ let destination = url.appendingPathComponent(relativePath)
+ try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try data.write(to: destination)
+ return destination
+ }
+
+ func write(_ text: String, to relativePath: String) throws -> URL {
+ try write(Data(text.utf8), to: relativePath)
+ }
+
+ func remove() throws {
+ try FileManager.default.removeItem(at: url)
+ }
+}
+
+struct TestPreferences {
+ let suite = "app.zabrian.codexbar.tests.\(UUID().uuidString)"
+ let defaults: UserDefaults
+
+ init() throws {
+ defaults = try #require(UserDefaults(suiteName: suite))
+ }
+
+ func remove() {
+ defaults.removePersistentDomain(forName: suite)
+ }
+}
diff --git a/CodexBarTests/WorkflowAggregationTests.swift b/CodexBarTests/WorkflowAggregationTests.swift
new file mode 100644
index 0000000..aad4aa2
--- /dev/null
+++ b/CodexBarTests/WorkflowAggregationTests.swift
@@ -0,0 +1,149 @@
+import Foundation
+import Testing
+
+struct WorkflowAggregationTests {
+ @Test func missingHookCountsRemainUnavailableThroughBothStorageFormats() throws {
+ let aggregate = try TestFixtures.decode(WorkflowDailyAggregate.self, #"{"date":"2026-09-15","stopCount":0}"#)
+ #expect(aggregate.eventCount == nil)
+ #expect(aggregate.interruptCount == nil)
+ #expect(aggregate.stopCount == 0)
+ let local = try JSONDecoder().decode(WorkflowDailyAggregate.self, from: aggregate.jsonLineData())
+ let synced = try JSONDecoder().decode(WorkflowSyncedDailyAggregate.self, from: aggregate.syncedAggregate.jsonLineData())
+ #expect(local == aggregate)
+ #expect(synced.interruptCount == nil)
+ #expect(synced.stopCount == 0)
+ }
+
+ @Test func eventPairsAndIdentifiersAreCountedWithoutDoubleCounting() {
+ var accumulator = makeAccumulator()
+ for name in [CodexHookEvent.sessionStart, .userPromptSubmit, .preToolUse, .postToolUse, .preCompact, .postCompact, .subagentStart, .subagentStop] {
+ accumulator.record(TestFixtures.event(name))
+ }
+ accumulator.record(TestFixtures.event(.stop, session: "terminal-only", turn: "terminal-only"))
+ accumulator.record(TestFixtures.event(.interrupt, session: "interrupt-only", turn: "interrupt-only"))
+ let retained = accumulator.finalized(identifierStorage: .retained)
+ let compacted = accumulator.finalized(identifierStorage: .compacted)
+ #expect(retained.eventCount == 10)
+ #expect(retained.sessionIds == ["interrupt-only", "session-a", "terminal-only"])
+ #expect(retained.turnIds == ["turn-a"])
+ #expect(retained.metrics.toolCallCount == 1)
+ #expect(retained.metrics.contextCompactionCount == 1)
+ #expect(retained.metrics.subagentCount == 1)
+ #expect(retained.metrics.interruptCount == 1)
+ #expect(retained.metrics == compacted.metrics)
+ #expect(compacted.sessionIds == nil)
+ #expect(compacted.turnIds == nil)
+ #expect(!compacted.supportsIncrementalAggregation)
+ }
+
+ @Test func incrementalAggregationMatchesFullReplay() {
+ let firstEvents = [TestFixtures.event(.sessionStart), TestFixtures.event()]
+ let laterEvents = [TestFixtures.event(.preToolUse), TestFixtures.event(turn: "turn-b")]
+ var full = makeAccumulator()
+ (firstEvents + laterEvents).forEach { full.record($0) }
+ var initial = makeAccumulator()
+ firstEvents.forEach { initial.record($0) }
+ var incremental = WorkflowDailyAccumulator(
+ appending: initial.finalized(identifierStorage: .retained), sourceGeneration: "source", sourceIsFresh: true
+ )
+ laterEvents.forEach { incremental.record($0) }
+ #expect(incremental.finalized(identifierStorage: .retained) == full.finalized(identifierStorage: .retained))
+ }
+
+ @Test func historicalAggregationIncludesAutoReviewEvents() {
+ var accumulator = makeAccumulator()
+ accumulator.record(TestFixtures.event(origin: .autoReview))
+ #expect(accumulator.finalized(identifierStorage: .compacted).metrics.turnCount == 1)
+ }
+
+ @Test func sessionEndAloneDoesNotCreateAnActiveSession() {
+ var accumulator = makeAccumulator()
+ accumulator.record(TestFixtures.event(.sessionEnd, turn: nil))
+ let aggregate = accumulator.finalized(identifierStorage: .compacted)
+ #expect(aggregate.sessionEndCount == 1)
+ #expect(aggregate.metrics.sessionCount == 0)
+ #expect(aggregate.metrics.turnCount == 0)
+ }
+
+ @Test func unavailableInterruptCountPropagatesAcrossDeviceMetrics() {
+ var known = TestFixtures.aggregate()
+ known.interruptCount = 3
+ var unknown = TestFixtures.aggregate()
+ unknown.interruptCount = nil
+ #expect(known.metrics.adding(unknown.metrics).interruptCount == nil)
+ #expect(known.metrics.adding(known.metrics).interruptCount == 6)
+ }
+
+ @Test func modelRankingHasDeterministicTiesAndIgnoresZeroCounts() {
+ var aggregate = TestFixtures.aggregate()
+ aggregate.modelCounts = ["z-model": 3, "a-model": 3, "unused": 0]
+ #expect(aggregate.metrics.mostUsedModel == "a-model")
+ aggregate.modelCounts = ["unused": 0]
+ #expect(aggregate.metrics.mostUsedModel == nil)
+ }
+
+ @Test func compactingLegacyIdentifiersPreservesUniqueCounts() throws {
+ var aggregate = try TestFixtures.decode(WorkflowDailyAggregate.self, """
+ {"date":"2026-09-15","sessionCount":0,"sessionIds":["a","a","b"],"turnIds":["x","x"],"stopCount":9}
+ """)
+ aggregate.normalizeIdentifierStorage(retainsIdentifiers: false)
+ #expect(aggregate.sessionCount == 2)
+ #expect(aggregate.turnCount == 1)
+ #expect(aggregate.sessionIds == nil)
+ }
+
+ @Test func syncExportContainsCountsWithoutRawTaskIdentifiers() throws {
+ var accumulator = makeAccumulator()
+ accumulator.record(TestFixtures.event())
+ let data = try accumulator.finalized(identifierStorage: .retained).syncedAggregate.jsonLineData()
+ let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
+ #expect(object["sessionIds"] == nil)
+ #expect(object["turnIds"] == nil)
+ #expect(object["sessionCount"] as? Int == 1)
+ let text = try #require(String(data: data, encoding: .utf8))
+ #expect(!text.contains("session-a"))
+ }
+
+ private func makeAccumulator() -> WorkflowDailyAccumulator {
+ WorkflowDailyAccumulator(rebuilding: "2026-09-15", sourceGeneration: "source", sourceIsFresh: true, hookCountAvailability: .all)
+ }
+}
+
+struct WorkflowMergeTests {
+ @Test func sameGenerationUsesOneMostCompleteContribution() {
+ let local = TestFixtures.aggregate(events: 2, turns: 1)
+ let remote = record(TestFixtures.aggregate(events: 4, turns: 2))
+ #expect(snapshot(local, [remote]).dailyMetrics.first?.turnCount == 2)
+ #expect(snapshot(TestFixtures.aggregate(events: 6, turns: 3), [remote]).dailyMetrics.first?.turnCount == 3)
+ }
+
+ @Test func freshIndependentGenerationAddsToPreviousContribution() {
+ let local = TestFixtures.aggregate(generation: "new", fresh: true, turns: 2)
+ #expect(snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 5)
+ }
+
+ @Test func unverifiedLocalGenerationDoesNotDoubleCountRemoteHistory() {
+ let local = TestFixtures.aggregate(generation: "unknown", fresh: false, turns: 2)
+ #expect(snapshot(local, [record(TestFixtures.aggregate(turns: 3))]).dailyMetrics.first?.turnCount == 3)
+ }
+
+ @Test func legacyContentMatchDeduplicatesAndOtherDevicesStillAdd() {
+ let local = TestFixtures.aggregate()
+ let remote = record(TestFixtures.aggregate(generation: nil))
+ let otherDevice = record(TestFixtures.aggregate(turns: 4), device: "other")
+ #expect(snapshot(local, [remote, otherDevice]).dailyMetrics.first?.turnCount == 5)
+ }
+
+ @Test func remoteOnlyDaysRemainVisible() {
+ let result = WorkflowSnapshot(localAggregates: [], syncedRecords: [record(TestFixtures.aggregate(turns: 4))], currentDeviceId: "device")
+ #expect(result.dailyMetrics.first?.turnCount == 4)
+ }
+
+ private func record(_ aggregate: WorkflowDailyAggregate, device: String = "device") -> WorkflowSyncedDailyRecord {
+ WorkflowSyncedDailyRecord(deviceId: device, daily: aggregate.syncedAggregate)
+ }
+
+ private func snapshot(_ local: WorkflowDailyAggregate, _ remote: [WorkflowSyncedDailyRecord]) -> WorkflowSnapshot {
+ WorkflowSnapshot(localAggregates: [local], syncedRecords: remote, currentDeviceId: "device")
+ }
+}
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index 32b1d5e..470b40f 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 4.0.1
-CURRENT_PROJECT_VERSION = 101
+MARKETING_VERSION = 4.0.2
+CURRENT_PROJECT_VERSION = 102
diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.md
index f3c4893..0ba063f 100644
--- a/Docs/DeveloperGuide/activity-monitor.md
+++ b/Docs/DeveloperGuide/activity-monitor.md
@@ -41,7 +41,7 @@ rollout JSONL -> CodexSessionLifecycleReader ----------------------------+
| 其他终态确认 | rollout terminal | 无明确终态时保留待确认任务,到期清理 |
| effort | Hook recorder 回查 | rollout lifecycle backfill |
-各字段按上表中的来源解析。Hook 每轮读取后等待 2 秒,rollout 每轮对账后等待 1 秒。
+Hook 每轮读取后等待 2 秒,rollout 每轮对账后等待 1 秒。
### 快照与转场
@@ -143,10 +143,10 @@ actor 在 `await` 期间可以重入,因此 `isProcessingReads` 和 `hasPendin
- 默认每 1 秒检查一次
- 初始尾部窗口为 512 KiB
- effort 等 turn context 字段最多回查 8 MiB
-- 只解析生命周期、turn, progress, effort 和 reviewer
+- 只解析线程归属、生命周期、turn、progress、effort 和 reviewer
- 对话内容不进入活动模型或产品展示
-Hook 的 `Stop` 将任务标记为“正在收尾”,保留在活动列表。后续工具、审批等进展继续更新同一任务;rollout 的 `task_complete` 确认完成,满足转场时效和恢复条件时发布完成转场。
+Hook 的 `Stop` 将任务标记为“正在收尾”,保留在活动列表;仍有其他 Agent 等待用户批准时优先显示等待。后续工具、审批等进展继续更新同一任务;rollout 的完成记录确认本轮结束,满足转场时效和恢复条件时发布完成转场。
rollout 暂时不可读或无法关联 session、turn 时,任务继续等待对账。`Stop` 不启动终态超时;新 turn 或 `SessionEnd` 将旧任务移出活动列表,开始前 5 秒的快速终态查询,之后每 30 秒继续查询。迟到的 `Stop` 只更新待确认任务的元数据与进展,不恢复展示或重置窗口。
@@ -168,6 +168,8 @@ resume 可能继续很早以前创建的 session。快速路径找不到时,
文件被移到 archive 后,已缓存 URL 不存在会清除 cursor 并允许重新完整定位。
+文件名按线程 ID 精确匹配,允许线程 ID 后带一个下划线和 UUID 后缀。候选文件须唯一,且首条 `session_meta.id` 与目标线程一致;读取元数据时采用与 Hook recorder 相同的[有界首行解析](hook-and-aggregation.md#来源归一化)
+
### Rollout 读取预算
实时任务只需要活跃 turn 附近的 lifecycle,全量读取一个长期 session 会增加常驻 I/O。
@@ -184,20 +186,22 @@ rollout 坏行将当时尚未结束的 turn 标记为有覆盖缺口,后续重
每个 session 的文件游标保存独立的 `currentTurnId`,按 JSONL 文件顺序更新:
-- 外层 `type = "turn_context"`,或外层 `type = "event_msg"` 且 `payload.type = "task_started"` 时,以 `payload.turn_id` 建立上下文
-- 记录自带 `payload.turn_id` 时优先使用该字段;缺失时沿用游标上下文
-- 当前 turn 的 `task_complete` 或 `turn_aborted` 清空上下文;迟到的其他 turn 终态不清空它
+- 外层 `type = "turn_context"`,或外层 `type = "event_msg"` 且 `payload.type` 为 `task_started` 或 `turn_started` 时,以 `payload.turn_id` 建立上下文
+- `response_item` 优先使用 `payload.internal_chat_message_metadata_passthrough.turn_id`;其他进展记录使用 `payload.turn_id`,缺失时沿用游标上下文
+- 当前 turn 的 `task_complete`、`turn_complete` 或 `turn_aborted` 清空上下文;迟到的其他 turn 终态不清空它
- 文件截断或替换时重建游标,同时清空上下文和已缓存的生命周期
-进展记录包括外层 `type` 为 `response_item` 或 `token_usage_record` 的记录,以及外层为 `event_msg`、`payload.type` 为 `token_count`、`item_completed`、`agent_message`、`agent_reasoning`、`task_started`、`task_complete` 或 `turn_aborted` 的记录。时间依次取外层 `timestamp`、`payload.completed_at`、`payload.started_at`。
+进展记录包括外层 `type` 为 `response_item` 或 `token_usage_record` 的记录,以及外层为 `event_msg`、`payload.type` 为 `token_count`、`item_completed`、`agent_message`、`agent_reasoning`、`task_started`、`turn_started`、`task_complete`、`turn_complete` 或 `turn_aborted` 的记录。时间依次取外层 `timestamp`、`payload.completed_at`、`payload.started_at`。
记录须有可用时间和 turn 归属,本轮读取完整且时间晚于任务的 `lastProgressAt` 时才更新进展。`token_usage_record` 按活动记录处理,不比较 token 数量是否增加。缺少显式 turn 和游标上下文的记录不计入任务进展。
+能用于推断审批恢复的执行进展单独记录为 `lastExecutionProgressAt`:包括 `response_item` 中 `role = "assistant"` 的记录及类型为 `function_call_output`、`custom_tool_call_output`、`tool_search_output` 的工具结果,以及 `agent_message`、`agent_reasoning` 事件。只有同一 Agent/轮次中晚于审批请求的执行进展才清除该等待;用量记录等普通活动只更新任务进展时间。
+
### Rollout 解析字段
共享的 `CodexRolloutLineEnvelope` 只提取 turn context, lifecycle 和 progress 所需字段。prompt, response 和 tool 内容不会进入活动模型。
-终态要求 `payload.turn_id` 非空,并且本轮读取状态为 `complete`。外层 `type = "event_msg"` 时,`payload.type = "task_complete"` 配合有效的 `payload.completed_at` 确认完成;`payload.type = "turn_aborted"` 确认中断。完成时间使用 Unix 秒,`payload.duration_ms` 换算为秒后用于耗时展示;中断时间缺失时,活动任务使用对账时间,待确认任务使用移出活动列表的时间,结果均不早于任务最后活动时间。
+终态要求 `payload.turn_id` 非空,并且本轮读取状态为 `complete`。外层 `type = "event_msg"` 时,`payload.type` 为 `task_complete` 或 `turn_complete` 确认完成,完成时间优先使用有效的 `payload.completed_at`(Unix 秒),缺失或无效时使用外层 `timestamp`;两者均不可用时不确认完成。`payload.type = "turn_aborted"` 确认中断。非负且有限的 `payload.duration_ms` 换算为秒后用于耗时展示;中断时间缺失时,活动任务使用对账时间,待确认任务使用移出活动列表的时间,结果均不早于任务最后活动时间。
## 任务身份
@@ -223,7 +227,7 @@ subagent 事件更新父任务的 subagent 活动,不创建独立顶层任务
### 实时任务来源过滤
-`CodexActivityMonitor.apply` 先检查 `WorkflowHookEvent.origin`,再执行任务状态转换。来源归一化规则见 [Hook 来源归一化](hook-and-aggregation.md#来源归一化)
+`CodexActivityMonitor.apply` 先解析实时链路的有效来源,再执行任务状态转换。沿用缓存来源时,事件副本使用该来源进行过滤和执行身份判断,原始 JSONL 保持不变。来源归一化规则见 [Hook 来源归一化](hook-and-aggregation.md#来源归一化)
monitor 按精确的 `session ID + turn ID` 在内存中保存来源,保留 24 小时。Codex 的 subagent Hook 复用父 session ID,因此来源判定不扩大到整个 session。
@@ -252,21 +256,23 @@ monitor 按精确的 `session ID + turn ID` 在内存中保存来源,保留 24
### 迟到事件如何被拒绝
-任务保存 `lastHookEventAt` 和 `lastProgressAt`,`lastActivityAt` 直接读取 `lastProgressAt` 的值:
+Hook 顺序按 Agent/轮次隔离,任务整体进展另行汇总:
| 字段 | 来源与用途 |
| --- | --- |
-| `lastHookEventAt` | 已接受的最新 Hook 时间,用于拒绝迟到的 Hook 状态变化 |
+| execution 的 `lastHookEventAt` | 同一 Agent/轮次已接受的最新 Hook 时间,用于拒绝该执行的迟到状态变化 |
+| `lastMainHookEventAt` | 主 Agent 的最新 Hook 时间,用于顶层 prompt、中断及会话结束判断 |
+| execution 的 `lastExecutionProgressAt` | 同一执行的 Hook 恢复信号与 rollout 执行进展时间,用于审批恢复和迟到审批过滤 |
| `lastProgressAt` | Hook 与 rollout 的最新进展时间,用于异常会话保护 |
| `lastActivityAt` | 由 `lastProgressAt` 派生,用于展示排序、保留期和终态时间校正 |
-rollout 进展不会推进 `lastHookEventAt`。较晚的 rollout 记录先被读取时,仍可接受时间稍早但有效的 `PermissionRequest`、工具、压缩、中断或新 prompt 事件。接受这些 Hook 时,`lastProgressAt` 和 `lastActivityAt` 保持单调递增。
+rollout 进展不会推进 Hook 时钟,其他 Agent 的较晚事件也不阻止本 Agent 的合法事件。审批请求还须不早于同一执行已知的执行进展,并晚于上次审批请求;任务的 `lastProgressAt` 和 `lastActivityAt` 保持单调递增。
完成和终止共用内存中的 `recentlyEndedTaskAt` 记录结束时间。展示记录仍分别保存在完成和终止列表,保留 10 分钟;去重记忆保留 24 小时,不随展示记录一起删除。来源过滤移除记录时,从剩余终态记忆重新计算对应 session 别名的最新时间。
迟到事件按以下规则处理:
-- Hook 状态变化和审批请求统一按 `lastHookEventAt` 排序;早于最新 Hook 进展的审批请求不恢复等待
+- 工具、压缩、子 Agent 和审批 Hook 按执行归属检查时间;已确认终态的执行不接受新的状态变化
- 精确 turn 在终态记忆保留期间不允许重新创建;session 和匿名键只允许时间更新的新 prompt 复用
- `Stop` 命中多个候选时不猜测
- 已进入 terminal 去重记忆的 key 会清除异常顺序留下的恢复任务
@@ -290,7 +296,7 @@ rollout 进展不会推进 `lastHookEventAt`。较晚的 rollout 记录先被读
| 状态 | 含义 |
| --- | --- |
| `running` | Codex 正在处理当前 turn |
-| `waitingApproval` | 当前 turn 明确等待用户批准 |
+| `waitingApproval` | 任务内至少一个主 Agent 或子 Agent 的执行正在等待用户批准 |
| `suppressed` | 任务被异常会话保护隐藏,等待新进展恢复 |
`PermissionRequest` 只有在 reviewer 是用户时才进入 `waitingApproval`。自动审批或策略审批不会被视为用户等待。
@@ -310,8 +316,9 @@ rollout 进展不会推进 `lastHookEventAt`。较晚的 rollout 记录先被读
| 不存在 | 顶层 tool 或 compact | running | 恢复任务,startedAt 暂缺 |
| running | tool, compact, subagent progress | running | 更新 last progress 和 generation |
| running | `PermissionRequest` + reviewer user | waitingApproval | 发布 live waiting transition |
-| waitingApproval | tool、compact 或 subagent Hook 进展 | running | 清除待审批候选,更新活动和进展 |
-| running 或 waiting | `Stop` | running | 显示正在收尾,保留任务直到 rollout 确认终态 |
+| waitingApproval | 审批所属 Agent/轮次的有效 Hook 或 rollout 执行进展 | waitingApproval 或 running | 清除该执行的审批;仍有其他等待时保持等待 |
+| waitingApproval | 其他 Agent 的进展 | waitingApproval | 更新进展,保留等待及其工具展示 |
+| running 或 waiting | 顶层 `Stop` | running 或 waitingApproval | 清除主执行等待;仍有子 Agent 等待时继续显示等待,否则显示正在收尾 |
| active | 新 prompt 或 `SessionEnd` | pending terminal | 从快照移除并开始后台终态查询 |
| active、suppressed 或 pending terminal | `Interrupt` | terminated | 移除匹配任务、记录终止并清理保护状态和通知 |
| running | 满足保护条件且静默达到阈值 | suppressed | 隐藏并退出防睡眠贡献 |
@@ -320,13 +327,13 @@ rollout 进展不会推进 `lastHookEventAt`。较晚的 rollout 记录先被读
### 等待批准的两阶段确认
-任务的 `approvalReviewer` 来自 Hook 记录或 rollout 的 `payload.approvals_reviewer`,取值为 `user`、`auto_review` 或 `guardian_subagent`
+任务按 Agent/轮次保存执行记录,主 Agent 使用无 `agentId` 的明确主来源身份,子 Agent 使用自身线程 ID。每个执行独立保存 `approvalReviewer`,来源为 Hook 或 rollout 的 `payload.approvals_reviewer`,取值为 `user`、`auto_review` 或 `guardian_subagent`
-收到 `PermissionRequest` 时,任务已有 reviewer 为 `user` 就立即进入等待。任务 reviewer 未知时保存 `pendingApprovalRequestedAt`,由 rollout 补齐后决定状态。自动审批路由保持当前状态,并在对账时清除候选。
+每个执行只有一份可选审批记录:`pending` 表示路由待确认,`waiting` 表示等待用户。收到 `PermissionRequest` 后,已知 reviewer 为 `user` 时立即确认等待,未知时保留候选;确认为自动审批时清除候选。请求时间、工具名和顺序随审批记录保存,重复请求不覆盖正在等待的展示信息。
-有效的工具、压缩、子 Agent 或顶层 `Stop` Hook 将任务恢复为运行中,并清除待审批候选;随后补齐 reviewer 不会重新打开已清除的等待。rollout 进展只更新时间,不单独解除审批等待。
+只有身份可靠且属于同一 Agent/轮次的进展才能清除该执行的审批。有效的工具、压缩、子 Agent 生命周期或顶层 `Stop` Hook 按现有恢复规则处理;rollout 执行进展须严格晚于请求时间。已清除的候选不会因后续 reviewer 回填重新进入等待,子线程的明确 rollout 终态也会清除对应执行的等待。
-审批等待按任务维护。同一任务内其他并行工具或子 Agent 的有效 Hook 进展也会解除等待。
+任务中仍有任意用户等待时保持 `waitingApproval`,展示请求时间最早的等待;同时间按记录顺序选择。等待持续期间切换展示对象不重置任务的等待起点。其他 Agent 的进展和身份不完整的进展不解除已知等待。同一 Agent/轮次内的并行调用仍共享审批记录,恢复依据是进展推断。
### Effort 合并
@@ -334,11 +341,11 @@ rollout 进展不会推进 `lastHookEventAt`。较晚的 rollout 记录先被读
### Subagent 计数可靠性
-subagent 的 turn ID 属于 subagent 自己,父任务只能通过共享 session 关联。
+子 Agent Hook 的 `agent_id` 和 `turn_id` 标识子线程及其轮次。monitor 读取相关子线程 rollout,使用 `session_meta.id` 校验线程,使用 `parent_thread_id`(缺失时取 `source.subagent.thread_spawn.parent_thread_id`)校验父线程信息,并通过上下文或开始事件中的 `root_turn_id` 关联根任务轮次。`root_turn_id` 指向根轮次,不是直接父 Agent 的轮次。
-子任务 Hook 关联同 session 唯一的活动父任务。存在待确认旧任务时,`SubagentStart` 可以关联;其他子任务事件要求其 `agent_id` 已记录在当前父任务中。父任务不唯一时忽略事件。
+根会话 ID 优先取 `session_meta.session_id`,缺失时使用已有关联或该子轮次 Hook 中唯一的根会话 ID。关联前暂存身份完整的子事件,确认后按原始来源重放;字段不足或关联冲突时不回退到当前唯一活动任务。子 Agent 活动只更新匹配的活动根任务,不创建独立卡片。
-计数可靠性由是否已知 prompt 起点初始化。缺少 `agent_id`,或首次观察某个 agent 就收到 stop 时,可靠性设为 `false`,UI 隐藏数量。每个 agent 按自己的事件时间更新运行状态。
+活跃子 Agent 数按已关联的 `SubagentStart` 和 `SubagentStop` 维护,与审批记录分开。计数可靠性由是否已知 prompt 起点初始化;首次观察某个 Agent 就收到 stop 时设为 `false`,UI 隐藏数量。每个 Agent 按自己的事件时间更新运行状态,已确认结束的执行不会被迟到的 start 计为运行。
## 快照优先级
@@ -369,7 +376,7 @@ monitor 每秒检查 rollout,并在清理 deadline 到达时刷新。
`presentationPublisher` 发布当前快照和本轮仍有效的 `terminalEvents`,供任务流光使用。展示事件包含匿名任务;通知使用独立的 `transitionPublisher`
-完成转场和终态短提示要求结束时间距当前不超过 10 秒,并且不早于各自的恢复界限。直接由 Hook 确认的等待转场也检查 10 秒时效;rollout 补齐 reviewer 后确认的等待转场只检查请求时间不早于 `sessionTransitionNotBefore`。
+完成转场和终态短提示要求结束时间距当前不超过 10 秒,并且不早于各自的恢复界限。Hook 直接确认或 rollout 补齐 reviewer 后确认的等待转场,均要求任务进入等待的时间距当前不超过 10 秒且不早于 `sessionTransitionNotBefore`。
历史重读、睡眠恢复和数据源健康状态变化时清空待发布事件,并更新 `terminalPresentationNotBefore`。bootstrap、恢复对账和数据源不健康期间暂停发布。
@@ -535,8 +542,9 @@ Monitor 为 reader 和异步恢复任务维护 generation:
- 连续 3 次不稳定后进入 degraded,不启动异常静默判断
- 新 prompt 替换旧 turn,分别验证终态在前 5 秒及之后到达时的补分类
- 同 session 多个 terminal 候选时不猜测 `Stop` 归属
-- 同一组审批 Hook 和稍晚的 rollout 进展以两种顺序读取,均显示橙色等待且只发布一次等待转场
-- rollout 先推进进展后,工具、压缩或子 Agent Hook 仍解除等待并更新活动;迟到审批或 reviewer 回填不恢复已清除的等待,中断和 `SessionEnd` 仍能结束对应任务
+- 主 Agent 与多个子 Agent 同时等待,逐个恢复时只清除自己的等待,最后一项清除后才切回运行
+- 普通 rollout 活动保持等待;同一执行的较新执行进展清除等待,同时间进展保持等待,迟到审批或 reviewer 回填不恢复已清除的等待
+- 子线程 `root_turn_id` 指向旧轮次时不更新新任务;关联缺失或冲突时不猜测父任务
- 新 turn 边界后无 `turn_id` 的记录只推进新任务;迟到旧终态、分批读取和文件替换不串用上下文
- reviewer 缺失后由 rollout 确认为 user 才进入等待
- auto review 始终不发布等待 transition
@@ -552,6 +560,7 @@ Monitor 为 reader 和异步恢复任务维护 generation:
- [`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)
- [`CodexActivityTask.swift`](../../CodexBar/Services/Workflow/CodexActivityTask.swift)
+- [`CodexActivitySubagentTracking.swift`](../../CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift)
- [`CodexActivityTerminalResolution.swift`](../../CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift)
- [`HookEventTailReader.swift`](../../CodexBar/Services/Workflow/HookEventTailReader.swift)
- [`CodexSessionLifecycleReader.swift`](../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift)
diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.md
index 3630f23..15b2f3b 100644
--- a/Docs/DeveloperGuide/architecture.md
+++ b/Docs/DeveloperGuide/architecture.md
@@ -8,14 +8,15 @@
CodexBar 是 macOS 15+ 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVVM。
-工程只有 `CodexBar` scheme,包含两个 target:
+工程只有 `CodexBar` scheme,包含三个 target:
| Target | 职责 |
| --- | --- |
| `CodexBar` | 菜单栏 UI、Codex 数据采集、自动重置、通知、同步和系统电源编排 |
| `CodexBarHelper` | 以 root LaunchDaemon 运行,负责固定的系统睡眠开关和自动重置唤醒计划 |
+| `CodexBarTests` | 无 App 宿主的 Swift Testing 单元测试,直接编译生产源码并隔离测试数据 |
-两个 target 通过 [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 共享 XPC 协议。
+App 与 helper 通过 [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 共享 XPC 协议。
App 使用 Sparkle 检查更新。工程默认启用 `MainActor` 隔离,Debug 和 Release 使用不同的 App 与 CodexBarHelper bundle ID。
diff --git a/Docs/DeveloperGuide/data-and-privacy.md b/Docs/DeveloperGuide/data-and-privacy.md
index 59e76e5..4acc3d5 100644
--- a/Docs/DeveloperGuide/data-and-privacy.md
+++ b/Docs/DeveloperGuide/data-and-privacy.md
@@ -19,12 +19,12 @@ Codex hook stdin / rollout / app-server
|
v
普通用户权限的 CodexBar
- | |
- v v
- CloudKit private DB 受限 XPC 接口
- |
- v
- root CodexBarHelper
+ | |
+ v v
+ CloudKit private DB 受限 XPC 接口
+ |
+ v
+ CodexBarHelper
```
边界含义如下:
@@ -76,7 +76,7 @@ Hook 子进程从 stdin 提取:
- permission 和 reviewer
- session, turn 和 agent 身份
-Hook 子进程优先从 `transcript_path` 指向的 rollout 第一条完整 `session_meta` 中提取并归一化来源。rollout 来源为 `unknown` 时,stdin 中已经提取的 model 只有精确匹配 `codex-auto-review` 才归类为 `autoReview`。JSONL 的来源字段只持久化 `main`, `autoReview`, `auxiliary` 或 `unknown`;rollout 读取按 32 KiB 分块且总计不超过 256 KiB。
+Hook 子进程从 rollout 首条 `session_meta` 的完整记录或已完成字段前缀中提取来源,按 32 KiB 分块且总计不超过 256 KiB。JSONL 只持久化归一化后的 `main`、`autoReview`、`auxiliary` 或 `unknown`,具体分类与 model 后备规则见 [来源归一化](hook-and-aggregation.md#来源归一化)
不把 prompt, response, tool 参数或 tool 输出写入 CodexBar Hook 文件。
@@ -84,9 +84,9 @@ Hook 子进程优先从 `transcript_path` 指向的 rollout 第一条完整 `ses
### Rollout 文件
-Hook recorder 通过 `transcript_path` 读取当前 rollout,实时活动 reader 还会访问 `$CODEX_HOME/sessions` 和 `$CODEX_HOME/archived_sessions`
+Hook recorder 通过 `transcript_path` 读取当前 rollout,`SubagentStop` 的来源使用子线程自身的 `agent_transcript_path`。实时活动 reader 访问 `$CODEX_HOME/sessions` 和 `$CODEX_HOME/archived_sessions` 中相关主线程及子线程的文件。
-这些读取只解析来源分类、生命周期、时间、turn context, progress, effort 和 reviewer 等结构字段,不把对话正文复制到 CodexBar 存储或展示到 UI。
+这些读取只解析来源分类、线程及轮次归属、生命周期、时间、turn context、progress、effort 和 reviewer 等结构字段。线程关联只在内存中使用,对话正文不进入 CodexBar 存储或 UI。
rollout reader 从文件尾部按预算扫描,一方面减少 I/O,另一方面降低无关历史内容进入进程内存的范围。解析 DTO 只声明所需字段,JSONDecoder 自动忽略其余内容。
diff --git a/Docs/DeveloperGuide/development.md b/Docs/DeveloperGuide/development.md
index b489529..4bb05af 100644
--- a/Docs/DeveloperGuide/development.md
+++ b/Docs/DeveloperGuide/development.md
@@ -4,20 +4,41 @@
## 环境与构建
-需要 macOS 15+、Xcode、Swift 6、`swiftformat` 和 `swiftlint`。唯一 scheme 为 `CodexBar`,包含 App 与 `CodexBarHelper` 两个 target,没有 XCTest target。
+需要 macOS 15+、Xcode、Swift 6、`swiftformat` 和 `swiftlint`。唯一 scheme 为 `CodexBar`,包含 App、`CodexBarHelper` 和 `CodexBarTests` 三个 target。
```bash
xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
+xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' test
swiftformat .
swiftlint
```
-格式配置见 `.swiftformat`,使用 Swift 6 和 4 空格缩进。`swiftlint` 只检查 `CodexBar/`,不覆盖 `Shared/`、`CodexBarHelper/` 和 `Scripts/`
+格式配置见 `.swiftformat`,使用 Swift 6 和 4 空格缩进。`swiftlint` 检查 `CodexBar/` 和 `CodexBarTests/`,不覆盖 `Shared/`、`CodexBarHelper/` 和 `Scripts/`
修改前检查 `git status --short`。已有未提交改动时,仅格式化本次涉及的 Swift 文件,或使用 `swiftformat --lint . --cache ignore` 检查。`swiftlint --no-cache` 可避免写入缓存。
日常构建不需要 Developer ID 或公证凭据。写作、Git 和兼容性规则见 [AGENTS.md](../../AGENTS.md)
+## 单元测试
+
+`CodexBarTests` 使用 Swift Testing,并加入共享的 `CodexBar` scheme,可用 Xcode 的 Test 操作或上述命令执行。
+
+测试 target 无 App 宿主,与 App 使用相同的 Swift 6、`MainActor` 和并发设置,直接编译 `CodexBar/` 与 `Shared/` 源码。`CODEXBAR_TESTING` 仅在测试 target 定义,用于移除 `@main`;测试不实例化 App,不启动 Codex、CloudKit 同步或 helper。这样无需为测试拆分生产模块,代价是测试构建会额外编译一份 App 源码。
+
+| 测试范围 | 关键约束 |
+| --- | --- |
+| Hook 与 JSONL | 名称归一化、坏行隔离、元数据读取预算、半行补齐、bootstrap 与 live 分流、文件替换 |
+| 实时任务 | 匿名身份、时长、乱序进展、子 Agent 计数、各执行归属独立的审批状态 |
+| rollout 生命周期 | 完成与进展、读取覆盖、损坏行、文件丢失或替换、归档定位 |
+| 聚合与同步模型 | ID 去重、事件对计数、缺失计数、增量与重放一致性、同设备 generation 去重 |
+| 持久化与设置 | 保护记录过期、跨实例合并、条件删除、旧记录默认值、配置损坏与回填 |
+| 额度、代理与展示 | 凭证筛选、稳定 UUID、实际运行版本、代理输入和环境变量、日期与热力图状态 |
+| 异步刷新 | 取消和代际过期后不提交结果、不结束较新的刷新 |
+
+每个文件测试创建独立临时目录,每个偏好测试创建独立 `UserDefaults` suite,并在结束时清理。测试使用固定时间、显式日历和受控异步检查点;新增测试应沿用这些隔离方式。
+
+单元测试不覆盖真实 CloudKit、app-server、系统通知、窗口焦点和 helper 电源行为。这些流程仍按下方手动场景验证。
+
## 修改入口
| 功能 | 主要位置 | 实现说明 |
@@ -44,7 +65,7 @@ swiftlint
1. 检查修改范围,确认未覆盖已有工作
2. 格式化并运行 `swiftlint`
-3. 构建 App 与 helper
+3. 构建 App 与 helper,并运行单元测试
4. 手动验证受影响的正常、失败和恢复流程
5. 检查文档及 `git diff --check`
diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.md
index 7a6449a..2c34182 100644
--- a/Docs/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/DeveloperGuide/hook-and-aggregation.md
@@ -119,7 +119,7 @@ CodexBar 订阅以下 Hook 事件:
把两类需求统一在一条最小原始记录中,可以让 recorder 只写一次,两个下游各自选择所需字段。但新增字段前仍要证明至少有一个消费者需要它,不能因为 Hook payload 中存在就全部持久化。
-`transcript_path` 可用时,recorder 会为来源分类有界读取 rollout 首行。rollout 来源无法确定时,只有精确匹配 `codex-auto-review` 的 model 才作为 Auto-review 来源的后备判定。`PermissionRequest` 和 `UserPromptSubmit` 的 reviewer 或 effort 可能不在 Hook payload 中,只有这两个事件还会按 turn 定向读取 rollout 尾部。
+recorder 为来源分类有界读取 rollout 首行。普通事件使用 `transcript_path`,`SubagentStop` 使用指向子线程自身的 `agent_transcript_path`。rollout 来源无法确定时,只有精确匹配 `codex-auto-review` 的 model 才作为 Auto-review 来源的后备判定。`PermissionRequest` 和 `UserPromptSubmit` 的 reviewer 或 effort 可能不在 Hook payload 中,只有这两个事件还会按 turn 定向读取 rollout 尾部。
## Hook 子进程
@@ -201,7 +201,7 @@ handler 超时由事件决定:
| `auxiliary` | `source` 明确表示其他 subagent,包括 `review`, `thread_spawn` 和 Memories 相关来源 |
| `unknown` | 字段缺失、结构损坏、无法读取或遇到未知顶层来源,并且 model 不满足 Auto-review 后备判定 |
-来源读取从文件起点按 32 KiB 分块,遇到第一个 newline 立即停止,总预算为 256 KiB。第一条完整记录不是 `session_meta`、超过预算或任何文件与解码操作失败时,rollout 来源回退到 `unknown`,不等待、不重试,也不能让 Hook 失败。model 后备判定只接受精确字符串,不做前缀、别名或模糊匹配。
+来源读取从文件起点按 32 KiB 分块,总预算为 256 KiB。遇到首个 newline 时解码完整首行;首行尚未读完时,在完整字段边界构造可解码的元数据前缀。确认类型为 `session_meta` 且 `source` 已完整解码后即可返回,大型指令字段无需读完。预算内无法取得来源、记录类型不符或读取与解码失败时,rollout 来源回退到 `unknown`。model 后备判定只接受精确字符串。
recorder 在写入前完成来源解析,JSONL 的来源字段只保存上述枚举值。`transcript_path`、原始 `source`、任意 `other` 字符串和 transcript 内容都不会写入 Hook 文件或系统日志。
diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.md
index a5dd92f..c90b716 100644
--- a/Docs/DeveloperGuide/notifications.md
+++ b/Docs/DeveloperGuide/notifications.md
@@ -152,10 +152,10 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正
只有 `PermissionRequest` 的 reviewer 确认是用户时才发送等待批准通知:
- 自动审批不通知
-- 同一等待项只通知一次
+- 同一任务连续等待期间只通知一次,其他 Agent 的进展不结束该等待;审批归属规则见 [等待批准的两阶段确认](activity-monitor.md#等待批准的两阶段确认)
- 任务离开等待状态后从相关集合移除
- bootstrap、恢复对账和 Hook 数据源不健康期间不发布等待转场
-- Hook 直接确认等待时,进入等待的时间须不早于恢复界限且距当前不超过 10 秒;rollout 补齐 reviewer 后确认等待时,只检查请求时间不早于恢复界限
+- Hook 直接确认和 rollout 补齐 reviewer 后确认均要求任务进入等待的时间不早于恢复界限且距当前不超过 10 秒
等待状态是否维持防睡眠是独立设置,不影响是否可以发送等待批准通知。
diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.md
index 006851f..5ee15ae 100644
--- a/Docs/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md
@@ -57,6 +57,10 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。
完成使用绿色,终止使用红色;结束时间相同优先终止。所有计时包含进场动画,到期后按最新快照恢复展示。
+设置从关闭切换为开启且 Hook 可用时,`TaskGlowSettings.previewRequests` 请求一次青色运行预览,完成一个 2.7 秒往返周期后恢复实际状态。启动和设置刷新只恢复开关值,不触发预览。预览覆盖期间继续接收真实任务更新,不产生任务事件。
+
+播放和收尾期间忽略新的预览请求。关闭开关通过光带已有的退场流程快速收回到中心并淡出;所有屏幕实际收尾完成后释放预览占用。Hook 不可用、系统睡眠、屏幕休眠或会话不活跃时取消预览。
+
光带使用不激活、穿透鼠标的 `NSPanel`,跨 Space 和全屏显示。系统睡眠、屏幕休眠或用户会话不活跃时移除窗口,恢复后按当前时间接续有效状态。屏幕配置变化时重建窗口,各显示器共享运动时钟。
## 状态栏图标
@@ -302,6 +306,7 @@ app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完
- 左键打开主面板,右键和 Control 点击打开上下文菜单
- 多任务运行或等待批准期间,完成和终止触发 3 秒流光提示;连续结束及全部任务结束时颜色与到期时间正确
+- 开启流光播放一次预览,关闭时收回并淡出,收尾期间不重播,收尾后可再次开启预览;预览期间任务状态变化后正确接续实际状态
- 历史重读及唤醒对账不补播旧终态短提示,恢复后的真实结束仍有提示;多显示器和屏幕配置变化后运动与到期时间一致
- 菜单栏符号随任务状态切换,最新终态在结束 10 秒后恢复空闲,跨睡眠唤醒后按当前时间显示
- 普通人物与四种任务徽章之间切换时过渡完整,快速连续切换后显示最新状态;带徽章时反复切换额度显隐仍保持流畅,首次显示和唤醒重算不播放过渡
diff --git a/Docs/UserGuide/activity-and-hook.md b/Docs/UserGuide/activity-and-hook.md
index 2c1d611..9a726ee 100644
--- a/Docs/UserGuide/activity-and-hook.md
+++ b/Docs/UserGuide/activity-and-hook.md
@@ -23,12 +23,14 @@ CodexBar 自动检查和修复已开启的 Hook 配置,保留用户和其他 A
| 最近完成 | 一轮任务已结束,不代表结果一定成功 |
| 最近终止 | 中断或其他终态信号确认任务终止,不发送完成通知 |
-收到 `Stop` 后会先显示“正在收尾”,确认本轮完成且满足通知设置后才发送完成提醒。如果其他 Hook 让任务继续执行,状态会继续更新;期间中断则显示已终止。
+收到 `Stop` 后会先显示“正在收尾”;仍有子 Agent 等待批准时优先显示等待。确认本轮完成且满足通知设置后才发送完成提醒,期间中断则显示已终止。
中断只结束对应轮次,同一会话随后开始的新任务保持活跃。全部符合条件的任务结束后,按任务防睡眠会释放。
子 Agent 的活动合并到所属任务中。内部自动审核任务和来源始终无法确认的任务不显示为实时任务,也不触发流光、任务提醒或防睡眠;它们的活动仍计入每日统计。同一会话和轮次已确认是正常任务后,后续暂时无法识别来源的事件仍会更新任务状态。
+主 Agent 或子 Agent 等待批准时,其他 Agent 的进展不会解除它的等待。只要该任务仍有一项用户审批等待,卡片就继续显示等待状态。
+
来源明确但无法识别会话的任务会带有橙色匿名图标。这类任务可以查看,但不触发通知或触觉反馈,也不参与防睡眠和异常会话保护。
长时间没有进展的运行任务可能被 [异常会话保护](sleep-prevention.md#异常会话保护) 隐藏,恢复进展后重新显示。
diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.md
index 8d2989b..6a26285 100644
--- a/Docs/UserGuide/settings.md
+++ b/Docs/UserGuide/settings.md
@@ -26,6 +26,8 @@ Hook 关闭时任务区域自动关闭,从关闭切换到开启时自动显示
在各显示器顶部显示任务状态,需要 CodexBar Hook 开启且校验通过。此开关默认关闭,与主面板的“动画效果”独立。
+开启时会播放一次青色往返预览,随后显示实际任务状态。关闭时光带快速收回到屏幕中心并淡出。预览播放或收尾期间反复开关不会重播;收尾完成后再次开启可以重新预览。
+
| 颜色 | 含义 |
| --- | --- |
| 青色往返流光 | 任务运行中 |
diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.md
index 73e3bad..0b40966 100644
--- a/Docs/en/DeveloperGuide/activity-monitor.md
+++ b/Docs/en/DeveloperGuide/activity-monitor.md
@@ -143,10 +143,10 @@ Rules are:
- Poll every 1 second by default
- Begin with a 512 KiB tail window
- Look back at most 8 MiB for turn-context fields such as effort
-- Parse only lifecycle, turn, progress, effort, and reviewer
+- Parse only thread relationships, lifecycle, turn, progress, effort, and reviewer
- Keep conversation content out of the activity model and product presentation
-Hook `Stop` marks the task as “Finishing up” and keeps it active. Tools, approvals, and other progress continue updating the same task. Rollout `task_complete` confirms completion; transition freshness and recovery conditions determine whether a completion transition is emitted.
+Hook `Stop` marks the task as “Finishing up” and keeps it active; approval waiting takes priority while another agent is still waiting. Tools, approvals, and other progress continue updating the same task. Rollout completion records confirm the end of the turn; transition freshness and recovery conditions determine whether a completion transition is emitted.
If rollout is temporarily unreadable or the session or turn cannot be matched, the task continues waiting for reconciliation. `Stop` does not start a terminal timeout. A new turn or `SessionEnd` removes the old task from the active list and starts five seconds of fast terminal polling, followed by polling every 30 seconds. A late `Stop` updates only the pending task's metadata and progress, without restoring its presentation or resetting the deadline.
@@ -168,6 +168,8 @@ A resume can continue a session created long ago. If the fast path misses, the f
If a file moves to the archive, a missing cached URL clears its cursor and allows full discovery again.
+Filenames match the thread ID exactly, optionally followed by an underscore and UUID suffix. A candidate must be unique, and its initial `session_meta.id` must match the requested thread. Metadata uses the same [bounded first-line parser](hook-and-aggregation.md#origin-normalization) as the Hook recorder.
+
### Rollout Read Budget
Live tasks need lifecycle near an active turn, not a full read of a long-running session. Starting from the last 512 KiB reduces resident I/O and discards the first potentially partial line.
@@ -184,20 +186,22 @@ A malformed rollout line marks unfinished turns as having a coverage gap. Repeat
Each session file cursor stores its own `currentTurnId`, updated in JSONL file order:
-- Outer `type = "turn_context"`, or `type = "event_msg"` with `payload.type = "task_started"`, establishes context from `payload.turn_id`
-- An explicit `payload.turn_id` takes priority; a record without it inherits cursor context
-- `task_complete` or `turn_aborted` for the current turn clears context; a late terminal for another turn does not
+- Outer `type = "turn_context"`, or `type = "event_msg"` with `payload.type` equal to `task_started` or `turn_started`, establishes context from `payload.turn_id`
+- `response_item` prefers `payload.internal_chat_message_metadata_passthrough.turn_id`; other progress records use `payload.turn_id`, falling back to cursor context when absent
+- `task_complete`, `turn_complete`, or `turn_aborted` for the current turn clears context; a late terminal for another turn does not
- Truncation or replacement rebuilds the cursor and clears both context and cached lifecycle states
-Progress includes records whose outer `type` is `response_item` or `token_usage_record`, and `event_msg` records whose `payload.type` is `token_count`, `item_completed`, `agent_message`, `agent_reasoning`, `task_started`, `task_complete`, or `turn_aborted`. Time comes from outer `timestamp`, then `payload.completed_at`, then `payload.started_at`.
+Progress includes records whose outer `type` is `response_item` or `token_usage_record`, and `event_msg` records whose `payload.type` is `token_count`, `item_completed`, `agent_message`, `agent_reasoning`, `task_started`, `turn_started`, `task_complete`, `turn_complete`, or `turn_aborted`. Time comes from outer `timestamp`, then `payload.completed_at`, then `payload.started_at`.
A record needs a usable timestamp and turn identity. It advances task progress only after a complete current read and when newer than `lastProgressAt`. A `token_usage_record` is treated as activity without comparing token totals. Records lacking both an explicit turn and cursor context do not contribute task progress.
+Execution progress eligible to infer approval recovery is recorded separately as `lastExecutionProgressAt`: `response_item` records with `role = "assistant"` or a type of `function_call_output`, `custom_tool_call_output`, or `tool_search_output`, and `agent_message` or `agent_reasoning` events. Only execution progress from the same agent and turn, later than the approval request, clears that wait. Ordinary activity such as usage records updates only task progress time.
+
### Rollout Fields
The shared `CodexRolloutLineEnvelope` extracts only fields needed for turn context, lifecycle, and progress. Prompt, response, and tool content never enters the activity model.
-Terminal resolution requires a nonempty `payload.turn_id` and a `complete` current read. With outer `type = "event_msg"`, `payload.type = "task_complete"` and a valid `payload.completed_at` confirm completion; `payload.type = "turn_aborted"` confirms interruption. Completion time uses Unix seconds, and `payload.duration_ms` is converted to seconds for duration display. A missing interruption timestamp uses reconciliation time for an active task or removal time for a pending task, never earlier than its last activity.
+Terminal resolution requires a nonempty `payload.turn_id` and a `complete` current read. With outer `type = "event_msg"`, `payload.type` equal to `task_complete` or `turn_complete` confirms completion. Completion time prefers a valid `payload.completed_at` in Unix seconds, falling back to outer `timestamp` when absent or invalid; neither being usable leaves completion unconfirmed. `payload.type = "turn_aborted"` confirms interruption. A finite, nonnegative `payload.duration_ms` is converted to seconds for duration display. A missing interruption timestamp uses reconciliation time for an active task or removal time for a pending task, never earlier than its last activity.
## Task Identity
@@ -223,7 +227,7 @@ Without a session ID, only a project key remains. It may merge concurrent anonym
### Live Task Origin Filtering
-`CodexActivityMonitor.apply` checks `WorkflowHookEvent.origin` before task-state transitions. See [Origin Normalization](hook-and-aggregation.md#origin-normalization) for input classification.
+`CodexActivityMonitor.apply` resolves the effective live origin before task-state transitions. When using a cached origin, an event copy carries that origin through filtering and execution identity checks; raw JSONL remains unchanged. See [Origin Normalization](hook-and-aggregation.md#origin-normalization) for input classification.
The monitor remembers origins in memory for 24 hours by exact `session ID + turn ID`. Codex subagent Hooks reuse the parent session ID, so origin decisions do not apply to an entire session.
@@ -252,21 +256,23 @@ A new prompt moves the previous turn in the same session to `pendingTerminalTask
### Rejecting Late Events
-Tasks store `lastHookEventAt` and `lastProgressAt`; `lastActivityAt` reads the same value as `lastProgressAt`:
+Hook ordering is isolated by agent and turn, while overall task progress is aggregated separately:
| Field | Source and purpose |
| --- | --- |
-| `lastHookEventAt` | Latest accepted Hook timestamp, used to reject stale Hook state changes |
+| Execution `lastHookEventAt` | Latest accepted Hook timestamp for an agent and turn, used to reject that execution's stale state changes |
+| `lastMainHookEventAt` | Latest main-agent Hook timestamp, used for top-level prompt, interruption, and session-end decisions |
+| Execution `lastExecutionProgressAt` | Hook recovery signals and rollout execution progress for the same execution, used for approval recovery and rejecting stale requests |
| `lastProgressAt` | Latest progress from Hook and rollout, used by inactivity protection |
| `lastActivityAt` | Computed from `lastProgressAt`, used for ordering, retention, and terminal timestamp adjustment |
-Rollout progress never advances `lastHookEventAt`. Reading a later rollout record first still allows a slightly earlier, valid permission, tool, compaction, interruption, or new-prompt Hook. Accepting such Hooks keeps `lastProgressAt` and `lastActivityAt` monotonic.
+Rollout progress never advances Hook clocks, and a later event from another agent does not block this agent's valid events. An approval request must also be no earlier than known execution progress for the same owner and later than its previous approval request. Task `lastProgressAt` and `lastActivityAt` remain monotonic.
Completion and termination share the in-memory `recentlyEndedTaskAt` map of end times. Their display records remain separate and expire after 10 minutes; deduplication memory lasts 24 hours independently. Removing a record through origin filtering recomputes its session alias from the remaining terminal timestamps.
Late events follow these rules:
-- Hook state changes and approval requests use `lastHookEventAt`; an approval request older than the latest Hook progress does not restore waiting
+- Tool, compaction, subagent, and approval Hooks check time within their execution scope; an execution with a confirmed terminal rejects further state changes
- An exact turn cannot be recreated while terminal memory is retained; session and anonymous keys can be reused only by a newer prompt
- A `Stop` matching several candidates is not guessed
- A key already in terminal deduplication memory clears recovery tasks left by abnormal ordering
@@ -290,7 +296,7 @@ Active tasks mainly use these internal states:
| State | Meaning |
| --- | --- |
| `running` | Codex is processing the current turn |
-| `waitingApproval` | The current turn is explicitly waiting for user approval |
+| `waitingApproval` | At least one main-agent or subagent execution in the task is waiting for user approval |
| `suppressed` | Stalled Task Protection hid the task pending new progress |
`PermissionRequest` enters `waitingApproval` only when the reviewer is the user. Automatic or policy approval does not count as user waiting.
@@ -310,8 +316,9 @@ Task endings are handled by signal:
| Absent | Top-level tool or compact | running | Recover task with unknown `startedAt` |
| running | Tool, compact, or subagent progress | running | Update last progress and generation |
| running | `PermissionRequest` + reviewer user | waitingApproval | Publish live waiting transition |
-| waitingApproval | Tool, compaction, or subagent Hook progress | running | Clear the pending approval candidate and update activity and progress |
-| running or waiting | `Stop` | running | Show Finishing up and retain the task until rollout confirms its terminal state |
+| waitingApproval | Valid Hook or rollout execution progress from the agent and turn owning the approval | waitingApproval or running | Clear that execution's approval; retain waiting while other waits remain |
+| waitingApproval | Progress from another agent | waitingApproval | Update progress while preserving the wait and its tool presentation |
+| running or waiting | Top-level `Stop` | running or waitingApproval | Clear the main execution's wait; show waiting while a subagent still waits, otherwise Finishing up |
| active | New prompt or `SessionEnd` | pending terminal | Remove from snapshot and begin background terminal polling |
| active, suppressed, or pending terminal | `Interrupt` | terminated | Remove the matching task, record termination, and clear protection state and notifications |
| running | Protection conditions hold and silence reaches threshold | suppressed | Hide and remove sleep-prevention contribution |
@@ -320,13 +327,13 @@ Task endings are handled by signal:
### Two-Stage Approval Confirmation
-The task’s `approvalReviewer` comes from Hook records or rollout `payload.approvals_reviewer`, with values `user`, `auto_review`, or `guardian_subagent`.
+Tasks keep execution records by agent and turn. The main agent uses an explicit main origin without `agentId`; subagents use their own thread IDs. Each execution has its own `approvalReviewer`, sourced from Hook or rollout `payload.approvals_reviewer`, with values `user`, `auto_review`, or `guardian_subagent`.
-A `PermissionRequest` enters waiting immediately when the task’s known reviewer is `user`. An unknown reviewer leaves `pendingApprovalRequestedAt` for rollout backfill. Automatic review routes retain the current state and clear the candidate during reconciliation.
+Each execution has one optional approval record: `pending` means the route is unconfirmed, and `waiting` means user approval is required. A `PermissionRequest` is confirmed immediately when the known reviewer is `user`; an unknown reviewer retains the candidate, and an automatic reviewer clears it. The record carries request time, tool name, and sequence. Repeated requests do not overwrite an existing wait's presentation.
-Valid tool, compaction, subagent, or top-level `Stop` Hooks restore running and clear the pending candidate. Later reviewer backfill does not reopen cleared waiting. Rollout progress updates timestamps without clearing approval waiting on its own.
+Only progress reliably attributed to the same agent and turn can clear that execution's approval. Valid tool, compaction, subagent lifecycle, and top-level `Stop` Hooks follow their recovery rules; rollout execution progress must be strictly later than the request. Reviewer backfill cannot reopen a cleared candidate. An explicit child rollout terminal also clears that execution's wait.
-Approval waiting is tracked per task. Valid Hook progress from another parallel tool or subagent within the same task also clears waiting.
+The task stays in `waitingApproval` while any user wait remains, displaying the earliest request and using sequence to break time ties. Changing the displayed wait does not reset the task's waiting start time. Other agents' progress and progress with incomplete identity do not clear known waits. Parallel calls within one agent and turn share an approval record, with recovery inferred from progress.
### Effort Merging
@@ -334,11 +341,11 @@ Several context events in one turn may report different reasoning efforts. The t
### Subagent Count Reliability
-A subagent turn ID belongs to the subagent, so its parent can be associated only by shared session.
+Subagent Hook `agent_id` and `turn_id` identify the child thread and turn. The monitor reads that thread's rollout, validates thread identity with `session_meta.id`, checks parent-thread information using `parent_thread_id` or its fallback `source.subagent.thread_spawn.parent_thread_id`, and associates the root task through `root_turn_id` in context or start records. `root_turn_id` identifies the root turn, not the direct parent agent's turn.
-Subagent Hooks associate with the session’s sole active parent. With an older pending task present, `SubagentStart` may associate; other subagent events require an `agent_id` already recorded under the active parent. Events with no unique parent are ignored.
+The root session ID comes first from `session_meta.session_id`, falling back to an existing association or the unique root session ID in Hooks for that child turn. Child events with complete identity are buffered until association, then replayed with their original source. Missing fields or conflicting associations do not fall back to the sole active task. Subagent activity updates only the matching active root task and creates no independent card.
-Count reliability is initialized from whether the prompt start is known. A missing `agent_id` or a stop first observed for an agent sets reliability to `false`, hiding the count in the UI. Each agent’s running state follows its own event timestamps.
+The active subagent count follows associated `SubagentStart` and `SubagentStop` events, separately from approval records. Reliability is initialized from whether the prompt start is known; a stop first observed for an agent sets it to `false`, hiding the count in the UI. Each agent's running state follows its own event timestamps. A late start does not count an execution already confirmed ended as running.
## Snapshot Priority
@@ -369,7 +376,7 @@ A candidate snapshot is compared with the current value and published only after
`presentationPublisher` publishes the current snapshot and the batch's still-valid `terminalEvents` for Task Glow. Presentation events include anonymous tasks; notifications use the separate `transitionPublisher`.
-Completion transitions and terminal indicators require an end timestamp no more than 10 seconds old and no earlier than their respective recovery boundaries. Waiting transitions confirmed directly by Hook also use a 10-second limit. Waiting confirmed by rollout reviewer backfill checks only that the request is no earlier than `sessionTransitionNotBefore`.
+Completion transitions and terminal indicators require an end timestamp no more than 10 seconds old and no earlier than their respective recovery boundaries. Waiting transitions, whether confirmed directly by Hook or through rollout reviewer backfill, require the task's waiting start time to be no more than 10 seconds old and no earlier than `sessionTransitionNotBefore`.
History reloads, sleep recovery, and source health changes clear pending events and update `terminalPresentationNotBefore`. Publication pauses during bootstrap, recovery reconciliation, and unhealthy source state.
@@ -534,8 +541,9 @@ Task progress invalidates its protection attempt. Reader, bootstrap, and recover
- Three unstable attempts enter degraded state without starting silence evaluation
- Replace an old turn with a new prompt and verify classification when the terminal arrives within and after the first five seconds
- A `Stop` is not guessed when one session has several terminal candidates
-- Read an approval Hook and slightly later rollout progress in both orders; both show orange waiting and emit one waiting transition
-- Advance rollout progress before tool, compaction, or subagent Hooks; those Hooks still clear waiting and update activity. Delayed approval requests or reviewer backfill do not reopen cleared waiting; interruption and `SessionEnd` still end the corresponding task
+- Put the main agent and multiple subagents into waiting; each recovery clears only its own wait, and running resumes after the last wait clears
+- Ordinary rollout activity preserves waiting; newer execution progress from the same owner clears it, equal-time progress preserves it, and late approvals or reviewer backfill do not reopen cleared waits
+- A child `root_turn_id` pointing to an old turn does not update the new task; missing or conflicting associations do not guess the parent
- Attribute turnless records after a new boundary only to the new turn; late old terminals, incremental reads, and file replacement preserve context isolation
- A missing reviewer enters waiting only after rollout confirms user
- Automatic review never emits a waiting transition
@@ -551,6 +559,7 @@ Task progress invalidates its protection attempt. Reader, bootstrap, and recover
- [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)
- [`CodexActivityTask.swift`](../../../CodexBar/Services/Workflow/CodexActivityTask.swift)
+- [`CodexActivitySubagentTracking.swift`](../../../CodexBar/Services/Workflow/CodexActivitySubagentTracking.swift)
- [`CodexActivityTerminalResolution.swift`](../../../CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift)
- [`HookEventTailReader.swift`](../../../CodexBar/Services/Workflow/HookEventTailReader.swift)
- [`CodexSessionLifecycleReader.swift`](../../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift)
diff --git a/Docs/en/DeveloperGuide/architecture.md b/Docs/en/DeveloperGuide/architecture.md
index c99700a..50cbb2c 100644
--- a/Docs/en/DeveloperGuide/architecture.md
+++ b/Docs/en/DeveloperGuide/architecture.md
@@ -8,14 +8,15 @@ Explore the processes, data flows, and recovery paths in the [Runtime Architectu
CodexBar is a menu bar app for macOS 15 and later, built with Swift 6, SwiftUI, AppKit, and MVVM.
-The project has one `CodexBar` scheme with two targets:
+The project has one `CodexBar` scheme with three targets:
| Target | Responsibility |
| --- | --- |
| `CodexBar` | Menu bar UI, Codex data collection, Automatic Reset, notifications, sync, and system-power orchestration |
| `CodexBarHelper` | A root LaunchDaemon that handles fixed system-sleep controls and Automatic Reset wake schedules |
+| `CodexBarTests` | Swift Testing unit tests without an app host, compiling production sources with isolated test data |
-The targets share their XPC protocol through [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift).
+The app and helper share their XPC protocol through [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift).
The app uses Sparkle for update checks. The project enables `MainActor` isolation by default, and Debug and Release use different app and CodexBarHelper bundle IDs.
diff --git a/Docs/en/DeveloperGuide/data-and-privacy.md b/Docs/en/DeveloperGuide/data-and-privacy.md
index 618dd83..ca37d29 100644
--- a/Docs/en/DeveloperGuide/data-and-privacy.md
+++ b/Docs/en/DeveloperGuide/data-and-privacy.md
@@ -19,12 +19,12 @@ Codex hook stdin / rollout / app-server
|
v
User-privileged CodexBar
- | |
- v v
- CloudKit private DB Constrained XPC interface
- |
- v
- root CodexBarHelper
+ | |
+ v v
+CloudKit private DB Constrained XPC interface
+ |
+ v
+ CodexBarHelper
```
These boundaries mean:
@@ -76,7 +76,7 @@ The Hook subprocess extracts from stdin:
- Permission and reviewer
- Session, turn, and agent identities
-The Hook subprocess first extracts and normalizes origin from the first complete `session_meta` record in the rollout referenced by `transcript_path`. When the rollout origin is `unknown`, the model already extracted from stdin classifies the event as `autoReview` only if it exactly equals `codex-auto-review`. The JSONL origin field persists only `main`, `autoReview`, `auxiliary`, or `unknown`; rollout reading uses 32 KiB chunks with a total limit of 256 KiB.
+The Hook subprocess extracts origin from the first rollout `session_meta`, using either the complete record or a prefix of completed fields. Reads use 32 KiB chunks with a total limit of 256 KiB. JSONL persists only the normalized `main`, `autoReview`, `auxiliary`, or `unknown` value. See [Origin Normalization](hook-and-aggregation.md#origin-normalization) for classification and model fallback rules.
It does not write prompt text, responses, tool arguments, or tool output to CodexBar Hook files.
@@ -84,9 +84,9 @@ The working directory is used only to derive a project display name and live-tas
### Rollout Files
-The Hook recorder reads the current rollout through `transcript_path`, and the live-activity reader also accesses `$CODEX_HOME/sessions` and `$CODEX_HOME/archived_sessions`.
+The Hook recorder reads the current rollout through `transcript_path`; origin for `SubagentStop` uses the child thread's own `agent_transcript_path`. The live-activity reader accesses relevant main-thread and child-thread files under `$CODEX_HOME/sessions` and `$CODEX_HOME/archived_sessions`.
-These reads parse only structural fields such as origin classification, lifecycle, time, turn context, progress, effort, and reviewer. They neither copy conversation text into CodexBar storage nor present it in the UI.
+These reads parse only structural fields such as origin classification, thread and turn relationships, lifecycle, time, turn context, progress, effort, and reviewer. Thread associations remain in memory, and conversation text does not enter CodexBar storage or UI.
The rollout reader scans backward from file tails under a budget. This reduces I/O and limits how much unrelated historical content enters process memory. Parsing DTOs declare only required fields, and `JSONDecoder` ignores everything else.
diff --git a/Docs/en/DeveloperGuide/development.md b/Docs/en/DeveloperGuide/development.md
index ef4822d..3140cc1 100644
--- a/Docs/en/DeveloperGuide/development.md
+++ b/Docs/en/DeveloperGuide/development.md
@@ -4,20 +4,41 @@
## Environment and Build
-Requires macOS 15+, Xcode, Swift 6, `swiftformat`, and `swiftlint`. The only scheme is `CodexBar`, containing the app and `CodexBarHelper` targets. There is no XCTest target.
+Requires macOS 15+, Xcode, Swift 6, `swiftformat`, and `swiftlint`. The only scheme is `CodexBar`, containing the app, `CodexBarHelper`, and `CodexBarTests` targets.
```bash
xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
+xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'platform=macOS' test
swiftformat .
swiftlint
```
-`.swiftformat` configures Swift 6 and 4-space indentation. `swiftlint` checks only `CodexBar/`, excluding `Shared/`, `CodexBarHelper/`, and `Scripts/`.
+`.swiftformat` configures Swift 6 and 4-space indentation. `swiftlint` checks `CodexBar/` and `CodexBarTests/`, excluding `Shared/`, `CodexBarHelper/`, and `Scripts/`.
Check `git status --short` before editing. With existing uncommitted work, format only Swift files touched by the change, or check with `swiftformat --lint . --cache ignore`. `swiftlint --no-cache` avoids cache writes.
Daily builds do not need Developer ID or notarization credentials. See [AGENTS.md](../../../AGENTS.md) for writing, Git, and compatibility rules.
+## Unit Tests
+
+`CodexBarTests` uses Swift Testing and belongs to the shared `CodexBar` scheme. Run it with Xcode’s Test action or the command above.
+
+The test target has no app host. It compiles the production sources in `CodexBar/` and `Shared/` with the same Swift 6, `MainActor`, and concurrency settings. The test-only `CODEXBAR_TESTING` condition removes `@main`; tests do not instantiate the app or start Codex, CloudKit sync, or the helper. This avoids extracting production modules solely for testing, at the cost of compiling the app sources again for tests.
+
+| Test area | Key constraints |
+| --- | --- |
+| Hook and JSONL | Name normalization, corrupt-line isolation, metadata read budget, partial lines, bootstrap/live separation, file replacement |
+| Live tasks | Anonymous identity, duration, out-of-order progress, subagent counts, approvals scoped to each execution |
+| Rollout lifecycle | Completion and progress, read coverage, corrupt lines, missing/replaced files, archived sessions |
+| Aggregation and sync models | Identifier deduplication, paired events, missing counts, incremental/replay equivalence, same-device generation deduplication |
+| Persistence and settings | Protection expiry, merging across store instances, conditional removal, legacy defaults, corrupt configuration and draft restoration |
+| Quota, proxy, and presentation | Credit filtering, stable UUIDs, actual running versions, proxy validation and environment, dates and heatmap states |
+| Asynchronous refresh | Cancellation and stale generations cannot commit results or finish newer refreshes |
+
+Each file test creates and removes its own temporary directory. Each preferences test uses and cleans up a unique `UserDefaults` suite. Tests use fixed dates, explicit calendars, and controlled asynchronous checkpoints; follow these isolation patterns when adding tests.
+
+Unit tests do not cover live CloudKit, app-server, system notifications, window focus, or helper power behavior. Validate those flows with the manual scenarios below.
+
## Implementation Entry Points
| Feature | Main location | Implementation guide |
@@ -44,7 +65,7 @@ For asynchronous changes, check cancellation, commit eligibility, and generation
1. Review the change scope and preserve existing work
2. Format and run `swiftlint`
-3. Build the app and helper
+3. Build the app and helper, and run unit tests
4. Manually verify affected normal, failure, and recovery flows
5. Review documentation and run `git diff --check`
diff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.md
index d73714a..a09c5df 100644
--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md
@@ -119,7 +119,7 @@ Historical counts need event name, date, project, model, and identity sets. Live
One minimal raw record lets the recorder write once while both consumers select their fields. A new field still requires a demonstrated consumer; its presence in the Hook payload does not justify persisting everything.
-When `transcript_path` is available, the recorder performs a bounded read of the rollout's first line to classify origin. If the rollout origin cannot be determined, only an exact `codex-auto-review` model match serves as the Auto-review fallback. Reviewer or effort for `PermissionRequest` and `UserPromptSubmit` may be absent from the Hook payload, so only those two events also read the rollout tail for that turn.
+The recorder performs a bounded read of the rollout's first line to classify origin. Ordinary events use `transcript_path`; `SubagentStop` uses `agent_transcript_path`, which points to the child thread itself. If the rollout origin cannot be determined, only an exact `codex-auto-review` model match serves as the Auto-review fallback. Reviewer or effort for `PermissionRequest` and `UserPromptSubmit` may be absent from the Hook payload, so only those two events also read the rollout tail for that turn.
## Hook Subprocess
@@ -201,7 +201,7 @@ The lookup:
| `auxiliary` | `source` explicitly represents another subagent, including `review`, `thread_spawn`, and Memories-related sources |
| `unknown` | The field is missing, malformed, unreadable, or an unknown top-level source, and the model does not satisfy the Auto-review fallback |
-Origin reading starts at byte zero in 32 KiB chunks, stops at the first newline, and has a total budget of 256 KiB. If the first complete record is not `session_meta`, exceeds the budget, or any file or decoding operation fails, the rollout origin falls back to `unknown` without waiting or retrying and without failing the Hook. The model fallback accepts only the exact string, with no prefix, alias, or fuzzy matching.
+Origin reading starts at byte zero in 32 KiB chunks with a total budget of 256 KiB. At the first newline, the parser decodes the complete first line. Before that line is complete, it constructs a decodable metadata prefix at a complete field boundary. It can return once the type is confirmed as `session_meta` and `source` has been fully decoded, without reading large instruction fields to completion. Missing origin within the budget, a different record type, or a read or decoding failure yields `unknown`. The model fallback accepts only the exact string.
The recorder resolves origin before writing, and the JSONL origin field stores only this enum. It never stores `transcript_path`, raw `source`, arbitrary `other` strings, or transcript content, and none of those values enter system logs.
diff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.md
index 927e4ba..b697013 100644
--- a/Docs/en/DeveloperGuide/notifications.md
+++ b/Docs/en/DeveloperGuide/notifications.md
@@ -152,10 +152,10 @@ Haptics start for every task transition. A new transition cancels the previous s
A waiting notification is sent only when the `PermissionRequest` reviewer is confirmed to be the user:
- Automatic review does not notify
-- One waiting item notifies only once
+- A task notifies once during a continuous wait; progress from other agents does not end that wait. See [Two-Stage Approval Confirmation](activity-monitor.md#two-stage-approval-confirmation) for ownership rules
- Leaving waiting state removes the item from the relevant set
- Waiting transitions pause during bootstrap, recovery reconciliation, and unhealthy Hook source state
-- Direct Hook confirmation requires waiting to have begun no earlier than the recovery boundary and no more than 10 seconds ago; rollout reviewer backfill checks only that the request is no earlier than the recovery boundary
+- Both direct Hook confirmation and rollout reviewer backfill require the task's waiting start time to be no earlier than the recovery boundary and no more than 10 seconds ago
Whether waiting maintains sleep prevention is an independent setting and does not affect notification eligibility.
diff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
index 4085221..3022b5a 100644
--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
@@ -57,6 +57,10 @@ Shutdown reverses the order, except for helper-owned system state. AppDelegate f
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.
+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.
+
+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.
## Status Bar Icon
@@ -301,6 +305,7 @@ 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
- 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
diff --git a/Docs/en/UserGuide/activity-and-hook.md b/Docs/en/UserGuide/activity-and-hook.md
index 37d304d..9e9d108 100644
--- a/Docs/en/UserGuide/activity-and-hook.md
+++ b/Docs/en/UserGuide/activity-and-hook.md
@@ -23,12 +23,14 @@ CodexBar automatically checks and repairs enabled Hook configuration, preserving
| Recently Completed | A turn ended; its result is not necessarily successful |
| Recently Terminated | An interruption or other terminal signal confirmed termination; no completion notification is sent |
-After `Stop`, the task first shows “Finishing up”. A completion notification is sent after the turn is confirmed complete and the notification settings are satisfied. If another Hook continues the task, progress keeps updating; an interruption during that time is shown as terminated.
+After `Stop`, the task shows “Finishing up”, with approval waiting taking priority while a subagent still waits. A completion notification is sent after the turn is confirmed complete and the notification settings are satisfied; an interruption during that time is shown as terminated.
Interruption ends only the matching turn; a newer turn in the same session stays active. Task-based sleep prevention releases once all eligible tasks end.
Subagent activity is combined with its parent task. Internal automatic-review tasks and tasks whose origin remains unconfirmed do not appear as live tasks or trigger Task Glow, task alerts, or sleep prevention; their activity still contributes to daily statistics. Once the same session and turn have been confirmed as a normal task, later events with a temporarily unknown origin continue updating its state.
+When the main agent or a subagent waits for approval, progress from another agent does not clear its wait. The card stays in the waiting state while any user approval wait remains in that task.
+
Tasks with a known origin whose session cannot be identified show an orange anonymous icon. You can view them, but they do not trigger notifications or haptics, prevent sleep, or participate in Stalled Task Protection.
[Stalled Task Protection](sleep-prevention.md#stalled-task-protection) may hide running tasks that stop making progress. They reappear when progress resumes.
diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.md
index 0fa1bd3..2efc794 100644
--- a/Docs/en/UserGuide/settings.md
+++ b/Docs/en/UserGuide/settings.md
@@ -26,6 +26,8 @@ Disabling Hook hides Tasks; switching Hook from off to on shows Tasks automatica
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.
+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.
+
| Color | Meaning |
| --- | --- |
| Cyan moving glow | Tasks are running |
diff --git a/appcast.xml b/appcast.xml
index 3b5f916..ad613b8 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.2</title>
+ <sparkle:version>102</sparkle:version>
+ <sparkle:shortVersionString>4.0.2</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#4.0.2</sparkle:releaseNotesLink>
+ <pubDate>Tue, 15 Sep 2026 18:52:56 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v4.0.2.dmg" sparkle:edSignature="BwapF7NqkWMYh/nv09uUGLQYnrAJhzFhI8Qx7K9M7wQ5FKoQKspQnocupu4DDeoO9WZZbUwso6xwry8nvonOAA==" length="8160296" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 4.0.1</title>
<sparkle:version>101</sparkle:version>