cc-pets 2.3.0 → 2.5.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 (101) hide show
  1. package/CC_BRIDGE.md +63 -7
  2. package/CC_BRIDGE.zh-CN.md +43 -5
  3. package/CHANGELOG.md +106 -0
  4. package/CHANGELOG.zh-CN.md +106 -0
  5. package/CONTRIBUTING.md +23 -1
  6. package/CONTRIBUTING.zh-CN.md +18 -1
  7. package/PROVIDER_PROTOCOL.md +5 -1
  8. package/PROVIDER_PROTOCOL.zh-CN.md +4 -1
  9. package/README.md +177 -33
  10. package/README.zh-CN.md +137 -32
  11. package/Resources/AgentIcons/claude.png +0 -0
  12. package/Resources/AgentIcons/codex.icns +0 -0
  13. package/Resources/IDEPlugins/cc-pets-terminal.vsix +0 -0
  14. package/Resources/IDEPlugins/cc-pets-terminal.zip +0 -0
  15. package/Resources/zh-Hans.lproj/Localizable.strings +187 -35
  16. package/Sources/CCPets/App/CCPetsAppDelegate+AgentEvents.m +47 -4
  17. package/Sources/CCPets/App/CCPetsAppDelegate+AgentStatus.m +121 -20
  18. package/Sources/CCPets/App/CCPetsAppDelegate+Bridge.m +8 -6
  19. package/Sources/CCPets/App/CCPetsAppDelegate+MenuBar.m +86 -0
  20. package/Sources/CCPets/App/CCPetsAppDelegate+Private.h +14 -1
  21. package/Sources/CCPets/App/CCPetsAppDelegate+Quota.m +6 -1
  22. package/Sources/CCPets/App/CCPetsAppDelegate+Settings.m +3 -6
  23. package/Sources/CCPets/App/CCPetsAppDelegate+Speech.m +118 -50
  24. package/Sources/CCPets/App/CCPetsAppDelegate+Update.m +4 -1
  25. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +4 -0
  26. package/Sources/CCPets/App/CCPetsAppDelegate.h +12 -2
  27. package/Sources/CCPets/App/CCPetsAppDelegate.m +4 -2
  28. package/Sources/CCPets/App/main.m +6 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridge.m +45 -18
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +175 -68
  31. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +14 -6
  32. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +356 -110
  33. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +0 -2
  34. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +247 -126
  35. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +37 -9
  36. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +385 -80
  37. package/Sources/CCPets/Integrations/CCPetsEvents.h +5 -0
  38. package/Sources/CCPets/Integrations/CCPetsEvents.m +68 -12
  39. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.h +21 -0
  40. package/Sources/CCPets/Integrations/CCPetsIDEIntegration.m +503 -0
  41. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +1 -1
  42. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.h +5 -0
  43. package/Sources/CCPets/Integrations/CCPetsLaunchPreflight.m +367 -0
  44. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.h +8 -1
  45. package/Sources/CCPets/Integrations/CCPetsTerminalFocus.m +156 -25
  46. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.h +17 -0
  47. package/Sources/CCPets/Integrations/CCPetsTerminalIntegration.m +64 -0
  48. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.h +23 -0
  49. package/Sources/CCPets/Integrations/CCPetsVSCodeIntegration.m +475 -0
  50. package/Sources/CCPets/Pet/CCPetsPhrasesEditor.m +7 -0
  51. package/Sources/CCPets/Pet/PetView+Menu.m +11 -3
  52. package/Sources/CCPets/Pet/PetView.h +7 -0
  53. package/Sources/CCPets/Pet/PetView.m +12 -1
  54. package/Sources/CCPets/Support/CCPetsDoctor.m +26 -12
  55. package/Sources/CCPets/Support/CCPetsPreferences.h +12 -0
  56. package/Sources/CCPets/Support/CCPetsPreferences.m +52 -2
  57. package/Sources/CCPets/UI/CCPetsFormBuilder.h +2 -0
  58. package/Sources/CCPets/UI/CCPetsFormBuilder.m +18 -7
  59. package/Sources/CCPets/UI/CCPetsGlassView.h +26 -4
  60. package/Sources/CCPets/UI/CCPetsGlassView.m +40 -9
  61. package/Sources/CCPets/UI/CCPetsMenuBarIcon.h +16 -0
  62. package/Sources/CCPets/UI/CCPetsMenuBarIcon.m +70 -0
  63. package/Sources/CCPets/UI/CCPetsMenuBarPanel.h +18 -0
  64. package/Sources/CCPets/UI/CCPetsMenuBarPanel.m +528 -0
  65. package/Sources/CCPets/UI/CCPetsMenuBarSummary.h +51 -0
  66. package/Sources/CCPets/UI/CCPetsMenuBarSummary.m +95 -0
  67. package/Sources/CCPets/UI/CCPetsSettingsPage.h +6 -1
  68. package/Sources/CCPets/UI/CCPetsSettingsPage.m +577 -66
  69. package/Sources/CCPets/UI/CCPetsStatusItem.h +28 -0
  70. package/Sources/CCPets/UI/CCPetsStatusItem.m +147 -0
  71. package/Sources/CCPets/UI/CCPetsUIStyle.h +5 -2
  72. package/Sources/CCPets/UI/CCPetsUIStyle.m +57 -8
  73. package/Sources/CCPets/UI/CCPetsUsageChartView.m +4 -0
  74. package/Sources/CCPets/UI/CCPetsUsagePage.m +23 -28
  75. package/Sources/CCPets/UI/CCPetsUsageStore.m +2 -2
  76. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +5 -3
  77. package/Sources/CCPets/Usage/CCPetsUsage+CodexBackground.m +193 -0
  78. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +1 -0
  79. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +49 -11
  80. package/Sources/CCPets/Usage/CCPetsUsage.h +3 -2
  81. package/Sources/CCPets/Usage/CCPetsUsageMonitor.m +15 -17
  82. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +11 -29
  83. package/Sources/CCPets/Usage/QuotaDashboardView.m +128 -2
  84. package/THIRD_PARTY_NOTICES.md +7 -3
  85. package/THIRD_PARTY_NOTICES.zh-CN.md +5 -1
  86. package/bin/claude-with-pet +2 -0
  87. package/bin/codex-with-pet +2 -0
  88. package/package.json +5 -1
  89. package/plugins/jetbrains/README.md +62 -0
  90. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalBridge.java +379 -0
  91. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalIdentity.java +24 -0
  92. package/plugins/jetbrains/src/main/java/com/ccpets/terminal/TerminalStartup.java +12 -0
  93. package/plugins/jetbrains/src/main/resources/META-INF/plugin.xml +23 -0
  94. package/plugins/jetbrains/src/main/resources/META-INF/pluginIcon.svg +380 -0
  95. package/plugins/vscode/README.md +63 -0
  96. package/plugins/vscode/extension.js +210 -0
  97. package/plugins/vscode/package.json +18 -0
  98. package/scripts/build-idea-plugin.sh +101 -0
  99. package/scripts/build-vscode-extension.sh +112 -0
  100. package/scripts/build.sh +24 -2
  101. package/scripts/compile-cached.zsh +133 -0
@@ -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
+ }
@@ -1,6 +1,7 @@
1
1
  #import "CCPetsPhrasesEditor.h"
2
2
  #import "CCPetsL10n.h"
3
3
  #import "CCPetsPhrases.h"
4
+ #import "CCPetsPreferences.h"
4
5
  #import "CCPetsUIStyle.h"
5
6
 
6
7
  static void (^PetPhrasesSpeakHandler)(NSString *);
@@ -491,6 +492,12 @@ static void (^PetPhrasesSpeakHandler)(NSString *);
491
492
  [self showStatus:[NSString stringWithFormat:L(@"[%@] has no usable lines."), tag] warning:YES];
492
493
  return;
493
494
  }
495
+ // 「仅菜单栏」时桌宠藏着,说了也看不见;照实告诉用户,句子本身仍然显示出来。
496
+ if ([CCPetsDisplayMode() isEqualToString:CCPetsDisplayModeMenuBar]) {
497
+ [self showStatus:[NSString stringWithFormat:L(@"The pet is hidden (menu bar only). Line: %@"), text]
498
+ warning:YES];
499
+ return;
500
+ }
494
501
  if (PetPhrasesSpeakHandler) PetPhrasesSpeakHandler(text);
495
502
  [self showStatus:[NSString stringWithFormat:L(@"Trying: %1$@%2$@"), text,
496
503
  fellBack ? L(@" (from the shared lines)") : @""] warning:NO];
@@ -490,6 +490,11 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
490
490
  }
491
491
 
492
492
  - (void)rightMouseDown:(NSEvent *)event {
493
+ [NSMenu popUpContextMenu:[self buildContextMenu] withEvent:event forView:self];
494
+ [self finishContextMenu];
495
+ }
496
+ // 菜单栏图标的右键菜单也是这一份,所以建菜单和收尾分开,不和 NSEvent 绑在一起。
497
+ - (NSMenu *)buildContextMenu {
493
498
  NSArray<NSDictionary *> *availablePets = self.petOptionsRequested ? self.petOptionsRequested() : @[];
494
499
  NSMenu *menu = [NSMenu new];
495
500
  menu.minimumWidth = 194.0;
@@ -552,9 +557,9 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
552
557
  return [CCPetsPanelTheme() isEqualToString:@"liquid"] && CCPetsLiquidGlassAvailable();
553
558
  };
554
559
  NSDictionary<NSNumber *, NSString *> *dimTitles = @{
555
- @0: L(@"Clear (0%)"), @15: L(@"Light (15%)"), @25: L(@"Standard (25%)"), @45: L(@"Legible (45%)")};
560
+ @0: L(@"Clear (0%)"), @25: L(@"Light (25%)"), @50: L(@"Standard (50%)"), @100: L(@"Legible (100%)")};
556
561
  // 主窗口里可以调成任意值,菜单只有四档:勾选最接近的那档。
557
- NSInteger selectedDim = CCPetsNearestGlassDimLevel(CCPetsGlassDimLevel());
562
+ NSInteger selectedDim = CCPetsNearestGlassDimLevel(CCPetsGlassDimPercent());
558
563
  for (NSNumber *level in CCPetsGlassDimLevels()) {
559
564
  NSMenuItem *item = [MenuChoiceRowView addToMenu:themeMenu title:dimTitles[level] group:@"dim"
560
565
  representedObject:level checked:level.integerValue == selectedDim
@@ -590,7 +595,10 @@ static const NSInteger PetMenuDeleteButtonTag = 1002;
590
595
  openItem.target = NSApp.delegate;
591
596
  NSMenuItem *quitItem = [menu addItemWithTitle:L(@"Quit CC Pets") action:@selector(terminate:) keyEquivalent:@"q"];
592
597
  quitItem.target = NSApp;
593
- [NSMenu popUpContextMenu:menu withEvent:event forView:self];
598
+ return menu;
599
+ }
600
+ // 菜单收起后:收掉悬停说明和宠物预览浮窗。
601
+ - (void)finishContextMenu {
594
602
  [MenuHint cancel];
595
603
  self.activePetSwitchMenu = nil;
596
604
  [self.petMenuPreviewPanel orderOut:nil];
@@ -42,5 +42,12 @@
42
42
  - (instancetype)initWithFrame:(NSRect)frame sheet:(NSImage *)sheet rowCount:(NSInteger)rowCount;
43
43
  - (void)applySheet:(NSImage *)sheet petID:(NSString *)petID rowCount:(NSInteger)rowCount;
44
44
  - (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed;
45
+ - (void)resetAgentToIdle;
45
46
  - (void)playRow:(NSInteger)row throughFrame:(NSInteger)last oneShot:(BOOL)oneShot;
46
47
  @end
48
+
49
+ // 右键菜单(现建)与菜单收起后的收尾,实现在 PetView+Menu.m。桌宠右键和菜单栏图标右键共用。
50
+ @interface PetView (Menu)
51
+ - (NSMenu *)buildContextMenu;
52
+ - (void)finishContextMenu;
53
+ @end
@@ -374,7 +374,18 @@ static const NSTimeInterval PetBreathPeriod = 3.6;
374
374
  NSUInteger hold = self.frameHolds[index].unsignedIntegerValue;
375
375
  return hold > 0 ? hold : 1;
376
376
  }
377
+ - (void)resetAgentToIdle {
378
+ [self noteActivity];
379
+ self.agentActive = NO;
380
+ if (self.microActive) [self endMicroBehavior];
381
+ [self playRow:0 throughFrame:5 oneShot:NO];
382
+ }
377
383
  - (void)handleAgentEvent:(NSString *)event tool:(NSString *)tool failed:(BOOL)failed {
384
+ // 会话退出不代表任务成功;直接恢复待机,不播放完成动作。
385
+ if ([event isEqualToString:@"SessionEnd"]) {
386
+ [self resetAgentToIdle];
387
+ return;
388
+ }
378
389
  [self noteActivity];
379
390
  [self bumpExertion];
380
391
  if ([event isEqualToString:@"SessionStart"]) {
@@ -418,7 +429,7 @@ static const NSTimeInterval PetBreathPeriod = 3.6;
418
429
  self.agentActive = YES;
419
430
  [self playRow:4 throughFrame:4 oneShot:YES];
420
431
  } else if ([event isEqualToString:@"Stop"] || [event isEqualToString:@"SubagentStop"] ||
421
- [event isEqualToString:@"TaskCompleted"] || [event isEqualToString:@"SessionEnd"]) {
432
+ [event isEqualToString:@"TaskCompleted"]) {
422
433
  self.agentActive = YES;
423
434
  [self playRow:3 throughFrame:3 oneShot:YES];
424
435
  }