cc-pets 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,32 @@ English | [简体中文](./CHANGELOG.zh-CN.md)
5
5
  This project follows Semantic Versioning. `package.json` is the single source of
6
6
  truth for the version.
7
7
 
8
+ ## [2.0.3] - 2026-09-17
9
+
10
+ Terminal jump-back and session-liveness fixes for agents started outside the wrapper scripts.
11
+
12
+ ### Agent status
13
+
14
+ - Fall back to the kernel when `CC_PETS_TERMINAL_*` is missing: read the controlling terminal through `sysctl(KERN_PROC_PID)` and resolve the host terminal application by walking up the parent process chain, so `claude` / `codex` launched directly can still be jumped back to.
15
+ - Fix sessions without a pid file being declared dead immediately: liveness now prefers the pid file, and falls back to the activity grace window for providers that never wrote one.
16
+
17
+ ## [2.0.2] - 2026-09-11
18
+
19
+ Multi-session agent list, plus session-liveness and Codex usage-trend fixes.
20
+
21
+ ### Agent status
22
+
23
+ - Every hook status card is clickable and returns to the terminal that triggered the event; Terminal.app and iTerm2 are selected precisely by TTY, other terminals fall back to activating the owning application.
24
+ - The circular status icon lists up to eight recent online agent terminal sessions, badges the number of sessions waiting for approval, and pins those sessions to the top of the list.
25
+ - Notify once and pull the card back to the front when an agent sits in approval for 2 minutes or in thinking for 5 minutes; the session re-arms after its next event.
26
+ - The card no longer clears after 60 idle seconds while an approval is outstanding.
27
+ - Fix stale online sessions: a session is online only when its controlling terminal still matches the TTY recorded in the pid file, so orphaned Node processes no longer keep a closed window listed.
28
+
29
+ ### Quota and usage
30
+
31
+ - Fix the usage-trend column being overridden by the pending refresh state while a 7-day percentage is available, and give the rate-limited footnote its own color.
32
+ - Keep official window percentages in quota history while rate limited, so a long-limited provider still has samples to draw a trend curve from.
33
+
8
34
  ## [2.0.1] - 2026-09-07
9
35
 
10
36
  Bug fixes for quota display and panel stability.
@@ -4,6 +4,32 @@
4
4
 
5
5
  本项目遵循语义化版本号。版本号以 `package.json` 为唯一来源。
6
6
 
7
+ ## [2.0.3] - 2026-09-17
8
+
9
+ 修复未经包装脚本启动的 Agent 的终端回跳与会话存活判定。
10
+
11
+ ### Agent 状态
12
+
13
+ - 缺少 `CC_PETS_TERMINAL_*` 时回退到内核信息:通过 `sysctl(KERN_PROC_PID)` 读取控制终端,并沿父进程链向上找到宿主终端应用,直接启动的 `claude` / `codex` 也能回跳。
14
+ - 修复没有 pid 文件的会话被立即判定为离线的问题:存活判定优先使用 pid 文件,从未写过 pid 文件的 provider 回退到活动宽限窗口。
15
+
16
+ ## [2.0.2] - 2026-09-11
17
+
18
+ 多会话 Agent 列表,以及会话存活判定与 Codex 用量趋势修复。
19
+
20
+ ### Agent 状态
21
+
22
+ - 所有 Hook 状态卡都可点击并返回触发事件的终端;Terminal 和 iTerm2 按 TTY 精确选中,其他终端回退为激活所属应用。
23
+ - 圆形状态图标可展开最近 8 个在线 Agent 终端会话,并以角标显示等待审批的会话数,这些会话在列表中置顶。
24
+ - Agent 停在等待审批超过 2 分钟、或停在思考态超过 5 分钟时提醒一次,并把状态卡重新推到眼前;该会话有新事件后重新武装。
25
+ - 存在未处理的审批时,状态卡不再在闲置 60 秒后清空。
26
+ - 修复在线会话残留:只有控制终端仍与 pid 文件中记录的 TTY 一致时才算在线,关闭窗口后残留的 Node 孤儿进程不再让会话一直挂在列表里。
27
+
28
+ ### 额度与用量
29
+
30
+ - 修复 7 天百分比可用时,用量趋势列仍被「等待刷新」覆盖的问题;限流脚注使用独立配色。
31
+ - 限流期间保留官方窗口百分比写入额度历史,长期限流的 provider 仍有样本可以绘制趋势曲线。
32
+
7
33
  ## [2.0.1] - 2026-09-07
8
34
 
9
35
  额度显示与面板稳定性问题修复。
package/README.md CHANGED
@@ -23,6 +23,10 @@ sessions and Claude Code's official status line input.
23
23
  - Converts reset times to the Mac's current system time zone.
24
24
  - Responds to thinking, tool, approval, subagent, completion, and failure events.
25
25
  - Displays a redacted glass status card with the active CLI session count.
26
+ - Returns to the terminal that triggered an event when its hook status card is clicked, including sessions started without the wrapper scripts.
27
+ - Lists up to eight recent online Agent terminal sessions from the status card icon.
28
+ - Badges the status icon with the number of sessions waiting for approval and pins those sessions to the top of the list.
29
+ - Speaks up when an Agent sits in approval or thinking longer than its threshold.
26
30
  - Supports optional local quota history and macOS notifications.
27
31
  - Supports third-party CLI agents through a provider event protocol.
28
32
  - Includes editable global and per-pet speech.
@@ -67,6 +71,22 @@ npm config set allow-scripts=cc-pets --location=user
67
71
  The allowlist only affects future installs, so reinstall the package or run
68
72
  `cc-pets install` after changing it.
69
73
 
74
+ When launched through `codex-with-pet` or `claude-with-pet`, CC Pets captures the
75
+ terminal identity before the agent starts, which is the most precise source. A
76
+ session started directly — plain `codex` / `claude`, or a terminal window opened
77
+ before the shims were installed — falls back to the kernel: the controlling
78
+ terminal and the host terminal application are resolved from the process tree, so
79
+ its status cards are clickable as well. Such a session writes no pid file, so it
80
+ stays in the recent-session list while its hooks keep emitting events and leaves
81
+ the list after 60 idle seconds.
82
+
83
+ Every hook status card is clickable. The circular status icon lists up to eight
84
+ recent online Agent terminal sessions. Terminal.app and iTerm2 are selected
85
+ precisely by TTY. Without an editor extension, VS Code, JetBrains IDEs, Warp,
86
+ WezTerm, and Ghostty fall back to activating the owning application; selection of
87
+ an internal tab is left to that application. macOS may request Automation
88
+ permission on the first Terminal.app or iTerm2 jump.
89
+
70
90
  ### Install from source
71
91
 
72
92
  ```bash
package/README.zh-CN.md CHANGED
@@ -23,9 +23,13 @@
23
23
  - 支持拖动桌宠位置,右键刷新用量、检查更新或退出
24
24
  - 响应 Codex 与 Claude Code Agent 的思考、工具调用、审批、子 Agent、完成和失败状态
25
25
  - 在桌宠旁显示脱敏后的玻璃 Agent 状态卡片,可展开、折叠并显示活跃 CLI 会话数
26
+ - 点击任意 Hook 状态卡,可返回触发该事件的终端;直接启动、没走包装脚本的会话同样可以回跳
27
+ - 点击状态卡右侧圆形图标,可从最近 8 个在线 Agent 终端会话中选择并回跳
28
+ - 圆形图标右上角以角标显示正在等待审批的会话数,这些会话在会话列表中置顶
29
+ - Agent 停在等待审批或思考态超过阈值时主动提醒,并把状态卡重新推到眼前
26
30
  - 支持第三方 CLI Agent 通过统一 Provider 事件协议接入动画和状态
27
31
  - 可选记录最近 7 天的本地额度历史,并在额度卡片中显示趋势
28
- - 可分别启用任务完成、失败和等待审批的 macOS 系统通知
32
+ - 可分别启用任务完成、失败、等待审批和响应超时的 macOS 系统通知
29
33
  - 内置一个原创素材,更多桌宠可从兼容 PetDex 的素材源按需下载到本机
30
34
  - 使用原生 AppKit,运行时不依赖 Electron
31
35
 
@@ -55,6 +59,17 @@ Claude Code Hook 会合并到 `~/.claude/settings.json`,现有的 `env`、`mod
55
59
  通过 npm 安装或升级时会自动重新构建应用、安装或更新两套 Hooks,并配置 shell 集成;如果旧版桌宠正在运行,
56
60
  安装器会自动重启桌宠,使新版本生效。`cc-pets install` 用于手动修复或重新初始化。
57
61
 
62
+ 通过 `codex-with-pet` / `claude-with-pet` 启动时,包装脚本会在 Agent 启动前记录终端身份,
63
+ 这是最精确的来源。直接运行 `codex` / `claude`、或终端窗口早于 shim 安装就已打开的会话,
64
+ 会回退到内核信息:从进程树解析控制终端和承载终端的应用,这些会话的状态卡同样可以点击回跳。
65
+ 这类会话没有 pid 文件,只要 Hook 还在持续发事件就会留在最近会话列表里,闲置 60 秒后移出列表。
66
+
67
+ 所有 Hook 状态卡都可以点击;右侧圆形状态图标会展开最近 8 个在线 Agent 终端会话。
68
+ macOS Terminal 和 iTerm2 会按 TTY 精确选中对应标签页或 Session。VS Code、
69
+ JetBrains IDE、Warp、WezTerm、Ghostty 等在不安装扩展的模式下仅激活对应应用;应用
70
+ 内部标签页是否恢复由应用自身决定。首次回跳 Terminal 或 iTerm2 时,macOS 可能要求
71
+ 允许 CC Pets 控制该终端应用。
72
+
58
73
  ### 鼠标互动
59
74
 
60
75
  | 操作 | 桌宠反馈 |
@@ -106,7 +121,8 @@ Agent 状态动画会优先播放。
106
121
  右键菜单中的“记录本地额度历史”默认关闭。启用后只在本机
107
122
  `~/Library/Application Support/CC Pets/quota-history.json` 保存最近 7 天的数据,
108
123
  每 15 分钟最多记录一次。系统通知也默认关闭,可在“系统通知”子菜单中分别启用任务完成、
109
- 任务失败和等待审批通知。
124
+ 任务失败、等待审批和响应超时通知。最后一项在 Agent 停在等待审批超过 2 分钟、
125
+ 或停在思考态超过 5 分钟时提醒一次;该会话有新事件后重新武装,下次卡住会再提醒。
110
126
 
111
127
  Agent 状态卡片会根据屏幕剩余空间自动显示在桌宠上方或下方。点击桌宠旁的圆形箭头可以
112
128
  折叠卡片;折叠后圆钮会显示当前活跃的 Codex/Claude CLI 会话数,点击后重新展开。卡片只展示
@@ -22,5 +22,7 @@
22
22
  <true/>
23
23
  <key>NSHighResolutionCapable</key>
24
24
  <true/>
25
+ <key>NSAppleEventsUsageDescription</key>
26
+ <string>用于在点击 Agent 状态气泡时返回对应的终端标签页。</string>
25
27
  </dict>
26
28
  </plist>
@@ -34,19 +34,31 @@
34
34
  @property NSTextField *statusTitleLabel;
35
35
  @property NSTextField *statusDetailLabel;
36
36
  @property NSButton *statusIconButton;
37
+ @property NSButton *statusClickButton;
38
+ // 圆形状态图标右上角的待审批角标。状态卡正文永远跟着最新事件走,角标负责让
39
+ // "还有几个会话在等你确认"始终留在视线里。
40
+ @property NSView *approvalBadgeView;
37
41
  @property BOOL statusBubbleExpanded;
38
42
  @property BOOL statusBubbleAbove;
39
43
  @property BOOL hasAgentStatus;
40
44
  @property NSInteger liveClientCount;
41
45
  @property NSString *lastStatusState;
42
46
  @property NSString *lastStatusProvider;
47
+ @property NSDictionary *lastTerminalFocusTarget;
43
48
  @property NSTimeInterval lastStatusTimestamp;
44
49
  @property NSSet<NSString *> *liveClientProviders;
50
+ // 包装脚本仍存活的精确 Agent 会话,键为 provider + TTY。
51
+ @property NSSet<NSString *> *liveAgentSessionKeys;
45
52
  // 每个 provider 最近一次事件的时间。不经包装脚本启动的客户端没有 pid 文件,
46
53
  // 只能靠"最近还在发事件"证明自己活着。
47
54
  @property NSMutableDictionary<NSString *, NSNumber *> *providerActivityAt;
48
55
  @property BOOL hasUnlabeledClient;
49
56
  @property NSMutableDictionary<NSString *, NSDictionary *> *pendingApprovalRecords;
57
+ // 按终端会话保存最后一条 Hook 状态,供状态图标展开最近多会话列表。
58
+ @property NSMutableDictionary<NSString *, NSDictionary *> *agentSessionRecords;
59
+ // 已经就"卡住"提醒过的会话,元素是会话键 + 该会话当时的时间戳。会话一有新事件
60
+ // 时间戳就变,旧元素随之失效,于是下一次卡住还会再提醒一次。
61
+ @property NSMutableSet<NSString *> *stallNotifiedSessionKeys;
50
62
  @property QuotaDashboardView *quotaView;
51
63
  @property BOOL managedByCLI;
52
64
  @property BOOL pocketHovering;
@@ -7,6 +7,7 @@
7
7
  #import "CCPetsPhrases.h"
8
8
  #import "CCPetsPhrasesEditor.h"
9
9
  #import "CCPetsUsage.h"
10
+ #import "CCPetsTerminalFocus.h"
10
11
  #import "MenuToggleSwitch.h"
11
12
  #import <UserNotifications/UserNotifications.h>
12
13
  #import <signal.h>
@@ -14,13 +15,68 @@
14
15
  #import <fcntl.h>
15
16
  #import <unistd.h>
16
17
  #import <errno.h>
18
+ #import <sys/sysctl.h>
19
+ #import <stdlib.h>
17
20
 
18
21
  static const NSTimeInterval PendingApprovalTTL = 24 * 60 * 60;
19
22
  static const NSUInteger PendingApprovalLimit = 100;
23
+ static const NSUInteger AgentSessionRecordLimit = 20;
24
+ static const NSUInteger AgentSessionMenuLimit = 8;
25
+ static const CGFloat PetApprovalBadgeSize = 17.0;
20
26
  static const unsigned long long UpdateLogSizeLimit = 1024 * 1024;
21
27
  static NSString *const PetInteractionPhrasesV1MigratedKey =
22
28
  @"CCPetsInteractionPhrasesV1Migrated";
23
29
 
30
+ @interface CCPetsStatusClickButton : NSButton
31
+ @end
32
+
33
+ @implementation CCPetsStatusClickButton
34
+ - (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
35
+ - (void)resetCursorRects {
36
+ [super resetCursorRects];
37
+ [self addCursorRect:self.bounds cursor:NSCursor.pointingHandCursor];
38
+ }
39
+ @end
40
+
41
+ // 待审批角标。等审批的会话按定义是停住不动的,它的时间戳只会越来越旧——状态卡
42
+ // 正文永远显示最新事件,会话列表又按时间倒序,两边都会把最该处理的那条推到看
43
+ // 不见的地方。角标把这个数字单独拎出来常驻。
44
+ @interface CCPetsApprovalBadgeView : NSView
45
+ @property(nonatomic) NSUInteger count;
46
+ @end
47
+
48
+ @implementation CCPetsApprovalBadgeView
49
+ - (void)setCount:(NSUInteger)count {
50
+ if (_count == count) return;
51
+ _count = count;
52
+ self.hidden = count == 0;
53
+ self.needsDisplay = YES;
54
+ }
55
+ // 角标压在圆形状态图标的右上角,但不能把那颗按钮的点击吃掉。
56
+ - (NSView *)hitTest:(NSPoint)point { return nil; }
57
+ - (void)drawRect:(NSRect)dirtyRect {
58
+ if (self.count == 0) return;
59
+ // 描边是给玻璃卡片准备的:审批色和卡片背景都偏亮,没有这圈白边角标会糊在一起。
60
+ NSRect circle = NSInsetRect(self.bounds, 1.0, 1.0);
61
+ NSBezierPath *fill = [NSBezierPath bezierPathWithOvalInRect:circle];
62
+ [[NSColor colorWithRed:0.86 green:0.24 blue:0.24 alpha:1] setFill];
63
+ [fill fill];
64
+ fill.lineWidth = 1.5;
65
+ [[NSColor colorWithWhite:1 alpha:0.92] setStroke];
66
+ [fill stroke];
67
+ BOOL overflow = self.count > 9;
68
+ NSString *text = overflow ? @"9+" : @(self.count).stringValue;
69
+ NSDictionary *attributes = @{
70
+ NSFontAttributeName: [NSFont systemFontOfSize:overflow ? 8.5 : 10
71
+ weight:NSFontWeightBold],
72
+ NSForegroundColorAttributeName: NSColor.whiteColor
73
+ };
74
+ NSSize size = [text sizeWithAttributes:attributes];
75
+ [text drawAtPoint:NSMakePoint(NSMidX(self.bounds) - size.width / 2.0,
76
+ NSMidY(self.bounds) - size.height / 2.0) withAttributes:attributes];
77
+ }
78
+ @end
79
+
24
80
  static void TrimUpdateLog(NSString *path) {
25
81
  NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
26
82
  if (!handle) return;
@@ -347,6 +403,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
347
403
  if (tag == 1) return NotificationCompletionKey;
348
404
  if (tag == 2) return NotificationFailureKey;
349
405
  if (tag == 3) return NotificationApprovalKey;
406
+ if (tag == 4) return NotificationStallKey;
350
407
  return nil;
351
408
  }
352
409
  - (void)toggleSpeech:(NSButton *)sender {
@@ -573,10 +630,39 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
573
630
  [self hideAgentStatus];
574
631
  }
575
632
  - (void)hideAgentStatus {
633
+ // 卡在审批的会话不该跟着沉默一起消失。60 秒没有新事件时,气泡不清场,而是回落
634
+ // 到最近那条审批:这样"有人在等你确认"始终有个落点,点卡片就能跳回那个终端,
635
+ // 角标也不会随面板一起被收走。
636
+ //
637
+ // 这不是把旧的"审批全局优先"逻辑搬回来——那一版在事件流里拦截,一个未处理的
638
+ // 审批会把其他 Agent 的所有 Hook 全挡住。这里只在完全没有新事件时才接管,任何
639
+ // 一条新事件都照常刷新正文。
640
+ NSArray<NSDictionary *> *pending = [self pendingApprovalSessionRecords];
641
+ if (self.hasAgentStatus && pending.count > 0) {
642
+ [self performSelector:@selector(hideAgentStatus) withObject:nil
643
+ afterDelay:AgentStatusInactivityInterval];
644
+ [self presentPendingApprovalRecord:pending.firstObject];
645
+ return;
646
+ }
576
647
  [NSObject cancelPreviousPerformRequestsWithTarget:self
577
648
  selector:@selector(enterIdleStatus) object:nil];
578
649
  [self.statusPanel orderOut:nil];
579
650
  self.hasAgentStatus = NO;
651
+ [self refreshApprovalBadge];
652
+ }
653
+ // 只改卡片内容和回跳目标,不走 displayAgentRecord:那条路会连带播动画、说一句话、
654
+ // 发一次通知,而这里是"气泡闲下来后回落",重复表演反而吵。
655
+ - (void)presentPendingApprovalRecord:(NSDictionary *)record {
656
+ if (record.count == 0) return;
657
+ NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
658
+ ? record[@"terminal"] : nil;
659
+ if (terminal.count > 0) self.lastTerminalFocusTarget = terminal;
660
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
661
+ NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
662
+ if ([self.lastStatusState isEqualToString:@"approval"] &&
663
+ [self.lastStatusProvider isEqualToString:provider]) return;
664
+ [self applyStatusPresentationForState:@"approval"
665
+ provider:provider.length > 0 ? provider : @"Agent" tool:tool];
580
666
  }
581
667
  // 勾选 = 显示气泡。没有 agent 状态时也允许改,这样用户可以提前设好偏好,
582
668
  // 而不必等下一次会话开始。
@@ -621,6 +707,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
621
707
  self.statusIconButton.contentTintColor = [stateColor blendedColorWithFraction:0.18
622
708
  ofColor:NSColor.blackColor] ?: stateColor;
623
709
  [self resizeStatusCardToFitText];
710
+ [self layoutApprovalBadge];
624
711
  [self positionAgentStatus];
625
712
  if (self.statusBubbleExpanded) {
626
713
  [self.statusPanel orderFrontRegardless];
@@ -651,6 +738,10 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
651
738
  if (self.hasAgentStatus && [provider isEqualToString:self.lastStatusProvider] &&
652
739
  [self isTrailingRecord:record afterState:self.lastStatusState]) return;
653
740
 
741
+ NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
742
+ ? record[@"terminal"] : nil;
743
+ self.lastTerminalFocusTarget = terminal.count > 0 ? terminal : nil;
744
+
654
745
  [NSObject cancelPreviousPerformRequestsWithTarget:self
655
746
  selector:@selector(hideAgentStatus) object:nil];
656
747
  [NSObject cancelPreviousPerformRequestsWithTarget:self
@@ -700,15 +791,6 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
700
791
  [self.pendingApprovalRecords removeObjectForKey:key];
701
792
  }
702
793
  }
703
- - (NSDictionary *)latestPendingApprovalRecord {
704
- NSDictionary *latest = nil;
705
- for (NSDictionary *record in self.pendingApprovalRecords.allValues) {
706
- if (!latest || [record[@"timestamp"] doubleValue] > [latest[@"timestamp"] doubleValue]) {
707
- latest = record;
708
- }
709
- }
710
- return latest;
711
- }
712
794
  - (void)displayAgentRecord:(NSDictionary *)record notify:(BOOL)shouldNotify {
713
795
  NSString *event = [record[@"event"] isKindOfClass:NSString.class] ? record[@"event"] : @"";
714
796
  NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
@@ -722,6 +804,246 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
722
804
  // 的 recentOnly + 5 秒 cutoff 挡住,再加上预算制和冷却,最坏也只多说一句。
723
805
  [self considerSpeechForRecord:record];
724
806
  }
807
+ - (NSString *)agentSessionKeyForRecord:(NSDictionary *)record {
808
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
809
+ NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
810
+ ? record[@"terminal"] : nil;
811
+ NSString *tty = SanitizedShortString(terminal[@"tty"], 64);
812
+ NSString *bundleID = SanitizedShortString(terminal[@"bundleID"], 128);
813
+ if (tty.length > 0) {
814
+ return [NSString stringWithFormat:@"%@|%@|%@", provider, bundleID, tty];
815
+ }
816
+ NSString *session = SanitizedShortString(record[@"session"], 128);
817
+ if (session.length > 0) return [NSString stringWithFormat:@"%@|%@", provider, session];
818
+ return terminal.count > 0 ? [NSString stringWithFormat:@"%@|%@", provider, bundleID] : nil;
819
+ }
820
+ - (NSString *)onlineAgentSessionKeyForProvider:(NSString *)provider tty:(NSString *)tty {
821
+ provider = SanitizedShortString(provider, 32);
822
+ tty = SanitizedShortString(tty.lastPathComponent, 64);
823
+ if (provider.length == 0 || tty.length == 0) return nil;
824
+ return [NSString stringWithFormat:@"%@|%@", provider, tty];
825
+ }
826
+ - (NSString *)onlineAgentSessionKeyForRecord:(NSDictionary *)record {
827
+ NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
828
+ ? record[@"terminal"] : nil;
829
+ return [self onlineAgentSessionKeyForProvider:record[@"provider"] tty:terminal[@"tty"]];
830
+ }
831
+ // 在线判定优先用包装脚本写出的 pid 文件:它给出精确的退出信号,会话一关列表就更新。
832
+ // 但直接跑 claude / codex(或终端窗口早于 shim 安装就已打开)的会话根本没有 pid 文件,
833
+ // 只按 pid 文件判定会把它们当场判死,列表里永远看不到——哪怕它们的 Hook 正在正常发事件。
834
+ // 这类会话退回活跃度宽限:最近一次事件在静默窗口内就算在线。某个 provider 一旦出现过
835
+ // pid 文件,说明包装脚本对它生效,继续按精确信号判定,不被宽限盖住。
836
+ - (BOOL)isAgentSessionRecordLive:(NSDictionary *)record {
837
+ NSString *onlineKey = [self onlineAgentSessionKeyForRecord:record];
838
+ if (onlineKey.length > 0 && [self.liveAgentSessionKeys containsObject:onlineKey]) return YES;
839
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
840
+ if (provider.length > 0 && [self.liveClientProviders containsObject:provider]) return NO;
841
+ return NSDate.date.timeIntervalSince1970 - [record[@"timestamp"] doubleValue]
842
+ < AgentStatusInactivityInterval;
843
+ }
844
+ - (void)pruneOfflineAgentSessionRecords {
845
+ for (NSString *key in self.agentSessionRecords.allKeys) {
846
+ if (![self isAgentSessionRecordLive:self.agentSessionRecords[key]]) {
847
+ [self.agentSessionRecords removeObjectForKey:key];
848
+ }
849
+ }
850
+ }
851
+ - (void)trackAgentSessionRecord:(NSDictionary *)record {
852
+ NSString *key = [self agentSessionKeyForRecord:record];
853
+ if (key.length == 0) return;
854
+ if (!self.agentSessionRecords) self.agentSessionRecords = [NSMutableDictionary dictionary];
855
+ self.agentSessionRecords[key] = record;
856
+ if (self.agentSessionRecords.count <= AgentSessionRecordLimit) return;
857
+ NSArray<NSDictionary *> *oldestFirst = [self.agentSessionRecords.allValues
858
+ sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
859
+ return [left[@"timestamp"] compare:right[@"timestamp"]];
860
+ }];
861
+ NSUInteger removeCount = oldestFirst.count - AgentSessionRecordLimit;
862
+ for (NSUInteger index = 0; index < removeCount; index++) {
863
+ NSString *oldKey = [self agentSessionKeyForRecord:oldestFirst[index]];
864
+ if (oldKey) [self.agentSessionRecords removeObjectForKey:oldKey];
865
+ }
866
+ }
867
+ - (BOOL)isApprovalSessionRecord:(NSDictionary *)record {
868
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
869
+ return [state isEqualToString:@"approval"];
870
+ }
871
+ // 卡在审批的在线会话,最近的排前面。角标计数和会话列表置顶共用这一份,两处数字
872
+ // 才不会打架。判据是"该会话的最后一条事件是审批"——审批一旦被处理,后续事件会
873
+ // 把这条记录顶掉,会话自然退出这个集合,不需要额外的解除信号。
874
+ - (NSArray<NSDictionary *> *)pendingApprovalSessionRecords {
875
+ [self pruneOfflineAgentSessionRecords];
876
+ NSMutableArray<NSDictionary *> *pending = [NSMutableArray array];
877
+ for (NSDictionary *record in self.agentSessionRecords.allValues) {
878
+ if ([self isApprovalSessionRecord:record]) [pending addObject:record];
879
+ }
880
+ [pending sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
881
+ return [right[@"timestamp"] compare:left[@"timestamp"]];
882
+ }];
883
+ return pending;
884
+ }
885
+ - (NSTimeInterval)stallIntervalForState:(NSString *)state {
886
+ if ([state isEqualToString:@"approval"]) return AgentApprovalStallInterval;
887
+ if ([state isEqualToString:@"thinking"]) return AgentThinkingStallInterval;
888
+ return 0;
889
+ }
890
+ // 会话停在同一个状态太久就提醒一次。去重键带上该会话当时的时间戳:会话一有新
891
+ // 事件,时间戳变了,旧键自然失效,于是下一次卡住还会再提醒。每轮用当前有效键
892
+ // 求交集,退出的会话不会在集合里留垃圾。
893
+ - (void)checkStalledAgentSessions {
894
+ if (self.agentSessionRecords.count == 0) {
895
+ [self.stallNotifiedSessionKeys removeAllObjects];
896
+ return;
897
+ }
898
+ [self pruneOfflineAgentSessionRecords];
899
+ if (!self.stallNotifiedSessionKeys) self.stallNotifiedSessionKeys = [NSMutableSet set];
900
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
901
+ BOOL shouldNotify = [NSUserDefaults.standardUserDefaults boolForKey:NotificationStallKey];
902
+ NSMutableSet<NSString *> *valid = [NSMutableSet set];
903
+ NSDictionary *stalled = nil;
904
+ for (NSString *key in self.agentSessionRecords.allKeys) {
905
+ NSDictionary *record = self.agentSessionRecords[key];
906
+ NSTimeInterval timestamp = [record[@"timestamp"] doubleValue];
907
+ NSString *stamp = [NSString stringWithFormat:@"%@|%.0f", key, timestamp];
908
+ [valid addObject:stamp];
909
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
910
+ NSTimeInterval limit = [self stallIntervalForState:state];
911
+ if (limit <= 0 || now - timestamp < limit) continue;
912
+ if ([self.stallNotifiedSessionKeys containsObject:stamp]) continue;
913
+ [self.stallNotifiedSessionKeys addObject:stamp];
914
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
915
+ if (provider.length == 0) provider = @"Agent";
916
+ if (shouldNotify) {
917
+ NSInteger minutes = (NSInteger)((now - timestamp) / 60.0);
918
+ [self sendNotificationWithTitle:
919
+ [state isEqualToString:@"approval"] ? @"审批仍在等待" : @"Agent 长时间无响应"
920
+ body:[NSString stringWithFormat:@"%@ 已%@ %ld 分钟。",
921
+ provider, [self statusTextForState:state tool:record[@"tool"]], (long)minutes]];
922
+ }
923
+ // 多个会话同时卡住时只把最旧的那条顶到气泡上:它等得最久。
924
+ if (!stalled || [record[@"timestamp"] doubleValue] < [stalled[@"timestamp"] doubleValue]) {
925
+ stalled = record;
926
+ }
927
+ }
928
+ [self.stallNotifiedSessionKeys intersectSet:valid];
929
+ if (!stalled) return;
930
+ NSString *event = [stalled[@"event"] isKindOfClass:NSString.class] ? stalled[@"event"] : @"";
931
+ NSString *tool = [stalled[@"tool"] isKindOfClass:NSString.class] ? stalled[@"tool"] : @"";
932
+ [self.petView handleAgentEvent:event tool:tool failed:NO];
933
+ [self presentStalledRecord:stalled];
934
+ }
935
+ // 卡住提醒要把气泡重新推到眼前,所以这里不走 presentPendingApprovalRecord 那条
936
+ // 带早退的回落路径——面板此刻很可能已经因为长时间沉默被收走了,必须强制重现。
937
+ - (void)presentStalledRecord:(NSDictionary *)record {
938
+ NSDictionary *terminal = [record[@"terminal"] isKindOfClass:NSDictionary.class]
939
+ ? record[@"terminal"] : nil;
940
+ if (terminal.count > 0) self.lastTerminalFocusTarget = terminal;
941
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
942
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
943
+ self.hasAgentStatus = YES;
944
+ [NSObject cancelPreviousPerformRequestsWithTarget:self
945
+ selector:@selector(hideAgentStatus) object:nil];
946
+ [self applyStatusPresentationForState:state
947
+ provider:provider.length > 0 ? provider : @"Agent"
948
+ tool:[record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @""];
949
+ [self.panel orderFrontRegardless];
950
+ [self performSelector:@selector(hideAgentStatus) withObject:nil
951
+ afterDelay:AgentStatusInactivityInterval];
952
+ }
953
+ - (void)layoutApprovalBadge {
954
+ if (!self.approvalBadgeView) return;
955
+ // statusIconButton 在玻璃卡片内,角标在卡片外层,差一个 6 点的卡片边距。
956
+ // 再各让出 4 点压到图标身上,看起来才是"贴在图标角上"而不是浮在旁边。
957
+ NSRect icon = self.statusIconButton.frame;
958
+ self.approvalBadgeView.frame = NSMakeRect(
959
+ 6 + NSMaxX(icon) - PetApprovalBadgeSize + 4,
960
+ 6 + NSMaxY(icon) - PetApprovalBadgeSize + 4,
961
+ PetApprovalBadgeSize, PetApprovalBadgeSize);
962
+ }
963
+ - (void)refreshApprovalBadge {
964
+ CCPetsApprovalBadgeView *badge = (CCPetsApprovalBadgeView *)self.approvalBadgeView;
965
+ if (!badge) return;
966
+ badge.count = [self pendingApprovalSessionRecords].count;
967
+ [self layoutApprovalBadge];
968
+ }
969
+ // 等审批的排最前面。纯按时间倒序会把它们推到最底下——它们的时间戳按定义只会
970
+ // 越来越旧,而它们恰恰是唯一需要用户动手的那几条。
971
+ - (NSArray<NSDictionary *> *)recentAgentSessionRecords {
972
+ [self pruneOfflineAgentSessionRecords];
973
+ NSArray<NSDictionary *> *records = [self.agentSessionRecords.allValues
974
+ sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
975
+ BOOL leftApproval = [self isApprovalSessionRecord:left];
976
+ BOOL rightApproval = [self isApprovalSessionRecord:right];
977
+ if (leftApproval != rightApproval) return leftApproval ? NSOrderedAscending : NSOrderedDescending;
978
+ return [right[@"timestamp"] compare:left[@"timestamp"]];
979
+ }];
980
+ if (records.count <= AgentSessionMenuLimit) return records;
981
+ return [records subarrayWithRange:NSMakeRange(0, AgentSessionMenuLimit)];
982
+ }
983
+ - (NSString *)terminalNameForTarget:(NSDictionary *)target {
984
+ NSString *program = SanitizedShortString(target[@"program"], 64);
985
+ NSString *lower = program.lowercaseString;
986
+ if ([lower isEqualToString:@"apple_terminal"]) return @"Terminal";
987
+ if ([lower containsString:@"iterm"]) return @"iTerm2";
988
+ if ([lower isEqualToString:@"vscode"]) return @"VS Code";
989
+ if ([lower containsString:@"jetbrains"]) return @"JetBrains";
990
+ if ([lower containsString:@"ghostty"]) return @"Ghostty";
991
+ if ([lower containsString:@"warp"]) return @"Warp";
992
+ if ([lower containsString:@"wezterm"]) return @"WezTerm";
993
+ if (program.length > 0) return program;
994
+ NSString *bundleID = SanitizedShortString(target[@"bundleID"], 128);
995
+ return bundleID.length > 0 ? bundleID : @"Terminal";
996
+ }
997
+ - (void)focusAgentSessionRecord:(NSMenuItem *)sender {
998
+ NSDictionary *record = [sender.representedObject isKindOfClass:NSDictionary.class]
999
+ ? sender.representedObject : nil;
1000
+ NSDictionary *target = [record[@"terminal"] isKindOfClass:NSDictionary.class]
1001
+ ? record[@"terminal"] : nil;
1002
+ if (target.count > 0) ActivateTerminalFocusTarget(target);
1003
+ }
1004
+ - (void)showAgentSessionsMenu:(NSButton *)sender {
1005
+ NSArray<NSDictionary *> *records = [self recentAgentSessionRecords];
1006
+ if (records.count == 0) return;
1007
+ NSMenu *menu = [[NSMenu alloc] initWithTitle:@"最近 Agent 会话"];
1008
+ NSMenuItem *heading = [menu addItemWithTitle:@"最近 Agent 会话" action:nil keyEquivalent:@""];
1009
+ heading.enabled = NO;
1010
+ [menu addItem:NSMenuItem.separatorItem];
1011
+ BOOL separatedApprovals = NO;
1012
+ for (NSDictionary *record in records) {
1013
+ NSString *provider = SanitizedShortString(record[@"provider"], 32);
1014
+ NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
1015
+ NSString *tool = [record[@"tool"] isKindOfClass:NSString.class] ? record[@"tool"] : @"";
1016
+ NSDictionary *target = record[@"terminal"];
1017
+ BOOL approval = [self isApprovalSessionRecord:record];
1018
+ // 置顶的审批组和其余会话之间划一道线,免得两段看起来像同一个时间序列。
1019
+ if (!approval && !separatedApprovals && record != records.firstObject) {
1020
+ [menu addItem:NSMenuItem.separatorItem];
1021
+ separatedApprovals = YES;
1022
+ }
1023
+ NSDate *date = [NSDate dateWithTimeIntervalSince1970:[record[@"timestamp"] doubleValue]];
1024
+ NSString *time = [NSDateFormatter localizedStringFromDate:date
1025
+ dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle];
1026
+ NSString *title = [NSString stringWithFormat:@"%@%@ · %@ · %@ · %@",
1027
+ approval ? @"⚠️ " : @"",
1028
+ provider.length > 0 ? provider : @"Agent",
1029
+ [self statusTextForState:state tool:tool], [self terminalNameForTarget:target], time];
1030
+ NSMenuItem *item = [menu addItemWithTitle:title
1031
+ action:@selector(focusAgentSessionRecord:) keyEquivalent:@""];
1032
+ item.target = self;
1033
+ item.representedObject = record;
1034
+ if ([target isEqual:self.lastTerminalFocusTarget]) item.state = NSControlStateValueOn;
1035
+ }
1036
+ [menu popUpMenuPositioningItem:nil
1037
+ atLocation:NSMakePoint(0, NSHeight(sender.bounds) + 4) inView:sender];
1038
+ }
1039
+ - (BOOL)focusLatestAgentTerminal {
1040
+ // 只有 Hook 状态气泡上的透明按钮会调用这里;桌宠本体继续负责原有互动。
1041
+ if (!self.hasAgentStatus || self.lastTerminalFocusTarget.count == 0) return NO;
1042
+ return ActivateTerminalFocusTarget(self.lastTerminalFocusTarget);
1043
+ }
1044
+ - (void)focusLatestAgentTerminal:(id)sender {
1045
+ [self focusLatestAgentTerminal];
1046
+ }
725
1047
  - (NSDictionary *)petManifestInDirectory:(NSString *)directory {
726
1048
  NSString *jsonPath = [directory stringByAppendingPathComponent:@"pet.json"];
727
1049
  NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
@@ -1022,7 +1344,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
1022
1344
  self.statusPanel.opaque = NO;
1023
1345
  self.statusPanel.backgroundColor = NSColor.clearColor;
1024
1346
  self.statusPanel.hasShadow = NO;
1025
- self.statusPanel.ignoresMouseEvents = YES;
1347
+ self.statusPanel.ignoresMouseEvents = NO;
1026
1348
  self.statusPanel.level = NSFloatingWindowLevel;
1027
1349
  self.statusPanel.collectionBehavior =
1028
1350
  NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;
@@ -1076,15 +1398,37 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
1076
1398
  self.statusDetailLabel.lineBreakMode = NSLineBreakByTruncatingTail;
1077
1399
  [self.statusGlass addSubview:self.statusDetailLabel];
1078
1400
 
1079
- self.statusIconButton = [[NSButton alloc] initWithFrame:NSMakeRect(
1401
+ self.statusIconButton = [[CCPetsStatusClickButton alloc] initWithFrame:NSMakeRect(
1080
1402
  statusGlassSize.width - 48, 12, 34, 34)];
1081
1403
  self.statusIconButton.bordered = NO;
1082
1404
  self.statusIconButton.imagePosition = NSImageOnly;
1083
1405
  self.statusIconButton.wantsLayer = YES;
1084
1406
  self.statusIconButton.layer.cornerRadius = 17;
1085
1407
  self.statusIconButton.layer.masksToBounds = YES;
1408
+ self.statusIconButton.toolTip = @"查看最近 Agent 会话";
1409
+ self.statusIconButton.target = self;
1410
+ self.statusIconButton.action = @selector(showAgentSessionsMenu:);
1086
1411
  [self.statusGlass addSubview:self.statusIconButton];
1087
1412
  [statusRoot addSubview:self.statusGlass];
1413
+ CCPetsStatusClickButton *statusClick = [[CCPetsStatusClickButton alloc]
1414
+ initWithFrame:NSMakeRect(6, 6, statusGlassSize.width - 56, statusGlassSize.height)];
1415
+ statusClick.bordered = NO;
1416
+ statusClick.transparent = YES;
1417
+ statusClick.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
1418
+ statusClick.title = @"";
1419
+ statusClick.toolTip = @"返回触发此状态的 Agent 终端";
1420
+ statusClick.target = self;
1421
+ statusClick.action = @selector(focusLatestAgentTerminal:);
1422
+ self.statusClickButton = statusClick;
1423
+ [statusRoot addSubview:statusClick];
1424
+ // 角标挂在 statusRoot 而不是 statusGlass 里:玻璃卡片是 masksToBounds 的胶囊,
1425
+ // 右上角正好落在圆角外面,放进去会被裁掉一半。
1426
+ CCPetsApprovalBadgeView *badge = [[CCPetsApprovalBadgeView alloc]
1427
+ initWithFrame:NSMakeRect(0, 0, PetApprovalBadgeSize, PetApprovalBadgeSize)];
1428
+ badge.hidden = YES;
1429
+ self.approvalBadgeView = badge;
1430
+ [statusRoot addSubview:badge];
1431
+ [self layoutApprovalBadge];
1088
1432
  self.statusPanel.contentView = statusRoot;
1089
1433
 
1090
1434
  NSSize quotaSize = NSMakeSize(QuotaLogicalWidth * QuotaScale, QuotaLogicalHeight * QuotaScale);
@@ -1135,6 +1479,7 @@ static NSString *const PetSpeechFrequencyChatty = @"chatty";
1135
1479
  self.systemMonitor = [CCPetsSystemMonitor new];
1136
1480
  self.agentEventPartialLine = [NSMutableData data];
1137
1481
  self.pendingApprovalRecords = [NSMutableDictionary dictionary];
1482
+ self.stallNotifiedSessionKeys = [NSMutableSet set];
1138
1483
  self.usageMonitor.changeHandler = ^(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
1139
1484
  [weakSelf applyCodexUsage:codexUsage claudeUsage:claudeUsage];
1140
1485
  [weakSelf considerQuotaSpeech];
@@ -1699,6 +2044,7 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
1699
2044
  }
1700
2045
  self.statusIconButton.frame = NSMakeRect(glassWidth - trailing - iconWidth,
1701
2046
  (height - iconWidth) / 2.0, iconWidth, iconWidth);
2047
+ self.statusClickButton.frame = NSMakeRect(6, 6, glassWidth - 56, height);
1702
2048
  }
1703
2049
 
1704
2050
  // 独立气泡:左右各 16 内边距,没有图标。
@@ -1842,6 +2188,7 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
1842
2188
  NSDictionary *record = [NSJSONSerialization JSONObjectWithData:lineData options:0 error:nil];
1843
2189
  if (![record isKindOfClass:NSDictionary.class]) continue;
1844
2190
  if (recentOnly && [record[@"timestamp"] doubleValue] < cutoff) continue;
2191
+ [self trackAgentSessionRecord:record];
1845
2192
  NSString *event = record[@"event"];
1846
2193
  NSString *state = [record[@"state"] isKindOfClass:NSString.class] ? record[@"state"] : @"";
1847
2194
  if ([event isKindOfClass:NSString.class]) {
@@ -1850,7 +2197,6 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
1850
2197
  }
1851
2198
  [self prunePendingApprovalRecords];
1852
2199
  NSString *approvalKey = [self approvalKeyForRecord:record];
1853
- NSDictionary *previousPriority = [self latestPendingApprovalRecord];
1854
2200
  BOOL manualApproval = [state isEqualToString:@"approval"];
1855
2201
  if (manualApproval) {
1856
2202
  self.pendingApprovalRecords[approvalKey] = record;
@@ -1858,18 +2204,12 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
1858
2204
  [self.pendingApprovalRecords removeObjectForKey:approvalKey];
1859
2205
  }
1860
2206
  [self prunePendingApprovalRecords];
1861
- NSDictionary *currentPriority = [self latestPendingApprovalRecord];
1862
- if (currentPriority) {
1863
- if (manualApproval) {
1864
- [self displayAgentRecord:currentPriority notify:YES];
1865
- } else if (currentPriority != previousPriority) {
1866
- [self displayAgentRecord:currentPriority notify:NO];
1867
- }
1868
- continue;
1869
- }
2207
+ // 多会话下不能让一个未处理的审批全局挡住其他 Agent 的所有 Hook。每条事件
2208
+ // 都正常驱动气泡和动画;仍在等待的审批保留在多会话记录中供用户回跳。
1870
2209
  [self displayAgentRecord:record notify:YES];
1871
2210
  }
1872
2211
  }
2212
+ [self refreshApprovalBadge];
1873
2213
  }
1874
2214
  - (void)readNewAgentEvents {
1875
2215
  NSString *path = AgentEventPath();
@@ -1945,6 +2285,26 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
1945
2285
  self.quotaView.hasUnlabeledClient = self.hasUnlabeledClient;
1946
2286
  self.quotaView.needsDisplay = YES;
1947
2287
  }
2288
+ // 客户端是否真的还在跑。只问 kill(pid, 0) 不够:关掉终端窗口只是销毁 pty,claude /
2289
+ // codex(Node 进程)不一定跟着 SIGHUP 退出,会变成脱离控制终端的孤儿继续活着。那样
2290
+ // pid 一直存在,会话就永久挂在"在线"上,最近会话列表里那条也永远不消失。
2291
+ // 所以再看两件事:进程是否还有控制终端;以及它是不是仍然是 pid 文件里记的那个 TTY
2292
+ // (pty 会被新开的窗口复用,光看"有 tty"挡不住换了主人的情况)。
2293
+ // recordedTTY 为空是 1.0.2 及更早的老客户端,只能退回"有控制终端"这一条。
2294
+ static BOOL ClientProcessAlive(pid_t pid, NSString *recordedTTY) {
2295
+ if (pid <= 1) return NO;
2296
+ struct kinfo_proc info;
2297
+ size_t length = sizeof(info);
2298
+ int name[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2299
+ if (sysctl(name, 4, &info, &length, NULL, 0) != 0 || length == 0) return NO;
2300
+ if (info.kp_proc.p_stat == SZOMB) return NO;
2301
+ dev_t device = info.kp_eproc.e_tdev;
2302
+ if (device == NODEV) return NO;
2303
+ if (recordedTTY.length == 0) return YES;
2304
+ const char *current = devname(device, S_IFCHR);
2305
+ if (!current) return NO;
2306
+ return [recordedTTY isEqualToString:@(current).lastPathComponent];
2307
+ }
1948
2308
  - (void)refreshClientLifecycle:(id)sender {
1949
2309
  [self considerIdleSpeech];
1950
2310
  [self prunePendingApprovalRecords];
@@ -1953,23 +2313,31 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
1953
2313
  NSArray<NSString *> *entries = [NSFileManager.defaultManager contentsOfDirectoryAtPath:clientDirectory error:nil] ?: @[];
1954
2314
  NSInteger liveClients = 0;
1955
2315
  NSMutableSet<NSString *> *providers = [NSMutableSet set];
2316
+ NSMutableSet<NSString *> *sessionKeys = [NSMutableSet set];
1956
2317
  BOOL unlabeled = NO;
1957
2318
  for (NSString *entry in entries) {
1958
2319
  pid_t pid = (pid_t)entry.intValue;
1959
- BOOL alive = pid > 1 && (kill(pid, 0) == 0 || errno == EPERM);
1960
2320
  NSString *path = [clientDirectory stringByAppendingPathComponent:entry];
1961
- if (!alive) {
2321
+ // 包装脚本会把 provider 名写进 pid 文件第一行、TTY 写进第二行。1.0.2 及更早
2322
+ // 的版本只 touch 出空文件,升级后仍在运行的老客户端读出来是空的:这类当作
2323
+ // “身份不明”,只要还有一个就不清场,避免把仍然活着的会话误判成已退出。
2324
+ NSString *contents = [NSString stringWithContentsOfFile:path
2325
+ encoding:NSUTF8StringEncoding error:nil] ?: @"";
2326
+ NSArray<NSString *> *lines = [contents componentsSeparatedByCharactersInSet:
2327
+ NSCharacterSet.newlineCharacterSet];
2328
+ NSString *label = [lines.firstObject
2329
+ stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
2330
+ NSString *tty = lines.count > 1 ? [lines[1]
2331
+ stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] : @"";
2332
+ if (!ClientProcessAlive(pid, tty)) {
1962
2333
  [NSFileManager.defaultManager removeItemAtPath:path error:nil];
1963
2334
  continue;
1964
2335
  }
1965
2336
  liveClients += 1;
1966
- // 包装脚本会把 provider 名写进 pid 文件。1.0.2 及更早的版本只 touch 出
1967
- // 空文件,升级后仍在运行的老客户端读出来是空的:这类当作“身份不明”,
1968
- // 只要还有一个就不清场,避免把仍然活着的会话误判成已退出。
1969
- NSString *label = [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]
1970
- stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
1971
2337
  if (label.length > 0 && label.length <= 32) [providers addObject:label];
1972
2338
  else unlabeled = YES;
2339
+ NSString *sessionKey = [self onlineAgentSessionKeyForProvider:label tty:tty];
2340
+ if (sessionKey.length > 0) [sessionKeys addObject:sessionKey];
1973
2341
  }
1974
2342
  // 包装脚本启动的客户端有精确的退出信号:pid 文件被回收。这一段不该被为"直接跑
1975
2343
  // claude / codex"准备的 60 秒活跃度宽限盖住,否则退出后还要挂满一分钟才转离线。
@@ -1978,7 +2346,9 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
1978
2346
  NSSet<NSString *> *previousProviders = self.liveClientProviders;
1979
2347
  self.liveClientCount = liveClients;
1980
2348
  self.liveClientProviders = providers;
2349
+ self.liveAgentSessionKeys = sessionKeys;
1981
2350
  self.hasUnlabeledClient = unlabeled;
2351
+ [self pruneOfflineAgentSessionRecords];
1982
2352
  for (NSString *provider in previousProviders) {
1983
2353
  if (![providers containsObject:provider]) {
1984
2354
  [self.providerActivityAt removeObjectForKey:provider];
@@ -1987,6 +2357,8 @@ static CGFloat PetMeasuredLabelWidth(NSTextField *label) {
1987
2357
  [self updateQuotaLiveState];
1988
2358
  [self refreshDetectedProviders];
1989
2359
  [self hideAgentStatusIfClientGone];
2360
+ [self checkStalledAgentSessions];
2361
+ [self refreshApprovalBadge];
1990
2362
  // 启动模式在应用生命周期内保持不变。手动启动的桌宠即使后来检测到
1991
2363
  // Codex/Claude 客户端,也不应被转成 CLI 托管模式并随客户端退出。
1992
2364
  if (liveClients == 0 && self.managedByCLI) [NSApp terminate:nil];
@@ -1,5 +1,6 @@
1
1
  #import "CCPetsEvents.h"
2
2
  #import "CCPetsPaths.h"
3
+ #import "CCPetsTerminalFocus.h"
3
4
  #import <sys/stat.h>
4
5
  #import <fcntl.h>
5
6
  #import <unistd.h>
@@ -196,6 +197,8 @@ int RecordHookEvent(void) {
196
197
  @"timestamp": @([NSDate.date timeIntervalSince1970])
197
198
  } mutableCopy];
198
199
  if (session.length > 0) record[@"session"] = session;
200
+ NSDictionary *terminal = TerminalFocusTargetFromEnvironment();
201
+ if (terminal.count > 0) record[@"terminal"] = terminal;
199
202
  AppendAgentEventRecord(record);
200
203
  return EXIT_SUCCESS;
201
204
  }
@@ -233,14 +236,16 @@ int RecordProviderEvent(void) {
233
236
  @"failed": @"StopFailure",
234
237
  @"notification": @"Notification"
235
238
  };
236
- NSDictionary *record = @{
239
+ NSMutableDictionary *record = [@{
237
240
  @"event": events[state],
238
241
  @"tool": tool,
239
242
  @"failed": @([state isEqualToString:@"failed"] || [state isEqualToString:@"tool_failed"]),
240
243
  @"provider": provider,
241
244
  @"state": state,
242
245
  @"timestamp": @([NSDate.date timeIntervalSince1970])
243
- };
246
+ } mutableCopy];
247
+ NSDictionary *terminal = TerminalFocusTargetFromEnvironment();
248
+ if (terminal.count > 0) record[@"terminal"] = terminal;
244
249
  if (!AppendAgentEventRecord(record)) {
245
250
  fprintf(stderr, "无法写入 Provider 事件。\n");
246
251
  return EXIT_FAILURE;
@@ -39,6 +39,8 @@ extern NSString *const HistoryEnabledKey;
39
39
  extern NSString *const NotificationCompletionKey;
40
40
  extern NSString *const NotificationFailureKey;
41
41
  extern NSString *const NotificationApprovalKey;
42
+ // Agent 卡在审批或思考态超过阈值时的提醒开关。
43
+ extern NSString *const NotificationStallKey;
42
44
  extern NSString *const StatusBubbleExpandedKey;
43
45
  extern NSString *const StatusBubblePreferenceV2Key;
44
46
  extern NSString *const ImportCodexPetsKey;
@@ -55,6 +57,8 @@ extern NSString *const DetectedProvidersKey;
55
57
  extern const NSTimeInterval AgentStatusInactivityInterval;
56
58
  extern const NSTimeInterval AgentStatusOrphanInterval;
57
59
  extern const NSTimeInterval AgentStartingGraceInterval;
60
+ extern const NSTimeInterval AgentApprovalStallInterval;
61
+ extern const NSTimeInterval AgentThinkingStallInterval;
58
62
  extern const NSTimeInterval UpdateRetryDelay;
59
63
  extern const NSTimeInterval UsageRefreshIntervalVisible;
60
64
  extern const NSTimeInterval UsageRefreshIntervalHidden;
@@ -213,6 +213,7 @@ NSString *const HistoryEnabledKey = @"CCPetsQuotaHistoryEnabled";
213
213
  NSString *const NotificationCompletionKey = @"CCPetsNotifyCompletion";
214
214
  NSString *const NotificationFailureKey = @"CCPetsNotifyFailure";
215
215
  NSString *const NotificationApprovalKey = @"CCPetsNotifyApproval";
216
+ NSString *const NotificationStallKey = @"CCPetsNotifyStall";
216
217
  NSString *const StatusBubbleExpandedKey = @"CCPetsStatusBubbleExpanded";
217
218
  NSString *const StatusBubblePreferenceV2Key = @"CCPetsStatusBubblePreferenceV2";
218
219
  NSString *const ImportCodexPetsKey = @"CCPetsImportCodexPets";
@@ -230,6 +231,11 @@ const NSTimeInterval AgentStatusOrphanInterval = 10.0;
230
231
  // "正在启动"只在会话拉起的一瞬间成立。超过这段还没有任何后续事件,说明会话已经就绪、
231
232
  // 正在等用户输入,气泡应当落到"待机中",否则启动态和空闲态看起来完全一样。
232
233
  const NSTimeInterval AgentStartingGraceInterval = 8.0;
234
+ // 审批和思考是唯二会长时间停住不动的状态:窗口切走之后没人知道 Agent 早就停在
235
+ // 那儿了。超过这两个阈值就主动提醒一次,会话有新事件后重新武装。审批是纯粹在等
236
+ // 人,给得短;思考本来就可能跑很久,给得长,免得正常的长任务被当成卡死。
237
+ const NSTimeInterval AgentApprovalStallInterval = 120.0;
238
+ const NSTimeInterval AgentThinkingStallInterval = 300.0;
233
239
  // 刚发布的版本存在 registry 传播竞态,更新失败后等这么久再自动重试一次。
234
240
  const NSTimeInterval UpdateRetryDelay = 5.0;
235
241
  // 额度变化由 FSEvents/VNODE 主动推送;定时器只保留为监听不可用时的 120 秒兜底。
@@ -24,8 +24,15 @@ static NSDictionary *HistoryProviderSample(NSDictionary *usage, NSString *usedKe
24
24
  NSNumber *fiveHour = RemainingValue(usage, @"fiveHour", usedKey);
25
25
  NSNumber *week = RemainingValue(usage, @"week", usedKey);
26
26
  // usage_limit_exceeded 没有窗口归属,既不能证明两个窗口都归零,也不能证明上次快照
27
- // 仍代表当前额度。受限期间不写历史点,等任意会话拿到更新的官方快照后再继续记录。
28
- if ([usage[@"exhaustedAt"] isKindOfClass:NSNumber.class]) {
27
+ // 仍代表当前额度。但"受限"和"没有可信百分比"是两件事:受限期间官方 rate_limits
28
+ // 照样会返回窗口百分比(见 CCPetsCodexRateLimits.m 的 LiveUsageFromRateLimitBucket,
29
+ // 受限分支之前就已经填好 fiveHour / week),那是服务端给的真实数值。一律丢掉的话,
30
+ // 长期受限的 provider 在 7 天里攒不下一个历史点,趋势曲线就只剩"当前"这一个点,
31
+ // 画不出线。所以只在快照比受限时刻更旧时才丢——判据与 CCPetsUsage.m 的
32
+ // ExhaustionStillHolds 一致:exhaustedAt < sampledAt 说明快照更新、仍然可信。
33
+ NSNumber *exhaustedAt = [usage[@"exhaustedAt"] isKindOfClass:NSNumber.class]
34
+ ? usage[@"exhaustedAt"] : nil;
35
+ if (exhaustedAt && exhaustedAt.doubleValue >= [usage[@"sampledAt"] doubleValue]) {
29
36
  fiveHour = nil;
30
37
  week = nil;
31
38
  }
@@ -0,0 +1,11 @@
1
+ #import <Cocoa/Cocoa.h>
2
+
3
+ // 包装脚本在 Agent 启动时固定下来的终端身份。Hook 子进程继承这些环境变量,
4
+ // 因此任务结束时即使用户已经切到别的应用,也不会把目标错记成当前前台窗口。
5
+ NSDictionary *TerminalFocusTargetFromEnvironment(void);
6
+
7
+ // Terminal / iTerm2 按 TTY 精确选中 tab/session;其他终端在无扩展模式下激活应用。
8
+ BOOL ActivateTerminalFocusTarget(NSDictionary *target);
9
+
10
+ // 供包装脚本在 exec Agent 之前捕获承载终端的应用。
11
+ NSString *FrontmostApplicationBundleIdentifier(void);
@@ -0,0 +1,150 @@
1
+ #import "CCPetsTerminalFocus.h"
2
+ #import "CCPetsEvents.h"
3
+ #import <sys/sysctl.h>
4
+ #import <sys/stat.h>
5
+ #import <stdlib.h>
6
+ #import <unistd.h>
7
+
8
+ static BOOL ProcessInfoForPID(pid_t pid, struct kinfo_proc *info) {
9
+ if (pid <= 0) return NO;
10
+ size_t length = sizeof(*info);
11
+ int name[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
12
+ return sysctl(name, 4, info, &length, NULL, 0) == 0 && length > 0;
13
+ }
14
+
15
+ // 包装脚本没被走到时(用户直接跑 codex / claude,或终端窗口早于 shim 安装就已打开)
16
+ // 环境里没有 CC_PETS_TERMINAL_*。记录端自己是 Agent 的子进程,控制终端就是 Agent
17
+ // 所在的那个 tty,直接问内核即可——stdin 是 JSON 管道,isatty 这类办法在这里没用。
18
+ static NSString *ControllingTerminalName(void) {
19
+ struct kinfo_proc info;
20
+ if (!ProcessInfoForPID(getpid(), &info)) return @"";
21
+ dev_t device = info.kp_eproc.e_tdev;
22
+ if (device == NODEV) return @"";
23
+ const char *tty = devname(device, S_IFCHR);
24
+ return tty ? @(tty).lastPathComponent : @"";
25
+ }
26
+
27
+ // 承载终端的应用:沿父进程链往上走,第一个能被 NSRunningApplication 认领的就是
28
+ // GUI 应用本体(Ghostty / Terminal / iTerm2 …)。不能用"当前前台应用"兜底——
29
+ // Hook 触发时用户往往已经切到别的窗口,那样会把跳转目标记错。
30
+ static NSString *HostApplicationBundleIdentifier(void) {
31
+ pid_t pid = getppid();
32
+ for (NSUInteger depth = 0; depth < 16 && pid > 1; depth++) {
33
+ NSString *bundleID = [NSRunningApplication
34
+ runningApplicationWithProcessIdentifier:pid].bundleIdentifier;
35
+ if (bundleID.length > 0) return bundleID;
36
+ struct kinfo_proc info;
37
+ if (!ProcessInfoForPID(pid, &info)) break;
38
+ pid = info.kp_eproc.e_ppid;
39
+ }
40
+ return @"";
41
+ }
42
+
43
+ static NSString *TerminalTargetValue(NSDictionary<NSString *, NSString *> *environment,
44
+ NSString *key, NSUInteger maximumLength) {
45
+ return SanitizedShortString(environment[key], maximumLength);
46
+ }
47
+
48
+ NSDictionary *TerminalFocusTargetFromEnvironment(void) {
49
+ NSDictionary<NSString *, NSString *> *environment = NSProcessInfo.processInfo.environment;
50
+ NSString *tty = environment[@"CC_PETS_TERMINAL_TTY"];
51
+ if ([tty isKindOfClass:NSString.class]) tty = tty.lastPathComponent;
52
+ tty = SanitizedShortString(tty, 64);
53
+ NSString *program = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_PROGRAM", 64);
54
+ NSString *session = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_SESSION", 128);
55
+ NSString *bundleID = TerminalTargetValue(environment, @"CC_PETS_TERMINAL_BUNDLE_ID", 128);
56
+ if (tty.length == 0) tty = SanitizedShortString(ControllingTerminalName(), 64);
57
+ if (bundleID.length == 0) {
58
+ bundleID = SanitizedShortString(HostApplicationBundleIdentifier(), 128);
59
+ }
60
+ if (tty.length == 0 && program.length == 0 && session.length == 0 && bundleID.length == 0) {
61
+ return @{};
62
+ }
63
+ NSMutableDictionary *target = [NSMutableDictionary dictionary];
64
+ if (tty.length > 0) target[@"tty"] = tty;
65
+ if (program.length > 0) target[@"program"] = program;
66
+ if (session.length > 0) target[@"session"] = session;
67
+ if (bundleID.length > 0) target[@"bundleID"] = bundleID;
68
+ return target;
69
+ }
70
+
71
+ NSString *FrontmostApplicationBundleIdentifier(void) {
72
+ return NSWorkspace.sharedWorkspace.frontmostApplication.bundleIdentifier ?: @"";
73
+ }
74
+
75
+ static BOOL RunTerminalSelectionScript(NSString *bundleID, NSString *ttyName) {
76
+ if (ttyName.length == 0) return NO;
77
+ NSString *tty = [@"/dev/" stringByAppendingString:ttyName.lastPathComponent];
78
+ NSString *source = nil;
79
+ if ([bundleID isEqualToString:@"com.apple.Terminal"]) {
80
+ source = [NSString stringWithFormat:
81
+ @"tell application \"Terminal\"\n"
82
+ "repeat with terminalWindow in windows\n"
83
+ "repeat with terminalTab in tabs of terminalWindow\n"
84
+ "if (tty of terminalTab) is \"%@\" then\n"
85
+ "set selected tab of terminalWindow to terminalTab\n"
86
+ "set index of terminalWindow to 1\n"
87
+ "activate\n"
88
+ "return true\n"
89
+ "end if\n"
90
+ "end repeat\n"
91
+ "end repeat\n"
92
+ "end tell\n"
93
+ "return false", tty];
94
+ } else if ([bundleID isEqualToString:@"com.googlecode.iterm2"]) {
95
+ source = [NSString stringWithFormat:
96
+ @"tell application \"iTerm2\"\n"
97
+ "repeat with terminalWindow in windows\n"
98
+ "repeat with terminalTab in tabs of terminalWindow\n"
99
+ "repeat with terminalSession in sessions of terminalTab\n"
100
+ "if (tty of terminalSession) is \"%@\" then\n"
101
+ "select terminalSession\n"
102
+ "select terminalWindow\n"
103
+ "activate\n"
104
+ "return true\n"
105
+ "end if\n"
106
+ "end repeat\n"
107
+ "end repeat\n"
108
+ "end repeat\n"
109
+ "end tell\n"
110
+ "return false", tty];
111
+ }
112
+ if (!source) return NO;
113
+ NSDictionary *error = nil;
114
+ NSAppleScript *script = [[NSAppleScript alloc] initWithSource:source];
115
+ NSAppleEventDescriptor *result = [script executeAndReturnError:&error];
116
+ return result.booleanValue && error == nil;
117
+ }
118
+
119
+ static NSString *BundleIDForTerminalProgram(NSString *program) {
120
+ NSString *lower = program.lowercaseString;
121
+ if ([lower isEqualToString:@"apple_terminal"]) return @"com.apple.Terminal";
122
+ if ([lower containsString:@"iterm"]) return @"com.googlecode.iterm2";
123
+ if ([lower isEqualToString:@"vscode"]) return @"com.microsoft.VSCode";
124
+ if ([lower containsString:@"warp"]) return @"dev.warp.Warp-Stable";
125
+ if ([lower containsString:@"wezterm"]) return @"com.github.wez.wezterm";
126
+ if ([lower containsString:@"ghostty"]) return @"com.mitchellh.ghostty";
127
+ return @"";
128
+ }
129
+
130
+ BOOL ActivateTerminalFocusTarget(NSDictionary *target) {
131
+ if (![target isKindOfClass:NSDictionary.class]) return NO;
132
+ NSString *tty = SanitizedShortString(target[@"tty"], 64);
133
+ // 已知 TERM_PROGRAM 比“启动瞬间的前台应用”更可靠:VS Code Task 可能在窗口不位于
134
+ // 前台时启动 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;
145
+ #pragma clang diagnostic push
146
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
147
+ return [application activateWithOptions:
148
+ NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps];
149
+ #pragma clang diagnostic pop
150
+ }
@@ -1505,7 +1505,8 @@ typedef NS_ENUM(NSInteger, PetMicroBehaviorKind) {
1505
1505
  NSArray<NSDictionary *> *notificationOptions = @[
1506
1506
  @{@"title": @"任务完成", @"key": NotificationCompletionKey, @"tag": @1},
1507
1507
  @{@"title": @"任务失败", @"key": NotificationFailureKey, @"tag": @2},
1508
- @{@"title": @"等待审批", @"key": NotificationApprovalKey, @"tag": @3}
1508
+ @{@"title": @"等待审批", @"key": NotificationApprovalKey, @"tag": @3},
1509
+ @{@"title": @"响应超时", @"key": NotificationStallKey, @"tag": @4}
1509
1510
  ];
1510
1511
  for (NSDictionary *option in notificationOptions) {
1511
1512
  [self addPersistentSwitchToMenu:notificationMenu
@@ -758,11 +758,24 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
758
758
  ? self.codexHistory : self.claudeHistory;
759
759
  NSNumber *currentUsed = weekUsed;
760
760
  NSArray<NSDictionary *> *points = [self curvePointsFromHistory:history currentUsed:currentUsed];
761
- NSDictionary *pace = exhausted
762
- ? @{ @"label": @"待刷新", @"tip": @"等待新的官方额度快照",
761
+ // 趋势这一列算的是 7 天窗口(currentUsed 取 weekUsed)。而 exhaustedAt 来自
762
+ // rateLimitReachedType,没有窗口归属,实际撞墙的通常是 5 小时窗口——拿它一票否决
763
+ // 整列,会出现左边 7 天窗口好好显示着 45% 剩余、右边却说"等待官方额度刷新"的自相
764
+ // 矛盾。所以只有 7 天窗口自己确实没有百分比时才退回"待刷新"。
765
+ BOOL weekUnknown = exhausted && currentUsed == nil;
766
+ NSDictionary *pace = weekUnknown
767
+ ? @{ @"label": @"待刷新", @"tip": @"等待官方额度刷新",
763
768
  @"color": NSColor.systemOrangeColor }
764
769
  : [self paceStatusForQuota:week currentUsed:currentUsed color:color];
765
770
  NSColor *paceColor = pace[@"color"];
771
+ // 档位讲的是 7 天趋势,脚注讲的是此刻为什么发不出请求:受限但 7 天窗口尚有余量时
772
+ // 两者都要说清,所以脚注单独取色,不跟着档位走。
773
+ NSString *paceTip = pace[@"tip"];
774
+ NSColor *tipColor = paceColor;
775
+ if (exhausted && !weekUnknown) {
776
+ paceTip = @"官方额度受限,等待重置";
777
+ tipColor = NSColor.systemOrangeColor;
778
+ }
766
779
  NSDictionary *pillAttributes = [self textAttributesWithSize:11 color:paceColor
767
780
  weight:NSFontWeightSemibold];
768
781
  // 档位标签跟在标题后面。宽度仍按文字算:四个档位不一样长,最宽的"数据不足"到
@@ -786,8 +799,8 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
786
799
  withAttributes:[self rightAlignedTextAttributesWithSize:10 color:secondary
787
800
  weight:NSFontWeightRegular]];
788
801
  // 与左边两列的"已用 Token"同一条基线(+22),也和 API 卡的脚注行对齐。
789
- [pace[@"tip"] drawInRect:NSMakeRect(trendX, NSMinY(card) + 22, 145, 18)
790
- withAttributes:[self textAttributesWithSize:11 color:paceColor weight:NSFontWeightMedium]];
802
+ [paceTip drawInRect:NSMakeRect(trendX, NSMinY(card) + 22, 145, 18)
803
+ withAttributes:[self textAttributesWithSize:11 color:tipColor weight:NSFontWeightMedium]];
791
804
  }
792
805
  - (void)drawRect:(NSRect)dirtyRect {
793
806
  [NSGraphicsContext saveGraphicsState];
@@ -7,6 +7,7 @@
7
7
  #import "CCPetsUsage.h"
8
8
  #import "CCPetsVersion.h"
9
9
  #import "CCPetsCleanup.h"
10
+ #import "CCPetsTerminalFocus.h"
10
11
  #import <sys/file.h>
11
12
  #import <sys/stat.h>
12
13
  #import <fcntl.h>
@@ -37,6 +38,10 @@ int main(int argc, const char *argv[]) {
37
38
  return RestartAfterPID(pid, appPath, managed);
38
39
  }
39
40
  if (argc > 1 && strcmp(argv[1], "--hook") == 0) return RecordHookEvent();
41
+ if (argc > 1 && strcmp(argv[1], "--frontmost-bundle-id") == 0) {
42
+ puts(FrontmostApplicationBundleIdentifier().UTF8String);
43
+ return EXIT_SUCCESS;
44
+ }
40
45
  if (argc > 1 && (strcmp(argv[1], "--provider-event") == 0 ||
41
46
  strcmp(argv[1], "provider-event") == 0)) return RecordProviderEvent();
42
47
  if (argc > 1 && strcmp(argv[1], "--claude-usage") == 0) return RecordClaudeUsage();
@@ -41,9 +41,15 @@ if [[ -d "${INSTALLED_APP}" ]]; then
41
41
  PET_APP="${INSTALLED_APP}"
42
42
  fi
43
43
 
44
+ # 固定 Agent 所在终端;后续所有 Hook 都会继承,用户中途切换应用也不会改错目标。
45
+ export CC_PETS_TERMINAL_TTY="${TTY:-}"
46
+ export CC_PETS_TERMINAL_PROGRAM="${TERM_PROGRAM:-}"
47
+ export CC_PETS_TERMINAL_SESSION="${TERM_SESSION_ID:-${ITERM_SESSION_ID:-}}"
48
+ export CC_PETS_TERMINAL_BUNDLE_ID="$("${PET_BIN}" --frontmost-bundle-id 2>/dev/null || true)"
49
+
44
50
  mkdir -p "${CLIENT_DIR}"
45
- # 写入 provider 名,桌宠据此判断“这一家的客户端是否还活着”。见 codex-with-pet 同处注释。
46
- print -r -- 'Claude' > "${CLIENT_FILE}"
51
+ # 第一行记录 provider,第二行记录 TTY;桌宠据此判断具体 Agent 会话是否仍在线。
52
+ printf '%s\n%s\n' 'Claude' "${CC_PETS_TERMINAL_TTY:t}" > "${CLIENT_FILE}"
47
53
 
48
54
  print -rn -- '{"schemaVersion":1,"provider":"Claude","state":"starting"}' | \
49
55
  "${PET_BIN}" --provider-event >/dev/null 2>&1 || true
@@ -39,10 +39,15 @@ if [[ -d "${INSTALLED_APP}" ]]; then
39
39
  PET_APP="${INSTALLED_APP}"
40
40
  fi
41
41
 
42
+ # Hook 的 stdin 是 JSON 管道,完成时再调用 tty 已经拿不到原始终端;必须在 exec 前固定。
43
+ export CC_PETS_TERMINAL_TTY="${TTY:-}"
44
+ export CC_PETS_TERMINAL_PROGRAM="${TERM_PROGRAM:-}"
45
+ export CC_PETS_TERMINAL_SESSION="${TERM_SESSION_ID:-${ITERM_SESSION_ID:-}}"
46
+ export CC_PETS_TERMINAL_BUNDLE_ID="$("${PET_BIN}" --frontmost-bundle-id 2>/dev/null || true)"
47
+
42
48
  mkdir -p "${CLIENT_DIR}"
43
- # 写入 provider 名,桌宠据此判断“这一家的客户端是否还活着”。只 touch 空文件的话,
44
- # Codex 全部退出后桌宠分不清剩下的客户端是谁,状态气泡会一直停在最后一条事件上。
45
- print -r -- 'Codex' > "${CLIENT_FILE}"
49
+ # 第一行记录 provider,第二行记录 TTY;桌宠据此判断具体 Agent 会话是否仍在线。
50
+ printf '%s\n%s\n' 'Codex' "${CC_PETS_TERMINAL_TTY:t}" > "${CLIENT_FILE}"
46
51
 
47
52
  print -rn -- '{"schemaVersion":1,"provider":"Codex","state":"starting"}' | \
48
53
  "${PET_BIN}" --provider-event >/dev/null 2>&1 || true
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "2.0.1",
3
+ "version": "2.0.3",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": {
6
6
  "name": "Sunnyshiny",