cc-pets 1.0.3 → 1.0.4
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 +5 -0
- package/README.md +12 -2
- package/Sources/CCPets/CCPetsAppDelegate.h +4 -2
- package/Sources/CCPets/CCPetsAppDelegate.m +65 -11
- package/Sources/CCPets/CCPetsCleanup.h +7 -0
- package/Sources/CCPets/CCPetsCleanup.m +126 -0
- package/Sources/CCPets/CCPetsImageLoader.h +4 -0
- package/Sources/CCPets/CCPetsImageLoader.m +36 -0
- package/Sources/CCPets/CCPetsPaths.m +4 -4
- package/Sources/CCPets/CCPetsUsage.h +2 -0
- package/Sources/CCPets/CCPetsUsage.m +13 -0
- package/Sources/CCPets/CCPetsUsageMonitor.h +10 -0
- package/Sources/CCPets/CCPetsUsageMonitor.m +163 -0
- package/Sources/CCPets/PetView.h +3 -1
- package/Sources/CCPets/PetView.m +40 -7
- package/Sources/CCPets/main.m +4 -0
- package/bin/cc-pets +5 -0
- package/package.json +1 -1
- package/scripts/build.sh +2 -0
- package/scripts/uninstall-app.sh +9 -0
- package/scripts/uninstall-shell-integration.sh +50 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,11 @@
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
- 新增 `cc-pets clean` 和带确认的 `cc-pets uninstall --purge`,并自动清理测试临时目录与过期运行状态。
|
|
8
|
+
- 更新日志每次更新前截断,并限制为最近 1 MB,避免长期残留增长。
|
|
9
|
+
- Codex/Claude 额度读取改为 FSEvents/VNODE 事件监听,并保留 120 秒容错刷新,降低空闲文件扫描与 JSON 解析。
|
|
10
|
+
- 精灵图按显示尺寸降采样,菜单预览改用有限缓存;待审批记录增加 TTL 与容量上限。
|
|
11
|
+
- 低电量模式和系统“减少动态效果”开启时自动降低动画刷新频率。
|
|
7
12
|
- 新增可展开折叠的玻璃 Agent 状态卡片、活跃 CLI 会话数徽标和可选的完成、失败、审批系统通知。
|
|
8
13
|
- 历史记录与系统通知设置改用右侧高对比度迷你开关,支持在菜单保持展开时连续调整。
|
|
9
14
|
- 折叠圆钮固定锚定在桌宠头部右上区域,展开和折叠时不再跳动。
|
package/README.md
CHANGED
|
@@ -134,13 +134,17 @@ cc-pets install
|
|
|
134
134
|
```bash
|
|
135
135
|
git clone https://gitee.com/wangxinyusqn/cc-pets.git
|
|
136
136
|
cd cc-pets
|
|
137
|
-
npm install -g . --
|
|
137
|
+
npm install -g . --ignore-scripts
|
|
138
|
+
cc-pets install
|
|
138
139
|
# 首次安装后新开一个终端
|
|
139
140
|
codex
|
|
140
141
|
# 或
|
|
141
142
|
claude
|
|
142
143
|
```
|
|
143
144
|
|
|
145
|
+
npm 12 会把本地目录安装识别为项目范围安装,不接受命令行传入的 `--allow-scripts`。
|
|
146
|
+
因此本地源码安装显式跳过生命周期脚本,再通过 `cc-pets install` 执行可重复的初始化流程。
|
|
147
|
+
|
|
144
148
|
两种方式都会安装 `cc-pets`、`codex-with-pet` 和 `claude-with-pet`。
|
|
145
149
|
npm 的安装后脚本会自动构建原生应用、安装两套 Agent Hooks,并向 `~/.zshrc` 追加带明确标记的
|
|
146
150
|
`codex` 与 `claude` alias,不会覆盖真实的 CLI 二进制。首次安装需要新开终端让 alias 生效;以后升级只需执行 npm 命令。
|
|
@@ -202,6 +206,9 @@ cc-pets --status
|
|
|
202
206
|
# 查看本机额度历史 JSON
|
|
203
207
|
cc-pets --history
|
|
204
208
|
|
|
209
|
+
# 清理可重建的临时状态、更新日志和构建缓存,保留历史、配置与偏好
|
|
210
|
+
cc-pets clean
|
|
211
|
+
|
|
205
212
|
# 从标准输入发送第三方 Provider 状态事件
|
|
206
213
|
printf '%s' '{"schemaVersion":1,"provider":"MyAgent","state":"thinking"}' \
|
|
207
214
|
| cc-pets provider-event
|
|
@@ -212,6 +219,9 @@ cc-pets install
|
|
|
212
219
|
# 安全移除 Hooks、恢复 Claude status line,并清理 shell alias
|
|
213
220
|
cc-pets uninstall
|
|
214
221
|
|
|
222
|
+
# 完整移除集成、应用和全部本地数据;执行前会再次确认
|
|
223
|
+
cc-pets uninstall --purge
|
|
224
|
+
|
|
215
225
|
# 仅删除 ~/Applications 中的 macOS 应用(不会删除 npm 包或 Hooks)
|
|
216
226
|
cc-pets uninstall-app
|
|
217
227
|
|
|
@@ -242,7 +252,7 @@ Claude.ai Pro/Max 订阅账号,并在会话完成首次 API 响应后出现;
|
|
|
242
252
|
额度详情面板使用青色区分 Codex、紫色区分 Claude。5 小时剩余额度使用进度条,周剩余
|
|
243
253
|
额度使用环形进度,右侧展示对应的周重置时间。服务端的 Unix 时间戳会使用 Mac 当前系统时区格式化为
|
|
244
254
|
`M/d HH:mm:ss`;因此它与 CLI 中标注其他时区的同一时刻可能日期和小时不同,但代表同一个真实时间。
|
|
245
|
-
|
|
255
|
+
应用通过文件事件实时读取额度,并保留 120 秒容错刷新;右上角刷新按钮也可立即读取本地数据。Codex 数据随本地 session 更新,Claude 数据则要等 Claude Code
|
|
246
256
|
下一次把 `rate_limits` 传给 status line 后才会变化,按钮不会主动请求 Claude 服务端。
|
|
247
257
|
面板使用原生 AppKit 毛玻璃材质,以紧凑悬浮卡片形式显示在桌宠左上方,并优先使用本机官方 Codex、Claude 应用
|
|
248
258
|
图标。鼠标从口袋移动到面板后可继续停留查看,移出两者后面板会延迟收起;拖动桌宠时
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#import <Cocoa/Cocoa.h>
|
|
2
2
|
#import "PetView.h"
|
|
3
3
|
#import "QuotaDashboardView.h"
|
|
4
|
-
#import "
|
|
4
|
+
#import "CCPetsUsageMonitor.h"
|
|
5
5
|
|
|
6
6
|
@interface AppDelegate : NSObject <NSApplicationDelegate>
|
|
7
7
|
@property NSPanel *panel;
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
@property BOOL petDragging;
|
|
32
32
|
@property NSString *binaryDirectory;
|
|
33
33
|
@property PetView *petView;
|
|
34
|
-
@property
|
|
34
|
+
@property CCPetsUsageMonitor *usageMonitor;
|
|
35
35
|
@property unsigned long long agentEventOffset;
|
|
36
36
|
@property NSMutableData *agentEventPartialLine;
|
|
37
37
|
@property dispatch_source_t agentEventSource;
|
|
@@ -46,7 +46,9 @@
|
|
|
46
46
|
- (void)hideQuotaDashboardIfNeeded;
|
|
47
47
|
- (void)positionAgentStatus;
|
|
48
48
|
- (void)showAgentStatusForRecord:(NSDictionary *)record;
|
|
49
|
+
- (void)prunePendingApprovalRecords;
|
|
49
50
|
- (void)toggleAgentStatusBubble:(id)sender;
|
|
50
51
|
- (void)refreshUsage:(id)sender;
|
|
52
|
+
- (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage;
|
|
51
53
|
- (void)switchPetToID:(NSString *)petID;
|
|
52
54
|
@end
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
#import "CCPetsVersion.h"
|
|
4
4
|
#import "CCPetsEvents.h"
|
|
5
5
|
#import "CCPetsQuotaHistory.h"
|
|
6
|
+
#import "CCPetsImageLoader.h"
|
|
6
7
|
#import "MenuToggleSwitch.h"
|
|
7
8
|
#import <UserNotifications/UserNotifications.h>
|
|
8
9
|
#import <signal.h>
|
|
@@ -11,6 +12,25 @@
|
|
|
11
12
|
#import <unistd.h>
|
|
12
13
|
#import <errno.h>
|
|
13
14
|
|
|
15
|
+
static const NSTimeInterval PendingApprovalTTL = 24 * 60 * 60;
|
|
16
|
+
static const NSUInteger PendingApprovalLimit = 100;
|
|
17
|
+
static const unsigned long long UpdateLogSizeLimit = 1024 * 1024;
|
|
18
|
+
|
|
19
|
+
static void TrimUpdateLog(NSString *path) {
|
|
20
|
+
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
|
|
21
|
+
if (!handle) return;
|
|
22
|
+
unsigned long long size = [handle seekToEndOfFile];
|
|
23
|
+
if (size <= UpdateLogSizeLimit) {
|
|
24
|
+
[handle closeFile];
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
[handle seekToFileOffset:size - UpdateLogSizeLimit];
|
|
28
|
+
NSData *tail = [handle readDataToEndOfFile];
|
|
29
|
+
[handle closeFile];
|
|
30
|
+
[tail writeToFile:path options:NSDataWritingAtomic error:nil];
|
|
31
|
+
chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
32
|
+
}
|
|
33
|
+
|
|
14
34
|
@implementation AppDelegate
|
|
15
35
|
- (NSString *)applicationSupportDirectory {
|
|
16
36
|
return ApplicationSupportDirectory();
|
|
@@ -89,9 +109,8 @@
|
|
|
89
109
|
return;
|
|
90
110
|
}
|
|
91
111
|
NSString *logPath = [supportDirectory stringByAppendingPathComponent:@"update.log"];
|
|
92
|
-
[
|
|
93
|
-
|
|
94
|
-
}];
|
|
112
|
+
[NSData.data writeToFile:logPath options:NSDataWritingAtomic error:nil];
|
|
113
|
+
chmod(logPath.fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
95
114
|
NSFileHandle *logHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
|
|
96
115
|
if (!logHandle) {
|
|
97
116
|
[self showUpdateAlertWithTitle:@"无法自动更新" message:@"无法创建更新日志。"];
|
|
@@ -123,6 +142,7 @@
|
|
|
123
142
|
__weak typeof(self) weakSelf = self;
|
|
124
143
|
task.terminationHandler = ^(NSTask *finishedTask) {
|
|
125
144
|
[logHandle closeFile];
|
|
145
|
+
TrimUpdateLog(logPath);
|
|
126
146
|
dispatch_async(dispatch_get_main_queue(), ^{
|
|
127
147
|
typeof(self) strongSelf = weakSelf;
|
|
128
148
|
if (!strongSelf) return;
|
|
@@ -431,6 +451,29 @@
|
|
|
431
451
|
? [NSString stringWithFormat:@"%@:%@", provider, session]
|
|
432
452
|
: provider;
|
|
433
453
|
}
|
|
454
|
+
- (void)prunePendingApprovalRecords {
|
|
455
|
+
NSTimeInterval cutoff = NSDate.date.timeIntervalSince1970 - PendingApprovalTTL;
|
|
456
|
+
for (NSString *key in self.pendingApprovalRecords.allKeys) {
|
|
457
|
+
NSDictionary *record = self.pendingApprovalRecords[key];
|
|
458
|
+
if ([record[@"timestamp"] doubleValue] < cutoff) {
|
|
459
|
+
[self.pendingApprovalRecords removeObjectForKey:key];
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
if (self.pendingApprovalRecords.count <= PendingApprovalLimit) return;
|
|
463
|
+
NSArray<NSDictionary *> *oldestFirst = [self.pendingApprovalRecords.allValues
|
|
464
|
+
sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
465
|
+
NSTimeInterval leftTime = [left[@"timestamp"] doubleValue];
|
|
466
|
+
NSTimeInterval rightTime = [right[@"timestamp"] doubleValue];
|
|
467
|
+
if (leftTime < rightTime) return NSOrderedAscending;
|
|
468
|
+
if (leftTime > rightTime) return NSOrderedDescending;
|
|
469
|
+
return NSOrderedSame;
|
|
470
|
+
}];
|
|
471
|
+
NSUInteger removeCount = oldestFirst.count - PendingApprovalLimit;
|
|
472
|
+
for (NSUInteger index = 0; index < removeCount; index++) {
|
|
473
|
+
NSString *key = [self approvalKeyForRecord:oldestFirst[index]];
|
|
474
|
+
[self.pendingApprovalRecords removeObjectForKey:key];
|
|
475
|
+
}
|
|
476
|
+
}
|
|
434
477
|
- (NSDictionary *)latestPendingApprovalRecord {
|
|
435
478
|
NSDictionary *latest = nil;
|
|
436
479
|
for (NSDictionary *record in self.pendingApprovalRecords.allValues) {
|
|
@@ -614,7 +657,8 @@
|
|
|
614
657
|
NSDictionary *selectedOption = [self petOptionWithID:selected inOptions:petOptions] ?: petOptions.firstObject;
|
|
615
658
|
selected = selectedOption[@"id"];
|
|
616
659
|
NSString *spritePath = selectedOption[@"path"];
|
|
617
|
-
NSImage *image =
|
|
660
|
+
NSImage *image = LoadPetSpriteImage(spritePath, NSMakeSize(140, 150),
|
|
661
|
+
[selectedOption[@"spriteRowCount"] integerValue] ?: 9);
|
|
618
662
|
if (!image) {
|
|
619
663
|
fprintf(stderr, "无法读取桌宠素材: %s\n", spritePath.UTF8String);
|
|
620
664
|
[NSApp terminate:nil];
|
|
@@ -807,10 +851,13 @@
|
|
|
807
851
|
NSRect visible = screen.visibleFrame;
|
|
808
852
|
[self.panel setFrameOrigin:NSMakePoint(NSMaxX(visible) - size.width - 24, NSMinY(visible) + 18)];
|
|
809
853
|
[self.panel orderFrontRegardless];
|
|
810
|
-
self.
|
|
854
|
+
self.usageMonitor = [CCPetsUsageMonitor new];
|
|
811
855
|
self.agentEventPartialLine = [NSMutableData data];
|
|
812
856
|
self.pendingApprovalRecords = [NSMutableDictionary dictionary];
|
|
813
|
-
|
|
857
|
+
self.usageMonitor.changeHandler = ^(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
|
|
858
|
+
[weakSelf applyCodexUsage:codexUsage claudeUsage:claudeUsage];
|
|
859
|
+
};
|
|
860
|
+
[self.usageMonitor start];
|
|
814
861
|
if ([NSProcessInfo.processInfo.arguments containsObject:@"--preview-dashboard"]) {
|
|
815
862
|
self.pocketHovering = YES;
|
|
816
863
|
[self showQuotaDashboard];
|
|
@@ -910,9 +957,9 @@
|
|
|
910
957
|
NSArray<NSDictionary *> *options = [self discoverPetOptions];
|
|
911
958
|
NSDictionary *option = [self petOptionWithID:petID inOptions:options];
|
|
912
959
|
if (!option) return;
|
|
913
|
-
NSImage *image = [[NSImage alloc] initWithContentsOfFile:option[@"path"]];
|
|
914
|
-
if (!image) return;
|
|
915
960
|
NSInteger spriteRowCount = [option[@"spriteRowCount"] integerValue] ?: 9;
|
|
961
|
+
NSImage *image = LoadPetSpriteImage(option[@"path"], NSMakeSize(140, 150), spriteRowCount);
|
|
962
|
+
if (!image) return;
|
|
916
963
|
[self.petView applySheet:image petID:petID rowCount:spriteRowCount];
|
|
917
964
|
[NSUserDefaults.standardUserDefaults setObject:petID forKey:@"CCPetsSelectedSprite"];
|
|
918
965
|
}
|
|
@@ -975,6 +1022,7 @@
|
|
|
975
1022
|
if (!self.pendingApprovalRecords) {
|
|
976
1023
|
self.pendingApprovalRecords = [NSMutableDictionary dictionary];
|
|
977
1024
|
}
|
|
1025
|
+
[self prunePendingApprovalRecords];
|
|
978
1026
|
NSString *approvalKey = [self approvalKeyForRecord:record];
|
|
979
1027
|
NSDictionary *previousPriority = [self latestPendingApprovalRecord];
|
|
980
1028
|
BOOL manualApproval = [state isEqualToString:@"approval"];
|
|
@@ -983,6 +1031,7 @@
|
|
|
983
1031
|
} else {
|
|
984
1032
|
[self.pendingApprovalRecords removeObjectForKey:approvalKey];
|
|
985
1033
|
}
|
|
1034
|
+
[self prunePendingApprovalRecords];
|
|
986
1035
|
NSDictionary *currentPriority = [self latestPendingApprovalRecord];
|
|
987
1036
|
if (currentPriority) {
|
|
988
1037
|
if (manualApproval) {
|
|
@@ -1052,6 +1101,7 @@
|
|
|
1052
1101
|
if (!self.agentEventSource) [self startAgentEventReader];
|
|
1053
1102
|
}
|
|
1054
1103
|
- (void)refreshClientLifecycle:(id)sender {
|
|
1104
|
+
[self prunePendingApprovalRecords];
|
|
1055
1105
|
NSString *clientName = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
|
|
1056
1106
|
NSString *clientDirectory = [PetStateDirectory() stringByAppendingPathComponent:clientName];
|
|
1057
1107
|
NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
|
|
@@ -1086,16 +1136,20 @@
|
|
|
1086
1136
|
// Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
|
|
1087
1137
|
if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
|
|
1088
1138
|
}
|
|
1089
|
-
- (void)
|
|
1090
|
-
self.quotaView.codexUsage =
|
|
1091
|
-
self.quotaView.claudeUsage =
|
|
1139
|
+
- (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage {
|
|
1140
|
+
self.quotaView.codexUsage = codexUsage;
|
|
1141
|
+
self.quotaView.claudeUsage = claudeUsage;
|
|
1092
1142
|
NSDictionary *history = RecordQuotaHistory(self.quotaView.codexUsage,
|
|
1093
1143
|
self.quotaView.claudeUsage);
|
|
1094
1144
|
self.quotaView.codexHistory = QuotaHistorySeries(history, @"codex");
|
|
1095
1145
|
self.quotaView.claudeHistory = QuotaHistorySeries(history, @"claude");
|
|
1096
1146
|
self.quotaView.needsDisplay = YES;
|
|
1097
1147
|
}
|
|
1148
|
+
- (void)refreshUsage:(id)sender {
|
|
1149
|
+
[self.usageMonitor refreshNow];
|
|
1150
|
+
}
|
|
1098
1151
|
- (void)applicationWillTerminate:(NSNotification *)notification {
|
|
1152
|
+
[self.usageMonitor stop];
|
|
1099
1153
|
if (self.agentEventSource) {
|
|
1100
1154
|
dispatch_source_cancel(self.agentEventSource);
|
|
1101
1155
|
self.agentEventSource = nil;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
#import "CCPetsCleanup.h"
|
|
2
|
+
#import "CCPetsPaths.h"
|
|
3
|
+
#import <sys/file.h>
|
|
4
|
+
#import <fcntl.h>
|
|
5
|
+
#import <signal.h>
|
|
6
|
+
#import <unistd.h>
|
|
7
|
+
#import <errno.h>
|
|
8
|
+
|
|
9
|
+
static const NSTimeInterval RuntimeStateTTL = 7 * 24 * 60 * 60;
|
|
10
|
+
static NSString *const PreferencesDomain = @"com.universewang.cc-pets";
|
|
11
|
+
|
|
12
|
+
static NSString *RuntimeLockPath(void) {
|
|
13
|
+
NSString *name = [NSString stringWithFormat:@"cc-pets-%u.lock", getuid()];
|
|
14
|
+
return [PetStateDirectory() stringByAppendingPathComponent:name];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
static NSString *ClientStateDirectory(void) {
|
|
18
|
+
NSString *name = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
|
|
19
|
+
return [PetStateDirectory() stringByAppendingPathComponent:name];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
static BOOL RemoveIfPresent(NSString *path) {
|
|
23
|
+
if (path.length == 0 || ![NSFileManager.defaultManager fileExistsAtPath:path]) return NO;
|
|
24
|
+
return [NSFileManager.defaultManager removeItemAtPath:path error:nil];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
static BOOL RuntimeIsActive(void) {
|
|
28
|
+
NSString *lockPath = RuntimeLockPath();
|
|
29
|
+
if (![NSFileManager.defaultManager fileExistsAtPath:lockPath]) return NO;
|
|
30
|
+
int descriptor = open(lockPath.fileSystemRepresentation, O_RDWR | O_CLOEXEC);
|
|
31
|
+
if (descriptor < 0) return YES;
|
|
32
|
+
BOOL active = flock(descriptor, LOCK_EX | LOCK_NB) != 0;
|
|
33
|
+
if (!active) flock(descriptor, LOCK_UN);
|
|
34
|
+
close(descriptor);
|
|
35
|
+
return active;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
static void RemoveExpiredFile(NSString *path, NSTimeInterval cutoff) {
|
|
39
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
40
|
+
NSDate *modified = attributes[NSFileModificationDate];
|
|
41
|
+
if (modified && modified.timeIntervalSince1970 < cutoff) RemoveIfPresent(path);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
static void RemoveDeadClientRecords(void) {
|
|
45
|
+
NSString *directory = ClientStateDirectory();
|
|
46
|
+
NSArray<NSString *> *entries =
|
|
47
|
+
[NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil] ?: @[];
|
|
48
|
+
for (NSString *entry in entries) {
|
|
49
|
+
pid_t pid = (pid_t)entry.intValue;
|
|
50
|
+
BOOL alive = pid > 1 && (kill(pid, 0) == 0 || errno == EPERM);
|
|
51
|
+
if (!alive) RemoveIfPresent([directory stringByAppendingPathComponent:entry]);
|
|
52
|
+
}
|
|
53
|
+
if ([NSFileManager.defaultManager
|
|
54
|
+
contentsOfDirectoryAtPath:directory error:nil].count == 0) {
|
|
55
|
+
RemoveIfPresent(directory);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
static NSString *BuildCacheDirectory(void) {
|
|
60
|
+
NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_BUILD_CACHE_DIR"];
|
|
61
|
+
if (override.length > 0) return override.stringByStandardizingPath;
|
|
62
|
+
NSString *binary = NSProcessInfo.processInfo.arguments.firstObject.stringByStandardizingPath;
|
|
63
|
+
NSString *release = binary.stringByDeletingLastPathComponent;
|
|
64
|
+
if (![release.lastPathComponent isEqualToString:@"release"]) return nil;
|
|
65
|
+
return [[release stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"clang-cache"];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
static BOOL IsSafeSupportDirectory(NSString *path) {
|
|
69
|
+
NSString *standardized = path.stringByStandardizingPath;
|
|
70
|
+
NSString *expected = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"]
|
|
71
|
+
stringByAppendingPathComponent:@"Application Support"]
|
|
72
|
+
stringByAppendingPathComponent:@"CC Pets"].stringByStandardizingPath;
|
|
73
|
+
if ([standardized isEqualToString:expected]) return YES;
|
|
74
|
+
return [standardized.lastPathComponent isEqualToString:@"CC Pets"] &&
|
|
75
|
+
[standardized.stringByDeletingLastPathComponent.lastPathComponent
|
|
76
|
+
isEqualToString:@"Application Support"];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
static BOOL IsSafeBuildCacheDirectory(NSString *path) {
|
|
80
|
+
NSString *standardized = path.stringByStandardizingPath;
|
|
81
|
+
return [standardized.lastPathComponent isEqualToString:@"clang-cache"] &&
|
|
82
|
+
[standardized.stringByDeletingLastPathComponent.lastPathComponent isEqualToString:@".build"];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
void PruneStaleRuntimeState(void) {
|
|
86
|
+
NSTimeInterval cutoff = NSDate.date.timeIntervalSince1970 - RuntimeStateTTL;
|
|
87
|
+
RemoveExpiredFile(AgentEventPath(), cutoff);
|
|
88
|
+
RemoveExpiredFile(ClaudeUsagePath(), cutoff);
|
|
89
|
+
RemoveDeadClientRecords();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
int CleanCCPetsData(BOOL purge) {
|
|
93
|
+
if (RuntimeIsActive()) {
|
|
94
|
+
fputs("清理失败:CC Pets 正在运行,请先退出桌宠。\n", stderr);
|
|
95
|
+
return 2;
|
|
96
|
+
}
|
|
97
|
+
NSString *supportDirectory = ApplicationSupportDirectory();
|
|
98
|
+
NSString *buildCache = BuildCacheDirectory();
|
|
99
|
+
if (!IsSafeSupportDirectory(supportDirectory)) {
|
|
100
|
+
fprintf(stderr, "清理失败:应用数据目录不属于 CC Pets:%s\n",
|
|
101
|
+
supportDirectory.UTF8String);
|
|
102
|
+
return 3;
|
|
103
|
+
}
|
|
104
|
+
if (buildCache.length > 0 && !IsSafeBuildCacheDirectory(buildCache)) {
|
|
105
|
+
fprintf(stderr, "清理失败:构建缓存目录不属于 CC Pets:%s\n",
|
|
106
|
+
buildCache.UTF8String);
|
|
107
|
+
return 3;
|
|
108
|
+
}
|
|
109
|
+
NSUInteger removed = 0;
|
|
110
|
+
for (NSString *path in @[AgentEventPath(), ClaudeUsagePath(), RuntimeLockPath(),
|
|
111
|
+
ClientStateDirectory(), buildCache ?: @""]) {
|
|
112
|
+
if (RemoveIfPresent(path)) removed += 1;
|
|
113
|
+
}
|
|
114
|
+
NSString *updateLog = [supportDirectory stringByAppendingPathComponent:@"update.log"];
|
|
115
|
+
if (RemoveIfPresent(updateLog)) removed += 1;
|
|
116
|
+
if (purge) {
|
|
117
|
+
if (RemoveIfPresent(supportDirectory)) removed += 1;
|
|
118
|
+
NSString *domain = NSProcessInfo.processInfo.environment[@"CC_PETS_PREFERENCES_DOMAIN"];
|
|
119
|
+
if (domain.length == 0) domain = PreferencesDomain;
|
|
120
|
+
[NSUserDefaults.standardUserDefaults removePersistentDomainForName:domain];
|
|
121
|
+
[NSUserDefaults.standardUserDefaults synchronize];
|
|
122
|
+
}
|
|
123
|
+
printf("%s完成,共移除 %lu 项。\n", purge ? "完整数据清理" : "缓存清理",
|
|
124
|
+
(unsigned long)removed);
|
|
125
|
+
return EXIT_SUCCESS;
|
|
126
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
#import "CCPetsImageLoader.h"
|
|
2
|
+
#import <ImageIO/ImageIO.h>
|
|
3
|
+
|
|
4
|
+
NSImage *LoadPetSpriteImage(NSString *path, NSSize cellSize, NSInteger rowCount) {
|
|
5
|
+
if (path.length == 0 || rowCount <= 0) return nil;
|
|
6
|
+
NSURL *url = [NSURL fileURLWithPath:path];
|
|
7
|
+
CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)url, NULL);
|
|
8
|
+
if (!source) return nil;
|
|
9
|
+
NSDictionary *properties = CFBridgingRelease(
|
|
10
|
+
CGImageSourceCopyPropertiesAtIndex(source, 0, NULL));
|
|
11
|
+
CGFloat sourceWidth = [properties[(NSString *)kCGImagePropertyPixelWidth] doubleValue];
|
|
12
|
+
CGFloat sourceHeight = [properties[(NSString *)kCGImagePropertyPixelHeight] doubleValue];
|
|
13
|
+
CGFloat desiredWidth = MAX(1.0, cellSize.width) * 8.0;
|
|
14
|
+
CGFloat desiredHeight = MAX(1.0, cellSize.height) * rowCount;
|
|
15
|
+
CGFloat scale = MIN(1.0, MAX(desiredWidth / MAX(1.0, sourceWidth),
|
|
16
|
+
desiredHeight / MAX(1.0, sourceHeight)));
|
|
17
|
+
if (scale >= 0.98) {
|
|
18
|
+
CFRelease(source);
|
|
19
|
+
return [[NSImage alloc] initWithContentsOfFile:path];
|
|
20
|
+
}
|
|
21
|
+
CGFloat maximumPixelSize = ceil(MAX(sourceWidth, sourceHeight) * scale);
|
|
22
|
+
NSDictionary *options = @{
|
|
23
|
+
(NSString *)kCGImageSourceCreateThumbnailFromImageAlways: @YES,
|
|
24
|
+
(NSString *)kCGImageSourceCreateThumbnailWithTransform: @YES,
|
|
25
|
+
(NSString *)kCGImageSourceThumbnailMaxPixelSize: @(maximumPixelSize),
|
|
26
|
+
(NSString *)kCGImageSourceShouldCacheImmediately: @YES
|
|
27
|
+
};
|
|
28
|
+
CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(
|
|
29
|
+
source, 0, (__bridge CFDictionaryRef)options);
|
|
30
|
+
CFRelease(source);
|
|
31
|
+
if (!imageRef) return [[NSImage alloc] initWithContentsOfFile:path];
|
|
32
|
+
NSImage *image = [[NSImage alloc] initWithCGImage:imageRef
|
|
33
|
+
size:NSMakeSize(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef))];
|
|
34
|
+
CGImageRelease(imageRef);
|
|
35
|
+
return image;
|
|
36
|
+
}
|
|
@@ -38,10 +38,10 @@ const NSTimeInterval AgentStatusInactivityInterval = 60.0;
|
|
|
38
38
|
// 留这段宽限是因为不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid
|
|
39
39
|
// 文件,只能靠"最近还在发事件"证明自己活着,不能一看不到 pid 文件就清掉。
|
|
40
40
|
const NSTimeInterval AgentStatusOrphanInterval = 10.0;
|
|
41
|
-
//
|
|
42
|
-
//
|
|
43
|
-
const NSTimeInterval UsageRefreshIntervalVisible =
|
|
44
|
-
const NSTimeInterval UsageRefreshIntervalHidden =
|
|
41
|
+
// 额度变化由 FSEvents/VNODE 主动推送;定时器只保留为监听不可用时的 120 秒兜底。
|
|
42
|
+
// 打开面板和手动刷新仍会立即读取一次。
|
|
43
|
+
const NSTimeInterval UsageRefreshIntervalVisible = 120.0;
|
|
44
|
+
const NSTimeInterval UsageRefreshIntervalHidden = 120.0;
|
|
45
45
|
const NSTimeInterval ClientLifecycleInterval = 3.0;
|
|
46
46
|
const NSTimeInterval AgentEventReaderCheckInterval = 5.0;
|
|
47
47
|
// 精灵动画帧间隔。定时器的 tolerance 让内核可以合并唤醒。
|
|
@@ -273,4 +273,17 @@ NSDictionary *LatestUsage(void) {
|
|
|
273
273
|
[handle closeFile];
|
|
274
274
|
return self.usage;
|
|
275
275
|
}
|
|
276
|
+
- (NSDictionary *)refreshWithFullDiscovery {
|
|
277
|
+
self.lastFullDiscovery = 0;
|
|
278
|
+
return [self refresh];
|
|
279
|
+
}
|
|
280
|
+
- (NSDictionary *)refreshForSessionURL:(NSURL *)url {
|
|
281
|
+
if (!url || ![url.pathExtension.lowercaseString isEqualToString:@"jsonl"]) return self.usage;
|
|
282
|
+
NSString *sessionsPath = self.sessionsURL.path.stringByResolvingSymlinksInPath;
|
|
283
|
+
NSString *candidatePath = url.path.stringByResolvingSymlinksInPath;
|
|
284
|
+
NSString *prefix = [sessionsPath stringByAppendingString:@"/"];
|
|
285
|
+
if (![candidatePath hasPrefix:prefix]) return self.usage;
|
|
286
|
+
if (![candidatePath isEqualToString:self.sessionURL.path]) [self selectSessionURL:url];
|
|
287
|
+
return [self refresh];
|
|
288
|
+
}
|
|
276
289
|
@end
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
@interface CCPetsUsageMonitor : NSObject
|
|
4
|
+
@property(copy) void (^changeHandler)(NSDictionary *codexUsage, NSDictionary *claudeUsage);
|
|
5
|
+
@property(readonly) NSDictionary *codexUsage;
|
|
6
|
+
@property(readonly) NSDictionary *claudeUsage;
|
|
7
|
+
- (void)start;
|
|
8
|
+
- (void)refreshNow;
|
|
9
|
+
- (void)stop;
|
|
10
|
+
@end
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
#import "CCPetsUsageMonitor.h"
|
|
2
|
+
#import "CCPetsUsage.h"
|
|
3
|
+
#import "CCPetsPaths.h"
|
|
4
|
+
#import <CoreServices/CoreServices.h>
|
|
5
|
+
#import <fcntl.h>
|
|
6
|
+
#import <unistd.h>
|
|
7
|
+
|
|
8
|
+
@interface CCPetsUsageMonitor ()
|
|
9
|
+
@property CodexUsageReader *codexReader;
|
|
10
|
+
@property(readwrite) NSDictionary *codexUsage;
|
|
11
|
+
@property(readwrite) NSDictionary *claudeUsage;
|
|
12
|
+
@property FSEventStreamRef codexStream;
|
|
13
|
+
@property dispatch_source_t claudeSource;
|
|
14
|
+
@property unsigned long long claudeSize;
|
|
15
|
+
@property NSTimeInterval claudeModifiedAt;
|
|
16
|
+
@property BOOL started;
|
|
17
|
+
- (void)publishChange;
|
|
18
|
+
- (void)startClaudeSource;
|
|
19
|
+
@end
|
|
20
|
+
|
|
21
|
+
static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
|
|
22
|
+
void *clientCallBackInfo, size_t numEvents, void *eventPaths,
|
|
23
|
+
const FSEventStreamEventFlags eventFlags[],
|
|
24
|
+
const FSEventStreamEventId eventIds[]) {
|
|
25
|
+
CCPetsUsageMonitor *monitor = (__bridge CCPetsUsageMonitor *)clientCallBackInfo;
|
|
26
|
+
NSArray<NSString *> *paths = (__bridge NSArray<NSString *> *)eventPaths;
|
|
27
|
+
BOOL requiresFullDiscovery = NO;
|
|
28
|
+
NSURL *latestSession = nil;
|
|
29
|
+
for (size_t index = 0; index < numEvents; index++) {
|
|
30
|
+
FSEventStreamEventFlags flags = eventFlags[index];
|
|
31
|
+
if (flags & (kFSEventStreamEventFlagMustScanSubDirs |
|
|
32
|
+
kFSEventStreamEventFlagUserDropped |
|
|
33
|
+
kFSEventStreamEventFlagKernelDropped |
|
|
34
|
+
kFSEventStreamEventFlagRootChanged)) {
|
|
35
|
+
requiresFullDiscovery = YES;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
NSString *path = paths[index];
|
|
39
|
+
if ([path.pathExtension.lowercaseString isEqualToString:@"jsonl"] &&
|
|
40
|
+
[path.stringByResolvingSymlinksInPath hasPrefix:
|
|
41
|
+
[monitor.codexReader.sessionsURL.path.stringByResolvingSymlinksInPath
|
|
42
|
+
stringByAppendingString:@"/"]]) {
|
|
43
|
+
latestSession = [NSURL fileURLWithPath:path];
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
monitor.codexUsage = requiresFullDiscovery
|
|
47
|
+
? [monitor.codexReader refreshWithFullDiscovery]
|
|
48
|
+
: (latestSession ? [monitor.codexReader refreshForSessionURL:latestSession] : monitor.codexUsage);
|
|
49
|
+
if (requiresFullDiscovery || latestSession) [monitor publishChange];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
@implementation CCPetsUsageMonitor
|
|
53
|
+
- (instancetype)init {
|
|
54
|
+
if ((self = [super init])) {
|
|
55
|
+
_codexReader = [CodexUsageReader new];
|
|
56
|
+
}
|
|
57
|
+
return self;
|
|
58
|
+
}
|
|
59
|
+
- (void)publishChange {
|
|
60
|
+
if (self.changeHandler) self.changeHandler(self.codexUsage, self.claudeUsage);
|
|
61
|
+
}
|
|
62
|
+
- (NSDictionary *)readClaudeUsageIfChanged:(BOOL)force {
|
|
63
|
+
NSString *path = ClaudeUsagePath();
|
|
64
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
65
|
+
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
66
|
+
NSTimeInterval modifiedAt = [attributes[NSFileModificationDate] timeIntervalSince1970];
|
|
67
|
+
if (!force && size == self.claudeSize && modifiedAt == self.claudeModifiedAt) {
|
|
68
|
+
return self.claudeUsage;
|
|
69
|
+
}
|
|
70
|
+
self.claudeSize = size;
|
|
71
|
+
self.claudeModifiedAt = modifiedAt;
|
|
72
|
+
return LatestClaudeUsage();
|
|
73
|
+
}
|
|
74
|
+
- (void)startCodexStream {
|
|
75
|
+
if (self.codexStream) return;
|
|
76
|
+
NSString *sessionsPath = self.codexReader.sessionsURL.path;
|
|
77
|
+
BOOL isDirectory = NO;
|
|
78
|
+
if (![NSFileManager.defaultManager fileExistsAtPath:sessionsPath isDirectory:&isDirectory] ||
|
|
79
|
+
!isDirectory) return;
|
|
80
|
+
FSEventStreamContext context = {0, (__bridge void *)self, NULL, NULL, NULL};
|
|
81
|
+
NSArray *paths = @[sessionsPath];
|
|
82
|
+
FSEventStreamCreateFlags flags =
|
|
83
|
+
kFSEventStreamCreateFlagFileEvents |
|
|
84
|
+
kFSEventStreamCreateFlagNoDefer |
|
|
85
|
+
kFSEventStreamCreateFlagUseCFTypes;
|
|
86
|
+
self.codexStream = FSEventStreamCreate(NULL, CodexEventsCallback, &context,
|
|
87
|
+
(__bridge CFArrayRef)paths, kFSEventStreamEventIdSinceNow, 0.5, flags);
|
|
88
|
+
if (!self.codexStream) return;
|
|
89
|
+
FSEventStreamSetDispatchQueue(self.codexStream, dispatch_get_main_queue());
|
|
90
|
+
if (!FSEventStreamStart(self.codexStream)) {
|
|
91
|
+
FSEventStreamInvalidate(self.codexStream);
|
|
92
|
+
FSEventStreamRelease(self.codexStream);
|
|
93
|
+
self.codexStream = NULL;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
- (void)startClaudeSource {
|
|
97
|
+
if (self.claudeSource || !self.started) return;
|
|
98
|
+
NSString *path = ClaudeUsagePath();
|
|
99
|
+
[NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
|
|
100
|
+
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
101
|
+
if (![NSFileManager.defaultManager fileExistsAtPath:path]) {
|
|
102
|
+
[NSFileManager.defaultManager createFileAtPath:path contents:nil attributes:nil];
|
|
103
|
+
}
|
|
104
|
+
int descriptor = open(path.fileSystemRepresentation, O_EVTONLY | O_CLOEXEC);
|
|
105
|
+
if (descriptor < 0) return;
|
|
106
|
+
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
|
|
107
|
+
DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
|
|
108
|
+
DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE, dispatch_get_main_queue());
|
|
109
|
+
if (!source) {
|
|
110
|
+
close(descriptor);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
self.claudeSource = source;
|
|
114
|
+
__weak typeof(self) weakSelf = self;
|
|
115
|
+
dispatch_source_set_event_handler(source, ^{
|
|
116
|
+
typeof(self) strongSelf = weakSelf;
|
|
117
|
+
if (!strongSelf) return;
|
|
118
|
+
dispatch_source_t current = strongSelf.claudeSource;
|
|
119
|
+
if (!current) return;
|
|
120
|
+
unsigned long flags = dispatch_source_get_data(current);
|
|
121
|
+
strongSelf.claudeUsage = [strongSelf readClaudeUsageIfChanged:YES];
|
|
122
|
+
[strongSelf publishChange];
|
|
123
|
+
if (flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE)) {
|
|
124
|
+
strongSelf.claudeSource = nil;
|
|
125
|
+
dispatch_source_cancel(current);
|
|
126
|
+
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
|
|
127
|
+
dispatch_get_main_queue(), ^{ [weakSelf startClaudeSource]; });
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
|
|
131
|
+
dispatch_resume(source);
|
|
132
|
+
}
|
|
133
|
+
- (void)start {
|
|
134
|
+
if (self.started) return;
|
|
135
|
+
self.started = YES;
|
|
136
|
+
[self refreshNow];
|
|
137
|
+
[self startCodexStream];
|
|
138
|
+
[self startClaudeSource];
|
|
139
|
+
}
|
|
140
|
+
- (void)refreshNow {
|
|
141
|
+
self.codexUsage = [self.codexReader refresh];
|
|
142
|
+
self.claudeUsage = [self readClaudeUsageIfChanged:NO];
|
|
143
|
+
if (!self.codexStream) [self startCodexStream];
|
|
144
|
+
if (!self.claudeSource) [self startClaudeSource];
|
|
145
|
+
[self publishChange];
|
|
146
|
+
}
|
|
147
|
+
- (void)stop {
|
|
148
|
+
self.started = NO;
|
|
149
|
+
if (self.codexStream) {
|
|
150
|
+
FSEventStreamStop(self.codexStream);
|
|
151
|
+
FSEventStreamInvalidate(self.codexStream);
|
|
152
|
+
FSEventStreamRelease(self.codexStream);
|
|
153
|
+
self.codexStream = NULL;
|
|
154
|
+
}
|
|
155
|
+
if (self.claudeSource) {
|
|
156
|
+
dispatch_source_cancel(self.claudeSource);
|
|
157
|
+
self.claudeSource = nil;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
- (void)dealloc {
|
|
161
|
+
[self stop];
|
|
162
|
+
}
|
|
163
|
+
@end
|
package/Sources/CCPets/PetView.h
CHANGED
|
@@ -21,11 +21,13 @@
|
|
|
21
21
|
@property(copy) void (^dragStateChanged)(BOOL dragging);
|
|
22
22
|
@property(copy) NSArray<NSDictionary *> *(^petOptionsRequested)(void);
|
|
23
23
|
@property(copy) void (^switchPetRequested)(NSString *petID);
|
|
24
|
-
@property
|
|
24
|
+
@property NSCache<NSString *, NSImage *> *petMenuPreviewCache;
|
|
25
25
|
@property NSPanel *petMenuPreviewPanel;
|
|
26
26
|
@property NSImageView *petMenuPreviewImageView;
|
|
27
27
|
@property NSTimer *frameTimer;
|
|
28
28
|
@property(nonatomic) BOOL animationSuspended;
|
|
29
|
+
@property BOOL lowPowerMode;
|
|
30
|
+
@property BOOL reduceMotion;
|
|
29
31
|
- (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount;
|
|
30
32
|
- (void)applySheet:(NSImage *)sheet petID:(NSString *)petID rowCount:(NSInteger)rowCount;
|
|
31
33
|
- (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed;
|
package/Sources/CCPets/PetView.m
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#import "PetView.h"
|
|
2
2
|
#import "MenuToggleSwitch.h"
|
|
3
3
|
#import "CCPetsPaths.h"
|
|
4
|
+
#import "CCPetsImageLoader.h"
|
|
4
5
|
|
|
5
6
|
@implementation PetView
|
|
6
7
|
- (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount {
|
|
@@ -9,7 +10,16 @@
|
|
|
9
10
|
_spriteRowCount = rowCount;
|
|
10
11
|
_lookDirection = -1;
|
|
11
12
|
_frames = @[@0, @1, @2, @3, @4, @5];
|
|
12
|
-
_petMenuPreviewCache = [
|
|
13
|
+
_petMenuPreviewCache = [NSCache new];
|
|
14
|
+
_petMenuPreviewCache.countLimit = 24;
|
|
15
|
+
_petMenuPreviewCache.totalCostLimit = 4 * 1024 * 1024;
|
|
16
|
+
[NSNotificationCenter.defaultCenter addObserver:self
|
|
17
|
+
selector:@selector(powerStateDidChange:)
|
|
18
|
+
name:NSProcessInfoPowerStateDidChangeNotification object:nil];
|
|
19
|
+
[NSWorkspace.sharedWorkspace.notificationCenter addObserver:self
|
|
20
|
+
selector:@selector(powerStateDidChange:)
|
|
21
|
+
name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
|
|
22
|
+
[self updatePowerPreferences];
|
|
13
23
|
[self updateFrameTimer];
|
|
14
24
|
NSTrackingArea *tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect
|
|
15
25
|
options:NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
|
|
@@ -26,6 +36,21 @@
|
|
|
26
36
|
[_frameTimer invalidate];
|
|
27
37
|
if (_globalMouseMonitor) [NSEvent removeMonitor:_globalMouseMonitor];
|
|
28
38
|
if (_localMouseMonitor) [NSEvent removeMonitor:_localMouseMonitor];
|
|
39
|
+
[NSNotificationCenter.defaultCenter removeObserver:self];
|
|
40
|
+
[NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self];
|
|
41
|
+
}
|
|
42
|
+
- (void)powerStateDidChange:(NSNotification *)notification {
|
|
43
|
+
[self updatePowerPreferences];
|
|
44
|
+
}
|
|
45
|
+
- (void)updatePowerPreferences {
|
|
46
|
+
BOOL lowPower = NSProcessInfo.processInfo.lowPowerModeEnabled;
|
|
47
|
+
BOOL reduceMotion = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion;
|
|
48
|
+
if (self.lowPowerMode == lowPower && self.reduceMotion == reduceMotion) return;
|
|
49
|
+
self.lowPowerMode = lowPower;
|
|
50
|
+
self.reduceMotion = reduceMotion;
|
|
51
|
+
[self.frameTimer invalidate];
|
|
52
|
+
self.frameTimer = nil;
|
|
53
|
+
[self updateFrameTimer];
|
|
29
54
|
}
|
|
30
55
|
// 动画帧只在“可见”且“不处于十六向跟随”时推进。跟随模式显示的是静态定格,
|
|
31
56
|
// nextFrame: 进来只会立刻 return,定时器纯属空转。
|
|
@@ -39,9 +64,12 @@
|
|
|
39
64
|
}
|
|
40
65
|
// block 版定时器 + weak self,避免 NSTimer 持有 target 造成 PetView 永不释放。
|
|
41
66
|
__weak PetView *weakSelf = self;
|
|
42
|
-
|
|
67
|
+
NSTimeInterval interval = PetFrameInterval;
|
|
68
|
+
if (self.lowPowerMode) interval *= 1.5;
|
|
69
|
+
if (self.reduceMotion) interval *= 2.0;
|
|
70
|
+
self.frameTimer = [NSTimer scheduledTimerWithTimeInterval:interval repeats:YES
|
|
43
71
|
block:^(NSTimer *timer) { [weakSelf nextFrame:timer]; }];
|
|
44
|
-
self.frameTimer.tolerance =
|
|
72
|
+
self.frameTimer.tolerance = interval * 0.25;
|
|
45
73
|
}
|
|
46
74
|
- (void)setLookDirection:(NSInteger)value {
|
|
47
75
|
if (_lookDirection == value) return;
|
|
@@ -298,11 +326,15 @@
|
|
|
298
326
|
NSInteger rowCount = [pet[@"spriteRowCount"] integerValue];
|
|
299
327
|
if (path.length == 0 || rowCount <= 0) return nil;
|
|
300
328
|
|
|
301
|
-
|
|
302
|
-
|
|
329
|
+
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
330
|
+
NSTimeInterval modifiedAt = [attributes[NSFileModificationDate] timeIntervalSince1970];
|
|
331
|
+
unsigned long long fileSize = [attributes[NSFileSize] unsignedLongLongValue];
|
|
332
|
+
NSString *cacheKey = [NSString stringWithFormat:@"%@:%ld:%.6f:%llu",
|
|
333
|
+
path, (long)rowCount, modifiedAt, fileSize];
|
|
334
|
+
NSImage *cached = [self.petMenuPreviewCache objectForKey:cacheKey];
|
|
303
335
|
if (cached) return cached;
|
|
304
336
|
|
|
305
|
-
NSImage *sheet =
|
|
337
|
+
NSImage *sheet = LoadPetSpriteImage(path, NSMakeSize(92, 76), rowCount);
|
|
306
338
|
if (!sheet || sheet.size.width <= 0 || sheet.size.height <= 0) return nil;
|
|
307
339
|
|
|
308
340
|
CGFloat cellWidth = sheet.size.width / 8.0;
|
|
@@ -316,7 +348,8 @@
|
|
|
316
348
|
operation:NSCompositingOperationSourceOver fraction:1.0
|
|
317
349
|
respectFlipped:NO hints:@{NSImageHintInterpolation: @(NSImageInterpolationNone)}];
|
|
318
350
|
[preview unlockFocus];
|
|
319
|
-
|
|
351
|
+
NSUInteger cost = (NSUInteger)ceil(previewWidth * previewHeight * 4.0);
|
|
352
|
+
[self.petMenuPreviewCache setObject:preview forKey:cacheKey cost:cost];
|
|
320
353
|
return preview;
|
|
321
354
|
}
|
|
322
355
|
- (void)preparePetMenuPreviewPanel {
|
package/Sources/CCPets/main.m
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
#import "CCPetsQuotaHistory.h"
|
|
7
7
|
#import "CCPetsUsage.h"
|
|
8
8
|
#import "CCPetsVersion.h"
|
|
9
|
+
#import "CCPetsCleanup.h"
|
|
9
10
|
#import <sys/file.h>
|
|
10
11
|
#import <sys/stat.h>
|
|
11
12
|
#import <fcntl.h>
|
|
@@ -39,6 +40,8 @@ int main(int argc, const char *argv[]) {
|
|
|
39
40
|
if (argc > 1 && (strcmp(argv[1], "--provider-event") == 0 ||
|
|
40
41
|
strcmp(argv[1], "provider-event") == 0)) return RecordProviderEvent();
|
|
41
42
|
if (argc > 1 && strcmp(argv[1], "--claude-usage") == 0) return RecordClaudeUsage();
|
|
43
|
+
if (argc > 1 && strcmp(argv[1], "--clean") == 0) return CleanCCPetsData(NO);
|
|
44
|
+
if (argc > 1 && strcmp(argv[1], "--purge-data") == 0) return CleanCCPetsData(YES);
|
|
42
45
|
if (argc > 1 && strcmp(argv[1], "--history") == 0) {
|
|
43
46
|
NSData *json = [NSJSONSerialization dataWithJSONObject:QuotaHistoryDocument()
|
|
44
47
|
options:NSJSONWritingPrettyPrinted error:nil];
|
|
@@ -74,6 +77,7 @@ int main(int argc, const char *argv[]) {
|
|
|
74
77
|
NSString *lockPath = [PetStateDirectory() stringByAppendingPathComponent:lockName];
|
|
75
78
|
int lock = open(lockPath.fileSystemRepresentation, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
|
|
76
79
|
if (lock < 0 || flock(lock, LOCK_EX | LOCK_NB) != 0) return EXIT_SUCCESS;
|
|
80
|
+
PruneStaleRuntimeState();
|
|
77
81
|
|
|
78
82
|
NSApplication *app = NSApplication.sharedApplication;
|
|
79
83
|
AppDelegate *delegate = [AppDelegate new];
|
package/bin/cc-pets
CHANGED
|
@@ -23,6 +23,11 @@ if [[ "${1:-}" == "build" ]]; then
|
|
|
23
23
|
exec "${PROJECT_DIR}/scripts/build.sh"
|
|
24
24
|
fi
|
|
25
25
|
|
|
26
|
+
if [[ "${1:-}" == "clean" ]]; then
|
|
27
|
+
shift
|
|
28
|
+
exec "${PET_BIN}" --clean "$@"
|
|
29
|
+
fi
|
|
30
|
+
|
|
26
31
|
if [[ ! -x "${PET_BIN}" || ! -d "${BUILD_APP}" ]]; then
|
|
27
32
|
"${PROJECT_DIR}/scripts/build.sh" >/dev/null
|
|
28
33
|
fi
|
package/package.json
CHANGED
package/scripts/build.sh
CHANGED
|
@@ -35,6 +35,8 @@ CLANG_MODULE_CACHE_PATH="${CACHE_DIR}" clang \
|
|
|
35
35
|
"-DCC_PETS_VERSION=\"${PACKAGE_VERSION}\"" \
|
|
36
36
|
-I"${PROJECT_DIR}/Sources/CCPets" \
|
|
37
37
|
-framework Cocoa \
|
|
38
|
+
-framework CoreServices \
|
|
39
|
+
-framework ImageIO \
|
|
38
40
|
-framework QuartzCore \
|
|
39
41
|
-framework UserNotifications \
|
|
40
42
|
"${SOURCES[@]}" \
|
package/scripts/uninstall-app.sh
CHANGED
|
@@ -5,6 +5,15 @@ APPLICATIONS_DIR="${CC_PETS_APPLICATIONS_DIR:-${HOME}/Applications}"
|
|
|
5
5
|
TARGET_APP="${APPLICATIONS_DIR}/CC Pets.app"
|
|
6
6
|
TARGET_EXECUTABLE="${TARGET_APP}/Contents/MacOS/cc-pets"
|
|
7
7
|
|
|
8
|
+
if [[ -e "${TARGET_APP}" ]]; then
|
|
9
|
+
BUNDLE_ID="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' \
|
|
10
|
+
"${TARGET_APP}/Contents/Info.plist" 2>/dev/null || true)"
|
|
11
|
+
if [[ "${BUNDLE_ID}" != "com.universewang.cc-pets" ]]; then
|
|
12
|
+
print -u2 "拒绝删除:${TARGET_APP} 不是 CC Pets 应用(Bundle ID 不匹配)。"
|
|
13
|
+
exit 2
|
|
14
|
+
fi
|
|
15
|
+
fi
|
|
16
|
+
|
|
8
17
|
if [[ "${CC_PETS_SKIP_APP_STOP:-0}" != "1" ]] && pgrep -f "${TARGET_EXECUTABLE}" >/dev/null 2>&1; then
|
|
9
18
|
pkill -f "${TARGET_EXECUTABLE}" || true
|
|
10
19
|
fi
|
|
@@ -4,17 +4,65 @@ set -eu
|
|
|
4
4
|
SCRIPT_DIR="${0:A:h}"
|
|
5
5
|
PROJECT_DIR="${SCRIPT_DIR:h}"
|
|
6
6
|
SHELL_RC="${ZDOTDIR:-${HOME}}/.zshrc"
|
|
7
|
+
PET_BIN="${PROJECT_DIR}/.build/release/cc-pets"
|
|
7
8
|
PET_APP_EXECUTABLE="${PROJECT_DIR}/.build/release/CC Pets.app/Contents/MacOS/cc-pets"
|
|
9
|
+
INSTALLED_APP_EXECUTABLE="${CC_PETS_APPLICATIONS_DIR:-${HOME}/Applications}/CC Pets.app/Contents/MacOS/cc-pets"
|
|
8
10
|
LEGACY_PET_APP_EXECUTABLE="${PROJECT_DIR}/.build/release/CodexPet.app/Contents/MacOS/codex-pet"
|
|
9
11
|
|
|
10
|
-
|
|
12
|
+
PURGE=0
|
|
13
|
+
ASSUME_YES=0
|
|
14
|
+
for argument in "$@"; do
|
|
15
|
+
[[ "${argument}" == "--purge" ]] && PURGE=1
|
|
16
|
+
[[ "${argument}" == "--yes" ]] && ASSUME_YES=1
|
|
17
|
+
done
|
|
18
|
+
|
|
19
|
+
if (( PURGE && ! ASSUME_YES )); then
|
|
20
|
+
if [[ ! -t 0 ]]; then
|
|
21
|
+
print -u2 "完整卸载会删除应用、额度历史、更新配置、日志和偏好。非交互环境请显式添加 --yes。"
|
|
22
|
+
exit 2
|
|
23
|
+
fi
|
|
24
|
+
print -u2 "完整卸载会永久删除 CC Pets 应用及全部本地数据,是否继续?[y/N] "
|
|
25
|
+
if ! read -r reply || [[ "${reply:l}" != "y" && "${reply:l}" != "yes" ]]; then
|
|
26
|
+
print "已取消完整卸载。"
|
|
27
|
+
exit 0
|
|
28
|
+
fi
|
|
29
|
+
fi
|
|
11
30
|
|
|
12
31
|
if [[ "${CC_PETS_SKIP_APP_STOP:-0}" != "1" ]]; then
|
|
13
|
-
for executable in "${PET_APP_EXECUTABLE}" "${LEGACY_PET_APP_EXECUTABLE}"; do
|
|
32
|
+
for executable in "${PET_APP_EXECUTABLE}" "${INSTALLED_APP_EXECUTABLE}" "${LEGACY_PET_APP_EXECUTABLE}"; do
|
|
14
33
|
if pgrep -f "${executable}" >/dev/null 2>&1; then
|
|
15
34
|
pkill -f "${executable}" || true
|
|
16
35
|
fi
|
|
17
36
|
done
|
|
37
|
+
if (( PURGE )); then
|
|
38
|
+
for _ in {1..30}; do
|
|
39
|
+
running=0
|
|
40
|
+
for executable in "${PET_APP_EXECUTABLE}" "${INSTALLED_APP_EXECUTABLE}" "${LEGACY_PET_APP_EXECUTABLE}"; do
|
|
41
|
+
if pgrep -f "${executable}" >/dev/null 2>&1; then
|
|
42
|
+
running=1
|
|
43
|
+
fi
|
|
44
|
+
done
|
|
45
|
+
(( running == 0 )) && break
|
|
46
|
+
sleep 0.1
|
|
47
|
+
done
|
|
48
|
+
if (( running != 0 )); then
|
|
49
|
+
print -u2 "完整卸载失败:CC Pets 未能退出,尚未删除集成或本地数据。"
|
|
50
|
+
exit 1
|
|
51
|
+
fi
|
|
52
|
+
fi
|
|
53
|
+
fi
|
|
54
|
+
|
|
55
|
+
node "${PROJECT_DIR}/scripts/uninstall-integrations.mjs" "${SHELL_RC}"
|
|
56
|
+
|
|
57
|
+
if (( PURGE )); then
|
|
58
|
+
if [[ ! -x "${PET_BIN}" ]]; then
|
|
59
|
+
print -u2 "完整卸载失败:找不到 ${PET_BIN},本地数据尚未删除。"
|
|
60
|
+
exit 1
|
|
61
|
+
fi
|
|
62
|
+
"${PET_BIN}" --purge-data
|
|
63
|
+
CC_PETS_SKIP_APP_STOP=1 "${PROJECT_DIR}/scripts/uninstall-app.sh"
|
|
64
|
+
print "完整卸载完成;npm 包本身如仍存在,可继续执行 npm uninstall -g cc-pets。"
|
|
65
|
+
exit 0
|
|
18
66
|
fi
|
|
19
67
|
|
|
20
68
|
print "卸载集成完成。执行 source ${(q)SHELL_RC} 更新当前终端;如需删除 npm 包,再执行 npm uninstall -g cc-pets。"
|