cc-pets 1.2.8 → 1.3.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.
@@ -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;
@@ -2,8 +2,10 @@
2
2
 
3
3
  // 额度面板按逻辑尺寸绘制后整体缩放,保证离屏渲染和实时显示是同一套代码。
4
4
  extern const CGFloat QuotaLogicalWidth;
5
+ // 两家 CLI 都装时的高度,也是预览图的尺寸。实际高度按检测到的 provider 数量算。
5
6
  extern const CGFloat QuotaLogicalHeight;
6
7
  extern const CGFloat QuotaScale;
8
+ CGFloat QuotaLogicalHeightForProviderCount(NSUInteger count);
7
9
 
8
10
  NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
9
11
 
@@ -18,6 +20,12 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
18
20
  @property NSSet<NSString *> *liveProviders;
19
21
  // 老版本包装脚本写出的 pid 文件没有 provider 名。有这种客户端时无法断言某一家离线。
20
22
  @property BOOL hasUnlabeledClient;
23
+ // 这台机器上检测到的 provider("Codex" / "Claude")。决定渲染几张额度卡、面板多高。
24
+ // 与 liveProviders 是两件事:那个是"此刻在不在线",只驱动徽章。nil 表示没探测过,
25
+ // 按两家都有渲染。
26
+ @property NSSet<NSString *> *detectedProviders;
27
+ - (NSArray<NSString *> *)visibleProviders;
28
+ - (CGFloat)logicalHeight;
21
29
  @property NSTimeInterval lastUpdatedAt;
22
30
  @property BOOL systemCPUEnabled;
23
31
  @property BOOL systemTemperatureEnabled;
@@ -25,6 +33,8 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
25
33
  @property NSNumber *systemCPUPercent;
26
34
  @property NSNumber *systemTemperatureCelsius;
27
35
  @property NSNumber *systemMemoryPercent;
36
+ @property BOOL codexShowsAPIUsage;
37
+ @property BOOL claudeShowsAPIUsage;
28
38
  - (BOOL)isProviderOnline:(NSString *)name;
29
39
  @property NSImage *codexLogo;
30
40
  @property NSImage *claudeLogo;