cc-pets 2.4.0 → 2.5.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 (53) hide show
  1. package/CC_BRIDGE.md +46 -9
  2. package/CC_BRIDGE.zh-CN.md +29 -6
  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 +69 -16
  10. package/README.zh-CN.md +54 -19
  11. package/Resources/zh-Hans.lproj/Localizable.strings +35 -11
  12. package/Sources/CCPets/App/CCPetsAppDelegate+AgentEvents.m +47 -4
  13. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +109 -14
  14. package/Sources/CCPets/App/CCPetsAppDelegate+Bridge.m +8 -6
  15. package/Sources/CCPets/App/CCPetsAppDelegate+MenuBar.m +86 -0
  16. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +13 -0
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Quota.m +6 -1
  18. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +5 -3
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Update.m +4 -1
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +4 -0
  21. package/Sources/CCPets/App/CCPetsAppDelegate.h +10 -0
  22. package/Sources/CCPets/App/CCPetsAppDelegate.m +4 -2
  23. package/Sources/CCPets/Bridge/CCPetsBridge.m +34 -12
  24. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +100 -33
  25. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +12 -3
  26. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +317 -89
  27. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +0 -2
  28. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +210 -95
  29. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +28 -3
  30. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +222 -35
  31. package/Sources/CCPets/Integrations/CCPetsEvents.h +5 -0
  32. package/Sources/CCPets/Integrations/CCPetsEvents.m +68 -12
  33. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +1 -1
  34. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +6 -0
  35. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +54 -5
  36. package/Sources/CCPets/Pet/CCPetsPhrasesEditor.m +7 -0
  37. package/Sources/CCPets/Pet/PetView+Menu.m +9 -1
  38. package/Sources/CCPets/Pet/PetView.h +7 -0
  39. package/Sources/CCPets/Pet/PetView.m +12 -1
  40. package/Sources/CCPets/Support/CCPetsPreferences.h +10 -0
  41. package/Sources/CCPets/Support/CCPetsPreferences.m +18 -0
  42. package/Sources/CCPets/UI/CCPetsMenuBarIcon.h +16 -0
  43. package/Sources/CCPets/UI/CCPetsMenuBarIcon.m +70 -0
  44. package/Sources/CCPets/UI/CCPetsMenuBarPanel.h +18 -0
  45. package/Sources/CCPets/UI/CCPetsMenuBarPanel.m +528 -0
  46. package/Sources/CCPets/UI/CCPetsMenuBarSummary.h +51 -0
  47. package/Sources/CCPets/UI/CCPetsMenuBarSummary.m +95 -0
  48. package/Sources/CCPets/UI/CCPetsSettingsPage.h +4 -1
  49. package/Sources/CCPets/UI/CCPetsSettingsPage.m +16 -0
  50. package/Sources/CCPets/UI/CCPetsStatusItem.h +28 -0
  51. package/Sources/CCPets/UI/CCPetsStatusItem.m +147 -0
  52. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +5 -3
  53. package/package.json +1 -1
@@ -0,0 +1,86 @@
1
+ // 显示位置:仅桌宠 / 桌宠 + 菜单栏 / 仅菜单栏。
2
+ //
3
+ // 「仅菜单栏」只关掉桌面上看得见的东西:桌宠窗口、状态卡、说话气泡、悬停面板和更新气泡。
4
+ // 事件读取、会话记录、额度采集、系统通知照常运行,菜单栏图标和主窗口都靠它们。
5
+ // 浮层各自的显示入口在 petVisible 为 NO 时直接不弹,不在这里逐个追着关。
6
+ #import "CCPetsAppDelegate+Private.h"
7
+
8
+ @implementation AppDelegate (MenuBar)
9
+
10
+ - (BOOL)petVisible {
11
+ return ![CCPetsDisplayMode() isEqualToString:CCPetsDisplayModeMenuBar];
12
+ }
13
+
14
+ - (BOOL)menuBarVisible {
15
+ return ![CCPetsDisplayMode() isEqualToString:CCPetsDisplayModePet];
16
+ }
17
+
18
+ - (void)updateDisplayMode:(NSString *)mode {
19
+ if (CCPetsPrefSetObject(CCPetsDisplayModeKey, mode)) [self applyDisplayMode];
20
+ }
21
+
22
+ // 菜单栏图标自己监听设置变更,改完数字当场刷新。
23
+ - (void)updateMenuBarShowsPercent:(BOOL)enabled {
24
+ CCPetsPrefSetBool(CCPetsMenuBarShowsPercentKey, enabled);
25
+ }
26
+
27
+ - (void)applyDisplayMode {
28
+ if ([self menuBarVisible] && !self.statusItemController) {
29
+ [self installStatusItem];
30
+ } else if (![self menuBarVisible] && self.statusItemController) {
31
+ [self.statusItemController invalidate];
32
+ self.statusItemController = nil;
33
+ }
34
+ if ([self petVisible]) [self showPetWindows];
35
+ else [self hidePetWindows];
36
+ [self.statusItemController refresh];
37
+ }
38
+
39
+ - (void)installStatusItem {
40
+ CCPetsStatusItemController *controller = [[CCPetsStatusItemController alloc] initWithSource:(id)self];
41
+ __weak typeof(self) weakSelf = self;
42
+ controller.petVisibleProvider = ^BOOL { return [weakSelf petVisible]; };
43
+ controller.stateColorProvider = ^NSColor *(NSString *state) { return [weakSelf statusColorForState:state]; };
44
+ // 菜单栏图标只在「桌宠 + 菜单栏」和「仅菜单栏」下存在,勾选项就在这两者之间切换。
45
+ controller.togglePetVisible = ^{
46
+ [weakSelf updateDisplayMode:[weakSelf petVisible] ? CCPetsDisplayModeMenuBar : CCPetsDisplayModeBoth];
47
+ };
48
+ controller.pendingUpdateVersionProvider = ^NSString * {
49
+ return weakSelf.updating ? nil : weakSelf.pendingUpdateVersion;
50
+ };
51
+ controller.showPendingUpdate = ^{ [weakSelf showPendingUpdate:nil]; };
52
+ // 右键和桌宠右键同一份菜单:启用 CC Bridge、免审批这些只在那里,仅菜单栏时不能没有入口。
53
+ controller.contextMenuProvider = ^NSMenu * { return [weakSelf.petView buildContextMenu]; };
54
+ controller.contextMenuFinished = ^{ [weakSelf.petView finishContextMenu]; };
55
+ self.statusItemController = controller;
56
+ }
57
+
58
+ - (void)showPetWindows {
59
+ [self.panel orderFrontRegardless];
60
+ [self.petView setAnimationSuspended:NO];
61
+ // 状态卡按原来的偏好还原;没有活跃会话时 updateStatusBubbleExpanded: 自己会保持隐藏。
62
+ [self updateStatusBubbleExpanded:self.statusBubbleExpanded];
63
+ [self refreshUpdateBadge];
64
+ }
65
+
66
+ - (void)hidePetWindows {
67
+ [NSObject cancelPreviousPerformRequestsWithTarget:self
68
+ selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
69
+ [NSObject cancelPreviousPerformRequestsWithTarget:self
70
+ selector:@selector(hideSpeechBubble) object:nil];
71
+ [NSObject cancelPreviousPerformRequestsWithTarget:self
72
+ selector:@selector(restoreStatusDetail) object:nil];
73
+ self.pocketHovering = NO;
74
+ self.dashboardHovering = NO;
75
+ self.updateBubbleVisible = NO;
76
+ self.updateBubbleSuppressedStatus = NO;
77
+ [self.quotaPanel orderOut:nil];
78
+ [self.speechPanel orderOut:nil];
79
+ [self.statusPanel orderOut:nil];
80
+ [CCPetsGlassMenu dismiss];
81
+ [self.panel orderOut:nil];
82
+ // 看不见的宠物不必逐帧动画,和屏幕睡眠走同一个开关。
83
+ [self.petView setAnimationSuspended:YES];
84
+ }
85
+
86
+ @end
@@ -20,6 +20,7 @@
20
20
  #import "CCPetsBridge.h"
21
21
  #import "CCPetsProfiles.h"
22
22
  #import "MenuToggleSwitch.h"
23
+ #import "CCPetsStatusItem.h"
23
24
  #import <UserNotifications/UserNotifications.h>
24
25
  #import <signal.h>
25
26
  #import <sys/stat.h>
@@ -218,6 +219,9 @@ static inline void PetResizeBubblePanel(NSPanel *panel, NSSize logicalSize) {
218
219
  - (void)displayAgentRecord:(NSDictionary *)record notify:(BOOL)shouldNotify;
219
220
  - (NSString *)agentSessionKeyForRecord:(NSDictionary *)record;
220
221
  - (NSString *)onlineAgentSessionKeyForRecord:(NSDictionary *)record;
222
+ - (NSString *)statusIdentityForRecord:(NSDictionary *)record;
223
+ - (NSNumber *)desktopSessionPersistenceForRecord:(NSDictionary *)record;
224
+ - (void)finishAgentSessionPresentation:(NSDictionary *)record;
221
225
  - (BOOL)isAgentSessionRecordLive:(NSDictionary *)record;
222
226
  - (void)pruneOfflineAgentSessionRecords;
223
227
  - (void)trackAgentSessionRecord:(NSDictionary *)record;
@@ -264,6 +268,15 @@ static inline void PetResizeBubblePanel(NSPanel *panel, NSSize logicalSize) {
264
268
  pending:(NSDictionary<NSString *, NSNumber *> *)pending;
265
269
  @end
266
270
 
271
+ // 显示位置:桌宠窗口与菜单栏图标的显隐。「仅菜单栏」时桌宠和它的浮层(状态卡、气泡、
272
+ // 悬停面板)都不出现,状态机照常运行,供菜单栏和系统通知使用。
273
+ @interface AppDelegate (MenuBar)
274
+ - (BOOL)petVisible;
275
+ - (void)applyDisplayMode;
276
+ - (void)updateDisplayMode:(NSString *)mode;
277
+ - (void)updateMenuBarShowsPercent:(BOOL)enabled;
278
+ @end
279
+
267
280
  // 用户显式添加、修复或移除 Claude/Codex Home。
268
281
  @interface AppDelegate (Profiles)
269
282
  - (void)addClaudeProfile:(id)sender;
@@ -19,6 +19,7 @@
19
19
  return NSDate.date.timeIntervalSince1970 - self.lastUsageRefreshAt >= UsageRefreshCoalesceWindow;
20
20
  }
21
21
  - (void)showQuotaDashboard {
22
+ if (![self petVisible]) return;
22
23
  [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
23
24
  if ([self shouldRefreshUsageForDashboard]) [self refreshUsage:nil];
24
25
  [self positionQuotaDashboard];
@@ -134,6 +135,7 @@
134
135
  NSMutableSet<NSString *> *unscopedProviders = [self.liveUnscopedClientProviders mutableCopy]
135
136
  ?: [NSMutableSet set];
136
137
  NSMutableSet<NSString *> *approvalProfiles = [NSMutableSet set];
138
+ NSInteger desktopSessions = 0;
137
139
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
138
140
  for (NSString *provider in self.providerActivityAt) {
139
141
  NSTimeInterval last = [self.providerActivityAt[provider] doubleValue];
@@ -143,6 +145,9 @@
143
145
  NSString *profileID = [record[@"profileId"] isKindOfClass:NSString.class]
144
146
  ? record[@"profileId"] : nil;
145
147
  if (![self isAgentSessionRecordLive:record]) continue;
148
+ NSString *provider = [record[@"provider"] isKindOfClass:NSString.class] ? record[@"provider"] : nil;
149
+ if (provider.length > 0) [online addObject:provider];
150
+ if ([provider isEqual:@"Codex"] && IsCodexDesktopFocusTarget(record[@"terminal"])) desktopSessions += 1;
146
151
  if (profileID.length > 0) {
147
152
  [onlineProfiles addObject:profileID];
148
153
  if ([record[@"state"] isEqualToString:@"approval"]) [approvalProfiles addObject:profileID];
@@ -152,7 +157,7 @@
152
157
  if (provider.length > 0) [unscopedProviders addObject:provider];
153
158
  }
154
159
  }
155
- NSInteger count = MAX(self.liveClientCount, (NSInteger)online.count);
160
+ NSInteger count = MAX(self.liveClientCount + desktopSessions, (NSInteger)online.count);
156
161
  if (self.quotaView.activeAgentCount == count &&
157
162
  [self.quotaView.liveProviders isEqualToSet:online] &&
158
163
  [self.quotaView.liveProfileIDs isEqualToSet:onlineProfiles] &&
@@ -70,7 +70,8 @@ static NSString *SpeechQuotaResetTime(NSDictionary *usage) {
70
70
  return ![self.lastStatusState isEqualToString:@"idle"];
71
71
  }
72
72
  - (BOOL)canSpeakNow {
73
- if (![self speechEnabled]) return NO;
73
+ // 「仅菜单栏」时没有地方放这句话,也不占预算和冷却。
74
+ if (![self speechEnabled] || ![self petVisible]) return NO;
74
75
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
75
76
  if (now < self.speechCooldownUntil) return NO;
76
77
  if (!self.speechTimestamps) self.speechTimestamps = [NSMutableArray array];
@@ -281,7 +282,7 @@ static NSString *SpeechQuotaResetTime(NSDictionary *usage) {
281
282
  // 话往哪儿显示只在这一处决定:有状态卡就并进它的副行,没有才起独立气泡。
282
283
  // 调试触发也必须走这里——否则看到的是现实中不会出现的画面(两个泡叠着)。
283
284
  - (void)presentSpeechText:(NSString *)text {
284
- if (text.length == 0) return;
285
+ if (text.length == 0 || ![self petVisible]) return;
285
286
  if (self.statusPanel.isVisible) {
286
287
  self.statusDetailLabel.stringValue = text;
287
288
  [self resizeStatusCardToFitText];
@@ -350,7 +351,8 @@ static NSString *SpeechQuotaResetTime(NSDictionary *usage) {
350
351
  // 被更新气泡临时收起的状态卡还回去(会话已结束或用户关了状态卡就不还)。
351
352
  if (self.updateBubbleSuppressedStatus) {
352
353
  self.updateBubbleSuppressedStatus = NO;
353
- if (self.hasAgentStatus && self.statusBubbleExpanded && !self.statusPanel.isVisible) {
354
+ if (self.hasAgentStatus && self.statusBubbleExpanded && [self petVisible] &&
355
+ !self.statusPanel.isVisible) {
354
356
  [self positionAgentStatus];
355
357
  [self.statusPanel orderFrontRegardless];
356
358
  }
@@ -445,7 +445,9 @@ static void TrimUpdateLog(NSString *path) {
445
445
  // agent 在忙就先记下来,等它闲下来(considerIdleSpeech 每 3 秒一跳)再冒;
446
446
  // 状态卡只是在待命时,临时把它收起让位,气泡消失后再放回来。
447
447
  - (void)showUpdateBubble {
448
- if (self.pendingUpdateVersion.length == 0 || self.updating || self.updateReminderSnoozed) {
448
+ // 「仅菜单栏」时更新入口是菜单栏菜单里的「更新到 x.y.z…」,不排队等气泡。
449
+ if (self.pendingUpdateVersion.length == 0 || self.updating || self.updateReminderSnoozed ||
450
+ ![self petVisible]) {
449
451
  self.updateBubbleDeferred = NO;
450
452
  return;
451
453
  }
@@ -468,6 +470,7 @@ static void TrimUpdateLog(NSString *path) {
468
470
  stringByReplacingOccurrencesOfString:@"{version}" withString:self.pendingUpdateVersion];
469
471
  }
470
472
  - (void)showUpdateBubbleWithText:(NSString *)text dwell:(NSTimeInterval)dwell {
473
+ if (![self petVisible]) return;
471
474
  if (self.statusPanel.isVisible) {
472
475
  [self.statusPanel orderOut:nil];
473
476
  self.updateBubbleSuppressedStatus = YES;
@@ -2,6 +2,7 @@
2
2
  // 不新增任何采集。
3
3
  #import "CCPetsAppDelegate+Private.h"
4
4
  #import "CCPetsBridge.h"
5
+ #import "CCPetsBridgeStore.h"
5
6
  #import "CCPetsDiagnosticsPage.h"
6
7
  #import "CCPetsUsageMode.h"
7
8
 
@@ -34,6 +35,7 @@ NSNotificationName const CCPetsWorkbenchQuotasDidChangeNotification = @"CCPetsWo
34
35
  session[@"updatedAt"] = record[@"timestamp"] ?: @0;
35
36
  NSDictionary *bridge = [self bridgeSessionEntryForRecord:record];
36
37
  if ([bridge[@"name"] isKindOfClass:NSString.class]) session[@"name"] = bridge[@"name"];
38
+ session[@"displayName"] = CCBridgeSessionDisplayName(bridge);
37
39
  NSString *bridgeID = [self bridgeSessionIdForRecord:record];
38
40
  session[@"pendingMessages"] = bridgeID ? (pending[bridgeID] ?: @0) : @0;
39
41
  [sessions addObject:session];
@@ -54,7 +56,9 @@ NSNotificationName const CCPetsWorkbenchQuotasDidChangeNotification = @"CCPetsWo
54
56
  NSMutableArray<NSDictionary *> *pending = [NSMutableArray array];
55
57
  [self.bridgePendingCounts enumerateKeysAndObjectsUsingBlock:^(NSString *session, NSNumber *count, BOOL *stop) {
56
58
  NSString *name = self.bridgeSessions[session][@"name"];
59
+ NSString *displayName = CCBridgeSessionDisplayName(self.bridgeSessions[session]);
57
60
  [pending addObject:@{@"session": session, @"name": [name isKindOfClass:NSString.class] ? name : session,
61
+ @"displayName": displayName.length > 0 ? displayName : session,
58
62
  @"count": count}];
59
63
  }];
60
64
  [pending sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
@@ -6,6 +6,8 @@
6
6
  #import "CCPetsSystemMonitor.h"
7
7
  #import "CCPetsGlassView.h"
8
8
 
9
+ @class CCPetsStatusItemController;
10
+
9
11
  @interface AppDelegate : NSObject <NSApplicationDelegate>
10
12
  @property NSPanel *panel;
11
13
  @property NSPanel *quotaPanel;
@@ -65,10 +67,14 @@
65
67
  @property NSInteger liveClientCount;
66
68
  @property NSString *lastStatusState;
67
69
  @property NSString *lastStatusProvider;
70
+ // 当前卡片所属会话的短标签(目录名.动物)和悬停提示;语言切换、回落待机时重排标题要用。
71
+ @property NSString *lastStatusSessionLabel;
72
+ @property NSString *lastStatusSessionTooltip;
68
73
  // lastStatusProvider 是卡片标题(有账号名时显示账号名),不能拿去对 pid 文件里的
69
74
  // "Claude"/"Codex";在线判定用原始 provider,判断“是不是同一账号”用 provider|profileId。
70
75
  @property NSString *lastStatusAgentProvider;
71
76
  @property NSString *lastStatusIdentity;
77
+ @property NSDictionary *lastStatusRecord;
72
78
  @property NSDictionary *lastTerminalFocusTarget;
73
79
  @property NSTimeInterval lastStatusTimestamp;
74
80
  @property NSSet<NSString *> *liveClientProviders;
@@ -77,6 +83,8 @@
77
83
  @property NSSet<NSString *> *liveUnscopedClientProviders;
78
84
  // 包装脚本仍存活的精确 Agent 会话,键为 provider + TTY。
79
85
  @property NSSet<NSString *> *liveAgentSessionKeys;
86
+ // 曾由包装器管理的会话身份(包含 session ID),不把复用同一 tty 的新会话认成旧会话。
87
+ @property NSMutableSet<NSString *> *managedAgentSessionKeys;
80
88
  // 每个 provider 最近一次事件的时间。不经包装脚本启动的客户端没有 pid 文件,
81
89
  // 只能靠"最近还在发事件"证明自己活着。
82
90
  @property NSMutableDictionary<NSString *, NSNumber *> *providerActivityAt;
@@ -126,4 +134,6 @@
126
134
  @property NSTimer *quotaClockTimer;
127
135
  @property NSTimer *systemMetricsTimer;
128
136
  @property CCPetsSystemMonitor *systemMonitor;
137
+ // 菜单栏图标。显示位置为「仅桌宠」时为 nil。
138
+ @property CCPetsStatusItemController *statusItemController;
129
139
  @end
@@ -482,7 +482,8 @@
482
482
  [self applyPetSizePreference];
483
483
  size = self.panel.frame.size;
484
484
  [self.panel setFrameOrigin:NSMakePoint(NSMaxX(visible) - size.width - 24, NSMinY(visible) + 18)];
485
- [self.panel orderFrontRegardless];
485
+ // 按显示位置决定桌宠窗口和菜单栏图标谁出现。
486
+ [self applyDisplayMode];
486
487
  self.usageMonitor = [CCPetsUsageMonitor new];
487
488
  self.systemMonitor = [CCPetsSystemMonitor new];
488
489
  self.agentEventPartialLine = [NSMutableData data];
@@ -549,7 +550,8 @@
549
550
  [self.petView setAnimationSuspended:YES];
550
551
  }
551
552
  - (void)screensDidWake:(NSNotification *)notification {
552
- [self.petView setAnimationSuspended:NO];
553
+ // 「仅菜单栏」时宠物藏着,醒来也别恢复逐帧动画。
554
+ if ([self petVisible]) [self.petView setAnimationSuspended:NO];
553
555
  }
554
556
  - (void)petWindowDidMove:(NSNotification *)notification {
555
557
  if (self.quotaPanel.isVisible) [self positionQuotaDashboard];
@@ -1,13 +1,12 @@
1
1
  #import "CCPetsBridge.h"
2
+ #import "CCPetsBridgeStore.h"
2
3
  #import "CCPetsPaths.h"
3
- #import <errno.h>
4
- #import <signal.h>
5
4
  #import <unistd.h>
6
5
 
7
6
  NSString *const BridgeBadgeEnabledKey = @"CCPetsBridgeBadgeEnabled";
8
7
  NSString *const BridgeNotificationKey = @"CCPetsBridgeNotification";
9
8
 
10
- // 目录里文件数的上限。回执保留 48 小时,正常使用远到不了这个量;
9
+ // 一次最多读这么多文件。回执保留 48 小时,正常使用远到不了这个量;
11
10
  // 真到了说明有东西在刷消息,宁可少显示几条也不让桌宠主线程卡在读盘上。
12
11
  static const NSUInteger BridgeFileScanLimit = 500;
13
12
 
@@ -87,6 +86,29 @@ static NSArray<NSString *> *JSONFilesInDirectory(NSString *directory) {
87
86
  return files;
88
87
  }
89
88
 
89
+ // 回执每次状态变化都是"临时文件 + rename",修改时间就是最后一次更新的时间,比 ID(创建时间)更准:
90
+ // 排了很久的消息也可能刚刚送达。比 since 早的文件里不可能有新送达,不用打开;
91
+ // 其余的按新到旧取,文件数超过上限时丢掉的才是最旧的。
92
+ static NSArray<NSString *> *ReceiptFilesUpdatedSince(NSString *directory, NSTimeInterval since) {
93
+ NSArray<NSURL *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtURL:[NSURL fileURLWithPath:directory]
94
+ includingPropertiesForKeys:@[NSURLContentModificationDateKey] options:0 error:nil];
95
+ NSMutableArray<NSDictionary *> *candidates = [NSMutableArray array];
96
+ for (NSURL *entry in entries) {
97
+ if (![entry.lastPathComponent hasSuffix:@".json"]) continue;
98
+ NSDate *modified = nil;
99
+ [entry getResourceValue:&modified forKey:NSURLContentModificationDateKey error:nil];
100
+ if (modified.timeIntervalSince1970 < since) continue;
101
+ [candidates addObject:@{@"path": entry.path, @"modified": modified}];
102
+ }
103
+ [candidates sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
104
+ return [right[@"modified"] compare:left[@"modified"]];
105
+ }];
106
+ if (candidates.count > BridgeFileScanLimit) {
107
+ [candidates removeObjectsInRange:NSMakeRange(BridgeFileScanLimit, candidates.count - BridgeFileScanLimit)];
108
+ }
109
+ return [candidates valueForKey:@"path"];
110
+ }
111
+
90
112
  static NSDictionary *ReadJSONObject(NSString *path) {
91
113
  NSData *data = [NSData dataWithContentsOfFile:path];
92
114
  if (data.length == 0) return nil;
@@ -140,13 +162,6 @@ NSUInteger CCBridgeActiveReservationCount(NSSet<NSString *> *sessionIds) {
140
162
  return count;
141
163
  }
142
164
 
143
- static BOOL ProcessAlive(id pidValue) {
144
- if (![pidValue isKindOfClass:NSNumber.class]) return YES; // 没记 pid 的会话交给 bridge 端判定
145
- pid_t pid = [pidValue intValue];
146
- if (pid <= 1) return YES;
147
- return kill(pid, 0) == 0 || errno == EPERM;
148
- }
149
-
150
165
  NSDictionary<NSString *, NSDictionary *> *CCBridgeSessions(void) {
151
166
  NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"sessions"];
152
167
  NSMutableDictionary<NSString *, NSDictionary *> *sessions = [NSMutableDictionary dictionary];
@@ -154,12 +169,17 @@ NSDictionary<NSString *, NSDictionary *> *CCBridgeSessions(void) {
154
169
  NSDictionary *record = ReadJSONObject(path);
155
170
  NSString *session = BridgeSafeString(record[@"session"], 128);
156
171
  NSString *name = BridgeSafeString(record[@"name"], 40);
157
- if (session.length == 0 || name.length == 0 || !ProcessAlive(record[@"pid"])) continue;
172
+ // 与 CLI 用同一条规则,否则菜单里的在线会话和 list_agents 对不上。
173
+ if (session.length == 0 || name.length == 0 || !CCBridgeSessionLive(record)) continue;
158
174
  NSMutableDictionary *entry = [@{
159
175
  @"name": name,
160
176
  @"ref": BridgeSafeString(record[@"ref"], 6),
161
177
  @"provider": BridgeSafeString(record[@"provider"], 16)
162
178
  } mutableCopy];
179
+ NSString *nameSource = [record[@"nameSource"] isKindOfClass:NSString.class] ? record[@"nameSource"] : nil;
180
+ if ([nameSource isEqualToString:@"generated"] || [nameSource isEqualToString:@"custom"]) {
181
+ entry[@"nameSource"] = nameSource;
182
+ }
163
183
  NSString *profileID = BridgeSafeString(record[@"profileId"], 128);
164
184
  if (profileID.length > 0) entry[@"profileId"] = profileID;
165
185
  NSString *tty = BridgeSafeString(record[@"tty"], 32);
@@ -172,7 +192,7 @@ NSDictionary<NSString *, NSDictionary *> *CCBridgeSessions(void) {
172
192
  NSArray<NSDictionary *> *CCBridgeRecentDeliveries(NSTimeInterval since, NSUInteger limit) {
173
193
  NSString *directory = [CCBridgeStateDirectory() stringByAppendingPathComponent:@"sent"];
174
194
  NSMutableArray<NSDictionary *> *deliveries = [NSMutableArray array];
175
- for (NSString *path in JSONFilesInDirectory(directory)) {
195
+ for (NSString *path in ReceiptFilesUpdatedSince(directory, since)) {
176
196
  NSDictionary *receipt = ReadJSONObject(path);
177
197
  if (![receipt[@"status"] isEqual:@"delivered"]) continue;
178
198
  NSDictionary *from = [receipt[@"from"] isKindOfClass:NSDictionary.class] ? receipt[@"from"] : nil;
@@ -191,6 +211,8 @@ NSArray<NSDictionary *> *CCBridgeRecentDeliveries(NSTimeInterval since, NSUInteg
191
211
  @"id": BridgeSafeString(receipt[@"id"], 64),
192
212
  @"from": fromName,
193
213
  @"to": toName,
214
+ @"fromIdentity": @{@"name": fromName, @"nameSource": BridgeSafeString(from[@"nameSource"], 16)},
215
+ @"toIdentity": @{@"name": toName, @"nameSource": BridgeSafeString(to[@"nameSource"], 16)},
194
216
  @"toSession": toSession,
195
217
  @"fromSession": BridgeSafeString(from[@"session"], 128),
196
218
  @"at": @(at)