cc-pets 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1073 @@
1
+ #import <Cocoa/Cocoa.h>
2
+ #import <sys/file.h>
3
+ #import <sys/stat.h>
4
+ #import <signal.h>
5
+
6
+ static NSString *PetStateDirectory(void) {
7
+ NSString *override = NSProcessInfo.processInfo.environment[@"CODEX_PET_STATE_DIR"];
8
+ if (override.length > 0) return override.stringByStandardizingPath;
9
+ return NSTemporaryDirectory();
10
+ }
11
+
12
+ static NSString *AgentEventPath(void) {
13
+ NSString *name = [NSString stringWithFormat:@"codex-pet-%u-agent-events.ndjson", getuid()];
14
+ return [PetStateDirectory() stringByAppendingPathComponent:name];
15
+ }
16
+
17
+ static NSString *ClaudeUsagePath(void) {
18
+ NSString *name = [NSString stringWithFormat:@"codex-pet-%u-claude-usage.json", getuid()];
19
+ return [PetStateDirectory() stringByAppendingPathComponent:name];
20
+ }
21
+
22
+ static int RecordClaudeUsage(void) {
23
+ NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
24
+ NSDictionary *payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
25
+ NSDictionary *limits = [payload[@"rate_limits"] isKindOfClass:NSDictionary.class] ? payload[@"rate_limits"] : nil;
26
+ if (!limits) return EXIT_SUCCESS;
27
+ NSData *json = [NSJSONSerialization dataWithJSONObject:limits options:0 error:nil];
28
+ if (!json) return EXIT_SUCCESS;
29
+ if (![json writeToFile:ClaudeUsagePath() options:NSDataWritingAtomic error:nil]) return EXIT_SUCCESS;
30
+ chmod(ClaudeUsagePath().fileSystemRepresentation, S_IRUSR | S_IWUSR);
31
+ return EXIT_SUCCESS;
32
+ }
33
+
34
+ static NSDictionary *LatestClaudeUsage(void) {
35
+ NSData *data = [NSData dataWithContentsOfFile:ClaudeUsagePath()];
36
+ NSDictionary *limits = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
37
+ if (![limits isKindOfClass:NSDictionary.class]) return nil;
38
+ id fiveHour = [limits[@"five_hour"] isKindOfClass:NSDictionary.class] ? limits[@"five_hour"] : NSNull.null;
39
+ id week = [limits[@"seven_day"] isKindOfClass:NSDictionary.class] ? limits[@"seven_day"] : NSNull.null;
40
+ return @{@"fiveHour": fiveHour, @"week": week};
41
+ }
42
+
43
+ static BOOL HookValueIndicatesFailure(id value) {
44
+ if ([value isKindOfClass:NSDictionary.class]) {
45
+ NSDictionary *dictionary = value;
46
+ if ([dictionary[@"is_error"] boolValue]) return YES;
47
+ if (dictionary[@"success"] && ![dictionary[@"success"] boolValue]) return YES;
48
+ NSString *status = [dictionary[@"status"] isKindOfClass:NSString.class] ? [dictionary[@"status"] lowercaseString] : nil;
49
+ if ([status isEqualToString:@"error"] || [status isEqualToString:@"failed"] || [status isEqualToString:@"failure"]) return YES;
50
+ if (dictionary[@"error"] && dictionary[@"error"] != NSNull.null) return YES;
51
+ for (id child in dictionary.allValues) if (HookValueIndicatesFailure(child)) return YES;
52
+ } else if ([value isKindOfClass:NSArray.class]) {
53
+ for (id child in value) if (HookValueIndicatesFailure(child)) return YES;
54
+ }
55
+ return NO;
56
+ }
57
+
58
+ static int RecordHookEvent(void) {
59
+ NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
60
+ NSDictionary *payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
61
+ if (![payload isKindOfClass:NSDictionary.class]) return EXIT_SUCCESS;
62
+ NSString *event = payload[@"hook_event_name"];
63
+ if (![event isKindOfClass:NSString.class] || event.length == 0) return EXIT_SUCCESS;
64
+ NSString *tool = [payload[@"tool_name"] isKindOfClass:NSString.class] ? payload[@"tool_name"] : @"";
65
+ id toolResult = payload[@"tool_response"] ?: payload[@"tool_result"];
66
+ BOOL failed = [event isEqualToString:@"PostToolUseFailure"] ||
67
+ [event isEqualToString:@"StopFailure"] || HookValueIndicatesFailure(toolResult);
68
+ NSDictionary *record = @{
69
+ @"event": event,
70
+ @"tool": tool,
71
+ @"failed": @(failed),
72
+ @"timestamp": @([NSDate.date timeIntervalSince1970])
73
+ };
74
+ NSData *json = [NSJSONSerialization dataWithJSONObject:record options:0 error:nil];
75
+ if (!json) return EXIT_SUCCESS;
76
+ int descriptor = open(AgentEventPath().fileSystemRepresentation, O_CREAT | O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR);
77
+ if (descriptor < 0) return EXIT_SUCCESS;
78
+ write(descriptor, json.bytes, json.length);
79
+ write(descriptor, "\n", 1);
80
+ close(descriptor);
81
+ return EXIT_SUCCESS;
82
+ }
83
+
84
+ static NSDictionary *LatestUsage(void) {
85
+ NSString *home = NSProcessInfo.processInfo.environment[@"CODEX_HOME"];
86
+ if (home.length == 0) home = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
87
+ NSURL *sessions = [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"sessions"]];
88
+ NSArray *keys = @[NSURLContentModificationDateKey, NSURLIsRegularFileKey];
89
+ NSDirectoryEnumerator *files = [NSFileManager.defaultManager enumeratorAtURL:sessions
90
+ includingPropertiesForKeys:keys options:NSDirectoryEnumerationSkipsHiddenFiles
91
+ errorHandler:nil];
92
+ NSURL *newest = nil;
93
+ NSDate *newestDate = NSDate.distantPast;
94
+ for (NSURL *url in files) {
95
+ if (![url.pathExtension isEqualToString:@"jsonl"]) continue;
96
+ NSDictionary *values = [url resourceValuesForKeys:keys error:nil];
97
+ if (![values[NSURLIsRegularFileKey] boolValue]) continue;
98
+ NSDate *date = values[NSURLContentModificationDateKey] ?: NSDate.distantPast;
99
+ if ([date compare:newestDate] == NSOrderedDescending) {
100
+ newest = url;
101
+ newestDate = date;
102
+ }
103
+ }
104
+ if (!newest) return nil;
105
+
106
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:newest error:nil];
107
+ if (!handle) return nil;
108
+ unsigned long long size = [handle seekToEndOfFile];
109
+ [handle seekToFileOffset:size > 2 * 1024 * 1024 ? size - 2 * 1024 * 1024 : 0];
110
+ NSData *tail = [handle readDataToEndOfFile];
111
+ [handle closeFile];
112
+ NSString *text = [[NSString alloc] initWithData:tail encoding:NSUTF8StringEncoding];
113
+ NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
114
+ for (NSString *line in lines.reverseObjectEnumerator) {
115
+ if ([line rangeOfString:@"\"type\":\"token_count\""].location == NSNotFound) continue;
116
+ NSData *data = [line dataUsingEncoding:NSUTF8StringEncoding];
117
+ NSDictionary *root = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
118
+ NSDictionary *payload = root[@"payload"];
119
+ if (![payload[@"type"] isEqualToString:@"token_count"]) continue;
120
+ NSDictionary *limits = payload[@"rate_limits"];
121
+ id primaryValue = limits[@"primary"];
122
+ id secondaryValue = limits[@"secondary"];
123
+ NSDictionary *primary = [primaryValue isKindOfClass:NSDictionary.class] ? primaryValue : nil;
124
+ NSDictionary *secondary = [secondaryValue isKindOfClass:NSDictionary.class] ? secondaryValue : nil;
125
+ NSDictionary *fiveHour = nil;
126
+ NSDictionary *week = nil;
127
+ for (NSDictionary *quota in @[primary ?: @{}, secondary ?: @{}]) {
128
+ NSInteger minutes = [quota[@"window_minutes"] integerValue];
129
+ if (minutes == 300) fiveHour = quota;
130
+ if (minutes == 10080) week = quota;
131
+ }
132
+ return @{
133
+ @"fiveHour": fiveHour ?: NSNull.null,
134
+ @"week": week ?: NSNull.null
135
+ };
136
+ }
137
+ return nil;
138
+ }
139
+
140
+ @interface PetView : NSView
141
+ @property NSImage *sheet;
142
+ @property NSInteger frameIndex;
143
+ @property NSInteger rowIndex;
144
+ @property NSArray<NSNumber *> *frames;
145
+ @property NSUInteger sequenceIndex;
146
+ @property BOOL oneShot;
147
+ @property BOOL draggingPet;
148
+ @property BOOL agentActive;
149
+ @property NSPoint dragStartMouse;
150
+ @property NSPoint dragStartWindowOrigin;
151
+ @property NSString *currentPetID;
152
+ @property(copy) void (^pocketHoverChanged)(BOOL hovering);
153
+ @property(copy) void (^positionChanged)(void);
154
+ @property(copy) void (^dragStateChanged)(BOOL dragging);
155
+ @property(copy) NSArray<NSDictionary *> *(^petOptionsRequested)(void);
156
+ @property(copy) void (^switchPetRequested)(NSString *petID);
157
+ @end
158
+
159
+ @implementation PetView
160
+ - (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet {
161
+ if ((self = [super initWithFrame:frame])) {
162
+ _sheet = sheet;
163
+ _frames = @[@0, @1, @2, @3, @4, @5];
164
+ [NSTimer scheduledTimerWithTimeInterval:0.22 target:self
165
+ selector:@selector(nextFrame:) userInfo:nil repeats:YES];
166
+ NSTrackingArea *tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect
167
+ options:NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
168
+ NSTrackingActiveAlways | NSTrackingInVisibleRect
169
+ owner:self userInfo:nil];
170
+ [self addTrackingArea:tracking];
171
+ }
172
+ return self;
173
+ }
174
+ - (NSArray<NSNumber *> *)framesFromZeroThrough:(NSInteger)last {
175
+ NSMutableArray<NSNumber *> *result = [NSMutableArray arrayWithCapacity:last + 1];
176
+ for (NSInteger index = 0; index <= last; index++) [result addObject:@(index)];
177
+ return result;
178
+ }
179
+ - (void)playRow:(NSInteger)row throughFrame:(NSInteger)last oneShot:(BOOL)oneShot {
180
+ if (!oneShot && !self.oneShot && self.rowIndex == row) return;
181
+ self.rowIndex = row;
182
+ self.frames = [self framesFromZeroThrough:last];
183
+ self.sequenceIndex = 0;
184
+ self.frameIndex = 0;
185
+ self.oneShot = oneShot;
186
+ self.needsDisplay = YES;
187
+ }
188
+ - (BOOL)isPocketPoint:(NSPoint)point {
189
+ CGFloat centerX = NSMidX(self.bounds);
190
+ CGFloat centerY = NSHeight(self.bounds) * 0.32;
191
+ CGFloat dx = (point.x - centerX) / (NSWidth(self.bounds) * 0.22);
192
+ CGFloat dy = (point.y - centerY) / (NSHeight(self.bounds) * 0.16);
193
+ return dx * dx + dy * dy <= 1.0;
194
+ }
195
+ - (void)updateHoverForPoint:(NSPoint)point {
196
+ BOOL overPocket = [self isPocketPoint:point];
197
+ if (self.pocketHoverChanged) self.pocketHoverChanged(overPocket);
198
+ if (overPocket) {
199
+ [NSCursor.pointingHandCursor set];
200
+ [self playRow:5 throughFrame:7 oneShot:NO];
201
+ } else if (point.y >= NSHeight(self.bounds) * 0.58) {
202
+ [NSCursor.pointingHandCursor set];
203
+ [self playRow:4 throughFrame:4 oneShot:NO];
204
+ } else if (point.y <= NSHeight(self.bounds) * 0.20) {
205
+ [NSCursor.pointingHandCursor set];
206
+ [self playRow:6 throughFrame:5 oneShot:NO];
207
+ } else if (point.x >= NSWidth(self.bounds) * 0.66) {
208
+ [NSCursor.arrowCursor set];
209
+ [self playRow:3 throughFrame:3 oneShot:NO];
210
+ } else if (point.x <= NSWidth(self.bounds) * 0.34) {
211
+ [NSCursor.arrowCursor set];
212
+ [self playRow:8 throughFrame:5 oneShot:NO];
213
+ } else {
214
+ [NSCursor.arrowCursor set];
215
+ [self playRow:0 throughFrame:5 oneShot:NO];
216
+ }
217
+ }
218
+ - (void)mouseMoved:(NSEvent *)event {
219
+ if (self.draggingPet || self.oneShot) return;
220
+ NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
221
+ if (self.agentActive) {
222
+ BOOL overPocket = [self isPocketPoint:point];
223
+ if (self.pocketHoverChanged) self.pocketHoverChanged(overPocket);
224
+ if (overPocket) [NSCursor.pointingHandCursor set];
225
+ else [NSCursor.arrowCursor set];
226
+ return;
227
+ }
228
+ [self updateHoverForPoint:point];
229
+ }
230
+ - (void)mouseExited:(NSEvent *)event {
231
+ if (self.draggingPet) return;
232
+ if (self.pocketHoverChanged) self.pocketHoverChanged(NO);
233
+ [NSCursor.arrowCursor set];
234
+ if (self.agentActive) return;
235
+ [self playRow:0 throughFrame:5 oneShot:NO];
236
+ }
237
+ - (void)nextFrame:(NSTimer *)timer {
238
+ self.sequenceIndex += 1;
239
+ if (self.sequenceIndex >= self.frames.count) {
240
+ if (self.oneShot) {
241
+ self.rowIndex = 0;
242
+ self.frames = [self framesFromZeroThrough:5];
243
+ self.oneShot = NO;
244
+ self.agentActive = NO;
245
+ }
246
+ self.sequenceIndex = 0;
247
+ }
248
+ self.frameIndex = self.frames[self.sequenceIndex].integerValue;
249
+ self.needsDisplay = YES;
250
+ }
251
+ - (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed {
252
+ if ([event isEqualToString:@"SessionStart"]) {
253
+ self.agentActive = YES;
254
+ [self playRow:4 throughFrame:4 oneShot:YES];
255
+ } else if ([event isEqualToString:@"UserPromptSubmit"]) {
256
+ self.agentActive = YES;
257
+ [self playRow:5 throughFrame:7 oneShot:NO];
258
+ } else if ([event isEqualToString:@"PermissionRequest"]) {
259
+ self.agentActive = YES;
260
+ [self playRow:4 throughFrame:4 oneShot:NO];
261
+ } else if ([event isEqualToString:@"PreToolUse"]) {
262
+ self.agentActive = YES;
263
+ NSString *lower = tool.lowercaseString;
264
+ if ([lower containsString:@"bash"] || [lower containsString:@"exec"]) {
265
+ [self playRow:1 throughFrame:7 oneShot:NO];
266
+ } else if ([lower containsString:@"patch"] || [lower containsString:@"edit"] || [lower containsString:@"write"]) {
267
+ [self playRow:7 throughFrame:5 oneShot:NO];
268
+ } else if ([lower containsString:@"read"] || [lower containsString:@"search"] || [lower containsString:@"find"] ||
269
+ [lower containsString:@"grep"] || [lower containsString:@"glob"] || [lower containsString:@"web"] ||
270
+ [lower hasPrefix:@"mcp__"]) {
271
+ [self playRow:3 throughFrame:3 oneShot:NO];
272
+ } else if ([lower isEqualToString:@"task"] || [lower containsString:@"agent"]) {
273
+ [self playRow:6 throughFrame:5 oneShot:NO];
274
+ } else {
275
+ [self playRow:8 throughFrame:5 oneShot:NO];
276
+ }
277
+ } else if ([event isEqualToString:@"SubagentStart"] || [event isEqualToString:@"TaskCreated"]) {
278
+ self.agentActive = YES;
279
+ [self playRow:6 throughFrame:5 oneShot:NO];
280
+ } else if ([event isEqualToString:@"PostToolUse"] || [event isEqualToString:@"PostToolUseFailure"]) {
281
+ self.agentActive = YES;
282
+ [self playRow:failed ? 5 : 7 throughFrame:failed ? 7 : 5 oneShot:YES];
283
+ } else if ([event isEqualToString:@"StopFailure"]) {
284
+ self.agentActive = YES;
285
+ [self playRow:5 throughFrame:7 oneShot:YES];
286
+ } else if ([event isEqualToString:@"Notification"]) {
287
+ self.agentActive = YES;
288
+ [self playRow:4 throughFrame:4 oneShot:YES];
289
+ } else if ([event isEqualToString:@"Stop"] || [event isEqualToString:@"SubagentStop"] ||
290
+ [event isEqualToString:@"TaskCompleted"] || [event isEqualToString:@"SessionEnd"]) {
291
+ self.agentActive = YES;
292
+ [self playRow:3 throughFrame:3 oneShot:YES];
293
+ }
294
+ }
295
+ - (void)mouseDown:(NSEvent *)event {
296
+ self.agentActive = NO;
297
+ self.dragStartMouse = NSEvent.mouseLocation;
298
+ self.dragStartWindowOrigin = self.window.frame.origin;
299
+ self.draggingPet = NO;
300
+ }
301
+ - (void)mouseDragged:(NSEvent *)event {
302
+ NSPoint current = NSEvent.mouseLocation;
303
+ CGFloat horizontal = current.x - self.dragStartMouse.x;
304
+ CGFloat vertical = current.y - self.dragStartMouse.y;
305
+ if (!self.draggingPet && hypot(horizontal, vertical) >= 3) {
306
+ self.draggingPet = YES;
307
+ if (self.dragStateChanged) self.dragStateChanged(YES);
308
+ }
309
+ if (self.draggingPet) {
310
+ if (self.pocketHoverChanged) self.pocketHoverChanged(NO);
311
+ [self playRow:horizontal >= 0 ? 1 : 2 throughFrame:7 oneShot:NO];
312
+ }
313
+ NSPoint origin = NSMakePoint(
314
+ self.dragStartWindowOrigin.x + horizontal,
315
+ self.dragStartWindowOrigin.y + vertical
316
+ );
317
+ [self.window setFrameOrigin:origin];
318
+ if (self.positionChanged) self.positionChanged();
319
+ }
320
+ - (void)mouseUp:(NSEvent *)event {
321
+ if (self.draggingPet) {
322
+ self.draggingPet = NO;
323
+ if (self.dragStateChanged) self.dragStateChanged(NO);
324
+ [self playRow:0 throughFrame:5 oneShot:NO];
325
+ } else {
326
+ // 第 8 行未标注的动作作为点击反馈,完整利用剩余素材。
327
+ [self playRow:7 throughFrame:5 oneShot:YES];
328
+ }
329
+ }
330
+ - (void)drawRect:(NSRect)dirtyRect {
331
+ CGFloat cellWidth = self.sheet.size.width / 8.0;
332
+ CGFloat cellHeight = self.sheet.size.height / 9.0;
333
+ NSRect source = NSMakeRect(self.frameIndex * cellWidth,
334
+ self.sheet.size.height - (self.rowIndex + 1) * cellHeight, cellWidth, cellHeight);
335
+ [self.sheet drawInRect:NSInsetRect(self.bounds, 2, 0) fromRect:source
336
+ operation:NSCompositingOperationSourceOver fraction:1.0
337
+ respectFlipped:NO hints:@{NSImageHintInterpolation: @(NSImageInterpolationNone)}];
338
+ }
339
+ - (void)applySheet:(NSImage *)sheet petID:(NSString *)petID {
340
+ self.sheet = sheet;
341
+ self.currentPetID = petID;
342
+ self.rowIndex = 0;
343
+ self.frameIndex = 0;
344
+ self.sequenceIndex = 0;
345
+ self.frames = [self framesFromZeroThrough:5];
346
+ self.oneShot = NO;
347
+ self.needsDisplay = YES;
348
+ }
349
+ - (void)selectPet:(NSMenuItem *)sender {
350
+ NSString *petID = sender.representedObject;
351
+ if (petID.length > 0 && self.switchPetRequested) self.switchPetRequested(petID);
352
+ }
353
+ - (void)rightMouseDown:(NSEvent *)event {
354
+ NSArray<NSDictionary *> *availablePets = self.petOptionsRequested ? self.petOptionsRequested() : @[];
355
+ NSMenu *menu = [NSMenu new];
356
+ NSMenuItem *switchItem = [menu addItemWithTitle:@"切换桌宠" action:nil keyEquivalent:@""];
357
+ NSMenu *switchMenu = [NSMenu new];
358
+ for (NSDictionary *pet in availablePets) {
359
+ NSString *petID = pet[@"id"];
360
+ NSMenuItem *item = [switchMenu addItemWithTitle:pet[@"name"]
361
+ action:@selector(selectPet:) keyEquivalent:@""];
362
+ item.target = self;
363
+ item.representedObject = petID;
364
+ item.state = [petID isEqualToString:self.currentPetID] ? NSControlStateValueOn : NSControlStateValueOff;
365
+ }
366
+ switchItem.submenu = switchMenu;
367
+ [menu addItem:NSMenuItem.separatorItem];
368
+ NSMenuItem *refreshItem = [menu addItemWithTitle:@"刷新用量" action:@selector(refreshUsage:) keyEquivalent:@"r"];
369
+ refreshItem.target = NSApp.delegate;
370
+ [menu addItem:NSMenuItem.separatorItem];
371
+ NSMenuItem *quitItem = [menu addItemWithTitle:@"退出桌宠" action:@selector(terminate:) keyEquivalent:@"q"];
372
+ quitItem.target = NSApp;
373
+ [NSMenu popUpContextMenu:menu withEvent:event forView:self];
374
+ }
375
+ @end
376
+
377
+ static const CGFloat QuotaLogicalWidth = 600;
378
+ static const CGFloat QuotaLogicalHeight = 360;
379
+ static const CGFloat QuotaScale = 0.6;
380
+
381
+ static NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
382
+ NSURL *appURL = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:bundleIdentifier];
383
+ NSMutableArray<NSString *> *paths = [NSMutableArray array];
384
+ if (appURL) {
385
+ NSBundle *bundle = [NSBundle bundleWithURL:appURL];
386
+ NSString *resourcePath = [bundle pathForResource:resourceName.stringByDeletingPathExtension
387
+ ofType:resourceName.pathExtension];
388
+ if (resourcePath.length > 0) [paths addObject:resourcePath];
389
+ }
390
+ NSString *applicationName = [bundleIdentifier containsString:@"anthropic"] ? @"Claude.app" : @"ChatGPT.app";
391
+ [paths addObject:[@"/Applications" stringByAppendingPathComponent:
392
+ [applicationName stringByAppendingPathComponent:[@"Contents/Resources" stringByAppendingPathComponent:resourceName]]]];
393
+ [paths addObject:[[NSHomeDirectory() stringByAppendingPathComponent:@"Applications"] stringByAppendingPathComponent:
394
+ [applicationName stringByAppendingPathComponent:[@"Contents/Resources" stringByAppendingPathComponent:resourceName]]]];
395
+ for (NSString *path in paths) {
396
+ NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
397
+ if (image) return image;
398
+ }
399
+ return appURL ? [NSWorkspace.sharedWorkspace iconForFile:appURL.path] : nil;
400
+ }
401
+
402
+ @interface QuotaDashboardView : NSView
403
+ @property NSDictionary *codexUsage;
404
+ @property NSDictionary *claudeUsage;
405
+ @property NSImage *codexLogo;
406
+ @property NSImage *claudeLogo;
407
+ @property BOOL refreshHovered;
408
+ @property BOOL refreshPressed;
409
+ @property NSTimeInterval refreshedUntil;
410
+ @property(copy) void (^hoverChanged)(BOOL hovering);
411
+ @property(copy) void (^refreshRequested)(void);
412
+ @end
413
+
414
+ @implementation QuotaDashboardView
415
+ - (instancetype)initWithFrame:(NSRect)frame {
416
+ if ((self = [super initWithFrame:frame])) {
417
+ NSTrackingArea *tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect
418
+ options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
419
+ NSTrackingActiveAlways | NSTrackingInVisibleRect
420
+ owner:self userInfo:nil];
421
+ [self addTrackingArea:tracking];
422
+ }
423
+ return self;
424
+ }
425
+ - (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
426
+ - (void)mouseEntered:(NSEvent *)event {
427
+ if (self.hoverChanged) self.hoverChanged(YES);
428
+ [self mouseMoved:event];
429
+ }
430
+ - (void)mouseExited:(NSEvent *)event {
431
+ self.refreshHovered = NO;
432
+ self.refreshPressed = NO;
433
+ [NSCursor.arrowCursor set];
434
+ self.needsDisplay = YES;
435
+ if (self.hoverChanged) self.hoverChanged(NO);
436
+ }
437
+ - (NSRect)logicalRefreshRect { return NSMakeRect(QuotaLogicalWidth - 54, QuotaLogicalHeight - 52, 34, 32); }
438
+ - (NSRect)refreshRect {
439
+ NSRect logical = [self logicalRefreshRect];
440
+ return NSMakeRect(logical.origin.x * QuotaScale, logical.origin.y * QuotaScale,
441
+ logical.size.width * QuotaScale, logical.size.height * QuotaScale);
442
+ }
443
+ - (void)mouseMoved:(NSEvent *)event {
444
+ NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
445
+ BOOL hovering = NSPointInRect(point, [self refreshRect]);
446
+ if (hovering != self.refreshHovered) {
447
+ self.refreshHovered = hovering;
448
+ self.needsDisplay = YES;
449
+ }
450
+ if (hovering) [NSCursor.pointingHandCursor set];
451
+ else [NSCursor.arrowCursor set];
452
+ }
453
+ - (void)mouseDown:(NSEvent *)event {
454
+ NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
455
+ if (NSPointInRect(point, [self refreshRect])) {
456
+ self.refreshPressed = YES;
457
+ self.needsDisplay = YES;
458
+ }
459
+ }
460
+ - (void)mouseUp:(NSEvent *)event {
461
+ NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
462
+ BOOL shouldRefresh = self.refreshPressed && NSPointInRect(point, [self refreshRect]);
463
+ self.refreshPressed = NO;
464
+ if (shouldRefresh) {
465
+ if (self.refreshRequested) self.refreshRequested();
466
+ self.refreshedUntil = NSDate.date.timeIntervalSince1970 + 1.2;
467
+ [[NSHapticFeedbackManager defaultPerformer] performFeedbackPattern:NSHapticFeedbackPatternAlignment
468
+ performanceTime:NSHapticFeedbackPerformanceTimeNow];
469
+ [self performSelector:@selector(clearRefreshConfirmation) withObject:nil afterDelay:1.2];
470
+ }
471
+ self.needsDisplay = YES;
472
+ }
473
+ - (void)clearRefreshConfirmation {
474
+ self.refreshedUntil = 0;
475
+ self.needsDisplay = YES;
476
+ }
477
+ - (NSDictionary *)quota:(NSDictionary *)usage key:(NSString *)key {
478
+ id value = usage[key];
479
+ return [value isKindOfClass:NSDictionary.class] ? value : nil;
480
+ }
481
+ - (NSNumber *)remainingForQuota:(NSDictionary *)quota usedKey:(NSString *)usedKey {
482
+ NSNumber *used = quota[usedKey];
483
+ if (![used isKindOfClass:NSNumber.class]) return nil;
484
+ return @(fmax(0, fmin(100, 100.0 - used.doubleValue)));
485
+ }
486
+ - (NSString *)weeklyReset:(NSDictionary *)week {
487
+ NSNumber *weekReset = week[@"resets_at"];
488
+ if (!weekReset) return @"--";
489
+ NSDateFormatter *formatter = [NSDateFormatter new];
490
+ formatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
491
+ formatter.timeZone = NSTimeZone.localTimeZone;
492
+ formatter.dateFormat = @"M/d HH:mm:ss";
493
+ return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:weekReset.doubleValue]];
494
+ }
495
+ - (NSDictionary *)textAttributesWithSize:(CGFloat)size color:(NSColor *)color weight:(NSFontWeight)weight {
496
+ return @{NSFontAttributeName: [NSFont systemFontOfSize:size weight:weight],
497
+ NSForegroundColorAttributeName: color};
498
+ }
499
+ - (NSDictionary *)centeredTextAttributesWithSize:(CGFloat)size color:(NSColor *)color weight:(NSFontWeight)weight {
500
+ NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
501
+ style.alignment = NSTextAlignmentCenter;
502
+ return @{NSFontAttributeName: [NSFont systemFontOfSize:size weight:weight],
503
+ NSForegroundColorAttributeName: color,
504
+ NSParagraphStyleAttributeName: style};
505
+ }
506
+ - (void)fillRoundedRect:(NSRect)rect radius:(CGFloat)radius color:(NSColor *)color {
507
+ [color setFill];
508
+ [[NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius] fill];
509
+ }
510
+ - (void)drawProvider:(NSString *)name usage:(NSDictionary *)usage usedKey:(NSString *)usedKey
511
+ color:(NSColor *)color cardRect:(NSRect)card {
512
+ NSColor *primary = [NSColor colorWithWhite:0.96 alpha:1];
513
+ NSColor *secondary = [NSColor colorWithWhite:0.68 alpha:1];
514
+ NSColor *track = [NSColor colorWithWhite:0.28 alpha:0.55];
515
+ NSDictionary *five = [self quota:usage key:@"fiveHour"];
516
+ NSDictionary *week = [self quota:usage key:@"week"];
517
+ NSNumber *fiveRemaining = [self remainingForQuota:five usedKey:usedKey];
518
+ NSNumber *weekRemaining = [self remainingForQuota:week usedKey:usedKey];
519
+ BOOL available = fiveRemaining || weekRemaining;
520
+
521
+ NSBezierPath *cardPath = [NSBezierPath bezierPathWithRoundedRect:card xRadius:16 yRadius:16];
522
+ NSGradient *cardGlass = [[NSGradient alloc]
523
+ initWithStartingColor:[NSColor colorWithWhite:1 alpha:0.13]
524
+ endingColor:[NSColor colorWithRed:0.30 green:0.42 blue:0.62 alpha:0.06]];
525
+ [cardGlass drawInBezierPath:cardPath angle:-30];
526
+ NSBezierPath *border = cardPath;
527
+ [[NSColor colorWithWhite:1 alpha:0.38] setStroke];
528
+ border.lineWidth = 1;
529
+ [border stroke];
530
+ NSBezierPath *innerBorder = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(card, 1.5, 1.5)
531
+ xRadius:14.5 yRadius:14.5];
532
+ [[NSColor colorWithRed:0.66 green:0.86 blue:1 alpha:0.12] setStroke];
533
+ innerBorder.lineWidth = 0.8;
534
+ [innerBorder stroke];
535
+
536
+ NSRect icon = NSMakeRect(NSMinX(card) + 18, NSMinY(card) + 37, 48, 48);
537
+ NSImage *logo = [name isEqualToString:@"Codex"] ? self.codexLogo : self.claudeLogo;
538
+ if (logo) {
539
+ [NSGraphicsContext saveGraphicsState];
540
+ [[NSBezierPath bezierPathWithRoundedRect:icon xRadius:13 yRadius:13] addClip];
541
+ [logo drawInRect:icon fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0
542
+ respectFlipped:YES hints:@{NSImageHintInterpolation: @(NSImageInterpolationHigh)}];
543
+ [NSGraphicsContext restoreGraphicsState];
544
+ } else {
545
+ [self fillRoundedRect:icon radius:13 color:[color colorWithAlphaComponent:0.7]];
546
+ NSString *iconText = [name isEqualToString:@"Codex"] ? @"C" : @"AI";
547
+ [iconText drawInRect:NSInsetRect(icon, 0, 10)
548
+ withAttributes:[self centeredTextAttributesWithSize:20 color:NSColor.whiteColor weight:NSFontWeightBold]];
549
+ }
550
+
551
+ [name drawInRect:NSMakeRect(NSMinX(card) + 78, NSMinY(card) + 64, 70, 24)
552
+ withAttributes:[self textAttributesWithSize:18 color:primary weight:NSFontWeightSemibold]];
553
+ NSRect status = NSMakeRect(NSMinX(card) + 78, NSMinY(card) + 37, available ? 44 : 68, 22);
554
+ [self fillRoundedRect:status radius:9 color:[available ? NSColor.systemGreenColor : secondary colorWithAlphaComponent:0.15]];
555
+ NSString *statusText = available ? @"在线" : @"等待数据";
556
+ [statusText drawInRect:NSInsetRect(status, 8, 3)
557
+ withAttributes:[self textAttributesWithSize:11 color:available ? NSColor.systemGreenColor : secondary weight:NSFontWeightMedium]];
558
+
559
+ CGFloat firstX = NSMinX(card) + 160;
560
+ [@"5 小时剩余" drawInRect:NSMakeRect(firstX, NSMinY(card) + 68, 100, 20)
561
+ withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
562
+ NSString *fiveText = fiveRemaining ? [NSString stringWithFormat:@"%.0f%%", fiveRemaining.doubleValue] : @"--";
563
+ [fiveText drawInRect:NSMakeRect(firstX, NSMinY(card) + 40, 90, 26)
564
+ withAttributes:[self textAttributesWithSize:20 color:primary weight:NSFontWeightSemibold]];
565
+ NSRect bar = NSMakeRect(firstX, NSMinY(card) + 24, 112, 8);
566
+ [self fillRoundedRect:bar radius:4 color:track];
567
+ if (fiveRemaining) {
568
+ NSRect fill = bar;
569
+ fill.size.width *= fiveRemaining.doubleValue / 100.0;
570
+ [self fillRoundedRect:fill radius:4 color:color];
571
+ }
572
+
573
+ CGFloat separatorOne = NSMinX(card) + 290;
574
+ [[NSColor colorWithWhite:1 alpha:0.12] setStroke];
575
+ [NSBezierPath strokeLineFromPoint:NSMakePoint(separatorOne, NSMinY(card) + 20)
576
+ toPoint:NSMakePoint(separatorOne, NSMaxY(card) - 20)];
577
+ CGFloat ringX = separatorOne + 38;
578
+ NSPoint center = NSMakePoint(ringX, NSMinY(card) + 51);
579
+ NSBezierPath *ringTrack = [NSBezierPath bezierPath];
580
+ [ringTrack appendBezierPathWithArcWithCenter:center radius:24 startAngle:0 endAngle:360];
581
+ ringTrack.lineWidth = 7;
582
+ [track setStroke];
583
+ [ringTrack stroke];
584
+ if (weekRemaining) {
585
+ NSBezierPath *ring = [NSBezierPath bezierPath];
586
+ [ring appendBezierPathWithArcWithCenter:center radius:24 startAngle:90
587
+ endAngle:90 - 360 * weekRemaining.doubleValue / 100.0 clockwise:YES];
588
+ ring.lineWidth = 7;
589
+ ring.lineCapStyle = NSLineCapStyleRound;
590
+ [color setStroke];
591
+ [ring stroke];
592
+ }
593
+ NSString *weekText = weekRemaining ? [NSString stringWithFormat:@"%.0f%%", weekRemaining.doubleValue] : @"--";
594
+ [weekText drawInRect:NSMakeRect(ringX - 19, NSMinY(card) + 42, 38, 18)
595
+ withAttributes:[self centeredTextAttributesWithSize:13 color:primary weight:NSFontWeightSemibold]];
596
+ [@"周剩余" drawInRect:NSMakeRect(separatorOne + 68, NSMinY(card) + 66, 55, 20)
597
+ withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
598
+
599
+ CGFloat separatorTwo = NSMinX(card) + 414;
600
+ [[NSColor colorWithWhite:1 alpha:0.12] setStroke];
601
+ [NSBezierPath strokeLineFromPoint:NSMakePoint(separatorTwo, NSMinY(card) + 20)
602
+ toPoint:NSMakePoint(separatorTwo, NSMaxY(card) - 20)];
603
+ [@"周重置" drawInRect:NSMakeRect(separatorTwo + 16, NSMinY(card) + 66, 80, 20)
604
+ withAttributes:[self textAttributesWithSize:12 color:secondary weight:NSFontWeightRegular]];
605
+ [[self weeklyReset:week] drawInRect:NSMakeRect(separatorTwo + 16, NSMinY(card) + 39,
606
+ NSMaxX(card) - separatorTwo - 28, 24)
607
+ withAttributes:[self textAttributesWithSize:15 color:primary weight:NSFontWeightMedium]];
608
+ }
609
+ - (void)drawRect:(NSRect)dirtyRect {
610
+ [NSGraphicsContext saveGraphicsState];
611
+ NSAffineTransform *scale = [NSAffineTransform transform];
612
+ [scale scaleBy:QuotaScale];
613
+ [scale concat];
614
+ NSRect logicalBounds = NSMakeRect(0, 0, QuotaLogicalWidth, QuotaLogicalHeight);
615
+ NSRect outer = NSInsetRect(logicalBounds, 1, 1);
616
+ NSBezierPath *background = [NSBezierPath bezierPathWithRoundedRect:outer xRadius:22 yRadius:22];
617
+ NSGradient *gradient = [[NSGradient alloc]
618
+ initWithStartingColor:[NSColor colorWithRed:0.035 green:0.075 blue:0.14 alpha:0.68]
619
+ endingColor:[NSColor colorWithRed:0.15 green:0.20 blue:0.31 alpha:0.46]];
620
+ [gradient drawInBezierPath:background angle:-20];
621
+
622
+ [NSGraphicsContext saveGraphicsState];
623
+ [background addClip];
624
+ NSGradient *topGlow = [[NSGradient alloc]
625
+ initWithStartingColor:[NSColor colorWithWhite:1 alpha:0.34]
626
+ endingColor:[NSColor colorWithWhite:1 alpha:0.0]];
627
+ [topGlow drawFromCenter:NSMakePoint(555, 348) radius:0
628
+ toCenter:NSMakePoint(555, 348) radius:180 options:0];
629
+ NSGradient *cyanGlow = [[NSGradient alloc]
630
+ initWithStartingColor:[NSColor colorWithRed:0.18 green:0.72 blue:1 alpha:0.11]
631
+ endingColor:[NSColor colorWithRed:0.18 green:0.88 blue:1 alpha:0.0]];
632
+ [cyanGlow drawFromCenter:NSMakePoint(560, 85) radius:0
633
+ toCenter:NSMakePoint(560, 85) radius:170 options:0];
634
+ [NSGraphicsContext restoreGraphicsState];
635
+
636
+ [[NSColor colorWithWhite:1 alpha:0.62] setStroke];
637
+ background.lineWidth = 1.5;
638
+ [background stroke];
639
+ NSBezierPath *innerGlassBorder = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(outer, 2, 2)
640
+ xRadius:20 yRadius:20];
641
+ [[NSColor colorWithRed:0.58 green:0.82 blue:1 alpha:0.22] setStroke];
642
+ innerGlassBorder.lineWidth = 0.8;
643
+ [innerGlassBorder stroke];
644
+
645
+
646
+ [@"Agent 余量" drawInRect:NSMakeRect(24, QuotaLogicalHeight - 53, 180, 30)
647
+ withAttributes:[self textAttributesWithSize:23 color:[NSColor colorWithWhite:0.97 alpha:1] weight:NSFontWeightBold]];
648
+ [@"实时配额状态" drawInRect:NSMakeRect(25, QuotaLogicalHeight - 76, 130, 20)
649
+ withAttributes:[self textAttributesWithSize:12 color:[NSColor colorWithWhite:0.63 alpha:1] weight:NSFontWeightRegular]];
650
+ BOOL recentlyRefreshed = self.refreshedUntil > NSDate.date.timeIntervalSince1970;
651
+ NSRect live = NSMakeRect(QuotaLogicalWidth - 145, QuotaLogicalHeight - 51, 78, 28);
652
+ [self fillRoundedRect:live radius:14 color:[NSColor colorWithWhite:1 alpha:0.055]];
653
+ [[NSColor systemGreenColor] setFill];
654
+ [[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(NSMinX(live) + 12, NSMinY(live) + 10, 8, 8)] fill];
655
+ [recentlyRefreshed ? @"已刷新" : @"实时更新" drawInRect:NSMakeRect(NSMinX(live) + 26, NSMinY(live) + 6, 50, 18)
656
+ withAttributes:[self textAttributesWithSize:11 color:[NSColor colorWithWhite:0.87 alpha:1] weight:NSFontWeightMedium]];
657
+ CGFloat buttonAlpha = self.refreshPressed ? 0.18 : (self.refreshHovered ? 0.12 : 0.06);
658
+ NSRect logicalRefreshRect = [self logicalRefreshRect];
659
+ NSRect refreshRect = self.refreshPressed ? NSInsetRect(logicalRefreshRect, 1.5, 1.5) : logicalRefreshRect;
660
+ [self fillRoundedRect:refreshRect radius:10 color:[NSColor colorWithWhite:1 alpha:buttonAlpha]];
661
+ [recentlyRefreshed ? @"✓" : @"↻" drawInRect:NSInsetRect(refreshRect, 8, 4)
662
+ withAttributes:[self textAttributesWithSize:19 color:[NSColor colorWithWhite:0.9 alpha:1] weight:NSFontWeightRegular]];
663
+
664
+ [self drawProvider:@"Codex" usage:self.codexUsage usedKey:@"used_percent"
665
+ color:[NSColor colorWithRed:0.30 green:0.82 blue:0.86 alpha:1]
666
+ cardRect:NSMakeRect(18, 174, QuotaLogicalWidth - 36, 104)];
667
+ [self drawProvider:@"Claude" usage:self.claudeUsage usedKey:@"used_percentage"
668
+ color:[NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1]
669
+ cardRect:NSMakeRect(18, 58, QuotaLogicalWidth - 36, 104)];
670
+ [@"ⓘ 额度随 CLI 响应自动更新,也可点击右上角刷新" drawInRect:NSMakeRect(24, 23, 390, 20)
671
+ withAttributes:[self textAttributesWithSize:11 color:[NSColor colorWithWhite:0.58 alpha:1] weight:NSFontWeightRegular]];
672
+ [NSGraphicsContext restoreGraphicsState];
673
+ }
674
+ @end
675
+
676
+ static int RenderQuotaDashboard(NSString *path) {
677
+ [NSApplication sharedApplication];
678
+ QuotaDashboardView *view = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0,
679
+ QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale)];
680
+ view.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
681
+ view.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
682
+ view.codexUsage = LatestUsage() ?: @{
683
+ @"fiveHour": @{@"used_percent": @34, @"resets_at": @([NSDate.date timeIntervalSince1970] + 7200)},
684
+ @"week": @{@"used_percent": @51, @"resets_at": @([NSDate.date timeIntervalSince1970] + 172800)}
685
+ };
686
+ view.claudeUsage = LatestClaudeUsage() ?: @{
687
+ @"fiveHour": @{@"used_percentage": @23, @"resets_at": @([NSDate.date timeIntervalSince1970] + 3600)},
688
+ @"week": @{@"used_percentage": @41, @"resets_at": @([NSDate.date timeIntervalSince1970] + 86400)}
689
+ };
690
+ NSInteger pixelWidth = (NSInteger)ceil(NSWidth(view.bounds));
691
+ NSInteger pixelHeight = (NSInteger)ceil(NSHeight(view.bounds));
692
+ NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
693
+ initWithBitmapDataPlanes:NULL
694
+ pixelsWide:pixelWidth
695
+ pixelsHigh:pixelHeight
696
+ bitsPerSample:8
697
+ samplesPerPixel:4
698
+ hasAlpha:YES
699
+ isPlanar:NO
700
+ colorSpaceName:NSDeviceRGBColorSpace
701
+ bytesPerRow:0
702
+ bitsPerPixel:0];
703
+ bitmap.size = view.bounds.size;
704
+ NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
705
+ [NSGraphicsContext saveGraphicsState];
706
+ NSGraphicsContext.currentContext = context;
707
+ [view displayRectIgnoringOpacity:view.bounds inContext:context];
708
+ [NSGraphicsContext restoreGraphicsState];
709
+ NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
710
+ return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
711
+ }
712
+
713
+ @interface AppDelegate : NSObject <NSApplicationDelegate>
714
+ @property NSPanel *panel;
715
+ @property NSPanel *quotaPanel;
716
+ @property QuotaDashboardView *quotaView;
717
+ @property BOOL managedByCLI;
718
+ @property BOOL pocketHovering;
719
+ @property BOOL dashboardHovering;
720
+ @property BOOL petDragging;
721
+ @property NSString *binaryDirectory;
722
+ @property PetView *petView;
723
+ @property unsigned long long agentEventOffset;
724
+ - (void)showQuotaDashboard;
725
+ - (void)positionQuotaDashboard;
726
+ - (void)scheduleQuotaDashboardHide;
727
+ - (void)hideQuotaDashboardIfNeeded;
728
+ @end
729
+
730
+ @implementation AppDelegate
731
+ - (NSString *)spritePathInDirectory:(NSString *)directory {
732
+ NSString *configuredName = nil;
733
+ NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
734
+ NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
735
+ if (jsonData) {
736
+ NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
737
+ id value = json[@"spritesheetPath"];
738
+ if ([value isKindOfClass:NSString.class]) configuredName = [value lastPathComponent];
739
+ }
740
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
741
+ if (configuredName.length > 0) [names addObject:configuredName];
742
+ [names addObjectsFromArray:@[@"spritesheet.webp", @"spritesheet.png"]];
743
+ for (NSString *name in names) {
744
+ NSString *path = [directory stringByAppendingPathComponent:name];
745
+ BOOL isDirectory = NO;
746
+ if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && !isDirectory) return path;
747
+ }
748
+ return nil;
749
+ }
750
+ - (NSArray<NSString *> *)petDirectoryNamesAtPath:(NSString *)root {
751
+ NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:root error:nil] ?: @[];
752
+ NSMutableArray<NSString *> *directories = [NSMutableArray array];
753
+ for (NSString *entry in entries) {
754
+ if ([entry hasPrefix:@"."]) continue;
755
+ BOOL isDirectory = NO;
756
+ NSString *path = [root stringByAppendingPathComponent:entry];
757
+ if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory) {
758
+ [directories addObject:entry];
759
+ }
760
+ }
761
+ return [directories sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
762
+ }
763
+ - (NSArray<NSDictionary *> *)discoverPetOptions {
764
+ NSString *home = NSHomeDirectory();
765
+ NSString *petdexRoot = [home stringByAppendingPathComponent:@".petdex/pets"];
766
+ NSString *codexRoot = [home stringByAppendingPathComponent:@".codex/pets"];
767
+ NSMutableArray<NSDictionary *> *result = [NSMutableArray array];
768
+ NSMutableSet<NSString *> *externalNames = [NSMutableSet set];
769
+
770
+ for (NSString *name in [self petDirectoryNamesAtPath:petdexRoot]) {
771
+ NSString *path = [self spritePathInDirectory:[petdexRoot stringByAppendingPathComponent:name]];
772
+ if (!path) path = [self spritePathInDirectory:[codexRoot stringByAppendingPathComponent:name]];
773
+ if (!path) continue;
774
+ [result addObject:@{@"id": [@"external:" stringByAppendingString:name], @"name": name, @"path": path}];
775
+ [externalNames addObject:name];
776
+ }
777
+ for (NSString *name in [self petDirectoryNamesAtPath:codexRoot]) {
778
+ if ([externalNames containsObject:name]) continue;
779
+ NSString *path = [self spritePathInDirectory:[codexRoot stringByAppendingPathComponent:name]];
780
+ if (!path) continue;
781
+ [result addObject:@{@"id": [@"external:" stringByAppendingString:name], @"name": name, @"path": path}];
782
+ [externalNames addObject:name];
783
+ }
784
+
785
+ NSArray<NSString *> *bundled = [NSFileManager.defaultManager contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
786
+ for (NSString *fileName in [bundled sortedArrayUsingSelector:@selector(localizedStandardCompare:)]) {
787
+ NSString *extension = fileName.pathExtension.lowercaseString;
788
+ if (![extension isEqualToString:@"webp"] && ![extension isEqualToString:@"png"]) continue;
789
+ [result addObject:@{
790
+ @"id": [@"builtin:" stringByAppendingString:fileName],
791
+ @"name": fileName.stringByDeletingPathExtension,
792
+ @"path": [self.binaryDirectory stringByAppendingPathComponent:fileName]
793
+ }];
794
+ }
795
+ return result;
796
+ }
797
+ - (NSDictionary *)petOptionWithID:(NSString *)petID inOptions:(NSArray<NSDictionary *> *)options {
798
+ for (NSDictionary *option in options) if ([option[@"id"] isEqualToString:petID]) return option;
799
+ return nil;
800
+ }
801
+ - (NSArray<NSDictionary *> *)waitForPetOptions {
802
+ while (YES) {
803
+ NSArray<NSDictionary *> *options = [self discoverPetOptions];
804
+ if (options.count > 0) return options;
805
+
806
+ [NSApp activateIgnoringOtherApps:YES];
807
+ NSAlert *alert = [NSAlert new];
808
+ alert.messageText = @"没有找到桌宠素材";
809
+ alert.informativeText = @"请将 PNG 或 WebP 精灵图放入 ~/.petdex/pets/<名称>/ 或 "
810
+ @"~/.codex/pets/<名称>/,也可以通过 PetDex 安装。完成后点击“重新扫描”。";
811
+ [alert addButtonWithTitle:@"重新扫描"];
812
+ [alert addButtonWithTitle:@"打开素材目录"];
813
+ [alert addButtonWithTitle:@"退出"];
814
+ NSModalResponse response = [alert runModal];
815
+ if (response == NSAlertSecondButtonReturn) {
816
+ NSString *directory = [NSHomeDirectory() stringByAppendingPathComponent:@".petdex/pets"];
817
+ [NSFileManager.defaultManager createDirectoryAtPath:directory
818
+ withIntermediateDirectories:YES attributes:nil error:nil];
819
+ [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:directory]];
820
+ } else if (response == NSAlertThirdButtonReturn) {
821
+ return @[];
822
+ }
823
+ }
824
+ }
825
+ - (void)applicationDidFinishLaunching:(NSNotification *)notification {
826
+ self.managedByCLI = [NSProcessInfo.processInfo.arguments containsObject:@"--managed"];
827
+ NSString *binaryDir = NSProcessInfo.processInfo.arguments.firstObject.stringByStandardizingPath.stringByDeletingLastPathComponent;
828
+ self.binaryDirectory = binaryDir;
829
+ NSArray<NSDictionary *> *petOptions = [self waitForPetOptions];
830
+ if (petOptions.count == 0) {
831
+ [NSApp terminate:nil];
832
+ return;
833
+ }
834
+ NSString *selected = [NSUserDefaults.standardUserDefaults stringForKey:@"CodexPetSelectedSprite"];
835
+ if (selected.length > 0 && ![selected containsString:@":"]) selected = [@"builtin:" stringByAppendingString:selected];
836
+ NSDictionary *selectedOption = [self petOptionWithID:selected inOptions:petOptions] ?: petOptions.firstObject;
837
+ selected = selectedOption[@"id"];
838
+ NSString *spritePath = selectedOption[@"path"];
839
+ NSImage *image = [[NSImage alloc] initWithContentsOfFile:spritePath];
840
+ if (!image) {
841
+ fprintf(stderr, "无法读取桌宠素材: %s\n", spritePath.UTF8String);
842
+ [NSApp terminate:nil];
843
+ return;
844
+ }
845
+
846
+ NSSize size = NSMakeSize(230, 170);
847
+ self.panel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, size.width, size.height)
848
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
849
+ backing:NSBackingStoreBuffered defer:NO];
850
+ self.panel.opaque = NO;
851
+ self.panel.backgroundColor = NSColor.clearColor;
852
+ self.panel.hasShadow = NO;
853
+ self.panel.level = NSFloatingWindowLevel;
854
+ self.panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
855
+ self.panel.movableByWindowBackground = YES;
856
+ self.panel.hidesOnDeactivate = NO;
857
+
858
+ NSView *root = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
859
+ self.panel.contentView = root;
860
+ self.petView = [[PetView alloc] initWithFrame:NSMakeRect(43, 0, 144, 150) sheet:image];
861
+ self.petView.currentPetID = selected;
862
+ __weak typeof(self) weakSelf = self;
863
+ self.petView.pocketHoverChanged = ^(BOOL hovering) {
864
+ weakSelf.pocketHovering = hovering;
865
+ if (hovering) [weakSelf showQuotaDashboard];
866
+ else [weakSelf scheduleQuotaDashboardHide];
867
+ };
868
+ self.petView.petOptionsRequested = ^NSArray<NSDictionary *> *{
869
+ return [weakSelf discoverPetOptions] ?: @[];
870
+ };
871
+ self.petView.switchPetRequested = ^(NSString *petID) {
872
+ [weakSelf switchPetToID:petID];
873
+ };
874
+ self.petView.positionChanged = ^{
875
+ if (weakSelf.quotaPanel.isVisible) [weakSelf positionQuotaDashboard];
876
+ };
877
+ self.petView.dragStateChanged = ^(BOOL dragging) {
878
+ weakSelf.petDragging = dragging;
879
+ if (!dragging) [weakSelf scheduleQuotaDashboardHide];
880
+ };
881
+ [root addSubview:self.petView];
882
+
883
+ NSSize quotaSize = NSMakeSize(QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale);
884
+ self.quotaPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)
885
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
886
+ backing:NSBackingStoreBuffered defer:NO];
887
+ self.quotaPanel.opaque = NO;
888
+ self.quotaPanel.backgroundColor = NSColor.clearColor;
889
+ self.quotaPanel.hasShadow = YES;
890
+ self.quotaPanel.acceptsMouseMovedEvents = YES;
891
+ self.quotaPanel.ignoresMouseEvents = NO;
892
+ self.quotaPanel.level = NSFloatingWindowLevel;
893
+ self.quotaPanel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
894
+ self.quotaPanel.hidesOnDeactivate = NO;
895
+ NSView *quotaRoot = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
896
+ NSVisualEffectView *glass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(0, 0,
897
+ quotaSize.width, quotaSize.height)];
898
+ glass.material = NSVisualEffectMaterialUnderWindowBackground;
899
+ glass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
900
+ glass.state = NSVisualEffectStateActive;
901
+ glass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
902
+ glass.wantsLayer = YES;
903
+ glass.layer.cornerRadius = 13;
904
+ glass.layer.masksToBounds = YES;
905
+ [quotaRoot addSubview:glass];
906
+ self.quotaView = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
907
+ self.quotaView.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
908
+ self.quotaView.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
909
+ self.quotaView.hoverChanged = ^(BOOL hovering) {
910
+ weakSelf.dashboardHovering = hovering;
911
+ if (!hovering) [weakSelf scheduleQuotaDashboardHide];
912
+ };
913
+ self.quotaView.refreshRequested = ^{
914
+ [weakSelf refreshUsage:nil];
915
+ };
916
+ [quotaRoot addSubview:self.quotaView];
917
+ self.quotaPanel.contentView = quotaRoot;
918
+
919
+ NSScreen *screen = NSScreen.mainScreen;
920
+ NSRect visible = screen.visibleFrame;
921
+ [self.panel setFrameOrigin:NSMakePoint(NSMaxX(visible) - size.width - 24, NSMinY(visible) + 18)];
922
+ [self.panel orderFrontRegardless];
923
+ [self refreshUsage:nil];
924
+ if ([NSProcessInfo.processInfo.arguments containsObject:@"--preview-dashboard"]) {
925
+ self.pocketHovering = YES;
926
+ [self showQuotaDashboard];
927
+ }
928
+ [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refreshUsage:) userInfo:nil repeats:YES];
929
+ [self refreshClientLifecycle:nil];
930
+ [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshClientLifecycle:) userInfo:nil repeats:YES];
931
+ [self prepareAgentEventReader];
932
+ [NSTimer scheduledTimerWithTimeInterval:0.15 target:self selector:@selector(pollAgentEvents:) userInfo:nil repeats:YES];
933
+ }
934
+ - (void)showQuotaDashboard {
935
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
936
+ [self refreshUsage:nil];
937
+ [self positionQuotaDashboard];
938
+ [self.quotaPanel orderFrontRegardless];
939
+ [self.panel orderFrontRegardless];
940
+ }
941
+ - (void)positionQuotaDashboard {
942
+ NSRect petFrame = self.panel.frame;
943
+ NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
944
+ NSSize size = self.quotaPanel.frame.size;
945
+ CGFloat x = NSMinX(petFrame) - size.width + 55;
946
+ CGFloat y = NSMinY(petFrame) + 112;
947
+ x = fmax(NSMinX(visible) + 12, fmin(x, NSMaxX(visible) - size.width - 12));
948
+ y = fmax(NSMinY(visible) + 12, fmin(y, NSMaxY(visible) - size.height - 12));
949
+ [self.quotaPanel setFrameOrigin:NSMakePoint(x, y)];
950
+ }
951
+ - (void)scheduleQuotaDashboardHide {
952
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
953
+ [self performSelector:@selector(hideQuotaDashboardIfNeeded) withObject:nil afterDelay:0.28];
954
+ }
955
+ - (void)hideQuotaDashboardIfNeeded {
956
+ if (!self.pocketHovering && !self.dashboardHovering && !self.petDragging) [self.quotaPanel orderOut:nil];
957
+ }
958
+ - (void)switchPetToID:(NSString *)petID {
959
+ NSArray<NSDictionary *> *options = [self discoverPetOptions];
960
+ NSDictionary *option = [self petOptionWithID:petID inOptions:options];
961
+ if (!option) return;
962
+ NSImage *image = [[NSImage alloc] initWithContentsOfFile:option[@"path"]];
963
+ if (!image) return;
964
+ [self.petView applySheet:image petID:petID];
965
+ [NSUserDefaults.standardUserDefaults setObject:petID forKey:@"CodexPetSelectedSprite"];
966
+ }
967
+ - (void)prepareAgentEventReader {
968
+ NSString *path = AgentEventPath();
969
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
970
+ unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
971
+ self.agentEventOffset = size;
972
+ if (size > 0) {
973
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
974
+ unsigned long long start = size > 65536 ? size - 65536 : 0;
975
+ [handle seekToFileOffset:start];
976
+ NSData *recent = [handle readDataToEndOfFile];
977
+ [handle closeFile];
978
+ [self processAgentEventData:recent ignoreFirstPartial:start > 0 recentOnly:YES];
979
+ }
980
+ }
981
+ - (void)processAgentEventData:(NSData *)data ignoreFirstPartial:(BOOL)ignoreFirstPartial recentOnly:(BOOL)recentOnly {
982
+ NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
983
+ if (!text) return;
984
+ NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
985
+ NSTimeInterval cutoff = [NSDate.date timeIntervalSince1970] - 5;
986
+ for (NSUInteger index = 0; index < lines.count; index++) {
987
+ if (ignoreFirstPartial && index == 0) continue;
988
+ NSData *lineData = [lines[index] dataUsingEncoding:NSUTF8StringEncoding];
989
+ if (lineData.length == 0) continue;
990
+ NSDictionary *record = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
991
+ if (![record isKindOfClass:NSDictionary.class]) continue;
992
+ if (recentOnly && [record[@"timestamp"] doubleValue] < cutoff) continue;
993
+ NSString *event = record[@"event"];
994
+ NSString *tool = record[@"tool"] ?: @"";
995
+ if ([event isKindOfClass:NSString.class]) {
996
+ [self.petView handleAgentEvent:event tool:tool failed:[record[@"failed"] boolValue]];
997
+ }
998
+ }
999
+ }
1000
+ - (void)pollAgentEvents:(id)sender {
1001
+ NSString *path = AgentEventPath();
1002
+ NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
1003
+ unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
1004
+ if (size < self.agentEventOffset) self.agentEventOffset = 0;
1005
+ if (size == self.agentEventOffset) return;
1006
+ NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1007
+ if (!handle) return;
1008
+ [handle seekToFileOffset:self.agentEventOffset];
1009
+ NSData *data = [handle readDataToEndOfFile];
1010
+ [handle closeFile];
1011
+ self.agentEventOffset = size;
1012
+ [self processAgentEventData:data ignoreFirstPartial:NO recentOnly:NO];
1013
+ }
1014
+ - (void)refreshClientLifecycle:(id)sender {
1015
+ NSString *clientName = [NSString stringWithFormat:@"codex-pet-%u-clients", getuid()];
1016
+ NSString *clientDirectory = [PetStateDirectory() stringByAppendingPathComponent:clientName];
1017
+ NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
1018
+ NSInteger liveClients = 0;
1019
+ for (NSString *entry in entries) {
1020
+ pid_t pid = (pid_t)entry.intValue;
1021
+ BOOL alive = pid > 1 && (kill(pid, 0) == 0 || errno == EPERM);
1022
+ if (alive) {
1023
+ liveClients += 1;
1024
+ } else {
1025
+ NSString *stale = [clientDirectory stringByAppendingPathComponent:entry];
1026
+ [NSFileManager.defaultManager removeItemAtPath:stale error:nil];
1027
+ }
1028
+ }
1029
+ if (liveClients > 0) self.managedByCLI = YES;
1030
+ else if (self.managedByCLI) [NSApp terminate:nil];
1031
+ }
1032
+ - (void)refreshUsage:(id)sender {
1033
+ self.quotaView.codexUsage = LatestUsage();
1034
+ self.quotaView.claudeUsage = LatestClaudeUsage();
1035
+ self.quotaView.needsDisplay = YES;
1036
+ }
1037
+ @end
1038
+
1039
+ int main(int argc, const char *argv[]) {
1040
+ @autoreleasepool {
1041
+ if (argc > 1 && strcmp(argv[1], "--hook") == 0) return RecordHookEvent();
1042
+ if (argc > 1 && strcmp(argv[1], "--claude-usage") == 0) return RecordClaudeUsage();
1043
+ if (argc > 2 && strcmp(argv[1], "--render-dashboard") == 0) {
1044
+ return RenderQuotaDashboard([NSString stringWithUTF8String:argv[2]]);
1045
+ }
1046
+ if (argc > 1 && strcmp(argv[1], "--status") == 0) {
1047
+ NSDictionary *usage = LatestUsage();
1048
+ if (!usage) {
1049
+ puts("Codex usage unavailable");
1050
+ return EXIT_FAILURE;
1051
+ }
1052
+ NSDictionary *fiveHour = (id)usage[@"fiveHour"] == NSNull.null ? nil : usage[@"fiveHour"];
1053
+ NSDictionary *week = (id)usage[@"week"] == NSNull.null ? nil : usage[@"week"];
1054
+ printf("five_hour=%s week=%s\n",
1055
+ fiveHour ? [[[fiveHour[@"used_percent"] stringValue] stringByAppendingString:@"%"] UTF8String] : "--",
1056
+ week ? [[[week[@"used_percent"] stringValue] stringByAppendingString:@"%"] UTF8String] : "--");
1057
+ return EXIT_SUCCESS;
1058
+ }
1059
+
1060
+ NSString *lockName = [NSString stringWithFormat:@"codex-pet-%u.lock", getuid()];
1061
+ NSString *lockPath = [PetStateDirectory() stringByAppendingPathComponent:lockName];
1062
+ int lock = open(lockPath.fileSystemRepresentation, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
1063
+ if (lock < 0 || flock(lock, LOCK_EX | LOCK_NB) != 0) return EXIT_SUCCESS;
1064
+
1065
+ NSApplication *app = NSApplication.sharedApplication;
1066
+ AppDelegate *delegate = [AppDelegate new];
1067
+ app.delegate = delegate;
1068
+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];
1069
+ [app run];
1070
+ (void)lock;
1071
+ }
1072
+ return EXIT_SUCCESS;
1073
+ }