cc-pets 1.2.6 → 1.2.8

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.
@@ -2,6 +2,7 @@
2
2
  #import "PetView.h"
3
3
  #import "QuotaDashboardView.h"
4
4
  #import "CCPetsUsageMonitor.h"
5
+ #import "CCPetsSystemMonitor.h"
5
6
 
6
7
  @interface AppDelegate : NSObject <NSApplicationDelegate>
7
8
  @property NSPanel *panel;
@@ -45,6 +46,8 @@
45
46
  @property NSTask *updateTask;
46
47
  @property NSTimer *usageTimer;
47
48
  @property NSTimer *quotaClockTimer;
49
+ @property NSTimer *systemMetricsTimer;
50
+ @property CCPetsSystemMonitor *systemMonitor;
48
51
  - (void)showQuotaDashboard;
49
52
  - (void)positionQuotaDashboard;
50
53
  - (void)scheduleQuotaDashboardHide;
@@ -54,6 +57,7 @@
54
57
  - (void)prunePendingApprovalRecords;
55
58
  - (void)toggleStatusBubbleFromMenu:(NSButton *)sender;
56
59
  - (void)refreshUsage:(id)sender;
60
+ - (void)toggleSystemMetric:(NSButton *)sender;
57
61
  - (void)applyCodexUsage:(NSDictionary *)codexUsage claudeUsage:(NSDictionary *)claudeUsage;
58
62
  - (void)switchPetToID:(NSString *)petID;
59
63
  @end
@@ -252,13 +252,29 @@ static void TrimUpdateLog(NSString *path) {
252
252
  }];
253
253
  [task resume];
254
254
  }
255
- - (void)toggleQuotaHistory:(NSButton *)sender {
255
+ - (NSString *)systemMetricKeyForTag:(NSInteger)tag {
256
+ if (tag == 1) return SystemCPUEnabledKey;
257
+ if (tag == 2) return SystemTemperatureEnabledKey;
258
+ if (tag == 3) return SystemMemoryEnabledKey;
259
+ return nil;
260
+ }
261
+ - (void)applySystemMetricPreferences {
256
262
  NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
257
- BOOL enabled = ![defaults boolForKey:HistoryEnabledKey];
258
- [defaults setBool:enabled forKey:HistoryEnabledKey];
263
+ self.quotaView.systemCPUEnabled = [defaults boolForKey:SystemCPUEnabledKey];
264
+ self.quotaView.systemTemperatureEnabled =
265
+ [defaults boolForKey:SystemTemperatureEnabledKey];
266
+ self.quotaView.systemMemoryEnabled = [defaults boolForKey:SystemMemoryEnabledKey];
267
+ self.quotaView.needsDisplay = YES;
268
+ }
269
+ - (void)toggleSystemMetric:(NSButton *)sender {
270
+ NSString *key = [self systemMetricKeyForTag:sender.tag];
271
+ if (!key) return;
272
+ NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
273
+ BOOL enabled = ![defaults boolForKey:key];
274
+ [defaults setBool:enabled forKey:key];
259
275
  sender.state = enabled ? NSControlStateValueOn : NSControlStateValueOff;
260
- self.quotaView.historyEnabled = enabled;
261
- [self refreshUsage:nil];
276
+ [self applySystemMetricPreferences];
277
+ [self updateSystemMetricsTimer];
262
278
  }
263
279
  // 开关打开时立刻导入一次,不用等下次启动——用户点开关就是想现在看到那些素材。
264
280
  - (void)toggleImportCodexPets:(NSButton *)sender {
@@ -712,6 +728,11 @@ static void TrimUpdateLog(NSString *path) {
712
728
  }
713
729
  NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
714
730
  [defaults registerDefaults:@{StatusBubbleExpandedKey: @YES}];
731
+ [defaults registerDefaults:@{
732
+ SystemCPUEnabledKey: @YES,
733
+ SystemTemperatureEnabledKey: @YES,
734
+ SystemMemoryEnabledKey: @YES
735
+ }];
715
736
  if (![defaults boolForKey:StatusBubblePreferenceV2Key]) {
716
737
  [defaults setBool:YES forKey:StatusBubbleExpandedKey];
717
738
  [defaults setBool:YES forKey:StatusBubblePreferenceV2Key];
@@ -878,7 +899,7 @@ static void TrimUpdateLog(NSString *path) {
878
899
  glass.layer.masksToBounds = YES;
879
900
  [quotaRoot addSubview:glass];
880
901
  self.quotaView = [[QuotaDashboardView alloc] initWithFrame:NSMakeRect(0, 0, quotaSize.width, quotaSize.height)];
881
- self.quotaView.historyEnabled = [defaults boolForKey:HistoryEnabledKey];
902
+ [self applySystemMetricPreferences];
882
903
  self.quotaView.codexLogo = OfficialAppIcon(@"com.openai.codex", @"icon-chatgpt.icns");
883
904
  self.quotaView.claudeLogo = OfficialAppIcon(@"com.anthropic.claudefordesktop", @"electron.icns");
884
905
  self.quotaView.hoverChanged = ^(BOOL hovering) {
@@ -896,6 +917,7 @@ static void TrimUpdateLog(NSString *path) {
896
917
  [self.panel setFrameOrigin:NSMakePoint(NSMaxX(visible) - size.width - 24, NSMinY(visible) + 18)];
897
918
  [self.panel orderFrontRegardless];
898
919
  self.usageMonitor = [CCPetsUsageMonitor new];
920
+ self.systemMonitor = [CCPetsSystemMonitor new];
899
921
  self.agentEventPartialLine = [NSMutableData data];
900
922
  self.pendingApprovalRecords = [NSMutableDictionary dictionary];
901
923
  self.usageMonitor.changeHandler = ^(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
@@ -949,6 +971,42 @@ static void TrimUpdateLog(NSString *path) {
949
971
  [self.panel orderFrontRegardless];
950
972
  [self rescheduleUsageTimer];
951
973
  [self startQuotaClock];
974
+ [self updateSystemMetricsTimer];
975
+ }
976
+ - (BOOL)hasEnabledSystemMetric {
977
+ return self.quotaView.systemCPUEnabled || self.quotaView.systemTemperatureEnabled ||
978
+ self.quotaView.systemMemoryEnabled;
979
+ }
980
+ - (void)refreshSystemMetrics:(id)sender {
981
+ if (![self hasEnabledSystemMetric]) return;
982
+ BOOL cpuEnabled = self.quotaView.systemCPUEnabled;
983
+ BOOL memoryEnabled = self.quotaView.systemMemoryEnabled;
984
+ BOOL temperatureEnabled = self.quotaView.systemTemperatureEnabled;
985
+ __weak typeof(self) weakSelf = self;
986
+ [self.systemMonitor sampleCPU:cpuEnabled memory:memoryEnabled
987
+ temperature:temperatureEnabled completion:^(NSNumber *cpu, NSNumber *memory,
988
+ NSNumber *temperature) {
989
+ typeof(self) strongSelf = weakSelf;
990
+ if (!strongSelf) return;
991
+ if (cpuEnabled) strongSelf.quotaView.systemCPUPercent = cpu;
992
+ if (memoryEnabled) strongSelf.quotaView.systemMemoryPercent = memory;
993
+ if (temperatureEnabled) strongSelf.quotaView.systemTemperatureCelsius = temperature;
994
+ strongSelf.quotaView.needsDisplay = YES;
995
+ }];
996
+ }
997
+ - (void)updateSystemMetricsTimer {
998
+ BOOL shouldRun = self.quotaPanel.isVisible && [self hasEnabledSystemMetric];
999
+ if (!shouldRun) {
1000
+ [self.systemMetricsTimer invalidate];
1001
+ self.systemMetricsTimer = nil;
1002
+ return;
1003
+ }
1004
+ if (self.systemMetricsTimer.isValid) return;
1005
+ [self refreshSystemMetrics:nil];
1006
+ __weak typeof(self) weakSelf = self;
1007
+ self.systemMetricsTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES
1008
+ block:^(NSTimer *timer) { [weakSelf refreshSystemMetrics:timer]; }];
1009
+ self.systemMetricsTimer.tolerance = 0.4;
952
1010
  }
953
1011
  // "数据刷新" 显示的是相对时间,没有新数据也得自己走字。面板隐藏时不需要这个定时器,
954
1012
  // 隐藏的窗口本来就不会重绘。
@@ -962,6 +1020,7 @@ static void TrimUpdateLog(NSString *path) {
962
1020
  if (!self.quotaPanel.isVisible) {
963
1021
  [self.quotaClockTimer invalidate];
964
1022
  self.quotaClockTimer = nil;
1023
+ [self updateSystemMetricsTimer];
965
1024
  return;
966
1025
  }
967
1026
  self.quotaView.needsDisplay = YES;
@@ -1026,6 +1085,7 @@ static void TrimUpdateLog(NSString *path) {
1026
1085
  [self rescheduleUsageTimer];
1027
1086
  [self.quotaClockTimer invalidate];
1028
1087
  self.quotaClockTimer = nil;
1088
+ [self updateSystemMetricsTimer];
1029
1089
  }
1030
1090
  }
1031
1091
  - (void)switchPetToID:(NSString *)petID {
@@ -1253,6 +1313,8 @@ static void TrimUpdateLog(NSString *path) {
1253
1313
  }
1254
1314
  - (void)applicationWillTerminate:(NSNotification *)notification {
1255
1315
  [self.usageMonitor stop];
1316
+ [self.systemMetricsTimer invalidate];
1317
+ self.systemMetricsTimer = nil;
1256
1318
  if (self.agentEventSource) {
1257
1319
  dispatch_source_cancel(self.agentEventSource);
1258
1320
  self.agentEventSource = nil;
@@ -172,6 +172,13 @@ int RecordHookEvent(void) {
172
172
  if (![payload isKindOfClass:NSDictionary.class]) return EXIT_SUCCESS;
173
173
  NSString *event = payload[@"hook_event_name"];
174
174
  if (![event isKindOfClass:NSString.class] || event.length == 0) return EXIT_SUCCESS;
175
+ // Claude Agent SDK / ACP 也会执行用户级 Hooks。IDE 或终端仅仅创建、销毁这类
176
+ // 后台会话时就会发 SessionStart / SessionEnd,但它们不代表用户启动了 Agent
177
+ // 任务或完成了一轮工作。真实 CLI 的启动状态由包装脚本显式写入,任务完成则由
178
+ // Stop 表示,因此这里忽略纯会话生命周期事件,避免普通终端开关触发误报。
179
+ if ([event isEqualToString:@"SessionStart"] || [event isEqualToString:@"SessionEnd"]) {
180
+ return EXIT_SUCCESS;
181
+ }
175
182
  NSString *tool = [payload[@"tool_name"] isKindOfClass:NSString.class] ? payload[@"tool_name"] : @"";
176
183
  NSString *session = SanitizedShortString(payload[@"session_id"], 128);
177
184
  id toolResult = payload[@"tool_response"] ?: payload[@"tool_result"];
@@ -31,6 +31,9 @@ extern NSString *const NotificationApprovalKey;
31
31
  extern NSString *const StatusBubbleExpandedKey;
32
32
  extern NSString *const StatusBubblePreferenceV2Key;
33
33
  extern NSString *const ImportCodexPetsKey;
34
+ extern NSString *const SystemCPUEnabledKey;
35
+ extern NSString *const SystemTemperatureEnabledKey;
36
+ extern NSString *const SystemMemoryEnabledKey;
34
37
 
35
38
  extern const NSTimeInterval AgentStatusInactivityInterval;
36
39
  extern const NSTimeInterval AgentStatusOrphanInterval;
@@ -169,6 +169,9 @@ NSString *const NotificationApprovalKey = @"CCPetsNotifyApproval";
169
169
  NSString *const StatusBubbleExpandedKey = @"CCPetsStatusBubbleExpanded";
170
170
  NSString *const StatusBubblePreferenceV2Key = @"CCPetsStatusBubblePreferenceV2";
171
171
  NSString *const ImportCodexPetsKey = @"CCPetsImportCodexPets";
172
+ NSString *const SystemCPUEnabledKey = @"CCPetsSystemCPUEnabled";
173
+ NSString *const SystemTemperatureEnabledKey = @"CCPetsSystemTemperatureEnabled";
174
+ NSString *const SystemMemoryEnabledKey = @"CCPetsSystemMemoryEnabled";
172
175
  const NSTimeInterval AgentStatusInactivityInterval = 60.0;
173
176
  // 客户端进程已经消失、但状态气泡还停在它最后一条事件上时,多等这么久再清场。
174
177
  // 留这段宽限是因为不经包装脚本启动的客户端(直接跑 claude / codex)没有 pid
@@ -32,7 +32,6 @@ int RenderQuotaDashboard(NSString *path) {
32
32
  @"source": @"local"
33
33
  }
34
34
  };
35
- view.historyEnabled = YES;
36
35
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
37
36
  NSTimeInterval day = 24 * 60 * 60;
38
37
  view.codexHistory = @[
@@ -1,6 +1,6 @@
1
1
  #import <Foundation/Foundation.h>
2
2
 
3
- // 本地额度历史(默认关闭,由 HistoryEnabledKey 控制)。
3
+ // 本地额度历史始终记录并展示。
4
4
  // RecordQuotaHistory 返回当前文档,调用方直接复用,避免一轮刷新里重复读盘。
5
5
  NSDictionary *QuotaHistoryDocument(void);
6
6
  NSDictionary *RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage);
@@ -39,7 +39,6 @@ static NSDictionary *HistoryProviderSample(NSDictionary *usage, NSString *usedKe
39
39
  // (这里一次、两条曲线各一次),现在整轮只读一次。
40
40
  NSDictionary *RecordQuotaHistory(NSDictionary *codexUsage, NSDictionary *claudeUsage) {
41
41
  NSDictionary *document = QuotaHistoryDocument();
42
- if (![NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]) return document;
43
42
  NSDictionary *codex = HistoryProviderSample(codexUsage, @"used_percent");
44
43
  NSDictionary *claude = HistoryProviderSample(claudeUsage, @"used_percentage");
45
44
  if (codex.count == 0 && claude.count == 0) return document;
@@ -0,0 +1,8 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ @interface CCPetsSystemMonitor : NSObject
4
+ - (void)sampleCPU:(BOOL)cpuEnabled memory:(BOOL)memoryEnabled
5
+ temperature:(BOOL)temperatureEnabled
6
+ completion:(void (^)(NSNumber *cpuPercent, NSNumber *memoryPercent,
7
+ NSNumber *temperatureCelsius))completion;
8
+ @end
@@ -0,0 +1,260 @@
1
+ #import "CCPetsSystemMonitor.h"
2
+ #import <IOKit/IOKitLib.h>
3
+ #import <dlfcn.h>
4
+ #import <mach/mach.h>
5
+ #import <mach/processor_info.h>
6
+ #import <mach/vm_statistics.h>
7
+
8
+ typedef struct {
9
+ uint8_t major;
10
+ uint8_t minor;
11
+ uint8_t build;
12
+ uint8_t reserved;
13
+ uint16_t release;
14
+ } CCPetsSMCVersion;
15
+
16
+ typedef struct {
17
+ uint16_t version;
18
+ uint16_t length;
19
+ uint32_t cpuPLimit;
20
+ uint32_t gpuPLimit;
21
+ uint32_t memPLimit;
22
+ } CCPetsSMCPLimitData;
23
+
24
+ typedef struct {
25
+ uint32_t dataSize;
26
+ uint32_t dataType;
27
+ uint8_t dataAttributes;
28
+ } CCPetsSMCKeyInfoData;
29
+
30
+ typedef struct {
31
+ uint32_t key;
32
+ CCPetsSMCVersion version;
33
+ CCPetsSMCPLimitData pLimitData;
34
+ CCPetsSMCKeyInfoData keyInfo;
35
+ uint8_t result;
36
+ uint8_t status;
37
+ uint8_t data8;
38
+ uint32_t data32;
39
+ uint8_t bytes[32];
40
+ } CCPetsSMCParamStruct;
41
+
42
+ static uint32_t CCPetsFourCC(NSString *text) {
43
+ if (text.length != 4) return 0;
44
+ uint32_t value = 0;
45
+ for (NSUInteger index = 0; index < 4; index++) {
46
+ value = (value << 8) | (uint8_t)[text characterAtIndex:index];
47
+ }
48
+ return value;
49
+ }
50
+
51
+ static NSNumber *CCPetsReadSMCTemperature(NSString *key) {
52
+ io_service_t service = IOServiceGetMatchingService(kIOMainPortDefault,
53
+ IOServiceMatching("AppleSMC"));
54
+ if (!service) return nil;
55
+ io_connect_t connection = IO_OBJECT_NULL;
56
+ kern_return_t result = IOServiceOpen(service, mach_task_self(), 0, &connection);
57
+ IOObjectRelease(service);
58
+ if (result != KERN_SUCCESS || !connection) return nil;
59
+
60
+ CCPetsSMCParamStruct input = {0};
61
+ CCPetsSMCParamStruct output = {0};
62
+ size_t outputSize = sizeof(output);
63
+ input.key = CCPetsFourCC(key);
64
+ input.data8 = 9; // kSMCGetKeyInfo
65
+ result = IOConnectCallStructMethod(connection, 2, &input, sizeof(input),
66
+ &output, &outputSize);
67
+ if (result != KERN_SUCCESS || output.keyInfo.dataSize == 0 ||
68
+ output.keyInfo.dataSize > sizeof(output.bytes)) {
69
+ IOServiceClose(connection);
70
+ return nil;
71
+ }
72
+
73
+ CCPetsSMCKeyInfoData keyInfo = output.keyInfo;
74
+ memset(&input, 0, sizeof(input));
75
+ memset(&output, 0, sizeof(output));
76
+ outputSize = sizeof(output);
77
+ input.key = CCPetsFourCC(key);
78
+ input.keyInfo.dataSize = keyInfo.dataSize;
79
+ input.data8 = 5; // kSMCReadKey
80
+ result = IOConnectCallStructMethod(connection, 2, &input, sizeof(input),
81
+ &output, &outputSize);
82
+ IOServiceClose(connection);
83
+ if (result != KERN_SUCCESS) return nil;
84
+
85
+ double temperature = NAN;
86
+ uint32_t type = keyInfo.dataType;
87
+ if (type == CCPetsFourCC(@"sp78") && keyInfo.dataSize >= 2) {
88
+ temperature = (double)(int16_t)((output.bytes[0] << 8) | output.bytes[1]) / 256.0;
89
+ } else if (type == CCPetsFourCC(@"flt ") && keyInfo.dataSize >= sizeof(float)) {
90
+ uint32_t bits = ((uint32_t)output.bytes[0] << 24) |
91
+ ((uint32_t)output.bytes[1] << 16) |
92
+ ((uint32_t)output.bytes[2] << 8) | output.bytes[3];
93
+ float value = 0;
94
+ memcpy(&value, &bits, sizeof(value));
95
+ temperature = value;
96
+ }
97
+ return isfinite(temperature) && temperature >= 0 && temperature <= 125
98
+ ? @(temperature) : nil;
99
+ }
100
+
101
+ // Apple Silicon 新机型(包括 M5)不再暴露 AppleSMC,但会把芯片温度作为
102
+ // IOHIDEventService 的 Temperature 事件提供。相关函数没有公开头文件,运行时解析
103
+ // 可以在旧系统上安全降级,不会形成私有符号的静态链接依赖。
104
+ static NSNumber *CCPetsReadHIDDieTemperature(void) {
105
+ typedef CFTypeRef (*CreateClientFunction)(CFAllocatorRef);
106
+ typedef CFArrayRef (*CopyServicesFunction)(CFTypeRef);
107
+ typedef CFTypeRef (*CopyPropertyFunction)(CFTypeRef, CFStringRef);
108
+ typedef CFTypeRef (*CopyEventFunction)(CFTypeRef, int64_t, int32_t, int64_t);
109
+ typedef double (*GetFloatValueFunction)(CFTypeRef, int32_t);
110
+
111
+ void *framework = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit",
112
+ RTLD_LAZY | RTLD_LOCAL);
113
+ if (!framework) return nil;
114
+ CreateClientFunction createClient =
115
+ (CreateClientFunction)dlsym(framework, "IOHIDEventSystemClientCreate");
116
+ CopyServicesFunction copyServices =
117
+ (CopyServicesFunction)dlsym(framework, "IOHIDEventSystemClientCopyServices");
118
+ CopyPropertyFunction copyProperty =
119
+ (CopyPropertyFunction)dlsym(framework, "IOHIDServiceClientCopyProperty");
120
+ CopyEventFunction copyEvent =
121
+ (CopyEventFunction)dlsym(framework, "IOHIDServiceClientCopyEvent");
122
+ GetFloatValueFunction getFloatValue =
123
+ (GetFloatValueFunction)dlsym(framework, "IOHIDEventGetFloatValue");
124
+ if (!createClient || !copyServices || !copyProperty || !copyEvent || !getFloatValue) {
125
+ dlclose(framework);
126
+ return nil;
127
+ }
128
+
129
+ CFTypeRef client = createClient(kCFAllocatorDefault);
130
+ CFArrayRef services = client ? copyServices(client) : nil;
131
+ double hottest = NAN;
132
+ for (CFIndex index = 0; services && index < CFArrayGetCount(services); index++) {
133
+ CFTypeRef service = CFArrayGetValueAtIndex(services, index);
134
+ CFTypeRef productValue = copyProperty(service, CFSTR("Product"));
135
+ NSString *product = productValue && CFGetTypeID(productValue) == CFStringGetTypeID()
136
+ ? (__bridge NSString *)productValue : nil;
137
+ BOOL isDieSensor = [product.lowercaseString containsString:@"tdie"];
138
+ if (productValue) CFRelease(productValue);
139
+ if (!isDieSensor) continue;
140
+
141
+ // kIOHIDEventTypeTemperature = 15;Level 字段位于该类型的 field base。
142
+ CFTypeRef event = copyEvent(service, 15, 0, 0);
143
+ if (!event) continue;
144
+ double value = getFloatValue(event, 15 << 16);
145
+ CFRelease(event);
146
+ if (isfinite(value) && value >= 0 && value <= 125 &&
147
+ (!isfinite(hottest) || value > hottest)) hottest = value;
148
+ }
149
+ if (services) CFRelease(services);
150
+ if (client) CFRelease(client);
151
+ dlclose(framework);
152
+ return isfinite(hottest) ? @(hottest) : nil;
153
+ }
154
+
155
+ @interface CCPetsSystemMonitor ()
156
+ @property dispatch_queue_t queue;
157
+ @property uint64_t previousUserTicks;
158
+ @property uint64_t previousSystemTicks;
159
+ @property uint64_t previousIdleTicks;
160
+ @property uint64_t previousNiceTicks;
161
+ @property NSNumber *cachedTemperature;
162
+ @property NSTimeInterval temperatureSampledAt;
163
+ @end
164
+
165
+ @implementation CCPetsSystemMonitor
166
+
167
+ - (instancetype)init {
168
+ if ((self = [super init])) {
169
+ _queue = dispatch_queue_create("com.universewang.cc-pets.system-monitor",
170
+ DISPATCH_QUEUE_SERIAL);
171
+ }
172
+ return self;
173
+ }
174
+
175
+ - (NSNumber *)cpuPercent {
176
+ processor_info_array_t info = NULL;
177
+ mach_msg_type_number_t count = 0;
178
+ natural_t processors = 0;
179
+ kern_return_t result = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO,
180
+ &processors, &info, &count);
181
+ if (result != KERN_SUCCESS || !info) return nil;
182
+ uint64_t user = 0, system = 0, idle = 0, nice = 0;
183
+ for (natural_t index = 0; index < processors; index++) {
184
+ processor_cpu_load_info_t load = (processor_cpu_load_info_t)info + index;
185
+ user += load->cpu_ticks[CPU_STATE_USER];
186
+ system += load->cpu_ticks[CPU_STATE_SYSTEM];
187
+ idle += load->cpu_ticks[CPU_STATE_IDLE];
188
+ nice += load->cpu_ticks[CPU_STATE_NICE];
189
+ }
190
+ vm_deallocate(mach_task_self(), (vm_address_t)info, count * sizeof(integer_t));
191
+
192
+ uint64_t previousTotal = self.previousUserTicks + self.previousSystemTicks +
193
+ self.previousIdleTicks + self.previousNiceTicks;
194
+ uint64_t total = user + system + idle + nice;
195
+ uint64_t totalDelta = total >= previousTotal ? total - previousTotal : 0;
196
+ uint64_t idleDelta = idle >= self.previousIdleTicks ? idle - self.previousIdleTicks : 0;
197
+ self.previousUserTicks = user;
198
+ self.previousSystemTicks = system;
199
+ self.previousIdleTicks = idle;
200
+ self.previousNiceTicks = nice;
201
+ if (totalDelta == 0) return nil;
202
+ return @(fmax(0, fmin(100, 100.0 * (double)(totalDelta - idleDelta) /
203
+ (double)totalDelta)));
204
+ }
205
+
206
+ - (NSNumber *)memoryPercent {
207
+ mach_port_t host = mach_host_self();
208
+ vm_size_t pageSize = 0;
209
+ if (host_page_size(host, &pageSize) != KERN_SUCCESS) return nil;
210
+ vm_statistics64_data_t stats = {0};
211
+ mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
212
+ if (host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&stats, &count) !=
213
+ KERN_SUCCESS) return nil;
214
+ uint64_t total = NSProcessInfo.processInfo.physicalMemory;
215
+ if (total == 0) return nil;
216
+ // 对齐活动监视器的“已使用内存”:物理内存减去空闲内存和可回收的文件缓存。
217
+ // file-backed 对应活动监视器里的“已缓存文件”,speculative 也属于可立即回收页。
218
+ uint64_t reclaimablePages = stats.free_count + stats.speculative_count +
219
+ stats.external_page_count;
220
+ uint64_t reclaimable = reclaimablePages * (uint64_t)pageSize;
221
+ uint64_t used = total > reclaimable ? total - reclaimable : 0;
222
+ return @(fmax(0, fmin(100, 100.0 * (double)used / (double)total)));
223
+ }
224
+
225
+ - (NSNumber *)temperature {
226
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
227
+ NSTimeInterval interval = self.cachedTemperature ? 5 : 30;
228
+ if (self.temperatureSampledAt > 0 && now - self.temperatureSampledAt < interval) {
229
+ return self.cachedTemperature;
230
+ }
231
+ self.temperatureSampledAt = now;
232
+ NSNumber *temperature = CCPetsReadHIDDieTemperature();
233
+ if (!temperature) {
234
+ // Intel 和部分早期 Apple Silicon 仍通过 AppleSMC 暴露这些 key。
235
+ for (NSString *key in @[@"TC0P", @"TC0D", @"Tp09", @"Tp0T", @"Tp01", @"Tp05"]) {
236
+ NSNumber *value = CCPetsReadSMCTemperature(key);
237
+ if (value) {
238
+ temperature = value;
239
+ break;
240
+ }
241
+ }
242
+ }
243
+ self.cachedTemperature = temperature;
244
+ return self.cachedTemperature;
245
+ }
246
+
247
+ - (void)sampleCPU:(BOOL)cpuEnabled memory:(BOOL)memoryEnabled
248
+ temperature:(BOOL)temperatureEnabled
249
+ completion:(void (^)(NSNumber *, NSNumber *, NSNumber *))completion {
250
+ dispatch_async(self.queue, ^{
251
+ NSNumber *cpu = cpuEnabled ? [self cpuPercent] : nil;
252
+ NSNumber *memory = memoryEnabled ? [self memoryPercent] : nil;
253
+ NSNumber *temperature = temperatureEnabled ? [self temperature] : nil;
254
+ dispatch_async(dispatch_get_main_queue(), ^{
255
+ if (completion) completion(cpu, memory, temperature);
256
+ });
257
+ });
258
+ }
259
+
260
+ @end
@@ -509,11 +509,6 @@ static const CGFloat PetDragThreshold = 3.0;
509
509
  checked:[NSUserDefaults.standardUserDefaults boolForKey:StatusBubbleExpandedKey]
510
510
  action:@selector(toggleStatusBubbleFromMenu:)
511
511
  tag:0];
512
- [self addPersistentSwitchToMenu:menu
513
- title:@"记录本地额度历史"
514
- checked:[NSUserDefaults.standardUserDefaults boolForKey:HistoryEnabledKey]
515
- action:@selector(toggleQuotaHistory:)
516
- tag:0];
517
512
  [self addPersistentSwitchToMenu:menu
518
513
  title:@"导入 Codex 素材"
519
514
  checked:[NSUserDefaults.standardUserDefaults boolForKey:ImportCodexPetsKey]
@@ -534,6 +529,21 @@ static const CGFloat PetDragThreshold = 3.0;
534
529
  tag:[option[@"tag"] integerValue]];
535
530
  }
536
531
  notificationItem.submenu = notificationMenu;
532
+ NSMenuItem *systemStatusItem = [menu addItemWithTitle:@"系统状态" action:nil keyEquivalent:@""];
533
+ NSMenu *systemStatusMenu = [NSMenu new];
534
+ NSArray<NSDictionary *> *systemStatusOptions = @[
535
+ @{@"title": @"CPU 占用", @"key": SystemCPUEnabledKey, @"tag": @1},
536
+ @{@"title": @"CPU 温度", @"key": SystemTemperatureEnabledKey, @"tag": @2},
537
+ @{@"title": @"内存占用", @"key": SystemMemoryEnabledKey, @"tag": @3}
538
+ ];
539
+ for (NSDictionary *option in systemStatusOptions) {
540
+ [self addPersistentSwitchToMenu:systemStatusMenu
541
+ title:option[@"title"]
542
+ checked:[NSUserDefaults.standardUserDefaults boolForKey:option[@"key"]]
543
+ action:@selector(toggleSystemMetric:)
544
+ tag:[option[@"tag"] integerValue]];
545
+ }
546
+ systemStatusItem.submenu = systemStatusMenu;
537
547
  NSMenuItem *updateItem = [menu addItemWithTitle:@"检查更新…" action:@selector(checkForUpdates:) keyEquivalent:@""];
538
548
  updateItem.target = NSApp.delegate;
539
549
  [menu addItem:NSMenuItem.separatorItem];
@@ -12,7 +12,6 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
12
12
  @property NSDictionary *claudeUsage;
13
13
  @property NSArray<NSDictionary *> *codexHistory;
14
14
  @property NSArray<NSDictionary *> *claudeHistory;
15
- @property BOOL historyEnabled;
16
15
  @property NSInteger activeAgentCount;
17
16
  // 仍在运行的客户端所属的 provider("Codex" / "Claude")。卡片的在线徽章据此判定,
18
17
  // 而不是看有没有额度数据——额度会一直缓存着,拿它当在线信号会恒亮。
@@ -20,6 +19,12 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName);
20
19
  // 老版本包装脚本写出的 pid 文件没有 provider 名。有这种客户端时无法断言某一家离线。
21
20
  @property BOOL hasUnlabeledClient;
22
21
  @property NSTimeInterval lastUpdatedAt;
22
+ @property BOOL systemCPUEnabled;
23
+ @property BOOL systemTemperatureEnabled;
24
+ @property BOOL systemMemoryEnabled;
25
+ @property NSNumber *systemCPUPercent;
26
+ @property NSNumber *systemTemperatureCelsius;
27
+ @property NSNumber *systemMemoryPercent;
23
28
  - (BOOL)isProviderOnline:(NSString *)name;
24
29
  @property NSImage *codexLogo;
25
30
  @property NSImage *claudeLogo;
@@ -183,6 +183,72 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
183
183
  - (NSColor *)agentStatusColor {
184
184
  return self.activeAgentCount > 0 ? NSColor.systemGreenColor : self.secondaryColor;
185
185
  }
186
+ - (void)drawSystemMetricsEndingAtX:(CGFloat)rightEdge y:(CGFloat)y {
187
+ NSMutableArray<NSDictionary *> *metrics = [NSMutableArray array];
188
+ if (self.systemCPUEnabled) {
189
+ NSString *value = self.systemCPUPercent
190
+ ? [NSString stringWithFormat:@"%.0f%%", self.systemCPUPercent.doubleValue] : @"--";
191
+ [metrics addObject:@{@"symbol": @"cpu", @"label": [NSString stringWithFormat:@"CPU %@", value],
192
+ @"color": [NSColor colorWithRed:245.0 / 255.0 green:166.0 / 255.0
193
+ blue:35.0 / 255.0 alpha:1]}];
194
+ }
195
+ if (self.systemTemperatureEnabled) {
196
+ NSString *value = self.systemTemperatureCelsius
197
+ ? [NSString stringWithFormat:@"%.0f°C", self.systemTemperatureCelsius.doubleValue] : @"--°C";
198
+ double temperature = self.systemTemperatureCelsius.doubleValue;
199
+ NSColor *color = temperature >= 90 ? NSColor.systemRedColor :
200
+ (temperature >= 80 ? [NSColor colorWithRed:1.00 green:0.35 blue:0.16 alpha:1] :
201
+ [NSColor colorWithRed:1.00 green:107.0 / 255.0 blue:74.0 / 255.0 alpha:1]);
202
+ [metrics addObject:@{@"symbol": @"thermometer.medium", @"label": value,
203
+ @"color": color}];
204
+ }
205
+ if (self.systemMemoryEnabled) {
206
+ NSString *value = self.systemMemoryPercent
207
+ ? [NSString stringWithFormat:@"%.0f%%", self.systemMemoryPercent.doubleValue] : @"--";
208
+ [metrics addObject:@{@"symbol": @"memorychip", @"label": [NSString stringWithFormat:@"MEM %@", value],
209
+ @"color": [NSColor colorWithRed:32.0 / 255.0 green:214.0 / 255.0
210
+ blue:165.0 / 255.0 alpha:1]}];
211
+ }
212
+ NSFont *font = [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold];
213
+ NSMutableAttributedString *statusLine = [NSMutableAttributedString new];
214
+ for (NSUInteger index = 0; index < metrics.count; index++) {
215
+ NSDictionary *metric = metrics[index];
216
+ NSString *label = metric[@"label"];
217
+ NSColor *color = metric[@"color"];
218
+ NSDictionary *attributes = @{NSFontAttributeName: font,
219
+ NSForegroundColorAttributeName: color};
220
+ NSImage *icon = [NSImage imageWithSystemSymbolName:metric[@"symbol"]
221
+ accessibilityDescription:label];
222
+ NSImageSymbolConfiguration *sizeConfiguration =
223
+ [NSImageSymbolConfiguration configurationWithPointSize:
224
+ [metric[@"symbol"] isEqualToString:@"thermometer.medium"] ? 16 : 14
225
+ weight:NSFontWeightSemibold];
226
+ NSImageSymbolConfiguration *colorConfiguration =
227
+ [NSImageSymbolConfiguration configurationWithHierarchicalColor:metric[@"color"]];
228
+ icon = [icon imageWithSymbolConfiguration:
229
+ [sizeConfiguration configurationByApplyingConfiguration:colorConfiguration]];
230
+ NSTextAttachment *attachment = [NSTextAttachment new];
231
+ attachment.image = icon;
232
+ CGFloat iconSize = [metric[@"symbol"] isEqualToString:@"thermometer.medium"] ? 18 : 16;
233
+ attachment.bounds = NSMakeRect(0, (font.capHeight - iconSize) / 2.0,
234
+ iconSize, iconSize);
235
+ [statusLine appendAttributedString:[NSAttributedString
236
+ attributedStringWithAttachment:attachment]];
237
+ [statusLine appendAttributedString:[[NSAttributedString alloc]
238
+ initWithString:@" " attributes:attributes]];
239
+ [statusLine appendAttributedString:[[NSAttributedString alloc]
240
+ initWithString:label attributes:attributes]];
241
+ if (index + 1 < metrics.count) {
242
+ NSDictionary *separatorAttributes = @{NSFontAttributeName:
243
+ [NSFont systemFontOfSize:12 weight:NSFontWeightRegular],
244
+ NSForegroundColorAttributeName: [NSColor colorWithWhite:0.42 alpha:0.7]};
245
+ [statusLine appendAttributedString:[[NSAttributedString alloc]
246
+ initWithString:@" │ " attributes:separatorAttributes]];
247
+ }
248
+ }
249
+ CGFloat width = ceil(statusLine.size.width);
250
+ [statusLine drawInRect:NSMakeRect(rightEdge - width, y, width + 1, 20)];
251
+ }
186
252
  - (NSString *)formattedTokenCountForUsage:(NSDictionary *)usage key:(NSString *)key {
187
253
  return [self formattedTokenCount:[self tokenTotals:usage key:key] ?: @{}];
188
254
  }
@@ -231,17 +297,15 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
231
297
  NSTimeInterval now = NSDate.date.timeIntervalSince1970;
232
298
  NSTimeInterval cutoff = now - 7 * 24 * 60 * 60;
233
299
  NSMutableArray<NSDictionary *> *points = [NSMutableArray array];
234
- if (self.historyEnabled) {
235
- for (NSDictionary *sample in history) {
236
- if (![sample isKindOfClass:NSDictionary.class]) continue;
237
- NSNumber *timestamp = [sample[@"timestamp"] isKindOfClass:NSNumber.class]
238
- ? sample[@"timestamp"] : nil;
239
- NSNumber *remaining = [sample[@"remaining"] isKindOfClass:NSNumber.class]
240
- ? sample[@"remaining"] : nil;
241
- if (!timestamp || !remaining || timestamp.doubleValue < cutoff) continue;
242
- double used = 100.0 - fmax(0, fmin(100, remaining.doubleValue));
243
- [points addObject:@{@"timestamp": timestamp, @"used": @(used)}];
244
- }
300
+ for (NSDictionary *sample in history) {
301
+ if (![sample isKindOfClass:NSDictionary.class]) continue;
302
+ NSNumber *timestamp = [sample[@"timestamp"] isKindOfClass:NSNumber.class]
303
+ ? sample[@"timestamp"] : nil;
304
+ NSNumber *remaining = [sample[@"remaining"] isKindOfClass:NSNumber.class]
305
+ ? sample[@"remaining"] : nil;
306
+ if (!timestamp || !remaining || timestamp.doubleValue < cutoff) continue;
307
+ double used = 100.0 - fmax(0, fmin(100, remaining.doubleValue));
308
+ [points addObject:@{@"timestamp": timestamp, @"used": @(used)}];
245
309
  }
246
310
  // 终点必须和卡片上的当前官方额度同源;历史落盘最多会慢 15 分钟,不能直接拿它
247
311
  // 冒充“当前”,否则同一张卡里会出现两个不同百分比。
@@ -537,6 +601,7 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
537
601
  : @"暂无 Agent 在线";
538
602
  [agentText drawInRect:NSMakeRect(190, QuotaLogicalHeight - 95, 160, 22)
539
603
  withAttributes:[self textAttributesWithSize:14 color:agentColor weight:NSFontWeightMedium]];
604
+ [self drawSystemMetricsEndingAtX:QuotaLogicalWidth - 28 y:QuotaLogicalHeight - 95];
540
605
 
541
606
  BOOL recentlyRefreshed = self.refreshedUntil > NSDate.date.timeIntervalSince1970;
542
607
  CGFloat buttonAlpha = self.refreshPressed ? 0.18 : (self.refreshHovered ? 0.12 : 0.06);
@@ -564,8 +629,10 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
564
629
  // 每格内是一张 2×2 表:标题独占一行,每个 Provider 独占一行;输入/输出标签放在
565
630
  // 对应数值上方。这样既能完整展示 7 天统计起期,也不会挤乱两家的数据行。
566
631
  NSArray<NSDictionary *> *cells = @[
567
- @{@"icon": @"◔", @"key": @"today", @"label": @"▣ 今日用量"},
568
- @{@"icon": @"◉", @"key": @"recentWeek", @"label": [self recentWeekUsageLabel]}
632
+ @{@"icon": @"◔", @"headerSymbol": @"calendar", @"key": @"today",
633
+ @"label": @"今日用量"},
634
+ @{@"icon": @"◉", @"headerSymbol": @"calendar.badge.clock", @"key": @"recentWeek",
635
+ @"label": [self recentWeekUsageLabel]}
569
636
  ];
570
637
  NSColor *claudeColor = [NSColor colorWithRed:0.66 green:0.43 blue:0.94 alpha:1];
571
638
  NSArray<NSDictionary *> *rows = @[
@@ -586,11 +653,31 @@ NSImage *OfficialAppIcon(NSString *bundleIdentifier, NSString *resourceName) {
586
653
  CGFloat x = NSMinX([self logicalSummaryCellRectAtIndex:index]);
587
654
  const CGFloat inputX = x + 176;
588
655
  const CGFloat outputX = x + 276;
589
- NSDictionary *headerAttributes = [self textAttributesWithSize:11 color:secondary
590
- weight:NSFontWeightRegular];
591
- [cell[@"label"] drawInRect:NSMakeRect(x + 24, NSMinY(summary) + 89,
592
- NSWidth([self logicalSummaryCellRectAtIndex:index]) - 48, 18)
593
- withAttributes:headerAttributes];
656
+ NSFont *headerFont = [NSFont systemFontOfSize:11 weight:NSFontWeightRegular];
657
+ NSDictionary *headerAttributes = @{NSFontAttributeName: headerFont,
658
+ NSForegroundColorAttributeName: secondary};
659
+ NSImage *headerIcon = [NSImage imageWithSystemSymbolName:cell[@"headerSymbol"]
660
+ accessibilityDescription:cell[@"label"]];
661
+ NSImageSymbolConfiguration *headerIconConfiguration =
662
+ [NSImageSymbolConfiguration configurationWithPointSize:11
663
+ weight:NSFontWeightRegular];
664
+ headerIconConfiguration = [headerIconConfiguration configurationByApplyingConfiguration:
665
+ [NSImageSymbolConfiguration configurationWithHierarchicalColor:secondary]];
666
+ headerIcon = [headerIcon imageWithSymbolConfiguration:headerIconConfiguration];
667
+ NSTextAttachment *headerAttachment = [NSTextAttachment new];
668
+ headerAttachment.image = headerIcon;
669
+ const CGFloat headerIconSize = 13;
670
+ headerAttachment.bounds = NSMakeRect(0,
671
+ (headerFont.capHeight - headerIconSize) / 2.0, headerIconSize, headerIconSize);
672
+ NSMutableAttributedString *header = [[NSMutableAttributedString alloc]
673
+ initWithAttributedString:[NSAttributedString
674
+ attributedStringWithAttachment:headerAttachment]];
675
+ [header appendAttributedString:[[NSAttributedString alloc]
676
+ initWithString:@" " attributes:headerAttributes]];
677
+ [header appendAttributedString:[[NSAttributedString alloc]
678
+ initWithString:cell[@"label"] attributes:headerAttributes]];
679
+ [header drawInRect:NSMakeRect(x + 24, NSMinY(summary) + 89,
680
+ NSWidth([self logicalSummaryCellRectAtIndex:index]) - 48, 18)];
594
681
  for (NSDictionary *row in rows) {
595
682
  NSDictionary *usage = row[@"usage"];
596
683
  NSColor *rowColor = row[@"color"];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-pets",
3
- "version": "1.2.6",
3
+ "version": "1.2.8",
4
4
  "description": "A native macOS desktop pet for Codex CLI and Claude Code",
5
5
  "author": "wangxinyusqn",
6
6
  "license": "MIT",
package/scripts/build.sh CHANGED
@@ -37,6 +37,7 @@ CLANG_MODULE_CACHE_PATH="${CACHE_DIR}" clang \
37
37
  -framework Cocoa \
38
38
  -framework CoreServices \
39
39
  -framework ImageIO \
40
+ -framework IOKit \
40
41
  -framework QuartzCore \
41
42
  -framework UserNotifications \
42
43
  "${SOURCES[@]}" \