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 let omitted = enabled ? ProcessInfo.processInfo.environment["KYMO_AUDIT_OMIT"] ?? "" : "" 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?) -> [NativePanelCurve.PlotView] { guard let view else { return [] } let own = (view as? NativePanelCurve.PlotView).map { [$0] } ?? [] 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.input?.hoveredIndex != 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)] }, animatedPlots: views.filter { $0.input?.animates == true }.count) 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 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) } } /// 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.makeStream() let cancelled = Task { 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 { 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 }