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.
@@ -5,7 +5,14 @@
5
5
  #import <fcntl.h>
6
6
  #import <unistd.h>
7
7
 
8
+ // 读取与聚合全部跑在这条串行队列上,主线程只收结果。两个 reader 都不加锁,线程安全完全
9
+ // 依赖“只有这条队列碰它们”这一条约束:FSEvents 流、Claude 的 vnode source、定时刷新、
10
+ // 手动刷新,四个入口都要派到这里,任何一个漏掉都会变成数据竞争。
11
+ //
12
+ // 改成异步的直接原因:首次聚合要把一整个月的会话解析一遍(本机实测 7 秒),同步跑在主线程上
13
+ // 会让桌宠窗口迟迟不出现、切换展示模式时整个界面卡死。
8
14
  @interface CCPetsUsageMonitor ()
15
+ @property dispatch_queue_t queue;
9
16
  @property CodexUsageReader *codexReader;
10
17
  @property ClaudeUsageReader *claudeReader;
11
18
  @property(readwrite) NSDictionary *codexUsage;
@@ -59,13 +66,24 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
59
66
  @implementation CCPetsUsageMonitor
60
67
  - (instancetype)init {
61
68
  if ((self = [super init])) {
69
+ _queue = dispatch_queue_create("com.universewang.cc-pets.usage",
70
+ dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,
71
+ QOS_CLASS_UTILITY, 0));
62
72
  _codexReader = [CodexUsageReader new];
63
73
  _claudeReader = [ClaudeUsageReader new];
74
+ // 桌宠是唯一的常驻读取者,摘要缓存由它维护并落盘。
75
+ _codexReader.persistsCache = YES;
76
+ _claudeReader.persistsCache = YES;
64
77
  }
65
78
  return self;
66
79
  }
80
+ // 回调交给主线程:下游全是 UI(面板重排、气泡定位、系统通知)。
67
81
  - (void)publishChange {
68
- if (self.changeHandler) self.changeHandler(self.codexUsage, self.claudeUsage);
82
+ void (^handler)(NSDictionary *, NSDictionary *) = self.changeHandler;
83
+ if (!handler) return;
84
+ NSDictionary *codex = self.codexUsage;
85
+ NSDictionary *claude = self.claudeUsage;
86
+ dispatch_async(dispatch_get_main_queue(), ^{ handler(codex, claude); });
69
87
  }
70
88
  // changed=YES 表示额度文件确实变了(VNODE 事件),跳过 stat 比较;
71
89
  // aggregate=YES 表示这是手动刷新/面板打开/兜底轮询,Token 聚合要绕过节流立即重算。
@@ -95,7 +113,8 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
95
113
  self.codexStream = FSEventStreamCreate(NULL, CodexEventsCallback, &context,
96
114
  (__bridge CFArrayRef)paths, kFSEventStreamEventIdSinceNow, 0.5, flags);
97
115
  if (!self.codexStream) return;
98
- FSEventStreamSetDispatchQueue(self.codexStream, dispatch_get_main_queue());
116
+ // 回调直接落在读取队列上,省掉一次跳转,也保证 reader 只被这条队列访问。
117
+ FSEventStreamSetDispatchQueue(self.codexStream, self.queue);
99
118
  if (!FSEventStreamStart(self.codexStream)) {
100
119
  FSEventStreamInvalidate(self.codexStream);
101
120
  FSEventStreamRelease(self.codexStream);
@@ -115,7 +134,7 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
115
134
  if (descriptor < 0) return;
116
135
  dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
117
136
  DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
118
- DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE, dispatch_get_main_queue());
137
+ DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE, self.queue);
119
138
  if (!source) {
120
139
  close(descriptor);
121
140
  return;
@@ -134,20 +153,23 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
134
153
  strongSelf.claudeSource = nil;
135
154
  dispatch_source_cancel(current);
136
155
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
137
- dispatch_get_main_queue(), ^{ [weakSelf startClaudeSource]; });
156
+ strongSelf.queue, ^{ [weakSelf startClaudeSource]; });
138
157
  }
139
158
  });
140
159
  dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
141
160
  dispatch_resume(source);
142
161
  }
162
+ // 立即返回:首次聚合可能要几秒,桌宠窗口不该等它。
143
163
  - (void)start {
144
164
  if (self.started) return;
145
165
  self.started = YES;
146
- [self refreshNow];
147
- [self startCodexStream];
148
- [self startClaudeSource];
166
+ dispatch_async(self.queue, ^{ [self refreshOnQueue]; });
149
167
  }
150
168
  - (void)refreshNow {
169
+ dispatch_async(self.queue, ^{ [self refreshOnQueue]; });
170
+ }
171
+ - (void)refreshOnQueue {
172
+ if (!self.started) return;
151
173
  // 手动刷新、面板打开和 120 秒兜底都走全量路径,Token 聚合的节流只约束 FSEvents 热路径。
152
174
  self.codexUsage = [self.codexReader refreshWithFullDiscovery];
153
175
  self.claudeUsage = [self readClaudeUsageChanged:NO forcingAggregation:YES];
@@ -155,8 +177,15 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
155
177
  if (!self.claudeSource) [self startClaudeSource];
156
178
  [self publishChange];
157
179
  }
180
+ // 同步收尾:退出时要保证事件源在进程消失之前真的停掉,而它们只能在读取队列上安全拆除。
158
181
  - (void)stop {
182
+ if (!self.started) return;
159
183
  self.started = NO;
184
+ // dealloc 也会走到这里,block 里不能强引用 self——那会在析构途中把它再 retain 一次。
185
+ __unsafe_unretained typeof(self) unsafeSelf = self;
186
+ dispatch_sync(self.queue, ^{ [unsafeSelf teardownSources]; });
187
+ }
188
+ - (void)teardownSources {
160
189
  if (self.codexStream) {
161
190
  FSEventStreamStop(self.codexStream);
162
191
  FSEventStreamInvalidate(self.codexStream);
@@ -3,3 +3,7 @@
3
3
  // 菜单里用的自绘开关。系统 NSSwitch 在 NSMenuItem 的自定义视图里对比度不足。
4
4
  @interface MenuToggleSwitch : NSButton
5
5
  @end
6
+
7
+ // 菜单里的用量展示模式按钮。外观接近开关,但点击后直接在两种模式间切换。
8
+ @interface MenuUsageModeButton : NSButton
9
+ @end
@@ -45,3 +45,51 @@
45
45
  [NSGraphicsContext restoreGraphicsState];
46
46
  }
47
47
  @end
48
+
49
+
50
+ @implementation MenuUsageModeButton
51
+
52
+ - (instancetype)initWithFrame:(NSRect)frameRect {
53
+ if ((self = [super initWithFrame:frameRect])) {
54
+ self.bordered = NO;
55
+ self.title = @"";
56
+ self.buttonType = NSButtonTypeToggle;
57
+ self.focusRingType = NSFocusRingTypeNone;
58
+ [self setAccessibilityRole:NSAccessibilityButtonRole];
59
+ }
60
+ return self;
61
+ }
62
+
63
+ - (void)setState:(NSControlStateValue)value {
64
+ [super setState:value];
65
+ [self setAccessibilityValue:value == NSControlStateValueOn ? @"用量" : @"订阅"];
66
+ self.needsDisplay = YES;
67
+ }
68
+
69
+ - (void)drawRect:(NSRect)dirtyRect {
70
+ BOOL usesAPI = self.state == NSControlStateValueOn;
71
+ NSRect pill = NSInsetRect(self.bounds, 1, 2);
72
+ NSColor *pillColor = usesAPI
73
+ ? [NSColor colorWithRed:0.12 green:0.52 blue:0.96 alpha:self.highlighted ? 0.78 : 0.96]
74
+ : [NSColor colorWithRed:0.20 green:0.68 blue:0.36 alpha:self.highlighted ? 0.78 : 0.96];
75
+ [pillColor setFill];
76
+ NSBezierPath *pillPath = [NSBezierPath bezierPathWithRoundedRect:pill
77
+ xRadius:NSHeight(pill) / 2.0 yRadius:NSHeight(pill) / 2.0];
78
+ [pillPath fill];
79
+ [[NSColor colorWithWhite:0 alpha:0.10] setStroke];
80
+ pillPath.lineWidth = 0.8;
81
+ [pillPath stroke];
82
+
83
+ NSString *title = usesAPI ? @"用量" : @"订阅";
84
+ NSDictionary<NSAttributedStringKey, id> *attributes = @{
85
+ NSFontAttributeName: [NSFont systemFontOfSize:11 weight:NSFontWeightSemibold],
86
+ NSForegroundColorAttributeName: NSColor.whiteColor,
87
+ };
88
+ NSSize titleSize = [title sizeWithAttributes:attributes];
89
+ NSPoint titleOrigin = NSMakePoint(
90
+ round(NSMidX(self.bounds) - titleSize.width / 2.0),
91
+ round(NSMidY(self.bounds) - titleSize.height / 2.0));
92
+ [title drawAtPoint:titleOrigin withAttributes:attributes];
93
+ }
94
+
95
+ @end
@@ -5,6 +5,10 @@
5
5
 
6
6
  // 按下后位移超过这个距离才判定为拖动,之内视为点击。
7
7
  static const CGFloat PetDragThreshold = 3.0;
8
+ // 菜单里自绘行的宽度:主菜单要撑满 menu.minimumWidth,子菜单按自身内容收窄,
9
+ // 三个子菜单(用量展示模式 / 系统通知 / 系统状态)用同一个宽度,看起来才是一套。
10
+ static const CGFloat PetMenuRowWidth = 194.0;
11
+ static const CGFloat PetSubmenuRowWidth = 134.0;
8
12
 
9
13
  @implementation PetView
10
14
  - (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount {
@@ -282,12 +286,17 @@ static const CGFloat PetDragThreshold = 3.0;
282
286
  // 介入同一次按下;窗口透明区没有这个覆写,继续走 movableByWindowBackground。
283
287
  // 两条路径底层都是窗口服务器拖动,手感一致。
284
288
  - (BOOL)mouseDownCanMoveWindow { return NO; }
289
+ // 阈值起点取事件自带的坐标,不用 NSEvent.mouseLocation(那是"处理这条事件时"鼠标的实时
290
+ // 位置)。主线程被别的活儿占住时,mouseDown 会晚一截才被处理,实时位置早已跟着手滑走,
291
+ // 起点于是落在远处,后面要多走同样的距离才够过阈值——表现为按住之后宠物迟迟不动。
292
+ // 阈值判定发生在窗口服务器接手拖动之前,窗口此刻还没动,所以窗口坐标是稳定的参照系。
285
293
  - (void)mouseDown:(NSEvent *)event {
286
294
  self.agentActive = NO;
287
- self.dragStartMouse = NSEvent.mouseLocation;
295
+ self.dragStartMouse = event.locationInWindow;
288
296
  }
289
297
  - (void)mouseDragged:(NSEvent *)event {
290
- NSPoint current = NSEvent.mouseLocation;
298
+ if (self.draggingPet) return;
299
+ NSPoint current = event.locationInWindow;
291
300
  CGFloat horizontal = current.x - self.dragStartMouse.x;
292
301
  CGFloat vertical = current.y - self.dragStartMouse.y;
293
302
  if (hypot(horizontal, vertical) < PetDragThreshold) return;
@@ -462,20 +471,28 @@ static const CGFloat PetDragThreshold = 3.0;
462
471
  - (void)menuDidClose:(NSMenu *)menu {
463
472
  [self.petMenuPreviewPanel orderOut:nil];
464
473
  }
474
+ // 主菜单的行要撑满 menu.minimumWidth;子菜单只有自己这几项,撑到 194 会让短标题和开关
475
+ // 之间空出一大段。宽度交给调用方定,行内布局按同一套边距(左 12 / 右 8)算。
465
476
  - (NSMenuItem *)addPersistentSwitchToMenu:(NSMenu *)menu
466
477
  title:(NSString *)title
467
478
  checked:(BOOL)checked
468
479
  action:(SEL)action
480
+ width:(CGFloat)width
469
481
  tag:(NSInteger)tag {
482
+ const CGFloat toggleWidth = 36;
483
+ const CGFloat trailingInset = 8;
484
+ const CGFloat leadingInset = 12;
485
+ CGFloat toggleX = width - trailingInset - toggleWidth;
470
486
  NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
471
- NSView *row = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 194, 28)];
487
+ NSView *row = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, width, 28)];
472
488
  NSTextField *label = [NSTextField labelWithString:title];
473
- label.frame = NSMakeRect(12, 5, 132, 18);
489
+ label.frame = NSMakeRect(leadingInset, 5, toggleX - leadingInset - trailingInset, 18);
474
490
  label.font = [NSFont menuFontOfSize:13];
475
491
  label.textColor = NSColor.labelColor;
476
492
  label.lineBreakMode = NSLineBreakByTruncatingTail;
477
493
  [row addSubview:label];
478
- MenuToggleSwitch *toggle = [[MenuToggleSwitch alloc] initWithFrame:NSMakeRect(150, 3, 36, 22)];
494
+ MenuToggleSwitch *toggle = [[MenuToggleSwitch alloc]
495
+ initWithFrame:NSMakeRect(toggleX, 3, toggleWidth, 22)];
479
496
  toggle.target = NSApp.delegate;
480
497
  toggle.action = action;
481
498
  toggle.state = checked ? NSControlStateValueOn : NSControlStateValueOff;
@@ -486,9 +503,34 @@ static const CGFloat PetDragThreshold = 3.0;
486
503
  [menu addItem:item];
487
504
  return item;
488
505
  }
506
+ - (NSMenuItem *)addUsageModeControlToMenu:(NSMenu *)menu
507
+ provider:(NSString *)provider
508
+ preferenceKey:(NSString *)preferenceKey
509
+ tag:(NSInteger)tag {
510
+ NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
511
+ NSView *row = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 134, 28)];
512
+ NSTextField *label = [NSTextField labelWithString:provider];
513
+ label.frame = NSMakeRect(12, 5, 48, 18);
514
+ label.font = [NSFont menuFontOfSize:13];
515
+ label.textColor = NSColor.labelColor;
516
+ [row addSubview:label];
517
+
518
+ MenuUsageModeButton *control = [[MenuUsageModeButton alloc] initWithFrame:NSMakeRect(68, 3, 58, 22)];
519
+ control.target = NSApp.delegate;
520
+ control.action = @selector(setUsageDisplayModeFromControl:);
521
+ control.state = [[NSUserDefaults.standardUserDefaults stringForKey:preferenceKey]
522
+ isEqualToString:@"api"] ? NSControlStateValueOn : NSControlStateValueOff;
523
+ control.tag = tag;
524
+ [control setAccessibilityLabel:[provider stringByAppendingString:@"用量展示模式"]];
525
+ [row addSubview:control];
526
+ item.view = row;
527
+ [menu addItem:item];
528
+ return item;
529
+ }
489
530
  - (void)rightMouseDown:(NSEvent *)event {
490
531
  NSArray<NSDictionary *> *availablePets = self.petOptionsRequested ? self.petOptionsRequested() : @[];
491
532
  NSMenu *menu = [NSMenu new];
533
+ menu.minimumWidth = 194.0;
492
534
  NSMenuItem *switchItem = [menu addItemWithTitle:@"切换桌宠" action:nil keyEquivalent:@""];
493
535
  NSMenu *switchMenu = [NSMenu new];
494
536
  switchMenu.delegate = self;
@@ -508,12 +550,21 @@ static const CGFloat PetDragThreshold = 3.0;
508
550
  title:@"显示消息气泡"
509
551
  checked:[NSUserDefaults.standardUserDefaults boolForKey:StatusBubbleExpandedKey]
510
552
  action:@selector(toggleStatusBubbleFromMenu:)
553
+ width:PetMenuRowWidth
511
554
  tag:0];
512
555
  [self addPersistentSwitchToMenu:menu
513
556
  title:@"导入 Codex 素材"
514
557
  checked:[NSUserDefaults.standardUserDefaults boolForKey:ImportCodexPetsKey]
515
558
  action:@selector(toggleImportCodexPets:)
559
+ width:PetMenuRowWidth
516
560
  tag:0];
561
+ NSMenuItem *usageModeItem = [menu addItemWithTitle:@"用量展示模式" action:nil keyEquivalent:@""];
562
+ NSMenu *usageModeMenu = [NSMenu new];
563
+ [self addUsageModeControlToMenu:usageModeMenu provider:@"Codex"
564
+ preferenceKey:CodexUsageDisplayModeKey tag:1];
565
+ [self addUsageModeControlToMenu:usageModeMenu provider:@"Claude"
566
+ preferenceKey:ClaudeUsageDisplayModeKey tag:2];
567
+ usageModeItem.submenu = usageModeMenu;
517
568
  NSMenuItem *notificationItem = [menu addItemWithTitle:@"系统通知" action:nil keyEquivalent:@""];
518
569
  NSMenu *notificationMenu = [NSMenu new];
519
570
  NSArray<NSDictionary *> *notificationOptions = @[
@@ -526,6 +577,7 @@ static const CGFloat PetDragThreshold = 3.0;
526
577
  title:option[@"title"]
527
578
  checked:[NSUserDefaults.standardUserDefaults boolForKey:option[@"key"]]
528
579
  action:@selector(toggleNotification:)
580
+ width:PetSubmenuRowWidth
529
581
  tag:[option[@"tag"] integerValue]];
530
582
  }
531
583
  notificationItem.submenu = notificationMenu;
@@ -541,6 +593,7 @@ static const CGFloat PetDragThreshold = 3.0;
541
593
  title:option[@"title"]
542
594
  checked:[NSUserDefaults.standardUserDefaults boolForKey:option[@"key"]]
543
595
  action:@selector(toggleSystemMetric:)
596
+ width:PetSubmenuRowWidth
544
597
  tag:[option[@"tag"] integerValue]];
545
598
  }
546
599
  systemStatusItem.submenu = systemStatusMenu;
@@ -33,6 +33,8 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
33
33
  @property NSNumber *systemCPUPercent;
34
34
  @property NSNumber *systemTemperatureCelsius;
35
35
  @property NSNumber *systemMemoryPercent;
36
+ @property BOOL codexShowsAPIUsage;
37
+ @property BOOL claudeShowsAPIUsage;
36
38
  - (BOOL)isProviderOnline:(NSString *)name;
37
39
  @property NSImage *codexLogo;
38
40
  @property NSImage *claudeLogo;
@@ -152,6 +152,25 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
152
152
  ? totals[@"total_tokens"] : nil;
153
153
  return number ? [self formattedTokenValue:number.doubleValue] : @"--";
154
154
  }
155
+ - (NSString *)formattedRequestCount:(NSDictionary *)totals {
156
+ NSNumber *number = [totals[@"request_count"] isKindOfClass:NSNumber.class]
157
+ ? totals[@"request_count"] : nil;
158
+ return number ? [NSNumberFormatter localizedStringFromNumber:number
159
+ numberStyle:NSNumberFormatterDecimalStyle] : @"--";
160
+ }
161
+ - (NSDictionary *)comparisonForCurrent:(double)current previous:(double)previous
162
+ color:(NSColor *)color {
163
+ if (previous <= 0) {
164
+ return @{ @"text": current > 0 ? @"较上月同期 新增" : @"较上月同期 持平",
165
+ @"color": current > 0 ? color : self.secondaryColor };
166
+ }
167
+ double change = (current - previous) * 100.0 / previous;
168
+ if (fabs(change) < 0.05) {
169
+ return @{ @"text": @"较上月同期 持平", @"color": self.secondaryColor };
170
+ }
171
+ return @{ @"text": [NSString stringWithFormat:@"较上月同期 %@%.1f%%",
172
+ change > 0 ? @"↑" : @"↓", fabs(change)], @"color": color };
173
+ }
155
174
  // 输入取 total - output,而不是把几个 input_* 字段加起来:两家的包含关系是相反的。
156
175
  // Codex 的 cached_input_tokens 是 input_tokens 的子集(实测 input+output == total),
157
176
  // 相加会把缓存部分算两遍;Claude 的 input_tokens 不含缓存读写,两者是并列项,不加又会漏。
@@ -406,6 +425,37 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
406
425
  }
407
426
  [self drawCurveSegment:allPoints inRect:rect color:color];
408
427
  }
428
+ - (void)drawMonthlyTokenCurve:(NSArray<NSDictionary *> *)series inRect:(NSRect)rect
429
+ color:(NSColor *)color {
430
+ [[NSColor colorWithWhite:1 alpha:0.08] setStroke];
431
+ [NSBezierPath strokeLineFromPoint:NSMakePoint(NSMinX(rect), NSMinY(rect))
432
+ toPoint:NSMakePoint(NSMaxX(rect), NSMinY(rect))];
433
+ if (series.count == 0) return;
434
+ // 横轴铺满整个自然月,曲线只画到今天:把月末还没到的日子当成 0 画出去,看起来会像
435
+ // 用量突然归零。留白本身就是"这个月还剩多少天"的刻度。
436
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
437
+ double peak = 0;
438
+ NSUInteger elapsed = 0;
439
+ for (NSDictionary *day in series) {
440
+ if ([day[@"timestamp"] doubleValue] > now) break;
441
+ NSDictionary *totals = [day[@"totals"] isKindOfClass:NSDictionary.class]
442
+ ? day[@"totals"] : nil;
443
+ peak = fmax(peak, [totals[@"total_tokens"] doubleValue]);
444
+ elapsed += 1;
445
+ }
446
+ if (peak <= 0 || elapsed == 0) return;
447
+ NSMutableArray<NSValue *> *points = [NSMutableArray arrayWithCapacity:elapsed];
448
+ for (NSUInteger index = 0; index < elapsed; index++) {
449
+ NSDictionary *totals = [series[index][@"totals"] isKindOfClass:NSDictionary.class]
450
+ ? series[index][@"totals"] : nil;
451
+ double value = [totals[@"total_tokens"] doubleValue];
452
+ CGFloat progress = series.count > 1 ? (CGFloat)index / (series.count - 1) : 1;
453
+ [points addObject:[NSValue valueWithPoint:NSMakePoint(
454
+ NSMinX(rect) + NSWidth(rect) * progress,
455
+ NSMinY(rect) + NSHeight(rect) * value / peak)]];
456
+ }
457
+ [self drawCurveSegment:points inRect:rect color:color];
458
+ }
409
459
  - (NSDictionary *)paceStatusForQuota:(NSDictionary *)quota currentUsed:(NSNumber *)currentUsed
410
460
  color:(NSColor *)providerColor {
411
461
  if (!currentUsed) {
@@ -488,12 +538,24 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
488
538
  NSDictionary *week = [self quota:usage key:@"week"];
489
539
  NSDictionary *fiveTokens = [self tokenTotals:usage key:@"fiveHour"];
490
540
  NSDictionary *weekTokens = [self tokenTotals:usage key:@"week"];
541
+ NSDictionary *monthTokens = [self tokenTotals:usage key:@"month"];
542
+ // 同比两侧都只数到最后一个完整自然日(见 CalendarMonthWindows),因此不能拿含今天的
543
+ // monthTokens 去比不含同日的上月——那样每天都会凭空多出小半天的增量。
544
+ NSDictionary *monthComparable = [self tokenTotals:usage key:@"monthComparable"];
545
+ NSDictionary *previousMonthTokens = [self tokenTotals:usage key:@"previousMonthToDate"];
546
+ NSDictionary *tokenUsage = [usage[@"tokenUsage"] isKindOfClass:NSDictionary.class]
547
+ ? usage[@"tokenUsage"] : nil;
548
+ NSArray<NSDictionary *> *monthDaily = [tokenUsage[@"monthDaily"] isKindOfClass:NSArray.class]
549
+ ? tokenUsage[@"monthDaily"] : @[];
550
+ BOOL apiMode = [name isEqualToString:@"Codex"]
551
+ ? self.codexShowsAPIUsage : self.claudeShowsAPIUsage;
491
552
  NSNumber *fiveUsed = [self usedForQuota:five usedKey:usedKey];
492
553
  NSNumber *weekUsed = [self usedForQuota:week usedKey:usedKey];
493
554
  // 额度被拒之后官方不再报告任何窗口,留在手里的百分比既过期、指向的结论又正好相反
494
555
  // (账号是共享的,别人用完时本机的数字纹丝不动)。这时按 0 显示,并把状态说清楚。
495
556
  BOOL exhausted = [usage[@"exhaustedAt"] isKindOfClass:NSNumber.class];
496
- BOOL hasData = fiveUsed || weekUsed || fiveTokens || weekTokens || exhausted;
557
+ BOOL hasData = apiMode ? (monthTokens != nil)
558
+ : (fiveUsed || weekUsed || fiveTokens || weekTokens || exhausted);
497
559
  BOOL online = [self isProviderOnline:name];
498
560
 
499
561
  NSBezierPath *cardPath = [NSBezierPath bezierPathWithRoundedRect:card xRadius:18 yRadius:18];
@@ -530,9 +592,9 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
530
592
  withAttributes:[self textAttributesWithSize:22 color:primary weight:NSFontWeightBold]];
531
593
  // 四态:额度被拒 → 额度已用尽(压过在线,这是此刻唯一要紧的信息);没有任何额度
532
594
  // 数据 → 等待数据;有数据但客户端已退出 → 离线;两者都有 → 在线。
533
- NSString *statusText = exhausted ? @"额度已用尽"
595
+ NSString *statusText = (!apiMode && exhausted) ? @"额度已用尽"
534
596
  : (!hasData ? @"等待数据" : (online ? @"● 在线" : @"离线"));
535
- NSColor *statusColor = exhausted ? NSColor.systemOrangeColor
597
+ NSColor *statusColor = (!apiMode && exhausted) ? NSColor.systemOrangeColor
536
598
  : (online && hasData ? NSColor.systemGreenColor : secondary);
537
599
  NSDictionary *statusAttributes = [self textAttributesWithSize:11 color:statusColor
538
600
  weight:NSFontWeightMedium];
@@ -541,6 +603,106 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
541
603
  [self fillRoundedRect:status radius:12 color:[statusColor colorWithAlphaComponent:0.13]];
542
604
  [statusText drawInRect:NSInsetRect(status, 9, 4) withAttributes:statusAttributes];
543
605
 
606
+ if (apiMode) {
607
+ CGFloat callX = NSMinX(card) + 214;
608
+ CGFloat tokenX = NSMinX(card) + 394;
609
+ [@"本月调用" drawInRect:NSMakeRect(callX, NSMinY(card) + 114, 130, 20)
610
+ withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
611
+ [@"本月消耗" drawInRect:NSMakeRect(tokenX, NSMinY(card) + 114, 130, 20)
612
+ withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
613
+
614
+ NSString *requests = [NSString stringWithFormat:@"%@ 次",
615
+ [self formattedRequestCount:monthTokens ?: @{}]];
616
+ [requests drawInRect:NSMakeRect(callX, NSMinY(card) + 75, 150, 34)
617
+ withAttributes:[self textAttributesWithSize:24 color:primary weight:NSFontWeightBold]];
618
+ // 曲线铺满整个自然月,月末那些还没到的日子不能算进"已过天数",否则日均会被稀释。
619
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
620
+ NSUInteger recordedDays = 0;
621
+ for (NSDictionary *day in monthDaily) {
622
+ if ([day[@"timestamp"] doubleValue] <= now) recordedDays += 1;
623
+ }
624
+ NSUInteger elapsedDays = MAX((NSUInteger)1, recordedDays);
625
+ NSNumber *requestCount = [monthTokens[@"request_count"] isKindOfClass:NSNumber.class]
626
+ ? monthTokens[@"request_count"] : nil;
627
+ NSString *average = requestCount
628
+ ? [NSString stringWithFormat:@"日均 %@ 次",
629
+ [NSNumberFormatter localizedStringFromNumber:
630
+ @(llround(requestCount.doubleValue / elapsedDays))
631
+ numberStyle:NSNumberFormatterDecimalStyle]]
632
+ : @"日均 --";
633
+ [average drawInRect:NSMakeRect(callX, NSMinY(card) + 48, 150, 20)
634
+ withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
635
+
636
+ // 这里不再重复"本月消耗"的合计:输入与输出各自的量级才是按量计费时要看的东西,
637
+ // 合计随时可以由这两个数得到,而它原先占掉了最显眼的一行。
638
+ NSArray<NSDictionary *> *splits = @[
639
+ @{@"label": @"输入", @"value": [self formattedTokenSplit:monthTokens ?: @{}
640
+ wantsOutput:NO], @"y": @(NSMinY(card) + 76)},
641
+ @{@"label": @"输出", @"value": [self formattedTokenSplit:monthTokens ?: @{}
642
+ wantsOutput:YES], @"y": @(NSMinY(card) + 48)}
643
+ ];
644
+ for (NSDictionary *split in splits) {
645
+ CGFloat y = [split[@"y"] doubleValue];
646
+ [split[@"label"] drawInRect:NSMakeRect(tokenX, y + 4, 28, 16)
647
+ withAttributes:[self textAttributesWithSize:11 color:secondary
648
+ weight:NSFontWeightRegular]];
649
+ [split[@"value"] drawInRect:NSMakeRect(tokenX + 32, y, 122, 26)
650
+ withAttributes:[self textAttributesWithSize:18 color:primary
651
+ weight:NSFontWeightBold]];
652
+ }
653
+
654
+ NSDictionary *requestComparison = [self comparisonForCurrent:
655
+ [monthComparable[@"request_count"] doubleValue]
656
+ previous:[previousMonthTokens[@"request_count"] doubleValue] color:color];
657
+ [requestComparison[@"text"] drawInRect:NSMakeRect(callX, NSMinY(card) + 22, 158, 18)
658
+ withAttributes:[self textAttributesWithSize:11 color:requestComparison[@"color"]
659
+ weight:NSFontWeightMedium]];
660
+ NSDictionary *tokenComparison = [self comparisonForCurrent:
661
+ [monthComparable[@"total_tokens"] doubleValue]
662
+ previous:[previousMonthTokens[@"total_tokens"] doubleValue] color:color];
663
+ [tokenComparison[@"text"] drawInRect:NSMakeRect(tokenX, NSMinY(card) + 22, 158, 18)
664
+ withAttributes:[self textAttributesWithSize:11 color:tokenComparison[@"color"]
665
+ weight:NSFontWeightMedium]];
666
+
667
+ CGFloat trendX = NSMinX(card) + 564;
668
+ // 「按日 Token」跟在标题后面,与标题同一行:它是标题的限定语,单独占一行既浪费
669
+ // 竖向空间,也把曲线和脚注挤得没法与左边两列对齐。
670
+ [@"本月趋势" drawInRect:NSMakeRect(trendX, NSMinY(card) + 114, 60, 20)
671
+ withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
672
+ NSDictionary *pillAttributes = [self textAttributesWithSize:11 color:color
673
+ weight:NSFontWeightSemibold];
674
+ NSRect pill = NSMakeRect(trendX + 59, NSMinY(card) + 113, 76, 22);
675
+ [self fillRoundedRect:pill radius:11 color:[color colorWithAlphaComponent:0.14]];
676
+ [@"按日 Token" drawInRect:NSInsetRect(pill, 9, 3) withAttributes:pillAttributes];
677
+ NSRect curveRect = NSMakeRect(trendX, NSMinY(card) + 62, 135, 38);
678
+ [self drawMonthlyTokenCurve:monthDaily inRect:curveRect color:color];
679
+ double peak = 0;
680
+ NSDictionary *todayTotals = nil;
681
+ for (NSDictionary *day in monthDaily) {
682
+ if ([day[@"timestamp"] doubleValue] > now) break;
683
+ NSDictionary *totals = [day[@"totals"] isKindOfClass:NSDictionary.class]
684
+ ? day[@"totals"] : nil;
685
+ peak = fmax(peak, [totals[@"total_tokens"] doubleValue]);
686
+ todayTotals = totals;
687
+ }
688
+ NSString *peakText = recordedDays > 0
689
+ ? [NSString stringWithFormat:@"峰值 %@", [self formattedTokenValue:peak]] : @"峰值 --";
690
+ NSString *todayText = todayTotals
691
+ ? [NSString stringWithFormat:@"今日 %@",
692
+ [self formattedTokenValue:[todayTotals[@"total_tokens"] doubleValue]]] : @"今日 --";
693
+ [peakText drawInRect:NSMakeRect(trendX, NSMinY(card) + 42, 74, 16)
694
+ withAttributes:[self textAttributesWithSize:10 color:secondary weight:NSFontWeightRegular]];
695
+ [todayText drawInRect:NSMakeRect(trendX + 61, NSMinY(card) + 42, 74, 16)
696
+ withAttributes:[self rightAlignedTextAttributesWithSize:10 color:secondary
697
+ weight:NSFontWeightRegular]];
698
+ // 与左边两列的"较上月同期"同一条基线(+22),三列脚注才在一条水平线上。
699
+ [[NSString stringWithFormat:@"本月已记录 %lu / %lu 天",
700
+ (unsigned long)recordedDays, (unsigned long)monthDaily.count]
701
+ drawInRect:NSMakeRect(trendX, NSMinY(card) + 22, 145, 18)
702
+ withAttributes:[self textAttributesWithSize:11 color:color weight:NSFontWeightMedium]];
703
+ return;
704
+ }
705
+
544
706
  // 层级:官方剩余额度是订阅限额的权威值,占主位;本机 Token 是参考量,降一级并用
545
707
  // 强调色区分;重置时间最小。反过来会让最抢眼的数字恰好是最不该照着做决定的那个。
546
708
  NSArray<NSDictionary *> *windows = @[
@@ -569,21 +731,22 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
569
731
  withAttributes:valueAttributes];
570
732
  [@"剩余" drawInRect:NSMakeRect(x + valueWidth + 7, NSMinY(card) + 78, 60, 20)
571
733
  withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
572
- NSString *tokenText = [NSString stringWithFormat:@"已用 Token %@",
573
- [self formattedTokenCount:window[@"tokens"]]];
574
- [tokenText drawInRect:NSMakeRect(x, NSMinY(card) + 46, 150, 22)
575
- withAttributes:[self textAttributesWithSize:14 color:color weight:NSFontWeightSemibold]];
576
734
  // 官方窗口拿不到时(账号没有这个窗口、或响应里没带),Token 走的是本机滚动窗口。
577
735
  // 说清楚这一行的口径,比留一个 `--` 让人以为是渲染坏了要好。
578
736
  NSString *resetValue = [self resetText:window[@"quota"]];
579
737
  NSString *reset = [resetValue isEqualToString:@"--"]
580
738
  ? window[@"rolling"] : [NSString stringWithFormat:@"重置时间 %@", resetValue];
581
- [reset drawInRect:NSMakeRect(x, NSMinY(card) + 22, 150, 18)
739
+ [reset drawInRect:NSMakeRect(x, NSMinY(card) + 46, 150, 18)
582
740
  withAttributes:[self textAttributesWithSize:11 color:secondary weight:NSFontWeightRegular]];
741
+ NSString *tokenText = [NSString stringWithFormat:@"已用 Token %@",
742
+ [self formattedTokenCount:window[@"tokens"]]];
743
+ [tokenText drawInRect:NSMakeRect(x, NSMinY(card) + 22, 150, 22)
744
+ withAttributes:[self textAttributesWithSize:14 color:color weight:NSFontWeightSemibold]];
583
745
  }
584
746
 
585
747
  CGFloat trendX = NSMinX(card) + 564;
586
- [@"使用趋势" drawInRect:NSMakeRect(trendX, NSMinY(card) + 114, 145, 20)
748
+ // 与 API 卡同一套骨架:标题行带 pill、中间曲线、脚注和左边两列齐平。
749
+ [@"使用趋势" drawInRect:NSMakeRect(trendX, NSMinY(card) + 114, 60, 20)
587
750
  withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
588
751
  NSArray<NSDictionary *> *history = [name isEqualToString:@"Codex"]
589
752
  ? self.codexHistory : self.claudeHistory;
@@ -593,12 +756,14 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
593
756
  NSColor *paceColor = pace[@"color"];
594
757
  NSDictionary *pillAttributes = [self textAttributesWithSize:11 color:paceColor
595
758
  weight:NSFontWeightSemibold];
759
+ // 档位标签跟在标题后面。宽度仍按文字算:四个档位不一样长,最宽的"数据不足"到
760
+ // trendX + 131,列宽 145 放得下。
596
761
  CGFloat pillWidth = ceil([pace[@"label"] sizeWithAttributes:pillAttributes].width) + 18;
597
- NSRect pill = NSMakeRect(trendX, NSMinY(card) + 88, pillWidth, 22);
762
+ NSRect pill = NSMakeRect(trendX + 59, NSMinY(card) + 113, pillWidth, 22);
598
763
  [self fillRoundedRect:pill radius:11 color:[paceColor colorWithAlphaComponent:0.14]];
599
764
  [pace[@"label"] drawInRect:NSInsetRect(pill, 9, 3) withAttributes:pillAttributes];
600
765
 
601
- NSRect curveRect = NSMakeRect(trendX, NSMinY(card) + 43, 135, 38);
766
+ NSRect curveRect = NSMakeRect(trendX, NSMinY(card) + 62, 135, 38);
602
767
  [self drawUsageCurve:points inRect:curveRect color:color];
603
768
  double peak = 0;
604
769
  for (NSDictionary *point in points) peak = fmax(peak, [point[@"used"] doubleValue]);
@@ -606,13 +771,14 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
606
771
  ? [NSString stringWithFormat:@"最高 %.0f%%", peak] : @"最高 --";
607
772
  NSString *currentText = currentUsed
608
773
  ? [NSString stringWithFormat:@"当前 %.0f%%", currentUsed.doubleValue] : @"当前 --";
609
- [peakText drawInRect:NSMakeRect(trendX, NSMinY(card) + 25, 72, 16)
774
+ [peakText drawInRect:NSMakeRect(trendX, NSMinY(card) + 42, 72, 16)
610
775
  withAttributes:[self textAttributesWithSize:10 color:secondary weight:NSFontWeightRegular]];
611
- [currentText drawInRect:NSMakeRect(trendX + 66, NSMinY(card) + 25, 69, 16)
776
+ [currentText drawInRect:NSMakeRect(trendX + 66, NSMinY(card) + 42, 69, 16)
612
777
  withAttributes:[self rightAlignedTextAttributesWithSize:10 color:secondary
613
778
  weight:NSFontWeightRegular]];
614
- [pace[@"tip"] drawInRect:NSMakeRect(trendX, NSMinY(card) + 7, 145, 16)
615
- withAttributes:[self textAttributesWithSize:10 color:paceColor weight:NSFontWeightMedium]];
779
+ // 与左边两列的"已用 Token"同一条基线(+22),也和 API 卡的脚注行对齐。
780
+ [pace[@"tip"] drawInRect:NSMakeRect(trendX, NSMinY(card) + 22, 145, 18)
781
+ withAttributes:[self textAttributesWithSize:11 color:paceColor weight:NSFontWeightMedium]];
616
782
  }
617
783
  - (void)drawRect:(NSRect)dirtyRect {
618
784
  [NSGraphicsContext saveGraphicsState];
@@ -725,9 +891,13 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
725
891
  withAttributes:[self textAttributesWithSize:11
726
892
  color:[NSColor colorWithWhite:0.52 alpha:1] weight:NSFontWeightRegular]];
727
893
  }
728
- NSString *footer = visibleProviders.count > 0
729
- ? @"ⓘ 百分比 = 官方订阅额度的剩余比例;Token = 本机统计的已用量(输入含缓存读写),两者口径不同"
730
- : @"ⓘ 桌宠与系统状态不受影响;额度卡只在检测到对应 CLI 时显示";
894
+ BOOL hasAPICard = ([visibleProviders containsObject:@"Codex"] && self.codexShowsAPIUsage) ||
895
+ ([visibleProviders containsObject:@"Claude"] && self.claudeShowsAPIUsage);
896
+ NSString *footer = visibleProviders.count == 0
897
+ ? @"ⓘ 桌宠与系统状态不受影响;额度卡只在检测到对应 CLI 时显示"
898
+ : (hasAPICard
899
+ ? @"ⓘ API 用量 = 本机会话统计(输入含缓存读写);环比按上月相同时间进度计算"
900
+ : @"ⓘ 百分比 = 官方订阅额度的剩余比例;Token = 本机统计的已用量(输入含缓存读写),两者口径不同");
731
901
  // 最后一块的底边距面板底 QuotaFooterHeight:脚注与其留约 8pt,底部留白 16pt,
732
902
  // 和顶部标题的留白大致对称。
733
903
  [footer drawInRect:NSMakeRect(28, 16, 650, 20)
@@ -1,6 +1,6 @@
1
1
  # 第三方声明
2
2
 
3
- CC Pets 发布包不捆绑 PetDex 下载的角色素材。内置的 `ByteMochi.png` 是专为本项目创建的
3
+ CC Pets 发布包不捆绑 PetDex 下载的角色素材。内置的 `默认.webp` 是专为本项目创建的
4
4
  原创默认素材,与任何现有动漫、游戏或商业吉祥物无关,并与项目代码一同按 MIT License 分发。
5
5
 
6
6
  程序会在运行时尝试读取用户本机已安装的 Codex/ChatGPT 和 Claude 应用图标,仅用于界面识别;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "1.2.9",
3
+ "version": "1.3.1",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",