CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 修复超长与残缺日志导致的任务状态异常
Bobd3e0ddbe1946
diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swiftindex f2b213c..a94bf7f 100644--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift@@ -331,8 +331,10 @@ final class CodexActivityMonitor: ObservableObject {let hadLifecycleCoverage = task.lifecycleCoverageCheckedAt != nilif !terminalOnly {- task.lifecycleCoverageCheckedAt = state.readStatus == .complete && state.hasContext ? Date() : nil- if task.lifecycleCoverageCheckedAt == nil {+ let now = Date()+ task.recordLifecycleRead(state, at: now)+ if task.activityProtectionDeadline(at: now, inactivityDuration: activityProtectionSettings.inactivityDuration.timeInterval)+ .map({ $0 <= now }) != true {cancelActivityProtectionAttempt(for: key)}}diff --git a/CodexBar/Services/Workflow/CodexActivityProtection.swift b/CodexBar/Services/Workflow/CodexActivityProtection.swiftindex 02030bd..5eebc8b 100644--- a/CodexBar/Services/Workflow/CodexActivityProtection.swift+++ b/CodexBar/Services/Workflow/CodexActivityProtection.swift@@ -114,7 +114,7 @@ extension CodexActivityMonitor {let restorableKeys = tasks.compactMap { key, task -> CodexActivityTaskKey? inguard !key.isAnonymous,task.state == .suppressed,- task.lastProgressAt.addingTimeInterval(threshold) > now else {+ task.activityProtectionReferenceAt.addingTimeInterval(threshold) > now else {return nil}return key@@ -126,8 +126,8 @@ 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 {+ let deadline = task.activityProtectionDeadline(at: now, inactivityDuration: threshold),+ deadline <= now else {return nil}return key@@ -148,11 +148,10 @@ 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}- return task.lastProgressAt.addingTimeInterval(threshold)+ return task.activityProtectionDeadline(at: now, inactivityDuration: threshold)}.min()guard let nextDeadline else {@@ -194,9 +193,9 @@ 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 {+ let deadline = task.activityProtectionDeadline(at: now, inactivityDuration: threshold),+ deadline <= now else {return nil}return ActivityProtectionCandidate(@@ -336,18 +335,11 @@ extension CodexActivityMonitor {now: Date) {guard !key.isAnonymous,- isStarted,- isActivityProtectionEnabled,- tailReader != nil,- !isBootstrapping,- !isActivityProtectionRecoveryInProgress,- isActivitySourceHealthy,+ canEvaluateActivityProtection,let task = tasks[key],task.state == .running,- task.hasFreshLifecycle(at: now),- task.lastProgressAt.addingTimeInterval(- activityProtectionSettings.inactivityDuration.timeInterval- ) <= now else {+ let deadline = task.activityProtectionDeadline(at: now, inactivityDuration: activityProtectionSettings.inactivityDuration.timeInterval),+ deadline <= now else {return}suppressActivityTaskSilently(key, markedAt: now)@@ -405,13 +397,12 @@ 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}- return task.lastProgressAt- .addingTimeInterval(candidate.inactivityDuration.timeInterval) <= now+ return task.activityProtectionDeadline(at: now, inactivityDuration: candidate.inactivityDuration.timeInterval)+ .map { $0 <= now } == true}func isInactivityProtectionNoticeRelevant(diff --git a/CodexBar/Services/Workflow/CodexActivityTask.swift b/CodexBar/Services/Workflow/CodexActivityTask.swiftindex e1c8e6b..5792273 100644--- a/CodexBar/Services/Workflow/CodexActivityTask.swift+++ b/CodexBar/Services/Workflow/CodexActivityTask.swift@@ -121,6 +121,8 @@ struct CodexActivityTask {let key: CodexActivityTaskKeyvar associatedTurnId: String?var lifecycleCoverageCheckedAt: Date?+ var incompleteTailCheckedAt: Date?+ var incompleteTailUnchangedSince: Date?var state: CodexActivityTaskStatevar latestEvent: CodexActivityEventvar projectName: String?@@ -224,6 +226,27 @@ struct CodexActivityTask {lifecycleCoverageCheckedAt.map { now.timeIntervalSince($0) < 5 } == true}+ mutating func recordLifecycleRead(_ state: CodexSessionTaskLifecycleState, at now: Date) {+ lifecycleCoverageCheckedAt = state.readStatus == .complete && state.hasContext ? now : nil+ incompleteTailUnchangedSince = state.readStatus == .incomplete && state.hasContext ? state.incompleteTailUnchangedSince : nil+ incompleteTailCheckedAt = incompleteTailUnchangedSince == nil ? nil : now+ }++ /// 阈值调整与隐藏共用计时起点, 恢复不要求读取结果仍在有效期内+ var activityProtectionReferenceAt: Date {+ max(lastProgressAt, incompleteTailUnchangedSince ?? lastProgressAt)+ }++ /// 隐藏还要求新鲜的读取依据, 半行观察不作为完整覆盖或任务进展+ func activityProtectionDeadline(at now: Date, inactivityDuration: TimeInterval) -> Date? {+ if hasFreshLifecycle(at: now) {+ return activityProtectionReferenceAt.addingTimeInterval(inactivityDuration)+ }+ guard let incompleteTailCheckedAt, now.timeIntervalSince(incompleteTailCheckedAt) < 5,+ incompleteTailUnchangedSince != nil else { return nil }+ return activityProtectionReferenceAt.addingTimeInterval(inactivityDuration)+ }+mutating func mergeMetadata(from event: WorkflowHookEvent) {if associatedTurnId == nil, !key.isAnonymous, event.agentId == nil {associatedTurnId = event.turnIddiff --git a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swiftindex 505c460..67fa8a9 100644--- a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift+++ b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift@@ -32,9 +32,9 @@ actor CodexSessionLifecycleReader {self.fileManager = fileManager}- func lifecycleStates(for references: [CodexActivityTurnReference]) -> [CodexSessionTaskLifecycleState] {+ func lifecycleStates(for references: [CodexActivityTurnReference], now: Date = Date()) -> [CodexSessionTaskLifecycleState] {let grouped = Dictionary(grouping: references, by: \.sessionId)- let cutoff = Date().addingTimeInterval(-CodexActivityRetention.window)+ let cutoff = now.addingTimeInterval(-CodexActivityRetention.window)cursorsBySession = cursorsBySession.filter { $0.value.lastReadAt > cutoff }lastResolutionAttemptBySession = lastResolutionAttemptBySession.filter { $0.value > cutoff }lastRecursiveAttemptBySession = lastRecursiveAttemptBySession.filter { $0.value > cutoff }@@ -50,7 +50,7 @@ actor CodexSessionLifecycleReader {let latest = sessionReferences.max(by: { $0.startedAt < $1.startedAt }) else { continue }var status = CodexSessionReadStatus.notFoundif var cursor = cursor(for: latest) {- status = scan(into: &cursor, limit: min(Self.incrementalByteLimit, budget))+ status = scan(into: &cursor, limit: min(Self.incrementalByteLimit, budget), now: now)if cursor.metadata?.id != sessionId {status = .unavailable}@@ -64,7 +64,7 @@ actor CodexSessionLifecycleReader {status = backfillContext(into: &cursor)performedBackfill = true}- cursor.lastReadAt = Date()+ cursor.lastReadAt = nowlet referencedTurns = Set(sessionReferences.map(\.turnId))cursor.lifecycleByTurnId = cursor.lifecycleByTurnId.filter {referencedTurns.contains($0.key) || ($0.value.lastProgressAt ?? .distantPast) > cutoff@@ -87,7 +87,9 @@ actor CodexSessionLifecycleReader {threadId: cursor?.metadata?.id,rootSessionId: cursor?.metadata?.sessionId,parentThreadId: cursor?.metadata?.parentThreadId,- lastExecutionProgressAt: known?.lastExecutionProgressAt+ lastExecutionProgressAt: known?.lastExecutionProgressAt,+ incompleteTailUnchangedSince: status == .incomplete && !hasReadGap && known?.hasContext == true && known?.terminal == nil+ ? cursor?.incompleteTailUnchangedSince : nil))}}@@ -163,7 +165,7 @@ actor CodexSessionLifecycleReader {let offset = size > Self.bootstrapByteLimit ? size - Self.bootstrapByteLimit : 0return SessionFileCursor(url: url, fileIdentifier: stat?.identifier, offset: offset, historicalOffset: offset,- discardsLeadingPartialLine: offset > 0,+ isDiscardingLine: offset > 0,metadata: WorkflowRolloutMetadataReader.metadata(transcriptPath: url.path))}@@ -176,7 +178,7 @@ actor CodexSessionLifecycleReader {fileIdentifier: cursor.fileIdentifier,offset: start,historicalOffset: start,- discardsLeadingPartialLine: start > 0,+ isDiscardingLine: start > 0,metadata: cursor.metadata)let status = scan(into: &restored, limit: Self.contextByteLimit, through: end)@@ -186,46 +188,40 @@ actor CodexSessionLifecycleReader {return .complete}- private func scan(into cursor: inout SessionFileCursor, limit: Int, through upperBound: UInt64? = nil) -> CodexSessionReadStatus {+ private func scan(into cursor: inout SessionFileCursor, limit: Int, through upperBound: UInt64? = nil, now: Date = Date()) -> CodexSessionReadStatus {cursor.lastReadByteCount = 0+ var previousTailUnchangedSince = cursor.incompleteTailUnchangedSince+ cursor.incompleteTailUnchangedSince = nilguard 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)+ previousTailUnchangedSince = nil}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.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 {- complete = JSONLines.droppingLeadingPartialLine(complete)- cursor.discardsLeadingPartialLine = false- }- for line in complete.split(separator: JSONLines.newlineByte) {- let decoded = JSONLines.decodeWithFailures(CodexRolloutLineEnvelope.self, from: Data(line))- if decoded.failedLineCount > 0 {- cursor.markReadGap()- }- for envelope in decoded.values {- cursor.apply(envelope)- }+ if end > cursor.offset {+ guard limit > 0 else { return .incomplete }+ guard (try? handle.seek(toOffset: cursor.offset)) != nil,+ let data = try? handle.read(upToCount: min(limit, Int(end - cursor.offset))), !data.isEmpty else { return .unavailable }+ cursor.lastReadByteCount = data.count+ cursor.offset += UInt64(data.count)+ cursor.fileIdentifier = stat.identifier+ cursor.consume(data, maximumBufferedLineByteCount: Self.maximumBufferedLineByteCount)}guard let after = WorkflowStorage.fileStat(at: cursor.url), after.identifier == stat.identifier,after.size >= end else { return .unavailable }- return cursor.offset == end ? .complete : .incomplete+ // 只有实际文件末尾的有界半行可以计时, 积压和跳过的大行不能作为静默依据+ if cursor.offset == after.size, cursor.hasPartialLine, !cursor.isDiscardingLine {+ cursor.incompleteTailUnchangedSince = cursor.lastReadByteCount > 0 ? now : previousTailUnchangedSince ?? now+ }+ return cursor.offset == end && !cursor.hasPartialLine ? .complete : .incomplete}private static let bootstrapByteLimit: UInt64 = 512 * 1024private static let incrementalByteLimit = 8 * 1024 * 1024private static let contextByteLimit = 8 * 1024 * 1024+ private static let maximumBufferedLineByteCount = 16 * 1024 * 1024}private nonisolated struct SessionFileCursor {@@ -233,14 +229,76 @@ private nonisolated struct SessionFileCursor {var fileIdentifier: UInt64?var offset: UInt64let historicalOffset: UInt64- var discardsLeadingPartialLine: Bool+ var isDiscardingLine: Boolvar metadata: WorkflowRolloutMetadataPayload?var currentTurnId: String?var lifecycleByTurnId: [String: SessionTurnLifecycle] = [:]+ var partialLineData = Data()var didBackfill = falsevar hasDecodeFailures = falsevar lastReadAt = Date()var lastReadByteCount = 0+ var incompleteTailUnchangedSince: Date?++ var hasPartialLine: Bool {+ isDiscardingLine || !partialLineData.isEmpty+ }++ /// 读取预算可以在一行中间结束, 游标仍需推进并在下一轮继续拼接+ /// 超过缓冲上限后只扫描到换行, 避免异常大行阻塞后续终态+ mutating func consume(_ data: Data, maximumBufferedLineByteCount: Int) {+ var fragmentStart = data.startIndex+ while let newline = data[fragmentStart...].firstIndex(of: JSONLines.newlineByte) {+ consumeLineFragment(+ data[fragmentStart ..< newline],+ completesLine: true,+ maximumBufferedLineByteCount: maximumBufferedLineByteCount+ )+ fragmentStart = data.index(after: newline)+ }+ if fragmentStart < data.endIndex {+ consumeLineFragment(+ data[fragmentStart...],+ completesLine: false,+ maximumBufferedLineByteCount: maximumBufferedLineByteCount+ )+ }+ }++ private mutating func consumeLineFragment(+ _ fragment: Data.SubSequence,+ completesLine: Bool,+ maximumBufferedLineByteCount: Int+ ) {+ if isDiscardingLine {+ if completesLine {+ isDiscardingLine = false+ }+ return+ }++ guard fragment.count <= maximumBufferedLineByteCount - partialLineData.count else {+ partialLineData.removeAll(keepingCapacity: false)+ markReadGap()+ isDiscardingLine = !completesLine+ return+ }++ partialLineData.append(contentsOf: fragment)+ guard completesLine else { return }+ let keepsCapacity = partialLineData.count <= Self.retainedLineCapacityByteLimit+ defer { partialLineData.removeAll(keepingCapacity: keepsCapacity) }++ let decoded = JSONLines.decodeWithFailures(CodexRolloutLineEnvelope.self, from: partialLineData)+ if decoded.failedLineCount > 0 {+ markReadGap()+ }+ for envelope in decoded.values {+ apply(envelope)+ }+ }++ private static let retainedLineCapacityByteLimit = 512 * 1024/// 损坏可能遮住 turn 边界, 只保留已明确结束的事实, 后续新 turn 独立建立覆盖mutating func markReadGap() {@@ -496,6 +554,7 @@ nonisolated struct CodexSessionTaskLifecycleState {var rootSessionId: String?var parentThreadId: String?var lastExecutionProgressAt: Date?+ var incompleteTailUnchangedSince: Date?}nonisolated enum CodexSessionReadStatus {diff --git a/CodexBarTests/CodexActivityTaskTests.swift b/CodexBarTests/CodexActivityTaskTests.swiftindex aed2a62..86b5438 100644--- a/CodexBarTests/CodexActivityTaskTests.swift+++ b/CodexBarTests/CodexActivityTaskTests.swift@@ -51,6 +51,165 @@ struct CodexActivityTaskTests {#expect(task.progressGeneration == 3)}+ @Test func incompleteTailDeadlineAlsoWaitsForLatestHookProgressAndUsesCurrentThreshold() {+ var task = makeTask()+ let observed = TestFixtures.now+ let checked = observed.addingTimeInterval(3600)+ task.recordLifecycleRead(incompleteTail(since: observed), at: checked)+ task.recordProgress(at: observed.addingTimeInterval(1800))+ #expect(task.activityProtectionDeadline(at: checked, inactivityDuration: 3600) == observed.addingTimeInterval(5400))+ #expect(task.activityProtectionDeadline(at: checked, inactivityDuration: 1800) == checked)+ #expect(!task.hasFreshLifecycle(at: checked))+ #expect(task.activityProtectionDeadline(at: checked.addingTimeInterval(5), inactivityDuration: 3600) == nil)+ }++ @Test(arguments: [CodexSessionReadStatus.incomplete, .unavailable, .notFound])+ func losingTailEvidenceRevokesProtectionEligibility(status: CodexSessionReadStatus) {+ var task = makeTask()+ let now = TestFixtures.now.addingTimeInterval(3600)+ task.recordLifecycleRead(incompleteTail(since: TestFixtures.now), at: now)+ #expect(task.activityProtectionDeadline(at: now, inactivityDuration: 3600) == now)+ var lost = incompleteTail(since: TestFixtures.now)+ lost.readStatus = status+ lost.incompleteTailUnchangedSince = nil+ task.recordLifecycleRead(lost, at: now)+ #expect(task.activityProtectionDeadline(at: now, inactivityDuration: 3600) == nil)+ #expect(task.incompleteTailCheckedAt == nil)+ }++ @Test func incompleteTailCannotResumeApprovalButCompleteProgressCan() {+ var task = makeTask()+ _ = task.recordApprovalRequest(from: TestFixtures.event(.permissionRequest))+ let now = TestFixtures.now.addingTimeInterval(3600)+ var state = incompleteTail(since: TestFixtures.now)+ state.lastExecutionProgressAt = now+ let owner = CodexActivityExecutionKey(agentId: nil, turnId: "turn-a")+ task.recordLifecycleRead(state, at: now)+ task.mergeExecutionLifecycle(state, owner: owner)+ #expect(task.state == .waitingApproval)+ #expect(!task.hasFreshLifecycle(at: now))++ state.readStatus = .complete+ state.incompleteTailUnchangedSince = nil+ task.recordLifecycleRead(state, at: now)+ task.mergeExecutionLifecycle(state, owner: owner)+ #expect(task.hasFreshLifecycle(at: now))+ #expect(task.incompleteTailCheckedAt == nil)+ #expect(task.state == .running)+ }++ private func incompleteTail(since date: Date) -> CodexSessionTaskLifecycleState {+ CodexSessionTaskLifecycleState(+ sessionId: "session-a", turnId: "turn-a", startedAt: nil, approvalReviewer: nil, effort: nil,+ lastProgressAt: nil, terminal: nil, readStatus: .incomplete, hasContext: true,+ incompleteTailUnchangedSince: date+ )+ }++ @Test(arguments: ["unchanged", "growth", "unavailable", "stale"])+ func suppressionRevalidatesTailAfterNotification(scenario: String) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = try makeProtectionMonitor(in: directory, preferences: preferences)+ defer { monitor.stop() }+ let now = Date()+ var task = makeTask(TestFixtures.event(at: now.addingTimeInterval(-7200)))+ task.recordLifecycleRead(incompleteTail(since: now.addingTimeInterval(-3601)), at: now)+ monitor.tasks[task.key] = task+ let candidate = ActivityProtectionCandidate(+ key: task.key, taskID: task.displayID, projectName: task.projectName,+ lastProgressAt: task.lastProgressAt, progressGeneration: task.progressGeneration, inactivityDuration: .oneHour+ )+ #expect(monitor.isActivityProtectionCandidateRelevant(candidate, now: now))++ switch scenario {+ case "growth": task.recordLifecycleRead(incompleteTail(since: now), at: now)+ case "unavailable":+ var state = incompleteTail(since: now)+ state.readStatus = .unavailable+ task.recordLifecycleRead(state, at: now)+ case "stale": task.incompleteTailCheckedAt = now.addingTimeInterval(-5)+ default: break+ }+ monitor.tasks[task.key] = task+ let attemptID = UUID()+ monitor.activityProtectionAttempts[task.key] = ActivityProtectionAttempt(+ id: attemptID, candidate: candidate, markedAt: now, timeoutTask: Task {}+ )+ monitor.finishActivityProtectionAttempt(task.key, attemptID: attemptID, taskID: task.displayID, notificationWasSubmitted: false)+ #expect(monitor.tasks[task.key]?.state == (scenario == "unchanged" ? .suppressed : .running))+ #expect(monitor.activityProtectionAttempts.isEmpty)+ }++ @Test(arguments: [false, true], [ActivityProtectionSettings.InactivityDuration.thirtyMinutes, .oneHour])+ func longerThresholdRestoresTailSuppressionAndUsesNewDeadline(+ expiredObservation: Bool, previousDuration: ActivityProtectionSettings.InactivityDuration+ ) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = try makeProtectionMonitor(in: directory, preferences: preferences)+ defer { monitor.stop() }+ let changedAt = Date()+ let hiddenAfter: TimeInterval = previousDuration == .thirtyMinutes ? 3000 : 3600+ let newDuration: ActivityProtectionSettings.InactivityDuration = previousDuration == .thirtyMinutes ? .oneHour : .twoHours+ let tailStoppedAt = changedAt.addingTimeInterval(-hiddenAfter - 300)+ let hiddenAt = tailStoppedAt.addingTimeInterval(hiddenAfter)+ let newDeadline = tailStoppedAt.addingTimeInterval(newDuration.timeInterval)+ var task = makeTask(TestFixtures.event(at: tailStoppedAt.addingTimeInterval(-3600)))+ let key = task.key+ let identifier = try #require(key.activityProtectionIdentifier)+ task.recordLifecycleRead(incompleteTail(since: tailStoppedAt), at: hiddenAt)+ monitor.tasks[key] = task+ monitor.activityProtectionSettings.setInactivityDuration(previousDuration)+ monitor.reconcileActivityProtection(now: hiddenAt, sendsNotification: false)+ #expect(monitor.tasks[key]?.state == .suppressed)+ #expect(monitor.activityProtectionRecords[identifier] != nil)++ let checkedAt = expiredObservation ? changedAt.addingTimeInterval(-5) : changedAt+ monitor.tasks[key]?.recordLifecycleRead(incompleteTail(since: tailStoppedAt), at: checkedAt)+ monitor.activityProtectionSettings.setInactivityDuration(newDuration)+ monitor.handleActivityProtectionTimingChange()+ #expect(monitor.tasks[key]?.state == .running)+ #expect(monitor.activityProtectionRecords[identifier] == nil)+ #expect(monitor.tasks[key]?.lastProgressAt == task.lastProgressAt)+ #expect(monitor.tasks[key]?.hasFreshLifecycle(at: changedAt) == false)++ monitor.reconcileActivityProtection(now: newDeadline, sendsNotification: false)+ #expect(monitor.tasks[key]?.state == .running)+ monitor.tasks[key]?.recordLifecycleRead(incompleteTail(since: tailStoppedAt), at: newDeadline.addingTimeInterval(-1))+ monitor.reconcileActivityProtection(now: newDeadline.addingTimeInterval(-1), sendsNotification: false)+ #expect(monitor.tasks[key]?.state == .running)+ monitor.reconcileActivityProtection(now: newDeadline, sendsNotification: false)+ #expect(monitor.tasks[key]?.state == .suppressed)+ #expect(monitor.activityProtectionRecords[identifier] != nil)+ monitor.cancelInactivityCheck()+ await monitor.activityProtectionPersistenceTask?.value+ }++ private func makeProtectionMonitor(in directory: TestDirectory, preferences: TestPreferences) throws -> CodexActivityMonitor {+ let monitor = try CodexActivityMonitor(+ codexHookSettings: CodexHookSettings(+ hooksURL: directory.url.appendingPathComponent("hooks.json"),+ codexStatusService: makeStatusService(suiteName: preferences.suite)+ ),+ activityProtectionSettings: ActivityProtectionSettings(defaults: preferences.defaults),+ activityProtectionStateStore: ActivityProtectionStateStore(directoryURL: directory.url)+ )+ monitor.isStarted = true+ monitor.isActivityProtectionEnabled = true+ monitor.isActivitySourceHealthy = true+ monitor.tailReader = HookEventTailReader(eventsDirectoryURL: directory.url) { _ in }+ return monitor+ }++ private nonisolated func makeStatusService(suiteName: String) throws -> CodexStatusService {+ try CodexStatusService(defaults: #require(UserDefaults(suiteName: suiteName)))+ }+@Test func subagentCountDeduplicatesAndRejectsOlderEvents() {var task = makeTask()#expect(task.snapshot.activeSubagentCount == 0)diff --git a/CodexBarTests/CodexSessionLifecycleReaderTests.swift b/CodexBarTests/CodexSessionLifecycleReaderTests.swiftindex 0f1d828..9d48113 100644--- a/CodexBarTests/CodexSessionLifecycleReaderTests.swift+++ b/CodexBarTests/CodexSessionLifecycleReaderTests.swift@@ -30,12 +30,107 @@ struct CodexSessionLifecycleReaderTests {let partial = try #require(await reader.lifecycleStates(for: [reference]).first)#expect(partial.readStatus == .incomplete)#expect(partial.terminal == nil)+ let unchanged = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(unchanged.readStatus == .incomplete)+ #expect(unchanged.terminal == nil)try append("\n", to: url)let complete = try #require(await reader.lifecycleStates(for: [reference]).first)#expect(complete.readStatus == .complete)#expect(complete.terminal != nil)}+ @Test func incompleteTailWaitsForFullThresholdAndGrowthRestartsObservation() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [context, start])+ try append(String(completion.dropLast()), to: url)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let firstObserved = TestFixtures.now.addingTimeInterval(7200)+ var task = CodexActivityTask(+ displayID: UUID(), key: CodexActivityTaskKey(event: TestFixtures.event()), event: TestFixtures.event(),+ state: .running, latestEvent: .promptSubmitted, startedAt: TestFixtures.now, progressGeneration: 1+ )++ for elapsed in [0.0, 3599, 3600] {+ let now = firstObserved.addingTimeInterval(elapsed)+ let state = try #require(await reader.lifecycleStates(for: [reference], now: now).first)+ #expect(state.readStatus == .incomplete)+ #expect(state.incompleteTailUnchangedSince == firstObserved)+ task.recordLifecycleRead(state, at: now)+ let deadline = try #require(task.activityProtectionDeadline(at: now, inactivityDuration: 3600))+ #expect((deadline <= now) == (elapsed == 3600))+ #expect(!task.hasFreshLifecycle(at: now))+ #expect(task.lastProgressAt == TestFixtures.now)+ }++ try append("}", to: url)+ let growthTime = firstObserved.addingTimeInterval(3601)+ let growing = try #require(await reader.lifecycleStates(for: [reference], now: growthTime).first)+ #expect(growing.incompleteTailUnchangedSince == growthTime)+ task.recordLifecycleRead(growing, at: growthTime)+ #expect(task.activityProtectionDeadline(at: growthTime, inactivityDuration: 3600) == growthTime.addingTimeInterval(3600))++ try append("\n", to: url)+ let completed = try #require(await reader.lifecycleStates(for: [reference], now: growthTime).first)+ #expect(completed.readStatus == .complete)+ #expect(completed.terminal != nil)+ #expect(completed.incompleteTailUnchangedSince == nil)+ }++ @Test func restartAndFileReplacementStartNewTailObservation() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [context, start])+ try append(completion, to: url)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ _ = await reader.lifecycleStates(for: [reference], now: TestFixtures.now)+ let later = TestFixtures.now.addingTimeInterval(3600)+ let restarted = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ #expect(await restarted.lifecycleStates(for: [reference], now: later).first?.incompleteTailUnchangedSince == later)++ let replacement = (metadata(session: "session-a") + "\n" + context + "\n" + start + "\n" + completion)+ try Data(replacement.utf8).write(to: url, options: .atomic)+ #expect(await reader.lifecycleStates(for: [reference], now: later).first?.incompleteTailUnchangedSince == later)+ }++ @Test func unreadableTailClearsObservationAndRecoveryStartsAgain() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [context, start])+ try append(completion, to: url)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ _ = await reader.lifecycleStates(for: [reference], now: TestFixtures.now)+ try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: url.path)+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) }+ let unavailable = try #require(await reader.lifecycleStates(for: [reference], now: TestFixtures.now.addingTimeInterval(1)).first)+ #expect(unavailable.readStatus == .unavailable)+ #expect(unavailable.incompleteTailUnchangedSince == nil)++ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)+ let later = TestFixtures.now.addingTimeInterval(3600)+ #expect(await reader.lifecycleStates(for: [reference], now: later).first?.incompleteTailUnchangedSince == later)+ }++ @Test(arguments: ["missing-context", "read-gap", "known-terminal"])+ func incompleteTailRequiresContextWithoutOtherGapsOrTerminal(scenario: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let lines = switch scenario {+ case "missing-context": [start]+ case "read-gap": [context, start, "broken"]+ default: [context, start, completion]+ }+ let url = try writeRollout(in: directory, lines: lines)+ try append("{", to: url)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ for _ in 0 ..< 2 {+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .incomplete)+ #expect(state.incompleteTailUnchangedSince == nil)+ #expect(state.terminal == nil)+ }+ }+@Test func corruptGapBlocksInactivityButExplicitTerminalStillResolves() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -49,6 +144,46 @@ struct CodexSessionLifecycleReaderTests {#expect(resolved.terminal != nil)}+ @Test func lineLargerThanIncrementalBudgetContinuesAcrossReads() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [context, start])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ _ = await reader.lifecycleStates(for: [reference])++ let compacted = oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)+ try append(compacted + "\n" + completion + "\n", to: url)++ let partial = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(partial.readStatus == .incomplete)+ #expect(partial.terminal == nil)+ #expect(partial.incompleteTailUnchangedSince == nil)+ let resolved = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(resolved.readStatus == .complete)+ #expect(resolved.terminal != nil)+ }++ @Test func lineLargerThanBufferLimitIsSkippedWithoutBlockingTerminal() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [context, start])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ _ = await reader.lifecycleStates(for: [reference])++ let compacted = oversizedLine(type: "compacted", payloadByteCount: 17 * 1024 * 1024)+ try append(compacted + "\n" + completion + "\n", to: url)++ for _ in 0 ..< 2 {+ let partial = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(partial.readStatus == .incomplete)+ #expect(partial.terminal == nil)+ #expect(partial.incompleteTailUnchangedSince == nil)+ }+ let resolved = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(resolved.readStatus == .complete)+ #expect(resolved.terminal != nil)+ }+@Test func tokenUsageDoesNotResumeApprovalButAssistantOutputDoes() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -123,6 +258,10 @@ struct CodexSessionLifecycleReaderTests {"{\"type\":\"session_meta\",\"payload\":{\"id\":\"\(session)\",\"source\":\"cli\"}}"}+ private func oversizedLine(type: String, payloadByteCount: Int) -> String {+ "{\"type\":\"\(type)\",\"payload\":{\"data\":\"\(String(repeating: "x", count: payloadByteCount))\"}}"+ }+private func writeRollout(in directory: TestDirectory, lines: [String], session: String = "session-a") throws -> URL {let datePath = CodexDateFormat.dayString(from: TestFixtures.now).replacingOccurrences(of: "-", with: "/")return try directory.write(([metadata(session: session)] + lines).joined(separator: "\n") + "\n", to: "sessions/\(datePath)/rollout-test-session-a.jsonl")diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.mdindex 0ba063f..a61d082 100644--- a/Docs/DeveloperGuide/activity-monitor.md+++ b/Docs/DeveloperGuide/activity-monitor.md@@ -176,9 +176,13 @@ resume 可能继续很早以前创建的 session。快速路径找不到时,初始 cursor 从最后 512 KiB 开始并丢弃第一条可能不完整的行。缺少上下文、effort 或 reviewer 时,最多向前重放 8 MiB,统一恢复 turn 归属、元数据和进展。每个文件游标成功补读一次后停止回查,每轮最多补读一个 session。-每轮增量扫描总预算为 8 MiB,多个 session 轮转共享预算;待确认任务每轮最多查询 16 个。超过预算或尚未读到完整行时返回 `incomplete`,读取失败返回 `unavailable`,未找到文件返回 `notFound`。缓存可以保留已经观察到的事实,但不能替代本轮读取成功。成功读到固定上界且恢复了 turn 上下文时,`lifecycleCoverageCheckedAt` 记录本次检查时间;读取未完成、失败、文件不存在或缺少上下文时将其清空。只有该时间存在且距当前不足 5 秒的任务,才可以参与异常静默判定。+每轮增量扫描总预算为 8 MiB,多个 session 轮转共享预算;待确认任务每轮最多查询 16 个。超过预算或尚未读到完整行时返回 `incomplete`,读取失败返回 `unavailable`,未找到文件返回 `notFound`。缓存可以保留已经观察到的事实,但不能替代本轮读取成功。成功读到固定上界且恢复了 turn 上下文时,`lifecycleCoverageCheckedAt` 记录本次检查时间;读取未完成、失败、文件不存在或缺少上下文时将其清空。常规异常静默判定要求该时间存在且距当前不足 5 秒。-增量扫描按完整行推进 offset。遇到超过 8 MiB 的单行时,每轮在该行起点返回 `incomplete`,后续记录无法被消费。+增量扫描按实际读取字节推进 offset,并跨轮拼接未结束的行。每轮读取预算仍为 8 MiB,单行最多缓冲 16 MiB;超过缓冲上限时标记读取缺口并分块跳到换行,后续记录仍可继续消费。明确的 rollout 终态不受此前读取缺口影响。++文件可读且已经追到实际末尾,仅剩有界残缺末行时,reader 记录首次观察或最近一次追加的时间。任务已有 turn 上下文、没有其他覆盖缺口或已知终态,且本次观察距当前不足 5 秒时,可以使用残缺末行兜底:任务最后进展和末行最后增长均达到用户设置的静默阈值后,允许隐藏任务。末行继续增长会重新计时;读取失败、文件替换或截断、App 重启后重新开始观察。积压未读完、缺少上下文和超限丢弃中的行不能使用此兜底。++残缺末行始终返回 `incomplete`,观察结果用于保护计时、调度和隐藏前复核,不作为终态或进展,也不直接触发任务恢复。后续补完记录后,按正常完整读取流程处理进展和终态。rollout 坏行将当时尚未结束的 turn 标记为有覆盖缺口,后续重复的同一 turn 上下文不能清除此标记。新的 turn 独立建立覆盖,身份明确的完成或中断记录可以结束有缺口的任务;后续坏行不会撤销已经读到的明确终态。读取失败或尚未读完时,缓存进展不推进任务的执行时间,也不能恢复隐藏任务或清除保护记录。@@ -448,7 +452,7 @@ bootstrap 等待 rollout 期间如果恢复代次改变,会丢弃旧生命周- 唤醒恢复- Hook 数据源不可用- reader 正在更换-- 当前任务的 rollout 未读全、读取失败、上下文缺失或读取结果过期+- 当前任务的 rollout 未读全且不满足残缺末行兜底条件、读取失败、上下文缺失或读取结果过期### progress generation 的作用@@ -463,6 +467,8 @@ bootstrap 等待 rollout 期间如果恢复代次改变,会丢弃旧生命周通知返回或 3 秒 grace 到期时,四项都必须仍匹配才允许 suppress。任意新进展或阈值变化都会让旧尝试失效。+使用残缺末行兜底的候选还要复核末行观察的新鲜度和静默期限。末行继续增长或读取失败时取消尚未完成的隐藏尝试。+### 保护记录的保存顺序候选开始时同步更新内存记录,再由 Task 按顺序调用 `ActivityProtectionStateStore.apply`。磁盘写入失败会记录日志,不阻止任务隐藏。@@ -475,6 +481,8 @@ bootstrap 等待 rollout 期间如果恢复代次改变,会丢弃旧生命周阈值变长时,未超过新阈值的 suppressed 任务会静默恢复,并清除保护记录和通知;仍超过阈值的任务继续隐藏。+恢复与隐藏共用保护计时起点:取任务最后进展与已保留的残缺末行最后增长观察时间中的较晚者。调大阈值后的恢复不要求读取结果仍在 5 秒有效期内;再次隐藏仍须取得新鲜读取依据并达到新期限。+关闭防睡眠主开关会停用异常保护,并恢复当前进程内所有 suppressed 任务。## 保护状态持久化diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.mdindex 0b40966..a9c415e 100644--- a/Docs/en/DeveloperGuide/activity-monitor.md+++ b/Docs/en/DeveloperGuide/activity-monitor.md@@ -176,9 +176,13 @@ Live tasks need lifecycle near an active turn, not a full read of a long-runningIf 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.+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. Normal inactivity protection requires this timestamp to be present and less than five seconds old.-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.+The incremental scan advances its offset by bytes read and carries an unfinished line across cycles. The per-cycle read budget remains 8 MiB, while a single line may buffer up to 16 MiB. Larger lines mark a read gap and are skipped in chunks through their newline so later records remain consumable. An explicit rollout terminal remains authoritative despite an earlier read gap.++When the file is readable and scanning reaches its actual end with only a bounded partial line remaining, the reader records the first observation or latest append time. A task with turn context, no other coverage gap or known terminal, and an observation less than five seconds old may use a partial-tail fallback: both its last progress and the tail's last growth must be at least the configured inactivity threshold ago before suppression. Further growth restarts the timer. Read failures, file replacement or truncation, and app restarts require a new observation period. Unread backlog, missing context, and oversized lines being discarded do not qualify.++A partial tail always returns `incomplete`. Its observation affects protection timing, scheduling, and revalidation before hiding; it does not establish a terminal or progress, or directly restore a task. Once the line is completed, normal complete-read progress and terminal handling apply.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.@@ -448,6 +452,7 @@ Evaluation pauses during:- Wake recovery- Hook data-source unavailability- Reader replacement+- An incomplete rollout that does not qualify for the partial-tail fallback, a read failure, missing context, or an expired read result### Purpose of Progress Generation@@ -462,6 +467,8 @@ Every valid progress event increments `progressGeneration`. A protection candidaAll four must still match when notification returns or grace expires. Any new progress or threshold change invalidates the old attempt.+Candidates using the partial-tail fallback also revalidate observation freshness and the inactivity deadline. Further tail growth or a read failure cancels a pending suppression attempt.+### Protection Record Save OrderingAn attempt updates the in-memory record synchronously, then a task calls `ActivityProtectionStateStore.apply` in sequence. A disk-write failure is logged and does not prevent hiding the task.@@ -474,6 +481,8 @@ Shortening the threshold immediately reevaluates running tasks already past it.Increasing the threshold silently restores suppressed tasks that no longer exceed it and clears their records and notifications. Tasks still beyond the threshold remain hidden.+Restoration and suppression use the same timing reference: the later of task progress and the retained observation of the partial tail's last growth. Restoration after increasing the threshold does not require the read result to remain within its five-second validity window. Suppressing the task again still requires fresh read evidence and reaching the new deadline.+Turning off the sleep-prevention switch disables Activity Protection and restores all suppressed tasks in the current process.## Protection-State Persistence