cc-pets 0.2.17 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  本项目遵循语义化版本号。
4
4
 
5
+ ## [Unreleased]
6
+
7
+ - 新增可展开折叠的玻璃 Agent 状态卡片、活跃 CLI 会话数徽标和可选的完成、失败、审批系统通知。
8
+ - 历史记录与系统通知设置改用右侧高对比度迷你开关,支持在菜单保持展开时连续调整。
9
+ - 折叠圆钮固定锚定在桌宠头部右上区域,展开和折叠时不再跳动。
10
+ - Agent 连续 1 分钟没有新状态事件时,状态卡片和圆钮会自动隐藏。
11
+ - Codex/Claude 包装器会在启动桌宠前写入 Provider 启动事件,避免共享事件流导致启动瞬间显示错误来源。
12
+ - 工具或子 Agent 完成后,状态卡片会恢复为思考中;仅在当前回合真正结束时显示任务完成。
13
+ - 新增统一 Provider 事件协议,第三方 CLI Agent 可接入桌宠状态和动画。
14
+ - 新增默认关闭的本地额度历史,按 15 分钟采样并滚动保留 7 天趋势。
15
+
5
16
  ## [0.2.15] - 2026-07-24
6
17
 
7
18
  - 支持 Codex/PetDex `spriteVersionNumber: 2` 的 `8×11` 精灵图布局及十六向鼠标跟随。
@@ -0,0 +1,45 @@
1
+ # CC Pets Provider 事件协议
2
+
3
+ 第三方 CLI Agent 可以通过标准输入向 CC Pets 写入统一状态事件,从而复用状态气泡、
4
+ 桌宠动画和可选的系统通知。协议只接收状态类别和工具类别,不接收提示词、命令正文、
5
+ 文件内容或模型输出。
6
+
7
+ ## 发送事件
8
+
9
+ ```bash
10
+ printf '%s' '{
11
+ "schemaVersion": 1,
12
+ "provider": "MyAgent",
13
+ "state": "tool",
14
+ "tool": "shell"
15
+ }' | cc-pets provider-event
16
+ ```
17
+
18
+ `provider` 必填,最长 32 个字符,仅保留字母、数字、空格、`.`、`_` 和 `-`。
19
+ `tool` 可选,最长 64 个字符,仅用于选择脱敏后的状态文案和动画。
20
+
21
+ `state` 必须是下列值之一:
22
+
23
+ | state | 含义 |
24
+ | --- | --- |
25
+ | `starting` | 会话开始 |
26
+ | `thinking` | Agent 思考 |
27
+ | `tool` | 工具开始执行 |
28
+ | `approval` | 等待用户审批 |
29
+ | `subagent` | 子 Agent 工作中 |
30
+ | `tool_completed` | 单次工具执行完成 |
31
+ | `tool_failed` | 单次工具执行失败 |
32
+ | `completed` | 当前任务完成 |
33
+ | `failed` | 当前任务失败 |
34
+ | `notification` | 需要用户关注 |
35
+
36
+ 建议工具类别使用 `shell`、`edit`、`write`、`read`、`search`、`web`、`mcp` 或
37
+ `agent`。CC Pets 不会执行 `tool` 字段,也不会将其作为通知正文。
38
+
39
+ ## 生命周期
40
+
41
+ 事件写入当前用户的临时状态目录,已经运行的 CC Pets 会立即读取。Provider 集成需要自行
42
+ 负责启动和关闭 CC Pets;事件协议不会创建后台守护进程,也不会改变现有 Codex/Claude CLI
43
+ 的托管生命周期。
44
+
45
+ 协议版本不兼容或字段无效时,命令返回退出码 `2`;写入失败时返回非零退出码。
package/README.md CHANGED
@@ -12,6 +12,10 @@
12
12
  - 支持待机、左右拖动、身体两侧感应、头部/脚部悬停和点击反馈动画
13
13
  - 支持拖动桌宠位置,右键刷新用量、检查更新或退出
14
14
  - 响应 Codex 与 Claude Code Agent 的思考、工具调用、审批、子 Agent、完成和失败状态
15
+ - 在桌宠旁显示脱敏后的玻璃 Agent 状态卡片,可展开、折叠并显示活跃 CLI 会话数
16
+ - 支持第三方 CLI Agent 通过统一 Provider 事件协议接入动画和状态
17
+ - 可选记录最近 7 天的本地额度历史,并在额度卡片中显示趋势
18
+ - 可分别启用任务完成、失败和等待审批的 macOS 系统通知
15
19
  - 使用原生 AppKit,运行时不依赖 Electron
16
20
 
17
21
  ## 互动方式
@@ -52,7 +56,7 @@ Claude Code Hook 会合并到 `~/.claude/settings.json`,现有的 `env`、`mod
52
56
  | 按住并向右拖动 | 播放向右拖行动画,同时移动桌宠 |
53
57
  | 按住并向左拖动 | 播放向左拖行动画,同时移动桌宠 |
54
58
  | 鼠标移开或拖动结束 | 恢复默认待机动画 |
55
- | 右键桌宠 | 切换已有桌宠、刷新用量、检查更新或退出 |
59
+ | 右键桌宠 | 切换桌宠、刷新用量、设置历史/通知、检查更新或退出 |
56
60
 
57
61
  右键菜单中的“切换桌宠”会动态扫描 `~/.petdex/pets/`、`~/.codex/pets/` 以及包内素材。
58
62
  外部桌宠使用目录名作为菜单名称,内置桌宠使用素材文件名(不显示扩展名)。选择后立即
@@ -81,6 +85,17 @@ Agent 状态动画会优先播放。
81
85
  8. 点击反馈(6 帧)
82
86
  9. 身体左侧感应(6 帧)
83
87
 
88
+ 右键菜单中的“记录本地额度历史”默认关闭。启用后只在本机
89
+ `~/Library/Application Support/CC Pets/quota-history.json` 保存最近 7 天的数据,
90
+ 每 15 分钟最多记录一次。系统通知也默认关闭,可在“系统通知”子菜单中分别启用任务完成、
91
+ 任务失败和等待审批通知。
92
+
93
+ Agent 状态卡片会根据屏幕剩余空间自动显示在桌宠上方或下方。点击桌宠旁的圆形箭头可以
94
+ 折叠卡片;折叠后圆钮会显示当前活跃的 Codex/Claude CLI 会话数,点击后重新展开。卡片只展示
95
+ Provider、脱敏状态和通用说明,不提供消息输入,也不会显示提示词、命令正文或模型输出。
96
+ 连续 1 分钟没有收到新的 Agent 状态事件时,卡片和圆钮会一起自动隐藏;下一次收到事件时
97
+ 会重新显示并重新计时。
98
+
84
99
  ## 系统要求
85
100
 
86
101
  - macOS 13 或更高版本
@@ -184,6 +199,13 @@ cc-pets --version
184
199
  # 查看当前解析到的 Codex 额度
185
200
  cc-pets --status
186
201
 
202
+ # 查看本机额度历史 JSON
203
+ cc-pets --history
204
+
205
+ # 从标准输入发送第三方 Provider 状态事件
206
+ printf '%s' '{"schemaVersion":1,"provider":"MyAgent","state":"thinking"}' \
207
+ | cc-pets provider-event
208
+
187
209
  # 手动修复或重新初始化 Hooks、shell alias,并让已运行桌宠加载当前版本
188
210
  cc-pets install
189
211
 
@@ -226,6 +248,9 @@ Claude.ai Pro/Max 订阅账号,并在会话完成首次 API 响应后出现;
226
248
  图标。鼠标从口袋移动到面板后可继续停留查看,移出两者后面板会延迟收起;拖动桌宠时
227
249
  面板会保持显示并实时跟随位置。
228
250
 
251
+ 第三方 CLI Agent 可以使用统一 Provider 事件协议复用状态气泡、动画和通知能力,协议说明见
252
+ [PROVIDER_PROTOCOL.md](./PROVIDER_PROTOCOL.md)。协议不接收命令正文、提示词或模型输出。
253
+
229
254
  可以独立验证解析结果:
230
255
 
231
256
  ```bash
@@ -258,6 +283,8 @@ npx petdex install <slug>
258
283
  - Codex 额度只从本机 `${CODEX_HOME:-~/.codex}/sessions` 读取。
259
284
  - Claude 额度只从 Claude Code 传给本机 status line 的 `rate_limits` 字段读取。
260
285
  - Agent Hooks 只向当前用户的临时目录写入桌宠事件和额度缓存。
286
+ - 额度历史默认关闭;启用后只在本机保留最近 7 天的剩余比例快照。
287
+ - 状态气泡和通知只显示 Provider、状态及脱敏工具类别,不显示会话正文。
261
288
  - 项目不上传会话内容、额度、凭据或使用统计,也不包含遥测服务。
262
289
  - 右键“退出桌宠”或执行 `cc-pets uninstall` 后,不会继续运行后台守护进程。
263
290
 
@@ -1,4 +1,5 @@
1
1
  #import <Cocoa/Cocoa.h>
2
+ #import <UserNotifications/UserNotifications.h>
2
3
 
3
4
  #ifndef CC_PETS_VERSION
4
5
  #define CC_PETS_VERSION "unknown"
@@ -25,6 +26,72 @@ static NSString *ClaudeUsagePath(void) {
25
26
  return [PetStateDirectory() stringByAppendingPathComponent:name];
26
27
  }
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 const NSTimeInterval AgentStatusInactivityInterval = 60.0;
46
+
47
+ static NSString *SanitizedShortString(id value, NSUInteger maximumLength) {
48
+ if (![value isKindOfClass:NSString.class]) return @"";
49
+ NSString *text = [(NSString *)value stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
50
+ if (text.length == 0) return @"";
51
+ NSMutableString *safe = [NSMutableString stringWithCapacity:MIN(text.length, maximumLength)];
52
+ NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:
53
+ @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._- "];
54
+ for (NSUInteger index = 0; index < text.length && safe.length < maximumLength; index++) {
55
+ unichar character = [text characterAtIndex:index];
56
+ if ([allowed characterIsMember:character]) [safe appendFormat:@"%C", character];
57
+ }
58
+ return [safe stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
59
+ }
60
+
61
+ static NSString *ProviderFromEnvironment(void) {
62
+ NSDictionary<NSString *, NSString *> *environment = NSProcessInfo.processInfo.environment;
63
+ if ([environment[@"CC_PETS_CODEX_AGENT_HOOK"] boolValue]) return @"Codex";
64
+ if ([environment[@"CC_PETS_CLAUDE_AGENT_HOOK"] boolValue]) return @"Claude";
65
+ return @"Agent";
66
+ }
67
+
68
+ static NSString *NormalizedStateForEvent(NSString *event, BOOL failed) {
69
+ if ([event isEqualToString:@"StopFailure"]) return @"failed";
70
+ if (failed || [event isEqualToString:@"PostToolUseFailure"]) return @"tool_failed";
71
+ if ([event isEqualToString:@"SessionStart"]) return @"starting";
72
+ if ([event isEqualToString:@"UserPromptSubmit"]) return @"thinking";
73
+ if ([event isEqualToString:@"PermissionRequest"]) return @"approval";
74
+ if ([event isEqualToString:@"PreToolUse"]) return @"tool";
75
+ if ([event isEqualToString:@"SubagentStart"] || [event isEqualToString:@"TaskCreated"]) return @"subagent";
76
+ if ([event isEqualToString:@"PostToolUse"] || [event isEqualToString:@"SubagentStop"] ||
77
+ [event isEqualToString:@"TaskCompleted"]) return @"thinking";
78
+ if ([event isEqualToString:@"Stop"] || [event isEqualToString:@"SessionEnd"]) return @"completed";
79
+ if ([event isEqualToString:@"Notification"]) return @"notification";
80
+ return @"thinking";
81
+ }
82
+
83
+ static BOOL AppendAgentEventRecord(NSDictionary *record) {
84
+ NSData *json = [NSJSONSerialization dataWithJSONObject:record options:0 error:nil];
85
+ if (!json) return NO;
86
+ int descriptor = open(AgentEventPath().fileSystemRepresentation,
87
+ O_CREAT | O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR);
88
+ if (descriptor < 0) return NO;
89
+ BOOL succeeded = write(descriptor, json.bytes, json.length) == (ssize_t)json.length &&
90
+ write(descriptor, "\n", 1) == 1;
91
+ close(descriptor);
92
+ return succeeded;
93
+ }
94
+
28
95
  static NSArray<NSNumber *> *StableVersionComponents(NSString *version) {
29
96
  if (![version isKindOfClass:NSString.class]) return nil;
30
97
  NSArray<NSString *> *parts = [version componentsSeparatedByString:@"."];
@@ -133,15 +200,59 @@ static int RecordHookEvent(void) {
133
200
  @"event": event,
134
201
  @"tool": tool,
135
202
  @"failed": @(failed),
203
+ @"provider": ProviderFromEnvironment(),
204
+ @"state": NormalizedStateForEvent(event, failed),
136
205
  @"timestamp": @([NSDate.date timeIntervalSince1970])
137
206
  };
138
- NSData *json = [NSJSONSerialization dataWithJSONObject:record options:0 error:nil];
139
- if (!json) return EXIT_SUCCESS;
140
- int descriptor = open(AgentEventPath().fileSystemRepresentation, O_CREAT | O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR);
141
- if (descriptor < 0) return EXIT_SUCCESS;
142
- write(descriptor, json.bytes, json.length);
143
- write(descriptor, "\n", 1);
144
- close(descriptor);
207
+ AppendAgentEventRecord(record);
208
+ return EXIT_SUCCESS;
209
+ }
210
+
211
+ static int RecordProviderEvent(void) {
212
+ NSData *input = [NSFileHandle.fileHandleWithStandardInput readDataToEndOfFile];
213
+ NSDictionary *payload = input.length > 0
214
+ ? [NSJSONSerialization JSONObjectWithData:input options:0 error:nil] : nil;
215
+ if (![payload isKindOfClass:NSDictionary.class] ||
216
+ ![payload[@"schemaVersion"] isKindOfClass:NSNumber.class] ||
217
+ [payload[@"schemaVersion"] integerValue] != 1) {
218
+ fprintf(stderr, "provider-event 需要 schemaVersion 为 1 的 JSON 对象。\n");
219
+ return 2;
220
+ }
221
+ NSString *provider = SanitizedShortString(payload[@"provider"], 32);
222
+ NSString *state = SanitizedShortString(payload[@"state"], 32).lowercaseString;
223
+ NSString *tool = SanitizedShortString(payload[@"tool"], 64);
224
+ NSSet<NSString *> *states = [NSSet setWithArray:@[
225
+ @"starting", @"thinking", @"tool", @"approval", @"subagent",
226
+ @"tool_completed", @"tool_failed", @"completed", @"failed", @"notification"
227
+ ]];
228
+ if (provider.length == 0 || ![states containsObject:state]) {
229
+ fprintf(stderr, "provider-event 的 provider 或 state 无效。\n");
230
+ return 2;
231
+ }
232
+ NSDictionary<NSString *, NSString *> *events = @{
233
+ @"starting": @"SessionStart",
234
+ @"thinking": @"UserPromptSubmit",
235
+ @"tool": @"PreToolUse",
236
+ @"approval": @"PermissionRequest",
237
+ @"subagent": @"SubagentStart",
238
+ @"tool_completed": @"PostToolUse",
239
+ @"tool_failed": @"PostToolUseFailure",
240
+ @"completed": @"Stop",
241
+ @"failed": @"StopFailure",
242
+ @"notification": @"Notification"
243
+ };
244
+ NSDictionary *record = @{
245
+ @"event": events[state],
246
+ @"tool": tool,
247
+ @"failed": @([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]),
248
+ @"provider": provider,
249
+ @"state": state,
250
+ @"timestamp": @([NSDate.date timeIntervalSince1970])
251
+ };
252
+ if (!AppendAgentEventRecord(record)) {
253
+ fprintf(stderr, "无法写入 Provider 事件。\n");
254
+ return EXIT_FAILURE;
255
+ }
145
256
  return EXIT_SUCCESS;
146
257
  }
147
258
 
@@ -218,6 +329,81 @@ static NSDictionary *LatestUsage(void) {
218
329
  return LatestUsageInData(tail);
219
330
  }
220
331
 
332
+ static NSNumber *RemainingValue(NSDictionary *usage, NSString *quotaKey, NSString *usedKey) {
333
+ NSDictionary *quota = [usage[quotaKey] isKindOfClass:NSDictionary.class] ? usage[quotaKey] : nil;
334
+ NSNumber *used = [quota[usedKey] isKindOfClass:NSNumber.class] ? quota[usedKey] : nil;
335
+ if (!used) return nil;
336
+ return @(fmax(0, fmin(100, 100.0 - used.doubleValue)));
337
+ }
338
+
339
+ static NSDictionary *QuotaHistoryDocument(void) {
340
+ NSData *data = [NSData dataWithContentsOfFile:QuotaHistoryPath()];
341
+ NSDictionary *document = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
342
+ if (![document isKindOfClass:NSDictionary.class] ||
343
+ [document[@"schemaVersion"] integerValue] != 1 ||
344
+ ![document[@"samples"] isKindOfClass:NSArray.class]) {
345
+ return @{@"schemaVersion": @1, @"samples": @[]};
346
+ }
347
+ return document;
348
+ }
349
+
350
+ static NSDictionary *HistoryProviderSample(NSDictionary *usage, NSString *usedKey) {
351
+ NSNumber *fiveHour = RemainingValue(usage, @"fiveHour", usedKey);
352
+ NSNumber *week = RemainingValue(usage, @"week", usedKey);
353
+ NSMutableDictionary *sample = [NSMutableDictionary dictionary];
354
+ if (fiveHour) sample[@"fiveHourRemaining"] = fiveHour;
355
+ if (week) sample[@"weekRemaining"] = week;
356
+ return sample;
357
+ }
358
+
359
+ static void RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
360
+ if (![NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]) return;
361
+ NSDictionary *codex = HistoryProviderSample(codexUsage, @"used_percent");
362
+ NSDictionary *claude = HistoryProviderSample(claudeUsage, @"used_percentage");
363
+ if (codex.count == 0 && claude.count == 0) return;
364
+
365
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
366
+ NSTimeInterval cutoff = now - 7 * 24 * 60 * 60;
367
+ NSArray *existing = QuotaHistoryDocument()[@"samples"];
368
+ NSMutableArray *samples = [NSMutableArray arrayWithCapacity:existing.count + 1];
369
+ for (NSDictionary *sample in existing) {
370
+ if (![sample isKindOfClass:NSDictionary.class] || [sample[@"timestamp"] doubleValue] < cutoff) continue;
371
+ [samples addObject:sample];
372
+ }
373
+ NSDictionary *last = samples.lastObject;
374
+ if (last && now - [last[@"timestamp"] doubleValue] < 15 * 60) return;
375
+
376
+ NSMutableDictionary *sample = [@{@"timestamp": @(now)} mutableCopy];
377
+ if (codex.count > 0) sample[@"codex"] = codex;
378
+ if (claude.count > 0) sample[@"claude"] = claude;
379
+ [samples addObject:sample];
380
+ if (samples.count > 672) {
381
+ [samples removeObjectsInRange:NSMakeRange(0, samples.count - 672)];
382
+ }
383
+
384
+ NSString *directory = QuotaHistoryPath().stringByDeletingLastPathComponent;
385
+ [NSFileManager.defaultManager createDirectoryAtPath:directory
386
+ withIntermediateDirectories:YES attributes:nil error:nil];
387
+ NSDictionary *document = @{@"schemaVersion": @1, @"samples": samples};
388
+ NSData *json = [NSJSONSerialization dataWithJSONObject:document
389
+ options:NSJSONWritingPrettyPrinted error:nil];
390
+ if ([json writeToFile:QuotaHistoryPath() options:NSDataWritingAtomic error:nil]) {
391
+ chmod(QuotaHistoryPath().fileSystemRepresentation, S_IRUSR | S_IWUSR);
392
+ }
393
+ }
394
+
395
+ static NSArray<NSNumber *> *QuotaHistorySeries(NSString *provider) {
396
+ NSMutableArray<NSNumber *> *series = [NSMutableArray array];
397
+ for (NSDictionary *sample in QuotaHistoryDocument()[@"samples"]) {
398
+ NSDictionary *providerSample = [sample[provider] isKindOfClass:NSDictionary.class]
399
+ ? sample[provider] : nil;
400
+ NSNumber *remaining = [providerSample[@"weekRemaining"] isKindOfClass:NSNumber.class]
401
+ ? providerSample[@"weekRemaining"] : nil;
402
+ if (remaining) [series addObject:remaining];
403
+ }
404
+ return series;
405
+ }
406
+
221
407
  @interface CodexUsageReader : NSObject
222
408
  @property NSURL *sessionsURL;
223
409
  @property NSURL *sessionURL;
@@ -324,6 +510,55 @@ static NSDictionary *LatestUsage(void) {
324
510
  }
325
511
  @end
326
512
 
513
+ @interface MenuToggleSwitch : NSButton
514
+ @end
515
+
516
+ @implementation MenuToggleSwitch
517
+ - (instancetype)initWithFrame:(NSRect)frameRect {
518
+ if ((self = [super initWithFrame:frameRect])) {
519
+ self.bordered = NO;
520
+ self.title = @"";
521
+ self.buttonType = NSButtonTypeToggle;
522
+ self.focusRingType = NSFocusRingTypeNone;
523
+ [self setAccessibilityRole:NSAccessibilityCheckBoxRole];
524
+ }
525
+ return self;
526
+ }
527
+ - (void)setState:(NSControlStateValue)value {
528
+ [super setState:value];
529
+ self.needsDisplay = YES;
530
+ }
531
+ - (void)drawRect:(NSRect)dirtyRect {
532
+ NSRect track = NSInsetRect(self.bounds, 1, 2);
533
+ BOOL enabled = self.state == NSControlStateValueOn;
534
+ NSColor *trackColor = enabled
535
+ ? [NSColor.controlAccentColor colorWithAlphaComponent:self.highlighted ? 0.72 : 0.96]
536
+ : [NSColor colorWithWhite:self.highlighted ? 0.38 : 0.46 alpha:0.82];
537
+ [trackColor setFill];
538
+ NSBezierPath *trackPath = [NSBezierPath bezierPathWithRoundedRect:track
539
+ xRadius:NSHeight(track) / 2.0 yRadius:NSHeight(track) / 2.0];
540
+ [trackPath fill];
541
+ [[NSColor colorWithWhite:0 alpha:enabled ? 0.08 : 0.16] setStroke];
542
+ trackPath.lineWidth = 0.8;
543
+ [trackPath stroke];
544
+
545
+ CGFloat diameter = NSHeight(track) - 4;
546
+ CGFloat knobX = enabled
547
+ ? NSMaxX(track) - diameter - 2
548
+ : NSMinX(track) + 2;
549
+ NSRect knob = NSMakeRect(knobX, NSMidY(track) - diameter / 2.0, diameter, diameter);
550
+ [NSGraphicsContext saveGraphicsState];
551
+ NSShadow *shadow = [NSShadow new];
552
+ shadow.shadowColor = [NSColor colorWithWhite:0 alpha:0.24];
553
+ shadow.shadowBlurRadius = 1.5;
554
+ shadow.shadowOffset = NSMakeSize(0, -0.5);
555
+ [shadow set];
556
+ [NSColor.whiteColor setFill];
557
+ [[NSBezierPath bezierPathWithOvalInRect:knob] fill];
558
+ [NSGraphicsContext restoreGraphicsState];
559
+ }
560
+ @end
561
+
327
562
  @interface PetView : NSView <NSMenuDelegate>
328
563
  @property NSImage *sheet;
329
564
  @property NSInteger spriteRowCount;
@@ -720,6 +955,30 @@ static NSDictionary *LatestUsage(void) {
720
955
  - (void)menuDidClose:(NSMenu *)menu {
721
956
  [self.petMenuPreviewPanel orderOut:nil];
722
957
  }
958
+ - (NSMenuItem *)addPersistentSwitchToMenu:(NSMenu *)menu
959
+ title:(NSString *)title
960
+ checked:(BOOL)checked
961
+ action:(SEL)action
962
+ tag:(NSInteger)tag {
963
+ NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
964
+ NSView *row = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 194, 28)];
965
+ NSTextField *label = [NSTextField labelWithString:title];
966
+ label.frame = NSMakeRect(12, 5, 132, 18);
967
+ label.font = [NSFont menuFontOfSize:13];
968
+ label.textColor = NSColor.labelColor;
969
+ label.lineBreakMode = NSLineBreakByTruncatingTail;
970
+ [row addSubview:label];
971
+ MenuToggleSwitch *toggle = [[MenuToggleSwitch alloc] initWithFrame:NSMakeRect(150, 3, 36, 22)];
972
+ toggle.target = NSApp.delegate;
973
+ toggle.action = action;
974
+ toggle.state = checked ? NSControlStateValueOn : NSControlStateValueOff;
975
+ toggle.tag = tag;
976
+ [toggle setAccessibilityLabel:title];
977
+ [row addSubview:toggle];
978
+ item.view = row;
979
+ [menu addItem:item];
980
+ return item;
981
+ }
723
982
  - (void)rightMouseDown:(NSEvent *)event {
724
983
  NSArray<NSDictionary *> *availablePets = self.petOptionsRequested ? self.petOptionsRequested() : @[];
725
984
  NSMenu *menu = [NSMenu new];
@@ -738,6 +997,26 @@ static NSDictionary *LatestUsage(void) {
738
997
  [menu addItem:NSMenuItem.separatorItem];
739
998
  NSMenuItem *refreshItem = [menu addItemWithTitle:@"刷新用量" action:@selector(refreshUsage:) keyEquivalent:@"r"];
740
999
  refreshItem.target = NSApp.delegate;
1000
+ [self addPersistentSwitchToMenu:menu
1001
+ title:@"记录本地额度历史"
1002
+ checked:[NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]
1003
+ action:@selector(toggleQuotaHistory:)
1004
+ tag:0];
1005
+ NSMenuItem *notificationItem = [menu addItemWithTitle:@"系统通知" action:nil keyEquivalent:@""];
1006
+ NSMenu *notificationMenu = [NSMenu new];
1007
+ NSArray<NSDictionary *> *notificationOptions = @[
1008
+ @{@"title": @"任务完成", @"key": NotificationCompletionKey, @"tag": @1},
1009
+ @{@"title": @"任务失败", @"key": NotificationFailureKey, @"tag": @2},
1010
+ @{@"title": @"等待审批", @"key": NotificationApprovalKey, @"tag": @3}
1011
+ ];
1012
+ for (NSDictionary *option in notificationOptions) {
1013
+ [self addPersistentSwitchToMenu:notificationMenu
1014
+ title:option[@"title"]
1015
+ checked:[NSUserDefaults.standardUserDefaults boolForKey:option[@"key"]]
1016
+ action:@selector(toggleNotification:)
1017
+ tag:[option[@"tag"] integerValue]];
1018
+ }
1019
+ notificationItem.submenu = notificationMenu;
741
1020
  NSMenuItem *updateItem = [menu addItemWithTitle:@"检查更新…" action:@selector(checkForUpdates:) keyEquivalent:@""];
742
1021
  updateItem.target = NSApp.delegate;
743
1022
  [menu addItem:NSMenuItem.separatorItem];
@@ -776,6 +1055,9 @@ static NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceNa
776
1055
  @interface QuotaDashboardView : NSView
777
1056
  @property NSDictionary *codexUsage;
778
1057
  @property NSDictionary *claudeUsage;
1058
+ @property NSArray<NSNumber *> *codexHistory;
1059
+ @property NSArray<NSNumber *> *claudeHistory;
1060
+ @property BOOL historyEnabled;
779
1061
  @property NSImage *codexLogo;
780
1062
  @property NSImage *claudeLogo;
781
1063
  @property BOOL refreshHovered;
@@ -881,6 +1163,29 @@ static NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceNa
881
1163
  [color setFill];
882
1164
  [[NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius] fill];
883
1165
  }
1166
+ - (void)drawHistorySeries:(NSArray<NSNumber *> *)series inRect:(NSRect)rect color:(NSColor *)color {
1167
+ if (!self.historyEnabled || series.count == 0) return;
1168
+ [[color colorWithAlphaComponent:0.10] setFill];
1169
+ [[NSBezierPath bezierPathWithRoundedRect:rect xRadius:4 yRadius:4] fill];
1170
+ CGFloat step = series.count > 1 ? NSWidth(rect) / (series.count - 1) : 0;
1171
+ NSBezierPath *line = [NSBezierPath bezierPath];
1172
+ for (NSUInteger index = 0; index < series.count; index++) {
1173
+ CGFloat value = fmax(0, fmin(100, series[index].doubleValue));
1174
+ NSPoint point = NSMakePoint(NSMinX(rect) + index * step,
1175
+ NSMinY(rect) + 2 + (NSHeight(rect) - 4) * value / 100.0);
1176
+ if (index == 0) [line moveToPoint:point];
1177
+ else [line lineToPoint:point];
1178
+ if (series.count == 1) {
1179
+ [[color colorWithAlphaComponent:0.9] setFill];
1180
+ [[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(point.x - 2, point.y - 2, 4, 4)] fill];
1181
+ }
1182
+ }
1183
+ line.lineWidth = 2;
1184
+ line.lineJoinStyle = NSLineJoinStyleRound;
1185
+ line.lineCapStyle = NSLineCapStyleRound;
1186
+ [[color colorWithAlphaComponent:0.9] setStroke];
1187
+ [line stroke];
1188
+ }
884
1189
  - (void)drawProvider:(NSString *)name usage:(NSDictionary *)usage usedKey:(NSString *)usedKey
885
1190
  color:(NSColor *)color cardRect:(NSRect)card {
886
1191
  NSColor *primary = [NSColor colorWithWhite:0.96 alpha:1];
@@ -979,6 +1284,10 @@ static NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceNa
979
1284
  [[self weeklyReset:week] drawInRect:NSMakeRect(separatorTwo + 16, NSMinY(card) + 39,
980
1285
  NSMaxX(card) - separatorTwo - 28, 24)
981
1286
  withAttributes:[self textAttributesWithSize:15 color:primary weight:NSFontWeightMedium]];
1287
+ NSArray<NSNumber *> *history = [name isEqualToString:@"Codex"] ? self.codexHistory : self.claudeHistory;
1288
+ [self drawHistorySeries:history
1289
+ inRect:NSMakeRect(separatorTwo + 16, NSMinY(card) + 14, NSMaxX(card) - separatorTwo - 28, 17)
1290
+ color:color];
982
1291
  }
983
1292
  - (void)drawRect:(NSRect)dirtyRect {
984
1293
  [NSGraphicsContext saveGraphicsState];
@@ -1041,7 +1350,10 @@ static NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceNa
1041
1350
  [self drawProvider:@"Claude" usage:self.claudeUsage usedKey:@"used_percentage"
1042
1351
  color:[NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1]
1043
1352
  cardRect:NSMakeRect(18, 58, QuotaLogicalWidth - 36, 104)];
1044
- [@"ⓘ 额度随 CLI 响应自动更新,也可点击右上角刷新" drawInRect:NSMakeRect(24, 23, 390, 20)
1353
+ NSString *footer = self.historyEnabled
1354
+ ? @"ⓘ 曲线为本机近 7 天周剩余额度 · 15 分钟采样"
1355
+ : @"ⓘ 额度随 CLI 响应自动更新 · 本地历史已关闭";
1356
+ [footer drawInRect:NSMakeRect(24, 23, 430, 20)
1045
1357
  withAttributes:[self textAttributesWithSize:11 color:[NSColor colorWithWhite:0.58 alpha:1] weight:NSFontWeightRegular]];
1046
1358
  [NSGraphicsContext restoreGraphicsState];
1047
1359
  }
@@ -1061,6 +1373,9 @@ static int RenderQuotaDashboard(NSString *path) {
1061
1373
  @"fiveHour": @{@"used_percentage": @23, @"resets_at": @([NSDate.date timeIntervalSince1970] + 3600)},
1062
1374
  @"week": @{@"used_percentage": @41, @"resets_at": @([NSDate.date timeIntervalSince1970] + 86400)}
1063
1375
  };
1376
+ view.historyEnabled = YES;
1377
+ view.codexHistory = @[@88, @81, @75, @68, @62, @55, @49];
1378
+ view.claudeHistory = @[@92, @86, @78, @72, @64, @58, @51];
1064
1379
  NSInteger pixelWidth = (NSInteger)ceil(NSWidth(view.bounds));
1065
1380
  NSInteger pixelHeight = (NSInteger)ceil(NSHeight(view.bounds));
1066
1381
  NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
@@ -1084,9 +1399,136 @@ static int RenderQuotaDashboard(NSString *path) {
1084
1399
  return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
1085
1400
  }
1086
1401
 
1402
+ static int RenderAgentStatusCard(NSString *path) {
1403
+ [NSApplication sharedApplication];
1404
+ NSSize glassSize = NSMakeSize(340, 58);
1405
+ NSSize size = NSMakeSize(glassSize.width + 12, glassSize.height + 12);
1406
+ NSView *root = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
1407
+ NSView *shadowView = [[NSView alloc] initWithFrame:NSMakeRect(
1408
+ 6, 6, glassSize.width, glassSize.height)];
1409
+ shadowView.wantsLayer = YES;
1410
+ shadowView.layer.backgroundColor = [NSColor colorWithWhite:0 alpha:0.01].CGColor;
1411
+ shadowView.layer.cornerRadius = glassSize.height / 2.0;
1412
+ shadowView.layer.cornerCurve = kCACornerCurveContinuous;
1413
+ shadowView.layer.shadowColor = NSColor.blackColor.CGColor;
1414
+ shadowView.layer.shadowOpacity = 0.24;
1415
+ shadowView.layer.shadowRadius = 8;
1416
+ shadowView.layer.shadowOffset = NSMakeSize(0, -3);
1417
+ CGPathRef shadowPath = CGPathCreateWithRoundedRect(shadowView.bounds,
1418
+ glassSize.height / 2.0, glassSize.height / 2.0, NULL);
1419
+ shadowView.layer.shadowPath = shadowPath;
1420
+ CGPathRelease(shadowPath);
1421
+ [root addSubview:shadowView];
1422
+
1423
+ NSVisualEffectView *glass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(
1424
+ 6, 6, glassSize.width, glassSize.height)];
1425
+ glass.material = NSVisualEffectMaterialPopover;
1426
+ glass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
1427
+ glass.state = NSVisualEffectStateActive;
1428
+ glass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
1429
+ glass.wantsLayer = YES;
1430
+ glass.layer.cornerRadius = glassSize.height / 2.0;
1431
+ glass.layer.cornerCurve = kCACornerCurveContinuous;
1432
+ glass.layer.masksToBounds = YES;
1433
+ glass.layer.borderWidth = 1;
1434
+ glass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
1435
+ [root addSubview:glass];
1436
+
1437
+ NSTextField *title = [NSTextField labelWithString:@"Codex · 任务已完成"];
1438
+ title.frame = NSMakeRect(20, 30, glassSize.width - 80, 18);
1439
+ title.font = [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold];
1440
+ title.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
1441
+ [glass addSubview:title];
1442
+ NSTextField *detail = [NSTextField labelWithString:@"好的,当前任务已经完成。"];
1443
+ detail.frame = NSMakeRect(20, 12, glassSize.width - 80, 17);
1444
+ detail.font = [NSFont systemFontOfSize:12 weight:NSFontWeightRegular];
1445
+ detail.textColor = [NSColor colorWithWhite:0.34 alpha:0.88];
1446
+ [glass addSubview:detail];
1447
+
1448
+ NSButton *icon = [[NSButton alloc] initWithFrame:NSMakeRect(glassSize.width - 48, 12, 34, 34)];
1449
+ icon.bordered = NO;
1450
+ icon.imagePosition = NSImageOnly;
1451
+ icon.wantsLayer = YES;
1452
+ icon.layer.cornerRadius = 17;
1453
+ icon.layer.masksToBounds = YES;
1454
+ NSColor *green = [NSColor colorWithRed:0.18 green:0.68 blue:0.35 alpha:1];
1455
+ icon.layer.backgroundColor = [green colorWithAlphaComponent:0.28].CGColor;
1456
+ NSImage *image = [NSImage imageWithSystemSymbolName:@"checkmark"
1457
+ accessibilityDescription:@"任务已完成"];
1458
+ icon.image = [image imageWithSymbolConfiguration:
1459
+ [NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightBold]];
1460
+ icon.contentTintColor = [green blendedColorWithFraction:0.18
1461
+ ofColor:NSColor.blackColor] ?: green;
1462
+ [glass addSubview:icon];
1463
+
1464
+ NSInteger pixelWidth = (NSInteger)ceil(size.width);
1465
+ NSInteger pixelHeight = (NSInteger)ceil(size.height);
1466
+ NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
1467
+ initWithBitmapDataPlanes:NULL pixelsWide:pixelWidth pixelsHigh:pixelHeight
1468
+ bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
1469
+ colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
1470
+ bitmap.size = size;
1471
+ NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
1472
+ [NSGraphicsContext saveGraphicsState];
1473
+ NSGraphicsContext.currentContext = context;
1474
+ [root displayRectIgnoringOpacity:root.bounds inContext:context];
1475
+ [NSGraphicsContext restoreGraphicsState];
1476
+ NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
1477
+ return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
1478
+ }
1479
+
1480
+ static int RenderMenuSwitches(NSString *path) {
1481
+ [NSApplication sharedApplication];
1482
+ NSSize size = NSMakeSize(220, 72);
1483
+ NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
1484
+ view.wantsLayer = YES;
1485
+ view.layer.backgroundColor = [NSColor colorWithWhite:0.86 alpha:1].CGColor;
1486
+ NSArray<NSDictionary *> *rows = @[
1487
+ @{@"title": @"任务完成", @"state": @YES, @"y": @40},
1488
+ @{@"title": @"任务失败", @"state": @NO, @"y": @10}
1489
+ ];
1490
+ for (NSDictionary *row in rows) {
1491
+ CGFloat y = [row[@"y"] doubleValue];
1492
+ NSTextField *label = [NSTextField labelWithString:row[@"title"]];
1493
+ label.frame = NSMakeRect(14, y + 3, 130, 18);
1494
+ label.font = [NSFont menuFontOfSize:13];
1495
+ label.textColor = NSColor.labelColor;
1496
+ [view addSubview:label];
1497
+ MenuToggleSwitch *toggle = [[MenuToggleSwitch alloc] initWithFrame:NSMakeRect(168, y, 36, 22)];
1498
+ toggle.state = [row[@"state"] boolValue] ? NSControlStateValueOn : NSControlStateValueOff;
1499
+ [view addSubview:toggle];
1500
+ }
1501
+
1502
+ NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
1503
+ initWithBitmapDataPlanes:NULL pixelsWide:(NSInteger)size.width pixelsHigh:(NSInteger)size.height
1504
+ bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
1505
+ colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
1506
+ bitmap.size = size;
1507
+ NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
1508
+ [NSGraphicsContext saveGraphicsState];
1509
+ NSGraphicsContext.currentContext = context;
1510
+ [view displayRectIgnoringOpacity:view.bounds inContext:context];
1511
+ [NSGraphicsContext restoreGraphicsState];
1512
+ NSData *png = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
1513
+ return [png writeToFile:path atomically:YES] ? EXIT_SUCCESS : EXIT_FAILURE;
1514
+ }
1515
+
1087
1516
  @interface AppDelegate : NSObject <NSApplicationDelegate>
1088
1517
  @property NSPanel *panel;
1089
1518
  @property NSPanel *quotaPanel;
1519
+ @property NSPanel *statusPanel;
1520
+ @property NSVisualEffectView *statusGlass;
1521
+ @property NSTextField *statusTitleLabel;
1522
+ @property NSTextField *statusDetailLabel;
1523
+ @property NSButton *statusIconButton;
1524
+ @property NSPanel *statusTogglePanel;
1525
+ @property NSVisualEffectView *statusToggleGlass;
1526
+ @property NSButton *statusToggleButton;
1527
+ @property BOOL statusBubbleExpanded;
1528
+ @property BOOL statusBubbleAbove;
1529
+ @property BOOL hasAgentStatus;
1530
+ @property NSInteger liveClientCount;
1531
+ @property NSString *lastStatusState;
1090
1532
  @property QuotaDashboardView *quotaView;
1091
1533
  @property BOOL managedByCLI;
1092
1534
  @property BOOL pocketHovering;
@@ -1106,14 +1548,14 @@ static int RenderQuotaDashboard(NSString *path) {
1106
1548
  - (void)positionQuotaDashboard;
1107
1549
  - (void)scheduleQuotaDashboardHide;
1108
1550
  - (void)hideQuotaDashboardIfNeeded;
1551
+ - (void)positionAgentStatus;
1552
+ - (void)showAgentStatusForRecord:(NSDictionary *)record;
1553
+ - (void)toggleAgentStatusBubble:(id)sender;
1109
1554
  @end
1110
1555
 
1111
1556
  @implementation AppDelegate
1112
1557
  - (NSString *)applicationSupportDirectory {
1113
- NSString *override = NSProcessInfo.processInfo.environment[@"CC_PETS_APPLICATION_SUPPORT_DIR"];
1114
- if (override.length > 0) return override.stringByStandardizingPath;
1115
- NSString *root = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject;
1116
- return [root stringByAppendingPathComponent:@"CC Pets"];
1558
+ return ApplicationSupportDirectory();
1117
1559
  }
1118
1560
  - (void)showUpdateAlertWithTitle:(NSString *)title message:(NSString *)message {
1119
1561
  [NSApp activateIgnoringOtherApps:YES];
@@ -1296,6 +1738,204 @@ static int RenderQuotaDashboard(NSString *path) {
1296
1738
  }];
1297
1739
  [task resume];
1298
1740
  }
1741
+ - (void)toggleQuotaHistory:(NSButton *)sender {
1742
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
1743
+ BOOL enabled = ![defaults boolForKey:HistoryEnabledKey];
1744
+ [defaults setBool:enabled forKey:HistoryEnabledKey];
1745
+ sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
1746
+ self.quotaView.historyEnabled = enabled;
1747
+ [self refreshUsage:nil];
1748
+ }
1749
+ - (NSString *)notificationKeyForTag:(NSInteger)tag {
1750
+ if (tag == 1) return NotificationCompletionKey;
1751
+ if (tag == 2) return NotificationFailureKey;
1752
+ if (tag == 3) return NotificationApprovalKey;
1753
+ return nil;
1754
+ }
1755
+ - (void)toggleNotification:(NSButton *)sender {
1756
+ NSString *key = [self notificationKeyForTag:sender.tag];
1757
+ if (!key) return;
1758
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
1759
+ if ([defaults boolForKey:key]) {
1760
+ [defaults setBool:NO forKey:key];
1761
+ sender.state = NSControlStateValueOff;
1762
+ return;
1763
+ }
1764
+ [UNUserNotificationCenter.currentNotificationCenter
1765
+ requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound
1766
+ completionHandler:^(BOOL granted, NSError *error) {
1767
+ dispatch_async(dispatch_get_main_queue(), ^{
1768
+ if (granted) {
1769
+ [defaults setBool:YES forKey:key];
1770
+ sender.state = NSControlStateValueOn;
1771
+ } else {
1772
+ sender.state = NSControlStateValueOff;
1773
+ NSString *message = error.localizedDescription ?:
1774
+ @"请在“系统设置 → 通知 → CC Pets”中允许通知后重试。";
1775
+ [self showUpdateAlertWithTitle:@"无法启用系统通知" message:message];
1776
+ }
1777
+ });
1778
+ }];
1779
+ }
1780
+ - (void)sendNotificationWithTitle:(NSString *)title body:(NSString *)body {
1781
+ UNMutableNotificationContent *content = [UNMutableNotificationContent new];
1782
+ content.title = title;
1783
+ content.body = body;
1784
+ content.sound = UNNotificationSound.defaultSound;
1785
+ NSString *identifier = [@"cc-pets-" stringByAppendingString:NSUUID.UUID.UUIDString];
1786
+ UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
1787
+ content:content trigger:nil];
1788
+ [UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:request
1789
+ withCompletionHandler:nil];
1790
+ }
1791
+ - (void)notifyForRecord:(NSDictionary *)record {
1792
+ NSString *event = record[@"event"];
1793
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
1794
+ if (provider.length == 0) provider = @"Agent";
1795
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
1796
+ if ([event isEqualToString:@"PermissionRequest"] &&
1797
+ [defaults boolForKey:NotificationApprovalKey]) {
1798
+ [self sendNotificationWithTitle:@"等待审批"
1799
+ body:[NSString stringWithFormat:@"%@ 正在等待操作。", provider]];
1800
+ } else if ([event isEqualToString:@"StopFailure"] &&
1801
+ [defaults boolForKey:NotificationFailureKey]) {
1802
+ [self sendNotificationWithTitle:@"任务失败"
1803
+ body:[NSString stringWithFormat:@"%@ 的任务执行失败。", provider]];
1804
+ } else if (([event isEqualToString:@"Stop"] || [event isEqualToString:@"SessionEnd"]) &&
1805
+ [defaults boolForKey:NotificationCompletionKey]) {
1806
+ [self sendNotificationWithTitle:@"任务完成"
1807
+ body:[NSString stringWithFormat:@"%@ 已完成当前任务。", provider]];
1808
+ }
1809
+ }
1810
+ - (NSString *)statusTextForState:(NSString *)state tool:(NSString *)tool {
1811
+ if ([state isEqualToString:@"starting"]) return @"正在启动";
1812
+ if ([state isEqualToString:@"thinking"]) return @"正在思考";
1813
+ if ([state isEqualToString:@"approval"]) return @"等待审批";
1814
+ if ([state isEqualToString:@"subagent"]) return @"子 Agent 工作中";
1815
+ if ([state isEqualToString:@"tool_completed"]) return @"操作已完成";
1816
+ if ([state isEqualToString:@"tool_failed"]) return @"工具执行失败";
1817
+ if ([state isEqualToString:@"completed"]) return @"任务已完成";
1818
+ if ([state isEqualToString:@"failed"]) return @"任务失败";
1819
+ if ([state isEqualToString:@"notification"]) return @"需要关注";
1820
+ if ([state isEqualToString:@"tool"]) {
1821
+ NSString *lower = tool.lowercaseString;
1822
+ if ([lower containsString:@"bash"] || [lower containsString:@"exec"] ||
1823
+ [lower containsString:@"shell"] || [lower containsString:@"terminal"]) return @"正在执行命令";
1824
+ if ([lower containsString:@"patch"] || [lower containsString:@"edit"] ||
1825
+ [lower containsString:@"write"]) return @"正在编辑文件";
1826
+ if ([lower containsString:@"read"] || [lower containsString:@"search"] ||
1827
+ [lower containsString:@"find"] || [lower containsString:@"grep"] ||
1828
+ [lower containsString:@"glob"] || [lower containsString:@"web"] ||
1829
+ [lower hasPrefix:@"mcp__"]) return @"正在查找资料";
1830
+ if ([lower containsString:@"task"] || [lower containsString:@"agent"]) return @"子 Agent 工作中";
1831
+ return @"正在使用工具";
1832
+ }
1833
+ return @"正在工作";
1834
+ }
1835
+ - (NSString *)statusDetailForState:(NSString *)state {
1836
+ if ([state isEqualToString:@"starting"]) return @"正在准备当前会话…";
1837
+ if ([state isEqualToString:@"thinking"]) return @"Agent 正在分析请求…";
1838
+ if ([state isEqualToString:@"approval"]) return @"请回到终端确认操作。";
1839
+ if ([state isEqualToString:@"subagent"]) return @"正在协调子 Agent。";
1840
+ if ([state isEqualToString:@"tool"]) return @"正在调用工具…";
1841
+ if ([state isEqualToString:@"tool_completed"]) return @"工具调用已完成。";
1842
+ if ([state isEqualToString:@"tool_failed"]) return @"工具执行失败,请查看终端。";
1843
+ if ([state isEqualToString:@"completed"]) return @"好的,当前任务已经完成。";
1844
+ if ([state isEqualToString:@"failed"]) return @"任务失败,请回到终端查看详情。";
1845
+ if ([state isEqualToString:@"notification"]) return @"Agent 有一条状态需要你关注。";
1846
+ return @"Agent 正在处理当前任务。";
1847
+ }
1848
+ - (NSColor *)statusColorForState:(NSString *)state {
1849
+ if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) {
1850
+ return [NSColor colorWithRed:0.18 green:0.68 blue:0.35 alpha:1];
1851
+ }
1852
+ if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) {
1853
+ return [NSColor colorWithRed:0.86 green:0.28 blue:0.28 alpha:1];
1854
+ }
1855
+ if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) {
1856
+ return [NSColor colorWithRed:0.92 green:0.58 blue:0.12 alpha:1];
1857
+ }
1858
+ return [NSColor colorWithRed:0.33 green:0.53 blue:0.78 alpha:1];
1859
+ }
1860
+ - (NSString *)statusSymbolForState:(NSString *)state {
1861
+ if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) return @"checkmark";
1862
+ if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) return @"xmark";
1863
+ if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) return @"exclamationmark";
1864
+ return @"ellipsis";
1865
+ }
1866
+ - (void)updateStatusToggleAppearance {
1867
+ if (!self.hasAgentStatus) return;
1868
+ NSColor *stateColor = [self statusColorForState:self.lastStatusState];
1869
+ if (self.statusBubbleExpanded) {
1870
+ self.statusToggleButton.title = @"";
1871
+ self.statusToggleButton.imagePosition = NSImageOnly;
1872
+ NSString *symbol = self.statusBubbleAbove ? @"chevron.down" : @"chevron.up";
1873
+ NSImage *image = [NSImage imageWithSystemSymbolName:symbol accessibilityDescription:@"折叠状态"];
1874
+ self.statusToggleButton.image = [image imageWithSymbolConfiguration:
1875
+ [NSImageSymbolConfiguration configurationWithPointSize:11 weight:NSFontWeightSemibold]];
1876
+ self.statusToggleButton.contentTintColor = NSColor.whiteColor;
1877
+ self.statusToggleGlass.layer.backgroundColor =
1878
+ [NSColor colorWithWhite:0.16 alpha:0.54].CGColor;
1879
+ } else {
1880
+ self.statusToggleButton.image = nil;
1881
+ self.statusToggleButton.imagePosition = NSNoImage;
1882
+ self.statusToggleButton.title = [NSString stringWithFormat:@"%ld",
1883
+ (long)MAX(1, self.liveClientCount)];
1884
+ self.statusToggleButton.font = [NSFont systemFontOfSize:11 weight:NSFontWeightSemibold];
1885
+ self.statusToggleButton.contentTintColor = NSColor.whiteColor;
1886
+ self.statusToggleGlass.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.72].CGColor;
1887
+ }
1888
+ }
1889
+ - (void)hideAgentStatus {
1890
+ [self.statusPanel orderOut:nil];
1891
+ [self.statusTogglePanel orderOut:nil];
1892
+ self.hasAgentStatus = NO;
1893
+ }
1894
+ - (void)toggleAgentStatusBubble:(id)sender {
1895
+ if (!self.hasAgentStatus) return;
1896
+ self.statusBubbleExpanded = !self.statusBubbleExpanded;
1897
+ [NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
1898
+ forKey:StatusBubbleExpandedKey];
1899
+ if (self.statusBubbleExpanded) {
1900
+ [self.statusPanel orderFrontRegardless];
1901
+ } else {
1902
+ [self.statusPanel orderOut:nil];
1903
+ }
1904
+ [self positionAgentStatus];
1905
+ [self updateStatusToggleAppearance];
1906
+ [self.statusTogglePanel orderFrontRegardless];
1907
+ }
1908
+ - (void)showAgentStatusForRecord:(NSDictionary *)record {
1909
+ [NSObject cancelPreviousPerformRequestsWithTarget:self
1910
+ selector:@selector(hideAgentStatus) object:nil];
1911
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
1912
+ if (provider.length == 0) provider = @"Agent";
1913
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class]
1914
+ ? record[@"state"] : NormalizedStateForEvent(record[@"event"], [record[@"failed"] boolValue]);
1915
+ NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
1916
+ self.hasAgentStatus = YES;
1917
+ self.lastStatusState = state;
1918
+ self.statusTitleLabel.stringValue = [NSString stringWithFormat:@"%@ · %@",
1919
+ provider, [self statusTextForState:state tool:tool]];
1920
+ self.statusDetailLabel.stringValue = [self statusDetailForState:state];
1921
+ NSColor *stateColor = [self statusColorForState:state];
1922
+ self.statusIconButton.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.28].CGColor;
1923
+ NSImage *icon = [NSImage imageWithSystemSymbolName:[self statusSymbolForState:state]
1924
+ accessibilityDescription:[self statusTextForState:state tool:tool]];
1925
+ self.statusIconButton.image = [icon imageWithSymbolConfiguration:
1926
+ [NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightBold]];
1927
+ self.statusIconButton.contentTintColor = [stateColor blendedColorWithFraction:0.18
1928
+ ofColor:NSColor.blackColor] ?: stateColor;
1929
+ [self positionAgentStatus];
1930
+ if (self.statusBubbleExpanded) [self.statusPanel orderFrontRegardless];
1931
+ else [self.statusPanel orderOut:nil];
1932
+ [self updateStatusToggleAppearance];
1933
+ [self.statusTogglePanel orderFrontRegardless];
1934
+ [self.panel orderFrontRegardless];
1935
+ [self performSelector:@selector(hideAgentStatus)
1936
+ withObject:nil afterDelay:AgentStatusInactivityInterval];
1937
+ [self notifyForRecord:record];
1938
+ }
1299
1939
  - (NSDictionary *)petManifestInDirectory:(NSString *)directory {
1300
1940
  NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
1301
1941
  NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
@@ -1440,6 +2080,8 @@ static int RenderQuotaDashboard(NSString *path) {
1440
2080
  return;
1441
2081
  }
1442
2082
  NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
2083
+ [defaults registerDefaults:@{StatusBubbleExpandedKey: @YES}];
2084
+ self.statusBubbleExpanded = [defaults boolForKey:StatusBubbleExpandedKey];
1443
2085
  NSString *selected = [defaults stringForKey:@"CCPetsSelectedSprite"];
1444
2086
  if (selected.length == 0) {
1445
2087
  NSDictionary *legacyDefaults = [defaults persistentDomainForName:@"com.universewang.codex-pet"];
@@ -1493,6 +2135,9 @@ static int RenderQuotaDashboard(NSString *path) {
1493
2135
  };
1494
2136
  self.petView.positionChanged = ^{
1495
2137
  if (weakSelf.quotaPanel.isVisible) [weakSelf positionQuotaDashboard];
2138
+ if (weakSelf.statusPanel.isVisible || weakSelf.statusTogglePanel.isVisible) {
2139
+ [weakSelf positionAgentStatus];
2140
+ }
1496
2141
  };
1497
2142
  self.petView.dragStateChanged = ^(BOOL dragging) {
1498
2143
  weakSelf.petDragging = dragging;
@@ -1500,6 +2145,109 @@ static int RenderQuotaDashboard(NSString *path) {
1500
2145
  };
1501
2146
  [root addSubview:self.petView];
1502
2147
 
2148
+ NSSize statusGlassSize = NSMakeSize(340, 58);
2149
+ NSSize statusSize = NSMakeSize(statusGlassSize.width + 12, statusGlassSize.height + 12);
2150
+ self.statusPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0,
2151
+ statusSize.width, statusSize.height)
2152
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
2153
+ backing:NSBackingStoreBuffered defer:NO];
2154
+ self.statusPanel.opaque = NO;
2155
+ self.statusPanel.backgroundColor = NSColor.clearColor;
2156
+ self.statusPanel.hasShadow = NO;
2157
+ self.statusPanel.ignoresMouseEvents = YES;
2158
+ self.statusPanel.level = NSFloatingWindowLevel;
2159
+ self.statusPanel.collectionBehavior =
2160
+ NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
2161
+ self.statusPanel.hidesOnDeactivate = NO;
2162
+ NSView *statusRoot = [[NSView alloc] initWithFrame:NSMakeRect(
2163
+ 0, 0, statusSize.width, statusSize.height)];
2164
+ NSView *statusShadow = [[NSView alloc] initWithFrame:NSMakeRect(
2165
+ 6, 6, statusGlassSize.width, statusGlassSize.height)];
2166
+ statusShadow.wantsLayer = YES;
2167
+ statusShadow.layer.backgroundColor = [NSColor colorWithWhite:0 alpha:0.01].CGColor;
2168
+ statusShadow.layer.cornerRadius = statusGlassSize.height / 2.0;
2169
+ statusShadow.layer.cornerCurve = kCACornerCurveContinuous;
2170
+ statusShadow.layer.shadowColor = NSColor.blackColor.CGColor;
2171
+ statusShadow.layer.shadowOpacity = 0.24;
2172
+ statusShadow.layer.shadowRadius = 8;
2173
+ statusShadow.layer.shadowOffset = NSMakeSize(0, -3);
2174
+ CGPathRef statusShadowPath = CGPathCreateWithRoundedRect(
2175
+ statusShadow.bounds, statusGlassSize.height / 2.0,
2176
+ statusGlassSize.height / 2.0, NULL);
2177
+ statusShadow.layer.shadowPath = statusShadowPath;
2178
+ CGPathRelease(statusShadowPath);
2179
+ [statusRoot addSubview:statusShadow];
2180
+
2181
+ self.statusGlass = [[NSVisualEffectView alloc]
2182
+ initWithFrame:NSMakeRect(6, 6, statusGlassSize.width, statusGlassSize.height)];
2183
+ self.statusGlass.material = NSVisualEffectMaterialPopover;
2184
+ self.statusGlass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
2185
+ self.statusGlass.state = NSVisualEffectStateActive;
2186
+ self.statusGlass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
2187
+ self.statusGlass.wantsLayer = YES;
2188
+ self.statusGlass.layer.cornerRadius = statusGlassSize.height / 2.0;
2189
+ self.statusGlass.layer.cornerCurve = kCACornerCurveContinuous;
2190
+ self.statusGlass.layer.masksToBounds = YES;
2191
+ self.statusGlass.layer.borderWidth = 1;
2192
+ self.statusGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
2193
+
2194
+ self.statusTitleLabel = [NSTextField labelWithString:@""];
2195
+ self.statusTitleLabel.frame = NSMakeRect(20, 30, statusGlassSize.width - 80, 18);
2196
+ self.statusTitleLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold];
2197
+ self.statusTitleLabel.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
2198
+ self.statusTitleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
2199
+ [self.statusGlass addSubview:self.statusTitleLabel];
2200
+
2201
+ self.statusDetailLabel = [NSTextField labelWithString:@""];
2202
+ self.statusDetailLabel.frame = NSMakeRect(20, 12, statusGlassSize.width - 80, 17);
2203
+ self.statusDetailLabel.font = [NSFont systemFontOfSize:12 weight:NSFontWeightRegular];
2204
+ self.statusDetailLabel.textColor = [NSColor colorWithWhite:0.34 alpha:0.88];
2205
+ self.statusDetailLabel.lineBreakMode = NSLineBreakByTruncatingTail;
2206
+ [self.statusGlass addSubview:self.statusDetailLabel];
2207
+
2208
+ self.statusIconButton = [[NSButton alloc] initWithFrame:NSMakeRect(
2209
+ statusGlassSize.width - 48, 12, 34, 34)];
2210
+ self.statusIconButton.bordered = NO;
2211
+ self.statusIconButton.imagePosition = NSImageOnly;
2212
+ self.statusIconButton.wantsLayer = YES;
2213
+ self.statusIconButton.layer.cornerRadius = 17;
2214
+ self.statusIconButton.layer.masksToBounds = YES;
2215
+ [self.statusGlass addSubview:self.statusIconButton];
2216
+ [statusRoot addSubview:self.statusGlass];
2217
+ self.statusPanel.contentView = statusRoot;
2218
+
2219
+ NSSize toggleSize = NSMakeSize(28, 28);
2220
+ self.statusTogglePanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0,
2221
+ toggleSize.width, toggleSize.height)
2222
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
2223
+ backing:NSBackingStoreBuffered defer:NO];
2224
+ self.statusTogglePanel.opaque = NO;
2225
+ self.statusTogglePanel.backgroundColor = NSColor.clearColor;
2226
+ self.statusTogglePanel.hasShadow = YES;
2227
+ self.statusTogglePanel.ignoresMouseEvents = NO;
2228
+ self.statusTogglePanel.level = NSFloatingWindowLevel;
2229
+ self.statusTogglePanel.collectionBehavior =
2230
+ NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
2231
+ self.statusTogglePanel.hidesOnDeactivate = NO;
2232
+ self.statusToggleGlass = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(
2233
+ 0, 0, toggleSize.width, toggleSize.height)];
2234
+ self.statusToggleGlass.material = NSVisualEffectMaterialHUDWindow;
2235
+ self.statusToggleGlass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
2236
+ self.statusToggleGlass.state = NSVisualEffectStateActive;
2237
+ self.statusToggleGlass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
2238
+ self.statusToggleGlass.wantsLayer = YES;
2239
+ self.statusToggleGlass.layer.cornerRadius = 14;
2240
+ self.statusToggleGlass.layer.masksToBounds = YES;
2241
+ self.statusToggleGlass.layer.borderWidth = 1;
2242
+ self.statusToggleGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.24].CGColor;
2243
+ self.statusToggleButton = [[NSButton alloc] initWithFrame:self.statusToggleGlass.bounds];
2244
+ self.statusToggleButton.bordered = NO;
2245
+ self.statusToggleButton.imagePosition = NSImageOnly;
2246
+ self.statusToggleButton.target = self;
2247
+ self.statusToggleButton.action = @selector(toggleAgentStatusBubble:);
2248
+ [self.statusToggleGlass addSubview:self.statusToggleButton];
2249
+ self.statusTogglePanel.contentView = self.statusToggleGlass;
2250
+
1503
2251
  NSSize quotaSize = NSMakeSize(QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale);
1504
2252
  self.quotaPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)
1505
2253
  styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
@@ -1524,6 +2272,7 @@ static int RenderQuotaDashboard(NSString *path) {
1524
2272
  glass.layer.masksToBounds = YES;
1525
2273
  [quotaRoot addSubview:glass];
1526
2274
  self.quotaView = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
2275
+ self.quotaView.historyEnabled = [defaults boolForKey:HistoryEnabledKey];
1527
2276
  self.quotaView.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
1528
2277
  self.quotaView.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
1529
2278
  self.quotaView.hoverChanged = ^(BOOL hovering) {
@@ -1571,6 +2320,34 @@ static int RenderQuotaDashboard(NSString *path) {
1571
2320
  y = fmax(NSMinY(visible) + 12, fmin(y, NSMaxY(visible) - size.height - 12));
1572
2321
  [self.quotaPanel setFrameOrigin:NSMakePoint(x, y)];
1573
2322
  }
2323
+ - (void)positionAgentStatus {
2324
+ NSRect petFrame = self.panel.frame;
2325
+ NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
2326
+ NSSize size = self.statusPanel.frame.size;
2327
+ CGFloat x = NSMidX(petFrame) - size.width / 2.0;
2328
+ CGFloat aboveY = NSMaxY(petFrame) + 8;
2329
+ CGFloat belowY = NSMinY(petFrame) - size.height - 8;
2330
+ BOOL aboveFits = aboveY + size.height <= NSMaxY(visible) - 10;
2331
+ BOOL belowFits = belowY >= NSMinY(visible) + 10;
2332
+ self.statusBubbleAbove = aboveFits || !belowFits;
2333
+ CGFloat y = self.statusBubbleAbove ? aboveY : belowY;
2334
+ x = fmax(NSMinX(visible) + 10, fmin(x, NSMaxX(visible) - size.width - 10));
2335
+ y = fmax(NSMinY(visible) + 10, fmin(y, NSMaxY(visible) - size.height - 10));
2336
+ [self.statusPanel setFrameOrigin:NSMakePoint(x, y)];
2337
+
2338
+ NSSize toggleSize = self.statusTogglePanel.frame.size;
2339
+ NSRect petViewFrame = self.petView.frame;
2340
+ CGFloat toggleX = NSMinX(petFrame) + NSMinX(petViewFrame) +
2341
+ NSWidth(petViewFrame) * 0.82;
2342
+ CGFloat toggleY = NSMinY(petFrame) + NSMinY(petViewFrame) +
2343
+ NSHeight(petViewFrame) * 0.70;
2344
+ toggleX = fmax(NSMinX(visible) + 8,
2345
+ fmin(toggleX, NSMaxX(visible) - toggleSize.width - 8));
2346
+ toggleY = fmax(NSMinY(visible) + 8,
2347
+ fmin(toggleY, NSMaxY(visible) - toggleSize.height - 8));
2348
+ [self.statusTogglePanel setFrameOrigin:NSMakePoint(toggleX, toggleY)];
2349
+ [self updateStatusToggleAppearance];
2350
+ }
1574
2351
  - (void)scheduleQuotaDashboardHide {
1575
2352
  [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
1576
2353
  [self performSelector:@selector(hideQuotaDashboardIfNeeded) withObject:nil afterDelay:0.28];
@@ -1645,6 +2422,7 @@ static int RenderQuotaDashboard(NSString *path) {
1645
2422
  NSString *tool = record[@"tool"] ?: @"";
1646
2423
  if ([event isKindOfClass:NSString.class]) {
1647
2424
  [self.petView handleAgentEvent:event tool:tool failed:[record[@"failed"] boolValue]];
2425
+ [self showAgentStatusForRecord:record];
1648
2426
  }
1649
2427
  }
1650
2428
  }
@@ -1718,6 +2496,10 @@ static int RenderQuotaDashboard(NSString *path) {
1718
2496
  [NSFileManager.defaultManager removeItemAtPath:stale error:nil];
1719
2497
  }
1720
2498
  }
2499
+ self.liveClientCount = liveClients;
2500
+ if (self.statusTogglePanel.isVisible && !self.statusBubbleExpanded) {
2501
+ [self updateStatusToggleAppearance];
2502
+ }
1721
2503
  // 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
1722
2504
  // Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
1723
2505
  if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
@@ -1725,6 +2507,9 @@ static int RenderQuotaDashboard(NSString *path) {
1725
2507
  - (void)refreshUsage:(id)sender {
1726
2508
  self.quotaView.codexUsage = [self.codexUsageReader refresh];
1727
2509
  self.quotaView.claudeUsage = LatestClaudeUsage();
2510
+ RecordQuotaHistory(self.quotaView.codexUsage, self.quotaView.claudeUsage);
2511
+ self.quotaView.codexHistory = QuotaHistorySeries(@"codex");
2512
+ self.quotaView.claudeHistory = QuotaHistorySeries(@"claude");
1728
2513
  self.quotaView.needsDisplay = YES;
1729
2514
  }
1730
2515
  - (void)applicationWillTerminate:(NSNotification *)notification {
@@ -1760,10 +2545,26 @@ int main(int argc, const char *argv[]) {
1760
2545
  return RestartAfterPID(pid, appPath, managed);
1761
2546
  }
1762
2547
  if (argc > 1 && strcmp(argv[1], "--hook") == 0) return RecordHookEvent();
2548
+ if (argc > 1 && (strcmp(argv[1], "--provider-event") == 0 ||
2549
+ strcmp(argv[1], "provider-event") == 0)) return RecordProviderEvent();
1763
2550
  if (argc > 1 && strcmp(argv[1], "--claude-usage") == 0) return RecordClaudeUsage();
2551
+ if (argc > 1 && strcmp(argv[1], "--history") == 0) {
2552
+ NSData *json = [NSJSONSerialization dataWithJSONObject:QuotaHistoryDocument()
2553
+ options:NSJSONWritingPrettyPrinted error:nil];
2554
+ if (!json) return EXIT_FAILURE;
2555
+ fwrite(json.bytes, 1, json.length, stdout);
2556
+ fputc('\n', stdout);
2557
+ return EXIT_SUCCESS;
2558
+ }
1764
2559
  if (argc > 2 && strcmp(argv[1], "--render-dashboard") == 0) {
1765
2560
  return RenderQuotaDashboard([NSString stringWithUTF8String:argv[2]]);
1766
2561
  }
2562
+ if (argc > 2 && strcmp(argv[1], "--render-status") == 0) {
2563
+ return RenderAgentStatusCard([NSString stringWithUTF8String:argv[2]]);
2564
+ }
2565
+ if (argc > 2 && strcmp(argv[1], "--render-switches") == 0) {
2566
+ return RenderMenuSwitches([NSString stringWithUTF8String:argv[2]]);
2567
+ }
1767
2568
  if (argc > 1 && strcmp(argv[1], "--status") == 0) {
1768
2569
  NSDictionary *usage = LatestUsage();
1769
2570
  if (!usage) {
package/bin/cc-pets CHANGED
@@ -41,4 +41,9 @@ if [[ "${1:-}" == "--foreground" ]]; then
41
41
  exec "${PET_BIN}" "$@"
42
42
  fi
43
43
 
44
+ if [[ "${1:-}" == "provider-event" ]]; then
45
+ shift
46
+ exec "${PET_BIN}" --provider-event "$@"
47
+ fi
48
+
44
49
  exec "${PET_BIN}" "$@"
@@ -30,5 +30,7 @@ fi
30
30
  mkdir -p "${CLIENT_DIR}"
31
31
  touch "${CLIENT_FILE}"
32
32
 
33
+ print -rn -- '{"schemaVersion":1,"provider":"Claude","state":"starting"}' | \
34
+ "${PET_BIN}" --provider-event >/dev/null 2>&1 || true
33
35
  open -g "${PET_APP}" --args --managed
34
36
  exec "${REAL_CLAUDE}" "$@"
@@ -30,5 +30,7 @@ fi
30
30
  mkdir -p "${CLIENT_DIR}"
31
31
  touch "${CLIENT_FILE}"
32
32
 
33
+ print -rn -- '{"schemaVersion":1,"provider":"Codex","state":"starting"}' | \
34
+ "${PET_BIN}" --provider-event >/dev/null 2>&1 || true
33
35
  open -g "${PET_APP}" --args --managed
34
36
  exec "${REAL_CODEX}" "$@"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",
@@ -34,6 +34,7 @@
34
34
  "Sources/CCPets/main.m",
35
35
  "Sources/CCPets/Resources",
36
36
  "README.md",
37
+ "PROVIDER_PROTOCOL.md",
37
38
  "CHANGELOG.md",
38
39
  "CONTRIBUTING.md",
39
40
  "SECURITY.md",
package/scripts/build.sh CHANGED
@@ -18,6 +18,8 @@ CLANG_MODULE_CACHE_PATH="${CACHE_DIR}" clang \
18
18
  -mmacosx-version-min=13.0 \
19
19
  "-DCC_PETS_VERSION=\"${PACKAGE_VERSION}\"" \
20
20
  -framework Cocoa \
21
+ -framework QuartzCore \
22
+ -framework UserNotifications \
21
23
  "${PROJECT_DIR}/Sources/CCPets/main.m" \
22
24
  -o "${BUILD_DIR}/cc-pets"
23
25