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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,25 @@
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ - 新增 Codex 与 Claude Code 本地 Token 用量统计,按官方重置时间对齐 5 小时与 7 天窗口;
8
+ Claude 侧按 `message.id + requestId` 去重,避免 `--resume`/fork 复制的记录重复计数。
9
+ 官方订阅额度仍以服务端百分比为准。
10
+ - Token 聚合改为增量跟读并按额度窗口节流,事件驱动的高频刷新不再重复扫描近 7 天会话;
11
+ 过期日期目录按目录名剪枝,无 Token 数据的会话文件缓存失败结果不再反复重读。
12
+ - 新开 Codex 会话时不再因为尚无 `rate_limits` 而清空面板上已知的额度。
13
+ - 修复额度卡片的在线徽章恒亮:此前按"有没有额度数据"判定,而额度会一直缓存,导致
14
+ 客户端早已退出、甚至单独打开 App 从未运行过 Agent 时两张卡片也显示在线。现改为按该
15
+ provider 是否还有存活客户端判定,并用事件活跃度覆盖不经包装脚本启动的会话。包装脚本
16
+ 启动的会话退出后 3 秒内转为"离线",不再被为直接启动会话准备的 60 秒静默宽限拖住。
17
+ - 额度面板调整信息层级:官方剩余百分比升为主值、本机 Token 降为次级;汇总条改为
18
+ 「今日」与「最近 7 天」双端 Token 合计——两家的 `resets_at` 并不一致,按各自订阅窗口
19
+ 算出的数不在同一区间上,改用与订阅无关的自然日窗口才可相加;"数据刷新"改由面板自身定时器走字;无 Agent 在线时
20
+ 状态配色转灰;额度窗口缺失的列标注"当前无活跃窗口"。
21
+ - 新增 `cc-pets clean` 和带确认的 `cc-pets uninstall --purge`,并自动清理测试临时目录与过期运行状态。
22
+ - 更新日志每次更新前截断,并限制为最近 1 MB,避免长期残留增长。
23
+ - Codex/Claude 额度读取改为 FSEvents/VNODE 事件监听,并保留 120 秒容错刷新,降低空闲文件扫描与 JSON 解析。
24
+ - 精灵图按显示尺寸降采样,菜单预览改用有限缓存;待审批记录增加 TTL 与容量上限。
25
+ - 低电量模式和系统“减少动态效果”开启时自动降低动画刷新频率。
7
26
  - 新增可展开折叠的玻璃 Agent 状态卡片、活跃 CLI 会话数徽标和可选的完成、失败、审批系统通知。
8
27
  - 历史记录与系统通知设置改用右侧高对比度迷你开关,支持在菜单保持展开时连续调整。
9
28
  - 折叠圆钮固定锚定在桌宠头部右上区域,展开和折叠时不再跳动。
package/README.md CHANGED
@@ -134,13 +134,17 @@ cc-pets install
134
134
  ```bash
135
135
  git clone https://gitee.com/wangxinyusqn/cc-pets.git
136
136
  cd cc-pets
137
- npm install -g . --allow-scripts=cc-pets
137
+ npm install -g . --ignore-scripts
138
+ cc-pets install
138
139
  # 首次安装后新开一个终端
139
140
  codex
140
141
  # 或
141
142
  claude
142
143
  ```
143
144
 
145
+ npm 12 会把本地目录安装识别为项目范围安装,不接受命令行传入的 `--allow-scripts`。
146
+ 因此本地源码安装显式跳过生命周期脚本,再通过 `cc-pets install` 执行可重复的初始化流程。
147
+
144
148
  两种方式都会安装 `cc-pets`、`codex-with-pet` 和 `claude-with-pet`。
145
149
  npm 的安装后脚本会自动构建原生应用、安装两套 Agent Hooks,并向 `~/.zshrc` 追加带明确标记的
146
150
  `codex` 与 `claude` alias,不会覆盖真实的 CLI 二进制。首次安装需要新开终端让 alias 生效;以后升级只需执行 npm 命令。
@@ -202,6 +206,9 @@ cc-pets --status
202
206
  # 查看本机额度历史 JSON
203
207
  cc-pets --history
204
208
 
209
+ # 清理可重建的临时状态、更新日志和构建缓存,保留历史、配置与偏好
210
+ cc-pets clean
211
+
205
212
  # 从标准输入发送第三方 Provider 状态事件
206
213
  printf '%s' '{"schemaVersion":1,"provider":"MyAgent","state":"thinking"}' \
207
214
  | cc-pets provider-event
@@ -212,6 +219,9 @@ cc-pets install
212
219
  # 安全移除 Hooks、恢复 Claude status line,并清理 shell alias
213
220
  cc-pets uninstall
214
221
 
222
+ # 完整移除集成、应用和全部本地数据;执行前会再次确认
223
+ cc-pets uninstall --purge
224
+
215
225
  # 仅删除 ~/Applications 中的 macOS 应用(不会删除 npm 包或 Hooks)
216
226
  cc-pets uninstall-app
217
227
 
@@ -233,16 +243,43 @@ Codex 用量来自 `~/.codex/sessions` 的本地 `token_count` 事件:
233
243
  - `window_minutes = 300` 对应 5 小时额度
234
244
  - `window_minutes = 10080` 对应周额度
235
245
  - 桌宠将 `used_percent` 换算为剩余百分比后显示
246
+ - Codex 本地 Token 按服务端 `resets_at - window_minutes` 到 `resets_at` 聚合,
247
+ 与官方 5 小时和 7 天额度周期保持一致
248
+ - Token 统计包含输入、缓存输入、缓存写入、输出、推理输出与总量;面板展示总量
236
249
  - Codex 当前事件未提供某个额度窗口时显示 `--`,不会使用已过期的历史额度冒充当前值
237
250
 
238
251
  Claude 用量来自官方 status line 输入中的 `rate_limits.five_hour` 与
239
252
  `rate_limits.seven_day`。其中的 `used_percentage` 会换算为剩余百分比。该字段仅面向
240
253
  Claude.ai Pro/Max 订阅账号,并在会话完成首次 API 响应后出现;字段尚不可用时显示 `--`。
241
254
 
242
- 额度详情面板使用青色区分 Codex、紫色区分 Claude。5 小时剩余额度使用进度条,周剩余
243
- 额度使用环形进度,右侧展示对应的周重置时间。服务端的 Unix 时间戳会使用 Mac 当前系统时区格式化为
244
- `M/d HH:mm:ss`;因此它与 CLI 中标注其他时区的同一时刻可能日期和小时不同,但代表同一个真实时间。
245
- 应用每 5 秒自动重新读取一次额度,右上角刷新按钮也可立即读取本地数据;Codex 数据随本地 session 更新,Claude 数据则要等 Claude Code
255
+ Claude Code 本地 Token 来自 `~/.claude/projects` 下的会话转录(受 `CLAUDE_CONFIG_DIR`
256
+ 影响):
257
+
258
+ - 每条 `type = assistant` 的记录带 `message.usage`,是**单次请求的增量**,与 Codex 的
259
+ 会话累计值不同,因此按时间戳逐条落窗口累加
260
+ - 窗口同样对齐 `resets_at`;Claude 的 `rate_limits` 不含 `window_minutes`,窗长按官方
261
+ 订阅固定为 300 / 10080 分钟
262
+ - `--resume`、fork 和 compact 会把旧记录原样复制进新的转录文件,因此按
263
+ `message.id + requestId` 全局去重(两者缺失时回退行级 `uuid`),否则用量会明显虚高
264
+ - 统计包含输入、缓存读取、缓存写入、输出与总量;Claude 的思考 token 已计入
265
+ `output_tokens`,不单列推理项
266
+
267
+ 本地 Token 是 CLI 会话事件的原始计数,不等同于订阅额度。官方额度可能受模型、缓存和
268
+ 请求复杂度等因素影响,应始终以服务端返回的百分比为准。
269
+
270
+ 额度详情面板使用青色区分 Codex、紫色区分 Claude。标题行显示在线 Agent 数,下方汇总条
271
+ 展示「今日」与「最近 7 天」的双端 Token 合计和最近刷新时间。汇总用的是与订阅无关的
272
+ 自然日窗口(今日 = 本机零点至今,最近 7 天 = 含今天在内的 7 个自然日),因为两家的
273
+ `resets_at` 并不一致,按各自订阅窗口算出的数不在同一区间上,相加没有意义;每个 Agent 卡片按 5 小时和 7 天两列
274
+ 展示官方剩余百分比(主值)、本机 Token 用量和重置时间,右侧是近 7 天额度趋势。某个窗口
275
+ 当前没有额度数据时该列标注"当前无活跃窗口"。卡片上的在线徽章表示该 Provider 是否还有
276
+ 运行中的客户端(包装脚本写出的 pid 文件,或该 Provider 最近 60 秒内仍在发事件),与是否
277
+ 已采集到额度数据无关;客户端退出后显示"离线",从未采集到数据时显示"等待数据"。经
278
+ `codex-with-pet` / `claude-with-pet` 启动的会话退出后 3 秒内转为离线;直接运行 `codex` /
279
+ `claude` 时没有可靠的退出信号,最多需要 60 秒静默才会转为离线。服务端的 Unix 时间戳会使用 Mac 当前系统时区
280
+ 格式化为 `M/d HH:mm`;因此它与 CLI 中标注其他时区的同一时刻可能日期和小时不同,但代表
281
+ 同一个真实时间。
282
+ 应用通过文件事件实时读取额度,并保留 120 秒容错刷新;右上角刷新按钮也可立即读取本地数据。Codex 数据随本地 session 更新,Claude 数据则要等 Claude Code
246
283
  下一次把 `rate_limits` 传给 status line 后才会变化,按钮不会主动请求 Claude 服务端。
247
284
  面板使用原生 AppKit 毛玻璃材质,以紧凑悬浮卡片形式显示在桌宠左上方,并优先使用本机官方 Codex、Claude 应用
248
285
  图标。鼠标从口袋移动到面板后可继续停留查看,移出两者后面板会延迟收起;拖动桌宠时
@@ -1,7 +1,7 @@
1
1
  #import <Cocoa/Cocoa.h>
2
2
  #import "PetView.h"
3
3
  #import "QuotaDashboardView.h"
4
- #import "CCPetsUsage.h"
4
+ #import "CCPetsUsageMonitor.h"
5
5
 
6
6
  @interface AppDelegate : NSObject <NSApplicationDelegate>
7
7
  @property NSPanel *panel;
@@ -22,6 +22,9 @@
22
22
  @property NSString *lastStatusProvider;
23
23
  @property NSTimeInterval lastStatusTimestamp;
24
24
  @property NSSet<NSString *> *liveClientProviders;
25
+ // 每个 provider 最近一次事件的时间。不经包装脚本启动的客户端没有 pid 文件,
26
+ // 只能靠"最近还在发事件"证明自己活着。
27
+ @property NSMutableDictionary<NSString *, NSNumber *> *providerActivityAt;
25
28
  @property BOOL hasUnlabeledClient;
26
29
  @property NSMutableDictionary<NSString *, NSDictionary *> *pendingApprovalRecords;
27
30
  @property QuotaDashboardView *quotaView;
@@ -31,7 +34,7 @@
31
34
  @property BOOL petDragging;
32
35
  @property NSString *binaryDirectory;
33
36
  @property PetView *petView;
34
- @property CodexUsageReader *codexUsageReader;
37
+ @property CCPetsUsageMonitor *usageMonitor;
35
38
  @property unsigned long long agentEventOffset;
36
39
  @property NSMutableData *agentEventPartialLine;
37
40
  @property dispatch_source_t agentEventSource;
@@ -40,13 +43,16 @@
40
43
  @property BOOL updating;
41
44
  @property NSTask *updateTask;
42
45
  @property NSTimer *usageTimer;
46
+ @property NSTimer *quotaClockTimer;
43
47
  - (void)showQuotaDashboard;
44
48
  - (void)positionQuotaDashboard;
45
49
  - (void)scheduleQuotaDashboardHide;
46
50
  - (void)hideQuotaDashboardIfNeeded;
47
51
  - (void)positionAgentStatus;
48
52
  - (void)showAgentStatusForRecord:(NSDictionary *)record;
53
+ - (void)prunePendingApprovalRecords;
49
54
  - (void)toggleAgentStatusBubble:(id)sender;
50
55
  - (void)refreshUsage:(id)sender;
56
+ - (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage;
51
57
  - (void)switchPetToID:(NSString *)petID;
52
58
  @end
@@ -3,6 +3,7 @@
3
3
  #import "CCPetsVersion.h"
4
4
  #import "CCPetsEvents.h"
5
5
  #import "CCPetsQuotaHistory.h"
6
+ #import "CCPetsImageLoader.h"
6
7
  #import "MenuToggleSwitch.h"
7
8
  #import <UserNotifications/UserNotifications.h>
8
9
  #import <signal.h>
@@ -11,6 +12,25 @@
11
12
  #import <unistd.h>
12
13
  #import <errno.h>
13
14
 
15
+ static const NSTimeInterval PendingApprovalTTL = 24 * 60 * 60;
16
+ static const NSUInteger PendingApprovalLimit = 100;
17
+ static const unsigned long long UpdateLogSizeLimit = 1024 * 1024;
18
+
19
+ static void TrimUpdateLog(NSString *path) {
20
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
21
+ if (!handle) return;
22
+ unsigned long long size = [handle seekToEndOfFile];
23
+ if (size <= UpdateLogSizeLimit) {
24
+ [handle closeFile];
25
+ return;
26
+ }
27
+ [handle seekToFileOffset:size - UpdateLogSizeLimit];
28
+ NSData *tail = [handle readDataToEndOfFile];
29
+ [handle closeFile];
30
+ [tail writeToFile:path options:NSDataWritingAtomic error:nil];
31
+ chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
32
+ }
33
+
14
34
  @implementation AppDelegate
15
35
  - (NSString *)applicationSupportDirectory {
16
36
  return ApplicationSupportDirectory();
@@ -89,9 +109,8 @@
89
109
  return;
90
110
  }
91
111
  NSString *logPath = [supportDirectory stringByAppendingPathComponent:@"update.log"];
92
- [NSFileManager.defaultManager createFileAtPath:logPath contents:nil attributes:@{
93
- NSFilePosixPermissions: @(S_IRUSR | S_IWUSR)
94
- }];
112
+ [NSData.data writeToFile:logPath options:NSDataWritingAtomic error:nil];
113
+ chmod(logPath.fileSystemRepresentation, S_IRUSR | S_IWUSR);
95
114
  NSFileHandle *logHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
96
115
  if (!logHandle) {
97
116
  [self showUpdateAlertWithTitle:@"无法自动更新" message:@"无法创建更新日志。"];
@@ -123,6 +142,7 @@
123
142
  __weak typeof(self) weakSelf = self;
124
143
  task.terminationHandler = ^(NSTask *finishedTask) {
125
144
  [logHandle closeFile];
145
+ TrimUpdateLog(logPath);
126
146
  dispatch_async(dispatch_get_main_queue(), ^{
127
147
  typeof(self) strongSelf = weakSelf;
128
148
  if (!strongSelf) return;
@@ -399,6 +419,9 @@
399
419
  self.lastStatusState = state;
400
420
  self.lastStatusProvider = provider;
401
421
  self.lastStatusTimestamp = [NSDate.date timeIntervalSince1970];
422
+ if (!self.providerActivityAt) self.providerActivityAt = [NSMutableDictionary dictionary];
423
+ self.providerActivityAt[provider] = @(self.lastStatusTimestamp);
424
+ [self updateQuotaLiveState];
402
425
  self.statusTitleLabel.stringValue = [NSString stringWithFormat:@"%@ · %@",
403
426
  provider, [self statusTextForState:state tool:tool]];
404
427
  self.statusDetailLabel.stringValue = [self statusDetailForState:state];
@@ -431,6 +454,29 @@
431
454
  ? [NSString stringWithFormat:@"%@:%@", provider, session]
432
455
  : provider;
433
456
  }
457
+ - (void)prunePendingApprovalRecords {
458
+ NSTimeInterval cutoff = NSDate.date.timeIntervalSince1970 - PendingApprovalTTL;
459
+ for (NSString *key in self.pendingApprovalRecords.allKeys) {
460
+ NSDictionary *record = self.pendingApprovalRecords[key];
461
+ if ([record[@"timestamp"] doubleValue] < cutoff) {
462
+ [self.pendingApprovalRecords removeObjectForKey:key];
463
+ }
464
+ }
465
+ if (self.pendingApprovalRecords.count <= PendingApprovalLimit) return;
466
+ NSArray<NSDictionary *> *oldestFirst = [self.pendingApprovalRecords.allValues
467
+ sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
468
+ NSTimeInterval leftTime = [left[@"timestamp"] doubleValue];
469
+ NSTimeInterval rightTime = [right[@"timestamp"] doubleValue];
470
+ if (leftTime < rightTime) return NSOrderedAscending;
471
+ if (leftTime > rightTime) return NSOrderedDescending;
472
+ return NSOrderedSame;
473
+ }];
474
+ NSUInteger removeCount = oldestFirst.count - PendingApprovalLimit;
475
+ for (NSUInteger index = 0; index < removeCount; index++) {
476
+ NSString *key = [self approvalKeyForRecord:oldestFirst[index]];
477
+ [self.pendingApprovalRecords removeObjectForKey:key];
478
+ }
479
+ }
434
480
  - (NSDictionary *)latestPendingApprovalRecord {
435
481
  NSDictionary *latest = nil;
436
482
  for (NSDictionary *record in self.pendingApprovalRecords.allValues) {
@@ -614,7 +660,8 @@
614
660
  NSDictionary *selectedOption = [self petOptionWithID:selected inOptions:petOptions] ?: petOptions.firstObject;
615
661
  selected = selectedOption[@"id"];
616
662
  NSString *spritePath = selectedOption[@"path"];
617
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:spritePath];
663
+ NSImage *image = LoadPetSpriteImage(spritePath, NSMakeSize(140, 150),
664
+ [selectedOption[@"spriteRowCount"] integerValue] ?: 9);
618
665
  if (!image) {
619
666
  fprintf(stderr, "无法读取桌宠素材: %s\n", spritePath.UTF8String);
620
667
  [NSApp terminate:nil];
@@ -807,10 +854,13 @@
807
854
  NSRect visible = screen.visibleFrame;
808
855
  [self.panel setFrameOrigin:NSMakePoint(NSMaxX(visible) - size.width - 24, NSMinY(visible) + 18)];
809
856
  [self.panel orderFrontRegardless];
810
- self.codexUsageReader = [CodexUsageReader new];
857
+ self.usageMonitor = [CCPetsUsageMonitor new];
811
858
  self.agentEventPartialLine = [NSMutableData data];
812
859
  self.pendingApprovalRecords = [NSMutableDictionary dictionary];
813
- [self refreshUsage:nil];
860
+ self.usageMonitor.changeHandler = ^(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
861
+ [weakSelf applyCodexUsage:codexUsage claudeUsage:claudeUsage];
862
+ };
863
+ [self.usageMonitor start];
814
864
  if ([NSProcessInfo.processInfo.arguments containsObject:@"--preview-dashboard"]) {
815
865
  self.pocketHovering = YES;
816
866
  [self showQuotaDashboard];
@@ -857,6 +907,23 @@
857
907
  [self.quotaPanel orderFrontRegardless];
858
908
  [self.panel orderFrontRegardless];
859
909
  [self rescheduleUsageTimer];
910
+ [self startQuotaClock];
911
+ }
912
+ // "数据刷新" 显示的是相对时间,没有新数据也得自己走字。面板隐藏时不需要这个定时器,
913
+ // 隐藏的窗口本来就不会重绘。
914
+ - (void)startQuotaClock {
915
+ if (self.quotaClockTimer.isValid) return;
916
+ self.quotaClockTimer = [NSTimer scheduledTimerWithTimeInterval:QuotaClockInterval
917
+ target:self selector:@selector(tickQuotaClock:) userInfo:nil repeats:YES];
918
+ self.quotaClockTimer.tolerance = QuotaClockInterval * 0.3;
919
+ }
920
+ - (void)tickQuotaClock:(id)sender {
921
+ if (!self.quotaPanel.isVisible) {
922
+ [self.quotaClockTimer invalidate];
923
+ self.quotaClockTimer = nil;
924
+ return;
925
+ }
926
+ self.quotaView.needsDisplay = YES;
860
927
  }
861
928
  - (void)positionQuotaDashboard {
862
929
  NSRect petFrame = self.panel.frame;
@@ -904,15 +971,17 @@
904
971
  if (!self.pocketHovering && !self.dashboardHovering && !self.petDragging) {
905
972
  [self.quotaPanel orderOut:nil];
906
973
  [self rescheduleUsageTimer];
974
+ [self.quotaClockTimer invalidate];
975
+ self.quotaClockTimer = nil;
907
976
  }
908
977
  }
909
978
  - (void)switchPetToID:(NSString *)petID {
910
979
  NSArray<NSDictionary *> *options = [self discoverPetOptions];
911
980
  NSDictionary *option = [self petOptionWithID:petID inOptions:options];
912
981
  if (!option) return;
913
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:option[@"path"]];
914
- if (!image) return;
915
982
  NSInteger spriteRowCount = [option[@"spriteRowCount"] integerValue] ?: 9;
983
+ NSImage *image = LoadPetSpriteImage(option[@"path"], NSMakeSize(140, 150), spriteRowCount);
984
+ if (!image) return;
916
985
  [self.petView applySheet:image petID:petID rowCount:spriteRowCount];
917
986
  [NSUserDefaults.standardUserDefaults setObject:petID forKey:@"CCPetsSelectedSprite"];
918
987
  }
@@ -975,6 +1044,7 @@
975
1044
  if (!self.pendingApprovalRecords) {
976
1045
  self.pendingApprovalRecords = [NSMutableDictionary dictionary];
977
1046
  }
1047
+ [self prunePendingApprovalRecords];
978
1048
  NSString *approvalKey = [self approvalKeyForRecord:record];
979
1049
  NSDictionary *previousPriority = [self latestPendingApprovalRecord];
980
1050
  BOOL manualApproval = [state isEqualToString:@"approval"];
@@ -983,6 +1053,7 @@
983
1053
  } else {
984
1054
  [self.pendingApprovalRecords removeObjectForKey:approvalKey];
985
1055
  }
1056
+ [self prunePendingApprovalRecords];
986
1057
  NSDictionary *currentPriority = [self latestPendingApprovalRecord];
987
1058
  if (currentPriority) {
988
1059
  if (manualApproval) {
@@ -1051,7 +1122,27 @@
1051
1122
  - (void)ensureAgentEventReader:(id)sender {
1052
1123
  if (!self.agentEventSource) [self startAgentEventReader];
1053
1124
  }
1125
+ // 在线判定合并两个信号:包装脚本写出的客户端 pid 文件,以及该 provider 最近是否还在
1126
+ // 发事件。只看前者会把直接跑 claude / codex 的会话误判成离线;只看后者则在客户端退出后
1127
+ // 还要挂满一整个静默窗口。额度数据本身不是在线信号——它一直缓存着,用它判定会恒亮。
1128
+ - (void)updateQuotaLiveState {
1129
+ NSMutableSet<NSString *> *online = [self.liveClientProviders mutableCopy] ?: [NSMutableSet set];
1130
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
1131
+ for (NSString *provider in self.providerActivityAt) {
1132
+ NSTimeInterval last = [self.providerActivityAt[provider] doubleValue];
1133
+ if (now - last < AgentStatusInactivityInterval) [online addObject:provider];
1134
+ }
1135
+ NSInteger count = MAX(self.liveClientCount, (NSInteger)online.count);
1136
+ if (self.quotaView.activeAgentCount == count &&
1137
+ [self.quotaView.liveProviders isEqualToSet:online] &&
1138
+ self.quotaView.hasUnlabeledClient == self.hasUnlabeledClient) return;
1139
+ self.quotaView.activeAgentCount = count;
1140
+ self.quotaView.liveProviders = online;
1141
+ self.quotaView.hasUnlabeledClient = self.hasUnlabeledClient;
1142
+ self.quotaView.needsDisplay = YES;
1143
+ }
1054
1144
  - (void)refreshClientLifecycle:(id)sender {
1145
+ [self prunePendingApprovalRecords];
1055
1146
  NSString *clientName = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
1056
1147
  NSString *clientDirectory = [PetStateDirectory() stringByAppendingPathComponent:clientName];
1057
1148
  NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
@@ -1075,9 +1166,20 @@
1075
1166
  if (label.length > 0 && label.length <= 32) [providers addObject:label];
1076
1167
  else unlabeled = YES;
1077
1168
  }
1169
+ // 包装脚本启动的客户端有精确的退出信号:pid 文件被回收。这一段不该被为"直接跑
1170
+ // claude / codex"准备的 60 秒活跃度宽限盖住,否则退出后还要挂满一分钟才转离线。
1171
+ // 因此某一家的 pid 文件一旦从有变无,立刻丢掉它的活跃度记录;从来没有过 pid 文件
1172
+ // 的(直接启动)不受影响,继续走宽限。
1173
+ NSSet<NSString *> *previousProviders = self.liveClientProviders;
1078
1174
  self.liveClientCount = liveClients;
1079
1175
  self.liveClientProviders = providers;
1080
1176
  self.hasUnlabeledClient = unlabeled;
1177
+ for (NSString *provider in previousProviders) {
1178
+ if (![providers containsObject:provider]) {
1179
+ [self.providerActivityAt removeObjectForKey:provider];
1180
+ }
1181
+ }
1182
+ [self updateQuotaLiveState];
1081
1183
  [self hideAgentStatusIfClientGone];
1082
1184
  if (self.statusTogglePanel.isVisible && !self.statusBubbleExpanded) {
1083
1185
  [self updateStatusToggleAppearance];
@@ -1086,16 +1188,21 @@
1086
1188
  // Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
1087
1189
  if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
1088
1190
  }
1089
- - (void)refreshUsage:(id)sender {
1090
- self.quotaView.codexUsage = [self.codexUsageReader refresh];
1091
- self.quotaView.claudeUsage = LatestClaudeUsage();
1191
+ - (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage {
1192
+ self.quotaView.codexUsage = codexUsage;
1193
+ self.quotaView.claudeUsage = claudeUsage;
1092
1194
  NSDictionary *history = RecordQuotaHistory(self.quotaView.codexUsage,
1093
1195
  self.quotaView.claudeUsage);
1094
1196
  self.quotaView.codexHistory = QuotaHistorySeries(history, @"codex");
1095
1197
  self.quotaView.claudeHistory = QuotaHistorySeries(history, @"claude");
1198
+ self.quotaView.lastUpdatedAt = NSDate.date.timeIntervalSince1970;
1096
1199
  self.quotaView.needsDisplay = YES;
1097
1200
  }
1201
+ - (void)refreshUsage:(id)sender {
1202
+ [self.usageMonitor refreshNow];
1203
+ }
1098
1204
  - (void)applicationWillTerminate:(NSNotification *)notification {
1205
+ [self.usageMonitor stop];
1099
1206
  if (self.agentEventSource) {
1100
1207
  dispatch_source_cancel(self.agentEventSource);
1101
1208
  self.agentEventSource = nil;
@@ -0,0 +1,7 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // 启动时只清理已经过期且不再有展示价值的临时状态。
4
+ void PruneStaleRuntimeState(void);
5
+
6
+ // clean 删除可重建缓存;purge 额外删除历史、更新配置和用户偏好。
7
+ int CleanCCPetsData(BOOL purge);
@@ -0,0 +1,126 @@
1
+ #import "CCPetsCleanup.h"
2
+ #import "CCPetsPaths.h"
3
+ #import <sys/file.h>
4
+ #import <fcntl.h>
5
+ #import <signal.h>
6
+ #import <unistd.h>
7
+ #import <errno.h>
8
+
9
+ static const NSTimeInterval RuntimeStateTTL = 7 * 24 * 60 * 60;
10
+ static NSString *const PreferencesDomain = @"com.universewang.cc-pets";
11
+
12
+ static NSString *RuntimeLockPath(void) {
13
+ NSString *name = [NSString stringWithFormat:@"cc-pets-%u.lock", getuid()];
14
+ return [PetStateDirectory() stringByAppendingPathComponent:name];
15
+ }
16
+
17
+ static NSString *ClientStateDirectory(void) {
18
+ NSString *name = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
19
+ return [PetStateDirectory() stringByAppendingPathComponent:name];
20
+ }
21
+
22
+ static BOOL RemoveIfPresent(NSString *path) {
23
+ if (path.length == 0 || ![NSFileManager.defaultManager fileExistsAtPath:path]) return NO;
24
+ return [NSFileManager.defaultManager removeItemAtPath:path error:nil];
25
+ }
26
+
27
+ static BOOL RuntimeIsActive(void) {
28
+ NSString *lockPath = RuntimeLockPath();
29
+ if (![NSFileManager.defaultManager fileExistsAtPath:lockPath]) return NO;
30
+ int descriptor = open(lockPath.fileSystemRepresentation, O_RDWR | O_CLOEXEC);
31
+ if (descriptor < 0) return YES;
32
+ BOOL active = flock(descriptor, LOCK_EX | LOCK_NB) != 0;
33
+ if (!active) flock(descriptor, LOCK_UN);
34
+ close(descriptor);
35
+ return active;
36
+ }
37
+
38
+ static void RemoveExpiredFile(NSString *path, NSTimeInterval cutoff) {
39
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
40
+ NSDate *modified = attributes[NSFileModificationDate];
41
+ if (modified && modified.timeIntervalSince1970 < cutoff) RemoveIfPresent(path);
42
+ }
43
+
44
+ static void RemoveDeadClientRecords(void) {
45
+ NSString *directory = ClientStateDirectory();
46
+ NSArray<NSString *> *entries =
47
+ [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil] ?: @[];
48
+ for (NSString *entry in entries) {
49
+ pid_t pid = (pid_t)entry.intValue;
50
+ BOOL alive = pid > 1 && (kill(pid, 0) == 0 || errno == EPERM);
51
+ if (!alive) RemoveIfPresent([directory stringByAppendingPathComponent:entry]);
52
+ }
53
+ if ([NSFileManager.defaultManager
54
+ contentsOfDirectoryAtPath:directory error:nil].count == 0) {
55
+ RemoveIfPresent(directory);
56
+ }
57
+ }
58
+
59
+ static NSString *BuildCacheDirectory(void) {
60
+ NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_BUILD_CACHE_DIR"];
61
+ if (override.length > 0) return override.stringByStandardizingPath;
62
+ NSString *binary = NSProcessInfo.processInfo.arguments.firstObject.stringByStandardizingPath;
63
+ NSString *release = binary.stringByDeletingLastPathComponent;
64
+ if (![release.lastPathComponent isEqualToString:@"release"]) return nil;
65
+ return [[release stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"clang-cache"];
66
+ }
67
+
68
+ static BOOL IsSafeSupportDirectory(NSString *path) {
69
+ NSString *standardized = path.stringByStandardizingPath;
70
+ NSString *expected = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"]
71
+ stringByAppendingPathComponent:@"Application Support"]
72
+ stringByAppendingPathComponent:@"CC Pets"].stringByStandardizingPath;
73
+ if ([standardized isEqualToString:expected]) return YES;
74
+ return [standardized.lastPathComponent isEqualToString:@"CC Pets"] &&
75
+ [standardized.stringByDeletingLastPathComponent.lastPathComponent
76
+ isEqualToString:@"Application Support"];
77
+ }
78
+
79
+ static BOOL IsSafeBuildCacheDirectory(NSString *path) {
80
+ NSString *standardized = path.stringByStandardizingPath;
81
+ return [standardized.lastPathComponent isEqualToString:@"clang-cache"] &&
82
+ [standardized.stringByDeletingLastPathComponent.lastPathComponent isEqualToString:@".build"];
83
+ }
84
+
85
+ void PruneStaleRuntimeState(void) {
86
+ NSTimeInterval cutoff = NSDate.date.timeIntervalSince1970 - RuntimeStateTTL;
87
+ RemoveExpiredFile(AgentEventPath(), cutoff);
88
+ RemoveExpiredFile(ClaudeUsagePath(), cutoff);
89
+ RemoveDeadClientRecords();
90
+ }
91
+
92
+ int CleanCCPetsData(BOOL purge) {
93
+ if (RuntimeIsActive()) {
94
+ fputs("清理失败:CC Pets 正在运行,请先退出桌宠。\n", stderr);
95
+ return 2;
96
+ }
97
+ NSString *supportDirectory = ApplicationSupportDirectory();
98
+ NSString *buildCache = BuildCacheDirectory();
99
+ if (!IsSafeSupportDirectory(supportDirectory)) {
100
+ fprintf(stderr, "清理失败:应用数据目录不属于 CC Pets:%s\n",
101
+ supportDirectory.UTF8String);
102
+ return 3;
103
+ }
104
+ if (buildCache.length > 0 && !IsSafeBuildCacheDirectory(buildCache)) {
105
+ fprintf(stderr, "清理失败:构建缓存目录不属于 CC Pets:%s\n",
106
+ buildCache.UTF8String);
107
+ return 3;
108
+ }
109
+ NSUInteger removed = 0;
110
+ for (NSString *path in @[AgentEventPath(), ClaudeUsagePath(), RuntimeLockPath(),
111
+ ClientStateDirectory(), buildCache ?: @""]) {
112
+ if (RemoveIfPresent(path)) removed += 1;
113
+ }
114
+ NSString *updateLog = [supportDirectory stringByAppendingPathComponent:@"update.log"];
115
+ if (RemoveIfPresent(updateLog)) removed += 1;
116
+ if (purge) {
117
+ if (RemoveIfPresent(supportDirectory)) removed += 1;
118
+ NSString *domain = NSProcessInfo.processInfo.environment[@"CC_PETS_PREFERENCES_DOMAIN"];
119
+ if (domain.length == 0) domain = PreferencesDomain;
120
+ [NSUserDefaults.standardUserDefaults removePersistentDomainForName:domain];
121
+ [NSUserDefaults.standardUserDefaults synchronize];
122
+ }
123
+ printf("%s完成,共移除 %lu 项。\n", purge ? "完整数据清理" : "缓存清理",
124
+ (unsigned long)removed);
125
+ return EXIT_SUCCESS;
126
+ }
@@ -0,0 +1,4 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // 按桌宠实际绘制尺寸解码精灵图,避免让超大外部素材长期占用完整 RGBA 内存。
4
+ NSImage *LoadPetSpriteImage(NSString *path, NSSize cellSize, NSInteger rowCount);
@@ -0,0 +1,36 @@
1
+ #import "CCPetsImageLoader.h"
2
+ #import <ImageIO/ImageIO.h>
3
+
4
+ NSImage *LoadPetSpriteImage(NSString *path, NSSize cellSize, NSInteger rowCount) {
5
+ if (path.length == 0 || rowCount <= 0) return nil;
6
+ NSURL *url = [NSURL fileURLWithPath:path];
7
+ CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)url, NULL);
8
+ if (!source) return nil;
9
+ NSDictionary *properties = CFBridgingRelease(
10
+ CGImageSourceCopyPropertiesAtIndex(source, 0, NULL));
11
+ CGFloat sourceWidth = [properties[(NSString *)kCGImagePropertyPixelWidth] doubleValue];
12
+ CGFloat sourceHeight = [properties[(NSString *)kCGImagePropertyPixelHeight] doubleValue];
13
+ CGFloat desiredWidth = MAX(1.0, cellSize.width) * 8.0;
14
+ CGFloat desiredHeight = MAX(1.0, cellSize.height) * rowCount;
15
+ CGFloat scale = MIN(1.0, MAX(desiredWidth / MAX(1.0, sourceWidth),
16
+ desiredHeight / MAX(1.0, sourceHeight)));
17
+ if (scale >= 0.98) {
18
+ CFRelease(source);
19
+ return [[NSImage alloc] initWithContentsOfFile:path];
20
+ }
21
+ CGFloat maximumPixelSize = ceil(MAX(sourceWidth, sourceHeight) * scale);
22
+ NSDictionary *options = @{
23
+ (NSString *)kCGImageSourceCreateThumbnailFromImageAlways: @YES,
24
+ (NSString *)kCGImageSourceCreateThumbnailWithTransform: @YES,
25
+ (NSString *)kCGImageSourceThumbnailMaxPixelSize: @(maximumPixelSize),
26
+ (NSString *)kCGImageSourceShouldCacheImmediately: @YES
27
+ };
28
+ CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(
29
+ source, 0, (__bridge CFDictionaryRef)options);
30
+ CFRelease(source);
31
+ if (!imageRef) return [[NSImage alloc] initWithContentsOfFile:path];
32
+ NSImage *image = [[NSImage alloc] initWithCGImage:imageRef
33
+ size:NSMakeSize(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef))];
34
+ CGImageRelease(imageRef);
35
+ return image;
36
+ }
@@ -19,5 +19,6 @@ extern const NSTimeInterval AgentStatusOrphanInterval;
19
19
  extern const NSTimeInterval UsageRefreshIntervalVisible;
20
20
  extern const NSTimeInterval UsageRefreshIntervalHidden;
21
21
  extern const NSTimeInterval ClientLifecycleInterval;
22
+ extern const NSTimeInterval QuotaClockInterval;
22
23
  extern const NSTimeInterval AgentEventReaderCheckInterval;
23
24
  extern const NSTimeInterval PetFrameInterval;
@@ -38,11 +38,13 @@ const NSTimeInterval AgentStatusInactivityInterval = 60.0;
38
38
  // 留这段宽限是因为不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid
39
39
  // 文件,只能靠"最近还在发事件"证明自己活着,不能一看不到 pid 文件就清掉。
40
40
  const NSTimeInterval AgentStatusOrphanInterval = 10.0;
41
- // 额度面板不可见时没人看这些数字,降到 60 秒;打开面板时 showQuotaDashboard 会
42
- // 立刻刷新一次,所以降频对显示的新鲜度没有影响。
43
- const NSTimeInterval UsageRefreshIntervalVisible = 5.0;
44
- const NSTimeInterval UsageRefreshIntervalHidden = 60.0;
41
+ // 额度变化由 FSEvents/VNODE 主动推送;定时器只保留为监听不可用时的 120 秒兜底。
42
+ // 打开面板和手动刷新仍会立即读取一次。
43
+ const NSTimeInterval UsageRefreshIntervalVisible = 120.0;
44
+ const NSTimeInterval UsageRefreshIntervalHidden = 120.0;
45
45
  const NSTimeInterval ClientLifecycleInterval = 3.0;
46
+ // 面板上"数据刷新"是相对时间,仅在面板可见时按这个间隔重绘走字。
47
+ const NSTimeInterval QuotaClockInterval = 10.0;
46
48
  const NSTimeInterval AgentEventReaderCheckInterval = 5.0;
47
49
  // 精灵动画帧间隔。定时器的 tolerance 让内核可以合并唤醒。
48
50
  const NSTimeInterval PetFrameInterval = 0.22;
@@ -12,15 +12,33 @@ int RenderQuotaDashboard(NSString *path) {
12
12
  view.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
13
13
  view.codexUsage = LatestUsage() ?: @{
14
14
  @"fiveHour": @{@"used_percent": @34, @"resets_at": @([NSDate.date timeIntervalSince1970] + 7200)},
15
- @"week": @{@"used_percent": @51, @"resets_at": @([NSDate.date timeIntervalSince1970] + 172800)}
15
+ @"week": @{@"used_percent": @51, @"resets_at": @([NSDate.date timeIntervalSince1970] + 172800)},
16
+ @"tokenUsage": @{
17
+ @"fiveHour": @{@"total_tokens": @1284000},
18
+ @"week": @{@"total_tokens": @8642000},
19
+ @"today": @{@"total_tokens": @2140000},
20
+ @"recentWeek": @{@"total_tokens": @8980000},
21
+ @"source": @"local"
22
+ }
16
23
  };
17
24
  view.claudeUsage = LatestClaudeUsage() ?: @{
18
25
  @"fiveHour": @{@"used_percentage": @23, @"resets_at": @([NSDate.date timeIntervalSince1970] + 3600)},
19
- @"week": @{@"used_percentage": @41, @"resets_at": @([NSDate.date timeIntervalSince1970] + 86400)}
26
+ @"week": @{@"used_percentage": @41, @"resets_at": @([NSDate.date timeIntervalSince1970] + 86400)},
27
+ @"tokenUsage": @{
28
+ @"fiveHour": @{@"total_tokens": @962000},
29
+ @"week": @{@"total_tokens": @5310000},
30
+ @"today": @{@"total_tokens": @1470000},
31
+ @"recentWeek": @{@"total_tokens": @5620000},
32
+ @"source": @"local"
33
+ }
20
34
  };
21
35
  view.historyEnabled = YES;
22
36
  view.codexHistory = @[@88, @81, @75, @68, @62, @55, @49];
23
37
  view.claudeHistory = @[@92, @86, @78, @72, @64, @58, @51];
38
+ view.activeAgentCount = 1;
39
+ // 预览里刻意只让一家在线,好把"有额度数据但客户端已退出"的离线态也画出来。
40
+ view.liveProviders = [NSSet setWithObject:@"Claude"];
41
+ view.lastUpdatedAt = NSDate.date.timeIntervalSince1970 - 12;
24
42
  NSInteger pixelWidth = (NSInteger)ceil(NSWidth(view.bounds));
25
43
  NSInteger pixelHeight = (NSInteger)ceil(NSHeight(view.bounds));
26
44
  NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]