From def3b1e130b466fe1efd427f1508325ab053b35b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A0=81=E5=86=9C=E9=98=BF=E6=A5=A0?= Date: Tue, 3 Nov 2026 23:19:52 +0800 Subject: [PATCH] =?UTF-8?q?perf(efficiency):=20=E8=90=BD=E5=AE=9E=E9=A6=96?= =?UTF-8?q?=E6=89=B9=E9=87=87=E6=A0=B7=E5=87=8F=E8=B4=9F=E4=B8=8E=E5=8F=91?= =?UTF-8?q?=E8=A1=8C=E5=8C=85=E7=98=A6=E8=BA=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SMARTService/main.swift | 24 +++-- docs/README.md | 4 +- docs/architecture.md | 18 ++-- docs/development.md | 2 +- docs/efficiency-first-batch.md | 95 +++++++++++++++++++ docs/extreme-efficiency-plan.md | 13 ++- docs/monitoring.md | 8 +- docs/testing.md | 6 ++ kymo.xcodeproj/project.pbxproj | 3 + kymo/App/kymoApp.swift | 17 ++-- .../BrandLogo.imageset/BrandLogo.svg | 2 +- kymo/Core/Monitors/ProcessMonitor.swift | 17 +++- kymo/Core/Monitors/SystemSampler.swift | 34 ++++--- .../CPUTemperatureServiceClient.swift | 83 ++++------------ kymo/Core/Services/MetricsStore.swift | 16 +++- kymo/Core/Services/SMARTServiceClient.swift | 41 +------- kymo/Core/Services/SMARTServiceProtocol.swift | 5 +- kymo/Core/Services/SamplingDiagnostics.swift | 3 + kymo/Core/Services/SamplingPreferences.swift | 22 ++++- kymo/Core/Services/SensorSchedule.swift | 14 +++ kymo/Core/Services/ServiceRequest.swift | 68 +++++++++++++ kymo/Features/MenuBar/CPUCoreGrid.swift | 2 - kymo/Features/MenuBar/GPUStatisticsView.swift | 3 - .../MenuBar/MenuPanelView+Network.swift | 3 +- .../MenuBar/MenuPanelView+ResourceCards.swift | 2 - kymo/Features/MenuBar/MenuPanelView.swift | 24 +++-- .../Features/MenuBar/PanelResourceAudit.swift | 39 ++++++++ kymo/Features/MenuBar/ProcessIcon.swift | 1 + .../Settings/AppearanceSettingsView.swift | 3 +- kymo/Resources/Localizable.xcstrings | 31 +++++- kymo/UI/Charts/PanelTrendChart.swift | 37 +------- kymo/UI/Components/AnimatedMetricText.swift | 5 +- kymo/UI/Components/FanSpeedIndicator.swift | 44 +-------- kymo/UI/Components/MetricRingGauge.swift | 2 - kymo/UI/Components/PanelStyle.swift | 2 - kymoTests/FanChecks.swift | 17 +--- kymoTests/SamplingChecks.swift | 1 + kymoTests/SamplingIntervalChecks.swift | 32 ++++++- kymoTests/SensorScheduleChecks.swift | 30 ++++++ tools/check.py | 1 + 40 files changed, 483 insertions(+), 291 deletions(-) create mode 100644 docs/efficiency-first-batch.md create mode 100644 kymo/Core/Services/SensorSchedule.swift create mode 100644 kymo/Core/Services/ServiceRequest.swift create mode 100644 kymo/Features/MenuBar/PanelResourceAudit.swift create mode 100644 kymoTests/SensorScheduleChecks.swift diff --git a/SMARTService/main.swift b/SMARTService/main.swift index 0ff75be..8db1fb6 100644 --- a/SMARTService/main.swift +++ b/SMARTService/main.swift @@ -14,14 +14,14 @@ private actor CPUTemperatureReader { final class SMARTService: NSObject, SMARTServiceProtocol { private let temperatureReader = CPUTemperatureReader() - func readGPUTemperature(withReply reply: @escaping (NSNumber?) -> Void) { - Task { reply(await temperatureReader.sampleGPU().map(NSNumber.init(value:))) } - } - - func readFanSpeeds(withReply reply: @escaping ([NSNumber]?) -> Void) { + func readSensors(cpu: Bool, gpu: Bool, fans: Bool, + withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void) { Task { - // Negative sentinel preserves an unavailable fan's position; never presented as RPM. - reply(await temperatureReader.sampleFans()?.map { NSNumber(value: $0 ?? -1) }) + let cpuValue = cpu ? await temperatureReader.sample() : nil + let gpuValue = gpu ? await temperatureReader.sampleGPU() : nil + let fanValues = fans ? await temperatureReader.sampleFans() : nil + reply(cpuValue.map(NSNumber.init(value:)), gpuValue.map(NSNumber.init(value:)), + fanValues?.map { NSNumber(value: $0 ?? -1) }) } } @@ -32,14 +32,12 @@ final class SMARTService: NSObject, SMARTServiceProtocol { } } - func readCPUTemperature(withReply reply: @escaping (NSNumber?) -> Void) { - Task { - reply(await temperatureReader.sample().map(NSNumber.init(value:))) - } - } + } final class ServiceDelegate: NSObject, NSXPCListenerDelegate { + // Actor-isolated discovery survives short client connections. + private let service = SMARTService() // Bind the peer to the containing app's actual designated signature, including ad-hoc builds. private let requirement: String? = { let host = Bundle.main.bundleURL.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() @@ -50,7 +48,7 @@ final class ServiceDelegate: NSObject, NSXPCListenerDelegate { guard connection.effectiveUserIdentifier == getuid(), let requirement else { return false } connection.setCodeSigningRequirement(requirement) connection.exportedInterface = NSXPCInterface(with: SMARTServiceProtocol.self) - connection.exportedObject = SMARTService() + connection.exportedObject = service connection.resume() return true } diff --git a/docs/README.md b/docs/README.md index e8a6c68..20abf36 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,7 +8,9 @@ | [监控指标](monitoring.md) | 数据来源、计算方式、缓存周期与降级行为 | | [开发指南](development.md) | 工程配置、构建运行、本地化、诊断入口 | | [测试与验证](testing.md) | 独立检查程序、执行方式和人工验收边界 | -| [极致轻量化与进程能耗方案](extreme-efficiency-plan.md) | 待实施:性能预算、逻辑浪费审查、真实能量列表、包体积收敛及分阶段验收 | +| [极致轻量化与进程能耗方案](extreme-efficiency-plan.md) | 实施中:性能预算、逻辑浪费审查、真实能量列表、包体积收敛及分阶段验收 | + +首批实施证据见[轻量化实施记录](efficiency-first-batch.md);其中包体积已收敛,内存和能耗列表仍在实施。 2026-11-03 依据当前源码重新整理;同日补充极致轻量化与进程能耗实施方案。此前清理的旧阶段计划、设计概念图和路线图可通过 Git 查询。主题文档描述当前实现,方案中的目标不代表已实现,也不以代码已实现代替运行验收。 diff --git a/docs/architecture.md b/docs/architecture.md index 1d251a4..29d2eb1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -25,7 +25,7 @@ `MenuPanelController` 拥有模板品牌状态项和无边框、可成为 key 的非激活 `MonitoringPanel`。左键切换面板;右键菜单提供打开 / 隐藏、设置和退出。窗口按状态项所在屏幕可见区域定位,水平居中、顶部预留 16pt;最大内容尺寸 1240 × 820pt,并按屏幕缩小。卡片随宽度采用 1 / 2 / 3 列,资源区空间不足时滚动,进程区保留最小高度。 -固定按钮切换普通 / floating 层级。未固定时外部交互或应用失活可收起,固定时仍可通过状态项或显式关闭收起。进程表的 Esc 依次处理搜索、选中和搜索焦点,随后关闭窗口。隐藏面板时释放内容视图并停止监听外部鼠标事件;后台采样继续。 +固定按钮切换普通 / floating 层级。未固定时外部交互或应用失活可收起,固定时仍可通过状态项或显式关闭收起。进程表的 Esc 依次处理搜索、选中和搜索焦点,随后关闭窗口。隐藏面板时释放内容视图并停止监听外部鼠标事件;仅显式启用后台趋势时保留常规采样。 设置窗口打开时切换 regular 模式并处理焦点恢复,关闭时由 `SettingsWindowLifecycle` 恢复 accessory 模式。关闭最后一个窗口不会退出应用。应用退出时关闭状态项、释放窗口引用及保持唤醒断言。 @@ -42,11 +42,11 @@ SMARTService(XPC)──→ 温度 / 风扇 / SMART 客户端 ──→ 慢任务缓存 ``` -`MetricsStore` 是 MainActor 上的可观察状态,启动后持续运行采样 Task。可见面板使用前台间隔,隐藏时使用后台间隔;切换可见性立即重新调度,修改当前间隔则按上次发布时间安排下一次采样。每轮采样完成后等待配置时长,因此配置值不是严格的墙钟定时周期。 +`MetricsStore` 是 MainActor 上的可观察状态。新配置默认隐藏时不启动采样 Task,展开使用前台间隔;显式启用后台趋势时,隐藏使用后台间隔(新配置 30 秒)。旧配置中存在合法后台间隔且没有显式开关时保留启用状态与间隔,显式关闭优先。无后台需求时隐藏停止采样,重开重置速率基线并标记历史断点。周期以单调时钟按每轮开始时间安排,不补跑错过的批次;间隔修改按上次发布时间调整下一轮。 -`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 秒(包含失败结果),每轮复用一个路径缓冲;枚举失败清空缓存,末次身份复核保留。进程退出提示以原始成功快照中的完整身份为准,搜索过滤和枚举失败不作为退出证据。 暂停取消采样发布、停用进程更新,保留当前快照和历史;已启动慢读取可能自行结束。恢复时重置 CPU / 网络 / IO 基线,历史标记断点。全局及每接口历史各最多 60 点,接口移除时清理其历史;实际覆盖时长由采样间隔决定。图表按真实时间和缺失值处理间断。GPU 平均统计仅累计有效且连续的时间区间。 @@ -54,12 +54,18 @@ SMARTService(XPC)──→ 温度 / 风扇 / SMART 客户端 ──→ 慢 主应用启用 App Sandbox,并声明网络客户端权限以访问公网地址 HTTPS 服务;嵌入的 `SMARTService.xpc` 未启用 App Sandbox,启用 Hardened Runtime。它是按需启动的只读辅助服务,不是 root 守护进程,也不执行 SMC 写操作。 -客户端按包内服务的实际指定签名设置连接要求;服务端要求同 UID,并按所在主应用的实际指定签名校验调用方。温度 / 风扇请求超时 2 秒,SMART 请求超时 15 秒;中断、错误、超时与正常响应统一通过一次性 continuation 完成并关闭连接。 +客户端按包内服务的实际指定签名设置连接要求;服务端要求同 UID,并按所在主应用的实际指定签名校验调用方。温度 / 风扇请求超时 2 秒,SMART 请求超时 15 秒;中断、错误、超时与正常响应统一通过一次性 continuation 完成并关闭连接,完成或取消立即取消超时 DispatchSource;请求支持 Task 取消,包括取消先于安装 continuation 的竞态。包内服务指定签名在客户端进程内只读取一次;每条连接仍设置验证要求。 -公网 IP 由 `PublicIPAddressService` 在面板网络任务中访问外部 HTTPS 服务,和本地接口采样分开。任务可见时持续刷新:成功缓存 600 秒,失败 30 秒后重试,超时 5 秒;有效期使用单调时间。路由键变化或面板隐藏取消旧任务的请求及等待,取消结果不缓存、不发布。保持唤醒通过两个进程级 IOPM 断言阻止用户空闲息屏与系统空闲睡眠,开关不持久化,失败时释放已取得断言,关闭或退出时释放。 +CPU / GPU / 风扇合并为一次只读 XPC 请求,按到期类别选择读取;服务进程共享 actor 隔离的传感器发现缓存。各类别成功后至少 10 秒再读,失败独立按 60 / 120 / 240 / 480 / 600 秒退避,其他类别成功不重置失败退避。服务重启后重新发现;不声称缓存跨服务进程退出保留。 + +公网 IP 由 `PublicIPAddressService` 在面板网络任务中访问外部 HTTPS 服务,和本地接口采样分开。任务可见时持续刷新:成功缓存 600 秒,失败 30 秒后重试,超时 5 秒;有效期使用单调时间。路由键变化、暂停或面板隐藏取消旧任务的请求及等待,取消结果不缓存、不发布。保持唤醒通过两个进程级 IOPM 断言阻止用户空闲息屏与系统空闲睡眠,开关不持久化,失败时释放已取得断言,关闭或退出时释放。 ## 状态与资源 外观、语言和双采样间隔写入 UserDefaults。图钉、暂停、保持唤醒和进程表交互状态不作为持久化偏好。`AppLanguageScope` 将语言环境注入 AppKit 承载的 SwiftUI 内容,并处理即时刷新;原生菜单文案通过 `AppLocalization` 读取;编号风扇等 SwiftUI 文案保留为带参数的 `Text`,由当前应用语言环境解析。 面板和资源卡片使用颜色资产中的不透明背景,顶部操作组使用玻璃效果;不再以全窗口液态玻璃概念图作为实现依据。品牌图标与颜色以 Assets 为运行时来源。 + +资源显示默认采用静态数字、曲线和进度条;风扇不创建 TimelineView。移除曲线追加过渡任务,保持原有缺失值、断点和悬浮语义。此措施不代表面板内存预算已通过;剩余峰值见效率实施记录。 + +`PanelResourceAudit` 仅在 `KYMO_RESOURCE_AUDIT=1` 时驱动真实面板测试生命周期,App 只装配调用。正常启动不创建测试任务;该入口不是鼠标 / AX 交互验证。诊断日志仍需 `KYMO_DIAGNOSTICS=1` 显式开启。 diff --git a/docs/development.md b/docs/development.md index 413b142..5d1688d 100644 --- a/docs/development.md +++ b/docs/development.md @@ -21,7 +21,7 @@ xcodebuild -project kymo.xcodeproj -scheme kymo -configuration Debug build - 采样调度与慢缓存:`MetricsStore.swift`、`SystemSampler.swift`。 - 设置:`AppearanceSettingsView.swift`、`SettingsWindowLifecycle.swift`;当前只有通用 / 关于两页。 -正常启动不显示 Dock 图标,点击菜单栏模板品牌图标打开面板。面板顶部修改可见时刷新频率,通用设置修改后台刷新频率。不要沿用旧 MenuBarExtra 或独立 Dashboard 的假设。 +正常启动不显示 Dock 图标,点击菜单栏模板品牌图标打开面板。面板顶部修改可见时刷新频率,通用设置显式启用后台趋势并修改其刷新频率(新配置默认不在隐藏时采样)。不要沿用旧 MenuBarExtra 或独立 Dashboard 的假设。 颜色和品牌图标修改 `kymo/Assets.xcassets`,当前运行资源不依赖 `docs/` 中的设计图片或生成脚本。外观仅系统 / 浅色 / 深色,没有强调色自选设置。 diff --git a/docs/efficiency-first-batch.md b/docs/efficiency-first-batch.md new file mode 100644 index 0000000..344475f --- /dev/null +++ b/docs/efficiency-first-batch.md @@ -0,0 +1,95 @@ +# 极致轻量化:首批实施记录 + +日期:2026-11-03。起点:`935701f`。本页记录首批代码与实测,不是 P0–P5 全部验收报告。 + +## 已实施 + +- 默认隐藏无消费者时不创建常规采样任务;设置增加后台趋势开关,新配置关闭、启用后默认 30 秒。已有合法自定义后台间隔保留原值和启用状态,显式开关优先。关闭后台趋势后重开重置速率基线、标记历史断点;不会补零。 +- 常规周期按单调时钟以轮次开始时间安排,不补跑错过的批次。隐藏后台趋势不启动温度、风扇、卷、SMART、电池健康慢读取;已在途的慢报告仍可能完成。 +- CPU / GPU / 风扇按到期类别合并为一条 XPC 请求,服务进程共享 actor 隔离的发现缓存。健康类别 10 秒;失败类别独立按 60、120、240、480、600 秒退避,其他类别成功不重置退避。服务进程退出后仍需重新发现,尚未实现持久连接或完整能力分类。 +- 两个客户端共用一次性请求生命周期,响应 / 错误 / 中断 / 超时 / 取消都关闭连接并取消 DispatchSource 超时源;客户端指定签名仅在进程内读取一次,每条连接仍要求对端验证,服务仍检查调用方 UID 与签名。取消竞态代码已实现,专门的传输故障注入回归仍待补齐。 +- 暂停纳入公网任务身份,取消请求和等待;不改变用户显式的保持唤醒开关。完整出口身份规范化、遮挡及睡眠需求调度仍未实施。 +- 默认去掉数字滚动、曲线追加、进度变化动效和风扇 TimelineView。图表直接绘制真实帧,保留断点、缺失值与悬浮;不再为每次追加建立过渡任务。 +- 进程路径按完整启动身份、命令名缓存 30 秒(含失败结果);每轮复用一个路径缓冲,成功枚举后清理离开者。保留末次枚举身份复核;枚举失败清空缓存。命令名不变的原地 exec 最多延迟 30 秒更新路径,不能声称实时路径事件订阅。 +- Release 按 [Apple 构建设置](https://developer.apple.com/documentation/xcode/build-settings-reference)启用各 Target 部署后符号剥离(各自在签名前执行);dSYM 留包外。复制阶段不再重复 strip 已签名 XPC。保留默认运行优化与 WMO,没有采用未经运行成本对照的 `-Osize`。 +- BrandLogo SVG 默认尺寸从 1024pt 改为实际设置页使用的 88pt,保留 1024 viewBox、全部矢量路径与 preserves-vector-representation。AppIcon、菜单栏标识、三语和辅助功能保留。 + +## P0 根因线索与隔离结果 + +同机、arm64 Release、脱离调试器、前台 2 秒。测试通过显式入口驱动真实 NSPanel,固定后展开 30 秒、隐藏 30 秒;不能当成鼠标 / 键盘事件自动化。后台默认禁用的优化包与旧包后台 5 秒的行为差异单列,不能据此直接做 CPU / 功耗归因。测试期间还运行过编译和回归检查,不是整机功耗受控环境。 + +| 对照 | 主进程 phys_footprint / 发现 | 边界 | +| --- | --- | --- | +| 本轮未优化 Release + 测量入口 | 首次记录到峰值 375.2 MiB;关闭后约 208 MiB | 新复现,不是此前用户 Debug 截图;首次关闭后中止了该副本,未跑满三轮 | +| 禁用进程图标 + MallocStackLogging | 堆约 142.8 MB,其中 CGGlyphBuilderLockBitmaps 约 93.9 MB、CGGlyphBitmapCreate 约 8.2 MB | 栈记录明显增加足迹,不能与关闭栈记录的数字直接计算收益 | +| 该探针分配调用树 | GlyphBuilder → render_glyphs → RenderBox Layer.make_cgimage / render → RBInterpolatedDisplayListContents → SwiftUI CGDrawingLayer | 最大 non-object 已追到绘制调用链;没有证据证明全是业务泄漏,尚未追到所有触发组件 | +| 仅取消数字滚动过渡 | 第一轮关闭 30 秒约 67.4 MiB;展开峰值仍超 200 MiB | 数字过渡是已隔离的放大因素;不是全部根因 | +| 再取消风扇旋转 | 第一轮关闭 10 秒约 71.8 MiB;首次展开仍超 200 MiB | 本轮没有证明风扇是主要内存来源;移除连续绘制的节能价值需另测 | +| 不创建进程表(旧绘制逻辑) | 首开 1 秒约 211.7 MiB | 不支持把全部峰值归咎 Table;图标 / Table 仍需有界缓存和实际行数分析 | +| 不绘制资源卡片(首批代码) | 首次峰值约 181.4 MiB;打开 30 秒约 61.6 MiB | 仅隔离实验,未删功能交付 | +| 不绘制页头(首批代码) | 首次峰值约 194.8 MiB | 单独去掉页头也未消除问题 | +| 纯 Text 容器 | 约 20–26 MiB,首开峰值约 25.9 MiB | 证明完整内容路径仍有显著成本;不是正式软件达标数据 | +| 取消整窗 clipShape | 首次峰值约 208.1 MiB,第二次约 223.4 MiB | 没有明显改善,未采用,保留圆角裁剪 | + +阶段性结论:过渡绘制与字形位图是已取得调用栈的重点;单独图标、Table、页头、卡片或根裁剪都不能解释全部增长。首批不是“已解决内存暴涨”。继续需要完整绘制调用次数、存活字形 / 宿主引用、局部静态 AppKit 对照与按域发布试验,不默认全面重写 SwiftUI。 + +## 发行包 + +本机签名、arm64、Release build,文件逻辑大小(十进制 B),没有公证 / DMG: + +| 产物 / 对照 | 大小 | +| --- | ---: | +| 本轮基线(含测量入口) | 5,122,880 B | +| 首批逻辑与静态显示,未开启发行剥离 | 5,041,982 B | +| 剥离 + `-Osize` 试验,原资源 | 3,037,166 B | +| 仅剥离、保留默认优化,原资源 | 3,123,854 B | +| 仅剥离、保留默认优化、修正品牌资源 | 1,882,766 B | +| 同格式 ZIP(ditto,keepParent / sequesterRsrc) | 1,005,772 B | + +最后一项 .app 已同时低于 4 MB 门槛与 3 MB 极致目标;只是本机产物,不等于完整性能与发行流程验收。ZIP 低于 1.5 MB 极致目标。`-Osize` 相对单纯剥离只再减少约 87 KB,本轮未采用,避免没有运行成本证据的取舍。 + +assetutil 确认 BrandLogo 原有 1024 / 2048 px 两份位图分别约 335,335 / 927,818 B,修正后 88 / 176 px 约 5,374 / 16,702 B,仍含约 870 B 矢量表示。实际从两份编译包分别渲染 88pt Retina 图像,视觉核对标志、渐变、边缘正常。签名 deep / strict 校验通过,真实 XPC 温度与 SMART 返回有效值。 + +## 最终包面板实测 + +最终 1.88 MB 包,开启 JSON 测量、关闭分配栈、前台 2 秒、后台趋势显式关闭。下表是主进程足迹,不能替代全部归属进程预算: + +| 时点 | MiB | +| --- | ---: | +| 启动 / 隐藏 10 秒 | 13.61 / 15.33 | +| 第一次打开 1 / 10 / 30 秒 | 195.09 / 75.84 / 194.63 | +| 首次累计峰值 | 203.83 | +| 暂停 10 秒 | 75.70 | +| 第一次关闭 10 / 30 秒 | 65.66 / 65.66 | +| 第二 / 三次关闭 30 秒 | 64.49 / 63.81 | +| 三轮累计峰值 | 214.69 | + +同一首批代码的未剥离包三轮实测:累计峰值约 223.2 MiB,关闭 30 秒约 68.95 → 74.92 → 76.58 MiB。存在预热或增长,三轮不足以判定平台;不声称无泄漏。辅助 XPC 的一轮只读检查当前约 3.30 MiB、峰值约 3.34 MiB,必须另计;共享系统自动填充服务归因仍未解决。 + +隐藏首个 10 秒无常规 sample 事件、打开后才启动 XPC;本轮暂停 10 秒区间没有常规 sample 发布。此证据加调度检查支持没有消费者时不采样及暂停冻结,不证明全部在途子进程已经取消。10 分钟无诊断 CPU、唤醒 / W、100 次与 8 小时验收均未完成。 + +## 验证 + +- Debug 与 Release 构建通过;工程仍无 XCTest Target。切换 strip 配置后的本轮增量构建曾令已剥离 XPC 重新生成空调试信息(no debug symbols);发行验证改用全新 DerivedData,并检查主程序 / XPC 的 dSYM UUID 与非空编译单元。普通无改动增量构建另已通过。发行必须保留干净归档中的完整 dSYM,不能仅凭 UUID 相同判断有调试信息。 +- Debug、Release 独立检查各 22 项、三语目录与沙盒权限检查通过(Release 全量检查针对缩品牌资源之前的同代码剥离包)。 +- 最终资源包另跑 PanelAssetChecks、LocalizationChecks、CodeIdentityChecks、SamplingIntervalChecks 共 4 项通过。 +- 原生 PanelWindowChecks、SettingsWindowChecks、LanguageScopeChecks 与实际沙盒 HTTPS 检查通过,共 4 项。它们不是完整面板鼠标 / 搜索 / 悬浮回归。 +- SensorScheduleChecks 新增独立退避、封顶及恢复;SamplingIntervalChecks 增加新配置零采样、迁移保留、显式关闭、后台开关与历史断点。保留既有 PID 复用 / 枚举失败检查。 +- 初次全量检查曾因读取期间源文件被本轮修改而中断;停止并在源文件稳定后完整重跑,22 项通过。该次中断不计入成功结果。 +- 原生工具对规范测试路径绑定仍超时(非规范路径返回 Invalid app);没有取得正式面板 AX / 坐标 / 键盘事件验证,也未据此判为缺少权限。 +- 测试前记录已有 Xcode 应用与调试进程,未向其发送退出 / 信号;仅管理本轮临时路径的测试副本。临时构建、原始采样、分配日志及图像在本轮结束时清理;本页保留匿名数值和调用链,不保存进程路径清单。 + +## 可复现入口与剩余工作 + +构建包后,只对隔离测试副本运行(会固定并显示测试面板约 200 秒,结束自行退出): + +```bash +open -n --env KYMO_RESOURCE_AUDIT=1 --env KYMO_DIAGNOSTICS=1 \ + --stdout /tmp/kymo-resource-audit.jsonl --stderr /tmp/kymo-resource-audit.err \ + /absolute/path/to/kymo.app --args \ + -sampling.panelMilliseconds 2000 -sampling.backgroundEnabled NO +``` + +`KYMO_AUDIT_OMIT` 可选 `icons` / `processes` / `resources` / `header` / `all`,仅在测量入口启用时生效;正常启动不执行这些分支。事件包含实际 recordedAt / uptime、快照时间、足迹与累计峰值。测试窗口方法调用不能冒充真实输入事件;原始日志可能包含接口标识,分享前需脱敏。 + +下一批优先:继续 P0 / P2 内存分配与发布范围定位,完善传输故障回归和 L07 / L08 / L15;然后实现 P3 真实系统能量差分与覆盖说明。当前“耗电进程”仍是旧 CPU 列表,没有声称已实现实际能耗。完整项目尚未完成,也未通过 CPU、内存、整机功耗及长期稳定性预算。 diff --git a/docs/extreme-efficiency-plan.md b/docs/extreme-efficiency-plan.md index 562ed63..74b7443 100644 --- a/docs/extreme-efficiency-plan.md +++ b/docs/extreme-efficiency-plan.md @@ -2,7 +2,7 @@ 日期:2026-11-03。源码基线:`8333349e93c627b8b1df3802e0d3adac32610472`。 -状态:方案待实施。本轮仅完成源码审查、前序会话实测结果归档与方案编写;以下目标、接口和调度策略均不代表当前实现或已通过验收。 +状态:实施中,已完成首批调度 / XPC / 静态显示 / 包体积改动,详见[首批实施记录](efficiency-first-batch.md)。以下设计仍含未实施部分;预算未全部通过,真实能耗列表尚未实现。 ## 1. 背景与目标 @@ -40,7 +40,7 @@ Kymo 的定位是体积极小、占用极小、省电的极客监控工具。当 ### 2.2 已确认的逻辑问题与候选浪费点 -“确认”表示源码路径存在,不表示已量化收益;“待剖析”必须经隔离对照后才能确定是否为主要根因。 +下表记录方案基线的缺陷,修正进展以[实施记录](efficiency-first-batch.md)为准,不能将原问题表当成修正后的代码事实。“确认”不表示已量化收益;“待剖析”必须经隔离对照后才能确定是否为主要根因。 | 编号 | 状态 / 优先级 | 位置与问题 | 实施方向 / 验收 | | --- | --- | --- | --- | @@ -289,9 +289,12 @@ python3 tools/check.py --configuration Release | 阶段 | 当前状态 | 证据 / 未完成 | | --- | --- | --- | | 方案 | 已编写 | 汇总本次会话与源码检查;尚未实施 | -| P0 | 未开始 | 先前短时测量 / 用户截图已归档,不是受控新基线 | -| P1–P4 | 未开始 | 没有性能修复或真实能耗列表代码变更 | -| P5 | 未开始 | 未取得完整面板 Release、长期、功耗和多硬件验收 | +| P0 | 进行中 | 新 Release 复现、字形分配栈、组件隔离与真实面板三轮;仍缺受控 Debug / 完整触发链 | +| P1 | 部分完成 | 批量 XPC / 服务共享 / 独立退避 / 取消超时 / 隐藏需求 / 公网暂停;出口、遮挡、睡眠和有界子进程未完成 | +| P2 | 部分完成 | 静态数字 / 曲线 / 风扇与路径缓存;内存峰值及回落未达标、按域发布 / 图标专项待做 | +| P3 | 未开始 | 耗电进程仍为旧 CPU 实现;真实系统能量列表待实现 | +| P4 | 首批产物达标 | 本机签名 arm64 app 1,882,766 B / ZIP 1,005,772 B,默认优化;发行流程与完整功能新增后需复验 | +| P5 | 未完成 | 短时面板和自动检查不替代 CPU / W / 100 次 / 8 小时与多硬件验收 | 每阶段更新本表及 L01–L16 的结论,记录提交、实测数值、未达标项和原因;架构 / 指标 / 测试事实分别同步主题文档。最终以完整功能、相同条件、关闭诊断的 Release 验收,不以“改完代码”或“编译通过”结束。方案完成后将稳定规则归入主题文档,过程记录保留到问题可审计为止。 diff --git a/docs/monitoring.md b/docs/monitoring.md index 24a0625..c31ee9f 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -37,15 +37,15 @@ | 数据 | 默认 / 周期策略 | | --- | --- | -| 常规资源快照 | 面板可见 2000ms,隐藏 5000ms;分别持久化,可设 500–1,800,000ms,步进 100ms | +| 常规资源快照 | 面板可见默认 2000ms;新配置隐藏默认停止采样,显式启用后台趋势后默认 30000ms;已有合法后台间隔保留启用和原值,显式开关优先;可设 500–1,800,000ms,步进 100ms | | 进程 | 面板可见且未暂停时随采样请求更新;异步完成可单独发布,最多一个在途 | -| CPU / GPU 温度、风扇 | 读取结束后至少 5 秒再试;三类全部不可用时至少 60 秒 | +| CPU / GPU 温度、风扇 | 一次批量请求中只读取到期类别;各类别成功后至少 10 秒再读,失败独立退避 60–600 秒 | | 卷列表 | 读取结束后至少 30 秒 | | SMART / 电池健康 | 成功后至少 3600 秒;失败后至少 600 秒 | -| 公网 IP | 同一路由键成功缓存 600 秒,失败缓存 30 秒,请求超时 5 秒;面板可见时按缓存到期持续刷新,路由键变化或面板隐藏取消请求及等待,取消不缓存;有效期使用单调时间 | +| 公网 IP | 同一路由键成功缓存 600 秒,失败缓存 30 秒,请求超时 5 秒;面板可见时按缓存到期持续刷新,路由键变化、暂停或面板隐藏取消请求及等待,取消不缓存;有效期使用单调时间 | | 趋势 | 全局与每接口最多各 60 点,仅内存保存 | -慢指标只在常规采样轮次检查是否到期,后台间隔较长时实际刷新更慢。快照中的慢指标可能来自之前的缓存;磁盘 / 电池健康快照带读取日期。暂停停止发布,不保证取消已进入系统调用的工作。 +传感器、卷与慢报告只在可见采样轮次检查是否到期;后台趋势不启动这些慢读取。快照中的慢指标可能来自之前的缓存;磁盘 / 电池健康快照带读取日期。暂停停止发布,不保证取消已进入系统调用的工作。 ## 兼容性边界 diff --git a/docs/testing.md b/docs/testing.md index 146de55..c354189 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -269,3 +269,9 @@ AppKit 宿主即时语言刷新回归检查: swiftc -parse-as-library kymo/Core/Services/LanguagePreferences.swift kymo/UI/Components/AppLanguageScope.swift kymoTests/LanguageScopeChecks.swift -o /private/tmp/kymo-scope-checks /private/tmp/kymo-scope-checks ``` + +## 资源开关周期测量 + +显式开启的真实面板入口、组件隔离参数与首批证据见[轻量化实施记录](efficiency-first-batch.md)。`SensorScheduleChecks` 核对分能力失败退避、封顶与恢复;`SamplingIntervalChecks` 同时核对隐藏无消费者零采样、旧偏好迁移、显式开关与重开断点。它们不替代真实签名 XPC 故障注入、完整面板输入或长期功耗验收。 + +Release 配置由各 Target 在签名前 strip,保留包外 dSYM;测量必须对最终签名包统计文件逻辑大小、相同格式 ZIP 与资源 rendition,不能使用只改 DerivedData 的手工 strip 结果。首次局部结果低于包大小预算,不代表内存 / CPU / W / 8 小时已经通过。 diff --git a/kymo.xcodeproj/project.pbxproj b/kymo.xcodeproj/project.pbxproj index f63da67..d45a498 100644 --- a/kymo.xcodeproj/project.pbxproj +++ b/kymo.xcodeproj/project.pbxproj @@ -376,6 +376,9 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; + DEPLOYMENT_POSTPROCESSING = YES; + STRIP_INSTALLED_PRODUCT = YES; + STRIP_STYLE = all; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; diff --git a/kymo/App/kymoApp.swift b/kymo/App/kymoApp.swift index 44ceaa9..b72eb2e 100644 --- a/kymo/App/kymoApp.swift +++ b/kymo/App/kymoApp.swift @@ -38,14 +38,19 @@ import AppKit menuTitle: { [language] key in AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem") }, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in - AppLanguageScope(preferences: language) { - MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, settingsPresentation: self.presentation, - presentation: panel, onOpenSettings: { [weak self] in - self?.menuBar?.hide() - settings.environment.openSettings() - }) + if PanelResourceAudit.omitted == "all" { + Text(verbatim: "Kymo").frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + AppLanguageScope(preferences: language) { + MenuPanelView(metrics: self.metrics, preferences: self.appearance, keepAwake: self.awake, settingsPresentation: self.presentation, + presentation: panel, onOpenSettings: { [weak self] in + self?.menuBar?.hide() + settings.environment.openSettings() + }) + } } } + if let menuBar { PanelResourceAudit.run(controller: menuBar, metrics: metrics) } } private func configureMainMenu() { diff --git a/kymo/Assets.xcassets/BrandLogo.imageset/BrandLogo.svg b/kymo/Assets.xcassets/BrandLogo.imageset/BrandLogo.svg index b7dc31f..2d71f5f 100644 --- a/kymo/Assets.xcassets/BrandLogo.imageset/BrandLogo.svg +++ b/kymo/Assets.xcassets/BrandLogo.imageset/BrandLogo.svg @@ -1,4 +1,4 @@ - + diff --git a/kymo/Core/Monitors/ProcessMonitor.swift b/kymo/Core/Monitors/ProcessMonitor.swift index 0bacfa7..5845581 100644 --- a/kymo/Core/Monitors/ProcessMonitor.swift +++ b/kymo/Core/Monitors/ProcessMonitor.swift @@ -4,6 +4,7 @@ import Darwin nonisolated struct ProcessMonitor: Sendable { private var previous: [ProcessIdentity: (UInt64, TimeInterval)] = [:] private var sampleSerial: UInt64 = 0 + private var paths: [ProcessIdentity: (name: String, path: String?, expires: TimeInterval)] = [:] static func cpu(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? { guard let previous, current >= previous, elapsed.isFinite, elapsed > 0 else { return nil } @@ -15,11 +16,13 @@ nonisolated struct ProcessMonitor: Sendable { let date = Date() guard let entries = Self.entries() else { previous = [:] + paths = [:] return ProcessSnapshot(date: date, enumerated: 0, readable: 0, rows: [], failed: true) } let now = ProcessInfo.processInfo.systemUptime var next: [ProcessIdentity: (UInt64, TimeInterval)] = [:] var rows: [ProcessMetrics] = [] + var pathBuffer = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN)) for entry in entries where entry.kp_proc.p_pid > 0 { let pid = entry.kp_proc.p_pid var info = proc_taskallinfo() @@ -34,8 +37,14 @@ nonisolated struct ProcessMonitor: Sendable { let name = withUnsafeBytes(of: ©) { raw in String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self) } - var path = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN)) - let pathSize = proc_pidpath(pid, &path, UInt32(path.count)) + let path: String? + if let cached = paths[id], seconds > 0, cached.name == name, now < cached.expires { + path = cached.path + } else { + let size = proc_pidpath(pid, &pathBuffer, UInt32(pathBuffer.count)) + path = size > 0 ? String(cString: pathBuffer) : nil + paths[id] = (name, path, now + 30) + } var usage: Double? if valid && seconds > 0 { let (total, overflow) = info.ptinfo.pti_total_user.addingReportingOverflow(info.ptinfo.pti_total_system) @@ -44,7 +53,7 @@ nonisolated struct ProcessMonitor: Sendable { next[id] = (total, now) } } - rows.append(ProcessMetrics(id: id, name: name, path: pathSize > 0 ? String(cString: path) : nil, + rows.append(ProcessMetrics(id: id, name: name, path: path, cpu: usage, residentBytes: valid ? info.ptinfo.pti_resident_size : nil, threads: valid ? Int(info.ptinfo.pti_threadnum) : nil, restricted: !valid)) } @@ -56,11 +65,13 @@ nonisolated struct ProcessMonitor: Sendable { }) rows.removeAll { $0.id.seconds > 0 && !identities.contains($0.id) } } else { + paths = [:] rows = rows.map { ProcessMetrics(id: $0.id, name: $0.name, path: nil, cpu: $0.cpu, residentBytes: $0.residentBytes, threads: $0.threads, restricted: $0.restricted) } } let retained = Set(rows.map(\.id)) previous = next.filter { retained.contains($0.key) } + paths = paths.filter { retained.contains($0.key) && $0.key.seconds > 0 } return ProcessSnapshot(date: date, enumerated: entries.filter { $0.kp_proc.p_pid > 0 }.count, readable: rows.filter { !$0.restricted }.count, rows: rows, failed: false) } diff --git a/kymo/Core/Monitors/SystemSampler.swift b/kymo/Core/Monitors/SystemSampler.swift index 1e01588..9075928 100644 --- a/kymo/Core/Monitors/SystemSampler.swift +++ b/kymo/Core/Monitors/SystemSampler.swift @@ -8,7 +8,9 @@ actor SystemSampler { private var temperatureCache: Double? private var gpuTemperatureCache: Double? private var fanCache: [FanMetrics]? - private var nextTemperature: TimeInterval = 0 + private var cpuSchedule = SensorSchedule() + private var gpuSchedule = SensorSchedule() + private var fanSchedule = SensorSchedule() private var didProbe = false private let diskHealth = DiskHealthMonitor() private let batteryHealth = SystemBatteryHealthMonitor() @@ -50,7 +52,8 @@ actor SystemSampler { // A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied. } - func sample(includeProcesses: Bool? = nil, processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot { + func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, + processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil) -> MetricsSnapshot { guard !Task.isCancelled else { return MetricsSnapshot() } if let includeProcesses { setProcessVisible(includeProcesses) } self.processUpdate = processUpdate @@ -61,12 +64,13 @@ actor SystemSampler { let start = ProcessInfo.processInfo.systemUptime var result = MetricsSnapshot() result.cpu = cpu.sample() - if temperatureTask == nil && start >= nextTemperature { + let readCPU = cpuSchedule.isDue(at: start) + let readGPU = gpuSchedule.isDue(at: start) + let readFans = fanSchedule.isDue(at: start) + if includeSlowMetrics && temperatureTask == nil && (readCPU || readGPU || readFans) { temperatureTask = Task { [self] in - async let cpu = CPUTemperatureServiceClient.read() - async let gpu = CPUTemperatureServiceClient.read(gpu: true) - async let fans = CPUTemperatureServiceClient.readFans() - await finishTemperature(cpu, gpu: gpu, fans: fans) + let readings = await CPUTemperatureServiceClient.readSensors(cpu: readCPU, gpu: readGPU, fans: readFans) + finishTemperature(readings, cpu: readCPU, gpu: readGPU, fans: readFans) } } result.cpuTemperature = temperatureCache @@ -82,16 +86,16 @@ actor SystemSampler { result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present result.gpu = GPUMonitor.sample() result.gpuUsage = result.gpu?.usage - if volumeTask == nil && start - volumeSampleTime >= 30 { + if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 { volumeTask = Task.detached(priority: .utility) { [self] in let value = DiskMonitor.volumes() await finishVolumes(value) } } - if diskTask == nil && start >= nextDisk { + if includeSlowMetrics && diskTask == nil && start >= nextDisk { diskTask = Task { [self, diskHealth] in await finishDisk(diskHealth.sample()) } } - if result.battery != nil && batteryTask == nil && start >= nextBattery { + if includeSlowMetrics && result.battery != nil && batteryTask == nil && start >= nextBattery { batteryTask = Task { [self, batteryHealth] in await finishBattery(batteryHealth.sample()) } } startProcessesIfNeeded() @@ -111,11 +115,11 @@ actor SystemSampler { return result } - private func finishTemperature(_ value: Double?, gpu: Double?, fans: [FanMetrics]?) { - fanCache = fans - gpuTemperatureCache = gpu - temperatureCache = value - nextTemperature = ProcessInfo.processInfo.systemUptime + (value == nil && gpu == nil && fans == nil ? 60 : 5) + private func finishTemperature(_ readings: SensorReadings?, cpu: Bool, gpu: Bool, fans: Bool) { + let now = ProcessInfo.processInfo.systemUptime + if cpu { temperatureCache = readings?.cpu; cpuSchedule.complete(available: temperatureCache != nil, at: now) } + if gpu { gpuTemperatureCache = readings?.gpu; gpuSchedule.complete(available: gpuTemperatureCache != nil, at: now) } + if fans { fanCache = readings?.fans; fanSchedule.complete(available: fanCache != nil, at: now) } temperatureTask = nil } diff --git a/kymo/Core/Services/CPUTemperatureServiceClient.swift b/kymo/Core/Services/CPUTemperatureServiceClient.swift index 6b8a45d..d256f5b 100644 --- a/kymo/Core/Services/CPUTemperatureServiceClient.swift +++ b/kymo/Core/Services/CPUTemperatureServiceClient.swift @@ -1,73 +1,24 @@ import Foundation +nonisolated struct SensorReadings: Sendable { + var cpu: Double? + var gpu: Double? + var fans: [FanMetrics]? +} + nonisolated enum CPUTemperatureServiceClient { - static func read(gpu: Bool = false) async -> Double? { - let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc") - guard let requirement = CodeIdentity.requirement(at: url) else { return nil } - return await withCheckedContinuation { continuation in - let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService") - connection.setCodeSigningRequirement(requirement) - connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self) - let reply = Reply(connection: connection, continuation: continuation) - connection.invalidationHandler = { reply.finish(nil) } - connection.interruptionHandler = { reply.finish(nil) } - connection.resume() - guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else { - reply.finish(nil) - return + static func readSensors(cpu: Bool, gpu: Bool, fans: Bool) async -> SensorReadings? { + await ServiceRequest.perform(timeout: 2) { proxy, finish in + proxy.readSensors(cpu: cpu, gpu: gpu, fans: fans) { cpu, gpu, fans in + func temperature(_ number: NSNumber?) -> Double? { + number.flatMap { $0.doubleValue.isFinite && $0.doubleValue > 0 && $0.doubleValue < 150 ? $0.doubleValue : nil } + } + let values = fans.flatMap { values -> [FanMetrics]? in + guard values.count <= 10 else { return nil } + return values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) } + } + finish(SensorReadings(cpu: temperature(cpu), gpu: temperature(gpu), fans: values)) } - let receive: (NSNumber?) -> Void = { number in - let value = number?.doubleValue - reply.finish(value.flatMap { $0.isFinite && $0 > 0 && $0 < 150 ? $0 : nil }) - } - if gpu { proxy.readGPUTemperature(withReply: receive) } - else { proxy.readCPUTemperature(withReply: receive) } - DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) } - } - } - - static func readFans() async -> [FanMetrics]? { - let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc") - guard let requirement = CodeIdentity.requirement(at: url) else { return nil } - return await withCheckedContinuation { continuation in - let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService") - connection.setCodeSigningRequirement(requirement) - connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self) - let reply = Reply(connection: connection, continuation: continuation) - connection.invalidationHandler = { reply.finish(nil) } - connection.interruptionHandler = { reply.finish(nil) } - connection.resume() - guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else { - reply.finish(nil); return - } - proxy.readFanSpeeds { values in - guard let values, values.count <= 10 else { reply.finish(nil); return } - reply.finish(values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) }) - } - DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) } - } - } - - private final class Reply: @unchecked Sendable { - private let lock = NSLock() - private var continuation: CheckedContinuation? - private let connection: NSXPCConnection - - init(connection: NSXPCConnection, continuation: CheckedContinuation) { - self.connection = connection - self.continuation = continuation - } - - func finish(_ value: Value?) { - lock.lock() - let callback = continuation - continuation = nil - lock.unlock() - guard let callback else { return } - connection.invalidationHandler = nil - connection.interruptionHandler = nil - connection.invalidate() - callback.resume(returning: value) } } } diff --git a/kymo/Core/Services/MetricsStore.swift b/kymo/Core/Services/MetricsStore.swift index 1713b79..4e7e6c4 100644 --- a/kymo/Core/Services/MetricsStore.swift +++ b/kymo/Core/Services/MetricsStore.swift @@ -9,6 +9,7 @@ final class MetricsStore { private(set) var isPanelVisible = false let sampling: SamplingPreferences var effectiveMilliseconds: Int { isPanelVisible ? sampling.panelMilliseconds : sampling.backgroundMilliseconds } + private var hasSamplingDemand: Bool { isPanelVisible || sampling.backgroundEnabled } @ObservationIgnored private var generation = 0 @ObservationIgnored private var visibilityGeneration = 0 @ObservationIgnored private var task: Task? @@ -21,7 +22,8 @@ final class MetricsStore { self.sampler = sampler self.sampling = sampling ?? SamplingPreferences() self.sampling.onChange = { [weak self] in - guard let self, !self.isPaused, self.effectiveMilliseconds != self.scheduledInterval else { return } + guard let self, !self.isPaused, + self.effectiveMilliseconds != self.scheduledInterval || self.hasSamplingDemand != (self.task != nil) else { return } self.reschedule(reset: false, sampleImmediately: false) } start() @@ -36,8 +38,10 @@ final class MetricsStore { private func reschedule(reset: Bool, sampleImmediately: Bool = true) { generation += 1 task?.cancel() + task = nil needsHistoryBoundary = needsHistoryBoundary || reset scheduledInterval = effectiveMilliseconds + guard hasSamplingDemand else { needsHistoryBoundary = true; return } var delay = Duration.zero if !sampleImmediately, let lastPublishedAt { delay = max(.zero, .milliseconds(effectiveMilliseconds) - lastPublishedAt.duration(to: .now)) @@ -51,8 +55,10 @@ final class MetricsStore { } if reset { await sampler.reset() } while !Task.isCancelled { + let sampledAt = ContinuousClock.now let visibleGeneration = self?.visibilityGeneration - var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true, processUpdate: { [weak self] processes in + var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true, + includeSlowMetrics: self?.isPanelVisible == true, processUpdate: { [weak self] processes in Task { @MainActor [weak self] in guard let self, self.visibilityGeneration == visibleGeneration, self.isPanelVisible, !self.isPaused else { return } @@ -71,7 +77,9 @@ final class MetricsStore { self?.needsHistoryBoundary = false SamplingDiagnostics.record(next) let interval = self?.effectiveMilliseconds ?? 5_000 - do { try await Task.sleep(for: .milliseconds(interval)) } + // Start-to-start cadence; missed deadlines do not trigger catch-up bursts. + let deadline = sampledAt.advanced(by: .milliseconds(interval)) + do { try await Task.sleep(until: max(deadline, .now), clock: .continuous) } catch { return } } } @@ -97,7 +105,7 @@ final class MetricsStore { if !visible { snapshot.processes = nil } let active = visible && !isPaused Task { await sampler.setProcessVisible(active) } - if !isPaused { reschedule(reset: false) } + if !isPaused { reschedule(reset: !sampling.backgroundEnabled) } } deinit { task?.cancel() } diff --git a/kymo/Core/Services/SMARTServiceClient.swift b/kymo/Core/Services/SMARTServiceClient.swift index 8c2048c..dc4f04a 100644 --- a/kymo/Core/Services/SMARTServiceClient.swift +++ b/kymo/Core/Services/SMARTServiceClient.swift @@ -2,50 +2,13 @@ import Foundation nonisolated enum SMARTServiceClient { static func read() async -> DiskHealthMetrics? { - let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc") - guard let requirement = CodeIdentity.requirement(at: url) else { return nil } - return await withCheckedContinuation { continuation in - let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService") - connection.setCodeSigningRequirement(requirement) - connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self) - let reply = Reply(connection: connection, continuation: continuation) - connection.invalidationHandler = { reply.finish(nil) } - connection.interruptionHandler = { reply.finish(nil) } - connection.resume() - guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else { - reply.finish(nil); return - } + await ServiceRequest.perform(timeout: 15) { proxy, finish in proxy.readSMART { remaining, hours in let life = remaining?.doubleValue let validLife = life.flatMap { $0.isFinite && (0...1).contains($0) ? $0 : nil } let validHours = hours.flatMap { UInt64($0.stringValue) } - reply.finish(validLife != nil || validHours != nil ? DiskHealthMetrics(remainingLife: validLife, powerOnHours: validHours) : nil) + finish(validLife != nil || validHours != nil ? DiskHealthMetrics(remainingLife: validLife, powerOnHours: validHours) : nil) } - DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 15) { reply.finish(nil) } - } - } - - /// Error, interruption, timeout and reply may race; resume exactly once. - private final class Reply: @unchecked Sendable { - private let lock = NSLock() - private var continuation: CheckedContinuation? - private let connection: NSXPCConnection - - init(connection: NSXPCConnection, continuation: CheckedContinuation) { - self.connection = connection - self.continuation = continuation - } - - func finish(_ value: DiskHealthMetrics?) { - lock.lock() - let callback = continuation - continuation = nil - lock.unlock() - guard let callback else { return } - connection.invalidationHandler = nil - connection.interruptionHandler = nil - connection.invalidate() - callback.resume(returning: value) } } } diff --git a/kymo/Core/Services/SMARTServiceProtocol.swift b/kymo/Core/Services/SMARTServiceProtocol.swift index 2ccd4bb..d2b3fb3 100644 --- a/kymo/Core/Services/SMARTServiceProtocol.swift +++ b/kymo/Core/Services/SMARTServiceProtocol.swift @@ -2,8 +2,7 @@ import Foundation /// Fixed read-only operation: no caller-supplied paths or commands. @objc protocol SMARTServiceProtocol { - nonisolated func readFanSpeeds(withReply reply: @escaping ([NSNumber]?) -> Void) + nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool, + withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void) nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void) - nonisolated func readGPUTemperature(withReply reply: @escaping (NSNumber?) -> Void) - nonisolated func readCPUTemperature(withReply reply: @escaping (NSNumber?) -> Void) } diff --git a/kymo/Core/Services/SamplingDiagnostics.swift b/kymo/Core/Services/SamplingDiagnostics.swift index 4b598bb..e77f2bb 100644 --- a/kymo/Core/Services/SamplingDiagnostics.swift +++ b/kymo/Core/Services/SamplingDiagnostics.swift @@ -9,6 +9,8 @@ nonisolated enum SamplingDiagnostics { guard enabled else { return } var payload: [String: Any] = [ "event": event, "timestamp": snapshot.date.timeIntervalSince1970, + "recordedAt": Date().timeIntervalSince1970, + "uptime": ProcessInfo.processInfo.systemUptime, "pid": ProcessInfo.processInfo.processIdentifier, "load": snapshot.load ] @@ -44,6 +46,7 @@ nonisolated enum SamplingDiagnostics { if status == KERN_SUCCESS { payload["residentBytes"] = info.resident_size payload["footprintBytes"] = info.phys_footprint + payload["peakFootprintBytes"] = info.ledger_phys_footprint_peak } guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else { return } try? FileHandle.standardOutput.write(contentsOf: data + Data([10])) diff --git a/kymo/Core/Services/SamplingPreferences.swift b/kymo/Core/Services/SamplingPreferences.swift index d249d7b..064fe9a 100644 --- a/kymo/Core/Services/SamplingPreferences.swift +++ b/kymo/Core/Services/SamplingPreferences.swift @@ -10,6 +10,16 @@ import CoreFoundation @ObservationIgnored var onChange: (() -> Void)? private var panelValue: Int private var backgroundValue: Int + private var backgroundEnabledValue: Bool + var backgroundEnabled: Bool { + get { backgroundEnabledValue } + set { + guard newValue != backgroundEnabledValue else { return } + backgroundEnabledValue = newValue + defaults.set(newValue, forKey: "sampling.backgroundEnabled") + onChange?() + } + } var panelMilliseconds: Int { get { panelValue } set { @@ -34,7 +44,17 @@ import CoreFoundation init(defaults: UserDefaults = .standard) { self.defaults = defaults panelValue = Self.read(defaults, key: "sampling.panelMilliseconds", fallback: 2_000) - backgroundValue = Self.read(defaults, key: "sampling.backgroundMilliseconds", fallback: 5_000) + backgroundValue = Self.read(defaults, key: "sampling.backgroundMilliseconds", fallback: 30_000) + // Retain an existing explicit background interval; new installs have no hidden consumer. + if let number = defaults.object(forKey: "sampling.backgroundEnabled") as? NSNumber, + CFGetTypeID(number) == CFBooleanGetTypeID() { + backgroundEnabledValue = number.boolValue + } else if let number = defaults.object(forKey: "sampling.backgroundMilliseconds") as? NSNumber, + CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite { + backgroundEnabledValue = true + } else { + backgroundEnabledValue = false + } } static func normalized(_ value: Int) -> Int { diff --git a/kymo/Core/Services/SensorSchedule.swift b/kymo/Core/Services/SensorSchedule.swift new file mode 100644 index 0000000..7af93ec --- /dev/null +++ b/kymo/Core/Services/SensorSchedule.swift @@ -0,0 +1,14 @@ +import Foundation + +/// Missing capabilities back off independently; success in another zone cannot reset this state. +nonisolated struct SensorSchedule { + private(set) var deadline: TimeInterval = 0 + private var failures = 0 + + func isDue(at now: TimeInterval) -> Bool { now >= deadline } + + mutating func complete(available: Bool, at now: TimeInterval) { + failures = available ? 0 : min(failures + 1, 5) + deadline = now + (available ? 10 : min(600, 60 * pow(2, Double(failures - 1)))) + } +} diff --git a/kymo/Core/Services/ServiceRequest.swift b/kymo/Core/Services/ServiceRequest.swift new file mode 100644 index 0000000..c8f0669 --- /dev/null +++ b/kymo/Core/Services/ServiceRequest.swift @@ -0,0 +1,68 @@ +import Foundation + +/// One short-lived authenticated connection. Every completion releases the timer and connection. +nonisolated enum ServiceRequest { + private static let requirement = CodeIdentity.requirement(at: + Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")) + + static func perform(timeout: TimeInterval, + invoke: @escaping (SMARTServiceProtocol, @escaping @Sendable (Value?) -> Void) -> Void + ) async -> Value? { + guard let requirement else { return nil } + let request = Pending() + return await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + request.start(requirement: requirement, timeout: timeout, continuation: continuation, invoke: invoke) + } + } onCancel: { request.finish(nil) } + } + + private final class Pending: @unchecked Sendable { + private let lock = NSLock() + private var finished = false + private var continuation: CheckedContinuation? + private var connection: NSXPCConnection? + private var timer: DispatchSourceTimer? + + func start(requirement: String, timeout: TimeInterval, continuation: CheckedContinuation, + invoke: (SMARTServiceProtocol, @escaping @Sendable (Value?) -> Void) -> Void) { + lock.lock() + guard !finished else { lock.unlock(); continuation.resume(returning: nil); return } + self.continuation = continuation + let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService") + self.connection = connection + connection.setCodeSigningRequirement(requirement) + connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self) + connection.invalidationHandler = { [weak self] in self?.finish(nil) } + connection.interruptionHandler = { [weak self] in self?.finish(nil) } + let timer = DispatchSource.makeTimerSource(queue: .global(qos: .utility)) + self.timer = timer + timer.schedule(deadline: .now() + timeout) + timer.setEventHandler { [weak self] in self?.finish(nil) } + timer.resume() + connection.resume() + lock.unlock() + guard let proxy = connection.remoteObjectProxyWithErrorHandler({ [weak self] _ in self?.finish(nil) }) as? SMARTServiceProtocol else { + finish(nil); return + } + invoke(proxy) { [weak self] in self?.finish($0) } + } + + func finish(_ value: Value?) { + lock.lock() + guard !finished else { lock.unlock(); return } + finished = true + let callback = continuation + let timer = timer + let connection = connection + continuation = nil; self.timer = nil; self.connection = nil + lock.unlock() + timer?.setEventHandler {} + timer?.cancel() + connection?.invalidationHandler = nil + connection?.interruptionHandler = nil + connection?.invalidate() + callback?.resume(returning: value) + } + } +} diff --git a/kymo/Features/MenuBar/CPUCoreGrid.swift b/kymo/Features/MenuBar/CPUCoreGrid.swift index 9114364..d16b420 100644 --- a/kymo/Features/MenuBar/CPUCoreGrid.swift +++ b/kymo/Features/MenuBar/CPUCoreGrid.swift @@ -5,7 +5,6 @@ struct CPUCoreGrid: View { let values: [Double] let kinds: [Int: CPUCoreTopology.Kind] let interval: TimeInterval - @Environment(\.accessibilityReduceMotion) private var reduceMotion private func color(_ kind: CPUCoreTopology.Kind?) -> Color { switch kind { @@ -93,7 +92,6 @@ struct CPUCoreGrid: View { Circle().inset(by: 1).trim(from: 0, to: value) .stroke(color(kind), style: StrokeStyle(lineWidth: 2, lineCap: .round)) .rotationEffect(.degrees(-90)) - .animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, interval * 0.8)), value: value) Text(verbatim: "\(Int((value * 100).rounded()))") .font(.system(size: 8, weight: .medium)).lineLimit(1).minimumScaleFactor(0.4) } diff --git a/kymo/Features/MenuBar/GPUStatisticsView.swift b/kymo/Features/MenuBar/GPUStatisticsView.swift index 338e05c..287ab72 100644 --- a/kymo/Features/MenuBar/GPUStatisticsView.swift +++ b/kymo/Features/MenuBar/GPUStatisticsView.swift @@ -6,7 +6,6 @@ struct GPUStatisticsView: View { let allocated: UInt64? let average: Double? let peak: Double? - @Environment(\.accessibilityReduceMotion) private var reduceMotion private var reference: Double { max(1, Double(max(inUse ?? 0, allocated ?? 0))) } @@ -33,8 +32,6 @@ struct GPUStatisticsView: View { }.font(PanelStyle.label).lineLimit(1) MetricProgressBar(value: bytes.map { Double($0) / reference } ?? 0, color: color) .frame(height: 3) - .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: bytes) - .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: reference) .accessibilityHidden(true) } } diff --git a/kymo/Features/MenuBar/MenuPanelView+Network.swift b/kymo/Features/MenuBar/MenuPanelView+Network.swift index 04be7b6..662bd96 100644 --- a/kymo/Features/MenuBar/MenuPanelView+Network.swift +++ b/kymo/Features/MenuBar/MenuPanelView+Network.swift @@ -52,7 +52,8 @@ extension MenuPanelView { }.font(PanelStyle.label) .modifier(CardInset()) } - .task(id: publicIPRoute) { + .task(id: "\(publicIPRoute):\(metrics.isPaused)") { + guard !metrics.isPaused, metrics.isPanelVisible else { return } publicIPAddress = nil guard snapshot.networkPath == .available else { return } await PublicIPAddressService.shared.refreshContinuously(route: publicIPRoute) { address in diff --git a/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift b/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift index 6d32d52..b90625c 100644 --- a/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift +++ b/kymo/Features/MenuBar/MenuPanelView+ResourceCards.swift @@ -109,7 +109,6 @@ extension MenuPanelView { HStack(spacing: 8) { Text(title).font(PanelStyle.label).frame(width: 100, alignment: .leading) MetricProgressBar(value: value ?? 0, color: color).frame(height: 5) - .animation(reduceMotion ? nil : .easeInOut(duration: min(0.35, chartInterval * 0.8)), value: value) AnimatedMetricText(value: MetricFormat.percent(value)).font(PanelStyle.value).frame(width: 30, alignment: .trailing) }.font(PanelStyle.label) } @@ -286,7 +285,6 @@ struct EnergyProcessListRow: View { .clipShape(Capsule()) } .frame(height: 4) - .animation(.easeInOut(duration: 0.35), value: process.cpu) AnimatedMetricText(value: process.cpu.map { String(format: "%.1f%%", $0 * 100) } ?? "--") .foregroundStyle(Color("MetricCPU")).font(PanelStyle.value) .monospacedDigit().frame(width: 39, alignment: .trailing) diff --git a/kymo/Features/MenuBar/MenuPanelView.swift b/kymo/Features/MenuBar/MenuPanelView.swift index 6337b93..7d5e0c9 100644 --- a/kymo/Features/MenuBar/MenuPanelView.swift +++ b/kymo/Features/MenuBar/MenuPanelView.swift @@ -47,14 +47,14 @@ struct MenuPanelView: View { var body: some View { VStack(spacing: PanelStyle.gap) { - header + if PanelResourceAudit.omitted != "header" { header } if PanelLayout.needsResourceScroll(size: panelSize, rows: rowHeights) { ScrollView { resourceRows } .frame(maxHeight: PanelLayout.resourceHeight(rows: rowHeights)) } else { resourceRows } - if metrics.isPanelVisible { + if metrics.isPanelVisible && PanelResourceAudit.omitted != "processes" { ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900).frame(maxWidth: .infinity, maxHeight: .infinity) .frame(minHeight: 170) } @@ -98,14 +98,18 @@ struct MenuPanelView: View { } @ViewBuilder private func resourceCard(at index: Int) -> some View { - switch index { - case 0: cpuCard - case 1: gpuCard - case 2: batteryCard - case 3: memoryCard - case 4: diskCard - case 5: networkCard - default: EmptyView() + if PanelResourceAudit.omitted == "resources" { + Color.clear + } else { + switch index { + case 0: cpuCard + case 1: gpuCard + case 2: batteryCard + case 3: memoryCard + case 4: diskCard + case 5: networkCard + default: EmptyView() + } } } diff --git a/kymo/Features/MenuBar/PanelResourceAudit.swift b/kymo/Features/MenuBar/PanelResourceAudit.swift new file mode 100644 index 0000000..417e2fd --- /dev/null +++ b/kymo/Features/MenuBar/PanelResourceAudit.swift @@ -0,0 +1,39 @@ +import AppKit + +/// Explicit local measurement only. Never schedules work during normal launches. +@MainActor enum PanelResourceAudit { + static let enabled = ProcessInfo.processInfo.environment["KYMO_RESOURCE_AUDIT"] == "1" + static let omitted = enabled ? ProcessInfo.processInfo.environment["KYMO_AUDIT_OMIT"] ?? "" : "" + + static func run(controller: MenuPanelController, metrics: MetricsStore) { + guard enabled else { return } + Task { @MainActor in + @MainActor func mark(_ event: String) { SamplingDiagnostics.record(metrics.snapshot, event: "audit." + event) } + func wait(_ seconds: Int) async { try? await Task.sleep(for: .seconds(seconds)) } + // Pin the test window so unrelated focus changes cannot invalidate a measurement. + controller.presentation.isPinned = true + mark("cold") + await wait(10) + mark("hidden10") + for cycle in 1...3 { + controller.show() + mark("open\(cycle).0") + await wait(1); mark("open\(cycle).1") + await wait(9); mark("open\(cycle).10") + await wait(20); mark("open\(cycle).30") + if cycle == 1 { + metrics.togglePause(); mark("paused.0") + await wait(10); mark("paused.10") + metrics.togglePause(); mark("resumed") + } + controller.hide() + await wait(1); mark("closed\(cycle).1") + await wait(9); mark("closed\(cycle).10") + await wait(20); mark("closed\(cycle).30") + } + controller.shutdown() + mark("complete") + NSApp.terminate(nil) + } + } +} diff --git a/kymo/Features/MenuBar/ProcessIcon.swift b/kymo/Features/MenuBar/ProcessIcon.swift index 3a6a492..9e7e02b 100644 --- a/kymo/Features/MenuBar/ProcessIcon.swift +++ b/kymo/Features/MenuBar/ProcessIcon.swift @@ -17,6 +17,7 @@ struct ProcessIcon: View { .frame(width: 15, height: 15) .accessibilityHidden(true) .task(id: "\(process.id)-\(process.path ?? "")") { + guard PanelResourceAudit.omitted != "icons" else { return } // Resolve by the sampled executable, avoiding an icon from a reused PID. guard let path = process.path else { icon = nil; return } let url = URL(fileURLWithPath: path) diff --git a/kymo/Features/Settings/AppearanceSettingsView.swift b/kymo/Features/Settings/AppearanceSettingsView.swift index 50353d0..16f48ed 100644 --- a/kymo/Features/Settings/AppearanceSettingsView.swift +++ b/kymo/Features/Settings/AppearanceSettingsView.swift @@ -63,9 +63,10 @@ struct AppearanceSettingsView: View { } } Section { + Toggle("sampling.backgroundEnabled", isOn: $sampling.backgroundEnabled) LabeledContent("sampling.background") { IntervalControl(milliseconds: $sampling.backgroundMilliseconds) - } + }.disabled(!sampling.backgroundEnabled) Text("sampling.backgroundHelp").font(.callout).foregroundStyle(.secondary) } } diff --git a/kymo/Resources/Localizable.xcstrings b/kymo/Resources/Localizable.xcstrings index cbc7d58..c40ac70 100644 --- a/kymo/Resources/Localizable.xcstrings +++ b/kymo/Resources/Localizable.xcstrings @@ -3876,19 +3876,19 @@ "en" : { "stringUnit" : { "state" : "translated", - "value" : "Applies while the panel is closed. Default: 5 seconds. Panel interval is adjusted in its toolbar." + "value" : "Off by default to save energy. Reopening starts a new interval; hidden periods remain gaps. Existing custom intervals are retained." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "仅在面板关闭时生效,默认 5 秒。面板打开时的间隔在顶部工具栏单独调整。" + "value" : "默认关闭以节省能耗。重开后重新采样,隐藏期间保留历史断点;已有自定义间隔会保留。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "僅在面板關閉時生效,預設 5 秒。面板開啟時的間隔在頂部工具列獨立調整。" + "value" : "預設關閉以節省能耗。重開後重新取樣,隱藏期間保留歷史斷點;既有自訂間隔會保留。" } } } @@ -4166,7 +4166,30 @@ } } } + }, + "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" -} \ No newline at end of file +} diff --git a/kymo/UI/Charts/PanelTrendChart.swift b/kymo/UI/Charts/PanelTrendChart.swift index 317b49e..69f85f6 100644 --- a/kymo/UI/Charts/PanelTrendChart.swift +++ b/kymo/UI/Charts/PanelTrendChart.swift @@ -8,7 +8,7 @@ enum TrendValueFormat { case watts } -/// Bounded, timestamp-based curves. Gaps remain gaps; animation only runs on append. +/// Bounded, timestamp-based static curves. Gaps remain gaps; no per-sample animation task. struct PanelTrendChart: View { let dates: [Date] let first: [Double?] @@ -33,18 +33,12 @@ struct PanelTrendChart: View { var intervals: [TimeInterval] = [] var plotHeight: CGFloat = PanelStyle.plotHeight var showsLegendValues = true - @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var retainedScale: Double = 1 @State private var smallSamples = 0 @State private var retainedSecondScale: Double = 1 @State private var smallSecondSamples = 0 @State private var hoveredDate: Date? @State private var hoverPoint: CGPoint? - @State private var previousBegin: Date? - @State private var previousEnd: Date? - @State private var progress: CGFloat = 1 - @State private var lastFrame: PanelCurveFrame? - @State private var displayedFrame: PanelCurveFrame? private var inputFrame: PanelCurveFrame { PanelCurveFrame(dates: dates, series: [first, second, third, fourth], @@ -129,11 +123,11 @@ struct PanelTrendChart: View { .lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: plotHeight) GeometryReader { proxy in ZStack(alignment: .topLeading) { - PanelCurveCanvas(frame: displayedFrame ?? inputFrame, colors: [color, secondColor, thirdColor, fourthColor], + PanelCurveCanvas(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor], scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale], maximumGap: max(5, expectedInterval * 2), - targetBegin: (lastFrame ?? inputFrame).dates.first, targetEnd: (lastFrame ?? inputFrame).dates.last, - previousBegin: previousBegin, previousEnd: previousEnd, progress: progress) + targetBegin: dates.first, targetEnd: dates.last, + previousBegin: nil, previousEnd: nil, progress: 1) if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin { let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin) Path { path in @@ -187,8 +181,6 @@ struct PanelTrendChart: View { .onAppear { retainedScale = maximum retainedSecondScale = secondMaximum - lastFrame = inputFrame - displayedFrame = inputFrame } .onChange(of: dates) { _, _ in let target = maximum @@ -203,28 +195,7 @@ struct PanelTrendChart: View { smallSecondSamples += 1 if smallSecondSamples >= 10 { retainedSecondScale = secondTarget; smallSecondSamples = 0 } } else { smallSecondSamples = 0 } - let next = inputFrame - let old = lastFrame - let gap = PanelCurveGeometry.allowedGap(at: next.dates.count - 1, intervals: next.intervals, fallback: max(5, expectedInterval * 2)) - let append = old.map { PanelCurveGeometry.isAppend(from: $0.dates, to: next.dates, maximumGap: gap) } == true - && !(next.dates.last.map { boundaryDates.contains($0) } ?? false) - let animated = append && !reduceMotion - var transaction = Transaction(); transaction.disablesAnimations = true - withTransaction(transaction) { - lastFrame = next - displayedFrame = next - if animated, let old { displayedFrame = PanelCurveFrame.transition(from: old, to: next) } - previousBegin = animated ? old?.dates.first : nil - previousEnd = animated ? old?.dates.last : nil - progress = animated ? 0 : 1 - } } - .task(id: lastFrame?.dates.last) { - guard progress == 0, !reduceMotion else { return } - do { try await Task.sleep(for: .milliseconds(16)) } catch { return } - withAnimation(.easeInOut(duration: 0.35)) { progress = 1 } - } - .onChange(of: reduceMotion) { _, reduced in if reduced { progress = 1; previousBegin = nil; previousEnd = nil; lastFrame = inputFrame; displayedFrame = inputFrame } } .accessibilityElement(children: .combine) } } diff --git a/kymo/UI/Components/AnimatedMetricText.swift b/kymo/UI/Components/AnimatedMetricText.swift index 46594d1..c86912b 100644 --- a/kymo/UI/Components/AnimatedMetricText.swift +++ b/kymo/UI/Components/AnimatedMetricText.swift @@ -1,15 +1,12 @@ import SwiftUI -/// The same system numeric roll/blur transition as the original metric rows. +/// Static numbers avoid per-sample glyph rasterization and transition caches. struct AnimatedMetricText: View { let value: String - @Environment(\.accessibilityReduceMotion) private var reduceMotion var body: some View { Text(verbatim: value) .monospacedDigit() - .contentTransition(.numericText()) - .animation(reduceMotion ? nil : .spring(duration: 0.35, bounce: 0), value: value) } } diff --git a/kymo/UI/Components/FanSpeedIndicator.swift b/kymo/UI/Components/FanSpeedIndicator.swift index 41b68d6..b8c78a4 100644 --- a/kymo/UI/Components/FanSpeedIndicator.swift +++ b/kymo/UI/Components/FanSpeedIndicator.swift @@ -1,57 +1,19 @@ import SwiftUI -/// Approximate visual speed tiers; rotation does not attempt to reproduce physical RPM. -nonisolated struct FanRotation { - private(set) var phase: Double = 0 - private(set) var speed: Double = 0 - private var reference: TimeInterval = 0 - - static func speed(rpm: Double?, reducedMotion: Bool) -> Double { - guard !reducedMotion, let rpm, rpm.isFinite, rpm > 0 else { return 0 } - switch rpm { - case ..<2000: return 90 - case ..<4000: return 180 - case ..<6000: return 300 - default: return 450 - } - } - - func angle(at time: TimeInterval) -> Double { - (phase + max(0, time - reference) * speed).truncatingRemainder(dividingBy: 360) - } - - mutating func update(rpm: Double?, reducedMotion: Bool, at time: TimeInterval) { - phase = angle(at: time) - reference = time - speed = Self.speed(rpm: rpm, reducedMotion: reducedMotion) - } -} - struct FanSpeedIndicator: View { let title: Text let rpm: Double? - @Environment(\.accessibilityReduceMotion) private var reduceMotion - @State private var rotation = FanRotation() var body: some View { HStack(spacing: 5) { - TimelineView(.animation(minimumInterval: 1.0 / 30, paused: rotation.speed == 0)) { context in - Image(systemName: "fanblades.fill") - .rotationEffect(.degrees(rotation.angle(at: context.date.timeIntervalSinceReferenceDate))) - .foregroundStyle(.secondary) - }.frame(width: 14, height: 14).accessibilityHidden(true) + Image(systemName: "fanblades.fill") + .foregroundStyle(.secondary) + .frame(width: 14, height: 14).accessibilityHidden(true) title.foregroundStyle(.secondary) Spacer(minLength: 2) AnimatedMetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM") .monospacedDigit().fontWeight(.medium) } .font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7) - .onAppear { update() } - .onChange(of: rpm) { _, _ in update() } - .onChange(of: reduceMotion) { _, _ in update() } - } - - private func update() { - rotation.update(rpm: rpm, reducedMotion: reduceMotion, at: Date.timeIntervalSinceReferenceDate) } } diff --git a/kymo/UI/Components/MetricRingGauge.swift b/kymo/UI/Components/MetricRingGauge.swift index 98967da..51c80db 100644 --- a/kymo/UI/Components/MetricRingGauge.swift +++ b/kymo/UI/Components/MetricRingGauge.swift @@ -5,7 +5,6 @@ struct MetricRingGauge: View { let title: LocalizedStringKey let value: Double? let color: Color - @Environment(\.accessibilityReduceMotion) private var reduceMotion private var fraction: Double { value.flatMap { $0.isFinite ? min(1, max(0, $0)) : nil } ?? 0 } @@ -16,7 +15,6 @@ struct MetricRingGauge: View { Circle().trim(from: 0, to: fraction) .stroke(color, style: StrokeStyle(lineWidth: 3, lineCap: .round)) .rotationEffect(.degrees(-90)) - .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: fraction) AnimatedMetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold)) .lineLimit(1).minimumScaleFactor(0.6).frame(width: 18, height: 12) }.padding(2).frame(width: 28, height: 28).accessibilityHidden(true) diff --git a/kymo/UI/Components/PanelStyle.swift b/kymo/UI/Components/PanelStyle.swift index 5882a6d..d1c8717 100644 --- a/kymo/UI/Components/PanelStyle.swift +++ b/kymo/UI/Components/PanelStyle.swift @@ -54,7 +54,6 @@ struct CapacityBar: View { let values: [Double] let colors: [Color] let total: Double - @Environment(\.accessibilityReduceMotion) private var reduceMotion var body: some View { GeometryReader { bounds in @@ -65,7 +64,6 @@ struct CapacityBar: View { } } .clipShape(Capsule()) - .animation(reduceMotion ? nil : .easeInOut(duration: 0.35), value: values) } .frame(height: 8) .accessibilityHidden(true) diff --git a/kymoTests/FanChecks.swift b/kymoTests/FanChecks.swift index aa4a5f3..4c9d62b 100644 --- a/kymoTests/FanChecks.swift +++ b/kymoTests/FanChecks.swift @@ -10,22 +10,7 @@ import Foundation precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0, bytes: []) == nil) precondition(FanMetrics.validRPM(0) == 0) for value in [Double.nan, .infinity, -1, 30_001] { precondition(FanMetrics.validRPM(value) == nil) } - precondition(FanRotation.speed(rpm: 0, reducedMotion: false) == 0) - precondition(FanRotation.speed(rpm: nil, reducedMotion: false) == 0) - precondition(FanRotation.speed(rpm: .nan, reducedMotion: false) == 0) - precondition(FanRotation.speed(rpm: 6000, reducedMotion: true) == 0) - let tiers = [1000.0, 3000, 5000, 7000].map { FanRotation.speed(rpm: $0, reducedMotion: false) } - precondition(zip(tiers, tiers.dropFirst()).allSatisfy { $0 < $1 }) - var rotation = FanRotation() - rotation.update(rpm: 1000, reducedMotion: false, at: 100) - let before = rotation.angle(at: 101) - rotation.update(rpm: 7000, reducedMotion: false, at: 101) - precondition(rotation.angle(at: 101) == before) - rotation.update(rpm: 0, reducedMotion: false, at: 102) - precondition(rotation.angle(at: 102) == rotation.angle(at: 200)) - rotation.update(rpm: 7000, reducedMotion: true, at: 200) - precondition(rotation.angle(at: 200) == rotation.angle(at: 300)) - print("PASS: fan decoding, invalid RPM, speed tiers, continuous phase and stop/reduced-motion") + print("PASS: fan decoding, invalid RPM and static indicator data") print("Live fan RPM:", CPUTemperatureMonitor().sampleFans() as Any) } } diff --git a/kymoTests/SamplingChecks.swift b/kymoTests/SamplingChecks.swift index faf3d34..3c71f95 100644 --- a/kymoTests/SamplingChecks.swift +++ b/kymoTests/SamplingChecks.swift @@ -96,6 +96,7 @@ import Foundation precondition(reset.cpu == nil) let sampling = SamplingPreferences(defaults: defaults) sampling.backgroundMilliseconds = 500 + sampling.backgroundEnabled = true let store = MetricsStore(sampling: sampling) try await waitUntil { store.snapshot.cpu != nil } precondition(store.snapshot.cpu != nil) diff --git a/kymoTests/SamplingIntervalChecks.swift b/kymoTests/SamplingIntervalChecks.swift index 506ce18..65dce0b 100644 --- a/kymoTests/SamplingIntervalChecks.swift +++ b/kymoTests/SamplingIntervalChecks.swift @@ -6,7 +6,7 @@ import Foundation let defaults = UserDefaults(suiteName: suite)! defer { defaults.removePersistentDomain(forName: suite) } let preferences = SamplingPreferences(defaults: defaults) - precondition(preferences.panelMilliseconds == 2000 && preferences.backgroundMilliseconds == 5000) + precondition(preferences.panelMilliseconds == 2000 && preferences.backgroundMilliseconds == 30000 && !preferences.backgroundEnabled) for (input, expected) in [(Int.min, 500), (549, 500), (550, 600), (1501, 1500), (Int.max, 1_800_000)] { preferences.panelMilliseconds = input precondition(preferences.panelMilliseconds == expected) @@ -14,10 +14,14 @@ import Foundation preferences.backgroundMilliseconds = 1799900 let restored = SamplingPreferences(defaults: defaults) precondition(restored.panelMilliseconds == 1_800_000 && restored.backgroundMilliseconds == 1799900) + precondition(restored.backgroundEnabled, "Existing explicit intervals retain background history") + restored.backgroundEnabled = false + precondition(!SamplingPreferences(defaults: defaults).backgroundEnabled, "Explicit opt-out overrides migration") defaults.set(Double.nan, forKey: "sampling.panelMilliseconds") defaults.set(true, forKey: "sampling.backgroundMilliseconds") let invalid = SamplingPreferences(defaults: defaults) - precondition(invalid.panelMilliseconds == 2000 && invalid.backgroundMilliseconds == 5000) + precondition(invalid.panelMilliseconds == 2000 && invalid.backgroundMilliseconds == 30000 && !invalid.backgroundEnabled) + preferences.backgroundEnabled = true preferences.panelMilliseconds = 500 preferences.backgroundMilliseconds = 1_800_000 let store = MetricsStore(sampling: preferences) @@ -77,6 +81,30 @@ import Foundation try await until { changingStore.snapshot.processes != nil } precondition(changingStore.history.samples.count == countBeforeChange, "Rate changes must preserve in-flight process delivery without an extra quick sample") changingStore.togglePause() + let dormantPreferences = SamplingPreferences(defaults: defaults) + dormantPreferences.backgroundEnabled = false + dormantPreferences.panelMilliseconds = 500 + let dormant = MetricsStore(sampling: dormantPreferences) + try await Task.sleep(for: .milliseconds(650)) + precondition(dormant.history.samples.isEmpty && dormant.snapshot.memory == nil, + "Hidden without a consumer must not perform even an initial full sample") + dormant.setPanelVisible(true) + try await until { dormant.snapshot.processes != nil } + dormant.setPanelVisible(false) + let hiddenCount = dormant.history.samples.count + try await Task.sleep(for: .milliseconds(650)) + precondition(dormant.history.samples.count == hiddenCount && dormant.snapshot.processes == nil) + dormantPreferences.backgroundEnabled = true + dormantPreferences.backgroundMilliseconds = 500 + try await until { dormant.history.samples.count > hiddenCount } + dormantPreferences.backgroundEnabled = false + let disabledCount = dormant.history.samples.count + try await Task.sleep(for: .milliseconds(650)) + precondition(dormant.history.samples.count == disabledCount) + dormant.setPanelVisible(true) + try await until { dormant.history.samples.count > disabledCount } + precondition(dormant.history.samples.last?.breakBefore == true) + dormant.togglePause() print("PASS: defaults, 100ms quantization/clamping, independent persistence, invalid defaults, active/background wake, pause precedence, slow-interval initial processes and history boundary") } @MainActor private static func until(_ predicate: () -> Bool) async throws { diff --git a/kymoTests/SensorScheduleChecks.swift b/kymoTests/SensorScheduleChecks.swift new file mode 100644 index 0000000..efd79fd --- /dev/null +++ b/kymoTests/SensorScheduleChecks.swift @@ -0,0 +1,30 @@ +import Foundation + +@main struct SensorScheduleChecks { + static func main() { + var cpu = SensorSchedule() + var gpu = SensorSchedule() + precondition(cpu.isDue(at: 0) && gpu.isDue(at: 0)) + cpu.complete(available: true, at: 0) + gpu.complete(available: false, at: 0) + precondition(!cpu.isDue(at: 9) && cpu.isDue(at: 10)) + for now in stride(from: 10.0, through: 60, by: 10) { + cpu.complete(available: true, at: now) + if now < 60 { precondition(!gpu.isDue(at: now)) } + } + precondition(gpu.isDue(at: 60)) + gpu.complete(available: false, at: 60) + precondition(!gpu.isDue(at: 179) && gpu.isDue(at: 180)) + var now = 180.0 + for delay in [240.0, 480, 600, 600, 600] { + gpu.complete(available: false, at: now) + precondition(gpu.deadline == now + delay) + now += delay + } + gpu.complete(available: true, at: now) + precondition(gpu.deadline == now + 10) + gpu.complete(available: false, at: now + 10) + precondition(gpu.deadline == now + 70) + print("PASS: independent sensor cadences, exponential failure backoff, cap and recovery") + } +} diff --git a/tools/check.py b/tools/check.py index 2384473..92fbb42 100644 --- a/tools/check.py +++ b/tools/check.py @@ -18,6 +18,7 @@ CHECKS = {name: list(CORE) for name in ( "SamplingChecks", "SamplingIntervalChecks", "UnifiedPanelChecks", "MemoryChecks", "GPUStatisticsChecks", "StageCChecks", "MachPortChecks")} CHECKS.update({ + "SensorScheduleChecks": ["kymo/Core/Services/SensorSchedule.swift"], "TrendScrollChecks": CORE + ["kymo/UI/Charts/TrendScroll.swift"], "CPUCoreGridChecks": ["kymo/Features/MenuBar/CPUCoreGrid.swift", "kymo/Core/Services/CPUCoreTopology.swift", "kymo/Core/Extensions/MetricFormat.swift", "kymo/UI/Components/MetricProgressBar.swift"],