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.
Tab sleeping like Arc: two opt-in switches, in-place discard keeps history and scroll, calls stay awake (#153) (#159)
Victor Kildahl72b3a6890941
diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swiftindex 8c74150..59b1ddf 100644--- a/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift@@ -98,7 +98,7 @@ public enum PerfInsights {if footprint >= largeFootprintBytes {let slept = r.tabs.latest?.slept ?? 0out.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." : "Pages you haven't looked at in 4 hours close, and reload when you open them; the 10 tabs used last stay."))+ detail: slept > 0 ? "Tab sleeping has \(slept) tab\(slept == 1 ? "" : "s") asleep." : "Pages you haven't looked at in a while (4 hours unless you change it) close, and reload when you open them. Settings ▸ Tabs ▸ Tab Cleanup can close them sooner, or when the Mac is short of memory."))}return out}diff --git a/Packages/CraCore/Sources/CraCore/SidebarModel.swift b/Packages/CraCore/Sources/CraCore/SidebarModel.swiftindex b2feaa2..8e92c02 100644--- a/Packages/CraCore/Sources/CraCore/SidebarModel.swift+++ b/Packages/CraCore/Sources/CraCore/SidebarModel.swift@@ -462,6 +462,13 @@ public struct AppSettings: Codable, Equatable {/// Dia's Tabs ▸ "Clean up tabs I haven't used in:" checkbox; `autoArchive` keeps the/// threshold while this is off.public var autoArchiveEnabled: Bool = true+ /// Tabs ▸ "Force tabs out of memory after:" (GitHub #153): on at Arc's 4 hours, like 0.1.28,+ /// which had no setting. Off, the clock closes no page. Keys of their own: the switch 0.1.22–0.1.27+ /// saved (tabSleepEnabled, tabSleep) must not turn this off on update.+ public var tabSleepTimerEnabled: Bool = true+ public var tabSleepAfter: TabSleepThreshold = .fourHours+ /// Tabs ▸ "Force tabs out of memory when the Mac is short of memory" (GitHub #153), off like Arc.+ public var tabSleepOnMemoryPressure: Bool = false/// Privacy ▸ "Always use secure connections": Chrome's HTTPS-Only Mode.public var httpsOnly: Bool = false/// Arc's searchSuggestEnabled: the command bar asks the search engine for suggestions@@ -632,6 +639,9 @@ extension AppSettings {hapticFeedbackOnReorder = try c.decodeIfPresent(Bool.self, forKey: .hapticFeedbackOnReorder) ?? truewarnBeforeQuitting = try c.decodeIfPresent(Bool.self, forKey: .warnBeforeQuitting) ?? falseautoArchiveEnabled = try c.decodeIfPresent(Bool.self, forKey: .autoArchiveEnabled) ?? true+ tabSleepTimerEnabled = try c.decodeIfPresent(Bool.self, forKey: .tabSleepTimerEnabled) ?? true+ tabSleepAfter = (try? c.decodeIfPresent(TabSleepThreshold.self, forKey: .tabSleepAfter)) ?? .fourHours+ tabSleepOnMemoryPressure = try c.decodeIfPresent(Bool.self, forKey: .tabSleepOnMemoryPressure) ?? falsehttpsOnly = try c.decodeIfPresent(Bool.self, forKey: .httpsOnly) ?? falsesearchSuggestions = try c.decodeIfPresent(Bool.self, forKey: .searchSuggestions) ?? trueshowSpaceHeaderOnSingleSpace = try c.decodeIfPresent(Bool.self, forKey: .showSpaceHeaderOnSingleSpace) ?? truediff --git a/Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift b/Packages/CraCore/Sources/CraCore/TabSleepPolicy.swiftnew file mode 100644index 0000000..2b0470b--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift@@ -0,0 +1,124 @@+import Foundation++/// Which hidden pages tab sleeping asks to close. By default it is Arc's (GitHub #136): a page out+/// of sight for 4 hours closes unless it is one of the 10 tabs used last. Settings ▸ Tabs can+/// change the time, turn the clock off, or close pages while macOS reports memory pressure+/// (GitHub #153). The probes in BrowserManager still decide whether a candidate may close.+public struct TabSleepPolicy: Equatable, Sendable {+ public enum Reason: String, Sendable { case timer, memoryPressure }++ /// A page this long out of sight, and silent as long, is a candidate.+ public var hiddenFor: TimeInterval+ /// The tabs on screen and the ones hidden most recently, `protectedRecentTabs` in all, stay.+ public var keepsRecentTabs: Bool+ /// At most this many pages are asked in one pass (nil: all of them).+ public var limit: Int?+ public var reason: Reason++ public init(hiddenFor: TimeInterval, keepsRecentTabs: Bool = true, limit: Int? = nil, reason: Reason = .timer) {+ self.hiddenFor = hiddenFor+ self.keepsRecentTabs = keepsRecentTabs+ self.limit = limit+ self.reason = reason+ }++ /// Arc never discards the pages of the 10 tabs used last (WebContentLifecycleOptimization's+ /// protectedLRUTabCount).+ public static let protectedRecentTabs = 10++ /// "Force tabs out of memory after:". Arc's 4 hours, or longer, keep the 10 tabs used last;+ /// a shorter time is asked for to close those too, since they hold most of the memory.+ public static func timer(_ after: TabSleepThreshold) -> TabSleepPolicy {+ TabSleepPolicy(hiddenFor: after.seconds, keepsRecentTabs: after.seconds >= TabSleepThreshold.fourHours.seconds)+ }++ /// "…when the Mac is short of memory": the 3 pages hidden longest, whatever their rank, but+ /// none left in the last 5 minutes, so a tab just left (or just woken) isn't closed again.+ public static let memoryPressure = TabSleepPolicy(hiddenFor: 5 * 60, keepsRecentTabs: false, limit: 3, reason: .memoryPressure)++ /// macOS reports a level for a while after pages close, so a sweep waits this long for the+ /// last one to tell before taking more.+ public static let pressureSweepInterval: TimeInterval = 90++ /// Whether the minute's pass sweeps for memory pressure.+ public static func sweepsForPressure(_ pressure: PerfSystemSample.Pressure, enabled: Bool, lastSweep: Date?, now: Date) -> Bool {+ enabled && pressure.isShort && lastSweep.map { now.timeIntervalSince($0) >= pressureSweepInterval } ?? true+ }++ /// A page as tab sleeping sees it: when it went off screen (nil while shown) and when it last+ /// played or stopped playing sound.+ public struct Page: Equatable, Sendable {+ public var id: UUID+ public var hiddenAt: Date?+ public var audibleAt: Date?++ public init(id: UUID, hiddenAt: Date?, audibleAt: Date? = nil) {+ self.id = id+ self.hiddenAt = hiddenAt+ self.audibleAt = audibleAt+ }+ }++ /// The tabs on screen, then the ones hidden most recently, `count` in all.+ public static func recentlyShown(_ pages: [Page], visible: [UUID], count: Int) -> Set<UUID> {+ let hidden = pages.compactMap { p in p.hiddenAt.map { (p.id, $0) } }.sorted { $0.1 > $1.1 }.map(\.0)+ return Set((visible + hidden).prefix(count))+ }++ /// Chromium's freezing policy sees what Cra's page probes can't: a call with the camera and+ /// microphone off (an open RTCPeerConnection), a USB, Bluetooth, HID or serial device, a+ /// mirrored or captured tab. `reasons` are its CannotFreezeReasonToString names for the page+ /// and the pages connected to it (Cra.getFreezingState); "" when none of them keeps it awake.+ public static func refusal(freezingReasons reasons: [String]) -> String {+ if reasons.contains("has an active WebRTC connection") { return "call" }+ if reasons.contains(where: { $0.hasPrefix("connected to ") }) { return "device" }+ if reasons.contains(where: { $0.hasPrefix("capturing ") || $0 == "being mirrored" }) { return "capturing" }+ return ""+ }++ /// The pages to ask, hidden longest first. The caller skips the ones its probes refuse+ /// before it counts toward `limit`.+ public func candidates(_ pages: [Page], visible: [UUID], protectedRecent: Int = protectedRecentTabs, now: Date) -> [UUID] {+ let cutoff = now.addingTimeInterval(-hiddenFor)+ let kept = keepsRecentTabs ? Self.recentlyShown(pages, visible: visible, count: protectedRecent) : []+ return pages+ .filter { p in+ guard let hidden = p.hiddenAt, hidden < cutoff, !visible.contains(p.id), !kept.contains(p.id) else { return false }+ return p.audibleAt.map { $0 < cutoff } ?? true+ }+ .sorted { ($0.hiddenAt!, $0.id.uuidString) < ($1.hiddenAt!, $1.id.uuidString) }+ .map(\.id)+ }+}++extension PerfSystemSample.Pressure {+ /// macOS warns while the compressor works hard; critical is the same state further along.+ public var isShort: Bool { self == .warning || self == .critical }+}++/// Settings ▸ Tabs ▸ "Force tabs out of memory after:" (GitHub #153). Arc's 4 hours by default;+/// the checkbox, not a case, turns the clock off.+public enum TabSleepThreshold: String, Codable, CaseIterable, Identifiable {+ case fifteenMinutes, thirtyMinutes, oneHour, twoHours, fourHours, eightHours+ public var id: String { rawValue }+ public var seconds: TimeInterval {+ switch self {+ case .fifteenMinutes: return 15 * 60+ case .thirtyMinutes: return 30 * 60+ case .oneHour: return 3600+ case .twoHours: return 2 * 3600+ case .fourHours: return 4 * 3600+ case .eightHours: return 8 * 3600+ }+ }+ public var label: String {+ switch self {+ case .fifteenMinutes: return "15 minutes"+ case .thirtyMinutes: return "30 minutes"+ case .oneHour: return "1 hour"+ case .twoHours: return "2 hours"+ case .fourHours: return "4 hours"+ case .eightHours: return "8 hours"+ }+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/settings.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/settings.jsonindex 3be6f0e..3083135 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/settings.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/settings.json@@ -10,5 +10,6 @@"newTabButtonAtTop": false, "newTabButtonDefaultMigrated": true, "newTabsAtTop": 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+ "showToolbar": true, "tabSleep": "fourHours", "tabSleepAfter": "oneHour", "tabSleepEnabled": true,+ "tabSleepOnMemoryPressure": true, "tabSleepTimerEnabled": false, "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 ea73102..582b03e 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@@ -33,6 +33,9 @@"showSpaceHeaderOnSingleSpace" : true,"showStatusBar" : true,"showToolbar" : false,+ "tabSleepAfter" : "fourHours",+ "tabSleepOnMemoryPressure" : false,+ "tabSleepTimerEnabled" : true,"toolbarDefaultMigrated" : true,"toolbarShowsFullURL" : false,"warnBeforeQuitting" : falsediff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.jsonindex 79c8d16..a3ff129 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json@@ -42,6 +42,9 @@"showSpaceHeaderOnSingleSpace" : true,"showStatusBar" : true,"showToolbar" : true,+ "tabSleepAfter" : "fourHours",+ "tabSleepOnMemoryPressure" : false,+ "tabSleepTimerEnabled" : true,"toolbarDefaultMigrated" : true,"toolbarShowsFullURL" : false,"warnBeforeQuitting" : falsediff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.jsonindex 612284f..d5bf063 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json@@ -42,6 +42,9 @@"showSpaceHeaderOnSingleSpace" : true,"showStatusBar" : true,"showToolbar" : true,+ "tabSleepAfter" : "fourHours",+ "tabSleepOnMemoryPressure" : false,+ "tabSleepTimerEnabled" : true,"toolbarDefaultMigrated" : true,"toolbarShowsFullURL" : false,"warnBeforeQuitting" : falsediff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.jsonindex bdb8d18..68bd11f 100644--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json@@ -52,6 +52,9 @@"showSpaceHeaderOnSingleSpace" : false,"showStatusBar" : false,"showToolbar" : true,+ "tabSleepAfter" : "oneHour",+ "tabSleepOnMemoryPressure" : true,+ "tabSleepTimerEnabled" : false,"toolbarDefaultMigrated" : true,"toolbarShowsFullURL" : false,"warnBeforeQuitting" : truediff --git a/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swift b/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swiftindex fcb9c77..485fa6e 100644--- a/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swift+++ b/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swift@@ -188,7 +188,7 @@ struct PerfInsightTests {#expect(r.insights[6].title == "1 page stopped (“Aw, Snap!”)")#expect(r.insights[11].detail.hasPrefix("1.0 GB free"))#expect(r.insights[12].title == "Cra uses 9.0 GB of memory")- #expect(r.insights[12].detail.contains("4 hours"))+ #expect(r.insights[12].detail.contains("Settings ▸ Tabs ▸ Tab Cleanup"))}@Test func aFewStallsInALongSessionAreNotFrequent() {diff --git a/Packages/CraCore/Tests/CraCoreTests/TabSleepPolicyTests.swift b/Packages/CraCore/Tests/CraCoreTests/TabSleepPolicyTests.swiftnew file mode 100644index 0000000..f7e2703--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/TabSleepPolicyTests.swift@@ -0,0 +1,121 @@+import CraCore+import Foundation+import Testing++/// Settings ▸ Tabs ▸ Tab Cleanup's two tab-sleeping switches (GitHub #153), on Arc's defaults.+struct TabSleepPolicyTests {+ let now = Date(timeIntervalSince1970: 1_000_000)+ let visible = UUID()++ /// Pages hidden `minutes` ago, one per entry, plus the visible tab.+ func pages(hiddenMinutesAgo minutes: [Double]) -> [TabSleepPolicy.Page] {+ [TabSleepPolicy.Page(id: visible, hiddenAt: nil)]+ + minutes.map { TabSleepPolicy.Page(id: UUID(), hiddenAt: now.addingTimeInterval(-$0 * 60)) }+ }++ /// A settings file without the keys is 0.1.28: 4 hours, the 10 tabs used last kept, no+ /// sweep for memory pressure.+ @Test func defaultsAreArcs() throws {+ let s = try JSONDecoder().decode(AppSettings.self, from: Data("{}".utf8))+ #expect(s.tabSleepTimerEnabled && s.tabSleepAfter == .fourHours && !s.tabSleepOnMemoryPressure)+ let policy = TabSleepPolicy.timer(s.tabSleepAfter)+ #expect(policy == TabSleepPolicy(hiddenFor: 4 * 3600, keepsRecentTabs: true))+ #expect(!TabSleepPolicy.sweepsForPressure(.critical, enabled: s.tabSleepOnMemoryPressure, lastSweep: nil, now: now))+ }++ /// 0.1.22–0.1.27 saved their own switch; it neither turns the clock off nor sets its time.+ @Test func earlierSwitchIsIgnored() throws {+ let json = #"{"tabSleepEnabled": false, "tabSleep": "fifteenMinutes"}"#+ let s = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8))+ #expect(s.tabSleepTimerEnabled && s.tabSleepAfter == .fourHours)+ }++ /// An unknown time (a later Cra's) falls back to 4 hours without resetting the file.+ @Test func unknownTimeFallsBack() throws {+ let json = #"{"tabSleepAfter": "fortnight", "searchEngine": "kagi"}"#+ let s = try JSONDecoder().decode(AppSettings.self, from: Data(json.utf8))+ #expect(s.tabSleepAfter == .fourHours && s.searchEngine == .kagi)+ }++ @Test func thresholds() {+ #expect(TabSleepThreshold.allCases.map(\.label) == ["15 minutes", "30 minutes", "1 hour", "2 hours", "4 hours", "8 hours"])+ #expect(TabSleepThreshold.allCases.map(\.seconds) == [900, 1800, 3600, 7200, 14400, 28800])+ }++ /// At 4 hours a page hidden 3 h 59 min stays and one hidden 4 h 1 min is a candidate, unless+ /// it is among the 10 tabs used last.+ @Test func fourHoursKeepsTheTenUsedLast() {+ let policy = TabSleepPolicy.timer(.fourHours)+ let p = pages(hiddenMinutesAgo: [239, 241])+ #expect(policy.candidates(p, visible: [visible], now: now) == [])+ #expect(policy.candidates(p, visible: [visible], protectedRecent: 2, now: now) == [p[2].id])+ let many = pages(hiddenMinutesAgo: (0..<12).map { 300 + Double($0) })+ // The visible tab and the 9 hidden most recently stay: the 3 hidden longest go, oldest first.+ #expect(policy.candidates(many, visible: [visible], now: now) == [many[12].id, many[11].id, many[10].id])+ }++ @Test func eightHoursKeepsThemToo() {+ let p = pages(hiddenMinutesAgo: [9 * 60])+ #expect(TabSleepPolicy.timer(.eightHours).candidates(p, visible: [visible], now: now) == [])+ #expect(TabSleepPolicy.timer(.eightHours).candidates(p, visible: [visible], protectedRecent: 1, now: now) == [p[1].id])+ }++ /// Shorter than Arc's 4 hours, the 10 tabs used last are not kept: they hold the memory.+ @Test func shortTimesCloseTheTenUsedLast() {+ let p = pages(hiddenMinutesAgo: [14, 16])+ #expect(TabSleepPolicy.timer(.fifteenMinutes).candidates(p, visible: [visible], now: now) == [p[2].id])+ #expect(!TabSleepPolicy.timer(.twoHours).keepsRecentTabs)+ }++ /// The tab on screen and both panes of a split are never candidates, whatever their dates.+ @Test func visiblePagesStay() {+ let split = TabSleepPolicy.Page(id: UUID(), hiddenAt: now.addingTimeInterval(-86400))+ let p = pages(hiddenMinutesAgo: []) + [split]+ #expect(TabSleepPolicy.memoryPressure.candidates(p, visible: [visible, split.id], now: now) == [])+ }++ /// A page that played sound waits as long after it went quiet as after it went out of sight.+ @Test func recentlyAudibleStays() {+ let id = UUID()+ let hidden = now.addingTimeInterval(-3600)+ let quiet2 = TabSleepPolicy.Page(id: id, hiddenAt: hidden, audibleAt: now.addingTimeInterval(-120))+ let quiet20 = TabSleepPolicy.Page(id: id, hiddenAt: hidden, audibleAt: now.addingTimeInterval(-1200))+ #expect(TabSleepPolicy.timer(.fifteenMinutes).candidates([quiet2], visible: [], now: now) == [])+ #expect(TabSleepPolicy.timer(.fifteenMinutes).candidates([quiet20], visible: [], now: now) == [id])+ #expect(TabSleepPolicy.memoryPressure.candidates([quiet2], visible: [], now: now) == [])+ }++ /// Under pressure: oldest first, the 10 used last included, none left in the last 5 minutes.+ @Test func pressureTakesTheOldestPastTheGrace() {+ let policy = TabSleepPolicy.memoryPressure+ #expect(policy.limit == 3 && policy.reason == .memoryPressure)+ let p = pages(hiddenMinutesAgo: [4.98, 5.02, 30, 10])+ #expect(policy.candidates(p, visible: [visible], now: now) == [p[3].id, p[4].id, p[2].id])+ }++ @Test func pressureSweepTiming() {+ #expect(!TabSleepPolicy.sweepsForPressure(.warning, enabled: false, lastSweep: nil, now: now))+ #expect(!TabSleepPolicy.sweepsForPressure(.normal, enabled: true, lastSweep: nil, now: now))+ #expect(!TabSleepPolicy.sweepsForPressure(.unknown, enabled: true, lastSweep: nil, now: now))+ #expect(TabSleepPolicy.sweepsForPressure(.warning, enabled: true, lastSweep: nil, now: now))+ #expect(TabSleepPolicy.sweepsForPressure(.critical, enabled: true, lastSweep: nil, now: now))+ #expect(!TabSleepPolicy.sweepsForPressure(.warning, enabled: true, lastSweep: now.addingTimeInterval(-89), now: now))+ #expect(TabSleepPolicy.sweepsForPressure(.warning, enabled: true, lastSweep: now.addingTimeInterval(-91), now: now))+ }++ /// Chromium's freezing reasons that keep a page from sleeping; the rest (a Web Lock, recently+ /// visible, notification permission) don't.+ @Test func freezingReasonsThatKeepAPage() {+ #expect(TabSleepPolicy.refusal(freezingReasons: ["has an active WebRTC connection", "holding Web Lock"]) == "call")+ #expect(TabSleepPolicy.refusal(freezingReasons: ["connected to USB device"]) == "device")+ #expect(TabSleepPolicy.refusal(freezingReasons: ["connected to serial port"]) == "device")+ #expect(TabSleepPolicy.refusal(freezingReasons: ["being mirrored"]) == "capturing")+ #expect(TabSleepPolicy.refusal(freezingReasons: ["capturing display"]) == "capturing")+ #expect(TabSleepPolicy.refusal(freezingReasons: ["holding Web Lock", "recently visible", "has notification permission"]) == "")+ #expect(TabSleepPolicy.refusal(freezingReasons: []) == "")+ }++ @Test func pressureLevels() {+ #expect([PerfSystemSample.Pressure.normal, .warning, .critical, .unknown].map(\.isShort) == [false, true, true, false])+ }+}diff --git a/Sources/Cra/App/AppComposition.swift b/Sources/Cra/App/AppComposition.swiftindex fdf5a35..275c132 100644--- a/Sources/Cra/App/AppComposition.swift+++ b/Sources/Cra/App/AppComposition.swift@@ -21,9 +21,6 @@ final class AppComposition {/// the windows' browser managers, which the composition does not own.static let autoArchiveInterval: TimeInterval = 1800static let tabSleepInterval: TimeInterval = 60- /// Arc discards a page after 4 hours out of sight and has no setting for it- /// (WebContentLifecycleOptimization's timeToDiscardTab, GitHub #136).- static let tabSleepAfter: TimeInterval = 4 * 3600/// Arc's timeToFreezeTab: a page out of sight 30 minutes is voted to freeze.static let tabFreezeAfter: TimeInterval = 30 * 60diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex 27284c4..d9641bd 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -52,7 +52,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {startContentBlocking()SoftwareUpdater.shared.start(app: self)buildMenus()- store.hasPage = { [unowned self] in self.runtime(for: $0) != nil }+ store.hasPage = { [unowned self] in self.runtime(for: $0).map { !$0.discarded } ?? false }// A tip takes the tones of the space its browser window is in (the sidebar may be a// floating panel, a child of that window).ArcTooltipController.shared.tones = { [unowned self] window in@@ -188,11 +188,28 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {/// AppComposition.tabFreezeAfter; `cra://debug?freezeTabs=` shortens it for a test.private var freezeAfter = AppComposition.tabFreezeAfter+ /// The last memory-pressure sweep (TabSleepPolicy.sweepsForPressure).+ private var lastPressureSweep: Date?++ /// Settings ▸ Tabs ▸ Tab Cleanup, read every minute so a change counts from the next pass.private func sleepIdleTabs() {+ let settings = store.settingsfor w in mainWindows {w.browsers.freezeIdleTabs(hiddenLongerThan: freezeAfter)- w.browsers.sleepIdleTabs(hiddenLongerThan: AppComposition.tabSleepAfter)+ if settings.tabSleepTimerEnabled { w.browsers.sleepIdleTabs(.timer(settings.tabSleepAfter)) }}+ sweepForMemoryPressure(PerfSystemSample.pressure(level: PerfSystemSampler.pressureLevel()))+ }++ /// "Force tabs out of memory when the Mac is short of memory" (GitHub #153): while macOS+ /// reports memory pressure, the pages hidden longest close, a few per sweep, until it doesn't.+ private func sweepForMemoryPressure(_ pressure: PerfSystemSample.Pressure) {+ let now = composition.clock.now+ guard TabSleepPolicy.sweepsForPressure(pressure, enabled: store.settings.tabSleepOnMemoryPressure,+ lastSweep: lastPressureSweep, now: now) else { return }+ lastPressureSweep = now+ CraLog.note("tab sleep: memory pressure \(pressure.rawValue), closing up to \(TabSleepPolicy.memoryPressure.limit ?? 0) pages per window")+ for w in mainWindows { w.browsers.sleepIdleTabs(.memoryPressure) }}/// Settings > Privacy > "Always use secure connections", live like content blocking.@@ -622,9 +639,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {for w in mainWindows { w.browsers.freezeIdleTabs(hiddenLongerThan: s) }return}- // One tab-sleeping pass with a short threshold (seconds), so it can be tried without waiting.+ // One tab-sleeping pass with a short threshold (seconds), so it can be tried without waiting+ // or opening 11 tabs: the 10 tabs used last aren't kept.if let s = dict["sleepTabs"].flatMap(Double.init) {- for w in mainWindows { w.browsers.sleepIdleTabs(hiddenLongerThan: s) }+ for w in mainWindows { w.browsers.sleepIdleTabs(TabSleepPolicy(hiddenFor: s, keepsRecentTabs: false)) }+ return+ }+ // One memory-pressure sweep as if macOS reported this level (warning, critical), without+ // filling memory or waiting out the last sweep. The setting still decides.+ if let level = dict["memoryPressure"].flatMap(PerfSystemSample.Pressure.init(rawValue:)) {+ lastPressureSweep = nil+ sweepForMemoryPressure(level)return}// Opens what normally needs a pointer or a held key, for screenshots.diff --git a/Sources/Cra/Perf/PerfCEF.swift b/Sources/Cra/Perf/PerfCEF.swiftindex e3f7ea3..bfe9450 100644--- a/Sources/Cra/Perf/PerfCEF.swift+++ b/Sources/Cra/Perf/PerfCEF.swift@@ -67,7 +67,7 @@ enum PerfCEF {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 },+ live: managers.reduce(0) { $0 + $1.runtimes.values.filter { !$0.discarded }.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 },diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftindex 5a9a8f5..fe72c38 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -24,6 +24,11 @@ final class TabRuntime {var freezeVoted = false/// When the page last went off screen (nil while shown); tab sleeping counts from here.var hiddenAt: Date?+ /// When the page last started or stopped playing sound; tab sleeping waits as long after it.+ var audibleAt: Date?+ /// Tab sleeping discarded the page in place (Cra.discard): Chromium keeps its history and+ /// scroll position and loads it again when the tab is shown.+ var discarded = false/// Invalidates a pending sleep probe even when navigation returns to the same URL.var navigationRevision: UInt = 0/// A page that refused to sleep isn't asked again before this (nil: ask on the next pass).@@ -235,6 +240,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {guard let rt = ensureRuntime(for: id) else { shown.append(id); continue }if let made { creating += Perf.ms(since: made) }if !wasVisible.contains(id) {+ wake(id, rt)returnToTab(rt)// A page can change its colours while hidden. One still loading reports them as it// paints; asked now, before its styles arrive, it would answer white.@@ -387,18 +393,23 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {// MARK: Tab sleeping- /// Like Arc, with no setting: a page off screen that long (AppComposition.tabSleepAfter, Arc's- /// 4 hours) closes, like a closed pinned tab, and loads its URL again when shown. Pages that are- /// loading, playing sound, recording, in Picture in Picture or DevTools, holding text the- /// user typed or asking before they close (their own onbeforeunload) stay awake, and are- /// asked again only after `refusalBackoff`. The log says once why a page stays awake.- func sleepIdleTabs(hiddenLongerThan seconds: TimeInterval) {+ /// The pages `policy` picks (by default Arc's: out of sight 4 hours, not one of the 10 tabs+ /// used last) are discarded like Arc's: Chromium ends the page and keeps its back/forward list+ /// and scroll position, and loads it again when the tab is shown. Pages that are loading,+ /// playing sound, recording, in Picture in Picture or DevTools, holding text the user typed,+ /// asking before they close (their own onbeforeunload), in a call (even with the camera and+ /// microphone off) or using a device stay awake, and are asked again only after+ /// `refusalBackoff`; those don't count toward the policy's limit. The log says once why a page+ /// stays awake.+ func sleepIdleTabs(_ policy: TabSleepPolicy) {let now = clock.now- let cutoff = now.addingTimeInterval(-seconds)- let recent = recentlyShown- for (id, rt) in runtimes where !recent.contains(id) {+ let cutoff = now.addingTimeInterval(-policy.hiddenFor)+ var asked = 0+ for id in policy.candidates(sleepPages, visible: visibleTabIDs, protectedRecent: protectedRecentTabs, now: now) {+ guard let rt = runtimes[id], canSleep(rt, before: cutoff), rt.sleepProbeAfter.map({ $0 <= now }) ?? true else { continue }+ if let limit = policy.limit, asked >= limit { break }+ asked += 1let b = rt.browser- guard canSleep(rt, before: cutoff), rt.sleepProbeAfter.map({ $0 <= now }) ?? true else { continue }let url = b.currentURLlet navigationRevision = rt.navigationRevision// Cra's isolated world sees typed text and media; the page's own onbeforeunload is only@@ -413,12 +424,16 @@ 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)")+ // Chromium knows about calls, devices and capture that the page's own+ // world can't show; an older CEF without Cra's methods doesn't say.+ rt.browser.sendDevToolsMethod("Cra.getFreezingState", params: "{}") { [weak self, weak rt] result, _ in+ DispatchQueue.main.async {+ guard let self, let rt, self.stillSleepable(id, rt, url, navigationRevision, cutoff) else { return }+ let refusal = TabSleepPolicy.refusal(freezingReasons: Self.freezingReasons(result))+ guard refusal.isEmpty else { return self.keepAwake(rt, url, refusal) }+ self.discard(id, rt, url, policy)+ }}- self.unload(id)}}}@@ -426,6 +441,51 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {}}+ /// Chrome's in-place discard (Cra.discard, which needs WebContentsDiscard). A CEF without it+ /// answers an error: the page closes instead, and its tab loads the URL again when shown.+ private func discard(_ id: UUID, _ rt: TabRuntime, _ url: String, _ policy: TabSleepPolicy) {+ rt.browser.sendDevToolsMethod("Cra.discard", params: "{}") { [weak self, weak rt] result, error in+ DispatchQueue.main.async {+ guard let self, let rt, self.runtimes[id] === rt, !self.visibleTabIDs.contains(id) else { return }+ let reply = error == nil ? Self.jsonObject(result) : nil+ let discarded = reply?["discarded"] as? Bool == true+ // Chromium keeps a page whose navigation was about to commit; ask again later.+ if error == nil, !discarded { return self.keepAwake(rt, url, "navigating") }+ self.sleptTabs.insert(id)+ Perf.count(.tabSlept, policy.reason.rawValue)+ if !rt.browser.isIncognito {+ let why = policy.reason == .memoryPressure ? ", the Mac is short of memory" : ""+ let how = !discarded ? "unloads" : reply?["processEnded"] as? Bool == true ? "discards (its renderer ended)" : "discards"+ CraLog.note("tab sleep \(how) \(CraLog.host(url)) (hidden \(Int(self.clock.now.timeIntervalSince(rt.hiddenAt ?? self.clock.now) / 60)) min\(why))")+ }+ guard discarded else { return self.unload(id) }+ rt.discarded = true+ if rt.freezeVoted { self.setFreezingVote(rt, false) }+ self.delegate?.browserManagerDidUpdate(id)+ }+ }+ }++ /// Shown again: Chromium loads a discarded page when it becomes visible; Cra.load starts it+ /// now, as Chrome does on selecting the tab, so a covered window doesn't wait.+ private func wake(_ id: UUID, _ rt: TabRuntime) {+ guard rt.discarded else { return }+ rt.discarded = false+ if sleptTabs.remove(id) != nil { Perf.begin(.tabWake, id.uuidString) }+ log(id, "loads its discarded page again")+ rt.browser.sendDevToolsMethod("Cra.load", params: "{}") { _, _ in }+ }++ private static func jsonObject(_ s: String?) -> [String: Any]? {+ s?.data(using: .utf8).flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }+ }++ /// Cra.getFreezingState's reasons for the page and the pages connected to it.+ private static func freezingReasons(_ result: String?) -> [String] {+ guard let json = jsonObject(result) else { return [] }+ return (json["reasons"] as? [String] ?? []) + (json["connectedReasons"] as? [String] ?? [])+ }+private func stillSleepable(_ id: UUID, _ rt: TabRuntime, _ url: String, _ revision: UInt, _ cutoff: Date) -> Bool {runtimes[id] === rt && rt.navigationRevision == revision && rt.browser.currentURL == url && canSleep(rt, before: cutoff)}@@ -452,7 +512,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {let recent = recentlyShownfor (id, rt) in runtimes {let b = rt.browser- let vote = !recent.contains(id) && rt.hiddenAt.map { $0 < cutoff } == true && b.isCreated && !b.isClosed+ let vote = !recent.contains(id) && !rt.discarded && rt.hiddenAt.map { $0 < cutoff } == true && b.isCreated && !b.isClosed&& !(nowPlaying?.entries.contains { $0.id == id } ?? false)if vote != rt.freezeVoted { setFreezingVote(rt, vote) }}@@ -470,20 +530,24 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {private static var loggedFreezingError = false- /// Arc never discards the pages of the 10 tabs used last, however long ago that was- /// (WebContentLifecycleOptimization's protectedLRUTabCount, GitHub #136).- var protectedRecentTabs = 10+ /// Arc never freezes or discards the pages of the 10 tabs used last, however long ago that+ /// was (TabSleepPolicy.protectedRecentTabs, GitHub #136).+ var protectedRecentTabs = TabSleepPolicy.protectedRecentTabs++ private var sleepPages: [TabSleepPolicy.Page] {+ // A discarded page has given its memory back, like a closed one: it holds none of the 10 places.+ runtimes.values.filter { !$0.discarded }.map { TabSleepPolicy.Page(id: $0.tabID, hiddenAt: $0.hiddenAt, audibleAt: $0.audibleAt) }+ }/// The tabs on screen now, then the ones hidden most recently, up to `protectedRecentTabs`.private var recentlyShown: Set<UUID> {- let hidden = runtimes.values.compactMap { rt in rt.hiddenAt.map { (rt.tabID, $0) } }.sorted { $0.1 > $1.1 }.map(\.0)- return Set((visibleTabIDs + hidden).prefix(protectedRecentTabs))+ TabSleepPolicy.recentlyShown(sleepPages, visible: visibleTabIDs, count: protectedRecentTabs)}private func canSleep(_ rt: TabRuntime, before cutoff: Date) -> Bool {let b = rt.browser- return rt.hiddenAt.map { $0 < cutoff } == true && !visibleTabIDs.contains(rt.tabID)- && b.isCreated && !b.isClosed && !b.isLoading && !b.isInPictureInPicture+ return !rt.discarded && rt.hiddenAt.map { $0 < cutoff } == true && rt.audibleAt.map { $0 < cutoff } != false+ && !visibleTabIDs.contains(rt.tabID) && b.isCreated && !b.isClosed && !b.isLoading && !b.isInPictureInPicture&& !b.isCapturingMedia && !b.isAudible && !b.hasDevTools}@@ -686,6 +750,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {func browser(_ browser: CraBrowser, didChangeAudible audible: Bool) {guard let id = tabID(of: browser) else { return }+ runtimes[id]?.audibleAt = clock.nowif let np = nowPlaying {if np.entries.contains(where: { $0.id == id }) {np.update(id) { $0.playing = audible }diff --git a/Sources/Cra/UI/Settings/TabsPane.swift b/Sources/Cra/UI/Settings/TabsPane.swiftindex 53307c4..a12d2f2 100644--- a/Sources/Cra/UI/Settings/TabsPane.swift+++ b/Sources/Cra/UI/Settings/TabsPane.swift@@ -51,6 +51,20 @@ struct TabsPane: View {.fixedSize().disabled(!store.settings.autoArchiveEnabled)}+ // Tab sleeping (GitHub #153): Arc's 4 hours and nothing more unless you ask.+ HStack(spacing: 6) {+ SettingsCheckbox(title: "Force tabs out of memory after:", isOn: $store.settings.tabSleepTimerEnabled)+ Picker("", selection: $store.settings.tabSleepAfter) {+ ForEach(TabSleepThreshold.allCases) { Text($0.label).tag($0) }+ }+ .labelsHidden()+ .fixedSize()+ .disabled(!store.settings.tabSleepTimerEnabled)+ }+ SettingsCheckbox(title: "Force tabs out of memory when the Mac is short of memory",+ isOn: $store.settings.tabSleepOnMemoryPressure)+ Text(tabSleepNote).font(.system(size: 11)).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)}}.sheet(isPresented: $showsAirTrafficControl) {@@ -60,6 +74,14 @@ struct TabsPane: View {@State private var showsAirTrafficControl = false+ /// Says what a forced-out tab costs, and which tabs stay, before the user finds out.+ private var tabSleepNote: String {+ let s = store.settings+ let note = "A tab forced out of memory reloads when you open it. Tabs playing sound, recording or holding text you typed stay."+ guard s.tabSleepTimerEnabled, TabSleepPolicy.timer(s.tabSleepAfter).keepsRecentTabs else { return note }+ return note + (s.tabSleepOnMemoryPressure ? " So do the 10 tabs you used last, unless the Mac is short of memory." : " So do the 10 tabs you used last.")+ }+private var routesSummary: String {switch store.settings.linkRoutes.count {case 0: return ""diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmindex 56e8e20..4a9d337 100644--- a/Sources/CraCEF/CraCEF.mm+++ b/Sources/CraCEF/CraCEF.mm@@ -642,7 +642,10 @@ public:// start leaves nothing to reset (it also covers such an extension installed later).std::string enabled = command_line->GetSwitchValue("enable-features");command_line->AppendSwitchWithValue("enable-features",- (enabled.empty() ? "" : enabled + ",") + "ForceWebRequestProxyForTest");+ (enabled.empty() ? "" : enabled + ",") + "ForceWebRequestProxyForTest,"+ // Tab sleeping discards a page in place (Cra.discard), as Arc's Chromium does: the tab+ // keeps its back/forward list and scroll position, and loads again when shown (#153).+ + "WebContentsDiscard");// Kerberos/NTLM single sign-on (ADFS /adfs/ls/wia and the like). Chromium only sends// the OS ticket to allowlisted hosts, and IT sets that list as a Chrome or Edge policy,// which CEF never reads. Without it those logins fail with ERR_INVALID_AUTH_CREDENTIALS.diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swiftindex a949cdf..26b577e 100644--- a/Tests/BrowserManagerLifecycleTests.swift+++ b/Tests/BrowserManagerLifecycleTests.swift@@ -87,6 +87,10 @@ enum BrowserManagerLifecycleTests {recentTabsCase()freezingVoteCase()await sleepClockCase()+ await pressureSweepCase()+ await discardCase()+ shortTimerCase()+ recentlyAudibleCase()devToolsCase()await beforeUnloadCase()nowPlayingCase()@@ -224,7 +228,7 @@ enum BrowserManagerLifecycleTests {let id = store.createTab(url: "https://example.test/sleep").idlet runtime = manager.ensureRuntime(for: id)!runtime.hiddenAt = Date.distantPast- manager.sleepIdleTabs(hiddenLongerThan: 60)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 60))expect(runtime.browser.replies.contains { $0.method == isolatedProbe }, "eligible page receives an asynchronous sleep probe")mutate(manager, runtime)runtime.browser.reply(to: isolatedProbe, with: reply)@@ -234,10 +238,33 @@ enum BrowserManagerLifecycleTests {runtime.browser.reply(to: "Runtime.evaluate", with: idleReply)await drainMainQueue()}- expect((manager.runtime(for: id) == nil) == shouldSleep, message)+ await finishSleep(runtime.browser)+ expect(asleep(manager, id) == shouldSleep, message)manager.closeAll()}+ private static let discardedReply = #"{"discarded":true,"processEnded":true}"#++ /// Answers the steps after the page's own probes: Chromium's freezing reasons, then the discard.+ @MainActor+ private static func finishSleep(_ browser: CraBrowser, reasons: String = #"{"reasons":[]}"#,+ discard: String? = discardedReply, discardError: String? = nil) async {+ if browser.replies.contains(where: { $0.method == "Cra.getFreezingState" }) {+ browser.reply(to: "Cra.getFreezingState", with: reasons)+ await drainMainQueue()+ }+ if browser.replies.contains(where: { $0.method == "Cra.discard" }) {+ if let discardError { browser.fail("Cra.discard", with: discardError) } else { browser.reply(to: "Cra.discard", with: discard) }+ await drainMainQueue()+ }+ }++ /// Discarded in place, or closed by a CEF that can't discard.+ @MainActor+ private static func asleep(_ manager: BrowserManager, _ id: UUID) -> Bool {+ manager.runtime(for: id).map(\.discarded) ?? true+ }+/// Like Arc, the 10 tabs used last keep their pages however long they have been hidden (#136).@MainActorprivate static func recentTabsCase() {@@ -247,7 +274,7 @@ enum BrowserManagerLifecycleTests {let runtimes = ids.map { manager.ensureRuntime(for: $0)! }manager.show(ids[12], focus: false)for (n, rt) in runtimes.dropLast().enumerated() { rt.hiddenAt = Date(timeIntervalSince1970: Double(n)) }- manager.sleepIdleTabs(hiddenLongerThan: 60)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 60))let probed = runtimes.map { $0.browser.replies.contains { $0.method == isolatedProbe } }expect(probed == [true, true, true] + Array(repeating: false, count: 10),"the visible tab and the 9 hidden most recently stay awake; only older pages are asked")@@ -286,13 +313,13 @@ enum BrowserManagerLifecycleTests {let id = store.createTab(url: "https://example.test/typed").idlet runtime = manager.ensureRuntime(for: id)!runtime.hiddenAt = Date.distantPast- manager.sleepIdleTabs(hiddenLongerThan: 60)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 60))runtime.browser.reply(to: isolatedProbe, with: #"{"result":{"type":"string","value":"typed"}}"#)await drainMainQueue()- manager.sleepIdleTabs(hiddenLongerThan: 60)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 60))expect(!runtime.browser.replies.contains { $0.method == isolatedProbe }, "a refused page is not probed again before the back-off")runtime.sleepProbeAfter = Date.distantPast- manager.sleepIdleTabs(hiddenLongerThan: 60)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 60))expect(runtime.browser.replies.contains { $0.method == isolatedProbe }, "a refused page is probed again after the back-off")manager.closeAll()}@@ -309,22 +336,138 @@ enum BrowserManagerLifecycleTests {let runtime = manager.ensureRuntime(for: id)!func probed() -> Bool { runtime.browser.replies.contains { $0.method == isolatedProbe } }clock.advance(by: 3599)- manager.sleepIdleTabs(hiddenLongerThan: 3600)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 3600))expect(!probed(), "a page hidden a second short of the threshold is not asked")clock.advance(by: 2)- manager.sleepIdleTabs(hiddenLongerThan: 3600)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 3600))expect(probed(), "a page hidden past the threshold is asked")runtime.browser.reply(to: isolatedProbe, with: #"{"result":{"type":"string","value":"typed"}}"#)await drainMainQueue()clock.advance(by: BrowserManager.refusalBackoff - 1)- manager.sleepIdleTabs(hiddenLongerThan: 3600)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 3600))expect(!probed(), "a refused page is not asked again inside the back-off")clock.advance(by: 1)- manager.sleepIdleTabs(hiddenLongerThan: 3600)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 3600))expect(probed(), "a refused page is asked again once the back-off ends")manager.closeAll()}+ /// Under memory pressure (#153) the 3 pages hidden longest are asked, the 10 tabs used last+ /// included; a page refusing inside its back-off doesn't take one of the 3, and a page left+ /// less than 5 minutes ago isn't asked.+ @MainActor+ private static func pressureSweepCase() async {+ let clock = ManualScheduler()+ let store = SidebarStore()+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView(), clock: clock)+ let ids = (0..<6).map { store.createTab(url: "https://example.test/pressure\($0)").id }+ let runtimes = ids.map { manager.ensureRuntime(for: $0)! }+ for (n, rt) in runtimes.enumerated() { rt.hiddenAt = clock.now.addingTimeInterval(-3600 + Double(n) * 60) }+ runtimes[5].hiddenAt = clock.now.addingTimeInterval(-4 * 60)+ runtimes[0].sleepProbeAfter = clock.now.addingTimeInterval(60)+ func probed() -> [Bool] { runtimes.map { rt in rt.browser.replies.contains { $0.method == isolatedProbe } } }+ manager.sleepIdleTabs(.memoryPressure)+ expect(probed() == [false, true, true, true, false, false],+ "the 3 pages hidden longest are asked, past a refusing page, none of the 10 used last kept")+ for rt in runtimes[1...3] {+ rt.browser.reply(to: isolatedProbe, with: idleReply)+ await drainMainQueue()+ rt.browser.reply(to: "Runtime.evaluate", with: idleReply)+ await drainMainQueue()+ await finishSleep(rt.browser)+ }+ expect(ids.map { asleep(manager, $0) } == [false, true, true, true, false, false], "the 3 pages are discarded")+ manager.sleepIdleTabs(.memoryPressure)+ expect(probed()[4] && !probed()[5], "the next sweep takes the next page, not one left 4 minutes ago")+ manager.closeAll()+ }++ /// Sleeping discards the page in place (#153): the runtime stays with Chromium's history and+ /// scroll position, showing the tab loads it now, and it holds none of the 10 recent places.+ /// A call with camera and microphone off, or a device, keeps the page awake; a CEF without+ /// Cra.discard closes the page as before.+ @MainActor+ private static func discardCase() async {+ let store = SidebarStore()+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())+ manager.protectedRecentTabs = 0+ func sleepOne(_ reasons: String = #"{"reasons":[]}"#, discard: String? = discardedReply, error: String? = nil) async -> (UUID, TabRuntime) {+ let id = store.createTab(url: "https://example.test/discard").id+ let rt = manager.ensureRuntime(for: id)!+ rt.hiddenAt = Date.distantPast+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 60))+ rt.browser.reply(to: isolatedProbe, with: idleReply)+ await drainMainQueue()+ rt.browser.reply(to: "Runtime.evaluate", with: idleReply)+ await drainMainQueue()+ await finishSleep(rt.browser, reasons: reasons, discard: discard, discardError: error)+ return (id, rt)+ }++ let (id, rt) = await sleepOne()+ expect(manager.runtime(for: id) === rt && rt.discarded && manager.sleptTabs.contains(id) && !rt.browser.closeRequested,+ "a discarded page keeps its runtime and browser")+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 60))+ expect(!rt.browser.replies.contains { $0.method == isolatedProbe }, "a discarded page isn't asked again")+ manager.show(id, focus: false)+ expect(!rt.discarded && !manager.sleptTabs.contains(id) && rt.browser.replies.contains { $0.method == "Cra.load" },+ "showing a discarded tab loads its page at once")++ let (call, callRT) = await sleepOne(#"{"reasons":["has an active WebRTC connection"],"connectedReasons":[]}"#)+ expect(!callRT.discarded && manager.runtime(for: call) === callRT && callRT.sleepRefusal == "call",+ "a page in a call with camera and microphone off stays awake")+ let (popup, popupRT) = await sleepOne(#"{"reasons":[],"connectedReasons":["connected to HID device"]}"#)+ expect(!popupRT.discarded && manager.runtime(for: popup) === popupRT && popupRT.sleepRefusal == "device",+ "a page whose connected page uses a device stays awake")+ let (old, _) = await sleepOne(error: "'Cra.discard' wasn't found")+ expect(manager.runtime(for: old) == nil && manager.sleptTabs.contains(old), "a CEF without Cra.discard closes the page as before")+ let (busy, busyRT) = await sleepOne(discard: #"{"discarded":false}"#)+ expect(!busyRT.discarded && manager.runtime(for: busy) === busyRT && busyRT.sleepRefusal == "navigating",+ "a page Chromium wouldn't discard is asked again later")+ manager.closeAll()+ }++ /// "Force tabs out of memory after:" below Arc's 4 hours closes the 10 tabs used last too;+ /// 4 hours and more keep them (#153).+ @MainActor+ private static func shortTimerCase() {+ let clock = ManualScheduler()+ let store = SidebarStore()+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView(), clock: clock)+ let id = store.createTab(url: "https://example.test/short").id+ let runtime = manager.ensureRuntime(for: id)!+ clock.advance(by: 9 * 3600)+ manager.sleepIdleTabs(.timer(.fourHours))+ manager.sleepIdleTabs(.timer(.eightHours))+ expect(!runtime.browser.replies.contains { $0.method == isolatedProbe }, "at 4 hours or more the tab used last stays")+ manager.sleepIdleTabs(.timer(.twoHours))+ expect(runtime.browser.replies.contains { $0.method == isolatedProbe }, "below 4 hours it is asked")+ manager.closeAll()+ }++ /// A page that played sound counts as in use: tab sleeping waits as long after it went quiet+ /// as after it went out of sight (#153).+ @MainActor+ private static func recentlyAudibleCase() {+ let clock = ManualScheduler()+ let store = SidebarStore()+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView(), clock: clock)+ manager.protectedRecentTabs = 0+ let id = store.createTab(url: "https://example.test/audible").id+ let runtime = manager.ensureRuntime(for: id)!+ clock.advance(by: 3600)+ manager.browser(runtime.browser, didChangeAudible: true)+ clock.advance(by: 120)+ manager.browser(runtime.browser, didChangeAudible: false)+ clock.advance(by: 14 * 60)+ manager.sleepIdleTabs(.timer(.fifteenMinutes))+ expect(!runtime.browser.replies.contains { $0.method == isolatedProbe }, "a page quiet for 14 minutes isn't asked at 15")+ clock.advance(by: 2 * 60)+ manager.sleepIdleTabs(.timer(.fifteenMinutes))+ expect(runtime.browser.replies.contains { $0.method == isolatedProbe }, "quiet for 16 minutes it is")+ manager.closeAll()+ }+/// ⌥⌘I pressed again while CEF is still closing DevTools opens them once they are gone,/// instead of closing them a second time. Console and Network switch panels on open DevTools.@MainActor@@ -365,7 +508,7 @@ enum BrowserManagerLifecycleTests {let id = store.createTab(url: "https://example.test/editor").idlet runtime = manager.ensureRuntime(for: id)!runtime.hiddenAt = Date.distantPast- manager.sleepIdleTabs(hiddenLongerThan: 60)+ manager.sleepIdleTabs(TabSleepPolicy(hiddenFor: 60))runtime.browser.reply(to: isolatedProbe, with: idleReply)await drainMainQueue()runtime.browser.reply(to: "Runtime.evaluate", with: #"{"result":{"type":"string","value":"beforeunload"}}"#)diff --git a/Tests/BrowserManagerSupport/CraCEF.swift b/Tests/BrowserManagerSupport/CraCEF.swiftindex 09d3eea..3ce18d6 100644--- a/Tests/BrowserManagerSupport/CraCEF.swift+++ b/Tests/BrowserManagerSupport/CraCEF.swift@@ -77,6 +77,11 @@ public final class CraBrowser {guard let index = replies.firstIndex(where: { $0.method == method }) else { fatalError("No pending \(method)") }replies.remove(at: index).completion(result, nil)}+ /// Answers with a protocol error, as CEF does for a method it doesn't have.+ public func fail(_ method: String, with error: String) {+ guard let index = replies.firstIndex(where: { $0.method == method }) else { fatalError("No pending \(method)") }+ replies.remove(at: index).completion(nil, error)+ }public func setLoading(_ loading: Bool) {isLoading = loadingdelegate?.browser(self, didChangeLoading: loading, canGoBack: false, canGoForward: false)diff --git a/Tests/test-browser-manager.sh b/Tests/test-browser-manager.shindex 8bfb49b..4b737d5 100755--- a/Tests/test-browser-manager.sh+++ b/Tests/test-browser-manager.sh@@ -11,7 +11,7 @@ xcrun swiftc -swift-version 5 -emit-module -emit-library -module-name CraCEF \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 \- Sources/Cra/Perf/Perf.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift Packages/CraCore/Sources/CraCore/PermissionPrompt.swift Tests/Support/ManualScheduler.swift Tests/BrowserManagerSupport/AppServices.swift \+ Sources/Cra/Perf/Perf.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift Packages/CraCore/Sources/CraCore/PermissionPrompt.swift Packages/CraCore/Sources/CraCore/TabSleepPolicy.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 7327bd1..8636f74 100644--- a/docs/development.md+++ b/docs/development.md@@ -101,7 +101,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>`, `stall=<ms>` (blocks the main+`snapshot=<ViewClass[,n]>&out=<png>`, `sleepTabs=<seconds>` (the 10 tabs used last too), `memoryPressure=warning|critical` (one+memory-pressure sweep at that level, if Settings ▸ Tabs has it on), `stall=<ms>` (blocks the mainthread), `perfReport=<path>` (the recorder's perf.json now), `systemAppearance=light|dark|system`(the appearance Auto space themes follow, without changing the Mac's), `themeEditor=1` (EditTheme Color… for the focused space), `relaunch=1` and `quit=1`.diff --git a/scripts/cef-patches/freezing-vote.patch b/scripts/cef-patches/freezing-vote.patchindex 14a2aae..a7ce008 100644--- a/scripts/cef-patches/freezing-vote.patch+++ b/scripts/cef-patches/freezing-vote.patch@@ -11,12 +11,15 @@ index dd0a558c0..a54f79de4 100644"//components/pref_registry","//components/printing/browser",diff --git a/cef/libcef/browser/devtools/devtools_controller.cc b/cef/libcef/browser/devtools/devtools_controller.cc-index c60f22d1a..0e4b547b7 100644+index c60f22d1a..d06000302 100644--- a/cef/libcef/browser/devtools/devtools_controller.cc+++ b/cef/libcef/browser/devtools/devtools_controller.cc-@@ -6,9 +6,108 @@+@@ -5,10 +5,149 @@+ #include "cef/libcef/browser/devtools/devtools_controller.h"#include "base/json/json_reader.h"++#include "base/feature_list.h"++#include "base/functional/callback_helpers.h"#include "base/json/json_writer.h"+#include "base/supports_user_data.h"+#include "base/task/sequenced_task_runner.h"@@ -26,7 +29,11 @@ index c60f22d1a..0e4b547b7 100644+#include "components/performance_manager/public/freezing/freezing.h"+#include "components/performance_manager/public/performance_manager.h"#include "content/public/browser/devtools_agent_host.h"++#include "content/public/browser/navigation_controller.h"++#include "content/public/browser/render_frame_host.h"++#include "content/public/browser/render_process_host.h"+#include "content/public/browser/web_contents.h"++#include "content/public/common/content_features.h"++namespace {+@@ -54,7 +61,13 @@ index c60f22d1a..0e4b547b7 100644+// {"id":N,"method":"Cra.setFreezingVote","params":{"vote":true|false}}: sets+// or drops the vote. {"id":N,"method":"Cra.getFreezingState"}: whether the+// page has Cra's vote, is frozen, and why the policy won't freeze it.-+// Returns true for either; any other message returns false.++// {"id":N,"method":"Cra.discard"}: discards the page in place, like Chrome's++// TabLifecycleUnit with WebContentsDiscard on: its renderer goes, the++// WebContents keeps its back/forward list and each entry's page state (scroll++// position, form contents), and showing it loads the page again.++// {"id":N,"method":"Cra.load"}: loads a discarded page now, as Chrome does++// when its tab is selected, even while the window is covered.++// Returns true for these; any other message returns false.+bool HandleCraMethod(content::WebContents* contents,+ std::string_view message,+ int* message_id,@@ -71,10 +84,38 @@ index c60f22d1a..0e4b547b7 100644+ const std::string* method = dict->FindString("method");+ std::optional<int> id = dict->FindInt("id");+ if (!method || !id ||-+ (*method != "Cra.setFreezingVote" && *method != "Cra.getFreezingState")) {++ (*method != "Cra.setFreezingVote" && *method != "Cra.getFreezingState" &&++ *method != "Cra.discard" && *method != "Cra.load")) {+ return false;+ }+ *message_id = *id;++ if (*method == "Cra.load") {++ // Does nothing unless the page was discarded and hasn't loaded since.++ contents->GetController().LoadIfNecessary();++ return true;++ }++ if (*method == "Cra.discard") {++ if (!base::FeatureList::IsEnabled(features::kWebContentsDiscard)) {++ *error = "discarding needs the WebContentsDiscard feature";++ return true;++ }++ if (!contents->WasDiscarded()) {++ // First try to end the renderer, if it holds only this page++ // (AttemptFastKillForDiscard).++ content::RenderFrameHost* main_frame = contents->GetPrimaryMainFrame();++ result->Set("processEnded",++ main_frame && main_frame->GetProcess()->FastShutdownIfPossible(++ 1u, /*skip_unload_handlers=*/false,++ /*ignore_workers=*/false,++ /*ignore_keep_alive=*/false,++ /*ignore_pending_reuse=*/false,++ /*use_outermost_main_frame_check=*/true));++ contents->Discard(base::DoNothing());++ }++ // False when a navigation was about to commit: Chromium keeps the page.++ result->Set("discarded", contents->WasDiscarded());++ return true;++ }+ if (*method == "Cra.getFreezingState") {+ result->Set("vote", !!contents->GetUserData(kCraFreezingVoteKey));+ const performance_manager::PageNode* page =@@ -123,7 +164,7 @@ index c60f22d1a..0e4b547b7 100644CefDevToolsController::CefDevToolsController(content::WebContents* inspected_contents)-@@ -30,6 +129,36 @@ CefDevToolsController::~CefDevToolsController() {+@@ -30,6 +169,36 @@ CefDevToolsController::~CefDevToolsController() {bool CefDevToolsController::SendDevToolsMessage(const std::string_view& message) {CEF_REQUIRE_UIT();diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.shindex b5a8a7e..b0f5620 100755--- a/scripts/fetch-cef.sh+++ b/scripts/fetch-cef.sh@@ -13,7 +13,7 @@ CEF_VERSION="${CEF_VERSION:-156.0.15+gcf671c0+chromium-156.0.8078.80}"ARCH="${CEF_ARCH:-macosarm64}"NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.-CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs10}"+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs11}"URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"mkdir -p vendor