Files
Kymo/kymo/Features/MenuBar/PanelResourceAudit.swift
T
wangairnan b9abb970d9 feat(menubar): 用分色进度柱展示电量、供电与睡眠历史
记录系统睡眠和唤醒区间,保留真实采样空档。电量柱按固定间距从右侧滑入,以蓝色、绿色和橙黄色分别标记外接电源、电池和睡眠,支持悬浮查看历史。
2026-11-16 11:07:07 +08:00

133 lines
6.9 KiB
Swift

import AppKit
/// Explicit local measurement only. Never schedules work during normal launches.
@MainActor enum PanelResourceAudit {
#if DEBUG || KYMO_AUDIT
static let enabled = ProcessInfo.processInfo.environment["KYMO_RESOURCE_AUDIT"] == "1"
static func run(controller: MenuPanelController, metrics: MetricsStore) {
guard enabled else { return }
Task { @MainActor in
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 plots(in view: NSView?) -> [NSView] {
guard let view else { return [] }
let own = view is NativePanelCurve.PlotView || view is BatteryHistoryViewport ? [view] : []
return own + view.subviews.flatMap { plots(in: $0) }
}
@MainActor func mark(_ event: String) {
var report = metrics.snapshot
report.processes = metrics.processSnapshot
let views = plots(in: controller.panel.contentView)
SamplingDiagnostics.record(report, event: "audit." + event, hiddenHostAlive: controller.lastHiddenContent != nil,
windowNumber: controller.panel.isVisible ? controller.panel.windowNumber : nil,
hoveredPlots: views.filter { ($0 as? NativePanelCurve.PlotView)?.input?.hoveredIndex != nil || ($0 as? BatteryHistoryViewport)?.plot.hit != nil }.count, nativePlots: views.count,
pointerInsidePanel: controller.panel.isVisible && controller.panel.frame.contains(NSEvent.mouseLocation),
plotBounds: views.map { [Double($0.bounds.width), Double($0.bounds.height)] })
if event == "open1.10", ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1",
let content = controller.panel.contentView { capture(content) }
}
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
if ProcessInfo.processInfo.environment["KYMO_AUDIT_INTERACTIVE"] == "1" {
controller.show()
if let value = ProcessInfo.processInfo.environment["KYMO_AUDIT_SIZE"] {
let parts = value.split(separator: "x").compactMap { Double($0) }
if parts.count == 2, parts.allSatisfy({ $0.isFinite }), parts[0] >= 360, parts[1] >= 360 {
controller.panel.setContentSize(CGSize(width: min(parts[0], controller.panel.frame.width),
height: min(parts[1], controller.panel.frame.height)))
}
}
mark("interactive")
if ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1" {
await wait(10)
mark("open1.10")
}
return
}
let quick = ProcessInfo.processInfo.environment["KYMO_AUDIT_QUICK"] == "1"
mark("cold")
await wait(quick ? 3 : 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 && !quick {
metrics.togglePause(); mark("paused.0")
await wait(10); mark("paused.10")
metrics.togglePause(); mark("resumed")
}
controller.hide()
await wait(1); mark("closed\(cycle).1")
if quick {
await wait(4); mark("closed\(cycle).5")
} else {
await wait(9); mark("closed\(cycle).10")
await wait(20); mark("closed\(cycle).30")
}
}
controller.shutdown()
mark("complete")
NSApp.terminate(nil)
}
}
/// Captures only our own hosted panel, never the desktop. Excluded from normal Release.
private static func capture(_ content: NSView) {
guard content.bounds.width > 0, content.bounds.height > 0,
content.bounds.width * content.bounds.height <= 1_100_000,
let bitmap = content.bitmapImageRepForCachingDisplay(in: content.bounds) else { return }
content.cacheDisplay(in: content.bounds, to: bitmap)
guard let png = bitmap.representation(using: .png, properties: [:]),
let data = try? JSONSerialization.data(withJSONObject: ["event": "audit.capture", "png": png.base64EncodedString()]) else { return }
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
}
/// 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 func run(controller: MenuPanelController, metrics: MetricsStore) {}
#endif
}