cc-pets 2.1.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CC_BRIDGE.md +11 -6
  2. package/CC_BRIDGE.zh-CN.md +8 -4
  3. package/CHANGELOG.md +59 -1
  4. package/CHANGELOG.zh-CN.md +59 -1
  5. package/README.md +60 -12
  6. package/README.zh-CN.md +58 -13
  7. package/Sources/CCPets/CCPetsAppDelegate+AgentEvents.m +215 -0
  8. package/Sources/CCPets/CCPetsAppDelegate+AgentStatus.m +660 -0
  9. package/Sources/CCPets/CCPetsAppDelegate+Bridge.m +297 -0
  10. package/Sources/CCPets/CCPetsAppDelegate+Pets.m +187 -0
  11. package/Sources/CCPets/CCPetsAppDelegate+Private.h +322 -0
  12. package/Sources/CCPets/CCPetsAppDelegate+Quota.m +216 -0
  13. package/Sources/CCPets/CCPetsAppDelegate+Settings.m +205 -0
  14. package/Sources/CCPets/CCPetsAppDelegate+Speech.m +392 -0
  15. package/Sources/CCPets/CCPetsAppDelegate+Update.m +458 -0
  16. package/Sources/CCPets/CCPetsAppDelegate.h +17 -16
  17. package/Sources/CCPets/CCPetsAppDelegate.m +74 -2406
  18. package/Sources/CCPets/CCPetsCleanup.h +4 -0
  19. package/Sources/CCPets/CCPetsCleanup.m +35 -2
  20. package/Sources/CCPets/CCPetsCodexRateLimits.h +1 -0
  21. package/Sources/CCPets/CCPetsCodexRateLimits.m +7 -0
  22. package/Sources/CCPets/CCPetsEvents.m +1 -1
  23. package/Sources/CCPets/CCPetsGlassMenu.h +10 -0
  24. package/Sources/CCPets/CCPetsGlassMenu.m +196 -0
  25. package/Sources/CCPets/CCPetsGlassView.h +31 -0
  26. package/Sources/CCPets/CCPetsGlassView.m +246 -0
  27. package/Sources/CCPets/CCPetsPaths.h +7 -1
  28. package/Sources/CCPets/CCPetsPaths.m +14 -1
  29. package/Sources/CCPets/CCPetsTerminalFocus.h +15 -0
  30. package/Sources/CCPets/CCPetsTerminalFocus.m +306 -15
  31. package/Sources/CCPets/CCPetsUsage.h +2 -1
  32. package/Sources/CCPets/CCPetsUsage.m +69 -21
  33. package/Sources/CCPets/CCPetsUsageMonitor.m +43 -8
  34. package/Sources/CCPets/CCPetsVersion.h +7 -0
  35. package/Sources/CCPets/CCPetsVersion.m +82 -0
  36. package/Sources/CCPets/MenuChoiceRow.h +19 -0
  37. package/Sources/CCPets/MenuChoiceRow.m +96 -0
  38. package/Sources/CCPets/MenuHintView.h +15 -0
  39. package/Sources/CCPets/MenuHintView.m +128 -0
  40. package/Sources/CCPets/PetView.h +2 -0
  41. package/Sources/CCPets/PetView.m +121 -53
  42. package/Sources/CCPets/QuotaDashboardView.h +3 -4
  43. package/Sources/CCPets/QuotaDashboardView.m +222 -146
  44. package/Sources/CCPets/main.m +29 -0
  45. package/bin/cc-pets +39 -1
  46. package/bin/codex-with-pet +2 -0
  47. package/package.json +3 -2
  48. package/scripts/bridge/cli.mjs +9 -2
  49. package/scripts/bridge/core.mjs +1 -1
  50. package/scripts/bridge/install.mjs +23 -1
  51. package/scripts/bridge/process.mjs +22 -0
  52. package/scripts/doctor.mjs +456 -0
  53. package/scripts/install-claude-hooks.mjs +12 -18
  54. package/scripts/install-codex-hooks.mjs +3 -9
  55. package/scripts/integration-markers.mjs +51 -0
  56. package/scripts/pet-store.mjs +2 -1
  57. package/scripts/uninstall-integrations.mjs +16 -44
  58. package/scripts/uninstall-shell-integration.sh +3 -3
@@ -1,5 +1,8 @@
1
1
  #import "CCPetsTerminalFocus.h"
2
2
  #import "CCPetsEvents.h"
3
+ #import "CCPetsPaths.h"
4
+ #import <fcntl.h>
5
+ #import <sys/file.h>
3
6
  #import <sys/sysctl.h>
4
7
  #import <sys/stat.h>
5
8
  #import <stdlib.h>
@@ -40,12 +43,53 @@ static NSString *HostApplicationBundleIdentifier(void) {
40
43
  return @"";
41
44
  }
42
45
 
46
+ // KERN_PROCARGS2 的布局:argc(int),可执行文件路径,若干 \0 填充,然后是 argc 个参数。
47
+ static NSArray<NSString *> *ProcessArguments(pid_t pid) {
48
+ int name[3] = { CTL_KERN, KERN_PROCARGS2, pid };
49
+ size_t size = 0;
50
+ if (sysctl(name, 3, NULL, &size, NULL, 0) != 0 || size <= sizeof(int)) return @[];
51
+ NSMutableData *buffer = [NSMutableData dataWithLength:size];
52
+ if (sysctl(name, 3, buffer.mutableBytes, &size, NULL, 0) != 0 || size <= sizeof(int)) return @[];
53
+ const char *bytes = buffer.bytes;
54
+ int argc = 0;
55
+ memcpy(&argc, bytes, sizeof(argc));
56
+ size_t offset = sizeof(argc);
57
+ while (offset < size && bytes[offset] != '\0') offset++; // 可执行文件路径
58
+ while (offset < size && bytes[offset] == '\0') offset++;
59
+ NSMutableArray<NSString *> *arguments = [NSMutableArray array];
60
+ while (offset < size && (int)arguments.count < argc) {
61
+ size_t length = strnlen(bytes + offset, size - offset);
62
+ NSString *argument = [[NSString alloc] initWithBytes:bytes + offset length:length
63
+ encoding:NSUTF8StringEncoding];
64
+ [arguments addObject:argument ?: @""];
65
+ offset += length + 1;
66
+ }
67
+ return arguments;
68
+ }
69
+
70
+ // 新版 Codex 把各个终端里的会话都交给一个常驻的共享服务(codex app-server --managed-daemon)
71
+ // 执行,hook 是这个服务拉起的,继承的是它自己的环境。那份环境停在第一次拉起服务的终端上:
72
+ // 实测服务从 IntelliJ 启动后,VS Code 里的 Codex 会话事件全被记成 IntelliJ 的 ttys001,
73
+ // 点气泡跳到了别的终端。此时 CC_PETS_TERMINAL_*、控制终端、父进程链都说明不了会话在哪儿。
74
+ BOOL TerminalFocusRunsUnderSharedAgentHost(void) {
75
+ pid_t pid = getppid();
76
+ for (NSUInteger depth = 0; depth < 16 && pid > 1; depth++) {
77
+ if ([ProcessArguments(pid) containsObject:@"--managed-daemon"]) return YES;
78
+ struct kinfo_proc info;
79
+ if (!ProcessInfoForPID(pid, &info)) break;
80
+ pid = info.kp_eproc.e_ppid;
81
+ }
82
+ return NO;
83
+ }
84
+
43
85
  static NSString *TerminalTargetValue(NSDictionary<NSString *, NSString *> *environment,
44
86
  NSString *key, NSUInteger maximumLength) {
45
87
  return SanitizedShortString(environment[key], maximumLength);
46
88
  }
47
89
 
48
90
  NSDictionary *TerminalFocusTargetFromEnvironment(void) {
91
+ // 记不准就不记:没有目标时点气泡不跳,比跳到别人的终端好。
92
+ if (TerminalFocusRunsUnderSharedAgentHost()) return @{};
49
93
  NSDictionary<NSString *, NSString *> *environment = NSProcessInfo.processInfo.environment;
50
94
  NSString *tty = environment[@"CC_PETS_TERMINAL_TTY"];
51
95
  if ([tty isKindOfClass:NSString.class]) tty = tty.lastPathComponent;
@@ -127,24 +171,271 @@ static NSString *BundleIDForTerminalProgram(NSString *program) {
127
171
  return @"";
128
172
  }
129
173
 
130
- BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
131
- if (![target isKindOfClass:NSDictionary.class]) return NO;
132
- NSString *tty = SanitizedShortString(target[@"tty"], 64);
174
+ // TERM_PROGRAM=vscode 是整个 VS Code 家族共用的标记:官方 VS Code、Cursor、Windsurf、
175
+ // Antigravity 这些分支全都这么写。它认不出具体是哪一个应用,固定映射到 com.microsoft.
176
+ // VSCode 就会把所有分支编辑器的回跳打死——那个 bundle ID 在机器上根本没有进程,激活
177
+ // 直接失败,点状态卡片毫无反应。家族内部谁是谁只有捕获到的 bundleID 知道。
178
+ static BOOL TerminalProgramIsVSCodeFamily(NSString *program) {
179
+ return [program.lowercaseString isEqualToString:@"vscode"];
180
+ }
181
+
182
+ NSArray<NSString *> *TerminalFocusBundleCandidates(NSDictionary *target) {
183
+ if (![target isKindOfClass:NSDictionary.class]) return @[];
184
+ NSString *program = SanitizedShortString(target[@"program"], 64);
133
185
  // 已知 TERM_PROGRAM 比“启动瞬间的前台应用”更可靠:VS Code Task 可能在窗口不位于
134
186
  // 前台时启动 shell。JetBrains 等没有稳定统一 bundle ID 的宿主才使用捕获值兜底。
135
- NSString *bundleID = BundleIDForTerminalProgram(
136
- SanitizedShortString(target[@"program"], 64));
137
- if (bundleID.length == 0) bundleID = SanitizedShortString(target[@"bundleID"], 128);
138
- if (bundleID.length == 0) return NO;
139
- if (RunTerminalSelectionScript(bundleID, tty)) return YES;
140
-
141
- NSArray<NSRunningApplication *> *applications =
142
- [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID];
143
- NSRunningApplication *application = applications.firstObject;
144
- if (!application) return NO;
187
+ // vscode 家族是例外,那个值分不出分支,只能反过来让捕获值当第一候选。
188
+ NSString *mapped = BundleIDForTerminalProgram(program);
189
+ NSString *captured = SanitizedShortString(target[@"bundleID"], 128);
190
+ NSArray<NSString *> *ordered = TerminalProgramIsVSCodeFamily(program)
191
+ ? @[captured, mapped] : @[mapped, captured];
192
+ NSMutableArray<NSString *> *candidates = [NSMutableArray array];
193
+ for (NSString *candidate in ordered) {
194
+ if (candidate.length == 0 || [candidates containsObject:candidate]) continue;
195
+ [candidates addObject:candidate];
196
+ }
197
+ return candidates;
198
+ }
199
+
200
+ BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
201
+ NSString *tty = SanitizedShortString(target[@"tty"], 64);
202
+ // 候选按优先级往下试,没在运行的直接跳过:映射值和捕获值总有一个指向真正承载
203
+ // 会话的那个应用,卡在第一个候选上就会白白丢掉一次可用的回跳。
204
+ for (NSString *bundleID in TerminalFocusBundleCandidates(target)) {
205
+ if (RunTerminalSelectionScript(bundleID, tty)) return YES;
206
+ NSRunningApplication *application =
207
+ [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID].firstObject;
208
+ if (!application) continue;
145
209
  #pragma clang diagnostic push
146
210
  #pragma clang diagnostic ignored "-Wdeprecated-declarations"
147
- return [application activateWithOptions:
148
- NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps];
211
+ return [application activateWithOptions:
212
+ NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps];
149
213
  #pragma clang diagnostic pop
214
+ }
215
+ return NO;
216
+ }
217
+
218
+ #pragma mark - Codex 共享服务下的会话 → 终端配对
219
+
220
+ // Codex 共享服务拉起的 hook 不知道会话在哪个终端(见 TerminalFocusRunsUnderSharedAgentHost)。
221
+ // 能确定的只有两头:codex-with-pet 启动时知道自己的终端、工作目录和时刻;hook 知道会话 ID,
222
+ // 会话记录(rollout)的第一行又记着会话的工作目录和创建时刻。新会话在 CLI 启动后一秒左右
223
+ // 就会创建,所以"同一目录里、紧挨在会话创建之前启动的那个 CLI"就是它的终端。配对结果记下来,
224
+ // 同一会话之后的事件直接查表。
225
+ static const NSUInteger CodexLaunchThreadLimit = 32;
226
+ static const NSTimeInterval CodexThreadCreationSlack = 5.0;
227
+
228
+ static NSTimeInterval ProcessStartTime(pid_t pid) {
229
+ struct kinfo_proc info;
230
+ if (!ProcessInfoForPID(pid, &info)) return 0;
231
+ struct timeval start = info.kp_proc.p_starttime;
232
+ return start.tv_sec + start.tv_usec / 1e6;
233
+ }
234
+
235
+ // pid 会被复用,只看 kill(pid, 0) 可能把登记套到一个毫不相干的新进程上。启动时刻对得上才算同一个。
236
+ static BOOL CodexLaunchIsAlive(NSDictionary *entry) {
237
+ pid_t pid = (pid_t)[entry[@"pid"] intValue];
238
+ if (pid <= 1) return NO;
239
+ NSTimeInterval started = ProcessStartTime(pid);
240
+ return started > 0 && fabs(started - [entry[@"processStartedAt"] doubleValue]) < 1.0;
241
+ }
242
+
243
+ static int LockCodexLaunchRegistry(void) {
244
+ NSString *path = CodexLaunchRegistryLockPath();
245
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
246
+ withIntermediateDirectories:YES attributes:nil error:nil];
247
+ int descriptor = open(path.fileSystemRepresentation, O_RDWR | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR);
248
+ if (descriptor < 0) return -1;
249
+ // 同 Claude 额度文件的写锁:拿不到就放弃这一次,hook 不能被一个卡住的写者挂住。
250
+ for (int attempt = 0; attempt < 50; attempt++) {
251
+ if (flock(descriptor, LOCK_EX | LOCK_NB) == 0) return descriptor;
252
+ if (errno != EWOULDBLOCK) break;
253
+ usleep(20 * 1000);
254
+ }
255
+ close(descriptor);
256
+ return -1;
257
+ }
258
+
259
+ static void UnlockCodexLaunchRegistry(int descriptor) {
260
+ flock(descriptor, LOCK_UN);
261
+ close(descriptor);
262
+ }
263
+
264
+ // 读出来时顺手丢掉已经退出的 CLI:它们不可能再是任何新会话的终端。
265
+ static NSMutableDictionary<NSString *, NSDictionary *> *LoadLiveCodexLaunches(void) {
266
+ NSData *data = [NSData dataWithContentsOfFile:CodexLaunchRegistryPath()];
267
+ id value = data.length > 0 ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
268
+ NSMutableDictionary *launches = [NSMutableDictionary dictionary];
269
+ if (![value isKindOfClass:NSDictionary.class]) return launches;
270
+ [(NSDictionary *)value enumerateKeysAndObjectsUsingBlock:^(id key, id entry, BOOL *stop) {
271
+ if ([key isKindOfClass:NSString.class] && [entry isKindOfClass:NSDictionary.class] &&
272
+ CodexLaunchIsAlive(entry)) launches[key] = entry;
273
+ }];
274
+ return launches;
275
+ }
276
+
277
+ static void SaveCodexLaunches(NSDictionary *launches) {
278
+ NSData *json = [NSJSONSerialization dataWithJSONObject:launches options:0 error:nil];
279
+ NSString *path = CodexLaunchRegistryPath();
280
+ if (json && [json writeToFile:path options:NSDataWritingAtomic error:nil]) {
281
+ chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
282
+ }
283
+ }
284
+
285
+ BOOL RegisterCodexLaunchForProcess(pid_t pid, NSString *cwd, NSDictionary *terminal,
286
+ NSTimeInterval launchedAt) {
287
+ NSTimeInterval processStartedAt = ProcessStartTime(pid);
288
+ if (processStartedAt <= 0 || cwd.length == 0 || terminal.count == 0) return NO;
289
+ int lock = LockCodexLaunchRegistry();
290
+ if (lock < 0) return NO;
291
+ NSMutableDictionary *launches = LoadLiveCodexLaunches();
292
+ launches[[NSString stringWithFormat:@"%d", pid]] = @{
293
+ @"pid": @(pid),
294
+ @"processStartedAt": @(processStartedAt),
295
+ @"launchedAt": @(launchedAt),
296
+ @"cwd": cwd.stringByStandardizingPath,
297
+ @"terminal": terminal,
298
+ @"threads": @[]
299
+ };
300
+ SaveCodexLaunches(launches);
301
+ UnlockCodexLaunchRegistry(lock);
302
+ return YES;
303
+ }
304
+
305
+ // codex-with-pet 在 exec 真正的 codex 之前调用;exec 不换 pid,所以父进程就是之后的 CLI。
306
+ int RegisterCodexLaunch(void) {
307
+ RegisterCodexLaunchForProcess(getppid(), NSFileManager.defaultManager.currentDirectoryPath,
308
+ TerminalFocusTargetFromEnvironment(), NSDate.date.timeIntervalSince1970);
309
+ return EXIT_SUCCESS;
310
+ }
311
+
312
+ // 会话记录按 sessions/YYYY/MM/DD/rollout-<时间>-<会话 ID>.jsonl 存放,目录名字典序即时间序。
313
+ // 刚开始收事件的会话一定在最近几天的目录里;resume 的旧会话找不到也没关系,按工作目录兜底。
314
+ static NSString *CodexRolloutPathForThread(NSString *thread) {
315
+ NSString *sessions = [DefaultCodexHomeDirectory() stringByAppendingPathComponent:@"sessions"];
316
+ NSFileManager *files = NSFileManager.defaultManager;
317
+ NSString *suffix = [NSString stringWithFormat:@"-%@.jsonl", thread];
318
+ NSUInteger examinedDays = 0;
319
+ NSArray *(^descending)(NSString *) = ^NSArray *(NSString *directory) {
320
+ return [[files contentsOfDirectoryAtPath:directory error:nil]
321
+ sortedArrayUsingSelector:@selector(compare:)].reverseObjectEnumerator.allObjects ?: @[];
322
+ };
323
+ for (NSString *year in descending(sessions)) {
324
+ NSString *yearPath = [sessions stringByAppendingPathComponent:year];
325
+ for (NSString *month in descending(yearPath)) {
326
+ NSString *monthPath = [yearPath stringByAppendingPathComponent:month];
327
+ for (NSString *day in descending(monthPath)) {
328
+ if (++examinedDays > 7) return nil;
329
+ NSString *dayPath = [monthPath stringByAppendingPathComponent:day];
330
+ for (NSString *name in [files contentsOfDirectoryAtPath:dayPath error:nil]) {
331
+ if ([name hasSuffix:suffix]) return [dayPath stringByAppendingPathComponent:name];
332
+ }
333
+ }
334
+ }
335
+ }
336
+ return nil;
337
+ }
338
+
339
+ // 第一行是 session_meta,带 cwd 和创建时刻;它里面有完整的系统提示词,可能很长,读到换行为止。
340
+ static NSDictionary *CodexThreadMeta(NSString *thread, NSDictionary *payload) {
341
+ NSString *path = [payload[@"transcript_path"] isKindOfClass:NSString.class]
342
+ ? payload[@"transcript_path"] : nil;
343
+ if (![NSFileManager.defaultManager fileExistsAtPath:path]) path = CodexRolloutPathForThread(thread);
344
+ NSFileHandle *handle = path ? [NSFileHandle fileHandleForReadingAtPath:path] : nil;
345
+ NSMutableData *line = [NSMutableData data];
346
+ while (handle && line.length < 8 * 1024 * 1024) {
347
+ NSData *chunk = [handle readDataOfLength:64 * 1024];
348
+ if (chunk.length == 0) break;
349
+ NSRange newline = [chunk rangeOfData:[NSData dataWithBytes:"\n" length:1] options:0
350
+ range:NSMakeRange(0, chunk.length)];
351
+ if (newline.location != NSNotFound) {
352
+ [line appendData:[chunk subdataWithRange:NSMakeRange(0, newline.location)]];
353
+ break;
354
+ }
355
+ [line appendData:chunk];
356
+ }
357
+ [handle closeFile];
358
+ id root = line.length > 0 ? [NSJSONSerialization JSONObjectWithData:line options:0 error:nil] : nil;
359
+ NSDictionary *meta = [root isKindOfClass:NSDictionary.class] &&
360
+ [root[@"payload"] isKindOfClass:NSDictionary.class] ? root[@"payload"] : @{};
361
+ NSMutableDictionary *result = [NSMutableDictionary dictionary];
362
+ NSString *cwd = [meta[@"cwd"] isKindOfClass:NSString.class] ? meta[@"cwd"]
363
+ : ([payload[@"cwd"] isKindOfClass:NSString.class] ? payload[@"cwd"] : nil);
364
+ if (cwd.length > 0) result[@"cwd"] = cwd.stringByStandardizingPath;
365
+ if ([meta[@"timestamp"] isKindOfClass:NSString.class]) {
366
+ NSISO8601DateFormatter *formatter = [NSISO8601DateFormatter new];
367
+ formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime |
368
+ NSISO8601DateFormatWithFractionalSeconds;
369
+ NSDate *created = [formatter dateFromString:meta[@"timestamp"]];
370
+ if (!created) {
371
+ formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime;
372
+ created = [formatter dateFromString:meta[@"timestamp"]];
373
+ }
374
+ if (created) result[@"createdAt"] = @(created.timeIntervalSince1970);
375
+ }
376
+ return result;
377
+ }
378
+
379
+ // 在同一工作目录的候选里挑:优先还没配过会话的 CLI;会话创建时刻已知时,取创建前最后一个
380
+ // 启动的(resume 的旧会话创建得比所有 CLI 都早,退回"最近启动的")。一个 TUI 里 /new 出来
381
+ // 的新会话没有空闲候选可配,这时同目录只剩一个 CLI 才认它,多于一个宁可不配。
382
+ static NSString *ChooseCodexLaunch(NSDictionary<NSString *, NSDictionary *> *launches,
383
+ NSString *cwd, NSNumber *createdAt) {
384
+ NSMutableArray<NSString *> *sameDirectory = [NSMutableArray array];
385
+ NSMutableArray<NSString *> *unbound = [NSMutableArray array];
386
+ for (NSString *key in launches) {
387
+ NSDictionary *entry = launches[key];
388
+ if (![entry[@"cwd"] isEqualToString:cwd]) continue;
389
+ [sameDirectory addObject:key];
390
+ if ([entry[@"threads"] count] == 0) [unbound addObject:key];
391
+ }
392
+ if (unbound.count == 0) return sameDirectory.count == 1 ? sameDirectory.firstObject : nil;
393
+ NSArray<NSString *> *byLaunch = [unbound sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
394
+ return [launches[a][@"launchedAt"] compare:launches[b][@"launchedAt"]];
395
+ }];
396
+ if (createdAt) {
397
+ NSString *preceding = nil;
398
+ for (NSString *key in byLaunch) {
399
+ if ([launches[key][@"launchedAt"] doubleValue] <=
400
+ createdAt.doubleValue + CodexThreadCreationSlack) preceding = key;
401
+ }
402
+ if (preceding) return preceding;
403
+ }
404
+ return byLaunch.lastObject;
405
+ }
406
+
407
+ NSDictionary *CodexLaunchTerminalForThread(NSString *thread, NSDictionary *payload) {
408
+ if (thread.length == 0) return @{};
409
+ int lock = LockCodexLaunchRegistry();
410
+ if (lock < 0) return @{};
411
+ NSMutableDictionary<NSString *, NSDictionary *> *launches = LoadLiveCodexLaunches();
412
+ NSDictionary *terminal = nil;
413
+ for (NSDictionary *entry in launches.allValues) {
414
+ if ([entry[@"threads"] containsObject:thread]) {
415
+ terminal = entry[@"terminal"];
416
+ break;
417
+ }
418
+ }
419
+ if (!terminal) {
420
+ NSDictionary *meta = CodexThreadMeta(thread, payload);
421
+ NSString *key = meta[@"cwd"] ? ChooseCodexLaunch(launches, meta[@"cwd"], meta[@"createdAt"]) : nil;
422
+ if (key) {
423
+ NSMutableDictionary *entry = [launches[key] mutableCopy];
424
+ NSMutableArray *threads = [entry[@"threads"] mutableCopy] ?: [NSMutableArray array];
425
+ [threads addObject:thread];
426
+ while (threads.count > CodexLaunchThreadLimit) [threads removeObjectAtIndex:0];
427
+ entry[@"threads"] = threads;
428
+ launches[key] = entry;
429
+ terminal = entry[@"terminal"];
430
+ }
431
+ }
432
+ SaveCodexLaunches(launches);
433
+ UnlockCodexLaunchRegistry(lock);
434
+ return [terminal isKindOfClass:NSDictionary.class] ? terminal : @{};
435
+ }
436
+
437
+ NSDictionary *TerminalFocusTargetForHook(NSDictionary *payload, NSString *provider) {
438
+ if (!TerminalFocusRunsUnderSharedAgentHost()) return TerminalFocusTargetFromEnvironment();
439
+ if (![provider isEqualToString:@"Codex"]) return @{};
440
+ return CodexLaunchTerminalForThread(SanitizedShortString(payload[@"session_id"], 128), payload);
150
441
  }
@@ -5,6 +5,8 @@ int RecordClaudeUsage(void);
5
5
  NSDictionary *ClaudeRateLimits(void);
6
6
  NSDictionary *LatestClaudeUsage(void);
7
7
  NSDictionary *LatestUsage(void);
8
+ // 清掉 resets_at 已经翻篇(或不可能属于当前窗口)的额度窗口,缺 resets_at 的保留。
9
+ NSDictionary *UsageByRemovingExpiredQuotaWindows(NSDictionary *usage);
8
10
 
9
11
  // 增量跟读 ~/.claude/projects 下的会话转录,按官方 5 小时 / 7 天窗口聚合本地 Token。
10
12
  @interface ClaudeUsageReader : NSObject
@@ -28,7 +30,6 @@ NSDictionary *LatestUsage(void);
28
30
  @property NSTimeInterval lastFullDiscovery;
29
31
  - (NSDictionary *)refresh;
30
32
  - (NSDictionary *)refreshWithFullDiscovery;
31
- - (NSDictionary *)refreshForSessionURL:(NSURL *)url;
32
33
  // 一批 FSEvents 里可能有多个会话文件同时变更(并发会话)。谁的额度采样更晚要读过才知道,
33
34
  // 不能取遍历到的最后一个,详见实现处注释。
34
35
  - (NSDictionary *)refreshForSessionURLs:(NSArray<NSURL *> *)urls;
@@ -71,6 +71,10 @@ static NSDictionary *UsageByRemovingInactiveQuotaWindows(NSDictionary *usage) {
71
71
  return result ?: usage;
72
72
  }
73
73
 
74
+ NSDictionary *UsageByRemovingExpiredQuotaWindows(NSDictionary *usage) {
75
+ return UsageByRemovingInactiveQuotaWindows(usage);
76
+ }
77
+
74
78
  // 同一个账号下的每个 Claude 会话都会把自己那次响应里的 rate_limits 抄到同一个文件上,
75
79
  // 而"响应更早、落盘更晚"在并发会话下完全正常。无条件覆盖时旧快照会盖掉新快照,面板上
76
80
  // 的剩余额度于是来回跳(实测 99% → 94% → 又回 99%)。同一窗口内官方用量只增不减,
@@ -81,20 +85,37 @@ static NSDictionary *UsageByRemovingInactiveQuotaWindows(NSDictionary *usage) {
81
85
  // 滚动、无条件接受归零"于是对 7 天窗口几乎每次都成立,这道防线等同于从未生效——
82
86
  // 2026-08-19 实测面板被一份 used=2% 的旧快照顶成剩余 98%,就是从这条分支进来的。
83
87
  // 真正的窗口滚动只可能发生在旧窗口到期之后,拿 now 和 storedReset 判断就够了。
88
+ //
89
+ // 用量真的下降(官方口径调整、临时提额)时单调性不成立,只能靠"这份快照来自更新的响应"
90
+ // 放行。freshSince / storedSince 就是两份快照各自对应响应的时刻(见 QuotaValueSince)。
91
+ // 原先这里是"上次接受已过 10 分钟就无条件放行",但 statusline 配了 refreshInterval 时,
92
+ // 每个开着的空闲会话每分钟都会把自己最后一次响应里的旧额度重报一遍:活跃会话一关,
93
+ // 10 分钟后面板就被某个空闲会话的旧值顶掉(2026-09-29 实测剩余 18% → 跳回 70%)。
84
94
  static BOOL ShouldAcceptQuotaWindow(id storedValue, NSDictionary *fresh, double windowMinutes,
85
- BOOL stale, NSTimeInterval now) {
95
+ NSTimeInterval freshSince, NSTimeInterval storedSince, NSTimeInterval now) {
86
96
  if (!QuotaWindowLooksCurrent(fresh, windowMinutes, now)) return NO;
87
97
  NSDictionary *stored = [storedValue isKindOfClass:NSDictionary.class] ? storedValue : nil;
88
98
  if (!stored) return YES;
89
99
  // 旧窗口确实到期了:新周期里用量归零是真的。
90
100
  if (now >= [stored[@"resets_at"] doubleValue]) return YES;
91
- if (stale) return YES;
92
- return [fresh[@"used_percentage"] doubleValue] >= [stored[@"used_percentage"] doubleValue];
101
+ if ([fresh[@"used_percentage"] doubleValue] >= [stored[@"used_percentage"] doubleValue]) return YES;
102
+ return freshSince > storedSince;
93
103
  }
94
104
 
95
- // 单调性判据只在旧快照还新鲜时成立。官方口径调整(例如临时提额)会让用量真的掉下去,
96
- // 这时旧值必须能被顶掉,否则面板会被永久钉在一个偏高的数字上。
97
- static const NSTimeInterval StaleQuotaSnapshotSeconds = 600.0;
105
+ // 一份快照对应的响应是什么时候拿到的。statusline 的 payload 不带这个时刻,只能按会话推断:
106
+ // 同一个会话重报的值和它上次一模一样,说明它没有拿到新响应,时刻沿用上次记下的;值变了
107
+ // 才是新响应,记为现在。第一次见到的会话记 0(未知)——它可能是早就开着的空闲会话,
108
+ // 不能凭"刚被看到"就当成最新;它下一次真的变了自然会拿到时刻。
109
+ static NSTimeInterval QuotaValueSince(NSDictionary *previous, NSDictionary *fresh, NSTimeInterval now) {
110
+ if (![previous isKindOfClass:NSDictionary.class]) return 0;
111
+ BOOL unchanged = [previous[@"used_percentage"] isEqual:fresh[@"used_percentage"]] &&
112
+ [previous[@"resets_at"] isEqual:fresh[@"resets_at"]];
113
+ return unchanged ? [previous[@"since"] doubleValue] : now;
114
+ }
115
+
116
+ // 会话记录只为判断"值有没有变",一天没再上报的会话早就关了;上限防止异常情况下无限增长。
117
+ static const NSTimeInterval QuotaSessionRecordTTL = 24 * 60 * 60;
118
+ static const NSUInteger QuotaSessionRecordLimit = 64;
98
119
 
99
120
  // 拿锁的重试上限。拿不到就放弃这次写入:并发写者手里的数据同样新鲜,跳过一次不丢信息,
100
121
  // 而无锁写入正是要避免的读改写交错。阻塞版 flock 没有超时,一个被 SIGSTOP 或卡在慢速
@@ -130,27 +151,55 @@ int RecordClaudeUsage(void) {
130
151
  ? [NSJSONSerialization JSONObjectWithData:existing options:0 error:nil] : nil;
131
152
  NSDictionary *stored = [storedValue isKindOfClass:NSDictionary.class] ? storedValue : nil;
132
153
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
133
- // 过期判据必须逐窗口记"上一次被接受的时刻"。用整个文件的写盘时间会让逃生阀失效:
134
- // 快照被判倒退而拒绝时文件照样被写,只要还有会话在持续上报,就永远到不了 10 分钟,
135
- // 于是官方真的下调用量时面板被永久钉住——正是这个阀门要防的情况。
136
- id acceptedValue = stored[@"accepted_at"];
137
- NSDictionary *accepted = [acceptedValue isKindOfClass:NSDictionary.class] ? acceptedValue : nil;
154
+ NSDictionary *storedSinceValue = [stored[@"value_since"] isKindOfClass:NSDictionary.class]
155
+ ? stored[@"value_since"] : @{};
156
+ NSMutableDictionary *sessions = [stored[@"sessions"] isKindOfClass:NSDictionary.class]
157
+ ? [stored[@"sessions"] mutableCopy] : [NSMutableDictionary dictionary];
158
+ // 没有 session_id 的 payload 无法区分"空闲重报"和"新响应",只按单调性判。
159
+ NSString *sessionID = [payload[@"session_id"] isKindOfClass:NSString.class] &&
160
+ [payload[@"session_id"] length] > 0 ? payload[@"session_id"] : nil;
161
+ NSDictionary *previousRecord = [sessions[sessionID] isKindOfClass:NSDictionary.class]
162
+ ? sessions[sessionID] : nil;
163
+ NSMutableDictionary *sessionRecord = [@{@"seen_at": @(now)} mutableCopy];
138
164
 
139
165
  NSMutableDictionary *merged = stored ? [stored mutableCopy] : [NSMutableDictionary dictionary];
140
- NSMutableDictionary *mergedAccepted = accepted ? [accepted mutableCopy] : [NSMutableDictionary dictionary];
166
+ [merged removeObjectForKey:@"accepted_at"]; // 上一版的逃生阀字段,已不再使用。
167
+ NSMutableDictionary *mergedSince = [storedSinceValue mutableCopy];
141
168
  NSDictionary *windowMinutes = @{@"five_hour": @(FiveHourWindowMinutes),
142
169
  @"seven_day": @(SevenDayWindowMinutes)};
143
170
  for (NSString *key in @[@"five_hour", @"seven_day"]) {
144
171
  NSDictionary *fresh = [limits[key] isKindOfClass:NSDictionary.class] ? limits[key] : nil;
145
172
  if (!fresh) continue; // 这次响应没带某个窗口时保留旧的:整体覆盖会让面板凭空少掉一个窗口。
146
- // accepted_at 缺失的是上一版写的文件,当过期处理,一次就能迁移过来。
147
- BOOL stale = now - [accepted[key] doubleValue] > StaleQuotaSnapshotSeconds;
173
+ NSTimeInterval freshSince = sessionID ? QuotaValueSince(previousRecord[key], fresh, now) : 0;
174
+ if (sessionID) {
175
+ sessionRecord[key] = @{@"used_percentage": fresh[@"used_percentage"] ?: NSNull.null,
176
+ @"resets_at": fresh[@"resets_at"] ?: NSNull.null,
177
+ @"since": @(freshSince)};
178
+ }
179
+ NSTimeInterval storedSince = [storedSinceValue[key] doubleValue];
148
180
  if (!ShouldAcceptQuotaWindow(stored[key], fresh, [windowMinutes[key] doubleValue],
149
- stale, now)) continue;
181
+ freshSince, storedSince, now)) continue;
150
182
  merged[key] = fresh;
151
- mergedAccepted[key] = @(now);
183
+ // 按单调性收下的旧响应不能把时刻往回拨,否则更旧的快照就能借它反超。
184
+ mergedSince[key] = @(fmax(freshSince, storedSince));
152
185
  }
153
- merged[@"accepted_at"] = mergedAccepted;
186
+ merged[@"value_since"] = mergedSince;
187
+
188
+ if (sessionID) sessions[sessionID] = sessionRecord;
189
+ for (NSString *key in sessions.allKeys) {
190
+ NSDictionary *record = [sessions[key] isKindOfClass:NSDictionary.class] ? sessions[key] : nil;
191
+ if (!record || now - [record[@"seen_at"] doubleValue] > QuotaSessionRecordTTL) {
192
+ [sessions removeObjectForKey:key];
193
+ }
194
+ }
195
+ if (sessions.count > QuotaSessionRecordLimit) {
196
+ NSArray *oldestFirst = [sessions keysSortedByValueUsingComparator:^NSComparisonResult(id left, id right) {
197
+ return [left[@"seen_at"] compare:right[@"seen_at"]];
198
+ }];
199
+ [sessions removeObjectsForKeys:[oldestFirst subarrayWithRange:
200
+ NSMakeRange(0, sessions.count - QuotaSessionRecordLimit)]];
201
+ }
202
+ merged[@"sessions"] = sessions;
154
203
  // 最后一次写盘时间。不再参与任何判据,只留给排查用。
155
204
  merged[@"written_at"] = @(now);
156
205
 
@@ -172,7 +221,9 @@ NSDictionary *ClaudeRateLimits(void) {
172
221
  if (![limits isKindOfClass:NSDictionary.class]) return nil;
173
222
  id fiveHour = [limits[@"five_hour"] isKindOfClass:NSDictionary.class] ? limits[@"five_hour"] : NSNull.null;
174
223
  id week = [limits[@"seven_day"] isKindOfClass:NSDictionary.class] ? limits[@"seven_day"] : NSNull.null;
175
- return @{@"fiveHour": fiveHour, @"week": week};
224
+ // 快照只在有会话上报时更新。窗口到期后没人再报,旧百分比会一直挂着(实测 5 小时窗口
225
+ // 重置后面板仍显示剩余 0%),与 Codex 同样按 resets_at 清掉已经翻篇的窗口。
226
+ return UsageByRemovingInactiveQuotaWindows(@{@"fiveHour": fiveHour, @"week": week});
176
227
  }
177
228
 
178
229
  NSDictionary *LatestClaudeUsage(void) {
@@ -1574,9 +1625,6 @@ static const NSUInteger MaximumPinnedSessions = 8;
1574
1625
  NSString *prefix = [sessionsPath stringByAppendingString:@"/"];
1575
1626
  return [url.path.stringByResolvingSymlinksInPath hasPrefix:prefix];
1576
1627
  }
1577
- - (NSDictionary *)refreshForSessionURL:(NSURL *)url {
1578
- return [self refreshForSessionURLs:url ? @[url] : @[]];
1579
- }
1580
1628
  // 并发会话下一批事件里会有多个会话文件同时变更,而"文件更晚被写"和"额度采样更晚"是两回事:
1581
1629
  // 会话拿到 rate_limits 之后还会继续追加别的行。取遍历到的最后一个就会切到采样偏旧的会话,
1582
1630
  // 面板上的百分比于是在两个会话之间来回跳。这里读各自的尾巴,按 sampledAt 挑,与
@@ -5,6 +5,7 @@
5
5
  #import <CoreServices/CoreServices.h>
6
6
  #import <fcntl.h>
7
7
  #import <unistd.h>
8
+ #import <sys/stat.h>
8
9
 
9
10
  // 读取与聚合全部跑在这条串行队列上,主线程只收结果。两个 reader 都不加锁,线程安全完全
10
11
  // 依赖“只有这条队列碰它们”这一条约束:FSEvents 流、Claude 的 vnode source、定时刷新、
@@ -31,10 +32,37 @@
31
32
  - (NSDictionary *)usageByApplyingLiveCodexUsage:(NSDictionary *)sessionUsage;
32
33
  @end
33
34
 
34
- // App Server 是服务端当前额度的权威源;会话日志只在成功响应落盘时才更新。短暂失败时
35
- // 留出一小段缓存寿命,既不因一次网络抖动闪回旧日志,也不会把实时值永久钉在界面上。
35
+ // App Server 是服务端当前额度的权威源;会话日志只在成功响应落盘时才更新。实时值的窗口
36
+ // 百分比不设寿命:它和会话快照按 sampledAt 比新旧(见 CodexUsageByApplyingLiveUsage),
37
+ // 窗口翻篇由 resets_at 兜底。只有"额度受限"标记有寿命——它没有窗口归属,实时查询连续
38
+ // 失败时不能让一次旧的受限结论一直挂着。
36
39
  static const NSTimeInterval CodexLiveUsageTTL = 5 * 60.0;
37
40
 
41
+ static NSDictionary *LoadCodexLiveUsage(void) {
42
+ NSData *data = [NSData dataWithContentsOfFile:CodexLiveUsagePath()];
43
+ id value = data.length > 0 ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
44
+ if (![value isKindOfClass:NSDictionary.class]) return nil;
45
+ NSDictionary *usage = value;
46
+ if (![usage[@"sampledAt"] isKindOfClass:NSNumber.class]) return nil;
47
+ for (NSString *key in @[@"fiveHour", @"week"]) {
48
+ id quota = usage[key];
49
+ if (quota && quota != NSNull.null && ![quota isKindOfClass:NSDictionary.class]) return nil;
50
+ }
51
+ return usage;
52
+ }
53
+
54
+ static void SaveCodexLiveUsage(NSDictionary *usage) {
55
+ NSData *json = [NSJSONSerialization isValidJSONObject:usage]
56
+ ? [NSJSONSerialization dataWithJSONObject:usage options:0 error:nil] : nil;
57
+ if (!json) return;
58
+ NSString *path = CodexLiveUsagePath();
59
+ [NSFileManager.defaultManager createDirectoryAtPath:path.stringByDeletingLastPathComponent
60
+ withIntermediateDirectories:YES attributes:nil error:nil];
61
+ if ([json writeToFile:path options:NSDataWritingAtomic error:nil]) {
62
+ chmod(path.fileSystemRepresentation, S_IRUSR | S_IWUSR);
63
+ }
64
+ }
65
+
38
66
  static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
39
67
  void *clientCallBackInfo, size_t numEvents, void *eventPaths,
40
68
  const FSEventStreamEventFlags eventFlags[],
@@ -86,6 +114,10 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
86
114
  // 桌宠是唯一的常驻读取者,摘要缓存由它维护并落盘。
87
115
  _codexReader.persistsCache = YES;
88
116
  _claudeReader.persistsCache = YES;
117
+ // 桌宠随最后一个客户端退出,下次启动时 App Server 要几秒才回话。这段时间先用上次
118
+ // 存下的实时值,否则面板会先显示会话日志里可能已经过时十几个小时的快照。
119
+ _codexLiveUsage = LoadCodexLiveUsage();
120
+ _codexLiveUsageUpdatedAt = [_codexLiveUsage[@"sampledAt"] doubleValue];
89
121
  __weak typeof(self) weakSelf = self;
90
122
  _codexRateLimitsReader.liveUsageHandler = ^(NSDictionary *liveUsage) {
91
123
  dispatch_async(weakSelf.queue, ^{
@@ -93,6 +125,7 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
93
125
  if (!strongSelf || !strongSelf.started) return;
94
126
  strongSelf.codexLiveUsage = liveUsage;
95
127
  strongSelf.codexLiveUsageUpdatedAt = NSDate.date.timeIntervalSince1970;
128
+ SaveCodexLiveUsage(liveUsage);
96
129
  strongSelf.codexUsage = [strongSelf usageByApplyingLiveCodexUsage:
97
130
  strongSelf.codexReader.usage ?: strongSelf.codexUsage];
98
131
  [strongSelf publishChange];
@@ -103,14 +136,16 @@ static void CodexEventsCallback(ConstFSEventStreamRef streamRef,
103
136
  }
104
137
 
105
138
  - (NSDictionary *)usageByApplyingLiveCodexUsage:(NSDictionary *)sessionUsage {
106
- if (self.codexLiveUsage && NSDate.date.timeIntervalSince1970 -
139
+ NSDictionary *live = self.codexLiveUsage;
140
+ if (!live) return sessionUsage;
141
+ if (live[@"exhaustedAt"] && NSDate.date.timeIntervalSince1970 -
107
142
  self.codexLiveUsageUpdatedAt > CodexLiveUsageTTL) {
108
- self.codexLiveUsage = nil;
109
- self.codexLiveUsageUpdatedAt = 0;
143
+ NSMutableDictionary *withoutExhaustion = [live mutableCopy];
144
+ [withoutExhaustion removeObjectForKey:@"exhaustedAt"];
145
+ live = withoutExhaustion;
110
146
  }
111
- return self.codexLiveUsage
112
- ? CodexUsageByApplyingLiveUsage(sessionUsage, self.codexLiveUsage)
113
- : sessionUsage;
147
+ // 存下来的实时值可能是好几个小时前的,窗口早已翻篇,合并后要再按 resets_at 过一遍。
148
+ return UsageByRemovingExpiredQuotaWindows(CodexUsageByApplyingLiveUsage(sessionUsage, live));
114
149
  }
115
150
  // 回调交给主线程:下游全是 UI(面板重排、气泡定位、系统通知)。
116
151
  - (void)publishChange {
@@ -11,3 +11,10 @@ int RestartAfterPID(pid_t pid, NSString *appPath, BOOL managed);
11
11
 
12
12
  // npm 安装日志里是否只是暂时性故障(值得自动重试一次),而不是真的装不上。
13
13
  BOOL UpdateFailureIsTransient(NSString *log);
14
+
15
+ // 从 GitHub Release 描述里摘出更新要点,给更新弹窗用。有「简体中文」标题段就只看那一段
16
+ // (Release 是中英双语的,菜单是中文),只取列表项,去掉 Markdown 标记,代码块整段跳过。
17
+ // 每条超过 maxLength 个字符截断加「…」;超过 limit 条时只返回前 limit 条并把 *truncated 置 YES。
18
+ // 没有列表项返回空数组——没写说明就不展示,不去猜正文。
19
+ NSArray<NSString *> *ReleaseNoteHighlights(NSString *body, NSUInteger limit, NSUInteger maxLength,
20
+ BOOL *truncated);