CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 修复 rollout 回放遗漏任务终态与用量
Bobbab1d0d28ef5
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 996a4e7..5c2d84a 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -153,6 +153,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {private struct StatusIconState: Equatable {let usesErrorImage: Bool+ let ordinaryUsageAllowed: Bool?let progress: StatusIconProgress?let activity: CodexActivitySnapshot@@ -432,6 +433,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {.map { loadState, snapshot, selection, activity inStatusIconState(usesErrorImage: loadState.isError || snapshot?.hasTrustedData == false,+ ordinaryUsageAllowed: snapshot?.ordinaryUsageAllowed,progress: StatusIconProgress(snapshot: snapshot, selection: selection),activity: snapshot == nil ? .empty : activity)@@ -582,6 +584,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {statusItem.button?.toolTip = toolTipstatusIconPresentation.update(symbolName: state.symbolName(at: now),+ ordinaryUsageAllowed: state.ordinaryUsageAllowed,percent: state.progress?.percent,isStale: state.progress?.isStale ?? false,animated: animateddiff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swiftindex 6133b5e..04d5464 100644--- a/CodexBar/Models/CodexQuotaModels.swift+++ b/CodexBar/Models/CodexQuotaModels.swift@@ -15,6 +15,7 @@ nonisolated enum CodexPercentageFormat {nonisolated struct CodexQuotaSnapshot: Equatable {let account: CodexAccountlet planType: String?+ let ordinaryUsageAllowed: Bool?let credits: RateLimitCreditsSnapshot?let resetCreditsAvailableCount: Int?let resetCreditExpirationDates: [Date]?@@ -155,11 +156,13 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {/// app-server account/rateLimits 原始响应模型nonisolated struct AccountRateLimitsResponse: Decodable {+ let ordinaryUsageAllowed: Bool?let rateLimits: RateLimitSnapshotlet rateLimitsByLimitID: [String: RateLimitSnapshot]?let rateLimitResetCredits: RateLimitResetCreditsSummary?private enum CodingKeys: String, CodingKey {+ case ordinaryUsageAllowedcase rateLimitscase rateLimitsByLimitID = "rateLimitsByLimitId"case rateLimitResetCredits@@ -323,6 +326,7 @@ nonisolated extension CodexQuotaSnapshot {self.init(account: account,planType: rateLimitsResponse?.rateLimits.planType,+ ordinaryUsageAllowed: rateLimitsResponse?.ordinaryUsageAllowed,credits: rateLimitsResponse.flatMap { Self.primaryCredits(from: $0) },resetCreditsAvailableCount: rateLimitsResponse?.rateLimitResetCredits?.availableCount,resetCreditExpirationDates: resetCreditExpirationDates,diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swiftindex 0a35705..90ae150 100644--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift@@ -321,6 +321,7 @@ final class CodexActivityMonitor: ObservableObject {task: pending.task,key: key,abortFallback: pending.supersededAt,+ publishesEvents: !state.isHistoricalTerminal,into: &transitions)return true@@ -353,6 +354,7 @@ final class CodexActivityMonitor: ObservableObject {task: task,key: key,abortFallback: Date(),+ publishesEvents: !state.isHistoricalTerminal,into: &transitions)return truediff --git a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift b/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swiftindex 992fe17..08ca273 100644--- a/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift+++ b/CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift@@ -39,7 +39,7 @@ extension CodexActivityMonitor {tasks.removeValue(forKey: key)pendingTerminalTasks.removeValue(forKey: key)clearActivityProtection(for: key, taskID: task?.displayID, reason: .terminal)- storeTermination(+ let termination = storeTermination(for: key,projectName: event.projectDisplayName ?? task?.projectName,modelName: event.modelName ?? task?.modelName,@@ -48,6 +48,7 @@ extension CodexActivityMonitor {duration: task?.preciseDuration(until: event.timestamp),task: task)+ recordTerminalPresentationEvent(.terminated(termination))recordEndedTask(key, at: event.timestamp)if let resolved = task?.resolvedTurnKey {recordEndedTask(resolved, at: event.timestamp)@@ -83,6 +84,7 @@ extension CodexActivityMonitor {task: CodexActivityTask,key: CodexActivityTaskKey,abortFallback: Date,+ publishesEvents: Bool = true,into transitions: inout [CodexActivityTransition]) {clearActivityProtection(@@ -96,7 +98,10 @@ extension CodexActivityMonitor {switch terminal {case let .aborted(reportedAt):let terminatedAt = max(reportedAt ?? abortFallback, task.lastActivityAt)- storeTermination(task, at: terminatedAt, includesDuration: reportedAt != nil)+ let termination = storeTermination(task, at: terminatedAt, includesDuration: reportedAt != nil)+ if publishesEvents {+ recordTerminalPresentationEvent(.terminated(termination))+ }recordEndedTask(key, at: terminatedAt)if let resolved = task.resolvedTurnKey {recordEndedTask(resolved, at: terminatedAt)@@ -108,6 +113,8 @@ extension CodexActivityMonitor {completedAt: completedAt,reportedDuration: duration)+ guard publishesEvents else { return }+ recordTerminalPresentationEvent(.completed(completion))if canPublishActivityTransitions, !completion.isAnonymous,Date().timeIntervalSince(completion.completedAt) <= 10,let sessionTransitionNotBefore,@@ -164,7 +171,6 @@ extension CodexActivityMonitor {completions.append(completion)terminalTaskKeyByID[completion.id] = keyregisterTerminalTokenUsage(id: completion.id, key: key, task: task, endedAt: recordedCompletedAt)- recordTerminalPresentationEvent(.completed(completion))recordEndedTask(key, at: recordedCompletedAt)if let resolved = task.resolvedTurnKey {recordEndedTask(resolved, at: recordedCompletedAt)@@ -172,11 +178,11 @@ extension CodexActivityMonitor {return completion}- func storeTermination(+ private func storeTermination(_ task: CodexActivityTask,at terminatedAt: Date,includesDuration: Bool- ) {+ ) -> CodexActivityTermination {storeTermination(for: task.key,projectName: task.projectName,@@ -196,7 +202,7 @@ extension CodexActivityMonitor {terminatedAt: Date,duration: TimeInterval?,task: CodexActivityTask? = nil- ) {+ ) -> CodexActivityTermination {let termination = CodexActivityTermination(id: UUID(),isAnonymous: key.isAnonymous,@@ -209,7 +215,7 @@ extension CodexActivityMonitor {terminations.append(termination)terminalTaskKeyByID[termination.id] = keyregisterTerminalTokenUsage(id: termination.id, key: key, task: task, endedAt: terminatedAt)- recordTerminalPresentationEvent(.terminated(termination))+ return termination}func recordTerminalPresentationEvent(_ event: CodexActivityTerminalEvent) {diff --git a/CodexBar/Services/Workflow/CodexActivityTokenUsage.swift b/CodexBar/Services/Workflow/CodexActivityTokenUsage.swiftindex a886581..410b7a6 100644--- a/CodexBar/Services/Workflow/CodexActivityTokenUsage.swift+++ b/CodexBar/Services/Workflow/CodexActivityTokenUsage.swift@@ -101,7 +101,11 @@ extension CodexActivityMonitor {terminalTokenUsageRequests[id] = requestreferences.formUnion(request.references)}- return Array(references)+ return references.map {+ var reference = $0+ reference.isTerminalUsageOnly = true+ return reference+ }}@discardableResultdiff --git a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swiftindex e915c31..f30ac96 100644--- a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift+++ b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift@@ -5,6 +5,7 @@ nonisolated struct CodexActivityTurnReference: Hashable {let threadID: Stringlet turnID: Stringlet startedAt: Date+ var isTerminalUsageOnly = falsestatic func == (lhs: Self, rhs: Self) -> Bool {lhs.threadID == rhs.threadID && lhs.turnID == rhs.turnID@@ -38,36 +39,41 @@ actor CodexSessionLifecycleReader {cursorsByThread = cursorsByThread.filter { $0.value.lastReadAt > cutoff }lastResolutionAttemptByThread = lastResolutionAttemptByThread.filter { $0.value > cutoff }lastRecursiveAttemptByThread = lastRecursiveAttemptByThread.filter { $0.value > cutoff }- var budget = Self.contextByteLimit- var performedBackfill = false+ var budget = Self.readByteLimitvar states: [CodexSessionTaskLifecycleState] = []let threadIDs = grouped.keys.sorted()let start = threadIDs.isEmpty ? 0 : roundRobinOffset % threadIDs.countlet ordered = Array(threadIDs.dropFirst(start)) + Array(threadIDs.prefix(start))roundRobinOffset = threadIDs.isEmpty ? 0 : (start + 1) % threadIDs.countfor threadID in ordered {+ guard !Task.isCancelled else { return [] }guard let threadReferences = grouped[threadID],let latest = threadReferences.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), now: now)+ let needsHistory = threadReferences.contains { cursor.historyReadLimit(for: $0) > 0 }+ let tailLimit = needsHistory ? Self.readByteLimit / 2 : Self.readByteLimit+ status = scan(into: &cursor, limit: min(tailLimit, budget), now: now)+ budget -= min(budget, cursor.lastReadByteCount)if cursor.metadata?.id != threadID {status = .unavailable}- budget -= min(budget, cursor.lastReadByteCount)- let needsContext = threadReferences.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.prepareSupplementalHistory(for: threadReferences, now: now)+ let historyLimit = threadReferences.map { cursor.historyReadLimit(for: $0) }.max() ?? 0+ if status != .unavailable, budget > 0, historyLimit > 0 {+ if !backfillHistory(into: &cursor, limit: historyLimit, budget: &budget) {+ status = .unavailable+ }}+ guard !Task.isCancelled else { return [] }cursor.lastReadAt = nowlet referencedTurns = Set(threadReferences.map(\.turnID))cursor.lifecycleByTurnID = cursor.lifecycleByTurnID.filter {referencedTurns.contains($0.key) || ($0.value.lastProgressAt ?? .distantPast) > cutoff+ || (cursor.supplementalHistoryByTurn[$0.key]?.lastRequestedAt ?? .distantPast) > cutoff+ }+ cursor.supplementalHistoryByTurn = cursor.supplementalHistoryByTurn.filter {+ $0.value.lastRequestedAt > cutoff}cursorsByThread[threadID] = cursor}@@ -75,8 +81,15 @@ actor CodexSessionLifecycleReader {for reference in threadReferences {let known = cursor?.lifecycleByTurnID[reference.turnID]let hasReadGap = known?.hasReadGap ?? (cursor?.hasDecodeFailures == true)- let turnStatus: CodexSessionReadStatus = status == .complete && hasReadGap && known?.terminal == nil- ? .incomplete : status+ let hasHistoryGap = cursor?.hasHistoryGap(for: reference.turnID) == true+ let turnStatus: CodexSessionReadStatus = if status == .unavailable || status == .notFound {+ status+ } else if known?.terminal != nil {+ // 明确终态不依赖文件尾部另一条记录是否已写完+ .complete+ } else {+ hasReadGap || hasHistoryGap ? .incomplete : status+ }states.append(CodexSessionTaskLifecycleState(requestedThreadID: threadID, turnID: reference.turnID, startedAt: known?.startedAt,approvalReviewer: known?.approvalReviewer, effort: known?.effort,@@ -88,9 +101,10 @@ actor CodexSessionLifecycleReader {rootSessionID: cursor?.metadata?.sessionID,parentThreadID: cursor?.metadata?.parentThreadID,lastExecutionProgressAt: known?.lastExecutionProgressAt,- incompleteTailUnchangedSince: status == .incomplete && !hasReadGap && known?.hasContext == true && known?.terminal == nil+ incompleteTailUnchangedSince: status == .incomplete && !hasReadGap && !hasHistoryGap && known?.hasContext == true && known?.terminal == nil? cursor?.incompleteTailUnchangedSince : nil,- tokenUsage: turnStatus == .complete ? known?.tokenUsage : nil+ tokenUsage: turnStatus == .complete && status == .complete ? known?.tokenUsage : nil,+ isHistoricalTerminal: known?.isHistoricalTerminal == true))}}@@ -165,31 +179,49 @@ actor CodexSessionLifecycleReader {let size = stat?.size ?? 0let offset = size > Self.bootstrapByteLimit ? size - Self.bootstrapByteLimit : 0return SessionFileCursor(- url: url, fileIdentifier: stat?.identifier, offset: offset, historicalOffset: offset,+ url: url, fileIdentifier: stat?.identifier, offset: offset,isDiscardingLine: offset > 0,- metadata: WorkflowRolloutMetadataReader.metadata(transcriptPath: url.path)+ metadata: WorkflowRolloutMetadataReader.metadata(transcriptPath: url.path),+ history: offset > 0 ? SessionHistoryCursor(offset: size, contextLookupOffset: offset) : nil,+ initialContextOffset: offset > 0 ? offset : nil,+ bootstrapEnd: offset > 0 ? size : nil)}- 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,- isDiscardingLine: start > 0,- metadata: cursor.metadata- )- let status = scan(into: &restored, limit: Self.contextByteLimit, through: end)- guard status == .complete else { return status }- restored.didBackfill = true- cursor = restored- return .complete+ private func backfillHistory(into cursor: inout SessionFileCursor, limit: Int, budget: inout Int) -> Bool {+ guard var history = cursor.history, history.offset > 0 else { return true }+ guard let before = WorkflowStorage.fileStat(at: cursor.url),+ before.identifier == cursor.fileIdentifier, before.size >= cursor.offset,+ let handle = try? FileHandle(forReadingFrom: cursor.url) else { return false }+ defer { try? handle.close() }+ let count = min(limit, budget, Int(history.offset))+ let start = history.offset - UInt64(count)+ guard (try? handle.seek(toOffset: start)) != nil,+ let data = try? handle.read(upToCount: count) else { return false }+ budget -= data.count+ // 短读或后置检查失败前实际读到的字节也计入补查预算+ cursor.totalHistoryBytesRead += UInt64(data.count)+ guard data.count == count else { return false }+ history.offset = start+ history.consume(data, file: cursor, maximumBufferedLineByteCount: Self.maximumBufferedLineByteCount)+ guard let after = WorkflowStorage.fileStat(at: cursor.url),+ after.identifier == before.identifier, after.size >= before.size else { return false }+ for (turnID, earlier) in history.lifecycleByTurnID {+ var latest = cursor.lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()+ if latest.terminal == nil, earlier.terminal != nil {+ latest.isHistoricalTerminal = true+ }+ latest.mergeEarlier(earlier)+ cursor.lifecycleByTurnID[turnID] = latest+ }+ cursor.restoreInitialContext(from: history)+ // 已合并的事实留在主游标, 回读只保留跨块半行和待定位的进展+ history.lifecycleByTurnID.removeAll(keepingCapacity: true)+ cursor.history = history+ return true}- private func scan(into cursor: inout SessionFileCursor, limit: Int, through upperBound: UInt64? = nil, now: Date = Date()) -> CodexSessionReadStatus {+ private func scan(into cursor: inout SessionFileCursor, limit: Int, now: Date = Date()) -> CodexSessionReadStatus {cursor.lastReadByteCount = 0var previousTailUnchangedSince = cursor.incompleteTailUnchangedSincecursor.incompleteTailUnchangedSince = nil@@ -198,7 +230,7 @@ actor CodexSessionLifecycleReader {cursor = initialCursor(for: cursor.url)previousTailUnchangedSince = nil}- let end = min(stat.size, upperBound ?? stat.size)+ let end = stat.sizeguard let handle = try? FileHandle(forReadingFrom: cursor.url) else { return .unavailable }defer { try? handle.close() }if end > cursor.offset {@@ -220,39 +252,115 @@ actor CodexSessionLifecycleReader {}private static let bootstrapByteLimit: UInt64 = 512 * 1024- private static let incrementalByteLimit = 8 * 1024 * 1024- private static let contextByteLimit = 8 * 1024 * 1024+ private static let readByteLimit = 8 * 1024 * 1024private static let maximumBufferedLineByteCount = 16 * 1024 * 1024}+private nonisolated struct SessionSupplementalHistoryRead {+ let initialHistoryBytesRead: UInt64+ var lastRequestedAt: Date+}+private nonisolated struct SessionFileCursor {let url: URLvar fileIdentifier: UInt64?var offset: UInt64- let historicalOffset: UInt64var isDiscardingLine: Boolvar metadata: WorkflowRolloutMetadataPayload?var currentTurnID: String?+ var hasTurnBoundary = falsevar lifecycleByTurnID: [String: SessionTurnLifecycle] = [:]+ var supplementalHistoryByTurn: [String: SessionSupplementalHistoryRead] = [:]+ var totalHistoryBytesRead: UInt64 = 0var partialLineData = Data()- var didBackfill = false- var hasDecodeFailures = false+ var history: SessionHistoryCursor?+ var initialContextOffset: UInt64?+ private var pendingInitialProgress = SessionTurnLifecycle()+ private var initialProgressBeforeTerminal: [String: SessionTurnLifecycle] = [:]+ var bootstrapEnd: UInt64?+ private(set) var lastReadGapOffset: UInt64?var lastReadAt = Date()var lastReadByteCount = 0var incompleteTailUnchangedSince: Date?+ var hasDecodeFailures: Bool {+ lastReadGapOffset != nil+ }+var hasPartialLine: Bool {isDiscardingLine || !partialLineData.isEmpty}+ private var hasPendingInitialProgress: Bool {+ initialContextOffset != nil && pendingInitialProgress.lastProgressAt != nil+ }++ func hasHistoryGap(for turnID: String) -> Bool {+ let hasStart = lifecycleByTurnID[turnID]?.startedAt != nil+ return (hasPendingInitialProgress && !hasStart)+ || history.map { $0.requiresLeadingLineRecovery || ($0.offset > 0 && (!hasStart || hasPendingInitialProgress)) } == true+ }++ func historyReadLimit(for reference: CodexActivityTurnReference) -> Int {+ guard history.map({ $0.offset > 0 }) == true else { return 0 }+ let known = lifecycleByTurnID[reference.turnID]+ if known?.terminal == nil, !reference.isTerminalUsageOnly {+ let needsHistory = hasPendingInitialProgress || history?.requiresLeadingLineRecovery == true+ || known?.startedAt == nil || known?.hasContext != true+ || known?.effort == nil || known?.approvalReviewer == nil+ return needsHistory ? Int.max : 0+ }+ guard known?.terminal == nil || known?.rootTurnID == nil || known?.hasTokenUsageRecord != true else { return 0 }+ let initialBytes = supplementalHistoryByTurn[reference.turnID]?.initialHistoryBytesRead ?? totalHistoryBytesRead+ let consumedBytes = min(UInt64(Self.supplementalHistoryByteLimit), totalHistoryBytesRead - initialBytes)+ return Self.supplementalHistoryByteLimit - Int(consumedBytes)+ }++ mutating func prepareSupplementalHistory(for references: [CodexActivityTurnReference], now: Date) {+ let initial = SessionSupplementalHistoryRead(initialHistoryBytesRead: totalHistoryBytesRead, lastRequestedAt: now)+ for reference in references where reference.isTerminalUsageOnly || lifecycleByTurnID[reference.turnID]?.terminal != nil {+ supplementalHistoryByTurn[reference.turnID, default: initial].lastRequestedAt = now+ }+ }++ private static let supplementalHistoryByteLimit = 32 * 1024 * 1024++ mutating func restoreInitialContext(from history: SessionHistoryCursor) {+ guard initialContextOffset != nil, history.hasInitialTurnBoundary, !history.initialContextHasReadGap else { return }+ if let turnID = history.initialTurnID {+ var state = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()+ state.mergeEarlier(initialProgressBeforeTerminal[turnID] ?? pendingInitialProgress)+ lifecycleByTurnID[turnID] = state+ }+ pendingInitialProgress = SessionTurnLifecycle()+ initialContextOffset = nil+ // 尾部可能已进入下一轮, 补查只给启动片段补归属, 不回退当前轮次+ if !hasTurnBoundary {+ currentTurnID = history.initialTurnID.flatMap { initialProgressBeforeTerminal[$0] == nil ? $0 : nil }+ hasTurnBoundary = true+ }+ initialProgressBeforeTerminal.removeAll()+ }+/// 读取预算可以在一行中间结束, 游标仍需推进并在下一轮继续拼接/// 超过缓冲上限后只扫描到换行, 避免异常大行阻塞后续终态mutating func consume(_ data: Data, maximumBufferedLineByteCount: Int) {var fragmentStart = data.startIndexwhile let newline = data[fragmentStart...].firstIndex(of: JSONLines.newlineByte) {+ if isDiscardingLine, let bootstrapEnd {+ let lineEnd = offset - UInt64(data.count) + UInt64(newline + 1)+ self.bootstrapEnd = nil+ // 启动时跨过的半行后来才写完, 重新定位这一行以免正反两路都跳过它+ if lineEnd > bootstrapEnd {+ history = SessionHistoryCursor(+ offset: lineEnd, contextLookupOffset: initialContextOffset, requiresLeadingLineRecovery: true+ )+ }+ }consumeLineFragment(data[fragmentStart ..< newline],completesLine: true,+ endingAt: offset - UInt64(data.count) + UInt64(newline + 1),maximumBufferedLineByteCount: maximumBufferedLineByteCount)fragmentStart = data.index(after: newline)@@ -261,6 +369,7 @@ private nonisolated struct SessionFileCursor {consumeLineFragment(data[fragmentStart...],completesLine: false,+ endingAt: offset,maximumBufferedLineByteCount: maximumBufferedLineByteCount)}@@ -269,6 +378,7 @@ private nonisolated struct SessionFileCursor {private mutating func consumeLineFragment(_ fragment: Data.SubSequence,completesLine: Bool,+ endingAt: UInt64,maximumBufferedLineByteCount: Int) {if isDiscardingLine {@@ -280,7 +390,7 @@ private nonisolated struct SessionFileCursor {guard fragment.count <= maximumBufferedLineByteCount - partialLineData.count else {partialLineData.removeAll(keepingCapacity: false)- markReadGap()+ markReadGap(at: endingAt)isDiscardingLine = !completesLinereturn}@@ -290,37 +400,48 @@ private nonisolated struct SessionFileCursor {let keepsCapacity = partialLineData.count <= Self.retainedLineCapacityByteLimitdefer { partialLineData.removeAll(keepingCapacity: keepsCapacity) }- let decoded = JSONLines.decodeWithFailures(CodexRolloutLineEnvelope.self, from: partialLineData)- if decoded.failedLineCount > 0 {- markReadGap()+ applyCompleteLine(partialLineData, endingAt: endingAt)+ }++ @discardableResult+ mutating func applyCompleteLine(_ data: Data, endingAt: UInt64) -> CodexRolloutLineEnvelope? {+ guard !JSONLines.isBlankLine(data) else { return nil }+ let decoder = JSONDecoder()+ guard let envelope = try? decoder.decode(CodexRolloutLineEnvelope.self, from: data) else {+ markReadGap(at: endingAt)+ return nil}- for envelope in decoded.values {- apply(envelope)- if envelope.type == "token_usage_record", let turnID = envelope.payload?.turnID {- // 用量字段损坏不能影响生命周期解码, 也不能沿用上一条累计值- var state = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()- state.tokenUsage = nil- if let record = try? JSONDecoder().decode(CodexRolloutTokenUsageRecord.self, from: partialLineData).payload,- record.threadID == metadata?.id,- record.sessionID == (metadata?.sessionID ?? metadata?.id),- !record.responseID.isEmpty, !record.rootTurnID.isEmpty,- !turnID.isEmpty, record.turnTokenUsage.isValid {- state.tokenUsage = record.turnTokenUsage- state.rootTurnID = record.rootTurnID- }- lifecycleByTurnID[turnID] = state+ apply(envelope)+ if envelope.type == "token_usage_record", let turnID = envelope.payload?.turnID {+ // 用量字段损坏不能影响生命周期解码, 也不能沿用上一条累计值+ var state = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()+ state.tokenUsage = nil+ state.hasTokenUsageRecord = true+ if let record = try? decoder.decode(CodexRolloutTokenUsageRecord.self, from: data).payload,+ record.threadID == metadata?.id,+ record.sessionID == (metadata?.sessionID ?? metadata?.id),+ !record.responseID.isEmpty, !record.rootTurnID.isEmpty,+ !turnID.isEmpty, record.turnTokenUsage.isValid {+ state.tokenUsage = record.turnTokenUsage+ state.rootTurnID = record.rootTurnID}+ lifecycleByTurnID[turnID] = state}+ return envelope}private static let retainedLineCapacityByteLimit = 512 * 1024/// 损坏可能遮住 turn 边界, 只保留已明确结束的事实, 后续新 turn 独立建立覆盖- mutating func markReadGap() {- hasDecodeFailures = true+ mutating func markReadGap(at offset: UInt64) {+ lastReadGapOffset = offsetcurrentTurnID = nil+ hasTurnBoundary = true+ pendingInitialProgress = SessionTurnLifecycle()+ initialProgressBeforeTerminal.removeAll()for turnID in lifecycleByTurnID.keys {lifecycleByTurnID[turnID]?.tokenUsage = nil+ lifecycleByTurnID[turnID]?.hasTokenUsageRecord = trueif lifecycleByTurnID[turnID]?.terminal == nil {lifecycleByTurnID[turnID]?.hasReadGap = true}@@ -328,7 +449,13 @@ private nonisolated struct SessionFileCursor {}mutating func apply(_ envelope: CodexRolloutLineEnvelope) {+ if envelope.endsTurnContext, !hasTurnBoundary, initialContextOffset != nil,+ let turnID = envelope.payload?.turnID, !turnID.isEmpty, initialProgressBeforeTerminal[turnID] == nil {+ // 起始归属尚未恢复, 先保留各轮次结束前的进展, 不让迟到终态截断其他轮次+ initialProgressBeforeTerminal[turnID] = pendingInitialProgress+ }if envelope.startsTurnContext {+ hasTurnBoundary = truecurrentTurnID = envelope.payload?.turnID.flatMap { $0.isEmpty ? nil : $0 }if let turnID = currentTurnID, let rootTurnID = envelope.payload?.rootTurnID, !rootTurnID.isEmpty {var state = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()@@ -338,6 +465,9 @@ private nonisolated struct SessionFileCursor {}if let event = envelope.progressEvent(currentTurnID: currentTurnID) {apply(event)+ } else if !hasTurnBoundary, initialContextOffset != nil, let progress = envelope.unassignedProgress {+ // 只暂存启动片段的进展时间, 首个轮次边界之后按新上下文正常处理+ pendingInitialProgress.apply(progress)}if let event = envelope.lifecycleEvent {apply(event)@@ -359,6 +489,119 @@ private nonisolated struct SessionFileCursor {}}+/// 从启动时的文件末尾向前读, 每个完整行只在回读链路中解析一次+private nonisolated struct SessionHistoryCursor {+ var offset: UInt64+ var contextLookupOffset: UInt64?+ var requiresLeadingLineRecovery = false+ private var hasSkippedTail = false+ var lifecycleByTurnID: [String: SessionTurnLifecycle] = [:]+ private var partialLineData = Data()+ // 第一段可能是尚未落盘完整的尾行, 由正向游标继续跟踪+ private var isDiscardingLine = true+ private var hasDecodeFailures = false+ private var pendingProgress = SessionTurnLifecycle()+ private var progressAfterTerminals: [(turnID: String, progress: SessionTurnLifecycle)] = []+ private var initialEndedTurnIDs: Set<String> = []+ private(set) var hasInitialTurnBoundary = false+ private(set) var initialTurnID: String?+ private(set) var initialContextHasReadGap = false++ mutating func consume(_ data: Data, file: SessionFileCursor, maximumBufferedLineByteCount: Int) {+ var end = data.endIndex+ while let newline = data[..<end].lastIndex(of: JSONLines.newlineByte) {+ prepend(data[(newline + 1) ..< end], maximumBufferedLineByteCount: maximumBufferedLineByteCount)+ finishLine(file: file, lineStart: offset + UInt64(newline + 1))+ end = newline+ }+ prepend(data[..<end], maximumBufferedLineByteCount: maximumBufferedLineByteCount)+ if offset == 0 {+ finishLine(file: file, lineStart: 0)+ }+ }++ private mutating func prepend(_ fragment: Data.SubSequence, maximumBufferedLineByteCount: Int) {+ guard !isDiscardingLine else { return }+ guard fragment.count <= maximumBufferedLineByteCount - partialLineData.count else {+ partialLineData.removeAll(keepingCapacity: false)+ isDiscardingLine = true+ hasDecodeFailures = true+ pendingProgress = SessionTurnLifecycle()+ progressAfterTerminals.removeAll()+ return+ }+ partialLineData = Data(fragment) + partialLineData+ }++ private mutating func finishLine(file: SessionFileCursor, lineStart: UInt64) {+ if hasSkippedTail {+ requiresLeadingLineRecovery = false+ }+ hasSkippedTail = true+ defer {+ partialLineData.removeAll(keepingCapacity: false)+ isDiscardingLine = false+ }+ guard !isDiscardingLine, !partialLineData.isEmpty else { return }+ var earlier = SessionFileCursor(+ url: file.url, fileIdentifier: file.fileIdentifier, offset: 0,+ isDiscardingLine: false, metadata: file.metadata+ )+ let envelope = earlier.applyCompleteLine(partialLineData, endingAt: lineStart + UInt64(partialLineData.count))+ if earlier.hasDecodeFailures {+ hasDecodeFailures = true+ pendingProgress = SessionTurnLifecycle()+ progressAfterTerminals.removeAll()+ }+ if let envelope {+ if !hasInitialTurnBoundary, let contextLookupOffset, lineStart <= contextLookupOffset {+ if envelope.endsTurnContext, let turnID = envelope.payload?.turnID, !turnID.isEmpty {+ initialEndedTurnIDs.insert(turnID)+ }+ if envelope.startsTurnContext {+ hasInitialTurnBoundary = true+ initialContextHasReadGap = hasDecodeFailures+ initialTurnID = envelope.payload?.turnID.flatMap { $0.isEmpty || initialEndedTurnIDs.contains($0) ? nil : $0 }+ initialEndedTurnIDs.removeAll()+ }+ }+ if envelope.endsTurnContext, let turnID = envelope.payload?.turnID, !turnID.isEmpty {+ progressAfterTerminals.append((turnID, pendingProgress))+ pendingProgress = SessionTurnLifecycle()+ }+ if envelope.startsTurnContext {+ if let turnID = envelope.payload?.turnID, !turnID.isEmpty {+ var state = earlier.lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()+ state.mergeEarlier(pendingProgress)+ // 反向读到开始边界后才确定归属, 只排除该轮次自身结束后的进展+ for segment in progressAfterTerminals.reversed() {+ guard segment.turnID != turnID else { break }+ state.mergeEarlier(segment.progress)+ }+ earlier.lifecycleByTurnID[turnID] = state+ }+ pendingProgress = SessionTurnLifecycle()+ progressAfterTerminals.removeAll()+ }+ // 没有显式轮次的进展, 遇到更早的上下文边界后才能确定归属+ if let progress = envelope.unassignedProgress {+ pendingProgress.apply(progress)+ }+ }+ for (turnID, var state) in earlier.lifecycleByTurnID {+ // 正向新增的坏行可能不在历史快照中, 按位置保留跨过该缺口的轮次状态+ if hasDecodeFailures || file.lastReadGapOffset.map({ lineStart < $0 }) == true {+ state.hasReadGap = true+ state.tokenUsage = nil+ state.hasTokenUsageRecord = true+ }+ var latest = lifecycleByTurnID[turnID] ?? SessionTurnLifecycle()+ latest.mergeEarlier(state)+ lifecycleByTurnID[turnID] = latest+ }+ }+}+// MARK: - rollout 行解码/// Codex rollout JSONL 单行的共享解码模型@@ -420,6 +663,20 @@ private nonisolated extension CodexRolloutLineEnvelope {}func progressEvent(currentTurnID: String?) -> SessionLifecycleEvent? {+ guard let turnID = explicitProgressTurnID ?? currentTurnID, !turnID.isEmpty,+ let change = progressChange else { return nil }+ return SessionLifecycleEvent(turnID: turnID, change: change)+ }++ var unassignedProgress: SessionLifecycleChange? {+ explicitProgressTurnID == nil ? progressChange : nil+ }++ private var explicitProgressTurnID: String? {+ type == "response_item" ? payload?.messageMetadata?.turnID : payload?.turnID+ }++ private var progressChange: SessionLifecycleChange? {let progressTypes: Set = ["token_count", "item_completed", "agent_message", "agent_reasoning","task_started", "turn_started", "task_complete", "turn_complete", "turn_aborted"@@ -435,16 +692,12 @@ private nonisolated extension CodexRolloutLineEnvelope {return nil}- let explicitTurnID = type == "response_item" ? payload?.messageMetadata?.turnID : payload?.turnID- guard let turnID = explicitTurnID ?? currentTurnID, !turnID.isEmpty else {- return nil- }let isExecutionProgress = if type == "response_item" {payload?.role == "assistant" || ["function_call_output", "custom_tool_call_output", "tool_search_output"].contains(payload?.type ?? "")} else {type == "event_msg" && ["agent_message", "agent_reasoning"].contains(payload?.type ?? "")}- return SessionLifecycleEvent(turnID: turnID, change: .progress(at: eventDate, resumesApproval: isExecutionProgress))+ return .progress(at: eventDate, resumesApproval: isExecutionProgress)}var lifecycleEvent: SessionLifecycleEvent? {@@ -520,6 +773,8 @@ private nonisolated enum SessionLifecycleChange {private nonisolated struct SessionTurnLifecycle {var tokenUsage: CodexTokenUsage?+ var hasTokenUsageRecord = false+ var isHistoricalTerminal = falsevar rootTurnID: String?var hasReadGap = falsevar contextObservedAt: Date?@@ -531,6 +786,29 @@ private nonisolated struct SessionTurnLifecycle {var lastExecutionProgressAt: Date?var terminal: CodexSessionTaskTerminalState?+ mutating func mergeEarlier(_ earlier: Self) {+ hasReadGap = hasReadGap || earlier.hasReadGap+ hasContext = hasContext || earlier.hasContext+ if let start = earlier.startedAt {+ startedAt = min(startedAt ?? start, start)+ }+ approvalReviewer = approvalReviewer ?? earlier.approvalReviewer+ effort = effort ?? earlier.effort+ contextObservedAt = contextObservedAt ?? earlier.contextObservedAt+ rootTurnID = rootTurnID ?? earlier.rootTurnID+ terminal = terminal ?? earlier.terminal+ if let progress = earlier.lastProgressAt {+ lastProgressAt = max(lastProgressAt ?? progress, progress)+ }+ if let progress = earlier.lastExecutionProgressAt {+ lastExecutionProgressAt = max(lastExecutionProgressAt ?? progress, progress)+ }+ if !hasTokenUsageRecord {+ tokenUsage = earlier.tokenUsage+ hasTokenUsageRecord = earlier.hasTokenUsageRecord+ }+ }+mutating func apply(_ change: SessionLifecycleChange) {switch change {case let .progress(at, resumesApproval):@@ -575,6 +853,7 @@ nonisolated struct CodexSessionTaskLifecycleState {var lastExecutionProgressAt: Date?var incompleteTailUnchangedSince: Date?var tokenUsage: CodexTokenUsage?+ var isHistoricalTerminal = false}nonisolated enum CodexSessionReadStatus {diff --git a/CodexBar/Services/Workflow/JSONLines.swift b/CodexBar/Services/Workflow/JSONLines.swiftindex 55a6614..a34a04d 100644--- a/CodexBar/Services/Workflow/JSONLines.swift+++ b/CodexBar/Services/Workflow/JSONLines.swift@@ -7,6 +7,10 @@ nonisolated enum JSONLines {/// RFC 8259 允许出现在值前后的空白, 用于识别只含空白的空行private static let jsonWhitespaceBytes: Set<UInt8> = [0x20, 0x09, 0x0A, 0x0D]+ static func isBlankLine(_ data: Data) -> Bool {+ !data.contains(where: { !jsonWhitespaceBytes.contains($0) })+ }+/// 落盘 JSON 统一的稳定输出配置, 保证文件可 diff 且格式一致/// 配置后不再修改, encode 可重入, 可跨并发域缓存共享static let stableEncoder: JSONEncoder = {@@ -44,7 +48,7 @@ nonisolated enum JSONLines {// 直接把字节切片交给 JSONDecoder: 它自己跳过首尾空白并拒收非法 UTF-8,// 省掉每行 String 转换 + trim + 再编码回 Data 的三次拷贝 (单次读取可达上万行)for line in data.split(separator: newlineByte) {- guard line.contains(where: { !Self.jsonWhitespaceBytes.contains($0) }) else {+ guard !isBlankLine(line) else {continue}guard let value = try? decoder.decode(T.self, from: Data(line)) else {diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swiftindex 24e687c..ba52ac2 100644--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift@@ -64,18 +64,23 @@ struct AccountCard: View {private static func planBadgeTint(for plan: String, colorScheme: ColorScheme) -> Color {let normalizedPlan = plan.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()- let colors = planTintRules.first { rule in- rule.keywords.contains { normalizedPlan.contains($0) }- }?.colors ?? (light: 0x0E7490, dark: 0x67E8F9)+ let colors = planTints.first { $0.plans.contains(normalizedPlan) }?.colors+ ?? (light: 0x69717A, dark: 0xB1B7C0)return Color(hex: colorScheme == .dark ? colors.dark : colors.light)}- private static let planTintRules: [(keywords: [String], colors: (light: Int, dark: Int))] = [- (["enterprise"], (0x52677F, 0xA7AFBA)),- (["team", "business", "pro"], (0x147B82, 0x82B3B5)),- (["plus"], (0x256FA3, 0x89A9C2)),- (["edu"], (0x9B5F12, 0xC7A96B)),- (["free"], (0x167A5E, 0x7FB5A4))+ /// 按完整套餐名归入产品系列, 避免复合名称被其他系列匹配+ private static let planTints: [(plans: [String], colors: (light: Int, dark: Int))] = [+ (["free"], (0x527566, 0xA3C8B5)),+ (["go"], (0x237D72, 0x77C9B6)),+ (["plus"], (0x366FA8, 0x8FBCEB)),+ (["prolite"], (0x6676AF, 0xB0BCEB)),+ (["pro"], (0x8055AB, 0xC5A5E8)),+ (["promax"], (0x986B2F, 0xE2BF7F)),+ (["team"], (0x287D94, 0x83C9DC)),+ (["business", "self_serve_business_prolite", "self_serve_business_usage_based"], (0xA1654B, 0xDDAF95)),+ (["enterprise", "ent26", "enterprise_cbp_automation", "enterprise_cbp_usage_based"], (0x566780, 0xAABBD5)),+ (["edu", "edu_plus", "edu_pro"], (0xA0567C, 0xDEABC9))]}diff --git a/CodexBar/Views/Menu/StatusItemIconView.swift b/CodexBar/Views/Menu/StatusItemIconView.swiftindex 52bc8e3..dc3680b 100644--- a/CodexBar/Views/Menu/StatusItemIconView.swift+++ b/CodexBar/Views/Menu/StatusItemIconView.swift@@ -5,6 +5,7 @@ import SwiftUIfinal class StatusItemIconPresentation: ObservableObject {struct State: Equatable {var symbolName = "person.fill"+ var isOrdinaryUsageRestricted = falsevar remainingPercent = 0var showsQuota = falsevar isStale = false@@ -12,9 +13,10 @@ final class StatusItemIconPresentation: ObservableObject {@Published private(set) var state = State()- func update(symbolName: String, percent: Int?, isStale: Bool, animated: Bool) {+ func update(symbolName: String, ordinaryUsageAllowed: Bool?, percent: Int?, isStale: Bool, animated: Bool) {let next = State(symbolName: symbolName,+ isOrdinaryUsageRestricted: ordinaryUsageAllowed == false,remainingPercent: percent.map { min(max($0, 0), 100) } ?? state.remainingPercent,showsQuota: percent != nil,isStale: percent == nil ? state.isStale : isStale@@ -42,6 +44,7 @@ final class StatusItemIconHostingView: NSHostingView<StatusItemIconView> {struct StatusItemIconView: View {@ObservedObject var presentation: StatusItemIconPresentation@Environment(\.displayScale) private var displayScale+ @Environment(\.colorScheme) private var colorSchemestatic let size = NSSize(width: 26, height: 22)private static var symbolImages: [String: [CGFloat: CGImage]] = [:]@@ -73,6 +76,7 @@ struct StatusItemIconView: View {anchor: UnitPoint(x: 0.5, y: 18.0 / 22.0))))}+ .foregroundStyle(symbolColor).animation(.easeInOut(duration: 0.2), value: state.symbolName).scaleEffect(state.showsQuota ? 1 : 16.0 / 14.0,@@ -88,16 +92,19 @@ struct StatusItemIconView: View {.allowsHitTesting(false)}+ private var symbolColor: Color {+ guard presentation.state.isOrdinaryUsageRestricted else { return .primary }+ return Color(hex: colorScheme == .dark ? 0xE8B27C : 0xD99858)+ }+@ViewBuilderprivate func symbolImage(named name: String) -> some View {let scale = ceil(max(displayScale, 1) * 16 / 14)if let image = Self.rasterizedSymbol(named: name, displayScale: displayScale, scale: scale) {Image(decorative: image, scale: scale).renderingMode(.template)- .foregroundStyle(.primary)} else {Self.symbolContent(named: name)- .foregroundStyle(.primary)}}diff --git a/CodexBarTests/CodexActivityTokenUsageTests.swift b/CodexBarTests/CodexActivityTokenUsageTests.swiftindex e82d72e..7809555 100644--- a/CodexBarTests/CodexActivityTokenUsageTests.swift+++ b/CodexBarTests/CodexActivityTokenUsageTests.swift@@ -206,6 +206,13 @@ struct CodexActivityTokenUsageTests {stopped.readStatus = .unavailable#expect(!monitor.applyTerminalTokenUsage([stopped]))#expect(monitor.terminations.first?.tokenUsage?.totalTokens == 210)+ let queryTime = Date()+ let terminalReferences = monitor.prepareTerminalTokenUsageReadBatch(now: queryTime)+ #expect(terminalReferences.count == 2)+ for reference in terminalReferences {+ #expect(reference.isTerminalUsageOnly)+ }+ #expect(monitor.prepareTerminalTokenUsageReadBatch(now: queryTime.addingTimeInterval(1)).isEmpty)_ = monitor.prepareTerminalTokenUsageReadBatch(now: Date().addingTimeInterval(31))#expect(monitor.terminalTokenUsageRequests.isEmpty)#expect(monitor.completions.first?.tokenUsage?.totalTokens == 110)@@ -253,6 +260,84 @@ struct CodexActivityTokenUsageTests {#expect(monitor.completions.first?.tokenUsage?.totalTokens == 320)}+ @Test(arguments: [false, true])+ func historicalTerminalUpdatesHistoryWithoutPublishingEvents(aborted: Bool) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = try makeMonitor(directory: directory, preferences: preferences)+ monitor.isActivitySourceHealthy = true+ monitor.isActivityProtectionRecoveryInProgress = false+ let now = Date()+ monitor.sessionTransitionNotBefore = now.addingTimeInterval(-1)+ monitor.terminalPresentationNotBefore = now.addingTimeInterval(-1)+ #expect(monitor.canPublishActivityTransitions)+ for publishesEvents in [false, true] {+ let event = TestFixtures.event(at: now, turn: publishesEvents ? "live-turn" : "historical-turn")+ let key = CodexActivityTaskKey(event: event)+ let task = CodexActivityTask(+ displayID: UUID(), key: key, event: event, state: .running,+ latestEvent: .promptSubmitted, startedAt: now, progressGeneration: 1+ )+ var transitions: [CodexActivityTransition] = []+ monitor.resolveTerminal(+ aborted ? .aborted(at: now) : .completed(at: now, duration: 1),+ task: task, key: key, abortFallback: now, publishesEvents: publishesEvents, into: &transitions+ )+ #expect(transitions.isEmpty == (aborted || !publishesEvents))+ #expect(monitor.pendingTerminalPresentationEvents.isEmpty == !publishesEvents)+ #expect(monitor.recentEndedDate(for: key, now: now) != nil)+ let presentationCount = monitor.pendingTerminalPresentationEvents.count+ monitor.resolveTerminal(+ aborted ? .aborted(at: now) : .completed(at: now, duration: 1),+ task: task, key: key, abortFallback: now, publishesEvents: true, into: &transitions+ )+ #expect(monitor.pendingTerminalPresentationEvents.count == presentationCount)+ }+ #expect(aborted ? monitor.terminations.count == 2 : monitor.completions.count == 2)+ #expect(monitor.terminalTokenUsageRequests.count == 2)+ }++ @Test(arguments: [false, true], [false, true])+ func liveTerminalPresentationPreservesAnonymousAndInterruptBehavior(interrupted: Bool, anonymous: Bool) throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let monitor = try makeMonitor(directory: directory, preferences: preferences)+ monitor.isActivitySourceHealthy = true+ monitor.isActivityProtectionRecoveryInProgress = false+ let now = Date()+ monitor.sessionTransitionNotBefore = now.addingTimeInterval(-1)+ monitor.terminalPresentationNotBefore = now.addingTimeInterval(-1)+ let event = TestFixtures.event(.interrupt, at: now, session: anonymous ? nil : "session-a")+ let key = CodexActivityTaskKey(event: event)+ let task = CodexActivityTask(+ displayID: UUID(), key: key, event: event, state: .running,+ latestEvent: .promptSubmitted, startedAt: now, progressGeneration: 1+ )+ var transitions: [CodexActivityTransition] = []+ if interrupted {+ monitor.tasks[key] = task+ monitor.interruptTask(from: event, source: .live)+ monitor.interruptTask(from: event, source: .live)+ #expect(monitor.tasks.isEmpty)+ #expect(monitor.terminations.count == 1)+ #expect(monitor.terminations.first?.isAnonymous == anonymous)+ } else {+ monitor.resolveTerminal(+ .completed(at: now, duration: 1), task: task, key: key,+ abortFallback: now, into: &transitions+ )+ #expect(monitor.completions.count == 1)+ #expect(monitor.completions.first?.isAnonymous == anonymous)+ }+ #expect(transitions.count == (interrupted || anonymous ? 0 : 1))+ #expect(monitor.pendingTerminalPresentationEvents.count == 1)+ #expect(monitor.terminalTokenUsageRequests.count == (anonymous ? 0 : 1))+ }+private func reference(_ thread: String, _ turn: String) -> CodexActivityTurnReference {CodexActivityTurnReference(threadID: thread, turnID: turn, startedAt: TestFixtures.now)}diff --git a/CodexBarTests/CodexQuotaAndIdentityTests.swift b/CodexBarTests/CodexQuotaAndIdentityTests.swiftindex 3446a18..56d9b89 100644--- a/CodexBarTests/CodexQuotaAndIdentityTests.swift+++ b/CodexBarTests/CodexQuotaAndIdentityTests.swift@@ -2,6 +2,44 @@ import Foundationimport Testingstruct CodexQuotaAndIdentityTests {+ @MainActor+ @Test func ordinaryUsagePermissionReachesStatusIconWithoutInferringFromQuota() throws {+ let presentation = StatusItemIconPresentation()+ let cases: [(field: String, allowed: Bool?)] = [+ (#""ordinaryUsageAllowed":false,"#, false),+ (#""ordinaryUsageAllowed":true,"#, true),+ (#""ordinaryUsageAllowed":false,"#, false),+ (#""ordinaryUsageAllowed":null,"#, nil),+ (#""ordinaryUsageAllowed":false,"#, false),+ ("", nil)+ ]+ for (field, allowed) in cases {+ let response = try TestFixtures.decode(AccountRateLimitsResponse.self, """+ {\(field)"rateLimits":{"primary":{"usedPercent":0}}}+ """)+ let snapshot = try CodexQuotaSnapshot(accountResponse: accountResponse, rateLimitsResponse: response)+ #expect(snapshot.ordinaryUsageAllowed == allowed)+ for percent: Int? in [100, 0, nil] {+ presentation.update(+ symbolName: "person.fill",+ ordinaryUsageAllowed: snapshot.ordinaryUsageAllowed,+ percent: percent,+ isStale: false,+ animated: false+ )+ #expect(presentation.state.isOrdinaryUsageRestricted == (allowed == false))+ }+ }+ }++ @Test func cachedQuotaRetainsLastExplicitOrdinaryUsagePermission() throws {+ let response = try TestFixtures.decode(AccountRateLimitsResponse.self, #"{"ordinaryUsageAllowed":false,"rateLimits":{}}"#)+ let snapshot = try CodexQuotaSnapshot(accountResponse: accountResponse, rateLimitsResponse: response, isRateLimitsStale: true)+ #expect(snapshot.ordinaryUsageAllowed == false)+ let empty = try CodexQuotaSnapshot(accountResponse: accountResponse, rateLimitsResponse: nil)+ #expect(empty.ordinaryUsageAllowed == nil)+ }+@Test func resetCandidatesRequireExplicitStatusTypeAndExpiration() throws {let summary = try TestFixtures.decode(RateLimitResetCreditsSummary.self, """{"availableCount":5,"credits":[diff --git a/CodexBarTests/CodexSessionLifecycleReaderTests.swift b/CodexBarTests/CodexSessionLifecycleReaderTests.swiftindex ca983d0..93cdb7d 100644--- a/CodexBarTests/CodexSessionLifecycleReaderTests.swift+++ b/CodexBarTests/CodexSessionLifecycleReaderTests.swift@@ -2,6 +2,34 @@ import Foundationimport Testingstruct CodexSessionLifecycleReaderTests {+ @Test(arguments: [false, true], ["whitespace", "invalid-json", "invalid-utf8"])+ func singleLineDecodingPreservesCoverageInBothDirections(historical: Bool, content: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ var data = Data(([metadata(session: "session-a"), context, start, tokenUsage(input: 100)]+ .joined(separator: "\r\n") + "\r\n").utf8)+ switch content {+ case "invalid-json": data.append(contentsOf: "{broken}\r\n".utf8)+ case "invalid-utf8": data.append(contentsOf: [0xFF, 0x0D, 0x0A])+ default: data.append(contentsOf: "\r\n \t\r\n".utf8)+ }+ if historical {+ data.append(contentsOf: (oversizedLine(type: "compacted", payloadByteCount: 1024 * 1024) + "\r\n").utf8)+ }+ let url = try directory.write(data, to: "archived_sessions/rollout-test-session-a.jsonl")+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == (content == "whitespace" ? .complete : .incomplete))+ #expect(state.hasContext)+ #expect(state.startedAt == TestFixtures.now)+ #expect(state.tokenUsage?.totalTokens == (content == "whitespace" ? 110 : nil))+ try append(completion + "\r\n", to: url)+ let completed = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(completed.readStatus == .complete)+ #expect(completed.terminal != nil)+ #expect(!completed.isHistoricalTerminal)+ }+@Test func completionHasStartDurationContextAndProgress() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -111,14 +139,14 @@ struct CodexSessionLifecycleReaderTests {#expect(await reader.lifecycleStates(for: [reference], now: later).first?.incompleteTailUnchangedSince == later)}- @Test(arguments: ["missing-context", "read-gap", "known-terminal"])+ @Test(arguments: ["missing-context", "read-gap"])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]+ default: [context, start, "broken"]}let url = try writeRollout(in: directory, lines: lines)try append("{", to: url)@@ -238,10 +266,541 @@ struct CodexSessionLifecycleReaderTests {#expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)}+ @Test(arguments: [false, true])+ func historicalTerminalIsFoundDespiteCompleteTailContextOrPartialTail(partialTail: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [+ context, start, completion, oversizedLine(type: "compacted", payloadByteCount: 1500 * 1024), context+ ])+ if partialTail {+ try append("{", to: url)+ }+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.terminal != nil)+ #expect(state.isHistoricalTerminal)+ #expect(state.incompleteTailUnchangedSince == nil)+ }++ @Test func completeTerminalRemainsUsableWhileNextLineIsPartial() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [context, start, completion])+ try append("{", to: url)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.terminal != nil)+ #expect(state.tokenUsage == nil)+ #expect(state.incompleteTailUnchangedSince == nil)+ }++ @Test func partialTerminalSpanningBootstrapBoundaryIsRecoveredWhenCompleted() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [context, start])+ let largeTerminal = String(completion.dropLast(2)) + ",\"last_agent_message\":\"" + String(repeating: "x", count: 1024 * 1024) + "\"}}"+ try append(largeTerminal, to: url)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)+ try append("\n", to: url)+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.terminal != nil)+ }++ @Test func historicalReadsContinuePastEightMiBAndAcrossOversizedLines() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ _ = try writeRollout(in: directory, lines: [+ context, start, completion, oversizedLine(type: "compacted", payloadByteCount: 17 * 1024 * 1024), context+ ])+ 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.terminal == nil)+ #expect(state.incompleteTailUnchangedSince == nil)+ }+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.terminal != nil)+ }++ @Test func historicalTerminalCrossingReadBoundaryIsNotDropped() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let tailCount = (8 * 1024 * 1024 - 512 * 1024) - 80+ let tail = oversizedLine(type: "compacted", payloadByteCount: tailCount)+ _ = try writeRollout(in: directory, lines: [context, start, completion, tail])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)+ }++ @Test func historicalReadsPreserveNewContextUsageAndImplicitProgress() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let newerContext = context.replacingOccurrences(of: "high", with: "low")+ .replacingOccurrences(of: "08:00:00", with: "08:01:00")+ let progress = #"{"timestamp":"2026-09-15T08:02:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#+ let url = try writeRollout(in: directory, lines: [+ context, start, tokenUsage(input: 100), newerContext,+ oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024),+ tokenUsage(input: 200), progress+ ])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ #expect(await reader.lifecycleStates(for: [reference]).first?.readStatus == .incomplete)+ try append(progress.replacingOccurrences(of: "08:02:00", with: "08:04:00") + "\n", to: url)+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.terminal == nil)+ #expect(state.effort == "low")+ #expect(state.contextObservedAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:01:00Z"))+ #expect(state.tokenUsage?.totalTokens == 210)+ #expect(state.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))+ try append(progress.replacingOccurrences(of: "08:02:00", with: "08:05:00") + "\n", to: url)+ let live = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(live.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:05:00Z"))+ try append(completion + "\n", to: url)+ let completed = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(completed.terminal != nil)+ #expect(!completed.isHistoricalTerminal)+ }++ @Test(arguments: ["agent_message", "function_call_output", "token_count"])+ func progressArrivingAcrossHistoricalReadsKeepsItsExecutionMeaning(kind: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [+ context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)+ ])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ #expect(await reader.lifecycleStates(for: [reference]).first?.readStatus == .incomplete)+ let type = kind == "function_call_output" ? "response_item" : "event_msg"+ try append("""+ {"timestamp":"2026-09-15T08:04:00Z","type":"\(type)","payload":{"type":"\(kind)"}}++ """, to: url)+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.lastProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))+ #expect((state.lastExecutionProgressAt != nil) == (kind != "token_count"))+ #expect(state.terminal == nil)+ }++ @Test(arguments: [false, true])+ func pendingInitialProgressDoesNotCrossIntoTheNextTurn(switchBeforeFirstRead: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [+ context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)+ ])+ let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#+ let nextContext = context.replacingOccurrences(of: "turn-a", with: "turn-b")+ let nextStart = start.replacingOccurrences(of: "turn-a", with: "turn-b")+ let boundary = [progress, nextContext, nextStart].joined(separator: "\n") + "\n"+ let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ if switchBeforeFirstRead {+ try append(boundary, to: url)+ }+ _ = await reader.lifecycleStates(for: [reference, next])+ if !switchBeforeFirstRead {+ try append(boundary, to: url)+ }+ let states = await reader.lifecycleStates(for: [reference, next])+ let previous = try #require(states.first { $0.turnID == "turn-a" })+ let current = try #require(states.first { $0.turnID == "turn-b" })+ #expect(previous.readStatus == .complete)+ #expect(previous.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))+ #expect(current.readStatus == .complete)+ #expect(current.lastExecutionProgressAt == nil)+ try append(progress.replacingOccurrences(of: "08:04:00", with: "08:05:00") + "\n", to: url)+ let live = await reader.lifecycleStates(for: [reference, next])+ #expect(live.first { $0.turnID == "turn-a" }?.lastExecutionProgressAt == previous.lastExecutionProgressAt)+ #expect(live.first { $0.turnID == "turn-b" }?.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:05:00Z"))+ }++ @Test(arguments: ["history", "bootstrap", "append"], [1, 9])+ func lateOldTerminalPreservesNewTurnProgressDuringBackfill(location: String, paddingMiB: Int) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#+ var lines = [+ context, start, context.replacingOccurrences(of: "turn-a", with: "turn-b"),+ start.replacingOccurrences(of: "turn-a", with: "turn-b")+ ]+ if location == "history" {+ lines.append(completion)+ }+ lines.append(oversizedLine(type: "compacted", payloadByteCount: paddingMiB * 1024 * 1024))+ if location == "bootstrap" {+ lines.append(completion)+ }+ if location != "append" {+ lines.append(progress)+ }+ let url = try writeRollout(in: directory, lines: lines)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ var state = try #require(await reader.lifecycleStates(for: [next]).first)+ if location == "append" {+ try append(completion + "\n" + progress + "\n", to: url)+ }+ for _ in 0 ..< 3 {+ state = try #require(await reader.lifecycleStates(for: [next]).first)+ }+ #expect(state.readStatus == .complete)+ #expect(state.terminal == nil)+ #expect(state.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))+ try append(progress.replacingOccurrences(of: "08:04:00", with: "08:05:00") + "\n", to: url)+ let live = try #require(await reader.lifecycleStates(for: [next]).first)+ #expect(live.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:05:00Z"))+ }++ @Test func historicalProgressStopsAtItsOwnTerminalDespiteOtherLateTerminals() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let progress = #"{"timestamp":"2026-09-15T08:02:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#+ _ = try writeRollout(in: directory, lines: [+ context, start, context.replacingOccurrences(of: "turn-a", with: "turn-b"),+ start.replacingOccurrences(of: "turn-a", with: "turn-b"), progress,+ completion.replacingOccurrences(of: "turn-a", with: "turn-b"), completion,+ progress.replacingOccurrences(of: "08:02:00", with: "08:04:00"),+ oversizedLine(type: "compacted", payloadByteCount: 1024 * 1024)+ ])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ let state = try #require(await reader.lifecycleStates(for: [next]).first)+ #expect(state.terminal != nil)+ #expect(state.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:02:00Z"))+ }++ @Test(arguments: [false, true], ["progress", "context", "usage"])+ func corruptGapSurvivesLateTurnDiscoveryWithoutTaintingNewTurns(duringBackfill: Bool, recordKind: String) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message","turn_id":"turn-a"}}"#+ let record = recordKind == "context" ? context : recordKind == "usage" ? tokenUsage(input: 200) : progress+ let suffix = [+ "{broken}", record, context.replacingOccurrences(of: "turn-a", with: "turn-b"),+ start.replacingOccurrences(of: "turn-a", with: "turn-b"), tokenUsage(input: 300, turn: "turn-b")+ ]+ var lines = [context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)]+ if !duringBackfill {+ lines += suffix+ }+ let url = try writeRollout(in: directory, lines: lines)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ _ = await reader.lifecycleStates(for: [reference, next])+ if duringBackfill {+ try append(suffix.joined(separator: "\n") + "\n", to: url)+ }+ for _ in 0 ..< 3 {+ let states = await reader.lifecycleStates(for: [reference, next])+ let old = try #require(states.first { $0.turnID == "turn-a" })+ #expect(old.readStatus == .incomplete)+ #expect(old.incompleteTailUnchangedSince == nil)+ #expect(old.tokenUsage == nil)+ #expect(states.first { $0.turnID == "turn-b" }?.readStatus == .complete)+ #expect(states.first { $0.turnID == "turn-b" }?.tokenUsage?.totalTokens == 310)+ }+ try append(completion + "\n", to: url)+ let states = await reader.lifecycleStates(for: [reference, next])+ #expect(states.first { $0.turnID == "turn-a" }?.terminal != nil)+ #expect(states.first { $0.turnID == "turn-b" }?.terminal == nil)+ }++ @Test func pendingProgressStopsAtTerminalBeforeAnotherTurnBegins() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [+ context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)+ ])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ _ = await reader.lifecycleStates(for: [reference])+ let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#+ try append([+ progress, completion, progress.replacingOccurrences(of: "08:04:00", with: "08:09:00"),+ context.replacingOccurrences(of: "turn-a", with: "turn-b"), start.replacingOccurrences(of: "turn-a", with: "turn-b")+ ].joined(separator: "\n") + "\n", to: url)+ let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ let states = await reader.lifecycleStates(for: [reference, next])+ let previous = try #require(states.first { $0.turnID == "turn-a" })+ let current = try #require(states.first { $0.turnID == "turn-b" })+ #expect(previous.terminal != nil)+ #expect(previous.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:04:00Z"))+ #expect(current.terminal == nil)+ #expect(current.readStatus == .complete)+ #expect(current.lastExecutionProgressAt == nil)+ }++ @Test func corruptBoundaryDiscardsPendingProgressWithoutBlockingANewTurn() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [+ context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)+ ])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ _ = await reader.lifecycleStates(for: [reference])+ let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#+ try append([+ progress, "broken", context.replacingOccurrences(of: "turn-a", with: "turn-b"),+ start.replacingOccurrences(of: "turn-a", with: "turn-b")+ ].joined(separator: "\n") + "\n", to: url)+ let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ let states = await reader.lifecycleStates(for: [reference, next])+ #expect(states.first { $0.turnID == "turn-a" }?.readStatus == .incomplete)+ #expect(states.first { $0.turnID == "turn-b" }?.readStatus == .complete)+ #expect(states.first { $0.turnID == "turn-b" }?.lastExecutionProgressAt == nil)+ }++ @Test func unassignedProgressAtFileHeadDoesNotClaimCompleteCoverage() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024)])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ _ = await reader.lifecycleStates(for: [reference])+ let progress = #"{"timestamp":"2026-09-15T08:04:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#+ try append(progress + "\n", to: url)+ for _ in 0 ..< 2 {+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .incomplete)+ #expect(state.lastExecutionProgressAt == nil)+ #expect(state.incompleteTailUnchangedSince == nil)+ }+ }++ @Test(arguments: [false, true])+ func replacingFileClearsUnassignedProgress(atomic: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let progress = #"{"timestamp":"2026-09-15T08:09:00Z","type":"event_msg","payload":{"type":"agent_message"}}"#+ let url = try writeRollout(in: directory, lines: [+ context, start, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024), progress+ ])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ _ = await reader.lifecycleStates(for: [reference])+ let replacement = [metadata(session: "session-a"), context, start, progress.replacingOccurrences(of: "08:09:00", with: "08:02:00")]+ .joined(separator: "\n") + "\n"+ try Data(replacement.utf8).write(to: url, options: atomic ? .atomic : [])+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.lastExecutionProgressAt == CodexDateFormat.iso8601Date(from: "2026-09-15T08:02:00Z"))+ }++ @Test func oldTerminalNeverCompletesAnotherTurnAndHistoryDoesNotReplaceFreshUsage() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let nextContext = context.replacingOccurrences(of: "turn-a", with: "turn-b")+ let nextStart = start.replacingOccurrences(of: "turn-a", with: "turn-b")+ _ = try writeRollout(in: directory, lines: [+ context, start, tokenUsage(input: 100), completion,+ oversizedLine(type: "compacted", payloadByteCount: 1200 * 1024),+ tokenUsage(input: 200), nextContext, nextStart+ ])+ let next = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let states = await reader.lifecycleStates(for: [reference, next])+ let previous = try #require(states.first { $0.turnID == "turn-a" })+ #expect(previous.terminal != nil)+ #expect(previous.tokenUsage?.totalTokens == 210)+ let running = try #require(states.first { $0.turnID == "turn-b" })+ #expect(running.terminal == nil)+ #expect(running.readStatus == .complete)+ }++ @Test func multipleFilesShareBudgetAndAllEventuallyReachTheirTerminals() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ var references: [CodexActivityTurnReference] = []+ for session in ["session-a", "session-b", "session-c"] {+ let text = [+ metadata(session: session),+ context,+ start,+ completion,+ oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024),+ context+ ].joined(separator: "\n") + "\n"+ _ = try directory.write(text, to: "archived_sessions/rollout-test-\(session)_00000000-0000-0000-0000-000000000001.jsonl")+ references.append(CodexActivityTurnReference(threadID: session, turnID: "turn-a", startedAt: TestFixtures.now))+ }+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let first = await reader.lifecycleStates(for: references)+ #expect(first.allSatisfy { $0.terminal == nil })+ var completed: Set<String> = []+ for _ in 0 ..< 6 {+ let states = await reader.lifecycleStates(for: references)+ completed.formUnion(states.filter { $0.terminal != nil }.map(\.requestedThreadID))+ }+ #expect(completed == Set(references.map(\.threadID)))+ }++ @Test(arguments: [false, true])+ func replacementOrTruncationDiscardsPendingHistory(atomic: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [+ context, start, completion, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024), context+ ])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)+ let replacement = Data(([metadata(session: "session-a"), context, start].joined(separator: "\n") + "\n").utf8)+ try replacement.write(to: url, options: atomic ? .atomic : [])+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.readStatus == .complete)+ #expect(state.terminal == nil)+ #expect(!state.isHistoricalTerminal)+ }++ @Test func archiveMoveDuringHistoricalReadRelocatesWithoutUsingOldCursor() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: [+ context, start, completion, oversizedLine(type: "compacted", payloadByteCount: 9 * 1024 * 1024), context+ ])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)+ let archived = directory.url.appendingPathComponent("archived_sessions")+ try FileManager.default.createDirectory(at: archived, withIntermediateDirectories: true)+ try FileManager.default.moveItem(at: url, to: archived.appendingPathComponent(url.lastPathComponent))+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal == nil)+ #expect(await reader.lifecycleStates(for: [reference]).first?.terminal != nil)+ }+private var reference: CodexActivityTurnReference {CodexActivityTurnReference(threadID: "session-a", turnID: "turn-a", startedAt: TestFixtures.now)}+ @Test(arguments: [1, 9])+ func terminalBackfillsUsageAndOwnershipWithoutDelayingCompletion(paddingMiB: Int) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ _ = try writeRollout(+ in: directory,+ lines: [context, start, tokenUsage(input: 100)]+ + historyPadding(mebibytes: paddingMiB) + [completion]+ )+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ let first = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(first.terminal != nil)+ #expect(first.readStatus == .complete)+ #expect(!first.isHistoricalTerminal)+ #expect(first.tokenUsage?.totalTokens == (paddingMiB == 1 ? 110 : nil))+ let recovered = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(recovered.tokenUsage?.totalTokens == 110)+ #expect(recovered.rootTurnID == "turn-a")+ #expect(!recovered.isHistoricalTerminal)+ }++ @Test(arguments: [31, 33], [false, true])+ func supplementalHistoryStopsAtLimitAndAcceptsAppendedUsage(paddingMiB: Int, hookEnded: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let other = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ let url = try writeRollout(+ in: directory,+ lines: [context, start, tokenUsage(input: 100)]+ + historyPadding(mebibytes: paddingMiB) + (hookEnded ? [] : [completion])+ + [+ context.replacingOccurrences(of: "turn-a", with: "turn-b"),+ tokenUsage(input: 300, turn: "turn-b"),+ completion.replacingOccurrences(of: "turn-a", with: "turn-b")+ ]+ )+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ var query = reference+ query.isTerminalUsageOnly = hookEnded+ for _ in 0 ..< 12 {+ _ = await reader.lifecycleStates(for: [query], now: TestFixtures.now)+ // 用量查询间隔中的其他轮次轮询不能重置累计预算+ _ = await reader.lifecycleStates(for: [other], now: TestFixtures.now)+ }+ let state = try #require(await reader.lifecycleStates(for: [query], now: TestFixtures.now).first)+ #expect(state.tokenUsage?.totalTokens == (paddingMiB == 31 ? 110 : nil))+ #expect(state.rootTurnID == (paddingMiB == 31 ? "turn-a" : nil))+ #expect((state.terminal != nil) == !hookEnded)++ try append([context, start, tokenUsage(input: 200), completion].joined(separator: "\n") + "\n", to: url)+ let updated = try #require(await reader.lifecycleStates(for: [query], now: TestFixtures.now).first)+ #expect(updated.terminal != nil)+ #expect(updated.tokenUsage?.totalTokens == 210)+ }++ @Test(arguments: [false, true])+ func laterSearchCanContinueBeyondSupplementalLimitAndShareResults(usageOnly: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ var other = CodexActivityTurnReference(threadID: "session-a", turnID: "turn-b", startedAt: TestFixtures.now)+ other.isTerminalUsageOnly = usageOnly+ _ = try writeRollout(in: directory, lines: [+ context.replacingOccurrences(of: "turn-a", with: "turn-b"),+ start.replacingOccurrences(of: "turn-a", with: "turn-b"),+ completion.replacingOccurrences(of: "turn-a", with: "turn-b"),+ context, start, tokenUsage(input: 100)+ ] + historyPadding(mebibytes: 33) + [completion])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ for _ in 0 ..< 8 {+ _ = await reader.lifecycleStates(for: [reference])+ }+ #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage == nil)+ let states = await reader.lifecycleStates(for: [reference, other])+ #expect(states.first { $0.turnID == "turn-b" }?.terminal != nil)+ #expect(states.first { $0.turnID == "turn-b" }?.isHistoricalTerminal == true)+ #expect(states.first { $0.turnID == "turn-a" }?.tokenUsage?.totalTokens == 110)+ }++ @Test func missingSupplementalInformationReachesHeadAndReplacementResetsBudget() async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let url = try writeRollout(in: directory, lines: historyPadding(mebibytes: 33) + [completion])+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ for _ in 0 ..< 8 {+ _ = await reader.lifecycleStates(for: [reference])+ }+ let replacement = [metadata(session: "session-a"), context, start]+ + historyPadding(mebibytes: 1) + [completion]+ try Data((replacement.joined(separator: "\n") + "\n").utf8).write(to: url, options: .atomic)+ for _ in 0 ..< 3 {+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.startedAt == TestFixtures.now)+ #expect(state.terminal != nil)+ #expect(state.tokenUsage == nil)+ #expect(state.rootTurnID == nil)+ }+ try append(tokenUsage(input: 200) + "\n", to: url)+ #expect(await reader.lifecycleStates(for: [reference]).first?.tokenUsage?.totalTokens == 210)+ }++ @Test(arguments: [false, true])+ func terminalBackfillDoesNotReplaceLatestUsageWithOlderSnapshot(invalidLatest: Bool) async throws {+ let directory = try TestDirectory()+ defer { try? directory.remove() }+ let rootContext = context.replacingOccurrences(of: "\"turn_id\":\"turn-a\"", with: "\"turn_id\":\"turn-a\",\"root_turn_id\":\"turn-a\"")+ let latest = invalidLatest ? tokenUsage(input: 200).replacingOccurrences(of: "\"total_tokens\":210", with: "\"total_tokens\":-1") : tokenUsage(input: 200)+ _ = try writeRollout(+ in: directory,+ lines: [rootContext, start, tokenUsage(input: 100)]+ + historyPadding(mebibytes: 9) + [latest, completion]+ )+ let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)+ for _ in 0 ..< 4 {+ let state = try #require(await reader.lifecycleStates(for: [reference]).first)+ #expect(state.terminal != nil)+ #expect(state.tokenUsage?.totalTokens == (invalidLatest ? nil : 210))+ }+ #expect(await reader.lifecycleStates(for: [reference]).first?.rootTurnID == "turn-a")+ }++ private func historyPadding(mebibytes: Int) -> [String] {+ Array(repeating: oversizedLine(type: "compacted", payloadByteCount: 1024 * 1024), count: mebibytes)+ }+@Test func tokenUsageUpdatesIncrementallyBeforeTaskCompletion() async throws {let directory = try TestDirectory()defer { try? directory.remove() }@@ -373,7 +932,8 @@ struct CodexSessionLifecycleReaderTests {"""}- @Test func forkedMetadataDoesNotReplaceChildUsageIdentity() async throws {+ @Test(arguments: [0, 9])+ func forkedMetadataDoesNotReplaceChildUsageIdentity(paddingMiB: Int) async throws {let directory = try TestDirectory()defer { try? directory.remove() }let childMetadata = #"{"type":"session_meta","payload":{"id":"child-a","session_id":"session-a","parent_thread_id":"session-a","#@@ -383,12 +943,14 @@ struct CodexSessionLifecycleReaderTests {.replacingOccurrences(of: #""root_turn_id":"child-turn""#, with: #""root_turn_id":"turn-a""#)let datePath = CodexDateFormat.dayString(from: TestFixtures.now).replacingOccurrences(of: "-", with: "/")_ = try directory.write(- [childMetadata, metadata(session: "session-a"), usage, completion.replacingOccurrences(of: "turn-a", with: "child-turn")]+ ([childMetadata, metadata(session: "session-a"), usage] + historyPadding(mebibytes: paddingMiB)+ + [completion.replacingOccurrences(of: "turn-a", with: "child-turn")]).joined(separator: "\n") + "\n",to: "sessions/\(datePath)/rollout-test-child-a.jsonl")let reader = CodexSessionLifecycleReader(codexHomeURL: directory.url)let child = CodexActivityTurnReference(threadID: "child-a", turnID: "child-turn", startedAt: TestFixtures.now)+ #expect(await reader.lifecycleStates(for: [child]).first?.terminal != nil)let state = try #require(await reader.lifecycleStates(for: [child]).first)#expect(state.recordedThreadID == "child-a")#expect(state.rootSessionID == "session-a")diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex 323b485..1451a28 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 4.1.0-CURRENT_PROJECT_VERSION = 110+MARKETING_VERSION = 4.1.1+CURRENT_PROJECT_VERSION = 111diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.mdindex e462aa6..fb92db1 100644--- a/Docs/DeveloperGuide/activity-monitor.md+++ b/Docs/DeveloperGuide/activity-monitor.md@@ -103,7 +103,7 @@ Hook recorder 可能正在写最后一行。reader 只把最后一个 newline半行不会丢弃,也不会被当作损坏事件。下一轮从旧 offset 重新读取,等行完整后再提交。未读完固定上界时,屏障返回 `sourceUnavailable`。完整坏行会使对应日期游标降级,不能因跳过坏行而报告健康;该日期退出读取窗口或文件替换重放后重新确定健康状态。-Hook 数据源降级期间仍会为已知任务读取 rollout,但只接受本轮完整读取、身份匹配的明确完成或中断记录,并静默结束对应任务。该路径不应用普通进展、不回填审批状态、不恢复隐藏任务,也不恢复异常会话保护。系统睡眠和 bootstrap 期间暂停该路径;任务取消或 reader 代次变化后丢弃读取结果。完整生命周期恢复仍要求 Hook 读取屏障成功。+Hook 数据源降级期间仍会为已知任务读取 rollout,但只接受本轮读取成功、线程和轮次匹配的明确完成或中断记录,并静默结束对应任务。该路径不应用普通进展、不回填审批状态、不恢复隐藏任务,也不恢复异常会话保护。系统睡眠和 bootstrap 期间暂停该路径;任务取消或 reader 代次变化后丢弃读取结果。完整生命周期恢复仍要求 Hook 读取屏障成功。### 跨日与文件替换@@ -143,8 +143,8 @@ actor 在 `await` 期间可以重入,因此 `isProcessingReads` 和 `hasPendin- 默认每 1 秒检查一次- 初始尾部窗口为 512 KiB-- effort 等 turn context 字段最多回查 8 MiB-- 只解析线程归属、生命周期、turn、progress、effort 和 reviewer+- 缺少生命周期或轮次上下文时分轮向前补查,正文读取每轮共享 8 MiB 预算+- 解析线程归属、生命周期、轮次进展、`effort`、`reviewer` 和轮次 Token 用量- 对话内容不进入活动模型或产品展示Hook 的 `Stop` 将任务标记为“正在收尾”,保留在活动列表;仍有其他 Agent 等待用户批准时优先显示等待。后续工具、审批等进展继续更新同一任务;rollout 的完成记录确认本轮结束,满足转场时效和恢复条件时发布完成转场。@@ -173,13 +173,15 @@ resume 可能继续很早以前创建的 session。快速路径找不到时,### Rollout 读取预算-实时任务只需要活跃 turn 附近的 lifecycle,全量读取一个长期 session 会增加常驻 I/O。+文件超过 512 KiB 时,初始游标从最后 512 KiB 开始并丢弃第一条可能不完整的行;较小文件从头读取。正向游标持续消费新增内容,反向游标分轮恢复历史。活动任务未确认终态且缺少开始记录、上下文、`effort`、`reviewer` 或启动片段的进展归属时继续补查,直到所需信息齐全、确认终态或到达文件头。启动时跨过的半行后来补齐后,会重新定位并补读该行。-初始 cursor 从最后 512 KiB 开始并丢弃第一条可能不完整的行。缺少上下文、effort 或 reviewer 时,最多向前重放 8 MiB,统一恢复 turn 归属、元数据和进展。每个文件游标成功补读一次后停止回查,每轮最多补读一个 session。+读取成功且线程、轮次匹配时,reader 返回明确终态,不等待用量补齐;子任务终态应用到主任务前还须确认归属。终态后的补查寻找缺失的归属和用量,不因缺少 `effort` 或 `reviewer` 继续扫描;最新用量记录无效时,不使用更早的有效值替代。每个轮次的补充查询累计最多读取 32 MiB 历史正文,Hook 已确认结束后的用量查询也受此限制。活动任务寻找结束记录不受该累计上限限制。-每轮增量扫描总预算为 8 MiB,多个 session 轮转共享预算;待确认任务每轮最多查询 16 个。超过预算或尚未读到完整行时返回 `incomplete`,读取失败返回 `unavailable`,未找到文件返回 `notFound`。缓存可以保留已经观察到的事实,但不能替代本轮读取成功。成功读到固定上界且恢复了 turn 上下文时,`lifecycleCoverageCheckedAt` 记录本次检查时间;读取未完成、失败、文件不存在或缺少上下文时将其清空。常规异常静默判定要求该时间存在且距当前不足 5 秒。+同一文件的查询共用历史游标、解析结果和累计实际读取量。每个补充查询以登记时的累计量为起点,用差值计算已消耗预算,其他查询推动的历史读取也计入差值。查询登记和相关终态按最近查询时间保留 24 小时,重复查询只刷新时间。找到所需信息、到达文件头或耗尽预算后,该查询停止推动补查;到达文件头表示历史已查完,预算耗尽时仍可能有未检查内容。后续新增记录或其他必要查询读到的信息仍可补齐结果。短读、后置检查失败和重试中实际读到的字节均计入预算。游标和预算保存在内存中,文件替换、可检测的截断或 reader 重建后重新建立。-增量扫描按实际读取字节推进 offset,并跨轮拼接未结束的行。每轮读取预算仍为 8 MiB,单行最多缓冲 16 MiB;超过缓冲上限时标记读取缺口并分块跳到换行,后续记录仍可继续消费。明确的 rollout 终态不受此前读取缺口影响。+每轮增量扫描与历史补查共享 8 MiB 正文读取预算,多个 session 轮转使用预算;待确认任务每轮最多查询 16 个。正向扫描未追到文件末尾、存在半行或未结束轮次存在覆盖缺口时返回 `incomplete`,读取失败返回 `unavailable`,未找到文件返回 `notFound`。本轮读取成功且已明确匹配的终态返回 `complete`,即使末尾另一条记录尚未写完;Token 用量仍要求尾部完整。轮次状态为 `complete` 且具有 turn 上下文时,`lifecycleCoverageCheckedAt` 记录本次检查时间;读取未完成、失败、文件不存在或缺少上下文时将其清空。常规异常静默判定要求该时间存在且距当前不足 5 秒。++增量扫描按实际读取字节推进 offset,并跨轮拼接未结束的行。单行最多缓冲 16 MiB;超过缓冲上限时标记读取缺口并分块跳到换行,后续记录继续消费。明确的 rollout 终态不受此前读取缺口影响。文件可读且已经追到实际末尾,仅剩有界残缺末行时,reader 记录首次观察或最近一次追加的时间。任务已有 turn 上下文、没有其他覆盖缺口或已知终态,且本次观察距当前不足 5 秒时,可以使用残缺末行兜底:任务最后进展和末行最后增长均达到用户设置的静默阈值后,允许隐藏任务。末行继续增长会重新计时;读取失败、文件替换或截断、App 重启后重新开始观察。积压未读完、缺少上下文和超限丢弃中的行不能使用此兜底。@@ -187,18 +189,20 @@ resume 可能继续很早以前创建的 session。快速路径找不到时,rollout 坏行将当时尚未结束的 turn 标记为有覆盖缺口,后续重复的同一 turn 上下文不能清除此标记。新的 turn 独立建立覆盖,身份明确的完成或中断记录可以结束有缺口的任务;后续坏行不会撤销已经读到的明确终态。读取失败或尚未读完时,缓存进展不推进任务的执行时间,也不能恢复隐藏任务或清除保护记录。+坏行出现时尚未定位的旧轮次,在历史补查中按文件位置继承覆盖缺口;坏行后带有明确 turn ID 的进展或重复上下文不能消除缺口。坏行之后开始的新轮次独立判断覆盖。历史补查发现的终态更新任务记录和去重状态,但不补发通知或终态展示事件。+### Rollout 进展的 turn 归属-每个 session 的文件游标保存独立的 `currentTurnId`,按 JSONL 文件顺序更新:+每个 session 的文件游标保存独立的 `currentTurnID`,按 JSONL 文件顺序更新:- 外层 `type = "turn_context"`,或外层 `type = "event_msg"` 且 `payload.type` 为 `task_started` 或 `turn_started` 时,以 `payload.turn_id` 建立上下文- `response_item` 优先使用 `payload.internal_chat_message_metadata_passthrough.turn_id`;其他进展记录使用 `payload.turn_id`,缺失时沿用游标上下文- 当前 turn 的 `task_complete`、`turn_complete` 或 `turn_aborted` 清空上下文;迟到的其他 turn 终态不清空它-- 文件截断或替换时重建游标,同时清空上下文和已缓存的生命周期+- 检测到文件标识变化或文件大小小于正向读取位置时重建游标,同时清空上下文、生命周期缓存和补查预算进展记录包括外层 `type` 为 `response_item` 或 `token_usage_record` 的记录,以及外层为 `event_msg`、`payload.type` 为 `token_count`、`item_completed`、`agent_message`、`agent_reasoning`、`task_started`、`turn_started`、`task_complete`、`turn_complete` 或 `turn_aborted` 的记录。时间依次取外层 `timestamp`、`payload.completed_at`、`payload.started_at`。-记录须有可用时间和 turn 归属,本轮读取完整且时间晚于任务的 `lastProgressAt` 时才更新进展。`token_usage_record` 按活动记录处理,不比较 token 数量是否增加。缺少显式 turn 和游标上下文的记录不计入任务进展。+记录须有可用时间和 turn 归属,本轮读取完整且时间晚于任务的 `lastProgressAt` 时才更新进展。`token_usage_record` 按活动记录处理,不比较 token 数量是否增加。启动片段中缺少显式 turn 和上下文的进展只暂存时间,补查恢复可靠归属后再合并;无法确定归属的进展不计入任务。正向暂存和反向补查都按轮次匹配结束记录,迟到的其他轮次终态不能截断当前轮次进展,当前轮次自身结束后的无归属进展也不能回填给它。能用于推断审批恢复的执行进展单独记录为 `lastExecutionProgressAt`:包括 `response_item` 中 `role = "assistant"` 的记录及类型为 `function_call_output`、`custom_tool_call_output`、`tool_search_output` 的工具结果,以及 `agent_message`、`agent_reasoning` 事件。只有同一 Agent/轮次中晚于审批请求的执行进展才清除该等待;用量记录等普通活动只更新任务进展时间。@@ -226,7 +230,7 @@ rollout 坏行将当时尚未结束的 turn 标记为有覆盖缺口,后续重`CodexActivityTokenUsage.swift` 按根任务收集主线程及已关联子线程的轮次引用,并按线程、轮次去重。运行中汇总本次读取完整且归属匹配的线程,尚未有用量的线程等待后续刷新;显示值因此可以是已知线程的小计。实时卡片使用内存任务快照,不读取历史日汇总或 iCloud 缓存。-完成和终止记录创建时用量为空,由结束后补读填入。补读最多持续 30 秒,每 2 秒安排一次,每批最多处理 16 个待补读任务。最终汇总要求已知子 Agent 身份齐全、各线程用量可用,且子线程已结束。补读取得用量后,后续读取不完整时保留该值,迟到的子线程关联只加入所属根轮次,不影响后续轮次。结束状态、通知和防睡眠释放不等待 Token 补读。+完成和终止记录创建时用量为空,由结束后补读填入。补读从登记查询时起最多持续 30 秒,每 2 秒安排一次,每批最多处理 16 个待补读任务。最终汇总要求已知子 Agent 身份齐全、各线程用量可用,且子线程已结束。取得用量后,在期限内继续接受更新;读取不完整时保留已有值。到期移除查询,未取得用量的记录保持为空。迟到的子线程关联只加入所属根轮次,不影响后续轮次。结束状态、通知和防睡眠释放不等待 Token 补读。历史回放使用独立的账本与读取游标,见 [Rollout Token 历史](sync.md#rollout-token-历史)diff --git a/Docs/DeveloperGuide/data-and-privacy.md b/Docs/DeveloperGuide/data-and-privacy.mdindex 0101bb6..ba657da 100644--- a/Docs/DeveloperGuide/data-and-privacy.md+++ b/Docs/DeveloperGuide/data-and-privacy.md@@ -91,7 +91,7 @@ Hook recorder 通过 `transcript_path` 读取当前 rollout,`SubagentStop` 的Token 历史扫描从文件起点建立轮次账本,再按游标增量读取。云端身份使用账户 salt 做 HMAC-SHA256,不上传原始线程或轮次 ID。字段和保留规则见 [Rollout Token 历史](sync.md#rollout-token-历史)-实时 rollout reader 从文件尾部按预算扫描,一方面减少 I/O,另一方面降低无关历史内容进入进程内存的范围。解析 DTO 只声明所需字段,JSONDecoder 自动忽略其余内容。+实时 rollout reader 初始读取末尾最多 512 KiB,随后增量读取追加内容,并按需向前补查历史。解析 DTO 只声明所需字段,`JSONDecoder` 忽略其余内容。补查停止条件和预算见 [Rollout 读取预算](activity-monitor.md#rollout-读取预算)### Reset Credits 明细diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.mdindex baf4127..b19e5eb 100644--- a/Docs/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md@@ -81,7 +81,7 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。### 分离图标与 tooltip 状态-`StatusIconState` 保存活动和额度输入。`StatusItemIconPresentation` 只发布影响图像的符号名称、额度、显隐和缓存标记,相同渲染状态不会重复发布:+`StatusIconState` 保存活动、额度和 `ordinaryUsageAllowed` 输入。`StatusItemIconPresentation` 发布符号名称、常规用量受限状态、额度、显隐和缓存标记,相同渲染状态不会重复发布:- 活跃任务持续时间每分钟变化,只更新 tooltip- 额度过期但仍展示缓存时,图标和进度使用降低后的 alpha@@ -92,7 +92,7 @@ UI 使用 SwiftUI 声明内容,由 AppKit Controller 管理窗口。- 关闭额度时保留最后的额度和配色供收回动画使用,零额度与缺失额度保持不同语义- 初次渲染和唤醒重算时不播放过渡动画-SwiftUI 视图持续挂载在原生 `NSStatusBarButton` 中,透明图片用于系统自适应占位。图标使用系统前景色,宿主视图不接受焦点或鼠标命中,左右键仍交给原按钮处理。+SwiftUI 视图持续挂载在原生 `NSStatusBarButton` 中,透明图片用于系统自适应占位。`ordinaryUsageAllowed == false` 时,人物及徽章使用适配浅色、深色外观的浅橙色;值为 `true` 或缺失时使用系统前景色。额度圆弧按剩余比例配色。宿主视图不接受焦点或鼠标命中,左右键交给原按钮处理。圆弧和人物通过 `drawingGroup()` 合成为一个绘制结果,保持全屏与普通桌面切换时额度圆弧的长度和颜色一致。@@ -166,7 +166,7 @@ popover 和备用面板分别持有 `MenuSurfaceAnimationState`。展示前将 `活动卡片和任务中心共用 `CodexActivityStatusText`,文字颜色跟随任务状态。运行时显示扫光,等待批准时显示橙色粒子,完成和终止时静态显示。卡片状态文字动画由 `mainPanelAnimationsEnabled` 控制,任务中心状态文字动画要求 `presentationState.isPresented` 和 `MainPanelSettings.areAnimationsEnabled` 同时开启。每个面板共用一条粒子时间线,只从可见的等待文字发射粒子,按面板边界裁剪;没有发射源时移除时间线。-活动卡片在 `primaryActivity.tokenUsage` 可用时展示 Token 指标和分割线。状态行固定在卡片顶部,卡片高度随 Token 区域显隐调整。+活动卡片在 `primaryActivity.tokenUsage` 可用时展示 Token 指标和分割线,为空时隐藏整个用量区域。完成或终止后的用量补读在后台进行,界面先显示结束状态,取得用量后再展开指标;查询到期不显示超时提示。任务中心的完成和终止条目仅在用量可用时显示总 Token。状态行固定在卡片顶部,卡片高度随 Token 区域显隐调整。展开和收起采用平滑减速的过渡,独立于“动画效果”设置。Token 区域随展开进度淡入并轻微上移,收起时提前淡出。`ActivityCardHeight` 逐帧提交插值后的布局高度,使相邻区块和主面板尺寸同步变化。防睡眠徽标、匿名图标和并发任务数的动画限定在状态行内。diff --git a/Docs/UserGuide/main-panel.md b/Docs/UserGuide/main-panel.mdindex ebf8650..8b4eab8 100644--- a/Docs/UserGuide/main-panel.md+++ b/Docs/UserGuide/main-panel.md@@ -9,6 +9,7 @@ CodexBar 用人物图标和可选额度圆弧表达账户、任务和额度状| 外观 | 含义 || --- | --- || 普通人形 | 默认或空闲状态 |+| 浅橙色人物及徽章 | 账户数据表明常规用量受限 || 斜杠人形 | 未登录、初始化失败或缺少可信额度与用量数据 || 时钟徽章 | 至少有一个任务正在运行 || 钥匙徽章 | 至少有一个任务正在等待用户批准 |@@ -31,7 +32,7 @@ CodexBar 用人物图标和可选额度圆弧表达账户、任务和额度状## 账户区域- 展示当前登录账户或账户类型-- 展示 Enterprise, Team, Business, Pro, Plus, Edu 和 Free 等套餐标识+- 展示 Enterprise, Team, Business, ProMax, Pro, ProLite, Plus, Go, Edu 和 Free 等套餐标识- 双击账户图标会立即刷新账户、额度和用量- 双击邮箱会切换模糊显示- 未登录时显示 `未登录`@@ -121,7 +122,7 @@ CodexBar 会展示 Codex 返回的全部额度分组和窗口。活动卡片取得本轮 rollout 用量后,在状态下方展示 Token 总量、输入输出、缓存使用和推理输出等指标,数量使用 K/M/B 缩写。用量区域和上方分割线一起展开或收起,动画不受 `动画效果` 开关控制。没有用量时隐藏整个区域。-运行中和等待批准时,已能确认归属的主线程与子 Agent 用量会持续更新;后续线程记录到达后继续补齐。完成或终止后会短暂补读本轮用量,取得完整汇总后显示。之后读取暂时失败时,保留已经取得的结束用量。这里统计的是当前对话轮次及其子 Agent,而非整个会话。+运行中和等待批准时,已能确认归属的主线程与子 Agent 用量会持续更新;后续线程记录到达后继续补齐。确认完成或终止后,后台最多追查 30 秒本轮用量,取得完整汇总后显示,期限内继续接受更新。结束状态立即展示,追查期间没有倒计时或加载提示。到期仍未取得用量时,用量区域保持隐藏;已经取得的数值会保留。统计范围是当前对话轮次及其子 Agent。总量等于输入加输出;缓存命中和缓存写入包含在输入中,推理输出包含在输出中,不能再次加到总量上。缓存命中率为缓存命中除以输入;输入为零时,卡片显示 `—`。英文标签 `Cached`、`Cache-W` 和 `Cache-H` 分别表示缓存命中、缓存写入和缓存命中率。diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.mdindex b94a697..1a9f72c 100644--- a/Docs/en/DeveloperGuide/activity-monitor.md+++ b/Docs/en/DeveloperGuide/activity-monitor.md@@ -103,7 +103,7 @@ The Hook recorder may be writing the final line. The reader includes only bytesA 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.+While the Hook source is degraded, rollout reads continue for known tasks, accepting only explicit completion or interruption records after a successful current read with matching thread and turn 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@@ -143,8 +143,8 @@ Rules are:- Poll every 1 second by default- Begin with a 512 KiB tail window-- Look back at most 8 MiB for turn-context fields such as effort-- Parse only thread relationships, lifecycle, turn, progress, effort, and reviewer+- Backfill missing lifecycle or turn context over multiple cycles, sharing an 8 MiB body-read budget per cycle+- Parse thread relationships, lifecycle, turn progress, `effort`, `reviewer`, and turn token usage- Keep conversation content out of the activity model and product presentationHook `Stop` marks the task as “Finishing up” and keeps it active; approval waiting takes priority while another agent is still waiting. Tools, approvals, and other progress continue updating the same task. Rollout completion records confirm the end of the turn; transition freshness and recovery conditions determine whether a completion transition is emitted.@@ -173,13 +173,17 @@ Filenames match the thread ID exactly, optionally followed by an underscore and### Rollout Read Budget-Live tasks need lifecycle near an active turn, not a full read of a long-running session. Starting from the last 512 KiB reduces resident I/O and discards the first potentially partial line.+For files larger than 512 KiB, the initial cursor starts at the last 512 KiB and discards the first potentially partial line. Smaller files are read from the beginning.-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.+The forward cursor consumes appended content while a reverse cursor restores history over multiple cycles. For an active turn without a confirmed terminal, backfill continues while its start, context, effort, reviewer, or initial progress ownership is missing, until the required information is available, a terminal is confirmed, or the file head is reached. A line straddling the bootstrap boundary that finishes later is located and read again.-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.+After a successful read with matching thread and turn identity, the reader returns a confirmed terminal without waiting for usage. Applying a child terminal to its parent task also requires confirmed ownership. Supplemental backfill seeks missing ownership and usage, not missing `effort` or `reviewer` fields. An invalid latest usage record cannot be replaced with an older valid snapshot. Each turn's supplemental query may read at most 32 MiB of historical body data, including usage-only queries after a Hook-confirmed end. Active lifecycle searches are not subject to this cumulative cap.-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.+Queries for the same file share a reverse cursor, decoded facts, and cumulative bytes actually read. Each supplemental query records the cumulative count at registration and uses the difference to calculate its consumed budget, including reads driven by other queries. Registrations and associated terminal facts are retained for 24 hours after the latest query; repeated queries refresh only that time. Finding the required information, reaching the file head, or exhausting the budget stops that query from driving backfill. The file head means history is exhausted; a spent budget may leave history unchecked. Appended records or reads required by other queries can still supply missing facts. Bytes read during short reads, failed post-read checks, and retries all count toward the budget. Cursors and budgets are in-memory and reset on file replacement, detectable truncation, or reader recreation.++Incremental scanning and historical backfill share an 8 MiB body-read budget per cycle across sessions in rotating order. At most 16 pending tasks are queried per cycle. An unread tail, a partial line, or a coverage gap for a nonterminal turn returns `incomplete`; read failures return `unavailable`, and unresolved files return `notFound`. A confirmed matching terminal returns `complete` after a successful current read even when another trailing record is unfinished; token usage still requires a complete tail. A turn with `complete` status and 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 bytes read and carries an unfinished line across cycles. 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.@@ -187,18 +191,20 @@ A partial tail always returns `incomplete`. Its observation affects protection tA 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.+Older turns not yet identified when corruption occurs inherit the gap by file position during backfill. Later progress with an explicit turn ID or repeated context cannot clear that gap. Turns beginning after the malformed line establish independent coverage. Historical terminals update task records and deduplication state without publishing notifications or terminal presentation events.+### Associating Rollout Progress with a Turn-Each session file cursor stores its own `currentTurnId`, updated in JSONL file order:+Each session file cursor stores its own `currentTurnID`, updated in JSONL file order:- Outer `type = "turn_context"`, or `type = "event_msg"` with `payload.type` equal to `task_started` or `turn_started`, establishes context from `payload.turn_id`- `response_item` prefers `payload.internal_chat_message_metadata_passthrough.turn_id`; other progress records use `payload.turn_id`, falling back to cursor context when absent- `task_complete`, `turn_complete`, or `turn_aborted` for the current turn clears context; a late terminal for another turn does not-- Truncation or replacement rebuilds the cursor and clears both context and cached lifecycle states+- A changed file identifier or file size below the forward read position rebuilds the cursor and clears context, cached lifecycle, and supplemental budgetsProgress includes records whose outer `type` is `response_item` or `token_usage_record`, and `event_msg` records whose `payload.type` is `token_count`, `item_completed`, `agent_message`, `agent_reasoning`, `task_started`, `turn_started`, `task_complete`, `turn_complete`, or `turn_aborted`. Time comes from outer `timestamp`, then `payload.completed_at`, then `payload.started_at`.-A record needs a usable timestamp and turn identity. It advances task progress only after a complete current read and when newer than `lastProgressAt`. A `token_usage_record` is treated as activity without comparing token totals. Records lacking both an explicit turn and cursor context do not contribute task progress.+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. Initial records without an explicit turn or context retain only their progress times until backfill establishes reliable ownership; unresolved progress does not update a task. Both forward buffering and reverse backfill match terminals by turn: another turn's late terminal cannot cut off current progress, and unassigned progress after a turn's own terminal cannot be attributed back to it.Execution progress eligible to infer approval recovery is recorded separately as `lastExecutionProgressAt`: `response_item` records with `role = "assistant"` or a type of `function_call_output`, `custom_tool_call_output`, or `tool_search_output`, and `agent_message` or `agent_reasoning` events. Only execution progress from the same agent and turn, later than the approval request, clears that wait. Ordinary activity such as usage records updates only task progress time.@@ -226,7 +232,7 @@ All required token counters must be present and nonnegative. Total must equal in`CodexActivityTokenUsage.swift` collects main and associated child-thread references for the root task, deduplicating by thread and turn. While running, it sums matching threads with complete current reads; threads without usage wait for later refreshes. The displayed value may therefore be a subtotal of known threads. The live card reads the in-memory task snapshot, not historical daily totals or iCloud caches.-Completed and terminated records start without usage and receive it through terminal rereads. Rereading lasts up to 30 seconds, scheduled every 2 seconds for at most 16 pending tasks per batch. Final aggregation requires all expected child identities and thread usage, with child threads ended. Once terminal usage has been obtained, later incomplete reads preserve that value. Late child associations join only their root turn, without affecting subsequent turns. Terminal state, notifications, and sleep-prevention release do not wait for token rereads.+Completed and terminated records start without usage and receive it through terminal rereads. Rereading lasts up to 30 seconds from query registration, scheduled every 2 seconds for at most 16 pending tasks per batch. Final aggregation requires all expected child identities and thread usage, with child threads ended. After usage is obtained, further updates are accepted until the deadline; incomplete reads preserve the existing value. Expiry removes the query, leaving records without usage empty. Late child associations join only their root turn, without affecting subsequent turns. Terminal state, notifications, and sleep-prevention release do not wait for token rereads.Historical replay uses its own ledger and read cursors. See [Rollout Token History](sync.md#rollout-token-history).diff --git a/Docs/en/DeveloperGuide/data-and-privacy.md b/Docs/en/DeveloperGuide/data-and-privacy.mdindex 6072575..cc5272a 100644--- a/Docs/en/DeveloperGuide/data-and-privacy.md+++ b/Docs/en/DeveloperGuide/data-and-privacy.md@@ -91,7 +91,7 @@ These reads parse structural fields including origin classification, thread andHistorical token scanning starts at the beginning of each source and then follows persisted cursors. Cloud identities use account-salted HMAC-SHA256; raw thread and turn IDs are not uploaded. See [Rollout Token History](sync.md#rollout-token-history) for fields and retention.-The live rollout reader scans backward from file tails under a budget. This reduces I/O and limits how much unrelated historical content enters process memory. Parsing DTOs declare only required fields, and `JSONDecoder` ignores everything else.+The live rollout reader initially reads up to the last 512 KiB, then consumes appended content incrementally and backfills earlier history as needed. Parsing DTOs declare only required fields, and `JSONDecoder` ignores everything else. See [Rollout Read Budget](activity-monitor.md#rollout-read-budget) for stopping conditions and budgets.### Reset Credits Detailsdiff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.mdindex a237717..a5b651d 100644--- a/Docs/en/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md@@ -81,7 +81,7 @@ When no tasks are active, `CodexActivitySnapshot.statusItemActivity(at:)` select### Separating Icon State from Tooltip State-`StatusIconState` retains activity and quota inputs. `StatusItemIconPresentation` publishes only changes to symbol name, quota, visibility, and stale state:+`StatusIconState` retains activity, quota, and `ordinaryUsageAllowed` inputs. `StatusItemIconPresentation` publishes changes to symbol name, ordinary-usage restriction state, quota, visibility, and stale state:- Minute-by-minute duration updates affect only the tooltip- Cached quota dims the symbol and arc@@ -92,7 +92,7 @@ When no tasks are active, `CodexActivitySnapshot.statusItemActivity(at:)` select- Hiding quota retains its last percentage and color for retraction; zero and unavailable quota remain distinct- Initial rendering and wake reconciliation disable transitions-A persistent SwiftUI view lives inside the native `NSStatusBarButton`, with a transparent image preserving automatic spacing. Symbols use the system foreground color. The hosting view rejects focus and hit testing, leaving mouse actions with the original button.+A persistent SwiftUI view lives inside the native `NSStatusBarButton`, with a transparent image preserving automatic spacing. When `ordinaryUsageAllowed == false`, the person and badge use pale orange adapted to light and dark appearances; `true` or an absent value uses the system foreground color. The quota arc uses colors based on the remaining percentage. The hosting view rejects focus and hit testing, leaving mouse actions with the original button.The arc and person symbol are composited with `drawingGroup()` so the quota arc keeps the same length and color when switching between full-screen and regular desktops.@@ -166,7 +166,7 @@ The main panel root view uses a fixed width and its ideal content height. The poThe activity card and Task Center share `CodexActivityStatusText`, whose color follows task state. Running text shimmers, approval-waiting text emits orange particles, and completed or terminated text stays static. Status-text animations in the card use `mainPanelAnimationsEnabled`; those in Task Center require both `presentationState.isPresented` and `MainPanelSettings.areAnimationsEnabled`. Each panel shares one particle timeline, emits only from visible waiting text, clips particles to the panel bounds, and removes the timeline when no emitters remain.-The activity card shows token metrics and a divider when `primaryActivity.tokenUsage` is available. The status row stays anchored at the top, and the card height adjusts as the token area appears or disappears.+The activity card shows token metrics and a divider when `primaryActivity.tokenUsage` is available, hiding the entire usage area when it is absent. Usage rereads after completion or termination run in the background: the UI shows the terminal state first and expands the metrics when usage arrives, without a timeout message on expiry. Completed and terminated entries in Task Center show total tokens only when usage is available. The status row stays anchored at the top, and the card height adjusts as the token area appears or disappears.Expansion and collapse use a smooth, decelerating transition, independently of Animation Effects. The token area fades in and moves slightly upward with expansion progress, and fades out early during collapse. `ActivityCardHeight` commits the interpolated layout height on every animation frame so adjacent sections and the main panel resize together. Animations for the sleep-prevention badge, anonymous-task icon, and concurrent-task count are scoped to the status row.diff --git a/Docs/en/UserGuide/main-panel.md b/Docs/en/UserGuide/main-panel.mdindex aade47a..496dfed 100644--- a/Docs/en/UserGuide/main-panel.md+++ b/Docs/en/UserGuide/main-panel.md@@ -9,6 +9,7 @@ CodexBar combines a person symbol with an optional circular rate-limit arc:| Appearance | Meaning || --- | --- || Plain person | Default or idle state |+| Pale orange person and badge | Account data indicates ordinary usage is restricted || Slashed person | You are signed out, initialization failed, or trusted rate-limit and usage data is unavailable || Clock badge | At least one task is running || Key badge | At least one task is waiting for approval |@@ -31,7 +32,7 @@ Reorder and show or hide sections in `Settings > General > Main Panel Layout`, w## Account- Shows the signed-in account or account type-- Identifies Enterprise, Team, Business, Pro, Plus, Edu, and Free plans+- Identifies Enterprise, Team, Business, ProMax, Pro, ProLite, Plus, Go, Edu, and Free plans- Double-clicking the account icon refreshes account, rate-limit, and usage data immediately- Double-clicking the email toggles blurring- Shows `Not signed in` when no account is signed in@@ -121,7 +122,7 @@ Click a populated activity card to open Task Center. In both views, status-textOnce rollout usage is available, the activity card shows token metrics beneath its status, including totals, input and output, cache usage, and reasoning output. Counts use K/M/B units. The usage row and its divider expand or collapse together, independently of `Animation Effects`. Both remain hidden when usage is unavailable.-While a task is running or waiting for approval, usage updates for main and child threads whose ownership is confirmed. Later thread records fill in the subtotal. Completed and terminated tasks briefly reread turn usage and display it once a complete total is available. Later temporary read failures preserve the usage already obtained for the ended task. These values cover the current turn and its subagents, rather than the entire conversation.+While a task is running or waiting for approval, usage updates for main and child threads whose ownership is confirmed. Later thread records fill in the subtotal. After completion or termination is confirmed, background usage queries run for up to 30 seconds, displaying a complete total when available and accepting updates until the deadline. The terminal state appears immediately, without a query countdown or loading indicator. If usage is still unavailable at expiry, the usage area stays hidden; values already obtained remain visible. These values cover the current turn and its subagents.Total equals input plus output. Cached input and cache write are included in input; reasoning is included in output. These subsets must not be added to the total again. Cache-H is cached input divided by input; the card shows `—` when input is zero. Cached shows the number of input tokens served from cache; Cache-W shows cache writes.diff --git a/appcast.xml b/appcast.xmlindex 70cddf4..40c8909 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.1.1</title>+ <sparkle:version>111</sparkle:version>+ <sparkle:shortVersionString>4.1.1</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#4.1.1</sparkle:releaseNotesLink>+ <pubDate>Fri, 02 Oct 2026 10:13:14 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v4.1.1.dmg" sparkle:edSignature="wpehOsAWbi0uDAGMSTqtSQAHjvp5BDuKF1NBrhnvWsUqyZWVQm1RItIVmoIgJOSx6Zre3+rZW1jFtE8VBgiUBA==" length="8765952" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 4.1.0</title><sparkle:version>110</sparkle:version>