cc-pets 2.4.0 → 2.6.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CC_BRIDGE.md +93 -14
  2. package/CC_BRIDGE.zh-CN.md +71 -11
  3. package/CHANGELOG.md +55 -0
  4. package/CHANGELOG.zh-CN.md +56 -1
  5. package/CONTRIBUTING.md +1 -1
  6. package/CONTRIBUTING.zh-CN.md +1 -1
  7. package/PROVIDER_PROTOCOL.md +5 -1
  8. package/PROVIDER_PROTOCOL.zh-CN.md +4 -1
  9. package/README.md +116 -34
  10. package/README.zh-CN.md +99 -35
  11. package/Resources/AgentIcons/antigravity.icns +0 -0
  12. package/Resources/zh-Hans.lproj/Localizable.strings +99 -26
  13. package/Sources/CCPets/App/CCPetsAppDelegate+AgentEvents.m +51 -4
  14. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +120 -17
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Bridge.m +24 -11
  16. package/Sources/CCPets/App/CCPetsAppDelegate+MenuBar.m +86 -0
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +24 -1
  18. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +21 -11
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Quota.m +33 -17
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +43 -7
  21. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +7 -4
  22. package/Sources/CCPets/App/CCPetsAppDelegate+Update.m +7 -4
  23. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +24 -22
  24. package/Sources/CCPets/App/CCPetsAppDelegate.h +10 -0
  25. package/Sources/CCPets/App/CCPetsAppDelegate.m +18 -8
  26. package/Sources/CCPets/App/CCPetsVersion.h +4 -0
  27. package/Sources/CCPets/App/CCPetsVersion.m +34 -0
  28. package/Sources/CCPets/App/main.m +11 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridge.m +41 -17
  30. package/Sources/CCPets/Bridge/CCPetsBridgeAntigravityApp.h +4 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeAntigravityApp.m +119 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +3 -1
  33. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +272 -50
  34. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +12 -3
  35. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +341 -95
  36. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +0 -2
  37. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +227 -95
  38. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +35 -5
  39. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +310 -42
  40. package/Sources/CCPets/Bridge/CCPetsBridgeTerminalTitle.h +12 -0
  41. package/Sources/CCPets/Bridge/CCPetsBridgeTerminalTitle.m +105 -0
  42. package/Sources/CCPets/Integrations/CCPetsAntigravityConfig.h +17 -0
  43. package/Sources/CCPets/Integrations/CCPetsAntigravityConfig.m +462 -0
  44. package/Sources/CCPets/Integrations/CCPetsAntigravityEvents.h +5 -0
  45. package/Sources/CCPets/Integrations/CCPetsAntigravityEvents.m +180 -0
  46. package/Sources/CCPets/Integrations/CCPetsBridgeTitleRelay.h +3 -0
  47. package/Sources/CCPets/Integrations/CCPetsBridgeTitleRelay.m +463 -0
  48. package/Sources/CCPets/Integrations/CCPetsEvents.h +5 -0
  49. package/Sources/CCPets/Integrations/CCPetsEvents.m +68 -12
  50. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +1 -1
  51. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +38 -8
  52. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +15 -5
  53. package/Sources/CCPets/Integrations/CCPetsProfiles.h +2 -1
  54. package/Sources/CCPets/Integrations/CCPetsProfiles.m +112 -81
  55. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +11 -1
  56. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +217 -45
  57. package/Sources/CCPets/Pet/CCPetsPhrasesEditor.m +7 -0
  58. package/Sources/CCPets/Pet/CCPetsPreviews.m +16 -8
  59. package/Sources/CCPets/Pet/PetView+Menu.m +64 -5
  60. package/Sources/CCPets/Pet/PetView.h +7 -0
  61. package/Sources/CCPets/Pet/PetView.m +12 -1
  62. package/Sources/CCPets/Support/CCPetsDoctor.m +126 -37
  63. package/Sources/CCPets/Support/CCPetsPaths.h +5 -0
  64. package/Sources/CCPets/Support/CCPetsPaths.m +15 -0
  65. package/Sources/CCPets/Support/CCPetsPreferences.h +14 -1
  66. package/Sources/CCPets/Support/CCPetsPreferences.m +36 -0
  67. package/Sources/CCPets/UI/CCPetsMenuBarIcon.h +16 -0
  68. package/Sources/CCPets/UI/CCPetsMenuBarIcon.m +70 -0
  69. package/Sources/CCPets/UI/CCPetsMenuBarPanel.h +18 -0
  70. package/Sources/CCPets/UI/CCPetsMenuBarPanel.m +533 -0
  71. package/Sources/CCPets/UI/CCPetsMenuBarSummary.h +51 -0
  72. package/Sources/CCPets/UI/CCPetsMenuBarSummary.m +98 -0
  73. package/Sources/CCPets/UI/CCPetsSettingsPage.h +7 -1
  74. package/Sources/CCPets/UI/CCPetsSettingsPage.m +205 -8
  75. package/Sources/CCPets/UI/CCPetsStatusItem.h +28 -0
  76. package/Sources/CCPets/UI/CCPetsStatusItem.m +147 -0
  77. package/Sources/CCPets/UI/CCPetsUIStyle.m +3 -1
  78. package/Sources/CCPets/UI/CCPetsUsagePage.h +4 -3
  79. package/Sources/CCPets/UI/CCPetsUsagePage.m +69 -43
  80. package/Sources/CCPets/UI/CCPetsUsageStore.m +11 -1
  81. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +6 -4
  82. package/Sources/CCPets/Usage/CCPetsAntigravityQuota.m +115 -0
  83. package/Sources/CCPets/Usage/CCPetsNormalizedUsage.h +5 -0
  84. package/Sources/CCPets/Usage/CCPetsNormalizedUsage.m +43 -0
  85. package/Sources/CCPets/Usage/CCPetsProviderRegistry+Testing.h +13 -0
  86. package/Sources/CCPets/Usage/CCPetsProviderRegistry.h +25 -0
  87. package/Sources/CCPets/Usage/CCPetsProviderRegistry.m +94 -0
  88. package/Sources/CCPets/Usage/CCPetsQuotaHistory.h +1 -1
  89. package/Sources/CCPets/Usage/CCPetsQuotaHistory.m +11 -8
  90. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +2 -0
  91. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +206 -14
  92. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +4 -4
  93. package/Sources/CCPets/Usage/CCPetsUsage.h +7 -2
  94. package/Sources/CCPets/Usage/CCPetsUsageMode.h +2 -0
  95. package/Sources/CCPets/Usage/CCPetsUsageMode.m +29 -4
  96. package/Sources/CCPets/Usage/CCPetsUsageMonitor.h +4 -4
  97. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +90 -7
  98. package/Sources/CCPets/Usage/QuotaDashboardView+CompactRow.m +81 -0
  99. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +5 -8
  100. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +26 -4
  101. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +99 -99
  102. package/Sources/CCPets/Usage/QuotaDashboardView.h +9 -10
  103. package/Sources/CCPets/Usage/QuotaDashboardView.m +232 -79
  104. package/THIRD_PARTY_NOTICES.md +5 -4
  105. package/THIRD_PARTY_NOTICES.zh-CN.md +6 -5
  106. package/bin/agy-with-pet +82 -0
  107. package/bin/cc-pets +1 -1
  108. package/bin/claude-with-pet +15 -0
  109. package/bin/codex-with-pet +17 -2
  110. package/package.json +5 -3
  111. package/scripts/install-shell-integration.sh +5 -0
@@ -4,6 +4,7 @@
4
4
  #import "CCPetsIDEIntegration.h"
5
5
  #import "CCPetsVSCodeIntegration.h"
6
6
  #import <fcntl.h>
7
+ #import <limits.h>
7
8
  #import <sys/file.h>
8
9
  #import <sys/sysctl.h>
9
10
  #import <sys/stat.h>
@@ -18,6 +19,68 @@ static BOOL ProcessInfoForPID(pid_t pid, struct kinfo_proc *info) {
18
19
  return sysctl(name, 4, info, &length, NULL, 0) == 0 && length > 0;
19
20
  }
20
21
 
22
+ BOOL IsCodexDesktopFocusTarget(NSDictionary *target) {
23
+ if (![target isKindOfClass:NSDictionary.class]) return NO;
24
+ return [target[@"bundleID"] isEqual:@"com.openai.codex"] &&
25
+ (![target[@"tty"] isKindOfClass:NSString.class] || [target[@"tty"] length] == 0);
26
+ }
27
+
28
+ BOOL CodexDesktopFocusTargetIsLive(NSDictionary *target, NSTimeInterval eventTime) {
29
+ if (!IsCodexDesktopFocusTarget(target) || !(eventTime > 0)) return NO;
30
+ for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.openai.codex"]) {
31
+ if (!app.terminated && app.launchDate && app.launchDate.timeIntervalSince1970 <= eventTime) return YES;
32
+ }
33
+ return NO;
34
+ }
35
+
36
+ BOOL CodexDesktopApplicationIsRunning(void) {
37
+ for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.openai.codex"]) {
38
+ if (!app.terminated) return YES;
39
+ }
40
+ return NO;
41
+ }
42
+
43
+ NSString *const CCPetsAntigravityAppBundleIdentifier = @"com.google.antigravity";
44
+
45
+ BOOL IsAntigravityDesktopFocusTarget(NSDictionary *target) {
46
+ if (![target isKindOfClass:NSDictionary.class]) return NO;
47
+ return [target[@"bundleID"] isEqual:CCPetsAntigravityAppBundleIdentifier] &&
48
+ (![target[@"tty"] isKindOfClass:NSString.class] || [target[@"tty"] length] == 0);
49
+ }
50
+
51
+ BOOL AntigravityDesktopApplicationIsRunning(void) {
52
+ for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:CCPetsAntigravityAppBundleIdentifier]) {
53
+ if (app.terminated || !app.bundleURL) continue;
54
+ // The earlier VS Code-based Antigravity IDE can have the same bundle ID.
55
+ NSString *backend = [app.bundleURL.path stringByAppendingPathComponent:@"Contents/Resources/bin/language_server"];
56
+ if ([NSFileManager.defaultManager isExecutableFileAtPath:backend]) return YES;
57
+ }
58
+ return NO;
59
+ }
60
+
61
+ NSNumber *CodexPersistentThreadStatus(NSString *thread, NSString *codexHome) {
62
+ if (thread.length == 0 || !codexHome.isAbsolutePath) return nil;
63
+ sqlite3 *db = NULL;
64
+ NSString *path = [codexHome stringByAppendingPathComponent:@"state_5.sqlite"];
65
+ if (sqlite3_open_v2(path.fileSystemRepresentation, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {
66
+ if (db) sqlite3_close(db);
67
+ return nil;
68
+ }
69
+ sqlite3_busy_timeout(db, 10);
70
+ sqlite3_stmt *statement = NULL;
71
+ NSNumber *result = nil;
72
+ // 索引不可读或版本改变时返回未知,不能把错误当作“会话已退出”。
73
+ if (sqlite3_prepare_v2(db, "SELECT archived FROM threads WHERE id = ? LIMIT 1", -1, &statement, NULL) == SQLITE_OK) {
74
+ sqlite3_bind_text(statement, 1, thread.UTF8String, -1, SQLITE_TRANSIENT);
75
+ int step = sqlite3_step(statement);
76
+ if (step == SQLITE_ROW) result = @(sqlite3_column_int(statement, 0) == 0);
77
+ else if (step == SQLITE_DONE) result = @NO;
78
+ }
79
+ sqlite3_finalize(statement);
80
+ sqlite3_close(db);
81
+ return result;
82
+ }
83
+
21
84
  // 包装脚本没被走到时(用户直接跑 codex / claude,或终端窗口早于 shim 安装就已打开)
22
85
  // 环境里没有 CC_PETS_TERMINAL_*。记录端自己是 Agent 的子进程,控制终端就是 Agent
23
86
  // 所在的那个 tty,直接问内核即可——stdin 是 JSON 管道,isatty 这类办法在这里没用。
@@ -102,6 +165,7 @@ NSDictionary *TerminalFocusTargetFromEnvironment(void) {
102
165
  NSString *bundleID = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_BUNDLE_ID", 128);
103
166
  NSString *ideInstance = TerminalTargetValue(environment, @"CC_PETS_IDE_INSTANCE_ID", 64);
104
167
  NSString *ideTerminal = TerminalTargetValue(environment, @"CC_PETS_IDE_TERMINAL_ID", 64);
168
+ NSString *titleToken = environment[@"CC_PETS_BRIDGE_TITLE_TOKEN"];
105
169
  if (tty.length == 0) tty = SanitizedShortString(ControllingTerminalName(), 64);
106
170
  if (bundleID.length == 0) {
107
171
  bundleID = SanitizedShortString(HostApplicationBundleIdentifier(), 128);
@@ -114,6 +178,7 @@ NSDictionary *TerminalFocusTargetFromEnvironment(void) {
114
178
  if (program.length > 0) target[@"program"] = program;
115
179
  if (session.length > 0) target[@"session"] = session;
116
180
  if (bundleID.length > 0) target[@"bundleID"] = bundleID;
181
+ if (titleToken.length == 36 && [[NSUUID alloc] initWithUUIDString:titleToken]) target[@"bridgeTitleToken"] = titleToken;
117
182
  if (ideInstance.length > 0 && ideTerminal.length > 0) {
118
183
  target[@"ideInstance"] = ideInstance;
119
184
  target[@"ideTerminal"] = ideTerminal;
@@ -275,7 +340,7 @@ BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
275
340
  // 能确定的只有两头:codex-with-pet 启动时知道自己的终端、工作目录和时刻;hook 知道会话 ID,
276
341
  // 会话记录(rollout)的第一行又记着会话的工作目录和创建时刻。CLI 启动后可能还要等网络
277
342
  // 初始化,不能按包装脚本的启动先后猜测归属。多个候选时读取本机 TUI 就绪日志的 PID,
278
- // 仅在会话创建前的一秒内存在唯一就绪候选时配对;信息不足就留空,之后的 Hook 可再试。
343
+ // 仅在会话创建前后一秒内存在唯一就绪候选时配对;信息不足就留空,之后的 Hook 可再试。
279
344
  static const NSUInteger CodexLaunchThreadLimit = 32;
280
345
  static const NSTimeInterval CodexClientReadyWindow = 1.0;
281
346
 
@@ -328,6 +393,20 @@ static NSMutableDictionary<NSString *, NSDictionary *> *LoadLiveCodexLaunches(vo
328
393
  return launches;
329
394
  }
330
395
 
396
+ static NSDictionary *CodexLaunchTarget(NSDictionary *launch) {
397
+ id terminal = launch[@"terminal"];
398
+ return [terminal isKindOfClass:NSDictionary.class] ? terminal : @{};
399
+ }
400
+
401
+ BOOL CodexHasTerminalTitleLaunch(NSString *cwd) {
402
+ if (!cwd.isAbsolutePath) return NO;
403
+ NSString *directory = cwd.stringByStandardizingPath;
404
+ for (NSDictionary *launch in LoadLiveCodexLaunches().allValues) {
405
+ if ([launch[@"cwd"] isEqual:directory] && CodexLaunchTarget(launch)[@"bridgeTitleToken"]) return YES;
406
+ }
407
+ return NO;
408
+ }
409
+
331
410
  static void SaveCodexLaunches(NSDictionary *launches) {
332
411
  NSData *json = [NSJSONSerialization dataWithJSONObject:launches options:0 error:nil];
333
412
  NSString *path = CodexLaunchRegistryPath();
@@ -433,24 +512,57 @@ static NSDictionary *CodexThreadMeta(NSString *thread, NSDictionary *payload, NS
433
512
  return result;
434
513
  }
435
514
 
436
- // Codex 0.166 的本机日志记录每个 TUI 的就绪时刻和带 PID 的 process_uuid。
515
+ // Codex 的本机日志记录每个 TUI 的就绪时刻和带 PID 的 process_uuid。
516
+ // 初始会话可能先于首帧就绪(0.167.1 实测晚约 1.56ms 才记录就绪),不能要求就绪
517
+ // 一定早于会话创建。前后使用同一窄窗口,并在整个窗口内检查唯一性,避免两侧各有
518
+ // 一个候选时误配;SQL 的秒级范围与下面的精确时间过滤必须使用相同的上下界。
437
519
  // 只读这一类元数据,不读取提示词、输出或 HTTP 日志。内部日志格式改变、日志尚未落盘、
438
520
  // 多个客户端同时就绪时都不能猜测;sqlite 的读锁等待和返回条数也有上限。
439
521
  static int CodexLogQueryExpired(void *context) {
440
522
  return CFAbsoluteTimeGetCurrent() > *(CFAbsoluteTime *)context;
441
523
  }
442
524
 
443
- static NSString *ReadyCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
444
- NSArray<NSString *> *candidates, NSNumber *createdAt, NSString *codexHome) {
445
- if (!createdAt || createdAt.doubleValue <= 0) return nil;
525
+ static sqlite3 *OpenCodexLogs(NSString *codexHome) {
446
526
  NSString *path = [(codexHome.length ? codexHome : DefaultCodexHomeDirectory())
447
527
  stringByAppendingPathComponent:@"logs_2.sqlite"];
448
528
  sqlite3 *database = NULL;
449
529
  if (sqlite3_open_v2(path.fileSystemRepresentation, &database, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) {
450
530
  if (database) sqlite3_close(database);
451
- return nil;
531
+ return NULL;
452
532
  }
453
533
  sqlite3_busy_timeout(database, 50);
534
+ return database;
535
+ }
536
+
537
+ static NSString *RegisteredCodexLaunchForClient(const char *process, NSDictionary<NSString *, NSDictionary *> *launches,
538
+ NSArray<NSString *> *candidates, NSTimeInterval readyAt) {
539
+ if (!process || strncmp(process, "pid:", 4) != 0) return nil;
540
+ char *end;
541
+ long client = strtol(process + 4, &end, 10);
542
+ if (*end != ':' || client <= 1 || client > INT_MAX) return nil;
543
+ // With npm installs, the registered Node launcher is the parent of the native TUI.
544
+ pid_t pid = (pid_t)client;
545
+ for (NSUInteger depth = 0; depth < 8 && pid > 1; depth++) {
546
+ NSString *key = [NSString stringWithFormat:@"%d", pid];
547
+ NSDictionary *launch = launches[key];
548
+ if (launch) {
549
+ return [candidates containsObject:key] && readyAt >= [launch[@"processStartedAt"] doubleValue] &&
550
+ readyAt >= [launch[@"launchedAt"] doubleValue] ? key : nil;
551
+ }
552
+ struct kinfo_proc info;
553
+ if (!ProcessInfoForPID(pid, &info)) break;
554
+ struct timeval started = info.kp_proc.p_starttime;
555
+ if (readyAt < started.tv_sec + started.tv_usec / 1e6) break;
556
+ pid = info.kp_eproc.e_ppid;
557
+ }
558
+ return nil;
559
+ }
560
+
561
+ static NSString *ReadyCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
562
+ NSArray<NSString *> *candidates, NSNumber *createdAt, NSString *codexHome) {
563
+ if (candidates.count == 0 || !createdAt || createdAt.doubleValue <= 0) return nil;
564
+ sqlite3 *database = OpenCodexLogs(codexHome);
565
+ if (!database) return nil;
454
566
  CFAbsoluteTime deadline = CFAbsoluteTimeGetCurrent() + 0.15;
455
567
  sqlite3_progress_handler(database, 1000, CodexLogQueryExpired, &deadline);
456
568
  sqlite3_stmt *statement = NULL;
@@ -459,23 +571,20 @@ static NSString *ReadyCodexLaunch(NSDictionary<NSString *, NSDictionary *> *laun
459
571
  "AND feedback_log_body LIKE 'tui startup initial frame scheduled%' LIMIT 128";
460
572
  NSMutableSet<NSString *> *matches = [NSMutableSet set];
461
573
  BOOL complete = NO;
574
+ NSTimeInterval earliestReadyAt = createdAt.doubleValue - CodexClientReadyWindow;
575
+ NSTimeInterval latestReadyAt = createdAt.doubleValue + CodexClientReadyWindow;
462
576
  if (sqlite3_prepare_v2(database, query, -1, &statement, NULL) == SQLITE_OK) {
463
- sqlite3_bind_int64(statement, 1, (sqlite3_int64)floor(createdAt.doubleValue - CodexClientReadyWindow));
464
- sqlite3_bind_int64(statement, 2, (sqlite3_int64)ceil(createdAt.doubleValue));
577
+ sqlite3_bind_int64(statement, 1, (sqlite3_int64)floor(earliestReadyAt));
578
+ sqlite3_bind_int64(statement, 2, (sqlite3_int64)ceil(latestReadyAt));
465
579
  int result;
466
580
  NSUInteger rows = 0;
467
581
  while ((result = sqlite3_step(statement)) == SQLITE_ROW) {
468
582
  rows++;
469
583
  double readyAt = sqlite3_column_int64(statement, 0) + sqlite3_column_int64(statement, 1) / 1e9;
470
- if (readyAt > createdAt.doubleValue || readyAt < createdAt.doubleValue - CodexClientReadyWindow) continue;
471
- const unsigned char *value = sqlite3_column_text(statement, 2);
472
- NSString *process = value ? @((const char *)value) : @"";
473
- for (NSString *key in candidates) {
474
- NSDictionary *entry = launches[key];
475
- NSString *prefix = [NSString stringWithFormat:@"pid:%d:", [entry[@"pid"] intValue]];
476
- if ([process hasPrefix:prefix] && readyAt >= [entry[@"processStartedAt"] doubleValue] &&
477
- readyAt >= [entry[@"launchedAt"] doubleValue]) [matches addObject:key];
478
- }
584
+ if (readyAt < earliestReadyAt || readyAt > latestReadyAt) continue;
585
+ const char *process = (const char *)sqlite3_column_text(statement, 2);
586
+ NSString *key = RegisteredCodexLaunchForClient(process, launches, candidates, readyAt);
587
+ if (key) [matches addObject:key];
479
588
  }
480
589
  complete = result == SQLITE_DONE && rows < 128;
481
590
  }
@@ -484,6 +593,63 @@ static NSString *ReadyCodexLaunch(NSDictionary<NSString *, NSDictionary *> *laun
484
593
  return complete && matches.count == 1 ? matches.anyObject : nil;
485
594
  }
486
595
 
596
+ // 在 TUI 里用 /resume(或不带会话 ID 的 codex resume)接上旧会话时,命令行里没有会话 ID,
597
+ // 会话创建时刻也远早于 TUI 就绪。共享后台的日志记着是哪条 codex-tui 连接发起了 thread/resume;
598
+ // 同一后台进程里这条连接最早的请求紧跟在 TUI 就绪之后,把它当作就绪时刻交给 ReadyCodexLaunch。
599
+ // 桌面端连接的 client_name 不是 codex-tui,不会被配到终端上。
600
+ static NSNumber *CodexResumeClientConnectedAt(NSString *thread, NSTimeInterval earliest, NSString *codexHome) {
601
+ if (thread.length == 0 || !(earliest > 0)) return nil;
602
+ sqlite3 *database = OpenCodexLogs(codexHome);
603
+ if (!database) return nil;
604
+ CFAbsoluteTime deadline = CFAbsoluteTimeGetCurrent() + 0.15;
605
+ sqlite3_progress_handler(database, 1000, CodexLogQueryExpired, &deadline);
606
+ sqlite3_stmt *statement = NULL;
607
+ double resumedAt = 0;
608
+ NSString *process = nil, *connection = nil;
609
+ const char *resumeQuery = "SELECT ts, ts_nanos, process_uuid, feedback_log_body FROM logs "
610
+ "WHERE thread_id = ? AND feedback_log_body LIKE '%rpc.method=\"thread/resume\"%' "
611
+ "AND feedback_log_body LIKE '%app_server.client_name=\"codex-tui\"%' "
612
+ "ORDER BY ts DESC, ts_nanos DESC LIMIT 1";
613
+ if (sqlite3_prepare_v2(database, resumeQuery, -1, &statement, NULL) == SQLITE_OK) {
614
+ sqlite3_bind_text(statement, 1, thread.UTF8String, -1, SQLITE_TRANSIENT);
615
+ if (sqlite3_step(statement) == SQLITE_ROW) {
616
+ resumedAt = sqlite3_column_int64(statement, 0) + sqlite3_column_int64(statement, 1) / 1e9;
617
+ const char *uuid = (const char *)sqlite3_column_text(statement, 2);
618
+ const char *body = (const char *)sqlite3_column_text(statement, 3);
619
+ process = uuid ? @(uuid) : nil;
620
+ NSString *text = body ? @(body) : nil;
621
+ NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:
622
+ @"app_server\\.connection_id=([0-9]{1,9})[ }]" options:0 error:nil];
623
+ NSTextCheckingResult *match = text ? [pattern firstMatchInString:text options:0
624
+ range:NSMakeRange(0, text.length)] : nil;
625
+ if (match) connection = [text substringWithRange:[match rangeAtIndex:1]];
626
+ }
627
+ }
628
+ if (statement) sqlite3_finalize(statement);
629
+ statement = NULL;
630
+ NSNumber *connectedAt = nil;
631
+ // 连接号只在同一个后台进程内唯一,所以按 process_uuid 限定;时间下界是候选终端的登记时刻。
632
+ if (process.length > 0 && connection.length > 0 && resumedAt >= earliest) {
633
+ const char *startQuery = "SELECT ts, ts_nanos FROM logs WHERE ts BETWEEN ? AND ? AND process_uuid = ? "
634
+ "AND (feedback_log_body LIKE ? OR feedback_log_body LIKE ?) ORDER BY ts, ts_nanos LIMIT 1";
635
+ if (sqlite3_prepare_v2(database, startQuery, -1, &statement, NULL) == SQLITE_OK) {
636
+ NSString *spaced = [NSString stringWithFormat:@"%%app_server.connection_id=%@ %%", connection];
637
+ NSString *closed = [NSString stringWithFormat:@"%%app_server.connection_id=%@}%%", connection];
638
+ sqlite3_bind_int64(statement, 1, (sqlite3_int64)floor(earliest));
639
+ sqlite3_bind_int64(statement, 2, (sqlite3_int64)ceil(resumedAt));
640
+ sqlite3_bind_text(statement, 3, process.UTF8String, -1, SQLITE_TRANSIENT);
641
+ sqlite3_bind_text(statement, 4, spaced.UTF8String, -1, SQLITE_TRANSIENT);
642
+ sqlite3_bind_text(statement, 5, closed.UTF8String, -1, SQLITE_TRANSIENT);
643
+ if (sqlite3_step(statement) == SQLITE_ROW) {
644
+ connectedAt = @(sqlite3_column_int64(statement, 0) + sqlite3_column_int64(statement, 1) / 1e9);
645
+ }
646
+ }
647
+ if (statement) sqlite3_finalize(statement);
648
+ }
649
+ sqlite3_close(database);
650
+ return connectedAt;
651
+ }
652
+
487
653
  // 显式 resume 优先按会话 ID;新会话用客户端就绪证据。多个同目录客户端时不能用
488
654
  // “最新未绑定的进程”兜底:网络启动延迟和首次发消息的顺序都可能与启动顺序不同。
489
655
  static NSString *ChooseCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
@@ -503,7 +669,19 @@ static NSString *ChooseCodexLaunch(NSDictionary<NSString *, NSDictionary *> *lau
503
669
  if (resumed.count > 0) return resumed.count == 1 ? resumed.firstObject : nil;
504
670
  NSString *ready = ReadyCodexLaunch(launches, sameDirectory, createdAt, codexHome);
505
671
  if (ready) return ready;
506
- return sameDirectory.count == 1 ? sameDirectory.firstObject : nil;
672
+ NSTimeInterval earliest = 0;
673
+ for (NSString *key in sameDirectory) {
674
+ NSTimeInterval launchedAt = [launches[key][@"launchedAt"] doubleValue];
675
+ if (launchedAt > 0 && (earliest == 0 || launchedAt < earliest)) earliest = launchedAt;
676
+ }
677
+ NSNumber *connectedAt = CodexResumeClientConnectedAt(thread, earliest, codexHome);
678
+ NSString *resumedInClient = connectedAt ? ReadyCodexLaunch(launches, sameDirectory, connectedAt, codexHome) : nil;
679
+ if (resumedInClient) return resumedInClient;
680
+ if (sameDirectory.count != 1) return nil;
681
+ NSString *onlyLaunch = sameDirectory.firstObject;
682
+ // A shared host can also serve a desktop conversation in this directory. A title
683
+ // relay waits for its own TUI evidence, which may not have reached SQLite yet.
684
+ return CodexLaunchTarget(launches[onlyLaunch])[@"bridgeTitleToken"] ? nil : onlyLaunch;
507
685
  }
508
686
 
509
687
  static NSDictionary *CodexLaunchTerminalForThreadAtHome(NSString *thread, NSDictionary *payload,
@@ -511,43 +689,37 @@ static NSDictionary *CodexLaunchTerminalForThreadAtHome(NSString *thread, NSDict
511
689
  if (thread.length == 0) return @{};
512
690
  int lock = LockCodexLaunchRegistry();
513
691
  if (lock < 0) return @{};
514
- NSMutableDictionary<NSString *, NSDictionary *> *launches = LoadLiveCodexLaunches();
515
- NSDictionary *terminal = nil;
516
- for (NSDictionary *entry in launches.allValues) {
517
- if ([entry[@"threads"] containsObject:thread]) {
518
- terminal = entry[@"terminal"];
519
- break;
692
+ @try {
693
+ NSMutableDictionary<NSString *, NSDictionary *> *launches = LoadLiveCodexLaunches();
694
+ for (NSDictionary *entry in launches.allValues) {
695
+ if ([entry[@"threads"] containsObject:thread]) return CodexLaunchTarget(entry);
520
696
  }
521
- }
522
- if (!terminal) {
523
697
  NSDictionary *meta = CodexThreadMeta(thread, payload, codexHome);
524
698
  NSString *key = meta[@"cwd"] ? ChooseCodexLaunch(launches, meta[@"cwd"], meta[@"createdAt"], thread, codexHome) : nil;
525
- if (key) {
526
- NSMutableDictionary *entry = [launches[key] mutableCopy];
527
- NSMutableArray *threads = [entry[@"threads"] mutableCopy] ?: [NSMutableArray array];
528
- [threads addObject:thread];
529
- while (threads.count > CodexLaunchThreadLimit) [threads removeObjectAtIndex:0];
530
- entry[@"threads"] = threads;
531
- launches[key] = entry;
532
- terminal = entry[@"terminal"];
533
- }
699
+ if (!key) return @{};
700
+ NSMutableDictionary *entry = [launches[key] mutableCopy];
701
+ NSMutableArray *threads = [entry[@"threads"] mutableCopy] ?: [NSMutableArray array];
702
+ [threads addObject:thread];
703
+ while (threads.count > CodexLaunchThreadLimit) [threads removeObjectAtIndex:0];
704
+ entry[@"threads"] = threads;
705
+ launches[key] = entry;
706
+ SaveCodexLaunches(launches);
707
+ return CodexLaunchTarget(entry);
708
+ } @finally {
709
+ UnlockCodexLaunchRegistry(lock);
534
710
  }
535
- SaveCodexLaunches(launches);
536
- UnlockCodexLaunchRegistry(lock);
537
- return [terminal isKindOfClass:NSDictionary.class] ? terminal : @{};
538
711
  }
539
712
 
540
713
  NSDictionary *CodexLaunchTerminalForThread(NSString *thread, NSDictionary *payload) {
541
- return CodexLaunchTerminalForThreadAtHome(thread, payload, DefaultCodexHomeDirectory());
714
+ // 是路径,不能走 SanitizedShortString:它会删掉 `/`,拼出一个不存在的目录。
715
+ NSString *profileHome = NSProcessInfo.processInfo.environment[@"CC_PETS_PROFILE_HOME"];
716
+ profileHome = [profileHome isKindOfClass:NSString.class] && profileHome.isAbsolutePath
717
+ ? profileHome.stringByStandardizingPath : nil;
718
+ return CodexLaunchTerminalForThreadAtHome(thread, payload, profileHome);
542
719
  }
543
720
 
544
721
  NSDictionary *TerminalFocusTargetForHook(NSDictionary *payload, NSString *provider) {
545
722
  if (!TerminalFocusRunsUnderSharedAgentHost()) return TerminalFocusTargetFromEnvironment();
546
723
  if (![provider isEqualToString:@"Codex"]) return @{};
547
- // 是路径,不能走 SanitizedShortString:它会删掉 `/`,拼出一个不存在的目录。
548
- NSString *profileHome = NSProcessInfo.processInfo.environment[@"CC_PETS_PROFILE_HOME"];
549
- profileHome = [profileHome isKindOfClass:NSString.class] && profileHome.isAbsolutePath
550
- ? profileHome.stringByStandardizingPath : nil;
551
- return CodexLaunchTerminalForThreadAtHome(
552
- SanitizedShortString(payload[@"session_id"], 128), payload, profileHome);
724
+ return CodexLaunchTerminalForThread(SanitizedShortString(payload[@"session_id"], 128), payload);
553
725
  }
@@ -1,6 +1,7 @@
1
1
  #import "CCPetsPhrasesEditor.h"
2
2
  #import "CCPetsL10n.h"
3
3
  #import "CCPetsPhrases.h"
4
+ #import "CCPetsPreferences.h"
4
5
  #import "CCPetsUIStyle.h"
5
6
 
6
7
  static void (^PetPhrasesSpeakHandler)(NSString *);
@@ -491,6 +492,12 @@ static void (^PetPhrasesSpeakHandler)(NSString *);
491
492
  [self showStatus:[NSString stringWithFormat:L(@"[%@] has no usable lines."), tag] warning:YES];
492
493
  return;
493
494
  }
495
+ // 「仅菜单栏」时桌宠藏着,说了也看不见;照实告诉用户,句子本身仍然显示出来。
496
+ if ([CCPetsDisplayMode() isEqualToString:CCPetsDisplayModeMenuBar]) {
497
+ [self showStatus:[NSString stringWithFormat:L(@"The pet is hidden (menu bar only). Line: %@"), text]
498
+ warning:YES];
499
+ return;
500
+ }
494
501
  if (PetPhrasesSpeakHandler) PetPhrasesSpeakHandler(text);
495
502
  [self showStatus:[NSString stringWithFormat:L(@"Trying: %1$@%2$@"), text,
496
503
  fellBack ? L(@" (from the shared lines)") : @""] warning:NO];
@@ -1,6 +1,7 @@
1
1
  #import "CCPetsPreviews.h"
2
2
  #import "CCPetsL10n.h"
3
3
  #import "QuotaDashboardView.h"
4
+ #import "CCPetsProviderRegistry.h"
4
5
  #import "MenuToggleSwitch.h"
5
6
  #import "CCPetsUsage.h"
6
7
  #import "PetView.h"
@@ -13,11 +14,16 @@ int RenderQuotaDashboard(NSString *path) {
13
14
  QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale)];
14
15
  // 本地视觉验收可用 CC_PETS_PREVIEW_API=1 渲染 API 用量态,不改用户偏好。
15
16
  BOOL previewsAPIUsage = [NSProcessInfo.processInfo.environment[@"CC_PETS_PREVIEW_API"] boolValue];
16
- view.codexShowsAPIUsage = previewsAPIUsage;
17
- view.claudeShowsAPIUsage = previewsAPIUsage;
18
- view.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
19
- view.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
20
- view.codexUsage = LatestUsage() ?: @{
17
+ NSMutableDictionary *showsAPIUsageByProvider = [NSMutableDictionary dictionary];
18
+ NSMutableDictionary *logoByProvider = [NSMutableDictionary dictionary];
19
+ for (CCPetsProviderDescriptor *provider in CCPetsProviderDescriptors()) {
20
+ showsAPIUsageByProvider[provider.name] = @(previewsAPIUsage);
21
+ NSImage *logo = OfficialAppIcon(provider.logoBundleIdentifier, provider.logoResourceName);
22
+ if (logo) logoByProvider[provider.name] = logo;
23
+ }
24
+ view.showsAPIUsageByProvider = showsAPIUsageByProvider;
25
+ view.logoByProvider = logoByProvider;
26
+ NSDictionary *codexUsage = LatestUsage() ?: @{
21
27
  @"fiveHour": @{@"used_percent": @34, @"resets_at": @([NSDate.date timeIntervalSince1970] + 7200)},
22
28
  @"week": @{@"used_percent": @51, @"resets_at": @([NSDate.date timeIntervalSince1970] + 172800)},
23
29
  @"tokenUsage": @{
@@ -28,7 +34,7 @@ int RenderQuotaDashboard(NSString *path) {
28
34
  @"source": @"local"
29
35
  }
30
36
  };
31
- view.claudeUsage = LatestClaudeUsage() ?: @{
37
+ NSDictionary *claudeUsage = LatestClaudeUsage() ?: @{
32
38
  @"fiveHour": @{@"used_percentage": @23, @"resets_at": @([NSDate.date timeIntervalSince1970] + 3600)},
33
39
  @"week": @{@"used_percentage": @41, @"resets_at": @([NSDate.date timeIntervalSince1970] + 86400)},
34
40
  @"tokenUsage": @{
@@ -39,9 +45,10 @@ int RenderQuotaDashboard(NSString *path) {
39
45
  @"source": @"local"
40
46
  }
41
47
  };
48
+ view.usageByProvider = @{@"Codex": codexUsage, @"Claude": claudeUsage};
42
49
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
43
50
  NSTimeInterval day = 24 * 60 * 60;
44
- view.codexHistory = @[
51
+ NSArray<NSDictionary *> *codexHistory = @[
45
52
  @{@"timestamp": @(now - 6.5 * day), @"remaining": @88},
46
53
  @{@"timestamp": @(now - 5.5 * day), @"remaining": @81},
47
54
  @{@"timestamp": @(now - 4.5 * day), @"remaining": @75},
@@ -50,7 +57,7 @@ int RenderQuotaDashboard(NSString *path) {
50
57
  @{@"timestamp": @(now - 1.5 * day), @"remaining": @55},
51
58
  @{@"timestamp": @(now - 0.5 * day), @"remaining": @49}
52
59
  ];
53
- view.claudeHistory = @[
60
+ NSArray<NSDictionary *> *claudeHistory = @[
54
61
  @{@"timestamp": @(now - 6.5 * day), @"remaining": @92},
55
62
  @{@"timestamp": @(now - 5.5 * day), @"remaining": @86},
56
63
  @{@"timestamp": @(now - 4.5 * day), @"remaining": @78},
@@ -59,6 +66,7 @@ int RenderQuotaDashboard(NSString *path) {
59
66
  @{@"timestamp": @(now - 1.5 * day), @"remaining": @58},
60
67
  @{@"timestamp": @(now - 0.5 * day), @"remaining": @51}
61
68
  ];
69
+ view.historyByProvider = @{@"Codex": codexHistory, @"Claude": claudeHistory};
62
70
  view.activeAgentCount = 1;
63
71
  // 预览里刻意只让一家在线,好把"有额度数据但客户端已退出"的离线态也画出来。
64
72
  view.liveProviders = [NSSet setWithObject:@"Claude"];
@@ -23,6 +23,20 @@ static const CGFloat PetMenuControlGap = 8.0;
23
23
  static const NSInteger PetMenuCheckViewTag = 1001;
24
24
  static const NSInteger PetMenuDeleteButtonTag = 1002;
25
25
 
26
+ // AppKit 单独创建菜单和玻璃背景窗口。只给父面板设置 Space 策略,背景仍可能留在普通桌面。
27
+ static void PetJoinMenuWindowsToSpaces(NSWindow *parent) {
28
+ for (NSWindow *child in parent.childWindows) {
29
+ NSWindowCollectionBehavior behavior = child.collectionBehavior;
30
+ behavior &= ~(NSWindowCollectionBehaviorMoveToActiveSpace | NSWindowCollectionBehaviorFullScreenNone |
31
+ NSWindowCollectionBehaviorFullScreenPrimary | NSWindowCollectionBehaviorPrimary |
32
+ NSWindowCollectionBehaviorAuxiliary);
33
+ behavior |= NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary |
34
+ NSWindowCollectionBehaviorCanJoinAllApplications;
35
+ if (child.collectionBehavior != behavior) child.collectionBehavior = behavior;
36
+ PetJoinMenuWindowsToSpaces(child);
37
+ }
38
+ }
39
+
26
40
  @implementation PetView (Menu)
27
41
  - (void)selectPetFromButton:(NSButton *)sender {
28
42
  NSString *petID = sender.identifier;
@@ -408,7 +422,7 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
408
422
  action:action width:PetSubmenuRowWidth tag:tag];
409
423
  ((MenuHintRowView *)item.view).hint = toolTip;
410
424
  }
411
- // 一级子菜单只放启用和最常动的两个开关(开关在上、二级菜单在下);免审批(设一次就不动)和只影响桌宠的提醒各收进二级菜单。
425
+ // 一级子菜单放常用开关;免审批和只影响桌宠的提醒各收进二级菜单。
412
426
  // 未开启时只留"启用"一行:其余开关此时都不生效,列出来只是占地方。开启是异步的,
413
427
  // 菜单停留期间不会自己长出其余项,下次打开时按实际状态重建。
414
428
  - (void)addBridgeMenuToMenu:(NSMenu *)menu {
@@ -420,7 +434,7 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
420
434
  BOOL enabled = CCBridgeEnabled();
421
435
  [self addBridgeSwitchToMenu:bridgeMenu title:L(@"Enable") checked:enabled
422
436
  action:@selector(toggleBridgeEnabled:) tag:0
423
- toolTip:L(@"Let local Claude Code / Codex sessions message and wake each other and reserve files")];
437
+ toolTip:L(@"Let local Agent sessions exchange messages, wake supported sessions, and reserve files")];
424
438
  if (!enabled) return;
425
439
 
426
440
  // 状态放在"启用"行的第二行,省掉底部单独的状态行和分隔线。开关上移与标题对齐,
@@ -451,9 +465,12 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
451
465
  [self addBridgeSwitchToMenu:bridgeMenu title:L(@"Edit guard") checked:[options[@"editGuard"] boolValue]
452
466
  action:@selector(toggleBridgeEditGuard:) tag:0
453
467
  toolTip:L(@"Pause once with an explanation when editing a file another session reserved; retrying goes through. Codex needs a session restart")];
468
+ [self addBridgeSwitchToMenu:bridgeMenu title:L(@"Tab nicknames") checked:[options[@"tabTitle"] boolValue]
469
+ action:@selector(toggleBridgeTabTitle:) tag:0
470
+ toolTip:L(@"Append CC Bridge nicknames to terminal tab titles. Restart CLI sessions after turning this on.")];
454
471
 
455
472
  NSMenuItem *approvalItem = [bridgeMenu addItemWithTitle:L(@"Auto-approve") action:nil keyEquivalent:@""];
456
- approvalItem.representedObject = L(@"Each group applies to both Codex approvals and Claude permissions. Codex needs a session restart");
473
+ approvalItem.representedObject = L(@"Each group applies to the integrated Agents. Restart sessions to reload tool permissions");
457
474
  NSMenu *approvalMenu = [NSMenu new];
458
475
  NSArray<NSDictionary *> *groups = @[
459
476
  @{@"title": L(@"Read"), @"group": @"view", @"tag": @1,
@@ -467,9 +484,12 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
467
484
  ];
468
485
  NSSet *codex = [NSSet setWithArray:options[@"codexApprove"]];
469
486
  NSSet *claude = [NSSet setWithArray:options[@"claudeAllow"]];
487
+ NSSet *agy = [NSSet setWithArray:options[@"antigravityAllow"]];
488
+ BOOL hasAntigravity = CCPetsProfilesForProvider(CCPetsProfileProviderAntigravity).count > 0;
470
489
  for (NSDictionary *group in groups) {
471
490
  NSSet *tools = [NSSet setWithArray:CCBridgeToolGroup(group[@"group"])];
472
- BOOL checked = tools.count > 0 && [tools isSubsetOfSet:codex] && [tools isSubsetOfSet:claude];
491
+ BOOL checked = tools.count > 0 && [tools isSubsetOfSet:codex] && [tools isSubsetOfSet:claude] &&
492
+ (!hasAntigravity || [tools isSubsetOfSet:agy]);
473
493
  [self addBridgeSwitchToMenu:approvalMenu title:group[@"title"] checked:checked
474
494
  action:@selector(toggleBridgeApproval:) tag:[group[@"tag"] integerValue] toolTip:group[@"tip"]];
475
495
  }
@@ -490,6 +510,36 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
490
510
  }
491
511
 
492
512
  - (void)rightMouseDown:(NSEvent *)event {
513
+ // 桌宠同时出现在多个 Space。用点击处的单独面板定位菜单,避免菜单跟随桌宠的原始桌面。
514
+ NSPoint click = [self.window convertPointToScreen:event.locationInWindow];
515
+ NSPanel *anchor = [[NSPanel alloc] initWithContentRect:NSMakeRect(click.x, click.y, 1, 1)
516
+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
517
+ backing:NSBackingStoreBuffered defer:NO];
518
+ anchor.opaque = NO;
519
+ anchor.backgroundColor = NSColor.clearColor;
520
+ anchor.hasShadow = NO;
521
+ anchor.hidesOnDeactivate = NO;
522
+ anchor.level = self.window.level;
523
+ anchor.collectionBehavior = NSWindowCollectionBehaviorMoveToActiveSpace |
524
+ NSWindowCollectionBehaviorTransient | NSWindowCollectionBehaviorFullScreenAuxiliary |
525
+ NSWindowCollectionBehaviorCanJoinAllApplications;
526
+ [anchor orderFrontRegardless];
527
+
528
+ NSMenu *menu = [self buildContextMenu];
529
+ CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(NULL, kCFRunLoopBeforeWaiting,
530
+ true, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
531
+ PetJoinMenuWindowsToSpaces(anchor);
532
+ });
533
+ CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
534
+ NSPoint location = [anchor.contentView convertPoint:[anchor convertPointFromScreen:click] fromView:nil];
535
+ [menu popUpMenuPositioningItem:nil atLocation:location inView:anchor.contentView];
536
+ CFRunLoopObserverInvalidate(observer);
537
+ CFRelease(observer);
538
+ [anchor orderOut:nil];
539
+ [self finishContextMenu];
540
+ }
541
+ // 菜单栏图标的右键菜单也是这一份,所以建菜单和收尾分开,不和 NSEvent 绑在一起。
542
+ - (NSMenu *)buildContextMenu {
493
543
  NSArray<NSDictionary *> *availablePets = self.petOptionsRequested ? self.petOptionsRequested() : @[];
494
544
  NSMenu *menu = [NSMenu new];
495
545
  menu.minimumWidth = 194.0;
@@ -529,6 +579,12 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
529
579
  preferenceKey:key tag:codex ? 1 : 2 profile:profile];
530
580
  }
531
581
  }
582
+ for (NSDictionary *profile in CCPetsProfilesForProvider(CCPetsProfileProviderAntigravity)) {
583
+ NSString *name = CCPetsProfileIsOfficialDefault(profile) && ![profile[@"customName"] boolValue]
584
+ ? @"Antigravity CLI" : [NSString stringWithFormat:@"Antigravity CLI · %@", profile[@"displayName"]];
585
+ [self addUsageModeControlToMenu:usageModeMenu provider:name preferenceKey:CCPetsUsageModePreferenceKey(profile)
586
+ tag:0 profile:profile];
587
+ }
532
588
  usageModeItem.submenu = usageModeMenu;
533
589
  NSMenuItem *themeItem = [menu addItemWithTitle:L(@"Panel Theme") action:nil keyEquivalent:@""];
534
590
  NSMenu *themeMenu = [[NSMenu alloc] initWithTitle:L(@"Panel Theme")];
@@ -590,7 +646,10 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
590
646
  openItem.target = NSApp.delegate;
591
647
  NSMenuItem *quitItem = [menu addItemWithTitle:L(@"Quit CC Pets") action:@selector(terminate:) keyEquivalent:@"q"];
592
648
  quitItem.target = NSApp;
593
- [NSMenu popUpContextMenu:menu withEvent:event forView:self];
649
+ return menu;
650
+ }
651
+ // 菜单收起后:收掉悬停说明和宠物预览浮窗。
652
+ - (void)finishContextMenu {
594
653
  [MenuHint cancel];
595
654
  self.activePetSwitchMenu = nil;
596
655
  [self.petMenuPreviewPanel orderOut:nil];
@@ -42,5 +42,12 @@
42
42
  - (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount;
43
43
  - (void)applySheet:(NSImage *)sheet petID:(NSString *)petID rowCount:(NSInteger)rowCount;
44
44
  - (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed;
45
+ - (void)resetAgentToIdle;
45
46
  - (void)playRow:(NSInteger)row throughFrame:(NSInteger)last oneShot:(BOOL)oneShot;
46
47
  @end
48
+
49
+ // 右键菜单(现建)与菜单收起后的收尾,实现在 PetView+Menu.m。桌宠右键和菜单栏图标右键共用。
50
+ @interface PetView (Menu)
51
+ - (NSMenu *)buildContextMenu;
52
+ - (void)finishContextMenu;
53
+ @end
@@ -374,7 +374,18 @@ static const NSTimeInterval PetBreathPeriod = 3.6;
374
374
  NSUInteger hold = self.frameHolds[index].unsignedIntegerValue;
375
375
  return hold > 0 ? hold : 1;
376
376
  }
377
+ - (void)resetAgentToIdle {
378
+ [self noteActivity];
379
+ self.agentActive = NO;
380
+ if (self.microActive) [self endMicroBehavior];
381
+ [self playRow:0 throughFrame:5 oneShot:NO];
382
+ }
377
383
  - (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed {
384
+ // 会话退出不代表任务成功;直接恢复待机,不播放完成动作。
385
+ if ([event isEqualToString:@"SessionEnd"]) {
386
+ [self resetAgentToIdle];
387
+ return;
388
+ }
378
389
  [self noteActivity];
379
390
  [self bumpExertion];
380
391
  if ([event isEqualToString:@"SessionStart"]) {
@@ -418,7 +429,7 @@ static const NSTimeInterval PetBreathPeriod = 3.6;
418
429
  self.agentActive = YES;
419
430
  [self playRow:4 throughFrame:4 oneShot:YES];
420
431
  } else if ([event isEqualToString:@"Stop"] || [event isEqualToString:@"SubagentStop"] ||
421
- [event isEqualToString:@"TaskCompleted"] || [event isEqualToString:@"SessionEnd"]) {
432
+ [event isEqualToString:@"TaskCompleted"]) {
422
433
  self.agentActive = YES;
423
434
  [self playRow:3 throughFrame:3 oneShot:YES];
424
435
  }