The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.
A local performance recorder: Settings ▸ Performance and perf.json in Export Diagnostics (#91) (#115)
Victor Kildahlb3c73c0f060f
diff --git a/Packages/CraCore/Sources/CraCore/Perf/LogHistogram.swift b/Packages/CraCore/Sources/CraCore/Perf/LogHistogram.swiftnew file mode 100644index 0000000..d27d9c9--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/LogHistogram.swift@@ -0,0 +1,118 @@+import Foundation++/// Durations in power-of-two buckets: under 1 ms, 1–2, 2–4, 4–8 ms and so on, the last one+/// 32.8 s or more. A fixed 17 numbers whatever it counts, so a run loop that turns thousands of times a second costs+/// the same memory as a tab switch, and two histograms add up bucket by bucket.+public struct LogHistogram: Codable, Equatable, Sendable {+ public static let bucketCount = 17+ public private(set) var buckets: [Int]+ public private(set) var count = 0+ public private(set) var totalMs: Double = 0+ public private(set) var maxMs: Double = 0++ public init() { buckets = Array(repeating: 0, count: Self.bucketCount) }++ /// The bucket for a duration: 0 below 1 ms, then n for [2^(n-1), 2^n) ms.+ public static func bucket(ms: Double) -> Int {+ guard ms >= 1, ms.isFinite else { return ms.isFinite ? 0 : bucketCount - 1 }+ let whole = UInt64(min(ms, 1e12))+ return min(64 - whole.leadingZeroBitCount, bucketCount - 1)+ }++ /// The lower edge of a bucket in milliseconds.+ public static func lowerBound(_ bucket: Int) -> Double { bucket <= 0 ? 0 : Double(1 << (bucket - 1)) }++ public mutating func record(_ ms: Double) {+ let ms = max(0, ms)+ buckets[Self.bucket(ms: ms)] += 1+ count += 1+ totalMs += ms.isFinite ? ms : 0+ if ms > maxMs, ms.isFinite { maxMs = ms }+ }++ public mutating func add(_ other: LogHistogram) {+ for i in buckets.indices { buckets[i] += other.buckets[i] }+ count += other.count+ totalMs += other.totalMs+ maxMs = max(maxMs, other.maxMs)+ }++ /// At most this many milliseconds for `fraction` of the samples: the upper edge of the+ /// bucket the percentile falls in (never above the largest sample). 0 when empty.+ public func percentile(_ fraction: Double) -> Double {+ guard count > 0 else { return 0 }+ let rank = max(1, Int((Double(count) * min(max(fraction, 0), 1)).rounded(.up)))+ var seen = 0+ for (i, n) in buckets.enumerated() {+ seen += n+ if seen >= rank { return min(Self.lowerBound(i + 1), maxMs) }+ }+ return maxMs+ }++ public var meanMs: Double { count == 0 ? 0 : totalMs / Double(count) }++ public init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ let stored = try c.decode([Int].self, forKey: .buckets)+ buckets = Array((stored + Array(repeating: 0, count: Self.bucketCount)).prefix(Self.bucketCount))+ count = try c.decode(Int.self, forKey: .count)+ totalMs = try c.decode(Double.self, forKey: .totalMs)+ maxMs = try c.decode(Double.self, forKey: .maxMs)+ }+}++/// The newest `capacity` elements, oldest first. Appending past the capacity drops the oldest,+/// so the recorder's memory has a ceiling however long Cra runs.+public struct PerfRing<Element> {+ public let capacity: Int+ private var storage: [Element] = []+ private var head = 0+ /// Everything ever appended, including what has been dropped.+ public private(set) var appended = 0++ public init(capacity: Int) { self.capacity = max(1, capacity) }++ public mutating func append(_ e: Element) {+ appended += 1+ if storage.count < capacity { storage.append(e); return }+ storage[head] = e+ head = (head + 1) % capacity+ }++ public var elements: [Element] { Array(storage[head...] + storage[..<head]) }+ public var last: Element? { storage.isEmpty ? nil : storage[(head + storage.count - 1) % storage.count] }+ public var count: Int { storage.count }+ public var isEmpty: Bool { storage.isEmpty }++ public mutating func removeAll() { storage = []; head = 0 }++ /// The last element, changed in place (a history bucket still filling).+ public mutating func updateLast(_ change: (inout Element) -> Void) {+ guard !storage.isEmpty else { return }+ change(&storage[(head + storage.count - 1) % storage.count])+ }+}++extension PerfRing: Equatable where Element: Equatable {+ public static func == (a: PerfRing, b: PerfRing) -> Bool { a.capacity == b.capacity && a.elements == b.elements }+}++extension PerfRing: Sendable where Element: Sendable {}++extension PerfRing: Codable where Element: Codable {+ private enum CodingKeys: String, CodingKey { case capacity, elements }++ public init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ self.init(capacity: try c.decode(Int.self, forKey: .capacity))+ for e in try c.decode([Element].self, forKey: .elements) { append(e) }+ appended = count+ }++ public func encode(to encoder: Encoder) throws {+ var c = encoder.container(keyedBy: CodingKeys.self)+ try c.encode(capacity, forKey: .capacity)+ try c.encode(elements, forKey: .elements)+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfHistory.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfHistory.swiftnew file mode 100644index 0000000..d9b32c8--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfHistory.swift@@ -0,0 +1,98 @@+import Foundation++/// `Perf/history.json`: the last 24 hours in 5-minute buckets, across launches, written every+/// 15 minutes and when Cra quits. One-minute buckets would be about 1.1 MB, and rewriting that+/// every 15 minutes would break the write budget (GitHub #91).+public struct PerfHistory: Codable, Equatable, Sendable {+ public static let bucketSeconds: Double = 300+ public static let capacity = 288++ /// Launches of this data folder while recording was on.+ public var launches = 0+ public var firstLaunchAt: Date?+ /// The last session that quitting closed normally (an abnormal one leaves its marker instead).+ public var lastSession: PerfPreviousSession?+ public var buckets = PerfRing<PerfHistoryBucket>(capacity: PerfHistory.capacity)++ public init() {}++ /// Adds a sample to its 5-minute bucket, starting a new bucket when the clock moved past the+ /// last one. A clock that went back (the user changed it) starts a new bucket too.+ public mutating func record(_ sample: PerfHistorySample, at date: Date) {+ let start = Date(timeIntervalSince1970: (date.timeIntervalSince1970 / Self.bucketSeconds).rounded(.down) * Self.bucketSeconds)+ if buckets.last?.start == start {+ buckets.updateLast { $0.add(sample) }+ } else {+ var b = PerfHistoryBucket(start: start)+ b.add(sample)+ buckets.append(b)+ }+ }++ /// Buckets that started within `seconds` before `now`.+ public func recent(_ seconds: Double, now: Date) -> [PerfHistoryBucket] {+ buckets.elements.filter { $0.start > now.addingTimeInterval(-seconds - Self.bucketSeconds) && $0.start <= now }+ }++ private enum CodingKeys: String, CodingKey { case launches, firstLaunchAt, lastSession, buckets }++ public init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ launches = try c.decodeIfPresent(Int.self, forKey: .launches) ?? 0+ firstLaunchAt = try c.decodeIfPresent(Date.self, forKey: .firstLaunchAt)+ lastSession = try c.decodeIfPresent(PerfPreviousSession.self, forKey: .lastSession)+ // A file from a build with another capacity keeps its newest buckets.+ var ring = PerfRing<PerfHistoryBucket>(capacity: Self.capacity)+ for b in (try c.decodeIfPresent(PerfRing<PerfHistoryBucket>.self, forKey: .buckets))?.elements ?? [] { ring.append(b) }+ buckets = ring+ }+}++/// What one 5-second sample adds to the history: levels, and counts since the sample before.+public struct PerfHistorySample: Equatable, Sendable {+ public var cpuPct: Double+ public var footprintBytes: Int64+ public var stalls: Int+ public var longStalls: Int+ public var longTasks: Int+ public var rendererCrashes: Int+ public var liveTabs: Int++ public init(cpuPct: Double, footprintBytes: Int64, stalls: Int = 0, longStalls: Int = 0, longTasks: Int = 0,+ rendererCrashes: Int = 0, liveTabs: Int = 0) {+ self.cpuPct = cpuPct+ self.footprintBytes = footprintBytes+ self.stalls = stalls+ self.longStalls = longStalls+ self.longTasks = longTasks+ self.rendererCrashes = rendererCrashes+ self.liveTabs = liveTabs+ }+}++public struct PerfHistoryBucket: Codable, Equatable, Sendable {+ public var start: Date+ public var samples = 0+ /// Cra and its helpers, percent of one core, averaged over the bucket.+ public var cpuPct: Double = 0+ /// The largest memory footprint of Cra and its helpers in the bucket.+ public var footprintMB: Int = 0+ public var stalls = 0+ public var longStalls = 0+ public var longTasks = 0+ public var rendererCrashes = 0+ public var liveTabs = 0++ public init(start: Date) { self.start = start }++ public mutating func add(_ s: PerfHistorySample) {+ cpuPct = (cpuPct * Double(samples) + s.cpuPct) / Double(samples + 1)+ samples += 1+ footprintMB = max(footprintMB, Int(s.footprintBytes >> 20))+ stalls += s.stalls+ longStalls += s.longStalls+ longTasks += s.longTasks+ rendererCrashes += s.rendererCrashes+ liveTabs = max(liveTabs, s.liveTabs)+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swiftnew file mode 100644index 0000000..5e16366--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift@@ -0,0 +1,123 @@+import Foundation++/// A plain-language reading of a report for the Performance pane's Overview.+public struct PerfInsight: Codable, Equatable, Sendable, Identifiable {+ public enum Severity: String, Codable, Sendable { case info, warning }++ public var id: String+ public var severity: Severity+ public var title: String+ public var detail: String++ public init(id: String, severity: Severity, title: String, detail: String) {+ self.id = id+ self.severity = severity+ self.title = title+ self.detail = detail+ }+}++/// The rules behind the insights. Each one reads the report alone, so the pane, perf.json and+/// a test all agree.+public enum PerfInsights {+ public static let lowDiskBytes: Int64 = 5 << 30+ public static let largeFootprintBytes: Int64 = 8 << 30+ /// Short stalls per hour of the session that are worth a line.+ public static let frequentStallsPerHour = 30.0++ public static func evaluate(_ r: PerfReport) -> [PerfInsight] {+ var out: [PerfInsight] = []+ if let p = r.session.previous, p.abnormal {+ out.append(PerfInsight(id: "previous-abnormal", severity: .warning, title: "The last session ended without quitting",+ detail: "Cra \(p.craVersion) crashed, was forced to quit or the Mac lost power. Its last minute is in the export."))+ }+ let m = r.mainThread+ if m.longStalls > 0 {+ out.append(PerfInsight(id: "freezes", severity: .warning,+ title: "Cra froze \(m.longStalls) time\(m.longStalls == 1 ? "" : "s") for a second or more",+ detail: "The longest lasted \(Self.duration(m.longestMs))\(m.hangs > 0 ? "; \(m.hangs) went past 2 s" : "")."))+ }+ let hours = max(r.session.uptimeSeconds / 3600, 1.0 / 12)+ if m.stalls >= 5, Double(m.stalls) / hours >= frequentStallsPerHour {+ out.append(PerfInsight(id: "stalls", severity: .info, title: "Frequent short stalls",+ detail: "\(m.stalls) pauses of a quarter second or more since launch."))+ }+ let crashes = r.counters[PerfCounter.rendererTerminated.rawValue]?.values.reduce(0, +) ?? 0+ if crashes > 0 {+ out.append(PerfInsight(id: "renderer-crashes", severity: .warning,+ title: "\(crashes) page\(crashes == 1 ? "" : "s") stopped (“Aw, Snap!”)",+ detail: "A page's process crashed, ran out of memory or was ended."))+ }+ let unresponsive = r.counters[PerfCounter.rendererUnresponsive.rawValue]?.values.reduce(0, +) ?? 0+ if unresponsive > 0 {+ out.append(PerfInsight(id: "unresponsive", severity: .warning, title: "\(unresponsive) page\(unresponsive == 1 ? "" : "s") stopped responding",+ detail: "Chromium asked whether to wait or close the page."))+ }+ if let s = r.system {+ if s.memoryPressure == .warning || s.memoryPressure == .critical {+ out.append(PerfInsight(id: "memory-pressure", severity: .warning, title: "The Mac is short of memory",+ detail: "macOS reports \(s.memoryPressure.rawValue) memory pressure; pages may reload and everything slows down."))+ }+ if s.thermalState == "serious" || s.thermalState == "critical" {+ out.append(PerfInsight(id: "thermal", severity: .info, title: "The Mac is running hot",+ detail: "macOS slows the processor down until it cools."))+ }+ if s.lowPowerMode {+ out.append(PerfInsight(id: "low-power", severity: .info, title: "Low Power Mode is on", detail: "Video and scrolling may be less smooth."))+ }+ }+ if let free = r.storage.freeDiskBytes ?? r.system?.freeDiskBytes, free < lowDiskBytes {+ out.append(PerfInsight(id: "low-disk", severity: .warning, title: "The disk is almost full",+ detail: "\(bytes(free)) free. Chromium's caches and swap need room."))+ }+ let footprint = r.processes.reduce(Int64(0)) { $0 + $1.footprintBytes }+ if footprint >= largeFootprintBytes {+ let slept = r.tabs.latest?.slept ?? 0+ out.append(PerfInsight(id: "footprint", severity: .info, title: "Cra uses \(bytes(footprint)) of memory",+ detail: slept > 0 ? "Tab sleeping has \(slept) tab\(slept == 1 ? "" : "s") asleep." : "Tab sleeping (Settings ▸ Tabs) closes pages you haven't looked at in a while."))+ }+ return out+ }++ public static func duration(_ ms: Double) -> String {+ ms >= 1000 ? String(format: "%.1f s", ms / 1000) : "\(Int(ms.rounded())) ms"+ }++ public static func bytes(_ n: Int64) -> String {+ let gb = Double(n) / Double(1 << 30)+ return gb >= 1 ? String(format: "%.1f GB", gb) : "\(n >> 20) MB"+ }+}++/// Settings ▸ Performance ▸ Copy Summary: a few lines to paste into an issue. Never a site name,+/// whatever "Hide site names" says: a summary gets pasted where nobody reviews the zip.+public enum PerfSummary {+ public static func text(_ r: PerfReport) -> String {+ let m = r.mainThread+ var lines = [+ "Cra \(r.session.craVersion), Chromium \(r.session.chromiumVersion), launch \(r.session.launch), up \(Int(r.session.uptimeSeconds / 60)) min",+ "Main thread: \(m.stalls) stalls ≥250 ms, \(m.longStalls) ≥1 s, \(m.hangs) ≥2 s, longest \(PerfInsights.duration(m.longestMs)) (p99 pass \(PerfInsights.duration(m.passes.percentile(0.99))))",+ ]+ if let p = r.session.previous { lines.append("Previous session: \(p.abnormal ? "ended without quitting" : "quit normally") (Cra \(p.craVersion))") }+ for g in r.processes where g.count > 0 {+ lines.append("\(g.kind.rawValue) ×\(g.count): \(String(format: "%.1f", g.cpuPct)) % CPU, \(PerfInsights.bytes(g.footprintBytes))")+ }+ if let s = r.system {+ lines.append("Mac: \(s.cpuPct.map { String(format: "%.0f", $0) + " % CPU" } ?? "CPU n/a"), memory \(s.memoryPressure.rawValue), thermal \(s.thermalState)\(s.lowPowerMode ? ", Low Power Mode" : "")")+ }+ if let t = r.tabs.latest {+ lines.append("Tabs: \(t.tabs), \(t.live) loaded, \(t.slept) asleep, \(t.windows) window\(t.windows == 1 ? "" : "s")")+ }+ for (key, metric) in [("tab switch", PerfMetric.tabSwitch), ("page create", .pageCreate), ("page load", .pageLoad)] {+ if let h = r.timings[metric.rawValue], h.count > 0 {+ lines.append("\(key): median \(PerfInsights.duration(h.percentile(0.5))), p95 \(PerfInsights.duration(h.percentile(0.95))) (\(h.count))")+ }+ }+ if r.tabs.longTasks > 0 { lines.append("Page long tasks: \(r.tabs.longTasks), \(PerfInsights.duration(r.tabs.longTaskMs)) in all") }+ for (counter, keys) in r.counters.sorted(by: { $0.key < $1.key }) where !keys.isEmpty {+ lines.append("\(counter): " + keys.sorted { $0.key < $1.key }.map { "\($0.key) ×\($0.value)" }.joined(separator: ", "))+ }+ for i in r.insights { lines.append("• \(i.title)") }+ return lines.joined(separator: "\n") + "\n"+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfMetric.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfMetric.swiftnew file mode 100644index 0000000..2d6a431--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfMetric.swift@@ -0,0 +1,60 @@+import Foundation++/// What the performance recorder times, in milliseconds (GitHub #91). The raw values are the+/// keys in perf.json, so renaming one changes the file's schema.+public enum PerfMetric: String, Codable, CaseIterable, Sendable {+ /// One pass of the main run loop between two points where it could take input. The main+ /// thread is also Chromium's browser UI thread: a long pass is a frozen window.+ case mainLoop+ /// Putting other tabs on screen (BrowserManager.show), the part on the main thread.+ case tabSwitch+ /// Making a tab's page: Chromium's view, its window and the browser object.+ case pageCreate+ /// A main-frame navigation, from loading to loaded.+ case pageLoad+ /// A tab that tab sleeping closed, shown again until its page finished loading.+ case tabWake+ /// A data-folder JSON file decoded at launch, or encoded and written.+ case jsonLoad+ case jsonSave+ /// Long tasks (50 ms or more) in the visible tab's page.+ case longTask+}++/// What the recorder counts. Some carry a key (`loadError` the error code, `sleepRefusal` the+/// reason); perf.json lists those per key.+public enum PerfCounter: String, Codable, CaseIterable, Sendable {+ /// A main-frame load that failed; the key is Chromium's net error code.+ case loadError+ /// A renderer that ended; the key is how (crashed, killed, out of memory…).+ case rendererTerminated+ /// Chromium's "Page Unresponsive" (about 15 s without handling input), and its recovery.+ case rendererUnresponsive+ case rendererResponsive+ /// Tab sleeping closed a page, or kept one awake; the key is why.+ case tabSlept+ case sleepRefusal+}++/// The kinds of process Cra runs, from the name macOS gives each one.+public enum PerfProcessKind: String, Codable, CaseIterable, Sendable {+ case browser, renderer, gpu, utility, other++ /// Chromium's `--type=` argument says what a helper is: CEF runs its GPU process from the plain+ /// `Cra Helper` app, so the app's name alone would call it a utility. Without one (it couldn't+ /// be read), the name decides: `Cra Helper (Renderer)`, `(GPU)`, other helpers are utilities, and+ /// anything that isn't a helper (`sample` at a hang) is other.+ public static func of(name: String, isSelf: Bool, type: String? = nil) -> PerfProcessKind {+ if isSelf { return .browser }+ switch type {+ case "renderer": return .renderer+ case "gpu-process": return .gpu+ case .some: return .utility+ case nil: break+ }+ guard name.contains("Helper") else { return .other }+ if name.hasSuffix("(Renderer)") { return .renderer }+ if name.hasSuffix("(GPU)") { return .gpu }+ return .utility+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfProcessTable.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfProcessTable.swiftnew file mode 100644index 0000000..8465228--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfProcessTable.swift@@ -0,0 +1,77 @@+import Foundation++/// One process as libproc read it at one sample. Nil numbers: macOS refused them (the process+/// ended between listing and reading, or isn't Cra's to read).+public struct PerfProcessReading: Equatable, Sendable {+ public var pid: Int32+ public var kind: PerfProcessKind+ /// User plus system CPU time since the process started, in nanoseconds.+ public var cpuNs: UInt64?+ public var footprintBytes: Int64?+ public var diskReadBytes: Int64?+ public var diskWriteBytes: Int64?+ public var wakeups: Int64?++ public init(pid: Int32, kind: PerfProcessKind, cpuNs: UInt64?, footprintBytes: Int64?, diskReadBytes: Int64?,+ diskWriteBytes: Int64?, wakeups: Int64?) {+ self.pid = pid+ self.kind = kind+ self.cpuNs = cpuNs+ self.footprintBytes = footprintBytes+ self.diskReadBytes = diskReadBytes+ self.diskWriteBytes = diskWriteBytes+ self.wakeups = wakeups+ }+}++/// Turns readings taken every few seconds into per-kind groups: CPU over the interval since the+/// last reading, and how many processes of each kind came and went (renderer churn).+public struct PerfProcessTable: Sendable {+ private var previousCPU: [Int32: UInt64] = [:]+ private var previousKinds: [Int32: PerfProcessKind]?+ private var previousAtNs: UInt64 = 0+ private var started: [PerfProcessKind: Int] = [:]+ private var ended: [PerfProcessKind: Int] = [:]++ public init() {}++ /// `atNs` is a monotonic clock (nanoseconds since boot). The first update has no interval+ /// yet: CPU reads 0, and the processes already running don't count as started.+ public mutating func update(_ readings: [PerfProcessReading], atNs: UInt64) -> [PerfProcessGroup] {+ let interval = previousAtNs > 0 && atNs > previousAtNs ? Double(atNs - previousAtNs) : 0+ var groups = Dictionary(uniqueKeysWithValues: PerfProcessKind.allCases.map { ($0, PerfProcessGroup(kind: $0, available: false)) })+ var cpu: [Int32: UInt64] = [:]+ for r in readings {+ var g = groups[r.kind]!+ g.count += 1+ if let now = r.cpuNs {+ g.available = true+ cpu[r.pid] = now+ if interval > 0, let before = previousCPU[r.pid], now >= before {+ g.cpuPct += Double(now - before) / interval * 100+ }+ }+ g.footprintBytes += r.footprintBytes ?? 0+ g.diskReadBytes += r.diskReadBytes ?? 0+ g.diskWriteBytes += r.diskWriteBytes ?? 0+ g.wakeups += r.wakeups ?? 0+ groups[r.kind] = g+ }+ let kinds = Dictionary(readings.map { ($0.pid, $0.kind) }, uniquingKeysWith: { a, _ in a })+ if let before = previousKinds {+ for (pid, kind) in kinds where before[pid] == nil { started[kind, default: 0] += 1 }+ for (pid, kind) in before where kinds[pid] == nil { ended[kind, default: 0] += 1 }+ }+ previousKinds = kinds+ previousCPU = cpu+ previousAtNs = atNs+ return PerfProcessKind.allCases.compactMap { kind in+ guard var g = groups[kind] else { return nil }+ g.started = started[kind] ?? 0+ g.ended = ended[kind] ?? 0+ // A kind with no process now and none ever seen is left out; one that had some keeps its churn.+ if g.count == 0 { g.available = true }+ return g.count > 0 || g.started > 0 || g.ended > 0 ? g : nil+ }+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfReport.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfReport.swiftnew file mode 100644index 0000000..e9110e5--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfReport.swift@@ -0,0 +1,302 @@+import Foundation++/// perf.json in Help ▸ Export Diagnostics, and the black box Cra keeps in `Perf/blackbox.json`+/// (GitHub #91). Numbers and site names only: no addresses, paths, titles or page text. Sites+/// appear where something happened on one (a stall while it was on screen, a renderer that+/// crashed) and become `site-N` with "Hide site names".+public struct PerfReport: Codable, Equatable, Sendable {+ /// Bumped when a field changes meaning or goes away; new fields don't bump it.+ public static let currentSchema = 1++ public var schema = PerfReport.currentSchema+ public var generatedAt: Date+ public var session: PerfSessionInfo+ public var selfCost: PerfSelfCost+ public var mainThread: MainThread+ public var processes: [PerfProcessGroup]+ public var system: PerfSystemSample?+ public var tabs: Tabs+ public var timings: [String: LogHistogram]+ public var counters: [String: [String: Int]]+ public var startup: [String: Double]+ public var storage: Storage+ public var events: [PerfEvent]+ public var insights: [PerfInsight]++ public struct MainThread: Codable, Equatable, Sendable {+ public var passes: LogHistogram+ public var stalls: Int+ public var longStalls: Int+ public var hangs: Int+ /// Stalls in a tracking or modal loop (a held menu, a drag, an alert): not freezes.+ public var outsideFreezes: Int+ public var longestMs: Double+ public var recent: [PerfStall]++ public init(passes: LogHistogram = LogHistogram(), stalls: Int = 0, longStalls: Int = 0, hangs: Int = 0,+ outsideFreezes: Int = 0, longestMs: Double = 0, recent: [PerfStall] = []) {+ self.passes = passes+ self.stalls = stalls+ self.longStalls = longStalls+ self.hangs = hangs+ self.outsideFreezes = outsideFreezes+ self.longestMs = longestMs+ self.recent = recent+ }+ }++ public struct Tabs: Codable, Equatable, Sendable {+ public var latest: PerfTabCounts?+ /// The page long tasks in the visible tab, summed since launch.+ public var longTasks: Int+ public var longTaskMs: Double++ public init(latest: PerfTabCounts? = nil, longTasks: Int = 0, longTaskMs: Double = 0) {+ self.latest = latest+ self.longTasks = longTasks+ self.longTaskMs = longTaskMs+ }+ }++ public struct Storage: Codable, Equatable, Sendable {+ /// The Chromium profile without its caches, and the caches; measured at export.+ public var profileBytes: Int64?+ public var cacheBytes: Int64?+ public var freeDiskBytes: Int64?++ public init(profileBytes: Int64? = nil, cacheBytes: Int64? = nil, freeDiskBytes: Int64? = nil) {+ self.profileBytes = profileBytes+ self.cacheBytes = cacheBytes+ self.freeDiskBytes = freeDiskBytes+ }+ }++ public init(generatedAt: Date, session: PerfSessionInfo, selfCost: PerfSelfCost, mainThread: MainThread,+ processes: [PerfProcessGroup], system: PerfSystemSample?, tabs: Tabs, timings: [String: LogHistogram],+ counters: [String: [String: Int]], startup: [String: Double], storage: Storage, events: [PerfEvent],+ insights: [PerfInsight]) {+ self.generatedAt = generatedAt+ self.session = session+ self.selfCost = selfCost+ self.mainThread = mainThread+ self.processes = processes+ self.system = system+ self.tabs = tabs+ self.timings = timings+ self.counters = counters+ self.startup = startup+ self.storage = storage+ self.events = events+ self.insights = insights+ }++ /// The encoder for every Perf file: sorted keys (a diff between two reports reads), ISO dates.+ public static func encoder(pretty: Bool = true) -> JSONEncoder {+ let e = JSONEncoder()+ e.outputFormatting = pretty ? [.prettyPrinted, .sortedKeys] : [.sortedKeys]+ e.dateEncodingStrategy = .iso8601+ return e+ }++ public static let decoder: JSONDecoder = {+ let d = JSONDecoder()+ d.dateDecodingStrategy = .iso8601+ return d+ }()++ /// Every site name in the report, for "Hide site names".+ public var sites: Set<String> {+ var s = Set(mainThread.recent.compactMap(\.site))+ s.formUnion(events.compactMap(\.site))+ return s+ }+}++/// Which launch this is, and how the one before it ended.+public struct PerfSessionInfo: Codable, Equatable, Sendable {+ /// Random per launch: matches a report to its hang files. Not an installation id.+ public var id: String+ /// How many times this data folder has been started, this launch included.+ public var launch: Int+ public var startedAt: Date+ public var uptimeSeconds: Double+ public var craVersion: String+ public var chromiumVersion: String+ /// This launch ran the onboarding (a fresh install, or one that never finished it).+ public var onboarding: Bool+ public var firstLaunchAt: Date?+ public var previous: PerfPreviousSession?+ /// Whether this Cra writes files under Perf/ (it owns the data folder and recording is on).+ public var writesFiles: Bool++ public init(id: String, launch: Int, startedAt: Date, uptimeSeconds: Double, craVersion: String, chromiumVersion: String,+ onboarding: Bool, firstLaunchAt: Date?, previous: PerfPreviousSession?, writesFiles: Bool) {+ self.id = id+ self.launch = launch+ self.startedAt = startedAt+ self.uptimeSeconds = uptimeSeconds+ self.craVersion = craVersion+ self.chromiumVersion = chromiumVersion+ self.onboarding = onboarding+ self.firstLaunchAt = firstLaunchAt+ self.previous = previous+ self.writesFiles = writesFiles+ }+}++/// What the profiler itself costs, so CI can hold it to its budget (under 0.1 % of a core).+public struct PerfSelfCost: Codable, Equatable, Sendable {+ public var cpuMs: Double+ public var cpuPct: Double+ /// Main run-loop callbacks observed, and their estimated cost (included in `cpuMs`).+ public var observerCallbacks: Int+ public var observerMs: Double+ public var bytesWritten: Int+ public var writes: Int+ /// The recorder's own data in memory, estimated from its counts.+ public var memoryBytes: Int++ public init(cpuMs: Double = 0, cpuPct: Double = 0, observerCallbacks: Int = 0, observerMs: Double = 0, bytesWritten: Int = 0,+ writes: Int = 0, memoryBytes: Int = 0) {+ self.cpuMs = cpuMs+ self.cpuPct = cpuPct+ self.observerCallbacks = observerCallbacks+ self.observerMs = observerMs+ self.bytesWritten = bytesWritten+ self.writes = writes+ self.memoryBytes = memoryBytes+ }+}++/// Cra's processes of one kind at the last sample, and over the session.+public struct PerfProcessGroup: Codable, Equatable, Sendable {+ public var kind: PerfProcessKind+ public var count: Int+ /// Percent of one core over the last sample interval, summed over the group.+ public var cpuPct: Double+ public var footprintBytes: Int64+ public var diskReadBytes: Int64+ public var diskWriteBytes: Int64+ /// Wakeups since the processes started: in the file, not the pane (the same call as CPU time).+ public var wakeups: Int64+ /// Processes of this kind that started and ended since launch (renderers coming and going).+ public var started: Int+ public var ended: Int+ /// False when macOS refused the numbers for every process of the group.+ public var available: Bool++ public init(kind: PerfProcessKind, count: Int = 0, cpuPct: Double = 0, footprintBytes: Int64 = 0, diskReadBytes: Int64 = 0,+ diskWriteBytes: Int64 = 0, wakeups: Int64 = 0, started: Int = 0, ended: Int = 0, available: Bool = true) {+ self.kind = kind+ self.count = count+ self.cpuPct = cpuPct+ self.footprintBytes = footprintBytes+ self.diskReadBytes = diskReadBytes+ self.diskWriteBytes = diskWriteBytes+ self.wakeups = wakeups+ self.started = started+ self.ended = ended+ self.available = available+ }+}++/// The Mac as a whole at the last sample.+public struct PerfSystemSample: Codable, Equatable, Sendable {+ public enum Pressure: String, Codable, Sendable { case normal, warning, critical, unknown }++ /// All cores together, 0–100.+ public var cpuPct: Double?+ public var memoryPressure: Pressure+ /// ProcessInfo.ThermalState: nominal, fair, serious, critical.+ public var thermalState: String+ public var lowPowerMode: Bool+ public var freeDiskBytes: Int64?++ public init(cpuPct: Double?, memoryPressure: Pressure, thermalState: String, lowPowerMode: Bool, freeDiskBytes: Int64?) {+ self.cpuPct = cpuPct+ self.memoryPressure = memoryPressure+ self.thermalState = thermalState+ self.lowPowerMode = lowPowerMode+ self.freeDiskBytes = freeDiskBytes+ }++ /// kern.memorystatus_vm_pressure_level: 1 normal, 2 warning, 4 critical.+ public static func pressure(level: Int32?) -> Pressure {+ switch level {+ case 1: return .normal+ case 2: return .warning+ case 4: return .critical+ default: return .unknown+ }+ }+}++/// Tabs by state, counted every few seconds.+public struct PerfTabCounts: Codable, Equatable, Sendable {+ public var tabs: Int+ /// Tabs with a page in memory, those on screen, those tab sleeping closed (not shown since).+ public var live: Int+ public var visible: Int+ public var slept: Int+ public var incognito: Int+ public var windows: Int++ public init(tabs: Int, live: Int, visible: Int, slept: Int, incognito: Int, windows: Int) {+ self.tabs = tabs+ self.live = live+ self.visible = visible+ self.slept = slept+ self.incognito = incognito+ self.windows = windows+ }+}++/// One thing that happened: a stall, a renderer that crashed, a load that failed.+public struct PerfEvent: Codable, Equatable, Sendable {+ /// Seconds since the session started.+ public var at: Double+ public var kind: String+ public var detail: String+ public var ms: Double?+ public var site: String?++ public init(at: Double, kind: String, detail: String, ms: Double? = nil, site: String? = nil) {+ self.at = at+ self.kind = kind+ self.detail = detail+ self.ms = ms+ self.site = site+ }+}++/// `Perf/hang-<session>-<n>.json`: a main thread blocked for 2 s or more, written by the watchdog+/// while it lasted (so it survives a force quit), with the main thread's stack when `sample` ran.+public struct PerfHang: Codable, Equatable, Sendable {+ public var session: String+ public var number: Int+ /// Seconds since the session started, when the block began.+ public var at: Double+ /// How long it had lasted when the file was written, and in the end (nil: Cra never recovered).+ public var stalledMs: Double+ public var endedMs: Double?+ public var mode: String+ public var marks: [String]+ public var site: String?+ public var stack: [String]+ /// Why there is no stack (sampling off, the limit reached, `sample` failed).+ public var stackNote: String?++ public init(session: String, number: Int, at: Double, stalledMs: Double, endedMs: Double? = nil, mode: String,+ marks: [String], site: String?, stack: [String] = [], stackNote: String? = nil) {+ self.session = session+ self.number = number+ self.at = at+ self.stalledMs = stalledMs+ self.endedMs = endedMs+ self.mode = mode+ self.marks = marks+ self.site = site+ self.stack = stack+ self.stackNote = stackNote+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfSampleStack.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfSampleStack.swiftnew file mode 100644index 0000000..dc300cb--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfSampleStack.swift@@ -0,0 +1,48 @@+import Foundation++/// The main thread's call tree from `/usr/bin/sample`, cut to what a hang report needs: frames+/// that took at least `minShare` of the thread's samples, each as `<count> <function> [<image>]`+/// indented by depth. No addresses, offsets or paths (the binary list at the end names the+/// home folder), so the result can go in a public issue.+public enum PerfSampleStack {+ public static func mainThread(from text: String, minShare: Double = 0.05, limit: Int = 40) -> [String] {+ var lines: [String] = []+ var inMain = false+ var total = 0+ var baseColumn = 0+ for raw in text.split(separator: "\n", omittingEmptySubsequences: false) {+ let line = String(raw)+ if !inMain {+ guard line.contains("com.apple.main-thread"), let n = leadingCount(line) else { continue }+ inMain = true+ total = n.count+ continue+ }+ // The tree's lines start with " +"; the next thread (or the end) doesn't.+ guard line.hasPrefix(" +"), let frame = leadingCount(line) else { break }+ if lines.isEmpty { baseColumn = frame.column }+ guard total > 0, Double(frame.count) >= Double(total) * minShare else { continue }+ let depth = max(0, (frame.column - baseColumn) / 2)+ lines.append(String(repeating: " ", count: min(depth, 30)) + "\(frame.count) \(symbol(frame.rest))")+ if lines.count >= limit { break }+ }+ return lines+ }++ /// The first number on the line, the column it starts at, and the text after it.+ private static func leadingCount(_ line: String) -> (count: Int, column: Int, rest: Substring)? {+ guard let start = line.firstIndex(where: \.isNumber) else { return nil }+ let end = line[start...].firstIndex(where: { !$0.isNumber }) ?? line.endIndex+ guard let n = Int(line[start..<end]) else { return nil }+ return (n, line.distance(from: line.startIndex, to: start), line[end...])+ }++ /// `busyLoop() (in Cra) + 156 [0x104b6903c]` → `busyLoop() [Cra]`.+ private static func symbol(_ rest: Substring) -> String {+ let s = rest.trimmingCharacters(in: .whitespaces)+ guard let open = s.range(of: " (in ") else { return String(s.prefix(160)) }+ let name = s[..<open.lowerBound]+ let image = s[open.upperBound...].prefix { $0 != ")" }+ return String("\(name) [\(image)]".prefix(160))+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfSession.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfSession.swiftnew file mode 100644index 0000000..aa2ae48--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfSession.swift@@ -0,0 +1,63 @@+import Foundation++/// `Perf/session.open`: made once Chromium has started, removed when Cra quits normally. Found+/// at the next launch, it means that session ended without quitting: a crash, a force quit,+/// `kill -9` or the Mac losing power.+public struct PerfSessionMarker: Codable, Equatable, Sendable {+ public var id: String+ public var launch: Int+ public var startedAt: Date+ public var pid: Int32+ public var craVersion: String++ public init(id: String, launch: Int, startedAt: Date, pid: Int32, craVersion: String) {+ self.id = id+ self.launch = launch+ self.startedAt = startedAt+ self.pid = pid+ self.craVersion = craVersion+ }+}++/// The session before this one, as this launch found it.+public struct PerfPreviousSession: Codable, Equatable, Sendable {+ public var id: String+ public var launch: Int+ public var startedAt: Date+ public var craVersion: String+ /// Ended without quitting (its marker was still there).+ public var abnormal: Bool+ /// When it quit; nil after an abnormal end.+ public var endedAt: Date?++ public init(id: String, launch: Int, startedAt: Date, craVersion: String, abnormal: Bool, endedAt: Date?) {+ self.id = id+ self.launch = launch+ self.startedAt = startedAt+ self.craVersion = craVersion+ self.abnormal = abnormal+ self.endedAt = endedAt+ }+}++/// When Cra records and when it writes (GitHub #91).+public enum PerfSessionRules {+ /// Settings ▸ Performance ▸ "Record performance", unless `CRA_PERF=0` turns it off for a+ /// development run.+ public static func recording(setting: Bool, environment: [String: String]) -> Bool {+ environment["CRA_PERF"] != "0" && setting+ }++ /// Only the Cra that owns the data folder writes, like CraLog's rotation: a second launch+ /// that hands its URLs over and quits must not replace the running one's files.+ public static func writesFiles(owner: Bool, recording: Bool) -> Bool { owner && recording }++ /// The session before this one: the marker it left (abnormal), else the one history recorded+ /// as quitting normally, else none (the first launch, or recording was off).+ public static func previous(marker: PerfSessionMarker?, history: PerfHistory) -> PerfPreviousSession? {+ if let m = marker {+ return PerfPreviousSession(id: m.id, launch: m.launch, startedAt: m.startedAt, craVersion: m.craVersion, abnormal: true, endedAt: nil)+ }+ return history.lastSession+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfStall.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfStall.swiftnew file mode 100644index 0000000..7225854--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfStall.swift@@ -0,0 +1,99 @@+import Foundation++/// A main run-loop pass long enough to notice. The mode tells a freeze from a loop the user is+/// in on purpose: a menu held open or a window dragged runs in the event-tracking mode, an+/// alert in the modal one, and neither is a frozen Cra however long it lasts.+public struct PerfStall: Codable, Equatable, Sendable {+ public enum Kind: String, Codable, Sendable {+ /// 250 ms or more: a dropped beat in a video, a click that lands late.+ case stall+ /// 1 s or more: the window visibly stops.+ case long+ /// 2 s or more: the watchdog wrote a hang file while it lasted.+ case hang+ }++ /// Seconds since the session started.+ public var at: Double+ public var ms: Double+ public var kind: Kind+ /// The run-loop mode, shortened: `default`, `tracking`, `modal`, `launch` (Cra starting up,+ /// before its run loop first waits) or the mode's own name.+ public var mode: String+ /// Counted as a freeze: not a tracking or modal loop, nor start-up.+ public var freeze: Bool+ /// What Cra did just before (HitchMonitor's marks), newest last.+ public var marks: [String]+ /// The host of the page on screen, nil for incognito or none.+ public var site: String?++ public init(at: Double, ms: Double, kind: Kind, mode: String, freeze: Bool, marks: [String], site: String?) {+ self.at = at+ self.ms = ms+ self.kind = kind+ self.mode = mode+ self.freeze = freeze+ self.marks = marks+ self.site = site+ }+}++/// When a main-loop pass counts, and as what.+public struct PerfStallPolicy: Equatable, Sendable {+ public var stallMs: Double = 250+ public var longMs: Double = 1000+ public var hangMs: Double = 2000+ /// Marks this close before the end of a stall are its breadcrumbs.+ public var breadcrumbWindow: Double = 5+ public var breadcrumbLimit = 8++ public init() {}++ public func kind(ms: Double) -> PerfStall.Kind? {+ if ms >= hangMs { return .hang }+ if ms >= longMs { return .long }+ if ms >= stallMs { return .stall }+ return nil+ }++ /// AppKit's mode names, as CFRunLoopCopyCurrentMode returns them.+ public static func shortMode(_ name: String) -> String {+ switch name {+ case "kCFRunLoopDefaultMode": return "default"+ case "NSEventTrackingRunLoopMode": return "tracking"+ case "NSModalPanelRunLoopMode": return "modal"+ case "kCFRunLoopCommonModes": return "common"+ default: return name+ }+ }++ /// A menu, a drag or a modal alert keeps the run loop in its own mode on purpose; start-up has+ /// its own phases (perf.json `startup`).+ public static func isFreeze(mode: String) -> Bool { !["tracking", "modal", "launch"].contains(mode) }++ /// The stall a pass of `ms` ending at `at` makes, with the marks of the seconds before it.+ public func stall(at: Double, ms: Double, mode: String, marks: [PerfMark], site: String?) -> PerfStall? {+ guard let kind = kind(ms: ms) else { return nil }+ let short = Self.shortMode(mode)+ let since = at - ms / 1000 - breadcrumbWindow+ let crumbs = marks.filter { $0.at >= since && $0.at <= at }.suffix(breadcrumbLimit).map(\.label)+ return PerfStall(at: at, ms: ms, kind: kind, mode: short, freeze: Self.isFreeze(mode: short), marks: Array(crumbs), site: site)+ }+}++/// A breadcrumb: something Cra did, by name (HitchMonitor.mark and the scripted commands).+public struct PerfMark: Codable, Equatable, Sendable {+ public var at: Double+ public var label: String++ public init(at: Double, label: String) {+ self.at = at+ self.label = Self.clean(label)+ }++ /// Never an address: a scripted `cra://open?url=…` keeps `cra://open`, and a label is short.+ public static func clean(_ label: String) -> String {+ let cut = label.firstIndex(where: { $0 == "?" || $0 == "\n" }).map { String(label[..<$0]) } ?? label+ return String(cut.prefix(120))+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfState.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfState.swiftnew file mode 100644index 0000000..7d77652--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfState.swift@@ -0,0 +1,118 @@+import Foundation++/// Everything the recorder holds in memory for one session, and the report made from it. The+/// recorder keeps one behind a lock; every change is a call here, so what a report says is+/// decided (and tested) in one place. Times are seconds since the session started.+public struct PerfState: Sendable {+ public var policy = PerfStallPolicy()+ public private(set) var passes = LogHistogram()+ public private(set) var timings: [PerfMetric: LogHistogram] = [:]+ public private(set) var counters: [PerfCounter: [String: Int]] = [:]+ public private(set) var stalls = PerfRing<PerfStall>(capacity: 40)+ public private(set) var stallCount = 0+ public private(set) var longStallCount = 0+ public private(set) var hangCount = 0+ public private(set) var outsideFreezes = 0+ public private(set) var longestMs: Double = 0+ public private(set) var marks = PerfRing<PerfMark>(capacity: 64)+ public private(set) var events = PerfRing<PerfEvent>(capacity: 150)+ public private(set) var longTasks = 0+ public private(set) var longTaskMs: Double = 0+ public private(set) var startup: [String: Double] = [:]+ public var processes: [PerfProcessGroup] = []+ public var system: PerfSystemSample?+ public var tabs: PerfTabCounts?+ /// The host of the page Cra put on screen last (nil for none or incognito), for stalls.+ public var visibleSite: String?+ private var historyBase = (stalls: 0, long: 0, longTasks: 0, crashes: 0)++ public init() {}++ public mutating func mark(_ label: String, at: Double) { marks.append(PerfMark(at: at, label: label)) }++ public mutating func time(_ metric: PerfMetric, ms: Double) { timings[metric, default: LogHistogram()].record(ms) }++ /// Main-loop passes measured since the last call (the observer keeps its own histogram so the+ /// main thread never waits on this state for a short pass).+ public mutating func addPasses(_ h: LogHistogram) { passes.add(h) }++ /// A pass of `ms` that ended at `at`: counted, and returned when it is a stall.+ @discardableResult+ public mutating func pass(ms: Double, endedAt at: Double, mode: String) -> PerfStall? {+ guard let s = policy.stall(at: at, ms: ms, mode: mode, marks: marks.elements, site: visibleSite) else { return nil }+ stalls.append(s)+ guard s.freeze else { outsideFreezes += 1; return s }+ stallCount += 1+ if s.kind != .stall { longStallCount += 1 }+ if s.kind == .hang { hangCount += 1 }+ longestMs = max(longestMs, ms)+ if s.kind != .stall {+ events.append(PerfEvent(at: at, kind: s.kind == .hang ? "hang" : "freeze",+ detail: s.marks.last.map { "after \($0)" } ?? "", ms: ms, site: s.site))+ }+ return s+ }++ /// A counted fact; renderer trouble and failed loads are events as well.+ public mutating func count(_ counter: PerfCounter, key: String, at: Double, site: String? = nil) {+ counters[counter, default: [:]][key, default: 0] += 1+ switch counter {+ case .rendererTerminated: events.append(PerfEvent(at: at, kind: "renderer", detail: key, site: site))+ case .rendererUnresponsive: events.append(PerfEvent(at: at, kind: "renderer", detail: "unresponsive", site: site))+ case .rendererResponsive: events.append(PerfEvent(at: at, kind: "renderer", detail: "responsive again", site: site))+ case .loadError: events.append(PerfEvent(at: at, kind: "load", detail: "error \(key)", site: site))+ case .tabSlept, .sleepRefusal: break+ }+ }++ /// The visible tab's long tasks since the last read (count, total, and each duration).+ public mutating func pageLongTasks(count: Int, totalMs: Double, durations: [Double]) {+ guard count > 0 else { return }+ longTasks += count+ longTaskMs += max(0, totalMs)+ for d in durations.prefix(100) { time(.longTask, ms: d) }+ }++ /// A start-up phase, the first time it is reached (milliseconds since the process started).+ public mutating func phase(_ name: String, ms: Double) {+ if startup[name] == nil { startup[name] = ms }+ }++ /// The counts since the last history sample, with the current levels.+ public mutating func historySample() -> PerfHistorySample {+ let crashes = counters[.rendererTerminated]?.values.reduce(0, +) ?? 0+ let s = PerfHistorySample(cpuPct: processes.reduce(0) { $0 + $1.cpuPct },+ footprintBytes: processes.reduce(0) { $0 + $1.footprintBytes },+ stalls: stallCount - historyBase.stalls, longStalls: longStallCount - historyBase.long,+ longTasks: longTasks - historyBase.longTasks, rendererCrashes: crashes - historyBase.crashes,+ liveTabs: tabs?.live ?? 0)+ historyBase = (stallCount, longStallCount, longTasks, crashes)+ return s+ }++ public func report(generatedAt: Date, session: PerfSessionInfo, selfCost: PerfSelfCost,+ storage: PerfReport.Storage = PerfReport.Storage()) -> PerfReport {+ var storage = storage+ if storage.freeDiskBytes == nil { storage.freeDiskBytes = system?.freeDiskBytes }+ var r = PerfReport(+ generatedAt: generatedAt, session: session, selfCost: selfCost,+ mainThread: .init(passes: passes, stalls: stallCount, longStalls: longStallCount, hangs: hangCount,+ outsideFreezes: outsideFreezes, longestMs: longestMs, recent: stalls.elements),+ processes: processes, system: system,+ tabs: .init(latest: tabs, longTasks: longTasks, longTaskMs: longTaskMs),+ timings: Dictionary(uniqueKeysWithValues: timings.map { ($0.key.rawValue, $0.value) }),+ counters: Dictionary(uniqueKeysWithValues: counters.map { ($0.key.rawValue, $0.value) }),+ startup: startup, storage: storage, events: events.elements, insights: [])+ r.insights = PerfInsights.evaluate(r)+ return r+ }++ /// About how much memory this holds: the budget is 5 MB.+ public var estimatedBytes: Int {+ let histograms = (timings.count + 1) * (LogHistogram.bucketCount + 3) * 8+ let marksBytes = marks.elements.reduce(0) { $0 + 32 + $1.label.utf8.count }+ let stallBytes = stalls.elements.reduce(0) { $0 + 96 + $1.marks.reduce(0) { $0 + $1.utf8.count + 16 } }+ let eventBytes = events.elements.reduce(0) { $0 + 80 + $1.detail.utf8.count + ($1.site?.utf8.count ?? 0) }+ return 1024 + histograms + marksBytes + stallBytes + eventBytes + processes.count * 96+ }+}diff --git a/Packages/CraCore/Sources/CraCore/Perf/SiteNames.swift b/Packages/CraCore/Sources/CraCore/Perf/SiteNames.swiftnew file mode 100644index 0000000..a3e5425--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/Perf/SiteNames.swift@@ -0,0 +1,88 @@+import Foundation++/// Settings ▸ Performance ▸ "Hide site names": every site Cra saw this session becomes `site-1`,+/// `site-2`… in every file of Help ▸ Export Diagnostics (GitHub #91). The same site gets the+/// same name in every file of one export, so a report can still say "site-3 crashed twice".+/// Not a hash: the list of domains is public, and a hash of one is found by looking it up.+public struct SiteNames {+ private var known: Set<String> = []+ private var aliases: [String: String] = [:]++ /// `hosts` are the sites to hide (from tabs, history and Cra's log). Hosts inside a web+ /// address in the text are hidden as well, known or not.+ public init(hosts: some Sequence<String>) {+ for h in hosts { if let k = Self.key(h) { known.insert(k) } }+ }++ /// A site's name in this export: the same for `www.example.com`, `example.com` and `EXAMPLE.COM`.+ public mutating func alias(_ host: String) -> String {+ guard let k = Self.key(host) else { return host }+ if let a = aliases[k] { return a }+ let a = "site-\(aliases.count + 1)"+ aliases[k] = a+ return a+ }++ /// The text with every known host, and the host of every web address, replaced. A host is a+ /// whole run of letters, digits, dots and dashes: `example.com` inside `api.example.com` is+ /// another site and stays unless it was seen too.+ public mutating func apply(_ text: String) -> String {+ let bytes = Array(text.utf8)+ var out = [UInt8]()+ out.reserveCapacity(bytes.count)+ var i = 0+ while i < bytes.count {+ guard Self.isHostByte(bytes[i]) else { out.append(bytes[i]); i += 1; continue }+ var end = i+ while end < bytes.count, Self.isHostByte(bytes[end]) { end += 1 }+ // Dots and dashes at either end belong to the sentence ("example.com." or "--flag").+ var lo = i, hi = end+ while lo < hi, bytes[lo] == UInt8(ascii: ".") || bytes[lo] == UInt8(ascii: "-") { lo += 1 }+ while hi > lo, bytes[hi - 1] == UInt8(ascii: ".") || bytes[hi - 1] == UInt8(ascii: "-") { hi -= 1 }+ out += bytes[i..<lo]+ if lo < hi {+ let token = String(decoding: bytes[lo..<hi], as: UTF8.self)+ if Self.followsWebScheme(bytes, at: lo) || known.contains(Self.key(token) ?? "") {+ out += Array(alias(token).utf8)+ } else {+ out += bytes[lo..<hi]+ }+ }+ out += bytes[hi..<end]+ i = end+ }+ return String(decoding: out, as: UTF8.self)+ }++ private static func isHostByte(_ b: UInt8) -> Bool {+ (b >= 0x30 && b <= 0x39) || (b >= 0x41 && b <= 0x5A) || (b >= 0x61 && b <= 0x7A) || b == 0x2E || b == 0x2D+ }++ /// `http://`, `https://`, `ws://`, `wss://` or `ftp://` right before `index`.+ private static func followsWebScheme(_ bytes: [UInt8], at index: Int) -> Bool {+ guard index >= 3, bytes[index - 3] == UInt8(ascii: ":"), bytes[index - 2] == UInt8(ascii: "/"),+ bytes[index - 1] == UInt8(ascii: "/") else { return false }+ var start = index - 3+ while start > 0, (bytes[start - 1] | 0x20) >= 0x61, (bytes[start - 1] | 0x20) <= 0x7A { start -= 1 }+ let scheme = String(decoding: bytes[start..<(index - 3)], as: UTF8.self).lowercased()+ return ["http", "https", "ws", "wss", "ftp"].contains(scheme)+ }++ /// The comparison key: lower case, without a leading `www.` or a trailing dot. Nil for what+ /// can't be a host Cra logged (empty, or Cra's own placeholders like "(no page)").+ public static func key(_ host: String) -> String? {+ var h = host.lowercased()+ while h.hasSuffix(".") { h.removeLast() }+ if h.hasPrefix("www.") { h.removeFirst(4) }+ guard !h.isEmpty, h.utf8.allSatisfy(isHostByte) else { return nil }+ return h+ }++ /// Hosts that name a site: http(s), ws(s) and ftp addresses. Cra's own pages, Chrome's,+ /// extensions and files are not sites.+ public static func siteHost(of url: String) -> String? {+ guard let u = URL(string: url), let scheme = u.scheme?.lowercased(),+ ["http", "https", "ws", "wss", "ftp"].contains(scheme), let host = u.host, !host.isEmpty else { return nil }+ return host+ }+}diff --git a/Packages/CraCore/Sources/CraCore/SidebarModel.swift b/Packages/CraCore/Sources/CraCore/SidebarModel.swiftindex c12eb20..cc12083 100644--- a/Packages/CraCore/Sources/CraCore/SidebarModel.swift+++ b/Packages/CraCore/Sources/CraCore/SidebarModel.swift@@ -475,6 +475,13 @@ public struct AppSettings: Codable, Equatable {/// GitHub #24, not in Arc: the page fills the window with no margin and no rounded/// card, like a traditional browser. Off by default.public var edgeToEdgeContent: Bool = false+ /// GitHub #91, Settings ▸ Performance: Cra records its own performance on this Mac (stalls,+ /// CPU and memory per process, tab timings) for Help ▸ Export Diagnostics. On by default in+ /// early releases; nothing leaves the Mac. Changing the default needs no migration.+ public var perfRecording: Bool = AppSettings.perfRecordingDefault+ public static let perfRecordingDefault = true+ /// Settings ▸ Performance ▸ "Hide site names": every site in the diagnostics zip becomes site-N.+ public var perfHidesSiteNames: Bool = falsepublic init() {}@@ -628,6 +635,8 @@ extension AppSettings {searchSuggestions = try c.decodeIfPresent(Bool.self, forKey: .searchSuggestions) ?? trueshowSpaceHeaderOnSingleSpace = try c.decodeIfPresent(Bool.self, forKey: .showSpaceHeaderOnSingleSpace) ?? trueedgeToEdgeContent = try c.decodeIfPresent(Bool.self, forKey: .edgeToEdgeContent) ?? false+ perfRecording = try c.decodeIfPresent(Bool.self, forKey: .perfRecording) ?? Self.perfRecordingDefault+ perfHidesSiteNames = try c.decodeIfPresent(Bool.self, forKey: .perfHidesSiteNames) ?? false}}diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/settings.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/settings.jsonindex 9b67b35..3be6f0e 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/settings.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/settings.json@@ -8,7 +8,7 @@{"id": "E0000000-0000-0000-0000-000000000002", "match": "equals", "text": "example.com/standup", "destination": {"littleWindow": {}}}],"newTabButtonAtTop": false, "newTabButtonDefaultMigrated": true, "newTabsAtTop": false,- "peekInEveryTab": true, "peekLinksToOtherSites": false, "peekOnShiftClick": false,+ "peekInEveryTab": true, "peekLinksToOtherSites": false, "peekOnShiftClick": false, "perfHidesSiteNames": true, "perfRecording": false,"searchEngine": "kagi", "searchSuggestions": false, "showSpaceHeaderOnSingleSpace": false, "showStatusBar": false,"showToolbar": true, "tabSleep": "fourHours", "tabSleepEnabled": true, "toolbarDefaultMigrated": true, "warnBeforeQuitting": true}diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-bad-routes.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-bad-routes.jsonindex d9278e2..8179269 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-bad-routes.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-bad-routes.json@@ -26,6 +26,8 @@"peekInEveryTab" : false,"peekLinksToOtherSites" : true,"peekOnShiftClick" : true,+ "perfHidesSiteNames" : false,+ "perfRecording" : true,"searchEngine" : "google","searchSuggestions" : true,"showSpaceHeaderOnSingleSpace" : true,diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.jsonindex f287642..54d27c3 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json@@ -35,6 +35,8 @@"peekInEveryTab" : false,"peekLinksToOtherSites" : true,"peekOnShiftClick" : true,+ "perfHidesSiteNames" : false,+ "perfRecording" : true,"searchEngine" : "google","searchSuggestions" : true,"showSpaceHeaderOnSingleSpace" : true,diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.jsonindex 4b0bb6b..4cb3b5e 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json@@ -35,6 +35,8 @@"peekInEveryTab" : false,"peekLinksToOtherSites" : true,"peekOnShiftClick" : true,+ "perfHidesSiteNames" : false,+ "perfRecording" : true,"searchEngine" : "duckduckgo","searchSuggestions" : true,"showSpaceHeaderOnSingleSpace" : true,diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.jsonindex edb37f0..b6b9b66 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json@@ -45,6 +45,8 @@"peekInEveryTab" : true,"peekLinksToOtherSites" : false,"peekOnShiftClick" : false,+ "perfHidesSiteNames" : true,+ "perfRecording" : false,"searchEngine" : "kagi","searchSuggestions" : false,"showSpaceHeaderOnSingleSpace" : false,diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Perf/perf-golden.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Perf/perf-golden.jsonnew file mode 100644index 0000000..1ca55b9--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Perf/perf-golden.json@@ -0,0 +1,264 @@+{+ "counters" : {+ "loadError" : {+ "-105" : 1+ },+ "rendererTerminated" : {+ "crashed" : 1+ },+ "sleepRefusal" : {+ "typed" : 1+ }+ },+ "events" : [+ {+ "at" : 101.7,+ "detail" : "after page-shown",+ "kind" : "freeze",+ "ms" : 1200,+ "site" : "video.example.com"+ },+ {+ "at" : 300,+ "detail" : "crashed",+ "kind" : "renderer",+ "site" : "video.example.com"+ },+ {+ "at" : 310,+ "detail" : "error -105",+ "kind" : "load"+ }+ ],+ "generatedAt" : "2026-10-26T07:43:20Z",+ "insights" : [+ {+ "detail" : "The longest lasted 1.2 s.",+ "id" : "freezes",+ "severity" : "warning",+ "title" : "Cra froze 1 time for a second or more"+ },+ {+ "detail" : "A page's process crashed, ran out of memory or was ended.",+ "id" : "renderer-crashes",+ "severity" : "warning",+ "title" : "1 page stopped (“Aw, Snap!”)"+ }+ ],+ "mainThread" : {+ "hangs" : 0,+ "longStalls" : 1,+ "longestMs" : 1200,+ "outsideFreezes" : 1,+ "passes" : {+ "buckets" : [+ 2,+ 0,+ 1,+ 0,+ 1,+ 0,+ 0,+ 0,+ 0,+ 1,+ 0,+ 1,+ 0,+ 0,+ 0,+ 0,+ 0+ ],+ "count" : 6,+ "maxMs" : 1200,+ "totalMs" : 1515.6+ },+ "recent" : [+ {+ "at" : 50,+ "freeze" : true,+ "kind" : "stall",+ "marks" : [++ ],+ "mode" : "default",+ "ms" : 300,+ "site" : "video.example.com"+ },+ {+ "at" : 101.7,+ "freeze" : true,+ "kind" : "long",+ "marks" : [+ "swipe-begin",+ "page-shown"+ ],+ "mode" : "default",+ "ms" : 1200,+ "site" : "video.example.com"+ },+ {+ "at" : 200,+ "freeze" : false,+ "kind" : "hang",+ "marks" : [++ ],+ "mode" : "tracking",+ "ms" : 4000,+ "site" : "video.example.com"+ }+ ],+ "stalls" : 2+ },+ "processes" : [+ {+ "available" : true,+ "count" : 1,+ "cpuPct" : 4.5,+ "diskReadBytes" : 1048576,+ "diskWriteBytes" : 2097152,+ "ended" : 0,+ "footprintBytes" : 314572800,+ "kind" : "browser",+ "started" : 0,+ "wakeups" : 1000+ },+ {+ "available" : true,+ "count" : 3,+ "cpuPct" : 12.25,+ "diskReadBytes" : 0,+ "diskWriteBytes" : 0,+ "ended" : 1,+ "footprintBytes" : 943718400,+ "kind" : "renderer",+ "started" : 4,+ "wakeups" : 5000+ }+ ],+ "schema" : 1,+ "selfCost" : {+ "bytesWritten" : 70000,+ "cpuMs" : 120,+ "cpuPct" : 0.02,+ "memoryBytes" : 9000,+ "observerCallbacks" : 50000,+ "observerMs" : 4,+ "writes" : 2+ },+ "session" : {+ "chromiumVersion" : "156.0.7445.0",+ "craVersion" : "0.1.27",+ "firstLaunchAt" : "2026-10-25T07:33:20Z",+ "id" : "0123abcd",+ "launch" : 2,+ "onboarding" : false,+ "startedAt" : "2026-10-26T07:33:20Z",+ "uptimeSeconds" : 600,+ "writesFiles" : true+ },+ "startup" : {+ "cefStarted" : 480,+ "main" : 12+ },+ "storage" : {+ "cacheBytes" : 209715200,+ "freeDiskBytes" : 107374182400,+ "profileBytes" : 524288000+ },+ "system" : {+ "cpuPct" : 23,+ "freeDiskBytes" : 107374182400,+ "lowPowerMode" : false,+ "memoryPressure" : "normal",+ "thermalState" : "nominal"+ },+ "tabs" : {+ "latest" : {+ "incognito" : 0,+ "live" : 6,+ "slept" : 3,+ "tabs" : 40,+ "visible" : 1,+ "windows" : 1+ },+ "longTaskMs" : 420,+ "longTasks" : 3+ },+ "timings" : {+ "longTask" : {+ "buckets" : [+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 1,+ 1,+ 1,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0+ ],+ "count" : 3,+ "maxMs" : 240,+ "totalMs" : 420+ },+ "pageCreate" : {+ "buckets" : [+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 1,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0+ ],+ "count" : 1,+ "maxMs" : 110,+ "totalMs" : 110+ },+ "tabSwitch" : {+ "buckets" : [+ 0,+ 0,+ 0,+ 1,+ 0,+ 0,+ 1,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0,+ 0+ ],+ "count" : 2,+ "maxMs" : 40,+ "totalMs" : 46+ }+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/PerfHistogramTests.swift b/Packages/CraCore/Tests/CraCoreTests/PerfHistogramTests.swiftnew file mode 100644index 0000000..0a32139--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/PerfHistogramTests.swift@@ -0,0 +1,128 @@+import CraCore+import Foundation+import Testing++/// GitHub #91: the recorder's fixed-size containers.+struct PerfHistogramTests {+ @Test(arguments: [(0.0, 0), (0.99, 0), (1.0, 1), (1.99, 1), (2.0, 2), (3.9, 2), (4.0, 3), (250.0, 8), (1000.0, 10),+ (2000.0, 11), (16384.0, 15), (40000.0, 16), (1e15, 16), (-5.0, 0)])+ func bucketsArePowersOfTwo(ms: Double, bucket: Int) {+ #expect(LogHistogram.bucket(ms: ms) == bucket)+ }++ @Test func nonFiniteDurationsDontPoisonTheTotal() {+ var h = LogHistogram()+ h.record(.infinity)+ h.record(.nan)+ h.record(10)+ #expect(h.count == 3)+ #expect(h.totalMs == 10)+ #expect(h.maxMs == 10)+ #expect(h.buckets[LogHistogram.bucketCount - 1] == 1) // infinity+ #expect(h.buckets[0] == 1) // NaN counts as 0+ }++ @Test func percentilesAreTheUpperEdgeOfTheirBucketCappedByTheMaximum() {+ var h = LogHistogram()+ #expect(h.percentile(0.5) == 0)+ for _ in 0..<90 { h.record(0.5) }+ for _ in 0..<9 { h.record(20) }+ h.record(700)+ #expect(h.percentile(0.5) == 1)+ #expect(h.percentile(0.95) == 32)+ #expect(h.percentile(1) == 700)+ #expect(h.percentile(2) == 700)+ #expect(h.count == 100)+ #expect(abs(h.meanMs - (45 + 180 + 700) / 100) < 1e-9)+ }++ @Test func histogramsAddBucketByBucket() {+ var a = LogHistogram(), b = LogHistogram()+ a.record(3)+ b.record(3)+ b.record(3000)+ a.add(b)+ #expect(a.count == 3)+ #expect(a.buckets[2] == 2)+ #expect(a.maxMs == 3000)+ #expect(a.totalMs == 3006)+ #expect(LogHistogram().meanMs == 0)+ }++ @Test func aHistogramFromAnOlderBuildWithFewerBucketsStillLoads() throws {+ let json = #"{"buckets":[1,2],"count":3,"totalMs":4,"maxMs":2}"#+ let h = try JSONDecoder().decode(LogHistogram.self, from: Data(json.utf8))+ #expect(h.buckets.count == LogHistogram.bucketCount)+ #expect(h.buckets[1] == 2)+ let back = try JSONDecoder().decode(LogHistogram.self, from: JSONEncoder().encode(h))+ #expect(back == h)+ }++ @Test func aRingKeepsTheNewestInOrder() {+ var r = PerfRing<Int>(capacity: 3)+ #expect(r.isEmpty)+ #expect(r.last == nil)+ for i in 1...5 { r.append(i) }+ #expect(r.elements == [3, 4, 5])+ #expect(r.last == 5)+ #expect(r.count == 3)+ #expect(r.appended == 5)+ r.updateLast { $0 = 50 }+ #expect(r.elements == [3, 4, 50])+ r.removeAll()+ #expect(r.isEmpty)+ r.updateLast { $0 = 1 }+ #expect(r.isEmpty)+ #expect(PerfRing<Int>(capacity: 0).capacity == 1)+ }++ @Test func aRingRoundTripsAndTrimsAFileFromALargerRing() throws {+ var r = PerfRing<String>(capacity: 2)+ r.append("a")+ let back = try JSONDecoder().decode(PerfRing<String>.self, from: JSONEncoder().encode(r))+ #expect(back == r)+ let wide = #"{"capacity":2,"elements":["a","b","c"]}"#+ #expect(try JSONDecoder().decode(PerfRing<String>.self, from: Data(wide.utf8)).elements == ["b", "c"])+ }+}++struct PerfStallTests {+ let policy = PerfStallPolicy()++ @Test(arguments: [(249.0, nil), (250.0, PerfStall.Kind.stall), (999.0, .stall), (1000.0, .long), (2000.0, .hang)] as [(Double, PerfStall.Kind?)])+ func thresholds(ms: Double, kind: PerfStall.Kind?) {+ #expect(policy.kind(ms: ms) == kind)+ }++ @Test(arguments: [("kCFRunLoopDefaultMode", "default", true), ("NSEventTrackingRunLoopMode", "tracking", false),+ ("NSModalPanelRunLoopMode", "modal", false), ("kCFRunLoopCommonModes", "common", true),+ ("launch", "launch", false), ("CEFCustomMode", "CEFCustomMode", true)])+ func aHeldMenuOrADragIsNotAFreeze(mode: String, short: String, freeze: Bool) throws {+ let s = try #require(policy.stall(at: 10, ms: 600, mode: mode, marks: [], site: nil))+ #expect(s.mode == short)+ #expect(s.freeze == freeze)+ }++ @Test func breadcrumbsAreTheMarksOfTheSecondsBeforeTheStall() throws {+ let marks = [PerfMark(at: 1, label: "old"), PerfMark(at: 7, label: "swipe-begin"), PerfMark(at: 9.4, label: "page-shown"),+ PerfMark(at: 11, label: "after")]+ let s = try #require(policy.stall(at: 10, ms: 500, mode: "kCFRunLoopDefaultMode", marks: marks, site: "example.com"))+ #expect(s.marks == ["swipe-begin", "page-shown"])+ #expect(s.site == "example.com")+ #expect(s.kind == .stall)+ #expect(policy.stall(at: 10, ms: 100, mode: "kCFRunLoopDefaultMode", marks: marks, site: nil) == nil)+ }++ @Test func breadcrumbsAreCappedToTheNewest() throws {+ var p = PerfStallPolicy()+ p.breadcrumbLimit = 2+ let marks = (0..<5).map { PerfMark(at: Double($0), label: "m\($0)") }+ #expect(try #require(p.stall(at: 5, ms: 300, mode: "x", marks: marks, site: nil)).marks == ["m3", "m4"])+ }++ @Test func aMarkNeverKeepsAnAddress() {+ #expect(PerfMark(at: 0, label: "cra://open?url=https%3A%2F%2Fexample.com%2Fsecret").label == "cra://open")+ #expect(PerfMark(at: 0, label: "first\nsecond").label == "first")+ #expect(PerfMark(at: 0, label: String(repeating: "x", count: 500)).label.count == 120)+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/PerfSessionTests.swift b/Packages/CraCore/Tests/CraCoreTests/PerfSessionTests.swiftnew file mode 100644index 0000000..bdc2fe0--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/PerfSessionTests.swift@@ -0,0 +1,158 @@+import CraCore+import Foundation+import Testing++/// GitHub #91: when Cra records, when it writes, and how the session before ended.+struct PerfSessionTests {+ let start = Date(timeIntervalSince1970: 1_793_000_000)++ @Test(arguments: [(true, [:], true), (false, [:], false), (true, ["CRA_PERF": "0"], false), (true, ["CRA_PERF": "1"], true)]+ as [(Bool, [String: String], Bool)])+ func recordingFollowsTheSettingUnlessTheEnvironmentTurnsItOff(setting: Bool, env: [String: String], on: Bool) {+ #expect(PerfSessionRules.recording(setting: setting, environment: env) == on)+ }++ @Test func onlyTheOwnerWritesAndOnlyWhileRecording() {+ #expect(PerfSessionRules.writesFiles(owner: true, recording: true))+ #expect(!PerfSessionRules.writesFiles(owner: false, recording: true))+ #expect(!PerfSessionRules.writesFiles(owner: true, recording: false))+ }++ @Test func aMarkerLeftBehindIsAnAbnormalEnd() {+ let marker = PerfSessionMarker(id: "abc", launch: 3, startedAt: start, pid: 42, craVersion: "0.1.26")+ var history = PerfHistory()+ history.lastSession = PerfPreviousSession(id: "old", launch: 2, startedAt: start, craVersion: "0.1.25", abnormal: false, endedAt: start)+ let p = PerfSessionRules.previous(marker: marker, history: history)+ #expect(p == PerfPreviousSession(id: "abc", launch: 3, startedAt: start, craVersion: "0.1.26", abnormal: true, endedAt: nil))+ #expect(PerfSessionRules.previous(marker: nil, history: history)?.abnormal == false)+ #expect(PerfSessionRules.previous(marker: nil, history: PerfHistory()) == nil)+ }++ @Test func historyKeepsFiveMinuteBuckets() {+ var h = PerfHistory()+ h.record(PerfHistorySample(cpuPct: 10, footprintBytes: 100 << 20, stalls: 1, liveTabs: 3), at: start)+ h.record(PerfHistorySample(cpuPct: 20, footprintBytes: 300 << 20, stalls: 2, longStalls: 1, longTasks: 4, rendererCrashes: 1, liveTabs: 2),+ at: start.addingTimeInterval(60))+ #expect(h.buckets.count == 1)+ let b = h.buckets.elements[0]+ #expect(b.samples == 2)+ #expect(b.cpuPct == 15)+ #expect(b.footprintMB == 300)+ #expect(b.stalls == 3 && b.longStalls == 1 && b.longTasks == 4 && b.rendererCrashes == 1)+ #expect(b.liveTabs == 3)+ #expect(b.start.timeIntervalSince1970.truncatingRemainder(dividingBy: 300) == 0)+ h.record(PerfHistorySample(cpuPct: 1, footprintBytes: 0), at: start.addingTimeInterval(400))+ #expect(h.buckets.count == 2)+ // A clock set back starts a new bucket rather than changing an old one.+ h.record(PerfHistorySample(cpuPct: 1, footprintBytes: 0), at: start.addingTimeInterval(-3600))+ #expect(h.buckets.count == 3)+ #expect(h.recent(600, now: start.addingTimeInterval(400)).count == 2)+ }++ @Test func historyHoldsADayAndLoadsWhatOlderFilesLack() throws {+ var h = PerfHistory()+ for i in 0..<(PerfHistory.capacity + 10) {+ h.record(PerfHistorySample(cpuPct: 1, footprintBytes: 0), at: start.addingTimeInterval(Double(i) * 300))+ }+ #expect(h.buckets.count == PerfHistory.capacity)+ h.launches = 4+ let data = try PerfReport.encoder().encode(h)+ #expect(try PerfReport.decoder.decode(PerfHistory.self, from: data) == h)+ let empty = try PerfReport.decoder.decode(PerfHistory.self, from: Data("{}".utf8))+ #expect(empty.launches == 0 && empty.buckets.isEmpty && empty.firstLaunchAt == nil)+ }+}++struct PerfProcessTableTests {+ func reading(_ pid: Int32, _ kind: PerfProcessKind, cpuMs: UInt64?, mb: Int64 = 10) -> PerfProcessReading {+ PerfProcessReading(pid: pid, kind: kind, cpuNs: cpuMs.map { $0 * 1_000_000 }, footprintBytes: mb << 20,+ diskReadBytes: 1, diskWriteBytes: 2, wakeups: 3)+ }++ @Test(arguments: [("Cra", true, PerfProcessKind.browser), ("Cra Helper (Renderer)", false, .renderer),+ ("CraX Helper (GPU)", false, .gpu), ("Cra Helper (Plugin)", false, .utility), ("Cra Helper", false, .utility),+ ("sample", false, .other)])+ func processKindsComeFromTheirNames(name: String, isSelf: Bool, kind: PerfProcessKind) {+ #expect(PerfProcessKind.of(name: name, isSelf: isSelf) == kind)+ }++ @Test(arguments: [("renderer", PerfProcessKind.renderer), ("gpu-process", .gpu), ("utility", .utility), ("zygote", .utility)])+ func chromiumsTypeArgumentWinsOverTheName(type: String, kind: PerfProcessKind) {+ // CEF's GPU process runs from the plain helper app.+ #expect(PerfProcessKind.of(name: "Cra Helper", isSelf: false, type: type) == kind)+ #expect(PerfProcessKind.of(name: "Cra", isSelf: true, type: type) == .browser)+ }++ @Test func cpuIsMeasuredOverTheIntervalAndChurnCountsComingAndGoing() throws {+ var t = PerfProcessTable()+ let first = t.update([reading(1, .browser, cpuMs: 1000), reading(2, .renderer, cpuMs: 500), reading(3, .renderer, cpuMs: 0)],+ atNs: 10_000_000_000)+ #expect(first.first { $0.kind == .browser }?.cpuPct == 0)+ #expect(first.first { $0.kind == .renderer }?.started == 0)+ #expect(first.first { $0.kind == .renderer }?.count == 2)+ #expect(first.first { $0.kind == .gpu } == nil)++ // 5 s later: the browser used 500 ms (10 %), renderer 2 ended, renderer 4 started.+ let second = t.update([reading(1, .browser, cpuMs: 1500), reading(3, .renderer, cpuMs: 250, mb: 30), reading(4, .renderer, cpuMs: nil)],+ atNs: 15_000_000_000)+ let browser = try #require(second.first { $0.kind == .browser })+ #expect(abs(browser.cpuPct - 10) < 1e-9)+ let renderers = try #require(second.first { $0.kind == .renderer })+ #expect(abs(renderers.cpuPct - 5) < 1e-9)+ #expect(renderers.started == 1 && renderers.ended == 1)+ #expect(renderers.footprintBytes == 40 << 20)+ #expect(renderers.wakeups == 6)+ #expect(renderers.available)++ // Every renderer gone: the group stays for its churn.+ let third = t.update([reading(1, .browser, cpuMs: 1500)], atNs: 20_000_000_000)+ let gone = try #require(third.first { $0.kind == .renderer })+ #expect(gone.count == 0 && gone.ended == 3 && gone.available)+ }++ @Test func aGroupMacOSRefusedEntirelyIsUnavailable() throws {+ var t = PerfProcessTable()+ let g = t.update([reading(9, .gpu, cpuMs: nil)], atNs: 1)+ #expect(try #require(g.first { $0.kind == .gpu }).available == false)+ }+}++struct PerfSampleStackTests {+ static let sample = """+ Analysis of sampling Cra (pid 12876) every 10 milliseconds+ Path: /Users/someone/Applications/Cra.app/Contents/MacOS/Cra+ ----++ Call graph:+ 100 Thread_7920090 DispatchQueue_1: com.apple.main-thread (serial)+ + 100 start (in dyld) + 6992 [0x18aafc4e4]+ + 100 main (in Cra) + 140 [0x104b68ad4]+ + 90 BrowserManager.show(_:focused:focus:) (in Cra) + 156 [0x104b6903c]+ + ! 88 -[CraBrowser initWithFrame:] (in Cra) + 56 [0x18d0667d4]+ + ! : 2 objc_msgSend (in libobjc.A.dylib) + 2 [0x1]+ + 10 SidebarStore.save() (in Cra) + 148,184 [0x104b69034,0x104b69058]+ 100 Thread_7920229+ + 100 thread_start (in libsystem_pthread.dylib) + 8 [0x18aec2c1c]++ Binary Images:+ 0x104b68000 - 0x104b6bfff Cra (0) <ABC> /Users/someone/Applications/Cra.app/Contents/MacOS/Cra+ """++ @Test func theMainThreadsHeavyFramesWithoutAddressesOrPaths() {+ let lines = PerfSampleStack.mainThread(from: Self.sample)+ #expect(lines == [+ "100 start [dyld]",+ " 100 main [Cra]",+ " 90 BrowserManager.show(_:focused:focus:) [Cra]",+ " 88 -[CraBrowser initWithFrame:] [Cra]",+ " 10 SidebarStore.save() [Cra]",+ ])+ #expect(!lines.joined().contains("/Users"))+ #expect(!lines.joined().contains("0x"))+ }++ @Test func noMainThreadNoLines() {+ #expect(PerfSampleStack.mainThread(from: "sample: failed to examine process").isEmpty)+ #expect(PerfSampleStack.mainThread(from: Self.sample, limit: 2).count == 2)+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swift b/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swiftnew file mode 100644index 0000000..17bce78--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swift@@ -0,0 +1,201 @@+import CraCore+import Foundation+import Testing++/// GitHub #91: what the recorder keeps, the report made from it, and its readings.+struct PerfStateTests {+ static let start = Date(timeIntervalSince1970: 1_793_000_000)++ static func session(previous: PerfPreviousSession? = nil, uptime: Double = 600) -> PerfSessionInfo {+ PerfSessionInfo(id: "0123abcd", launch: 2, startedAt: start, uptimeSeconds: uptime, craVersion: "0.1.27",+ chromiumVersion: "156.0.7445.0", onboarding: false, firstLaunchAt: start.addingTimeInterval(-86400),+ previous: previous, writesFiles: true)+ }++ /// A made-up session: a swipe that froze for 1.2 s on a site, a held menu, a crashed renderer.+ static func sampleState() -> PerfState {+ var s = PerfState()+ s.visibleSite = "video.example.com"+ var passes = LogHistogram()+ for ms in [0.2, 0.4, 3, 12, 300, 1200] { passes.record(ms) }+ s.addPasses(passes)+ s.mark("swipe-begin", at: 100)+ s.mark("page-shown", at: 100.5)+ s.pass(ms: 300, endedAt: 50, mode: "kCFRunLoopDefaultMode")+ s.pass(ms: 1200, endedAt: 101.7, mode: "kCFRunLoopDefaultMode")+ s.pass(ms: 4000, endedAt: 200, mode: "NSEventTrackingRunLoopMode")+ s.time(.tabSwitch, ms: 6)+ s.time(.tabSwitch, ms: 40)+ s.time(.pageCreate, ms: 110)+ s.count(.rendererTerminated, key: "crashed", at: 300, site: "video.example.com")+ s.count(.loadError, key: "-105", at: 310)+ s.count(.sleepRefusal, key: "typed", at: 320)+ s.pageLongTasks(count: 3, totalMs: 420, durations: [60, 120, 240])+ s.phase("main", ms: 12)+ s.phase("cefStarted", ms: 480)+ s.phase("main", ms: 999)+ s.processes = [PerfProcessGroup(kind: .browser, count: 1, cpuPct: 4.5, footprintBytes: 300 << 20, diskReadBytes: 1 << 20,+ diskWriteBytes: 2 << 20, wakeups: 1000, started: 0, ended: 0, available: true),+ PerfProcessGroup(kind: .renderer, count: 3, cpuPct: 12.25, footprintBytes: 900 << 20, diskReadBytes: 0,+ diskWriteBytes: 0, wakeups: 5000, started: 4, ended: 1, available: true)]+ s.system = PerfSystemSample(cpuPct: 23, memoryPressure: .normal, thermalState: "nominal", lowPowerMode: false, freeDiskBytes: 100 << 30)+ s.tabs = PerfTabCounts(tabs: 40, live: 6, visible: 1, slept: 3, incognito: 0, windows: 1)+ return s+ }++ static func sampleReport() -> PerfReport {+ sampleState().report(generatedAt: start.addingTimeInterval(600), session: session(),+ selfCost: PerfSelfCost(cpuMs: 120, cpuPct: 0.02, observerCallbacks: 50000, observerMs: 4,+ bytesWritten: 70000, writes: 2, memoryBytes: 9000),+ storage: .init(profileBytes: 500 << 20, cacheBytes: 200 << 20))+ }++ @Test func stallsAreCountedByKindAndHeldMenusAreNotFreezes() {+ let r = Self.sampleReport()+ let m = r.mainThread+ #expect(m.stalls == 2)+ #expect(m.longStalls == 1)+ #expect(m.hangs == 0)+ #expect(m.outsideFreezes == 1)+ #expect(m.longestMs == 1200)+ #expect(m.recent.count == 3)+ #expect(m.recent[1].marks == ["swipe-begin", "page-shown"])+ #expect(m.recent[1].site == "video.example.com")+ #expect(m.passes.count == 6)+ #expect(r.events.map(\.kind) == ["freeze", "renderer", "load"])+ #expect(r.events[0].detail == "after page-shown")+ #expect(r.startup == ["main": 12, "cefStarted": 480])+ #expect(r.counters["sleepRefusal"] == ["typed": 1])+ #expect(r.timings["longTask"]?.count == 3)+ #expect(r.tabs.longTasks == 3 && r.tabs.longTaskMs == 420)+ #expect(r.storage.freeDiskBytes == 100 << 30)+ #expect(r.sites == ["video.example.com"])+ }++ @Test func aHangCountsAsAllThreeAndIsAnEvent() {+ var s = PerfState()+ #expect(s.pass(ms: 100, endedAt: 1, mode: "kCFRunLoopDefaultMode") == nil)+ let hang = s.pass(ms: 2500, endedAt: 3, mode: "kCFRunLoopDefaultMode")+ #expect(hang?.kind == .hang)+ #expect(s.stallCount == 1 && s.longStallCount == 1 && s.hangCount == 1)+ #expect(s.events.elements.map(\.kind) == ["hang"])+ s.count(.rendererUnresponsive, key: "", at: 4)+ s.count(.rendererResponsive, key: "", at: 5)+ s.count(.tabSlept, key: "idle", at: 6)+ #expect(s.events.elements.map(\.detail) == ["", "unresponsive", "responsive again"])+ s.pageLongTasks(count: 0, totalMs: 0, durations: [])+ #expect(s.longTasks == 0)+ }++ @Test func historySamplesCountWhatHappenedSinceTheLastOne() {+ var s = Self.sampleState()+ let first = s.historySample()+ #expect(first.stalls == 2 && first.longStalls == 1 && first.longTasks == 3 && first.rendererCrashes == 1)+ #expect(first.liveTabs == 6)+ #expect(abs(first.cpuPct - 16.75) < 1e-9)+ #expect(first.footprintBytes == 1200 << 20)+ s.pass(ms: 260, endedAt: 400, mode: "kCFRunLoopDefaultMode")+ let second = s.historySample()+ #expect(second.stalls == 1 && second.longStalls == 0 && second.rendererCrashes == 0)+ }++ @Test func memoryStaysSmallWhateverHappens() {+ var s = PerfState()+ for i in 0..<100_000 {+ s.mark("mark \(i)", at: Double(i))+ s.pass(ms: 300, endedAt: Double(i), mode: "kCFRunLoopDefaultMode")+ s.count(.loadError, key: "-\(i % 50)", at: Double(i))+ }+ #expect(s.marks.count == 64 && s.stalls.count == 40 && s.events.count == 150)+ #expect(s.estimatedBytes < 100_000)+ }++ @Test func aHangFileRoundTrips() throws {+ let h = PerfHang(session: "0123abcd", number: 1, at: 12.5, stalledMs: 2100, mode: "default", marks: ["page-shown"],+ site: "example.com", stack: ["10 main [Cra]"])+ #expect(try PerfReport.decoder.decode(PerfHang.self, from: PerfReport.encoder().encode(h)) == h)+ }++ /// The schema as it ships: a change that moves or renames a field shows up here. Re-record with+ /// CRA_RECORD_GOLDEN=1 swift test --package-path Packages/CraCore, then say why in the PR.+ @Test func reportMatchesTheGoldenFile() throws {+ let json = String(decoding: try PerfReport.encoder().encode(Self.sampleReport()), as: UTF8.self) + "\n"+ if ProcessInfo.processInfo.environment["CRA_RECORD_GOLDEN"] == "1" {+ let source = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/Perf/perf-golden.json")+ try json.write(to: source, atomically: true, encoding: .utf8)+ }+ let url = try #require(Bundle.module.url(forResource: "perf-golden", withExtension: "json", subdirectory: "Fixtures/Perf"))+ let golden = try String(contentsOf: url, encoding: .utf8)+ #expect(json == golden)+ let decoded = try PerfReport.decoder.decode(PerfReport.self, from: Data(golden.utf8))+ #expect(decoded == Self.sampleReport())+ }+}++struct PerfInsightTests {+ func report(_ change: (inout PerfReport) -> Void) -> PerfReport {+ var r = PerfState().report(generatedAt: PerfStateTests.start, session: PerfStateTests.session(), selfCost: PerfSelfCost())+ change(&r)+ r.insights = PerfInsights.evaluate(r)+ return r+ }++ @Test func aQuietSessionSaysNothing() {+ #expect(report { _ in }.insights.isEmpty)+ }++ @Test func eachRuleFires() {+ let r = report {+ $0.session.previous = PerfPreviousSession(id: "x", launch: 1, startedAt: PerfStateTests.start, craVersion: "0.1.26",+ abnormal: true, endedAt: nil)+ $0.mainThread.longStalls = 2+ $0.mainThread.hangs = 1+ $0.mainThread.longestMs = 2600+ $0.mainThread.stalls = 40+ $0.counters = ["rendererTerminated": ["crashed": 1], "rendererUnresponsive": ["": 2]]+ $0.system = PerfSystemSample(cpuPct: 90, memoryPressure: .critical, thermalState: "serious", lowPowerMode: true,+ freeDiskBytes: 1 << 30)+ $0.processes = [PerfProcessGroup(kind: .renderer, count: 30, footprintBytes: 9 << 30)]+ $0.tabs.latest = PerfTabCounts(tabs: 100, live: 30, visible: 1, slept: 0, incognito: 0, windows: 2)+ }+ #expect(r.insights.map(\.id) == ["previous-abnormal", "freezes", "stalls", "renderer-crashes", "unresponsive",+ "memory-pressure", "thermal", "low-power", "low-disk", "footprint"])+ #expect(r.insights[1].title == "Cra froze 2 times for a second or more")+ #expect(r.insights[1].detail == "The longest lasted 2.6 s; 1 went past 2 s.")+ #expect(r.insights[3].title == "1 page stopped (“Aw, Snap!”)")+ #expect(r.insights[8].detail.hasPrefix("1.0 GB free"))+ #expect(r.insights[9].title == "Cra uses 9.0 GB of memory")+ #expect(r.insights[9].detail.contains("Tab sleeping (Settings ▸ Tabs)"))+ }++ @Test func aFewStallsInALongSessionAreNotFrequent() {+ #expect(report { $0.mainThread.stalls = 5; $0.session.uptimeSeconds = 3600 }.insights.isEmpty)+ #expect(report { $0.mainThread.stalls = 5; $0.session.uptimeSeconds = 300 }.insights.map(\.id) == ["stalls"])+ }++ @Test func formatting() {+ #expect(PerfInsights.duration(250.4) == "250 ms")+ #expect(PerfInsights.duration(1500) == "1.5 s")+ #expect(PerfInsights.bytes(300 << 20) == "300 MB")+ #expect(PerfSystemSample.pressure(level: 2) == .warning)+ #expect(PerfSystemSample.pressure(level: 1) == .normal)+ #expect(PerfSystemSample.pressure(level: 4) == .critical)+ #expect(PerfSystemSample.pressure(level: nil) == .unknown)+ }++ @Test func theSummaryNeverNamesASite() {+ var r = PerfStateTests.sampleReport()+ r.session.previous = PerfPreviousSession(id: "x", launch: 1, startedAt: PerfStateTests.start, craVersion: "0.1.26",+ abnormal: true, endedAt: nil)+ r.insights = PerfInsights.evaluate(r)+ let text = PerfSummary.text(r)+ #expect(!text.contains("example.com"))+ #expect(text.contains("Main thread: 2 stalls ≥250 ms, 1 ≥1 s, 0 ≥2 s, longest 1.2 s"))+ #expect(text.contains("renderer ×3: 12.2 % CPU, 900 MB"))+ #expect(text.contains("Previous session: ended without quitting (Cra 0.1.26)"))+ #expect(text.contains("Tabs: 40, 6 loaded, 3 asleep, 1 window"))+ #expect(text.contains("tab switch: median 8 ms, p95 40 ms (2)"))+ #expect(text.contains("loadError: -105 ×1"))+ #expect(text.contains("• The last session ended without quitting"))+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/SiteNamesTests.swift b/Packages/CraCore/Tests/CraCoreTests/SiteNamesTests.swiftnew file mode 100644index 0000000..b16ae9a--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/SiteNamesTests.swift@@ -0,0 +1,66 @@+import CraCore+import Foundation+import Testing++/// GitHub #91: "Hide site names" leaves no host of the session in any file of the zip.+struct SiteNamesTests {+ /// Lines as Cra and Chromium write them (cra.log, chromium.log, pages.txt), after the redaction.+ static let files = [+ "2026-11-02 10:00:01.000 tab 1A2B3C4D shown: mail.example.com, loading\n2026-11-02 10:00:02.000 tab 1A2B3C4D loaded www.news.example.org (HTTP 200)",+ "[1102/100003.000:WARNING:CraCEF.mm(1173)] Cra: loading intranet failed: net::ERR_NAME_NOT_RESOLVED (-105)\nCra: renderer for 192.168.1.20 ended: crashed (code 11, )",+ " on screen 1A2B3C4D: sidebar mail.example.com, page mail.example.com, loading=false\n probe: https://unknown.example.net/… blank=0",+ "tab sleep keeps NEWS.EXAMPLE.ORG awake: typed",+ ]++ @Test func everyHostOfTheSessionBecomesASiteNumber() {+ var names = SiteNames(hosts: ["mail.example.com", "news.example.org", "intranet", "192.168.1.20"])+ let out = Self.files.map { names.apply($0) }.joined(separator: "\n")+ for host in ["mail.example.com", "news.example.org", "NEWS.EXAMPLE.ORG", "intranet", "192.168.1.20", "unknown.example.net"] {+ #expect(!out.contains(host), "\(host) left in the export")+ }+ #expect(out.contains("shown: site-1, loading"))+ #expect(out.contains("loaded site-2 (HTTP 200)"))+ #expect(out.contains("sidebar site-1, page site-1"))+ #expect(out.contains("https://site-5/…"))+ #expect(out.contains("keeps site-2 awake"))+ // What isn't a host stays: file names, versions, error names.+ #expect(out.contains("CraCEF.mm(1173)"))+ #expect(out.contains("net::ERR_NAME_NOT_RESOLVED"))+ }++ @Test func theSameSiteKeepsItsNameAcrossFiles() {+ var names = SiteNames(hosts: ["example.com"])+ #expect(names.apply("a example.com") == "a site-1")+ #expect(names.apply("b www.example.com.") == "b site-1.")+ #expect(names.alias("other.com") == "site-2")+ #expect(names.alias("EXAMPLE.com") == "site-1")+ #expect(names.alias("(no page)") == "(no page)")+ }++ @Test func aDifferentSiteThatContainsAKnownOneIsNotTouchedUnlessItIsAnAddress() {+ var names = SiteNames(hosts: ["example.com"])+ #expect(names.apply("api.example.com and example.community") == "api.example.com and example.community")+ #expect(names.apply("see http://api.example.com:8080/x") == "see http://site-1:8080/x")+ #expect(names.apply("chrome-extension://abcdef/options.html") == "chrome-extension://abcdef/options.html")+ #expect(names.apply("--flag-name-.") == "--flag-name-.")+ }++ @Test func unicodeAndPunctuationPassThrough() {+ var names = SiteNames(hosts: ["example.com"])+ #expect(names.apply("“example.com” — ✓") == "“site-1” — ✓")+ #expect(names.apply("") == "")+ }++ @Test(arguments: [("https://www.Example.com/a", "www.Example.com"), ("wss://x.example.com", "x.example.com"),+ ("chrome://settings", nil), ("cra://newtab", nil), ("file:///Users/a", nil), ("data:text/html,x", nil),+ ("not a url", nil)] as [(String, String?)])+ func onlyWebAddressesNameASite(url: String, host: String?) {+ #expect(SiteNames.siteHost(of: url) == host)+ }++ @Test func keysIgnoreCaseWwwAndTheTrailingDot() {+ #expect(SiteNames.key("WWW.Example.COM.") == "example.com")+ #expect(SiteNames.key("(incognito)") == nil)+ #expect(SiteNames.key("") == nil)+ }+}diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex a080867..631d7b6 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -44,6 +44,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {bootstrapped = trueNSApp.setActivationPolicy(.regular)installURLEventHandler()+ PerfCEF.install(app: self)CraCEFRuntime.setChromeHosting(store.settings.chromeEngine)CraCEFRuntime.setOwnContextMenus(EmbeddedPages.isEnabled)CraCEFRuntime.setDocumentStartScript(PageScript.mainWorld, isolatedScript: PageScript.isolatedWorld, world: PageScript.world)@@ -113,11 +114,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {let urls = pendingURLspendingURLs = []for u in urls { openExternalURL(u) }+ Perf.phase("windowsShown")}/// A fresh install runs Dia's onboarding (cover, default browser, privacy,/// import, pinned tabs, personalization, outro).- private var needsOnboarding: Bool {+ var needsOnboarding: Bool {!store.settings.hasSeenImportPrompt && store.allTabs().count <= 2}@@ -509,6 +511,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {if let st = dict["status"] { main.browserManager(statusMessage: st); return }// Scenario hooks (scripts/scenario.sh): what a journey needs without a pointer.if dict["checkStore"] != nil { logSidebarProblems(); return }+ // A main-thread stall of this many milliseconds, for the performance recorder's tests.+ if let ms = dict["stall"].flatMap(Double.init) { usleep(useconds_t(min(max(ms, 0), 30_000) * 1000)); return }+ if let path = dict["perfReport"] {+ PerfRecorder.shared?.snapshot { report in+ try? PerfReport.encoder().encode(report).write(to: URL(fileURLWithPath: path), options: .atomic)+ }+ return+ }if let js = dict["pageJS"] { main.currentBrowser?.executeJavaScript(js); return }if let path = dict["installExtension"] {do { try ExtensionStore.shared.add(folder: URL(fileURLWithPath: path, isDirectory: true)) } catch {@@ -898,7 +908,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {_ = self.store.createTab(url: url, select: true)self.settingsWindow?.close()self.main.showWindow(nil)- })+ },+ exportDiagnostics: { [weak self] in self?.exportDiagnostics() })let c = SettingsWindowController(store: store, bindings: bindings, actions: actions)settingsController = csettingsWindow = c.windowdiff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swiftindex faa79c5..7e86190 100644--- a/Sources/Cra/App/main.swift+++ b/Sources/Cra/App/main.swift@@ -2,11 +2,14 @@ import AppKitimport CraCEFMainActor.assumeIsolated {+ // Start-up phases count from here, before AppDelegate decodes the data folder's files.+ Perf.launch()// Order matters: the CefAppProtocol NSApplication must exist before Chromium// initializes, and Chromium must be initialized before any browser is made.let app = CraApplication.sharedlet delegate = AppDelegate()app.delegate = delegate+ Perf.phase("storeLoaded")// The newest copy of Cra runs: an older install opens a newer one, and an older// Cra holding the profile quits rather than receiving this launch (NewestCopy).@@ -57,11 +60,22 @@ MainActor.assumeIsolated {ChromiumBluetoothCache.install()+ // Only now: the "another Cra is running" and failed-start exits above leave no session marker.+ Perf.phase("chromiumStarted")+ let info = Bundle.main.infoDictionary+ PerfRecorder.configure(owner: profileIsFree,+ recording: PerfSessionRules.recording(setting: delegate.store.settings.perfRecording,+ environment: ProcessInfo.processInfo.environment),+ config: .init(folder: AppPaths.file("Perf"), chromiumFolder: AppPaths.chromiumCache),+ craVersion: "\(info?["CFBundleShortVersionString"] as? String ?? "dev") (\(info?["CFBundleVersion"] as? String ?? "?"))",+ chromiumVersion: CraCEFRuntime.chromiumVersion(), onboarding: delegate.needsOnboarding)+// Belt and braces: Chromium's run loop drives NSApplication and should call// applicationDidFinishLaunching, but bootstrapping is idempotent either way.DispatchQueue.main.async { delegate.bootstrapIfNeeded() }HitchMonitor.startIfRequested()CraCEFRuntime.runMessageLoop()+ PerfRecorder.quit()// A log that ends without this line ended in a crash or a forced quit.CraLog.note("Cra quits")CraLog.flush()diff --git a/Sources/Cra/Perf/MainLoopObserver.swift b/Sources/Cra/Perf/MainLoopObserver.swiftnew file mode 100644index 0000000..a2eb0ac--- /dev/null+++ b/Sources/Cra/Perf/MainLoopObserver.swift@@ -0,0 +1,146 @@+import Foundation+import os++/// How long the main thread goes between points where it could take input, measured from the+/// run loop itself: a CFRunLoopObserver notes the time at each pass and when the loop goes to+/// sleep, so a pass is never slept-through time. Unlike HitchMonitor it sends the main thread+/// nothing; the cost is a clock read and an uncontended lock per callback.+///+/// A pass of 2 s or more is seen while it lasts by a watchdog thread (2 Hz), which reports it+/// from its own thread: the main thread is the one that's stuck.+final class MainLoopObserver: @unchecked Sendable {+ struct Drained {+ var passes: LogHistogram+ var callbacks: Int+ /// Estimated main-thread time spent in the callbacks, and the watchdog thread's CPU time.+ var observerNs: UInt64+ var watchdogNs: UInt64+ }++ private struct Shared {+ /// When the current pass started; 0 while the run loop sleeps or before it first runs.+ var passStart: UInt64 = 0+ var passes = LogHistogram()+ var callbacks = 0+ var sampledNs: UInt64 = 0+ var sampled = 0+ var reportedPass: UInt64 = 0+ /// Until the run loop first sleeps: AppKit finishes launching (Cra's bootstrap) inside+ /// -[NSApplication run] before the loop's first pass, where no observer sees it.+ var launching = true+ var watchdogNs: UInt64 = 0+ var stopped = false+ }++ private let shared = OSAllocatedUnfairLock(initialState: Shared())+ private var observers: [CFRunLoopObserver] = []+ private let stallMs: Double+ private let hangMs: Double+ private let onStall: (_ ms: Double, _ endedAt: UInt64, _ mode: String) -> Void+ private let onHang: (_ ms: Double, _ passStart: UInt64, _ mode: String) -> Void++ /// `onStall` runs on the main thread when a pass of `stallMs` or more ends; `onHang` on the+ /// watchdog thread once per pass that reaches `hangMs` while it still lasts.+ init(stallMs: Double, hangMs: Double, onStall: @escaping (Double, UInt64, String) -> Void,+ onHang: @escaping (Double, UInt64, String) -> Void) {+ self.stallMs = stallMs+ self.hangMs = hangMs+ self.onStall = onStall+ self.onHang = onHang+ }++ func start() {+ guard observers.isEmpty else { return }+ // A pass starts before anyone else's observer runs and ends after everyone's: Core+ // Animation commits (layout, drawing) in a before-waiting observer, and that is main-thread+ // time too.+ let first: CFRunLoopActivity = [.entry, .afterWaiting, .beforeTimers]+ let last: CFRunLoopActivity = [.beforeWaiting, .exit]+ for (activities, order) in [(first, Int.min), (last, Int.max)] {+ let o = CFRunLoopObserverCreateWithHandler(nil, activities.rawValue, true, order) { [weak self] _, activity in+ self?.callback(activity)+ }!+ observers.append(o)+ CFRunLoopAddObserver(CFRunLoopGetMain(), o, .commonModes)+ }+ // From here (main.swift, before the run loop starts) the main thread is busy launching.+ let now = Perf.now()+ shared.withLock { $0.passStart = now }+ let thread = Thread { [weak self] in self?.watch() }+ thread.name = "PerfWatchdog"+ thread.qualityOfService = .utility+ thread.start()+ }++ /// The observer goes and the watchdog ends within half a second.+ func stop() {+ for o in observers { CFRunLoopObserverInvalidate(o); CFRunLoopRemoveObserver(CFRunLoopGetMain(), o, .commonModes) }+ observers = []+ shared.withLock { $0.stopped = true; $0.passStart = 0 }+ }++ /// What was measured since the last call.+ func drain() -> Drained {+ shared.withLock { s in+ let estimate = s.sampled > 0 ? s.sampledNs / UInt64(s.sampled) * UInt64(s.callbacks) : 0+ let d = Drained(passes: s.passes, callbacks: s.callbacks, observerNs: estimate, watchdogNs: s.watchdogNs)+ s.passes = LogHistogram()+ s.callbacks = 0+ s.sampledNs = 0+ s.sampled = 0+ s.watchdogNs = 0+ return d+ }+ }++ private func callback(_ activity: CFRunLoopActivity) {+ let now = Perf.now()+ let (ended, launch, timed): (Double?, Bool, Bool) = shared.withLock { s in+ s.callbacks += 1+ var ms: Double?+ let launch = s.launching+ if s.passStart != 0 {+ let pass = Double(now &- s.passStart) / 1e6+ s.passes.record(pass)+ if pass >= stallMs { ms = pass }+ }+ s.passStart = activity == .beforeWaiting ? 0 : now+ if activity == .beforeWaiting { s.launching = false }+ // One callback in 256 is timed, for the self-cost estimate.+ return (ms, launch, s.callbacks & 255 == 0)+ }+ if let ended { onStall(ended, now, launch ? "launch" : Self.currentMode()) }+ if timed {+ let cost = Perf.now() &- now+ shared.withLock { $0.sampledNs += cost; $0.sampled += 1 }+ }+ }++ private func watch() {+ while true {+ usleep(500_000)+ let start = Self.threadCPU()+ let (passStart, stopped, reported) = shared.withLock { ($0.passStart, $0.stopped, $0.reportedPass) }+ if stopped { return }+ if passStart != 0, passStart != reported {+ let ms = Double(Perf.now() &- passStart) / 1e6+ if ms >= hangMs {+ shared.withLock { $0.reportedPass = passStart }+ let launch = shared.withLock { $0.launching }+ onHang(ms, passStart, launch ? "launch" : Self.currentMode())+ }+ }+ let cost = Self.threadCPU() &- start+ shared.withLock { $0.watchdogNs += cost + 2_000 } // + the wakeup itself, about 2 µs+ }+ }++ /// The main run loop's mode right now ("none" between runs).+ static func currentMode() -> String {+ guard let mode = CFRunLoopCopyCurrentMode(CFRunLoopGetMain()) else { return "none" }+ return mode.rawValue as String+ }++ /// CPU time the calling thread has used, in nanoseconds.+ static func threadCPU() -> UInt64 { clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) }+}diff --git a/Sources/Cra/Perf/Perf.swift b/Sources/Cra/Perf/Perf.swiftnew file mode 100644index 0000000..106b2cb--- /dev/null+++ b/Sources/Cra/Perf/Perf.swift@@ -0,0 +1,109 @@+import Foundation++/// The one way the rest of Cra reaches the performance recorder (GitHub #91, docs/performance.md).+/// Small facts, recorded under one lock: a duration, a count, a breadcrumb. Nothing here does+/// file I/O, encoding or system calls, and it depends on neither CEF nor libproc, so the test+/// harnesses compile the files that call it unchanged. Until the recorder starts the facts wait+/// in a short buffer (start-up decodes JSON before Chromium is up); when recording is off they+/// are dropped.+enum Perf {+ /// One fact for the recorder; `at` is `Perf.now()`.+ enum Fact {+ case time(PerfMetric, ms: Double)+ case count(PerfCounter, key: String, site: String?, at: UInt64)+ case mark(String, at: UInt64)+ case phase(String, ms: Double)+ case visibleSite(String?)+ }++ private static let lock = NSLock()+ nonisolated(unsafe) private static var sink: ((Fact) -> Void)?+ nonisolated(unsafe) private static var early: [Fact]? = []+ nonisolated(unsafe) private static var started: [String: UInt64] = [:]+ nonisolated(unsafe) private(set) static var launchedAt: UInt64 = now()++ /// Monotonic nanoseconds (the clock DispatchTime and mach_absolute_time share).+ static func now() -> UInt64 { DispatchTime.now().uptimeNanoseconds }++ static func ms(since t: UInt64) -> Double { Double(now() &- t) / 1e6 }++ /// The top of main.swift: start-up phases count from here.+ static func launch() { launchedAt = now() }++ /// The recorder, once it starts; nil when recording is off (buffered facts are dropped).+ static func attach(_ newSink: ((Fact) -> Void)?) {+ lock.lock()+ sink = newSink+ let pending = early ?? []+ early = nil+ started = [:]+ lock.unlock()+ if let newSink { pending.forEach(newSink) }+ }++ static var isRecording: Bool {+ lock.lock()+ defer { lock.unlock() }+ return sink != nil+ }++ private static func send(_ fact: Fact) {+ lock.lock()+ if early != nil {+ if early!.count < 256 { early!.append(fact) }+ lock.unlock()+ return+ }+ let s = sink+ lock.unlock()+ s?(fact)+ }++ static func time(_ metric: PerfMetric, ms: Double) { send(.time(metric, ms: ms)) }++ /// Times `work` on the calling thread.+ @discardableResult+ static func time<T>(_ metric: PerfMetric, _ work: () throws -> T) rethrows -> T {+ let t = now()+ defer { time(metric, ms: ms(since: t)) }+ return try work()+ }++ static func count(_ counter: PerfCounter, _ key: String = "", site: String? = nil) {+ send(.count(counter, key: key, site: site, at: now()))+ }++ /// A breadcrumb (HitchMonitor.mark forwards here): what a stall report says Cra did before it.+ static func mark(_ label: String) { send(.mark(label, at: now())) }++ /// A start-up phase reached, in milliseconds since `launch()`; only the first counts.+ static func phase(_ name: String) { send(.phase(name, ms: ms(since: launchedAt))) }++ /// The site of the page put on screen last, for the stalls that happen while it is (nil: none,+ /// or incognito).+ static func visibleSite(_ host: String?) { send(.visibleSite(host)) }++ /// A duration that ends on another call: `begin` and `end` with the same key. A begin+ /// without an end (a page closed while loading) is forgotten by `cancel` or the next begin.+ static func begin(_ metric: PerfMetric, _ key: String) {+ lock.lock()+ defer { lock.unlock() }+ guard sink != nil || early != nil else { return }+ // Keys are tab ids; a leak (begins that never end) is cut off rather than kept.+ if started.count > 512 { started = [:] }+ started[metric.rawValue + key] = now()+ }++ static func end(_ metric: PerfMetric, _ key: String) {+ lock.lock()+ let t = started.removeValue(forKey: metric.rawValue + key)+ lock.unlock()+ if let t { time(metric, ms: ms(since: t)) }+ }++ static func cancel(_ metric: PerfMetric, _ key: String) {+ lock.lock()+ started[metric.rawValue + key] = nil+ lock.unlock()+ }+}diff --git a/Sources/Cra/Perf/PerfCEF.swift b/Sources/Cra/Perf/PerfCEF.swiftnew file mode 100644index 0000000..375e23d--- /dev/null+++ b/Sources/Cra/Perf/PerfCEF.swift@@ -0,0 +1,62 @@+import AppKit+import CraCEF++/// The performance recorder's app side, the one Perf file that sees Chromium (lint: perf-boundary):+/// renderer trouble and failed loads from CraCEF, the visible tab's long tasks from Cra's isolated+/// world, tab counts from the windows, and the Settings switch.+@MainActor+enum PerfCEF {+ /// From AppDelegate.bootstrapIfNeeded.+ static func install(app: AppDelegate) {+ CraCEFRuntime.setProcessEventHandler { kind, detail, site in+ switch kind {+ case "terminated": Perf.count(.rendererTerminated, detail, site: site)+ case "unresponsive": Perf.count(.rendererUnresponsive, site: site)+ case "responsive": Perf.count(.rendererResponsive, site: site)+ case "loadError": Perf.count(.loadError, detail, site: site)+ default: break+ }+ }+ PerfRecorder.mainSampler = { [weak app] recorder in+ guard let app else { return }+ let start = MainLoopObserver.threadCPU()+ recorder.tabs(tabCounts(app))+ if let browser = app.main?.currentBrowser, browser.isCreated, !browser.isClosed { readLongTasks(browser, recorder) }+ recorder.addMainThreadCost(ns: MainLoopObserver.threadCPU() &- start)+ }+ let environment = ProcessInfo.processInfo.environment+ observeChanges(of: { [store = app.store] in store.settings.perfRecording }) { on in+ PerfRecorder.setRecording(PerfSessionRules.recording(setting: on, environment: environment))+ }+ }++ private static func tabCounts(_ app: AppDelegate) -> PerfTabCounts {+ let managers = app.mainWindows.compactMap(\.browsers)+ return PerfTabCounts(tabs: app.store.allTabs().count,+ live: managers.reduce(0) { $0 + $1.runtimes.count },+ visible: managers.reduce(0) { $0 + $1.visibleTabIDs.count },+ slept: managers.reduce(0) { $0 + $1.sleptTabs.count },+ incognito: managers.reduce(0) { $0 + $1.runtimes.values.filter { $0.browser.isIncognito }.count },+ windows: app.mainWindows.filter { $0.window?.isVisible == true }.count)+ }++ /// Reads and resets the counters PageScript keeps in `__cra.lt`. A page without them (Cra's+ /// own pages, one still loading) answers null.+ private static let readLongTasksParams: String = {+ let js = "(() => { const l = window.__cra?.lt; if (!l || !l.n) return null; const r = JSON.stringify([l.n, l.t, l.d]); l.n = 0; l.t = 0; l.d = []; return r; })()"+ let params: [String: Any] = ["expression": js, "returnByValue": true]+ return String(decoding: (try? JSONSerialization.data(withJSONObject: params)) ?? Data(), as: UTF8.self)+ }()++ private static func readLongTasks(_ browser: CraBrowser, _ recorder: PerfRecorder) {+ browser.evaluate(inIsolatedWorld: PageScript.world, params: readLongTasksParams) { [weak recorder] result, _ in+ guard let data = result?.data(using: .utf8),+ let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],+ let value = (json["result"] as? [String: Any])?["value"] as? String,+ let triple = (try? JSONSerialization.jsonObject(with: Data(value.utf8))) as? [Any], triple.count == 3,+ let count = triple[0] as? Int, let total = triple[1] as? Double else { return }+ let durations = (triple[2] as? [Double]) ?? []+ DispatchQueue.main.async { recorder?.pageLongTasks(count: count, totalMs: total, durations: durations) }+ }+ }+}diff --git a/Sources/Cra/Perf/PerfFiles.swift b/Sources/Cra/Perf/PerfFiles.swiftnew file mode 100644index 0000000..474a9e6--- /dev/null+++ b/Sources/Cra/Perf/PerfFiles.swift@@ -0,0 +1,60 @@+import Foundation++/// `Application Support/Cra/Perf/`: the black box (the last minute), the 24-hour history, the+/// session marker and the hang files. Written atomically (a temporary file renamed over the+/// old one), not through JSONStore, which copies a `.bak` on every save. Under 2 MB in all.+struct PerfFiles {+ let folder: URL++ init(folder: URL) { self.folder = folder }++ /// Only a Cra that writes makes the folder: a second launch or a recording that is off leaves+ /// the data folder as it was.+ func prepare() { try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) }++ var blackBox: URL { folder.appendingPathComponent("blackbox.json") }+ var previousBlackBox: URL { folder.appendingPathComponent("blackbox.previous.json") }+ var history: URL { folder.appendingPathComponent("history.json") }+ var marker: URL { folder.appendingPathComponent("session.open") }+ func hang(session: String, number: Int) -> URL { folder.appendingPathComponent("hang-\(session)-\(number).json") }++ /// Bytes written, 0 when the write failed (a full disk must not stop anything else).+ @discardableResult+ func write<T: Encodable>(_ value: T, to url: URL, pretty: Bool = true) -> Int {+ guard let data = try? PerfReport.encoder(pretty: pretty).encode(value) else { return 0 }+ do { try data.write(to: url, options: .atomic) } catch { return 0 }+ return data.count+ }++ func read<T: Decodable>(_ type: T.Type, from url: URL) -> T? {+ (try? Data(contentsOf: url)).flatMap { try? PerfReport.decoder.decode(T.self, from: $0) }+ }++ /// At launch: the last session's black box becomes the previous one, and hang files older+ /// than the last session go: two sessions' worth, three each at most.+ func rotate(keepingHangsOf previousSession: String?) {+ let fm = FileManager.default+ if fm.fileExists(atPath: blackBox.path) {+ try? fm.removeItem(at: previousBlackBox)+ try? fm.moveItem(at: blackBox, to: previousBlackBox)+ }+ let keep = previousSession.map { "hang-\($0)-" }+ for f in hangFiles() where keep.map({ !f.lastPathComponent.hasPrefix($0) }) ?? true {+ try? fm.removeItem(at: f)+ }+ }++ func hangFiles() -> [URL] {+ ((try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.contentModificationDateKey])) ?? [])+ .filter { $0.lastPathComponent.hasPrefix("hang-") && $0.pathExtension == "json" }+ .sorted { $0.lastPathComponent < $1.lastPathComponent }+ }++ /// Settings ▸ Performance ▸ Clear: everything but the marker of the session that is running.+ func clear() {+ let fm = FileManager.default+ for f in (try? fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? [] where f != marker {+ try? fm.removeItem(at: f)+ }+ }+}diff --git a/Sources/Cra/Perf/PerfRecorder.swift b/Sources/Cra/Perf/PerfRecorder.swiftnew file mode 100644index 0000000..b548cc9--- /dev/null+++ b/Sources/Cra/Perf/PerfRecorder.swift@@ -0,0 +1,347 @@+import Foundation++/// Cra's own performance, recorded on this Mac (GitHub #91, docs/performance.md). Data flows one+/// way. The main thread records small facts under one lock (Perf, the run-loop observer); the+/// watchdog thread writes a hang file itself while the main thread is blocked; one serial queue+/// samples processes and the system every 5 s, writes the black box every 60 s and the history+/// every 15 minutes, and builds the export. Nothing on the main thread does file I/O, JSON+/// encoding or libproc calls. Nothing here touches the network (lint: perf-no-network).+final class PerfRecorder: @unchecked Sendable {+ struct Config {+ var sampleInterval: Double = 5+ var blackBoxEvery = 12 // samples: 60 s+ var historyEvery = 180 // samples: 15 min+ var policy = PerfStallPolicy()+ /// `/usr/bin/sample` on Cra at a hang, at most this many times a session (0: never).+ var stacks = 3+ var folder: URL+ var chromiumFolder: URL?+ }++ /// The running recorder; nil while recording is off.+ nonisolated(unsafe) private(set) static var shared: PerfRecorder?+ /// Whether this Cra owns the data folder (only the owner writes), from main.swift.+ nonisolated(unsafe) private static var owner = false+ nonisolated(unsafe) private static var config: Config?+ nonisolated(unsafe) private static var appInfo = (cra: "", chromium: "", onboarding: false)++ /// Called on the main thread every sample: the app counts tabs and reads the visible page's+ /// long tasks (PerfCEF), then reports back through `tabs(_:)` and `pageLongTasks`.+ nonisolated(unsafe) static var mainSampler: (@MainActor (PerfRecorder) -> Void)?++ let config: Config+ let writesFiles: Bool+ let sessionID = String(UUID().uuidString.prefix(8)).lowercased()+ private let files: PerfFiles+ private let queue = DispatchQueue(label: "dk.kildahl.cra.perf", qos: .utility)+ private let lock = NSLock()+ private var state = PerfState()+ private var history = PerfHistory()+ private var session: PerfSessionInfo+ private let startedAt = Date()+ private var observer: MainLoopObserver?+ private var timer: DispatchSourceTimer?+ private var processes = PerfProcessTable()+ private var processSampler = PerfProcessSampler()+ private var system = PerfSystemSampler()+ private var samples = 0+ private var hangs = 0+ private var hangFiles: [UInt64: URL] = [:]+ /// What recording costs, under `lock` (the queue, the watchdog and the main thread add to it).+ private var cost = (cpuNs: UInt64(0), observerNs: UInt64(0), callbacks: 0, bytes: 0, writes: 0)+ private var stopped = false++ // MARK: Lifecycle (main.swift, the settings observer)++ /// After Chromium started: `owner` is CraLog's answer, `recording` the setting and CRA_PERF.+ static func configure(owner: Bool, recording: Bool, config: Config, craVersion: String, chromiumVersion: String, onboarding: Bool) {+ Self.owner = owner+ Self.config = config+ appInfo = (craVersion, chromiumVersion, onboarding)+ setRecording(recording)+ }++ /// Settings ▸ Performance ▸ "Record performance". Off: no samples, no timers, no writes+ /// (files already written stay until Clear).+ static func setRecording(_ on: Bool) {+ guard let config else { return }+ if on, shared == nil {+ let r = PerfRecorder(config: config, writesFiles: PerfSessionRules.writesFiles(owner: owner, recording: true))+ shared = r+ Perf.attach { [weak r] fact in r?.record(fact) }+ r.start()+ } else if !on {+ Perf.attach(nil)+ shared?.stop(clean: false)+ shared = nil+ }+ }++ /// Cra quits: the history is saved and the marker removed, so the next launch knows this one+ /// ended normally.+ static func quit() {+ Perf.attach(nil)+ shared?.stop(clean: true)+ shared = nil+ }++ init(config: Config, writesFiles: Bool) {+ self.config = config+ self.writesFiles = writesFiles+ files = PerfFiles(folder: config.folder)+ state.policy = config.policy+ session = PerfSessionInfo(id: sessionID, launch: 0, startedAt: startedAt, uptimeSeconds: 0, craVersion: Self.appInfo.cra,+ chromiumVersion: Self.appInfo.chromium, onboarding: Self.appInfo.onboarding, firstLaunchAt: nil,+ previous: nil, writesFiles: writesFiles)+ }++ private func start() {+ // Reading is allowed to anyone; only the owner moves, prunes or writes.+ history = files.read(PerfHistory.self, from: files.history) ?? PerfHistory()+ let marker = writesFiles ? files.read(PerfSessionMarker.self, from: files.marker) : nil+ session.previous = PerfSessionRules.previous(marker: marker, history: history)+ if writesFiles {+ files.prepare()+ files.rotate(keepingHangsOf: session.previous?.id)+ history.launches += 1+ if history.firstLaunchAt == nil { history.firstLaunchAt = startedAt }+ write(PerfSessionMarker(id: sessionID, launch: history.launches, startedAt: startedAt, pid: getpid(), craVersion: session.craVersion),+ to: files.marker)+ }+ session.launch = history.launches+ session.firstLaunchAt = history.firstLaunchAt+ if session.previous?.abnormal == true { CraLog.note("perf: the previous session (\(session.previous!.id)) ended without quitting") }++ let o = MainLoopObserver(stallMs: config.policy.stallMs, hangMs: config.policy.hangMs,+ onStall: { [weak self] ms, end, mode in self?.passEnded(ms: ms, at: end, mode: mode) },+ onHang: { [weak self] ms, start, mode in self?.hangStarted(ms: ms, at: start, mode: mode) })+ observer = o+ o.start()+ let t = DispatchSource.makeTimerSource(queue: queue)+ t.schedule(deadline: .now() + config.sampleInterval, repeating: config.sampleInterval, leeway: .milliseconds(500))+ t.setEventHandler { [weak self] in self?.tick() }+ timer = t+ t.resume()+ queue.async { [weak self] in self?.measured { self?.sampleProcesses() } }+ }++ private func stop(clean: Bool) {+ guard !stopped else { return }+ stopped = true+ observer?.stop()+ timer?.cancel()+ queue.sync {+ guard writesFiles else { return }+ if clean {+ pullObserver()+ history.record(lock.withLock { state.historySample() }, at: Date())+ history.lastSession = PerfPreviousSession(id: sessionID, launch: session.launch, startedAt: startedAt,+ craVersion: session.craVersion, abnormal: false, endedAt: Date())+ write(history, to: files.history, pretty: false)+ write(buildReport(), to: files.blackBox)+ }+ try? FileManager.default.removeItem(at: files.marker)+ }+ }++ // MARK: Facts++ private func seconds(_ at: UInt64) -> Double { Double(Int64(bitPattern: at &- Perf.launchedAt)) / 1e9 }++ private func record(_ fact: Perf.Fact) {+ lock.lock()+ defer { lock.unlock() }+ switch fact {+ case .time(let metric, let ms): state.time(metric, ms: ms)+ case .count(let counter, let key, let site, let at): state.count(counter, key: key, at: seconds(at), site: site)+ case .mark(let label, let at): state.mark(label, at: seconds(at))+ case .phase(let name, let ms): state.phase(name, ms: ms)+ case .visibleSite(let host): state.visibleSite = host+ }+ }++ /// The main thread, after a pass of a quarter second or more.+ private func passEnded(ms: Double, at: UInt64, mode: String) {+ let stall = lock.withLock { state.pass(ms: ms, endedAt: seconds(at), mode: mode) }+ if let stall, stall.kind != .stall { CraLog.note("perf: main thread blocked \(Int(ms)) ms (\(stall.mode))\(stall.marks.last.map { " after \($0)" } ?? "")") }+ // The hang file of this pass learns how it ended.+ let start = at &- UInt64(ms * 1e6)+ queue.async { [weak self] in+ guard let self, let url = self.hangFiles.first(where: { abs(Int64(bitPattern: $0.key &- start)) < 50_000_000 })?.value,+ var hang = self.files.read(PerfHang.self, from: url) else { return }+ hang.endedMs = ms+ self.write(hang, to: url)+ }+ }++ /// The watchdog thread, while the main thread is still blocked: the file is written now, in+ /// case Cra never comes back (a force quit), then the stack is added.+ private func hangStarted(ms: Double, at start: UInt64, mode: String) {+ let (number, marks, site): (Int, [String], String?) = lock.withLock {+ hangs += 1+ let s = state.policy.stall(at: seconds(Perf.now()), ms: ms, mode: mode, marks: state.marks.elements, site: state.visibleSite)+ return (hangs, s?.marks ?? [], state.visibleSite)+ }+ guard writesFiles, number <= 3 else { return }+ let hang = PerfHang(session: sessionID, number: number, at: seconds(start), stalledMs: ms,+ mode: PerfStallPolicy.shortMode(mode), marks: marks, site: site,+ stackNote: number <= config.stacks ? "sampling" : "stacks off")+ let url = files.hang(session: sessionID, number: number)+ write(hang, to: url)+ queue.async { [weak self] in self?.hangFiles[start] = url }+ guard number <= config.stacks else { return }+ let stack = Self.sampleMainThread()+ // On the queue, after any `endedMs` the main thread's recovery queued while `sample` ran.+ queue.sync {+ var latest = files.read(PerfHang.self, from: url) ?? hang+ latest.stack = stack+ latest.stackNote = stack.isEmpty ? "sample gave no main thread" : nil+ write(latest, to: url)+ }+ }++ /// One second of `/usr/bin/sample` on Cra, every 10 ms, from the watchdog thread.+ private static func sampleMainThread() -> [String] {+ let out = FileManager.default.temporaryDirectory.appendingPathComponent("cra-hang-\(UUID().uuidString).txt")+ defer { try? FileManager.default.removeItem(at: out) }+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/usr/bin/sample")+ p.arguments = [String(getpid()), "1", "10", "-mayDie", "-file", out.path]+ p.standardOutput = FileHandle.nullDevice+ p.standardError = FileHandle.nullDevice+ do { try p.run() } catch { return [] }+ p.waitUntilExit()+ guard let text = try? String(contentsOf: out, encoding: .utf8) else { return [] }+ return PerfSampleStack.mainThread(from: text)+ }++ /// From the main sampler.+ @MainActor func tabs(_ counts: PerfTabCounts) { lock.withLock { state.tabs = counts } }++ @MainActor func pageLongTasks(count: Int, totalMs: Double, durations: [Double]) {+ lock.withLock { state.pageLongTasks(count: count, totalMs: totalMs, durations: durations) }+ }++ @MainActor func addMainThreadCost(ns: UInt64) { lock.withLock { cost.cpuNs &+= ns } }++ // MARK: The queue++ private func tick() {+ measured {+ samples += 1+ sampleProcesses()+ pullObserver()+ history.record(lock.withLock { state.historySample() }, at: Date())+ if writesFiles, samples % config.blackBoxEvery == 0 { write(buildReport(), to: files.blackBox) }+ if writesFiles, samples % config.historyEvery == 0 { write(history, to: files.history, pretty: false) }+ }+ if let sampler = Self.mainSampler {+ DispatchQueue.main.async { [weak self] in if let self { sampler(self) } }+ }+ }++ private func measured(_ work: () -> Void) {+ let start = MainLoopObserver.threadCPU()+ work()+ let used = MainLoopObserver.threadCPU() &- start+ lock.withLock { cost.cpuNs &+= used }+ }++ private func sampleProcesses() {+ let groups = processes.update(processSampler.read(), atNs: Perf.now())+ let sys = system.read(dataFolder: config.folder)+ lock.withLock {+ state.processes = groups+ state.system = sys+ }+ }++ private func pullObserver() {+ guard let d = observer?.drain() else { return }+ lock.withLock {+ state.addPasses(d.passes)+ cost.cpuNs &+= d.observerNs &+ d.watchdogNs+ cost.observerNs &+= d.observerNs+ cost.callbacks += d.callbacks+ }+ }++ private func write<T: Encodable>(_ value: T, to url: URL, pretty: Bool = true) {+ let n = files.write(value, to: url, pretty: pretty)+ lock.withLock {+ cost.bytes += n+ cost.writes += 1+ }+ }++ /// On the queue.+ private func buildReport(storage: PerfReport.Storage = PerfReport.Storage()) -> PerfReport {+ var info = session+ info.uptimeSeconds = Date().timeIntervalSince(startedAt)+ let uptimeMs = max(info.uptimeSeconds * 1000, 1)+ let (snapshot, c) = lock.withLock { (state, cost) }+ let selfCost = PerfSelfCost(cpuMs: Double(c.cpuNs) / 1e6, cpuPct: Double(c.cpuNs) / 1e6 / uptimeMs * 100,+ observerCallbacks: c.callbacks, observerMs: Double(c.observerNs) / 1e6,+ bytesWritten: c.bytes, writes: c.writes,+ memoryBytes: snapshot.estimatedBytes + history.buckets.count * 120)+ return snapshot.report(generatedAt: Date(), session: info, selfCost: selfCost, storage: storage)+ }++ // MARK: Reading (the pane, the export, scenarios)++ /// The report as of now, on the main thread.+ func snapshot(_ done: @escaping @MainActor (PerfReport) -> Void) {+ queue.async { [weak self] in+ guard let self else { return }+ self.measured { self.pullObserver() }+ let r = self.buildReport()+ DispatchQueue.main.async { done(r) }+ }+ }++ /// Help ▸ Export Diagnostics: `perf.json` (with the profile's size, measured now), the previous+ /// session's black box and the hang files, as text for the zip (Diagnostics redacts them).+ static func exportFiles(_ done: @escaping @MainActor ([(name: String, text: String)], Set<String>) -> Void) {+ let r = shared+ let folder = config?.folder+ let chromium = config?.chromiumFolder+ let work = {+ var out: [(String, String)] = []+ var sites = Set<String>()+ let sizes = chromium.map(PerfFolderSizes.measure)+ if let r {+ r.pullObserver()+ let report = r.buildReport(storage: .init(profileBytes: sizes?.profile, cacheBytes: sizes?.cache))+ sites = report.sites+ if let data = try? PerfReport.encoder().encode(report) { out.append(("perf.json", String(decoding: data, as: UTF8.self))) }+ } else {+ out.append(("perf.json", "{\n \"recording\" : false\n}\n"))+ }+ if let folder {+ let files = PerfFiles(folder: folder)+ for url in [files.previousBlackBox] + files.hangFiles() {+ if let data = try? Data(contentsOf: url) { out.append(("perf/" + url.lastPathComponent, String(decoding: data, as: UTF8.self))) }+ }+ }+ DispatchQueue.main.async { done(out, sites) }+ }+ if let r { r.queue.async(execute: work) } else { DispatchQueue.global(qos: .utility).async(execute: work) }+ }++ /// Settings ▸ Performance ▸ Clear: the files, and what this session recorded so far.+ static func clear() {+ if let r = shared {+ r.queue.async {+ r.lock.withLock {+ let policy = r.state.policy+ r.state = PerfState()+ r.state.policy = policy+ }+ r.history = PerfHistory()+ if r.writesFiles { r.files.clear() }+ }+ } else if let folder = config?.folder {+ PerfFiles(folder: folder).clear()+ }+ }+}diff --git a/Sources/Cra/Perf/PerfSamplers.swift b/Sources/Cra/Perf/PerfSamplers.swiftnew file mode 100644index 0000000..9bb636d--- /dev/null+++ b/Sources/Cra/Perf/PerfSamplers.swift@@ -0,0 +1,145 @@+import Darwin+import Foundation++/// Cra and its helper processes through libproc: one `proc_pid_rusage` per process, about a+/// millisecond for the lot. Public API, no task ports, works on a notarized hardened build+/// (Chromium's helpers are Cra's children and the same user's processes).+struct PerfProcessSampler {+ /// What each helper is, read once per process (its arguments don't change).+ private var kinds: [pid_t: PerfProcessKind] = [:]++ mutating func read() -> [PerfProcessReading] {+ let me = getpid()+ let pids = [me] + Self.children(of: me)+ kinds = kinds.filter { pids.contains($0.key) }+ return pids.map { pid in+ var info = rusage_info_v4()+ let ok = withUnsafeMutablePointer(to: &info) {+ $0.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(pid, RUSAGE_INFO_V4, $0) }+ } == 0+ let kind = kinds[pid] ?? PerfProcessKind.of(name: Self.name(of: pid), isSelf: pid == me, type: Self.chromiumType(of: pid))+ kinds[pid] = kind+ guard ok else {+ return PerfProcessReading(pid: pid, kind: kind, cpuNs: nil, footprintBytes: nil, diskReadBytes: nil, diskWriteBytes: nil, wakeups: nil)+ }+ return PerfProcessReading(pid: pid, kind: kind, cpuNs: Self.nanoseconds(info.ri_user_time &+ info.ri_system_time),+ footprintBytes: Int64(clamping: info.ri_phys_footprint),+ diskReadBytes: Int64(clamping: info.ri_diskio_bytesread),+ diskWriteBytes: Int64(clamping: info.ri_diskio_byteswritten),+ wakeups: Int64(clamping: info.ri_pkg_idle_wkups &+ info.ri_interrupt_wkups))+ }+ }++ /// Chromium starts every helper itself, so they are its children. `proc_listchildpids` is in+ /// the public libproc.h but undocumented; `proc_listpids(PROC_PPID_ONLY)` is the fallback.+ static func children(of pid: pid_t) -> [pid_t] {+ var buffer = [pid_t](repeating: 0, count: 1024)+ let size = Int32(buffer.count * MemoryLayout<pid_t>.size)+ let n = proc_listchildpids(pid, &buffer, size)+ if n > 0 { return Array(buffer.prefix(Int(min(n, Int32(buffer.count))))).filter { $0 > 0 } }+ let bytes = proc_listpids(UInt32(PROC_PPID_ONLY), UInt32(pid), &buffer, size)+ guard bytes > 0 else { return [] }+ return Array(buffer.prefix(Int(bytes) / MemoryLayout<pid_t>.size)).filter { $0 > 0 }+ }++ /// Chromium's `--type=` (renderer, gpu-process, utility) from the process's arguments, which+ /// macOS gives the same user's processes (what `ps` reads).+ static func chromiumType(of pid: pid_t) -> String? {+ var mib = [CTL_KERN, KERN_PROCARGS2, pid]+ var size = 0+ guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > 0 else { return nil }+ var buffer = [UInt8](repeating: 0, count: size)+ guard sysctl(&mib, 3, &buffer, &size, nil, 0) == 0 else { return nil }+ for arg in buffer.prefix(size).split(separator: 0) {+ let s = String(decoding: arg, as: UTF8.self)+ if s.hasPrefix("--type=") { return String(s.dropFirst(7)) }+ }+ return nil+ }++ static func name(of pid: pid_t) -> String {+ var buffer = [CChar](repeating: 0, count: 64)+ guard proc_name(pid, &buffer, UInt32(buffer.count)) > 0 else { return "" }+ return String(cString: buffer)+ }++ /// rusage times are mach ticks (125/3 ns each on Apple silicon).+ private static let timebase: (numer: UInt64, denom: UInt64) = {+ var tb = mach_timebase_info_data_t()+ mach_timebase_info(&tb)+ return (UInt64(max(tb.numer, 1)), UInt64(max(tb.denom, 1)))+ }()++ static func nanoseconds(_ ticks: UInt64) -> UInt64 { ticks.multipliedReportingOverflow(by: timebase.numer).partialValue / timebase.denom }+}++/// The Mac as a whole: CPU over the last interval, memory pressure, heat, Low Power Mode, free disk.+struct PerfSystemSampler {+ private var previousTicks: [UInt64]?+ private var freeDisk: (bytes: Int64?, at: UInt64) = (nil, 0)++ mutating func read(dataFolder: URL) -> PerfSystemSample {+ let now = Perf.now()+ // The volume's free space changes slowly and costs a file-system call: once a minute.+ if freeDisk.at == 0 || now &- freeDisk.at > 60_000_000_000 {+ let values = try? dataFolder.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])+ freeDisk = (values?.volumeAvailableCapacityForImportantUsage, now)+ }+ let thermal: String+ switch ProcessInfo.processInfo.thermalState {+ case .nominal: thermal = "nominal"+ case .fair: thermal = "fair"+ case .serious: thermal = "serious"+ case .critical: thermal = "critical"+ @unknown default: thermal = "unknown"+ }+ return PerfSystemSample(cpuPct: cpu(), memoryPressure: PerfSystemSample.pressure(level: Self.pressureLevel()),+ thermalState: thermal, lowPowerMode: ProcessInfo.processInfo.isLowPowerModeEnabled,+ freeDiskBytes: freeDisk.bytes)+ }++ /// All cores' user, system, idle and nice ticks since boot; busy share since the last call.+ private mutating func cpu() -> Double? {+ var info = host_cpu_load_info()+ var count = mach_msg_type_number_t(MemoryLayout<host_cpu_load_info>.size / MemoryLayout<integer_t>.size)+ let r = withUnsafeMutablePointer(to: &info) {+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, $0, &count) }+ }+ guard r == KERN_SUCCESS else { return nil }+ let t = info.cpu_ticks+ let ticks = [UInt64(t.0), UInt64(t.1), UInt64(t.2), UInt64(t.3)] // user, system, idle, nice+ defer { previousTicks = ticks }+ guard let p = previousTicks else { return nil }+ let d = zip(ticks, p).map { $0 >= $1 ? $0 - $1 : 0 }+ let total = d.reduce(0, +)+ guard total > 0 else { return nil }+ return Double(total - d[2]) / Double(total) * 100+ }++ static func pressureLevel() -> Int32? {+ var level: Int32 = 0+ var size = MemoryLayout<Int32>.size+ return sysctlbyname("kern.memorystatus_vm_pressure_level", &level, &size, nil, 0) == 0 ? level : nil+ }+}++enum PerfFolderSizes {+ /// Chromium's caches inside a profile: they grow and shrink by themselves.+ static let cacheFolders: Set<String> = ["Cache", "Code Cache", "GPUCache", "DawnGraphiteCache", "DawnWebGPUCache", "GrShaderCache", "ShaderCache"]++ /// The Chromium folder's size without its caches, and the caches. Walks every file: only at+ /// export and when the Performance pane asks, never on a timer.+ static func measure(_ chromium: URL) -> (profile: Int64, cache: Int64) {+ let keys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .isDirectoryKey]+ guard let walk = FileManager.default.enumerator(at: chromium, includingPropertiesForKeys: keys, options: [], errorHandler: { _, _ in true })+ else { return (0, 0) }+ var profile: Int64 = 0, cache: Int64 = 0+ for case let url as URL in walk {+ guard let v = try? url.resourceValues(forKeys: Set(keys)), v.isDirectory != true else { continue }+ let size = Int64(v.totalFileAllocatedSize ?? 0)+ let relative = url.path.dropFirst(chromium.path.count).split(separator: "/")+ if relative.contains(where: { cacheFolders.contains(String($0)) }) { cache += size } else { profile += size }+ }+ return (profile, cache)+ }+}diff --git a/Sources/Cra/Perf/PerformancePane.swift b/Sources/Cra/Perf/PerformancePane.swiftnew file mode 100644index 0000000..3b6fd5c--- /dev/null+++ b/Sources/Cra/Perf/PerformancePane.swift@@ -0,0 +1,230 @@+import AppKit+import SwiftUI++/// Settings ▸ Performance (GitHub #91): what the recorder measured this session, read every two+/// seconds while the pane is on screen and never while it isn't. Card style like Privacy. Not in+/// Dia or Arc: Cra's own, for reports of freezes that are gone by the time they are written up.+struct PerformancePane: View {+ let nav: SettingsNavigation+ let actions: SettingsActions+ @Environment(SidebarStore.self) private var store+ @State private var section = Section.overview+ @State private var report: PerfReport?+ @State private var copied = false++ enum Section: String, CaseIterable { case overview = "Overview", events = "Events", export = "Export" }++ var body: some View {+ @Bindable var store = store+ SettingsCardPane {+ Picker("", selection: $section) { ForEach(Section.allCases, id: \.self) { Text($0.rawValue).tag($0) } }+ .pickerStyle(.segmented).labelsHidden().fixedSize()+ .frame(maxWidth: .infinity)+ .padding(.bottom, 16)+ switch section {+ case .overview: overview($store.settings.perfRecording)+ case .events: events+ case .export: export($store.settings.perfHidesSiteNames)+ }+ }+ .task(id: RefreshKey(open: nav.isOpen, recording: store.settings.perfRecording)) {+ report = nil+ guard nav.isOpen, store.settings.perfRecording else { return }+ while !Task.isCancelled {+ if let r = PerfRecorder.shared { r.snapshot { report = $0 } }+ try? await Task.sleep(for: .seconds(2))+ }+ }+ }++ private struct RefreshKey: Equatable { var open: Bool; var recording: Bool }++ // MARK: Overview++ @ViewBuilder private func overview(_ recording: Binding<Bool>) -> some View {+ SettingsCard {+ SettingsCardRow {+ HStack(spacing: 5.5) {+ SettingsGlyph(symbol: "gauge.with.dots.needle.67percent", color: Color(nsColor: .systemBlue))+ Text("Record performance").font(.system(size: 13))+ }+ } trailing: {+ Toggle("Record performance", isOn: recording).toggleStyle(.switch).labelsHidden()+ }+ }+ SettingsFootnote("Cra measures itself on this Mac: freezes, CPU and memory per process, tab timings. Nothing leaves the Mac unless you export it with Help ▸ Export Diagnostics.")++ if let r = report {+ if !r.insights.isEmpty {+ SettingsHeader("Findings").padding(.top, 20)+ SettingsCard {+ ForEach(Array(r.insights.enumerated()), id: \.element.id) { i, insight in+ if i > 0 { SettingsCardDivider() }+ SettingsCardRow {+ HStack(alignment: .top, spacing: 8) {+ Image(systemName: insight.severity == .warning ? "exclamationmark.triangle.fill" : "info.circle.fill")+ .foregroundStyle(insight.severity == .warning ? Color(nsColor: .systemOrange) : Color.secondary)+ VStack(alignment: .leading, spacing: 2) {+ Text(insight.title).font(.system(size: 13))+ Text(insight.detail).font(.system(size: 11)).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ }+ } trailing: { EmptyView() }+ }+ }+ }+ let m = r.mainThread+ card("Main thread", [+ ("Stalls of ¼ s or more", "\(m.stalls)"),+ ("Freezes of 1 s or more", "\(m.longStalls)"),+ ("Longest", m.longestMs > 0 ? PerfInsights.duration(m.longestMs) : "–"),+ ("Typical pass (99 %)", PerfInsights.duration(m.passes.percentile(0.99))),+ ])+ card("Processes", r.processes.filter { $0.count > 0 }.map { g in+ (g.kind.label + (g.count > 1 ? " ×\(g.count)" : ""),+ g.available ? "\(String(format: "%.1f", g.cpuPct)) % CPU · \(PerfInsights.bytes(g.footprintBytes))" : "not available")+ })+ if let s = r.system {+ card("Mac", [+ ("CPU, all cores", s.cpuPct.map { "\(Int($0.rounded())) %" } ?? "–"),+ ("Memory pressure", s.memoryPressure.rawValue.capitalized),+ ("Temperature", s.thermalState.capitalized),+ ("Low Power Mode", s.lowPowerMode ? "On" : "Off"),+ ("Free disk", s.freeDiskBytes.map(PerfInsights.bytes) ?? "–"),+ ])+ }+ card("Tabs", tabRows(r))+ Text("Session \(r.session.id), launch \(r.session.launch), up \(Int(r.session.uptimeSeconds / 60)) min · recording costs \(String(format: "%.3f", r.selfCost.cpuPct)) % of a core")+ .font(.system(size: 11)).foregroundStyle(.secondary)+ .padding(.leading, 8).padding(.top, 12)+ } else if !recording.wrappedValue {+ SettingsFootnote("Recording is off: no samples, no timers, nothing written. Files already recorded stay until you clear them.")+ .padding(.top, 12)+ } else {+ ProgressView().controlSize(.small).frame(maxWidth: .infinity).padding(.top, 24)+ }+ }++ private func tabRows(_ r: PerfReport) -> [(String, String)] {+ var rows: [(String, String)] = []+ if let t = r.tabs.latest { rows.append(("Tabs", "\(t.tabs) · \(t.live) loaded · \(t.slept) asleep")) }+ for (title, metric) in [("Tab switch", PerfMetric.tabSwitch), ("New page", .pageCreate), ("Page load", .pageLoad), ("Waking a slept tab", .tabWake)] {+ guard let h = r.timings[metric.rawValue], h.count > 0 else { continue }+ rows.append((title, "\(PerfInsights.duration(h.percentile(0.5))) typical · \(PerfInsights.duration(h.percentile(0.95))) slow"))+ }+ if r.tabs.longTasks > 0 { rows.append(("Busy page (long tasks)", "\(r.tabs.longTasks) · \(PerfInsights.duration(r.tabs.longTaskMs))")) }+ return rows+ }++ @ViewBuilder private func card(_ title: String, _ rows: [(String, String)]) -> some View {+ if !rows.isEmpty {+ SettingsHeader(title).padding(.top, 20)+ SettingsCard {+ ForEach(Array(rows.enumerated()), id: \.offset) { i, row in+ if i > 0 { SettingsCardDivider() }+ SettingsCardRow {+ Text(row.0).font(.system(size: 13))+ } trailing: {+ Text(row.1).font(.system(size: 13).monospacedDigit()).foregroundStyle(.secondary)+ }+ }+ }+ }+ }++ // MARK: Events++ @ViewBuilder private var events: some View {+ let list = report.map(Self.timeline) ?? []+ if list.isEmpty {+ SettingsFootnote(report == nil ? "Recording is off." : "Nothing has happened this session: no stalls, crashed pages or failed loads.")+ } else {+ SettingsCard {+ ForEach(Array(list.prefix(100).enumerated()), id: \.offset) { i, e in+ if i > 0 { SettingsCardDivider() }+ SettingsCardRow {+ VStack(alignment: .leading, spacing: 2) {+ Text(e.title).font(.system(size: 13))+ if !e.detail.isEmpty {+ Text(e.detail).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(2)+ }+ }+ } trailing: {+ Text(e.time).font(.system(size: 11).monospacedDigit()).foregroundStyle(.secondary)+ }+ }+ }+ }+ }++ private struct Row { var at: Double; var time: String; var title: String; var detail: String }++ /// Stalls and events, newest first.+ private static func timeline(_ r: PerfReport) -> [Row] {+ let f = DateFormatter()+ f.dateFormat = "HH:mm:ss"+ func time(_ at: Double) -> String { f.string(from: r.session.startedAt.addingTimeInterval(at)) }+ var rows = r.mainThread.recent.map { s in+ Row(at: s.at, time: time(s.at),+ title: "\(s.freeze ? (s.kind == .stall ? "Stall" : "Freeze") : "Busy \(s.mode) loop") \(PerfInsights.duration(s.ms))",+ detail: ([s.site].compactMap { $0 } + (s.marks.isEmpty ? [] : ["after " + s.marks.joined(separator: " → ")])).joined(separator: " · "))+ }+ rows += r.events.filter { $0.kind != "freeze" && $0.kind != "hang" }.map { e in+ Row(at: e.at, time: time(e.at), title: e.kind == "renderer" ? "Page process \(e.detail)" : "Load failed (\(e.detail))",+ detail: e.site ?? "")+ }+ return rows.sorted { $0.at > $1.at }+ }++ // MARK: Export++ @ViewBuilder private func export(_ hideSites: Binding<Bool>) -> some View {+ SettingsCard {+ SettingsCardRow {+ Text("Hide site names").font(.system(size: 13))+ } trailing: {+ Toggle("Hide site names", isOn: hideSites).toggleStyle(.switch).labelsHidden()+ }+ }+ SettingsFootnote("Sites in the exported files become site-1, site-2… in every file, logs included. Without it they keep their host name (never the full address), as Cra's logs always have.")+ HStack(spacing: 8) {+ Button("Export Diagnostics…") { actions.exportDiagnostics() }+ Button(copied ? "Copied" : "Copy Summary") {+ guard let r = report else { return }+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(PerfSummary.text(r), forType: .string)+ copied = true+ }+ .disabled(report == nil)+ Spacer(minLength: 0)+ Button("Clear…") { confirmClear() }+ }+ .padding(.top, 16)+ SettingsFootnote("Copy Summary never names a site. The recording lives in \(AppPaths.file("Perf").path.replacingOccurrences(of: NSHomeDirectory(), with: "~")) and stays under 2 MB.")+ .padding(.top, 4)+ }++ private func confirmClear() {+ let alert = NSAlert()+ alert.messageText = "Clear the performance recording?"+ alert.informativeText = "This session's numbers, the last 24 hours and saved freezes are deleted."+ alert.addButton(withTitle: "Clear")+ alert.addButton(withTitle: "Cancel")+ guard alert.runModal() == .alertFirstButtonReturn else { return }+ PerfRecorder.clear()+ report = nil+ }+}++private extension PerfProcessKind {+ var label: String {+ switch self {+ case .browser: return "Cra"+ case .renderer: return "Pages"+ case .gpu: return "GPU"+ case .utility: return "Network, storage, audio"+ case .other: return "Other"+ }+ }+}diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftindex cafb1e6..dd9d879 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -75,6 +75,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {private(set) var visibleTabID: UUID?/// Every tab on screen, in pane order (one entry outside split view).private(set) var visibleTabIDs: [UUID] = []+ /// Tabs whose page tab sleeping closed and that haven't been shown since.+ private(set) var sleptTabs: Set<UUID> = []/// Split view: the view a tab's Alloy-hosted Chromium view should live in.var paneHost: ((UUID) -> NSView?)?/// The browser window this manager shows pages in (tabs it opens are selected there).@@ -113,8 +115,11 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {release(tabID)?.browser.close()}log(tabID, "opens a page for \(site(tab.url, tabID))")- let browser = CraBrowser(frame: container.bounds, url: tab.url, delegate: self, incognito: store.isIncognito(item: tabID),- profilePath: store.profilePath(item: tabID))+ if sleptTabs.remove(tabID) != nil { Perf.begin(.tabWake, tabID.uuidString) }+ let browser = Perf.time(.pageCreate) {+ CraBrowser(frame: container.bounds, url: tab.url, delegate: self, incognito: store.isIncognito(item: tabID),+ profilePath: store.profilePath(item: tabID))+ }return register(browser: browser, tabID: tabID)}@@ -201,6 +206,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {/// Show several tabs at once (split view); `focused` gets keyboard focus.func show(_ tabIDs: [UUID], focused: UUID?, focus: Bool) {+ let started = Perf.now()let newSet = Set(tabIDs)for previous in visibleTabIDs where !newSet.contains(previous) {leaveTab(previous)@@ -240,7 +246,13 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {visibleTabIDs = shownif let np = nowPlaying, np.onScreen != Set(shown) { np.onScreen = Set(shown) }visibleTabID = focused.flatMap { newSet.contains($0) ? $0 : nil } ?? shown.first- if wasVisible != Set(shown) { HitchMonitor.mark("page-shown") }+ if wasVisible != Set(shown) {+ HitchMonitor.mark("page-shown")+ if let rt = visibleRuntime {+ Perf.visibleSite(rt.browser.isIncognito ? nil : SiteNames.siteHost(of: rt.browser.currentURL))+ Perf.phase("firstPageShown")+ }+ }if focus, let f = visibleTabID, let rt = runtimes[f] { rt.browser.setFocused(true) }for id in shown where !wasVisible.contains(id) {scheduleSnapshot(id)@@ -251,6 +263,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {}syncDevToolsVisibility()delegate?.browserManagerPageWindowsChanged(focus: focus)+ if wasVisible != Set(shown) { Perf.time(.tabSwitch, ms: Perf.ms(since: started)) }}// MARK: Diagnostics@@ -336,6 +349,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {// creates a new browser, and late callbacks cannot mutate its replacement.guard let rt = release(tabID) else { return }log(tabID, "closes its page")+ Perf.cancel(.pageLoad, tabID.uuidString)+ Perf.cancel(.tabWake, tabID.uuidString)rt.browser.containerView.isHidden = trueclosingBrowsers[ObjectIdentifier(rt.browser)] = rt.browserrt.browser.close()@@ -370,6 +385,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {guard let self, let rt, self.stillSleepable(id, rt, url, navigationRevision, cutoff) else { return }let refusal = Self.sleepRefusal(result)guard refusal.isEmpty else { return self.keepAwake(rt, url, refusal) }+ self.sleptTabs.insert(id)+ Perf.count(.tabSlept)if !rt.browser.isIncognito {CraLog.note("tab sleep unloads \(CraLog.host(url)) (hidden \(Int(self.clock.now.timeIntervalSince(rt.hiddenAt ?? self.clock.now) / 60)) min)")}@@ -388,6 +405,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {/// Asked again after the back-off; the log names the site once per reason (never an incognito one).private func keepAwake(_ rt: TabRuntime, _ url: String, _ refusal: String) {rt.sleepProbeAfter = clock.now.addingTimeInterval(Self.refusalBackoff)+ Perf.count(.sleepRefusal, refusal)if rt.sleepRefusal != refusal, !rt.browser.isIncognito { CraLog.note("tab sleep keeps \(CraLog.host(url)) awake: \(refusal)") }rt.sleepRefusal = refusal}@@ -442,6 +460,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {/// space switched profiles, closes and loads its URL again there when shown.func pruneMissingTabs() {for id in runtimes.keys where store.item(id)?.isTab != true { unload(id) }+ sleptTabs = sleptTabs.filter { store.item($0)?.isTab == true }for (id, rt) in runtimes where store.item(id)?.isTab == true && !inRightProfile(rt) {release(id)?.browser.close()}@@ -719,6 +738,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {if !browser.isAudible { nowPlaying?.remove(id) }// Our own error page is a data: URL; keep the real address in the model.if url.hasPrefix("data:text/html;base64,") { return }+ // A restored page has no address yet when it is shown.+ if id == visibleTabID { Perf.visibleSite(browser.isIncognito ? nil : SiteNames.siteHost(of: url)) }store.updateTab(id, url: url)if !browser.isIncognito { LiveFolderManager.shared.pageChanged(tab: id, to: url) }delegate?.browserManagerDidUpdate(id)@@ -727,6 +748,10 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {func browser(_ browser: CraBrowser, didChangeLoading loading: Bool, canGoBack: Bool, canGoForward: Bool) {guard let id = tabID(of: browser) else { return }if loading { runtimes[id]?.navigationRevision &+= 1 }+ if loading { Perf.begin(.pageLoad, id.uuidString) } else {+ Perf.end(.pageLoad, id.uuidString)+ Perf.end(.tabWake, id.uuidString)+ }if !loading { runtimes[id]?.progress = 0 }if !loading { scheduleSnapshot(id) }delegate?.browserManagerDidUpdate(id)diff --git a/Sources/Cra/Services/CraLog.swift b/Sources/Cra/Services/CraLog.swiftindex 34ff41c..d692445 100644--- a/Sources/Cra/Services/CraLog.swift+++ b/Sources/Cra/Services/CraLog.swift@@ -77,6 +77,23 @@ enum CraLog {/// Only the host: logs get shared in bug reports.static func host(_ url: String) -> String {- URL(string: url).flatMap { $0.host ?? $0.scheme.map { "\($0):" } } ?? "(no page)"+ if let site = SiteNames.siteHost(of: url) { remember(site) }+ return URL(string: url).flatMap { $0.host ?? $0.scheme.map { "\($0):" } } ?? "(no page)"+ }++ private static let sitesLock = NSLock()+ nonisolated(unsafe) private static var sites: Set<String> = []++ /// Every site this session's log named: what "Hide site names" replaces in the export.+ static var sitesSeen: Set<String> {+ sitesLock.lock()+ defer { sitesLock.unlock() }+ return sites+ }++ private static func remember(_ site: String) {+ sitesLock.lock()+ if sites.count < 10_000 { sites.insert(site) }+ sitesLock.unlock()}}diff --git a/Sources/Cra/Services/Diagnostics.swift b/Sources/Cra/Services/Diagnostics.swiftindex 98bc373..4ffe8e2 100644--- a/Sources/Cra/Services/Diagnostics.swift+++ b/Sources/Cra/Services/Diagnostics.swift@@ -4,8 +4,10 @@ import UniformTypeIdentifiers/// Help ▸ Export Diagnostics…: a zip a user can attach to an issue or send by mail. Holds/// Cra's and Chromium's logs (this launch and the last), the on-screen pages' state, the GPU-/// report and recent crash reports. Addresses are cut to their host and the home folder to-/// `~`; no history, cookies, passwords or page content leave the Mac.+/// report, recent crash reports and the performance recorder's perf.json (GitHub #91).+/// Addresses are cut to their host and the home folder to `~`; with Settings ▸ Performance ▸+/// "Hide site names" the hosts become site-1, site-2… in every file. No history, cookies,+/// passwords or page content leave the Mac.@MainActorenum Diagnostics {/// Asks where to save, unless `destination` is given (cra://debug?exportDiagnostics=<path>).@@ -13,8 +15,10 @@ enum Diagnostics {CraLog.note("diagnostics export started")collectPages(windows: windows, store: store) { pages inCraCEFRuntime.sendBrowserDevToolsMethod("SystemInfo.getInfo", params: "{}") { gpu, error in- DispatchQueue.main.async {- save(pages: pages, gpu: gpu ?? "{\"error\": \"\(error ?? "no answer")\"}", store: store, to: destination)+ // The profile's size is measured off the main thread.+ PerfRecorder.exportFiles { perf, perfSites in+ save(pages: pages, gpu: gpu ?? "{\"error\": \"\(error ?? "no answer")\"}", perf: perf, perfSites: perfSites,+ store: store, to: destination)}}}@@ -49,7 +53,8 @@ enum Diagnostics {}}- private static func save(pages: String, gpu: String, store: SidebarStore, to chosen: URL?) {+ private static func save(pages: String, gpu: String, perf: [(name: String, text: String)], perfSites: Set<String>,+ store: SidebarStore, to chosen: URL?) {let stamp: String = {let f = DateFormatter()f.locale = Locale(identifier: "en_US_POSIX")@@ -64,14 +69,19 @@ enum Diagnostics {let folder = staging.appendingPathComponent(name, isDirectory: true)try? fm.createDirectory(at: folder, withIntermediateDirectories: true)let home = NSHomeDirectory()+ var sites = store.settings.perfHidesSiteNames ? SiteNames(hosts: knownSites(store).union(perfSites)) : nilfunc write(_ text: String, _ file: String) {- try? Data(DiagnosticsRedaction.redact(text, home: home).utf8).write(to: folder.appendingPathComponent(file))+ var out = DiagnosticsRedaction.redact(text, home: home)+ if sites != nil { out = sites!.apply(out) }+ try? Data(out.utf8).write(to: folder.appendingPathComponent(file))}CraLog.flush()write(summary(store: store), "summary.txt")write(pages, "pages.txt")write(gpu, "gpu.json")+ if perf.contains(where: { $0.name.hasPrefix("perf/") }) { try? fm.createDirectory(at: folder.appendingPathComponent("perf"), withIntermediateDirectories: true) }+ for (name, text) in perf { write(text, name) }for (url, file) in [(CraLog.file, "cra.log"), (CraLog.previousFile, "cra.previous.log"),(AppPaths.log, "chromium.log"), (CraLog.chromiumPreviousFile, "chromium.previous.log")] {if let data = try? Data(contentsOf: url) { write(String(decoding: data, as: UTF8.self), file) }@@ -109,10 +119,20 @@ enum Diagnostics {if chosen == nil { NSWorkspace.shared.activateFileViewerSelecting([destination]) }}+ /// Every site the zip can name: the log's, the sidebar's, the history's and the archive's+ /// (Chromium's log names the sites of the same tabs).+ private static func knownSites(_ store: SidebarStore) -> Set<String> {+ var hosts = CraLog.sitesSeen+ let urls = store.allTabs().compactMap { $0.tab?.url } + store.history.values.map(\.url)+ + store.archive.compactMap { $0.item.tab?.url }+ for u in urls { if let h = SiteNames.siteHost(of: u) { hosts.insert(h) } }+ return hosts+ }+private static func askWhere(_ fileName: String) -> URL? {let panel = NSSavePanel()panel.title = "Export Diagnostics"- panel.message = "Cra's logs, the state of the pages on screen and recent crash reports. Site names only: no addresses, history, cookies or passwords."+ panel.message = "Cra's logs, its performance record, the state of the pages on screen and recent crash reports. Site names only: no addresses, history, cookies or passwords."panel.nameFieldStringValue = fileNamepanel.allowedContentTypes = [.zip]panel.directoryURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).firstdiff --git a/Sources/Cra/Services/HitchMonitor.swift b/Sources/Cra/Services/HitchMonitor.swiftindex 7e97b20..4c16f9a 100644--- a/Sources/Cra/Services/HitchMonitor.swift+++ b/Sources/Cra/Services/HitchMonitor.swift@@ -39,7 +39,11 @@ enum HitchMonitor {thread.start()}- static func mark(_ label: String) { write("mark \(label)") }+ /// Also a breadcrumb for the performance recorder: what Cra did before a stall.+ static func mark(_ label: String) {+ Perf.mark(label)+ write("mark \(label)")+ }private static func write(_ line: String) {lock.lock()diff --git a/Sources/Cra/Services/PageScript.swift b/Sources/Cra/Services/PageScript.swiftindex 56d0287..e19e07c 100644--- a/Sources/Cra/Services/PageScript.swift+++ b/Sources/Cra/Services/PageScript.swift@@ -12,6 +12,10 @@ import Foundation/// player can skip tracks. `setActionHandler` can't be called from outside and its handlers/// live in the page's world, so a small wrapper there keeps them in a closure and answers an/// event whose name is random per launch: nothing in the page's world names Cra.+/// - `lt`: the top frame's long tasks (50 ms or more) for the performance recorder (GitHub #91):+/// a count, the total and the last 100 durations, which Cra reads and resets for the visible+/// tab every few seconds. No attribution, no addresses; the observer only runs when a long+/// task happens, so it never polls or wakes a background tab.enum PageScript {static let world = "cra"private static let channel = "c" + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()@@ -47,6 +51,12 @@ enum PageScript {addEventListener('\(channel)r', e => { cra.handlers = String(e.detail || '').split(',').filter(Boolean); });cra.send = action => dispatchEvent(new CustomEvent('\(channel)', { detail: action }));cra.query = () => (cra.send('?'), cra.handlers);+ if (window.top === window) try {+ const lt = cra.lt = { n: 0, t: 0, d: [] };+ new PerformanceObserver(list => {+ for (const e of list.getEntries()) { lt.n++; lt.t += e.duration; if (lt.d.length < 100) lt.d.push(Math.round(e.duration)); }+ }).observe({ type: 'longtask' });+ } catch {}})();"""}diff --git a/Sources/Cra/Services/Persistence.swift b/Sources/Cra/Services/Persistence.swiftindex e1eeb47..1eeac75 100644--- a/Sources/Cra/Services/Persistence.swift+++ b/Sources/Cra/Services/Persistence.swift@@ -69,7 +69,7 @@ final class JSONStore<T: Codable> {func load(or fallback: () -> T) -> T {guard let data = try? Data(contentsOf: url) else { return fallback() }- do { return try decoder.decode(T.self, from: data) } catch {+ do { return try Perf.time(.jsonLoad) { try decoder.decode(T.self, from: data) } } catch {// Corrupt file: keep it aside for forensics and start fresh.CraLog.fault("\(url.lastPathComponent) unreadable, set aside as .corrupt: \(error)")try? FileManager.default.moveItem(at: url, to: url.appendingPathExtension("corrupt"))@@ -92,6 +92,8 @@ final class JSONStore<T: Codable> {}private func write(_ value: T) {+ let started = Perf.now()+ defer { Perf.time(.jsonSave, ms: Perf.ms(since: started)) }let data: Datado { data = try encoder.encode(value) } catch {CraLog.fault("\(url.lastPathComponent) not saved, encoding failed: \(error)")diff --git a/Sources/Cra/UI/Settings/SettingsWindowController.swift b/Sources/Cra/UI/Settings/SettingsWindowController.swiftindex b0aac3d..8dd0160 100644--- a/Sources/Cra/UI/Settings/SettingsWindowController.swift+++ b/Sources/Cra/UI/Settings/SettingsWindowController.swift@@ -5,13 +5,14 @@ import SwiftUIstruct SettingsActions {var importData: () -> Void = {}var openURL: (String) -> Void = { _ in }+ var exportDiagnostics: () -> Void = {}}/// The panes in Dia's Settings sidebar (Dia 1.54.2: Account, Tabs, Privacy, Profiles, Skills,/// Apps, Shortcuts, Advanced). Cra has no account or AI skills/apps; General/// (system integration) and Extensions take rows instead.enum SettingsPane: String, CaseIterable, Identifiable {- case general, tabs, privacy, profiles, extensions, shortcuts, advanced+ case general, tabs, privacy, profiles, extensions, shortcuts, performance, advancedvar id: String { rawValue }var title: String {@@ -22,6 +23,7 @@ enum SettingsPane: String, CaseIterable, Identifiable {case .profiles: return "Profiles"case .extensions: return "Extensions"case .shortcuts: return "Shortcuts"+ case .performance: return "Performance"case .advanced: return "Advanced"}}@@ -35,6 +37,7 @@ enum SettingsPane: String, CaseIterable, Identifiable {case .profiles: return "person"case .extensions: return "puzzlepiece.extension"case .shortcuts: return "keyboard"+ case .performance: return "gauge.with.dots.needle.67percent"case .advanced: return "gearshape.2"}}@@ -47,6 +50,8 @@ final class SettingsNavigation {private(set) var pane: SettingsPane = .generalprivate(set) var back: [SettingsPane] = []private(set) var forward: [SettingsPane] = []+ /// The window is on screen: panes that refresh (Performance) stop while it is closed or covered.+ var isOpen = falsefunc show(_ p: SettingsPane) {guard p != pane else { return }@@ -112,6 +117,16 @@ final class SettingsWindowController: NSWindowController, NSToolbarDelegate {// Size last: the toolbar and full-size content change how the frame is derived.window.setFrame(NSRect(origin: .zero, size: SettingsMetrics.windowSize), display: false)window.center()+ // On screen: shown and not entirely covered (the window needn't be key).+ for name in [NSWindow.didChangeOcclusionStateNotification, NSWindow.willCloseNotification] {+ NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [nav] note in+ MainActor.assumeIsolated {+ guard let w = note.object as? NSWindow else { return }+ let open = note.name != NSWindow.willCloseNotification && w.occlusionState.contains(.visible)+ if nav.isOpen != open { nav.isOpen = open }+ }+ }+ }}required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }@@ -225,6 +240,7 @@ struct SettingsContent: View {case .profiles: ProfilesPane()case .extensions: ExtensionsPane(actions: actions)case .shortcuts: ShortcutsPane()+ case .performance: PerformancePane(nav: nav, actions: actions)case .advanced: AdvancedPane(actions: actions)}}diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex 6d5249d..b6e54a5 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -69,6 +69,7 @@ static NSHashTable<CraBrowser*>* g_allBrowsers = nil;/// Closed tabs whose page stays alive until its downloads end (see -[CraBrowser close]).static NSMutableSet<CraBrowser*>* g_parkedBrowsers = nil;static void (^g_strayPageHandler)(NSString*) = nil;+static void (^g_processEventHandler)(NSString*, NSString*, NSString*) = nil;static NSString* NSStringFromCef(const CefString& s) {std::string utf8 = s.ToString();@@ -1178,6 +1179,7 @@ public:LOG(WARNING) << "Cra: loading " << LogHost(browser, failedUrl) << " failed: " << errorText.ToString() << " ("<< (int)errorCode << ")";if ((int)errorCode == -3 /* ERR_ABORTED */) return;+ ReportProcessEvent(browser, @"loadError", [NSString stringWithFormat:@"%d", (int)errorCode], failedUrl);// Chrome-style pages get Chrome's own error page: Reload retries the site and it// reloads by itself when the network returns. Ours, a data: URL loaded on top,// made Reload reload the error and added a history entry.@@ -1329,14 +1331,42 @@ public:const char* what = status >= 0 && status < TS_NUM_VALUES ? kStatus[status] : "unknown";LOG(ERROR) << "Cra: renderer for " << LogHost(browser) << " ended: " << what << " (code " << error_code<< ", " << error_string.ToString() << ")";+ ReportProcessEvent(browser, @"terminated", @(what));}bool OnRenderProcessUnresponsive(CefRefPtr<CefBrowser> browser,CefRefPtr<CefUnresponsiveProcessCallback> callback) override {LOG(ERROR) << "Cra: renderer for " << LogHost(browser) << " is unresponsive";+ ReportProcessEvent(browser, @"unresponsive", @"");return false; // Chrome's "Page Unresponsive" dialog}+ void OnRenderProcessResponsive(CefRefPtr<CefBrowser> browser) override {+ ReportProcessEvent(browser, @"responsive", @"");+ }++ /// To the performance recorder: the host only, and none for incognito or Cra's own pages.+ void ReportProcessEvent(CefRefPtr<CefBrowser> browser, NSString* kind, NSString* detail, const CefString& url = CefString()) {+ void (^handler)(NSString*, NSString*, NSString*) = g_processEventHandler;+ if (!handler) return;+ CraBrowser* o = owner_;+ NSString* site = nil;+ if (o && !o.isIncognito) {+ CefString u = url;+ if (u.empty()) {+ CefRefPtr<CefFrame> frame = browser->GetMainFrame();+ if (frame) u = frame->GetURL();+ }+ CefURLParts parts;+ if (!u.empty() && CefParseURL(u, parts)) {+ std::string scheme = CefString(&parts.scheme).ToString();+ std::string host = CefString(&parts.host).ToString();+ if ((scheme == "http" || scheme == "https") && !host.empty()) site = @(host.c_str());+ }+ }+ handler(kind, detail, site);+ }+/// The site for chromium.log, which Help ▸ Export Diagnostics sends: never an incognito one/// (nor one whose tab is already gone, when that can't be told).std::string LogHost(CefRefPtr<CefBrowser> browser, const CefString& url = CefString()) {@@ -2357,6 +2387,7 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {+ (BOOL)anotherInstanceWasNotified { return g_alreadyRunning; }+ (void)setRelaunchHandler:(void (^)(NSArray<NSString*>*))handler { g_relaunchHandler = [handler copy]; }+ (void)setStrayPageHandler:(void (^)(NSString*))handler { g_strayPageHandler = [handler copy]; }++ (void)setProcessEventHandler:(void (^)(NSString*, NSString*, NSString*))handler { g_processEventHandler = [handler copy]; }+ (BOOL)isExtensionWindow:(NSWindow*)window { return window && [g_extensionWindows containsObject:window]; }+ (BOOL)isPageWindow:(NSWindow*)window {for (CraBrowser* b in g_allBrowsers) if (window && b.hostWindow == window) return YES;diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hindex 05e9ac9..744161a 100644--- a/Sources/CraCEF/include/CraCEF.h+++ b/Sources/CraCEF/include/CraCEF.h@@ -264,6 +264,11 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {/// the URL to open as a Cra tab; Chrome's own window for it is closed./// Popup-type windows (windows.create({type: "popup"})) stay Chrome's windows.+ (void)setStrayPageHandler:(void (^)(NSString *url))handler;+/// Renderer trouble and failed loads, for Cra's performance recorder (GitHub #91): `kind` is+/// terminated, unresponsive, responsive or loadError; `detail` how it ended or the net error+/// code; `site` the host (nil for incognito, Cra's own pages or a closed tab). Never a URL.+/// On the main thread. Chrome's "Page Unresponsive" dialog still shows.++ (void)setProcessEventHandler:(void (^)(NSString *kind, NSString *detail, NSString *_Nullable site))handler;/// YES for a popup window an extension opened (kept by the stray page handling).+ (BOOL)isExtensionWindow:(NSWindow *)window;/// YES for the Chrome-style window hosting one of Cra's own browsers.diff --git a/Tests/PerfTests.swift b/Tests/PerfTests.swiftnew file mode 100644index 0000000..9c9b2ac--- /dev/null+++ b/Tests/PerfTests.swift@@ -0,0 +1,253 @@+import Foundation++/// GitHub #91: the performance recorder on a real main run loop, with its files in a temporary+/// folder. Stalls are made the way Cra makes them (work blocking the main queue), and the hang+/// file's stack comes from the real /usr/bin/sample.+@main+enum PerfTests {+ private static var checks = 0+ private static let root = FileManager.default.temporaryDirectory.appendingPathComponent("cra-perf-tests-\(getpid())")++ @MainActor+ static func main() {+ defer { try? FileManager.default.removeItem(at: root) }+ stallsAreRecordedWithTheirBreadcrumbs()+ aHangIsWrittenWhileItLastsWithItsStack()+ aSessionThatNeverQuitIsAbnormalNextLaunch()+ aSecondCraWritesNothing()+ recordingOffStopsSamplingAndWriting()+ theFacadeWaitsForTheRecorderAndTimesWork()+ aSlowLaunchIsAStallButNotAFreeze()+ print("Perf recorder: \(checks) checks passed")+ }++ static func config(_ name: String, hangMs: Double = 2000, stacks: Int = 0) -> PerfRecorder.Config {+ var c = PerfRecorder.Config(folder: root.appendingPathComponent(name))+ c.sampleInterval = 0.2+ c.blackBoxEvery = 2+ c.historyEvery = 3+ c.policy.hangMs = hangMs+ c.stacks = stacks+ return c+ }++ @MainActor static func start(_ c: PerfRecorder.Config, owner: Bool = true, recording: Bool = true) {+ PerfRecorder.configure(owner: owner, recording: recording, config: c, craVersion: "test", chromiumVersion: "0", onboarding: false)+ }++ /// Runs the main run loop, as Cra's does, for `seconds`.+ static func spin(_ seconds: Double) { RunLoop.main.run(until: Date().addingTimeInterval(seconds)) }++ @MainActor static func report() -> PerfReport? {+ var out: PerfReport?+ PerfRecorder.shared?.snapshot { out = $0 }+ for _ in 0..<50 where out == nil { spin(0.05) }+ return out+ }++ /// Busy on the main thread until `done` (checked every 50 ms) or `limit` seconds.+ @inline(never) static func busyMainThreadForPerfTest(atLeast seconds: Double, limit: Double, until done: () -> Bool) {+ let start = Date()+ var x = 0.0, next = start+ while Date().timeIntervalSince(start) < limit {+ x += sin(x) + 1+ if Date() >= next {+ if Date().timeIntervalSince(start) >= seconds, done() { break }+ next = Date().addingTimeInterval(0.05)+ }+ }+ if x < 0 { print(x) }+ }++ @MainActor static func stallsAreRecordedWithTheirBreadcrumbs() {+ let c = config("stall")+ start(c)+ spin(0.3)+ DispatchQueue.main.async {+ Perf.mark("cra://debug?stall=500")+ usleep(500_000)+ }+ spin(0.5)+ DispatchQueue.main.async { usleep(300_000) }+ spin(1.2)+ guard let r = report() else { return expect(false, "a report while recording") }+ expect(r.mainThread.stalls == 2, "both stalls counted (\(r.mainThread.stalls))")+ expect(r.mainThread.recent.allSatisfy { $0.mode != "launch" }, "a quick start is no stall")+ let first = r.mainThread.recent.first+ expect(first.map { $0.ms >= 500 && $0.ms < 900 } == true, "the injected 500 ms stall measured as such (\(first?.ms ?? 0))")+ expect(first?.marks == ["cra://debug"], "with its breadcrumb, cut before the query (\(first?.marks ?? []))")+ expect(first?.mode == "default" && first?.freeze == true, "in the default mode: a freeze")+ expect(r.mainThread.passes.count > 2 && r.mainThread.passes.maxMs >= 500, "every pass in the histogram")+ expect(r.processes.contains { $0.kind == .browser && $0.count == 1 && $0.footprintBytes > 0 }, "libproc read this process")+ expect(r.system?.memoryPressure != nil && r.system?.thermalState.isEmpty == false, "the Mac sampled")+ expect(r.selfCost.cpuPct < 5 && r.selfCost.observerCallbacks > 0, "self-cost reported (\(r.selfCost.cpuPct) %)")+ expect(r.session.launch == 1 && r.session.previous == nil && r.session.writesFiles, "a first launch, writing")+ let files = PerfFiles(folder: c.folder)+ expect(FileManager.default.fileExists(atPath: files.marker.path), "session.open while running")+ expect(files.read(PerfReport.self, from: files.blackBox) != nil, "the black box written on its schedule")++ var exported: [(name: String, text: String)] = []+ var sites: Set<String> = ["unset"]+ PerfRecorder.exportFiles { exported = $0; sites = $1 }+ for _ in 0..<100 where exported.isEmpty { spin(0.05) }+ expect(exported.first?.name == "perf.json" && exported.first!.text.contains("\"stalls\" : 2"), "perf.json in the export")+ expect(sites.isEmpty, "no sites: no page was on screen")++ PerfRecorder.quit()+ expect(!FileManager.default.fileExists(atPath: files.marker.path), "a clean quit removes the marker")+ let history = files.read(PerfHistory.self, from: files.history)+ expect(history?.lastSession?.abnormal == false && history?.launches == 1, "and records the session as quit")+ expect(!Perf.isRecording, "the facade lets go")++ start(c)+ expect(PerfRecorder.shared.map { _ in report()?.session.previous?.abnormal == false } == true, "the next launch: previous quit normally")+ expect(report()?.session.launch == 2, "launch 2")+ expect(FileManager.default.fileExists(atPath: files.previousBlackBox.path), "the last black box kept as the previous one")+ PerfRecorder.quit()+ }++ @MainActor static func aHangIsWrittenWhileItLastsWithItsStack() {+ let c = config("hang", hangMs: 600, stacks: 1)+ start(c)+ spin(0.3)+ let files = PerfFiles(folder: c.folder)+ var seenDuring = false+ // The watchdog writes from its own thread while the main thread is still busy. The block+ // lasts until the stack is in the file, however long `sample` takes to attach (a CI runner+ // is slower than a desk Mac).+ DispatchQueue.main.async {+ busyMainThreadForPerfTest(atLeast: 1, limit: 15) {+ files.hangFiles().first.flatMap { files.read(PerfHang.self, from: $0) }.map { $0.stackNote != "sampling" } ?? false+ }+ seenDuring = !files.hangFiles().isEmpty+ }+ // `sample` takes about 2 s here and longer on a CI runner: wait for the stack, not a time.+ var hang: PerfHang?+ for _ in 0..<100 {+ spin(0.2)+ hang = files.hangFiles().first.flatMap { files.read(PerfHang.self, from: $0) }+ if hang?.stackNote != "sampling", hang?.endedMs != nil { break }+ }+ expect(seenDuring, "the hang file exists before the main thread comes back")+ expect(hang?.stalledMs ?? 0 >= 600, "it says how long the main thread had been blocked")+ expect(hang.map { $0.endedMs ?? 0 >= 1000 } == true, "and how long it was in the end (\(hang?.endedMs ?? -1))")+ expect(hang?.stack.contains { $0.contains("busyMainThreadForPerfTest") } == true,+ "with the main thread's stack from sample (\(hang?.stackNote ?? "")): \(hang?.stack.prefix(6) ?? [])")+ expect(hang?.stack.contains { $0.contains("/Users") || $0.contains("0x") } == false, "no paths or addresses")+ let r = report()+ expect(r?.mainThread.hangs == 1 && r?.events.first?.kind == "hang", "counted as a hang")+ PerfRecorder.quit()+ }++ @MainActor static func aSessionThatNeverQuitIsAbnormalNextLaunch() {+ let c = config("abnormal")+ start(c)+ spin(0.5)+ let files = PerfFiles(folder: c.folder)+ let id = PerfRecorder.shared?.sessionID+ // What kill -9 leaves: the marker, the black box, a hang file. Nothing gets to quit().+ let marker = files.read(PerfSessionMarker.self, from: files.marker)+ expect(marker?.id == id, "the marker names the session")+ PerfRecorder.setRecording(false)+ files.write(marker!, to: files.marker)+ files.write(PerfHang(session: id!, number: 1, at: 1, stalledMs: 3000, mode: "default", marks: [], site: nil), to: files.hang(session: id!, number: 1))+ files.write(PerfHang(session: "older000", number: 1, at: 1, stalledMs: 3000, mode: "default", marks: [], site: nil), to: files.hang(session: "older000", number: 1))++ start(c)+ let previous = report()?.session.previous+ expect(previous?.abnormal == true && previous?.id == id, "the next launch reports it as ended without quitting")+ expect(report()?.insights.first?.id == "previous-abnormal", "and says so first")+ expect(files.hangFiles().map(\.lastPathComponent) == ["hang-\(id!)-1.json"], "its hang file stays, older ones go")+ PerfRecorder.quit()+ }++ @MainActor static func aSecondCraWritesNothing() {+ let c = config("second")+ start(c, owner: false)+ spin(0.8)+ expect(PerfRecorder.shared?.writesFiles == false, "a Cra that doesn't own the data folder records in memory only")+ expect(!FileManager.default.fileExists(atPath: c.folder.path), "and makes no folder, no marker, no files")+ PerfRecorder.quit()+ expect(!FileManager.default.fileExists(atPath: c.folder.path), "not even when it quits")+ }++ @MainActor static func recordingOffStopsSamplingAndWriting() {+ let c = config("off")+ start(c, recording: false)+ spin(0.5)+ expect(PerfRecorder.shared == nil && !Perf.isRecording, "off at launch: no recorder")+ expect(!FileManager.default.fileExists(atPath: c.folder.path), "and nothing written")++ PerfRecorder.setRecording(true)+ spin(0.6)+ let files = PerfFiles(folder: c.folder)+ expect(FileManager.default.fileExists(atPath: files.marker.path), "turned on: a session starts")+ PerfRecorder.setRecording(false)+ expect(!FileManager.default.fileExists(atPath: files.marker.path), "turned off: its marker goes")+ let before = snapshot(c.folder)+ spin(1)+ expect(snapshot(c.folder) == before, "and nothing is written after (\(before.count) files)")+ DispatchQueue.main.async { usleep(300_000) }+ spin(0.5)+ expect(PerfRecorder.shared == nil, "stalls with recording off reach nobody")++ PerfRecorder.clear()+ expect(PerfFiles(folder: c.folder).hangFiles().isEmpty && !FileManager.default.fileExists(atPath: files.history.path),+ "Clear removes the files while off")+ }++ @MainActor static func theFacadeWaitsForTheRecorderAndTimesWork() {+ let c = config("facade")+ start(c)+ Perf.time(.jsonSave, ms: 12)+ let n = Perf.time(.jsonLoad) { 41 + 1 }+ Perf.begin(.pageLoad, "tab")+ usleep(20_000)+ Perf.end(.pageLoad, "tab")+ Perf.begin(.tabWake, "gone")+ Perf.cancel(.tabWake, "gone")+ Perf.end(.tabWake, "gone")+ Perf.count(.loadError, "-105", site: "example.com")+ Perf.phase("test")+ let r = report()+ expect(n == 42, "a timed closure returns its value")+ expect(r?.timings["jsonSave"]?.count == 1 && r?.timings["jsonLoad"]?.count == 1, "durations recorded")+ expect(r.map { ($0.timings["pageLoad"]?.maxMs ?? 0) >= 20 } == true, "begin and end make one duration")+ expect(r?.timings["tabWake"] == nil, "a cancelled begin makes none")+ expect(r?.counters["loadError"] == ["-105": 1] && r?.events.last?.site == "example.com", "a failed load counted, with its site")+ expect(r?.sites == ["example.com"], "the report lists the sites it names, for Hide site names")+ expect(r?.startup["test"] != nil, "start-up phases")+ PerfRecorder.quit()+ }++ /// AppKit runs applicationDidFinishLaunching before the run loop's first pass: the recorder+ /// counts from its own start until the loop first sleeps.+ @MainActor static func aSlowLaunchIsAStallButNotAFreeze() {+ start(config("launch"))+ usleep(400_000)+ spin(0.5)+ let r = report()+ expect(r?.mainThread.recent.first?.mode == "launch" && r?.mainThread.recent.first?.freeze == false,+ "a slow start-up is a stall in the launch mode (\(r?.mainThread.recent.first?.mode ?? "none"))")+ expect(r?.mainThread.stalls == 0 && r?.mainThread.outsideFreezes == 1+ && r?.insights.contains { $0.id == "freezes" || $0.id == "stalls" } == false,+ "not a freeze, no freeze finding (\(r?.mainThread.stalls ?? -1), \(r?.mainThread.outsideFreezes ?? -1), \(r?.insights.map(\.id) ?? []))")+ PerfRecorder.quit()+ }++ static func snapshot(_ folder: URL) -> [String: Date] {+ var out: [String: Date] = [:]+ for f in (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.contentModificationDateKey])) ?? [] {+ out[f.lastPathComponent] = try? f.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate+ }+ return out+ }++ private static func expect(_ condition: @autoclosure () -> Bool, _ message: String) {+ guard condition() else {+ FileHandle.standardError.write(Data("FAIL: \(message)\n".utf8))+ exit(1)+ }+ checks += 1+ }+}diff --git a/Tests/test-browser-manager.sh b/Tests/test-browser-manager.shindex de0fa14..7a2a3d4 100755--- a/Tests/test-browser-manager.sh+++ b/Tests/test-browser-manager.sh@@ -10,7 +10,8 @@ xcrun swiftc -swift-version 5 -emit-module -emit-library -module-name CraCEF \-emit-module-path "$TEST_DIR/CraCEF.swiftmodule"xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} -I "$TEST_DIR" -L "$TEST_DIR" -lCraCEF \-Xlinker -rpath -Xlinker "$TEST_DIR" \- "$MANAGER_SOURCE" Sources/Cra/Services/NowPlaying.swift Sources/Cra/Services/PageScript.swift Sources/Cra/Services/Scheduler.swift Sources/Cra/Services/DevToolsToggle.swift Sources/Cra/Services/CraLog.swift Sources/Cra/Services/PageProbe.swift Sources/Cra/Services/Persistence.swift Tests/Support/ManualScheduler.swift Tests/BrowserManagerSupport/AppServices.swift \+ "$MANAGER_SOURCE" Sources/Cra/Services/NowPlaying.swift Sources/Cra/Services/PageScript.swift Sources/Cra/Services/Scheduler.swift Sources/Cra/Services/DevToolsToggle.swift Sources/Cra/Services/CraLog.swift Sources/Cra/Services/PageProbe.swift Sources/Cra/Services/Persistence.swift \+ Sources/Cra/Perf/Perf.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Tests/Support/ManualScheduler.swift Tests/BrowserManagerSupport/AppServices.swift \Tests/BrowserManagerLifecycleTests.swift -o "$TEST_DIR/lifecycle-tests""$TEST_DIR/lifecycle-tests"[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/lifecycle-tests" "$CRA_TEST_KEEP/"diff --git a/docs/development.md b/docs/development.mdindex 12c59f4..e534415 100644--- a/docs/development.md+++ b/docs/development.md@@ -85,6 +85,9 @@ app it builds.`ManualScheduler`, against the made-up Arc and Chromium profiles in `Tests/Fixtures`.- `scripts/test-policies.sh`: the decisions pulled out of the window controllers(`ToolbarComposition`, `ExtensionLaunch`, `DevToolsToggle`, `FeatureFlags`).+- `scripts/test-perf.sh`: the performance recorder on a real main run loop: injected stalls,+ hang files with a `sample` stack, the session marker, ownership, the recording switch+ ([performance.md](performance.md)).- `scripts/lint.py`: Cra's own rules (testing.md), checked by `scripts/test.sh`.- `Tests/smoke-launch.sh [app]`: starts the app on a throwaway data folder with no pages,with a page opened, then with it restored, and quits it like ⌘Q after a settings write.@@ -97,7 +100,8 @@ behave. Check those by hand, and say how in the PR.Scenario hooks for a command file (`cra://debug?…`): `checkStore=1` logs a fault per brokensidebar link, `pageJS=<js>` runs script in the focused page, `installExtension=<folder>` and`removeExtension=<id>`, `extensionAction=<id>`, `fullscreen=1|0`, `windowSize=1280x800`,-`snapshot=<ViewClass[,n]>&out=<png>`, `sleepTabs=<seconds>`, `relaunch=1` and `quit=1`.+`snapshot=<ViewClass[,n]>&out=<png>`, `sleepTabs=<seconds>`, `stall=<ms>` (blocks the main+thread), `perfReport=<path>` (the recorder's perf.json now), `relaunch=1` and `quit=1`.## Running a test instancediff --git a/docs/performance.md b/docs/performance.mdnew file mode 100644index 0000000..9ac5419--- /dev/null+++ b/docs/performance.md@@ -0,0 +1,136 @@+# Performance recorder++Cra records its own performance on the Mac it runs on (GitHub #91): main-thread stalls with+what Cra did just before, CPU and memory per process, tab timings, and how the last session+ended. Settings ▸ Performance shows it; Help ▸ Export Diagnostics adds `perf.json` and the+hang files to the zip. It is on by default in early releases, off with one switch, and nothing+leaves the Mac unless the user exports it.++## Layers++| Where | What | Imports |+|---|---|---|+| `Packages/CraCore/Sources/CraCore/Perf/` | metrics, histograms, rings, stall rules, process kinds, history, session rules, insights, the summary text, site names, the report schema | Foundation |+| `Sources/Cra/Perf/Perf.swift` | the facade the rest of the app calls: `time`, `count`, `mark`, `phase`, `begin`/`end` | Foundation |+| `Sources/Cra/Perf/` (the rest) | run-loop observer and watchdog, libproc and system samplers, files, the recorder | Foundation, Darwin |+| `Sources/Cra/Perf/PerfCEF.swift` | Chromium's process events, the visible page's long tasks, tab counts, the Settings switch | AppKit, CraCEF |+| `Sources/Cra/Perf/PerformancePane.swift` | Settings ▸ Performance | SwiftUI |++`scripts/lint.py` holds the line: `perf-no-network` rejects networking in both Perf folders,+and `perf-boundary` allows Perf calls only in the files listed under "Removing it" and+`CraCEF` only in `PerfCEF.swift`.++Data flows one way. The main thread records small facts under one lock. The watchdog thread+(2 Hz) writes a hang file itself while the main thread is blocked. One serial utility queue+samples processes and the Mac every 5 s, writes the black box every 60 s and the history every+15 minutes, and builds the export. Nothing on the main thread does file I/O, JSON encoding or+libproc calls; once every 5 s it counts tabs and asks the visible page for its long tasks.++## What a pass is++`MainLoopObserver` puts two `CFRunLoopObserver`s on the main run loop in the common modes: one+first in line when a pass starts (entry, after waiting, before timers), one last in line when+it ends (before waiting, exit), so Core Animation's commit counts. A pass is the time between+two points where the main thread could take input. It differs from HitchMonitor, which times+how long a block queued on the main queue waits; that wait can span several passes. On+`fifty-tabs` both see the same number of 250 ms stalls, give or take one.++- 250 ms or more is a stall, 1 s a freeze, 2 s a hang (the watchdog writes `hang-<session>-<n>.json`+ while it lasts, then runs `/usr/bin/sample` on Cra for a second, at most three times a session).+- Stalls are tagged with the run-loop mode. `tracking` (a held menu, a drag), `modal` (an+ alert) and `launch` (from the recorder's start until the run loop first sleeps: AppKit runs+ `applicationDidFinishLaunching` before the loop's first pass) are recorded but are not freezes.+- Breadcrumbs are HitchMonitor's marks (swipes, page shown, extension popups, scripted+ commands), cut before any `?`.++## What is recorded++Main-thread passes as a histogram, stalls with mode, breadcrumbs and the site on screen. Per+process kind (browser, renderer, GPU, utility, other, from Chromium's `--type=` argument): CPU,+memory footprint, disk reads and writes, wakeups (in the file only), and processes started and+ended. The Mac: CPU, memory pressure, thermal state, Low Power Mode, free disk. Tabs by state,+sleep refusals by reason, and timings for tab switch, page create, page load and waking a+slept tab. Long tasks in the visible page. Renderer crashes, hangs and failed loads with their+codes. Start-up phases, JSON load and save times, the profile's and caches' size (at export).+The session: a random id, the launch number, the previous session and whether it quit.++Never: addresses beyond the host, paths, query strings, titles, page text, form values, typed+text, an installation id. Incognito pages give counts only.++## Files++`Application Support/Cra/Perf/`, written atomically (not through `JSONStore`, which copies a+`.bak` on every save), and only by the Cra that owns the data folder:++| File | When | Size |+|---|---|---|+| `session.open` | after Chromium starts; removed on a normal quit or when recording is turned off | 200 B |+| `blackbox.json` | every 60 s and at quit: the report as of then | 5–40 KB |+| `blackbox.previous.json` | the last session's black box, moved at launch | 5–40 KB |+| `history.json` | every 15 minutes and at quit: 5-minute buckets for 24 hours, launches, the last session | up to 60 KB |+| `hang-<session>-<n>.json` | at a 2 s hang; this session's and the last one's | 1–10 KB each |++A `session.open` found at launch means that session ended without quitting (crash, force quit,+`kill -9`, power loss). It is made only after `CraCEFRuntime.initialize` succeeds, so the+"another Cra is running" and failed-start exits never leave one.++## Measured (2 Nov 2026, M-series Mac)++| | Budget | Measured |+|---|---|---|+| CPU | < 0.1 % of a core | 0.027–0.039 % (`fifty-tabs`, three runs; an idle session 0.027 %) |+| Main thread | < 0.2 ms per tick | ~95 ns per observer callback (114,663 callbacks, 10.8 ms over a `fifty-tabs` run) |+| Memory | < 5 MB | ~5 KB of recorder data (`selfCost.memoryBytes`) |+| Disk writes | < 60 KB per minute | ~5 KB per minute (black box) plus ~4 KB per minute (history) |++`selfCost` in every report says what recording cost that session; `scripts/scenario.sh`+fails a scenario above 0.1 %.++## Spikes (phase 0)++- **Run-loop observer and modes**: works in the common modes. Found that the launch work runs+ before the first pass and would be missed; it is now measured as a `launch` pass.+- **libproc on helpers**: `proc_listchildpids` returns a pid count; `proc_pid_rusage` reads+ every helper of an ad-hoc hardened-runtime build (no task port needed); `ri_*_time` is in+ mach ticks (×125/3 ns on Apple silicon). CEF runs its GPU process from the plain helper app,+ so kinds come from `--type=` (`KERN_PROCARGS2`), not the app name.+- **`sample` on a release build**: works from the app on itself under the hardened runtime,+ with readable Swift and Objective-C symbols even after `strip` (e.g. `AppDelegate.handleInternalURL(_:)` → `usleep`).+ It takes about 2 s for a 1 s sample, so it runs on the watchdog thread after the hang file+ is written. A notarized Developer ID build still needs a check on the first release.+- **Isolated-world long tasks**: a `PerformanceObserver` in Cra's isolated world receives the+ page's long tasks. Chromium reports none while a page is hidden, so a covered window counts+ nothing (test copies run with `--disable-backgrounding-occluded-windows`).+- **Not done (phase 2)**: Chromium's histograms over CDP, a renderer-side route for+ process-to-tab mapping.++## Testing++- `swift test --package-path Packages/CraCore`: histograms, rings, stall rules, site names,+ sessions, history, process churn, the `sample` parser, insights, the summary and the golden+ `Fixtures/Perf/perf-golden.json` (re-record with `CRA_RECORD_GOLDEN=1`).+- `scripts/test-perf.sh`: the recorder on a real main run loop: injected stalls with their+ breadcrumbs, a hang file on disk before the main thread returns, with a real `sample` stack,+ the marker after a quit and after a simulated kill, a second Cra writing nothing, recording+ off writing nothing.+- `cra://debug?stall=<ms>` blocks the main thread; `cra://debug?perfReport=<path>` writes the+ report now.+- `CRA_PERF=0` turns recording off for a development run.++## Removing it++1. Delete `Sources/Cra/Perf/`, `Packages/CraCore/Sources/CraCore/Perf/`, their tests+ (`Tests/PerfTests.swift`, `scripts/test-perf.sh`, the `Perf*` and `SiteNames` tests and+ `Fixtures/Perf` in CraCore) and the `Perf recorder` line in `scripts/test.sh`.+2. Remove the calls in the files `perf-boundary` allows: `App/main.swift`, `App/AppDelegate.swift`+ (`PerfCEF.install`, the `stall` and `perfReport` hooks, `exportDiagnostics` in the settings+ actions), `Services/BrowserManager.swift`, `Services/Persistence.swift`,+ `Services/HitchMonitor.swift`, `Services/Diagnostics.swift`, `UI/Settings/SettingsWindowController.swift`+ (the pane, `isOpen`). Then the two rules in `scripts/lint.py`.+3. `CraLog.sitesSeen` and `SiteNames` serve "Hide site names"; keep them if that stays.+4. The `lt` observer in `PageScript.isolatedWorld`, and `setProcessEventHandler` in CraCEF.+5. `perfRecording` and `perfHidesSiteNames` in `AppSettings` (old files keep loading: unknown+ keys are ignored) and their lines in `Fixtures/Model`.+6. The harness lists that compile `Perf.swift` and `CraCore/Perf/*.swift`+ (`Tests/test-browser-manager.sh`, `scripts/test-store.sh`, `scripts/fuzz.sh`), and the+ perf invariant in `scripts/scenario.sh`.diff --git a/docs/testing.md b/docs/testing.mdindex 696d45f..0414bb3 100644--- a/docs/testing.md+++ b/docs/testing.md@@ -49,8 +49,9 @@ no page content), so it checks geometry, ink and fills.- **Scenario invariants**, the same for every scenario: the app is still running at the end,no new crash report for its processes, no `fault:` line in `cra.log`, the sidebar sound(`SidebarIntegrity`), main-thread stalls inside the scenario's budget, Cra's memory inside- its budget, helper processes back to baseline five seconds after tabs close, and a quit- within 20 seconds.+ its budget, helper processes back to baseline five seconds after tabs close, the performance+ recorder under 0.1 % of a core (`selfCost.cpuPct` in its perf.json, `budget perfcpu=`) with its+ count of 250 ms stalls within a few of HitchMonitor's, and a quit within 20 seconds.Stall budgets are set from what the app does today, so they catch regressions rather thandescribe a goal. The count of stalls over 50 ms is steady from run to run and carries the@@ -77,6 +78,10 @@ a finding fails, and when one loses a finding the baseline comes down- `importer-without-fixture`: an `…Importer` with no profile under `Tests/Fixtures`.- `core-platform-import`: `Packages/CraCore` importing AppKit, Cocoa, SwiftUI, UIKit or CraCEF([CLAUDE.md](../CLAUDE.md) has the layers).+- `perf-no-network`: networking under either Perf folder. The performance recorder never sends+ anything ([performance.md](performance.md)).+- `perf-boundary`: the recorder reached from a file outside its list, or `CraCEF` imported in+ `Sources/Cra/Perf` anywhere but `PerfCEF.swift`, so it stays removable and testable.## Faultsdiff --git a/scripts/fuzz.sh b/scripts/fuzz.shindex 50c6ef5..9c0fdf8 100755--- a/scripts/fuzz.sh+++ b/scripts/fuzz.sh@@ -8,7 +8,8 @@ TEST_DIR="$(mktemp -d /tmp/cra-fuzz.XXXXXX)"trap 'rm -rf "$TEST_DIR"' EXITmkdir -p build/fuzzxcrun swiftc -swift-version 5 -parse-as-library -sanitize=address -g \- Packages/CraCore/Sources/CraCore/*.swift Sources/Cra/Services/Import/*.swift \+ Packages/CraCore/Sources/CraCore/*.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Sources/Cra/Perf/Perf.swift \+ Sources/Cra/Services/Import/*.swift \Sources/Cra/Services/SidebarStore.swift Sources/Cra/Services/SidebarIntegrity.swift Sources/Cra/Services/Persistence.swift \Sources/Cra/Services/GitHubLiveClient.swift Sources/Cra/Services/FaviconCache.swift \Sources/Cra/Services/SafeStorage.swift Sources/Cra/Services/CraLog.swift Sources/Cra/Services/Scheduler.swift \diff --git a/scripts/lint.py b/scripts/lint.pyindex 53b556c..20d6ed7 100755--- a/scripts/lint.py+++ b/scripts/lint.py@@ -27,6 +27,13 @@ gains a finding fails, one that loses one is reported so the baseline can come dPackages/CraCore importing AppKit, Cocoa, SwiftUI, UIKit or CraCEF. The core is models anddecisions that build and test without a window or Chromium (#51); what needs one stays inthe app, with the pure part in CraCore (Shortcut over KeyChord, FaviconCache over FaviconKey).+ perf-no-network+ Networking (URLSession, CFNetwork, Network.framework, sockets) under either Perf folder: the+ performance recorder never sends anything anywhere (#91); the export is the user's to share.+ perf-boundary+ The performance recorder stays removable (#91, docs/performance.md): outside its two folders+ only the files in PERF_CALLERS reach it, and inside Sources/Cra/Perf only PerfCEF.swift sees+ Chromium (CraCEF), so the facade and recorder compile in the test harnesses."""import collectionsimport os@@ -41,6 +48,12 @@ BASELINE = os.path.join(ROOT, "Tests", "lint-baseline.txt")LAYER_SET = re.compile(r"\b(?!layer\b)(\w*[Ll]ayer)\.(backgroundColor|borderColor|colors|opacity|shadowColor|fillColor|strokeColor)\s*=")FUNC_START = re.compile(r"^\s*(?:@\w+\s+)*(?:(?:private|fileprivate|internal|public|override|static|final|class|nonisolated|convenience|required|@objc)\s+)*(func\s|init[(?!])")CORE_IMPORT = re.compile(r"^\s*(?:@\w+\s+)*import\s+(?:(?:struct|class|enum|protocol|func|var|let|typealias)\s+)?(AppKit|Cocoa|SwiftUI|UIKit|CraCEF)\b")+PERF_DIRS = ("Perf/",)+PERF_CORE = os.path.join("Packages", "CraCore", "Sources", "CraCore", "Perf") + os.sep+PERF_CALLERS = {"App/main.swift", "App/AppDelegate.swift", "Services/BrowserManager.swift", "Services/Persistence.swift",+ "Services/HitchMonitor.swift", "Services/Diagnostics.swift", "UI/Settings/SettingsWindowController.swift"}+PERF_NAME = re.compile(r"\b(?:Perf(?:[A-Z]\w*)?|PerformancePane)\b")+NETWORK = re.compile(r"\bURLSession\b|\bCFNetwork\b|\bNWConnection\b|\bNWPathMonitor\b|^\s*import\s+Network\b|\bCFSocket\w*|\bCFStream\w*|\bsocket\(")CLOCK_FILES = {"Services/SidebarStore.swift", "Services/BrowserManager.swift", "Services/LiveFolderManager.swift","Services/SidebarIntegrity.swift", "App/AppComposition.swift"}@@ -89,6 +102,13 @@ def findings():hit("wall-clock-in-decision", rel, i)if "withObservationTracking" in line:hit("raw-observation-tracking", rel, i)+ if rel.startswith(PERF_DIRS):+ if NETWORK.search(line):+ hit("perf-no-network", rel, i)+ if CORE_IMPORT.match(line) and re.search(r"\bCraCEF\b", line) and rel != "Perf/PerfCEF.swift":+ hit("perf-boundary", rel, i)+ elif rel not in PERF_CALLERS and PERF_NAME.search(line):+ hit("perf-boundary", rel, i)for name in re.findall(r"\benum (\w+)Importer\b", line):if not os.path.isdir(os.path.join(ROOT, "Tests", "Fixtures", name)):hit("importer-without-fixture", f"{rel}:{name}", i)@@ -100,6 +120,8 @@ def findings():for i, line in enumerate(f, 1):if CORE_IMPORT.match(code(line)):hit("core-platform-import", os.path.relpath(full, ROOT), i)+ if os.path.relpath(full, ROOT).startswith(PERF_CORE) and NETWORK.search(code(line)):+ hit("perf-no-network", os.path.relpath(full, ROOT), i)return out, wherediff --git a/scripts/mutate.py b/scripts/mutate.pyindex 237f73d..041791e 100755--- a/scripts/mutate.py+++ b/scripts/mutate.py@@ -27,7 +27,7 @@ TARGETS = [("Sources/Cra/App/AppComposition.swift", ["bash", "scripts/test-store.sh"]),("Sources/Cra/App/FeatureFlags.swift", ["bash", "scripts/test-policies.sh"]),] + [(os.path.relpath(p, ROOT), ["swift", "test", "--package-path", "Packages/CraCore"])- for p in sorted(glob.glob(os.path.join(ROOT, "Packages/CraCore/Sources/CraCore/*.swift")))]+ for p in sorted(glob.glob(os.path.join(ROOT, "Packages/CraCore/Sources/CraCore/**/*.swift"), recursive=True))]OPERATORS = [(r" == ", " != "), (r" != ", " == "), (r" < ", " >= "), (r" > ", " <= "), (r" <= ", " > "), (r" >= ", " < "),diff --git a/scripts/scenario.sh b/scripts/scenario.shindex e8a612b..fc9dae0 100755--- a/scripts/scenario.sh+++ b/scripts/scenario.sh@@ -18,7 +18,7 @@# wait <s> let the app work# pace <s> pause after each command (default 0.2)# repeat <n> <cra://…${i}…> the command n times, ${i} = 1…n-# budget rss=<MB> maxstall=<ms> stalls50=<n> launchstall=<ms>+# budget rss=<MB> maxstall=<ms> stalls50=<n> launchstall=<ms> perfcpu=<% of a core># (stalls count from the first command; start-up has its own launchstall budget)# helpers baseline | helpers settle [slack]# relaunch cra://debug?relaunch=1, then follow the new process@@ -117,7 +117,7 @@ ready "$PID" || problem "Cra did not start reading commands in 30 s"sleep 2PACE=0.2-RSS_BUDGET=1500 MAXSTALL=1500 STALLS50=10 LAUNCHSTALL=1000+RSS_BUDGET=1500 MAXSTALL=1500 STALLS50=10 LAUNCHSTALL=1000 PERFCPU=0.1BASELINE=""expand() { local s="$1"; s="${s//\$\{FIXTURES\}/$FIXTURES}"; s="${s//\$\{PAGE\}/$PAGE}"; s="${s//\$\{EXTENSION_ID\}/$EXTENSION_ID}"; printf '%s' "$s"; }@@ -138,7 +138,7 @@ while IFS= read -r raw || [ -n "$raw" ]; dobudget)shiftfor kv in "$@"; do- case "$kv" in rss=*) RSS_BUDGET="${kv#*=}" ;; launchstall=*) LAUNCHSTALL="${kv#*=}" ;; maxstall=*) MAXSTALL="${kv#*=}" ;; stalls50=*) STALLS50="${kv#*=}" ;; esac+ case "$kv" in rss=*) RSS_BUDGET="${kv#*=}" ;; perfcpu=*) PERFCPU="${kv#*=}" ;; launchstall=*) LAUNCHSTALL="${kv#*=}" ;; maxstall=*) MAXSTALL="${kv#*=}" ;; stalls50=*) STALLS50="${kv#*=}" ;; esacdone ;;helpers)if [ "$2" = "baseline" ]; then BASELINE=$(helpers); echo " helpers: baseline $BASELINE"@@ -204,6 +204,30 @@ echo " stalls: start-up ${launch} ms (budget ${LAUNCHSTALL}); then longest ${ma[ "${maxstall:-0}" -le "$MAXSTALL" ] || problem "a ${maxstall} ms main-thread stall, budget ${MAXSTALL} ms"[ "${over50:-0}" -le "$STALLS50" ] || problem "${over50} stalls over 50 ms, budget ${STALLS50}"+# The performance recorder (#91): what it costs, and whether it saw the stalls HitchMonitor saw.+if alive; then+ send "cra://debug?perfReport=$OUT/perf.json"+ for _ in $(seq 1 25); do [ -s "$OUT/perf.json" ] && break; sleep 0.2; done+ hitch250=$(cat "$OUT/hitch.earlier" "$HITCH" 2>/dev/null | awk '$2 == "stall" && $3 >= 250 { n++ } END { print n + 0 }')+ if [ ! -s "$OUT/perf.json" ]; then problem "no perf.json from the performance recorder"+ else+ verdict=$(python3 -I - "$OUT/perf.json" "$PERFCPU" "$hitch250" <<'PY'+import json, sys+r = json.load(open(sys.argv[1]))+cpu, budget, hitch = r["selfCost"]["cpuPct"], float(sys.argv[2]), int(sys.argv[3])+m = r["mainThread"]+seen = m["stalls"] + m["outsideFreezes"]+print(f"perf: recording costs {cpu:.3f} % of a core (budget {budget}); stalls ≥250 ms: recorder {seen}, HitchMonitor {hitch}")+if cpu > budget: print(f"PROBLEM the performance recorder costs {cpu:.3f} % of a core, budget {budget} %")+# This run's HitchMonitor log starts after the launch the recorder also saw; a few either way is timing.+if abs(seen - hitch) > max(2, hitch // 5): print(f"PROBLEM the recorder counted {seen} stalls of 250 ms or more, HitchMonitor {hitch}")+PY+)+ echo " $(head -1 <<< "$verdict")"+ while IFS= read -r l; do [[ "$l" == PROBLEM* ]] && problem "${l#PROBLEM }"; done <<< "$verdict"+ fi+fi+# A clean quit, within the CefShutdown watchdog.if alive; thensend "cra://debug?quit=1"diff --git a/scripts/test-perf.sh b/scripts/test-perf.shnew file mode 100755index 0000000..82edb6c--- /dev/null+++ b/scripts/test-perf.sh@@ -0,0 +1,14 @@+#!/bin/bash+# The performance recorder (#91) on a real main run loop: stalls, hang files with a stack, the+# session marker, ownership and the recording switch. Its files go to a temporary folder.+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d /tmp/cra-perf-tests.XXXXXX)"+trap 'rm -rf "$TEST_DIR"' EXIT+xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} \+ Packages/CraCore/Sources/CraCore/Perf/*.swift Sources/Cra/Perf/Perf.swift Sources/Cra/Perf/MainLoopObserver.swift \+ Sources/Cra/Perf/PerfSamplers.swift Sources/Cra/Perf/PerfFiles.swift Sources/Cra/Perf/PerfRecorder.swift \+ Sources/Cra/Services/CraLog.swift Sources/Cra/Services/Persistence.swift \+ Tests/PerfTests.swift -o "$TEST_DIR/perf-tests"+"$TEST_DIR/perf-tests"+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/perf-tests" "$CRA_TEST_KEEP/"diff --git a/scripts/test-store.sh b/scripts/test-store.shindex f62c63b..ad0fb34 100755--- a/scripts/test-store.sh+++ b/scripts/test-store.sh@@ -5,7 +5,8 @@ cd "$(dirname "$0")/.."TEST_DIR="$(mktemp -d /tmp/cra-store-tests.XXXXXX)"trap 'rm -rf "$TEST_DIR"' EXITxcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} \- Packages/CraCore/Sources/CraCore/*.swift Sources/Cra/Services/Import/*.swift \+ Packages/CraCore/Sources/CraCore/*.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Sources/Cra/Perf/Perf.swift \+ Sources/Cra/Services/Import/*.swift \Sources/Cra/Services/SidebarStore.swift Sources/Cra/Services/SidebarIntegrity.swift Sources/Cra/Services/Persistence.swift \Sources/Cra/Services/GitHubLiveClient.swift Sources/Cra/Services/FaviconCache.swift Sources/Cra/Services/SafeStorage.swift \Sources/Cra/Services/CraLog.swift Sources/Cra/Services/Scheduler.swift \diff --git a/scripts/test.sh b/scripts/test.shindex 9b86af7..739ca16 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -23,6 +23,7 @@ if [ "${1:-}" != core ]; thensuite "Store and importers" scripts/test-store.shsuite "Policies" scripts/test-policies.shsuite "Command bar glyph" scripts/test-command-bar-glyph.sh+ suite "Perf recorder" scripts/test-perf.shsuite "Lint" scripts/lint.pyfi