diff --git a/SMARTService/main.swift b/SMARTService/main.swift index 34003e6..0ff75be 100644 --- a/SMARTService/main.swift +++ b/SMARTService/main.swift @@ -1,12 +1,42 @@ import Foundation +private actor CPUTemperatureReader { + private let monitor = CPUTemperatureMonitor() + private let gpuMonitor = CPUTemperatureMonitor(zone: .gpu) + func sampleFans() -> [Double?]? { monitor.sampleFans() } + func sampleGPU() -> Double? { gpuMonitor.sample() } + + func sample() -> Double? { + monitor.sample() + } +} + final class SMARTService: NSObject, SMARTServiceProtocol { + private let temperatureReader = CPUTemperatureReader() + + func readGPUTemperature(withReply reply: @escaping (NSNumber?) -> Void) { + Task { reply(await temperatureReader.sampleGPU().map(NSNumber.init(value:))) } + } + + func readFanSpeeds(withReply reply: @escaping ([NSNumber]?) -> Void) { + Task { + // Negative sentinel preserves an unavailable fan's position; never presented as RPM. + reply(await temperatureReader.sampleFans()?.map { NSNumber(value: $0 ?? -1) }) + } + } + func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void) { Task { let result = await DiskSMARTReader.readReport() reply(result?.remainingLife.map(NSNumber.init(value:)), result?.powerOnHours.map(NSNumber.init(value:))) } } + + func readCPUTemperature(withReply reply: @escaping (NSNumber?) -> Void) { + Task { + reply(await temperatureReader.sample().map(NSNumber.init(value:))) + } + } } final class ServiceDelegate: NSObject, NSXPCListenerDelegate { diff --git a/docs/architecture.md b/docs/architecture.md index f3408d8..b1cb4cb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -40,7 +40,7 @@ Kymo 是一款 macOS 菜单栏常驻的资源监控工具,设计目标为「 仓库创建唯一 Task,调用 `SystemSampler` actor,在后台串行读取 `CPUMonitor`、 `MemoryMonitor` 与 `getloadavg`,返回 Sendable `MetricsSnapshot`,再回 MainActor 整体发布。 每次采样完成后等待当前间隔,不重叠快速采样。SamplingPreferences 以毫秒整数分别保存面板/后台间隔,100ms 步进、500ms–1800000ms,非法值归一化。前者在面板顶栏调整,后者在设置监控页调整。频率或可见性变化取消旧等待、递增快速快照发布代次并重排,不重置差分基线;改频率按上次发布时间计算新截止时刻,避免立即重复读取;开面板仍立即刷新。未生效一侧偏好改变不唤醒当前调度。暂停优先于频率和可见性,恢复重新建立基线。 -SystemSampler 统一协调 SMART、电池健康、卷列表与进程的单次在途任务,快速链路不等待其完成;SMART/电池健康结果带时间戳,成功一小时、失败十分钟后重试,卷列表约三十秒刷新。任务完成清空在途槽;取消/隐藏不释放尚未结束的同步查询槽,不无限补发。 +SystemSampler 统一协调 SMART、电池健康、CPU 温度、卷列表与进程的单次在途任务,快速链路不等待其完成;SMART/电池健康结果带时间戳,成功一小时、失败十分钟后重试,卷列表约三十秒刷新,CPU 温度成功两秒、失败六十秒后重试。任务完成清空在途槽;取消/隐藏不释放尚未结束的同步查询槽,不无限补发。 进程通过 sysctl 枚举并逐项读取 proc_taskallinfo/proc_pidpath;PID + 启动秒/微秒为身份,读取前后核对枚举身份,未知字段独立降级。CPU 计时为纳秒差分,单核 100%,RSS 不等同活动监视器内存。只在面板可见且未暂停时采样;关闭清空快照、监控器基线与缓存,迟到结果按代次拒绝,重新打开重建基线;其他用户受限行保留覆盖说明。Store 另以发布/可见性代次防止暂停或快速开关后发布旧结果。进程单次在途完成后通过 Sendable 回调立即发布当前可见性/暂停代次结果,纯改频率不丢弃有效在途进程结果,不等待可能长达 30min 的下一周期,不追加图表历史或新建轮询;快速快照保留同周期已先到的进程结果,防止覆盖为 nil。若快速关开时旧同步读取仍占在途槽,旧结果结束后接续最新可见代次的待办查询,不等下一长周期,仍仅一次在途。 菜单栏由 Features/MenuBar 的 MenuPanelController 持有 NSStatusItem,仅显示模板 BrandMark。点击图标切换同一 NSPanel,所属屏幕优先按菜单栏按钮选择,水平居中、顶部留边并限制在 visibleFrame 内。NSPanel 允许成为 key 而不成为 main,不因失焦自动隐藏。可见期间注册被动本地/全局鼠标监听,不拦截外部点击;普通状态外部点击/应用失活关闭,固定时使用 floating 层级并忽略外部关闭请求。菜单图标、Esc/Cmd+W 和进入设置可显式隐藏面板,固定状态保留到本次进程结束;shutdown 复位,不持久化。隐藏时拆卸内容并移除鼠标监听。App 只装配生命周期与服务,Features 之间不横向依赖。 @@ -49,22 +49,24 @@ Settings 保留 SwiftUI Settings 场景,App 在 applicationWillFinishLaunching CPU 以每核 Mach tick 差分计算,总占用按 tick 加权;首帧、恢复监控首帧及读取失败显示 `--`。 CPU 计数按 UInt32 回绕计算,`host_processor_info` 分配的缓冲区每次释放。 +CPU 温度由非沙盒 XPC 服务通过 IOKit `AppleSMC` 用户态只读枚举 `flt` 类型的 `Tp`/`Te` 区域传感器,过滤 0–150°C 后取最高有效值;它是可用区域传感器热点的代理,不是 Apple 公开的封装温度或逐核心温度。签名沙盒主应用直接访问该接口会被系统拦截,因此 Core 通过固定、无参数的 XPC 查询取数。AppleSMC 连接或传感器不可用时数据保持 `nil`,面板隐藏温度胶囊;达到 90°C 时 CPU 标题图标、标题与温度胶囊转为红色并显示“温度过高”。 内存已用口径为 `max(internal - purgeable, 0) + wired + compressor`,上限为物理内存。 Swap 和压力通过 sysctl 分别读取,失败仅令对应子项为空;压力不由占用率推算。 -GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取单设备总体利用率;有限值须落在 0–100 才归一化,缺失/多设备降级未知。gpu-core-count 只代表拓扑,不代表可读每核利用率;当前没有独立每核数据。旧 IOReport 订阅失败记录保留,不能据此否定已验证的注册表总体路径。 +GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取单设备总体利用率;有限值须落在 0–100 才归一化,缺失/多设备降级未知。gpu-core-count 只代表拓扑,不代表可读每核利用率;当前没有独立每核数据。旧 IOReport 订阅失败记录保留,不能据此否定已验证的注册表总体路径。 2026-11-03 的独立命令行探针重新枚举 IOReport 与 Metal,并尝试 RawCounter 初始化,仍未获得逐核数值;第二轮确认 RawCounter 初始化返回 kIOReturnNotPrivileged,euid=0 仍拒绝;探针不进入产品 Target、不改变正式采样链路,证据及未来接入门槛见 [GPU 逐核心调查](gpu-per-core-investigation.md)。 网络、存储、电池及磁盘 SMART 已接入采样与面板;磁盘 SMART 通过签名的辅助 XPC 在 应用沙盒外读取,失败时显示 `--`。 ### 面板、历史与外观 -- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含上/下行和设备读/写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线;breakBefore 标记只在首次/暂停恢复处断开;每个样本及分接口历史保留自己的预期间隔,改频率不插入人为断点。60 点代表样本数,时间跨度随真实间隔变化。 -- 当前正式入口为统一 `MenuPanelView`:第一排 CPU/GPU/电池,电池宽高比 4:3、CPU/GPU 均分余宽;第二排内存/存储/网络等宽。宽度按所属屏幕 visibleFrame 限制在 1240pt 内,高度上限 820pt;≥1160pt 三列、≥900pt 两列、其他单列。三列且高度至少 810pt 时两排完整布局,参考尺寸两排分别 230/240pt,进程区使用剩余空间(最小 170pt)。其他尺寸资源独立滚动,进程常驻;三列低高度仍保持上述比例与顺序。原生 Table 自带纵横滚动与单元格复用,不在资源滚动容器内。首次布局计入屏幕与窗口 chrome,布局后约束完整 frame 原点并水平居中。NSPanel 固定/关闭策略和 key/main 资格已有独立检查;实际外部点击与多屏专项待补。 +- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含 CPU、GPU、内存、电量、电池功率、网络上下行和设备读写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线;breakBefore 标记只在首次/暂停恢复处断开;每个样本及分接口历史保留自己的预期间隔,改频率不插入人为断点。60 点代表样本数,时间跨度随真实间隔变化。 +- 当前正式入口为统一 `MenuPanelView`:第一排 CPU/GPU/电池等宽,第二排内存/存储/网络等宽。宽度按所属屏幕 visibleFrame 限制在 1240pt 内,高度上限 820pt;≥1160pt 三列、≥900pt 两列、其他单列。三列且高度至少 810pt 时两排完整布局;第一排在 CPU 核心占两行时参考高度约 239pt,不预留第三行空间,只有实际需要第三行核心时再扩展到约 265pt;第二排保持 240pt。进程区使用剩余空间(最小 170pt)。其他尺寸资源独立滚动,进程常驻;三列低高度仍保持上述等宽比例与顺序。原生 Table 自带纵横滚动与单元格复用,不在资源滚动容器内。首次布局计入屏幕与窗口 chrome,布局后约束完整 frame 原点并水平居中。NSPanel 固定/关闭策略和 key/main 资格已有独立检查;实际外部点击与多屏专项待补。 - `PanelWindowObserver` 仅观察所属窗口的屏幕/移动/缩放,测量尺寸并约束居中;可见性由 MenuPanelController 开关与内容挂载生命周期通知 Store,不根据失焦推断关闭。 - CPU 逻辑核心类型在启动后按需从 IODeviceTree 的 `logical-cpu-id` 与 `cluster-type` 一次读取并缓存,按编号关联 Mach 采样结果;E、M、P 分别对应较低、中间和较高等级。存在 M 时 P 显示为超性能核,否则 P 显示为性能核。未知字段或无法读取时保持中性色,不依据核心顺序或数量推断;此设备树字段并非稳定的公开分类接口。卡片图例与辅助功能说明类型,核心进度条按采样平滑变化并遵循减少动态效果。底部标注开机运行时间;负载展示最近 1 分钟的原始平均值和逻辑核心数,进度条以核心数为满刻度,超出时只裁剪图形、保留原始数值,不把负载解释为 CPU 占用率。 -- CPU 核心按可用宽度优先均分两行,空间不足时均分三行,每行数量相差不超过一;更多核心通过收紧间距和缩短条形适配,极窄空间下核心编号也会缩小。核心条仍保持各自的颜色、辅助功能和动画。 -- `PanelTrendChart` 只接收时间戳、最多三序列、颜色/量纲/图例文本;Canvas 按真实时间定位,带三段刻度、网格和独立分段面积。CPU 同时绘制总体/用户/系统,网络上下行、存储读写共用量级。曲线使用相邻点间不超调的三次贝塞尔;缺失值、显式中断标记和超过 max(5s, 相邻样本预期间隔较大值×2) 的间隙断线。图例始终显示最新值;悬浮时使用独立浮层显示历史时刻与各序列值,保留游标/交点,不覆盖图例数据。图表通过 Anchor Preference 上报绘图区锚点、悬浮位置与内容,ResourceCard 在卡片最外层 overlay 统一绘制浮层,避免局部 zIndex 无法越过时间刻度/卡片字段;按实际本地化内容尺寸测量并约束在卡片内。浮层不参与鼠标命中,不创建顶层窗口;背景使用 NSVisualEffectView 的 popover/withinWindow 材质模糊下方内容,轻叠资源色,减少透明度时回退实色;原生材质视图也透传鼠标。CPU 使用青绿/紫红/金色区分,所有数据序列统一使用圆滑实线,未知仍为 --。真实追加时只运行一次 0.35 秒时间轴平移/新点揭示;UI 渲染帧最多保留 61 点,包含一个移出样本,旧首尾域连续插值到新首尾域,左端线段随动画裁出,不能先删除左端点。动画任务由提交后的帧状态触发,无独立 Timer 或后台循环;暂停间隙与重置不插值,减少动态效果时立即更新。CPU/GPU/电量固定 0–100%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。 -- 各卡标题与彩色主值均为 13pt、共享基线同行,数值组件复用系统 numericText 数字翻动/模糊过渡并遵循减少动态效果;进程行不施加该动画。PanelBackground / PanelCard 深浅色均为不透明实色,主面板与按钮组不使用玻璃材质;NSPanel 保留透明窗口壳仅用于圆角外部。深色强调色为薄荷青 #35D6BD、莓粉 #F56DA6、嫩绿 #93D45B、晴蓝 #6FA0FF、暖金 #FFC15A、浅紫 #BE8AFF,浅色提供同色相较深版本以保证可读性。网络下载/上传为蓝/金,存储读/写为金/紫,CPU 总体/用户/系统为青/粉/金;图表浮窗及原生控件弹窗继续使用模糊材质,遵循减少透明度设置。操作强调色仍由偏好决定;刷新控件、图钉、保持唤醒、暂停/恢复、设置、退出胶囊位于顶栏右侧。顶栏左侧为品牌、版本及缓存的本机产品名/芯片,产品名不可读时退回 hw.model,不读取序列号。原采样状态/更新时间与底栏移除。 +- CPU 核心按真实类型分区,依次显示能效、中间、性能及未知类型;每组保留实际核心数量,不推断缺失拓扑。分区按两行所需列数比例分配可用宽度,组内优先均分两行,单元宽低于 16pt 时使用三行,更多核心缩小圆环;所有分区统一使用最小可用圆环直径。高度与首排扩展按各分区实际最大行数计算,不预留第三行。每核中央显示百分比、不显示编号,辅助功能与悬浮说明保留编号;进度动画遵循减少动态效果。CPU 卡片通过细分隔线区分曲线、核心与底部状态,底部负载使用标签与数值同行、下方圆角条,运行时间独立一列。 +- `PanelTrendChart` 只接收时间戳、最多三序列、颜色/量纲/图例文本;Canvas 按真实时间定位,带三段刻度、网格和独立分段面积。CPU 同时绘制总体/用户/系统,用户与系统实时值只保留在图表图例,不在下方重复展示;网络上下行、存储读写共用量级。曲线使用相邻点间不超调的三次贝塞尔;缺失值、显式中断标记和超过 max(5s, 相邻样本预期间隔较大值×2) 的间隙断线。图例始终显示最新值;悬浮时使用独立浮层显示历史时刻与各序列值,保留游标/交点,不覆盖图例数据。图表通过 Anchor Preference 上报绘图区锚点、悬浮位置与内容,ResourceCard 在卡片最外层 overlay 统一绘制浮层,避免局部 zIndex 无法越过时间刻度/卡片字段;按实际本地化内容尺寸测量并约束在卡片内。浮层不参与鼠标命中,不创建顶层窗口;背景使用 NSVisualEffectView 的 popover/withinWindow 材质模糊下方内容,轻叠资源色,减少透明度时回退实色;原生材质视图也透传鼠标。CPU 使用青绿/紫红/金色区分,所有数据序列统一使用圆滑实线,未知仍为 --。真实追加时只运行一次 0.35 秒时间轴平移/新点揭示;UI 渲染帧最多保留 61 点,包含一个移出样本,旧首尾域连续插值到新首尾域,左端线段随动画裁出,不能先删除左端点。动画任务由提交后的帧状态触发,无独立 Timer 或后台循环;暂停间隙与重置不插值,减少动态效果时立即更新。CPU/GPU/电量固定 0–100%,内存按物理总字节;动态量级扩大立即,缩小连续十次低于一半后调整。 +- 电池趋势同时绘制 0–100% 电量与瓦特功率;功率序列使用独立自动量级和右侧刻度,避免百分比与 W 共用纵轴。图例和悬浮值分别按百分比与 W 格式化。电池卡下方保留两行摘要:健康度/循环次数、电源类型/续航预估;随后以紧凑列表显示 CPU 占用最高的 3 个进程,每行包含运行应用或可执行文件图标、名称和 CPU 占用。该列表是可观测代理,数据尚未完成或不可读时显示等待状态,不宣称等同于系统能耗评分。 +- 各卡标题与彩色主值均为 13pt、垂直居中对齐同一行,温度胶囊与告警文案也共享该中线;数值组件复用系统 numericText 数字翻动/模糊过渡并遵循减少动态效果,进程行不施加该动画。PanelBackground / PanelCard 深浅色均为不透明实色,主面板与卡片不使用玻璃材质;顶栏操作胶囊使用系统液态玻璃材质,NSPanel 保留透明窗口壳仅用于圆角外部。深色强调色为薄荷青 #35D6BD、莓粉 #F56DA6、嫩绿 #93D45B、晴蓝 #6FA0FF、暖金 #FFC15A、浅紫 #BE8AFF,浅色提供同色相较深版本以保证可读性。网络下载/上传为蓝/金,存储读/写为金/紫,CPU 总体/用户/系统为青/粉/金;图表浮窗及原生控件弹窗继续使用模糊材质,遵循减少透明度设置。操作强调色仍由偏好决定;刷新控件、图钉、保持唤醒、暂停/恢复、设置、退出胶囊位于顶栏右侧。顶栏左侧为品牌与右上角小号版本号,经竖线与缓存的本机产品名/芯片分隔,产品名不可读时退回 hw.model,不读取序列号。原采样状态/更新时间与底栏移除。 - NetworkPathObserver 从系统路径的偏好首位接口提供默认接口名称([NWPath 接口按偏好排序](https://developer.apple.com/documentation/network/nwpath)),网络卡默认直接展示该接口的 IPv4,若无则展示 IPv6;未知不随意选择另一个接口。手动切换接口时同步展示该接口地址。getifaddrs 元数据、接口速率和路径状态仍独立采集;不把接口 IP 当作公网出口地址。 - 进程表支持 CPU/内存(RSS)排序、名称/PID/路径搜索、同卡内选中路径展示/复制与读取覆盖计数。投影按采样/筛选/排序事件计算并缓存,不在 body 或滚动中重复排序;hover、搜索/焦点和选中冻结旧身份顺序,新增项追加到其后。完整路径在表下方同卡展示以保持固定行高;选中进程退出短暂提示后移除,关闭面板拆卸表并清掉路径状态。路径不持久化,不收集参数或环境变量。 - 旧 MetricRow / HoverDetailPresenter / DetailPlacement 与旧迷你趋势源码暂保留作迁移参照,正式面板已无调用;待真实 UI 回归后在 P6 清理并同步其历史检查程序,不能把源码存在理解为仍有双套交互。 @@ -127,12 +129,12 @@ RSS 与物理足迹分别报告;50 MB 目标在口径确认和长期验证前 - 网络改为 `sysctl NET_RT_IFLIST2 / if_msghdr2` 64 位计数,边界检查消息长度并最多重试三次列表扩容;接口增删/计数回退重新建立差分。只汇总 en 链路,不统计隧道,不能代表所有 VPN/虚拟接口流量。 - `NetworkPathObserver` 持有 NWPathMonitor,回调只在 NSLock 下更新路径状态,统一采样器读取快照。生命周期释放时取消,不生成采样 Timer;暂停时路径观察仍存在,但暂停快照不发布。路径可用不能证明互联网服务可访问。 - `DiskIOMonitor` 在同一 actor 中持有块设备 registry ID 与字节基线;设备集合变化、初次、回退时本轮速率未知。统计全部可读 IOBlockStorageDriver,不冒充某卷流量。卷列表每 30 秒枚举可见本地卷,不求和 APFS 共享空间。 -- 电池基础状态和时间由 Power Sources 读取,AppleSmartBattery 补循环;最大容量采用下述缓存系统报告口径,不再计算原始容量比。 +- 电池基础状态和时间由 Power Sources 读取,AppleSmartBattery 补循环、电压与瞬时电流;功率为两者乘积的绝对值,使充电和放电都能在同一非负趋势上比较,方向由图例和当前电源状态说明。电压、电流缺失或越界为 nil。最大容量采用下述缓存系统报告口径,不再计算原始容量比。 - MetricHistory 为网络下载、主卷占用、电量保留同样 60 点;网络图按当前历史峰值(下限 1 KB/s)缩放,不代表百分比。网络与卷详情限定 280pt 并可滚动。C 诊断字段仅在 KYMO_DIAGNOSTICS=1 时写出。 ### C 第三轮口径与降级修正 -电池仅展示系统报告最大容量,不再展示原始容量比与算法说明。续航先取 Power Sources 字典分钟数,放电时以 IOPSGetTimeRemainingEstimate 秒数作兜底;外接电源/未知值不生成伪预估。网络与磁盘详情共用 Core 的 MetricFormat.rate 十进制单位换算。用户确认的本机电源热插拔、网络开关和详情滚动仅关闭对应交互专项。 +电池仅展示系统报告最大容量,不再展示原始容量比与算法说明。续航先取 Power Sources 字典分钟数,放电时以 IOPSGetTimeRemainingEstimate 秒数作兜底;外接电源/未知值不生成伪预估。网络与磁盘详情共用 Core 的 MetricFormat.rate 十进制单位换算。电池功率由 AppleSmartBattery 的 mV 与 mA 计算为 W,并经过合理范围过滤;高能耗进程复用面板可见期间的进程 CPU 快照,关闭面板后不额外查询。 ### 系统报告健康度(替代原始容量比) @@ -142,7 +144,7 @@ RSS 与物理足迹分别报告;50 MB 目标在口径确认和长期验证前 DiskHealthMetrics 为 Core 模型,DiskHealthMonitor actor 由 SystemSampler 调用,缓存一小时(失败十分钟),通过 SMARTServiceClient 连接随应用嵌入的 SMARTService.xpc。直接沙盒查询返回空字典的问题已改由用户授权的独立非沙盒服务解决。只保留预计剩余寿命与通电小时;未读取/不支持为 --,多物理设备卷不合成单值。 -SMARTService/ 是独立 Target,不属于 kymo/ 的同步源码目录。共享最小协议 SMARTServiceProtocol、CodeIdentity、DiskHealthMetrics、纯解析 DiskHealthReport;不依赖 Features/UI。主应用继续 App Sandbox,XPC 服务以当前用户权限按需启动、非沙盒,无 root、LaunchAgent 或开机项。固定查询用户目录所属卷挂载点的 diskutil info -plist,不接受来自客户端的路径、命令或可写操作,只返回 NSNumber 形式的寿命/小时,不返回完整报告。 +SMARTService/ 是独立 Target,不属于 kymo/ 的同步源码目录。共享最小协议 SMARTServiceProtocol、CodeIdentity、CPU 区域温度读取器、DiskHealthMetrics 与纯解析 DiskHealthReport;不依赖 Features/UI。主应用继续 App Sandbox,XPC 服务以当前用户权限按需启动、非沙盒,无 root、LaunchAgent 或开机项。服务只有两个固定只读操作:无参数读取 CPU 区域温度;查询用户目录所属卷挂载点的 diskutil info -plist。不接受来自客户端的路径、命令或可写操作;磁盘查询只返回 NSNumber 形式的寿命/小时,不返回完整报告。 连接两侧设置代码签名要求:客户端由嵌入服务的 designated requirement 校验服务;服务由宿主应用的 designated requirement 校验调用方,且 uid 必须相同。无法取得要求时拒绝服务;支持本地 ad-hoc Debug 签名,不使用标识字符串白名单代替签名。客户端在回复/中断/错误/15 秒超时竞争时用锁保证 continuation 只恢复一次,失效后释放连接;服务内部查询十秒终止。无额外轮询 Timer。Xcode 构建依赖与 Embed XPC Services 阶段负责先构建、签名并嵌入服务。 @@ -154,7 +156,7 @@ App 持有进程级 `KeepAwakeService`(Core/Services,MainActor + Observable 状态不持久化,重启默认关闭;关闭面板、暂停资源采样均不影响已开启的保持唤醒,无额外定时器、辅助进程或权限变更。主动锁屏、主动睡眠、合盖、低电量保护与管理策略仍由系统决定;独立屏保/自动锁定策略的实际行为需在用户环境验收,不以电源断言创建成功替代锁屏实测。 -面板底部四个按钮置于一个原生 `.glassEffect(.regular, in: .capsule)` 液态玻璃胶囊内,各按钮采用圆形悬停/按压反馈,退出按钮前有分隔线;咖啡杯开启时使用当前强调色,并提供三语帮助及无障碍开关状态。 +面板顶栏右侧操作按钮置于一个原生 `.glassEffect(.regular, in: .capsule)` 液态玻璃胶囊内,各按钮采用圆形悬停/按压反馈,退出按钮前有分隔线;咖啡杯开启时使用当前强调色,并提供三语帮助及无障碍开关状态。 2026-10-30 验证:Debug 构建通过;独立核心检查在普通进程与带主应用沙盒权限的临时 .app 中均通过,实际查询本进程断言,覆盖默认关闭、连续三次开关、开启后两类断言存在、关闭/服务销毁后消失。CLI 检查器直接加沙盒签名会在 libsecinit 初始化阶段退出,改用完整 .app 包后通过,未更改产品权限。当前没有 Xcode 测试 Target。UI 自动化 getApp 本轮构建超时;本轮仅退出自动化启动的测试副本,保留用户 Xcode 进程。底部实际视觉、关闭面板后长时间空闲不锁屏/息屏以及关闭开关后恢复系统策略,待用户验收。 @@ -185,3 +187,21 @@ SystemSampler 在首次采样前仅当 `KYMO_PANEL_PROBE=1` 执行一次 PanelCa NET_RT_IFLIST2 吞吐枚举活动非 loopback 接口;总体只汇总活动 en 接口,VPN 等接口可独立查看但不计总体。getifaddrs 提供索引和本机 IPv4/IPv6,地址/活动状态改变、计数回退均重新建立速率基线;缺失不作为零。接口历史与总体历史分离,不请求公网地址。电池不存在与系统电源读取失败采用独立状态;健康查询异步完成后在下一次快照发布。 - `MetricProgressBar` 统一绘制每核心与进程 CPU 圆角进度条;有限值钳制到 0–1,非有限值按空轨道显示,零值不绘制填充。背景与填充整体按轨道 Capsule 裁剪,防止极窄填充超出圆角轨道。 + +### GPU 卡片补全 + +GPU 单设备快照新增 Renderer/Tiler 活跃度与驱动系统内存统计,历史保留阶段曲线,Core 依据真实时间计算最多一分钟的利用率平均/峰值(排除缺失/休眠/过长间隔)。GPU 温区沿用 AppleSMC 只读读取器,固定 Tg 前缀,经现有当前用户 XPC 的固定方法返回最高有效温区值;CPU/GPU 异步并发读取且缓存,不引入 daemon 或 root。界面不把流水线阶段相加、不把驱动内存等同独立显存。实现及限制见 `gpu-card-plan.md`。 + +### GPU 卡风扇融合(2026-11-03) +SMC 读取器新增固定 FNum/FnAc 只读查询(最多 10 个,支持 flt/fpe2,合法 RPM 为 0–30000);风扇连接不依赖 CPU 温度键是否存在。SMARTService 固定 readFanSpeeds 返回有序 NSNumber 数组,-1 仅作单个缺失的传输哨兵;Core 客户端验证并转换为 FanMetrics,不向 UI 泄露哨兵。SystemSampler 将风扇与温度并发查询、共同异步缓存,5 秒更新,全部通道失败时 60 秒重试;无 caller-supplied SMC key、无写入、无 root。 + +GPU 卡保留各项统计,以两行紧凑统计区和 46pt 曲线容纳底部风扇条;其他卡曲线默认仍为 58pt。双风扇左右是显示顺序,物理左右未经证实,悬浮帮助说明;单只或更多保留编号,多只按两列排布并增加所需行高。FanSpeedIndicator 仅接收标签/RPM,FanRotation 按速度档位累计旋转相位(30fps),切速不跳转,零/缺失/减少动态效果时停止时间线,无 Core→UI 依赖。 + +### GPU 统计图形化(2026-11-03) +ResourceCard 新增可选标题详情标签,GPU 核心数移到标题行,其他卡默认不显示。Features 的 GPUStatisticsView 接收驱动内存与利用率统计,内存双条使用 max(在用,分配,1字节) 共用参考尺度,不当作容量占比,帮助说明动态尺度语义。UI MetricRingGauge 仅接收标签/比例/颜色,显示平均和峰值百分比,有限值钳制到0–1,缺失保留--,遵守减少动态效果。统计区固定42pt以替代原文字区与核心数行;采样、历史统计、风扇与XPC数据流不变。 + +### 首排卡片对齐(2026-11-03) + +CPU、GPU、电池在三列及窄屏网格中共享显式行高:基础 260pt,CPU 需要第三行时增加 26pt,多风扇行按每行 19pt 扩展,取两者较大值。核心排布使用当前列数对应的实际卡片宽度计算。三张趋势图统一为 58pt 绘图区;标题、图例、图表下沿和首条分隔线保持一致。CPU 核心区与 GPU 统计区由上下弹性间距平衡,电池列表靠底;风扇区域不再提供悬浮帮助。采样与数据语义不变。 + +电池耗电进程区固定预留 72pt(标题及三行),等待采样、少量进程与完整 Top 3 使用相同尺寸;电池摘要固定 32pt,避免异步数据填入后其固有高度突破首排行高。 diff --git a/docs/gpu-card-plan.md b/docs/gpu-card-plan.md new file mode 100644 index 0000000..e6b6250 --- /dev/null +++ b/docs/gpu-card-plan.md @@ -0,0 +1,30 @@ +# GPU 卡片信息补全 + +## 目标与范围 +按获批单卡概念补齐 GPU 信息密度,保留实色卡片、三路曲线与圆角进度。涉及 Core 采样/模型/历史、只读 XPC、MenuBar 呈现和本地化;不加入逐核虚构数据或特权 daemon。 + +## 实施与数据契约(已实现) +1. IOAccelerator 读取总利用率、Renderer/Tiler 活跃度、驱动在用/分配系统内存;独立缺失、非法值返回 nil。保留单 GPU 门槛。 +2. 历史保留两项阶段序列。最近一分钟平均采用区间线性插值的时间积分,截取窗口边界;缺失、休眠边界与超过预期间隔 2.5 倍的空档不积分。峰值为窗口内已采样最大值。历史不足一分钟时仅统计已有历史。 +3. 现有 AppleSMC 只读读取器增加固定 GPU Tg 温区,复用签名校验 XPC。无调用者自定义键或写操作。CPU/GPU 并发读取、统一缓存(有任一有效结果每 5 秒,全部失败每 60 秒),主采样不等待。 +4. CPU/GPU 曲线改称总利用率。GPU 卡片展示温度胶囊、三路曲线、两阶段圆角条、驱动内存、平均/峰值和核心数;说明移入悬浮帮助以适应原有行高。 + +## 风险和兼容性 +SMC/IOAccelerator 均有非公开字段,跨机型缺失降级为 --;GPU 温度为最高有效温区读数,并非官方封装或逐核温度。驱动内存仅显示原始统计,不能解释为独立显存容量或驻留内存,不用分配量作为进度条分母。频率、功率与逐核指标仍不提供。保留原有 60 点历史容量,500ms 刷新时统计覆盖可小于一分钟,帮助明确说明。 + +## 验证 +GPUStatisticsChecks 覆盖时间加权、窗口截断、缺失、休眠、长间隔、历史序列与内存非法值,并采样真实 GPU/温区。Debug 构建、字符串 JSON 和 diff 检查;产品窗口、签名 XPC 新方法和实际动画需启动新版后验收,不将命令行裸读成功视为产品 XPC 已验证。 + +## 风扇融合实施计划(2026-11-03,已实现) +- Core:固定只读 FNum/FnAc,支持 flt 与 Intel fpe2,零转速保留、缺失独立表示,限制枚举数量与数值范围。 +- XPC/采样:固定风扇读取接口,不接受调用者传入键;复用签名校验、2 秒超时和后台缓存,不阻塞主采样。 +- UI:GPU 卡底部加入无标题风扇条;按左右排布标识,帮助明确其为显示位置(本机 F0ID/F1ID 缺失,物理左右尚未证实)。多于两只保留编号。0/缺失静止,非零按档位旋转,切速保持相位连续;减少动态效果时停转。 +- 布局:统计区压为两行,GPU 图表略压低,避免新增风扇挤出卡片。 +- 验证:构建、SMC 解码/零值/非法值/实时读取与动画速度及相位边界;实际面板和 XPC 回传分别记录。 + +验证结果:标准签名 Debug 构建、FanChecks、GPUStatisticsChecks、字符串 JSON 与 diff 检查通过;独立签名沙盒应用的实际 XPC 风扇回传通过。初次产品 UI 读取超时;后续用户自行运行新版后,通过 bundle ID 成功核验实际面板布局及非零RPM显示,动画手感仍需人工验收。 + +## 统计图形化调整(2026-11-03,已实现) +将核心数移到标题行独立小标签,删除原底部文字行。内存改为共享动态参考尺度的双横条,仅比较绝对字节值,不使用“在用/分配”容量百分比;缺失保持 --。近一分钟平均/采样峰值改为带数值圆环,保留统计帮助及减少动态效果。保持原有卡片预算,构建后验证布局。 + +图形化验证:标准 Debug 构建、JSON/diff 检查通过,370pt和280pt实际组件离屏渲染检查普通/低值/0/100%/缺失;整卡窗口及动效待新版运行验收。 diff --git a/docs/gpu-per-core-investigation.md b/docs/gpu-per-core-investigation.md new file mode 100644 index 0000000..a25a2f2 --- /dev/null +++ b/docs/gpu-per-core-investigation.md @@ -0,0 +1,83 @@ +# GPU 逐核心采样调查与实施门槛 + +## 目标与当前范围 + +用户要求读取真实的每个 GPU 核心数据。当前 `GPUMonitor` 仅读取单设备总体利用率与核心数;本轮先验证数据源,不用总体均分、渲染器/分块器比例或随机数生成核心指标。探针位于 `tools/`,不进入应用 Target、不增加后台轮询、不修改沙盒或系统权限。 + +## 2026-11-03 本机证据 + +环境:Apple M4 Pro、20 核 GPU、macOS 27.2(26B123)。以下探测运行于普通用户命令行,**不等于签名沙盒主应用验证**。 + +| 路径 | 实测 | 结论边界 | +| --- | --- | --- | +| IOAccelerator | `gpu-core-count=20`;`Device Utilization %`、`Renderer Utilization %`、`Tiler Utilization %` 可读 | 总体/流水线阶段;没有每个物理核心的独立利用率字段 | +| GPUConfigurationVariable | `num_cores=20`、`num_mgpus=2`、`core_mask_list=[1023,1023]` | 提供拓扑线索;掩码不是动态利用率,不能据此产生 20 份占用 | +| IOReportCopyAllChannels | 共 11,015 个通道,按 driver/group/subgroup/name 的 GPU/AGX/GFX 关键字筛出 417 个 | 已枚举,未对全部通道建立订阅或验证单位;未找到可确认对应 20 核的独立利用率 | +| GPU Stats | 频率状态、活跃/空闲直方图、温度、虚拟通道、降频等 | `Channel 0…3` 是 vChannel Usage,不能当物理核心;温度传感器也没有已验证逐核映射 | +| GPU UT AggD Stats | Min/Max/Sum/Count/Not_Engaged_Count 各 16 项,名称为 `Perf_State_0…15` | 按性能档位统计,非 16 个核心 | +| Metal counterSets | 唯一集合 `timestamp`,唯一计数器 `GPUTimestamp` | 本机公开接口未列出逐核忙闲计数器 | +| Xcode Instruments | 存在 GPU、Metal GPU Counters 等工具 | 工具存在不能证明可通过常驻监控 API 读取逐核系统利用率;未录制 trace | +| 私有 RawCounter 插件 | `AGXGPURawCounterBundle` 可加载、`AGXGPURawCounterSourceGroup` 存在;传 IOAccelerator service 初始化返回 nil;标准 type-0 IOServiceOpen 返回 `0x10000003`(invalid destination port);从唯一 Metal 设备的私有 `acceleratorPort` 获取端口后初始化同样返回 nil | 三种入口均未获得 sourceList;尚未确定正确连接契约,不能归因于缺少授权,也不能证明该框架永远不可用 | + +Apple 的 [Metal counter 文档](https://developer.apple.com/documentation/metal/gpu-counters-and-counter-sample-buffers) 描述在自身 pass/command 中插入采样并解析缓冲区;[Live GPU Profiling](https://developer.apple.com/videos/play/tech-talks/10001/) 同样展示 encoder 内插桩。这些接口文档未给出系统范围的逐核心占用读取契约。 + +当前结论:**目标未完成。已测试接口没有提供可以可靠交付的逐核心利用率;不扩大为所有 Mac 都无法获取。** 私有框架仍是未解的研究路径,不能以“先做 20 个圆环”代替数据获取。 + +## 可复现探针 + +```bash +python3 tools/gpu_capability_probe.py > /tmp/kymo-gpu-capabilities.json +clang -fobjc-arc -framework Foundation -framework IOKit -framework Metal tools/gpu_raw_counter_probe.m -o /tmp/kymo-gpu-raw-probe +/tmp/kymo-gpu-raw-probe +``` + +Python 探针枚举注册表白名单字段、IOReport GPU 相关通道名称、Metal 支持的集合,输出 JSON;失败独立写入 error,不伪装为空结果。RawCounter 探针只尝试初始化与描述符枚举,不调用 startSampling、enableCounters 或 requestCounters。均不输出用户进程、地址、路径、完整注册表。私有接口未来可能变化,探针失败不是产品运行失败。 + +本轮两个探针已运行;RawCounter helper 已编译。未修改产品源码,无需重新构建应用。未运行负载关联、逐核数值有效性、签名沙盒或长期能耗验证,因为尚未得到候选逐核数值源。 + +## 后续阶段与验收条件 + +1. **连接契约研究(未完成)**:确认 RawCounter 插件正确的 acceleratorPort 来源、资源生命周期和错误语义;只凭方法名猜连接类型不能成为产品实现。验证是否可枚举核心实例及 busy/total 时钟计数。 +2. **计数器语义(未开始)**:必须建立物理核心稳定标识与数量映射,确认是否为系统范围、单位、累计/瞬时、计数回绕、休眠与 DVFS 行为。用受控 Metal 工作负载对照总体和逐核变化;禁止将逐 pass 或阶段指标标成系统逐核指标。 +3. **跨模块接入(受前两步约束)**:Core 新增能力状态与可选逐核样本,沿 SystemSampler → MetricsSnapshot → Store → Features/MenuBar 传递;UI 按真实数量布局。需要权限或独立服务时先另写边界设计,不扩展 SMART 服务为通用驱动访问入口。未知、读取失败和硬件不支持分开表达。 +4. **验证(未开始)**:Core 边界检查、Debug 构建、签名沙盒实测、面板开关采样调度与资源释放、不同芯片/OS、长期资源消耗。私有接口必须支持运行时降级,且不影响已有总体利用率。 + +如果只能拿到总体、频率、功率、温度或阶段数据,应如实单独展示,不称为逐核方案已完成。支持逐核是研究目标,尚不是可以承诺的兼容能力。 + +## 深入验证结果(2026-11-03,第二轮) + +### RawCounter 的实际失败点 + +用 LLDB 调试**本轮自建探针**,沿 `AGXGPURawCounterSourceGroup` → `AGXGPURawCounter::createInstance` → `AGXGPURawCounterImpl::init` 确认:IOGPUDeviceCreate 与 IOGPUDeviceGetConnect 已成功;失败发生在插件自身调用 `IOConnectCallStructMethod` 的 selector `0x105`(261)、72 字节初始化请求,返回 `0xe00002c1`。SDK `IOReturn.h` 明确定义它为 `kIOReturnNotPrivileged`(privilege violation)。未修改指令、寄存器、返回值或驱动配置以跳过检查。 + +新增 `tools/gpu_driver_call_trace.c`,仅加载到自建探针观察插件调用,参数与返回值原样转发。普通用户 euid=501 与经系统授权运行的管理员 euid=0 均观察到相同的初始化拒绝;后续清理调用可返回成功,但不表示初始化成功。RawCounter 仍返回 nil、sourceList 为空。**root 已验证,普通提权不足以解决此问题。** + +在本机 Apple 签名的 `DTServiceHub` 中读取到 `com.apple.private.agx.performance-spi=true`。它与 root 仍拒绝的现象吻合,提示存在私有授权约束;尚未反编译内核来确定该 entitlement 是否是当前失败分支的唯一条件。未伪造 Apple 授权、改签 Apple 组件、修改系统安全设置或启用开发者模式。未将受限接口接入产品。 + +```bash +clang -dynamiclib -framework IOKit tools/gpu_driver_call_trace.c -o /tmp/kymo-gpu-call-trace.dylib +DYLD_INSERT_LIBRARIES=/tmp/kymo-gpu-call-trace.dylib /tmp/kymo-gpu-raw-probe +``` + +追踪器在 stderr 输出 euid、selector、请求长度及真实状态;探针 stdout 输出 uid/euid 与设备初始化结果。加载 dylib 只用于该探针,不用于用户应用或 Apple 服务。第一版诊断转发使用 dlsym 时自递归导致探针崩溃,已改为标准 interpose 的同映像原函数转发,并重新运行验证;最终版本退出码 0。 + +### 开源实现对照 + +检查 [Stats GPU reader(固定提交)](https://github.com/exelban/stats/blob/9248780d0d4293b4f2d1651ab7638af0211a6681/Modules/GPU/reader.swift#L139) 及 [GPU_Info](https://github.com/exelban/stats/blob/9248780d0d4293b4f2d1651ab7638af0211a6681/Modules/GPU/main.swift#L25):设备总体、Renderer、Tiler、核心数量及若干可选温度/频率字段,没有逐物理核心利用率数组。该项目的传感器说明也明确温度区不等同于物理核心。仅参考数据源与字段语义,没有复制其源码。 + +### Apple 官方工具对照 + +`xctrace --instrument 'Metal GPU Counters'` 可以录制。先用 `/usr/bin/true` 做启动检查,再编译运行 `tools/gpu_compute_probe.swift`(自建、约 256 KiB 缓冲、循环目标 3 秒、逐次等待命令完成,性能分析器可能延长实际运行时间),仅录制该测试进程,不附加用户进程。 + +默认配置为 Performance Limiters / Shader Timeline Enabled / Induced GPU Performance State Default。本次 `gpu-counter-info` 仅导出一个描述符:`RT Unit Active`,描述为活跃光追单元的 GPU 核心比例,ring-buffer-count=1;`metal-gpu-counter-intervals` 也是此项聚合值。没有各核心标识及独立利用率。此结果限于本机、本次默认配置,不能推断所有 Instruments 配置均无其他指标。Trace 可以生成也不表示第三方 app 获得了同等驱动访问权。 + +```bash +swiftc tools/gpu_compute_probe.swift -o /tmp/kymo-gpu-compute-probe +xcrun xctrace record --instrument 'Metal GPU Counters' --time-limit 5s --output /tmp/kymo-gpu-compute.trace --launch -- /tmp/kymo-gpu-compute-probe +``` + +### 本轮结论与交付边界 + +已有明确结果:**本机 RawCounter 初始化受驱动权限检查阻断,管理员权限也无效;Stats 和本次官方工具对照均未提供可直接用于 Kymo 的逐核心利用率。** 逐核心产品功能未完成,不能承诺仅靠继续调整 Swift/IOKit 调用就能实现。当前架构仍保留真实总体数据,尚无经过验证的可交付逐核路径。没有将阶段比例、传感器温度、活跃核心比例或总体均分包装为逐核心数据。 + +已验证探针编译/运行、普通用户与 root 错误码、受控负载的官方工具录制/描述符导出;未修改产品源码,无需产品构建。未验证 Apple 私有授权如何取得、其他 counter profiles、其他芯片/OS 或长期采样性能。临时二进制、dylib、clone、trace 与原始导出在检查后清理。 diff --git a/docs/monitoring.md b/docs/monitoring.md index adb5b21..fa5e456 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -6,13 +6,13 @@ | 指标 | 子项 | 优先级 | 状态 | | --- | --- | --- | --- | -| CPU | 总占用率、系统/用户占比、每核占用、负载均值(1/5/15 min) | P0 | 已实现,本机基础验证通过;长期预算待验收 | +| CPU | 总占用率、系统/用户占比、每核占用、负载均值(1/5/15 min)、整体温度 | P0 | 已实现;温度按 SMC 可用性降级,本机基础验证通过,其他芯片与长期预算待验收 | | 内存 | 已用/可用、各分类(wired / compressed / app)、内存压力、Swap | P0 | 已实现,本机基础验证通过;长期预算待验收 | | 网络 | 每接口上下行速率、累计流量、连接状态 | P1 | C 网络路径/64 位差分及存储卷/块设备 IO 已实现,专项验收中 | | 磁盘 | 各卷容量占用、读写速率 | P1 | C 网络路径/64 位差分及存储卷/块设备 IO 已实现,专项验收中 | | 磁盘寿命 | NVMe 预计剩余寿命、通电时间 | P1 | 只读 XPC 已实现,本机沙盒主应用读取通过,其他设备待验证 | -| 电池 | 电量、充放电状态、循环次数、系统报告最大容量 | P2 | C 电源/时间/循环/系统报告最大容量已实现,专项验收中 | -| 传感器 | CPU/GPU 温度、风扇转速 | P2(v0.4) | 规划中(SMC,失败降级隐藏) | +| 电池 | 电量、充放电状态与功率、循环次数、系统报告最大容量、当前高 CPU 进程 | P2 | C 电源/时间/循环/系统报告最大容量已实现;功率与高 CPU 进程展示待实机验收 | +| 传感器 | CPU 温度、GPU 温度、风扇转速 | P2(v0.4) | CPU 温度区域最高值已接入;GPU 温度与风扇仍规划中 | | GPU | 利用率、显存 | P0(面板指标) | 本机已接入 IOAccelerator 总体/核心数;每核独立利用率不可用 | | 进程 | CPU / RSS / 线程 / 路径 | 统一面板 | sysctl/proc 已实现,本用户可读、其他用户部分受限;交互待验收 | @@ -30,8 +30,8 @@ | 网络 | `sysctl NET_RT_IFLIST2` 64 位字节计数差分 | 按活动 en 接口统计上下行;`NWPathMonitor` 仅判断系统网络路径 | | 磁盘容量 | `URL.resourceValues(.volumeTotalCapacityKey / .volumeAvailableCapacityKey)` | 注意 available 与 importantAvailable 的差异 | | 磁盘 IO | IOKit IOBlockStorageDriver Statistics | 全部可读块设备计数差分;接口不可用时显示 -- | -| 电池 | IOKit Power Sources(`IOPSCopyPowerSourcesInfo` 等)+ AppleSmartBattery + 缓存系统报告 | 基础状态/循环走 IOKit;最大容量按 system_profiler 报告,成功缓存一小时;失败为 -- | -| 传感器 | IOKit `AppleSMC` 用户态读取 | 非公开接口,读取失败自动降级隐藏 | +| 电池 | IOKit Power Sources(`IOPSCopyPowerSourcesInfo` 等)+ AppleSmartBattery + 缓存系统报告 | 基础状态/循环走 IOKit;功率为 `Voltage(mV) × abs(InstantAmperage)(mA)`,缺失或越界显示 --;最大容量按 system_profiler 报告,成功缓存一小时 | +| 传感器 | IOKit `AppleSMC` 用户态读取,经嵌入的只读 XPC 服务调用 | 非公开接口;枚举 `flt` 类型的 `Tp`/`Te` CPU 区域传感器并显示最高有效值,不宣称官方封装温度或逐核心温度;失败隐藏胶囊并按 60 秒重试 | | 进程 | `sysctl(KERN_PROC_ALL)` / `proc_pidinfo` | Top N 采样成本较高,放低优先级 | | GPU | IOKit IOReport | 利用率与显存读取;非公开特性,A 阶段先做 spike 验证,失败则模块置灰、保留不可用提示 | | 告警 | `UNUserNotificationCenter` | 阈值由采样调度器统一判定,避免额外轮询 | @@ -40,7 +40,7 @@ 工程默认开启 App Sandbox。上表中的系统级统计 API(Mach、sysctl、getifaddrs、Power Sources)已有本机主要指标验证,不能保证全部机型/API 均可读取: -- SMC 传感器读取在沙盒下预期受限 → 读取失败即降级隐藏,不为此申请额外权限; +- 签名的沙盒主应用直接访问 AppleSMC 在本机被系统拦截。CPU 温度改由现有非沙盒只读 XPC 服务读取,主应用不申请额外权限;本机已通过完整签名包端到端验证,其他芯片与系统版本仍需按机型验证; - 如未来需要「读取任意目录磁盘信息」等能力,再评估 entitlements,默认保持最小权限; - 通知权限(告警功能)需用户显式授权,授权入口集中在设置窗口的权限页,未授权不影响任何监控功能。 @@ -48,14 +48,28 @@ - 全部采样由统一的采样调度器驱动,禁止各模块自建 Timer; - 差分类指标(CPU、网络、磁盘 IO)采样器内部持有上一次快照,自行做差分; +- 电池功率按瞬时电压与电流计算绝对值;当前电源类型和充电状态决定图例为充电功率、放电功率或电池功率。高能耗程序仅按进程 CPU 占用排序,不冒充系统能耗影响评分; - 菜单栏仅显示品牌图标,指标在面板展示; - 采样完成后按可见性等待:面板默认 2s,关闭默认 5s;两者独立持久化、100ms 步进、500ms–30min,面板顶栏调前者,设置监控页调后者;顶栏暂停/恢复。 - 改有效频率或开关面板立即取消旧等待并重排,频率修改以距上次发布的剩余间隔等待、避免重复快采样;纯改频率不重置差分基线;暂停不会被偏好变更唤醒。进程完成单次读取后立即发布有效代次结果,隐藏不查询进程。60 点历史跨度随间隔变化,显式边界保留暂停中断,样本各自携带间隔元数据以平滑连接有效切频历史。 -磁盘寿命通过用户授权的嵌入式非沙盒 XPC 服务低频读取 `diskutil info -plist`,主应用保留沙盒。NVMe 寿命消耗字段换算预计剩余寿命,通电小时读取 128 位计数的可表示部分;高位非零不截断展示。SMART 数据是物理设备级,多个 APFS 卷不重复合算,缺失/多物理存储显示 --。服务固定只读查询,无管理员权限或系统开机项,详见 disk-smart-helper-plan.md。 +CPU 温度与磁盘寿命通过嵌入的只读非沙盒 XPC 服务访问系统接口,主应用保留沙盒。温度查询无参数,只返回 CPU 区域传感器最高有效值;磁盘查询低频执行 `diskutil info -plist`,NVMe 寿命消耗字段换算预计剩余寿命,通电小时读取 128 位计数的可表示部分,高位非零不截断展示。SMART 数据是物理设备级,多个 APFS 卷不重复合算,缺失/多物理存储显示 --。服务不开放通用查询、管理员权限或系统开机项,磁盘细节详见 disk-smart-helper-plan.md。 ## 统一面板增量(首版已接入,专项验收中) 指标与口径见 [统一面板方案 §4、§6](unified-panel-plan.md)。已实现本机 IPv4/IPv6、总体/接口选择及双向历史;进程 CPU 差分、RSS、线程与可执行文件路径;GPU 单设备总体占用和核心拓扑。每核独立利用率未获得,不由总体推算。sysctl 枚举在真实签名沙盒主应用中成立,本用户主要字段可读、其他用户部分受限;正式界面显示覆盖范围。网络总体只汇总活动 en 接口,其他接口独立展示避免 VPN 双计。能力与验证限制见 [实施验证记录](unified-panel-validation.md)。 + +### GPU 逐核心专项调查(2026-11-03) + +本机重新枚举 IOReport 全通道与 Metal counterSets,并尝试私有 RawCounter 描述符初始化;尚未获得可映射物理核心的独立利用率。详细证据、可复现探针与接入门槛见 [GPU 逐核心调查](gpu-per-core-investigation.md)。枚举成功不代表订阅成功,当前调查也不代表所有硬件不支持。 + +第二轮已定位 RawCounter 初始化驱动调用返回 `kIOReturnNotPrivileged`,系统授权后 euid=0 仍同样拒绝;Stats 固定提交未实现逐核 GPU,官方工具本次默认配置也只导出聚合指标。详情见专项调查第二轮;逐核能力仍未实现。 + +### GPU 卡片新增指标 + +读取 `Renderer Utilization %`、`Tiler Utilization %`(独立 0–100 校验),以及 `In use system memory` / `Alloc system memory`(非负有限字节)。后二者显示为驱动在用/分配系统内存,不表示显存容量或物理驻留量。GPU Tg 浮点温区读取沿用只读 XPC;本机命令行实测约 53–56°C,但产品新 XPC 方法运行验收尚未完成。利用率平均按真实时间积分,峰值为实际采样最大值;历史不足一分钟时不填充虚构历史。 + +### 风扇 RPM +固定只读 SMC FNum 和 F0Ac…F9Ac,最多10只;Apple Silicon flt、Intel fpe2 解码,零为有效停转,非有限/负/超过30000视为缺失。0风扇或整个读取失败不展示风扇条;已发现风扇的单项失败显示 --,不会伪装0。GPU 卡是整机风扇信息的展示入口,不代表GPU专属散热器。F0ID/F1ID 本机缺失,左右标签仅为排布位置;真实物理左右待硬件专属映射核实。 diff --git a/docs/sensors-feasibility.md b/docs/sensors-feasibility.md new file mode 100644 index 0000000..65d19bb --- /dev/null +++ b/docs/sensors-feasibility.md @@ -0,0 +1,15 @@ +# Sensors 可行性核验(2026-11-03) + +范围:本机 Apple M4 Pro,只读独立命令行探针;未修改应用、未验证沙盒/XPC 新增 Sensors 接口。 + +- AppleSMC 枚举 3374 个键,普通用户可读取多路 flt 温度、电压、功率和风扇数据,无需 root。 +- CPU:Te05=49.0085°C、Te0S=49.1018°C;Tp1k=65.1562°C、Tp1o=75.3906°C。多个 Tp00/Tp01 等读数均为40°C,不能只凭存在和范围判断有效。 +- GPU:Tg1U=42.6979°C、Tg1k=42.7756°C、Tg0k=49.1813°C 等。可显示温区,尚未证明对应物理 GPU 簇。 +- 电压示例:VP0b=1.1114V、VP1b=0.8198V、VS0b=0.6492V;CPU/GPU/分簇归属未确认。 +- 功率示例:PP0b=5.2900W、PZC0=5.5392W、PZC1=3.5127W;不能据键名前缀直接归属 CPU/GPU。 +- 风扇:FNum=2;F0Ac/F1Ac=0RPM;两只 F*Mn=2317RPM、F*Mx=7826RPM。只读瞬时快照,未验证升速过程,也未确认左右位置。 +- IOReport Energy Model 可枚举 CPU Energy、GPU Energy、EACC_CPU、PACC0_CPU、PACC1_CPU、GPU、GPU SRAM 等能量通道。这里只核验枚举,尚未完成订阅、能量差分/实际时间换算功率和单位验证。 + +参考 Stats Sensors 源码:https://github.com/exelban/stats/blob/master/Modules/Sensors/values.swift 与 readers.swift。其 M4 通用映射包含本机部分恒40°C的 Tp 键,不能直接照搬。其功率路径使用 IOReport Energy Model 差分,而不是把任意 P 键视为 CPU/GPU 功率。 + +结论:可做多温区、供电轨、风扇 Sensors 列表;CPU/GPU 精确分簇温度/电压仍需芯片专属映射。功率优先进一步验证 IOReport 能量通道。读数可用性不等同于物理归属已确认。 diff --git a/docs/unified-panel-validation.md b/docs/unified-panel-validation.md index 180172f..77b918e 100644 --- a/docs/unified-panel-validation.md +++ b/docs/unified-panel-validation.md @@ -63,7 +63,7 @@ Debug / Release 首版构建通过;不能据此标记 P1、P3、P4 退出条 ### 九项布局与图表修订(2026-11-03) - 第一排为 CPU/GPU/电池,1240×820pt 下电池 230×230pt,CPU/GPU 各 487pt;第二排内存/存储/网络各约 401pt。标题与主值同行,版本和本机产品名/芯片移入顶栏,四项操作位于右侧,移除采样标识/更新时间和底栏。较低三列屏幕保持该顺序与比例,资源区单独滚动。 -- CPU 历史保留总占用、用户、系统三份真实采样,复合曲线使用三色图例;网络上下行、存储读写使用双曲线与图例。采用相邻点内的圆滑曲线、真实时间轴追加过渡、数值 numericText 动效;减少动态效果时关闭过渡。悬浮绘图区选择最近历史样本,显示各线读数、时刻、游标和交点,缺失值仍为 --。 +- CPU 历史保留总占用、用户、系统三份真实采样,复合曲线使用三色图例;用户与系统实时值只在图例中展示,删除图表下方重复行。网络上下行、存储读写使用双曲线与图例。采用相邻点内的圆滑曲线、真实时间轴追加过渡、数值 numericText 动效;减少动态效果时关闭过渡。悬浮绘图区选择最近历史样本,显示各线读数、时刻、游标和交点,缺失值仍为 --。 - 网络默认地址来自 NWPath 偏好首位接口,实际沙盒窗口确认 en0 的 IPv4 已直接展示(不把地址记录在本文件);断网/元数据不可读显示未知。本机硬件信息已确认显示 MacBook Pro (14-inch, Nov 2024) · Apple M4 Pro,产品名不可读退回硬件代码;不读取序列号。 - 卡片资源深浅色 alpha 均为 0.68,减少透明度时回退到系统实色背景;编译 NSColor 检查确认资源透明度和指标色 alpha=1。进程表头与排序改为“内存”,说明保留物理驻留大小(RSS)口径。 @@ -79,6 +79,13 @@ Debug / Release 首版构建通过;不能据此标记 P1、P3、P4 退出条 刷新以整数毫秒分别持久化:面板默认 2000、后台默认 5000;步进 100、范围 500–1800000。顶栏调整前者,设置监控页调整后者;有效频率或可见性改变立即取消旧等待并重排,另一侧偏好改变不唤醒当前调度,暂停优先。进程单次在途完成后立即发布有效代次结果,避免长间隔下首次列表空等;快速快照保留已先到的同周期进程结果,隐藏/暂停拒绝迟到结果。显式历史中断标记防止跨暂停/切频率补线,正常慢间隔仍可连接。 +### CPU 温度、圆环核心与等宽首排(2026-11-03) + +- CPU 卡标题后接入温度胶囊,90°C 起标题图标、标题、胶囊与“温度过高”提示转为红色;无可用传感器时隐藏胶囊。整体温度口径为 `Tp`/`Te` CPU 区域传感器最高有效值,不宣称 Apple 官方封装温度或逐核心温度。 +- 核心改为分类色圆环,中央显示四舍五入百分比,界面不显示核心编号,进度动画遵循减少动态效果。18 核在常规及较窄卡片优先均分两行;单元宽度低于 16pt 才进入三行。圆环缩小并将描边内缩,布局行高为 22pt 并保留上下余量以避免底部裁切。第一排按实际核心行数决定高度:两行时约 239pt,不预留第三行空白;第三行实际出现时扩展到约 265pt。第一排 CPU/GPU/电池等宽,第二排继续三等分。卡片标题、温度胶囊、告警文案和主值改为垂直居中对齐。 +- 沙盒主应用直接执行 AppleSMC 查询在本机被系统拦截。扩展既有只读 XPC 的固定无参数查询后,完整分离签名应用端到端读到 `81.58°C`,第二次快速采样已将该值写入正式 `MetricsSnapshot` 诊断输出;测试副本 PID 30741 与 SMART 服务均在验证后退出,用户原有 Xcode 副本 PID 30325 保留。 +- AppleSMC 结构布局、90°C 阈值与实时值范围检查通过;核心布局 0–128 核、18/32/48 核分配检查通过;首排等宽和第二排布局计算检查通过;SamplingChecks、专项闭环历史/暂停恢复/CPU/内存/负载检查及 Debug 构建通过。菜单栏应用的 AX 绑定仍超时,未取得实际面板截图;圆环、胶囊和红色提示的视觉及动画手感仍需用户运行验收,其他芯片与系统版本的传感器键仍待跨机型验证。 + 图例始终保留最新值,历史读数用独立浮层;CPU 采用青绿/紫红/金色及实线/虚线/点线,网络和存储双线也有独立色/线型。浅色渲染检查发现材质浮层会透出底下文字,最终改为深浅资源 alpha=0.97 的浮层底色;卡片仍为 alpha=0.68。间隔单位指定固定宽度,避免顶栏压缩。 通过的客观验证: @@ -125,12 +132,26 @@ Debug / Release 首版构建通过;不能据此标记 P1、P3、P4 退出条 ### 明亮配色与实色面板(2026-11-03) -采用用户确认的深色概念配色,见 [配色说明](solid-panel-palette.md)。主面板 #171A21、卡片 #222731 均 alpha=1;移除主面板 ultraThinMaterial 与顶栏按钮组 glassEffect。CPU 青/粉/金、网络蓝/金、存储金/紫,六类指标主色统一由资源控制;浅色使用同色相较深版本。TooltipMaterialBackground、原生菜单/popover 与设置页材质不变。 +采用用户确认的深色概念配色,见 [配色说明](solid-panel-palette.md)。主面板 #171A21、卡片 #222731 均 alpha=1;主面板与卡片保持实色,顶栏按钮组按要求恢复系统液态玻璃胶囊。CPU 青/粉/金、网络蓝/金、存储金/紫,六类指标主色统一由资源控制;浅色使用同色相较深版本。TooltipMaterialBackground、原生菜单/popover 与设置页材质不变。 通过:Debug 构建;PanelAssetChecks 从编译后的实际应用读取深浅资源,检查面板/卡片/指标 alpha、CPU 序列色相差至少 36°、指标/序列对卡片图形对比度至少 3:1。原来的 RGB 欧氏距离阈值不能直接表达新调色的色相分离,故改为环形色相间隔并新增实际亮度对比度校验。 使用实际 ResourceCard、PanelTrendChart、MetricProgressBar 和编译资源,通过 ImageRenderer 渲染固定样本的两排六卡片,深浅两种模式确认实色层级、明亮强调色与复合曲线区分。该样例使用简化文本/固定样本,不是完整 MenuPanelView 截图,不证明正式 NSPanel 悬浮事件或真实数据;本轮未重启用户应用。临时渲染程序、图片、缓存及构建产物清理,用户既有本地化改动未纳入提交。 +### 顶栏品牌与玻璃按钮组细化(2026-11-03) + +版本号改为 Kymo 名称右上角的小号上标;名称与电脑产品名/芯片之间增加低对比竖线,窄布局隐藏产品名时同步隐藏分隔线。右侧刷新、图钉、保持唤醒、暂停/恢复、设置和退出操作保留单一胶囊,并将实色背景替换为系统 `.glassEffect(.regular, in: .capsule)`;主面板和资源卡片继续保持不透明实色。 + +该轮只修改顶栏呈现,不改采样、窗口固定或操作逻辑。客观构建结果见本轮交付;液体玻璃的明暗观感与不同背景下的边缘对比仍需实际面板验收。 + +### 电池功率、摘要与高能耗进程(2026-11-03) + +电池图从 AppleSmartBattery 的 `Voltage`(mV)和 `InstantAmperage`(mA)计算电池侧功率,伏安乘积换算为 W,并过滤缺失、非有限与越界值。图表继续以 0–100% 绘制电量,同时为功率启用独立自动量级与右侧 W 刻度;图例及悬浮浮层分别按百分比和 W 显示。当前图例在充电、放电与插电保持状态分别标注“充电功率”“放电功率”“电池功率”,历史仍以非负功率比较。 + +卡片下方第一行显示电池健康度与循环次数,第二行显示电源类型与续航预估;外接电源不生成伪续航。下方耗电列表按当前进程快照显示 CPU 占用最高的 3 项,每项包含运行应用或可执行文件图标、名称与百分比;帮助文案明确它是可观测代理,不等同于 macOS 的系统能耗影响评分。进程不可读或首次采样未完成时显示等待/`--`,关闭面板后不会为该项额外查询进程。 + +通过:Debug 构建;功率 mV×mA 换算、无效电压/电流、W 格式化、电量与功率历史、最高 CPU 进程及前 3 项边界、Localizable JSON 语法、历史曲线几何及三语资源检查。Stage C 本机实时采样读到电量 80%、循环 64、充电状态否、功率 0.0 W,与当前插电 80% 限充状态一致。未重启用户正在运行的应用;正式电池卡片双纵轴排版、图例/悬浮字符宽度、三行耗电列表与图标回落仍需重新运行验收。 + ### 设置窗口深浅混用修复(2026-11-03) 在隔离测试包中使用与正式入口相同的 NSHostingSceneRepresentation + Settings 和实际 AppearanceSettingsView,原生点击深色→浅色,复现标题栏/背景变浅、侧栏文字与 Form 仍深色的用户截图现象。单独取消全局动画、在两栏重复注入外观均不能解决;按主题刷新分栏承载子树后消除。正式实现由 AppearanceStyle 提供默认关闭的 refreshContentOnChange,仅设置页开启,以解析后的 light/dark 为身份,覆盖手动选择与跟随系统解析变化。外层页面选择/偏好仓库保持不变,主题切换时原生控件及临时滚动/焦点可能重新建立。 @@ -138,3 +159,56 @@ Debug / Release 首版构建通过;不能据此标记 P1、P3、P4 退出条 通过:最终 Debug 构建;既有 PresentationChecks 的显式/系统窗口外观重置、独立系统主题解析及原生色板检查。最终源码隔离 Settings 窗口中,真实点击深→浅、浅→深、深→跟随系统(当前系统为浅色),截图确认窗口外壳、侧栏文字、表单与选择器一致;切到监控页确认表单仍为浅色。测试包未打包本地化资源,截图展示键名,不用它评价正式中文排版。未修改系统主题来测试系统通知、未重复完整多屏/失焦矩阵,未重启用户主应用。 测试前记录并保留用户 Xcode 副本 PID 25966。仅退出本轮隔离测试包,注销并清理临时应用、独立偏好 suite、编译缓存与产物;工作区已有本地化改动不纳入提交。 + +### 电池卡片视觉整理(2026-11-03) + +按确认概念图将状态整理为两列两行,中间细分隔线;耗电列表独立分区,显示应用图标、名称、动画细进度条与右对齐百分比,并明确标注 CPU 占用。进度以单核 100% 为满刻度,超过时封顶,文字保留实际值。保留外接电源时续航不适用文案及既有双轴图表。颜色沿用语义资源,适配深浅色。未重启用户实例;真实卡片宽度下的名称截断、两行状态与整体高度尚待运行验收。 + +### CPU 卡片分区改版(2026-11-03) + +按确认概念图整理为趋势、核心分组、底部负载与运行时间三个区域。核心按实际拓扑分组,宽度按列数动态分配、组内两行优先且最多三行,所有类型统一圆环直径;未知类型保留。首排高度使用分组后的最大行数。独立检查覆盖 0–128 核、多个宽度、18/32/48 核及未知类型的完整性和行数边界。Debug 构建通过;未重启用户已有应用,实际面板视觉及动画尚未运行验收。 + +## GPU 逐核心数据源专项(2026-11-03) + +已运行 `tools/gpu_capability_probe.py`,IORegistry / IOReport / Metal 三路均完成枚举;已用 clang 编译并运行 `tools/gpu_raw_counter_probe.m`,插件加载成功、三种初始化路径未获得 sourceList。详细结果见 [专项调查](gpu-per-core-investigation.md)。本轮未修改应用源码,未重启用户应用;不声称逐核读取、沙盒接入、UI 或长期资源验收通过。 + +GPU 专项第二轮:已完成 LLDB 失败分支定位、探针调用原样转发观察、普通用户/euid=0 对照(均 kIOReturnNotPrivileged)、Stats 源码对照和自建 Metal 负载的 xctrace GPU Counters 录制。官方工具本次仅导出聚合 RT Unit Active;无真实逐核实现。证据及限制见专项调查第二轮。 + +## GPU 卡片信息补全 + +- GPUStatisticsChecks:时间加权平均、60 秒截断、空历史/单点、nil/休眠/长间隔、三路历史、内存非法值与真实采样。 +- 本机只读采样:20 核,总利用率约 33–34%、Renderer 32–33%、Tiler 9%,Tg 温区约 53–56°C;仅为瞬时证据。 +- 保留用户 PID 38877 的 Xcode 实例。未重启或替换运行实例;新版卡片实际空间、悬浮交互、动画和新 XPC 方法待运行验收。 + +- 本轮结果:GPUStatisticsChecks 通过;默认签名 Debug 构建、字符串 JSON 与 diff 检查通过。未启动新应用实例。 + +## GPU 风扇融合(2026-11-03) +- 普通用户裸读:2只风扇均0 RPM;F0ID/F1ID缺失,未确认物理左右。 +- FanChecks:flt/fpe2/ui8解码、损坏长度/NaN、零/负/超范围RPM、动画档位单调、变速相位连续、零速和减少动态效果停转通过。 +- 独立临时签名沙盒 `.app` 嵌入构建出的 SMARTService,复用实际客户端及签名校验调用 readFanSpeeds,返回两个0 RPM;证明沙盒→XPC回传,本轮未替换/退出用户进程 PID40226。 +- `cua.getApp("Kymo")` 读取超时,实际面板布局及动画观感未验证;不能据此判断授权缺失。未采集屏幕,也未进行风扇控制或人为高负载升速。 +- 验收:用户重新运行后,确认GPU底部左右读数不截断;非零RPM图标转动且高速更快;0RPM停止;系统减少动态效果开启时停转。物理左右映射仍未验证,帮助文本明确说明。 +- 最终标准签名 Debug 构建、GPUStatisticsChecks 回归、字符串 JSON 与 diff 检查通过。 + +### 后续本机面板核验 +用户运行实例已变为 PID41225(非智能体重启)。通过 `cua.getApp("cn.airnan.kymo")` 成功读取面板并取得仅应用窗口截图:GPU统计和左右风扇条完整、未截断,未显示“整机散热”标题。AX 读数3843/4135 RPM,截图时4197/4475 RPM;同阶段独立裸读和签名沙盒XPC均为3795.55/4112.55 RPM,实时变化合理。真实非零转速回传已验证,动画档位与停转状态测试通过,实际旋转手感仍需人工验收。未操作用户其他窗口、未控制风扇或启动负载。截图仅在工具内显示,未创建本地截图文件。 + +## GPU 核心标签与图形统计(2026-11-03) +- 标准 Debug 构建、字符串 JSON 与 diff 检查通过。 +- 用真实 GPUStatisticsView、MetricRingGauge、MetricProgressBar 与编译资源离屏渲染 370pt/280pt 宽度,检查普通值、很小内存值、0%、100%和全缺失:文字/圆环完整、细小横条保持在圆角轨道内,缺失保留--。临时渲染器有 sandbox_extension 诊断,但成功输出图像并人工检查,不能将其视为真实窗口交互通过。 +- 未退出用户应用;新版整卡实际窗口和动效观感尚未验证,需用户下次运行后确认标题核心数标签及新图形区。 + +### 首排对齐调整(2026-11-03) + +- CPU/GPU/电池显式共享行高,GPU 绘图区恢复 58pt,与另外两张卡片保持相同基线;调整核心、GPU 统计及电池列表间距。 +- 保留第三行核心和多风扇时的动态扩展,窄屏网格按实际列宽计算核心行数。 +- 删除风扇区域的 `.help`,旋转行为不变。 +- 本轮未重启用户 Xcode 启动的 Kymo;新版整卡的实际窗口布局、第三行核心及窄屏视觉效果尚待运行验收。 +- 验证:签名 Debug 构建通过,`git diff --check` 通过;未对当前旧实例的画面冒称新版验收。 + +### 耗电进程加载高度修复(2026-11-03) + +- 耗电区预留固定 72pt,覆盖标题、三条 16pt 行及 4pt 间距,等待数据与完整列表尺寸一致。 +- 电池两行摘要固定 32pt,取消额外上下内边距,避免完整内容超过 260pt 卡片预算。 +- 实际运行中加载前后的整卡对齐尚未验收;不重启用户现有实例。 +- 签名 Debug 构建及 `git diff --check` 通过。 diff --git a/kymo.xcodeproj/project.pbxproj b/kymo.xcodeproj/project.pbxproj index 95ba371..de34b16 100644 --- a/kymo.xcodeproj/project.pbxproj +++ b/kymo.xcodeproj/project.pbxproj @@ -14,6 +14,7 @@ BB0000000000000000000022 /* DiskHealthMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000E /* DiskHealthMetrics.swift */; }; BB0000000000000000000023 /* DiskHealthReport.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000F /* DiskHealthReport.swift */; }; BB0000000000000000000024 /* SMARTService.xpc in Embed XPC Services */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000002 /* SMARTService.xpc */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + BB0000000000000000000025 /* CPUTemperatureMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000010 /* CPUTemperatureMonitor.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -46,6 +47,7 @@ BB000000000000000000000D /* CodeIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = CodeIdentity.swift; path = kymo/Core/Services/CodeIdentity.swift; sourceTree = SOURCE_ROOT; }; BB000000000000000000000E /* DiskHealthMetrics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DiskHealthMetrics.swift; path = kymo/Core/Models/DiskHealthMetrics.swift; sourceTree = SOURCE_ROOT; }; BB000000000000000000000F /* DiskHealthReport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DiskHealthReport.swift; path = kymo/Core/Monitors/DiskHealthReport.swift; sourceTree = SOURCE_ROOT; }; + BB0000000000000000000010 /* CPUTemperatureMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = CPUTemperatureMonitor.swift; path = kymo/Core/Monitors/CPUTemperatureMonitor.swift; sourceTree = SOURCE_ROOT; }; BB0000000000000000000016 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = SMARTService/Info.plist; sourceTree = SOURCE_ROOT; }; D9E51E73309338B0000608DE /* kymo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = kymo.app; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -105,6 +107,7 @@ BB000000000000000000000D /* CodeIdentity.swift */, BB000000000000000000000E /* DiskHealthMetrics.swift */, BB000000000000000000000F /* DiskHealthReport.swift */, + BB0000000000000000000010 /* CPUTemperatureMonitor.swift */, ); name = "SMART Service"; sourceTree = ""; @@ -221,6 +224,7 @@ BB0000000000000000000021 /* CodeIdentity.swift in Sources */, BB0000000000000000000022 /* DiskHealthMetrics.swift in Sources */, BB0000000000000000000023 /* DiskHealthReport.swift in Sources */, + BB0000000000000000000025 /* CPUTemperatureMonitor.swift in Sources */, ); }; D9E51E6F309338B0000608DE /* Sources */ = { diff --git a/kymo/Core/Extensions/MetricFormat.swift b/kymo/Core/Extensions/MetricFormat.swift index 15f17e8..42919b5 100644 --- a/kymo/Core/Extensions/MetricFormat.swift +++ b/kymo/Core/Extensions/MetricFormat.swift @@ -20,5 +20,10 @@ nonisolated enum MetricFormat { return String(format: "%.1f %@", scaled, units[index]) } + static func watts(_ value: Double?) -> String { + guard let value, value.isFinite, value >= 0 else { return "--" } + return String(format: "%.1f W", value) + } + static func decimal(_ value: Double) -> String { String(format: "%.1f", value) } } diff --git a/kymo/Core/Models/FanMetrics.swift b/kymo/Core/Models/FanMetrics.swift new file mode 100644 index 0000000..1994b53 --- /dev/null +++ b/kymo/Core/Models/FanMetrics.swift @@ -0,0 +1,11 @@ +import Foundation + +nonisolated struct FanMetrics: Sendable, Identifiable { + let id: Int + let rpm: Double? + + static func validRPM(_ value: Double?) -> Double? { + guard let value, value.isFinite, value >= 0, value <= 30_000 else { return nil } + return value + } +} diff --git a/kymo/Core/Models/MetricHistory.swift b/kymo/Core/Models/MetricHistory.swift index e163a29..fa560c8 100644 --- a/kymo/Core/Models/MetricHistory.swift +++ b/kymo/Core/Models/MetricHistory.swift @@ -8,11 +8,14 @@ nonisolated struct TrendSample: Sendable { var download: Double? var disk: Double? var battery: Double? + var batteryPower: Double? var upload: Double? var read: Double? var write: Double? var cpuUser: Double? var cpuSystem: Double? + var gpuRenderer: Double? + var gpuTiler: Double? var breakBefore = false var expectedInterval: TimeInterval = 2 } @@ -27,9 +30,10 @@ nonisolated struct MetricHistory: Sendable { samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage, gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage, download: snapshot.downloadRate, disk: snapshot.disk?.usage, - battery: snapshot.battery?.charge, upload: snapshot.uploadRate, + battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power, + upload: snapshot.uploadRate, read: snapshot.diskIO?.read, write: snapshot.diskIO?.written, - cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore, expectedInterval: expectedInterval)) + cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler, breakBefore: breakBefore, expectedInterval: expectedInterval)) let current = snapshot.network ?? [] let keys = Set(current.map(\.identity)) interfaces = interfaces.filter { keys.contains($0.key) } @@ -47,3 +51,30 @@ nonisolated struct InterfaceTrendSample: Sendable { let upload: Double? var expectedInterval: TimeInterval = 2 } + +/// Time-weighted observed utilization; never bridge failures or sleep boundaries. +nonisolated struct GPUUtilizationSummary { + let average: Double? + let peak: Double? + let coverage: TimeInterval + + init(samples: [TrendSample], window: TimeInterval = 60) { + guard let end = samples.last?.date else { average = nil; peak = nil; coverage = 0; return } + let start = end.addingTimeInterval(-window) + peak = samples.filter { $0.date >= start }.compactMap(\.gpu).max() + var area = 0.0 + var duration = 0.0 + for (a, b) in zip(samples, samples.dropFirst()) { + let dt = b.date.timeIntervalSince(a.date) + guard !b.breakBefore, dt > 0, dt <= max(a.expectedInterval, b.expectedInterval) * 2.5, + let av = a.gpu, let bv = b.gpu else { continue } + let overlap = b.date.timeIntervalSince(max(a.date, start)) + guard overlap > 0 else { continue } + let left = av + (bv - av) * (1 - overlap / dt) + area += (left + bv) * 0.5 * overlap + duration += overlap + } + coverage = duration + average = duration > 0 ? area / duration : nil + } +} diff --git a/kymo/Core/Models/MetricsSnapshot.swift b/kymo/Core/Models/MetricsSnapshot.swift index 656e8e2..6a550b5 100644 --- a/kymo/Core/Models/MetricsSnapshot.swift +++ b/kymo/Core/Models/MetricsSnapshot.swift @@ -20,6 +20,9 @@ nonisolated struct MemoryMetrics: Sendable { nonisolated struct MetricsSnapshot: Sendable { var date = Date() var cpu: CPUMetrics? + var cpuTemperature: Double? + var gpuTemperature: Double? + var fans: [FanMetrics]? var memory: MemoryMetrics? var network: [NetworkInterfaceMetrics]? var networkPath: NetworkPathStatus? diff --git a/kymo/Core/Models/ProcessMetrics.swift b/kymo/Core/Models/ProcessMetrics.swift index 65cab67..777f0d4 100644 --- a/kymo/Core/Models/ProcessMetrics.swift +++ b/kymo/Core/Models/ProcessMetrics.swift @@ -23,3 +23,21 @@ nonisolated struct ProcessSnapshot: Sendable { let rows: [ProcessMetrics] let failed: Bool } + +nonisolated extension ProcessSnapshot { + func highestCPUProcesses(limit: Int) -> [ProcessMetrics] { + guard limit > 0 else { return [] } + var result: [ProcessMetrics] = [] + for row in rows { + guard let cpu = row.cpu, cpu.isFinite, cpu >= 0 else { continue } + let index = result.firstIndex { ($0.cpu ?? 0) < cpu } ?? result.endIndex + result.insert(row, at: index) + if result.count > limit { result.removeLast() } + } + return result + } + + var highestCPUProcess: ProcessMetrics? { + highestCPUProcesses(limit: 1).first + } +} diff --git a/kymo/Core/Monitors/BatteryMonitor.swift b/kymo/Core/Monitors/BatteryMonitor.swift index 286ed57..c321229 100644 --- a/kymo/Core/Monitors/BatteryMonitor.swift +++ b/kymo/Core/Monitors/BatteryMonitor.swift @@ -5,12 +5,22 @@ nonisolated struct BatteryMetrics: Sendable { let charge: Double? let charging: Bool let externalPower: Bool + var power: Double? = nil var minutesRemaining: Int? var cycles: Int? var health: Double? } nonisolated enum BatteryMonitor { + static func normalizedPower(voltageMillivolts: Double?, amperageMilliamps: Double?) -> Double? { + guard let voltageMillivolts, let amperageMilliamps, + voltageMillivolts.isFinite, amperageMilliamps.isFinite, + voltageMillivolts > 0, voltageMillivolts <= 30_000, + abs(amperageMilliamps) <= 20_000 else { return nil } + let watts = abs(voltageMillivolts * amperageMilliamps) / 1_000_000 + return watts.isFinite && watts <= 500 ? watts : nil + } + static func positiveMinutes(_ value: Int?) -> Int? { value.flatMap { $0 > 0 ? $0 : nil } } @@ -55,10 +65,24 @@ nonisolated enum BatteryMonitor { let charging = item[kIOPSIsChargingKey] as? Bool ?? false let external = item[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue let minutes = charging ? item[kIOPSTimeToFullChargeKey] as? Int : external ? nil : item[kIOPSTimeToEmptyKey] as? Int + let batteryData = properties["BatteryData"] as? [String: Any] ?? [:] + let voltage = firstNumber([properties["Voltage"], batteryData["Voltage"], batteryData["AppleRawBatteryVoltage"]]) + let amperage = firstNumber([properties["InstantAmperage"], batteryData["InstantAmperage"], properties["Amperage"], batteryData["Amperage"]]) return BatteryMetrics(charge: charge, charging: item[kIOPSIsChargingKey] as? Bool ?? false, - externalPower: external, minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()), + externalPower: external, + power: normalizedPower(voltageMillivolts: voltage, amperageMilliamps: amperage), + minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()), cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil }) } return nil } + + private static func firstNumber(_ values: [Any?]) -> Double? { + for case let value? in values { + if let number = value as? NSNumber, number.doubleValue.isFinite { + return number.doubleValue + } + } + return nil + } } diff --git a/kymo/Core/Monitors/CPUTemperatureMonitor.swift b/kymo/Core/Monitors/CPUTemperatureMonitor.swift new file mode 100644 index 0000000..dd2a91e --- /dev/null +++ b/kymo/Core/Monitors/CPUTemperatureMonitor.swift @@ -0,0 +1,123 @@ +import Foundation +import IOKit + +// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan keys; never write keys. +nonisolated final class CPUTemperatureMonitor { + static let highTemperatureThreshold = 90.0 + + private struct Version { var major: UInt8 = 0; var minor: UInt8 = 0; var build: UInt8 = 0; var reserved: UInt8 = 0; var release: UInt16 = 0 } + private struct Limits { var version: UInt16 = 0; var length: UInt16 = 0; var cpu: UInt32 = 0; var gpu: UInt32 = 0; var memory: UInt32 = 0 } + private struct KeyInfo { var size: UInt32 = 0; var type: UInt32 = 0; var attributes: UInt8 = 0; var padding1: UInt8 = 0; var padding2: UInt8 = 0; var padding3: UInt8 = 0 } + private struct Request { + var key: UInt32 = 0; var version = Version(); var limits = Limits(); var info = KeyInfo() + var result: UInt8 = 0; var status: UInt8 = 0; var command: UInt8 = 0; var index: UInt32 = 0 + var bytes: (UInt64, UInt64, UInt64, UInt64) = (0, 0, 0, 0) + } + static var hasExpectedLayout: Bool { + MemoryLayout.stride == 80 && MemoryLayout.offset(of: \Request.info) == 28 && + MemoryLayout.offset(of: \Request.command) == 42 && MemoryLayout.offset(of: \Request.index) == 44 && + MemoryLayout.offset(of: \Request.bytes) == 48 + } + static func isHighTemperature(_ value: Double?) -> Bool { + guard let value else { return false } + return value >= highTemperatureThreshold + } + enum Zone { case cpu, gpu } + private let zone: Zone + init(zone: Zone = .cpu) { self.zone = zone } + + private var connection: io_connect_t = 0 + private var keys: [(UInt32, UInt32)] = [] + private var attempted = false + + deinit { if connection != 0 { IOServiceClose(connection) } } + + private func call(_ request: inout Request) -> Request? { + var response = Request() + var size = MemoryLayout.stride + let result = IOConnectCallStructMethod(connection, 2, &request, MemoryLayout.stride, &response, &size) + guard result == KERN_SUCCESS, size == MemoryLayout.stride, response.result == 0 else { return nil } + return response + } + + private func openConnection() -> Bool { + if connection != 0 { return true } + guard Self.hasExpectedLayout else { return false } + let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC")) + guard service != 0 else { return false } + defer { IOObjectRelease(service) } + guard IOServiceOpen(service, mach_task_self_, 0, &connection) == KERN_SUCCESS else { connection = 0; return false } + return true + } + + private func discover() { + attempted = true + guard openConnection() else { return } + var countRequest = Request(); countRequest.key = 0x234b4559; countRequest.info.size = 4; countRequest.command = 5 + guard let countResponse = call(&countRequest) else { return } + let count = withUnsafeBytes(of: countResponse.bytes) { UInt32($0[0]) << 24 | UInt32($0[1]) << 16 | UInt32($0[2]) << 8 | UInt32($0[3]) } + guard count <= 10000 else { return } + for index in 0..> 16 + guard zone == .gpu ? prefix == 0x5467 : (prefix == 0x5470 || prefix == 0x5465) else { continue } + var info = Request(); info.key = response.key; info.command = 9 + guard let metadata = call(&info), metadata.info.type == 0x666c7420, metadata.info.size == 4 else { continue } + keys.append((response.key, metadata.info.size)) + } + if keys.isEmpty { + IOServiceClose(connection) + connection = 0 + attempted = false + } + } + + /// Highest valid selected temperature-zone sensor reading in Celsius, not an official package temperature. + func sample() -> Double? { + if !attempted { discover() } + guard connection != 0 else { return nil } + var highest: Double? + for (key, size) in keys { + var request = Request(); request.key = key; request.info.size = size; request.command = 5 + guard let response = call(&request) else { continue } + let bits = withUnsafeBytes(of: response.bytes) { UInt32($0[0]) | UInt32($0[1]) << 8 | UInt32($0[2]) << 16 | UInt32($0[3]) << 24 } + let value = Double(Float(bitPattern: bits)) + guard value.isFinite, value > 0, value < 150 else { continue } + highest = max(highest ?? value, value) + } + return highest + } + /// Fixed read-only fan keys. nil means unavailable; [] means a fanless device. + func sampleFans() -> [Double?]? { + guard openConnection(), let count = readNumber(0x464e756d), + count.isFinite, count >= 0, count <= 10, count.rounded() == count else { return nil } + return (0..= 0, rpm <= 30_000 else { return nil } + return rpm + } + } + + private func readNumber(_ key: UInt32) -> Double? { + var request = Request(); request.key = key; request.command = 9 + guard let metadata = call(&request), metadata.info.size <= 32 else { return nil } + request.command = 5; request.info.size = metadata.info.size + guard let response = call(&request) else { return nil } + let bytes = withUnsafeBytes(of: response.bytes) { Array($0.prefix(Int(metadata.info.size))) } + return Self.decodeSensorNumber(type: metadata.info.type, bytes: bytes) + } + + static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? { + switch (type, bytes.count) { + case (0x666c7420, 4): // flt, little-endian IEEE754 + let bits = UInt32(bytes[0]) | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) << 16 | UInt32(bytes[3]) << 24 + let value = Double(Float(bitPattern: bits)) + return value.isFinite ? value : nil + case (0x66706532, 2): // fpe2, big-endian unsigned 14.2 fixed point + return Double(UInt16(bytes[0]) << 8 | UInt16(bytes[1])) / 4 + case (0x75693820, 1): return Double(bytes[0]) // ui8 + default: return nil + } + } +} diff --git a/kymo/Core/Monitors/GPUMonitor.swift b/kymo/Core/Monitors/GPUMonitor.swift index 4c0aa7d..fe217a4 100644 --- a/kymo/Core/Monitors/GPUMonitor.swift +++ b/kymo/Core/Monitors/GPUMonitor.swift @@ -4,6 +4,11 @@ import IOKit nonisolated struct GPUMetrics: Sendable { let usage: Double? let coreCount: Int? + var renderer: Double? = nil + var tiler: Double? = nil + // Driver accounting, not dedicated VRAM or a capacity denominator. + var inUseMemory: UInt64? = nil + var allocatedMemory: UInt64? = nil // Independent per-core counters have not been obtained. Never split total usage. } @@ -20,12 +25,23 @@ nonisolated enum GPUMonitor { let stats = IORegistryEntryCreateCFProperty(service, "PerformanceStatistics" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? [String: Any] let raw = (stats?["Device Utilization %"] as? NSNumber)?.doubleValue let cores = (IORegistryEntryCreateCFProperty(service, "gpu-core-count" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber)?.intValue - devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil })) + devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil }, + renderer: normalized((stats?["Renderer Utilization %"] as? NSNumber)?.doubleValue), + tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue), + inUseMemory: memoryBytes(stats?["In use system memory"]), + allocatedMemory: memoryBytes(stats?["Alloc system memory"]))) } // Do not average incompatible utilization counters on multi-GPU machines. return devices.count == 1 ? devices[0] : nil } + static func memoryBytes(_ raw: Any?) -> UInt64? { + guard let number = raw as? NSNumber else { return nil } + let value = number.doubleValue + guard value.isFinite, value >= 0, value < Double(UInt64.max) else { return nil } + return UInt64(value) + } + static func normalized(_ value: Double?) -> Double? { value.flatMap { $0.isFinite && (0...100).contains($0) ? $0 / 100 : nil } } diff --git a/kymo/Core/Monitors/SystemSampler.swift b/kymo/Core/Monitors/SystemSampler.swift index b01d796..1e01588 100644 --- a/kymo/Core/Monitors/SystemSampler.swift +++ b/kymo/Core/Monitors/SystemSampler.swift @@ -4,6 +4,11 @@ import Darwin /// One coordinator owns baselines; slow workers have at most one in-flight call each. actor SystemSampler { private var cpu = CPUMonitor() + private var temperatureTask: Task? + private var temperatureCache: Double? + private var gpuTemperatureCache: Double? + private var fanCache: [FanMetrics]? + private var nextTemperature: TimeInterval = 0 private var didProbe = false private let diskHealth = DiskHealthMonitor() private let batteryHealth = SystemBatteryHealthMonitor() @@ -56,6 +61,17 @@ actor SystemSampler { let start = ProcessInfo.processInfo.systemUptime var result = MetricsSnapshot() result.cpu = cpu.sample() + if temperatureTask == nil && start >= nextTemperature { + temperatureTask = Task { [self] in + async let cpu = CPUTemperatureServiceClient.read() + async let gpu = CPUTemperatureServiceClient.read(gpu: true) + async let fans = CPUTemperatureServiceClient.readFans() + await finishTemperature(cpu, gpu: gpu, fans: fans) + } + } + result.cpuTemperature = temperatureCache + result.gpuTemperature = gpuTemperatureCache + result.fans = fanCache result.memory = MemoryMonitor.sample() result.network = network.sample() result.networkPath = networkPath.snapshot() @@ -95,6 +111,14 @@ actor SystemSampler { return result } + private func finishTemperature(_ value: Double?, gpu: Double?, fans: [FanMetrics]?) { + fanCache = fans + gpuTemperatureCache = gpu + temperatureCache = value + nextTemperature = ProcessInfo.processInfo.systemUptime + (value == nil && gpu == nil && fans == nil ? 60 : 5) + temperatureTask = nil + } + private func finishVolumes(_ value: [VolumeMetrics]?) { volumes = value; volumeSampleTime = ProcessInfo.processInfo.systemUptime; volumeTask = nil } diff --git a/kymo/Core/Services/CPUTemperatureServiceClient.swift b/kymo/Core/Services/CPUTemperatureServiceClient.swift new file mode 100644 index 0000000..6b8a45d --- /dev/null +++ b/kymo/Core/Services/CPUTemperatureServiceClient.swift @@ -0,0 +1,73 @@ +import Foundation + +nonisolated enum CPUTemperatureServiceClient { + static func read(gpu: Bool = false) async -> Double? { + let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc") + guard let requirement = CodeIdentity.requirement(at: url) else { return nil } + return await withCheckedContinuation { continuation in + let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService") + connection.setCodeSigningRequirement(requirement) + connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self) + let reply = Reply(connection: connection, continuation: continuation) + connection.invalidationHandler = { reply.finish(nil) } + connection.interruptionHandler = { reply.finish(nil) } + connection.resume() + guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else { + reply.finish(nil) + return + } + let receive: (NSNumber?) -> Void = { number in + let value = number?.doubleValue + reply.finish(value.flatMap { $0.isFinite && $0 > 0 && $0 < 150 ? $0 : nil }) + } + if gpu { proxy.readGPUTemperature(withReply: receive) } + else { proxy.readCPUTemperature(withReply: receive) } + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) } + } + } + + static func readFans() async -> [FanMetrics]? { + let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc") + guard let requirement = CodeIdentity.requirement(at: url) else { return nil } + return await withCheckedContinuation { continuation in + let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService") + connection.setCodeSigningRequirement(requirement) + connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self) + let reply = Reply(connection: connection, continuation: continuation) + connection.invalidationHandler = { reply.finish(nil) } + connection.interruptionHandler = { reply.finish(nil) } + connection.resume() + guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else { + reply.finish(nil); return + } + proxy.readFanSpeeds { values in + guard let values, values.count <= 10 else { reply.finish(nil); return } + reply.finish(values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) }) + } + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) } + } + } + + private final class Reply: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private let connection: NSXPCConnection + + init(connection: NSXPCConnection, continuation: CheckedContinuation) { + self.connection = connection + self.continuation = continuation + } + + func finish(_ value: Value?) { + lock.lock() + let callback = continuation + continuation = nil + lock.unlock() + guard let callback else { return } + connection.invalidationHandler = nil + connection.interruptionHandler = nil + connection.invalidate() + callback.resume(returning: value) + } + } +} diff --git a/kymo/Core/Services/SMARTServiceProtocol.swift b/kymo/Core/Services/SMARTServiceProtocol.swift index 8a46c2b..2ccd4bb 100644 --- a/kymo/Core/Services/SMARTServiceProtocol.swift +++ b/kymo/Core/Services/SMARTServiceProtocol.swift @@ -2,5 +2,8 @@ import Foundation /// Fixed read-only operation: no caller-supplied paths or commands. @objc protocol SMARTServiceProtocol { + nonisolated func readFanSpeeds(withReply reply: @escaping ([NSNumber]?) -> Void) nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void) + nonisolated func readGPUTemperature(withReply reply: @escaping (NSNumber?) -> Void) + nonisolated func readCPUTemperature(withReply reply: @escaping (NSNumber?) -> Void) } diff --git a/kymo/Core/Services/SamplingDiagnostics.swift b/kymo/Core/Services/SamplingDiagnostics.swift index c19f90e..4b598bb 100644 --- a/kymo/Core/Services/SamplingDiagnostics.swift +++ b/kymo/Core/Services/SamplingDiagnostics.swift @@ -14,6 +14,7 @@ nonisolated enum SamplingDiagnostics { ] payload["cpu"] = snapshot.cpu?.usage payload["cores"] = snapshot.cpu?.cores.count + payload["cpuTemperature"] = snapshot.cpuTemperature payload["gpuUsage"] = snapshot.gpuUsage payload["gpuCoreCount"] = snapshot.gpu?.coreCount payload["processEnumerated"] = snapshot.processes?.enumerated @@ -32,6 +33,7 @@ nonisolated enum SamplingDiagnostics { payload["volumeCount"] = snapshot.volumes?.count payload["batteryCycles"] = snapshot.battery?.cycles payload["batteryHealth"] = snapshot.battery?.health + payload["batteryPower"] = snapshot.battery?.power var info = task_vm_info_data_t() var count = mach_msg_type_number_t(MemoryLayout.size / MemoryLayout.size) let status = withUnsafeMutablePointer(to: &info) { pointer in diff --git a/kymo/Features/MenuBar/CPUCoreGrid.swift b/kymo/Features/MenuBar/CPUCoreGrid.swift index 0cb9512..18aa316 100644 --- a/kymo/Features/MenuBar/CPUCoreGrid.swift +++ b/kymo/Features/MenuBar/CPUCoreGrid.swift @@ -27,42 +27,98 @@ struct CPUCoreGrid: View { } } + static func groups(count: Int, kinds: [Int: CPUCoreTopology.Kind]) -> [[Int]] { + let order: [CPUCoreTopology.Kind?] = [.efficiency, .middle, .performance, nil] + return order.map { kind in (0.. [CGFloat] { + let weights = groups.map { CGFloat(($0.count + 1) / 2) } + let total = max(1, weights.reduce(0, +)) + let available = max(0, width - CGFloat(max(0, groups.count - 1)) * 13) + return weights.map { available * $0 / total } + } + var body: some View { - CPUCoreGridLayout { - ForEach(Array(values.enumerated()), id: \.offset) { index, value in - let kind = kinds[index] - GeometryReader { proxy in - let numberWidth = min(max(12, CGFloat(String(values.count).count) * 6), max(0, proxy.size.width * 0.45)) - let spacing = min(3, proxy.size.width * 0.08) - ZStack(alignment: .leading) { - Text(verbatim: "\(index + 1)").font(.system(size: 9)) - .lineLimit(1).minimumScaleFactor(0.3).frame(width: numberWidth) - MetricProgressBar(value: value, color: color(kind)) - .frame(width: max(0, proxy.size.width - numberWidth - spacing), height: 7) - .offset(x: numberWidth + spacing) - .animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, interval * 0.8)), value: value) - }.frame(width: proxy.size.width, height: proxy.size.height, alignment: .leading) - }.clipped() - .help((kind.map { label($0) + Text(verbatim: " · ") } ?? Text("cpu.core")) + Text(verbatim: "\(index + 1): \(MetricFormat.percent(value))")) - .accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core")) - .accessibilityValue("\(index + 1): \(MetricFormat.percent(value))") + let groups = Self.groups(count: values.count, kinds: kinds) + GeometryReader { geometry in + let widths = Self.groupWidths(groups: groups, width: geometry.size.width) + let diameter = zip(groups, widths).map { indices, width in + let columns = CPUCoreGridLayout.rowCounts(count: indices.count, width: width).max() ?? 1 + let spacing = min(CPUCoreGridLayout.columnSpacing, max(0, (width / CGFloat(columns) - 18) / 2)) + return max(0, (width - CGFloat(columns - 1) * spacing) / CGFloat(columns) - 4) + }.min() ?? 20 + HStack(alignment: .top, spacing: 6) { + ForEach(groups.indices, id: \.self) { group in + if group > 0 { + Rectangle().fill(.primary.opacity(0.08)).frame(width: 1) + } + VStack(alignment: .leading, spacing: 5) { + HStack(spacing: 3) { + Circle().fill(color(kinds[groups[group][0]])).frame(width: 5, height: 5) + if let kind = kinds[groups[group][0]] { label(kind) } + else { Text("cpu.core") } + Text(verbatim: "\(groups[group].count)").foregroundStyle(.secondary) + } + .font(.system(size: 9, weight: .medium)) + .lineLimit(1).minimumScaleFactor(0.6) + CPUCoreGridLayout { + ForEach(groups[group], id: \.self) { index in + ring(index: index, maximumDiameter: min(20, diameter)) + } + } + }.frame(width: widths[group], alignment: .topLeading) + } } - }.padding(.vertical, 3) + } + .frame(height: 15 + CGFloat(maxRows(groups: groups)) * 22 + CGFloat(max(0, maxRows(groups: groups) - 1)) * 4) + .padding(.vertical, 4) + } + + // Match the content width so row reservation agrees with placement. + var availableWidth: CGFloat = 380 + + private func maxRows(groups: [[Int]]) -> Int { + let widths = Self.groupWidths(groups: groups, width: availableWidth) + return zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0 + } + + private func ring(index: Int, maximumDiameter: CGFloat) -> some View { + let kind = kinds[index] + let value = values[index].isFinite ? min(1, max(0, values[index])) : 0 + return GeometryReader { proxy in + let diameter = min(maximumDiameter, max(0, proxy.size.width - 4)) + ZStack { + Circle().inset(by: 1).stroke(color(kind).opacity(0.16), lineWidth: 2) + Circle().inset(by: 1).trim(from: 0, to: value) + .stroke(color(kind), style: StrokeStyle(lineWidth: 2, lineCap: .round)) + .rotationEffect(.degrees(-90)) + .animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, interval * 0.8)), value: value) + Text(verbatim: "\(Int((value * 100).rounded()))") + .font(.system(size: 8, weight: .medium)).lineLimit(1).minimumScaleFactor(0.4) + } + .frame(width: diameter, height: diameter) + .frame(width: proxy.size.width, height: proxy.size.height) + } + .help((kind.map { label($0) + Text(verbatim: " · ") } ?? Text("cpu.core")) + Text(verbatim: "\(index + 1): \(MetricFormat.percent(value))")) + .accessibilityLabel(kind.map { label($0) } ?? Text("cpu.core")) + .accessibilityValue("\(index + 1): \(MetricFormat.percent(value))") } } struct CPUCoreGridLayout: Layout { static let columnSpacing: CGFloat = 6 - static let rowSpacing: CGFloat = 5 - static let rowHeight: CGFloat = 12 - static let preferredCellWidth: CGFloat = 38 + static let rowSpacing: CGFloat = 4 + static let rowHeight: CGFloat = 22 + static let minimumTwoRowCellWidth: CGFloat = 16 static func rowCounts(count: Int, width: CGFloat) -> [Int] { guard count > 0 else { return [] } guard count > 1 else { return [1] } let twoColumns = (count + 1) / 2 - let widthForTwoRows = CGFloat(twoColumns) * preferredCellWidth + CGFloat(twoColumns - 1) * columnSpacing - let rows = count > 2 && width < widthForTwoRows ? 3 : 2 + let availableForCells = width - CGFloat(twoColumns - 1) * columnSpacing + let twoRowCellWidth = availableForCells / CGFloat(twoColumns) + let rows = count > 2 && twoRowCellWidth < minimumTwoRowCellWidth ? 3 : 2 let quotient = count / rows, remainder = count % rows return (0.. some View { + VStack(spacing: 3) { + HStack(spacing: 4) { + Text(title).foregroundStyle(.secondary) + Spacer(minLength: 0) + AnimatedMetricText(value: MetricFormat.bytes(bytes)).fontWeight(.medium) + }.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.7) + MetricProgressBar(value: bytes.map { Double($0) / reference } ?? 0, color: color) + .frame(height: 3) + .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: bytes) + .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: reference) + .accessibilityHidden(true) + } + } +} diff --git a/kymo/Features/MenuBar/MenuPanelView.swift b/kymo/Features/MenuBar/MenuPanelView.swift index 19fe871..6b6f2fe 100644 --- a/kymo/Features/MenuBar/MenuPanelView.swift +++ b/kymo/Features/MenuBar/MenuPanelView.swift @@ -8,6 +8,7 @@ struct MenuPanelView: View { let settingsPresentation: SettingsPresentation var presentation = PanelPresentation() var onOpenSettings: () -> Void = {} + @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var panelSize = PanelLayout.contentSize(visible: NSScreen.main?.visibleFrame ?? CGRect(x: 0, y: 0, width: 1000, height: 760)) @State private var selectedInterface = "" @State private var showAddresses = false @@ -19,6 +20,14 @@ struct MenuPanelView: View { private var chartInterval: TimeInterval { Double(metrics.effectiveMilliseconds) / 1000 } private var chartBoundaries: Set { Set(samples.filter(\.breakBefore).map(\.date)) } private var columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 } + private var firstRowHeight: CGFloat { + let cardWidth = (panelSize.width - 20 - CGFloat(columns - 1) * 8) / CGFloat(columns) + let groups = CPUCoreGrid.groups(count: snapshot.cpu?.cores.count ?? 0, kinds: CPUCoreTopology.cores) + let widths = CPUCoreGrid.groupWidths(groups: groups, width: max(0, cardWidth - 20)) + let coreRows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0 + let extraFanRows = max(0, ((snapshot.fans?.count ?? 0) + 1) / 2 - 1) + return max(260 + (coreRows >= 3 ? 26 : 0), 260 + CGFloat(extraFanRows) * 19) + } private var network: [NetworkInterfaceMetrics] { (snapshot.network ?? []).filter { selectedInterface.isEmpty ? $0.isIncludedInTotal : $0.identity == selectedInterface } } @@ -36,9 +45,9 @@ struct MenuPanelView: View { } else { ScrollView { LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .top), count: columns), spacing: 8) { - cpuCard.frame(minHeight: 240) - gpuCard.frame(minHeight: 240) - batteryCard.aspectRatio(4.0 / 3.0, contentMode: .fit) + cpuCard.frame(height: firstRowHeight) + gpuCard.frame(height: firstRowHeight) + batteryCard.frame(height: firstRowHeight) memoryCard.frame(minHeight: 240) diskCard.frame(minHeight: 250) networkCard.frame(minHeight: 250) @@ -68,10 +77,10 @@ struct MenuPanelView: View { private var resourceRows: some View { VStack(spacing: 8) { HStack(alignment: .top, spacing: 8) { - cpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize)) - gpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize)) - batteryCard.frame(width: PanelLayout.batteryWidth(size: panelSize)) - }.frame(height: PanelLayout.resourceRowHeight(size: panelSize)) + cpuCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight) + gpuCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight) + batteryCard.frame(width: PanelLayout.cardWidth(size: panelSize), height: firstRowHeight) + }.frame(height: firstRowHeight) HStack(alignment: .top, spacing: 8) { memoryCard.frame(width: (panelSize.width - 36) / 3) diskCard.frame(width: (panelSize.width - 36) / 3) @@ -83,10 +92,18 @@ struct MenuPanelView: View { private var header: some View { HStack(spacing: 10) { Image("BrandMark").renderingMode(.template) - Text("Kymo").font(.system(size: 18, weight: .semibold)) - Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")") - .font(.system(size: 10)).foregroundStyle(.secondary) + HStack(alignment: .firstTextBaseline, spacing: 2) { + Text("Kymo").font(.system(size: 18, weight: .semibold)) + Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")") + .font(.system(size: 8, weight: .medium)) + .foregroundStyle(.secondary) + .baselineOffset(7) + } if panelSize.width >= 900 { + Rectangle() + .fill(.secondary.opacity(0.32)) + .frame(width: 1, height: 16) + .accessibilityHidden(true) Text(verbatim: HardwareIdentity.displayName) .font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) } @@ -122,58 +139,97 @@ struct MenuPanelView: View { } } + private func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey { + if battery.charging { return "battery.chargePower" } + if !battery.externalPower { return "battery.dischargePower" } + return "battery.power" + } + private var cpuCard: some View { - ResourceCard(title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), value: MetricFormat.percent(snapshot.cpu?.usage)) { + let temperature = snapshot.cpuTemperature + let highTemperature = CPUTemperatureMonitor.isHighTemperature(temperature) + return ResourceCard( + title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), + value: MetricFormat.percent(snapshot.cpu?.usage), + status: temperature.map { "\(Int($0.rounded()))°C" }, + statusWarning: highTemperature, + statusHelp: temperature == nil ? nil : Text("cpu.temperature.help", tableName: "CPUDetails"), + warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil + ) { PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.cpu), second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem), color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"), - firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) + firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) if let cpu = snapshot.cpu { - HStack { line("cpu.user", MetricFormat.percent(cpu.user)); line("cpu.system", MetricFormat.percent(cpu.system)) } - let kinds = [CPUCoreTopology.Kind.efficiency, .middle, .performance].filter { CPUCoreTopology.cores.values.contains($0) } - if !kinds.isEmpty { - HStack(spacing: 10) { - ForEach(kinds, id: \.rawValue) { kind in - HStack(spacing: 3) { Circle().fill(coreColor(kind)).frame(width: 6, height: 6); coreLabel(kind) } - } - }.font(.system(size: 9)).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading) - } - CPUCoreGrid(values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval) + Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) + Spacer(minLength: 0) + CPUCoreGrid(values: cpu.cores, kinds: CPUCoreTopology.cores, interval: chartInterval, + availableWidth: max(0, (columns == 3 ? PanelLayout.cardWidth(size: panelSize) : (panelSize.width - 20 - CGFloat(columns - 1) * 8) / CGFloat(columns)) - 20)) } else { Text("metric.waiting").foregroundStyle(.secondary) } Spacer(minLength: 0) - HStack(spacing: 5) { - HStack(spacing: 5) { - Text("cpu.load.oneMinute", tableName: "CPUDetails").foregroundStyle(.secondary) - if let load = snapshot.load.first, load.isFinite, load >= 0, let count = snapshot.cpu?.cores.count, count > 0 { - MetricProgressBar(value: load / Double(count), color: Color("MetricCPU")) - .frame(minWidth: 20, maxWidth: .infinity).frame(height: 7) - .accessibilityHidden(true) - AnimatedMetricText(value: "\(MetricFormat.decimal(load)) / \(count)") - } else { - Spacer(minLength: 20) - Text(verbatim: "--") + Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) + HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 4) { + HStack { + Text("cpu.load.oneMinute", tableName: "CPUDetails").foregroundStyle(.secondary) + Spacer(minLength: 3) + AnimatedMetricText(value: snapshot.load.first.map { "\(MetricFormat.decimal($0)) / \(snapshot.cpu?.cores.count ?? 0)" } ?? "--") } + MetricProgressBar(value: (snapshot.load.first ?? 0) / Double(max(1, snapshot.cpu?.cores.count ?? 0)), color: Color("MetricCPU")) + .frame(height: 5).accessibilityHidden(true) + }.frame(maxWidth: .infinity).help(Text("cpu.load.help", tableName: "CPUDetails")) + Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 25) + VStack(alignment: .leading, spacing: 3) { + Text("panel.uptime").foregroundStyle(.secondary) + AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600)) + .fontWeight(.medium) } - .help(Text("cpu.load.help", tableName: "CPUDetails")) - Spacer(minLength: 8) - Text("panel.uptime").foregroundStyle(.secondary) - AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600)) - } - .lineLimit(1).minimumScaleFactor(0.7) + }.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7) + } } private var gpuCard: some View { - ResourceCard(title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage)) { - chart(\.gpu, color: Color("MetricGPU")) + let summary = GPUUtilizationSummary(samples: samples) + return ResourceCard(title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage), + status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" }, + statusHelp: Text("gpu.temperatureHelp"), + detail: snapshot.gpu?.coreCount.map { String(format: String(localized: "gpu.coreCountFormat"), $0) }) { + PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.gpu), + second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler), + color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"), + firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler", + expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals) if snapshot.gpuUsage == nil { Text("gpu.unavailable").foregroundStyle(.secondary) } - line("panel.gpuCores", snapshot.gpu?.coreCount.map(String.init) ?? "--") - Label("panel.gpuPerCore", systemImage: "info.circle").foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) + gpuActivity("gpu.rendererActivity", value: snapshot.gpu?.renderer, color: Color("MetricCPU")) + gpuActivity("gpu.tilerActivity", value: snapshot.gpu?.tiler, color: Color("SeriesSystem")) + Divider().padding(.vertical, 3) Spacer(minLength: 0) - Text("panel.gpuSource").font(.system(size: 9)).foregroundStyle(.secondary) + GPUStatisticsView(inUse: snapshot.gpu?.inUseMemory, allocated: snapshot.gpu?.allocatedMemory, + average: summary.average, peak: summary.peak) + Spacer(minLength: 0) + if let fans = snapshot.fans, !fans.isEmpty { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 5) { + ForEach(fans) { fan in + FanSpeedIndicator(title: fans.count == 2 ? (fan.id == 0 ? "gpu.fanLeft" : "gpu.fanRight") : LocalizedStringKey("\(String(localized: "gpu.fan")) \(fan.id + 1)"), rpm: fan.rpm) + } + } + .padding(.horizontal, 7).padding(.vertical, 5) + .background(.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6)) + } } } + + private func gpuActivity(_ title: LocalizedStringKey, value: Double?, color: Color) -> some View { + HStack(spacing: 8) { + Text(title).frame(width: 65, alignment: .leading) + MetricProgressBar(value: value ?? 0, color: color).frame(height: 5) + .animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, chartInterval * 0.8)), value: value) + AnimatedMetricText(value: MetricFormat.percent(value)).frame(width: 30, alignment: .trailing) + }.font(.system(size: 10)).help(Text("gpu.pipelineHelp")) + } private var memoryCard: some View { ResourceCard(title: "metric.memory", symbol: "memorychip", color: Color("MetricMemory"), value: snapshot.memory.map { String(format: "%.1f / %.1f GB", Double($0.used) / 1_000_000_000, Double($0.total) / 1_000_000_000) } ?? "--") { PanelTrendChart(dates: samples.map(\.date), @@ -294,17 +350,68 @@ struct MenuPanelView: View { private var batteryCard: some View { ResourceCard(title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"), value: MetricFormat.percent(snapshot.battery?.charge)) { if let battery = snapshot.battery { - chart(\.battery, color: Color("MetricBattery"), label: "metric.battery") - Text(battery.charging ? "battery.charging" : battery.externalPower ? "battery.external" : "battery.discharging") - line("battery.cycles", battery.cycles.map(String.init) ?? "--") - line("battery.health", MetricFormat.percent(battery.health)) - HStack { - Text(battery.charging ? "battery.timeFull" : "battery.timeEmpty").foregroundStyle(.secondary) - Spacer() - if battery.externalPower && !battery.charging { Text("battery.timeNotApplicable") } - else if let minutes = battery.minutesRemaining { AnimatedMetricText(value: "\(minutes) min") } - else { Text("battery.timeUnknown") } + PanelTrendChart( + dates: samples.map(\.date), + first: samples.map(\.battery), + second: samples.map(\.batteryPower), + color: Color("MetricBattery"), + secondColor: Color("SeriesUser"), + fixedScale: 1, + secondSeriesUsesAutonomousScale: true, + secondValueFormat: .watts, + firstLabel: "metric.battery", + secondLabel: batteryPowerLabel(battery), + expectedInterval: chartInterval, + boundaryDates: chartBoundaries, + intervals: chartIntervals + ) + Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) + HStack(alignment: .top, spacing: 10) { + VStack(spacing: 5) { + line("battery.health", MetricFormat.percent(battery.health)) + HStack { + Text("battery.powerSource").foregroundStyle(.secondary) + Spacer(minLength: 4) + Text(battery.externalPower ? "battery.acPower" : "battery.batterySource") + } + } + Rectangle().fill(.primary.opacity(0.08)).frame(width: 1, height: 32) + VStack(spacing: 5) { + line("battery.cycles", battery.cycles.map(String.init) ?? "--") + HStack { + Text("battery.timeEstimate").foregroundStyle(.secondary) + Spacer(minLength: 4) + if battery.externalPower { Text("battery.timeNotApplicable") } + else if let minutes = battery.minutesRemaining { AnimatedMetricText(value: "\(minutes) min") } + else { Text("battery.timeUnknown") } + } + } } + .font(.system(size: 10)) + .lineLimit(1).minimumScaleFactor(0.72) + .frame(height: 32) + Spacer(minLength: 0) + Rectangle().fill(.primary.opacity(0.08)).frame(height: 1).padding(.vertical, 3) + VStack(alignment: .leading, spacing: 4) { + HStack { + Text("battery.highestEnergyProcess").fontWeight(.semibold) + Spacer() + Text("battery.cpuUsage").foregroundStyle(.secondary) + } + .font(.system(size: 10)) + let energyProcesses = snapshot.processes?.highestCPUProcesses(limit: 3) ?? [] + if energyProcesses.isEmpty { + Text("metric.waiting").foregroundStyle(.secondary) + } else { + ForEach(energyProcesses) { process in + EnergyProcessListRow(process: process) + } + } + } + // Reserve the header and all three rows before process sampling completes. + .frame(height: 72, alignment: .top) + .lineLimit(1) + .help(Text("battery.energyProxyHelp")) } else { Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary) @@ -356,13 +463,61 @@ struct MenuPanelView: View { } .buttonStyle(PanelControlButtonStyle()) .padding(4) - .background(Color("PanelCard"), in: .capsule) + .glassEffect(.regular, in: .capsule) } .controlSize(.small) .padding(.horizontal, 2).padding(.vertical, 0) } } +private struct EnergyProcessListRow: View { + let process: ProcessMetrics + @State private var icon: NSImage? + + private var progress: Double { + guard let value = process.cpu, value.isFinite else { return 0 } + return min(max(value, 0), 1) + } + + var body: some View { + HStack(spacing: 5) { + Group { + if let icon { + Image(nsImage: icon).resizable().interpolation(.high) + } else { + Image(systemName: "app.dashed").resizable().scaledToFit().padding(2) + } + } + .frame(width: 15, height: 15) + .accessibilityHidden(true) + Text(verbatim: process.name).lineLimit(1).truncationMode(.middle) + .frame(width: 66, alignment: .leading) + GeometryReader { proxy in + Capsule().fill(.primary.opacity(0.07)) + .overlay(alignment: .leading) { + Capsule().fill(Color("MetricCPU")) + .frame(width: proxy.size.width * progress, height: 4) + .clipped() + } + .clipShape(Capsule()) + } + .frame(height: 4) + .animation(.easeInOut(duration: 0.35), value: process.cpu) + AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--") + .foregroundStyle(Color("MetricCPU")) + .monospacedDigit().frame(width: 39, alignment: .trailing) + } + .font(.system(size: 10)) + .frame(height: 16) + .task(id: process.id) { + icon = NSRunningApplication(processIdentifier: process.id.pid)?.icon + if icon == nil, let path = process.path { + icon = NSWorkspace.shared.icon(forFile: path) + } + } + } +} + private struct PanelControlButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { diff --git a/kymo/Features/MenuBar/PanelLayout.swift b/kymo/Features/MenuBar/PanelLayout.swift index b52f00e..dbe9e64 100644 --- a/kymo/Features/MenuBar/PanelLayout.swift +++ b/kymo/Features/MenuBar/PanelLayout.swift @@ -2,9 +2,12 @@ import Foundation import CoreGraphics nonisolated enum PanelLayout { - static func resourceRowHeight(size: CGSize) -> CGFloat { min(230, max(220, size.height - 590)) } - static func batteryWidth(size: CGSize) -> CGFloat { resourceRowHeight(size: size) * 4 / 3 } - static func firstRowWideCardWidth(size: CGSize) -> CGFloat { (size.width - 36 - batteryWidth(size: size)) / 2 } + static func resourceRowHeight(size: CGSize, coreRows: Int) -> CGFloat { + let compact = min(239, max(224, size.height - 581)) + let thirdRowExpansion: CGFloat = coreRows >= 3 ? 26 : 0 + return min(265, compact + thirdRowExpansion) + } + static func cardWidth(size: CGSize) -> CGFloat { max(0, (size.width - 36) / 3) } static func contentSize(visible: CGRect, chrome: CGSize = .zero) -> CGSize { CGSize(width: max(1, min(1240, visible.width - 32 - max(0, chrome.width))), diff --git a/kymo/Resources/CPUDetails.xcstrings b/kymo/Resources/CPUDetails.xcstrings index b98e001..0ed1074 100644 --- a/kymo/Resources/CPUDetails.xcstrings +++ b/kymo/Resources/CPUDetails.xcstrings @@ -115,6 +115,52 @@ } } } + }, + "cpu.temperature.help": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Highest valid CPU cluster sensor reading; warning at 90°C." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "CPU 核心区域的最高有效传感器读数;达到 90°C 时提示。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "CPU 核心區域的最高有效感測器讀數;達到 90°C 時提示。" + } + } + } + }, + "cpu.temperature.high": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "High temperature" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "温度过高" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "溫度過高" + } + } + } } }, "version": "1.0" diff --git a/kymo/Resources/Localizable.xcstrings b/kymo/Resources/Localizable.xcstrings index b77f33d..e7faf3c 100644 --- a/kymo/Resources/Localizable.xcstrings +++ b/kymo/Resources/Localizable.xcstrings @@ -1,6 +1,19 @@ { "sourceLanguage" : "en", "strings" : { + "%@ %lld" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ %2$lld" + } + } + } + }, + "%lld cores" : { + + }, "%lld: %@" : { "localizations" : { "en" : { @@ -262,209 +275,140 @@ } } }, - "action.file" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "File" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "文件" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "檔案" - } - } - } - }, "action.closeWindow" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Close Window" + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Close Window" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "关闭窗口" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "关闭窗口" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "關閉視窗" - } - } - } - }, - "action.edit" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Edit" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "编辑" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "編輯" - } - } - } - }, - "action.undo" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Undo" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "撤销" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "復原" - } - } - } - }, - "action.redo" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Redo" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "重做" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "重做" - } - } - } - }, - "action.cut" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Cut" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "剪切" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "剪下" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "關閉視窗" } } } }, "action.copy" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Copy" + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Copy" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "复制" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "复制" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "複製" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "複製" + } + } + } + }, + "action.cut" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cut" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "剪切" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "剪下" + } + } + } + }, + "action.edit" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Edit" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "编辑" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "編輯" + } + } + } + }, + "action.file" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "File" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "文件" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "檔案" } } } }, "action.paste" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Paste" + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paste" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "粘贴" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "粘贴" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "貼上" - } - } - } - }, - "action.selectAll" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Select All" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "全选" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "全選" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "貼上" } } } @@ -515,6 +459,29 @@ } } }, + "action.redo" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Redo" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "重做" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "重做" + } + } + } + }, "action.resume" : { "extractionState" : "manual", "localizations" : { @@ -538,6 +505,29 @@ } } }, + "action.selectAll" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Select All" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "全选" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "全選" + } + } + } + }, "action.settings" : { "extractionState" : "manual", "localizations" : { @@ -561,6 +551,29 @@ } } }, + "action.undo" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Undo" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "撤销" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "復原" + } + } + } + }, "appearance.dark" : { "extractionState" : "manual", "localizations" : { @@ -763,7 +776,74 @@ } } }, + "battery.acPower" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "AC power" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "交流电" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "交流電" + } + } + } + }, + "battery.batterySource" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Battery" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "电池" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "電池" + } + } + } + }, + "battery.chargePower" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Charge power" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "充电功率" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "充電功率" + } + } + } + }, "battery.charging" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -785,6 +865,28 @@ } } }, + "battery.cpuUsage" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "CPU utilization" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "CPU 利用率" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "CPU 利用率" + } + } + } + }, "battery.cycles" : { "localizations" : { "en" : { @@ -807,7 +909,30 @@ } } }, + "battery.dischargePower" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Discharge power" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "放电功率" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "放電功率" + } + } + } + }, "battery.discharging" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -829,7 +954,30 @@ } } }, + "battery.energyProxyHelp" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ranked by current process CPU usage; this is not the system energy impact score." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "按当前进程 CPU 利用率排序,不代表系统能耗影响评分。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "依目前處理程序 CPU 使用率排序,不代表系統能耗影響評分。" + } + } + } + }, "battery.external" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -873,7 +1021,74 @@ } } }, + "battery.highestEnergyProcess" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Energy use" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "耗电进程" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "耗電處理程序" + } + } + } + }, + "battery.power" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Battery power" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "电池功率" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "電池功率" + } + } + } + }, + "battery.powerSource" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Power source" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "电源类型" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "電源類型" + } + } + } + }, "battery.timeEmpty" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -896,7 +1111,6 @@ } }, "battery.timeEstimate" : { - "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -919,6 +1133,7 @@ } }, "battery.timeFull" : { + "extractionState" : "stale", "localizations" : { "en" : { "stringUnit" : { @@ -1302,6 +1517,472 @@ } } }, + "gpu.allocatedMemory" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Driver allocated" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "驱动分配" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "驅動分配" + } + } + } + }, + "gpu.average" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Average" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "平均" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "平均" + } + } + } + }, + "gpu.coreCountFormat" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%d cores" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%d 核" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%d 核" + } + } + } + }, + "gpu.driverMemory" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Driver memory in use" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "驱动在用内存" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "驅動在用記憶體" + } + } + } + }, + "gpu.fan" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fan" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "风扇" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "風扇" + } + } + } + }, + "gpu.fanHelp" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "System fan speed, not a dedicated GPU fan. Left/right describe display order (fan 1/2); physical position is unverified. Zero RPM stops the icon; unavailable readings show --." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "整机风扇,并非 GPU 专属。左右为显示排布(风扇 1/2),物理位置尚未确认。0 RPM 时图标停止,读取失败显示 --。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "整機風扇,並非 GPU 專屬。左右為顯示排布(風扇 1/2),物理位置尚未確認。0 RPM 時圖示停止,讀取失敗顯示 --。" + } + } + } + }, + "gpu.fanLeft" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Left" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "左" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "左" + } + } + } + }, + "gpu.fanRight" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Right" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "右" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "右" + } + } + } + }, + "gpu.memoryComparisonHelp" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU driver system-memory accounting, not dedicated VRAM. The two bars share a changing byte scale to compare absolute values; they do not show capacity usage. Allocated memory is not necessarily resident." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 驱动的系统内存统计,不代表独立显存。两条横条共用动态字节尺度,仅比较绝对值,不表示容量占比;分配量不等于实际驻留量。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 驅動的系統記憶體統計,不代表獨立顯示記憶體。兩條橫條共用動態位元組尺度,僅比較絕對值,不表示容量佔比;分配量不等於實際駐留量。" + } + } + } + }, + "gpu.memoryHelp" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "System memory accounting reported by the GPU driver, not dedicated VRAM capacity. Allocated memory is not necessarily resident." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 驱动报告的系统内存统计,不代表独立显存容量;分配量不等于实际驻留量。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 驅動報告的系統記憶體統計,不代表獨立顯示記憶體容量;分配量不等於實際駐留量。" + } + } + } + }, + "gpu.peak" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Peak" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "峰值" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "峰值" + } + } + } + }, + "gpu.pipelineHelp" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pipeline activity; values are not additive" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "流水线阶段活跃度,不相加" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "流水線階段活躍度,不相加" + } + } + } + }, + "gpu.recentAverage" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Recent average" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "近 1 分钟平均" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "近 1 分鐘平均" + } + } + } + }, + "gpu.recentUtilization" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Last minute utilization" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "近 1 分钟利用率" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "近 1 分鐘利用率" + } + } + } + }, + "gpu.renderer" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Renderer" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "渲染" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "渲染" + } + } + } + }, + "gpu.rendererActivity" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Renderer activity" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "渲染活跃度" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "渲染活躍度" + } + } + } + }, + "gpu.summaryHelp" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Time-weighted over available history, up to one minute. Missing samples and sleep gaps are excluded." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "按实际时间加权,仅统计可用历史,最多最近 1 分钟;不跨越缺失数据或休眠间隔。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "依實際時間加權,僅統計可用歷史,最多最近 1 分鐘;不跨越缺失資料或睡眠間隔。" + } + } + } + }, + "gpu.temperatureHelp" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Highest valid GPU temperature-zone reading, not an official package or per-core temperature." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 温区有效读数的最高值,不代表官方封装温度或逐核温度。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "GPU 溫區有效讀數的最高值,不代表官方封裝溫度或逐核心溫度。" + } + } + } + }, + "gpu.tiler" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tiler" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分块" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分塊" + } + } + } + }, + "gpu.tilerActivity" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tiler activity" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分块活跃度" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分塊活躍度" + } + } + } + }, + "gpu.totalUtilization" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Total utilization" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "总利用率" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "總利用率" + } + } + } + }, "gpu.unavailable" : { "extractionState" : "manual", "localizations" : { @@ -2329,6 +3010,52 @@ } } }, + "panel.pin" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pin panel on top" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "固定面板并置顶" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "固定面板並置頂" + } + } + } + }, + "panel.pinned" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pinned" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已固定" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已固定" + } + } + } + }, "panel.processes" : { "extractionState" : "manual", "localizations" : { @@ -2673,6 +3400,52 @@ } } }, + "panel.unpin" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Unpin panel" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "取消固定面板" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "取消固定面板" + } + } + } + }, + "panel.unpinned" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Not pinned" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未固定" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "未固定" + } + } + } + }, "panel.uptime" : { "extractionState" : "manual", "localizations" : { @@ -2768,278 +3541,163 @@ } } }, - "sampling.panel" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Panel refresh interval" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "面板刷新间隔" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "面板重新整理間隔" - } - } - } - }, "sampling.background" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Background refresh interval" + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Background refresh interval" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "后台刷新间隔" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "后台刷新间隔" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "背景重新整理間隔" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "背景重新整理間隔" } } } }, "sampling.backgroundHelp" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Applies while the panel is closed. Default: 5 seconds. Panel interval is adjusted in its toolbar." + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Applies while the panel is closed. Default: 5 seconds. Panel interval is adjusted in its toolbar." } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "仅在面板关闭时生效,默认 5 秒。面板打开时的间隔在顶部工具栏单独调整。" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "仅在面板关闭时生效,默认 5 秒。面板打开时的间隔在顶部工具栏单独调整。" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "僅在面板關閉時生效,預設 5 秒。面板開啟時的間隔在頂部工具列獨立調整。" - } - } - } - }, - "sampling.seconds" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Seconds" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "秒数" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "秒數" - } - } - } - }, - "sampling.unit" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "s" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "秒" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "秒" - } - } - } - }, - "sampling.interval" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Refresh interval" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "刷新间隔" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "重新整理間隔" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "僅在面板關閉時生效,預設 5 秒。面板開啟時的間隔在頂部工具列獨立調整。" } } } }, "sampling.bounds" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "0.5–1800 seconds, in 0.1-second steps" + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "0.5–1800 seconds, in 0.1-second steps" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "0.5–1800 秒,步进 0.1 秒" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "0.5–1800 秒,步进 0.1 秒" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "0.5–1800 秒,每次 0.1 秒" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "0.5–1800 秒,每次 0.1 秒" } } } }, - "settings.monitoring" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Monitoring" + "sampling.interval" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Refresh interval" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "监控" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "刷新间隔" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "監控" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "重新整理間隔" } } } }, - "panel.pin" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Pin panel on top" + "sampling.panel" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Panel refresh interval" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "固定面板并置顶" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "面板刷新间隔" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "固定面板並置頂" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "面板重新整理間隔" } } } }, - "panel.unpin" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Unpin panel" + "sampling.seconds" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Seconds" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "取消固定面板" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "秒数" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "取消固定面板" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "秒數" } } } }, - "panel.pinned" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Pinned" + "sampling.unit" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "s" } }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "已固定" + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "秒" } }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "已固定" - } - } - } - }, - "panel.unpinned" : { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Not pinned" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "未固定" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "未固定" + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "秒" } } } @@ -3112,6 +3770,29 @@ } } }, + "settings.monitoring" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Monitoring" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "监控" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "監控" + } + } + } + }, "settings.title" : { "extractionState" : "manual", "localizations" : { diff --git a/kymo/UI/Charts/PanelTrendChart.swift b/kymo/UI/Charts/PanelTrendChart.swift index b707d68..f06961f 100644 --- a/kymo/UI/Charts/PanelTrendChart.swift +++ b/kymo/UI/Charts/PanelTrendChart.swift @@ -1,5 +1,12 @@ import SwiftUI +enum TrendValueFormat { + case percent + case rate + case bytes + case watts +} + /// Bounded, timestamp-based curves. Gaps remain gaps; animation only runs on append. struct PanelTrendChart: View { let dates: [Date] @@ -11,15 +18,20 @@ struct PanelTrendChart: View { var thirdColor: Color = .purple var fixedScale: Double? = 1 var scaleLabel: String? + var secondSeriesUsesAutonomousScale = false + var secondValueFormat: TrendValueFormat? var firstLabel: LocalizedStringKey = "panel.total" var secondLabel: LocalizedStringKey = "network.upload" var thirdLabel: LocalizedStringKey = "cpu.system" var expectedInterval: TimeInterval = 2 var boundaryDates: Set = [] var intervals: [TimeInterval] = [] + var plotHeight: CGFloat = 58 @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var retainedScale: Double = 1 @State private var smallSamples = 0 + @State private var retainedSecondScale: Double = 1 + @State private var smallSecondSamples = 0 @State private var hoveredDate: Date? @State private var hoverPoint: CGPoint? @State private var previousBegin: Date? @@ -34,39 +46,50 @@ struct PanelTrendChart: View { boundaryDates: boundaryDates) } private var maximum: Double { max(1, (first + second + third).compactMap { $0 }.filter(\.isFinite).max() ?? 1) } + private var secondMaximum: Double { max(1, second.compactMap { $0 }.filter(\.isFinite).max() ?? 1) } private var scale: Double { max(0.0001, fixedScale ?? retainedScale) } + private var secondaryScale: Double { max(0.0001, retainedSecondScale) } + private var hasSecondaryScale: Bool { secondSeriesUsesAutonomousScale && !second.isEmpty } + private var automaticFormat: TrendValueFormat { + if fixedScale == 1 { return .percent } + if fixedScale == nil { return .rate } + return .bytes + } private var index: Int? { guard !dates.isEmpty else { return nil } guard let hoveredDate else { return dates.count - 1 } return dates.indices.min { abs(dates[$0].timeIntervalSince(hoveredDate)) < abs(dates[$1].timeIntervalSince(hoveredDate)) } } - private func formatted(_ value: Double?) -> String { + private func formatted(_ value: Double?, format: TrendValueFormat? = nil) -> String { guard let value, value.isFinite else { return "--" } - if fixedScale == 1 { return MetricFormat.percent(value) } - if fixedScale == nil { return MetricFormat.rate(value) } - return MetricFormat.bytes(UInt64(max(0, value))) + switch format ?? automaticFormat { + case .percent: return MetricFormat.percent(value) + case .rate: return MetricFormat.rate(value) + case .bytes: return MetricFormat.bytes(UInt64(max(0, value))) + case .watts: return MetricFormat.watts(value) + } } - private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color) -> some View { + private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil) -> some View { HStack(spacing: 3) { RoundedRectangle(cornerRadius: 1).fill(tint).frame(width: 7, height: 7) Text(label) - Text(verbatim: formatted(values.last ?? nil)).monospacedDigit() + Text(verbatim: formatted(values.last ?? nil, format: format)).monospacedDigit() }.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.8) } - private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, index: Int) -> some View { + private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil, index: Int) -> some View { HStack(spacing: 6) { RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8) Text(label) Spacer(minLength: 4) - Text(verbatim: formatted(index < values.count ? values[index] : nil)).monospacedDigit() + Text(verbatim: formatted(index < values.count ? values[index] : nil, format: format)).monospacedDigit() } } private func tooltip(index: Int) -> some View { VStack(alignment: .leading, spacing: 5) { Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.secondary) tooltipRow(firstLabel, values: first, tint: color, index: index) - if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, index: index) } + if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, format: secondValueFormat, index: index) } if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) } } .font(.system(size: 10)).padding(8) @@ -79,7 +102,7 @@ struct PanelTrendChart: View { VStack(spacing: 3) { HStack(spacing: 10) { legend(firstLabel, values: first, tint: color) - if !second.isEmpty { legend(secondLabel, values: second, tint: secondColor) } + if !second.isEmpty { legend(secondLabel, values: second, tint: secondColor, format: secondValueFormat) } if !third.isEmpty { legend(thirdLabel, values: third, tint: thirdColor) } Spacer(minLength: 0) }.frame(height: 14) @@ -91,11 +114,12 @@ struct PanelTrendChart: View { Spacer(minLength: 0) Text(verbatim: "0") }.font(.system(size: 8)).foregroundStyle(.secondary) - .lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: 58) + .lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: plotHeight) GeometryReader { proxy in ZStack(alignment: .topLeading) { PanelCurveCanvas(frame: displayedFrame ?? inputFrame, colors: [color, secondColor, thirdColor], - scale: scale, maximumGap: max(5, expectedInterval * 2), + scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale], + maximumGap: max(5, expectedInterval * 2), targetBegin: (lastFrame ?? inputFrame).dates.first, targetEnd: (lastFrame ?? inputFrame).dates.last, previousBegin: previousBegin, previousEnd: previousEnd, progress: progress) if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin { @@ -106,8 +130,9 @@ struct PanelTrendChart: View { ForEach(0..<3, id: \.self) { series in let values = [first, second, third][series] if index < values.count, let value = values[index], value.isFinite { + let seriesScale = [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale][series] Circle().fill([color, secondColor, thirdColor][series]).frame(width: 5, height: 5) - .position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / scale)))) + .position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / seriesScale)))) } } } @@ -124,11 +149,21 @@ struct PanelTrendChart: View { } } .clipped() - }.frame(height: 58) + }.frame(height: plotHeight) .anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { plot in guard let hoverPoint, let index else { return nil } return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index))) } + if hasSecondaryScale { + VStack(alignment: .leading) { + Text(verbatim: formatted(secondaryScale, format: .watts)) + Spacer(minLength: 0) + Text(verbatim: formatted(secondaryScale / 2, format: .watts)) + Spacer(minLength: 0) + Text(verbatim: "0 W") + }.font(.system(size: 8)).foregroundStyle(.secondary) + .lineLimit(1).minimumScaleFactor(0.6).frame(width: 45, height: plotHeight) + } } HStack { if let date = dates.first { Text(date, style: .time) } @@ -137,7 +172,12 @@ struct PanelTrendChart: View { }.font(.system(size: 9)).foregroundStyle(.secondary).frame(height: 12) } .frame(maxWidth: .infinity) - .onAppear { retainedScale = maximum; lastFrame = inputFrame; displayedFrame = inputFrame } + .onAppear { + retainedScale = maximum + retainedSecondScale = secondMaximum + lastFrame = inputFrame + displayedFrame = inputFrame + } .onChange(of: dates) { _, _ in let target = maximum if target > retainedScale { retainedScale = target; smallSamples = 0 } @@ -145,6 +185,12 @@ struct PanelTrendChart: View { smallSamples += 1 if smallSamples >= 10 { retainedScale = target; smallSamples = 0 } } else { smallSamples = 0 } + let secondTarget = secondMaximum + if secondTarget > retainedSecondScale { retainedSecondScale = secondTarget; smallSecondSamples = 0 } + else if secondTarget < retainedSecondScale * 0.5 { + smallSecondSamples += 1 + if smallSecondSamples >= 10 { retainedSecondScale = secondTarget; smallSecondSamples = 0 } + } else { smallSecondSamples = 0 } let next = inputFrame let old = lastFrame let gap = PanelCurveGeometry.allowedGap(at: next.dates.count - 1, intervals: next.intervals, fallback: max(5, expectedInterval * 2)) @@ -174,7 +220,7 @@ struct PanelTrendChart: View { private struct PanelCurveCanvas: View, Animatable { let frame: PanelCurveFrame let colors: [Color] - let scale: Double + let scales: [Double] let maximumGap: TimeInterval let targetBegin: Date? let targetEnd: Date? @@ -201,7 +247,10 @@ private struct PanelCurveCanvas: View, Animatable { guard let first = targetBegin, let last = targetEnd else { return } let domain = PanelCurveFrame.domain(previousBegin: previousBegin, previousEnd: previousEnd, begin: first, end: last, progress: Double(progress)) - for (values, tint) in zip(frame.series, colors) { + for seriesIndex in frame.series.indices { + let values = frame.series[seriesIndex] + let tint = colors[min(seriesIndex, colors.count - 1)] + let scale = scales[min(seriesIndex, scales.count - 1)] for run in PanelCurveGeometry.runs(dates: frame.dates, values: values, maximumGap: maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) { let points = run.map { item in CGPoint(x: size.width * domain.position(item.date), diff --git a/kymo/UI/Components/FanSpeedIndicator.swift b/kymo/UI/Components/FanSpeedIndicator.swift new file mode 100644 index 0000000..c8814ec --- /dev/null +++ b/kymo/UI/Components/FanSpeedIndicator.swift @@ -0,0 +1,57 @@ +import SwiftUI + +/// Approximate visual speed tiers; rotation does not attempt to reproduce physical RPM. +nonisolated struct FanRotation { + private(set) var phase: Double = 0 + private(set) var speed: Double = 0 + private var reference: TimeInterval = 0 + + static func speed(rpm: Double?, reducedMotion: Bool) -> Double { + guard !reducedMotion, let rpm, rpm.isFinite, rpm > 0 else { return 0 } + switch rpm { + case ..<2000: return 90 + case ..<4000: return 180 + case ..<6000: return 300 + default: return 450 + } + } + + func angle(at time: TimeInterval) -> Double { + (phase + max(0, time - reference) * speed).truncatingRemainder(dividingBy: 360) + } + + mutating func update(rpm: Double?, reducedMotion: Bool, at time: TimeInterval) { + phase = angle(at: time) + reference = time + speed = Self.speed(rpm: rpm, reducedMotion: reducedMotion) + } +} + +struct FanSpeedIndicator: View { + let title: LocalizedStringKey + let rpm: Double? + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var rotation = FanRotation() + + var body: some View { + HStack(spacing: 5) { + TimelineView(.animation(minimumInterval: 1.0 / 30, paused: rotation.speed == 0)) { context in + Image(systemName: "fanblades.fill") + .rotationEffect(.degrees(rotation.angle(at: context.date.timeIntervalSinceReferenceDate))) + .foregroundStyle(.secondary) + }.frame(width: 14, height: 14).accessibilityHidden(true) + Text(title).foregroundStyle(.secondary) + Spacer(minLength: 2) + AnimatedMetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM") + .monospacedDigit().fontWeight(.medium) + } + .font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7) + .onAppear { update() } + .onChange(of: rpm) { _, _ in update() } + .onChange(of: reduceMotion) { _, _ in update() } + } + + private func update() { + rotation.update(rpm: rpm, reducedMotion: reduceMotion, at: Date.timeIntervalSinceReferenceDate) + } +} diff --git a/kymo/UI/Components/MetricRingGauge.swift b/kymo/UI/Components/MetricRingGauge.swift new file mode 100644 index 0000000..98967da --- /dev/null +++ b/kymo/UI/Components/MetricRingGauge.swift @@ -0,0 +1,31 @@ +import SwiftUI + +/// A bounded percentage gauge; missing data keeps an empty track and an explicit -- label. +struct MetricRingGauge: View { + let title: LocalizedStringKey + let value: Double? + let color: Color + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + private var fraction: Double { value.flatMap { $0.isFinite ? min(1, max(0, $0)) : nil } ?? 0 } + + var body: some View { + VStack(spacing: 3) { + ZStack { + Circle().stroke(color.opacity(0.17), lineWidth: 3) + Circle().trim(from: 0, to: fraction) + .stroke(color, style: StrokeStyle(lineWidth: 3, lineCap: .round)) + .rotationEffect(.degrees(-90)) + .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: fraction) + AnimatedMetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold)) + .lineLimit(1).minimumScaleFactor(0.6).frame(width: 18, height: 12) + }.padding(2).frame(width: 28, height: 28).accessibilityHidden(true) + Text(title).font(.system(size: 8)).foregroundStyle(.secondary) + .lineLimit(1).minimumScaleFactor(0.7) + } + .frame(maxWidth: .infinity) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(title)) + .accessibilityValue(Text(verbatim: MetricFormat.percent(value))) + } +} diff --git a/kymo/UI/Components/ResourceCard.swift b/kymo/UI/Components/ResourceCard.swift index b05e6f4..3be1769 100644 --- a/kymo/UI/Components/ResourceCard.swift +++ b/kymo/UI/Components/ResourceCard.swift @@ -6,16 +6,40 @@ struct ResourceCard: View { let color: Color let value: String var secondaryValue: String? = nil + var status: String? = nil + var statusWarning = false + var statusHelp: Text? = nil + var warningText: Text? = nil + var detail: String? = nil @ViewBuilder var content: () -> Content var body: some View { - VStack(alignment: .leading, spacing: 4) { - HStack(alignment: .firstTextBaseline, spacing: 6) { - Label { Text(title).foregroundStyle(.primary) } icon: { - Image(systemName: symbol).foregroundStyle(color) + VStack(alignment: .leading, spacing: 3) { + HStack(alignment: .center, spacing: 6) { + Label { Text(title).foregroundStyle(statusWarning ? .red : .primary) } icon: { + Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color) }.font(.system(size: 13, weight: .semibold)).fixedSize() + if let status { + Text(verbatim: status) + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(statusWarning ? .red : color) + .padding(.horizontal, 6).padding(.vertical, 2) + .background((statusWarning ? Color.red : color).opacity(0.14), in: Capsule()) + .help(statusHelp ?? Text(verbatim: status)) + if let warningText { + warningText + .font(.system(size: 10)).foregroundStyle(.red).lineLimit(1).minimumScaleFactor(0.7) + } + } + if let detail { + Text(verbatim: detail) + .font(.system(size: 9, weight: .medium)).foregroundStyle(.secondary) + .padding(.horizontal, 5).padding(.vertical, 2) + .background(.primary.opacity(0.06), in: Capsule()) + .lineLimit(1).minimumScaleFactor(0.7) + } Spacer(minLength: 0) - HStack(alignment: .firstTextBaseline, spacing: 6) { + HStack(alignment: .center, spacing: 6) { AnimatedMetricText(value: value) .font(.system(size: 13, weight: .semibold)) if let secondaryValue { diff --git a/kymoTests/CPUCoreGridChecks.swift b/kymoTests/CPUCoreGridChecks.swift index 1f29c5c..4f01cd9 100644 --- a/kymoTests/CPUCoreGridChecks.swift +++ b/kymoTests/CPUCoreGridChecks.swift @@ -12,8 +12,24 @@ import SwiftUI } } precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 430) == [9, 9]) - precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 280) == [6, 6, 6]) - precondition(CPUCoreGridLayout.rowCounts(count: 32, width: 430) == [11, 11, 10]) + precondition(CPUCoreGridLayout.rowCounts(count: 18, width: 280) == [9, 9]) + precondition(CPUCoreGridLayout.rowCounts(count: 32, width: 430) == [16, 16]) + precondition(CPUCoreGridLayout.rowCounts(count: 48, width: 430) == [16, 16, 16]) + for count in [0, 1, 4, 8, 14, 18, 24, 32, 48, 128] { + let kinds = Dictionary(uniqueKeysWithValues: (0..= 0 && $0.isFinite }) + precondition(widths.reduce(0, +) <= width + 0.001) + for (group, groupWidth) in zip(groups, widths) { + let rows = CPUCoreGridLayout.rowCounts(count: group.count, width: groupWidth) + precondition(rows.count <= 3 && rows.reduce(0, +) == group.count) + } + } + } + precondition(CPUCoreGrid.groups(count: 3, kinds: [0: .efficiency]).count == 2) print("PASS: balanced core rows at multiple widths and counts") } } diff --git a/kymoTests/CPUTemperatureChecks.swift b/kymoTests/CPUTemperatureChecks.swift new file mode 100644 index 0000000..d74ab52 --- /dev/null +++ b/kymoTests/CPUTemperatureChecks.swift @@ -0,0 +1,14 @@ +import Foundation + +@main struct CPUTemperatureChecks { + static func main() { + precondition(CPUTemperatureMonitor.hasExpectedLayout) + precondition(!CPUTemperatureMonitor.isHighTemperature(nil)) + precondition(!CPUTemperatureMonitor.isHighTemperature(89.9)) + precondition(CPUTemperatureMonitor.isHighTemperature(90)) + if let temperature = CPUTemperatureMonitor().sample() { + precondition(temperature > 0 && temperature < 150) + } + print("PASS: AppleSMC layout, warning threshold, and optional live temperature read") + } +} diff --git a/kymoTests/FanChecks.swift b/kymoTests/FanChecks.swift new file mode 100644 index 0000000..aa4a5f3 --- /dev/null +++ b/kymoTests/FanChecks.swift @@ -0,0 +1,31 @@ +import Foundation + +@main struct FanChecks { + static func main() { + precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x666c7420, bytes: [0, 0, 0, 0]) == 0) + precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x66706532, bytes: [0x24, 0x34]) == 2317) + precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x75693820, bytes: [2]) == 2) + precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x666c7420, bytes: [0, 0, 0xc0, 0x7f]) == nil) + precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x666c7420, bytes: [0]) == nil) + precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0, bytes: []) == nil) + precondition(FanMetrics.validRPM(0) == 0) + for value in [Double.nan, .infinity, -1, 30_001] { precondition(FanMetrics.validRPM(value) == nil) } + precondition(FanRotation.speed(rpm: 0, reducedMotion: false) == 0) + precondition(FanRotation.speed(rpm: nil, reducedMotion: false) == 0) + precondition(FanRotation.speed(rpm: .nan, reducedMotion: false) == 0) + precondition(FanRotation.speed(rpm: 6000, reducedMotion: true) == 0) + let tiers = [1000.0, 3000, 5000, 7000].map { FanRotation.speed(rpm: $0, reducedMotion: false) } + precondition(zip(tiers, tiers.dropFirst()).allSatisfy { $0 < $1 }) + var rotation = FanRotation() + rotation.update(rpm: 1000, reducedMotion: false, at: 100) + let before = rotation.angle(at: 101) + rotation.update(rpm: 7000, reducedMotion: false, at: 101) + precondition(rotation.angle(at: 101) == before) + rotation.update(rpm: 0, reducedMotion: false, at: 102) + precondition(rotation.angle(at: 102) == rotation.angle(at: 200)) + rotation.update(rpm: 7000, reducedMotion: true, at: 200) + precondition(rotation.angle(at: 200) == rotation.angle(at: 300)) + print("PASS: fan decoding, invalid RPM, speed tiers, continuous phase and stop/reduced-motion") + print("Live fan RPM:", CPUTemperatureMonitor().sampleFans() as Any) + } +} diff --git a/kymoTests/GPUStatisticsChecks.swift b/kymoTests/GPUStatisticsChecks.swift new file mode 100644 index 0000000..b56c94f --- /dev/null +++ b/kymoTests/GPUStatisticsChecks.swift @@ -0,0 +1,32 @@ +import Foundation + +@main struct GPUStatisticsChecks { + static func main() { + func sample(_ time: Double, _ value: Double?, interval: Double = 2, boundary: Bool = false) -> TrendSample { + TrendSample(date: Date(timeIntervalSince1970: time), cpu: nil, gpu: value, memory: nil, + breakBefore: boundary, expectedInterval: interval) + } + let variable = GPUUtilizationSummary(samples: [sample(0, 0), sample(2, 1), sample(10, 1, interval: 8)]) + precondition(abs(variable.average! - 0.9) < 0.00001 && variable.peak == 1) + let clipped = GPUUtilizationSummary(samples: [sample(0, 0, interval: 120), sample(120, 1, interval: 120)]) + precondition(abs(clipped.average! - 0.75) < 0.00001 && clipped.coverage == 60) + precondition(GPUUtilizationSummary(samples: []).average == nil) + precondition(GPUUtilizationSummary(samples: [sample(0, 1)]).average == nil) + precondition(GPUUtilizationSummary(samples: [sample(0, 1), sample(2, nil), sample(4, 0)]).average == nil) + precondition(GPUUtilizationSummary(samples: [sample(0, 1), sample(2, 0, boundary: true)]).average == nil) + precondition(GPUUtilizationSummary(samples: [sample(0, 1), sample(60, 0)]).average == nil) + precondition(GPUMonitor.memoryBytes(NSNumber(value: -1)) == nil) + precondition(GPUMonitor.memoryBytes(NSNumber(value: Double.nan)) == nil) + precondition(GPUMonitor.memoryBytes(NSNumber(value: 0)) == 0) + precondition(GPUMonitor.normalized(101) == nil) + var snapshot = MetricsSnapshot() + snapshot.gpu = GPUMetrics(usage: 0.4, coreCount: 20, renderer: 0.3, tiler: 0.1) + snapshot.gpuUsage = snapshot.gpu?.usage + var history = MetricHistory() + history.append(snapshot) + precondition(history.samples.last?.gpuRenderer == 0.3 && history.samples.last?.gpuTiler == 0.1) + let live = GPUMonitor.sample() + print("GPU statistics checks passed; live:", live as Any) + print("GPU temperature zone:", CPUTemperatureMonitor(zone: .gpu).sample() as Any) + } +} diff --git a/kymoTests/PanelLayoutChecks.swift b/kymoTests/PanelLayoutChecks.swift index a4013c6..6d2460f 100644 --- a/kymoTests/PanelLayoutChecks.swift +++ b/kymoTests/PanelLayoutChecks.swift @@ -14,11 +14,12 @@ import CoreGraphics } } for size in [CGSize(width: 1240, height: 820), CGSize(width: 1160, height: 810)] { - let square = PanelLayout.resourceRowHeight(size: size) - let wide = PanelLayout.firstRowWideCardWidth(size: size) - precondition(square >= 220 && square <= 230) - precondition(abs(PanelLayout.batteryWidth(size: size) / square - 4.0 / 3.0) < 0.001) - precondition(abs(2 * wide + PanelLayout.batteryWidth(size: size) + 16 - (size.width - 20)) < 0.001) + let compact = PanelLayout.resourceRowHeight(size: size, coreRows: 2) + let expanded = PanelLayout.resourceRowHeight(size: size, coreRows: 3) + let width = PanelLayout.cardWidth(size: size) + precondition(compact >= 224 && compact <= 239) + precondition(expanded == min(265, compact + 26)) + precondition(abs(3 * width + 16 - (size.width - 20)) < 0.001) } let input: [ProcessMetrics] = (0..<2000).map { (index: Int) -> ProcessMetrics in let id = ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0) diff --git a/kymoTests/README.md b/kymoTests/README.md index 2384103..e1c20a3 100644 --- a/kymoTests/README.md +++ b/kymoTests/README.md @@ -10,6 +10,15 @@ swiftc -parse-as-library -module-cache-path /private/tmp/kymo-core-grid-cache \ /private/tmp/kymo-core-grid-checks ``` +CPU 温度检查(检查 AppleSMC C 结构对齐、90°C 提示边界,并在接口可用时核对实时值范围): + +```bash +swiftc -parse-as-library -module-cache-path /private/tmp/kymo-temperature-cache \ + kymo/Core/Monitors/CPUTemperatureMonitor.swift kymoTests/CPUTemperatureChecks.swift \ + -o /private/tmp/kymo-temperature-checks +/private/tmp/kymo-temperature-checks +``` + 单元测试目录。当前工程尚未创建测试 Target,添加步骤见 [docs/development.md](../docs/development.md)「添加测试 Target」一节。 @@ -75,7 +84,7 @@ swiftc -module-cache-path /private/tmp/kymo-check-cache \ C 阶段基础边界与本机采样检查: ```bash -swiftc -module-cache-path /private/tmp/kymo-c-cache kymo/Core/Monitors/NetworkMonitor.swift kymo/Core/Monitors/DiskMonitor.swift kymo/Core/Monitors/DiskIOMonitor.swift kymo/Core/Monitors/BatteryMonitor.swift kymo/Core/Monitors/SystemBatteryHealthMonitor.swift kymoTests/StageCChecks.swift -o /private/tmp/kymo-c-check +swiftc -module-cache-path /private/tmp/kymo-c-cache kymo/Core/Models/*.swift kymo/Core/Monitors/*.swift kymo/Core/Services/*.swift kymo/Core/Extensions/*.swift kymoTests/StageCChecks.swift -o /private/tmp/kymo-c-check /private/tmp/kymo-c-check ``` @@ -171,3 +180,25 @@ swiftc -parse-as-library -module-cache-path /private/tmp/kymo-check-cache \ ``` 窗口程序应放进独立 `.app/Contents/MacOS`、配置隔离 Info.plist 并签名后运行。前者覆盖双频持久化/边界、30min 等待唤醒、暂停优先级、隐藏进程清理及长间隔初始列表发布;后者创建真实 NSPanel,检查居中/层级/外部关闭策略/显式关闭/退出复位,不安装状态栏图标。外部关闭策略方法检查不等于实际系统鼠标事件已投递。GUI 工具能力与证据见 [统一面板验证](../docs/unified-panel-validation.md)。 + +## GPU 信息与统计 + +```bash +swiftc kymo/Core/Models/*.swift kymo/Core/Monitors/*.swift \ + kymo/Core/Services/*.swift kymo/Core/Extensions/*.swift \ + kymoTests/GPUStatisticsChecks.swift -o /private/tmp/kymo-gpu-statistics-checks +/private/tmp/kymo-gpu-statistics-checks +``` + +覆盖实际时间加权、窗口截断、缺失/休眠边界、阶段曲线历史和驱动内存边界;命令行采样不代替签名 XPC 与实际卡片验收。 + +## 风扇解码与动画状态 + +```bash +swiftc kymo/Core/Models/FanMetrics.swift kymo/Core/Monitors/CPUTemperatureMonitor.swift \ + kymo/UI/Components/FanSpeedIndicator.swift kymo/UI/Components/AnimatedMetricText.swift \ + kymoTests/FanChecks.swift -o /private/tmp/kymo-fan-checks +/private/tmp/kymo-fan-checks +``` + +检查解码/非法/零RPM、速度档位、连续相位及停转。动态手感仍需实际面板验收,不将状态检查等同于帧呈现验证。 diff --git a/kymoTests/SamplingChecks.swift b/kymoTests/SamplingChecks.swift index b7a0233..45dc9fd 100644 --- a/kymoTests/SamplingChecks.swift +++ b/kymoTests/SamplingChecks.swift @@ -22,15 +22,24 @@ import Foundation precondition(MetricFormat.rate(1000) == "1.0 KB/s") precondition(MetricFormat.rate(1_000_000) == "1.0 MB/s") precondition(MetricFormat.rate(1_000_000_000) == "1.0 GB/s") + precondition(MetricFormat.watts(nil) == "--") + precondition(MetricFormat.watts(.nan) == "--") + precondition(MetricFormat.watts(-1) == "--") + precondition(MetricFormat.watts(0) == "0.0 W") + precondition(MetricFormat.watts(12.34) == "12.3 W") var extended = MetricsSnapshot() extended.network = [NetworkInterfaceMetrics(name: "en0", received: 100, sent: 50, download: 20, upload: 10)] extended.disk = DiskMetrics(total: 100, available: 40) - extended.battery = BatteryMetrics(charge: 0.8, charging: false, externalPower: true) + extended.battery = BatteryMetrics(charge: 0.8, charging: false, externalPower: true, power: 0) var extendedHistory = MetricHistory() extendedHistory.append(extended) precondition(extendedHistory.samples.last?.download == 20) precondition(extendedHistory.samples.last?.disk == 0.6) precondition(extendedHistory.samples.last?.battery == 0.8) + precondition(extendedHistory.samples.last?.batteryPower == 0) + extended.battery?.power = 12.5 + extendedHistory.append(extended) + precondition(extendedHistory.samples.last?.batteryPower == 12.5) extended.network = [NetworkInterfaceMetrics(name: "en0", received: 100, sent: 50, download: nil, upload: nil)] extendedHistory.append(extended) precondition(extendedHistory.samples.last?.download == nil) diff --git a/kymoTests/StageCChecks.swift b/kymoTests/StageCChecks.swift index c3b2730..0b3fda0 100644 --- a/kymoTests/StageCChecks.swift +++ b/kymoTests/StageCChecks.swift @@ -18,6 +18,11 @@ import Foundation precondition(BatteryMonitor.estimatedMinutes(charging: true, externalPower: true, sourceMinutes: 30, systemSeconds: -2) == 30) precondition(BatteryMonitor.estimatedMinutes(charging: true, externalPower: true, sourceMinutes: nil, systemSeconds: 5400) == nil) precondition(BatteryMonitor.estimatedMinutes(charging: false, externalPower: false, sourceMinutes: nil, systemSeconds: .infinity) == nil) + precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: 2_500) == 30) + precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: -2_500) == 30) + precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 0, amperageMilliamps: 2_500) == nil) + precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: .nan) == nil) + precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 50_000, amperageMilliamps: 2_500) == nil) let report = Data(#"{"SPPowerDataType":[{"sppower_battery_health_info":{"sppower_battery_health_maximum_capacity":"100%"}}]}"#.utf8) precondition(SystemBatteryHealthMonitor.parse(report) == 1) precondition(SystemBatteryHealthMonitor.parse(Data(String(decoding: report, as: UTF8.self).replacingOccurrences(of: "100%", with: "83%").utf8)) == 0.83) @@ -44,7 +49,8 @@ import Foundation } if let battery = BatteryMonitor.sample() { precondition(battery.charge.map { (0...1).contains($0) } ?? true) - print("Battery:", battery.charge as Any, "charging:", battery.charging, "cycles:", battery.cycles as Any, "health:", battery.health as Any, "minutes:", battery.minutesRemaining as Any) + precondition(battery.power.map { $0.isFinite && (0...500).contains($0) } ?? true) + print("Battery:", battery.charge as Any, "charging:", battery.charging, "cycles:", battery.cycles as Any, "health:", battery.health as Any, "powerW:", battery.power as Any, "minutes:", battery.minutesRemaining as Any) } else { print("Battery unavailable or absent") } print("Stage C checks passed") } diff --git a/kymoTests/UnifiedPanelChecks.swift b/kymoTests/UnifiedPanelChecks.swift index ac51e72..2666d93 100644 --- a/kymoTests/UnifiedPanelChecks.swift +++ b/kymoTests/UnifiedPanelChecks.swift @@ -8,6 +8,16 @@ import Foundation precondition(ProcessMonitor.cpu(current: 1, previous: 0, elapsed: 0) == nil) precondition(GPUMonitor.normalized(53) == 0.53) precondition(GPUMonitor.normalized(101) == nil && GPUMonitor.normalized(.nan) == nil) + let processRows = [ + ProcessMetrics(id: ProcessIdentity(pid: 1, seconds: 1, microseconds: 1), name: "unknown", path: nil, cpu: nil, residentBytes: nil, threads: nil, restricted: true), + ProcessMetrics(id: ProcessIdentity(pid: 2, seconds: 1, microseconds: 2), name: "busy", path: nil, cpu: 2.5, residentBytes: nil, threads: nil, restricted: false), + ProcessMetrics(id: ProcessIdentity(pid: 3, seconds: 1, microseconds: 3), name: "idle", path: nil, cpu: 0, residentBytes: nil, threads: nil, restricted: false), + ProcessMetrics(id: ProcessIdentity(pid: 4, seconds: 1, microseconds: 4), name: "invalid", path: nil, cpu: -.infinity, residentBytes: nil, threads: nil, restricted: false) + ] + let processSnapshot = ProcessSnapshot(date: Date(), enumerated: 4, readable: 3, rows: processRows, failed: false) + precondition(processSnapshot.highestCPUProcess?.name == "busy") + precondition(processSnapshot.highestCPUProcesses(limit: 3).map(\.name) == ["busy", "idle"]) + precondition(processSnapshot.highestCPUProcesses(limit: 0).isEmpty) var snapshot = MetricsSnapshot() snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 1, sent: 1, download: 12, upload: 8), NetworkInterfaceMetrics(name: "utun0", received: 1, sent: 1, download: 99, upload: 99)] diff --git a/tools/gpu_capability_probe.py b/tools/gpu_capability_probe.py new file mode 100644 index 0000000..b0a5311 --- /dev/null +++ b/tools/gpu_capability_probe.py @@ -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(" 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)) diff --git a/tools/gpu_compute_probe.swift b/tools/gpu_compute_probe.swift new file mode 100644 index 0000000..7a601f1 --- /dev/null +++ b/tools/gpu_compute_probe.swift @@ -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 +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.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") diff --git a/tools/gpu_driver_call_trace.c b/tools/gpu_driver_call_trace.c new file mode 100644 index 0000000..0c7059e --- /dev/null +++ b/tools/gpu_driver_call_trace.c @@ -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 +#include +#include +#include + +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 +}; diff --git a/tools/gpu_raw_counter_probe.m b/tools/gpu_raw_counter_probe.m new file mode 100644 index 0000000..c7a3712 --- /dev/null +++ b/tools/gpu_raw_counter_probe.m @@ -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 +#import +#import +#import +#import + +@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, ®istryID); + NSArray> *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; +}