CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 修正 Hook 与 rollout 协作中的任务状态判定
Bob74d7f5810963
diff --git a/CodexBar/Models/CodexActivityModels.swift b/CodexBar/Models/CodexActivityModels.swiftindex b2f7033..02273a3 100644--- a/CodexBar/Models/CodexActivityModels.swift+++ b/CodexBar/Models/CodexActivityModels.swift@@ -94,8 +94,6 @@ nonisolated struct CodexActivityProtectionNotice: Equatable, Sendable {let attemptID: UUIDlet projectName: String?let inactivityDurationText: String- let inactivityDurationSeconds: Int- let progressGeneration: UInt64}/// UI 只消费该快照, 不直接读取或解释 Hook 事件diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex afb55c5..ff56b8f 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -235,9 +235,7 @@ final class CodexNotificationService: NSObject {isStillRelevant: { [weak self] inself?.activityMonitor.isInactivityProtectionNoticeRelevant(taskID: notice.taskID,- attemptID: notice.attemptID,- progressGeneration: notice.progressGeneration,- inactivityDurationSeconds: notice.inactivityDurationSeconds+ attemptID: notice.attemptID) ?? false},retryCount: 0diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swiftindex d030404..d39a6db 100644--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift@@ -37,6 +37,10 @@ final class CodexActivityMonitor: ObservableObject {var tailReader: HookEventTailReader?private var tailReaderControlTask: Task<Void, Never>?private var tailReaderGeneration: UInt64 = 0+ private var recoveryTask: Task<Void, Never>?+ private var recoveryTaskID: UUID?+ private var isSystemSleeping = false+ private var isReconcilingLifecycles = falseprivate var sessionLifecyclePollTask: Task<Void, Never>?private var cleanupTask: Task<Void, Never>?private var cleanupDeadline: Date?@@ -105,6 +109,8 @@ final class CodexActivityMonitor: ObservableObject {guard let self else {return}+ isSystemSleeping = true+ recoveryTask?.cancel()beginActivityProtectionRecovery()AppLog.activity.notice("异常任务判定已暂停: reason=systemSleep")}@@ -120,29 +126,8 @@ final class CodexActivityMonitor: ObservableObject {AppLog.activity.notice("事件重读已触发: trigger=\(LogTrigger.wake.rawValue, privacy: .public)")- let recoveryGeneration = beginActivityProtectionRecovery()- guard let reader = tailReader else {- finishActivityProtectionRecovery(generation: recoveryGeneration)- return- }- let readerGeneration = tailReaderGeneration- Task { @MainActor [weak self] in- let drainResult = await reader.drainNow()- guard let self,- readerGeneration == tailReaderGeneration else {- return- }- guard case .completed = drainResult else {- finishActivityProtectionRecovery(generation: recoveryGeneration)- return- }- await sessionLifecycleReader.resetResolutionFallbacks()- await reconcileSessionLifecycles(generation: readerGeneration)- guard readerGeneration == tailReaderGeneration else {- return- }- finishActivityProtectionRecovery(generation: recoveryGeneration)- }+ isSystemSleeping = false+ requestActivityRecovery()}.store(in: &cancellables)@@ -232,6 +217,8 @@ final class CodexActivityMonitor: ObservableObject {private func stopReaderAndClearState() {tailReaderGeneration &+= 1+ recoveryTask?.cancel()+ recoveryTask = nilresetActivityProtectionRecovery()tailReaderControlTask?.cancel()tailReaderControlTask = nil@@ -267,7 +254,13 @@ final class CodexActivityMonitor: ObservableObject {guard let self else {return}- await reconcileSessionLifecycles(generation: generation)+ if isActivityProtectionRecoveryInProgress {+ if !isSystemSleeping, recoveryTask == nil {+ requestActivityRecovery()+ }+ } else {+ _ = await reconcileSessionLifecycles(generation: generation, terminalOnly: !isActivitySourceHealthy)+ }try? await Task.sleep(for: .seconds(Self.sessionLifecyclePollInterval))}}@@ -299,16 +292,20 @@ final class CodexActivityMonitor: ObservableObject {/// 待确认终态的任务与在跑的任务走两条分支, 前者已经从 tasks 里挪走private func applyLifecycleState(_ state: CodexSessionTaskLifecycleState,+ terminalOnly: Bool = false,into transitions: inout [CodexActivityTransition]) -> Bool {- let key = CodexActivityTaskKey.turn(session: state.sessionId, turn: state.turnId)+ guard !terminalOnly || (state.readStatus == .complete && state.terminal != nil) else { return false }+ let exact = CodexActivityTaskKey.turn(session: state.sessionId, turn: state.turnId)+ let key = tasks.first(where: { $0.value.resolvedTurnKey == exact })?.key+ ?? pendingTerminalTasks.first(where: { $0.value.task.resolvedTurnKey == exact })?.key ?? exactif var pending = pendingTerminalTasks[key] {let pendingDidChange = Self.mergeLifecycleBackfill(from: state,into: &pending.task)- guard let terminal = state.terminal else {+ guard state.readStatus == .complete, let terminal = state.terminal else {guard pendingDidChange else {return false}@@ -330,15 +327,21 @@ final class CodexActivityMonitor: ObservableObject {return false}- var taskDidChange = Self.mergeLifecycleBackfill(from: state, into: &task)- let progressDidChange = mergeLifecycleProgress(+ let hadLifecycleCoverage = task.lifecycleCoverageCheckedAt != nil+ if !terminalOnly {+ task.lifecycleCoverageCheckedAt = state.readStatus == .complete && state.hasContext ? Date() : nil+ if task.lifecycleCoverageCheckedAt == nil {+ cancelActivityProtectionAttempt(for: key)+ }+ }+ _ = Self.mergeLifecycleBackfill(from: state, into: &task)+ let progressDidChange = !terminalOnly && mergeLifecycleProgress(from: state,key: key,into: &task)- taskDidChange = progressDidChange || taskDidChange- if let terminal = state.terminal {+ if state.readStatus == .complete, let terminal = state.terminal {tasks.removeValue(forKey: key)resolveTerminal(terminal,@@ -351,9 +354,12 @@ final class CodexActivityMonitor: ObservableObject {}if let approvalReviewer = state.approvalReviewer,+ state.readStatus == .complete,+ let observedAt = state.contextObservedAt,+ observedAt >= (task.approvalContextObservedAt ?? .distantPast),task.approvalReviewer != approvalReviewer {task.approvalReviewer = approvalReviewer- taskDidChange = true+ task.approvalContextObservedAt = observedAt}let wasSuppressedBeforeApproval = task.state == .suppressed@@ -368,14 +374,10 @@ final class CodexActivityMonitor: ObservableObject {reason: .progress)}- taskDidChange = true}- guard taskDidChange else {- return false- }tasks[key] = task- if progressDidChange {+ if progressDidChange || (!hadLifecycleCoverage && task.lifecycleCoverageCheckedAt != nil) {suppressBackfilledActivityTaskIfOverdue(key, now: Date())}return true@@ -386,7 +388,8 @@ final class CodexActivityMonitor: ObservableObject {key: CodexActivityTaskKey,into task: inout CodexActivityTask) -> Bool {- guard let lastProgressAt = state.lastProgressAt,+ guard state.readStatus == .complete,+ let lastProgressAt = state.lastProgressAt,lastProgressAt > task.lastProgressAt else {return false}@@ -407,42 +410,94 @@ final class CodexActivityMonitor: ObservableObject {return true}- private func reconcileSessionLifecycles(generation: UInt64) async {- guard generation == tailReaderGeneration,- tailReader != nil,- !isBootstrapping else {- return+ /// 恢复只由读取屏障后的调用推进, 普通 poll 不能绕过恢复代次+ private func requestActivityRecovery() {+ guard !isSystemSleeping, let reader = tailReader, !isBootstrapping else { return }+ recoveryTask?.cancel()+ let recoveryGeneration = beginActivityProtectionRecovery()+ let generation = tailReaderGeneration+ let taskID = UUID()+ recoveryTaskID = taskID+ recoveryTask = Task { @MainActor [weak self] in+ let result = await reader.drainNow()+ guard let self else { return }+ defer {+ if recoveryTaskID == taskID {+ recoveryTask = nil+ recoveryTaskID = nil+ }+ }+ guard !Task.isCancelled, generation == tailReaderGeneration,+ recoveryGeneration == activityProtectionRecoveryGeneration else { return }+ if case .sourceUnavailable = result {+ // Hook 缺口只阻止完整恢复, 独立读取成功的明确终态仍可静默收敛+ _ = await reconcileSessionLifecycles(generation: generation, terminalOnly: true)+ return+ }+ guard case .completed = result, isActivitySourceHealthy, !isBootstrapping else { return }+ await sessionLifecycleReader.resetResolutionFallbacks()+ guard !Task.isCancelled, !isSystemSleeping,+ recoveryGeneration == activityProtectionRecoveryGeneration else { return }+ let didReconcile = await reconcileSessionLifecycles(generation: generation, recovering: true)+ guard didReconcile, !Task.isCancelled, generation == tailReaderGeneration,+ recoveryGeneration == activityProtectionRecoveryGeneration else { return }+ finishActivityProtectionRecovery(generation: recoveryGeneration)}+ }++ private func lifecycleReferences(now: Date, includeAll: Bool) -> [CodexActivityTurnReference] {+ var references = tasks.values.compactMap(\.turnReference)+ let due = pendingTerminalTasks.filter { includeAll || $0.value.nextPollAt <= now }+ .sorted { $0.value.nextPollAt < $1.value.nextPollAt }+ for (key, var pending) in due.prefix(16) {+ if let reference = pending.task.turnReference {+ references.append(reference)+ }+ pending.nextPollAt = now.addingTimeInterval(now < pending.deadline ? 1 : 30)+ pendingTerminalTasks[key] = pending+ }+ return references+ }++ @discardableResult+ private func reconcileSessionLifecycles(+ generation: UInt64,+ recovering: Bool = false,+ terminalOnly: Bool = false+ ) async -> Bool {+ guard generation == tailReaderGeneration, tailReader != nil, !isBootstrapping,+ terminalOnly || isActivitySourceHealthy, !isSystemSleeping,+ recovering || terminalOnly || !isActivityProtectionRecoveryInProgress,+ !isReconcilingLifecycles else { return false }+ isReconcilingLifecycles = true+ defer { isReconcilingLifecycles = false }let bootstrapGeneration = bootstrapCompletionGenerationlet recoveryGeneration = activityProtectionRecoveryGeneration- let references = tasks.values.compactMap(\.turnReference)- + pendingTerminalTasks.values.compactMap(\.task.turnReference)- guard !references.isEmpty else {- return- }+ let references = lifecycleReferences(now: Date(), includeAll: recovering)let states = await sessionLifecycleReader.lifecycleStates(for: references)- guard !Task.isCancelled,- generation == tailReaderGeneration,+ guard !Task.isCancelled, generation == tailReaderGeneration,bootstrapGeneration == bootstrapCompletionGeneration,recoveryGeneration == activityProtectionRecoveryGeneration,- tailReader != nil,- !isBootstrapping,- !states.isEmpty else {- return- }-+ tailReader != nil, !isBootstrapping, terminalOnly || isActivitySourceHealthy,+ !isSystemSleeping else { return false }var didChange = falsevar transitions: [CodexActivityTransition] = []for state in states {- didChange = applyLifecycleState(state, into: &transitions) || didChange+ didChange = applyLifecycleState(state, terminalOnly: terminalOnly, into: &transitions) || didChange}-if didChange {refreshSnapshot(now: Date())}- for transition in transitions {- transitionSubject.send(transition)+ if canPublishActivityTransitions {+ for transition in transitions {+ transitionSubject.send(transition)+ }}+ return true+ }++ var canPublishActivityTransitions: Bool {+ !isBootstrapping && !isActivityProtectionRecoveryInProgress && isActivitySourceHealthy}// MARK: - Hook 事件消费@@ -450,6 +505,8 @@ final class CodexActivityMonitor: ObservableObject {private func consume(_ batch: HookEventBatch) {switch batch {case .bootstrapStart:+ recoveryTask?.cancel()+ recoveryTask = nil// 重试会重放整段历史, 计时从第一次开始算才是用户等到的总时长if !isBootstrapping {bootstrapDuration = LogDuration()@@ -516,8 +573,11 @@ final class CodexActivityMonitor: ObservableObject {isActivitySourceHealthy = isHealthyresetTerminalPresentationEvents()if isHealthy {- reconcileActivityProtection(now: Date(), sendsNotification: false)+ if !isBootstrapping {+ requestActivityRecovery()+ }} else {+ beginActivityProtectionRecovery()cancelInactivityCheck()cancelAllActivityProtectionAttempts()AppLog.activity.error(@@ -532,18 +592,21 @@ final class CodexActivityMonitor: ObservableObject {attempts: Int,completionGeneration: UInt64) async {+ let recoveryGeneration = activityProtectionRecoveryGenerationif !degraded {let references = tasks.values.compactMap(\.turnReference)+ pendingTerminalTasks.values.compactMap(\.task.turnReference)if !references.isEmpty {let states = await sessionLifecycleReader.lifecycleStates(for: references)- guard completionGeneration == bootstrapCompletionGeneration,+ guard !Task.isCancelled, completionGeneration == bootstrapCompletionGeneration,tailReader != nil else {return}var ignoredTransitions: [CodexActivityTransition] = []- for state in states {- _ = applyLifecycleState(state, into: &ignoredTransitions)+ if recoveryGeneration == activityProtectionRecoveryGeneration, isActivitySourceHealthy, !isSystemSleeping {+ for state in states {+ _ = applyLifecycleState(state, into: &ignoredTransitions)+ }}}}@@ -554,6 +617,13 @@ final class CodexActivityMonitor: ObservableObject {}resetTerminalPresentationEvents()isBootstrapping = false+ if isActivitySourceHealthy, !isSystemSleeping {+ if recoveryGeneration == activityProtectionRecoveryGeneration {+ finishActivityProtectionRecovery(generation: recoveryGeneration)+ } else {+ requestActivityRecovery()+ }+ }let now = Date()applyPersistedActivityProtection(now: now)reconcileActivityProtection(now: now, sendsNotification: false)@@ -568,8 +638,8 @@ final class CodexActivityMonitor: ObservableObject {"events=\(eventCount)","activeTasks=\(activeCount)","elapsed=\(elapsed)",- "reason=unstableBoundary",- "action=skipHistory"+ "reason=incompleteHistory",+ "action=pauseProtection")AppLog.activity.notice("历史回放已降级: \(details, privacy: .public)")return@@ -694,6 +764,18 @@ final class CodexActivityMonitor: ObservableObject {source: CodexActivityEventSource) {let key = CodexActivityTaskKey(event: event)+ guard !updateAliasedPrompt(from: event, key: key) else { return }+ preserveSupersededSessionTask(from: event, key: key)+ if let pending = pendingTerminalTasks[key] {+ guard key.turnId == nil, event.timestamp > pending.supersededAt else { return }+ pendingTerminalTasks.removeValue(forKey: key)+ if let resolved = pending.task.resolvedTurnKey {+ pendingTerminalTasks[resolved] = pending+ }+ }+ if pendingTerminalTasks.values.contains(where: { $0.task.resolvedTurnKey == key }) {+ return+ }let existingTask = tasks[key]let displayID = existingTask?.displayID ?? UUID()if let endedAt = recentEndedDate(for: key) {@@ -704,7 +786,7 @@ final class CodexActivityMonitor: ObservableObject {return}}- if let existing = tasks[key], event.timestamp < existing.lastActivityAt {+ if let existing = tasks[key], event.timestamp < existing.lastHookEventAt {return}@@ -712,7 +794,7 @@ final class CodexActivityMonitor: ObservableObject {// 同一 session 的 turn 按顺序执行. 新 prompt 让旧 turn 立即退出活动列表// 但保留短暂终态确认窗口, 避免把迟到的正常完成误记为终止guard !tasks.values.contains(where: {- $0.key.sessionId == sessionId && $0.lastActivityAt > event.timestamp+ $0.key.sessionId == sessionId && $0.lastHookEventAt > event.timestamp}) else {return}@@ -720,8 +802,7 @@ final class CodexActivityMonitor: ObservableObject {$0.key != key && $0.key.sessionId == sessionId}for task in supersededTasks {- cancelActivityProtectionAttempt(for: task.key)- invalidateActivityProtectionNotification(for: task.displayID)+ clearActivityProtection(for: task.key, taskID: task.displayID, reason: .terminal)pendingTerminalTasks[task.key] = PendingTerminalTask(task: task,supersededAt: event.timestamp,@@ -747,7 +828,7 @@ final class CodexActivityMonitor: ObservableObject {recentlyEndedTaskAt.removeValue(forKey: .session(sessionId))}- tasks[key] = CodexActivityTask(+ var task = CodexActivityTask(displayID: displayID,key: key,event: event,@@ -756,6 +837,10 @@ final class CodexActivityMonitor: ObservableObject {startedAt: event.timestamp,progressGeneration: (existingTask?.progressGeneration ?? 0) &+ 1)+ if let existingTask {+ task.lastProgressAt = max(task.lastProgressAt, existingTask.lastProgressAt)+ }+ tasks[key] = task}private func resumeTask(@@ -774,7 +859,7 @@ final class CodexActivityMonitor: ObservableObject {pendingTerminalTasks[key] == nil else {return}- guard event.timestamp >= task.lastActivityAt else {+ guard event.timestamp >= task.lastHookEventAt else {return}@@ -786,7 +871,7 @@ final class CodexActivityMonitor: ObservableObject {task.pendingApprovalRequestedAt = niltask.latestEvent = latestEventtask.mergeMetadata(from: event)- task.recordProgress(at: event.timestamp)+ task.recordHookEvent(at: event.timestamp)tasks[key] = taskif wasSuppressed || source == .live {clearActivityProtection(@@ -800,7 +885,8 @@ final class CodexActivityMonitor: ObservableObject {guard allowsRecovery,recentEndedDate(for: eventKey) == nil,- pendingTerminalTasks[eventKey] == nil else {+ pendingTerminalTasks[eventKey] == nil,+ !pendingTerminalTasks.values.contains(where: { $0.task.resolvedTurnKey == eventKey }) else {return}@@ -846,7 +932,7 @@ final class CodexActivityMonitor: ObservableObject {at: event.timestamp)- if event.timestamp >= task.lastActivityAt {+ if event.timestamp >= task.lastHookEventAt {let wasSuppressed = task.state == .suppressedif task.state != .running {task.state = .running@@ -855,7 +941,7 @@ final class CodexActivityMonitor: ObservableObject {task.pendingApprovalRequestedAt = niltask.latestEvent = isStarting ? .subagentStarted : .subagentFinishedtask.mergeMetadata(from: event)- task.recordProgress(at: event.timestamp)+ task.recordHookEvent(at: event.timestamp)if wasSuppressed || source == .live {clearActivityProtection(for: key,@@ -881,7 +967,7 @@ final class CodexActivityMonitor: ObservableObject {pendingTerminalTasks[key] == nil else {return nil}- guard event.timestamp >= task.lastActivityAt else {+ guard event.timestamp >= task.lastHookEventAt else {return nil}@@ -889,7 +975,7 @@ final class CodexActivityMonitor: ObservableObject {task.mergeMetadata(from: event)// 权限事件描述当前请求; 缺失工具名时不能沿用上一条工具事件task.toolName = event.toolName- task.recordProgress(at: event.timestamp)+ task.recordHookEvent(at: event.timestamp)let enteredWaiting = task.recordApprovalRequest(at: event.timestamp)tasks[key] = taskif wasSuppressed || source == .live {@@ -904,7 +990,8 @@ final class CodexActivityMonitor: ObservableObject {guard event.agentId == nil,recentEndedDate(for: eventKey) == nil,- pendingTerminalTasks[eventKey] == nil else {+ pendingTerminalTasks[eventKey] == nil,+ !pendingTerminalTasks.values.contains(where: { $0.task.resolvedTurnKey == eventKey }) else {return nil}@@ -943,12 +1030,12 @@ final class CodexActivityMonitor: ObservableObject {AppLog.activity.error("任务终态已延后: reason=ambiguousStop")case let .pending(key):guard var pending = pendingTerminalTasks[key],- event.timestamp >= pending.task.lastActivityAt else {+ event.timestamp >= pending.task.lastHookEventAt else {return}// 新 turn 或 SessionEnd 已确定旧任务退出活动列表, Stop 不恢复它或重置 gracepending.task.mergeMetadata(from: event)- pending.task.recordProgress(at: event.timestamp)+ pending.task.recordHookEvent(at: event.timestamp)pendingTerminalTasks[key] = pendingcase .active, .none:resumeTask(@@ -986,7 +1073,7 @@ final class CodexActivityMonitor: ObservableObject {let deadline = Date().addingTimeInterval(Self.supersededTerminalGracePeriod)let matchingPendingTasks = pendingTerminalTasks.filter { key, pending in- key.sessionId == sessionId && pending.task.lastActivityAt <= event.timestamp+ key.sessionId == sessionId && pending.task.lastHookEventAt <= event.timestamp}for (key, pending) in matchingPendingTasks {pendingTerminalTasks[key] = PendingTerminalTask(@@ -997,12 +1084,11 @@ final class CodexActivityMonitor: ObservableObject {}let matchingActiveTasks = tasks.filter { key, task in- key.sessionId == sessionId && task.lastActivityAt <= event.timestamp+ key.sessionId == sessionId && task.lastHookEventAt <= event.timestamp}for (key, task) in matchingActiveTasks {tasks.removeValue(forKey: key)- cancelActivityProtectionAttempt(for: key)- invalidateActivityProtectionNotification(for: task.displayID)+ clearActivityProtection(for: key, taskID: task.displayID, reason: .terminal)pendingTerminalTasks[key] = PendingTerminalTask(task: task,supersededAt: event.timestamp,@@ -1014,6 +1100,9 @@ final class CodexActivityMonitor: ObservableObject {/// 精确 turn 失败后只接受同 session 唯一活动任务, 有待确认旧 turn 时不猜测private func matchingActiveTaskKey(for event: WorkflowHookEvent) -> CodexActivityTaskKey? {let exactKey = CodexActivityTaskKey(event: event)+ if let key = tasks.first(where: { $0.value.resolvedTurnKey == exactKey })?.key {+ return key+ }if tasks[exactKey] != nil {return exactKey}@@ -1026,7 +1115,7 @@ final class CodexActivityMonitor: ObservableObject {}let candidates = tasks.values.filter { task intask.key.sessionId == sessionId- && (event.turnId == nil || task.key.isSessionOnly)+ && (event.turnId == nil || task.associatedTurnId == nil)}guard candidates.count == 1 else {return nil@@ -1044,14 +1133,12 @@ final class CodexActivityMonitor: ObservableObject {private func matchingSubagentParentTaskKey(for event: WorkflowHookEvent) -> CodexActivityTaskKey? {- guard let sessionId = event.sessionId,- !pendingTerminalTasks.values.contains(where: {- $0.task.key.sessionId == sessionId- }) else {- return nil- }+ guard let sessionId = event.sessionId else { return nil }let candidates = tasks.values.filter { $0.key.sessionId == sessionId }- guard candidates.count == 1 else {+ 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@@ -1062,6 +1149,12 @@ final class CodexActivityMonitor: ObservableObject {allowsAnonymousFallback: Bool = true) -> CodexTerminalTaskMatch {let exactKey = CodexActivityTaskKey(event: event)+ if let key = pendingTerminalTasks.first(where: { $0.value.task.resolvedTurnKey == exactKey })?.key {+ return .pending(key)+ }+ if let key = tasks.first(where: { $0.value.resolvedTurnKey == exactKey })?.key {+ return .active(key)+ }if pendingTerminalTasks[exactKey] != nil {return .pending(exactKey)}@@ -1071,13 +1164,13 @@ final class CodexActivityMonitor: ObservableObject {}if let sessionId = event.sessionId {- let pendingCandidates = pendingTerminalTasks.values.filter {- $0.task.key.sessionId == sessionId- && $0.task.lastActivityAt <= event.timestamp- && (event.turnId == nil || $0.task.key.isSessionOnly)+ let pendingCandidates = pendingTerminalTasks.filter {+ $0.value.task.key.sessionId == sessionId+ && $0.value.task.lastHookEventAt <= event.timestamp+ && (event.turnId == nil || $0.value.task.associatedTurnId == nil)}- if pendingCandidates.count == 1 {- return .pending(pendingCandidates[0].task.key)+ if pendingCandidates.count == 1, let key = pendingCandidates.keys.first {+ return .pending(key)}if pendingCandidates.count > 1 {return .ambiguous@@ -1085,8 +1178,8 @@ final class CodexActivityMonitor: ObservableObject {let activeCandidates = tasks.values.filter {$0.key.sessionId == sessionId- && $0.lastActivityAt <= event.timestamp- && (event.turnId == nil || $0.key.isSessionOnly)+ && $0.lastHookEventAt <= event.timestamp+ && (event.turnId == nil || $0.associatedTurnId == nil)}if activeCandidates.count == 1 {return .active(activeCandidates[0].key)@@ -1203,7 +1296,7 @@ final class CodexActivityMonitor: ObservableObject {deadlines.append(contentsOf: terminations.map {$0.terminatedAt.addingTimeInterval(Self.recentHistoryRetention)})- deadlines.append(contentsOf: pendingTerminalTasks.values.map(\.deadline))+ deadlines.append(contentsOf: pendingTerminalTasks.values.map(\.expiresAt))deadlines.append(contentsOf: recentlyEndedTaskAt.values.map {$0.addingTimeInterval(Self.endedTaskRetention)})@@ -1242,3 +1335,29 @@ final class CodexActivityMonitor: ObservableObject {private static let supersededTerminalGracePeriod: TimeInterval = 5private static let sessionLifecyclePollInterval: TimeInterval = 1}++private extension CodexActivityMonitor {+ func preserveSupersededSessionTask(from event: WorkflowHookEvent, key: CodexActivityTaskKey) {+ if let existing = tasks[key], key.isSessionOnly,+ let resolved = existing.resolvedTurnKey,+ event.timestamp > (existing.startedAt ?? existing.lastHookEventAt) {+ pendingTerminalTasks[resolved] = PendingTerminalTask(+ task: existing,+ supersededAt: event.timestamp,+ deadline: Date().addingTimeInterval(Self.supersededTerminalGracePeriod)+ )+ }+ }++ func updateAliasedPrompt(from event: WorkflowHookEvent, key: CodexActivityTaskKey) -> Bool {+ guard let existing = tasks.values.first(where: { $0.resolvedTurnKey == key && $0.key != key }) else {+ return false+ }+ guard event.timestamp >= existing.lastHookEventAt else { return true }+ var task = existing+ task.mergeMetadata(from: event)+ task.recordHookEvent(at: event.timestamp)+ tasks[existing.key] = task+ return true+ }+}diff --git a/CodexBar/Services/Workflow/CodexActivityProtection.swift b/CodexBar/Services/Workflow/CodexActivityProtection.swiftindex df928a6..02030bd 100644--- a/CodexBar/Services/Workflow/CodexActivityProtection.swift+++ b/CodexBar/Services/Workflow/CodexActivityProtection.swift@@ -43,6 +43,7 @@ extension CodexActivityMonitor {func beginActivityProtectionRecovery() -> UInt64 {activityProtectionRecoveryGeneration &+= 1isActivityProtectionRecoveryInProgress = true+ sessionTransitionNotBefore = nilresetTerminalPresentationEvents()cancelInactivityCheck()cancelAllActivityProtectionAttempts()@@ -55,6 +56,7 @@ extension CodexActivityMonitor {}resetTerminalPresentationEvents()isActivityProtectionRecoveryInProgress = false+ sessionTransitionNotBefore = Date()reconcileActivityProtection(now: Date(), sendsNotification: false)}@@ -67,12 +69,13 @@ extension CodexActivityMonitor {func applyPersistedActivityProtection(now: Date) {removeExpiredActivityProtectionRecords(now: now)- guard isActivityProtectionEnabled else {+ guard canEvaluateActivityProtection else {return}for (key, var task) in tasks {- guard let identifier = key.activityProtectionIdentifier,+ guard task.hasFreshLifecycle(at: now),+ let identifier = key.activityProtectionIdentifier,let record = activityProtectionRecords[identifier] else {continue}@@ -123,6 +126,7 @@ extension CodexActivityMonitor {let overdueKeys = tasks.compactMap { key, task -> CodexActivityTaskKey? inguard !key.isAnonymous,task.state == .running,+ task.hasFreshLifecycle(at: now),task.lastProgressAt.addingTimeInterval(threshold) <= now else {return nil}@@ -144,6 +148,7 @@ extension CodexActivityMonitor {let nextDeadline = tasks.compactMap { key, task -> Date? inguard !key.isAnonymous,task.state == .running,+ task.hasFreshLifecycle(at: now),activityProtectionAttempts[key] == nil else {return nil}@@ -180,8 +185,7 @@ extension CodexActivityMonitor {}func beginDueInactivityChecks(now: Date) {- guard isActivityProtectionEnabled,- !isActivityProtectionRecoveryInProgress else {+ guard canEvaluateActivityProtection else {refreshSnapshot(now: now)return}@@ -190,6 +194,7 @@ extension CodexActivityMonitor {let candidates = tasks.compactMap { key, task -> ActivityProtectionCandidate? inguard !key.isAnonymous,task.state == .running,+ task.hasFreshLifecycle(at: now),activityProtectionAttempts[key] == nil,task.lastProgressAt.addingTimeInterval(threshold) <= now else {return nil@@ -249,9 +254,7 @@ extension CodexActivityMonitor {taskID: candidate.taskID,attemptID: attemptID,projectName: candidate.projectName,- inactivityDurationText: candidate.inactivityDuration.title,- inactivityDurationSeconds: candidate.inactivityDuration.rawValue,- progressGeneration: candidate.progressGeneration+ inactivityDurationText: candidate.inactivityDuration.title)let notificationHandler = onInactivityProtectionTriggeredTask { @MainActor [weak self] in@@ -337,9 +340,11 @@ extension CodexActivityMonitor {isActivityProtectionEnabled,tailReader != nil,!isBootstrapping,+ !isActivityProtectionRecoveryInProgress,isActivitySourceHealthy,let task = tasks[key],task.state == .running,+ task.hasFreshLifecycle(at: now),task.lastProgressAt.addingTimeInterval(activityProtectionSettings.inactivityDuration.timeInterval) <= now else {@@ -400,6 +405,7 @@ extension CodexActivityMonitor {let task = tasks[candidate.key],task.displayID == candidate.taskID,task.state == .running,+ task.hasFreshLifecycle(at: now),task.lastProgressAt == candidate.lastProgressAt,task.progressGeneration == candidate.progressGeneration else {return false@@ -410,30 +416,16 @@ extension CodexActivityMonitor {func isInactivityProtectionNoticeRelevant(taskID: UUID,- attemptID: UUID,- progressGeneration: UInt64,- inactivityDurationSeconds: Int+ attemptID: UUID) -> Bool {- guard canEvaluateActivityProtection,- activityProtectionSettings.inactivityDuration.rawValue == inactivityDurationSeconds,- activityProtectionNoticeAttemptIDs[taskID] == attemptID,+ guard activityProtectionNoticeAttemptIDs[taskID] == attemptID,let attempt = activityProtectionAttempts.values.first(where: {$0.id == attemptID && $0.candidate.taskID == taskID}) else {return false}- let now = Date()- guard !attempt.candidate.key.isAnonymous,- let task = tasks[attempt.candidate.key] else {- return false- }- return task.displayID == taskID- && task.state == .running- && task.progressGeneration == progressGeneration- && task.lastProgressAt.addingTimeInterval(- activityProtectionSettings.inactivityDuration.timeInterval- ) <= now+ return isActivityProtectionCandidateRelevant(attempt.candidate, now: Date())}func shouldRestoreActivityProtection(diff --git a/CodexBar/Services/Workflow/CodexActivityTask.swift b/CodexBar/Services/Workflow/CodexActivityTask.swiftindex 5606c7b..7420ffa 100644--- a/CodexBar/Services/Workflow/CodexActivityTask.swift+++ b/CodexBar/Services/Workflow/CodexActivityTask.swift@@ -23,6 +23,13 @@ enum CodexActivityTaskKey: Hashable {}}+ var turnId: String? {+ if case let .turn(_, turn) = self {+ return turn+ }+ return nil+ }+var isAnonymous: Bool {if case .anonymous = self {return true@@ -103,11 +110,18 @@ struct PendingTerminalTask {var task: CodexActivityTasklet supersededAt: Datelet deadline: Date+ var nextPollAt: Date = .distantPast+ var expiresAt: Date {+ supersededAt.addingTimeInterval(CodexActivityRetention.window)+ }}struct CodexActivityTask {let displayID: UUIDlet key: CodexActivityTaskKey+ var associatedTurnId: String?+ var lifecycleCoverageCheckedAt: Date?+ var approvalContextObservedAt: Date?var state: CodexActivityTaskStatevar latestEvent: CodexActivityEventvar projectName: String?@@ -116,7 +130,7 @@ struct CodexActivityTask {var toolName: String?var startedAt: Date?var stateChangedAt: Date- var lastActivityAt: Date+ var lastHookEventAt: Datevar lastProgressAt: Datevar progressGeneration: UInt64var approvalReviewer: CodexApprovalReviewer?@@ -135,6 +149,7 @@ struct CodexActivityTask {) {self.displayID = displayIDself.key = key+ associatedTurnId = key.turnIdself.state = stateself.latestEvent = latestEventprojectName = event.projectDisplayName@@ -143,10 +158,11 @@ struct CodexActivityTask {toolName = event.toolNameself.startedAt = startedAtstateChangedAt = event.timestamp- lastActivityAt = event.timestamp+ lastHookEventAt = event.timestamplastProgressAt = event.timestampself.progressGeneration = progressGenerationapprovalReviewer = event.approvalReviewer+ approvalContextObservedAt = event.approvalReviewer == nil ? nil : event.timestamppendingApprovalRequestedAt = nilsubagentsByID = [:]isSubagentCountReliable = startedAt != nil@@ -181,7 +197,7 @@ struct CodexActivityTask {}var turnReference: CodexActivityTurnReference? {- guard case let .turn(sessionId, turnId) = key else {+ guard let sessionId = key.sessionId, let turnId = associatedTurnId else {return nil}return CodexActivityTurnReference(@@ -193,23 +209,48 @@ struct CodexActivityTask {var promptReference: CodexActivityPromptReference? {guard startedAt == nil,- case let .turn(sessionId, turnId) = key else {+ let sessionId = key.sessionId, let turnId = associatedTurnId else {return nil}return CodexActivityPromptReference(sessionId: sessionId, turnId: turnId)}+ var resolvedTurnKey: CodexActivityTaskKey? {+ guard let session = key.sessionId, let turn = associatedTurnId else { return nil }+ return .turn(session: session, turn: turn)+ }++ var lastActivityAt: Date {+ lastProgressAt+ }++ func hasFreshLifecycle(at now: Date) -> Bool {+ lifecycleCoverageCheckedAt.map { now.timeIntervalSince($0) < 5 } == true+ }+mutating func mergeMetadata(from event: WorkflowHookEvent) {+ if associatedTurnId == nil, !key.isAnonymous, event.agentId == nil {+ associatedTurnId = event.turnId+ }projectName = event.projectDisplayName ?? projectNamemodelName = event.modelName ?? modelName_ = mergeEffort(event.effort)toolName = event.toolName ?? toolName- approvalReviewer = event.approvalReviewer ?? approvalReviewer+ if let reviewer = event.approvalReviewer,+ event.timestamp >= (approvalContextObservedAt ?? .distantPast) {+ approvalReviewer = reviewer+ approvalContextObservedAt = event.timestamp+ }+ }++ /// Hook 顺序独立于 rollout 进展, 避免用量记录使稍早的状态事件失效+ mutating func recordHookEvent(at timestamp: Date) {+ lastHookEventAt = max(lastHookEventAt, timestamp)+ recordProgress(at: timestamp)}mutating func recordProgress(at timestamp: Date) {- lastActivityAt = max(lastActivityAt, timestamp)- lastProgressAt = timestamp+ lastProgressAt = max(lastProgressAt, timestamp)progressGeneration &+= 1}diff --git a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift b/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swiftindex 8379723..fcd4ad5 100644--- a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift+++ b/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift@@ -28,7 +28,7 @@ extension CodexActivityMonitor {key = eventKeytask = nil}- guard task.map({ event.timestamp >= $0.lastActivityAt }) ?? true else {+ guard task.map({ event.timestamp >= $0.lastHookEventAt }) ?? true else {return}if recentEndedDate(for: key) != nil {@@ -48,6 +48,9 @@ extension CodexActivityMonitor {duration: task?.preciseDuration(until: event.timestamp))recordEndedTask(key, at: event.timestamp)+ if let resolved = task?.resolvedTurnKey {+ recordEndedTask(resolved, at: event.timestamp)+ }recordEndedTask(eventKey, at: event.timestamp)if source == .live {AppLog.activity.notice("任务已终止: source=interruptHook")@@ -70,7 +73,7 @@ extension CodexActivityMonitor {case .user:let wasWaiting = task.state == .waitingApprovaltask.confirmPendingApproval()- if !wasWaiting,+ if !wasWaiting, canPublishActivityTransitions,!task.key.isAnonymous,let sessionTransitionNotBefore,requestedAt >= sessionTransitionNotBefore {@@ -104,6 +107,9 @@ extension CodexActivityMonitor {let terminatedAt = max(reportedAt ?? abortFallback, task.lastActivityAt)storeTermination(task, at: terminatedAt, includesDuration: reportedAt != nil)recordEndedTask(key, at: terminatedAt)+ if let resolved = task.resolvedTurnKey {+ recordEndedTask(resolved, at: terminatedAt)+ }case let .completed(completedAt, duration):let completion = storeResolvedCompletion(task,@@ -111,7 +117,8 @@ extension CodexActivityMonitor {completedAt: completedAt,reportedDuration: duration)- if !completion.isAnonymous,+ if canPublishActivityTransitions, !completion.isAnonymous,+ Date().timeIntervalSince(completion.completedAt) <= 10,let sessionTransitionNotBefore,completion.completedAt >= sessionTransitionNotBefore {transitions.append(.completed(completion))@@ -167,6 +174,9 @@ extension CodexActivityMonitor {terminalTaskKeyByID[completion.id] = keyrecordTerminalPresentationEvent(.completed(completion))recordEndedTask(key, at: recordedCompletedAt)+ if let resolved = task.resolvedTurnKey {+ recordEndedTask(resolved, at: recordedCompletedAt)+ }return completion}@@ -208,7 +218,7 @@ extension CodexActivityMonitor {}func recordTerminalPresentationEvent(_ event: CodexActivityTerminalEvent) {- guard !isBootstrapping, !isActivityProtectionRecoveryInProgress, isActivitySourceHealthy,+ guard canPublishActivityTransitions, Date().timeIntervalSince(event.endedAt) <= 10,event.endedAt >= terminalPresentationNotBefore else {return}@@ -228,6 +238,9 @@ extension CodexActivityMonitor {guard let date = recentlyEndedTaskAt[key] else {return nil}+ if key.isSessionOnly, let startedAt = tasks[key]?.startedAt, startedAt > date {+ return nil+ }guard date > now.addingTimeInterval(-Self.endedTaskRetention) else {recentlyEndedTaskAt.removeValue(forKey: key)return nil@@ -262,17 +275,12 @@ extension CodexActivityMonitor {func finalizeExpiredPendingTerminalTasks(now: Date) {let expiredKeys = pendingTerminalTasks.compactMap { key, pending in- pending.deadline <= now ? key : nil+ pending.expiresAt <= now ? key : nil}for key in expiredKeys {guard let pending = pendingTerminalTasks.removeValue(forKey: key) else {continue}- let terminatedAt = max(pending.supersededAt, pending.task.lastActivityAt)- if pending.task.state != .suppressed {- storeTermination(pending.task, at: terminatedAt, includesDuration: true)- }- recordEndedTask(key, at: terminatedAt)clearActivityProtection(for: key,taskID: pending.task.displayID,@@ -282,6 +290,7 @@ extension CodexActivityMonitor {}func publishWaitingApprovalTransitions(_ taskKeys: [CodexActivityTaskKey]) {+ guard canPublishActivityTransitions else { return }var lastWaitingIndexByKey: [CodexActivityTaskKey: Int] = [:]for (index, key) in taskKeys.enumerated() {lastWaitingIndexByKey[key] = index@@ -291,7 +300,10 @@ extension CodexActivityMonitor {guard !key.isAnonymous,lastWaitingIndexByKey[key] == index,let task = tasks[key],- task.state == .waitingApproval else {+ task.state == .waitingApproval,+ let sessionTransitionNotBefore,+ task.stateChangedAt >= sessionTransitionNotBefore,+ Date().timeIntervalSince(task.stateChangedAt) <= 10 else {continue}transitionSubject.send(.waitingApproval(task.snapshot))diff --git a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swiftindex c9c25a4..e6ebe3e 100644--- a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift+++ b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift@@ -7,371 +7,237 @@ nonisolated struct CodexActivityTurnReference: Hashable {let startedAt: Date}-/// 增量读取活跃 Codex session 的 rollout JSONL, 只提取 turn 生命周期字段+/// 文件读取结果包含覆盖状态, 缓存事实不能替代本轮读取成功actor CodexSessionLifecycleReader {private let sessionsRootURL: URLprivate let archivedSessionsRootURL: URLprivate let fileManager: FileManager+ private var roundRobinOffset = 0private var cursorsBySession: [String: SessionFileCursor] = [:]private var lastResolutionAttemptBySession: [String: Date] = [:]- private var recursiveFallbackSessionIds = Set<String>()+ private var lastRecursiveAttemptBySession: [String: Date] = [:]- init(- codexHomeURL: URL = CodexCLIResolver.codexHomeDirectory(),- fileManager: FileManager = .default- ) {+ init(codexHomeURL: URL = CodexCLIResolver.codexHomeDirectory(), fileManager: FileManager = .default) {sessionsRootURL = codexHomeURL.appendingPathComponent("sessions", isDirectory: true)- archivedSessionsRootURL = codexHomeURL.appendingPathComponent(- "archived_sessions",- isDirectory: true- )+ archivedSessionsRootURL = codexHomeURL.appendingPathComponent("archived_sessions", isDirectory: true)self.fileManager = fileManager}- /// 返回 rollout 中已知的起点和终态, 不解码会话或工具内容- func lifecycleStates(- for references: [CodexActivityTurnReference]- ) -> [CodexSessionTaskLifecycleState] {- let referencesBySession = Dictionary(grouping: references, by: \CodexActivityTurnReference.sessionId)- let activeSessionIds = Set(referencesBySession.keys)- cursorsBySession = cursorsBySession.filter { activeSessionIds.contains($0.key) }- lastResolutionAttemptBySession = lastResolutionAttemptBySession.filter {- activeSessionIds.contains($0.key)- }- recursiveFallbackSessionIds.formIntersection(activeSessionIds)-+ func lifecycleStates(for references: [CodexActivityTurnReference]) -> [CodexSessionTaskLifecycleState] {+ let grouped = Dictionary(grouping: references, by: \.sessionId)+ let cutoff = Date().addingTimeInterval(-CodexActivityRetention.window)+ cursorsBySession = cursorsBySession.filter { $0.value.lastReadAt > cutoff }+ lastResolutionAttemptBySession = lastResolutionAttemptBySession.filter { $0.value > cutoff }+ lastRecursiveAttemptBySession = lastRecursiveAttemptBySession.filter { $0.value > cutoff }+ var budget = Self.contextByteLimit+ var performedBackfill = falsevar states: [CodexSessionTaskLifecycleState] = []- var performedEffortBackfill = false- let now = Date()- for (sessionId, sessionReferences) in referencesBySession {- guard let reference = sessionReferences.max(by: { $0.startedAt < $1.startedAt }),- var cursor = cursor(for: reference) else {- continue- }-- scanNewLifecycleEvents(into: &cursor, fallbackReference: reference)- pruneEffortBackfillState(- in: &cursor,- activeTurnIds: Set(sessionReferences.map(\.turnId))- )- if !performedEffortBackfill,- let reference = effortBackfillReference(- from: sessionReferences,- cursor: cursor,- now: now- ) {- performedEffortBackfill = true- cursor.lastEffortBackfillAttemptByTurnId[reference.turnId] = now- switch backfilledEffort(- from: cursor.url,- turnId: reference.turnId- ) {- case let .found(effort):- var lifecycle = cursor.lifecycleByTurnId[reference.turnId]- ?? SessionTurnLifecycle()- lifecycle.apply(- .context(approvalReviewer: nil, effort: effort)- )- cursor.lifecycleByTurnId[reference.turnId] = lifecycle- cursor.completedEffortBackfillTurnIds.insert(reference.turnId)- cursor.lastEffortBackfillAttemptByTurnId.removeValue(- forKey: reference.turnId- )- case .notFound:- cursor.completedEffortBackfillTurnIds.insert(reference.turnId)- cursor.lastEffortBackfillAttemptByTurnId.removeValue(- forKey: reference.turnId- )- case .unavailable:- break+ let sessions = grouped.keys.sorted()+ let start = sessions.isEmpty ? 0 : roundRobinOffset % sessions.count+ let ordered = Array(sessions.dropFirst(start)) + Array(sessions.prefix(start))+ roundRobinOffset = sessions.isEmpty ? 0 : (start + 1) % sessions.count+ for sessionId in ordered {+ guard let sessionReferences = grouped[sessionId],+ let latest = sessionReferences.max(by: { $0.startedAt < $1.startedAt }) else { continue }+ var status = CodexSessionReadStatus.notFound+ if var cursor = cursor(for: latest) {+ status = scan(into: &cursor, limit: min(Self.incrementalByteLimit, budget))+ budget -= min(budget, cursor.lastReadByteCount)+ let needsContext = sessionReferences.contains {+ let known = cursor.lifecycleByTurnId[$0.turnId]+ return known?.terminal == nil && (known?.hasContext != true || known?.effort == nil || known?.approvalReviewer == nil)+ }+ if status == .complete, needsContext, cursor.historicalOffset > 0,+ !cursor.didBackfill, !performedBackfill {+ status = backfillContext(into: &cursor)+ performedBackfill = true+ }+ cursor.lastReadAt = Date()+ let referencedTurns = Set(sessionReferences.map(\.turnId))+ cursor.lifecycleByTurnId = cursor.lifecycleByTurnId.filter {+ referencedTurns.contains($0.key) || ($0.value.lastProgressAt ?? .distantPast) > cutoff}+ cursorsBySession[sessionId] = cursor}- cursorsBySession[sessionId] = cursor+ let cursor = cursorsBySession[sessionId]for reference in sessionReferences {- guard let lifecycle = cursor.lifecycleByTurnId[reference.turnId] else {- continue- }- states.append(- CodexSessionTaskLifecycleState(- sessionId: reference.sessionId,- turnId: reference.turnId,- startedAt: lifecycle.startedAt,- approvalReviewer: lifecycle.approvalReviewer,- effort: lifecycle.effort,- lastProgressAt: lifecycle.lastProgressAt,- terminal: lifecycle.terminal- )- )+ let known = cursor?.lifecycleByTurnId[reference.turnId]+ let hasReadGap = known?.hasReadGap ?? (cursor?.hasDecodeFailures == true)+ let turnStatus: CodexSessionReadStatus = status == .complete && hasReadGap && known?.terminal == nil+ ? .incomplete : status+ states.append(CodexSessionTaskLifecycleState(+ sessionId: sessionId, turnId: reference.turnId, startedAt: known?.startedAt,+ approvalReviewer: known?.approvalReviewer, effort: known?.effort,+ lastProgressAt: known?.lastProgressAt, terminal: turnStatus == .complete ? known?.terminal : nil,+ readStatus: turnStatus, hasContext: known?.hasContext == true,+ contextObservedAt: known?.contextObservedAt+ ))}}return states}- private func pruneEffortBackfillState(- in cursor: inout SessionFileCursor,- activeTurnIds: Set<String>- ) {- cursor.completedEffortBackfillTurnIds.formIntersection(activeTurnIds)- cursor.lastEffortBackfillAttemptByTurnId = cursor- .lastEffortBackfillAttemptByTurnId- .filter { activeTurnIds.contains($0.key) }- }-- private func effortBackfillReference(- from references: [CodexActivityTurnReference],- cursor: SessionFileCursor,- now: Date- ) -> CodexActivityTurnReference? {- guard cursor.hasUnscannedHistoricalPrefix else {- return nil- }-- return references- .filter { reference in- guard now.timeIntervalSince(reference.startedAt)- >= Self.effortBackfillMinimumTaskAge,- cursor.lifecycleByTurnId[reference.turnId]?.effort == nil,- cursor.lifecycleByTurnId[reference.turnId]?.terminal == nil,- !cursor.completedEffortBackfillTurnIds.contains(reference.turnId) else {- return false- }- guard let lastAttempt = cursor- .lastEffortBackfillAttemptByTurnId[reference.turnId] else {- return true- }- return now.timeIntervalSince(lastAttempt)- >= Self.effortBackfillRetryInterval- }- .max(by: { $0.startedAt < $1.startedAt })- }-- /// 唤醒后允许仍未定位到文件的活跃 session 重新执行一次递归兜底func resetResolutionFallbacks() {lastResolutionAttemptBySession.removeAll()- recursiveFallbackSessionIds.removeAll()+ lastRecursiveAttemptBySession.removeAll()}- // MARK: - 会话文件定位-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], fileManager.fileExists(atPath: cursor.url.path) {return cursor}if cursorsBySession.removeValue(forKey: reference.sessionId) != nil {- // 缓存文件可能被移动到 archived_sessions, 允许重新完整定位一次- recursiveFallbackSessionIds.remove(reference.sessionId)+ lastResolutionAttemptBySession.removeValue(forKey: reference.sessionId)+ lastRecursiveAttemptBySession.removeValue(forKey: reference.sessionId)}-let now = Date()- if let lastAttempt = lastResolutionAttemptBySession[reference.sessionId],- now.timeIntervalSince(lastAttempt) < Self.fileResolutionRetryInterval {+ if let last = lastResolutionAttemptBySession[reference.sessionId], now.timeIntervalSince(last) < 10 {return nil}lastResolutionAttemptBySession[reference.sessionId] = now-- let url = locateLikelySessionFile(for: reference)- ?? recursiveSessionFileIfNeeded(for: reference)- guard let url else {- return nil- }- lastResolutionAttemptBySession.removeValue(forKey: reference.sessionId)- return initialCursor(for: url)- }-- private func locateLikelySessionFile(for reference: CodexActivityTurnReference) -> URL? {let suffix = "-\(reference.sessionId).jsonl"- let likelyDirectories = [- sessionDirectory(for: reference.startedAt),- sessionDirectory(for: Date()),- archivedSessionsRootURL- ]-- for directory in likelyDirectories {- if let match = matchingFile(in: directory, suffix: suffix) {- return match+ for directory in [sessionDirectory(for: reference.startedAt), sessionDirectory(for: now), archivedSessionsRootURL] {+ if let url = matchingFile(in: directory, suffix: suffix) {+ return initialCursor(for: url)}}- return nil- }-- private func recursiveSessionFileIfNeeded(- for reference: CodexActivityTurnReference- ) -> URL? {- guard recursiveFallbackSessionIds.insert(reference.sessionId).inserted else {+ if let last = lastRecursiveAttemptBySession[reference.sessionId], now.timeIntervalSince(last) < 60 {return nil}-- // resume 可能继续很早以前创建的 session; 每次活跃生命周期最多递归一次- let suffix = "-\(reference.sessionId).jsonl"+ lastRecursiveAttemptBySession[reference.sessionId] = nowguard let enumerator = fileManager.enumerator(- at: sessionsRootURL,- includingPropertiesForKeys: [.isRegularFileKey],+ at: sessionsRootURL, includingPropertiesForKeys: [.isRegularFileKey],options: [.skipsHiddenFiles, .skipsPackageDescendants]- ) else {- return nil- }+ ) else { return nil }for case let url as URL in enumerator where url.lastPathComponent.hasSuffix(suffix) {- return url+ return initialCursor(for: url)}return nil}private func matchingFile(in directory: URL, suffix: String) -> URL? {- guard let urls = try? fileManager.contentsOfDirectory(- at: directory,- includingPropertiesForKeys: nil,- options: [.skipsHiddenFiles]- ) else {- return nil- }- return urls.first { $0.lastPathComponent.hasSuffix(suffix) }+ (try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]))?+ .first { $0.lastPathComponent.hasSuffix(suffix) }}private func sessionDirectory(for date: Date) -> URL {- // Codex 的 sessions 目录名是公历, 必须固定公历日历- let components = CodexDateFormat.localGregorianCalendar- .dateComponents([.year, .month, .day], from: date)- return sessionsRootURL- .appendingPathComponent(String(format: "%04d", components.year ?? 0), isDirectory: true)- .appendingPathComponent(String(format: "%02d", components.month ?? 0), isDirectory: true)- .appendingPathComponent(String(format: "%02d", components.day ?? 0), isDirectory: true)+ let components = CodexDateFormat.localGregorianCalendar.dateComponents([.year, .month, .day], from: date)+ return sessionsRootURL.appendingPathComponent(String(format: "%04d/%02d/%02d", components.year ?? 0, components.month ?? 0, components.day ?? 0))}private func initialCursor(for url: URL) -> SessionFileCursor {let stat = WorkflowStorage.fileStat(at: url)let size = stat?.size ?? 0let offset = size > Self.bootstrapByteLimit ? size - Self.bootstrapByteLimit : 0- return SessionFileCursor(- url: url,- fileIdentifier: stat?.identifier,- offset: offset,- discardsLeadingPartialLine: offset > 0,- lifecycleByTurnId: [:],- hasUnscannedHistoricalPrefix: offset > 0,- completedEffortBackfillTurnIds: [],- lastEffortBackfillAttemptByTurnId: [:]- )+ return SessionFileCursor(url: url, fileIdentifier: stat?.identifier, offset: offset, historicalOffset: offset, discardsLeadingPartialLine: offset > 0)}- private func backfilledEffort(- from url: URL,- turnId: String- ) -> EffortBackfillResult {- let size = WorkflowStorage.fileSize(at: url)- guard size > 0,- let handle = try? FileHandle(forReadingFrom: url) else {- return .unavailable- }- defer {- try? handle.close()- }-- let offset = size > Self.effortBackfillByteLimit- ? size - Self.effortBackfillByteLimit- : 0- guard (try? handle.seek(toOffset: offset)) != nil,- let data = try? handle.readToEnd(),- !data.isEmpty else {- return .unavailable- }-- let completeData = offset > 0- ? JSONLines.droppingLeadingPartialLine(data)- : data- for envelope in JSONLines.decode(- CodexRolloutLineEnvelope.self,- from: completeData- ).reversed() where envelope.type == "turn_context"- && envelope.payload?.turnId == turnId {- if let effort = envelope.payload?.normalizedEffort {- return .found(effort)- }- }- return .notFound+ private func backfillContext(into cursor: inout SessionFileCursor) -> CodexSessionReadStatus {+ let end = cursor.offset+ let start = end > UInt64(Self.contextByteLimit) ? end - UInt64(Self.contextByteLimit) : 0+ var restored = SessionFileCursor(+ url: cursor.url,+ fileIdentifier: cursor.fileIdentifier,+ offset: start,+ historicalOffset: start,+ discardsLeadingPartialLine: start > 0+ )+ let status = scan(into: &restored, limit: Self.contextByteLimit, through: end)+ guard status == .complete else { return status }+ restored.didBackfill = true+ cursor = restored+ return .complete}- // MARK: - 增量扫描-- private func scanNewLifecycleEvents(- into cursor: inout SessionFileCursor,- fallbackReference: CodexActivityTurnReference- ) {- let stat = WorkflowStorage.fileStat(at: cursor.url)- let size = stat?.size ?? 0- let identifier = stat?.identifier- if size < cursor.offset- || (cursor.fileIdentifier != nil && identifier != nil && cursor.fileIdentifier != identifier) {+ private func scan(into cursor: inout SessionFileCursor, limit: Int, through upperBound: UInt64? = nil) -> CodexSessionReadStatus {+ cursor.lastReadByteCount = 0+ guard let stat = WorkflowStorage.fileStat(at: cursor.url) else { return .unavailable }+ if stat.size < cursor.offset || (cursor.fileIdentifier != nil && cursor.fileIdentifier != stat.identifier) {cursor = initialCursor(for: cursor.url)}-- guard size > cursor.offset,- let handle = try? FileHandle(forReadingFrom: cursor.url) else {- return- }- defer {- try? handle.close()- }-+ let end = min(stat.size, upperBound ?? stat.size)+ guard let handle = try? FileHandle(forReadingFrom: cursor.url) else { return .unavailable }+ defer { try? handle.close() }+ guard end > cursor.offset else { return .complete }+ guard limit > 0 else { return .incomplete }guard (try? handle.seek(toOffset: cursor.offset)) != nil,- let data = try? handle.readToEnd(),- !data.isEmpty,- let lastNewlineIndex = data.lastIndex(of: JSONLines.newlineByte) else {- return- }-- let consumedCount = data.distance(from: data.startIndex, to: lastNewlineIndex) + 1- cursor.offset += UInt64(consumedCount)- cursor.fileIdentifier = identifier-- var completeData = Data(data[data.startIndex ... lastNewlineIndex])+ let data = try? handle.read(upToCount: min(limit, Int(end - cursor.offset))), !data.isEmpty else { return .unavailable }+ cursor.lastReadByteCount = data.count+ guard let newline = data.lastIndex(of: JSONLines.newlineByte) else { return .incomplete }+ let consumed = data.distance(from: data.startIndex, to: newline) + 1+ cursor.offset += UInt64(consumed)+ cursor.fileIdentifier = stat.identifier+ var complete = Data(data[...newline])if cursor.discardsLeadingPartialLine {- completeData = JSONLines.droppingLeadingPartialLine(completeData)+ complete = JSONLines.droppingLeadingPartialLine(complete)cursor.discardsLeadingPartialLine = false}-- guard !completeData.isEmpty else {- return- }-- for envelope in JSONLines.decode(CodexRolloutLineEnvelope.self, from: completeData) {- if let event = envelope.progressEvent(fallbackReference: fallbackReference) {- cursor.apply(event)+ for line in complete.split(separator: JSONLines.newlineByte) {+ let decoded = JSONLines.decodeWithFailures(CodexRolloutLineEnvelope.self, from: Data(line))+ if decoded.failedLineCount > 0 {+ cursor.markReadGap()}- if let event = envelope.lifecycleEvent {- cursor.apply(event)+ for envelope in decoded.values {+ cursor.apply(envelope)}}+ guard let after = WorkflowStorage.fileStat(at: cursor.url), after.identifier == stat.identifier,+ after.size >= end else { return .unavailable }+ return cursor.offset == end ? .complete : .incomplete}private static let bootstrapByteLimit: UInt64 = 512 * 1024- private static let effortBackfillByteLimit: UInt64 = 8 * 1024 * 1024- private static let effortBackfillMinimumTaskAge: TimeInterval = 2- private static let effortBackfillRetryInterval: TimeInterval = 10- private static let fileResolutionRetryInterval: TimeInterval = 10+ private static let incrementalByteLimit = 8 * 1024 * 1024+ private static let contextByteLimit = 8 * 1024 * 1024}private nonisolated struct SessionFileCursor {let url: URLvar fileIdentifier: UInt64?var offset: UInt64+ let historicalOffset: UInt64var discardsLeadingPartialLine: Bool- var lifecycleByTurnId: [String: SessionTurnLifecycle]- let hasUnscannedHistoricalPrefix: Bool- var completedEffortBackfillTurnIds: Set<String>- var lastEffortBackfillAttemptByTurnId: [String: Date]+ var currentTurnId: String?+ var lifecycleByTurnId: [String: SessionTurnLifecycle] = [:]+ var didBackfill = false+ var hasDecodeFailures = false+ var lastReadAt = Date()+ var lastReadByteCount = 0++ /// 损坏可能遮住 turn 边界, 只保留已明确结束的事实, 后续新 turn 独立建立覆盖+ mutating func markReadGap() {+ hasDecodeFailures = true+ currentTurnId = nil+ for turnId in lifecycleByTurnId.keys where lifecycleByTurnId[turnId]?.terminal == nil {+ lifecycleByTurnId[turnId]?.hasReadGap = true+ }+ }- mutating func apply(_ event: SessionLifecycleEvent) {- var lifecycle = lifecycleByTurnId[event.turnId] ?? SessionTurnLifecycle()- lifecycle.apply(event.change)- lifecycleByTurnId[event.turnId] = lifecycle+ mutating func apply(_ envelope: CodexRolloutLineEnvelope) {+ if envelope.startsTurnContext {+ currentTurnId = envelope.payload?.turnId.flatMap { $0.isEmpty ? nil : $0 }+ }+ if let event = envelope.progressEvent(currentTurnId: currentTurnId) {+ apply(event)+ }+ if let event = envelope.lifecycleEvent {+ apply(event)+ }+ if envelope.type == "turn_context", let turnId = currentTurnId {+ var state = lifecycleByTurnId[turnId] ?? SessionTurnLifecycle()+ state.hasContext = true+ lifecycleByTurnId[turnId] = state+ }+ if envelope.endsTurnContext, envelope.payload?.turnId == currentTurnId {+ currentTurnId = nil+ }}-}-private nonisolated enum EffortBackfillResult {- case found(String)- case notFound- case unavailable+ mutating func apply(_ event: SessionLifecycleEvent) {+ var state = lifecycleByTurnId[event.turnId] ?? SessionTurnLifecycle()+ state.apply(event.change)+ lifecycleByTurnId[event.turnId] = state+ }}// MARK: - rollout 行解码@@ -413,19 +279,28 @@ nonisolated struct CodexRolloutLinePayload: Decodable {}private nonisolated extension CodexRolloutLineEnvelope {- func progressEvent(- fallbackReference: CodexActivityTurnReference- ) -> SessionLifecycleEvent? {+ var startsTurnContext: Bool {+ type == "turn_context" || (type == "event_msg" && payload?.type == "task_started")+ }++ var endsTurnContext: Bool {+ type == "event_msg" && (payload?.type == "task_complete" || payload?.type == "turn_aborted")+ }++ func progressEvent(currentTurnId: String?) -> SessionLifecycleEvent? {+ let progressTypes: Set = ["token_count", "item_completed", "agent_message", "agent_reasoning", "task_started", "task_complete", "turn_aborted"]+ guard type == "response_item" || type == "token_usage_record"+ || (type == "event_msg" && payload?.type.map(progressTypes.contains) == true) else {+ return nil+ }let eventDate = timestamp.flatMap(CodexDateFormat.iso8601Date)?? payload?.completedAt.flatMap(Self.date)?? payload?.startedAt.flatMap(Self.date)- guard let eventDate,- eventDate >= fallbackReference.startedAt.addingTimeInterval(-1) else {+ guard let eventDate else {return nil}- let turnId = payload?.turnId ?? fallbackReference.turnId- guard !turnId.isEmpty else {+ guard let turnId = payload?.turnId ?? currentTurnId, !turnId.isEmpty else {return nil}return SessionLifecycleEvent(turnId: turnId, change: .progress(at: eventDate))@@ -447,7 +322,8 @@ private nonisolated extension CodexRolloutLineEnvelope {turnId: turnId,change: .context(approvalReviewer: payload.approvalReviewer,- effort: effort+ effort: effort,+ observedAt: timestamp.flatMap(CodexDateFormat.iso8601Date)))}@@ -496,12 +372,15 @@ private nonisolated struct SessionLifecycleEvent {private nonisolated enum SessionLifecycleChange {case progress(at: Date)case started(at: Date)- case context(approvalReviewer: CodexApprovalReviewer?, effort: String?)+ case context(approvalReviewer: CodexApprovalReviewer?, effort: String?, observedAt: Date?)case completed(at: Date, duration: TimeInterval?)case aborted(at: Date?)}private nonisolated struct SessionTurnLifecycle {+ var hasReadGap = false+ var contextObservedAt: Date?+ var hasContext = falsevar startedAt: Date?var approvalReviewer: CodexApprovalReviewer?var effort: String?@@ -518,7 +397,9 @@ private nonisolated struct SessionTurnLifecycle {} else {startedAt = at}- case let .context(reviewer, reasoningEffort):+ case let .context(reviewer, reasoningEffort, observedAt):+ hasContext = true+ contextObservedAt = observedAt ?? contextObservedAtapprovalReviewer = reviewer ?? approvalReviewereffort = reasoningEffort ?? effortcase let .completed(at, duration):@@ -537,6 +418,16 @@ nonisolated struct CodexSessionTaskLifecycleState {let effort: String?let lastProgressAt: Date?let terminal: CodexSessionTaskTerminalState?+ var readStatus: CodexSessionReadStatus = .complete+ var hasContext = false+ var contextObservedAt: Date?+}++nonisolated enum CodexSessionReadStatus {+ case complete+ case incomplete+ case unavailable+ case notFound}nonisolated enum CodexSessionTaskTerminalState {diff --git a/CodexBar/Services/Workflow/HookEventTailReader.swift b/CodexBar/Services/Workflow/HookEventTailReader.swiftindex 729b8a7..ec2cea6 100644--- a/CodexBar/Services/Workflow/HookEventTailReader.swift+++ b/CodexBar/Services/Workflow/HookEventTailReader.swift@@ -1,10 +1,10 @@+import Darwinimport Foundationnonisolated enum HookEventBatch {case bootstrapStartcase bootstrapEvents([WorkflowHookEvent])- /// degraded 表示放弃回放直接跳到文件末尾, 这一轮的活跃任务是空的而不是真的没有- /// attempts 由 reader 给出, 它才知道循环跑了几轮以及放弃时补发过一次清场+ /// degraded 表示历史覆盖不完整, 不得据此判断任务静默case bootstrapEnd(degraded: Bool, attempts: Int)case live([WorkflowHookEvent])case sourceHealthChanged(Bool)@@ -17,7 +17,7 @@ nonisolated enum HookEventDrainResult: Sendable {}/// 在独立 actor 中按完整 JSONL 行读取 HookEvents/events-/// bootstrap 覆盖滚动 24 小时并作为单次事务发送, live 随后按当日文件 offset 增量读取+/// bootstrap 覆盖滚动 24 小时并作为单次事务发送, live 随后按窗口内各日期文件 offset 增量读取actor HookEventTailReader {private let onBatch: @MainActor @Sendable (HookEventBatch) -> Voidprivate var pollTask: Task<Void, Never>?@@ -26,14 +26,21 @@ actor HookEventTailReader {// actor 会在 await 期间重入; 所有外部读取请求通过这两个标记合并为单一读取流程private var isProcessingReads = falseprivate var hasPendingDrain = false- private var activeDateKey = ""- private var activeFileOffset: UInt64 = 0- private var activeFileIdentifier: UInt64?+ private var fileCursors: [String: HookFileCursor] = [:]+ private let eventsDirectoryURL: URL+ private let now: @Sendable () -> Date+ private var bootstrapRetryAt: Date?private var lastReportedSourceHealth: Bool?private var requestedDrainGeneration: UInt64 = 0private var drainWaiters: [UInt64: CheckedContinuation<HookEventDrainResult, Never>] = [:]- init(onBatch: @escaping @MainActor @Sendable (HookEventBatch) -> Void) {+ init(+ eventsDirectoryURL: URL = WorkflowStorage.eventsDirectoryURL(),+ now: @escaping @Sendable () -> Date = Date.init,+ onBatch: @escaping @MainActor @Sendable (HookEventBatch) -> Void+ ) {+ self.eventsDirectoryURL = eventsDirectoryURL+ self.now = nowself.onBatch = onBatch}@@ -152,8 +159,8 @@ actor HookEventTailReader {drainWaiters.removeValue(forKey: generation)?.resume(returning: .cancelled)}- private var activeFileURL: URL {- WorkflowStorage.eventLogURL(for: activeDateKey)+ private func eventLogURL(for dateKey: String) -> URL {+ WorkflowStorage.eventLogURL(for: dateKey, in: eventsDirectoryURL)}// MARK: - bootstrap@@ -163,46 +170,50 @@ actor HookEventTailReader {guard isRunning, !Task.isCancelled else {return}- if let result = await bootstrapAttempt(now: Date()) {- activeDateKey = result.activeDateKey- activeFileOffset = result.activeFileOffset- activeFileIdentifier = result.activeFileIdentifier- await onBatch(.bootstrapEnd(degraded: false, attempts: attempt + 1))- await reportSourceHealth(true)+ if let result = await bootstrapAttempt(now: now()) {+ bootstrapRetryAt = nil+ fileCursors = result.cursors+ let healthy = result.cursors.values.allSatisfy { !$0.isDegraded }+ await onBatch(.bootstrapEnd(degraded: !healthy, attempts: attempt + 1))+ await reportSourceHealth(healthy)return}}// 连续读取失败时清空恢复态并跳过当前已有字节, 避免稍后误当 live 发送历史通知// 代价是丢掉最多 24 小时的任务状态, 所以要让下游知道这一轮是降级而不是真的没有历史- let dateKey = WorkflowStorage.dateKey(for: Date())- let stat = WorkflowStorage.fileStat(at: WorkflowStorage.eventLogURL(for: dateKey))- activeDateKey = dateKey- activeFileOffset = stat?.size ?? 0- activeFileIdentifier = stat?.identifier+ let current = now()+ bootstrapRetryAt = current.addingTimeInterval(Self.bootstrapRetryInterval)+ fileCursors = Dictionary(uniqueKeysWithValues: Self.dateKeys(+ from: current.addingTimeInterval(-Self.activityRetention), through: current+ ).map { dateKey in+ let stat = WorkflowStorage.fileStat(at: eventLogURL(for: dateKey))+ return (dateKey, HookFileCursor(offset: stat?.size ?? 0, identifier: stat?.identifier, isDegraded: true))+ })await onBatch(.bootstrapStart)await onBatch(.bootstrapEnd(degraded: true, attempts: Self.bootstrapAttemptLimit))await reportSourceHealth(false)}private func bootstrapAttempt(now: Date) async -> BootstrapResult? {+ guard (try? FileManager.default.contentsOfDirectory(atPath: eventsDirectoryURL.path)) != nil else { return nil }let cutoff = now.addingTimeInterval(-Self.activityRetention)let dateKeys = Self.dateKeys(from: cutoff, through: now)let bootstrapDateKey = WorkflowStorage.dateKey(for: now)- let boundaries = dateKeys.map { dateKey in- let url = WorkflowStorage.eventLogURL(for: dateKey)- let stat = WorkflowStorage.fileStat(at: url)+ guard let boundaries = try? dateKeys.map({ dateKey in+ let url = eventLogURL(for: dateKey)+ let stat = try readableStat(at: url)return HookFileBoundary(dateKey: dateKey,url: url,size: stat?.size ?? 0,fileIdentifier: stat?.identifier)- }+ }) else { return nil }await onBatch(.bootstrapStart)- var activeCompleteOffset: UInt64 = 0+ var cursors: [String: HookFileCursor] = [:]for boundary in boundaries {guard isRunning, !Task.isCancelled else {return nil@@ -218,22 +229,19 @@ actor HookEventTailReader {guard streamResult.didReachUpperBound else {return nil}- if boundary.dateKey == bootstrapDateKey {- activeCompleteOffset = streamResult.completeOffset- }+ cursors[boundary.dateKey] = HookFileCursor(+ offset: streamResult.completeOffset,+ identifier: boundary.fileIdentifier,+ isDegraded: streamResult.hasDecodeFailures+ )}guard boundariesAreStable(boundaries, activeDateKey: bootstrapDateKey),- WorkflowStorage.dateKey(for: Date()) == bootstrapDateKey else {+ WorkflowStorage.dateKey(for: self.now()) == bootstrapDateKey else {return nil}- let activeBoundary = boundaries.first { $0.dateKey == bootstrapDateKey }- return BootstrapResult(- activeDateKey: bootstrapDateKey,- activeFileOffset: activeCompleteOffset,- activeFileIdentifier: activeBoundary?.fileIdentifier- )+ return BootstrapResult(cursors: cursors)}// MARK: - 增量 tail@@ -243,65 +251,62 @@ actor HookEventTailReader {return .cancelled}- let todayKey = WorkflowStorage.dateKey(for: Date())- if todayKey != activeDateKey {- // 跨零点先读完旧文件尾部, 再切到新日期文件- guard await readAppendedLines() else {- // bootstrap 已经完成切日; 临时失败则保留旧日期, 下一轮继续重试- return currentDrainResult()+ guard (try? FileManager.default.contentsOfDirectory(atPath: eventsDirectoryURL.path)) != nil else {+ await reportSourceHealth(false)+ return .sourceUnavailable+ }+ let current = now()+ if let bootstrapRetryAt {+ guard current >= bootstrapRetryAt else { return .sourceUnavailable }+ await bootstrapRecentActivity()+ guard isRunning, !Task.isCancelled else { return .cancelled }+ return lastReportedSourceHealth == true ? .completed : .sourceUnavailable+ }+ let dates = Self.dateKeys(from: current.addingTimeInterval(-Self.activityRetention), through: current)+ fileCursors = fileCursors.filter { dates.contains($0.key) }+ var healthy = true+ for dateKey in dates {+ let url = eventLogURL(for: dateKey)+ let stat: WorkflowFileStat?+ do {+ stat = try readableStat(at: url)+ } catch {+ await reportSourceHealth(false)+ return .sourceUnavailable}- guard isRunning, !Task.isCancelled else {- return .cancelled+ var cursor = fileCursors[dateKey] ?? HookFileCursor()+ if (cursor.identifier != nil && stat?.identifier != cursor.identifier)+ || (stat?.size ?? 0) < cursor.offset {+ await bootstrapRecentActivity()+ return lastReportedSourceHealth == true ? .completed : .sourceUnavailable}- activeDateKey = todayKey- activeFileOffset = 0- activeFileIdentifier = nil- }-- _ = await readAppendedLines()- guard isRunning, !Task.isCancelled else {- return .cancelled- }- return currentDrainResult()- }-- private func currentDrainResult() -> HookEventDrainResult {- lastReportedSourceHealth == true ? .completed : .sourceUnavailable+ let size = stat?.size ?? 0+ let result = await streamEvents(+ at: url, from: cursor.offset, through: size,+ cutoff: current.addingTimeInterval(-Self.activityRetention), makeBatch: HookEventBatch.live+ )+ guard isRunning, !Task.isCancelled else { return .cancelled }+ cursor.offset = result.completeOffset+ cursor.identifier = stat?.identifier+ cursor.isDegraded = cursor.isDegraded || result.hasDecodeFailures+ fileCursors[dateKey] = cursor+ healthy = healthy && result.didReachUpperBound && !cursor.isDegraded+ }+ await reportSourceHealth(healthy)+ return healthy ? .completed : .sourceUnavailable}- /// 返回是否读到当前文件上界; 触发重新 bootstrap 或读取中断时为 false- private func readAppendedLines() async -> Bool {- let url = activeFileURL- let stat = WorkflowStorage.fileStat(at: url)- if activeFileIdentifier != nil, stat?.identifier != activeFileIdentifier {- await bootstrapRecentActivity()- return false- }- if activeFileIdentifier == nil {- activeFileIdentifier = stat?.identifier- }-- let size = stat?.size ?? 0- if size < activeFileOffset {- await bootstrapRecentActivity()- return false- }-- guard size > activeFileOffset else {- await reportSourceHealth(true)- return true+ private func readableStat(at url: URL) throws -> WorkflowFileStat? {+ guard let stat = WorkflowStorage.fileStat(at: url) else {+ let code = errno+ if code == ENOENT {+ return nil+ }+ throw POSIXError(POSIXErrorCode(rawValue: code) ?? .EIO)}-- let streamResult = await streamEvents(- at: url,- from: activeFileOffset,- through: size,- cutoff: nil,- makeBatch: HookEventBatch.live- )- activeFileOffset = streamResult.completeOffset- await reportSourceHealth(streamResult.didReachUpperBound)- return streamResult.didReachUpperBound+ let handle = try FileHandle(forReadingFrom: url)+ try handle.close()+ return stat}private func reportSourceHealth(_ isHealthy: Bool) async {@@ -337,10 +342,11 @@ actor HookEventTailReader {var readOffset = startOffsetvar completeOffset = startOffsetvar pending = Data()+ var hasDecodeFailures = falsewhile readOffset < upperBound {guard isRunning, !Task.isCancelled else {- return .interrupted(at: completeOffset)+ return HookEventStreamResult(completeOffset: completeOffset, didReachUpperBound: false, hasDecodeFailures: hasDecodeFailures)}let requestedCount = Int(min(@@ -349,7 +355,7 @@ actor HookEventTailReader {))guard let chunk = try? handle.read(upToCount: requestedCount),!chunk.isEmpty else {- return .interrupted(at: completeOffset)+ return HookEventStreamResult(completeOffset: completeOffset, didReachUpperBound: false, hasDecodeFailures: hasDecodeFailures)}readOffset += UInt64(chunk.count)@@ -367,7 +373,12 @@ actor HookEventTailReader {: Data()completeOffset = readOffset - UInt64(pending.count)- var events = JSONLines.decode(WorkflowHookEvent.self, from: completeData)+ let decoded = JSONLines.decodeWithFailures(WorkflowHookEvent.self, from: completeData)+ if decoded.failedLineCount > 0 {+ hasDecodeFailures = true+ await reportSourceHealth(false)+ }+ var events = decoded.valuesif let cutoff {events.removeAll { $0.timestamp < cutoff }}@@ -377,14 +388,18 @@ actor HookEventTailReader {await Task.yield()}- return .completed(at: completeOffset)+ return HookEventStreamResult(+ completeOffset: completeOffset,+ didReachUpperBound: completeOffset == upperBound,+ hasDecodeFailures: hasDecodeFailures+ )}/// 从 24 小时窗口之前的事件文件中定向查找 Prompt 起点, 供 bootstrap 后回填恢复任务的开始时间func findPromptStartTimes(for references: [CodexActivityPromptReference]) -> [CodexActivityPromptReference: Date] {- let cutoff = Date().addingTimeInterval(-Self.activityRetention)+ let cutoff = now().addingTimeInterval(-Self.activityRetention)var unresolvedKeys = Set(references)var startTimes: [CodexActivityPromptReference: Date] = [:]var remainingBytes = Self.promptSearchByteLimit@@ -433,10 +448,10 @@ actor HookEventTailReader {private func eventLogURLs(onOrBefore cutoff: Date) -> [URL] {let cutoffDateKey = WorkflowStorage.dateKey(for: cutoff)- return WorkflowStorage.eventLogDateKeys()+ return WorkflowStorage.eventLogDateKeys(in: eventsDirectoryURL).filter { $0 <= cutoffDateKey }.sorted(by: >)- .map { WorkflowStorage.eventLogURL(for: $0) }+ .map { eventLogURL(for: $0) }}private func boundariesAreStable(@@ -483,6 +498,7 @@ actor HookEventTailReader {private static let readChunkByteCount = 512 * 1024private static let promptSearchByteLimit: UInt64 = 8 * 1024 * 1024private static let bootstrapAttemptLimit = 3+ private static let bootstrapRetryInterval: TimeInterval = 10}private nonisolated struct HookFileBoundary {@@ -492,15 +508,20 @@ private nonisolated struct HookFileBoundary {let fileIdentifier: UInt64?}+private nonisolated struct HookFileCursor {+ var offset: UInt64 = 0+ var identifier: UInt64?+ var isDegraded = false+}+private nonisolated struct BootstrapResult {- let activeDateKey: String- let activeFileOffset: UInt64- let activeFileIdentifier: UInt64?+ let cursors: [String: HookFileCursor]}private nonisolated struct HookEventStreamResult {let completeOffset: UInt64let didReachUpperBound: Bool+ var hasDecodeFailures = falsestatic func completed(at offset: UInt64) -> Self {Self(completeOffset: offset, didReachUpperBound: true)diff --git a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swiftindex cfd1408..cbd0f47 100644--- a/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift+++ b/CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift@@ -337,7 +337,7 @@ private nonisolated enum WorkflowTurnContextReader {let offset = size > searchByteLimit ? size - searchByteLimit : 0guard (try? handle.seek(toOffset: offset)) != nil,- let data = try? handle.readToEnd(),+ let data = try? handle.read(upToCount: Int(size - offset)),!data.isEmpty else {return nil}@@ -359,7 +359,7 @@ private nonisolated enum WorkflowTurnContextReader {return nil}- private static let searchByteLimit: UInt64 = 512 * 1024+ private static let searchByteLimit: UInt64 = 8 * 1024 * 1024}private nonisolated struct WorkflowTurnContext {diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex e3a06ab..32b1d5e 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 4.0.0-CURRENT_PROJECT_VERSION = 100+MARKETING_VERSION = 4.0.1+CURRENT_PROJECT_VERSION = 101diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.mdindex bfe3751..f3c4893 100644--- a/Docs/DeveloperGuide/activity-monitor.md+++ b/Docs/DeveloperGuide/activity-monitor.md@@ -14,11 +14,21 @@Hook 事件提供实时进展和中断信号,rollout 文件补充生命周期信息。[`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) 合并两者并发布唯一任务快照:```text-Hook JSONL -> HookEventTailReader ---------+- +-> CodexActivityMonitor -> CodexActivitySnapshot-rollout JSONL -> CodexSessionLifecycleReader++Codex Hook -> WorkflowHookEventRecorder -> Hook JSONL+ |-> WorkflowService -> 历史日聚合+ |-> HookEventTailReader -----++ |-> CodexActivityMonitor+rollout JSONL -> CodexSessionLifecycleReader ----------------------------+ |+ v+ CodexActivitySnapshot+ |-> 活动卡片和任务中心+ |-> 流光和防睡眠```+`WorkflowHookEventRecorder` 从 `stdin` 提取最小字段,按需有界回查 rollout 元数据,加锁追加事件后退出。历史聚合和实时任务分别读取同一份 Hook JSONL;app-server 额度与用量走独立链路。采集与聚合细节见 [Hook 采集与历史聚合](hook-and-aggregation.md)++通知和触觉反馈消费 monitor 发布的实时转场。流光消费快照与终态展示事件:等待用户批准为橙色,运行中为青色,完成为绿色,终止为红色。存在等待任务时,活跃状态优先显示橙色;短暂终态提示可以覆盖活跃状态。+### 两种来源的分工| 信息 | 优先来源 | 补充来源 |@@ -28,7 +38,7 @@ rollout JSONL -> CodexSessionLifecycleReader+| turn 起点 | `UserPromptSubmit` | rollout startedAt 或历史回查 || 完成候选 | `Stop` | rollout terminal || 明确的 turn 中断 | `Interrupt` | rollout terminal |-| 其他终态确认 | rollout terminal | grace 到期 fallback |+| 其他终态确认 | rollout terminal | 无明确终态时保留待确认任务,到期清理 || effort | Hook recorder 回查 | rollout lifecycle backfill |各字段按上表中的来源解析。Hook 每轮读取后等待 2 秒,rollout 每轮对账后等待 1 秒。@@ -39,8 +49,8 @@ snapshot 可以在 View 重建、新消费者订阅或设置变化时反复读例如 App 启动时 bootstrap 恢复出一个已经等待批准的任务:-- snapshot 应显示它正在等待-- transition 不应发布等待事件+- snapshot 显示它正在等待+- transition 不发布等待事件- 通知服务因此不会补发一条历史通知任务完成也一样。通知服务消费 `.completed` transition,不扫描 `recentCompletions`,避免 App 重启或 UI 刷新重复提醒。@@ -53,16 +63,16 @@ snapshot 可以在 View 重建、新消费者订阅或设置变化时反复读首次启动读取最近 24 小时文件以建立任务基线:-- 每块最多读取 512 KB+- 每块最多读取 512 KiB- 最多尝试 3 次获得稳定文件边界- 使用 inode 和 size 判断读取期间是否发生替换或追加- bootstrap 结果不会触发历史完成或等待通知-如果无法得到稳定边界,reader 会跳到当前文件末尾并发布显式不健康状态。这样不会把不完整历史误解释为真实任务变化。+无法得到稳定边界时,reader 清空恢复态,跳到各日期文件末尾,并发布不健康状态。### bootstrap 是一个逻辑事务-24 小时窗口可能跨两个自然日文件,单个文件又会分成多个 512 KB batch 发送。+24 小时窗口可能跨两个自然日文件,单个文件又会分成多个 512 KiB batch 发送。monitor 在 `.bootstrapStart` 时先清空上一次恢复态并暂停副作用,接收所有 `.bootstrapEvents`,最后在 `.bootstrapEnd` 才统一:@@ -72,7 +82,7 @@ monitor 在 `.bootstrapStart` 时先清空上一次恢复态并暂停副作用- 定向回查缺失 prompt 起点- 发布完整 snapshot-中间 batch 不应让 UI 或通知看到半恢复状态。+中间 batch 只更新内部任务状态。rollout 补齐和异常保护对账要求数据源健康,且系统未处于睡眠。### 稳定边界重试@@ -84,17 +94,21 @@ reader 在每次尝试开始时固定所有日期文件的 inode 和 size,读任何条件不成立都从新的基线重试。连续 3 次失败后跳到当前文件末尾,并发布 degraded health,暂停异常会话保护判断。+bootstrap 因目录暂时不存在、不可读或边界不稳定而失败后,reader 最多每 10 秒重新尝试一次。目录恢复后的已有事件通过 bootstrap 静默重放,成功后才恢复正常增量读取。完整坏行导致的历史覆盖缺口不会因普通读取成功而消失,也不会触发无限历史重读。+### 完整行游标Hook recorder 可能正在写最后一行。reader 只把最后一个 newline 之前的字节计入 `completeOffset`-半行不会丢弃,也不会被当作损坏事件。下一轮从旧 offset 重新读取,等行完整后再提交。+半行不会丢弃,也不会被当作损坏事件。下一轮从旧 offset 重新读取,等行完整后再提交。未读完固定上界时,屏障返回 `sourceUnavailable`。完整坏行会使对应日期游标降级,不能因跳过坏行而报告健康;该日期退出读取窗口或文件替换重放后重新确定健康状态。++Hook 数据源降级期间仍会为已知任务读取 rollout,但只接受本轮完整读取、身份匹配的明确完成或中断记录,并静默结束对应任务。该路径不应用普通进展、不回填审批状态、不恢复隐藏任务,也不恢复异常会话保护。系统睡眠和 bootstrap 期间暂停该路径;任务取消或 reader 代次变化后丢弃读取结果。完整生命周期恢复仍要求 Hook 读取屏障成功。### 跨日与文件替换-正常跨日时先排空旧日期文件,再切换到新日期文件。inode 改变或文件缩小时重新 bootstrap,不沿用旧游标。+reader 为滚动 24 小时覆盖的每个自然日保留独立游标,每轮读取窗口内的全部日期。跨多日恢复会补读中间日期,切日后仍读取前一日的迟到追加。inode 改变或文件缩小时重新 bootstrap,不沿用旧游标。-当 `UserPromptSubmit` 早于当前增量窗口时,reader 可以向前回查最多 8 MB,为现存任务补齐 prompt 起点。+当 `UserPromptSubmit` 早于当前增量窗口时,reader 可以向前回查最多 8 MiB,为现存任务补齐 prompt 起点。### drainNow 读取屏障@@ -127,14 +141,14 @@ actor 在 `await` 期间可以重入,因此 `isProcessingReads` 和 `hasPendin读取规则如下:- 默认每 1 秒检查一次-- 初始尾部窗口为 512 KB-- effort 等 turn context 字段最多回查 8 MB+- 初始尾部窗口为 512 KiB+- effort 等 turn context 字段最多回查 8 MiB- 只解析生命周期、turn, progress, effort 和 reviewer-- 不读取或保存对话内容用于产品展示+- 对话内容不进入活动模型或产品展示-Hook 的 `Stop` 将任务标记为“正在收尾”,保留在活动列表。后续工具、审批等进展继续更新同一任务,rollout 确认 `task_complete` 后才记录完成并发布完成转场。+Hook 的 `Stop` 将任务标记为“正在收尾”,保留在活动列表。后续工具、审批等进展继续更新同一任务;rollout 的 `task_complete` 确认完成,满足转场时效和恢复条件时发布完成转场。-rollout 暂时不可读或无法关联 session、turn 时,任务继续等待对账。`Stop` 不启动终态超时;新 turn 或 `SessionEnd` 将旧任务移出活动列表,开启 5 秒终态确认窗口。迟到的 `Stop` 只更新待确认任务的元数据与进展,不恢复展示或重置窗口。+rollout 暂时不可读或无法关联 session、turn 时,任务继续等待对账。`Stop` 不启动终态超时;新 turn 或 `SessionEnd` 将旧任务移出活动列表,开始前 5 秒的快速终态查询,之后每 30 秒继续查询。迟到的 `Stop` 只更新待确认任务的元数据与进展,不恢复展示或重置窗口。### 明确中断@@ -150,7 +164,7 @@ reader 先检查最可能的少量目录:2. 当前日期目录3. `archived_sessions`-resume 可能继续很早以前创建的 session。快速路径找不到时,每个活跃 session 生命周期最多执行一次递归兜底,避免每秒 poll 都扫描整个 sessions 树。+resume 可能继续很早以前创建的 session。快速路径找不到时,快速路径每 10 秒允许重试,递归兜底每 60 秒允许重试,避免每秒 poll 都扫描整个 sessions 树,同时允许发现迟到或移动的文件。文件被移到 archive 后,已缓存 URL 不存在会清除 cursor 并允许重新完整定位。@@ -158,15 +172,32 @@ resume 可能继续很早以前创建的 session。快速路径找不到时,实时任务只需要活跃 turn 附近的 lifecycle,全量读取一个长期 session 会增加常驻 I/O。-初始 cursor 从最后 512 KB 开始并丢弃第一条可能不完整的行。如果 effort 仍缺失,对具体 turn 再定向回查最多 8 MB。+初始 cursor 从最后 512 KiB 开始并丢弃第一条可能不完整的行。缺少上下文、effort 或 reviewer 时,最多向前重放 8 MiB,统一恢复 turn 归属、元数据和进展。每个文件游标成功补读一次后停止回查,每轮最多补读一个 session。++每轮增量扫描总预算为 8 MiB,多个 session 轮转共享预算;待确认任务每轮最多查询 16 个。超过预算或尚未读到完整行时返回 `incomplete`,读取失败返回 `unavailable`,未找到文件返回 `notFound`。缓存可以保留已经观察到的事实,但不能替代本轮读取成功。成功读到固定上界且恢复了 turn 上下文时,`lifecycleCoverageCheckedAt` 记录本次检查时间;读取未完成、失败、文件不存在或缺少上下文时将其清空。只有该时间存在且距当前不足 5 秒的任务,才可以参与异常静默判定。++增量扫描按完整行推进 offset。遇到超过 8 MiB 的单行时,每轮在该行起点返回 `incomplete`,后续记录无法被消费。++rollout 坏行将当时尚未结束的 turn 标记为有覆盖缺口,后续重复的同一 turn 上下文不能清除此标记。新的 turn 独立建立覆盖,身份明确的完成或中断记录可以结束有缺口的任务;后续坏行不会撤销已经读到的明确终态。读取失败或尚未读完时,缓存进展不推进任务的执行时间,也不能恢复隐藏任务或清除保护记录。++### 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` 为 `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`。-effort backfill 只针对至少运行 2 秒,尚未 terminal 且仍缺 effort 的任务,同一 turn 重试间隔 10 秒。这避免刚创建任务时立刻做大范围回查。+记录须有可用时间和 turn 归属,本轮读取完整且时间晚于任务的 `lastProgressAt` 时才更新进展。`token_usage_record` 按活动记录处理,不比较 token 数量是否增加。缺少显式 turn 和游标上下文的记录不计入任务进展。### Rollout 解析字段共享的 `CodexRolloutLineEnvelope` 只提取 turn context, lifecycle 和 progress 所需字段。prompt, response 和 tool 内容不会进入活动模型。-这既收紧隐私边界,也降低大 rollout 的解码成本。新增实时字段时应先扩展这份最小 envelope,不应把完整 transcript 解码成通用 JSON 树。+终态要求 `payload.turn_id` 非空,并且本轮读取状态为 `complete`。外层 `type = "event_msg"` 时,`payload.type = "task_complete"` 配合有效的 `payload.completed_at` 确认完成;`payload.type = "turn_aborted"` 确认中断。完成时间使用 Unix 秒,`payload.duration_ms` 换算为秒后用于耗时展示;中断时间缺失时,活动任务使用对账时间,待确认任务使用移出活动列表的时间,结果均不早于任务最后活动时间。## 任务身份@@ -176,7 +207,7 @@ effort backfill 只针对至少运行 2 秒,尚未 terminal 且仍缺 effort2. `session ID`3. 匿名 project key-新的 prompt 会替代同一 session 的旧 turn。旧 turn 进入最长 5 秒 terminal grace,给迟到的结束事件留出对账时间。+新的 prompt 会替代同一 session 的旧 turn。旧 turn 在后台等待明确终态,前 5 秒快速查询,之后每 30 秒补查,最长保留到移出活动列表后的 24 小时。subagent 事件更新父任务的 subagent 活动,不创建独立顶层任务卡片。@@ -184,7 +215,9 @@ subagent 事件更新父任务的 subagent 活动,不创建独立顶层任务`session ID + turn ID` 能精确区分同一 session 中顺序执行的 turn,是首选身份。-某些事件只有 session ID。此时 session key 允许事件仍然参与状态,但终态匹配必须更保守。如果同一 session 同时存在多个候选,monitor 返回 ambiguous 而不是猜一个任务结束。+某些事件只有 session ID。后续顶层 Hook 匹配到该任务并提供 turn ID 时,任务在内存中补充 `associatedTurnId` 和终态别名,用于 rollout 查询与去重;初始 key 和保护哈希保持不变。++终态匹配先检查精确 key 及别名,再按 session 检查待确认任务。待确认候选唯一时使用该任务,多个时返回 `ambiguous`;没有待确认候选时再检查活动任务。候选须满足 Hook 时间顺序及 turn 身份条件。完全没有 session ID 时只能使用 project key。这个 key 可能把同项目并发匿名任务合并,所以匿名任务只承担可撤销的 UI 展示,不驱动通知、防睡眠或持久化保护。@@ -205,29 +238,35 @@ monitor 按精确的 `session ID + turn ID` 在内存中保存来源,保留 24这些规则同时用于 bootstrap 和实时读取。其他 subagent(包括 Memories)归类为 `auxiliary`,按辅助任务规则关联。历史聚合仍消费全部原始事件,来源记忆不持久化或上传。-### 新 prompt 与终态宽限--同一 session 的 turn 顺序执行。新 prompt 到来时旧 turn 必须立即离开活跃列表,否则 UI 会短暂显示两个顶层任务。--但新 prompt 可能早于旧 turn 的 rollout terminal 到达。直接记录中断会误判一个正常完成的任务。+### 新 prompt 与终态确认-因此旧 turn 被移到 `pendingTerminalTasks`+新 prompt 到来时,同一 session 的旧 turn 移到 `pendingTerminalTasks`,等待 rollout 确认结果:- 从 active snapshot 立即移除- 保留原任务元数据和开始时间-- 等待最多 5 秒 rollout terminal+- 前 5 秒快速查询 rollout terminal,随后每 30 秒补查- terminal 到达时准确分类 completed 或 aborted-- grace 到期仍无终态时按保守 fallback 收口+- 24 小时后仍无终态则清理,不生成完成、终止、通知或流光提示`SessionEnd` 使用同一个终态确认窗口,只是按 session 一次移动所有不晚于该事件的任务。### 迟到事件如何被拒绝-任务保存 `lastActivityAt`,完成和终止共用内存中的 `recentlyEndedTaskAt` 记录结束时间。展示记录仍分别保存在完成和终止列表,保留 10 分钟;去重记忆保留 24 小时,不随展示记录一起删除。来源过滤移除记录时,从剩余终态记忆重新计算对应 session 别名的最新时间。+任务保存 `lastHookEventAt` 和 `lastProgressAt`,`lastActivityAt` 直接读取 `lastProgressAt` 的值:++| 字段 | 来源与用途 |+| --- | --- |+| `lastHookEventAt` | 已接受的最新 Hook 时间,用于拒绝迟到的 Hook 状态变化 |+| `lastProgressAt` | Hook 与 rollout 的最新进展时间,用于异常会话保护 |+| `lastActivityAt` | 由 `lastProgressAt` 派生,用于展示排序、保留期和终态时间校正 |++rollout 进展不会推进 `lastHookEventAt`。较晚的 rollout 记录先被读取时,仍可接受时间稍早但有效的 `PermissionRequest`、工具、压缩、中断或新 prompt 事件。接受这些 Hook 时,`lastProgressAt` 和 `lastActivityAt` 保持单调递增。++完成和终止共用内存中的 `recentlyEndedTaskAt` 记录结束时间。展示记录仍分别保存在完成和终止列表,保留 10 分钟;去重记忆保留 24 小时,不随展示记录一起删除。来源过滤移除记录时,从剩余终态记忆重新计算对应 session 别名的最新时间。迟到事件按以下规则处理:-- 早于当前任务最后活动的事件不覆盖新状态+- Hook 状态变化和审批请求统一按 `lastHookEventAt` 排序;早于最新 Hook 进展的审批请求不恢复等待- 精确 turn 在终态记忆保留期间不允许重新创建;session 和匿名键只允许时间更新的新 prompt 复用- `Stop` 命中多个候选时不猜测- 已进入 terminal 去重记忆的 key 会清除异常顺序留下的恢复任务@@ -261,7 +300,7 @@ monitor 按精确的 `session ID + turn ID` 在内存中保存来源,保留 24- `Stop` 将任务标记为正在收尾,继续保留在活动列表- `Interrupt` 将匹配的 turn 记录为终止- rollout terminal 确认完成或终止-- 新 turn 或 `SessionEnd` 将旧任务移入 5 秒终态确认窗口,到期仍无终态时记录终止;已隐藏任务只记录去重状态+- 新 turn 或 `SessionEnd` 将旧任务移出活动列表并后台补查;没有明确终态就保持未确认,到期只清理### 事件到状态的主要转换@@ -271,20 +310,23 @@ monitor 按精确的 `session ID + turn ID` 在内存中保存来源,保留 24| 不存在 | 顶层 tool 或 compact | running | 恢复任务,startedAt 暂缺 || running | tool, compact, subagent progress | running | 更新 last progress 和 generation || running | `PermissionRequest` + reviewer user | waitingApproval | 发布 live waiting transition |-| waitingApproval | 新进展 | running | 清除 pending approval 和保护记录 |+| waitingApproval | tool、compact 或 subagent Hook 进展 | running | 清除待审批候选,更新活动和进展 || running 或 waiting | `Stop` | running | 显示正在收尾,保留任务直到 rollout 确认终态 |-| active | 新 prompt 或 `SessionEnd` | pending terminal | 从快照移除并开启 5 秒 grace |+| active | 新 prompt 或 `SessionEnd` | pending terminal | 从快照移除并开始后台终态查询 || active、suppressed 或 pending terminal | `Interrupt` | terminated | 移除匹配任务、记录终止并清理保护状态和通知 |-| running | 静默超过阈值 | suppressed | 隐藏并退出防睡眠贡献 |-| suppressed | 新进展 | running | 清除持久化保护与旧通知 |+| running | 满足保护条件且静默达到阈值 | suppressed | 隐藏并退出防睡眠贡献 |+| suppressed | 有效的工具、压缩、子任务或 `Stop` Hook,或健康对账读到新进展 | running | 清除持久化保护与旧通知 |+| active、suppressed 或 pending terminal | 完整读取的匹配 rollout terminal | completed 或 terminated | 记录明确终态并清理任务,降级期间静默处理 |### 等待批准的两阶段确认-`PermissionRequest` 的 reviewer 接受 `user`、`auto_review` 和 `guardian_subagent`。+任务的 `approvalReviewer` 来自 Hook 记录或 rollout 的 `payload.approvals_reviewer`,取值为 `user`、`auto_review` 或 `guardian_subagent`++收到 `PermissionRequest` 时,任务已有 reviewer 为 `user` 就立即进入等待。任务 reviewer 未知时保存 `pendingApprovalRequestedAt`,由 rollout 补齐后决定状态。自动审批路由保持当前状态,并在对账时清除候选。-Hook event 到达时如果已经带有 reviewer,task 可以立即确认。reviewer 缺失时先保存 `pendingApprovalRequestedAt`,rollout poll 补齐后再决定是否进入 `waitingApproval`+有效的工具、压缩、子 Agent 或顶层 `Stop` Hook 将任务恢复为运行中,并清除待审批候选;随后补齐 reviewer 不会重新打开已清除的等待。rollout 进展只更新时间,不单独解除审批等待。-只有 reviewer 明确为 user 才发布 waiting transition。不确定时维持 running 比误报用户正在被等待更符合事实。+审批等待按任务维护。同一任务内其他并行工具或子 Agent 的有效 Hook 进展也会解除等待。### Effort 合并@@ -294,9 +336,9 @@ Hook event 到达时如果已经带有 reviewer,task 可以立即确认。revisubagent 的 turn ID 属于 subagent 自己,父任务只能通过共享 session 关联。-只有同 session 恰好有一个 active 父任务、没有 pending terminal 歧义,并且 start/stop 带稳定 agent ID 时,active subagent count 才可靠。+子任务 Hook 关联同 session 唯一的活动父任务。存在待确认旧任务时,`SubagentStart` 可以关联;其他子任务事件要求其 `agent_id` 已记录在当前父任务中。父任务不唯一时忽略事件。-缺少 ID、先看到 stop 或同 session 有多个候选时,monitor 将可靠性降为 false,UI 不展示伪精确数字。+计数可靠性由是否已知 prompt 起点初始化。缺少 `agent_id`,或首次观察某个 agent 就收到 stop 时,可靠性设为 `false`,UI 隐藏数量。每个 agent 按自己的事件时间更新运行状态。## 快照优先级@@ -327,7 +369,9 @@ monitor 每秒检查 rollout,并在清理 deadline 到达时刷新。`presentationPublisher` 发布当前快照和本轮仍有效的 `terminalEvents`,供任务流光使用。展示事件包含匿名任务;通知使用独立的 `transitionPublisher`-历史重读、睡眠恢复和数据源健康状态变化时清空待发布事件,并更新 `terminalPresentationNotBefore`。bootstrap、唤醒对账和数据源不健康期间暂停收集;结束时间早于恢复界限的记录不产生短提示,恢复后结束的任务正常发布。+完成转场和终态短提示要求结束时间距当前不超过 10 秒,并且不早于各自的恢复界限。直接由 Hook 确认的等待转场也检查 10 秒时效;rollout 补齐 reviewer 后确认的等待转场只检查请求时间不早于 `sessionTransitionNotBefore`。++历史重读、睡眠恢复和数据源健康状态变化时清空待发布事件,并更新 `terminalPresentationNotBefore`。bootstrap、恢复对账和数据源不健康期间暂停发布。### 稳定排序@@ -337,13 +381,13 @@ monitor 每秒检查 rollout,并在清理 deadline 到达时刷新。### 清理采用最近 deadline-monitor 管理 terminal grace、活动保留、历史保留、terminal 去重和保护记录过期。菜单栏终态提示和任务流光分别由 `StatusItemController`、`TaskGlowController` 管理到期时间。提示到期不重新发布活动快照。+monitor 管理待确认任务、活动任务、历史记录、终态去重和保护记录的过期时间。菜单栏终态提示和任务流光分别由 `StatusItemController`、`TaskGlowController` 管理到期时间。提示到期不重新发布活动快照。清理任务只等待最近的未来 deadline,到点处理后安排下一次。## 系统睡眠与唤醒-系统即将睡眠时暂停异常会话保护判断。唤醒后执行严格恢复顺序:+系统即将睡眠时暂停异常会话保护判断。唤醒后的完整恢复顺序为:1. 进入恢复状态并继续暂停保护2. 等待 `HookEventTailReader.drainNow()` 成功@@ -351,7 +395,7 @@ monitor 管理 terminal grace、活动保留、历史保留、terminal 去重和4. 使用新 Hook 结果和 rollout 结果统一对账5. 恢复异常会话保护判断-如果新一轮读取失败、reader 被更换或数据源不可用,不得使用睡眠前快照继续判断任务静默。+Hook 屏障返回 `sourceUnavailable` 时,仅为已知任务对账明确终态,保持静默并继续暂停保护,后续轮询重试完整恢复。reader 被更换或任务取消时丢弃该轮结果。### 系统睡眠期间暂停判定@@ -359,11 +403,11 @@ monitor 管理 terminal grace、活动保留、历史保留、terminal 去重和检查任务使用 `SuspendingClock` 等待,但静默时长仍按 `Date` 与 `lastProgressAt` 的差值计算,不扣除系统睡眠经过的时间。will-sleep 进入 recovery,did-wake 通过新的数据读取屏障后重新判定。-### 唤醒顺序为何不能交换+### 唤醒恢复的关联与代次-rollout 对账必须发生在 Hook drain 成功之后。+完整恢复先消费 Hook,以建立睡眠期间产生的任务身份,再合并 rollout 的生命周期和进展,最后恢复保护判断。降级终态对账仅处理已有任务。-如果先读 rollout,此时 monitor 中可能还没有睡眠期间刚追加的任务 key,lifecycle 结果无法关联。如果先恢复保护判定,则会基于睡前 last progress 误隐藏任务。+bootstrap 等待 rollout 期间如果恢复代次改变,会丢弃旧生命周期结果;结束 bootstrap 后重新进入读取屏障,不能直接结束较新的恢复。`tailReaderGeneration` 防止唤醒 Task 返回时 reader 已因 Hook 设置变化被替换。`activityProtectionRecoveryGeneration` 防止两次睡眠或设置变化交错后,较早恢复流程提前解除暂停。@@ -397,6 +441,7 @@ rollout 对账必须发生在 Hook drain 成功之后。- 唤醒恢复- Hook 数据源不可用- reader 正在更换+- 当前任务的 rollout 未读全、读取失败、上下文缺失或读取结果过期### progress generation 的作用@@ -464,8 +509,6 @@ Monitor 为 reader 和异步恢复任务维护 generation:- 取消的 drain 不满足恢复屏障- 数据源显式不健康时不沿用最后健康快照做静默判断-这些约束避免系统唤醒、Hook 重装或 `CODEX_HOME` 变化时出现错误完成通知和错误释放。-### monitor 中的主要 generation| generation | 保护的异步路径 |@@ -475,7 +518,7 @@ Monitor 为 reader 和异步恢复任务维护 generation:| `activityProtectionRecoveryGeneration` | 睡眠、唤醒恢复流程,以及跨恢复批次的 rollout 对账结果 || task `progressGeneration` | 通知宽限期间的保护候选 |-每一项都对应不同的“当前性”问题,不能合并成一个全局计数。例如 reader 没变但任务有新进展时,只需要让 protection attempt 失效,不应丢弃整个 reader。+任务进展只使对应的保护尝试失效;reader、bootstrap 和恢复代次分别隔离各自的异步结果。## 建议验证的故障场景@@ -490,13 +533,16 @@ Monitor 为 reader 和异步恢复任务维护 generation:- App 在任务已运行时启动,bootstrap 展示任务但不补发通知- bootstrap 文件持续追加时能重试并最终获得稳定边界- 连续 3 次不稳定后进入 degraded,不启动异常静默判断-- 新 prompt 立即替换旧 turn,rollout terminal 在 5 秒内准确补分类+- 新 prompt 替换旧 turn,分别验证终态在前 5 秒及之后到达时的补分类- 同 session 多个 terminal 候选时不猜测 `Stop` 归属+- 同一组审批 Hook 和稍晚的 rollout 进展以两种顺序读取,均显示橙色等待且只发布一次等待转场+- rollout 先推进进展后,工具、压缩或子 Agent Hook 仍解除等待并更新活动;迟到审批或 reviewer 回填不恢复已清除的等待,中断和 `SessionEnd` 仍能结束对应任务+- 新 turn 边界后无 `turn_id` 的记录只推进新任务;迟到旧终态、分批读取和文件替换不串用上下文- reviewer 缺失后由 rollout 确认为 user 才进入等待- auto review 始终不发布等待 transition-- subagent 关联不可靠时 UI 不展示伪精确数量+- 子任务计数可靠性为 `false` 时 UI 隐藏数量- reader 进行中调用 `drainNow()` 必须再执行一轮新读取-- 唤醒 drain 失败时保护继续暂停+- 唤醒 drain 失败时保护继续暂停;Hook 坏行期间明确 rollout 终态静默结束已知任务,普通进展不恢复隐藏任务- 静默候选在 3 秒窗口内出现进展后不隐藏,迟到通知被撤回- 阈值调长后未超新阈值的 suppressed 任务恢复- Debug 与 Release 并发更新保护记录时新记录不被旧 removal 删除diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.mdindex 44cc4d0..7a6449a 100644--- a/Docs/DeveloperGuide/hook-and-aggregation.md+++ b/Docs/DeveloperGuide/hook-and-aggregation.md@@ -186,7 +186,7 @@ handler 超时由事件决定:回查范围如下:-- 单次最多读取 512 KB+- 单次最多读取 8 MiB- 只提取 reviewer 和 effort 等结构字段- 不把 prompt 或 response 内容写入 Hook 统计@@ -223,7 +223,7 @@ Hook payload 在不同版本中可能把标识或时间表示为不同 JSON 类### rollout 尾部回查的边界-回查只读取 transcript 最后 512 KB、丢弃可能被截断的第一行,再从后向前寻找匹配 turn 的 `turn_context`+回查只读取 transcript 最后 8 MiB、丢弃可能被截断的第一行,再从后向前寻找匹配 turn 的 `turn_context`从后向前是因为同一个 turn 的最新上下文更接近文件尾。限制读取范围是为了守住 Hook 超时,找不到时保留字段缺失而不是扩大成无界扫描。diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.mdindex 661801f..a5dd92f 100644--- a/Docs/DeveloperGuide/notifications.md+++ b/Docs/DeveloperGuide/notifications.md@@ -137,7 +137,8 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正- bootstrap 建立的历史任务不发送通知- 终态任务键在活动监控层保留 24 小时去重- 通知服务还维护自己的已发送 key-- `Stop` 保留正在收尾的任务,rollout 确认完成后只发布一次完成转场+- `Stop` 保留正在收尾的任务;rollout 确认完成后,结束时间不早于恢复界限且距当前不超过 10 秒时发布完成转场+- bootstrap、恢复对账和 Hook 数据源不健康期间,完成记录静默更新- `Interrupt` 和其他终止记录不触发完成通知或任务触觉反馈匿名任务不会发布给任务通知消费者。通知服务在 transition 入口再次过滤 `isAnonymous`,因此匿名任务不发送完成或等待批准通知,也不触发任务触觉反馈。@@ -153,7 +154,8 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正- 自动审批不通知- 同一等待项只通知一次- 任务离开等待状态后从相关集合移除-- bootstrap 中已存在的等待状态不补发历史通知+- bootstrap、恢复对账和 Hook 数据源不健康期间不发布等待转场+- Hook 直接确认等待时,进入等待的时间须不早于恢复界限且距当前不超过 10 秒;rollout 补齐 reviewer 后确认等待时,只检查请求时间不早于恢复界限等待状态是否维持防睡眠是独立设置,不影响是否可以发送等待批准通知。diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.mdindex 7e54cfe..73e3bad 100644--- a/Docs/en/DeveloperGuide/activity-monitor.md+++ b/Docs/en/DeveloperGuide/activity-monitor.md@@ -14,11 +14,21 @@ The live-task flow answers four questions:Hook events provide live progress and interruption signals, while rollout files supply lifecycle context. [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) merges both into the sole task snapshot:```text-Hook JSONL -> HookEventTailReader ---------+- +-> CodexActivityMonitor -> CodexActivitySnapshot-rollout JSONL -> CodexSessionLifecycleReader++Codex Hook -> WorkflowHookEventRecorder -> Hook JSONL+ |-> WorkflowService -> Daily history aggregates+ |-> HookEventTailReader -----++ |-> CodexActivityMonitor+rollout JSONL -> CodexSessionLifecycleReader ----------------------------+ |+ v+ CodexActivitySnapshot+ |-> Activity card and task center+ |-> Glow and sleep prevention```+`WorkflowHookEventRecorder` extracts minimal fields from `stdin`, performs bounded rollout metadata lookup when needed, appends under a file lock, and exits. Historical aggregation and live monitoring independently read the same Hook JSONL. App-server quota and usage use a separate pipeline. See [Hook Collection and Aggregation](hook-and-aggregation.md) for collection details.++Notifications and haptics consume live transitions from the monitor. Glow consumes snapshots and terminal presentation events: orange for user approval, cyan for running, green for completion, and red for termination. Waiting takes precedence among active tasks; a short terminal indication can temporarily override active state.+### Division Between Sources| Information | Primary source | Supplemental source |@@ -28,7 +38,7 @@ rollout JSONL -> CodexSessionLifecycleReader+| Turn start | `UserPromptSubmit` | Rollout `startedAt` or historical lookup || Completion candidate | `Stop` | Rollout terminal || Explicit turn interruption | `Interrupt` | Rollout terminal |-| Other terminal resolution | Rollout terminal | Grace-expiration fallback |+| Other terminal resolution | Rollout terminal | Retain unresolved tasks until expiration || Effort | Hook-recorder lookup | Rollout lifecycle backfill |Each field is resolved from the sources listed above. Hook polling waits 2 seconds after each read, and rollout polling waits 1 second after each reconciliation round.@@ -39,8 +49,8 @@ A snapshot may be read repeatedly after view reconstruction, a new subscription,For example, bootstrap may recover a task already waiting for approval when the app starts:-- The snapshot should show it waiting-- No waiting transition should be emitted+- The snapshot shows it waiting+- No waiting transition is emitted- The notification service therefore does not replay a historical alertCompletion works the same way. Notifications consume `.completed` transitions rather than scanning `recentCompletions`, preventing reminders on app restart or UI refresh.@@ -53,16 +63,16 @@ Completion works the same way. Notifications consume `.completed` transitions raInitial startup reads the latest 24 hours to establish a task baseline:-- Read chunks of at most 512 KB+- Read chunks of at most 512 KiB- Try at most 3 times to obtain stable file boundaries- Use inode and size to detect replacement or append during reading- Never trigger historical completion or waiting notifications from bootstrap results-If it cannot obtain a stable boundary, the reader moves to the current file tail and publishes explicit unhealthy state. Incomplete history is not misrepresented as a real task change.+If stable boundaries cannot be obtained, the reader clears recovered state, moves to each date file’s tail, and publishes unhealthy state.### Bootstrap Is One Logical Transaction-The 24-hour window may span two calendar-day files, and one file may arrive in several 512 KB batches.+The 24-hour window may span two calendar-day files, and one file may arrive in several 512 KiB batches.At `.bootstrapStart`, the monitor clears previous recovered state and pauses side effects. It consumes every `.bootstrapEvents` batch, then waits until `.bootstrapEnd` to:@@ -72,7 +82,7 @@ At `.bootstrapStart`, the monitor clears previous recovered state and pauses sid- Look up missing prompt starts selectively- Publish one complete snapshot-Neither UI nor notifications should observe a partially recovered intermediate batch.+Intermediate batches update internal task state only. Rollout backfill and protection reconciliation require a healthy source and an awake system.### Stable-Boundary Retries@@ -84,17 +94,21 @@ At the start of an attempt, the reader fixes inode and size for all relevant datIf any condition fails, the reader retries from a new baseline. After three consecutive failures, it moves to the current tail and publishes degraded health, pausing Activity Protection checks.+A bootstrap that fails because a directory is unavailable or its boundaries are unstable is retried at most every 10 seconds. Existing events are replayed silently before normal incremental reading resumes. Complete malformed lines retain their coverage gaps without triggering repeated history scans.+### Complete-Line CursorThe Hook recorder may be writing the final line. The reader includes only bytes before the last newline in `completeOffset`.-A partial line is neither discarded nor classified as corrupt. The next cycle rereads from the old offset and commits after the line is complete.+A partial line is neither discarded nor classified as corrupt. The next cycle rereads from the old offset and commits after the line is complete. Until the fixed boundary is fully consumed, the barrier returns `sourceUnavailable`. A malformed complete line degrades its date cursor until that date leaves the reading window or a replacement file is replayed.++While the Hook source is degraded, rollout reads continue for known tasks, accepting only explicit completion or interruption records from a complete current read with matching task identity. These tasks end silently. This path does not apply ordinary progress, backfill approval state, restore suppressed tasks, or resume Activity Protection. It pauses during system sleep and bootstrap, and discards results after cancellation or a reader generation change. Full lifecycle recovery still requires a successful Hook read barrier.### Date Rollover and File Replacement-Normal rollover drains the old date file before switching to the new date. An inode change or file shrink restarts bootstrap instead of reusing the old cursor.+The reader keeps an independent cursor for each calendar date in the rolling 24-hour window. Every cycle covers all these dates, including intermediate dates after a long pause and late appends to the previous date. An inode change or file shrink restarts bootstrap.-When `UserPromptSubmit` predates the current incremental window, the reader can look backward up to 8 MB to recover the prompt start of an existing task.+When `UserPromptSubmit` predates the current incremental window, the reader can look backward up to 8 MiB to recover the prompt start of an existing task.### `drainNow()` Read Barrier@@ -127,14 +141,14 @@ Actors can reenter during `await`; `isProcessingReads` and `hasPendingDrain` conRules are:- Poll every 1 second by default-- Begin with a 512 KB tail window-- Look back at most 8 MB for turn-context fields such as effort+- 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-- Never read or store conversation content for product presentation+- 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 and emits a completion transition.+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.-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 opens a five-second terminal-confirmation window. A late `Stop` updates only the pending task's metadata and progress, without restoring its presentation or resetting the deadline.+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.### Explicit Interruptions@@ -150,23 +164,40 @@ The reader checks a few likely directories first:2. The current date directory3. `archived_sessions`-A resume can continue a session created long ago. If the fast path misses, each active session lifecycle performs one recursive fallback scan at most, avoiding a full sessions-tree traversal every second.+A resume can continue a session created long ago. If the fast path misses, the fast path can retry every 10 seconds and the recursive fallback every 60 seconds. This discovers delayed or moved files without traversing the tree every second.If a file moves to the archive, a missing cached URL clears its cursor and allows full discovery again.### 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 KB reduces resident I/O and discards the first potentially partial line.+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.++If context, effort, or reviewer is missing, the reader replays up to 8 MiB to recover turn ownership, metadata, and progress together. Each file cursor stops looking back after one successful backfill; each cycle backfills at most one session.++Incremental scanning shares an 8 MiB budget per cycle across sessions in rotating order. At most 16 pending tasks are queried per cycle. Budget exhaustion and partial lines return `incomplete`, read failures return `unavailable`, and unresolved files return `notFound`. Cached facts do not establish successful current coverage. A complete read with turn context sets `lifecycleCoverageCheckedAt` to the check time; an incomplete or failed read, a missing file, or missing context clears it. Protection requires this timestamp to be present and less than five seconds old.-If effort remains missing, a targeted lookup for that turn can read up to 8 MB.+The incremental scan advances its offset by complete lines. A line larger than 8 MiB returns `incomplete` from the same line start each cycle, preventing consumption of subsequent records.-Effort backfill applies only to nonterminal tasks that have run for at least 2 seconds and still lack effort, with a 10-second retry interval per turn. This avoids a large search immediately after every task creation.+A malformed rollout line marks unfinished turns as having a coverage gap. Repeated context for the same turn does not clear the gap. New turns establish independent coverage, and explicit terminal records can end a task with incomplete history. Later malformed lines do not revoke known terminal facts. Failed or incomplete reads cannot use cached progress to advance task progress, restore suppressed tasks, or remove protection records.++### Associating Rollout Progress with a Turn++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+- 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`.++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.### Rollout FieldsThe shared `CodexRolloutLineEnvelope` extracts only fields needed for turn context, lifecycle, and progress. Prompt, response, and tool content never enters the activity model.-This tightens privacy boundaries and reduces decode cost for large rollouts. A new live field should extend the minimal envelope rather than decode the full transcript into a general JSON tree.+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.## Task Identity@@ -176,7 +207,7 @@ The task key chooses the most precise available identity:2. `session ID`3. Anonymous project key-A new prompt replaces the old turn in the same session. The old turn enters terminal grace for up to 5 seconds so late ending events can reconcile it.+A new prompt replaces the old turn in the same session. The old turn waits for an explicit terminal result in the background: fast polling for five seconds, then every 30 seconds, retained for at most 24 hours after removal from the active list.Subagent events update activity under their parent task and do not create separate top-level cards.@@ -184,7 +215,9 @@ Subagent events update activity under their parent task and do not create separa`session ID + turn ID` precisely distinguishes sequential turns in one session and is preferred.-Some events contain only session ID. A session key still participates in state, but terminal matching must be more conservative. If one session has several candidates, the monitor returns ambiguous rather than guessing which task ended.+Some events contain only session ID. A later top-level Hook that matches the task and supplies a turn ID fills the in-memory `associatedTurnId` and terminal alias for rollout lookup and deduplication, retaining the original key and protection hash.++Terminal matching checks exact keys and aliases first, then pending tasks in the session. One pending candidate is selected; several return `ambiguous`. Active tasks are checked only when no pending candidate matches. Candidates must satisfy Hook timestamp ordering and turn identity conditions.Without a session ID, only a project key remains. It may merge concurrent anonymous tasks in one project, so anonymous tasks provide reversible UI visibility but cannot drive notifications, sleep prevention, or persisted protection.@@ -205,29 +238,35 @@ Events missing a session ID or turn ID do not create origin memory; `unknown` anThese rules apply to bootstrap and live reads. Other subagents, including Memories, are classified as `auxiliary` and follow auxiliary-task association rules. Historical aggregation still consumes all raw events. Origin memory is neither persisted nor uploaded.-### New Prompts and Terminal Grace+### New Prompts and Terminal Confirmation-Turns in one session run sequentially. When a new prompt arrives, the old turn must leave the active list immediately or the UI briefly shows two top-level tasks.--The new prompt may precede the old turn's rollout terminal, however. Recording termination immediately would misclassify a normally completed task.--The old turn therefore moves to `pendingTerminalTasks`:+A new prompt moves the previous turn in the same session to `pendingTerminalTasks` while rollout confirms its result:- Remove it from the active snapshot immediately- Retain task metadata and start time-- Wait up to 5 seconds for rollout terminal+- Poll quickly for five seconds, then every 30 seconds for rollout terminal- Classify accurately as completed or aborted when terminal arrives-- Converge with a conservative fallback when grace expires without terminal+- Remove unresolved tasks after 24 hours without inventing completion, termination, notification, or glow events`SessionEnd` uses the same confirmation window but moves all tasks in the session no later than that event.### Rejecting Late Events-Tasks store `lastActivityAt`. 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.+Tasks store `lastHookEventAt` and `lastProgressAt`; `lastActivityAt` reads the same value as `lastProgressAt`:++| Field | Source and purpose |+| --- | --- |+| `lastHookEventAt` | Latest accepted Hook timestamp, used to reject stale Hook state changes |+| `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.++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:-- An event older than current last activity cannot overwrite newer state+- Hook state changes and approval requests use `lastHookEventAt`; an approval request older than the latest Hook progress does not restore waiting- 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@@ -261,7 +300,7 @@ Task endings are handled by signal:- `Stop` marks the task as finishing while retaining it in the active list- `Interrupt` records the matching turn as terminated- Rollout terminal confirms completion or termination-- A new turn or `SessionEnd` moves the old task into a five-second terminal-confirmation window; expiration without a terminal result records termination, while suppressed tasks only retain deduplication state+- A new turn or `SessionEnd` removes the old task from the active list and starts background reconciliation; missing terminal evidence stays unresolved until cleanup### Main Event-to-State Transitions@@ -271,20 +310,23 @@ 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 | New progress | running | Clear pending approval and protection record |+| 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 |-| active | New prompt or `SessionEnd` | pending terminal | Remove from snapshot and begin 5-second grace |+| 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 | Silence exceeds threshold | suppressed | Hide and remove sleep-prevention contribution |-| suppressed | New progress | running | Clear persisted protection and old notification |+| running | Protection conditions hold and silence reaches threshold | suppressed | Hide and remove sleep-prevention contribution |+| suppressed | Valid tool, compaction, subagent, or `Stop` Hook, or new progress from healthy reconciliation | running | Clear persisted protection and old notification |+| active, suppressed, or pending terminal | Matching rollout terminal from a complete read | completed or terminated | Record the terminal and remove the task; process silently while degraded |### Two-Stage Approval Confirmation-`PermissionRequest` accepts reviewers `user`, `auto_review`, and `guardian_subagent`.+The task’s `approvalReviewer` comes from Hook records or rollout `payload.approvals_reviewer`, with values `user`, `auto_review`, or `guardian_subagent`.-If the Hook event includes reviewer, the task can confirm immediately. If reviewer is missing, it saves `pendingApprovalRequestedAt` and waits for rollout polling to fill it in.+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.-Only an explicit user reviewer emits a waiting transition. Remaining running while uncertain is more truthful than falsely telling the user Codex is waiting for them.+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.++Approval waiting is tracked per task. Valid Hook progress from another parallel tool or subagent within the same task also clears waiting.### Effort Merging@@ -294,9 +336,9 @@ Several context events in one turn may report different reasoning efforts. The tA subagent turn ID belongs to the subagent, so its parent can be associated only by shared session.-Active subagent count is reliable only when exactly one active parent exists in that session, no pending-terminal ambiguity exists, and start/stop events carry stable agent IDs.+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.-With missing IDs, stop-before-start, or several candidates in one session, the monitor lowers reliability and the UI omits a falsely precise number.+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.## Snapshot Priority@@ -327,7 +369,9 @@ 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`.-History reloads, sleep recovery, and source health changes clear pending events and update `terminalPresentationNotBefore`. Collection pauses during bootstrap, wake reconciliation, and unhealthy source state. Records ending before the recovery boundary do not produce brief indicators; tasks ending after recovery publish normally.+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`.++History reloads, sleep recovery, and source health changes clear pending events and update `terminalPresentationNotBefore`. Publication pauses during bootstrap, recovery reconciliation, and unhealthy source state.### Stable Ordering@@ -337,13 +381,13 @@ All lists sort by most recent time first and then display UUID string. Stable or### Cleanup Uses the Nearest Deadline-The monitor manages terminal grace, activity retention, history retention, terminal deduplication, and protection-record expiration. Menu bar terminal hints and task glow have their expiry managed by `StatusItemController` and `TaskGlowController`, respectively. Hint expiry does not republish activity snapshots.+The monitor manages expiration for pending tasks, active tasks, history, terminal deduplication, and protection records. Menu bar terminal hints and task glow have their expiry managed by `StatusItemController` and `TaskGlowController`, respectively. Hint expiry does not republish activity snapshots.The cleanup task waits for the nearest future deadline, processes it, then schedules the next.## System Sleep and Wake-Stalled Task Protection pauses when the system is about to sleep. Wake follows a strict recovery order:+Stalled Task Protection pauses when the system is about to sleep. Full recovery after wake follows this order:1. Enter recovery and keep protection paused2. Wait for `HookEventTailReader.drainNow()` to succeed@@ -351,7 +395,7 @@ Stalled Task Protection pauses when the system is about to sleep. Wake follows a4. Reconcile from the new Hook and rollout results together5. Resume Stalled Task Protection-If the new read fails, the reader is replaced, or the source is unavailable, evaluation must not continue from the pre-sleep snapshot.+If the Hook barrier returns `sourceUnavailable`, only explicit terminal records for known tasks are reconciled, silently, while protection stays paused. Later polling retries full recovery. Reader replacement or task cancellation discards that round’s results.### Evaluation Pauses During System Sleep@@ -359,14 +403,14 @@ Silence evaluation stops during system sleep. On recovery, the monitor silentlyThe check task waits with `SuspendingClock`, but silence duration is calculated from `Date` and `lastProgressAt` without subtracting time spent asleep. `will-sleep` enters recovery; `did-wake` reevaluates after a new data read barrier.-### Why Wake Order Cannot Be Reversed--Rollout reconciliation must occur after a successful Hook drain.+### Identity and Generations During Wake Recovery-Reading rollout first may find lifecycle data whose task key has not yet been added to the monitor from Hook events written during sleep. Resuming protection first could hide tasks from a pre-sleep last-progress time.+Full recovery consumes Hook events first to establish task identities created during sleep, then merges rollout lifecycle and progress before resuming protection. Degraded terminal reconciliation handles known tasks only.`tailReaderGeneration` prevents a returning wake task from using a reader replaced by a Hook settings change. `activityProtectionRecoveryGeneration` prevents an older recovery from unpausing evaluation after two overlapping sleep or settings changes.+If the recovery generation changes while bootstrap awaits rollout, its old lifecycle result is discarded. Bootstrap then enters a fresh read barrier instead of completing the newer recovery generation.+## Stalled Task ProtectionStalled Task Protection works only while Prevent System Sleep is enabled and evaluates only non-anonymous `running` tasks.@@ -464,8 +508,6 @@ The monitor maintains generations for readers and asynchronous recovery:- A canceled drain does not satisfy a recovery barrier- Explicitly unhealthy source state cannot reuse the last healthy snapshot for silence evaluation-These constraints prevent false completion alerts and incorrect release during system wake, Hook reinstall, or `CODEX_HOME` change.-### Main Generations in the Monitor| Generation | Protected asynchronous path |@@ -475,7 +517,7 @@ These constraints prevent false completion alerts and incorrect release during s| `activityProtectionRecoveryGeneration` | Sleep/wake recovery and rollout reconciliation results spanning recovery generations || Task `progressGeneration` | Protection candidate during notification grace |-Each answers a different “is this current?” question and cannot become one global counter. A task making progress without a reader change should invalidate only its protection attempt, not the entire reader.+Task progress invalidates its protection attempt. Reader, bootstrap, and recovery generations each isolate their own asynchronous results.## Suggested Failure-Scenario Tests@@ -490,13 +532,16 @@ Each answers a different “is this current?” question and cannot become one g- Starting the app while a task is running shows it through bootstrap without replaying notifications- Bootstrap retries while files continuously append and eventually obtains a stable boundary- Three unstable attempts enter degraded state without starting silence evaluation-- A new prompt immediately replaces the old turn, and rollout terminal within 5 seconds classifies it correctly+- 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+- 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-- The UI omits a falsely precise subagent count when association is unreliable+- The UI hides the subagent count when count reliability is `false`- Calling `drainNow()` during a read forces another new read-- Protection remains paused after a failed wake drain+- A failed wake drain keeps protection paused; explicit rollout terminals silently end known tasks during Hook corruption, while ordinary progress leaves suppressed tasks hidden- A silence candidate that progresses within the 3-second window is not hidden, and a late notification is withdrawn- Lengthening the threshold restores suppressed tasks below the new threshold- Concurrent Debug and Release updates do not let an old removal delete a new protection recorddiff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.mdindex 74c1deb..d73714a 100644--- a/Docs/en/DeveloperGuide/hook-and-aggregation.md+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md@@ -186,7 +186,7 @@ For `UserPromptSubmit` and `PermissionRequest`, input may omit reviewer or efforThe lookup:-- Reads at most 512 KB once+- Reads at most 8 MiB once- Extracts only structural fields such as reviewer and effort- Never writes prompt or response content to Hook statistics@@ -223,7 +223,7 @@ Permissiveness exists only at the external-input boundary. After conversion to `### Rollout Tail-Lookup Boundary-The lookup reads only the last 512 KB of the transcript, discards a potentially truncated first line, then searches backward for the matching turn's `turn_context`.+The lookup reads only the last 8 MiB of the transcript, discards a potentially truncated first line, then searches backward for the matching turn's `turn_context`.Backward search finds the latest context for a turn nearest the file tail. The read limit protects Hook timeout; a miss leaves the field absent instead of expanding into an unbounded scan.diff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.mdindex 3e3015c..927e4ba 100644--- a/Docs/en/DeveloperGuide/notifications.md+++ b/Docs/en/DeveloperGuide/notifications.md@@ -137,7 +137,8 @@ Task notifications respond only to new terminal transitions published by the mon- Tasks established during bootstrap do not notify- The activity monitor retains terminal task keys for 24-hour deduplication- The notification service also tracks its own sent keys-- `Stop` retains the finishing task; rollout confirmation emits one completion transition+- `Stop` retains the finishing task; rollout confirmation emits a completion transition when its end time is no earlier than the recovery boundary and no more than 10 seconds old+- Completion records update silently during bootstrap, recovery reconciliation, and unhealthy Hook source state- `Interrupt` and other termination records do not trigger completion notifications or task hapticsAnonymous tasks are not published to task-notification consumers. The notification service filters `isAnonymous` again at the transition boundary, so anonymous tasks cannot send completion or approval notifications or trigger task haptics.@@ -153,7 +154,8 @@ A waiting notification is sent only when the `PermissionRequest` reviewer is con- Automatic review does not notify- One waiting item notifies only once- Leaving waiting state removes the item from the relevant set-- Waiting state found during bootstrap does not replay historical notifications+- 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 boundaryWhether waiting maintains sleep prevention is an independent setting and does not affect notification eligibility.diff --git a/appcast.xml b/appcast.xmlindex 0508d35..3b5f916 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.1</title>+ <sparkle:version>101</sparkle:version>+ <sparkle:shortVersionString>4.0.1</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#4.0.1</sparkle:releaseNotesLink>+ <pubDate>Mon, 14 Sep 2026 20:17:36 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v4.0.1.dmg" sparkle:edSignature="78Yh/oljrOfxMdN3XpMuAog0JJLXldQ0K0Oh/Li5AMgJlMTmRSNswGakcMMP/Fn4xxi/W73oHcXXnfarOu8MAg==" length="8091527" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 4.0.0</title><sparkle:version>100</sparkle:version>