cc-pets 2.1.0 → 2.1.2
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 +11 -6
- package/CC_BRIDGE.zh-CN.md +8 -4
- package/CHANGELOG.md +59 -1
- package/CHANGELOG.zh-CN.md +59 -1
- package/README.md +60 -12
- package/README.zh-CN.md +58 -13
- package/Sources/CCPets/CCPetsAppDelegate+AgentEvents.m +215 -0
- package/Sources/CCPets/CCPetsAppDelegate+AgentStatus.m +660 -0
- package/Sources/CCPets/CCPetsAppDelegate+Bridge.m +297 -0
- package/Sources/CCPets/CCPetsAppDelegate+Pets.m +187 -0
- package/Sources/CCPets/CCPetsAppDelegate+Private.h +322 -0
- package/Sources/CCPets/CCPetsAppDelegate+Quota.m +216 -0
- package/Sources/CCPets/CCPetsAppDelegate+Settings.m +205 -0
- package/Sources/CCPets/CCPetsAppDelegate+Speech.m +392 -0
- package/Sources/CCPets/CCPetsAppDelegate+Update.m +458 -0
- package/Sources/CCPets/CCPetsAppDelegate.h +17 -16
- package/Sources/CCPets/CCPetsAppDelegate.m +74 -2406
- package/Sources/CCPets/CCPetsCleanup.h +4 -0
- package/Sources/CCPets/CCPetsCleanup.m +35 -2
- package/Sources/CCPets/CCPetsCodexRateLimits.h +1 -0
- package/Sources/CCPets/CCPetsCodexRateLimits.m +7 -0
- package/Sources/CCPets/CCPetsEvents.m +1 -1
- package/Sources/CCPets/CCPetsGlassMenu.h +10 -0
- package/Sources/CCPets/CCPetsGlassMenu.m +196 -0
- package/Sources/CCPets/CCPetsGlassView.h +31 -0
- package/Sources/CCPets/CCPetsGlassView.m +246 -0
- package/Sources/CCPets/CCPetsPaths.h +7 -1
- package/Sources/CCPets/CCPetsPaths.m +14 -1
- package/Sources/CCPets/CCPetsTerminalFocus.h +15 -0
- package/Sources/CCPets/CCPetsTerminalFocus.m +306 -15
- package/Sources/CCPets/CCPetsUsage.h +2 -1
- package/Sources/CCPets/CCPetsUsage.m +69 -21
- package/Sources/CCPets/CCPetsUsageMonitor.m +43 -8
- package/Sources/CCPets/CCPetsVersion.h +7 -0
- package/Sources/CCPets/CCPetsVersion.m +82 -0
- package/Sources/CCPets/MenuChoiceRow.h +19 -0
- package/Sources/CCPets/MenuChoiceRow.m +96 -0
- package/Sources/CCPets/MenuHintView.h +15 -0
- package/Sources/CCPets/MenuHintView.m +128 -0
- package/Sources/CCPets/PetView.h +2 -0
- package/Sources/CCPets/PetView.m +121 -53
- package/Sources/CCPets/QuotaDashboardView.h +3 -4
- package/Sources/CCPets/QuotaDashboardView.m +222 -146
- package/Sources/CCPets/main.m +29 -0
- package/bin/cc-pets +39 -1
- package/bin/codex-with-pet +2 -0
- package/package.json +3 -2
- package/scripts/bridge/cli.mjs +9 -2
- package/scripts/bridge/core.mjs +1 -1
- package/scripts/bridge/install.mjs +23 -1
- package/scripts/bridge/process.mjs +22 -0
- package/scripts/doctor.mjs +456 -0
- package/scripts/install-claude-hooks.mjs +12 -18
- package/scripts/install-codex-hooks.mjs +3 -9
- package/scripts/integration-markers.mjs +51 -0
- package/scripts/pet-store.mjs +2 -1
- package/scripts/uninstall-integrations.mjs +16 -44
- package/scripts/uninstall-shell-integration.sh +3 -3
|
@@ -1,39 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
#import "
|
|
4
|
-
#import "CCPetsEvents.h"
|
|
5
|
-
#import "CCPetsQuotaHistory.h"
|
|
6
|
-
#import "CCPetsImageLoader.h"
|
|
7
|
-
#import "CCPetsPhrases.h"
|
|
8
|
-
#import "CCPetsPhrasesEditor.h"
|
|
9
|
-
#import "CCPetsUsage.h"
|
|
10
|
-
#import "CCPetsTerminalFocus.h"
|
|
11
|
-
#import "CCPetsBridge.h"
|
|
12
|
-
#import "MenuToggleSwitch.h"
|
|
13
|
-
#import <UserNotifications/UserNotifications.h>
|
|
14
|
-
#import <signal.h>
|
|
15
|
-
#import <sys/stat.h>
|
|
16
|
-
#import <fcntl.h>
|
|
17
|
-
#import <unistd.h>
|
|
18
|
-
#import <errno.h>
|
|
19
|
-
#import <sys/sysctl.h>
|
|
20
|
-
#import <stdlib.h>
|
|
21
|
-
|
|
22
|
-
static const NSTimeInterval PendingApprovalTTL = 24 * 60 * 60;
|
|
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;
|
|
31
|
-
static const unsigned long long UpdateLogSizeLimit = 1024 * 1024;
|
|
32
|
-
static NSString *const PetInteractionPhrasesV1MigratedKey =
|
|
33
|
-
@"CCPetsInteractionPhrasesV1Migrated";
|
|
34
|
-
|
|
35
|
-
@interface CCPetsStatusClickButton : NSButton
|
|
36
|
-
@end
|
|
1
|
+
// AppDelegate 主干:启动、退出、窗口跟随。各功能模块在 CCPetsAppDelegate+<模块>.m 里,
|
|
2
|
+
// 共享常量和跨文件的方法声明见 CCPetsAppDelegate+Private.h。
|
|
3
|
+
#import "CCPetsAppDelegate+Private.h"
|
|
37
4
|
|
|
38
5
|
@implementation CCPetsStatusClickButton
|
|
39
6
|
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
|
|
@@ -43,15 +10,6 @@ static NSString *const PetInteractionPhrasesV1MigratedKey =
|
|
|
43
10
|
}
|
|
44
11
|
@end
|
|
45
12
|
|
|
46
|
-
// 待审批角标。等审批的会话按定义是停住不动的,它的时间戳只会越来越旧——状态卡
|
|
47
|
-
// 正文永远显示最新事件,会话列表又按时间倒序,两边都会把最该处理的那条推到看
|
|
48
|
-
// 不见的地方。角标把这个数字单独拎出来常驻。
|
|
49
|
-
@interface CCPetsApprovalBadgeView : NSView
|
|
50
|
-
@property(nonatomic) NSUInteger count;
|
|
51
|
-
// 默认审批红;CC Bridge 消息角标复用同一个视图,换成蓝色 / 橙色。
|
|
52
|
-
@property(nonatomic) NSColor *fillColor;
|
|
53
|
-
@end
|
|
54
|
-
|
|
55
13
|
@implementation CCPetsApprovalBadgeView
|
|
56
14
|
- (void)setCount:(NSUInteger)count {
|
|
57
15
|
if (_count == count) return;
|
|
@@ -89,50 +47,13 @@ static NSString *const PetInteractionPhrasesV1MigratedKey =
|
|
|
89
47
|
}
|
|
90
48
|
@end
|
|
91
49
|
|
|
92
|
-
static void TrimUpdateLog(NSString *path) {
|
|
93
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
|
|
94
|
-
if (!handle) return;
|
|
95
|
-
unsigned long long size = [handle seekToEndOfFile];
|
|
96
|
-
if (size <= UpdateLogSizeLimit) {
|
|
97
|
-
[handle closeFile];
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
[handle seekToFileOffset:size - UpdateLogSizeLimit];
|
|
101
|
-
NSData *tail = [handle readDataToEndOfFile];
|
|
102
|
-
[handle closeFile];
|
|
103
|
-
[tail writeToFile:path options:NSDataWritingAtomic error:nil];
|
|
104
|
-
chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// 碎碎念的话痨程度。四道闸(每小时预算 / 两句间隔 / 静默门槛 / 出话概率)本来是
|
|
108
|
-
// 四个互相牵制的常数,单独调任何一个都不会真的变频繁——比如把冷却调到 0,
|
|
109
|
-
// 每小时 4 句的预算照样卡死。所以对用户只暴露一个档位,四个值一起走。
|
|
110
|
-
//
|
|
111
|
-
// normal 档就是改造前的原值,默认不变。
|
|
112
|
-
typedef struct {
|
|
113
|
-
NSInteger hourlyBudget;
|
|
114
|
-
NSTimeInterval cooldown;
|
|
115
|
-
NSTimeInterval quietSeconds; // 距上一次 agent 事件多久才算"没人打扰"
|
|
116
|
-
uint32_t idleChancePercent; // 每次判定(≤30 秒一次)的出话概率
|
|
117
|
-
} PetSpeechRate;
|
|
118
|
-
|
|
119
|
-
static const PetSpeechRate PetSpeechRateLow = {2, 480.0, 300.0, 15};
|
|
120
|
-
static const PetSpeechRate PetSpeechRateNormal = {4, 240.0, 180.0, 25};
|
|
121
|
-
static const PetSpeechRate PetSpeechRateHigh = {8, 120.0, 90.0, 45};
|
|
122
|
-
static const PetSpeechRate PetSpeechRateChatty = {20, 45.0, 45.0, 70};
|
|
123
|
-
|
|
124
|
-
// 档位写进 defaults 的值。字符串而不是整数:以后加档、调顺序都不会让老配置错位。
|
|
125
|
-
NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
|
|
126
|
-
static NSString *const PetSpeechFrequencyLow = @"low";
|
|
127
|
-
static NSString *const PetSpeechFrequencyNormal = @"normal";
|
|
128
|
-
static NSString *const PetSpeechFrequencyHigh = @"high";
|
|
129
|
-
static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
130
|
-
|
|
131
50
|
@implementation AppDelegate
|
|
132
51
|
- (NSString *)applicationSupportDirectory {
|
|
133
52
|
return ApplicationSupportDirectory();
|
|
134
53
|
}
|
|
135
|
-
|
|
54
|
+
// 只有一个「好」按钮的提示框,各模块报错 / 告知结果都用它。桌宠是 LSUIElement,
|
|
55
|
+
// 不先激活的话弹窗会开在其他 App 后面。
|
|
56
|
+
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
|
|
136
57
|
[NSApp activateIgnoringOtherApps:YES];
|
|
137
58
|
NSAlert *alert = [NSAlert new];
|
|
138
59
|
alert.messageText = title;
|
|
@@ -140,1381 +61,6 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
140
61
|
[alert addButtonWithTitle:@"好"];
|
|
141
62
|
[alert runModal];
|
|
142
63
|
}
|
|
143
|
-
- (NSDictionary *)updaterConfiguration {
|
|
144
|
-
NSString *path = [[self applicationSupportDirectory] stringByAppendingPathComponent:@"updater.json"];
|
|
145
|
-
NSData *data = [NSData dataWithContentsOfFile:path];
|
|
146
|
-
NSDictionary *configuration = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
147
|
-
return [configuration isKindOfClass:NSDictionary.class] ? configuration : nil;
|
|
148
|
-
}
|
|
149
|
-
- (BOOL)restartAfterUpdateToVersion:(NSString *)version configuration:(NSDictionary *)configuration {
|
|
150
|
-
NSString *appPath = [configuration[@"appPath"] isKindOfClass:NSString.class]
|
|
151
|
-
? [configuration[@"appPath"] stringByStandardizingPath] : nil;
|
|
152
|
-
if (appPath.length == 0 &&
|
|
153
|
-
[NSBundle.mainBundle.bundlePath.pathExtension.lowercaseString isEqualToString:@"app"]) {
|
|
154
|
-
appPath = NSBundle.mainBundle.bundlePath.stringByStandardizingPath;
|
|
155
|
-
}
|
|
156
|
-
if (appPath.length == 0) {
|
|
157
|
-
appPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Applications"]
|
|
158
|
-
stringByAppendingPathComponent:@"CC Pets.app"];
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
NSString *infoPath = [appPath stringByAppendingPathComponent:@"Contents/Info.plist"];
|
|
162
|
-
NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:infoPath];
|
|
163
|
-
NSString *installedVersion = [info[@"CFBundleShortVersionString"] isKindOfClass:NSString.class]
|
|
164
|
-
? info[@"CFBundleShortVersionString"] : nil;
|
|
165
|
-
NSString *executablePath = [appPath stringByAppendingPathComponent:@"Contents/MacOS/cc-pets"];
|
|
166
|
-
if (![installedVersion isEqualToString:version] ||
|
|
167
|
-
![NSFileManager.defaultManager isExecutableFileAtPath:executablePath]) return NO;
|
|
168
|
-
|
|
169
|
-
NSTask *restartTask = [NSTask new];
|
|
170
|
-
restartTask.executableURL = [NSURL fileURLWithPath:executablePath];
|
|
171
|
-
restartTask.arguments = @[
|
|
172
|
-
@"--restart-after-pid",
|
|
173
|
-
[NSString stringWithFormat:@"%d", NSProcessInfo.processInfo.processIdentifier],
|
|
174
|
-
appPath,
|
|
175
|
-
self.managedByCLI ? @"--managed" : @"--standalone"
|
|
176
|
-
];
|
|
177
|
-
NSError *error = nil;
|
|
178
|
-
if (![restartTask launchAndReturnError:&error]) return NO;
|
|
179
|
-
[NSApp terminate:nil];
|
|
180
|
-
return YES;
|
|
181
|
-
}
|
|
182
|
-
- (void)startUpdateToVersion:(NSString *)version {
|
|
183
|
-
if (self.updating) return;
|
|
184
|
-
[self startUpdateToVersion:version attempt:0];
|
|
185
|
-
}
|
|
186
|
-
- (void)retryUpdate:(NSArray *)context {
|
|
187
|
-
self.updating = NO;
|
|
188
|
-
[self startUpdateToVersion:context[0] attempt:[context[1] integerValue]];
|
|
189
|
-
}
|
|
190
|
-
- (void)startUpdateToVersion:(NSString *)version attempt:(NSInteger)attempt {
|
|
191
|
-
NSDictionary *configuration = [self updaterConfiguration];
|
|
192
|
-
NSString *nodePath = [configuration[@"nodePath"] isKindOfClass:NSString.class]
|
|
193
|
-
? [configuration[@"nodePath"] stringByStandardizingPath] : nil;
|
|
194
|
-
NSString *npmCliPath = [configuration[@"npmCliPath"] isKindOfClass:NSString.class]
|
|
195
|
-
? [configuration[@"npmCliPath"] stringByStandardizingPath] : nil;
|
|
196
|
-
BOOL nodeExecutable = nodePath.isAbsolutePath &&
|
|
197
|
-
[NSFileManager.defaultManager isExecutableFileAtPath:nodePath];
|
|
198
|
-
BOOL npmCliExists = npmCliPath.isAbsolutePath &&
|
|
199
|
-
[NSFileManager.defaultManager isReadableFileAtPath:npmCliPath];
|
|
200
|
-
if (!nodeExecutable || !npmCliExists) {
|
|
201
|
-
[self showUpdateAlertWithTitle:@"无法自动更新"
|
|
202
|
-
message:@"没有找到安装 CC Pets 时使用的 Node.js/npm。请先手动执行一次:\n\n"
|
|
203
|
-
"npm install -g cc-pets@latest --allow-scripts=cc-pets"];
|
|
204
|
-
return;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
NSString *supportDirectory = [self applicationSupportDirectory];
|
|
208
|
-
NSError *directoryError = nil;
|
|
209
|
-
[NSFileManager.defaultManager createDirectoryAtPath:supportDirectory
|
|
210
|
-
withIntermediateDirectories:YES attributes:nil error:&directoryError];
|
|
211
|
-
if (directoryError) {
|
|
212
|
-
[self showUpdateAlertWithTitle:@"无法自动更新" message:directoryError.localizedDescription];
|
|
213
|
-
return;
|
|
214
|
-
}
|
|
215
|
-
NSString *logPath = [supportDirectory stringByAppendingPathComponent:@"update.log"];
|
|
216
|
-
[NSData.data writeToFile:logPath options:NSDataWritingAtomic error:nil];
|
|
217
|
-
chmod(logPath.fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
218
|
-
NSFileHandle *logHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
|
|
219
|
-
if (!logHandle) {
|
|
220
|
-
[self showUpdateAlertWithTitle:@"无法自动更新" message:@"无法创建更新日志。"];
|
|
221
|
-
return;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
NSTask *task = [NSTask new];
|
|
225
|
-
task.executableURL = [NSURL fileURLWithPath:nodePath];
|
|
226
|
-
NSMutableArray<NSString *> *arguments = [@[
|
|
227
|
-
npmCliPath,
|
|
228
|
-
@"install",
|
|
229
|
-
@"--global",
|
|
230
|
-
[@"cc-pets@" stringByAppendingString:version],
|
|
231
|
-
@"--allow-scripts=cc-pets",
|
|
232
|
-
@"--prefer-online"
|
|
233
|
-
] mutableCopy];
|
|
234
|
-
if (attempt > 0) {
|
|
235
|
-
// 重试走一个一次性缓存目录:ETARGET 的成因就是本机缓存里的包元数据还没有这个
|
|
236
|
-
// 版本,--prefer-online 只是允许重新校验,命中 304 时依然拿到旧元数据。
|
|
237
|
-
// 换缓存目录能强制冷取,又不动用户真正的 npm 缓存。
|
|
238
|
-
[arguments addObjectsFromArray:@[@"--cache",
|
|
239
|
-
[supportDirectory stringByAppendingPathComponent:@"update-retry-cache"]]];
|
|
240
|
-
}
|
|
241
|
-
task.arguments = arguments;
|
|
242
|
-
NSMutableDictionary<NSString *, NSString *> *environment =
|
|
243
|
-
[NSProcessInfo.processInfo.environment mutableCopy];
|
|
244
|
-
NSString *nodeDirectory = nodePath.stringByDeletingLastPathComponent;
|
|
245
|
-
NSString *existingPath = environment[@"PATH"];
|
|
246
|
-
if (existingPath.length == 0) existingPath = @"/usr/bin:/bin:/usr/sbin:/sbin";
|
|
247
|
-
environment[@"PATH"] = [NSString stringWithFormat:@"%@:%@", nodeDirectory, existingPath];
|
|
248
|
-
task.environment = environment;
|
|
249
|
-
task.currentDirectoryURL = [NSURL fileURLWithPath:NSHomeDirectory()];
|
|
250
|
-
task.standardOutput = logHandle;
|
|
251
|
-
task.standardError = logHandle;
|
|
252
|
-
self.updating = YES;
|
|
253
|
-
self.updateTask = task;
|
|
254
|
-
__weak typeof(self) weakSelf = self;
|
|
255
|
-
task.terminationHandler = ^(NSTask *finishedTask) {
|
|
256
|
-
[logHandle closeFile];
|
|
257
|
-
TrimUpdateLog(logPath);
|
|
258
|
-
dispatch_async(dispatch_get_main_queue(), ^{
|
|
259
|
-
typeof(self) strongSelf = weakSelf;
|
|
260
|
-
if (!strongSelf) return;
|
|
261
|
-
strongSelf.updateTask = nil;
|
|
262
|
-
if (finishedTask.terminationStatus == EXIT_SUCCESS) {
|
|
263
|
-
strongSelf.updating = NO;
|
|
264
|
-
if ([strongSelf restartAfterUpdateToVersion:version configuration:configuration]) return;
|
|
265
|
-
[strongSelf showUpdateAlertWithTitle:@"更新完成"
|
|
266
|
-
message:@"CC Pets 已更新,但没有找到可自动启动的新版应用,请手动重新启动一次。"];
|
|
267
|
-
return;
|
|
268
|
-
}
|
|
269
|
-
// 暂时性故障(典型是刚发布的版本报 ETARGET)自动重试一次再说,
|
|
270
|
-
// 别把一个重试就能过的问题弹成"更新失败"。updating 保持为 YES,
|
|
271
|
-
// 等待期间不接受新的更新请求。
|
|
272
|
-
NSString *log = [NSString stringWithContentsOfFile:logPath
|
|
273
|
-
encoding:NSUTF8StringEncoding error:nil];
|
|
274
|
-
if (attempt == 0 && UpdateFailureIsTransient(log)) {
|
|
275
|
-
[strongSelf performSelector:@selector(retryUpdate:)
|
|
276
|
-
withObject:@[version, @1] afterDelay:UpdateRetryDelay];
|
|
277
|
-
return;
|
|
278
|
-
}
|
|
279
|
-
strongSelf.updating = NO;
|
|
280
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
281
|
-
NSAlert *alert = [NSAlert new];
|
|
282
|
-
alert.messageText = @"更新失败";
|
|
283
|
-
alert.informativeText = [NSString stringWithFormat:
|
|
284
|
-
@"旧版本仍可继续使用。错误详情已写入:\n%@", logPath];
|
|
285
|
-
[alert addButtonWithTitle:@"打开日志"];
|
|
286
|
-
[alert addButtonWithTitle:@"关闭"];
|
|
287
|
-
if ([alert runModal] == NSAlertFirstButtonReturn) {
|
|
288
|
-
[NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:logPath]];
|
|
289
|
-
}
|
|
290
|
-
});
|
|
291
|
-
};
|
|
292
|
-
NSError *launchError = nil;
|
|
293
|
-
if (![task launchAndReturnError:&launchError]) {
|
|
294
|
-
self.updating = NO;
|
|
295
|
-
self.updateTask = nil;
|
|
296
|
-
[logHandle closeFile];
|
|
297
|
-
[self showUpdateAlertWithTitle:@"无法启动更新" message:launchError.localizedDescription];
|
|
298
|
-
return;
|
|
299
|
-
}
|
|
300
|
-
// 重试是静默的:第一次已经弹过"正在更新",再弹一次只会让人以为出了两回事。
|
|
301
|
-
if (attempt == 0) {
|
|
302
|
-
[self showUpdateAlertWithTitle:@"正在更新"
|
|
303
|
-
message:[NSString stringWithFormat:@"正在下载并安装 CC Pets %@。完成后桌宠会自动重启。", version]];
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
- (void)checkForUpdates:(id)sender {
|
|
307
|
-
if (self.checkingForUpdate || self.updating) return;
|
|
308
|
-
self.checkingForUpdate = YES;
|
|
309
|
-
NSURL *url = [NSURL URLWithString:@"https://registry.npmjs.org/cc-pets/latest"];
|
|
310
|
-
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
|
|
311
|
-
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
|
|
312
|
-
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
|
|
313
|
-
__weak typeof(self) weakSelf = self;
|
|
314
|
-
NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithRequest:request
|
|
315
|
-
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
|
|
316
|
-
dispatch_async(dispatch_get_main_queue(), ^{
|
|
317
|
-
typeof(self) strongSelf = weakSelf;
|
|
318
|
-
if (!strongSelf) return;
|
|
319
|
-
strongSelf.checkingForUpdate = NO;
|
|
320
|
-
NSHTTPURLResponse *httpResponse = [response isKindOfClass:NSHTTPURLResponse.class]
|
|
321
|
-
? (NSHTTPURLResponse *)response : nil;
|
|
322
|
-
NSDictionary *metadata = data
|
|
323
|
-
? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
324
|
-
NSString *latestVersion = [metadata[@"version"] isKindOfClass:NSString.class]
|
|
325
|
-
? metadata[@"version"] : nil;
|
|
326
|
-
BOOL valid = NO;
|
|
327
|
-
NSComparisonResult comparison = CompareStableVersions(@CC_PETS_VERSION, latestVersion, &valid);
|
|
328
|
-
if (error || httpResponse.statusCode != 200 || !valid) {
|
|
329
|
-
NSString *message = error.localizedDescription ?: @"npm Registry 返回了无效的版本信息,请稍后重试。";
|
|
330
|
-
[strongSelf showUpdateAlertWithTitle:@"检查更新失败" message:message];
|
|
331
|
-
return;
|
|
332
|
-
}
|
|
333
|
-
if (comparison != NSOrderedAscending) {
|
|
334
|
-
[strongSelf showUpdateAlertWithTitle:@"已是最新版本"
|
|
335
|
-
message:[NSString stringWithFormat:@"当前版本:%@", @CC_PETS_VERSION]];
|
|
336
|
-
return;
|
|
337
|
-
}
|
|
338
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
339
|
-
NSAlert *alert = [NSAlert new];
|
|
340
|
-
alert.messageText = @"发现新版本";
|
|
341
|
-
alert.informativeText = [NSString stringWithFormat:
|
|
342
|
-
@"当前版本:%@\n最新版本:%@\n\n是否立即更新?", @CC_PETS_VERSION, latestVersion];
|
|
343
|
-
[alert addButtonWithTitle:@"立即更新"];
|
|
344
|
-
[alert addButtonWithTitle:@"稍后"];
|
|
345
|
-
if ([alert runModal] == NSAlertFirstButtonReturn) {
|
|
346
|
-
[strongSelf startUpdateToVersion:latestVersion];
|
|
347
|
-
}
|
|
348
|
-
});
|
|
349
|
-
}];
|
|
350
|
-
[task resume];
|
|
351
|
-
}
|
|
352
|
-
- (NSString *)systemMetricKeyForTag:(NSInteger)tag {
|
|
353
|
-
if (tag == 1) return SystemCPUEnabledKey;
|
|
354
|
-
if (tag == 2) return SystemTemperatureEnabledKey;
|
|
355
|
-
if (tag == 3) return SystemMemoryEnabledKey;
|
|
356
|
-
return nil;
|
|
357
|
-
}
|
|
358
|
-
- (void)applySystemMetricPreferences {
|
|
359
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
360
|
-
self.quotaView.systemCPUEnabled = [defaults boolForKey:SystemCPUEnabledKey];
|
|
361
|
-
self.quotaView.systemTemperatureEnabled =
|
|
362
|
-
[defaults boolForKey:SystemTemperatureEnabledKey];
|
|
363
|
-
self.quotaView.systemMemoryEnabled = [defaults boolForKey:SystemMemoryEnabledKey];
|
|
364
|
-
self.quotaView.needsDisplay = YES;
|
|
365
|
-
}
|
|
366
|
-
- (void)applyUsageDisplayModePreferences {
|
|
367
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
368
|
-
self.quotaView.codexShowsAPIUsage =
|
|
369
|
-
[[defaults stringForKey:CodexUsageDisplayModeKey] isEqualToString:@"api"];
|
|
370
|
-
self.quotaView.claudeShowsAPIUsage =
|
|
371
|
-
[[defaults stringForKey:ClaudeUsageDisplayModeKey] isEqualToString:@"api"];
|
|
372
|
-
self.quotaView.needsDisplay = YES;
|
|
373
|
-
}
|
|
374
|
-
- (void)setUsageDisplayModeFromControl:(NSButton *)sender {
|
|
375
|
-
NSString *key = sender.tag == 1 ? CodexUsageDisplayModeKey
|
|
376
|
-
: (sender.tag == 2 ? ClaudeUsageDisplayModeKey : nil);
|
|
377
|
-
NSString *mode = sender.state == NSControlStateValueOn ? @"api" : @"subscription";
|
|
378
|
-
if (!key) return;
|
|
379
|
-
[NSUserDefaults.standardUserDefaults setObject:mode forKey:key];
|
|
380
|
-
[self applyUsageDisplayModePreferences];
|
|
381
|
-
// 展示模式决定了会话要回溯多远(订阅 8 天 / API 到上月月初),切换之后必须重新聚合,
|
|
382
|
-
// 否则刚打开 API 视图时手里只有一段按 8 天窗口扫出来的数据。
|
|
383
|
-
[self refreshUsage:nil];
|
|
384
|
-
}
|
|
385
|
-
- (void)toggleSystemMetric:(NSButton *)sender {
|
|
386
|
-
NSString *key = [self systemMetricKeyForTag:sender.tag];
|
|
387
|
-
if (!key) return;
|
|
388
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
389
|
-
BOOL enabled = ![defaults boolForKey:key];
|
|
390
|
-
[defaults setBool:enabled forKey:key];
|
|
391
|
-
sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
392
|
-
[self applySystemMetricPreferences];
|
|
393
|
-
[self updateSystemMetricsTimer];
|
|
394
|
-
}
|
|
395
|
-
// 开关打开时立刻导入一次,不用等下次启动——用户点开关就是想现在看到那些素材。
|
|
396
|
-
- (void)toggleImportCodexPets:(NSButton *)sender {
|
|
397
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
398
|
-
BOOL enabled = ![defaults boolForKey:ImportCodexPetsKey];
|
|
399
|
-
[defaults setBool:enabled forKey:ImportCodexPetsKey];
|
|
400
|
-
sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
401
|
-
if (!enabled) return;
|
|
402
|
-
NSUInteger imported = ImportCodexPets();
|
|
403
|
-
if (imported == 0) return;
|
|
404
|
-
[self invalidatePetOptionsCache];
|
|
405
|
-
[self showImportedCodexPetsAlert:imported];
|
|
406
|
-
}
|
|
407
|
-
- (void)showImportedCodexPetsAlert:(NSUInteger)imported {
|
|
408
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
409
|
-
NSAlert *alert = [NSAlert new];
|
|
410
|
-
alert.messageText = @"已导入 Codex 素材";
|
|
411
|
-
[alert addButtonWithTitle:@"好"];
|
|
412
|
-
[alert runModal];
|
|
413
|
-
}
|
|
414
|
-
- (NSString *)notificationKeyForTag:(NSInteger)tag {
|
|
415
|
-
if (tag == 1) return NotificationCompletionKey;
|
|
416
|
-
if (tag == 2) return NotificationFailureKey;
|
|
417
|
-
if (tag == 3) return NotificationApprovalKey;
|
|
418
|
-
if (tag == 4) return NotificationStallKey;
|
|
419
|
-
return nil;
|
|
420
|
-
}
|
|
421
|
-
- (void)toggleSpeech:(NSButton *)sender {
|
|
422
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
423
|
-
id current = [defaults objectForKey:@"CCPetsSpeechEnabled"];
|
|
424
|
-
BOOL enabled = current == nil ? YES : [current boolValue];
|
|
425
|
-
[defaults setBool:!enabled forKey:@"CCPetsSpeechEnabled"];
|
|
426
|
-
sender.state = !enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
427
|
-
if (enabled) [self hideSpeechBubble];
|
|
428
|
-
}
|
|
429
|
-
- (void)togglePetInteraction:(NSButton *)sender {
|
|
430
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
431
|
-
BOOL enabled = ![defaults boolForKey:PetInteractionEnabledKey];
|
|
432
|
-
[defaults setBool:enabled forKey:PetInteractionEnabledKey];
|
|
433
|
-
sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
434
|
-
}
|
|
435
|
-
- (void)setPetInteractionHeartThreshold:(NSMenuItem *)sender {
|
|
436
|
-
NSNumber *value = [sender.representedObject isKindOfClass:NSNumber.class] ?
|
|
437
|
-
sender.representedObject : @3;
|
|
438
|
-
[NSUserDefaults.standardUserDefaults setInteger:MAX((NSInteger)2, value.integerValue)
|
|
439
|
-
forKey:PetInteractionHeartThresholdKey];
|
|
440
|
-
}
|
|
441
|
-
- (void)setPetInteractionAnnoyedThreshold:(NSMenuItem *)sender {
|
|
442
|
-
NSNumber *value = [sender.representedObject isKindOfClass:NSNumber.class] ?
|
|
443
|
-
sender.representedObject : @10;
|
|
444
|
-
NSInteger heart = MAX((NSInteger)2, [NSUserDefaults.standardUserDefaults
|
|
445
|
-
integerForKey:PetInteractionHeartThresholdKey]);
|
|
446
|
-
[NSUserDefaults.standardUserDefaults setInteger:MAX(heart + 1, value.integerValue)
|
|
447
|
-
forKey:PetInteractionAnnoyedThresholdKey];
|
|
448
|
-
}
|
|
449
|
-
- (void)setPetInteractionInterval:(NSMenuItem *)sender {
|
|
450
|
-
NSNumber *value = [sender.representedObject isKindOfClass:NSNumber.class] ?
|
|
451
|
-
sender.representedObject : @1.2;
|
|
452
|
-
[NSUserDefaults.standardUserDefaults setDouble:MAX(0.4, MIN(3.0, value.doubleValue))
|
|
453
|
-
forKey:PetInteractionIntervalKey];
|
|
454
|
-
}
|
|
455
|
-
// 频率档位。改完立刻生效——四道闸都是现读的,不缓存。
|
|
456
|
-
// 顺手把冷却清掉,否则刚调高档位还要等完上一档的冷却才见效,会让人以为没生效。
|
|
457
|
-
- (void)setSpeechFrequency:(NSMenuItem *)sender {
|
|
458
|
-
NSString *value = [sender.representedObject isKindOfClass:NSString.class] ?
|
|
459
|
-
sender.representedObject : PetSpeechFrequencyNormal;
|
|
460
|
-
[NSUserDefaults.standardUserDefaults setObject:value forKey:PetSpeechFrequencyKey];
|
|
461
|
-
self.speechCooldownUntil = 0;
|
|
462
|
-
self.lastIdleSpeechCheck = 0;
|
|
463
|
-
}
|
|
464
|
-
// 台词交给内置编辑器,不再 openURL: 丢给"文本编辑"。
|
|
465
|
-
//
|
|
466
|
-
// 换掉的理由是反馈:系统编辑器保存完什么都不会说,小节名拼错、句子超 30 字、槽位
|
|
467
|
-
// 写错名字全是静默失效,用户只知道"改了没用"。内置编辑器保存时校验并当场报出来,
|
|
468
|
-
// 还能"试说一句"直接听效果。
|
|
469
|
-
- (void)editPhrasesFile:(id)sender {
|
|
470
|
-
// 编辑器只管文本,不认识气泡;把"说出来"这一步作为回调注入。
|
|
471
|
-
__weak typeof(self) weakSelf = self;
|
|
472
|
-
[PetPhrasesEditorController setSpeakHandler:^(NSString *text) {
|
|
473
|
-
[weakSelf presentSpeechText:text];
|
|
474
|
-
}];
|
|
475
|
-
[PetPhrasesEditorController present];
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
- (void)toggleNotification:(NSButton *)sender {
|
|
479
|
-
NSString *key = [self notificationKeyForTag:sender.tag];
|
|
480
|
-
if (!key) return;
|
|
481
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
482
|
-
if ([defaults boolForKey:key]) {
|
|
483
|
-
[defaults setBool:NO forKey:key];
|
|
484
|
-
sender.state = NSControlStateValueOff;
|
|
485
|
-
return;
|
|
486
|
-
}
|
|
487
|
-
[UNUserNotificationCenter.currentNotificationCenter
|
|
488
|
-
requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound
|
|
489
|
-
completionHandler:^(BOOL granted, NSError *error) {
|
|
490
|
-
dispatch_async(dispatch_get_main_queue(), ^{
|
|
491
|
-
if (granted) {
|
|
492
|
-
[defaults setBool:YES forKey:key];
|
|
493
|
-
sender.state = NSControlStateValueOn;
|
|
494
|
-
} else {
|
|
495
|
-
sender.state = NSControlStateValueOff;
|
|
496
|
-
NSString *message = error.localizedDescription ?:
|
|
497
|
-
@"请在“系统设置 → 通知 → CC Pets”中允许通知后重试。";
|
|
498
|
-
[self showUpdateAlertWithTitle:@"无法启用系统通知" message:message];
|
|
499
|
-
}
|
|
500
|
-
});
|
|
501
|
-
}];
|
|
502
|
-
}
|
|
503
|
-
- (void)sendNotificationWithTitle:(NSString *)title body:(NSString *)body {
|
|
504
|
-
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
|
|
505
|
-
content.title = title;
|
|
506
|
-
content.body = body;
|
|
507
|
-
content.sound = UNNotificationSound.defaultSound;
|
|
508
|
-
NSString *identifier = [@"cc-pets-" stringByAppendingString:NSUUID.UUID.UUIDString];
|
|
509
|
-
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
|
|
510
|
-
content:content trigger:nil];
|
|
511
|
-
[UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:request
|
|
512
|
-
withCompletionHandler:nil];
|
|
513
|
-
}
|
|
514
|
-
- (void)notifyForRecord:(NSDictionary *)record {
|
|
515
|
-
NSString *event = record[@"event"];
|
|
516
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
517
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
518
|
-
if (provider.length == 0) provider = @"Agent";
|
|
519
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
520
|
-
if ([event isEqualToString:@"PermissionRequest"] &&
|
|
521
|
-
![state isEqualToString:@"auto_review"] &&
|
|
522
|
-
[defaults boolForKey:NotificationApprovalKey]) {
|
|
523
|
-
[self sendNotificationWithTitle:@"等待审批"
|
|
524
|
-
body:[NSString stringWithFormat:@"%@ 正在等待操作。", provider]];
|
|
525
|
-
} else if ([event isEqualToString:@"StopFailure"] &&
|
|
526
|
-
[defaults boolForKey:NotificationFailureKey]) {
|
|
527
|
-
[self sendNotificationWithTitle:@"任务失败"
|
|
528
|
-
body:[NSString stringWithFormat:@"%@ 的任务执行失败。", provider]];
|
|
529
|
-
} else if (([event isEqualToString:@"Stop"] || [event isEqualToString:@"SessionEnd"]) &&
|
|
530
|
-
[defaults boolForKey:NotificationCompletionKey]) {
|
|
531
|
-
[self sendNotificationWithTitle:@"任务完成"
|
|
532
|
-
body:[NSString stringWithFormat:@"%@ 已完成当前任务。", provider]];
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
- (NSString *)statusTextForState:(NSString *)state tool:(NSString *)tool {
|
|
536
|
-
if ([state isEqualToString:@"starting"]) return @"正在启动";
|
|
537
|
-
if ([state isEqualToString:@"idle"]) return @"待机中";
|
|
538
|
-
if ([state isEqualToString:@"thinking"]) return @"正在思考";
|
|
539
|
-
if ([state isEqualToString:@"auto_review"]) return @"自动审批中";
|
|
540
|
-
if ([state isEqualToString:@"approval"]) return @"等待审批";
|
|
541
|
-
if ([state isEqualToString:@"subagent"]) return @"子 Agent 工作中";
|
|
542
|
-
if ([state isEqualToString:@"tool_completed"]) return @"操作已完成";
|
|
543
|
-
if ([state isEqualToString:@"tool_failed"]) return @"工具执行失败";
|
|
544
|
-
if ([state isEqualToString:@"completed"]) return @"任务已完成";
|
|
545
|
-
if ([state isEqualToString:@"failed"]) return @"任务失败";
|
|
546
|
-
if ([state isEqualToString:@"notification"]) return @"需要关注";
|
|
547
|
-
if ([state isEqualToString:@"tool"]) {
|
|
548
|
-
NSString *lower = tool.lowercaseString;
|
|
549
|
-
if ([lower containsString:@"bash"] || [lower containsString:@"exec"] ||
|
|
550
|
-
[lower containsString:@"shell"] || [lower containsString:@"terminal"]) return @"正在执行命令";
|
|
551
|
-
if ([lower containsString:@"patch"] || [lower containsString:@"edit"] ||
|
|
552
|
-
[lower containsString:@"write"]) return @"正在编辑文件";
|
|
553
|
-
if ([lower containsString:@"read"] || [lower containsString:@"search"] ||
|
|
554
|
-
[lower containsString:@"find"] || [lower containsString:@"grep"] ||
|
|
555
|
-
[lower containsString:@"glob"] || [lower containsString:@"web"] ||
|
|
556
|
-
[lower hasPrefix:@"mcp__"]) return @"正在查找资料";
|
|
557
|
-
if ([lower containsString:@"task"] || [lower containsString:@"agent"]) return @"子 Agent 工作中";
|
|
558
|
-
return @"正在使用工具";
|
|
559
|
-
}
|
|
560
|
-
return @"正在工作";
|
|
561
|
-
}
|
|
562
|
-
// 状态卡副行的正文。每个 hook 状态都由宠物来讲,标题仍然给事实。
|
|
563
|
-
//
|
|
564
|
-
// 这不是"额外说话",是把原来的样板文案整体换成宠物口吻,所以不受说话预算限制——
|
|
565
|
-
// 状态本来就在变,每次变化说一句是应该的。预算只管情绪句那一层。
|
|
566
|
-
- (NSString *)petVoiceTagForState:(NSString *)state tool:(NSString *)tool {
|
|
567
|
-
if ([state isEqualToString:@"starting"]) return PetPhraseTagStateStarting;
|
|
568
|
-
if ([state isEqualToString:@"idle"]) return PetPhraseTagStateIdle;
|
|
569
|
-
if ([state isEqualToString:@"thinking"]) return PetPhraseTagStateThinking;
|
|
570
|
-
if ([state isEqualToString:@"auto_review"]) return PetPhraseTagStateAutoReview;
|
|
571
|
-
if ([state isEqualToString:@"approval"]) return PetPhraseTagStateApproval;
|
|
572
|
-
if ([state isEqualToString:@"subagent"]) return PetPhraseTagStateSubagent;
|
|
573
|
-
if ([state isEqualToString:@"tool_completed"]) return PetPhraseTagStateToolDone;
|
|
574
|
-
if ([state isEqualToString:@"tool_failed"]) return PetPhraseTagStateToolFailed;
|
|
575
|
-
if ([state isEqualToString:@"completed"]) return PetPhraseTagStateCompleted;
|
|
576
|
-
if ([state isEqualToString:@"failed"]) return PetPhraseTagStateFailed;
|
|
577
|
-
if ([state isEqualToString:@"notification"]) return PetPhraseTagStateNotification;
|
|
578
|
-
if ([state isEqualToString:@"tool"]) {
|
|
579
|
-
// 工具四分类和标题那边同源。原来副行只有一句"正在调用工具…"覆盖全部四类,
|
|
580
|
-
// 分开之后副行的信息量反而比改造前更大。
|
|
581
|
-
NSString *lower = tool.lowercaseString;
|
|
582
|
-
if ([lower containsString:@"bash"] || [lower containsString:@"exec"] ||
|
|
583
|
-
[lower containsString:@"shell"] || [lower containsString:@"terminal"]) {
|
|
584
|
-
return PetPhraseTagStateToolBash;
|
|
585
|
-
}
|
|
586
|
-
if ([lower containsString:@"patch"] || [lower containsString:@"edit"] ||
|
|
587
|
-
[lower containsString:@"write"]) return PetPhraseTagStateToolEdit;
|
|
588
|
-
if ([lower containsString:@"read"] || [lower containsString:@"search"] ||
|
|
589
|
-
[lower containsString:@"find"] || [lower containsString:@"grep"] ||
|
|
590
|
-
[lower containsString:@"glob"] || [lower containsString:@"web"] ||
|
|
591
|
-
[lower hasPrefix:@"mcp__"]) return PetPhraseTagStateToolRead;
|
|
592
|
-
if ([lower containsString:@"task"] || [lower containsString:@"agent"]) {
|
|
593
|
-
return PetPhraseTagStateSubagent;
|
|
594
|
-
}
|
|
595
|
-
return PetPhraseTagStateTool;
|
|
596
|
-
}
|
|
597
|
-
return PetPhraseTagStateTool;
|
|
598
|
-
}
|
|
599
|
-
- (NSString *)statusDetailForState:(NSString *)state tool:(NSString *)tool {
|
|
600
|
-
NSString *tag = [self petVoiceTagForState:state tool:tool];
|
|
601
|
-
// 同一个状态连着来一串事件时不重摇,否则副行会不停闪。一次状态转换说一句就够。
|
|
602
|
-
if ([tag isEqualToString:self.lastPetVoiceTag] && self.lastPetVoiceText.length > 0) {
|
|
603
|
-
return self.lastPetVoiceText;
|
|
604
|
-
}
|
|
605
|
-
NSString *text = PetPhraseForTag(tag, [self speechSlots]);
|
|
606
|
-
self.lastPetVoiceTag = tag;
|
|
607
|
-
self.lastPetVoiceText = text;
|
|
608
|
-
return text;
|
|
609
|
-
}
|
|
610
|
-
- (NSColor *)statusColorForState:(NSString *)state {
|
|
611
|
-
if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) {
|
|
612
|
-
return [NSColor colorWithRed:0.18 green:0.68 blue:0.35 alpha:1];
|
|
613
|
-
}
|
|
614
|
-
if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) {
|
|
615
|
-
return [NSColor colorWithRed:0.86 green:0.28 blue:0.28 alpha:1];
|
|
616
|
-
}
|
|
617
|
-
if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) {
|
|
618
|
-
return [NSColor colorWithRed:0.92 green:0.58 blue:0.12 alpha:1];
|
|
619
|
-
}
|
|
620
|
-
// 待机是"没在干活",用中性灰和工作中的蓝拉开距离。
|
|
621
|
-
if ([state isEqualToString:@"idle"]) return [NSColor colorWithWhite:0.55 alpha:1];
|
|
622
|
-
return [NSColor colorWithRed:0.33 green:0.53 blue:0.78 alpha:1];
|
|
623
|
-
}
|
|
624
|
-
- (NSString *)statusSymbolForState:(NSString *)state {
|
|
625
|
-
if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) return @"checkmark";
|
|
626
|
-
if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) return @"xmark";
|
|
627
|
-
if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) return @"exclamationmark";
|
|
628
|
-
if ([state isEqualToString:@"idle"]) return @"zzz";
|
|
629
|
-
return @"ellipsis";
|
|
630
|
-
}
|
|
631
|
-
// Codex / Claude 退出时不会补发结束事件:包装脚本最后一行是 exec,自身已经被
|
|
632
|
-
// 替换掉,装不上 EXIT trap。唯一可靠的退出信号是客户端 pid 文件被回收。
|
|
633
|
-
// 没有这一步的话,“正在启动”只能等 60 秒无活动才消失,而另一个 provider 的事件
|
|
634
|
-
// 会不断把这 60 秒重置掉——用户关掉所有 Codex 窗口后仍然看到“Codex 正在启动”。
|
|
635
|
-
- (void)hideAgentStatusIfClientGone {
|
|
636
|
-
if (!self.hasAgentStatus || self.hasUnlabeledClient) return;
|
|
637
|
-
NSString *provider = self.lastStatusProvider;
|
|
638
|
-
if (provider.length == 0 || [self.liveClientProviders containsObject:provider]) return;
|
|
639
|
-
// 不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid 文件,只能靠
|
|
640
|
-
// “最近还在发事件”证明自己活着,所以这里必须留一段静默宽限再清。
|
|
641
|
-
if ([NSDate.date timeIntervalSince1970] - self.lastStatusTimestamp < AgentStatusOrphanInterval) return;
|
|
642
|
-
[self hideAgentStatus];
|
|
643
|
-
}
|
|
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
|
-
}
|
|
659
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
660
|
-
selector:@selector(enterIdleStatus) object:nil];
|
|
661
|
-
[self.statusPanel orderOut:nil];
|
|
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];
|
|
678
|
-
}
|
|
679
|
-
// 勾选 = 显示气泡。没有 agent 状态时也允许改,这样用户可以提前设好偏好,
|
|
680
|
-
// 而不必等下一次会话开始。
|
|
681
|
-
- (void)toggleStatusBubbleFromMenu:(NSButton *)sender {
|
|
682
|
-
self.statusBubbleExpanded = !self.statusBubbleExpanded;
|
|
683
|
-
[NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
|
|
684
|
-
forKey:StatusBubbleExpandedKey];
|
|
685
|
-
sender.state = self.statusBubbleExpanded ? NSControlStateValueOn : NSControlStateValueOff;
|
|
686
|
-
if (self.statusBubbleExpanded && self.hasAgentStatus) {
|
|
687
|
-
[self positionAgentStatus];
|
|
688
|
-
[self.statusPanel orderFrontRegardless];
|
|
689
|
-
} else {
|
|
690
|
-
[self.statusPanel orderOut:nil];
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
// Stop 之后还会飘来 SubagentStop / PostToolUse / TaskCompleted 这类"仍在工作"的尾巴事件
|
|
694
|
-
// (实测 Stop 后 4 秒),它们和 UserPromptSubmit 一样都归一成 thinking,只看 state 分不出来,
|
|
695
|
-
// 所以必须按事件名判断。终态只能被新一轮真实动作解除(用户提问、工具调用、需要关注),
|
|
696
|
-
// 否则"任务已完成"会被打回"正在思考",看起来像任务又活了。
|
|
697
|
-
- (BOOL)isTrailingRecord:(NSDictionary *)record afterState:(NSString *)state {
|
|
698
|
-
if (![state isEqualToString:@"completed"] && ![state isEqualToString:@"failed"]) return NO;
|
|
699
|
-
NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
|
|
700
|
-
return [event isEqualToString:@"SubagentStop"] || [event isEqualToString:@"PostToolUse"] ||
|
|
701
|
-
[event isEqualToString:@"TaskCompleted"];
|
|
702
|
-
}
|
|
703
|
-
- (void)applyStatusPresentationForState:(NSString *)state provider:(NSString *)provider
|
|
704
|
-
tool:(NSString *)tool {
|
|
705
|
-
self.lastStatusState = state;
|
|
706
|
-
self.lastStatusProvider = provider;
|
|
707
|
-
self.statusTitleLabel.stringValue = [NSString stringWithFormat:@"%@ · %@",
|
|
708
|
-
provider, [self statusTextForState:state tool:tool]];
|
|
709
|
-
self.statusDetailLabel.stringValue = [self statusDetailForState:state tool:tool];
|
|
710
|
-
// 上一句碎碎念借走的副行已经被新状态覆盖,取消那次归还,否则它会把旧文案写回来。
|
|
711
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
712
|
-
selector:@selector(restoreStatusDetail) object:nil];
|
|
713
|
-
NSColor *stateColor = [self statusColorForState:state];
|
|
714
|
-
self.statusIconButton.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.28].CGColor;
|
|
715
|
-
NSImage *icon = [NSImage imageWithSystemSymbolName:[self statusSymbolForState:state]
|
|
716
|
-
accessibilityDescription:[self statusTextForState:state tool:tool]];
|
|
717
|
-
self.statusIconButton.image = [icon imageWithSymbolConfiguration:
|
|
718
|
-
[NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightBold]];
|
|
719
|
-
self.statusIconButton.contentTintColor = [stateColor blendedColorWithFraction:0.18
|
|
720
|
-
ofColor:NSColor.blackColor] ?: stateColor;
|
|
721
|
-
[self resizeStatusCardToFitText];
|
|
722
|
-
[self layoutApprovalBadge];
|
|
723
|
-
[self positionAgentStatus];
|
|
724
|
-
if (self.statusBubbleExpanded) {
|
|
725
|
-
[self.statusPanel orderFrontRegardless];
|
|
726
|
-
// 卡片一出现就收掉独立气泡:两者都是宠物在说话,同时挂着就是重影。
|
|
727
|
-
if (self.speechPanel.isVisible) [self hideSpeechBubble];
|
|
728
|
-
} else {
|
|
729
|
-
[self.statusPanel orderOut:nil];
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
// "正在启动"只在会话拉起的一瞬间成立。之后如果没有任何后续事件,真实情况是会话已就绪、
|
|
733
|
-
// 正在等用户输入——继续显示"正在准备当前会话…"会让启动和待机看起来一模一样。
|
|
734
|
-
- (void)enterIdleStatus {
|
|
735
|
-
if (!self.hasAgentStatus) return;
|
|
736
|
-
[self applyStatusPresentationForState:@"idle"
|
|
737
|
-
provider:self.lastStatusProvider ?: @"Agent" tool:@""];
|
|
738
|
-
}
|
|
739
|
-
- (void)showAgentStatusForRecord:(NSDictionary *)record notify:(BOOL)shouldNotify {
|
|
740
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
741
|
-
if (provider.length == 0) provider = @"Agent";
|
|
742
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class]
|
|
743
|
-
? record[@"state"] : NormalizedStateForEvent(record[@"event"], [record[@"failed"] boolValue]);
|
|
744
|
-
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
|
|
745
|
-
// 尾巴事件仍然算"客户端还活着",只是不该改写气泡上的终态。
|
|
746
|
-
self.lastStatusTimestamp = [NSDate.date timeIntervalSince1970];
|
|
747
|
-
if (!self.providerActivityAt) self.providerActivityAt = [NSMutableDictionary dictionary];
|
|
748
|
-
self.providerActivityAt[provider] = @(self.lastStatusTimestamp);
|
|
749
|
-
[self updateQuotaLiveState];
|
|
750
|
-
if (self.hasAgentStatus && [provider isEqualToString:self.lastStatusProvider] &&
|
|
751
|
-
[self isTrailingRecord:record afterState:self.lastStatusState]) return;
|
|
752
|
-
|
|
753
|
-
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
754
|
-
? record[@"terminal"] : nil;
|
|
755
|
-
self.lastTerminalFocusTarget = terminal.count > 0 ? terminal : nil;
|
|
756
|
-
|
|
757
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
758
|
-
selector:@selector(hideAgentStatus) object:nil];
|
|
759
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
760
|
-
selector:@selector(enterIdleStatus) object:nil];
|
|
761
|
-
self.hasAgentStatus = YES;
|
|
762
|
-
[self applyStatusPresentationForState:state provider:provider tool:tool];
|
|
763
|
-
[self.panel orderFrontRegardless];
|
|
764
|
-
[self performSelector:@selector(hideAgentStatus)
|
|
765
|
-
withObject:nil afterDelay:AgentStatusInactivityInterval];
|
|
766
|
-
if ([state isEqualToString:@"starting"]) {
|
|
767
|
-
[self performSelector:@selector(enterIdleStatus) withObject:nil
|
|
768
|
-
afterDelay:AgentStartingGraceInterval];
|
|
769
|
-
}
|
|
770
|
-
if (shouldNotify) [self notifyForRecord:record];
|
|
771
|
-
}
|
|
772
|
-
- (void)showAgentStatusForRecord:(NSDictionary *)record {
|
|
773
|
-
[self showAgentStatusForRecord:record notify:YES];
|
|
774
|
-
}
|
|
775
|
-
- (NSString *)approvalKeyForRecord:(NSDictionary *)record {
|
|
776
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
777
|
-
if (provider.length == 0) provider = @"Agent";
|
|
778
|
-
NSString *session = SanitizedShortString(record[@"session"], 128);
|
|
779
|
-
return session.length > 0
|
|
780
|
-
? [NSString stringWithFormat:@"%@:%@", provider, session]
|
|
781
|
-
: provider;
|
|
782
|
-
}
|
|
783
|
-
- (void)prunePendingApprovalRecords {
|
|
784
|
-
NSTimeInterval cutoff = NSDate.date.timeIntervalSince1970 - PendingApprovalTTL;
|
|
785
|
-
for (NSString *key in self.pendingApprovalRecords.allKeys) {
|
|
786
|
-
NSDictionary *record = self.pendingApprovalRecords[key];
|
|
787
|
-
if ([record[@"timestamp"] doubleValue] < cutoff) {
|
|
788
|
-
[self.pendingApprovalRecords removeObjectForKey:key];
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
if (self.pendingApprovalRecords.count <= PendingApprovalLimit) return;
|
|
792
|
-
NSArray<NSDictionary *> *oldestFirst = [self.pendingApprovalRecords.allValues
|
|
793
|
-
sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
794
|
-
NSTimeInterval leftTime = [left[@"timestamp"] doubleValue];
|
|
795
|
-
NSTimeInterval rightTime = [right[@"timestamp"] doubleValue];
|
|
796
|
-
if (leftTime < rightTime) return NSOrderedAscending;
|
|
797
|
-
if (leftTime > rightTime) return NSOrderedDescending;
|
|
798
|
-
return NSOrderedSame;
|
|
799
|
-
}];
|
|
800
|
-
NSUInteger removeCount = oldestFirst.count - PendingApprovalLimit;
|
|
801
|
-
for (NSUInteger index = 0; index < removeCount; index++) {
|
|
802
|
-
NSString *key = [self approvalKeyForRecord:oldestFirst[index]];
|
|
803
|
-
[self.pendingApprovalRecords removeObjectForKey:key];
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
- (void)displayAgentRecord:(NSDictionary *)record notify:(BOOL)shouldNotify {
|
|
807
|
-
NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
|
|
808
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
809
|
-
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
|
|
810
|
-
NSString *animationEvent = [state isEqualToString:@"auto_review"]
|
|
811
|
-
? @"AutoReviewRequest" : event;
|
|
812
|
-
[self.petView handleAgentEvent:animationEvent tool:tool
|
|
813
|
-
failed:[record[@"failed"] boolValue]];
|
|
814
|
-
[self showAgentStatusForRecord:record notify:shouldNotify];
|
|
815
|
-
// 说话是事件流的新消费者,不改变事件生产。冷启动重放已被 processAgentEventData
|
|
816
|
-
// 的 recentOnly + 5 秒 cutoff 挡住,再加上预算制和冷却,最坏也只多说一句。
|
|
817
|
-
[self considerSpeechForRecord:record];
|
|
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
|
-
}
|
|
1380
|
-
- (NSDictionary *)petManifestInDirectory:(NSString *)directory {
|
|
1381
|
-
NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
|
|
1382
|
-
NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
|
|
1383
|
-
if (!jsonData) return @{};
|
|
1384
|
-
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
|
|
1385
|
-
return [json isKindOfClass:NSDictionary.class] ? json : @{};
|
|
1386
|
-
}
|
|
1387
|
-
- (NSInteger)spriteVersionInDirectory:(NSString *)directory fallbackDirectory:(NSString *)fallbackDirectory {
|
|
1388
|
-
NSArray<NSString *> *directories = fallbackDirectory.length > 0
|
|
1389
|
-
? @[directory, fallbackDirectory]
|
|
1390
|
-
: @[directory];
|
|
1391
|
-
for (NSString *candidate in directories) {
|
|
1392
|
-
id value = [self petManifestInDirectory:candidate][@"spriteVersionNumber"];
|
|
1393
|
-
if (![value isKindOfClass:NSNumber.class]) continue;
|
|
1394
|
-
NSInteger version = [value integerValue];
|
|
1395
|
-
if (version == 1 || version == 2) return version;
|
|
1396
|
-
}
|
|
1397
|
-
return 1;
|
|
1398
|
-
}
|
|
1399
|
-
- (NSInteger)spriteRowCountForVersion:(NSInteger)version {
|
|
1400
|
-
return version == 2 ? 11 : 9;
|
|
1401
|
-
}
|
|
1402
|
-
- (NSString *)spritePathInDirectory:(NSString *)directory {
|
|
1403
|
-
NSString *configuredName = nil;
|
|
1404
|
-
id value = [self petManifestInDirectory:directory][@"spritesheetPath"];
|
|
1405
|
-
if ([value isKindOfClass:NSString.class]) configuredName = [value lastPathComponent];
|
|
1406
|
-
NSMutableArray<NSString *> *names = [NSMutableArray array];
|
|
1407
|
-
if (configuredName.length > 0) [names addObject:configuredName];
|
|
1408
|
-
[names addObjectsFromArray:@[@"spritesheet.webp", @"spritesheet.png"]];
|
|
1409
|
-
for (NSString *name in names) {
|
|
1410
|
-
NSString *path = [directory stringByAppendingPathComponent:name];
|
|
1411
|
-
BOOL isDirectory = NO;
|
|
1412
|
-
if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && !isDirectory) return path;
|
|
1413
|
-
}
|
|
1414
|
-
return nil;
|
|
1415
|
-
}
|
|
1416
|
-
- (NSArray<NSString *> *)petDirectoryNamesAtPath:(NSString *)root {
|
|
1417
|
-
NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:root error:nil] ?: @[];
|
|
1418
|
-
NSMutableArray<NSString *> *directories = [NSMutableArray array];
|
|
1419
|
-
for (NSString *entry in entries) {
|
|
1420
|
-
if ([entry hasPrefix:@"."]) continue;
|
|
1421
|
-
BOOL isDirectory = NO;
|
|
1422
|
-
NSString *path = [root stringByAppendingPathComponent:entry];
|
|
1423
|
-
if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory) {
|
|
1424
|
-
[directories addObject:entry];
|
|
1425
|
-
}
|
|
1426
|
-
}
|
|
1427
|
-
return [directories sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
|
|
1428
|
-
}
|
|
1429
|
-
// 桌宠只扫 OwnPetsDirectory() 加包内素材,无条件、不看那里有没有东西。~/.petdex/pets 和
|
|
1430
|
-
// ~/.codex/pets 由别的工具写入,直接扫就永远分不清哪只是自己装的;要用 Codex 的素材就打开
|
|
1431
|
-
// "导入 Codex 素材"开关,由 ImportCodexPets 复制进来,之后它们和自己装的没有区别。
|
|
1432
|
-
- (NSArray<NSDictionary *> *)discoverPetOptions {
|
|
1433
|
-
NSString *ownRoot = OwnPetsDirectory();
|
|
1434
|
-
NSMutableArray<NSDictionary *> *result = [NSMutableArray array];
|
|
1435
|
-
|
|
1436
|
-
for (NSString *name in [self petDirectoryNamesAtPath:ownRoot]) {
|
|
1437
|
-
NSString *directory = [ownRoot stringByAppendingPathComponent:name];
|
|
1438
|
-
NSString *path = [self spritePathInDirectory:directory];
|
|
1439
|
-
if (!path) continue;
|
|
1440
|
-
NSInteger version = [self spriteVersionInDirectory:directory fallbackDirectory:nil];
|
|
1441
|
-
[result addObject:@{
|
|
1442
|
-
@"id": [@"external:" stringByAppendingString:name],
|
|
1443
|
-
@"name": name,
|
|
1444
|
-
@"path": path,
|
|
1445
|
-
@"spriteVersionNumber": @(version),
|
|
1446
|
-
@"spriteRowCount": @([self spriteRowCountForVersion:version])
|
|
1447
|
-
}];
|
|
1448
|
-
}
|
|
1449
|
-
|
|
1450
|
-
NSArray<NSString *> *bundled = [NSFileManager.defaultManager
|
|
1451
|
-
contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
|
|
1452
|
-
for (NSString *fileName in [bundled sortedArrayUsingSelector:@selector(localizedStandardCompare:)]) {
|
|
1453
|
-
NSString *extension = fileName.pathExtension.lowercaseString;
|
|
1454
|
-
if (![extension isEqualToString:@"webp"] && ![extension isEqualToString:@"png"]) continue;
|
|
1455
|
-
[result addObject:@{
|
|
1456
|
-
@"id": [@"builtin:" stringByAppendingString:fileName],
|
|
1457
|
-
@"name": fileName.stringByDeletingPathExtension,
|
|
1458
|
-
@"path": [self.binaryDirectory stringByAppendingPathComponent:fileName],
|
|
1459
|
-
@"spriteVersionNumber": @1,
|
|
1460
|
-
@"spriteRowCount": @9
|
|
1461
|
-
}];
|
|
1462
|
-
}
|
|
1463
|
-
return result;
|
|
1464
|
-
}
|
|
1465
|
-
// 素材目录的 mtime。目录里增删条目会改动它,而 `cc-pets pet add` / `remove` 正是在增删
|
|
1466
|
-
// 条目——所以这一个时间戳就足以判断列表是否需要重扫,不必每次打开菜单都遍历目录。
|
|
1467
|
-
- (NSDate *)petOptionsStamp {
|
|
1468
|
-
NSDictionary *attributes = [NSFileManager.defaultManager
|
|
1469
|
-
attributesOfItemAtPath:OwnPetsDirectory() error:nil];
|
|
1470
|
-
return attributes[NSFileModificationDate];
|
|
1471
|
-
}
|
|
1472
|
-
- (void)invalidatePetOptionsCache {
|
|
1473
|
-
self.cachedPetOptions = nil;
|
|
1474
|
-
self.cachedPetOptionsStamp = nil;
|
|
1475
|
-
}
|
|
1476
|
-
- (NSArray<NSDictionary *> *)petOptions {
|
|
1477
|
-
NSDate *stamp = [self petOptionsStamp];
|
|
1478
|
-
BOOL stale = !self.cachedPetOptions ||
|
|
1479
|
-
(stamp == nil) != (self.cachedPetOptionsStamp == nil) ||
|
|
1480
|
-
(stamp && ![stamp isEqualToDate:self.cachedPetOptionsStamp]);
|
|
1481
|
-
if (stale) {
|
|
1482
|
-
self.cachedPetOptions = [self discoverPetOptions];
|
|
1483
|
-
self.cachedPetOptionsStamp = stamp;
|
|
1484
|
-
}
|
|
1485
|
-
return self.cachedPetOptions;
|
|
1486
|
-
}
|
|
1487
|
-
- (NSDictionary *)petOptionWithID:(NSString *)petID inOptions:(NSArray<NSDictionary *> *)options {
|
|
1488
|
-
for (NSDictionary *option in options) if ([option[@"id"] isEqualToString:petID]) return option;
|
|
1489
|
-
return nil;
|
|
1490
|
-
}
|
|
1491
|
-
- (NSArray<NSDictionary *> *)waitForPetOptions {
|
|
1492
|
-
while (YES) {
|
|
1493
|
-
// 这个循环就是"重新扫描"按钮的实现,必须绕开缓存。
|
|
1494
|
-
[self invalidatePetOptionsCache];
|
|
1495
|
-
NSArray<NSDictionary *> *options = [self petOptions];
|
|
1496
|
-
if (options.count > 0) return options;
|
|
1497
|
-
|
|
1498
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
1499
|
-
NSAlert *alert = [NSAlert new];
|
|
1500
|
-
alert.messageText = @"没有找到桌宠素材";
|
|
1501
|
-
alert.informativeText = @"用 `cc-pets pet add <名称>` 下载素材,或把 PNG / WebP 精灵图放入 "
|
|
1502
|
-
@"~/.cc-pets/pets/<名称>/。桌宠不会去读 ~/.petdex/pets/ 和 ~/.codex/pets/;"
|
|
1503
|
-
@"要用 Codex 的素材,请在右键菜单打开“导入 Codex 素材”。完成后点击“重新扫描”。";
|
|
1504
|
-
[alert addButtonWithTitle:@"重新扫描"];
|
|
1505
|
-
[alert addButtonWithTitle:@"打开素材目录"];
|
|
1506
|
-
[alert addButtonWithTitle:@"退出"];
|
|
1507
|
-
NSModalResponse response = [alert runModal];
|
|
1508
|
-
if (response == NSAlertSecondButtonReturn) {
|
|
1509
|
-
NSString *directory = OwnPetsDirectory();
|
|
1510
|
-
[NSFileManager.defaultManager createDirectoryAtPath:directory
|
|
1511
|
-
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
1512
|
-
[NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:directory]];
|
|
1513
|
-
} else if (response == NSAlertThirdButtonReturn) {
|
|
1514
|
-
return @[];
|
|
1515
|
-
}
|
|
1516
|
-
}
|
|
1517
|
-
}
|
|
1518
64
|
// 建一个只有"编辑"的主菜单。
|
|
1519
65
|
//
|
|
1520
66
|
// ⌘C/⌘V/⌘A/⌘Z 不是 NSTextView 自己处理的:按键先走 NSApp.mainMenu 的
|
|
@@ -1556,7 +102,6 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1556
102
|
editItem.submenu = editMenu;
|
|
1557
103
|
NSApp.mainMenu = mainMenu;
|
|
1558
104
|
}
|
|
1559
|
-
|
|
1560
105
|
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
|
|
1561
106
|
// 没有主菜单的话,台词编辑器里 ⌘C/⌘V/⌘A/⌘Z 全部没反应。
|
|
1562
107
|
[self installEditMenu];
|
|
@@ -1648,6 +193,9 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1648
193
|
self.petView.petOptionsRequested = ^NSArray<NSDictionary *> *{
|
|
1649
194
|
return [weakSelf petOptions] ?: @[];
|
|
1650
195
|
};
|
|
196
|
+
self.petView.pendingUpdateVersionRequested = ^NSString *{
|
|
197
|
+
return weakSelf.updating ? nil : weakSelf.pendingUpdateVersion;
|
|
198
|
+
};
|
|
1651
199
|
self.petView.switchPetRequested = ^(NSString *petID) {
|
|
1652
200
|
[weakSelf switchPetToID:petID];
|
|
1653
201
|
};
|
|
@@ -1669,6 +217,38 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1669
217
|
selector:@selector(petWindowDidMove:)
|
|
1670
218
|
name:NSWindowDidMoveNotification object:self.panel];
|
|
1671
219
|
[root addSubview:self.petView];
|
|
220
|
+
// 有新版本时挂在宠物右上角的「↑」角标:气泡只冒一会儿,角标一直在,点一下弹更新窗口。
|
|
221
|
+
// 底子用和状态卡、气泡同一套 CCPetsGlassView,跟着面板主题和压暗档位走。
|
|
222
|
+
// 在 petView 之后加入,点击先落到角标上。
|
|
223
|
+
NSView *updateBadge = [[NSView alloc] initWithFrame:NSMakeRect(
|
|
224
|
+
NSMaxX(self.petView.frame) - 30, NSMaxY(self.petView.frame) - 28,
|
|
225
|
+
PetUpdateBadgeSize, PetUpdateBadgeSize)];
|
|
226
|
+
updateBadge.hidden = YES;
|
|
227
|
+
self.updateBadgeGlass = [[CCPetsGlassView alloc]
|
|
228
|
+
initWithFrame:updateBadge.bounds material:NSVisualEffectMaterialPopover
|
|
229
|
+
appearance:NSAppearanceNameAqua cornerRadius:PetUpdateBadgeSize / 2.0];
|
|
230
|
+
self.updateBadgeGlass.edgeShadeHeight = 4;
|
|
231
|
+
self.updateBadgeGlass.edgeShadeAlpha = 0.5;
|
|
232
|
+
self.updateBadgeGlass.usesWidgetGlass = YES;
|
|
233
|
+
[updateBadge addSubview:self.updateBadgeGlass];
|
|
234
|
+
self.updateBadgeArrow = [[NSImageView alloc] initWithFrame:updateBadge.bounds];
|
|
235
|
+
self.updateBadgeArrow.imageScaling = NSImageScaleNone;
|
|
236
|
+
self.updateBadgeArrow.image = [[NSImage imageWithSystemSymbolName:@"arrow.up"
|
|
237
|
+
accessibilityDescription:@"有新版本"] imageWithSymbolConfiguration:
|
|
238
|
+
[NSImageSymbolConfiguration configurationWithPointSize:11 weight:NSFontWeightBold]];
|
|
239
|
+
[updateBadge addSubview:self.updateBadgeArrow];
|
|
240
|
+
CCPetsStatusClickButton *updateClick = [[CCPetsStatusClickButton alloc]
|
|
241
|
+
initWithFrame:updateBadge.bounds];
|
|
242
|
+
updateClick.bordered = NO;
|
|
243
|
+
updateClick.transparent = YES;
|
|
244
|
+
updateClick.title = @"";
|
|
245
|
+
updateClick.target = self;
|
|
246
|
+
updateClick.action = @selector(updateBubbleClicked:);
|
|
247
|
+
[updateBadge addSubview:updateClick];
|
|
248
|
+
self.updateBadgeButton = updateClick;
|
|
249
|
+
self.updateBadgeView = updateBadge;
|
|
250
|
+
[root addSubview:updateBadge];
|
|
251
|
+
[self applyUpdateBadgeStyle];
|
|
1672
252
|
|
|
1673
253
|
NSSize statusGlassSize = NSMakeSize(340, PetStatusBodyHeight);
|
|
1674
254
|
NSSize statusSize = NSMakeSize(statusGlassSize.width + 12, statusGlassSize.height + 12);
|
|
@@ -1689,8 +269,8 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1689
269
|
NSView *statusShadow = [[NSView alloc] initWithFrame:NSMakeRect(
|
|
1690
270
|
6, 6, statusGlassSize.width, statusGlassSize.height)];
|
|
1691
271
|
self.statusShadowView = statusShadow;
|
|
1692
|
-
statusShadow.layer.cornerRadius = statusGlassSize.height / 2.0;
|
|
1693
272
|
statusShadow.wantsLayer = YES;
|
|
273
|
+
statusShadow.layer.cornerRadius = statusGlassSize.height / 2.0;
|
|
1694
274
|
statusShadow.layer.backgroundColor = [NSColor colorWithWhite:0 alpha:0.01].CGColor;
|
|
1695
275
|
statusShadow.layer.cornerCurve = kCACornerCurveContinuous;
|
|
1696
276
|
statusShadow.layer.shadowColor = NSColor.blackColor.CGColor;
|
|
@@ -1704,18 +284,14 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1704
284
|
CGPathRelease(statusShadowPath);
|
|
1705
285
|
[statusRoot addSubview:statusShadow];
|
|
1706
286
|
|
|
1707
|
-
self.statusGlass = [[
|
|
1708
|
-
initWithFrame:NSMakeRect(6, 6, statusGlassSize.width, statusGlassSize.height)
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
self.statusGlass.
|
|
1713
|
-
self.statusGlass.
|
|
1714
|
-
self.statusGlass.
|
|
1715
|
-
self.statusGlass.layer.cornerCurve = kCACornerCurveContinuous;
|
|
1716
|
-
self.statusGlass.layer.masksToBounds = YES;
|
|
1717
|
-
self.statusGlass.layer.borderWidth = 1;
|
|
1718
|
-
self.statusGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
|
|
287
|
+
self.statusGlass = [[CCPetsGlassView alloc]
|
|
288
|
+
initWithFrame:NSMakeRect(6, 6, statusGlassSize.width, statusGlassSize.height)
|
|
289
|
+
material:NSVisualEffectMaterialPopover appearance:NSAppearanceNameAqua
|
|
290
|
+
cornerRadius:statusGlassSize.height / 2.0];
|
|
291
|
+
// 胶囊比面板矮,边缘高光占比更大;10pt / 0.6 是对照截图里深色背景下刚好压住的值。
|
|
292
|
+
self.statusGlass.edgeShadeHeight = 10;
|
|
293
|
+
self.statusGlass.edgeShadeAlpha = 0.6;
|
|
294
|
+
self.statusGlass.usesWidgetGlass = YES;
|
|
1719
295
|
|
|
1720
296
|
self.statusTitleLabel = [NSTextField labelWithString:@""];
|
|
1721
297
|
// 层级是反的:宠物是主角,事实退成眉标。
|
|
@@ -1724,14 +300,14 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1724
300
|
self.statusTitleLabel.font = [NSFont systemFontOfSize:11 weight:NSFontWeightMedium];
|
|
1725
301
|
self.statusTitleLabel.textColor = [NSColor colorWithWhite:0.42 alpha:0.90];
|
|
1726
302
|
self.statusTitleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
|
|
1727
|
-
[self.statusGlass addSubview:self.statusTitleLabel];
|
|
303
|
+
[self.statusGlass.contentView addSubview:self.statusTitleLabel];
|
|
1728
304
|
|
|
1729
305
|
self.statusDetailLabel = [NSTextField labelWithString:@""];
|
|
1730
306
|
self.statusDetailLabel.frame = NSMakeRect(20, 10, statusGlassSize.width - 80, 22);
|
|
1731
307
|
self.statusDetailLabel.font = [NSFont systemFontOfSize:14 weight:NSFontWeightMedium];
|
|
1732
308
|
self.statusDetailLabel.textColor = [NSColor colorWithWhite:0.12 alpha:0.96];
|
|
1733
309
|
self.statusDetailLabel.lineBreakMode = NSLineBreakByTruncatingTail;
|
|
1734
|
-
[self.statusGlass addSubview:self.statusDetailLabel];
|
|
310
|
+
[self.statusGlass.contentView addSubview:self.statusDetailLabel];
|
|
1735
311
|
|
|
1736
312
|
self.statusIconButton = [[CCPetsStatusClickButton alloc] initWithFrame:NSMakeRect(
|
|
1737
313
|
statusGlassSize.width - 48, 12, 34, 34)];
|
|
@@ -1743,8 +319,11 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1743
319
|
self.statusIconButton.toolTip = @"查看最近 Agent 会话与 CC Bridge 消息";
|
|
1744
320
|
self.statusIconButton.target = self;
|
|
1745
321
|
self.statusIconButton.action = @selector(showAgentSessionsMenu:);
|
|
1746
|
-
[self.statusGlass addSubview:self.statusIconButton];
|
|
322
|
+
[self.statusGlass.contentView addSubview:self.statusIconButton];
|
|
323
|
+
// 原生玻璃自带阴影,再叠手工阴影会糊成两层。
|
|
324
|
+
self.statusShadowView.hidden = self.statusGlass.usesLiquidGlass;
|
|
1747
325
|
[statusRoot addSubview:self.statusGlass];
|
|
326
|
+
[self applyBubbleTextStyle];
|
|
1748
327
|
CCPetsStatusClickButton *statusClick = [[CCPetsStatusClickButton alloc]
|
|
1749
328
|
initWithFrame:NSMakeRect(6, 6, statusGlassSize.width - 56, statusGlassSize.height)];
|
|
1750
329
|
statusClick.bordered = NO;
|
|
@@ -1756,7 +335,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1756
335
|
statusClick.action = @selector(focusLatestAgentTerminal:);
|
|
1757
336
|
self.statusClickButton = statusClick;
|
|
1758
337
|
[statusRoot addSubview:statusClick];
|
|
1759
|
-
// 角标挂在 statusRoot
|
|
338
|
+
// 角标挂在 statusRoot 而不是玻璃内容里:玻璃卡片会按胶囊形状裁切,
|
|
1760
339
|
// 右上角正好落在圆角外面,放进去会被裁掉一半。
|
|
1761
340
|
CCPetsApprovalBadgeView *badge = [[CCPetsApprovalBadgeView alloc]
|
|
1762
341
|
initWithFrame:NSMakeRect(0, 0, PetApprovalBadgeSize, PetApprovalBadgeSize)];
|
|
@@ -1787,17 +366,15 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1787
366
|
self.quotaPanel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
|
|
1788
367
|
self.quotaPanel.hidesOnDeactivate = NO;
|
|
1789
368
|
NSView *quotaRoot = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
glass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
|
|
1796
|
-
glass.wantsLayer = YES;
|
|
1797
|
-
glass.layer.cornerRadius = 13;
|
|
1798
|
-
glass.layer.masksToBounds = YES;
|
|
1799
|
-
[quotaRoot addSubview:glass];
|
|
369
|
+
self.quotaGlass = [[CCPetsGlassView alloc] initWithFrame:quotaRoot.bounds
|
|
370
|
+
material:NSVisualEffectMaterialUnderWindowBackground
|
|
371
|
+
appearance:NSAppearanceNameDarkAqua cornerRadius:13];
|
|
372
|
+
self.quotaGlass.usesWidgetGlass = YES;
|
|
373
|
+
[quotaRoot addSubview:self.quotaGlass];
|
|
1800
374
|
self.quotaView = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
|
|
375
|
+
self.quotaView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
|
|
376
|
+
self.quotaView.usesLiquidGlass = self.quotaGlass.usesLiquidGlass;
|
|
377
|
+
self.quotaView.cardScrimAlpha = CCPetsGlassCardScrimAlpha();
|
|
1801
378
|
[self applySystemMetricPreferences];
|
|
1802
379
|
[self applyUsageDisplayModePreferences];
|
|
1803
380
|
self.quotaView.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
|
|
@@ -1806,10 +383,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1806
383
|
weakSelf.dashboardHovering = hovering;
|
|
1807
384
|
if (!hovering) [weakSelf scheduleQuotaDashboardHide];
|
|
1808
385
|
};
|
|
1809
|
-
self.
|
|
1810
|
-
[weakSelf refreshUsage:nil];
|
|
1811
|
-
};
|
|
1812
|
-
[quotaRoot addSubview:self.quotaView];
|
|
386
|
+
[self.quotaGlass.contentView addSubview:self.quotaView];
|
|
1813
387
|
self.quotaPanel.contentView = quotaRoot;
|
|
1814
388
|
// 先探测再第一次显示:否则面板会先按两张卡的高度弹出来再收缩一下。
|
|
1815
389
|
[self refreshDetectedProviders];
|
|
@@ -1858,6 +432,14 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1858
432
|
name:NSWorkspaceScreensDidSleepNotification object:nil];
|
|
1859
433
|
[workspaceCenter addObserver:self selector:@selector(screensDidWake:)
|
|
1860
434
|
name:NSWorkspaceScreensDidWakeNotification object:nil];
|
|
435
|
+
// 启动先让界面和事件流就位,再联网检查更新,别和启动抢时间。
|
|
436
|
+
[self performSelector:@selector(silentCheckForUpdate) withObject:nil afterDelay:5.0];
|
|
437
|
+
}
|
|
438
|
+
// CLI 启动时桌宠若已在运行,`open -g` 不会重新启动它,只会发一个 reopen 事件过来。
|
|
439
|
+
// 借这个时机同样静默检查一次更新(silentCheckForUpdate 自己做节流)。
|
|
440
|
+
- (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag {
|
|
441
|
+
[self silentCheckForUpdate];
|
|
442
|
+
return NO;
|
|
1861
443
|
}
|
|
1862
444
|
- (void)screensDidSleep:(NSNotification *)notification {
|
|
1863
445
|
[self.petView setAnimationSuspended:YES];
|
|
@@ -1865,925 +447,11 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1865
447
|
- (void)screensDidWake:(NSNotification *)notification {
|
|
1866
448
|
[self.petView setAnimationSuspended:NO];
|
|
1867
449
|
}
|
|
1868
|
-
- (void)rescheduleUsageTimer {
|
|
1869
|
-
NSTimeInterval interval = self.quotaPanel.isVisible
|
|
1870
|
-
? UsageRefreshIntervalVisible : UsageRefreshIntervalHidden;
|
|
1871
|
-
if (self.usageTimer.isValid && self.usageTimer.timeInterval == interval) return;
|
|
1872
|
-
[self.usageTimer invalidate];
|
|
1873
|
-
self.usageTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self
|
|
1874
|
-
selector:@selector(refreshUsage:) userInfo:nil repeats:YES];
|
|
1875
|
-
self.usageTimer.tolerance = interval * 0.2;
|
|
1876
|
-
}
|
|
1877
|
-
// 全量聚合是同步的主线程活儿(本机实测数十毫秒,会话目录越大越久),而面板恰好由"鼠标
|
|
1878
|
-
// 停在口袋上"触发——那正是用户可能马上按下并拖动的时刻。事件被这几十毫秒挡住,mouseDown
|
|
1879
|
-
// 和 mouseDragged 就会成批迟到,手感上像是"鼠标走远了宠物才跟上"。
|
|
1880
|
-
// 因此:左键按着的时候不刷(拖动期间没人看数字),刚刷过的也不重刷(进出热区会反复触发)。
|
|
1881
|
-
static const NSTimeInterval UsageRefreshCoalesceWindow = 2.0;
|
|
1882
|
-
- (BOOL)shouldRefreshUsageForDashboard {
|
|
1883
|
-
if (CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, kCGMouseButtonLeft)) {
|
|
1884
|
-
return NO;
|
|
1885
|
-
}
|
|
1886
|
-
return NSDate.date.timeIntervalSince1970 - self.lastUsageRefreshAt >= UsageRefreshCoalesceWindow;
|
|
1887
|
-
}
|
|
1888
|
-
- (void)showQuotaDashboard {
|
|
1889
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
|
|
1890
|
-
if ([self shouldRefreshUsageForDashboard]) [self refreshUsage:nil];
|
|
1891
|
-
[self positionQuotaDashboard];
|
|
1892
|
-
[self.quotaPanel orderFrontRegardless];
|
|
1893
|
-
[self.panel orderFrontRegardless];
|
|
1894
|
-
[self rescheduleUsageTimer];
|
|
1895
|
-
[self startQuotaClock];
|
|
1896
|
-
[self updateSystemMetricsTimer];
|
|
1897
|
-
}
|
|
1898
|
-
- (BOOL)hasEnabledSystemMetric {
|
|
1899
|
-
return self.quotaView.systemCPUEnabled || self.quotaView.systemTemperatureEnabled ||
|
|
1900
|
-
self.quotaView.systemMemoryEnabled;
|
|
1901
|
-
}
|
|
1902
|
-
- (void)refreshSystemMetrics:(id)sender {
|
|
1903
|
-
if (![self hasEnabledSystemMetric]) return;
|
|
1904
|
-
BOOL cpuEnabled = self.quotaView.systemCPUEnabled;
|
|
1905
|
-
BOOL memoryEnabled = self.quotaView.systemMemoryEnabled;
|
|
1906
|
-
BOOL temperatureEnabled = self.quotaView.systemTemperatureEnabled;
|
|
1907
|
-
__weak typeof(self) weakSelf = self;
|
|
1908
|
-
[self.systemMonitor sampleCPU:cpuEnabled memory:memoryEnabled
|
|
1909
|
-
temperature:temperatureEnabled completion:^(NSNumber *cpu, NSNumber *memory,
|
|
1910
|
-
NSNumber *temperature) {
|
|
1911
|
-
typeof(self) strongSelf = weakSelf;
|
|
1912
|
-
if (!strongSelf) return;
|
|
1913
|
-
if (cpuEnabled) strongSelf.quotaView.systemCPUPercent = cpu;
|
|
1914
|
-
if (memoryEnabled) strongSelf.quotaView.systemMemoryPercent = memory;
|
|
1915
|
-
if (temperatureEnabled) strongSelf.quotaView.systemTemperatureCelsius = temperature;
|
|
1916
|
-
strongSelf.quotaView.needsDisplay = YES;
|
|
1917
|
-
}];
|
|
1918
|
-
}
|
|
1919
|
-
- (void)updateSystemMetricsTimer {
|
|
1920
|
-
BOOL shouldRun = self.quotaPanel.isVisible && [self hasEnabledSystemMetric];
|
|
1921
|
-
if (!shouldRun) {
|
|
1922
|
-
[self.systemMetricsTimer invalidate];
|
|
1923
|
-
self.systemMetricsTimer = nil;
|
|
1924
|
-
return;
|
|
1925
|
-
}
|
|
1926
|
-
if (self.systemMetricsTimer.isValid) return;
|
|
1927
|
-
[self refreshSystemMetrics:nil];
|
|
1928
|
-
__weak typeof(self) weakSelf = self;
|
|
1929
|
-
self.systemMetricsTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES
|
|
1930
|
-
block:^(NSTimer *timer) { [weakSelf refreshSystemMetrics:timer]; }];
|
|
1931
|
-
self.systemMetricsTimer.tolerance = 0.4;
|
|
1932
|
-
}
|
|
1933
|
-
// "数据刷新" 显示的是相对时间,没有新数据也得自己走字。面板隐藏时不需要这个定时器,
|
|
1934
|
-
// 隐藏的窗口本来就不会重绘。
|
|
1935
|
-
- (void)startQuotaClock {
|
|
1936
|
-
if (self.quotaClockTimer.isValid) return;
|
|
1937
|
-
self.quotaClockTimer = [NSTimer scheduledTimerWithTimeInterval:QuotaClockInterval
|
|
1938
|
-
target:self selector:@selector(tickQuotaClock:) userInfo:nil repeats:YES];
|
|
1939
|
-
self.quotaClockTimer.tolerance = QuotaClockInterval * 0.3;
|
|
1940
|
-
}
|
|
1941
|
-
- (void)tickQuotaClock:(id)sender {
|
|
1942
|
-
if (!self.quotaPanel.isVisible) {
|
|
1943
|
-
[self.quotaClockTimer invalidate];
|
|
1944
|
-
self.quotaClockTimer = nil;
|
|
1945
|
-
[self updateSystemMetricsTimer];
|
|
1946
|
-
return;
|
|
1947
|
-
}
|
|
1948
|
-
self.quotaView.needsDisplay = YES;
|
|
1949
|
-
}
|
|
1950
|
-
- (void)positionQuotaDashboard {
|
|
1951
|
-
NSRect petFrame = self.panel.frame;
|
|
1952
|
-
NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
|
|
1953
|
-
NSSize size = self.quotaPanel.frame.size;
|
|
1954
|
-
const CGFloat margin = 12;
|
|
1955
|
-
const CGFloat gap = 8;
|
|
1956
|
-
CGFloat minX = NSMinX(visible) + margin;
|
|
1957
|
-
CGFloat maxX = NSMaxX(visible) - size.width - margin;
|
|
1958
|
-
CGFloat minY = NSMinY(visible) + margin;
|
|
1959
|
-
CGFloat maxY = NSMaxY(visible) - size.height - margin;
|
|
1960
|
-
CGFloat leftX = NSMinX(petFrame) - size.width - gap;
|
|
1961
|
-
CGFloat rightX = NSMaxX(petFrame) + gap;
|
|
1962
|
-
CGFloat x;
|
|
1963
|
-
CGFloat y = fmax(minY, fmin(NSMinY(petFrame) + 112, maxY));
|
|
1964
|
-
|
|
1965
|
-
// 优先放在宠物左侧,其次右侧;两个可点击窗口之间始终留出间隔。
|
|
1966
|
-
if (leftX >= minX) {
|
|
1967
|
-
x = leftX;
|
|
1968
|
-
} else if (rightX <= maxX) {
|
|
1969
|
-
x = rightX;
|
|
1970
|
-
} else {
|
|
1971
|
-
// 横向空间不足时改放上/下方,避免屏幕边缘钳位后重新盖住宠物。
|
|
1972
|
-
x = fmax(minX, fmin(NSMidX(petFrame) - size.width / 2.0, maxX));
|
|
1973
|
-
CGFloat aboveY = NSMaxY(petFrame) + gap;
|
|
1974
|
-
CGFloat belowY = NSMinY(petFrame) - size.height - gap;
|
|
1975
|
-
if (aboveY <= maxY) y = aboveY;
|
|
1976
|
-
else if (belowY >= minY) y = belowY;
|
|
1977
|
-
else y = fmax(minY, fmin(aboveY, maxY));
|
|
1978
|
-
}
|
|
1979
|
-
[self.quotaPanel setFrameOrigin:NSMakePoint(x, y)];
|
|
1980
|
-
}
|
|
1981
450
|
- (void)petWindowDidMove:(NSNotification *)notification {
|
|
1982
451
|
if (self.quotaPanel.isVisible) [self positionQuotaDashboard];
|
|
1983
452
|
if (self.statusPanel.isVisible) [self positionAgentStatus];
|
|
1984
453
|
if (self.speechPanel.isVisible) [self positionSpeechPanel];
|
|
1985
454
|
}
|
|
1986
|
-
#pragma mark - 说话气泡
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
// 气泡停留时长。
|
|
1991
|
-
static const NSTimeInterval PetSpeechDwell = 4.5;
|
|
1992
|
-
// 气泡与状态卡的本体高度。
|
|
1993
|
-
//
|
|
1994
|
-
// 不要再加尾巴(三角、锥形、思考圆点都试过):药丸的圆角等于高度一半,整条边都是弧,
|
|
1995
|
-
// 尾巴只能从弧上长出来,怎么调都像贴上去的;换成圆角矩形能配尾巴,但那要放弃
|
|
1996
|
-
// layer.cornerRadius + kCACornerCurveContinuous 改用位图 maskImage 裁形,
|
|
1997
|
-
// squircle 和 GPU 端矢量裁切的质感一起丢了,得不偿失。
|
|
1998
|
-
// 结论:保持药丸 + 原生圆角,靠贴近宠物来表达归属。
|
|
1999
|
-
static const CGFloat PetSpeechBodyHeight = 38.0;
|
|
2000
|
-
static const CGFloat PetStatusBodyHeight = 58.0;
|
|
2001
|
-
// 副行没东西可显示时的高度,只放得下标题一行。
|
|
2002
|
-
static const CGFloat PetStatusSingleLineHeight = 40.0;
|
|
2003
|
-
|
|
2004
|
-
- (BOOL)speechEnabled {
|
|
2005
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
2006
|
-
// 缺省开启;用户可在右键菜单里关掉。
|
|
2007
|
-
id value = [defaults objectForKey:@"CCPetsSpeechEnabled"];
|
|
2008
|
-
return value == nil ? YES : [value boolValue];
|
|
2009
|
-
}
|
|
2010
|
-
// 当前档位。现读,右键菜单里改完立刻生效不用重启。
|
|
2011
|
-
- (PetSpeechRate)speechRate {
|
|
2012
|
-
NSString *value = [NSUserDefaults.standardUserDefaults stringForKey:PetSpeechFrequencyKey];
|
|
2013
|
-
if ([value isEqualToString:PetSpeechFrequencyLow]) return PetSpeechRateLow;
|
|
2014
|
-
if ([value isEqualToString:PetSpeechFrequencyHigh]) return PetSpeechRateHigh;
|
|
2015
|
-
if ([value isEqualToString:PetSpeechFrequencyChatty]) return PetSpeechRateChatty;
|
|
2016
|
-
return PetSpeechRateNormal;
|
|
2017
|
-
}
|
|
2018
|
-
// 预算与冷却。两道闸门都过了才允许说。
|
|
2019
|
-
// 默认跟随上面的档位;下面这两个键是更细的手动覆盖,写了就压过档位,
|
|
2020
|
-
// 现读,改完立刻生效不用重启:
|
|
2021
|
-
// defaults write com.universewang.cc-pets CCPetsSpeechCooldown -float 0
|
|
2022
|
-
// defaults write com.universewang.cc-pets CCPetsSpeechHourlyBudget -int 100
|
|
2023
|
-
// defaults delete com.universewang.cc-pets CCPetsSpeechCooldown # 交回档位
|
|
2024
|
-
// 域名是 bundle identifier,不是 "cc-pets"——写错域的话键会落在另一个 plist 里,
|
|
2025
|
-
// 桌宠永远看不到,表现为"设了没反应"。
|
|
2026
|
-
- (NSTimeInterval)speechCooldownSeconds {
|
|
2027
|
-
id value = [NSUserDefaults.standardUserDefaults objectForKey:@"CCPetsSpeechCooldown"];
|
|
2028
|
-
if (![value isKindOfClass:NSNumber.class]) return [self speechRate].cooldown;
|
|
2029
|
-
return MAX(0.0, [value doubleValue]);
|
|
2030
|
-
}
|
|
2031
|
-
- (NSInteger)speechHourlyBudget {
|
|
2032
|
-
id value = [NSUserDefaults.standardUserDefaults objectForKey:@"CCPetsSpeechHourlyBudget"];
|
|
2033
|
-
if (![value isKindOfClass:NSNumber.class]) return [self speechRate].hourlyBudget;
|
|
2034
|
-
return MAX((NSInteger)1, [value integerValue]);
|
|
2035
|
-
}
|
|
2036
|
-
// agent 是不是正在干活。只有"待机中"和状态卡压根没显示这两种情况算闲——
|
|
2037
|
-
// thinking / tool / subagent / approval / notification / completed / failed
|
|
2038
|
-
// 副行上都带着用户还需要看的信息,闲话一律让路。
|
|
2039
|
-
// 用 hasAgentStatus 而不是 statusPanel.isVisible:用户把状态卡折叠起来时卡片是隐藏的,
|
|
2040
|
-
// 但 agent 照样在干活,这时候冒气泡等于绕过折叠又把话糊到脸上。
|
|
2041
|
-
- (BOOL)agentBusyForSpeech {
|
|
2042
|
-
if (!self.hasAgentStatus) return NO;
|
|
2043
|
-
return ![self.lastStatusState isEqualToString:@"idle"];
|
|
2044
|
-
}
|
|
2045
|
-
- (BOOL)canSpeakNow {
|
|
2046
|
-
if (![self speechEnabled]) return NO;
|
|
2047
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2048
|
-
if (now < self.speechCooldownUntil) return NO;
|
|
2049
|
-
if (!self.speechTimestamps) self.speechTimestamps = [NSMutableArray array];
|
|
2050
|
-
while (self.speechTimestamps.count > 0 &&
|
|
2051
|
-
now - self.speechTimestamps.firstObject.doubleValue > 3600.0) {
|
|
2052
|
-
[self.speechTimestamps removeObjectAtIndex:0];
|
|
2053
|
-
}
|
|
2054
|
-
return (NSInteger)self.speechTimestamps.count < [self speechHourlyBudget];
|
|
2055
|
-
}
|
|
2056
|
-
// 当前可用的槽位值。取不到的键就不放进去,模板层会因此跳过需要它的那些条目。
|
|
2057
|
-
- (NSDictionary<NSString *, NSString *> *)speechSlots {
|
|
2058
|
-
return [self speechSlotsWithTool:self.lastSpeechTool];
|
|
2059
|
-
}
|
|
2060
|
-
- (NSDictionary<NSString *, NSString *> *)speechSlotsWithTool:(NSString *)tool {
|
|
2061
|
-
NSMutableDictionary<NSString *, NSString *> *slots = [NSMutableDictionary dictionary];
|
|
2062
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
2063
|
-
slots[@"hour"] = [@([calendar component:NSCalendarUnitHour fromDate:NSDate.date]) stringValue];
|
|
2064
|
-
if (self.consecutiveFailures > 0) {
|
|
2065
|
-
slots[@"failCount"] = [@(self.consecutiveFailures) stringValue];
|
|
2066
|
-
}
|
|
2067
|
-
if (self.sessionStartedAt > 0) {
|
|
2068
|
-
NSInteger minutes = (NSInteger)((NSDate.date.timeIntervalSince1970 -
|
|
2069
|
-
self.sessionStartedAt) / 60.0);
|
|
2070
|
-
if (minutes > 0) slots[@"sessionMin"] = [@(minutes) stringValue];
|
|
2071
|
-
}
|
|
2072
|
-
NSInteger remaining = [self remainingFiveHourQuotaPercent];
|
|
2073
|
-
if (remaining >= 0) {
|
|
2074
|
-
slots[@"quota5h"] = [NSString stringWithFormat:@"%ld%%", (long)remaining];
|
|
2075
|
-
}
|
|
2076
|
-
NSString *reset = [self fiveHourResetTimeText];
|
|
2077
|
-
if (reset.length > 0) slots[@"resetTime"] = reset;
|
|
2078
|
-
// 工具名此前从来没被填过,导致 "{toolName} 这货不靠谱。" 这类台词永远被跳过。
|
|
2079
|
-
NSString *trimmed = [tool stringByTrimmingCharactersInSet:
|
|
2080
|
-
NSCharacterSet.whitespaceCharacterSet];
|
|
2081
|
-
if (trimmed.length > 0 && trimmed.length <= 24) slots[@"toolName"] = trimmed;
|
|
2082
|
-
return slots;
|
|
2083
|
-
}
|
|
2084
|
-
// 5 小时窗口的剩余百分比,取不到返回 -1。Claude 和 Codex 的字段名不一样,都认。
|
|
2085
|
-
- (NSInteger)remainingFiveHourQuotaPercent {
|
|
2086
|
-
NSDictionary *usage = LatestClaudeUsage() ?: LatestUsage();
|
|
2087
|
-
NSDictionary *fiveHour = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
2088
|
-
? usage[@"fiveHour"] : nil;
|
|
2089
|
-
id used = fiveHour[@"used_percentage"] ?: fiveHour[@"used_percent"];
|
|
2090
|
-
if (![used isKindOfClass:NSNumber.class]) return -1;
|
|
2091
|
-
NSInteger remaining = 100 - [used integerValue];
|
|
2092
|
-
return MAX((NSInteger)0, MIN((NSInteger)100, remaining));
|
|
2093
|
-
}
|
|
2094
|
-
// 回血时间,按本机时区格式化。没有这个槽位的话,带 {resetTime} 的词条会被整条跳过。
|
|
2095
|
-
- (NSString *)fiveHourResetTimeText {
|
|
2096
|
-
NSDictionary *usage = LatestClaudeUsage() ?: LatestUsage();
|
|
2097
|
-
NSDictionary *fiveHour = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
2098
|
-
? usage[@"fiveHour"] : nil;
|
|
2099
|
-
id resets = fiveHour[@"resets_at"];
|
|
2100
|
-
if (![resets isKindOfClass:NSNumber.class]) return nil;
|
|
2101
|
-
NSTimeInterval at = [resets doubleValue];
|
|
2102
|
-
if (at <= NSDate.date.timeIntervalSince1970) return nil;
|
|
2103
|
-
NSDateFormatter *formatter = [NSDateFormatter new];
|
|
2104
|
-
formatter.dateFormat = @"HH:mm";
|
|
2105
|
-
formatter.timeZone = NSTimeZone.systemTimeZone;
|
|
2106
|
-
return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:at]];
|
|
2107
|
-
}
|
|
2108
|
-
// 额度是"跨阈值"事件,不是状态事件,所以单独判档。
|
|
2109
|
-
//
|
|
2110
|
-
// 只在向下穿档时说一次:低于 20%% 就一直念叨会变成唠叨,而额度刷新是每分钟级别的,
|
|
2111
|
-
// 不设档位的话一小时预算瞬间就被烧光。回血(档位回升)时把标记还回去,
|
|
2112
|
-
// 下个周期才能再触发。
|
|
2113
|
-
- (void)considerQuotaSpeech {
|
|
2114
|
-
NSInteger remaining = [self remainingFiveHourQuotaPercent];
|
|
2115
|
-
if (remaining < 0) return;
|
|
2116
|
-
NSInteger tier;
|
|
2117
|
-
if (remaining <= 5) tier = 0;
|
|
2118
|
-
else if (remaining <= 10) tier = 1;
|
|
2119
|
-
else if (remaining <= 20) tier = 2;
|
|
2120
|
-
else tier = 3;
|
|
2121
|
-
|
|
2122
|
-
NSInteger previous = self.lastQuotaTier;
|
|
2123
|
-
self.lastQuotaTier = tier;
|
|
2124
|
-
// 首次拿到数据只记档不出声,免得每次启动都通报一遍额度。
|
|
2125
|
-
// (lastQuotaTier 的初值 0 恰好是最低档,不加这道判断的话冷启动必然误判成"刚跌到 5%"。)
|
|
2126
|
-
if (!self.lastQuotaTierInitialized) {
|
|
2127
|
-
self.lastQuotaTierInitialized = YES;
|
|
2128
|
-
return;
|
|
2129
|
-
}
|
|
2130
|
-
if (tier >= previous) return; // 回血或没跨档
|
|
2131
|
-
[self speakWithTag:PetPhraseTagQuotaLow];
|
|
2132
|
-
}
|
|
2133
|
-
- (void)buildSpeechPanelIfNeeded {
|
|
2134
|
-
if (self.speechPanel) return;
|
|
2135
|
-
NSSize glassSize = NSMakeSize(210, PetSpeechBodyHeight);
|
|
2136
|
-
NSSize size = NSMakeSize(glassSize.width + 12, glassSize.height + 12);
|
|
2137
|
-
self.speechPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, size.width, size.height)
|
|
2138
|
-
styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
|
|
2139
|
-
backing:NSBackingStoreBuffered defer:NO];
|
|
2140
|
-
self.speechPanel.opaque = NO;
|
|
2141
|
-
self.speechPanel.backgroundColor = NSColor.clearColor;
|
|
2142
|
-
self.speechPanel.hasShadow = NO;
|
|
2143
|
-
self.speechPanel.level = NSFloatingWindowLevel;
|
|
2144
|
-
self.speechPanel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
|
|
2145
|
-
NSWindowCollectionBehaviorFullScreenAuxiliary;
|
|
2146
|
-
// 气泡不抢焦点、不接受点击:它是纯播报,挡住宠物就本末倒置了。
|
|
2147
|
-
self.speechPanel.ignoresMouseEvents = YES;
|
|
2148
|
-
|
|
2149
|
-
NSView *root = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
|
|
2150
|
-
self.speechGlass = [[NSVisualEffectView alloc]
|
|
2151
|
-
initWithFrame:NSMakeRect(6, 6, glassSize.width, glassSize.height)];
|
|
2152
|
-
self.speechGlass.material = NSVisualEffectMaterialPopover;
|
|
2153
|
-
self.speechGlass.blendingMode = NSVisualEffectBlendingModeBehindWindow;
|
|
2154
|
-
self.speechGlass.state = NSVisualEffectStateActive;
|
|
2155
|
-
self.speechGlass.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
|
|
2156
|
-
self.speechGlass.wantsLayer = YES;
|
|
2157
|
-
// 圆角交给 layer 自己:cornerRadius 是 GPU 端矢量裁切,配 continuous 曲率就是
|
|
2158
|
-
// macOS 那个 squircle。位图 maskImage 换不来这个质感。
|
|
2159
|
-
self.speechGlass.layer.cornerRadius = glassSize.height / 2.0;
|
|
2160
|
-
self.speechGlass.layer.cornerCurve = kCACornerCurveContinuous;
|
|
2161
|
-
self.speechGlass.layer.masksToBounds = YES;
|
|
2162
|
-
self.speechGlass.layer.borderWidth = 1;
|
|
2163
|
-
self.speechGlass.layer.borderColor = [NSColor colorWithWhite:1 alpha:0.48].CGColor;
|
|
2164
|
-
|
|
2165
|
-
self.speechLabel = [NSTextField labelWithString:@""];
|
|
2166
|
-
self.speechLabel.frame = NSMakeRect(14, 10, glassSize.width - 28, 18);
|
|
2167
|
-
// 独立气泡里这句话是唯一元素,不与标题争,比并入状态卡时大半档。
|
|
2168
|
-
self.speechLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightMedium];
|
|
2169
|
-
self.speechLabel.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
|
|
2170
|
-
self.speechLabel.alignment = NSTextAlignmentCenter;
|
|
2171
|
-
self.speechLabel.lineBreakMode = NSLineBreakByTruncatingTail;
|
|
2172
|
-
[self.speechGlass addSubview:self.speechLabel];
|
|
2173
|
-
[root addSubview:self.speechGlass];
|
|
2174
|
-
self.speechPanel.contentView = root;
|
|
2175
|
-
}
|
|
2176
|
-
// 独立气泡只在没有状态卡时出现(有状态卡时话并进它的副行),所以固定放宠物头顶即可,
|
|
2177
|
-
// 不用再和状态卡抢位置。
|
|
2178
|
-
- (void)positionSpeechPanel {
|
|
2179
|
-
NSRect petFrame = self.panel.frame;
|
|
2180
|
-
NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
|
|
2181
|
-
NSSize size = self.speechPanel.frame.size;
|
|
2182
|
-
CGFloat x = NSMidX(petFrame) - size.width / 2.0;
|
|
2183
|
-
// 头顶放不下就翻到脚下,尾巴跟着改朝向长在顶边。
|
|
2184
|
-
CGFloat aboveY = NSMaxY(petFrame) - 6;
|
|
2185
|
-
BOOL fitsAbove = aboveY + size.height <= NSMaxY(visible) - 10;
|
|
2186
|
-
CGFloat y = fitsAbove ? aboveY : NSMinY(petFrame) - size.height + 6;
|
|
2187
|
-
x = fmax(NSMinX(visible) + 10, fmin(x, NSMaxX(visible) - size.width - 10));
|
|
2188
|
-
y = fmax(NSMinY(visible) + 10, fmin(y, NSMaxY(visible) - size.height - 10));
|
|
2189
|
-
[self.speechPanel setFrameOrigin:NSMakePoint(x, y)];
|
|
2190
|
-
}
|
|
2191
|
-
// 说一句。tag 取不到词条、预算用完、或状态卡正展开时都直接不说——
|
|
2192
|
-
// 两个泡同时挂在宠物头上会很吵。
|
|
2193
|
-
- (void)speakWithTag:(NSString *)tag {
|
|
2194
|
-
if (![self canSpeakNow]) return;
|
|
2195
|
-
NSString *text = PetPhraseForTag(tag, [self speechSlots]);
|
|
2196
|
-
if (text.length == 0) return;
|
|
2197
|
-
|
|
2198
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2199
|
-
[self.speechTimestamps addObject:@(now)];
|
|
2200
|
-
self.speechCooldownUntil = now + [self speechCooldownSeconds];
|
|
2201
|
-
|
|
2202
|
-
[self presentSpeechText:text];
|
|
2203
|
-
}
|
|
2204
|
-
// 话往哪儿显示只在这一处决定:有状态卡就并进它的副行,没有才起独立气泡。
|
|
2205
|
-
// 调试触发也必须走这里——否则看到的是现实中不会出现的画面(两个泡叠着)。
|
|
2206
|
-
- (void)presentSpeechText:(NSString *)text {
|
|
2207
|
-
if (text.length == 0) return;
|
|
2208
|
-
if (self.statusPanel.isVisible) {
|
|
2209
|
-
self.statusDetailLabel.stringValue = text;
|
|
2210
|
-
[self resizeStatusCardToFitText];
|
|
2211
|
-
[self positionAgentStatus];
|
|
2212
|
-
// 上一句的独立气泡可能还没淡完,收掉它,别和状态卡叠着。
|
|
2213
|
-
[self hideSpeechBubble];
|
|
2214
|
-
// 副行是状态卡的正文,借走说一句之后必须还回去,否则闲话会一直挂着,
|
|
2215
|
-
// 看起来像状态卡卡死了。
|
|
2216
|
-
//
|
|
2217
|
-
// 这里刻意不写 lastPetVoiceText/lastPetVoiceTag:那两个是状态文案的
|
|
2218
|
-
// 去重缓存,被闲话污染的话 restoreStatusDetail 就没有东西可还,而且
|
|
2219
|
-
// 下一次同状态事件会把闲话当成"该状态的文案"复读出来。
|
|
2220
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
2221
|
-
selector:@selector(restoreStatusDetail) object:nil];
|
|
2222
|
-
[self performSelector:@selector(restoreStatusDetail) withObject:nil
|
|
2223
|
-
afterDelay:PetSpeechDwell];
|
|
2224
|
-
return;
|
|
2225
|
-
}
|
|
2226
|
-
[self showSpeechBubbleWithText:text];
|
|
2227
|
-
}
|
|
2228
|
-
// 把副行还给状态文案。lastPetVoiceText 里存的就是当前状态本该显示的那句。
|
|
2229
|
-
- (void)restoreStatusDetail {
|
|
2230
|
-
if (!self.statusPanel.isVisible || self.lastPetVoiceText.length == 0) return;
|
|
2231
|
-
self.statusDetailLabel.stringValue = self.lastPetVoiceText;
|
|
2232
|
-
[self resizeStatusCardToFitText];
|
|
2233
|
-
[self positionAgentStatus];
|
|
2234
|
-
}
|
|
2235
|
-
- (void)showSpeechBubbleWithText:(NSString *)text {
|
|
2236
|
-
[self buildSpeechPanelIfNeeded];
|
|
2237
|
-
self.speechLabel.stringValue = text;
|
|
2238
|
-
[self resizeSpeechBubbleToFitText];
|
|
2239
|
-
[self positionSpeechPanel];
|
|
2240
|
-
self.speechPanel.alphaValue = 0;
|
|
2241
|
-
[self.speechPanel orderFront:nil];
|
|
2242
|
-
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
|
|
2243
|
-
context.duration = 0.18;
|
|
2244
|
-
self.speechPanel.animator.alphaValue = 1.0;
|
|
2245
|
-
} completionHandler:nil];
|
|
2246
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
2247
|
-
selector:@selector(hideSpeechBubble) object:nil];
|
|
2248
|
-
[self performSelector:@selector(hideSpeechBubble) withObject:nil afterDelay:PetSpeechDwell];
|
|
2249
|
-
}
|
|
2250
|
-
// 调试触发:写一个标签进 defaults,下一跳(≤3 秒)就强制弹一次独立气泡,
|
|
2251
|
-
// 绕开安静期、概率、预算和状态卡判断,弹完自动把键删掉,不会残留。
|
|
2252
|
-
// defaults write com.universewang.cc-pets CCPetsSpeechDebugTag -string idle
|
|
2253
|
-
// 标签可填 idle / done / fail / quota_low / late_night / long_session / wake
|
|
2254
|
-
- (void)consumeSpeechDebugTrigger {
|
|
2255
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
2256
|
-
id value = [defaults objectForKey:@"CCPetsSpeechDebugTag"];
|
|
2257
|
-
if (![value isKindOfClass:NSString.class] || [value length] == 0) return;
|
|
2258
|
-
[defaults removeObjectForKey:@"CCPetsSpeechDebugTag"];
|
|
2259
|
-
NSString *text = PetPhraseForTag(value, [self speechSlots]);
|
|
2260
|
-
if (text.length == 0) text = @"(这个标签取不到词条)";
|
|
2261
|
-
[self presentSpeechText:text];
|
|
2262
|
-
}
|
|
2263
|
-
- (void)hideSpeechBubble {
|
|
2264
|
-
if (!self.speechPanel) return;
|
|
2265
|
-
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
|
|
2266
|
-
context.duration = 0.22;
|
|
2267
|
-
self.speechPanel.animator.alphaValue = 0;
|
|
2268
|
-
} completionHandler:^{
|
|
2269
|
-
if (self.speechPanel.alphaValue <= 0.01) [self.speechPanel orderOut:nil];
|
|
2270
|
-
}];
|
|
2271
|
-
}
|
|
2272
|
-
// 闲着时候的自发说话。
|
|
2273
|
-
//
|
|
2274
|
-
// 光挂在 agent 事件流上是不够的:那样宠物永远只会就着工作说话,late_night /
|
|
2275
|
-
// long_session / idle 这些词条根本没有属于自己的触发时机,独立气泡也永远不会出现
|
|
2276
|
-
// (agent 事件必定先把状态卡显示出来,话就并进去了)。
|
|
2277
|
-
//
|
|
2278
|
-
// 挂在已有的客户端存活定时器上,不新起 timer——常驻唤醒一个都不该多。
|
|
2279
|
-
- (void)considerIdleSpeech {
|
|
2280
|
-
[self consumeSpeechDebugTrigger];
|
|
2281
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2282
|
-
// 真正的判断最多 30 秒做一次,3 秒一跳的定时器上不必每次都算。
|
|
2283
|
-
if (now - self.lastIdleSpeechCheck < 30.0) return;
|
|
2284
|
-
self.lastIdleSpeechCheck = now;
|
|
2285
|
-
// agent 正在干活时闭嘴——工作文案优先级最高,闲话不许顶掉它。
|
|
2286
|
-
// 注意判断的是"在不在干活",不是"状态卡在不在":状态卡只要客户端活着就常驻,
|
|
2287
|
-
// 用它当闸门等于开着终端就永远不碎碎念。
|
|
2288
|
-
if ([self agentBusyForSpeech]) return;
|
|
2289
|
-
if (![self canSpeakNow]) return;
|
|
2290
|
-
|
|
2291
|
-
// 安静多久才算"没人打扰"。复用无聊曲线那个缩放旋钮,测试时一并压缩。
|
|
2292
|
-
double scale = 1.0;
|
|
2293
|
-
id scaleValue = [NSUserDefaults.standardUserDefaults objectForKey:@"CCPetsBoredomScale"];
|
|
2294
|
-
if ([scaleValue isKindOfClass:NSNumber.class] && [scaleValue doubleValue] > 0) {
|
|
2295
|
-
scale = MIN([scaleValue doubleValue], 10.0);
|
|
2296
|
-
}
|
|
2297
|
-
PetSpeechRate rate = [self speechRate];
|
|
2298
|
-
NSTimeInterval quiet = self.lastAgentEventAt > 0 ? now - self.lastAgentEventAt : now;
|
|
2299
|
-
if (quiet < rate.quietSeconds * scale) return;
|
|
2300
|
-
|
|
2301
|
-
// 不是每次够条件都说:概率化,免得变成整点报时。
|
|
2302
|
-
if (arc4random_uniform(100) >= rate.idleChancePercent) return;
|
|
2303
|
-
|
|
2304
|
-
NSInteger hour = [NSCalendar.currentCalendar component:NSCalendarUnitHour fromDate:NSDate.date];
|
|
2305
|
-
NSTimeInterval sessionLength = self.sessionStartedAt > 0 ? now - self.sessionStartedAt : 0;
|
|
2306
|
-
if (hour >= 1 && hour < 5) [self speakWithTag:PetPhraseTagLateNight];
|
|
2307
|
-
else if (sessionLength > 90 * 60.0) [self speakWithTag:PetPhraseTagLongSession];
|
|
2308
|
-
else [self speakWithTag:PetPhraseTagIdle];
|
|
2309
|
-
}
|
|
2310
|
-
// 只在显著时刻说话,不是每个 agent 事件都冒泡。
|
|
2311
|
-
- (void)considerSpeechForRecord:(NSDictionary *)record {
|
|
2312
|
-
self.lastAgentEventAt = NSDate.date.timeIntervalSince1970;
|
|
2313
|
-
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : nil;
|
|
2314
|
-
if (tool.length > 0) self.lastSpeechTool = tool;
|
|
2315
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
2316
|
-
NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
|
|
2317
|
-
BOOL failed = [record[@"failed"] boolValue];
|
|
2318
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2319
|
-
|
|
2320
|
-
if ([event isEqualToString:@"SessionStart"]) {
|
|
2321
|
-
// 久别重逢:距上次会话超过 4 小时才算,不然每开一个终端都要寒暄一遍。
|
|
2322
|
-
BOOL longGap = self.sessionStartedAt <= 0 || now - self.sessionStartedAt > 4 * 3600.0;
|
|
2323
|
-
self.sessionStartedAt = now;
|
|
2324
|
-
self.consecutiveFailures = 0;
|
|
2325
|
-
if (longGap) [self speakWithTag:PetPhraseTagWake];
|
|
2326
|
-
return;
|
|
2327
|
-
}
|
|
2328
|
-
if (failed) {
|
|
2329
|
-
self.consecutiveFailures += 1;
|
|
2330
|
-
// 单次失败很常见,连续两次才值得出声。
|
|
2331
|
-
if (self.consecutiveFailures >= 2) [self speakWithTag:PetPhraseTagFail];
|
|
2332
|
-
return;
|
|
2333
|
-
}
|
|
2334
|
-
if ([state isEqualToString:@"completed"]) {
|
|
2335
|
-
self.consecutiveFailures = 0;
|
|
2336
|
-
NSInteger hour = [NSCalendar.currentCalendar component:NSCalendarUnitHour
|
|
2337
|
-
fromDate:NSDate.date];
|
|
2338
|
-
NSTimeInterval sessionLength = self.sessionStartedAt > 0 ? now - self.sessionStartedAt : 0;
|
|
2339
|
-
// 同一时刻可能同时满足几个情境,按"更值得一提"的顺序挑一个说,不叠着说。
|
|
2340
|
-
if (hour >= 1 && hour < 5) [self speakWithTag:PetPhraseTagLateNight];
|
|
2341
|
-
else if (sessionLength > 90 * 60.0) [self speakWithTag:PetPhraseTagLongSession];
|
|
2342
|
-
else [self speakWithTag:PetPhraseTagDone];
|
|
2343
|
-
}
|
|
2344
|
-
}
|
|
2345
|
-
#pragma mark - 宽度自适应
|
|
2346
|
-
|
|
2347
|
-
// 卡片和气泡都按文案实际宽度伸缩。固定宽度下"收工!"和"到处翻资料呢。"占一样长的条,
|
|
2348
|
-
// 前者会拖着一大截空白,看着像没加载完。
|
|
2349
|
-
// 用控件自己的 fittingSize 量,不要用 sizeWithAttributes:。
|
|
2350
|
-
// NSTextField 的 cell 有一点内部留白,纯按字符串量出来的宽度会比控件真正需要的小几个点,
|
|
2351
|
-
// 结果就是明明算着"刚好够",显示出来最后一两个字变成省略号。
|
|
2352
|
-
static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
2353
|
-
if (label.stringValue.length == 0) return 0;
|
|
2354
|
-
return ceil(label.fittingSize.width) + 2;
|
|
2355
|
-
}
|
|
2356
|
-
// 状态卡:左内边距 20 + 文字 + 间隙 8 + 图标 34 + 右内边距 14。
|
|
2357
|
-
- (void)resizeStatusCardToFitText {
|
|
2358
|
-
const CGFloat leading = 20, gap = 8, iconWidth = 34, trailing = 14;
|
|
2359
|
-
// 副行没内容时收成单行,而不是留一块空白。
|
|
2360
|
-
//
|
|
2361
|
-
// 台词全在 speech.txt 里,代码里没有兜底文案:用户把某个 state_ 小节清空了,
|
|
2362
|
-
// 副行就真的没有东西可显示。编辑器保存时会拦下这种文件,但外部编辑器绕得过去,
|
|
2363
|
-
// 所以显示层必须自己站得住。
|
|
2364
|
-
BOOL hasDetail = self.statusDetailLabel.stringValue.length > 0;
|
|
2365
|
-
CGFloat height = hasDetail ? PetStatusBodyHeight : PetStatusSingleLineHeight;
|
|
2366
|
-
CGFloat textWidth = PetMeasuredLabelWidth(self.statusTitleLabel);
|
|
2367
|
-
if (hasDetail) {
|
|
2368
|
-
textWidth = fmax(textWidth, PetMeasuredLabelWidth(self.statusDetailLabel));
|
|
2369
|
-
}
|
|
2370
|
-
CGFloat glassWidth = leading + textWidth + gap + iconWidth + trailing;
|
|
2371
|
-
glassWidth = fmax(210.0, fmin(glassWidth, 420.0));
|
|
2372
|
-
// 高度也要参与早退判断,否则单行/双行之间切换时尺寸不会更新。
|
|
2373
|
-
if (fabs(NSWidth(self.statusGlass.frame) - glassWidth) < 0.5 &&
|
|
2374
|
-
fabs(NSHeight(self.statusGlass.frame) - height) < 0.5) return;
|
|
2375
|
-
|
|
2376
|
-
NSSize panelSize = NSMakeSize(glassWidth + 12, height + 12);
|
|
2377
|
-
[self.statusPanel setContentSize:panelSize];
|
|
2378
|
-
self.statusPanel.contentView.frame = NSMakeRect(0, 0, panelSize.width, panelSize.height);
|
|
2379
|
-
self.statusGlass.frame = NSMakeRect(6, 6, glassWidth, height);
|
|
2380
|
-
self.statusShadowView.frame = NSMakeRect(6, 6, glassWidth, height);
|
|
2381
|
-
// shadowPath 是按旧尺寸算死的,卡片变宽后不重算,阴影会留在原来的形状上。
|
|
2382
|
-
CGPathRef path = CGPathCreateWithRoundedRect(self.statusShadowView.bounds,
|
|
2383
|
-
height / 2.0, height / 2.0, NULL);
|
|
2384
|
-
self.statusShadowView.layer.shadowPath = path;
|
|
2385
|
-
CGPathRelease(path);
|
|
2386
|
-
|
|
2387
|
-
CGFloat labelWidth = glassWidth - leading - gap - iconWidth - trailing;
|
|
2388
|
-
self.statusDetailLabel.hidden = !hasDetail;
|
|
2389
|
-
if (hasDetail) {
|
|
2390
|
-
self.statusTitleLabel.frame = NSMakeRect(leading, 34, labelWidth, 14);
|
|
2391
|
-
self.statusDetailLabel.frame = NSMakeRect(leading, 10, labelWidth, 22);
|
|
2392
|
-
} else {
|
|
2393
|
-
self.statusTitleLabel.frame = NSMakeRect(leading, (height - 14) / 2.0, labelWidth, 14);
|
|
2394
|
-
}
|
|
2395
|
-
self.statusIconButton.frame = NSMakeRect(glassWidth - trailing - iconWidth,
|
|
2396
|
-
(height - iconWidth) / 2.0, iconWidth, iconWidth);
|
|
2397
|
-
self.statusClickButton.frame = NSMakeRect(6, 6, glassWidth - 56, height);
|
|
2398
|
-
}
|
|
2399
|
-
|
|
2400
|
-
// 独立气泡:左右各 16 内边距,没有图标。
|
|
2401
|
-
- (void)resizeSpeechBubbleToFitText {
|
|
2402
|
-
const CGFloat padding = 16;
|
|
2403
|
-
CGFloat width = padding * 2 + PetMeasuredLabelWidth(self.speechLabel);
|
|
2404
|
-
width = fmax(96.0, fmin(width, 300.0));
|
|
2405
|
-
NSSize panelSize = NSMakeSize(width + 12, PetSpeechBodyHeight + 12);
|
|
2406
|
-
[self.speechPanel setContentSize:panelSize];
|
|
2407
|
-
self.speechPanel.contentView.frame = NSMakeRect(0, 0, panelSize.width, panelSize.height);
|
|
2408
|
-
self.speechGlass.frame = NSMakeRect(6, 6, width, PetSpeechBodyHeight);
|
|
2409
|
-
self.speechGlass.layer.cornerRadius = PetSpeechBodyHeight / 2.0;
|
|
2410
|
-
self.speechLabel.frame = NSMakeRect(padding, 10, width - padding * 2, 18);
|
|
2411
|
-
}
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
// 面板底边到"最小那颗圆点底边"的距离。定位要拿它反推面板该放多高,
|
|
2415
|
-
// 才能让圆点正好落在宠物头顶而不是悬在空中。
|
|
2416
|
-
- (void)positionAgentStatus {
|
|
2417
|
-
NSRect petFrame = self.panel.frame;
|
|
2418
|
-
NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
|
|
2419
|
-
NSSize size = self.statusPanel.frame.size;
|
|
2420
|
-
CGFloat x = NSMidX(petFrame) - size.width / 2.0;
|
|
2421
|
-
CGFloat aboveY = NSMaxY(petFrame) + 8;
|
|
2422
|
-
CGFloat belowY = NSMinY(petFrame) - size.height - 8;
|
|
2423
|
-
BOOL aboveFits = aboveY + size.height <= NSMaxY(visible) - 10;
|
|
2424
|
-
BOOL belowFits = belowY >= NSMinY(visible) + 10;
|
|
2425
|
-
self.statusBubbleAbove = aboveFits || !belowFits;
|
|
2426
|
-
CGFloat y = self.statusBubbleAbove ? aboveY : belowY;
|
|
2427
|
-
x = fmax(NSMinX(visible) + 10, fmin(x, NSMaxX(visible) - size.width - 10));
|
|
2428
|
-
y = fmax(NSMinY(visible) + 10, fmin(y, NSMaxY(visible) - size.height - 10));
|
|
2429
|
-
[self.statusPanel setFrameOrigin:NSMakePoint(x, y)];
|
|
2430
|
-
}
|
|
2431
|
-
- (void)scheduleQuotaDashboardHide {
|
|
2432
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
|
|
2433
|
-
[self performSelector:@selector(hideQuotaDashboardIfNeeded) withObject:nil afterDelay:0.28];
|
|
2434
|
-
}
|
|
2435
|
-
- (void)hideQuotaDashboardIfNeeded {
|
|
2436
|
-
if (!self.pocketHovering && !self.dashboardHovering && !self.petDragging) {
|
|
2437
|
-
[self.quotaPanel orderOut:nil];
|
|
2438
|
-
[self rescheduleUsageTimer];
|
|
2439
|
-
[self.quotaClockTimer invalidate];
|
|
2440
|
-
self.quotaClockTimer = nil;
|
|
2441
|
-
[self updateSystemMetricsTimer];
|
|
2442
|
-
}
|
|
2443
|
-
}
|
|
2444
|
-
- (void)switchPetToID:(NSString *)petID {
|
|
2445
|
-
NSArray<NSDictionary *> *options = [self petOptions];
|
|
2446
|
-
NSDictionary *option = [self petOptionWithID:petID inOptions:options];
|
|
2447
|
-
if (!option) return;
|
|
2448
|
-
NSInteger spriteRowCount = [option[@"spriteRowCount"] integerValue] ?: 9;
|
|
2449
|
-
NSImage *image = LoadPetSpriteImage(option[@"path"], NSMakeSize(140, 150), spriteRowCount);
|
|
2450
|
-
if (!image) return;
|
|
2451
|
-
[self.petView applySheet:image petID:petID rowCount:spriteRowCount];
|
|
2452
|
-
PetPhrasesSetCurrentPetID(petID);
|
|
2453
|
-
[NSUserDefaults.standardUserDefaults setObject:petID forKey:@"CCPetsSelectedSprite"];
|
|
2454
|
-
}
|
|
2455
|
-
- (BOOL)deletePetWithID:(NSString *)petID {
|
|
2456
|
-
if (![petID hasPrefix:@"external:"]) return NO;
|
|
2457
|
-
NSArray<NSDictionary *> *options = [self petOptions];
|
|
2458
|
-
NSDictionary *option = [self petOptionWithID:petID inOptions:options];
|
|
2459
|
-
if (!option) return NO;
|
|
2460
|
-
|
|
2461
|
-
NSString *name = [petID substringFromIndex:@"external:".length];
|
|
2462
|
-
if (name.length == 0 || [name containsString:@"/"] || [name isEqualToString:@"."] ||
|
|
2463
|
-
[name isEqualToString:@".."]) return NO;
|
|
2464
|
-
NSString *root = OwnPetsDirectory().stringByStandardizingPath;
|
|
2465
|
-
NSString *directory = [root stringByAppendingPathComponent:name].stringByStandardizingPath;
|
|
2466
|
-
NSString *optionDirectory = [[option[@"path"] stringByDeletingLastPathComponent] stringByStandardizingPath];
|
|
2467
|
-
if (![directory.stringByDeletingLastPathComponent isEqualToString:root] ||
|
|
2468
|
-
![optionDirectory isEqualToString:directory]) return NO;
|
|
2469
|
-
|
|
2470
|
-
NSError *error = nil;
|
|
2471
|
-
if (![NSFileManager.defaultManager removeItemAtPath:directory error:&error]) {
|
|
2472
|
-
[self showUpdateAlertWithTitle:@"无法删除素材"
|
|
2473
|
-
message:error.localizedDescription ?: @"素材目录删除失败。"];
|
|
2474
|
-
return NO;
|
|
2475
|
-
}
|
|
2476
|
-
|
|
2477
|
-
[self invalidatePetOptionsCache];
|
|
2478
|
-
if ([self.petView.currentPetID isEqualToString:petID]) {
|
|
2479
|
-
NSDictionary *fallback = [self petOptions].firstObject;
|
|
2480
|
-
if (fallback) [self switchPetToID:fallback[@"id"]];
|
|
2481
|
-
else {
|
|
2482
|
-
PetPhrasesSetCurrentPetID(nil);
|
|
2483
|
-
[NSUserDefaults.standardUserDefaults removeObjectForKey:@"CCPetsSelectedSprite"];
|
|
2484
|
-
}
|
|
2485
|
-
}
|
|
2486
|
-
return YES;
|
|
2487
|
-
}
|
|
2488
|
-
- (void)prepareAgentEventReader {
|
|
2489
|
-
NSString *path = AgentEventPath();
|
|
2490
|
-
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
2491
|
-
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
2492
|
-
if (self.agentEventReaderInitialized) {
|
|
2493
|
-
if (size < self.agentEventOffset) {
|
|
2494
|
-
self.agentEventOffset = 0;
|
|
2495
|
-
[self.agentEventPartialLine setLength:0];
|
|
2496
|
-
}
|
|
2497
|
-
[self readNewAgentEvents];
|
|
2498
|
-
return;
|
|
2499
|
-
}
|
|
2500
|
-
self.agentEventReaderInitialized = YES;
|
|
2501
|
-
self.agentEventOffset = size;
|
|
2502
|
-
if (size > 0) {
|
|
2503
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
|
|
2504
|
-
unsigned long long start = size > 65536 ? size - 65536 : 0;
|
|
2505
|
-
[handle seekToFileOffset:start];
|
|
2506
|
-
NSData *recent = [handle readDataToEndOfFile];
|
|
2507
|
-
[handle closeFile];
|
|
2508
|
-
[self processAgentEventData:recent ignoreFirstPartial:start > 0 recentOnly:YES];
|
|
2509
|
-
}
|
|
2510
|
-
}
|
|
2511
|
-
- (void)consumeAgentEventData:(NSData *)data {
|
|
2512
|
-
if (data.length == 0) return;
|
|
2513
|
-
[self.agentEventPartialLine appendData:data];
|
|
2514
|
-
const uint8_t *bytes = self.agentEventPartialLine.bytes;
|
|
2515
|
-
NSUInteger lineStart = 0;
|
|
2516
|
-
for (NSUInteger index = 0; index < self.agentEventPartialLine.length; index++) {
|
|
2517
|
-
if (bytes[index] != '\n') continue;
|
|
2518
|
-
NSData *lineData = [self.agentEventPartialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
|
|
2519
|
-
[self processAgentEventData:lineData ignoreFirstPartial:NO recentOnly:NO];
|
|
2520
|
-
lineStart = index + 1;
|
|
2521
|
-
}
|
|
2522
|
-
if (lineStart > 0) {
|
|
2523
|
-
NSData *remainder = [self.agentEventPartialLine subdataWithRange:
|
|
2524
|
-
NSMakeRange(lineStart, self.agentEventPartialLine.length - lineStart)];
|
|
2525
|
-
self.agentEventPartialLine = [remainder mutableCopy];
|
|
2526
|
-
}
|
|
2527
|
-
if (self.agentEventPartialLine.length > 1024 * 1024) [self.agentEventPartialLine setLength:0];
|
|
2528
|
-
}
|
|
2529
|
-
- (void)processAgentEventData:(NSData *)data ignoreFirstPartial:(BOOL)ignoreFirstPartial recentOnly:(BOOL)recentOnly {
|
|
2530
|
-
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
|
2531
|
-
if (!text) return;
|
|
2532
|
-
NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
|
|
2533
|
-
NSTimeInterval cutoff = [NSDate.date timeIntervalSince1970] - 5;
|
|
2534
|
-
for (NSUInteger index = 0; index < lines.count; index++) {
|
|
2535
|
-
if (ignoreFirstPartial && index == 0) continue;
|
|
2536
|
-
NSData *lineData = [lines[index] dataUsingEncoding:NSUTF8StringEncoding];
|
|
2537
|
-
if (lineData.length == 0) continue;
|
|
2538
|
-
NSDictionary *record = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
2539
|
-
if (![record isKindOfClass:NSDictionary.class]) continue;
|
|
2540
|
-
if (recentOnly && [record[@"timestamp"] doubleValue] < cutoff) continue;
|
|
2541
|
-
[self trackAgentSessionRecord:record];
|
|
2542
|
-
NSString *event = record[@"event"];
|
|
2543
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
2544
|
-
if ([event isKindOfClass:NSString.class]) {
|
|
2545
|
-
if (!self.pendingApprovalRecords) {
|
|
2546
|
-
self.pendingApprovalRecords = [NSMutableDictionary dictionary];
|
|
2547
|
-
}
|
|
2548
|
-
[self prunePendingApprovalRecords];
|
|
2549
|
-
NSString *approvalKey = [self approvalKeyForRecord:record];
|
|
2550
|
-
BOOL manualApproval = [state isEqualToString:@"approval"];
|
|
2551
|
-
if (manualApproval) {
|
|
2552
|
-
self.pendingApprovalRecords[approvalKey] = record;
|
|
2553
|
-
} else {
|
|
2554
|
-
[self.pendingApprovalRecords removeObjectForKey:approvalKey];
|
|
2555
|
-
}
|
|
2556
|
-
[self prunePendingApprovalRecords];
|
|
2557
|
-
// 多会话下不能让一个未处理的审批全局挡住其他 Agent 的所有 Hook。每条事件
|
|
2558
|
-
// 都正常驱动气泡和动画;仍在等待的审批保留在多会话记录中供用户回跳。
|
|
2559
|
-
[self displayAgentRecord:record notify:YES];
|
|
2560
|
-
}
|
|
2561
|
-
}
|
|
2562
|
-
[self refreshApprovalBadge];
|
|
2563
|
-
}
|
|
2564
|
-
- (void)readNewAgentEvents {
|
|
2565
|
-
NSString *path = AgentEventPath();
|
|
2566
|
-
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
2567
|
-
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
2568
|
-
if (size < self.agentEventOffset) self.agentEventOffset = 0;
|
|
2569
|
-
if (size == self.agentEventOffset) return;
|
|
2570
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
|
|
2571
|
-
if (!handle) return;
|
|
2572
|
-
unsigned long long start = self.agentEventOffset;
|
|
2573
|
-
[handle seekToFileOffset:start];
|
|
2574
|
-
NSData *data = [handle readDataToEndOfFile];
|
|
2575
|
-
[handle closeFile];
|
|
2576
|
-
self.agentEventOffset = start + data.length;
|
|
2577
|
-
[self consumeAgentEventData:data];
|
|
2578
|
-
}
|
|
2579
|
-
- (void)startAgentEventReader {
|
|
2580
|
-
if (self.agentEventSource) return;
|
|
2581
|
-
NSString *path = AgentEventPath();
|
|
2582
|
-
[NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
|
|
2583
|
-
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
2584
|
-
int creator = open(path.fileSystemRepresentation, O_CREAT | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR);
|
|
2585
|
-
if (creator >= 0) close(creator);
|
|
2586
|
-
int descriptor = open(path.fileSystemRepresentation, O_EVTONLY | O_CLOEXEC);
|
|
2587
|
-
if (descriptor < 0) return;
|
|
2588
|
-
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
|
|
2589
|
-
DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
|
|
2590
|
-
DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE,
|
|
2591
|
-
dispatch_get_main_queue());
|
|
2592
|
-
if (!source) {
|
|
2593
|
-
close(descriptor);
|
|
2594
|
-
return;
|
|
2595
|
-
}
|
|
2596
|
-
self.agentEventSource = source;
|
|
2597
|
-
__weak typeof(self) weakSelf = self;
|
|
2598
|
-
dispatch_source_set_event_handler(source, ^{
|
|
2599
|
-
typeof(self) strongSelf = weakSelf;
|
|
2600
|
-
if (!strongSelf) return;
|
|
2601
|
-
dispatch_source_t currentSource = strongSelf.agentEventSource;
|
|
2602
|
-
if (!currentSource) return;
|
|
2603
|
-
unsigned long flags = dispatch_source_get_data(currentSource);
|
|
2604
|
-
[strongSelf readNewAgentEvents];
|
|
2605
|
-
if (flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE)) {
|
|
2606
|
-
strongSelf.agentEventSource = nil;
|
|
2607
|
-
dispatch_source_cancel(currentSource);
|
|
2608
|
-
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
|
|
2609
|
-
dispatch_get_main_queue(), ^{ [weakSelf startAgentEventReader]; });
|
|
2610
|
-
}
|
|
2611
|
-
});
|
|
2612
|
-
dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
|
|
2613
|
-
dispatch_resume(source);
|
|
2614
|
-
[self prepareAgentEventReader];
|
|
2615
|
-
}
|
|
2616
|
-
- (void)ensureAgentEventReader:(id)sender {
|
|
2617
|
-
if (!self.agentEventSource) [self startAgentEventReader];
|
|
2618
|
-
}
|
|
2619
|
-
// 在线判定合并两个信号:包装脚本写出的客户端 pid 文件,以及该 provider 最近是否还在
|
|
2620
|
-
// 发事件。只看前者会把直接跑 claude / codex 的会话误判成离线;只看后者则在客户端退出后
|
|
2621
|
-
// 还要挂满一整个静默窗口。额度数据本身不是在线信号——它一直缓存着,用它判定会恒亮。
|
|
2622
|
-
- (void)updateQuotaLiveState {
|
|
2623
|
-
NSMutableSet<NSString *> *online = [self.liveClientProviders mutableCopy] ?: [NSMutableSet set];
|
|
2624
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2625
|
-
for (NSString *provider in self.providerActivityAt) {
|
|
2626
|
-
NSTimeInterval last = [self.providerActivityAt[provider] doubleValue];
|
|
2627
|
-
if (now - last < AgentStatusInactivityInterval) [online addObject:provider];
|
|
2628
|
-
}
|
|
2629
|
-
NSInteger count = MAX(self.liveClientCount, (NSInteger)online.count);
|
|
2630
|
-
if (self.quotaView.activeAgentCount == count &&
|
|
2631
|
-
[self.quotaView.liveProviders isEqualToSet:online] &&
|
|
2632
|
-
self.quotaView.hasUnlabeledClient == self.hasUnlabeledClient) return;
|
|
2633
|
-
self.quotaView.activeAgentCount = count;
|
|
2634
|
-
self.quotaView.liveProviders = online;
|
|
2635
|
-
self.quotaView.hasUnlabeledClient = self.hasUnlabeledClient;
|
|
2636
|
-
self.quotaView.needsDisplay = YES;
|
|
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
|
-
}
|
|
2658
|
-
- (void)refreshClientLifecycle:(id)sender {
|
|
2659
|
-
[self considerIdleSpeech];
|
|
2660
|
-
[self prunePendingApprovalRecords];
|
|
2661
|
-
NSString *clientName = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
|
|
2662
|
-
NSString *clientDirectory = [PetStateDirectory() stringByAppendingPathComponent:clientName];
|
|
2663
|
-
NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
|
|
2664
|
-
NSInteger liveClients = 0;
|
|
2665
|
-
NSMutableSet<NSString *> *providers = [NSMutableSet set];
|
|
2666
|
-
NSMutableSet<NSString *> *sessionKeys = [NSMutableSet set];
|
|
2667
|
-
BOOL unlabeled = NO;
|
|
2668
|
-
for (NSString *entry in entries) {
|
|
2669
|
-
pid_t pid = (pid_t)entry.intValue;
|
|
2670
|
-
NSString *path = [clientDirectory stringByAppendingPathComponent:entry];
|
|
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)) {
|
|
2683
|
-
[NSFileManager.defaultManager removeItemAtPath:path error:nil];
|
|
2684
|
-
continue;
|
|
2685
|
-
}
|
|
2686
|
-
liveClients += 1;
|
|
2687
|
-
if (label.length > 0 && label.length <= 32) [providers addObject:label];
|
|
2688
|
-
else unlabeled = YES;
|
|
2689
|
-
NSString *sessionKey = [self onlineAgentSessionKeyForProvider:label tty:tty];
|
|
2690
|
-
if (sessionKey.length > 0) [sessionKeys addObject:sessionKey];
|
|
2691
|
-
}
|
|
2692
|
-
// 包装脚本启动的客户端有精确的退出信号:pid 文件被回收。这一段不该被为"直接跑
|
|
2693
|
-
// claude / codex"准备的 60 秒活跃度宽限盖住,否则退出后还要挂满一分钟才转离线。
|
|
2694
|
-
// 因此某一家的 pid 文件一旦从有变无,立刻丢掉它的活跃度记录;从来没有过 pid 文件
|
|
2695
|
-
// 的(直接启动)不受影响,继续走宽限。
|
|
2696
|
-
NSSet<NSString *> *previousProviders = self.liveClientProviders;
|
|
2697
|
-
self.liveClientCount = liveClients;
|
|
2698
|
-
self.liveClientProviders = providers;
|
|
2699
|
-
self.liveAgentSessionKeys = sessionKeys;
|
|
2700
|
-
self.hasUnlabeledClient = unlabeled;
|
|
2701
|
-
[self pruneOfflineAgentSessionRecords];
|
|
2702
|
-
for (NSString *provider in previousProviders) {
|
|
2703
|
-
if (![providers containsObject:provider]) {
|
|
2704
|
-
[self.providerActivityAt removeObjectForKey:provider];
|
|
2705
|
-
}
|
|
2706
|
-
}
|
|
2707
|
-
[self updateQuotaLiveState];
|
|
2708
|
-
[self refreshDetectedProviders];
|
|
2709
|
-
[self hideAgentStatusIfClientGone];
|
|
2710
|
-
[self checkStalledAgentSessions];
|
|
2711
|
-
[self refreshApprovalBadge];
|
|
2712
|
-
// 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
|
|
2713
|
-
// Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
|
|
2714
|
-
if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
|
|
2715
|
-
}
|
|
2716
|
-
// 面板高度取决于渲染几张额度卡。quotaRoot / 毛玻璃 / quotaView 三层都是固定 frame、
|
|
2717
|
-
// 没有 autoresizingMask,所以统一在这里按 contentView 的 subviews 铺一遍,避免漏掉一层。
|
|
2718
|
-
- (void)resizeQuotaDashboard {
|
|
2719
|
-
NSSize size = NSMakeSize(QuotaLogicalWidth * QuotaScale,
|
|
2720
|
-
QuotaLogicalHeightForProviderCount([self.quotaView visibleProviders].count) * QuotaScale);
|
|
2721
|
-
if (NSEqualSizes(self.quotaPanel.frame.size, size)) return;
|
|
2722
|
-
// 只改 size 不动 origin:窗口 frame 的原点在左下,面板会朝上收缩,底边保持贴着宠物。
|
|
2723
|
-
NSRect frame = self.quotaPanel.frame;
|
|
2724
|
-
frame.size = size;
|
|
2725
|
-
[self.quotaPanel setFrame:frame display:NO];
|
|
2726
|
-
NSRect bounds = NSMakeRect(0, 0, size.width, size.height);
|
|
2727
|
-
self.quotaPanel.contentView.frame = bounds;
|
|
2728
|
-
for (NSView *subview in self.quotaPanel.contentView.subviews) subview.frame = bounds;
|
|
2729
|
-
self.quotaView.needsDisplay = YES;
|
|
2730
|
-
if (self.quotaPanel.isVisible) [self positionQuotaDashboard];
|
|
2731
|
-
}
|
|
2732
|
-
// 额度字典"非空"不等于"这家真的在用"。Claude 的 reader 刻意永不返回 nil(见
|
|
2733
|
-
// CCPetsUsage.m 里 -[ClaudeUsageReader refresh] 的注释:Token 是本机从转录数出来的,
|
|
2734
|
-
// 不能被缺失的官方额度一票否决),什么都没有时照样返回
|
|
2735
|
-
// {fiveHour: NSNull, week: NSNull, tokenUsage: 全 0},count 恒为 3。
|
|
2736
|
-
// 拿 count > 0 当证据,Claude 就永远算"检测到",卡片再也去不掉。这里只认实质证据:
|
|
2737
|
-
// 官方额度块真实存在,或者本机统计出过非零 Token。Codex 侧同一套判据也成立。
|
|
2738
|
-
static BOOL UsageShowsProviderInUse(NSDictionary *usage) {
|
|
2739
|
-
if (usage.count == 0) return NO;
|
|
2740
|
-
for (NSString *key in @[@"fiveHour", @"week"]) {
|
|
2741
|
-
if ([usage[key] isKindOfClass:NSDictionary.class]) return YES;
|
|
2742
|
-
}
|
|
2743
|
-
NSDictionary *tokenUsage = [usage[@"tokenUsage"] isKindOfClass:NSDictionary.class]
|
|
2744
|
-
? usage[@"tokenUsage"] : nil;
|
|
2745
|
-
for (NSString *key in @[@"fiveHour", @"week", @"today", @"recentWeek"]) {
|
|
2746
|
-
NSDictionary *totals = [tokenUsage[key] isKindOfClass:NSDictionary.class]
|
|
2747
|
-
? tokenUsage[key] : nil;
|
|
2748
|
-
if ([totals[@"total_tokens"] doubleValue] > 0) return YES;
|
|
2749
|
-
}
|
|
2750
|
-
return NO;
|
|
2751
|
-
}
|
|
2752
|
-
// "这台机器上有哪几家 CLI"。只增不减,并持久化:探测会瞬时失败(配置目录被改名、
|
|
2753
|
-
// 外置盘没挂上),卡片当着用户的面消失比多留一张更像 bug。
|
|
2754
|
-
- (void)refreshDetectedProviders {
|
|
2755
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
2756
|
-
NSMutableSet<NSString *> *detected = [NSMutableSet setWithArray:
|
|
2757
|
-
[defaults arrayForKey:DetectedProvidersKey] ?: @[]];
|
|
2758
|
-
if (CodexCLIDetected()) [detected addObject:@"Codex"];
|
|
2759
|
-
if (ClaudeCLIDetected()) [detected addObject:@"Claude"];
|
|
2760
|
-
// 正在跑的客户端和已经拿到的额度数据都是比目录探测更硬的证据:探测漏判也不能
|
|
2761
|
-
// 把一个正在工作、或者明明有额度的 provider 藏起来。
|
|
2762
|
-
if (self.liveClientProviders.count > 0) [detected unionSet:self.liveClientProviders];
|
|
2763
|
-
if (UsageShowsProviderInUse(self.quotaView.codexUsage)) [detected addObject:@"Codex"];
|
|
2764
|
-
if (UsageShowsProviderInUse(self.quotaView.claudeUsage)) [detected addObject:@"Claude"];
|
|
2765
|
-
if (self.quotaView.detectedProviders &&
|
|
2766
|
-
[detected isEqualToSet:self.quotaView.detectedProviders]) return;
|
|
2767
|
-
self.quotaView.detectedProviders = detected;
|
|
2768
|
-
[defaults setObject:detected.allObjects forKey:DetectedProvidersKey];
|
|
2769
|
-
[self resizeQuotaDashboard];
|
|
2770
|
-
self.quotaView.needsDisplay = YES;
|
|
2771
|
-
}
|
|
2772
|
-
- (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage {
|
|
2773
|
-
self.quotaView.codexUsage = codexUsage;
|
|
2774
|
-
self.quotaView.claudeUsage = claudeUsage;
|
|
2775
|
-
[self refreshDetectedProviders];
|
|
2776
|
-
NSDictionary *history = RecordQuotaHistory(self.quotaView.codexUsage,
|
|
2777
|
-
self.quotaView.claudeUsage);
|
|
2778
|
-
self.quotaView.codexHistory = QuotaHistorySeries(history, @"codex");
|
|
2779
|
-
self.quotaView.claudeHistory = QuotaHistorySeries(history, @"claude");
|
|
2780
|
-
self.quotaView.lastUpdatedAt = NSDate.date.timeIntervalSince1970;
|
|
2781
|
-
self.quotaView.needsDisplay = YES;
|
|
2782
|
-
}
|
|
2783
|
-
- (void)refreshUsage:(id)sender {
|
|
2784
|
-
self.lastUsageRefreshAt = NSDate.date.timeIntervalSince1970;
|
|
2785
|
-
[self.usageMonitor refreshNow];
|
|
2786
|
-
}
|
|
2787
455
|
- (void)applicationWillTerminate:(NSNotification *)notification {
|
|
2788
456
|
[self.usageMonitor stop];
|
|
2789
457
|
[self.systemMetricsTimer invalidate];
|