cc-pets 1.1.3 → 1.2.0

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.
@@ -650,6 +650,7 @@ static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessio
650
650
  @"week": weekTokens ?: NSNull.null,
651
651
  @"today": todayTokens ?: NSNull.null,
652
652
  @"recentWeek": recentTokens ?: NSNull.null,
653
+ @"recentWeekStartsAt": @(rollingWeekStart),
653
654
  @"source": @"local"
654
655
  };
655
656
  return result;
@@ -842,13 +843,16 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
842
843
 
843
844
  // MARK: - Claude Code 本地 Token 统计
844
845
  //
845
- // 数据源是 ~/.claude/projects/<编码后的 cwd>/<session-uuid>.jsonl。每条 type=assistant
846
- // 的行带 timestamp 和 message.usage,是**单次请求的增量**,与 Codex 的会话累计值不同,
847
- // 因此必须逐条落窗口累加,不能取末行。
846
+ // 数据源是 ~/.claude/projects/<编码后的 cwd>/<session-uuid>.jsonl,以及同级的
847
+ // <session-uuid>/subagents/agent-*.jsonl(子 agent 的转录,见 RecentClaudeTranscriptURLs)。
848
+ // 每条 type=assistant 的行带 timestamp 和 message.usage,是**单次请求的增量**,
849
+ // 与 Codex 的会话累计值不同,因此必须逐条落窗口累加,不能取末行。
848
850
  //
849
851
  // 关键差异:Claude 的 --resume / fork / compact 会把旧行原样复制进新文件,本机实测
850
852
  // 5575 行里有 692 行重复(12%)。不去重的话 7 天用量会虚高一成以上,所以按
851
- // message.id + requestId 做全局去重(两者缺失时回退 uuid)。
853
+ // message.id + requestId 做全局去重(两者缺失时回退 uuid)。同一次请求还会被拆成多行、
854
+ // 各带一份递增的 usage 快照,所以去重是**逐字段取最大值合并**而不是丢弃后续行,
855
+ // 详见 ClaudeTokenTotals。
852
856
 
853
857
  typedef struct {
854
858
  double timestamp;
@@ -924,28 +928,63 @@ static NSURL *ClaudeProjectsURL(void) {
924
928
  [DefaultClaudeConfigDirectory() stringByAppendingPathComponent:@"projects"]];
925
929
  }
926
930
 
931
+ // 收集目录内 mtime 落在窗口内的 .jsonl;顺带把子目录交给调用方(传 nil 表示不关心),
932
+ // 省一次 readdir。
933
+ static void AppendRecentTranscriptsInDirectory(NSURL *directory, NSTimeInterval earliest,
934
+ NSMutableArray<NSURL *> *urls, NSMutableArray<NSURL *> *outSubdirectories) {
935
+ NSArray<NSURLResourceKey> *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey,
936
+ NSURLIsDirectoryKey];
937
+ NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:directory
938
+ includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
939
+ for (NSURL *url in contents) {
940
+ NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
941
+ if ([values[NSURLIsDirectoryKey] boolValue]) {
942
+ [outSubdirectories addObject:url];
943
+ continue;
944
+ }
945
+ if (![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) continue;
946
+ if (![values[NSURLIsRegularFileKey] boolValue]) continue;
947
+ NSDate *modified = values[NSURLContentModificationDateKey];
948
+ if (modified && modified.timeIntervalSince1970 < earliest) continue;
949
+ [urls addObject:url];
950
+ }
951
+ }
952
+
927
953
  // 只看 mtime 落在窗口内的转录文件。本机 76 个文件里近 7 天只有 44 个,目录遍历约 3ms。
954
+ //
955
+ // 子 agent(Task/Explore)的转录不写进主会话文件,而是单独落在
956
+ // <project>/<session-uuid>/subagents/agent-*.jsonl,只扫项目目录一层的话它们一条都进不来
957
+ // ——本机主会话文件里 isSidechain 的行数为 0,漏掉的就是全部子 agent 用量(历史上单个
958
+ // 文件到过 269 万 token)。
959
+ //
960
+ // 下钻哪些会话由主会话文件 <session-uuid>.jsonl 的 mtime 决定:Task 的调用和结果都会写进
961
+ // 主会话文件,主文件不在窗口内,它的子 agent 也不可能在。projects/ 目录只增不减(本机
962
+ // 99 个会话里近 8 天只有 27 个),无条件下钻等于给每个历史会话都白跑一次 readdir,而且
963
+ // 多数子目录压根不是 subagents(本机 13 个里 7 个是 tool-results/memory)。
964
+ // 不能改用 <session-uuid>/ 目录自身的 mtime 剪枝:目录 mtime 只在直接子项增删时更新,
965
+ // 往已有 agent-*.jsonl 追加写不会动它,正在跑的长任务会被剪掉。
928
966
  static NSArray<NSURL *> *RecentClaudeTranscriptURLs(NSURL *projectsURL) {
929
967
  NSTimeInterval earliest = EarliestTokenWindowStart();
930
- NSArray<NSURLResourceKey> *keys = @[NSURLIsDirectoryKey];
931
968
  NSArray<NSURL *> *projects = [NSFileManager.defaultManager contentsOfDirectoryAtURL:projectsURL
932
- includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
969
+ includingPropertiesForKeys:@[NSURLIsDirectoryKey]
970
+ options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
933
971
  NSMutableArray<NSURL *> *urls = [NSMutableArray array];
934
- NSArray<NSURLResourceKey> *fileKeys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey];
935
972
  for (NSURL *project in projects) {
936
973
  NSNumber *isDirectory = nil;
937
974
  if (![project getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]) continue;
938
975
  if (!isDirectory.boolValue) continue;
939
- NSArray<NSURL *> *contents = [NSFileManager.defaultManager contentsOfDirectoryAtURL:project
940
- includingPropertiesForKeys:fileKeys options:NSDirectoryEnumerationSkipsHiddenFiles
941
- error:nil];
942
- for (NSURL *url in contents) {
943
- if (![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) continue;
944
- NSDictionary *values = [url resourceValuesForKeys:fileKeys error:nil];
945
- if (![values[NSURLIsRegularFileKey] boolValue]) continue;
946
- NSDate *modified = values[NSURLContentModificationDateKey];
947
- if (modified && modified.timeIntervalSince1970 < earliest) continue;
948
- [urls addObject:url];
976
+ NSMutableArray<NSURL *> *sessions = [NSMutableArray array];
977
+ NSUInteger firstIndex = urls.count;
978
+ AppendRecentTranscriptsInDirectory(project, earliest, urls, sessions);
979
+ NSMutableSet<NSString *> *activeSessions = [NSMutableSet set];
980
+ for (NSUInteger index = firstIndex; index < urls.count; index++) {
981
+ [activeSessions addObject:urls[index].URLByDeletingPathExtension.lastPathComponent];
982
+ }
983
+ for (NSURL *session in sessions) {
984
+ if (![activeSessions containsObject:session.lastPathComponent]) continue;
985
+ AppendRecentTranscriptsInDirectory(
986
+ [session URLByAppendingPathComponent:@"subagents" isDirectory:YES],
987
+ earliest, urls, nil);
949
988
  }
950
989
  }
951
990
  return urls;
@@ -990,10 +1029,15 @@ static NSData *ClaudeRecordsForFile(NSURL *url, NSMutableDictionary *cache) {
990
1029
  return records;
991
1030
  }
992
1031
 
1032
+ // 同一次请求会被拆成多行写入(thinking / text / tool_use 各一行),每行都带一份 usage
1033
+ // 快照,而这些快照是**递增的**:本机实测有 14 组末行的 output_tokens 远大于首行
1034
+ // (6→235、3→1870),首行取到的是流式过程中的中间值。因此同 identity 的多行必须逐字段
1035
+ // 取最大值合并,只保留第一条会少算——全量口径下少算 16060 个 output token。
1036
+ // 取 max 而不是"取最后一行":fork/resume 会把旧行复制进新文件,跨文件的行序没有保证。
993
1037
  static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInterval start,
994
1038
  NSTimeInterval end) {
995
- NSMutableSet<NSNumber *> *seen = [NSMutableSet set];
996
- unsigned long long input = 0, output = 0, cacheRead = 0, cacheWrite = 0;
1039
+ NSMutableDictionary<NSNumber *, NSNumber *> *slots = [NSMutableDictionary dictionary];
1040
+ NSMutableData *merged = [NSMutableData data];
997
1041
  for (NSData *data in recordSets) {
998
1042
  const ClaudeTokenRecord *records = data.bytes;
999
1043
  NSUInteger count = data.length / sizeof(ClaudeTokenRecord);
@@ -1001,14 +1045,29 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
1001
1045
  const ClaudeTokenRecord *record = &records[index];
1002
1046
  if (record->timestamp < start || record->timestamp >= end) continue;
1003
1047
  NSNumber *identity = @(record->identity);
1004
- if ([seen containsObject:identity]) continue;
1005
- [seen addObject:identity];
1006
- input += record->input;
1007
- output += record->output;
1008
- cacheRead += record->cacheRead;
1009
- cacheWrite += record->cacheWrite;
1048
+ NSNumber *slot = slots[identity];
1049
+ if (!slot) {
1050
+ slots[identity] = @(merged.length / sizeof(ClaudeTokenRecord));
1051
+ [merged appendBytes:record length:sizeof(*record)];
1052
+ continue;
1053
+ }
1054
+ // append 可能搬动缓冲区,基址每次重新取。
1055
+ ClaudeTokenRecord *target =
1056
+ (ClaudeTokenRecord *)merged.mutableBytes + slot.unsignedIntegerValue;
1057
+ target->input = MAX(target->input, record->input);
1058
+ target->output = MAX(target->output, record->output);
1059
+ target->cacheRead = MAX(target->cacheRead, record->cacheRead);
1060
+ target->cacheWrite = MAX(target->cacheWrite, record->cacheWrite);
1010
1061
  }
1011
1062
  }
1063
+ unsigned long long input = 0, output = 0, cacheRead = 0, cacheWrite = 0;
1064
+ const ClaudeTokenRecord *unique = merged.bytes;
1065
+ for (NSUInteger index = 0; index < merged.length / sizeof(ClaudeTokenRecord); index++) {
1066
+ input += unique[index].input;
1067
+ output += unique[index].output;
1068
+ cacheRead += unique[index].cacheRead;
1069
+ cacheWrite += unique[index].cacheWrite;
1070
+ }
1012
1071
  // 不输出 reasoning_output_tokens:Claude 的思考 token 已经计入 output_tokens,
1013
1072
  // 单列一个恒为 0 的字段会让人误以为没统计。
1014
1073
  return @{
@@ -1064,6 +1123,7 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
1064
1123
  @"week": ClaudeTokenTotals(recordSets, weekStart, weekEnd),
1065
1124
  @"today": ClaudeTokenTotals(recordSets, todayStart, rollingEnd),
1066
1125
  @"recentWeek": ClaudeTokenTotals(recordSets, rollingWeekStart, rollingEnd),
1126
+ @"recentWeekStartsAt": @(rollingWeekStart),
1067
1127
  @"source": @"local"
1068
1128
  };
1069
1129
  }
@@ -55,7 +55,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
55
55
  logical.size.width * QuotaScale, logical.size.height * QuotaScale);
56
56
  }
57
57
  - (NSRect)logicalSummaryRect {
58
- return NSMakeRect(20, 372, QuotaLogicalWidth - 40, 86);
58
+ return NSMakeRect(20, 372, QuotaLogicalWidth - 40, 112);
59
59
  }
60
60
  // 刷新时间挪去了右上角,这一版块整宽留给两个统计格,各占一半。
61
61
  - (NSRect)logicalSummaryCellRectAtIndex:(NSUInteger)index {
@@ -145,6 +145,32 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
145
145
  NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
146
146
  return reset ? [self clockText:reset.doubleValue] : @"--";
147
147
  }
148
+ // 汇总条的最近 7 天是共享的自然日口径。优先显示聚合结果携带的真实边界;兼容旧缓存时,
149
+ // 再按同一规则(含今天在内的 7 个自然日)现场计算,避免界面暂时退回到没有起期。
150
+ - (NSString *)recentWeekUsageLabel {
151
+ NSNumber *start = nil;
152
+ for (NSDictionary *usage in @[self.codexUsage ?: @{}, self.claudeUsage ?: @{}]) {
153
+ NSDictionary *tokenUsage = [usage[@"tokenUsage"] isKindOfClass:NSDictionary.class]
154
+ ? usage[@"tokenUsage"] : nil;
155
+ if ([tokenUsage[@"recentWeekStartsAt"] isKindOfClass:NSNumber.class]) {
156
+ start = tokenUsage[@"recentWeekStartsAt"];
157
+ break;
158
+ }
159
+ }
160
+ if (!start) {
161
+ NSCalendar *calendar = NSCalendar.currentCalendar;
162
+ NSDate *midnight = [calendar startOfDayForDate:NSDate.date];
163
+ NSDate *date = [calendar dateByAddingUnit:NSCalendarUnitDay value:-6 toDate:midnight
164
+ options:0];
165
+ start = @((date ?: midnight).timeIntervalSince1970);
166
+ }
167
+ NSDateFormatter *formatter = [NSDateFormatter new];
168
+ formatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
169
+ formatter.timeZone = NSTimeZone.localTimeZone;
170
+ formatter.dateFormat = @"yyyy-MM-dd";
171
+ return [NSString stringWithFormat:@"近 7 天(%@ 至今)",
172
+ [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:start.doubleValue]]];
173
+ }
148
174
  // 在线 = 这一家还有活着的客户端,和有没有额度数据无关:额度会一直缓存着,
149
175
  // 拿它当在线信号会恒亮。身份不明的老客户端无法归属到某一家,保守地都算在线。
150
176
  - (BOOL)isProviderOnline:(NSString *)name {
@@ -406,16 +432,18 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
406
432
 
407
433
  // 今日与最近 7 天都按 Provider 分开展示。底层本来就是两套独立的自然日统计,
408
434
  // 不在展示层相加,避免用户无法判断 Token 来自 Codex 还是 Claude。
409
- // 每格内是一张 2×2 表:行是 Provider,列是输入/输出,列头与格标题共用一行 —— 86pt
410
- // 高度只够三行,再单开一行列头就得把格子拔高,挤掉下面两张 Provider 卡片。
435
+ // 每格内是一张 2×2 表:标题独占一行,每个 Provider 独占一行;输入/输出标签放在
436
+ // 对应数值上方。这样既能完整展示 7 天统计起期,也不会挤乱两家的数据行。
411
437
  NSArray<NSDictionary *> *cells = @[
412
- @{@"icon": @"◔", @"key": @"today", @"label": @"今日已用 Token"},
413
- @{@"icon": @"◉", @"key": @"recentWeek", @"label": @"近 7 天已用 Token"}
438
+ @{@"icon": @"◔", @"key": @"today", @"label": @"▣ 今日用量"},
439
+ @{@"icon": @"◉", @"key": @"recentWeek", @"label": [self recentWeekUsageLabel]}
414
440
  ];
415
441
  NSColor *claudeColor = [NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1];
416
442
  NSArray<NSDictionary *> *rows = @[
417
- @{@"name": @"Codex", @"usage": self.codexUsage ?: @{}, @"color": cyan, @"y": @35},
418
- @{@"name": @"Claude", @"usage": self.claudeUsage ?: @{}, @"color": claudeColor, @"y": @12}
443
+ @{@"name": @"Codex", @"usage": self.codexUsage ?: @{}, @"color": cyan,
444
+ @"iconY": @43, @"nameY": @52, @"labelY": @68, @"valueY": @47},
445
+ @{@"name": @"Claude", @"usage": self.claudeUsage ?: @{}, @"color": claudeColor,
446
+ @"iconY": @5, @"nameY": @14, @"labelY": @30, @"valueY": @9}
419
447
  ];
420
448
  [[NSColor colorWithWhite:1 alpha:0.10] setStroke];
421
449
  for (NSUInteger index = 1; index < cells.count; index++) {
@@ -428,29 +456,35 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
428
456
  NSString *key = cell[@"key"];
429
457
  CGFloat x = NSMinX([self logicalSummaryCellRectAtIndex:index]);
430
458
  const CGFloat inputX = x + 176;
431
- const CGFloat outputX = x + 266;
432
- [cell[@"icon"] drawInRect:NSMakeRect(x + 24, NSMinY(summary) + 23, 42, 42)
433
- withAttributes:[self textAttributesWithSize:30 color:cyan weight:NSFontWeightRegular]];
459
+ const CGFloat outputX = x + 276;
434
460
  NSDictionary *headerAttributes = [self textAttributesWithSize:11 color:secondary
435
461
  weight:NSFontWeightRegular];
436
- [cell[@"label"] drawInRect:NSMakeRect(x + 72, NSMinY(summary) + 59, 100, 18)
437
- withAttributes:headerAttributes];
438
- [@"输入" drawInRect:NSMakeRect(inputX, NSMinY(summary) + 59, 86, 18)
439
- withAttributes:headerAttributes];
440
- [@"输出" drawInRect:NSMakeRect(outputX, NSMinY(summary) + 59, 86, 18)
462
+ [cell[@"label"] drawInRect:NSMakeRect(x + 24, NSMinY(summary) + 89,
463
+ NSWidth([self logicalSummaryCellRectAtIndex:index]) - 48, 18)
441
464
  withAttributes:headerAttributes];
442
465
  for (NSDictionary *row in rows) {
443
- CGFloat y = NSMinY(summary) + [row[@"y"] doubleValue];
444
466
  NSDictionary *usage = row[@"usage"];
445
- [row[@"name"] drawInRect:NSMakeRect(x + 72, y, 60, 20)
446
- withAttributes:[self textAttributesWithSize:12 color:row[@"color"]
467
+ NSColor *rowColor = row[@"color"];
468
+ CGFloat iconY = NSMinY(summary) + [row[@"iconY"] doubleValue];
469
+ CGFloat nameY = NSMinY(summary) + [row[@"nameY"] doubleValue];
470
+ CGFloat labelY = NSMinY(summary) + [row[@"labelY"] doubleValue];
471
+ CGFloat valueY = NSMinY(summary) + [row[@"valueY"] doubleValue];
472
+ [cell[@"icon"] drawInRect:NSMakeRect(x + 20, iconY, 42, 42)
473
+ withAttributes:[self textAttributesWithSize:30 color:rowColor
474
+ weight:NSFontWeightRegular]];
475
+ [row[@"name"] drawInRect:NSMakeRect(x + 66, nameY, 76, 22)
476
+ withAttributes:[self textAttributesWithSize:14 color:rowColor
447
477
  weight:NSFontWeightMedium]];
478
+ [@"输入" drawInRect:NSMakeRect(inputX, labelY, 76, 16)
479
+ withAttributes:headerAttributes];
480
+ [@"输出" drawInRect:NSMakeRect(outputX, labelY, 76, 16)
481
+ withAttributes:headerAttributes];
448
482
  NSDictionary *valueAttributes = [self textAttributesWithSize:16 color:primary
449
483
  weight:NSFontWeightBold];
450
484
  [[self formattedTokenSplitForUsage:usage key:key wantsOutput:NO]
451
- drawInRect:NSMakeRect(inputX, y - 2, 86, 23) withAttributes:valueAttributes];
485
+ drawInRect:NSMakeRect(inputX, valueY, 86, 23) withAttributes:valueAttributes];
452
486
  [[self formattedTokenSplitForUsage:usage key:key wantsOutput:YES]
453
- drawInRect:NSMakeRect(outputX, y - 2, 86, 23) withAttributes:valueAttributes];
487
+ drawInRect:NSMakeRect(outputX, valueY, 76, 23) withAttributes:valueAttributes];
454
488
  }
455
489
  }
456
490
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "1.1.3",
3
+ "version": "1.2.0",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",