diff --git a/App/Dashboard/CPUSection.swift b/App/Dashboard/CPUSection.swift index fc69a63..eb57911 100644 --- a/App/Dashboard/CPUSection.swift +++ b/App/Dashboard/CPUSection.swift @@ -26,7 +26,7 @@ struct CPUDetails: View { let history: History let frequencies: FrequencySample? let temperature: Temperature? - let processes: TopProcesses? + let processes: TopApps? @Environment(\.temperatureUnit) private var temperatureUnit @@ -54,7 +54,7 @@ struct CPUDetails: View { ) } } - ProcessList.byCPU(processes, tint: DashboardSection.cpu.tint) + AppList.byCPU(processes, tint: DashboardSection.cpu.tint) } } diff --git a/App/Dashboard/DashboardComponents.swift b/App/Dashboard/DashboardComponents.swift index e5d7599..aa4e5f0 100644 --- a/App/Dashboard/DashboardComponents.swift +++ b/App/Dashboard/DashboardComponents.swift @@ -434,31 +434,31 @@ extension RateChart where Element == NetworkSample { } } -/// The busiest few processes by one measure, with bars relative to the busiest. +/// The busiest few apps by one measure, with bars relative to the busiest. /// Shows placeholder rows until the first usage arrives, so the details don't jump. -struct ProcessList: View { +struct AppList: View { let title: String - let processes: [ProcessUsage]? + let apps: [AppUsage]? let tint: Color - let measure: (ProcessUsage) -> Double - let value: (ProcessUsage) -> String + let measure: (AppUsage) -> Double + let value: (AppUsage) -> String var body: some View { VStack(alignment: .leading, spacing: 4) { DetailsHeading(title) - if let processes { - let top = processes.map(measure).max() ?? 0 - ForEach(processes) { process in - row(name: process.name, fraction: top > 0 ? measure(process) / top : 0, value: value(process)) + if let apps { + let top = apps.map(measure).max() ?? 0 + ForEach(apps) { usage in + row(app: usage.app, fraction: top > 0 ? measure(usage) / top : 0, value: value(usage)) } - if processes.isEmpty { - Text("No processes to show") + if apps.isEmpty { + Text("No apps to show") .font(.caption) .foregroundStyle(.secondary) } } else { ForEach(0..<4, id: \.self) { _ in - row(name: "Process name", fraction: 0, value: "0.0%") + row(app: AppIdentity(name: "App name", bundleURL: nil), fraction: 0, value: "0.0%") } .redacted(reason: .placeholder) } @@ -468,25 +468,44 @@ struct ProcessList: View { } } - private func row(name: String, fraction: Double, value: String) -> some View { + private func row(app: AppIdentity, fraction: Double, value: String) -> some View { HStack(spacing: 8) { - Text(name) + Image(nsImage: AppIcons.icon(for: app.bundleURL)) + .resizable() + .frame(width: 16, height: 16) + Text(app.name) .lineLimit(1) - .truncationMode(.middle) .frame(maxWidth: .infinity, alignment: .leading) ProgressBar(fraction: fraction, color: tint) .frame(width: 60) Text(value) .monospacedDigit() + .lineLimit(1) .frame(width: 64, alignment: .trailing) } .font(.callout) .accessibilityElement(children: .ignore) - .accessibilityLabel(name) + .accessibilityLabel(app.name) .accessibilityValue(value) } } +/// App icons, cached since the lists redraw on every reading. +@MainActor +private enum AppIcons { + private static var cache: [URL: NSImage] = [:] + private static let executable = NSWorkspace.shared.icon(for: .unixExecutable) + + /// The generic executable icon for processes outside an app. + static func icon(for bundleURL: URL?) -> NSImage { + guard let bundleURL else { return executable } + if let icon = cache[bundleURL] { return icon } + let icon = NSWorkspace.shared.icon(forFile: bundleURL.path(percentEncoded: false)) + cache[bundleURL] = icon + return icon + } +} + extension Power { /// Milliwatts below a watt, so idle processes don't all read "0.0 W". var processFormatted: String { @@ -584,9 +603,9 @@ func summary(_ parts: String?...) -> String? { /// Shown in place of a reading that isn't available. let missingValue = "—" -extension ProcessList { - static func byCPU(_ processes: TopProcesses?, title: String = "Top processes", tint: Color) -> some View { - ProcessList(title: title, processes: processes?.byCPU, tint: tint, measure: \.cpu.cores) { $0.cpu.formatted() } +extension AppList { + static func byCPU(_ processes: TopApps?, title: String = "Top apps", tint: Color) -> some View { + AppList(title: title, apps: processes?.byCPU, tint: tint, measure: \.cpu.cores) { $0.cpu.formatted() } .padding(.top, 4) } } diff --git a/App/Dashboard/GPUSection.swift b/App/Dashboard/GPUSection.swift index e226654..2c69379 100644 --- a/App/Dashboard/GPUSection.swift +++ b/App/Dashboard/GPUSection.swift @@ -28,7 +28,7 @@ struct GPUDetails: View { let frequency: Frequency? let maximumFrequency: Frequency? let totalMemory: ByteCount? - let processes: TopProcesses? + let processes: TopApps? @Environment(\.temperatureUnit) private var temperatureUnit @@ -51,7 +51,7 @@ struct GPUDetails: View { ) } // macOS doesn't expose GPU time per process without root, so this shows CPU use instead. - ProcessList.byCPU(processes, title: "Top processes by CPU", tint: DashboardSection.gpu.tint) + AppList.byCPU(processes, title: "Top apps by CPU", tint: DashboardSection.gpu.tint) } } diff --git a/App/Dashboard/MemorySection.swift b/App/Dashboard/MemorySection.swift index ae20640..f38664c 100644 --- a/App/Dashboard/MemorySection.swift +++ b/App/Dashboard/MemorySection.swift @@ -27,7 +27,7 @@ struct MemorySection: View { struct MemoryDetails: View { let memory: MemorySample let history: History - let processes: TopProcesses? + let processes: TopApps? var body: some View { VStack(alignment: .leading, spacing: 6) { @@ -54,12 +54,12 @@ struct MemoryDetails: View { if let swap = memory.swapUsed { DetailRow(label: "Swap used", value: swap.bytes == 0 ? "None" : swap.formatted(.memory)) } - ProcessList( - title: "Top processes", - processes: processes?.byMemory, + AppList( + title: "Top apps", + apps: processes?.byMemory, tint: DashboardSection.memory.tint, measure: { Double($0.memory.bytes) }, - value: { $0.memory.formatted(.memory) } + value: { $0.memory.formattedCompact() } ) .padding(.top, 4) } diff --git a/App/Dashboard/PowerSection.swift b/App/Dashboard/PowerSection.swift index b557bf3..6bca2c6 100644 --- a/App/Dashboard/PowerSection.swift +++ b/App/Dashboard/PowerSection.swift @@ -31,7 +31,7 @@ struct PowerDetails: View { let sensors: SensorSample? let battery: BatterySample? let history: History - let processes: TopProcesses? + let processes: TopApps? let isKeepingAwake: Bool @Environment(\.temperatureUnit) private var temperatureUnit @@ -70,9 +70,9 @@ struct PowerDetails: View { value: fan.isSpinning ? "\(fan.rpm.formatted(.number.precision(.fractionLength(0)))) RPM" : "Off" ) } - ProcessList( + AppList( title: "Top energy use", - processes: processes?.byPower, + apps: processes?.byPower, tint: DashboardSection.power.tint, measure: \.power.watts, value: \.power.processFormatted diff --git a/PRIVACY.md b/PRIVACY.md index a1b632d..6a19f97 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -9,9 +9,10 @@ made by Wolff.Tech. ## What the app reads Barometry reads CPU, GPU, memory, disk, network, sensor, and battery -statistics from macOS, and the names and resource usage of running processes -for the dashboard's top-process lists. These readings stay in memory for the -graphs and history and are never written to disk or sent anywhere. +statistics from macOS. For the dashboard's top-app lists, it also reads the +resource usage of running processes and the names of the apps responsible +for them. These readings stay in memory for the graphs and history and are +never written to disk or sent anywhere. ## What the app controls diff --git a/Packages/BarometryKit/Sources/BarometryKit/Model/ProcessSample.swift b/Packages/BarometryKit/Sources/BarometryKit/Model/ProcessSample.swift index b412d48..36db25a 100644 --- a/Packages/BarometryKit/Sources/BarometryKit/Model/ProcessSample.swift +++ b/Packages/BarometryKit/Sources/BarometryKit/Model/ProcessSample.swift @@ -22,32 +22,61 @@ public struct CPUUsage: Hashable, Comparable, Sendable { } } -/// One process's resource use over the last interval. -public struct ProcessUsage: Equatable, Sendable, Identifiable { +/// The app a group of processes belongs to. +public struct AppIdentity: Equatable, Sendable { + public let name: String + /// The app bundle, for its icon. Nil for processes outside an app, such as command-line tools. + public let bundleURL: URL? + + public init(name: String, bundleURL: URL?) { + self.name = name + self.bundleURL = bundleURL + } + + /// The outermost app bundle in the path, so helpers nested inside an app, such as + /// "Google Chrome Helper (Renderer).app", name the app itself. Otherwise the file name. + init(executablePath path: String) { + let url = URL(filePath: path) + let components = url.pathComponents + if let index = components.firstIndex(where: { $0.hasSuffix(".app") }) { + let bundle = URL(filePath: NSString.path(withComponents: Array(components[...index])), directoryHint: .isDirectory) + self.init(name: bundle.deletingPathExtension().lastPathComponent, bundleURL: bundle) + } else { + self.init(name: url.lastPathComponent, bundleURL: nil) + } + } +} + +/// One app's resource use over the last interval, summed over every process macOS holds it +/// responsible for. That includes helpers outside its bundle, such as Safari's +/// WebContent processes, and command-line tools started from it, as Activity Monitor's +/// Energy tab counts them. +public struct AppUsage: Equatable, Sendable, Identifiable { + /// The responsible process's ID. public let id: Int32 - public internal(set) var name: String + public internal(set) var app: AppIdentity public let cpu: CPUUsage /// Physical footprint, as Activity Monitor's "Memory" column. public let memory: ByteCount public let power: Power - public init(id: Int32, name: String, cpu: CPUUsage, memory: ByteCount, power: Power) { + public init(id: Int32, app: AppIdentity, cpu: CPUUsage, memory: ByteCount, power: Power) { self.id = id - self.name = name + self.app = app self.cpu = cpu self.memory = memory self.power = power } } -/// The busiest processes by each measure. Only the user's own processes are included, +/// The busiest apps by each measure. Only the user's own processes are included, /// since reading other users' needs root. -public struct TopProcesses: Equatable, Sendable { - public let byCPU: [ProcessUsage] - public let byMemory: [ProcessUsage] - public let byPower: [ProcessUsage] +public struct TopApps: Equatable, Sendable { + public let byCPU: [AppUsage] + public let byMemory: [AppUsage] + public let byPower: [AppUsage] - public init(byCPU: [ProcessUsage], byMemory: [ProcessUsage], byPower: [ProcessUsage]) { + public init(byCPU: [AppUsage], byMemory: [AppUsage], byPower: [AppUsage]) { self.byCPU = byCPU self.byMemory = byMemory self.byPower = byPower @@ -57,6 +86,8 @@ public struct TopProcesses: Equatable, Sendable { /// Cumulative counters for one process from `proc_pid_rusage`. struct ProcessReading: Equatable { let pid: Int32 + /// The process macOS holds responsible for this one, which may be itself. + let owner: Int32 /// Tells a reused process ID apart from the process that had it before. let startTime: UInt64 /// User and system time, in nanoseconds. @@ -66,9 +97,9 @@ struct ProcessReading: Equatable { let memory: UInt64 } -/// Turns successive readings of every process into the busiest few. +/// Turns successive readings of every process into the busiest few apps. struct ProcessUsageTracker { - /// Processes in each list. + /// Apps in each list. static let count = 4 /// Shortest span worth measuring. A tick that lands just after the first reading would /// otherwise rank processes by a few milliseconds of noise. @@ -77,13 +108,14 @@ struct ProcessUsageTracker { private var previous: (readings: [Int32: ProcessReading], time: ContinuousClock.Instant)? /// Returns nil for the first readings, since usage needs two, and for readings too soon - /// after the last, which are dropped. Only processes present in both readings are ranked. - /// `name` is called only for the processes that make a list. + /// after the last, which are dropped. Only processes present in both readings count. + /// `identify` is called only for the apps that make a list, with the responsible process + /// and one of its processes to fall back on if the responsible one has exited. mutating func update( _ readings: [ProcessReading], at time: ContinuousClock.Instant, - name: (Int32) -> String - ) -> TopProcesses? { + identify: (_ owner: Int32, _ member: Int32) -> AppIdentity + ) -> TopApps? { if let previous, time - previous.time < Self.minimumInterval { return nil } @@ -92,30 +124,48 @@ struct ProcessUsageTracker { guard let earlier else { return nil } let elapsed = (time - earlier.time).seconds - // Named later, since looking up a name costs more than reading a process. - let measured = readings.compactMap { reading -> ProcessUsage? in - guard let before = earlier.readings[reading.pid], before.startTime == reading.startTime else { return nil } - return ProcessUsage( - id: reading.pid, - name: "", - cpu: CPUUsage(cores: Double(reading.cpuTime &- before.cpuTime) / 1e9 / elapsed), - memory: ByteCount(bytes: Int64(clamping: reading.memory)), - power: Power(watts: Double(reading.energy &- before.energy) / 1e9 / elapsed) + var totals: [Int32: Totals] = [:] + for reading in readings { + guard let before = earlier.readings[reading.pid], before.startTime == reading.startTime else { continue } + totals[reading.owner, default: Totals(member: reading.pid)].add(reading, since: before) + } + // Identified later, since looking up an app costs more than reading a process. + let measured = totals.map { owner, total in + AppUsage( + id: owner, + app: AppIdentity(name: "", bundleURL: nil), + cpu: CPUUsage(cores: Double(total.cpuTime) / 1e9 / elapsed), + memory: ByteCount(bytes: Int64(clamping: total.memory)), + power: Power(watts: Double(total.energy) / 1e9 / elapsed) ) } - var names: [Int32: String] = [:] - func top(by value: (ProcessUsage) -> Value) -> [ProcessUsage] { + var apps: [Int32: AppIdentity] = [:] + func top(by value: (AppUsage) -> Value) -> [AppUsage] { measured.sorted { value($0) > value($1) }.prefix(Self.count).map { usage in - var named = usage - named.name = names[usage.id] ?? name(usage.id) - names[usage.id] = named.name - return named + var identified = usage + identified.app = apps[usage.id] ?? identify(usage.id, totals[usage.id]!.member) + apps[usage.id] = identified.app + return identified } } - return TopProcesses(byCPU: top(by: \.cpu), byMemory: top(by: \.memory), byPower: top(by: \.power)) + return TopApps(byCPU: top(by: \.cpu), byMemory: top(by: \.memory), byPower: top(by: \.power)) } mutating func reset() { previous = nil } + + /// One app's usage since the earlier readings. + private struct Totals { + let member: Int32 + var cpuTime: UInt64 = 0 + var energy: UInt64 = 0 + var memory: UInt64 = 0 + + mutating func add(_ reading: ProcessReading, since before: ProcessReading) { + cpuTime &+= reading.cpuTime &- before.cpuTime + energy &+= reading.energy &- before.energy + memory &+= reading.memory + } + } } diff --git a/Packages/BarometryKit/Sources/BarometryKit/Samplers/ProcessSampler.swift b/Packages/BarometryKit/Sources/BarometryKit/Samplers/ProcessSampler.swift index 4976627..a7fd24a 100644 --- a/Packages/BarometryKit/Sources/BarometryKit/Samplers/ProcessSampler.swift +++ b/Packages/BarometryKit/Sources/BarometryKit/Samplers/ProcessSampler.swift @@ -2,9 +2,11 @@ // SPDX-License-Identifier: GPL-3.0-only import Darwin +import Foundation -/// Reads every process the user can see with `proc_pid_rusage`. A full pass takes a few -/// milliseconds, so the monitor runs it only while process lists are on screen. +/// Reads every process the user can see with `proc_pid_rusage` and groups them by the app +/// responsible for them. A full pass takes a few milliseconds, so the monitor runs it only +/// while process lists are on screen. struct ProcessSampler { private var tracker = ProcessUsageTracker() private let timebase: mach_timebase_info_data_t = { @@ -14,9 +16,11 @@ struct ProcessSampler { }() /// Returns nil on the first call, since usage needs two readings. - mutating func sample() -> TopProcesses? { + mutating func sample() -> TopApps? { let readings = Self.processIDs().compactMap(reading) - return tracker.update(readings, at: .now, name: Self.name) + return tracker.update(readings, at: .now) { owner, member in + AppIdentity(executablePath: Self.path(owner) ?? Self.path(member) ?? Self.name(member)) + } } mutating func reset() { @@ -45,6 +49,7 @@ struct ProcessSampler { let cpuTicks = info.ri_user_time + info.ri_system_time return ProcessReading( pid: pid, + owner: Self.responsibleProcess(pid) ?? pid, startTime: info.ri_proc_start_abstime, cpuTime: cpuTicks * UInt64(timebase.numer) / UInt64(timebase.denom), energy: info.ri_energy_nj, @@ -52,16 +57,29 @@ struct ProcessSampler { ) } - /// The executable's file name, such as "Google Chrome Helper (Renderer)", which - /// `proc_name` truncates. - private static func name(_ pid: pid_t) -> String { - var path = [CChar](repeating: 0, count: Int(MAXPATHLEN) * 4) - if proc_pidpath(pid, &path, UInt32(path.count)) > 0 { - let fullPath = String(decoding: path.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) - if let last = fullPath.split(separator: "/").last { - return String(last) - } + /// Looked up at runtime, since it's private to macOS. It's what Activity Monitor uses to + /// count helpers, such as Safari's WebContent processes, toward their app. + private static let responsibilityLookup: (@convention(c) (pid_t) -> pid_t)? = { + // -2 is RTLD_DEFAULT, which Swift doesn't import. + guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "responsibility_get_pid_responsible_for_pid") else { + return nil } + return unsafeBitCast(symbol, to: (@convention(c) (pid_t) -> pid_t).self) + }() + + private static func responsibleProcess(_ pid: pid_t) -> pid_t? { + guard let owner = responsibilityLookup?(pid), owner > 0 else { return nil } + return owner + } + + private static func path(_ pid: pid_t) -> String? { + var path = [CChar](repeating: 0, count: Int(MAXPATHLEN) * 4) + guard proc_pidpath(pid, &path, UInt32(path.count)) > 0 else { return nil } + return String(decoding: path.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) + } + + /// The short name from `proc_name`, for when the path can't be read. + private static func name(_ pid: pid_t) -> String { var name = [CChar](repeating: 0, count: 64) proc_name(pid, &name, UInt32(name.count)) return String(decoding: name.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) diff --git a/Packages/BarometryKit/Sources/BarometryKit/SystemMonitor.swift b/Packages/BarometryKit/Sources/BarometryKit/SystemMonitor.swift index 13ada2f..a4e3b56 100644 --- a/Packages/BarometryKit/Sources/BarometryKit/SystemMonitor.swift +++ b/Packages/BarometryKit/Sources/BarometryKit/SystemMonitor.swift @@ -16,7 +16,7 @@ struct Snapshot: Sendable { var gpu: GPUSample? var sensors: SensorSample? var frequencies: FrequencySample? - var processes: TopProcesses? + var processes: TopApps? } /// Owns the samplers and runs them off the main actor. @@ -62,12 +62,12 @@ actor SamplingEngine { ) } - func sampleProcesses() -> TopProcesses? { + func sampleProcesses() -> TopApps? { processes.sample() } /// Forgets the last reading, so usage restarts cleanly rather than averaging over the gap. - private func stopSamplingProcesses() -> TopProcesses? { + private func stopSamplingProcesses() -> TopApps? { processes.reset() return nil } @@ -114,7 +114,7 @@ public final class SystemMonitor { public private(set) var sensors: SensorSample? public private(set) var frequencies: FrequencySample? /// Nil unless `samplesProcesses` is on, and for the first reading after it turns on. - public private(set) var processes: TopProcesses? + public private(set) var processes: TopApps? public private(set) var cpuHistory = History(capacity: historyCapacity) public private(set) var networkHistory = History(capacity: historyCapacity) diff --git a/Packages/BarometryKit/Tests/BarometryKitTests/ProcessUsageTrackerTests.swift b/Packages/BarometryKit/Tests/BarometryKitTests/ProcessUsageTrackerTests.swift index 9a4205e..337218b 100644 --- a/Packages/BarometryKit/Tests/BarometryKitTests/ProcessUsageTrackerTests.swift +++ b/Packages/BarometryKit/Tests/BarometryKitTests/ProcessUsageTrackerTests.swift @@ -7,10 +7,19 @@ import Testing struct ProcessUsageTrackerTests { private let start = ContinuousClock.now - - private func reading(_ pid: Int32, startTime: UInt64 = 1, cpuSeconds: Double = 0, joules: Double = 0, megabytes: UInt64 = 0) -> ProcessReading { + private let unnamed = AppIdentity(name: "", bundleURL: nil) + + private func reading( + _ pid: Int32, + owner: Int32? = nil, + startTime: UInt64 = 1, + cpuSeconds: Double = 0, + joules: Double = 0, + megabytes: UInt64 = 0 + ) -> ProcessReading { ProcessReading( pid: pid, + owner: owner ?? pid, startTime: startTime, cpuTime: UInt64(cpuSeconds * 1e9), energy: UInt64(joules * 1e9), @@ -21,14 +30,14 @@ struct ProcessUsageTrackerTests { @Test func firstReadingHasNoUsage() { var tracker = ProcessUsageTracker() - let result = tracker.update([reading(1)], at: start) { _ in "" } + let result = tracker.update([reading(1)], at: start) { _, _ in unnamed } #expect(result == nil) } @Test func ranksEachMeasureOverElapsedTime() throws { var tracker = ProcessUsageTracker() - _ = tracker.update([reading(1), reading(2), reading(3)], at: start) { _ in "" } + _ = tracker.update([reading(1), reading(2), reading(3)], at: start) { _, _ in unnamed } let result = tracker.update( [ @@ -37,12 +46,12 @@ struct ProcessUsageTrackerTests { reading(3, cpuSeconds: 0.2, joules: 2, megabytes: 200), ], at: start + .seconds(2) - ) { "p\($0)" } + ) { owner, _ in AppIdentity(name: "p\(owner)", bundleURL: nil) } let top = try #require(result) #expect(top.byCPU.map(\.id) == [1, 2, 3]) #expect(top.byCPU.first?.cpu == CPUUsage(cores: 1.5)) - #expect(top.byCPU.first?.name == "p1") + #expect(top.byCPU.first?.app.name == "p1") #expect(top.byMemory.map(\.id) == [2, 3, 1]) #expect(top.byPower.map(\.id) == [2, 3, 1]) #expect(top.byPower.first?.power == Power(watts: 2)) @@ -50,10 +59,10 @@ struct ProcessUsageTrackerTests { @Test func readingTooSoonKeepsTheEarlierBaseline() throws { var tracker = ProcessUsageTracker() - _ = tracker.update([reading(1)], at: start) { _ in "" } + _ = tracker.update([reading(1)], at: start) { _, _ in unnamed } - let tooSoon = tracker.update([reading(1, cpuSeconds: 0.01)], at: start + .milliseconds(10)) { _ in "" } - let later = tracker.update([reading(1, cpuSeconds: 1)], at: start + .seconds(1)) { _ in "" } + let tooSoon = tracker.update([reading(1, cpuSeconds: 0.01)], at: start + .milliseconds(10)) { _, _ in unnamed } + let later = tracker.update([reading(1, cpuSeconds: 1)], at: start + .seconds(1)) { _, _ in unnamed } #expect(tooSoon == nil) #expect(try #require(later).byCPU.first?.cpu == CPUUsage(cores: 1)) @@ -61,12 +70,12 @@ struct ProcessUsageTrackerTests { @Test func skipsNewAndReusedProcessIDs() throws { var tracker = ProcessUsageTracker() - _ = tracker.update([reading(1, startTime: 10)], at: start) { _ in "" } + _ = tracker.update([reading(1, startTime: 10)], at: start) { _, _ in unnamed } let result = tracker.update( [reading(1, startTime: 20, cpuSeconds: 5), reading(2, cpuSeconds: 5)], at: start + .seconds(1) - ) { _ in "" } + ) { _, _ in unnamed } #expect(try #require(result).byCPU.isEmpty) } @@ -74,21 +83,61 @@ struct ProcessUsageTrackerTests { @Test func keepsTheBusiestFewAndNamesOnlyThose() throws { var tracker = ProcessUsageTracker() let pids = Array(Int32(1)...10) - _ = tracker.update(pids.map { reading($0) }, at: start) { _ in "" } + _ = tracker.update(pids.map { reading($0) }, at: start) { _, _ in unnamed } var named: Set = [] let result = tracker.update( pids.map { reading($0, cpuSeconds: Double($0), joules: Double($0), megabytes: UInt64($0)) }, at: start + .seconds(1) - ) { pid in - named.insert(pid) - return "" + ) { owner, _ in + named.insert(owner) + return unnamed } #expect(try #require(result).byCPU.map(\.id) == [10, 9, 8, 7]) #expect(named == [10, 9, 8, 7]) } + @Test func sumsEachAppsProcesses() throws { + var tracker = ProcessUsageTracker() + let earlier = [reading(1), reading(2, owner: 1), reading(3, owner: 1), reading(4)] + _ = tracker.update(earlier, at: start) { _, _ in unnamed } + var identified: [Int32] = [] + + let result = tracker.update( + [ + reading(1, cpuSeconds: 0.5, joules: 1, megabytes: 100), + reading(2, owner: 1, cpuSeconds: 1, joules: 2, megabytes: 300), + reading(3, owner: 1, cpuSeconds: 1.5, joules: 3, megabytes: 400), + reading(4, cpuSeconds: 2, joules: 5, megabytes: 500), + ], + at: start + .seconds(1) + ) { owner, _ in + identified.append(owner) + return AppIdentity(name: "p\(owner)", bundleURL: nil) + } + + let top = try #require(result) + #expect(top.byCPU.map(\.id) == [1, 4]) + #expect(top.byCPU.first?.cpu == CPUUsage(cores: 3)) + #expect(top.byMemory.first?.memory == ByteCount(bytes: 800_000_000)) + #expect(top.byPower.first?.power == Power(watts: 6)) + #expect(top.byCPU.first?.app.name == "p1") + #expect(identified.sorted() == [1, 4]) + } + + @Test func namesTheOutermostAppInThePath() { + let helper = AppIdentity( + executablePath: "/Applications/Microsoft Edge.app/Contents/Frameworks/Microsoft Edge Framework.framework/Helpers/" + + "Microsoft Edge Helper (Renderer).app/Contents/MacOS/Microsoft Edge Helper (Renderer)" + ) + let tool = AppIdentity(executablePath: "/opt/homebrew/bin/claude") + + #expect(helper.name == "Microsoft Edge") + #expect(helper.bundleURL?.path(percentEncoded: false) == "/Applications/Microsoft Edge.app/") + #expect(tool == AppIdentity(name: "claude", bundleURL: nil)) + } + @Test func formatsUsageAboveOneCore() { #expect(CPUUsage(cores: 1.43).formatted(locale: Locale(identifier: "en_US")) == "143.0%") #expect(CPUUsage(cores: 0.061).formatted(locale: Locale(identifier: "en_US")) == "6.1%") diff --git a/README.md b/README.md index 7cec6c9..17f6e74 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Barometry shows CPU, GPU, memory, network, sensor, and battery readings as compa - Menu bar modules for CPU, GPU, memory, network, sensors, and battery - One menu bar item per module, or a single combined item in the order you choose - A dashboard in two styles, an instrument cluster of dials or a list of rows with live trends, with sections you can hide and reorder -- Details beside the dashboard: hover a section to see its history, breakdown, and top processes, or click it to keep them open +- Details beside the dashboard: hover a section to see its history, breakdown, and top apps, or click it to keep them open - Temperatures in °C or °F, and a choice of network interface - A refresh interval of 1, 2, or 5 seconds, with 1-second updates while the dashboard is open - Keep Awake, which stops idle sleep and keeps the display on, marked with a cup on the battery in the menu bar