Skip to content

armgit / cra

Public Imported from GitHub
0

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 tab's first seconds, and tab freezing and sleeping like Arc (#136) (#143)

Victor Kildahlf9b65e6ff0cf
diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift
index b92db6b..8c74150 100644
--- a/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift
+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfInsights.swift
@@ -21,7 +21,9 @@ public struct PerfInsight: Codable, Equatable, Sendable, Identifiable {
/// a test all agree.
public enum PerfInsights {
public static let lowDiskBytes: Int64 = 5 << 30
- public static let largeFootprintBytes: Int64 = 8 << 30
+ /// A 16 GB Mac is short of memory well before 8 GB (#136): nine live pages, four of them
+ /// YouTube, came to 4.2 GB there.
+ public static let largeFootprintBytes: Int64 = 4 << 30
/// Short stalls per hour of the session that are worth a line.
public static let frequentStallsPerHour = 30.0
/// What recording may cost, in percent of one core (docs/performance.md).
@@ -96,7 +98,7 @@ public enum PerfInsights {
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."))
+ 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."))
}
return out
}
diff --git a/Packages/CraCore/Sources/CraCore/Perf/PerfMetric.swift b/Packages/CraCore/Sources/CraCore/Perf/PerfMetric.swift
index 81351fa..991b37e 100644
--- a/Packages/CraCore/Sources/CraCore/Perf/PerfMetric.swift
+++ b/Packages/CraCore/Sources/CraCore/Perf/PerfMetric.swift
@@ -3,7 +3,8 @@ 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 {
- /// Putting other tabs on screen (BrowserManager.show), the part on the main thread.
+ /// Putting other tabs on screen (BrowserManager.show), the part on the main thread, without
+ /// making a page for a tab that had none (that is `pageCreate`).
case tabSwitch
/// Making a tab's page: Chromium's view, its window and the browser object.
case pageCreate
@@ -17,6 +18,8 @@ public enum PerfMetric: String, Codable, CaseIterable, Sendable {
case jsonSave
/// Long tasks (50 ms or more) in the visible tab's page.
case longTask
+ /// Framing an extension's popup once Chrome shows it (ExtensionPopupWindow.present).
+ case extensionPopup
}
/// What the recorder counts. Some carry a key (`loadError` the error code, `sleepRefusal` the
diff --git a/Packages/CraCore/Sources/CraCore/SidebarModel.swift b/Packages/CraCore/Sources/CraCore/SidebarModel.swift
index cc12083..08db282 100644
--- a/Packages/CraCore/Sources/CraCore/SidebarModel.swift
+++ b/Packages/CraCore/Sources/CraCore/SidebarModel.swift
@@ -348,27 +348,6 @@ public enum AutoArchiveThreshold: String, Codable, CaseIterable, Identifiable {
}
}
-public enum TabSleepThreshold: String, Codable, CaseIterable, Identifiable {
- case fifteenMinutes, oneHour, fourHours, twelveHours
- public var id: String { rawValue }
- public var seconds: TimeInterval {
- switch self {
- case .fifteenMinutes: return 15 * 60
- case .oneHour: return 3600
- case .fourHours: return 4 * 3600
- case .twelveHours: return 12 * 3600
- }
- }
- public var label: String {
- switch self {
- case .fifteenMinutes: return "15 minutes"
- case .oneHour: return "1 hour"
- case .fourHours: return "4 hours"
- case .twelveHours: return "12 hours"
- }
- }
-}
-
public enum SearchEngine: String, Codable, CaseIterable, Identifiable {
case google, duckduckgo, bing, kagi
public var id: String { rawValue }
@@ -460,10 +439,6 @@ 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 ▸ "Sleep tabs I haven't looked at in:": a page hidden that long closes and
- /// loads again when shown (BrowserManager.sleepIdleTabs). Off by default.
- public var tabSleepEnabled: Bool = false
- public var tabSleep: TabSleepThreshold = .oneHour
/// 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
@@ -629,8 +604,6 @@ extension AppSettings {
hapticFeedbackOnReorder = try c.decodeIfPresent(Bool.self, forKey: .hapticFeedbackOnReorder) ?? true
warnBeforeQuitting = try c.decodeIfPresent(Bool.self, forKey: .warnBeforeQuitting) ?? false
autoArchiveEnabled = try c.decodeIfPresent(Bool.self, forKey: .autoArchiveEnabled) ?? true
- tabSleepEnabled = try c.decodeIfPresent(Bool.self, forKey: .tabSleepEnabled) ?? false
- tabSleep = (try? c.decodeIfPresent(TabSleepThreshold.self, forKey: .tabSleep)) ?? .oneHour
httpsOnly = try c.decodeIfPresent(Bool.self, forKey: .httpsOnly) ?? false
searchSuggestions = try c.decodeIfPresent(Bool.self, forKey: .searchSuggestions) ?? true
showSpaceHeaderOnSingleSpace = try c.decodeIfPresent(Bool.self, forKey: .showSpaceHeaderOnSingleSpace) ?? 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.json
index 8179269..ea73102 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,8 +33,6 @@
"showSpaceHeaderOnSingleSpace" : true,
"showStatusBar" : true,
"showToolbar" : false,
- "tabSleep" : "oneHour",
- "tabSleepEnabled" : false,
"toolbarDefaultMigrated" : true,
"toolbarShowsFullURL" : false,
"warnBeforeQuitting" : false
diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json
index 54d27c3..79c8d16 100644
--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json
+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-empty.json
@@ -42,8 +42,6 @@
"showSpaceHeaderOnSingleSpace" : true,
"showStatusBar" : true,
"showToolbar" : true,
- "tabSleep" : "oneHour",
- "tabSleepEnabled" : false,
"toolbarDefaultMigrated" : true,
"toolbarShowsFullURL" : false,
"warnBeforeQuitting" : false
diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json
index 4cb3b5e..612284f 100644
--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json
+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings-legacy.json
@@ -42,8 +42,6 @@
"showSpaceHeaderOnSingleSpace" : true,
"showStatusBar" : true,
"showToolbar" : true,
- "tabSleep" : "oneHour",
- "tabSleepEnabled" : false,
"toolbarDefaultMigrated" : true,
"toolbarShowsFullURL" : false,
"warnBeforeQuitting" : false
diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json
index b6b9b66..bdb8d18 100644
--- a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json
+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/settings.json
@@ -52,8 +52,6 @@
"showSpaceHeaderOnSingleSpace" : false,
"showStatusBar" : false,
"showToolbar" : true,
- "tabSleep" : "fourHours",
- "tabSleepEnabled" : true,
"toolbarDefaultMigrated" : true,
"toolbarShowsFullURL" : false,
"warnBeforeQuitting" : true
diff --git a/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift b/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift
index be5a26b..4fbf7ff 100644
--- a/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift
+++ b/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift
@@ -137,7 +137,6 @@ struct ModelFixtureTests {
"Links from other apps → Little Window off becomes the most recent space")
#expect(legacy.linkRoutes.map(\.text) == ["meet.google.com"], "settings from before Air Traffic Control get Arc's Meet route")
#expect(legacy.newTabButtonAtTop, "the New Tab row goes back above Today once")
- #expect(legacy.tabSleep == .oneHour, "a sleep threshold this version doesn't know falls back")
#expect(legacy.showToolbar, "Arc's toolbar preference wins over the 0.1.0 value")
let bad = try Self.loadSettings("settings-bad-routes.json").loaded
diff --git a/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swift b/Packages/CraCore/Tests/CraCoreTests/PerfStateTests.swift
index cd16ab3..fcb9c77 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("Tab sleeping (Settings ▸ Tabs)"))
+ #expect(r.insights[12].detail.contains("4 hours"))
}
@Test func aFewStallsInALongSessionAreNotFrequent() {
diff --git a/Packages/CraCore/Tests/CraCoreTests/SidebarModelTests.swift b/Packages/CraCore/Tests/CraCoreTests/SidebarModelTests.swift
index e84a87a..2307320 100644
--- a/Packages/CraCore/Tests/CraCoreTests/SidebarModelTests.swift
+++ b/Packages/CraCore/Tests/CraCoreTests/SidebarModelTests.swift
@@ -89,9 +89,6 @@ struct SidebarModelTests {
#expect(AutoArchiveThreshold.allCases.map(\.seconds) == [43_200, 86_400, 604_800, 2_592_000])
#expect(AutoArchiveThreshold.allCases.map(\.label) == ["12 hours", "24 hours", "7 days", "30 days"])
#expect(AutoArchiveThreshold.allCases.map(\.id) == AutoArchiveThreshold.allCases.map(\.rawValue))
- #expect(TabSleepThreshold.allCases.map(\.seconds) == [900, 3600, 14_400, 43_200])
- #expect(TabSleepThreshold.allCases.map(\.label) == ["15 minutes", "1 hour", "4 hours", "12 hours"])
- #expect(TabSleepThreshold.allCases.map(\.id) == TabSleepThreshold.allCases.map(\.rawValue))
}
@Test(arguments: [
diff --git a/Sources/Cra/App/AppComposition.swift b/Sources/Cra/App/AppComposition.swift
index 1db8240..fdf5a35 100644
--- a/Sources/Cra/App/AppComposition.swift
+++ b/Sources/Cra/App/AppComposition.swift
@@ -17,20 +17,22 @@ final class AppComposition {
store = SidebarStore(clock: self.clock)
}
- /// Arc archives on a 30-minute pass; tab sleeping looks every minute. `sleepTabs` reaches
+ /// Arc archives on a 30-minute pass; tab freezing and sleeping look every minute. `sleepTabs` reaches
/// the windows' browser managers, which the composition does not own.
static let autoArchiveInterval: TimeInterval = 1800
static 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 * 60
func startPeriodicWork(sleepTabs: @escaping @MainActor () -> Void) {
periodic.forEach { $0.cancel() }
store.runAutoArchive()
periodic = [
clock.every(Self.autoArchiveInterval) { [weak self] in self?.store.runAutoArchive() },
- clock.every(Self.tabSleepInterval) { [weak self] in
- guard let self, self.store.settings.tabSleepEnabled else { return }
- sleepTabs()
- },
+ clock.every(Self.tabSleepInterval) { sleepTabs() },
]
}
}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 691521b..3088586 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -174,8 +174,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
if problems.count > 20 { CraLog.fault("sidebar: \(problems.count - 20) more problems") }
}
+ /// AppComposition.tabFreezeAfter; `cra://debug?freezeTabs=` shortens it for a test.
+ private var freezeAfter = AppComposition.tabFreezeAfter
+
private func sleepIdleTabs() {
- for w in mainWindows { w.browsers.sleepIdleTabs(hiddenLongerThan: store.settings.tabSleep.seconds) }
+ for w in mainWindows {
+ w.browsers.freezeIdleTabs(hiddenLongerThan: freezeAfter)
+ w.browsers.sleepIdleTabs(hiddenLongerThan: AppComposition.tabSleepAfter)
+ }
}
/// Settings > Privacy > "Always use secure connections", live like content blocking.
@@ -589,6 +595,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
if dict["relaunch"] != nil { relaunch(); return }
if dict["quit"] != nil { NSApp.terminate(nil); return }
if let t = dict["selectTab"].flatMap(UUID.init(uuidString:)) { store.selectTab(t, window: main.windowID); return }
+ // Tab freezing with a short threshold (seconds) from now on, so it can be tried without
+ // waiting: the minute's pass would otherwise take the votes back.
+ if let s = dict["freezeTabs"].flatMap(Double.init) {
+ freezeAfter = s
+ 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.
if let s = dict["sleepTabs"].flatMap(Double.init) {
for w in mainWindows { w.browsers.sleepIdleTabs(hiddenLongerThan: s) }
@@ -638,8 +651,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
return
}
if let method = dict["cdp"] {
- // target=little: the newest Little Window's (or Peek's) page.
- let b = dict["target"] == "little" ? littleWindows.last?.browser : main.currentBrowser
+ // target=little: the newest Little Window's (or Peek's) page; tab=<id>: that tab's page.
+ let tab = dict["tab"].flatMap(UUID.init(uuidString:)).flatMap { main.browsers.runtime(for: $0)?.browser }
+ let b = dict["target"] == "little" ? littleWindows.last?.browser : tab ?? main.currentBrowser
b?.sendDevToolsMethod(method, params: dict["params"] ?? "{}") { result, error in
NSLog("Cra cdp %@ → %@", method, result ?? "error: \(error ?? "?")")
}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index 8cc3cc2..5a9a8f5 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -18,6 +18,10 @@ final class TabRuntime {
/// The tab switcher's thumbnail, taken while the page was last on screen.
var snapshot: NSImage?
var snapshotWork: DispatchWorkItem?
+ /// The page probe for this time on screen, until it has run (BrowserManager.scheduleProbe).
+ var probeWork: DispatchWorkItem?
+ /// Cra votes to freeze the page (BrowserManager.freezeIdleTabs); Chromium decides.
+ var freezeVoted = false
/// When the page last went off screen (nil while shown); tab sleeping counts from here.
var hiddenAt: Date?
/// Invalidates a pending sleep probe even when navigation returns to the same URL.
@@ -188,6 +192,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
byBrowser[ObjectIdentifier(rt.browser)] = nil
rt.snapshotWork?.cancel()
rt.snapshotWork = nil
+ rt.probeWork?.cancel()
+ rt.probeWork = nil
if rt.browser.hasDevTools { rt.browser.closeDevTools() }
devToolsViews[tabID] = nil
devToolsPlaceholders[tabID] = nil
@@ -222,8 +228,12 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
let wasVisible = Set(visibleTabIDs)
var shown: [UUID] = []
+ // A tab without a page gets one here, timed as pageCreate: tabSwitch leaves it out (#136).
+ var creating = 0.0
for id in tabIDs {
+ let made = runtimes[id] == nil ? Perf.now() : nil
guard let rt = ensureRuntime(for: id) else { shown.append(id); continue }
+ if let made { creating += Perf.ms(since: made) }
if !wasVisible.contains(id) {
returnToTab(rt)
// A page can change its colours while hidden. One still loading reports them as it
@@ -232,6 +242,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
rt.hiddenAt = nil
rt.sleepProbeAfter = nil
+ if rt.freezeVoted { setFreezingVote(rt, false) }
let v = rt.browser.containerView
// Alloy hosting only: the Chromium view moves into its pane. Chrome-style
// pages live in their own windows; re-parenting their view makes Chrome
@@ -263,15 +274,18 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
if focus, let f = visibleTabID, let rt = runtimes[f] { rt.browser.setFocused(true) }
for id in shown where !wasVisible.contains(id) {
- scheduleSnapshot(id)
if let rt = runtimes[id] {
+ // A loading page gets its thumbnail once it has loaded: a capture now would be of
+ // a half-painted page, in the busiest second of its load (#136).
+ if !rt.browser.isLoading { scheduleSnapshot(id) }
log(id, "shown: \(site(rt.browser.currentURL, id, rt.browser))\(rt.browser.isLoading ? ", loading" : "")\(rt.browser.isCreated ? "" : ", page not created yet")")
- scheduleProbe(id, rt)
+ // A loading page is probed once it has loaded (didChangeLoading), or says it never did.
+ scheduleProbe(id, rt, after: rt.browser.isLoading ? 12 : 3)
}
}
syncDevToolsVisibility()
delegate?.browserManagerPageWindowsChanged(focus: focus)
- if wasVisible != Set(shown) { Perf.time(.tabSwitch, ms: Perf.ms(since: started)) }
+ if wasVisible != Set(shown) { Perf.time(.tabSwitch, ms: Perf.ms(since: started) - creating) }
}
// MARK: Diagnostics
@@ -284,18 +298,22 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
browser?.isIncognito ?? store.isIncognito(item: id) ? "(incognito)" : CraLog.host(url)
}
- /// A moment after a tab comes on screen, the log gets what its page holds and where Cra put
- /// it: for the tab that "shows a white page until reloaded", the line that says why.
- private func scheduleProbe(_ id: UUID, _ rt: TabRuntime, attempt: Int = 1) {
- DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self, weak rt] in
- guard let self, let rt, self.runtimes[id] === rt, self.visibleTabIDs.contains(id) else { return }
- // A slow site: look again once it has had time, and say so if it never finishes.
- if rt.browser.isLoading, attempt < 4 { return self.scheduleProbe(id, rt, attempt: attempt + 1) }
+ /// A moment after a tab comes on screen and its page has loaded, the log gets what the page
+ /// holds and where Cra put it: for the tab that "shows a white page until reloaded", the line
+ /// that says why. Not sooner: the probe runs in the page, which is busiest while it loads (#136).
+ private func scheduleProbe(_ id: UUID, _ rt: TabRuntime, after delay: TimeInterval) {
+ rt.probeWork?.cancel()
+ let work = DispatchWorkItem { [weak self, weak rt] in
+ guard let self, let rt, self.runtimes[id] === rt else { return }
+ rt.probeWork = nil
+ guard self.visibleTabIDs.contains(id) else { return }
PageProbe.run(rt.browser) { [weak self] probe in
guard let self, self.runtimes[id] === rt else { return }
self.log(id, "page \(self.site(rt.browser.currentURL, id, rt.browser))\(rt.browser.isLoading ? " still loading" : ""): \(probe) \(PageProbe.viewState(rt))")
}
}
+ rt.probeWork = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work)
}
// MARK: Tab switcher thumbnails
@@ -369,15 +387,16 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
// MARK: Tab sleeping
- /// Settings ▸ Tabs ▸ "Sleep tabs I haven't looked at in": a page off screen that long
- /// closes, like a closed pinned tab, and loads its URL again when shown. Pages that are
+ /// 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) {
let now = clock.now
let cutoff = now.addingTimeInterval(-seconds)
- for (id, rt) in runtimes {
+ let recent = recentlyShown
+ for (id, rt) in runtimes where !recent.contains(id) {
let b = rt.browser
guard canSleep(rt, before: cutoff), rt.sleepProbeAfter.map({ $0 <= now }) ?? true else { continue }
let url = b.currentURL
@@ -421,6 +440,46 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
static let refusalBackoff: TimeInterval = 10 * 60
+ /// Arc's WebContentLifecycleOptimization freezes a page out of sight for `timeToFreezeTab`
+ /// (30 minutes), unless it is one of the 10 tabs used last or has a media player open, by
+ /// voting for it in Chromium's freezing policy (its freeze token). The policy freezes it only
+ /// while nothing it knows forbids that: sound now or lately, capture, a Web Lock or IndexedDB
+ /// lock, a device, a WebRTC connection, notification permission. Showing the tab drops the
+ /// vote. Needs the CEF patch behind "Cra.setFreezingVote" (cef-patches/freezing-vote.patch);
+ /// an older CEF answers that the method doesn't exist and nothing freezes (GitHub #136).
+ func freezeIdleTabs(hiddenLongerThan seconds: TimeInterval) {
+ let cutoff = clock.now.addingTimeInterval(-seconds)
+ let recent = recentlyShown
+ for (id, rt) in runtimes {
+ let b = rt.browser
+ let vote = !recent.contains(id) && rt.hiddenAt.map { $0 < cutoff } == true && b.isCreated && !b.isClosed
+ && !(nowPlaying?.entries.contains { $0.id == id } ?? false)
+ if vote != rt.freezeVoted { setFreezingVote(rt, vote) }
+ }
+ }
+
+ private func setFreezingVote(_ rt: TabRuntime, _ vote: Bool) {
+ rt.freezeVoted = vote
+ log(rt.tabID, vote ? "votes to freeze its page" : "drops its freezing vote")
+ rt.browser.sendDevToolsMethod("Cra.setFreezingVote", params: vote ? #"{"vote":true}"# : #"{"vote":false}"#) { _, error in
+ guard let error, vote, !Self.loggedFreezingError else { return }
+ Self.loggedFreezingError = true
+ DispatchQueue.main.async { CraLog.note("tab freezing unavailable: \(error)") }
+ }
+ }
+
+ 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
+
+ /// 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))
+ }
+
private func canSleep(_ rt: TabRuntime, before cutoff: Date) -> Bool {
let b = rt.browser
return rt.hiddenAt.map { $0 < cutoff } == true && !visibleTabIDs.contains(rt.tabID)
@@ -763,13 +822,18 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
Perf.end(.tabWake, id.uuidString)
}
if !loading { runtimes[id]?.progress = 0 }
- if !loading { scheduleSnapshot(id) }
+ // Two seconds on, the page (a video player especially) has settled before it is captured.
+ if !loading { scheduleSnapshot(id, after: 2) }
+ if !loading, let rt = runtimes[id], rt.probeWork != nil { scheduleProbe(id, rt, after: 3) }
+ if !loading, id == visibleTabID { Perf.phase("firstPageLoaded") }
delegate?.browserManagerDidUpdate(id)
}
/// The window's loading bar pulses until the page commits, then sweeps (LoadingIndicator).
func browser(_ browser: CraBrowser, didChangeCommittedLoad committed: Bool) {
guard let id = tabID(of: browser) else { return }
+ // Start-up phases: firstPageShown, then the page's navigation committed, then loaded.
+ if committed, id == visibleTabID { Perf.phase("firstPageCommitted") }
delegate?.browserManagerDidUpdate(id)
}
@@ -791,8 +855,12 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
/// A restored tab's extension page, asked for before --load-extension loaded the extension,
/// loads again once it is up (ExtensionPageRetry).
func browser(_ browser: CraBrowser, didFailLoadingURL url: String, errorCode: Int) {
- guard let id = tabID(of: browser), let rt = runtimes[id], !browser.isIncognito else { return }
+ guard let id = tabID(of: browser), let rt = runtimes[id] else { return }
let profile = store.profileDirectoryName(item: id)
+ // Which extension the request went through, if any: a slow or failed first page is then a
+ // network wait or a proxy that is down, told apart from a render (#136).
+ log(id, "\(site(url, id, browser)) failed to load: net error \(errorCode), proxy \(ExtensionStore.shared.proxyLine(inProfile: profile))")
+ guard !browser.isIncognito else { return }
guard let wait = ExtensionPageRetry.delay(url: url, errorCode: errorCode, attempt: rt.extensionPageRetries, isOn: { ext in
ExtensionStore.shared.entries(inProfile: profile).contains { $0.extensionID == ext }
}) else { return }
diff --git a/Sources/Cra/Services/ExtensionActions.swift b/Sources/Cra/Services/ExtensionActions.swift
index cff20a4..a1ce0cd 100644
--- a/Sources/Cra/Services/ExtensionActions.swift
+++ b/Sources/Cra/Services/ExtensionActions.swift
@@ -126,7 +126,7 @@ final class ExtensionActions {
if !unsized || popup.alphaValue > 0 || Date().timeIntervalSince(since) > 0.25 {
HitchMonitor.mark("extension present window=\(popup.windowNumber) frame=\(NSStringFromRect(popup.frame)) parent=\(popup.parent?.windowNumber ?? -1)")
placingOwnPopup = false
- ExtensionPopupWindow.present(popup, anchor: anchor)
+ Perf.time(.extensionPopup) { ExtensionPopupWindow.present(popup, anchor: anchor) }
revealHiddenBubbles()
return
}
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swift
index ef0ba36..980e155 100644
--- a/Sources/Cra/Services/ExtensionStore.swift
+++ b/Sources/Cra/Services/ExtensionStore.swift
@@ -194,6 +194,9 @@ final class ExtensionStore {
proxyControllers = next
}
+ /// The line for one profile folder, as a page's failed load in cra.log names it.
+ func proxyLine(inProfile name: String) -> String { Self.proxyLine(proxyControllers[name] ?? []) }
+
/// "set by <id> (<config>), overriding <id>, <id>", or "not set by an extension".
static func proxyLine(_ controllers: [ExtensionProxyControl.Controller]) -> String {
guard let first = controllers.first else { return "not set by an extension" }
diff --git a/Sources/Cra/Services/PageProbe.swift b/Sources/Cra/Services/PageProbe.swift
index 43493ac..923145d 100644
--- a/Sources/Cra/Services/PageProbe.swift
+++ b/Sources/Cra/Services/PageProbe.swift
@@ -7,7 +7,9 @@ import CraCEF
///
/// `frameRate` counts animation frames for half a second. A visible page gets one per display
/// refresh; 0 means Chromium's compositor never asked it to draw. Frames without `painted`
-/// mean they were drawn but never reached the screen (#80).
+/// mean they were drawn but never reached the screen (#80). `children` tells a page with
+/// content from an empty body without reading its text, a walk of the whole page (#136), and
+/// `video` is the first video's dropped/total frames so far (getVideoPlaybackQuality).
@MainActor
enum PageProbe {
private static let script = """
@@ -20,7 +22,8 @@ enum PageProbe {
viewport: innerWidth + 'x' + innerHeight + '@' + devicePixelRatio,
scrollHeight: document.documentElement ? document.documentElement.scrollHeight : 0,
elements: document.getElementsByTagName('*').length,
- text: document.body ? document.body.textContent.length : -1,
+ children: document.body ? document.body.childElementCount : -1,
+ video: (q => q ? q.droppedVideoFrames + '/' + q.totalVideoFrames : 'none')(document.querySelector('video')?.getVideoPlaybackQuality()),
painted: performance.getEntriesByName('first-contentful-paint').length > 0,
frameRate: frames * 2})); }, 500);
})
@@ -47,7 +50,7 @@ enum PageProbe {
finish("probe failed: \(error ?? "no result")")
return
}
- finish(["blank", "ready", "visibility", "viewport", "scrollHeight", "elements", "text", "painted", "frameRate"]
+ finish(["blank", "ready", "visibility", "viewport", "scrollHeight", "elements", "children", "painted", "frameRate", "video"]
.map { "\($0)=\(fields[$0].map { "\($0)" } ?? "?")" }.joined(separator: " "))
}
}
diff --git a/Sources/Cra/UI/Settings/TabsPane.swift b/Sources/Cra/UI/Settings/TabsPane.swift
index 7ca0c5a..53307c4 100644
--- a/Sources/Cra/UI/Settings/TabsPane.swift
+++ b/Sources/Cra/UI/Settings/TabsPane.swift
@@ -51,18 +51,6 @@ struct TabsPane: View {
.fixedSize()
.disabled(!store.settings.autoArchiveEnabled)
}
- HStack(spacing: 6) {
- SettingsCheckbox(title: "Sleep tabs I haven’t looked at in:", isOn: $store.settings.tabSleepEnabled)
- Picker("", selection: $store.settings.tabSleep) {
- ForEach(TabSleepThreshold.allCases) { Text($0.label).tag($0) }
- }
- .labelsHidden()
- .fixedSize()
- .disabled(!store.settings.tabSleepEnabled)
- }
- Text("Sleeping tabs free their memory and reload when you open them. Tabs playing sound or holding something you typed stay awake.")
- .font(.system(size: 11)).foregroundStyle(.secondary)
- .fixedSize(horizontal: false, vertical: true)
}
}
.sheet(isPresented: $showsAirTrafficControl) {
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index affc280..261c872 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -112,8 +112,9 @@ final class ShellView: NSView {
var showToolbar = true { didSet { needsLayout = true } }
var hasTab = false { didSet { needsLayout = true } }
var onEdgeHover: ((Bool) -> Void)?
+ /// Set again each time the window becomes key; only a change rebuilds the backdrop.
var windowActive = true {
- didSet { refreshLift() }
+ didSet { if windowActive != oldValue { refreshLift() } }
}
/// Dark vibrant themes keep the earlier calibration (underWindowBackground + 15% lift).
diff --git a/Sources/Cra/UI/Windows/FloatingSidebar.swift b/Sources/Cra/UI/Windows/FloatingSidebar.swift
index 9f3a4d7..4382279 100644
--- a/Sources/Cra/UI/Windows/FloatingSidebar.swift
+++ b/Sources/Cra/UI/Windows/FloatingSidebar.swift
@@ -48,21 +48,43 @@ final class FloatingSidebarController {
deinit {
poll?.invalidate()
+ activation.forEach(NotificationCenter.default.removeObserver)
}
private var poll: Timer?
+ private var activation: [NSObjectProtocol] = []
/// No window of ours reliably receives mouse-moved events here: the key window
/// is usually a Chromium page window, and the shell's tracking areas only run in
- /// the key window. So the pointer is sampled on a timer while the app is active.
+ /// the key window. So the pointer is sampled on a timer while the app is active,
+ /// and the timer stops while it is not: at 30 Hz it was most of the run loop's
+ /// wake-ups in a Cra left in the background (#136).
func install() {
- guard poll == nil else { return }
+ guard activation.isEmpty else { return }
+ let center = NotificationCenter.default
+ activation = [(NSApplication.didBecomeActiveNotification, true), (NSApplication.didResignActiveNotification, false)].map { name, on in
+ center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in
+ MainActor.assumeIsolated { self?.setPolling(on) }
+ }
+ }
+ setPolling(NSApp.isActive)
+ }
+
+ private func setPolling(_ on: Bool) {
+ guard on != (poll != nil) else { return }
+ poll?.invalidate()
+ poll = nil
+ guard on else { return }
+ // Fired on the main run loop, so no hop to the main actor: one wake-up per tick, not two.
poll = Timer.scheduledTimer(withTimeInterval: 1.0 / 30, repeats: true) { [weak self] _ in
- Task { @MainActor in self?.pointerMoved() }
+ MainActor.assumeIsolated { self?.pointerMoved() }
}
poll?.tolerance = 0.01
}
+ /// Whether the pointer is being sampled (the tests check it follows the app's activation).
+ var isPolling: Bool { poll != nil }
+
private func pointerMoved() {
guard NSApp.isActive, !shell.contentFullscreen, window.isVisible else { return }
guard isShown || sidebarHidden() else { return }
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index aaacca9..cef17a8 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -2557,8 +2557,23 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
browsers.windowVisibilityChanged(covered: true)
}
- private static var screenIsLocked: Bool {
- (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool ?? false
+ /// Asked once, then kept by the system's lock and unlock notifications: the session query is a
+ /// WindowServer round trip, and every occlusion change of a fullscreen window asked it (#136).
+ private static let screenLock = ScreenLockState()
+ private static var screenIsLocked: Bool { screenLock.isLocked }
+
+ @MainActor private final class ScreenLockState {
+ private(set) var isLocked = (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool ?? false
+ private var observers: [NSObjectProtocol] = []
+
+ init() {
+ let center = DistributedNotificationCenter.default()
+ observers = [("com.apple.screenIsLocked", true), ("com.apple.screenIsUnlocked", false)].map { name, locked in
+ center.addObserver(forName: Notification.Name(name), object: nil, queue: .main) { [weak self] _ in
+ MainActor.assumeIsolated { self?.isLocked = locked }
+ }
+ }
+ }
}
/// The frame lives in the store's observed prefs, which every sidebar row reads (selection):
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index df258d9..a949cdf 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -61,6 +61,7 @@ enum BrowserManagerLifecycleTests {
embeddedPageHandoffCase()
await snapshotCase()
+ loadingTabCase()
await sleepCase("an unchanged idle page sleeps", shouldSleep: true) { _, _ in }
await sleepCase("loading started while the probe was pending stays awake") { _, rt in rt.browser.setLoading(true) }
await sleepCase("a completed same-URL reload invalidates the old probe") { _, rt in
@@ -83,6 +84,8 @@ enum BrowserManagerLifecycleTests {
await sleepCase("an exception reply cannot authorize sleeping", reply: #"{"exceptionDetails":{},"result":{"value":""}}"#) { _, _ in }
await sleepCase("a page holding typed text stays awake", reply: #"{"result":{"type":"string","value":"typed"}}"#) { _, _ in }
await refusalBackoffCase()
+ recentTabsCase()
+ freezingVoteCase()
await sleepClockCase()
devToolsCase()
await beforeUnloadCase()
@@ -114,7 +117,7 @@ enum BrowserManagerLifecycleTests {
let reply = try! JSONSerialization.data(withJSONObject: ["result": ["type": "string", "value": page]])
runtime.browser.reply(to: "Runtime.evaluate", with: String(decoding: reply, as: UTF8.self))
await drainMainQueue()
- expect(line?.hasSuffix("visibility=visible viewport=? scrollHeight=? elements=? text=? painted=0 frameRate=0") == true,
+ expect(line?.hasSuffix("visibility=visible viewport=? scrollHeight=? elements=? children=? painted=0 frameRate=0 video=?") == true,
"a visible page that was never asked to draw reads frameRate=0")
// Off every screen, as in a headless run: the window follows no display.
@@ -192,11 +195,32 @@ enum BrowserManagerLifecycleTests {
manager.closeAll()
}
+ /// A tab shown while its page loads is neither captured nor probed until the load is over
+ /// (#136): both ask the renderer for work in the busiest second of the page.
+ @MainActor
+ private static func loadingTabCase() {
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ let id = store.createTab(url: "https://example.test/loading").id
+ let rt = manager.ensureRuntime(for: id)!
+ rt.browser.isLoading = true
+ manager.show(id, focus: false)
+ let probe = rt.probeWork
+ expect(rt.snapshotWork == nil && probe != nil, "a page shown while loading gets no thumbnail yet, and a pending probe")
+ rt.browser.setLoading(false)
+ expect(rt.snapshotWork != nil, "its thumbnail is taken once it has loaded")
+ expect(probe?.isCancelled == true && rt.probeWork != nil && rt.probeWork !== probe, "its probe moves to after the load")
+ manager.unload(id)
+ expect(rt.probeWork == nil && rt.snapshotWork == nil, "unloading drops the pending probe")
+ manager.closeAll()
+ }
+
@MainActor
private static func sleepCase(_ message: String, shouldSleep: Bool = false, reply: String? = idleReply,
mutate: (BrowserManager, TabRuntime) -> Void) async {
let store = SidebarStore()
let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ manager.protectedRecentTabs = 0 // one page alone; the 10 most recent are kept (recentTabsCase)
let id = store.createTab(url: "https://example.test/sleep").id
let runtime = manager.ensureRuntime(for: id)!
runtime.hiddenAt = Date.distantPast
@@ -214,11 +238,51 @@ enum BrowserManagerLifecycleTests {
manager.closeAll()
}
+ /// Like Arc, the 10 tabs used last keep their pages however long they have been hidden (#136).
+ @MainActor
+ private static func recentTabsCase() {
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ let ids = (0..<13).map { store.createTab(url: "https://example.test/recent\($0)").id }
+ 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)
+ 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")
+ manager.closeAll()
+ }
+
+ /// Like Arc, a page out of sight past the threshold is voted to freeze unless it is one of
+ /// the 10 tabs used last; showing it drops the vote (#136).
+ @MainActor
+ private static func freezingVoteCase() {
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ let ids = (0..<12).map { store.createTab(url: "https://example.test/freeze\($0)").id }
+ let runtimes = ids.map { manager.ensureRuntime(for: $0)! }
+ manager.show(ids[11], focus: false)
+ for (n, rt) in runtimes.dropLast().enumerated() { rt.hiddenAt = Date(timeIntervalSince1970: Double(n)) }
+ let votes = { runtimes.map { rt in rt.browser.replies.filter { $0.method == "Cra.setFreezingVote" }.count } }
+ manager.freezeIdleTabs(hiddenLongerThan: 60)
+ expect(votes() == [1, 1] + Array(repeating: 0, count: 10) && runtimes[0].freezeVoted && !runtimes[2].freezeVoted,
+ "only pages beyond the 10 tabs used last are voted to freeze")
+ expect(runtimes[0].browser.lastParams.contains("true") || runtimes[1].browser.lastParams.contains("true"), "the vote says true")
+ manager.freezeIdleTabs(hiddenLongerThan: 60)
+ expect(votes() == [1, 1] + Array(repeating: 0, count: 10), "a vote already cast is not sent again")
+ manager.show(ids[0], focus: false)
+ expect(!runtimes[0].freezeVoted && votes()[0] == 2 && runtimes[0].browser.lastParams.contains("false"),
+ "showing a frozen tab drops its vote")
+ manager.closeAll()
+ }
+
/// A page that refused isn't probed again every minute, only after the back-off or once shown again.
@MainActor
private static func refusalBackoffCase() async {
let store = SidebarStore()
let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ manager.protectedRecentTabs = 0 // one page alone; the 10 most recent are kept (recentTabsCase)
let id = store.createTab(url: "https://example.test/typed").id
let runtime = manager.ensureRuntime(for: id)!
runtime.hiddenAt = Date.distantPast
@@ -240,6 +304,7 @@ enum BrowserManagerLifecycleTests {
let clock = ManualScheduler()
let store = SidebarStore()
let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView(), clock: clock)
+ manager.protectedRecentTabs = 0 // one page alone; the 10 most recent are kept (recentTabsCase)
let id = store.createTab(url: "https://example.test/clock").id
let runtime = manager.ensureRuntime(for: id)!
func probed() -> Bool { runtime.browser.replies.contains { $0.method == isolatedProbe } }
@@ -296,6 +361,7 @@ enum BrowserManagerLifecycleTests {
private static func beforeUnloadCase() async {
let store = SidebarStore()
let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ manager.protectedRecentTabs = 0 // one page alone; the 10 most recent are kept (recentTabsCase)
let id = store.createTab(url: "https://example.test/editor").id
let runtime = manager.ensureRuntime(for: id)!
runtime.hiddenAt = Date.distantPast
diff --git a/Tests/BrowserManagerSupport/AppServices.swift b/Tests/BrowserManagerSupport/AppServices.swift
index 61e08fb..a565e18 100644
--- a/Tests/BrowserManagerSupport/AppServices.swift
+++ b/Tests/BrowserManagerSupport/AppServices.swift
@@ -46,6 +46,7 @@ enum TestRoot { case today }
static let shared = ExtensionStore()
var entries: [Entry] = []
func entries(inProfile name: String) -> [Entry] { entries }
+ func proxyLine(inProfile name: String) -> String { "not set by an extension" }
}
enum FaviconKey { static func key(for url: String) -> String? { url } }
enum BrowsingDataClear {
diff --git a/Tests/FloatingSidebarTests.swift b/Tests/FloatingSidebarTests.swift
index 5566efb..7b75e64 100644
--- a/Tests/FloatingSidebarTests.swift
+++ b/Tests/FloatingSidebarTests.swift
@@ -105,6 +105,14 @@ enum FloatingSidebarTests {
window.removeChildWindow(page)
page.close()
front.close()
+
+ // #136: the pointer is sampled only while Cra is the active app.
+ sidebar.install()
+ expect(!sidebar.isPolling, "an inactive app installs no pointer timer")
+ NotificationCenter.default.post(name: NSApplication.didBecomeActiveNotification, object: NSApp)
+ expect(sidebar.isPolling, "becoming active starts the pointer timer")
+ NotificationCenter.default.post(name: NSApplication.didResignActiveNotification, object: NSApp)
+ expect(!sidebar.isPolling, "leaving the app stops it")
window.close()
print("Floating sidebar: \(checks) checks passed")
}
diff --git a/Tests/StoreTests.swift b/Tests/StoreTests.swift
index 08198f3..8ef7042 100644
--- a/Tests/StoreTests.swift
+++ b/Tests/StoreTests.swift
@@ -221,12 +221,11 @@ enum StoreTests {
expect(!archived(later.id), "with auto-archive off nothing is archived")
}
- /// Tab sleeping asks the windows once a minute, and only while it is turned on.
+ /// Tab sleeping asks the windows once a minute; like Arc, it has no switch.
@MainActor
private static func tabSleepCadence() {
let clock = ManualScheduler()
let composition = AppComposition(clock: clock)
- composition.store.settings.tabSleepEnabled = true
var passes = 0
composition.startPeriodicWork { passes += 1 }
clock.advance(by: 59)
@@ -235,9 +234,6 @@ enum StoreTests {
expect(passes == 1, "a pass every minute")
clock.advance(by: 9 * 60)
expect(passes == 10, "ten passes in ten minutes")
- composition.store.settings.tabSleepEnabled = false
- clock.advance(by: 10 * 60)
- expect(passes == 10, "no passes while tab sleeping is off")
composition.startPeriodicWork { passes += 100 }
expect(clock.pendingCount == 2, "starting again replaces the timers instead of adding to them")
}
diff --git a/docs/development.md b/docs/development.md
index e534415..faa0786 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -42,10 +42,11 @@ Data lives in `~/Library/Application Support/Cra`: the sidebar and archive as JS
`keybindings.json`, cached favicons, the logs and a Chromium profile folder. Delete it to
start over.
-`cra.log` is Cra's own log: each tab's page opening, showing, loading and closing, and three
-seconds after a tab comes on screen, what its page holds (`blank`, `visibility`, element and
-text counts, `painted` for a first contentful paint, `frameRate` for the animation frames
-it got in half a second) and where Cra put it (view size, `window=covered` when another
+`cra.log` is Cra's own log: each tab's page opening, showing, loading, failing to load (with
+the net error and the extension that set the proxy) and closing, and three seconds after a tab
+comes on screen and its page has loaded, what the page holds (`blank`, `visibility`, element
+and body child counts, `painted` for a first contentful paint, `frameRate` for the animation
+frames it got in half a second, `video` for the first video's dropped/total frames) and where Cra put it (view size, `window=covered` when another
window hides it, `display=` the refresh rate of the display it is on). A visible page with
`frameRate=0` was never asked to draw; frames without `painted` never reached the screen. `chromium.log` holds Chromium's warnings,
failed page loads and crashed renderers. Each launch keeps the last one's as `*.previous.log`.
diff --git a/docs/performance.md b/docs/performance.md
index 3bd9b8c..c4fef47 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -72,11 +72,13 @@ Chromium's `--type=` argument): CPU, memory footprint, disk reads and writes, wa
file only), and processes started and ended. The Mac: CPU, memory pressure, thermal state, Low
Power Mode, free disk, and Cra's average CPU while nobody used the Mac (`idle`: 5-second samples
with no keyboard or mouse input for a minute). Tabs by state, sleep refusals by reason, and
-timings for tab switch, page create, page load and waking a slept tab. In the visible page,
+timings for tab switch (without the page created for a tab that had none, which is page
+create), page create, page load, waking a slept tab and framing an extension's popup. In the visible page,
read with the long tasks every 5 s and never in background tabs: long tasks, Chromium's long
animation frames (`longFrames`, `longestFrameMs`: a passive observer, it asks for no frames) and
the frames its videos played and dropped (`getVideoPlaybackQuality`). Renderer crashes, hangs
-and failed loads with their codes. Start-up phases, JSON load and save times (saves run on the
+and failed loads with their codes. Start-up phases (store loaded, Chromium started, windows shown, then the first page shown,
+committed and loaded), JSON load and save times (saves run on the
persistence queue, so `jsonSave` is never a main-thread stall), the profile's and caches' size
(at export only). The session: a random id, the launch number, the previous session and whether
it quit. The totals in `tabs` are since launch; `history.json`, in the export too, has stalls
@@ -165,7 +167,8 @@ real export. On `fifty-tabs` the 13.5 ms were: observer 6.7, process sample 5.1
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`
+ `Services/HitchMonitor.swift`, `Services/Diagnostics.swift`, `Services/ExtensionActions.swift`
+ (the popup's `Perf.time`), `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` and `lf` observers in `PageScript.isolatedWorld`, the `load-start`/`load-end` and
diff --git a/scripts/cef-patches/freezing-vote.patch b/scripts/cef-patches/freezing-vote.patch
new file mode 100644
index 0000000..14a2aae
--- /dev/null
+++ b/scripts/cef-patches/freezing-vote.patch
@@ -0,0 +1,162 @@
+diff --git a/cef/BUILD.gn b/cef/BUILD.gn
+index dd0a558c0..a54f79de4 100644
+--- a/cef/BUILD.gn
++++ b/cef/BUILD.gn
+@@ -973,6 +973,7 @@ source_set("libcef_static") {
+ "//components/network_session_configurator/common",
+ "//components/pdf/browser",
+ "//components/pdf/renderer",
++ "//components/performance_manager",
+ "//components/plugins/renderer",
+ "//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
+--- a/cef/libcef/browser/devtools/devtools_controller.cc
++++ b/cef/libcef/browser/devtools/devtools_controller.cc
+@@ -6,9 +6,108 @@
+
+ #include "base/json/json_reader.h"
+ #include "base/json/json_writer.h"
++#include "base/supports_user_data.h"
++#include "base/task/sequenced_task_runner.h"
+ #include "cef/libcef/browser/devtools/devtools_util.h"
+ #include "cef/libcef/browser/thread_util.h"
++#include "components/performance_manager/freezing/freezing_policy.h"
++#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/web_contents.h"
++
++namespace {
++
++// Cra: a page's freezing vote, held while the client asks for it, like Arc's
++// freeze token. Chromium's freezing policy freezes the page only while no
++// CannotFreezeReason applies (audible, capturing, Web Locks, WebRTC,
++// notification permission, ...).
++const char kCraFreezingVoteKey[] = "cra-freezing-vote";
++
++struct CraFreezingVote : public base::SupportsUserData::Data {
++ explicit CraFreezingVote(content::WebContents* contents) : vote(contents) {}
++ performance_manager::freezing::FreezingVote vote;
++};
++
++base::ListValue ReasonList(
++ const performance_manager::freezing::CannotFreezeReasonSet& reasons) {
++ base::ListValue list;
++ for (auto reason : reasons) {
++ list.Append(
++ performance_manager::freezing::CannotFreezeReasonToString(reason));
++ }
++ return list;
++}
++
++// {"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.
++bool HandleCraMethod(content::WebContents* contents,
++ std::string_view message,
++ int* message_id,
++ base::DictValue* result,
++ std::string* error) {
++ if (message.find("\"Cra.") == std::string_view::npos) {
++ return false;
++ }
++ std::optional<base::DictValue> dict =
++ base::JSONReader::ReadDict(message, base::JSON_PARSE_RFC);
++ if (!dict) {
++ return false;
++ }
++ const std::string* method = dict->FindString("method");
++ std::optional<int> id = dict->FindInt("id");
++ if (!method || !id ||
++ (*method != "Cra.setFreezingVote" && *method != "Cra.getFreezingState")) {
++ return false;
++ }
++ *message_id = *id;
++ if (*method == "Cra.getFreezingState") {
++ result->Set("vote", !!contents->GetUserData(kCraFreezingVoteKey));
++ const performance_manager::PageNode* page =
++ performance_manager::PerformanceManager::
++ GetPrimaryPageNodeForWebContents(contents)
++ .get();
++ if (page && performance_manager::PerformanceManager::GetGraph()
++ ->GetRegisteredObjectAs<
++ performance_manager::FreezingPolicy>()) {
++ result->Set("frozen", page->GetLifecycleState() ==
++ performance_manager::mojom::LifecycleState::kFrozen);
++ auto details =
++ performance_manager::freezing::GetCanFreezeDetailsForPageNode(page);
++ result->Set("reasons", ReasonList(details.cannot_freeze_reasons));
++ result->Set("connectedReasons",
++ ReasonList(details.cannot_freeze_reasons_connected_pages));
++ }
++ return true;
++ }
++ const base::DictValue* params = dict->FindDict("params");
++ const bool vote = params && params->FindBool("vote").value_or(false);
++ if (!vote) {
++ contents->RemoveUserData(kCraFreezingVoteKey);
++ return true;
++ }
++ if (contents->GetUserData(kCraFreezingVoteKey)) {
++ return true;
++ }
++ // FreezingVote CHECKs both: a page Chrome's tab helpers never saw has no
++ // page node.
++ auto* graph = performance_manager::PerformanceManager::GetGraph();
++ if (!performance_manager::PerformanceManager::
++ GetPrimaryPageNodeForWebContents(contents) ||
++ !graph ||
++ !graph->GetRegisteredObjectAs<
++ performance_manager::FreezingPolicy>()) {
++ *error = "freezing is not available for this page";
++ return true;
++ }
++ contents->SetUserData(kCraFreezingVoteKey,
++ std::make_unique<CraFreezingVote>(contents));
++ return true;
++}
++
++} // namespace
+
+ CefDevToolsController::CefDevToolsController(
+ content::WebContents* inspected_contents)
+@@ -30,6 +129,36 @@ CefDevToolsController::~CefDevToolsController() {
+ bool CefDevToolsController::SendDevToolsMessage(
+ const std::string_view& message) {
+ CEF_REQUIRE_UIT();
++ int cra_message_id = 0;
++ base::DictValue cra_result;
++ std::string cra_error;
++ if (HandleCraMethod(inspected_contents_, message, &cra_message_id,
++ &cra_result, &cra_error)) {
++ // Answered like a protocol method, after the caller has returned.
++ base::DictValue reply;
++ reply.Set("id", cra_message_id);
++ if (cra_error.empty()) {
++ reply.Set("result", std::move(cra_result));
++ } else {
++ base::DictValue error;
++ error.Set("code", -32000);
++ error.Set("message", cra_error);
++ reply.Set("error", std::move(error));
++ }
++ std::string json;
++ base::JSONWriter::Write(reply, &json);
++ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
++ FROM_HERE,
++ base::BindOnce(
++ [](base::WeakPtr<CefDevToolsController> self, std::string json) {
++ if (self) {
++ self->DispatchProtocolMessage(
++ nullptr, base::as_bytes(base::span(json)));
++ }
++ },
++ weak_ptr_factory_.GetWeakPtr(), std::move(json)));
++ return true;
++ }
+ if (!EnsureAgentHost()) {
+ return false;
+ }
diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.sh
index 5b94913..b5a8a7e 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%%+*}-codecs9}"
+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs10}"
URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"
mkdir -p vendor
diff --git a/scripts/lint.py b/scripts/lint.py
index 20d6ed7..a504281 100755
--- a/scripts/lint.py
+++ b/scripts/lint.py
@@ -51,7 +51,8 @@ CORE_IMPORT = re.compile(r"^\s*(?:@\w+\s+)*import\s+(?:(?:struct|class|enum|prot
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"}
+ "Services/HitchMonitor.swift", "Services/Diagnostics.swift", "Services/ExtensionActions.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",