cc-pets 2.0.0 → 2.0.3

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +73 -30
  2. package/CHANGELOG.zh-CN.md +90 -0
  3. package/CONTRIBUTING.md +18 -15
  4. package/CONTRIBUTING.zh-CN.md +22 -0
  5. package/LICENSE +1 -1
  6. package/PROVIDER_PROTOCOL.md +50 -41
  7. package/PROVIDER_PROTOCOL.zh-CN.md +58 -0
  8. package/README.md +240 -502
  9. package/README.zh-CN.md +617 -0
  10. package/Resources/Info.plist +2 -0
  11. package/Resources/phrases.default.txt +48 -49
  12. package/SECURITY.md +13 -10
  13. package/SECURITY.zh-CN.md +18 -0
  14. package/Sources/CCPets/CCPetsAppDelegate.h +12 -0
  15. package/Sources/CCPets/CCPetsAppDelegate.m +400 -37
  16. package/Sources/CCPets/CCPetsCodexRateLimits.h +13 -0
  17. package/Sources/CCPets/CCPetsCodexRateLimits.m +383 -0
  18. package/Sources/CCPets/CCPetsEvents.m +7 -2
  19. package/Sources/CCPets/CCPetsPaths.h +4 -0
  20. package/Sources/CCPets/CCPetsPaths.m +6 -0
  21. package/Sources/CCPets/CCPetsPhrases.h +1 -24
  22. package/Sources/CCPets/CCPetsPhrases.m +1 -82
  23. package/Sources/CCPets/CCPetsPhrasesEditor.m +0 -28
  24. package/Sources/CCPets/CCPetsQuotaHistory.m +12 -5
  25. package/Sources/CCPets/CCPetsTerminalFocus.h +11 -0
  26. package/Sources/CCPets/CCPetsTerminalFocus.m +150 -0
  27. package/Sources/CCPets/CCPetsUsage.m +135 -14
  28. package/Sources/CCPets/CCPetsUsageMonitor.m +41 -3
  29. package/Sources/CCPets/PetView.m +19 -11
  30. package/Sources/CCPets/QuotaDashboardView.m +38 -16
  31. package/Sources/CCPets/main.m +5 -0
  32. package/THIRD_PARTY_NOTICES.md +13 -7
  33. package/THIRD_PARTY_NOTICES.zh-CN.md +12 -0
  34. package/bin/claude-with-pet +8 -2
  35. package/bin/codex-with-pet +8 -3
  36. package/package.json +14 -5
  37. package/scripts/pet-store.mjs +1 -1
@@ -0,0 +1,150 @@
1
+ #import "CCPetsTerminalFocus.h"
2
+ #import "CCPetsEvents.h"
3
+ #import <sys/sysctl.h>
4
+ #import <sys/stat.h>
5
+ #import <stdlib.h>
6
+ #import <unistd.h>
7
+
8
+ static BOOL ProcessInfoForPID(pid_t pid, struct kinfo_proc *info) {
9
+ if (pid <= 0) return NO;
10
+ size_t length = sizeof(*info);
11
+ int name[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
12
+ return sysctl(name, 4, info, &length, NULL, 0) == 0 && length > 0;
13
+ }
14
+
15
+ // 包装脚本没被走到时(用户直接跑 codex / claude,或终端窗口早于 shim 安装就已打开)
16
+ // 环境里没有 CC_PETS_TERMINAL_*。记录端自己是 Agent 的子进程,控制终端就是 Agent
17
+ // 所在的那个 tty,直接问内核即可——stdin 是 JSON 管道,isatty 这类办法在这里没用。
18
+ static NSString *ControllingTerminalName(void) {
19
+ struct kinfo_proc info;
20
+ if (!ProcessInfoForPID(getpid(), &info)) return @"";
21
+ dev_t device = info.kp_eproc.e_tdev;
22
+ if (device == NODEV) return @"";
23
+ const char *tty = devname(device, S_IFCHR);
24
+ return tty ? @(tty).lastPathComponent : @"";
25
+ }
26
+
27
+ // 承载终端的应用:沿父进程链往上走,第一个能被 NSRunningApplication 认领的就是
28
+ // GUI 应用本体(Ghostty / Terminal / iTerm2 …)。不能用"当前前台应用"兜底——
29
+ // Hook 触发时用户往往已经切到别的窗口,那样会把跳转目标记错。
30
+ static NSString *HostApplicationBundleIdentifier(void) {
31
+ pid_t pid = getppid();
32
+ for (NSUInteger depth = 0; depth < 16 && pid > 1; depth++) {
33
+ NSString *bundleID = [NSRunningApplication
34
+ runningApplicationWithProcessIdentifier:pid].bundleIdentifier;
35
+ if (bundleID.length > 0) return bundleID;
36
+ struct kinfo_proc info;
37
+ if (!ProcessInfoForPID(pid, &info)) break;
38
+ pid = info.kp_eproc.e_ppid;
39
+ }
40
+ return @"";
41
+ }
42
+
43
+ static NSString *TerminalTargetValue(NSDictionary<NSString *, NSString *> *environment,
44
+ NSString *key, NSUInteger maximumLength) {
45
+ return SanitizedShortString(environment[key], maximumLength);
46
+ }
47
+
48
+ NSDictionary *TerminalFocusTargetFromEnvironment(void) {
49
+ NSDictionary<NSString *, NSString *> *environment = NSProcessInfo.processInfo.environment;
50
+ NSString *tty = environment[@"CC_PETS_TERMINAL_TTY"];
51
+ if ([tty isKindOfClass:NSString.class]) tty = tty.lastPathComponent;
52
+ tty = SanitizedShortString(tty, 64);
53
+ NSString *program = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_PROGRAM", 64);
54
+ NSString *session = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_SESSION", 128);
55
+ NSString *bundleID = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_BUNDLE_ID", 128);
56
+ if (tty.length == 0) tty = SanitizedShortString(ControllingTerminalName(), 64);
57
+ if (bundleID.length == 0) {
58
+ bundleID = SanitizedShortString(HostApplicationBundleIdentifier(), 128);
59
+ }
60
+ if (tty.length == 0 && program.length == 0 && session.length == 0 && bundleID.length == 0) {
61
+ return @{};
62
+ }
63
+ NSMutableDictionary *target = [NSMutableDictionary dictionary];
64
+ if (tty.length > 0) target[@"tty"] = tty;
65
+ if (program.length > 0) target[@"program"] = program;
66
+ if (session.length > 0) target[@"session"] = session;
67
+ if (bundleID.length > 0) target[@"bundleID"] = bundleID;
68
+ return target;
69
+ }
70
+
71
+ NSString *FrontmostApplicationBundleIdentifier(void) {
72
+ return NSWorkspace.sharedWorkspace.frontmostApplication.bundleIdentifier ?: @"";
73
+ }
74
+
75
+ static BOOL RunTerminalSelectionScript(NSString *bundleID, NSString *ttyName) {
76
+ if (ttyName.length == 0) return NO;
77
+ NSString *tty = [@"/dev/" stringByAppendingString:ttyName.lastPathComponent];
78
+ NSString *source = nil;
79
+ if ([bundleID isEqualToString:@"com.apple.Terminal"]) {
80
+ source = [NSString stringWithFormat:
81
+ @"tell application \"Terminal\"\n"
82
+ "repeat with terminalWindow in windows\n"
83
+ "repeat with terminalTab in tabs of terminalWindow\n"
84
+ "if (tty of terminalTab) is \"%@\" then\n"
85
+ "set selected tab of terminalWindow to terminalTab\n"
86
+ "set index of terminalWindow to 1\n"
87
+ "activate\n"
88
+ "return true\n"
89
+ "end if\n"
90
+ "end repeat\n"
91
+ "end repeat\n"
92
+ "end tell\n"
93
+ "return false", tty];
94
+ } else if ([bundleID isEqualToString:@"com.googlecode.iterm2"]) {
95
+ source = [NSString stringWithFormat:
96
+ @"tell application \"iTerm2\"\n"
97
+ "repeat with terminalWindow in windows\n"
98
+ "repeat with terminalTab in tabs of terminalWindow\n"
99
+ "repeat with terminalSession in sessions of terminalTab\n"
100
+ "if (tty of terminalSession) is \"%@\" then\n"
101
+ "select terminalSession\n"
102
+ "select terminalWindow\n"
103
+ "activate\n"
104
+ "return true\n"
105
+ "end if\n"
106
+ "end repeat\n"
107
+ "end repeat\n"
108
+ "end repeat\n"
109
+ "end tell\n"
110
+ "return false", tty];
111
+ }
112
+ if (!source) return NO;
113
+ NSDictionary *error = nil;
114
+ NSAppleScript *script = [[NSAppleScript alloc] initWithSource:source];
115
+ NSAppleEventDescriptor *result = [script executeAndReturnError:&error];
116
+ return result.booleanValue && error == nil;
117
+ }
118
+
119
+ static NSString *BundleIDForTerminalProgram(NSString *program) {
120
+ NSString *lower = program.lowercaseString;
121
+ if ([lower isEqualToString:@"apple_terminal"]) return @"com.apple.Terminal";
122
+ if ([lower containsString:@"iterm"]) return @"com.googlecode.iterm2";
123
+ if ([lower isEqualToString:@"vscode"]) return @"com.microsoft.VSCode";
124
+ if ([lower containsString:@"warp"]) return @"dev.warp.Warp-Stable";
125
+ if ([lower containsString:@"wezterm"]) return @"com.github.wez.wezterm";
126
+ if ([lower containsString:@"ghostty"]) return @"com.mitchellh.ghostty";
127
+ return @"";
128
+ }
129
+
130
+ BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
131
+ if (![target isKindOfClass:NSDictionary.class]) return NO;
132
+ NSString *tty = SanitizedShortString(target[@"tty"], 64);
133
+ // 已知 TERM_PROGRAM 比“启动瞬间的前台应用”更可靠:VS Code Task 可能在窗口不位于
134
+ // 前台时启动 shell。JetBrains 等没有稳定统一 bundle ID 的宿主才使用捕获值兜底。
135
+ NSString *bundleID = BundleIDForTerminalProgram(
136
+ SanitizedShortString(target[@"program"], 64));
137
+ if (bundleID.length == 0) bundleID = SanitizedShortString(target[@"bundleID"], 128);
138
+ if (bundleID.length == 0) return NO;
139
+ if (RunTerminalSelectionScript(bundleID, tty)) return YES;
140
+
141
+ NSArray<NSRunningApplication *> *applications =
142
+ [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID];
143
+ NSRunningApplication *application = applications.firstObject;
144
+ if (!application) return NO;
145
+ #pragma clang diagnostic push
146
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
147
+ return [application activateWithOptions:
148
+ NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps];
149
+ #pragma clang diagnostic pop
150
+ }
@@ -15,14 +15,60 @@ static const double SevenDayWindowMinutes = 10080;
15
15
  // 把一份本来正常的快照判死。
16
16
  static const NSTimeInterval QuotaResetSkewSeconds = 600.0;
17
17
 
18
+ // 一条限额错误刚发生、手上却一个可用窗口都没有时的保留时长。见 ExhaustionStillHolds。
19
+ static const NSTimeInterval RecentExhaustionGraceSeconds = 300.0;
20
+
18
21
  // 一份快照要么描述当前窗口,要么就没有任何用处:resets_at 落在过去说明这个窗口早就翻篇,
19
22
  // 落在一个窗长之外则根本不可能是它的重置时刻。2026-08-19 实测被顶进来的坏快照正是后者
20
23
  // ——5 小时窗口的 resets_at 报到了十几小时之后。两种都在入口就拒绝,别让它进文件。
21
- static BOOL QuotaWindowLooksCurrent(NSDictionary *quota, double windowMinutes, NSTimeInterval now) {
24
+ static BOOL ResetLooksCurrentAt(double reset, double windowMinutes, NSTimeInterval sampledAt) {
25
+ if (reset <= 0 || windowMinutes <= 0) return NO;
26
+ return reset > sampledAt && reset <= sampledAt + windowMinutes * 60.0 + QuotaResetSkewSeconds;
27
+ }
28
+
29
+ static BOOL QuotaWindowLooksCurrentAt(NSDictionary *quota, double windowMinutes,
30
+ NSTimeInterval sampledAt) {
22
31
  NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
23
- if (!reset || windowMinutes <= 0) return NO;
24
- double value = reset.doubleValue;
25
- return value > now && value <= now + windowMinutes * 60.0 + QuotaResetSkewSeconds;
32
+ if (!reset) return NO;
33
+ return ResetLooksCurrentAt(reset.doubleValue, windowMinutes, sampledAt);
34
+ }
35
+
36
+ static BOOL QuotaWindowLooksCurrent(NSDictionary *quota, double windowMinutes, NSTimeInterval now) {
37
+ return QuotaWindowLooksCurrentAt(quota, windowMinutes, now);
38
+ }
39
+
40
+ // Codex 的 rate_limits 是一份会话快照,不会在窗口自然重置时自行刷新。一个快照里的
41
+ // 5 小时和 7 天窗口因此可能处于不同状态:例如 5 小时的 resets_at 已过去几天,但 7 天
42
+ // 的仍在未来。不能因为后者还活着,就把前者的旧百分比继续当成当前额度展示。
43
+ //
44
+ // 缺 resets_at 的旧版记录暂时保留,兼容历史会话和只提供百分比的上游版本;只要服务端给了
45
+ // 重置时间,就必须用它校验窗口。这个函数放在读取层而不是绘制层,状态栏、历史曲线和气泡
46
+ // 台词才能使用同一份已校正的数据。
47
+ static NSDictionary *UsageByRemovingInactiveQuotaWindows(NSDictionary *usage) {
48
+ if (![usage isKindOfClass:NSDictionary.class]) return usage;
49
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
50
+ NSDictionary<NSString *, NSNumber *> *windows = @{
51
+ @"fiveHour": @(FiveHourWindowMinutes),
52
+ @"week": @(SevenDayWindowMinutes)
53
+ };
54
+ NSMutableDictionary *result = nil;
55
+ NSMutableDictionary *expired = nil;
56
+ for (NSString *key in windows) {
57
+ NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
58
+ NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class]
59
+ ? quota[@"resets_at"] : nil;
60
+ if (!reset || QuotaWindowLooksCurrent(quota, windows[key].doubleValue, now)) continue;
61
+ if (!result) result = [usage mutableCopy];
62
+ result[key] = NSNull.null;
63
+ // 百分比不再展示,但 resets_at 必须留下。窗口一旦被清空,"这个窗口已经重置过"
64
+ // 就再也无从得知——而缺失的窗口本来就用 NSNull 表示(官方没给),两者混在一起
65
+ // 分不开。ExhaustionStillHolds 要靠这份记录让受限标记按时失效,否则只剩一个
66
+ // 未到期的 7 天窗口时,一次限流会让卡片永久挂着"额度受限"。
67
+ if (!expired) expired = [NSMutableDictionary dictionary];
68
+ expired[key] = reset;
69
+ }
70
+ if (expired) result[@"expiredWindowResets"] = expired;
71
+ return result ?: usage;
26
72
  }
27
73
 
28
74
  // 同一个账号下的每个 Claude 会话都会把自己那次响应里的 rate_limits 抄到同一个文件上,
@@ -343,10 +389,68 @@ static NSDictionary *UsageFromCodexLine(NSData *lineData) {
343
389
  };
344
390
  }
345
391
 
346
- // 耗尽事件不早于当前额度快照时,把标记贴到 usage 上,供面板把剩余额度显示成 0。
392
+ // 受限事件没有窗口归属,只能给它一个有效期:快照里最短窗口的 resets_at 一过,那个窗口
393
+ // 必然已经重置,再挂着"额度受限"就是在声称一件我们已经不知道的事——而受限期间官方常年
394
+ // 只回 primary/secondary 全 null(见 UsageFromCodexLine),等"更新的快照"来推翻可能等不到。
395
+ // 真正用尽的是 7 天窗口时,5 小时窗口重置后仍会被拒,届时会写下新的 usage_limit_exceeded,
396
+ // 标记自己会贴回来。
397
+ static BOOL ExhaustionStillHolds(NSDictionary *usage, NSTimeInterval exhaustedAt) {
398
+ if (![usage isKindOfClass:NSDictionary.class] || exhaustedAt <= 0) return NO;
399
+ if (exhaustedAt < [usage[@"sampledAt"] doubleValue]) return NO;
400
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
401
+ NSTimeInterval earliestReset = 0;
402
+ BOOL foundReset = NO;
403
+ BOOL foundQuotaWithoutReset = NO;
404
+ NSDictionary<NSString *, NSNumber *> *windows = @{
405
+ @"fiveHour": @(FiveHourWindowMinutes),
406
+ @"week": @(SevenDayWindowMinutes)
407
+ };
408
+ NSDictionary *expired = [usage[@"expiredWindowResets"] isKindOfClass:NSDictionary.class]
409
+ ? usage[@"expiredWindowResets"] : nil;
410
+ for (NSString *key in windows) {
411
+ NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
412
+ NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
413
+ // 关键是“限额错误发生时”这个 reset 是否还属于当前窗口,而不是它现在是否已过期。
414
+ // 例如错误发生后 5 小时窗口自然重置,标记应当清掉;反过来,数天前就过期的
415
+ // 5 小时快照不能让一条刚发生的错误立即失效。
416
+ if (!quota) {
417
+ // 窗口被 UsageByRemovingInactiveQuotaWindows 清掉了,用它留下的 resets_at 继续
418
+ // 判断。少了这一支,5 小时窗口重置后标记就再也没有失效的依据。
419
+ NSNumber *expiredReset = [expired[key] isKindOfClass:NSNumber.class] ? expired[key] : nil;
420
+ if (!expiredReset) continue;
421
+ foundReset = YES;
422
+ double value = expiredReset.doubleValue;
423
+ if (!ResetLooksCurrentAt(value, windows[key].doubleValue, exhaustedAt)) continue;
424
+ if (earliestReset == 0 || value < earliestReset) earliestReset = value;
425
+ continue;
426
+ }
427
+ if (!reset) {
428
+ foundQuotaWithoutReset = YES;
429
+ continue;
430
+ }
431
+ foundReset = YES;
432
+ if (!QuotaWindowLooksCurrentAt(quota, windows[key].doubleValue, exhaustedAt)) continue;
433
+ double value = reset.doubleValue;
434
+ if (earliestReset == 0 || value < earliestReset) earliestReset = value;
435
+ }
436
+ if (earliestReset > now) return YES;
437
+ // 有一个属于当前窗口的 reset 且它已经过去,说明额度确实重置了,标记必须清掉。
438
+ if (earliestReset > 0) return NO;
439
+ // 走到这里说明一个可用窗口都没有,推不出有效期。这恰恰是最需要受限提示的时刻——
440
+ // 上面注释里说的"受限期间官方常年只回 primary/secondary 全 null"就落在这个分支,
441
+ // app-server 也拿不到实时额度时更是如此。所以刚发生的错误先无条件保留一小段时间,
442
+ // 别让面板在用户正撞限额的当口显示一切正常。
443
+ if (now - exhaustedAt < RecentExhaustionGraceSeconds) return YES;
444
+ // 老版会话只给百分比、没有 resets_at 时无法推断受限状态的有效期;沿用之前的保守
445
+ // 行为,等更新的额度快照来清掉它。只要至少有一个明确的 reset,就以它为准。
446
+ return !foundReset && foundQuotaWithoutReset;
447
+ }
448
+
449
+ // 受限事件仍然成立时,把标记贴到 usage 上。事件本身没有窗口归属,面板只能提示"额度受限"
450
+ // 并把已有百分比标为快照,不能据此把 5 小时和 7 天窗口都判成 0。
347
451
  static NSDictionary *UsageByMarkingExhaustion(NSDictionary *usage, NSTimeInterval exhaustedAt) {
348
- if (![usage isKindOfClass:NSDictionary.class] || exhaustedAt <= 0) return usage;
349
- if (exhaustedAt < [usage[@"sampledAt"] doubleValue]) return usage;
452
+ if (![usage isKindOfClass:NSDictionary.class]) return usage;
453
+ if (!ExhaustionStillHolds(usage, exhaustedAt)) return usage;
350
454
  NSMutableDictionary *result = [usage mutableCopy];
351
455
  result[@"exhaustedAt"] = @(exhaustedAt);
352
456
  return result;
@@ -514,10 +618,13 @@ static NSData *SessionTailData(NSURL *url) {
514
618
 
515
619
  static BOOL UsageHasLiveWindow(NSDictionary *usage) {
516
620
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
517
- for (NSString *key in @[@"fiveHour", @"week"]) {
621
+ NSDictionary<NSString *, NSNumber *> *windows = @{
622
+ @"fiveHour": @(FiveHourWindowMinutes),
623
+ @"week": @(SevenDayWindowMinutes)
624
+ };
625
+ for (NSString *key in windows) {
518
626
  NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
519
- NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
520
- if (reset && reset.doubleValue > now) return YES;
627
+ if (QuotaWindowLooksCurrent(quota, windows[key].doubleValue, now)) return YES;
521
628
  }
522
629
  return NO;
523
630
  }
@@ -1222,6 +1329,7 @@ NSDictionary *LatestUsage(void) {
1222
1329
  NSNumber *exhaustedAt = nil;
1223
1330
  NSDictionary *usage = LatestUsageInData(tail, &exhaustedAt)
1224
1331
  ?: LatestQuotaInRecentSessions(sessions, newest);
1332
+ usage = UsageByRemovingInactiveQuotaWindows(usage);
1225
1333
  // --status 这类一次性调用不带缓存也不写归档:它只需要当下这一份数字。
1226
1334
  usage = UsageByAddingTokenTotals(usage, sessions, newest ? @[newest] : nil,
1227
1335
  [NSMutableDictionary dictionary],
@@ -1285,6 +1393,7 @@ static const NSTimeInterval TokenCacheSaveInterval = 60.0;
1285
1393
  }
1286
1394
  - (NSDictionary *)usageWithTokenTotals:(NSDictionary *)usage {
1287
1395
  if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
1396
+ usage = UsageByRemovingInactiveQuotaWindows(usage);
1288
1397
  NSString *identity = TokenWindowIdentity(usage);
1289
1398
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
1290
1399
  BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
@@ -1293,7 +1402,7 @@ static const NSTimeInterval TokenCacheSaveInterval = 60.0;
1293
1402
  if (reusable) {
1294
1403
  NSMutableDictionary *result = [usage mutableCopy];
1295
1404
  result[@"tokenUsage"] = self.tokenUsage;
1296
- return UsageByMarkingExhaustion(result, self.exhaustedAt);
1405
+ return [self usageByApplyingExhaustion:result];
1297
1406
  }
1298
1407
  BOOL archiveChanged = NO;
1299
1408
  // 正在增量读取的会话永远排在钉住列表最前面:它是最不该被漏掉的那一个,而漏掉它
@@ -1311,12 +1420,24 @@ static const NSTimeInterval TokenCacheSaveInterval = 60.0;
1311
1420
  self.tokenWindowIdentity = identity;
1312
1421
  self.tokenComputedAt = now;
1313
1422
  self.forcesTokenAggregation = NO;
1314
- return UsageByMarkingExhaustion(result, self.exhaustedAt);
1423
+ return [self usageByApplyingExhaustion:result];
1315
1424
  }
1316
- // 耗尽事件只往前走:额度恢复由"更新的额度快照"表达(见 UsageByMarkingExhaustion)。
1425
+ // 耗尽事件只往前走:额度恢复由"更新的额度快照"或窗口重置表达(见 ExhaustionStillHolds)。
1317
1426
  - (void)noteExhaustion:(NSNumber *)timestamp {
1318
1427
  if (timestamp.doubleValue > self.exhaustedAt) self.exhaustedAt = timestamp.doubleValue;
1319
1428
  }
1429
+ // 标记失效时把记下的时刻一并清掉:留着它只会在下一轮再比一次同样的大小,而窗口一旦重置,
1430
+ // 这个时刻就永远不该再让任何快照被判成受限了。
1431
+ - (NSDictionary *)usageByApplyingExhaustion:(NSDictionary *)usage {
1432
+ if (![usage isKindOfClass:NSDictionary.class]) return usage;
1433
+ if (!ExhaustionStillHolds(usage, self.exhaustedAt)) {
1434
+ // 快照只会向前走(NewerUsageSnapshot),所以失效一次就是永久失效;真再撞上限流,
1435
+ // noteExhaustion: 会记下新的时刻。
1436
+ self.exhaustedAt = 0;
1437
+ return usage;
1438
+ }
1439
+ return UsageByMarkingExhaustion(usage, self.exhaustedAt);
1440
+ }
1320
1441
  // 最近被写过的会话,最新的排在前面。并发会话不会太多,留 8 个足够覆盖一批 FSEvents;
1321
1442
  // 更早的那些反正也会被目录扫描按 mtime 捞回来,钉住它们只是白读文件。
1322
1443
  static const NSUInteger MaximumPinnedSessions = 8;
@@ -1495,7 +1616,7 @@ static const NSUInteger MaximumPinnedSessions = 8;
1495
1616
  if (!chosen) chosen = currentSession;
1496
1617
  // 一个候选都没选中就不会再走到 usageWithTokenTotals,刚记下的耗尽标记得在这里贴上。
1497
1618
  if (!chosen) {
1498
- self.usage = UsageByMarkingExhaustion(self.usage, self.exhaustedAt);
1619
+ self.usage = [self usageByApplyingExhaustion:self.usage];
1499
1620
  return self.usage;
1500
1621
  }
1501
1622
  if (![chosen.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:chosen];
@@ -1,5 +1,6 @@
1
1
  #import "CCPetsUsageMonitor.h"
2
2
  #import "CCPetsUsage.h"
3
+ #import "CCPetsCodexRateLimits.h"
3
4
  #import "CCPetsPaths.h"
4
5
  #import <CoreServices/CoreServices.h>
5
6
  #import <fcntl.h>
@@ -14,9 +15,12 @@
14
15
  @interface CCPetsUsageMonitor ()
15
16
  @property dispatch_queue_t queue;
16
17
  @property CodexUsageReader *codexReader;
18
+ @property CCPetsCodexRateLimitsReader *codexRateLimitsReader;
17
19
  @property ClaudeUsageReader *claudeReader;
18
20
  @property(readwrite) NSDictionary *codexUsage;
19
21
  @property(readwrite) NSDictionary *claudeUsage;
22
+ @property NSDictionary *codexLiveUsage;
23
+ @property NSTimeInterval codexLiveUsageUpdatedAt;
20
24
  @property FSEventStreamRef codexStream;
21
25
  @property dispatch_source_t claudeSource;
22
26
  @property unsigned long long claudeSize;
@@ -24,8 +28,13 @@
24
28
  @property BOOL started;
25
29
  - (void)publishChange;
26
30
  - (void)startClaudeSource;
31
+ - (NSDictionary *)usageByApplyingLiveCodexUsage:(NSDictionary *)sessionUsage;
27
32
  @end
28
33
 
34
+ // App Server 是服务端当前额度的权威源;会话日志只在成功响应落盘时才更新。短暂失败时
35
+ // 留出一小段缓存寿命,既不因一次网络抖动闪回旧日志,也不会把实时值永久钉在界面上。
36
+ static const NSTimeInterval CodexLiveUsageTTL = 5 * 60.0;
37
+
29
38
  static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
30
39
  void *clientCallBackInfo, size_t numEvents, void *eventPaths,
31
40
  const FSEventStreamEventFlags eventFlags[],
@@ -54,11 +63,13 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
54
63
  }
55
64
  }
56
65
  if (requiresFullDiscovery) {
57
- monitor.codexUsage = [monitor.codexReader refreshWithFullDiscovery];
66
+ monitor.codexUsage = [monitor usageByApplyingLiveCodexUsage:
67
+ [monitor.codexReader refreshWithFullDiscovery]];
58
68
  } else if (changedSessions.count > 0) {
59
69
  NSMutableArray<NSURL *> *urls = [NSMutableArray arrayWithCapacity:changedSessions.count];
60
70
  for (NSString *path in changedSessions) [urls addObject:[NSURL fileURLWithPath:path]];
61
- monitor.codexUsage = [monitor.codexReader refreshForSessionURLs:urls];
71
+ monitor.codexUsage = [monitor usageByApplyingLiveCodexUsage:
72
+ [monitor.codexReader refreshForSessionURLs:urls]];
62
73
  }
63
74
  if (requiresFullDiscovery || changedSessions.count > 0) [monitor publishChange];
64
75
  }
@@ -70,13 +81,37 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
70
81
  dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,
71
82
  QOS_CLASS_UTILITY, 0));
72
83
  _codexReader = [CodexUsageReader new];
84
+ _codexRateLimitsReader = [CCPetsCodexRateLimitsReader new];
73
85
  _claudeReader = [ClaudeUsageReader new];
74
86
  // 桌宠是唯一的常驻读取者,摘要缓存由它维护并落盘。
75
87
  _codexReader.persistsCache = YES;
76
88
  _claudeReader.persistsCache = YES;
89
+ __weak typeof(self) weakSelf = self;
90
+ _codexRateLimitsReader.liveUsageHandler = ^(NSDictionary *liveUsage) {
91
+ dispatch_async(weakSelf.queue, ^{
92
+ typeof(self) strongSelf = weakSelf;
93
+ if (!strongSelf || !strongSelf.started) return;
94
+ strongSelf.codexLiveUsage = liveUsage;
95
+ strongSelf.codexLiveUsageUpdatedAt = NSDate.date.timeIntervalSince1970;
96
+ strongSelf.codexUsage = [strongSelf usageByApplyingLiveCodexUsage:
97
+ strongSelf.codexReader.usage ?: strongSelf.codexUsage];
98
+ [strongSelf publishChange];
99
+ });
100
+ };
77
101
  }
78
102
  return self;
79
103
  }
104
+
105
+ - (NSDictionary *)usageByApplyingLiveCodexUsage:(NSDictionary *)sessionUsage {
106
+ if (self.codexLiveUsage && NSDate.date.timeIntervalSince1970 -
107
+ self.codexLiveUsageUpdatedAt > CodexLiveUsageTTL) {
108
+ self.codexLiveUsage = nil;
109
+ self.codexLiveUsageUpdatedAt = 0;
110
+ }
111
+ return self.codexLiveUsage
112
+ ? CodexUsageByApplyingLiveUsage(sessionUsage, self.codexLiveUsage)
113
+ : sessionUsage;
114
+ }
80
115
  // 回调交给主线程:下游全是 UI(面板重排、气泡定位、系统通知)。
81
116
  - (void)publishChange {
82
117
  void (^handler)(NSDictionary *, NSDictionary *) = self.changeHandler;
@@ -171,7 +206,9 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
171
206
  - (void)refreshOnQueue {
172
207
  if (!self.started) return;
173
208
  // 手动刷新、面板打开和 120 秒兜底都走全量路径,Token 聚合的节流只约束 FSEvents 热路径。
174
- self.codexUsage = [self.codexReader refreshWithFullDiscovery];
209
+ self.codexUsage = [self usageByApplyingLiveCodexUsage:
210
+ [self.codexReader refreshWithFullDiscovery]];
211
+ [self.codexRateLimitsReader refresh];
175
212
  self.claudeUsage = [self readClaudeUsageChanged:NO forcingAggregation:YES];
176
213
  if (!self.codexStream) [self startCodexStream];
177
214
  if (!self.claudeSource) [self startClaudeSource];
@@ -186,6 +223,7 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
186
223
  dispatch_sync(self.queue, ^{ [unsafeSelf teardownSources]; });
187
224
  }
188
225
  - (void)teardownSources {
226
+ [self.codexRateLimitsReader stop];
189
227
  if (self.codexStream) {
190
228
  FSEventStreamStop(self.codexStream);
191
229
  FSEventStreamInvalidate(self.codexStream);
@@ -376,12 +376,17 @@ typedef NS_ENUM(NSInteger, PetMicroBehaviorKind) {
376
376
  CGFloat dy = (point.y - centerY) / (NSHeight(self.bounds) * 0.16);
377
377
  return dx * dx + dy * dy <= 1.0;
378
378
  }
379
- - (void)updateHoverForPoint:(NSPoint)point {
380
- [self noteActivity];
379
+ - (BOOL)updatePocketHoverForPoint:(NSPoint)point {
381
380
  BOOL overPocket = [self isPocketPoint:point];
382
381
  if (self.pocketHoverChanged) self.pocketHoverChanged(overPocket);
382
+ if (overPocket) [NSCursor.pointingHandCursor set];
383
+ else [NSCursor.arrowCursor set];
384
+ return overPocket;
385
+ }
386
+ - (void)updateHoverForPoint:(NSPoint)point {
387
+ [self noteActivity];
388
+ BOOL overPocket = [self updatePocketHoverForPoint:point];
383
389
  if (overPocket) {
384
- [NSCursor.pointingHandCursor set];
385
390
  [self playRow:5 throughFrame:7 oneShot:NO];
386
391
  } else if (point.y >= NSHeight(self.bounds) * 0.58) {
387
392
  [NSCursor.pointingHandCursor set];
@@ -400,14 +405,16 @@ typedef NS_ENUM(NSInteger, PetMicroBehaviorKind) {
400
405
  [self playRow:0 throughFrame:5 oneShot:NO];
401
406
  }
402
407
  }
408
+ - (void)mouseEntered:(NSEvent *)event {
409
+ [self mouseMoved:event];
410
+ }
403
411
  - (void)mouseMoved:(NSEvent *)event {
404
- if (self.draggingPet || self.oneShot) return;
412
+ if (self.draggingPet) return;
405
413
  NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
406
- if (self.agentActive) {
407
- BOOL overPocket = [self isPocketPoint:point];
408
- if (self.pocketHoverChanged) self.pocketHoverChanged(overPocket);
409
- if (overPocket) [NSCursor.pointingHandCursor set];
410
- else [NSCursor.arrowCursor set];
414
+ // 一次性动作只锁定动画,不应锁住面板热区。否则鼠标在动作期间进入后停住,
415
+ // oneShot 结束时不会再收到 mouseMoved,额度面板就一直没有机会展示。
416
+ if (self.oneShot || self.agentActive) {
417
+ [self updatePocketHoverForPoint:point];
411
418
  return;
412
419
  }
413
420
  [self updateHoverForPoint:point];
@@ -416,7 +423,7 @@ typedef NS_ENUM(NSInteger, PetMicroBehaviorKind) {
416
423
  if (self.draggingPet) return;
417
424
  if (self.pocketHoverChanged) self.pocketHoverChanged(NO);
418
425
  [NSCursor.arrowCursor set];
419
- if (self.agentActive) return;
426
+ if (self.agentActive || self.oneShot) return;
420
427
  [self playRow:0 throughFrame:5 oneShot:NO];
421
428
  }
422
429
  - (void)nextFrame:(NSTimer *)timer {
@@ -1498,7 +1505,8 @@ typedef NS_ENUM(NSInteger, PetMicroBehaviorKind) {
1498
1505
  NSArray<NSDictionary *> *notificationOptions = @[
1499
1506
  @{@"title": @"任务完成", @"key": NotificationCompletionKey, @"tag": @1},
1500
1507
  @{@"title": @"任务失败", @"key": NotificationFailureKey, @"tag": @2},
1501
- @{@"title": @"等待审批", @"key": NotificationApprovalKey, @"tag": @3}
1508
+ @{@"title": @"等待审批", @"key": NotificationApprovalKey, @"tag": @3},
1509
+ @{@"title": @"响应超时", @"key": NotificationStallKey, @"tag": @4}
1502
1510
  ];
1503
1511
  for (NSDictionary *option in notificationOptions) {
1504
1512
  [self addPersistentSwitchToMenu:notificationMenu
@@ -551,8 +551,9 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
551
551
  ? self.codexShowsAPIUsage : self.claudeShowsAPIUsage;
552
552
  NSNumber *fiveUsed = [self usedForQuota:five usedKey:usedKey];
553
553
  NSNumber *weekUsed = [self usedForQuota:week usedKey:usedKey];
554
- // 额度被拒之后官方不再报告任何窗口,留在手里的百分比既过期、指向的结论又正好相反
555
- // (账号是共享的,别人用完时本机的数字纹丝不动)。这时按 0 显示,并把状态说清楚。
554
+ // usage_limit_exceeded 只能说明某次请求被额度限制,不能说明耗尽的是 5 小时还是
555
+ // 7 天窗口;切到 credits 后请求还能继续成功,但 rate_limits 可能一直为空。因此把它
556
+ // 作为独立的“额度受限”状态,不再拿一个无窗口归属的事件覆盖两个官方百分比。
556
557
  BOOL exhausted = [usage[@"exhaustedAt"] isKindOfClass:NSNumber.class];
557
558
  BOOL hasData = apiMode ? (monthTokens != nil)
558
559
  : (fiveUsed || weekUsed || fiveTokens || weekTokens || exhausted);
@@ -590,9 +591,9 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
590
591
  }
591
592
  [name drawInRect:NSMakeRect(NSMinX(card) + 94, NSMinY(card) + 84, 88, 30)
592
593
  withAttributes:[self textAttributesWithSize:22 color:primary weight:NSFontWeightBold]];
593
- // 四态:额度被拒 → 额度已用尽(压过在线,这是此刻唯一要紧的信息);没有任何额度
594
- // 数据 → 等待数据;有数据但客户端已退出 → 离线;两者都有 → 在线。
595
- NSString *statusText = (!apiMode && exhausted) ? @"额度已用尽"
594
+ // 四态:额度被拒 → 额度受限(百分比仍是上次官方快照);没有任何额度数据 → 等待数据;
595
+ // 有数据但客户端已退出 → 离线;两者都有 → 在线。
596
+ NSString *statusText = (!apiMode && exhausted) ? @"额度受限"
596
597
  : (!hasData ? @"等待数据" : (online ? @"● 在线" : @"离线"));
597
598
  NSColor *statusColor = (!apiMode && exhausted) ? NSColor.systemOrangeColor
598
599
  : (online && hasData ? NSColor.systemGreenColor : secondary);
@@ -708,19 +709,18 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
708
709
  NSArray<NSDictionary *> *windows = @[
709
710
  @{@"x": @(NSMinX(card) + 214), @"title": @"官方 5 小时窗口", @"quota": five ?: @{},
710
711
  @"tokens": fiveTokens ?: @{}, @"used": fiveUsed ?: NSNull.null,
711
- @"rolling": @"无限制"},
712
+ @"rolling": @"官方额度待刷新"},
712
713
  @{@"x": @(NSMinX(card) + 394), @"title": @"官方 7 天窗口", @"quota": week ?: @{},
713
714
  @"tokens": weekTokens ?: @{}, @"used": weekUsed ?: NSNull.null,
714
- @"rolling": @"无限制"}
715
+ @"rolling": @"官方额度待刷新"}
715
716
  ];
716
717
  for (NSDictionary *window in windows) {
717
718
  CGFloat x = [window[@"x"] doubleValue];
718
719
  [window[@"title"] drawInRect:NSMakeRect(x, NSMinY(card) + 114, 130, 20)
719
720
  withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
720
721
  NSNumber *used = [window[@"used"] isKindOfClass:NSNumber.class] ? window[@"used"] : nil;
721
- double remaining = exhausted ? 0 : (used ? 100.0 - used.doubleValue : 0);
722
- NSString *official = (used || exhausted)
723
- ? [NSString stringWithFormat:@"%.0f%%", remaining] : @"--";
722
+ double remaining = used ? 100.0 - used.doubleValue : 0;
723
+ NSString *official = used ? [NSString stringWithFormat:@"%.0f%%", remaining] : @"--";
724
724
  // 百分比是"剩余"、Token 是"已用",方向相反。后缀直接贴在数字右侧、
725
725
  // 前缀写进 Token 行,否则两个数字并排看会被当成同一口径。
726
726
  NSDictionary *valueAttributes = [self textAttributesWithSize:25
@@ -729,8 +729,14 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
729
729
  CGFloat valueWidth = ceil([official sizeWithAttributes:valueAttributes].width);
730
730
  [official drawInRect:NSMakeRect(x, NSMinY(card) + 74, valueWidth + 4, 34)
731
731
  withAttributes:valueAttributes];
732
- [@"剩余" drawInRect:NSMakeRect(x + valueWidth + 7, NSMinY(card) + 78, 60, 20)
733
- withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
732
+ // 没有数字可标时不给口径标签:"-- 剩余"看起来像一个真实的 0 值,而实际上是
733
+ // 官方快照待刷新。下方的状态文字会说明它为何不可用。
734
+ NSString *valueLabel = !used ? @"" : (exhausted ? @"快照" : @"剩余");
735
+ if (valueLabel.length > 0) {
736
+ [valueLabel drawInRect:NSMakeRect(x + valueWidth + 7, NSMinY(card) + 78, 60, 20)
737
+ withAttributes:[self textAttributesWithSize:12 color:secondary
738
+ weight:NSFontWeightRegular]];
739
+ }
734
740
  // 官方窗口拿不到时(账号没有这个窗口、或响应里没带),Token 走的是本机滚动窗口。
735
741
  // 说清楚这一行的口径,比留一个 `--` 让人以为是渲染坏了要好。
736
742
  NSString *resetValue = [self resetText:window[@"quota"]];
@@ -750,10 +756,26 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
750
756
  withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
751
757
  NSArray<NSDictionary *> *history = [name isEqualToString:@"Codex"]
752
758
  ? self.codexHistory : self.claudeHistory;
753
- NSNumber *currentUsed = exhausted ? @100 : weekUsed;
759
+ NSNumber *currentUsed = weekUsed;
754
760
  NSArray<NSDictionary *> *points = [self curvePointsFromHistory:history currentUsed:currentUsed];
755
- NSDictionary *pace = [self paceStatusForQuota:week currentUsed:currentUsed color:color];
761
+ // 趋势这一列算的是 7 天窗口(currentUsed 取 weekUsed)。而 exhaustedAt 来自
762
+ // rateLimitReachedType,没有窗口归属,实际撞墙的通常是 5 小时窗口——拿它一票否决
763
+ // 整列,会出现左边 7 天窗口好好显示着 45% 剩余、右边却说"等待官方额度刷新"的自相
764
+ // 矛盾。所以只有 7 天窗口自己确实没有百分比时才退回"待刷新"。
765
+ BOOL weekUnknown = exhausted && currentUsed == nil;
766
+ NSDictionary *pace = weekUnknown
767
+ ? @{ @"label": @"待刷新", @"tip": @"等待官方额度刷新",
768
+ @"color": NSColor.systemOrangeColor }
769
+ : [self paceStatusForQuota:week currentUsed:currentUsed color:color];
756
770
  NSColor *paceColor = pace[@"color"];
771
+ // 档位讲的是 7 天趋势,脚注讲的是此刻为什么发不出请求:受限但 7 天窗口尚有余量时
772
+ // 两者都要说清,所以脚注单独取色,不跟着档位走。
773
+ NSString *paceTip = pace[@"tip"];
774
+ NSColor *tipColor = paceColor;
775
+ if (exhausted && !weekUnknown) {
776
+ paceTip = @"官方额度受限,等待重置";
777
+ tipColor = NSColor.systemOrangeColor;
778
+ }
757
779
  NSDictionary *pillAttributes = [self textAttributesWithSize:11 color:paceColor
758
780
  weight:NSFontWeightSemibold];
759
781
  // 档位标签跟在标题后面。宽度仍按文字算:四个档位不一样长,最宽的"数据不足"到
@@ -777,8 +799,8 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
777
799
  withAttributes:[self rightAlignedTextAttributesWithSize:10 color:secondary
778
800
  weight:NSFontWeightRegular]];
779
801
  // 与左边两列的"已用 Token"同一条基线(+22),也和 API 卡的脚注行对齐。
780
- [pace[@"tip"] drawInRect:NSMakeRect(trendX, NSMinY(card) + 22, 145, 18)
781
- withAttributes:[self textAttributesWithSize:11 color:paceColor weight:NSFontWeightMedium]];
802
+ [paceTip drawInRect:NSMakeRect(trendX, NSMinY(card) + 22, 145, 18)
803
+ withAttributes:[self textAttributesWithSize:11 color:tipColor weight:NSFontWeightMedium]];
782
804
  }
783
805
  - (void)drawRect:(NSRect)dirtyRect {
784
806
  [NSGraphicsContext saveGraphicsState];