cc-pets 2.0.1 → 2.1.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.
- package/CC_BRIDGE.md +239 -0
- package/CC_BRIDGE.zh-CN.md +210 -0
- package/CHANGELOG.md +39 -0
- package/CHANGELOG.zh-CN.md +39 -0
- package/PROVIDER_PROTOCOL.md +6 -0
- package/PROVIDER_PROTOCOL.zh-CN.md +5 -0
- package/README.md +26 -0
- package/README.zh-CN.md +25 -2
- package/Resources/Info.plist +2 -0
- package/Sources/CCPets/CCPetsAppDelegate.h +25 -0
- package/Sources/CCPets/CCPetsAppDelegate.m +751 -29
- package/Sources/CCPets/CCPetsBridge.h +43 -0
- package/Sources/CCPets/CCPetsBridge.m +198 -0
- package/Sources/CCPets/CCPetsEvents.m +7 -2
- package/Sources/CCPets/CCPetsPaths.h +4 -0
- package/Sources/CCPets/CCPetsPaths.m +6 -0
- package/Sources/CCPets/CCPetsQuotaHistory.m +9 -2
- package/Sources/CCPets/CCPetsTerminalFocus.h +11 -0
- package/Sources/CCPets/CCPetsTerminalFocus.m +150 -0
- package/Sources/CCPets/PetView.m +86 -1
- package/Sources/CCPets/QuotaDashboardView.m +17 -4
- package/Sources/CCPets/main.m +5 -0
- package/bin/cc-pets +5 -0
- package/bin/claude-with-pet +8 -2
- package/bin/codex-with-pet +8 -3
- package/package.json +3 -1
- package/scripts/bridge/cli.mjs +229 -0
- package/scripts/bridge/core.mjs +227 -0
- package/scripts/bridge/hook.mjs +149 -0
- package/scripts/bridge/install.mjs +288 -0
- package/scripts/bridge/mcp-server.mjs +300 -0
- package/scripts/bridge/options.mjs +86 -0
- package/scripts/bridge/process.mjs +129 -0
- package/scripts/bridge/reservations.mjs +247 -0
- package/scripts/bridge/store.mjs +432 -0
- package/scripts/bridge/watch.mjs +69 -0
- package/scripts/install-shell-integration.sh +3 -0
- package/scripts/uninstall-integrations.mjs +10 -0
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
#import "CCPetsPhrases.h"
|
|
8
8
|
#import "CCPetsPhrasesEditor.h"
|
|
9
9
|
#import "CCPetsUsage.h"
|
|
10
|
+
#import "CCPetsTerminalFocus.h"
|
|
11
|
+
#import "CCPetsBridge.h"
|
|
10
12
|
#import "MenuToggleSwitch.h"
|
|
11
13
|
#import <UserNotifications/UserNotifications.h>
|
|
12
14
|
#import <signal.h>
|
|
@@ -14,13 +16,79 @@
|
|
|
14
16
|
#import <fcntl.h>
|
|
15
17
|
#import <unistd.h>
|
|
16
18
|
#import <errno.h>
|
|
19
|
+
#import <sys/sysctl.h>
|
|
20
|
+
#import <stdlib.h>
|
|
17
21
|
|
|
18
22
|
static const NSTimeInterval PendingApprovalTTL = 24 * 60 * 60;
|
|
19
23
|
static const NSUInteger PendingApprovalLimit = 100;
|
|
24
|
+
static const NSUInteger AgentSessionRecordLimit = 20;
|
|
25
|
+
static const NSUInteger AgentSessionMenuLimit = 8;
|
|
26
|
+
static const CGFloat PetApprovalBadgeSize = 17.0;
|
|
27
|
+
// CC Bridge:轮询间隔、"最近消息"的时间窗、菜单里最多列几条。
|
|
28
|
+
static const NSTimeInterval BridgeRefreshInterval = 3.0;
|
|
29
|
+
static const NSTimeInterval BridgeRecentWindow = 30 * 60;
|
|
30
|
+
static const NSUInteger BridgeMenuDeliveryLimit = 5;
|
|
20
31
|
static const unsigned long long UpdateLogSizeLimit = 1024 * 1024;
|
|
21
32
|
static NSString *const PetInteractionPhrasesV1MigratedKey =
|
|
22
33
|
@"CCPetsInteractionPhrasesV1Migrated";
|
|
23
34
|
|
|
35
|
+
@interface CCPetsStatusClickButton : NSButton
|
|
36
|
+
@end
|
|
37
|
+
|
|
38
|
+
@implementation CCPetsStatusClickButton
|
|
39
|
+
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
|
|
40
|
+
- (void)resetCursorRects {
|
|
41
|
+
[super resetCursorRects];
|
|
42
|
+
[self addCursorRect:self.bounds cursor:NSCursor.pointingHandCursor];
|
|
43
|
+
}
|
|
44
|
+
@end
|
|
45
|
+
|
|
46
|
+
// 待审批角标。等审批的会话按定义是停住不动的,它的时间戳只会越来越旧——状态卡
|
|
47
|
+
// 正文永远显示最新事件,会话列表又按时间倒序,两边都会把最该处理的那条推到看
|
|
48
|
+
// 不见的地方。角标把这个数字单独拎出来常驻。
|
|
49
|
+
@interface CCPetsApprovalBadgeView : NSView
|
|
50
|
+
@property(nonatomic) NSUInteger count;
|
|
51
|
+
// 默认审批红;CC Bridge 消息角标复用同一个视图,换成蓝色 / 橙色。
|
|
52
|
+
@property(nonatomic) NSColor *fillColor;
|
|
53
|
+
@end
|
|
54
|
+
|
|
55
|
+
@implementation CCPetsApprovalBadgeView
|
|
56
|
+
- (void)setCount:(NSUInteger)count {
|
|
57
|
+
if (_count == count) return;
|
|
58
|
+
_count = count;
|
|
59
|
+
self.hidden = count == 0;
|
|
60
|
+
self.needsDisplay = YES;
|
|
61
|
+
}
|
|
62
|
+
- (void)setFillColor:(NSColor *)fillColor {
|
|
63
|
+
if ([_fillColor isEqual:fillColor]) return;
|
|
64
|
+
_fillColor = fillColor;
|
|
65
|
+
self.needsDisplay = YES;
|
|
66
|
+
}
|
|
67
|
+
// 角标压在圆形状态图标的右上角,但不能把那颗按钮的点击吃掉。
|
|
68
|
+
- (NSView *)hitTest:(NSPoint)point { return nil; }
|
|
69
|
+
- (void)drawRect:(NSRect)dirtyRect {
|
|
70
|
+
if (self.count == 0) return;
|
|
71
|
+
// 描边是给玻璃卡片准备的:审批色和卡片背景都偏亮,没有这圈白边角标会糊在一起。
|
|
72
|
+
NSRect circle = NSInsetRect(self.bounds, 1.0, 1.0);
|
|
73
|
+
NSBezierPath *fill = [NSBezierPath bezierPathWithOvalInRect:circle];
|
|
74
|
+
[(self.fillColor ?: [NSColor colorWithRed:0.86 green:0.24 blue:0.24 alpha:1]) setFill];
|
|
75
|
+
[fill fill];
|
|
76
|
+
fill.lineWidth = 1.5;
|
|
77
|
+
[[NSColor colorWithWhite:1 alpha:0.92] setStroke];
|
|
78
|
+
[fill stroke];
|
|
79
|
+
BOOL overflow = self.count > 9;
|
|
80
|
+
NSString *text = overflow ? @"9+" : @(self.count).stringValue;
|
|
81
|
+
NSDictionary *attributes = @{
|
|
82
|
+
NSFontAttributeName: [NSFont systemFontOfSize:overflow ? 8.5 : 10
|
|
83
|
+
weight:NSFontWeightBold],
|
|
84
|
+
NSForegroundColorAttributeName: NSColor.whiteColor
|
|
85
|
+
};
|
|
86
|
+
NSSize size = [text sizeWithAttributes:attributes];
|
|
87
|
+
[text drawAtPoint:NSMakePoint(NSMidX(self.bounds) - size.width / 2.0,
|
|
88
|
+
NSMidY(self.bounds) - size.height / 2.0) withAttributes:attributes];
|
|
89
|
+
}
|
|
90
|
+
@end
|
|
91
|
+
|
|
24
92
|
static void TrimUpdateLog(NSString *path) {
|
|
25
93
|
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
|
|
26
94
|
if (!handle) return;
|
|
@@ -347,6 +415,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
347
415
|
if (tag == 1) return NotificationCompletionKey;
|
|
348
416
|
if (tag == 2) return NotificationFailureKey;
|
|
349
417
|
if (tag == 3) return NotificationApprovalKey;
|
|
418
|
+
if (tag == 4) return NotificationStallKey;
|
|
350
419
|
return nil;
|
|
351
420
|
}
|
|
352
421
|
- (void)toggleSpeech:(NSButton *)sender {
|
|
@@ -573,10 +642,39 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
573
642
|
[self hideAgentStatus];
|
|
574
643
|
}
|
|
575
644
|
- (void)hideAgentStatus {
|
|
645
|
+
// 卡在审批的会话不该跟着沉默一起消失。60 秒没有新事件时,气泡不清场,而是回落
|
|
646
|
+
// 到最近那条审批:这样"有人在等你确认"始终有个落点,点卡片就能跳回那个终端,
|
|
647
|
+
// 角标也不会随面板一起被收走。
|
|
648
|
+
//
|
|
649
|
+
// 这不是把旧的"审批全局优先"逻辑搬回来——那一版在事件流里拦截,一个未处理的
|
|
650
|
+
// 审批会把其他 Agent 的所有 Hook 全挡住。这里只在完全没有新事件时才接管,任何
|
|
651
|
+
// 一条新事件都照常刷新正文。
|
|
652
|
+
NSArray<NSDictionary *> *pending = [self pendingApprovalSessionRecords];
|
|
653
|
+
if (self.hasAgentStatus && pending.count > 0) {
|
|
654
|
+
[self performSelector:@selector(hideAgentStatus) withObject:nil
|
|
655
|
+
afterDelay:AgentStatusInactivityInterval];
|
|
656
|
+
[self presentPendingApprovalRecord:pending.firstObject];
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
576
659
|
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
577
660
|
selector:@selector(enterIdleStatus) object:nil];
|
|
578
661
|
[self.statusPanel orderOut:nil];
|
|
579
662
|
self.hasAgentStatus = NO;
|
|
663
|
+
[self refreshApprovalBadge];
|
|
664
|
+
}
|
|
665
|
+
// 只改卡片内容和回跳目标,不走 displayAgentRecord:那条路会连带播动画、说一句话、
|
|
666
|
+
// 发一次通知,而这里是"气泡闲下来后回落",重复表演反而吵。
|
|
667
|
+
- (void)presentPendingApprovalRecord:(NSDictionary *)record {
|
|
668
|
+
if (record.count == 0) return;
|
|
669
|
+
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
670
|
+
? record[@"terminal"] : nil;
|
|
671
|
+
if (terminal.count > 0) self.lastTerminalFocusTarget = terminal;
|
|
672
|
+
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
673
|
+
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
|
|
674
|
+
if ([self.lastStatusState isEqualToString:@"approval"] &&
|
|
675
|
+
[self.lastStatusProvider isEqualToString:provider]) return;
|
|
676
|
+
[self applyStatusPresentationForState:@"approval"
|
|
677
|
+
provider:provider.length > 0 ? provider : @"Agent" tool:tool];
|
|
580
678
|
}
|
|
581
679
|
// 勾选 = 显示气泡。没有 agent 状态时也允许改,这样用户可以提前设好偏好,
|
|
582
680
|
// 而不必等下一次会话开始。
|
|
@@ -621,6 +719,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
621
719
|
self.statusIconButton.contentTintColor = [stateColor blendedColorWithFraction:0.18
|
|
622
720
|
ofColor:NSColor.blackColor] ?: stateColor;
|
|
623
721
|
[self resizeStatusCardToFitText];
|
|
722
|
+
[self layoutApprovalBadge];
|
|
624
723
|
[self positionAgentStatus];
|
|
625
724
|
if (self.statusBubbleExpanded) {
|
|
626
725
|
[self.statusPanel orderFrontRegardless];
|
|
@@ -651,6 +750,10 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
651
750
|
if (self.hasAgentStatus && [provider isEqualToString:self.lastStatusProvider] &&
|
|
652
751
|
[self isTrailingRecord:record afterState:self.lastStatusState]) return;
|
|
653
752
|
|
|
753
|
+
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
754
|
+
? record[@"terminal"] : nil;
|
|
755
|
+
self.lastTerminalFocusTarget = terminal.count > 0 ? terminal : nil;
|
|
756
|
+
|
|
654
757
|
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
655
758
|
selector:@selector(hideAgentStatus) object:nil];
|
|
656
759
|
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
@@ -700,15 +803,6 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
700
803
|
[self.pendingApprovalRecords removeObjectForKey:key];
|
|
701
804
|
}
|
|
702
805
|
}
|
|
703
|
-
- (NSDictionary *)latestPendingApprovalRecord {
|
|
704
|
-
NSDictionary *latest = nil;
|
|
705
|
-
for (NSDictionary *record in self.pendingApprovalRecords.allValues) {
|
|
706
|
-
if (!latest || [record[@"timestamp"] doubleValue] > [latest[@"timestamp"] doubleValue]) {
|
|
707
|
-
latest = record;
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
return latest;
|
|
711
|
-
}
|
|
712
806
|
- (void)displayAgentRecord:(NSDictionary *)record notify:(BOOL)shouldNotify {
|
|
713
807
|
NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
|
|
714
808
|
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
@@ -722,6 +816,567 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
722
816
|
// 的 recentOnly + 5 秒 cutoff 挡住,再加上预算制和冷却,最坏也只多说一句。
|
|
723
817
|
[self considerSpeechForRecord:record];
|
|
724
818
|
}
|
|
819
|
+
- (NSString *)agentSessionKeyForRecord:(NSDictionary *)record {
|
|
820
|
+
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
821
|
+
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
822
|
+
? record[@"terminal"] : nil;
|
|
823
|
+
NSString *tty = SanitizedShortString(terminal[@"tty"], 64);
|
|
824
|
+
NSString *bundleID = SanitizedShortString(terminal[@"bundleID"], 128);
|
|
825
|
+
if (tty.length > 0) {
|
|
826
|
+
return [NSString stringWithFormat:@"%@|%@|%@", provider, bundleID, tty];
|
|
827
|
+
}
|
|
828
|
+
NSString *session = SanitizedShortString(record[@"session"], 128);
|
|
829
|
+
if (session.length > 0) return [NSString stringWithFormat:@"%@|%@", provider, session];
|
|
830
|
+
return terminal.count > 0 ? [NSString stringWithFormat:@"%@|%@", provider, bundleID] : nil;
|
|
831
|
+
}
|
|
832
|
+
- (NSString *)onlineAgentSessionKeyForProvider:(NSString *)provider tty:(NSString *)tty {
|
|
833
|
+
provider = SanitizedShortString(provider, 32);
|
|
834
|
+
tty = SanitizedShortString(tty.lastPathComponent, 64);
|
|
835
|
+
if (provider.length == 0 || tty.length == 0) return nil;
|
|
836
|
+
return [NSString stringWithFormat:@"%@|%@", provider, tty];
|
|
837
|
+
}
|
|
838
|
+
- (NSString *)onlineAgentSessionKeyForRecord:(NSDictionary *)record {
|
|
839
|
+
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
840
|
+
? record[@"terminal"] : nil;
|
|
841
|
+
return [self onlineAgentSessionKeyForProvider:record[@"provider"] tty:terminal[@"tty"]];
|
|
842
|
+
}
|
|
843
|
+
// 在线判定优先用包装脚本写出的 pid 文件:它给出精确的退出信号,会话一关列表就更新。
|
|
844
|
+
// 但直接跑 claude / codex(或终端窗口早于 shim 安装就已打开)的会话根本没有 pid 文件,
|
|
845
|
+
// 只按 pid 文件判定会把它们当场判死,列表里永远看不到——哪怕它们的 Hook 正在正常发事件。
|
|
846
|
+
// 这类会话退回活跃度宽限:最近一次事件在静默窗口内就算在线。某个 provider 一旦出现过
|
|
847
|
+
// pid 文件,说明包装脚本对它生效,继续按精确信号判定,不被宽限盖住。
|
|
848
|
+
- (BOOL)isAgentSessionRecordLive:(NSDictionary *)record {
|
|
849
|
+
NSString *onlineKey = [self onlineAgentSessionKeyForRecord:record];
|
|
850
|
+
if (onlineKey.length > 0 && [self.liveAgentSessionKeys containsObject:onlineKey]) return YES;
|
|
851
|
+
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
852
|
+
if (provider.length > 0 && [self.liveClientProviders containsObject:provider]) return NO;
|
|
853
|
+
return NSDate.date.timeIntervalSince1970 - [record[@"timestamp"] doubleValue]
|
|
854
|
+
< AgentStatusInactivityInterval;
|
|
855
|
+
}
|
|
856
|
+
- (void)pruneOfflineAgentSessionRecords {
|
|
857
|
+
for (NSString *key in self.agentSessionRecords.allKeys) {
|
|
858
|
+
if (![self isAgentSessionRecordLive:self.agentSessionRecords[key]]) {
|
|
859
|
+
[self.agentSessionRecords removeObjectForKey:key];
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
- (void)trackAgentSessionRecord:(NSDictionary *)record {
|
|
864
|
+
NSString *key = [self agentSessionKeyForRecord:record];
|
|
865
|
+
if (key.length == 0) return;
|
|
866
|
+
if (!self.agentSessionRecords) self.agentSessionRecords = [NSMutableDictionary dictionary];
|
|
867
|
+
self.agentSessionRecords[key] = record;
|
|
868
|
+
if (self.agentSessionRecords.count <= AgentSessionRecordLimit) return;
|
|
869
|
+
NSArray<NSDictionary *> *oldestFirst = [self.agentSessionRecords.allValues
|
|
870
|
+
sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
871
|
+
return [left[@"timestamp"] compare:right[@"timestamp"]];
|
|
872
|
+
}];
|
|
873
|
+
NSUInteger removeCount = oldestFirst.count - AgentSessionRecordLimit;
|
|
874
|
+
for (NSUInteger index = 0; index < removeCount; index++) {
|
|
875
|
+
NSString *oldKey = [self agentSessionKeyForRecord:oldestFirst[index]];
|
|
876
|
+
if (oldKey) [self.agentSessionRecords removeObjectForKey:oldKey];
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
- (BOOL)isApprovalSessionRecord:(NSDictionary *)record {
|
|
880
|
+
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
881
|
+
return [state isEqualToString:@"approval"];
|
|
882
|
+
}
|
|
883
|
+
// 卡在审批的在线会话,最近的排前面。角标计数和会话列表置顶共用这一份,两处数字
|
|
884
|
+
// 才不会打架。判据是"该会话的最后一条事件是审批"——审批一旦被处理,后续事件会
|
|
885
|
+
// 把这条记录顶掉,会话自然退出这个集合,不需要额外的解除信号。
|
|
886
|
+
- (NSArray<NSDictionary *> *)pendingApprovalSessionRecords {
|
|
887
|
+
[self pruneOfflineAgentSessionRecords];
|
|
888
|
+
NSMutableArray<NSDictionary *> *pending = [NSMutableArray array];
|
|
889
|
+
for (NSDictionary *record in self.agentSessionRecords.allValues) {
|
|
890
|
+
if ([self isApprovalSessionRecord:record]) [pending addObject:record];
|
|
891
|
+
}
|
|
892
|
+
[pending sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
893
|
+
return [right[@"timestamp"] compare:left[@"timestamp"]];
|
|
894
|
+
}];
|
|
895
|
+
return pending;
|
|
896
|
+
}
|
|
897
|
+
- (NSTimeInterval)stallIntervalForState:(NSString *)state {
|
|
898
|
+
if ([state isEqualToString:@"approval"]) return AgentApprovalStallInterval;
|
|
899
|
+
if ([state isEqualToString:@"thinking"]) return AgentThinkingStallInterval;
|
|
900
|
+
return 0;
|
|
901
|
+
}
|
|
902
|
+
// 会话停在同一个状态太久就提醒一次。去重键带上该会话当时的时间戳:会话一有新
|
|
903
|
+
// 事件,时间戳变了,旧键自然失效,于是下一次卡住还会再提醒。每轮用当前有效键
|
|
904
|
+
// 求交集,退出的会话不会在集合里留垃圾。
|
|
905
|
+
- (void)checkStalledAgentSessions {
|
|
906
|
+
if (self.agentSessionRecords.count == 0) {
|
|
907
|
+
[self.stallNotifiedSessionKeys removeAllObjects];
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
[self pruneOfflineAgentSessionRecords];
|
|
911
|
+
if (!self.stallNotifiedSessionKeys) self.stallNotifiedSessionKeys = [NSMutableSet set];
|
|
912
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
913
|
+
BOOL shouldNotify = [NSUserDefaults.standardUserDefaults boolForKey:NotificationStallKey];
|
|
914
|
+
NSMutableSet<NSString *> *valid = [NSMutableSet set];
|
|
915
|
+
NSDictionary *stalled = nil;
|
|
916
|
+
for (NSString *key in self.agentSessionRecords.allKeys) {
|
|
917
|
+
NSDictionary *record = self.agentSessionRecords[key];
|
|
918
|
+
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
919
|
+
NSString *stamp = [NSString stringWithFormat:@"%@|%.0f", key, timestamp];
|
|
920
|
+
[valid addObject:stamp];
|
|
921
|
+
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
922
|
+
NSTimeInterval limit = [self stallIntervalForState:state];
|
|
923
|
+
if (limit <= 0 || now - timestamp < limit) continue;
|
|
924
|
+
if ([self.stallNotifiedSessionKeys containsObject:stamp]) continue;
|
|
925
|
+
[self.stallNotifiedSessionKeys addObject:stamp];
|
|
926
|
+
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
927
|
+
if (provider.length == 0) provider = @"Agent";
|
|
928
|
+
if (shouldNotify) {
|
|
929
|
+
NSInteger minutes = (NSInteger)((now - timestamp) / 60.0);
|
|
930
|
+
[self sendNotificationWithTitle:
|
|
931
|
+
[state isEqualToString:@"approval"] ? @"审批仍在等待" : @"Agent 长时间无响应"
|
|
932
|
+
body:[NSString stringWithFormat:@"%@ 已%@ %ld 分钟。",
|
|
933
|
+
provider, [self statusTextForState:state tool:record[@"tool"]], (long)minutes]];
|
|
934
|
+
}
|
|
935
|
+
// 多个会话同时卡住时只把最旧的那条顶到气泡上:它等得最久。
|
|
936
|
+
if (!stalled || [record[@"timestamp"] doubleValue] < [stalled[@"timestamp"] doubleValue]) {
|
|
937
|
+
stalled = record;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
[self.stallNotifiedSessionKeys intersectSet:valid];
|
|
941
|
+
if (!stalled) return;
|
|
942
|
+
NSString *event = [stalled[@"event"] isKindOfClass:NSString.class] ? stalled[@"event"] : @"";
|
|
943
|
+
NSString *tool = [stalled[@"tool"] isKindOfClass:NSString.class] ? stalled[@"tool"] : @"";
|
|
944
|
+
[self.petView handleAgentEvent:event tool:tool failed:NO];
|
|
945
|
+
[self presentStalledRecord:stalled];
|
|
946
|
+
}
|
|
947
|
+
// 卡住提醒要把气泡重新推到眼前,所以这里不走 presentPendingApprovalRecord 那条
|
|
948
|
+
// 带早退的回落路径——面板此刻很可能已经因为长时间沉默被收走了,必须强制重现。
|
|
949
|
+
- (void)presentStalledRecord:(NSDictionary *)record {
|
|
950
|
+
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
951
|
+
? record[@"terminal"] : nil;
|
|
952
|
+
if (terminal.count > 0) self.lastTerminalFocusTarget = terminal;
|
|
953
|
+
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
954
|
+
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
955
|
+
self.hasAgentStatus = YES;
|
|
956
|
+
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
957
|
+
selector:@selector(hideAgentStatus) object:nil];
|
|
958
|
+
[self applyStatusPresentationForState:state
|
|
959
|
+
provider:provider.length > 0 ? provider : @"Agent"
|
|
960
|
+
tool:[record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @""];
|
|
961
|
+
[self.panel orderFrontRegardless];
|
|
962
|
+
[self performSelector:@selector(hideAgentStatus) withObject:nil
|
|
963
|
+
afterDelay:AgentStatusInactivityInterval];
|
|
964
|
+
}
|
|
965
|
+
- (void)layoutApprovalBadge {
|
|
966
|
+
if (!self.approvalBadgeView) return;
|
|
967
|
+
// statusIconButton 在玻璃卡片内,角标在卡片外层,差一个 6 点的卡片边距。
|
|
968
|
+
// 再各让出 4 点压到图标身上,看起来才是"贴在图标角上"而不是浮在旁边。
|
|
969
|
+
NSRect icon = self.statusIconButton.frame;
|
|
970
|
+
self.approvalBadgeView.frame = NSMakeRect(
|
|
971
|
+
6 + NSMaxX(icon) - PetApprovalBadgeSize + 4,
|
|
972
|
+
6 + NSMaxY(icon) - PetApprovalBadgeSize + 4,
|
|
973
|
+
PetApprovalBadgeSize, PetApprovalBadgeSize);
|
|
974
|
+
self.bridgeBadgeView.frame = NSMakeRect(
|
|
975
|
+
6 + NSMaxX(icon) - PetApprovalBadgeSize + 4,
|
|
976
|
+
6 + NSMinY(icon) - 4,
|
|
977
|
+
PetApprovalBadgeSize, PetApprovalBadgeSize);
|
|
978
|
+
}
|
|
979
|
+
- (void)refreshApprovalBadge {
|
|
980
|
+
CCPetsApprovalBadgeView *badge = (CCPetsApprovalBadgeView *)self.approvalBadgeView;
|
|
981
|
+
if (!badge) return;
|
|
982
|
+
badge.count = [self pendingApprovalSessionRecords].count;
|
|
983
|
+
[self layoutApprovalBadge];
|
|
984
|
+
}
|
|
985
|
+
// 等审批的排最前面。纯按时间倒序会把它们推到最底下——它们的时间戳按定义只会
|
|
986
|
+
// 越来越旧,而它们恰恰是唯一需要用户动手的那几条。
|
|
987
|
+
- (NSArray<NSDictionary *> *)recentAgentSessionRecords {
|
|
988
|
+
[self pruneOfflineAgentSessionRecords];
|
|
989
|
+
NSArray<NSDictionary *> *records = [self.agentSessionRecords.allValues
|
|
990
|
+
sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
991
|
+
BOOL leftApproval = [self isApprovalSessionRecord:left];
|
|
992
|
+
BOOL rightApproval = [self isApprovalSessionRecord:right];
|
|
993
|
+
if (leftApproval != rightApproval) return leftApproval ? NSOrderedAscending : NSOrderedDescending;
|
|
994
|
+
return [right[@"timestamp"] compare:left[@"timestamp"]];
|
|
995
|
+
}];
|
|
996
|
+
if (records.count <= AgentSessionMenuLimit) return records;
|
|
997
|
+
return [records subarrayWithRange:NSMakeRange(0, AgentSessionMenuLimit)];
|
|
998
|
+
}
|
|
999
|
+
- (NSString *)terminalNameForTarget:(NSDictionary *)target {
|
|
1000
|
+
NSString *program = SanitizedShortString(target[@"program"], 64);
|
|
1001
|
+
NSString *lower = program.lowercaseString;
|
|
1002
|
+
if ([lower isEqualToString:@"apple_terminal"]) return @"Terminal";
|
|
1003
|
+
if ([lower containsString:@"iterm"]) return @"iTerm2";
|
|
1004
|
+
if ([lower isEqualToString:@"vscode"]) return @"VS Code";
|
|
1005
|
+
if ([lower containsString:@"jetbrains"]) return @"JetBrains";
|
|
1006
|
+
if ([lower containsString:@"ghostty"]) return @"Ghostty";
|
|
1007
|
+
if ([lower containsString:@"warp"]) return @"Warp";
|
|
1008
|
+
if ([lower containsString:@"wezterm"]) return @"WezTerm";
|
|
1009
|
+
if (program.length > 0) return program;
|
|
1010
|
+
NSString *bundleID = SanitizedShortString(target[@"bundleID"], 128);
|
|
1011
|
+
return bundleID.length > 0 ? bundleID : @"Terminal";
|
|
1012
|
+
}
|
|
1013
|
+
- (void)focusAgentSessionRecord:(NSMenuItem *)sender {
|
|
1014
|
+
NSDictionary *record = [sender.representedObject isKindOfClass:NSDictionary.class]
|
|
1015
|
+
? sender.representedObject : nil;
|
|
1016
|
+
NSDictionary *target = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
1017
|
+
? record[@"terminal"] : nil;
|
|
1018
|
+
if (target.count > 0) ActivateTerminalFocusTarget(target);
|
|
1019
|
+
}
|
|
1020
|
+
- (void)showAgentSessionsMenu:(NSButton *)sender {
|
|
1021
|
+
NSArray<NSDictionary *> *records = [self recentAgentSessionRecords];
|
|
1022
|
+
[self refreshBridgeState:nil];
|
|
1023
|
+
NSArray<NSDictionary *> *deliveries = self.bridgeRecentDeliveries ?: @[];
|
|
1024
|
+
NSDictionary<NSString *, NSNumber *> *pending = self.bridgePendingCounts ?: @{};
|
|
1025
|
+
if (records.count == 0 && deliveries.count == 0 && pending.count == 0) return;
|
|
1026
|
+
NSMenu *menu = [[NSMenu alloc] initWithTitle:@"最近 Agent 会话"];
|
|
1027
|
+
if (deliveries.count > 0 || pending.count > 0) {
|
|
1028
|
+
[self addBridgeItemsToMenu:menu deliveries:deliveries pending:pending];
|
|
1029
|
+
[menu addItem:NSMenuItem.separatorItem];
|
|
1030
|
+
}
|
|
1031
|
+
// 菜单打开即视为看过:角标清零,下一条新消息再亮。
|
|
1032
|
+
self.bridgeSeenAt = NSDate.date.timeIntervalSince1970;
|
|
1033
|
+
[self refreshBridgeBadge];
|
|
1034
|
+
if (records.count == 0) {
|
|
1035
|
+
[menu popUpMenuPositioningItem:nil
|
|
1036
|
+
atLocation:NSMakePoint(0, NSHeight(sender.bounds) + 4) inView:sender];
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
NSMenuItem *heading = [menu addItemWithTitle:@"最近 Agent 会话" action:nil keyEquivalent:@""];
|
|
1040
|
+
heading.enabled = NO;
|
|
1041
|
+
[menu addItem:NSMenuItem.separatorItem];
|
|
1042
|
+
BOOL separatedApprovals = NO;
|
|
1043
|
+
for (NSDictionary *record in records) {
|
|
1044
|
+
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
1045
|
+
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
1046
|
+
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
|
|
1047
|
+
NSDictionary *target = record[@"terminal"];
|
|
1048
|
+
BOOL approval = [self isApprovalSessionRecord:record];
|
|
1049
|
+
// 置顶的审批组和其余会话之间划一道线,免得两段看起来像同一个时间序列。
|
|
1050
|
+
if (!approval && !separatedApprovals && record != records.firstObject) {
|
|
1051
|
+
[menu addItem:NSMenuItem.separatorItem];
|
|
1052
|
+
separatedApprovals = YES;
|
|
1053
|
+
}
|
|
1054
|
+
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[record[@"timestamp"] doubleValue]];
|
|
1055
|
+
NSString *time = [NSDateFormatter localizedStringFromDate:date
|
|
1056
|
+
dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle];
|
|
1057
|
+
// 开启 CC Bridge 时带上会话名:用户和 Agent 之间就是用这个名字互相指代的。
|
|
1058
|
+
NSDictionary *bridge = [self bridgeSessionEntryForRecord:record];
|
|
1059
|
+
NSString *bridgeName = bridge.count > 0
|
|
1060
|
+
? [NSString stringWithFormat:@"(%@)", bridge[@"name"]] : @"";
|
|
1061
|
+
NSUInteger waiting = [pending[[self bridgeSessionIdForRecord:record] ?: @""] unsignedIntegerValue];
|
|
1062
|
+
NSString *title = [NSString stringWithFormat:@"%@%@%@ · %@ · %@ · %@%@",
|
|
1063
|
+
approval ? @"⚠️ " : @"",
|
|
1064
|
+
provider.length > 0 ? provider : @"Agent", bridgeName,
|
|
1065
|
+
[self statusTextForState:state tool:tool], [self terminalNameForTarget:target], time,
|
|
1066
|
+
waiting > 0 ? [NSString stringWithFormat:@" · 📬 %lu", (unsigned long)waiting] : @""];
|
|
1067
|
+
NSMenuItem *item = [menu addItemWithTitle:title
|
|
1068
|
+
action:@selector(focusAgentSessionRecord:) keyEquivalent:@""];
|
|
1069
|
+
item.target = self;
|
|
1070
|
+
item.representedObject = record;
|
|
1071
|
+
if ([target isEqual:self.lastTerminalFocusTarget]) item.state = NSControlStateValueOn;
|
|
1072
|
+
}
|
|
1073
|
+
[menu popUpMenuPositioningItem:nil
|
|
1074
|
+
atLocation:NSMakePoint(0, NSHeight(sender.bounds) + 4) inView:sender];
|
|
1075
|
+
}
|
|
1076
|
+
#pragma mark - CC Bridge
|
|
1077
|
+
|
|
1078
|
+
// 菜单开关 → cc-pets bridge enable / disable / configure。逻辑全在 CLI 里,桌宠只负责调用,
|
|
1079
|
+
// 命令行与菜单两条路的行为才一致。enable 要跑 claude / codex mcp add,要几秒,所以异步执行;
|
|
1080
|
+
// 执行期间忽略新的切换,结束后按实际状态刷新(菜单下次打开时现读)。
|
|
1081
|
+
- (void)runBridgeCommand:(NSArray<NSString *> *)arguments sender:(NSButton *)sender
|
|
1082
|
+
successMessage:(NSString *)successMessage {
|
|
1083
|
+
NSDictionary<NSString *, NSString *> *locator = CCBridgeCLILocator();
|
|
1084
|
+
if (!locator) {
|
|
1085
|
+
[self showUpdateAlertWithTitle:@"无法修改 CC Bridge 设置"
|
|
1086
|
+
message:@"没有找到 cc-pets 的命令行程序。请在终端执行一次 cc-pets install 后重试。"];
|
|
1087
|
+
[self syncBridgeSwitch:sender];
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
1090
|
+
if (self.bridgeCommandRunning) {
|
|
1091
|
+
[self syncBridgeSwitch:sender];
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
self.bridgeCommandRunning = YES;
|
|
1095
|
+
NSTask *task = [NSTask new];
|
|
1096
|
+
task.executableURL = [NSURL fileURLWithPath:locator[@"node"]];
|
|
1097
|
+
task.arguments = [@[locator[@"cli"]] arrayByAddingObjectsFromArray:arguments];
|
|
1098
|
+
NSMutableDictionary<NSString *, NSString *> *environment =
|
|
1099
|
+
[NSProcessInfo.processInfo.environment mutableCopy];
|
|
1100
|
+
NSString *existingPath = environment[@"PATH"].length > 0 ? environment[@"PATH"] : @"/usr/bin:/bin:/usr/sbin:/sbin";
|
|
1101
|
+
// claude / codex 常装在 node 同目录(nvm),桌宠的 PATH 里未必有。
|
|
1102
|
+
environment[@"PATH"] = [NSString stringWithFormat:@"%@:%@",
|
|
1103
|
+
[locator[@"node"] stringByDeletingLastPathComponent], existingPath];
|
|
1104
|
+
task.environment = environment;
|
|
1105
|
+
NSPipe *output = [NSPipe pipe];
|
|
1106
|
+
task.standardOutput = output;
|
|
1107
|
+
task.standardError = output;
|
|
1108
|
+
__weak typeof(self) weakSelf = self;
|
|
1109
|
+
task.terminationHandler = ^(NSTask *finished) {
|
|
1110
|
+
NSData *data = [output.fileHandleForReading readDataToEndOfFile];
|
|
1111
|
+
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"";
|
|
1112
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1113
|
+
typeof(self) strongSelf = weakSelf;
|
|
1114
|
+
if (!strongSelf) return;
|
|
1115
|
+
strongSelf.bridgeCommandRunning = NO;
|
|
1116
|
+
[strongSelf refreshBridgeState:nil];
|
|
1117
|
+
if (finished.terminationStatus == EXIT_SUCCESS) {
|
|
1118
|
+
if (successMessage.length > 0) {
|
|
1119
|
+
[strongSelf sendNotificationWithTitle:@"CC Bridge" body:successMessage];
|
|
1120
|
+
}
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
1123
|
+
[strongSelf syncBridgeSwitch:sender];
|
|
1124
|
+
NSString *detail = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
|
1125
|
+
[strongSelf showUpdateAlertWithTitle:@"CC Bridge 设置失败"
|
|
1126
|
+
message:detail.length > 0 ? detail : @"命令执行失败。"];
|
|
1127
|
+
});
|
|
1128
|
+
};
|
|
1129
|
+
NSError *error = nil;
|
|
1130
|
+
if (![task launchAndReturnError:&error]) {
|
|
1131
|
+
self.bridgeCommandRunning = NO;
|
|
1132
|
+
[self syncBridgeSwitch:sender];
|
|
1133
|
+
[self showUpdateAlertWithTitle:@"CC Bridge 设置失败" message:error.localizedDescription];
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
// 与其他菜单开关一致:目标状态按"实际存储的状态取反"算,不信任开关视图自己翻转后的 state——
|
|
1137
|
+
// 菜单停留期间状态可能已被命令行改过。命令没执行成功时再把开关翻回实际状态。
|
|
1138
|
+
- (BOOL)currentBridgeStateForSwitch:(NSButton *)sender {
|
|
1139
|
+
NSDictionary *options = CCBridgeOptions();
|
|
1140
|
+
if (sender.action == @selector(toggleBridgeEnabled:)) return CCBridgeEnabled();
|
|
1141
|
+
if (sender.action == @selector(toggleBridgeWake:)) return [options[@"wake"] boolValue];
|
|
1142
|
+
if (sender.action == @selector(toggleBridgeEditGuard:)) return [options[@"editGuard"] boolValue];
|
|
1143
|
+
if (sender.action == @selector(toggleBridgeApproval:)) {
|
|
1144
|
+
NSSet *tools = [NSSet setWithArray:CCBridgeToolGroup([self bridgeApprovalGroupForTag:sender.tag])];
|
|
1145
|
+
return tools.count > 0 && [tools isSubsetOfSet:[NSSet setWithArray:options[@"codexApprove"]]] &&
|
|
1146
|
+
[tools isSubsetOfSet:[NSSet setWithArray:options[@"claudeAllow"]]];
|
|
1147
|
+
}
|
|
1148
|
+
return NO;
|
|
1149
|
+
}
|
|
1150
|
+
- (void)syncBridgeSwitch:(NSButton *)sender {
|
|
1151
|
+
if (!sender) return;
|
|
1152
|
+
sender.state = [self currentBridgeStateForSwitch:sender] ? NSControlStateValueOn : NSControlStateValueOff;
|
|
1153
|
+
}
|
|
1154
|
+
// 返回目标状态,并先把开关视图摆到目标状态上(命令失败时 syncBridgeSwitch 再翻回来)。
|
|
1155
|
+
- (BOOL)targetBridgeStateForSwitch:(NSButton *)sender {
|
|
1156
|
+
BOOL target = ![self currentBridgeStateForSwitch:sender];
|
|
1157
|
+
sender.state = target ? NSControlStateValueOn : NSControlStateValueOff;
|
|
1158
|
+
return target;
|
|
1159
|
+
}
|
|
1160
|
+
- (NSString *)bridgeApprovalGroupForTag:(NSInteger)tag {
|
|
1161
|
+
NSArray<NSString *> *groups = CCBridgeToolGroupNames();
|
|
1162
|
+
return tag >= 1 && tag <= (NSInteger)groups.count ? groups[tag - 1] : @"";
|
|
1163
|
+
}
|
|
1164
|
+
- (void)toggleBridgeEnabled:(NSButton *)sender {
|
|
1165
|
+
BOOL enable = [self targetBridgeStateForSwitch:sender];
|
|
1166
|
+
[self runBridgeCommand:@[enable ? @"enable" : @"disable"] sender:sender
|
|
1167
|
+
successMessage:enable
|
|
1168
|
+
? @"已开启。已在运行的 Codex 会话需重启并在 /hooks 中信任;Claude 会话重启后才有 cc-bridge 工具。"
|
|
1169
|
+
: @"已关闭,相关 hooks 与 MCP 注册已移除。"];
|
|
1170
|
+
}
|
|
1171
|
+
// 一个分组同时作用于 Codex 免审批与 Claude 免确认:菜单上只有一组开关,两边保持一致。
|
|
1172
|
+
- (void)toggleBridgeApproval:(NSButton *)sender {
|
|
1173
|
+
NSArray<NSString *> *tools = CCBridgeToolGroup([self bridgeApprovalGroupForTag:sender.tag]);
|
|
1174
|
+
if (tools.count == 0) return;
|
|
1175
|
+
BOOL allow = [self targetBridgeStateForSwitch:sender];
|
|
1176
|
+
NSDictionary *options = CCBridgeOptions();
|
|
1177
|
+
NSString *(^apply)(NSArray<NSString *> *) = ^NSString *(NSArray<NSString *> *current) {
|
|
1178
|
+
NSMutableOrderedSet<NSString *> *next = [NSMutableOrderedSet orderedSetWithArray:current];
|
|
1179
|
+
if (allow) [next addObjectsFromArray:tools]; else [next removeObjectsInArray:tools];
|
|
1180
|
+
return [next.array componentsJoinedByString:@","];
|
|
1181
|
+
};
|
|
1182
|
+
[self runBridgeCommand:@[@"configure",
|
|
1183
|
+
[@"--codex-approve=" stringByAppendingString:apply(options[@"codexApprove"])],
|
|
1184
|
+
[@"--claude-allow=" stringByAppendingString:apply(options[@"claudeAllow"])]]
|
|
1185
|
+
sender:sender successMessage:nil];
|
|
1186
|
+
}
|
|
1187
|
+
- (void)toggleBridgeWake:(NSButton *)sender {
|
|
1188
|
+
[self runBridgeCommand:@[@"configure",
|
|
1189
|
+
[self targetBridgeStateForSwitch:sender] ? @"--wake=on" : @"--wake=off"] sender:sender successMessage:nil];
|
|
1190
|
+
}
|
|
1191
|
+
- (void)toggleBridgeEditGuard:(NSButton *)sender {
|
|
1192
|
+
[self runBridgeCommand:@[@"configure",
|
|
1193
|
+
[self targetBridgeStateForSwitch:sender] ? @"--edit-guard=on" : @"--edit-guard=off"]
|
|
1194
|
+
sender:sender successMessage:nil];
|
|
1195
|
+
}
|
|
1196
|
+
- (void)toggleBridgeBadge:(NSButton *)sender {
|
|
1197
|
+
BOOL enabled = ![NSUserDefaults.standardUserDefaults boolForKey:BridgeBadgeEnabledKey];
|
|
1198
|
+
[NSUserDefaults.standardUserDefaults setBool:enabled forKey:BridgeBadgeEnabledKey];
|
|
1199
|
+
sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
1200
|
+
[self refreshBridgeBadge];
|
|
1201
|
+
}
|
|
1202
|
+
// 与"系统通知"那组开关同一套授权流程:第一次打开时向系统申请通知权限。
|
|
1203
|
+
- (void)toggleBridgeNotification:(NSButton *)sender {
|
|
1204
|
+
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
1205
|
+
if ([defaults boolForKey:BridgeNotificationKey]) {
|
|
1206
|
+
[defaults setBool:NO forKey:BridgeNotificationKey];
|
|
1207
|
+
sender.state = NSControlStateValueOff;
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
[UNUserNotificationCenter.currentNotificationCenter
|
|
1211
|
+
requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound
|
|
1212
|
+
completionHandler:^(BOOL granted, NSError *error) {
|
|
1213
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1214
|
+
[defaults setBool:granted forKey:BridgeNotificationKey];
|
|
1215
|
+
sender.state = granted ? NSControlStateValueOn : NSControlStateValueOff;
|
|
1216
|
+
if (!granted) {
|
|
1217
|
+
[self showUpdateAlertWithTitle:@"无法启用系统通知" message:error.localizedDescription ?:
|
|
1218
|
+
@"请在“系统设置 → 通知 → CC Pets”中允许通知后重试。"];
|
|
1219
|
+
}
|
|
1220
|
+
});
|
|
1221
|
+
}];
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// 读 bridge 状态(会话名、最近送达、信箱积压),刷新角标。bridge 未开启时清空并隐藏。
|
|
1225
|
+
// 回执目录没变就不重读文件,只按时间窗重新过滤缓存——回执状态一变,写入端的
|
|
1226
|
+
// "临时文件 + rename" 必然改动目录的修改时间。
|
|
1227
|
+
- (void)refreshBridgeState:(NSTimer *)timer {
|
|
1228
|
+
if (!CCBridgeEnabled()) {
|
|
1229
|
+
self.bridgeSessions = nil;
|
|
1230
|
+
self.bridgeRecentDeliveries = nil;
|
|
1231
|
+
self.bridgePendingCounts = nil;
|
|
1232
|
+
self.bridgeSentStamp = nil;
|
|
1233
|
+
[self refreshBridgeBadge];
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
1237
|
+
NSString *directory = CCBridgeStateDirectory();
|
|
1238
|
+
self.bridgeSessions = CCBridgeSessions();
|
|
1239
|
+
NSDate *stamp = [NSFileManager.defaultManager attributesOfItemAtPath:
|
|
1240
|
+
[directory stringByAppendingPathComponent:@"sent"] error:nil].fileModificationDate;
|
|
1241
|
+
if (!stamp || ![stamp isEqualToDate:self.bridgeSentStamp] || !self.bridgeDeliveryCache) {
|
|
1242
|
+
self.bridgeDeliveryCache = CCBridgeRecentDeliveries(now - BridgeRecentWindow, 50);
|
|
1243
|
+
self.bridgeSentStamp = stamp;
|
|
1244
|
+
}
|
|
1245
|
+
NSMutableArray<NSDictionary *> *recent = [NSMutableArray array];
|
|
1246
|
+
for (NSDictionary *delivery in self.bridgeDeliveryCache) {
|
|
1247
|
+
if ([delivery[@"at"] doubleValue] >= now - BridgeRecentWindow) [recent addObject:delivery];
|
|
1248
|
+
}
|
|
1249
|
+
self.bridgeRecentDeliveries = recent;
|
|
1250
|
+
// 只算仍在线的会话:已退出会话的积压已经投不出去,提醒也无从处理。
|
|
1251
|
+
NSMutableDictionary<NSString *, NSNumber *> *pending = [NSMutableDictionary dictionary];
|
|
1252
|
+
[CCBridgePendingCounts() enumerateKeysAndObjectsUsingBlock:^(NSString *session, NSNumber *count, BOOL *stop) {
|
|
1253
|
+
if (self.bridgeSessions[session]) pending[session] = count;
|
|
1254
|
+
}];
|
|
1255
|
+
self.bridgePendingCounts = pending;
|
|
1256
|
+
[self notifyNewBridgeDeliveries];
|
|
1257
|
+
[self refreshBridgeBadge];
|
|
1258
|
+
}
|
|
1259
|
+
// 新送达的跨会话消息发系统通知:只含谁发给谁,不含正文。一次刷新里来了多条时合并成一条。
|
|
1260
|
+
- (void)notifyNewBridgeDeliveries {
|
|
1261
|
+
NSMutableArray<NSDictionary *> *fresh = [NSMutableArray array];
|
|
1262
|
+
for (NSDictionary *delivery in self.bridgeRecentDeliveries) {
|
|
1263
|
+
if ([delivery[@"at"] doubleValue] > self.bridgeNotifiedAt) [fresh addObject:delivery];
|
|
1264
|
+
}
|
|
1265
|
+
if (fresh.count == 0) return;
|
|
1266
|
+
for (NSDictionary *delivery in fresh) {
|
|
1267
|
+
self.bridgeNotifiedAt = MAX(self.bridgeNotifiedAt, [delivery[@"at"] doubleValue]);
|
|
1268
|
+
}
|
|
1269
|
+
if (![NSUserDefaults.standardUserDefaults boolForKey:BridgeNotificationKey]) return;
|
|
1270
|
+
NSDictionary *latest = fresh.firstObject;
|
|
1271
|
+
NSString *body = fresh.count == 1
|
|
1272
|
+
? [NSString stringWithFormat:@"%@ → %@", latest[@"from"], latest[@"to"]]
|
|
1273
|
+
: [NSString stringWithFormat:@"%@ → %@ 等 %lu 条", latest[@"from"], latest[@"to"],
|
|
1274
|
+
(unsigned long)fresh.count];
|
|
1275
|
+
[self sendNotificationWithTitle:@"CC Bridge 新消息" body:body];
|
|
1276
|
+
}
|
|
1277
|
+
// 蓝色 = 有新的跨会话消息送达;橙色 = 有消息卡在某个会话的信箱里(那个 Claude 会话长时间空闲、
|
|
1278
|
+
// 唤醒 watcher 已退出,要等用户在那个终端开口才会送进去),需要用户过去看一眼。
|
|
1279
|
+
- (void)refreshBridgeBadge {
|
|
1280
|
+
CCPetsApprovalBadgeView *badge = (CCPetsApprovalBadgeView *)self.bridgeBadgeView;
|
|
1281
|
+
if (!badge) return;
|
|
1282
|
+
if (![NSUserDefaults.standardUserDefaults boolForKey:BridgeBadgeEnabledKey]) {
|
|
1283
|
+
badge.count = 0;
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
NSUInteger unseen = 0;
|
|
1287
|
+
for (NSDictionary *delivery in self.bridgeRecentDeliveries) {
|
|
1288
|
+
if ([delivery[@"at"] doubleValue] > self.bridgeSeenAt) unseen++;
|
|
1289
|
+
}
|
|
1290
|
+
NSUInteger waiting = 0;
|
|
1291
|
+
for (NSNumber *count in self.bridgePendingCounts.allValues) waiting += count.unsignedIntegerValue;
|
|
1292
|
+
badge.fillColor = waiting > 0
|
|
1293
|
+
? [NSColor colorWithRed:0.92 green:0.58 blue:0.12 alpha:1]
|
|
1294
|
+
: [NSColor colorWithRed:0.20 green:0.47 blue:0.90 alpha:1];
|
|
1295
|
+
badge.count = unseen + waiting;
|
|
1296
|
+
[self layoutApprovalBadge];
|
|
1297
|
+
}
|
|
1298
|
+
- (NSString *)bridgeSessionIdForRecord:(NSDictionary *)record {
|
|
1299
|
+
NSString *session = SanitizedShortString(record[@"session"], 128);
|
|
1300
|
+
if (session.length > 0 && self.bridgeSessions[session]) return session;
|
|
1301
|
+
// 事件里没有 session id 的记录,退回按 provider + tty 对上 bridge 注册表。
|
|
1302
|
+
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class] ? record[@"terminal"] : nil;
|
|
1303
|
+
NSString *tty = SanitizedShortString([terminal[@"tty"] lastPathComponent], 64);
|
|
1304
|
+
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
1305
|
+
if (tty.length == 0) return nil;
|
|
1306
|
+
__block NSString *match = nil;
|
|
1307
|
+
[self.bridgeSessions enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary *entry, BOOL *stop) {
|
|
1308
|
+
if ([entry[@"tty"] isEqualToString:tty] && [entry[@"provider"] isEqualToString:provider]) {
|
|
1309
|
+
match = key;
|
|
1310
|
+
*stop = YES;
|
|
1311
|
+
}
|
|
1312
|
+
}];
|
|
1313
|
+
return match;
|
|
1314
|
+
}
|
|
1315
|
+
- (NSDictionary *)bridgeSessionEntryForRecord:(NSDictionary *)record {
|
|
1316
|
+
NSString *session = [self bridgeSessionIdForRecord:record];
|
|
1317
|
+
return session ? self.bridgeSessions[session] : nil;
|
|
1318
|
+
}
|
|
1319
|
+
// 收件会话的终端:优先用桌宠自己记录的该会话终端信息(带宿主应用),其次按 tty 对上任一
|
|
1320
|
+
// 已知终端,最后借用最近一次的宿主应用配上 bridge 记录的 tty。
|
|
1321
|
+
- (NSDictionary *)terminalTargetForBridgeSession:(NSString *)sessionId {
|
|
1322
|
+
NSString *tty = self.bridgeSessions[sessionId][@"tty"];
|
|
1323
|
+
NSDictionary *byTty = nil;
|
|
1324
|
+
for (NSDictionary *record in self.agentSessionRecords.allValues) {
|
|
1325
|
+
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class] ? record[@"terminal"] : nil;
|
|
1326
|
+
if (terminal.count == 0) continue;
|
|
1327
|
+
if ([SanitizedShortString(record[@"session"], 128) isEqualToString:sessionId]) return terminal;
|
|
1328
|
+
if (tty.length > 0 && [[terminal[@"tty"] lastPathComponent] isEqualToString:tty]) byTty = terminal;
|
|
1329
|
+
}
|
|
1330
|
+
if (byTty) return byTty;
|
|
1331
|
+
if (tty.length > 0 && self.lastTerminalFocusTarget.count > 0) {
|
|
1332
|
+
NSMutableDictionary *target = [self.lastTerminalFocusTarget mutableCopy];
|
|
1333
|
+
target[@"tty"] = tty;
|
|
1334
|
+
[target removeObjectForKey:@"session"];
|
|
1335
|
+
return target;
|
|
1336
|
+
}
|
|
1337
|
+
return nil;
|
|
1338
|
+
}
|
|
1339
|
+
- (void)focusBridgeSession:(NSMenuItem *)sender {
|
|
1340
|
+
NSString *sessionId = [sender.representedObject isKindOfClass:NSString.class] ? sender.representedObject : nil;
|
|
1341
|
+
NSDictionary *target = sessionId ? [self terminalTargetForBridgeSession:sessionId] : nil;
|
|
1342
|
+
if (target.count > 0) ActivateTerminalFocusTarget(target);
|
|
1343
|
+
}
|
|
1344
|
+
- (void)addBridgeItemsToMenu:(NSMenu *)menu deliveries:(NSArray<NSDictionary *> *)deliveries
|
|
1345
|
+
pending:(NSDictionary<NSString *, NSNumber *> *)pending {
|
|
1346
|
+
NSMenuItem *heading = [menu addItemWithTitle:@"CC Bridge 消息" action:nil keyEquivalent:@""];
|
|
1347
|
+
heading.enabled = NO;
|
|
1348
|
+
[pending enumerateKeysAndObjectsUsingBlock:^(NSString *session, NSNumber *count, BOOL *stop) {
|
|
1349
|
+
NSString *name = self.bridgeSessions[session][@"name"] ?: session;
|
|
1350
|
+
NSString *title = [NSString stringWithFormat:@"📬 %@ 有 %lu 条消息待投递(去那个终端说句话即可送达)",
|
|
1351
|
+
name, count.unsignedLongValue];
|
|
1352
|
+
NSMenuItem *item = [menu addItemWithTitle:title action:@selector(focusBridgeSession:) keyEquivalent:@""];
|
|
1353
|
+
item.target = self;
|
|
1354
|
+
item.representedObject = session;
|
|
1355
|
+
}];
|
|
1356
|
+
NSUInteger shown = 0;
|
|
1357
|
+
for (NSDictionary *delivery in deliveries) {
|
|
1358
|
+
if (shown++ >= BridgeMenuDeliveryLimit) break;
|
|
1359
|
+
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[delivery[@"at"] doubleValue]];
|
|
1360
|
+
NSString *time = [NSDateFormatter localizedStringFromDate:date
|
|
1361
|
+
dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle];
|
|
1362
|
+
BOOL unseen = [delivery[@"at"] doubleValue] > self.bridgeSeenAt;
|
|
1363
|
+
NSString *title = [NSString stringWithFormat:@"%@%@ → %@ · %@",
|
|
1364
|
+
unseen ? @"✉️ " : @"", delivery[@"from"], delivery[@"to"], time];
|
|
1365
|
+
NSMenuItem *item = [menu addItemWithTitle:title action:@selector(focusBridgeSession:) keyEquivalent:@""];
|
|
1366
|
+
item.target = self;
|
|
1367
|
+
item.representedObject = delivery[@"toSession"];
|
|
1368
|
+
item.toolTip = [NSString stringWithFormat:@"跳到 %@ 所在的终端", delivery[@"to"]];
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
- (BOOL)focusLatestAgentTerminal {
|
|
1373
|
+
// 只有 Hook 状态气泡上的透明按钮会调用这里;桌宠本体继续负责原有互动。
|
|
1374
|
+
if (!self.hasAgentStatus || self.lastTerminalFocusTarget.count == 0) return NO;
|
|
1375
|
+
return ActivateTerminalFocusTarget(self.lastTerminalFocusTarget);
|
|
1376
|
+
}
|
|
1377
|
+
- (void)focusLatestAgentTerminal:(id)sender {
|
|
1378
|
+
[self focusLatestAgentTerminal];
|
|
1379
|
+
}
|
|
725
1380
|
- (NSDictionary *)petManifestInDirectory:(NSString *)directory {
|
|
726
1381
|
NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
|
|
727
1382
|
NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
|
|
@@ -939,7 +1594,9 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
939
1594
|
PetInteractionEnabledKey: @YES,
|
|
940
1595
|
PetInteractionHeartThresholdKey: @3,
|
|
941
1596
|
PetInteractionAnnoyedThresholdKey: @10,
|
|
942
|
-
PetInteractionIntervalKey: @1.2
|
|
1597
|
+
PetInteractionIntervalKey: @1.2,
|
|
1598
|
+
BridgeBadgeEnabledKey: @YES,
|
|
1599
|
+
BridgeNotificationKey: @NO
|
|
943
1600
|
}];
|
|
944
1601
|
if (![defaults boolForKey:StatusBubblePreferenceV2Key]) {
|
|
945
1602
|
[defaults setBool:YES forKey:StatusBubbleExpandedKey];
|
|
@@ -1022,7 +1679,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1022
1679
|
self.statusPanel.opaque = NO;
|
|
1023
1680
|
self.statusPanel.backgroundColor = NSColor.clearColor;
|
|
1024
1681
|
self.statusPanel.hasShadow = NO;
|
|
1025
|
-
self.statusPanel.ignoresMouseEvents =
|
|
1682
|
+
self.statusPanel.ignoresMouseEvents = NO;
|
|
1026
1683
|
self.statusPanel.level = NSFloatingWindowLevel;
|
|
1027
1684
|
self.statusPanel.collectionBehavior =
|
|
1028
1685
|
NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
|
|
@@ -1076,15 +1733,45 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1076
1733
|
self.statusDetailLabel.lineBreakMode = NSLineBreakByTruncatingTail;
|
|
1077
1734
|
[self.statusGlass addSubview:self.statusDetailLabel];
|
|
1078
1735
|
|
|
1079
|
-
self.statusIconButton = [[
|
|
1736
|
+
self.statusIconButton = [[CCPetsStatusClickButton alloc] initWithFrame:NSMakeRect(
|
|
1080
1737
|
statusGlassSize.width - 48, 12, 34, 34)];
|
|
1081
1738
|
self.statusIconButton.bordered = NO;
|
|
1082
1739
|
self.statusIconButton.imagePosition = NSImageOnly;
|
|
1083
1740
|
self.statusIconButton.wantsLayer = YES;
|
|
1084
1741
|
self.statusIconButton.layer.cornerRadius = 17;
|
|
1085
1742
|
self.statusIconButton.layer.masksToBounds = YES;
|
|
1743
|
+
self.statusIconButton.toolTip = @"查看最近 Agent 会话与 CC Bridge 消息";
|
|
1744
|
+
self.statusIconButton.target = self;
|
|
1745
|
+
self.statusIconButton.action = @selector(showAgentSessionsMenu:);
|
|
1086
1746
|
[self.statusGlass addSubview:self.statusIconButton];
|
|
1087
1747
|
[statusRoot addSubview:self.statusGlass];
|
|
1748
|
+
CCPetsStatusClickButton *statusClick = [[CCPetsStatusClickButton alloc]
|
|
1749
|
+
initWithFrame:NSMakeRect(6, 6, statusGlassSize.width - 56, statusGlassSize.height)];
|
|
1750
|
+
statusClick.bordered = NO;
|
|
1751
|
+
statusClick.transparent = YES;
|
|
1752
|
+
statusClick.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
|
|
1753
|
+
statusClick.title = @"";
|
|
1754
|
+
statusClick.toolTip = @"返回触发此状态的 Agent 终端";
|
|
1755
|
+
statusClick.target = self;
|
|
1756
|
+
statusClick.action = @selector(focusLatestAgentTerminal:);
|
|
1757
|
+
self.statusClickButton = statusClick;
|
|
1758
|
+
[statusRoot addSubview:statusClick];
|
|
1759
|
+
// 角标挂在 statusRoot 而不是 statusGlass 里:玻璃卡片是 masksToBounds 的胶囊,
|
|
1760
|
+
// 右上角正好落在圆角外面,放进去会被裁掉一半。
|
|
1761
|
+
CCPetsApprovalBadgeView *badge = [[CCPetsApprovalBadgeView alloc]
|
|
1762
|
+
initWithFrame:NSMakeRect(0, 0, PetApprovalBadgeSize, PetApprovalBadgeSize)];
|
|
1763
|
+
badge.hidden = YES;
|
|
1764
|
+
self.approvalBadgeView = badge;
|
|
1765
|
+
[statusRoot addSubview:badge];
|
|
1766
|
+
// CC Bridge 消息角标压在图标右下角,与右上角的审批角标错开。点击同样穿透到图标,
|
|
1767
|
+
// 打开的会话菜单里列出最近的跨会话消息。
|
|
1768
|
+
CCPetsApprovalBadgeView *bridgeBadge = [[CCPetsApprovalBadgeView alloc]
|
|
1769
|
+
initWithFrame:NSMakeRect(0, 0, PetApprovalBadgeSize, PetApprovalBadgeSize)];
|
|
1770
|
+
bridgeBadge.hidden = YES;
|
|
1771
|
+
bridgeBadge.fillColor = [NSColor colorWithRed:0.20 green:0.47 blue:0.90 alpha:1];
|
|
1772
|
+
self.bridgeBadgeView = bridgeBadge;
|
|
1773
|
+
[statusRoot addSubview:bridgeBadge];
|
|
1774
|
+
[self layoutApprovalBadge];
|
|
1088
1775
|
self.statusPanel.contentView = statusRoot;
|
|
1089
1776
|
|
|
1090
1777
|
NSSize quotaSize = NSMakeSize(QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale);
|
|
@@ -1135,6 +1822,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1135
1822
|
self.systemMonitor = [CCPetsSystemMonitor new];
|
|
1136
1823
|
self.agentEventPartialLine = [NSMutableData data];
|
|
1137
1824
|
self.pendingApprovalRecords = [NSMutableDictionary dictionary];
|
|
1825
|
+
self.stallNotifiedSessionKeys = [NSMutableSet set];
|
|
1138
1826
|
self.usageMonitor.changeHandler = ^(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
|
|
1139
1827
|
[weakSelf applyCodexUsage:codexUsage claudeUsage:claudeUsage];
|
|
1140
1828
|
[weakSelf considerQuotaSpeech];
|
|
@@ -1153,6 +1841,13 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1153
1841
|
NSTimer *readerTimer = [NSTimer scheduledTimerWithTimeInterval:AgentEventReaderCheckInterval
|
|
1154
1842
|
target:self selector:@selector(ensureAgentEventReader:) userInfo:nil repeats:YES];
|
|
1155
1843
|
readerTimer.tolerance = AgentEventReaderCheckInterval * 0.3;
|
|
1844
|
+
// 启动前的消息不算"未读":角标只提示桌宠运行期间新发生的跨会话往来。通知同理。
|
|
1845
|
+
self.bridgeSeenAt = NSDate.date.timeIntervalSince1970;
|
|
1846
|
+
self.bridgeNotifiedAt = self.bridgeSeenAt;
|
|
1847
|
+
[self refreshBridgeState:nil];
|
|
1848
|
+
NSTimer *bridgeTimer = [NSTimer scheduledTimerWithTimeInterval:BridgeRefreshInterval
|
|
1849
|
+
target:self selector:@selector(refreshBridgeState:) userInfo:nil repeats:YES];
|
|
1850
|
+
bridgeTimer.tolerance = BridgeRefreshInterval * 0.3;
|
|
1156
1851
|
// 这里刻意不使用 occlusionState / NSWindowDidChangeOcclusionStateNotification:
|
|
1157
1852
|
// 桌宠是置顶的(NSFloatingWindowLevel + FullScreenAuxiliary),全屏应用也压不住它,
|
|
1158
1853
|
// 所以“被遮挡”几乎不会真实发生,收益接近零;而实测中 occlusionState 会在
|
|
@@ -1699,6 +2394,7 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
|
1699
2394
|
}
|
|
1700
2395
|
self.statusIconButton.frame = NSMakeRect(glassWidth - trailing - iconWidth,
|
|
1701
2396
|
(height - iconWidth) / 2.0, iconWidth, iconWidth);
|
|
2397
|
+
self.statusClickButton.frame = NSMakeRect(6, 6, glassWidth - 56, height);
|
|
1702
2398
|
}
|
|
1703
2399
|
|
|
1704
2400
|
// 独立气泡:左右各 16 内边距,没有图标。
|
|
@@ -1842,6 +2538,7 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
|
1842
2538
|
NSDictionary *record = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
1843
2539
|
if (![record isKindOfClass:NSDictionary.class]) continue;
|
|
1844
2540
|
if (recentOnly && [record[@"timestamp"] doubleValue] < cutoff) continue;
|
|
2541
|
+
[self trackAgentSessionRecord:record];
|
|
1845
2542
|
NSString *event = record[@"event"];
|
|
1846
2543
|
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
1847
2544
|
if ([event isKindOfClass:NSString.class]) {
|
|
@@ -1850,7 +2547,6 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
|
1850
2547
|
}
|
|
1851
2548
|
[self prunePendingApprovalRecords];
|
|
1852
2549
|
NSString *approvalKey = [self approvalKeyForRecord:record];
|
|
1853
|
-
NSDictionary *previousPriority = [self latestPendingApprovalRecord];
|
|
1854
2550
|
BOOL manualApproval = [state isEqualToString:@"approval"];
|
|
1855
2551
|
if (manualApproval) {
|
|
1856
2552
|
self.pendingApprovalRecords[approvalKey] = record;
|
|
@@ -1858,18 +2554,12 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
|
1858
2554
|
[self.pendingApprovalRecords removeObjectForKey:approvalKey];
|
|
1859
2555
|
}
|
|
1860
2556
|
[self prunePendingApprovalRecords];
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
if (manualApproval) {
|
|
1864
|
-
[self displayAgentRecord:currentPriority notify:YES];
|
|
1865
|
-
} else if (currentPriority != previousPriority) {
|
|
1866
|
-
[self displayAgentRecord:currentPriority notify:NO];
|
|
1867
|
-
}
|
|
1868
|
-
continue;
|
|
1869
|
-
}
|
|
2557
|
+
// 多会话下不能让一个未处理的审批全局挡住其他 Agent 的所有 Hook。每条事件
|
|
2558
|
+
// 都正常驱动气泡和动画;仍在等待的审批保留在多会话记录中供用户回跳。
|
|
1870
2559
|
[self displayAgentRecord:record notify:YES];
|
|
1871
2560
|
}
|
|
1872
2561
|
}
|
|
2562
|
+
[self refreshApprovalBadge];
|
|
1873
2563
|
}
|
|
1874
2564
|
- (void)readNewAgentEvents {
|
|
1875
2565
|
NSString *path = AgentEventPath();
|
|
@@ -1945,6 +2635,26 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
|
1945
2635
|
self.quotaView.hasUnlabeledClient = self.hasUnlabeledClient;
|
|
1946
2636
|
self.quotaView.needsDisplay = YES;
|
|
1947
2637
|
}
|
|
2638
|
+
// 客户端是否真的还在跑。只问 kill(pid, 0) 不够:关掉终端窗口只是销毁 pty,claude /
|
|
2639
|
+
// codex(Node 进程)不一定跟着 SIGHUP 退出,会变成脱离控制终端的孤儿继续活着。那样
|
|
2640
|
+
// pid 一直存在,会话就永久挂在"在线"上,最近会话列表里那条也永远不消失。
|
|
2641
|
+
// 所以再看两件事:进程是否还有控制终端;以及它是不是仍然是 pid 文件里记的那个 TTY
|
|
2642
|
+
// (pty 会被新开的窗口复用,光看"有 tty"挡不住换了主人的情况)。
|
|
2643
|
+
// recordedTTY 为空是 1.0.2 及更早的老客户端,只能退回"有控制终端"这一条。
|
|
2644
|
+
static BOOL ClientProcessAlive(pid_t pid, NSString *recordedTTY) {
|
|
2645
|
+
if (pid <= 1) return NO;
|
|
2646
|
+
struct kinfo_proc info;
|
|
2647
|
+
size_t length = sizeof(info);
|
|
2648
|
+
int name[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
|
|
2649
|
+
if (sysctl(name, 4, &info, &length, NULL, 0) != 0 || length == 0) return NO;
|
|
2650
|
+
if (info.kp_proc.p_stat == SZOMB) return NO;
|
|
2651
|
+
dev_t device = info.kp_eproc.e_tdev;
|
|
2652
|
+
if (device == NODEV) return NO;
|
|
2653
|
+
if (recordedTTY.length == 0) return YES;
|
|
2654
|
+
const char *current = devname(device, S_IFCHR);
|
|
2655
|
+
if (!current) return NO;
|
|
2656
|
+
return [recordedTTY isEqualToString:@(current).lastPathComponent];
|
|
2657
|
+
}
|
|
1948
2658
|
- (void)refreshClientLifecycle:(id)sender {
|
|
1949
2659
|
[self considerIdleSpeech];
|
|
1950
2660
|
[self prunePendingApprovalRecords];
|
|
@@ -1953,23 +2663,31 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
|
1953
2663
|
NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
|
|
1954
2664
|
NSInteger liveClients = 0;
|
|
1955
2665
|
NSMutableSet<NSString *> *providers = [NSMutableSet set];
|
|
2666
|
+
NSMutableSet<NSString *> *sessionKeys = [NSMutableSet set];
|
|
1956
2667
|
BOOL unlabeled = NO;
|
|
1957
2668
|
for (NSString *entry in entries) {
|
|
1958
2669
|
pid_t pid = (pid_t)entry.intValue;
|
|
1959
|
-
BOOL alive = pid > 1 && (kill(pid, 0) == 0 || errno == EPERM);
|
|
1960
2670
|
NSString *path = [clientDirectory stringByAppendingPathComponent:entry];
|
|
1961
|
-
|
|
2671
|
+
// 包装脚本会把 provider 名写进 pid 文件第一行、TTY 写进第二行。1.0.2 及更早
|
|
2672
|
+
// 的版本只 touch 出空文件,升级后仍在运行的老客户端读出来是空的:这类当作
|
|
2673
|
+
// “身份不明”,只要还有一个就不清场,避免把仍然活着的会话误判成已退出。
|
|
2674
|
+
NSString *contents = [NSString stringWithContentsOfFile:path
|
|
2675
|
+
encoding:NSUTF8StringEncoding error:nil] ?: @"";
|
|
2676
|
+
NSArray<NSString *> *lines = [contents componentsSeparatedByCharactersInSet:
|
|
2677
|
+
NSCharacterSet.newlineCharacterSet];
|
|
2678
|
+
NSString *label = [lines.firstObject
|
|
2679
|
+
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
|
2680
|
+
NSString *tty = lines.count > 1 ? [lines[1]
|
|
2681
|
+
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] : @"";
|
|
2682
|
+
if (!ClientProcessAlive(pid, tty)) {
|
|
1962
2683
|
[NSFileManager.defaultManager removeItemAtPath:path error:nil];
|
|
1963
2684
|
continue;
|
|
1964
2685
|
}
|
|
1965
2686
|
liveClients += 1;
|
|
1966
|
-
// 包装脚本会把 provider 名写进 pid 文件。1.0.2 及更早的版本只 touch 出
|
|
1967
|
-
// 空文件,升级后仍在运行的老客户端读出来是空的:这类当作“身份不明”,
|
|
1968
|
-
// 只要还有一个就不清场,避免把仍然活着的会话误判成已退出。
|
|
1969
|
-
NSString *label = [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]
|
|
1970
|
-
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
|
1971
2687
|
if (label.length > 0 && label.length <= 32) [providers addObject:label];
|
|
1972
2688
|
else unlabeled = YES;
|
|
2689
|
+
NSString *sessionKey = [self onlineAgentSessionKeyForProvider:label tty:tty];
|
|
2690
|
+
if (sessionKey.length > 0) [sessionKeys addObject:sessionKey];
|
|
1973
2691
|
}
|
|
1974
2692
|
// 包装脚本启动的客户端有精确的退出信号:pid 文件被回收。这一段不该被为"直接跑
|
|
1975
2693
|
// claude / codex"准备的 60 秒活跃度宽限盖住,否则退出后还要挂满一分钟才转离线。
|
|
@@ -1978,7 +2696,9 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
|
1978
2696
|
NSSet<NSString *> *previousProviders = self.liveClientProviders;
|
|
1979
2697
|
self.liveClientCount = liveClients;
|
|
1980
2698
|
self.liveClientProviders = providers;
|
|
2699
|
+
self.liveAgentSessionKeys = sessionKeys;
|
|
1981
2700
|
self.hasUnlabeledClient = unlabeled;
|
|
2701
|
+
[self pruneOfflineAgentSessionRecords];
|
|
1982
2702
|
for (NSString *provider in previousProviders) {
|
|
1983
2703
|
if (![providers containsObject:provider]) {
|
|
1984
2704
|
[self.providerActivityAt removeObjectForKey:provider];
|
|
@@ -1987,6 +2707,8 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
|
1987
2707
|
[self updateQuotaLiveState];
|
|
1988
2708
|
[self refreshDetectedProviders];
|
|
1989
2709
|
[self hideAgentStatusIfClientGone];
|
|
2710
|
+
[self checkStalledAgentSessions];
|
|
2711
|
+
[self refreshApprovalBadge];
|
|
1990
2712
|
// 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
|
|
1991
2713
|
// Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
|
|
1992
2714
|
if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
|