cc-pets 1.0.1 → 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.
Files changed (37) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +12 -2
  3. package/Sources/CCPets/CCPetsAppDelegate.h +54 -0
  4. package/Sources/CCPets/CCPetsAppDelegate.m +1158 -0
  5. package/Sources/CCPets/CCPetsCleanup.h +7 -0
  6. package/Sources/CCPets/CCPetsCleanup.m +126 -0
  7. package/Sources/CCPets/CCPetsEvents.h +10 -0
  8. package/Sources/CCPets/CCPetsEvents.m +232 -0
  9. package/Sources/CCPets/CCPetsImageLoader.h +4 -0
  10. package/Sources/CCPets/CCPetsImageLoader.m +36 -0
  11. package/Sources/CCPets/CCPetsPaths.h +23 -0
  12. package/Sources/CCPets/CCPetsPaths.m +48 -0
  13. package/Sources/CCPets/CCPetsPreviews.h +6 -0
  14. package/Sources/CCPets/CCPetsPreviews.m +159 -0
  15. package/Sources/CCPets/CCPetsQuotaHistory.h +7 -0
  16. package/Sources/CCPets/CCPetsQuotaHistory.m +83 -0
  17. package/Sources/CCPets/CCPetsUsage.h +19 -0
  18. package/Sources/CCPets/CCPetsUsage.m +289 -0
  19. package/Sources/CCPets/CCPetsUsageMonitor.h +10 -0
  20. package/Sources/CCPets/CCPetsUsageMonitor.m +163 -0
  21. package/Sources/CCPets/CCPetsVersion.h +10 -0
  22. package/Sources/CCPets/CCPetsVersion.m +62 -0
  23. package/Sources/CCPets/MenuToggleSwitch.h +5 -0
  24. package/Sources/CCPets/MenuToggleSwitch.m +47 -0
  25. package/Sources/CCPets/PetView.h +35 -0
  26. package/Sources/CCPets/PetView.m +511 -0
  27. package/Sources/CCPets/QuotaDashboardView.h +23 -0
  28. package/Sources/CCPets/QuotaDashboardView.m +318 -0
  29. package/Sources/CCPets/main.m +11 -2528
  30. package/bin/cc-pets +5 -0
  31. package/bin/claude-with-pet +2 -1
  32. package/bin/codex-with-pet +3 -1
  33. package/package.json +2 -3
  34. package/scripts/build.sh +20 -1
  35. package/scripts/install-git-hooks.sh +47 -0
  36. package/scripts/uninstall-app.sh +9 -0
  37. package/scripts/uninstall-shell-integration.sh +50 -2
@@ -0,0 +1,1158 @@
1
+ #import "CCPetsAppDelegate.h"
2
+ #import "CCPetsPaths.h"
3
+ #import "CCPetsVersion.h"
4
+ #import "CCPetsEvents.h"
5
+ #import "CCPetsQuotaHistory.h"
6
+ #import "CCPetsImageLoader.h"
7
+ #import "MenuToggleSwitch.h"
8
+ #import <UserNotifications/UserNotifications.h>
9
+ #import <signal.h>
10
+ #import <sys/stat.h>
11
+ #import <fcntl.h>
12
+ #import <unistd.h>
13
+ #import <errno.h>
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
+
34
+ @implementation AppDelegate
35
+ - (NSString *)applicationSupportDirectory {
36
+ return ApplicationSupportDirectory();
37
+ }
38
+ - (void)showUpdateAlertWithTitle:(NSString *)title message:(NSString *)message {
39
+ [NSApp activateIgnoringOtherApps:YES];
40
+ NSAlert *alert = [NSAlert new];
41
+ alert.messageText = title;
42
+ alert.informativeText = message;
43
+ [alert addButtonWithTitle:@"好"];
44
+ [alert runModal];
45
+ }
46
+ - (NSDictionary *)updaterConfiguration {
47
+ NSString *path = [[self applicationSupportDirectory] stringByAppendingPathComponent:@"updater.json"];
48
+ NSData *data = [NSData dataWithContentsOfFile:path];
49
+ NSDictionary *configuration = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
50
+ return [configuration isKindOfClass:NSDictionary.class] ? configuration : nil;
51
+ }
52
+ - (BOOL)restartAfterUpdateToVersion:(NSString *)version configuration:(NSDictionary *)configuration {
53
+ NSString *appPath = [configuration[@"appPath"] isKindOfClass:NSString.class]
54
+ ? [configuration[@"appPath"] stringByStandardizingPath] : nil;
55
+ if (appPath.length == 0 &&
56
+ [NSBundle.mainBundle.bundlePath.pathExtension.lowercaseString isEqualToString:@"app"]) {
57
+ appPath = NSBundle.mainBundle.bundlePath.stringByStandardizingPath;
58
+ }
59
+ if (appPath.length == 0) {
60
+ appPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Applications"]
61
+ stringByAppendingPathComponent:@"CC Pets.app"];
62
+ }
63
+
64
+ NSString *infoPath = [appPath stringByAppendingPathComponent:@"Contents/Info.plist"];
65
+ NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:infoPath];
66
+ NSString *installedVersion = [info[@"CFBundleShortVersionString"] isKindOfClass:NSString.class]
67
+ ? info[@"CFBundleShortVersionString"] : nil;
68
+ NSString *executablePath = [appPath stringByAppendingPathComponent:@"Contents/MacOS/cc-pets"];
69
+ if (![installedVersion isEqualToString:version] ||
70
+ ![NSFileManager.defaultManager isExecutableFileAtPath:executablePath]) return NO;
71
+
72
+ NSTask *restartTask = [NSTask new];
73
+ restartTask.executableURL = [NSURL fileURLWithPath:executablePath];
74
+ restartTask.arguments = @[
75
+ @"--restart-after-pid",
76
+ [NSString stringWithFormat:@"%d", NSProcessInfo.processInfo.processIdentifier],
77
+ appPath,
78
+ self.managedByCLI ? @"--managed" : @"--standalone"
79
+ ];
80
+ NSError *error = nil;
81
+ if (![restartTask launchAndReturnError:&error]) return NO;
82
+ [NSApp terminate:nil];
83
+ return YES;
84
+ }
85
+ - (void)startUpdateToVersion:(NSString *)version {
86
+ if (self.updating) return;
87
+ NSDictionary *configuration = [self updaterConfiguration];
88
+ NSString *nodePath = [configuration[@"nodePath"] isKindOfClass:NSString.class]
89
+ ? [configuration[@"nodePath"] stringByStandardizingPath] : nil;
90
+ NSString *npmCliPath = [configuration[@"npmCliPath"] isKindOfClass:NSString.class]
91
+ ? [configuration[@"npmCliPath"] stringByStandardizingPath] : nil;
92
+ BOOL nodeExecutable = nodePath.isAbsolutePath &&
93
+ [NSFileManager.defaultManager isExecutableFileAtPath:nodePath];
94
+ BOOL npmCliExists = npmCliPath.isAbsolutePath &&
95
+ [NSFileManager.defaultManager isReadableFileAtPath:npmCliPath];
96
+ if (!nodeExecutable || !npmCliExists) {
97
+ [self showUpdateAlertWithTitle:@"无法自动更新"
98
+ message:@"没有找到安装 CC Pets 时使用的 Node.js/npm。请先手动执行一次:\n\n"
99
+ "npm install -g cc-pets@latest --allow-scripts=cc-pets --prefer-online"];
100
+ return;
101
+ }
102
+
103
+ NSString *supportDirectory = [self applicationSupportDirectory];
104
+ NSError *directoryError = nil;
105
+ [NSFileManager.defaultManager createDirectoryAtPath:supportDirectory
106
+ withIntermediateDirectories:YES attributes:nil error:&directoryError];
107
+ if (directoryError) {
108
+ [self showUpdateAlertWithTitle:@"无法自动更新" message:directoryError.localizedDescription];
109
+ return;
110
+ }
111
+ NSString *logPath = [supportDirectory stringByAppendingPathComponent:@"update.log"];
112
+ [NSData.data writeToFile:logPath options:NSDataWritingAtomic error:nil];
113
+ chmod(logPath.fileSystemRepresentation, S_IRUSR | S_IWUSR);
114
+ NSFileHandle *logHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
115
+ if (!logHandle) {
116
+ [self showUpdateAlertWithTitle:@"无法自动更新" message:@"无法创建更新日志。"];
117
+ return;
118
+ }
119
+
120
+ NSTask *task = [NSTask new];
121
+ task.executableURL = [NSURL fileURLWithPath:nodePath];
122
+ task.arguments = @[
123
+ npmCliPath,
124
+ @"install",
125
+ @"--global",
126
+ [@"cc-pets@" stringByAppendingString:version],
127
+ @"--allow-scripts=cc-pets",
128
+ @"--prefer-online"
129
+ ];
130
+ NSMutableDictionary<NSString *, NSString *> *environment =
131
+ [NSProcessInfo.processInfo.environment mutableCopy];
132
+ NSString *nodeDirectory = nodePath.stringByDeletingLastPathComponent;
133
+ NSString *existingPath = environment[@"PATH"];
134
+ if (existingPath.length == 0) existingPath = @"/usr/bin:/bin:/usr/sbin:/sbin";
135
+ environment[@"PATH"] = [NSString stringWithFormat:@"%@:%@", nodeDirectory, existingPath];
136
+ task.environment = environment;
137
+ task.currentDirectoryURL = [NSURL fileURLWithPath:NSHomeDirectory()];
138
+ task.standardOutput = logHandle;
139
+ task.standardError = logHandle;
140
+ self.updating = YES;
141
+ self.updateTask = task;
142
+ __weak typeof(self) weakSelf = self;
143
+ task.terminationHandler = ^(NSTask *finishedTask) {
144
+ [logHandle closeFile];
145
+ TrimUpdateLog(logPath);
146
+ dispatch_async(dispatch_get_main_queue(), ^{
147
+ typeof(self) strongSelf = weakSelf;
148
+ if (!strongSelf) return;
149
+ strongSelf.updating = NO;
150
+ strongSelf.updateTask = nil;
151
+ if (finishedTask.terminationStatus == EXIT_SUCCESS) {
152
+ if ([strongSelf restartAfterUpdateToVersion:version configuration:configuration]) return;
153
+ [strongSelf showUpdateAlertWithTitle:@"更新完成"
154
+ message:@"CC Pets 已更新,但没有找到可自动启动的新版应用,请手动重新启动一次。"];
155
+ return;
156
+ }
157
+ [NSApp activateIgnoringOtherApps:YES];
158
+ NSAlert *alert = [NSAlert new];
159
+ alert.messageText = @"更新失败";
160
+ alert.informativeText = [NSString stringWithFormat:
161
+ @"旧版本仍可继续使用。错误详情已写入:\n%@", logPath];
162
+ [alert addButtonWithTitle:@"打开日志"];
163
+ [alert addButtonWithTitle:@"关闭"];
164
+ if ([alert runModal] == NSAlertFirstButtonReturn) {
165
+ [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:logPath]];
166
+ }
167
+ });
168
+ };
169
+ NSError *launchError = nil;
170
+ if (![task launchAndReturnError:&launchError]) {
171
+ self.updating = NO;
172
+ self.updateTask = nil;
173
+ [logHandle closeFile];
174
+ [self showUpdateAlertWithTitle:@"无法启动更新" message:launchError.localizedDescription];
175
+ return;
176
+ }
177
+ [self showUpdateAlertWithTitle:@"正在更新"
178
+ message:[NSString stringWithFormat:@"正在下载并安装 CC Pets %@。完成后桌宠会自动重启。", version]];
179
+ }
180
+ - (void)checkForUpdates:(id)sender {
181
+ if (self.checkingForUpdate || self.updating) return;
182
+ self.checkingForUpdate = YES;
183
+ NSURL *url = [NSURL URLWithString:@"https://registry.npmjs.org/cc-pets/latest"];
184
+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
185
+ cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
186
+ [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
187
+ __weak typeof(self) weakSelf = self;
188
+ NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithRequest:request
189
+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
190
+ dispatch_async(dispatch_get_main_queue(), ^{
191
+ typeof(self) strongSelf = weakSelf;
192
+ if (!strongSelf) return;
193
+ strongSelf.checkingForUpdate = NO;
194
+ NSHTTPURLResponse *httpResponse = [response isKindOfClass:NSHTTPURLResponse.class]
195
+ ? (NSHTTPURLResponse *)response : nil;
196
+ NSDictionary *metadata = data
197
+ ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
198
+ NSString *latestVersion = [metadata[@"version"] isKindOfClass:NSString.class]
199
+ ? metadata[@"version"] : nil;
200
+ BOOL valid = NO;
201
+ NSComparisonResult comparison = CompareStableVersions(@CC_PETS_VERSION, latestVersion, &valid);
202
+ if (error || httpResponse.statusCode != 200 || !valid) {
203
+ NSString *message = error.localizedDescription ?: @"npm Registry 返回了无效的版本信息,请稍后重试。";
204
+ [strongSelf showUpdateAlertWithTitle:@"检查更新失败" message:message];
205
+ return;
206
+ }
207
+ if (comparison != NSOrderedAscending) {
208
+ [strongSelf showUpdateAlertWithTitle:@"已是最新版本"
209
+ message:[NSString stringWithFormat:@"当前版本:%@", @CC_PETS_VERSION]];
210
+ return;
211
+ }
212
+ [NSApp activateIgnoringOtherApps:YES];
213
+ NSAlert *alert = [NSAlert new];
214
+ alert.messageText = @"发现新版本";
215
+ alert.informativeText = [NSString stringWithFormat:
216
+ @"当前版本:%@\n最新版本:%@\n\n是否立即更新?", @CC_PETS_VERSION, latestVersion];
217
+ [alert addButtonWithTitle:@"立即更新"];
218
+ [alert addButtonWithTitle:@"稍后"];
219
+ if ([alert runModal] == NSAlertFirstButtonReturn) {
220
+ [strongSelf startUpdateToVersion:latestVersion];
221
+ }
222
+ });
223
+ }];
224
+ [task resume];
225
+ }
226
+ - (void)toggleQuotaHistory:(NSButton *)sender {
227
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
228
+ BOOL enabled = ![defaults boolForKey:HistoryEnabledKey];
229
+ [defaults setBool:enabled forKey:HistoryEnabledKey];
230
+ sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
231
+ self.quotaView.historyEnabled = enabled;
232
+ [self refreshUsage:nil];
233
+ }
234
+ - (NSString *)notificationKeyForTag:(NSInteger)tag {
235
+ if (tag == 1) return NotificationCompletionKey;
236
+ if (tag == 2) return NotificationFailureKey;
237
+ if (tag == 3) return NotificationApprovalKey;
238
+ return nil;
239
+ }
240
+ - (void)toggleNotification:(NSButton *)sender {
241
+ NSString *key = [self notificationKeyForTag:sender.tag];
242
+ if (!key) return;
243
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
244
+ if ([defaults boolForKey:key]) {
245
+ [defaults setBool:NO forKey:key];
246
+ sender.state = NSControlStateValueOff;
247
+ return;
248
+ }
249
+ [UNUserNotificationCenter.currentNotificationCenter
250
+ requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound
251
+ completionHandler:^(BOOL granted, NSError *error) {
252
+ dispatch_async(dispatch_get_main_queue(), ^{
253
+ if (granted) {
254
+ [defaults setBool:YES forKey:key];
255
+ sender.state = NSControlStateValueOn;
256
+ } else {
257
+ sender.state = NSControlStateValueOff;
258
+ NSString *message = error.localizedDescription ?:
259
+ @"请在“系统设置 → 通知 → CC Pets”中允许通知后重试。";
260
+ [self showUpdateAlertWithTitle:@"无法启用系统通知" message:message];
261
+ }
262
+ });
263
+ }];
264
+ }
265
+ - (void)sendNotificationWithTitle:(NSString *)title body:(NSString *)body {
266
+ UNMutableNotificationContent *content = [UNMutableNotificationContent new];
267
+ content.title = title;
268
+ content.body = body;
269
+ content.sound = UNNotificationSound.defaultSound;
270
+ NSString *identifier = [@"cc-pets-" stringByAppendingString:NSUUID.UUID.UUIDString];
271
+ UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
272
+ content:content trigger:nil];
273
+ [UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:request
274
+ withCompletionHandler:nil];
275
+ }
276
+ - (void)notifyForRecord:(NSDictionary *)record {
277
+ NSString *event = record[@"event"];
278
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
279
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
280
+ if (provider.length == 0) provider = @"Agent";
281
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
282
+ if ([event isEqualToString:@"PermissionRequest"] &&
283
+ ![state isEqualToString:@"auto_review"] &&
284
+ [defaults boolForKey:NotificationApprovalKey]) {
285
+ [self sendNotificationWithTitle:@"等待审批"
286
+ body:[NSString stringWithFormat:@"%@ 正在等待操作。", provider]];
287
+ } else if ([event isEqualToString:@"StopFailure"] &&
288
+ [defaults boolForKey:NotificationFailureKey]) {
289
+ [self sendNotificationWithTitle:@"任务失败"
290
+ body:[NSString stringWithFormat:@"%@ 的任务执行失败。", provider]];
291
+ } else if (([event isEqualToString:@"Stop"] || [event isEqualToString:@"SessionEnd"]) &&
292
+ [defaults boolForKey:NotificationCompletionKey]) {
293
+ [self sendNotificationWithTitle:@"任务完成"
294
+ body:[NSString stringWithFormat:@"%@ 已完成当前任务。", provider]];
295
+ }
296
+ }
297
+ - (NSString *)statusTextForState:(NSString *)state tool:(NSString *)tool {
298
+ if ([state isEqualToString:@"starting"]) return @"正在启动";
299
+ if ([state isEqualToString:@"thinking"]) return @"正在思考";
300
+ if ([state isEqualToString:@"auto_review"]) return @"自动审批中";
301
+ if ([state isEqualToString:@"approval"]) return @"等待审批";
302
+ if ([state isEqualToString:@"subagent"]) return @"子 Agent 工作中";
303
+ if ([state isEqualToString:@"tool_completed"]) return @"操作已完成";
304
+ if ([state isEqualToString:@"tool_failed"]) return @"工具执行失败";
305
+ if ([state isEqualToString:@"completed"]) return @"任务已完成";
306
+ if ([state isEqualToString:@"failed"]) return @"任务失败";
307
+ if ([state isEqualToString:@"notification"]) return @"需要关注";
308
+ if ([state isEqualToString:@"tool"]) {
309
+ NSString *lower = tool.lowercaseString;
310
+ if ([lower containsString:@"bash"] || [lower containsString:@"exec"] ||
311
+ [lower containsString:@"shell"] || [lower containsString:@"terminal"]) return @"正在执行命令";
312
+ if ([lower containsString:@"patch"] || [lower containsString:@"edit"] ||
313
+ [lower containsString:@"write"]) return @"正在编辑文件";
314
+ if ([lower containsString:@"read"] || [lower containsString:@"search"] ||
315
+ [lower containsString:@"find"] || [lower containsString:@"grep"] ||
316
+ [lower containsString:@"glob"] || [lower containsString:@"web"] ||
317
+ [lower hasPrefix:@"mcp__"]) return @"正在查找资料";
318
+ if ([lower containsString:@"task"] || [lower containsString:@"agent"]) return @"子 Agent 工作中";
319
+ return @"正在使用工具";
320
+ }
321
+ return @"正在工作";
322
+ }
323
+ - (NSString *)statusDetailForState:(NSString *)state {
324
+ if ([state isEqualToString:@"starting"]) return @"正在准备当前会话…";
325
+ if ([state isEqualToString:@"thinking"]) return @"正在分析请求…";
326
+ if ([state isEqualToString:@"auto_review"]) return @"正在由 Auto-review 审核,无需手动操作。";
327
+ if ([state isEqualToString:@"approval"]) return @"请回到终端确认操作。";
328
+ if ([state isEqualToString:@"subagent"]) return @"正在协调子 Agent。";
329
+ if ([state isEqualToString:@"tool"]) return @"正在调用工具…";
330
+ if ([state isEqualToString:@"tool_completed"]) return @"工具调用已完成。";
331
+ if ([state isEqualToString:@"tool_failed"]) return @"工具执行失败,请查看终端。";
332
+ if ([state isEqualToString:@"completed"]) return @"好的,当前任务已经完成。";
333
+ if ([state isEqualToString:@"failed"]) return @"任务失败,请回到终端查看详情。";
334
+ if ([state isEqualToString:@"notification"]) return @"有一条状态需要你关注。";
335
+ return @"正在处理当前任务。";
336
+ }
337
+ - (NSColor *)statusColorForState:(NSString *)state {
338
+ if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) {
339
+ return [NSColor colorWithRed:0.18 green:0.68 blue:0.35 alpha:1];
340
+ }
341
+ if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) {
342
+ return [NSColor colorWithRed:0.86 green:0.28 blue:0.28 alpha:1];
343
+ }
344
+ if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) {
345
+ return [NSColor colorWithRed:0.92 green:0.58 blue:0.12 alpha:1];
346
+ }
347
+ return [NSColor colorWithRed:0.33 green:0.53 blue:0.78 alpha:1];
348
+ }
349
+ - (NSString *)statusSymbolForState:(NSString *)state {
350
+ if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) return @"checkmark";
351
+ if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) return @"xmark";
352
+ if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) return @"exclamationmark";
353
+ return @"ellipsis";
354
+ }
355
+ - (void)updateStatusToggleAppearance {
356
+ if (!self.hasAgentStatus) return;
357
+ NSColor *stateColor = [self statusColorForState:self.lastStatusState];
358
+ if (self.statusBubbleExpanded) {
359
+ self.statusToggleButton.title = @"";
360
+ self.statusToggleButton.imagePosition = NSImageOnly;
361
+ NSString *symbol = self.statusBubbleAbove ? @"chevron.down" : @"chevron.up";
362
+ NSImage *image = [NSImage imageWithSystemSymbolName:symbol accessibilityDescription:@"折叠状态"];
363
+ self.statusToggleButton.image = [image imageWithSymbolConfiguration:
364
+ [NSImageSymbolConfiguration configurationWithPointSize:11 weight:NSFontWeightSemibold]];
365
+ self.statusToggleButton.contentTintColor = NSColor.whiteColor;
366
+ self.statusToggleGlass.layer.backgroundColor =
367
+ [NSColor colorWithWhite:0.16 alpha:0.54].CGColor;
368
+ } else {
369
+ self.statusToggleButton.image = nil;
370
+ self.statusToggleButton.imagePosition = NSNoImage;
371
+ self.statusToggleButton.title = [NSString stringWithFormat:@"%ld",
372
+ (long)MAX(1, self.liveClientCount)];
373
+ self.statusToggleButton.font = [NSFont systemFontOfSize:11 weight:NSFontWeightSemibold];
374
+ self.statusToggleButton.contentTintColor = NSColor.whiteColor;
375
+ self.statusToggleGlass.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.72].CGColor;
376
+ }
377
+ }
378
+ // Codex / Claude 退出时不会补发结束事件:包装脚本最后一行是 exec,自身已经被
379
+ // 替换掉,装不上 EXIT trap。唯一可靠的退出信号是客户端 pid 文件被回收。
380
+ // 没有这一步的话,“正在启动”只能等 60 秒无活动才消失,而另一个 provider 的事件
381
+ // 会不断把这 60 秒重置掉——用户关掉所有 Codex 窗口后仍然看到“Codex 正在启动”。
382
+ - (void)hideAgentStatusIfClientGone {
383
+ if (!self.hasAgentStatus || self.hasUnlabeledClient) return;
384
+ NSString *provider = self.lastStatusProvider;
385
+ if (provider.length == 0 || [self.liveClientProviders containsObject:provider]) return;
386
+ // 不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid 文件,只能靠
387
+ // “最近还在发事件”证明自己活着,所以这里必须留一段静默宽限再清。
388
+ if ([NSDate.date timeIntervalSince1970] - self.lastStatusTimestamp < AgentStatusOrphanInterval) return;
389
+ [self hideAgentStatus];
390
+ }
391
+ - (void)hideAgentStatus {
392
+ [self.statusPanel orderOut:nil];
393
+ [self.statusTogglePanel orderOut:nil];
394
+ self.hasAgentStatus = NO;
395
+ }
396
+ - (void)toggleAgentStatusBubble:(id)sender {
397
+ if (!self.hasAgentStatus) return;
398
+ self.statusBubbleExpanded = !self.statusBubbleExpanded;
399
+ [NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
400
+ forKey:StatusBubbleExpandedKey];
401
+ if (self.statusBubbleExpanded) {
402
+ [self.statusPanel orderFrontRegardless];
403
+ } else {
404
+ [self.statusPanel orderOut:nil];
405
+ }
406
+ [self positionAgentStatus];
407
+ [self updateStatusToggleAppearance];
408
+ [self.statusTogglePanel orderFrontRegardless];
409
+ }
410
+ - (void)showAgentStatusForRecord:(NSDictionary *)record notify:(BOOL)shouldNotify {
411
+ [NSObject cancelPreviousPerformRequestsWithTarget:self
412
+ selector:@selector(hideAgentStatus) object:nil];
413
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
414
+ if (provider.length == 0) provider = @"Agent";
415
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class]
416
+ ? record[@"state"] : NormalizedStateForEvent(record[@"event"], [record[@"failed"] boolValue]);
417
+ NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
418
+ self.hasAgentStatus = YES;
419
+ self.lastStatusState = state;
420
+ self.lastStatusProvider = provider;
421
+ self.lastStatusTimestamp = [NSDate.date timeIntervalSince1970];
422
+ self.statusTitleLabel.stringValue = [NSString stringWithFormat:@"%@ · %@",
423
+ provider, [self statusTextForState:state tool:tool]];
424
+ self.statusDetailLabel.stringValue = [self statusDetailForState:state];
425
+ NSColor *stateColor = [self statusColorForState:state];
426
+ self.statusIconButton.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.28].CGColor;
427
+ NSImage *icon = [NSImage imageWithSystemSymbolName:[self statusSymbolForState:state]
428
+ accessibilityDescription:[self statusTextForState:state tool:tool]];
429
+ self.statusIconButton.image = [icon imageWithSymbolConfiguration:
430
+ [NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightBold]];
431
+ self.statusIconButton.contentTintColor = [stateColor blendedColorWithFraction:0.18
432
+ ofColor:NSColor.blackColor] ?: stateColor;
433
+ [self positionAgentStatus];
434
+ if (self.statusBubbleExpanded) [self.statusPanel orderFrontRegardless];
435
+ else [self.statusPanel orderOut:nil];
436
+ [self updateStatusToggleAppearance];
437
+ [self.statusTogglePanel orderFrontRegardless];
438
+ [self.panel orderFrontRegardless];
439
+ [self performSelector:@selector(hideAgentStatus)
440
+ withObject:nil afterDelay:AgentStatusInactivityInterval];
441
+ if (shouldNotify) [self notifyForRecord:record];
442
+ }
443
+ - (void)showAgentStatusForRecord:(NSDictionary *)record {
444
+ [self showAgentStatusForRecord:record notify:YES];
445
+ }
446
+ - (NSString *)approvalKeyForRecord:(NSDictionary *)record {
447
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
448
+ if (provider.length == 0) provider = @"Agent";
449
+ NSString *session = SanitizedShortString(record[@"session"], 128);
450
+ return session.length > 0
451
+ ? [NSString stringWithFormat:@"%@:%@", provider, session]
452
+ : provider;
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
+ }
477
+ - (NSDictionary *)latestPendingApprovalRecord {
478
+ NSDictionary *latest = nil;
479
+ for (NSDictionary *record in self.pendingApprovalRecords.allValues) {
480
+ if (!latest || [record[@"timestamp"] doubleValue] > [latest[@"timestamp"] doubleValue]) {
481
+ latest = record;
482
+ }
483
+ }
484
+ return latest;
485
+ }
486
+ - (void)displayAgentRecord:(NSDictionary *)record notify:(BOOL)shouldNotify {
487
+ NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
488
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
489
+ NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
490
+ NSString *animationEvent = [state isEqualToString:@"auto_review"]
491
+ ? @"AutoReviewRequest" : event;
492
+ [self.petView handleAgentEvent:animationEvent tool:tool
493
+ failed:[record[@"failed"] boolValue]];
494
+ [self showAgentStatusForRecord:record notify:shouldNotify];
495
+ }
496
+ - (NSDictionary *)petManifestInDirectory:(NSString *)directory {
497
+ NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
498
+ NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
499
+ if (!jsonData) return @{};
500
+ id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
501
+ return [json isKindOfClass:NSDictionary.class] ? json : @{};
502
+ }
503
+ - (NSInteger)spriteVersionInDirectory:(NSString *)directory fallbackDirectory:(NSString *)fallbackDirectory {
504
+ NSArray<NSString *> *directories = fallbackDirectory.length > 0
505
+ ? @[directory, fallbackDirectory]
506
+ : @[directory];
507
+ for (NSString *candidate in directories) {
508
+ id value = [self petManifestInDirectory:candidate][@"spriteVersionNumber"];
509
+ if (![value isKindOfClass:NSNumber.class]) continue;
510
+ NSInteger version = [value integerValue];
511
+ if (version == 1 || version == 2) return version;
512
+ }
513
+ return 1;
514
+ }
515
+ - (NSInteger)spriteRowCountForVersion:(NSInteger)version {
516
+ return version == 2 ? 11 : 9;
517
+ }
518
+ - (NSString *)spritePathInDirectory:(NSString *)directory {
519
+ NSString *configuredName = nil;
520
+ id value = [self petManifestInDirectory:directory][@"spritesheetPath"];
521
+ if ([value isKindOfClass:NSString.class]) configuredName = [value lastPathComponent];
522
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
523
+ if (configuredName.length > 0) [names addObject:configuredName];
524
+ [names addObjectsFromArray:@[@"spritesheet.webp", @"spritesheet.png"]];
525
+ for (NSString *name in names) {
526
+ NSString *path = [directory stringByAppendingPathComponent:name];
527
+ BOOL isDirectory = NO;
528
+ if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && !isDirectory) return path;
529
+ }
530
+ return nil;
531
+ }
532
+ - (NSArray<NSString *> *)petDirectoryNamesAtPath:(NSString *)root {
533
+ NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:root error:nil] ?: @[];
534
+ NSMutableArray<NSString *> *directories = [NSMutableArray array];
535
+ for (NSString *entry in entries) {
536
+ if ([entry hasPrefix:@"."]) continue;
537
+ BOOL isDirectory = NO;
538
+ NSString *path = [root stringByAppendingPathComponent:entry];
539
+ if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory) {
540
+ [directories addObject:entry];
541
+ }
542
+ }
543
+ return [directories sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
544
+ }
545
+ - (NSArray<NSDictionary *> *)discoverPetOptions {
546
+ NSString *home = NSHomeDirectory();
547
+ NSString *petdexRoot = [home stringByAppendingPathComponent:@".petdex/pets"];
548
+ NSString *codexRoot = [home stringByAppendingPathComponent:@".codex/pets"];
549
+ NSMutableArray<NSDictionary *> *result = [NSMutableArray array];
550
+ NSMutableSet<NSString *> *externalNames = [NSMutableSet set];
551
+
552
+ for (NSString *name in [self petDirectoryNamesAtPath:petdexRoot]) {
553
+ NSString *petdexDirectory = [petdexRoot stringByAppendingPathComponent:name];
554
+ NSString *codexDirectory = [codexRoot stringByAppendingPathComponent:name];
555
+ NSString *path = [self spritePathInDirectory:petdexDirectory];
556
+ if (!path) path = [self spritePathInDirectory:codexDirectory];
557
+ if (!path) continue;
558
+ NSInteger version = [self spriteVersionInDirectory:petdexDirectory fallbackDirectory:codexDirectory];
559
+ [result addObject:@{
560
+ @"id": [@"external:" stringByAppendingString:name],
561
+ @"name": name,
562
+ @"path": path,
563
+ @"spriteVersionNumber": @(version),
564
+ @"spriteRowCount": @([self spriteRowCountForVersion:version])
565
+ }];
566
+ [externalNames addObject:name];
567
+ }
568
+ for (NSString *name in [self petDirectoryNamesAtPath:codexRoot]) {
569
+ if ([externalNames containsObject:name]) continue;
570
+ NSString *codexDirectory = [codexRoot stringByAppendingPathComponent:name];
571
+ NSString *path = [self spritePathInDirectory:codexDirectory];
572
+ if (!path) continue;
573
+ NSInteger version = [self spriteVersionInDirectory:codexDirectory fallbackDirectory:nil];
574
+ [result addObject:@{
575
+ @"id": [@"external:" stringByAppendingString:name],
576
+ @"name": name,
577
+ @"path": path,
578
+ @"spriteVersionNumber": @(version),
579
+ @"spriteRowCount": @([self spriteRowCountForVersion:version])
580
+ }];
581
+ [externalNames addObject:name];
582
+ }
583
+
584
+ NSArray<NSString *> *bundled = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
585
+ for (NSString *fileName in [bundled sortedArrayUsingSelector:@selector(localizedStandardCompare:)]) {
586
+ NSString *extension = fileName.pathExtension.lowercaseString;
587
+ if (![extension isEqualToString:@"webp"] && ![extension isEqualToString:@"png"]) continue;
588
+ [result addObject:@{
589
+ @"id": [@"builtin:" stringByAppendingString:fileName],
590
+ @"name": fileName.stringByDeletingPathExtension,
591
+ @"path": [self.binaryDirectory stringByAppendingPathComponent:fileName],
592
+ @"spriteVersionNumber": @1,
593
+ @"spriteRowCount": @9
594
+ }];
595
+ }
596
+ return result;
597
+ }
598
+ - (NSDictionary *)petOptionWithID:(NSString *)petID inOptions:(NSArray<NSDictionary *> *)options {
599
+ for (NSDictionary *option in options) if ([option[@"id"] isEqualToString:petID]) return option;
600
+ return nil;
601
+ }
602
+ - (NSArray<NSDictionary *> *)waitForPetOptions {
603
+ while (YES) {
604
+ NSArray<NSDictionary *> *options = [self discoverPetOptions];
605
+ if (options.count > 0) return options;
606
+
607
+ [NSApp activateIgnoringOtherApps:YES];
608
+ NSAlert *alert = [NSAlert new];
609
+ alert.messageText = @"没有找到桌宠素材";
610
+ alert.informativeText = @"请将 PNG 或 WebP 精灵图放入 ~/.petdex/pets/<名称>/ 或 "
611
+ @"~/.codex/pets/<名称>/,也可以通过 PetDex 安装。完成后点击“重新扫描”。";
612
+ [alert addButtonWithTitle:@"重新扫描"];
613
+ [alert addButtonWithTitle:@"打开素材目录"];
614
+ [alert addButtonWithTitle:@"退出"];
615
+ NSModalResponse response = [alert runModal];
616
+ if (response == NSAlertSecondButtonReturn) {
617
+ NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@".petdex/pets"];
618
+ [NSFileManager.defaultManager createDirectoryAtPath:directory
619
+ withIntermediateDirectories:YES attributes:nil error:nil];
620
+ [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:directory]];
621
+ } else if (response == NSAlertThirdButtonReturn) {
622
+ return @[];
623
+ }
624
+ }
625
+ }
626
+ - (void)applicationDidFinishLaunching:(NSNotification *)notification {
627
+ self.managedByCLI = [NSProcessInfo.processInfo.arguments containsObject:@"--managed"];
628
+ NSString *binaryDir = NSProcessInfo.processInfo.arguments.firstObject.stringByStandardizingPath.stringByDeletingLastPathComponent;
629
+ NSBundle *mainBundle = NSBundle.mainBundle;
630
+ BOOL runsFromAppBundle = [mainBundle.bundlePath.pathExtension.lowercaseString isEqualToString:@"app"];
631
+ self.binaryDirectory = runsFromAppBundle && mainBundle.resourcePath.length > 0
632
+ ? mainBundle.resourcePath
633
+ : binaryDir;
634
+ NSArray<NSDictionary *> *petOptions = [self waitForPetOptions];
635
+ if (petOptions.count == 0) {
636
+ [NSApp terminate:nil];
637
+ return;
638
+ }
639
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
640
+ [defaults registerDefaults:@{StatusBubbleExpandedKey: @YES}];
641
+ if (![defaults boolForKey:StatusBubblePreferenceV2Key]) {
642
+ [defaults setBool:YES forKey:StatusBubbleExpandedKey];
643
+ [defaults setBool:YES forKey:StatusBubblePreferenceV2Key];
644
+ }
645
+ self.statusBubbleExpanded = [defaults boolForKey:StatusBubbleExpandedKey];
646
+ NSString *selected = [defaults stringForKey:@"CCPetsSelectedSprite"];
647
+ if (selected.length == 0) {
648
+ NSDictionary *legacyDefaults = [defaults persistentDomainForName:@"com.universewang.codex-pet"];
649
+ NSString *legacySelected = [legacyDefaults[@"CodexPetSelectedSprite"] isKindOfClass:NSString.class]
650
+ ? legacyDefaults[@"CodexPetSelectedSprite"] : nil;
651
+ if (legacySelected.length > 0) {
652
+ selected = legacySelected;
653
+ [defaults setObject:selected forKey:@"CCPetsSelectedSprite"];
654
+ }
655
+ }
656
+ if (selected.length > 0 && ![selected containsString:@":"]) selected = [@"builtin:" stringByAppendingString:selected];
657
+ NSDictionary *selectedOption = [self petOptionWithID:selected inOptions:petOptions] ?: petOptions.firstObject;
658
+ selected = selectedOption[@"id"];
659
+ NSString *spritePath = selectedOption[@"path"];
660
+ NSImage *image = LoadPetSpriteImage(spritePath, NSMakeSize(140, 150),
661
+ [selectedOption[@"spriteRowCount"] integerValue] ?: 9);
662
+ if (!image) {
663
+ fprintf(stderr, "无法读取桌宠素材: %s\n", spritePath.UTF8String);
664
+ [NSApp terminate:nil];
665
+ return;
666
+ }
667
+
668
+ NSSize size = NSMakeSize(230, 170);
669
+ self.panel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, size.width, size.height)
670
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
671
+ backing:NSBackingStoreBuffered defer:NO];
672
+ self.panel.opaque = NO;
673
+ self.panel.backgroundColor = NSColor.clearColor;
674
+ self.panel.hasShadow = NO;
675
+ self.panel.level = NSFloatingWindowLevel;
676
+ self.panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
677
+ self.panel.movableByWindowBackground = YES;
678
+ self.panel.hidesOnDeactivate = NO;
679
+
680
+ NSView *root = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
681
+ self.panel.contentView = root;
682
+ NSInteger spriteRowCount = [selectedOption[@"spriteRowCount"] integerValue] ?: 9;
683
+ self.petView = [[PetView alloc] initWithFrame:NSMakeRect(43, 0, 144, 150)
684
+ sheet:image rowCount:spriteRowCount];
685
+ self.petView.currentPetID = selected;
686
+ __weak typeof(self) weakSelf = self;
687
+ self.petView.pocketHoverChanged = ^(BOOL hovering) {
688
+ weakSelf.pocketHovering = hovering;
689
+ if (hovering) [weakSelf showQuotaDashboard];
690
+ else [weakSelf scheduleQuotaDashboardHide];
691
+ };
692
+ self.petView.petOptionsRequested = ^NSArray<NSDictionary *> *{
693
+ return [weakSelf discoverPetOptions] ?: @[];
694
+ };
695
+ self.petView.switchPetRequested = ^(NSString *petID) {
696
+ [weakSelf switchPetToID:petID];
697
+ };
698
+ self.petView.positionChanged = ^{
699
+ if (weakSelf.quotaPanel.isVisible) [weakSelf positionQuotaDashboard];
700
+ if (weakSelf.statusPanel.isVisible || weakSelf.statusTogglePanel.isVisible) {
701
+ [weakSelf positionAgentStatus];
702
+ }
703
+ };
704
+ self.petView.dragStateChanged = ^(BOOL dragging) {
705
+ weakSelf.petDragging = dragging;
706
+ if (!dragging) [weakSelf scheduleQuotaDashboardHide];
707
+ };
708
+ [root addSubview:self.petView];
709
+
710
+ NSSize statusGlassSize = NSMakeSize(340, 58);
711
+ NSSize statusSize = NSMakeSize(statusGlassSize.width + 12, statusGlassSize.height + 12);
712
+ self.statusPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0,
713
+ statusSize.width, statusSize.height)
714
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
715
+ backing:NSBackingStoreBuffered defer:NO];
716
+ self.statusPanel.opaque = NO;
717
+ self.statusPanel.backgroundColor = NSColor.clearColor;
718
+ self.statusPanel.hasShadow = NO;
719
+ self.statusPanel.ignoresMouseEvents = YES;
720
+ self.statusPanel.level = NSFloatingWindowLevel;
721
+ self.statusPanel.collectionBehavior =
722
+ NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
723
+ self.statusPanel.hidesOnDeactivate = NO;
724
+ NSView *statusRoot = [[NSView alloc] initWithFrame:NSMakeRect(
725
+ 0, 0, statusSize.width, statusSize.height)];
726
+ NSView *statusShadow = [[NSView alloc] initWithFrame:NSMakeRect(
727
+ 6, 6, statusGlassSize.width, statusGlassSize.height)];
728
+ statusShadow.wantsLayer = YES;
729
+ statusShadow.layer.backgroundColor = [NSColor colorWithWhite:0 alpha:0.01].CGColor;
730
+ statusShadow.layer.cornerRadius = statusGlassSize.height / 2.0;
731
+ statusShadow.layer.cornerCurve = kCACornerCurveContinuous;
732
+ statusShadow.layer.shadowColor = NSColor.blackColor.CGColor;
733
+ statusShadow.layer.shadowOpacity = 0.24;
734
+ statusShadow.layer.shadowRadius = 8;
735
+ statusShadow.layer.shadowOffset = NSMakeSize(0, -3);
736
+ CGPathRef statusShadowPath = CGPathCreateWithRoundedRect(
737
+ statusShadow.bounds, statusGlassSize.height / 2.0,
738
+ statusGlassSize.height / 2.0, NULL);
739
+ statusShadow.layer.shadowPath = statusShadowPath;
740
+ CGPathRelease(statusShadowPath);
741
+ [statusRoot addSubview:statusShadow];
742
+
743
+ self.statusGlass = [[NSVisualEffectView alloc]
744
+ initWithFrame:NSMakeRect(6, 6, statusGlassSize.width, statusGlassSize.height)];
745
+ self.statusGlass.material = NSVisualEffectMaterialPopover;
746
+ self.statusGlass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
747
+ self.statusGlass.state = NSVisualEffectStateActive;
748
+ self.statusGlass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
749
+ self.statusGlass.wantsLayer = YES;
750
+ self.statusGlass.layer.cornerRadius = statusGlassSize.height / 2.0;
751
+ self.statusGlass.layer.cornerCurve = kCACornerCurveContinuous;
752
+ self.statusGlass.layer.masksToBounds = YES;
753
+ self.statusGlass.layer.borderWidth = 1;
754
+ self.statusGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
755
+
756
+ self.statusTitleLabel = [NSTextField labelWithString:@""];
757
+ self.statusTitleLabel.frame = NSMakeRect(20, 30, statusGlassSize.width - 80, 18);
758
+ self.statusTitleLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold];
759
+ self.statusTitleLabel.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
760
+ self.statusTitleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
761
+ [self.statusGlass addSubview:self.statusTitleLabel];
762
+
763
+ self.statusDetailLabel = [NSTextField labelWithString:@""];
764
+ self.statusDetailLabel.frame = NSMakeRect(20, 12, statusGlassSize.width - 80, 17);
765
+ self.statusDetailLabel.font = [NSFont systemFontOfSize:12 weight:NSFontWeightRegular];
766
+ self.statusDetailLabel.textColor = [NSColor colorWithWhite:0.34 alpha:0.88];
767
+ self.statusDetailLabel.lineBreakMode = NSLineBreakByTruncatingTail;
768
+ [self.statusGlass addSubview:self.statusDetailLabel];
769
+
770
+ self.statusIconButton = [[NSButton alloc] initWithFrame:NSMakeRect(
771
+ statusGlassSize.width - 48, 12, 34, 34)];
772
+ self.statusIconButton.bordered = NO;
773
+ self.statusIconButton.imagePosition = NSImageOnly;
774
+ self.statusIconButton.wantsLayer = YES;
775
+ self.statusIconButton.layer.cornerRadius = 17;
776
+ self.statusIconButton.layer.masksToBounds = YES;
777
+ [self.statusGlass addSubview:self.statusIconButton];
778
+ [statusRoot addSubview:self.statusGlass];
779
+ self.statusPanel.contentView = statusRoot;
780
+
781
+ NSSize toggleSize = NSMakeSize(28, 28);
782
+ self.statusTogglePanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0,
783
+ toggleSize.width, toggleSize.height)
784
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
785
+ backing:NSBackingStoreBuffered defer:NO];
786
+ self.statusTogglePanel.opaque = NO;
787
+ self.statusTogglePanel.backgroundColor = NSColor.clearColor;
788
+ self.statusTogglePanel.hasShadow = YES;
789
+ self.statusTogglePanel.ignoresMouseEvents = NO;
790
+ self.statusTogglePanel.level = NSFloatingWindowLevel;
791
+ self.statusTogglePanel.collectionBehavior =
792
+ NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
793
+ self.statusTogglePanel.hidesOnDeactivate = NO;
794
+ self.statusToggleGlass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(
795
+ 0, 0, toggleSize.width, toggleSize.height)];
796
+ self.statusToggleGlass.material = NSVisualEffectMaterialHUDWindow;
797
+ self.statusToggleGlass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
798
+ self.statusToggleGlass.state = NSVisualEffectStateActive;
799
+ self.statusToggleGlass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
800
+ self.statusToggleGlass.wantsLayer = YES;
801
+ self.statusToggleGlass.layer.cornerRadius = 14;
802
+ self.statusToggleGlass.layer.masksToBounds = YES;
803
+ self.statusToggleGlass.layer.borderWidth = 1;
804
+ self.statusToggleGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.24].CGColor;
805
+ self.statusToggleButton = [[NSButton alloc] initWithFrame:self.statusToggleGlass.bounds];
806
+ self.statusToggleButton.bordered = NO;
807
+ self.statusToggleButton.imagePosition = NSImageOnly;
808
+ self.statusToggleButton.target = self;
809
+ self.statusToggleButton.action = @selector(toggleAgentStatusBubble:);
810
+ [self.statusToggleGlass addSubview:self.statusToggleButton];
811
+ self.statusTogglePanel.contentView = self.statusToggleGlass;
812
+
813
+ NSSize quotaSize = NSMakeSize(QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale);
814
+ self.quotaPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)
815
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
816
+ backing:NSBackingStoreBuffered defer:NO];
817
+ self.quotaPanel.opaque = NO;
818
+ self.quotaPanel.backgroundColor = NSColor.clearColor;
819
+ self.quotaPanel.hasShadow = YES;
820
+ self.quotaPanel.acceptsMouseMovedEvents = YES;
821
+ self.quotaPanel.ignoresMouseEvents = NO;
822
+ self.quotaPanel.level = NSFloatingWindowLevel;
823
+ self.quotaPanel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
824
+ self.quotaPanel.hidesOnDeactivate = NO;
825
+ NSView *quotaRoot = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
826
+ NSVisualEffectView *glass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(0, 0,
827
+ quotaSize.width, quotaSize.height)];
828
+ glass.material = NSVisualEffectMaterialUnderWindowBackground;
829
+ glass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
830
+ glass.state = NSVisualEffectStateActive;
831
+ glass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
832
+ glass.wantsLayer = YES;
833
+ glass.layer.cornerRadius = 13;
834
+ glass.layer.masksToBounds = YES;
835
+ [quotaRoot addSubview:glass];
836
+ self.quotaView = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
837
+ self.quotaView.historyEnabled = [defaults boolForKey:HistoryEnabledKey];
838
+ self.quotaView.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
839
+ self.quotaView.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
840
+ self.quotaView.hoverChanged = ^(BOOL hovering) {
841
+ weakSelf.dashboardHovering = hovering;
842
+ if (!hovering) [weakSelf scheduleQuotaDashboardHide];
843
+ };
844
+ self.quotaView.refreshRequested = ^{
845
+ [weakSelf refreshUsage:nil];
846
+ };
847
+ [quotaRoot addSubview:self.quotaView];
848
+ self.quotaPanel.contentView = quotaRoot;
849
+
850
+ NSScreen *screen = NSScreen.mainScreen;
851
+ NSRect visible = screen.visibleFrame;
852
+ [self.panel setFrameOrigin:NSMakePoint(NSMaxX(visible) - size.width - 24, NSMinY(visible) + 18)];
853
+ [self.panel orderFrontRegardless];
854
+ self.usageMonitor = [CCPetsUsageMonitor new];
855
+ self.agentEventPartialLine = [NSMutableData data];
856
+ self.pendingApprovalRecords = [NSMutableDictionary dictionary];
857
+ self.usageMonitor.changeHandler = ^(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
858
+ [weakSelf applyCodexUsage:codexUsage claudeUsage:claudeUsage];
859
+ };
860
+ [self.usageMonitor start];
861
+ if ([NSProcessInfo.processInfo.arguments containsObject:@"--preview-dashboard"]) {
862
+ self.pocketHovering = YES;
863
+ [self showQuotaDashboard];
864
+ }
865
+ [self rescheduleUsageTimer];
866
+ [self refreshClientLifecycle:nil];
867
+ NSTimer *lifecycleTimer = [NSTimer scheduledTimerWithTimeInterval:ClientLifecycleInterval
868
+ target:self selector:@selector(refreshClientLifecycle:) userInfo:nil repeats:YES];
869
+ lifecycleTimer.tolerance = ClientLifecycleInterval * 0.3;
870
+ [self startAgentEventReader];
871
+ NSTimer *readerTimer = [NSTimer scheduledTimerWithTimeInterval:AgentEventReaderCheckInterval
872
+ target:self selector:@selector(ensureAgentEventReader:) userInfo:nil repeats:YES];
873
+ readerTimer.tolerance = AgentEventReaderCheckInterval * 0.3;
874
+ // 这里刻意不使用 occlusionState / NSWindowDidChangeOcclusionStateNotification:
875
+ // 桌宠是置顶的(NSFloatingWindowLevel + FullScreenAuxiliary),全屏应用也压不住它,
876
+ // 所以“被遮挡”几乎不会真实发生,收益接近零;而实测中 occlusionState 会在
877
+ // Space / 全屏过渡期间报出长达十几秒的“不可见”,那会把一只用户正看着的桌宠冻在
878
+ // 某一帧上。显示器睡眠则是无歧义的信号:屏幕灭了,桌宠必定不可见。
879
+ NSNotificationCenter *workspaceCenter = NSWorkspace.sharedWorkspace.notificationCenter;
880
+ [workspaceCenter addObserver:self selector:@selector(screensDidSleep:)
881
+ name:NSWorkspaceScreensDidSleepNotification object:nil];
882
+ [workspaceCenter addObserver:self selector:@selector(screensDidWake:)
883
+ name:NSWorkspaceScreensDidWakeNotification object:nil];
884
+ }
885
+ - (void)screensDidSleep:(NSNotification *)notification {
886
+ [self.petView setAnimationSuspended:YES];
887
+ }
888
+ - (void)screensDidWake:(NSNotification *)notification {
889
+ [self.petView setAnimationSuspended:NO];
890
+ }
891
+ - (void)rescheduleUsageTimer {
892
+ NSTimeInterval interval = self.quotaPanel.isVisible
893
+ ? UsageRefreshIntervalVisible : UsageRefreshIntervalHidden;
894
+ if (self.usageTimer.isValid && self.usageTimer.timeInterval == interval) return;
895
+ [self.usageTimer invalidate];
896
+ self.usageTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self
897
+ selector:@selector(refreshUsage:) userInfo:nil repeats:YES];
898
+ self.usageTimer.tolerance = interval * 0.2;
899
+ }
900
+ - (void)showQuotaDashboard {
901
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
902
+ [self refreshUsage:nil];
903
+ [self positionQuotaDashboard];
904
+ [self.quotaPanel orderFrontRegardless];
905
+ [self.panel orderFrontRegardless];
906
+ [self rescheduleUsageTimer];
907
+ }
908
+ - (void)positionQuotaDashboard {
909
+ NSRect petFrame = self.panel.frame;
910
+ NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
911
+ NSSize size = self.quotaPanel.frame.size;
912
+ CGFloat x = NSMinX(petFrame) - size.width + 55;
913
+ CGFloat y = NSMinY(petFrame) + 112;
914
+ x = fmax(NSMinX(visible) + 12, fmin(x, NSMaxX(visible) - size.width - 12));
915
+ y = fmax(NSMinY(visible) + 12, fmin(y, NSMaxY(visible) - size.height - 12));
916
+ [self.quotaPanel setFrameOrigin:NSMakePoint(x, y)];
917
+ }
918
+ - (void)positionAgentStatus {
919
+ NSRect petFrame = self.panel.frame;
920
+ NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
921
+ NSSize size = self.statusPanel.frame.size;
922
+ CGFloat x = NSMidX(petFrame) - size.width / 2.0;
923
+ CGFloat aboveY = NSMaxY(petFrame) + 8;
924
+ CGFloat belowY = NSMinY(petFrame) - size.height - 8;
925
+ BOOL aboveFits = aboveY + size.height <= NSMaxY(visible) - 10;
926
+ BOOL belowFits = belowY >= NSMinY(visible) + 10;
927
+ self.statusBubbleAbove = aboveFits || !belowFits;
928
+ CGFloat y = self.statusBubbleAbove ? aboveY : belowY;
929
+ x = fmax(NSMinX(visible) + 10, fmin(x, NSMaxX(visible) - size.width - 10));
930
+ y = fmax(NSMinY(visible) + 10, fmin(y, NSMaxY(visible) - size.height - 10));
931
+ [self.statusPanel setFrameOrigin:NSMakePoint(x, y)];
932
+
933
+ NSSize toggleSize = self.statusTogglePanel.frame.size;
934
+ NSRect petViewFrame = self.petView.frame;
935
+ CGFloat toggleX = NSMinX(petFrame) + NSMinX(petViewFrame) +
936
+ NSWidth(petViewFrame) * 0.82;
937
+ CGFloat toggleY = NSMinY(petFrame) + NSMinY(petViewFrame) +
938
+ NSHeight(petViewFrame) * 0.70;
939
+ toggleX = fmax(NSMinX(visible) + 8,
940
+ fmin(toggleX, NSMaxX(visible) - toggleSize.width - 8));
941
+ toggleY = fmax(NSMinY(visible) + 8,
942
+ fmin(toggleY, NSMaxY(visible) - toggleSize.height - 8));
943
+ [self.statusTogglePanel setFrameOrigin:NSMakePoint(toggleX, toggleY)];
944
+ [self updateStatusToggleAppearance];
945
+ }
946
+ - (void)scheduleQuotaDashboardHide {
947
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
948
+ [self performSelector:@selector(hideQuotaDashboardIfNeeded) withObject:nil afterDelay:0.28];
949
+ }
950
+ - (void)hideQuotaDashboardIfNeeded {
951
+ if (!self.pocketHovering && !self.dashboardHovering && !self.petDragging) {
952
+ [self.quotaPanel orderOut:nil];
953
+ [self rescheduleUsageTimer];
954
+ }
955
+ }
956
+ - (void)switchPetToID:(NSString *)petID {
957
+ NSArray<NSDictionary *> *options = [self discoverPetOptions];
958
+ NSDictionary *option = [self petOptionWithID:petID inOptions:options];
959
+ if (!option) return;
960
+ NSInteger spriteRowCount = [option[@"spriteRowCount"] integerValue] ?: 9;
961
+ NSImage *image = LoadPetSpriteImage(option[@"path"], NSMakeSize(140, 150), spriteRowCount);
962
+ if (!image) return;
963
+ [self.petView applySheet:image petID:petID rowCount:spriteRowCount];
964
+ [NSUserDefaults.standardUserDefaults setObject:petID forKey:@"CCPetsSelectedSprite"];
965
+ }
966
+ - (void)prepareAgentEventReader {
967
+ NSString *path = AgentEventPath();
968
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
969
+ unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
970
+ if (self.agentEventReaderInitialized) {
971
+ if (size < self.agentEventOffset) {
972
+ self.agentEventOffset = 0;
973
+ [self.agentEventPartialLine setLength:0];
974
+ }
975
+ [self readNewAgentEvents];
976
+ return;
977
+ }
978
+ self.agentEventReaderInitialized = YES;
979
+ self.agentEventOffset = size;
980
+ if (size > 0) {
981
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
982
+ unsigned long long start = size > 65536 ? size - 65536 : 0;
983
+ [handle seekToFileOffset:start];
984
+ NSData *recent = [handle readDataToEndOfFile];
985
+ [handle closeFile];
986
+ [self processAgentEventData:recent ignoreFirstPartial:start > 0 recentOnly:YES];
987
+ }
988
+ }
989
+ - (void)consumeAgentEventData:(NSData *)data {
990
+ if (data.length == 0) return;
991
+ [self.agentEventPartialLine appendData:data];
992
+ const uint8_t *bytes = self.agentEventPartialLine.bytes;
993
+ NSUInteger lineStart = 0;
994
+ for (NSUInteger index = 0; index < self.agentEventPartialLine.length; index++) {
995
+ if (bytes[index] != '\n') continue;
996
+ NSData *lineData = [self.agentEventPartialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
997
+ [self processAgentEventData:lineData ignoreFirstPartial:NO recentOnly:NO];
998
+ lineStart = index + 1;
999
+ }
1000
+ if (lineStart > 0) {
1001
+ NSData *remainder = [self.agentEventPartialLine subdataWithRange:
1002
+ NSMakeRange(lineStart, self.agentEventPartialLine.length - lineStart)];
1003
+ self.agentEventPartialLine = [remainder mutableCopy];
1004
+ }
1005
+ if (self.agentEventPartialLine.length > 1024 * 1024) [self.agentEventPartialLine setLength:0];
1006
+ }
1007
+ - (void)processAgentEventData:(NSData *)data ignoreFirstPartial:(BOOL)ignoreFirstPartial recentOnly:(BOOL)recentOnly {
1008
+ NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
1009
+ if (!text) return;
1010
+ NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
1011
+ NSTimeInterval cutoff = [NSDate.date timeIntervalSince1970] - 5;
1012
+ for (NSUInteger index = 0; index < lines.count; index++) {
1013
+ if (ignoreFirstPartial && index == 0) continue;
1014
+ NSData *lineData = [lines[index] dataUsingEncoding:NSUTF8StringEncoding];
1015
+ if (lineData.length == 0) continue;
1016
+ NSDictionary *record = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
1017
+ if (![record isKindOfClass:NSDictionary.class]) continue;
1018
+ if (recentOnly && [record[@"timestamp"] doubleValue] < cutoff) continue;
1019
+ NSString *event = record[@"event"];
1020
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
1021
+ if ([event isKindOfClass:NSString.class]) {
1022
+ if (!self.pendingApprovalRecords) {
1023
+ self.pendingApprovalRecords = [NSMutableDictionary dictionary];
1024
+ }
1025
+ [self prunePendingApprovalRecords];
1026
+ NSString *approvalKey = [self approvalKeyForRecord:record];
1027
+ NSDictionary *previousPriority = [self latestPendingApprovalRecord];
1028
+ BOOL manualApproval = [state isEqualToString:@"approval"];
1029
+ if (manualApproval) {
1030
+ self.pendingApprovalRecords[approvalKey] = record;
1031
+ } else {
1032
+ [self.pendingApprovalRecords removeObjectForKey:approvalKey];
1033
+ }
1034
+ [self prunePendingApprovalRecords];
1035
+ NSDictionary *currentPriority = [self latestPendingApprovalRecord];
1036
+ if (currentPriority) {
1037
+ if (manualApproval) {
1038
+ [self displayAgentRecord:currentPriority notify:YES];
1039
+ } else if (currentPriority != previousPriority) {
1040
+ [self displayAgentRecord:currentPriority notify:NO];
1041
+ }
1042
+ continue;
1043
+ }
1044
+ [self displayAgentRecord:record notify:YES];
1045
+ }
1046
+ }
1047
+ }
1048
+ - (void)readNewAgentEvents {
1049
+ NSString *path = AgentEventPath();
1050
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
1051
+ unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
1052
+ if (size < self.agentEventOffset) self.agentEventOffset = 0;
1053
+ if (size == self.agentEventOffset) return;
1054
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1055
+ if (!handle) return;
1056
+ unsigned long long start = self.agentEventOffset;
1057
+ [handle seekToFileOffset:start];
1058
+ NSData *data = [handle readDataToEndOfFile];
1059
+ [handle closeFile];
1060
+ self.agentEventOffset = start + data.length;
1061
+ [self consumeAgentEventData:data];
1062
+ }
1063
+ - (void)startAgentEventReader {
1064
+ if (self.agentEventSource) return;
1065
+ NSString *path = AgentEventPath();
1066
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
1067
+ withIntermediateDirectories:YES attributes:nil error:nil];
1068
+ int creator = open(path.fileSystemRepresentation, O_CREAT | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR);
1069
+ if (creator >= 0) close(creator);
1070
+ int descriptor = open(path.fileSystemRepresentation, O_EVTONLY | O_CLOEXEC);
1071
+ if (descriptor < 0) return;
1072
+ dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
1073
+ DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
1074
+ DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE,
1075
+ dispatch_get_main_queue());
1076
+ if (!source) {
1077
+ close(descriptor);
1078
+ return;
1079
+ }
1080
+ self.agentEventSource = source;
1081
+ __weak typeof(self) weakSelf = self;
1082
+ dispatch_source_set_event_handler(source, ^{
1083
+ typeof(self) strongSelf = weakSelf;
1084
+ if (!strongSelf) return;
1085
+ dispatch_source_t currentSource = strongSelf.agentEventSource;
1086
+ if (!currentSource) return;
1087
+ unsigned long flags = dispatch_source_get_data(currentSource);
1088
+ [strongSelf readNewAgentEvents];
1089
+ if (flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE)) {
1090
+ strongSelf.agentEventSource = nil;
1091
+ dispatch_source_cancel(currentSource);
1092
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
1093
+ dispatch_get_main_queue(), ^{ [weakSelf startAgentEventReader]; });
1094
+ }
1095
+ });
1096
+ dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
1097
+ dispatch_resume(source);
1098
+ [self prepareAgentEventReader];
1099
+ }
1100
+ - (void)ensureAgentEventReader:(id)sender {
1101
+ if (!self.agentEventSource) [self startAgentEventReader];
1102
+ }
1103
+ - (void)refreshClientLifecycle:(id)sender {
1104
+ [self prunePendingApprovalRecords];
1105
+ NSString *clientName = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
1106
+ NSString *clientDirectory = [PetStateDirectory() stringByAppendingPathComponent:clientName];
1107
+ NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
1108
+ NSInteger liveClients = 0;
1109
+ NSMutableSet<NSString *> *providers = [NSMutableSet set];
1110
+ BOOL unlabeled = NO;
1111
+ for (NSString *entry in entries) {
1112
+ pid_t pid = (pid_t)entry.intValue;
1113
+ BOOL alive = pid > 1 && (kill(pid, 0) == 0 || errno == EPERM);
1114
+ NSString *path = [clientDirectory stringByAppendingPathComponent:entry];
1115
+ if (!alive) {
1116
+ [NSFileManager.defaultManager removeItemAtPath:path error:nil];
1117
+ continue;
1118
+ }
1119
+ liveClients += 1;
1120
+ // 包装脚本会把 provider 名写进 pid 文件。1.0.2 及更早的版本只 touch 出
1121
+ // 空文件,升级后仍在运行的老客户端读出来是空的:这类当作“身份不明”,
1122
+ // 只要还有一个就不清场,避免把仍然活着的会话误判成已退出。
1123
+ NSString *label = [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]
1124
+ stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
1125
+ if (label.length > 0 && label.length <= 32) [providers addObject:label];
1126
+ else unlabeled = YES;
1127
+ }
1128
+ self.liveClientCount = liveClients;
1129
+ self.liveClientProviders = providers;
1130
+ self.hasUnlabeledClient = unlabeled;
1131
+ [self hideAgentStatusIfClientGone];
1132
+ if (self.statusTogglePanel.isVisible && !self.statusBubbleExpanded) {
1133
+ [self updateStatusToggleAppearance];
1134
+ }
1135
+ // 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
1136
+ // Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
1137
+ if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
1138
+ }
1139
+ - (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage {
1140
+ self.quotaView.codexUsage = codexUsage;
1141
+ self.quotaView.claudeUsage = claudeUsage;
1142
+ NSDictionary *history = RecordQuotaHistory(self.quotaView.codexUsage,
1143
+ self.quotaView.claudeUsage);
1144
+ self.quotaView.codexHistory = QuotaHistorySeries(history, @"codex");
1145
+ self.quotaView.claudeHistory = QuotaHistorySeries(history, @"claude");
1146
+ self.quotaView.needsDisplay = YES;
1147
+ }
1148
+ - (void)refreshUsage:(id)sender {
1149
+ [self.usageMonitor refreshNow];
1150
+ }
1151
+ - (void)applicationWillTerminate:(NSNotification *)notification {
1152
+ [self.usageMonitor stop];
1153
+ if (self.agentEventSource) {
1154
+ dispatch_source_cancel(self.agentEventSource);
1155
+ self.agentEventSource = nil;
1156
+ }
1157
+ }
1158
+ @end