feat(menubar): 完善首排监控卡片与温度风扇采样

补充 GPU 渲染分块、内存与利用率统计,增加只读 SMC 温度及风扇信息和旋转动效。完善电池功率与耗电进程列表,统一首排布局并固定异步加载区域高度。同步验证用例、架构说明和 GPU 能力调研工具。
This commit is contained in:
2026-11-03 16:42:09 +08:00
parent 45a6e16bb8
commit cc38066de2
43 changed files with 2658 additions and 536 deletions
+92
View File
@@ -0,0 +1,92 @@
"""Read-only GPU discovery; run manually with python3, outside the app sandbox.
Enumerates names, not private counter semantics. A matching name is a research
candidate, never proof of per-core utilization. Does not create subscriptions,
submit GPU work, request root, or collect process/application information.
"""
import ctypes as C
import json
import plistlib
import subprocess
from collections import Counter
def command(*args):
return subprocess.check_output(args, timeout=60)
def registry_devices():
roots = plistlib.loads(command("ioreg", "-a", "-r", "-c", "IOAccelerator", "-d", "0"))
if isinstance(roots, dict):
roots = [roots]
keys = ("model", "gpu-core-count", "GPUConfigurationVariable", "PerformanceStatistics",
"GPURawCounterBundleName", "GPURawCounterPluginClassName")
return [{k: n[k] for k in keys if k in n} for n in roots]
def ioreport_channels():
cf = C.CDLL("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
io = C.CDLL("/usr/lib/libIOReport.dylib")
io.IOReportCopyAllChannels.argtypes = [C.c_uint64, C.c_uint64]
io.IOReportCopyAllChannels.restype = C.c_void_p
cf.CFPropertyListCreateData.argtypes = [C.c_void_p, C.c_void_p, C.c_long, C.c_ulong, C.c_void_p]
cf.CFPropertyListCreateData.restype = C.c_void_p
cf.CFDataGetLength.argtypes = [C.c_void_p]
cf.CFDataGetLength.restype = C.c_long
cf.CFDataGetBytePtr.argtypes = [C.c_void_p]
cf.CFDataGetBytePtr.restype = C.c_void_p
cf.CFRelease.argtypes = [C.c_void_p]
channels = io.IOReportCopyAllChannels(0, 0)
if not channels:
raise RuntimeError("IOReportCopyAllChannels returned nil")
data = None
try:
data = cf.CFPropertyListCreateData(None, channels, 100, 0, None)
if not data:
raise RuntimeError("IOReport channel serialization failed")
report = plistlib.loads(C.string_at(cf.CFDataGetBytePtr(data), cf.CFDataGetLength(data)))
all_channels = report.get("IOReportChannels", [])
selected = []
for channel in all_channels:
driver = channel.get("DriverName", "").split(" <id ")[0]
group = channel.get("IOReportGroupName", "")
subgroup = channel.get("IOReportSubGroupName", "")
legend = channel.get("LegendChannel", [])
name = str(legend[2]) if len(legend) > 2 else ""
if any(term in " ".join((driver, group, subgroup, name)).lower()
for term in ("gpu", "agx", "gfx")):
selected.append(dict(driver=driver, group=group, subgroup=subgroup, name=name))
counts = Counter((x["driver"], x["group"], x["subgroup"]) for x in selected)
return dict(totalChannels=len(all_channels), gpuRelatedChannels=len(selected),
groups=[dict(driver=d, group=g, subgroup=s, count=n)
for (d, g, s), n in sorted(counts.items())], channels=selected)
finally:
if data:
cf.CFRelease(data)
cf.CFRelease(channels)
def metal_counters():
source = '''import Foundation
import Metal
let devices: [[String: Any]] = MTLCopyAllDevices().map { device in
["name": device.name, "counterSets": (device.counterSets ?? []).map { set in
["name": set.name, "counters": set.counters.map { $0.name }] as [String: Any]
}]
}
let data = try JSONSerialization.data(withJSONObject: devices, options: [.sortedKeys])
print(String(decoding: data, as: UTF8.self))
'''
return json.loads(command("xcrun", "swift", "-e", source))
if __name__ == "__main__":
result = {"os": command("sw_vers").decode().strip(), "scope": "unsandboxed discovery only"}
for key, probe in (("registry", registry_devices), ("ioreport", ioreport_channels),
("metal", metal_counters)):
try:
result[key] = probe()
except (AttributeError, OSError, RuntimeError, ValueError, subprocess.SubprocessError) as error:
result[key] = {"error": str(error)}
print(json.dumps(result, ensure_ascii=False, indent=2))
+37
View File
@@ -0,0 +1,37 @@
// Bounded, self-contained workload for Instruments validation (not app code).
// swiftc tools/gpu_compute_probe.swift -o /tmp/kymo-gpu-compute-probe
import Foundation
import Metal
guard let device = MTLCreateSystemDefaultDevice(), let queue = device.makeCommandQueue() else {
fatalError("Metal device/queue unavailable")
}
let source = """
#include <metal_stdlib>
using namespace metal;
kernel void probe(device float *values [[buffer(0)]], uint index [[thread_position_in_grid]]) {
float value = float(index) * 0.0001f;
for (uint i = 0; i < 512; ++i) value = sin(value) * 0.99f + 0.01f;
values[index] = value;
}
"""
let library = try device.makeLibrary(source: source, options: nil)
let pipeline = try device.makeComputePipelineState(function: library.makeFunction(name: "probe")!)
let count = 65_536
let buffer = device.makeBuffer(length: count * MemoryLayout<Float>.stride, options: .storageModeShared)!
let start = ProcessInfo.processInfo.systemUptime
var completed = 0
while ProcessInfo.processInfo.systemUptime - start < 3 {
let command = queue.makeCommandBuffer()!
let encoder = command.makeComputeCommandEncoder()!
encoder.setComputePipelineState(pipeline)
encoder.setBuffer(buffer, offset: 0, index: 0)
encoder.dispatchThreads(MTLSize(width: count, height: 1, depth: 1),
threadsPerThreadgroup: MTLSize(width: min(256, pipeline.maxTotalThreadsPerThreadgroup), height: 1, depth: 1))
encoder.endEncoding()
command.commit()
command.waitUntilCompleted()
guard command.status == .completed else { fatalError("GPU command failed: \(String(describing: command.error))") }
completed += 1
}
print("GPU probe completed \(completed) commands")
+22
View File
@@ -0,0 +1,22 @@
// Diagnostic interposer for our standalone probe ONLY. Observes the raw-counter
// driver's calls, forwards every argument unchanged, and returns the real status.
// clang -dynamiclib -framework IOKit tools/gpu_driver_call_trace.c -o /tmp/kymo-gpu-call-trace.dylib
#include <IOKit/IOKitLib.h>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
static kern_return_t traceStructCall(mach_port_t connection, uint32_t selector,
const void *input, size_t inputSize,
void *output, size_t *outputSize) {
kern_return_t status = IOConnectCallStructMethod(connection, selector, input, inputSize, output, outputSize);
if (selector == 0x105) {
fprintf(stderr, "{\"event\":\"rawCounterDriverCall\",\"euid\":%u,\"selector\":%u,\"inputBytes\":%zu,\"status\":\"0x%08x\"}\n",
geteuid(), selector, inputSize, status);
}
return status;
}
__attribute__((used)) static const struct { const void *replacement; const void *original; }
interposeStructCall __attribute__((section("__DATA,__interpose"))) = {
(const void *)traceStructCall, (const void *)IOConnectCallStructMethod
};
+75
View File
@@ -0,0 +1,75 @@
// Research only: enumerate Apple's private counter descriptors, never start sampling.
// clang -fobjc-arc -framework Foundation -framework IOKit -framework Metal tools/gpu_raw_counter_probe.m -o /tmp/kymo-gpu-raw-probe
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import <Metal/Metal.h>
#import <dlfcn.h>
#import <unistd.h>
@interface NSObject (KymoRawCounterDiscovery)
- (instancetype)initWithAcceleratorPort:(io_service_t)port;
- (NSArray *)sourceList;
- (NSArray *)availableCounters;
- (NSString *)name;
- (io_service_t)acceleratorPort;
@end
int main(void) {
@autoreleasepool {
void *bundle = dlopen("/System/Library/Extensions/AGXGPURawCounterBundle.bundle/Contents/MacOS/AGXGPURawCounterBundle", RTLD_LAZY);
Class type = NSClassFromString(@"AGXGPURawCounterSourceGroup");
if (!bundle || !type) { fprintf(stderr, "Raw counter plugin unavailable\n"); return 1; }
io_iterator_t iterator = 0;
if (IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &iterator) != KERN_SUCCESS) return 2;
NSMutableArray *devices = [NSMutableArray array];
io_service_t service;
while ((service = IOIteratorNext(iterator))) {
io_connect_t connection = IO_OBJECT_NULL;
@try {
id group = [[type alloc] initWithAcceleratorPort:service];
// Also test the standard type-0 device connection; do not guess
// privileged user-client types or enable performance collection.
kern_return_t openStatus = KERN_SUCCESS;
BOOL serviceInitialized = group != nil;
if (!group) {
openStatus = IOServiceOpen(service, mach_task_self(), 0, &connection);
if (openStatus == KERN_SUCCESS) group = [[type alloc] initWithAcceleratorPort:connection];
}
BOOL connectionInitialized = group != nil;
uint64_t registryID = 0;
IORegistryEntryGetRegistryEntryID(service, &registryID);
NSArray<id<MTLDevice>> *metalDevices = MTLCopyAllDevices();
BOOL metalPortAttempted = NO;
for (id device in metalDevices) {
if (!group && (metalDevices.count == 1 || [device registryID] == registryID) && [device respondsToSelector:@selector(acceleratorPort)]) {
metalPortAttempted = YES;
group = [[type alloc] initWithAcceleratorPort:[device acceleratorPort]];
}
}
NSMutableArray *sources = [NSMutableArray array];
for (id source in [group sourceList]) {
NSMutableArray *counters = [NSMutableArray array];
for (id counter in [source availableCounters]) {
[counters addObject:@{@"name": [counter name] ?: @"", @"description": [counter description] ?: @""}];
}
[sources addObject:@{@"name": [source name] ?: @"", @"counters": counters}];
}
[devices addObject:@{@"serviceInitialized": @(serviceInitialized), @"connectionInitialized": @(connectionInitialized), @"metalPortAttempted": @(metalPortAttempted), @"initialized": @(group != nil), @"type0OpenStatus": @(openStatus), @"sources": sources}];
group = nil;
} @catch (NSException *exception) {
[devices addObject:@{@"error": exception.reason ?: exception.name}];
} @finally {
if (connection != IO_OBJECT_NULL) IOServiceClose(connection);
IOObjectRelease(service);
}
}
IOObjectRelease(iterator);
NSError *error = nil;
NSDictionary *report = @{@"uid": @(getuid()), @"euid": @(geteuid()),
@"devices": devices};
NSData *data = [NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingPrettyPrinted error:&error];
if (!data) { fprintf(stderr, "%s\n", error.description.UTF8String); return 3; }
puts([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding].UTF8String);
}
return 0;
}