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.
Files changed (74) hide show
  1. package/CC_BRIDGE.md +5 -0
  2. package/CC_BRIDGE.zh-CN.md +4 -0
  3. package/CHANGELOG.md +40 -1
  4. package/CHANGELOG.zh-CN.md +40 -1
  5. package/CONTRIBUTING.md +54 -0
  6. package/CONTRIBUTING.zh-CN.md +45 -0
  7. package/README.md +57 -14
  8. package/README.zh-CN.md +56 -14
  9. package/Resources/Info.plist +3 -1
  10. package/Resources/en.lproj/InfoPlist.strings +1 -0
  11. package/Resources/phrases.default.en.txt +182 -0
  12. package/Resources/zh-Hans.lproj/InfoPlist.strings +1 -0
  13. package/Resources/zh-Hans.lproj/Localizable.strings +332 -0
  14. package/Sources/CCPets/CCPetsAppDelegate+AgentEvents.m +215 -0
  15. package/Sources/CCPets/CCPetsAppDelegate+AgentStatus.m +660 -0
  16. package/Sources/CCPets/CCPetsAppDelegate+Bridge.m +299 -0
  17. package/Sources/CCPets/CCPetsAppDelegate+Pets.m +185 -0
  18. package/Sources/CCPets/CCPetsAppDelegate+Private.h +325 -0
  19. package/Sources/CCPets/CCPetsAppDelegate+Quota.m +216 -0
  20. package/Sources/CCPets/CCPetsAppDelegate+Settings.m +226 -0
  21. package/Sources/CCPets/CCPetsAppDelegate+Speech.m +392 -0
  22. package/Sources/CCPets/CCPetsAppDelegate+Update.m +459 -0
  23. package/Sources/CCPets/CCPetsAppDelegate.h +13 -14
  24. package/Sources/CCPets/CCPetsAppDelegate.m +68 -2466
  25. package/Sources/CCPets/CCPetsCleanup.h +4 -0
  26. package/Sources/CCPets/CCPetsCleanup.m +41 -7
  27. package/Sources/CCPets/CCPetsEvents.m +4 -3
  28. package/Sources/CCPets/CCPetsL10n.h +55 -0
  29. package/Sources/CCPets/CCPetsL10n.m +219 -0
  30. package/Sources/CCPets/CCPetsPaths.h +0 -1
  31. package/Sources/CCPets/CCPetsPaths.m +0 -1
  32. package/Sources/CCPets/CCPetsPhrases.h +7 -1
  33. package/Sources/CCPets/CCPetsPhrases.m +86 -31
  34. package/Sources/CCPets/CCPetsPhrasesEditor.m +62 -64
  35. package/Sources/CCPets/CCPetsPreviews.m +7 -6
  36. package/Sources/CCPets/CCPetsUsage.h +0 -1
  37. package/Sources/CCPets/CCPetsUsage.m +0 -3
  38. package/Sources/CCPets/CCPetsVersion.h +10 -0
  39. package/Sources/CCPets/CCPetsVersion.m +92 -2
  40. package/Sources/CCPets/MenuToggleSwitch.m +3 -2
  41. package/Sources/CCPets/PetView.h +2 -0
  42. package/Sources/CCPets/PetView.m +115 -74
  43. package/Sources/CCPets/QuotaDashboardView.m +122 -88
  44. package/Sources/CCPets/main.m +16 -1
  45. package/bin/cc-pets +25 -20
  46. package/bin/claude-with-pet +2 -1
  47. package/bin/codex-with-pet +2 -1
  48. package/package.json +5 -3
  49. package/scripts/bridge/cli.mjs +47 -39
  50. package/scripts/bridge/core.mjs +28 -27
  51. package/scripts/bridge/hook.mjs +7 -6
  52. package/scripts/bridge/install.mjs +42 -19
  53. package/scripts/bridge/mcp-server.mjs +79 -71
  54. package/scripts/bridge/options.mjs +7 -6
  55. package/scripts/bridge/process.mjs +22 -0
  56. package/scripts/bridge/reservations.mjs +6 -5
  57. package/scripts/bridge/store.mjs +10 -9
  58. package/scripts/build.sh +24 -5
  59. package/scripts/check-l10n.mjs +168 -0
  60. package/scripts/configure-updater.mjs +4 -3
  61. package/scripts/doctor.mjs +470 -0
  62. package/scripts/i18n.mjs +122 -0
  63. package/scripts/i18n.zsh +66 -0
  64. package/scripts/install-app.sh +3 -2
  65. package/scripts/install-claude-hooks.mjs +22 -27
  66. package/scripts/install-codex-hooks.mjs +10 -15
  67. package/scripts/install-shell-integration.sh +6 -5
  68. package/scripts/integration-markers.mjs +51 -0
  69. package/scripts/locales/zh-Hans.json +366 -0
  70. package/scripts/pet-store.mjs +47 -45
  71. package/scripts/uninstall-app.sh +4 -3
  72. package/scripts/uninstall-integrations.mjs +24 -51
  73. package/scripts/uninstall-shell-integration.sh +8 -7
  74. /package/Resources/{phrases.default.txt → phrases.default.zh-Hans.txt} +0 -0
@@ -0,0 +1,299 @@
1
+ // CC Bridge 开关、消息角标与菜单。
2
+ #import "CCPetsAppDelegate+Private.h"
3
+
4
+ @implementation AppDelegate (Bridge)
5
+ // 菜单开关 → cc-pets bridge enable / disable / configure。逻辑全在 CLI 里,桌宠只负责调用,
6
+ // 命令行与菜单两条路的行为才一致。enable 要跑 claude / codex mcp add,要几秒,所以异步执行;
7
+ // 执行期间忽略新的切换,结束后按实际状态刷新(菜单下次打开时现读)。
8
+ - (void)runBridgeCommand:(NSArray<NSString *> *)arguments sender:(NSButton *)sender
9
+ successMessage:(NSString *)successMessage {
10
+ NSDictionary<NSString *, NSString *> *locator = CCBridgeCLILocator();
11
+ if (!locator) {
12
+ [self showAlertWithTitle:L(@"Can't Change CC Bridge Settings")
13
+ message:L(@"The cc-pets command-line tool wasn't found. Run cc-pets install in a terminal, then try again.")];
14
+ [self syncBridgeSwitch:sender];
15
+ return;
16
+ }
17
+ if (self.bridgeCommandRunning) {
18
+ [self syncBridgeSwitch:sender];
19
+ return;
20
+ }
21
+ self.bridgeCommandRunning = YES;
22
+ NSTask *task = [NSTask new];
23
+ task.executableURL = [NSURL fileURLWithPath:locator[@"node"]];
24
+ task.arguments = [@[locator[@"cli"]] arrayByAddingObjectsFromArray:arguments];
25
+ NSMutableDictionary<NSString *, NSString *> *environment =
26
+ [NSProcessInfo.processInfo.environment mutableCopy];
27
+ NSString *existingPath = environment[@"PATH"].length > 0 ? environment[@"PATH"] : @"/usr/bin:/bin:/usr/sbin:/sbin";
28
+ // claude / codex 常装在 node 同目录(nvm),桌宠的 PATH 里未必有。
29
+ environment[@"PATH"] = [NSString stringWithFormat:@"%@:%@",
30
+ [locator[@"node"] stringByDeletingLastPathComponent], existingPath];
31
+ task.environment = environment;
32
+ NSPipe *output = [NSPipe pipe];
33
+ task.standardOutput = output;
34
+ task.standardError = output;
35
+ __weak typeof(self) weakSelf = self;
36
+ task.terminationHandler = ^(NSTask *finished) {
37
+ NSData *data = [output.fileHandleForReading readDataToEndOfFile];
38
+ NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"";
39
+ dispatch_async(dispatch_get_main_queue(), ^{
40
+ typeof(self) strongSelf = weakSelf;
41
+ if (!strongSelf) return;
42
+ strongSelf.bridgeCommandRunning = NO;
43
+ [strongSelf refreshBridgeState:nil];
44
+ if (finished.terminationStatus == EXIT_SUCCESS) {
45
+ if (successMessage.length > 0) {
46
+ [strongSelf sendNotificationWithTitle:@"CC Bridge" body:successMessage];
47
+ }
48
+ return;
49
+ }
50
+ [strongSelf syncBridgeSwitch:sender];
51
+ NSString *detail = [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
52
+ [strongSelf showAlertWithTitle:L(@"CC Bridge Setup Failed")
53
+ message:detail.length > 0 ? detail : L(@"The command failed.")];
54
+ });
55
+ };
56
+ NSError *error = nil;
57
+ if (![task launchAndReturnError:&error]) {
58
+ self.bridgeCommandRunning = NO;
59
+ [self syncBridgeSwitch:sender];
60
+ [self showAlertWithTitle:L(@"CC Bridge Setup Failed") message:error.localizedDescription];
61
+ }
62
+ }
63
+ // 与其他菜单开关一致:目标状态按"实际存储的状态取反"算,不信任开关视图自己翻转后的 state——
64
+ // 菜单停留期间状态可能已被命令行改过。命令没执行成功时再把开关翻回实际状态。
65
+ - (BOOL)currentBridgeStateForSwitch:(NSButton *)sender {
66
+ NSDictionary *options = CCBridgeOptions();
67
+ if (sender.action == @selector(toggleBridgeEnabled:)) return CCBridgeEnabled();
68
+ if (sender.action == @selector(toggleBridgeWake:)) return [options[@"wake"] boolValue];
69
+ if (sender.action == @selector(toggleBridgeEditGuard:)) return [options[@"editGuard"] boolValue];
70
+ if (sender.action == @selector(toggleBridgeApproval:)) {
71
+ NSSet *tools = [NSSet setWithArray:CCBridgeToolGroup([self bridgeApprovalGroupForTag:sender.tag])];
72
+ return tools.count > 0 && [tools isSubsetOfSet:[NSSet setWithArray:options[@"codexApprove"]]] &&
73
+ [tools isSubsetOfSet:[NSSet setWithArray:options[@"claudeAllow"]]];
74
+ }
75
+ return NO;
76
+ }
77
+ - (void)syncBridgeSwitch:(NSButton *)sender {
78
+ if (!sender) return;
79
+ sender.state = [self currentBridgeStateForSwitch:sender] ? NSControlStateValueOn : NSControlStateValueOff;
80
+ }
81
+ // 返回目标状态,并先把开关视图摆到目标状态上(命令失败时 syncBridgeSwitch 再翻回来)。
82
+ - (BOOL)targetBridgeStateForSwitch:(NSButton *)sender {
83
+ BOOL target = ![self currentBridgeStateForSwitch:sender];
84
+ sender.state = target ? NSControlStateValueOn : NSControlStateValueOff;
85
+ return target;
86
+ }
87
+ - (NSString *)bridgeApprovalGroupForTag:(NSInteger)tag {
88
+ NSArray<NSString *> *groups = CCBridgeToolGroupNames();
89
+ return tag >= 1 && tag <= (NSInteger)groups.count ? groups[tag - 1] : @"";
90
+ }
91
+ - (void)toggleBridgeEnabled:(NSButton *)sender {
92
+ BOOL enable = [self targetBridgeStateForSwitch:sender];
93
+ [self runBridgeCommand:@[enable ? @"enable" : @"disable"] sender:sender
94
+ successMessage:enable
95
+ ? L(@"Enabled. Running Codex sessions need a restart and must be trusted in /hooks; Claude sessions get the cc-bridge tools after a restart.")
96
+ : L(@"Disabled. The related hooks and MCP registrations were removed.")];
97
+ }
98
+ // 一个分组同时作用于 Codex 免审批与 Claude 免确认:菜单上只有一组开关,两边保持一致。
99
+ - (void)toggleBridgeApproval:(NSButton *)sender {
100
+ NSArray<NSString *> *tools = CCBridgeToolGroup([self bridgeApprovalGroupForTag:sender.tag]);
101
+ if (tools.count == 0) return;
102
+ BOOL allow = [self targetBridgeStateForSwitch:sender];
103
+ NSDictionary *options = CCBridgeOptions();
104
+ NSString *(^apply)(NSArray<NSString *> *) = ^NSString *(NSArray<NSString *> *current) {
105
+ NSMutableOrderedSet<NSString *> *next = [NSMutableOrderedSet orderedSetWithArray:current];
106
+ if (allow) [next addObjectsFromArray:tools]; else [next removeObjectsInArray:tools];
107
+ return [next.array componentsJoinedByString:@","];
108
+ };
109
+ [self runBridgeCommand:@[@"configure",
110
+ [@"--codex-approve=" stringByAppendingString:apply(options[@"codexApprove"])],
111
+ [@"--claude-allow=" stringByAppendingString:apply(options[@"claudeAllow"])]]
112
+ sender:sender successMessage:nil];
113
+ }
114
+ - (void)toggleBridgeWake:(NSButton *)sender {
115
+ [self runBridgeCommand:@[@"configure",
116
+ [self targetBridgeStateForSwitch:sender] ? @"--wake=on" : @"--wake=off"] sender:sender successMessage:nil];
117
+ }
118
+ - (void)toggleBridgeEditGuard:(NSButton *)sender {
119
+ [self runBridgeCommand:@[@"configure",
120
+ [self targetBridgeStateForSwitch:sender] ? @"--edit-guard=on" : @"--edit-guard=off"]
121
+ sender:sender successMessage:nil];
122
+ }
123
+ - (void)toggleBridgeBadge:(NSButton *)sender {
124
+ BOOL enabled = ![NSUserDefaults.standardUserDefaults boolForKey:BridgeBadgeEnabledKey];
125
+ [NSUserDefaults.standardUserDefaults setBool:enabled forKey:BridgeBadgeEnabledKey];
126
+ sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
127
+ [self refreshBridgeBadge];
128
+ }
129
+ // 与"系统通知"那组开关同一套授权流程:第一次打开时向系统申请通知权限。
130
+ - (void)toggleBridgeNotification:(NSButton *)sender {
131
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
132
+ if ([defaults boolForKey:BridgeNotificationKey]) {
133
+ [defaults setBool:NO forKey:BridgeNotificationKey];
134
+ sender.state = NSControlStateValueOff;
135
+ return;
136
+ }
137
+ [UNUserNotificationCenter.currentNotificationCenter
138
+ requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound
139
+ completionHandler:^(BOOL granted, NSError *error) {
140
+ dispatch_async(dispatch_get_main_queue(), ^{
141
+ [defaults setBool:granted forKey:BridgeNotificationKey];
142
+ sender.state = granted ? NSControlStateValueOn : NSControlStateValueOff;
143
+ if (!granted) {
144
+ [self showAlertWithTitle:L(@"Can't Enable Notifications") message:error.localizedDescription ?:
145
+ L(@"Allow notifications in System Settings → Notifications → CC Pets, then try again.")];
146
+ }
147
+ });
148
+ }];
149
+ }
150
+ // 读 bridge 状态(会话名、最近送达、信箱积压),刷新角标。bridge 未开启时清空并隐藏。
151
+ // 回执目录没变就不重读文件,只按时间窗重新过滤缓存——回执状态一变,写入端的
152
+ // "临时文件 + rename" 必然改动目录的修改时间。
153
+ - (void)refreshBridgeState:(NSTimer *)timer {
154
+ if (!CCBridgeEnabled()) {
155
+ self.bridgeSessions = nil;
156
+ self.bridgeRecentDeliveries = nil;
157
+ self.bridgePendingCounts = nil;
158
+ self.bridgeSentStamp = nil;
159
+ [self refreshBridgeBadge];
160
+ return;
161
+ }
162
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
163
+ NSString *directory = CCBridgeStateDirectory();
164
+ self.bridgeSessions = CCBridgeSessions();
165
+ NSDate *stamp = [NSFileManager.defaultManager attributesOfItemAtPath:
166
+ [directory stringByAppendingPathComponent:@"sent"] error:nil].fileModificationDate;
167
+ if (!stamp || ![stamp isEqualToDate:self.bridgeSentStamp] || !self.bridgeDeliveryCache) {
168
+ self.bridgeDeliveryCache = CCBridgeRecentDeliveries(now - BridgeRecentWindow, 50);
169
+ self.bridgeSentStamp = stamp;
170
+ }
171
+ NSMutableArray<NSDictionary *> *recent = [NSMutableArray array];
172
+ for (NSDictionary *delivery in self.bridgeDeliveryCache) {
173
+ if ([delivery[@"at"] doubleValue] >= now - BridgeRecentWindow) [recent addObject:delivery];
174
+ }
175
+ self.bridgeRecentDeliveries = recent;
176
+ // 只算仍在线的会话:已退出会话的积压已经投不出去,提醒也无从处理。
177
+ NSMutableDictionary<NSString *, NSNumber *> *pending = [NSMutableDictionary dictionary];
178
+ [CCBridgePendingCounts() enumerateKeysAndObjectsUsingBlock:^(NSString *session, NSNumber *count, BOOL *stop) {
179
+ if (self.bridgeSessions[session]) pending[session] = count;
180
+ }];
181
+ self.bridgePendingCounts = pending;
182
+ [self notifyNewBridgeDeliveries];
183
+ [self refreshBridgeBadge];
184
+ }
185
+ // 新送达的跨会话消息发系统通知:只含谁发给谁,不含正文。一次刷新里来了多条时合并成一条。
186
+ - (void)notifyNewBridgeDeliveries {
187
+ NSMutableArray<NSDictionary *> *fresh = [NSMutableArray array];
188
+ for (NSDictionary *delivery in self.bridgeRecentDeliveries) {
189
+ if ([delivery[@"at"] doubleValue] > self.bridgeNotifiedAt) [fresh addObject:delivery];
190
+ }
191
+ if (fresh.count == 0) return;
192
+ for (NSDictionary *delivery in fresh) {
193
+ self.bridgeNotifiedAt = MAX(self.bridgeNotifiedAt, [delivery[@"at"] doubleValue]);
194
+ }
195
+ if (![NSUserDefaults.standardUserDefaults boolForKey:BridgeNotificationKey]) return;
196
+ NSDictionary *latest = fresh.firstObject;
197
+ NSString *body = fresh.count == 1
198
+ ? [NSString stringWithFormat:@"%@ → %@", latest[@"from"], latest[@"to"]]
199
+ : [NSString stringWithFormat:L(@"%1$@ → %2$@ and %3$lu more"), latest[@"from"], latest[@"to"],
200
+ (unsigned long)fresh.count];
201
+ [self sendNotificationWithTitle:L(@"New CC Bridge Message") body:body];
202
+ }
203
+ // 蓝色 = 有新的跨会话消息送达;橙色 = 有消息卡在某个会话的信箱里(那个 Claude 会话长时间空闲、
204
+ // 唤醒 watcher 已退出,要等用户在那个终端开口才会送进去),需要用户过去看一眼。
205
+ - (void)refreshBridgeBadge {
206
+ CCPetsApprovalBadgeView *badge = (CCPetsApprovalBadgeView *)self.bridgeBadgeView;
207
+ if (!badge) return;
208
+ if (![NSUserDefaults.standardUserDefaults boolForKey:BridgeBadgeEnabledKey]) {
209
+ badge.count = 0;
210
+ return;
211
+ }
212
+ NSUInteger unseen = 0;
213
+ for (NSDictionary *delivery in self.bridgeRecentDeliveries) {
214
+ if ([delivery[@"at"] doubleValue] > self.bridgeSeenAt) unseen++;
215
+ }
216
+ NSUInteger waiting = 0;
217
+ for (NSNumber *count in self.bridgePendingCounts.allValues) waiting += count.unsignedIntegerValue;
218
+ badge.fillColor = waiting > 0
219
+ ? [NSColor colorWithRed:0.92 green:0.58 blue:0.12 alpha:1]
220
+ : [NSColor colorWithRed:0.20 green:0.47 blue:0.90 alpha:1];
221
+ badge.count = unseen + waiting;
222
+ [self layoutApprovalBadge];
223
+ }
224
+ - (NSString *)bridgeSessionIdForRecord:(NSDictionary *)record {
225
+ NSString *session = SanitizedShortString(record[@"session"], 128);
226
+ if (session.length > 0 && self.bridgeSessions[session]) return session;
227
+ // 事件里没有 session id 的记录,退回按 provider + tty 对上 bridge 注册表。
228
+ NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class] ? record[@"terminal"] : nil;
229
+ NSString *tty = SanitizedShortString([terminal[@"tty"] lastPathComponent], 64);
230
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
231
+ if (tty.length == 0) return nil;
232
+ __block NSString *match = nil;
233
+ [self.bridgeSessions enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSDictionary *entry, BOOL *stop) {
234
+ if ([entry[@"tty"] isEqualToString:tty] && [entry[@"provider"] isEqualToString:provider]) {
235
+ match = key;
236
+ *stop = YES;
237
+ }
238
+ }];
239
+ return match;
240
+ }
241
+ - (NSDictionary *)bridgeSessionEntryForRecord:(NSDictionary *)record {
242
+ NSString *session = [self bridgeSessionIdForRecord:record];
243
+ return session ? self.bridgeSessions[session] : nil;
244
+ }
245
+ // 收件会话的终端:优先用桌宠自己记录的该会话终端信息(带宿主应用),其次按 tty 对上任一
246
+ // 已知终端,最后借用最近一次的宿主应用配上 bridge 记录的 tty。
247
+ - (NSDictionary *)terminalTargetForBridgeSession:(NSString *)sessionId {
248
+ NSString *tty = self.bridgeSessions[sessionId][@"tty"];
249
+ NSDictionary *byTty = nil;
250
+ for (NSDictionary *record in self.agentSessionRecords.allValues) {
251
+ NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class] ? record[@"terminal"] : nil;
252
+ if (terminal.count == 0) continue;
253
+ if ([SanitizedShortString(record[@"session"], 128) isEqualToString:sessionId]) return terminal;
254
+ if (tty.length > 0 && [[terminal[@"tty"] lastPathComponent] isEqualToString:tty]) byTty = terminal;
255
+ }
256
+ if (byTty) return byTty;
257
+ if (tty.length > 0 && self.lastTerminalFocusTarget.count > 0) {
258
+ NSMutableDictionary *target = [self.lastTerminalFocusTarget mutableCopy];
259
+ target[@"tty"] = tty;
260
+ [target removeObjectForKey:@"session"];
261
+ return target;
262
+ }
263
+ return nil;
264
+ }
265
+ - (void)focusBridgeSession:(NSMenuItem *)sender {
266
+ NSString *sessionId = [sender.representedObject isKindOfClass:NSString.class] ? sender.representedObject : nil;
267
+ NSDictionary *target = sessionId ? [self terminalTargetForBridgeSession:sessionId] : nil;
268
+ if (target.count > 0) ActivateTerminalFocusTarget(target);
269
+ }
270
+ - (void)addBridgeItemsToMenu:(NSMenu *)menu deliveries:(NSArray<NSDictionary *> *)deliveries
271
+ pending:(NSDictionary<NSString *, NSNumber *> *)pending {
272
+ NSMenuItem *heading = [menu addItemWithTitle:L(@"CC Bridge Messages") action:nil keyEquivalent:@""];
273
+ heading.enabled = NO;
274
+ [pending enumerateKeysAndObjectsUsingBlock:^(NSString *session, NSNumber *count, BOOL *stop) {
275
+ NSString *name = self.bridgeSessions[session][@"name"] ?: session;
276
+ NSString *title = [NSString stringWithFormat:count.unsignedLongValue != 1
277
+ ? L(@"📬 %1$@ has %2$lu undelivered messages (say anything in that terminal to deliver)")
278
+ : L(@"📬 %1$@ has %2$lu undelivered message (say anything in that terminal to deliver)"),
279
+ name, count.unsignedLongValue];
280
+ NSMenuItem *item = [menu addItemWithTitle:title action:@selector(focusBridgeSession:) keyEquivalent:@""];
281
+ item.target = self;
282
+ item.representedObject = session;
283
+ }];
284
+ NSUInteger shown = 0;
285
+ for (NSDictionary *delivery in deliveries) {
286
+ if (shown++ >= BridgeMenuDeliveryLimit) break;
287
+ NSDate *date = [NSDate dateWithTimeIntervalSince1970:[delivery[@"at"] doubleValue]];
288
+ NSString *time = [NSDateFormatter localizedStringFromDate:date
289
+ dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle];
290
+ BOOL unseen = [delivery[@"at"] doubleValue] > self.bridgeSeenAt;
291
+ NSString *title = [NSString stringWithFormat:@"%@%@ → %@ · %@",
292
+ unseen ? @"✉️ " : @"", delivery[@"from"], delivery[@"to"], time];
293
+ NSMenuItem *item = [menu addItemWithTitle:title action:@selector(focusBridgeSession:) keyEquivalent:@""];
294
+ item.target = self;
295
+ item.representedObject = delivery[@"toSession"];
296
+ item.toolTip = [NSString stringWithFormat:L(@"Jump to %@'s terminal"), delivery[@"to"]];
297
+ }
298
+ }
299
+ @end
@@ -0,0 +1,185 @@
1
+ // 宠物素材发现、切换与删除。
2
+ #import "CCPetsAppDelegate+Private.h"
3
+
4
+ @implementation AppDelegate (Pets)
5
+ - (NSDictionary *)petManifestInDirectory:(NSString *)directory {
6
+ NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
7
+ NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
8
+ if (!jsonData) return @{};
9
+ id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
10
+ return [json isKindOfClass:NSDictionary.class] ? json : @{};
11
+ }
12
+ - (NSInteger)spriteVersionInDirectory:(NSString *)directory fallbackDirectory:(NSString *)fallbackDirectory {
13
+ NSArray<NSString *> *directories = fallbackDirectory.length > 0
14
+ ? @[directory, fallbackDirectory]
15
+ : @[directory];
16
+ for (NSString *candidate in directories) {
17
+ id value = [self petManifestInDirectory:candidate][@"spriteVersionNumber"];
18
+ if (![value isKindOfClass:NSNumber.class]) continue;
19
+ NSInteger version = [value integerValue];
20
+ if (version == 1 || version == 2) return version;
21
+ }
22
+ return 1;
23
+ }
24
+ - (NSInteger)spriteRowCountForVersion:(NSInteger)version {
25
+ return version == 2 ? 11 : 9;
26
+ }
27
+ - (NSString *)spritePathInDirectory:(NSString *)directory {
28
+ NSString *configuredName = nil;
29
+ id value = [self petManifestInDirectory:directory][@"spritesheetPath"];
30
+ if ([value isKindOfClass:NSString.class]) configuredName = [value lastPathComponent];
31
+ NSMutableArray<NSString *> *names = [NSMutableArray array];
32
+ if (configuredName.length > 0) [names addObject:configuredName];
33
+ [names addObjectsFromArray:@[@"spritesheet.webp", @"spritesheet.png"]];
34
+ for (NSString *name in names) {
35
+ NSString *path = [directory stringByAppendingPathComponent:name];
36
+ BOOL isDirectory = NO;
37
+ if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && !isDirectory) return path;
38
+ }
39
+ return nil;
40
+ }
41
+ - (NSArray<NSString *> *)petDirectoryNamesAtPath:(NSString *)root {
42
+ NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:root error:nil] ?: @[];
43
+ NSMutableArray<NSString *> *directories = [NSMutableArray array];
44
+ for (NSString *entry in entries) {
45
+ if ([entry hasPrefix:@"."]) continue;
46
+ BOOL isDirectory = NO;
47
+ NSString *path = [root stringByAppendingPathComponent:entry];
48
+ if ([NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory) {
49
+ [directories addObject:entry];
50
+ }
51
+ }
52
+ return [directories sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
53
+ }
54
+ // 桌宠只扫 OwnPetsDirectory() 加包内素材,无条件、不看那里有没有东西。~/.petdex/pets 和
55
+ // ~/.codex/pets 由别的工具写入,直接扫就永远分不清哪只是自己装的;要用 Codex 的素材就打开
56
+ // "导入 Codex 素材"开关,由 ImportCodexPets 复制进来,之后它们和自己装的没有区别。
57
+ - (NSArray<NSDictionary *> *)discoverPetOptions {
58
+ NSString *ownRoot = OwnPetsDirectory();
59
+ NSMutableArray<NSDictionary *> *result = [NSMutableArray array];
60
+
61
+ for (NSString *name in [self petDirectoryNamesAtPath:ownRoot]) {
62
+ NSString *directory = [ownRoot stringByAppendingPathComponent:name];
63
+ NSString *path = [self spritePathInDirectory:directory];
64
+ if (!path) continue;
65
+ NSInteger version = [self spriteVersionInDirectory:directory fallbackDirectory:nil];
66
+ [result addObject:@{
67
+ @"id": [@"external:" stringByAppendingString:name],
68
+ @"name": name,
69
+ @"path": path,
70
+ @"spriteVersionNumber": @(version),
71
+ @"spriteRowCount": @([self spriteRowCountForVersion:version])
72
+ }];
73
+ }
74
+
75
+ NSArray<NSString *> *bundled = [NSFileManager.defaultManager
76
+ contentsOfDirectoryAtPath:self.binaryDirectory error:nil] ?: @[];
77
+ for (NSString *fileName in [bundled sortedArrayUsingSelector:@selector(localizedStandardCompare:)]) {
78
+ NSString *extension = fileName.pathExtension.lowercaseString;
79
+ if (![extension isEqualToString:@"webp"] && ![extension isEqualToString:@"png"]) continue;
80
+ [result addObject:@{
81
+ @"id": [@"builtin:" stringByAppendingString:fileName],
82
+ @"name": fileName.stringByDeletingPathExtension,
83
+ @"path": [self.binaryDirectory stringByAppendingPathComponent:fileName],
84
+ @"spriteVersionNumber": @1,
85
+ @"spriteRowCount": @9
86
+ }];
87
+ }
88
+ return result;
89
+ }
90
+ // 素材目录的 mtime。目录里增删条目会改动它,而 `cc-pets pet add` / `remove` 正是在增删
91
+ // 条目——所以这一个时间戳就足以判断列表是否需要重扫,不必每次打开菜单都遍历目录。
92
+ - (NSDate *)petOptionsStamp {
93
+ NSDictionary *attributes = [NSFileManager.defaultManager
94
+ attributesOfItemAtPath:OwnPetsDirectory() error:nil];
95
+ return attributes[NSFileModificationDate];
96
+ }
97
+ - (void)invalidatePetOptionsCache {
98
+ self.cachedPetOptions = nil;
99
+ self.cachedPetOptionsStamp = nil;
100
+ }
101
+ - (NSArray<NSDictionary *> *)petOptions {
102
+ NSDate *stamp = [self petOptionsStamp];
103
+ BOOL stale = !self.cachedPetOptions ||
104
+ (stamp == nil) != (self.cachedPetOptionsStamp == nil) ||
105
+ (stamp && ![stamp isEqualToDate:self.cachedPetOptionsStamp]);
106
+ if (stale) {
107
+ self.cachedPetOptions = [self discoverPetOptions];
108
+ self.cachedPetOptionsStamp = stamp;
109
+ }
110
+ return self.cachedPetOptions;
111
+ }
112
+ - (NSDictionary *)petOptionWithID:(NSString *)petID inOptions:(NSArray<NSDictionary *> *)options {
113
+ for (NSDictionary *option in options) if ([option[@"id"] isEqualToString:petID]) return option;
114
+ return nil;
115
+ }
116
+ - (NSArray<NSDictionary *> *)waitForPetOptions {
117
+ while (YES) {
118
+ // 这个循环就是"重新扫描"按钮的实现,必须绕开缓存。
119
+ [self invalidatePetOptionsCache];
120
+ NSArray<NSDictionary *> *options = [self petOptions];
121
+ if (options.count > 0) return options;
122
+
123
+ [NSApp activateIgnoringOtherApps:YES];
124
+ NSAlert *alert = [NSAlert new];
125
+ alert.messageText = L(@"No Pet Sprites Found");
126
+ alert.informativeText = L(@"Download one with `cc-pets pet add <name>`, or put a PNG / WebP sprite sheet in ~/.cc-pets/pets/<name>/. CC Pets doesn't read ~/.petdex/pets/ or ~/.codex/pets/; to use Codex pets, turn on “Import Codex pets” in the right-click menu. Then click “Rescan”.");
127
+ [alert addButtonWithTitle:L(@"Rescan")];
128
+ [alert addButtonWithTitle:L(@"Open Pets Folder")];
129
+ [alert addButtonWithTitle:L(@"Quit")];
130
+ NSModalResponse response = [alert runModal];
131
+ if (response == NSAlertSecondButtonReturn) {
132
+ NSString *directory = OwnPetsDirectory();
133
+ [NSFileManager.defaultManager createDirectoryAtPath:directory
134
+ withIntermediateDirectories:YES attributes:nil error:nil];
135
+ [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:directory]];
136
+ } else if (response == NSAlertThirdButtonReturn) {
137
+ return @[];
138
+ }
139
+ }
140
+ }
141
+ - (void)switchPetToID:(NSString *)petID {
142
+ NSArray<NSDictionary *> *options = [self petOptions];
143
+ NSDictionary *option = [self petOptionWithID:petID inOptions:options];
144
+ if (!option) return;
145
+ NSInteger spriteRowCount = [option[@"spriteRowCount"] integerValue] ?: 9;
146
+ NSImage *image = LoadPetSpriteImage(option[@"path"], NSMakeSize(140, 150), spriteRowCount);
147
+ if (!image) return;
148
+ [self.petView applySheet:image petID:petID rowCount:spriteRowCount];
149
+ PetPhrasesSetCurrentPetID(petID);
150
+ [NSUserDefaults.standardUserDefaults setObject:petID forKey:@"CCPetsSelectedSprite"];
151
+ }
152
+ - (BOOL)deletePetWithID:(NSString *)petID {
153
+ if (![petID hasPrefix:@"external:"]) return NO;
154
+ NSArray<NSDictionary *> *options = [self petOptions];
155
+ NSDictionary *option = [self petOptionWithID:petID inOptions:options];
156
+ if (!option) return NO;
157
+
158
+ NSString *name = [petID substringFromIndex:@"external:".length];
159
+ if (name.length == 0 || [name containsString:@"/"] || [name isEqualToString:@"."] ||
160
+ [name isEqualToString:@".."]) return NO;
161
+ NSString *root = OwnPetsDirectory().stringByStandardizingPath;
162
+ NSString *directory = [root stringByAppendingPathComponent:name].stringByStandardizingPath;
163
+ NSString *optionDirectory = [[option[@"path"] stringByDeletingLastPathComponent] stringByStandardizingPath];
164
+ if (![directory.stringByDeletingLastPathComponent isEqualToString:root] ||
165
+ ![optionDirectory isEqualToString:directory]) return NO;
166
+
167
+ NSError *error = nil;
168
+ if (![NSFileManager.defaultManager removeItemAtPath:directory error:&error]) {
169
+ [self showAlertWithTitle:L(@"Can't Delete Pet")
170
+ message:error.localizedDescription ?: L(@"Failed to delete the pet folder.")];
171
+ return NO;
172
+ }
173
+
174
+ [self invalidatePetOptionsCache];
175
+ if ([self.petView.currentPetID isEqualToString:petID]) {
176
+ NSDictionary *fallback = [self petOptions].firstObject;
177
+ if (fallback) [self switchPetToID:fallback[@"id"]];
178
+ else {
179
+ PetPhrasesSetCurrentPetID(nil);
180
+ [NSUserDefaults.standardUserDefaults removeObjectForKey:@"CCPetsSelectedSprite"];
181
+ }
182
+ }
183
+ return YES;
184
+ }
185
+ @end