cc-pets 1.2.9 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -357,11 +357,37 @@ static NSDictionary *LatestUsageInData(NSData *data, NSNumber **outExhaustedAt)
357
357
  return usage;
358
358
  }
359
359
 
360
+ // 「本月 / 上月同期」只有 API 展示模式要用。让默认的订阅视图也回溯到上月月初,等于把上个月
361
+ // 的全部会话白解析一遍:本机实测冷启动 7s vs 0.7s,扫描的文件数 327 vs 61。因此按每家自己的
362
+ // 展示模式决定回溯多远,两家的读取窗口互不牵连。
363
+ static BOOL ProviderShowsAPIUsage(NSString *preferenceKey) {
364
+ return [[NSUserDefaults.standardUserDefaults stringForKey:preferenceKey] isEqualToString:@"api"];
365
+ }
366
+
360
367
  // resets_at 恒在未来,因此 7 天窗口的起点不可能早于 now - 7d;再留一天覆盖时区和跨日边界。
361
- static NSTimeInterval EarliestTokenWindowStart(void) {
368
+ // 这是所有模式的下限:订阅视图只要这么多,API 视图的月窗口在月初也可能比它还窄。
369
+ static NSTimeInterval RollingTokenWindowFloor(void) {
362
370
  return NSDate.date.timeIntervalSince1970 - 8 * 86400.0;
363
371
  }
364
372
 
373
+ // 本月 1 日 00:00。
374
+ static NSDate *CurrentMonthStartDate(void) {
375
+ NSCalendar *calendar = NSCalendar.currentCalendar;
376
+ NSDate *now = NSDate.date;
377
+ NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth
378
+ fromDate:now];
379
+ components.day = 1;
380
+ return [calendar dateFromComponents:components] ?: [calendar startOfDayForDate:now];
381
+ }
382
+
383
+ // 归档的键:本机时区的 YYYY-MM。
384
+ static NSString *MonthArchiveKey(NSTimeInterval monthStart) {
385
+ NSDateComponents *components = [NSCalendar.currentCalendar
386
+ components:NSCalendarUnitYear | NSCalendarUnitMonth
387
+ fromDate:[NSDate dateWithTimeIntervalSince1970:monthStart]];
388
+ return [NSString stringWithFormat:@"%04ld-%02ld", (long)components.year, (long)components.month];
389
+ }
390
+
365
391
  // 目录名是本机时区的 YYYY/MM/DD。解析不出日期时返回 0,调用方据此放弃剪枝而不是误删。
366
392
  static NSTimeInterval DayDirectoryEnd(NSURL *year, NSURL *month, NSURL *day) {
367
393
  NSDateComponents *components = [NSDateComponents new];
@@ -372,12 +398,14 @@ static NSTimeInterval DayDirectoryEnd(NSURL *year, NSURL *month, NSURL *day) {
372
398
  return date ? date.timeIntervalSince1970 + 86400.0 : 0;
373
399
  }
374
400
 
375
- static NSArray<NSURL *> *RecentCodexSessionURLs(NSURL *sessionsURL) {
401
+ // earliest 由调用方按当前口径算好:订阅视图是 8 天,API 视图是本月 1 日(上月已归档)或
402
+ // 上月 1 日(还没归档,要扫一次把归档建出来),三者都不会早于 8 天下限。
403
+ static NSArray<NSURL *> *RecentCodexSessionURLs(NSURL *sessionsURL, NSTimeInterval earliest) {
376
404
  NSMutableArray<NSURL *> *urls = [NSMutableArray array];
377
405
  NSUInteger examinedDays = 0;
378
- // 7 天窗口最多横跨 8 个自然日,多留一天处理时区边界。
379
- const NSUInteger maximumTokenDays = 9;
380
- const NSTimeInterval earliest = EarliestTokenWindowStart();
406
+ // 目录个数的上限跟着时间窗口走,再多留几天处理时区边界和异常目录。
407
+ const NSUInteger maximumTokenDays =
408
+ (NSUInteger)ceil((NSDate.date.timeIntervalSince1970 - earliest) / 86400.0) + 3;
381
409
  for (NSURL *year in DescendingNumericSubdirectories(sessionsURL)) {
382
410
  for (NSURL *month in DescendingNumericSubdirectories(year)) {
383
411
  for (NSURL *day in DescendingNumericSubdirectories(month)) {
@@ -426,7 +454,10 @@ static BOOL UsageHasLiveWindow(NSDictionary *usage) {
426
454
  // 而新会话在第一次拿到限流响应之前一条都不写,冷启动正好撞上就会整块空白。
427
455
  // 只接受 resets_at 还没到的窗口,免得把过期的百分比当成当前值。
428
456
  static NSDictionary *LatestQuotaInRecentSessions(NSURL *sessionsURL, NSURL *skipURL) {
429
- NSArray<NSURL *> *urls = [RecentCodexSessionURLs(sessionsURL) sortedArrayUsingComparator:
457
+ // 找的是"最近一次额度快照",按 mtime 排完只看前 8 个文件,没有必要把上个月的会话
458
+ // 也列出来再排一遍序,因此这里固定用窄窗口。
459
+ NSArray<NSURL *> *urls = [RecentCodexSessionURLs(sessionsURL, RollingTokenWindowFloor())
460
+ sortedArrayUsingComparator:
430
461
  ^NSComparisonResult(NSURL *left, NSURL *right) {
431
462
  NSDate *leftDate = nil, *rightDate = nil;
432
463
  [left getResourceValue:&leftDate forKey:NSURLContentModificationDateKey error:nil];
@@ -514,8 +545,26 @@ static NSDictionary *SummedSegmentTotals(NSArray<NSDictionary *> *segments) {
514
545
  return total;
515
546
  }
516
547
 
548
+ // 日桶除 Token 字段外还带 request_count,合并时要一起累加。
549
+ static void AddDailyTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
550
+ AddTokenCounts(target, counts);
551
+ if (!counts[@"request_count"]) return;
552
+ target[@"request_count"] = @([target[@"request_count"] unsignedLongLongValue] +
553
+ [counts[@"request_count"] unsignedLongLongValue]);
554
+ }
555
+
556
+ static NSString *DayBucketKey(NSTimeInterval dayStart) {
557
+ return [NSString stringWithFormat:@"%.0f", dayStart];
558
+ }
559
+
560
+ static NSDictionary *TokenCountsBySubtracting(NSDictionary *totals, NSDictionary *baseline);
561
+
517
562
  // 分段必须整篇扫描(末行 total 不再够用),因此改成按偏移增量追读:活跃会话每轮只解析
518
563
  // 新增的那几行,段状态(各段末尾的累计值)留在缓存里续接。
564
+ //
565
+ // 解析时顺手把每条记录的增量摊到它所属的自然日(summary[@"days"])。API 视图要画一个月的
566
+ // 日曲线,如果改成按天各扫一遍窗口,跨天会话会被 PartialTokenTotals 整篇重读 31 次——
567
+ // 实测本机每次刷新要多花 130ms,全落在主线程上,悬停时连拖动都会卡住。
519
568
  static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache) {
520
569
  NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:url.path error:nil];
521
570
  unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
@@ -528,8 +577,11 @@ static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache)
528
577
 
529
578
  unsigned long long offset = 0;
530
579
  NSMutableArray<NSDictionary *> *segments = [NSMutableArray array];
580
+ NSMutableArray<NSNumber *> *requestTimestamps = [NSMutableArray array];
581
+ NSMutableDictionary<NSString *, NSMutableDictionary *> *days = [NSMutableDictionary dictionary];
531
582
  __block NSNumber *start = nil;
532
583
  __block NSTimeInterval last = 0;
584
+ __block NSDictionary *lastRequestTotal = nil;
533
585
  if (cached) {
534
586
  unsigned long long cachedOffset = [cached[@"offset"] unsignedLongLongValue];
535
587
  // offset > size 只可能是文件被改写(截断/重建),旧的段全部作废,整篇重来。
@@ -540,9 +592,23 @@ static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache)
540
592
  if ([cached[@"segments"] isKindOfClass:NSArray.class]) {
541
593
  [segments addObjectsFromArray:cached[@"segments"]];
542
594
  }
595
+ if ([cached[@"requestTimestamps"] isKindOfClass:NSArray.class]) {
596
+ [requestTimestamps addObjectsFromArray:cached[@"requestTimestamps"]];
597
+ }
598
+ if ([cached[@"days"] isKindOfClass:NSDictionary.class]) {
599
+ for (NSString *key in (NSDictionary *)cached[@"days"]) {
600
+ days[key] = [cached[@"days"][key] mutableCopy];
601
+ }
602
+ }
603
+ lastRequestTotal = [cached[@"lastRequestTotal"] isKindOfClass:NSDictionary.class]
604
+ ? cached[@"lastRequestTotal"] : nil;
543
605
  }
544
606
  }
545
607
 
608
+ NSCalendar *calendar = NSCalendar.currentCalendar;
609
+ // 会话内记录是按时间递增写入的,日边界只在跨天那一条上重算,不必每条都问日历。
610
+ __block NSTimeInterval bucketStart = 0;
611
+ __block NSTimeInterval bucketEnd = 0;
546
612
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
547
613
  if (!handle) return nil;
548
614
  if (offset > 0) [handle seekToFileOffset:offset];
@@ -557,6 +623,31 @@ static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache)
557
623
  NSDictionary *total = record[@"total"];
558
624
  if (!total) return;
559
625
  last = [record[@"timestamp"] doubleValue];
626
+ // Codex 会重复写同一份累计快照,事件行数不能直接当调用次数。累计值发生变化才代表
627
+ // 一次新的模型响应;上下文压缩导致累计值归零时同样会被识别为新响应。
628
+ BOOL newRequest = !lastRequestTotal || ![total isEqualToDictionary:lastRequestTotal];
629
+ if (newRequest) [requestTimestamps addObject:record[@"timestamp"]];
630
+ // 段内用累计值相减、归零时整份计入,与 TokenSessionSummary 的分段口径一致:
631
+ // 逐条增量相加会收敛回段末的累计值,因此日桶之和等于 summary[@"total"]。
632
+ NSDictionary *increment = TokenCountsBySubtracting(total, lastRequestTotal);
633
+ if (last < bucketStart || last >= bucketEnd) {
634
+ NSDate *dayStart = [calendar startOfDayForDate:[NSDate dateWithTimeIntervalSince1970:last]];
635
+ NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:dayStart
636
+ options:0];
637
+ bucketStart = dayStart.timeIntervalSince1970;
638
+ bucketEnd = (next ?: [dayStart dateByAddingTimeInterval:86400]).timeIntervalSince1970;
639
+ }
640
+ NSString *dayKey = DayBucketKey(bucketStart);
641
+ NSMutableDictionary *bucket = days[dayKey];
642
+ if (!bucket) {
643
+ bucket = [NSMutableDictionary dictionary];
644
+ days[dayKey] = bucket;
645
+ }
646
+ AddTokenCounts(bucket, increment);
647
+ if (newRequest) {
648
+ bucket[@"request_count"] = @([bucket[@"request_count"] unsignedLongLongValue] + 1);
649
+ }
650
+ lastRequestTotal = total;
560
651
  NSDictionary *previous = segments.lastObject;
561
652
  if (!previous || TokenTotalsDidReset(total, previous)) [segments addObject:total];
562
653
  else segments[segments.count - 1] = total;
@@ -569,6 +660,12 @@ static NSDictionary *TokenSessionSummary(NSURL *url, NSMutableDictionary *cache)
569
660
  summary[@"segments"] = [segments copy];
570
661
  summary[@"end"] = @(last);
571
662
  summary[@"total"] = SummedSegmentTotals(segments);
663
+ summary[@"requestTimestamps"] = [requestTimestamps copy];
664
+ // 冻结成不可变,避免下一轮增量追读时改到已经交给调用方的那份。
665
+ NSMutableDictionary *frozenDays = [NSMutableDictionary dictionaryWithCapacity:days.count];
666
+ for (NSString *key in days) frozenDays[key] = [days[key] copy];
667
+ summary[@"days"] = [frozenDays copy];
668
+ if (lastRequestTotal) summary[@"lastRequestTotal"] = lastRequestTotal;
572
669
  }
573
670
  cache[url.path] = summary;
574
671
  return (start && summary[@"total"]) ? summary : nil;
@@ -684,14 +781,59 @@ static void RollingTokenWindows(NSTimeInterval *todayStart, NSTimeInterval *week
684
781
  }
685
782
  }
686
783
 
784
+ // 自然月窗口。本月是 1 日 00:00 起算,展示区间到"此刻",曲线区间到月底。
785
+ //
786
+ // 同比区间两边都只数到"最后一个完整的自然日":本月 1 日至今日 00:00,对比上月 1 日至上月
787
+ // 第 N 日 00:00(N = 本月已过完的整日数)。刻意不做到同一时刻——上月的数据来自日粒度的
788
+ // 归档,切不出"14 日 15:30"这种半天;而月度同比本来就是趋势判断,差半天换来"上月的会话
789
+ // 文件一次都不用再打开",这笔账是划算的。上月天数不够时(3 月 31 日对比 2 月)封顶到上月末。
790
+ static NSDictionary *CalendarMonthWindows(NSTimeInterval alignedEnd) {
791
+ NSCalendar *calendar = NSCalendar.currentCalendar;
792
+ NSDate *now = NSDate.date;
793
+ NSDate *monthStart = CurrentMonthStartDate();
794
+ NSDate *nextMonthStart = [calendar dateByAddingUnit:NSCalendarUnitMonth value:1
795
+ toDate:monthStart options:0] ?: now;
796
+ NSDate *previousMonthStart = [calendar dateByAddingUnit:NSCalendarUnitMonth value:-1
797
+ toDate:monthStart options:0] ?: monthStart;
798
+ NSDate *todayStart = [calendar startOfDayForDate:now];
799
+ NSInteger elapsedDays = [calendar components:NSCalendarUnitDay fromDate:monthStart
800
+ toDate:todayStart options:0].day;
801
+ if (elapsedDays < 0) elapsedDays = 0;
802
+ NSDate *previousComparableEnd = [calendar dateByAddingUnit:NSCalendarUnitDay
803
+ value:(int)elapsedDays toDate:previousMonthStart options:0] ?: previousMonthStart;
804
+ NSTimeInterval currentStart = monthStart.timeIntervalSince1970;
805
+ return @{ @"monthStart": @(currentStart),
806
+ @"monthEnd": @(fmin(alignedEnd, nextMonthStart.timeIntervalSince1970)),
807
+ @"monthCurveEnd": @(nextMonthStart.timeIntervalSince1970),
808
+ // 每月 1 号这一天 todayStart == monthStart,同比区间两边都是空的,比出来是"持平"。
809
+ @"monthComparableEnd": @(todayStart.timeIntervalSince1970),
810
+ @"previousMonthStart": @(previousMonthStart.timeIntervalSince1970),
811
+ @"previousMonthEnd": @(fmin(currentStart,
812
+ previousComparableEnd.timeIntervalSince1970)) };
813
+ }
814
+
687
815
  static NSString *PartialTokenKey(NSTimeInterval start, NSTimeInterval end) {
688
816
  return [NSString stringWithFormat:@"partial-%.0f-%.0f", start, end];
689
817
  }
690
818
 
819
+ // requestTimestamps 按写入顺序递增,取区间计数用二分即可:逐条比较要在每个窗口上把
820
+ // 所有会话的时间戳全走一遍,窗口一多就成了主线程上的固定开销。
821
+ static NSUInteger TimestampLowerBound(NSArray<NSNumber *> *timestamps, NSTimeInterval value) {
822
+ NSUInteger low = 0;
823
+ NSUInteger high = timestamps.count;
824
+ while (low < high) {
825
+ NSUInteger middle = low + (high - low) / 2;
826
+ if (timestamps[middle].doubleValue < value) low = middle + 1;
827
+ else high = middle;
828
+ }
829
+ return low;
830
+ }
831
+
691
832
  static NSDictionary *TokenTotalsInWindow(NSTimeInterval start, NSTimeInterval end,
692
833
  NSArray<NSURL *> *urls, NSMutableDictionary *cache) {
693
834
  NSMutableDictionary *totals = [NSMutableDictionary dictionary];
694
835
  BOOL hasTokenSchema = NO;
836
+ unsigned long long requestCount = 0;
695
837
  for (NSURL *url in urls) {
696
838
  NSMutableDictionary *summary = [(NSDictionary *)TokenSessionSummary(url, cache) mutableCopy];
697
839
  if (!summary) continue;
@@ -699,6 +841,10 @@ static NSDictionary *TokenTotalsInWindow(NSTimeInterval start, NSTimeInterval en
699
841
  NSTimeInterval sessionStart = [summary[@"start"] doubleValue];
700
842
  NSTimeInterval sessionEnd = [summary[@"end"] doubleValue];
701
843
  if (sessionEnd < start || sessionStart >= end) continue;
844
+ NSArray<NSNumber *> *timestamps = [summary[@"requestTimestamps"] isKindOfClass:NSArray.class]
845
+ ? summary[@"requestTimestamps"] : @[];
846
+ requestCount += TimestampLowerBound(timestamps, end) -
847
+ TimestampLowerBound(timestamps, start);
702
848
  if (sessionStart >= start) {
703
849
  AddTokenCounts(totals, summary[@"total"]);
704
850
  continue;
@@ -717,6 +863,7 @@ static NSDictionary *TokenTotalsInWindow(NSTimeInterval start, NSTimeInterval en
717
863
  if (totals.count == 0) {
718
864
  for (NSString *key in TokenKeys()) totals[key] = @0;
719
865
  }
866
+ totals[@"request_count"] = @(requestCount);
720
867
  return totals;
721
868
  }
722
869
 
@@ -728,6 +875,67 @@ static NSDictionary *TokenTotalsForQuota(NSDictionary *quota, double fallbackMin
728
875
  return TokenTotalsInWindow(start, end, urls, cache);
729
876
  }
730
877
 
878
+ // 日曲线直接汇总各会话解析时就分好的日桶:一天一次窗口聚合会让跨天会话被整篇重读,
879
+ // 而日桶只是遍历一遍缓存里的小字典。
880
+ static NSArray<NSDictionary *> *CodexDailyTokenSeries(NSTimeInterval start, NSTimeInterval end,
881
+ NSArray<NSURL *> *urls, NSMutableDictionary *cache, BOOL *outHasTokenSchema) {
882
+ NSCalendar *calendar = NSCalendar.currentCalendar;
883
+ NSMutableArray<NSNumber *> *dayStarts = [NSMutableArray array];
884
+ NSMutableDictionary<NSString *, NSMutableDictionary *> *buckets = [NSMutableDictionary dictionary];
885
+ NSDate *cursor = [calendar startOfDayForDate:[NSDate dateWithTimeIntervalSince1970:start]];
886
+ while (cursor.timeIntervalSince1970 < end) {
887
+ NSTimeInterval dayStart = cursor.timeIntervalSince1970;
888
+ if (dayStart >= start) {
889
+ [dayStarts addObject:@(dayStart)];
890
+ buckets[DayBucketKey(dayStart)] = [NSMutableDictionary dictionary];
891
+ }
892
+ NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:cursor options:0];
893
+ if (!next) break;
894
+ cursor = next;
895
+ }
896
+ for (NSURL *url in urls) {
897
+ NSDictionary *summary = TokenSessionSummary(url, cache);
898
+ NSDictionary *days = [summary[@"days"] isKindOfClass:NSDictionary.class]
899
+ ? summary[@"days"] : nil;
900
+ if (days && outHasTokenSchema) *outHasTokenSchema = YES;
901
+ for (NSString *key in days) {
902
+ NSMutableDictionary *bucket = buckets[key];
903
+ if (bucket) AddDailyTokenCounts(bucket, days[key]);
904
+ }
905
+ }
906
+ NSMutableArray<NSDictionary *> *series = [NSMutableArray arrayWithCapacity:dayStarts.count];
907
+ for (NSNumber *dayStart in dayStarts) {
908
+ NSMutableDictionary *bucket = buckets[DayBucketKey(dayStart.doubleValue)];
909
+ // 没有任何记录的那天是真实的 0,不能留成空字典让调用方当"无数据"。
910
+ for (NSString *key in TokenKeys()) if (!bucket[key]) bucket[key] = @0;
911
+ if (!bucket[@"request_count"]) bucket[@"request_count"] = @0;
912
+ [series addObject:@{ @"timestamp": dayStart, @"totals": [bucket copy] }];
913
+ }
914
+ return series;
915
+ }
916
+
917
+ // 本月至今的窗口起点是自然日零点、终点在未来(对齐到 10 分钟的"现在"),窗口内不可能有
918
+ // 半天,所以日桶之和与按窗口聚合逐字节等价——省掉一遍对全部会话的窗口扫描。
919
+ // 上月同期的终点落在某天中间,仍然要走 TokenTotalsInWindow。
920
+ static NSDictionary *SummedDailyTokenSeries(NSArray<NSDictionary *> *series) {
921
+ NSMutableDictionary *totals = [NSMutableDictionary dictionary];
922
+ for (NSDictionary *day in series) AddDailyTokenCounts(totals, day[@"totals"]);
923
+ for (NSString *key in TokenKeys()) if (!totals[key]) totals[key] = @0;
924
+ if (!totals[@"request_count"]) totals[@"request_count"] = @0;
925
+ return totals;
926
+ }
927
+
928
+ // 日序列里 [start, end) 之间那几天的合计。同比两侧都靠它切出"到最后一个完整自然日为止"。
929
+ static NSDictionary *SummedDailyTokenSeriesInRange(NSArray<NSDictionary *> *series,
930
+ NSTimeInterval start, NSTimeInterval end) {
931
+ NSMutableArray<NSDictionary *> *slice = [NSMutableArray array];
932
+ for (NSDictionary *day in series) {
933
+ NSTimeInterval timestamp = [day[@"timestamp"] doubleValue];
934
+ if (timestamp >= start && timestamp < end) [slice addObject:day];
935
+ }
936
+ return SummedDailyTokenSeries(slice);
937
+ }
938
+
731
939
  // 会话滚出 7 天窗口、额度窗口滚动之后,缓存里对应的条目和 partial-* 分片再也不会被读到。
732
940
  // 常驻进程不清理就是只增不减。
733
941
  static void PruneTokenCache(NSMutableDictionary *cache, NSArray<NSURL *> *urls,
@@ -750,11 +958,108 @@ static void PruneTokenCache(NSMutableDictionary *cache, NSArray<NSURL *> *urls,
750
958
  }
751
959
  }
752
960
 
961
+ // 摘要缓存落盘/读回。二进制 plist:内容全是 NSNumber / NSString / NSData / 容器,
962
+ // 写入走临时文件 + 替换,中途崩溃不会留下半个文件。缓存丢失或格式不对只意味着重新解析一遍,
963
+ // 因此所有失败路径都是静默降级。
964
+ static NSMutableDictionary *LoadTokenSummaryCache(NSString *path) {
965
+ NSData *data = [NSData dataWithContentsOfFile:path];
966
+ if (!data) return [NSMutableDictionary dictionary];
967
+ id root = [NSPropertyListSerialization propertyListWithData:data
968
+ options:NSPropertyListMutableContainers format:NULL error:NULL];
969
+ if (![root isKindOfClass:NSMutableDictionary.class]) return [NSMutableDictionary dictionary];
970
+ // 条目形如 路径 -> 摘要字典。别的形状一律丢掉,后面的代码不必再防一遍。
971
+ NSMutableDictionary *cache = root;
972
+ for (NSString *key in cache.allKeys) {
973
+ if (![key isKindOfClass:NSString.class] ||
974
+ ![cache[key] isKindOfClass:NSDictionary.class]) {
975
+ [cache removeObjectForKey:key];
976
+ }
977
+ }
978
+ return cache;
979
+ }
980
+
981
+ // NSData 是类簇,可变性判断不能靠 isKindOfClass:二进制 plist 解析出来的**不可变**
982
+ // __NSCFData 对 isKindOfClass:NSMutableData 同样返回 YES。据此把只读缓冲区当成可变的
983
+ // 原地 appendBytes,就会写到它末尾之外——ASan 抓到的正是这一下:
984
+ // heap-buffer-overflow, WRITE of size 48, 0 bytes after 6640-byte region
985
+ // 分配点 __CFBinaryPlistCreateObjectFiltered <- LoadTokenSummaryCache
986
+ // 越界写破坏堆之后进程不会当场死,而是在之后任意一次内存操作上倒下,因此崩溃点看起来
987
+ // 和这里毫无关系(实际报告里落在 EnumerateLines 和 SaveTokenSummaryCache 上)。
988
+ //
989
+ // 可靠的做法只有一条:落盘缓存一读回来就把 records 换成本进程创建的可变副本,
990
+ // 之后 ClaudeRecordsForFile 的原地追加才成立。只替换 records,其余字段原样保留——
991
+ // Codex 侧的条目形状不同(start/total/segments/days…),整条重建会把它们抹掉。
992
+ static void MakeCachedRecordsMutable(NSMutableDictionary *cache) {
993
+ for (NSString *path in cache.allKeys) {
994
+ NSDictionary *entry = cache[path];
995
+ if (![entry isKindOfClass:NSDictionary.class]) continue;
996
+ NSData *records = [entry[@"records"] isKindOfClass:NSData.class] ? entry[@"records"] : nil;
997
+ if (!records) continue;
998
+ NSMutableDictionary *updated = [entry mutableCopy];
999
+ updated[@"records"] = [records mutableCopy];
1000
+ cache[path] = updated;
1001
+ }
1002
+ }
1003
+
1004
+ static void SaveTokenSummaryCache(NSDictionary *cache, NSString *path) {
1005
+ if (!path.length) return;
1006
+ NSData *data = [NSPropertyListSerialization dataWithPropertyList:cache
1007
+ format:NSPropertyListBinaryFormat_v1_0 options:0 error:NULL];
1008
+ if (!data) return;
1009
+ NSString *temporary = [path stringByAppendingPathExtension:@"tmp"];
1010
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
1011
+ withIntermediateDirectories:YES attributes:nil error:nil];
1012
+ if (![data writeToFile:temporary atomically:NO]) return;
1013
+ NSURL *destination = [NSURL fileURLWithPath:path];
1014
+ if (![NSFileManager.defaultManager replaceItemAtURL:destination
1015
+ withItemAtURL:[NSURL fileURLWithPath:temporary] backupItemName:nil options:0
1016
+ resultingItemURL:NULL error:NULL]) {
1017
+ // 目标还不存在时 replaceItemAtURL 会失败,这时直接搬过去。
1018
+ [NSFileManager.defaultManager removeItemAtPath:path error:nil];
1019
+ if (![NSFileManager.defaultManager moveItemAtPath:temporary toPath:path error:nil]) {
1020
+ [NSFileManager.defaultManager removeItemAtPath:temporary error:nil];
1021
+ }
1022
+ }
1023
+ }
1024
+
1025
+ // 归档只用来做"上月同期"对比,留着更早的月份没有意义。保留 3 个月是给跨月那一下留余量,
1026
+ // 顺带在时区/系统时间被改回去时还能命中。
1027
+ static void PruneMonthlyArchive(NSMutableDictionary *archive) {
1028
+ NSCalendar *calendar = NSCalendar.currentCalendar;
1029
+ NSDate *monthStart = CurrentMonthStartDate();
1030
+ NSDate *oldest = [calendar dateByAddingUnit:NSCalendarUnitMonth value:-3 toDate:monthStart
1031
+ options:0] ?: monthStart;
1032
+ NSString *oldestKey = MonthArchiveKey(oldest.timeIntervalSince1970);
1033
+ for (NSString *key in archive.allKeys) {
1034
+ if ([key compare:oldestKey] == NSOrderedAscending) [archive removeObjectForKey:key];
1035
+ }
1036
+ }
1037
+
753
1038
  // 一份额度都没拿到时也照样统计 Token:Token 是本机数出来的,不该因为官方额度缺失就空着。
1039
+ //
1040
+ // archive 是"已结束自然月"的归档(见 MonthlyUsageArchivePath)。上月一旦归档,扫描范围就
1041
+ // 收窄到本月,上月的会话文件再也不会被打开;archiveChanged 置位表示这一轮新写了归档,
1042
+ // 调用方据此落盘。
754
1043
  static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessionsURL,
755
- NSMutableDictionary *cache) {
1044
+ NSMutableDictionary *cache, NSMutableDictionary *archive, BOOL *archiveChanged) {
756
1045
  if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
757
- NSArray<NSURL *> *urls = RecentCodexSessionURLs(sessionsURL);
1046
+ BOOL apiMode = ProviderShowsAPIUsage(CodexUsageDisplayModeKey);
1047
+ NSTimeInterval rollingFloor = RollingTokenWindowFloor();
1048
+ NSDictionary *monthWindows = CalendarMonthWindows(0);
1049
+ NSTimeInterval monthStart = [monthWindows[@"monthStart"] doubleValue];
1050
+ NSTimeInterval monthCurveEnd = [monthWindows[@"monthCurveEnd"] doubleValue];
1051
+ NSTimeInterval monthComparableEnd = [monthWindows[@"monthComparableEnd"] doubleValue];
1052
+ NSTimeInterval previousMonthStart = [monthWindows[@"previousMonthStart"] doubleValue];
1053
+ NSTimeInterval previousMonthEnd = [monthWindows[@"previousMonthEnd"] doubleValue];
1054
+ NSString *previousMonthKey = MonthArchiveKey(previousMonthStart);
1055
+ NSArray<NSDictionary *> *archivedDaily = apiMode &&
1056
+ [archive[previousMonthKey][@"daily"] isKindOfClass:NSArray.class]
1057
+ ? archive[previousMonthKey][@"daily"] : nil;
1058
+ // 上月还没归档时才把扫描范围放宽到上月月初,而且只放宽这一次。
1059
+ BOOL buildsArchive = apiMode && !archivedDaily;
1060
+ NSTimeInterval earliest = buildsArchive ? previousMonthStart
1061
+ : (apiMode ? fmin(monthStart, rollingFloor) : rollingFloor);
1062
+ NSArray<NSURL *> *urls = RecentCodexSessionURLs(sessionsURL, earliest);
758
1063
  NSDictionary *five = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
759
1064
  ? usage[@"fiveHour"] : nil;
760
1065
  NSDictionary *week = [usage[@"week"] isKindOfClass:NSDictionary.class] ? usage[@"week"] : nil;
@@ -764,6 +1069,25 @@ static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessio
764
1069
  RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
765
1070
  NSDictionary *todayTokens = TokenTotalsInWindow(todayStart, rollingEnd, urls, cache);
766
1071
  NSDictionary *recentTokens = TokenTotalsInWindow(rollingWeekStart, rollingEnd, urls, cache);
1072
+ // 订阅视图不看月度数据,连算都不必算:会话列表本来就只回溯 8 天,月窗口只会得到
1073
+ // 一段被截断的假数据,而代价是每次刷新多遍历一遍全部会话。
1074
+ BOOL hasDailySchema = NO;
1075
+ // 曲线铺满整个自然月:末尾这些还没到的日子是货真价实的 0,读者能一眼看出月份过了多少。
1076
+ NSArray *monthDaily = apiMode
1077
+ ? CodexDailyTokenSeries(monthStart, monthCurveEnd, urls, cache, &hasDailySchema) : @[];
1078
+ NSDictionary *monthTokens = hasDailySchema ? SummedDailyTokenSeries(monthDaily) : nil;
1079
+ NSDictionary *monthComparable = hasDailySchema
1080
+ ? SummedDailyTokenSeriesInRange(monthDaily, monthStart, monthComparableEnd) : nil;
1081
+ if (buildsArchive) {
1082
+ NSArray *previousDaily = CodexDailyTokenSeries(previousMonthStart, monthStart,
1083
+ urls, cache, NULL);
1084
+ archive[previousMonthKey] = @{ @"daily": previousDaily,
1085
+ @"totals": SummedDailyTokenSeries(previousDaily) };
1086
+ archivedDaily = previousDaily;
1087
+ if (archiveChanged) *archiveChanged = YES;
1088
+ }
1089
+ NSDictionary *previousMonthTokens = archivedDaily
1090
+ ? SummedDailyTokenSeriesInRange(archivedDaily, previousMonthStart, previousMonthEnd) : nil;
767
1091
  NSMutableSet<NSString *> *liveWindowKeys = [NSMutableSet setWithArray:@[
768
1092
  PartialTokenKey(todayStart, rollingEnd), PartialTokenKey(rollingWeekStart, rollingEnd)]];
769
1093
  NSArray<NSDictionary *> *windows = @[
@@ -784,6 +1108,14 @@ static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessio
784
1108
  @"today": todayTokens ?: NSNull.null,
785
1109
  @"recentWeek": recentTokens ?: NSNull.null,
786
1110
  @"recentWeekStartsAt": @(rollingWeekStart),
1111
+ @"month": monthTokens ?: NSNull.null,
1112
+ // 同比用的是"到最后一个完整自然日为止"的两段,与展示用的 month(含今天)不是一回事。
1113
+ @"monthComparable": monthComparable ?: NSNull.null,
1114
+ @"previousMonthToDate": previousMonthTokens ?: NSNull.null,
1115
+ @"monthDaily": monthDaily,
1116
+ @"monthStartsAt": @(monthStart),
1117
+ @"monthComparableEndsAt": @(monthComparableEnd),
1118
+ @"previousMonthComparableEndsAt": @(previousMonthEnd),
787
1119
  @"source": @"local"
788
1120
  };
789
1121
  return result;
@@ -804,7 +1136,9 @@ NSDictionary *LatestUsage(void) {
804
1136
  NSNumber *exhaustedAt = nil;
805
1137
  NSDictionary *usage = LatestUsageInData(tail, &exhaustedAt)
806
1138
  ?: LatestQuotaInRecentSessions(sessions, newest);
807
- usage = UsageByAddingTokenTotals(usage, sessions, [NSMutableDictionary dictionary]);
1139
+ // --status 这类一次性调用不带缓存也不写归档:它只需要当下这一份数字。
1140
+ usage = UsageByAddingTokenTotals(usage, sessions, [NSMutableDictionary dictionary],
1141
+ LoadTokenSummaryCache(MonthlyUsageArchivePath(@"codex", sessions.path)), NULL);
808
1142
  return UsageByMarkingExhaustion(usage, exhaustedAt.doubleValue);
809
1143
  }
810
1144
 
@@ -821,8 +1155,16 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
821
1155
  [five[@"resets_at"] doubleValue], [week[@"resets_at"] doubleValue]];
822
1156
  }
823
1157
 
1158
+ // 落盘节流:聚合本身最快 5 秒一次,缓存写盘没必要跟得那么紧。进程被 kill 而没来得及写,
1159
+ // 代价也只是下次启动多解析一段。
1160
+ static const NSTimeInterval TokenCacheSaveInterval = 60.0;
1161
+
824
1162
  @interface CodexUsageReader ()
825
1163
  @property NSMutableDictionary *tokenSummaryCache;
1164
+ @property NSString *tokenSummaryCachePath;
1165
+ @property NSTimeInterval tokenCacheSavedAt;
1166
+ @property NSMutableDictionary *monthlyArchive;
1167
+ @property NSString *monthlyArchivePath;
826
1168
  @property NSDictionary *tokenUsage;
827
1169
  @property NSString *tokenWindowIdentity;
828
1170
  @property NSTimeInterval tokenComputedAt;
@@ -835,10 +1177,21 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
835
1177
  if ((self = [super init])) {
836
1178
  _sessionsURL = CodexSessionsURL();
837
1179
  _partialLine = [NSMutableData data];
838
- _tokenSummaryCache = [NSMutableDictionary dictionary];
1180
+ _tokenSummaryCachePath = TokenSummaryCachePath(@"codex", _sessionsURL.path);
1181
+ _tokenSummaryCache = LoadTokenSummaryCache(_tokenSummaryCachePath);
1182
+ _monthlyArchivePath = MonthlyUsageArchivePath(@"codex", _sessionsURL.path);
1183
+ _monthlyArchive = LoadTokenSummaryCache(_monthlyArchivePath);
839
1184
  }
840
1185
  return self;
841
1186
  }
1187
+ // 缓存里过期的条目由 PruneTokenCache 在每次聚合里清掉,所以落盘的那份不会只增不减。
1188
+ - (void)persistTokenSummaryCacheThrottled:(BOOL)throttled {
1189
+ if (!self.persistsCache) return;
1190
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
1191
+ if (throttled && now - self.tokenCacheSavedAt < TokenCacheSaveInterval) return;
1192
+ self.tokenCacheSavedAt = now;
1193
+ SaveTokenSummaryCache(self.tokenSummaryCache, self.tokenSummaryCachePath);
1194
+ }
842
1195
  - (NSDictionary *)usageWithTokenTotals:(NSDictionary *)usage {
843
1196
  if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
844
1197
  NSString *identity = TokenWindowIdentity(usage);
@@ -851,7 +1204,14 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
851
1204
  result[@"tokenUsage"] = self.tokenUsage;
852
1205
  return UsageByMarkingExhaustion(result, self.exhaustedAt);
853
1206
  }
854
- NSDictionary *result = UsageByAddingTokenTotals(usage, self.sessionsURL, self.tokenSummaryCache);
1207
+ BOOL archiveChanged = NO;
1208
+ NSDictionary *result = UsageByAddingTokenTotals(usage, self.sessionsURL,
1209
+ self.tokenSummaryCache, self.monthlyArchive, &archiveChanged);
1210
+ if (archiveChanged) {
1211
+ PruneMonthlyArchive(self.monthlyArchive);
1212
+ if (self.persistsCache) SaveTokenSummaryCache(self.monthlyArchive, self.monthlyArchivePath);
1213
+ }
1214
+ [self persistTokenSummaryCacheThrottled:YES];
855
1215
  id tokens = result[@"tokenUsage"];
856
1216
  self.tokenUsage = [tokens isKindOfClass:NSDictionary.class] ? tokens : nil;
857
1217
  self.tokenWindowIdentity = identity;
@@ -1146,8 +1506,9 @@ static void AppendRecentTranscriptsInDirectory(NSURL *directory, NSTimeInterval
1146
1506
  // 多数子目录压根不是 subagents(本机 13 个里 7 个是 tool-results/memory)。
1147
1507
  // 不能改用 <session-uuid>/ 目录自身的 mtime 剪枝:目录 mtime 只在直接子项增删时更新,
1148
1508
  // 往已有 agent-*.jsonl 追加写不会动它,正在跑的长任务会被剪掉。
1149
- static NSArray<NSURL *> *RecentClaudeTranscriptURLs(NSURL *projectsURL) {
1150
- NSTimeInterval earliest = EarliestTokenWindowStart();
1509
+ // earliest 的口径与 RecentCodexSessionURLs 一致,由调用方按展示模式和归档状态算好。
1510
+ static NSArray<NSURL *> *RecentClaudeTranscriptURLs(NSURL *projectsURL,
1511
+ NSTimeInterval earliest) {
1151
1512
  NSArray<NSURL *> *projects = [NSFileManager.defaultManager contentsOfDirectoryAtURL:projectsURL
1152
1513
  includingPropertiesForKeys:@[NSURLIsDirectoryKey]
1153
1514
  options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
@@ -1180,13 +1541,24 @@ static NSData *ClaudeRecordsForFile(NSURL *url, NSMutableDictionary *cache) {
1180
1541
  unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
1181
1542
  NSDictionary *cached = cache[url.path];
1182
1543
  unsigned long long offset = [cached[@"offset"] unsignedLongLongValue];
1183
- NSMutableData *records = cached[@"records"];
1544
+ // 这里可以直接原地追加:可变性由 MakeCachedRecordsMutable 在缓存读回时统一保证。
1545
+ // 不要退回成 isKindOfClass:NSMutableData 判断——NSData 是类簇,落盘缓存解析出的
1546
+ // 不可变 __NSCFData 对它同样返回 YES,据此原地 appendBytes 会写出界。详见该函数注释。
1547
+ NSMutableData *records = [cached[@"records"] isKindOfClass:NSData.class]
1548
+ ? (NSMutableData *)cached[@"records"] : nil;
1184
1549
  if (!records || offset > size) {
1185
1550
  // 首次读取,或文件被改写导致偏移失效,整篇重来。
1186
1551
  offset = 0;
1187
1552
  records = [NSMutableData data];
1188
1553
  }
1189
- if (cached && offset == size) return records;
1554
+ if (cached && offset == size) {
1555
+ // 正常情况下 records 就是缓存里那一份,不必回写;只有上面因偏移失效重建过
1556
+ // (文件被清空到 0 字节)才是新对象,这时写回去,免得下一轮又重建一遍。
1557
+ if (records != cached[@"records"]) {
1558
+ cache[url.path] = @{@"offset": @(offset), @"records": records};
1559
+ }
1560
+ return records;
1561
+ }
1190
1562
 
1191
1563
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
1192
1564
  if (!handle) return records;
@@ -1258,12 +1630,33 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
1258
1630
  @"cached_input_tokens": @(cacheRead),
1259
1631
  @"cache_write_input_tokens": @(cacheWrite),
1260
1632
  @"output_tokens": @(output),
1261
- @"total_tokens": @(input + output + cacheRead + cacheWrite)
1633
+ @"total_tokens": @(input + output + cacheRead + cacheWrite),
1634
+ @"request_count": @(merged.length / sizeof(ClaudeTokenRecord))
1262
1635
  };
1263
1636
  }
1264
1637
 
1638
+ static NSArray<NSDictionary *> *ClaudeDailyTokenSeries(NSArray<NSData *> *recordSets,
1639
+ NSTimeInterval start, NSTimeInterval end) {
1640
+ NSCalendar *calendar = NSCalendar.currentCalendar;
1641
+ NSMutableArray<NSDictionary *> *series = [NSMutableArray array];
1642
+ NSDate *cursor = [NSDate dateWithTimeIntervalSince1970:start];
1643
+ while (cursor.timeIntervalSince1970 < end) {
1644
+ NSDate *next = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:cursor options:0];
1645
+ if (!next) break;
1646
+ NSTimeInterval bucketEnd = fmin(end, next.timeIntervalSince1970);
1647
+ [series addObject:@{ @"timestamp": @(cursor.timeIntervalSince1970),
1648
+ @"totals": ClaudeTokenTotals(recordSets, cursor.timeIntervalSince1970, bucketEnd) }];
1649
+ cursor = next;
1650
+ }
1651
+ return series;
1652
+ }
1653
+
1265
1654
  @interface ClaudeUsageReader ()
1266
1655
  @property NSMutableDictionary *recordCache;
1656
+ @property NSString *recordCachePath;
1657
+ @property NSTimeInterval recordCacheSavedAt;
1658
+ @property NSMutableDictionary *monthlyArchive;
1659
+ @property NSString *monthlyArchivePath;
1267
1660
  @property NSDictionary *tokenUsage;
1268
1661
  @property NSString *tokenWindowIdentity;
1269
1662
  @property NSTimeInterval tokenComputedAt;
@@ -1274,7 +1667,11 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
1274
1667
  - (instancetype)init {
1275
1668
  if ((self = [super init])) {
1276
1669
  _projectsURL = ClaudeProjectsURL();
1277
- _recordCache = [NSMutableDictionary dictionary];
1670
+ _recordCachePath = TokenSummaryCachePath(@"claude", _projectsURL.path);
1671
+ _recordCache = LoadTokenSummaryCache(_recordCachePath);
1672
+ MakeCachedRecordsMutable(_recordCache);
1673
+ _monthlyArchivePath = MonthlyUsageArchivePath(@"claude", _projectsURL.path);
1674
+ _monthlyArchive = LoadTokenSummaryCache(_monthlyArchivePath);
1278
1675
  }
1279
1676
  return self;
1280
1677
  }
@@ -1288,7 +1685,22 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
1288
1685
  TokenWindowOrFallback(five, FiveHourWindowMinutes, &fiveStart, &fiveEnd);
1289
1686
  TokenWindowOrFallback(week, SevenDayWindowMinutes, &weekStart, &weekEnd);
1290
1687
  // 自然日窗口和额度无关,即使两个额度窗口都不可用也照样统计。
1291
- NSArray<NSURL *> *urls = RecentClaudeTranscriptURLs(self.projectsURL);
1688
+ BOOL apiMode = ProviderShowsAPIUsage(ClaudeUsageDisplayModeKey);
1689
+ NSDictionary *monthWindows = CalendarMonthWindows(0);
1690
+ NSTimeInterval monthStart = [monthWindows[@"monthStart"] doubleValue];
1691
+ NSTimeInterval monthCurveEnd = [monthWindows[@"monthCurveEnd"] doubleValue];
1692
+ NSTimeInterval monthComparableEnd = [monthWindows[@"monthComparableEnd"] doubleValue];
1693
+ NSTimeInterval previousMonthStart = [monthWindows[@"previousMonthStart"] doubleValue];
1694
+ NSTimeInterval previousMonthEnd = [monthWindows[@"previousMonthEnd"] doubleValue];
1695
+ NSString *previousMonthKey = MonthArchiveKey(previousMonthStart);
1696
+ NSArray<NSDictionary *> *archivedDaily = apiMode &&
1697
+ [self.monthlyArchive[previousMonthKey][@"daily"] isKindOfClass:NSArray.class]
1698
+ ? self.monthlyArchive[previousMonthKey][@"daily"] : nil;
1699
+ // 与 Codex 侧同一套:上月归档好了就只读本月的转录,没归档才放宽一次把归档建出来。
1700
+ BOOL buildsArchive = apiMode && !archivedDaily;
1701
+ NSTimeInterval earliest = buildsArchive ? previousMonthStart
1702
+ : (apiMode ? fmin(monthStart, RollingTokenWindowFloor()) : RollingTokenWindowFloor());
1703
+ NSArray<NSURL *> *urls = RecentClaudeTranscriptURLs(self.projectsURL, earliest);
1292
1704
  NSMutableArray<NSData *> *recordSets = [NSMutableArray arrayWithCapacity:urls.count];
1293
1705
  NSMutableSet<NSString *> *livePaths = [NSMutableSet setWithCapacity:urls.count];
1294
1706
  for (NSURL *url in urls) {
@@ -1299,14 +1711,44 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
1299
1711
  for (NSString *path in self.recordCache.allKeys) {
1300
1712
  if (![livePaths containsObject:path]) [self.recordCache removeObjectForKey:path];
1301
1713
  }
1714
+ NSTimeInterval savedAt = NSDate.date.timeIntervalSince1970;
1715
+ if (self.persistsCache && savedAt - self.recordCacheSavedAt >= TokenCacheSaveInterval) {
1716
+ self.recordCacheSavedAt = savedAt;
1717
+ SaveTokenSummaryCache(self.recordCache, self.recordCachePath);
1718
+ }
1302
1719
  NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
1303
1720
  RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
1721
+ // 与 Codex 侧同理:订阅视图下转录只回溯 8 天,月度口径既算不准也没人看。
1722
+ // 曲线同样铺满整个自然月,末尾没到的日子是 0。
1723
+ NSArray<NSDictionary *> *monthDaily = apiMode
1724
+ ? ClaudeDailyTokenSeries(recordSets, monthStart, monthCurveEnd) : @[];
1725
+ if (buildsArchive) {
1726
+ NSArray *previousDaily = ClaudeDailyTokenSeries(recordSets, previousMonthStart, monthStart);
1727
+ self.monthlyArchive[previousMonthKey] = @{ @"daily": previousDaily,
1728
+ @"totals": SummedDailyTokenSeries(previousDaily) };
1729
+ archivedDaily = previousDaily;
1730
+ PruneMonthlyArchive(self.monthlyArchive);
1731
+ if (self.persistsCache) {
1732
+ SaveTokenSummaryCache(self.monthlyArchive, self.monthlyArchivePath);
1733
+ }
1734
+ }
1304
1735
  return @{
1305
1736
  @"fiveHour": ClaudeTokenTotals(recordSets, fiveStart, fiveEnd),
1306
1737
  @"week": ClaudeTokenTotals(recordSets, weekStart, weekEnd),
1307
1738
  @"today": ClaudeTokenTotals(recordSets, todayStart, rollingEnd),
1308
1739
  @"recentWeek": ClaudeTokenTotals(recordSets, rollingWeekStart, rollingEnd),
1309
1740
  @"recentWeekStartsAt": @(rollingWeekStart),
1741
+ @"month": apiMode ? SummedDailyTokenSeries(monthDaily) : NSNull.null,
1742
+ @"monthComparable": apiMode
1743
+ ? SummedDailyTokenSeriesInRange(monthDaily, monthStart, monthComparableEnd)
1744
+ : NSNull.null,
1745
+ @"previousMonthToDate": archivedDaily
1746
+ ? SummedDailyTokenSeriesInRange(archivedDaily, previousMonthStart, previousMonthEnd)
1747
+ : NSNull.null,
1748
+ @"monthDaily": monthDaily,
1749
+ @"monthStartsAt": @(monthStart),
1750
+ @"monthComparableEndsAt": @(monthComparableEnd),
1751
+ @"previousMonthComparableEndsAt": @(previousMonthEnd),
1310
1752
  @"source": @"local"
1311
1753
  };
1312
1754
  }