cc-pets 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Sources/CCPets/CCPetsAppDelegate.h +52 -0
- package/Sources/CCPets/CCPetsAppDelegate.m +1104 -0
- package/Sources/CCPets/CCPetsEvents.h +10 -0
- package/Sources/CCPets/CCPetsEvents.m +232 -0
- package/Sources/CCPets/CCPetsPaths.h +23 -0
- package/Sources/CCPets/CCPetsPaths.m +48 -0
- package/Sources/CCPets/CCPetsPreviews.h +6 -0
- package/Sources/CCPets/CCPetsPreviews.m +159 -0
- package/Sources/CCPets/CCPetsQuotaHistory.h +7 -0
- package/Sources/CCPets/CCPetsQuotaHistory.m +83 -0
- package/Sources/CCPets/CCPetsUsage.h +17 -0
- package/Sources/CCPets/CCPetsUsage.m +276 -0
- package/Sources/CCPets/CCPetsVersion.h +10 -0
- package/Sources/CCPets/CCPetsVersion.m +62 -0
- package/Sources/CCPets/MenuToggleSwitch.h +5 -0
- package/Sources/CCPets/MenuToggleSwitch.m +47 -0
- package/Sources/CCPets/PetView.h +33 -0
- package/Sources/CCPets/PetView.m +478 -0
- package/Sources/CCPets/QuotaDashboardView.h +23 -0
- package/Sources/CCPets/QuotaDashboardView.m +318 -0
- package/Sources/CCPets/main.m +7 -2528
- package/bin/claude-with-pet +2 -1
- package/bin/codex-with-pet +3 -1
- package/package.json +2 -3
- package/scripts/build.sh +18 -1
- package/scripts/install-git-hooks.sh +47 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
// Agent 事件的记录与状态归一化,同时是 --hook / --provider-event 两个子命令的实现。
|
|
4
|
+
NSString *SanitizedShortString(id value, NSUInteger maximumLength);
|
|
5
|
+
NSString *ProviderFromEnvironment(void);
|
|
6
|
+
NSString *NormalizedStateForEvent(NSString *event, BOOL failed);
|
|
7
|
+
BOOL AppendAgentEventRecord(NSDictionary *record);
|
|
8
|
+
BOOL HookValueIndicatesFailure(id value);
|
|
9
|
+
int RecordHookEvent(void);
|
|
10
|
+
int RecordProviderEvent(void);
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
#import "CCPetsEvents.h"
|
|
2
|
+
#import "CCPetsPaths.h"
|
|
3
|
+
#import <sys/stat.h>
|
|
4
|
+
#import <fcntl.h>
|
|
5
|
+
#import <unistd.h>
|
|
6
|
+
|
|
7
|
+
NSString *SanitizedShortString(id value, NSUInteger maximumLength) {
|
|
8
|
+
if (![value isKindOfClass:NSString.class]) return @"";
|
|
9
|
+
NSString *text = [(NSString *)value stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
|
10
|
+
if (text.length == 0) return @"";
|
|
11
|
+
NSMutableString *safe = [NSMutableString stringWithCapacity:MIN(text.length, maximumLength)];
|
|
12
|
+
NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:
|
|
13
|
+
@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._- "];
|
|
14
|
+
for (NSUInteger index = 0; index < text.length && safe.length < maximumLength; index++) {
|
|
15
|
+
unichar character = [text characterAtIndex:index];
|
|
16
|
+
if ([allowed characterIsMember:character]) [safe appendFormat:@"%C", character];
|
|
17
|
+
}
|
|
18
|
+
return [safe stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
NSString *ProviderFromEnvironment(void) {
|
|
22
|
+
NSDictionary<NSString *, NSString *> *environment = NSProcessInfo.processInfo.environment;
|
|
23
|
+
if ([environment[@"CC_PETS_CODEX_AGENT_HOOK"] boolValue]) return @"Codex";
|
|
24
|
+
if ([environment[@"CC_PETS_CLAUDE_AGENT_HOOK"] boolValue]) return @"Claude";
|
|
25
|
+
return @"Agent";
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
static BOOL CodexAutoReviewEnabled(void) {
|
|
29
|
+
NSDictionary<NSString *, NSString *> *environment = NSProcessInfo.processInfo.environment;
|
|
30
|
+
NSString *codexHome = environment[@"CODEX_HOME"];
|
|
31
|
+
if (![codexHome isKindOfClass:NSString.class] || codexHome.length == 0) {
|
|
32
|
+
codexHome = [NSHomeDirectory() stringByAppendingPathComponent:@".codex"];
|
|
33
|
+
}
|
|
34
|
+
NSString *configPath = [codexHome stringByAppendingPathComponent:@"config.toml"];
|
|
35
|
+
NSString *contents = [NSString stringWithContentsOfFile:configPath
|
|
36
|
+
encoding:NSUTF8StringEncoding error:nil];
|
|
37
|
+
if (contents.length == 0) return NO;
|
|
38
|
+
|
|
39
|
+
__block BOOL topLevel = YES;
|
|
40
|
+
__block BOOL enabled = NO;
|
|
41
|
+
[contents enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
|
|
42
|
+
NSString *trimmed = [line stringByTrimmingCharactersInSet:
|
|
43
|
+
NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
|
44
|
+
if (trimmed.length == 0 || [trimmed hasPrefix:@"#"]) return;
|
|
45
|
+
if ([trimmed hasPrefix:@"["]) {
|
|
46
|
+
topLevel = NO;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (!topLevel) return;
|
|
50
|
+
NSRange equals = [trimmed rangeOfString:@"="];
|
|
51
|
+
if (equals.location == NSNotFound) return;
|
|
52
|
+
NSString *key = [[trimmed substringToIndex:equals.location]
|
|
53
|
+
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
|
|
54
|
+
if (![key isEqualToString:@"approvals_reviewer"]) return;
|
|
55
|
+
NSString *value = [[trimmed substringFromIndex:equals.location + 1]
|
|
56
|
+
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
|
|
57
|
+
NSRange comment = [value rangeOfString:@"#"];
|
|
58
|
+
if (comment.location != NSNotFound) {
|
|
59
|
+
value = [[value substringToIndex:comment.location]
|
|
60
|
+
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
|
|
61
|
+
}
|
|
62
|
+
if (value.length >= 2) {
|
|
63
|
+
unichar first = [value characterAtIndex:0];
|
|
64
|
+
unichar last = [value characterAtIndex:value.length - 1];
|
|
65
|
+
if ((first == '"' && last == '"') || (first == '\'' && last == '\'')) {
|
|
66
|
+
value = [value substringWithRange:NSMakeRange(1, value.length - 2)];
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
enabled = [value isEqualToString:@"auto_review"];
|
|
70
|
+
*stop = YES;
|
|
71
|
+
}];
|
|
72
|
+
return enabled;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
NSString *NormalizedStateForEvent(NSString *event, BOOL failed) {
|
|
76
|
+
if ([event isEqualToString:@"StopFailure"]) return @"failed";
|
|
77
|
+
if (failed || [event isEqualToString:@"PostToolUseFailure"]) return @"tool_failed";
|
|
78
|
+
if ([event isEqualToString:@"SessionStart"]) return @"starting";
|
|
79
|
+
if ([event isEqualToString:@"UserPromptSubmit"]) return @"thinking";
|
|
80
|
+
if ([event isEqualToString:@"PermissionRequest"]) return @"approval";
|
|
81
|
+
if ([event isEqualToString:@"PreToolUse"]) return @"tool";
|
|
82
|
+
if ([event isEqualToString:@"SubagentStart"] || [event isEqualToString:@"TaskCreated"]) return @"subagent";
|
|
83
|
+
if ([event isEqualToString:@"PostToolUse"] || [event isEqualToString:@"SubagentStop"] ||
|
|
84
|
+
[event isEqualToString:@"TaskCompleted"]) return @"thinking";
|
|
85
|
+
if ([event isEqualToString:@"Stop"] || [event isEqualToString:@"SessionEnd"]) return @"completed";
|
|
86
|
+
if ([event isEqualToString:@"Notification"]) return @"notification";
|
|
87
|
+
return @"thinking";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
static const off_t AgentEventLogSizeLimit = 4 * 1024 * 1024;
|
|
91
|
+
|
|
92
|
+
BOOL AppendAgentEventRecord(NSDictionary *record) {
|
|
93
|
+
NSData *json = [NSJSONSerialization dataWithJSONObject:record options:0 error:nil];
|
|
94
|
+
if (!json) return NO;
|
|
95
|
+
// JSON 和换行必须一次 write 写完:O_APPEND 只保证单次 write 的原子性,
|
|
96
|
+
// 拆成两次的话,Codex 与 Claude 的 hook 同时触发就可能交错成
|
|
97
|
+
// “json1 json2 \n \n”,坏行会被读取端整行丢弃,桌宠漏掉一次状态切换。
|
|
98
|
+
NSMutableData *line = [NSMutableData dataWithCapacity:json.length + 1];
|
|
99
|
+
[line appendData:json];
|
|
100
|
+
[line appendBytes:"\n" length:1];
|
|
101
|
+
int descriptor = open(AgentEventPath().fileSystemRepresentation,
|
|
102
|
+
O_CREAT | O_WRONLY | O_APPEND | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR);
|
|
103
|
+
if (descriptor < 0) return NO;
|
|
104
|
+
// 事件文件只被追加、从不回收。超过上限就整体截断重来:读取端已经能处理
|
|
105
|
+
// “文件变短”(size < offset 时重置偏移),所以截断是安全的。
|
|
106
|
+
struct stat status;
|
|
107
|
+
if (fstat(descriptor, &status) == 0 && status.st_size > AgentEventLogSizeLimit) {
|
|
108
|
+
ftruncate(descriptor, 0);
|
|
109
|
+
}
|
|
110
|
+
BOOL succeeded = write(descriptor, line.bytes, line.length) == (ssize_t)line.length;
|
|
111
|
+
close(descriptor);
|
|
112
|
+
return succeeded;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 只有 NSNumber / NSString 响应 -boolValue。原实现直接对 dictionary[@"is_error"]
|
|
116
|
+
// 取 boolValue,遇到 "is_error": null 就是对 NSNull 发未实现的选择子,直接崩。
|
|
117
|
+
static BOOL HookFlagIsTruthy(id value, BOOL *present) {
|
|
118
|
+
if ([value isKindOfClass:NSNumber.class] || [value isKindOfClass:NSString.class]) {
|
|
119
|
+
if (present) *present = YES;
|
|
120
|
+
return [value boolValue];
|
|
121
|
+
}
|
|
122
|
+
if (present) *present = NO;
|
|
123
|
+
return NO;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
static const NSUInteger HookFailureMaximumDepth = 4;
|
|
127
|
+
|
|
128
|
+
static BOOL HookValueIndicatesFailureAtDepth(id value, NSUInteger depth) {
|
|
129
|
+
if (depth > HookFailureMaximumDepth) return NO;
|
|
130
|
+
if ([value isKindOfClass:NSDictionary.class]) {
|
|
131
|
+
NSDictionary *dictionary = value;
|
|
132
|
+
BOOL present = NO;
|
|
133
|
+
if (HookFlagIsTruthy(dictionary[@"is_error"], &present) && present) return YES;
|
|
134
|
+
BOOL success = HookFlagIsTruthy(dictionary[@"success"], &present);
|
|
135
|
+
if (present && !success) return YES;
|
|
136
|
+
NSString *status = [dictionary[@"status"] isKindOfClass:NSString.class]
|
|
137
|
+
? [(NSString *)dictionary[@"status"] lowercaseString] : nil;
|
|
138
|
+
if ([status isEqualToString:@"error"] || [status isEqualToString:@"failed"] ||
|
|
139
|
+
[status isEqualToString:@"failure"]) return YES;
|
|
140
|
+
// 原实现还有一条 `dictionary[@"error"] != nil` 判定,任意层级只要出现一个非空
|
|
141
|
+
// error 键就整体判失败——诊断数组、返回体里的 error 字段都会误命中,导致
|
|
142
|
+
// 任务成功却播失败动画并弹“任务失败”通知。这里只认上面几个显式信号。
|
|
143
|
+
for (id child in dictionary.allValues) {
|
|
144
|
+
if (HookValueIndicatesFailureAtDepth(child, depth + 1)) return YES;
|
|
145
|
+
}
|
|
146
|
+
} else if ([value isKindOfClass:NSArray.class]) {
|
|
147
|
+
for (id child in value) {
|
|
148
|
+
if (HookValueIndicatesFailureAtDepth(child, depth + 1)) return YES;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return NO;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// 深度上限防止深嵌套 JSON 递归爆栈。
|
|
155
|
+
BOOL HookValueIndicatesFailure(id value) {
|
|
156
|
+
return HookValueIndicatesFailureAtDepth(value, 0);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
int RecordHookEvent(void) {
|
|
160
|
+
NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
|
|
161
|
+
NSDictionary *payload = input.length > 0 ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
|
|
162
|
+
if (![payload isKindOfClass:NSDictionary.class]) return EXIT_SUCCESS;
|
|
163
|
+
NSString *event = payload[@"hook_event_name"];
|
|
164
|
+
if (![event isKindOfClass:NSString.class] || event.length == 0) return EXIT_SUCCESS;
|
|
165
|
+
NSString *tool = [payload[@"tool_name"] isKindOfClass:NSString.class] ? payload[@"tool_name"] : @"";
|
|
166
|
+
NSString *session = SanitizedShortString(payload[@"session_id"], 128);
|
|
167
|
+
id toolResult = payload[@"tool_response"] ?: payload[@"tool_result"];
|
|
168
|
+
BOOL failed = [event isEqualToString:@"PostToolUseFailure"] ||
|
|
169
|
+
[event isEqualToString:@"StopFailure"] || HookValueIndicatesFailure(toolResult);
|
|
170
|
+
NSString *provider = ProviderFromEnvironment();
|
|
171
|
+
BOOL autoReview = [provider isEqualToString:@"Codex"] &&
|
|
172
|
+
[event isEqualToString:@"PermissionRequest"] && CodexAutoReviewEnabled();
|
|
173
|
+
NSMutableDictionary *record = [@{
|
|
174
|
+
@"event": event,
|
|
175
|
+
@"tool": tool,
|
|
176
|
+
@"failed": @(failed),
|
|
177
|
+
@"provider": provider,
|
|
178
|
+
@"state": autoReview ? @"auto_review" : NormalizedStateForEvent(event, failed),
|
|
179
|
+
@"timestamp": @([NSDate.date timeIntervalSince1970])
|
|
180
|
+
} mutableCopy];
|
|
181
|
+
if (session.length > 0) record[@"session"] = session;
|
|
182
|
+
AppendAgentEventRecord(record);
|
|
183
|
+
return EXIT_SUCCESS;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
int RecordProviderEvent(void) {
|
|
187
|
+
NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
|
|
188
|
+
NSDictionary *payload = input.length > 0
|
|
189
|
+
? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
|
|
190
|
+
if (![payload isKindOfClass:NSDictionary.class] ||
|
|
191
|
+
![payload[@"schemaVersion"] isKindOfClass:NSNumber.class] ||
|
|
192
|
+
[payload[@"schemaVersion"] integerValue] != 1) {
|
|
193
|
+
fprintf(stderr, "provider-event 需要 schemaVersion 为 1 的 JSON 对象。\n");
|
|
194
|
+
return 2;
|
|
195
|
+
}
|
|
196
|
+
NSString *provider = SanitizedShortString(payload[@"provider"], 32);
|
|
197
|
+
NSString *state = SanitizedShortString(payload[@"state"], 32).lowercaseString;
|
|
198
|
+
NSString *tool = SanitizedShortString(payload[@"tool"], 64);
|
|
199
|
+
NSSet<NSString *> *states = [NSSet setWithArray:@[
|
|
200
|
+
@"starting", @"thinking", @"tool", @"approval", @"subagent",
|
|
201
|
+
@"tool_completed", @"tool_failed", @"completed", @"failed", @"notification"
|
|
202
|
+
]];
|
|
203
|
+
if (provider.length == 0 || ![states containsObject:state]) {
|
|
204
|
+
fprintf(stderr, "provider-event 的 provider 或 state 无效。\n");
|
|
205
|
+
return 2;
|
|
206
|
+
}
|
|
207
|
+
NSDictionary<NSString *, NSString *> *events = @{
|
|
208
|
+
@"starting": @"SessionStart",
|
|
209
|
+
@"thinking": @"UserPromptSubmit",
|
|
210
|
+
@"tool": @"PreToolUse",
|
|
211
|
+
@"approval": @"PermissionRequest",
|
|
212
|
+
@"subagent": @"SubagentStart",
|
|
213
|
+
@"tool_completed": @"PostToolUse",
|
|
214
|
+
@"tool_failed": @"PostToolUseFailure",
|
|
215
|
+
@"completed": @"Stop",
|
|
216
|
+
@"failed": @"StopFailure",
|
|
217
|
+
@"notification": @"Notification"
|
|
218
|
+
};
|
|
219
|
+
NSDictionary *record = @{
|
|
220
|
+
@"event": events[state],
|
|
221
|
+
@"tool": tool,
|
|
222
|
+
@"failed": @([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]),
|
|
223
|
+
@"provider": provider,
|
|
224
|
+
@"state": state,
|
|
225
|
+
@"timestamp": @([NSDate.date timeIntervalSince1970])
|
|
226
|
+
};
|
|
227
|
+
if (!AppendAgentEventRecord(record)) {
|
|
228
|
+
fprintf(stderr, "无法写入 Provider 事件。\n");
|
|
229
|
+
return EXIT_FAILURE;
|
|
230
|
+
}
|
|
231
|
+
return EXIT_SUCCESS;
|
|
232
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
// 状态文件与配置目录。所有路径都可以通过环境变量覆盖,测试依赖这一点做隔离。
|
|
4
|
+
NSString *PetStateDirectory(void);
|
|
5
|
+
NSString *AgentEventPath(void);
|
|
6
|
+
NSString *ClaudeUsagePath(void);
|
|
7
|
+
NSString *ApplicationSupportDirectory(void);
|
|
8
|
+
NSString *QuotaHistoryPath(void);
|
|
9
|
+
|
|
10
|
+
extern NSString *const HistoryEnabledKey;
|
|
11
|
+
extern NSString *const NotificationCompletionKey;
|
|
12
|
+
extern NSString *const NotificationFailureKey;
|
|
13
|
+
extern NSString *const NotificationApprovalKey;
|
|
14
|
+
extern NSString *const StatusBubbleExpandedKey;
|
|
15
|
+
extern NSString *const StatusBubblePreferenceV2Key;
|
|
16
|
+
|
|
17
|
+
extern const NSTimeInterval AgentStatusInactivityInterval;
|
|
18
|
+
extern const NSTimeInterval AgentStatusOrphanInterval;
|
|
19
|
+
extern const NSTimeInterval UsageRefreshIntervalVisible;
|
|
20
|
+
extern const NSTimeInterval UsageRefreshIntervalHidden;
|
|
21
|
+
extern const NSTimeInterval ClientLifecycleInterval;
|
|
22
|
+
extern const NSTimeInterval AgentEventReaderCheckInterval;
|
|
23
|
+
extern const NSTimeInterval PetFrameInterval;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
#import "CCPetsPaths.h"
|
|
2
|
+
|
|
3
|
+
NSString *PetStateDirectory(void) {
|
|
4
|
+
NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_STATE_DIR"];
|
|
5
|
+
if (override.length > 0) return override.stringByStandardizingPath;
|
|
6
|
+
return NSTemporaryDirectory();
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
NSString *AgentEventPath(void) {
|
|
10
|
+
NSString *name = [NSString stringWithFormat:@"cc-pets-%u-agent-events.ndjson", getuid()];
|
|
11
|
+
return [PetStateDirectory() stringByAppendingPathComponent:name];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
NSString *ClaudeUsagePath(void) {
|
|
15
|
+
NSString *name = [NSString stringWithFormat:@"cc-pets-%u-claude-usage.json", getuid()];
|
|
16
|
+
return [PetStateDirectory() stringByAppendingPathComponent:name];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
NSString *ApplicationSupportDirectory(void) {
|
|
20
|
+
NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_APPLICATION_SUPPORT_DIR"];
|
|
21
|
+
if (override.length > 0) return override.stringByStandardizingPath;
|
|
22
|
+
NSString *root = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject;
|
|
23
|
+
return [root stringByAppendingPathComponent:@"CC Pets"];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
NSString *QuotaHistoryPath(void) {
|
|
27
|
+
return [ApplicationSupportDirectory() stringByAppendingPathComponent:@"quota-history.json"];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
NSString *const HistoryEnabledKey = @"CCPetsQuotaHistoryEnabled";
|
|
31
|
+
NSString *const NotificationCompletionKey = @"CCPetsNotifyCompletion";
|
|
32
|
+
NSString *const NotificationFailureKey = @"CCPetsNotifyFailure";
|
|
33
|
+
NSString *const NotificationApprovalKey = @"CCPetsNotifyApproval";
|
|
34
|
+
NSString *const StatusBubbleExpandedKey = @"CCPetsStatusBubbleExpanded";
|
|
35
|
+
NSString *const StatusBubblePreferenceV2Key = @"CCPetsStatusBubblePreferenceV2";
|
|
36
|
+
const NSTimeInterval AgentStatusInactivityInterval = 60.0;
|
|
37
|
+
// 客户端进程已经消失、但状态气泡还停在它最后一条事件上时,多等这么久再清场。
|
|
38
|
+
// 留这段宽限是因为不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid
|
|
39
|
+
// 文件,只能靠"最近还在发事件"证明自己活着,不能一看不到 pid 文件就清掉。
|
|
40
|
+
const NSTimeInterval AgentStatusOrphanInterval = 10.0;
|
|
41
|
+
// 额度面板不可见时没人看这些数字,降到 60 秒;打开面板时 showQuotaDashboard 会
|
|
42
|
+
// 立刻刷新一次,所以降频对显示的新鲜度没有影响。
|
|
43
|
+
const NSTimeInterval UsageRefreshIntervalVisible = 5.0;
|
|
44
|
+
const NSTimeInterval UsageRefreshIntervalHidden = 60.0;
|
|
45
|
+
const NSTimeInterval ClientLifecycleInterval = 3.0;
|
|
46
|
+
const NSTimeInterval AgentEventReaderCheckInterval = 5.0;
|
|
47
|
+
// 精灵动画帧间隔。定时器的 tolerance 让内核可以合并唤醒。
|
|
48
|
+
const NSTimeInterval PetFrameInterval = 0.22;
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
#import "CCPetsPreviews.h"
|
|
2
|
+
#import "QuotaDashboardView.h"
|
|
3
|
+
#import "MenuToggleSwitch.h"
|
|
4
|
+
#import "CCPetsUsage.h"
|
|
5
|
+
#import <Cocoa/Cocoa.h>
|
|
6
|
+
|
|
7
|
+
int RenderQuotaDashboard(NSString *path) {
|
|
8
|
+
[NSApplication sharedApplication];
|
|
9
|
+
QuotaDashboardView *view = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0,
|
|
10
|
+
QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale)];
|
|
11
|
+
view.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
|
|
12
|
+
view.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
|
|
13
|
+
view.codexUsage = LatestUsage() ?: @{
|
|
14
|
+
@"fiveHour": @{@"used_percent": @34, @"resets_at": @([NSDate.date timeIntervalSince1970] + 7200)},
|
|
15
|
+
@"week": @{@"used_percent": @51, @"resets_at": @([NSDate.date timeIntervalSince1970] + 172800)}
|
|
16
|
+
};
|
|
17
|
+
view.claudeUsage = LatestClaudeUsage() ?: @{
|
|
18
|
+
@"fiveHour": @{@"used_percentage": @23, @"resets_at": @([NSDate.date timeIntervalSince1970] + 3600)},
|
|
19
|
+
@"week": @{@"used_percentage": @41, @"resets_at": @([NSDate.date timeIntervalSince1970] + 86400)}
|
|
20
|
+
};
|
|
21
|
+
view.historyEnabled = YES;
|
|
22
|
+
view.codexHistory = @[@88, @81, @75, @68, @62, @55, @49];
|
|
23
|
+
view.claudeHistory = @[@92, @86, @78, @72, @64, @58, @51];
|
|
24
|
+
NSInteger pixelWidth = (NSInteger)ceil(NSWidth(view.bounds));
|
|
25
|
+
NSInteger pixelHeight = (NSInteger)ceil(NSHeight(view.bounds));
|
|
26
|
+
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
|
|
27
|
+
initWithBitmapDataPlanes:NULL
|
|
28
|
+
pixelsWide:pixelWidth
|
|
29
|
+
pixelsHigh:pixelHeight
|
|
30
|
+
bitsPerSample:8
|
|
31
|
+
samplesPerPixel:4
|
|
32
|
+
hasAlpha:YES
|
|
33
|
+
isPlanar:NO
|
|
34
|
+
colorSpaceName:NSDeviceRGBColorSpace
|
|
35
|
+
bytesPerRow:0
|
|
36
|
+
bitsPerPixel:0];
|
|
37
|
+
bitmap.size = view.bounds.size;
|
|
38
|
+
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
|
|
39
|
+
[NSGraphicsContext saveGraphicsState];
|
|
40
|
+
NSGraphicsContext.currentContext = context;
|
|
41
|
+
[view displayRectIgnoringOpacity:view.bounds inContext:context];
|
|
42
|
+
[NSGraphicsContext restoreGraphicsState];
|
|
43
|
+
NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
|
44
|
+
return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
int RenderAgentStatusCard(NSString *path) {
|
|
48
|
+
[NSApplication sharedApplication];
|
|
49
|
+
NSSize glassSize = NSMakeSize(340, 58);
|
|
50
|
+
NSSize size = NSMakeSize(glassSize.width + 12, glassSize.height + 12);
|
|
51
|
+
NSView *root = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
|
|
52
|
+
NSView *shadowView = [[NSView alloc] initWithFrame:NSMakeRect(
|
|
53
|
+
6, 6, glassSize.width, glassSize.height)];
|
|
54
|
+
shadowView.wantsLayer = YES;
|
|
55
|
+
shadowView.layer.backgroundColor = [NSColor colorWithWhite:0 alpha:0.01].CGColor;
|
|
56
|
+
shadowView.layer.cornerRadius = glassSize.height / 2.0;
|
|
57
|
+
shadowView.layer.cornerCurve = kCACornerCurveContinuous;
|
|
58
|
+
shadowView.layer.shadowColor = NSColor.blackColor.CGColor;
|
|
59
|
+
shadowView.layer.shadowOpacity = 0.24;
|
|
60
|
+
shadowView.layer.shadowRadius = 8;
|
|
61
|
+
shadowView.layer.shadowOffset = NSMakeSize(0, -3);
|
|
62
|
+
CGPathRef shadowPath = CGPathCreateWithRoundedRect(shadowView.bounds,
|
|
63
|
+
glassSize.height / 2.0, glassSize.height / 2.0, NULL);
|
|
64
|
+
shadowView.layer.shadowPath = shadowPath;
|
|
65
|
+
CGPathRelease(shadowPath);
|
|
66
|
+
[root addSubview:shadowView];
|
|
67
|
+
|
|
68
|
+
NSVisualEffectView *glass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(
|
|
69
|
+
6, 6, glassSize.width, glassSize.height)];
|
|
70
|
+
glass.material = NSVisualEffectMaterialPopover;
|
|
71
|
+
glass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
|
|
72
|
+
glass.state = NSVisualEffectStateActive;
|
|
73
|
+
glass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
|
|
74
|
+
glass.wantsLayer = YES;
|
|
75
|
+
glass.layer.cornerRadius = glassSize.height / 2.0;
|
|
76
|
+
glass.layer.cornerCurve = kCACornerCurveContinuous;
|
|
77
|
+
glass.layer.masksToBounds = YES;
|
|
78
|
+
glass.layer.borderWidth = 1;
|
|
79
|
+
glass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
|
|
80
|
+
[root addSubview:glass];
|
|
81
|
+
|
|
82
|
+
NSTextField *title = [NSTextField labelWithString:@"Codex · 任务已完成"];
|
|
83
|
+
title.frame = NSMakeRect(20, 30, glassSize.width - 80, 18);
|
|
84
|
+
title.font = [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold];
|
|
85
|
+
title.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
|
|
86
|
+
[glass addSubview:title];
|
|
87
|
+
NSTextField *detail = [NSTextField labelWithString:@"好的,当前任务已经完成。"];
|
|
88
|
+
detail.frame = NSMakeRect(20, 12, glassSize.width - 80, 17);
|
|
89
|
+
detail.font = [NSFont systemFontOfSize:12 weight:NSFontWeightRegular];
|
|
90
|
+
detail.textColor = [NSColor colorWithWhite:0.34 alpha:0.88];
|
|
91
|
+
[glass addSubview:detail];
|
|
92
|
+
|
|
93
|
+
NSButton *icon = [[NSButton alloc] initWithFrame:NSMakeRect(glassSize.width - 48, 12, 34, 34)];
|
|
94
|
+
icon.bordered = NO;
|
|
95
|
+
icon.imagePosition = NSImageOnly;
|
|
96
|
+
icon.wantsLayer = YES;
|
|
97
|
+
icon.layer.cornerRadius = 17;
|
|
98
|
+
icon.layer.masksToBounds = YES;
|
|
99
|
+
NSColor *green = [NSColor colorWithRed:0.18 green:0.68 blue:0.35 alpha:1];
|
|
100
|
+
icon.layer.backgroundColor = [green colorWithAlphaComponent:0.28].CGColor;
|
|
101
|
+
NSImage *image = [NSImage imageWithSystemSymbolName:@"checkmark"
|
|
102
|
+
accessibilityDescription:@"任务已完成"];
|
|
103
|
+
icon.image = [image imageWithSymbolConfiguration:
|
|
104
|
+
[NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightBold]];
|
|
105
|
+
icon.contentTintColor = [green blendedColorWithFraction:0.18
|
|
106
|
+
ofColor:NSColor.blackColor] ?: green;
|
|
107
|
+
[glass addSubview:icon];
|
|
108
|
+
|
|
109
|
+
NSInteger pixelWidth = (NSInteger)ceil(size.width);
|
|
110
|
+
NSInteger pixelHeight = (NSInteger)ceil(size.height);
|
|
111
|
+
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
|
|
112
|
+
initWithBitmapDataPlanes:NULL pixelsWide:pixelWidth pixelsHigh:pixelHeight
|
|
113
|
+
bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
|
|
114
|
+
colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
|
|
115
|
+
bitmap.size = size;
|
|
116
|
+
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
|
|
117
|
+
[NSGraphicsContext saveGraphicsState];
|
|
118
|
+
NSGraphicsContext.currentContext = context;
|
|
119
|
+
[root displayRectIgnoringOpacity:root.bounds inContext:context];
|
|
120
|
+
[NSGraphicsContext restoreGraphicsState];
|
|
121
|
+
NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
|
122
|
+
return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
int RenderMenuSwitches(NSString *path) {
|
|
126
|
+
[NSApplication sharedApplication];
|
|
127
|
+
NSSize size = NSMakeSize(220, 72);
|
|
128
|
+
NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
|
|
129
|
+
view.wantsLayer = YES;
|
|
130
|
+
view.layer.backgroundColor = [NSColor colorWithWhite:0.86 alpha:1].CGColor;
|
|
131
|
+
NSArray<NSDictionary *> *rows = @[
|
|
132
|
+
@{@"title": @"任务完成", @"state": @YES, @"y": @40},
|
|
133
|
+
@{@"title": @"任务失败", @"state": @NO, @"y": @10}
|
|
134
|
+
];
|
|
135
|
+
for (NSDictionary *row in rows) {
|
|
136
|
+
CGFloat y = [row[@"y"] doubleValue];
|
|
137
|
+
NSTextField *label = [NSTextField labelWithString:row[@"title"]];
|
|
138
|
+
label.frame = NSMakeRect(14, y + 3, 130, 18);
|
|
139
|
+
label.font = [NSFont menuFontOfSize:13];
|
|
140
|
+
label.textColor = NSColor.labelColor;
|
|
141
|
+
[view addSubview:label];
|
|
142
|
+
MenuToggleSwitch *toggle = [[MenuToggleSwitch alloc] initWithFrame:NSMakeRect(168, y, 36, 22)];
|
|
143
|
+
toggle.state = [row[@"state"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff;
|
|
144
|
+
[view addSubview:toggle];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
|
|
148
|
+
initWithBitmapDataPlanes:NULL pixelsWide:(NSInteger)size.width pixelsHigh:(NSInteger)size.height
|
|
149
|
+
bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
|
|
150
|
+
colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
|
|
151
|
+
bitmap.size = size;
|
|
152
|
+
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
|
|
153
|
+
[NSGraphicsContext saveGraphicsState];
|
|
154
|
+
NSGraphicsContext.currentContext = context;
|
|
155
|
+
[view displayRectIgnoringOpacity:view.bounds inContext:context];
|
|
156
|
+
[NSGraphicsContext restoreGraphicsState];
|
|
157
|
+
NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
|
158
|
+
return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
|
|
159
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
// 本地额度历史(默认关闭,由 HistoryEnabledKey 控制)。
|
|
4
|
+
// RecordQuotaHistory 返回当前文档,调用方直接复用,避免一轮刷新里重复读盘。
|
|
5
|
+
NSDictionary *QuotaHistoryDocument(void);
|
|
6
|
+
NSDictionary *RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage);
|
|
7
|
+
NSArray<NSNumber *> *QuotaHistorySeries(NSDictionary *document, NSString *provider);
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
#import "CCPetsQuotaHistory.h"
|
|
2
|
+
#import "CCPetsPaths.h"
|
|
3
|
+
#import <sys/stat.h>
|
|
4
|
+
|
|
5
|
+
static NSNumber *RemainingValue(NSDictionary *usage, NSString *quotaKey, NSString *usedKey) {
|
|
6
|
+
NSDictionary *quota = [usage[quotaKey] isKindOfClass:NSDictionary.class] ? usage[quotaKey] : nil;
|
|
7
|
+
NSNumber *used = [quota[usedKey] isKindOfClass:NSNumber.class] ? quota[usedKey] : nil;
|
|
8
|
+
if (!used) return nil;
|
|
9
|
+
return @(fmax(0, fmin(100, 100.0 - used.doubleValue)));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
NSDictionary *QuotaHistoryDocument(void) {
|
|
13
|
+
NSData *data = [NSData dataWithContentsOfFile:QuotaHistoryPath()];
|
|
14
|
+
NSDictionary *document = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
15
|
+
if (![document isKindOfClass:NSDictionary.class] ||
|
|
16
|
+
[document[@"schemaVersion"] integerValue] != 1 ||
|
|
17
|
+
![document[@"samples"] isKindOfClass:NSArray.class]) {
|
|
18
|
+
return @{@"schemaVersion": @1, @"samples": @[]};
|
|
19
|
+
}
|
|
20
|
+
return document;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
static NSDictionary *HistoryProviderSample(NSDictionary *usage, NSString *usedKey) {
|
|
24
|
+
NSNumber *fiveHour = RemainingValue(usage, @"fiveHour", usedKey);
|
|
25
|
+
NSNumber *week = RemainingValue(usage, @"week", usedKey);
|
|
26
|
+
NSMutableDictionary *sample = [NSMutableDictionary dictionary];
|
|
27
|
+
if (fiveHour) sample[@"fiveHourRemaining"] = fiveHour;
|
|
28
|
+
if (week) sample[@"weekRemaining"] = week;
|
|
29
|
+
return sample;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// 返回当前的历史文档,供调用方直接取用:原先每次刷新要读盘+解析三次
|
|
33
|
+
// (这里一次、两条曲线各一次),现在整轮只读一次。
|
|
34
|
+
NSDictionary *RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
|
|
35
|
+
NSDictionary *document = QuotaHistoryDocument();
|
|
36
|
+
if (![NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]) return document;
|
|
37
|
+
NSDictionary *codex = HistoryProviderSample(codexUsage, @"used_percent");
|
|
38
|
+
NSDictionary *claude = HistoryProviderSample(claudeUsage, @"used_percentage");
|
|
39
|
+
if (codex.count == 0 && claude.count == 0) return document;
|
|
40
|
+
|
|
41
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
42
|
+
NSTimeInterval cutoff = now - 7 * 24 * 60 * 60;
|
|
43
|
+
NSArray *existing = document[@"samples"];
|
|
44
|
+
NSMutableArray *samples = [NSMutableArray arrayWithCapacity:existing.count + 1];
|
|
45
|
+
for (NSDictionary *sample in existing) {
|
|
46
|
+
if (![sample isKindOfClass:NSDictionary.class] || [sample[@"timestamp"] doubleValue] < cutoff) continue;
|
|
47
|
+
[samples addObject:sample];
|
|
48
|
+
}
|
|
49
|
+
NSDictionary *last = samples.lastObject;
|
|
50
|
+
if (last && now - [last[@"timestamp"] doubleValue] < 15 * 60) return document;
|
|
51
|
+
|
|
52
|
+
NSMutableDictionary *sample = [@{@"timestamp": @(now)} mutableCopy];
|
|
53
|
+
if (codex.count > 0) sample[@"codex"] = codex;
|
|
54
|
+
if (claude.count > 0) sample[@"claude"] = claude;
|
|
55
|
+
[samples addObject:sample];
|
|
56
|
+
if (samples.count > 672) {
|
|
57
|
+
[samples removeObjectsInRange:NSMakeRange(0, samples.count - 672)];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
NSString *directory = QuotaHistoryPath().stringByDeletingLastPathComponent;
|
|
61
|
+
[NSFileManager.defaultManager createDirectoryAtPath:directory
|
|
62
|
+
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
63
|
+
NSDictionary *updated = @{@"schemaVersion": @1, @"samples": samples};
|
|
64
|
+
NSData *json = [NSJSONSerialization dataWithJSONObject:updated
|
|
65
|
+
options:NSJSONWritingPrettyPrinted error:nil];
|
|
66
|
+
if ([json writeToFile:QuotaHistoryPath() options:NSDataWritingAtomic error:nil]) {
|
|
67
|
+
chmod(QuotaHistoryPath().fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
68
|
+
}
|
|
69
|
+
return updated;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
NSArray<NSNumber *> *QuotaHistorySeries(NSDictionary *document, NSString *provider) {
|
|
73
|
+
NSMutableArray<NSNumber *> *series = [NSMutableArray array];
|
|
74
|
+
for (NSDictionary *sample in document[@"samples"]) {
|
|
75
|
+
if (![sample isKindOfClass:NSDictionary.class]) continue;
|
|
76
|
+
NSDictionary *providerSample = [sample[provider] isKindOfClass:NSDictionary.class]
|
|
77
|
+
? sample[provider] : nil;
|
|
78
|
+
NSNumber *remaining = [providerSample[@"weekRemaining"] isKindOfClass:NSNumber.class]
|
|
79
|
+
? providerSample[@"weekRemaining"] : nil;
|
|
80
|
+
if (remaining) [series addObject:remaining];
|
|
81
|
+
}
|
|
82
|
+
return series;
|
|
83
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
// Codex 与 Claude 的额度读取。
|
|
4
|
+
int RecordClaudeUsage(void);
|
|
5
|
+
NSDictionary *LatestClaudeUsage(void);
|
|
6
|
+
NSDictionary *LatestUsage(void);
|
|
7
|
+
|
|
8
|
+
// 增量跟读当前 Codex 会话文件:只在会话切换时做一次冷读,之后按偏移追读。
|
|
9
|
+
@interface CodexUsageReader : NSObject
|
|
10
|
+
@property NSURL *sessionsURL;
|
|
11
|
+
@property NSURL *sessionURL;
|
|
12
|
+
@property NSDictionary *usage;
|
|
13
|
+
@property unsigned long long offset;
|
|
14
|
+
@property NSMutableData *partialLine;
|
|
15
|
+
@property NSTimeInterval lastFullDiscovery;
|
|
16
|
+
- (NSDictionary *)refresh;
|
|
17
|
+
@end
|