cc-pets 1.0.3 → 1.0.5

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.
@@ -0,0 +1,10 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ @interface CCPetsUsageMonitor : NSObject
4
+ @property(copy) void (^changeHandler)(NSDictionary *codexUsage, NSDictionary *claudeUsage);
5
+ @property(readonly) NSDictionary *codexUsage;
6
+ @property(readonly) NSDictionary *claudeUsage;
7
+ - (void)start;
8
+ - (void)refreshNow;
9
+ - (void)stop;
10
+ @end
@@ -0,0 +1,167 @@
1
+ #import "CCPetsUsageMonitor.h"
2
+ #import "CCPetsUsage.h"
3
+ #import "CCPetsPaths.h"
4
+ #import <CoreServices/CoreServices.h>
5
+ #import <fcntl.h>
6
+ #import <unistd.h>
7
+
8
+ @interface CCPetsUsageMonitor ()
9
+ @property CodexUsageReader *codexReader;
10
+ @property ClaudeUsageReader *claudeReader;
11
+ @property(readwrite) NSDictionary *codexUsage;
12
+ @property(readwrite) NSDictionary *claudeUsage;
13
+ @property FSEventStreamRef codexStream;
14
+ @property dispatch_source_t claudeSource;
15
+ @property unsigned long long claudeSize;
16
+ @property NSTimeInterval claudeModifiedAt;
17
+ @property BOOL started;
18
+ - (void)publishChange;
19
+ - (void)startClaudeSource;
20
+ @end
21
+
22
+ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
23
+ void *clientCallBackInfo, size_t numEvents, void *eventPaths,
24
+ const FSEventStreamEventFlags eventFlags[],
25
+ const FSEventStreamEventId eventIds[]) {
26
+ CCPetsUsageMonitor *monitor = (__bridge CCPetsUsageMonitor *)clientCallBackInfo;
27
+ NSArray<NSString *> *paths = (__bridge NSArray<NSString *> *)eventPaths;
28
+ BOOL requiresFullDiscovery = NO;
29
+ NSURL *latestSession = nil;
30
+ for (size_t index = 0; index < numEvents; index++) {
31
+ FSEventStreamEventFlags flags = eventFlags[index];
32
+ if (flags & (kFSEventStreamEventFlagMustScanSubDirs |
33
+ kFSEventStreamEventFlagUserDropped |
34
+ kFSEventStreamEventFlagKernelDropped |
35
+ kFSEventStreamEventFlagRootChanged)) {
36
+ requiresFullDiscovery = YES;
37
+ continue;
38
+ }
39
+ NSString *path = paths[index];
40
+ if ([path.pathExtension.lowercaseString isEqualToString:@"jsonl"] &&
41
+ [path.stringByResolvingSymlinksInPath hasPrefix:
42
+ [monitor.codexReader.sessionsURL.path.stringByResolvingSymlinksInPath
43
+ stringByAppendingString:@"/"]]) {
44
+ latestSession = [NSURL fileURLWithPath:path];
45
+ }
46
+ }
47
+ monitor.codexUsage = requiresFullDiscovery
48
+ ? [monitor.codexReader refreshWithFullDiscovery]
49
+ : (latestSession ? [monitor.codexReader refreshForSessionURL:latestSession] : monitor.codexUsage);
50
+ if (requiresFullDiscovery || latestSession) [monitor publishChange];
51
+ }
52
+
53
+ @implementation CCPetsUsageMonitor
54
+ - (instancetype)init {
55
+ if ((self = [super init])) {
56
+ _codexReader = [CodexUsageReader new];
57
+ _claudeReader = [ClaudeUsageReader new];
58
+ }
59
+ return self;
60
+ }
61
+ - (void)publishChange {
62
+ if (self.changeHandler) self.changeHandler(self.codexUsage, self.claudeUsage);
63
+ }
64
+ // changed=YES 表示额度文件确实变了(VNODE 事件),跳过 stat 比较;
65
+ // aggregate=YES 表示这是手动刷新/面板打开/兜底轮询,Token 聚合要绕过节流立即重算。
66
+ - (NSDictionary *)readClaudeUsageChanged:(BOOL)changed forcingAggregation:(BOOL)aggregate {
67
+ NSString *path = ClaudeUsagePath();
68
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
69
+ unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
70
+ NSTimeInterval modifiedAt = [attributes[NSFileModificationDate] timeIntervalSince1970];
71
+ BOOL unchanged = size == self.claudeSize && modifiedAt == self.claudeModifiedAt;
72
+ self.claudeSize = size;
73
+ self.claudeModifiedAt = modifiedAt;
74
+ if (!changed && !aggregate && unchanged && self.claudeUsage) return self.claudeUsage;
75
+ return aggregate ? [self.claudeReader refreshWithFullAggregation] : [self.claudeReader refresh];
76
+ }
77
+ - (void)startCodexStream {
78
+ if (self.codexStream) return;
79
+ NSString *sessionsPath = self.codexReader.sessionsURL.path;
80
+ BOOL isDirectory = NO;
81
+ if (![NSFileManager.defaultManager fileExistsAtPath:sessionsPath isDirectory:&isDirectory] ||
82
+ !isDirectory) return;
83
+ FSEventStreamContext context = {0, (__bridge void *)self, NULL, NULL, NULL};
84
+ NSArray *paths = @[sessionsPath];
85
+ FSEventStreamCreateFlags flags =
86
+ kFSEventStreamCreateFlagFileEvents |
87
+ kFSEventStreamCreateFlagNoDefer |
88
+ kFSEventStreamCreateFlagUseCFTypes;
89
+ self.codexStream = FSEventStreamCreate(NULL, CodexEventsCallback, &context,
90
+ (__bridge CFArrayRef)paths, kFSEventStreamEventIdSinceNow, 0.5, flags);
91
+ if (!self.codexStream) return;
92
+ FSEventStreamSetDispatchQueue(self.codexStream, dispatch_get_main_queue());
93
+ if (!FSEventStreamStart(self.codexStream)) {
94
+ FSEventStreamInvalidate(self.codexStream);
95
+ FSEventStreamRelease(self.codexStream);
96
+ self.codexStream = NULL;
97
+ }
98
+ }
99
+ - (void)startClaudeSource {
100
+ if (self.claudeSource || !self.started) return;
101
+ NSString *path = ClaudeUsagePath();
102
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
103
+ withIntermediateDirectories:YES attributes:nil error:nil];
104
+ if (![NSFileManager.defaultManager fileExistsAtPath:path]) {
105
+ [NSFileManager.defaultManager createFileAtPath:path contents:nil attributes:nil];
106
+ }
107
+ int descriptor = open(path.fileSystemRepresentation, O_EVTONLY | O_CLOEXEC);
108
+ if (descriptor < 0) return;
109
+ dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
110
+ DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
111
+ DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE, dispatch_get_main_queue());
112
+ if (!source) {
113
+ close(descriptor);
114
+ return;
115
+ }
116
+ self.claudeSource = source;
117
+ __weak typeof(self) weakSelf = self;
118
+ dispatch_source_set_event_handler(source, ^{
119
+ typeof(self) strongSelf = weakSelf;
120
+ if (!strongSelf) return;
121
+ dispatch_source_t current = strongSelf.claudeSource;
122
+ if (!current) return;
123
+ unsigned long flags = dispatch_source_get_data(current);
124
+ strongSelf.claudeUsage = [strongSelf readClaudeUsageChanged:YES forcingAggregation:NO];
125
+ [strongSelf publishChange];
126
+ if (flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE)) {
127
+ strongSelf.claudeSource = nil;
128
+ dispatch_source_cancel(current);
129
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
130
+ dispatch_get_main_queue(), ^{ [weakSelf startClaudeSource]; });
131
+ }
132
+ });
133
+ dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
134
+ dispatch_resume(source);
135
+ }
136
+ - (void)start {
137
+ if (self.started) return;
138
+ self.started = YES;
139
+ [self refreshNow];
140
+ [self startCodexStream];
141
+ [self startClaudeSource];
142
+ }
143
+ - (void)refreshNow {
144
+ // 手动刷新、面板打开和 120 秒兜底都走全量路径,Token 聚合的节流只约束 FSEvents 热路径。
145
+ self.codexUsage = [self.codexReader refreshWithFullDiscovery];
146
+ self.claudeUsage = [self readClaudeUsageChanged:NO forcingAggregation:YES];
147
+ if (!self.codexStream) [self startCodexStream];
148
+ if (!self.claudeSource) [self startClaudeSource];
149
+ [self publishChange];
150
+ }
151
+ - (void)stop {
152
+ self.started = NO;
153
+ if (self.codexStream) {
154
+ FSEventStreamStop(self.codexStream);
155
+ FSEventStreamInvalidate(self.codexStream);
156
+ FSEventStreamRelease(self.codexStream);
157
+ self.codexStream = NULL;
158
+ }
159
+ if (self.claudeSource) {
160
+ dispatch_source_cancel(self.claudeSource);
161
+ self.claudeSource = nil;
162
+ }
163
+ }
164
+ - (void)dealloc {
165
+ [self stop];
166
+ }
167
+ @end
@@ -21,11 +21,13 @@
21
21
  @property(copy) void (^dragStateChanged)(BOOL dragging);
22
22
  @property(copy) NSArray<NSDictionary *> *(^petOptionsRequested)(void);
23
23
  @property(copy) void (^switchPetRequested)(NSString *petID);
24
- @property NSMutableDictionary<NSString *, NSImage *> *petMenuPreviewCache;
24
+ @property NSCache<NSString *, NSImage *> *petMenuPreviewCache;
25
25
  @property NSPanel *petMenuPreviewPanel;
26
26
  @property NSImageView *petMenuPreviewImageView;
27
27
  @property NSTimer *frameTimer;
28
28
  @property(nonatomic) BOOL animationSuspended;
29
+ @property BOOL lowPowerMode;
30
+ @property BOOL reduceMotion;
29
31
  - (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount;
30
32
  - (void)applySheet:(NSImage *)sheet petID:(NSString *)petID rowCount:(NSInteger)rowCount;
31
33
  - (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed;
@@ -1,6 +1,7 @@
1
1
  #import "PetView.h"
2
2
  #import "MenuToggleSwitch.h"
3
3
  #import "CCPetsPaths.h"
4
+ #import "CCPetsImageLoader.h"
4
5
 
5
6
  @implementation PetView
6
7
  - (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount {
@@ -9,7 +10,16 @@
9
10
  _spriteRowCount = rowCount;
10
11
  _lookDirection = -1;
11
12
  _frames = @[@0, @1, @2, @3, @4, @5];
12
- _petMenuPreviewCache = [NSMutableDictionary dictionary];
13
+ _petMenuPreviewCache = [NSCache new];
14
+ _petMenuPreviewCache.countLimit = 24;
15
+ _petMenuPreviewCache.totalCostLimit = 4 * 1024 * 1024;
16
+ [NSNotificationCenter.defaultCenter addObserver:self
17
+ selector:@selector(powerStateDidChange:)
18
+ name:NSProcessInfoPowerStateDidChangeNotification object:nil];
19
+ [NSWorkspace.sharedWorkspace.notificationCenter addObserver:self
20
+ selector:@selector(powerStateDidChange:)
21
+ name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
22
+ [self updatePowerPreferences];
13
23
  [self updateFrameTimer];
14
24
  NSTrackingArea *tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect
15
25
  options:NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
@@ -26,6 +36,21 @@
26
36
  [_frameTimer invalidate];
27
37
  if (_globalMouseMonitor) [NSEvent removeMonitor:_globalMouseMonitor];
28
38
  if (_localMouseMonitor) [NSEvent removeMonitor:_localMouseMonitor];
39
+ [NSNotificationCenter.defaultCenter removeObserver:self];
40
+ [NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self];
41
+ }
42
+ - (void)powerStateDidChange:(NSNotification *)notification {
43
+ [self updatePowerPreferences];
44
+ }
45
+ - (void)updatePowerPreferences {
46
+ BOOL lowPower = NSProcessInfo.processInfo.lowPowerModeEnabled;
47
+ BOOL reduceMotion = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion;
48
+ if (self.lowPowerMode == lowPower && self.reduceMotion == reduceMotion) return;
49
+ self.lowPowerMode = lowPower;
50
+ self.reduceMotion = reduceMotion;
51
+ [self.frameTimer invalidate];
52
+ self.frameTimer = nil;
53
+ [self updateFrameTimer];
29
54
  }
30
55
  // 动画帧只在“可见”且“不处于十六向跟随”时推进。跟随模式显示的是静态定格,
31
56
  // nextFrame: 进来只会立刻 return,定时器纯属空转。
@@ -39,9 +64,12 @@
39
64
  }
40
65
  // block 版定时器 + weak self,避免 NSTimer 持有 target 造成 PetView 永不释放。
41
66
  __weak PetView *weakSelf = self;
42
- self.frameTimer = [NSTimer scheduledTimerWithTimeInterval:PetFrameInterval repeats:YES
67
+ NSTimeInterval interval = PetFrameInterval;
68
+ if (self.lowPowerMode) interval *= 1.5;
69
+ if (self.reduceMotion) interval *= 2.0;
70
+ self.frameTimer = [NSTimer scheduledTimerWithTimeInterval:interval repeats:YES
43
71
  block:^(NSTimer *timer) { [weakSelf nextFrame:timer]; }];
44
- self.frameTimer.tolerance = PetFrameInterval * 0.25;
72
+ self.frameTimer.tolerance = interval * 0.25;
45
73
  }
46
74
  - (void)setLookDirection:(NSInteger)value {
47
75
  if (_lookDirection == value) return;
@@ -298,11 +326,15 @@
298
326
  NSInteger rowCount = [pet[@"spriteRowCount"] integerValue];
299
327
  if (path.length == 0 || rowCount <= 0) return nil;
300
328
 
301
- NSString *cacheKey = [NSString stringWithFormat:@"%@:%ld", path, (long)rowCount];
302
- NSImage *cached = self.petMenuPreviewCache[cacheKey];
329
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
330
+ NSTimeInterval modifiedAt = [attributes[NSFileModificationDate] timeIntervalSince1970];
331
+ unsigned long long fileSize = [attributes[NSFileSize] unsignedLongLongValue];
332
+ NSString *cacheKey = [NSString stringWithFormat:@"%@:%ld:%.6f:%llu",
333
+ path, (long)rowCount, modifiedAt, fileSize];
334
+ NSImage *cached = [self.petMenuPreviewCache objectForKey:cacheKey];
303
335
  if (cached) return cached;
304
336
 
305
- NSImage *sheet = [[NSImage alloc] initWithContentsOfFile:path];
337
+ NSImage *sheet = LoadPetSpriteImage(path, NSMakeSize(92, 76), rowCount);
306
338
  if (!sheet || sheet.size.width <= 0 || sheet.size.height <= 0) return nil;
307
339
 
308
340
  CGFloat cellWidth = sheet.size.width / 8.0;
@@ -316,7 +348,8 @@
316
348
  operation:NSCompositingOperationSourceOver fraction:1.0
317
349
  respectFlipped:NO hints:@{NSImageHintInterpolation: @(NSImageInterpolationNone)}];
318
350
  [preview unlockFocus];
319
- self.petMenuPreviewCache[cacheKey] = preview;
351
+ NSUInteger cost = (NSUInteger)ceil(previewWidth * previewHeight * 4.0);
352
+ [self.petMenuPreviewCache setObject:preview forKey:cacheKey cost:cost];
320
353
  return preview;
321
354
  }
322
355
  - (void)preparePetMenuPreviewPanel {
@@ -13,6 +13,14 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
13
13
  @property NSArray<NSNumber *> *codexHistory;
14
14
  @property NSArray<NSNumber *> *claudeHistory;
15
15
  @property BOOL historyEnabled;
16
+ @property NSInteger activeAgentCount;
17
+ // 仍在运行的客户端所属的 provider("Codex" / "Claude")。卡片的在线徽章据此判定,
18
+ // 而不是看有没有额度数据——额度会一直缓存着,拿它当在线信号会恒亮。
19
+ @property NSSet<NSString *> *liveProviders;
20
+ // 老版本包装脚本写出的 pid 文件没有 provider 名。有这种客户端时无法断言某一家离线。
21
+ @property BOOL hasUnlabeledClient;
22
+ @property NSTimeInterval lastUpdatedAt;
23
+ - (BOOL)isProviderOnline:(NSString *)name;
16
24
  @property NSImage *codexLogo;
17
25
  @property NSImage *claudeLogo;
18
26
  @property BOOL refreshHovered;