cc-pets 1.0.9 → 1.1.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/CHANGELOG.md +8 -2
- package/README.md +7 -4
- package/Sources/CCPets/CCPetsAppDelegate.h +1 -3
- package/Sources/CCPets/CCPetsAppDelegate.m +55 -87
- package/Sources/CCPets/CCPetsEvents.m +10 -0
- package/Sources/CCPets/CCPetsPaths.h +2 -0
- package/Sources/CCPets/CCPetsPaths.m +9 -0
- package/Sources/CCPets/CCPetsQuotaHistory.m +6 -0
- package/Sources/CCPets/CCPetsUsage.m +188 -55
- package/Sources/CCPets/PetView.h +1 -2
- package/Sources/CCPets/PetView.m +45 -25
- package/Sources/CCPets/QuotaDashboardView.m +96 -58
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
- Token 聚合改为增量跟读并按额度窗口节流,事件驱动的高频刷新不再重复扫描近 7 天会话;
|
|
11
11
|
过期日期目录按目录名剪枝,无 Token 数据的会话文件缓存失败结果不再反复重读。
|
|
12
12
|
- 新开 Codex 会话时不再因为尚无 `rate_limits` 而清空面板上已知的额度。
|
|
13
|
+
- 修正跨窗口 Codex 会话的 Token 高估:Codex 会把同一份 `token_count` 重复写进会话
|
|
14
|
+
(实测近 7 天 68 个会话里 14 个存在重复,累加值整体偏高约 1%,最差的单个会话偏高
|
|
15
|
+
7.7%),窗口内那一段改为按 `total_token_usage` 求差,累计值对重复事件是幂等的。
|
|
16
|
+
- 桌宠端不再跟随继承来的 `CODEX_HOME`,与 `CLAUDE_CONFIG_DIR` 的处理对齐:常驻进程会一直
|
|
17
|
+
带着启动时的环境,用它选目录等于永久绑定到第一个拉起桌宠的那份 Codex 配置。需要时用
|
|
18
|
+
`CC_PETS_CODEX_HOME` 覆盖;跑在会话里的记录端仍认 `CODEX_HOME`。
|
|
13
19
|
- 修复存在多个 Claude 配置目录时统计错账号:桌宠是被客户端启动的常驻进程,会一直带着
|
|
14
20
|
启动时的 `CLAUDE_CONFIG_DIR`,等于永久绑定到"第一个拉起它的账号"。现固定只统计
|
|
15
21
|
`~/.claude`(可用 `CC_PETS_CLAUDE_CONFIG_DIR` 覆盖),包装脚本启动桌宠时也不再透传该
|
|
@@ -33,8 +39,8 @@
|
|
|
33
39
|
provider 是否还有存活客户端判定,并用事件活跃度覆盖不经包装脚本启动的会话。包装脚本
|
|
34
40
|
启动的会话退出后 3 秒内转为"离线",不再被为直接启动会话准备的 60 秒静默宽限拖住。
|
|
35
41
|
- 额度面板调整信息层级:官方剩余百分比升为主值、本机 Token 降为次级;汇总条改为
|
|
36
|
-
|
|
37
|
-
|
|
42
|
+
分别展示 Codex、Claude 的「今日」与「最近 7 天」Token;统计改用与订阅无关的自然日窗口,
|
|
43
|
+
并保留 Provider 归属;"数据刷新"改由面板自身定时器走字;无 Agent 在线时
|
|
38
44
|
状态配色转灰;额度窗口缺失的列标注"当前无活跃窗口"。
|
|
39
45
|
- 新增 `cc-pets clean` 和带确认的 `cc-pets uninstall --purge`,并自动清理测试临时目录与过期运行状态。
|
|
40
46
|
- 更新日志每次更新前截断,并限制为最近 1 MB,避免长期残留增长。
|
package/README.md
CHANGED
|
@@ -162,7 +162,6 @@ Codex/Claude Hooks 和 shell 集成,并自动重启正在运行的桌宠。自
|
|
|
162
162
|
|
|
163
163
|
```bash
|
|
164
164
|
npm install -g cc-pets@latest \
|
|
165
|
-
--allow-scripts=cc-pets \
|
|
166
165
|
--prefer-online
|
|
167
166
|
```
|
|
168
167
|
|
|
@@ -273,13 +272,17 @@ Claude Code 支持用 `CLAUDE_CONFIG_DIR` 把配置目录指到别处,同一
|
|
|
273
272
|
额度文件按配置目录分开存放,因此多个配置目录的 status line 不会互相覆盖——否则面板会
|
|
274
273
|
把一个账号的剩余百分比配上另一个账号的用量。
|
|
275
274
|
|
|
275
|
+
Codex 侧同理:桌宠固定只统计 `~/.codex`,不读继承来的 `CODEX_HOME`,需要时用
|
|
276
|
+
`CC_PETS_CODEX_HOME` 覆盖。跑在 Codex 会话里的记录端(Agent Hooks、安装脚本)照常认
|
|
277
|
+
`CODEX_HOME`,那是会话级的、不存在被常驻进程带跑的问题。
|
|
278
|
+
|
|
276
279
|
本地 Token 是 CLI 会话事件的原始计数,不等同于订阅额度。官方额度可能受模型、缓存和
|
|
277
280
|
请求复杂度等因素影响,应始终以服务端返回的百分比为准。
|
|
278
281
|
|
|
279
282
|
额度详情面板使用青色区分 Codex、紫色区分 Claude。标题行显示在线 Agent 数,下方汇总条
|
|
280
|
-
|
|
283
|
+
分别展示 Codex、Claude 的「今日」与「最近 7 天」Token,并显示最近刷新时间。统计用的是与订阅无关的
|
|
281
284
|
自然日窗口(今日 = 本机零点至今,最近 7 天 = 含今天在内的 7 个自然日),因为两家的
|
|
282
|
-
`resets_at`
|
|
285
|
+
`resets_at` 并不一致,按各自订阅窗口算出的数不在同一区间上,相加没有意义。每个 Agent 卡片按 5 小时和 7 天两列
|
|
283
286
|
展示官方剩余百分比(主值)、本机 Token 用量和重置时间,右侧是近 7 天额度趋势。某个窗口
|
|
284
287
|
当前没有额度数据时该列标注"当前无活跃窗口"。卡片上的在线徽章表示该 Provider 是否还有
|
|
285
288
|
运行中的客户端(包装脚本写出的 pid 文件,或该 Provider 最近 60 秒内仍在发事件),与是否
|
|
@@ -326,7 +329,7 @@ npx petdex install <slug>
|
|
|
326
329
|
|
|
327
330
|
## 隐私
|
|
328
331
|
|
|
329
|
-
- Codex
|
|
332
|
+
- Codex 额度与 Token 只从本机 `~/.codex/sessions` 读取(可用 `CC_PETS_CODEX_HOME` 覆盖)。
|
|
330
333
|
- Claude 额度只从 Claude Code 传给本机 status line 的 `rate_limits` 字段读取。
|
|
331
334
|
- Agent Hooks 只向当前用户的临时目录写入桌宠事件和额度缓存。
|
|
332
335
|
- 额度历史默认关闭;启用后只在本机保留最近 7 天的剩余比例快照。
|
|
@@ -11,9 +11,6 @@
|
|
|
11
11
|
@property NSTextField *statusTitleLabel;
|
|
12
12
|
@property NSTextField *statusDetailLabel;
|
|
13
13
|
@property NSButton *statusIconButton;
|
|
14
|
-
@property NSPanel *statusTogglePanel;
|
|
15
|
-
@property NSVisualEffectView *statusToggleGlass;
|
|
16
|
-
@property NSButton *statusToggleButton;
|
|
17
14
|
@property BOOL statusBubbleExpanded;
|
|
18
15
|
@property BOOL statusBubbleAbove;
|
|
19
16
|
@property BOOL hasAgentStatus;
|
|
@@ -52,6 +49,7 @@
|
|
|
52
49
|
- (void)showAgentStatusForRecord:(NSDictionary *)record;
|
|
53
50
|
- (void)prunePendingApprovalRecords;
|
|
54
51
|
- (void)toggleAgentStatusBubble:(id)sender;
|
|
52
|
+
- (void)toggleStatusBubbleFromMenu:(NSButton *)sender;
|
|
55
53
|
- (void)refreshUsage:(id)sender;
|
|
56
54
|
- (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage;
|
|
57
55
|
- (void)switchPetToID:(NSString *)petID;
|
|
@@ -386,29 +386,6 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
386
386
|
if ([state isEqualToString:@"idle"]) return @"zzz";
|
|
387
387
|
return @"ellipsis";
|
|
388
388
|
}
|
|
389
|
-
- (void)updateStatusToggleAppearance {
|
|
390
|
-
if (!self.hasAgentStatus) return;
|
|
391
|
-
NSColor *stateColor = [self statusColorForState:self.lastStatusState];
|
|
392
|
-
if (self.statusBubbleExpanded) {
|
|
393
|
-
self.statusToggleButton.title = @"";
|
|
394
|
-
self.statusToggleButton.imagePosition = NSImageOnly;
|
|
395
|
-
NSString *symbol = self.statusBubbleAbove ? @"chevron.down" : @"chevron.up";
|
|
396
|
-
NSImage *image = [NSImage imageWithSystemSymbolName:symbol accessibilityDescription:@"折叠状态"];
|
|
397
|
-
self.statusToggleButton.image = [image imageWithSymbolConfiguration:
|
|
398
|
-
[NSImageSymbolConfiguration configurationWithPointSize:11 weight:NSFontWeightSemibold]];
|
|
399
|
-
self.statusToggleButton.contentTintColor = NSColor.whiteColor;
|
|
400
|
-
self.statusToggleGlass.layer.backgroundColor =
|
|
401
|
-
[NSColor colorWithWhite:0.16 alpha:0.54].CGColor;
|
|
402
|
-
} else {
|
|
403
|
-
self.statusToggleButton.image = nil;
|
|
404
|
-
self.statusToggleButton.imagePosition = NSNoImage;
|
|
405
|
-
self.statusToggleButton.title = [NSString stringWithFormat:@"%ld",
|
|
406
|
-
(long)MAX(1, self.liveClientCount)];
|
|
407
|
-
self.statusToggleButton.font = [NSFont systemFontOfSize:11 weight:NSFontWeightSemibold];
|
|
408
|
-
self.statusToggleButton.contentTintColor = NSColor.whiteColor;
|
|
409
|
-
self.statusToggleGlass.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.72].CGColor;
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
389
|
// Codex / Claude 退出时不会补发结束事件:包装脚本最后一行是 exec,自身已经被
|
|
413
390
|
// 替换掉,装不上 EXIT trap。唯一可靠的退出信号是客户端 pid 文件被回收。
|
|
414
391
|
// 没有这一步的话,“正在启动”只能等 60 秒无活动才消失,而另一个 provider 的事件
|
|
@@ -426,7 +403,6 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
426
403
|
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
427
404
|
selector:@selector(enterIdleStatus) object:nil];
|
|
428
405
|
[self.statusPanel orderOut:nil];
|
|
429
|
-
[self.statusTogglePanel orderOut:nil];
|
|
430
406
|
self.hasAgentStatus = NO;
|
|
431
407
|
}
|
|
432
408
|
- (void)toggleAgentStatusBubble:(id)sender {
|
|
@@ -435,13 +411,25 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
435
411
|
[NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
|
|
436
412
|
forKey:StatusBubbleExpandedKey];
|
|
437
413
|
if (self.statusBubbleExpanded) {
|
|
414
|
+
[self positionAgentStatus];
|
|
415
|
+
[self.statusPanel orderFrontRegardless];
|
|
416
|
+
} else {
|
|
417
|
+
[self.statusPanel orderOut:nil];
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
// 菜单开关的语义和点击宠物相反:勾选 = 显示气泡。没有 agent 状态时也允许改,
|
|
421
|
+
// 这样用户可以提前设好偏好,而不必等下一次会话开始。
|
|
422
|
+
- (void)toggleStatusBubbleFromMenu:(NSButton *)sender {
|
|
423
|
+
self.statusBubbleExpanded = !self.statusBubbleExpanded;
|
|
424
|
+
[NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
|
|
425
|
+
forKey:StatusBubbleExpandedKey];
|
|
426
|
+
sender.state = self.statusBubbleExpanded ? NSControlStateValueOn : NSControlStateValueOff;
|
|
427
|
+
if (self.statusBubbleExpanded && self.hasAgentStatus) {
|
|
428
|
+
[self positionAgentStatus];
|
|
438
429
|
[self.statusPanel orderFrontRegardless];
|
|
439
430
|
} else {
|
|
440
431
|
[self.statusPanel orderOut:nil];
|
|
441
432
|
}
|
|
442
|
-
[self positionAgentStatus];
|
|
443
|
-
[self updateStatusToggleAppearance];
|
|
444
|
-
[self.statusTogglePanel orderFrontRegardless];
|
|
445
433
|
}
|
|
446
434
|
// Stop 之后还会飘来 SubagentStop / PostToolUse / TaskCompleted 这类"仍在工作"的尾巴事件
|
|
447
435
|
// (实测 Stop 后 4 秒),它们和 UserPromptSubmit 一样都归一成 thinking,只看 state 分不出来,
|
|
@@ -471,8 +459,6 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
471
459
|
[self positionAgentStatus];
|
|
472
460
|
if (self.statusBubbleExpanded) [self.statusPanel orderFrontRegardless];
|
|
473
461
|
else [self.statusPanel orderOut:nil];
|
|
474
|
-
[self updateStatusToggleAppearance];
|
|
475
|
-
[self.statusTogglePanel orderFrontRegardless];
|
|
476
462
|
}
|
|
477
463
|
// "正在启动"只在会话拉起的一瞬间成立。之后如果没有任何后续事件,真实情况是会话已就绪、
|
|
478
464
|
// 正在等用户输入——继续显示"正在准备当前会话…"会让启动和待机看起来一模一样。
|
|
@@ -744,6 +730,8 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
744
730
|
self.panel.hasShadow = NO;
|
|
745
731
|
self.panel.level = NSFloatingWindowLevel;
|
|
746
732
|
self.panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
|
|
733
|
+
// 与 1.0 一致:透明背景交给 AppKit 原生拖动;PetView 通过
|
|
734
|
+
// mouseDownCanMoveWindow=NO 保留自己的点击和奔跑动画拖动,两条路径按命中区隔离。
|
|
747
735
|
self.panel.movableByWindowBackground = YES;
|
|
748
736
|
self.panel.hidesOnDeactivate = NO;
|
|
749
737
|
|
|
@@ -765,16 +753,19 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
765
753
|
self.petView.switchPetRequested = ^(NSString *petID) {
|
|
766
754
|
[weakSelf switchPetToID:petID];
|
|
767
755
|
};
|
|
768
|
-
self.petView.positionChanged = ^{
|
|
769
|
-
if (weakSelf.quotaPanel.isVisible) [weakSelf positionQuotaDashboard];
|
|
770
|
-
if (weakSelf.statusPanel.isVisible || weakSelf.statusTogglePanel.isVisible) {
|
|
771
|
-
[weakSelf positionAgentStatus];
|
|
772
|
-
}
|
|
773
|
-
};
|
|
774
756
|
self.petView.dragStateChanged = ^(BOOL dragging) {
|
|
775
757
|
weakSelf.petDragging = dragging;
|
|
776
758
|
if (!dragging) [weakSelf scheduleQuotaDashboardHide];
|
|
777
759
|
};
|
|
760
|
+
self.petView.statusToggleRequested = ^{
|
|
761
|
+
[weakSelf toggleAgentStatusBubble:nil];
|
|
762
|
+
};
|
|
763
|
+
// 附属面板的跟随必须挂在窗口自身的移动通知上,不能只挂 PetView 的拖动回调:
|
|
764
|
+
// panel 开了 movableByWindowBackground,按在 PetView 之外的透明边上时由 AppKit
|
|
765
|
+
// 直接搬窗口,PetView 的 mouseDragged 根本不触发,气泡就会留在原地。
|
|
766
|
+
[NSNotificationCenter.defaultCenter addObserver:self
|
|
767
|
+
selector:@selector(petWindowDidMove:)
|
|
768
|
+
name:NSWindowDidMoveNotification object:self.panel];
|
|
778
769
|
[root addSubview:self.petView];
|
|
779
770
|
|
|
780
771
|
NSSize statusGlassSize = NSMakeSize(340, 58);
|
|
@@ -848,38 +839,6 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
848
839
|
[statusRoot addSubview:self.statusGlass];
|
|
849
840
|
self.statusPanel.contentView = statusRoot;
|
|
850
841
|
|
|
851
|
-
NSSize toggleSize = NSMakeSize(28, 28);
|
|
852
|
-
self.statusTogglePanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0,
|
|
853
|
-
toggleSize.width, toggleSize.height)
|
|
854
|
-
styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
|
|
855
|
-
backing:NSBackingStoreBuffered defer:NO];
|
|
856
|
-
self.statusTogglePanel.opaque = NO;
|
|
857
|
-
self.statusTogglePanel.backgroundColor = NSColor.clearColor;
|
|
858
|
-
self.statusTogglePanel.hasShadow = YES;
|
|
859
|
-
self.statusTogglePanel.ignoresMouseEvents = NO;
|
|
860
|
-
self.statusTogglePanel.level = NSFloatingWindowLevel;
|
|
861
|
-
self.statusTogglePanel.collectionBehavior =
|
|
862
|
-
NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
|
|
863
|
-
self.statusTogglePanel.hidesOnDeactivate = NO;
|
|
864
|
-
self.statusToggleGlass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(
|
|
865
|
-
0, 0, toggleSize.width, toggleSize.height)];
|
|
866
|
-
self.statusToggleGlass.material = NSVisualEffectMaterialHUDWindow;
|
|
867
|
-
self.statusToggleGlass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
|
|
868
|
-
self.statusToggleGlass.state = NSVisualEffectStateActive;
|
|
869
|
-
self.statusToggleGlass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
|
|
870
|
-
self.statusToggleGlass.wantsLayer = YES;
|
|
871
|
-
self.statusToggleGlass.layer.cornerRadius = 14;
|
|
872
|
-
self.statusToggleGlass.layer.masksToBounds = YES;
|
|
873
|
-
self.statusToggleGlass.layer.borderWidth = 1;
|
|
874
|
-
self.statusToggleGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.24].CGColor;
|
|
875
|
-
self.statusToggleButton = [[NSButton alloc] initWithFrame:self.statusToggleGlass.bounds];
|
|
876
|
-
self.statusToggleButton.bordered = NO;
|
|
877
|
-
self.statusToggleButton.imagePosition = NSImageOnly;
|
|
878
|
-
self.statusToggleButton.target = self;
|
|
879
|
-
self.statusToggleButton.action = @selector(toggleAgentStatusBubble:);
|
|
880
|
-
[self.statusToggleGlass addSubview:self.statusToggleButton];
|
|
881
|
-
self.statusTogglePanel.contentView = self.statusToggleGlass;
|
|
882
|
-
|
|
883
842
|
NSSize quotaSize = NSMakeSize(QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale);
|
|
884
843
|
self.quotaPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)
|
|
885
844
|
styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
|
|
@@ -996,12 +955,37 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
996
955
|
NSRect petFrame = self.panel.frame;
|
|
997
956
|
NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
|
|
998
957
|
NSSize size = self.quotaPanel.frame.size;
|
|
999
|
-
CGFloat
|
|
1000
|
-
CGFloat
|
|
1001
|
-
|
|
1002
|
-
|
|
958
|
+
const CGFloat margin = 12;
|
|
959
|
+
const CGFloat gap = 8;
|
|
960
|
+
CGFloat minX = NSMinX(visible) + margin;
|
|
961
|
+
CGFloat maxX = NSMaxX(visible) - size.width - margin;
|
|
962
|
+
CGFloat minY = NSMinY(visible) + margin;
|
|
963
|
+
CGFloat maxY = NSMaxY(visible) - size.height - margin;
|
|
964
|
+
CGFloat leftX = NSMinX(petFrame) - size.width - gap;
|
|
965
|
+
CGFloat rightX = NSMaxX(petFrame) + gap;
|
|
966
|
+
CGFloat x;
|
|
967
|
+
CGFloat y = fmax(minY, fmin(NSMinY(petFrame) + 112, maxY));
|
|
968
|
+
|
|
969
|
+
// 优先放在宠物左侧,其次右侧;两个可点击窗口之间始终留出间隔。
|
|
970
|
+
if (leftX >= minX) {
|
|
971
|
+
x = leftX;
|
|
972
|
+
} else if (rightX <= maxX) {
|
|
973
|
+
x = rightX;
|
|
974
|
+
} else {
|
|
975
|
+
// 横向空间不足时改放上/下方,避免屏幕边缘钳位后重新盖住宠物。
|
|
976
|
+
x = fmax(minX, fmin(NSMidX(petFrame) - size.width / 2.0, maxX));
|
|
977
|
+
CGFloat aboveY = NSMaxY(petFrame) + gap;
|
|
978
|
+
CGFloat belowY = NSMinY(petFrame) - size.height - gap;
|
|
979
|
+
if (aboveY <= maxY) y = aboveY;
|
|
980
|
+
else if (belowY >= minY) y = belowY;
|
|
981
|
+
else y = fmax(minY, fmin(aboveY, maxY));
|
|
982
|
+
}
|
|
1003
983
|
[self.quotaPanel setFrameOrigin:NSMakePoint(x, y)];
|
|
1004
984
|
}
|
|
985
|
+
- (void)petWindowDidMove:(NSNotification *)notification {
|
|
986
|
+
if (self.quotaPanel.isVisible) [self positionQuotaDashboard];
|
|
987
|
+
if (self.statusPanel.isVisible) [self positionAgentStatus];
|
|
988
|
+
}
|
|
1005
989
|
- (void)positionAgentStatus {
|
|
1006
990
|
NSRect petFrame = self.panel.frame;
|
|
1007
991
|
NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
|
|
@@ -1016,19 +1000,6 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
1016
1000
|
x = fmax(NSMinX(visible) + 10, fmin(x, NSMaxX(visible) - size.width - 10));
|
|
1017
1001
|
y = fmax(NSMinY(visible) + 10, fmin(y, NSMaxY(visible) - size.height - 10));
|
|
1018
1002
|
[self.statusPanel setFrameOrigin:NSMakePoint(x, y)];
|
|
1019
|
-
|
|
1020
|
-
NSSize toggleSize = self.statusTogglePanel.frame.size;
|
|
1021
|
-
NSRect petViewFrame = self.petView.frame;
|
|
1022
|
-
CGFloat toggleX = NSMinX(petFrame) + NSMinX(petViewFrame) +
|
|
1023
|
-
NSWidth(petViewFrame) * 0.82;
|
|
1024
|
-
CGFloat toggleY = NSMinY(petFrame) + NSMinY(petViewFrame) +
|
|
1025
|
-
NSHeight(petViewFrame) * 0.70;
|
|
1026
|
-
toggleX = fmax(NSMinX(visible) + 8,
|
|
1027
|
-
fmin(toggleX, NSMaxX(visible) - toggleSize.width - 8));
|
|
1028
|
-
toggleY = fmax(NSMinY(visible) + 8,
|
|
1029
|
-
fmin(toggleY, NSMaxY(visible) - toggleSize.height - 8));
|
|
1030
|
-
[self.statusTogglePanel setFrameOrigin:NSMakePoint(toggleX, toggleY)];
|
|
1031
|
-
[self updateStatusToggleAppearance];
|
|
1032
1003
|
}
|
|
1033
1004
|
- (void)scheduleQuotaDashboardHide {
|
|
1034
1005
|
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
|
|
@@ -1248,9 +1219,6 @@ static void TrimUpdateLog(NSString *path) {
|
|
|
1248
1219
|
}
|
|
1249
1220
|
[self updateQuotaLiveState];
|
|
1250
1221
|
[self hideAgentStatusIfClientGone];
|
|
1251
|
-
if (self.statusTogglePanel.isVisible && !self.statusBubbleExpanded) {
|
|
1252
|
-
[self updateStatusToggleAppearance];
|
|
1253
|
-
}
|
|
1254
1222
|
// 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
|
|
1255
1223
|
// Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
|
|
1256
1224
|
if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
|
|
@@ -90,6 +90,16 @@ NSString *NormalizedStateForEvent(NSString *event, BOOL failed) {
|
|
|
90
90
|
static const off_t AgentEventLogSizeLimit = 4 * 1024 * 1024;
|
|
91
91
|
|
|
92
92
|
BOOL AppendAgentEventRecord(NSDictionary *record) {
|
|
93
|
+
// 测试会跑包装脚本和 hook,漏设 CC_PETS_STATE_DIR 的用例会把事件写进用户真实的
|
|
94
|
+
// 事件流里,把正在运行的桌宠打回"正在启动"。测试统一导出这个变量,写入端打上标记,
|
|
95
|
+
// 收尾就能只对"测试自己写的行"判污染——按文件大小判会被同机的真实会话误伤。
|
|
96
|
+
// 正常使用下没有任何东西会设它。
|
|
97
|
+
NSString *mark = NSProcessInfo.processInfo.environment[@"CC_PETS_TEST_MARK"];
|
|
98
|
+
if (mark.length > 0) {
|
|
99
|
+
NSMutableDictionary *marked = [record mutableCopy];
|
|
100
|
+
marked[@"testMark"] = SanitizedShortString(mark, 64);
|
|
101
|
+
record = marked;
|
|
102
|
+
}
|
|
93
103
|
NSData *json = [NSJSONSerialization dataWithJSONObject:record options:0 error:nil];
|
|
94
104
|
if (!json) return NO;
|
|
95
105
|
// JSON 和换行必须一次 write 写完:O_APPEND 只保证单次 write 的原子性,
|
|
@@ -8,6 +8,8 @@ NSString *ClaudeUsagePath(void);
|
|
|
8
8
|
// 桌宠端用:只看主账号,不受继承来的 CLAUDE_CONFIG_DIR 影响。
|
|
9
9
|
NSString *DefaultClaudeConfigDirectory(void);
|
|
10
10
|
NSString *CurrentClaudeConfigDirectory(void);
|
|
11
|
+
// 桌宠端用:只看主账号的 Codex 目录,不受继承来的 CODEX_HOME 影响。
|
|
12
|
+
NSString *DefaultCodexHomeDirectory(void);
|
|
11
13
|
NSString *ClaudeUsagePathForConfigDirectory(NSString *configDirectory);
|
|
12
14
|
NSString *ApplicationSupportDirectory(void);
|
|
13
15
|
NSString *QuotaHistoryPath(void);
|
|
@@ -29,6 +29,15 @@ NSString *CurrentClaudeConfigDirectory(void) {
|
|
|
29
29
|
return DefaultClaudeConfigDirectory();
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
// 与 DefaultClaudeConfigDirectory 同一个理由:桌宠是被某个客户端 open 起来的常驻进程,
|
|
33
|
+
// 会把当时的 CODEX_HOME 一直带着,等于永久绑定到"第一个拉起它的那份 Codex 配置"。
|
|
34
|
+
// 记录端(--provider-event 之类跑在 Codex 会话里的入口)照常用 CODEX_HOME,那是会话级的。
|
|
35
|
+
NSString *DefaultCodexHomeDirectory(void) {
|
|
36
|
+
NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_CODEX_HOME"];
|
|
37
|
+
if (override.length > 0) return override.stringByStandardizingPath;
|
|
38
|
+
return [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
|
|
39
|
+
}
|
|
40
|
+
|
|
32
41
|
// 额度是按账号的。一台机器上可以有多个配置目录(例如 ~/.claude 和 ~/.claude-nw),
|
|
33
42
|
// 各自是不同账号、不同额度周期。共用一个文件的话两边的 statusline 会互相覆盖,
|
|
34
43
|
// 面板就会把 A 账号的剩余百分比配上 B 账号的用量。因此按配置目录分文件。
|
|
@@ -23,6 +23,12 @@ NSDictionary *QuotaHistoryDocument(void) {
|
|
|
23
23
|
static NSDictionary *HistoryProviderSample(NSDictionary *usage, NSString *usedKey) {
|
|
24
24
|
NSNumber *fiveHour = RemainingValue(usage, @"fiveHour", usedKey);
|
|
25
25
|
NSNumber *week = RemainingValue(usage, @"week", usedKey);
|
|
26
|
+
// 额度被拒之后官方不再报窗口,留在手里的百分比是过期值,照抄进历史会画出一条
|
|
27
|
+
// "一直有余额"的假曲线。
|
|
28
|
+
if ([usage[@"exhaustedAt"] isKindOfClass:NSNumber.class]) {
|
|
29
|
+
if (fiveHour) fiveHour = @0;
|
|
30
|
+
if (week) week = @0;
|
|
31
|
+
}
|
|
26
32
|
NSMutableDictionary *sample = [NSMutableDictionary dictionary];
|
|
27
33
|
if (fiveHour) sample[@"fiveHourRemaining"] = fiveHour;
|
|
28
34
|
if (week) sample[@"weekRemaining"] = week;
|
|
@@ -185,8 +185,34 @@ static NSURL *NewestCodexSessionURL(NSURL *sessionsURL) {
|
|
|
185
185
|
return newest ?: NewestSessionFileInDirectory(sessionsURL, NULL);
|
|
186
186
|
}
|
|
187
187
|
|
|
188
|
+
// 额度被拒时 Codex 会写一条带 error.codex_error_info = usage_limit_exceeded 的事件。
|
|
189
|
+
// 这是唯一能说明"官方额度现在不给用了"的结构化信号:同一时刻 rate_limits 里
|
|
190
|
+
// primary/secondary 全是 null,光看额度字段只能看到"这行没有数据",于是上一份百分比
|
|
191
|
+
// 会一直挂在面板上——账号被别人用完时,那个数字既过期又正好指向相反的结论。
|
|
192
|
+
static NSNumber *ExhaustionTimestampFromLine(NSData *lineData) {
|
|
193
|
+
if (lineData.length == 0) return nil;
|
|
194
|
+
static NSData *marker;
|
|
195
|
+
static dispatch_once_t once;
|
|
196
|
+
dispatch_once(&once, ^{
|
|
197
|
+
marker = [@"usage_limit_exceeded" dataUsingEncoding:NSUTF8StringEncoding];
|
|
198
|
+
});
|
|
199
|
+
if ([lineData rangeOfData:marker options:0 range:NSMakeRange(0, lineData.length)].location ==
|
|
200
|
+
NSNotFound) return nil;
|
|
201
|
+
id rootValue = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
202
|
+
if (![rootValue isKindOfClass:NSDictionary.class]) return nil;
|
|
203
|
+
NSDictionary *root = rootValue;
|
|
204
|
+
NSDictionary *payload = [root[@"payload"] isKindOfClass:NSDictionary.class] ? root[@"payload"] : nil;
|
|
205
|
+
NSDictionary *error = [payload[@"error"] isKindOfClass:NSDictionary.class] ? payload[@"error"] : nil;
|
|
206
|
+
NSString *info = [error[@"codex_error_info"] isKindOfClass:NSString.class]
|
|
207
|
+
? error[@"codex_error_info"] : nil;
|
|
208
|
+
if (![info containsString:@"usage_limit"]) return nil;
|
|
209
|
+
NSDate *date = ISO8601Timestamp(root[@"timestamp"]);
|
|
210
|
+
return date ? @(date.timeIntervalSince1970) : nil;
|
|
211
|
+
}
|
|
212
|
+
|
|
188
213
|
static NSDictionary *UsageFromCodexLine(NSData *lineData) {
|
|
189
|
-
NSDictionary *
|
|
214
|
+
NSDictionary *root = nil;
|
|
215
|
+
NSDictionary *payload = TokenPayloadFromLine(lineData, &root);
|
|
190
216
|
if (!payload) return nil;
|
|
191
217
|
id limitsValue = payload[@"rate_limits"];
|
|
192
218
|
if (![limitsValue isKindOfClass:NSDictionary.class]) return nil;
|
|
@@ -202,29 +228,49 @@ static NSDictionary *UsageFromCodexLine(NSData *lineData) {
|
|
|
202
228
|
if (minutes == 300) fiveHour = quota;
|
|
203
229
|
if (minutes == 10080) week = quota;
|
|
204
230
|
}
|
|
231
|
+
// primary/secondary 全是 null 的 rate_limits(实测切到 premium/credits 计费后每条都这样)
|
|
232
|
+
// 并不表示额度消失,只是这条响应没带窗口信息。当成"这行没有额度"往前找,
|
|
233
|
+
// 否则上一份仍然有效的窗口会被它整块盖掉,面板退回 `--` + 等待数据。
|
|
234
|
+
if (!fiveHour && !week) return nil;
|
|
235
|
+
// 采样时刻用来和耗尽事件比先后:耗尽之后又拿到新的额度快照,说明额度已经恢复。
|
|
236
|
+
NSDate *sampledAt = ISO8601Timestamp(root[@"timestamp"]);
|
|
205
237
|
return @{
|
|
206
238
|
@"fiveHour": fiveHour ?: NSNull.null,
|
|
207
|
-
@"week": week ?: NSNull.null
|
|
239
|
+
@"week": week ?: NSNull.null,
|
|
240
|
+
@"sampledAt": @(sampledAt ? sampledAt.timeIntervalSince1970 : 0)
|
|
208
241
|
};
|
|
209
242
|
}
|
|
210
243
|
|
|
244
|
+
// 耗尽事件不早于当前额度快照时,把标记贴到 usage 上,供面板把剩余额度显示成 0。
|
|
245
|
+
static NSDictionary *UsageByMarkingExhaustion(NSDictionary *usage, NSTimeInterval exhaustedAt) {
|
|
246
|
+
if (![usage isKindOfClass:NSDictionary.class] || exhaustedAt <= 0) return usage;
|
|
247
|
+
if (exhaustedAt < [usage[@"sampledAt"] doubleValue]) return usage;
|
|
248
|
+
NSMutableDictionary *result = [usage mutableCopy];
|
|
249
|
+
result[@"exhaustedAt"] = @(exhaustedAt);
|
|
250
|
+
return result;
|
|
251
|
+
}
|
|
252
|
+
|
|
211
253
|
// token_count 行几乎总在文件末尾,因此从尾部反向按 \n 切片逐行试,命中即停。
|
|
212
254
|
// 原实现会把整段(最多 2MB)解码成 NSString、再切成全部行、再把每行编码回 NSData、
|
|
213
255
|
// 又解码回 NSString 查子串,等于来回往返两遍。
|
|
214
|
-
static NSDictionary *LatestUsageInData(NSData *data) {
|
|
256
|
+
static NSDictionary *LatestUsageInData(NSData *data, NSNumber **outExhaustedAt) {
|
|
215
257
|
const uint8_t *bytes = data.bytes;
|
|
216
258
|
NSUInteger end = data.length;
|
|
259
|
+
NSDictionary *usage = nil;
|
|
260
|
+
NSNumber *exhaustedAt = nil;
|
|
217
261
|
while (end > 0) {
|
|
218
262
|
NSUInteger start = end;
|
|
219
263
|
while (start > 0 && bytes[start - 1] != '\n') start -= 1;
|
|
220
264
|
if (end > start) {
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
if (usage)
|
|
265
|
+
NSData *line = [data subdataWithRange:NSMakeRange(start, end - start)];
|
|
266
|
+
if (!exhaustedAt) exhaustedAt = ExhaustionTimestampFromLine(line);
|
|
267
|
+
if (!usage) usage = UsageFromCodexLine(line);
|
|
268
|
+
if (usage && exhaustedAt) break;
|
|
224
269
|
}
|
|
225
270
|
end = start > 0 ? start - 1 : 0;
|
|
226
271
|
}
|
|
227
|
-
|
|
272
|
+
if (outExhaustedAt) *outExhaustedAt = exhaustedAt;
|
|
273
|
+
return usage;
|
|
228
274
|
}
|
|
229
275
|
|
|
230
276
|
// resets_at 恒在未来,因此 7 天窗口的起点不可能早于 now - 7d;再留一天覆盖时区和跨日边界。
|
|
@@ -272,6 +318,47 @@ static NSArray<NSURL *> *RecentCodexSessionURLs(NSURL *sessionsURL) {
|
|
|
272
318
|
return urls;
|
|
273
319
|
}
|
|
274
320
|
|
|
321
|
+
static NSData *SessionTailData(NSURL *url) {
|
|
322
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
323
|
+
if (!handle) return nil;
|
|
324
|
+
unsigned long long size = [handle seekToEndOfFile];
|
|
325
|
+
[handle seekToFileOffset:size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0];
|
|
326
|
+
NSData *tail = [handle readDataToEndOfFile];
|
|
327
|
+
[handle closeFile];
|
|
328
|
+
return tail;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
static BOOL UsageHasLiveWindow(NSDictionary *usage) {
|
|
332
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
333
|
+
for (NSString *key in @[@"fiveHour", @"week"]) {
|
|
334
|
+
NSDictionary *quota = [usage[key] isKindOfClass:NSDictionary.class] ? usage[key] : nil;
|
|
335
|
+
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
|
|
336
|
+
if (reset && reset.doubleValue > now) return YES;
|
|
337
|
+
}
|
|
338
|
+
return NO;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// 最新会话整篇都没有额度时往前找。rate_limits 是账号级的,写在哪个会话里都一样;
|
|
342
|
+
// 而新会话在第一次拿到限流响应之前一条都不写,冷启动正好撞上就会整块空白。
|
|
343
|
+
// 只接受 resets_at 还没到的窗口,免得把过期的百分比当成当前值。
|
|
344
|
+
static NSDictionary *LatestQuotaInRecentSessions(NSURL *sessionsURL, NSURL *skipURL) {
|
|
345
|
+
NSArray<NSURL *> *urls = [RecentCodexSessionURLs(sessionsURL) sortedArrayUsingComparator:
|
|
346
|
+
^NSComparisonResult(NSURL *left, NSURL *right) {
|
|
347
|
+
NSDate *leftDate = nil, *rightDate = nil;
|
|
348
|
+
[left getResourceValue:&leftDate forKey:NSURLContentModificationDateKey error:nil];
|
|
349
|
+
[right getResourceValue:&rightDate forKey:NSURLContentModificationDateKey error:nil];
|
|
350
|
+
return [(rightDate ?: NSDate.distantPast) compare:(leftDate ?: NSDate.distantPast)];
|
|
351
|
+
}];
|
|
352
|
+
NSUInteger examined = 0;
|
|
353
|
+
for (NSURL *url in urls) {
|
|
354
|
+
if (skipURL && [url.path isEqualToString:skipURL.path]) continue;
|
|
355
|
+
if (++examined > 8) break;
|
|
356
|
+
NSDictionary *usage = LatestUsageInData(SessionTailData(url), NULL);
|
|
357
|
+
if (usage && UsageHasLiveWindow(usage)) return usage;
|
|
358
|
+
}
|
|
359
|
+
return nil;
|
|
360
|
+
}
|
|
361
|
+
|
|
275
362
|
static NSDictionary *FirstTimestampRecordInData(NSData *data) {
|
|
276
363
|
const uint8_t *bytes = data.bytes;
|
|
277
364
|
NSUInteger start = 0;
|
|
@@ -348,10 +435,34 @@ static void AddTokenCounts(NSMutableDictionary *target, NSDictionary *counts) {
|
|
|
348
435
|
}
|
|
349
436
|
}
|
|
350
437
|
|
|
438
|
+
// 累计值相减,而不是累加窗口内的 last_token_usage:Codex 会把同一份 token_count
|
|
439
|
+
// 重复写进会话(本机近期 68 个会话里 14 个如此,sum(last) 整体比末行 total 高 1.1%,
|
|
440
|
+
// 最差的单个会话高 7.7%),累加就把重复的那次算了两遍。累计值对重复事件是幂等的。
|
|
441
|
+
// total_token_usage 罕见地回退(会话内重置)时,窗口前的基线已经失效,直接取窗口内的值。
|
|
442
|
+
static NSDictionary *TokenCountsBySubtracting(NSDictionary *totals, NSDictionary *baseline) {
|
|
443
|
+
NSMutableDictionary *result = [NSMutableDictionary dictionary];
|
|
444
|
+
for (NSString *key in TokenKeys()) {
|
|
445
|
+
if (!totals[key]) continue;
|
|
446
|
+
unsigned long long current = [totals[key] unsignedLongLongValue];
|
|
447
|
+
unsigned long long previous = [baseline[key] unsignedLongLongValue];
|
|
448
|
+
result[key] = @(current >= previous ? current - previous : current);
|
|
449
|
+
}
|
|
450
|
+
return result;
|
|
451
|
+
}
|
|
452
|
+
|
|
351
453
|
static NSDictionary *PartialTokenTotals(NSURL *url, NSTimeInterval start, NSTimeInterval end) {
|
|
352
454
|
NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
|
|
353
455
|
if (!handle) return nil;
|
|
354
|
-
|
|
456
|
+
__block NSDictionary *baseline = nil;
|
|
457
|
+
__block NSDictionary *inside = nil;
|
|
458
|
+
void (^consume)(NSData *) = ^(NSData *line) {
|
|
459
|
+
NSDictionary *record = TokenRecordFromLine(line);
|
|
460
|
+
NSDictionary *total = record[@"total"];
|
|
461
|
+
if (!total) return;
|
|
462
|
+
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
463
|
+
if (timestamp < start) baseline = total;
|
|
464
|
+
else if (timestamp < end) inside = total;
|
|
465
|
+
};
|
|
355
466
|
NSMutableData *pending = [NSMutableData data];
|
|
356
467
|
while (YES) {
|
|
357
468
|
NSData *chunk = [handle readDataOfLength:256 * 1024];
|
|
@@ -361,12 +472,7 @@ static NSDictionary *PartialTokenTotals(NSURL *url, NSTimeInterval start, NSTime
|
|
|
361
472
|
NSUInteger lineStart = 0;
|
|
362
473
|
for (NSUInteger index = 0; index < pending.length; index++) {
|
|
363
474
|
if (bytes[index] != '\n') continue;
|
|
364
|
-
|
|
365
|
-
[pending subdataWithRange:NSMakeRange(lineStart, index - lineStart)]);
|
|
366
|
-
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
367
|
-
if (record[@"last"] && timestamp >= start && timestamp < end) {
|
|
368
|
-
AddTokenCounts(totals, record[@"last"]);
|
|
369
|
-
}
|
|
475
|
+
consume([pending subdataWithRange:NSMakeRange(lineStart, index - lineStart)]);
|
|
370
476
|
lineStart = index + 1;
|
|
371
477
|
}
|
|
372
478
|
if (lineStart > 0) {
|
|
@@ -374,15 +480,10 @@ static NSDictionary *PartialTokenTotals(NSURL *url, NSTimeInterval start, NSTime
|
|
|
374
480
|
lineStart, pending.length - lineStart)] mutableCopy];
|
|
375
481
|
}
|
|
376
482
|
}
|
|
377
|
-
if (pending.length > 0)
|
|
378
|
-
NSDictionary *record = TokenRecordFromLine(pending);
|
|
379
|
-
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
380
|
-
if (record[@"last"] && timestamp >= start && timestamp < end) {
|
|
381
|
-
AddTokenCounts(totals, record[@"last"]);
|
|
382
|
-
}
|
|
383
|
-
}
|
|
483
|
+
if (pending.length > 0) consume(pending);
|
|
384
484
|
[handle closeFile];
|
|
385
|
-
|
|
485
|
+
// 窗口内一条 token_count 都没有:这段时间没有产生用量。
|
|
486
|
+
return inside ? TokenCountsBySubtracting(inside, baseline) : @{};
|
|
386
487
|
}
|
|
387
488
|
|
|
388
489
|
// 聚合区间对齐官方重置时间:[resets_at - 窗长, resets_at)。
|
|
@@ -406,9 +507,26 @@ static BOOL TokenWindowForQuota(NSDictionary *quota, double fallbackMinutes,
|
|
|
406
507
|
static const double FiveHourWindowMinutes = 300;
|
|
407
508
|
static const double SevenDayWindowMinutes = 10080;
|
|
408
509
|
|
|
409
|
-
//
|
|
410
|
-
//
|
|
411
|
-
//
|
|
510
|
+
// 官方窗口拿不到时(账号根本没有这个窗口、缺 resets_at、或窗口已过期),Token 依然是
|
|
511
|
+
// 本机自己数出来的,没有理由跟着变成 `--`。退化成按本机时钟往回推的滚动窗口。
|
|
512
|
+
// 终点向上对齐到 10 分钟:起点每秒都在动的话,分片缓存的键每轮都变,跨界会话会被整篇重扫。
|
|
513
|
+
static const NSTimeInterval TokenFallbackGranularity = 600;
|
|
514
|
+
static void RollingWindowForMinutes(double minutes, NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
515
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
516
|
+
NSTimeInterval end = (floor(now / TokenFallbackGranularity) + 1) * TokenFallbackGranularity;
|
|
517
|
+
if (outStart) *outStart = end - minutes * 60.0;
|
|
518
|
+
if (outEnd) *outEnd = end;
|
|
519
|
+
}
|
|
520
|
+
static BOOL TokenWindowOrFallback(NSDictionary *quota, double fallbackMinutes,
|
|
521
|
+
NSTimeInterval *outStart, NSTimeInterval *outEnd) {
|
|
522
|
+
if (TokenWindowForQuota(quota, fallbackMinutes, outStart, outEnd)) return YES;
|
|
523
|
+
if (fallbackMinutes <= 0) return NO;
|
|
524
|
+
RollingWindowForMinutes(fallbackMinutes, outStart, outEnd);
|
|
525
|
+
return YES;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// 面板要并列展示两家数据,而两家的 resets_at 并不一致(实测能差 2 天以上),
|
|
529
|
+
// 所以汇总另用一组与订阅完全脱钩的自然日窗口,保证两家的时间口径一致。
|
|
412
530
|
//
|
|
413
531
|
// 取自然日边界而不是"从现在往回推 N 秒",是因为分片缓存的键里含窗口起点:起点每秒
|
|
414
532
|
// 都在动的话,跨界会话每一轮都要整篇重扫;对齐到零点后起点一天之内不变,缓存才能命中。
|
|
@@ -463,11 +581,11 @@ static NSDictionary *TokenTotalsInWindow(NSTimeInterval start, NSTimeInterval en
|
|
|
463
581
|
return totals;
|
|
464
582
|
}
|
|
465
583
|
|
|
466
|
-
static NSDictionary *TokenTotalsForQuota(NSDictionary *quota,
|
|
467
|
-
NSMutableDictionary *cache) {
|
|
584
|
+
static NSDictionary *TokenTotalsForQuota(NSDictionary *quota, double fallbackMinutes,
|
|
585
|
+
NSArray<NSURL *> *urls, NSMutableDictionary *cache) {
|
|
468
586
|
NSTimeInterval start = 0;
|
|
469
587
|
NSTimeInterval end = 0;
|
|
470
|
-
if (!
|
|
588
|
+
if (!TokenWindowOrFallback(quota, fallbackMinutes, &start, &end)) return nil;
|
|
471
589
|
return TokenTotalsInWindow(start, end, urls, cache);
|
|
472
590
|
}
|
|
473
591
|
|
|
@@ -493,25 +611,29 @@ static void PruneTokenCache(NSMutableDictionary *cache, NSArray<NSURL *> *urls,
|
|
|
493
611
|
}
|
|
494
612
|
}
|
|
495
613
|
|
|
614
|
+
// 一份额度都没拿到时也照样统计 Token:Token 是本机数出来的,不该因为官方额度缺失就空着。
|
|
496
615
|
static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessionsURL,
|
|
497
616
|
NSMutableDictionary *cache) {
|
|
498
|
-
if (![usage isKindOfClass:NSDictionary.class])
|
|
617
|
+
if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
|
|
499
618
|
NSArray<NSURL *> *urls = RecentCodexSessionURLs(sessionsURL);
|
|
500
619
|
NSDictionary *five = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
501
620
|
? usage[@"fiveHour"] : nil;
|
|
502
621
|
NSDictionary *week = [usage[@"week"] isKindOfClass:NSDictionary.class] ? usage[@"week"] : nil;
|
|
503
|
-
NSDictionary *fiveTokens =
|
|
504
|
-
NSDictionary *weekTokens =
|
|
622
|
+
NSDictionary *fiveTokens = TokenTotalsForQuota(five, FiveHourWindowMinutes, urls, cache);
|
|
623
|
+
NSDictionary *weekTokens = TokenTotalsForQuota(week, SevenDayWindowMinutes, urls, cache);
|
|
505
624
|
NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
|
|
506
625
|
RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
|
|
507
626
|
NSDictionary *todayTokens = TokenTotalsInWindow(todayStart, rollingEnd, urls, cache);
|
|
508
627
|
NSDictionary *recentTokens = TokenTotalsInWindow(rollingWeekStart, rollingEnd, urls, cache);
|
|
509
628
|
NSMutableSet<NSString *> *liveWindowKeys = [NSMutableSet setWithArray:@[
|
|
510
629
|
PartialTokenKey(todayStart, rollingEnd), PartialTokenKey(rollingWeekStart, rollingEnd)]];
|
|
511
|
-
|
|
630
|
+
NSArray<NSDictionary *> *windows = @[
|
|
631
|
+
@{@"quota": five ?: @{}, @"minutes": @(FiveHourWindowMinutes)},
|
|
632
|
+
@{@"quota": week ?: @{}, @"minutes": @(SevenDayWindowMinutes)}];
|
|
633
|
+
for (NSDictionary *window in windows) {
|
|
512
634
|
NSTimeInterval start = 0;
|
|
513
635
|
NSTimeInterval end = 0;
|
|
514
|
-
if (
|
|
636
|
+
if (TokenWindowOrFallback(window[@"quota"], [window[@"minutes"] doubleValue], &start, &end)) {
|
|
515
637
|
[liveWindowKeys addObject:PartialTokenKey(start, end)];
|
|
516
638
|
}
|
|
517
639
|
}
|
|
@@ -527,21 +649,23 @@ static NSDictionary *UsageByAddingTokenTotals(NSDictionary *usage, NSURL *sessio
|
|
|
527
649
|
return result;
|
|
528
650
|
}
|
|
529
651
|
|
|
652
|
+
static NSURL *CodexSessionsURL(void) {
|
|
653
|
+
return [NSURL fileURLWithPath:
|
|
654
|
+
[DefaultCodexHomeDirectory() stringByAppendingPathComponent:@"sessions"]];
|
|
655
|
+
}
|
|
656
|
+
|
|
530
657
|
NSDictionary *LatestUsage(void) {
|
|
531
|
-
|
|
532
|
-
if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
|
|
533
|
-
NSURL *sessions = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
|
|
658
|
+
NSURL *sessions = CodexSessionsURL();
|
|
534
659
|
NSURL *newest = NewestCodexSessionURL(sessions);
|
|
535
660
|
if (!newest) return nil;
|
|
536
661
|
|
|
537
|
-
|
|
538
|
-
if (!
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
[
|
|
543
|
-
|
|
544
|
-
return UsageByAddingTokenTotals(usage, sessions, [NSMutableDictionary dictionary]);
|
|
662
|
+
NSData *tail = SessionTailData(newest);
|
|
663
|
+
if (!tail) return nil;
|
|
664
|
+
NSNumber *exhaustedAt = nil;
|
|
665
|
+
NSDictionary *usage = LatestUsageInData(tail, &exhaustedAt)
|
|
666
|
+
?: LatestQuotaInRecentSessions(sessions, newest);
|
|
667
|
+
usage = UsageByAddingTokenTotals(usage, sessions, [NSMutableDictionary dictionary]);
|
|
668
|
+
return UsageByMarkingExhaustion(usage, exhaustedAt.doubleValue);
|
|
545
669
|
}
|
|
546
670
|
|
|
547
671
|
// Token 聚合要遍历近 7 天的会话文件,而 refresh 由 FSEvents 驱动、会话写盘时约 0.5 秒
|
|
@@ -562,22 +686,21 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
|
|
|
562
686
|
@property NSDictionary *tokenUsage;
|
|
563
687
|
@property NSString *tokenWindowIdentity;
|
|
564
688
|
@property NSTimeInterval tokenComputedAt;
|
|
689
|
+
@property NSTimeInterval exhaustedAt;
|
|
565
690
|
@property BOOL forcesTokenAggregation;
|
|
566
691
|
@end
|
|
567
692
|
|
|
568
693
|
@implementation CodexUsageReader
|
|
569
694
|
- (instancetype)init {
|
|
570
695
|
if ((self = [super init])) {
|
|
571
|
-
|
|
572
|
-
if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
|
|
573
|
-
_sessionsURL = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
|
|
696
|
+
_sessionsURL = CodexSessionsURL();
|
|
574
697
|
_partialLine = [NSMutableData data];
|
|
575
698
|
_tokenSummaryCache = [NSMutableDictionary dictionary];
|
|
576
699
|
}
|
|
577
700
|
return self;
|
|
578
701
|
}
|
|
579
702
|
- (NSDictionary *)usageWithTokenTotals:(NSDictionary *)usage {
|
|
580
|
-
if (![usage isKindOfClass:NSDictionary.class])
|
|
703
|
+
if (![usage isKindOfClass:NSDictionary.class]) usage = @{};
|
|
581
704
|
NSString *identity = TokenWindowIdentity(usage);
|
|
582
705
|
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
583
706
|
BOOL reusable = !self.forcesTokenAggregation && self.tokenUsage &&
|
|
@@ -586,7 +709,7 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
|
|
|
586
709
|
if (reusable) {
|
|
587
710
|
NSMutableDictionary *result = [usage mutableCopy];
|
|
588
711
|
result[@"tokenUsage"] = self.tokenUsage;
|
|
589
|
-
return result;
|
|
712
|
+
return UsageByMarkingExhaustion(result, self.exhaustedAt);
|
|
590
713
|
}
|
|
591
714
|
NSDictionary *result = UsageByAddingTokenTotals(usage, self.sessionsURL, self.tokenSummaryCache);
|
|
592
715
|
id tokens = result[@"tokenUsage"];
|
|
@@ -594,7 +717,11 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
|
|
|
594
717
|
self.tokenWindowIdentity = identity;
|
|
595
718
|
self.tokenComputedAt = now;
|
|
596
719
|
self.forcesTokenAggregation = NO;
|
|
597
|
-
return result;
|
|
720
|
+
return UsageByMarkingExhaustion(result, self.exhaustedAt);
|
|
721
|
+
}
|
|
722
|
+
// 耗尽事件只往前走:额度恢复由"更新的额度快照"表达(见 UsageByMarkingExhaustion)。
|
|
723
|
+
- (void)noteExhaustion:(NSNumber *)timestamp {
|
|
724
|
+
if (timestamp.doubleValue > self.exhaustedAt) self.exhaustedAt = timestamp.doubleValue;
|
|
598
725
|
}
|
|
599
726
|
- (void)selectSessionURL:(NSURL *)url {
|
|
600
727
|
self.sessionURL = url;
|
|
@@ -616,7 +743,11 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
|
|
|
616
743
|
self.forcesTokenAggregation = YES;
|
|
617
744
|
// 额度是账号级的,不随会话切换失效。新会话在首个 token_count 落盘前没有 rate_limits,
|
|
618
745
|
// 这时沿用上一份,否则每次开新会话面板都会整块闪空。窗口过期的判定另有 resets_at 兜底。
|
|
619
|
-
|
|
746
|
+
NSNumber *exhaustedAt = nil;
|
|
747
|
+
NSDictionary *latest = LatestUsageInData(tail, &exhaustedAt);
|
|
748
|
+
[self noteExhaustion:exhaustedAt];
|
|
749
|
+
self.usage = [self usageWithTokenTotals:latest ?: self.usage
|
|
750
|
+
?: LatestQuotaInRecentSessions(self.sessionsURL, url)];
|
|
620
751
|
|
|
621
752
|
const uint8_t *bytes = tail.bytes;
|
|
622
753
|
NSUInteger lastNewline = NSNotFound;
|
|
@@ -639,6 +770,7 @@ static NSString *TokenWindowIdentity(NSDictionary *usage) {
|
|
|
639
770
|
for (NSUInteger index = 0; index < self.partialLine.length; index++) {
|
|
640
771
|
if (bytes[index] != '\n') continue;
|
|
641
772
|
NSData *line = [self.partialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
|
|
773
|
+
[self noteExhaustion:ExhaustionTimestampFromLine(line)];
|
|
642
774
|
NSDictionary *newUsage = UsageFromCodexLine(line);
|
|
643
775
|
if (newUsage) self.usage = newUsage;
|
|
644
776
|
lineStart = index + 1;
|
|
@@ -904,8 +1036,9 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
|
|
|
904
1036
|
NSDictionary *week = [limits[@"week"] isKindOfClass:NSDictionary.class] ? limits[@"week"] : nil;
|
|
905
1037
|
NSTimeInterval fiveStart = 0, fiveEnd = 0, weekStart = 0, weekEnd = 0;
|
|
906
1038
|
// Claude 的 rate_limits 没有 window_minutes,窗长按官方订阅固定为 5 小时 / 7 天。
|
|
907
|
-
|
|
908
|
-
|
|
1039
|
+
// 窗口不可用时退化成滚动窗口,Token 是本机数据,不跟着官方额度一起变成 `--`。
|
|
1040
|
+
TokenWindowOrFallback(five, FiveHourWindowMinutes, &fiveStart, &fiveEnd);
|
|
1041
|
+
TokenWindowOrFallback(week, SevenDayWindowMinutes, &weekStart, &weekEnd);
|
|
909
1042
|
// 自然日窗口和额度无关,即使两个额度窗口都不可用也照样统计。
|
|
910
1043
|
NSArray<NSURL *> *urls = RecentClaudeTranscriptURLs(self.projectsURL);
|
|
911
1044
|
NSMutableArray<NSData *> *recordSets = [NSMutableArray arrayWithCapacity:urls.count];
|
|
@@ -921,8 +1054,8 @@ static NSDictionary *ClaudeTokenTotals(NSArray<NSData *> *recordSets, NSTimeInte
|
|
|
921
1054
|
NSTimeInterval todayStart = 0, rollingWeekStart = 0, rollingEnd = 0;
|
|
922
1055
|
RollingTokenWindows(&todayStart, &rollingWeekStart, &rollingEnd);
|
|
923
1056
|
return @{
|
|
924
|
-
@"fiveHour":
|
|
925
|
-
@"week":
|
|
1057
|
+
@"fiveHour": ClaudeTokenTotals(recordSets, fiveStart, fiveEnd),
|
|
1058
|
+
@"week": ClaudeTokenTotals(recordSets, weekStart, weekEnd),
|
|
926
1059
|
@"today": ClaudeTokenTotals(recordSets, todayStart, rollingEnd),
|
|
927
1060
|
@"recentWeek": ClaudeTokenTotals(recordSets, rollingWeekStart, rollingEnd),
|
|
928
1061
|
@"source": @"local"
|
package/Sources/CCPets/PetView.h
CHANGED
|
@@ -12,13 +12,12 @@
|
|
|
12
12
|
@property BOOL draggingPet;
|
|
13
13
|
@property BOOL agentActive;
|
|
14
14
|
@property NSPoint dragStartMouse;
|
|
15
|
-
@property NSPoint dragStartWindowOrigin;
|
|
16
15
|
@property NSString *currentPetID;
|
|
17
16
|
@property id globalMouseMonitor;
|
|
18
17
|
@property id localMouseMonitor;
|
|
19
18
|
@property(copy) void (^pocketHoverChanged)(BOOL hovering);
|
|
20
|
-
@property(copy) void (^positionChanged)(void);
|
|
21
19
|
@property(copy) void (^dragStateChanged)(BOOL dragging);
|
|
20
|
+
@property(copy) void (^statusToggleRequested)(void);
|
|
22
21
|
@property(copy) NSArray<NSDictionary *> *(^petOptionsRequested)(void);
|
|
23
22
|
@property(copy) void (^switchPetRequested)(NSString *petID);
|
|
24
23
|
@property NSCache<NSString *, NSImage *> *petMenuPreviewCache;
|
package/Sources/CCPets/PetView.m
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
#import "CCPetsPaths.h"
|
|
4
4
|
#import "CCPetsImageLoader.h"
|
|
5
5
|
|
|
6
|
+
// 按下后位移超过这个距离才判定为拖动,之内视为点击。
|
|
7
|
+
static const CGFloat PetDragThreshold = 3.0;
|
|
8
|
+
|
|
6
9
|
@implementation PetView
|
|
7
10
|
- (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount {
|
|
8
11
|
if ((self = [super initWithFrame:frame])) {
|
|
@@ -67,9 +70,13 @@
|
|
|
67
70
|
NSTimeInterval interval = PetFrameInterval;
|
|
68
71
|
if (self.lowPowerMode) interval *= 1.5;
|
|
69
72
|
if (self.reduceMotion) interval *= 2.0;
|
|
70
|
-
|
|
73
|
+
// 必须注册到 common modes:performWindowDragWithEvent: 期间主 runloop 处于
|
|
74
|
+
// NSEventTrackingRunLoopMode,只挂在默认 mode 上的定时器不会触发,宠物会
|
|
75
|
+
// 定格在拖动起手的那一帧上,直到松手才继续动。
|
|
76
|
+
self.frameTimer = [NSTimer timerWithTimeInterval:interval repeats:YES
|
|
71
77
|
block:^(NSTimer *timer) { [weakSelf nextFrame:timer]; }];
|
|
72
78
|
self.frameTimer.tolerance = interval * 0.25;
|
|
79
|
+
[NSRunLoop.mainRunLoop addTimer:self.frameTimer forMode:NSRunLoopCommonModes];
|
|
73
80
|
}
|
|
74
81
|
- (void)setLookDirection:(NSInteger)value {
|
|
75
82
|
if (_lookDirection == value) return;
|
|
@@ -258,40 +265,47 @@
|
|
|
258
265
|
[self playRow:3 throughFrame:3 oneShot:YES];
|
|
259
266
|
}
|
|
260
267
|
}
|
|
268
|
+
// 桌宠是 LSUIElement + NSNonactivatingPanel,几乎永远不是活跃应用。不接受 first mouse
|
|
269
|
+
// 的话,AppKit 会把点击非活跃应用窗口的第一次 mouseDown 当成"激活点击"消耗掉,视图
|
|
270
|
+
// 根本收不到——表现为要点两下才拖得动。以前靠 movableByWindowBackground 拖动时不受
|
|
271
|
+
// 影响(窗口背景拖动在窗口服务器层处理,不走视图的 first mouse 判定),关掉它之后
|
|
272
|
+
// 这个缺陷才暴露出来。
|
|
273
|
+
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
|
|
274
|
+
// 精灵区的拖动由 runWindowDragWithEvent: 自己发起,不让 AppKit 的窗口背景拖动同时
|
|
275
|
+
// 介入同一次按下;窗口透明区没有这个覆写,继续走 movableByWindowBackground。
|
|
276
|
+
// 两条路径底层都是窗口服务器拖动,手感一致。
|
|
277
|
+
- (BOOL)mouseDownCanMoveWindow { return NO; }
|
|
261
278
|
- (void)mouseDown:(NSEvent *)event {
|
|
262
279
|
self.agentActive = NO;
|
|
263
280
|
self.dragStartMouse = NSEvent.mouseLocation;
|
|
264
|
-
self.dragStartWindowOrigin = self.window.frame.origin;
|
|
265
|
-
self.draggingPet = NO;
|
|
266
281
|
}
|
|
267
282
|
- (void)mouseDragged:(NSEvent *)event {
|
|
268
283
|
NSPoint current = NSEvent.mouseLocation;
|
|
269
284
|
CGFloat horizontal = current.x - self.dragStartMouse.x;
|
|
270
285
|
CGFloat vertical = current.y - self.dragStartMouse.y;
|
|
271
|
-
if (
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
[self.window
|
|
284
|
-
|
|
286
|
+
if (hypot(horizontal, vertical) < PetDragThreshold) return;
|
|
287
|
+
[self runWindowDragWithEvent:event movingRight:horizontal >= 0];
|
|
288
|
+
}
|
|
289
|
+
// 拖动整段交给窗口服务器:它不依赖应用事件流,所以掠过其他窗口、拖出屏幕、
|
|
290
|
+
// 应用非活跃都不会中断,也不可能丢 mouseUp。函数阻塞到用户松手才返回,
|
|
291
|
+
// 前后两段状态因此天然配对,不存在"开始了但没结束"。
|
|
292
|
+
- (void)runWindowDragWithEvent:(NSEvent *)event movingRight:(BOOL)movingRight {
|
|
293
|
+
self.draggingPet = YES;
|
|
294
|
+
if (self.pocketHoverChanged) self.pocketHoverChanged(NO);
|
|
295
|
+
if (self.dragStateChanged) self.dragStateChanged(YES);
|
|
296
|
+
[self playRow:movingRight ? 1 : 2 throughFrame:7 oneShot:NO];
|
|
297
|
+
|
|
298
|
+
[self.window performWindowDragWithEvent:event];
|
|
299
|
+
|
|
300
|
+
self.draggingPet = NO;
|
|
301
|
+
if (self.dragStateChanged) self.dragStateChanged(NO);
|
|
302
|
+
[self playRow:0 throughFrame:5 oneShot:NO];
|
|
285
303
|
}
|
|
304
|
+
// 拖动会话(含 mouseUp)已被 performWindowDragWithEvent: 消费,所以能走到这里
|
|
305
|
+
// 就说明本次按下没有拖动过,不需要额外的标志来区分。
|
|
286
306
|
- (void)mouseUp:(NSEvent *)event {
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
if (self.dragStateChanged) self.dragStateChanged(NO);
|
|
290
|
-
[self playRow:0 throughFrame:5 oneShot:NO];
|
|
291
|
-
} else {
|
|
292
|
-
// 第 8 行未标注的动作作为点击反馈,完整利用剩余素材。
|
|
293
|
-
[self playRow:7 throughFrame:5 oneShot:YES];
|
|
294
|
-
}
|
|
307
|
+
[self playRow:7 throughFrame:5 oneShot:YES];
|
|
308
|
+
if (self.statusToggleRequested) self.statusToggleRequested();
|
|
295
309
|
}
|
|
296
310
|
- (void)drawRect:(NSRect)dirtyRect {
|
|
297
311
|
CGFloat cellWidth = self.sheet.size.width / 8.0;
|
|
@@ -480,6 +494,12 @@
|
|
|
480
494
|
[menu addItem:NSMenuItem.separatorItem];
|
|
481
495
|
NSMenuItem *refreshItem = [menu addItemWithTitle:@"刷新用量" action:@selector(refreshUsage:) keyEquivalent:@"r"];
|
|
482
496
|
refreshItem.target = NSApp.delegate;
|
|
497
|
+
// 点击宠物本体也能折叠气泡,但那个交互没有任何视觉提示。这里留一个可发现的入口。
|
|
498
|
+
[self addPersistentSwitchToMenu:menu
|
|
499
|
+
title:@"显示消息气泡"
|
|
500
|
+
checked:[NSUserDefaults.standardUserDefaults boolForKey:StatusBubbleExpandedKey]
|
|
501
|
+
action:@selector(toggleStatusBubbleFromMenu:)
|
|
502
|
+
tag:0];
|
|
483
503
|
[self addPersistentSwitchToMenu:menu
|
|
484
504
|
title:@"记录本地额度历史"
|
|
485
505
|
checked:[NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]
|
|
@@ -54,6 +54,18 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
54
54
|
return NSMakeRect(logical.origin.x * QuotaScale, logical.origin.y * QuotaScale,
|
|
55
55
|
logical.size.width * QuotaScale, logical.size.height * QuotaScale);
|
|
56
56
|
}
|
|
57
|
+
- (NSRect)logicalSummaryRect {
|
|
58
|
+
return NSMakeRect(20, 372, QuotaLogicalWidth - 40, 86);
|
|
59
|
+
}
|
|
60
|
+
- (NSRect)logicalSummaryCellRectAtIndex:(NSUInteger)index {
|
|
61
|
+
NSRect summary = [self logicalSummaryRect];
|
|
62
|
+
const CGFloat widths[] = {280, 280, 160};
|
|
63
|
+
CGFloat x = NSMinX(summary);
|
|
64
|
+
for (NSUInteger current = 0; current < MIN(index, (NSUInteger)3); current++) {
|
|
65
|
+
x += widths[current];
|
|
66
|
+
}
|
|
67
|
+
return index < 3 ? NSMakeRect(x, NSMinY(summary), widths[index], NSHeight(summary)) : NSZeroRect;
|
|
68
|
+
}
|
|
57
69
|
- (void)mouseMoved:(NSEvent *)event {
|
|
58
70
|
NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
|
|
59
71
|
BOOL hovering = NSPointInRect(point, [self refreshRect]);
|
|
@@ -108,14 +120,16 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
108
120
|
return [NSString stringWithFormat:@"%.0f", value];
|
|
109
121
|
}
|
|
110
122
|
// 两个窗口共用。resets_at 是整分对齐的,带秒只会多占宽度。
|
|
111
|
-
- (NSString *)
|
|
112
|
-
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
|
|
113
|
-
if (!reset) return @"--";
|
|
123
|
+
- (NSString *)clockText:(NSTimeInterval)value {
|
|
114
124
|
NSDateFormatter *formatter = [NSDateFormatter new];
|
|
115
125
|
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
|
|
116
126
|
formatter.timeZone = NSTimeZone.localTimeZone;
|
|
117
127
|
formatter.dateFormat = @"M/d HH:mm";
|
|
118
|
-
return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:
|
|
128
|
+
return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:value]];
|
|
129
|
+
}
|
|
130
|
+
- (NSString *)resetText:(NSDictionary *)quota {
|
|
131
|
+
NSNumber *reset = [quota[@"resets_at"] isKindOfClass:NSNumber.class] ? quota[@"resets_at"] : nil;
|
|
132
|
+
return reset ? [self clockText:reset.doubleValue] : @"--";
|
|
119
133
|
}
|
|
120
134
|
// 在线 = 这一家还有活着的客户端,和有没有额度数据无关:额度会一直缓存着,
|
|
121
135
|
// 拿它当在线信号会恒亮。身份不明的老客户端无法归属到某一家,保守地都算在线。
|
|
@@ -129,19 +143,8 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
129
143
|
- (NSColor *)agentStatusColor {
|
|
130
144
|
return self.activeAgentCount > 0 ? NSColor.systemGreenColor : self.secondaryColor;
|
|
131
145
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
// 按各自 resets_at 算出来的数不在同一区间上,相加得不到任何有意义的量。
|
|
135
|
-
- (NSDictionary *)combinedTokens:(NSString *)key {
|
|
136
|
-
NSDictionary *codex = [self tokenTotals:self.codexUsage key:key];
|
|
137
|
-
NSDictionary *claude = [self tokenTotals:self.claudeUsage key:key];
|
|
138
|
-
NSNumber *codexTotal = [codex[@"total_tokens"] isKindOfClass:NSNumber.class]
|
|
139
|
-
? codex[@"total_tokens"] : nil;
|
|
140
|
-
NSNumber *claudeTotal = [claude[@"total_tokens"] isKindOfClass:NSNumber.class]
|
|
141
|
-
? claude[@"total_tokens"] : nil;
|
|
142
|
-
if (!codexTotal && !claudeTotal) return @{};
|
|
143
|
-
return @{@"total_tokens": @(codexTotal.unsignedLongLongValue +
|
|
144
|
-
claudeTotal.unsignedLongLongValue)};
|
|
146
|
+
- (NSString *)formattedTokenCountForUsage:(NSDictionary *)usage key:(NSString *)key {
|
|
147
|
+
return [self formattedTokenCount:[self tokenTotals:usage key:key] ?: @{}];
|
|
145
148
|
}
|
|
146
149
|
- (NSNumber *)usedForQuota:(NSDictionary *)quota usedKey:(NSString *)usedKey {
|
|
147
150
|
NSNumber *used = [quota[usedKey] isKindOfClass:NSNumber.class] ? quota[usedKey] : nil;
|
|
@@ -196,7 +199,10 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
196
199
|
NSDictionary *weekTokens = [self tokenTotals:usage key:@"week"];
|
|
197
200
|
NSNumber *fiveUsed = [self usedForQuota:five usedKey:usedKey];
|
|
198
201
|
NSNumber *weekUsed = [self usedForQuota:week usedKey:usedKey];
|
|
199
|
-
|
|
202
|
+
// 额度被拒之后官方不再报告任何窗口,留在手里的百分比既过期、指向的结论又正好相反
|
|
203
|
+
// (账号是共享的,别人用完时本机的数字纹丝不动)。这时按 0 显示,并把状态说清楚。
|
|
204
|
+
BOOL exhausted = [usage[@"exhaustedAt"] isKindOfClass:NSNumber.class];
|
|
205
|
+
BOOL hasData = fiveUsed || weekUsed || fiveTokens || weekTokens || exhausted;
|
|
200
206
|
BOOL online = [self isProviderOnline:name];
|
|
201
207
|
|
|
202
208
|
NSBezierPath *cardPath = [NSBezierPath bezierPathWithRoundedRect:card xRadius:18 yRadius:18];
|
|
@@ -231,9 +237,12 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
231
237
|
}
|
|
232
238
|
[name drawInRect:NSMakeRect(NSMinX(card) + 94, NSMinY(card) + 84, 88, 30)
|
|
233
239
|
withAttributes:[self textAttributesWithSize:22 color:primary weight:NSFontWeightBold]];
|
|
234
|
-
//
|
|
235
|
-
|
|
236
|
-
|
|
240
|
+
// 四态:额度被拒 → 额度已用尽(压过在线,这是此刻唯一要紧的信息);没有任何额度
|
|
241
|
+
// 数据 → 等待数据;有数据但客户端已退出 → 离线;两者都有 → 在线。
|
|
242
|
+
NSString *statusText = exhausted ? @"额度已用尽"
|
|
243
|
+
: (!hasData ? @"等待数据" : (online ? @"● 在线" : @"离线"));
|
|
244
|
+
NSColor *statusColor = exhausted ? NSColor.systemOrangeColor
|
|
245
|
+
: (online && hasData ? NSColor.systemGreenColor : secondary);
|
|
237
246
|
NSDictionary *statusAttributes = [self textAttributesWithSize:11 color:statusColor
|
|
238
247
|
weight:NSFontWeightMedium];
|
|
239
248
|
CGFloat statusWidth = ceil([statusText sizeWithAttributes:statusAttributes].width) + 18;
|
|
@@ -244,37 +253,46 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
244
253
|
// 层级:官方剩余额度是订阅限额的权威值,占主位;本机 Token 是参考量,降一级并用
|
|
245
254
|
// 强调色区分;重置时间最小。反过来会让最抢眼的数字恰好是最不该照着做决定的那个。
|
|
246
255
|
NSArray<NSDictionary *> *windows = @[
|
|
247
|
-
@{@"x": @(NSMinX(card) + 214), @"title": @"5
|
|
248
|
-
@"tokens": fiveTokens ?: @{}, @"used": fiveUsed ?: NSNull.null
|
|
249
|
-
|
|
250
|
-
|
|
256
|
+
@{@"x": @(NSMinX(card) + 214), @"title": @"5 小时窗口", @"quota": five ?: @{},
|
|
257
|
+
@"tokens": fiveTokens ?: @{}, @"used": fiveUsed ?: NSNull.null,
|
|
258
|
+
@"rolling": @"无官方窗口 · 近 5 小时"},
|
|
259
|
+
@{@"x": @(NSMinX(card) + 394), @"title": @"7 天窗口", @"quota": week ?: @{},
|
|
260
|
+
@"tokens": weekTokens ?: @{}, @"used": weekUsed ?: NSNull.null,
|
|
261
|
+
@"rolling": @"无官方窗口 · 近 7 天"}
|
|
251
262
|
];
|
|
252
263
|
for (NSDictionary *window in windows) {
|
|
253
264
|
CGFloat x = [window[@"x"] doubleValue];
|
|
254
265
|
[window[@"title"] drawInRect:NSMakeRect(x, NSMinY(card) + 114, 130, 20)
|
|
255
266
|
withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
|
|
256
267
|
NSNumber *used = [window[@"used"] isKindOfClass:NSNumber.class] ? window[@"used"] : nil;
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
268
|
+
double remaining = exhausted ? 0 : (used ? 100.0 - used.doubleValue : 0);
|
|
269
|
+
NSString *official = (used || exhausted)
|
|
270
|
+
? [NSString stringWithFormat:@"%.0f%%", remaining] : @"--";
|
|
271
|
+
// 百分比是"剩余"、Token 是"已用",方向相反。后缀直接贴在数字右侧、
|
|
272
|
+
// 前缀写进 Token 行,否则两个数字并排看会被当成同一口径。
|
|
273
|
+
NSDictionary *valueAttributes = [self textAttributesWithSize:25
|
|
274
|
+
color:exhausted ? NSColor.systemOrangeColor : primary
|
|
275
|
+
weight:NSFontWeightBold];
|
|
276
|
+
CGFloat valueWidth = ceil([official sizeWithAttributes:valueAttributes].width);
|
|
277
|
+
[official drawInRect:NSMakeRect(x, NSMinY(card) + 74, valueWidth + 4, 34)
|
|
278
|
+
withAttributes:valueAttributes];
|
|
279
|
+
[@"剩余" drawInRect:NSMakeRect(x + valueWidth + 7, NSMinY(card) + 78, 60, 20)
|
|
280
|
+
withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
|
|
281
|
+
NSString *tokenText = [NSString stringWithFormat:@"已用 Token %@",
|
|
264
282
|
[self formattedTokenCount:window[@"tokens"]]];
|
|
265
|
-
[tokenText drawInRect:NSMakeRect(x, NSMinY(card) +
|
|
266
|
-
withAttributes:[self textAttributesWithSize:
|
|
267
|
-
//
|
|
268
|
-
//
|
|
283
|
+
[tokenText drawInRect:NSMakeRect(x, NSMinY(card) + 46, 150, 22)
|
|
284
|
+
withAttributes:[self textAttributesWithSize:14 color:color weight:NSFontWeightSemibold]];
|
|
285
|
+
// 官方窗口拿不到时(账号没有这个窗口、或响应里没带),Token 走的是本机滚动窗口。
|
|
286
|
+
// 说清楚这一行的口径,比留一个 `--` 让人以为是渲染坏了要好。
|
|
269
287
|
NSString *resetValue = [self resetText:window[@"quota"]];
|
|
270
288
|
NSString *reset = [resetValue isEqualToString:@"--"]
|
|
271
|
-
? @"
|
|
272
|
-
[reset drawInRect:NSMakeRect(x, NSMinY(card) +
|
|
289
|
+
? window[@"rolling"] : [NSString stringWithFormat:@"额度重置 %@", resetValue];
|
|
290
|
+
[reset drawInRect:NSMakeRect(x, NSMinY(card) + 22, 150, 18)
|
|
273
291
|
withAttributes:[self textAttributesWithSize:11 color:secondary weight:NSFontWeightRegular]];
|
|
274
292
|
}
|
|
275
293
|
|
|
276
294
|
CGFloat trendX = NSMinX(card) + 564;
|
|
277
|
-
[@"过去 7
|
|
295
|
+
[@"过去 7 天已用趋势" drawInRect:NSMakeRect(trendX, NSMinY(card) + 114, 145, 20)
|
|
278
296
|
withAttributes:[self textAttributesWithSize:13 color:secondary weight:NSFontWeightRegular]];
|
|
279
297
|
NSArray<NSNumber *> *history = [name isEqualToString:@"Codex"] ? self.codexHistory : self.claudeHistory;
|
|
280
298
|
[self drawUsageBars:history inRect:NSMakeRect(trendX, NSMinY(card) + 42, 135, 64) color:color];
|
|
@@ -282,7 +300,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
282
300
|
if (self.historyEnabled && history.count > 0) {
|
|
283
301
|
double peak = 0;
|
|
284
302
|
for (NSNumber *remaining in history) peak = fmax(peak, 100.0 - remaining.doubleValue);
|
|
285
|
-
trendDetail = [NSString stringWithFormat:@"
|
|
303
|
+
trendDetail = [NSString stringWithFormat:@"峰值已用 %.0f%%", peak];
|
|
286
304
|
}
|
|
287
305
|
[trendDetail drawInRect:NSMakeRect(trendX, NSMinY(card) + 18, 145, 18)
|
|
288
306
|
withAttributes:[self textAttributesWithSize:11 color:secondary weight:NSFontWeightRegular]];
|
|
@@ -346,41 +364,61 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
346
364
|
[recentlyRefreshed ? @"✓" : @"↻" drawInRect:NSInsetRect(refreshRect, 8, 4)
|
|
347
365
|
withAttributes:[self textAttributesWithSize:19 color:[NSColor colorWithWhite:0.9 alpha:1] weight:NSFontWeightRegular]];
|
|
348
366
|
|
|
349
|
-
NSRect summary =
|
|
367
|
+
NSRect summary = [self logicalSummaryRect];
|
|
350
368
|
NSBezierPath *summaryPath = [NSBezierPath bezierPathWithRoundedRect:summary xRadius:18 yRadius:18];
|
|
351
369
|
[[NSColor colorWithWhite:1 alpha:0.065] setFill];
|
|
352
370
|
[summaryPath fill];
|
|
353
371
|
[[NSColor colorWithWhite:1 alpha:0.16] setStroke];
|
|
354
372
|
[summaryPath stroke];
|
|
355
373
|
|
|
356
|
-
//
|
|
357
|
-
//
|
|
374
|
+
// 今日与最近 7 天都按 Provider 分开展示。底层本来就是两套独立的自然日统计,
|
|
375
|
+
// 不在展示层相加,避免用户无法判断 Token 来自 Codex 还是 Claude。
|
|
376
|
+
// 两个统计格各占 280pt,刷新格压缩为 160pt,把主要空间留给双 Provider 数据。
|
|
358
377
|
NSArray<NSDictionary *> *cells = @[
|
|
359
|
-
@{@"icon": @"◔", @"
|
|
360
|
-
|
|
361
|
-
@{@"icon": @"◉", @"tint": cyan, @"value": [self formattedTokenCount:
|
|
362
|
-
[self combinedTokens:@"recentWeek"]], @"label": @"最近 7 天"},
|
|
378
|
+
@{@"icon": @"◔", @"key": @"today", @"label": @"今日已用 Token"},
|
|
379
|
+
@{@"icon": @"◉", @"key": @"recentWeek", @"label": @"近 7 天已用 Token"},
|
|
363
380
|
@{@"icon": @"◷", @"tint": NSColor.systemPurpleColor, @"value": [self refreshAgeText],
|
|
364
381
|
@"label": @"数据刷新"}
|
|
365
382
|
];
|
|
366
|
-
CGFloat cellWidth = NSWidth(summary) / cells.count;
|
|
367
383
|
[[NSColor colorWithWhite:1 alpha:0.10] setStroke];
|
|
368
384
|
for (NSUInteger index = 1; index < cells.count; index++) {
|
|
369
|
-
CGFloat x = NSMinX(
|
|
385
|
+
CGFloat x = NSMinX([self logicalSummaryCellRectAtIndex:index]);
|
|
370
386
|
[NSBezierPath strokeLineFromPoint:NSMakePoint(x, NSMinY(summary) + 16)
|
|
371
387
|
toPoint:NSMakePoint(x, NSMaxY(summary) - 16)];
|
|
372
388
|
}
|
|
373
389
|
for (NSUInteger index = 0; index < cells.count; index++) {
|
|
374
390
|
NSDictionary *cell = cells[index];
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
withAttributes:[self textAttributesWithSize:12 color:secondary
|
|
391
|
+
NSRect cellRect = [self logicalSummaryCellRectAtIndex:index];
|
|
392
|
+
CGFloat x = NSMinX(cellRect);
|
|
393
|
+
BOOL isTokenWindow = [cell[@"key"] isKindOfClass:NSString.class];
|
|
394
|
+
NSColor *tint = isTokenWindow ? cyan : cell[@"tint"];
|
|
395
|
+
CGFloat iconX = x + (isTokenWindow ? 26 : 16);
|
|
396
|
+
[cell[@"icon"] drawInRect:NSMakeRect(iconX, NSMinY(summary) + 23, 42, 42)
|
|
397
|
+
withAttributes:[self textAttributesWithSize:30 color:tint
|
|
383
398
|
weight:NSFontWeightRegular]];
|
|
399
|
+
if (isTokenWindow) {
|
|
400
|
+
NSString *key = cell[@"key"];
|
|
401
|
+
NSColor *claudeColor = [NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1];
|
|
402
|
+
[cell[@"label"] drawInRect:NSMakeRect(x + 74, NSMinY(summary) + 59, 180, 18)
|
|
403
|
+
withAttributes:[self textAttributesWithSize:11 color:secondary
|
|
404
|
+
weight:NSFontWeightRegular]];
|
|
405
|
+
[@"Codex" drawInRect:NSMakeRect(x + 74, NSMinY(summary) + 35, 54, 20)
|
|
406
|
+
withAttributes:[self textAttributesWithSize:12 color:cyan weight:NSFontWeightMedium]];
|
|
407
|
+
[[self formattedTokenCountForUsage:self.codexUsage key:key]
|
|
408
|
+
drawInRect:NSMakeRect(x + 126, NSMinY(summary) + 33, 92, 23)
|
|
409
|
+
withAttributes:[self textAttributesWithSize:16 color:primary weight:NSFontWeightBold]];
|
|
410
|
+
[@"Claude" drawInRect:NSMakeRect(x + 74, NSMinY(summary) + 12, 54, 20)
|
|
411
|
+
withAttributes:[self textAttributesWithSize:12 color:claudeColor weight:NSFontWeightMedium]];
|
|
412
|
+
[[self formattedTokenCountForUsage:self.claudeUsage key:key]
|
|
413
|
+
drawInRect:NSMakeRect(x + 126, NSMinY(summary) + 10, 92, 23)
|
|
414
|
+
withAttributes:[self textAttributesWithSize:16 color:primary weight:NSFontWeightBold]];
|
|
415
|
+
} else {
|
|
416
|
+
[cell[@"value"] drawInRect:NSMakeRect(x + 56, NSMinY(summary) + 40, 96, 28)
|
|
417
|
+
withAttributes:[self textAttributesWithSize:20 color:primary weight:NSFontWeightBold]];
|
|
418
|
+
[cell[@"label"] drawInRect:NSMakeRect(x + 56, NSMinY(summary) + 17, 96, 20)
|
|
419
|
+
withAttributes:[self textAttributesWithSize:11 color:secondary
|
|
420
|
+
weight:NSFontWeightRegular]];
|
|
421
|
+
}
|
|
384
422
|
}
|
|
385
423
|
|
|
386
424
|
[self drawProvider:@"Codex" usage:self.codexUsage usedKey:@"used_percent"
|
|
@@ -388,7 +426,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
|
|
|
388
426
|
[self drawProvider:@"Claude" usage:self.claudeUsage usedKey:@"used_percentage"
|
|
389
427
|
color:[NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1]
|
|
390
428
|
cardRect:NSMakeRect(20, 44, QuotaLogicalWidth - 40, 152)];
|
|
391
|
-
NSString *footer = @"ⓘ Token
|
|
429
|
+
NSString *footer = @"ⓘ 百分比 = 官方订阅额度的剩余比例;Token = 本机统计的已用量,两者口径不同";
|
|
392
430
|
// 卡片底边在 y=44,原来 footer 顶到 44 完全没有间隙。下移到与卡片留约 8pt,
|
|
393
431
|
// 同时底部留白 16pt,和顶部标题的留白大致对称。
|
|
394
432
|
[footer drawInRect:NSMakeRect(28, 16, 650, 20)
|