perf(efficiency): 接入真实CPU能量并隔离展示与采样需求
This commit is contained in:
@@ -0,0 +1,54 @@
|
|||||||
|
import Foundation
|
||||||
|
import Darwin
|
||||||
|
|
||||||
|
nonisolated enum ProcessEnergyReader {
|
||||||
|
private static let readLock = NSLock()
|
||||||
|
static func read(_ data: Data) -> Data? {
|
||||||
|
guard data.count <= ProcessEnergyRequest.byteLimit,
|
||||||
|
let request = try? JSONDecoder().decode(ProcessEnergyRequest.self, from: data),
|
||||||
|
request.identities.count <= ProcessEnergyRequest.limit,
|
||||||
|
Set(request.identities.map(\.pid)).count == request.identities.count else { return nil }
|
||||||
|
guard readLock.try() else { return nil }
|
||||||
|
defer { readLock.unlock() }
|
||||||
|
let capability: EnergyCapability
|
||||||
|
#if arch(arm64)
|
||||||
|
let own = usage(getpid())
|
||||||
|
capability = own.map { $0.ri_energy_nj > 0 } == true ? .verifiedCPU : .unverified
|
||||||
|
#else
|
||||||
|
capability = .unsupported
|
||||||
|
#endif
|
||||||
|
let deadline = ProcessInfo.processInfo.systemUptime + 1
|
||||||
|
let values = request.identities.map { id -> ProcessEnergyReading in
|
||||||
|
func result(_ status: EnergyReadStatus, _ usage: rusage_info_v6? = nil) -> ProcessEnergyReading {
|
||||||
|
ProcessEnergyReading(id: id, birth: usage?.ri_proc_start_abstime ?? 0,
|
||||||
|
uptime: ProcessInfo.processInfo.systemUptime, nanojoules: usage?.ri_energy_nj, status: status)
|
||||||
|
}
|
||||||
|
guard capability != .unsupported else { return result(.unsupported) }
|
||||||
|
guard capability == .verifiedCPU else { return result(.unverified) }
|
||||||
|
guard ProcessInfo.processInfo.systemUptime < deadline else { return result(.deadline) }
|
||||||
|
guard id.pid > 0, id.seconds > 0 else { return result(.identityChanged) }
|
||||||
|
guard let before = identity(id.pid) else { return result(errno == ESRCH ? .gone : .denied) }
|
||||||
|
guard before.pbi_uid == getuid() else { return result(.denied) }
|
||||||
|
guard matches(before, id) else { return result(.identityChanged) }
|
||||||
|
guard let value = usage(id.pid) else { return result(errno == EPERM || errno == EACCES ? .denied : .failed) }
|
||||||
|
guard let after = identity(id.pid), matches(after, id), after.pbi_uid == getuid() else { return result(.identityChanged) }
|
||||||
|
return result(.available, value)
|
||||||
|
}
|
||||||
|
return try? JSONEncoder().encode(ProcessEnergyReply(token: request.token, capability: capability, readings: values))
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func matches(_ info: proc_bsdinfo, _ id: ProcessIdentity) -> Bool {
|
||||||
|
info.pbi_start_tvsec == id.seconds && info.pbi_start_tvusec == id.microseconds
|
||||||
|
}
|
||||||
|
private static func identity(_ pid: Int32) -> proc_bsdinfo? {
|
||||||
|
var info = proc_bsdinfo()
|
||||||
|
return proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, Int32(MemoryLayout.size(ofValue: info))) == MemoryLayout.size(ofValue: info) ? info : nil
|
||||||
|
}
|
||||||
|
private static func usage(_ pid: Int32) -> rusage_info_v6? {
|
||||||
|
var info = rusage_info_v6()
|
||||||
|
let status = withUnsafeMutablePointer(to: &info) { pointer in
|
||||||
|
pointer.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(pid, RUSAGE_INFO_V6, $0) }
|
||||||
|
}
|
||||||
|
return status == 0 ? info : nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,10 @@ final class SMARTService: NSObject, SMARTServiceProtocol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void) {
|
||||||
|
Task.detached(priority: .utility) { reply(ProcessEnergyReader.read(request)) }
|
||||||
|
}
|
||||||
|
|
||||||
func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void) {
|
func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void) {
|
||||||
Task {
|
Task {
|
||||||
let result = await DiskSMARTReader.readReport()
|
let result = await DiskSMARTReader.readReport()
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@
|
|||||||
| [测试与验证](testing.md) | 独立检查程序、执行方式和人工验收边界 |
|
| [测试与验证](testing.md) | 独立检查程序、执行方式和人工验收边界 |
|
||||||
| [极致轻量化与进程能耗方案](extreme-efficiency-plan.md) | 实施中:性能预算、逻辑浪费审查、真实能量列表、包体积收敛及分阶段验收 |
|
| [极致轻量化与进程能耗方案](extreme-efficiency-plan.md) | 实施中:性能预算、逻辑浪费审查、真实能量列表、包体积收敛及分阶段验收 |
|
||||||
|
|
||||||
首批实施证据见[轻量化实施记录](efficiency-first-batch.md);其中包体积已收敛,内存和能耗列表仍在实施。
|
首批实施证据见[轻量化实施记录](efficiency-first-batch.md);第二批见[能量列表与纯文字对照记录](efficiency-second-batch.md)。包体积已收敛,真实 CPU 能量列表已实现;内存与长期性能预算仍待通过。
|
||||||
|
|
||||||
2026-11-03 依据当前源码重新整理;同日补充极致轻量化与进程能耗实施方案。此前清理的旧阶段计划、设计概念图和路线图可通过 Git 查询。主题文档描述当前实现,方案中的目标不代表已实现,也不以代码已实现代替运行验收。
|
2026-11-03 依据当前源码重新整理;同日补充极致轻量化与进程能耗实施方案。此前清理的旧阶段计划、设计概念图和路线图可通过 Git 查询。主题文档描述当前实现,方案中的目标不代表已实现,也不以代码已实现代替运行验收。
|
||||||
|
|
||||||
|
|||||||
+19
-5
@@ -13,7 +13,7 @@
|
|||||||
| `kymo/Core/Extensions` | 指标格式化 |
|
| `kymo/Core/Extensions` | 指标格式化 |
|
||||||
| `kymo/UI` | 图表、卡片、控件、悬浮呈现、外观与本地化宿主等可复用展示能力 |
|
| `kymo/UI` | 图表、卡片、控件、悬浮呈现、外观与本地化宿主等可复用展示能力 |
|
||||||
| `kymo/Resources` / `kymo/Assets.xcassets` | 字符串目录 / 颜色与图片 |
|
| `kymo/Resources` / `kymo/Assets.xcassets` | 字符串目录 / 颜色与图片 |
|
||||||
| `SMARTService` | 独立 XPC Target,读取磁盘报告、CPU / GPU 温度和风扇 |
|
| `SMARTService` | 独立 XPC Target,读取磁盘报告、CPU / GPU 温度、风扇和同 UID 进程 CPU 能量计数 |
|
||||||
|
|
||||||
`Dashboard` 目录仅有占位文件,没有独立总览功能。统一监控面板位于 MenuBar。
|
`Dashboard` 目录仅有占位文件,没有独立总览功能。统一监控面板位于 MenuBar。
|
||||||
|
|
||||||
@@ -36,9 +36,11 @@
|
|||||||
│ │
|
│ │
|
||||||
├─ 慢任务缓存 ▼
|
├─ 慢任务缓存 ▼
|
||||||
└─ 可见时进程任务 MetricsStore(MainActor)
|
└─ 可见时进程任务 MetricsStore(MainActor)
|
||||||
├─ snapshot → 面板 / 进程表
|
├─ snapshot → 资源卡片
|
||||||
|
├─ processSnapshot → 进程表
|
||||||
|
├─ energy → 耗电进程区
|
||||||
└─ MetricHistory → 趋势图
|
└─ MetricHistory → 趋势图
|
||||||
面板可见性 / SamplingPreferences ──────────→ 调度切换
|
面板实际可见性 / 系统和显示器睡眠 / SamplingPreferences ──────────→ 调度切换
|
||||||
SMARTService(XPC)──→ 温度 / 风扇 / SMART 客户端 ──→ 慢任务缓存
|
SMARTService(XPC)──→ 温度 / 风扇 / SMART 客户端 ──→ 慢任务缓存
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -46,7 +48,7 @@ SMARTService(XPC)──→ 温度 / 风扇 / SMART 客户端 ──→ 慢
|
|||||||
|
|
||||||
`SystemSampler` actor 持有 CPU、网络、磁盘 IO 差分基线。CPU / 内存每次 Mach 查询取得的 host 发送权在调用结束(含失败路径)释放。卷列表与进程读取放入 utility detached Task;温度、磁盘健康、电池健康独立更新缓存,各类慢任务最多一个在途;隐藏后台趋势不新发起传感器、卷或慢报告读取。慢指标可晚于快照更新,周期详见[监控指标](monitoring.md)。
|
`SystemSampler` actor 持有 CPU、网络、磁盘 IO 差分基线。CPU / 内存每次 Mach 查询取得的 host 发送权在调用结束(含失败路径)释放。卷列表与进程读取放入 utility detached Task;温度、磁盘健康、电池健康独立更新缓存,各类慢任务最多一个在途;隐藏后台趋势不新发起传感器、卷或慢报告读取。慢指标可晚于快照更新,周期详见[监控指标](monitoring.md)。
|
||||||
|
|
||||||
进程只在面板可见且未暂停时读取。进程结果可异步单独发布,不必等下一轮资源快照。可见性代次和调度代次阻止过期结果回写;隐藏时清除已发布进程,重新打开重建基线。同步系统调用即使不能及时取消,也会占用原在途槽,避免重叠读取。路径按完整身份与命令名缓存 30 秒(包含失败结果),每轮复用一个路径缓冲;枚举失败清空缓存,末次身份复核保留。进程退出提示以原始成功快照中的完整身份为准,搜索过滤和枚举失败不作为退出证据。
|
进程只在面板可见且未暂停时读取。进程结果可异步单独发布到 processSnapshot,资源 snapshot 的 processes 保持 nil;能耗独立发布到 energy。进程与能耗区以独立 View 订阅,避免异步进程发布再次使整个资源区失效。可见性代次和调度代次阻止过期结果回写;隐藏时清除已发布进程,重新打开重建基线。同步系统调用即使不能及时取消,也会占用原在途槽,避免重叠读取。路径按完整身份与命令名缓存 30 秒(包含失败结果),每轮复用一个路径缓冲;枚举失败清空缓存,末次身份复核保留。进程退出提示以原始成功快照中的完整身份为准,搜索过滤和枚举失败不作为退出证据。
|
||||||
|
|
||||||
暂停取消采样发布、停用进程更新,保留当前快照和历史;已启动慢读取可能自行结束。恢复时重置 CPU / 网络 / IO 基线,历史标记断点。全局及每接口历史各最多 60 点,接口移除时清理其历史;实际覆盖时长由采样间隔决定。图表按真实时间和缺失值处理间断。GPU 平均统计仅累计有效且连续的时间区间。
|
暂停取消采样发布、停用进程更新,保留当前快照和历史;已启动慢读取可能自行结束。恢复时重置 CPU / 网络 / IO 基线,历史标记断点。全局及每接口历史各最多 60 点,接口移除时清理其历史;实际覆盖时长由采样间隔决定。图表按真实时间和缺失值处理间断。GPU 平均统计仅累计有效且连续的时间区间。
|
||||||
|
|
||||||
@@ -68,6 +70,18 @@ CPU / GPU / 风扇合并为一次只读 XPC 请求,按到期类别选择读取
|
|||||||
|
|
||||||
资源显示默认采用静态数字、曲线和进度条;风扇不创建 TimelineView。移除曲线追加过渡任务,保持原有缺失值、断点和悬浮语义。此措施不代表面板内存预算已通过;剩余峰值见效率实施记录。
|
资源显示默认采用静态数字、曲线和进度条;风扇不创建 TimelineView。移除曲线追加过渡任务,保持原有缺失值、断点和悬浮语义。此措施不代表面板内存预算已通过;剩余峰值见效率实施记录。
|
||||||
|
|
||||||
`PanelResourceAudit` 仅在 `KYMO_RESOURCE_AUDIT=1` 时驱动真实面板测试生命周期,App 只装配调用。正常启动不创建测试任务;该入口不是鼠标 / AX 交互验证。诊断日志仍需 `KYMO_DIAGNOSTICS=1` 显式开启。
|
`PanelResourceAudit` 与纯文字对照渲染器仅在 Debug 或显式 `KYMO_AUDIT` 编译条件下包含实现;普通 Release 不包含诊断驱动与文字列表实现。测试构建还需设置 `KYMO_RESOURCE_AUDIT=1` 才驱动真实面板测试生命周期,App 只装配调用。正常启动不创建测试任务;该入口不是鼠标 / AX 交互验证。诊断日志仍需 `KYMO_DIAGNOSTICS=1` 显式开启。
|
||||||
|
|
||||||
外部 `system_profiler` / `diskutil` 报告共用 Core 的 `BoundedProcess`(同时编入 XPC Target)。utility 队列阻塞于输出 / 取消 / 退出事件,累计保留输出不超过 256 KiB,最多多读 1 字节判断溢出;10 秒截止、输出超限或调用 Task 取消时 SIGKILL 本轮直接子进程并等待回收。子进程关闭 stdout 后不退出也受截止约束。取消管道唤醒 poll,无周期检查计时器;不杀进程组或其他进程。此取消能力不代表 XPC 连接断开已传播到服务内部 Task,暂停后已启动慢报告的上层取消仍需完善。
|
外部 `system_profiler` / `diskutil` 报告共用 Core 的 `BoundedProcess`(同时编入 XPC Target)。utility 队列阻塞于输出 / 取消 / 退出事件,累计保留输出不超过 256 KiB,最多多读 1 字节判断溢出;10 秒截止、输出超限或调用 Task 取消时 SIGKILL 本轮直接子进程并等待回收。子进程关闭 stdout 后不退出也受截止约束。取消管道唤醒 poll,无周期检查计时器;不杀进程组或其他进程。此取消能力不代表 XPC 连接断开已传播到服务内部 Task,暂停后已启动慢报告的上层取消仍需完善。
|
||||||
|
|
||||||
|
## 实际需求与能量数据流
|
||||||
|
|
||||||
|
控制器分别维护 presentation.isOpen(内容装配)和采样可见性(isVisible 且 occlusionState 可见),监听窗口遮挡通知和 isVisible KVO。固定面板完全遮挡或 orderOut 后按隐藏需求降级,恢复后补采;遮挡不销毁已打开内容和表格交互状态,显式隐藏仍卸载内容。App 仅转发 NSWorkspace 的系统 / 显示器睡眠事件。系统睡眠停止全部周期采样;息屏停止前台、进程、能量、公网和慢读取,只允许用户显式开启的后台趋势。保持唤醒仍由用户独立控制。
|
||||||
|
|
||||||
|
Store 将递增需求代次交给 SystemSampler;actor 在开始系统调用前拒绝过期代次,旧停止不能覆盖新恢复,旧采样不能复活已隐藏需求。异步结果仍需通过 MainActor 和 actor 两侧代次检查。重建需求使能量基线失效;不能跨暂停或睡眠差分。
|
||||||
|
|
||||||
|
一次成功进程枚举的全部已识别行进入 ProcessEnergyServiceClient,不按 CPU 预筛选。签名认证 XPC 每批最多 256 项 / 请求 64 KiB,总客户端截止 3 秒、每请求最多 1.5 秒;服务串行读取(忙时拒绝),每批截止 1 秒。服务限制同 UID,读取前后复核 PID + 启动时间,返回原请求 UUID、Mach 启动标记、单调时间及 UInt64 能量。客户端复核 UUID、身份集合与响应大小。受限或超时部分明确反映为覆盖不全。
|
||||||
|
|
||||||
|
ProcessEnergyMonitor 在相同身份、Mach 启动标记和连续有效计数间,以整数先相减再转浮点,得到 nJ / 秒 / 1e9 的 W;保留最大三项,不添加 CPU 代理。失败、缺失、计数回退、重建需求均使旧基线失效。普通间隔最长允许 30 秒差分;用户设置长采样间隔时放宽至两倍前台间隔、上限 3600 秒,并显示实际窗口。详情见监控口径。
|
||||||
|
|
||||||
|
网络展示和诊断文字窗口共用 PanelPublicIPRefresh,遵循同一可见 / 暂停 / 睡眠与缓存策略。出口键仍包含全部活动地址,L07 尚待修正。外观观察器在挂载后延迟初始化,避免每次 View 值构造就创建 KVO / 通知订阅者。
|
||||||
|
|||||||
@@ -93,3 +93,5 @@ open -n --env KYMO_RESOURCE_AUDIT=1 --env KYMO_DIAGNOSTICS=1 \
|
|||||||
`KYMO_AUDIT_OMIT` 可选 `icons` / `processes` / `resources` / `header` / `all`,仅在测量入口启用时生效;正常启动不执行这些分支。事件包含实际 recordedAt / uptime、快照时间、足迹与累计峰值。测试窗口方法调用不能冒充真实输入事件;原始日志可能包含接口标识,分享前需脱敏。
|
`KYMO_AUDIT_OMIT` 可选 `icons` / `processes` / `resources` / `header` / `all`,仅在测量入口启用时生效;正常启动不执行这些分支。事件包含实际 recordedAt / uptime、快照时间、足迹与累计峰值。测试窗口方法调用不能冒充真实输入事件;原始日志可能包含接口标识,分享前需脱敏。
|
||||||
|
|
||||||
下一批优先:继续 P0 / P2 内存分配与发布范围定位,完善传输故障回归和 L07 / L08 / L15;然后实现 P3 真实系统能量差分与覆盖说明。当前“耗电进程”仍是旧 CPU 列表,没有声称已实现实际能耗。完整项目尚未完成,也未通过 CPU、内存、整机功耗及长期稳定性预算。
|
下一批优先:继续 P0 / P2 内存分配与发布范围定位,完善传输故障回归和 L07 / L08 / L15;然后实现 P3 真实系统能量差分与覆盖说明。当前“耗电进程”仍是旧 CPU 列表,没有声称已实现实际能耗。完整项目尚未完成,也未通过 CPU、内存、整机功耗及长期稳定性预算。
|
||||||
|
|
||||||
|
后续入口变化:从第二批开始,Release 资源审计需以 `SWIFT_ACTIVE_COMPILATION_CONDITIONS=KYMO_AUDIT` 构建;普通发行 Release 已排除实现。文字对照新增 `KYMO_AUDIT_OMIT=text`,详见[第二批记录](efficiency-second-batch.md)。
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# 第二批:CPU 能量列表、需求调度与纯文字对照
|
||||||
|
|
||||||
|
日期:2026-11-04。基于首批提交 `def3b1e`,有界子进程实现另已提交为 `a96d188`。本轮不是性能预算全部通过的声明。
|
||||||
|
|
||||||
|
## 本轮改动
|
||||||
|
|
||||||
|
- 实现正式签名沙盒主程序 → 认证 XPC → 同 UID `ri_energy_nj` 读取 → 整数能量差分 → CPU 平均功率前三名。复用全部已识别进程候选,不按 CPU 预选;首帧、不可用、不支持和覆盖不全均明确显示,禁止 CPU 降级。默认能量至少间隔 5 秒,在默认 2 秒轮次中通常约 6 秒,失败独立退避。
|
||||||
|
- 将资源、进程、能量分开发布。进程延迟完成不再使资源 snapshot 观察者失效;资源区、表格和能量列表各自订阅。
|
||||||
|
- 修正固定面板完全遮挡 / orderOut 仍持续采样的需求错误;系统睡眠停止采样,息屏仅保留用户显式后台趋势。递增需求代次同时在 Store / sampler 检查,防止旧请求复活隐藏需求或旧停止覆盖新恢复。
|
||||||
|
- 外观系统观察器延迟到挂载后初始化,避免重建 View 值时重复构造观察者。公网 IP 抽取为产品与文字对照共用的 modifier,保持请求条件一致。
|
||||||
|
- 外部报告限制输出、可靠终止超时直接子进程并回收,已单独提交。服务断连向慢报告内部 Task 的取消传播仍未完成。
|
||||||
|
- Debug / 显式 `KYMO_AUDIT` 构建加入纯文字对照;普通 Release 排除测试驱动和文字列表实现,避免正式包为测量功能增加实现体积;测量所用诊断包约 2.10 MB,排除诊断实现可减少约 85 KB。
|
||||||
|
|
||||||
|
## 纯文字对照方法
|
||||||
|
|
||||||
|
响应用户要求,以同一个 arm64 Release 诊断包顺序运行纯文字和完整面板,前台 2 秒、后台关闭、能量开启、全部进程候选不变、公网查询策略不变。两种模式均使用同一个 NSPanel、无窗口开合动画,鼠标移至面板外;不并行运行编译或其他 GUI 检查。每个进程冷启动隐藏 10 秒,展开 30 秒 / 隐藏 30 秒,共三轮,第一轮另暂停 10 秒。
|
||||||
|
|
||||||
|
文字模式采用原生固定行高 NSTableView,只有文字,无图表、图标和持续动画;全部进程可滚动,按可见行创建并复用文字单元格。不能用一个静态 “Kymo” 标签代表有实时数据的文字模式。保留同一后端与历史;它是诊断前端,尚未替换产品交互。
|
||||||
|
|
||||||
|
环境为 Apple M4 Pro / 48 GiB / macOS 27.2。两组候选进程数量随系统小幅变化,未固定外部进程工作负载,因此 CPU 差异仅作定位线索。
|
||||||
|
|
||||||
|
内存记录主进程 phys_footprint 及进程生命周期峰值,另用 libproc 每秒采集主程序 / 本包 XPC 的足迹与累计 CPU;CPU 的 Mach tick 以本机 timebase 转秒。主程序与 XPC 分列;采集器自身开销不混入应用 CPU,但仍可能干扰环境。这是短期诊断,不是 10 分钟无诊断能耗验收,也没有 WindowServer 配对功耗数据。
|
||||||
|
|
||||||
|
复现入口(仅对自己构建的副本运行;两组依次启动,不能并行):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Release \
|
||||||
|
-derivedDataPath /private/tmp/kymo-audit SWIFT_ACTIVE_COMPILATION_CONDITIONS=KYMO_AUDIT build
|
||||||
|
# 文字组;完整组去掉 KYMO_AUDIT_OMIT=text。入口会完成三轮并自动退出。
|
||||||
|
open -n -W --env KYMO_RESOURCE_AUDIT=1 --env KYMO_DIAGNOSTICS=1 \
|
||||||
|
--env KYMO_AUDIT_OMIT=text --stdout /private/tmp/kymo-audit-text.jsonl \
|
||||||
|
/private/tmp/kymo-audit/Build/Products/Release/kymo.app \
|
||||||
|
--args -sampling.backgroundEnabled NO -sampling.panelMilliseconds 2000
|
||||||
|
```
|
||||||
|
|
||||||
|
普通发行 Release 不接受这些审计开关。诊断会固定浮动面板,应避免干扰正常操作;原始日志可能包含接口标识,汇总后清理。
|
||||||
|
|
||||||
|
## 三轮文字结果
|
||||||
|
|
||||||
|
| 轮次 | 展开 30 秒主进程 MiB | 关闭 30 秒主进程 MiB | 主进程累计峰值 MiB | 展开 10–30 秒主进程 CPU | 同窗口 XPC CPU |
|
||||||
|
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||||
|
| 1 | 36.83 | 33.08 | 43.10 | 1.427% | 0.190% |
|
||||||
|
| 2 | 30.75 | 30.52 | 43.10 | 1.692% | 0.204% |
|
||||||
|
| 3 | 31.33 | 31.24 | 43.10 | 1.628% | 0.199% |
|
||||||
|
|
||||||
|
冷启动隐藏 10 秒约 15.42 MiB;展开窗口中的 XPC 足迹约 4.55–5.02 MiB,需另计。三轮中均约 733–740 个候选、503–509 个可读进程,文字前端每次挂载最多创建 54 个文字单元格,刷新不再逐轮增加。第一版原生表调用 reloadData 导致每次刷新重建约 54 个单元格,已改为原地更新可见文字,行数变化只在尾部增删行。
|
||||||
|
|
||||||
|
关闭后的内容视图弱引用在每轮 1 / 10 / 30 秒均已释放;没有发现此宿主持有导致整块驻留。冷启动等待与暂停窗口内资源 / 能量采样发布均为 0。短期内存没有按开关轮次累积,但这不能证明 100 次或 8 小时达标。文字模式的主程序 + XPC CPU 仍超过正式门槛,不能据此称作省电已达标。
|
||||||
|
|
||||||
|
## 同构建完整面板对照
|
||||||
|
|
||||||
|
| 轮次 | 展开 30 秒主进程 MiB | 关闭 30 秒主进程 MiB | 主进程累计峰值 MiB | 展开 10–30 秒主进程 CPU | 同窗口 XPC CPU |
|
||||||
|
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||||
|
| 1 | 191.53 | 60.95 | 206.49 | 3.189% | 0.199% |
|
||||||
|
| 2 | 82.20 | 65.86 | 215.00 | 3.604% | 0.215% |
|
||||||
|
| 3 | 79.22 | 63.13 | 220.86 | 3.246% | 0.202% |
|
||||||
|
|
||||||
|
30 秒列是时间点读数,不能称作稳态平均:10–30 秒每秒采样中,完整面板主进程足迹范围分别为 72.24–196.06、77.60–196.44、74.16–202.78 MiB;文字对应范围为 35.92–42.16、29.69–33.13、29.99–35.69 MiB。完整 UI 的大增量在刷新期间反复出现,并非只有首次展开时的单一高峰。
|
||||||
|
|
||||||
|
完整面板候选数 732–736、可读 502–506,与文字组的后台略有变化;XPC 足迹约 4.52–4.94 MiB。关闭后宿主弱引用也均已释放。两组 10 秒冷启动等待、10 秒暂停中均无资源 / 能量采样发布;完整面板首次隐藏 10 秒为 15.49 MiB。
|
||||||
|
|
||||||
|
相同后端下,文字窗口将三轮累计峰值从 220.86 MiB 降到 43.10 MiB(约 80%),关闭后仍保留约 31 MiB;足以确认展示路径是重要增量来源,但不证明具体框架 / 控件是全部根因,也不能把剩余内存都叫缓存或泄漏。文字组 CPU 明显较低,但与完整组都没有达到正式 CPU 门槛。当前完整面板峰值、展开和隐藏内存门槛仍未通过。
|
||||||
|
|
||||||
|
本轮文字 / 完整面板运行期间未观察到新增 SafariPlatformSupport.Helper PID;已有系统辅助进程不能在无归属证据时全算给 Kymo。未模拟搜索编辑等用户输入,所以自动填充服务的触发问题仍未解决。
|
||||||
|
|
||||||
|
## 已做过的隔离与失败实验
|
||||||
|
|
||||||
|
在首批基线上,分别去掉 SF Symbols、文件图标、输入控件、monospacedDigit、preferredColorScheme、显式窗口 / 根事务动画、切换英文后,仍出现约 203–224 MiB 峰值。当前能量实现去掉整个进程表仍约 203 MiB。它们排除了部分“单一控件就是全部原因”的解释,没有证明某个系统框架是唯一根因。
|
||||||
|
|
||||||
|
直接把全部约 750 行、约 95k 字符放进 NSTextView 也不可靠:初版首轮峰值约 44 MiB,但第二轮约 161 MiB;改成整体 attributedString 并调整 TextKit 布局后,峰值反升到约 248–250 MiB、稳态约 69–75 MiB。说明“只显示文字”仍可能因整体重排浪费资源;最终对照改为原生文字行复用,避免每轮重建整份长文本布局。这些试验未作为产品改动保留。另以源码副本移除全部 8 处 minimumScaleFactor,首轮峰值仍为 205.91 MiB、展开 30 秒为 195.00 MiB;未解决峰值,因此也未合入。
|
||||||
|
|
||||||
|
## 产物
|
||||||
|
|
||||||
|
干净 DerivedData 的普通签名 arm64 Release(无 KYMO_AUDIT):
|
||||||
|
|
||||||
|
| 项目 | 字节 |
|
||||||
|
| --- | ---: |
|
||||||
|
| .app 全部文件逻辑大小 | 2,016,168 |
|
||||||
|
| 同格式 ZIP | 1,049,871 |
|
||||||
|
| 主可执行文件 | 1,231,088 |
|
||||||
|
| Assets.car | 495,784 |
|
||||||
|
| XPC 可执行文件 | 141,296 |
|
||||||
|
|
||||||
|
包含真实 CPU 能量功能后仍满足 .app ≤3 MB、ZIP ≤1.5 MB 的包体积目标。该数字不是通用架构、公证 DMG 或 APFS 实际占用;不为减小体积移除签名、安全校验或必要功能。当前保留默认优化,未擅自改用未经性能对照的 -Osize。
|
||||||
|
|
||||||
|
## 本轮验证
|
||||||
|
|
||||||
|
- Debug / Release 构建通过;仅出现未使用 AppIntents 的系统元数据提取提示,没有 Swift 编译告警。普通 Release 深度严格签名核验通过,二进制不包含文字诊断标记和 XPC 竞态审计标记。
|
||||||
|
- 当前源码在 Debug 实包上运行 `python3 tools/check.py --app ... --gui --network`:29 项 Swift 检查、208 项三语目录与沙盒权限检查全部通过,包含独立原生 NSPanel 遮挡 / 恢复 / orderOut、设置生命周期、即时语言及签名沙盒公网 HTTPS 200。没有 XCTest Target,未将独立检查冒称 xcodebuild test。
|
||||||
|
- 正式签名 Release 诊断副本的 ServiceRequest 检查通过:顺序 / 并发重复完成、超时、在途及提前取消。此处为真实连接生命周期加本地回调注入,实际 peer 中断尚未测试。
|
||||||
|
- 另用受控约 200ms CPU 工作核对采集器单位:rusage 经本机 125/3 timebase 换算为 0.199938 秒,线程 CPU 时钟为 0.199920 秒,避免将 Mach tick 错当纳秒。
|
||||||
|
- 所有三轮原始诊断、探针与临时构建在汇总匿名数值后清理;仅退出本轮副本,不操作用户已有 Xcode 调试实例。
|
||||||
|
|
||||||
|
## 验收边界与后续
|
||||||
|
|
||||||
|
系统能量本机受控 CPU 负载可推进,正式 XPC 实测约 720–740 个候选、约 490–506 个可读,排名由有效差分形成。不同 UID 不可读会使覆盖不全;不能称作全机完整耗电榜。巨大候选数在总截止下的公平轮转、其他机型 / 系统尚未验收。
|
||||||
|
|
||||||
|
真实硬件睡眠 / 息屏未触发,以免打断用户;本轮验证状态注入与事件装配。工具绑定正式产品路径再次超时(-10005),未据此推断权限缺失;原生独立窗口测试和真实面板方法驱动不等于 AX / 鼠标 / 键盘事件已验证。自动填充辅助服务触发条件与系统绘制资源归属仍未定位。
|
||||||
|
|
||||||
|
仍需继续:内存峰值 / 隐藏回落、完整面板 CPU、能量列表额外 CPU 配对对照、100 次开关 / 8 小时、整机功耗、WindowServer 与辅助服务增量、图标有界缓存、真实出口键规范化、XPC 中断取消传播。短期数值不能豁免原预算,也不能将已释放视图后的驻留全部称作泄漏或缓存。
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
日期:2026-11-03。源码基线:`8333349e93c627b8b1df3802e0d3adac32610472`。
|
日期:2026-11-03。源码基线:`8333349e93c627b8b1df3802e0d3adac32610472`。
|
||||||
|
|
||||||
状态:实施中,已完成首批调度 / XPC / 静态显示 / 包体积改动,详见[首批实施记录](efficiency-first-batch.md)。以下设计仍含未实施部分;预算未全部通过,真实能耗列表尚未实现。
|
状态:实施中,已完成首批调度 / XPC / 静态显示 / 包体积改动,详见[首批实施记录](efficiency-first-batch.md)。以下设计仍含未实施部分;真实 CPU 能量列表已实现,预算未全部通过;最新证据见[第二批记录](efficiency-second-batch.md)。
|
||||||
|
|
||||||
## 1. 背景与目标
|
## 1. 背景与目标
|
||||||
|
|
||||||
@@ -120,7 +120,7 @@ Kymo 的定位是体积极小、占用极小、省电的极客监控工具。当
|
|||||||
|
|
||||||
### 5.1 按状态决定工作
|
### 5.1 按状态决定工作
|
||||||
|
|
||||||
默认隐藏后不保留连续后台趋势采样;以打开时补采和历史断点明确表达空白。保留显式“后台趋势”选项,默认关闭,开启后默认基础周期 30 秒,温度 / 风扇默认不采。旧版本已有自定义后台间隔不擅自覆盖;迁移与 UI 清楚表达启用条件,记录更改理由。这是计划中的行为变化,不是已实施的决定。
|
默认隐藏后不保留连续后台趋势采样;以打开时补采和历史断点明确表达空白。保留显式“后台趋势”选项,默认关闭,开启后默认基础周期 30 秒,温度 / 风扇默认不采。旧版本已有自定义后台间隔不擅自覆盖;迁移与 UI 清楚表达启用条件,记录更改理由。该行为已实施。
|
||||||
|
|
||||||
| 状态 | 基础指标 | 进程 / 能量 | 传感器 / 慢报告 / 公网 | 绘制 |
|
| 状态 | 基础指标 | 进程 / 能量 | 传感器 / 慢报告 / 公网 | 绘制 |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
@@ -288,12 +288,12 @@ python3 tools/check.py --configuration Release
|
|||||||
|
|
||||||
| 阶段 | 当前状态 | 证据 / 未完成 |
|
| 阶段 | 当前状态 | 证据 / 未完成 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 方案 | 已编写 | 汇总本次会话与源码检查;尚未实施 |
|
| 方案 | 实施中 | 按首批与第二批记录推进,性能预算保持原值 |
|
||||||
| P0 | 进行中 | 新 Release 复现、字形分配栈、组件隔离与真实面板三轮;仍缺受控 Debug / 完整触发链 |
|
| P0 | 进行中 | 新 Release 复现、字形分配栈、组件隔离与真实面板三轮;仍缺受控 Debug / 完整触发链 |
|
||||||
| P1 | 部分完成 | 批量 XPC / 服务共享 / 独立退避 / 取消超时 / 隐藏需求 / 公网暂停;出口、遮挡、睡眠和有界子进程未完成 |
|
| P1 | 部分完成 | 批量 XPC / 服务共享 / 独立退避 / 取消超时 / 隐藏需求 / 公网暂停;遮挡、睡眠、息屏、需求代次与有界子进程已补;出口键和慢报告上层取消未完成 |
|
||||||
| P2 | 部分完成 | 静态数字 / 曲线 / 风扇与路径缓存;内存峰值及回落未达标、按域发布 / 图标专项待做 |
|
| P2 | 部分完成 | 静态数字 / 曲线 / 风扇与路径缓存;内存峰值及回落未达标、按域发布已做,纯文字 / 完整面板三轮对照已记录(约 43 / 221 MiB 峰值);图标专项待做 |
|
||||||
| P3 | 未开始 | 耗电进程仍为旧 CPU 实现;真实系统能量列表待实现 |
|
| P3 | 功能已实现,验收未完成 | 真实 CPU 能量、签名 XPC、部分覆盖与边界检查;跨硬件、巨大集合、公平性及额外 CPU 预算待验 |
|
||||||
| P4 | 首批产物达标 | 本机签名 arm64 app 1,882,766 B / ZIP 1,005,772 B,默认优化;发行流程与完整功能新增后需复验 |
|
| P4 | 本轮包体积目标达标 | 含真实 CPU 能量的普通签名 arm64 app 2,016,168 B / ZIP 1,049,871 B,排除诊断实现;通用架构 / 公证发行流程待验 |
|
||||||
| P5 | 未完成 | 短时面板和自动检查不替代 CPU / W / 100 次 / 8 小时与多硬件验收 |
|
| P5 | 未完成 | 短时面板和自动检查不替代 CPU / W / 100 次 / 8 小时与多硬件验收 |
|
||||||
|
|
||||||
每阶段更新本表及 L01–L16 的结论,记录提交、实测数值、未达标项和原因;架构 / 指标 / 测试事实分别同步主题文档。最终以完整功能、相同条件、关闭诊断的 Release 验收,不以“改完代码”或“编译通过”结束。方案完成后将稳定规则归入主题文档,过程记录保留到问题可审计为止。
|
每阶段更新本表及 L01–L16 的结论,记录提交、实测数值、未达标项和原因;架构 / 指标 / 测试事实分别同步主题文档。最终以完整功能、相同条件、关闭诊断的 Release 验收,不以“改完代码”或“编译通过”结束。方案完成后将稳定规则归入主题文档,过程记录保留到问题可审计为止。
|
||||||
|
|||||||
+11
-2
@@ -30,7 +30,7 @@
|
|||||||
- GPU Renderer / Tiler 是活动阶段指标,可能重叠,不能相加成为总占用。GPU 核心数不代表逐核计数;目前没有独立逐核 GPU 占用。
|
- GPU Renderer / Tiler 是活动阶段指标,可能重叠,不能相加成为总占用。GPU 核心数不代表逐核计数;目前没有独立逐核 GPU 占用。
|
||||||
- GPU 驱动内存不是独立显存容量,也不是可计算占比的统一内存上限。平均值为最近 60 秒窗口内有效连续区间的时间加权平均,峰值取窗口内可用样本;历史不足时统计覆盖时间更短,不能视为完整一分钟。
|
- GPU 驱动内存不是独立显存容量,也不是可计算占比的统一内存上限。平均值为最近 60 秒窗口内有效连续区间的时间加权平均,峰值取窗口内可用样本;历史不足时统计覆盖时间更短,不能视为完整一分钟。
|
||||||
- 网络“全部”仅汇总 active 且名称以 `en` 开头的接口,避免物理链路与 `utun` 双计。接口选择仍可查看其他活动接口;这个规则不等于所有设备和隧道的通用流量归因。
|
- 网络“全部”仅汇总 active 且名称以 `en` 开头的接口,避免物理链路与 `utun` 双计。接口选择仍可查看其他活动接口;这个规则不等于所有设备和隧道的通用流量归因。
|
||||||
- 进程 CPU 以一个逻辑核满载为 100%,多线程可超过 100%,不能直接与整机 CPU 百分比比较。首次进程采样没有差分值;电池卡片前三名按 CPU 排序,并非电池能耗测量。
|
- 进程 CPU 以一个逻辑核满载为 100%,多线程可超过 100%,不能直接与整机 CPU 百分比比较。首次进程采样没有差分值;耗电区已改为独立 CPU 能量计数差分,不能将进程 CPU 百分比当成耗电。
|
||||||
- 电池模型可计算充电 / 放电时间,但当前卡片仅在非外接电源时显示剩余时间,外接电源显示不适用。系统未给出有效估计时显示未知。
|
- 电池模型可计算充电 / 放电时间,但当前卡片仅在非外接电源时显示剩余时间,外接电源显示不适用。系统未给出有效估计时显示未知。
|
||||||
|
|
||||||
## 采样与缓存周期
|
## 采样与缓存周期
|
||||||
@@ -38,7 +38,8 @@
|
|||||||
| 数据 | 默认 / 周期策略 |
|
| 数据 | 默认 / 周期策略 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 常规资源快照 | 面板可见默认 2000ms;新配置隐藏默认停止采样,显式启用后台趋势后默认 30000ms;已有合法后台间隔保留启用和原值,显式开关优先;可设 500–1,800,000ms,步进 100ms |
|
| 常规资源快照 | 面板可见默认 2000ms;新配置隐藏默认停止采样,显式启用后台趋势后默认 30000ms;已有合法后台间隔保留启用和原值,显式开关优先;可设 500–1,800,000ms,步进 100ms |
|
||||||
| 进程 | 面板可见且未暂停时随采样请求更新;异步完成可单独发布,最多一个在途 |
|
| 进程 | 面板实际可见且未暂停 / 睡眠时随采样请求更新;异步独立发布,最多一个在途 |
|
||||||
|
| 进程 CPU 能量 | 复用同轮进程候选,成功后至少 5 秒再读(默认 2 秒轮次下通常约 6 秒);失败 30–600 秒退避,明确不支持后 600 秒;最多一批在途 |
|
||||||
| CPU / GPU 温度、风扇 | 一次批量请求中只读取到期类别;各类别成功后至少 10 秒再读,失败独立退避 60–600 秒 |
|
| CPU / GPU 温度、风扇 | 一次批量请求中只读取到期类别;各类别成功后至少 10 秒再读,失败独立退避 60–600 秒 |
|
||||||
| 卷列表 | 读取结束后至少 30 秒 |
|
| 卷列表 | 读取结束后至少 30 秒 |
|
||||||
| SMART / 电池健康 | 成功后至少 3600 秒;失败后至少 600 秒 |
|
| SMART / 电池健康 | 成功后至少 3600 秒;失败后至少 600 秒 |
|
||||||
@@ -52,3 +53,11 @@
|
|||||||
AppleSMC 和 GPU 驱动字段不是稳定公开的跨机型指标接口,缺失时应降级。磁盘报告、电池报告与进程读取受系统版本、硬件和沙盒权限影响。新增支持必须有实际采样和合理性核对,不从核心数、总利用率或其他传感器推导不存在的读数。
|
AppleSMC 和 GPU 驱动字段不是稳定公开的跨机型指标接口,缺失时应降级。磁盘报告、电池报告与进程读取受系统版本、硬件和沙盒权限影响。新增支持必须有实际采样和合理性核对,不从核心数、总利用率或其他传感器推导不存在的读数。
|
||||||
|
|
||||||
慢报告输出通过共享 `BoundedProcess` 流式限制为 256 KiB(检测溢出多读至多 1 字节),截止 10 秒;超限、超时和直接调用 Task 取消会强制终止并回收本轮子进程,失败按原缓存周期退避。不会先无限读完再判大小。
|
慢报告输出通过共享 `BoundedProcess` 流式限制为 256 KiB(检测溢出多读至多 1 字节),截止 10 秒;超限、超时和直接调用 Task 取消会强制终止并回收本轮子进程,失败按原缓存周期退避。不会先无限读完再判大小。
|
||||||
|
|
||||||
|
## 耗电进程:CPU 归属能量
|
||||||
|
|
||||||
|
读取 `proc_pid_rusage(RUSAGE_INFO_V6).ri_energy_nj`,显示相邻有效计数的平均功率 mW / W 和实际窗口。服务 arm64 自身计数非零时才返回 verifiedCPU;其他架构返回 unsupported,未确认能力时不提供零瓦或 CPU 排名。当前 M4 Pro 实测受控 CPU 工作使计数增长,并通过正式签名沙盒主程序 → XPC 取得同 UID 其他进程的有效差分。
|
||||||
|
|
||||||
|
该口径是系统归属的 CPU 能量,参考 [Apple XNU task.c](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/task.c) 和 [recount.c](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/recount.c);开源主线不保证与目标系统二进制完全一致。它不含完整 GPU / 屏幕 / 网络 / 整机功耗,不聚合应用子进程,不等于活动监视器 Energy Impact。条形图相对当前列表最大值,不能理解为整机耗电百分比。
|
||||||
|
|
||||||
|
按全部可测候选的有效能量差分排名。权限受限、进程退出和截止会降低覆盖率;UI 显示已形成差分数 / 枚举总数,首帧等待,失败或不支持明确显示状态。零增量只有连续两帧有效时才代表 0 W。身份变化、计数回退、无效时间和超过允许窗口均不形成排名。超大进程集合在总截止下可能只覆盖部分批次,尚未验证极端规模下的公平轮转。
|
||||||
|
|||||||
@@ -277,3 +277,13 @@ swiftc -parse-as-library kymo/Core/Services/LanguagePreferences.swift kymo/UI/Co
|
|||||||
Release 配置由各 Target 在签名前 strip,保留包外 dSYM;测量必须对最终签名包统计文件逻辑大小、相同格式 ZIP 与资源 rendition,不能使用只改 DerivedData 的手工 strip 结果。首次局部结果低于包大小预算,不代表内存 / CPU / W / 8 小时已经通过。
|
Release 配置由各 Target 在签名前 strip,保留包外 dSYM;测量必须对最终签名包统计文件逻辑大小、相同格式 ZIP 与资源 rendition,不能使用只改 DerivedData 的手工 strip 结果。首次局部结果低于包大小预算,不代表内存 / CPU / W / 8 小时已经通过。
|
||||||
|
|
||||||
`BoundedProcessChecks` 实际启动本检查程序的子模式,验证精确上限 / 超限、大输出、非零退出、关闭 stdout 后挂起、忽略 SIGTERM 的静默挂起、截止时间、启动前与启动后取消,以及直接子进程全部回收。独立运行不需要 GUI、网络或管理员权限;禁止以真实系统进程充当终止测试对象。
|
`BoundedProcessChecks` 实际启动本检查程序的子模式,验证精确上限 / 超限、大输出、非零退出、关闭 stdout 后挂起、忽略 SIGTERM 的静默挂起、截止时间、启动前与启动后取消,以及直接子进程全部回收。独立运行不需要 GUI、网络或管理员权限;禁止以真实系统进程充当终止测试对象。
|
||||||
|
|
||||||
|
## 第二批效率回归与对照
|
||||||
|
|
||||||
|
`ProcessEnergyChecks` 覆盖大 UInt64 差分与序列化、首帧 / 零值 / 回退 / 身份复用 / 缺失 / 时间边界、真实能量与 CPU 排序相反、部分覆盖与无 CPU 降级;`ProcessEnergyReaderChecks` 覆盖本机受控 CPU 能量增长、身份 / UID、重复和超限请求。`SamplingIntervalChecks` 增加进程发布不触发资源观察者、系统 / 显示器睡眠、显式后台保留及旧需求代次不能覆盖新状态。状态注入不等于真实硬件睡眠实测。
|
||||||
|
|
||||||
|
`PanelWindowChecks` 额外用独立原生窗口完全遮挡固定面板,检查采样降级、恢复及 orderOut / orderFront。测试时不要同时运行固定浮动的资源审计窗口,否则测试窗口被覆盖会使“可见”断言失效。
|
||||||
|
|
||||||
|
纯文字与完整面板对照使用同一 Release 诊断包,构建时设置 `SWIFT_ACTIVE_COMPILATION_CONDITIONS=KYMO_AUDIT`;普通 Release 已排除诊断实现。`KYMO_RESOURCE_AUDIT=1 KYMO_DIAGNOSTICS=1` 启用三轮真实窗口生命周期,`KYMO_AUDIT_OMIT=text` 选择原生虚拟文字列表;保留全部后端、历史、公网策略和候选进程,只取消图表、图标、动画与复杂交互呈现。每次顺序运行,固定鼠标位置、不并行编译或 GUI 检查。日志记录 materialized cells 与关闭内容弱引用;这是诊断前端,并非产品界面已替换。
|
||||||
|
|
||||||
|
同一诊断包增加 `KYMO_XPC_AUDIT=1` 可检查 ServiceRequest 重复 / 并发响应、超时、启动前与在途取消。这使用真实连接生命周期与注入的本地完成回调,不代表服务端中断 / 崩溃传播已经实测;对端认证和实际读取另行验证。
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
objects = {
|
objects = {
|
||||||
|
|
||||||
/* Begin PBXBuildFile section */
|
/* Begin PBXBuildFile section */
|
||||||
CC1000000000000000000001 /* BoundedProcess.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000002 /* BoundedProcess.swift */; };
|
|
||||||
BB000000000000000000001E /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000A /* main.swift */; };
|
BB000000000000000000001E /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000A /* main.swift */; };
|
||||||
BB000000000000000000001F /* DiskSMARTReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000B /* DiskSMARTReader.swift */; };
|
BB000000000000000000001F /* DiskSMARTReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000B /* DiskSMARTReader.swift */; };
|
||||||
BB0000000000000000000020 /* SMARTServiceProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000C /* SMARTServiceProtocol.swift */; };
|
BB0000000000000000000020 /* SMARTServiceProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000C /* SMARTServiceProtocol.swift */; };
|
||||||
@@ -16,6 +15,10 @@
|
|||||||
BB0000000000000000000023 /* DiskHealthReport.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB000000000000000000000F /* DiskHealthReport.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, ); }; };
|
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 */; };
|
BB0000000000000000000025 /* CPUTemperatureMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB0000000000000000000010 /* CPUTemperatureMonitor.swift */; };
|
||||||
|
CC1000000000000000000001 /* BoundedProcess.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000002 /* BoundedProcess.swift */; };
|
||||||
|
CC1000000000000000000003 /* ProcessMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000004 /* ProcessMetrics.swift */; };
|
||||||
|
CC1000000000000000000005 /* ProcessEnergy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000006 /* ProcessEnergy.swift */; };
|
||||||
|
CC1000000000000000000007 /* ProcessEnergyReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1000000000000000000008 /* ProcessEnergyReader.swift */; };
|
||||||
/* End PBXBuildFile section */
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
/* Begin PBXContainerItemProxy section */
|
/* Begin PBXContainerItemProxy section */
|
||||||
@@ -41,7 +44,6 @@
|
|||||||
/* End PBXCopyFilesBuildPhase section */
|
/* End PBXCopyFilesBuildPhase section */
|
||||||
|
|
||||||
/* Begin PBXFileReference section */
|
/* Begin PBXFileReference section */
|
||||||
CC1000000000000000000002 /* BoundedProcess.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = BoundedProcess.swift; path = kymo/Core/Services/BoundedProcess.swift; sourceTree = SOURCE_ROOT; };
|
|
||||||
BB0000000000000000000002 /* SMARTService.xpc */ = {isa = PBXFileReference; explicitFileType = "wrapper.xpc-service"; includeInIndex = 0; path = SMARTService.xpc; sourceTree = BUILT_PRODUCTS_DIR; };
|
BB0000000000000000000002 /* SMARTService.xpc */ = {isa = PBXFileReference; explicitFileType = "wrapper.xpc-service"; includeInIndex = 0; path = SMARTService.xpc; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
BB000000000000000000000A /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = main.swift; path = SMARTService/main.swift; sourceTree = SOURCE_ROOT; };
|
BB000000000000000000000A /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = main.swift; path = SMARTService/main.swift; sourceTree = SOURCE_ROOT; };
|
||||||
BB000000000000000000000B /* DiskSMARTReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DiskSMARTReader.swift; path = SMARTService/DiskSMARTReader.swift; sourceTree = SOURCE_ROOT; };
|
BB000000000000000000000B /* DiskSMARTReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DiskSMARTReader.swift; path = SMARTService/DiskSMARTReader.swift; sourceTree = SOURCE_ROOT; };
|
||||||
@@ -51,6 +53,10 @@
|
|||||||
BB000000000000000000000F /* DiskHealthReport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DiskHealthReport.swift; path = kymo/Core/Monitors/DiskHealthReport.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; };
|
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; };
|
BB0000000000000000000016 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = SMARTService/Info.plist; sourceTree = SOURCE_ROOT; };
|
||||||
|
CC1000000000000000000002 /* BoundedProcess.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = BoundedProcess.swift; path = kymo/Core/Services/BoundedProcess.swift; sourceTree = SOURCE_ROOT; };
|
||||||
|
CC1000000000000000000004 /* ProcessMetrics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ProcessMetrics.swift; path = kymo/Core/Models/ProcessMetrics.swift; sourceTree = SOURCE_ROOT; };
|
||||||
|
CC1000000000000000000006 /* ProcessEnergy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ProcessEnergy.swift; path = kymo/Core/Models/ProcessEnergy.swift; sourceTree = SOURCE_ROOT; };
|
||||||
|
CC1000000000000000000008 /* ProcessEnergyReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ProcessEnergyReader.swift; path = SMARTService/ProcessEnergyReader.swift; sourceTree = SOURCE_ROOT; };
|
||||||
D9E51E73309338B0000608DE /* kymo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = kymo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
D9E51E73309338B0000608DE /* kymo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = kymo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
/* End PBXFileReference section */
|
/* End PBXFileReference section */
|
||||||
|
|
||||||
@@ -108,6 +114,9 @@
|
|||||||
BB000000000000000000000C /* SMARTServiceProtocol.swift */,
|
BB000000000000000000000C /* SMARTServiceProtocol.swift */,
|
||||||
BB000000000000000000000D /* CodeIdentity.swift */,
|
BB000000000000000000000D /* CodeIdentity.swift */,
|
||||||
CC1000000000000000000002 /* BoundedProcess.swift */,
|
CC1000000000000000000002 /* BoundedProcess.swift */,
|
||||||
|
CC1000000000000000000008 /* ProcessEnergyReader.swift */,
|
||||||
|
CC1000000000000000000006 /* ProcessEnergy.swift */,
|
||||||
|
CC1000000000000000000004 /* ProcessMetrics.swift */,
|
||||||
BB000000000000000000000E /* DiskHealthMetrics.swift */,
|
BB000000000000000000000E /* DiskHealthMetrics.swift */,
|
||||||
BB000000000000000000000F /* DiskHealthReport.swift */,
|
BB000000000000000000000F /* DiskHealthReport.swift */,
|
||||||
BB0000000000000000000010 /* CPUTemperatureMonitor.swift */,
|
BB0000000000000000000010 /* CPUTemperatureMonitor.swift */,
|
||||||
@@ -226,6 +235,9 @@
|
|||||||
BB0000000000000000000020 /* SMARTServiceProtocol.swift in Sources */,
|
BB0000000000000000000020 /* SMARTServiceProtocol.swift in Sources */,
|
||||||
BB0000000000000000000021 /* CodeIdentity.swift in Sources */,
|
BB0000000000000000000021 /* CodeIdentity.swift in Sources */,
|
||||||
CC1000000000000000000001 /* BoundedProcess.swift in Sources */,
|
CC1000000000000000000001 /* BoundedProcess.swift in Sources */,
|
||||||
|
CC1000000000000000000007 /* ProcessEnergyReader.swift in Sources */,
|
||||||
|
CC1000000000000000000005 /* ProcessEnergy.swift in Sources */,
|
||||||
|
CC1000000000000000000003 /* ProcessMetrics.swift in Sources */,
|
||||||
BB0000000000000000000022 /* DiskHealthMetrics.swift in Sources */,
|
BB0000000000000000000022 /* DiskHealthMetrics.swift in Sources */,
|
||||||
BB0000000000000000000023 /* DiskHealthReport.swift in Sources */,
|
BB0000000000000000000023 /* DiskHealthReport.swift in Sources */,
|
||||||
BB0000000000000000000025 /* CPUTemperatureMonitor.swift in Sources */,
|
BB0000000000000000000025 /* CPUTemperatureMonitor.swift in Sources */,
|
||||||
@@ -380,11 +392,9 @@
|
|||||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||||
COPY_PHASE_STRIP = NO;
|
COPY_PHASE_STRIP = NO;
|
||||||
DEPLOYMENT_POSTPROCESSING = YES;
|
|
||||||
STRIP_INSTALLED_PRODUCT = YES;
|
|
||||||
STRIP_STYLE = all;
|
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||||
|
DEPLOYMENT_POSTPROCESSING = YES;
|
||||||
ENABLE_NS_ASSERTIONS = NO;
|
ENABLE_NS_ASSERTIONS = NO;
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||||
@@ -402,6 +412,8 @@
|
|||||||
MTL_FAST_MATH = YES;
|
MTL_FAST_MATH = YES;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||||
|
STRIP_INSTALLED_PRODUCT = YES;
|
||||||
|
STRIP_STYLE = all;
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
};
|
};
|
||||||
name = Release;
|
name = Release;
|
||||||
|
|||||||
+18
-2
@@ -13,7 +13,7 @@ import AppKit
|
|||||||
}
|
}
|
||||||
|
|
||||||
@MainActor private final class ApplicationLifecycle: NSObject, NSApplicationDelegate {
|
@MainActor private final class ApplicationLifecycle: NSObject, NSApplicationDelegate {
|
||||||
private let metrics = MetricsStore()
|
private let metrics = MetricsStore(energyEnabled: PanelResourceAudit.omitted != "energy")
|
||||||
private let awake = KeepAwakeService()
|
private let awake = KeepAwakeService()
|
||||||
private let presentation = SettingsPresentation()
|
private let presentation = SettingsPresentation()
|
||||||
private let appearance = AppearancePreferences()
|
private let appearance = AppearancePreferences()
|
||||||
@@ -21,8 +21,20 @@ import AppKit
|
|||||||
private var openSettingsAction: (() -> Void)?
|
private var openSettingsAction: (() -> Void)?
|
||||||
private var scenes: AnyObject?
|
private var scenes: AnyObject?
|
||||||
private var menuBar: MenuPanelController?
|
private var menuBar: MenuPanelController?
|
||||||
|
private var workspaceTokens: [NSObjectProtocol] = []
|
||||||
|
|
||||||
func applicationWillFinishLaunching(_ notification: Notification) {
|
func applicationWillFinishLaunching(_ notification: Notification) {
|
||||||
|
let center = NSWorkspace.shared.notificationCenter
|
||||||
|
for (name, sleeping) in [(NSWorkspace.willSleepNotification, true), (NSWorkspace.didWakeNotification, false)] {
|
||||||
|
workspaceTokens.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
|
||||||
|
MainActor.assumeIsolated { self?.metrics.setSystemSleeping(sleeping) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for (name, sleeping) in [(NSWorkspace.screensDidSleepNotification, true), (NSWorkspace.screensDidWakeNotification, false)] {
|
||||||
|
workspaceTokens.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
|
||||||
|
MainActor.assumeIsolated { self?.metrics.setDisplaySleeping(sleeping) }
|
||||||
|
})
|
||||||
|
}
|
||||||
let settings = NSHostingSceneRepresentation {
|
let settings = NSHostingSceneRepresentation {
|
||||||
Settings {
|
Settings {
|
||||||
AppLanguageScope(preferences: language, onChange: { self.configureMainMenu() }) { [self] in
|
AppLanguageScope(preferences: language, onChange: { self.configureMainMenu() }) { [self] in
|
||||||
@@ -38,7 +50,9 @@ import AppKit
|
|||||||
menuTitle: { [language] key in
|
menuTitle: { [language] key in
|
||||||
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
|
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
|
||||||
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
|
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
|
||||||
if PanelResourceAudit.omitted == "all" {
|
if PanelResourceAudit.omitted == "text" {
|
||||||
|
TextMonitoringAuditView(metrics: self.metrics, appearance: self.appearance)
|
||||||
|
} else if PanelResourceAudit.omitted == "all" {
|
||||||
Text(verbatim: "Kymo").frame(maxWidth: .infinity, maxHeight: .infinity)
|
Text(verbatim: "Kymo").frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
} else {
|
} else {
|
||||||
AppLanguageScope(preferences: language) {
|
AppLanguageScope(preferences: language) {
|
||||||
@@ -84,6 +98,8 @@ import AppKit
|
|||||||
}
|
}
|
||||||
|
|
||||||
func applicationWillTerminate(_ notification: Notification) {
|
func applicationWillTerminate(_ notification: Notification) {
|
||||||
|
workspaceTokens.forEach(NSWorkspace.shared.notificationCenter.removeObserver)
|
||||||
|
workspaceTokens.removeAll()
|
||||||
menuBar?.shutdown()
|
menuBar?.shutdown()
|
||||||
awake.disable()
|
awake.disable()
|
||||||
menuBar = nil
|
menuBar = nil
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
nonisolated enum EnergyReadStatus: String, Codable, Sendable {
|
||||||
|
case available, denied, gone, failed, identityChanged, deadline, unsupported, unverified
|
||||||
|
}
|
||||||
|
nonisolated enum EnergyCapability: String, Codable, Sendable { case verifiedCPU, unverified, unsupported, unavailable }
|
||||||
|
nonisolated struct ProcessEnergyRequest: Codable, Sendable {
|
||||||
|
let token: UUID
|
||||||
|
let identities: [ProcessIdentity]
|
||||||
|
static let limit = 256
|
||||||
|
static let byteLimit = 65_536
|
||||||
|
}
|
||||||
|
nonisolated struct ProcessEnergyReading: Codable, Sendable {
|
||||||
|
let id: ProcessIdentity
|
||||||
|
let birth: UInt64
|
||||||
|
let uptime: TimeInterval
|
||||||
|
let nanojoules: UInt64?
|
||||||
|
let status: EnergyReadStatus
|
||||||
|
}
|
||||||
|
nonisolated struct ProcessEnergyReply: Codable, Sendable {
|
||||||
|
let token: UUID
|
||||||
|
let capability: EnergyCapability
|
||||||
|
let readings: [ProcessEnergyReading]
|
||||||
|
}
|
||||||
|
nonisolated struct ProcessEnergyUsage: Identifiable, Sendable {
|
||||||
|
let process: ProcessMetrics
|
||||||
|
let watts: Double
|
||||||
|
let seconds: TimeInterval
|
||||||
|
var id: ProcessIdentity { process.id }
|
||||||
|
var formattedPower: String { watts >= 1 ? String(format: "%.2f W", watts) : String(format: "%.1f mW", watts * 1000) }
|
||||||
|
}
|
||||||
|
nonisolated struct ProcessEnergySnapshot: Sendable {
|
||||||
|
enum State: Sendable { case waiting, available, partial, unavailable, unsupported }
|
||||||
|
let date: Date
|
||||||
|
let candidates: Int
|
||||||
|
let readable: Int
|
||||||
|
let measured: Int
|
||||||
|
let rows: [ProcessEnergyUsage] // Only the top three; no CPU prefilter.
|
||||||
|
let state: State
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
nonisolated struct ProcessIdentity: Hashable, Sendable {
|
nonisolated struct ProcessIdentity: Hashable, Codable, Sendable {
|
||||||
let pid: Int32
|
let pid: Int32
|
||||||
let seconds: UInt64
|
let seconds: UInt64
|
||||||
let microseconds: UInt64
|
let microseconds: UInt64
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Uses system CPU energy attribution; never derives energy from CPU time or percentage.
|
||||||
|
nonisolated struct ProcessEnergyMonitor: Sendable {
|
||||||
|
private var previous: [ProcessIdentity: ProcessEnergyReading] = [:]
|
||||||
|
|
||||||
|
static func watts(current: ProcessEnergyReading, previous: ProcessEnergyReading?, maximumInterval: TimeInterval = 30) -> (Double, Double)? {
|
||||||
|
guard current.status == .available, let currentEnergy = current.nanojoules,
|
||||||
|
let previous, previous.status == .available, let previousEnergy = previous.nanojoules,
|
||||||
|
current.id == previous.id, current.birth != 0, current.birth == previous.birth,
|
||||||
|
currentEnergy >= previousEnergy else { return nil }
|
||||||
|
let elapsed = current.uptime - previous.uptime
|
||||||
|
guard elapsed.isFinite, elapsed > 0, maximumInterval.isFinite, elapsed <= maximumInterval else { return nil }
|
||||||
|
// Integer subtraction preserves low bits of large cumulative counters.
|
||||||
|
let power = Double(currentEnergy - previousEnergy) / 1_000_000_000 / elapsed
|
||||||
|
return power.isFinite && power >= 0 ? (power, elapsed) : nil
|
||||||
|
}
|
||||||
|
|
||||||
|
mutating func update(processes: ProcessSnapshot, readings: [ProcessEnergyReading], capability: EnergyCapability, maximumInterval: TimeInterval = 30) -> ProcessEnergySnapshot {
|
||||||
|
let processesByID = Dictionary(processes.rows.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
|
||||||
|
var next: [ProcessIdentity: ProcessEnergyReading] = [:]
|
||||||
|
var usages: [ProcessEnergyUsage] = []
|
||||||
|
var measured = 0
|
||||||
|
if capability == .verifiedCPU && !processes.failed {
|
||||||
|
for reading in readings where next[reading.id] == nil {
|
||||||
|
guard let process = processesByID[reading.id], reading.status == .available,
|
||||||
|
reading.nanojoules != nil, reading.birth > 0, reading.uptime.isFinite else { continue }
|
||||||
|
next[reading.id] = reading
|
||||||
|
if let (power, seconds) = Self.watts(current: reading, previous: previous[reading.id], maximumInterval: maximumInterval) {
|
||||||
|
measured += 1
|
||||||
|
let usage = ProcessEnergyUsage(process: process, watts: power, seconds: seconds)
|
||||||
|
let index = usages.firstIndex {
|
||||||
|
$0.watts < power || ($0.watts == power && $0.id.pid > process.id.pid)
|
||||||
|
} ?? usages.endIndex
|
||||||
|
usages.insert(usage, at: index)
|
||||||
|
if usages.count > 3 { usages.removeLast() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
previous = next // Failed / missing readings invalidate the old baseline.
|
||||||
|
let state: ProcessEnergySnapshot.State
|
||||||
|
if capability == .unsupported { state = .unsupported }
|
||||||
|
else if capability == .unavailable || processes.failed || (capability == .verifiedCPU && next.isEmpty) { state = .unavailable }
|
||||||
|
else if measured == 0 { state = .waiting }
|
||||||
|
else { state = measured < processes.enumerated ? .partial : .available }
|
||||||
|
return ProcessEnergySnapshot(date: Date(), candidates: processes.enumerated, readable: next.count,
|
||||||
|
measured: measured, rows: usages, state: state)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -30,11 +30,17 @@ actor SystemSampler {
|
|||||||
private var nextBattery: TimeInterval = 0
|
private var nextBattery: TimeInterval = 0
|
||||||
private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot
|
private let processRead: @Sendable (inout ProcessMonitor) -> ProcessSnapshot
|
||||||
private var processMonitor = ProcessMonitor()
|
private var processMonitor = ProcessMonitor()
|
||||||
|
private var energyMonitor = ProcessEnergyMonitor()
|
||||||
|
private var energyTask: Task<Void, Never>?
|
||||||
|
private var energySchedule = SensorSchedule(successInterval: 5, failureInterval: 30)
|
||||||
|
private var maximumEnergyInterval: TimeInterval = 30
|
||||||
|
private var energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)?
|
||||||
private var processTask: Task<Void, Never>?
|
private var processTask: Task<Void, Never>?
|
||||||
private var processCache: ProcessSnapshot?
|
private var processCache: ProcessSnapshot?
|
||||||
private var processUpdate: (@Sendable (ProcessSnapshot) -> Void)?
|
private var processUpdate: (@Sendable (ProcessSnapshot) -> Void)?
|
||||||
private var processVisible = false
|
private var processVisible = false
|
||||||
private var processGeneration = 0
|
private var processGeneration = 0
|
||||||
|
private var demandRevision = Int.min
|
||||||
|
|
||||||
init(processRead: @escaping @Sendable (inout ProcessMonitor) -> ProcessSnapshot = { $0.sample() }) {
|
init(processRead: @escaping @Sendable (inout ProcessMonitor) -> ProcessSnapshot = { $0.sample() }) {
|
||||||
self.processRead = processRead
|
self.processRead = processRead
|
||||||
@@ -42,21 +48,34 @@ actor SystemSampler {
|
|||||||
|
|
||||||
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
|
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
|
||||||
|
|
||||||
func setProcessVisible(_ visible: Bool) {
|
func setProcessVisible(_ visible: Bool, revision: Int? = nil) {
|
||||||
guard visible != processVisible else { return }
|
var changedRevision = false
|
||||||
|
if let revision {
|
||||||
|
guard revision >= demandRevision else { return }
|
||||||
|
changedRevision = revision != demandRevision
|
||||||
|
demandRevision = revision
|
||||||
|
}
|
||||||
|
guard visible != processVisible || changedRevision else { return }
|
||||||
processVisible = visible
|
processVisible = visible
|
||||||
processGeneration += 1
|
processGeneration += 1
|
||||||
processCache = nil
|
processCache = nil
|
||||||
if !visible { processUpdate = nil }
|
if !visible { processUpdate = nil; energyUpdate = nil }
|
||||||
|
energyTask?.cancel()
|
||||||
|
energyMonitor = ProcessEnergyMonitor()
|
||||||
|
energySchedule = SensorSchedule(successInterval: 5, failureInterval: 30)
|
||||||
processMonitor = ProcessMonitor()
|
processMonitor = ProcessMonitor()
|
||||||
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
|
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
|
||||||
}
|
}
|
||||||
|
|
||||||
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true,
|
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, includeEnergy: Bool = true, demandRevision: Int? = nil,
|
||||||
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot {
|
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil,
|
||||||
|
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot {
|
||||||
guard !Task.isCancelled else { return MetricsSnapshot() }
|
guard !Task.isCancelled else { return MetricsSnapshot() }
|
||||||
if let includeProcesses { setProcessVisible(includeProcesses) }
|
if let demandRevision, demandRevision < self.demandRevision { return MetricsSnapshot() }
|
||||||
|
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
|
||||||
|
self.maximumEnergyInterval = min(3600, max(30, maximumEnergyInterval))
|
||||||
self.processUpdate = processUpdate
|
self.processUpdate = processUpdate
|
||||||
|
self.energyUpdate = includeEnergy ? energyUpdate : nil
|
||||||
if !didProbe {
|
if !didProbe {
|
||||||
didProbe = true
|
didProbe = true
|
||||||
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
|
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
|
||||||
@@ -157,5 +176,25 @@ actor SystemSampler {
|
|||||||
}
|
}
|
||||||
processMonitor = monitor; processCache = value
|
processMonitor = monitor; processCache = value
|
||||||
processUpdate?(value)
|
processUpdate?(value)
|
||||||
|
startEnergyIfNeeded(value)
|
||||||
|
}
|
||||||
|
private func startEnergyIfNeeded(_ processes: ProcessSnapshot) {
|
||||||
|
guard processVisible, energyUpdate != nil, energyTask == nil,
|
||||||
|
energySchedule.isDue(at: ProcessInfo.processInfo.systemUptime) else { return }
|
||||||
|
let generation = processGeneration
|
||||||
|
energyTask = Task { [self] in
|
||||||
|
let (readings, capability) = await ProcessEnergyServiceClient.read(processes.rows.map(\.id))
|
||||||
|
finishEnergy(processes, readings: readings, capability: capability, generation: generation)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func finishEnergy(_ processes: ProcessSnapshot, readings: [ProcessEnergyReading],
|
||||||
|
capability: EnergyCapability, generation: Int) {
|
||||||
|
energyTask = nil
|
||||||
|
guard processVisible, processGeneration == generation else { return }
|
||||||
|
energySchedule.complete(available: capability == .verifiedCPU, at: ProcessInfo.processInfo.systemUptime,
|
||||||
|
retryInterval: capability == .unsupported ? 600 : nil)
|
||||||
|
energyUpdate?(energyMonitor.update(processes: processes, readings: readings, capability: capability, maximumInterval: maximumEnergyInterval))
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,12 +4,18 @@ import Observation
|
|||||||
@MainActor @Observable
|
@MainActor @Observable
|
||||||
final class MetricsStore {
|
final class MetricsStore {
|
||||||
private(set) var snapshot = MetricsSnapshot()
|
private(set) var snapshot = MetricsSnapshot()
|
||||||
|
private(set) var processSnapshot: ProcessSnapshot?
|
||||||
private(set) var history = MetricHistory()
|
private(set) var history = MetricHistory()
|
||||||
|
private(set) var energy: ProcessEnergySnapshot?
|
||||||
private(set) var isPaused = false
|
private(set) var isPaused = false
|
||||||
|
private(set) var isSystemSleeping = false
|
||||||
|
private(set) var isDisplaySleeping = false
|
||||||
private(set) var isPanelVisible = false
|
private(set) var isPanelVisible = false
|
||||||
let sampling: SamplingPreferences
|
let sampling: SamplingPreferences
|
||||||
var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
|
private let energyEnabled: Bool
|
||||||
private var hasSamplingDemand: Bool { isPanelVisible || sampling.backgroundEnabled }
|
private var panelDemand: Bool { isPanelVisible && !isDisplaySleeping }
|
||||||
|
var effectiveMilliseconds: Int { panelDemand ? sampling.panelMilliseconds : sampling.backgroundMilliseconds }
|
||||||
|
private var hasSamplingDemand: Bool { !isSystemSleeping && (panelDemand || sampling.backgroundEnabled) }
|
||||||
@ObservationIgnored private var generation = 0
|
@ObservationIgnored private var generation = 0
|
||||||
@ObservationIgnored private var visibilityGeneration = 0
|
@ObservationIgnored private var visibilityGeneration = 0
|
||||||
@ObservationIgnored private var task: Task<Void, Never>?
|
@ObservationIgnored private var task: Task<Void, Never>?
|
||||||
@@ -18,8 +24,9 @@ final class MetricsStore {
|
|||||||
@ObservationIgnored private var needsHistoryBoundary = true
|
@ObservationIgnored private var needsHistoryBoundary = true
|
||||||
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
|
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
|
||||||
|
|
||||||
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler()) {
|
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler(), energyEnabled: Bool = true) {
|
||||||
self.sampler = sampler
|
self.sampler = sampler
|
||||||
|
self.energyEnabled = energyEnabled
|
||||||
self.sampling = sampling ?? SamplingPreferences()
|
self.sampling = sampling ?? SamplingPreferences()
|
||||||
self.sampling.onChange = { [weak self] in
|
self.sampling.onChange = { [weak self] in
|
||||||
guard let self, !self.isPaused,
|
guard let self, !self.isPaused,
|
||||||
@@ -31,6 +38,7 @@ final class MetricsStore {
|
|||||||
|
|
||||||
func start() {
|
func start() {
|
||||||
guard task == nil else { return }
|
guard task == nil else { return }
|
||||||
|
if isPaused { energy = nil; visibilityGeneration += 1 }
|
||||||
isPaused = false
|
isPaused = false
|
||||||
reschedule(reset: true)
|
reschedule(reset: true)
|
||||||
}
|
}
|
||||||
@@ -57,21 +65,32 @@ final class MetricsStore {
|
|||||||
while !Task.isCancelled {
|
while !Task.isCancelled {
|
||||||
let sampledAt = ContinuousClock.now
|
let sampledAt = ContinuousClock.now
|
||||||
let visibleGeneration = self?.visibilityGeneration
|
let visibleGeneration = self?.visibilityGeneration
|
||||||
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true,
|
var next = await sampler.sample(includeProcesses: self?.panelDemand == true,
|
||||||
includeSlowMetrics: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
|
includeSlowMetrics: self?.panelDemand == true,
|
||||||
|
maximumEnergyInterval: max(30, Double(self?.effectiveMilliseconds ?? 2000) / 500),
|
||||||
|
includeEnergy: self?.energyEnabled == true, demandRevision: visibleGeneration, processUpdate: { [weak self] processes in
|
||||||
Task { @MainActor [weak self] in
|
Task { @MainActor [weak self] in
|
||||||
guard let self, self.visibilityGeneration == visibleGeneration,
|
guard let self, self.visibilityGeneration == visibleGeneration,
|
||||||
self.isPanelVisible, !self.isPaused else { return }
|
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
|
||||||
if self.snapshot.processes.map({ $0.date > processes.date }) != true { self.snapshot.processes = processes }
|
if self.processSnapshot.map({ $0.date > processes.date }) != true { self.processSnapshot = processes }
|
||||||
|
}
|
||||||
|
}, energyUpdate: { [weak self] energy in
|
||||||
|
Task { @MainActor [weak self] in
|
||||||
|
guard let self, self.visibilityGeneration == visibleGeneration,
|
||||||
|
self.panelDemand, !self.isPaused, !self.isSystemSleeping else { return }
|
||||||
|
self.energy = energy
|
||||||
|
SamplingDiagnostics.recordEnergy(energy)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
|
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
|
||||||
if self?.isPanelVisible != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
|
if self?.panelDemand != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
|
||||||
else if let completed = self?.snapshot.processes, completed.date >= next.date {
|
else if let completed = self?.processSnapshot, completed.date >= next.date {
|
||||||
// A fast detached process result may reach MainActor before this quick snapshot.
|
// A fast detached process result may reach MainActor before this quick snapshot.
|
||||||
next.processes = completed
|
next.processes = completed
|
||||||
}
|
}
|
||||||
self?.snapshot = next
|
var resources = next
|
||||||
|
resources.processes = nil
|
||||||
|
self?.snapshot = resources
|
||||||
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true, expectedInterval: Double(self?.effectiveMilliseconds ?? 5_000) / 1000)
|
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true, expectedInterval: Double(self?.effectiveMilliseconds ?? 5_000) / 1000)
|
||||||
self?.lastPublishedAt = .now
|
self?.lastPublishedAt = .now
|
||||||
self?.needsHistoryBoundary = false
|
self?.needsHistoryBoundary = false
|
||||||
@@ -92,20 +111,39 @@ final class MetricsStore {
|
|||||||
visibilityGeneration += 1
|
visibilityGeneration += 1
|
||||||
task?.cancel()
|
task?.cancel()
|
||||||
task = nil
|
task = nil
|
||||||
Task { await sampler.setProcessVisible(false) }
|
let revision = visibilityGeneration
|
||||||
|
Task { await sampler.setProcessVisible(false, revision: revision) }
|
||||||
isPaused = true
|
isPaused = true
|
||||||
SamplingDiagnostics.record(snapshot, event: "pause")
|
SamplingDiagnostics.record(snapshot, event: "pause")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func setSystemSleeping(_ sleeping: Bool) {
|
||||||
|
guard sleeping != isSystemSleeping else { return }
|
||||||
|
isSystemSleeping = sleeping
|
||||||
|
updateDemand(reset: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setDisplaySleeping(_ sleeping: Bool) {
|
||||||
|
guard sleeping != isDisplaySleeping else { return }
|
||||||
|
isDisplaySleeping = sleeping
|
||||||
|
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
|
||||||
|
}
|
||||||
|
|
||||||
func setPanelVisible(_ visible: Bool) {
|
func setPanelVisible(_ visible: Bool) {
|
||||||
guard isPanelVisible != visible else { return }
|
guard isPanelVisible != visible else { return }
|
||||||
visibilityGeneration += 1
|
|
||||||
isPanelVisible = visible
|
isPanelVisible = visible
|
||||||
if !visible { snapshot.processes = nil }
|
updateDemand(reset: !sampling.backgroundEnabled, sampleImmediately: panelDemand)
|
||||||
let active = visible && !isPaused
|
}
|
||||||
Task { await sampler.setProcessVisible(active) }
|
|
||||||
if !isPaused { reschedule(reset: !sampling.backgroundEnabled) }
|
private func updateDemand(reset: Bool, sampleImmediately: Bool = true) {
|
||||||
|
visibilityGeneration += 1
|
||||||
|
let revision = visibilityGeneration
|
||||||
|
let active = panelDemand && !isPaused && !isSystemSleeping
|
||||||
|
if !active { processSnapshot = nil }
|
||||||
|
energy = nil
|
||||||
|
Task { await sampler.setProcessVisible(active, revision: revision) }
|
||||||
|
if !isPaused { reschedule(reset: reset, sampleImmediately: sampleImmediately) }
|
||||||
}
|
}
|
||||||
|
|
||||||
deinit { task?.cancel() }
|
deinit { task?.cancel() }
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
nonisolated enum ProcessEnergyServiceClient {
|
||||||
|
static func read(_ identities: [ProcessIdentity]) async -> ([ProcessEnergyReading], EnergyCapability) {
|
||||||
|
var readings: [ProcessEnergyReading] = []
|
||||||
|
var capability: EnergyCapability = .unavailable
|
||||||
|
let deadline = ProcessInfo.processInfo.systemUptime + 3
|
||||||
|
for start in stride(from: 0, to: identities.count, by: ProcessEnergyRequest.limit) {
|
||||||
|
guard !Task.isCancelled, ProcessInfo.processInfo.systemUptime < deadline else { break }
|
||||||
|
let chunk = Array(identities[start..<min(start + ProcessEnergyRequest.limit, identities.count)])
|
||||||
|
let request = ProcessEnergyRequest(token: UUID(), identities: chunk)
|
||||||
|
guard let data = try? JSONEncoder().encode(request), data.count <= ProcessEnergyRequest.byteLimit else { continue }
|
||||||
|
let reply: ProcessEnergyReply? = await ServiceRequest.perform(timeout: min(1.5, deadline - ProcessInfo.processInfo.systemUptime)) { proxy, finish in
|
||||||
|
proxy.readProcessEnergy(data) { data in
|
||||||
|
guard let data, data.count <= 262_144,
|
||||||
|
let value = try? JSONDecoder().decode(ProcessEnergyReply.self, from: data), value.token == request.token,
|
||||||
|
value.readings.count == chunk.count,
|
||||||
|
Set(value.readings.map(\.id)) == Set(chunk) else { finish(nil); return }
|
||||||
|
finish(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let reply {
|
||||||
|
if capability == .unavailable { capability = .unverified }
|
||||||
|
if reply.capability == .unsupported { return ([], .unsupported) }
|
||||||
|
if reply.capability == .verifiedCPU {
|
||||||
|
capability = .verifiedCPU
|
||||||
|
readings.append(contentsOf: reply.readings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (readings, capability)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import Foundation
|
|||||||
|
|
||||||
/// Fixed read-only operation: no caller-supplied paths or commands.
|
/// Fixed read-only operation: no caller-supplied paths or commands.
|
||||||
@objc protocol SMARTServiceProtocol {
|
@objc protocol SMARTServiceProtocol {
|
||||||
|
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void)
|
||||||
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
|
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
|
||||||
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
|
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
|
||||||
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
|
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
|
||||||
|
|||||||
@@ -5,7 +5,23 @@ import Darwin
|
|||||||
nonisolated enum SamplingDiagnostics {
|
nonisolated enum SamplingDiagnostics {
|
||||||
static let enabled = ProcessInfo.processInfo.environment["KYMO_DIAGNOSTICS"] == "1"
|
static let enabled = ProcessInfo.processInfo.environment["KYMO_DIAGNOSTICS"] == "1"
|
||||||
|
|
||||||
static func record(_ snapshot: MetricsSnapshot, event: String = "sample") {
|
static func recordTextPresentation(processes: Int, cells: Int) {
|
||||||
|
guard enabled else { return }
|
||||||
|
let line = "{\"event\":\"textPresentation\",\"processes\":\(processes),\"createdCells\":\(cells)}\n"
|
||||||
|
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
|
||||||
|
}
|
||||||
|
|
||||||
|
static func recordEnergy(_ snapshot: ProcessEnergySnapshot) {
|
||||||
|
guard enabled else { return }
|
||||||
|
let payload: [String: Any] = ["event": "energy", "recordedAt": Date().timeIntervalSince1970,
|
||||||
|
"state": String(describing: snapshot.state), "candidates": snapshot.candidates,
|
||||||
|
"readable": snapshot.readable, "measured": snapshot.measured,
|
||||||
|
"watts": snapshot.rows.map(\.watts), "intervals": snapshot.rows.map(\.seconds)]
|
||||||
|
guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else { return }
|
||||||
|
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
|
||||||
|
}
|
||||||
|
|
||||||
|
static func record(_ snapshot: MetricsSnapshot, event: String = "sample", hiddenHostAlive: Bool? = nil) {
|
||||||
guard enabled else { return }
|
guard enabled else { return }
|
||||||
var payload: [String: Any] = [
|
var payload: [String: Any] = [
|
||||||
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
|
"event": event, "timestamp": snapshot.date.timeIntervalSince1970,
|
||||||
@@ -14,6 +30,7 @@ nonisolated enum SamplingDiagnostics {
|
|||||||
"pid": ProcessInfo.processInfo.processIdentifier,
|
"pid": ProcessInfo.processInfo.processIdentifier,
|
||||||
"load": snapshot.load
|
"load": snapshot.load
|
||||||
]
|
]
|
||||||
|
payload["hiddenHostAlive"] = hiddenHostAlive
|
||||||
payload["cpu"] = snapshot.cpu?.usage
|
payload["cpu"] = snapshot.cpu?.usage
|
||||||
payload["cores"] = snapshot.cpu?.cores.count
|
payload["cores"] = snapshot.cpu?.cores.count
|
||||||
payload["cpuTemperature"] = snapshot.cpuTemperature
|
payload["cpuTemperature"] = snapshot.cpuTemperature
|
||||||
|
|||||||
@@ -4,11 +4,17 @@ import Foundation
|
|||||||
nonisolated struct SensorSchedule {
|
nonisolated struct SensorSchedule {
|
||||||
private(set) var deadline: TimeInterval = 0
|
private(set) var deadline: TimeInterval = 0
|
||||||
private var failures = 0
|
private var failures = 0
|
||||||
|
private let successInterval: TimeInterval
|
||||||
|
private let failureInterval: TimeInterval
|
||||||
|
init(successInterval: TimeInterval = 10, failureInterval: TimeInterval = 60) {
|
||||||
|
self.successInterval = successInterval
|
||||||
|
self.failureInterval = failureInterval
|
||||||
|
}
|
||||||
|
|
||||||
func isDue(at now: TimeInterval) -> Bool { now >= deadline }
|
func isDue(at now: TimeInterval) -> Bool { now >= deadline }
|
||||||
|
|
||||||
mutating func complete(available: Bool, at now: TimeInterval) {
|
mutating func complete(available: Bool, at now: TimeInterval, retryInterval: TimeInterval? = nil) {
|
||||||
failures = available ? 0 : min(failures + 1, 5)
|
failures = available ? 0 : min(failures + 1, 8)
|
||||||
deadline = now + (available ? 10 : min(600, 60 * pow(2, Double(failures - 1))))
|
deadline = now + (retryInterval ?? (available ? successInterval : min(600, failureInterval * pow(2, Double(failures - 1)))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// A separate observation scope: energy completion does not replace the resource snapshot.
|
||||||
|
struct EnergyProcessSection: View {
|
||||||
|
let metrics: MetricsStore
|
||||||
|
private var snapshot: ProcessEnergySnapshot? { metrics.energy }
|
||||||
|
private var rows: [ProcessEnergyUsage] { snapshot?.rows ?? [] }
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
HStack {
|
||||||
|
Text("energy.cpuProcesses").font(PanelStyle.section)
|
||||||
|
if snapshot?.state == .partial {
|
||||||
|
Text("energy.partial").font(.system(size: 8)).foregroundStyle(.secondary)
|
||||||
|
.help(Text("energy.coverage \(snapshot?.measured ?? 0) \(snapshot?.candidates ?? 0)"))
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
Text("energy.averagePower").foregroundStyle(.secondary)
|
||||||
|
}.font(PanelStyle.label)
|
||||||
|
if rows.isEmpty {
|
||||||
|
Text(statusKey).foregroundStyle(.secondary).font(PanelStyle.label)
|
||||||
|
} else {
|
||||||
|
ForEach(rows) { usage in
|
||||||
|
EnergyProcessListRow(usage: usage, maximum: rows.first?.watts ?? 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.help(Text("energy.scopeHelp"))
|
||||||
|
}
|
||||||
|
private var statusKey: LocalizedStringKey {
|
||||||
|
switch snapshot?.state {
|
||||||
|
case .unsupported: "energy.unsupported"
|
||||||
|
case .unavailable: "energy.unavailable"
|
||||||
|
default: "energy.waiting"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct EnergyProcessListRow: View {
|
||||||
|
let usage: ProcessEnergyUsage
|
||||||
|
let maximum: Double
|
||||||
|
private var progress: Double { maximum > 0 ? min(1, max(0, usage.watts / maximum)) : 0 }
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(spacing: 5) {
|
||||||
|
ProcessIcon(process: usage.process)
|
||||||
|
Text(verbatim: usage.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)
|
||||||
|
Text(verbatim: usage.formattedPower)
|
||||||
|
.foregroundStyle(Color("MetricCPU")).font(PanelStyle.value)
|
||||||
|
.monospacedDigit().frame(width: 57, alignment: .trailing)
|
||||||
|
}
|
||||||
|
.font(PanelStyle.label).frame(height: 16)
|
||||||
|
.help(Text("energy.window \(usage.seconds.formatted(.number.precision(.fractionLength(1))))"))
|
||||||
|
.accessibilityElement(children: .combine)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import SwiftUI
|
|||||||
import Observation
|
import Observation
|
||||||
|
|
||||||
@MainActor @Observable final class PanelPresentation {
|
@MainActor @Observable final class PanelPresentation {
|
||||||
|
fileprivate(set) var isOpen = false
|
||||||
var isPinned = false { didSet { onPinChange?(isPinned) } }
|
var isPinned = false { didSet { onPinChange?(isPinned) } }
|
||||||
@ObservationIgnored var onPinChange: ((Bool) -> Void)?
|
@ObservationIgnored var onPinChange: ((Bool) -> Void)?
|
||||||
}
|
}
|
||||||
@@ -11,10 +12,14 @@ import Observation
|
|||||||
@MainActor final class MenuPanelController: NSObject {
|
@MainActor final class MenuPanelController: NSObject {
|
||||||
let presentation = PanelPresentation()
|
let presentation = PanelPresentation()
|
||||||
let panel = MonitoringPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
let panel = MonitoringPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
||||||
|
#if DEBUG || KYMO_AUDIT
|
||||||
|
private(set) weak var lastHiddenContent: NSView?
|
||||||
|
#endif
|
||||||
private var statusItem: NSStatusItem?
|
private var statusItem: NSStatusItem?
|
||||||
private var localMouse: Any?
|
private var localMouse: Any?
|
||||||
private var globalMouse: Any?
|
private var globalMouse: Any?
|
||||||
private var tokens: [NSObjectProtocol] = []
|
private var tokens: [NSObjectProtocol] = []
|
||||||
|
private var visibilityObservation: NSKeyValueObservation?
|
||||||
private let content: (PanelPresentation) -> NSView
|
private let content: (PanelPresentation) -> NSView
|
||||||
private let visibility: (Bool) -> Void
|
private let visibility: (Bool) -> Void
|
||||||
private let menuTitle: (String) -> String
|
private let menuTitle: (String) -> String
|
||||||
@@ -52,6 +57,12 @@ import Observation
|
|||||||
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
|
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
|
||||||
MainActor.assumeIsolated { self?.place() }
|
MainActor.assumeIsolated { self?.place() }
|
||||||
})
|
})
|
||||||
|
visibilityObservation = panel.observe(\.isVisible, options: [.new]) { [weak self] _, _ in
|
||||||
|
Task { @MainActor [weak self] in self?.publishVisibility() }
|
||||||
|
}
|
||||||
|
tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.didChangeOcclusionStateNotification, object: panel, queue: .main) { [weak self] _ in
|
||||||
|
MainActor.assumeIsolated { self?.publishVisibility() }
|
||||||
|
})
|
||||||
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: NSApp, queue: .main) { [weak self] _ in
|
tokens.append(NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: NSApp, queue: .main) { [weak self] _ in
|
||||||
MainActor.assumeIsolated {
|
MainActor.assumeIsolated {
|
||||||
guard let self, !self.showingStatusMenu, !self.isOverStatusItem(NSEvent.mouseLocation) else { return }
|
guard let self, !self.showingStatusMenu, !self.isOverStatusItem(NSEvent.mouseLocation) else { return }
|
||||||
@@ -98,6 +109,7 @@ import Observation
|
|||||||
func show() {
|
func show() {
|
||||||
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
|
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
|
||||||
place()
|
place()
|
||||||
|
presentation.isOpen = true
|
||||||
panel.contentView = content(presentation)
|
panel.contentView = content(presentation)
|
||||||
panel.level = presentation.isPinned ? .floating : .normal
|
panel.level = presentation.isPinned ? .floating : .normal
|
||||||
panel.makeKeyAndOrderFront(nil)
|
panel.makeKeyAndOrderFront(nil)
|
||||||
@@ -105,12 +117,20 @@ import Observation
|
|||||||
// Opening the panel must not start editing the first text field.
|
// Opening the panel must not start editing the first text field.
|
||||||
// Explicit clicks and keyboard navigation can still focus its controls.
|
// Explicit clicks and keyboard navigation can still focus its controls.
|
||||||
panel.makeFirstResponder(panel)
|
panel.makeFirstResponder(panel)
|
||||||
visibility(true)
|
publishVisibility()
|
||||||
installMonitors()
|
installMonitors()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func publishVisibility() {
|
||||||
|
visibility(panel.isVisible && panel.occlusionState.contains(.visible))
|
||||||
|
}
|
||||||
|
|
||||||
func hide() {
|
func hide() {
|
||||||
|
presentation.isOpen = false
|
||||||
panel.orderOut(nil)
|
panel.orderOut(nil)
|
||||||
|
#if DEBUG || KYMO_AUDIT
|
||||||
|
if let content = panel.contentView { lastHiddenContent = content }
|
||||||
|
#endif
|
||||||
panel.contentView = nil
|
panel.contentView = nil
|
||||||
visibility(false)
|
visibility(false)
|
||||||
removeMonitors()
|
removeMonitors()
|
||||||
@@ -127,6 +147,7 @@ import Observation
|
|||||||
statusItem = nil
|
statusItem = nil
|
||||||
tokens.forEach(NotificationCenter.default.removeObserver)
|
tokens.forEach(NotificationCenter.default.removeObserver)
|
||||||
tokens.removeAll()
|
tokens.removeAll()
|
||||||
|
visibilityObservation = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
private func place() {
|
private func place() {
|
||||||
|
|||||||
@@ -52,20 +52,7 @@ extension MenuPanelView {
|
|||||||
}.font(PanelStyle.label)
|
}.font(PanelStyle.label)
|
||||||
.modifier(CardInset())
|
.modifier(CardInset())
|
||||||
}
|
}
|
||||||
.task(id: "\(publicIPRoute):\(metrics.isPaused)") {
|
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicIPAddress))
|
||||||
guard !metrics.isPaused, metrics.isPanelVisible else { return }
|
|
||||||
publicIPAddress = nil
|
|
||||||
guard snapshot.networkPath == .available else { return }
|
|
||||||
await PublicIPAddressService.shared.refreshContinuously(route: publicIPRoute) { address in
|
|
||||||
await MainActor.run {
|
|
||||||
guard !Task.isCancelled else { return }
|
|
||||||
publicIPAddress = address
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var publicIPRoute: String {
|
|
||||||
"\(snapshot.defaultNetworkInterface ?? ""):\(String(describing: snapshot.networkPath)):\(snapshot.network?.filter { $0.active }.map { $0.addresses.joined(separator: ",") }.joined(separator: ";") ?? "")"
|
|
||||||
}
|
}
|
||||||
func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View {
|
func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View {
|
||||||
HStack(spacing: 4) {
|
HStack(spacing: 4) {
|
||||||
|
|||||||
@@ -237,22 +237,7 @@ extension MenuPanelView {
|
|||||||
.frame(height: 32)
|
.frame(height: 32)
|
||||||
Spacer(minLength: 0)
|
Spacer(minLength: 0)
|
||||||
CardSeparator()
|
CardSeparator()
|
||||||
VStack(alignment: .leading, spacing: 4) {
|
EnergyProcessSection(metrics: metrics)
|
||||||
HStack {
|
|
||||||
Text("battery.highestEnergyProcess").font(PanelStyle.section)
|
|
||||||
Spacer()
|
|
||||||
Text("battery.cpuUsage").foregroundStyle(.secondary)
|
|
||||||
}
|
|
||||||
.font(PanelStyle.label)
|
|
||||||
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.
|
// Reserve the header and all three rows before process sampling completes.
|
||||||
.frame(height: 74, alignment: .top)
|
.frame(height: 74, alignment: .top)
|
||||||
.lineLimit(1)
|
.lineLimit(1)
|
||||||
@@ -261,36 +246,3 @@ extension MenuPanelView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct EnergyProcessListRow: View {
|
|
||||||
let process: ProcessMetrics
|
|
||||||
|
|
||||||
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) {
|
|
||||||
ProcessIcon(process: process)
|
|
||||||
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)
|
|
||||||
AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--")
|
|
||||||
.foregroundStyle(Color("MetricCPU")).font(PanelStyle.value)
|
|
||||||
.monospacedDigit().frame(width: 39, alignment: .trailing)
|
|
||||||
}
|
|
||||||
.font(PanelStyle.label)
|
|
||||||
.frame(height: 16)
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -54,8 +54,8 @@ struct MenuPanelView: View {
|
|||||||
} else {
|
} else {
|
||||||
resourceRows
|
resourceRows
|
||||||
}
|
}
|
||||||
if metrics.isPanelVisible && PanelResourceAudit.omitted != "processes" {
|
if presentation.isOpen && PanelResourceAudit.omitted != "processes" {
|
||||||
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
|
PanelProcessSection(metrics: metrics, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
.frame(minHeight: 170)
|
.frame(minHeight: 170)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -65,13 +65,11 @@ struct MenuPanelView: View {
|
|||||||
if panelSize != size { panelSize = size }
|
if panelSize != size { panelSize = size }
|
||||||
}.frame(width: 0, height: 0))
|
}.frame(width: 0, height: 0))
|
||||||
.onAppear {
|
.onAppear {
|
||||||
metrics.setPanelVisible(true)
|
|
||||||
reservedFanCount = snapshot.fans?.count ?? 0
|
reservedFanCount = snapshot.fans?.count ?? 0
|
||||||
}
|
}
|
||||||
.onChange(of: snapshot.fans?.count) { _, count in
|
.onChange(of: snapshot.fans?.count) { _, count in
|
||||||
reservedFanCount = max(reservedFanCount, count ?? 0)
|
reservedFanCount = max(reservedFanCount, count ?? 0)
|
||||||
}
|
}
|
||||||
.onDisappear { metrics.setPanelVisible(false) }
|
|
||||||
.onChange(of: snapshot.network?.map(\.identity)) { _, keys in
|
.onChange(of: snapshot.network?.map(\.identity)) { _, keys in
|
||||||
if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" }
|
if !selectedInterface.isEmpty && !(keys ?? []).contains(selectedInterface) { selectedInterface = "" }
|
||||||
}
|
}
|
||||||
@@ -215,3 +213,10 @@ private struct PanelControlButtonBody<Content: View>: View {
|
|||||||
.onHover { isHovered = $0 }
|
.onHover { isHovered = $0 }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Keep process publications out of the resource-card observation scope.
|
||||||
|
private struct PanelProcessSection: View {
|
||||||
|
let metrics: MetricsStore
|
||||||
|
let wide: Bool
|
||||||
|
var body: some View { ProcessTableView(snapshot: metrics.processSnapshot, wide: wide) }
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// Shared by the dashboard and the text-only audit so network work is comparable.
|
||||||
|
struct PanelPublicIPRefresh: ViewModifier {
|
||||||
|
let metrics: MetricsStore
|
||||||
|
@Binding var address: String?
|
||||||
|
private var route: String {
|
||||||
|
let snapshot = metrics.snapshot
|
||||||
|
return "\(snapshot.defaultNetworkInterface ?? ""):\(String(describing: snapshot.networkPath)):\(snapshot.network?.filter { $0.active }.map { $0.addresses.joined(separator: ",") }.joined(separator: ";") ?? "")"
|
||||||
|
}
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
content.task(id: "\(route):\(metrics.isPaused):\(metrics.isSystemSleeping):\(metrics.isDisplaySleeping):\(metrics.isPanelVisible)") {
|
||||||
|
guard !metrics.isPaused, !metrics.isSystemSleeping, !metrics.isDisplaySleeping, metrics.isPanelVisible else { return }
|
||||||
|
address = nil
|
||||||
|
guard metrics.snapshot.networkPath == .available else { return }
|
||||||
|
await PublicIPAddressService.shared.refreshContinuously(route: route) { value in
|
||||||
|
await MainActor.run {
|
||||||
|
guard !Task.isCancelled else { return }
|
||||||
|
address = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,13 +2,26 @@ import AppKit
|
|||||||
|
|
||||||
/// Explicit local measurement only. Never schedules work during normal launches.
|
/// Explicit local measurement only. Never schedules work during normal launches.
|
||||||
@MainActor enum PanelResourceAudit {
|
@MainActor enum PanelResourceAudit {
|
||||||
|
#if DEBUG || KYMO_AUDIT
|
||||||
static let enabled = ProcessInfo.processInfo.environment["KYMO_RESOURCE_AUDIT"] == "1"
|
static let enabled = ProcessInfo.processInfo.environment["KYMO_RESOURCE_AUDIT"] == "1"
|
||||||
static let omitted = enabled ? ProcessInfo.processInfo.environment["KYMO_AUDIT_OMIT"] ?? "" : ""
|
static let omitted = enabled ? ProcessInfo.processInfo.environment["KYMO_AUDIT_OMIT"] ?? "" : ""
|
||||||
|
|
||||||
static func run(controller: MenuPanelController, metrics: MetricsStore) {
|
static func run(controller: MenuPanelController, metrics: MetricsStore) {
|
||||||
guard enabled else { return }
|
guard enabled else { return }
|
||||||
Task { @MainActor in
|
Task { @MainActor in
|
||||||
@MainActor func mark(_ event: String) { SamplingDiagnostics.record(metrics.snapshot, event: "audit." + event) }
|
controller.panel.animationBehavior = .none
|
||||||
|
if ProcessInfo.processInfo.environment["KYMO_XPC_AUDIT"] == "1" {
|
||||||
|
await checkRequestCompletion()
|
||||||
|
SamplingDiagnostics.record(metrics.snapshot, event: "audit.xpcChecksPassed")
|
||||||
|
controller.shutdown()
|
||||||
|
NSApp.terminate(nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
@MainActor func mark(_ event: String) {
|
||||||
|
var report = metrics.snapshot
|
||||||
|
report.processes = metrics.processSnapshot
|
||||||
|
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil)
|
||||||
|
}
|
||||||
func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) }
|
func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) }
|
||||||
// Pin the test window so unrelated focus changes cannot invalidate a measurement.
|
// Pin the test window so unrelated focus changes cannot invalidate a measurement.
|
||||||
controller.presentation.isPinned = true
|
controller.presentation.isPinned = true
|
||||||
@@ -36,4 +49,43 @@ import AppKit
|
|||||||
NSApp.terminate(nil)
|
NSApp.terminate(nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/// Uses real connection lifecycle but injects local callbacks; peer auth is tested separately by RPCs.
|
||||||
|
private static func checkRequestCompletion() async {
|
||||||
|
for _ in 0..<20 {
|
||||||
|
let result: Int? = await ServiceRequest.perform(timeout: 0.2) { _, finish in
|
||||||
|
finish(1); finish(2)
|
||||||
|
}
|
||||||
|
precondition(result == 1, "A reply must finish exactly once")
|
||||||
|
}
|
||||||
|
for _ in 0..<20 {
|
||||||
|
let result: Int? = await ServiceRequest.perform(timeout: 0.2) { _, finish in
|
||||||
|
DispatchQueue.concurrentPerform(iterations: 2) { finish($0) }
|
||||||
|
}
|
||||||
|
precondition(result == 0 || result == 1)
|
||||||
|
}
|
||||||
|
let timeoutStart = ContinuousClock.now
|
||||||
|
let timedOut: Int? = await ServiceRequest.perform(timeout: 0.1) { _, _ in }
|
||||||
|
let timeoutElapsed = timeoutStart.duration(to: .now)
|
||||||
|
precondition(timedOut == nil && timeoutElapsed >= .milliseconds(80) && timeoutElapsed < .seconds(2))
|
||||||
|
let cancellationStart = ContinuousClock.now
|
||||||
|
let (started, signal) = AsyncStream<Void>.makeStream()
|
||||||
|
let cancelled = Task<Int?, Never> {
|
||||||
|
await ServiceRequest.perform(timeout: 10) { _, _ in signal.yield(()); signal.finish() }
|
||||||
|
}
|
||||||
|
for await _ in started { break }
|
||||||
|
cancelled.cancel()
|
||||||
|
let cancelledResult = await cancelled.value
|
||||||
|
precondition(cancelledResult == nil && cancellationStart.duration(to: .now) < .seconds(2))
|
||||||
|
let early = Task<Int?, Never> { await ServiceRequest.perform(timeout: 10) { _, _ in } }
|
||||||
|
early.cancel()
|
||||||
|
let earlyResult = await early.value
|
||||||
|
precondition(earlyResult == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
#else
|
||||||
|
static let enabled = false
|
||||||
|
static let omitted = ""
|
||||||
|
static func run(controller: MenuPanelController, metrics: MetricsStore) {}
|
||||||
|
#endif
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
#if DEBUG || KYMO_AUDIT
|
||||||
|
/// An opt-in comparison frontend. Sampling, history, IPC and public-IP policy remain enabled.
|
||||||
|
struct TextMonitoringAuditView: View {
|
||||||
|
let metrics: MetricsStore
|
||||||
|
let appearance: AppearancePreferences
|
||||||
|
@State private var publicAddress: String?
|
||||||
|
var body: some View {
|
||||||
|
TextReportHost(snapshot: metrics.snapshot, processes: metrics.processSnapshot, energy: metrics.energy,
|
||||||
|
historyPoints: metrics.history.samples.count, publicAddress: publicAddress, appearance: appearance.appearance)
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicAddress))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct TextReportHost: NSViewRepresentable {
|
||||||
|
let snapshot: MetricsSnapshot
|
||||||
|
let processes: ProcessSnapshot?
|
||||||
|
let energy: ProcessEnergySnapshot?
|
||||||
|
let historyPoints: Int
|
||||||
|
let publicAddress: String?
|
||||||
|
let appearance: AppAppearance
|
||||||
|
func makeCoordinator() -> Coordinator { Coordinator() }
|
||||||
|
func makeNSView(context: Context) -> ReportScrollView {
|
||||||
|
let scroll = ReportScrollView()
|
||||||
|
scroll.hasVerticalScroller = true
|
||||||
|
scroll.hasHorizontalScroller = true
|
||||||
|
scroll.autohidesScrollers = false
|
||||||
|
scroll.scrollerStyle = .legacy
|
||||||
|
let table = NSTableView(frame: NSRect(x: 0, y: 0, width: 3200, height: 800))
|
||||||
|
table.headerView = nil
|
||||||
|
table.style = .plain
|
||||||
|
table.rowHeight = 15
|
||||||
|
table.intercellSpacing = .zero
|
||||||
|
table.selectionHighlightStyle = .none
|
||||||
|
table.backgroundColor = .windowBackgroundColor
|
||||||
|
table.columnAutoresizingStyle = .noColumnAutoresizing
|
||||||
|
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("text"))
|
||||||
|
column.width = 3200
|
||||||
|
table.addTableColumn(column)
|
||||||
|
table.delegate = context.coordinator
|
||||||
|
table.dataSource = context.coordinator
|
||||||
|
scroll.documentView = table
|
||||||
|
return scroll
|
||||||
|
}
|
||||||
|
func updateNSView(_ scroll: ReportScrollView, context: Context) {
|
||||||
|
scroll.choice = appearance
|
||||||
|
guard let table = scroll.documentView as? NSTableView else { return }
|
||||||
|
let c = context.coordinator
|
||||||
|
if c.processDate != processes?.date {
|
||||||
|
c.processDate = processes?.date
|
||||||
|
c.rows = ProcessTableProjection.rows(processes?.rows ?? [], query: "", sorting: [ProcessSort(key: .cpu)], order: [])
|
||||||
|
}
|
||||||
|
let heading = Self.resourceText(snapshot) + "\nHistory points retained: \(historyPoints)\nPublic IP: \(publicAddress ?? "--")\n\n" + Self.energyText(energy)
|
||||||
|
+ "\nProcesses: \(processes?.readable ?? 0)/\(processes?.enumerated ?? 0), failed=\(processes?.failed ?? false)\nPID\tCPU %\tRSS bytes\tThreads\tRestricted\tName\tPath"
|
||||||
|
c.lines = heading.components(separatedBy: "\n")
|
||||||
|
let origin = scroll.contentView.bounds.origin
|
||||||
|
let oldCount = table.numberOfRows
|
||||||
|
let newCount = c.lines.count + c.rows.count
|
||||||
|
if newCount != oldCount {
|
||||||
|
table.beginUpdates()
|
||||||
|
if newCount > oldCount { table.insertRows(at: IndexSet(integersIn: oldCount..<newCount), withAnimation: []) }
|
||||||
|
else { table.removeRows(at: IndexSet(integersIn: newCount..<oldCount), withAnimation: []) }
|
||||||
|
table.endUpdates()
|
||||||
|
}
|
||||||
|
let visible = table.rows(in: table.visibleRect)
|
||||||
|
if visible.location != NSNotFound, visible.length > 0 {
|
||||||
|
for row in visible.location..<min(newCount, visible.location + visible.length) {
|
||||||
|
if let cell = table.view(atColumn: 0, row: row, makeIfNecessary: false) as? NSTableCellView {
|
||||||
|
c.update(cell, row: row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scroll.contentView.scroll(to: origin)
|
||||||
|
scroll.reflectScrolledClipView(scroll.contentView)
|
||||||
|
SamplingDiagnostics.recordTextPresentation(processes: c.rows.count, cells: c.createdCells)
|
||||||
|
}
|
||||||
|
/// Fixed-height native text rows format only visible records. All sampled rows remain scrollable.
|
||||||
|
final class Coordinator: NSObject, NSTableViewDataSource, NSTableViewDelegate {
|
||||||
|
var processDate: Date?
|
||||||
|
var rows: [ProcessMetrics] = []
|
||||||
|
var lines: [String] = []
|
||||||
|
var createdCells = 0
|
||||||
|
func numberOfRows(in tableView: NSTableView) -> Int { lines.count + rows.count }
|
||||||
|
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
|
||||||
|
guard row >= 0, row < lines.count + rows.count else { return nil }
|
||||||
|
let key = NSUserInterfaceItemIdentifier("text.cell")
|
||||||
|
let cell: NSTableCellView
|
||||||
|
if let reused = tableView.makeView(withIdentifier: key, owner: nil) as? NSTableCellView { cell = reused }
|
||||||
|
else {
|
||||||
|
cell = NSTableCellView()
|
||||||
|
cell.identifier = key
|
||||||
|
let field = NSTextField(labelWithString: "")
|
||||||
|
field.font = .monospacedSystemFont(ofSize: 11, weight: .regular)
|
||||||
|
field.lineBreakMode = .byClipping
|
||||||
|
field.translatesAutoresizingMaskIntoConstraints = false
|
||||||
|
cell.addSubview(field)
|
||||||
|
cell.textField = field
|
||||||
|
NSLayoutConstraint.activate([
|
||||||
|
field.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 8),
|
||||||
|
field.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -4),
|
||||||
|
field.topAnchor.constraint(equalTo: cell.topAnchor), field.bottomAnchor.constraint(equalTo: cell.bottomAnchor)
|
||||||
|
])
|
||||||
|
createdCells += 1
|
||||||
|
}
|
||||||
|
update(cell, row: row)
|
||||||
|
return cell
|
||||||
|
}
|
||||||
|
func update(_ cell: NSTableCellView, row: Int) {
|
||||||
|
guard row >= 0, row < lines.count + rows.count else { return }
|
||||||
|
let value = row < lines.count ? lines[row] : TextReportHost.processLine(rows[row - lines.count])
|
||||||
|
if cell.textField?.stringValue != value { cell.textField?.stringValue = value }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final class ReportScrollView: NSScrollView {
|
||||||
|
var choice = AppAppearance.system { didSet { apply() } }
|
||||||
|
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); apply() }
|
||||||
|
private func apply() {
|
||||||
|
let target = choice.windowAppearance
|
||||||
|
if window?.appearance?.name != target?.name { window?.appearance = target }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static func number(_ value: Double?) -> String { value.map { String(format: "%.3f", $0) } ?? "--" }
|
||||||
|
private static func bytes(_ value: UInt64?) -> String { value.map(String.init) ?? "--" }
|
||||||
|
private static func resourceText(_ s: MetricsSnapshot) -> String {
|
||||||
|
var lines = ["Kymo — plain text comparison (no charts, icons or animation)", "Resource timestamp: \(s.date.timeIntervalSince1970)"]
|
||||||
|
lines += ["CPU total/user/system fraction: \(number(s.cpu?.usage)) / \(number(s.cpu?.user)) / \(number(s.cpu?.system))",
|
||||||
|
"CPU cores: \(s.cpu?.cores.map { number($0) }.joined(separator: " ") ?? "--")",
|
||||||
|
"CPU/GPU temperature °C: \(number(s.cpuTemperature)) / \(number(s.gpuTemperature))",
|
||||||
|
"Fans RPM: \(s.fans?.map { "\($0.id)=\(number($0.rpm))" }.joined(separator: " ") ?? "--")",
|
||||||
|
"GPU usage/renderer/tiler/cores: \(number(s.gpu?.usage)) / \(number(s.gpu?.renderer)) / \(number(s.gpu?.tiler)) / \(s.gpu?.coreCount.map(String.init) ?? "--")",
|
||||||
|
"GPU in-use/allocated bytes: \(bytes(s.gpu?.inUseMemory)) / \(bytes(s.gpu?.allocatedMemory))",
|
||||||
|
"Memory total/used/available/cached/wired/compressed/swap bytes: \(bytes(s.memory?.total)) / \(bytes(s.memory?.used)) / \(bytes(s.memory?.available)) / \(bytes(s.memory?.cached)) / \(bytes(s.memory?.wired)) / \(bytes(s.memory?.compressed)) / \(bytes(s.memory?.swapUsed))",
|
||||||
|
"Memory pressure: \(s.memory?.pressure.map(String.init) ?? "--")",
|
||||||
|
"Disk total/available bytes: \(bytes(s.disk?.total)) / \(bytes(s.disk?.available))",
|
||||||
|
"Disk IO read/write B/s: \(number(s.diskIO?.read)) / \(number(s.diskIO?.written))",
|
||||||
|
"SMART remaining/hour: \(number(s.diskHealth?.remainingLife)) / \(bytes(s.diskHealth?.powerOnHours))",
|
||||||
|
"Battery charge/health/power W/cycles: \(number(s.battery?.charge)) / \(number(s.battery?.health)) / \(number(s.battery?.power)) / \(s.battery?.cycles.map(String.init) ?? "--")",
|
||||||
|
"Battery charging/external/minutes/state: \(String(describing: s.battery?.charging)) / \(String(describing: s.battery?.externalPower)) / \(s.battery?.minutesRemaining.map(String.init) ?? "--") / \(s.batteryState)",
|
||||||
|
"Uptime/load: \(number(s.uptime)) / \(s.load.map { number($0) }.joined(separator: " "))",
|
||||||
|
"Network path/default interface: \(String(describing: s.networkPath)) / \(s.defaultNetworkInterface ?? "--")"]
|
||||||
|
for i in s.network ?? [] { lines.append("\(i.name) active=\(i.active) received/sent=\(i.received)/\(i.sent) B, down/up=\(number(i.download))/\(number(i.upload)) B/s, addresses=\(i.addresses.joined(separator: ","))") }
|
||||||
|
for v in s.volumes ?? [] { lines.append("Volume \(v.name) \(v.path): total/available \(v.capacity.total)/\(v.capacity.available) B") }
|
||||||
|
return lines.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
private static func energyText(_ energy: ProcessEnergySnapshot?) -> String {
|
||||||
|
guard let energy else { return "CPU energy: waiting\n" }
|
||||||
|
return "CPU energy: \(energy.state), measured/readable/enumerated=\(energy.measured)/\(energy.readable)/\(energy.candidates)\n" + energy.rows.map { "\($0.id.pid) \($0.process.name): \($0.formattedPower), interval \(number($0.seconds)) s" }.joined(separator: "\n") + "\n"
|
||||||
|
}
|
||||||
|
private static func processLine(_ process: ProcessMetrics) -> String {
|
||||||
|
"\(process.id.pid)\t\(number(process.cpu.map { $0 * 100 }))\t\(bytes(process.residentBytes))\t\(process.threads.map(String.init) ?? "--")\t\(process.restricted)\t\(process.name)\t\(process.path ?? "--")"
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
#else
|
||||||
|
/// The diagnostic renderer is excluded from distribution builds.
|
||||||
|
struct TextMonitoringAuditView: View {
|
||||||
|
let metrics: MetricsStore
|
||||||
|
let appearance: AppearancePreferences
|
||||||
|
var body: some View { EmptyView() }
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -748,6 +748,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"battery.cpuUsage" : {
|
"battery.cpuUsage" : {
|
||||||
|
"extractionState" : "stale",
|
||||||
"localizations" : {
|
"localizations" : {
|
||||||
"en" : {
|
"en" : {
|
||||||
"stringUnit" : {
|
"stringUnit" : {
|
||||||
@@ -836,29 +837,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"battery.energyProxyHelp" : {
|
|
||||||
"extractionState" : "stale",
|
|
||||||
"localizations" : {
|
|
||||||
"en" : {
|
|
||||||
"stringUnit" : {
|
|
||||||
"state" : "translated",
|
|
||||||
"value" : "Ranked by current process CPU utilization; this is not the system energy impact score."
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"zh-Hans" : {
|
|
||||||
"stringUnit" : {
|
|
||||||
"state" : "translated",
|
|
||||||
"value" : "按当前进程 CPU 利用率排序,不代表系统能耗影响评分。"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"zh-Hant" : {
|
|
||||||
"stringUnit" : {
|
|
||||||
"state" : "translated",
|
|
||||||
"value" : "依目前處理程序 CPU 使用率排序,不代表系統能耗影響評分。"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"battery.external" : {
|
"battery.external" : {
|
||||||
"extractionState" : "manual",
|
"extractionState" : "manual",
|
||||||
"localizations" : {
|
"localizations" : {
|
||||||
@@ -905,6 +883,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"battery.highestEnergyProcess" : {
|
"battery.highestEnergyProcess" : {
|
||||||
|
"extractionState" : "stale",
|
||||||
"localizations" : {
|
"localizations" : {
|
||||||
"en" : {
|
"en" : {
|
||||||
"stringUnit" : {
|
"stringUnit" : {
|
||||||
@@ -1577,6 +1556,213 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"energy.averagePower" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Average power"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "平均功率"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "平均功率"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"energy.coverage %lld %lld" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Measured intervals / enumerated processes: %1$lld / %2$lld"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "有效区间进程数 / 枚举数:%1$lld / %2$lld"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "有效區間程序數 / 列舉數:%1$lld / %2$lld"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"energy.cpuProcesses" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Energy processes (CPU)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "耗电进程(CPU)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "耗電程序(CPU)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"energy.partial" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Partial"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "部分可测"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "部分可測"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"energy.scopeHelp" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Ranked by system CPU energy counter deltas among measurable processes. Not total app/device power; GPU, display, network and helper processes are not aggregated. Bars are relative to this list."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "在可测进程中按系统 CPU 归属能量差值排序,不代表应用或整机完整功耗;不聚合 GPU、屏幕、网络或辅助进程。条形图仅为列表内相对值。"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "在可測程序中依系統 CPU 歸屬能量差值排序,不代表應用程式或整機完整功耗;不彙總 GPU、螢幕、網路或輔助程序。長條僅為清單內相對值。"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"energy.unavailable" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Energy counter unavailable"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "能量计数不可用或受限"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "能量計數不可用或受限"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"energy.unsupported" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Energy counter unsupported"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "系统不支持能量计数"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "系統不支援能量計數"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"energy.waiting" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Waiting for energy interval…"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "等待能量区间采样…"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "等待能量區間取樣…"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"energy.window %@" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Measured interval: %@ s"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "实际统计窗口:%@ 秒"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "實際統計區間:%@ 秒"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"gpu.allocatedMemory" : {
|
"gpu.allocatedMemory" : {
|
||||||
"localizations" : {
|
"localizations" : {
|
||||||
"en" : {
|
"en" : {
|
||||||
@@ -3870,6 +4056,29 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"sampling.backgroundEnabled" : {
|
||||||
|
"extractionState" : "manual",
|
||||||
|
"localizations" : {
|
||||||
|
"en" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "Record trends while hidden"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hans" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "隐藏时记录趋势"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zh-Hant" : {
|
||||||
|
"stringUnit" : {
|
||||||
|
"state" : "translated",
|
||||||
|
"value" : "隱藏時記錄趨勢"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"sampling.backgroundHelp" : {
|
"sampling.backgroundHelp" : {
|
||||||
"extractionState" : "manual",
|
"extractionState" : "manual",
|
||||||
"localizations" : {
|
"localizations" : {
|
||||||
@@ -4166,29 +4375,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
|
||||||
"sampling.backgroundEnabled" : {
|
|
||||||
"extractionState" : "manual",
|
|
||||||
"localizations" : {
|
|
||||||
"en" : {
|
|
||||||
"stringUnit" : {
|
|
||||||
"state" : "translated",
|
|
||||||
"value" : "Record trends while hidden"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"zh-Hans" : {
|
|
||||||
"stringUnit" : {
|
|
||||||
"state" : "translated",
|
|
||||||
"value" : "隐藏时记录趋势"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"zh-Hant" : {
|
|
||||||
"stringUnit" : {
|
|
||||||
"state" : "translated",
|
|
||||||
"value" : "隱藏時記錄趨勢"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"version" : "1.0"
|
"version" : "1.0"
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ extension AppAppearance {
|
|||||||
struct AppearanceStyle: ViewModifier {
|
struct AppearanceStyle: ViewModifier {
|
||||||
let preferences: AppearancePreferences
|
let preferences: AppearancePreferences
|
||||||
var refreshContentOnChange = false
|
var refreshContentOnChange = false
|
||||||
@State private var system = SystemAppearanceObserver()
|
@State private var system: SystemAppearanceObserver?
|
||||||
private var resolved: AppAppearance { preferences.appearance.resolved(systemIsDark: system.isDark) }
|
private var resolved: AppAppearance { preferences.appearance.resolved(systemIsDark: system?.isDark ?? SystemAppearanceObserver.isDark(globalDomain: UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain))) }
|
||||||
private var scheme: ColorScheme { resolved == .dark ? .dark : .light }
|
private var scheme: ColorScheme { resolved == .dark ? .dark : .light }
|
||||||
func body(content: Content) -> some View {
|
func body(content: Content) -> some View {
|
||||||
content
|
content
|
||||||
@@ -31,6 +31,7 @@ struct AppearanceStyle: ViewModifier {
|
|||||||
.preferredColorScheme(scheme)
|
.preferredColorScheme(scheme)
|
||||||
.environment(\.colorScheme, scheme)
|
.environment(\.colorScheme, scheme)
|
||||||
.tint(.blue)
|
.tint(.blue)
|
||||||
|
.onAppear { if system == nil { system = SystemAppearanceObserver() } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,30 @@ import SwiftUI
|
|||||||
try? await Task.sleep(for: .milliseconds(150))
|
try? await Task.sleep(for: .milliseconds(150))
|
||||||
precondition(controller.panel.isVisible && visible)
|
precondition(controller.panel.isVisible && visible)
|
||||||
precondition(controller.panel.firstResponder === controller.panel, "Opening must not focus the interval editor")
|
precondition(controller.panel.firstResponder === controller.panel, "Opening must not focus the interval editor")
|
||||||
|
controller.presentation.isPinned = true
|
||||||
|
let cover = NSWindow(contentRect: controller.panel.frame.insetBy(dx: -8, dy: -8),
|
||||||
|
styleMask: [.borderless], backing: .buffered, defer: false)
|
||||||
|
cover.isReleasedWhenClosed = false
|
||||||
|
cover.isOpaque = true
|
||||||
|
cover.backgroundColor = .black
|
||||||
|
cover.level = NSWindow.Level(rawValue: controller.panel.level.rawValue + 1)
|
||||||
|
cover.orderFrontRegardless()
|
||||||
|
let coveredDeadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||||
|
while visible && ContinuousClock.now < coveredDeadline { try? await Task.sleep(for: .milliseconds(20)) }
|
||||||
|
precondition(controller.panel.isVisible && controller.presentation.isOpen && !visible,
|
||||||
|
"A fully covered pinned panel must lose demand without closing its content")
|
||||||
|
cover.orderOut(nil); cover.close()
|
||||||
|
let uncoveredDeadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||||
|
while !visible && ContinuousClock.now < uncoveredDeadline { try? await Task.sleep(for: .milliseconds(20)) }
|
||||||
|
precondition(visible, "Uncovering must restore demand")
|
||||||
|
controller.presentation.isPinned = false
|
||||||
|
controller.panel.orderOut(nil)
|
||||||
|
let hiddenDeadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||||
|
while visible && ContinuousClock.now < hiddenDeadline { try? await Task.sleep(for: .milliseconds(20)) }
|
||||||
|
precondition(!visible && controller.presentation.isOpen, "OS visibility loss must stop demand without closing content/state")
|
||||||
|
controller.panel.makeKeyAndOrderFront(nil)
|
||||||
|
try? await Task.sleep(for: .milliseconds(150))
|
||||||
|
precondition(visible, "OS visibility restoration must restore sampling demand")
|
||||||
precondition(controller.panel.canBecomeKey && !controller.panel.canBecomeMain)
|
precondition(controller.panel.canBecomeKey && !controller.panel.canBecomeMain)
|
||||||
precondition(controller.statusMenu().items.first?.title == "hide")
|
precondition(controller.statusMenu().items.first?.title == "hide")
|
||||||
controller.togglePanel()
|
controller.togglePanel()
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
@main struct ProcessEnergyChecks {
|
||||||
|
static let id = ProcessIdentity(pid: 42, seconds: 100, microseconds: 2)
|
||||||
|
static func reading(_ energy: UInt64?, at time: Double, id: ProcessIdentity = id,
|
||||||
|
birth: UInt64 = 1, status: EnergyReadStatus = .available) -> ProcessEnergyReading {
|
||||||
|
ProcessEnergyReading(id: id, birth: birth, uptime: time, nanojoules: energy, status: status)
|
||||||
|
}
|
||||||
|
static func main() {
|
||||||
|
let wire = ProcessEnergyReply(token: UUID(), capability: .verifiedCPU, readings: [reading(UInt64.max - 1, at: 10)])
|
||||||
|
let decoded = try! JSONDecoder().decode(ProcessEnergyReply.self, from: JSONEncoder().encode(wire))
|
||||||
|
precondition(decoded.readings[0].nanojoules == UInt64.max - 1 && decoded.token == wire.token)
|
||||||
|
let old = reading(UInt64.max - 2_000_000_000, at: 10)
|
||||||
|
let now = reading(UInt64.max - 1_000_000_000, at: 15)
|
||||||
|
precondition(ProcessEnergyMonitor.watts(current: now, previous: nil) == nil)
|
||||||
|
precondition(ProcessEnergyMonitor.watts(current: now, previous: old)?.0 == 0.2)
|
||||||
|
precondition(ProcessEnergyMonitor.watts(current: old, previous: now) == nil)
|
||||||
|
precondition(ProcessEnergyMonitor.watts(current: reading(5, at: 15), previous: reading(5, at: 10))?.0 == 0)
|
||||||
|
for invalid in [reading(nil, at: 15, status: .denied), reading(10, at: 10), reading(10, at: .nan),
|
||||||
|
reading(10, at: 50), reading(10, at: 15, birth: 2),
|
||||||
|
reading(10, at: 15, id: ProcessIdentity(pid: 42, seconds: 101, microseconds: 2))] {
|
||||||
|
precondition(ProcessEnergyMonitor.watts(current: invalid, previous: reading(5, at: 10)) == nil)
|
||||||
|
}
|
||||||
|
func row(_ id: ProcessIdentity, _ cpu: Double) -> ProcessMetrics {
|
||||||
|
ProcessMetrics(id: id, name: "fixture", path: nil, cpu: cpu, residentBytes: nil, threads: nil, restricted: false)
|
||||||
|
}
|
||||||
|
let id2 = ProcessIdentity(pid: 43, seconds: 100, microseconds: 2)
|
||||||
|
let processes = ProcessSnapshot(date: Date(), enumerated: 3, readable: 2, rows: [row(id, 5), row(id2, 0.01)], failed: false)
|
||||||
|
var monitor = ProcessEnergyMonitor()
|
||||||
|
let first = monitor.update(processes: processes, readings: [reading(0, at: 10), reading(0, at: 10, id: id2)], capability: .verifiedCPU)
|
||||||
|
precondition(first.state == .waiting && first.rows.isEmpty)
|
||||||
|
let measured = monitor.update(processes: processes, readings: [reading(1_000_000_000, at: 15), reading(5_000_000_000, at: 15, id: id2)], capability: .verifiedCPU)
|
||||||
|
precondition(measured.state == .partial && measured.rows.first?.id == id2 && measured.measured == 2)
|
||||||
|
precondition(measured.rows.first?.watts == 1)
|
||||||
|
_ = monitor.update(processes: processes, readings: [], capability: .unavailable)
|
||||||
|
let recovered = monitor.update(processes: processes, readings: [reading(6_000_000_000, at: 20, id: id2)], capability: .verifiedCPU)
|
||||||
|
precondition(recovered.rows.isEmpty, "Failure must not bridge a missing interval")
|
||||||
|
let unsupported = monitor.update(processes: processes, readings: [], capability: .unsupported)
|
||||||
|
precondition(unsupported.state == .unsupported && unsupported.rows.isEmpty)
|
||||||
|
let unverified = monitor.update(processes: processes, readings: [reading(0, at: 25)], capability: .unverified)
|
||||||
|
precondition(unverified.rows.isEmpty && unverified.readable == 0)
|
||||||
|
print("PASS: exact large-integer deltas, first/zero/reset/reuse/gap/error/time boundaries, energy-vs-CPU ranking, partial coverage and no CPU fallback")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import Foundation
|
||||||
|
import Darwin
|
||||||
|
|
||||||
|
@main struct ProcessEnergyReaderChecks {
|
||||||
|
static func main() throws {
|
||||||
|
var bsd = proc_bsdinfo()
|
||||||
|
precondition(proc_pidinfo(getpid(), PROC_PIDTBSDINFO, 0, &bsd, Int32(MemoryLayout.size(ofValue: bsd))) > 0)
|
||||||
|
let id = ProcessIdentity(pid: getpid(), seconds: bsd.pbi_start_tvsec, microseconds: bsd.pbi_start_tvusec)
|
||||||
|
func read(_ ids: [ProcessIdentity]) throws -> ProcessEnergyReply {
|
||||||
|
let request = ProcessEnergyRequest(token: UUID(), identities: ids)
|
||||||
|
let data = try JSONEncoder().encode(request)
|
||||||
|
let reply = try JSONDecoder().decode(ProcessEnergyReply.self, from: ProcessEnergyReader.read(data)!)
|
||||||
|
precondition(reply.token == request.token && reply.readings.count == ids.count)
|
||||||
|
return reply
|
||||||
|
}
|
||||||
|
usleep(10_000)
|
||||||
|
let first = try read([id]).readings[0]
|
||||||
|
#if arch(arm64)
|
||||||
|
let start = ProcessInfo.processInfo.systemUptime
|
||||||
|
var work: UInt64 = 1
|
||||||
|
while ProcessInfo.processInfo.systemUptime - start < 0.15 { work = work &* 6364136223846793005 &+ 1 }
|
||||||
|
usleep(10_000) // Let scheduler accounting include the completed CPU slice.
|
||||||
|
let second = try read([id])
|
||||||
|
precondition(second.capability == .verifiedCPU && second.readings[0].nanojoules! > first.nanojoules!)
|
||||||
|
precondition(second.readings[0].birth == first.birth && second.readings[0].uptime > first.uptime)
|
||||||
|
print("PASS: live same-UID CPU energy counter advances under controlled CPU work", work)
|
||||||
|
#else
|
||||||
|
precondition(first.status == .unsupported)
|
||||||
|
#endif
|
||||||
|
let wrong = ProcessIdentity(pid: getpid(), seconds: id.seconds + 1, microseconds: id.microseconds)
|
||||||
|
let mismatched = try read([wrong])
|
||||||
|
#if arch(arm64)
|
||||||
|
precondition(mismatched.readings[0].status == .identityChanged)
|
||||||
|
let denied = try read([ProcessIdentity(pid: 1, seconds: 1, microseconds: 0)])
|
||||||
|
precondition(denied.readings[0].status == .denied || denied.readings[0].status == .gone)
|
||||||
|
#endif
|
||||||
|
precondition(ProcessEnergyReader.read(Data(repeating: 0, count: ProcessEnergyRequest.byteLimit + 1)) == nil)
|
||||||
|
let duplicates = try JSONEncoder().encode(ProcessEnergyRequest(token: UUID(), identities: [id, id]))
|
||||||
|
precondition(ProcessEnergyReader.read(duplicates) == nil)
|
||||||
|
precondition(ProcessEnergyReader.read(Data("not json".utf8)) == nil)
|
||||||
|
let tooMany = try JSONEncoder().encode(ProcessEnergyRequest(token: UUID(), identities: (1...257).map {
|
||||||
|
ProcessIdentity(pid: Int32($0), seconds: 1, microseconds: 0)
|
||||||
|
}))
|
||||||
|
precondition(ProcessEnergyReader.read(tooMany) == nil)
|
||||||
|
print("PASS: nonce/identity, permission, duplicate and byte/decode boundaries")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
|
import Observation
|
||||||
|
|
||||||
@main struct SamplingIntervalChecks {
|
@main struct SamplingIntervalChecks {
|
||||||
@MainActor static func main() async throws {
|
@MainActor static func main() async throws {
|
||||||
@@ -26,15 +27,15 @@ import Foundation
|
|||||||
preferences.backgroundMilliseconds = 1_800_000
|
preferences.backgroundMilliseconds = 1_800_000
|
||||||
let store = MetricsStore(sampling: preferences)
|
let store = MetricsStore(sampling: preferences)
|
||||||
store.setPanelVisible(true)
|
store.setPanelVisible(true)
|
||||||
try await until { store.snapshot.processes != nil }
|
try await until { store.processSnapshot != nil }
|
||||||
precondition(store.effectiveMilliseconds == 500)
|
precondition(store.effectiveMilliseconds == 500)
|
||||||
store.setPanelVisible(false)
|
store.setPanelVisible(false)
|
||||||
precondition(store.snapshot.processes == nil && store.effectiveMilliseconds == 1_800_000)
|
precondition(store.processSnapshot == nil && store.effectiveMilliseconds == 1_800_000)
|
||||||
try await Task.sleep(for: .milliseconds(200))
|
try await Task.sleep(for: .milliseconds(200))
|
||||||
let hiddenDate = store.snapshot.date
|
let hiddenDate = store.snapshot.date
|
||||||
preferences.panelMilliseconds = 700
|
preferences.panelMilliseconds = 700
|
||||||
try await Task.sleep(for: .milliseconds(650))
|
try await Task.sleep(for: .milliseconds(650))
|
||||||
precondition(store.snapshot.date == hiddenDate && store.snapshot.processes == nil)
|
precondition(store.snapshot.date == hiddenDate && store.processSnapshot == nil)
|
||||||
preferences.backgroundMilliseconds = 500
|
preferences.backgroundMilliseconds = 500
|
||||||
try await until { store.snapshot.date > hiddenDate }
|
try await until { store.snapshot.date > hiddenDate }
|
||||||
precondition(store.history.samples.last?.breakBefore == false)
|
precondition(store.history.samples.last?.breakBefore == false)
|
||||||
@@ -50,7 +51,7 @@ import Foundation
|
|||||||
try await Task.sleep(for: .milliseconds(650))
|
try await Task.sleep(for: .milliseconds(650))
|
||||||
precondition(store.isPaused && store.snapshot.date == paused)
|
precondition(store.isPaused && store.snapshot.date == paused)
|
||||||
store.togglePause()
|
store.togglePause()
|
||||||
try await until { store.snapshot.date > paused && store.snapshot.processes != nil }
|
try await until { store.snapshot.date > paused && store.processSnapshot != nil }
|
||||||
precondition(store.effectiveMilliseconds == 1_800_000)
|
precondition(store.effectiveMilliseconds == 1_800_000)
|
||||||
precondition(store.history.samples.last?.breakBefore == true)
|
precondition(store.history.samples.last?.breakBefore == true)
|
||||||
store.togglePause()
|
store.togglePause()
|
||||||
@@ -75,11 +76,14 @@ import Foundation
|
|||||||
let changingStore = MetricsStore(sampling: changing, sampler: SystemSampler(processRead: { slowRead.read(&$0) }))
|
let changingStore = MetricsStore(sampling: changing, sampler: SystemSampler(processRead: { slowRead.read(&$0) }))
|
||||||
changingStore.setPanelVisible(true)
|
changingStore.setPanelVisible(true)
|
||||||
try await until { !changingStore.history.samples.isEmpty }
|
try await until { !changingStore.history.samples.isEmpty }
|
||||||
precondition(changingStore.snapshot.processes == nil)
|
precondition(changingStore.processSnapshot == nil)
|
||||||
let countBeforeChange = changingStore.history.samples.count
|
let countBeforeChange = changingStore.history.samples.count
|
||||||
|
let resourceChanges = PublicationCount()
|
||||||
|
withObservationTracking { _ = changingStore.snapshot } onChange: { resourceChanges.increment() }
|
||||||
changing.panelMilliseconds = 1_800_000
|
changing.panelMilliseconds = 1_800_000
|
||||||
try await until { changingStore.snapshot.processes != nil }
|
try await until { changingStore.processSnapshot != nil }
|
||||||
precondition(changingStore.history.samples.count == countBeforeChange, "Rate changes must preserve in-flight process delivery without an extra quick sample")
|
precondition(changingStore.history.samples.count == countBeforeChange, "Rate changes must preserve in-flight process delivery without an extra quick sample")
|
||||||
|
precondition(resourceChanges.value == 0, "Process completion must not invalidate resource snapshot observers")
|
||||||
changingStore.togglePause()
|
changingStore.togglePause()
|
||||||
let dormantPreferences = SamplingPreferences(defaults: defaults)
|
let dormantPreferences = SamplingPreferences(defaults: defaults)
|
||||||
dormantPreferences.backgroundEnabled = false
|
dormantPreferences.backgroundEnabled = false
|
||||||
@@ -89,11 +93,11 @@ import Foundation
|
|||||||
precondition(dormant.history.samples.isEmpty && dormant.snapshot.memory == nil,
|
precondition(dormant.history.samples.isEmpty && dormant.snapshot.memory == nil,
|
||||||
"Hidden without a consumer must not perform even an initial full sample")
|
"Hidden without a consumer must not perform even an initial full sample")
|
||||||
dormant.setPanelVisible(true)
|
dormant.setPanelVisible(true)
|
||||||
try await until { dormant.snapshot.processes != nil }
|
try await until { dormant.processSnapshot != nil }
|
||||||
dormant.setPanelVisible(false)
|
dormant.setPanelVisible(false)
|
||||||
let hiddenCount = dormant.history.samples.count
|
let hiddenCount = dormant.history.samples.count
|
||||||
try await Task.sleep(for: .milliseconds(650))
|
try await Task.sleep(for: .milliseconds(650))
|
||||||
precondition(dormant.history.samples.count == hiddenCount && dormant.snapshot.processes == nil)
|
precondition(dormant.history.samples.count == hiddenCount && dormant.processSnapshot == nil)
|
||||||
dormantPreferences.backgroundEnabled = true
|
dormantPreferences.backgroundEnabled = true
|
||||||
dormantPreferences.backgroundMilliseconds = 500
|
dormantPreferences.backgroundMilliseconds = 500
|
||||||
try await until { dormant.history.samples.count > hiddenCount }
|
try await until { dormant.history.samples.count > hiddenCount }
|
||||||
@@ -104,6 +108,38 @@ import Foundation
|
|||||||
dormant.setPanelVisible(true)
|
dormant.setPanelVisible(true)
|
||||||
try await until { dormant.history.samples.count > disabledCount }
|
try await until { dormant.history.samples.count > disabledCount }
|
||||||
precondition(dormant.history.samples.last?.breakBefore == true)
|
precondition(dormant.history.samples.last?.breakBefore == true)
|
||||||
|
dormant.setDisplaySleeping(true)
|
||||||
|
let darkCount = dormant.history.samples.count
|
||||||
|
try await Task.sleep(for: .milliseconds(650))
|
||||||
|
precondition(dormant.history.samples.count == darkCount && dormant.processSnapshot == nil && dormant.energy == nil)
|
||||||
|
dormantPreferences.backgroundEnabled = true
|
||||||
|
dormantPreferences.backgroundMilliseconds = 500
|
||||||
|
try await until { dormant.history.samples.count > darkCount }
|
||||||
|
precondition(dormant.processSnapshot == nil && dormant.energy == nil,
|
||||||
|
"Explicit background trends may run with the display off, but process/energy scans must stay stopped")
|
||||||
|
dormantPreferences.backgroundEnabled = false
|
||||||
|
dormant.setDisplaySleeping(false)
|
||||||
|
try await until { dormant.processSnapshot != nil }
|
||||||
|
dormant.setSystemSleeping(true)
|
||||||
|
let sleepingCount = dormant.history.samples.count
|
||||||
|
try await Task.sleep(for: .milliseconds(650))
|
||||||
|
precondition(dormant.isSystemSleeping && dormant.history.samples.count == sleepingCount && dormant.energy == nil)
|
||||||
|
dormant.setSystemSleeping(false)
|
||||||
|
try await until { dormant.history.samples.count > sleepingCount }
|
||||||
|
precondition(dormant.history.samples.last?.breakBefore == true && dormant.snapshot.cpu == nil)
|
||||||
|
let staleProbe = DelayedProcessRead(delay: 0.01)
|
||||||
|
let stale = SystemSampler(processRead: { staleProbe.read(&$0) })
|
||||||
|
await stale.setProcessVisible(false, revision: 2)
|
||||||
|
_ = await stale.sample(includeProcesses: true, includeSlowMetrics: false, demandRevision: 1)
|
||||||
|
try await Task.sleep(for: .milliseconds(100))
|
||||||
|
precondition(staleProbe.count == 0, "A stale demand must not start any process work")
|
||||||
|
await stale.setProcessVisible(true, revision: 3)
|
||||||
|
await stale.setProcessVisible(false, revision: 2)
|
||||||
|
_ = await stale.sample(includeSlowMetrics: false, demandRevision: 3)
|
||||||
|
let liveDeadline = ContinuousClock.now.advanced(by: .seconds(2))
|
||||||
|
while staleProbe.count == 0 && ContinuousClock.now < liveDeadline { try await Task.sleep(for: .milliseconds(20)) }
|
||||||
|
precondition(staleProbe.count == 1, "A stale stop must not undo the newer visible demand")
|
||||||
|
await stale.setProcessVisible(false, revision: 4)
|
||||||
dormant.togglePause()
|
dormant.togglePause()
|
||||||
print("PASS: defaults, 100ms quantization/clamping, independent persistence, invalid defaults, active/background wake, pause precedence, slow-interval initial processes and history boundary")
|
print("PASS: defaults, 100ms quantization/clamping, independent persistence, invalid defaults, active/background wake, pause precedence, slow-interval initial processes and history boundary")
|
||||||
}
|
}
|
||||||
@@ -135,3 +171,10 @@ private final class DelayedProcessRead: @unchecked Sendable {
|
|||||||
return monitor.sample()
|
return monitor.sample()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private final class PublicationCount: @unchecked Sendable {
|
||||||
|
private let lock = NSLock()
|
||||||
|
private var count = 0
|
||||||
|
var value: Int { lock.lock(); defer { lock.unlock() }; return count }
|
||||||
|
func increment() { lock.lock(); count += 1; lock.unlock() }
|
||||||
|
}
|
||||||
|
|||||||
@@ -25,6 +25,15 @@ import Foundation
|
|||||||
precondition(gpu.deadline == now + 10)
|
precondition(gpu.deadline == now + 10)
|
||||||
gpu.complete(available: false, at: now + 10)
|
gpu.complete(available: false, at: now + 10)
|
||||||
precondition(gpu.deadline == now + 70)
|
precondition(gpu.deadline == now + 70)
|
||||||
|
var energy = SensorSchedule(successInterval: 5, failureInterval: 30)
|
||||||
|
energy.complete(available: true, at: 0)
|
||||||
|
precondition(energy.deadline == 5)
|
||||||
|
energy.complete(available: false, at: 5)
|
||||||
|
precondition(energy.deadline == 35)
|
||||||
|
energy.complete(available: false, at: 35)
|
||||||
|
precondition(energy.deadline == 95)
|
||||||
|
energy.complete(available: false, at: 95, retryInterval: 600)
|
||||||
|
precondition(energy.deadline == 695)
|
||||||
print("PASS: independent sensor cadences, exponential failure backoff, cap and recovery")
|
print("PASS: independent sensor cadences, exponential failure backoff, cap and recovery")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,14 +55,14 @@ import Foundation
|
|||||||
let store = MetricsStore()
|
let store = MetricsStore()
|
||||||
store.setPanelVisible(true)
|
store.setPanelVisible(true)
|
||||||
for _ in 0..<40 {
|
for _ in 0..<40 {
|
||||||
if store.snapshot.processes != nil { break }
|
if store.processSnapshot != nil { break }
|
||||||
try? await Task.sleep(for: .milliseconds(200))
|
try? await Task.sleep(for: .milliseconds(200))
|
||||||
}
|
}
|
||||||
precondition(store.snapshot.processes?.readable ?? 0 > 0)
|
precondition(store.processSnapshot?.readable ?? 0 > 0)
|
||||||
store.setPanelVisible(false)
|
store.setPanelVisible(false)
|
||||||
precondition(store.snapshot.processes == nil)
|
precondition(store.processSnapshot == nil)
|
||||||
try? await Task.sleep(for: .milliseconds(2200))
|
try? await Task.sleep(for: .milliseconds(2200))
|
||||||
precondition(store.snapshot.processes == nil)
|
precondition(store.processSnapshot == nil)
|
||||||
store.togglePause()
|
store.togglePause()
|
||||||
print("PASS: process CPU boundaries/live baseline, GPU range, VPN total exclusion, bounded interface history, visibility reset")
|
print("PASS: process CPU boundaries/live baseline, GPU range, VPN total exclusion, bounded interface history, visibility reset")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ CHECKS = {name: list(CORE) for name in (
|
|||||||
"SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks",
|
"SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks",
|
||||||
"GPUStatisticsChecks", "StageCChecks", "MachPortChecks")}
|
"GPUStatisticsChecks", "StageCChecks", "MachPortChecks")}
|
||||||
CHECKS.update({
|
CHECKS.update({
|
||||||
|
"ProcessEnergyChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Core/Models/ProcessEnergy.swift", "kymo/Core/Monitors/ProcessEnergyMonitor.swift"],
|
||||||
|
"ProcessEnergyReaderChecks": ["kymo/Core/Models/ProcessMetrics.swift", "kymo/Core/Models/ProcessEnergy.swift", "SMARTService/ProcessEnergyReader.swift"],
|
||||||
"BoundedProcessChecks": ["kymo/Core/Services/BoundedProcess.swift"],
|
"BoundedProcessChecks": ["kymo/Core/Services/BoundedProcess.swift"],
|
||||||
"SensorScheduleChecks": ["kymo/Core/Services/SensorSchedule.swift"],
|
"SensorScheduleChecks": ["kymo/Core/Services/SensorSchedule.swift"],
|
||||||
"TrendScrollChecks": CORE + ["kymo/UI/Charts/TrendScroll.swift"],
|
"TrendScrollChecks": CORE + ["kymo/UI/Charts/TrendScroll.swift"],
|
||||||
|
|||||||
Reference in New Issue
Block a user