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.

An extension page restored at launch loads once its extension is up, instead of Chromium's error page (#127)

Victor Kildahl1fc95a019865
diff --git a/Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift b/Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift
new file mode 100644
index 0000000..8d2f0b2
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift
@@ -0,0 +1,30 @@
+import Foundation
+
+/// A tab restored at launch can ask for an extension's page (its options page, say) before
+/// Chromium has loaded the extension: `--load-extension` loads the `Extensions` folder after the
+/// restored tabs start loading (the same race ForceWebRequestProxyForTest covers for webRequest).
+/// Chromium then blocks the page with ERR_BLOCKED_BY_CLIENT and shows its error page until a
+/// reload. Arc and Chrome install their extensions before restoring tabs, so the page just loads.
+/// Cra loads it again a few times while the extension comes up. An extension that is off or gone
+/// in the tab's profile is not retried: its error page is the answer.
+public enum ExtensionPageRetry {
+ /// net::ERR_BLOCKED_BY_CLIENT.
+ public static let blockedByClient = -20
+ /// 0.25, 0.5, 1, 2, 4, 4 s: about 12 s in all.
+ public static let attempts = 6
+
+ /// The extension ID of a `chrome-extension://<id>/…` address.
+ public static func extensionID(of url: String) -> String? {
+ guard let u = URLComponents(string: url), u.scheme == "chrome-extension", let id = u.host, !id.isEmpty else { return nil }
+ return id
+ }
+
+ /// How long to wait before loading `url` again after it failed with `errorCode` for the
+ /// `attempt`-th time (0 first), or nil to leave the error. `isOn` says whether the
+ /// extension is installed and turned on in the tab's profile.
+ public static func delay(url: String, errorCode: Int, attempt: Int, isOn: (String) -> Bool) -> TimeInterval? {
+ guard errorCode == blockedByClient, attempt >= 0, attempt < attempts,
+ let id = extensionID(of: url), isOn(id) else { return nil }
+ return min(0.25 * pow(2, Double(attempt)), 4)
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/ExtensionPageRetryTests.swift b/Packages/CraCore/Tests/CraCoreTests/ExtensionPageRetryTests.swift
new file mode 100644
index 0000000..c47c22d
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/ExtensionPageRetryTests.swift
@@ -0,0 +1,38 @@
+import CraCore
+import Foundation
+import Testing
+
+/// A restored extension page that Chromium blocked because the extension wasn't loaded yet.
+struct ExtensionPageRetryTests {
+ let options = "chrome-extension://abcdefghijklmnopabcdefghijklmnop/options.html#general"
+ let on: (String) -> Bool = { _ in true }
+
+ @Test func retriesWithGrowingWaits() {
+ let waits = (0..<ExtensionPageRetry.attempts).map { ExtensionPageRetry.delay(url: options, errorCode: -20, attempt: $0, isOn: on) }
+ #expect(waits == [0.25, 0.5, 1, 2, 4, 4])
+ #expect(ExtensionPageRetry.delay(url: options, errorCode: -20, attempt: ExtensionPageRetry.attempts, isOn: on) == nil)
+ }
+
+ /// Off or removed in the tab's profile: Chromium's error page stays.
+ @Test func extensionThatIsOffIsNotRetried() {
+ var asked: [String] = []
+ let off: (String) -> Bool = { asked.append($0); return false }
+ #expect(ExtensionPageRetry.delay(url: options, errorCode: -20, attempt: 0, isOn: off) == nil)
+ #expect(asked == ["abcdefghijklmnopabcdefghijklmnop"])
+ }
+
+ @Test(arguments: [
+ ("https://example.com/", -20), // an ad blocker blocked a site
+ ("chrome-extension://abcdefghijklmnopabcdefghijklmnop/options.html", -105), // another error
+ ("chrome-extension:///options.html", -20),
+ ("chrome://extensions", -20),
+ ])
+ func otherFailuresAreLeft(url: String, code: Int) {
+ #expect(ExtensionPageRetry.delay(url: url, errorCode: code, attempt: 0, isOn: on) == nil)
+ }
+
+ @Test func extensionIDs() {
+ #expect(ExtensionPageRetry.extensionID(of: options) == "abcdefghijklmnopabcdefghijklmnop")
+ #expect(ExtensionPageRetry.extensionID(of: "https://example.com/") == nil)
+ }
+}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index 418a3f8..a8bfa72 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -28,6 +28,11 @@ final class TabRuntime {
var sleepRefusal: String?
/// Whether this page's DevTools are open, closing or asked for (DevToolsToggle).
var devTools = DevToolsToggle()
+ /// Loads of an extension's page Chromium blocked because the extension wasn't up yet
+ /// (ExtensionPageRetry); back to 0 once a page loads.
+ var extensionPageRetries = 0
+ /// The next of those loads (LiveScheduler runs work only while its handle is kept).
+ var extensionPageRetry: ScheduledWork?
/// Chrome-style hosting: the page's own window (nil until created, or for Alloy).
var hostWindow: NSWindow? { browser.hostWindow }
init(tabID: UUID, browser: CraBrowser) {
@@ -769,11 +774,29 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
func browser(_ browser: CraBrowser, didFinishLoadingURL url: String, title: String, statusCode: Int) {
guard let id = tabID(of: browser) else { return }
log(id, "loaded \(site(url, id, browser)) (HTTP \(statusCode))")
+ if statusCode != 0 { runtimes[id]?.extensionPageRetries = 0 }
guard !browser.isIncognito else { return }
if url.hasPrefix("chrome://settings") { watchClearBrowsingData(browser) }
store.recordVisit(url: url, title: title.isEmpty ? (store.item(id)?.tab?.savedTitle ?? "") : title)
}
+ /// 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 }
+ let profile = store.profileDirectoryName(item: id)
+ 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 }
+ rt.extensionPageRetries += 1
+ log(id, "loads \(site(url, id, browser)) again in \(wait) s: the extension wasn't loaded yet")
+ rt.extensionPageRetry = clock.after(wait) { [weak self, weak browser] in
+ // Still this tab's page, and nobody has gone elsewhere meanwhile.
+ guard let self, let browser, self.runtimes[id]?.browser === browser, browser.currentURL == url else { return }
+ browser.loadURL(url)
+ }
+ }
+
func browser(_ browser: CraBrowser, didLoadFavicon image: NSImage, forURL iconURL: String) {
guard let id = tabID(of: browser), let tab = store.item(id)?.tab else { return }
let key = FaviconKey.key(for: tab.url) ?? tab.faviconKey
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index f36fbad..7b87dbf 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -1226,6 +1226,9 @@ public:
<< (int)errorCode << ")";
if ((int)errorCode == -3 /* ERR_ABORTED */) return;
ReportProcessEvent(browser, @"loadError", [NSString stringWithFormat:@"%d", (int)errorCode], failedUrl);
+ CraBrowser* o = owner_;
+ if (o && [o.delegate respondsToSelector:@selector(browser:didFailLoadingURL:errorCode:)])
+ [o.delegate browser:o didFailLoadingURL:NSStringFromCef(failedUrl) errorCode:(NSInteger)errorCode];
// Chrome-style pages get Chrome's own error page: Reload retries the site and it
// reloads by itself when the network returns. Ours, a data: URL loaded on top,
// made Reload reload the error and added a history entry.
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index 9696b8d..15ddf1b 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -96,6 +96,9 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
- (void)browser:(CraBrowser *)browser didChangeMediaCapture:(BOOL)capturing;
/// The page started or stopped playing sound (see `isAudible`).
- (void)browser:(CraBrowser *)browser didChangeAudible:(BOOL)audible;
+/// The page's main-frame load failed with a net error (ERR_ABORTED, a navigation cut off,
+/// is left out): `url` is the address that failed.
+- (void)browser:(CraBrowser *)browser didFailLoadingURL:(NSString *)url errorCode:(NSInteger)errorCode;
/// An extension asked to bring this page's tab to the front (chrome.tabs.update with
/// active: true; scripts/cef-patches/extension-tab-activate.patch).
- (void)browserRequestsActivation:(CraBrowser *)browser;
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index da14066..e7fa223 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -88,6 +88,7 @@ enum BrowserManagerLifecycleTests {
await leaveVideoTabPictureInPictureCase()
await coveredWindowPictureInPictureCase()
pageColoursCase()
+ extensionPageRetryCase()
await sleepCase("malformed or missing replies cannot authorize sleeping", reply: nil) { _, _ in }
await pageProbeCase()
print("Browser manager lifecycle: \(checks) checks passed")
@@ -450,6 +451,47 @@ enum BrowserManagerLifecycleTests {
manager.closeAll()
}
+ /// A restored tab asked for an extension's page before --load-extension loaded it: Chromium
+ /// blocked it (ERR_BLOCKED_BY_CLIENT), and the page is loaded again while the extension comes up.
+ @MainActor
+ private static func extensionPageRetryCase() {
+ let clock = ManualScheduler()
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView(), clock: clock)
+ let ext = "abcdefghijklmnopabcdefghijklmnop", url = "chrome-extension://\(ext)/options.html"
+ ExtensionStore.shared.entries = [.init(extensionID: ext)]
+ let rt = manager.ensureRuntime(for: store.createTab(url: url).id)!
+ manager.browser(rt.browser, didFailLoadingURL: url, errorCode: -20)
+ clock.advance(by: 0.2)
+ expect(rt.browser.loads.isEmpty, "the page is not loaded again before the first wait ends")
+ clock.advance(by: 0.1)
+ expect(rt.browser.loads == [url], "the blocked page is loaded again once")
+ for _ in 1..<ExtensionPageRetry.attempts {
+ manager.browser(rt.browser, didFailLoadingURL: url, errorCode: -20)
+ clock.advance(by: 4)
+ }
+ expect(rt.browser.loads.count == ExtensionPageRetry.attempts, "every attempt loads it again")
+ manager.browser(rt.browser, didFailLoadingURL: url, errorCode: -20)
+ clock.advance(by: 60)
+ expect(rt.browser.loads.count == ExtensionPageRetry.attempts, "after the last attempt the error page stays")
+ manager.browser(rt.browser, didFinishLoadingURL: url, title: "Options", statusCode: 200)
+ manager.browser(rt.browser, didFailLoadingURL: url, errorCode: -20)
+ clock.advance(by: 0.25)
+ expect(rt.browser.loads.count == ExtensionPageRetry.attempts + 1, "a page that loaded starts counting again")
+
+ let other = manager.ensureRuntime(for: store.createTab(url: url).id)!
+ manager.browser(other.browser, didFailLoadingURL: url, errorCode: -20)
+ other.browser.navigate(to: "https://example.test/")
+ clock.advance(by: 1)
+ expect(other.browser.loads.isEmpty, "a tab that went elsewhere meanwhile stays there")
+ ExtensionStore.shared.entries = []
+ other.browser.navigate(to: url)
+ manager.browser(other.browser, didFailLoadingURL: url, errorCode: -20)
+ clock.advance(by: 60)
+ expect(other.browser.loads.isEmpty, "an extension that is off in the tab's profile is not retried")
+ manager.closeAll()
+ }
+
@MainActor
private static func drainMainQueue() async {
await withCheckedContinuation { continuation in DispatchQueue.main.async { continuation.resume() } }
diff --git a/Tests/BrowserManagerSupport/AppServices.swift b/Tests/BrowserManagerSupport/AppServices.swift
index f84afa0..61e08fb 100644
--- a/Tests/BrowserManagerSupport/AppServices.swift
+++ b/Tests/BrowserManagerSupport/AppServices.swift
@@ -20,6 +20,7 @@ enum TestRoot { case today }
func item(_ id: UUID) -> TestItem? { items[id] }
func isIncognito(item: UUID) -> Bool { false }
func profilePath(item: UUID) -> String? { nil }
+ func profileDirectoryName(item: UUID) -> String { "Default" }
func spaceID(ofItem: UUID) -> UUID? { nil }
func rootContainer(of: UUID) -> TestRoot? { nil }
func updateTab(_ id: UUID, url: String? = nil, title: String? = nil) {
@@ -39,6 +40,13 @@ enum TestRoot { case today }
return item
}
}
+/// The extensions turned on in the Default profile.
+@MainActor final class ExtensionStore {
+ struct Entry { let extensionID: String }
+ static let shared = ExtensionStore()
+ var entries: [Entry] = []
+ func entries(inProfile name: String) -> [Entry] { entries }
+}
enum FaviconKey { static func key(for url: String) -> String? { url } }
enum BrowsingDataClear {
enum Range { case allTime }
diff --git a/Tests/BrowserManagerSupport/CraCEF.swift b/Tests/BrowserManagerSupport/CraCEF.swift
index 1a9f918..0ec6b16 100644
--- a/Tests/BrowserManagerSupport/CraCEF.swift
+++ b/Tests/BrowserManagerSupport/CraCEF.swift
@@ -80,6 +80,9 @@ public final class CraBrowser {
isLoading = loading
delegate?.browser(self, didChangeLoading: loading, canGoBack: false, canGoForward: false)
}
+ /// Addresses Cra asked to load, in order.
+ public private(set) var loads: [String] = []
+ public func loadURL(_ url: String) { loads.append(url) }
public func navigate(to url: String) {
currentURL = url
delegate?.browser(self, didChangeURL: url)
diff --git a/Tests/test-browser-manager.sh b/Tests/test-browser-manager.sh
index 7a2a3d4..a3a9967 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 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 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/"