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
@@ -1,2537 +1,17 @@
1
1
  #import <Cocoa/Cocoa.h>
2
- #import <UserNotifications/UserNotifications.h>
3
-
4
- #ifndef CC_PETS_VERSION
5
- #define CC_PETS_VERSION "unknown"
6
- #endif
2
+ #import "CCPetsAppDelegate.h"
3
+ #import "CCPetsEvents.h"
4
+ #import "CCPetsPaths.h"
5
+ #import "CCPetsPreviews.h"
6
+ #import "CCPetsQuotaHistory.h"
7
+ #import "CCPetsUsage.h"
8
+ #import "CCPetsVersion.h"
9
+ #import "CCPetsCleanup.h"
7
10
  #import <sys/file.h>
8
11
  #import <sys/stat.h>
9
12
  #import <fcntl.h>
10
- #import <signal.h>
11
13
  #import <unistd.h>
12
14
 
13
- static NSString *PetStateDirectory(void) {
14
- NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_STATE_DIR"];
15
- if (override.length > 0) return override.stringByStandardizingPath;
16
- return NSTemporaryDirectory();
17
- }
18
-
19
- static NSString *AgentEventPath(void) {
20
- NSString *name = [NSString stringWithFormat:@"cc-pets-%u-agent-events.ndjson", getuid()];
21
- return [PetStateDirectory() stringByAppendingPathComponent:name];
22
- }
23
-
24
- static NSString *ClaudeUsagePath(void) {
25
- NSString *name = [NSString stringWithFormat:@"cc-pets-%u-claude-usage.json", getuid()];
26
- return [PetStateDirectory() stringByAppendingPathComponent:name];
27
- }
28
-
29
- static NSString *ApplicationSupportDirectory(void) {
30
- NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_APPLICATION_SUPPORT_DIR"];
31
- if (override.length > 0) return override.stringByStandardizingPath;
32
- NSString *root = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject;
33
- return [root stringByAppendingPathComponent:@"CC Pets"];
34
- }
35
-
36
- static NSString *QuotaHistoryPath(void) {
37
- return [ApplicationSupportDirectory() stringByAppendingPathComponent:@"quota-history.json"];
38
- }
39
-
40
- static NSString *const HistoryEnabledKey = @"CCPetsQuotaHistoryEnabled";
41
- static NSString *const NotificationCompletionKey = @"CCPetsNotifyCompletion";
42
- static NSString *const NotificationFailureKey = @"CCPetsNotifyFailure";
43
- static NSString *const NotificationApprovalKey = @"CCPetsNotifyApproval";
44
- static NSString *const StatusBubbleExpandedKey = @"CCPetsStatusBubbleExpanded";
45
- static NSString *const StatusBubblePreferenceV2Key = @"CCPetsStatusBubblePreferenceV2";
46
- static const NSTimeInterval AgentStatusInactivityInterval = 60.0;
47
-
48
- static NSString *SanitizedShortString(id value, NSUInteger maximumLength) {
49
- if (![value isKindOfClass:NSString.class]) return @"";
50
- NSString *text = [(NSString *)value stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
51
- if (text.length == 0) return @"";
52
- NSMutableString *safe = [NSMutableString stringWithCapacity:MIN(text.length, maximumLength)];
53
- NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:
54
- @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._- "];
55
- for (NSUInteger index = 0; index < text.length && safe.length < maximumLength; index++) {
56
- unichar character = [text characterAtIndex:index];
57
- if ([allowed characterIsMember:character]) [safe appendFormat:@"%C", character];
58
- }
59
- return [safe stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
60
- }
61
-
62
- static NSString *ProviderFromEnvironment(void) {
63
- NSDictionary<NSString *, NSString *> *environment = NSProcessInfo.processInfo.environment;
64
- if ([environment[@"CC_PETS_CODEX_AGENT_HOOK"] boolValue]) return @"Codex";
65
- if ([environment[@"CC_PETS_CLAUDE_AGENT_HOOK"] boolValue]) return @"Claude";
66
- return @"Agent";
67
- }
68
-
69
- static NSString *NormalizedStateForEvent(NSString *event, BOOL failed) {
70
- if ([event isEqualToString:@"StopFailure"]) return @"failed";
71
- if (failed || [event isEqualToString:@"PostToolUseFailure"]) return @"tool_failed";
72
- if ([event isEqualToString:@"SessionStart"]) return @"starting";
73
- if ([event isEqualToString:@"UserPromptSubmit"]) return @"thinking";
74
- if ([event isEqualToString:@"PermissionRequest"]) return @"approval";
75
- if ([event isEqualToString:@"PreToolUse"]) return @"tool";
76
- if ([event isEqualToString:@"SubagentStart"] || [event isEqualToString:@"TaskCreated"]) return @"subagent";
77
- if ([event isEqualToString:@"PostToolUse"] || [event isEqualToString:@"SubagentStop"] ||
78
- [event isEqualToString:@"TaskCompleted"]) return @"thinking";
79
- if ([event isEqualToString:@"Stop"] || [event isEqualToString:@"SessionEnd"]) return @"completed";
80
- if ([event isEqualToString:@"Notification"]) return @"notification";
81
- return @"thinking";
82
- }
83
-
84
- static BOOL AppendAgentEventRecord(NSDictionary *record) {
85
- NSData *json = [NSJSONSerialization dataWithJSONObject:record options:0 error:nil];
86
- if (!json) return NO;
87
- int descriptor = open(AgentEventPath().fileSystemRepresentation,
88
- O_CREAT | O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR);
89
- if (descriptor < 0) return NO;
90
- BOOL succeeded = write(descriptor, json.bytes, json.length) == (ssize_t)json.length &&
91
- write(descriptor, "\n", 1) == 1;
92
- close(descriptor);
93
- return succeeded;
94
- }
95
-
96
- static NSArray<NSNumber *> *StableVersionComponents(NSString *version) {
97
- if (![version isKindOfClass:NSString.class]) return nil;
98
- NSArray<NSString *> *parts = [version componentsSeparatedByString:@"."];
99
- if (parts.count != 3) return nil;
100
- NSCharacterSet *nonDigits = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"].invertedSet;
101
- NSMutableArray<NSNumber *> *components = [NSMutableArray arrayWithCapacity:3];
102
- for (NSString *part in parts) {
103
- if (part.length == 0 || part.length > 9 ||
104
- (part.length > 1 && [part hasPrefix:@"0"]) ||
105
- [part rangeOfCharacterFromSet:nonDigits].location != NSNotFound) return nil;
106
- [components addObject:@(part.longLongValue)];
107
- }
108
- return components;
109
- }
110
-
111
- static NSComparisonResult CompareStableVersions(NSString *left, NSString *right, BOOL *valid) {
112
- NSArray<NSNumber *> *leftParts = StableVersionComponents(left);
113
- NSArray<NSNumber *> *rightParts = StableVersionComponents(right);
114
- if (!leftParts || !rightParts) {
115
- if (valid) *valid = NO;
116
- return NSOrderedSame;
117
- }
118
- if (valid) *valid = YES;
119
- for (NSUInteger index = 0; index < 3; index++) {
120
- long long leftValue = leftParts[index].longLongValue;
121
- long long rightValue = rightParts[index].longLongValue;
122
- if (leftValue < rightValue) return NSOrderedAscending;
123
- if (leftValue > rightValue) return NSOrderedDescending;
124
- }
125
- return NSOrderedSame;
126
- }
127
-
128
- static int RestartAfterPID(pid_t pid, NSString *appPath, BOOL managed) {
129
- for (NSUInteger attempt = 0; attempt < 300; attempt++) {
130
- if (pid <= 1 || (kill(pid, 0) != 0 && errno == ESRCH)) break;
131
- usleep(100000);
132
- }
133
- if (pid > 1 && (kill(pid, 0) == 0 || errno == EPERM)) {
134
- fprintf(stderr, "等待旧版 CC Pets 退出超时。\n");
135
- return EXIT_FAILURE;
136
- }
137
-
138
- NSString *openPath = NSProcessInfo.processInfo.environment[@"CC_PETS_OPEN_PATH"];
139
- if (openPath.length == 0) openPath = @"/usr/bin/open";
140
- NSTask *task = [NSTask new];
141
- task.executableURL = [NSURL fileURLWithPath:openPath];
142
- NSMutableArray<NSString *> *arguments = [NSMutableArray arrayWithObjects:@"-g", appPath, nil];
143
- if (managed) [arguments addObjectsFromArray:@[@"--args", @"--managed"]];
144
- task.arguments = arguments;
145
- NSError *error = nil;
146
- if (![task launchAndReturnError:&error]) {
147
- fprintf(stderr, "无法重新启动 CC Pets: %s\n", error.localizedDescription.UTF8String);
148
- return EXIT_FAILURE;
149
- }
150
- [task waitUntilExit];
151
- return task.terminationStatus == EXIT_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
152
- }
153
-
154
- static int RecordClaudeUsage(void) {
155
- NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
156
- NSDictionary *payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
157
- NSDictionary *limits = [payload[@"rate_limits"] isKindOfClass:NSDictionary.class] ? payload[@"rate_limits"] : nil;
158
- if (!limits) return EXIT_SUCCESS;
159
- NSData *json = [NSJSONSerialization dataWithJSONObject:limits options:0 error:nil];
160
- if (!json) return EXIT_SUCCESS;
161
- if (![json writeToFile:ClaudeUsagePath() options:NSDataWritingAtomic error:nil]) return EXIT_SUCCESS;
162
- chmod(ClaudeUsagePath().fileSystemRepresentation, S_IRUSR | S_IWUSR);
163
- return EXIT_SUCCESS;
164
- }
165
-
166
- static NSDictionary *LatestClaudeUsage(void) {
167
- NSData *data = [NSData dataWithContentsOfFile:ClaudeUsagePath()];
168
- NSDictionary *limits = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
169
- if (![limits isKindOfClass:NSDictionary.class]) return nil;
170
- id fiveHour = [limits[@"five_hour"] isKindOfClass:NSDictionary.class] ? limits[@"five_hour"] : NSNull.null;
171
- id week = [limits[@"seven_day"] isKindOfClass:NSDictionary.class] ? limits[@"seven_day"] : NSNull.null;
172
- return @{@"fiveHour": fiveHour, @"week": week};
173
- }
174
-
175
- static BOOL HookValueIndicatesFailure(id value) {
176
- if ([value isKindOfClass:NSDictionary.class]) {
177
- NSDictionary *dictionary = value;
178
- if ([dictionary[@"is_error"] boolValue]) return YES;
179
- if (dictionary[@"success"] && ![dictionary[@"success"] boolValue]) return YES;
180
- NSString *status = [dictionary[@"status"] isKindOfClass:NSString.class] ? [dictionary[@"status"] lowercaseString] : nil;
181
- if ([status isEqualToString:@"error"] || [status isEqualToString:@"failed"] || [status isEqualToString:@"failure"]) return YES;
182
- if (dictionary[@"error"] && dictionary[@"error"] != NSNull.null) return YES;
183
- for (id child in dictionary.allValues) if (HookValueIndicatesFailure(child)) return YES;
184
- } else if ([value isKindOfClass:NSArray.class]) {
185
- for (id child in value) if (HookValueIndicatesFailure(child)) return YES;
186
- }
187
- return NO;
188
- }
189
-
190
- static int RecordHookEvent(void) {
191
- NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
192
- NSDictionary *payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
193
- if (![payload isKindOfClass:NSDictionary.class]) return EXIT_SUCCESS;
194
- NSString *event = payload[@"hook_event_name"];
195
- if (![event isKindOfClass:NSString.class] || event.length == 0) return EXIT_SUCCESS;
196
- NSString *tool = [payload[@"tool_name"] isKindOfClass:NSString.class] ? payload[@"tool_name"] : @"";
197
- id toolResult = payload[@"tool_response"] ?: payload[@"tool_result"];
198
- BOOL failed = [event isEqualToString:@"PostToolUseFailure"] ||
199
- [event isEqualToString:@"StopFailure"] || HookValueIndicatesFailure(toolResult);
200
- NSDictionary *record = @{
201
- @"event": event,
202
- @"tool": tool,
203
- @"failed": @(failed),
204
- @"provider": ProviderFromEnvironment(),
205
- @"state": NormalizedStateForEvent(event, failed),
206
- @"timestamp": @([NSDate.date timeIntervalSince1970])
207
- };
208
- AppendAgentEventRecord(record);
209
- return EXIT_SUCCESS;
210
- }
211
-
212
- static int RecordProviderEvent(void) {
213
- NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
214
- NSDictionary *payload = input.length > 0
215
- ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
216
- if (![payload isKindOfClass:NSDictionary.class] ||
217
- ![payload[@"schemaVersion"] isKindOfClass:NSNumber.class] ||
218
- [payload[@"schemaVersion"] integerValue] != 1) {
219
- fprintf(stderr, "provider-event 需要 schemaVersion 为 1 的 JSON 对象。\n");
220
- return 2;
221
- }
222
- NSString *provider = SanitizedShortString(payload[@"provider"], 32);
223
- NSString *state = SanitizedShortString(payload[@"state"], 32).lowercaseString;
224
- NSString *tool = SanitizedShortString(payload[@"tool"], 64);
225
- NSSet<NSString *> *states = [NSSet setWithArray:@[
226
- @"starting", @"thinking", @"tool", @"approval", @"subagent",
227
- @"tool_completed", @"tool_failed", @"completed", @"failed", @"notification"
228
- ]];
229
- if (provider.length == 0 || ![states containsObject:state]) {
230
- fprintf(stderr, "provider-event 的 provider 或 state 无效。\n");
231
- return 2;
232
- }
233
- NSDictionary<NSString *, NSString *> *events = @{
234
- @"starting": @"SessionStart",
235
- @"thinking": @"UserPromptSubmit",
236
- @"tool": @"PreToolUse",
237
- @"approval": @"PermissionRequest",
238
- @"subagent": @"SubagentStart",
239
- @"tool_completed": @"PostToolUse",
240
- @"tool_failed": @"PostToolUseFailure",
241
- @"completed": @"Stop",
242
- @"failed": @"StopFailure",
243
- @"notification": @"Notification"
244
- };
245
- NSDictionary *record = @{
246
- @"event": events[state],
247
- @"tool": tool,
248
- @"failed": @([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]),
249
- @"provider": provider,
250
- @"state": state,
251
- @"timestamp": @([NSDate.date timeIntervalSince1970])
252
- };
253
- if (!AppendAgentEventRecord(record)) {
254
- fprintf(stderr, "无法写入 Provider 事件。\n");
255
- return EXIT_FAILURE;
256
- }
257
- return EXIT_SUCCESS;
258
- }
259
-
260
- static NSURL *NewestCodexSessionURL(NSURL *directory, BOOL recursive) {
261
- NSDirectoryEnumerationOptions options = NSDirectoryEnumerationSkipsHiddenFiles;
262
- if (!recursive) options |= NSDirectoryEnumerationSkipsSubdirectoryDescendants;
263
- NSArray *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey];
264
- NSDirectoryEnumerator *files = [NSFileManager.defaultManager enumeratorAtURL:directory
265
- includingPropertiesForKeys:keys options:options errorHandler:nil];
266
- NSURL *newest = nil;
267
- NSDate *newestDate = NSDate.distantPast;
268
- for (NSURL *url in files) {
269
- if (![url.pathExtension isEqualToString:@"jsonl"]) continue;
270
- NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
271
- if (![values[NSURLIsRegularFileKey] boolValue]) continue;
272
- NSDate *date = values[NSURLContentModificationDateKey] ?: NSDate.distantPast;
273
- if ([date compare:newestDate] == NSOrderedDescending) {
274
- newest = url;
275
- newestDate = date;
276
- }
277
- }
278
- return newest;
279
- }
280
-
281
- static NSDictionary *UsageFromCodexLine(NSData *lineData) {
282
- if (lineData.length == 0) return nil;
283
- NSString *line = [[NSString alloc] initWithData:lineData encoding:NSUTF8StringEncoding];
284
- if (!line || [line rangeOfString:@"\"type\":\"token_count\""].location == NSNotFound) return nil;
285
- NSDictionary *root = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
286
- NSDictionary *payload = root[@"payload"];
287
- if (![payload[@"type"] isEqualToString:@"token_count"]) return nil;
288
- NSDictionary *limits = payload[@"rate_limits"];
289
- id primaryValue = limits[@"primary"];
290
- id secondaryValue = limits[@"secondary"];
291
- NSDictionary *primary = [primaryValue isKindOfClass:NSDictionary.class] ? primaryValue : nil;
292
- NSDictionary *secondary = [secondaryValue isKindOfClass:NSDictionary.class] ? secondaryValue : nil;
293
- NSDictionary *fiveHour = nil;
294
- NSDictionary *week = nil;
295
- for (NSDictionary *quota in @[primary ?: @{}, secondary ?: @{}]) {
296
- NSInteger minutes = [quota[@"window_minutes"] integerValue];
297
- if (minutes == 300) fiveHour = quota;
298
- if (minutes == 10080) week = quota;
299
- }
300
- return @{
301
- @"fiveHour": fiveHour ?: NSNull.null,
302
- @"week": week ?: NSNull.null
303
- };
304
- }
305
-
306
- static NSDictionary *LatestUsageInData(NSData *data) {
307
- NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
308
- if (!text) return nil;
309
- NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
310
- for (NSString *line in lines.reverseObjectEnumerator) {
311
- NSDictionary *usage = UsageFromCodexLine([line dataUsingEncoding:NSUTF8StringEncoding]);
312
- if (usage) return usage;
313
- }
314
- return nil;
315
- }
316
-
317
- static NSDictionary *LatestUsage(void) {
318
- NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
319
- if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
320
- NSURL *sessions = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
321
- NSURL *newest = NewestCodexSessionURL(sessions, YES);
322
- if (!newest) return nil;
323
-
324
- NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:newest error:nil];
325
- if (!handle) return nil;
326
- unsigned long long size = [handle seekToEndOfFile];
327
- [handle seekToFileOffset:size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0];
328
- NSData *tail = [handle readDataToEndOfFile];
329
- [handle closeFile];
330
- return LatestUsageInData(tail);
331
- }
332
-
333
- static NSNumber *RemainingValue(NSDictionary *usage, NSString *quotaKey, NSString *usedKey) {
334
- NSDictionary *quota = [usage[quotaKey] isKindOfClass:NSDictionary.class] ? usage[quotaKey] : nil;
335
- NSNumber *used = [quota[usedKey] isKindOfClass:NSNumber.class] ? quota[usedKey] : nil;
336
- if (!used) return nil;
337
- return @(fmax(0, fmin(100, 100.0 - used.doubleValue)));
338
- }
339
-
340
- static NSDictionary *QuotaHistoryDocument(void) {
341
- NSData *data = [NSData dataWithContentsOfFile:QuotaHistoryPath()];
342
- NSDictionary *document = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
343
- if (![document isKindOfClass:NSDictionary.class] ||
344
- [document[@"schemaVersion"] integerValue] != 1 ||
345
- ![document[@"samples"] isKindOfClass:NSArray.class]) {
346
- return @{@"schemaVersion": @1, @"samples": @[]};
347
- }
348
- return document;
349
- }
350
-
351
- static NSDictionary *HistoryProviderSample(NSDictionary *usage, NSString *usedKey) {
352
- NSNumber *fiveHour = RemainingValue(usage, @"fiveHour", usedKey);
353
- NSNumber *week = RemainingValue(usage, @"week", usedKey);
354
- NSMutableDictionary *sample = [NSMutableDictionary dictionary];
355
- if (fiveHour) sample[@"fiveHourRemaining"] = fiveHour;
356
- if (week) sample[@"weekRemaining"] = week;
357
- return sample;
358
- }
359
-
360
- static void RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
361
- if (![NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]) return;
362
- NSDictionary *codex = HistoryProviderSample(codexUsage, @"used_percent");
363
- NSDictionary *claude = HistoryProviderSample(claudeUsage, @"used_percentage");
364
- if (codex.count == 0 && claude.count == 0) return;
365
-
366
- NSTimeInterval now = NSDate.date.timeIntervalSince1970;
367
- NSTimeInterval cutoff = now - 7 * 24 * 60 * 60;
368
- NSArray *existing = QuotaHistoryDocument()[@"samples"];
369
- NSMutableArray *samples = [NSMutableArray arrayWithCapacity:existing.count + 1];
370
- for (NSDictionary *sample in existing) {
371
- if (![sample isKindOfClass:NSDictionary.class] || [sample[@"timestamp"] doubleValue] < cutoff) continue;
372
- [samples addObject:sample];
373
- }
374
- NSDictionary *last = samples.lastObject;
375
- if (last && now - [last[@"timestamp"] doubleValue] < 15 * 60) return;
376
-
377
- NSMutableDictionary *sample = [@{@"timestamp": @(now)} mutableCopy];
378
- if (codex.count > 0) sample[@"codex"] = codex;
379
- if (claude.count > 0) sample[@"claude"] = claude;
380
- [samples addObject:sample];
381
- if (samples.count > 672) {
382
- [samples removeObjectsInRange:NSMakeRange(0, samples.count - 672)];
383
- }
384
-
385
- NSString *directory = QuotaHistoryPath().stringByDeletingLastPathComponent;
386
- [NSFileManager.defaultManager createDirectoryAtPath:directory
387
- withIntermediateDirectories:YES attributes:nil error:nil];
388
- NSDictionary *document = @{@"schemaVersion": @1, @"samples": samples};
389
- NSData *json = [NSJSONSerialization dataWithJSONObject:document
390
- options:NSJSONWritingPrettyPrinted error:nil];
391
- if ([json writeToFile:QuotaHistoryPath() options:NSDataWritingAtomic error:nil]) {
392
- chmod(QuotaHistoryPath().fileSystemRepresentation, S_IRUSR | S_IWUSR);
393
- }
394
- }
395
-
396
- static NSArray<NSNumber *> *QuotaHistorySeries(NSString *provider) {
397
- NSMutableArray<NSNumber *> *series = [NSMutableArray array];
398
- for (NSDictionary *sample in QuotaHistoryDocument()[@"samples"]) {
399
- NSDictionary *providerSample = [sample[provider] isKindOfClass:NSDictionary.class]
400
- ? sample[provider] : nil;
401
- NSNumber *remaining = [providerSample[@"weekRemaining"] isKindOfClass:NSNumber.class]
402
- ? providerSample[@"weekRemaining"] : nil;
403
- if (remaining) [series addObject:remaining];
404
- }
405
- return series;
406
- }
407
-
408
- @interface CodexUsageReader : NSObject
409
- @property NSURL *sessionsURL;
410
- @property NSURL *sessionURL;
411
- @property NSDictionary *usage;
412
- @property unsigned long long offset;
413
- @property NSMutableData *partialLine;
414
- @property NSTimeInterval lastFullDiscovery;
415
- - (NSDictionary *)refresh;
416
- @end
417
-
418
- @implementation CodexUsageReader
419
- - (instancetype)init {
420
- if ((self = [super init])) {
421
- NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
422
- if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
423
- _sessionsURL = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
424
- _partialLine = [NSMutableData data];
425
- }
426
- return self;
427
- }
428
- - (void)selectSessionURL:(NSURL *)url {
429
- self.sessionURL = url;
430
- self.offset = 0;
431
- [self.partialLine setLength:0];
432
- if (!url) {
433
- self.usage = nil;
434
- return;
435
- }
436
- NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
437
- if (!handle) return;
438
- unsigned long long size = [handle seekToEndOfFile];
439
- unsigned long long start = size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0;
440
- [handle seekToFileOffset:start];
441
- NSData *tail = [handle readDataToEndOfFile];
442
- [handle closeFile];
443
- self.offset = start + tail.length;
444
- self.usage = LatestUsageInData(tail);
445
-
446
- const uint8_t *bytes = tail.bytes;
447
- NSUInteger lastNewline = NSNotFound;
448
- for (NSUInteger index = tail.length; index > 0; index--) {
449
- if (bytes[index - 1] == '\n') {
450
- lastNewline = index - 1;
451
- break;
452
- }
453
- }
454
- if (lastNewline == NSNotFound) [self.partialLine appendData:tail];
455
- else if (lastNewline + 1 < tail.length) {
456
- [self.partialLine appendData:[tail subdataWithRange:NSMakeRange(lastNewline + 1, tail.length - lastNewline - 1)]];
457
- }
458
- }
459
- - (void)consumeIncrementalData:(NSData *)data {
460
- if (data.length == 0) return;
461
- [self.partialLine appendData:data];
462
- const uint8_t *bytes = self.partialLine.bytes;
463
- NSUInteger lineStart = 0;
464
- for (NSUInteger index = 0; index < self.partialLine.length; index++) {
465
- if (bytes[index] != '\n') continue;
466
- NSData *line = [self.partialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
467
- NSDictionary *newUsage = UsageFromCodexLine(line);
468
- if (newUsage) self.usage = newUsage;
469
- lineStart = index + 1;
470
- }
471
- if (lineStart > 0) {
472
- NSData *remainder = [self.partialLine subdataWithRange:
473
- NSMakeRange(lineStart, self.partialLine.length - lineStart)];
474
- self.partialLine = [remainder mutableCopy];
475
- }
476
- if (self.partialLine.length > 2 * 1024 * 1024) [self.partialLine setLength:0];
477
- }
478
- - (NSDictionary *)refresh {
479
- NSTimeInterval now = NSDate.date.timeIntervalSince1970;
480
- BOOL needsFullDiscovery = !self.sessionURL || now - self.lastFullDiscovery >= 60;
481
- NSURL *candidate = nil;
482
- if (needsFullDiscovery) {
483
- candidate = NewestCodexSessionURL(self.sessionsURL, YES);
484
- self.lastFullDiscovery = now;
485
- } else {
486
- candidate = NewestCodexSessionURL(self.sessionURL.URLByDeletingLastPathComponent, NO);
487
- }
488
- if (candidate && ![candidate.path isEqualToString:self.sessionURL.path]) [self selectSessionURL:candidate];
489
- if (!self.sessionURL) return self.usage;
490
-
491
- NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:self.sessionURL error:nil];
492
- if (!handle) {
493
- self.lastFullDiscovery = 0;
494
- return self.usage;
495
- }
496
- unsigned long long size = [handle seekToEndOfFile];
497
- if (size < self.offset) {
498
- [handle closeFile];
499
- [self selectSessionURL:self.sessionURL];
500
- return self.usage;
501
- }
502
- if (size > self.offset) {
503
- unsigned long long start = self.offset;
504
- [handle seekToFileOffset:start];
505
- NSData *newData = [handle readDataToEndOfFile];
506
- self.offset = start + newData.length;
507
- [self consumeIncrementalData:newData];
508
- }
509
- [handle closeFile];
510
- return self.usage;
511
- }
512
- @end
513
-
514
- @interface MenuToggleSwitch : NSButton
515
- @end
516
-
517
- @implementation MenuToggleSwitch
518
- - (instancetype)initWithFrame:(NSRect)frameRect {
519
- if ((self = [super initWithFrame:frameRect])) {
520
- self.bordered = NO;
521
- self.title = @"";
522
- self.buttonType = NSButtonTypeToggle;
523
- self.focusRingType = NSFocusRingTypeNone;
524
- [self setAccessibilityRole:NSAccessibilityCheckBoxRole];
525
- }
526
- return self;
527
- }
528
- - (void)setState:(NSControlStateValue)value {
529
- [super setState:value];
530
- self.needsDisplay = YES;
531
- }
532
- - (void)drawRect:(NSRect)dirtyRect {
533
- NSRect track = NSInsetRect(self.bounds, 1, 2);
534
- BOOL enabled = self.state == NSControlStateValueOn;
535
- NSColor *trackColor = enabled
536
- ? [NSColor.controlAccentColor colorWithAlphaComponent:self.highlighted ? 0.72 : 0.96]
537
- : [NSColor colorWithWhite:self.highlighted ? 0.38 : 0.46 alpha:0.82];
538
- [trackColor setFill];
539
- NSBezierPath *trackPath = [NSBezierPath bezierPathWithRoundedRect:track
540
- xRadius:NSHeight(track) / 2.0 yRadius:NSHeight(track) / 2.0];
541
- [trackPath fill];
542
- [[NSColor colorWithWhite:0 alpha:enabled ? 0.08 : 0.16] setStroke];
543
- trackPath.lineWidth = 0.8;
544
- [trackPath stroke];
545
-
546
- CGFloat diameter = NSHeight(track) - 4;
547
- CGFloat knobX = enabled
548
- ? NSMaxX(track) - diameter - 2
549
- : NSMinX(track) + 2;
550
- NSRect knob = NSMakeRect(knobX, NSMidY(track) - diameter / 2.0, diameter, diameter);
551
- [NSGraphicsContext saveGraphicsState];
552
- NSShadow *shadow = [NSShadow new];
553
- shadow.shadowColor = [NSColor colorWithWhite:0 alpha:0.24];
554
- shadow.shadowBlurRadius = 1.5;
555
- shadow.shadowOffset = NSMakeSize(0, -0.5);
556
- [shadow set];
557
- [NSColor.whiteColor setFill];
558
- [[NSBezierPath bezierPathWithOvalInRect:knob] fill];
559
- [NSGraphicsContext restoreGraphicsState];
560
- }
561
- @end
562
-
563
- @interface PetView : NSView <NSMenuDelegate>
564
- @property NSImage *sheet;
565
- @property NSInteger spriteRowCount;
566
- @property NSInteger lookDirection;
567
- @property NSInteger frameIndex;
568
- @property NSInteger rowIndex;
569
- @property NSArray<NSNumber *> *frames;
570
- @property NSUInteger sequenceIndex;
571
- @property BOOL oneShot;
572
- @property BOOL draggingPet;
573
- @property BOOL agentActive;
574
- @property NSPoint dragStartMouse;
575
- @property NSPoint dragStartWindowOrigin;
576
- @property NSString *currentPetID;
577
- @property id globalMouseMonitor;
578
- @property id localMouseMonitor;
579
- @property(copy) void (^pocketHoverChanged)(BOOL hovering);
580
- @property(copy) void (^positionChanged)(void);
581
- @property(copy) void (^dragStateChanged)(BOOL dragging);
582
- @property(copy) NSArray<NSDictionary *> *(^petOptionsRequested)(void);
583
- @property(copy) void (^switchPetRequested)(NSString *petID);
584
- @property NSMutableDictionary<NSString *, NSImage *> *petMenuPreviewCache;
585
- @property NSPanel *petMenuPreviewPanel;
586
- @property NSImageView *petMenuPreviewImageView;
587
- @end
588
-
589
- @implementation PetView
590
- - (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount {
591
- if ((self = [super initWithFrame:frame])) {
592
- _sheet = sheet;
593
- _spriteRowCount = rowCount;
594
- _lookDirection = -1;
595
- _frames = @[@0, @1, @2, @3, @4, @5];
596
- _petMenuPreviewCache = [NSMutableDictionary dictionary];
597
- [NSTimer scheduledTimerWithTimeInterval:0.22 target:self
598
- selector:@selector(nextFrame:) userInfo:nil repeats:YES];
599
- NSTrackingArea *tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect
600
- options:NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
601
- NSTrackingActiveAlways | NSTrackingInVisibleRect
602
- owner:self userInfo:nil];
603
- [self addTrackingArea:tracking];
604
- [self updateLookTracking];
605
- }
606
- return self;
607
- }
608
- - (void)dealloc {
609
- [self stopLookTracking];
610
- }
611
- - (void)startLookTracking {
612
- if (self.spriteRowCount != 11 || self.globalMouseMonitor || self.localMouseMonitor) return;
613
- __weak PetView *weakSelf = self;
614
- self.globalMouseMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskMouseMoved
615
- handler:^(NSEvent *event) {
616
- [weakSelf updateLookForScreenPoint:NSEvent.mouseLocation];
617
- }];
618
- self.localMouseMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskMouseMoved
619
- handler:^NSEvent *(NSEvent *event) {
620
- [weakSelf updateLookForScreenPoint:NSEvent.mouseLocation];
621
- return event;
622
- }];
623
- }
624
- - (void)stopLookTracking {
625
- if (self.globalMouseMonitor) {
626
- [NSEvent removeMonitor:self.globalMouseMonitor];
627
- self.globalMouseMonitor = nil;
628
- }
629
- if (self.localMouseMonitor) {
630
- [NSEvent removeMonitor:self.localMouseMonitor];
631
- self.localMouseMonitor = nil;
632
- }
633
- self.lookDirection = -1;
634
- }
635
- - (void)updateLookTracking {
636
- if (self.spriteRowCount == 11) [self startLookTracking];
637
- else [self stopLookTracking];
638
- }
639
- - (void)updateLookForScreenPoint:(NSPoint)screenPoint {
640
- if (self.spriteRowCount != 11 || self.draggingPet || self.oneShot || self.agentActive || !self.window) return;
641
-
642
- NSPoint windowPoint = [self.window convertPointFromScreen:screenPoint];
643
- NSPoint localPoint = [self convertPoint:windowPoint fromView:nil];
644
- if (NSPointInRect(localPoint, self.bounds)) return;
645
-
646
- NSPoint center = [self convertPoint:NSMakePoint(NSMidX(self.bounds), NSMidY(self.bounds)) toView:nil];
647
- center = [self.window convertPointToScreen:center];
648
- CGFloat dx = screenPoint.x - center.x;
649
- CGFloat dy = screenPoint.y - center.y;
650
- if (hypot(dx, dy) <= 1.0) return;
651
-
652
- CGFloat degrees = fmod(atan2(dx, dy) * 180.0 / M_PI + 360.0, 360.0);
653
- NSInteger direction = ((NSInteger)llround(degrees / 22.5)) % 16;
654
- if (direction == self.lookDirection) return;
655
-
656
- self.lookDirection = direction;
657
- self.rowIndex = 9 + direction / 8;
658
- self.frameIndex = direction % 8;
659
- self.needsDisplay = YES;
660
- }
661
- - (NSArray<NSNumber *> *)framesFromZeroThrough:(NSInteger)last {
662
- NSMutableArray<NSNumber *> *result = [NSMutableArray arrayWithCapacity:last + 1];
663
- for (NSInteger index = 0; index <= last; index++) [result addObject:@(index)];
664
- return result;
665
- }
666
- - (void)playRow:(NSInteger)row throughFrame:(NSInteger)last oneShot:(BOOL)oneShot {
667
- if (!oneShot && !self.oneShot && self.rowIndex == row) return;
668
- self.lookDirection = -1;
669
- self.rowIndex = row;
670
- self.frames = [self framesFromZeroThrough:last];
671
- self.sequenceIndex = 0;
672
- self.frameIndex = 0;
673
- self.oneShot = oneShot;
674
- self.needsDisplay = YES;
675
- }
676
- - (BOOL)isPocketPoint:(NSPoint)point {
677
- CGFloat centerX = NSMidX(self.bounds);
678
- CGFloat centerY = NSHeight(self.bounds) * 0.32;
679
- CGFloat dx = (point.x - centerX) / (NSWidth(self.bounds) * 0.22);
680
- CGFloat dy = (point.y - centerY) / (NSHeight(self.bounds) * 0.16);
681
- return dx * dx + dy * dy <= 1.0;
682
- }
683
- - (void)updateHoverForPoint:(NSPoint)point {
684
- BOOL overPocket = [self isPocketPoint:point];
685
- if (self.pocketHoverChanged) self.pocketHoverChanged(overPocket);
686
- if (overPocket) {
687
- [NSCursor.pointingHandCursor set];
688
- [self playRow:5 throughFrame:7 oneShot:NO];
689
- } else if (point.y >= NSHeight(self.bounds) * 0.58) {
690
- [NSCursor.pointingHandCursor set];
691
- [self playRow:4 throughFrame:4 oneShot:NO];
692
- } else if (point.y <= NSHeight(self.bounds) * 0.20) {
693
- [NSCursor.pointingHandCursor set];
694
- [self playRow:6 throughFrame:5 oneShot:NO];
695
- } else if (point.x >= NSWidth(self.bounds) * 0.66) {
696
- [NSCursor.arrowCursor set];
697
- [self playRow:3 throughFrame:3 oneShot:NO];
698
- } else if (point.x <= NSWidth(self.bounds) * 0.34) {
699
- [NSCursor.arrowCursor set];
700
- [self playRow:8 throughFrame:5 oneShot:NO];
701
- } else {
702
- [NSCursor.arrowCursor set];
703
- [self playRow:0 throughFrame:5 oneShot:NO];
704
- }
705
- }
706
- - (void)mouseMoved:(NSEvent *)event {
707
- if (self.draggingPet || self.oneShot) return;
708
- NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
709
- if (self.agentActive) {
710
- BOOL overPocket = [self isPocketPoint:point];
711
- if (self.pocketHoverChanged) self.pocketHoverChanged(overPocket);
712
- if (overPocket) [NSCursor.pointingHandCursor set];
713
- else [NSCursor.arrowCursor set];
714
- return;
715
- }
716
- [self updateHoverForPoint:point];
717
- }
718
- - (void)mouseExited:(NSEvent *)event {
719
- if (self.draggingPet) return;
720
- if (self.pocketHoverChanged) self.pocketHoverChanged(NO);
721
- [NSCursor.arrowCursor set];
722
- if (self.agentActive) return;
723
- [self playRow:0 throughFrame:5 oneShot:NO];
724
- }
725
- - (void)nextFrame:(NSTimer *)timer {
726
- if (self.lookDirection >= 0) return;
727
- self.sequenceIndex += 1;
728
- if (self.sequenceIndex >= self.frames.count) {
729
- if (self.oneShot) {
730
- self.rowIndex = 0;
731
- self.frames = [self framesFromZeroThrough:5];
732
- self.oneShot = NO;
733
- self.agentActive = NO;
734
- }
735
- self.sequenceIndex = 0;
736
- }
737
- self.frameIndex = self.frames[self.sequenceIndex].integerValue;
738
- self.needsDisplay = YES;
739
- }
740
- - (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed {
741
- if ([event isEqualToString:@"SessionStart"]) {
742
- self.agentActive = YES;
743
- [self playRow:4 throughFrame:4 oneShot:YES];
744
- } else if ([event isEqualToString:@"UserPromptSubmit"]) {
745
- self.agentActive = YES;
746
- [self playRow:5 throughFrame:7 oneShot:NO];
747
- } else if ([event isEqualToString:@"PermissionRequest"]) {
748
- self.agentActive = YES;
749
- [self playRow:4 throughFrame:4 oneShot:NO];
750
- } else if ([event isEqualToString:@"PreToolUse"]) {
751
- self.agentActive = YES;
752
- NSString *lower = tool.lowercaseString;
753
- if ([lower containsString:@"bash"] || [lower containsString:@"exec"]) {
754
- [self playRow:1 throughFrame:7 oneShot:NO];
755
- } else if ([lower containsString:@"patch"] || [lower containsString:@"edit"] || [lower containsString:@"write"]) {
756
- [self playRow:7 throughFrame:5 oneShot:NO];
757
- } else if ([lower containsString:@"read"] || [lower containsString:@"search"] || [lower containsString:@"find"] ||
758
- [lower containsString:@"grep"] || [lower containsString:@"glob"] || [lower containsString:@"web"] ||
759
- [lower hasPrefix:@"mcp__"]) {
760
- [self playRow:3 throughFrame:3 oneShot:NO];
761
- } else if ([lower isEqualToString:@"task"] || [lower containsString:@"agent"]) {
762
- [self playRow:6 throughFrame:5 oneShot:NO];
763
- } else {
764
- [self playRow:8 throughFrame:5 oneShot:NO];
765
- }
766
- } else if ([event isEqualToString:@"SubagentStart"] || [event isEqualToString:@"TaskCreated"]) {
767
- self.agentActive = YES;
768
- [self playRow:6 throughFrame:5 oneShot:NO];
769
- } else if ([event isEqualToString:@"PostToolUse"] || [event isEqualToString:@"PostToolUseFailure"]) {
770
- self.agentActive = YES;
771
- [self playRow:failed ? 5 : 7 throughFrame:failed ? 7 : 5 oneShot:YES];
772
- } else if ([event isEqualToString:@"StopFailure"]) {
773
- self.agentActive = YES;
774
- [self playRow:5 throughFrame:7 oneShot:YES];
775
- } else if ([event isEqualToString:@"Notification"]) {
776
- self.agentActive = YES;
777
- [self playRow:4 throughFrame:4 oneShot:YES];
778
- } else if ([event isEqualToString:@"Stop"] || [event isEqualToString:@"SubagentStop"] ||
779
- [event isEqualToString:@"TaskCompleted"] || [event isEqualToString:@"SessionEnd"]) {
780
- self.agentActive = YES;
781
- [self playRow:3 throughFrame:3 oneShot:YES];
782
- }
783
- }
784
- - (void)mouseDown:(NSEvent *)event {
785
- self.agentActive = NO;
786
- self.dragStartMouse = NSEvent.mouseLocation;
787
- self.dragStartWindowOrigin = self.window.frame.origin;
788
- self.draggingPet = NO;
789
- }
790
- - (void)mouseDragged:(NSEvent *)event {
791
- NSPoint current = NSEvent.mouseLocation;
792
- CGFloat horizontal = current.x - self.dragStartMouse.x;
793
- CGFloat vertical = current.y - self.dragStartMouse.y;
794
- if (!self.draggingPet && hypot(horizontal, vertical) >= 3) {
795
- self.draggingPet = YES;
796
- if (self.dragStateChanged) self.dragStateChanged(YES);
797
- }
798
- if (self.draggingPet) {
799
- if (self.pocketHoverChanged) self.pocketHoverChanged(NO);
800
- [self playRow:horizontal >= 0 ? 1 : 2 throughFrame:7 oneShot:NO];
801
- }
802
- NSPoint origin = NSMakePoint(
803
- self.dragStartWindowOrigin.x + horizontal,
804
- self.dragStartWindowOrigin.y + vertical
805
- );
806
- [self.window setFrameOrigin:origin];
807
- if (self.positionChanged) self.positionChanged();
808
- }
809
- - (void)mouseUp:(NSEvent *)event {
810
- if (self.draggingPet) {
811
- self.draggingPet = NO;
812
- if (self.dragStateChanged) self.dragStateChanged(NO);
813
- [self playRow:0 throughFrame:5 oneShot:NO];
814
- } else {
815
- // 第 8 行未标注的动作作为点击反馈,完整利用剩余素材。
816
- [self playRow:7 throughFrame:5 oneShot:YES];
817
- }
818
- }
819
- - (void)drawRect:(NSRect)dirtyRect {
820
- CGFloat cellWidth = self.sheet.size.width / 8.0;
821
- CGFloat cellHeight = self.sheet.size.height / self.spriteRowCount;
822
- NSRect source = NSMakeRect(self.frameIndex * cellWidth,
823
- self.sheet.size.height - (self.rowIndex + 1) * cellHeight, cellWidth, cellHeight);
824
- [self.sheet drawInRect:NSInsetRect(self.bounds, 2, 0) fromRect:source
825
- operation:NSCompositingOperationSourceOver fraction:1.0
826
- respectFlipped:NO hints:@{NSImageHintInterpolation: @(NSImageInterpolationNone)}];
827
- }
828
- - (void)applySheet:(NSImage *)sheet petID:(NSString *)petID rowCount:(NSInteger)rowCount {
829
- self.sheet = sheet;
830
- self.spriteRowCount = rowCount;
831
- self.lookDirection = -1;
832
- self.currentPetID = petID;
833
- self.rowIndex = 0;
834
- self.frameIndex = 0;
835
- self.sequenceIndex = 0;
836
- self.frames = [self framesFromZeroThrough:5];
837
- self.oneShot = NO;
838
- [self updateLookTracking];
839
- self.needsDisplay = YES;
840
- }
841
- - (void)selectPet:(NSMenuItem *)sender {
842
- NSDictionary *pet = [sender.representedObject isKindOfClass:NSDictionary.class]
843
- ? sender.representedObject : nil;
844
- NSString *petID = pet[@"id"];
845
- if (petID.length > 0 && self.switchPetRequested) self.switchPetRequested(petID);
846
- }
847
- - (NSImage *)menuPreviewForPet:(NSDictionary *)pet {
848
- NSString *path = [pet[@"path"] isKindOfClass:NSString.class] ? pet[@"path"] : nil;
849
- NSInteger rowCount = [pet[@"spriteRowCount"] integerValue];
850
- if (path.length == 0 || rowCount <= 0) return nil;
851
-
852
- NSString *cacheKey = [NSString stringWithFormat:@"%@:%ld", path, (long)rowCount];
853
- NSImage *cached = self.petMenuPreviewCache[cacheKey];
854
- if (cached) return cached;
855
-
856
- NSImage *sheet = [[NSImage alloc] initWithContentsOfFile:path];
857
- if (!sheet || sheet.size.width <= 0 || sheet.size.height <= 0) return nil;
858
-
859
- CGFloat cellWidth = sheet.size.width / 8.0;
860
- CGFloat cellHeight = sheet.size.height / rowCount;
861
- NSRect firstFrame = NSMakeRect(0, sheet.size.height - cellHeight, cellWidth, cellHeight);
862
- CGFloat previewHeight = 76.0;
863
- CGFloat previewWidth = round(previewHeight * cellWidth / cellHeight);
864
- NSImage *preview = [[NSImage alloc] initWithSize:NSMakeSize(previewWidth, previewHeight)];
865
- [preview lockFocus];
866
- [sheet drawInRect:NSMakeRect(0, 0, previewWidth, previewHeight) fromRect:firstFrame
867
- operation:NSCompositingOperationSourceOver fraction:1.0
868
- respectFlipped:NO hints:@{NSImageHintInterpolation: @(NSImageInterpolationNone)}];
869
- [preview unlockFocus];
870
- self.petMenuPreviewCache[cacheKey] = preview;
871
- return preview;
872
- }
873
- - (void)preparePetMenuPreviewPanel {
874
- if (self.petMenuPreviewPanel) return;
875
-
876
- NSRect panelFrame = NSMakeRect(0, 0, 92, 100);
877
- self.petMenuPreviewPanel = [[NSPanel alloc] initWithContentRect:panelFrame
878
- styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
879
- backing:NSBackingStoreBuffered defer:NO];
880
- self.petMenuPreviewPanel.opaque = NO;
881
- self.petMenuPreviewPanel.backgroundColor = NSColor.clearColor;
882
- self.petMenuPreviewPanel.hasShadow = YES;
883
- self.petMenuPreviewPanel.ignoresMouseEvents = YES;
884
- self.petMenuPreviewPanel.level = NSPopUpMenuWindowLevel + 1;
885
- self.petMenuPreviewPanel.collectionBehavior = NSWindowCollectionBehaviorTransient |
886
- NSWindowCollectionBehaviorMoveToActiveSpace;
887
-
888
- NSVisualEffectView *background = [[NSVisualEffectView alloc] initWithFrame:panelFrame];
889
- background.material = NSVisualEffectMaterialMenu;
890
- background.blendingMode = NSVisualEffectBlendingModeBehindWindow;
891
- background.state = NSVisualEffectStateActive;
892
- background.wantsLayer = YES;
893
- background.layer.cornerRadius = 10.0;
894
- background.layer.masksToBounds = YES;
895
-
896
- self.petMenuPreviewImageView = [[NSImageView alloc] initWithFrame:NSInsetRect(panelFrame, 8, 8)];
897
- self.petMenuPreviewImageView.imageScaling = NSImageScaleProportionallyUpOrDown;
898
- self.petMenuPreviewImageView.animates = NO;
899
- [background addSubview:self.petMenuPreviewImageView];
900
- self.petMenuPreviewPanel.contentView = background;
901
- }
902
- - (void)showMenuPreviewForPet:(NSDictionary *)pet item:(NSMenuItem *)item menu:(NSMenu *)menu {
903
- NSImage *preview = [self menuPreviewForPet:pet];
904
- if (!preview) {
905
- [self.petMenuPreviewPanel orderOut:nil];
906
- return;
907
- }
908
- [self preparePetMenuPreviewPanel];
909
- self.petMenuPreviewImageView.image = preview;
910
-
911
- NSRect itemFrame = item.accessibilityFrame;
912
- NSRect menuFrame = menu.accessibilityFrame;
913
- if (NSIsEmptyRect(menuFrame)) {
914
- NSPoint mouse = NSEvent.mouseLocation;
915
- menuFrame = NSMakeRect(mouse.x - menu.size.width / 2.0,
916
- mouse.y - menu.size.height / 2.0, menu.size.width, menu.size.height);
917
- }
918
- if (NSIsEmptyRect(itemFrame)) {
919
- NSPoint mouse = NSEvent.mouseLocation;
920
- itemFrame = NSMakeRect(menuFrame.origin.x, mouse.y - 11.0, menuFrame.size.width, 22.0);
921
- }
922
-
923
- // 子菜单可能根据屏幕空间展开到主菜单左侧。预览应放在整组菜单外侧,
924
- // 不能只按当前子菜单定位,否则会覆盖它右边的主菜单。
925
- NSRect menuGroupFrame = menuFrame;
926
- for (NSMenu *ancestor = menu.supermenu; ancestor; ancestor = ancestor.supermenu) {
927
- NSRect ancestorFrame = ancestor.accessibilityFrame;
928
- if (!NSIsEmptyRect(ancestorFrame)) menuGroupFrame = NSUnionRect(menuGroupFrame, ancestorFrame);
929
- }
930
-
931
- NSPoint menuCenter = NSMakePoint(NSMidX(menuGroupFrame), NSMidY(menuGroupFrame));
932
- NSScreen *targetScreen = NSScreen.mainScreen ?: NSScreen.screens.firstObject;
933
- for (NSScreen *screen in NSScreen.screens) {
934
- if (NSPointInRect(menuCenter, screen.frame)) {
935
- targetScreen = screen;
936
- break;
937
- }
938
- }
939
- NSRect screenFrame = targetScreen.visibleFrame;
940
- NSSize previewSize = self.petMenuPreviewPanel.frame.size;
941
- CGFloat x = NSMaxX(menuGroupFrame) + 8.0;
942
- if (x + previewSize.width > NSMaxX(screenFrame)) {
943
- x = NSMinX(menuGroupFrame) - previewSize.width - 8.0;
944
- }
945
- CGFloat y = NSMidY(itemFrame) - previewSize.height / 2.0;
946
- y = MIN(MAX(y, NSMinY(screenFrame)), NSMaxY(screenFrame) - previewSize.height);
947
- [self.petMenuPreviewPanel setFrameOrigin:NSMakePoint(x, y)];
948
- [self.petMenuPreviewPanel orderFront:nil];
949
- }
950
- - (void)menu:(NSMenu *)menu willHighlightItem:(NSMenuItem *)item {
951
- NSDictionary *pet = [item.representedObject isKindOfClass:NSDictionary.class]
952
- ? item.representedObject : nil;
953
- if (pet) [self showMenuPreviewForPet:pet item:item menu:menu];
954
- else [self.petMenuPreviewPanel orderOut:nil];
955
- }
956
- - (void)menuDidClose:(NSMenu *)menu {
957
- [self.petMenuPreviewPanel orderOut:nil];
958
- }
959
- - (NSMenuItem *)addPersistentSwitchToMenu:(NSMenu *)menu
960
- title:(NSString *)title
961
- checked:(BOOL)checked
962
- action:(SEL)action
963
- tag:(NSInteger)tag {
964
- NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
965
- NSView *row = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 194, 28)];
966
- NSTextField *label = [NSTextField labelWithString:title];
967
- label.frame = NSMakeRect(12, 5, 132, 18);
968
- label.font = [NSFont menuFontOfSize:13];
969
- label.textColor = NSColor.labelColor;
970
- label.lineBreakMode = NSLineBreakByTruncatingTail;
971
- [row addSubview:label];
972
- MenuToggleSwitch *toggle = [[MenuToggleSwitch alloc] initWithFrame:NSMakeRect(150, 3, 36, 22)];
973
- toggle.target = NSApp.delegate;
974
- toggle.action = action;
975
- toggle.state = checked ? NSControlStateValueOn : NSControlStateValueOff;
976
- toggle.tag = tag;
977
- [toggle setAccessibilityLabel:title];
978
- [row addSubview:toggle];
979
- item.view = row;
980
- [menu addItem:item];
981
- return item;
982
- }
983
- - (void)rightMouseDown:(NSEvent *)event {
984
- NSArray<NSDictionary *> *availablePets = self.petOptionsRequested ? self.petOptionsRequested() : @[];
985
- NSMenu *menu = [NSMenu new];
986
- NSMenuItem *switchItem = [menu addItemWithTitle:@"切换桌宠" action:nil keyEquivalent:@""];
987
- NSMenu *switchMenu = [NSMenu new];
988
- switchMenu.delegate = self;
989
- for (NSDictionary *pet in availablePets) {
990
- NSString *petID = pet[@"id"];
991
- NSMenuItem *item = [switchMenu addItemWithTitle:pet[@"name"]
992
- action:@selector(selectPet:) keyEquivalent:@""];
993
- item.target = self;
994
- item.representedObject = pet;
995
- item.state = [petID isEqualToString:self.currentPetID] ? NSControlStateValueOn : NSControlStateValueOff;
996
- }
997
- switchItem.submenu = switchMenu;
998
- [menu addItem:NSMenuItem.separatorItem];
999
- NSMenuItem *refreshItem = [menu addItemWithTitle:@"刷新用量" action:@selector(refreshUsage:) keyEquivalent:@"r"];
1000
- refreshItem.target = NSApp.delegate;
1001
- [self addPersistentSwitchToMenu:menu
1002
- title:@"记录本地额度历史"
1003
- checked:[NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]
1004
- action:@selector(toggleQuotaHistory:)
1005
- tag:0];
1006
- NSMenuItem *notificationItem = [menu addItemWithTitle:@"系统通知" action:nil keyEquivalent:@""];
1007
- NSMenu *notificationMenu = [NSMenu new];
1008
- NSArray<NSDictionary *> *notificationOptions = @[
1009
- @{@"title": @"任务完成", @"key": NotificationCompletionKey, @"tag": @1},
1010
- @{@"title": @"任务失败", @"key": NotificationFailureKey, @"tag": @2},
1011
- @{@"title": @"等待审批", @"key": NotificationApprovalKey, @"tag": @3}
1012
- ];
1013
- for (NSDictionary *option in notificationOptions) {
1014
- [self addPersistentSwitchToMenu:notificationMenu
1015
- title:option[@"title"]
1016
- checked:[NSUserDefaults.standardUserDefaults boolForKey:option[@"key"]]
1017
- action:@selector(toggleNotification:)
1018
- tag:[option[@"tag"] integerValue]];
1019
- }
1020
- notificationItem.submenu = notificationMenu;
1021
- NSMenuItem *updateItem = [menu addItemWithTitle:@"检查更新…" action:@selector(checkForUpdates:) keyEquivalent:@""];
1022
- updateItem.target = NSApp.delegate;
1023
- [menu addItem:NSMenuItem.separatorItem];
1024
- NSMenuItem *quitItem = [menu addItemWithTitle:@"退出桌宠" action:@selector(terminate:) keyEquivalent:@"q"];
1025
- quitItem.target = NSApp;
1026
- [NSMenu popUpContextMenu:menu withEvent:event forView:self];
1027
- [self.petMenuPreviewPanel orderOut:nil];
1028
- }
1029
- @end
1030
-
1031
- static const CGFloat QuotaLogicalWidth = 600;
1032
- static const CGFloat QuotaLogicalHeight = 360;
1033
- static const CGFloat QuotaScale = 0.6;
1034
-
1035
- static NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
1036
- NSURL *appURL = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:bundleIdentifier];
1037
- NSMutableArray<NSString *> *paths = [NSMutableArray array];
1038
- if (appURL) {
1039
- NSBundle *bundle = [NSBundle bundleWithURL:appURL];
1040
- NSString *resourcePath = [bundle pathForResource:resourceName.stringByDeletingPathExtension
1041
- ofType:resourceName.pathExtension];
1042
- if (resourcePath.length > 0) [paths addObject:resourcePath];
1043
- }
1044
- NSString *applicationName = [bundleIdentifier containsString:@"anthropic"] ? @"Claude.app" : @"ChatGPT.app";
1045
- [paths addObject:[@"/Applications" stringByAppendingPathComponent:
1046
- [applicationName stringByAppendingPathComponent:[@"Contents/Resources" stringByAppendingPathComponent:resourceName]]]];
1047
- [paths addObject:[[NSHomeDirectory() stringByAppendingPathComponent:@"Applications"] stringByAppendingPathComponent:
1048
- [applicationName stringByAppendingPathComponent:[@"Contents/Resources" stringByAppendingPathComponent:resourceName]]]];
1049
- for (NSString *path in paths) {
1050
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
1051
- if (image) return image;
1052
- }
1053
- return appURL ? [NSWorkspace.sharedWorkspace iconForFile:appURL.path] : nil;
1054
- }
1055
-
1056
- @interface QuotaDashboardView : NSView
1057
- @property NSDictionary *codexUsage;
1058
- @property NSDictionary *claudeUsage;
1059
- @property NSArray<NSNumber *> *codexHistory;
1060
- @property NSArray<NSNumber *> *claudeHistory;
1061
- @property BOOL historyEnabled;
1062
- @property NSImage *codexLogo;
1063
- @property NSImage *claudeLogo;
1064
- @property BOOL refreshHovered;
1065
- @property BOOL refreshPressed;
1066
- @property NSTimeInterval refreshedUntil;
1067
- @property(copy) void (^hoverChanged)(BOOL hovering);
1068
- @property(copy) void (^refreshRequested)(void);
1069
- @end
1070
-
1071
- @implementation QuotaDashboardView
1072
- - (instancetype)initWithFrame:(NSRect)frame {
1073
- if ((self = [super initWithFrame:frame])) {
1074
- NSTrackingArea *tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect
1075
- options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
1076
- NSTrackingActiveAlways | NSTrackingInVisibleRect
1077
- owner:self userInfo:nil];
1078
- [self addTrackingArea:tracking];
1079
- }
1080
- return self;
1081
- }
1082
- - (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
1083
- - (void)mouseEntered:(NSEvent *)event {
1084
- if (self.hoverChanged) self.hoverChanged(YES);
1085
- [self mouseMoved:event];
1086
- }
1087
- - (void)mouseExited:(NSEvent *)event {
1088
- self.refreshHovered = NO;
1089
- self.refreshPressed = NO;
1090
- [NSCursor.arrowCursor set];
1091
- self.needsDisplay = YES;
1092
- if (self.hoverChanged) self.hoverChanged(NO);
1093
- }
1094
- - (NSRect)logicalRefreshRect { return NSMakeRect(QuotaLogicalWidth - 54, QuotaLogicalHeight - 52, 34, 32); }
1095
- - (NSRect)refreshRect {
1096
- NSRect logical = [self logicalRefreshRect];
1097
- return NSMakeRect(logical.origin.x * QuotaScale, logical.origin.y * QuotaScale,
1098
- logical.size.width * QuotaScale, logical.size.height * QuotaScale);
1099
- }
1100
- - (void)mouseMoved:(NSEvent *)event {
1101
- NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
1102
- BOOL hovering = NSPointInRect(point, [self refreshRect]);
1103
- if (hovering != self.refreshHovered) {
1104
- self.refreshHovered = hovering;
1105
- self.needsDisplay = YES;
1106
- }
1107
- if (hovering) [NSCursor.pointingHandCursor set];
1108
- else [NSCursor.arrowCursor set];
1109
- }
1110
- - (void)mouseDown:(NSEvent *)event {
1111
- NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
1112
- if (NSPointInRect(point, [self refreshRect])) {
1113
- self.refreshPressed = YES;
1114
- self.needsDisplay = YES;
1115
- }
1116
- }
1117
- - (void)mouseUp:(NSEvent *)event {
1118
- NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
1119
- BOOL shouldRefresh = self.refreshPressed && NSPointInRect(point, [self refreshRect]);
1120
- self.refreshPressed = NO;
1121
- if (shouldRefresh) {
1122
- if (self.refreshRequested) self.refreshRequested();
1123
- self.refreshedUntil = NSDate.date.timeIntervalSince1970 + 1.2;
1124
- [[NSHapticFeedbackManager defaultPerformer] performFeedbackPattern:NSHapticFeedbackPatternAlignment
1125
- performanceTime:NSHapticFeedbackPerformanceTimeNow];
1126
- [self performSelector:@selector(clearRefreshConfirmation) withObject:nil afterDelay:1.2];
1127
- }
1128
- self.needsDisplay = YES;
1129
- }
1130
- - (void)clearRefreshConfirmation {
1131
- self.refreshedUntil = 0;
1132
- self.needsDisplay = YES;
1133
- }
1134
- - (NSDictionary *)quota:(NSDictionary *)usage key:(NSString *)key {
1135
- id value = usage[key];
1136
- return [value isKindOfClass:NSDictionary.class] ? value : nil;
1137
- }
1138
- - (NSNumber *)remainingForQuota:(NSDictionary *)quota usedKey:(NSString *)usedKey {
1139
- NSNumber *used = quota[usedKey];
1140
- if (![used isKindOfClass:NSNumber.class]) return nil;
1141
- return @(fmax(0, fmin(100, 100.0 - used.doubleValue)));
1142
- }
1143
- - (NSString *)weeklyReset:(NSDictionary *)week {
1144
- NSNumber *weekReset = week[@"resets_at"];
1145
- if (!weekReset) return @"--";
1146
- NSDateFormatter *formatter = [NSDateFormatter new];
1147
- formatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
1148
- formatter.timeZone = NSTimeZone.localTimeZone;
1149
- formatter.dateFormat = @"M/d HH:mm:ss";
1150
- return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:weekReset.doubleValue]];
1151
- }
1152
- - (NSDictionary *)textAttributesWithSize:(CGFloat)size color:(NSColor *)color weight:(NSFontWeight)weight {
1153
- return @{NSFontAttributeName: [NSFont systemFontOfSize:size weight:weight],
1154
- NSForegroundColorAttributeName: color};
1155
- }
1156
- - (NSDictionary *)centeredTextAttributesWithSize:(CGFloat)size color:(NSColor *)color weight:(NSFontWeight)weight {
1157
- NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
1158
- style.alignment = NSTextAlignmentCenter;
1159
- return @{NSFontAttributeName: [NSFont systemFontOfSize:size weight:weight],
1160
- NSForegroundColorAttributeName: color,
1161
- NSParagraphStyleAttributeName: style};
1162
- }
1163
- - (void)fillRoundedRect:(NSRect)rect radius:(CGFloat)radius color:(NSColor *)color {
1164
- [color setFill];
1165
- [[NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius] fill];
1166
- }
1167
- - (void)drawHistorySeries:(NSArray<NSNumber *> *)series inRect:(NSRect)rect color:(NSColor *)color {
1168
- if (!self.historyEnabled || series.count == 0) return;
1169
- [[color colorWithAlphaComponent:0.10] setFill];
1170
- [[NSBezierPath bezierPathWithRoundedRect:rect xRadius:4 yRadius:4] fill];
1171
- CGFloat step = series.count > 1 ? NSWidth(rect) / (series.count - 1) : 0;
1172
- NSBezierPath *line = [NSBezierPath bezierPath];
1173
- for (NSUInteger index = 0; index < series.count; index++) {
1174
- CGFloat value = fmax(0, fmin(100, series[index].doubleValue));
1175
- NSPoint point = NSMakePoint(NSMinX(rect) + index * step,
1176
- NSMinY(rect) + 2 + (NSHeight(rect) - 4) * value / 100.0);
1177
- if (index == 0) [line moveToPoint:point];
1178
- else [line lineToPoint:point];
1179
- if (series.count == 1) {
1180
- [[color colorWithAlphaComponent:0.9] setFill];
1181
- [[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(point.x - 2, point.y - 2, 4, 4)] fill];
1182
- }
1183
- }
1184
- line.lineWidth = 2;
1185
- line.lineJoinStyle = NSLineJoinStyleRound;
1186
- line.lineCapStyle = NSLineCapStyleRound;
1187
- [[color colorWithAlphaComponent:0.9] setStroke];
1188
- [line stroke];
1189
- }
1190
- - (void)drawProvider:(NSString *)name usage:(NSDictionary *)usage usedKey:(NSString *)usedKey
1191
- color:(NSColor *)color cardRect:(NSRect)card {
1192
- NSColor *primary = [NSColor colorWithWhite:0.96 alpha:1];
1193
- NSColor *secondary = [NSColor colorWithWhite:0.68 alpha:1];
1194
- NSColor *track = [NSColor colorWithWhite:0.28 alpha:0.55];
1195
- NSDictionary *five = [self quota:usage key:@"fiveHour"];
1196
- NSDictionary *week = [self quota:usage key:@"week"];
1197
- NSNumber *fiveRemaining = [self remainingForQuota:five usedKey:usedKey];
1198
- NSNumber *weekRemaining = [self remainingForQuota:week usedKey:usedKey];
1199
- BOOL available = fiveRemaining || weekRemaining;
1200
-
1201
- NSBezierPath *cardPath = [NSBezierPath bezierPathWithRoundedRect:card xRadius:16 yRadius:16];
1202
- NSGradient *cardGlass = [[NSGradient alloc]
1203
- initWithStartingColor:[NSColor colorWithWhite:1 alpha:0.13]
1204
- endingColor:[NSColor colorWithRed:0.30 green:0.42 blue:0.62 alpha:0.06]];
1205
- [cardGlass drawInBezierPath:cardPath angle:-30];
1206
- NSBezierPath *border = cardPath;
1207
- [[NSColor colorWithWhite:1 alpha:0.38] setStroke];
1208
- border.lineWidth = 1;
1209
- [border stroke];
1210
- NSBezierPath *innerBorder = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(card, 1.5, 1.5)
1211
- xRadius:14.5 yRadius:14.5];
1212
- [[NSColor colorWithRed:0.66 green:0.86 blue:1 alpha:0.12] setStroke];
1213
- innerBorder.lineWidth = 0.8;
1214
- [innerBorder stroke];
1215
-
1216
- NSRect icon = NSMakeRect(NSMinX(card) + 18, NSMinY(card) + 37, 48, 48);
1217
- NSImage *logo = [name isEqualToString:@"Codex"] ? self.codexLogo : self.claudeLogo;
1218
- if (logo) {
1219
- [NSGraphicsContext saveGraphicsState];
1220
- [[NSBezierPath bezierPathWithRoundedRect:icon xRadius:13 yRadius:13] addClip];
1221
- [logo drawInRect:icon fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0
1222
- respectFlipped:YES hints:@{NSImageHintInterpolation: @(NSImageInterpolationHigh)}];
1223
- [NSGraphicsContext restoreGraphicsState];
1224
- } else {
1225
- [self fillRoundedRect:icon radius:13 color:[color colorWithAlphaComponent:0.7]];
1226
- NSString *iconText = [name isEqualToString:@"Codex"] ? @"C" : @"AI";
1227
- [iconText drawInRect:NSInsetRect(icon, 0, 10)
1228
- withAttributes:[self centeredTextAttributesWithSize:20 color:NSColor.whiteColor weight:NSFontWeightBold]];
1229
- }
1230
-
1231
- [name drawInRect:NSMakeRect(NSMinX(card) + 78, NSMinY(card) + 64, 70, 24)
1232
- withAttributes:[self textAttributesWithSize:18 color:primary weight:NSFontWeightSemibold]];
1233
- NSRect status = NSMakeRect(NSMinX(card) + 78, NSMinY(card) + 37, available ? 44 : 68, 22);
1234
- [self fillRoundedRect:status radius:9 color:[available ? NSColor.systemGreenColor : secondary colorWithAlphaComponent:0.15]];
1235
- NSString *statusText = available ? @"在线" : @"等待数据";
1236
- [statusText drawInRect:NSInsetRect(status, 8, 3)
1237
- withAttributes:[self textAttributesWithSize:11 color:available ? NSColor.systemGreenColor : secondary weight:NSFontWeightMedium]];
1238
-
1239
- CGFloat firstX = NSMinX(card) + 160;
1240
- [@"5 小时剩余" drawInRect:NSMakeRect(firstX, NSMinY(card) + 68, 100, 20)
1241
- withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
1242
- NSString *fiveText = fiveRemaining ? [NSString stringWithFormat:@"%.0f%%", fiveRemaining.doubleValue] : @"--";
1243
- [fiveText drawInRect:NSMakeRect(firstX, NSMinY(card) + 40, 90, 26)
1244
- withAttributes:[self textAttributesWithSize:20 color:primary weight:NSFontWeightSemibold]];
1245
- NSRect bar = NSMakeRect(firstX, NSMinY(card) + 24, 112, 8);
1246
- [self fillRoundedRect:bar radius:4 color:track];
1247
- if (fiveRemaining) {
1248
- NSRect fill = bar;
1249
- fill.size.width *= fiveRemaining.doubleValue / 100.0;
1250
- [self fillRoundedRect:fill radius:4 color:color];
1251
- }
1252
-
1253
- CGFloat separatorOne = NSMinX(card) + 290;
1254
- [[NSColor colorWithWhite:1 alpha:0.12] setStroke];
1255
- [NSBezierPath strokeLineFromPoint:NSMakePoint(separatorOne, NSMinY(card) + 20)
1256
- toPoint:NSMakePoint(separatorOne, NSMaxY(card) - 20)];
1257
- CGFloat ringX = separatorOne + 38;
1258
- NSPoint center = NSMakePoint(ringX, NSMinY(card) + 51);
1259
- NSBezierPath *ringTrack = [NSBezierPath bezierPath];
1260
- [ringTrack appendBezierPathWithArcWithCenter:center radius:24 startAngle:0 endAngle:360];
1261
- ringTrack.lineWidth = 7;
1262
- [track setStroke];
1263
- [ringTrack stroke];
1264
- if (weekRemaining) {
1265
- NSBezierPath *ring = [NSBezierPath bezierPath];
1266
- [ring appendBezierPathWithArcWithCenter:center radius:24 startAngle:90
1267
- endAngle:90 - 360 * weekRemaining.doubleValue / 100.0 clockwise:YES];
1268
- ring.lineWidth = 7;
1269
- ring.lineCapStyle = NSLineCapStyleRound;
1270
- [color setStroke];
1271
- [ring stroke];
1272
- }
1273
- NSString *weekText = weekRemaining ? [NSString stringWithFormat:@"%.0f%%", weekRemaining.doubleValue] : @"--";
1274
- [weekText drawInRect:NSMakeRect(ringX - 19, NSMinY(card) + 42, 38, 18)
1275
- withAttributes:[self centeredTextAttributesWithSize:13 color:primary weight:NSFontWeightSemibold]];
1276
- [@"周剩余" drawInRect:NSMakeRect(separatorOne + 68, NSMinY(card) + 66, 55, 20)
1277
- withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
1278
-
1279
- CGFloat separatorTwo = NSMinX(card) + 414;
1280
- [[NSColor colorWithWhite:1 alpha:0.12] setStroke];
1281
- [NSBezierPath strokeLineFromPoint:NSMakePoint(separatorTwo, NSMinY(card) + 20)
1282
- toPoint:NSMakePoint(separatorTwo, NSMaxY(card) - 20)];
1283
- [@"周重置" drawInRect:NSMakeRect(separatorTwo + 16, NSMinY(card) + 66, 80, 20)
1284
- withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
1285
- [[self weeklyReset:week] drawInRect:NSMakeRect(separatorTwo + 16, NSMinY(card) + 39,
1286
- NSMaxX(card) - separatorTwo - 28, 24)
1287
- withAttributes:[self textAttributesWithSize:15 color:primary weight:NSFontWeightMedium]];
1288
- NSArray<NSNumber *> *history = [name isEqualToString:@"Codex"] ? self.codexHistory : self.claudeHistory;
1289
- [self drawHistorySeries:history
1290
- inRect:NSMakeRect(separatorTwo + 16, NSMinY(card) + 14, NSMaxX(card) - separatorTwo - 28, 17)
1291
- color:color];
1292
- }
1293
- - (void)drawRect:(NSRect)dirtyRect {
1294
- [NSGraphicsContext saveGraphicsState];
1295
- NSAffineTransform *scale = [NSAffineTransform transform];
1296
- [scale scaleBy:QuotaScale];
1297
- [scale concat];
1298
- NSRect logicalBounds = NSMakeRect(0, 0, QuotaLogicalWidth, QuotaLogicalHeight);
1299
- NSRect outer = NSInsetRect(logicalBounds, 1, 1);
1300
- NSBezierPath *background = [NSBezierPath bezierPathWithRoundedRect:outer xRadius:22 yRadius:22];
1301
- NSGradient *gradient = [[NSGradient alloc]
1302
- initWithStartingColor:[NSColor colorWithRed:0.035 green:0.075 blue:0.14 alpha:0.68]
1303
- endingColor:[NSColor colorWithRed:0.15 green:0.20 blue:0.31 alpha:0.46]];
1304
- [gradient drawInBezierPath:background angle:-20];
1305
-
1306
- [NSGraphicsContext saveGraphicsState];
1307
- [background addClip];
1308
- NSGradient *topGlow = [[NSGradient alloc]
1309
- initWithStartingColor:[NSColor colorWithWhite:1 alpha:0.34]
1310
- endingColor:[NSColor colorWithWhite:1 alpha:0.0]];
1311
- [topGlow drawFromCenter:NSMakePoint(555, 348) radius:0
1312
- toCenter:NSMakePoint(555, 348) radius:180 options:0];
1313
- NSGradient *cyanGlow = [[NSGradient alloc]
1314
- initWithStartingColor:[NSColor colorWithRed:0.18 green:0.72 blue:1 alpha:0.11]
1315
- endingColor:[NSColor colorWithRed:0.18 green:0.88 blue:1 alpha:0.0]];
1316
- [cyanGlow drawFromCenter:NSMakePoint(560, 85) radius:0
1317
- toCenter:NSMakePoint(560, 85) radius:170 options:0];
1318
- [NSGraphicsContext restoreGraphicsState];
1319
-
1320
- [[NSColor colorWithWhite:1 alpha:0.62] setStroke];
1321
- background.lineWidth = 1.5;
1322
- [background stroke];
1323
- NSBezierPath *innerGlassBorder = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(outer, 2, 2)
1324
- xRadius:20 yRadius:20];
1325
- [[NSColor colorWithRed:0.58 green:0.82 blue:1 alpha:0.22] setStroke];
1326
- innerGlassBorder.lineWidth = 0.8;
1327
- [innerGlassBorder stroke];
1328
-
1329
-
1330
- [@"Agent 余量" drawInRect:NSMakeRect(24, QuotaLogicalHeight - 53, 180, 30)
1331
- withAttributes:[self textAttributesWithSize:23 color:[NSColor colorWithWhite:0.97 alpha:1] weight:NSFontWeightBold]];
1332
- [@"实时配额状态" drawInRect:NSMakeRect(25, QuotaLogicalHeight - 76, 130, 20)
1333
- withAttributes:[self textAttributesWithSize:12 color:[NSColor colorWithWhite:0.63 alpha:1] weight:NSFontWeightRegular]];
1334
- BOOL recentlyRefreshed = self.refreshedUntil > NSDate.date.timeIntervalSince1970;
1335
- NSRect live = NSMakeRect(QuotaLogicalWidth - 145, QuotaLogicalHeight - 51, 78, 28);
1336
- [self fillRoundedRect:live radius:14 color:[NSColor colorWithWhite:1 alpha:0.055]];
1337
- [[NSColor systemGreenColor] setFill];
1338
- [[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(NSMinX(live) + 12, NSMinY(live) + 10, 8, 8)] fill];
1339
- [recentlyRefreshed ? @"已刷新" : @"实时更新" drawInRect:NSMakeRect(NSMinX(live) + 26, NSMinY(live) + 6, 50, 18)
1340
- withAttributes:[self textAttributesWithSize:11 color:[NSColor colorWithWhite:0.87 alpha:1] weight:NSFontWeightMedium]];
1341
- CGFloat buttonAlpha = self.refreshPressed ? 0.18 : (self.refreshHovered ? 0.12 : 0.06);
1342
- NSRect logicalRefreshRect = [self logicalRefreshRect];
1343
- NSRect refreshRect = self.refreshPressed ? NSInsetRect(logicalRefreshRect, 1.5, 1.5) : logicalRefreshRect;
1344
- [self fillRoundedRect:refreshRect radius:10 color:[NSColor colorWithWhite:1 alpha:buttonAlpha]];
1345
- [recentlyRefreshed ? @"✓" : @"↻" drawInRect:NSInsetRect(refreshRect, 8, 4)
1346
- withAttributes:[self textAttributesWithSize:19 color:[NSColor colorWithWhite:0.9 alpha:1] weight:NSFontWeightRegular]];
1347
-
1348
- [self drawProvider:@"Codex" usage:self.codexUsage usedKey:@"used_percent"
1349
- color:[NSColor colorWithRed:0.30 green:0.82 blue:0.86 alpha:1]
1350
- cardRect:NSMakeRect(18, 174, QuotaLogicalWidth - 36, 104)];
1351
- [self drawProvider:@"Claude" usage:self.claudeUsage usedKey:@"used_percentage"
1352
- color:[NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1]
1353
- cardRect:NSMakeRect(18, 58, QuotaLogicalWidth - 36, 104)];
1354
- NSString *footer = self.historyEnabled
1355
- ? @"ⓘ 曲线为本机近 7 天周剩余额度 · 15 分钟采样"
1356
- : @"ⓘ 额度随 CLI 响应自动更新 · 本地历史已关闭";
1357
- [footer drawInRect:NSMakeRect(24, 23, 430, 20)
1358
- withAttributes:[self textAttributesWithSize:11 color:[NSColor colorWithWhite:0.58 alpha:1] weight:NSFontWeightRegular]];
1359
- [NSGraphicsContext restoreGraphicsState];
1360
- }
1361
- @end
1362
-
1363
- static int RenderQuotaDashboard(NSString *path) {
1364
- [NSApplication sharedApplication];
1365
- QuotaDashboardView *view = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0,
1366
- QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale)];
1367
- view.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
1368
- view.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
1369
- view.codexUsage = LatestUsage() ?: @{
1370
- @"fiveHour": @{@"used_percent": @34, @"resets_at": @([NSDate.date timeIntervalSince1970] + 7200)},
1371
- @"week": @{@"used_percent": @51, @"resets_at": @([NSDate.date timeIntervalSince1970] + 172800)}
1372
- };
1373
- view.claudeUsage = LatestClaudeUsage() ?: @{
1374
- @"fiveHour": @{@"used_percentage": @23, @"resets_at": @([NSDate.date timeIntervalSince1970] + 3600)},
1375
- @"week": @{@"used_percentage": @41, @"resets_at": @([NSDate.date timeIntervalSince1970] + 86400)}
1376
- };
1377
- view.historyEnabled = YES;
1378
- view.codexHistory = @[@88, @81, @75, @68, @62, @55, @49];
1379
- view.claudeHistory = @[@92, @86, @78, @72, @64, @58, @51];
1380
- NSInteger pixelWidth = (NSInteger)ceil(NSWidth(view.bounds));
1381
- NSInteger pixelHeight = (NSInteger)ceil(NSHeight(view.bounds));
1382
- NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
1383
- initWithBitmapDataPlanes:NULL
1384
- pixelsWide:pixelWidth
1385
- pixelsHigh:pixelHeight
1386
- bitsPerSample:8
1387
- samplesPerPixel:4
1388
- hasAlpha:YES
1389
- isPlanar:NO
1390
- colorSpaceName:NSDeviceRGBColorSpace
1391
- bytesPerRow:0
1392
- bitsPerPixel:0];
1393
- bitmap.size = view.bounds.size;
1394
- NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
1395
- [NSGraphicsContext saveGraphicsState];
1396
- NSGraphicsContext.currentContext = context;
1397
- [view displayRectIgnoringOpacity:view.bounds inContext:context];
1398
- [NSGraphicsContext restoreGraphicsState];
1399
- NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
1400
- return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
1401
- }
1402
-
1403
- static int RenderAgentStatusCard(NSString *path) {
1404
- [NSApplication sharedApplication];
1405
- NSSize glassSize = NSMakeSize(340, 58);
1406
- NSSize size = NSMakeSize(glassSize.width + 12, glassSize.height + 12);
1407
- NSView *root = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
1408
- NSView *shadowView = [[NSView alloc] initWithFrame:NSMakeRect(
1409
- 6, 6, glassSize.width, glassSize.height)];
1410
- shadowView.wantsLayer = YES;
1411
- shadowView.layer.backgroundColor = [NSColor colorWithWhite:0 alpha:0.01].CGColor;
1412
- shadowView.layer.cornerRadius = glassSize.height / 2.0;
1413
- shadowView.layer.cornerCurve = kCACornerCurveContinuous;
1414
- shadowView.layer.shadowColor = NSColor.blackColor.CGColor;
1415
- shadowView.layer.shadowOpacity = 0.24;
1416
- shadowView.layer.shadowRadius = 8;
1417
- shadowView.layer.shadowOffset = NSMakeSize(0, -3);
1418
- CGPathRef shadowPath = CGPathCreateWithRoundedRect(shadowView.bounds,
1419
- glassSize.height / 2.0, glassSize.height / 2.0, NULL);
1420
- shadowView.layer.shadowPath = shadowPath;
1421
- CGPathRelease(shadowPath);
1422
- [root addSubview:shadowView];
1423
-
1424
- NSVisualEffectView *glass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(
1425
- 6, 6, glassSize.width, glassSize.height)];
1426
- glass.material = NSVisualEffectMaterialPopover;
1427
- glass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
1428
- glass.state = NSVisualEffectStateActive;
1429
- glass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
1430
- glass.wantsLayer = YES;
1431
- glass.layer.cornerRadius = glassSize.height / 2.0;
1432
- glass.layer.cornerCurve = kCACornerCurveContinuous;
1433
- glass.layer.masksToBounds = YES;
1434
- glass.layer.borderWidth = 1;
1435
- glass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
1436
- [root addSubview:glass];
1437
-
1438
- NSTextField *title = [NSTextField labelWithString:@"Codex · 任务已完成"];
1439
- title.frame = NSMakeRect(20, 30, glassSize.width - 80, 18);
1440
- title.font = [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold];
1441
- title.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
1442
- [glass addSubview:title];
1443
- NSTextField *detail = [NSTextField labelWithString:@"好的,当前任务已经完成。"];
1444
- detail.frame = NSMakeRect(20, 12, glassSize.width - 80, 17);
1445
- detail.font = [NSFont systemFontOfSize:12 weight:NSFontWeightRegular];
1446
- detail.textColor = [NSColor colorWithWhite:0.34 alpha:0.88];
1447
- [glass addSubview:detail];
1448
-
1449
- NSButton *icon = [[NSButton alloc] initWithFrame:NSMakeRect(glassSize.width - 48, 12, 34, 34)];
1450
- icon.bordered = NO;
1451
- icon.imagePosition = NSImageOnly;
1452
- icon.wantsLayer = YES;
1453
- icon.layer.cornerRadius = 17;
1454
- icon.layer.masksToBounds = YES;
1455
- NSColor *green = [NSColor colorWithRed:0.18 green:0.68 blue:0.35 alpha:1];
1456
- icon.layer.backgroundColor = [green colorWithAlphaComponent:0.28].CGColor;
1457
- NSImage *image = [NSImage imageWithSystemSymbolName:@"checkmark"
1458
- accessibilityDescription:@"任务已完成"];
1459
- icon.image = [image imageWithSymbolConfiguration:
1460
- [NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightBold]];
1461
- icon.contentTintColor = [green blendedColorWithFraction:0.18
1462
- ofColor:NSColor.blackColor] ?: green;
1463
- [glass addSubview:icon];
1464
-
1465
- NSInteger pixelWidth = (NSInteger)ceil(size.width);
1466
- NSInteger pixelHeight = (NSInteger)ceil(size.height);
1467
- NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
1468
- initWithBitmapDataPlanes:NULL pixelsWide:pixelWidth pixelsHigh:pixelHeight
1469
- bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
1470
- colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
1471
- bitmap.size = size;
1472
- NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
1473
- [NSGraphicsContext saveGraphicsState];
1474
- NSGraphicsContext.currentContext = context;
1475
- [root displayRectIgnoringOpacity:root.bounds inContext:context];
1476
- [NSGraphicsContext restoreGraphicsState];
1477
- NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
1478
- return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
1479
- }
1480
-
1481
- static int RenderMenuSwitches(NSString *path) {
1482
- [NSApplication sharedApplication];
1483
- NSSize size = NSMakeSize(220, 72);
1484
- NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
1485
- view.wantsLayer = YES;
1486
- view.layer.backgroundColor = [NSColor colorWithWhite:0.86 alpha:1].CGColor;
1487
- NSArray<NSDictionary *> *rows = @[
1488
- @{@"title": @"任务完成", @"state": @YES, @"y": @40},
1489
- @{@"title": @"任务失败", @"state": @NO, @"y": @10}
1490
- ];
1491
- for (NSDictionary *row in rows) {
1492
- CGFloat y = [row[@"y"] doubleValue];
1493
- NSTextField *label = [NSTextField labelWithString:row[@"title"]];
1494
- label.frame = NSMakeRect(14, y + 3, 130, 18);
1495
- label.font = [NSFont menuFontOfSize:13];
1496
- label.textColor = NSColor.labelColor;
1497
- [view addSubview:label];
1498
- MenuToggleSwitch *toggle = [[MenuToggleSwitch alloc] initWithFrame:NSMakeRect(168, y, 36, 22)];
1499
- toggle.state = [row[@"state"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff;
1500
- [view addSubview:toggle];
1501
- }
1502
-
1503
- NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
1504
- initWithBitmapDataPlanes:NULL pixelsWide:(NSInteger)size.width pixelsHigh:(NSInteger)size.height
1505
- bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
1506
- colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
1507
- bitmap.size = size;
1508
- NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
1509
- [NSGraphicsContext saveGraphicsState];
1510
- NSGraphicsContext.currentContext = context;
1511
- [view displayRectIgnoringOpacity:view.bounds inContext:context];
1512
- [NSGraphicsContext restoreGraphicsState];
1513
- NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
1514
- return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
1515
- }
1516
-
1517
- @interface AppDelegate : NSObject <NSApplicationDelegate>
1518
- @property NSPanel *panel;
1519
- @property NSPanel *quotaPanel;
1520
- @property NSPanel *statusPanel;
1521
- @property NSVisualEffectView *statusGlass;
1522
- @property NSTextField *statusTitleLabel;
1523
- @property NSTextField *statusDetailLabel;
1524
- @property NSButton *statusIconButton;
1525
- @property NSPanel *statusTogglePanel;
1526
- @property NSVisualEffectView *statusToggleGlass;
1527
- @property NSButton *statusToggleButton;
1528
- @property BOOL statusBubbleExpanded;
1529
- @property BOOL statusBubbleAbove;
1530
- @property BOOL hasAgentStatus;
1531
- @property NSInteger liveClientCount;
1532
- @property NSString *lastStatusState;
1533
- @property QuotaDashboardView *quotaView;
1534
- @property BOOL managedByCLI;
1535
- @property BOOL pocketHovering;
1536
- @property BOOL dashboardHovering;
1537
- @property BOOL petDragging;
1538
- @property NSString *binaryDirectory;
1539
- @property PetView *petView;
1540
- @property CodexUsageReader *codexUsageReader;
1541
- @property unsigned long long agentEventOffset;
1542
- @property NSMutableData *agentEventPartialLine;
1543
- @property dispatch_source_t agentEventSource;
1544
- @property BOOL agentEventReaderInitialized;
1545
- @property BOOL checkingForUpdate;
1546
- @property BOOL updating;
1547
- @property NSTask *updateTask;
1548
- - (void)showQuotaDashboard;
1549
- - (void)positionQuotaDashboard;
1550
- - (void)scheduleQuotaDashboardHide;
1551
- - (void)hideQuotaDashboardIfNeeded;
1552
- - (void)positionAgentStatus;
1553
- - (void)showAgentStatusForRecord:(NSDictionary *)record;
1554
- - (void)toggleAgentStatusBubble:(id)sender;
1555
- @end
1556
-
1557
- @implementation AppDelegate
1558
- - (NSString *)applicationSupportDirectory {
1559
- return ApplicationSupportDirectory();
1560
- }
1561
- - (void)showUpdateAlertWithTitle:(NSString *)title message:(NSString *)message {
1562
- [NSApp activateIgnoringOtherApps:YES];
1563
- NSAlert *alert = [NSAlert new];
1564
- alert.messageText = title;
1565
- alert.informativeText = message;
1566
- [alert addButtonWithTitle:@"好"];
1567
- [alert runModal];
1568
- }
1569
- - (NSDictionary *)updaterConfiguration {
1570
- NSString *path = [[self applicationSupportDirectory] stringByAppendingPathComponent:@"updater.json"];
1571
- NSData *data = [NSData dataWithContentsOfFile:path];
1572
- NSDictionary *configuration = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
1573
- return [configuration isKindOfClass:NSDictionary.class] ? configuration : nil;
1574
- }
1575
- - (BOOL)restartAfterUpdateToVersion:(NSString *)version configuration:(NSDictionary *)configuration {
1576
- NSString *appPath = [configuration[@"appPath"] isKindOfClass:NSString.class]
1577
- ? [configuration[@"appPath"] stringByStandardizingPath] : nil;
1578
- if (appPath.length == 0 &&
1579
- [NSBundle.mainBundle.bundlePath.pathExtension.lowercaseString isEqualToString:@"app"]) {
1580
- appPath = NSBundle.mainBundle.bundlePath.stringByStandardizingPath;
1581
- }
1582
- if (appPath.length == 0) {
1583
- appPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Applications"]
1584
- stringByAppendingPathComponent:@"CC Pets.app"];
1585
- }
1586
-
1587
- NSString *infoPath = [appPath stringByAppendingPathComponent:@"Contents/Info.plist"];
1588
- NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:infoPath];
1589
- NSString *installedVersion = [info[@"CFBundleShortVersionString"] isKindOfClass:NSString.class]
1590
- ? info[@"CFBundleShortVersionString"] : nil;
1591
- NSString *executablePath = [appPath stringByAppendingPathComponent:@"Contents/MacOS/cc-pets"];
1592
- if (![installedVersion isEqualToString:version] ||
1593
- ![NSFileManager.defaultManager isExecutableFileAtPath:executablePath]) return NO;
1594
-
1595
- NSTask *restartTask = [NSTask new];
1596
- restartTask.executableURL = [NSURL fileURLWithPath:executablePath];
1597
- restartTask.arguments = @[
1598
- @"--restart-after-pid",
1599
- [NSString stringWithFormat:@"%d", NSProcessInfo.processInfo.processIdentifier],
1600
- appPath,
1601
- self.managedByCLI ? @"--managed" : @"--standalone"
1602
- ];
1603
- NSError *error = nil;
1604
- if (![restartTask launchAndReturnError:&error]) return NO;
1605
- [NSApp terminate:nil];
1606
- return YES;
1607
- }
1608
- - (void)startUpdateToVersion:(NSString *)version {
1609
- if (self.updating) return;
1610
- NSDictionary *configuration = [self updaterConfiguration];
1611
- NSString *nodePath = [configuration[@"nodePath"] isKindOfClass:NSString.class]
1612
- ? [configuration[@"nodePath"] stringByStandardizingPath] : nil;
1613
- NSString *npmCliPath = [configuration[@"npmCliPath"] isKindOfClass:NSString.class]
1614
- ? [configuration[@"npmCliPath"] stringByStandardizingPath] : nil;
1615
- BOOL nodeExecutable = nodePath.isAbsolutePath &&
1616
- [NSFileManager.defaultManager isExecutableFileAtPath:nodePath];
1617
- BOOL npmCliExists = npmCliPath.isAbsolutePath &&
1618
- [NSFileManager.defaultManager isReadableFileAtPath:npmCliPath];
1619
- if (!nodeExecutable || !npmCliExists) {
1620
- [self showUpdateAlertWithTitle:@"无法自动更新"
1621
- message:@"没有找到安装 CC Pets 时使用的 Node.js/npm。请先手动执行一次:\n\n"
1622
- "npm install -g cc-pets@latest --allow-scripts=cc-pets --prefer-online"];
1623
- return;
1624
- }
1625
-
1626
- NSString *supportDirectory = [self applicationSupportDirectory];
1627
- NSError *directoryError = nil;
1628
- [NSFileManager.defaultManager createDirectoryAtPath:supportDirectory
1629
- withIntermediateDirectories:YES attributes:nil error:&directoryError];
1630
- if (directoryError) {
1631
- [self showUpdateAlertWithTitle:@"无法自动更新" message:directoryError.localizedDescription];
1632
- return;
1633
- }
1634
- NSString *logPath = [supportDirectory stringByAppendingPathComponent:@"update.log"];
1635
- [NSFileManager.defaultManager createFileAtPath:logPath contents:nil attributes:@{
1636
- NSFilePosixPermissions: @(S_IRUSR | S_IWUSR)
1637
- }];
1638
- NSFileHandle *logHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
1639
- if (!logHandle) {
1640
- [self showUpdateAlertWithTitle:@"无法自动更新" message:@"无法创建更新日志。"];
1641
- return;
1642
- }
1643
-
1644
- NSTask *task = [NSTask new];
1645
- task.executableURL = [NSURL fileURLWithPath:nodePath];
1646
- task.arguments = @[
1647
- npmCliPath,
1648
- @"install",
1649
- @"--global",
1650
- [@"cc-pets@" stringByAppendingString:version],
1651
- @"--allow-scripts=cc-pets",
1652
- @"--prefer-online"
1653
- ];
1654
- NSMutableDictionary<NSString *, NSString *> *environment =
1655
- [NSProcessInfo.processInfo.environment mutableCopy];
1656
- NSString *nodeDirectory = nodePath.stringByDeletingLastPathComponent;
1657
- NSString *existingPath = environment[@"PATH"];
1658
- if (existingPath.length == 0) existingPath = @"/usr/bin:/bin:/usr/sbin:/sbin";
1659
- environment[@"PATH"] = [NSString stringWithFormat:@"%@:%@", nodeDirectory, existingPath];
1660
- task.environment = environment;
1661
- task.currentDirectoryURL = [NSURL fileURLWithPath:NSHomeDirectory()];
1662
- task.standardOutput = logHandle;
1663
- task.standardError = logHandle;
1664
- self.updating = YES;
1665
- self.updateTask = task;
1666
- __weak typeof(self) weakSelf = self;
1667
- task.terminationHandler = ^(NSTask *finishedTask) {
1668
- [logHandle closeFile];
1669
- dispatch_async(dispatch_get_main_queue(), ^{
1670
- typeof(self) strongSelf = weakSelf;
1671
- if (!strongSelf) return;
1672
- strongSelf.updating = NO;
1673
- strongSelf.updateTask = nil;
1674
- if (finishedTask.terminationStatus == EXIT_SUCCESS) {
1675
- if ([strongSelf restartAfterUpdateToVersion:version configuration:configuration]) return;
1676
- [strongSelf showUpdateAlertWithTitle:@"更新完成"
1677
- message:@"CC Pets 已更新,但没有找到可自动启动的新版应用,请手动重新启动一次。"];
1678
- return;
1679
- }
1680
- [NSApp activateIgnoringOtherApps:YES];
1681
- NSAlert *alert = [NSAlert new];
1682
- alert.messageText = @"更新失败";
1683
- alert.informativeText = [NSString stringWithFormat:
1684
- @"旧版本仍可继续使用。错误详情已写入:\n%@", logPath];
1685
- [alert addButtonWithTitle:@"打开日志"];
1686
- [alert addButtonWithTitle:@"关闭"];
1687
- if ([alert runModal] == NSAlertFirstButtonReturn) {
1688
- [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:logPath]];
1689
- }
1690
- });
1691
- };
1692
- NSError *launchError = nil;
1693
- if (![task launchAndReturnError:&launchError]) {
1694
- self.updating = NO;
1695
- self.updateTask = nil;
1696
- [logHandle closeFile];
1697
- [self showUpdateAlertWithTitle:@"无法启动更新" message:launchError.localizedDescription];
1698
- return;
1699
- }
1700
- [self showUpdateAlertWithTitle:@"正在更新"
1701
- message:[NSString stringWithFormat:@"正在下载并安装 CC Pets %@。完成后桌宠会自动重启。", version]];
1702
- }
1703
- - (void)checkForUpdates:(id)sender {
1704
- if (self.checkingForUpdate || self.updating) return;
1705
- self.checkingForUpdate = YES;
1706
- NSURL *url = [NSURL URLWithString:@"https://registry.npmjs.org/cc-pets/latest"];
1707
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
1708
- cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
1709
- [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
1710
- __weak typeof(self) weakSelf = self;
1711
- NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithRequest:request
1712
- completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
1713
- dispatch_async(dispatch_get_main_queue(), ^{
1714
- typeof(self) strongSelf = weakSelf;
1715
- if (!strongSelf) return;
1716
- strongSelf.checkingForUpdate = NO;
1717
- NSHTTPURLResponse *httpResponse = [response isKindOfClass:NSHTTPURLResponse.class]
1718
- ? (NSHTTPURLResponse *)response : nil;
1719
- NSDictionary *metadata = data
1720
- ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
1721
- NSString *latestVersion = [metadata[@"version"] isKindOfClass:NSString.class]
1722
- ? metadata[@"version"] : nil;
1723
- BOOL valid = NO;
1724
- NSComparisonResult comparison = CompareStableVersions(@CC_PETS_VERSION, latestVersion, &valid);
1725
- if (error || httpResponse.statusCode != 200 || !valid) {
1726
- NSString *message = error.localizedDescription ?: @"npm Registry 返回了无效的版本信息,请稍后重试。";
1727
- [strongSelf showUpdateAlertWithTitle:@"检查更新失败" message:message];
1728
- return;
1729
- }
1730
- if (comparison != NSOrderedAscending) {
1731
- [strongSelf showUpdateAlertWithTitle:@"已是最新版本"
1732
- message:[NSString stringWithFormat:@"当前版本:%@", @CC_PETS_VERSION]];
1733
- return;
1734
- }
1735
- [NSApp activateIgnoringOtherApps:YES];
1736
- NSAlert *alert = [NSAlert new];
1737
- alert.messageText = @"发现新版本";
1738
- alert.informativeText = [NSString stringWithFormat:
1739
- @"当前版本:%@\n最新版本:%@\n\n是否立即更新?", @CC_PETS_VERSION, latestVersion];
1740
- [alert addButtonWithTitle:@"立即更新"];
1741
- [alert addButtonWithTitle:@"稍后"];
1742
- if ([alert runModal] == NSAlertFirstButtonReturn) {
1743
- [strongSelf startUpdateToVersion:latestVersion];
1744
- }
1745
- });
1746
- }];
1747
- [task resume];
1748
- }
1749
- - (void)toggleQuotaHistory:(NSButton *)sender {
1750
- NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
1751
- BOOL enabled = ![defaults boolForKey:HistoryEnabledKey];
1752
- [defaults setBool:enabled forKey:HistoryEnabledKey];
1753
- sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
1754
- self.quotaView.historyEnabled = enabled;
1755
- [self refreshUsage:nil];
1756
- }
1757
- - (NSString *)notificationKeyForTag:(NSInteger)tag {
1758
- if (tag == 1) return NotificationCompletionKey;
1759
- if (tag == 2) return NotificationFailureKey;
1760
- if (tag == 3) return NotificationApprovalKey;
1761
- return nil;
1762
- }
1763
- - (void)toggleNotification:(NSButton *)sender {
1764
- NSString *key = [self notificationKeyForTag:sender.tag];
1765
- if (!key) return;
1766
- NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
1767
- if ([defaults boolForKey:key]) {
1768
- [defaults setBool:NO forKey:key];
1769
- sender.state = NSControlStateValueOff;
1770
- return;
1771
- }
1772
- [UNUserNotificationCenter.currentNotificationCenter
1773
- requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound
1774
- completionHandler:^(BOOL granted, NSError *error) {
1775
- dispatch_async(dispatch_get_main_queue(), ^{
1776
- if (granted) {
1777
- [defaults setBool:YES forKey:key];
1778
- sender.state = NSControlStateValueOn;
1779
- } else {
1780
- sender.state = NSControlStateValueOff;
1781
- NSString *message = error.localizedDescription ?:
1782
- @"请在“系统设置 → 通知 → CC Pets”中允许通知后重试。";
1783
- [self showUpdateAlertWithTitle:@"无法启用系统通知" message:message];
1784
- }
1785
- });
1786
- }];
1787
- }
1788
- - (void)sendNotificationWithTitle:(NSString *)title body:(NSString *)body {
1789
- UNMutableNotificationContent *content = [UNMutableNotificationContent new];
1790
- content.title = title;
1791
- content.body = body;
1792
- content.sound = UNNotificationSound.defaultSound;
1793
- NSString *identifier = [@"cc-pets-" stringByAppendingString:NSUUID.UUID.UUIDString];
1794
- UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
1795
- content:content trigger:nil];
1796
- [UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:request
1797
- withCompletionHandler:nil];
1798
- }
1799
- - (void)notifyForRecord:(NSDictionary *)record {
1800
- NSString *event = record[@"event"];
1801
- NSString *provider = SanitizedShortString(record[@"provider"], 32);
1802
- if (provider.length == 0) provider = @"Agent";
1803
- NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
1804
- if ([event isEqualToString:@"PermissionRequest"] &&
1805
- [defaults boolForKey:NotificationApprovalKey]) {
1806
- [self sendNotificationWithTitle:@"等待审批"
1807
- body:[NSString stringWithFormat:@"%@ 正在等待操作。", provider]];
1808
- } else if ([event isEqualToString:@"StopFailure"] &&
1809
- [defaults boolForKey:NotificationFailureKey]) {
1810
- [self sendNotificationWithTitle:@"任务失败"
1811
- body:[NSString stringWithFormat:@"%@ 的任务执行失败。", provider]];
1812
- } else if (([event isEqualToString:@"Stop"] || [event isEqualToString:@"SessionEnd"]) &&
1813
- [defaults boolForKey:NotificationCompletionKey]) {
1814
- [self sendNotificationWithTitle:@"任务完成"
1815
- body:[NSString stringWithFormat:@"%@ 已完成当前任务。", provider]];
1816
- }
1817
- }
1818
- - (NSString *)statusTextForState:(NSString *)state tool:(NSString *)tool {
1819
- if ([state isEqualToString:@"starting"]) return @"正在启动";
1820
- if ([state isEqualToString:@"thinking"]) return @"正在思考";
1821
- if ([state isEqualToString:@"approval"]) return @"等待审批";
1822
- if ([state isEqualToString:@"subagent"]) return @"子 Agent 工作中";
1823
- if ([state isEqualToString:@"tool_completed"]) return @"操作已完成";
1824
- if ([state isEqualToString:@"tool_failed"]) return @"工具执行失败";
1825
- if ([state isEqualToString:@"completed"]) return @"任务已完成";
1826
- if ([state isEqualToString:@"failed"]) return @"任务失败";
1827
- if ([state isEqualToString:@"notification"]) return @"需要关注";
1828
- if ([state isEqualToString:@"tool"]) {
1829
- NSString *lower = tool.lowercaseString;
1830
- if ([lower containsString:@"bash"] || [lower containsString:@"exec"] ||
1831
- [lower containsString:@"shell"] || [lower containsString:@"terminal"]) return @"正在执行命令";
1832
- if ([lower containsString:@"patch"] || [lower containsString:@"edit"] ||
1833
- [lower containsString:@"write"]) return @"正在编辑文件";
1834
- if ([lower containsString:@"read"] || [lower containsString:@"search"] ||
1835
- [lower containsString:@"find"] || [lower containsString:@"grep"] ||
1836
- [lower containsString:@"glob"] || [lower containsString:@"web"] ||
1837
- [lower hasPrefix:@"mcp__"]) return @"正在查找资料";
1838
- if ([lower containsString:@"task"] || [lower containsString:@"agent"]) return @"子 Agent 工作中";
1839
- return @"正在使用工具";
1840
- }
1841
- return @"正在工作";
1842
- }
1843
- - (NSString *)statusDetailForState:(NSString *)state {
1844
- if ([state isEqualToString:@"starting"]) return @"正在准备当前会话…";
1845
- if ([state isEqualToString:@"thinking"]) return @"正在分析请求…";
1846
- if ([state isEqualToString:@"approval"]) return @"请回到终端确认操作。";
1847
- if ([state isEqualToString:@"subagent"]) return @"正在协调子 Agent。";
1848
- if ([state isEqualToString:@"tool"]) return @"正在调用工具…";
1849
- if ([state isEqualToString:@"tool_completed"]) return @"工具调用已完成。";
1850
- if ([state isEqualToString:@"tool_failed"]) return @"工具执行失败,请查看终端。";
1851
- if ([state isEqualToString:@"completed"]) return @"好的,当前任务已经完成。";
1852
- if ([state isEqualToString:@"failed"]) return @"任务失败,请回到终端查看详情。";
1853
- if ([state isEqualToString:@"notification"]) return @"有一条状态需要你关注。";
1854
- return @"正在处理当前任务。";
1855
- }
1856
- - (NSColor *)statusColorForState:(NSString *)state {
1857
- if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) {
1858
- return [NSColor colorWithRed:0.18 green:0.68 blue:0.35 alpha:1];
1859
- }
1860
- if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) {
1861
- return [NSColor colorWithRed:0.86 green:0.28 blue:0.28 alpha:1];
1862
- }
1863
- if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) {
1864
- return [NSColor colorWithRed:0.92 green:0.58 blue:0.12 alpha:1];
1865
- }
1866
- return [NSColor colorWithRed:0.33 green:0.53 blue:0.78 alpha:1];
1867
- }
1868
- - (NSString *)statusSymbolForState:(NSString *)state {
1869
- if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) return @"checkmark";
1870
- if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) return @"xmark";
1871
- if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) return @"exclamationmark";
1872
- return @"ellipsis";
1873
- }
1874
- - (void)updateStatusToggleAppearance {
1875
- if (!self.hasAgentStatus) return;
1876
- NSColor *stateColor = [self statusColorForState:self.lastStatusState];
1877
- if (self.statusBubbleExpanded) {
1878
- self.statusToggleButton.title = @"";
1879
- self.statusToggleButton.imagePosition = NSImageOnly;
1880
- NSString *symbol = self.statusBubbleAbove ? @"chevron.down" : @"chevron.up";
1881
- NSImage *image = [NSImage imageWithSystemSymbolName:symbol accessibilityDescription:@"折叠状态"];
1882
- self.statusToggleButton.image = [image imageWithSymbolConfiguration:
1883
- [NSImageSymbolConfiguration configurationWithPointSize:11 weight:NSFontWeightSemibold]];
1884
- self.statusToggleButton.contentTintColor = NSColor.whiteColor;
1885
- self.statusToggleGlass.layer.backgroundColor =
1886
- [NSColor colorWithWhite:0.16 alpha:0.54].CGColor;
1887
- } else {
1888
- self.statusToggleButton.image = nil;
1889
- self.statusToggleButton.imagePosition = NSNoImage;
1890
- self.statusToggleButton.title = [NSString stringWithFormat:@"%ld",
1891
- (long)MAX(1, self.liveClientCount)];
1892
- self.statusToggleButton.font = [NSFont systemFontOfSize:11 weight:NSFontWeightSemibold];
1893
- self.statusToggleButton.contentTintColor = NSColor.whiteColor;
1894
- self.statusToggleGlass.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.72].CGColor;
1895
- }
1896
- }
1897
- - (void)hideAgentStatus {
1898
- [self.statusPanel orderOut:nil];
1899
- [self.statusTogglePanel orderOut:nil];
1900
- self.hasAgentStatus = NO;
1901
- }
1902
- - (void)toggleAgentStatusBubble:(id)sender {
1903
- if (!self.hasAgentStatus) return;
1904
- self.statusBubbleExpanded = !self.statusBubbleExpanded;
1905
- [NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
1906
- forKey:StatusBubbleExpandedKey];
1907
- if (self.statusBubbleExpanded) {
1908
- [self.statusPanel orderFrontRegardless];
1909
- } else {
1910
- [self.statusPanel orderOut:nil];
1911
- }
1912
- [self positionAgentStatus];
1913
- [self updateStatusToggleAppearance];
1914
- [self.statusTogglePanel orderFrontRegardless];
1915
- }
1916
- - (void)showAgentStatusForRecord:(NSDictionary *)record {
1917
- [NSObject cancelPreviousPerformRequestsWithTarget:self
1918
- selector:@selector(hideAgentStatus) object:nil];
1919
- NSString *provider = SanitizedShortString(record[@"provider"], 32);
1920
- if (provider.length == 0) provider = @"Agent";
1921
- NSString *state = [record[@"state"] isKindOfClass:NSString.class]
1922
- ? record[@"state"] : NormalizedStateForEvent(record[@"event"], [record[@"failed"] boolValue]);
1923
- NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
1924
- self.hasAgentStatus = YES;
1925
- self.lastStatusState = state;
1926
- self.statusTitleLabel.stringValue = [NSString stringWithFormat:@"%@ · %@",
1927
- provider, [self statusTextForState:state tool:tool]];
1928
- self.statusDetailLabel.stringValue = [self statusDetailForState:state];
1929
- NSColor *stateColor = [self statusColorForState:state];
1930
- self.statusIconButton.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.28].CGColor;
1931
- NSImage *icon = [NSImage imageWithSystemSymbolName:[self statusSymbolForState:state]
1932
- accessibilityDescription:[self statusTextForState:state tool:tool]];
1933
- self.statusIconButton.image = [icon imageWithSymbolConfiguration:
1934
- [NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightBold]];
1935
- self.statusIconButton.contentTintColor = [stateColor blendedColorWithFraction:0.18
1936
- ofColor:NSColor.blackColor] ?: stateColor;
1937
- [self positionAgentStatus];
1938
- if (self.statusBubbleExpanded) [self.statusPanel orderFrontRegardless];
1939
- else [self.statusPanel orderOut:nil];
1940
- [self updateStatusToggleAppearance];
1941
- [self.statusTogglePanel orderFrontRegardless];
1942
- [self.panel orderFrontRegardless];
1943
- [self performSelector:@selector(hideAgentStatus)
1944
- withObject:nil afterDelay:AgentStatusInactivityInterval];
1945
- [self notifyForRecord:record];
1946
- }
1947
- - (NSDictionary *)petManifestInDirectory:(NSString *)directory {
1948
- NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
1949
- NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
1950
- if (!jsonData) return @{};
1951
- id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
1952
- return [json isKindOfClass:NSDictionary.class] ? json : @{};
1953
- }
1954
- - (NSInteger)spriteVersionInDirectory:(NSString *)directory fallbackDirectory:(NSString *)fallbackDirectory {
1955
- NSArray<NSString *> *directories = fallbackDirectory.length > 0
1956
- ? @[directory, fallbackDirectory]
1957
- : @[directory];
1958
- for (NSString *candidate in directories) {
1959
- id value = [self petManifestInDirectory:candidate][@"spriteVersionNumber"];
1960
- if (![value isKindOfClass:NSNumber.class]) continue;
1961
- NSInteger version = [value integerValue];
1962
- if (version == 1 || version == 2) return version;
1963
- }
1964
- return 1;
1965
- }
1966
- - (NSInteger)spriteRowCountForVersion:(NSInteger)version {
1967
- return version == 2 ? 11 : 9;
1968
- }
1969
- - (NSString *)spritePathInDirectory:(NSString *)directory {
1970
- NSString *configuredName = nil;
1971
- id value = [self petManifestInDirectory:directory][@"spritesheetPath"];
1972
- if ([value isKindOfClass:NSString.class]) configuredName = [value lastPathComponent];
1973
- NSMutableArray<NSString *> *names = [NSMutableArray array];
1974
- if (configuredName.length > 0) [names addObject:configuredName];
1975
- [names addObjectsFromArray:@[@"spritesheet.webp", @"spritesheet.png"]];
1976
- for (NSString *name in names) {
1977
- NSString *path = [directory stringByAppendingPathComponent:name];
1978
- BOOL isDirectory = NO;
1979
- if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && !isDirectory) return path;
1980
- }
1981
- return nil;
1982
- }
1983
- - (NSArray<NSString *> *)petDirectoryNamesAtPath:(NSString *)root {
1984
- NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:root error:nil] ?: @[];
1985
- NSMutableArray<NSString *> *directories = [NSMutableArray array];
1986
- for (NSString *entry in entries) {
1987
- if ([entry hasPrefix:@"."]) continue;
1988
- BOOL isDirectory = NO;
1989
- NSString *path = [root stringByAppendingPathComponent:entry];
1990
- if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory) {
1991
- [directories addObject:entry];
1992
- }
1993
- }
1994
- return [directories sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
1995
- }
1996
- - (NSArray<NSDictionary *> *)discoverPetOptions {
1997
- NSString *home = NSHomeDirectory();
1998
- NSString *petdexRoot = [home stringByAppendingPathComponent:@".petdex/pets"];
1999
- NSString *codexRoot = [home stringByAppendingPathComponent:@".codex/pets"];
2000
- NSMutableArray<NSDictionary *> *result = [NSMutableArray array];
2001
- NSMutableSet<NSString *> *externalNames = [NSMutableSet set];
2002
-
2003
- for (NSString *name in [self petDirectoryNamesAtPath:petdexRoot]) {
2004
- NSString *petdexDirectory = [petdexRoot stringByAppendingPathComponent:name];
2005
- NSString *codexDirectory = [codexRoot stringByAppendingPathComponent:name];
2006
- NSString *path = [self spritePathInDirectory:petdexDirectory];
2007
- if (!path) path = [self spritePathInDirectory:codexDirectory];
2008
- if (!path) continue;
2009
- NSInteger version = [self spriteVersionInDirectory:petdexDirectory fallbackDirectory:codexDirectory];
2010
- [result addObject:@{
2011
- @"id": [@"external:" stringByAppendingString:name],
2012
- @"name": name,
2013
- @"path": path,
2014
- @"spriteVersionNumber": @(version),
2015
- @"spriteRowCount": @([self spriteRowCountForVersion:version])
2016
- }];
2017
- [externalNames addObject:name];
2018
- }
2019
- for (NSString *name in [self petDirectoryNamesAtPath:codexRoot]) {
2020
- if ([externalNames containsObject:name]) continue;
2021
- NSString *codexDirectory = [codexRoot stringByAppendingPathComponent:name];
2022
- NSString *path = [self spritePathInDirectory:codexDirectory];
2023
- if (!path) continue;
2024
- NSInteger version = [self spriteVersionInDirectory:codexDirectory fallbackDirectory:nil];
2025
- [result addObject:@{
2026
- @"id": [@"external:" stringByAppendingString:name],
2027
- @"name": name,
2028
- @"path": path,
2029
- @"spriteVersionNumber": @(version),
2030
- @"spriteRowCount": @([self spriteRowCountForVersion:version])
2031
- }];
2032
- [externalNames addObject:name];
2033
- }
2034
-
2035
- NSArray<NSString *> *bundled = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
2036
- for (NSString *fileName in [bundled sortedArrayUsingSelector:@selector(localizedStandardCompare:)]) {
2037
- NSString *extension = fileName.pathExtension.lowercaseString;
2038
- if (![extension isEqualToString:@"webp"] && ![extension isEqualToString:@"png"]) continue;
2039
- [result addObject:@{
2040
- @"id": [@"builtin:" stringByAppendingString:fileName],
2041
- @"name": fileName.stringByDeletingPathExtension,
2042
- @"path": [self.binaryDirectory stringByAppendingPathComponent:fileName],
2043
- @"spriteVersionNumber": @1,
2044
- @"spriteRowCount": @9
2045
- }];
2046
- }
2047
- return result;
2048
- }
2049
- - (NSDictionary *)petOptionWithID:(NSString *)petID inOptions:(NSArray<NSDictionary *> *)options {
2050
- for (NSDictionary *option in options) if ([option[@"id"] isEqualToString:petID]) return option;
2051
- return nil;
2052
- }
2053
- - (NSArray<NSDictionary *> *)waitForPetOptions {
2054
- while (YES) {
2055
- NSArray<NSDictionary *> *options = [self discoverPetOptions];
2056
- if (options.count > 0) return options;
2057
-
2058
- [NSApp activateIgnoringOtherApps:YES];
2059
- NSAlert *alert = [NSAlert new];
2060
- alert.messageText = @"没有找到桌宠素材";
2061
- alert.informativeText = @"请将 PNG 或 WebP 精灵图放入 ~/.petdex/pets/<名称>/ 或 "
2062
- @"~/.codex/pets/<名称>/,也可以通过 PetDex 安装。完成后点击“重新扫描”。";
2063
- [alert addButtonWithTitle:@"重新扫描"];
2064
- [alert addButtonWithTitle:@"打开素材目录"];
2065
- [alert addButtonWithTitle:@"退出"];
2066
- NSModalResponse response = [alert runModal];
2067
- if (response == NSAlertSecondButtonReturn) {
2068
- NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@".petdex/pets"];
2069
- [NSFileManager.defaultManager createDirectoryAtPath:directory
2070
- withIntermediateDirectories:YES attributes:nil error:nil];
2071
- [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:directory]];
2072
- } else if (response == NSAlertThirdButtonReturn) {
2073
- return @[];
2074
- }
2075
- }
2076
- }
2077
- - (void)applicationDidFinishLaunching:(NSNotification *)notification {
2078
- self.managedByCLI = [NSProcessInfo.processInfo.arguments containsObject:@"--managed"];
2079
- NSString *binaryDir = NSProcessInfo.processInfo.arguments.firstObject.stringByStandardizingPath.stringByDeletingLastPathComponent;
2080
- NSBundle *mainBundle = NSBundle.mainBundle;
2081
- BOOL runsFromAppBundle = [mainBundle.bundlePath.pathExtension.lowercaseString isEqualToString:@"app"];
2082
- self.binaryDirectory = runsFromAppBundle && mainBundle.resourcePath.length > 0
2083
- ? mainBundle.resourcePath
2084
- : binaryDir;
2085
- NSArray<NSDictionary *> *petOptions = [self waitForPetOptions];
2086
- if (petOptions.count == 0) {
2087
- [NSApp terminate:nil];
2088
- return;
2089
- }
2090
- NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
2091
- [defaults registerDefaults:@{StatusBubbleExpandedKey: @YES}];
2092
- if (![defaults boolForKey:StatusBubblePreferenceV2Key]) {
2093
- [defaults setBool:YES forKey:StatusBubbleExpandedKey];
2094
- [defaults setBool:YES forKey:StatusBubblePreferenceV2Key];
2095
- }
2096
- self.statusBubbleExpanded = [defaults boolForKey:StatusBubbleExpandedKey];
2097
- NSString *selected = [defaults stringForKey:@"CCPetsSelectedSprite"];
2098
- if (selected.length == 0) {
2099
- NSDictionary *legacyDefaults = [defaults persistentDomainForName:@"com.universewang.codex-pet"];
2100
- NSString *legacySelected = [legacyDefaults[@"CodexPetSelectedSprite"] isKindOfClass:NSString.class]
2101
- ? legacyDefaults[@"CodexPetSelectedSprite"] : nil;
2102
- if (legacySelected.length > 0) {
2103
- selected = legacySelected;
2104
- [defaults setObject:selected forKey:@"CCPetsSelectedSprite"];
2105
- }
2106
- }
2107
- if (selected.length > 0 && ![selected containsString:@":"]) selected = [@"builtin:" stringByAppendingString:selected];
2108
- NSDictionary *selectedOption = [self petOptionWithID:selected inOptions:petOptions] ?: petOptions.firstObject;
2109
- selected = selectedOption[@"id"];
2110
- NSString *spritePath = selectedOption[@"path"];
2111
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:spritePath];
2112
- if (!image) {
2113
- fprintf(stderr, "无法读取桌宠素材: %s\n", spritePath.UTF8String);
2114
- [NSApp terminate:nil];
2115
- return;
2116
- }
2117
-
2118
- NSSize size = NSMakeSize(230, 170);
2119
- self.panel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, size.width, size.height)
2120
- styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
2121
- backing:NSBackingStoreBuffered defer:NO];
2122
- self.panel.opaque = NO;
2123
- self.panel.backgroundColor = NSColor.clearColor;
2124
- self.panel.hasShadow = NO;
2125
- self.panel.level = NSFloatingWindowLevel;
2126
- self.panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
2127
- self.panel.movableByWindowBackground = YES;
2128
- self.panel.hidesOnDeactivate = NO;
2129
-
2130
- NSView *root = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
2131
- self.panel.contentView = root;
2132
- NSInteger spriteRowCount = [selectedOption[@"spriteRowCount"] integerValue] ?: 9;
2133
- self.petView = [[PetView alloc] initWithFrame:NSMakeRect(43, 0, 144, 150)
2134
- sheet:image rowCount:spriteRowCount];
2135
- self.petView.currentPetID = selected;
2136
- __weak typeof(self) weakSelf = self;
2137
- self.petView.pocketHoverChanged = ^(BOOL hovering) {
2138
- weakSelf.pocketHovering = hovering;
2139
- if (hovering) [weakSelf showQuotaDashboard];
2140
- else [weakSelf scheduleQuotaDashboardHide];
2141
- };
2142
- self.petView.petOptionsRequested = ^NSArray<NSDictionary *> *{
2143
- return [weakSelf discoverPetOptions] ?: @[];
2144
- };
2145
- self.petView.switchPetRequested = ^(NSString *petID) {
2146
- [weakSelf switchPetToID:petID];
2147
- };
2148
- self.petView.positionChanged = ^{
2149
- if (weakSelf.quotaPanel.isVisible) [weakSelf positionQuotaDashboard];
2150
- if (weakSelf.statusPanel.isVisible || weakSelf.statusTogglePanel.isVisible) {
2151
- [weakSelf positionAgentStatus];
2152
- }
2153
- };
2154
- self.petView.dragStateChanged = ^(BOOL dragging) {
2155
- weakSelf.petDragging = dragging;
2156
- if (!dragging) [weakSelf scheduleQuotaDashboardHide];
2157
- };
2158
- [root addSubview:self.petView];
2159
-
2160
- NSSize statusGlassSize = NSMakeSize(340, 58);
2161
- NSSize statusSize = NSMakeSize(statusGlassSize.width + 12, statusGlassSize.height + 12);
2162
- self.statusPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0,
2163
- statusSize.width, statusSize.height)
2164
- styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
2165
- backing:NSBackingStoreBuffered defer:NO];
2166
- self.statusPanel.opaque = NO;
2167
- self.statusPanel.backgroundColor = NSColor.clearColor;
2168
- self.statusPanel.hasShadow = NO;
2169
- self.statusPanel.ignoresMouseEvents = YES;
2170
- self.statusPanel.level = NSFloatingWindowLevel;
2171
- self.statusPanel.collectionBehavior =
2172
- NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
2173
- self.statusPanel.hidesOnDeactivate = NO;
2174
- NSView *statusRoot = [[NSView alloc] initWithFrame:NSMakeRect(
2175
- 0, 0, statusSize.width, statusSize.height)];
2176
- NSView *statusShadow = [[NSView alloc] initWithFrame:NSMakeRect(
2177
- 6, 6, statusGlassSize.width, statusGlassSize.height)];
2178
- statusShadow.wantsLayer = YES;
2179
- statusShadow.layer.backgroundColor = [NSColor colorWithWhite:0 alpha:0.01].CGColor;
2180
- statusShadow.layer.cornerRadius = statusGlassSize.height / 2.0;
2181
- statusShadow.layer.cornerCurve = kCACornerCurveContinuous;
2182
- statusShadow.layer.shadowColor = NSColor.blackColor.CGColor;
2183
- statusShadow.layer.shadowOpacity = 0.24;
2184
- statusShadow.layer.shadowRadius = 8;
2185
- statusShadow.layer.shadowOffset = NSMakeSize(0, -3);
2186
- CGPathRef statusShadowPath = CGPathCreateWithRoundedRect(
2187
- statusShadow.bounds, statusGlassSize.height / 2.0,
2188
- statusGlassSize.height / 2.0, NULL);
2189
- statusShadow.layer.shadowPath = statusShadowPath;
2190
- CGPathRelease(statusShadowPath);
2191
- [statusRoot addSubview:statusShadow];
2192
-
2193
- self.statusGlass = [[NSVisualEffectView alloc]
2194
- initWithFrame:NSMakeRect(6, 6, statusGlassSize.width, statusGlassSize.height)];
2195
- self.statusGlass.material = NSVisualEffectMaterialPopover;
2196
- self.statusGlass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
2197
- self.statusGlass.state = NSVisualEffectStateActive;
2198
- self.statusGlass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
2199
- self.statusGlass.wantsLayer = YES;
2200
- self.statusGlass.layer.cornerRadius = statusGlassSize.height / 2.0;
2201
- self.statusGlass.layer.cornerCurve = kCACornerCurveContinuous;
2202
- self.statusGlass.layer.masksToBounds = YES;
2203
- self.statusGlass.layer.borderWidth = 1;
2204
- self.statusGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
2205
-
2206
- self.statusTitleLabel = [NSTextField labelWithString:@""];
2207
- self.statusTitleLabel.frame = NSMakeRect(20, 30, statusGlassSize.width - 80, 18);
2208
- self.statusTitleLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold];
2209
- self.statusTitleLabel.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
2210
- self.statusTitleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
2211
- [self.statusGlass addSubview:self.statusTitleLabel];
2212
-
2213
- self.statusDetailLabel = [NSTextField labelWithString:@""];
2214
- self.statusDetailLabel.frame = NSMakeRect(20, 12, statusGlassSize.width - 80, 17);
2215
- self.statusDetailLabel.font = [NSFont systemFontOfSize:12 weight:NSFontWeightRegular];
2216
- self.statusDetailLabel.textColor = [NSColor colorWithWhite:0.34 alpha:0.88];
2217
- self.statusDetailLabel.lineBreakMode = NSLineBreakByTruncatingTail;
2218
- [self.statusGlass addSubview:self.statusDetailLabel];
2219
-
2220
- self.statusIconButton = [[NSButton alloc] initWithFrame:NSMakeRect(
2221
- statusGlassSize.width - 48, 12, 34, 34)];
2222
- self.statusIconButton.bordered = NO;
2223
- self.statusIconButton.imagePosition = NSImageOnly;
2224
- self.statusIconButton.wantsLayer = YES;
2225
- self.statusIconButton.layer.cornerRadius = 17;
2226
- self.statusIconButton.layer.masksToBounds = YES;
2227
- [self.statusGlass addSubview:self.statusIconButton];
2228
- [statusRoot addSubview:self.statusGlass];
2229
- self.statusPanel.contentView = statusRoot;
2230
-
2231
- NSSize toggleSize = NSMakeSize(28, 28);
2232
- self.statusTogglePanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0,
2233
- toggleSize.width, toggleSize.height)
2234
- styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
2235
- backing:NSBackingStoreBuffered defer:NO];
2236
- self.statusTogglePanel.opaque = NO;
2237
- self.statusTogglePanel.backgroundColor = NSColor.clearColor;
2238
- self.statusTogglePanel.hasShadow = YES;
2239
- self.statusTogglePanel.ignoresMouseEvents = NO;
2240
- self.statusTogglePanel.level = NSFloatingWindowLevel;
2241
- self.statusTogglePanel.collectionBehavior =
2242
- NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
2243
- self.statusTogglePanel.hidesOnDeactivate = NO;
2244
- self.statusToggleGlass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(
2245
- 0, 0, toggleSize.width, toggleSize.height)];
2246
- self.statusToggleGlass.material = NSVisualEffectMaterialHUDWindow;
2247
- self.statusToggleGlass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
2248
- self.statusToggleGlass.state = NSVisualEffectStateActive;
2249
- self.statusToggleGlass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
2250
- self.statusToggleGlass.wantsLayer = YES;
2251
- self.statusToggleGlass.layer.cornerRadius = 14;
2252
- self.statusToggleGlass.layer.masksToBounds = YES;
2253
- self.statusToggleGlass.layer.borderWidth = 1;
2254
- self.statusToggleGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.24].CGColor;
2255
- self.statusToggleButton = [[NSButton alloc] initWithFrame:self.statusToggleGlass.bounds];
2256
- self.statusToggleButton.bordered = NO;
2257
- self.statusToggleButton.imagePosition = NSImageOnly;
2258
- self.statusToggleButton.target = self;
2259
- self.statusToggleButton.action = @selector(toggleAgentStatusBubble:);
2260
- [self.statusToggleGlass addSubview:self.statusToggleButton];
2261
- self.statusTogglePanel.contentView = self.statusToggleGlass;
2262
-
2263
- NSSize quotaSize = NSMakeSize(QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale);
2264
- self.quotaPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)
2265
- styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
2266
- backing:NSBackingStoreBuffered defer:NO];
2267
- self.quotaPanel.opaque = NO;
2268
- self.quotaPanel.backgroundColor = NSColor.clearColor;
2269
- self.quotaPanel.hasShadow = YES;
2270
- self.quotaPanel.acceptsMouseMovedEvents = YES;
2271
- self.quotaPanel.ignoresMouseEvents = NO;
2272
- self.quotaPanel.level = NSFloatingWindowLevel;
2273
- self.quotaPanel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
2274
- self.quotaPanel.hidesOnDeactivate = NO;
2275
- NSView *quotaRoot = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
2276
- NSVisualEffectView *glass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(0, 0,
2277
- quotaSize.width, quotaSize.height)];
2278
- glass.material = NSVisualEffectMaterialUnderWindowBackground;
2279
- glass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
2280
- glass.state = NSVisualEffectStateActive;
2281
- glass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
2282
- glass.wantsLayer = YES;
2283
- glass.layer.cornerRadius = 13;
2284
- glass.layer.masksToBounds = YES;
2285
- [quotaRoot addSubview:glass];
2286
- self.quotaView = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
2287
- self.quotaView.historyEnabled = [defaults boolForKey:HistoryEnabledKey];
2288
- self.quotaView.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
2289
- self.quotaView.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
2290
- self.quotaView.hoverChanged = ^(BOOL hovering) {
2291
- weakSelf.dashboardHovering = hovering;
2292
- if (!hovering) [weakSelf scheduleQuotaDashboardHide];
2293
- };
2294
- self.quotaView.refreshRequested = ^{
2295
- [weakSelf refreshUsage:nil];
2296
- };
2297
- [quotaRoot addSubview:self.quotaView];
2298
- self.quotaPanel.contentView = quotaRoot;
2299
-
2300
- NSScreen *screen = NSScreen.mainScreen;
2301
- NSRect visible = screen.visibleFrame;
2302
- [self.panel setFrameOrigin:NSMakePoint(NSMaxX(visible) - size.width - 24, NSMinY(visible) + 18)];
2303
- [self.panel orderFrontRegardless];
2304
- self.codexUsageReader = [CodexUsageReader new];
2305
- self.agentEventPartialLine = [NSMutableData data];
2306
- [self refreshUsage:nil];
2307
- if ([NSProcessInfo.processInfo.arguments containsObject:@"--preview-dashboard"]) {
2308
- self.pocketHovering = YES;
2309
- [self showQuotaDashboard];
2310
- }
2311
- [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refreshUsage:) userInfo:nil repeats:YES];
2312
- [self refreshClientLifecycle:nil];
2313
- [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshClientLifecycle:) userInfo:nil repeats:YES];
2314
- [self startAgentEventReader];
2315
- [NSTimer scheduledTimerWithTimeInterval:5 target:self
2316
- selector:@selector(ensureAgentEventReader:) userInfo:nil repeats:YES];
2317
- }
2318
- - (void)showQuotaDashboard {
2319
- [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
2320
- [self refreshUsage:nil];
2321
- [self positionQuotaDashboard];
2322
- [self.quotaPanel orderFrontRegardless];
2323
- [self.panel orderFrontRegardless];
2324
- }
2325
- - (void)positionQuotaDashboard {
2326
- NSRect petFrame = self.panel.frame;
2327
- NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
2328
- NSSize size = self.quotaPanel.frame.size;
2329
- CGFloat x = NSMinX(petFrame) - size.width + 55;
2330
- CGFloat y = NSMinY(petFrame) + 112;
2331
- x = fmax(NSMinX(visible) + 12, fmin(x, NSMaxX(visible) - size.width - 12));
2332
- y = fmax(NSMinY(visible) + 12, fmin(y, NSMaxY(visible) - size.height - 12));
2333
- [self.quotaPanel setFrameOrigin:NSMakePoint(x, y)];
2334
- }
2335
- - (void)positionAgentStatus {
2336
- NSRect petFrame = self.panel.frame;
2337
- NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
2338
- NSSize size = self.statusPanel.frame.size;
2339
- CGFloat x = NSMidX(petFrame) - size.width / 2.0;
2340
- CGFloat aboveY = NSMaxY(petFrame) + 8;
2341
- CGFloat belowY = NSMinY(petFrame) - size.height - 8;
2342
- BOOL aboveFits = aboveY + size.height <= NSMaxY(visible) - 10;
2343
- BOOL belowFits = belowY >= NSMinY(visible) + 10;
2344
- self.statusBubbleAbove = aboveFits || !belowFits;
2345
- CGFloat y = self.statusBubbleAbove ? aboveY : belowY;
2346
- x = fmax(NSMinX(visible) + 10, fmin(x, NSMaxX(visible) - size.width - 10));
2347
- y = fmax(NSMinY(visible) + 10, fmin(y, NSMaxY(visible) - size.height - 10));
2348
- [self.statusPanel setFrameOrigin:NSMakePoint(x, y)];
2349
-
2350
- NSSize toggleSize = self.statusTogglePanel.frame.size;
2351
- NSRect petViewFrame = self.petView.frame;
2352
- CGFloat toggleX = NSMinX(petFrame) + NSMinX(petViewFrame) +
2353
- NSWidth(petViewFrame) * 0.82;
2354
- CGFloat toggleY = NSMinY(petFrame) + NSMinY(petViewFrame) +
2355
- NSHeight(petViewFrame) * 0.70;
2356
- toggleX = fmax(NSMinX(visible) + 8,
2357
- fmin(toggleX, NSMaxX(visible) - toggleSize.width - 8));
2358
- toggleY = fmax(NSMinY(visible) + 8,
2359
- fmin(toggleY, NSMaxY(visible) - toggleSize.height - 8));
2360
- [self.statusTogglePanel setFrameOrigin:NSMakePoint(toggleX, toggleY)];
2361
- [self updateStatusToggleAppearance];
2362
- }
2363
- - (void)scheduleQuotaDashboardHide {
2364
- [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
2365
- [self performSelector:@selector(hideQuotaDashboardIfNeeded) withObject:nil afterDelay:0.28];
2366
- }
2367
- - (void)hideQuotaDashboardIfNeeded {
2368
- if (!self.pocketHovering && !self.dashboardHovering && !self.petDragging) [self.quotaPanel orderOut:nil];
2369
- }
2370
- - (void)switchPetToID:(NSString *)petID {
2371
- NSArray<NSDictionary *> *options = [self discoverPetOptions];
2372
- NSDictionary *option = [self petOptionWithID:petID inOptions:options];
2373
- if (!option) return;
2374
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:option[@"path"]];
2375
- if (!image) return;
2376
- NSInteger spriteRowCount = [option[@"spriteRowCount"] integerValue] ?: 9;
2377
- [self.petView applySheet:image petID:petID rowCount:spriteRowCount];
2378
- [NSUserDefaults.standardUserDefaults setObject:petID forKey:@"CCPetsSelectedSprite"];
2379
- }
2380
- - (void)prepareAgentEventReader {
2381
- NSString *path = AgentEventPath();
2382
- NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
2383
- unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
2384
- if (self.agentEventReaderInitialized) {
2385
- if (size < self.agentEventOffset) {
2386
- self.agentEventOffset = 0;
2387
- [self.agentEventPartialLine setLength:0];
2388
- }
2389
- [self readNewAgentEvents];
2390
- return;
2391
- }
2392
- self.agentEventReaderInitialized = YES;
2393
- self.agentEventOffset = size;
2394
- if (size > 0) {
2395
- NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2396
- unsigned long long start = size > 65536 ? size - 65536 : 0;
2397
- [handle seekToFileOffset:start];
2398
- NSData *recent = [handle readDataToEndOfFile];
2399
- [handle closeFile];
2400
- [self processAgentEventData:recent ignoreFirstPartial:start > 0 recentOnly:YES];
2401
- }
2402
- }
2403
- - (void)consumeAgentEventData:(NSData *)data {
2404
- if (data.length == 0) return;
2405
- [self.agentEventPartialLine appendData:data];
2406
- const uint8_t *bytes = self.agentEventPartialLine.bytes;
2407
- NSUInteger lineStart = 0;
2408
- for (NSUInteger index = 0; index < self.agentEventPartialLine.length; index++) {
2409
- if (bytes[index] != '\n') continue;
2410
- NSData *lineData = [self.agentEventPartialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
2411
- [self processAgentEventData:lineData ignoreFirstPartial:NO recentOnly:NO];
2412
- lineStart = index + 1;
2413
- }
2414
- if (lineStart > 0) {
2415
- NSData *remainder = [self.agentEventPartialLine subdataWithRange:
2416
- NSMakeRange(lineStart, self.agentEventPartialLine.length - lineStart)];
2417
- self.agentEventPartialLine = [remainder mutableCopy];
2418
- }
2419
- if (self.agentEventPartialLine.length > 1024 * 1024) [self.agentEventPartialLine setLength:0];
2420
- }
2421
- - (void)processAgentEventData:(NSData *)data ignoreFirstPartial:(BOOL)ignoreFirstPartial recentOnly:(BOOL)recentOnly {
2422
- NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
2423
- if (!text) return;
2424
- NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
2425
- NSTimeInterval cutoff = [NSDate.date timeIntervalSince1970] - 5;
2426
- for (NSUInteger index = 0; index < lines.count; index++) {
2427
- if (ignoreFirstPartial && index == 0) continue;
2428
- NSData *lineData = [lines[index] dataUsingEncoding:NSUTF8StringEncoding];
2429
- if (lineData.length == 0) continue;
2430
- NSDictionary *record = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
2431
- if (![record isKindOfClass:NSDictionary.class]) continue;
2432
- if (recentOnly && [record[@"timestamp"] doubleValue] < cutoff) continue;
2433
- NSString *event = record[@"event"];
2434
- NSString *tool = record[@"tool"] ?: @"";
2435
- if ([event isKindOfClass:NSString.class]) {
2436
- [self.petView handleAgentEvent:event tool:tool failed:[record[@"failed"] boolValue]];
2437
- [self showAgentStatusForRecord:record];
2438
- }
2439
- }
2440
- }
2441
- - (void)readNewAgentEvents {
2442
- NSString *path = AgentEventPath();
2443
- NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
2444
- unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
2445
- if (size < self.agentEventOffset) self.agentEventOffset = 0;
2446
- if (size == self.agentEventOffset) return;
2447
- NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2448
- if (!handle) return;
2449
- unsigned long long start = self.agentEventOffset;
2450
- [handle seekToFileOffset:start];
2451
- NSData *data = [handle readDataToEndOfFile];
2452
- [handle closeFile];
2453
- self.agentEventOffset = start + data.length;
2454
- [self consumeAgentEventData:data];
2455
- }
2456
- - (void)startAgentEventReader {
2457
- if (self.agentEventSource) return;
2458
- NSString *path = AgentEventPath();
2459
- [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
2460
- withIntermediateDirectories:YES attributes:nil error:nil];
2461
- int creator = open(path.fileSystemRepresentation, O_CREAT | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR);
2462
- if (creator >= 0) close(creator);
2463
- int descriptor = open(path.fileSystemRepresentation, O_EVTONLY | O_CLOEXEC);
2464
- if (descriptor < 0) return;
2465
- dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
2466
- DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
2467
- DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE,
2468
- dispatch_get_main_queue());
2469
- if (!source) {
2470
- close(descriptor);
2471
- return;
2472
- }
2473
- self.agentEventSource = source;
2474
- __weak typeof(self) weakSelf = self;
2475
- dispatch_source_set_event_handler(source, ^{
2476
- typeof(self) strongSelf = weakSelf;
2477
- if (!strongSelf) return;
2478
- dispatch_source_t currentSource = strongSelf.agentEventSource;
2479
- if (!currentSource) return;
2480
- unsigned long flags = dispatch_source_get_data(currentSource);
2481
- [strongSelf readNewAgentEvents];
2482
- if (flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE)) {
2483
- strongSelf.agentEventSource = nil;
2484
- dispatch_source_cancel(currentSource);
2485
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
2486
- dispatch_get_main_queue(), ^{ [weakSelf startAgentEventReader]; });
2487
- }
2488
- });
2489
- dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
2490
- dispatch_resume(source);
2491
- [self prepareAgentEventReader];
2492
- }
2493
- - (void)ensureAgentEventReader:(id)sender {
2494
- if (!self.agentEventSource) [self startAgentEventReader];
2495
- }
2496
- - (void)refreshClientLifecycle:(id)sender {
2497
- NSString *clientName = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
2498
- NSString *clientDirectory = [PetStateDirectory() stringByAppendingPathComponent:clientName];
2499
- NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
2500
- NSInteger liveClients = 0;
2501
- for (NSString *entry in entries) {
2502
- pid_t pid = (pid_t)entry.intValue;
2503
- BOOL alive = pid > 1 && (kill(pid, 0) == 0 || errno == EPERM);
2504
- if (alive) {
2505
- liveClients += 1;
2506
- } else {
2507
- NSString *stale = [clientDirectory stringByAppendingPathComponent:entry];
2508
- [NSFileManager.defaultManager removeItemAtPath:stale error:nil];
2509
- }
2510
- }
2511
- self.liveClientCount = liveClients;
2512
- if (self.statusTogglePanel.isVisible && !self.statusBubbleExpanded) {
2513
- [self updateStatusToggleAppearance];
2514
- }
2515
- // 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
2516
- // Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
2517
- if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
2518
- }
2519
- - (void)refreshUsage:(id)sender {
2520
- self.quotaView.codexUsage = [self.codexUsageReader refresh];
2521
- self.quotaView.claudeUsage = LatestClaudeUsage();
2522
- RecordQuotaHistory(self.quotaView.codexUsage, self.quotaView.claudeUsage);
2523
- self.quotaView.codexHistory = QuotaHistorySeries(@"codex");
2524
- self.quotaView.claudeHistory = QuotaHistorySeries(@"claude");
2525
- self.quotaView.needsDisplay = YES;
2526
- }
2527
- - (void)applicationWillTerminate:(NSNotification *)notification {
2528
- if (self.agentEventSource) {
2529
- dispatch_source_cancel(self.agentEventSource);
2530
- self.agentEventSource = nil;
2531
- }
2532
- }
2533
- @end
2534
-
2535
15
  int main(int argc, const char *argv[]) {
2536
16
  @autoreleasepool {
2537
17
  if (argc > 1 && (strcmp(argv[1], "--version") == 0 ||
@@ -2560,6 +40,8 @@ int main(int argc, const char *argv[]) {
2560
40
  if (argc > 1 && (strcmp(argv[1], "--provider-event") == 0 ||
2561
41
  strcmp(argv[1], "provider-event") == 0)) return RecordProviderEvent();
2562
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);
2563
45
  if (argc > 1 && strcmp(argv[1], "--history") == 0) {
2564
46
  NSData *json = [NSJSONSerialization dataWithJSONObject:QuotaHistoryDocument()
2565
47
  options:NSJSONWritingPrettyPrinted error:nil];
@@ -2595,6 +77,7 @@ int main(int argc, const char *argv[]) {
2595
77
  NSString *lockPath = [PetStateDirectory() stringByAppendingPathComponent:lockName];
2596
78
  int lock = open(lockPath.fileSystemRepresentation, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
2597
79
  if (lock < 0 || flock(lock, LOCK_EX | LOCK_NB) != 0) return EXIT_SUCCESS;
80
+ PruneStaleRuntimeState();
2598
81
 
2599
82
  NSApplication *app = NSApplication.sharedApplication;
2600
83
  AppDelegate *delegate = [AppDelegate new];