cc-pets 2.3.0 → 2.4.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 (76) hide show
  1. package/CC_BRIDGE.md +19 -0
  2. package/CC_BRIDGE.zh-CN.md +15 -0
  3. package/CHANGELOG.md +51 -0
  4. package/CHANGELOG.zh-CN.md +51 -0
  5. package/CONTRIBUTING.md +22 -0
  6. package/CONTRIBUTING.zh-CN.md +17 -0
  7. package/README.md +117 -26
  8. package/README.zh-CN.md +92 -22
  9. package/Resources/AgentIcons/claude.png +0 -0
  10. package/Resources/AgentIcons/codex.icns +0 -0
  11. package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
  12. package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
  13. package/Resources/zh-Hans.lproj/Localizable.strings +155 -27
  14. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +12 -6
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +1 -1
  16. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +3 -6
  17. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +113 -47
  18. package/Sources/CCPets/App/CCPetsAppDelegate.h +2 -2
  19. package/Sources/CCPets/App/main.m +6 -0
  20. package/Sources/CCPets/Bridge/CCPetsBridge.m +11 -6
  21. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +78 -38
  22. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +2 -3
  23. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +50 -32
  24. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +46 -40
  25. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +9 -6
  26. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +171 -53
  27. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
  28. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
  29. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
  30. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
  31. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +2 -1
  32. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +107 -25
  33. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
  34. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
  35. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
  36. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
  37. package/Sources/CCPets/Pet/PetView+Menu.m +2 -2
  38. package/Sources/CCPets/Support/CCPetsDoctor.m +26 -12
  39. package/Sources/CCPets/Support/CCPetsPreferences.h +2 -0
  40. package/Sources/CCPets/Support/CCPetsPreferences.m +34 -2
  41. package/Sources/CCPets/UI/CCPetsFormBuilder.h +2 -0
  42. package/Sources/CCPets/UI/CCPetsFormBuilder.m +18 -7
  43. package/Sources/CCPets/UI/CCPetsGlassView.h +26 -4
  44. package/Sources/CCPets/UI/CCPetsGlassView.m +40 -9
  45. package/Sources/CCPets/UI/CCPetsSettingsPage.h +2 -0
  46. package/Sources/CCPets/UI/CCPetsSettingsPage.m +561 -66
  47. package/Sources/CCPets/UI/CCPetsUIStyle.h +5 -2
  48. package/Sources/CCPets/UI/CCPetsUIStyle.m +57 -8
  49. package/Sources/CCPets/UI/CCPetsUsageChartView.m +4 -0
  50. package/Sources/CCPets/UI/CCPetsUsagePage.m +23 -28
  51. package/Sources/CCPets/UI/CCPetsUsageStore.m +2 -2
  52. package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
  53. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +1 -0
  54. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +49 -11
  55. package/Sources/CCPets/Usage/CCPetsUsage.h +3 -2
  56. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +15 -17
  57. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +11 -29
  58. package/Sources/CCPets/Usage/QuotaDashboardView.m +128 -2
  59. package/THIRD_PARTY_NOTICES.md +7 -3
  60. package/THIRD_PARTY_NOTICES.zh-CN.md +5 -1
  61. package/bin/claude-with-pet +2 -0
  62. package/bin/codex-with-pet +2 -0
  63. package/package.json +5 -1
  64. package/plugins/jetbrains/README.md +62 -0
  65. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
  66. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
  67. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
  68. package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
  69. package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
  70. package/plugins/vscode/README.md +63 -0
  71. package/plugins/vscode/extension.js +210 -0
  72. package/plugins/vscode/package.json +18 -0
  73. package/scripts/build-idea-plugin.sh +101 -0
  74. package/scripts/build-vscode-extension.sh +112 -0
  75. package/scripts/build.sh +24 -2
  76. package/scripts/compile-cached.zsh +133 -0
@@ -0,0 +1,64 @@
1
+ #import "CCPetsTerminalIntegration.h"
2
+ #import <CoreServices/CoreServices.h>
3
+
4
+ static NSString *const GhosttyBundleID = @"com.mitchellh.ghostty";
5
+ // Ghostty 1.4 起在 AppleScript 字典里暴露 terminal 的 tty。
6
+ static NSString *const GhosttyMinimumVersion = @"1.4";
7
+
8
+ static NSString *AutomationState(NSString *bundleID, BOOL askUserIfNeeded) {
9
+ NSAppleEventDescriptor *target = [NSAppleEventDescriptor descriptorWithBundleIdentifier:bundleID];
10
+ OSStatus status = AEDeterminePermissionToAutomateTarget(target.aeDesc, typeWildCard, typeWildCard, askUserIfNeeded);
11
+ switch (status) {
12
+ case noErr: return @"granted";
13
+ case errAEEventNotPermitted: return @"denied";
14
+ case errAEEventWouldRequireUserConsent: return @"notDetermined";
15
+ case procNotFound: return @"notRunning";
16
+ default: return @"notDetermined";
17
+ }
18
+ }
19
+
20
+ static BOOL ApplicationIsRunning(NSString *bundleID) {
21
+ return [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID].count > 0;
22
+ }
23
+
24
+ NSArray<NSDictionary *> *CCPetsTerminalIntegrationSnapshot(void) {
25
+ NSArray<NSArray<NSString *> *> *terminals = @[
26
+ @[@"com.apple.Terminal", @"apple"],
27
+ @[@"com.googlecode.iterm2", @"apple"],
28
+ @[GhosttyBundleID, @"ghostty"],
29
+ ];
30
+ NSMutableArray *rows = [NSMutableArray array];
31
+ for (NSArray<NSString *> *terminal in terminals) {
32
+ NSString *bundleID = terminal[0];
33
+ NSURL *url = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:bundleID];
34
+ if (!url) continue;
35
+ NSBundle *bundle = [NSBundle bundleWithURL:url];
36
+ NSString *name = [NSFileManager.defaultManager displayNameAtPath:url.path].stringByDeletingPathExtension;
37
+ NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
38
+ if (![version isKindOfClass:NSString.class]) version = @"";
39
+ NSString *state;
40
+ if ([bundleID isEqualToString:GhosttyBundleID] && version.length &&
41
+ [version compare:GhosttyMinimumVersion options:NSNumericSearch] == NSOrderedAscending) {
42
+ state = @"unsupported";
43
+ } else if (!ApplicationIsRunning(bundleID)) {
44
+ state = @"notRunning";
45
+ } else {
46
+ state = AutomationState(bundleID, NO);
47
+ }
48
+ [rows addObject:@{@"name": name ?: bundleID, @"bundleID": bundleID, @"version": version,
49
+ @"group": terminal[1], @"state": state}];
50
+ }
51
+ return rows;
52
+ }
53
+
54
+ void CCPetsRequestTerminalAutomation(NSString *bundleID, void (^completion)(void)) {
55
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
56
+ if (ApplicationIsRunning(bundleID)) AutomationState(bundleID, YES);
57
+ if (completion) dispatch_async(dispatch_get_main_queue(), completion);
58
+ });
59
+ }
60
+
61
+ void CCPetsOpenAutomationSettings(void) {
62
+ NSURL *url = [NSURL URLWithString:@"x-apple.systempreferences:com.apple.preference.security?Privacy_Automation"];
63
+ [NSWorkspace.sharedWorkspace openURL:url];
64
+ }
@@ -0,0 +1,23 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // VS Code and its forks (Cursor, Windsurf, VSCodium, …) via the bundled CC Pets Terminal
4
+ // extension. A fork is recognised by Contents/Resources/app/product.json, not by bundle ID.
5
+
6
+ // YES for an installed app of the VS Code family. Cheap enough for the main thread.
7
+ BOOL CCPetsBundleIsVSCodeFamily(NSString *bundleID);
8
+
9
+ // Snapshot (disk + authenticated loopback queries): call off the main thread.
10
+ // state: connected / installed / pendingRestart / outdated / missing / disabled / unsupported.
11
+ // autoInstall is YES when the app ships its command line tool, which does the install.
12
+ NSArray<NSDictionary *> *CCPetsVSCodeIntegrationSnapshot(void);
13
+ // Installs or updates the bundled VSIX through the app's own CLI. Blocking.
14
+ BOOL CCPetsInstallVSCodeExtension(NSDictionary *app, NSError **error);
15
+ // Confirms, installs in the background and reports failures; falls back to the manual
16
+ // installer when autoInstall is NO. completion runs on the main thread.
17
+ void CCPetsPromptInstallVSCodeExtension(NSDictionary *app, void (^completion)(void));
18
+ // Reveals the bundled VSIX and explains "Install from VSIX…".
19
+ void CCPetsShowVSCodeExtensionInstaller(NSString *appName);
20
+
21
+ // Exact focus for a VS Code family target. NO when no connected window of that app could
22
+ // own the terminal, so the caller falls back to bringing the app forward.
23
+ BOOL CCPetsRequestVSCodeTerminalFocus(NSDictionary *target);
@@ -0,0 +1,475 @@
1
+ #import "CCPetsVSCodeIntegration.h"
2
+ #import "CCPetsEvents.h"
3
+ #import "CCPetsIDEIntegration.h"
4
+ #import "CCPetsL10n.h"
5
+ #import "CCPetsTerminalFocus.h"
6
+ #import <signal.h>
7
+ #import <sqlite3.h>
8
+ #import <sys/stat.h>
9
+ #import <unistd.h>
10
+
11
+ // 扩展的工作方式见 plugins/vscode/extension.js 开头的注释。这里负责三件事:识别 VS Code
12
+ // 家族应用并列出扩展状态、调用应用自带的 CLI 安装 VSIX、点卡片时按 TTY 让对应窗口选中
13
+ // 终端再把这个窗口前置。
14
+
15
+ static NSString *const VSCodeExtensionID = @"ccpets.cc-pets-terminal";
16
+ static NSString *const VSCodeMinimumVersion = @"1.80.0";
17
+
18
+ #pragma mark - Product metadata
19
+
20
+ // VS Code 家族的共同点是 Contents/Resources/app/product.json:applicationName 是 CLI 名
21
+ // (code / cursor / windsurf …),dataFolderName 是 ~ 下的数据目录(.vscode / .cursor …),
22
+ // nameShort 是 Application Support 下的用户数据目录。文件有几十 KB,按路径和 mtime 缓存。
23
+ static NSDictionary *VSCodeProduct(NSString *appPath) {
24
+ if (appPath.length == 0) return nil;
25
+ static NSMutableDictionary<NSString *, id> *cache;
26
+ static dispatch_once_t once;
27
+ dispatch_once(&once, ^{ cache = [NSMutableDictionary dictionary]; });
28
+ NSString *file = [appPath stringByAppendingPathComponent:@"Contents/Resources/app/product.json"];
29
+ struct stat info;
30
+ if (stat(file.fileSystemRepresentation, &info) || !S_ISREG(info.st_mode) || info.st_size > 4 * 1024 * 1024) return nil;
31
+ NSString *key = [NSString stringWithFormat:@"%@|%lld|%ld", file, (long long)info.st_size, (long)info.st_mtimespec.tv_sec];
32
+ @synchronized(cache) {
33
+ id cached = cache[key];
34
+ if (cached) return cached == NSNull.null ? nil : cached;
35
+ }
36
+ NSData *data = [NSData dataWithContentsOfFile:file];
37
+ id json = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
38
+ NSDictionary *product = nil;
39
+ if ([json isKindOfClass:NSDictionary.class]) {
40
+ NSString *cli = json[@"applicationName"], *dataFolder = json[@"dataFolderName"];
41
+ BOOL safeName = [cli isKindOfClass:NSString.class] && cli.length > 0 && cli.length < 64 &&
42
+ ![cli containsString:@"/"] && ![cli hasPrefix:@"."];
43
+ BOOL safeFolder = [dataFolder isKindOfClass:NSString.class] && [dataFolder hasPrefix:@"."] &&
44
+ dataFolder.length < 64 && ![dataFolder containsString:@"/"] && ![dataFolder isEqualToString:@".."];
45
+ if (safeName && safeFolder) {
46
+ NSMutableDictionary *picked = [@{@"applicationName": cli, @"dataFolderName": dataFolder} mutableCopy];
47
+ for (NSString *field in @[@"version", @"nameShort", @"nameLong"]) {
48
+ if ([json[field] isKindOfClass:NSString.class]) picked[field] = json[field];
49
+ }
50
+ product = picked;
51
+ }
52
+ }
53
+ @synchronized(cache) { cache[key] = product ?: NSNull.null; }
54
+ return product;
55
+ }
56
+
57
+ // 同一 bundle ID 可能对应多个安装:老版 Antigravity 是 VS Code 分支,2.x 不是,两者都叫
58
+ // com.google.antigravity。LaunchServices 只给一个"首选"路径,未必是正在运行的那个,所以先看
59
+ // 运行中的实例(承载终端的必然在运行),任一属于 VS Code 家族即可;都没运行才问 LaunchServices。
60
+ BOOL CCPetsBundleIsVSCodeFamily(NSString *bundleID) {
61
+ if (![bundleID isKindOfClass:NSString.class] || bundleID.length == 0) return NO;
62
+ NSArray<NSRunningApplication *> *running = [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID];
63
+ for (NSRunningApplication *app in running) {
64
+ if (VSCodeProduct(app.bundleURL.path)) return YES;
65
+ }
66
+ if (running.count) return NO;
67
+ NSURL *url = [NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:bundleID];
68
+ return VSCodeProduct(url.path) != nil;
69
+ }
70
+
71
+ static NSString *VSCodeCLIPath(NSString *appPath, NSDictionary *product) {
72
+ NSString *cli = [appPath stringByAppendingPathComponent:
73
+ [@"Contents/Resources/app/bin" stringByAppendingPathComponent:product[@"applicationName"]]];
74
+ struct stat info;
75
+ // 必须是包内的普通可执行文件,不跟随符号链接到包外。
76
+ if (lstat(cli.fileSystemRepresentation, &info) || !S_ISREG(info.st_mode) || !(info.st_mode & S_IXUSR)) return nil;
77
+ return cli;
78
+ }
79
+
80
+ static NSString *VSCodeAppVersion(NSString *appPath, NSDictionary *product) {
81
+ NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:
82
+ [appPath stringByAppendingPathComponent:@"Contents/Info.plist"]];
83
+ NSString *version = plist[@"CFBundleShortVersionString"];
84
+ return [version isKindOfClass:NSString.class] ? version : (product[@"version"] ?: @"");
85
+ }
86
+
87
+ #pragma mark - Extension versions
88
+
89
+ static NSString *VSCodeExtensionArchive(void) {
90
+ NSString *relative = @"IDEPlugins/cc-pets-terminal.vsix";
91
+ NSString *bundled = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:relative];
92
+ if ([NSFileManager.defaultManager fileExistsAtPath:bundled]) return bundled;
93
+ NSString *besideBinary = [[NSProcessInfo.processInfo.arguments.firstObject stringByDeletingLastPathComponent]
94
+ stringByAppendingPathComponent:relative];
95
+ return [NSFileManager.defaultManager fileExistsAtPath:besideBinary] ? besideBinary : nil;
96
+ }
97
+
98
+ static NSString *VersionFromPackageJSON(NSData *data) {
99
+ id json = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
100
+ NSString *version = [json isKindOfClass:NSDictionary.class] ? json[@"version"] : nil;
101
+ return [version isKindOfClass:NSString.class] && version.length < 32 ? version : nil;
102
+ }
103
+
104
+ static NSString *VSCodeBundledVersion(void) {
105
+ NSString *archive = VSCodeExtensionArchive();
106
+ if (!archive) return nil;
107
+ static NSString *cachedKey, *cachedVersion;
108
+ struct stat info;
109
+ if (stat(archive.fileSystemRepresentation, &info)) return nil;
110
+ NSString *key = [NSString stringWithFormat:@"%@|%lld|%ld", archive, (long long)info.st_size, (long)info.st_mtimespec.tv_sec];
111
+ @synchronized(VSCodeExtensionID) {
112
+ if ([cachedKey isEqualToString:key]) return cachedVersion.length ? cachedVersion : nil;
113
+ }
114
+ NSTask *task = [NSTask new];
115
+ task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/unzip"];
116
+ task.arguments = @[@"-p", archive, @"extension/package.json"];
117
+ NSPipe *output = [NSPipe pipe];
118
+ task.standardOutput = output;
119
+ task.standardError = NSFileHandle.fileHandleWithNullDevice;
120
+ NSString *version = nil;
121
+ if ([task launchAndReturnError:nil]) {
122
+ NSData *data = [output.fileHandleForReading readDataToEndOfFile];
123
+ [task waitUntilExit];
124
+ if (task.terminationStatus == 0 && data.length < 65536) version = VersionFromPackageJSON(data);
125
+ }
126
+ @synchronized(VSCodeExtensionID) {
127
+ cachedKey = key;
128
+ cachedVersion = version ?: @"";
129
+ }
130
+ return version;
131
+ }
132
+
133
+ // 扩展目录里的 ccpets.cc-pets-terminal-<版本>,排除已标记删除(.obsolete)的旧版本。
134
+ static NSString *VSCodeInstalledVersion(NSString *extensionsPath) {
135
+ NSData *obsoleteData = [NSData dataWithContentsOfFile:[extensionsPath stringByAppendingPathComponent:@".obsolete"]];
136
+ id obsolete = obsoleteData ? [NSJSONSerialization JSONObjectWithData:obsoleteData options:0 error:nil] : nil;
137
+ if (![obsolete isKindOfClass:NSDictionary.class]) obsolete = @{};
138
+ NSString *prefix = [VSCodeExtensionID stringByAppendingString:@"-"];
139
+ NSString *best = nil;
140
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:extensionsPath error:nil]) {
141
+ if (![name.lowercaseString hasPrefix:prefix] || [obsolete[name] boolValue]) continue;
142
+ NSString *manifest = [[extensionsPath stringByAppendingPathComponent:name] stringByAppendingPathComponent:@"package.json"];
143
+ struct stat info;
144
+ if (lstat(manifest.fileSystemRepresentation, &info) || !S_ISREG(info.st_mode) || info.st_size > 65536) continue;
145
+ NSString *version = VersionFromPackageJSON([NSData dataWithContentsOfFile:manifest]);
146
+ if (version && (!best || [version compare:best options:NSNumericSearch] == NSOrderedDescending)) best = version;
147
+ }
148
+ return best;
149
+ }
150
+
151
+ // 用户在扩展视图里禁用后,ID 记在全局状态库的 extensionsIdentifiers/disabled 里。
152
+ static BOOL VSCodeExtensionDisabled(NSDictionary *product) {
153
+ NSString *userData = product[@"nameShort"];
154
+ if (userData.length == 0 || [userData containsString:@"/"]) return NO;
155
+ NSString *database = [NSString stringWithFormat:@"%@/Library/Application Support/%@/User/globalStorage/state.vscdb",
156
+ NSHomeDirectory(), userData];
157
+ if (![NSFileManager.defaultManager fileExistsAtPath:database]) return NO;
158
+ sqlite3 *db = NULL;
159
+ BOOL disabled = NO;
160
+ if (sqlite3_open_v2(database.fileSystemRepresentation, &db, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK) {
161
+ sqlite3_busy_timeout(db, 200);
162
+ sqlite3_stmt *statement = NULL;
163
+ if (sqlite3_prepare_v2(db, "SELECT value FROM ItemTable WHERE key = 'extensionsIdentifiers/disabled'",
164
+ -1, &statement, NULL) == SQLITE_OK && sqlite3_step(statement) == SQLITE_ROW) {
165
+ const void *bytes = sqlite3_column_blob(statement, 0);
166
+ int length = sqlite3_column_bytes(statement, 0);
167
+ NSData *data = bytes && length > 0 && length < 1024 * 1024 ? [NSData dataWithBytes:bytes length:length] : nil;
168
+ id list = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
169
+ if ([list isKindOfClass:NSArray.class]) {
170
+ for (id entry in list) {
171
+ NSString *identifier = [entry isKindOfClass:NSDictionary.class] ? entry[@"id"] : nil;
172
+ if ([identifier isKindOfClass:NSString.class] &&
173
+ [identifier caseInsensitiveCompare:VSCodeExtensionID] == NSOrderedSame) disabled = YES;
174
+ }
175
+ }
176
+ }
177
+ sqlite3_finalize(statement);
178
+ }
179
+ sqlite3_close(db);
180
+ return disabled;
181
+ }
182
+
183
+ #pragma mark - Instances
184
+
185
+ static BOOL ProcessIsAlive(pid_t pid) {
186
+ return pid > 0 && (kill(pid, 0) == 0 || errno == EPERM);
187
+ }
188
+
189
+ // 主进程活着不代表窗口还在:关掉的窗口留下的注册文件,靠 extension host 的 PID 排除。
190
+ static NSArray<NSDictionary *> *VSCodeInstances(NSArray<NSString *> *bundleIDs) {
191
+ return CCPetsIDEBridgeInstances(^BOOL(NSDictionary *record, NSRunningApplication *app) {
192
+ if (![record[@"kind"] isEqual:@"vscode"] || !VSCodeProduct(app.bundleURL.path)) return NO;
193
+ if (!ProcessIsAlive([record[@"extensionHostPid"] intValue])) return NO;
194
+ return bundleIDs.count == 0 || [bundleIDs containsObject:app.bundleIdentifier ?: @""];
195
+ });
196
+ }
197
+
198
+ #pragma mark - Snapshot
199
+
200
+ NSArray<NSDictionary *> *CCPetsVSCodeIntegrationSnapshot(void) {
201
+ NSMutableOrderedSet<NSString *> *paths = [NSMutableOrderedSet orderedSet];
202
+ for (NSString *directory in @[@"/Applications", [NSHomeDirectory() stringByAppendingPathComponent:@"Applications"]]) {
203
+ for (NSString *name in [NSFileManager.defaultManager contentsOfDirectoryAtPath:directory error:nil]) {
204
+ NSString *path = [directory stringByAppendingPathComponent:name];
205
+ if ([name.pathExtension isEqualToString:@"app"] && VSCodeProduct(path)) [paths addObject:path];
206
+ }
207
+ }
208
+ NSMutableDictionary<NSString *, NSRunningApplication *> *running = [NSMutableDictionary dictionary];
209
+ for (NSRunningApplication *app in NSWorkspace.sharedWorkspace.runningApplications) {
210
+ NSString *path = app.bundleURL.path;
211
+ if (!path || !VSCodeProduct(path)) continue;
212
+ [paths addObject:path];
213
+ running[path] = app;
214
+ }
215
+ if (paths.count == 0) return @[];
216
+
217
+ // 每个应用可能开着多个窗口;任一窗口应答即视为已连接,同时取它报告的真实扩展目录。
218
+ NSMutableDictionary<NSString *, NSDictionary *> *connected = [NSMutableDictionary dictionary];
219
+ for (NSDictionary *instance in VSCodeInstances(nil)) {
220
+ NSString *appPath = instance[@"appPath"];
221
+ if (connected[appPath]) continue;
222
+ NSDictionary *status = CCPetsIDEBridgeRequest(instance, @"status", nil);
223
+ if (![status[@"instanceID"] isEqual:instance[@"instanceID"]] || [status[@"schemaVersion"] integerValue] != 1) continue;
224
+ NSMutableDictionary *merged = [status mutableCopy];
225
+ if ([instance[@"extensionsPath"] isKindOfClass:NSString.class]) merged[@"extensionsPath"] = instance[@"extensionsPath"];
226
+ connected[appPath] = merged;
227
+ }
228
+
229
+ NSString *bundledVersion = VSCodeBundledVersion();
230
+ NSMutableArray *rows = [NSMutableArray array];
231
+ for (NSString *path in paths) {
232
+ NSDictionary *product = VSCodeProduct(path);
233
+ NSDictionary *status = connected[path];
234
+ NSString *engine = product[@"version"];
235
+ BOOL compatible = engine.length == 0 ||
236
+ [engine compare:VSCodeMinimumVersion options:NSNumericSearch] != NSOrderedAscending;
237
+ NSString *extensions = [status[@"extensionsPath"] isKindOfClass:NSString.class] ? status[@"extensionsPath"]
238
+ : [[NSHomeDirectory() stringByAppendingPathComponent:product[@"dataFolderName"]]
239
+ stringByAppendingPathComponent:@"extensions"];
240
+ NSString *installedVersion = VSCodeInstalledVersion(extensions);
241
+ NSString *runningVersion = [status[@"pluginVersion"] isKindOfClass:NSString.class] ? status[@"pluginVersion"] : nil;
242
+ BOOL outdated = installedVersion.length && bundledVersion.length &&
243
+ [installedVersion compare:bundledVersion options:NSNumericSearch] == NSOrderedAscending;
244
+ BOOL pendingRestart = status && installedVersion.length && runningVersion.length &&
245
+ ![runningVersion isEqualToString:installedVersion];
246
+ NSString *cli = VSCodeCLIPath(path, product);
247
+
248
+ NSString *state;
249
+ if (!compatible && !status) state = @"unsupported";
250
+ else if (!installedVersion && !status) state = @"missing";
251
+ else if (outdated) state = @"outdated";
252
+ else if (pendingRestart) state = @"pendingRestart";
253
+ else if (status) state = @"connected";
254
+ else if (VSCodeExtensionDisabled(product)) state = @"disabled";
255
+ else state = @"installed";
256
+
257
+ NSString *name = [path.lastPathComponent stringByDeletingPathExtension];
258
+ NSMutableDictionary *row = [@{@"name": name, @"version": VSCodeAppVersion(path, product),
259
+ @"state": state, @"path": path, @"compatible": @(compatible), @"autoInstall": @(cli != nil),
260
+ @"running": @(running[path] != nil), @"extensionsPath": extensions} mutableCopy];
261
+ NSString *bundleID = running[path].bundleIdentifier ?: [NSBundle bundleWithPath:path].bundleIdentifier;
262
+ if (bundleID) row[@"bundleID"] = bundleID;
263
+ if (cli) row[@"cliPath"] = cli;
264
+ if (installedVersion) row[@"pluginVersion"] = installedVersion;
265
+ if (bundledVersion) row[@"bundledVersion"] = bundledVersion;
266
+ [rows addObject:row];
267
+ }
268
+ return rows;
269
+ }
270
+
271
+ #pragma mark - Install
272
+
273
+ static NSError *VSCodeInstallError(NSString *message) {
274
+ return [NSError errorWithDomain:@"CCPetsVSCodeExtension" code:1 userInfo:@{NSLocalizedDescriptionKey: message}];
275
+ }
276
+
277
+ // CLI 在 VS Code 终端里会把请求转给那个窗口(VSCODE_IPC_HOOK_CLI),从而装进别的应用;
278
+ // ELECTRON_RUN_AS_NODE 等也会改变它的行为。Pet 自己可能就是从 VS Code 终端启动的。
279
+ // 用户用来改数据目录的几个变量应用本身也认,保留。
280
+ static NSDictionary *VSCodeCLIEnvironment(void) {
281
+ NSSet *kept = [NSSet setWithArray:@[@"VSCODE_EXTENSIONS", @"VSCODE_APPDATA", @"VSCODE_PORTABLE"]];
282
+ NSMutableDictionary *environment = [NSProcessInfo.processInfo.environment mutableCopy];
283
+ for (NSString *key in environment.allKeys) {
284
+ if (([key hasPrefix:@"VSCODE_"] && ![kept containsObject:key]) || [key hasPrefix:@"ELECTRON_"]) {
285
+ [environment removeObjectForKey:key];
286
+ }
287
+ }
288
+ return environment;
289
+ }
290
+
291
+ BOOL CCPetsInstallVSCodeExtension(NSDictionary *app, NSError **error) {
292
+ NSString *archive = VSCodeExtensionArchive();
293
+ if (!archive) {
294
+ if (error) *error = VSCodeInstallError(L(@"The VS Code extension is missing from this CC Pets installation. Reinstall CC Pets to restore it."));
295
+ return NO;
296
+ }
297
+ NSString *path = app[@"path"];
298
+ NSDictionary *product = VSCodeProduct(path);
299
+ NSString *cli = product ? VSCodeCLIPath(path, product) : nil;
300
+ if (!cli || ![cli isEqualToString:app[@"cliPath"]]) {
301
+ if (error) *error = VSCodeInstallError(L(@"This app's command line tool was not found."));
302
+ return NO;
303
+ }
304
+ NSTask *task = [NSTask new];
305
+ task.executableURL = [NSURL fileURLWithPath:cli];
306
+ task.arguments = @[@"--install-extension", archive, @"--force"];
307
+ task.environment = VSCodeCLIEnvironment();
308
+ task.currentDirectoryURL = [NSURL fileURLWithPath:NSHomeDirectory()];
309
+ NSPipe *output = [NSPipe pipe];
310
+ task.standardOutput = output;
311
+ task.standardError = output;
312
+ task.standardInput = NSFileHandle.fileHandleWithNullDevice;
313
+ dispatch_semaphore_t exited = dispatch_semaphore_create(0);
314
+ task.terminationHandler = ^(NSTask *finished) { dispatch_semaphore_signal(exited); };
315
+ NSError *launchError = nil;
316
+ if (![task launchAndReturnError:&launchError]) {
317
+ if (error) *error = VSCodeInstallError(launchError.localizedDescription ?: L(@"Installation failed."));
318
+ return NO;
319
+ }
320
+ // 边跑边读,免得输出塞满管道把 CLI 卡住。
321
+ __block NSData *log = nil;
322
+ dispatch_semaphore_t drained = dispatch_semaphore_create(0);
323
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
324
+ log = [output.fileHandleForReading readDataToEndOfFile];
325
+ dispatch_semaphore_signal(drained);
326
+ });
327
+ if (dispatch_semaphore_wait(exited, dispatch_time(DISPATCH_TIME_NOW, 120 * NSEC_PER_SEC))) {
328
+ [task terminate];
329
+ if (error) *error = VSCodeInstallError(L(@"The command line tool did not finish in time."));
330
+ return NO;
331
+ }
332
+ dispatch_semaphore_wait(drained, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC));
333
+ NSString *text = log ? [[NSString alloc] initWithData:log encoding:NSUTF8StringEncoding] : @"";
334
+ if (task.terminationStatus == 0 && ![text localizedCaseInsensitiveContainsString:@"failed"]) return YES;
335
+ // 把 CLI 最后一行有内容的输出交给用户,通常就是失败原因。
336
+ NSString *reason = nil;
337
+ for (NSString *line in [text componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet].reverseObjectEnumerator) {
338
+ NSString *trimmed = [line stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
339
+ if (trimmed.length) { reason = trimmed.length > 300 ? [trimmed substringToIndex:300] : trimmed; break; }
340
+ }
341
+ if (error) *error = VSCodeInstallError(reason ?: L(@"Installation failed."));
342
+ return NO;
343
+ }
344
+
345
+ void CCPetsShowVSCodeExtensionInstaller(NSString *appName) {
346
+ NSString *archive = VSCodeExtensionArchive();
347
+ NSAlert *alert = [NSAlert new];
348
+ alert.messageText = L(@"Install the VS Code extension");
349
+ if (!archive) {
350
+ alert.informativeText = L(@"The VS Code extension is missing from this CC Pets installation. Reinstall CC Pets to restore it.");
351
+ [alert addButtonWithTitle:L(@"OK")];
352
+ [alert runModal];
353
+ return;
354
+ }
355
+ [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:archive]]];
356
+ alert.informativeText = [NSString stringWithFormat:
357
+ L(@"In %@, open the Extensions view, choose ⋯ → Install from VSIX…, then pick cc-pets-terminal.vsix. Open windows connect automatically; reload a window if it does not."),
358
+ appName.length ? appName : @"VS Code"];
359
+ [alert addButtonWithTitle:L(@"Copy VSIX Path")];
360
+ [alert addButtonWithTitle:L(@"Done")];
361
+ if ([alert runModal] == NSAlertFirstButtonReturn) {
362
+ [NSPasteboard.generalPasteboard clearContents];
363
+ [NSPasteboard.generalPasteboard setString:archive forType:NSPasteboardTypeString];
364
+ }
365
+ }
366
+
367
+ void CCPetsPromptInstallVSCodeExtension(NSDictionary *app, void (^completion)(void)) {
368
+ NSString *name = app[@"name"];
369
+ if (![app[@"autoInstall"] boolValue]) {
370
+ CCPetsShowVSCodeExtensionInstaller(name);
371
+ if (completion) completion();
372
+ return;
373
+ }
374
+ BOOL update = [app[@"state"] isEqualToString:@"outdated"];
375
+ NSAlert *confirm = [NSAlert new];
376
+ confirm.messageText = [NSString stringWithFormat:
377
+ update ? L(@"Update CC Pets Terminal in %@?") : L(@"Install CC Pets Terminal in %@?"), name];
378
+ NSString *how = [NSString stringWithFormat:L(@"CC Pets installs the extension with %@'s command line tool."), name];
379
+ NSString *after = ![app[@"running"] boolValue] ? [NSString stringWithFormat:L(@"It loads the next time %@ starts."), name]
380
+ : (update ? L(@"Reload open windows afterwards to load the new version.")
381
+ : L(@"Open windows connect automatically; reload a window if it does not."));
382
+ confirm.informativeText = [NSString stringWithFormat:@"%@ %@", how, after];
383
+ [confirm addButtonWithTitle:update ? L(@"Update") : L(@"Install")];
384
+ [confirm addButtonWithTitle:L(@"Cancel")];
385
+ if ([confirm runModal] != NSAlertFirstButtonReturn) {
386
+ if (completion) completion();
387
+ return;
388
+ }
389
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
390
+ NSError *error = nil;
391
+ BOOL ok = CCPetsInstallVSCodeExtension(app, &error);
392
+ dispatch_async(dispatch_get_main_queue(), ^{
393
+ if (!ok) {
394
+ NSAlert *alert = [NSAlert new];
395
+ alert.alertStyle = NSAlertStyleWarning;
396
+ alert.messageText = L(@"Could not install the extension automatically");
397
+ alert.informativeText = error.localizedDescription ?: L(@"Installation failed.");
398
+ [alert addButtonWithTitle:L(@"Install Manually…")];
399
+ [alert addButtonWithTitle:L(@"OK")];
400
+ if ([alert runModal] == NSAlertFirstButtonReturn) CCPetsShowVSCodeExtensionInstaller(name);
401
+ }
402
+ if (completion) completion();
403
+ });
404
+ });
405
+ }
406
+
407
+ #pragma mark - Focus
408
+
409
+ static NSWorkspaceOpenConfiguration *ActivatingConfiguration(void) {
410
+ NSWorkspaceOpenConfiguration *configuration = [NSWorkspaceOpenConfiguration configuration];
411
+ configuration.activates = YES;
412
+ configuration.addsToRecentItems = NO;
413
+ return configuration;
414
+ }
415
+
416
+ // 扩展 API 无法前置系统窗口。把窗口的工作区再交给应用打开一次:已经打开它的窗口会被
417
+ // 聚焦并切到所在桌面,与在 Finder 里打开同一个文件夹的效果一样。只交出确实存在的文件夹
418
+ // 或 .code-workspace 文件,避免路径失效时开出新窗口;没有工作区的窗口只能激活应用。
419
+ static void VSCodeBringWindowForward(NSString *appPath, NSString *workspace) {
420
+ NSURL *application = [NSURL fileURLWithPath:appPath isDirectory:YES];
421
+ BOOL isDirectory = NO;
422
+ BOOL openable = [workspace isKindOfClass:NSString.class] && workspace.isAbsolutePath &&
423
+ [NSFileManager.defaultManager fileExistsAtPath:workspace isDirectory:&isDirectory] &&
424
+ (isDirectory || [workspace.pathExtension isEqualToString:@"code-workspace"]);
425
+ if (openable) {
426
+ [NSWorkspace.sharedWorkspace openURLs:@[[NSURL fileURLWithPath:workspace isDirectory:isDirectory]]
427
+ withApplicationAtURL:application configuration:ActivatingConfiguration() completionHandler:nil];
428
+ } else {
429
+ [NSWorkspace.sharedWorkspace openApplicationAtURL:application
430
+ configuration:ActivatingConfiguration() completionHandler:nil];
431
+ }
432
+ }
433
+
434
+ BOOL CCPetsRequestVSCodeTerminalFocus(NSDictionary *target) {
435
+ if (![target isKindOfClass:NSDictionary.class]) return NO;
436
+ NSString *tty = SanitizedShortString([target[@"tty"] isKindOfClass:NSString.class]
437
+ ? [target[@"tty"] lastPathComponent] : nil, 64);
438
+ if (![tty hasPrefix:@"ttys"]) return NO;
439
+ NSMutableArray<NSString *> *bundles = [NSMutableArray array];
440
+ for (NSString *bundleID in TerminalFocusBundleCandidates(target)) {
441
+ if (CCPetsBundleIsVSCodeFamily(bundleID)) [bundles addObject:bundleID];
442
+ }
443
+ // TERM_PROGRAM=vscode 却没捕获到应用时问遍所有 VS Code 家族窗口:TTY 在本机唯一。
444
+ NSString *program = SanitizedShortString(target[@"program"], 64).lowercaseString;
445
+ if (bundles.count == 0 && ![program isEqualToString:@"vscode"]) return NO;
446
+ // 只读注册文件,不发请求;没有连接中的窗口时立即交还给调用方激活应用。
447
+ NSArray<NSDictionary *> *instances = VSCodeInstances(bundles);
448
+ if (instances.count == 0) return NO;
449
+
450
+ static BOOL focusing = NO;
451
+ if (focusing) return YES;
452
+ focusing = YES;
453
+ NSString *fallbackApp = instances.firstObject[@"appPath"];
454
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
455
+ NSString *appPath = nil, *workspace = nil;
456
+ for (NSDictionary *instance in instances) {
457
+ NSDictionary *response = CCPetsIDEBridgeRequest(instance, @"focus", @{@"tty": tty});
458
+ if (![response[@"focused"] boolValue]) continue;
459
+ appPath = instance[@"appPath"];
460
+ workspace = response[@"workspace"];
461
+ break;
462
+ }
463
+ dispatch_async(dispatch_get_main_queue(), ^{
464
+ focusing = NO;
465
+ if (appPath) {
466
+ VSCodeBringWindowForward(appPath, workspace);
467
+ } else {
468
+ // 远程窗口或扩展加载前就开着的异常情况:至少回到应用。
469
+ NSLog(@"VS Code terminal focus: no window owns %@", tty);
470
+ VSCodeBringWindowForward(fallbackApp, nil);
471
+ }
472
+ });
473
+ });
474
+ return YES;
475
+ }
@@ -552,9 +552,9 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
552
552
  return [CCPetsPanelTheme() isEqualToString:@"liquid"] && CCPetsLiquidGlassAvailable();
553
553
  };
554
554
  NSDictionary<NSNumber *, NSString *> *dimTitles = @{
555
- @0: L(@"Clear (0%)"), @15: L(@"Light (15%)"), @25: L(@"Standard (25%)"), @45: L(@"Legible (45%)")};
555
+ @0: L(@"Clear (0%)"), @25: L(@"Light (25%)"), @50: L(@"Standard (50%)"), @100: L(@"Legible (100%)")};
556
556
  // 主窗口里可以调成任意值,菜单只有四档:勾选最接近的那档。
557
- NSInteger selectedDim = CCPetsNearestGlassDimLevel(CCPetsGlassDimLevel());
557
+ NSInteger selectedDim = CCPetsNearestGlassDimLevel(CCPetsGlassDimPercent());
558
558
  for (NSNumber *level in CCPetsGlassDimLevels()) {
559
559
  NSMenuItem *item = [MenuChoiceRowView addToMenu:themeMenu title:dimTitles[level] group:@"dim"
560
560
  representedObject:level checked:level.integerValue == selectedDim