cc-pets 2.3.0 → 2.4.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.
- package/CC_BRIDGE.md +19 -0
- package/CC_BRIDGE.zh-CN.md +15 -0
- package/CHANGELOG.md +51 -0
- package/CHANGELOG.zh-CN.md +51 -0
- package/CONTRIBUTING.md +22 -0
- package/CONTRIBUTING.zh-CN.md +17 -0
- package/README.md +117 -26
- package/README.zh-CN.md +92 -22
- package/Resources/AgentIcons/claude.png +0 -0
- package/Resources/AgentIcons/codex.icns +0 -0
- package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
- package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
- package/Resources/zh-Hans.lproj/Localizable.strings +155 -27
- package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +12 -6
- package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +1 -1
- package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +3 -6
- package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +113 -47
- package/Sources/CCPets/App/CCPetsAppDelegate.h +2 -2
- package/Sources/CCPets/App/main.m +6 -0
- package/Sources/CCPets/Bridge/CCPetsBridge.m +11 -6
- package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +78 -38
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +2 -3
- package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +50 -32
- package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +46 -40
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +9 -6
- package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +171 -53
- package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
- package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
- package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
- package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
- package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +2 -1
- package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +107 -25
- package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
- package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
- package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
- package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
- package/Sources/CCPets/Pet/PetView+Menu.m +2 -2
- package/Sources/CCPets/Support/CCPetsDoctor.m +26 -12
- package/Sources/CCPets/Support/CCPetsPreferences.h +2 -0
- package/Sources/CCPets/Support/CCPetsPreferences.m +34 -2
- package/Sources/CCPets/UI/CCPetsFormBuilder.h +2 -0
- package/Sources/CCPets/UI/CCPetsFormBuilder.m +18 -7
- package/Sources/CCPets/UI/CCPetsGlassView.h +26 -4
- package/Sources/CCPets/UI/CCPetsGlassView.m +40 -9
- package/Sources/CCPets/UI/CCPetsSettingsPage.h +2 -0
- package/Sources/CCPets/UI/CCPetsSettingsPage.m +561 -66
- package/Sources/CCPets/UI/CCPetsUIStyle.h +5 -2
- package/Sources/CCPets/UI/CCPetsUIStyle.m +57 -8
- package/Sources/CCPets/UI/CCPetsUsageChartView.m +4 -0
- package/Sources/CCPets/UI/CCPetsUsagePage.m +23 -28
- package/Sources/CCPets/UI/CCPetsUsageStore.m +2 -2
- package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +1 -0
- package/Sources/CCPets/Usage/CCPetsUsage+Models.m +49 -11
- package/Sources/CCPets/Usage/CCPetsUsage.h +3 -2
- package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +15 -17
- package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +11 -29
- package/Sources/CCPets/Usage/QuotaDashboardView.m +128 -2
- package/THIRD_PARTY_NOTICES.md +7 -3
- package/THIRD_PARTY_NOTICES.zh-CN.md +5 -1
- package/bin/claude-with-pet +2 -0
- package/bin/codex-with-pet +2 -0
- package/package.json +5 -1
- package/plugins/jetbrains/README.md +62 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
- package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
- package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
- package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
- package/plugins/vscode/README.md +63 -0
- package/plugins/vscode/extension.js +210 -0
- package/plugins/vscode/package.json +18 -0
- package/scripts/build-idea-plugin.sh +101 -0
- package/scripts/build-vscode-extension.sh +112 -0
- package/scripts/build.sh +24 -2
- package/scripts/compile-cached.zsh +133 -0
|
@@ -42,8 +42,7 @@ NSColor *CCPetsStatusBackgroundColor(CCPetsStatusKind kind);
|
|
|
42
42
|
// Agent 状态(thinking / approval / failed …)归到哪一类。
|
|
43
43
|
CCPetsStatusKind CCPetsStatusKindForAgentState(NSString *state);
|
|
44
44
|
|
|
45
|
-
//
|
|
46
|
-
// 顺序就是色盲安全的保证(相邻两色在三类色盲下都分得开),不要重排。
|
|
45
|
+
// 图表模型色板:前 16 色固定,更多槽位生成颜色;负数表示未知模型的灰色。
|
|
47
46
|
NSColor *CCPetsChartColor(NSInteger slot);
|
|
48
47
|
extern const NSInteger CCPetsChartColorCount;
|
|
49
48
|
|
|
@@ -71,6 +70,10 @@ NSTextField *CCPetsWrappingLabel(NSString *text, CGFloat size, NSFontWeight weig
|
|
|
71
70
|
// 可点的卡片:整张卡片是一个按钮。onClick 为 nil 时不响应。
|
|
72
71
|
@interface CCPetsTileView : CCPetsCardView
|
|
73
72
|
@property(nonatomic, copy) void (^onClick)(void);
|
|
73
|
+
// 这块区域(整行宽)里是控件,不显示手形指针。
|
|
74
|
+
@property(nonatomic, weak) NSView *cursorExclusionView;
|
|
75
|
+
// 只在鼠标停在卡片上时显示的附属控件(比如删除按钮),必须是卡片的子视图。
|
|
76
|
+
@property(nonatomic, weak) NSView *hoverAccessoryView;
|
|
74
77
|
@end
|
|
75
78
|
|
|
76
79
|
// 填色胶囊按钮:悬停面板「订阅 / 用量」那种一点就切换的开关,和右键菜单里的样子一致。
|
|
@@ -79,16 +79,16 @@ CCPetsStatusKind CCPetsStatusKindForAgentState(NSString *state) {
|
|
|
79
79
|
return CCPetsStatusWork;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
const NSInteger CCPetsChartColorCount =
|
|
82
|
+
const NSInteger CCPetsChartColorCount = 16;
|
|
83
83
|
|
|
84
|
-
//
|
|
84
|
+
// 保留原有八色,扩展常用模型色板;更多模型按色相生成颜色。
|
|
85
85
|
NSColor *CCPetsChartColor(NSInteger slot) {
|
|
86
86
|
static NSArray<NSColor *> *colors;
|
|
87
87
|
static NSColor *other;
|
|
88
88
|
static dispatch_once_t once;
|
|
89
89
|
dispatch_once(&once, ^{
|
|
90
|
-
const uint32_t light[] = {0x1597ac, 0xe05c86, 0x6874dc, 0xdd9a1f, 0x9a62d0, 0x3fa577, 0x3a7fc6, 0x8a9a2b};
|
|
91
|
-
const uint32_t dark[] = {0x22a2b8, 0xd65f86, 0x7d87e8, 0xb8841f, 0xa77ad8, 0x3fa577, 0x4c95dc, 0x879733};
|
|
90
|
+
const uint32_t light[] = {0x1597ac, 0xe05c86, 0x6874dc, 0xdd9a1f, 0x9a62d0, 0x3fa577, 0x3a7fc6, 0x8a9a2b, 0xc96b32, 0x258477, 0xb24baf, 0x5266a8, 0xb84c4c, 0x657d34, 0x9b6881, 0x397c99};
|
|
91
|
+
const uint32_t dark[] = {0x22a2b8, 0xd65f86, 0x7d87e8, 0xb8841f, 0xa77ad8, 0x3fa577, 0x4c95dc, 0x879733, 0xec965e, 0x68c5b5, 0xe18bd9, 0xa2b2f0, 0xef8b88, 0xb6c96c, 0xc997b0, 0x80c4df};
|
|
92
92
|
NSMutableArray<NSColor *> *list = [NSMutableArray array];
|
|
93
93
|
for (NSInteger index = 0; index < CCPetsChartColorCount; index++) {
|
|
94
94
|
[list addObject:Dynamic(light[index], 1, dark[index], 1)];
|
|
@@ -96,7 +96,14 @@ NSColor *CCPetsChartColor(NSInteger slot) {
|
|
|
96
96
|
colors = list;
|
|
97
97
|
other = Dynamic(0x9aa3af, 1, 0x66707c, 1);
|
|
98
98
|
});
|
|
99
|
-
|
|
99
|
+
if (slot < 0) return other;
|
|
100
|
+
if (slot < CCPetsChartColorCount) return colors[(NSUInteger)slot];
|
|
101
|
+
CGFloat hue = fmod((slot - CCPetsChartColorCount) * 0.61803398875 + 0.05, 1.0);
|
|
102
|
+
return [NSColor colorWithName:nil dynamicProvider:^NSColor *(NSAppearance *appearance) {
|
|
103
|
+
BOOL dark = AppearanceIsDark(appearance);
|
|
104
|
+
return [NSColor colorWithHue:hue saturation:dark ? 0.48 : 0.65
|
|
105
|
+
brightness:dark ? 0.85 : 0.65 alpha:1];
|
|
106
|
+
}];
|
|
100
107
|
}
|
|
101
108
|
|
|
102
109
|
NSTextField *CCPetsLabel(NSString *text, CGFloat size, NSFontWeight weight, NSColor *color) {
|
|
@@ -145,12 +152,13 @@ NSView *CCPetsMetricRow(NSArray<NSArray<NSString *> *> *items) {
|
|
|
145
152
|
NSFontWeightRegular, CCPetsTertiaryInkColor());
|
|
146
153
|
NSView *heading = title;
|
|
147
154
|
if (item.count > 3 && item[3].length > 0) {
|
|
148
|
-
NSImageView *icon = [NSImageView
|
|
149
|
-
|
|
155
|
+
NSImageView *icon = [NSImageView new];
|
|
156
|
+
icon.image = [NSImage imageWithSystemSymbolName:@"info.circle" accessibilityDescription:item[3]];
|
|
150
157
|
icon.symbolConfiguration = [NSImageSymbolConfiguration configurationWithPointSize:10
|
|
151
158
|
weight:NSFontWeightRegular];
|
|
152
159
|
icon.contentTintColor = CCPetsTertiaryInkColor();
|
|
153
160
|
icon.toolTip = item[3];
|
|
161
|
+
icon.accessibilityHelp = item[3];
|
|
154
162
|
[icon setContentHuggingPriority:NSLayoutPriorityRequired
|
|
155
163
|
forOrientation:NSLayoutConstraintOrientationHorizontal];
|
|
156
164
|
NSStackView *line = [NSStackView stackViewWithViews:@[title, icon]];
|
|
@@ -274,8 +282,37 @@ NSView *CCPetsMetricRow(NSArray<NSArray<NSString *> *> *items) {
|
|
|
274
282
|
|
|
275
283
|
@end
|
|
276
284
|
|
|
285
|
+
@interface CCPetsTileView ()
|
|
286
|
+
@property(nonatomic) NSTrackingArea *hoverTracking;
|
|
287
|
+
@end
|
|
288
|
+
|
|
277
289
|
@implementation CCPetsTileView
|
|
278
290
|
|
|
291
|
+
- (void)setHoverAccessoryView:(NSView *)view {
|
|
292
|
+
_hoverAccessoryView = view;
|
|
293
|
+
view.hidden = YES;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
- (void)updateTrackingAreas {
|
|
297
|
+
[super updateTrackingAreas];
|
|
298
|
+
if (self.hoverTracking) [self removeTrackingArea:self.hoverTracking];
|
|
299
|
+
self.hoverTracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect
|
|
300
|
+
options:NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect
|
|
301
|
+
owner:self userInfo:nil];
|
|
302
|
+
[self addTrackingArea:self.hoverTracking];
|
|
303
|
+
// 卡片重排后鼠标可能已经不在上面,按实际位置校正一次。
|
|
304
|
+
NSPoint mouse = [self convertPoint:self.window.mouseLocationOutsideOfEventStream fromView:nil];
|
|
305
|
+
self.hoverAccessoryView.hidden = !(self.window && NSPointInRect(mouse, self.bounds));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
- (void)mouseEntered:(NSEvent *)event {
|
|
309
|
+
self.hoverAccessoryView.hidden = NO;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
- (void)mouseExited:(NSEvent *)event {
|
|
313
|
+
self.hoverAccessoryView.hidden = YES;
|
|
314
|
+
}
|
|
315
|
+
|
|
279
316
|
- (void)mouseDown:(NSEvent *)event {
|
|
280
317
|
// 按下不立刻触发,松开时还在卡片上才算一次点击,和按钮一个手感。
|
|
281
318
|
}
|
|
@@ -290,7 +327,19 @@ NSView *CCPetsMetricRow(NSArray<NSArray<NSString *> *> *items) {
|
|
|
290
327
|
}
|
|
291
328
|
|
|
292
329
|
- (void)resetCursorRects {
|
|
293
|
-
if (self.onClick)
|
|
330
|
+
if (!self.onClick) return;
|
|
331
|
+
NSView *excluded = self.cursorExclusionView;
|
|
332
|
+
if (!excluded || excluded.superview != self) {
|
|
333
|
+
[self addCursorRect:self.bounds cursor:NSCursor.pointingHandCursor];
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
// 排除区域按整行宽处理:只给它上方和下方的部分加手形指针。
|
|
337
|
+
NSRect frame = excluded.frame;
|
|
338
|
+
NSRect below = NSMakeRect(0, 0, NSWidth(self.bounds), NSMinY(frame));
|
|
339
|
+
NSRect above = NSMakeRect(0, NSMaxY(frame), NSWidth(self.bounds), NSMaxY(self.bounds) - NSMaxY(frame));
|
|
340
|
+
for (NSValue *value in @[[NSValue valueWithRect:below], [NSValue valueWithRect:above]]) {
|
|
341
|
+
if (!NSIsEmptyRect(value.rectValue)) [self addCursorRect:value.rectValue cursor:NSCursor.pointingHandCursor];
|
|
342
|
+
}
|
|
294
343
|
}
|
|
295
344
|
|
|
296
345
|
- (BOOL)isAccessibilityElement {
|
|
@@ -161,6 +161,10 @@ static double NiceStep(double peak) {
|
|
|
161
161
|
[rows addObject:@{@"title": part[0], @"value": CCPetsFormatTokens(Count(counts, part[1])), @"color": color}];
|
|
162
162
|
}
|
|
163
163
|
[rows addObject:@{@"title": L(@"Requests"), @"value": FormatCount(Count(counts, @"requests")), @"color": color}];
|
|
164
|
+
if (Count(counts, @"background") > 0) {
|
|
165
|
+
[rows addObject:@{@"title": L(@"Background (breakdown unavailable)"),
|
|
166
|
+
@"value": CCPetsFormatTokens(Count(counts, @"background")), @"color": color}];
|
|
167
|
+
}
|
|
164
168
|
} else {
|
|
165
169
|
NSMutableArray<NSDictionary *> *layers = [NSMutableArray array];
|
|
166
170
|
for (NSDictionary *layer in self.series) {
|
|
@@ -56,7 +56,7 @@ static NSString *ModelTitle(NSString *model) {
|
|
|
56
56
|
static NSMutableDictionary *SummedCounts(NSArray<NSDictionary *> *list) {
|
|
57
57
|
NSMutableDictionary *sum = [NSMutableDictionary dictionary];
|
|
58
58
|
for (NSDictionary *counts in list) {
|
|
59
|
-
for (NSString *key in @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests"]) {
|
|
59
|
+
for (NSString *key in @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests", @"background"]) {
|
|
60
60
|
sum[key] = @(Count(sum, key) + Count(counts, key));
|
|
61
61
|
}
|
|
62
62
|
}
|
|
@@ -77,11 +77,15 @@ NSArray<NSArray<NSString *> *> *CCPetsUsageMetricItems(NSString *totalTitle, NSD
|
|
|
77
77
|
unsigned long long input = Count(sum, @"input"), write = Count(sum, @"cacheWrite");
|
|
78
78
|
unsigned long long output = Count(sum, @"output"), read = Count(sum, @"cacheRead");
|
|
79
79
|
unsigned long long side = input + write + read;
|
|
80
|
+
unsigned long long background = Count(sum, @"background");
|
|
81
|
+
NSMutableArray<NSString *> *notes = [NSMutableArray array];
|
|
82
|
+
if (write > 0) [notes addObject:[NSString stringWithFormat:L(@"Includes %@ cache write"), CCPetsFormatTokens(write)]];
|
|
83
|
+
if (background > 0) [notes addObject:[NSString stringWithFormat:L(@"Background %@ · breakdown unavailable"), CCPetsFormatTokens(background)]];
|
|
80
84
|
NSString *hit = side > 0 ? [NSString stringWithFormat:L(@"Hit rate %.0f%%"), 100.0 * read / side]
|
|
81
85
|
: L(@"No cache reads yet");
|
|
82
86
|
return @[
|
|
83
|
-
@[totalTitle, CCPetsFormatTokens(CCPetsTotalTokens(sum)),
|
|
84
|
-
? [
|
|
87
|
+
@[totalTitle, CCPetsFormatTokens(CCPetsTotalTokens(sum)), notes.count > 0
|
|
88
|
+
? [notes componentsJoinedByString:@" · "] : L(@"All tokens")],
|
|
85
89
|
@[L(@"Input"), CCPetsFormatTokens(input), L(@"Excluding cache")],
|
|
86
90
|
@[L(@"Output"), CCPetsFormatTokens(output), L(@"Generated by the model")],
|
|
87
91
|
@[L(@"Cached Input"), CCPetsFormatTokens(read), hit],
|
|
@@ -120,7 +124,7 @@ static const NSTimeInterval UsagePageRefreshInterval = 60;
|
|
|
120
124
|
// 当前筛选下的模型条目:key、provider、model、counts(区间合计)、days(每天的 counts)。按总用量从大到小。
|
|
121
125
|
@property(nonatomic) NSArray<NSDictionary *> *entries;
|
|
122
126
|
// 模型 -> 色板位置。按 90 天、全部来源的总用量排序分配,之后切来源、区间、指标都不重新上色:
|
|
123
|
-
//
|
|
127
|
+
// 颜色跟着模型走,不跟着名次走。数据重载时已有模型保留原色,见 computeColorSlots。
|
|
124
128
|
@property(nonatomic) NSDictionary<NSString *, NSNumber *> *colorSlots;
|
|
125
129
|
// 选中的模型 key;nil 是全部模型。
|
|
126
130
|
@property(nonatomic, copy) NSString *selectedKey;
|
|
@@ -316,10 +320,9 @@ static const NSTimeInterval UsagePageRefreshInterval = 60;
|
|
|
316
320
|
NSArray<NSString *> *ranked = [totals keysSortedByValueUsingComparator:^NSComparisonResult(NSNumber *a, NSNumber *b) {
|
|
317
321
|
return [b compare:a];
|
|
318
322
|
}];
|
|
319
|
-
NSUInteger colored = MIN(ranked.count, (NSUInteger)CCPetsChartColorCount);
|
|
320
323
|
NSMutableDictionary<NSString *, NSNumber *> *slots = [NSMutableDictionary dictionary];
|
|
321
324
|
NSMutableIndexSet *taken = [NSMutableIndexSet indexSet];
|
|
322
|
-
for (NSUInteger index = 0; index <
|
|
325
|
+
for (NSUInteger index = 0; index < ranked.count; index++) {
|
|
323
326
|
NSInteger previous = self.colorSlots[ranked[index]] ? self.colorSlots[ranked[index]].integerValue : -1;
|
|
324
327
|
if (previous < 0) continue;
|
|
325
328
|
slots[ranked[index]] = @(previous);
|
|
@@ -328,10 +331,6 @@ static const NSTimeInterval UsagePageRefreshInterval = 60;
|
|
|
328
331
|
NSUInteger next = 0;
|
|
329
332
|
for (NSUInteger index = 0; index < ranked.count; index++) {
|
|
330
333
|
if (slots[ranked[index]]) continue;
|
|
331
|
-
if (index >= colored) {
|
|
332
|
-
slots[ranked[index]] = @(-1);
|
|
333
|
-
continue;
|
|
334
|
-
}
|
|
335
334
|
while ([taken containsIndex:next]) next++;
|
|
336
335
|
slots[ranked[index]] = @((NSInteger)next);
|
|
337
336
|
[taken addIndex:next];
|
|
@@ -385,7 +384,7 @@ static const NSTimeInterval UsagePageRefreshInterval = 60;
|
|
|
385
384
|
|
|
386
385
|
- (void)render {
|
|
387
386
|
NSInteger rangeDays = [self rangeDays];
|
|
388
|
-
self.form.subtitleLabel.stringValue = [NSString stringWithFormat:L(@"Last %ld days · local
|
|
387
|
+
self.form.subtitleLabel.stringValue = [NSString stringWithFormat:L(@"Last %ld days · local usage logs"),
|
|
389
388
|
(long)rangeDays];
|
|
390
389
|
[self.form removeAllContent];
|
|
391
390
|
self.legendItems = [NSMutableDictionary dictionary];
|
|
@@ -401,6 +400,9 @@ static const NSTimeInterval UsagePageRefreshInterval = 60;
|
|
|
401
400
|
|
|
402
401
|
NSMutableDictionary *sum = SummedCounts([self.entries valueForKey:@"counts"]);
|
|
403
402
|
[self.form addView:[self kpiStripWithSum:sum rangeDays:rangeDays]];
|
|
403
|
+
if (Count(sum, @"background") > 0) {
|
|
404
|
+
[self.form addFootnote:L(@"Background usage is included in the total. Its input, output and cache breakdown is unavailable; the corresponding metrics cover recorded details only.")];
|
|
405
|
+
}
|
|
404
406
|
[self.form addView:[self chartCardView]];
|
|
405
407
|
if (self.entries.count > 0) [self.form addView:[self modelTable]];
|
|
406
408
|
[self renderChart];
|
|
@@ -409,11 +411,14 @@ static const NSTimeInterval UsagePageRefreshInterval = 60;
|
|
|
409
411
|
#pragma mark 指标条
|
|
410
412
|
|
|
411
413
|
// 五格和概览一样(同一个部件、同一套口径),只是总用量换成当前来源和区间的合计。
|
|
412
|
-
//
|
|
414
|
+
// 缓存写入和后台用量只在总用量标题后的 ⓘ 悬停展示,不在数字下方重复显示。
|
|
413
415
|
- (NSView *)kpiStripWithSum:(NSDictionary *)sum rangeDays:(NSInteger)rangeDays {
|
|
414
416
|
NSString *title = [NSString stringWithFormat:L(@"Last %ld days · Total"), (long)rangeDays];
|
|
415
417
|
NSMutableArray<NSArray<NSString *> *> *items = [CCPetsUsageMetricItems(title, sum, self.entries.count) mutableCopy];
|
|
416
|
-
|
|
418
|
+
NSString *details = [NSString stringWithFormat:@"%@\n%@",
|
|
419
|
+
[NSString stringWithFormat:L(@"Includes cached input %@"), CCPetsFormatTokens(Count(sum, @"cacheWrite"))],
|
|
420
|
+
[NSString stringWithFormat:L(@"Background usage %@"), CCPetsFormatTokens(Count(sum, @"background"))]];
|
|
421
|
+
items[0] = @[items[0][0], items[0][1], L(@"All tokens"), details];
|
|
417
422
|
NSView *row = CCPetsMetricRow(items);
|
|
418
423
|
CCPetsCardView *card = [CCPetsCardView new];
|
|
419
424
|
row.translatesAutoresizingMaskIntoConstraints = NO;
|
|
@@ -519,7 +524,6 @@ static const NSTimeInterval UsagePageRefreshInterval = 60;
|
|
|
519
524
|
|
|
520
525
|
NSMutableArray<NSDictionary *> *series = [NSMutableArray array];
|
|
521
526
|
NSUInteger dayCount = self.dayStamps.count;
|
|
522
|
-
NSMutableArray<NSNumber *> *otherValues = nil;
|
|
523
527
|
for (NSDictionary *entry in self.entries) {
|
|
524
528
|
if (selected && entry != selected) continue;
|
|
525
529
|
NSString *key = entry[@"key"];
|
|
@@ -533,23 +537,9 @@ static const NSTimeInterval UsagePageRefreshInterval = 60;
|
|
|
533
537
|
[values addObject:@(MetricValue(metric, day))];
|
|
534
538
|
[counts addObject:day];
|
|
535
539
|
}
|
|
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
540
|
[series addObject:@{@"title": ModelTitle(entry[@"model"]), @"color": [self colorForKey:key],
|
|
548
541
|
@"values": values, @"counts": counts}];
|
|
549
542
|
}
|
|
550
|
-
if (otherValues) {
|
|
551
|
-
[series addObject:@{@"title": L(@"Other"), @"color": CCPetsChartColor(-1), @"values": otherValues, @"counts": @[]}];
|
|
552
|
-
}
|
|
553
543
|
self.chart.days = self.dayStamps;
|
|
554
544
|
self.chart.series = series;
|
|
555
545
|
self.chart.metric = metric;
|
|
@@ -711,6 +701,11 @@ static const CGFloat ModelShareWidth = 130, ModelNumberWidth = 66, ModelRateWidt
|
|
|
711
701
|
row.toolTip = [NSString stringWithFormat:@"%@ %@ · %@ %@ · %@ %@", L(@"Input"),
|
|
712
702
|
CCPetsFormatTokens(Count(counts, @"input")), L(@"Cache Write"), CCPetsFormatTokens(Count(counts, @"cacheWrite")),
|
|
713
703
|
L(@"Output"), CCPetsFormatTokens(Count(counts, @"output"))];
|
|
704
|
+
if (Count(counts, @"background") > 0) {
|
|
705
|
+
row.toolTip = [row.toolTip stringByAppendingFormat:@"\n%@",
|
|
706
|
+
[NSString stringWithFormat:L(@"Background %@ · breakdown unavailable"),
|
|
707
|
+
CCPetsFormatTokens(Count(counts, @"background"))]];
|
|
708
|
+
}
|
|
714
709
|
return row;
|
|
715
710
|
}
|
|
716
711
|
|
|
@@ -42,7 +42,7 @@ static NSDictionary *MergeModelUsageResults(NSArray<NSDictionary *> *values) {
|
|
|
42
42
|
NSMutableDictionary *counts = models[model];
|
|
43
43
|
if (!counts) { counts = [NSMutableDictionary dictionary]; models[model] = counts; }
|
|
44
44
|
NSDictionary *incoming = day[@"models"][model];
|
|
45
|
-
for (NSString *key in @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests"]) {
|
|
45
|
+
for (NSString *key in @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests", @"background"]) {
|
|
46
46
|
counts[key] = @(Count(counts, key) + Count(incoming, key));
|
|
47
47
|
}
|
|
48
48
|
}
|
|
@@ -55,7 +55,7 @@ static NSDictionary *MergeModelUsageResults(NSArray<NSDictionary *> *values) {
|
|
|
55
55
|
for (NSString *model in models) {
|
|
56
56
|
NSMutableDictionary *sum = totals[model];
|
|
57
57
|
if (!sum) { sum = [NSMutableDictionary dictionary]; totals[model] = sum; }
|
|
58
|
-
for (NSString *key in @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests"]) {
|
|
58
|
+
for (NSString *key in @[@"input", @"cacheRead", @"cacheWrite", @"output", @"reasoning", @"requests", @"background"]) {
|
|
59
59
|
sum[key] = @(Count(sum, key) + Count(models[model], key));
|
|
60
60
|
}
|
|
61
61
|
}
|
|
@@ -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
|
|
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
|
-
//
|
|
14
|
-
//
|
|
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
|
-
|
|
41
|
-
|
|
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
|
-
|
|
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];
|