cc-pets 2.3.0 → 2.5.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.
Files changed (101) hide show
  1. package/CC_BRIDGE.md +63 -7
  2. package/CC_BRIDGE.zh-CN.md +43 -5
  3. package/CHANGELOG.md +106 -0
  4. package/CHANGELOG.zh-CN.md +106 -0
  5. package/CONTRIBUTING.md +23 -1
  6. package/CONTRIBUTING.zh-CN.md +18 -1
  7. package/PROVIDER_PROTOCOL.md +5 -1
  8. package/PROVIDER_PROTOCOL.zh-CN.md +4 -1
  9. package/README.md +177 -33
  10. package/README.zh-CN.md +137 -32
  11. package/Resources/AgentIcons/claude.png +0 -0
  12. package/Resources/AgentIcons/codex.icns +0 -0
  13. package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
  14. package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
  15. package/Resources/zh-Hans.lproj/Localizable.strings +187 -35
  16. package/Sources/CCPets/App/CCPetsAppDelegate+AgentEvents.m +47 -4
  17. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +121 -20
  18. package/Sources/CCPets/App/CCPetsAppDelegate+Bridge.m +8 -6
  19. package/Sources/CCPets/App/CCPetsAppDelegate+MenuBar.m +86 -0
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +14 -1
  21. package/Sources/CCPets/App/CCPetsAppDelegate+Quota.m +6 -1
  22. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +3 -6
  23. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +118 -50
  24. package/Sources/CCPets/App/CCPetsAppDelegate+Update.m +4 -1
  25. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +4 -0
  26. package/Sources/CCPets/App/CCPetsAppDelegate.h +12 -2
  27. package/Sources/CCPets/App/CCPetsAppDelegate.m +4 -2
  28. package/Sources/CCPets/App/main.m +6 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridge.m +45 -18
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +175 -68
  31. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +14 -6
  32. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +356 -110
  33. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +0 -2
  34. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +247 -126
  35. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +37 -9
  36. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +385 -80
  37. package/Sources/CCPets/Integrations/CCPetsEvents.h +5 -0
  38. package/Sources/CCPets/Integrations/CCPetsEvents.m +68 -12
  39. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
  40. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
  41. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +1 -1
  42. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
  43. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
  44. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +8 -1
  45. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +156 -25
  46. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
  47. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
  48. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
  49. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
  50. package/Sources/CCPets/Pet/CCPetsPhrasesEditor.m +7 -0
  51. package/Sources/CCPets/Pet/PetView+Menu.m +11 -3
  52. package/Sources/CCPets/Pet/PetView.h +7 -0
  53. package/Sources/CCPets/Pet/PetView.m +12 -1
  54. package/Sources/CCPets/Support/CCPetsDoctor.m +26 -12
  55. package/Sources/CCPets/Support/CCPetsPreferences.h +12 -0
  56. package/Sources/CCPets/Support/CCPetsPreferences.m +52 -2
  57. package/Sources/CCPets/UI/CCPetsFormBuilder.h +2 -0
  58. package/Sources/CCPets/UI/CCPetsFormBuilder.m +18 -7
  59. package/Sources/CCPets/UI/CCPetsGlassView.h +26 -4
  60. package/Sources/CCPets/UI/CCPetsGlassView.m +40 -9
  61. package/Sources/CCPets/UI/CCPetsMenuBarIcon.h +16 -0
  62. package/Sources/CCPets/UI/CCPetsMenuBarIcon.m +70 -0
  63. package/Sources/CCPets/UI/CCPetsMenuBarPanel.h +18 -0
  64. package/Sources/CCPets/UI/CCPetsMenuBarPanel.m +528 -0
  65. package/Sources/CCPets/UI/CCPetsMenuBarSummary.h +51 -0
  66. package/Sources/CCPets/UI/CCPetsMenuBarSummary.m +95 -0
  67. package/Sources/CCPets/UI/CCPetsSettingsPage.h +6 -1
  68. package/Sources/CCPets/UI/CCPetsSettingsPage.m +577 -66
  69. package/Sources/CCPets/UI/CCPetsStatusItem.h +28 -0
  70. package/Sources/CCPets/UI/CCPetsStatusItem.m +147 -0
  71. package/Sources/CCPets/UI/CCPetsUIStyle.h +5 -2
  72. package/Sources/CCPets/UI/CCPetsUIStyle.m +57 -8
  73. package/Sources/CCPets/UI/CCPetsUsageChartView.m +4 -0
  74. package/Sources/CCPets/UI/CCPetsUsagePage.m +23 -28
  75. package/Sources/CCPets/UI/CCPetsUsageStore.m +2 -2
  76. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +5 -3
  77. package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
  78. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +1 -0
  79. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +49 -11
  80. package/Sources/CCPets/Usage/CCPetsUsage.h +3 -2
  81. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +15 -17
  82. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +11 -29
  83. package/Sources/CCPets/Usage/QuotaDashboardView.m +128 -2
  84. package/THIRD_PARTY_NOTICES.md +7 -3
  85. package/THIRD_PARTY_NOTICES.zh-CN.md +5 -1
  86. package/bin/claude-with-pet +2 -0
  87. package/bin/codex-with-pet +2 -0
  88. package/package.json +5 -1
  89. package/plugins/jetbrains/README.md +62 -0
  90. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
  91. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
  92. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
  93. package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
  94. package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
  95. package/plugins/vscode/README.md +63 -0
  96. package/plugins/vscode/extension.js +210 -0
  97. package/plugins/vscode/package.json +18 -0
  98. package/scripts/build-idea-plugin.sh +101 -0
  99. package/scripts/build-vscode-extension.sh +112 -0
  100. package/scripts/build.sh +24 -2
  101. package/scripts/compile-cached.zsh +133 -0
@@ -0,0 +1,193 @@
1
+ #import "CCPetsUsage+Internal.h"
2
+ #import "CCPetsPaths.h"
3
+ #import <sqlite3.h>
4
+
5
+ // 只补没有持久化会话的线程。不能把运行日志和 rollout 相加:同一次响应会同时出现
6
+ // 在两处,而且后台日志只给累计总量,没有可靠的输入、输出拆分。
7
+ static NSString *BackgroundMatch(NSString *text, NSString *pattern) {
8
+ static NSMutableDictionary<NSString *, NSRegularExpression *> *patterns;
9
+ static dispatch_once_t once;
10
+ dispatch_once(&once, ^{ patterns = [NSMutableDictionary dictionary]; });
11
+ NSRegularExpression *regex;
12
+ @synchronized (patterns) {
13
+ regex = patterns[pattern];
14
+ if (!regex) {
15
+ regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
16
+ if (regex) patterns[pattern] = regex;
17
+ }
18
+ }
19
+ NSTextCheckingResult *match = [regex firstMatchInString:text options:0
20
+ range:NSMakeRange(0, text.length)];
21
+ return match ? [text substringWithRange:[match rangeAtIndex:1]] : nil;
22
+ }
23
+
24
+ static NSString *BackgroundColumn(sqlite3_stmt *statement, int column) {
25
+ const unsigned char *text = sqlite3_column_text(statement, column);
26
+ return text ? [NSString stringWithUTF8String:(const char *)text] : nil;
27
+ }
28
+
29
+ static sqlite3 *BackgroundOpen(NSString *path) {
30
+ sqlite3 *db = NULL;
31
+ // 不创建数据库、不设置 journal_mode,也不执行任何写 SQL。
32
+ if (sqlite3_open_v2(path.fileSystemRepresentation, &db,
33
+ SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {
34
+ if (db) sqlite3_close(db);
35
+ return NULL;
36
+ }
37
+ sqlite3_busy_timeout(db, 100);
38
+ return db;
39
+ }
40
+
41
+ static void BackgroundCoveredThreads(NSString *home, NSMutableDictionary *covered, double now) {
42
+ // state 索引能在 rollout 尚未写完时排除主会话;归档/旧版本还要从文件名补齐。
43
+ sqlite3 *db = BackgroundOpen([home stringByAppendingPathComponent:@"state_5.sqlite"]);
44
+ sqlite3_stmt *statement = NULL;
45
+ if (db && sqlite3_prepare_v2(db, "SELECT id FROM threads", -1, &statement, NULL) == SQLITE_OK) {
46
+ while (sqlite3_step(statement) == SQLITE_ROW) {
47
+ NSString *thread = BackgroundColumn(statement, 0);
48
+ if (thread.length) covered[thread] = @(now);
49
+ }
50
+ }
51
+ sqlite3_finalize(statement);
52
+ if (db) sqlite3_close(db);
53
+ for (NSString *directory in @[@"sessions", @"archived_sessions"]) {
54
+ NSDirectoryEnumerator *files = [NSFileManager.defaultManager enumeratorAtURL:
55
+ [NSURL fileURLWithPath:[home stringByAppendingPathComponent:directory]]
56
+ includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:nil];
57
+ for (NSURL *file in files) {
58
+ if (![file.pathExtension isEqualToString:@"jsonl"]) continue;
59
+ NSString *thread = BackgroundMatch(file.lastPathComponent,
60
+ @"([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\\.jsonl$");
61
+ if (thread) covered[thread.lowercaseString] = @(now);
62
+ }
63
+ }
64
+ }
65
+
66
+ NSDictionary *CodexBackgroundModelDays(NSString *home, NSTimeInterval start, NSTimeInterval end) {
67
+ NSString *path = TokenSummaryCachePath(@"codex-background", home);
68
+ NSMutableDictionary *cache = LoadTokenSummaryCache(path);
69
+ NSMutableDictionary *events = [cache[@"events"] mutableCopy] ?: [NSMutableDictionary dictionary];
70
+ NSMutableDictionary *covered = [cache[@"covered"] mutableCopy] ?: [NSMutableDictionary dictionary];
71
+ NSDictionary *cursor = cache[@"cursor"] ?: @{};
72
+ double now = NSDate.date.timeIntervalSince1970;
73
+ // 与用量页 90 天窗口一致,留 10 天余量;先采集所有仍保留的记录,再做日桶切片。
74
+ double retentionStart = now - 100 * 86400.0;
75
+ BackgroundCoveredThreads(home, covered, now);
76
+ NSString *dbPath = [home stringByAppendingPathComponent:@"logs_2.sqlite"];
77
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:dbPath error:nil];
78
+ NSString *identity = [NSString stringWithFormat:@"%@/%@", attributes[NSFileSystemNumber],
79
+ attributes[NSFileSystemFileNumber]];
80
+ sqlite3 *db = BackgroundOpen(dbPath);
81
+ if (db) {
82
+ sqlite3_stmt *statement = NULL;
83
+ sqlite3_int64 maximum = 0;
84
+ BOOL hasMaximum = NO;
85
+ if (sqlite3_prepare_v2(db, "SELECT MAX(id) FROM logs", -1, &statement, NULL) == SQLITE_OK &&
86
+ sqlite3_step(statement) == SQLITE_ROW) {
87
+ maximum = sqlite3_column_int64(statement, 0);
88
+ hasMaximum = YES;
89
+ }
90
+ sqlite3_finalize(statement);
91
+ statement = NULL;
92
+ sqlite3_int64 lastID = [cursor[@"id"] longLongValue];
93
+ if (![cursor[@"identity"] isEqual:identity] || maximum < lastID) lastID = 0;
94
+ // MAX(id) 给这一批固定上界。按主键推进,不为每次刷新扫描全部运行日志。
95
+ // 首次扫描虽有时间过滤,但不假设 ts 有索引。
96
+ const char *sql = "SELECT id, ts, ts_nanos, feedback_log_body, thread_id FROM logs "
97
+ "WHERE id > ? AND id <= ? AND ts >= ? "
98
+ "AND feedback_log_body LIKE '%post sampling token usage%' ORDER BY id";
99
+ if (hasMaximum && sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK) {
100
+ sqlite3_bind_int64(statement, 1, lastID);
101
+ sqlite3_bind_int64(statement, 2, maximum);
102
+ sqlite3_bind_double(statement, 3, retentionStart);
103
+ int status;
104
+ while ((status = sqlite3_step(statement)) == SQLITE_ROW) {
105
+ @autoreleasepool {
106
+ NSString *body = BackgroundColumn(statement, 3) ?: @"";
107
+ NSString *thread = BackgroundMatch(body, @"thread_id=\"?([0-9a-fA-F-]{36})")
108
+ ?: BackgroundColumn(statement, 4);
109
+ NSString *turn = BackgroundMatch(body, @"turn_id=\"?([0-9a-fA-F-]{36})");
110
+ NSString *total = BackgroundMatch(body, @"total_usage_tokens=([0-9]+)");
111
+ NSString *model = BackgroundMatch(body, @"\\bmodel=\"?([^\\s\"}]+)");
112
+ if (!thread.length || !turn.length || !total.length) continue;
113
+ thread = thread.lowercaseString;
114
+ if (covered[thread]) continue;
115
+ // 同一轮可多次采样,甚至重置后回到相同累计值,不能只用 turn/total 去重。
116
+ // 时间戳标识一次采样;重复累计快照稍后求差为 0,不增加请求数。
117
+ NSString *key = [NSString stringWithFormat:@"%@/%@/%lld/%lld/%@", thread, turn,
118
+ sqlite3_column_int64(statement, 1), sqlite3_column_int64(statement, 2), total];
119
+ if (events[key]) continue;
120
+ events[key] = @{@"thread": thread, @"turn": turn,
121
+ @"model": model ?: @"unknown", @"total": @([total longLongValue]),
122
+ @"timestamp": @(sqlite3_column_double(statement, 1) +
123
+ sqlite3_column_double(statement, 2) / 1e9),
124
+ @"id": @(sqlite3_column_int64(statement, 0))};
125
+ }
126
+ }
127
+ // 锁冲突/读取失败时不推进游标;已经读到的事件有稳定标识,重读不会重复计算。
128
+ if (status == SQLITE_DONE) cache[@"cursor"] = @{@"id": @(maximum), @"identity": identity};
129
+ }
130
+ sqlite3_finalize(statement);
131
+ sqlite3_close(db);
132
+ }
133
+ for (NSString *key in covered.allKeys) {
134
+ if ([covered[key] doubleValue] < retentionStart) [covered removeObjectForKey:key];
135
+ }
136
+ // 长期运行的临时线程跨越保留边界时,保留边界前最后一个快照作基线,
137
+ // 否则删掉旧快照会把新窗口首条累计值误当成全部新增量。
138
+ NSMutableSet *recentThreads = [NSMutableSet set];
139
+ NSMutableDictionary *baselineKeys = [NSMutableDictionary dictionary];
140
+ for (NSString *key in events.allKeys) {
141
+ NSDictionary *event = events[key];
142
+ NSString *thread = event[@"thread"];
143
+ if (covered[thread]) { [events removeObjectForKey:key]; continue; }
144
+ if ([event[@"timestamp"] doubleValue] >= retentionStart) [recentThreads addObject:thread];
145
+ else {
146
+ NSString *oldKey = baselineKeys[thread];
147
+ if (!oldKey || [event[@"timestamp"] doubleValue] > [events[oldKey][@"timestamp"] doubleValue]) {
148
+ baselineKeys[thread] = key;
149
+ }
150
+ }
151
+ }
152
+ for (NSString *key in events.allKeys) {
153
+ NSDictionary *event = events[key];
154
+ NSString *thread = event[@"thread"];
155
+ if ([event[@"timestamp"] doubleValue] < retentionStart &&
156
+ !([recentThreads containsObject:thread] && [baselineKeys[thread] isEqual:key])) {
157
+ [events removeObjectForKey:key];
158
+ }
159
+ }
160
+ cache[@"events"] = events;
161
+ cache[@"covered"] = covered;
162
+ SaveTokenSummaryCache(cache, path);
163
+
164
+ NSArray *ordered = [events.allValues sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
165
+ NSComparisonResult order = [a[@"timestamp"] compare:b[@"timestamp"]];
166
+ return order == NSOrderedSame ? [a[@"id"] compare:b[@"id"]] : order;
167
+ }];
168
+ NSMutableDictionary *previous = [NSMutableDictionary dictionary];
169
+ NSMutableDictionary *days = [NSMutableDictionary dictionary];
170
+ NSCalendar *calendar = NSCalendar.currentCalendar;
171
+ for (NSDictionary *event in ordered) {
172
+ NSString *thread = event[@"thread"];
173
+ if (covered[thread]) continue;
174
+ unsigned long long total = [event[@"total"] unsignedLongLongValue];
175
+ unsigned long long baseline = [previous[thread] unsignedLongLongValue];
176
+ previous[thread] = @(total);
177
+ unsigned long long delta = total >= baseline ? total - baseline : total;
178
+ double timestamp = [event[@"timestamp"] doubleValue];
179
+ // 留 10 秒等主会话文件/索引落盘,下一轮刷新再展示,不提前把它冒充后台用量。
180
+ if (!delta || timestamp < start || timestamp >= end || timestamp > now - 10) continue;
181
+ NSDateComponents *date = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
182
+ fromDate:[NSDate dateWithTimeIntervalSince1970:timestamp]];
183
+ NSString *day = [NSString stringWithFormat:@"%04ld-%02ld-%02ld", (long)date.year, (long)date.month, (long)date.day];
184
+ NSMutableDictionary *models = days[day];
185
+ if (!models) { models = [NSMutableDictionary dictionary]; days[day] = models; }
186
+ NSString *model = event[@"model"];
187
+ NSMutableDictionary *counts = models[model];
188
+ if (!counts) { counts = [NSMutableDictionary dictionary]; models[model] = counts; }
189
+ counts[@"background"] = @([counts[@"background"] unsignedLongLongValue] + delta);
190
+ counts[@"requests"] = @([counts[@"requests"] unsignedLongLongValue] + 1);
191
+ }
192
+ return days;
193
+ }
@@ -58,6 +58,7 @@ NSDictionary *LatestQuotaInRecentSessions(NSURL *sessionsURL, NSURL *skipURL);
58
58
 
59
59
  // Token 窗口聚合、摘要缓存与月度归档(CCPetsUsage+TokenTotals.m)
60
60
  BOOL IsPseudoModelName(NSString *model);
61
+ NSDictionary *CodexBackgroundModelDays(NSString *home, NSTimeInterval start, NSTimeInterval end);
61
62
  NSDictionary *TokenSessionSummaryTracking(NSURL *url, NSMutableDictionary *cache,
62
63
  BOOL trackModels);
63
64
  BOOL TokenWindowOrFallback(NSDictionary *quota, double fallbackMinutes,
@@ -3,15 +3,16 @@
3
3
 
4
4
  #pragma mark - 按模型的用量
5
5
 
6
- // 面向 UI 的统一口径:四栏互不重叠,加起来就是总 Token。
6
+ // 面向 UI 的统一口径:四个明细栏互不重叠,另加缺少明细的后台用量得到总 Token。
7
7
  // input 非缓存输入
8
8
  // cacheRead 缓存命中读
9
9
  // cacheWrite 缓存写入
10
10
  // output 输出
11
11
  // reasoning 输出里的推理 token(Codex 才有,是 output 的子集,不另外加)
12
12
  // requests 请求数
13
- // 两家原始口径不同:Claude 的 input_tokens 不含缓存;Codex 的 cached_input_tokens 是
14
- // input_tokens 的子集(input + output = total),所以 Codex 要先减掉缓存命中的部分。
13
+ // background 后台请求的总 Token(无输入/输出明细,不参与命中率)
14
+ // 两家原始口径不同:Claude 的 input_tokens 不含缓存;Codex 的缓存读取和写入都是
15
+ // input_tokens 的子集(input + output = total),拆成四栏时必须把两者都从输入中扣除。
15
16
  static NSDictionary *ModelCountsMake(unsigned long long input, unsigned long long cacheRead,
16
17
  unsigned long long cacheWrite, unsigned long long output, unsigned long long reasoning,
17
18
  unsigned long long requests) {
@@ -20,7 +21,7 @@ static NSDictionary *ModelCountsMake(unsigned long long input, unsigned long lon
20
21
  }
21
22
 
22
23
  static NSArray<NSString *> *ModelCountKeys(void) {
23
- return @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests"];
24
+ return @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests", @"background"];
24
25
  }
25
26
 
26
27
  static void AddModelCounts(NSMutableDictionary *target, NSDictionary *counts) {
@@ -31,14 +32,16 @@ static void AddModelCounts(NSMutableDictionary *target, NSDictionary *counts) {
31
32
 
32
33
  unsigned long long CCPetsTotalTokens(NSDictionary *counts) {
33
34
  return [counts[@"input"] unsignedLongLongValue] + [counts[@"cacheRead"] unsignedLongLongValue] +
34
- [counts[@"cacheWrite"] unsignedLongLongValue] + [counts[@"output"] unsignedLongLongValue];
35
+ [counts[@"cacheWrite"] unsignedLongLongValue] + [counts[@"output"] unsignedLongLongValue] +
36
+ [counts[@"background"] unsignedLongLongValue];
35
37
  }
36
38
 
37
39
  static NSDictionary *ModelCountsFromCodexBucket(NSDictionary *bucket) {
38
40
  unsigned long long input = [bucket[@"input_tokens"] unsignedLongLongValue];
39
41
  unsigned long long cached = [bucket[@"cached_input_tokens"] unsignedLongLongValue];
40
- return ModelCountsMake(input >= cached ? input - cached : 0, cached,
41
- [bucket[@"cache_write_input_tokens"] unsignedLongLongValue],
42
+ unsigned long long written = [bucket[@"cache_write_input_tokens"] unsignedLongLongValue];
43
+ unsigned long long uncached = input >= cached ? input - cached : 0;
44
+ return ModelCountsMake(uncached >= written ? uncached - written : 0, cached, written,
42
45
  [bucket[@"output_tokens"] unsignedLongLongValue],
43
46
  [bucket[@"reasoning_output_tokens"] unsignedLongLongValue],
44
47
  [bucket[@"request_count"] unsignedLongLongValue]);
@@ -170,13 +173,14 @@ static unsigned long long ModelDayTokens(NSDictionary *models) {
170
173
 
171
174
  static NSString *const ModelArchiveSchemaKey = @"schema";
172
175
  // 2 起归档的键是 DayLabel(日期),1 是日零点的时间戳字符串。
173
- static const NSInteger ModelArchiveSchemaVersion = 2;
176
+ // 3 起 Codex 的 input 不再包含 cacheWrite,四栏之和不再重复计算缓存写入。
177
+ static const NSInteger ModelArchiveSchemaVersion = 3;
174
178
  // 用量页最长看 90 天(CCPetsUsagePage.m 的 UsageMaximumRangeDays),归档只需要覆盖这么多,
175
179
  // 再留几天余量。读取只取请求区间里的日子,留得更久也没有路径能读到。两边要一起改。
176
180
  static const NSInteger ModelArchiveRetentionDays = 100;
177
181
 
178
182
  // 版本 1 的归档不能直接丢:源头被清掉的那些天只剩这一份。把时间戳键换成日期就能接着用。
179
- static NSMutableDictionary *LoadModelArchive(NSString *path, BOOL *outMigrated) {
183
+ static NSMutableDictionary *LoadModelArchive(NSString *path, BOOL isClaude, BOOL *outMigrated) {
180
184
  NSMutableDictionary *archive = LoadTokenSummaryCache(path);
181
185
  NSDictionary *schema = [archive[ModelArchiveSchemaKey] isKindOfClass:NSDictionary.class]
182
186
  ? archive[ModelArchiveSchemaKey] : nil;
@@ -194,9 +198,31 @@ static NSMutableDictionary *LoadModelArchive(NSString *path, BOOL *outMigrated)
194
198
  }
195
199
  archive[@"days"] = days;
196
200
  if (outMigrated) *outMigrated = YES;
197
- } else if (version != ModelArchiveSchemaVersion) {
201
+ } else if (version != 2 && version != ModelArchiveSchemaVersion) {
198
202
  [archive removeAllObjects];
199
203
  }
204
+ // 不能只让源日志重算:归档合并会保留较大的旧值,而且有些源日志已经被清理。
205
+ // 旧归档保留了独立的 cacheWrite,因此可以原地纠正,版本号保证只扣除一次。
206
+ if (version == 1 || version == 2) {
207
+ if (!isClaude) {
208
+ NSDictionary *oldDays = archive[@"days"];
209
+ NSMutableDictionary *days = [NSMutableDictionary dictionary];
210
+ for (NSString *day in oldDays) {
211
+ NSDictionary *oldModels = oldDays[day];
212
+ NSMutableDictionary *models = [NSMutableDictionary dictionary];
213
+ for (NSString *model in oldModels) {
214
+ NSMutableDictionary *counts = [oldModels[model] mutableCopy];
215
+ unsigned long long input = [counts[@"input"] unsignedLongLongValue];
216
+ unsigned long long written = [counts[@"cacheWrite"] unsignedLongLongValue];
217
+ counts[@"input"] = @(input >= written ? input - written : 0);
218
+ models[model] = counts;
219
+ }
220
+ days[day] = models;
221
+ }
222
+ archive[@"days"] = days;
223
+ }
224
+ if (outMigrated) *outMigrated = YES;
225
+ }
200
226
  archive[ModelArchiveSchemaKey] = @{@"version": @(ModelArchiveSchemaVersion)};
201
227
  if (![archive[@"days"] isKindOfClass:NSDictionary.class]) archive[@"days"] = @{};
202
228
  return archive;
@@ -223,11 +249,12 @@ NSDictionary *CCPetsModelUsageAtHome(NSString *provider, NSString *home,
223
249
  NSMutableDictionary *cache = LoadTokenSummaryCache(cachePath);
224
250
  if (isClaude) MakeCachedRecordsMutable(cache);
225
251
  BOOL archiveChanged = NO;
226
- NSMutableDictionary *archive = LoadModelArchive(archivePath, &archiveChanged);
252
+ NSMutableDictionary *archive = LoadModelArchive(archivePath, isClaude, &archiveChanged);
227
253
 
228
254
  NSDictionary<NSString *, NSDictionary *> *fresh = isClaude
229
255
  ? ClaudeModelDays(start, end, cache, sourceURL)
230
256
  : CodexModelDays(start, end, cache, sourceURL);
257
+ NSDictionary *backgroundDays = isClaude ? @{} : CodexBackgroundModelDays(canonicalHome, start, end);
231
258
 
232
259
  NSMutableDictionary *archivedDays = [archive[@"days"] mutableCopy];
233
260
  NSTimeInterval todayStart = [NSCalendar.currentCalendar
@@ -258,6 +285,17 @@ NSDictionary *CCPetsModelUsageAtHome(NSString *provider, NSString *home,
258
285
  }
259
286
  models = combined;
260
287
  }
288
+ // 后台补录独立持久化,不进入取大保留的日归档。对应 rollout 迟到时可以撤销补录,
289
+ // 不会把它锁在历史最大值里,也不会影响未来主会话日志清理后的保留逻辑。
290
+ if ([backgroundDays[key] count] > 0) {
291
+ NSMutableDictionary *combined = [models mutableCopy];
292
+ for (NSString *model in backgroundDays[key]) {
293
+ NSMutableDictionary *counts = [combined[model] mutableCopy] ?: [NSMutableDictionary dictionary];
294
+ AddModelCounts(counts, backgroundDays[key][model]);
295
+ combined[model] = counts;
296
+ }
297
+ models = combined;
298
+ }
261
299
  [daily addObject:@{@"timestamp": dayStart, @"models": models}];
262
300
  for (NSString *model in models) {
263
301
  NSMutableDictionary *sum = totals[model];
@@ -44,7 +44,8 @@ NSDictionary *UsageByRemovingExpiredQuotaWindows(NSDictionary *usage);
44
44
  // models: @{模型名: counts} 区间合计
45
45
  // daily: @[@{timestamp: 日零点, models: @{模型名: counts}}] 每天一项,没数据的天 models 为空
46
46
  // counts 的键:input(非缓存输入)/ cacheRead / cacheWrite / output / reasoning(output 的子集)/
47
- // requests。四栏 input + cacheRead + cacheWrite + output 互不重叠,等于总 Token。
47
+ // requests / background(后台请求的总 Token,缺少分类明细)。
48
+ // input + cacheRead + cacheWrite + output + background 互不重叠,等于总 Token。
48
49
  // 用自己的缓存和按日归档(Claude Code 默认约 30 天后清理转录,归档里留得更久),
49
50
  // 不碰桌宠悬停面板用的那套缓存。
50
51
  // 每次调用都会把缓存清理到只剩 [start, end) 涉及的会话文件,所以调用方应固定用同一个最长区间,
@@ -52,6 +53,6 @@ NSDictionary *UsageByRemovingExpiredQuotaWindows(NSDictionary *usage);
52
53
  NSDictionary *CCPetsModelUsage(NSString *provider, NSTimeInterval start, NSTimeInterval end);
53
54
  NSDictionary *CCPetsModelUsageAtHome(NSString *provider, NSString *home,
54
55
  NSTimeInterval start, NSTimeInterval end);
55
- // 一份 counts 的总 Token = input + cacheRead + cacheWrite + output(reasoning 是 output 的子集,不另加)。
56
+ // 总 Token = input + cacheRead + cacheWrite + output + background(reasoning 不另加)。
56
57
  // 数据层归档取大和 UI 的合计共用这一个口径。
57
58
  unsigned long long CCPetsTotalTokens(NSDictionary *counts);
@@ -30,7 +30,6 @@
30
30
  @property NSMutableDictionary<NSString *, NSDictionary *> *codexProfileLiveUsages;
31
31
  @property NSMutableDictionary<NSString *, NSString *> *profileReaderHomes;
32
32
  @property NSDictionary *codexLiveUsage;
33
- @property NSTimeInterval codexLiveUsageUpdatedAt;
34
33
  @property FSEventStreamRef codexStream;
35
34
  @property dispatch_source_t claudeSource;
36
35
  @property unsigned long long claudeSize;
@@ -47,6 +46,18 @@
47
46
  // 失败时不能让一次旧的受限结论一直挂着。
48
47
  static const NSTimeInterval CodexLiveUsageTTL = 5 * 60.0;
49
48
 
49
+ // 默认账号、自定义 Home、缓存恢复和实时回调共用同一条合并路径。
50
+ // 用采样时间计龄,轮询旧缓存不会延长受限标记的寿命;窗口百分比仍按新旧快照择优。
51
+ static NSDictionary *ApplyLiveCodexUsage(NSDictionary *sessionUsage, NSDictionary *live) {
52
+ if (live[@"exhaustedAt"] && NSDate.date.timeIntervalSince1970 -
53
+ [live[@"sampledAt"] doubleValue] > CodexLiveUsageTTL) {
54
+ NSMutableDictionary *withoutExhaustion = [live mutableCopy];
55
+ [withoutExhaustion removeObjectForKey:@"exhaustedAt"];
56
+ live = withoutExhaustion;
57
+ }
58
+ return UsageByRemovingExpiredQuotaWindows(CodexUsageByApplyingLiveUsage(sessionUsage, live));
59
+ }
60
+
50
61
  static BOOL HasRegisteredDefaultProfile(NSString *provider) {
51
62
  NSString *target = ([provider isEqualToString:CCPetsProfileProviderClaude]
52
63
  ? DefaultClaudeConfigDirectory() : DefaultCodexHomeDirectory()).stringByStandardizingPath;
@@ -140,14 +151,12 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
140
151
  // 桌宠随最后一个客户端退出,下次启动时 App Server 要几秒才回话。这段时间先用上次
141
152
  // 存下的实时值,否则面板会先显示会话日志里可能已经过时十几个小时的快照。
142
153
  _codexLiveUsage = LoadCodexLiveUsage();
143
- _codexLiveUsageUpdatedAt = [_codexLiveUsage[@"sampledAt"] doubleValue];
144
154
  __weak typeof(self) weakSelf = self;
145
155
  _codexRateLimitsReader.liveUsageHandler = ^(NSDictionary *liveUsage) {
146
156
  dispatch_async(weakSelf.queue, ^{
147
157
  typeof(self) strongSelf = weakSelf;
148
158
  if (!strongSelf || !strongSelf.started) return;
149
159
  strongSelf.codexLiveUsage = liveUsage;
150
- strongSelf.codexLiveUsageUpdatedAt = NSDate.date.timeIntervalSince1970;
151
160
  SaveCodexLiveUsage(liveUsage);
152
161
  strongSelf.codexUsage = [strongSelf usageByApplyingLiveCodexUsage:
153
162
  strongSelf.codexReader.usage ?: strongSelf.codexUsage];
@@ -159,16 +168,7 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
159
168
  }
160
169
 
161
170
  - (NSDictionary *)usageByApplyingLiveCodexUsage:(NSDictionary *)sessionUsage {
162
- NSDictionary *live = self.codexLiveUsage;
163
- if (!live) return sessionUsage;
164
- if (live[@"exhaustedAt"] && NSDate.date.timeIntervalSince1970 -
165
- self.codexLiveUsageUpdatedAt > CodexLiveUsageTTL) {
166
- NSMutableDictionary *withoutExhaustion = [live mutableCopy];
167
- [withoutExhaustion removeObjectForKey:@"exhaustedAt"];
168
- live = withoutExhaustion;
169
- }
170
- // 存下来的实时值可能是好几个小时前的,窗口早已翻篇,合并后要再按 resets_at 过一遍。
171
- return UsageByRemovingExpiredQuotaWindows(CodexUsageByApplyingLiveUsage(sessionUsage, live));
171
+ return ApplyLiveCodexUsage(sessionUsage, self.codexLiveUsage);
172
172
  }
173
173
  // 回调交给主线程:下游全是 UI(面板重排、气泡定位、系统通知)。
174
174
  - (void)publishChange {
@@ -249,8 +249,7 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
249
249
  }
250
250
  usage = [reader refreshWithFullDiscovery];
251
251
  NSDictionary *live = self.codexProfileLiveUsages[profileID];
252
- if (live) usage = UsageByRemovingExpiredQuotaWindows(
253
- CodexUsageByApplyingLiveUsage(usage, live));
252
+ usage = ApplyLiveCodexUsage(usage, live);
254
253
  CCPetsCodexRateLimitsReader *rateReader = self.codexProfileRateReaders[profileID];
255
254
  if (!rateReader) {
256
255
  rateReader = [[CCPetsCodexRateLimitsReader alloc] initWithCodexHome:home];
@@ -263,8 +262,7 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
263
262
  strongSelf.codexProfileLiveUsages[capturedID] = liveUsage;
264
263
  NSMutableDictionary *updated = [strongSelf.profileUsages mutableCopy] ?: [NSMutableDictionary dictionary];
265
264
  NSDictionary *session = strongSelf.codexProfileReaders[capturedID].usage;
266
- if (session) updated[capturedID] = UsageByRemovingExpiredQuotaWindows(
267
- CodexUsageByApplyingLiveUsage(session, liveUsage));
265
+ updated[capturedID] = ApplyLiveCodexUsage(session, liveUsage);
268
266
  strongSelf.profileUsages = updated;
269
267
  [strongSelf publishChange];
270
268
  });
@@ -198,46 +198,28 @@
198
198
  dotColor:tokenComparison[@"color"]];
199
199
 
200
200
  CGFloat trendX = NSMinX(card) + 574;
201
- // 「按日 Token」跟在标题后面,与标题同一行:它是标题的限定语,单独占一行既浪费
202
- // 竖向空间,也把曲线和脚注挤得没法与左边两列对齐。
203
- [L(@"Month") drawInRect:NSMakeRect(trendX, NSMinY(card) + 114, 60, 20)
204
- withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
205
- if (self.usesLiquidGlass) {
206
- [self drawText:L(@"Daily tokens") inRect:NSMakeRect(trendX + 62, NSMinY(card) + 114, 84, 20)
207
- size:11 weight:NSFontWeightSemibold color:color dotColor:color];
208
- } else {
209
- NSDictionary *pillAttributes = [self textAttributesWithSize:11 color:color
210
- weight:NSFontWeightSemibold];
211
- NSRect pill = NSMakeRect(trendX + 59, NSMinY(card) + 113, 76, 22);
212
- [self fillRoundedRect:pill radius:11 color:[color colorWithAlphaComponent:0.14]];
213
- [L(@"Daily tokens") drawInRect:NSInsetRect(pill, 9, 3) withAttributes:pillAttributes];
214
- }
215
- NSRect curveRect = NSMakeRect(trendX, NSMinY(card) + 62, 135, 38);
201
+ // 今日用量和记录天数各占一行,峰值放进悬浮提示。
202
+ [self drawText:L(@"Month") inRect:NSMakeRect(trendX, NSMinY(card) + 114, 145, 20)
203
+ size:13 weight:NSFontWeightRegular color:secondary dotColor:nil];
204
+ NSRect curveRect = NSMakeRect(trendX, NSMinY(card) + 66, 135, 34);
216
205
  [self drawMonthlyTokenCurve:monthDaily inRect:curveRect color:color];
217
- double peak = 0;
218
206
  NSDictionary *todayTotals = nil;
219
207
  for (NSDictionary *day in monthDaily) {
220
208
  if ([day[@"timestamp"] doubleValue] > now) break;
221
209
  NSDictionary *totals = [day[@"totals"] isKindOfClass:NSDictionary.class]
222
210
  ? day[@"totals"] : nil;
223
- peak = fmax(peak, [totals[@"total_tokens"] doubleValue]);
224
211
  todayTotals = totals;
225
212
  }
226
- NSString *peakText = recordedDays > 0
227
- ? [NSString stringWithFormat:L(@"Peak %@"), [self formattedTokenValue:peak]] : L(@"Peak --");
228
213
  NSString *todayText = todayTotals
229
214
  ? [NSString stringWithFormat:L(@"Today %@"),
230
215
  [self formattedTokenValue:[todayTotals[@"total_tokens"] doubleValue]]] : L(@"Today --");
231
- [peakText drawInRect:NSMakeRect(trendX, NSMinY(card) + 42, 74, 16)
232
- withAttributes:[self textAttributesWithSize:10 color:secondary weight:NSFontWeightRegular]];
233
- [todayText drawInRect:NSMakeRect(trendX + 61, NSMinY(card) + 42, 74, 16)
234
- withAttributes:[self rightAlignedTextAttributesWithSize:10 color:secondary
235
- weight:NSFontWeightRegular]];
236
- // 与左边两列的"较上月同期"同一条基线(+22),三列脚注才在一条水平线上。
237
- [[NSString stringWithFormat:L(@"%lu / %lu days recorded"),
238
- (unsigned long)recordedDays, (unsigned long)monthDaily.count]
239
- drawInRect:NSMakeRect(trendX, NSMinY(card) + 22, 145, 18)
240
- withAttributes:[self textAttributesWithSize:11 color:color weight:NSFontWeightMedium]];
216
+ [self drawText:todayText inRect:NSMakeRect(trendX, NSMinY(card) + 44, 145, 18)
217
+ size:11 weight:NSFontWeightRegular color:secondary dotColor:nil];
218
+ // 记录天数与左侧两列的月同比脚注保持相同基线和字号。
219
+ NSString *recordedText = [NSString stringWithFormat:L(@"%lu / %lu days recorded"),
220
+ (unsigned long)recordedDays, (unsigned long)monthDaily.count];
221
+ [self drawText:recordedText inRect:NSMakeRect(trendX, NSMinY(card) + 22, 145, 18)
222
+ size:11 weight:NSFontWeightMedium color:color dotColor:nil];
241
223
  [NSGraphicsContext restoreGraphicsState];
242
224
  return;
243
225
  }
@@ -12,6 +12,60 @@ CGFloat QuotaLogicalHeightForProviderCount(NSUInteger count) {
12
12
  }
13
13
 
14
14
 
15
+ // 各家图标的透明边距不同。加载时按不透明主体裁切,再放进相同的留白画布,
16
+ // 避免每次重绘扫描像素,也避免 ICNS 的阴影影响视觉尺寸。
17
+ static NSImage *NormalizedAgentIcon(NSImage *image) {
18
+ const size_t side = 256;
19
+ CGImageRef source = [image CGImageForProposedRect:NULL context:nil hints:nil];
20
+ if (!source) return image;
21
+ unsigned char *pixels = calloc(side * side, 4);
22
+ if (!pixels) return image;
23
+ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
24
+ CGContextRef context = CGBitmapContextCreate(pixels, side, side, 8, side * 4,
25
+ colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
26
+ CGColorSpaceRelease(colorSpace);
27
+ if (!context) { free(pixels); return image; }
28
+ CGFloat width = CGImageGetWidth(source), height = CGImageGetHeight(source);
29
+ CGFloat scale = MIN(side / width, side / height);
30
+ CGContextDrawImage(context, CGRectMake((side - width * scale) / 2,
31
+ (side - height * scale) / 2, width * scale, height * scale), source);
32
+ size_t minX = side, minY = side, maxX = 0, maxY = 0;
33
+ for (size_t y = 0; y < side; y++) {
34
+ for (size_t x = 0; x < side; x++) {
35
+ if (pixels[(y * side + x) * 4 + 3] < 128) continue;
36
+ minX = MIN(minX, x); minY = MIN(minY, y);
37
+ maxX = MAX(maxX, x); maxY = MAX(maxY, y);
38
+ }
39
+ }
40
+ CGImageRef raster = CGBitmapContextCreateImage(context);
41
+ CGContextRelease(context);
42
+ free(pixels);
43
+ if (!raster || minX == side) {
44
+ if (raster) CGImageRelease(raster);
45
+ return image;
46
+ }
47
+ CGImageRef cropped = CGImageCreateWithImageInRect(raster,
48
+ CGRectMake(minX, minY, maxX - minX + 1, maxY - minY + 1));
49
+ CGImageRelease(raster);
50
+ if (!cropped) return image;
51
+ NSSize size = NSMakeSize(CGImageGetWidth(cropped), CGImageGetHeight(cropped));
52
+ NSImage *content = [[NSImage alloc] initWithCGImage:cropped size:size];
53
+ CGImageRelease(cropped);
54
+ return [NSImage imageWithSize:NSMakeSize(side, side) flipped:NO drawingHandler:^BOOL(NSRect bounds) {
55
+ NSRect available = NSInsetRect(bounds, 16, 16);
56
+ CGFloat fit = MIN(NSWidth(available) / size.width, NSHeight(available) / size.height);
57
+ NSRect target = NSMakeRect(NSMidX(bounds) - size.width * fit / 2,
58
+ NSMidY(bounds) - size.height * fit / 2, size.width * fit, size.height * fit);
59
+ [NSGraphicsContext saveGraphicsState];
60
+ CGFloat radius = MIN(NSWidth(target), NSHeight(target)) * 18 / 70;
61
+ [[NSBezierPath bezierPathWithRoundedRect:target xRadius:radius yRadius:radius] addClip];
62
+ [content drawInRect:target fromRect:NSZeroRect operation:NSCompositingOperationSourceOver
63
+ fraction:1 respectFlipped:YES hints:@{NSImageHintInterpolation: @(NSImageInterpolationHigh)}];
64
+ [NSGraphicsContext restoreGraphicsState];
65
+ return YES;
66
+ }];
67
+ }
68
+
15
69
  NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
16
70
  NSURL *appURL = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:bundleIdentifier];
17
71
  NSMutableArray<NSString *> *paths = [NSMutableArray array];
@@ -28,9 +82,28 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
28
82
  [applicationName stringByAppendingPathComponent:[@"Contents/Resources" stringByAppendingPathComponent:resourceName]]]];
29
83
  for (NSString *path in paths) {
30
84
  NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
31
- if (image) return image;
85
+ if (image) return NormalizedAgentIcon(image);
32
86
  }
33
- return appURL ? [NSWorkspace.sharedWorkspace iconForFile:appURL.path] : nil;
87
+ if (appURL && [NSFileManager.defaultManager fileExistsAtPath:appURL.path]) {
88
+ NSImage *image = [NSWorkspace.sharedWorkspace iconForFile:appURL.path];
89
+ if (image) return NormalizedAgentIcon(image);
90
+ }
91
+ // 没装官方桌面端(例如只装 CLI)时,从发布包读取备用图标。
92
+ NSString *fallback = [bundleIdentifier isEqualToString:@"com.anthropic.claudefordesktop"]
93
+ ? @"claude.png" : ([bundleIdentifier isEqualToString:@"com.openai.codex"] ? @"codex.icns" : nil);
94
+ if (!fallback) return nil;
95
+ NSArray<NSString *> *directories = @[
96
+ NSBundle.mainBundle.resourcePath ?: @"",
97
+ NSBundle.mainBundle.executablePath.stringByDeletingLastPathComponent ?: @""
98
+ ];
99
+ for (NSString *directory in directories) {
100
+ if (directory.length == 0) continue;
101
+ NSString *path = [[directory stringByAppendingPathComponent:@"AgentIcons"]
102
+ stringByAppendingPathComponent:fallback];
103
+ NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
104
+ if (image) return NormalizedAgentIcon(image);
105
+ }
106
+ return nil;
34
107
  }
35
108
 
36
109
 
@@ -206,6 +279,59 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
206
279
  return NSZeroRect;
207
280
  }
208
281
 
282
+ - (NSRect)logicalTrendRectForProvider:(NSString *)provider {
283
+ NSRect card = [self logicalCardRectForProvider:provider];
284
+ CGFloat contentOffset = (NSHeight(card) - QuotaBaseCardHeight) / 2;
285
+ return NSMakeRect(NSMinX(card) + 574, NSMinY(card) + contentOffset + 22, 145, 112);
286
+ }
287
+
288
+ - (void)updateTrackingAreas {
289
+ [super updateTrackingAreas];
290
+ [self removeAllToolTips];
291
+ for (NSString *provider in [self visibleProviders]) {
292
+ NSRect rect = [self logicalTrendRectForProvider:provider];
293
+ rect.origin.x *= QuotaScale;
294
+ rect.origin.y *= QuotaScale;
295
+ rect.size.width *= QuotaScale;
296
+ rect.size.height *= QuotaScale;
297
+ [self addToolTipRect:rect owner:self userData:NULL];
298
+ }
299
+ }
300
+
301
+ - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag
302
+ point:(NSPoint)point userData:(void *)data {
303
+ // 在显示时读取当前账号,轮播或刷新数据后不会留下上一账号的统计。
304
+ if (self.animatingCarouselProvider.length > 0) return nil;
305
+ NSPoint logicalPoint = NSMakePoint(point.x / QuotaScale, point.y / QuotaScale);
306
+ for (NSString *provider in [self visibleProviders]) {
307
+ if (!NSPointInRect(logicalPoint, [self logicalTrendRectForProvider:provider])) continue;
308
+ NSDictionary *usage = [self usageForProvider:provider];
309
+ NSDictionary *state = [self accountStateForProvider:provider
310
+ profile:[self selectedProfileForProvider:provider] usage:usage];
311
+ if (![state[@"apiMode"] boolValue]) return nil;
312
+ NSDictionary *tokenUsage = [usage[@"tokenUsage"] isKindOfClass:NSDictionary.class]
313
+ ? usage[@"tokenUsage"] : nil;
314
+ NSArray<NSDictionary *> *days = [tokenUsage[@"monthDaily"] isKindOfClass:NSArray.class]
315
+ ? tokenUsage[@"monthDaily"] : @[];
316
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
317
+ NSUInteger recordedDays = 0;
318
+ double peak = 0;
319
+ for (NSDictionary *day in days) {
320
+ if ([day[@"timestamp"] doubleValue] > now) continue;
321
+ NSDictionary *totals = [day[@"totals"] isKindOfClass:NSDictionary.class]
322
+ ? day[@"totals"] : nil;
323
+ peak = fmax(peak, [totals[@"total_tokens"] doubleValue]);
324
+ recordedDays += 1;
325
+ }
326
+ NSString *peakText = recordedDays > 0
327
+ ? [NSString stringWithFormat:L(@"Peak %@"), [self formattedTokenValue:peak]] : L(@"Peak --");
328
+ NSString *recordedText = [NSString stringWithFormat:L(@"%lu / %lu days recorded"),
329
+ (unsigned long)recordedDays, (unsigned long)days.count];
330
+ return [NSString stringWithFormat:@"%@\n%@\n%@", L(@"Daily tokens"), peakText, recordedText];
331
+ }
332
+ return nil;
333
+ }
334
+
209
335
  - (NSString *)providerAtEvent:(NSEvent *)event includeArrowGutters:(BOOL)includeArrowGutters
210
336
  logicalPoint:(NSPoint *)outPoint {
211
337
  NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];