cc-pets 2.3.0 → 2.4.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 (76) hide show
  1. package/CC_BRIDGE.md +19 -0
  2. package/CC_BRIDGE.zh-CN.md +15 -0
  3. package/CHANGELOG.md +51 -0
  4. package/CHANGELOG.zh-CN.md +51 -0
  5. package/CONTRIBUTING.md +22 -0
  6. package/CONTRIBUTING.zh-CN.md +17 -0
  7. package/README.md +117 -26
  8. package/README.zh-CN.md +92 -22
  9. package/Resources/AgentIcons/claude.png +0 -0
  10. package/Resources/AgentIcons/codex.icns +0 -0
  11. package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
  12. package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
  13. package/Resources/zh-Hans.lproj/Localizable.strings +155 -27
  14. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +12 -6
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +1 -1
  16. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +3 -6
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +113 -47
  18. package/Sources/CCPets/App/CCPetsAppDelegate.h +2 -2
  19. package/Sources/CCPets/App/main.m +6 -0
  20. package/Sources/CCPets/Bridge/CCPetsBridge.m +11 -6
  21. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +78 -38
  22. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +2 -3
  23. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +50 -32
  24. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +46 -40
  25. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +9 -6
  26. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +171 -53
  27. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
  28. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
  29. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
  30. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
  31. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +2 -1
  32. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +107 -25
  33. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
  34. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
  35. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
  36. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
  37. package/Sources/CCPets/Pet/PetView+Menu.m +2 -2
  38. package/Sources/CCPets/Support/CCPetsDoctor.m +26 -12
  39. package/Sources/CCPets/Support/CCPetsPreferences.h +2 -0
  40. package/Sources/CCPets/Support/CCPetsPreferences.m +34 -2
  41. package/Sources/CCPets/UI/CCPetsFormBuilder.h +2 -0
  42. package/Sources/CCPets/UI/CCPetsFormBuilder.m +18 -7
  43. package/Sources/CCPets/UI/CCPetsGlassView.h +26 -4
  44. package/Sources/CCPets/UI/CCPetsGlassView.m +40 -9
  45. package/Sources/CCPets/UI/CCPetsSettingsPage.h +2 -0
  46. package/Sources/CCPets/UI/CCPetsSettingsPage.m +561 -66
  47. package/Sources/CCPets/UI/CCPetsUIStyle.h +5 -2
  48. package/Sources/CCPets/UI/CCPetsUIStyle.m +57 -8
  49. package/Sources/CCPets/UI/CCPetsUsageChartView.m +4 -0
  50. package/Sources/CCPets/UI/CCPetsUsagePage.m +23 -28
  51. package/Sources/CCPets/UI/CCPetsUsageStore.m +2 -2
  52. package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
  53. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +1 -0
  54. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +49 -11
  55. package/Sources/CCPets/Usage/CCPetsUsage.h +3 -2
  56. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +15 -17
  57. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +11 -29
  58. package/Sources/CCPets/Usage/QuotaDashboardView.m +128 -2
  59. package/THIRD_PARTY_NOTICES.md +7 -3
  60. package/THIRD_PARTY_NOTICES.zh-CN.md +5 -1
  61. package/bin/claude-with-pet +2 -0
  62. package/bin/codex-with-pet +2 -0
  63. package/package.json +5 -1
  64. package/plugins/jetbrains/README.md +62 -0
  65. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
  66. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
  67. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
  68. package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
  69. package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
  70. package/plugins/vscode/README.md +63 -0
  71. package/plugins/vscode/extension.js +210 -0
  72. package/plugins/vscode/package.json +18 -0
  73. package/scripts/build-idea-plugin.sh +101 -0
  74. package/scripts/build-vscode-extension.sh +112 -0
  75. package/scripts/build.sh +24 -2
  76. package/scripts/compile-cached.zsh +133 -0
@@ -6,6 +6,7 @@
6
6
  #import <CommonCrypto/CommonDigest.h>
7
7
  #import <sys/sysctl.h>
8
8
  #import <sys/stat.h>
9
+ #import <sys/file.h>
9
10
  #import <fcntl.h>
10
11
  #import <signal.h>
11
12
  #import <unistd.h>
@@ -75,7 +76,8 @@ BOOL CCBridgeMigrateLegacyFlag(void) {
75
76
 
76
77
  void CCBridgeSetEnabled(BOOL enabled, NSDictionary *options) {
77
78
  if (!enabled) {
78
- unlink(EnabledFlagPath().fileSystemRepresentation);
79
+ if (unlink(EnabledFlagPath().fileSystemRepresentation) != 0 && errno != ENOENT)
80
+ [NSException raise:@"CCBridgeConfig" format:@"%@: %s", EnabledFlagPath(), strerror(errno)];
79
81
  return;
80
82
  }
81
83
  EnsureHomeDirectory();
@@ -85,7 +87,9 @@ void CCBridgeSetEnabled(BOOL enabled, NSDictionary *options) {
85
87
  NSISO8601DateFormatter *formatter = [NSISO8601DateFormatter new];
86
88
  formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime | NSISO8601DateFormatWithFractionalSeconds;
87
89
  document[@"enabledAt"] = [formatter stringFromDate:NSDate.date];
88
- CCPetsWriteFileAtomically(EnabledFlagPath(), [CCPetsJSONStringify(document) stringByAppendingString:@"\n"], 0600, NULL);
90
+ NSString *error = nil;
91
+ if (!CCPetsWriteFileAtomically(EnabledFlagPath(), [CCPetsJSONStringify(document) stringByAppendingString:@"\n"], 0600, &error))
92
+ [NSException raise:@"CCBridgeConfig" format:@"%@", error ?: @"Could not save bridge settings"];
89
93
  }
90
94
 
91
95
  void CCBridgeWriteCLILocator(void) {
@@ -247,6 +251,17 @@ static NSArray<NSString *> *ListJSON(NSString *directory) {
247
251
  return [names sortedArrayUsingSelector:@selector(compare:)];
248
252
  }
249
253
 
254
+ static NSString *WaitForLock(NSString *name) {
255
+ // hook 有执行时限;锁繁忙时明确失败,不能无锁继续覆盖状态。
256
+ for (NSUInteger attempt = 0; attempt < 200; attempt++) {
257
+ NSString *lock = CCBridgeAcquireLock(name);
258
+ if (lock) return lock;
259
+ usleep(10000);
260
+ }
261
+ [NSException raise:@"CCBridgeLock" format:@"Timed out waiting for bridge lock: %@", name];
262
+ return nil;
263
+ }
264
+
250
265
  #pragma mark - 会话注册表
251
266
 
252
267
  NSString *CCBridgeSessionRef(NSString *sessionId) {
@@ -276,7 +291,27 @@ NSArray<NSDictionary *> *CCBridgeListSessions(void) {
276
291
 
277
292
  void CCBridgeRemoveSession(id sessionId) {
278
293
  NSString *safe = CCBridgeSafeSessionId(sessionId);
279
- if (safe) unlink(SessionFile(safe).fileSystemRepresentation);
294
+ if (!safe) return;
295
+ NSString *lock = WaitForLock(@"sessions");
296
+ @try { unlink(SessionFile(safe).fileSystemRepresentation); }
297
+ @finally { CCBridgeReleaseLock(lock); }
298
+ }
299
+
300
+ void CCBridgeRemoveSessionIfOffline(id sessionId) {
301
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
302
+ if (!safe) return;
303
+ NSString *lock = WaitForLock(@"sessions");
304
+ @try {
305
+ if (!CCBridgeSessionLive(CCBridgeReadSession(safe))) unlink(SessionFile(safe).fileSystemRepresentation);
306
+ } @finally { CCBridgeReleaseLock(lock); }
307
+ }
308
+
309
+ static NSArray<NSDictionary *> *RegisteredLiveSessions(void) {
310
+ NSMutableArray *sessions = [NSMutableArray array];
311
+ for (NSDictionary *session in CCBridgeListSessions()) {
312
+ if (CCBridgeSessionLive(session)) [sessions addObject:session];
313
+ }
314
+ return sessions;
280
315
  }
281
316
 
282
317
  // 小写,连续的非 [a-z0-9] 合并成 -,截到 limit 后去掉首尾的 -;结果可能为空。
@@ -350,8 +385,9 @@ static NSString *AllocateName(NSString *provider, NSString *profileName, NSStrin
350
385
  static NSString *AllocateCustomName(NSString *name, NSString *sessionId, NSArray<NSDictionary *> *liveSessions) {
351
386
  if (!NameTakenBy(name, sessionId, liveSessions)) return name;
352
387
  for (NSUInteger index = 2; ; index++) {
353
- NSString *candidate = [NSString stringWithFormat:@"%@-%lu", name, (unsigned long)index];
354
- if (candidate.length > 40) candidate = [candidate substringToIndex:40];
388
+ NSString *suffix = [NSString stringWithFormat:@"-%lu", (unsigned long)index];
389
+ NSString *base = [name substringToIndex:MIN(name.length, 40 - suffix.length)];
390
+ NSString *candidate = [base stringByAppendingString:suffix];
355
391
  if (!NameTakenBy(candidate, sessionId, liveSessions)) return candidate;
356
392
  }
357
393
  }
@@ -365,7 +401,7 @@ NSString *CCBridgeNormalizeSessionName(id value) {
365
401
  return [pattern firstMatchInString:name options:0 range:NSMakeRange(0, name.length)] ? name : nil;
366
402
  }
367
403
 
368
- NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
404
+ static NSDictionary *UpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
369
405
  NSString *tty, NSString *status, NSString *preferredName, NSString *profileID,
370
406
  NSString *profileName, NSArray<NSDictionary *> *liveSessions) {
371
407
  NSString *safe = CCBridgeSafeSessionId(sessionId);
@@ -381,6 +417,9 @@ NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSN
381
417
  if (cwd.length > 0) record[@"cwd"] = cwd;
382
418
  if (tty.length > 0) record[@"tty"] = tty;
383
419
  if (profileID.length > 0) record[@"profileId"] = profileID;
420
+ NSString *home = CCPetsEnvironmentValue(@"CC_PETS_PROFILE_HOME");
421
+ if (home.length == 0 && [provider isEqual:@"Codex"]) home = CCPetsCodexHome();
422
+ if (home.length > 0) record[@"home"] = home;
384
423
  if (profileName.length > 0) record[@"profileName"] = profileName;
385
424
  if (!StringValue(record[@"name"])) {
386
425
  NSString *custom = CCBridgeNormalizeSessionName(preferredName);
@@ -394,7 +433,7 @@ NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSN
394
433
  return record;
395
434
  }
396
435
 
397
- NSDictionary *CCBridgeRenameSession(NSString *sessionId, NSString *requestedName, NSArray<NSDictionary *> *liveSessions) {
436
+ static NSDictionary *RenameSession(NSString *sessionId, NSString *requestedName, NSArray<NSDictionary *> *liveSessions) {
398
437
  NSMutableDictionary *record = [CCBridgeReadSession(sessionId) mutableCopy];
399
438
  if (!record) return @{@"error": L(@"This session isn't registered yet.")};
400
439
  NSString *name = CCBridgeNormalizeSessionName(requestedName);
@@ -413,6 +452,22 @@ NSDictionary *CCBridgeRenameSession(NSString *sessionId, NSString *requestedName
413
452
  return @{@"session": record, @"previous": previous};
414
453
  }
415
454
 
455
+ NSDictionary *CCBridgeUpsertSession(NSString *sessionId, NSString *provider, NSNumber *pid, NSString *cwd,
456
+ NSString *tty, NSString *status, NSString *preferredName, NSString *profileID,
457
+ NSString *profileName, NSArray<NSDictionary *> *liveSessions) {
458
+ NSString *lock = WaitForLock(@"sessions");
459
+ @try {
460
+ return UpsertSession(sessionId, provider, pid, cwd, tty, status, preferredName, profileID,
461
+ profileName, CCBridgeReadSession(sessionId) ? @[] : RegisteredLiveSessions());
462
+ } @finally { CCBridgeReleaseLock(lock); }
463
+ }
464
+
465
+ NSDictionary *CCBridgeRenameSession(NSString *sessionId, NSString *requestedName, NSArray<NSDictionary *> *liveSessions) {
466
+ NSString *lock = WaitForLock(@"sessions");
467
+ @try { return RenameSession(sessionId, requestedName, RegisteredLiveSessions()); }
468
+ @finally { CCBridgeReleaseLock(lock); }
469
+ }
470
+
416
471
  #pragma mark - 消息
417
472
 
418
473
  NSString *CCBridgeNewMessageId(void) {
@@ -451,12 +506,18 @@ void CCBridgeWriteReceipt(NSDictionary *message) {
451
506
  }
452
507
 
453
508
  NSDictionary *CCBridgeUpdateReceipt(NSString *messageId, NSDictionary *patch) {
454
- NSMutableDictionary *next = [CCBridgeReadReceipt(messageId) mutableCopy];
455
- if (!next) return nil;
456
- [next addEntriesFromDictionary:patch];
457
- next[@"updatedAt"] = @(CCPetsMilliseconds());
458
- CCBridgeWriteReceipt(next);
459
- return next;
509
+ if (!IsMessageId(messageId)) return nil;
510
+ NSString *lock = WaitForLock(@"receipts");
511
+ @try {
512
+ NSMutableDictionary *next = [CCBridgeReadReceipt(messageId) mutableCopy];
513
+ if (!next) return nil;
514
+ // 终态不能被迟到的 pending、失败回调等覆盖。
515
+ if ([@[@"delivered", @"expired", @"undeliverable"] containsObject:next[@"status"]]) return next;
516
+ [next addEntriesFromDictionary:patch];
517
+ next[@"updatedAt"] = @(CCPetsMilliseconds());
518
+ CCBridgeWriteReceipt(next);
519
+ return next;
520
+ } @finally { CCBridgeReleaseLock(lock); }
460
521
  }
461
522
 
462
523
  NSArray<NSDictionary *> *CCBridgeListReceipts(void) {
@@ -501,46 +562,91 @@ void CCBridgeEnqueueInbox(NSDictionary *message) {
501
562
  [message[@"id"] stringByAppendingString:@".json"]], message);
502
563
  }
503
564
 
565
+ static NSString *InboxLockFile(NSString *sessionId) {
566
+ return [CCBridgeSubdirectory(@[@"locks"]) stringByAppendingPathComponent:
567
+ [NSString stringWithFormat:@"inbox-%@.pid", sessionId]];
568
+ }
569
+
570
+ // 持有每个信箱的内核锁直到输出成功。崩溃后 claimed 保留,下次消费者会重新读取。
504
571
  NSArray<NSDictionary *> *CCBridgeClaimInbox(id sessionId) {
505
572
  NSString *safe = CCBridgeSafeSessionId(sessionId);
506
573
  if (!safe) return @[];
507
- NSString *inbox = CCBridgeSubdirectory(@[@"inbox", safe]);
508
- NSString *claimed = CCBridgeSubdirectory(@[@"claimed", safe]);
509
- long long now = CCPetsMilliseconds();
510
- NSMutableArray<NSDictionary *> *messages = [NSMutableArray array];
511
- for (NSString *name in ListJSON(inbox)) {
512
- NSString *source = [inbox stringByAppendingPathComponent:name];
513
- NSString *destination = [claimed stringByAppendingPathComponent:name];
514
- if (rename(source.fileSystemRepresentation, destination.fileSystemRepresentation) != 0) continue;
515
- id message = CCBridgeReadJSON(destination);
516
- unlink(destination.fileSystemRepresentation);
517
- if (![message isKindOfClass:NSDictionary.class]) continue;
518
- if (now - NumberValue(message[@"createdAt"]) > CCBridgeMessageTTL) {
519
- CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"expired"});
520
- continue;
574
+ NSString *lock = CCBridgeAcquireLock([@"inbox-" stringByAppendingString:safe]);
575
+ if (!lock) return @[];
576
+ @try {
577
+ NSString *inbox = CCBridgeSubdirectory(@[@"inbox", safe]);
578
+ NSString *claimed = CCBridgeSubdirectory(@[@"claimed", safe]);
579
+ for (NSString *name in ListJSON(inbox)) {
580
+ NSString *source = [inbox stringByAppendingPathComponent:name];
581
+ NSString *destination = [claimed stringByAppendingPathComponent:name];
582
+ if ([NSFileManager.defaultManager fileExistsAtPath:destination]) continue;
583
+ if (rename(source.fileSystemRepresentation, destination.fileSystemRepresentation) != 0 && errno != ENOENT)
584
+ [NSException raise:@"CCBridgeInbox" format:@"%@: %s", source, strerror(errno)];
585
+ }
586
+ NSMutableArray *messages = [NSMutableArray array];
587
+ for (NSString *name in ListJSON(claimed)) {
588
+ NSString *file = [claimed stringByAppendingPathComponent:name];
589
+ id message = CCBridgeReadJSON(file);
590
+ if (![message isKindOfClass:NSDictionary.class] || !IsMessageId(message[@"id"])) continue;
591
+ NSString *status = CCBridgeReadReceipt(message[@"id"])[@"status"];
592
+ if ([@[@"delivered", @"expired", @"undeliverable"] containsObject:status ?: @""]) {
593
+ unlink(file.fileSystemRepresentation);
594
+ continue;
595
+ }
596
+ if (CCPetsMilliseconds() - NumberValue(message[@"createdAt"]) > CCBridgeMessageTTL) {
597
+ CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"expired"});
598
+ unlink(file.fileSystemRepresentation);
599
+ continue;
600
+ }
601
+ [messages addObject:message];
521
602
  }
522
- [messages addObject:message];
603
+ if (messages.count == 0) CCBridgeReleaseLock(lock);
604
+ return messages;
605
+ } @catch (NSException *exception) {
606
+ CCBridgeReleaseLock(lock);
607
+ @throw;
523
608
  }
524
- return messages;
609
+ }
610
+
611
+ void CCBridgeFinishInbox(id sessionId, NSArray<NSDictionary *> *messages, NSString *transport) {
612
+ NSString *safe = CCBridgeSafeSessionId(sessionId);
613
+ if (!safe) return;
614
+ @try {
615
+ if (!transport) return; // 输出失败:保留 claimed,供下次重新投递。
616
+ NSString *claimed = CCBridgeSubdirectory(@[@"claimed", safe]);
617
+ for (NSDictionary *message in messages) {
618
+ NSDictionary *receipt = CCBridgeUpdateReceipt(message[@"id"],
619
+ @{@"status": @"delivered", @"transport": @{@"kind": transport}});
620
+ if (!receipt) continue;
621
+ unlink([claimed stringByAppendingPathComponent:[message[@"id"] stringByAppendingString:@".json"]].fileSystemRepresentation);
622
+ }
623
+ } @finally { CCBridgeReleaseLock(InboxLockFile(safe)); }
525
624
  }
526
625
 
527
626
  NSUInteger CCBridgePendingCount(id sessionId) {
528
627
  NSString *safe = CCBridgeSafeSessionId(sessionId);
529
- return safe ? ListJSON(CCBridgeSubdirectory(@[@"inbox", safe])).count : 0;
628
+ if (!safe) return 0;
629
+ return ListJSON(CCBridgeSubdirectory(@[@"inbox", safe])).count +
630
+ ListJSON(CCBridgeSubdirectory(@[@"claimed", safe])).count;
530
631
  }
531
632
 
532
633
  void CCBridgeAbandonInbox(id sessionId) {
533
634
  NSString *safe = CCBridgeSafeSessionId(sessionId);
534
635
  if (!safe) return;
535
- NSString *inbox = CCBridgeSubdirectory(@[@"inbox", safe]);
536
- for (NSString *name in ListJSON(inbox)) {
537
- NSString *file = [inbox stringByAppendingPathComponent:name];
538
- id message = CCBridgeReadJSON(file);
539
- unlink(file.fileSystemRepresentation);
540
- if ([message isKindOfClass:NSDictionary.class]) {
541
- CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"undeliverable", @"reason": L(@"the target session has ended")});
636
+ NSString *lock = WaitForLock([@"inbox-" stringByAppendingString:safe]);
637
+ @try {
638
+ for (NSString *kind in @[@"inbox", @"claimed"]) {
639
+ NSString *directory = CCBridgeSubdirectory(@[kind, safe]);
640
+ for (NSString *name in ListJSON(directory)) {
641
+ NSString *file = [directory stringByAppendingPathComponent:name];
642
+ id message = CCBridgeReadJSON(file);
643
+ if ([message isKindOfClass:NSDictionary.class]) {
644
+ CCBridgeUpdateReceipt(message[@"id"], @{@"status": @"undeliverable", @"reason": L(@"the target session has ended")});
645
+ }
646
+ unlink(file.fileSystemRepresentation);
647
+ }
542
648
  }
543
- }
649
+ } @finally { CCBridgeReleaseLock(lock); }
544
650
  }
545
651
 
546
652
  // 回执保留 TTL 两倍时长,够排查问题,又不会无限增长。
@@ -592,31 +698,43 @@ NSArray<NSString *> *CCBridgeTakeIdleSubscriptions(NSString *targetSession) {
592
698
 
593
699
  #pragma mark - 锁
594
700
 
595
- static pid_t LockHolder(NSString *file) {
596
- NSString *text = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
597
- return (pid_t)text.intValue;
701
+ // 内核锁文件保持稳定 inode,PID 文件仅用于诊断;不能通过删除“陈旧锁”抢占。
702
+ static NSMutableDictionary<NSString *, NSNumber *> *HeldLocks(void) {
703
+ static NSMutableDictionary *locks;
704
+ static dispatch_once_t once;
705
+ dispatch_once(&once, ^{ locks = [NSMutableDictionary dictionary]; });
706
+ return locks;
598
707
  }
599
708
 
600
709
  NSString *CCBridgeAcquireLock(NSString *name) {
601
710
  NSString *file = [CCBridgeSubdirectory(@[@"locks"]) stringByAppendingPathComponent:[name stringByAppendingString:@".pid"]];
602
- for (int attempt = 0; attempt < 2; attempt++) {
603
- int descriptor = open(file.fileSystemRepresentation, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
604
- if (descriptor >= 0) {
605
- NSData *pid = [[NSString stringWithFormat:@"%d", getpid()] dataUsingEncoding:NSUTF8StringEncoding];
606
- write(descriptor, pid.bytes, pid.length);
711
+ @synchronized (HeldLocks()) {
712
+ if (HeldLocks()[file]) return nil;
713
+ NSString *guard = [file stringByAppendingString:@".lock"];
714
+ int descriptor = open(guard.fileSystemRepresentation, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
715
+ if (descriptor < 0) [NSException raise:@"CCBridgeLock" format:@"%@: %s", guard, strerror(errno)];
716
+ if (flock(descriptor, LOCK_EX | LOCK_NB) != 0) {
717
+ int failure = errno;
607
718
  close(descriptor);
608
- return file;
719
+ if (failure == EWOULDBLOCK || failure == EAGAIN) return nil;
720
+ [NSException raise:@"CCBridgeLock" format:@"%@: %s", guard, strerror(failure)];
609
721
  }
610
- if (errno != EEXIST) [NSException raise:@"CCBridgeLock" format:@"%@: %s", file, strerror(errno)];
611
- pid_t holder = LockHolder(file);
612
- if (holder > 0 && CCBridgeProcessAlive(holder)) return nil;
613
- unlink(file.fileSystemRepresentation);
722
+ HeldLocks()[file] = @(descriptor);
723
+ [[NSString stringWithFormat:@"%d", getpid()] writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
724
+ chmod(file.fileSystemRepresentation, 0600);
725
+ return file;
614
726
  }
615
- return nil;
616
727
  }
617
728
 
618
729
  void CCBridgeReleaseLock(NSString *lockFile) {
619
- if (lockFile && LockHolder(lockFile) == getpid()) unlink(lockFile.fileSystemRepresentation);
730
+ if (!lockFile) return;
731
+ @synchronized (HeldLocks()) {
732
+ NSNumber *descriptor = HeldLocks()[lockFile];
733
+ if (!descriptor) return;
734
+ unlink(lockFile.fileSystemRepresentation);
735
+ [HeldLocks() removeObjectForKey:lockFile];
736
+ close(descriptor.intValue); // 包括进程异常退出,内核都会释放 flock。
737
+ }
620
738
  }
621
739
 
622
740
  #pragma mark - 进程探测
@@ -0,0 +1,21 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // Snapshot (disk + authenticated loopback queries): call off the main thread.
4
+ // state: connected / installed / pendingRestart / outdated / missing / disabled / unsupported.
5
+ // autoInstall is YES when the plugin folder is known well enough to install into it.
6
+ NSArray<NSDictionary *> *CCPetsIDEIntegrationSnapshot(void);
7
+ // Installs or updates the bundled plugin into one snapshot row's plugin folder. Blocking.
8
+ BOOL CCPetsInstallIDEPlugin(NSDictionary *ide, NSError **error);
9
+ // Confirms, installs in the background and reports failures; falls back to the manual
10
+ // installer when autoInstall is NO. completion runs on the main thread.
11
+ void CCPetsPromptInstallIDEPlugin(NSDictionary *ide, void (^completion)(void));
12
+ // Schedules exact focus without blocking AppKit. NO means this is not a JetBrains IDE target.
13
+ BOOL CCPetsRequestIDETerminalFocus(NSDictionary *target);
14
+ // Reveals the bundled ZIP and explains the IDE's own install-from-disk workflow.
15
+ void CCPetsShowIDEPluginInstaller(void);
16
+
17
+ // Shared with other IDE bridges (VS Code). Registrations live in
18
+ // ~/Library/Application Support/CC Pets/ide-instances/; accept filters validated records
19
+ // whose pid belongs to a running app at record[@"appPath"]. Both block: call off main.
20
+ NSArray<NSDictionary *> *CCPetsIDEBridgeInstances(BOOL (^accept)(NSDictionary *record, NSRunningApplication *app));
21
+ NSDictionary *CCPetsIDEBridgeRequest(NSDictionary *instance, NSString *route, NSDictionary *body);