cc-pets 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +60 -0
  4. package/CHANGELOG.zh-CN.md +60 -0
  5. package/CONTRIBUTING.md +13 -10
  6. package/CONTRIBUTING.zh-CN.md +11 -10
  7. package/README.md +113 -24
  8. package/README.zh-CN.md +89 -28
  9. package/Resources/zh-Hans.lproj/Localizable.strings +568 -17
  10. package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
  11. package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +82 -23
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +17 -3
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +70 -22
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
  16. package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
  17. package/Sources/CCPets/{CCPetsAppDelegate+Settings.m → App/CCPetsAppDelegate+Settings.m} +86 -98
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +8 -4
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  20. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +15 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +107 -11
  22. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  23. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  24. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  25. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  26. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  27. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  35. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  37. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  38. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  39. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  41. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  43. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  44. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  45. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  46. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +11 -2
  47. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +19 -2
  48. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +4 -1
  49. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  50. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  51. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  52. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  53. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  54. package/Sources/CCPets/Pet/PetView.m +635 -0
  55. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  56. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  57. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  58. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  59. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  60. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  61. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  62. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  63. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  64. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  65. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  66. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  67. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  68. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  69. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  70. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  71. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  72. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  73. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  74. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  75. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  76. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  77. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  78. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  79. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  80. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  81. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  82. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  83. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  84. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  85. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  86. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  87. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  88. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  89. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  90. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  91. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  92. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  93. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  94. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  95. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  96. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  97. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  98. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  99. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  100. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  101. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  102. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  103. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  104. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  105. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  106. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  107. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  108. package/THIRD_PARTY_NOTICES.md +1 -1
  109. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  110. package/bin/cc-pets +8 -6
  111. package/bin/claude-with-pet +10 -2
  112. package/bin/codex-with-pet +13 -5
  113. package/package.json +1 -1
  114. package/scripts/build.sh +7 -3
  115. package/scripts/i18n.zsh +9 -52
  116. package/scripts/install-app.sh +4 -0
  117. package/scripts/install-shell-integration.sh +17 -10
  118. package/scripts/uninstall-shell-integration.sh +6 -1
  119. package/Sources/CCPets/CCPetsEvents.h +0 -10
  120. package/Sources/CCPets/CCPetsUsage.h +0 -36
  121. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  122. package/Sources/CCPets/PetView.m +0 -1839
  123. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  124. package/scripts/bridge/cli.mjs +0 -237
  125. package/scripts/bridge/core.mjs +0 -228
  126. package/scripts/bridge/hook.mjs +0 -150
  127. package/scripts/bridge/install.mjs +0 -311
  128. package/scripts/bridge/mcp-server.mjs +0 -308
  129. package/scripts/bridge/options.mjs +0 -87
  130. package/scripts/bridge/process.mjs +0 -151
  131. package/scripts/bridge/reservations.mjs +0 -248
  132. package/scripts/bridge/store.mjs +0 -433
  133. package/scripts/bridge/watch.mjs +0 -69
  134. package/scripts/check-l10n.mjs +0 -168
  135. package/scripts/configure-updater.mjs +0 -43
  136. package/scripts/detect-cli.mjs +0 -68
  137. package/scripts/doctor.mjs +0 -470
  138. package/scripts/i18n.mjs +0 -122
  139. package/scripts/install-claude-hooks.mjs +0 -253
  140. package/scripts/install-codex-hooks.mjs +0 -78
  141. package/scripts/integration-markers.mjs +0 -51
  142. package/scripts/locales/zh-Hans.json +0 -366
  143. package/scripts/pet-store.mjs +0 -415
  144. package/scripts/uninstall-integrations.mjs +0 -205
  145. /package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +0 -0
  146. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  147. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  148. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  149. /package/Sources/CCPets/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
  150. /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
  151. /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
  152. /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
  153. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  154. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  155. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  156. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  157. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  159. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  161. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  162. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  163. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  164. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  165. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  166. /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
  167. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  168. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  169. /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
  170. /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
  171. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -0,0 +1,717 @@
1
+ #import "CCPetsUsagePage.h"
2
+ #import "CCPetsFormBuilder.h"
3
+ #import "CCPetsL10n.h"
4
+ #import "CCPetsUIStyle.h"
5
+ #import "CCPetsUsage.h"
6
+ #import "CCPetsProfiles.h"
7
+ #import "CCPetsCLISupport.h"
8
+ #import "CCPetsUsageShared.h"
9
+ #import "CCPetsUsageChartView.h"
10
+ #import "CCPetsUsageWidgets.h"
11
+
12
+ // 1234 -> 1.23K,1234567 -> 1.23M:卡片里放不下一长串数字,精确值在悬停时给。
13
+ // 先按三位有效数字舍入再定单位:999,950 直接格式化会得到 "1000K",9,995 会得到 "10.00K"。
14
+ NSString *CCPetsFormatTokens(unsigned long long value) {
15
+ if (value < 1000) return [NSString stringWithFormat:@"%llu", value];
16
+ double scaled = (double)value;
17
+ NSUInteger unit = 0;
18
+ NSArray<NSString *> *suffixes = @[@"K", @"M", @"B", @"T"];
19
+ while (unit < suffixes.count) {
20
+ scaled /= 1000;
21
+ double rounded = scaled >= 100 ? round(scaled) : (scaled >= 10 ? round(scaled * 10) / 10 : round(scaled * 100) / 100);
22
+ if (rounded < 1000 || unit == suffixes.count - 1) {
23
+ scaled = rounded;
24
+ break;
25
+ }
26
+ unit++;
27
+ }
28
+ return [NSString stringWithFormat:scaled >= 100 ? @"%.0f%@" : (scaled >= 10 ? @"%.1f%@" : @"%.2f%@"),
29
+ scaled, suffixes[unit]];
30
+ }
31
+
32
+ // 命中率 = 缓存读 / 全部输入侧(非缓存输入 + 缓存读 + 缓存写)。两家的原始口径不同,
33
+ // 但 CCPetsModelUsage 已经统一成四栏互不重叠,所以这里同一个公式。
34
+ static NSString *HitRateText(NSDictionary *counts) {
35
+ unsigned long long side = Count(counts, @"input") + Count(counts, @"cacheRead") + Count(counts, @"cacheWrite");
36
+ if (side == 0) return @"–";
37
+ return [NSString stringWithFormat:@"%.0f%%", 100.0 * Count(counts, @"cacheRead") / side];
38
+ }
39
+
40
+ static NSString *ProviderTitle(NSString *provider) {
41
+ return [provider isEqualToString:@"claude"] ? @"Claude Code" : @"Codex";
42
+ }
43
+
44
+ static NSString *EntrySourceTitle(NSDictionary *entry) {
45
+ NSString *accountName = [entry[@"accountName"] isKindOfClass:NSString.class]
46
+ ? entry[@"accountName"] : nil;
47
+ return accountName.length > 0 ? accountName : ProviderTitle(entry[@"provider"]);
48
+ }
49
+
50
+ // 数据层把认不出模型的用量记在 "unknown" 名下(旧格式会话、没见过 turn_context 的续读段),
51
+ // 这个名字是内部占位,显示时换成本地化文案。
52
+ static NSString *ModelTitle(NSString *model) {
53
+ return [model isEqualToString:@"unknown"] ? L(@"Unknown Model") : model;
54
+ }
55
+
56
+ static NSMutableDictionary *SummedCounts(NSArray<NSDictionary *> *list) {
57
+ NSMutableDictionary *sum = [NSMutableDictionary dictionary];
58
+ for (NSDictionary *counts in list) {
59
+ for (NSString *key in @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests"]) {
60
+ sum[key] = @(Count(sum, key) + Count(counts, key));
61
+ }
62
+ }
63
+ return sum;
64
+ }
65
+
66
+ NSDictionary *CCPetsUsageDayTotals(NSDictionary *day) {
67
+ NSDictionary *models = [day[@"models"] isKindOfClass:NSDictionary.class] ? day[@"models"] : @{};
68
+ return SummedCounts(models.allValues);
69
+ }
70
+
71
+ NSDictionary *CCPetsUsageSum(NSArray<NSDictionary *> *list) {
72
+ return SummedCounts(list);
73
+ }
74
+
75
+ // 缓存写量小,不单占一格,只在总用量下面带一句。
76
+ NSArray<NSArray<NSString *> *> *CCPetsUsageMetricItems(NSString *totalTitle, NSDictionary *sum, NSUInteger modelCount) {
77
+ unsigned long long input = Count(sum, @"input"), write = Count(sum, @"cacheWrite");
78
+ unsigned long long output = Count(sum, @"output"), read = Count(sum, @"cacheRead");
79
+ unsigned long long side = input + write + read;
80
+ NSString *hit = side > 0 ? [NSString stringWithFormat:L(@"Hit rate %.0f%%"), 100.0 * read / side]
81
+ : L(@"No cache reads yet");
82
+ return @[
83
+ @[totalTitle, CCPetsFormatTokens(CCPetsTotalTokens(sum)), write > 0
84
+ ? [NSString stringWithFormat:L(@"Includes %@ cache write"), CCPetsFormatTokens(write)] : L(@"All tokens")],
85
+ @[L(@"Input"), CCPetsFormatTokens(input), L(@"Excluding cache")],
86
+ @[L(@"Output"), CCPetsFormatTokens(output), L(@"Generated by the model")],
87
+ @[L(@"Cached Input"), CCPetsFormatTokens(read), hit],
88
+ @[L(@"Requests"), FormatCount(Count(sum, @"requests")), modelCount == 1 ? L(@"1 model")
89
+ : [NSString stringWithFormat:L(@"%lu models"), (unsigned long)modelCount]],
90
+ ];
91
+ }
92
+
93
+ // 用量页开着时多久问一次 loadIfStale。没过期时它直接返回,所以这只是一次时间比较。
94
+ static const NSTimeInterval UsagePageRefreshInterval = 60;
95
+
96
+ #pragma mark - 页面
97
+
98
+ @interface CCPetsUsageHandler : NSObject
99
+ @property(nonatomic, copy) void (^block)(id sender);
100
+ - (void)invoke:(id)sender;
101
+ @end
102
+
103
+ @implementation CCPetsUsageHandler
104
+ - (void)invoke:(id)sender {
105
+ if (self.block) self.block(sender);
106
+ }
107
+ @end
108
+
109
+ @interface CCPetsUsagePage ()
110
+ @property(nonatomic) CCPetsFormBuilder *form;
111
+ @property(nonatomic) NSSegmentedControl *sourceControl;
112
+ @property(nonatomic) NSPopUpButton *sourcePopup;
113
+ @property(nonatomic) NSStackView *sourceSwitcher;
114
+ // segment 0 是全部账号,其余与这里的 profile 顺序一一对应。
115
+ @property(nonatomic) NSArray<NSDictionary *> *filterProfiles;
116
+ @property(nonatomic) NSSegmentedControl *rangeControl;
117
+ @property(nonatomic) NSSegmentedControl *metricControl;
118
+ @property(nonatomic) NSProgressIndicator *spinner;
119
+ @property(nonatomic) NSMutableArray<CCPetsUsageHandler *> *handlers;
120
+ // 当前筛选下的模型条目:key、provider、model、counts(区间合计)、days(每天的 counts)。按总用量从大到小。
121
+ @property(nonatomic) NSArray<NSDictionary *> *entries;
122
+ // 模型 -> 色板位置。按 90 天、全部来源的总用量排序分配,之后切来源、区间、指标都不重新上色:
123
+ // 颜色跟着模型走,不跟着名次走。数据重载时已经有颜色、仍在前 8 名的模型保留原色,见 computeColorSlots。
124
+ @property(nonatomic) NSDictionary<NSString *, NSNumber *> *colorSlots;
125
+ // 选中的模型 key;nil 是全部模型。
126
+ @property(nonatomic, copy) NSString *selectedKey;
127
+ @property(nonatomic) NSArray<NSNumber *> *dayStamps;
128
+ @property(nonatomic) CCPetsUsageChartView *chart;
129
+ @property(nonatomic) NSTextField *chartTitle;
130
+ @property(nonatomic) NSTextField *chartHint;
131
+ @property(nonatomic) CCPetsFlowView *legend;
132
+ @property(nonatomic) NSMutableDictionary<NSString *, CCPetsLegendItem *> *legendItems;
133
+ @property(nonatomic) NSMutableDictionary<NSString *, CCPetsUsageModelRow *> *modelRows;
134
+ @property(nonatomic) NSView *kpis;
135
+ @property(nonatomic) NSView *chartCard;
136
+ @property(nonatomic) NSView *tableCard;
137
+ // 页面显示期间定时触发 loadIfStale,让一直开着的用量页也能看到新用量、跨天后换到新的区间。
138
+ @property(nonatomic) NSTimer *refreshTimer;
139
+ @end
140
+
141
+ @implementation CCPetsUsagePage
142
+
143
+ - (void)bind:(NSControl *)control to:(void (^)(id sender))block {
144
+ CCPetsUsageHandler *handler = [CCPetsUsageHandler new];
145
+ handler.block = block;
146
+ [self.handlers addObject:handler];
147
+ control.target = handler;
148
+ control.action = @selector(invoke:);
149
+ }
150
+
151
+ - (NSSegmentedControl *)segmentedWithLabels:(NSArray<NSString *> *)labels selected:(NSInteger)selected {
152
+ NSSegmentedControl *control = [NSSegmentedControl segmentedControlWithLabels:labels
153
+ trackingMode:NSSegmentSwitchTrackingSelectOne target:nil action:nil];
154
+ control.controlSize = NSControlSizeSmall;
155
+ control.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
156
+ control.selectedSegment = selected;
157
+ CCPetsApplyAccent(control);
158
+ return control;
159
+ }
160
+
161
+ - (void)loadView {
162
+ self.handlers = [NSMutableArray array];
163
+ self.form = [[CCPetsFormBuilder alloc] initWithTitle:L(@"Usage") subtitle:@""];
164
+ __weak typeof(self) weakSelf = self;
165
+
166
+ self.sourceControl = [self segmentedWithLabels:@[L(@"All")] selected:0];
167
+ [self bind:self.sourceControl to:^(id sender) {
168
+ weakSelf.selectedKey = nil;
169
+ [weakSelf render];
170
+ }];
171
+ self.sourcePopup = [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO];
172
+ self.sourcePopup.controlSize = NSControlSizeSmall;
173
+ self.sourcePopup.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize];
174
+ [self bind:self.sourcePopup to:^(id sender) {
175
+ weakSelf.selectedKey = nil;
176
+ [weakSelf render];
177
+ }];
178
+ self.sourceSwitcher = [NSStackView stackViewWithViews:@[self.sourceControl, self.sourcePopup]];
179
+ self.sourceSwitcher.orientation = NSUserInterfaceLayoutOrientationHorizontal;
180
+ self.sourceSwitcher.spacing = 0;
181
+ [self rebuildSourceControlSelectingProfileID:nil];
182
+ NSMutableArray<NSString *> *ranges = [NSMutableArray array];
183
+ for (NSNumber *days in @[@7, @30, @90]) {
184
+ [ranges addObject:[NSString stringWithFormat:L(@"%ld Days"), (long)days.integerValue]];
185
+ }
186
+ self.rangeControl = [self segmentedWithLabels:ranges selected:1];
187
+ [self bind:self.rangeControl to:^(id sender) { [weakSelf render]; }];
188
+
189
+ NSProgressIndicator *spinner = [NSProgressIndicator new];
190
+ spinner.style = NSProgressIndicatorStyleSpinning;
191
+ spinner.controlSize = NSControlSizeSmall;
192
+ spinner.displayedWhenStopped = NO;
193
+ self.spinner = spinner;
194
+ [self.form setAccessoryViews:@[spinner, self.sourceSwitcher, self.rangeControl]];
195
+
196
+ NSMutableArray<NSString *> *metrics = [NSMutableArray array];
197
+ for (UsageMetric metric = UsageMetricTotal; metric <= UsageMetricRequests; metric++) [metrics addObject:MetricTitle(metric)];
198
+ self.metricControl = [self segmentedWithLabels:metrics selected:0];
199
+ [self bind:self.metricControl to:^(id sender) { [weakSelf renderChart]; }];
200
+
201
+ self.view = self.form.view;
202
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(storeDidChange:)
203
+ name:CCPetsUsageStoreDidChangeNotification object:nil];
204
+ [self render];
205
+ [CCPetsUsageStore loadIfStale];
206
+ if (CCPetsUsageStore.loading) [spinner startAnimation:nil];
207
+ }
208
+
209
+ - (void)viewDidAppear {
210
+ [super viewDidAppear];
211
+ [self.refreshTimer invalidate];
212
+ __weak typeof(self) weakSelf = self;
213
+ self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:UsagePageRefreshInterval repeats:YES
214
+ block:^(NSTimer *timer) {
215
+ CCPetsUsagePage *page = weakSelf;
216
+ if (!page.view.window.isVisible || page.view.window.isMiniaturized) return;
217
+ [CCPetsUsageStore loadIfStale];
218
+ if (CCPetsUsageStore.loading) [page.spinner startAnimation:nil];
219
+ }];
220
+ self.refreshTimer.tolerance = 10;
221
+ }
222
+
223
+ - (void)viewWillDisappear {
224
+ [super viewWillDisappear];
225
+ [self.refreshTimer invalidate];
226
+ self.refreshTimer = nil;
227
+ }
228
+
229
+ - (void)dealloc {
230
+ [_refreshTimer invalidate];
231
+ [NSNotificationCenter.defaultCenter removeObserver:self];
232
+ }
233
+
234
+ - (void)storeDidChange:(NSNotification *)notification {
235
+ [self.spinner stopAnimation:nil];
236
+ NSString *selectedID = [self selectedAccountID];
237
+ [self rebuildSourceControlSelectingProfileID:selectedID];
238
+ [self computeColorSlots];
239
+ [self render];
240
+ }
241
+
242
+ - (NSInteger)rangeDays {
243
+ static const NSInteger ranges[] = {7, 30, 90};
244
+ return ranges[MIN(2, MAX(0, self.rangeControl.selectedSegment))];
245
+ }
246
+
247
+ - (UsageMetric)metric {
248
+ return (UsageMetric)MAX(0, self.metricControl.selectedSegment);
249
+ }
250
+
251
+ - (void)rebuildSourceControlSelectingProfileID:(NSString *)selectedID {
252
+ NSMutableArray<NSDictionary *> *profiles = [NSMutableArray array];
253
+ // 同一家账号放在一起,顺序与面板一致:Codex 在前,Claude 在后。
254
+ [profiles addObjectsFromArray:CCPetsProfilesForProvider(CCPetsProfileProviderCodex)];
255
+ [profiles addObjectsFromArray:CCPetsProfilesForProvider(CCPetsProfileProviderClaude)];
256
+ self.filterProfiles = profiles;
257
+ self.sourceControl.segmentCount = profiles.count + 1;
258
+ [self.sourceControl setLabel:L(@"All") forSegment:0];
259
+ [self.sourceControl setWidth:0 forSegment:0];
260
+ [self.sourcePopup removeAllItems];
261
+ [self.sourcePopup addItemWithTitle:L(@"All")];
262
+ NSInteger selectedSegment = 0;
263
+ CGFloat estimatedWidth = 44;
264
+ for (NSUInteger index = 0; index < profiles.count; index++) {
265
+ NSDictionary *profile = profiles[index];
266
+ NSString *title = profile[@"displayName"] ?: profile[@"slug"] ?: profile[@"provider"];
267
+ NSInteger segment = (NSInteger)index + 1;
268
+ [self.sourceControl setLabel:title forSegment:segment];
269
+ [self.sourceControl setToolTip:CCPetsTildePath(profile[@"home"]) forSegment:segment];
270
+ [self.sourceControl setWidth:0 forSegment:segment];
271
+ [self.sourcePopup addItemWithTitle:title];
272
+ self.sourcePopup.lastItem.toolTip = CCPetsTildePath(profile[@"home"]);
273
+ estimatedWidth += MAX(54, [title sizeWithAttributes:@{
274
+ NSFontAttributeName: self.sourceControl.font
275
+ }].width + 22);
276
+ if (selectedID.length > 0 && [profile[@"id"] isEqualToString:selectedID]) {
277
+ selectedSegment = segment;
278
+ }
279
+ }
280
+ self.sourceControl.selectedSegment = selectedSegment;
281
+ [self.sourcePopup selectItemAtIndex:selectedSegment];
282
+ // 少量短名称保留快速分段切换;账号多或名称长时自动降级为下拉菜单,避免和
283
+ // 右侧时间范围控件互相挤压。下拉菜单仍完整保留每个账号和 Home 提示。
284
+ BOOL usePopup = profiles.count > 3 || estimatedWidth > 360;
285
+ self.sourceControl.hidden = usePopup;
286
+ self.sourcePopup.hidden = !usePopup;
287
+ }
288
+
289
+ - (NSDictionary *)selectedProfile {
290
+ NSInteger selected = self.sourcePopup.hidden
291
+ ? self.sourceControl.selectedSegment : self.sourcePopup.indexOfSelectedItem;
292
+ NSInteger index = selected - 1;
293
+ return index >= 0 && index < (NSInteger)self.filterProfiles.count
294
+ ? self.filterProfiles[(NSUInteger)index] : nil;
295
+ }
296
+
297
+ - (NSString *)selectedAccountID {
298
+ NSString *value = [self selectedProfile][@"id"];
299
+ return [value isKindOfClass:NSString.class] && value.length > 0 ? value : nil;
300
+ }
301
+
302
+ // 色板位置:90 天、全部来源里按总用量排名,前 8 名各占一色,其余归「其他」。
303
+ // 重算时已经有颜色、仍在前 8 名的模型保留原来的位置,只有新进前 8 的模型按名次去占空出来的位置——
304
+ // 否则两个模型名次一互换,图表和图例里的颜色就跟着对调。
305
+ - (void)computeColorSlots {
306
+ NSMutableDictionary<NSString *, NSNumber *> *totals = [NSMutableDictionary dictionary];
307
+ for (NSString *provider in CCPetsUsageStore.results) {
308
+ for (NSDictionary *day in CCPetsUsageStore.results[provider][@"daily"]) {
309
+ NSDictionary *models = day[@"models"];
310
+ for (NSString *model in models) {
311
+ NSString *key = [NSString stringWithFormat:@"%@|%@", provider, model];
312
+ totals[key] = @(totals[key].unsignedLongLongValue + CCPetsTotalTokens(models[model]));
313
+ }
314
+ }
315
+ }
316
+ NSArray<NSString *> *ranked = [totals keysSortedByValueUsingComparator:^NSComparisonResult(NSNumber *a, NSNumber *b) {
317
+ return [b compare:a];
318
+ }];
319
+ NSUInteger colored = MIN(ranked.count, (NSUInteger)CCPetsChartColorCount);
320
+ NSMutableDictionary<NSString *, NSNumber *> *slots = [NSMutableDictionary dictionary];
321
+ NSMutableIndexSet *taken = [NSMutableIndexSet indexSet];
322
+ for (NSUInteger index = 0; index < colored; index++) {
323
+ NSInteger previous = self.colorSlots[ranked[index]] ? self.colorSlots[ranked[index]].integerValue : -1;
324
+ if (previous < 0) continue;
325
+ slots[ranked[index]] = @(previous);
326
+ [taken addIndex:(NSUInteger)previous];
327
+ }
328
+ NSUInteger next = 0;
329
+ for (NSUInteger index = 0; index < ranked.count; index++) {
330
+ if (slots[ranked[index]]) continue;
331
+ if (index >= colored) {
332
+ slots[ranked[index]] = @(-1);
333
+ continue;
334
+ }
335
+ while ([taken containsIndex:next]) next++;
336
+ slots[ranked[index]] = @((NSInteger)next);
337
+ [taken addIndex:next];
338
+ }
339
+ self.colorSlots = slots;
340
+ }
341
+
342
+ - (NSColor *)colorForKey:(NSString *)key {
343
+ NSNumber *slot = self.colorSlots[key];
344
+ return CCPetsChartColor(slot ? slot.integerValue : -1);
345
+ }
346
+
347
+ // 按当前来源和区间整理条目。区间合计由截取后的每日数据现加,不用数据层的 models(那是整整 90 天的)。
348
+ - (NSArray<NSDictionary *> *)entriesForRangeDays:(NSInteger)rangeDays {
349
+ NSMutableArray<NSDictionary *> *entries = [NSMutableArray array];
350
+ NSDictionary *selectedProfile = [self selectedProfile];
351
+ NSString *selectedProvider = selectedProfile[@"provider"];
352
+ NSArray<NSString *> *providers = selectedProvider.length > 0
353
+ ? @[selectedProvider] : @[@"claude", @"codex"];
354
+ NSArray<NSNumber *> *stamps = nil;
355
+ for (NSString *provider in providers) {
356
+ NSString *selectedID = selectedProfile[@"id"];
357
+ NSDictionary *result = selectedID.length > 0
358
+ ? CCPetsUsageStore.profileResults[selectedID] : CCPetsUsageStore.results[provider];
359
+ NSArray<NSDictionary *> *daily = result[@"daily"];
360
+ if (daily.count > (NSUInteger)rangeDays) {
361
+ daily = [daily subarrayWithRange:NSMakeRange(daily.count - (NSUInteger)rangeDays, (NSUInteger)rangeDays)];
362
+ }
363
+ if (!stamps || daily.count > stamps.count) stamps = [daily valueForKey:@"timestamp"];
364
+ NSMutableSet<NSString *> *models = [NSMutableSet set];
365
+ for (NSDictionary *day in daily) [models addObjectsFromArray:[day[@"models"] allKeys]];
366
+ for (NSString *model in models) {
367
+ NSMutableArray<NSDictionary *> *days = [NSMutableArray arrayWithCapacity:daily.count];
368
+ for (NSDictionary *day in daily) [days addObject:day[@"models"][model] ?: @{}];
369
+ NSDictionary *counts = SummedCounts(days);
370
+ if (CCPetsTotalTokens(counts) == 0 && Count(counts, @"requests") == 0) continue;
371
+ NSMutableDictionary *entry = [@{@"key": [NSString stringWithFormat:@"%@|%@", provider, model],
372
+ @"provider": provider, @"model": model, @"counts": counts, @"days": days} mutableCopy];
373
+ NSString *accountName = selectedProfile[@"displayName"] ?: selectedProfile[@"slug"];
374
+ if (accountName.length > 0) entry[@"accountName"] = accountName;
375
+ [entries addObject:entry];
376
+ }
377
+ }
378
+ self.dayStamps = stamps ?: @[];
379
+ [entries sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
380
+ unsigned long long left = CCPetsTotalTokens(a[@"counts"]), right = CCPetsTotalTokens(b[@"counts"]);
381
+ return left == right ? NSOrderedSame : (left > right ? NSOrderedAscending : NSOrderedDescending);
382
+ }];
383
+ return entries;
384
+ }
385
+
386
+ - (void)render {
387
+ NSInteger rangeDays = [self rangeDays];
388
+ self.form.subtitleLabel.stringValue = [NSString stringWithFormat:L(@"Last %ld days · local session logs"),
389
+ (long)rangeDays];
390
+ [self.form removeAllContent];
391
+ self.legendItems = [NSMutableDictionary dictionary];
392
+ self.modelRows = [NSMutableDictionary dictionary];
393
+ if (!CCPetsUsageStore.results) {
394
+ // 还没算完:转圈的指示器已经在说明在算,别闪一下"没有数据"。
395
+ [self.form addFootnote:L(@"Reading local session logs…")];
396
+ return;
397
+ }
398
+ if (!self.colorSlots) [self computeColorSlots];
399
+ self.entries = [self entriesForRangeDays:rangeDays];
400
+ if (self.selectedKey && ![[self.entries valueForKey:@"key"] containsObject:self.selectedKey]) self.selectedKey = nil;
401
+
402
+ NSMutableDictionary *sum = SummedCounts([self.entries valueForKey:@"counts"]);
403
+ [self.form addView:[self kpiStripWithSum:sum rangeDays:rangeDays]];
404
+ [self.form addView:[self chartCardView]];
405
+ if (self.entries.count > 0) [self.form addView:[self modelTable]];
406
+ [self renderChart];
407
+ }
408
+
409
+ #pragma mark 指标条
410
+
411
+ // 五格和概览一样(同一个部件、同一套口径),只是总用量换成当前来源和区间的合计。
412
+ // 口径说明不占版面,挂在总用量标题后面的 ⓘ 上,悬停才显示。
413
+ - (NSView *)kpiStripWithSum:(NSDictionary *)sum rangeDays:(NSInteger)rangeDays {
414
+ NSString *title = [NSString stringWithFormat:L(@"Last %ld days · Total"), (long)rangeDays];
415
+ NSMutableArray<NSArray<NSString *> *> *items = [CCPetsUsageMetricItems(title, sum, self.entries.count) mutableCopy];
416
+ items[0] = [items[0] arrayByAddingObject:L(@"Total = input (excluding cache) + cache write + output + cached input. Codex counts cache hits inside input; they are subtracted here. Hit rate = cached input ÷ all input-side tokens.")];
417
+ NSView *row = CCPetsMetricRow(items);
418
+ CCPetsCardView *card = [CCPetsCardView new];
419
+ row.translatesAutoresizingMaskIntoConstraints = NO;
420
+ [card addSubview:row];
421
+ [NSLayoutConstraint activateConstraints:@[
422
+ [row.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
423
+ [row.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-16],
424
+ [row.topAnchor constraintEqualToAnchor:card.topAnchor constant:14],
425
+ [row.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-14],
426
+ ]];
427
+ return card;
428
+ }
429
+
430
+ #pragma mark 图表卡片
431
+
432
+ - (NSView *)chartCardView {
433
+ CCPetsCardView *card = [CCPetsCardView new];
434
+ self.chartTitle = CCPetsLabel(@"", 13, NSFontWeightSemibold, CCPetsInkColor());
435
+ self.chartHint = CCPetsLabel(@"", 11, NSFontWeightRegular, CCPetsTertiaryInkColor());
436
+ [self.chartHint setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
437
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
438
+ CCPetsUsageChartView *chart = [CCPetsUsageChartView new];
439
+ self.chart = chart;
440
+ CCPetsFlowView *legend = [CCPetsFlowView new];
441
+ legend.spacing = 4;
442
+ legend.lineSpacing = 2;
443
+ self.legend = legend;
444
+ NSView *rule = [CCPetsLineView new];
445
+ NSTextField *empty = nil;
446
+ if (self.entries.count == 0) {
447
+ empty = CCPetsLabel(L(@"No usage in this period."), 12, NSFontWeightRegular, CCPetsTertiaryInkColor());
448
+ }
449
+ NSMutableArray<NSView *> *views = [NSMutableArray arrayWithArray:@[self.chartTitle, self.chartHint,
450
+ self.metricControl, chart, rule, legend]];
451
+ if (empty) [views addObject:empty];
452
+ for (NSView *view in views) {
453
+ view.translatesAutoresizingMaskIntoConstraints = NO;
454
+ [card addSubview:view];
455
+ }
456
+ [NSLayoutConstraint activateConstraints:@[
457
+ [self.chartTitle.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
458
+ [self.chartTitle.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:14],
459
+ [self.chartTitle.trailingAnchor constraintLessThanOrEqualToAnchor:self.metricControl.leadingAnchor constant:-10],
460
+ [self.chartHint.topAnchor constraintEqualToAnchor:self.chartTitle.bottomAnchor constant:1],
461
+ [self.chartHint.leadingAnchor constraintEqualToAnchor:self.chartTitle.leadingAnchor],
462
+ [self.chartHint.trailingAnchor constraintLessThanOrEqualToAnchor:self.metricControl.leadingAnchor constant:-10],
463
+ [self.metricControl.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
464
+ [self.metricControl.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-14],
465
+ [chart.topAnchor constraintEqualToAnchor:self.chartHint.bottomAnchor constant:10],
466
+ [chart.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:8],
467
+ [chart.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-14],
468
+ [chart.heightAnchor constraintEqualToConstant:230],
469
+ [rule.topAnchor constraintEqualToAnchor:chart.bottomAnchor constant:8],
470
+ [rule.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:14],
471
+ [rule.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-14],
472
+ [rule.heightAnchor constraintEqualToConstant:1],
473
+ [legend.topAnchor constraintEqualToAnchor:rule.bottomAnchor constant:8],
474
+ [legend.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:10],
475
+ [legend.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-10],
476
+ [legend.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-10],
477
+ ]];
478
+ if (empty) {
479
+ [NSLayoutConstraint activateConstraints:@[
480
+ [empty.centerXAnchor constraintEqualToAnchor:chart.centerXAnchor],
481
+ [empty.centerYAnchor constraintEqualToAnchor:chart.centerYAnchor],
482
+ ]];
483
+ }
484
+ __weak typeof(self) weakSelf = self;
485
+ for (NSDictionary *entry in self.entries) {
486
+ NSString *key = entry[@"key"];
487
+ CCPetsLegendItem *item = [[CCPetsLegendItem alloc] initWithTitle:ModelTitle(entry[@"model"])
488
+ color:[self colorForKey:key]];
489
+ item.onClick = ^{ [weakSelf toggleModel:key]; };
490
+ item.toolTip = EntrySourceTitle(entry);
491
+ self.legendItems[key] = item;
492
+ [legend addSubview:item];
493
+ }
494
+ self.chartCard = card;
495
+ return card;
496
+ }
497
+
498
+ - (void)toggleModel:(NSString *)key {
499
+ self.selectedKey = [self.selectedKey isEqualToString:key] ? nil : key;
500
+ [self renderChart];
501
+ }
502
+
503
+ // 图表、图例、表格的选中态一起刷新;KPI 不跟着模型变,始终是当前来源和区间的总量。
504
+ - (void)renderChart {
505
+ UsageMetric metric = [self metric];
506
+ NSString *metricName = [NSString stringWithFormat:L(@"Daily %@"), MetricTitle(metric)];
507
+ NSDictionary *selected = nil;
508
+ for (NSDictionary *entry in self.entries) {
509
+ if ([entry[@"key"] isEqualToString:self.selectedKey]) selected = entry;
510
+ }
511
+ if (selected) {
512
+ self.chartTitle.stringValue = [NSString stringWithFormat:@"%@ · %@", ModelTitle(selected[@"model"]), metricName];
513
+ self.chartHint.stringValue = L(@"Click it again in the legend or the table to go back to all models.");
514
+ } else {
515
+ self.chartTitle.stringValue = metricName;
516
+ self.chartHint.stringValue = self.entries.count > 1
517
+ ? L(@"Stacked by model. Click a model below to see only that one.") : @"";
518
+ }
519
+
520
+ NSMutableArray<NSDictionary *> *series = [NSMutableArray array];
521
+ NSUInteger dayCount = self.dayStamps.count;
522
+ NSMutableArray<NSNumber *> *otherValues = nil;
523
+ for (NSDictionary *entry in self.entries) {
524
+ if (selected && entry != selected) continue;
525
+ NSString *key = entry[@"key"];
526
+ NSArray<NSDictionary *> *days = entry[@"days"];
527
+ // 不同来源的天数可能不一样长(某家这几天没数据),按右端对齐到同一条时间轴。
528
+ NSUInteger offset = dayCount > days.count ? dayCount - days.count : 0;
529
+ NSMutableArray<NSNumber *> *values = [NSMutableArray arrayWithCapacity:dayCount];
530
+ NSMutableArray<NSDictionary *> *counts = [NSMutableArray arrayWithCapacity:dayCount];
531
+ for (NSUInteger index = 0; index < dayCount; index++) {
532
+ NSDictionary *day = index >= offset ? days[index - offset] : @{};
533
+ [values addObject:@(MetricValue(metric, day))];
534
+ [counts addObject:day];
535
+ }
536
+ // 第 9 名以后合并成一层「其他」,颜色不够分也看不清。单看一个模型时不合并。
537
+ if (!selected && [self.colorSlots[key] integerValue] < 0) {
538
+ if (!otherValues) {
539
+ otherValues = [NSMutableArray arrayWithCapacity:dayCount];
540
+ for (NSUInteger index = 0; index < dayCount; index++) [otherValues addObject:@0];
541
+ }
542
+ for (NSUInteger index = 0; index < dayCount; index++) {
543
+ otherValues[index] = @(otherValues[index].unsignedLongLongValue + values[index].unsignedLongLongValue);
544
+ }
545
+ continue;
546
+ }
547
+ [series addObject:@{@"title": ModelTitle(entry[@"model"]), @"color": [self colorForKey:key],
548
+ @"values": values, @"counts": counts}];
549
+ }
550
+ if (otherValues) {
551
+ [series addObject:@{@"title": L(@"Other"), @"color": CCPetsChartColor(-1), @"values": otherValues, @"counts": @[]}];
552
+ }
553
+ self.chart.days = self.dayStamps;
554
+ self.chart.series = series;
555
+ self.chart.metric = metric;
556
+ self.chart.singleModel = selected != nil;
557
+ [self.chart reloadData];
558
+
559
+ [self.legendItems enumerateKeysAndObjectsUsingBlock:^(NSString *key, CCPetsLegendItem *item, BOOL *stop) {
560
+ item.selected = [key isEqualToString:self.selectedKey];
561
+ item.dimmed = self.selectedKey && !item.selected;
562
+ }];
563
+ [self.modelRows enumerateKeysAndObjectsUsingBlock:^(NSString *key, CCPetsUsageModelRow *row, BOOL *stop) {
564
+ row.selected = [key isEqualToString:self.selectedKey];
565
+ row.dimmed = self.selectedKey && !row.selected;
566
+ }];
567
+ }
568
+
569
+ #pragma mark 模型表
570
+
571
+ static const CGFloat ModelShareWidth = 130, ModelNumberWidth = 66, ModelRateWidth = 52, ModelNameMinimumWidth = 150;
572
+
573
+ - (NSView *)tableHeader {
574
+ NSView *header = [NSView new];
575
+ NSArray<NSArray *> *columns = @[@[L(@"Model"), @0], @[L(@"Share of Total"), @1], @[L(@"Total Usage"), @2],
576
+ @[L(@"Cached Input"), @3], @[L(@"Hit Rate"), @4], @[L(@"Requests"), @5]];
577
+ NSMutableArray<NSTextField *> *labels = [NSMutableArray array];
578
+ for (NSArray *column in columns) {
579
+ NSTextField *label = CCPetsLabel(column[0], 11, NSFontWeightSemibold, CCPetsTertiaryInkColor());
580
+ label.alignment = [column[1] integerValue] >= 2 ? NSTextAlignmentRight : NSTextAlignmentLeft;
581
+ label.translatesAutoresizingMaskIntoConstraints = NO;
582
+ [header addSubview:label];
583
+ [labels addObject:label];
584
+ }
585
+ [self layoutColumns:labels inRow:header];
586
+ [header.heightAnchor constraintEqualToConstant:30].active = YES;
587
+ return header;
588
+ }
589
+
590
+ // 六列:模型(自适应)、占比条、四列右对齐的数字。表头和每一行用同一套列宽。
591
+ - (void)layoutColumns:(NSArray<NSView *> *)cells inRow:(NSView *)row {
592
+ CGFloat widths[] = {0, ModelShareWidth, ModelNumberWidth, ModelNumberWidth, ModelRateWidth, ModelNumberWidth};
593
+ NSView *next = nil;
594
+ for (NSInteger index = (NSInteger)cells.count - 1; index >= 0; index--) {
595
+ NSView *cell = cells[(NSUInteger)index];
596
+ [cell.centerYAnchor constraintEqualToAnchor:row.centerYAnchor].active = YES;
597
+ if (next) [cell.trailingAnchor constraintEqualToAnchor:next.leadingAnchor constant:-12].active = YES;
598
+ else [cell.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:-14].active = YES;
599
+ if (index == 1) {
600
+ // 窗口窄时先让占比条变短,模型名留够宽度:名字才是这张表的主语。
601
+ NSLayoutConstraint *preferred = [cell.widthAnchor constraintEqualToConstant:widths[index]];
602
+ preferred.priority = NSLayoutPriorityDefaultLow;
603
+ [NSLayoutConstraint activateConstraints:@[preferred,
604
+ [cell.widthAnchor constraintGreaterThanOrEqualToConstant:44],
605
+ [cell.widthAnchor constraintLessThanOrEqualToConstant:widths[index]]]];
606
+ } else if (index > 0) {
607
+ [cell.widthAnchor constraintEqualToConstant:widths[index]].active = YES;
608
+ } else {
609
+ [cell.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:14].active = YES;
610
+ NSLayoutConstraint *minimum = [cell.widthAnchor constraintGreaterThanOrEqualToConstant:ModelNameMinimumWidth];
611
+ minimum.priority = NSLayoutPriorityDefaultHigh;
612
+ minimum.active = YES;
613
+ }
614
+ next = cell;
615
+ }
616
+ }
617
+
618
+ - (NSView *)modelTable {
619
+ NSStackView *stack = [NSStackView stackViewWithViews:@[]];
620
+ stack.orientation = NSUserInterfaceLayoutOrientationVertical;
621
+ stack.spacing = 0;
622
+ stack.translatesAutoresizingMaskIntoConstraints = NO;
623
+ NSView *header = [self tableHeader];
624
+ [stack addArrangedSubview:header];
625
+ [header.widthAnchor constraintEqualToAnchor:stack.widthAnchor].active = YES;
626
+ unsigned long long totalNew = 0, maxNew = 1;
627
+ for (NSDictionary *entry in self.entries) {
628
+ totalNew += CCPetsTotalTokens(entry[@"counts"]);
629
+ maxNew = MAX(maxNew, CCPetsTotalTokens(entry[@"counts"]));
630
+ }
631
+ __weak typeof(self) weakSelf = self;
632
+ for (NSDictionary *entry in self.entries) {
633
+ NSView *rule = [CCPetsFormBuilder separator];
634
+ [stack addArrangedSubview:rule];
635
+ [rule.widthAnchor constraintEqualToAnchor:stack.widthAnchor].active = YES;
636
+ CCPetsUsageModelRow *row = [self rowForEntry:entry totalNew:totalNew maxNew:maxNew];
637
+ NSString *key = entry[@"key"];
638
+ row.onClick = ^{ [weakSelf toggleModel:key]; };
639
+ self.modelRows[key] = row;
640
+ [stack addArrangedSubview:row];
641
+ [row.widthAnchor constraintEqualToAnchor:stack.widthAnchor].active = YES;
642
+ }
643
+ CCPetsCardView *card = [CCPetsCardView new];
644
+ [card addSubview:stack];
645
+ [NSLayoutConstraint activateConstraints:@[
646
+ [stack.leadingAnchor constraintEqualToAnchor:card.leadingAnchor],
647
+ [stack.trailingAnchor constraintEqualToAnchor:card.trailingAnchor],
648
+ [stack.topAnchor constraintEqualToAnchor:card.topAnchor],
649
+ [stack.bottomAnchor constraintEqualToAnchor:card.bottomAnchor],
650
+ ]];
651
+ self.tableCard = card;
652
+ return card;
653
+ }
654
+
655
+ - (CCPetsUsageModelRow *)rowForEntry:(NSDictionary *)entry totalNew:(unsigned long long)totalNew
656
+ maxNew:(unsigned long long)maxNew {
657
+ NSDictionary *counts = entry[@"counts"];
658
+ NSColor *color = [self colorForKey:entry[@"key"]];
659
+ unsigned long long newTokens = CCPetsTotalTokens(counts);
660
+
661
+ CCPetsColorDot *swatch = [[CCPetsColorDot alloc] initWithColor:color diameter:8];
662
+ NSTextField *name = CCPetsLabel(ModelTitle(entry[@"model"]), 12, NSFontWeightSemibold, CCPetsInkColor());
663
+ name.font = [NSFont monospacedSystemFontOfSize:12 weight:NSFontWeightSemibold];
664
+ name.lineBreakMode = NSLineBreakByTruncatingMiddle;
665
+ [name setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
666
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
667
+ NSStackView *nameLine = [NSStackView stackViewWithViews:@[swatch, name]];
668
+ nameLine.spacing = 6;
669
+ nameLine.alignment = NSLayoutAttributeCenterY;
670
+ NSTextField *provider = CCPetsLabel(EntrySourceTitle(entry), 11, NSFontWeightRegular, CCPetsTertiaryInkColor());
671
+ NSStackView *nameCell = [NSStackView stackViewWithViews:@[nameLine, provider]];
672
+ nameCell.orientation = NSUserInterfaceLayoutOrientationVertical;
673
+ nameCell.alignment = NSLayoutAttributeLeading;
674
+ nameCell.spacing = 1;
675
+ [provider.leadingAnchor constraintEqualToAnchor:name.leadingAnchor].active = YES;
676
+ [nameCell setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
677
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
678
+
679
+ CCPetsShareBar *bar = [CCPetsShareBar new];
680
+ bar.fraction = (double)newTokens / maxNew;
681
+ bar.color = color;
682
+ bar.translatesAutoresizingMaskIntoConstraints = NO;
683
+ [bar.heightAnchor constraintEqualToConstant:4].active = YES;
684
+ NSTextField *percent = CCPetsNumberLabel(totalNew > 0
685
+ ? [NSString stringWithFormat:@"%.0f%%", 100.0 * newTokens / totalNew] : @"–",
686
+ 10, NSFontWeightRegular, CCPetsTertiaryInkColor());
687
+ NSStackView *shareCell = [NSStackView stackViewWithViews:@[bar, percent]];
688
+ shareCell.orientation = NSUserInterfaceLayoutOrientationVertical;
689
+ shareCell.alignment = NSLayoutAttributeLeading;
690
+ shareCell.spacing = 3;
691
+ [bar.widthAnchor constraintEqualToAnchor:shareCell.widthAnchor multiplier:0.86].active = YES;
692
+
693
+ NSTextField *newLabel = CCPetsNumberLabel(CCPetsFormatTokens(newTokens), 12, NSFontWeightRegular, CCPetsInkColor());
694
+ newLabel.toolTip = FormatCount(newTokens);
695
+ NSTextField *readLabel = CCPetsNumberLabel(CCPetsFormatTokens(Count(counts, @"cacheRead")), 12,
696
+ NSFontWeightRegular, CCPetsInkColor());
697
+ readLabel.toolTip = FormatCount(Count(counts, @"cacheRead"));
698
+ NSTextField *rateLabel = CCPetsNumberLabel(HitRateText(counts), 12, NSFontWeightRegular, CCPetsInkColor());
699
+ NSTextField *requestLabel = CCPetsNumberLabel(FormatCount(Count(counts, @"requests")), 12,
700
+ NSFontWeightRegular, CCPetsInkColor());
701
+ for (NSTextField *label in @[newLabel, readLabel, rateLabel, requestLabel]) label.alignment = NSTextAlignmentRight;
702
+
703
+ CCPetsUsageModelRow *row = [[CCPetsUsageModelRow alloc] initWithFrame:NSZeroRect];
704
+ NSArray<NSView *> *cells = @[nameCell, shareCell, newLabel, readLabel, rateLabel, requestLabel];
705
+ for (NSView *cell in cells) {
706
+ cell.translatesAutoresizingMaskIntoConstraints = NO;
707
+ [row addSubview:cell];
708
+ }
709
+ [self layoutColumns:cells inRow:row];
710
+ [row.heightAnchor constraintEqualToConstant:46].active = YES;
711
+ row.toolTip = [NSString stringWithFormat:@"%@ %@ · %@ %@ · %@ %@", L(@"Input"),
712
+ CCPetsFormatTokens(Count(counts, @"input")), L(@"Cache Write"), CCPetsFormatTokens(Count(counts, @"cacheWrite")),
713
+ L(@"Output"), CCPetsFormatTokens(Count(counts, @"output"))];
714
+ return row;
715
+ }
716
+
717
+ @end