cc-pets 2.1.1 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CC_BRIDGE.md +5 -0
- package/CC_BRIDGE.zh-CN.md +4 -0
- package/CHANGELOG.md +40 -1
- package/CHANGELOG.zh-CN.md +40 -1
- package/CONTRIBUTING.md +54 -0
- package/CONTRIBUTING.zh-CN.md +45 -0
- package/README.md +57 -14
- package/README.zh-CN.md +56 -14
- package/Resources/Info.plist +3 -1
- package/Resources/en.lproj/InfoPlist.strings +1 -0
- package/Resources/phrases.default.en.txt +182 -0
- package/Resources/zh-Hans.lproj/InfoPlist.strings +1 -0
- package/Resources/zh-Hans.lproj/Localizable.strings +332 -0
- package/Sources/CCPets/CCPetsAppDelegate+AgentEvents.m +215 -0
- package/Sources/CCPets/CCPetsAppDelegate+AgentStatus.m +660 -0
- package/Sources/CCPets/CCPetsAppDelegate+Bridge.m +299 -0
- package/Sources/CCPets/CCPetsAppDelegate+Pets.m +185 -0
- package/Sources/CCPets/CCPetsAppDelegate+Private.h +325 -0
- package/Sources/CCPets/CCPetsAppDelegate+Quota.m +216 -0
- package/Sources/CCPets/CCPetsAppDelegate+Settings.m +226 -0
- package/Sources/CCPets/CCPetsAppDelegate+Speech.m +392 -0
- package/Sources/CCPets/CCPetsAppDelegate+Update.m +459 -0
- package/Sources/CCPets/CCPetsAppDelegate.h +13 -14
- package/Sources/CCPets/CCPetsAppDelegate.m +68 -2466
- package/Sources/CCPets/CCPetsCleanup.h +4 -0
- package/Sources/CCPets/CCPetsCleanup.m +41 -7
- package/Sources/CCPets/CCPetsEvents.m +4 -3
- package/Sources/CCPets/CCPetsL10n.h +55 -0
- package/Sources/CCPets/CCPetsL10n.m +219 -0
- package/Sources/CCPets/CCPetsPaths.h +0 -1
- package/Sources/CCPets/CCPetsPaths.m +0 -1
- package/Sources/CCPets/CCPetsPhrases.h +7 -1
- package/Sources/CCPets/CCPetsPhrases.m +86 -31
- package/Sources/CCPets/CCPetsPhrasesEditor.m +62 -64
- package/Sources/CCPets/CCPetsPreviews.m +7 -6
- package/Sources/CCPets/CCPetsUsage.h +0 -1
- package/Sources/CCPets/CCPetsUsage.m +0 -3
- package/Sources/CCPets/CCPetsVersion.h +10 -0
- package/Sources/CCPets/CCPetsVersion.m +92 -2
- package/Sources/CCPets/MenuToggleSwitch.m +3 -2
- package/Sources/CCPets/PetView.h +2 -0
- package/Sources/CCPets/PetView.m +115 -74
- package/Sources/CCPets/QuotaDashboardView.m +122 -88
- package/Sources/CCPets/main.m +16 -1
- package/bin/cc-pets +25 -20
- package/bin/claude-with-pet +2 -1
- package/bin/codex-with-pet +2 -1
- package/package.json +5 -3
- package/scripts/bridge/cli.mjs +47 -39
- package/scripts/bridge/core.mjs +28 -27
- package/scripts/bridge/hook.mjs +7 -6
- package/scripts/bridge/install.mjs +42 -19
- package/scripts/bridge/mcp-server.mjs +79 -71
- package/scripts/bridge/options.mjs +7 -6
- package/scripts/bridge/process.mjs +22 -0
- package/scripts/bridge/reservations.mjs +6 -5
- package/scripts/bridge/store.mjs +10 -9
- package/scripts/build.sh +24 -5
- package/scripts/check-l10n.mjs +168 -0
- package/scripts/configure-updater.mjs +4 -3
- package/scripts/doctor.mjs +470 -0
- package/scripts/i18n.mjs +122 -0
- package/scripts/i18n.zsh +66 -0
- package/scripts/install-app.sh +3 -2
- package/scripts/install-claude-hooks.mjs +22 -27
- package/scripts/install-codex-hooks.mjs +10 -15
- package/scripts/install-shell-integration.sh +6 -5
- package/scripts/integration-markers.mjs +51 -0
- package/scripts/locales/zh-Hans.json +366 -0
- package/scripts/pet-store.mjs +47 -45
- package/scripts/uninstall-app.sh +4 -3
- package/scripts/uninstall-integrations.mjs +24 -51
- package/scripts/uninstall-shell-integration.sh +8 -7
- /package/Resources/{phrases.default.txt → phrases.default.zh-Hans.txt} +0 -0
|
@@ -1,41 +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 "MenuChoiceRow.h"
|
|
12
|
-
#import "CCPetsGlassMenu.h"
|
|
13
|
-
#import "CCPetsBridge.h"
|
|
14
|
-
#import "MenuToggleSwitch.h"
|
|
15
|
-
#import <UserNotifications/UserNotifications.h>
|
|
16
|
-
#import <signal.h>
|
|
17
|
-
#import <sys/stat.h>
|
|
18
|
-
#import <fcntl.h>
|
|
19
|
-
#import <unistd.h>
|
|
20
|
-
#import <errno.h>
|
|
21
|
-
#import <sys/sysctl.h>
|
|
22
|
-
#import <stdlib.h>
|
|
23
|
-
|
|
24
|
-
static const NSTimeInterval PendingApprovalTTL = 24 * 60 * 60;
|
|
25
|
-
static const NSUInteger PendingApprovalLimit = 100;
|
|
26
|
-
static const NSUInteger AgentSessionRecordLimit = 20;
|
|
27
|
-
static const NSUInteger AgentSessionMenuLimit = 8;
|
|
28
|
-
static const CGFloat PetApprovalBadgeSize = 17.0;
|
|
29
|
-
// CC Bridge:轮询间隔、"最近消息"的时间窗、菜单里最多列几条。
|
|
30
|
-
static const NSTimeInterval BridgeRefreshInterval = 3.0;
|
|
31
|
-
static const NSTimeInterval BridgeRecentWindow = 30 * 60;
|
|
32
|
-
static const NSUInteger BridgeMenuDeliveryLimit = 5;
|
|
33
|
-
static const unsigned long long UpdateLogSizeLimit = 1024 * 1024;
|
|
34
|
-
static NSString *const PetInteractionPhrasesV1MigratedKey =
|
|
35
|
-
@"CCPetsInteractionPhrasesV1Migrated";
|
|
36
|
-
|
|
37
|
-
@interface CCPetsStatusClickButton : NSButton
|
|
38
|
-
@end
|
|
1
|
+
// AppDelegate 主干:启动、退出、窗口跟随。各功能模块在 CCPetsAppDelegate+<模块>.m 里,
|
|
2
|
+
// 共享常量和跨文件的方法声明见 CCPetsAppDelegate+Private.h。
|
|
3
|
+
#import "CCPetsAppDelegate+Private.h"
|
|
39
4
|
|
|
40
5
|
@implementation CCPetsStatusClickButton
|
|
41
6
|
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
|
|
@@ -45,15 +10,6 @@ static NSString *const PetInteractionPhrasesV1MigratedKey =
|
|
|
45
10
|
}
|
|
46
11
|
@end
|
|
47
12
|
|
|
48
|
-
// 待审批角标。等审批的会话按定义是停住不动的,它的时间戳只会越来越旧——状态卡
|
|
49
|
-
// 正文永远显示最新事件,会话列表又按时间倒序,两边都会把最该处理的那条推到看
|
|
50
|
-
// 不见的地方。角标把这个数字单独拎出来常驻。
|
|
51
|
-
@interface CCPetsApprovalBadgeView : NSView
|
|
52
|
-
@property(nonatomic) NSUInteger count;
|
|
53
|
-
// 默认审批红;CC Bridge 消息角标复用同一个视图,换成蓝色 / 橙色。
|
|
54
|
-
@property(nonatomic) NSColor *fillColor;
|
|
55
|
-
@end
|
|
56
|
-
|
|
57
13
|
@implementation CCPetsApprovalBadgeView
|
|
58
14
|
- (void)setCount:(NSUInteger)count {
|
|
59
15
|
if (_count == count) return;
|
|
@@ -91,1513 +47,20 @@ static NSString *const PetInteractionPhrasesV1MigratedKey =
|
|
|
91
47
|
}
|
|
92
48
|
@end
|
|
93
49
|
|
|
94
|
-
static void TrimUpdateLog(NSString *path) {
|
|
95
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
|
|
96
|
-
if (!handle) return;
|
|
97
|
-
unsigned long long size = [handle seekToEndOfFile];
|
|
98
|
-
if (size <= UpdateLogSizeLimit) {
|
|
99
|
-
[handle closeFile];
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
[handle seekToFileOffset:size - UpdateLogSizeLimit];
|
|
103
|
-
NSData *tail = [handle readDataToEndOfFile];
|
|
104
|
-
[handle closeFile];
|
|
105
|
-
[tail writeToFile:path options:NSDataWritingAtomic error:nil];
|
|
106
|
-
chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// 碎碎念的话痨程度。四道闸(每小时预算 / 两句间隔 / 静默门槛 / 出话概率)本来是
|
|
110
|
-
// 四个互相牵制的常数,单独调任何一个都不会真的变频繁——比如把冷却调到 0,
|
|
111
|
-
// 每小时 4 句的预算照样卡死。所以对用户只暴露一个档位,四个值一起走。
|
|
112
|
-
//
|
|
113
|
-
// normal 档就是改造前的原值,默认不变。
|
|
114
|
-
typedef struct {
|
|
115
|
-
NSInteger hourlyBudget;
|
|
116
|
-
NSTimeInterval cooldown;
|
|
117
|
-
NSTimeInterval quietSeconds; // 距上一次 agent 事件多久才算"没人打扰"
|
|
118
|
-
uint32_t idleChancePercent; // 每次判定(≤30 秒一次)的出话概率
|
|
119
|
-
} PetSpeechRate;
|
|
120
|
-
|
|
121
|
-
static const PetSpeechRate PetSpeechRateLow = {2, 480.0, 300.0, 15};
|
|
122
|
-
static const PetSpeechRate PetSpeechRateNormal = {4, 240.0, 180.0, 25};
|
|
123
|
-
static const PetSpeechRate PetSpeechRateHigh = {8, 120.0, 90.0, 45};
|
|
124
|
-
static const PetSpeechRate PetSpeechRateChatty = {20, 45.0, 45.0, 70};
|
|
125
|
-
|
|
126
|
-
// 档位写进 defaults 的值。字符串而不是整数:以后加档、调顺序都不会让老配置错位。
|
|
127
|
-
NSString *const PetSpeechFrequencyKey = @"CCPetsSpeechFrequency";
|
|
128
|
-
static NSString *const PetSpeechFrequencyLow = @"low";
|
|
129
|
-
static NSString *const PetSpeechFrequencyNormal = @"normal";
|
|
130
|
-
static NSString *const PetSpeechFrequencyHigh = @"high";
|
|
131
|
-
static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
132
|
-
|
|
133
50
|
@implementation AppDelegate
|
|
134
51
|
- (NSString *)applicationSupportDirectory {
|
|
135
52
|
return ApplicationSupportDirectory();
|
|
136
53
|
}
|
|
137
|
-
|
|
54
|
+
// 只有一个「好」按钮的提示框,各模块报错 / 告知结果都用它。桌宠是 LSUIElement,
|
|
55
|
+
// 不先激活的话弹窗会开在其他 App 后面。
|
|
56
|
+
- (void)showAlertWithTitle:(NSString *)title message:(NSString *)message {
|
|
138
57
|
[NSApp activateIgnoringOtherApps:YES];
|
|
139
58
|
NSAlert *alert = [NSAlert new];
|
|
140
59
|
alert.messageText = title;
|
|
141
60
|
alert.informativeText = message;
|
|
142
|
-
[alert addButtonWithTitle
|
|
61
|
+
[alert addButtonWithTitle:L(@"OK")];
|
|
143
62
|
[alert runModal];
|
|
144
63
|
}
|
|
145
|
-
- (NSDictionary *)updaterConfiguration {
|
|
146
|
-
NSString *path = [[self applicationSupportDirectory] stringByAppendingPathComponent:@"updater.json"];
|
|
147
|
-
NSData *data = [NSData dataWithContentsOfFile:path];
|
|
148
|
-
NSDictionary *configuration = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
149
|
-
return [configuration isKindOfClass:NSDictionary.class] ? configuration : nil;
|
|
150
|
-
}
|
|
151
|
-
- (BOOL)restartAfterUpdateToVersion:(NSString *)version configuration:(NSDictionary *)configuration {
|
|
152
|
-
NSString *appPath = [configuration[@"appPath"] isKindOfClass:NSString.class]
|
|
153
|
-
? [configuration[@"appPath"] stringByStandardizingPath] : nil;
|
|
154
|
-
if (appPath.length == 0 &&
|
|
155
|
-
[NSBundle.mainBundle.bundlePath.pathExtension.lowercaseString isEqualToString:@"app"]) {
|
|
156
|
-
appPath = NSBundle.mainBundle.bundlePath.stringByStandardizingPath;
|
|
157
|
-
}
|
|
158
|
-
if (appPath.length == 0) {
|
|
159
|
-
appPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Applications"]
|
|
160
|
-
stringByAppendingPathComponent:@"CC Pets.app"];
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
NSString *infoPath = [appPath stringByAppendingPathComponent:@"Contents/Info.plist"];
|
|
164
|
-
NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:infoPath];
|
|
165
|
-
NSString *installedVersion = [info[@"CFBundleShortVersionString"] isKindOfClass:NSString.class]
|
|
166
|
-
? info[@"CFBundleShortVersionString"] : nil;
|
|
167
|
-
NSString *executablePath = [appPath stringByAppendingPathComponent:@"Contents/MacOS/cc-pets"];
|
|
168
|
-
if (![installedVersion isEqualToString:version] ||
|
|
169
|
-
![NSFileManager.defaultManager isExecutableFileAtPath:executablePath]) return NO;
|
|
170
|
-
|
|
171
|
-
NSTask *restartTask = [NSTask new];
|
|
172
|
-
restartTask.executableURL = [NSURL fileURLWithPath:executablePath];
|
|
173
|
-
restartTask.arguments = @[
|
|
174
|
-
@"--restart-after-pid",
|
|
175
|
-
[NSString stringWithFormat:@"%d", NSProcessInfo.processInfo.processIdentifier],
|
|
176
|
-
appPath,
|
|
177
|
-
self.managedByCLI ? @"--managed" : @"--standalone"
|
|
178
|
-
];
|
|
179
|
-
NSError *error = nil;
|
|
180
|
-
if (![restartTask launchAndReturnError:&error]) return NO;
|
|
181
|
-
[NSApp terminate:nil];
|
|
182
|
-
return YES;
|
|
183
|
-
}
|
|
184
|
-
- (void)startUpdateToVersion:(NSString *)version {
|
|
185
|
-
if (self.updating) return;
|
|
186
|
-
[self startUpdateToVersion:version attempt:0];
|
|
187
|
-
}
|
|
188
|
-
- (void)retryUpdate:(NSArray *)context {
|
|
189
|
-
self.updating = NO;
|
|
190
|
-
[self startUpdateToVersion:context[0] attempt:[context[1] integerValue]];
|
|
191
|
-
}
|
|
192
|
-
- (void)startUpdateToVersion:(NSString *)version attempt:(NSInteger)attempt {
|
|
193
|
-
NSDictionary *configuration = [self updaterConfiguration];
|
|
194
|
-
NSString *nodePath = [configuration[@"nodePath"] isKindOfClass:NSString.class]
|
|
195
|
-
? [configuration[@"nodePath"] stringByStandardizingPath] : nil;
|
|
196
|
-
NSString *npmCliPath = [configuration[@"npmCliPath"] isKindOfClass:NSString.class]
|
|
197
|
-
? [configuration[@"npmCliPath"] stringByStandardizingPath] : nil;
|
|
198
|
-
BOOL nodeExecutable = nodePath.isAbsolutePath &&
|
|
199
|
-
[NSFileManager.defaultManager isExecutableFileAtPath:nodePath];
|
|
200
|
-
BOOL npmCliExists = npmCliPath.isAbsolutePath &&
|
|
201
|
-
[NSFileManager.defaultManager isReadableFileAtPath:npmCliPath];
|
|
202
|
-
if (!nodeExecutable || !npmCliExists) {
|
|
203
|
-
[self showUpdateAlertWithTitle:@"无法自动更新"
|
|
204
|
-
message:@"没有找到安装 CC Pets 时使用的 Node.js/npm。请先手动执行一次:\n\n"
|
|
205
|
-
"npm install -g cc-pets@latest --allow-scripts=cc-pets"];
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
NSString *supportDirectory = [self applicationSupportDirectory];
|
|
210
|
-
NSError *directoryError = nil;
|
|
211
|
-
[NSFileManager.defaultManager createDirectoryAtPath:supportDirectory
|
|
212
|
-
withIntermediateDirectories:YES attributes:nil error:&directoryError];
|
|
213
|
-
if (directoryError) {
|
|
214
|
-
[self showUpdateAlertWithTitle:@"无法自动更新" message:directoryError.localizedDescription];
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
NSString *logPath = [supportDirectory stringByAppendingPathComponent:@"update.log"];
|
|
218
|
-
[NSData.data writeToFile:logPath options:NSDataWritingAtomic error:nil];
|
|
219
|
-
chmod(logPath.fileSystemRepresentation, S_IRUSR | S_IWUSR);
|
|
220
|
-
NSFileHandle *logHandle = [NSFileHandle fileHandleForWritingAtPath:logPath];
|
|
221
|
-
if (!logHandle) {
|
|
222
|
-
[self showUpdateAlertWithTitle:@"无法自动更新" message:@"无法创建更新日志。"];
|
|
223
|
-
return;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
NSTask *task = [NSTask new];
|
|
227
|
-
task.executableURL = [NSURL fileURLWithPath:nodePath];
|
|
228
|
-
NSMutableArray<NSString *> *arguments = [@[
|
|
229
|
-
npmCliPath,
|
|
230
|
-
@"install",
|
|
231
|
-
@"--global",
|
|
232
|
-
[@"cc-pets@" stringByAppendingString:version],
|
|
233
|
-
@"--allow-scripts=cc-pets",
|
|
234
|
-
@"--prefer-online"
|
|
235
|
-
] mutableCopy];
|
|
236
|
-
if (attempt > 0) {
|
|
237
|
-
// 重试走一个一次性缓存目录:ETARGET 的成因就是本机缓存里的包元数据还没有这个
|
|
238
|
-
// 版本,--prefer-online 只是允许重新校验,命中 304 时依然拿到旧元数据。
|
|
239
|
-
// 换缓存目录能强制冷取,又不动用户真正的 npm 缓存。
|
|
240
|
-
[arguments addObjectsFromArray:@[@"--cache",
|
|
241
|
-
[supportDirectory stringByAppendingPathComponent:@"update-retry-cache"]]];
|
|
242
|
-
}
|
|
243
|
-
task.arguments = arguments;
|
|
244
|
-
NSMutableDictionary<NSString *, NSString *> *environment =
|
|
245
|
-
[NSProcessInfo.processInfo.environment mutableCopy];
|
|
246
|
-
NSString *nodeDirectory = nodePath.stringByDeletingLastPathComponent;
|
|
247
|
-
NSString *existingPath = environment[@"PATH"];
|
|
248
|
-
if (existingPath.length == 0) existingPath = @"/usr/bin:/bin:/usr/sbin:/sbin";
|
|
249
|
-
environment[@"PATH"] = [NSString stringWithFormat:@"%@:%@", nodeDirectory, existingPath];
|
|
250
|
-
task.environment = environment;
|
|
251
|
-
task.currentDirectoryURL = [NSURL fileURLWithPath:NSHomeDirectory()];
|
|
252
|
-
task.standardOutput = logHandle;
|
|
253
|
-
task.standardError = logHandle;
|
|
254
|
-
self.updating = YES;
|
|
255
|
-
self.updateTask = task;
|
|
256
|
-
__weak typeof(self) weakSelf = self;
|
|
257
|
-
task.terminationHandler = ^(NSTask *finishedTask) {
|
|
258
|
-
[logHandle closeFile];
|
|
259
|
-
TrimUpdateLog(logPath);
|
|
260
|
-
dispatch_async(dispatch_get_main_queue(), ^{
|
|
261
|
-
typeof(self) strongSelf = weakSelf;
|
|
262
|
-
if (!strongSelf) return;
|
|
263
|
-
strongSelf.updateTask = nil;
|
|
264
|
-
if (finishedTask.terminationStatus == EXIT_SUCCESS) {
|
|
265
|
-
strongSelf.updating = NO;
|
|
266
|
-
if ([strongSelf restartAfterUpdateToVersion:version configuration:configuration]) return;
|
|
267
|
-
[strongSelf showUpdateAlertWithTitle:@"更新完成"
|
|
268
|
-
message:@"CC Pets 已更新,但没有找到可自动启动的新版应用,请手动重新启动一次。"];
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
// 暂时性故障(典型是刚发布的版本报 ETARGET)自动重试一次再说,
|
|
272
|
-
// 别把一个重试就能过的问题弹成"更新失败"。updating 保持为 YES,
|
|
273
|
-
// 等待期间不接受新的更新请求。
|
|
274
|
-
NSString *log = [NSString stringWithContentsOfFile:logPath
|
|
275
|
-
encoding:NSUTF8StringEncoding error:nil];
|
|
276
|
-
if (attempt == 0 && UpdateFailureIsTransient(log)) {
|
|
277
|
-
[strongSelf performSelector:@selector(retryUpdate:)
|
|
278
|
-
withObject:@[version, @1] afterDelay:UpdateRetryDelay];
|
|
279
|
-
return;
|
|
280
|
-
}
|
|
281
|
-
strongSelf.updating = NO;
|
|
282
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
283
|
-
NSAlert *alert = [NSAlert new];
|
|
284
|
-
alert.messageText = @"更新失败";
|
|
285
|
-
alert.informativeText = [NSString stringWithFormat:
|
|
286
|
-
@"旧版本仍可继续使用。错误详情已写入:\n%@", logPath];
|
|
287
|
-
[alert addButtonWithTitle:@"打开日志"];
|
|
288
|
-
[alert addButtonWithTitle:@"关闭"];
|
|
289
|
-
if ([alert runModal] == NSAlertFirstButtonReturn) {
|
|
290
|
-
[NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:logPath]];
|
|
291
|
-
}
|
|
292
|
-
});
|
|
293
|
-
};
|
|
294
|
-
NSError *launchError = nil;
|
|
295
|
-
if (![task launchAndReturnError:&launchError]) {
|
|
296
|
-
self.updating = NO;
|
|
297
|
-
self.updateTask = nil;
|
|
298
|
-
[logHandle closeFile];
|
|
299
|
-
[self showUpdateAlertWithTitle:@"无法启动更新" message:launchError.localizedDescription];
|
|
300
|
-
return;
|
|
301
|
-
}
|
|
302
|
-
// 重试是静默的:第一次已经弹过"正在更新",再弹一次只会让人以为出了两回事。
|
|
303
|
-
if (attempt == 0) {
|
|
304
|
-
[self showUpdateAlertWithTitle:@"正在更新"
|
|
305
|
-
message:[NSString stringWithFormat:@"正在下载并安装 CC Pets %@。完成后桌宠会自动重启。", version]];
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
// 系统标准关于面板:图标取自 Info.plist,版本号用构建时注入的 CC_PETS_VERSION(与检查更新
|
|
309
|
-
// 同一口径)。桌宠是 LSUIElement,不先激活的话面板会开在其他 App 后面。
|
|
310
|
-
- (void)showAboutPanel:(id)sender {
|
|
311
|
-
NSMutableAttributedString *credits = [[NSMutableAttributedString alloc]
|
|
312
|
-
initWithString:@"Claude Code / Codex CLI 的多功能桌面宠物。\n\n"
|
|
313
|
-
attributes:@{NSFontAttributeName: [NSFont systemFontOfSize:11],
|
|
314
|
-
NSForegroundColorAttributeName: NSColor.secondaryLabelColor}];
|
|
315
|
-
NSString *homepage = @"https://github.com/Sunnyshinnny776/cc-pets";
|
|
316
|
-
[credits appendAttributedString:[[NSAttributedString alloc] initWithString:homepage
|
|
317
|
-
attributes:@{NSFontAttributeName: [NSFont systemFontOfSize:11],
|
|
318
|
-
NSLinkAttributeName: [NSURL URLWithString:homepage]}]];
|
|
319
|
-
NSMutableParagraphStyle *centered = [NSMutableParagraphStyle new];
|
|
320
|
-
centered.alignment = NSTextAlignmentCenter;
|
|
321
|
-
[credits addAttribute:NSParagraphStyleAttributeName value:centered
|
|
322
|
-
range:NSMakeRange(0, credits.length)];
|
|
323
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
324
|
-
[NSApp orderFrontStandardAboutPanelWithOptions:@{
|
|
325
|
-
NSAboutPanelOptionApplicationName: @"CC Pets",
|
|
326
|
-
NSAboutPanelOptionApplicationVersion: @CC_PETS_VERSION,
|
|
327
|
-
// 空字符串才能去掉版本号后面括号里的 CFBundleVersion(Info.plist 里没有这一项)。
|
|
328
|
-
NSAboutPanelOptionVersion: @"",
|
|
329
|
-
NSAboutPanelOptionCredits: credits
|
|
330
|
-
}];
|
|
331
|
-
}
|
|
332
|
-
- (void)checkForUpdates:(id)sender {
|
|
333
|
-
if (self.checkingForUpdate || self.updating) return;
|
|
334
|
-
self.checkingForUpdate = YES;
|
|
335
|
-
NSURL *url = [NSURL URLWithString:@"https://registry.npmjs.org/cc-pets/latest"];
|
|
336
|
-
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
|
|
337
|
-
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
|
|
338
|
-
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
|
|
339
|
-
__weak typeof(self) weakSelf = self;
|
|
340
|
-
NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithRequest:request
|
|
341
|
-
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
|
|
342
|
-
dispatch_async(dispatch_get_main_queue(), ^{
|
|
343
|
-
typeof(self) strongSelf = weakSelf;
|
|
344
|
-
if (!strongSelf) return;
|
|
345
|
-
strongSelf.checkingForUpdate = NO;
|
|
346
|
-
NSHTTPURLResponse *httpResponse = [response isKindOfClass:NSHTTPURLResponse.class]
|
|
347
|
-
? (NSHTTPURLResponse *)response : nil;
|
|
348
|
-
NSDictionary *metadata = data
|
|
349
|
-
? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
350
|
-
NSString *latestVersion = [metadata[@"version"] isKindOfClass:NSString.class]
|
|
351
|
-
? metadata[@"version"] : nil;
|
|
352
|
-
BOOL valid = NO;
|
|
353
|
-
NSComparisonResult comparison = CompareStableVersions(@CC_PETS_VERSION, latestVersion, &valid);
|
|
354
|
-
if (error || httpResponse.statusCode != 200 || !valid) {
|
|
355
|
-
NSString *message = error.localizedDescription ?: @"npm Registry 返回了无效的版本信息,请稍后重试。";
|
|
356
|
-
[strongSelf showUpdateAlertWithTitle:@"检查更新失败" message:message];
|
|
357
|
-
return;
|
|
358
|
-
}
|
|
359
|
-
if (comparison != NSOrderedAscending) {
|
|
360
|
-
[strongSelf showUpdateAlertWithTitle:@"已是最新版本"
|
|
361
|
-
message:[NSString stringWithFormat:@"当前版本:%@", @CC_PETS_VERSION]];
|
|
362
|
-
return;
|
|
363
|
-
}
|
|
364
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
365
|
-
NSAlert *alert = [NSAlert new];
|
|
366
|
-
alert.messageText = @"发现新版本";
|
|
367
|
-
alert.informativeText = [NSString stringWithFormat:
|
|
368
|
-
@"当前版本:%@\n最新版本:%@\n\n是否立即更新?", @CC_PETS_VERSION, latestVersion];
|
|
369
|
-
[alert addButtonWithTitle:@"立即更新"];
|
|
370
|
-
[alert addButtonWithTitle:@"稍后"];
|
|
371
|
-
if ([alert runModal] == NSAlertFirstButtonReturn) {
|
|
372
|
-
[strongSelf startUpdateToVersion:latestVersion];
|
|
373
|
-
}
|
|
374
|
-
});
|
|
375
|
-
}];
|
|
376
|
-
[task resume];
|
|
377
|
-
}
|
|
378
|
-
- (NSString *)systemMetricKeyForTag:(NSInteger)tag {
|
|
379
|
-
if (tag == 1) return SystemCPUEnabledKey;
|
|
380
|
-
if (tag == 2) return SystemTemperatureEnabledKey;
|
|
381
|
-
if (tag == 3) return SystemMemoryEnabledKey;
|
|
382
|
-
return nil;
|
|
383
|
-
}
|
|
384
|
-
- (void)applySystemMetricPreferences {
|
|
385
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
386
|
-
self.quotaView.systemCPUEnabled = [defaults boolForKey:SystemCPUEnabledKey];
|
|
387
|
-
self.quotaView.systemTemperatureEnabled =
|
|
388
|
-
[defaults boolForKey:SystemTemperatureEnabledKey];
|
|
389
|
-
self.quotaView.systemMemoryEnabled = [defaults boolForKey:SystemMemoryEnabledKey];
|
|
390
|
-
self.quotaView.needsDisplay = YES;
|
|
391
|
-
}
|
|
392
|
-
- (void)applyUsageDisplayModePreferences {
|
|
393
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
394
|
-
self.quotaView.codexShowsAPIUsage =
|
|
395
|
-
[[defaults stringForKey:CodexUsageDisplayModeKey] isEqualToString:@"api"];
|
|
396
|
-
self.quotaView.claudeShowsAPIUsage =
|
|
397
|
-
[[defaults stringForKey:ClaudeUsageDisplayModeKey] isEqualToString:@"api"];
|
|
398
|
-
self.quotaView.needsDisplay = YES;
|
|
399
|
-
}
|
|
400
|
-
- (void)setUsageDisplayModeFromControl:(NSButton *)sender {
|
|
401
|
-
NSString *key = sender.tag == 1 ? CodexUsageDisplayModeKey
|
|
402
|
-
: (sender.tag == 2 ? ClaudeUsageDisplayModeKey : nil);
|
|
403
|
-
NSString *mode = sender.state == NSControlStateValueOn ? @"api" : @"subscription";
|
|
404
|
-
if (!key) return;
|
|
405
|
-
[NSUserDefaults.standardUserDefaults setObject:mode forKey:key];
|
|
406
|
-
[self applyUsageDisplayModePreferences];
|
|
407
|
-
// 展示模式决定了会话要回溯多远(订阅 8 天 / API 到上月月初),切换之后必须重新聚合,
|
|
408
|
-
// 否则刚打开 API 视图时手里只有一段按 8 天窗口扫出来的数据。
|
|
409
|
-
[self refreshUsage:nil];
|
|
410
|
-
}
|
|
411
|
-
- (void)toggleSystemMetric:(NSButton *)sender {
|
|
412
|
-
NSString *key = [self systemMetricKeyForTag:sender.tag];
|
|
413
|
-
if (!key) return;
|
|
414
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
415
|
-
BOOL enabled = ![defaults boolForKey:key];
|
|
416
|
-
[defaults setBool:enabled forKey:key];
|
|
417
|
-
sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
418
|
-
[self applySystemMetricPreferences];
|
|
419
|
-
[self updateSystemMetricsTimer];
|
|
420
|
-
}
|
|
421
|
-
// 开关打开时立刻导入一次,不用等下次启动——用户点开关就是想现在看到那些素材。
|
|
422
|
-
- (void)toggleImportCodexPets:(NSButton *)sender {
|
|
423
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
424
|
-
BOOL enabled = ![defaults boolForKey:ImportCodexPetsKey];
|
|
425
|
-
[defaults setBool:enabled forKey:ImportCodexPetsKey];
|
|
426
|
-
sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
427
|
-
if (!enabled) return;
|
|
428
|
-
NSUInteger imported = ImportCodexPets();
|
|
429
|
-
if (imported == 0) return;
|
|
430
|
-
[self invalidatePetOptionsCache];
|
|
431
|
-
[self showImportedCodexPetsAlert:imported];
|
|
432
|
-
}
|
|
433
|
-
- (void)showImportedCodexPetsAlert:(NSUInteger)imported {
|
|
434
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
435
|
-
NSAlert *alert = [NSAlert new];
|
|
436
|
-
alert.messageText = @"已导入 Codex 素材";
|
|
437
|
-
[alert addButtonWithTitle:@"好"];
|
|
438
|
-
[alert runModal];
|
|
439
|
-
}
|
|
440
|
-
- (NSString *)notificationKeyForTag:(NSInteger)tag {
|
|
441
|
-
if (tag == 1) return NotificationCompletionKey;
|
|
442
|
-
if (tag == 2) return NotificationFailureKey;
|
|
443
|
-
if (tag == 3) return NotificationApprovalKey;
|
|
444
|
-
if (tag == 4) return NotificationStallKey;
|
|
445
|
-
return nil;
|
|
446
|
-
}
|
|
447
|
-
// sender 是菜单里的 MenuChoiceRowView,勾选状态由它自己更新。
|
|
448
|
-
- (void)setPanelTheme:(MenuChoiceRowView *)sender {
|
|
449
|
-
NSString *theme = sender.representedObject;
|
|
450
|
-
if (![@[@"classic", @"liquid"] containsObject:theme]) return;
|
|
451
|
-
[NSUserDefaults.standardUserDefaults setObject:theme forKey:CCPetsPanelThemeKey];
|
|
452
|
-
[self.statusGlass applyTheme];
|
|
453
|
-
[self.speechGlass applyTheme];
|
|
454
|
-
[self.quotaGlass applyTheme];
|
|
455
|
-
self.statusShadowView.hidden = self.statusGlass.usesLiquidGlass;
|
|
456
|
-
self.quotaView.usesLiquidGlass = self.quotaGlass.usesLiquidGlass;
|
|
457
|
-
self.quotaView.cardScrimAlpha = CCPetsGlassCardScrimAlpha();
|
|
458
|
-
self.quotaView.needsDisplay = YES;
|
|
459
|
-
[self applyBubbleTextStyle];
|
|
460
|
-
// quotaView 换了父视图,mouseExited 不一定会送达;切主题是在宠物右键菜单里点的,
|
|
461
|
-
// 鼠标此刻不在面板上,直接复位,免得面板一直当作"悬停中"不收起。
|
|
462
|
-
self.dashboardHovering = NO;
|
|
463
|
-
}
|
|
464
|
-
// 状态卡和说话气泡原来是浅色磨砂配深色字;换成原生清透玻璃后背景是任意壁纸加一层
|
|
465
|
-
// 压暗,深色字会看不见,改成白字加贴字形的投影,和额度面板一致。
|
|
466
|
-
- (void)applyBubbleTextStyle {
|
|
467
|
-
NSShadow *shadow = [NSShadow new];
|
|
468
|
-
shadow.shadowColor = [NSColor colorWithWhite:0 alpha:0.45];
|
|
469
|
-
shadow.shadowBlurRadius = 2;
|
|
470
|
-
shadow.shadowOffset = NSMakeSize(0, -0.5);
|
|
471
|
-
BOOL statusLiquid = self.statusGlass.usesLiquidGlass;
|
|
472
|
-
self.statusTitleLabel.textColor = statusLiquid ? [NSColor colorWithWhite:1 alpha:0.78]
|
|
473
|
-
: [NSColor colorWithWhite:0.42 alpha:0.90];
|
|
474
|
-
self.statusDetailLabel.textColor = statusLiquid ? [NSColor colorWithWhite:1 alpha:0.97]
|
|
475
|
-
: [NSColor colorWithWhite:0.12 alpha:0.96];
|
|
476
|
-
self.statusTitleLabel.shadow = statusLiquid ? shadow : nil;
|
|
477
|
-
self.statusDetailLabel.shadow = statusLiquid ? shadow : nil;
|
|
478
|
-
BOOL speechLiquid = self.speechGlass.usesLiquidGlass;
|
|
479
|
-
self.speechLabel.textColor = speechLiquid ? [NSColor colorWithWhite:1 alpha:0.97]
|
|
480
|
-
: [NSColor colorWithWhite:0.10 alpha:0.96];
|
|
481
|
-
self.speechLabel.shadow = speechLiquid ? shadow : nil;
|
|
482
|
-
}
|
|
483
|
-
- (void)setGlassDimLevel:(MenuChoiceRowView *)sender {
|
|
484
|
-
NSNumber *level = sender.representedObject;
|
|
485
|
-
if (![CCPetsGlassDimLevels() containsObject:level]) return;
|
|
486
|
-
[NSUserDefaults.standardUserDefaults setObject:level forKey:CCPetsGlassDimKey];
|
|
487
|
-
[self.quotaGlass applyDimLevel];
|
|
488
|
-
[self.statusGlass applyDimLevel];
|
|
489
|
-
[self.speechGlass applyDimLevel];
|
|
490
|
-
self.quotaView.cardScrimAlpha = CCPetsGlassCardScrimAlpha();
|
|
491
|
-
self.quotaView.needsDisplay = YES;
|
|
492
|
-
}
|
|
493
|
-
- (void)toggleSpeech:(NSButton *)sender {
|
|
494
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
495
|
-
id current = [defaults objectForKey:@"CCPetsSpeechEnabled"];
|
|
496
|
-
BOOL enabled = current == nil ? YES : [current boolValue];
|
|
497
|
-
[defaults setBool:!enabled forKey:@"CCPetsSpeechEnabled"];
|
|
498
|
-
sender.state = !enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
499
|
-
if (enabled) [self hideSpeechBubble];
|
|
500
|
-
}
|
|
501
|
-
- (void)togglePetInteraction:(NSButton *)sender {
|
|
502
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
503
|
-
BOOL enabled = ![defaults boolForKey:PetInteractionEnabledKey];
|
|
504
|
-
[defaults setBool:enabled forKey:PetInteractionEnabledKey];
|
|
505
|
-
sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
506
|
-
}
|
|
507
|
-
- (void)setPetInteractionHeartThreshold:(NSMenuItem *)sender {
|
|
508
|
-
NSNumber *value = [sender.representedObject isKindOfClass:NSNumber.class] ?
|
|
509
|
-
sender.representedObject : @3;
|
|
510
|
-
[NSUserDefaults.standardUserDefaults setInteger:MAX((NSInteger)2, value.integerValue)
|
|
511
|
-
forKey:PetInteractionHeartThresholdKey];
|
|
512
|
-
}
|
|
513
|
-
- (void)setPetInteractionAnnoyedThreshold:(NSMenuItem *)sender {
|
|
514
|
-
NSNumber *value = [sender.representedObject isKindOfClass:NSNumber.class] ?
|
|
515
|
-
sender.representedObject : @10;
|
|
516
|
-
NSInteger heart = MAX((NSInteger)2, [NSUserDefaults.standardUserDefaults
|
|
517
|
-
integerForKey:PetInteractionHeartThresholdKey]);
|
|
518
|
-
[NSUserDefaults.standardUserDefaults setInteger:MAX(heart + 1, value.integerValue)
|
|
519
|
-
forKey:PetInteractionAnnoyedThresholdKey];
|
|
520
|
-
}
|
|
521
|
-
- (void)setPetInteractionInterval:(NSMenuItem *)sender {
|
|
522
|
-
NSNumber *value = [sender.representedObject isKindOfClass:NSNumber.class] ?
|
|
523
|
-
sender.representedObject : @1.2;
|
|
524
|
-
[NSUserDefaults.standardUserDefaults setDouble:MAX(0.4, MIN(3.0, value.doubleValue))
|
|
525
|
-
forKey:PetInteractionIntervalKey];
|
|
526
|
-
}
|
|
527
|
-
// 频率档位。改完立刻生效——四道闸都是现读的,不缓存。
|
|
528
|
-
// 顺手把冷却清掉,否则刚调高档位还要等完上一档的冷却才见效,会让人以为没生效。
|
|
529
|
-
- (void)setSpeechFrequency:(NSMenuItem *)sender {
|
|
530
|
-
NSString *value = [sender.representedObject isKindOfClass:NSString.class] ?
|
|
531
|
-
sender.representedObject : PetSpeechFrequencyNormal;
|
|
532
|
-
[NSUserDefaults.standardUserDefaults setObject:value forKey:PetSpeechFrequencyKey];
|
|
533
|
-
self.speechCooldownUntil = 0;
|
|
534
|
-
self.lastIdleSpeechCheck = 0;
|
|
535
|
-
}
|
|
536
|
-
// 台词交给内置编辑器,不再 openURL: 丢给"文本编辑"。
|
|
537
|
-
//
|
|
538
|
-
// 换掉的理由是反馈:系统编辑器保存完什么都不会说,小节名拼错、句子超 30 字、槽位
|
|
539
|
-
// 写错名字全是静默失效,用户只知道"改了没用"。内置编辑器保存时校验并当场报出来,
|
|
540
|
-
// 还能"试说一句"直接听效果。
|
|
541
|
-
- (void)editPhrasesFile:(id)sender {
|
|
542
|
-
// 编辑器只管文本,不认识气泡;把"说出来"这一步作为回调注入。
|
|
543
|
-
__weak typeof(self) weakSelf = self;
|
|
544
|
-
[PetPhrasesEditorController setSpeakHandler:^(NSString *text) {
|
|
545
|
-
[weakSelf presentSpeechText:text];
|
|
546
|
-
}];
|
|
547
|
-
[PetPhrasesEditorController present];
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
- (void)toggleNotification:(NSButton *)sender {
|
|
551
|
-
NSString *key = [self notificationKeyForTag:sender.tag];
|
|
552
|
-
if (!key) return;
|
|
553
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
554
|
-
if ([defaults boolForKey:key]) {
|
|
555
|
-
[defaults setBool:NO forKey:key];
|
|
556
|
-
sender.state = NSControlStateValueOff;
|
|
557
|
-
return;
|
|
558
|
-
}
|
|
559
|
-
[UNUserNotificationCenter.currentNotificationCenter
|
|
560
|
-
requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound
|
|
561
|
-
completionHandler:^(BOOL granted, NSError *error) {
|
|
562
|
-
dispatch_async(dispatch_get_main_queue(), ^{
|
|
563
|
-
if (granted) {
|
|
564
|
-
[defaults setBool:YES forKey:key];
|
|
565
|
-
sender.state = NSControlStateValueOn;
|
|
566
|
-
} else {
|
|
567
|
-
sender.state = NSControlStateValueOff;
|
|
568
|
-
NSString *message = error.localizedDescription ?:
|
|
569
|
-
@"请在“系统设置 → 通知 → CC Pets”中允许通知后重试。";
|
|
570
|
-
[self showUpdateAlertWithTitle:@"无法启用系统通知" message:message];
|
|
571
|
-
}
|
|
572
|
-
});
|
|
573
|
-
}];
|
|
574
|
-
}
|
|
575
|
-
- (void)sendNotificationWithTitle:(NSString *)title body:(NSString *)body {
|
|
576
|
-
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
|
|
577
|
-
content.title = title;
|
|
578
|
-
content.body = body;
|
|
579
|
-
content.sound = UNNotificationSound.defaultSound;
|
|
580
|
-
NSString *identifier = [@"cc-pets-" stringByAppendingString:NSUUID.UUID.UUIDString];
|
|
581
|
-
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
|
|
582
|
-
content:content trigger:nil];
|
|
583
|
-
[UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:request
|
|
584
|
-
withCompletionHandler:nil];
|
|
585
|
-
}
|
|
586
|
-
- (void)notifyForRecord:(NSDictionary *)record {
|
|
587
|
-
NSString *event = record[@"event"];
|
|
588
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
589
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
590
|
-
if (provider.length == 0) provider = @"Agent";
|
|
591
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
592
|
-
if ([event isEqualToString:@"PermissionRequest"] &&
|
|
593
|
-
![state isEqualToString:@"auto_review"] &&
|
|
594
|
-
[defaults boolForKey:NotificationApprovalKey]) {
|
|
595
|
-
[self sendNotificationWithTitle:@"等待审批"
|
|
596
|
-
body:[NSString stringWithFormat:@"%@ 正在等待操作。", provider]];
|
|
597
|
-
} else if ([event isEqualToString:@"StopFailure"] &&
|
|
598
|
-
[defaults boolForKey:NotificationFailureKey]) {
|
|
599
|
-
[self sendNotificationWithTitle:@"任务失败"
|
|
600
|
-
body:[NSString stringWithFormat:@"%@ 的任务执行失败。", provider]];
|
|
601
|
-
} else if (([event isEqualToString:@"Stop"] || [event isEqualToString:@"SessionEnd"]) &&
|
|
602
|
-
[defaults boolForKey:NotificationCompletionKey]) {
|
|
603
|
-
[self sendNotificationWithTitle:@"任务完成"
|
|
604
|
-
body:[NSString stringWithFormat:@"%@ 已完成当前任务。", provider]];
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
- (NSString *)statusTextForState:(NSString *)state tool:(NSString *)tool {
|
|
608
|
-
if ([state isEqualToString:@"starting"]) return @"正在启动";
|
|
609
|
-
if ([state isEqualToString:@"idle"]) return @"待机中";
|
|
610
|
-
if ([state isEqualToString:@"thinking"]) return @"正在思考";
|
|
611
|
-
if ([state isEqualToString:@"auto_review"]) return @"自动审批中";
|
|
612
|
-
if ([state isEqualToString:@"approval"]) return @"等待审批";
|
|
613
|
-
if ([state isEqualToString:@"subagent"]) return @"子 Agent 工作中";
|
|
614
|
-
if ([state isEqualToString:@"tool_completed"]) return @"操作已完成";
|
|
615
|
-
if ([state isEqualToString:@"tool_failed"]) return @"工具执行失败";
|
|
616
|
-
if ([state isEqualToString:@"completed"]) return @"任务已完成";
|
|
617
|
-
if ([state isEqualToString:@"failed"]) return @"任务失败";
|
|
618
|
-
if ([state isEqualToString:@"notification"]) return @"需要关注";
|
|
619
|
-
if ([state isEqualToString:@"tool"]) {
|
|
620
|
-
NSString *lower = tool.lowercaseString;
|
|
621
|
-
if ([lower containsString:@"bash"] || [lower containsString:@"exec"] ||
|
|
622
|
-
[lower containsString:@"shell"] || [lower containsString:@"terminal"]) return @"正在执行命令";
|
|
623
|
-
if ([lower containsString:@"patch"] || [lower containsString:@"edit"] ||
|
|
624
|
-
[lower containsString:@"write"]) return @"正在编辑文件";
|
|
625
|
-
if ([lower containsString:@"read"] || [lower containsString:@"search"] ||
|
|
626
|
-
[lower containsString:@"find"] || [lower containsString:@"grep"] ||
|
|
627
|
-
[lower containsString:@"glob"] || [lower containsString:@"web"] ||
|
|
628
|
-
[lower hasPrefix:@"mcp__"]) return @"正在查找资料";
|
|
629
|
-
if ([lower containsString:@"task"] || [lower containsString:@"agent"]) return @"子 Agent 工作中";
|
|
630
|
-
return @"正在使用工具";
|
|
631
|
-
}
|
|
632
|
-
return @"正在工作";
|
|
633
|
-
}
|
|
634
|
-
// 状态卡副行的正文。每个 hook 状态都由宠物来讲,标题仍然给事实。
|
|
635
|
-
//
|
|
636
|
-
// 这不是"额外说话",是把原来的样板文案整体换成宠物口吻,所以不受说话预算限制——
|
|
637
|
-
// 状态本来就在变,每次变化说一句是应该的。预算只管情绪句那一层。
|
|
638
|
-
- (NSString *)petVoiceTagForState:(NSString *)state tool:(NSString *)tool {
|
|
639
|
-
if ([state isEqualToString:@"starting"]) return PetPhraseTagStateStarting;
|
|
640
|
-
if ([state isEqualToString:@"idle"]) return PetPhraseTagStateIdle;
|
|
641
|
-
if ([state isEqualToString:@"thinking"]) return PetPhraseTagStateThinking;
|
|
642
|
-
if ([state isEqualToString:@"auto_review"]) return PetPhraseTagStateAutoReview;
|
|
643
|
-
if ([state isEqualToString:@"approval"]) return PetPhraseTagStateApproval;
|
|
644
|
-
if ([state isEqualToString:@"subagent"]) return PetPhraseTagStateSubagent;
|
|
645
|
-
if ([state isEqualToString:@"tool_completed"]) return PetPhraseTagStateToolDone;
|
|
646
|
-
if ([state isEqualToString:@"tool_failed"]) return PetPhraseTagStateToolFailed;
|
|
647
|
-
if ([state isEqualToString:@"completed"]) return PetPhraseTagStateCompleted;
|
|
648
|
-
if ([state isEqualToString:@"failed"]) return PetPhraseTagStateFailed;
|
|
649
|
-
if ([state isEqualToString:@"notification"]) return PetPhraseTagStateNotification;
|
|
650
|
-
if ([state isEqualToString:@"tool"]) {
|
|
651
|
-
// 工具四分类和标题那边同源。原来副行只有一句"正在调用工具…"覆盖全部四类,
|
|
652
|
-
// 分开之后副行的信息量反而比改造前更大。
|
|
653
|
-
NSString *lower = tool.lowercaseString;
|
|
654
|
-
if ([lower containsString:@"bash"] || [lower containsString:@"exec"] ||
|
|
655
|
-
[lower containsString:@"shell"] || [lower containsString:@"terminal"]) {
|
|
656
|
-
return PetPhraseTagStateToolBash;
|
|
657
|
-
}
|
|
658
|
-
if ([lower containsString:@"patch"] || [lower containsString:@"edit"] ||
|
|
659
|
-
[lower containsString:@"write"]) return PetPhraseTagStateToolEdit;
|
|
660
|
-
if ([lower containsString:@"read"] || [lower containsString:@"search"] ||
|
|
661
|
-
[lower containsString:@"find"] || [lower containsString:@"grep"] ||
|
|
662
|
-
[lower containsString:@"glob"] || [lower containsString:@"web"] ||
|
|
663
|
-
[lower hasPrefix:@"mcp__"]) return PetPhraseTagStateToolRead;
|
|
664
|
-
if ([lower containsString:@"task"] || [lower containsString:@"agent"]) {
|
|
665
|
-
return PetPhraseTagStateSubagent;
|
|
666
|
-
}
|
|
667
|
-
return PetPhraseTagStateTool;
|
|
668
|
-
}
|
|
669
|
-
return PetPhraseTagStateTool;
|
|
670
|
-
}
|
|
671
|
-
- (NSString *)statusDetailForState:(NSString *)state tool:(NSString *)tool {
|
|
672
|
-
NSString *tag = [self petVoiceTagForState:state tool:tool];
|
|
673
|
-
// 同一个状态连着来一串事件时不重摇,否则副行会不停闪。一次状态转换说一句就够。
|
|
674
|
-
if ([tag isEqualToString:self.lastPetVoiceTag] && self.lastPetVoiceText.length > 0) {
|
|
675
|
-
return self.lastPetVoiceText;
|
|
676
|
-
}
|
|
677
|
-
NSString *text = PetPhraseForTag(tag, [self speechSlots]);
|
|
678
|
-
self.lastPetVoiceTag = tag;
|
|
679
|
-
self.lastPetVoiceText = text;
|
|
680
|
-
return text;
|
|
681
|
-
}
|
|
682
|
-
- (NSColor *)statusColorForState:(NSString *)state {
|
|
683
|
-
if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) {
|
|
684
|
-
return [NSColor colorWithRed:0.18 green:0.68 blue:0.35 alpha:1];
|
|
685
|
-
}
|
|
686
|
-
if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) {
|
|
687
|
-
return [NSColor colorWithRed:0.86 green:0.28 blue:0.28 alpha:1];
|
|
688
|
-
}
|
|
689
|
-
if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) {
|
|
690
|
-
return [NSColor colorWithRed:0.92 green:0.58 blue:0.12 alpha:1];
|
|
691
|
-
}
|
|
692
|
-
// 待机是"没在干活",用中性灰和工作中的蓝拉开距离。
|
|
693
|
-
if ([state isEqualToString:@"idle"]) return [NSColor colorWithWhite:0.55 alpha:1];
|
|
694
|
-
return [NSColor colorWithRed:0.33 green:0.53 blue:0.78 alpha:1];
|
|
695
|
-
}
|
|
696
|
-
- (NSString *)statusSymbolForState:(NSString *)state {
|
|
697
|
-
if ([state isEqualToString:@"completed"] || [state isEqualToString:@"tool_completed"]) return @"checkmark";
|
|
698
|
-
if ([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]) return @"xmark";
|
|
699
|
-
if ([state isEqualToString:@"approval"] || [state isEqualToString:@"notification"]) return @"exclamationmark";
|
|
700
|
-
if ([state isEqualToString:@"idle"]) return @"zzz";
|
|
701
|
-
return @"ellipsis";
|
|
702
|
-
}
|
|
703
|
-
// Codex / Claude 退出时不会补发结束事件:包装脚本最后一行是 exec,自身已经被
|
|
704
|
-
// 替换掉,装不上 EXIT trap。唯一可靠的退出信号是客户端 pid 文件被回收。
|
|
705
|
-
// 没有这一步的话,“正在启动”只能等 60 秒无活动才消失,而另一个 provider 的事件
|
|
706
|
-
// 会不断把这 60 秒重置掉——用户关掉所有 Codex 窗口后仍然看到“Codex 正在启动”。
|
|
707
|
-
- (void)hideAgentStatusIfClientGone {
|
|
708
|
-
if (!self.hasAgentStatus || self.hasUnlabeledClient) return;
|
|
709
|
-
NSString *provider = self.lastStatusProvider;
|
|
710
|
-
if (provider.length == 0 || [self.liveClientProviders containsObject:provider]) return;
|
|
711
|
-
// 不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid 文件,只能靠
|
|
712
|
-
// “最近还在发事件”证明自己活着,所以这里必须留一段静默宽限再清。
|
|
713
|
-
if ([NSDate.date timeIntervalSince1970] - self.lastStatusTimestamp < AgentStatusOrphanInterval) return;
|
|
714
|
-
[self hideAgentStatus];
|
|
715
|
-
}
|
|
716
|
-
- (void)hideAgentStatus {
|
|
717
|
-
// 卡在审批的会话不该跟着沉默一起消失。60 秒没有新事件时,气泡不清场,而是回落
|
|
718
|
-
// 到最近那条审批:这样"有人在等你确认"始终有个落点,点卡片就能跳回那个终端,
|
|
719
|
-
// 角标也不会随面板一起被收走。
|
|
720
|
-
//
|
|
721
|
-
// 这不是把旧的"审批全局优先"逻辑搬回来——那一版在事件流里拦截,一个未处理的
|
|
722
|
-
// 审批会把其他 Agent 的所有 Hook 全挡住。这里只在完全没有新事件时才接管,任何
|
|
723
|
-
// 一条新事件都照常刷新正文。
|
|
724
|
-
NSArray<NSDictionary *> *pending = [self pendingApprovalSessionRecords];
|
|
725
|
-
if (self.hasAgentStatus && pending.count > 0) {
|
|
726
|
-
[self performSelector:@selector(hideAgentStatus) withObject:nil
|
|
727
|
-
afterDelay:AgentStatusInactivityInterval];
|
|
728
|
-
[self presentPendingApprovalRecord:pending.firstObject];
|
|
729
|
-
return;
|
|
730
|
-
}
|
|
731
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
732
|
-
selector:@selector(enterIdleStatus) object:nil];
|
|
733
|
-
[self.statusPanel orderOut:nil];
|
|
734
|
-
[CCPetsGlassMenu dismiss];
|
|
735
|
-
self.hasAgentStatus = NO;
|
|
736
|
-
[self refreshApprovalBadge];
|
|
737
|
-
}
|
|
738
|
-
// 只改卡片内容和回跳目标,不走 displayAgentRecord:那条路会连带播动画、说一句话、
|
|
739
|
-
// 发一次通知,而这里是"气泡闲下来后回落",重复表演反而吵。
|
|
740
|
-
- (void)presentPendingApprovalRecord:(NSDictionary *)record {
|
|
741
|
-
if (record.count == 0) return;
|
|
742
|
-
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
743
|
-
? record[@"terminal"] : nil;
|
|
744
|
-
if (terminal.count > 0) self.lastTerminalFocusTarget = terminal;
|
|
745
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
746
|
-
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
|
|
747
|
-
if ([self.lastStatusState isEqualToString:@"approval"] &&
|
|
748
|
-
[self.lastStatusProvider isEqualToString:provider]) return;
|
|
749
|
-
[self applyStatusPresentationForState:@"approval"
|
|
750
|
-
provider:provider.length > 0 ? provider : @"Agent" tool:tool];
|
|
751
|
-
}
|
|
752
|
-
// 勾选 = 显示气泡。没有 agent 状态时也允许改,这样用户可以提前设好偏好,
|
|
753
|
-
// 而不必等下一次会话开始。
|
|
754
|
-
- (void)toggleStatusBubbleFromMenu:(NSButton *)sender {
|
|
755
|
-
self.statusBubbleExpanded = !self.statusBubbleExpanded;
|
|
756
|
-
[NSUserDefaults.standardUserDefaults setBool:self.statusBubbleExpanded
|
|
757
|
-
forKey:StatusBubbleExpandedKey];
|
|
758
|
-
sender.state = self.statusBubbleExpanded ? NSControlStateValueOn : NSControlStateValueOff;
|
|
759
|
-
if (self.statusBubbleExpanded && self.hasAgentStatus) {
|
|
760
|
-
[self positionAgentStatus];
|
|
761
|
-
[self.statusPanel orderFrontRegardless];
|
|
762
|
-
} else {
|
|
763
|
-
[self.statusPanel orderOut:nil];
|
|
764
|
-
[CCPetsGlassMenu dismiss];
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
// Stop 之后还会飘来 SubagentStop / PostToolUse / TaskCompleted 这类"仍在工作"的尾巴事件
|
|
768
|
-
// (实测 Stop 后 4 秒),它们和 UserPromptSubmit 一样都归一成 thinking,只看 state 分不出来,
|
|
769
|
-
// 所以必须按事件名判断。终态只能被新一轮真实动作解除(用户提问、工具调用、需要关注),
|
|
770
|
-
// 否则"任务已完成"会被打回"正在思考",看起来像任务又活了。
|
|
771
|
-
- (BOOL)isTrailingRecord:(NSDictionary *)record afterState:(NSString *)state {
|
|
772
|
-
if (![state isEqualToString:@"completed"] && ![state isEqualToString:@"failed"]) return NO;
|
|
773
|
-
NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
|
|
774
|
-
return [event isEqualToString:@"SubagentStop"] || [event isEqualToString:@"PostToolUse"] ||
|
|
775
|
-
[event isEqualToString:@"TaskCompleted"];
|
|
776
|
-
}
|
|
777
|
-
- (void)applyStatusPresentationForState:(NSString *)state provider:(NSString *)provider
|
|
778
|
-
tool:(NSString *)tool {
|
|
779
|
-
self.lastStatusState = state;
|
|
780
|
-
self.lastStatusProvider = provider;
|
|
781
|
-
self.statusTitleLabel.stringValue = [NSString stringWithFormat:@"%@ · %@",
|
|
782
|
-
provider, [self statusTextForState:state tool:tool]];
|
|
783
|
-
self.statusDetailLabel.stringValue = [self statusDetailForState:state tool:tool];
|
|
784
|
-
// 上一句碎碎念借走的副行已经被新状态覆盖,取消那次归还,否则它会把旧文案写回来。
|
|
785
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
786
|
-
selector:@selector(restoreStatusDetail) object:nil];
|
|
787
|
-
NSColor *stateColor = [self statusColorForState:state];
|
|
788
|
-
self.statusIconButton.layer.backgroundColor = [stateColor colorWithAlphaComponent:0.28].CGColor;
|
|
789
|
-
NSImage *icon = [NSImage imageWithSystemSymbolName:[self statusSymbolForState:state]
|
|
790
|
-
accessibilityDescription:[self statusTextForState:state tool:tool]];
|
|
791
|
-
self.statusIconButton.image = [icon imageWithSymbolConfiguration:
|
|
792
|
-
[NSImageSymbolConfiguration configurationWithPointSize:15 weight:NSFontWeightBold]];
|
|
793
|
-
self.statusIconButton.contentTintColor = [stateColor blendedColorWithFraction:0.18
|
|
794
|
-
ofColor:NSColor.blackColor] ?: stateColor;
|
|
795
|
-
[self resizeStatusCardToFitText];
|
|
796
|
-
[self layoutApprovalBadge];
|
|
797
|
-
[self positionAgentStatus];
|
|
798
|
-
if (self.statusBubbleExpanded) {
|
|
799
|
-
[self.statusPanel orderFrontRegardless];
|
|
800
|
-
// 卡片一出现就收掉独立气泡:两者都是宠物在说话,同时挂着就是重影。
|
|
801
|
-
if (self.speechPanel.isVisible) [self hideSpeechBubble];
|
|
802
|
-
} else {
|
|
803
|
-
[self.statusPanel orderOut:nil];
|
|
804
|
-
[CCPetsGlassMenu dismiss];
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
// "正在启动"只在会话拉起的一瞬间成立。之后如果没有任何后续事件,真实情况是会话已就绪、
|
|
808
|
-
// 正在等用户输入——继续显示"正在准备当前会话…"会让启动和待机看起来一模一样。
|
|
809
|
-
- (void)enterIdleStatus {
|
|
810
|
-
if (!self.hasAgentStatus) return;
|
|
811
|
-
[self applyStatusPresentationForState:@"idle"
|
|
812
|
-
provider:self.lastStatusProvider ?: @"Agent" tool:@""];
|
|
813
|
-
}
|
|
814
|
-
- (void)showAgentStatusForRecord:(NSDictionary *)record notify:(BOOL)shouldNotify {
|
|
815
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
816
|
-
if (provider.length == 0) provider = @"Agent";
|
|
817
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class]
|
|
818
|
-
? record[@"state"] : NormalizedStateForEvent(record[@"event"], [record[@"failed"] boolValue]);
|
|
819
|
-
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
|
|
820
|
-
// 尾巴事件仍然算"客户端还活着",只是不该改写气泡上的终态。
|
|
821
|
-
self.lastStatusTimestamp = [NSDate.date timeIntervalSince1970];
|
|
822
|
-
if (!self.providerActivityAt) self.providerActivityAt = [NSMutableDictionary dictionary];
|
|
823
|
-
self.providerActivityAt[provider] = @(self.lastStatusTimestamp);
|
|
824
|
-
[self updateQuotaLiveState];
|
|
825
|
-
if (self.hasAgentStatus && [provider isEqualToString:self.lastStatusProvider] &&
|
|
826
|
-
[self isTrailingRecord:record afterState:self.lastStatusState]) return;
|
|
827
|
-
|
|
828
|
-
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
829
|
-
? record[@"terminal"] : nil;
|
|
830
|
-
self.lastTerminalFocusTarget = terminal.count > 0 ? terminal : nil;
|
|
831
|
-
|
|
832
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
833
|
-
selector:@selector(hideAgentStatus) object:nil];
|
|
834
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
835
|
-
selector:@selector(enterIdleStatus) object:nil];
|
|
836
|
-
self.hasAgentStatus = YES;
|
|
837
|
-
[self applyStatusPresentationForState:state provider:provider tool:tool];
|
|
838
|
-
[self.panel orderFrontRegardless];
|
|
839
|
-
[self performSelector:@selector(hideAgentStatus)
|
|
840
|
-
withObject:nil afterDelay:AgentStatusInactivityInterval];
|
|
841
|
-
if ([state isEqualToString:@"starting"]) {
|
|
842
|
-
[self performSelector:@selector(enterIdleStatus) withObject:nil
|
|
843
|
-
afterDelay:AgentStartingGraceInterval];
|
|
844
|
-
}
|
|
845
|
-
if (shouldNotify) [self notifyForRecord:record];
|
|
846
|
-
}
|
|
847
|
-
- (void)showAgentStatusForRecord:(NSDictionary *)record {
|
|
848
|
-
[self showAgentStatusForRecord:record notify:YES];
|
|
849
|
-
}
|
|
850
|
-
- (NSString *)approvalKeyForRecord:(NSDictionary *)record {
|
|
851
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
852
|
-
if (provider.length == 0) provider = @"Agent";
|
|
853
|
-
NSString *session = SanitizedShortString(record[@"session"], 128);
|
|
854
|
-
return session.length > 0
|
|
855
|
-
? [NSString stringWithFormat:@"%@:%@", provider, session]
|
|
856
|
-
: provider;
|
|
857
|
-
}
|
|
858
|
-
- (void)prunePendingApprovalRecords {
|
|
859
|
-
NSTimeInterval cutoff = NSDate.date.timeIntervalSince1970 - PendingApprovalTTL;
|
|
860
|
-
for (NSString *key in self.pendingApprovalRecords.allKeys) {
|
|
861
|
-
NSDictionary *record = self.pendingApprovalRecords[key];
|
|
862
|
-
if ([record[@"timestamp"] doubleValue] < cutoff) {
|
|
863
|
-
[self.pendingApprovalRecords removeObjectForKey:key];
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
if (self.pendingApprovalRecords.count <= PendingApprovalLimit) return;
|
|
867
|
-
NSArray<NSDictionary *> *oldestFirst = [self.pendingApprovalRecords.allValues
|
|
868
|
-
sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
869
|
-
NSTimeInterval leftTime = [left[@"timestamp"] doubleValue];
|
|
870
|
-
NSTimeInterval rightTime = [right[@"timestamp"] doubleValue];
|
|
871
|
-
if (leftTime < rightTime) return NSOrderedAscending;
|
|
872
|
-
if (leftTime > rightTime) return NSOrderedDescending;
|
|
873
|
-
return NSOrderedSame;
|
|
874
|
-
}];
|
|
875
|
-
NSUInteger removeCount = oldestFirst.count - PendingApprovalLimit;
|
|
876
|
-
for (NSUInteger index = 0; index < removeCount; index++) {
|
|
877
|
-
NSString *key = [self approvalKeyForRecord:oldestFirst[index]];
|
|
878
|
-
[self.pendingApprovalRecords removeObjectForKey:key];
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
- (void)displayAgentRecord:(NSDictionary *)record notify:(BOOL)shouldNotify {
|
|
882
|
-
NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
|
|
883
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
884
|
-
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
|
|
885
|
-
NSString *animationEvent = [state isEqualToString:@"auto_review"]
|
|
886
|
-
? @"AutoReviewRequest" : event;
|
|
887
|
-
[self.petView handleAgentEvent:animationEvent tool:tool
|
|
888
|
-
failed:[record[@"failed"] boolValue]];
|
|
889
|
-
[self showAgentStatusForRecord:record notify:shouldNotify];
|
|
890
|
-
// 说话是事件流的新消费者,不改变事件生产。冷启动重放已被 processAgentEventData
|
|
891
|
-
// 的 recentOnly + 5 秒 cutoff 挡住,再加上预算制和冷却,最坏也只多说一句。
|
|
892
|
-
[self considerSpeechForRecord:record];
|
|
893
|
-
}
|
|
894
|
-
- (NSString *)agentSessionKeyForRecord:(NSDictionary *)record {
|
|
895
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
896
|
-
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
897
|
-
? record[@"terminal"] : nil;
|
|
898
|
-
NSString *tty = SanitizedShortString(terminal[@"tty"], 64);
|
|
899
|
-
NSString *bundleID = SanitizedShortString(terminal[@"bundleID"], 128);
|
|
900
|
-
if (tty.length > 0) {
|
|
901
|
-
return [NSString stringWithFormat:@"%@|%@|%@", provider, bundleID, tty];
|
|
902
|
-
}
|
|
903
|
-
NSString *session = SanitizedShortString(record[@"session"], 128);
|
|
904
|
-
if (session.length > 0) return [NSString stringWithFormat:@"%@|%@", provider, session];
|
|
905
|
-
return terminal.count > 0 ? [NSString stringWithFormat:@"%@|%@", provider, bundleID] : nil;
|
|
906
|
-
}
|
|
907
|
-
- (NSString *)onlineAgentSessionKeyForProvider:(NSString *)provider tty:(NSString *)tty {
|
|
908
|
-
provider = SanitizedShortString(provider, 32);
|
|
909
|
-
tty = SanitizedShortString(tty.lastPathComponent, 64);
|
|
910
|
-
if (provider.length == 0 || tty.length == 0) return nil;
|
|
911
|
-
return [NSString stringWithFormat:@"%@|%@", provider, tty];
|
|
912
|
-
}
|
|
913
|
-
- (NSString *)onlineAgentSessionKeyForRecord:(NSDictionary *)record {
|
|
914
|
-
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
915
|
-
? record[@"terminal"] : nil;
|
|
916
|
-
return [self onlineAgentSessionKeyForProvider:record[@"provider"] tty:terminal[@"tty"]];
|
|
917
|
-
}
|
|
918
|
-
// 在线判定优先用包装脚本写出的 pid 文件:它给出精确的退出信号,会话一关列表就更新。
|
|
919
|
-
// 但直接跑 claude / codex(或终端窗口早于 shim 安装就已打开)的会话根本没有 pid 文件,
|
|
920
|
-
// 只按 pid 文件判定会把它们当场判死,列表里永远看不到——哪怕它们的 Hook 正在正常发事件。
|
|
921
|
-
// 这类会话退回活跃度宽限:最近一次事件在静默窗口内就算在线。某个 provider 一旦出现过
|
|
922
|
-
// pid 文件,说明包装脚本对它生效,继续按精确信号判定,不被宽限盖住。
|
|
923
|
-
- (BOOL)isAgentSessionRecordLive:(NSDictionary *)record {
|
|
924
|
-
NSString *onlineKey = [self onlineAgentSessionKeyForRecord:record];
|
|
925
|
-
if (onlineKey.length > 0 && [self.liveAgentSessionKeys containsObject:onlineKey]) return YES;
|
|
926
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
927
|
-
if (provider.length > 0 && [self.liveClientProviders containsObject:provider]) return NO;
|
|
928
|
-
return NSDate.date.timeIntervalSince1970 - [record[@"timestamp"] doubleValue]
|
|
929
|
-
< AgentStatusInactivityInterval;
|
|
930
|
-
}
|
|
931
|
-
- (void)pruneOfflineAgentSessionRecords {
|
|
932
|
-
for (NSString *key in self.agentSessionRecords.allKeys) {
|
|
933
|
-
if (![self isAgentSessionRecordLive:self.agentSessionRecords[key]]) {
|
|
934
|
-
[self.agentSessionRecords removeObjectForKey:key];
|
|
935
|
-
}
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
- (void)trackAgentSessionRecord:(NSDictionary *)record {
|
|
939
|
-
NSString *key = [self agentSessionKeyForRecord:record];
|
|
940
|
-
if (key.length == 0) return;
|
|
941
|
-
if (!self.agentSessionRecords) self.agentSessionRecords = [NSMutableDictionary dictionary];
|
|
942
|
-
self.agentSessionRecords[key] = record;
|
|
943
|
-
if (self.agentSessionRecords.count <= AgentSessionRecordLimit) return;
|
|
944
|
-
NSArray<NSDictionary *> *oldestFirst = [self.agentSessionRecords.allValues
|
|
945
|
-
sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
946
|
-
return [left[@"timestamp"] compare:right[@"timestamp"]];
|
|
947
|
-
}];
|
|
948
|
-
NSUInteger removeCount = oldestFirst.count - AgentSessionRecordLimit;
|
|
949
|
-
for (NSUInteger index = 0; index < removeCount; index++) {
|
|
950
|
-
NSString *oldKey = [self agentSessionKeyForRecord:oldestFirst[index]];
|
|
951
|
-
if (oldKey) [self.agentSessionRecords removeObjectForKey:oldKey];
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
- (BOOL)isApprovalSessionRecord:(NSDictionary *)record {
|
|
955
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
956
|
-
return [state isEqualToString:@"approval"];
|
|
957
|
-
}
|
|
958
|
-
// 卡在审批的在线会话,最近的排前面。角标计数和会话列表置顶共用这一份,两处数字
|
|
959
|
-
// 才不会打架。判据是"该会话的最后一条事件是审批"——审批一旦被处理,后续事件会
|
|
960
|
-
// 把这条记录顶掉,会话自然退出这个集合,不需要额外的解除信号。
|
|
961
|
-
- (NSArray<NSDictionary *> *)pendingApprovalSessionRecords {
|
|
962
|
-
[self pruneOfflineAgentSessionRecords];
|
|
963
|
-
NSMutableArray<NSDictionary *> *pending = [NSMutableArray array];
|
|
964
|
-
for (NSDictionary *record in self.agentSessionRecords.allValues) {
|
|
965
|
-
if ([self isApprovalSessionRecord:record]) [pending addObject:record];
|
|
966
|
-
}
|
|
967
|
-
[pending sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
968
|
-
return [right[@"timestamp"] compare:left[@"timestamp"]];
|
|
969
|
-
}];
|
|
970
|
-
return pending;
|
|
971
|
-
}
|
|
972
|
-
- (NSTimeInterval)stallIntervalForState:(NSString *)state {
|
|
973
|
-
if ([state isEqualToString:@"approval"]) return AgentApprovalStallInterval;
|
|
974
|
-
if ([state isEqualToString:@"thinking"]) return AgentThinkingStallInterval;
|
|
975
|
-
return 0;
|
|
976
|
-
}
|
|
977
|
-
// 会话停在同一个状态太久就提醒一次。去重键带上该会话当时的时间戳:会话一有新
|
|
978
|
-
// 事件,时间戳变了,旧键自然失效,于是下一次卡住还会再提醒。每轮用当前有效键
|
|
979
|
-
// 求交集,退出的会话不会在集合里留垃圾。
|
|
980
|
-
- (void)checkStalledAgentSessions {
|
|
981
|
-
if (self.agentSessionRecords.count == 0) {
|
|
982
|
-
[self.stallNotifiedSessionKeys removeAllObjects];
|
|
983
|
-
return;
|
|
984
|
-
}
|
|
985
|
-
[self pruneOfflineAgentSessionRecords];
|
|
986
|
-
if (!self.stallNotifiedSessionKeys) self.stallNotifiedSessionKeys = [NSMutableSet set];
|
|
987
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
988
|
-
BOOL shouldNotify = [NSUserDefaults.standardUserDefaults boolForKey:NotificationStallKey];
|
|
989
|
-
NSMutableSet<NSString *> *valid = [NSMutableSet set];
|
|
990
|
-
NSDictionary *stalled = nil;
|
|
991
|
-
for (NSString *key in self.agentSessionRecords.allKeys) {
|
|
992
|
-
NSDictionary *record = self.agentSessionRecords[key];
|
|
993
|
-
NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
|
|
994
|
-
NSString *stamp = [NSString stringWithFormat:@"%@|%.0f", key, timestamp];
|
|
995
|
-
[valid addObject:stamp];
|
|
996
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
997
|
-
NSTimeInterval limit = [self stallIntervalForState:state];
|
|
998
|
-
if (limit <= 0 || now - timestamp < limit) continue;
|
|
999
|
-
if ([self.stallNotifiedSessionKeys containsObject:stamp]) continue;
|
|
1000
|
-
[self.stallNotifiedSessionKeys addObject:stamp];
|
|
1001
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
1002
|
-
if (provider.length == 0) provider = @"Agent";
|
|
1003
|
-
if (shouldNotify) {
|
|
1004
|
-
NSInteger minutes = (NSInteger)((now - timestamp) / 60.0);
|
|
1005
|
-
[self sendNotificationWithTitle:
|
|
1006
|
-
[state isEqualToString:@"approval"] ? @"审批仍在等待" : @"Agent 长时间无响应"
|
|
1007
|
-
body:[NSString stringWithFormat:@"%@ 已%@ %ld 分钟。",
|
|
1008
|
-
provider, [self statusTextForState:state tool:record[@"tool"]], (long)minutes]];
|
|
1009
|
-
}
|
|
1010
|
-
// 多个会话同时卡住时只把最旧的那条顶到气泡上:它等得最久。
|
|
1011
|
-
if (!stalled || [record[@"timestamp"] doubleValue] < [stalled[@"timestamp"] doubleValue]) {
|
|
1012
|
-
stalled = record;
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
[self.stallNotifiedSessionKeys intersectSet:valid];
|
|
1016
|
-
if (!stalled) return;
|
|
1017
|
-
NSString *event = [stalled[@"event"] isKindOfClass:NSString.class] ? stalled[@"event"] : @"";
|
|
1018
|
-
NSString *tool = [stalled[@"tool"] isKindOfClass:NSString.class] ? stalled[@"tool"] : @"";
|
|
1019
|
-
[self.petView handleAgentEvent:event tool:tool failed:NO];
|
|
1020
|
-
[self presentStalledRecord:stalled];
|
|
1021
|
-
}
|
|
1022
|
-
// 卡住提醒要把气泡重新推到眼前,所以这里不走 presentPendingApprovalRecord 那条
|
|
1023
|
-
// 带早退的回落路径——面板此刻很可能已经因为长时间沉默被收走了,必须强制重现。
|
|
1024
|
-
- (void)presentStalledRecord:(NSDictionary *)record {
|
|
1025
|
-
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
1026
|
-
? record[@"terminal"] : nil;
|
|
1027
|
-
if (terminal.count > 0) self.lastTerminalFocusTarget = terminal;
|
|
1028
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
1029
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
1030
|
-
self.hasAgentStatus = YES;
|
|
1031
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
1032
|
-
selector:@selector(hideAgentStatus) object:nil];
|
|
1033
|
-
[self applyStatusPresentationForState:state
|
|
1034
|
-
provider:provider.length > 0 ? provider : @"Agent"
|
|
1035
|
-
tool:[record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @""];
|
|
1036
|
-
[self.panel orderFrontRegardless];
|
|
1037
|
-
[self performSelector:@selector(hideAgentStatus) withObject:nil
|
|
1038
|
-
afterDelay:AgentStatusInactivityInterval];
|
|
1039
|
-
}
|
|
1040
|
-
- (void)layoutApprovalBadge {
|
|
1041
|
-
if (!self.approvalBadgeView) return;
|
|
1042
|
-
// statusIconButton 在玻璃卡片内,角标在卡片外层,差一个 6 点的卡片边距。
|
|
1043
|
-
// 再各让出 4 点压到图标身上,看起来才是"贴在图标角上"而不是浮在旁边。
|
|
1044
|
-
NSRect icon = self.statusIconButton.frame;
|
|
1045
|
-
self.approvalBadgeView.frame = NSMakeRect(
|
|
1046
|
-
6 + NSMaxX(icon) - PetApprovalBadgeSize + 4,
|
|
1047
|
-
6 + NSMaxY(icon) - PetApprovalBadgeSize + 4,
|
|
1048
|
-
PetApprovalBadgeSize, PetApprovalBadgeSize);
|
|
1049
|
-
self.bridgeBadgeView.frame = NSMakeRect(
|
|
1050
|
-
6 + NSMaxX(icon) - PetApprovalBadgeSize + 4,
|
|
1051
|
-
6 + NSMinY(icon) - 4,
|
|
1052
|
-
PetApprovalBadgeSize, PetApprovalBadgeSize);
|
|
1053
|
-
}
|
|
1054
|
-
- (void)refreshApprovalBadge {
|
|
1055
|
-
CCPetsApprovalBadgeView *badge = (CCPetsApprovalBadgeView *)self.approvalBadgeView;
|
|
1056
|
-
if (!badge) return;
|
|
1057
|
-
badge.count = [self pendingApprovalSessionRecords].count;
|
|
1058
|
-
[self layoutApprovalBadge];
|
|
1059
|
-
}
|
|
1060
|
-
// 等审批的排最前面。纯按时间倒序会把它们推到最底下——它们的时间戳按定义只会
|
|
1061
|
-
// 越来越旧,而它们恰恰是唯一需要用户动手的那几条。
|
|
1062
|
-
- (NSArray<NSDictionary *> *)recentAgentSessionRecords {
|
|
1063
|
-
[self pruneOfflineAgentSessionRecords];
|
|
1064
|
-
NSArray<NSDictionary *> *records = [self.agentSessionRecords.allValues
|
|
1065
|
-
sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
|
1066
|
-
BOOL leftApproval = [self isApprovalSessionRecord:left];
|
|
1067
|
-
BOOL rightApproval = [self isApprovalSessionRecord:right];
|
|
1068
|
-
if (leftApproval != rightApproval) return leftApproval ? NSOrderedAscending : NSOrderedDescending;
|
|
1069
|
-
return [right[@"timestamp"] compare:left[@"timestamp"]];
|
|
1070
|
-
}];
|
|
1071
|
-
if (records.count <= AgentSessionMenuLimit) return records;
|
|
1072
|
-
return [records subarrayWithRange:NSMakeRange(0, AgentSessionMenuLimit)];
|
|
1073
|
-
}
|
|
1074
|
-
- (NSString *)terminalNameForTarget:(NSDictionary *)target {
|
|
1075
|
-
NSString *program = SanitizedShortString(target[@"program"], 64);
|
|
1076
|
-
NSString *lower = program.lowercaseString;
|
|
1077
|
-
if ([lower isEqualToString:@"apple_terminal"]) return @"Terminal";
|
|
1078
|
-
if ([lower containsString:@"iterm"]) return @"iTerm2";
|
|
1079
|
-
if ([lower isEqualToString:@"vscode"]) return @"VS Code";
|
|
1080
|
-
if ([lower containsString:@"jetbrains"]) return @"JetBrains";
|
|
1081
|
-
if ([lower containsString:@"ghostty"]) return @"Ghostty";
|
|
1082
|
-
if ([lower containsString:@"warp"]) return @"Warp";
|
|
1083
|
-
if ([lower containsString:@"wezterm"]) return @"WezTerm";
|
|
1084
|
-
if (program.length > 0) return program;
|
|
1085
|
-
NSString *bundleID = SanitizedShortString(target[@"bundleID"], 128);
|
|
1086
|
-
return bundleID.length > 0 ? bundleID : @"Terminal";
|
|
1087
|
-
}
|
|
1088
|
-
- (void)focusAgentSessionRecord:(NSMenuItem *)sender {
|
|
1089
|
-
NSDictionary *record = [sender.representedObject isKindOfClass:NSDictionary.class]
|
|
1090
|
-
? sender.representedObject : nil;
|
|
1091
|
-
NSDictionary *target = [record[@"terminal"] isKindOfClass:NSDictionary.class]
|
|
1092
|
-
? record[@"terminal"] : nil;
|
|
1093
|
-
if (target.count > 0) ActivateTerminalFocusTarget(target);
|
|
1094
|
-
}
|
|
1095
|
-
- (void)showAgentSessionsMenu:(NSButton *)sender {
|
|
1096
|
-
NSArray<NSDictionary *> *records = [self recentAgentSessionRecords];
|
|
1097
|
-
[self refreshBridgeState:nil];
|
|
1098
|
-
NSArray<NSDictionary *> *deliveries = self.bridgeRecentDeliveries ?: @[];
|
|
1099
|
-
NSDictionary<NSString *, NSNumber *> *pending = self.bridgePendingCounts ?: @{};
|
|
1100
|
-
if (records.count == 0 && deliveries.count == 0 && pending.count == 0) return;
|
|
1101
|
-
NSMenu *menu = [[NSMenu alloc] initWithTitle:@"最近 Agent 会话"];
|
|
1102
|
-
if (deliveries.count > 0 || pending.count > 0) {
|
|
1103
|
-
[self addBridgeItemsToMenu:menu deliveries:deliveries pending:pending];
|
|
1104
|
-
[menu addItem:NSMenuItem.separatorItem];
|
|
1105
|
-
}
|
|
1106
|
-
// 菜单打开即视为看过:角标清零,下一条新消息再亮。
|
|
1107
|
-
self.bridgeSeenAt = NSDate.date.timeIntervalSince1970;
|
|
1108
|
-
[self refreshBridgeBadge];
|
|
1109
|
-
if (records.count == 0) {
|
|
1110
|
-
[self popUpAgentSessionsMenu:menu from:sender];
|
|
1111
|
-
return;
|
|
1112
|
-
}
|
|
1113
|
-
NSMenuItem *heading = [menu addItemWithTitle:@"最近 Agent 会话" action:nil keyEquivalent:@""];
|
|
1114
|
-
heading.enabled = NO;
|
|
1115
|
-
[menu addItem:NSMenuItem.separatorItem];
|
|
1116
|
-
BOOL separatedApprovals = NO;
|
|
1117
|
-
for (NSDictionary *record in records) {
|
|
1118
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
1119
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
1120
|
-
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
|
|
1121
|
-
NSDictionary *target = record[@"terminal"];
|
|
1122
|
-
BOOL approval = [self isApprovalSessionRecord:record];
|
|
1123
|
-
// 置顶的审批组和其余会话之间划一道线,免得两段看起来像同一个时间序列。
|
|
1124
|
-
if (!approval && !separatedApprovals && record != records.firstObject) {
|
|
1125
|
-
[menu addItem:NSMenuItem.separatorItem];
|
|
1126
|
-
separatedApprovals = YES;
|
|
1127
|
-
}
|
|
1128
|
-
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[record[@"timestamp"] doubleValue]];
|
|
1129
|
-
NSString *time = [NSDateFormatter localizedStringFromDate:date
|
|
1130
|
-
dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle];
|
|
1131
|
-
// 开启 CC Bridge 时带上会话名:用户和 Agent 之间就是用这个名字互相指代的。
|
|
1132
|
-
NSDictionary *bridge = [self bridgeSessionEntryForRecord:record];
|
|
1133
|
-
NSString *bridgeName = bridge.count > 0
|
|
1134
|
-
? [NSString stringWithFormat:@"(%@)", bridge[@"name"]] : @"";
|
|
1135
|
-
NSUInteger waiting = [pending[[self bridgeSessionIdForRecord:record] ?: @""] unsignedIntegerValue];
|
|
1136
|
-
NSString *title = [NSString stringWithFormat:@"%@%@%@ · %@ · %@ · %@%@",
|
|
1137
|
-
approval ? @"⚠️ " : @"",
|
|
1138
|
-
provider.length > 0 ? provider : @"Agent", bridgeName,
|
|
1139
|
-
[self statusTextForState:state tool:tool], [self terminalNameForTarget:target], time,
|
|
1140
|
-
waiting > 0 ? [NSString stringWithFormat:@" · 📬 %lu", (unsigned long)waiting] : @""];
|
|
1141
|
-
NSMenuItem *item = [menu addItemWithTitle:title
|
|
1142
|
-
action:@selector(focusAgentSessionRecord:) keyEquivalent:@""];
|
|
1143
|
-
item.target = self;
|
|
1144
|
-
item.representedObject = record;
|
|
1145
|
-
if ([target isEqual:self.lastTerminalFocusTarget]) item.state = NSControlStateValueOn;
|
|
1146
|
-
}
|
|
1147
|
-
[self popUpAgentSessionsMenu:menu from:sender];
|
|
1148
|
-
}
|
|
1149
|
-
// Liquid Glass 主题下用玻璃面板展示,和旁边的玻璃状态卡保持一致;经典主题仍是系统菜单。
|
|
1150
|
-
// 玻璃面板不抢焦点,所以不支持方向键选择,Esc 只在本 App 处于前台时有效。
|
|
1151
|
-
- (void)popUpAgentSessionsMenu:(NSMenu *)menu from:(NSButton *)sender {
|
|
1152
|
-
if (self.statusGlass.usesLiquidGlass) {
|
|
1153
|
-
[CCPetsGlassMenu showMenu:menu belowView:self.statusGlass alignRightTo:self.statusGlass];
|
|
1154
|
-
return;
|
|
1155
|
-
}
|
|
1156
|
-
[menu popUpMenuPositioningItem:nil
|
|
1157
|
-
atLocation:NSMakePoint(0, NSHeight(sender.bounds) + 4) inView:sender];
|
|
1158
|
-
}
|
|
1159
|
-
#pragma mark - CC Bridge
|
|
1160
|
-
|
|
1161
|
-
// 菜单开关 → cc-pets bridge enable / disable / configure。逻辑全在 CLI 里,桌宠只负责调用,
|
|
1162
|
-
// 命令行与菜单两条路的行为才一致。enable 要跑 claude / codex mcp add,要几秒,所以异步执行;
|
|
1163
|
-
// 执行期间忽略新的切换,结束后按实际状态刷新(菜单下次打开时现读)。
|
|
1164
|
-
- (void)runBridgeCommand:(NSArray<NSString *> *)arguments sender:(NSButton *)sender
|
|
1165
|
-
successMessage:(NSString *)successMessage {
|
|
1166
|
-
NSDictionary<NSString *, NSString *> *locator = CCBridgeCLILocator();
|
|
1167
|
-
if (!locator) {
|
|
1168
|
-
[self showUpdateAlertWithTitle:@"无法修改 CC Bridge 设置"
|
|
1169
|
-
message:@"没有找到 cc-pets 的命令行程序。请在终端执行一次 cc-pets install 后重试。"];
|
|
1170
|
-
[self syncBridgeSwitch:sender];
|
|
1171
|
-
return;
|
|
1172
|
-
}
|
|
1173
|
-
if (self.bridgeCommandRunning) {
|
|
1174
|
-
[self syncBridgeSwitch:sender];
|
|
1175
|
-
return;
|
|
1176
|
-
}
|
|
1177
|
-
self.bridgeCommandRunning = YES;
|
|
1178
|
-
NSTask *task = [NSTask new];
|
|
1179
|
-
task.executableURL = [NSURL fileURLWithPath:locator[@"node"]];
|
|
1180
|
-
task.arguments = [@[locator[@"cli"]] arrayByAddingObjectsFromArray:arguments];
|
|
1181
|
-
NSMutableDictionary<NSString *, NSString *> *environment =
|
|
1182
|
-
[NSProcessInfo.processInfo.environment mutableCopy];
|
|
1183
|
-
NSString *existingPath = environment[@"PATH"].length > 0 ? environment[@"PATH"] : @"/usr/bin:/bin:/usr/sbin:/sbin";
|
|
1184
|
-
// claude / codex 常装在 node 同目录(nvm),桌宠的 PATH 里未必有。
|
|
1185
|
-
environment[@"PATH"] = [NSString stringWithFormat:@"%@:%@",
|
|
1186
|
-
[locator[@"node"] stringByDeletingLastPathComponent], existingPath];
|
|
1187
|
-
task.environment = environment;
|
|
1188
|
-
NSPipe *output = [NSPipe pipe];
|
|
1189
|
-
task.standardOutput = output;
|
|
1190
|
-
task.standardError = output;
|
|
1191
|
-
__weak typeof(self) weakSelf = self;
|
|
1192
|
-
task.terminationHandler = ^(NSTask *finished) {
|
|
1193
|
-
NSData *data = [output.fileHandleForReading readDataToEndOfFile];
|
|
1194
|
-
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"";
|
|
1195
|
-
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1196
|
-
typeof(self) strongSelf = weakSelf;
|
|
1197
|
-
if (!strongSelf) return;
|
|
1198
|
-
strongSelf.bridgeCommandRunning = NO;
|
|
1199
|
-
[strongSelf refreshBridgeState:nil];
|
|
1200
|
-
if (finished.terminationStatus == EXIT_SUCCESS) {
|
|
1201
|
-
if (successMessage.length > 0) {
|
|
1202
|
-
[strongSelf sendNotificationWithTitle:@"CC Bridge" body:successMessage];
|
|
1203
|
-
}
|
|
1204
|
-
return;
|
|
1205
|
-
}
|
|
1206
|
-
[strongSelf syncBridgeSwitch:sender];
|
|
1207
|
-
NSString *detail = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
|
1208
|
-
[strongSelf showUpdateAlertWithTitle:@"CC Bridge 设置失败"
|
|
1209
|
-
message:detail.length > 0 ? detail : @"命令执行失败。"];
|
|
1210
|
-
});
|
|
1211
|
-
};
|
|
1212
|
-
NSError *error = nil;
|
|
1213
|
-
if (![task launchAndReturnError:&error]) {
|
|
1214
|
-
self.bridgeCommandRunning = NO;
|
|
1215
|
-
[self syncBridgeSwitch:sender];
|
|
1216
|
-
[self showUpdateAlertWithTitle:@"CC Bridge 设置失败" message:error.localizedDescription];
|
|
1217
|
-
}
|
|
1218
|
-
}
|
|
1219
|
-
// 与其他菜单开关一致:目标状态按"实际存储的状态取反"算,不信任开关视图自己翻转后的 state——
|
|
1220
|
-
// 菜单停留期间状态可能已被命令行改过。命令没执行成功时再把开关翻回实际状态。
|
|
1221
|
-
- (BOOL)currentBridgeStateForSwitch:(NSButton *)sender {
|
|
1222
|
-
NSDictionary *options = CCBridgeOptions();
|
|
1223
|
-
if (sender.action == @selector(toggleBridgeEnabled:)) return CCBridgeEnabled();
|
|
1224
|
-
if (sender.action == @selector(toggleBridgeWake:)) return [options[@"wake"] boolValue];
|
|
1225
|
-
if (sender.action == @selector(toggleBridgeEditGuard:)) return [options[@"editGuard"] boolValue];
|
|
1226
|
-
if (sender.action == @selector(toggleBridgeApproval:)) {
|
|
1227
|
-
NSSet *tools = [NSSet setWithArray:CCBridgeToolGroup([self bridgeApprovalGroupForTag:sender.tag])];
|
|
1228
|
-
return tools.count > 0 && [tools isSubsetOfSet:[NSSet setWithArray:options[@"codexApprove"]]] &&
|
|
1229
|
-
[tools isSubsetOfSet:[NSSet setWithArray:options[@"claudeAllow"]]];
|
|
1230
|
-
}
|
|
1231
|
-
return NO;
|
|
1232
|
-
}
|
|
1233
|
-
- (void)syncBridgeSwitch:(NSButton *)sender {
|
|
1234
|
-
if (!sender) return;
|
|
1235
|
-
sender.state = [self currentBridgeStateForSwitch:sender] ? NSControlStateValueOn : NSControlStateValueOff;
|
|
1236
|
-
}
|
|
1237
|
-
// 返回目标状态,并先把开关视图摆到目标状态上(命令失败时 syncBridgeSwitch 再翻回来)。
|
|
1238
|
-
- (BOOL)targetBridgeStateForSwitch:(NSButton *)sender {
|
|
1239
|
-
BOOL target = ![self currentBridgeStateForSwitch:sender];
|
|
1240
|
-
sender.state = target ? NSControlStateValueOn : NSControlStateValueOff;
|
|
1241
|
-
return target;
|
|
1242
|
-
}
|
|
1243
|
-
- (NSString *)bridgeApprovalGroupForTag:(NSInteger)tag {
|
|
1244
|
-
NSArray<NSString *> *groups = CCBridgeToolGroupNames();
|
|
1245
|
-
return tag >= 1 && tag <= (NSInteger)groups.count ? groups[tag - 1] : @"";
|
|
1246
|
-
}
|
|
1247
|
-
- (void)toggleBridgeEnabled:(NSButton *)sender {
|
|
1248
|
-
BOOL enable = [self targetBridgeStateForSwitch:sender];
|
|
1249
|
-
[self runBridgeCommand:@[enable ? @"enable" : @"disable"] sender:sender
|
|
1250
|
-
successMessage:enable
|
|
1251
|
-
? @"已开启。已在运行的 Codex 会话需重启并在 /hooks 中信任;Claude 会话重启后才有 cc-bridge 工具。"
|
|
1252
|
-
: @"已关闭,相关 hooks 与 MCP 注册已移除。"];
|
|
1253
|
-
}
|
|
1254
|
-
// 一个分组同时作用于 Codex 免审批与 Claude 免确认:菜单上只有一组开关,两边保持一致。
|
|
1255
|
-
- (void)toggleBridgeApproval:(NSButton *)sender {
|
|
1256
|
-
NSArray<NSString *> *tools = CCBridgeToolGroup([self bridgeApprovalGroupForTag:sender.tag]);
|
|
1257
|
-
if (tools.count == 0) return;
|
|
1258
|
-
BOOL allow = [self targetBridgeStateForSwitch:sender];
|
|
1259
|
-
NSDictionary *options = CCBridgeOptions();
|
|
1260
|
-
NSString *(^apply)(NSArray<NSString *> *) = ^NSString *(NSArray<NSString *> *current) {
|
|
1261
|
-
NSMutableOrderedSet<NSString *> *next = [NSMutableOrderedSet orderedSetWithArray:current];
|
|
1262
|
-
if (allow) [next addObjectsFromArray:tools]; else [next removeObjectsInArray:tools];
|
|
1263
|
-
return [next.array componentsJoinedByString:@","];
|
|
1264
|
-
};
|
|
1265
|
-
[self runBridgeCommand:@[@"configure",
|
|
1266
|
-
[@"--codex-approve=" stringByAppendingString:apply(options[@"codexApprove"])],
|
|
1267
|
-
[@"--claude-allow=" stringByAppendingString:apply(options[@"claudeAllow"])]]
|
|
1268
|
-
sender:sender successMessage:nil];
|
|
1269
|
-
}
|
|
1270
|
-
- (void)toggleBridgeWake:(NSButton *)sender {
|
|
1271
|
-
[self runBridgeCommand:@[@"configure",
|
|
1272
|
-
[self targetBridgeStateForSwitch:sender] ? @"--wake=on" : @"--wake=off"] sender:sender successMessage:nil];
|
|
1273
|
-
}
|
|
1274
|
-
- (void)toggleBridgeEditGuard:(NSButton *)sender {
|
|
1275
|
-
[self runBridgeCommand:@[@"configure",
|
|
1276
|
-
[self targetBridgeStateForSwitch:sender] ? @"--edit-guard=on" : @"--edit-guard=off"]
|
|
1277
|
-
sender:sender successMessage:nil];
|
|
1278
|
-
}
|
|
1279
|
-
- (void)toggleBridgeBadge:(NSButton *)sender {
|
|
1280
|
-
BOOL enabled = ![NSUserDefaults.standardUserDefaults boolForKey:BridgeBadgeEnabledKey];
|
|
1281
|
-
[NSUserDefaults.standardUserDefaults setBool:enabled forKey:BridgeBadgeEnabledKey];
|
|
1282
|
-
sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
|
|
1283
|
-
[self refreshBridgeBadge];
|
|
1284
|
-
}
|
|
1285
|
-
// 与"系统通知"那组开关同一套授权流程:第一次打开时向系统申请通知权限。
|
|
1286
|
-
- (void)toggleBridgeNotification:(NSButton *)sender {
|
|
1287
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
1288
|
-
if ([defaults boolForKey:BridgeNotificationKey]) {
|
|
1289
|
-
[defaults setBool:NO forKey:BridgeNotificationKey];
|
|
1290
|
-
sender.state = NSControlStateValueOff;
|
|
1291
|
-
return;
|
|
1292
|
-
}
|
|
1293
|
-
[UNUserNotificationCenter.currentNotificationCenter
|
|
1294
|
-
requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound
|
|
1295
|
-
completionHandler:^(BOOL granted, NSError *error) {
|
|
1296
|
-
dispatch_async(dispatch_get_main_queue(), ^{
|
|
1297
|
-
[defaults setBool:granted forKey:BridgeNotificationKey];
|
|
1298
|
-
sender.state = granted ? NSControlStateValueOn : NSControlStateValueOff;
|
|
1299
|
-
if (!granted) {
|
|
1300
|
-
[self showUpdateAlertWithTitle:@"无法启用系统通知" message:error.localizedDescription ?:
|
|
1301
|
-
@"请在“系统设置 → 通知 → CC Pets”中允许通知后重试。"];
|
|
1302
|
-
}
|
|
1303
|
-
});
|
|
1304
|
-
}];
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
// 读 bridge 状态(会话名、最近送达、信箱积压),刷新角标。bridge 未开启时清空并隐藏。
|
|
1308
|
-
// 回执目录没变就不重读文件,只按时间窗重新过滤缓存——回执状态一变,写入端的
|
|
1309
|
-
// "临时文件 + rename" 必然改动目录的修改时间。
|
|
1310
|
-
- (void)refreshBridgeState:(NSTimer *)timer {
|
|
1311
|
-
if (!CCBridgeEnabled()) {
|
|
1312
|
-
self.bridgeSessions = nil;
|
|
1313
|
-
self.bridgeRecentDeliveries = nil;
|
|
1314
|
-
self.bridgePendingCounts = nil;
|
|
1315
|
-
self.bridgeSentStamp = nil;
|
|
1316
|
-
[self refreshBridgeBadge];
|
|
1317
|
-
return;
|
|
1318
|
-
}
|
|
1319
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
1320
|
-
NSString *directory = CCBridgeStateDirectory();
|
|
1321
|
-
self.bridgeSessions = CCBridgeSessions();
|
|
1322
|
-
NSDate *stamp = [NSFileManager.defaultManager attributesOfItemAtPath:
|
|
1323
|
-
[directory stringByAppendingPathComponent:@"sent"] error:nil].fileModificationDate;
|
|
1324
|
-
if (!stamp || ![stamp isEqualToDate:self.bridgeSentStamp] || !self.bridgeDeliveryCache) {
|
|
1325
|
-
self.bridgeDeliveryCache = CCBridgeRecentDeliveries(now - BridgeRecentWindow, 50);
|
|
1326
|
-
self.bridgeSentStamp = stamp;
|
|
1327
|
-
}
|
|
1328
|
-
NSMutableArray<NSDictionary *> *recent = [NSMutableArray array];
|
|
1329
|
-
for (NSDictionary *delivery in self.bridgeDeliveryCache) {
|
|
1330
|
-
if ([delivery[@"at"] doubleValue] >= now - BridgeRecentWindow) [recent addObject:delivery];
|
|
1331
|
-
}
|
|
1332
|
-
self.bridgeRecentDeliveries = recent;
|
|
1333
|
-
// 只算仍在线的会话:已退出会话的积压已经投不出去,提醒也无从处理。
|
|
1334
|
-
NSMutableDictionary<NSString *, NSNumber *> *pending = [NSMutableDictionary dictionary];
|
|
1335
|
-
[CCBridgePendingCounts() enumerateKeysAndObjectsUsingBlock:^(NSString *session, NSNumber *count, BOOL *stop) {
|
|
1336
|
-
if (self.bridgeSessions[session]) pending[session] = count;
|
|
1337
|
-
}];
|
|
1338
|
-
self.bridgePendingCounts = pending;
|
|
1339
|
-
[self notifyNewBridgeDeliveries];
|
|
1340
|
-
[self refreshBridgeBadge];
|
|
1341
|
-
}
|
|
1342
|
-
// 新送达的跨会话消息发系统通知:只含谁发给谁,不含正文。一次刷新里来了多条时合并成一条。
|
|
1343
|
-
- (void)notifyNewBridgeDeliveries {
|
|
1344
|
-
NSMutableArray<NSDictionary *> *fresh = [NSMutableArray array];
|
|
1345
|
-
for (NSDictionary *delivery in self.bridgeRecentDeliveries) {
|
|
1346
|
-
if ([delivery[@"at"] doubleValue] > self.bridgeNotifiedAt) [fresh addObject:delivery];
|
|
1347
|
-
}
|
|
1348
|
-
if (fresh.count == 0) return;
|
|
1349
|
-
for (NSDictionary *delivery in fresh) {
|
|
1350
|
-
self.bridgeNotifiedAt = MAX(self.bridgeNotifiedAt, [delivery[@"at"] doubleValue]);
|
|
1351
|
-
}
|
|
1352
|
-
if (![NSUserDefaults.standardUserDefaults boolForKey:BridgeNotificationKey]) return;
|
|
1353
|
-
NSDictionary *latest = fresh.firstObject;
|
|
1354
|
-
NSString *body = fresh.count == 1
|
|
1355
|
-
? [NSString stringWithFormat:@"%@ → %@", latest[@"from"], latest[@"to"]]
|
|
1356
|
-
: [NSString stringWithFormat:@"%@ → %@ 等 %lu 条", latest[@"from"], latest[@"to"],
|
|
1357
|
-
(unsigned long)fresh.count];
|
|
1358
|
-
[self sendNotificationWithTitle:@"CC Bridge 新消息" body:body];
|
|
1359
|
-
}
|
|
1360
|
-
// 蓝色 = 有新的跨会话消息送达;橙色 = 有消息卡在某个会话的信箱里(那个 Claude 会话长时间空闲、
|
|
1361
|
-
// 唤醒 watcher 已退出,要等用户在那个终端开口才会送进去),需要用户过去看一眼。
|
|
1362
|
-
- (void)refreshBridgeBadge {
|
|
1363
|
-
CCPetsApprovalBadgeView *badge = (CCPetsApprovalBadgeView *)self.bridgeBadgeView;
|
|
1364
|
-
if (!badge) return;
|
|
1365
|
-
if (![NSUserDefaults.standardUserDefaults boolForKey:BridgeBadgeEnabledKey]) {
|
|
1366
|
-
badge.count = 0;
|
|
1367
|
-
return;
|
|
1368
|
-
}
|
|
1369
|
-
NSUInteger unseen = 0;
|
|
1370
|
-
for (NSDictionary *delivery in self.bridgeRecentDeliveries) {
|
|
1371
|
-
if ([delivery[@"at"] doubleValue] > self.bridgeSeenAt) unseen++;
|
|
1372
|
-
}
|
|
1373
|
-
NSUInteger waiting = 0;
|
|
1374
|
-
for (NSNumber *count in self.bridgePendingCounts.allValues) waiting += count.unsignedIntegerValue;
|
|
1375
|
-
badge.fillColor = waiting > 0
|
|
1376
|
-
? [NSColor colorWithRed:0.92 green:0.58 blue:0.12 alpha:1]
|
|
1377
|
-
: [NSColor colorWithRed:0.20 green:0.47 blue:0.90 alpha:1];
|
|
1378
|
-
badge.count = unseen + waiting;
|
|
1379
|
-
[self layoutApprovalBadge];
|
|
1380
|
-
}
|
|
1381
|
-
- (NSString *)bridgeSessionIdForRecord:(NSDictionary *)record {
|
|
1382
|
-
NSString *session = SanitizedShortString(record[@"session"], 128);
|
|
1383
|
-
if (session.length > 0 && self.bridgeSessions[session]) return session;
|
|
1384
|
-
// 事件里没有 session id 的记录,退回按 provider + tty 对上 bridge 注册表。
|
|
1385
|
-
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class] ? record[@"terminal"] : nil;
|
|
1386
|
-
NSString *tty = SanitizedShortString([terminal[@"tty"] lastPathComponent], 64);
|
|
1387
|
-
NSString *provider = SanitizedShortString(record[@"provider"], 32);
|
|
1388
|
-
if (tty.length == 0) return nil;
|
|
1389
|
-
__block NSString *match = nil;
|
|
1390
|
-
[self.bridgeSessions enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary *entry, BOOL *stop) {
|
|
1391
|
-
if ([entry[@"tty"] isEqualToString:tty] && [entry[@"provider"] isEqualToString:provider]) {
|
|
1392
|
-
match = key;
|
|
1393
|
-
*stop = YES;
|
|
1394
|
-
}
|
|
1395
|
-
}];
|
|
1396
|
-
return match;
|
|
1397
|
-
}
|
|
1398
|
-
- (NSDictionary *)bridgeSessionEntryForRecord:(NSDictionary *)record {
|
|
1399
|
-
NSString *session = [self bridgeSessionIdForRecord:record];
|
|
1400
|
-
return session ? self.bridgeSessions[session] : nil;
|
|
1401
|
-
}
|
|
1402
|
-
// 收件会话的终端:优先用桌宠自己记录的该会话终端信息(带宿主应用),其次按 tty 对上任一
|
|
1403
|
-
// 已知终端,最后借用最近一次的宿主应用配上 bridge 记录的 tty。
|
|
1404
|
-
- (NSDictionary *)terminalTargetForBridgeSession:(NSString *)sessionId {
|
|
1405
|
-
NSString *tty = self.bridgeSessions[sessionId][@"tty"];
|
|
1406
|
-
NSDictionary *byTty = nil;
|
|
1407
|
-
for (NSDictionary *record in self.agentSessionRecords.allValues) {
|
|
1408
|
-
NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class] ? record[@"terminal"] : nil;
|
|
1409
|
-
if (terminal.count == 0) continue;
|
|
1410
|
-
if ([SanitizedShortString(record[@"session"], 128) isEqualToString:sessionId]) return terminal;
|
|
1411
|
-
if (tty.length > 0 && [[terminal[@"tty"] lastPathComponent] isEqualToString:tty]) byTty = terminal;
|
|
1412
|
-
}
|
|
1413
|
-
if (byTty) return byTty;
|
|
1414
|
-
if (tty.length > 0 && self.lastTerminalFocusTarget.count > 0) {
|
|
1415
|
-
NSMutableDictionary *target = [self.lastTerminalFocusTarget mutableCopy];
|
|
1416
|
-
target[@"tty"] = tty;
|
|
1417
|
-
[target removeObjectForKey:@"session"];
|
|
1418
|
-
return target;
|
|
1419
|
-
}
|
|
1420
|
-
return nil;
|
|
1421
|
-
}
|
|
1422
|
-
- (void)focusBridgeSession:(NSMenuItem *)sender {
|
|
1423
|
-
NSString *sessionId = [sender.representedObject isKindOfClass:NSString.class] ? sender.representedObject : nil;
|
|
1424
|
-
NSDictionary *target = sessionId ? [self terminalTargetForBridgeSession:sessionId] : nil;
|
|
1425
|
-
if (target.count > 0) ActivateTerminalFocusTarget(target);
|
|
1426
|
-
}
|
|
1427
|
-
- (void)addBridgeItemsToMenu:(NSMenu *)menu deliveries:(NSArray<NSDictionary *> *)deliveries
|
|
1428
|
-
pending:(NSDictionary<NSString *, NSNumber *> *)pending {
|
|
1429
|
-
NSMenuItem *heading = [menu addItemWithTitle:@"CC Bridge 消息" action:nil keyEquivalent:@""];
|
|
1430
|
-
heading.enabled = NO;
|
|
1431
|
-
[pending enumerateKeysAndObjectsUsingBlock:^(NSString *session, NSNumber *count, BOOL *stop) {
|
|
1432
|
-
NSString *name = self.bridgeSessions[session][@"name"] ?: session;
|
|
1433
|
-
NSString *title = [NSString stringWithFormat:@"📬 %@ 有 %lu 条消息待投递(去那个终端说句话即可送达)",
|
|
1434
|
-
name, count.unsignedLongValue];
|
|
1435
|
-
NSMenuItem *item = [menu addItemWithTitle:title action:@selector(focusBridgeSession:) keyEquivalent:@""];
|
|
1436
|
-
item.target = self;
|
|
1437
|
-
item.representedObject = session;
|
|
1438
|
-
}];
|
|
1439
|
-
NSUInteger shown = 0;
|
|
1440
|
-
for (NSDictionary *delivery in deliveries) {
|
|
1441
|
-
if (shown++ >= BridgeMenuDeliveryLimit) break;
|
|
1442
|
-
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[delivery[@"at"] doubleValue]];
|
|
1443
|
-
NSString *time = [NSDateFormatter localizedStringFromDate:date
|
|
1444
|
-
dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle];
|
|
1445
|
-
BOOL unseen = [delivery[@"at"] doubleValue] > self.bridgeSeenAt;
|
|
1446
|
-
NSString *title = [NSString stringWithFormat:@"%@%@ → %@ · %@",
|
|
1447
|
-
unseen ? @"✉️ " : @"", delivery[@"from"], delivery[@"to"], time];
|
|
1448
|
-
NSMenuItem *item = [menu addItemWithTitle:title action:@selector(focusBridgeSession:) keyEquivalent:@""];
|
|
1449
|
-
item.target = self;
|
|
1450
|
-
item.representedObject = delivery[@"toSession"];
|
|
1451
|
-
item.toolTip = [NSString stringWithFormat:@"跳到 %@ 所在的终端", delivery[@"to"]];
|
|
1452
|
-
}
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
- (BOOL)focusLatestAgentTerminal {
|
|
1456
|
-
// 只有 Hook 状态气泡上的透明按钮会调用这里;桌宠本体继续负责原有互动。
|
|
1457
|
-
if (!self.hasAgentStatus || self.lastTerminalFocusTarget.count == 0) return NO;
|
|
1458
|
-
return ActivateTerminalFocusTarget(self.lastTerminalFocusTarget);
|
|
1459
|
-
}
|
|
1460
|
-
- (void)focusLatestAgentTerminal:(id)sender {
|
|
1461
|
-
[self focusLatestAgentTerminal];
|
|
1462
|
-
}
|
|
1463
|
-
- (NSDictionary *)petManifestInDirectory:(NSString *)directory {
|
|
1464
|
-
NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
|
|
1465
|
-
NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
|
|
1466
|
-
if (!jsonData) return @{};
|
|
1467
|
-
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
|
|
1468
|
-
return [json isKindOfClass:NSDictionary.class] ? json : @{};
|
|
1469
|
-
}
|
|
1470
|
-
- (NSInteger)spriteVersionInDirectory:(NSString *)directory fallbackDirectory:(NSString *)fallbackDirectory {
|
|
1471
|
-
NSArray<NSString *> *directories = fallbackDirectory.length > 0
|
|
1472
|
-
? @[directory, fallbackDirectory]
|
|
1473
|
-
: @[directory];
|
|
1474
|
-
for (NSString *candidate in directories) {
|
|
1475
|
-
id value = [self petManifestInDirectory:candidate][@"spriteVersionNumber"];
|
|
1476
|
-
if (![value isKindOfClass:NSNumber.class]) continue;
|
|
1477
|
-
NSInteger version = [value integerValue];
|
|
1478
|
-
if (version == 1 || version == 2) return version;
|
|
1479
|
-
}
|
|
1480
|
-
return 1;
|
|
1481
|
-
}
|
|
1482
|
-
- (NSInteger)spriteRowCountForVersion:(NSInteger)version {
|
|
1483
|
-
return version == 2 ? 11 : 9;
|
|
1484
|
-
}
|
|
1485
|
-
- (NSString *)spritePathInDirectory:(NSString *)directory {
|
|
1486
|
-
NSString *configuredName = nil;
|
|
1487
|
-
id value = [self petManifestInDirectory:directory][@"spritesheetPath"];
|
|
1488
|
-
if ([value isKindOfClass:NSString.class]) configuredName = [value lastPathComponent];
|
|
1489
|
-
NSMutableArray<NSString *> *names = [NSMutableArray array];
|
|
1490
|
-
if (configuredName.length > 0) [names addObject:configuredName];
|
|
1491
|
-
[names addObjectsFromArray:@[@"spritesheet.webp", @"spritesheet.png"]];
|
|
1492
|
-
for (NSString *name in names) {
|
|
1493
|
-
NSString *path = [directory stringByAppendingPathComponent:name];
|
|
1494
|
-
BOOL isDirectory = NO;
|
|
1495
|
-
if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && !isDirectory) return path;
|
|
1496
|
-
}
|
|
1497
|
-
return nil;
|
|
1498
|
-
}
|
|
1499
|
-
- (NSArray<NSString *> *)petDirectoryNamesAtPath:(NSString *)root {
|
|
1500
|
-
NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:root error:nil] ?: @[];
|
|
1501
|
-
NSMutableArray<NSString *> *directories = [NSMutableArray array];
|
|
1502
|
-
for (NSString *entry in entries) {
|
|
1503
|
-
if ([entry hasPrefix:@"."]) continue;
|
|
1504
|
-
BOOL isDirectory = NO;
|
|
1505
|
-
NSString *path = [root stringByAppendingPathComponent:entry];
|
|
1506
|
-
if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory) {
|
|
1507
|
-
[directories addObject:entry];
|
|
1508
|
-
}
|
|
1509
|
-
}
|
|
1510
|
-
return [directories sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
|
|
1511
|
-
}
|
|
1512
|
-
// 桌宠只扫 OwnPetsDirectory() 加包内素材,无条件、不看那里有没有东西。~/.petdex/pets 和
|
|
1513
|
-
// ~/.codex/pets 由别的工具写入,直接扫就永远分不清哪只是自己装的;要用 Codex 的素材就打开
|
|
1514
|
-
// "导入 Codex 素材"开关,由 ImportCodexPets 复制进来,之后它们和自己装的没有区别。
|
|
1515
|
-
- (NSArray<NSDictionary *> *)discoverPetOptions {
|
|
1516
|
-
NSString *ownRoot = OwnPetsDirectory();
|
|
1517
|
-
NSMutableArray<NSDictionary *> *result = [NSMutableArray array];
|
|
1518
|
-
|
|
1519
|
-
for (NSString *name in [self petDirectoryNamesAtPath:ownRoot]) {
|
|
1520
|
-
NSString *directory = [ownRoot stringByAppendingPathComponent:name];
|
|
1521
|
-
NSString *path = [self spritePathInDirectory:directory];
|
|
1522
|
-
if (!path) continue;
|
|
1523
|
-
NSInteger version = [self spriteVersionInDirectory:directory fallbackDirectory:nil];
|
|
1524
|
-
[result addObject:@{
|
|
1525
|
-
@"id": [@"external:" stringByAppendingString:name],
|
|
1526
|
-
@"name": name,
|
|
1527
|
-
@"path": path,
|
|
1528
|
-
@"spriteVersionNumber": @(version),
|
|
1529
|
-
@"spriteRowCount": @([self spriteRowCountForVersion:version])
|
|
1530
|
-
}];
|
|
1531
|
-
}
|
|
1532
|
-
|
|
1533
|
-
NSArray<NSString *> *bundled = [NSFileManager.defaultManager
|
|
1534
|
-
contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
|
|
1535
|
-
for (NSString *fileName in [bundled sortedArrayUsingSelector:@selector(localizedStandardCompare:)]) {
|
|
1536
|
-
NSString *extension = fileName.pathExtension.lowercaseString;
|
|
1537
|
-
if (![extension isEqualToString:@"webp"] && ![extension isEqualToString:@"png"]) continue;
|
|
1538
|
-
[result addObject:@{
|
|
1539
|
-
@"id": [@"builtin:" stringByAppendingString:fileName],
|
|
1540
|
-
@"name": fileName.stringByDeletingPathExtension,
|
|
1541
|
-
@"path": [self.binaryDirectory stringByAppendingPathComponent:fileName],
|
|
1542
|
-
@"spriteVersionNumber": @1,
|
|
1543
|
-
@"spriteRowCount": @9
|
|
1544
|
-
}];
|
|
1545
|
-
}
|
|
1546
|
-
return result;
|
|
1547
|
-
}
|
|
1548
|
-
// 素材目录的 mtime。目录里增删条目会改动它,而 `cc-pets pet add` / `remove` 正是在增删
|
|
1549
|
-
// 条目——所以这一个时间戳就足以判断列表是否需要重扫,不必每次打开菜单都遍历目录。
|
|
1550
|
-
- (NSDate *)petOptionsStamp {
|
|
1551
|
-
NSDictionary *attributes = [NSFileManager.defaultManager
|
|
1552
|
-
attributesOfItemAtPath:OwnPetsDirectory() error:nil];
|
|
1553
|
-
return attributes[NSFileModificationDate];
|
|
1554
|
-
}
|
|
1555
|
-
- (void)invalidatePetOptionsCache {
|
|
1556
|
-
self.cachedPetOptions = nil;
|
|
1557
|
-
self.cachedPetOptionsStamp = nil;
|
|
1558
|
-
}
|
|
1559
|
-
- (NSArray<NSDictionary *> *)petOptions {
|
|
1560
|
-
NSDate *stamp = [self petOptionsStamp];
|
|
1561
|
-
BOOL stale = !self.cachedPetOptions ||
|
|
1562
|
-
(stamp == nil) != (self.cachedPetOptionsStamp == nil) ||
|
|
1563
|
-
(stamp && ![stamp isEqualToDate:self.cachedPetOptionsStamp]);
|
|
1564
|
-
if (stale) {
|
|
1565
|
-
self.cachedPetOptions = [self discoverPetOptions];
|
|
1566
|
-
self.cachedPetOptionsStamp = stamp;
|
|
1567
|
-
}
|
|
1568
|
-
return self.cachedPetOptions;
|
|
1569
|
-
}
|
|
1570
|
-
- (NSDictionary *)petOptionWithID:(NSString *)petID inOptions:(NSArray<NSDictionary *> *)options {
|
|
1571
|
-
for (NSDictionary *option in options) if ([option[@"id"] isEqualToString:petID]) return option;
|
|
1572
|
-
return nil;
|
|
1573
|
-
}
|
|
1574
|
-
- (NSArray<NSDictionary *> *)waitForPetOptions {
|
|
1575
|
-
while (YES) {
|
|
1576
|
-
// 这个循环就是"重新扫描"按钮的实现,必须绕开缓存。
|
|
1577
|
-
[self invalidatePetOptionsCache];
|
|
1578
|
-
NSArray<NSDictionary *> *options = [self petOptions];
|
|
1579
|
-
if (options.count > 0) return options;
|
|
1580
|
-
|
|
1581
|
-
[NSApp activateIgnoringOtherApps:YES];
|
|
1582
|
-
NSAlert *alert = [NSAlert new];
|
|
1583
|
-
alert.messageText = @"没有找到桌宠素材";
|
|
1584
|
-
alert.informativeText = @"用 `cc-pets pet add <名称>` 下载素材,或把 PNG / WebP 精灵图放入 "
|
|
1585
|
-
@"~/.cc-pets/pets/<名称>/。桌宠不会去读 ~/.petdex/pets/ 和 ~/.codex/pets/;"
|
|
1586
|
-
@"要用 Codex 的素材,请在右键菜单打开“导入 Codex 素材”。完成后点击“重新扫描”。";
|
|
1587
|
-
[alert addButtonWithTitle:@"重新扫描"];
|
|
1588
|
-
[alert addButtonWithTitle:@"打开素材目录"];
|
|
1589
|
-
[alert addButtonWithTitle:@"退出"];
|
|
1590
|
-
NSModalResponse response = [alert runModal];
|
|
1591
|
-
if (response == NSAlertSecondButtonReturn) {
|
|
1592
|
-
NSString *directory = OwnPetsDirectory();
|
|
1593
|
-
[NSFileManager.defaultManager createDirectoryAtPath:directory
|
|
1594
|
-
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
1595
|
-
[NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:directory]];
|
|
1596
|
-
} else if (response == NSAlertThirdButtonReturn) {
|
|
1597
|
-
return @[];
|
|
1598
|
-
}
|
|
1599
|
-
}
|
|
1600
|
-
}
|
|
1601
64
|
// 建一个只有"编辑"的主菜单。
|
|
1602
65
|
//
|
|
1603
66
|
// ⌘C/⌘V/⌘A/⌘Z 不是 NSTextView 自己处理的:按键先走 NSApp.mainMenu 的
|
|
@@ -1613,19 +76,19 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1613
76
|
- (void)installEditMenu {
|
|
1614
77
|
if (NSApp.mainMenu) return;
|
|
1615
78
|
NSMenu *mainMenu = [NSMenu new];
|
|
1616
|
-
NSMenuItem *editItem = [mainMenu addItemWithTitle
|
|
1617
|
-
NSMenu *editMenu = [[NSMenu alloc] initWithTitle
|
|
79
|
+
NSMenuItem *editItem = [mainMenu addItemWithTitle:L(@"Edit") action:nil keyEquivalent:@""];
|
|
80
|
+
NSMenu *editMenu = [[NSMenu alloc] initWithTitle:L(@"Edit")];
|
|
1618
81
|
|
|
1619
82
|
NSArray<NSArray *> *entries = @[
|
|
1620
|
-
@[@"
|
|
1621
|
-
@[@"
|
|
83
|
+
@[L(@"Undo"), NSStringFromSelector(@selector(undo:)), @"z", @(NSEventModifierFlagCommand)],
|
|
84
|
+
@[L(@"Redo"), NSStringFromSelector(@selector(redo:)), @"z",
|
|
1622
85
|
@(NSEventModifierFlagCommand | NSEventModifierFlagShift)],
|
|
1623
86
|
@[@"-", @"", @"", @0],
|
|
1624
|
-
@[@"
|
|
1625
|
-
@[@"
|
|
1626
|
-
@[@"
|
|
1627
|
-
@[@"
|
|
1628
|
-
@[@"
|
|
87
|
+
@[L(@"Cut"), NSStringFromSelector(@selector(cut:)), @"x", @(NSEventModifierFlagCommand)],
|
|
88
|
+
@[L(@"Copy"), NSStringFromSelector(@selector(copy:)), @"c", @(NSEventModifierFlagCommand)],
|
|
89
|
+
@[L(@"Paste"), NSStringFromSelector(@selector(paste:)), @"v", @(NSEventModifierFlagCommand)],
|
|
90
|
+
@[L(@"Delete"), NSStringFromSelector(@selector(delete:)), @"", @0],
|
|
91
|
+
@[L(@"Select All"), NSStringFromSelector(@selector(selectAll:)), @"a", @(NSEventModifierFlagCommand)],
|
|
1629
92
|
];
|
|
1630
93
|
for (NSArray *entry in entries) {
|
|
1631
94
|
if ([entry[0] isEqualToString:@"-"]) {
|
|
@@ -1639,13 +102,18 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1639
102
|
editItem.submenu = editMenu;
|
|
1640
103
|
NSApp.mainMenu = mainMenu;
|
|
1641
104
|
}
|
|
1642
|
-
|
|
1643
105
|
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
|
|
1644
106
|
// 没有主菜单的话,台词编辑器里 ⌘C/⌘V/⌘A/⌘Z 全部没反应。
|
|
1645
107
|
[self installEditMenu];
|
|
1646
108
|
// 台词全在这个文件里,代码里没有第二份。首次启动先从默认词库拷一份出来,
|
|
1647
109
|
// 否则新装的桌宠一句话都不会说。
|
|
1648
110
|
PetPhrasesEnsureFileExists();
|
|
111
|
+
// 没改过的默认台词跟着界面语言走(例如英文系统上从旧版升级上来的用户)。
|
|
112
|
+
PetPhrasesAdoptLanguageDefaults();
|
|
113
|
+
// Node 端(cc-pets、hook、CC Bridge)读这个文件决定输出语言。
|
|
114
|
+
CCPetsWriteLanguageFile();
|
|
115
|
+
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(languageDidChange:)
|
|
116
|
+
name:CCPetsLanguageDidChangeNotification object:nil];
|
|
1649
117
|
if (![NSUserDefaults.standardUserDefaults boolForKey:PetInteractionPhrasesV1MigratedKey] &&
|
|
1650
118
|
PetPhrasesEnsureInteractionSections()) {
|
|
1651
119
|
[NSUserDefaults.standardUserDefaults setBool:YES
|
|
@@ -1694,7 +162,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1694
162
|
NSImage *image = LoadPetSpriteImage(spritePath, NSMakeSize(140, 150),
|
|
1695
163
|
[selectedOption[@"spriteRowCount"] integerValue] ?: 9);
|
|
1696
164
|
if (!image) {
|
|
1697
|
-
fprintf(stderr, "
|
|
165
|
+
fprintf(stderr, "%s\n", [NSString stringWithFormat:L(@"Can't read the pet sprite: %@"), spritePath].UTF8String);
|
|
1698
166
|
[NSApp terminate:nil];
|
|
1699
167
|
return;
|
|
1700
168
|
}
|
|
@@ -1731,6 +199,9 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1731
199
|
self.petView.petOptionsRequested = ^NSArray<NSDictionary *> *{
|
|
1732
200
|
return [weakSelf petOptions] ?: @[];
|
|
1733
201
|
};
|
|
202
|
+
self.petView.pendingUpdateVersionRequested = ^NSString *{
|
|
203
|
+
return weakSelf.updating ? nil : weakSelf.pendingUpdateVersion;
|
|
204
|
+
};
|
|
1734
205
|
self.petView.switchPetRequested = ^(NSString *petID) {
|
|
1735
206
|
[weakSelf switchPetToID:petID];
|
|
1736
207
|
};
|
|
@@ -1752,6 +223,38 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1752
223
|
selector:@selector(petWindowDidMove:)
|
|
1753
224
|
name:NSWindowDidMoveNotification object:self.panel];
|
|
1754
225
|
[root addSubview:self.petView];
|
|
226
|
+
// 有新版本时挂在宠物右上角的「↑」角标:气泡只冒一会儿,角标一直在,点一下弹更新窗口。
|
|
227
|
+
// 底子用和状态卡、气泡同一套 CCPetsGlassView,跟着面板主题和压暗档位走。
|
|
228
|
+
// 在 petView 之后加入,点击先落到角标上。
|
|
229
|
+
NSView *updateBadge = [[NSView alloc] initWithFrame:NSMakeRect(
|
|
230
|
+
NSMaxX(self.petView.frame) - 30, NSMaxY(self.petView.frame) - 28,
|
|
231
|
+
PetUpdateBadgeSize, PetUpdateBadgeSize)];
|
|
232
|
+
updateBadge.hidden = YES;
|
|
233
|
+
self.updateBadgeGlass = [[CCPetsGlassView alloc]
|
|
234
|
+
initWithFrame:updateBadge.bounds material:NSVisualEffectMaterialPopover
|
|
235
|
+
appearance:NSAppearanceNameAqua cornerRadius:PetUpdateBadgeSize / 2.0];
|
|
236
|
+
self.updateBadgeGlass.edgeShadeHeight = 4;
|
|
237
|
+
self.updateBadgeGlass.edgeShadeAlpha = 0.5;
|
|
238
|
+
self.updateBadgeGlass.usesWidgetGlass = YES;
|
|
239
|
+
[updateBadge addSubview:self.updateBadgeGlass];
|
|
240
|
+
self.updateBadgeArrow = [[NSImageView alloc] initWithFrame:updateBadge.bounds];
|
|
241
|
+
self.updateBadgeArrow.imageScaling = NSImageScaleNone;
|
|
242
|
+
self.updateBadgeArrow.image = [[NSImage imageWithSystemSymbolName:@"arrow.up"
|
|
243
|
+
accessibilityDescription:L(@"Update available")] imageWithSymbolConfiguration:
|
|
244
|
+
[NSImageSymbolConfiguration configurationWithPointSize:11 weight:NSFontWeightBold]];
|
|
245
|
+
[updateBadge addSubview:self.updateBadgeArrow];
|
|
246
|
+
CCPetsStatusClickButton *updateClick = [[CCPetsStatusClickButton alloc]
|
|
247
|
+
initWithFrame:updateBadge.bounds];
|
|
248
|
+
updateClick.bordered = NO;
|
|
249
|
+
updateClick.transparent = YES;
|
|
250
|
+
updateClick.title = @"";
|
|
251
|
+
updateClick.target = self;
|
|
252
|
+
updateClick.action = @selector(updateBubbleClicked:);
|
|
253
|
+
[updateBadge addSubview:updateClick];
|
|
254
|
+
self.updateBadgeButton = updateClick;
|
|
255
|
+
self.updateBadgeView = updateBadge;
|
|
256
|
+
[root addSubview:updateBadge];
|
|
257
|
+
[self applyUpdateBadgeStyle];
|
|
1755
258
|
|
|
1756
259
|
NSSize statusGlassSize = NSMakeSize(340, PetStatusBodyHeight);
|
|
1757
260
|
NSSize statusSize = NSMakeSize(statusGlassSize.width + 12, statusGlassSize.height + 12);
|
|
@@ -1819,7 +322,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1819
322
|
self.statusIconButton.wantsLayer = YES;
|
|
1820
323
|
self.statusIconButton.layer.cornerRadius = 17;
|
|
1821
324
|
self.statusIconButton.layer.masksToBounds = YES;
|
|
1822
|
-
self.statusIconButton.toolTip = @"
|
|
325
|
+
self.statusIconButton.toolTip = L(@"Recent Agent sessions and CC Bridge messages");
|
|
1823
326
|
self.statusIconButton.target = self;
|
|
1824
327
|
self.statusIconButton.action = @selector(showAgentSessionsMenu:);
|
|
1825
328
|
[self.statusGlass.contentView addSubview:self.statusIconButton];
|
|
@@ -1833,7 +336,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1833
336
|
statusClick.transparent = YES;
|
|
1834
337
|
statusClick.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
|
|
1835
338
|
statusClick.title = @"";
|
|
1836
|
-
statusClick.toolTip = @"
|
|
339
|
+
statusClick.toolTip = L(@"Go back to the Agent's terminal");
|
|
1837
340
|
statusClick.target = self;
|
|
1838
341
|
statusClick.action = @selector(focusLatestAgentTerminal:);
|
|
1839
342
|
self.statusClickButton = statusClick;
|
|
@@ -1935,6 +438,14 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1935
438
|
name:NSWorkspaceScreensDidSleepNotification object:nil];
|
|
1936
439
|
[workspaceCenter addObserver:self selector:@selector(screensDidWake:)
|
|
1937
440
|
name:NSWorkspaceScreensDidWakeNotification object:nil];
|
|
441
|
+
// 启动先让界面和事件流就位,再联网检查更新,别和启动抢时间。
|
|
442
|
+
[self performSelector:@selector(silentCheckForUpdate) withObject:nil afterDelay:5.0];
|
|
443
|
+
}
|
|
444
|
+
// CLI 启动时桌宠若已在运行,`open -g` 不会重新启动它,只会发一个 reopen 事件过来。
|
|
445
|
+
// 借这个时机同样静默检查一次更新(silentCheckForUpdate 自己做节流)。
|
|
446
|
+
- (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag {
|
|
447
|
+
[self silentCheckForUpdate];
|
|
448
|
+
return NO;
|
|
1938
449
|
}
|
|
1939
450
|
- (void)screensDidSleep:(NSNotification *)notification {
|
|
1940
451
|
[self.petView setAnimationSuspended:YES];
|
|
@@ -1942,920 +453,11 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
|
|
|
1942
453
|
- (void)screensDidWake:(NSNotification *)notification {
|
|
1943
454
|
[self.petView setAnimationSuspended:NO];
|
|
1944
455
|
}
|
|
1945
|
-
- (void)rescheduleUsageTimer {
|
|
1946
|
-
NSTimeInterval interval = self.quotaPanel.isVisible
|
|
1947
|
-
? UsageRefreshIntervalVisible : UsageRefreshIntervalHidden;
|
|
1948
|
-
if (self.usageTimer.isValid && self.usageTimer.timeInterval == interval) return;
|
|
1949
|
-
[self.usageTimer invalidate];
|
|
1950
|
-
self.usageTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self
|
|
1951
|
-
selector:@selector(refreshUsage:) userInfo:nil repeats:YES];
|
|
1952
|
-
self.usageTimer.tolerance = interval * 0.2;
|
|
1953
|
-
}
|
|
1954
|
-
// 全量聚合是同步的主线程活儿(本机实测数十毫秒,会话目录越大越久),而面板恰好由"鼠标
|
|
1955
|
-
// 停在口袋上"触发——那正是用户可能马上按下并拖动的时刻。事件被这几十毫秒挡住,mouseDown
|
|
1956
|
-
// 和 mouseDragged 就会成批迟到,手感上像是"鼠标走远了宠物才跟上"。
|
|
1957
|
-
// 因此:左键按着的时候不刷(拖动期间没人看数字),刚刷过的也不重刷(进出热区会反复触发)。
|
|
1958
|
-
static const NSTimeInterval UsageRefreshCoalesceWindow = 2.0;
|
|
1959
|
-
- (BOOL)shouldRefreshUsageForDashboard {
|
|
1960
|
-
if (CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, kCGMouseButtonLeft)) {
|
|
1961
|
-
return NO;
|
|
1962
|
-
}
|
|
1963
|
-
return NSDate.date.timeIntervalSince1970 - self.lastUsageRefreshAt >= UsageRefreshCoalesceWindow;
|
|
1964
|
-
}
|
|
1965
|
-
- (void)showQuotaDashboard {
|
|
1966
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
|
|
1967
|
-
if ([self shouldRefreshUsageForDashboard]) [self refreshUsage:nil];
|
|
1968
|
-
[self positionQuotaDashboard];
|
|
1969
|
-
[self.quotaPanel orderFrontRegardless];
|
|
1970
|
-
[self.panel orderFrontRegardless];
|
|
1971
|
-
[self rescheduleUsageTimer];
|
|
1972
|
-
[self startQuotaClock];
|
|
1973
|
-
[self updateSystemMetricsTimer];
|
|
1974
|
-
}
|
|
1975
|
-
- (BOOL)hasEnabledSystemMetric {
|
|
1976
|
-
return self.quotaView.systemCPUEnabled || self.quotaView.systemTemperatureEnabled ||
|
|
1977
|
-
self.quotaView.systemMemoryEnabled;
|
|
1978
|
-
}
|
|
1979
|
-
- (void)refreshSystemMetrics:(id)sender {
|
|
1980
|
-
if (![self hasEnabledSystemMetric]) return;
|
|
1981
|
-
BOOL cpuEnabled = self.quotaView.systemCPUEnabled;
|
|
1982
|
-
BOOL memoryEnabled = self.quotaView.systemMemoryEnabled;
|
|
1983
|
-
BOOL temperatureEnabled = self.quotaView.systemTemperatureEnabled;
|
|
1984
|
-
__weak typeof(self) weakSelf = self;
|
|
1985
|
-
[self.systemMonitor sampleCPU:cpuEnabled memory:memoryEnabled
|
|
1986
|
-
temperature:temperatureEnabled completion:^(NSNumber *cpu, NSNumber *memory,
|
|
1987
|
-
NSNumber *temperature) {
|
|
1988
|
-
typeof(self) strongSelf = weakSelf;
|
|
1989
|
-
if (!strongSelf) return;
|
|
1990
|
-
if (cpuEnabled) strongSelf.quotaView.systemCPUPercent = cpu;
|
|
1991
|
-
if (memoryEnabled) strongSelf.quotaView.systemMemoryPercent = memory;
|
|
1992
|
-
if (temperatureEnabled) strongSelf.quotaView.systemTemperatureCelsius = temperature;
|
|
1993
|
-
strongSelf.quotaView.needsDisplay = YES;
|
|
1994
|
-
}];
|
|
1995
|
-
}
|
|
1996
|
-
- (void)updateSystemMetricsTimer {
|
|
1997
|
-
BOOL shouldRun = self.quotaPanel.isVisible && [self hasEnabledSystemMetric];
|
|
1998
|
-
if (!shouldRun) {
|
|
1999
|
-
[self.systemMetricsTimer invalidate];
|
|
2000
|
-
self.systemMetricsTimer = nil;
|
|
2001
|
-
return;
|
|
2002
|
-
}
|
|
2003
|
-
if (self.systemMetricsTimer.isValid) return;
|
|
2004
|
-
[self refreshSystemMetrics:nil];
|
|
2005
|
-
__weak typeof(self) weakSelf = self;
|
|
2006
|
-
self.systemMetricsTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES
|
|
2007
|
-
block:^(NSTimer *timer) { [weakSelf refreshSystemMetrics:timer]; }];
|
|
2008
|
-
self.systemMetricsTimer.tolerance = 0.4;
|
|
2009
|
-
}
|
|
2010
|
-
// "数据刷新" 显示的是相对时间,没有新数据也得自己走字。面板隐藏时不需要这个定时器,
|
|
2011
|
-
// 隐藏的窗口本来就不会重绘。
|
|
2012
|
-
- (void)startQuotaClock {
|
|
2013
|
-
if (self.quotaClockTimer.isValid) return;
|
|
2014
|
-
self.quotaClockTimer = [NSTimer scheduledTimerWithTimeInterval:QuotaClockInterval
|
|
2015
|
-
target:self selector:@selector(tickQuotaClock:) userInfo:nil repeats:YES];
|
|
2016
|
-
self.quotaClockTimer.tolerance = QuotaClockInterval * 0.3;
|
|
2017
|
-
}
|
|
2018
|
-
- (void)tickQuotaClock:(id)sender {
|
|
2019
|
-
if (!self.quotaPanel.isVisible) {
|
|
2020
|
-
[self.quotaClockTimer invalidate];
|
|
2021
|
-
self.quotaClockTimer = nil;
|
|
2022
|
-
[self updateSystemMetricsTimer];
|
|
2023
|
-
return;
|
|
2024
|
-
}
|
|
2025
|
-
self.quotaView.needsDisplay = YES;
|
|
2026
|
-
}
|
|
2027
|
-
- (void)positionQuotaDashboard {
|
|
2028
|
-
NSRect petFrame = self.panel.frame;
|
|
2029
|
-
NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
|
|
2030
|
-
NSSize size = self.quotaPanel.frame.size;
|
|
2031
|
-
const CGFloat margin = 12;
|
|
2032
|
-
const CGFloat gap = 8;
|
|
2033
|
-
CGFloat minX = NSMinX(visible) + margin;
|
|
2034
|
-
CGFloat maxX = NSMaxX(visible) - size.width - margin;
|
|
2035
|
-
CGFloat minY = NSMinY(visible) + margin;
|
|
2036
|
-
CGFloat maxY = NSMaxY(visible) - size.height - margin;
|
|
2037
|
-
CGFloat leftX = NSMinX(petFrame) - size.width - gap;
|
|
2038
|
-
CGFloat rightX = NSMaxX(petFrame) + gap;
|
|
2039
|
-
CGFloat x;
|
|
2040
|
-
CGFloat y = fmax(minY, fmin(NSMinY(petFrame) + 112, maxY));
|
|
2041
|
-
|
|
2042
|
-
// 优先放在宠物左侧,其次右侧;两个可点击窗口之间始终留出间隔。
|
|
2043
|
-
if (leftX >= minX) {
|
|
2044
|
-
x = leftX;
|
|
2045
|
-
} else if (rightX <= maxX) {
|
|
2046
|
-
x = rightX;
|
|
2047
|
-
} else {
|
|
2048
|
-
// 横向空间不足时改放上/下方,避免屏幕边缘钳位后重新盖住宠物。
|
|
2049
|
-
x = fmax(minX, fmin(NSMidX(petFrame) - size.width / 2.0, maxX));
|
|
2050
|
-
CGFloat aboveY = NSMaxY(petFrame) + gap;
|
|
2051
|
-
CGFloat belowY = NSMinY(petFrame) - size.height - gap;
|
|
2052
|
-
if (aboveY <= maxY) y = aboveY;
|
|
2053
|
-
else if (belowY >= minY) y = belowY;
|
|
2054
|
-
else y = fmax(minY, fmin(aboveY, maxY));
|
|
2055
|
-
}
|
|
2056
|
-
[self.quotaPanel setFrameOrigin:NSMakePoint(x, y)];
|
|
2057
|
-
}
|
|
2058
456
|
- (void)petWindowDidMove:(NSNotification *)notification {
|
|
2059
457
|
if (self.quotaPanel.isVisible) [self positionQuotaDashboard];
|
|
2060
458
|
if (self.statusPanel.isVisible) [self positionAgentStatus];
|
|
2061
459
|
if (self.speechPanel.isVisible) [self positionSpeechPanel];
|
|
2062
460
|
}
|
|
2063
|
-
#pragma mark - 说话气泡
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
// 气泡停留时长。
|
|
2068
|
-
static const NSTimeInterval PetSpeechDwell = 4.5;
|
|
2069
|
-
// 气泡与状态卡的本体高度。
|
|
2070
|
-
//
|
|
2071
|
-
// 不要再加尾巴(三角、锥形、思考圆点都试过):药丸的圆角等于高度一半,整条边都是弧,
|
|
2072
|
-
// 尾巴只能从弧上长出来,怎么调都像贴上去的;换成圆角矩形能配尾巴,但那要放弃
|
|
2073
|
-
// layer.cornerRadius + kCACornerCurveContinuous 改用位图 maskImage 裁形,
|
|
2074
|
-
// squircle 和 GPU 端矢量裁切的质感一起丢了,得不偿失。
|
|
2075
|
-
// 结论:保持药丸 + 原生圆角,靠贴近宠物来表达归属。
|
|
2076
|
-
static const CGFloat PetSpeechBodyHeight = 38.0;
|
|
2077
|
-
static const CGFloat PetStatusBodyHeight = 58.0;
|
|
2078
|
-
// 副行没东西可显示时的高度,只放得下标题一行。
|
|
2079
|
-
static const CGFloat PetStatusSingleLineHeight = 40.0;
|
|
2080
|
-
|
|
2081
|
-
- (BOOL)speechEnabled {
|
|
2082
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
2083
|
-
// 缺省开启;用户可在右键菜单里关掉。
|
|
2084
|
-
id value = [defaults objectForKey:@"CCPetsSpeechEnabled"];
|
|
2085
|
-
return value == nil ? YES : [value boolValue];
|
|
2086
|
-
}
|
|
2087
|
-
// 当前档位。现读,右键菜单里改完立刻生效不用重启。
|
|
2088
|
-
- (PetSpeechRate)speechRate {
|
|
2089
|
-
NSString *value = [NSUserDefaults.standardUserDefaults stringForKey:PetSpeechFrequencyKey];
|
|
2090
|
-
if ([value isEqualToString:PetSpeechFrequencyLow]) return PetSpeechRateLow;
|
|
2091
|
-
if ([value isEqualToString:PetSpeechFrequencyHigh]) return PetSpeechRateHigh;
|
|
2092
|
-
if ([value isEqualToString:PetSpeechFrequencyChatty]) return PetSpeechRateChatty;
|
|
2093
|
-
return PetSpeechRateNormal;
|
|
2094
|
-
}
|
|
2095
|
-
// 预算与冷却。两道闸门都过了才允许说。
|
|
2096
|
-
// 默认跟随上面的档位;下面这两个键是更细的手动覆盖,写了就压过档位,
|
|
2097
|
-
// 现读,改完立刻生效不用重启:
|
|
2098
|
-
// defaults write com.universewang.cc-pets CCPetsSpeechCooldown -float 0
|
|
2099
|
-
// defaults write com.universewang.cc-pets CCPetsSpeechHourlyBudget -int 100
|
|
2100
|
-
// defaults delete com.universewang.cc-pets CCPetsSpeechCooldown # 交回档位
|
|
2101
|
-
// 域名是 bundle identifier,不是 "cc-pets"——写错域的话键会落在另一个 plist 里,
|
|
2102
|
-
// 桌宠永远看不到,表现为"设了没反应"。
|
|
2103
|
-
- (NSTimeInterval)speechCooldownSeconds {
|
|
2104
|
-
id value = [NSUserDefaults.standardUserDefaults objectForKey:@"CCPetsSpeechCooldown"];
|
|
2105
|
-
if (![value isKindOfClass:NSNumber.class]) return [self speechRate].cooldown;
|
|
2106
|
-
return MAX(0.0, [value doubleValue]);
|
|
2107
|
-
}
|
|
2108
|
-
- (NSInteger)speechHourlyBudget {
|
|
2109
|
-
id value = [NSUserDefaults.standardUserDefaults objectForKey:@"CCPetsSpeechHourlyBudget"];
|
|
2110
|
-
if (![value isKindOfClass:NSNumber.class]) return [self speechRate].hourlyBudget;
|
|
2111
|
-
return MAX((NSInteger)1, [value integerValue]);
|
|
2112
|
-
}
|
|
2113
|
-
// agent 是不是正在干活。只有"待机中"和状态卡压根没显示这两种情况算闲——
|
|
2114
|
-
// thinking / tool / subagent / approval / notification / completed / failed
|
|
2115
|
-
// 副行上都带着用户还需要看的信息,闲话一律让路。
|
|
2116
|
-
// 用 hasAgentStatus 而不是 statusPanel.isVisible:用户把状态卡折叠起来时卡片是隐藏的,
|
|
2117
|
-
// 但 agent 照样在干活,这时候冒气泡等于绕过折叠又把话糊到脸上。
|
|
2118
|
-
- (BOOL)agentBusyForSpeech {
|
|
2119
|
-
if (!self.hasAgentStatus) return NO;
|
|
2120
|
-
return ![self.lastStatusState isEqualToString:@"idle"];
|
|
2121
|
-
}
|
|
2122
|
-
- (BOOL)canSpeakNow {
|
|
2123
|
-
if (![self speechEnabled]) return NO;
|
|
2124
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2125
|
-
if (now < self.speechCooldownUntil) return NO;
|
|
2126
|
-
if (!self.speechTimestamps) self.speechTimestamps = [NSMutableArray array];
|
|
2127
|
-
while (self.speechTimestamps.count > 0 &&
|
|
2128
|
-
now - self.speechTimestamps.firstObject.doubleValue > 3600.0) {
|
|
2129
|
-
[self.speechTimestamps removeObjectAtIndex:0];
|
|
2130
|
-
}
|
|
2131
|
-
return (NSInteger)self.speechTimestamps.count < [self speechHourlyBudget];
|
|
2132
|
-
}
|
|
2133
|
-
// 当前可用的槽位值。取不到的键就不放进去,模板层会因此跳过需要它的那些条目。
|
|
2134
|
-
- (NSDictionary<NSString *, NSString *> *)speechSlots {
|
|
2135
|
-
return [self speechSlotsWithTool:self.lastSpeechTool];
|
|
2136
|
-
}
|
|
2137
|
-
- (NSDictionary<NSString *, NSString *> *)speechSlotsWithTool:(NSString *)tool {
|
|
2138
|
-
NSMutableDictionary<NSString *, NSString *> *slots = [NSMutableDictionary dictionary];
|
|
2139
|
-
NSCalendar *calendar = NSCalendar.currentCalendar;
|
|
2140
|
-
slots[@"hour"] = [@([calendar component:NSCalendarUnitHour fromDate:NSDate.date]) stringValue];
|
|
2141
|
-
if (self.consecutiveFailures > 0) {
|
|
2142
|
-
slots[@"failCount"] = [@(self.consecutiveFailures) stringValue];
|
|
2143
|
-
}
|
|
2144
|
-
if (self.sessionStartedAt > 0) {
|
|
2145
|
-
NSInteger minutes = (NSInteger)((NSDate.date.timeIntervalSince1970 -
|
|
2146
|
-
self.sessionStartedAt) / 60.0);
|
|
2147
|
-
if (minutes > 0) slots[@"sessionMin"] = [@(minutes) stringValue];
|
|
2148
|
-
}
|
|
2149
|
-
NSInteger remaining = [self remainingFiveHourQuotaPercent];
|
|
2150
|
-
if (remaining >= 0) {
|
|
2151
|
-
slots[@"quota5h"] = [NSString stringWithFormat:@"%ld%%", (long)remaining];
|
|
2152
|
-
}
|
|
2153
|
-
NSString *reset = [self fiveHourResetTimeText];
|
|
2154
|
-
if (reset.length > 0) slots[@"resetTime"] = reset;
|
|
2155
|
-
// 工具名此前从来没被填过,导致 "{toolName} 这货不靠谱。" 这类台词永远被跳过。
|
|
2156
|
-
NSString *trimmed = [tool stringByTrimmingCharactersInSet:
|
|
2157
|
-
NSCharacterSet.whitespaceCharacterSet];
|
|
2158
|
-
if (trimmed.length > 0 && trimmed.length <= 24) slots[@"toolName"] = trimmed;
|
|
2159
|
-
return slots;
|
|
2160
|
-
}
|
|
2161
|
-
// 5 小时窗口的剩余百分比,取不到返回 -1。Claude 和 Codex 的字段名不一样,都认。
|
|
2162
|
-
- (NSInteger)remainingFiveHourQuotaPercent {
|
|
2163
|
-
NSDictionary *usage = LatestClaudeUsage() ?: LatestUsage();
|
|
2164
|
-
NSDictionary *fiveHour = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
2165
|
-
? usage[@"fiveHour"] : nil;
|
|
2166
|
-
id used = fiveHour[@"used_percentage"] ?: fiveHour[@"used_percent"];
|
|
2167
|
-
if (![used isKindOfClass:NSNumber.class]) return -1;
|
|
2168
|
-
NSInteger remaining = 100 - [used integerValue];
|
|
2169
|
-
return MAX((NSInteger)0, MIN((NSInteger)100, remaining));
|
|
2170
|
-
}
|
|
2171
|
-
// 回血时间,按本机时区格式化。没有这个槽位的话,带 {resetTime} 的词条会被整条跳过。
|
|
2172
|
-
- (NSString *)fiveHourResetTimeText {
|
|
2173
|
-
NSDictionary *usage = LatestClaudeUsage() ?: LatestUsage();
|
|
2174
|
-
NSDictionary *fiveHour = [usage[@"fiveHour"] isKindOfClass:NSDictionary.class]
|
|
2175
|
-
? usage[@"fiveHour"] : nil;
|
|
2176
|
-
id resets = fiveHour[@"resets_at"];
|
|
2177
|
-
if (![resets isKindOfClass:NSNumber.class]) return nil;
|
|
2178
|
-
NSTimeInterval at = [resets doubleValue];
|
|
2179
|
-
if (at <= NSDate.date.timeIntervalSince1970) return nil;
|
|
2180
|
-
NSDateFormatter *formatter = [NSDateFormatter new];
|
|
2181
|
-
formatter.dateFormat = @"HH:mm";
|
|
2182
|
-
formatter.timeZone = NSTimeZone.systemTimeZone;
|
|
2183
|
-
return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:at]];
|
|
2184
|
-
}
|
|
2185
|
-
// 额度是"跨阈值"事件,不是状态事件,所以单独判档。
|
|
2186
|
-
//
|
|
2187
|
-
// 只在向下穿档时说一次:低于 20%% 就一直念叨会变成唠叨,而额度刷新是每分钟级别的,
|
|
2188
|
-
// 不设档位的话一小时预算瞬间就被烧光。回血(档位回升)时把标记还回去,
|
|
2189
|
-
// 下个周期才能再触发。
|
|
2190
|
-
- (void)considerQuotaSpeech {
|
|
2191
|
-
NSInteger remaining = [self remainingFiveHourQuotaPercent];
|
|
2192
|
-
if (remaining < 0) return;
|
|
2193
|
-
NSInteger tier;
|
|
2194
|
-
if (remaining <= 5) tier = 0;
|
|
2195
|
-
else if (remaining <= 10) tier = 1;
|
|
2196
|
-
else if (remaining <= 20) tier = 2;
|
|
2197
|
-
else tier = 3;
|
|
2198
|
-
|
|
2199
|
-
NSInteger previous = self.lastQuotaTier;
|
|
2200
|
-
self.lastQuotaTier = tier;
|
|
2201
|
-
// 首次拿到数据只记档不出声,免得每次启动都通报一遍额度。
|
|
2202
|
-
// (lastQuotaTier 的初值 0 恰好是最低档,不加这道判断的话冷启动必然误判成"刚跌到 5%"。)
|
|
2203
|
-
if (!self.lastQuotaTierInitialized) {
|
|
2204
|
-
self.lastQuotaTierInitialized = YES;
|
|
2205
|
-
return;
|
|
2206
|
-
}
|
|
2207
|
-
if (tier >= previous) return; // 回血或没跨档
|
|
2208
|
-
[self speakWithTag:PetPhraseTagQuotaLow];
|
|
2209
|
-
}
|
|
2210
|
-
- (void)buildSpeechPanelIfNeeded {
|
|
2211
|
-
if (self.speechPanel) return;
|
|
2212
|
-
NSSize glassSize = NSMakeSize(210, PetSpeechBodyHeight);
|
|
2213
|
-
NSSize size = NSMakeSize(glassSize.width + 12, glassSize.height + 12);
|
|
2214
|
-
self.speechPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, size.width, size.height)
|
|
2215
|
-
styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
|
|
2216
|
-
backing:NSBackingStoreBuffered defer:NO];
|
|
2217
|
-
self.speechPanel.opaque = NO;
|
|
2218
|
-
self.speechPanel.backgroundColor = NSColor.clearColor;
|
|
2219
|
-
self.speechPanel.hasShadow = NO;
|
|
2220
|
-
self.speechPanel.level = NSFloatingWindowLevel;
|
|
2221
|
-
self.speechPanel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
|
|
2222
|
-
NSWindowCollectionBehaviorFullScreenAuxiliary;
|
|
2223
|
-
// 气泡不抢焦点、不接受点击:它是纯播报,挡住宠物就本末倒置了。
|
|
2224
|
-
self.speechPanel.ignoresMouseEvents = YES;
|
|
2225
|
-
|
|
2226
|
-
NSView *root = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
|
|
2227
|
-
self.speechGlass = [[CCPetsGlassView alloc]
|
|
2228
|
-
initWithFrame:NSMakeRect(6, 6, glassSize.width, glassSize.height)
|
|
2229
|
-
material:NSVisualEffectMaterialPopover appearance:NSAppearanceNameAqua
|
|
2230
|
-
cornerRadius:glassSize.height / 2.0];
|
|
2231
|
-
self.speechGlass.edgeShadeHeight = 9;
|
|
2232
|
-
self.speechGlass.edgeShadeAlpha = 0.6;
|
|
2233
|
-
self.speechGlass.usesWidgetGlass = YES;
|
|
2234
|
-
|
|
2235
|
-
self.speechLabel = [NSTextField labelWithString:@""];
|
|
2236
|
-
self.speechLabel.frame = NSMakeRect(14, 10, glassSize.width - 28, 18);
|
|
2237
|
-
// 独立气泡里这句话是唯一元素,不与标题争,比并入状态卡时大半档。
|
|
2238
|
-
self.speechLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightMedium];
|
|
2239
|
-
self.speechLabel.textColor = [NSColor colorWithWhite:0.10 alpha:0.96];
|
|
2240
|
-
self.speechLabel.alignment = NSTextAlignmentCenter;
|
|
2241
|
-
self.speechLabel.lineBreakMode = NSLineBreakByTruncatingTail;
|
|
2242
|
-
[self.speechGlass.contentView addSubview:self.speechLabel];
|
|
2243
|
-
[root addSubview:self.speechGlass];
|
|
2244
|
-
[self applyBubbleTextStyle];
|
|
2245
|
-
self.speechPanel.contentView = root;
|
|
2246
|
-
}
|
|
2247
|
-
// 独立气泡只在没有状态卡时出现(有状态卡时话并进它的副行),所以固定放宠物头顶即可,
|
|
2248
|
-
// 不用再和状态卡抢位置。
|
|
2249
|
-
- (void)positionSpeechPanel {
|
|
2250
|
-
NSRect petFrame = self.panel.frame;
|
|
2251
|
-
NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
|
|
2252
|
-
NSSize size = self.speechPanel.frame.size;
|
|
2253
|
-
CGFloat x = NSMidX(petFrame) - size.width / 2.0;
|
|
2254
|
-
// 头顶放不下就翻到脚下,尾巴跟着改朝向长在顶边。
|
|
2255
|
-
CGFloat aboveY = NSMaxY(petFrame) - 6;
|
|
2256
|
-
BOOL fitsAbove = aboveY + size.height <= NSMaxY(visible) - 10;
|
|
2257
|
-
CGFloat y = fitsAbove ? aboveY : NSMinY(petFrame) - size.height + 6;
|
|
2258
|
-
x = fmax(NSMinX(visible) + 10, fmin(x, NSMaxX(visible) - size.width - 10));
|
|
2259
|
-
y = fmax(NSMinY(visible) + 10, fmin(y, NSMaxY(visible) - size.height - 10));
|
|
2260
|
-
[self.speechPanel setFrameOrigin:NSMakePoint(x, y)];
|
|
2261
|
-
}
|
|
2262
|
-
// 说一句。tag 取不到词条、预算用完、或状态卡正展开时都直接不说——
|
|
2263
|
-
// 两个泡同时挂在宠物头上会很吵。
|
|
2264
|
-
- (void)speakWithTag:(NSString *)tag {
|
|
2265
|
-
if (![self canSpeakNow]) return;
|
|
2266
|
-
NSString *text = PetPhraseForTag(tag, [self speechSlots]);
|
|
2267
|
-
if (text.length == 0) return;
|
|
2268
|
-
|
|
2269
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2270
|
-
[self.speechTimestamps addObject:@(now)];
|
|
2271
|
-
self.speechCooldownUntil = now + [self speechCooldownSeconds];
|
|
2272
|
-
|
|
2273
|
-
[self presentSpeechText:text];
|
|
2274
|
-
}
|
|
2275
|
-
// 话往哪儿显示只在这一处决定:有状态卡就并进它的副行,没有才起独立气泡。
|
|
2276
|
-
// 调试触发也必须走这里——否则看到的是现实中不会出现的画面(两个泡叠着)。
|
|
2277
|
-
- (void)presentSpeechText:(NSString *)text {
|
|
2278
|
-
if (text.length == 0) return;
|
|
2279
|
-
if (self.statusPanel.isVisible) {
|
|
2280
|
-
self.statusDetailLabel.stringValue = text;
|
|
2281
|
-
[self resizeStatusCardToFitText];
|
|
2282
|
-
[self positionAgentStatus];
|
|
2283
|
-
// 上一句的独立气泡可能还没淡完,收掉它,别和状态卡叠着。
|
|
2284
|
-
[self hideSpeechBubble];
|
|
2285
|
-
// 副行是状态卡的正文,借走说一句之后必须还回去,否则闲话会一直挂着,
|
|
2286
|
-
// 看起来像状态卡卡死了。
|
|
2287
|
-
//
|
|
2288
|
-
// 这里刻意不写 lastPetVoiceText/lastPetVoiceTag:那两个是状态文案的
|
|
2289
|
-
// 去重缓存,被闲话污染的话 restoreStatusDetail 就没有东西可还,而且
|
|
2290
|
-
// 下一次同状态事件会把闲话当成"该状态的文案"复读出来。
|
|
2291
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
2292
|
-
selector:@selector(restoreStatusDetail) object:nil];
|
|
2293
|
-
[self performSelector:@selector(restoreStatusDetail) withObject:nil
|
|
2294
|
-
afterDelay:PetSpeechDwell];
|
|
2295
|
-
return;
|
|
2296
|
-
}
|
|
2297
|
-
[self showSpeechBubbleWithText:text];
|
|
2298
|
-
}
|
|
2299
|
-
// 把副行还给状态文案。lastPetVoiceText 里存的就是当前状态本该显示的那句。
|
|
2300
|
-
- (void)restoreStatusDetail {
|
|
2301
|
-
if (!self.statusPanel.isVisible || self.lastPetVoiceText.length == 0) return;
|
|
2302
|
-
self.statusDetailLabel.stringValue = self.lastPetVoiceText;
|
|
2303
|
-
[self resizeStatusCardToFitText];
|
|
2304
|
-
[self positionAgentStatus];
|
|
2305
|
-
}
|
|
2306
|
-
- (void)showSpeechBubbleWithText:(NSString *)text {
|
|
2307
|
-
[self buildSpeechPanelIfNeeded];
|
|
2308
|
-
self.speechLabel.stringValue = text;
|
|
2309
|
-
[self resizeSpeechBubbleToFitText];
|
|
2310
|
-
[self positionSpeechPanel];
|
|
2311
|
-
self.speechPanel.alphaValue = 0;
|
|
2312
|
-
[self.speechPanel orderFront:nil];
|
|
2313
|
-
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
|
|
2314
|
-
context.duration = 0.18;
|
|
2315
|
-
self.speechPanel.animator.alphaValue = 1.0;
|
|
2316
|
-
} completionHandler:nil];
|
|
2317
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self
|
|
2318
|
-
selector:@selector(hideSpeechBubble) object:nil];
|
|
2319
|
-
[self performSelector:@selector(hideSpeechBubble) withObject:nil afterDelay:PetSpeechDwell];
|
|
2320
|
-
}
|
|
2321
|
-
// 调试触发:写一个标签进 defaults,下一跳(≤3 秒)就强制弹一次独立气泡,
|
|
2322
|
-
// 绕开安静期、概率、预算和状态卡判断,弹完自动把键删掉,不会残留。
|
|
2323
|
-
// defaults write com.universewang.cc-pets CCPetsSpeechDebugTag -string idle
|
|
2324
|
-
// 标签可填 idle / done / fail / quota_low / late_night / long_session / wake
|
|
2325
|
-
- (void)consumeSpeechDebugTrigger {
|
|
2326
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
2327
|
-
id value = [defaults objectForKey:@"CCPetsSpeechDebugTag"];
|
|
2328
|
-
if (![value isKindOfClass:NSString.class] || [value length] == 0) return;
|
|
2329
|
-
[defaults removeObjectForKey:@"CCPetsSpeechDebugTag"];
|
|
2330
|
-
NSString *text = PetPhraseForTag(value, [self speechSlots]);
|
|
2331
|
-
if (text.length == 0) text = @"(这个标签取不到词条)";
|
|
2332
|
-
[self presentSpeechText:text];
|
|
2333
|
-
}
|
|
2334
|
-
- (void)hideSpeechBubble {
|
|
2335
|
-
if (!self.speechPanel) return;
|
|
2336
|
-
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
|
|
2337
|
-
context.duration = 0.22;
|
|
2338
|
-
self.speechPanel.animator.alphaValue = 0;
|
|
2339
|
-
} completionHandler:^{
|
|
2340
|
-
if (self.speechPanel.alphaValue <= 0.01) [self.speechPanel orderOut:nil];
|
|
2341
|
-
}];
|
|
2342
|
-
}
|
|
2343
|
-
// 闲着时候的自发说话。
|
|
2344
|
-
//
|
|
2345
|
-
// 光挂在 agent 事件流上是不够的:那样宠物永远只会就着工作说话,late_night /
|
|
2346
|
-
// long_session / idle 这些词条根本没有属于自己的触发时机,独立气泡也永远不会出现
|
|
2347
|
-
// (agent 事件必定先把状态卡显示出来,话就并进去了)。
|
|
2348
|
-
//
|
|
2349
|
-
// 挂在已有的客户端存活定时器上,不新起 timer——常驻唤醒一个都不该多。
|
|
2350
|
-
- (void)considerIdleSpeech {
|
|
2351
|
-
[self consumeSpeechDebugTrigger];
|
|
2352
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2353
|
-
// 真正的判断最多 30 秒做一次,3 秒一跳的定时器上不必每次都算。
|
|
2354
|
-
if (now - self.lastIdleSpeechCheck < 30.0) return;
|
|
2355
|
-
self.lastIdleSpeechCheck = now;
|
|
2356
|
-
// agent 正在干活时闭嘴——工作文案优先级最高,闲话不许顶掉它。
|
|
2357
|
-
// 注意判断的是"在不在干活",不是"状态卡在不在":状态卡只要客户端活着就常驻,
|
|
2358
|
-
// 用它当闸门等于开着终端就永远不碎碎念。
|
|
2359
|
-
if ([self agentBusyForSpeech]) return;
|
|
2360
|
-
if (![self canSpeakNow]) return;
|
|
2361
|
-
|
|
2362
|
-
// 安静多久才算"没人打扰"。复用无聊曲线那个缩放旋钮,测试时一并压缩。
|
|
2363
|
-
double scale = 1.0;
|
|
2364
|
-
id scaleValue = [NSUserDefaults.standardUserDefaults objectForKey:@"CCPetsBoredomScale"];
|
|
2365
|
-
if ([scaleValue isKindOfClass:NSNumber.class] && [scaleValue doubleValue] > 0) {
|
|
2366
|
-
scale = MIN([scaleValue doubleValue], 10.0);
|
|
2367
|
-
}
|
|
2368
|
-
PetSpeechRate rate = [self speechRate];
|
|
2369
|
-
NSTimeInterval quiet = self.lastAgentEventAt > 0 ? now - self.lastAgentEventAt : now;
|
|
2370
|
-
if (quiet < rate.quietSeconds * scale) return;
|
|
2371
|
-
|
|
2372
|
-
// 不是每次够条件都说:概率化,免得变成整点报时。
|
|
2373
|
-
if (arc4random_uniform(100) >= rate.idleChancePercent) return;
|
|
2374
|
-
|
|
2375
|
-
NSInteger hour = [NSCalendar.currentCalendar component:NSCalendarUnitHour fromDate:NSDate.date];
|
|
2376
|
-
NSTimeInterval sessionLength = self.sessionStartedAt > 0 ? now - self.sessionStartedAt : 0;
|
|
2377
|
-
if (hour >= 1 && hour < 5) [self speakWithTag:PetPhraseTagLateNight];
|
|
2378
|
-
else if (sessionLength > 90 * 60.0) [self speakWithTag:PetPhraseTagLongSession];
|
|
2379
|
-
else [self speakWithTag:PetPhraseTagIdle];
|
|
2380
|
-
}
|
|
2381
|
-
// 只在显著时刻说话,不是每个 agent 事件都冒泡。
|
|
2382
|
-
- (void)considerSpeechForRecord:(NSDictionary *)record {
|
|
2383
|
-
self.lastAgentEventAt = NSDate.date.timeIntervalSince1970;
|
|
2384
|
-
NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : nil;
|
|
2385
|
-
if (tool.length > 0) self.lastSpeechTool = tool;
|
|
2386
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
2387
|
-
NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
|
|
2388
|
-
BOOL failed = [record[@"failed"] boolValue];
|
|
2389
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2390
|
-
|
|
2391
|
-
if ([event isEqualToString:@"SessionStart"]) {
|
|
2392
|
-
// 久别重逢:距上次会话超过 4 小时才算,不然每开一个终端都要寒暄一遍。
|
|
2393
|
-
BOOL longGap = self.sessionStartedAt <= 0 || now - self.sessionStartedAt > 4 * 3600.0;
|
|
2394
|
-
self.sessionStartedAt = now;
|
|
2395
|
-
self.consecutiveFailures = 0;
|
|
2396
|
-
if (longGap) [self speakWithTag:PetPhraseTagWake];
|
|
2397
|
-
return;
|
|
2398
|
-
}
|
|
2399
|
-
if (failed) {
|
|
2400
|
-
self.consecutiveFailures += 1;
|
|
2401
|
-
// 单次失败很常见,连续两次才值得出声。
|
|
2402
|
-
if (self.consecutiveFailures >= 2) [self speakWithTag:PetPhraseTagFail];
|
|
2403
|
-
return;
|
|
2404
|
-
}
|
|
2405
|
-
if ([state isEqualToString:@"completed"]) {
|
|
2406
|
-
self.consecutiveFailures = 0;
|
|
2407
|
-
NSInteger hour = [NSCalendar.currentCalendar component:NSCalendarUnitHour
|
|
2408
|
-
fromDate:NSDate.date];
|
|
2409
|
-
NSTimeInterval sessionLength = self.sessionStartedAt > 0 ? now - self.sessionStartedAt : 0;
|
|
2410
|
-
// 同一时刻可能同时满足几个情境,按"更值得一提"的顺序挑一个说,不叠着说。
|
|
2411
|
-
if (hour >= 1 && hour < 5) [self speakWithTag:PetPhraseTagLateNight];
|
|
2412
|
-
else if (sessionLength > 90 * 60.0) [self speakWithTag:PetPhraseTagLongSession];
|
|
2413
|
-
else [self speakWithTag:PetPhraseTagDone];
|
|
2414
|
-
}
|
|
2415
|
-
}
|
|
2416
|
-
#pragma mark - 宽度自适应
|
|
2417
|
-
|
|
2418
|
-
// 卡片和气泡都按文案实际宽度伸缩。固定宽度下"收工!"和"到处翻资料呢。"占一样长的条,
|
|
2419
|
-
// 前者会拖着一大截空白,看着像没加载完。
|
|
2420
|
-
// 用控件自己的 fittingSize 量,不要用 sizeWithAttributes:。
|
|
2421
|
-
// NSTextField 的 cell 有一点内部留白,纯按字符串量出来的宽度会比控件真正需要的小几个点,
|
|
2422
|
-
// 结果就是明明算着"刚好够",显示出来最后一两个字变成省略号。
|
|
2423
|
-
static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
|
|
2424
|
-
if (label.stringValue.length == 0) return 0;
|
|
2425
|
-
return ceil(label.fittingSize.width) + 2;
|
|
2426
|
-
}
|
|
2427
|
-
// 状态卡:左内边距 20 + 文字 + 间隙 8 + 图标 34 + 右内边距 14。
|
|
2428
|
-
- (void)resizeStatusCardToFitText {
|
|
2429
|
-
const CGFloat leading = 20, gap = 8, iconWidth = 34, trailing = 14;
|
|
2430
|
-
// 副行没内容时收成单行,而不是留一块空白。
|
|
2431
|
-
//
|
|
2432
|
-
// 台词全在 speech.txt 里,代码里没有兜底文案:用户把某个 state_ 小节清空了,
|
|
2433
|
-
// 副行就真的没有东西可显示。编辑器保存时会拦下这种文件,但外部编辑器绕得过去,
|
|
2434
|
-
// 所以显示层必须自己站得住。
|
|
2435
|
-
BOOL hasDetail = self.statusDetailLabel.stringValue.length > 0;
|
|
2436
|
-
CGFloat height = hasDetail ? PetStatusBodyHeight : PetStatusSingleLineHeight;
|
|
2437
|
-
CGFloat textWidth = PetMeasuredLabelWidth(self.statusTitleLabel);
|
|
2438
|
-
if (hasDetail) {
|
|
2439
|
-
textWidth = fmax(textWidth, PetMeasuredLabelWidth(self.statusDetailLabel));
|
|
2440
|
-
}
|
|
2441
|
-
CGFloat glassWidth = leading + textWidth + gap + iconWidth + trailing;
|
|
2442
|
-
glassWidth = fmax(210.0, fmin(glassWidth, 420.0));
|
|
2443
|
-
// 高度也要参与早退判断,否则单行/双行之间切换时尺寸不会更新。
|
|
2444
|
-
if (fabs(NSWidth(self.statusGlass.frame) - glassWidth) < 0.5 &&
|
|
2445
|
-
fabs(NSHeight(self.statusGlass.frame) - height) < 0.5) return;
|
|
2446
|
-
|
|
2447
|
-
NSSize panelSize = NSMakeSize(glassWidth + 12, height + 12);
|
|
2448
|
-
[self.statusPanel setContentSize:panelSize];
|
|
2449
|
-
self.statusPanel.contentView.frame = NSMakeRect(0, 0, panelSize.width, panelSize.height);
|
|
2450
|
-
self.statusGlass.frame = NSMakeRect(6, 6, glassWidth, height);
|
|
2451
|
-
self.statusGlass.cornerRadius = height / 2.0;
|
|
2452
|
-
self.statusShadowView.frame = NSMakeRect(6, 6, glassWidth, height);
|
|
2453
|
-
self.statusShadowView.layer.cornerRadius = height / 2.0;
|
|
2454
|
-
// shadowPath 是按旧尺寸算死的,卡片变宽后不重算,阴影会留在原来的形状上。
|
|
2455
|
-
CGPathRef path = CGPathCreateWithRoundedRect(self.statusShadowView.bounds,
|
|
2456
|
-
height / 2.0, height / 2.0, NULL);
|
|
2457
|
-
self.statusShadowView.layer.shadowPath = path;
|
|
2458
|
-
CGPathRelease(path);
|
|
2459
|
-
|
|
2460
|
-
CGFloat labelWidth = glassWidth - leading - gap - iconWidth - trailing;
|
|
2461
|
-
self.statusDetailLabel.hidden = !hasDetail;
|
|
2462
|
-
if (hasDetail) {
|
|
2463
|
-
self.statusTitleLabel.frame = NSMakeRect(leading, 34, labelWidth, 14);
|
|
2464
|
-
self.statusDetailLabel.frame = NSMakeRect(leading, 10, labelWidth, 22);
|
|
2465
|
-
} else {
|
|
2466
|
-
self.statusTitleLabel.frame = NSMakeRect(leading, (height - 14) / 2.0, labelWidth, 14);
|
|
2467
|
-
}
|
|
2468
|
-
self.statusIconButton.frame = NSMakeRect(glassWidth - trailing - iconWidth,
|
|
2469
|
-
(height - iconWidth) / 2.0, iconWidth, iconWidth);
|
|
2470
|
-
self.statusClickButton.frame = NSMakeRect(6, 6, glassWidth - 56, height);
|
|
2471
|
-
}
|
|
2472
|
-
|
|
2473
|
-
// 独立气泡:左右各 16 内边距,没有图标。
|
|
2474
|
-
- (void)resizeSpeechBubbleToFitText {
|
|
2475
|
-
const CGFloat padding = 16;
|
|
2476
|
-
CGFloat width = padding * 2 + PetMeasuredLabelWidth(self.speechLabel);
|
|
2477
|
-
width = fmax(96.0, fmin(width, 300.0));
|
|
2478
|
-
NSSize panelSize = NSMakeSize(width + 12, PetSpeechBodyHeight + 12);
|
|
2479
|
-
[self.speechPanel setContentSize:panelSize];
|
|
2480
|
-
self.speechPanel.contentView.frame = NSMakeRect(0, 0, panelSize.width, panelSize.height);
|
|
2481
|
-
self.speechGlass.frame = NSMakeRect(6, 6, width, PetSpeechBodyHeight);
|
|
2482
|
-
self.speechGlass.cornerRadius = PetSpeechBodyHeight / 2.0;
|
|
2483
|
-
self.speechLabel.frame = NSMakeRect(padding, 10, width - padding * 2, 18);
|
|
2484
|
-
}
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
// 面板底边到"最小那颗圆点底边"的距离。定位要拿它反推面板该放多高,
|
|
2488
|
-
// 才能让圆点正好落在宠物头顶而不是悬在空中。
|
|
2489
|
-
- (void)positionAgentStatus {
|
|
2490
|
-
NSRect petFrame = self.panel.frame;
|
|
2491
|
-
NSRect visible = (self.panel.screen ?: NSScreen.mainScreen).visibleFrame;
|
|
2492
|
-
NSSize size = self.statusPanel.frame.size;
|
|
2493
|
-
CGFloat x = NSMidX(petFrame) - size.width / 2.0;
|
|
2494
|
-
CGFloat aboveY = NSMaxY(petFrame) + 8;
|
|
2495
|
-
CGFloat belowY = NSMinY(petFrame) - size.height - 8;
|
|
2496
|
-
BOOL aboveFits = aboveY + size.height <= NSMaxY(visible) - 10;
|
|
2497
|
-
BOOL belowFits = belowY >= NSMinY(visible) + 10;
|
|
2498
|
-
self.statusBubbleAbove = aboveFits || !belowFits;
|
|
2499
|
-
CGFloat y = self.statusBubbleAbove ? aboveY : belowY;
|
|
2500
|
-
x = fmax(NSMinX(visible) + 10, fmin(x, NSMaxX(visible) - size.width - 10));
|
|
2501
|
-
y = fmax(NSMinY(visible) + 10, fmin(y, NSMaxY(visible) - size.height - 10));
|
|
2502
|
-
[self.statusPanel setFrameOrigin:NSMakePoint(x, y)];
|
|
2503
|
-
}
|
|
2504
|
-
- (void)scheduleQuotaDashboardHide {
|
|
2505
|
-
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideQuotaDashboardIfNeeded) object:nil];
|
|
2506
|
-
[self performSelector:@selector(hideQuotaDashboardIfNeeded) withObject:nil afterDelay:0.28];
|
|
2507
|
-
}
|
|
2508
|
-
- (void)hideQuotaDashboardIfNeeded {
|
|
2509
|
-
if (!self.pocketHovering && !self.dashboardHovering && !self.petDragging) {
|
|
2510
|
-
[self.quotaPanel orderOut:nil];
|
|
2511
|
-
[self rescheduleUsageTimer];
|
|
2512
|
-
[self.quotaClockTimer invalidate];
|
|
2513
|
-
self.quotaClockTimer = nil;
|
|
2514
|
-
[self updateSystemMetricsTimer];
|
|
2515
|
-
}
|
|
2516
|
-
}
|
|
2517
|
-
- (void)switchPetToID:(NSString *)petID {
|
|
2518
|
-
NSArray<NSDictionary *> *options = [self petOptions];
|
|
2519
|
-
NSDictionary *option = [self petOptionWithID:petID inOptions:options];
|
|
2520
|
-
if (!option) return;
|
|
2521
|
-
NSInteger spriteRowCount = [option[@"spriteRowCount"] integerValue] ?: 9;
|
|
2522
|
-
NSImage *image = LoadPetSpriteImage(option[@"path"], NSMakeSize(140, 150), spriteRowCount);
|
|
2523
|
-
if (!image) return;
|
|
2524
|
-
[self.petView applySheet:image petID:petID rowCount:spriteRowCount];
|
|
2525
|
-
PetPhrasesSetCurrentPetID(petID);
|
|
2526
|
-
[NSUserDefaults.standardUserDefaults setObject:petID forKey:@"CCPetsSelectedSprite"];
|
|
2527
|
-
}
|
|
2528
|
-
- (BOOL)deletePetWithID:(NSString *)petID {
|
|
2529
|
-
if (![petID hasPrefix:@"external:"]) return NO;
|
|
2530
|
-
NSArray<NSDictionary *> *options = [self petOptions];
|
|
2531
|
-
NSDictionary *option = [self petOptionWithID:petID inOptions:options];
|
|
2532
|
-
if (!option) return NO;
|
|
2533
|
-
|
|
2534
|
-
NSString *name = [petID substringFromIndex:@"external:".length];
|
|
2535
|
-
if (name.length == 0 || [name containsString:@"/"] || [name isEqualToString:@"."] ||
|
|
2536
|
-
[name isEqualToString:@".."]) return NO;
|
|
2537
|
-
NSString *root = OwnPetsDirectory().stringByStandardizingPath;
|
|
2538
|
-
NSString *directory = [root stringByAppendingPathComponent:name].stringByStandardizingPath;
|
|
2539
|
-
NSString *optionDirectory = [[option[@"path"] stringByDeletingLastPathComponent] stringByStandardizingPath];
|
|
2540
|
-
if (![directory.stringByDeletingLastPathComponent isEqualToString:root] ||
|
|
2541
|
-
![optionDirectory isEqualToString:directory]) return NO;
|
|
2542
|
-
|
|
2543
|
-
NSError *error = nil;
|
|
2544
|
-
if (![NSFileManager.defaultManager removeItemAtPath:directory error:&error]) {
|
|
2545
|
-
[self showUpdateAlertWithTitle:@"无法删除素材"
|
|
2546
|
-
message:error.localizedDescription ?: @"素材目录删除失败。"];
|
|
2547
|
-
return NO;
|
|
2548
|
-
}
|
|
2549
|
-
|
|
2550
|
-
[self invalidatePetOptionsCache];
|
|
2551
|
-
if ([self.petView.currentPetID isEqualToString:petID]) {
|
|
2552
|
-
NSDictionary *fallback = [self petOptions].firstObject;
|
|
2553
|
-
if (fallback) [self switchPetToID:fallback[@"id"]];
|
|
2554
|
-
else {
|
|
2555
|
-
PetPhrasesSetCurrentPetID(nil);
|
|
2556
|
-
[NSUserDefaults.standardUserDefaults removeObjectForKey:@"CCPetsSelectedSprite"];
|
|
2557
|
-
}
|
|
2558
|
-
}
|
|
2559
|
-
return YES;
|
|
2560
|
-
}
|
|
2561
|
-
- (void)prepareAgentEventReader {
|
|
2562
|
-
NSString *path = AgentEventPath();
|
|
2563
|
-
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
2564
|
-
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
2565
|
-
if (self.agentEventReaderInitialized) {
|
|
2566
|
-
if (size < self.agentEventOffset) {
|
|
2567
|
-
self.agentEventOffset = 0;
|
|
2568
|
-
[self.agentEventPartialLine setLength:0];
|
|
2569
|
-
}
|
|
2570
|
-
[self readNewAgentEvents];
|
|
2571
|
-
return;
|
|
2572
|
-
}
|
|
2573
|
-
self.agentEventReaderInitialized = YES;
|
|
2574
|
-
self.agentEventOffset = size;
|
|
2575
|
-
if (size > 0) {
|
|
2576
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
|
|
2577
|
-
unsigned long long start = size > 65536 ? size - 65536 : 0;
|
|
2578
|
-
[handle seekToFileOffset:start];
|
|
2579
|
-
NSData *recent = [handle readDataToEndOfFile];
|
|
2580
|
-
[handle closeFile];
|
|
2581
|
-
[self processAgentEventData:recent ignoreFirstPartial:start > 0 recentOnly:YES];
|
|
2582
|
-
}
|
|
2583
|
-
}
|
|
2584
|
-
- (void)consumeAgentEventData:(NSData *)data {
|
|
2585
|
-
if (data.length == 0) return;
|
|
2586
|
-
[self.agentEventPartialLine appendData:data];
|
|
2587
|
-
const uint8_t *bytes = self.agentEventPartialLine.bytes;
|
|
2588
|
-
NSUInteger lineStart = 0;
|
|
2589
|
-
for (NSUInteger index = 0; index < self.agentEventPartialLine.length; index++) {
|
|
2590
|
-
if (bytes[index] != '\n') continue;
|
|
2591
|
-
NSData *lineData = [self.agentEventPartialLine subdataWithRange:NSMakeRange(lineStart, index - lineStart)];
|
|
2592
|
-
[self processAgentEventData:lineData ignoreFirstPartial:NO recentOnly:NO];
|
|
2593
|
-
lineStart = index + 1;
|
|
2594
|
-
}
|
|
2595
|
-
if (lineStart > 0) {
|
|
2596
|
-
NSData *remainder = [self.agentEventPartialLine subdataWithRange:
|
|
2597
|
-
NSMakeRange(lineStart, self.agentEventPartialLine.length - lineStart)];
|
|
2598
|
-
self.agentEventPartialLine = [remainder mutableCopy];
|
|
2599
|
-
}
|
|
2600
|
-
if (self.agentEventPartialLine.length > 1024 * 1024) [self.agentEventPartialLine setLength:0];
|
|
2601
|
-
}
|
|
2602
|
-
- (void)processAgentEventData:(NSData *)data ignoreFirstPartial:(BOOL)ignoreFirstPartial recentOnly:(BOOL)recentOnly {
|
|
2603
|
-
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
|
2604
|
-
if (!text) return;
|
|
2605
|
-
NSArray<NSString *> *lines = [text componentsSeparatedByString:@"\n"];
|
|
2606
|
-
NSTimeInterval cutoff = [NSDate.date timeIntervalSince1970] - 5;
|
|
2607
|
-
for (NSUInteger index = 0; index < lines.count; index++) {
|
|
2608
|
-
if (ignoreFirstPartial && index == 0) continue;
|
|
2609
|
-
NSData *lineData = [lines[index] dataUsingEncoding:NSUTF8StringEncoding];
|
|
2610
|
-
if (lineData.length == 0) continue;
|
|
2611
|
-
NSDictionary *record = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
|
|
2612
|
-
if (![record isKindOfClass:NSDictionary.class]) continue;
|
|
2613
|
-
if (recentOnly && [record[@"timestamp"] doubleValue] < cutoff) continue;
|
|
2614
|
-
[self trackAgentSessionRecord:record];
|
|
2615
|
-
NSString *event = record[@"event"];
|
|
2616
|
-
NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
|
|
2617
|
-
if ([event isKindOfClass:NSString.class]) {
|
|
2618
|
-
if (!self.pendingApprovalRecords) {
|
|
2619
|
-
self.pendingApprovalRecords = [NSMutableDictionary dictionary];
|
|
2620
|
-
}
|
|
2621
|
-
[self prunePendingApprovalRecords];
|
|
2622
|
-
NSString *approvalKey = [self approvalKeyForRecord:record];
|
|
2623
|
-
BOOL manualApproval = [state isEqualToString:@"approval"];
|
|
2624
|
-
if (manualApproval) {
|
|
2625
|
-
self.pendingApprovalRecords[approvalKey] = record;
|
|
2626
|
-
} else {
|
|
2627
|
-
[self.pendingApprovalRecords removeObjectForKey:approvalKey];
|
|
2628
|
-
}
|
|
2629
|
-
[self prunePendingApprovalRecords];
|
|
2630
|
-
// 多会话下不能让一个未处理的审批全局挡住其他 Agent 的所有 Hook。每条事件
|
|
2631
|
-
// 都正常驱动气泡和动画;仍在等待的审批保留在多会话记录中供用户回跳。
|
|
2632
|
-
[self displayAgentRecord:record notify:YES];
|
|
2633
|
-
}
|
|
2634
|
-
}
|
|
2635
|
-
[self refreshApprovalBadge];
|
|
2636
|
-
}
|
|
2637
|
-
- (void)readNewAgentEvents {
|
|
2638
|
-
NSString *path = AgentEventPath();
|
|
2639
|
-
NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil];
|
|
2640
|
-
unsigned long long size = [attributes[NSFileSize] unsignedLongLongValue];
|
|
2641
|
-
if (size < self.agentEventOffset) self.agentEventOffset = 0;
|
|
2642
|
-
if (size == self.agentEventOffset) return;
|
|
2643
|
-
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
|
|
2644
|
-
if (!handle) return;
|
|
2645
|
-
unsigned long long start = self.agentEventOffset;
|
|
2646
|
-
[handle seekToFileOffset:start];
|
|
2647
|
-
NSData *data = [handle readDataToEndOfFile];
|
|
2648
|
-
[handle closeFile];
|
|
2649
|
-
self.agentEventOffset = start + data.length;
|
|
2650
|
-
[self consumeAgentEventData:data];
|
|
2651
|
-
}
|
|
2652
|
-
- (void)startAgentEventReader {
|
|
2653
|
-
if (self.agentEventSource) return;
|
|
2654
|
-
NSString *path = AgentEventPath();
|
|
2655
|
-
[NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
|
|
2656
|
-
withIntermediateDirectories:YES attributes:nil error:nil];
|
|
2657
|
-
int creator = open(path.fileSystemRepresentation, O_CREAT | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR);
|
|
2658
|
-
if (creator >= 0) close(creator);
|
|
2659
|
-
int descriptor = open(path.fileSystemRepresentation, O_EVTONLY | O_CLOEXEC);
|
|
2660
|
-
if (descriptor < 0) return;
|
|
2661
|
-
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor,
|
|
2662
|
-
DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_DELETE |
|
|
2663
|
-
DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE,
|
|
2664
|
-
dispatch_get_main_queue());
|
|
2665
|
-
if (!source) {
|
|
2666
|
-
close(descriptor);
|
|
2667
|
-
return;
|
|
2668
|
-
}
|
|
2669
|
-
self.agentEventSource = source;
|
|
2670
|
-
__weak typeof(self) weakSelf = self;
|
|
2671
|
-
dispatch_source_set_event_handler(source, ^{
|
|
2672
|
-
typeof(self) strongSelf = weakSelf;
|
|
2673
|
-
if (!strongSelf) return;
|
|
2674
|
-
dispatch_source_t currentSource = strongSelf.agentEventSource;
|
|
2675
|
-
if (!currentSource) return;
|
|
2676
|
-
unsigned long flags = dispatch_source_get_data(currentSource);
|
|
2677
|
-
[strongSelf readNewAgentEvents];
|
|
2678
|
-
if (flags & (DISPATCH_VNODE_DELETE | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE)) {
|
|
2679
|
-
strongSelf.agentEventSource = nil;
|
|
2680
|
-
dispatch_source_cancel(currentSource);
|
|
2681
|
-
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC),
|
|
2682
|
-
dispatch_get_main_queue(), ^{ [weakSelf startAgentEventReader]; });
|
|
2683
|
-
}
|
|
2684
|
-
});
|
|
2685
|
-
dispatch_source_set_cancel_handler(source, ^{ close(descriptor); });
|
|
2686
|
-
dispatch_resume(source);
|
|
2687
|
-
[self prepareAgentEventReader];
|
|
2688
|
-
}
|
|
2689
|
-
- (void)ensureAgentEventReader:(id)sender {
|
|
2690
|
-
if (!self.agentEventSource) [self startAgentEventReader];
|
|
2691
|
-
}
|
|
2692
|
-
// 在线判定合并两个信号:包装脚本写出的客户端 pid 文件,以及该 provider 最近是否还在
|
|
2693
|
-
// 发事件。只看前者会把直接跑 claude / codex 的会话误判成离线;只看后者则在客户端退出后
|
|
2694
|
-
// 还要挂满一整个静默窗口。额度数据本身不是在线信号——它一直缓存着,用它判定会恒亮。
|
|
2695
|
-
- (void)updateQuotaLiveState {
|
|
2696
|
-
NSMutableSet<NSString *> *online = [self.liveClientProviders mutableCopy] ?: [NSMutableSet set];
|
|
2697
|
-
NSTimeInterval now = NSDate.date.timeIntervalSince1970;
|
|
2698
|
-
for (NSString *provider in self.providerActivityAt) {
|
|
2699
|
-
NSTimeInterval last = [self.providerActivityAt[provider] doubleValue];
|
|
2700
|
-
if (now - last < AgentStatusInactivityInterval) [online addObject:provider];
|
|
2701
|
-
}
|
|
2702
|
-
NSInteger count = MAX(self.liveClientCount, (NSInteger)online.count);
|
|
2703
|
-
if (self.quotaView.activeAgentCount == count &&
|
|
2704
|
-
[self.quotaView.liveProviders isEqualToSet:online] &&
|
|
2705
|
-
self.quotaView.hasUnlabeledClient == self.hasUnlabeledClient) return;
|
|
2706
|
-
self.quotaView.activeAgentCount = count;
|
|
2707
|
-
self.quotaView.liveProviders = online;
|
|
2708
|
-
self.quotaView.hasUnlabeledClient = self.hasUnlabeledClient;
|
|
2709
|
-
self.quotaView.needsDisplay = YES;
|
|
2710
|
-
}
|
|
2711
|
-
// 客户端是否真的还在跑。只问 kill(pid, 0) 不够:关掉终端窗口只是销毁 pty,claude /
|
|
2712
|
-
// codex(Node 进程)不一定跟着 SIGHUP 退出,会变成脱离控制终端的孤儿继续活着。那样
|
|
2713
|
-
// pid 一直存在,会话就永久挂在"在线"上,最近会话列表里那条也永远不消失。
|
|
2714
|
-
// 所以再看两件事:进程是否还有控制终端;以及它是不是仍然是 pid 文件里记的那个 TTY
|
|
2715
|
-
// (pty 会被新开的窗口复用,光看"有 tty"挡不住换了主人的情况)。
|
|
2716
|
-
// recordedTTY 为空是 1.0.2 及更早的老客户端,只能退回"有控制终端"这一条。
|
|
2717
|
-
static BOOL ClientProcessAlive(pid_t pid, NSString *recordedTTY) {
|
|
2718
|
-
if (pid <= 1) return NO;
|
|
2719
|
-
struct kinfo_proc info;
|
|
2720
|
-
size_t length = sizeof(info);
|
|
2721
|
-
int name[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
|
|
2722
|
-
if (sysctl(name, 4, &info, &length, NULL, 0) != 0 || length == 0) return NO;
|
|
2723
|
-
if (info.kp_proc.p_stat == SZOMB) return NO;
|
|
2724
|
-
dev_t device = info.kp_eproc.e_tdev;
|
|
2725
|
-
if (device == NODEV) return NO;
|
|
2726
|
-
if (recordedTTY.length == 0) return YES;
|
|
2727
|
-
const char *current = devname(device, S_IFCHR);
|
|
2728
|
-
if (!current) return NO;
|
|
2729
|
-
return [recordedTTY isEqualToString:@(current).lastPathComponent];
|
|
2730
|
-
}
|
|
2731
|
-
- (void)refreshClientLifecycle:(id)sender {
|
|
2732
|
-
[self considerIdleSpeech];
|
|
2733
|
-
[self prunePendingApprovalRecords];
|
|
2734
|
-
NSString *clientName = [NSString stringWithFormat:@"cc-pets-%u-clients", getuid()];
|
|
2735
|
-
NSString *clientDirectory = [PetStateDirectory() stringByAppendingPathComponent:clientName];
|
|
2736
|
-
NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
|
|
2737
|
-
NSInteger liveClients = 0;
|
|
2738
|
-
NSMutableSet<NSString *> *providers = [NSMutableSet set];
|
|
2739
|
-
NSMutableSet<NSString *> *sessionKeys = [NSMutableSet set];
|
|
2740
|
-
BOOL unlabeled = NO;
|
|
2741
|
-
for (NSString *entry in entries) {
|
|
2742
|
-
pid_t pid = (pid_t)entry.intValue;
|
|
2743
|
-
NSString *path = [clientDirectory stringByAppendingPathComponent:entry];
|
|
2744
|
-
// 包装脚本会把 provider 名写进 pid 文件第一行、TTY 写进第二行。1.0.2 及更早
|
|
2745
|
-
// 的版本只 touch 出空文件,升级后仍在运行的老客户端读出来是空的:这类当作
|
|
2746
|
-
// “身份不明”,只要还有一个就不清场,避免把仍然活着的会话误判成已退出。
|
|
2747
|
-
NSString *contents = [NSString stringWithContentsOfFile:path
|
|
2748
|
-
encoding:NSUTF8StringEncoding error:nil] ?: @"";
|
|
2749
|
-
NSArray<NSString *> *lines = [contents componentsSeparatedByCharactersInSet:
|
|
2750
|
-
NSCharacterSet.newlineCharacterSet];
|
|
2751
|
-
NSString *label = [lines.firstObject
|
|
2752
|
-
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
|
2753
|
-
NSString *tty = lines.count > 1 ? [lines[1]
|
|
2754
|
-
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] : @"";
|
|
2755
|
-
if (!ClientProcessAlive(pid, tty)) {
|
|
2756
|
-
[NSFileManager.defaultManager removeItemAtPath:path error:nil];
|
|
2757
|
-
continue;
|
|
2758
|
-
}
|
|
2759
|
-
liveClients += 1;
|
|
2760
|
-
if (label.length > 0 && label.length <= 32) [providers addObject:label];
|
|
2761
|
-
else unlabeled = YES;
|
|
2762
|
-
NSString *sessionKey = [self onlineAgentSessionKeyForProvider:label tty:tty];
|
|
2763
|
-
if (sessionKey.length > 0) [sessionKeys addObject:sessionKey];
|
|
2764
|
-
}
|
|
2765
|
-
// 包装脚本启动的客户端有精确的退出信号:pid 文件被回收。这一段不该被为"直接跑
|
|
2766
|
-
// claude / codex"准备的 60 秒活跃度宽限盖住,否则退出后还要挂满一分钟才转离线。
|
|
2767
|
-
// 因此某一家的 pid 文件一旦从有变无,立刻丢掉它的活跃度记录;从来没有过 pid 文件
|
|
2768
|
-
// 的(直接启动)不受影响,继续走宽限。
|
|
2769
|
-
NSSet<NSString *> *previousProviders = self.liveClientProviders;
|
|
2770
|
-
self.liveClientCount = liveClients;
|
|
2771
|
-
self.liveClientProviders = providers;
|
|
2772
|
-
self.liveAgentSessionKeys = sessionKeys;
|
|
2773
|
-
self.hasUnlabeledClient = unlabeled;
|
|
2774
|
-
[self pruneOfflineAgentSessionRecords];
|
|
2775
|
-
for (NSString *provider in previousProviders) {
|
|
2776
|
-
if (![providers containsObject:provider]) {
|
|
2777
|
-
[self.providerActivityAt removeObjectForKey:provider];
|
|
2778
|
-
}
|
|
2779
|
-
}
|
|
2780
|
-
[self updateQuotaLiveState];
|
|
2781
|
-
[self refreshDetectedProviders];
|
|
2782
|
-
[self hideAgentStatusIfClientGone];
|
|
2783
|
-
[self checkStalledAgentSessions];
|
|
2784
|
-
[self refreshApprovalBadge];
|
|
2785
|
-
// 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
|
|
2786
|
-
// Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
|
|
2787
|
-
if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
|
|
2788
|
-
}
|
|
2789
|
-
// 面板高度取决于渲染几张额度卡。调整玻璃容器后,内部内容随 autoresizingMask 铺满。
|
|
2790
|
-
- (void)resizeQuotaDashboard {
|
|
2791
|
-
NSSize size = NSMakeSize(QuotaLogicalWidth * QuotaScale,
|
|
2792
|
-
QuotaLogicalHeightForProviderCount([self.quotaView visibleProviders].count) * QuotaScale);
|
|
2793
|
-
if (NSEqualSizes(self.quotaPanel.frame.size, size)) return;
|
|
2794
|
-
// 只改 size 不动 origin:窗口 frame 的原点在左下,面板会朝上收缩,底边保持贴着宠物。
|
|
2795
|
-
NSRect frame = self.quotaPanel.frame;
|
|
2796
|
-
frame.size = size;
|
|
2797
|
-
[self.quotaPanel setFrame:frame display:NO];
|
|
2798
|
-
NSRect bounds = NSMakeRect(0, 0, size.width, size.height);
|
|
2799
|
-
self.quotaPanel.contentView.frame = bounds;
|
|
2800
|
-
for (NSView *subview in self.quotaPanel.contentView.subviews) subview.frame = bounds;
|
|
2801
|
-
self.quotaView.needsDisplay = YES;
|
|
2802
|
-
if (self.quotaPanel.isVisible) [self positionQuotaDashboard];
|
|
2803
|
-
}
|
|
2804
|
-
// 额度字典"非空"不等于"这家真的在用"。Claude 的 reader 刻意永不返回 nil(见
|
|
2805
|
-
// CCPetsUsage.m 里 -[ClaudeUsageReader refresh] 的注释:Token 是本机从转录数出来的,
|
|
2806
|
-
// 不能被缺失的官方额度一票否决),什么都没有时照样返回
|
|
2807
|
-
// {fiveHour: NSNull, week: NSNull, tokenUsage: 全 0},count 恒为 3。
|
|
2808
|
-
// 拿 count > 0 当证据,Claude 就永远算"检测到",卡片再也去不掉。这里只认实质证据:
|
|
2809
|
-
// 官方额度块真实存在,或者本机统计出过非零 Token。Codex 侧同一套判据也成立。
|
|
2810
|
-
static BOOL UsageShowsProviderInUse(NSDictionary *usage) {
|
|
2811
|
-
if (usage.count == 0) return NO;
|
|
2812
|
-
for (NSString *key in @[@"fiveHour", @"week"]) {
|
|
2813
|
-
if ([usage[key] isKindOfClass:NSDictionary.class]) return YES;
|
|
2814
|
-
}
|
|
2815
|
-
NSDictionary *tokenUsage = [usage[@"tokenUsage"] isKindOfClass:NSDictionary.class]
|
|
2816
|
-
? usage[@"tokenUsage"] : nil;
|
|
2817
|
-
for (NSString *key in @[@"fiveHour", @"week", @"today", @"recentWeek"]) {
|
|
2818
|
-
NSDictionary *totals = [tokenUsage[key] isKindOfClass:NSDictionary.class]
|
|
2819
|
-
? tokenUsage[key] : nil;
|
|
2820
|
-
if ([totals[@"total_tokens"] doubleValue] > 0) return YES;
|
|
2821
|
-
}
|
|
2822
|
-
return NO;
|
|
2823
|
-
}
|
|
2824
|
-
// "这台机器上有哪几家 CLI"。只增不减,并持久化:探测会瞬时失败(配置目录被改名、
|
|
2825
|
-
// 外置盘没挂上),卡片当着用户的面消失比多留一张更像 bug。
|
|
2826
|
-
- (void)refreshDetectedProviders {
|
|
2827
|
-
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
|
2828
|
-
NSMutableSet<NSString *> *detected = [NSMutableSet setWithArray:
|
|
2829
|
-
[defaults arrayForKey:DetectedProvidersKey] ?: @[]];
|
|
2830
|
-
if (CodexCLIDetected()) [detected addObject:@"Codex"];
|
|
2831
|
-
if (ClaudeCLIDetected()) [detected addObject:@"Claude"];
|
|
2832
|
-
// 正在跑的客户端和已经拿到的额度数据都是比目录探测更硬的证据:探测漏判也不能
|
|
2833
|
-
// 把一个正在工作、或者明明有额度的 provider 藏起来。
|
|
2834
|
-
if (self.liveClientProviders.count > 0) [detected unionSet:self.liveClientProviders];
|
|
2835
|
-
if (UsageShowsProviderInUse(self.quotaView.codexUsage)) [detected addObject:@"Codex"];
|
|
2836
|
-
if (UsageShowsProviderInUse(self.quotaView.claudeUsage)) [detected addObject:@"Claude"];
|
|
2837
|
-
if (self.quotaView.detectedProviders &&
|
|
2838
|
-
[detected isEqualToSet:self.quotaView.detectedProviders]) return;
|
|
2839
|
-
self.quotaView.detectedProviders = detected;
|
|
2840
|
-
[defaults setObject:detected.allObjects forKey:DetectedProvidersKey];
|
|
2841
|
-
[self resizeQuotaDashboard];
|
|
2842
|
-
self.quotaView.needsDisplay = YES;
|
|
2843
|
-
}
|
|
2844
|
-
- (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage {
|
|
2845
|
-
self.quotaView.codexUsage = codexUsage;
|
|
2846
|
-
self.quotaView.claudeUsage = claudeUsage;
|
|
2847
|
-
[self refreshDetectedProviders];
|
|
2848
|
-
NSDictionary *history = RecordQuotaHistory(self.quotaView.codexUsage,
|
|
2849
|
-
self.quotaView.claudeUsage);
|
|
2850
|
-
self.quotaView.codexHistory = QuotaHistorySeries(history, @"codex");
|
|
2851
|
-
self.quotaView.claudeHistory = QuotaHistorySeries(history, @"claude");
|
|
2852
|
-
self.quotaView.lastUpdatedAt = NSDate.date.timeIntervalSince1970;
|
|
2853
|
-
self.quotaView.needsDisplay = YES;
|
|
2854
|
-
}
|
|
2855
|
-
- (void)refreshUsage:(id)sender {
|
|
2856
|
-
self.lastUsageRefreshAt = NSDate.date.timeIntervalSince1970;
|
|
2857
|
-
[self.usageMonitor refreshNow];
|
|
2858
|
-
}
|
|
2859
461
|
- (void)applicationWillTerminate:(NSNotification *)notification {
|
|
2860
462
|
[self.usageMonitor stop];
|
|
2861
463
|
[self.systemMetricsTimer invalidate];
|